]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Add support for 'u' and 'y' RegExp flags in ES6 mode.
[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: 20140114
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 (defvar js2-harmony-externs
207 (mapcar 'symbol-name
208 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
209 "ES6 externs. If `js2-include-browser-externs' is enabled and
210 `js2-language-version' is sufficiently high, these will be included.")
211
212 ;;; Variables
213
214 (defun js2-mark-safe-local (name pred)
215 "Make the variable NAME buffer-local and mark it as safe file-local
216 variable with predicate PRED."
217 (make-variable-buffer-local name)
218 (put name 'safe-local-variable pred))
219
220 (defcustom js2-highlight-level 2
221 "Amount of syntax highlighting to perform.
222 0 or a negative value means none.
223 1 adds basic syntax highlighting.
224 2 adds highlighting of some Ecma built-in properties.
225 3 adds highlighting of many Ecma built-in functions."
226 :group 'js2-mode
227 :type '(choice (const :tag "None" 0)
228 (const :tag "Basic" 1)
229 (const :tag "Include Properties" 2)
230 (const :tag "Include Functions" 3)))
231
232 (defvar js2-mode-dev-mode-p nil
233 "Non-nil if running in development mode. Normally nil.")
234
235 (defgroup js2-mode nil
236 "An improved JavaScript mode."
237 :group 'languages)
238
239 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
240 (numberp c-basic-offset))
241 c-basic-offset
242 4)
243 "Number of spaces to indent nested statements.
244 Similar to `c-basic-offset'."
245 :group 'js2-mode
246 :type 'integer)
247 (js2-mark-safe-local 'js2-basic-offset 'integerp)
248
249 (defcustom js2-bounce-indent-p nil
250 "Non-nil to have indent-line function choose among alternatives.
251 If nil, the indent-line function will indent to a predetermined column
252 based on heuristic guessing. If non-nil, then if the current line is
253 already indented to that predetermined column, indenting will choose
254 another likely column and indent to that spot. Repeated invocation of
255 the indent-line function will cycle among the computed alternatives.
256 See the function `js2-bounce-indent' for details. When it is non-nil,
257 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
258 :type 'boolean
259 :group 'js2-mode)
260
261 (defcustom js2-pretty-multiline-declarations t
262 "Non-nil to line up multiline declarations vertically:
263
264 var a = 10,
265 b = 20,
266 c = 30;
267
268 If the value is not `all', and the first assigned value in
269 declaration is a function/array/object literal spanning several
270 lines, it won't be indented additionally:
271
272 var o = { var bar = 2,
273 foo: 3 vs. o = {
274 }, foo: 3
275 bar = 2; };"
276 :group 'js2-mode
277 :type 'symbol)
278 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
279
280 (defcustom js2-indent-switch-body nil
281 "When nil, case labels are indented on the same level as the
282 containing switch statement. Otherwise, all lines inside
283 switch statement body are indented one additional level."
284 :type 'boolean
285 :group 'js2-mode)
286 (js2-mark-safe-local 'js2-indent-case-same-as-switch 'booleanp)
287
288 (defcustom js2-idle-timer-delay 0.2
289 "Delay in secs before re-parsing after user makes changes.
290 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
291 :type 'number
292 :group 'js2-mode)
293 (make-variable-buffer-local 'js2-idle-timer-delay)
294
295 (defcustom js2-dynamic-idle-timer-adjust 0
296 "Positive to adjust `js2-idle-timer-delay' based on file size.
297 The idea is that for short files, parsing is faster so we can be
298 more responsive to user edits without interfering with editing.
299 The buffer length in characters (typically bytes) is divided by
300 this value and used to multiply `js2-idle-timer-delay' for the
301 buffer. For example, a 21k file and 10k adjust yields 21k/10k
302 == 2, so js2-idle-timer-delay is multiplied by 2.
303 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
304 `js2-idle-timer-delay' is not dependent on the file size."
305 :type 'number
306 :group 'js2-mode)
307
308 (defcustom js2-concat-multiline-strings t
309 "When non-nil, `js2-line-break' in mid-string will make it a
310 string concatenation. When `eol', the '+' will be inserted at the
311 end of the line, otherwise, at the beginning of the next line."
312 :type '(choice (const t) (const eol) (const nil))
313 :group 'js2-mode)
314
315 (defcustom js2-mode-show-parse-errors t
316 "True to highlight parse errors."
317 :type 'boolean
318 :group 'js2-mode)
319
320 (defcustom js2-mode-show-strict-warnings t
321 "Non-nil to emit Ecma strict-mode warnings.
322 Some of the warnings can be individually disabled by other flags,
323 even if this flag is non-nil."
324 :type 'boolean
325 :group 'js2-mode)
326
327 (defcustom js2-strict-trailing-comma-warning t
328 "Non-nil to warn about trailing commas in array literals.
329 Ecma-262-5.1 allows them, but older versions of IE raise an error."
330 :type 'boolean
331 :group 'js2-mode)
332
333 (defcustom js2-strict-missing-semi-warning t
334 "Non-nil to warn about semicolon auto-insertion after statement.
335 Technically this is legal per Ecma-262, but some style guides disallow
336 depending on it."
337 :type 'boolean
338 :group 'js2-mode)
339
340 (defcustom js2-missing-semi-one-line-override nil
341 "Non-nil to permit missing semicolons in one-line functions.
342 In one-liner functions such as `function identity(x) {return x}'
343 people often omit the semicolon for a cleaner look. If you are
344 such a person, you can suppress the missing-semicolon warning
345 by setting this variable to t."
346 :type 'boolean
347 :group 'js2-mode)
348
349 (defcustom js2-strict-inconsistent-return-warning t
350 "Non-nil to warn about mixing returns with value-returns.
351 It's perfectly legal to have a `return' and a `return foo' in the
352 same function, but it's often an indicator of a bug, and it also
353 interferes with type inference (in systems that support it.)"
354 :type 'boolean
355 :group 'js2-mode)
356
357 (defcustom js2-strict-cond-assign-warning t
358 "Non-nil to warn about expressions like if (a = b).
359 This often should have been '==' instead of '='. If the warning
360 is enabled, you can suppress it on a per-expression basis by
361 parenthesizing the expression, e.g. if ((a = b)) ..."
362 :type 'boolean
363 :group 'js2-mode)
364
365 (defcustom js2-strict-var-redeclaration-warning t
366 "Non-nil to warn about redeclaring variables in a script or function."
367 :type 'boolean
368 :group 'js2-mode)
369
370 (defcustom js2-strict-var-hides-function-arg-warning t
371 "Non-nil to warn about a var decl hiding a function argument."
372 :type 'boolean
373 :group 'js2-mode)
374
375 (defcustom js2-skip-preprocessor-directives nil
376 "Non-nil to treat lines beginning with # as comments.
377 Useful for viewing Mozilla JavaScript source code."
378 :type 'boolean
379 :group 'js2-mode)
380
381 (defcustom js2-language-version 200
382 "Configures what JavaScript language version to recognize.
383 Currently versions 150, 160, 170, 180 and 200 are supported,
384 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
385 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
386 yield, and Array comprehensions, and 1.8 adds function closures."
387 :type 'integer
388 :group 'js2-mode)
389
390 (defcustom js2-allow-keywords-as-property-names t
391 "If non-nil, you can use JavaScript keywords as object property names.
392 Examples:
393
394 var foo = {int: 5, while: 6, continue: 7};
395 foo.return = 8;
396
397 Ecma-262 5.1 allows this syntax, but some engines still don't."
398 :type 'boolean
399 :group 'js2-mode)
400
401 (defcustom js2-instanceof-has-side-effects nil
402 "If non-nil, treats the instanceof operator as having side effects.
403 This is useful for xulrunner apps."
404 :type 'boolean
405 :group 'js2-mode)
406
407 (defcustom js2-move-point-on-right-click t
408 "Non-nil to move insertion point when you right-click.
409 This makes right-click context menu behavior a bit more intuitive,
410 since menu operations generally apply to the point. The exception
411 is if there is a region selection, in which case the point does -not-
412 move, so cut/copy/paste can work properly.
413
414 Note that IntelliJ moves the point, and Eclipse leaves it alone,
415 so this behavior is customizable."
416 :group 'js2-mode
417 :type 'boolean)
418
419 (defcustom js2-allow-rhino-new-expr-initializer t
420 "Non-nil to support a Rhino's experimental syntactic construct.
421
422 Rhino supports the ability to follow a `new' expression with an object
423 literal, which is used to set additional properties on the new object
424 after calling its constructor. Syntax:
425
426 new <expr> [ ( arglist ) ] [initializer]
427
428 Hence, this expression:
429
430 new Object {a: 1, b: 2}
431
432 results in an Object with properties a=1 and b=2. This syntax is
433 apparently not configurable in Rhino - it's currently always enabled,
434 as of Rhino version 1.7R2."
435 :type 'boolean
436 :group 'js2-mode)
437
438 (defcustom js2-allow-member-expr-as-function-name nil
439 "Non-nil to support experimental Rhino syntax for function names.
440
441 Rhino supports an experimental syntax configured via the Rhino Context
442 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
443
444 function <member-expr> ( [ arg-list ] ) { <body> }
445
446 Where member-expr is a non-parenthesized 'member expression', which
447 is anything at the grammar level of a new-expression or lower, meaning
448 any expression that does not involve infix or unary operators.
449
450 When <member-expr> is not a simple identifier, then it is syntactic
451 sugar for assigning the anonymous function to the <member-expr>. Hence,
452 this code:
453
454 function a.b().c[2] (x, y) { ... }
455
456 is rewritten as:
457
458 a.b().c[2] = function(x, y) {...}
459
460 which doesn't seem particularly useful, but Rhino permits it."
461 :type 'boolean
462 :group 'js2-mode)
463
464 ;; scanner variables
465
466 (defmacro js2-deflocal (name value &optional comment)
467 "Define a buffer-local variable NAME with VALUE and COMMENT."
468 `(progn
469 (defvar ,name ,value ,comment)
470 (make-variable-buffer-local ',name)))
471
472 (defvar js2-EOF_CHAR -1
473 "Represents end of stream. Distinct from js2-EOF token type.")
474
475 ;; I originally used symbols to represent tokens, but Rhino uses
476 ;; ints and then sets various flag bits in them, so ints it is.
477 ;; The upshot is that we need a `js2-' prefix in front of each name.
478 (defvar js2-ERROR -1)
479 (defvar js2-EOF 0)
480 (defvar js2-EOL 1)
481 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
482 (defvar js2-LEAVEWITH 3)
483 (defvar js2-RETURN 4)
484 (defvar js2-GOTO 5)
485 (defvar js2-IFEQ 6)
486 (defvar js2-IFNE 7)
487 (defvar js2-SETNAME 8)
488 (defvar js2-BITOR 9)
489 (defvar js2-BITXOR 10)
490 (defvar js2-BITAND 11)
491 (defvar js2-EQ 12)
492 (defvar js2-NE 13)
493 (defvar js2-LT 14)
494 (defvar js2-LE 15)
495 (defvar js2-GT 16)
496 (defvar js2-GE 17)
497 (defvar js2-LSH 18)
498 (defvar js2-RSH 19)
499 (defvar js2-URSH 20)
500 (defvar js2-ADD 21) ; infix plus
501 (defvar js2-SUB 22) ; infix minus
502 (defvar js2-MUL 23)
503 (defvar js2-DIV 24)
504 (defvar js2-MOD 25)
505 (defvar js2-NOT 26)
506 (defvar js2-BITNOT 27)
507 (defvar js2-POS 28) ; unary plus
508 (defvar js2-NEG 29) ; unary minus
509 (defvar js2-NEW 30)
510 (defvar js2-DELPROP 31)
511 (defvar js2-TYPEOF 32)
512 (defvar js2-GETPROP 33)
513 (defvar js2-GETPROPNOWARN 34)
514 (defvar js2-SETPROP 35)
515 (defvar js2-GETELEM 36)
516 (defvar js2-SETELEM 37)
517 (defvar js2-CALL 38)
518 (defvar js2-NAME 39) ; an identifier
519 (defvar js2-NUMBER 40)
520 (defvar js2-STRING 41)
521 (defvar js2-NULL 42)
522 (defvar js2-THIS 43)
523 (defvar js2-FALSE 44)
524 (defvar js2-TRUE 45)
525 (defvar js2-SHEQ 46) ; shallow equality (===)
526 (defvar js2-SHNE 47) ; shallow inequality (!==)
527 (defvar js2-REGEXP 48)
528 (defvar js2-BINDNAME 49)
529 (defvar js2-THROW 50)
530 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
531 (defvar js2-IN 52)
532 (defvar js2-INSTANCEOF 53)
533 (defvar js2-LOCAL_LOAD 54)
534 (defvar js2-GETVAR 55)
535 (defvar js2-SETVAR 56)
536 (defvar js2-CATCH_SCOPE 57)
537 (defvar js2-ENUM_INIT_KEYS 58)
538 (defvar js2-ENUM_INIT_VALUES 59)
539 (defvar js2-ENUM_INIT_ARRAY 60)
540 (defvar js2-ENUM_NEXT 61)
541 (defvar js2-ENUM_ID 62)
542 (defvar js2-THISFN 63)
543 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
544 (defvar js2-ARRAYLIT 65) ; array literal
545 (defvar js2-OBJECTLIT 66) ; object literal
546 (defvar js2-GET_REF 67) ; *reference
547 (defvar js2-SET_REF 68) ; *reference = something
548 (defvar js2-DEL_REF 69) ; delete reference
549 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
550 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
551 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
552
553 ;; XML support
554 (defvar js2-DEFAULTNAMESPACE 73)
555 (defvar js2-ESCXMLATTR 74)
556 (defvar js2-ESCXMLTEXT 75)
557 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
558 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
559 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
560 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
561
562 (defvar js2-first-bytecode js2-ENTERWITH)
563 (defvar js2-last-bytecode js2-REF_NS_NAME)
564
565 (defvar js2-TRY 80)
566 (defvar js2-SEMI 81) ; semicolon
567 (defvar js2-LB 82) ; left and right brackets
568 (defvar js2-RB 83)
569 (defvar js2-LC 84) ; left and right curly-braces
570 (defvar js2-RC 85)
571 (defvar js2-LP 86) ; left and right parens
572 (defvar js2-RP 87)
573 (defvar js2-COMMA 88) ; comma operator
574
575 (defvar js2-ASSIGN 89) ; simple assignment (=)
576 (defvar js2-ASSIGN_BITOR 90) ; |=
577 (defvar js2-ASSIGN_BITXOR 91) ; ^=
578 (defvar js2-ASSIGN_BITAND 92) ; &=
579 (defvar js2-ASSIGN_LSH 93) ; <<=
580 (defvar js2-ASSIGN_RSH 94) ; >>=
581 (defvar js2-ASSIGN_URSH 95) ; >>>=
582 (defvar js2-ASSIGN_ADD 96) ; +=
583 (defvar js2-ASSIGN_SUB 97) ; -=
584 (defvar js2-ASSIGN_MUL 98) ; *=
585 (defvar js2-ASSIGN_DIV 99) ; /=
586 (defvar js2-ASSIGN_MOD 100) ; %=
587
588 (defvar js2-first-assign js2-ASSIGN)
589 (defvar js2-last-assign js2-ASSIGN_MOD)
590
591 (defvar js2-HOOK 101) ; conditional (?:)
592 (defvar js2-COLON 102)
593 (defvar js2-OR 103) ; logical or (||)
594 (defvar js2-AND 104) ; logical and (&&)
595 (defvar js2-INC 105) ; increment/decrement (++ --)
596 (defvar js2-DEC 106)
597 (defvar js2-DOT 107) ; member operator (.)
598 (defvar js2-FUNCTION 108) ; function keyword
599 (defvar js2-EXPORT 109) ; export keyword
600 (defvar js2-IMPORT 110) ; import keyword
601 (defvar js2-IF 111) ; if keyword
602 (defvar js2-ELSE 112) ; else keyword
603 (defvar js2-SWITCH 113) ; switch keyword
604 (defvar js2-CASE 114) ; case keyword
605 (defvar js2-DEFAULT 115) ; default keyword
606 (defvar js2-WHILE 116) ; while keyword
607 (defvar js2-DO 117) ; do keyword
608 (defvar js2-FOR 118) ; for keyword
609 (defvar js2-BREAK 119) ; break keyword
610 (defvar js2-CONTINUE 120) ; continue keyword
611 (defvar js2-VAR 121) ; var keyword
612 (defvar js2-WITH 122) ; with keyword
613 (defvar js2-CATCH 123) ; catch keyword
614 (defvar js2-FINALLY 124) ; finally keyword
615 (defvar js2-VOID 125) ; void keyword
616 (defvar js2-RESERVED 126) ; reserved keywords
617
618 (defvar js2-EMPTY 127)
619
620 ;; Types used for the parse tree - never returned by scanner.
621
622 (defvar js2-BLOCK 128) ; statement block
623 (defvar js2-LABEL 129) ; label
624 (defvar js2-TARGET 130)
625 (defvar js2-LOOP 131)
626 (defvar js2-EXPR_VOID 132) ; expression statement in functions
627 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
628 (defvar js2-JSR 134)
629 (defvar js2-SCRIPT 135) ; top-level node for entire script
630 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
631 (defvar js2-USE_STACK 137)
632 (defvar js2-SETPROP_OP 138) ; x.y op= something
633 (defvar js2-SETELEM_OP 139) ; x[y] op= something
634 (defvar js2-LOCAL_BLOCK 140)
635 (defvar js2-SET_REF_OP 141) ; *reference op= something
636
637 ;; For XML support:
638 (defvar js2-DOTDOT 142) ; member operator (..)
639 (defvar js2-COLONCOLON 143) ; namespace::name
640 (defvar js2-XML 144) ; XML type
641 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
642 (defvar js2-XMLATTR 146) ; @
643 (defvar js2-XMLEND 147)
644
645 ;; Optimizer-only tokens
646 (defvar js2-TO_OBJECT 148)
647 (defvar js2-TO_DOUBLE 149)
648
649 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
650 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
651 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
652 (defvar js2-CONST 153)
653 (defvar js2-SETCONST 154)
654 (defvar js2-SETCONSTVAR 155)
655 (defvar js2-ARRAYCOMP 156)
656 (defvar js2-LETEXPR 157)
657 (defvar js2-WITHEXPR 158)
658 (defvar js2-DEBUGGER 159)
659
660 (defvar js2-COMMENT 160)
661 (defvar js2-ENUM 161) ; for "enum" reserved word
662 (defvar js2-TRIPLEDOT 162) ; for rest parameter
663 (defvar js2-ARROW 163) ; function arrow (=>)
664
665 (defconst js2-num-tokens (1+ js2-ARROW))
666
667 (defconst js2-debug-print-trees nil)
668
669 ;; Rhino accepts any string or stream as input. Emacs character
670 ;; processing works best in buffers, so we'll assume the input is a
671 ;; buffer. JavaScript strings can be copied into temp buffers before
672 ;; scanning them.
673
674 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
675 ;; They're the Emacs equivalent of instance variables, more or less.
676
677 (js2-deflocal js2-ts-dirty-line nil
678 "Token stream buffer-local variable.
679 Indicates stuff other than whitespace since start of line.")
680
681 (js2-deflocal js2-ts-hit-eof nil
682 "Token stream buffer-local variable.")
683
684 ;; FIXME: Unused.
685 (js2-deflocal js2-ts-line-start 0
686 "Token stream buffer-local variable.")
687
688 (js2-deflocal js2-ts-lineno 1
689 "Token stream buffer-local variable.")
690
691 ;; FIXME: Unused.
692 (js2-deflocal js2-ts-line-end-char -1
693 "Token stream buffer-local variable.")
694
695 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
696 "Token stream buffer-local variable.
697 Current scan position.")
698
699 ;; FIXME: Unused.
700 (js2-deflocal js2-ts-is-xml-attribute nil
701 "Token stream buffer-local variable.")
702
703 (js2-deflocal js2-ts-xml-is-tag-content nil
704 "Token stream buffer-local variable.")
705
706 (js2-deflocal js2-ts-xml-open-tags-count 0
707 "Token stream buffer-local variable.")
708
709 (js2-deflocal js2-ts-string-buffer nil
710 "Token stream buffer-local variable.
711 List of chars built up while scanning various tokens.")
712
713 (defstruct (js2-token
714 (:constructor nil)
715 (:constructor make-js2-token (beg)))
716 "Value returned from the token stream."
717 (type js2-EOF)
718 (beg 1)
719 (end -1)
720 (string "")
721 number
722 regexp-flags
723 comment-type
724 follows-eol-p)
725
726 (defstruct (js2-ts-state
727 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
728 (cursor js2-ts-cursor)
729 (tokens (copy-sequence js2-ti-tokens))
730 (tokens-cursor js2-ti-tokens-cursor)
731 (lookahead js2-ti-lookahead))))
732 lineno
733 cursor
734 tokens
735 tokens-cursor
736 lookahead)
737
738 ;;; Parser variables
739
740 (js2-deflocal js2-parsed-errors nil
741 "List of errors produced during scanning/parsing.")
742
743 (js2-deflocal js2-parsed-warnings nil
744 "List of warnings produced during scanning/parsing.")
745
746 (js2-deflocal js2-recover-from-parse-errors t
747 "Non-nil to continue parsing after a syntax error.
748
749 In recovery mode, the AST will be built in full, and any error
750 nodes will be flagged with appropriate error information. If
751 this flag is nil, a syntax error will result in an error being
752 signaled.
753
754 The variable is automatically buffer-local, because different
755 modes that use the parser will need different settings.")
756
757 (js2-deflocal js2-parse-hook nil
758 "List of callbacks for receiving parsing progress.")
759
760 (defvar js2-parse-finished-hook nil
761 "List of callbacks to notify when parsing finishes.
762 Not called if parsing was interrupted.")
763
764 (js2-deflocal js2-is-eval-code nil
765 "True if we're evaluating code in a string.
766 If non-nil, the tokenizer will record the token text, and the AST nodes
767 will record their source text. Off by default for IDE modes, since the
768 text is available in the buffer.")
769
770 (defvar js2-parse-ide-mode t
771 "Non-nil if the parser is being used for `js2-mode'.
772 If non-nil, the parser will set text properties for fontification
773 and the syntax table. The value should be nil when using the
774 parser as a frontend to an interpreter or byte compiler.")
775
776 ;;; Parser instance variables (buffer-local vars for js2-parse)
777
778 (defconst js2-ti-after-eol (lsh 1 16)
779 "Flag: first token of the source line.")
780
781 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
782
783 (js2-deflocal js2-compiler-generate-debug-info t)
784 (js2-deflocal js2-compiler-use-dynamic-scope nil)
785 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
786 (js2-deflocal js2-compiler-xml-available t)
787 (js2-deflocal js2-compiler-optimization-level 0)
788 (js2-deflocal js2-compiler-generating-source t)
789 (js2-deflocal js2-compiler-strict-mode nil)
790 (js2-deflocal js2-compiler-report-warning-as-error nil)
791 (js2-deflocal js2-compiler-generate-observer-count nil)
792 (js2-deflocal js2-compiler-activation-names nil)
793
794 ;; SKIP: sourceURI
795
796 ;; There's a compileFunction method in Context.java - may need it.
797 (js2-deflocal js2-called-by-compile-function nil
798 "True if `js2-parse' was called by `js2-compile-function'.
799 Will only be used when we finish implementing the interpreter.")
800
801 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
802
803 ;; SKIP: node factory - we're going to just call functions directly,
804 ;; and eventually go to a unified AST format.
805
806 (js2-deflocal js2-nesting-of-function 0)
807
808 (js2-deflocal js2-recorded-identifiers nil
809 "Tracks identifiers found during parsing.")
810
811 (js2-deflocal js2-is-in-destructuring nil
812 "True while parsing destructuring expression.")
813
814 (defcustom js2-global-externs nil
815 "A list of any extern names you'd like to consider always declared.
816 This list is global and is used by all `js2-mode' files.
817 You can create buffer-local externs list using `js2-additional-externs'.
818
819 There is also a buffer-local variable `js2-default-externs',
820 which is initialized by default to include the Ecma-262 externs
821 and the standard browser externs. The three lists are all
822 checked during highlighting."
823 :type 'list
824 :group 'js2-mode)
825
826 (js2-deflocal js2-default-externs nil
827 "Default external declarations.
828
829 These are currently only used for highlighting undeclared variables,
830 which only worries about top-level (unqualified) references.
831 As js2-mode's processing improves, we will flesh out this list.
832
833 The initial value is set to `js2-ecma-262-externs', unless some
834 of the `js2-include-?-externs' variables are set to t, in which
835 case the browser, Rhino and/or Node.js externs are also included.
836
837 See `js2-additional-externs' for more information.")
838
839 (defcustom js2-include-browser-externs t
840 "Non-nil to include browser externs in the master externs list.
841 If you work on JavaScript files that are not intended for browsers,
842 such as Mozilla Rhino server-side JavaScript, set this to nil.
843 See `js2-additional-externs' for more information about externs."
844 :type 'boolean
845 :group 'js2-mode)
846
847 (defcustom js2-include-rhino-externs nil
848 "Non-nil to include Mozilla Rhino 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 (defcustom js2-include-node-externs nil
854 "Non-nil to include Node.js externs in the master externs list.
855 See `js2-additional-externs' for more information about externs."
856 :type 'boolean
857 :group 'js2-mode)
858
859 (js2-deflocal js2-additional-externs nil
860 "A buffer-local list of additional external declarations.
861 It is used to decide whether variables are considered undeclared
862 for purposes of highlighting.
863
864 Each entry is a Lisp string. The string should be the fully qualified
865 name of an external entity. All externs should be added to this list,
866 so that as js2-mode's processing improves it can take advantage of them.
867
868 You may want to declare your externs in three ways.
869 First, you can add externs that are valid for all your JavaScript files.
870 You should probably do this by adding them to `js2-global-externs', which
871 is a global list used for all js2-mode files.
872
873 Next, you can add a function to `js2-init-hook' that adds additional
874 externs appropriate for the specific file, perhaps based on its path.
875 These should go in `js2-additional-externs', which is buffer-local.
876
877 Third, you can use JSLint's global declaration, as long as
878 `js2-include-jslint-globals' is non-nil, which see.
879
880 Finally, you can add a function to `js2-post-parse-callbacks',
881 which is called after parsing completes, and `js2-mode-ast' is bound to
882 the root of the parse tree. At this stage you can set up an AST
883 node visitor using `js2-visit-ast' and examine the parse tree
884 for specific import patterns that may imply the existence of
885 other externs, possibly tied to your build system. These should also
886 be added to `js2-additional-externs'.
887
888 Your post-parse callback may of course also use the simpler and
889 faster (but perhaps less robust) approach of simply scanning the
890 buffer text for your imports, using regular expressions.")
891
892 ;; SKIP: decompiler
893 ;; SKIP: encoded-source
894
895 ;;; The following variables are per-function and should be saved/restored
896 ;;; during function parsing...
897
898 (js2-deflocal js2-current-script-or-fn nil)
899 (js2-deflocal js2-current-scope nil)
900 (js2-deflocal js2-nesting-of-with 0)
901 (js2-deflocal js2-label-set nil
902 "An alist mapping label names to nodes.")
903
904 (js2-deflocal js2-loop-set nil)
905 (js2-deflocal js2-loop-and-switch-set nil)
906 (js2-deflocal js2-has-return-value nil)
907 (js2-deflocal js2-end-flags 0)
908
909 ;;; ...end of per function variables
910
911 ;; These flags enumerate the possible ways a statement/function can
912 ;; terminate. These flags are used by endCheck() and by the Parser to
913 ;; detect inconsistent return usage.
914 ;;
915 ;; END_UNREACHED is reserved for code paths that are assumed to always be
916 ;; able to execute (example: throw, continue)
917 ;;
918 ;; END_DROPS_OFF indicates if the statement can transfer control to the
919 ;; next one. Statement such as return dont. A compound statement may have
920 ;; some branch that drops off control to the next statement.
921 ;;
922 ;; END_RETURNS indicates that the statement can return (without arguments)
923 ;; END_RETURNS_VALUE indicates that the statement can return a value.
924 ;;
925 ;; A compound statement such as
926 ;; if (condition) {
927 ;; return value;
928 ;; }
929 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
930
931 (defconst js2-end-unreached #x0)
932 (defconst js2-end-drops-off #x1)
933 (defconst js2-end-returns #x2)
934 (defconst js2-end-returns-value #x4)
935
936 ;; Rhino awkwardly passes a statementLabel parameter to the
937 ;; statementHelper() function, the main statement parser, which
938 ;; is then used by quite a few of the sub-parsers. We just make
939 ;; it a buffer-local variable and make sure it's cleaned up properly.
940 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
941
942 ;; Similarly, Rhino passes an inForInit boolean through about half
943 ;; the expression parsers. We use a dynamically-scoped variable,
944 ;; which makes it easier to funcall the parsers individually without
945 ;; worrying about whether they take the parameter or not.
946 (js2-deflocal js2-in-for-init nil)
947 (js2-deflocal js2-temp-name-counter 0)
948 (js2-deflocal js2-parse-stmt-count 0)
949
950 (defsubst js2-get-next-temp-name ()
951 (format "$%d" (incf js2-temp-name-counter)))
952
953 (defvar js2-parse-interruptable-p t
954 "Set this to nil to force parse to continue until finished.
955 This will mostly be useful for interpreters.")
956
957 (defvar js2-statements-per-pause 50
958 "Pause after this many statements to check for user input.
959 If user input is pending, stop the parse and discard the tree.
960 This makes for a smoother user experience for large files.
961 You may have to wait a second or two before the highlighting
962 and error-reporting appear, but you can always type ahead if
963 you wish. This appears to be more or less how Eclipse, IntelliJ
964 and other editors work.")
965
966 (js2-deflocal js2-record-comments t
967 "Instructs the scanner to record comments in `js2-scanned-comments'.")
968
969 (js2-deflocal js2-scanned-comments nil
970 "List of all comments from the current parse.")
971
972 (defcustom js2-mode-indent-inhibit-undo nil
973 "Non-nil to disable collection of Undo information when indenting lines.
974 Some users have requested this behavior. It's nil by default because
975 other Emacs modes don't work this way."
976 :type 'boolean
977 :group 'js2-mode)
978
979 (defcustom js2-mode-indent-ignore-first-tab nil
980 "If non-nil, ignore first TAB keypress if we look indented properly.
981 It's fairly common for users to navigate to an already-indented line
982 and press TAB for reassurance that it's been indented. For this class
983 of users, we want the first TAB press on a line to be ignored if the
984 line is already indented to one of the precomputed alternatives.
985
986 This behavior is only partly implemented. If you TAB-indent a line,
987 navigate to another line, and then navigate back, it fails to clear
988 the last-indented variable, so it thinks you've already hit TAB once,
989 and performs the indent. A full solution would involve getting on the
990 point-motion hooks for the entire buffer. If we come across another
991 use cases that requires watching point motion, I'll consider doing it.
992
993 If you set this variable to nil, then the TAB key will always change
994 the indentation of the current line, if more than one alternative
995 indentation spot exists."
996 :type 'boolean
997 :group 'js2-mode)
998
999 (defvar js2-indent-hook nil
1000 "A hook for user-defined indentation rules.
1001
1002 Functions on this hook should expect two arguments: (LIST INDEX)
1003 The LIST argument is the list of computed indentation points for
1004 the current line. INDEX is the list index of the indentation point
1005 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1006 indent function is not going to change the current line indentation.
1007
1008 If a hook function on this list returns a non-nil value, then
1009 `js2-bounce-indent' assumes the hook function has performed its own
1010 indentation, and will do nothing. If all hook functions on the list
1011 return nil, then `js2-bounce-indent' will use its computed indentation
1012 and reindent the line.
1013
1014 When hook functions on this hook list are called, the variable
1015 `js2-mode-ast' may or may not be set, depending on whether the
1016 parse tree is available. If the variable is nil, you can pass a
1017 callback to `js2-mode-wait-for-parse', and your callback will be
1018 called after the new parse tree is built. This can take some time
1019 in large files.")
1020
1021 (defface js2-warning
1022 `((((class color) (background light))
1023 (:underline "orange"))
1024 (((class color) (background dark))
1025 (:underline "orange"))
1026 (t (:underline t)))
1027 "Face for JavaScript warnings."
1028 :group 'js2-mode)
1029
1030 (defface js2-error
1031 `((((class color) (background light))
1032 (:foreground "red"))
1033 (((class color) (background dark))
1034 (:foreground "red"))
1035 (t (:foreground "red")))
1036 "Face for JavaScript errors."
1037 :group 'js2-mode)
1038
1039 (defface js2-jsdoc-tag
1040 '((t :foreground "SlateGray"))
1041 "Face used to highlight @whatever tags in jsdoc comments."
1042 :group 'js2-mode)
1043
1044 (defface js2-jsdoc-type
1045 '((t :foreground "SteelBlue"))
1046 "Face used to highlight {FooBar} types in jsdoc comments."
1047 :group 'js2-mode)
1048
1049 (defface js2-jsdoc-value
1050 '((t :foreground "PeachPuff3"))
1051 "Face used to highlight tag values in jsdoc comments."
1052 :group 'js2-mode)
1053
1054 (defface js2-function-param
1055 '((t :foreground "SeaGreen"))
1056 "Face used to highlight function parameters in javascript."
1057 :group 'js2-mode)
1058
1059 (defface js2-function-call
1060 '((t :inherit default))
1061 "Face used to highlight function name in calls."
1062 :group 'js2-mode)
1063
1064 (defface js2-instance-member
1065 '((t :foreground "DarkOrchid"))
1066 "Face used to highlight instance variables in javascript.
1067 Not currently used."
1068 :group 'js2-mode)
1069
1070 (defface js2-private-member
1071 '((t :foreground "PeachPuff3"))
1072 "Face used to highlight calls to private methods in javascript.
1073 Not currently used."
1074 :group 'js2-mode)
1075
1076 (defface js2-private-function-call
1077 '((t :foreground "goldenrod"))
1078 "Face used to highlight calls to private functions in javascript.
1079 Not currently used."
1080 :group 'js2-mode)
1081
1082 (defface js2-jsdoc-html-tag-name
1083 '((((class color) (min-colors 88) (background light))
1084 (:foreground "rosybrown"))
1085 (((class color) (min-colors 8) (background dark))
1086 (:foreground "yellow"))
1087 (((class color) (min-colors 8) (background light))
1088 (:foreground "magenta")))
1089 "Face used to highlight jsdoc html tag names"
1090 :group 'js2-mode)
1091
1092 (defface js2-jsdoc-html-tag-delimiter
1093 '((((class color) (min-colors 88) (background light))
1094 (:foreground "dark khaki"))
1095 (((class color) (min-colors 8) (background dark))
1096 (:foreground "green"))
1097 (((class color) (min-colors 8) (background light))
1098 (:foreground "green")))
1099 "Face used to highlight brackets in jsdoc html tags."
1100 :group 'js2-mode)
1101
1102 (defface js2-external-variable
1103 '((t :foreground "orange"))
1104 "Face used to highlight undeclared variable identifiers.")
1105
1106 (defcustom js2-init-hook nil
1107 "List of functions to be called after `js2-mode' or
1108 `js2-minor-mode' has initialized all variables, before parsing
1109 the buffer for the first time."
1110 :type 'hook
1111 :group 'js2-mode
1112 :version "20130608")
1113
1114 (defcustom js2-post-parse-callbacks nil
1115 "List of callback functions invoked after parsing finishes.
1116 Currently, the main use for this function is to add synthetic
1117 declarations to `js2-recorded-identifiers', which see."
1118 :type 'hook
1119 :group 'js2-mode)
1120
1121 (defcustom js2-highlight-external-variables t
1122 "Non-nil to highlight undeclared variable identifiers.
1123 An undeclared variable is any variable not declared with var or let
1124 in the current scope or any lexically enclosing scope. If you use
1125 such a variable, then you are either expecting it to originate from
1126 another file, or you've got a potential bug."
1127 :type 'boolean
1128 :group 'js2-mode)
1129
1130 (defcustom js2-include-jslint-globals t
1131 "Non-nil to include the identifiers from JSLint global
1132 declaration (see http://www.jslint.com/lint.html#global) in the
1133 buffer-local externs list. See `js2-additional-externs' for more
1134 information."
1135 :type 'boolean
1136 :group 'js2-mode)
1137
1138 (defvar js2-mode-map
1139 (let ((map (make-sparse-keymap)))
1140 (define-key map [mouse-1] #'js2-mode-show-node)
1141 (define-key map (kbd "M-j") #'js2-line-break)
1142 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1143 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1144 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1145 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1146 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1147 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1148 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1149 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1150 (when js2-bounce-indent-p
1151 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1152
1153 (define-key map [menu-bar javascript]
1154 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1155
1156 (define-key map [menu-bar javascript customize-js2-mode]
1157 '(menu-item "Customize js2-mode" js2-mode-customize
1158 :help "Customize the behavior of this mode"))
1159
1160 (define-key map [menu-bar javascript js2-force-refresh]
1161 '(menu-item "Force buffer refresh" js2-mode-reset
1162 :help "Re-parse the buffer from scratch"))
1163
1164 (define-key map [menu-bar javascript separator-2]
1165 '("--"))
1166
1167 (define-key map [menu-bar javascript next-error]
1168 '(menu-item "Next warning or error" next-error
1169 :enabled (and js2-mode-ast
1170 (or (js2-ast-root-errors js2-mode-ast)
1171 (js2-ast-root-warnings js2-mode-ast)))
1172 :help "Move to next warning or error"))
1173
1174 (define-key map [menu-bar javascript display-errors]
1175 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1176 :visible (not js2-mode-show-parse-errors)
1177 :help "Turn on display of warnings and errors"))
1178
1179 (define-key map [menu-bar javascript hide-errors]
1180 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1181 :visible js2-mode-show-parse-errors
1182 :help "Turn off display of warnings and errors"))
1183
1184 (define-key map [menu-bar javascript separator-1]
1185 '("--"))
1186
1187 (define-key map [menu-bar javascript js2-toggle-function]
1188 '(menu-item "Show/collapse element" js2-mode-toggle-element
1189 :help "Hide or show function body or comment"))
1190
1191 (define-key map [menu-bar javascript show-comments]
1192 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1193 :visible js2-mode-comments-hidden
1194 :help "Expand all hidden block comments"))
1195
1196 (define-key map [menu-bar javascript hide-comments]
1197 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1198 :visible (not js2-mode-comments-hidden)
1199 :help "Show block comments as /*...*/"))
1200
1201 (define-key map [menu-bar javascript show-all-functions]
1202 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1203 :visible js2-mode-functions-hidden
1204 :help "Expand all hidden function bodies"))
1205
1206 (define-key map [menu-bar javascript hide-all-functions]
1207 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1208 :visible (not js2-mode-functions-hidden)
1209 :help "Show {...} for all top-level function bodies"))
1210
1211 map)
1212 "Keymap used in `js2-mode' buffers.")
1213
1214 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1215
1216 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1217 "Matches a //-comment line. Must be first non-whitespace on line.
1218 First match-group is the leading whitespace.")
1219
1220 (defvar js2-mode-hook nil)
1221
1222 (js2-deflocal js2-mode-ast nil "Private variable.")
1223 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1224 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1225 (js2-deflocal js2-mode-parsing nil "Private variable.")
1226 (js2-deflocal js2-mode-node-overlay nil)
1227
1228 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1229 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1230
1231 (js2-deflocal js2-mode-fontifications nil "Private variable")
1232 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1233 (js2-deflocal js2-imenu-recorder nil "Private variable")
1234 (js2-deflocal js2-imenu-function-map nil "Private variable")
1235
1236 (defvar js2-paragraph-start
1237 "\\(@[[:alpha:]]+\\>\\|$\\)")
1238
1239 ;; Note that we also set a 'c-in-sws text property in html comments,
1240 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1241 (defvar js2-syntactic-ws-start
1242 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1243
1244 (defvar js2-syntactic-ws-end
1245 "\\s \\|[\n\r/]\\|\\s!")
1246
1247 (defvar js2-syntactic-eol
1248 (concat "\\s *\\(/\\*[^*\n\r]*"
1249 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1250 "\\*+/\\s *\\)*"
1251 "\\(//\\|/\\*[^*\n\r]*"
1252 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1253 "\\|\\\\$\\|$\\)")
1254 "Copied from `java-mode'. Needed for some cc-engine functions.")
1255
1256 (defvar js2-comment-prefix-regexp
1257 "//+\\|\\**")
1258
1259 (defvar js2-comment-start-skip
1260 "\\(//+\\|/\\*+\\)\\s *")
1261
1262 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1263 "Non-nil to emit status messages during parsing.")
1264
1265 (defvar js2-mode-functions-hidden nil "Private variable.")
1266 (defvar js2-mode-comments-hidden nil "Private variable.")
1267
1268 (defvar js2-mode-syntax-table
1269 (let ((table (make-syntax-table)))
1270 (c-populate-syntax-table table)
1271 table)
1272 "Syntax table used in `js2-mode' buffers.")
1273
1274 (defvar js2-mode-abbrev-table nil
1275 "Abbrev table in use in `js2-mode' buffers.")
1276 (define-abbrev-table 'js2-mode-abbrev-table ())
1277
1278 (defvar js2-mode-pending-parse-callbacks nil
1279 "List of functions waiting to be notified that parse is finished.")
1280
1281 (defvar js2-mode-last-indented-line -1)
1282
1283 ;;; Localizable error and warning messages
1284
1285 ;; Messages are copied from Rhino's Messages.properties.
1286 ;; Many of the Java-specific messages have been elided.
1287 ;; Add any js2-specific ones at the end, so we can keep
1288 ;; this file synced with changes to Rhino's.
1289
1290 (defvar js2-message-table
1291 (make-hash-table :test 'equal :size 250)
1292 "Contains localized messages for `js2-mode'.")
1293
1294 ;; TODO(stevey): construct this table at compile-time.
1295 (defmacro js2-msg (key &rest strings)
1296 `(puthash ,key (concat ,@strings)
1297 js2-message-table))
1298
1299 (defun js2-get-msg (msg-key)
1300 "Look up a localized message.
1301 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1302 the correct number of ARGS must be provided."
1303 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1304 (args (if (listp msg-key) (cdr msg-key)))
1305 (msg (gethash key js2-message-table)))
1306 (if msg
1307 (apply #'format msg args)
1308 key))) ; default to showing the key
1309
1310 (js2-msg "msg.dup.parms"
1311 "Duplicate parameter name '%s'.")
1312
1313 (js2-msg "msg.too.big.jump"
1314 "Program too complex: jump offset too big.")
1315
1316 (js2-msg "msg.too.big.index"
1317 "Program too complex: internal index exceeds 64K limit.")
1318
1319 (js2-msg "msg.while.compiling.fn"
1320 "Encountered code generation error while compiling function '%s': %s")
1321
1322 (js2-msg "msg.while.compiling.script"
1323 "Encountered code generation error while compiling script: %s")
1324
1325 ;; Context
1326 (js2-msg "msg.ctor.not.found"
1327 "Constructor for '%s' not found.")
1328
1329 (js2-msg "msg.not.ctor"
1330 "'%s' is not a constructor.")
1331
1332 ;; FunctionObject
1333 (js2-msg "msg.varargs.ctor"
1334 "Method or constructor '%s' must be static "
1335 "with the signature (Context cx, Object[] args, "
1336 "Function ctorObj, boolean inNewExpr) "
1337 "to define a variable arguments constructor.")
1338
1339 (js2-msg "msg.varargs.fun"
1340 "Method '%s' must be static with the signature "
1341 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1342 "to define a variable arguments function.")
1343
1344 (js2-msg "msg.incompat.call"
1345 "Method '%s' called on incompatible object.")
1346
1347 (js2-msg "msg.bad.parms"
1348 "Unsupported parameter type '%s' in method '%s'.")
1349
1350 (js2-msg "msg.bad.method.return"
1351 "Unsupported return type '%s' in method '%s'.")
1352
1353 (js2-msg "msg.bad.ctor.return"
1354 "Construction of objects of type '%s' is not supported.")
1355
1356 (js2-msg "msg.no.overload"
1357 "Method '%s' occurs multiple times in class '%s'.")
1358
1359 (js2-msg "msg.method.not.found"
1360 "Method '%s' not found in '%s'.")
1361
1362 ;; IRFactory
1363
1364 (js2-msg "msg.bad.for.in.lhs"
1365 "Invalid left-hand side of for..in loop.")
1366
1367 (js2-msg "msg.mult.index"
1368 "Only one variable allowed in for..in loop.")
1369
1370 (js2-msg "msg.bad.for.in.destruct"
1371 "Left hand side of for..in loop must be an array of "
1372 "length 2 to accept key/value pair.")
1373
1374 (js2-msg "msg.cant.convert"
1375 "Can't convert to type '%s'.")
1376
1377 (js2-msg "msg.bad.assign.left"
1378 "Invalid assignment left-hand side.")
1379
1380 (js2-msg "msg.bad.decr"
1381 "Invalid decerement operand.")
1382
1383 (js2-msg "msg.bad.incr"
1384 "Invalid increment operand.")
1385
1386 (js2-msg "msg.bad.yield"
1387 "yield must be in a function.")
1388
1389 (js2-msg "msg.yield.parenthesized"
1390 "yield expression must be parenthesized.")
1391
1392 ;; NativeGlobal
1393 (js2-msg "msg.cant.call.indirect"
1394 "Function '%s' must be called directly, and not by way of a "
1395 "function of another name.")
1396
1397 (js2-msg "msg.eval.nonstring"
1398 "Calling eval() with anything other than a primitive "
1399 "string value will simply return the value. "
1400 "Is this what you intended?")
1401
1402 (js2-msg "msg.eval.nonstring.strict"
1403 "Calling eval() with anything other than a primitive "
1404 "string value is not allowed in strict mode.")
1405
1406 (js2-msg "msg.bad.destruct.op"
1407 "Invalid destructuring assignment operator")
1408
1409 ;; NativeCall
1410 (js2-msg "msg.only.from.new"
1411 "'%s' may only be invoked from a `new' expression.")
1412
1413 (js2-msg "msg.deprec.ctor"
1414 "The '%s' constructor is deprecated.")
1415
1416 ;; NativeFunction
1417 (js2-msg "msg.no.function.ref.found"
1418 "no source found to decompile function reference %s")
1419
1420 (js2-msg "msg.arg.isnt.array"
1421 "second argument to Function.prototype.apply must be an array")
1422
1423 ;; NativeGlobal
1424 (js2-msg "msg.bad.esc.mask"
1425 "invalid string escape mask")
1426
1427 ;; NativeRegExp
1428 (js2-msg "msg.bad.quant"
1429 "Invalid quantifier %s")
1430
1431 (js2-msg "msg.overlarge.backref"
1432 "Overly large back reference %s")
1433
1434 (js2-msg "msg.overlarge.min"
1435 "Overly large minimum %s")
1436
1437 (js2-msg "msg.overlarge.max"
1438 "Overly large maximum %s")
1439
1440 (js2-msg "msg.zero.quant"
1441 "Zero quantifier %s")
1442
1443 (js2-msg "msg.max.lt.min"
1444 "Maximum %s less than minimum")
1445
1446 (js2-msg "msg.unterm.quant"
1447 "Unterminated quantifier %s")
1448
1449 (js2-msg "msg.unterm.paren"
1450 "Unterminated parenthetical %s")
1451
1452 (js2-msg "msg.unterm.class"
1453 "Unterminated character class %s")
1454
1455 (js2-msg "msg.bad.range"
1456 "Invalid range in character class.")
1457
1458 (js2-msg "msg.trail.backslash"
1459 "Trailing \\ in regular expression.")
1460
1461 (js2-msg "msg.re.unmatched.right.paren"
1462 "unmatched ) in regular expression.")
1463
1464 (js2-msg "msg.no.regexp"
1465 "Regular expressions are not available.")
1466
1467 (js2-msg "msg.bad.backref"
1468 "back-reference exceeds number of capturing parentheses.")
1469
1470 (js2-msg "msg.bad.regexp.compile"
1471 "Only one argument may be specified if the first "
1472 "argument to RegExp.prototype.compile is a RegExp object.")
1473
1474 ;; Parser
1475 (js2-msg "msg.got.syntax.errors"
1476 "Compilation produced %s syntax errors.")
1477
1478 (js2-msg "msg.var.redecl"
1479 "TypeError: redeclaration of var %s.")
1480
1481 (js2-msg "msg.const.redecl"
1482 "TypeError: redeclaration of const %s.")
1483
1484 (js2-msg "msg.let.redecl"
1485 "TypeError: redeclaration of variable %s.")
1486
1487 (js2-msg "msg.parm.redecl"
1488 "TypeError: redeclaration of formal parameter %s.")
1489
1490 (js2-msg "msg.fn.redecl"
1491 "TypeError: redeclaration of function %s.")
1492
1493 (js2-msg "msg.let.decl.not.in.block"
1494 "SyntaxError: let declaration not directly within block")
1495
1496 ;; NodeTransformer
1497 (js2-msg "msg.dup.label"
1498 "duplicated label")
1499
1500 (js2-msg "msg.undef.label"
1501 "undefined label")
1502
1503 (js2-msg "msg.bad.break"
1504 "unlabelled break must be inside loop or switch")
1505
1506 (js2-msg "msg.continue.outside"
1507 "continue must be inside loop")
1508
1509 (js2-msg "msg.continue.nonloop"
1510 "continue can only use labels of iteration statements")
1511
1512 (js2-msg "msg.bad.throw.eol"
1513 "Line terminator is not allowed between the throw "
1514 "keyword and throw expression.")
1515
1516 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1517 "function statement requires a name")
1518
1519 (js2-msg "msg.no.paren.parms"
1520 "missing ( before function parameters.")
1521
1522 (js2-msg "msg.no.parm"
1523 "missing formal parameter")
1524
1525 (js2-msg "msg.no.paren.after.parms"
1526 "missing ) after formal parameters")
1527
1528 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1529 "parameter without default follows parameter with default")
1530
1531 (js2-msg "msg.param.after.rest" ; added by js2-mode
1532 "parameter after rest parameter")
1533
1534 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1535 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1536
1537 (js2-msg "msg.no.brace.body"
1538 "missing '{' before function body")
1539
1540 (js2-msg "msg.no.brace.after.body"
1541 "missing } after function body")
1542
1543 (js2-msg "msg.no.paren.cond"
1544 "missing ( before condition")
1545
1546 (js2-msg "msg.no.paren.after.cond"
1547 "missing ) after condition")
1548
1549 (js2-msg "msg.no.semi.stmt"
1550 "missing ; before statement")
1551
1552 (js2-msg "msg.missing.semi"
1553 "missing ; after statement")
1554
1555 (js2-msg "msg.no.name.after.dot"
1556 "missing name after . operator")
1557
1558 (js2-msg "msg.no.name.after.coloncolon"
1559 "missing name after :: operator")
1560
1561 (js2-msg "msg.no.name.after.dotdot"
1562 "missing name after .. operator")
1563
1564 (js2-msg "msg.no.name.after.xmlAttr"
1565 "missing name after .@")
1566
1567 (js2-msg "msg.no.bracket.index"
1568 "missing ] in index expression")
1569
1570 (js2-msg "msg.no.paren.switch"
1571 "missing ( before switch expression")
1572
1573 (js2-msg "msg.no.paren.after.switch"
1574 "missing ) after switch expression")
1575
1576 (js2-msg "msg.no.brace.switch"
1577 "missing '{' before switch body")
1578
1579 (js2-msg "msg.bad.switch"
1580 "invalid switch statement")
1581
1582 (js2-msg "msg.no.colon.case"
1583 "missing : after case expression")
1584
1585 (js2-msg "msg.double.switch.default"
1586 "double default label in the switch statement")
1587
1588 (js2-msg "msg.no.while.do"
1589 "missing while after do-loop body")
1590
1591 (js2-msg "msg.no.paren.for"
1592 "missing ( after for")
1593
1594 (js2-msg "msg.no.semi.for"
1595 "missing ; after for-loop initializer")
1596
1597 (js2-msg "msg.no.semi.for.cond"
1598 "missing ; after for-loop condition")
1599
1600 (js2-msg "msg.in.after.for.name"
1601 "missing in or of after for")
1602
1603 (js2-msg "msg.no.paren.for.ctrl"
1604 "missing ) after for-loop control")
1605
1606 (js2-msg "msg.no.paren.with"
1607 "missing ( before with-statement object")
1608
1609 (js2-msg "msg.no.paren.after.with"
1610 "missing ) after with-statement object")
1611
1612 (js2-msg "msg.no.paren.after.let"
1613 "missing ( after let")
1614
1615 (js2-msg "msg.no.paren.let"
1616 "missing ) after variable list")
1617
1618 (js2-msg "msg.no.curly.let"
1619 "missing } after let statement")
1620
1621 (js2-msg "msg.bad.return"
1622 "invalid return")
1623
1624 (js2-msg "msg.no.brace.block"
1625 "missing } in compound statement")
1626
1627 (js2-msg "msg.bad.label"
1628 "invalid label")
1629
1630 (js2-msg "msg.bad.var"
1631 "missing variable name")
1632
1633 (js2-msg "msg.bad.var.init"
1634 "invalid variable initialization")
1635
1636 (js2-msg "msg.no.colon.cond"
1637 "missing : in conditional expression")
1638
1639 (js2-msg "msg.no.paren.arg"
1640 "missing ) after argument list")
1641
1642 (js2-msg "msg.no.bracket.arg"
1643 "missing ] after element list")
1644
1645 (js2-msg "msg.bad.prop"
1646 "invalid property id")
1647
1648 (js2-msg "msg.no.colon.prop"
1649 "missing : after property id")
1650
1651 (js2-msg "msg.no.brace.prop"
1652 "missing } after property list")
1653
1654 (js2-msg "msg.no.paren"
1655 "missing ) in parenthetical")
1656
1657 (js2-msg "msg.reserved.id"
1658 "'%s' is a reserved identifier")
1659
1660 (js2-msg "msg.no.paren.catch"
1661 "missing ( before catch-block condition")
1662
1663 (js2-msg "msg.bad.catchcond"
1664 "invalid catch block condition")
1665
1666 (js2-msg "msg.catch.unreachable"
1667 "any catch clauses following an unqualified catch are unreachable")
1668
1669 (js2-msg "msg.no.brace.try"
1670 "missing '{' before try block")
1671
1672 (js2-msg "msg.no.brace.catchblock"
1673 "missing '{' before catch-block body")
1674
1675 (js2-msg "msg.try.no.catchfinally"
1676 "'try' without 'catch' or 'finally'")
1677
1678 (js2-msg "msg.no.return.value"
1679 "function %s does not always return a value")
1680
1681 (js2-msg "msg.anon.no.return.value"
1682 "anonymous function does not always return a value")
1683
1684 (js2-msg "msg.return.inconsistent"
1685 "return statement is inconsistent with previous usage")
1686
1687 (js2-msg "msg.generator.returns"
1688 "TypeError: legacy generator function '%s' returns a value")
1689
1690 (js2-msg "msg.anon.generator.returns"
1691 "TypeError: anonymous legacy generator function returns a value")
1692
1693 (js2-msg "msg.syntax"
1694 "syntax error")
1695
1696 (js2-msg "msg.unexpected.eof"
1697 "Unexpected end of file")
1698
1699 (js2-msg "msg.XML.bad.form"
1700 "illegally formed XML syntax")
1701
1702 (js2-msg "msg.XML.not.available"
1703 "XML runtime not available")
1704
1705 (js2-msg "msg.too.deep.parser.recursion"
1706 "Too deep recursion while parsing")
1707
1708 (js2-msg "msg.no.side.effects"
1709 "Code has no side effects")
1710
1711 (js2-msg "msg.extra.trailing.comma"
1712 "Trailing comma is not supported in some browsers")
1713
1714 (js2-msg "msg.array.trailing.comma"
1715 "Trailing comma yields different behavior across browsers")
1716
1717 (js2-msg "msg.equal.as.assign"
1718 (concat "Test for equality (==) mistyped as assignment (=)?"
1719 " (parenthesize to suppress warning)"))
1720
1721 (js2-msg "msg.var.hides.arg"
1722 "Variable %s hides argument")
1723
1724 (js2-msg "msg.destruct.assign.no.init"
1725 "Missing = in destructuring declaration")
1726
1727 ;; ScriptRuntime
1728 (js2-msg "msg.no.properties"
1729 "%s has no properties.")
1730
1731 (js2-msg "msg.invalid.iterator"
1732 "Invalid iterator value")
1733
1734 (js2-msg "msg.iterator.primitive"
1735 "__iterator__ returned a primitive value")
1736
1737 (js2-msg "msg.assn.create.strict"
1738 "Assignment to undeclared variable %s")
1739
1740 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1741 "Undeclared variable or function '%s'")
1742
1743 (js2-msg "msg.ref.undefined.prop"
1744 "Reference to undefined property '%s'")
1745
1746 (js2-msg "msg.prop.not.found"
1747 "Property %s not found.")
1748
1749 (js2-msg "msg.invalid.type"
1750 "Invalid JavaScript value of type %s")
1751
1752 (js2-msg "msg.primitive.expected"
1753 "Primitive type expected (had %s instead)")
1754
1755 (js2-msg "msg.namespace.expected"
1756 "Namespace object expected to left of :: (found %s instead)")
1757
1758 (js2-msg "msg.null.to.object"
1759 "Cannot convert null to an object.")
1760
1761 (js2-msg "msg.undef.to.object"
1762 "Cannot convert undefined to an object.")
1763
1764 (js2-msg "msg.cyclic.value"
1765 "Cyclic %s value not allowed.")
1766
1767 (js2-msg "msg.is.not.defined"
1768 "'%s' is not defined.")
1769
1770 (js2-msg "msg.undef.prop.read"
1771 "Cannot read property '%s' from %s")
1772
1773 (js2-msg "msg.undef.prop.write"
1774 "Cannot set property '%s' of %s to '%s'")
1775
1776 (js2-msg "msg.undef.prop.delete"
1777 "Cannot delete property '%s' of %s")
1778
1779 (js2-msg "msg.undef.method.call"
1780 "Cannot call method '%s' of %s")
1781
1782 (js2-msg "msg.undef.with"
1783 "Cannot apply 'with' to %s")
1784
1785 (js2-msg "msg.isnt.function"
1786 "%s is not a function, it is %s.")
1787
1788 (js2-msg "msg.isnt.function.in"
1789 "Cannot call property %s in object %s. "
1790 "It is not a function, it is '%s'.")
1791
1792 (js2-msg "msg.function.not.found"
1793 "Cannot find function %s.")
1794
1795 (js2-msg "msg.function.not.found.in"
1796 "Cannot find function %s in object %s.")
1797
1798 (js2-msg "msg.isnt.xml.object"
1799 "%s is not an xml object.")
1800
1801 (js2-msg "msg.no.ref.to.get"
1802 "%s is not a reference to read reference value.")
1803
1804 (js2-msg "msg.no.ref.to.set"
1805 "%s is not a reference to set reference value to %s.")
1806
1807 (js2-msg "msg.no.ref.from.function"
1808 "Function %s can not be used as the left-hand "
1809 "side of assignment or as an operand of ++ or -- operator.")
1810
1811 (js2-msg "msg.bad.default.value"
1812 "Object's getDefaultValue() method returned an object.")
1813
1814 (js2-msg "msg.instanceof.not.object"
1815 "Can't use instanceof on a non-object.")
1816
1817 (js2-msg "msg.instanceof.bad.prototype"
1818 "'prototype' property of %s is not an object.")
1819
1820 (js2-msg "msg.bad.radix"
1821 "illegal radix %s.")
1822
1823 ;; ScriptableObject
1824 (js2-msg "msg.default.value"
1825 "Cannot find default value for object.")
1826
1827 (js2-msg "msg.zero.arg.ctor"
1828 "Cannot load class '%s' which has no zero-parameter constructor.")
1829
1830 (js2-msg "msg.ctor.multiple.parms"
1831 "Can't define constructor or class %s since more than "
1832 "one constructor has multiple parameters.")
1833
1834 (js2-msg "msg.extend.scriptable"
1835 "%s must extend ScriptableObject in order to define property %s.")
1836
1837 (js2-msg "msg.bad.getter.parms"
1838 "In order to define a property, getter %s must have zero "
1839 "parameters or a single ScriptableObject parameter.")
1840
1841 (js2-msg "msg.obj.getter.parms"
1842 "Expected static or delegated getter %s to take "
1843 "a ScriptableObject parameter.")
1844
1845 (js2-msg "msg.getter.static"
1846 "Getter and setter must both be static or neither be static.")
1847
1848 (js2-msg "msg.setter.return"
1849 "Setter must have void return type: %s")
1850
1851 (js2-msg "msg.setter2.parms"
1852 "Two-parameter setter must take a ScriptableObject as "
1853 "its first parameter.")
1854
1855 (js2-msg "msg.setter1.parms"
1856 "Expected single parameter setter for %s")
1857
1858 (js2-msg "msg.setter2.expected"
1859 "Expected static or delegated setter %s to take two parameters.")
1860
1861 (js2-msg "msg.setter.parms"
1862 "Expected either one or two parameters for setter.")
1863
1864 (js2-msg "msg.setter.bad.type"
1865 "Unsupported parameter type '%s' in setter '%s'.")
1866
1867 (js2-msg "msg.add.sealed"
1868 "Cannot add a property to a sealed object: %s.")
1869
1870 (js2-msg "msg.remove.sealed"
1871 "Cannot remove a property from a sealed object: %s.")
1872
1873 (js2-msg "msg.modify.sealed"
1874 "Cannot modify a property of a sealed object: %s.")
1875
1876 (js2-msg "msg.modify.readonly"
1877 "Cannot modify readonly property: %s.")
1878
1879 ;; TokenStream
1880 (js2-msg "msg.missing.exponent"
1881 "missing exponent")
1882
1883 (js2-msg "msg.caught.nfe"
1884 "number format error")
1885
1886 (js2-msg "msg.unterminated.string.lit"
1887 "unterminated string literal")
1888
1889 (js2-msg "msg.unterminated.comment"
1890 "unterminated comment")
1891
1892 (js2-msg "msg.unterminated.re.lit"
1893 "unterminated regular expression literal")
1894
1895 (js2-msg "msg.invalid.re.flag"
1896 "invalid flag after regular expression")
1897
1898 (js2-msg "msg.no.re.input.for"
1899 "no input for %s")
1900
1901 (js2-msg "msg.illegal.character"
1902 "illegal character")
1903
1904 (js2-msg "msg.invalid.escape"
1905 "invalid Unicode escape sequence")
1906
1907 (js2-msg "msg.bad.namespace"
1908 "not a valid default namespace statement. "
1909 "Syntax is: default xml namespace = EXPRESSION;")
1910
1911 ;; TokensStream warnings
1912 (js2-msg "msg.bad.octal.literal"
1913 "illegal octal literal digit %s; "
1914 "interpreting it as a decimal digit")
1915
1916 (js2-msg "msg.missing.hex.digits"
1917 "missing hexadecimal digits after '0x'")
1918
1919 (js2-msg "msg.missing.binary.digits"
1920 "missing binary digits after '0b'")
1921
1922 (js2-msg "msg.missing.octal.digits"
1923 "missing octal digits after '0o'")
1924
1925 (js2-msg "msg.script.is.not.constructor"
1926 "Script objects are not constructors.")
1927
1928 ;; Arrays
1929 (js2-msg "msg.arraylength.bad"
1930 "Inappropriate array length.")
1931
1932 ;; Arrays
1933 (js2-msg "msg.arraylength.too.big"
1934 "Array length %s exceeds supported capacity limit.")
1935
1936 ;; URI
1937 (js2-msg "msg.bad.uri"
1938 "Malformed URI sequence.")
1939
1940 ;; Number
1941 (js2-msg "msg.bad.precision"
1942 "Precision %s out of range.")
1943
1944 ;; NativeGenerator
1945 (js2-msg "msg.send.newborn"
1946 "Attempt to send value to newborn generator")
1947
1948 (js2-msg "msg.already.exec.gen"
1949 "Already executing generator")
1950
1951 (js2-msg "msg.StopIteration.invalid"
1952 "StopIteration may not be changed to an arbitrary object.")
1953
1954 ;; Interpreter
1955 (js2-msg "msg.yield.closing"
1956 "Yield from closing generator")
1957
1958 ;;; Tokens Buffer
1959
1960 (defconst js2-ti-max-lookahead 2)
1961 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1962
1963 ;; Have to call `js2-init-scanner' to initialize the values.
1964 (js2-deflocal js2-ti-tokens nil)
1965 (js2-deflocal js2-ti-tokens-cursor nil)
1966 (js2-deflocal js2-ti-lookahead nil)
1967
1968 (defun js2-new-token (offset)
1969 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
1970 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
1971 (aset js2-ti-tokens js2-ti-tokens-cursor token)
1972 token))
1973
1974 (defsubst js2-current-token ()
1975 (aref js2-ti-tokens js2-ti-tokens-cursor))
1976
1977 (defsubst js2-current-token-string ()
1978 (js2-token-string (js2-current-token)))
1979
1980 (defsubst js2-current-token-type ()
1981 (js2-token-type (js2-current-token)))
1982
1983 (defsubst js2-current-token-beg ()
1984 (js2-token-beg (js2-current-token)))
1985
1986 (defsubst js2-current-token-end ()
1987 (js2-token-end (js2-current-token)))
1988
1989 (defun js2-current-token-len ()
1990 (let ((token (js2-current-token)))
1991 (- (js2-token-end token)
1992 (js2-token-beg token))))
1993
1994 (defun js2-ts-seek (state)
1995 (setq js2-ts-lineno (js2-ts-state-lineno state)
1996 js2-ts-cursor (js2-ts-state-cursor state)
1997 js2-ti-tokens (js2-ts-state-tokens state)
1998 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
1999 js2-ti-lookahead (js2-ts-state-lookahead state)))
2000
2001 ;;; Utilities
2002
2003 (defun js2-delete-if (predicate list)
2004 "Remove all items satisfying PREDICATE in LIST."
2005 (loop for item in list
2006 if (not (funcall predicate item))
2007 collect item))
2008
2009 (defun js2-position (element list)
2010 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2011 Returns nil if element is not found in the list."
2012 (let ((count 0)
2013 found)
2014 (while (and list (not found))
2015 (if (eq element (car list))
2016 (setq found t)
2017 (setq count (1+ count)
2018 list (cdr list))))
2019 (if found count)))
2020
2021 (defun js2-find-if (predicate list)
2022 "Find first item satisfying PREDICATE in LIST."
2023 (let (result)
2024 (while (and list (not result))
2025 (if (funcall predicate (car list))
2026 (setq result (car list)))
2027 (setq list (cdr list)))
2028 result))
2029
2030 (defmacro js2-time (form)
2031 "Evaluate FORM, discard result, and return elapsed time in sec."
2032 (declare (debug t))
2033 (let ((beg (make-symbol "--js2-time-beg--"))
2034 (delta (make-symbol "--js2-time-end--")))
2035 `(let ((,beg (current-time))
2036 ,delta)
2037 ,form
2038 (/ (truncate (* (- (float-time (current-time))
2039 (float-time ,beg))
2040 10000))
2041 10000.0))))
2042
2043 (defsubst js2-same-line (pos)
2044 "Return t if POS is on the same line as current point."
2045 (and (>= pos (point-at-bol))
2046 (<= pos (point-at-eol))))
2047
2048 (defun js2-code-bug ()
2049 "Signal an error when we encounter an unexpected code path."
2050 (error "failed assertion"))
2051
2052 (defsubst js2-record-text-property (beg end prop value)
2053 "Record a text property to set when parsing finishes."
2054 (push (list beg end prop value) js2-mode-deferred-properties))
2055
2056 ;; I'd like to associate errors with nodes, but for now the
2057 ;; easiest thing to do is get the context info from the last token.
2058 (defun js2-record-parse-error (msg &optional arg pos len)
2059 (push (list (list msg arg)
2060 (or pos (js2-current-token-beg))
2061 (or len (js2-current-token-len)))
2062 js2-parsed-errors))
2063
2064 (defun js2-report-error (msg &optional msg-arg pos len)
2065 "Signal a syntax error or record a parse error."
2066 (if js2-recover-from-parse-errors
2067 (js2-record-parse-error msg msg-arg pos len)
2068 (signal 'js2-syntax-error
2069 (list msg
2070 js2-ts-lineno
2071 (save-excursion
2072 (goto-char js2-ts-cursor)
2073 (current-column))
2074 js2-ts-hit-eof))))
2075
2076 (defun js2-report-warning (msg &optional msg-arg pos len face)
2077 (if js2-compiler-report-warning-as-error
2078 (js2-report-error msg msg-arg pos len)
2079 (push (list (list msg msg-arg)
2080 (or pos (js2-current-token-beg))
2081 (or len (js2-current-token-len))
2082 face)
2083 js2-parsed-warnings)))
2084
2085 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2086 (if js2-compiler-strict-mode
2087 (js2-report-warning msg-id msg-arg beg
2088 (and beg end (- end beg)))))
2089
2090 (put 'js2-syntax-error 'error-conditions
2091 '(error syntax-error js2-syntax-error))
2092 (put 'js2-syntax-error 'error-message "Syntax error")
2093
2094 (put 'js2-parse-error 'error-conditions
2095 '(error parse-error js2-parse-error))
2096 (put 'js2-parse-error 'error-message "Parse error")
2097
2098 (defmacro js2-clear-flag (flags flag)
2099 `(setq ,flags (logand ,flags (lognot ,flag))))
2100
2101 (defmacro js2-set-flag (flags flag)
2102 "Logical-or FLAG into FLAGS."
2103 `(setq ,flags (logior ,flags ,flag)))
2104
2105 (defsubst js2-flag-set-p (flags flag)
2106 (/= 0 (logand flags flag)))
2107
2108 (defsubst js2-flag-not-set-p (flags flag)
2109 (zerop (logand flags flag)))
2110
2111 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2112 "Evaluate BODY with the _ character set to be word-syntax."
2113 (declare (indent 0) (debug t))
2114 (let ((old-syntax (make-symbol "old-syntax")))
2115 `(let ((,old-syntax (string (char-syntax ?_))))
2116 (unwind-protect
2117 (progn
2118 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2119 ,@body)
2120 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2121
2122 ;;; AST struct and function definitions
2123
2124 ;; flags for ast node property 'member-type (used for e4x operators)
2125 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2126 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2127 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2128
2129 (defsubst js2-relpos (pos anchor)
2130 "Convert POS to be relative to ANCHOR.
2131 If POS is nil, returns nil."
2132 (and pos (- pos anchor)))
2133
2134 (defun js2-make-pad (indent)
2135 (if (zerop indent)
2136 ""
2137 (make-string (* indent js2-basic-offset) ? )))
2138
2139 (defun js2-visit-ast (node callback)
2140 "Visit every node in ast NODE with visitor CALLBACK.
2141
2142 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2143 called twice: once to visit the node, and again after all the node's
2144 children have been processed. The END-P argument is nil on the first
2145 call and non-nil on the second call. The return value of the callback
2146 affects the traversal: if non-nil, the children of NODE are processed.
2147 If the callback returns nil, or if the node has no children, then the
2148 callback is called immediately with a non-nil END-P argument.
2149
2150 The node traversal is approximately lexical-order, although there
2151 are currently no guarantees around this."
2152 (when node
2153 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2154 ;; visit the node
2155 (when (funcall callback node nil)
2156 ;; visit the kids
2157 (cond
2158 ((eq vfunc 'js2-visit-none)
2159 nil) ; don't even bother calling it
2160 ;; Each AST node type has to define a `js2-visitor' function
2161 ;; that takes a node and a callback, and calls `js2-visit-ast'
2162 ;; on each child of the node.
2163 (vfunc
2164 (funcall vfunc node callback))
2165 (t
2166 (error "%s does not define a visitor-traversal function"
2167 (aref node 0)))))
2168 ;; call the end-visit
2169 (funcall callback node t))))
2170
2171 (defstruct (js2-node
2172 (:constructor nil)) ; abstract
2173 "Base AST node type."
2174 (type -1) ; token type
2175 (pos -1) ; start position of this AST node in parsed input
2176 (len 1) ; num characters spanned by the node
2177 props ; optional node property list (an alist)
2178 parent) ; link to parent node; null for root
2179
2180 (defsubst js2-node-get-prop (node prop &optional default)
2181 (or (cadr (assoc prop (js2-node-props node))) default))
2182
2183 (defsubst js2-node-set-prop (node prop value)
2184 (setf (js2-node-props node)
2185 (cons (list prop value) (js2-node-props node))))
2186
2187 (defun js2-fixup-starts (n nodes)
2188 "Adjust the start positions of NODES to be relative to N.
2189 Any node in the list may be nil, for convenience."
2190 (dolist (node nodes)
2191 (when node
2192 (setf (js2-node-pos node) (- (js2-node-pos node)
2193 (js2-node-pos n))))))
2194
2195 (defun js2-node-add-children (parent &rest nodes)
2196 "Set parent node of NODES to PARENT, and return PARENT.
2197 Does nothing if we're not recording parent links.
2198 If any given node in NODES is nil, doesn't record that link."
2199 (js2-fixup-starts parent nodes)
2200 (dolist (node nodes)
2201 (and node
2202 (setf (js2-node-parent node) parent))))
2203
2204 ;; Non-recursive since it's called a frightening number of times.
2205 (defun js2-node-abs-pos (n)
2206 (let ((pos (js2-node-pos n)))
2207 (while (setq n (js2-node-parent n))
2208 (setq pos (+ pos (js2-node-pos n))))
2209 pos))
2210
2211 (defsubst js2-node-abs-end (n)
2212 "Return absolute buffer position of end of N."
2213 (+ (js2-node-abs-pos n) (js2-node-len n)))
2214
2215 ;; It's important to make sure block nodes have a Lisp list for the
2216 ;; child nodes, to limit printing recursion depth in an AST that
2217 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2218 ;; a sufficiently large vector tree.
2219
2220 (defstruct (js2-block-node
2221 (:include js2-node)
2222 (:constructor nil)
2223 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2224 (pos (js2-current-token-beg))
2225 len
2226 props
2227 kids)))
2228 "A block of statements."
2229 kids) ; a Lisp list of the child statement nodes
2230
2231 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2232 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2233
2234 (defun js2-visit-block (ast callback)
2235 "Visit the `js2-block-node' children of AST."
2236 (dolist (kid (js2-block-node-kids ast))
2237 (js2-visit-ast kid callback)))
2238
2239 (defun js2-print-block (n i)
2240 (let ((pad (js2-make-pad i)))
2241 (insert pad "{\n")
2242 (dolist (kid (js2-block-node-kids n))
2243 (js2-print-ast kid (1+ i)))
2244 (insert pad "}")))
2245
2246 (defstruct (js2-scope
2247 (:include js2-block-node)
2248 (:constructor nil)
2249 (:constructor make-js2-scope (&key (type js2-BLOCK)
2250 (pos (js2-current-token-beg))
2251 len
2252 kids)))
2253 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2254 ;; I don't have one of those handy, so I'll use an alist for now.
2255 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2256 ;; and is much lighter-weight to construct (both CPU and mem).
2257 ;; The keys are interned strings (symbols) for faster lookup.
2258 ;; Should switch to hybrid alist/hashtable eventually.
2259 symbol-table ; an alist of (symbol . js2-symbol)
2260 parent-scope ; a `js2-scope'
2261 top) ; top-level `js2-scope' (script/function)
2262
2263 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2264 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2265
2266 (defun js2-node-get-enclosing-scope (node)
2267 "Return the innermost `js2-scope' node surrounding NODE.
2268 Returns nil if there is no enclosing scope node."
2269 (let ((parent (js2-node-parent node)))
2270 (while (not (js2-scope-p parent))
2271 (setq parent (js2-node-parent parent)))
2272 parent))
2273
2274 (defun js2-get-defining-scope (scope name)
2275 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2276 Returns `js2-scope' in which NAME is defined, or nil if not found."
2277 (let ((sym (if (symbolp name)
2278 name
2279 (intern name)))
2280 table
2281 result
2282 (continue t))
2283 (while (and scope continue)
2284 (if (and (setq table (js2-scope-symbol-table scope))
2285 (assq sym table))
2286 (setq continue nil
2287 result scope)
2288 (setq scope (js2-scope-parent-scope scope))))
2289 result))
2290
2291 (defun js2-scope-get-symbol (scope name)
2292 "Return symbol table entry for NAME in SCOPE.
2293 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2294 (and (js2-scope-symbol-table scope)
2295 (cdr (assq (if (symbolp name)
2296 name
2297 (intern name))
2298 (js2-scope-symbol-table scope)))))
2299
2300 (defun js2-scope-put-symbol (scope name symbol)
2301 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2302 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2303 (let* ((table (js2-scope-symbol-table scope))
2304 (sym (if (symbolp name) name (intern name)))
2305 (entry (assq sym table)))
2306 (if entry
2307 (setcdr entry symbol)
2308 (push (cons sym symbol)
2309 (js2-scope-symbol-table scope)))))
2310
2311 (defstruct (js2-symbol
2312 (:constructor nil)
2313 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2314 "A symbol table entry."
2315 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2316 ;; js2-LET, or js2-CONST
2317 decl-type
2318 name ; string
2319 ast-node) ; a `js2-node'
2320
2321 (defstruct (js2-error-node
2322 (:include js2-node)
2323 (:constructor nil) ; silence emacs21 byte-compiler
2324 (:constructor make-js2-error-node (&key (type js2-ERROR)
2325 (pos (js2-current-token-beg))
2326 len)))
2327 "AST node representing a parse error.")
2328
2329 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2330 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2331
2332 (defstruct (js2-script-node
2333 (:include js2-scope)
2334 (:constructor nil)
2335 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2336 (pos (js2-current-token-beg))
2337 len
2338 ;; FIXME: What are those?
2339 var-decls
2340 fun-decls)))
2341 functions ; Lisp list of nested functions
2342 regexps ; Lisp list of (string . flags)
2343 symbols ; alist (every symbol gets unique index)
2344 (param-count 0)
2345 var-names ; vector of string names
2346 consts ; bool-vector matching var-decls
2347 (temp-number 0)) ; for generating temp variables
2348
2349 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2350 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2351
2352 (defun js2-print-script (node indent)
2353 (dolist (kid (js2-block-node-kids node))
2354 (js2-print-ast kid indent)))
2355
2356 (defstruct (js2-ast-root
2357 (:include js2-script-node)
2358 (:constructor nil)
2359 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2360 (pos (js2-current-token-beg))
2361 len
2362 buffer)))
2363 "The root node of a js2 AST."
2364 buffer ; the source buffer from which the code was parsed
2365 comments ; a Lisp list of comments, ordered by start position
2366 errors ; a Lisp list of errors found during parsing
2367 warnings ; a Lisp list of warnings found during parsing
2368 node-count) ; number of nodes in the tree, including the root
2369
2370 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2371 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2372
2373 (defun js2-visit-ast-root (ast callback)
2374 (dolist (kid (js2-ast-root-kids ast))
2375 (js2-visit-ast kid callback))
2376 (dolist (comment (js2-ast-root-comments ast))
2377 (js2-visit-ast comment callback)))
2378
2379 (defstruct (js2-comment-node
2380 (:include js2-node)
2381 (:constructor nil)
2382 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2383 (pos (js2-current-token-beg))
2384 len
2385 format)))
2386 format) ; 'line, 'block, 'jsdoc or 'html
2387
2388 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2389 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2390
2391 (defun js2-print-comment (n i)
2392 ;; We really ought to link end-of-line comments to their nodes.
2393 ;; Or maybe we could add a new comment type, 'endline.
2394 (insert (js2-make-pad i)
2395 (js2-node-string n)))
2396
2397 (defstruct (js2-expr-stmt-node
2398 (:include js2-node)
2399 (:constructor nil)
2400 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2401 (pos js2-ts-cursor)
2402 len
2403 expr)))
2404 "An expression statement."
2405 expr)
2406
2407 (defsubst js2-expr-stmt-node-set-has-result (node)
2408 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2409 (setf (js2-node-type node) js2-EXPR_RESULT))
2410
2411 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2412 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2413
2414 (defun js2-visit-expr-stmt-node (n v)
2415 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2416
2417 (defun js2-print-expr-stmt-node (n indent)
2418 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2419 (insert ";\n"))
2420
2421 (defstruct (js2-loop-node
2422 (:include js2-scope)
2423 (:constructor nil))
2424 "Abstract supertype of loop nodes."
2425 body ; a `js2-block-node'
2426 lp ; position of left-paren, nil if omitted
2427 rp) ; position of right-paren, nil if omitted
2428
2429 (defstruct (js2-do-node
2430 (:include js2-loop-node)
2431 (:constructor nil)
2432 (:constructor make-js2-do-node (&key (type js2-DO)
2433 (pos (js2-current-token-beg))
2434 len
2435 body
2436 condition
2437 while-pos
2438 lp
2439 rp)))
2440 "AST node for do-loop."
2441 condition ; while (expression)
2442 while-pos) ; buffer position of 'while' keyword
2443
2444 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2445 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2446
2447 (defun js2-visit-do-node (n v)
2448 (js2-visit-ast (js2-do-node-body n) v)
2449 (js2-visit-ast (js2-do-node-condition n) v))
2450
2451 (defun js2-print-do-node (n i)
2452 (let ((pad (js2-make-pad i)))
2453 (insert pad "do {\n")
2454 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2455 (js2-print-ast kid (1+ i)))
2456 (insert pad "} while (")
2457 (js2-print-ast (js2-do-node-condition n) 0)
2458 (insert ");\n")))
2459
2460 (defstruct (js2-while-node
2461 (:include js2-loop-node)
2462 (:constructor nil)
2463 (:constructor make-js2-while-node (&key (type js2-WHILE)
2464 (pos (js2-current-token-beg))
2465 len body
2466 condition lp
2467 rp)))
2468 "AST node for while-loop."
2469 condition) ; while-condition
2470
2471 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2472 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2473
2474 (defun js2-visit-while-node (n v)
2475 (js2-visit-ast (js2-while-node-condition n) v)
2476 (js2-visit-ast (js2-while-node-body n) v))
2477
2478 (defun js2-print-while-node (n i)
2479 (let ((pad (js2-make-pad i)))
2480 (insert pad "while (")
2481 (js2-print-ast (js2-while-node-condition n) 0)
2482 (insert ") {\n")
2483 (js2-print-body (js2-while-node-body n) (1+ i))
2484 (insert pad "}\n")))
2485
2486 (defstruct (js2-for-node
2487 (:include js2-loop-node)
2488 (:constructor nil)
2489 (:constructor make-js2-for-node (&key (type js2-FOR)
2490 (pos js2-ts-cursor)
2491 len body init
2492 condition
2493 update lp rp)))
2494 "AST node for a C-style for-loop."
2495 init ; initialization expression
2496 condition ; loop condition
2497 update) ; update clause
2498
2499 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2500 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2501
2502 (defun js2-visit-for-node (n v)
2503 (js2-visit-ast (js2-for-node-init n) v)
2504 (js2-visit-ast (js2-for-node-condition n) v)
2505 (js2-visit-ast (js2-for-node-update n) v)
2506 (js2-visit-ast (js2-for-node-body n) v))
2507
2508 (defun js2-print-for-node (n i)
2509 (let ((pad (js2-make-pad i)))
2510 (insert pad "for (")
2511 (js2-print-ast (js2-for-node-init n) 0)
2512 (insert "; ")
2513 (js2-print-ast (js2-for-node-condition n) 0)
2514 (insert "; ")
2515 (js2-print-ast (js2-for-node-update n) 0)
2516 (insert ") {\n")
2517 (js2-print-body (js2-for-node-body n) (1+ i))
2518 (insert pad "}\n")))
2519
2520 (defstruct (js2-for-in-node
2521 (:include js2-loop-node)
2522 (:constructor nil)
2523 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2524 (pos js2-ts-cursor)
2525 len body
2526 iterator
2527 object
2528 in-pos
2529 each-pos
2530 foreach-p forof-p
2531 lp rp)))
2532 "AST node for a for..in loop."
2533 iterator ; [var] foo in ...
2534 object ; object over which we're iterating
2535 in-pos ; buffer position of 'in' keyword
2536 each-pos ; buffer position of 'each' keyword, if foreach-p
2537 foreach-p ; t if it's a for-each loop
2538 forof-p) ; t if it's a for-of loop
2539
2540 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2541 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2542
2543 (defun js2-visit-for-in-node (n v)
2544 (js2-visit-ast (js2-for-in-node-iterator n) v)
2545 (js2-visit-ast (js2-for-in-node-object n) v)
2546 (js2-visit-ast (js2-for-in-node-body n) v))
2547
2548 (defun js2-print-for-in-node (n i)
2549 (let ((pad (js2-make-pad i))
2550 (foreach (js2-for-in-node-foreach-p n))
2551 (forof (js2-for-in-node-forof-p n)))
2552 (insert pad "for ")
2553 (if foreach
2554 (insert "each "))
2555 (insert "(")
2556 (js2-print-ast (js2-for-in-node-iterator n) 0)
2557 (insert (if forof " of " " in "))
2558 (js2-print-ast (js2-for-in-node-object n) 0)
2559 (insert ") {\n")
2560 (js2-print-body (js2-for-in-node-body n) (1+ i))
2561 (insert pad "}\n")))
2562
2563 (defstruct (js2-return-node
2564 (:include js2-node)
2565 (:constructor nil)
2566 (:constructor make-js2-return-node (&key (type js2-RETURN)
2567 (pos js2-ts-cursor)
2568 len
2569 retval)))
2570 "AST node for a return statement."
2571 retval) ; expression to return, or 'undefined
2572
2573 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2574 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2575
2576 (defun js2-visit-return-node (n v)
2577 (js2-visit-ast (js2-return-node-retval n) v))
2578
2579 (defun js2-print-return-node (n i)
2580 (insert (js2-make-pad i) "return")
2581 (when (js2-return-node-retval n)
2582 (insert " ")
2583 (js2-print-ast (js2-return-node-retval n) 0))
2584 (insert ";\n"))
2585
2586 (defstruct (js2-if-node
2587 (:include js2-node)
2588 (:constructor nil)
2589 (:constructor make-js2-if-node (&key (type js2-IF)
2590 (pos js2-ts-cursor)
2591 len condition
2592 then-part
2593 else-pos
2594 else-part lp
2595 rp)))
2596 "AST node for an if-statement."
2597 condition ; expression
2598 then-part ; statement or block
2599 else-pos ; optional buffer position of 'else' keyword
2600 else-part ; optional statement or block
2601 lp ; position of left-paren, nil if omitted
2602 rp) ; position of right-paren, nil if omitted
2603
2604 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2605 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2606
2607 (defun js2-visit-if-node (n v)
2608 (js2-visit-ast (js2-if-node-condition n) v)
2609 (js2-visit-ast (js2-if-node-then-part n) v)
2610 (js2-visit-ast (js2-if-node-else-part n) v))
2611
2612 (defun js2-print-if-node (n i)
2613 (let ((pad (js2-make-pad i))
2614 (then-part (js2-if-node-then-part n))
2615 (else-part (js2-if-node-else-part n)))
2616 (insert pad "if (")
2617 (js2-print-ast (js2-if-node-condition n) 0)
2618 (insert ") {\n")
2619 (js2-print-body then-part (1+ i))
2620 (insert pad "}")
2621 (cond
2622 ((not else-part)
2623 (insert "\n"))
2624 ((js2-if-node-p else-part)
2625 (insert " else ")
2626 (js2-print-body else-part i))
2627 (t
2628 (insert " else {\n")
2629 (js2-print-body else-part (1+ i))
2630 (insert pad "}\n")))))
2631
2632 (defstruct (js2-try-node
2633 (:include js2-node)
2634 (:constructor nil)
2635 (:constructor make-js2-try-node (&key (type js2-TRY)
2636 (pos js2-ts-cursor)
2637 len
2638 try-block
2639 catch-clauses
2640 finally-block)))
2641 "AST node for a try-statement."
2642 try-block
2643 catch-clauses ; a Lisp list of `js2-catch-node'
2644 finally-block) ; a `js2-finally-node'
2645
2646 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2647 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2648
2649 (defun js2-visit-try-node (n v)
2650 (js2-visit-ast (js2-try-node-try-block n) v)
2651 (dolist (clause (js2-try-node-catch-clauses n))
2652 (js2-visit-ast clause v))
2653 (js2-visit-ast (js2-try-node-finally-block n) v))
2654
2655 (defun js2-print-try-node (n i)
2656 (let ((pad (js2-make-pad i))
2657 (catches (js2-try-node-catch-clauses n))
2658 (finally (js2-try-node-finally-block n)))
2659 (insert pad "try {\n")
2660 (js2-print-body (js2-try-node-try-block n) (1+ i))
2661 (insert pad "}")
2662 (when catches
2663 (dolist (catch catches)
2664 (js2-print-ast catch i)))
2665 (if finally
2666 (js2-print-ast finally i)
2667 (insert "\n"))))
2668
2669 (defstruct (js2-catch-node
2670 (:include js2-node)
2671 (:constructor nil)
2672 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2673 (pos js2-ts-cursor)
2674 len
2675 param
2676 guard-kwd
2677 guard-expr
2678 block lp
2679 rp)))
2680 "AST node for a catch clause."
2681 param ; destructuring form or simple name node
2682 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2683 guard-expr ; catch condition, a `js2-node'
2684 block ; statements, a `js2-block-node'
2685 lp ; buffer position of left-paren, nil if omitted
2686 rp) ; buffer position of right-paren, nil if omitted
2687
2688 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2689 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2690
2691 (defun js2-visit-catch-node (n v)
2692 (js2-visit-ast (js2-catch-node-param n) v)
2693 (when (js2-catch-node-guard-kwd n)
2694 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2695 (js2-visit-ast (js2-catch-node-block n) v))
2696
2697 (defun js2-print-catch-node (n i)
2698 (let ((pad (js2-make-pad i))
2699 (guard-kwd (js2-catch-node-guard-kwd n))
2700 (guard-expr (js2-catch-node-guard-expr n)))
2701 (insert " catch (")
2702 (js2-print-ast (js2-catch-node-param n) 0)
2703 (when guard-kwd
2704 (insert " if ")
2705 (js2-print-ast guard-expr 0))
2706 (insert ") {\n")
2707 (js2-print-body (js2-catch-node-block n) (1+ i))
2708 (insert pad "}")))
2709
2710 (defstruct (js2-finally-node
2711 (:include js2-node)
2712 (:constructor nil)
2713 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2714 (pos js2-ts-cursor)
2715 len body)))
2716 "AST node for a finally clause."
2717 body) ; a `js2-node', often but not always a block node
2718
2719 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2720 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2721
2722 (defun js2-visit-finally-node (n v)
2723 (js2-visit-ast (js2-finally-node-body n) v))
2724
2725 (defun js2-print-finally-node (n i)
2726 (let ((pad (js2-make-pad i)))
2727 (insert " finally {\n")
2728 (js2-print-body (js2-finally-node-body n) (1+ i))
2729 (insert pad "}\n")))
2730
2731 (defstruct (js2-switch-node
2732 (:include js2-node)
2733 (:constructor nil)
2734 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2735 (pos js2-ts-cursor)
2736 len
2737 discriminant
2738 cases lp
2739 rp)))
2740 "AST node for a switch statement."
2741 discriminant ; a `js2-node' (switch expression)
2742 cases ; a Lisp list of `js2-case-node'
2743 lp ; position of open-paren for discriminant, nil if omitted
2744 rp) ; position of close-paren for discriminant, nil if omitted
2745
2746 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2747 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2748
2749 (defun js2-visit-switch-node (n v)
2750 (js2-visit-ast (js2-switch-node-discriminant n) v)
2751 (dolist (c (js2-switch-node-cases n))
2752 (js2-visit-ast c v)))
2753
2754 (defun js2-print-switch-node (n i)
2755 (let ((pad (js2-make-pad i))
2756 (cases (js2-switch-node-cases n)))
2757 (insert pad "switch (")
2758 (js2-print-ast (js2-switch-node-discriminant n) 0)
2759 (insert ") {\n")
2760 (dolist (case cases)
2761 (js2-print-ast case i))
2762 (insert pad "}\n")))
2763
2764 (defstruct (js2-case-node
2765 (:include js2-block-node)
2766 (:constructor nil)
2767 (:constructor make-js2-case-node (&key (type js2-CASE)
2768 (pos js2-ts-cursor)
2769 len kids expr)))
2770 "AST node for a case clause of a switch statement."
2771 expr) ; the case expression (nil for default)
2772
2773 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2774 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2775
2776 (defun js2-visit-case-node (n v)
2777 (js2-visit-ast (js2-case-node-expr n) v)
2778 (js2-visit-block n v))
2779
2780 (defun js2-print-case-node (n i)
2781 (let ((pad (js2-make-pad i))
2782 (expr (js2-case-node-expr n)))
2783 (insert pad)
2784 (if (null expr)
2785 (insert "default:\n")
2786 (insert "case ")
2787 (js2-print-ast expr 0)
2788 (insert ":\n"))
2789 (dolist (kid (js2-case-node-kids n))
2790 (js2-print-ast kid (1+ i)))))
2791
2792 (defstruct (js2-throw-node
2793 (:include js2-node)
2794 (:constructor nil)
2795 (:constructor make-js2-throw-node (&key (type js2-THROW)
2796 (pos js2-ts-cursor)
2797 len expr)))
2798 "AST node for a throw statement."
2799 expr) ; the expression to throw
2800
2801 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2802 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2803
2804 (defun js2-visit-throw-node (n v)
2805 (js2-visit-ast (js2-throw-node-expr n) v))
2806
2807 (defun js2-print-throw-node (n i)
2808 (insert (js2-make-pad i) "throw ")
2809 (js2-print-ast (js2-throw-node-expr n) 0)
2810 (insert ";\n"))
2811
2812 (defstruct (js2-with-node
2813 (:include js2-node)
2814 (:constructor nil)
2815 (:constructor make-js2-with-node (&key (type js2-WITH)
2816 (pos js2-ts-cursor)
2817 len object
2818 body lp rp)))
2819 "AST node for a with-statement."
2820 object
2821 body
2822 lp ; buffer position of left-paren around object, nil if omitted
2823 rp) ; buffer position of right-paren around object, nil if omitted
2824
2825 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2826 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2827
2828 (defun js2-visit-with-node (n v)
2829 (js2-visit-ast (js2-with-node-object n) v)
2830 (js2-visit-ast (js2-with-node-body n) v))
2831
2832 (defun js2-print-with-node (n i)
2833 (let ((pad (js2-make-pad i)))
2834 (insert pad "with (")
2835 (js2-print-ast (js2-with-node-object n) 0)
2836 (insert ") {\n")
2837 (js2-print-body (js2-with-node-body n) (1+ i))
2838 (insert pad "}\n")))
2839
2840 (defstruct (js2-label-node
2841 (:include js2-node)
2842 (:constructor nil)
2843 (:constructor make-js2-label-node (&key (type js2-LABEL)
2844 (pos js2-ts-cursor)
2845 len name)))
2846 "AST node for a statement label or case label."
2847 name ; a string
2848 loop) ; for validating and code-generating continue-to-label
2849
2850 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2851 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2852
2853 (defun js2-print-label (n i)
2854 (insert (js2-make-pad i)
2855 (js2-label-node-name n)
2856 ":\n"))
2857
2858 (defstruct (js2-labeled-stmt-node
2859 (:include js2-node)
2860 (:constructor nil)
2861 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2862 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2863 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2864 (pos js2-ts-cursor)
2865 len labels stmt)))
2866 "AST node for a statement with one or more labels.
2867 Multiple labels for a statement are collapsed into the labels field."
2868 labels ; Lisp list of `js2-label-node'
2869 stmt) ; the statement these labels are for
2870
2871 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2872 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2873
2874 (defun js2-get-label-by-name (lbl-stmt name)
2875 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2876 Returns nil if no such label is in the list."
2877 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2878 result)
2879 (while (and label-list (not result))
2880 (if (string= (js2-label-node-name (car label-list)) name)
2881 (setq result (car label-list))
2882 (setq label-list (cdr label-list))))
2883 result))
2884
2885 (defun js2-visit-labeled-stmt (n v)
2886 (dolist (label (js2-labeled-stmt-node-labels n))
2887 (js2-visit-ast label v))
2888 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2889
2890 (defun js2-print-labeled-stmt (n i)
2891 (dolist (label (js2-labeled-stmt-node-labels n))
2892 (js2-print-ast label i))
2893 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
2894
2895 (defun js2-labeled-stmt-node-contains (node label)
2896 "Return t if NODE contains LABEL in its label set.
2897 NODE is a `js2-labels-node'. LABEL is an identifier."
2898 (loop for nl in (js2-labeled-stmt-node-labels node)
2899 if (string= label (js2-label-node-name nl))
2900 return t
2901 finally return nil))
2902
2903 (defsubst js2-labeled-stmt-node-add-label (node label)
2904 "Add a `js2-label-node' to the label set for this statement."
2905 (setf (js2-labeled-stmt-node-labels node)
2906 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2907
2908 (defstruct (js2-jump-node
2909 (:include js2-node)
2910 (:constructor nil))
2911 "Abstract supertype of break and continue nodes."
2912 label ; `js2-name-node' for location of label identifier, if present
2913 target) ; target js2-labels-node or loop/switch statement
2914
2915 (defun js2-visit-jump-node (n v)
2916 ;; We don't visit the target, since it's a back-link.
2917 (js2-visit-ast (js2-jump-node-label n) v))
2918
2919 (defstruct (js2-break-node
2920 (:include js2-jump-node)
2921 (:constructor nil)
2922 (:constructor make-js2-break-node (&key (type js2-BREAK)
2923 (pos js2-ts-cursor)
2924 len label target)))
2925 "AST node for a break statement.
2926 The label field is a `js2-name-node', possibly nil, for the named label
2927 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2928 is the target of the break - a label node or enclosing loop/switch statement.")
2929
2930 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2931 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2932
2933 (defun js2-print-break-node (n i)
2934 (insert (js2-make-pad i) "break")
2935 (when (js2-break-node-label n)
2936 (insert " ")
2937 (js2-print-ast (js2-break-node-label n) 0))
2938 (insert ";\n"))
2939
2940 (defstruct (js2-continue-node
2941 (:include js2-jump-node)
2942 (:constructor nil)
2943 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2944 (pos js2-ts-cursor)
2945 len label target)))
2946 "AST node for a continue statement.
2947 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2948 It is nil if continue specifies no label. The target field is the jump target:
2949 a `js2-label-node' or the innermost enclosing loop.")
2950
2951 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2952 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2953
2954 (defun js2-print-continue-node (n i)
2955 (insert (js2-make-pad i) "continue")
2956 (when (js2-continue-node-label n)
2957 (insert " ")
2958 (js2-print-ast (js2-continue-node-label n) 0))
2959 (insert ";\n"))
2960
2961 (defstruct (js2-function-node
2962 (:include js2-script-node)
2963 (:constructor nil)
2964 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2965 (pos js2-ts-cursor)
2966 len
2967 (ftype 'FUNCTION)
2968 (form 'FUNCTION_STATEMENT)
2969 (name "")
2970 params rest-p
2971 body
2972 generator-type
2973 lp rp)))
2974 "AST node for a function declaration.
2975 The `params' field is a Lisp list of nodes. Each node is either a simple
2976 `js2-name-node', or if it's a destructuring-assignment parameter, a
2977 `js2-array-node' or `js2-object-node'."
2978 ftype ; FUNCTION, GETTER or SETTER
2979 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
2980 name ; function name (a `js2-name-node', or nil if anonymous)
2981 params ; a Lisp list of destructuring forms or simple name nodes
2982 rest-p ; if t, the last parameter is rest parameter
2983 body ; a `js2-block-node' or expression node (1.8 only)
2984 lp ; position of arg-list open-paren, or nil if omitted
2985 rp ; position of arg-list close-paren, or nil if omitted
2986 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2987 needs-activation ; t if we need an activation object for this frame
2988 generator-type ; STAR, LEGACY, COMPREHENSION or nil
2989 member-expr) ; nonstandard Ecma extension from Rhino
2990
2991 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2992 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2993
2994 (defun js2-visit-function-node (n v)
2995 (js2-visit-ast (js2-function-node-name n) v)
2996 (dolist (p (js2-function-node-params n))
2997 (js2-visit-ast p v))
2998 (js2-visit-ast (js2-function-node-body n) v))
2999
3000 (defun js2-print-function-node (n i)
3001 (let* ((pad (js2-make-pad i))
3002 (getter (js2-node-get-prop n 'GETTER_SETTER))
3003 (name (or (js2-function-node-name n)
3004 (js2-function-node-member-expr n)))
3005 (params (js2-function-node-params n))
3006 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3007 (rest-p (js2-function-node-rest-p n))
3008 (body (js2-function-node-body n))
3009 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3010 (unless (or getter arrow)
3011 (insert pad "function")
3012 (when (eq (js2-function-node-generator-type n) 'STAR)
3013 (insert "*")))
3014 (when name
3015 (insert " ")
3016 (js2-print-ast name 0))
3017 (insert "(")
3018 (loop with len = (length params)
3019 for param in params
3020 for count from 1
3021 do
3022 (when (and rest-p (= count len))
3023 (insert "..."))
3024 (js2-print-ast param 0)
3025 (when (< count len)
3026 (insert ", ")))
3027 (insert ") ")
3028 (when arrow
3029 (insert "=> "))
3030 (insert "{")
3031 ;; TODO: fix this to be smarter about indenting, etc.
3032 (unless expr
3033 (insert "\n"))
3034 (if (js2-block-node-p body)
3035 (js2-print-body body (1+ i))
3036 (js2-print-ast body 0))
3037 (insert pad "}")
3038 (unless expr
3039 (insert "\n"))))
3040
3041 (defun js2-function-name (node)
3042 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3043 (and (js2-function-node-name node)
3044 (js2-name-node-name (js2-function-node-name node))))
3045
3046 ;; Having this be an expression node makes it more flexible.
3047 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3048 ;; that work better if you assume it's an expression. Whenever we have
3049 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3050 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3051 (defstruct (js2-var-decl-node
3052 (:include js2-node)
3053 (:constructor nil)
3054 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3055 (pos (js2-current-token-beg))
3056 len kids
3057 decl-type)))
3058 "AST node for a variable declaration list (VAR, CONST or LET).
3059 The node bounds differ depending on the declaration type. For VAR or
3060 CONST declarations, the bounds include the var/const keyword. For LET
3061 declarations, the node begins at the position of the first child."
3062 kids ; a Lisp list of `js2-var-init-node' structs.
3063 decl-type) ; js2-VAR, js2-CONST or js2-LET
3064
3065 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3066 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3067
3068 (defun js2-visit-var-decl (n v)
3069 (dolist (kid (js2-var-decl-node-kids n))
3070 (js2-visit-ast kid v)))
3071
3072 (defun js2-print-var-decl (n i)
3073 (let ((pad (js2-make-pad i))
3074 (tt (js2-var-decl-node-decl-type n)))
3075 (insert pad)
3076 (insert (cond
3077 ((= tt js2-VAR) "var ")
3078 ((= tt js2-LET) "let ")
3079 ((= tt js2-CONST) "const ")
3080 (t
3081 (error "malformed var-decl node"))))
3082 (loop with kids = (js2-var-decl-node-kids n)
3083 with len = (length kids)
3084 for kid in kids
3085 for count from 1
3086 do
3087 (js2-print-ast kid 0)
3088 (if (< count len)
3089 (insert ", ")))))
3090
3091 (defstruct (js2-var-init-node
3092 (:include js2-node)
3093 (:constructor nil)
3094 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3095 (pos js2-ts-cursor)
3096 len target
3097 initializer)))
3098 "AST node for a variable declaration.
3099 The type field will be js2-CONST for a const decl."
3100 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3101 initializer) ; initializer expression, a `js2-node'
3102
3103 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3104 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3105
3106 (defun js2-visit-var-init-node (n v)
3107 (js2-visit-ast (js2-var-init-node-target n) v)
3108 (js2-visit-ast (js2-var-init-node-initializer n) v))
3109
3110 (defun js2-print-var-init-node (n i)
3111 (let ((pad (js2-make-pad i))
3112 (name (js2-var-init-node-target n))
3113 (init (js2-var-init-node-initializer n)))
3114 (insert pad)
3115 (js2-print-ast name 0)
3116 (when init
3117 (insert " = ")
3118 (js2-print-ast init 0))))
3119
3120 (defstruct (js2-cond-node
3121 (:include js2-node)
3122 (:constructor nil)
3123 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3124 (pos js2-ts-cursor)
3125 len
3126 test-expr
3127 true-expr
3128 false-expr
3129 q-pos c-pos)))
3130 "AST node for the ternary operator"
3131 test-expr
3132 true-expr
3133 false-expr
3134 q-pos ; buffer position of ?
3135 c-pos) ; buffer position of :
3136
3137 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3138 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3139
3140 (defun js2-visit-cond-node (n v)
3141 (js2-visit-ast (js2-cond-node-test-expr n) v)
3142 (js2-visit-ast (js2-cond-node-true-expr n) v)
3143 (js2-visit-ast (js2-cond-node-false-expr n) v))
3144
3145 (defun js2-print-cond-node (n i)
3146 (let ((pad (js2-make-pad i)))
3147 (insert pad)
3148 (js2-print-ast (js2-cond-node-test-expr n) 0)
3149 (insert " ? ")
3150 (js2-print-ast (js2-cond-node-true-expr n) 0)
3151 (insert " : ")
3152 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3153
3154 (defstruct (js2-infix-node
3155 (:include js2-node)
3156 (:constructor nil)
3157 (:constructor make-js2-infix-node (&key type
3158 (pos js2-ts-cursor)
3159 len op-pos
3160 left right)))
3161 "Represents infix expressions.
3162 Includes assignment ops like `|=', and the comma operator.
3163 The type field inherited from `js2-node' holds the operator."
3164 op-pos ; buffer position where operator begins
3165 left ; any `js2-node'
3166 right) ; any `js2-node'
3167
3168 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3169 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3170
3171 (defun js2-visit-infix-node (n v)
3172 (js2-visit-ast (js2-infix-node-left n) v)
3173 (js2-visit-ast (js2-infix-node-right n) v))
3174
3175 (defconst js2-operator-tokens
3176 (let ((table (make-hash-table :test 'eq))
3177 (tokens
3178 (list (cons js2-IN "in")
3179 (cons js2-TYPEOF "typeof")
3180 (cons js2-INSTANCEOF "instanceof")
3181 (cons js2-DELPROP "delete")
3182 (cons js2-COMMA ",")
3183 (cons js2-COLON ":")
3184 (cons js2-OR "||")
3185 (cons js2-AND "&&")
3186 (cons js2-INC "++")
3187 (cons js2-DEC "--")
3188 (cons js2-BITOR "|")
3189 (cons js2-BITXOR "^")
3190 (cons js2-BITAND "&")
3191 (cons js2-EQ "==")
3192 (cons js2-NE "!=")
3193 (cons js2-LT "<")
3194 (cons js2-LE "<=")
3195 (cons js2-GT ">")
3196 (cons js2-GE ">=")
3197 (cons js2-LSH "<<")
3198 (cons js2-RSH ">>")
3199 (cons js2-URSH ">>>")
3200 (cons js2-ADD "+") ; infix plus
3201 (cons js2-SUB "-") ; infix minus
3202 (cons js2-MUL "*")
3203 (cons js2-DIV "/")
3204 (cons js2-MOD "%")
3205 (cons js2-NOT "!")
3206 (cons js2-BITNOT "~")
3207 (cons js2-POS "+") ; unary plus
3208 (cons js2-NEG "-") ; unary minus
3209 (cons js2-TRIPLEDOT "...")
3210 (cons js2-SHEQ "===") ; shallow equality
3211 (cons js2-SHNE "!==") ; shallow inequality
3212 (cons js2-ASSIGN "=")
3213 (cons js2-ASSIGN_BITOR "|=")
3214 (cons js2-ASSIGN_BITXOR "^=")
3215 (cons js2-ASSIGN_BITAND "&=")
3216 (cons js2-ASSIGN_LSH "<<=")
3217 (cons js2-ASSIGN_RSH ">>=")
3218 (cons js2-ASSIGN_URSH ">>>=")
3219 (cons js2-ASSIGN_ADD "+=")
3220 (cons js2-ASSIGN_SUB "-=")
3221 (cons js2-ASSIGN_MUL "*=")
3222 (cons js2-ASSIGN_DIV "/=")
3223 (cons js2-ASSIGN_MOD "%="))))
3224 (loop for (k . v) in tokens do
3225 (puthash k v table))
3226 table))
3227
3228 (defun js2-print-infix-node (n i)
3229 (let* ((tt (js2-node-type n))
3230 (op (gethash tt js2-operator-tokens)))
3231 (unless op
3232 (error "unrecognized infix operator %s" (js2-node-type n)))
3233 (insert (js2-make-pad i))
3234 (js2-print-ast (js2-infix-node-left n) 0)
3235 (unless (= tt js2-COMMA)
3236 (insert " "))
3237 (insert op)
3238 (insert " ")
3239 (js2-print-ast (js2-infix-node-right n) 0)))
3240
3241 (defstruct (js2-assign-node
3242 (:include js2-infix-node)
3243 (:constructor nil)
3244 (:constructor make-js2-assign-node (&key type
3245 (pos js2-ts-cursor)
3246 len op-pos
3247 left right)))
3248 "Represents any assignment.
3249 The type field holds the actual assignment operator.")
3250
3251 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3252 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3253
3254 (defstruct (js2-unary-node
3255 (:include js2-node)
3256 (:constructor nil)
3257 (:constructor make-js2-unary-node (&key type ; required
3258 (pos js2-ts-cursor)
3259 len operand)))
3260 "AST node type for unary operator nodes.
3261 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3262 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3263 property is added if the operator follows the operand."
3264 operand) ; a `js2-node' expression
3265
3266 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3267 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3268
3269 (defun js2-visit-unary-node (n v)
3270 (js2-visit-ast (js2-unary-node-operand n) v))
3271
3272 (defun js2-print-unary-node (n i)
3273 (let* ((tt (js2-node-type n))
3274 (op (gethash tt js2-operator-tokens))
3275 (postfix (js2-node-get-prop n 'postfix)))
3276 (unless op
3277 (error "unrecognized unary operator %s" tt))
3278 (insert (js2-make-pad i))
3279 (unless postfix
3280 (insert op))
3281 (if (or (= tt js2-TYPEOF)
3282 (= tt js2-DELPROP))
3283 (insert " "))
3284 (js2-print-ast (js2-unary-node-operand n) 0)
3285 (when postfix
3286 (insert op))))
3287
3288 (defstruct (js2-let-node
3289 (:include js2-scope)
3290 (:constructor nil)
3291 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3292 (pos (js2-current-token-beg))
3293 len vars body
3294 lp rp)))
3295 "AST node for a let expression or a let statement.
3296 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3297 vars ; a `js2-var-decl-node'
3298 body ; a `js2-node' representing the expression or body block
3299 lp
3300 rp)
3301
3302 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3303 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3304
3305 (defun js2-visit-let-node (n v)
3306 (js2-visit-ast (js2-let-node-vars n) v)
3307 (js2-visit-ast (js2-let-node-body n) v))
3308
3309 (defun js2-print-let-node (n i)
3310 (insert (js2-make-pad i) "let (")
3311 (let ((p (point)))
3312 (js2-print-ast (js2-let-node-vars n) 0)
3313 (delete-region p (+ p 4)))
3314 (insert ") ")
3315 (js2-print-ast (js2-let-node-body n) i))
3316
3317 (defstruct (js2-keyword-node
3318 (:include js2-node)
3319 (:constructor nil)
3320 (:constructor make-js2-keyword-node (&key type
3321 (pos (js2-current-token-beg))
3322 (len (- js2-ts-cursor pos)))))
3323 "AST node representing a literal keyword such as `null'.
3324 Used for `null', `this', `true', `false' and `debugger'.
3325 The node type is set to js2-NULL, js2-THIS, etc.")
3326
3327 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3328 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3329
3330 (defun js2-print-keyword-node (n i)
3331 (insert (js2-make-pad i)
3332 (let ((tt (js2-node-type n)))
3333 (cond
3334 ((= tt js2-THIS) "this")
3335 ((= tt js2-NULL) "null")
3336 ((= tt js2-TRUE) "true")
3337 ((= tt js2-FALSE) "false")
3338 ((= tt js2-DEBUGGER) "debugger")
3339 (t (error "Invalid keyword literal type: %d" tt))))))
3340
3341 (defsubst js2-this-node-p (node)
3342 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3343 (eq (js2-node-type node) js2-THIS))
3344
3345 (defstruct (js2-new-node
3346 (:include js2-node)
3347 (:constructor nil)
3348 (:constructor make-js2-new-node (&key (type js2-NEW)
3349 (pos (js2-current-token-beg))
3350 len target
3351 args initializer
3352 lp rp)))
3353 "AST node for new-expression such as new Foo()."
3354 target ; an identifier or reference
3355 args ; a Lisp list of argument nodes
3356 lp ; position of left-paren, nil if omitted
3357 rp ; position of right-paren, nil if omitted
3358 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3359
3360 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3361 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3362
3363 (defun js2-visit-new-node (n v)
3364 (js2-visit-ast (js2-new-node-target n) v)
3365 (dolist (arg (js2-new-node-args n))
3366 (js2-visit-ast arg v))
3367 (js2-visit-ast (js2-new-node-initializer n) v))
3368
3369 (defun js2-print-new-node (n i)
3370 (insert (js2-make-pad i) "new ")
3371 (js2-print-ast (js2-new-node-target n))
3372 (insert "(")
3373 (js2-print-list (js2-new-node-args n))
3374 (insert ")")
3375 (when (js2-new-node-initializer n)
3376 (insert " ")
3377 (js2-print-ast (js2-new-node-initializer n))))
3378
3379 (defstruct (js2-name-node
3380 (:include js2-node)
3381 (:constructor nil)
3382 (:constructor make-js2-name-node (&key (type js2-NAME)
3383 (pos (js2-current-token-beg))
3384 (len (- js2-ts-cursor
3385 (js2-current-token-beg)))
3386 (name (js2-current-token-string)))))
3387 "AST node for a JavaScript identifier"
3388 name ; a string
3389 scope) ; a `js2-scope' (optional, used for codegen)
3390
3391 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3392 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3393
3394 (defun js2-print-name-node (n i)
3395 (insert (js2-make-pad i)
3396 (js2-name-node-name n)))
3397
3398 (defsubst js2-name-node-length (node)
3399 "Return identifier length of NODE, a `js2-name-node'.
3400 Returns 0 if NODE is nil or its identifier field is nil."
3401 (if node
3402 (length (js2-name-node-name node))
3403 0))
3404
3405 (defstruct (js2-number-node
3406 (:include js2-node)
3407 (:constructor nil)
3408 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3409 (pos (js2-current-token-beg))
3410 (len (- js2-ts-cursor
3411 (js2-current-token-beg)))
3412 (value (js2-current-token-string))
3413 (num-value (js2-token-number
3414 (js2-current-token))))))
3415 "AST node for a number literal."
3416 value ; the original string, e.g. "6.02e23"
3417 num-value) ; the parsed number value
3418
3419 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3420 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3421
3422 (defun js2-print-number-node (n i)
3423 (insert (js2-make-pad i)
3424 (number-to-string (js2-number-node-num-value n))))
3425
3426 (defstruct (js2-regexp-node
3427 (:include js2-node)
3428 (:constructor nil)
3429 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3430 (pos (js2-current-token-beg))
3431 (len (- js2-ts-cursor
3432 (js2-current-token-beg)))
3433 value flags)))
3434 "AST node for a regular expression literal."
3435 value ; the regexp string, without // delimiters
3436 flags) ; a string of flags, e.g. `mi'.
3437
3438 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3439 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3440
3441 (defun js2-print-regexp (n i)
3442 (insert (js2-make-pad i)
3443 "/"
3444 (js2-regexp-node-value n)
3445 "/")
3446 (if (js2-regexp-node-flags n)
3447 (insert (js2-regexp-node-flags n))))
3448
3449 (defstruct (js2-string-node
3450 (:include js2-node)
3451 (:constructor nil)
3452 (:constructor make-js2-string-node (&key (type js2-STRING)
3453 (pos (js2-current-token-beg))
3454 (len (- js2-ts-cursor
3455 (js2-current-token-beg)))
3456 (value (js2-current-token-string)))))
3457 "String literal.
3458 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3459 You can tell the quote type by looking at the first character."
3460 value) ; the characters of the string, including the quotes
3461
3462 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3463 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3464
3465 (defun js2-print-string-node (n i)
3466 (insert (js2-make-pad i)
3467 (js2-node-string n)))
3468
3469 (defstruct (js2-array-node
3470 (:include js2-node)
3471 (:constructor nil)
3472 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3473 (pos js2-ts-cursor)
3474 len elems)))
3475 "AST node for an array literal."
3476 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3477
3478 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3479 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3480
3481 (defun js2-visit-array-node (n v)
3482 (dolist (e (js2-array-node-elems n))
3483 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3484
3485 (defun js2-print-array-node (n i)
3486 (insert (js2-make-pad i) "[")
3487 (let ((elems (js2-array-node-elems n)))
3488 (js2-print-list elems)
3489 (when (and elems (null (car (last elems))))
3490 (insert ",")))
3491 (insert "]"))
3492
3493 (defstruct (js2-object-node
3494 (:include js2-node)
3495 (:constructor nil)
3496 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3497 (pos js2-ts-cursor)
3498 len
3499 elems)))
3500 "AST node for an object literal expression.
3501 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3502 The latter represents abbreviation in destructuring expressions."
3503 elems)
3504
3505 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3506 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3507
3508 (defun js2-visit-object-node (n v)
3509 (dolist (e (js2-object-node-elems n))
3510 (js2-visit-ast e v)))
3511
3512 (defun js2-print-object-node (n i)
3513 (insert (js2-make-pad i) "{")
3514 (js2-print-list (js2-object-node-elems n))
3515 (insert "}"))
3516
3517 (defstruct (js2-object-prop-node
3518 (:include js2-infix-node)
3519 (:constructor nil)
3520 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3521 (pos js2-ts-cursor)
3522 len left
3523 right op-pos)))
3524 "AST node for an object literal prop:value entry.
3525 The `left' field is the property: a name node, string node or number node.
3526 The `right' field is a `js2-node' representing the initializer value.")
3527
3528 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3529 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3530
3531 (defun js2-print-object-prop-node (n i)
3532 (let* ((left (js2-object-prop-node-left n))
3533 (computed (not (or (js2-string-node-p left)
3534 (js2-number-node-p left)
3535 (js2-name-node-p left)))))
3536 (insert (js2-make-pad i))
3537 (if computed
3538 (insert "["))
3539 (js2-print-ast left 0)
3540 (if computed
3541 (insert "]"))
3542 (if (not (js2-node-get-prop n 'SHORTHAND))
3543 (progn
3544 (insert ": ")
3545 (js2-print-ast (js2-object-prop-node-right n) 0)))))
3546
3547 (defstruct (js2-getter-setter-node
3548 (:include js2-infix-node)
3549 (:constructor nil)
3550 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3551 (pos js2-ts-cursor)
3552 len left right)))
3553 "AST node for a getter/setter property in an object literal.
3554 The `left' field is the `js2-name-node' naming the getter/setter prop.
3555 The `right' field is always an anonymous `js2-function-node' with a node
3556 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3557
3558 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3559 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3560
3561 (defun js2-print-getter-setter (n i)
3562 (let ((pad (js2-make-pad i))
3563 (left (js2-getter-setter-node-left n))
3564 (right (js2-getter-setter-node-right n)))
3565 (insert pad)
3566 (if (/= (js2-node-type n) js2-FUNCTION)
3567 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3568 (js2-print-ast left 0)
3569 (js2-print-ast right 0)))
3570
3571 (defstruct (js2-prop-get-node
3572 (:include js2-infix-node)
3573 (:constructor nil)
3574 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3575 (pos js2-ts-cursor)
3576 len left right)))
3577 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3578
3579 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3580 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3581
3582 (defun js2-visit-prop-get-node (n v)
3583 (js2-visit-ast (js2-prop-get-node-left n) v)
3584 (js2-visit-ast (js2-prop-get-node-right n) v))
3585
3586 (defun js2-print-prop-get-node (n i)
3587 (insert (js2-make-pad i))
3588 (js2-print-ast (js2-prop-get-node-left n) 0)
3589 (insert ".")
3590 (js2-print-ast (js2-prop-get-node-right n) 0))
3591
3592 (defstruct (js2-elem-get-node
3593 (:include js2-node)
3594 (:constructor nil)
3595 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3596 (pos js2-ts-cursor)
3597 len target element
3598 lb rb)))
3599 "AST node for an array index expression such as foo[bar]."
3600 target ; a `js2-node' - the expression preceding the "."
3601 element ; a `js2-node' - the expression in brackets
3602 lb ; position of left-bracket, nil if omitted
3603 rb) ; position of right-bracket, nil if omitted
3604
3605 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3606 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3607
3608 (defun js2-visit-elem-get-node (n v)
3609 (js2-visit-ast (js2-elem-get-node-target n) v)
3610 (js2-visit-ast (js2-elem-get-node-element n) v))
3611
3612 (defun js2-print-elem-get-node (n i)
3613 (insert (js2-make-pad i))
3614 (js2-print-ast (js2-elem-get-node-target n) 0)
3615 (insert "[")
3616 (js2-print-ast (js2-elem-get-node-element n) 0)
3617 (insert "]"))
3618
3619 (defstruct (js2-call-node
3620 (:include js2-node)
3621 (:constructor nil)
3622 (:constructor make-js2-call-node (&key (type js2-CALL)
3623 (pos js2-ts-cursor)
3624 len target args
3625 lp rp)))
3626 "AST node for a JavaScript function call."
3627 target ; a `js2-node' evaluating to the function to call
3628 args ; a Lisp list of `js2-node' arguments
3629 lp ; position of open-paren, or nil if missing
3630 rp) ; position of close-paren, or nil if missing
3631
3632 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3633 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3634
3635 (defun js2-visit-call-node (n v)
3636 (js2-visit-ast (js2-call-node-target n) v)
3637 (dolist (arg (js2-call-node-args n))
3638 (js2-visit-ast arg v)))
3639
3640 (defun js2-print-call-node (n i)
3641 (insert (js2-make-pad i))
3642 (js2-print-ast (js2-call-node-target n) 0)
3643 (insert "(")
3644 (js2-print-list (js2-call-node-args n))
3645 (insert ")"))
3646
3647 (defstruct (js2-yield-node
3648 (:include js2-node)
3649 (:constructor nil)
3650 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3651 (pos js2-ts-cursor)
3652 len value star-p)))
3653 "AST node for yield statement or expression."
3654 star-p ; whether it's yield*
3655 value) ; optional: value to be yielded
3656
3657 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3658 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3659
3660 (defun js2-visit-yield-node (n v)
3661 (js2-visit-ast (js2-yield-node-value n) v))
3662
3663 (defun js2-print-yield-node (n i)
3664 (insert (js2-make-pad i))
3665 (insert "yield")
3666 (when (js2-yield-node-star-p n)
3667 (insert "*"))
3668 (when (js2-yield-node-value n)
3669 (insert " ")
3670 (js2-print-ast (js2-yield-node-value n) 0)))
3671
3672 (defstruct (js2-paren-node
3673 (:include js2-node)
3674 (:constructor nil)
3675 (:constructor make-js2-paren-node (&key (type js2-LP)
3676 (pos js2-ts-cursor)
3677 len expr)))
3678 "AST node for a parenthesized expression.
3679 In particular, used when the parens are syntactically optional,
3680 as opposed to required parens such as those enclosing an if-conditional."
3681 expr) ; `js2-node'
3682
3683 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3684 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3685
3686 (defun js2-visit-paren-node (n v)
3687 (js2-visit-ast (js2-paren-node-expr n) v))
3688
3689 (defun js2-print-paren-node (n i)
3690 (insert (js2-make-pad i))
3691 (insert "(")
3692 (js2-print-ast (js2-paren-node-expr n) 0)
3693 (insert ")"))
3694
3695 (defstruct (js2-comp-node
3696 (:include js2-scope)
3697 (:constructor nil)
3698 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
3699 (pos js2-ts-cursor)
3700 len result
3701 loops filters
3702 form)))
3703 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3704 result ; result expression (just after left-bracket)
3705 loops ; a Lisp list of `js2-comp-loop-node'
3706 filters ; a Lisp list of guard/filter expressions
3707 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
3708 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
3709 )
3710
3711 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
3712 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
3713
3714 (defun js2-visit-comp-node (n v)
3715 (js2-visit-ast (js2-comp-node-result n) v)
3716 (dolist (l (js2-comp-node-loops n))
3717 (js2-visit-ast l v))
3718 (dolist (f (js2-comp-node-filters n))
3719 (js2-visit-ast f v)))
3720
3721 (defun js2-print-comp-node (n i)
3722 (let ((pad (js2-make-pad i))
3723 (result (js2-comp-node-result n))
3724 (loops (js2-comp-node-loops n))
3725 (filters (js2-comp-node-filters n))
3726 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
3727 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
3728 (insert pad (if gen-p "(" "["))
3729 (when legacy-p
3730 (js2-print-ast result 0))
3731 (dolist (l loops)
3732 (when legacy-p
3733 (insert " "))
3734 (js2-print-ast l 0)
3735 (unless legacy-p
3736 (insert " ")))
3737 (dolist (f filters)
3738 (when legacy-p
3739 (insert " "))
3740 (insert "if (")
3741 (js2-print-ast f 0)
3742 (insert ")")
3743 (unless legacy-p
3744 (insert " ")))
3745 (unless legacy-p
3746 (js2-print-ast result 0))
3747 (insert (if gen-p ")" "]"))))
3748
3749 (defstruct (js2-comp-loop-node
3750 (:include js2-for-in-node)
3751 (:constructor nil)
3752 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
3753 (pos js2-ts-cursor)
3754 len iterator
3755 object in-pos
3756 foreach-p
3757 each-pos
3758 forof-p
3759 lp rp)))
3760 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3761
3762 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
3763 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
3764
3765 (defun js2-visit-comp-loop (n v)
3766 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
3767 (js2-visit-ast (js2-comp-loop-node-object n) v))
3768
3769 (defun js2-print-comp-loop (n _i)
3770 (insert "for ")
3771 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
3772 (insert "(")
3773 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
3774 (insert (if (js2-comp-loop-node-forof-p n)
3775 " of " " in "))
3776 (js2-print-ast (js2-comp-loop-node-object n) 0)
3777 (insert ")"))
3778
3779 (defstruct (js2-empty-expr-node
3780 (:include js2-node)
3781 (:constructor nil)
3782 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3783 (pos (js2-current-token-beg))
3784 len)))
3785 "AST node for an empty expression.")
3786
3787 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3788 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3789
3790 (defstruct (js2-xml-node
3791 (:include js2-block-node)
3792 (:constructor nil)
3793 (:constructor make-js2-xml-node (&key (type js2-XML)
3794 (pos (js2-current-token-beg))
3795 len kids)))
3796 "AST node for initial parse of E4X literals.
3797 The kids field is a list of XML fragments, each a `js2-string-node' or
3798 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3799
3800 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3801 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3802
3803 (defun js2-print-xml-node (n i)
3804 (dolist (kid (js2-xml-node-kids n))
3805 (js2-print-ast kid i)))
3806
3807 (defstruct (js2-xml-js-expr-node
3808 (:include js2-xml-node)
3809 (:constructor nil)
3810 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3811 (pos js2-ts-cursor)
3812 len expr)))
3813 "AST node for an embedded JavaScript {expression} in an E4X literal.
3814 The start and end fields correspond to the curly-braces."
3815 expr) ; a `js2-expr-node' of some sort
3816
3817 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3818 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3819
3820 (defun js2-visit-xml-js-expr (n v)
3821 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3822
3823 (defun js2-print-xml-js-expr (n i)
3824 (insert (js2-make-pad i))
3825 (insert "{")
3826 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3827 (insert "}"))
3828
3829 (defstruct (js2-xml-dot-query-node
3830 (:include js2-infix-node)
3831 (:constructor nil)
3832 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3833 (pos js2-ts-cursor)
3834 op-pos len left
3835 right rp)))
3836 "AST node for an E4X foo.(bar) filter expression.
3837 Note that the left-paren is automatically the character immediately
3838 following the dot (.) in the operator. No whitespace is permitted
3839 between the dot and the lp by the scanner."
3840 rp)
3841
3842 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3843 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3844
3845 (defun js2-print-xml-dot-query (n i)
3846 (insert (js2-make-pad i))
3847 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3848 (insert ".(")
3849 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3850 (insert ")"))
3851
3852 (defstruct (js2-xml-ref-node
3853 (:include js2-node)
3854 (:constructor nil)) ; abstract
3855 "Base type for E4X XML attribute-access or property-get expressions.
3856 Such expressions can take a variety of forms. The general syntax has
3857 three parts:
3858
3859 - (optional) an @ (specifying an attribute access)
3860 - (optional) a namespace (a `js2-name-node') and double-colon
3861 - (required) either a `js2-name-node' or a bracketed [expression]
3862
3863 The property-name expressions (examples: ns::name, @name) are
3864 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3865 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3866
3867 This node type (or more specifically, its subclasses) will sometimes
3868 be the right-hand child of a `js2-prop-get-node' or a
3869 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3870 The `js2-xml-ref-node' may also be a standalone primary expression with
3871 no explicit target, which is valid in certain expression contexts such as
3872
3873 company..employee.(@id < 100)
3874
3875 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3876 expression whose parent is a `js2-xml-dot-query-node'."
3877 namespace
3878 at-pos
3879 colon-pos)
3880
3881 (defsubst js2-xml-ref-node-attr-access-p (node)
3882 "Return non-nil if this expression began with an @-token."
3883 (and (numberp (js2-xml-ref-node-at-pos node))
3884 (plusp (js2-xml-ref-node-at-pos node))))
3885
3886 (defstruct (js2-xml-prop-ref-node
3887 (:include js2-xml-ref-node)
3888 (:constructor nil)
3889 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3890 (pos (js2-current-token-beg))
3891 len propname
3892 namespace at-pos
3893 colon-pos)))
3894 "AST node for an E4X XML [expr] property-ref expression.
3895 The JavaScript syntax is an optional @, an optional ns::, and a name.
3896
3897 [ '@' ] [ name '::' ] name
3898
3899 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3900 @ns::*, @*::attr, @*::*, and @*.
3901
3902 The node starts at the @ token, if present. Otherwise it starts at the
3903 namespace name. The node bounds extend through the closing right-bracket,
3904 or if it is missing due to a syntax error, through the end of the index
3905 expression."
3906 propname)
3907
3908 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3909 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3910
3911 (defun js2-visit-xml-prop-ref-node (n v)
3912 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3913 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3914
3915 (defun js2-print-xml-prop-ref-node (n i)
3916 (insert (js2-make-pad i))
3917 (if (js2-xml-ref-node-attr-access-p n)
3918 (insert "@"))
3919 (when (js2-xml-prop-ref-node-namespace n)
3920 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3921 (insert "::"))
3922 (if (js2-xml-prop-ref-node-propname n)
3923 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3924
3925 (defstruct (js2-xml-elem-ref-node
3926 (:include js2-xml-ref-node)
3927 (:constructor nil)
3928 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3929 (pos (js2-current-token-beg))
3930 len expr lb rb
3931 namespace at-pos
3932 colon-pos)))
3933 "AST node for an E4X XML [expr] member-ref expression.
3934 Syntax:
3935
3936 [ '@' ] [ name '::' ] '[' expr ']'
3937
3938 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3939
3940 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3941 is not a legal E4X XML element-ref expression, since it's already used
3942 for standard JavaScript element-get array indexing. Hence, a
3943 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3944 non-nil namespace node, or both.
3945
3946 The node starts at the @ token, if present. Otherwise it starts
3947 at the namespace name. The node bounds extend through the closing
3948 right-bracket, or if it is missing due to a syntax error, through the
3949 end of the index expression."
3950 expr ; the bracketed index expression
3951 lb
3952 rb)
3953
3954 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3955 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3956
3957 (defun js2-visit-xml-elem-ref-node (n v)
3958 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3959 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3960
3961 (defun js2-print-xml-elem-ref-node (n i)
3962 (insert (js2-make-pad i))
3963 (if (js2-xml-ref-node-attr-access-p n)
3964 (insert "@"))
3965 (when (js2-xml-elem-ref-node-namespace n)
3966 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3967 (insert "::"))
3968 (insert "[")
3969 (if (js2-xml-elem-ref-node-expr n)
3970 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3971 (insert "]"))
3972
3973 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3974
3975 (defstruct (js2-xml-start-tag-node
3976 (:include js2-xml-node)
3977 (:constructor nil)
3978 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3979 (pos js2-ts-cursor)
3980 len name attrs kids
3981 empty-p)))
3982 "AST node for an XML start-tag. Not currently used.
3983 The `kids' field is a Lisp list of child content nodes."
3984 name ; a `js2-xml-name-node'
3985 attrs ; a Lisp list of `js2-xml-attr-node'
3986 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3987
3988 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3989 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3990
3991 (defun js2-visit-xml-start-tag (n v)
3992 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3993 (dolist (attr (js2-xml-start-tag-node-attrs n))
3994 (js2-visit-ast attr v))
3995 (js2-visit-block n v))
3996
3997 (defun js2-print-xml-start-tag (n i)
3998 (insert (js2-make-pad i) "<")
3999 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4000 (when (js2-xml-start-tag-node-attrs n)
4001 (insert " ")
4002 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4003 (insert ">"))
4004
4005 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4006 ;; and add the end-tag to the kids list of the parent as well.
4007 (defstruct (js2-xml-end-tag-node
4008 (:include js2-xml-node)
4009 (:constructor nil)
4010 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4011 (pos js2-ts-cursor)
4012 len name)))
4013 "AST node for an XML end-tag. Not currently used."
4014 name) ; a `js2-xml-name-node'
4015
4016 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4017 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4018
4019 (defun js2-visit-xml-end-tag (n v)
4020 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4021
4022 (defun js2-print-xml-end-tag (n i)
4023 (insert (js2-make-pad i))
4024 (insert "</")
4025 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4026 (insert ">"))
4027
4028 (defstruct (js2-xml-name-node
4029 (:include js2-xml-node)
4030 (:constructor nil)
4031 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4032 (pos js2-ts-cursor)
4033 len namespace kids)))
4034 "AST node for an E4X XML name. Not currently used.
4035 Any XML name can be qualified with a namespace, hence the namespace field.
4036 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4037 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4038 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4039 namespace) ; a `js2-string-node'
4040
4041 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4042 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4043
4044 (defun js2-visit-xml-name-node (n v)
4045 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4046
4047 (defun js2-print-xml-name-node (n i)
4048 (insert (js2-make-pad i))
4049 (when (js2-xml-name-node-namespace n)
4050 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4051 (insert "::"))
4052 (dolist (kid (js2-xml-name-node-kids n))
4053 (js2-print-ast kid 0)))
4054
4055 (defstruct (js2-xml-pi-node
4056 (:include js2-xml-node)
4057 (:constructor nil)
4058 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4059 (pos js2-ts-cursor)
4060 len name attrs)))
4061 "AST node for an E4X XML processing instruction. Not currently used."
4062 name ; a `js2-xml-name-node'
4063 attrs) ; a list of `js2-xml-attr-node'
4064
4065 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4066 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4067
4068 (defun js2-visit-xml-pi-node (n v)
4069 (js2-visit-ast (js2-xml-pi-node-name n) v)
4070 (dolist (attr (js2-xml-pi-node-attrs n))
4071 (js2-visit-ast attr v)))
4072
4073 (defun js2-print-xml-pi-node (n i)
4074 (insert (js2-make-pad i) "<?")
4075 (js2-print-ast (js2-xml-pi-node-name n))
4076 (when (js2-xml-pi-node-attrs n)
4077 (insert " ")
4078 (js2-print-list (js2-xml-pi-node-attrs n)))
4079 (insert "?>"))
4080
4081 (defstruct (js2-xml-cdata-node
4082 (:include js2-xml-node)
4083 (:constructor nil)
4084 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4085 (pos js2-ts-cursor)
4086 len content)))
4087 "AST node for a CDATA escape section. Not currently used."
4088 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4089
4090 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4091 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4092
4093 (defun js2-visit-xml-cdata-node (n v)
4094 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4095
4096 (defun js2-print-xml-cdata-node (n i)
4097 (insert (js2-make-pad i))
4098 (js2-print-ast (js2-xml-cdata-node-content n)))
4099
4100 (defstruct (js2-xml-attr-node
4101 (:include js2-xml-node)
4102 (:constructor nil)
4103 (:constructor make-js2-attr-node (&key (type js2-XML)
4104 (pos js2-ts-cursor)
4105 len name value
4106 eq-pos quote-type)))
4107 "AST node representing a foo='bar' XML attribute value. Not yet used."
4108 name ; a `js2-xml-name-node'
4109 value ; a `js2-xml-name-node'
4110 eq-pos ; buffer position of "=" sign
4111 quote-type) ; 'single or 'double
4112
4113 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4114 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4115
4116 (defun js2-visit-xml-attr-node (n v)
4117 (js2-visit-ast (js2-xml-attr-node-name n) v)
4118 (js2-visit-ast (js2-xml-attr-node-value n) v))
4119
4120 (defun js2-print-xml-attr-node (n i)
4121 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4122 "'"
4123 "\"")))
4124 (insert (js2-make-pad i))
4125 (js2-print-ast (js2-xml-attr-node-name n) 0)
4126 (insert "=" quote)
4127 (js2-print-ast (js2-xml-attr-node-value n) 0)
4128 (insert quote)))
4129
4130 (defstruct (js2-xml-text-node
4131 (:include js2-xml-node)
4132 (:constructor nil)
4133 (:constructor make-js2-text-node (&key (type js2-XML)
4134 (pos js2-ts-cursor)
4135 len content)))
4136 "AST node for an E4X XML text node. Not currently used."
4137 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4138
4139 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4140 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4141
4142 (defun js2-visit-xml-text-node (n v)
4143 (js2-visit-ast (js2-xml-text-node-content n) v))
4144
4145 (defun js2-print-xml-text-node (n i)
4146 (insert (js2-make-pad i))
4147 (dolist (kid (js2-xml-text-node-content n))
4148 (js2-print-ast kid)))
4149
4150 (defstruct (js2-xml-comment-node
4151 (:include js2-xml-node)
4152 (:constructor nil)
4153 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4154 (pos js2-ts-cursor)
4155 len)))
4156 "AST node for E4X XML comment. Not currently used.")
4157
4158 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4159 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4160
4161 (defun js2-print-xml-comment (n i)
4162 (insert (js2-make-pad i)
4163 (js2-node-string n)))
4164
4165 ;;; Node utilities
4166
4167 (defsubst js2-node-line (n)
4168 "Fetch the source line number at the start of node N.
4169 This is O(n) in the length of the source buffer; use prudently."
4170 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4171
4172 (defsubst js2-block-node-kid (n i)
4173 "Return child I of node N, or nil if there aren't that many."
4174 (nth i (js2-block-node-kids n)))
4175
4176 (defsubst js2-block-node-first (n)
4177 "Return first child of block node N, or nil if there is none."
4178 (first (js2-block-node-kids n)))
4179
4180 (defun js2-node-root (n)
4181 "Return the root of the AST containing N.
4182 If N has no parent pointer, returns N."
4183 (let ((parent (js2-node-parent n)))
4184 (if parent
4185 (js2-node-root parent)
4186 n)))
4187
4188 (defsubst js2-node-short-name (n)
4189 "Return the short name of node N as a string, e.g. `js2-if-node'."
4190 (substring (symbol-name (aref n 0))
4191 (length "cl-struct-")))
4192
4193 (defun js2-node-child-list (node)
4194 "Return the child list for NODE, a Lisp list of nodes.
4195 Works for block nodes, array nodes, obj literals, funarg lists,
4196 var decls and try nodes (for catch clauses). Note that you should call
4197 `js2-block-node-kids' on the function body for the body statements.
4198 Returns nil for zero-length child lists or unsupported nodes."
4199 (cond
4200 ((js2-function-node-p node)
4201 (js2-function-node-params node))
4202 ((js2-block-node-p node)
4203 (js2-block-node-kids node))
4204 ((js2-try-node-p node)
4205 (js2-try-node-catch-clauses node))
4206 ((js2-array-node-p node)
4207 (js2-array-node-elems node))
4208 ((js2-object-node-p node)
4209 (js2-object-node-elems node))
4210 ((js2-call-node-p node)
4211 (js2-call-node-args node))
4212 ((js2-new-node-p node)
4213 (js2-new-node-args node))
4214 ((js2-var-decl-node-p node)
4215 (js2-var-decl-node-kids node))
4216 (t
4217 nil)))
4218
4219 (defun js2-node-set-child-list (node kids)
4220 "Set the child list for NODE to KIDS."
4221 (cond
4222 ((js2-function-node-p node)
4223 (setf (js2-function-node-params node) kids))
4224 ((js2-block-node-p node)
4225 (setf (js2-block-node-kids node) kids))
4226 ((js2-try-node-p node)
4227 (setf (js2-try-node-catch-clauses node) kids))
4228 ((js2-array-node-p node)
4229 (setf (js2-array-node-elems node) kids))
4230 ((js2-object-node-p node)
4231 (setf (js2-object-node-elems node) kids))
4232 ((js2-call-node-p node)
4233 (setf (js2-call-node-args node) kids))
4234 ((js2-new-node-p node)
4235 (setf (js2-new-node-args node) kids))
4236 ((js2-var-decl-node-p node)
4237 (setf (js2-var-decl-node-kids node) kids))
4238 (t
4239 (error "Unsupported node type: %s" (js2-node-short-name node))))
4240 kids)
4241
4242 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4243 (defconst js2-paren-expr-nodes
4244 '(cl-struct-js2-comp-loop-node
4245 cl-struct-js2-comp-node
4246 cl-struct-js2-call-node
4247 cl-struct-js2-catch-node
4248 cl-struct-js2-do-node
4249 cl-struct-js2-elem-get-node
4250 cl-struct-js2-for-in-node
4251 cl-struct-js2-for-node
4252 cl-struct-js2-function-node
4253 cl-struct-js2-if-node
4254 cl-struct-js2-let-node
4255 cl-struct-js2-new-node
4256 cl-struct-js2-paren-node
4257 cl-struct-js2-switch-node
4258 cl-struct-js2-while-node
4259 cl-struct-js2-with-node
4260 cl-struct-js2-xml-dot-query-node)
4261 "Node types that can have a parenthesized child expression.
4262 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4263
4264 (defsubst js2-paren-expr-node-p (node)
4265 "Return t for nodes that typically have a parenthesized child expression.
4266 Useful for computing the indentation anchors for arg-lists and conditions.
4267 Note that it may return a false positive, for instance when NODE is
4268 a `js2-new-node' and there are no arguments or parentheses."
4269 (memq (aref node 0) js2-paren-expr-nodes))
4270
4271 ;; Fake polymorphism... yech.
4272 (defun js2-node-lp (node)
4273 "Return relative left-paren position for NODE, if applicable.
4274 For `js2-elem-get-node' structs, returns left-bracket position.
4275 Note that the position may be nil in the case of a parse error."
4276 (cond
4277 ((js2-elem-get-node-p node)
4278 (js2-elem-get-node-lb node))
4279 ((js2-loop-node-p node)
4280 (js2-loop-node-lp node))
4281 ((js2-function-node-p node)
4282 (js2-function-node-lp node))
4283 ((js2-if-node-p node)
4284 (js2-if-node-lp node))
4285 ((js2-new-node-p node)
4286 (js2-new-node-lp node))
4287 ((js2-call-node-p node)
4288 (js2-call-node-lp node))
4289 ((js2-paren-node-p node)
4290 0)
4291 ((js2-switch-node-p node)
4292 (js2-switch-node-lp node))
4293 ((js2-catch-node-p node)
4294 (js2-catch-node-lp node))
4295 ((js2-let-node-p node)
4296 (js2-let-node-lp node))
4297 ((js2-comp-node-p node)
4298 0)
4299 ((js2-with-node-p node)
4300 (js2-with-node-lp node))
4301 ((js2-xml-dot-query-node-p node)
4302 (1+ (js2-infix-node-op-pos node)))
4303 (t
4304 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4305
4306 ;; Fake polymorphism... blech.
4307 (defun js2-node-rp (node)
4308 "Return relative right-paren position for NODE, if applicable.
4309 For `js2-elem-get-node' structs, returns right-bracket position.
4310 Note that the position may be nil in the case of a parse error."
4311 (cond
4312 ((js2-elem-get-node-p node)
4313 (js2-elem-get-node-rb node))
4314 ((js2-loop-node-p node)
4315 (js2-loop-node-rp node))
4316 ((js2-function-node-p node)
4317 (js2-function-node-rp node))
4318 ((js2-if-node-p node)
4319 (js2-if-node-rp node))
4320 ((js2-new-node-p node)
4321 (js2-new-node-rp node))
4322 ((js2-call-node-p node)
4323 (js2-call-node-rp node))
4324 ((js2-paren-node-p node)
4325 (1- (js2-node-len node)))
4326 ((js2-switch-node-p node)
4327 (js2-switch-node-rp node))
4328 ((js2-catch-node-p node)
4329 (js2-catch-node-rp node))
4330 ((js2-let-node-p node)
4331 (js2-let-node-rp node))
4332 ((js2-comp-node-p node)
4333 (1- (js2-node-len node)))
4334 ((js2-with-node-p node)
4335 (js2-with-node-rp node))
4336 ((js2-xml-dot-query-node-p node)
4337 (1+ (js2-xml-dot-query-node-rp node)))
4338 (t
4339 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4340
4341 (defsubst js2-node-first-child (node)
4342 "Return the first element of `js2-node-child-list' for NODE."
4343 (car (js2-node-child-list node)))
4344
4345 (defsubst js2-node-last-child (node)
4346 "Return the last element of `js2-node-last-child' for NODE."
4347 (car (last (js2-node-child-list node))))
4348
4349 (defun js2-node-prev-sibling (node)
4350 "Return the previous statement in parent.
4351 Works for parents supported by `js2-node-child-list'.
4352 Returns nil if NODE is not in the parent, or PARENT is
4353 not a supported node, or if NODE is the first child."
4354 (let* ((p (js2-node-parent node))
4355 (kids (js2-node-child-list p))
4356 (sib (car kids)))
4357 (while (and kids
4358 (not (eq node (cadr kids))))
4359 (setq kids (cdr kids)
4360 sib (car kids)))
4361 sib))
4362
4363 (defun js2-node-next-sibling (node)
4364 "Return the next statement in parent block.
4365 Returns nil if NODE is not in the block, or PARENT is not
4366 a block node, or if NODE is the last statement."
4367 (let* ((p (js2-node-parent node))
4368 (kids (js2-node-child-list p)))
4369 (while (and kids
4370 (not (eq node (car kids))))
4371 (setq kids (cdr kids)))
4372 (cadr kids)))
4373
4374 (defun js2-node-find-child-before (pos parent &optional after)
4375 "Find the last child that starts before POS in parent.
4376 If AFTER is non-nil, returns first child starting after POS.
4377 POS is an absolute buffer position. PARENT is any node
4378 supported by `js2-node-child-list'.
4379 Returns nil if no applicable child is found."
4380 (let ((kids (if (js2-function-node-p parent)
4381 (js2-block-node-kids (js2-function-node-body parent))
4382 (js2-node-child-list parent)))
4383 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4384 (js2-function-node-body parent)
4385 parent)))
4386 kid result fn
4387 (continue t))
4388 (setq fn (if after '>= '<))
4389 (while (and kids continue)
4390 (setq kid (car kids))
4391 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4392 (setq result kid
4393 continue (not after))
4394 (setq continue after))
4395 (setq kids (cdr kids)))
4396 result))
4397
4398 (defun js2-node-find-child-after (pos parent)
4399 "Find first child that starts after POS in parent.
4400 POS is an absolute buffer position. PARENT is any node
4401 supported by `js2-node-child-list'.
4402 Returns nil if no applicable child is found."
4403 (js2-node-find-child-before pos parent 'after))
4404
4405 (defun js2-node-replace-child (pos parent new-node)
4406 "Replace node at index POS in PARENT with NEW-NODE.
4407 Only works for parents supported by `js2-node-child-list'."
4408 (let ((kids (js2-node-child-list parent))
4409 (i 0))
4410 (while (< i pos)
4411 (setq kids (cdr kids)
4412 i (1+ i)))
4413 (setcar kids new-node)
4414 (js2-node-add-children parent new-node)))
4415
4416 (defun js2-node-buffer (n)
4417 "Return the buffer associated with AST N.
4418 Returns nil if the buffer is not set as a property on the root
4419 node, or if parent links were not recorded during parsing."
4420 (let ((root (js2-node-root n)))
4421 (and root
4422 (js2-ast-root-p root)
4423 (js2-ast-root-buffer root))))
4424
4425 (defun js2-block-node-push (n kid)
4426 "Push js2-node KID onto the end of js2-block-node N's child list.
4427 KID is always added to the -end- of the kids list.
4428 Function also calls `js2-node-add-children' to add the parent link."
4429 (let ((kids (js2-node-child-list n)))
4430 (if kids
4431 (setcdr kids (nconc (cdr kids) (list kid)))
4432 (js2-node-set-child-list n (list kid)))
4433 (js2-node-add-children n kid)))
4434
4435 (defun js2-node-string (node)
4436 (with-current-buffer (or (js2-node-buffer node)
4437 (error "No buffer available for node %s" node))
4438 (let ((pos (js2-node-abs-pos node)))
4439 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4440
4441 ;; Container for storing the node we're looking for in a traversal.
4442 (js2-deflocal js2-discovered-node nil)
4443
4444 ;; Keep track of absolute node position during traversals.
4445 (js2-deflocal js2-visitor-offset nil)
4446
4447 (js2-deflocal js2-node-search-point nil)
4448
4449 (when js2-mode-dev-mode-p
4450 (defun js2-find-node-at-point ()
4451 (interactive)
4452 (let ((node (js2-node-at-point)))
4453 (message "%s" (or node "No node found at point"))))
4454 (defun js2-node-name-at-point ()
4455 (interactive)
4456 (let ((node (js2-node-at-point)))
4457 (message "%s" (if node
4458 (js2-node-short-name node)
4459 "No node found at point.")))))
4460
4461 (defun js2-node-at-point (&optional pos skip-comments)
4462 "Return AST node at POS, a buffer position, defaulting to current point.
4463 The `js2-mode-ast' variable must be set to the current parse tree.
4464 Signals an error if the AST (`js2-mode-ast') is nil.
4465 Always returns a node - if it can't find one, it returns the root.
4466 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4467 (let ((ast js2-mode-ast)
4468 result)
4469 (unless ast
4470 (error "No JavaScript AST available"))
4471 ;; Look through comments first, since they may be inside nodes that
4472 ;; would otherwise report a match.
4473 (setq pos (or pos (point))
4474 result (if (> pos (js2-node-abs-end ast))
4475 ast
4476 (if (not skip-comments)
4477 (js2-comment-at-point pos))))
4478 (unless result
4479 (setq js2-discovered-node nil
4480 js2-visitor-offset 0
4481 js2-node-search-point pos)
4482 (unwind-protect
4483 (catch 'js2-visit-done
4484 (js2-visit-ast ast #'js2-node-at-point-visitor))
4485 (setq js2-visitor-offset nil
4486 js2-node-search-point nil))
4487 (setq result js2-discovered-node))
4488 ;; may have found a comment beyond end of last child node,
4489 ;; since visiting the ast-root looks at the comment-list last.
4490 (if (and skip-comments
4491 (js2-comment-node-p result))
4492 (setq result nil))
4493 (or result js2-mode-ast)))
4494
4495 (defun js2-node-at-point-visitor (node end-p)
4496 (let ((rel-pos (js2-node-pos node))
4497 abs-pos
4498 abs-end
4499 (point js2-node-search-point))
4500 (cond
4501 (end-p
4502 ;; this evaluates to a non-nil return value, even if it's zero
4503 (decf js2-visitor-offset rel-pos))
4504 ;; we already looked for comments before visiting, and don't want them now
4505 ((js2-comment-node-p node)
4506 nil)
4507 (t
4508 (setq abs-pos (incf js2-visitor-offset rel-pos)
4509 ;; we only want to use the node if the point is before
4510 ;; the last character position in the node, so we decrement
4511 ;; the absolute end by 1.
4512 abs-end (+ abs-pos (js2-node-len node) -1))
4513 (cond
4514 ;; If this node starts after search-point, stop the search.
4515 ((> abs-pos point)
4516 (throw 'js2-visit-done nil))
4517 ;; If this node ends before the search-point, don't check kids.
4518 ((> point abs-end)
4519 nil)
4520 (t
4521 ;; Otherwise point is within this node, possibly in a child.
4522 (setq js2-discovered-node node)
4523 t)))))) ; keep processing kids to look for more specific match
4524
4525 (defsubst js2-block-comment-p (node)
4526 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4527 (and (js2-comment-node-p node)
4528 (memq (js2-comment-node-format node) '(jsdoc block))))
4529
4530 ;; TODO: put the comments in a vector and binary-search them instead
4531 (defun js2-comment-at-point (&optional pos)
4532 "Look through scanned comment nodes for one containing POS.
4533 POS is a buffer position that defaults to current point.
4534 Function returns nil if POS was not in any comment node."
4535 (let ((ast js2-mode-ast)
4536 (x (or pos (point)))
4537 beg end)
4538 (unless ast
4539 (error "No JavaScript AST available"))
4540 (catch 'done
4541 ;; Comments are stored in lexical order.
4542 (dolist (comment (js2-ast-root-comments ast) nil)
4543 (setq beg (js2-node-abs-pos comment)
4544 end (+ beg (js2-node-len comment)))
4545 (if (and (>= x beg)
4546 (<= x end))
4547 (throw 'done comment))))))
4548
4549 (defun js2-mode-find-parent-fn (node)
4550 "Find function enclosing NODE.
4551 Returns nil if NODE is not inside a function."
4552 (setq node (js2-node-parent node))
4553 (while (and node (not (js2-function-node-p node)))
4554 (setq node (js2-node-parent node)))
4555 (and (js2-function-node-p node) node))
4556
4557 (defun js2-mode-find-enclosing-fn (node)
4558 "Find function or root enclosing NODE."
4559 (if (js2-ast-root-p node)
4560 node
4561 (setq node (js2-node-parent node))
4562 (while (not (or (js2-ast-root-p node)
4563 (js2-function-node-p node)))
4564 (setq node (js2-node-parent node)))
4565 node))
4566
4567 (defun js2-mode-find-enclosing-node (beg end)
4568 "Find node fully enclosing BEG and END."
4569 (let ((node (js2-node-at-point beg))
4570 pos
4571 (continue t))
4572 (while continue
4573 (if (or (js2-ast-root-p node)
4574 (and
4575 (<= (setq pos (js2-node-abs-pos node)) beg)
4576 (>= (+ pos (js2-node-len node)) end)))
4577 (setq continue nil)
4578 (setq node (js2-node-parent node))))
4579 node))
4580
4581 (defun js2-node-parent-script-or-fn (node)
4582 "Find script or function immediately enclosing NODE.
4583 If NODE is the ast-root, returns nil."
4584 (if (js2-ast-root-p node)
4585 nil
4586 (setq node (js2-node-parent node))
4587 (while (and node (not (or (js2-function-node-p node)
4588 (js2-script-node-p node))))
4589 (setq node (js2-node-parent node)))
4590 node))
4591
4592 (defun js2-node-is-descendant (node ancestor)
4593 "Return t if NODE is a descendant of ANCESTOR."
4594 (while (and node
4595 (not (eq node ancestor)))
4596 (setq node (js2-node-parent node)))
4597 node)
4598
4599 ;;; visitor infrastructure
4600
4601 (defun js2-visit-none (_node _callback)
4602 "Visitor for AST node that have no node children."
4603 nil)
4604
4605 (defun js2-print-none (_node _indent)
4606 "Visitor for AST node with no printed representation.")
4607
4608 (defun js2-print-body (node indent)
4609 "Print a statement, or a block without braces."
4610 (if (js2-block-node-p node)
4611 (dolist (kid (js2-block-node-kids node))
4612 (js2-print-ast kid indent))
4613 (js2-print-ast node indent)))
4614
4615 (defun js2-print-list (args &optional delimiter)
4616 (loop with len = (length args)
4617 for arg in args
4618 for count from 1
4619 do
4620 (when arg (js2-print-ast arg 0))
4621 (if (< count len)
4622 (insert (or delimiter ", ")))))
4623
4624 (defun js2-print-tree (ast)
4625 "Prints an AST to the current buffer.
4626 Makes `js2-ast-parent-nodes' available to the printer functions."
4627 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4628 (js2-print-ast ast)))
4629
4630 (defun js2-print-ast (node &optional indent)
4631 "Helper function for printing AST nodes.
4632 Requires `js2-ast-parent-nodes' to be non-nil.
4633 You should use `js2-print-tree' instead of this function."
4634 (let ((printer (get (aref node 0) 'js2-printer))
4635 (i (or indent 0)))
4636 ;; TODO: wedge comments in here somewhere
4637 (if printer
4638 (funcall printer node i))))
4639
4640 (defconst js2-side-effecting-tokens
4641 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4642 (dolist (tt (list js2-ASSIGN
4643 js2-ASSIGN_ADD
4644 js2-ASSIGN_BITAND
4645 js2-ASSIGN_BITOR
4646 js2-ASSIGN_BITXOR
4647 js2-ASSIGN_DIV
4648 js2-ASSIGN_LSH
4649 js2-ASSIGN_MOD
4650 js2-ASSIGN_MUL
4651 js2-ASSIGN_RSH
4652 js2-ASSIGN_SUB
4653 js2-ASSIGN_URSH
4654 js2-BLOCK
4655 js2-BREAK
4656 js2-CALL
4657 js2-CATCH
4658 js2-CATCH_SCOPE
4659 js2-CONST
4660 js2-CONTINUE
4661 js2-DEBUGGER
4662 js2-DEC
4663 js2-DELPROP
4664 js2-DEL_REF
4665 js2-DO
4666 js2-ELSE
4667 js2-EMPTY
4668 js2-ENTERWITH
4669 js2-EXPORT
4670 js2-EXPR_RESULT
4671 js2-FINALLY
4672 js2-FOR
4673 js2-FUNCTION
4674 js2-GOTO
4675 js2-IF
4676 js2-IFEQ
4677 js2-IFNE
4678 js2-IMPORT
4679 js2-INC
4680 js2-JSR
4681 js2-LABEL
4682 js2-LEAVEWITH
4683 js2-LET
4684 js2-LETEXPR
4685 js2-LOCAL_BLOCK
4686 js2-LOOP
4687 js2-NEW
4688 js2-REF_CALL
4689 js2-RETHROW
4690 js2-RETURN
4691 js2-RETURN_RESULT
4692 js2-SEMI
4693 js2-SETELEM
4694 js2-SETELEM_OP
4695 js2-SETNAME
4696 js2-SETPROP
4697 js2-SETPROP_OP
4698 js2-SETVAR
4699 js2-SET_REF
4700 js2-SET_REF_OP
4701 js2-SWITCH
4702 js2-TARGET
4703 js2-THROW
4704 js2-TRY
4705 js2-VAR
4706 js2-WHILE
4707 js2-WITH
4708 js2-WITHEXPR
4709 js2-YIELD))
4710 (aset tokens tt t))
4711 (if js2-instanceof-has-side-effects
4712 (aset tokens js2-INSTANCEOF t))
4713 tokens))
4714
4715 (defun js2-node-has-side-effects (node)
4716 "Return t if NODE has side effects."
4717 (when node ; makes it easier to handle malformed expressions
4718 (let ((tt (js2-node-type node)))
4719 (cond
4720 ;; This doubtless needs some work, since EXPR_VOID is used
4721 ;; in several ways in Rhino and I may not have caught them all.
4722 ;; I'll wait for people to notice incorrect warnings.
4723 ((and (= tt js2-EXPR_VOID)
4724 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4725 (let ((expr (js2-expr-stmt-node-expr node)))
4726 (or (js2-node-has-side-effects expr)
4727 (when (js2-string-node-p expr)
4728 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4729 ((= tt js2-COMMA)
4730 (js2-node-has-side-effects (js2-infix-node-right node)))
4731 ((or (= tt js2-AND)
4732 (= tt js2-OR))
4733 (or (js2-node-has-side-effects (js2-infix-node-right node))
4734 (js2-node-has-side-effects (js2-infix-node-left node))))
4735 ((= tt js2-HOOK)
4736 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4737 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4738 ((js2-paren-node-p node)
4739 (js2-node-has-side-effects (js2-paren-node-expr node)))
4740 ((= tt js2-ERROR) ; avoid cascaded error messages
4741 nil)
4742 (t
4743 (aref js2-side-effecting-tokens tt))))))
4744
4745 (defconst js2-stmt-node-types
4746 (list js2-BLOCK
4747 js2-BREAK
4748 js2-CONTINUE
4749 js2-DEFAULT ; e4x "default xml namespace" statement
4750 js2-DO
4751 js2-EXPR_RESULT
4752 js2-EXPR_VOID
4753 js2-FOR
4754 js2-IF
4755 js2-RETURN
4756 js2-SWITCH
4757 js2-THROW
4758 js2-TRY
4759 js2-WHILE
4760 js2-WITH)
4761 "Node types that only appear in statement contexts.
4762 The list does not include nodes that always appear as the child
4763 of another specific statement type, such as switch-cases,
4764 catch and finally blocks, and else-clauses. The list also excludes
4765 nodes like yield, let and var, which may appear in either expression
4766 or statement context, and in the latter context always have a
4767 `js2-expr-stmt-node' parent. Finally, the list does not include
4768 functions or scripts, which are treated separately from statements
4769 by the JavaScript parser and runtime.")
4770
4771 (defun js2-stmt-node-p (node)
4772 "Heuristic for figuring out if NODE is a statement.
4773 Some node types can appear in either an expression context or a
4774 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4775 For these node types in a statement context, the parent will be a
4776 `js2-expr-stmt-node'.
4777 Functions aren't included in the check."
4778 (memq (js2-node-type node) js2-stmt-node-types))
4779
4780 (defun js2-mode-find-first-stmt (node)
4781 "Search upward starting from NODE looking for a statement.
4782 For purposes of this function, a `js2-function-node' counts."
4783 (while (not (or (js2-stmt-node-p node)
4784 (js2-function-node-p node)))
4785 (setq node (js2-node-parent node)))
4786 node)
4787
4788 (defun js2-node-parent-stmt (node)
4789 "Return the node's first ancestor that is a statement.
4790 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4791 appearing in a statement context will have a parent that is a
4792 `js2-expr-stmt-node' that will be returned by this function."
4793 (let ((parent (js2-node-parent node)))
4794 (if (or (null parent)
4795 (js2-stmt-node-p parent)
4796 (and (js2-function-node-p parent)
4797 (not (eq (js2-function-node-form parent)
4798 'FUNCTION_EXPRESSION))))
4799 parent
4800 (js2-node-parent-stmt parent))))
4801
4802 ;; In the Mozilla Rhino sources, Roshan James writes:
4803 ;; Does consistent-return analysis on the function body when strict mode is
4804 ;; enabled.
4805 ;;
4806 ;; function (x) { return (x+1) }
4807 ;;
4808 ;; is ok, but
4809 ;;
4810 ;; function (x) { if (x < 0) return (x+1); }
4811 ;;
4812 ;; is not because the function can potentially return a value when the
4813 ;; condition is satisfied and if not, the function does not explicitly
4814 ;; return a value.
4815 ;;
4816 ;; This extends to checking mismatches such as "return" and "return <value>"
4817 ;; used in the same function. Warnings are not emitted if inconsistent
4818 ;; returns exist in code that can be statically shown to be unreachable.
4819 ;; Ex.
4820 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4821 ;;
4822 ;; emits no warning. However if the loop had a break statement, then a
4823 ;; warning would be emitted.
4824 ;;
4825 ;; The consistency analysis looks at control structures such as loops, ifs,
4826 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4827 ;; warns the user about an inconsistent set of termination possibilities.
4828 ;;
4829 ;; These flags enumerate the possible ways a statement/function can
4830 ;; terminate. These flags are used by endCheck() and by the Parser to
4831 ;; detect inconsistent return usage.
4832 ;;
4833 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4834 ;; able to execute (example: throw, continue)
4835 ;;
4836 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4837 ;; next one. Statement such as return dont. A compound statement may have
4838 ;; some branch that drops off control to the next statement.
4839 ;;
4840 ;; END_RETURNS indicates that the statement can return with no value.
4841 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4842 ;;
4843 ;; A compound statement such as
4844 ;; if (condition) {
4845 ;; return value;
4846 ;; }
4847 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4848
4849 (defconst js2-END_UNREACHED 0)
4850 (defconst js2-END_DROPS_OFF 1)
4851 (defconst js2-END_RETURNS 2)
4852 (defconst js2-END_RETURNS_VALUE 4)
4853 (defconst js2-END_YIELDS 8)
4854
4855 (defun js2-has-consistent-return-usage (node)
4856 "Check that every return usage in a function body is consistent.
4857 Returns t if the function satisfies strict mode requirement."
4858 (let ((n (js2-end-check node)))
4859 ;; either it doesn't return a value in any branch...
4860 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4861 ;; or it returns a value (or is unreached) at every branch
4862 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4863 js2-END_RETURNS
4864 js2-END_YIELDS)))))
4865
4866 (defun js2-end-check-if (node)
4867 "Ensure that return usage in then/else blocks is consistent.
4868 If there is no else block, then the return statement can fall through.
4869 Returns logical OR of END_* flags"
4870 (let ((th (js2-if-node-then-part node))
4871 (el (js2-if-node-else-part node)))
4872 (if (null th)
4873 js2-END_UNREACHED
4874 (logior (js2-end-check th) (if el
4875 (js2-end-check el)
4876 js2-END_DROPS_OFF)))))
4877
4878 (defun js2-end-check-switch (node)
4879 "Consistency of return statements is checked between the case statements.
4880 If there is no default, then the switch can fall through. If there is a
4881 default, we check to see if all code paths in the default return or if
4882 there is a code path that can fall through.
4883 Returns logical OR of END_* flags."
4884 (let ((rv js2-END_UNREACHED)
4885 default-case)
4886 ;; examine the cases
4887 (catch 'break
4888 (dolist (c (js2-switch-node-cases node))
4889 (if (js2-case-node-expr c)
4890 (js2-set-flag rv (js2-end-check-block c))
4891 (setq default-case c)
4892 (throw 'break nil))))
4893 ;; we don't care how the cases drop into each other
4894 (js2-clear-flag rv js2-END_DROPS_OFF)
4895 ;; examine the default
4896 (js2-set-flag rv (if default-case
4897 (js2-end-check default-case)
4898 js2-END_DROPS_OFF))
4899 rv))
4900
4901 (defun js2-end-check-try (node)
4902 "If the block has a finally, return consistency is checked in the
4903 finally block. If all code paths in the finally return, then the
4904 returns in the try-catch blocks don't matter. If there is a code path
4905 that does not return or if there is no finally block, the returns
4906 of the try and catch blocks are checked for mismatch.
4907 Returns logical OR of END_* flags."
4908 (let ((finally (js2-try-node-finally-block node))
4909 rv)
4910 ;; check the finally if it exists
4911 (setq rv (if finally
4912 (js2-end-check (js2-finally-node-body finally))
4913 js2-END_DROPS_OFF))
4914 ;; If the finally block always returns, then none of the returns
4915 ;; in the try or catch blocks matter.
4916 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4917 (js2-clear-flag rv js2-END_DROPS_OFF)
4918 ;; examine the try block
4919 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4920 ;; check each catch block
4921 (dolist (cb (js2-try-node-catch-clauses node))
4922 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4923 rv))
4924
4925 (defun js2-end-check-loop (node)
4926 "Return statement in the loop body must be consistent.
4927 The default assumption for any kind of a loop is that it will eventually
4928 terminate. The only exception is a loop with a constant true condition.
4929 Code that follows such a loop is examined only if one can determine
4930 statically that there is a break out of the loop.
4931
4932 for(... ; ... ; ...) {}
4933 for(... in ... ) {}
4934 while(...) { }
4935 do { } while(...)
4936
4937 Returns logical OR of END_* flags."
4938 (let ((rv (js2-end-check (js2-loop-node-body node)))
4939 (condition (cond
4940 ((js2-while-node-p node)
4941 (js2-while-node-condition node))
4942 ((js2-do-node-p node)
4943 (js2-do-node-condition node))
4944 ((js2-for-node-p node)
4945 (js2-for-node-condition node)))))
4946
4947 ;; check to see if the loop condition is always true
4948 (if (and condition
4949 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4950 (js2-clear-flag rv js2-END_DROPS_OFF))
4951
4952 ;; look for effect of breaks
4953 (js2-set-flag rv (js2-node-get-prop node
4954 'CONTROL_BLOCK_PROP
4955 js2-END_UNREACHED))
4956 rv))
4957
4958 (defun js2-end-check-block (node)
4959 "A general block of code is examined statement by statement.
4960 If any statement (even a compound one) returns in all branches, then
4961 subsequent statements are not examined.
4962 Returns logical OR of END_* flags."
4963 (let* ((rv js2-END_DROPS_OFF)
4964 (kids (js2-block-node-kids node))
4965 (n (car kids)))
4966 ;; Check each statment. If the statement can continue onto the next
4967 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4968 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4969 (js2-clear-flag rv js2-END_DROPS_OFF)
4970 (js2-set-flag rv (js2-end-check n))
4971 (setq kids (cdr kids)
4972 n (car kids)))
4973 rv))
4974
4975 (defun js2-end-check-label (node)
4976 "A labeled statement implies that there may be a break to the label.
4977 The function processes the labeled statement and then checks the
4978 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4979 particular label.
4980 Returns logical OR of END_* flags."
4981 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4982 (logior rv (js2-node-get-prop node
4983 'CONTROL_BLOCK_PROP
4984 js2-END_UNREACHED))))
4985
4986 (defun js2-end-check-break (node)
4987 "When a break is encountered annotate the statement being broken
4988 out of by setting its CONTROL_BLOCK_PROP property.
4989 Returns logical OR of END_* flags."
4990 (and (js2-break-node-target node)
4991 (js2-node-set-prop (js2-break-node-target node)
4992 'CONTROL_BLOCK_PROP
4993 js2-END_DROPS_OFF))
4994 js2-END_UNREACHED)
4995
4996 (defun js2-end-check (node)
4997 "Examine the body of a function, doing a basic reachability analysis.
4998 Returns a combination of flags END_* flags that indicate
4999 how the function execution can terminate. These constitute only the
5000 pessimistic set of termination conditions. It is possible that at
5001 runtime certain code paths will never be actually taken. Hence this
5002 analysis will flag errors in cases where there may not be errors.
5003 Returns logical OR of END_* flags"
5004 (let (kid)
5005 (cond
5006 ((js2-break-node-p node)
5007 (js2-end-check-break node))
5008 ((js2-expr-stmt-node-p node)
5009 (if (setq kid (js2-expr-stmt-node-expr node))
5010 (js2-end-check kid)
5011 js2-END_DROPS_OFF))
5012 ((or (js2-continue-node-p node)
5013 (js2-throw-node-p node))
5014 js2-END_UNREACHED)
5015 ((js2-return-node-p node)
5016 (if (setq kid (js2-return-node-retval node))
5017 js2-END_RETURNS_VALUE
5018 js2-END_RETURNS))
5019 ((js2-loop-node-p node)
5020 (js2-end-check-loop node))
5021 ((js2-switch-node-p node)
5022 (js2-end-check-switch node))
5023 ((js2-labeled-stmt-node-p node)
5024 (js2-end-check-label node))
5025 ((js2-if-node-p node)
5026 (js2-end-check-if node))
5027 ((js2-try-node-p node)
5028 (js2-end-check-try node))
5029 ((js2-block-node-p node)
5030 (if (null (js2-block-node-kids node))
5031 js2-END_DROPS_OFF
5032 (js2-end-check-block node)))
5033 ((js2-yield-node-p node)
5034 js2-END_YIELDS)
5035 (t
5036 js2-END_DROPS_OFF))))
5037
5038 (defun js2-always-defined-boolean-p (node)
5039 "Check if NODE always evaluates to true or false in boolean context.
5040 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5041 nor always false."
5042 (let ((tt (js2-node-type node))
5043 num)
5044 (cond
5045 ((or (= tt js2-FALSE) (= tt js2-NULL))
5046 'ALWAYS_FALSE)
5047 ((= tt js2-TRUE)
5048 'ALWAYS_TRUE)
5049 ((= tt js2-NUMBER)
5050 (setq num (js2-number-node-num-value node))
5051 (if (and (not (eq num 0.0e+NaN))
5052 (not (zerop num)))
5053 'ALWAYS_TRUE
5054 'ALWAYS_FALSE))
5055 (t
5056 nil))))
5057
5058 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5059 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5060
5061 (defvar js2-tokens nil
5062 "List of all defined token names.") ; initialized in `js2-token-names'
5063
5064 (defconst js2-token-names
5065 (let* ((names (make-vector js2-num-tokens -1))
5066 (case-fold-search nil) ; only match js2-UPPER_CASE
5067 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5068 (loop for sym in syms
5069 for i from 0
5070 do
5071 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5072 (not (boundp sym)))
5073 (aset names (symbol-value sym) ; code, e.g. 152
5074 (downcase
5075 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5076 (push sym js2-tokens)))
5077 names)
5078 "Vector mapping int values to token string names, sans `js2-' prefix.")
5079
5080 (defun js2-tt-name (tok)
5081 "Return a string name for TOK, a token symbol or code.
5082 Signals an error if it's not a recognized token."
5083 (let ((code tok))
5084 (if (symbolp tok)
5085 (setq code (symbol-value tok)))
5086 (if (eq code -1)
5087 "ERROR"
5088 (if (and (numberp code)
5089 (not (minusp code))
5090 (< code js2-num-tokens))
5091 (aref js2-token-names code)
5092 (error "Invalid token: %s" code)))))
5093
5094 (defsubst js2-tt-sym (tok)
5095 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5096 (intern (js2-tt-name tok)))
5097
5098 (defconst js2-token-codes
5099 (let ((table (make-hash-table :test 'eq :size 256)))
5100 (loop for name across js2-token-names
5101 for sym = (intern (concat "js2-" (upcase name)))
5102 do
5103 (puthash sym (symbol-value sym) table))
5104 ;; clean up a few that are "wrong" in Rhino's token codes
5105 (puthash 'js2-DELETE js2-DELPROP table)
5106 table)
5107 "Hashtable mapping token type symbols to their bytecodes.")
5108
5109 (defsubst js2-tt-code (sym)
5110 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5111 (or (gethash sym js2-token-codes)
5112 (error "Invalid token symbol: %s " sym))) ; signal code bug
5113
5114 (defun js2-report-scan-error (msg &optional no-throw beg len)
5115 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5116 (js2-report-error msg nil
5117 (or beg (js2-current-token-beg))
5118 (or len (js2-current-token-len)))
5119 (unless no-throw
5120 (throw 'return js2-ERROR)))
5121
5122 (defun js2-set-string-from-buffer (token)
5123 "Set `string' and `end' slots for TOKEN, return the string."
5124 (setf (js2-token-end token) js2-ts-cursor
5125 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5126
5127 ;; TODO: could potentially avoid a lot of consing by allocating a
5128 ;; char buffer the way Rhino does.
5129 (defsubst js2-add-to-string (c)
5130 (push c js2-ts-string-buffer))
5131
5132 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5133 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5134 ;; any other character: when it's not part of the current token, we
5135 ;; unget it, allowing it to be read again by the following call.
5136 (defsubst js2-unget-char ()
5137 (decf js2-ts-cursor))
5138
5139 ;; Rhino distinguishes \r and \n line endings. We don't need to
5140 ;; because we only scan from Emacs buffers, which always use \n.
5141 (defun js2-get-char ()
5142 "Read and return the next character from the input buffer.
5143 Increments `js2-ts-lineno' if the return value is a newline char.
5144 Updates `js2-ts-cursor' to the point after the returned char.
5145 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5146 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5147 (let (c)
5148 ;; check for end of buffer
5149 (if (>= js2-ts-cursor (point-max))
5150 (setq js2-ts-hit-eof t
5151 js2-ts-cursor (1+ js2-ts-cursor)
5152 c js2-EOF_CHAR) ; return value
5153 ;; otherwise read next char
5154 (setq c (char-before (incf js2-ts-cursor)))
5155 ;; if we read a newline, update counters
5156 (if (= c ?\n)
5157 (setq js2-ts-line-start js2-ts-cursor
5158 js2-ts-lineno (1+ js2-ts-lineno)))
5159 ;; TODO: skip over format characters
5160 c)))
5161
5162 (defun js2-read-unicode-escape ()
5163 "Read a \\uNNNN sequence from the input.
5164 Assumes the ?\ and ?u have already been read.
5165 Returns the unicode character, or nil if it wasn't a valid character.
5166 Doesn't change the values of any scanner variables."
5167 ;; I really wish I knew a better way to do this, but I can't
5168 ;; find the Emacs function that takes a 16-bit int and converts
5169 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5170 ;; Have to first check that it's 4 hex characters or it may stop
5171 ;; the read early.
5172 (ignore-errors
5173 (let ((s (buffer-substring-no-properties js2-ts-cursor
5174 (+ 4 js2-ts-cursor))))
5175 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5176 (read (concat "?\\u" s))))))
5177
5178 (defun js2-match-char (test)
5179 "Consume and return next character if it matches TEST, a character.
5180 Returns nil and consumes nothing if TEST is not the next character."
5181 (let ((c (js2-get-char)))
5182 (if (eq c test)
5183 t
5184 (js2-unget-char)
5185 nil)))
5186
5187 (defun js2-peek-char ()
5188 (prog1
5189 (js2-get-char)
5190 (js2-unget-char)))
5191
5192 (defun js2-identifier-start-p (c)
5193 "Is C a valid start to an ES5 Identifier?
5194 See http://es5.github.io/#x7.6"
5195 (or
5196 (memq c '(?$ ?_))
5197 (memq (get-char-code-property c 'general-category)
5198 ;; Letters
5199 '(Lu Ll Lt Lm Lo Nl))))
5200
5201 (defun js2-identifier-part-p (c)
5202 "Is C a valid part of an ES5 Identifier?
5203 See http://es5.github.io/#x7.6"
5204 (or
5205 (memq c '(?$ ?_ ?\u200c ?\u200d))
5206 (memq (get-char-code-property c 'general-category)
5207 '(;; Letters
5208 Lu Ll Lt Lm Lo Nl
5209 ;; Combining Marks
5210 Mn Mc
5211 ;; Digits
5212 Nd
5213 ;; Connector Punctuation
5214 Pc))))
5215
5216 (defun js2-alpha-p (c)
5217 (cond ((and (<= ?A c) (<= c ?Z)) t)
5218 ((and (<= ?a c) (<= c ?z)) t)
5219 (t nil)))
5220
5221 (defsubst js2-digit-p (c)
5222 (and (<= ?0 c) (<= c ?9)))
5223
5224 (defun js2-js-space-p (c)
5225 (if (<= c 127)
5226 (memq c '(#x20 #x9 #xB #xC #xD))
5227 (or
5228 (eq c #xA0)
5229 ;; TODO: change this nil to check for Unicode space character
5230 nil)))
5231
5232 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5233
5234 (defun js2-skip-line ()
5235 "Skip to end of line."
5236 (while (not (memq (js2-get-char) js2-eol-chars)))
5237 (js2-unget-char)
5238 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5239 (setq js2-token-end js2-ts-cursor))
5240
5241 (defun js2-init-scanner (&optional buf line)
5242 "Create token stream for BUF starting on LINE.
5243 BUF defaults to `current-buffer' and LINE defaults to 1.
5244
5245 A buffer can only have one scanner active at a time, which yields
5246 dramatically simpler code than using a defstruct. If you need to
5247 have simultaneous scanners in a buffer, copy the regions to scan
5248 into temp buffers."
5249 (with-current-buffer (or buf (current-buffer))
5250 (setq js2-ts-dirty-line nil
5251 js2-ts-hit-eof nil
5252 js2-ts-line-start 0
5253 js2-ts-lineno (or line 1)
5254 js2-ts-line-end-char -1
5255 js2-ts-cursor (point-min)
5256 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5257 js2-ti-tokens-cursor 0
5258 js2-ti-lookahead 0
5259 js2-ts-is-xml-attribute nil
5260 js2-ts-xml-is-tag-content nil
5261 js2-ts-xml-open-tags-count 0
5262 js2-ts-string-buffer nil)))
5263
5264 ;; This function uses the cached op, string and number fields in
5265 ;; TokenStream; if getToken has been called since the passed token
5266 ;; was scanned, the op or string printed may be incorrect.
5267 (defun js2-token-to-string (token)
5268 ;; Not sure where this function is used in Rhino. Not tested.
5269 (if (not js2-debug-print-trees)
5270 ""
5271 (let ((name (js2-tt-name token)))
5272 (cond
5273 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5274 (concat name " `" (js2-current-token-string) "'"))
5275 ((eq token js2-NUMBER)
5276 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5277 (t
5278 name)))))
5279
5280 (defconst js2-keywords
5281 '(break
5282 case catch const continue
5283 debugger default delete do
5284 else enum
5285 false finally for function
5286 if in instanceof import
5287 let
5288 new null
5289 return
5290 switch
5291 this throw true try typeof
5292 var void
5293 while with
5294 yield))
5295
5296 ;; Token names aren't exactly the same as the keywords, unfortunately.
5297 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5298 (defconst js2-kwd-tokens
5299 (let ((table (make-vector js2-num-tokens nil))
5300 (tokens
5301 (list js2-BREAK
5302 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5303 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5304 js2-ELSE
5305 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5306 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5307 js2-LET
5308 js2-NEW js2-NULL
5309 js2-RETURN
5310 js2-SWITCH
5311 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5312 js2-VAR
5313 js2-WHILE js2-WITH
5314 js2-YIELD)))
5315 (dolist (i tokens)
5316 (aset table i 'font-lock-keyword-face))
5317 (aset table js2-STRING 'font-lock-string-face)
5318 (aset table js2-REGEXP 'font-lock-string-face)
5319 (aset table js2-COMMENT 'font-lock-comment-face)
5320 (aset table js2-THIS 'font-lock-builtin-face)
5321 (aset table js2-VOID 'font-lock-constant-face)
5322 (aset table js2-NULL 'font-lock-constant-face)
5323 (aset table js2-TRUE 'font-lock-constant-face)
5324 (aset table js2-FALSE 'font-lock-constant-face)
5325 (aset table js2-NOT 'font-lock-negation-char-face)
5326 table)
5327 "Vector whose values are non-nil for tokens that are keywords.
5328 The values are default faces to use for highlighting the keywords.")
5329
5330 ;; FIXME: Support strict mode-only future reserved words, after we know
5331 ;; which parts scopes are in strict mode, and which are not.
5332 (defconst js2-reserved-words '(class export extends import super)
5333 "Future reserved keywords in ECMAScript 5.")
5334
5335 (defconst js2-keyword-names
5336 (let ((table (make-hash-table :test 'equal)))
5337 (loop for k in js2-keywords
5338 do (puthash
5339 (symbol-name k) ; instanceof
5340 (intern (concat "js2-"
5341 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5342 table))
5343 table)
5344 "JavaScript keywords by name, mapped to their symbols.")
5345
5346 (defconst js2-reserved-word-names
5347 (let ((table (make-hash-table :test 'equal)))
5348 (loop for k in js2-reserved-words
5349 do
5350 (puthash (symbol-name k) 'js2-RESERVED table))
5351 table)
5352 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5353
5354 (defun js2-collect-string (buf)
5355 "Convert BUF, a list of chars, to a string.
5356 Reverses BUF before converting."
5357 (if buf
5358 (apply #'string (nreverse buf))
5359 ""))
5360
5361 (defun js2-string-to-keyword (s)
5362 "Return token for S, a string, if S is a keyword or reserved word.
5363 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5364 (or (gethash s js2-keyword-names)
5365 (gethash s js2-reserved-word-names)))
5366
5367 (defsubst js2-ts-set-char-token-bounds (token)
5368 "Used when next token is one character."
5369 (setf (js2-token-beg token) (1- js2-ts-cursor)
5370 (js2-token-end token) js2-ts-cursor))
5371
5372 (defsubst js2-ts-return (token type)
5373 "Update the `end' and `type' slots of TOKEN,
5374 then throw `return' with value TYPE."
5375 (setf (js2-token-end token) js2-ts-cursor
5376 (js2-token-type token) type)
5377 (throw 'return type))
5378
5379 (defun js2-x-digit-to-int (c accumulator)
5380 "Build up a hex number.
5381 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5382 corresponding number. Otherwise return -1."
5383 (catch 'return
5384 (catch 'check
5385 ;; Use 0..9 < A..Z < a..z
5386 (cond
5387 ((<= c ?9)
5388 (decf c ?0)
5389 (if (<= 0 c)
5390 (throw 'check nil)))
5391 ((<= c ?F)
5392 (when (<= ?A c)
5393 (decf c (- ?A 10))
5394 (throw 'check nil)))
5395 ((<= c ?f)
5396 (when (<= ?a c)
5397 (decf c (- ?a 10))
5398 (throw 'check nil))))
5399 (throw 'return -1))
5400 (logior c (lsh accumulator 4))))
5401
5402 (defun js2-get-token ()
5403 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5404 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5405 next saved token.
5406
5407 This function will not return a newline (js2-EOL) - instead, it
5408 gobbles newlines until it finds a non-newline token. Call
5409 `js2-peek-token-or-eol' when you care about newlines.
5410
5411 This function will also not return a js2-COMMENT. Instead, it
5412 records comments found in `js2-scanned-comments'. If the token
5413 returned by this function immediately follows a jsdoc comment,
5414 the token is flagged as such."
5415 (if (zerop js2-ti-lookahead)
5416 (js2-get-token-internal)
5417 (decf js2-ti-lookahead)
5418 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5419 (let ((tt (js2-current-token-type)))
5420 (assert (not (= tt js2-EOL)))
5421 tt)))
5422
5423 (defun js2-unget-token ()
5424 (assert (< js2-ti-lookahead js2-ti-max-lookahead))
5425 (incf js2-ti-lookahead)
5426 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5427
5428 (defun js2-get-token-internal ()
5429 (let* ((token (js2-get-token-internal-1)) ; call scanner
5430 (tt (js2-token-type token))
5431 saw-eol
5432 face)
5433 ;; process comments
5434 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5435 (if (= tt js2-EOL)
5436 (setq saw-eol t)
5437 (setq saw-eol nil)
5438 (when js2-record-comments
5439 (js2-record-comment token)))
5440 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5441 (setq token (js2-get-token-internal-1) ; call scanner again
5442 tt (js2-token-type token)))
5443
5444 (when saw-eol
5445 (setf (js2-token-follows-eol-p token) t))
5446
5447 ;; perform lexical fontification as soon as token is scanned
5448 (when js2-parse-ide-mode
5449 (cond
5450 ((minusp tt)
5451 (js2-record-face 'js2-error token))
5452 ((setq face (aref js2-kwd-tokens tt))
5453 (js2-record-face face token))
5454 ((and (= tt js2-NAME)
5455 (equal (js2-token-string token) "undefined"))
5456 (js2-record-face 'font-lock-constant-face token))))
5457 tt))
5458
5459 (defun js2-get-token-internal-1 ()
5460 "Return next JavaScript token type, an int such as js2-RETURN.
5461 During operation, creates an instance of `js2-token' struct, sets
5462 its relevant fields and puts it into `js2-ti-tokens'."
5463 (let (c c1 identifier-start is-unicode-escape-start
5464 contains-escape escape-val str result base
5465 quote-char val look-for-slash continue tt
5466 (token (js2-new-token 0)))
5467 (setq
5468 tt
5469 (catch 'return
5470 (while t
5471 ;; Eat whitespace, possibly sensitive to newlines.
5472 (setq continue t)
5473 (while continue
5474 (setq c (js2-get-char))
5475 (cond
5476 ((eq c js2-EOF_CHAR)
5477 (js2-unget-char)
5478 (js2-ts-set-char-token-bounds token)
5479 (throw 'return js2-EOF))
5480 ((eq c ?\n)
5481 (js2-ts-set-char-token-bounds token)
5482 (setq js2-ts-dirty-line nil)
5483 (throw 'return js2-EOL))
5484 ((not (js2-js-space-p c))
5485 (if (/= c ?-) ; in case end of HTML comment
5486 (setq js2-ts-dirty-line t))
5487 (setq continue nil))))
5488 ;; Assume the token will be 1 char - fixed up below.
5489 (js2-ts-set-char-token-bounds token)
5490 (when (eq c ?@)
5491 (throw 'return js2-XMLATTR))
5492 ;; identifier/keyword/instanceof?
5493 ;; watch out for starting with a <backslash>
5494 (cond
5495 ((eq c ?\\)
5496 (setq c (js2-get-char))
5497 (if (eq c ?u)
5498 (setq identifier-start t
5499 is-unicode-escape-start t
5500 js2-ts-string-buffer nil)
5501 (setq identifier-start nil)
5502 (js2-unget-char)
5503 (setq c ?\\)))
5504 (t
5505 (when (setq identifier-start (js2-identifier-start-p c))
5506 (setq js2-ts-string-buffer nil)
5507 (js2-add-to-string c))))
5508 (when identifier-start
5509 (setq contains-escape is-unicode-escape-start)
5510 (catch 'break
5511 (while t
5512 (if is-unicode-escape-start
5513 ;; strictly speaking we should probably push-back
5514 ;; all the bad characters if the <backslash>uXXXX
5515 ;; sequence is malformed. But since there isn't a
5516 ;; correct context(is there?) for a bad Unicode
5517 ;; escape sequence in an identifier, we can report
5518 ;; an error here.
5519 (progn
5520 (setq escape-val 0)
5521 (dotimes (_ 4)
5522 (setq c (js2-get-char)
5523 escape-val (js2-x-digit-to-int c escape-val))
5524 ;; Next check takes care of c < 0 and bad escape
5525 (if (minusp escape-val)
5526 (throw 'break nil)))
5527 (if (minusp escape-val)
5528 (js2-report-scan-error "msg.invalid.escape" t))
5529 (js2-add-to-string escape-val)
5530 (setq is-unicode-escape-start nil))
5531 (setq c (js2-get-char))
5532 (cond
5533 ((eq c ?\\)
5534 (setq c (js2-get-char))
5535 (if (eq c ?u)
5536 (setq is-unicode-escape-start t
5537 contains-escape t)
5538 (js2-report-scan-error "msg.illegal.character" t)))
5539 (t
5540 (if (or (eq c js2-EOF_CHAR)
5541 (not (js2-identifier-part-p c)))
5542 (throw 'break nil))
5543 (js2-add-to-string c))))))
5544 (js2-unget-char)
5545 (setf str (js2-collect-string js2-ts-string-buffer)
5546 (js2-token-end token) js2-ts-cursor)
5547 ;; FIXME: Invalid in ES5 and ES6, see
5548 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5549 ;; Probably should just drop this conditional.
5550 (unless contains-escape
5551 ;; OPT we shouldn't have to make a string (object!) to
5552 ;; check if it's a keyword.
5553 ;; Return the corresponding token if it's a keyword
5554 (when (setq result (js2-string-to-keyword str))
5555 (if (and (< js2-language-version 170)
5556 (memq result '(js2-LET js2-YIELD)))
5557 ;; LET and YIELD are tokens only in 1.7 and later
5558 (setq result 'js2-NAME))
5559 (when (eq result 'js2-RESERVED)
5560 (setf (js2-token-string token) str))
5561 (throw 'return (js2-tt-code result))))
5562 ;; If we want to intern these as Rhino does, just use (intern str)
5563 (setf (js2-token-string token) str)
5564 (throw 'return js2-NAME)) ; end identifier/kwd check
5565 ;; is it a number?
5566 (when (or (js2-digit-p c)
5567 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5568 (setq js2-ts-string-buffer nil
5569 base 10)
5570 (when (eq c ?0)
5571 (setq c (js2-get-char))
5572 (cond
5573 ((or (eq c ?x) (eq c ?X))
5574 (setq base 16)
5575 (setq c (js2-get-char)))
5576 ((and (or (eq c ?b) (eq c ?B))
5577 (>= js2-language-version 200))
5578 (setq base 2)
5579 (setq c (js2-get-char)))
5580 ((and (or (eq c ?o) (eq c ?O))
5581 (>= js2-language-version 200))
5582 (setq base 8)
5583 (setq c (js2-get-char)))
5584 ((js2-digit-p c)
5585 (setq base 'maybe-8))
5586 (t
5587 (js2-add-to-string ?0))))
5588 (cond
5589 ((eq base 16)
5590 (if (> 0 (js2-x-digit-to-int c 0))
5591 (js2-report-scan-error "msg.missing.hex.digits")
5592 (while (<= 0 (js2-x-digit-to-int c 0))
5593 (js2-add-to-string c)
5594 (setq c (js2-get-char)))))
5595 ((eq base 2)
5596 (if (not (memq c '(?0 ?1)))
5597 (js2-report-scan-error "msg.missing.binary.digits")
5598 (while (memq c '(?0 ?1))
5599 (js2-add-to-string c)
5600 (setq c (js2-get-char)))))
5601 ((eq base 8)
5602 (if (or (> ?0 c) (< ?7 c))
5603 (js2-report-scan-error "msg.missing.octal.digits")
5604 (while (and (<= ?0 c) (>= ?7 c))
5605 (js2-add-to-string c)
5606 (setq c (js2-get-char)))))
5607 (t
5608 (while (and (<= ?0 c) (<= c ?9))
5609 ;; We permit 08 and 09 as decimal numbers, which
5610 ;; makes our behavior a superset of the ECMA
5611 ;; numeric grammar. We might not always be so
5612 ;; permissive, so we warn about it.
5613 (when (and (eq base 'maybe-8) (>= c ?8))
5614 (js2-report-warning "msg.bad.octal.literal"
5615 (if (eq c ?8) "8" "9"))
5616 (setq base 10))
5617 (js2-add-to-string c)
5618 (setq c (js2-get-char)))
5619 (when (eq base 'maybe-8)
5620 (setq base 8))))
5621 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5622 (when (eq c ?.)
5623 (loop do
5624 (js2-add-to-string c)
5625 (setq c (js2-get-char))
5626 while (js2-digit-p c)))
5627 (when (memq c '(?e ?E))
5628 (js2-add-to-string c)
5629 (setq c (js2-get-char))
5630 (when (memq c '(?+ ?-))
5631 (js2-add-to-string c)
5632 (setq c (js2-get-char)))
5633 (unless (js2-digit-p c)
5634 (js2-report-scan-error "msg.missing.exponent" t))
5635 (loop do
5636 (js2-add-to-string c)
5637 (setq c (js2-get-char))
5638 while (js2-digit-p c))))
5639 (js2-unget-char)
5640 (let ((str (js2-set-string-from-buffer token)))
5641 (setf (js2-token-number token)
5642 (js2-string-to-number str base)))
5643 (throw 'return js2-NUMBER))
5644 ;; is it a string?
5645 (when (memq c '(?\" ?\'))
5646 ;; We attempt to accumulate a string the fast way, by
5647 ;; building it directly out of the reader. But if there
5648 ;; are any escaped characters in the string, we revert to
5649 ;; building it out of a string buffer.
5650 (setq quote-char c
5651 js2-ts-string-buffer nil
5652 c (js2-get-char))
5653 (catch 'break
5654 (while (/= c quote-char)
5655 (catch 'continue
5656 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5657 (js2-unget-char)
5658 (setf (js2-token-end token) js2-ts-cursor)
5659 (js2-report-error "msg.unterminated.string.lit")
5660 (throw 'return js2-STRING))
5661 (when (eq c ?\\)
5662 ;; We've hit an escaped character
5663 (setq c (js2-get-char))
5664 (case c
5665 (?b (setq c ?\b))
5666 (?f (setq c ?\f))
5667 (?n (setq c ?\n))
5668 (?r (setq c ?\r))
5669 (?t (setq c ?\t))
5670 (?v (setq c ?\v))
5671 (?u
5672 (setq c1 (js2-read-unicode-escape))
5673 (if js2-parse-ide-mode
5674 (if c1
5675 (progn
5676 ;; just copy the string in IDE-mode
5677 (js2-add-to-string ?\\)
5678 (js2-add-to-string ?u)
5679 (dotimes (_ 3)
5680 (js2-add-to-string (js2-get-char)))
5681 (setq c (js2-get-char))) ; added at end of loop
5682 ;; flag it as an invalid escape
5683 (js2-report-warning "msg.invalid.escape"
5684 nil (- js2-ts-cursor 2) 6))
5685 ;; Get 4 hex digits; if the u escape is not
5686 ;; followed by 4 hex digits, use 'u' + the
5687 ;; literal character sequence that follows.
5688 (js2-add-to-string ?u)
5689 (setq escape-val 0)
5690 (dotimes (_ 4)
5691 (setq c (js2-get-char)
5692 escape-val (js2-x-digit-to-int c escape-val))
5693 (if (minusp escape-val)
5694 (throw 'continue nil))
5695 (js2-add-to-string c))
5696 ;; prepare for replace of stored 'u' sequence by escape value
5697 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5698 c escape-val)))
5699 (?x
5700 ;; Get 2 hex digits, defaulting to 'x'+literal
5701 ;; sequence, as above.
5702 (setq c (js2-get-char)
5703 escape-val (js2-x-digit-to-int c 0))
5704 (if (minusp escape-val)
5705 (progn
5706 (js2-add-to-string ?x)
5707 (throw 'continue nil))
5708 (setq c1 c
5709 c (js2-get-char)
5710 escape-val (js2-x-digit-to-int c escape-val))
5711 (if (minusp escape-val)
5712 (progn
5713 (js2-add-to-string ?x)
5714 (js2-add-to-string c1)
5715 (throw 'continue nil))
5716 ;; got 2 hex digits
5717 (setq c escape-val))))
5718 (?\n
5719 ;; Remove line terminator after escape to follow
5720 ;; SpiderMonkey and C/C++
5721 (setq c (js2-get-char))
5722 (throw 'continue nil))
5723 (t
5724 (when (and (<= ?0 c) (< c ?8))
5725 (setq val (- c ?0)
5726 c (js2-get-char))
5727 (when (and (<= ?0 c) (< c ?8))
5728 (setq val (- (+ (* 8 val) c) ?0)
5729 c (js2-get-char))
5730 (when (and (<= ?0 c)
5731 (< c ?8)
5732 (< val #o37))
5733 ;; c is 3rd char of octal sequence only
5734 ;; if the resulting val <= 0377
5735 (setq val (- (+ (* 8 val) c) ?0)
5736 c (js2-get-char))))
5737 (js2-unget-char)
5738 (setq c val)))))
5739 (js2-add-to-string c)
5740 (setq c (js2-get-char)))))
5741 (js2-set-string-from-buffer token)
5742 (throw 'return js2-STRING))
5743 (js2-ts-return token
5744 (case c
5745 (?\;
5746 (throw 'return js2-SEMI))
5747 (?\[
5748 (throw 'return js2-LB))
5749 (?\]
5750 (throw 'return js2-RB))
5751 (?{
5752 (throw 'return js2-LC))
5753 (?}
5754 (throw 'return js2-RC))
5755 (?\(
5756 (throw 'return js2-LP))
5757 (?\)
5758 (throw 'return js2-RP))
5759 (?,
5760 (throw 'return js2-COMMA))
5761 (??
5762 (throw 'return js2-HOOK))
5763 (?:
5764 (if (js2-match-char ?:)
5765 js2-COLONCOLON
5766 (throw 'return js2-COLON)))
5767 (?.
5768 (if (js2-match-char ?.)
5769 (if (js2-match-char ?.)
5770 js2-TRIPLEDOT js2-DOTDOT)
5771 (if (js2-match-char ?\()
5772 js2-DOTQUERY
5773 (throw 'return js2-DOT))))
5774 (?|
5775 (if (js2-match-char ?|)
5776 (throw 'return js2-OR)
5777 (if (js2-match-char ?=)
5778 js2-ASSIGN_BITOR
5779 (throw 'return js2-BITOR))))
5780 (?^
5781 (if (js2-match-char ?=)
5782 js2-ASSIGN_BITOR
5783 (throw 'return js2-BITXOR)))
5784 (?&
5785 (if (js2-match-char ?&)
5786 (throw 'return js2-AND)
5787 (if (js2-match-char ?=)
5788 js2-ASSIGN_BITAND
5789 (throw 'return js2-BITAND))))
5790 (?=
5791 (if (js2-match-char ?=)
5792 (if (js2-match-char ?=)
5793 js2-SHEQ
5794 (throw 'return js2-EQ))
5795 (if (js2-match-char ?>)
5796 (js2-ts-return token js2-ARROW)
5797 (throw 'return js2-ASSIGN))))
5798 (?!
5799 (if (js2-match-char ?=)
5800 (if (js2-match-char ?=)
5801 js2-SHNE
5802 js2-NE)
5803 (throw 'return js2-NOT)))
5804 (?<
5805 ;; NB:treat HTML begin-comment as comment-till-eol
5806 (when (js2-match-char ?!)
5807 (when (js2-match-char ?-)
5808 (when (js2-match-char ?-)
5809 (js2-skip-line)
5810 (setf (js2-token-comment-type (js2-current-token)) 'html)
5811 (throw 'return js2-COMMENT)))
5812 (js2-unget-char))
5813 (if (js2-match-char ?<)
5814 (if (js2-match-char ?=)
5815 js2-ASSIGN_LSH
5816 js2-LSH)
5817 (if (js2-match-char ?=)
5818 js2-LE
5819 (throw 'return js2-LT))))
5820 (?>
5821 (if (js2-match-char ?>)
5822 (if (js2-match-char ?>)
5823 (if (js2-match-char ?=)
5824 js2-ASSIGN_URSH
5825 js2-URSH)
5826 (if (js2-match-char ?=)
5827 js2-ASSIGN_RSH
5828 js2-RSH))
5829 (if (js2-match-char ?=)
5830 js2-GE
5831 (throw 'return js2-GT))))
5832 (?*
5833 (if (js2-match-char ?=)
5834 js2-ASSIGN_MUL
5835 (throw 'return js2-MUL)))
5836 (?/
5837 ;; is it a // comment?
5838 (when (js2-match-char ?/)
5839 (setf (js2-token-beg token) (- js2-ts-cursor 2))
5840 (js2-skip-line)
5841 (setf (js2-token-comment-type token) 'line)
5842 ;; include newline so highlighting goes to end of window
5843 (incf (js2-token-end token))
5844 (throw 'return js2-COMMENT))
5845 ;; is it a /* comment?
5846 (when (js2-match-char ?*)
5847 (setf look-for-slash nil
5848 (js2-token-beg token) (- js2-ts-cursor 2)
5849 (js2-token-comment-type token)
5850 (if (js2-match-char ?*)
5851 (progn
5852 (setq look-for-slash t)
5853 'jsdoc)
5854 'block))
5855 (while t
5856 (setq c (js2-get-char))
5857 (cond
5858 ((eq c js2-EOF_CHAR)
5859 (setf (js2-token-end token) (1- js2-ts-cursor))
5860 (js2-report-error "msg.unterminated.comment")
5861 (throw 'return js2-COMMENT))
5862 ((eq c ?*)
5863 (setq look-for-slash t))
5864 ((eq c ?/)
5865 (if look-for-slash
5866 (js2-ts-return token js2-COMMENT)))
5867 (t
5868 (setf look-for-slash nil
5869 (js2-token-end token) js2-ts-cursor)))))
5870 (if (js2-match-char ?=)
5871 js2-ASSIGN_DIV
5872 (throw 'return js2-DIV)))
5873 (?#
5874 (when js2-skip-preprocessor-directives
5875 (js2-skip-line)
5876 (setf (js2-token-comment-type token) 'preprocessor
5877 (js2-token-end token) js2-ts-cursor)
5878 (throw 'return js2-COMMENT))
5879 (throw 'return js2-ERROR))
5880 (?%
5881 (if (js2-match-char ?=)
5882 js2-ASSIGN_MOD
5883 (throw 'return js2-MOD)))
5884 (?~
5885 (throw 'return js2-BITNOT))
5886 (?+
5887 (if (js2-match-char ?=)
5888 js2-ASSIGN_ADD
5889 (if (js2-match-char ?+)
5890 js2-INC
5891 (throw 'return js2-ADD))))
5892 (?-
5893 (cond
5894 ((js2-match-char ?=)
5895 (setq c js2-ASSIGN_SUB))
5896 ((js2-match-char ?-)
5897 (unless js2-ts-dirty-line
5898 ;; treat HTML end-comment after possible whitespace
5899 ;; after line start as comment-until-eol
5900 (when (js2-match-char ?>)
5901 (js2-skip-line)
5902 (setf (js2-token-comment-type (js2-current-token)) 'html)
5903 (throw 'return js2-COMMENT)))
5904 (setq c js2-DEC))
5905 (t
5906 (setq c js2-SUB)))
5907 (setq js2-ts-dirty-line t)
5908 c)
5909 (otherwise
5910 (js2-report-scan-error "msg.illegal.character")))))))
5911 (setf (js2-token-type token) tt)
5912 token))
5913
5914 (defsubst js2-string-to-number (str base)
5915 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5916 (condition-case nil
5917 (string-to-number str base)
5918 (overflow-error -1)))
5919
5920 (defun js2-read-regexp (start-tt)
5921 "Called by parser when it gets / or /= in literal context."
5922 (let (c err
5923 in-class ; inside a '[' .. ']' character-class
5924 flags
5925 (continue t)
5926 (token (js2-new-token 0)))
5927 (setq js2-ts-string-buffer nil)
5928 (if (eq start-tt js2-ASSIGN_DIV)
5929 ;; mis-scanned /=
5930 (js2-add-to-string ?=)
5931 (if (not (eq start-tt js2-DIV))
5932 (error "failed assertion")))
5933 (while (and (not err)
5934 (or (/= (setq c (js2-get-char)) ?/)
5935 in-class))
5936 (cond
5937 ((or (= c ?\n)
5938 (= c js2-EOF_CHAR))
5939 (setf (js2-token-end token) (1- js2-ts-cursor)
5940 err t
5941 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
5942 (js2-report-error "msg.unterminated.re.lit"))
5943 (t (cond
5944 ((= c ?\\)
5945 (js2-add-to-string c)
5946 (setq c (js2-get-char)))
5947 ((= c ?\[)
5948 (setq in-class t))
5949 ((= c ?\])
5950 (setq in-class nil)))
5951 (js2-add-to-string c))))
5952 (unless err
5953 (while continue
5954 (cond
5955 ((js2-match-char ?g)
5956 (push ?g flags))
5957 ((js2-match-char ?i)
5958 (push ?i flags))
5959 ((js2-match-char ?m)
5960 (push ?m flags))
5961 ((and (js2-match-char ?u)
5962 (>= js2-language-version 200))
5963 (push ?u flags))
5964 ((and (js2-match-char ?y)
5965 (>= js2-language-version 200))
5966 (push ?y flags))
5967 (t
5968 (setq continue nil))))
5969 (if (js2-alpha-p (js2-peek-char))
5970 (js2-report-scan-error "msg.invalid.re.flag" t
5971 js2-ts-cursor 1))
5972 (js2-set-string-from-buffer token))
5973 (js2-collect-string flags)))
5974
5975 (defun js2-get-first-xml-token ()
5976 (setq js2-ts-xml-open-tags-count 0
5977 js2-ts-is-xml-attribute nil
5978 js2-ts-xml-is-tag-content nil)
5979 (js2-unget-char)
5980 (js2-get-next-xml-token))
5981
5982 (defun js2-xml-discard-string (token)
5983 "Throw away the string in progress and flag an XML parse error."
5984 (setf js2-ts-string-buffer nil
5985 (js2-token-string token) nil)
5986 (js2-report-scan-error "msg.XML.bad.form" t))
5987
5988 (defun js2-get-next-xml-token ()
5989 (setq js2-ts-string-buffer nil) ; for recording the XML
5990 (let ((token (js2-new-token 0))
5991 c result)
5992 (setq result
5993 (catch 'return
5994 (while t
5995 (setq c (js2-get-char))
5996 (cond
5997 ((= c js2-EOF_CHAR)
5998 (throw 'return js2-ERROR))
5999 (js2-ts-xml-is-tag-content
6000 (case c
6001 (?>
6002 (js2-add-to-string c)
6003 (setq js2-ts-xml-is-tag-content nil
6004 js2-ts-is-xml-attribute nil))
6005 (?/
6006 (js2-add-to-string c)
6007 (when (eq ?> (js2-peek-char))
6008 (setq c (js2-get-char))
6009 (js2-add-to-string c)
6010 (setq js2-ts-xml-is-tag-content nil)
6011 (decf js2-ts-xml-open-tags-count)))
6012 (?{
6013 (js2-unget-char)
6014 (js2-set-string-from-buffer token)
6015 (throw 'return js2-XML))
6016 ((?\' ?\")
6017 (js2-add-to-string c)
6018 (unless (js2-read-quoted-string c token)
6019 (throw 'return js2-ERROR)))
6020 (?=
6021 (js2-add-to-string c)
6022 (setq js2-ts-is-xml-attribute t))
6023 ((? ?\t ?\r ?\n)
6024 (js2-add-to-string c))
6025 (t
6026 (js2-add-to-string c)
6027 (setq js2-ts-is-xml-attribute nil)))
6028 (when (and (not js2-ts-xml-is-tag-content)
6029 (zerop js2-ts-xml-open-tags-count))
6030 (js2-set-string-from-buffer token)
6031 (throw 'return js2-XMLEND)))
6032 (t
6033 ;; else not tag content
6034 (case c
6035 (?<
6036 (js2-add-to-string c)
6037 (setq c (js2-peek-char))
6038 (case c
6039 (?!
6040 (setq c (js2-get-char)) ;; skip !
6041 (js2-add-to-string c)
6042 (setq c (js2-peek-char))
6043 (case c
6044 (?-
6045 (setq c (js2-get-char)) ;; skip -
6046 (js2-add-to-string c)
6047 (if (eq c ?-)
6048 (progn
6049 (js2-add-to-string c)
6050 (unless (js2-read-xml-comment token)
6051 (throw 'return js2-ERROR)))
6052 (js2-xml-discard-string token)
6053 (throw 'return js2-ERROR)))
6054 (?\[
6055 (setq c (js2-get-char)) ;; skip [
6056 (js2-add-to-string c)
6057 (if (and (= (js2-get-char) ?C)
6058 (= (js2-get-char) ?D)
6059 (= (js2-get-char) ?A)
6060 (= (js2-get-char) ?T)
6061 (= (js2-get-char) ?A)
6062 (= (js2-get-char) ?\[))
6063 (progn
6064 (js2-add-to-string ?C)
6065 (js2-add-to-string ?D)
6066 (js2-add-to-string ?A)
6067 (js2-add-to-string ?T)
6068 (js2-add-to-string ?A)
6069 (js2-add-to-string ?\[)
6070 (unless (js2-read-cdata token)
6071 (throw 'return js2-ERROR)))
6072 (js2-xml-discard-string token)
6073 (throw 'return js2-ERROR)))
6074 (t
6075 (unless (js2-read-entity token)
6076 (throw 'return js2-ERROR))))
6077 ;; Allow bare CDATA section, e.g.:
6078 ;; let xml = <![CDATA[ foo bar baz ]]>;
6079 (when (zerop js2-ts-xml-open-tags-count)
6080 (throw 'return js2-XMLEND)))
6081 (??
6082 (setq c (js2-get-char)) ;; skip ?
6083 (js2-add-to-string c)
6084 (unless (js2-read-PI token)
6085 (throw 'return js2-ERROR)))
6086 (?/
6087 ;; end tag
6088 (setq c (js2-get-char)) ;; skip /
6089 (js2-add-to-string c)
6090 (when (zerop js2-ts-xml-open-tags-count)
6091 (js2-xml-discard-string token)
6092 (throw 'return js2-ERROR))
6093 (setq js2-ts-xml-is-tag-content t)
6094 (decf js2-ts-xml-open-tags-count))
6095 (t
6096 ;; start tag
6097 (setq js2-ts-xml-is-tag-content t)
6098 (incf js2-ts-xml-open-tags-count))))
6099 (?{
6100 (js2-unget-char)
6101 (js2-set-string-from-buffer token)
6102 (throw 'return js2-XML))
6103 (t
6104 (js2-add-to-string c))))))))
6105 (setf (js2-token-end token) js2-ts-cursor)
6106 (setf (js2-token-type token) result)
6107 result))
6108
6109 (defun js2-read-quoted-string (quote token)
6110 (let (c)
6111 (catch 'return
6112 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6113 (js2-add-to-string c)
6114 (if (eq c quote)
6115 (throw 'return t)))
6116 (js2-xml-discard-string token) ;; throw away string in progress
6117 nil)))
6118
6119 (defun js2-read-xml-comment (token)
6120 (let ((c (js2-get-char)))
6121 (catch 'return
6122 (while (/= c js2-EOF_CHAR)
6123 (catch 'continue
6124 (js2-add-to-string c)
6125 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6126 (setq c (js2-get-char))
6127 (js2-add-to-string c)
6128 (if (eq (js2-peek-char) ?>)
6129 (progn
6130 (setq c (js2-get-char)) ;; skip >
6131 (js2-add-to-string c)
6132 (throw 'return t))
6133 (throw 'continue nil)))
6134 (setq c (js2-get-char))))
6135 (js2-xml-discard-string token)
6136 nil)))
6137
6138 (defun js2-read-cdata (token)
6139 (let ((c (js2-get-char)))
6140 (catch 'return
6141 (while (/= c js2-EOF_CHAR)
6142 (catch 'continue
6143 (js2-add-to-string c)
6144 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6145 (setq c (js2-get-char))
6146 (js2-add-to-string c)
6147 (if (eq (js2-peek-char) ?>)
6148 (progn
6149 (setq c (js2-get-char)) ;; Skip >
6150 (js2-add-to-string c)
6151 (throw 'return t))
6152 (throw 'continue nil)))
6153 (setq c (js2-get-char))))
6154 (js2-xml-discard-string token)
6155 nil)))
6156
6157 (defun js2-read-entity (token)
6158 (let ((decl-tags 1)
6159 c)
6160 (catch 'return
6161 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6162 (js2-add-to-string c)
6163 (case c
6164 (?<
6165 (incf decl-tags))
6166 (?>
6167 (decf decl-tags)
6168 (if (zerop decl-tags)
6169 (throw 'return t)))))
6170 (js2-xml-discard-string token)
6171 nil)))
6172
6173 (defun js2-read-PI (token)
6174 "Scan an XML processing instruction."
6175 (let (c)
6176 (catch 'return
6177 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6178 (js2-add-to-string c)
6179 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6180 (setq c (js2-get-char)) ;; Skip >
6181 (js2-add-to-string c)
6182 (throw 'return t)))
6183 (js2-xml-discard-string token)
6184 nil)))
6185
6186 ;;; Highlighting
6187
6188 (defun js2-set-face (beg end face &optional record)
6189 "Fontify a region. If RECORD is non-nil, record for later."
6190 (when (plusp js2-highlight-level)
6191 (setq beg (min (point-max) beg)
6192 beg (max (point-min) beg)
6193 end (min (point-max) end)
6194 end (max (point-min) end))
6195 (if record
6196 (push (list beg end face) js2-mode-fontifications)
6197 (put-text-property beg end 'font-lock-face face))))
6198
6199 (defsubst js2-clear-face (beg end)
6200 (remove-text-properties beg end '(font-lock-face nil
6201 help-echo nil
6202 point-entered nil
6203 c-in-sws nil)))
6204
6205 (defconst js2-ecma-global-props
6206 (concat "^"
6207 (regexp-opt
6208 '("Infinity" "NaN" "undefined" "arguments") t)
6209 "$")
6210 "Value properties of the Ecma-262 Global Object.
6211 Shown at or above `js2-highlight-level' 2.")
6212
6213 ;; might want to add the name "arguments" to this list?
6214 (defconst js2-ecma-object-props
6215 (concat "^"
6216 (regexp-opt
6217 '("prototype" "__proto__" "__parent__") t)
6218 "$")
6219 "Value properties of the Ecma-262 Object constructor.
6220 Shown at or above `js2-highlight-level' 2.")
6221
6222 (defconst js2-ecma-global-funcs
6223 (concat
6224 "^"
6225 (regexp-opt
6226 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6227 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6228 "$")
6229 "Function properties of the Ecma-262 Global object.
6230 Shown at or above `js2-highlight-level' 2.")
6231
6232 (defconst js2-ecma-number-props
6233 (concat "^"
6234 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6235 "NEGATIVE_INFINITY"
6236 "POSITIVE_INFINITY") t)
6237 "$")
6238 "Properties of the Ecma-262 Number constructor.
6239 Shown at or above `js2-highlight-level' 2.")
6240
6241 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6242 "Properties of the Ecma-262 Date constructor.
6243 Shown at or above `js2-highlight-level' 2.")
6244
6245 (defconst js2-ecma-math-props
6246 (concat "^"
6247 (regexp-opt
6248 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6249 t)
6250 "$")
6251 "Properties of the Ecma-262 Math object.
6252 Shown at or above `js2-highlight-level' 2.")
6253
6254 (defconst js2-ecma-math-funcs
6255 (concat "^"
6256 (regexp-opt
6257 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6258 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6259 "$")
6260 "Function properties of the Ecma-262 Math object.
6261 Shown at or above `js2-highlight-level' 2.")
6262
6263 (defconst js2-ecma-function-props
6264 (concat
6265 "^"
6266 (regexp-opt
6267 '(;; properties of the Object prototype object
6268 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6269 "toLocaleString" "toString" "valueOf"
6270 ;; properties of the Function prototype object
6271 "apply" "call"
6272 ;; properties of the Array prototype object
6273 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6274 "splice" "unshift"
6275 ;; properties of the String prototype object
6276 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6277 "localeCompare" "match" "replace" "search" "split" "substring"
6278 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6279 "toUpperCase"
6280 ;; properties of the Number prototype object
6281 "toExponential" "toFixed" "toPrecision"
6282 ;; properties of the Date prototype object
6283 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6284 "getMinutes" "getMonth" "getSeconds" "getTime"
6285 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6286 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6287 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6288 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6289 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6290 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6291 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6292 "toTimeString" "toUTCString"
6293 ;; properties of the RegExp prototype object
6294 "exec" "test"
6295 ;; properties of the JSON prototype object
6296 "parse" "stringify"
6297 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6298 "toSource" "__defineGetter__" "__defineSetter__"
6299 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6300 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6301 t)
6302 "$")
6303 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6304 Shown at or above `js2-highlight-level' 3.")
6305
6306 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6307 (let ((target-name (and target
6308 (js2-name-node-p target)
6309 (js2-name-node-name target)))
6310 (prop-name (if prop (js2-name-node-name prop)))
6311 (level2 (>= js2-highlight-level 2))
6312 (level3 (>= js2-highlight-level 3)))
6313 (when level2
6314 (let ((face
6315 (if call-p
6316 (cond
6317 ((and target prop)
6318 (cond
6319 ((and level3 (string-match js2-ecma-function-props prop-name))
6320 'font-lock-builtin-face)
6321 ((and target-name prop)
6322 (cond
6323 ((string= target-name "Date")
6324 (if (string-match js2-ecma-date-props prop-name)
6325 'font-lock-builtin-face))
6326 ((string= target-name "Math")
6327 (if (string-match js2-ecma-math-funcs prop-name)
6328 'font-lock-builtin-face))))))
6329 (prop
6330 (if (string-match js2-ecma-global-funcs prop-name)
6331 'font-lock-builtin-face)))
6332 (cond
6333 ((and target prop)
6334 (cond
6335 ((string= target-name "Number")
6336 (if (string-match js2-ecma-number-props prop-name)
6337 'font-lock-constant-face))
6338 ((string= target-name "Math")
6339 (if (string-match js2-ecma-math-props prop-name)
6340 'font-lock-constant-face))))
6341 (prop
6342 (if (string-match js2-ecma-object-props prop-name)
6343 'font-lock-constant-face))))))
6344 (when face
6345 (let ((pos (+ (js2-node-pos parent) ; absolute
6346 (js2-node-pos prop)))) ; relative
6347 (js2-set-face pos
6348 (+ pos (js2-node-len prop))
6349 face 'record)))))))
6350
6351 (defun js2-parse-highlight-member-expr-node (node)
6352 "Perform syntax highlighting of EcmaScript built-in properties.
6353 The variable `js2-highlight-level' governs this highighting."
6354 (let (face target prop name pos end parent call-p callee)
6355 (cond
6356 ;; case 1: simple name, e.g. foo
6357 ((js2-name-node-p node)
6358 (setq name (js2-name-node-name node))
6359 ;; possible for name to be nil in rare cases - saw it when
6360 ;; running js2-mode on an elisp buffer. Might as well try to
6361 ;; make it so js2-mode never barfs.
6362 (when name
6363 (setq face (if (string-match js2-ecma-global-props name)
6364 'font-lock-constant-face))
6365 (when face
6366 (setq pos (js2-node-pos node)
6367 end (+ pos (js2-node-len node)))
6368 (js2-set-face pos end face 'record))))
6369 ;; case 2: property access or function call
6370 ((or (js2-prop-get-node-p node)
6371 ;; highlight function call if expr is a prop-get node
6372 ;; or a plain name (i.e. unqualified function call)
6373 (and (setq call-p (js2-call-node-p node))
6374 (setq callee (js2-call-node-target node)) ; separate setq!
6375 (or (js2-prop-get-node-p callee)
6376 (js2-name-node-p callee))))
6377 (setq parent node
6378 node (if call-p callee node))
6379 (if (and call-p (js2-name-node-p callee))
6380 (setq prop callee)
6381 (setq target (js2-prop-get-node-left node)
6382 prop (js2-prop-get-node-right node)))
6383 (cond
6384 ((js2-name-node-p prop)
6385 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6386 (js2-parse-highlight-prop-get parent target prop call-p))
6387 ((js2-name-node-p target)
6388 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6389 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6390
6391 (defun js2-parse-highlight-member-expr-fn-name (expr)
6392 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6393 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6394 We currently only handle the case where the last component is a prop-get
6395 of a simple name. Called before EXPR has a parent node."
6396 (let (pos
6397 (name (and (js2-prop-get-node-p expr)
6398 (js2-prop-get-node-right expr))))
6399 (when (js2-name-node-p name)
6400 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6401 (js2-node-pos name)))
6402 (+ pos (js2-node-len name))
6403 'font-lock-function-name-face
6404 'record))))
6405
6406 ;; source: http://jsdoc.sourceforge.net/
6407 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6408 ;; allows type specifications, and needs work before entering the wild.
6409
6410 (defconst js2-jsdoc-param-tag-regexp
6411 (concat "^\\s-*\\*+\\s-*\\(@"
6412 "\\(?:param\\|argument\\)"
6413 "\\)"
6414 "\\s-*\\({[^}]+}\\)?" ; optional type
6415 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6416 "\\>")
6417 "Matches jsdoc tags with optional type and optional param name.")
6418
6419 (defconst js2-jsdoc-typed-tag-regexp
6420 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6421 (regexp-opt
6422 '("enum"
6423 "extends"
6424 "field"
6425 "id"
6426 "implements"
6427 "lends"
6428 "mods"
6429 "requires"
6430 "return"
6431 "returns"
6432 "throw"
6433 "throws"))
6434 "\\)\\)\\s-*\\({[^}]+}\\)?")
6435 "Matches jsdoc tags with optional type.")
6436
6437 (defconst js2-jsdoc-arg-tag-regexp
6438 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6439 (regexp-opt
6440 '("alias"
6441 "augments"
6442 "borrows"
6443 "bug"
6444 "base"
6445 "config"
6446 "default"
6447 "define"
6448 "exception"
6449 "function"
6450 "member"
6451 "memberOf"
6452 "name"
6453 "namespace"
6454 "property"
6455 "since"
6456 "suppress"
6457 "this"
6458 "throws"
6459 "type"
6460 "version"))
6461 "\\)\\)\\s-+\\([^ \t]+\\)")
6462 "Matches jsdoc tags with a single argument.")
6463
6464 (defconst js2-jsdoc-empty-tag-regexp
6465 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6466 (regexp-opt
6467 '("addon"
6468 "author"
6469 "class"
6470 "const"
6471 "constant"
6472 "constructor"
6473 "constructs"
6474 "deprecated"
6475 "desc"
6476 "description"
6477 "event"
6478 "example"
6479 "exec"
6480 "export"
6481 "fileoverview"
6482 "final"
6483 "function"
6484 "hidden"
6485 "ignore"
6486 "implicitCast"
6487 "inheritDoc"
6488 "inner"
6489 "interface"
6490 "license"
6491 "noalias"
6492 "noshadow"
6493 "notypecheck"
6494 "override"
6495 "owner"
6496 "preserve"
6497 "preserveTry"
6498 "private"
6499 "protected"
6500 "public"
6501 "static"
6502 "supported"
6503 ))
6504 "\\)\\)\\s-*")
6505 "Matches empty jsdoc tags.")
6506
6507 (defconst js2-jsdoc-link-tag-regexp
6508 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6509 "Matches a jsdoc link or code tag.")
6510
6511 (defconst js2-jsdoc-see-tag-regexp
6512 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6513 "Matches a jsdoc @see tag.")
6514
6515 (defconst js2-jsdoc-html-tag-regexp
6516 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6517 "Matches a simple (no attributes) html start- or end-tag.")
6518
6519 (defun js2-jsdoc-highlight-helper ()
6520 (js2-set-face (match-beginning 1)
6521 (match-end 1)
6522 'js2-jsdoc-tag)
6523 (if (match-beginning 2)
6524 (if (save-excursion
6525 (goto-char (match-beginning 2))
6526 (= (char-after) ?{))
6527 (js2-set-face (1+ (match-beginning 2))
6528 (1- (match-end 2))
6529 'js2-jsdoc-type)
6530 (js2-set-face (match-beginning 2)
6531 (match-end 2)
6532 'js2-jsdoc-value)))
6533 (if (match-beginning 3)
6534 (js2-set-face (match-beginning 3)
6535 (match-end 3)
6536 'js2-jsdoc-value)))
6537
6538 (defun js2-highlight-jsdoc (ast)
6539 "Highlight doc comment tags."
6540 (let ((comments (js2-ast-root-comments ast))
6541 beg end)
6542 (save-excursion
6543 (dolist (node comments)
6544 (when (eq (js2-comment-node-format node) 'jsdoc)
6545 (setq beg (js2-node-abs-pos node)
6546 end (+ beg (js2-node-len node)))
6547 (save-restriction
6548 (narrow-to-region beg end)
6549 (dolist (re (list js2-jsdoc-param-tag-regexp
6550 js2-jsdoc-typed-tag-regexp
6551 js2-jsdoc-arg-tag-regexp
6552 js2-jsdoc-link-tag-regexp
6553 js2-jsdoc-see-tag-regexp
6554 js2-jsdoc-empty-tag-regexp))
6555 (goto-char beg)
6556 (while (re-search-forward re nil t)
6557 (js2-jsdoc-highlight-helper)))
6558 ;; simple highlighting for html tags
6559 (goto-char beg)
6560 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6561 (js2-set-face (match-beginning 1)
6562 (match-end 1)
6563 'js2-jsdoc-html-tag-delimiter)
6564 (js2-set-face (match-beginning 2)
6565 (match-end 2)
6566 'js2-jsdoc-html-tag-name)
6567 (js2-set-face (match-beginning 3)
6568 (match-end 3)
6569 'js2-jsdoc-html-tag-delimiter))))))))
6570
6571 (defun js2-highlight-assign-targets (_node left right)
6572 "Highlight function properties and external variables."
6573 (let (leftpos name)
6574 ;; highlight vars and props assigned function values
6575 (when (js2-function-node-p right)
6576 (cond
6577 ;; var foo = function() {...}
6578 ((js2-name-node-p left)
6579 (setq name left))
6580 ;; foo.bar.baz = function() {...}
6581 ((and (js2-prop-get-node-p left)
6582 (js2-name-node-p (js2-prop-get-node-right left)))
6583 (setq name (js2-prop-get-node-right left))))
6584 (when name
6585 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6586 (+ leftpos (js2-node-len name))
6587 'font-lock-function-name-face
6588 'record)))))
6589
6590 (defun js2-record-name-node (node)
6591 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6592 later. NODE must be a name node."
6593 (let ((leftpos (js2-node-abs-pos node)))
6594 (push (list node js2-current-scope
6595 leftpos
6596 (+ leftpos (js2-node-len node)))
6597 js2-recorded-identifiers)))
6598
6599 (defun js2-highlight-undeclared-vars ()
6600 "After entire parse is finished, look for undeclared variable references.
6601 We have to wait until entire buffer is parsed, since JavaScript permits var
6602 decls to occur after they're used.
6603
6604 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6605 it is considered declared."
6606 (let (name)
6607 (dolist (entry js2-recorded-identifiers)
6608 (destructuring-bind (name-node scope pos end) entry
6609 (setq name (js2-name-node-name name-node))
6610 (unless (or (member name js2-global-externs)
6611 (member name js2-default-externs)
6612 (member name js2-additional-externs)
6613 (js2-get-defining-scope scope name))
6614 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6615 'js2-external-variable))))
6616 (setq js2-recorded-identifiers nil)))
6617
6618 (defun js2-set-default-externs ()
6619 "Set the value of `js2-default-externs' based on the various
6620 `js2-include-?-externs' variables."
6621 (setq js2-default-externs
6622 (append js2-ecma-262-externs
6623 (if js2-include-browser-externs js2-browser-externs)
6624 (if (and js2-include-browser-externs
6625 (>= js2-language-version 200)) js2-harmony-externs)
6626 (if js2-include-rhino-externs js2-rhino-externs)
6627 (if js2-include-node-externs js2-node-externs)
6628 (if (or js2-include-browser-externs js2-include-node-externs)
6629 js2-typed-array-externs))))
6630
6631 (defun js2-apply-jslint-globals ()
6632 (setq js2-additional-externs
6633 (nconc (js2-get-jslint-globals)
6634 js2-additional-externs)))
6635
6636 (defun js2-get-jslint-globals ()
6637 (loop for node in (js2-ast-root-comments js2-mode-ast)
6638 when (and (eq 'block (js2-comment-node-format node))
6639 (save-excursion
6640 (goto-char (js2-node-abs-pos node))
6641 (looking-at "/\\*global ")))
6642 append (js2-get-jslint-globals-in
6643 (match-end 0)
6644 (js2-node-abs-end node))))
6645
6646 (defun js2-get-jslint-globals-in (beg end)
6647 (let (res)
6648 (save-excursion
6649 (goto-char beg)
6650 (while (re-search-forward js2-mode-identifier-re end t)
6651 (let ((match (match-string 0)))
6652 (unless (member match '("true" "false"))
6653 (push match res)))))
6654 (nreverse res)))
6655
6656 ;;; IMenu support
6657
6658 ;; We currently only support imenu, but eventually should support speedbar and
6659 ;; possibly other browsing mechanisms.
6660
6661 ;; The basic strategy is to identify function assignment targets of the form
6662 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6663 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6664 ;; for imenu after parsing is finished.
6665
6666 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6667 ;; JavaScript, and the general problem is undecidable. However, several forms
6668 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6669 ;; include:
6670
6671 ;; function foo() -- function declaration
6672 ;; foo = function() -- function expression assigned to variable
6673 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6674 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6675 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6676 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6677 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6678 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6679 ;; function foo() {function bar() {...}} -- nested function
6680 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6681
6682 ;; This list boils down to a few forms that can be combined recursively.
6683 ;; Top-level named function declarations include both the left-hand (name)
6684 ;; and the right-hand (function value) expressions needed to produce an imenu
6685 ;; entry. The other "right-hand" forms we need to look for are:
6686 ;; - functions declared as props/getters/setters in object literals
6687 ;; - nested named function declarations
6688 ;; The "left-hand" expressions that functions can be assigned to include:
6689 ;; - local/global variables
6690 ;; - nested property-get expressions like a.b.c.d
6691 ;; - element gets like foo[10] or foo['bar'] where the index
6692 ;; expression can be trivially converted to a property name. They
6693 ;; effectively then become property gets.
6694
6695 ;; All the different definition types are canonicalized into the form
6696 ;; foo.bar.baz = position-of-function-keyword
6697
6698 ;; We need to build a trie-like structure for imenu. As an example,
6699 ;; consider the following JavaScript code:
6700
6701 ;; a = function() {...} // function at position 5
6702 ;; b = function() {...} // function at position 25
6703 ;; foo = function() {...} // function at position 100
6704 ;; foo.bar = function() {...} // function at position 200
6705 ;; foo.bar.baz = function() {...} // function at position 300
6706 ;; foo.bar.zab = function() {...} // function at position 400
6707
6708 ;; During parsing we accumulate an entry for each definition in
6709 ;; the variable `js2-imenu-recorder', like so:
6710
6711 ;; '((fn a 5)
6712 ;; (fn b 25)
6713 ;; (fn foo 100)
6714 ;; (fn foo bar 200)
6715 ;; (fn foo bar baz 300)
6716 ;; (fn foo bar zab 400))
6717
6718 ;; Where 'fn' is the respective function node.
6719 ;; After parsing these entries are merged into this alist-trie:
6720
6721 ;; '((a . 1)
6722 ;; (b . 2)
6723 ;; (foo (<definition> . 3)
6724 ;; (bar (<definition> . 6)
6725 ;; (baz . 100)
6726 ;; (zab . 200))))
6727
6728 ;; Note the wacky need for a <definition> name. The token can be anything
6729 ;; that isn't a valid JavaScript identifier, because you might make foo
6730 ;; a function and then start setting properties on it that are also functions.
6731
6732 (defun js2-prop-node-name (node)
6733 "Return the name of a node that may be a property-get/property-name.
6734 If NODE is not a valid name-node, string-node or integral number-node,
6735 returns nil. Otherwise returns the string name/value of the node."
6736 (cond
6737 ((js2-name-node-p node)
6738 (js2-name-node-name node))
6739 ((js2-string-node-p node)
6740 (js2-string-node-value node))
6741 ((and (js2-number-node-p node)
6742 (string-match "^[0-9]+$" (js2-number-node-value node)))
6743 (js2-number-node-value node))
6744 ((js2-this-node-p node)
6745 "this")))
6746
6747 (defun js2-node-qname-component (node)
6748 "Return the name of this node, if it contributes to a qname.
6749 Returns nil if the node doesn't contribute."
6750 (copy-sequence
6751 (or (js2-prop-node-name node)
6752 (if (and (js2-function-node-p node)
6753 (js2-function-node-name node))
6754 (js2-name-node-name (js2-function-node-name node))))))
6755
6756 (defun js2-record-imenu-entry (fn-node qname pos)
6757 "Add an entry to `js2-imenu-recorder'.
6758 FN-NODE should be the current item's function node.
6759
6760 Associate FN-NODE with its QNAME for later lookup.
6761 This is used in postprocessing the chain list. For each chain, we find
6762 the parent function, look up its qname, then prepend a copy of it to the chain."
6763 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6764 (unless js2-imenu-function-map
6765 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6766 (puthash fn-node qname js2-imenu-function-map))
6767
6768 (defun js2-record-imenu-functions (node &optional var)
6769 "Record function definitions for imenu.
6770 NODE is a function node or an object literal.
6771 VAR, if non-nil, is the expression that NODE is being assigned to.
6772 When passed arguments of wrong type, does nothing."
6773 (when js2-parse-ide-mode
6774 (let ((fun-p (js2-function-node-p node))
6775 qname fname-node)
6776 (cond
6777 ;; non-anonymous function declaration?
6778 ((and fun-p
6779 (not var)
6780 (setq fname-node (js2-function-node-name node)))
6781 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6782 ;; for remaining forms, compute left-side tree branch first
6783 ((and var (setq qname (js2-compute-nested-prop-get var)))
6784 (cond
6785 ;; foo.bar.baz = function
6786 (fun-p
6787 (js2-record-imenu-entry node qname (js2-node-pos node)))
6788 ;; foo.bar.baz = object-literal
6789 ;; look for nested functions: {a: {b: function() {...} }}
6790 ((js2-object-node-p node)
6791 ;; Node position here is still absolute, since the parser
6792 ;; passes the assignment target and value expressions
6793 ;; to us before they are added as children of the assignment node.
6794 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6795
6796 (defun js2-compute-nested-prop-get (node)
6797 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6798 component nodes as a list. Otherwise return nil. Element-gets are treated
6799 as property-gets if the index expression is a string, or a positive integer."
6800 (let (left right head)
6801 (cond
6802 ((or (js2-name-node-p node)
6803 (js2-this-node-p node))
6804 (list node))
6805 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6806 ((js2-prop-get-node-p node) ; foo.bar
6807 (setq left (js2-prop-get-node-left node)
6808 right (js2-prop-get-node-right node))
6809 (if (setq head (js2-compute-nested-prop-get left))
6810 (nconc head (list right))))
6811 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6812 (setq left (js2-elem-get-node-target node)
6813 right (js2-elem-get-node-element node))
6814 (if (or (js2-string-node-p right) ; ['bar']
6815 (and (js2-number-node-p right) ; [10]
6816 (string-match "^[0-9]+$"
6817 (js2-number-node-value right))))
6818 (if (setq head (js2-compute-nested-prop-get left))
6819 (nconc head (list right))))))))
6820
6821 (defun js2-record-object-literal (node qname pos)
6822 "Recursively process an object literal looking for functions.
6823 NODE is an object literal that is the right-hand child of an assignment
6824 expression. QNAME is a list of nodes representing the assignment target,
6825 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6826 POS is the absolute position of the node.
6827 We do a depth-first traversal of NODE. For any functions we find,
6828 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6829 (let (right)
6830 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6831 (let ((left (js2-infix-node-left e))
6832 ;; Element positions are relative to the parent position.
6833 (pos (+ pos (js2-node-pos e))))
6834 (cond
6835 ;; foo: function() {...}
6836 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6837 (when (js2-prop-node-name left)
6838 ;; As a policy decision, we record the position of the property,
6839 ;; not the position of the `function' keyword, since the property
6840 ;; is effectively the name of the function.
6841 (js2-record-imenu-entry right (append qname (list left)) pos)))
6842 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6843 ((js2-object-node-p right)
6844 (js2-record-object-literal right
6845 (append qname (list (js2-infix-node-left e)))
6846 (+ pos (js2-node-pos right)))))))))
6847
6848 (defun js2-node-top-level-decl-p (node)
6849 "Return t if NODE's name is defined in the top-level scope.
6850 Also returns t if NODE's name is not defined in any scope, since it implies
6851 that it's an external variable, which must also be in the top-level scope."
6852 (let* ((name (js2-prop-node-name node))
6853 (this-scope (js2-node-get-enclosing-scope node))
6854 defining-scope)
6855 (cond
6856 ((js2-this-node-p node)
6857 nil)
6858 ((null this-scope)
6859 t)
6860 ((setq defining-scope (js2-get-defining-scope this-scope name))
6861 (js2-ast-root-p defining-scope))
6862 (t t))))
6863
6864 (defun js2-wrapper-function-p (node)
6865 "Return t if NODE is a function expression that's immediately invoked.
6866 NODE must be `js2-function-node'."
6867 (let ((parent (js2-node-parent node)))
6868 (or
6869 ;; function(){...}();
6870 (js2-call-node-p parent)
6871 (and (js2-paren-node-p parent)
6872 ;; (function(){...})();
6873 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6874 ;; (function(){...}).call(this);
6875 (and (js2-prop-get-node-p parent)
6876 (member (js2-name-node-name (js2-prop-get-node-right parent))
6877 '("call" "apply"))
6878 (js2-call-node-p (js2-node-parent parent))))))))
6879
6880 (defun js2-browse-postprocess-chains (entries)
6881 "Modify function-declaration name chains after parsing finishes.
6882 Some of the information is only available after the parse tree is complete.
6883 For instance, processing a nested scope requires a parent function node."
6884 (let (result fn parent-qname p elem)
6885 (dolist (entry entries)
6886 ;; function node goes first
6887 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6888 ;; Examine head's defining scope:
6889 ;; Pre-processed chain, or top-level/external, keep as-is.
6890 (if (or (stringp head) (js2-node-top-level-decl-p head))
6891 (push chain result)
6892 (when (js2-this-node-p head)
6893 (setq chain (cdr chain))) ; discard this-node
6894 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6895 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6896 (when (eq parent-qname 'not-found)
6897 ;; anonymous function expressions are not recorded
6898 ;; during the parse, so we need to handle this case here
6899 (setq parent-qname
6900 (if (js2-wrapper-function-p fn)
6901 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6902 (if (js2-ast-root-p grandparent)
6903 nil
6904 (gethash grandparent js2-imenu-function-map 'skip)))
6905 'skip))
6906 (puthash fn parent-qname js2-imenu-function-map))
6907 (unless (eq parent-qname 'skip)
6908 ;; prefix parent fn qname to this chain.
6909 (let ((qname (append parent-qname chain)))
6910 (puthash current-fn (butlast qname) js2-imenu-function-map)
6911 (push qname result)))))))
6912 ;; finally replace each node in each chain with its name.
6913 (dolist (chain result)
6914 (setq p chain)
6915 (while p
6916 (if (js2-node-p (setq elem (car p)))
6917 (setcar p (js2-node-qname-component elem)))
6918 (setq p (cdr p))))
6919 result))
6920
6921 ;; Merge name chains into a trie-like tree structure of nested lists.
6922 ;; To simplify construction of the trie, we first build it out using the rule
6923 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6924 ;; [key, num-or-list]. The second element can be a number; if so, this key
6925 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6926 ;; associated with the key at this level.) Otherwise the second element is
6927 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6928 ;; a simple recursive formulation.
6929 ;;
6930 ;; js2-mode is building the data structure for imenu. The imenu documentation
6931 ;; claims that it's the structure above, but in practice it wants the children
6932 ;; at the same list level as the key for that level, which is how I've drawn
6933 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6934 ;; list wrapper around the children at each level.
6935 ;;
6936 ;; A completed nested imenu-alist entry looks like this:
6937 ;; '(("foo"
6938 ;; ("<definition>" . 7)
6939 ;; ("bar"
6940 ;; ("a" . 40)
6941 ;; ("b" . 60))))
6942 ;;
6943 ;; In particular, the documentation for `imenu--index-alist' says that
6944 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6945 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6946
6947 (defun js2-treeify (lst)
6948 "Convert (a b c d) to (a ((b ((c d)))))."
6949 (if (null (cddr lst)) ; list length <= 2
6950 lst
6951 (list (car lst) (list (js2-treeify (cdr lst))))))
6952
6953 (defun js2-build-alist-trie (chains trie)
6954 "Merge declaration name chains into a trie-like alist structure for imenu.
6955 CHAINS is the qname chain list produced during parsing. TRIE is a
6956 list of elements built up so far."
6957 (let (head tail pos branch kids)
6958 (dolist (chain chains)
6959 (setq head (car chain)
6960 tail (cdr chain)
6961 pos (if (numberp (car tail)) (car tail))
6962 branch (js2-find-if (lambda (n)
6963 (string= (car n) head))
6964 trie)
6965 kids (second branch))
6966 (cond
6967 ;; case 1: this key isn't in the trie yet
6968 ((null branch)
6969 (if trie
6970 (setcdr (last trie) (list (js2-treeify chain)))
6971 (setq trie (list (js2-treeify chain)))))
6972 ;; case 2: key is present with a single number entry: replace w/ list
6973 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6974 ;; ("<definition>" 20)))
6975 ((numberp kids)
6976 (setcar (cdr branch)
6977 (list (list "<definition-1>" kids)
6978 (if pos
6979 (list "<definition-2>" pos)
6980 (js2-treeify tail)))))
6981 ;; case 3: key is there (with kids), and we're a number entry
6982 (pos
6983 (setcdr (last kids)
6984 (list
6985 (list (format "<definition-%d>"
6986 (1+ (loop for kid in kids
6987 count (eq ?< (aref (car kid) 0)))))
6988 pos))))
6989 ;; case 4: key is there with kids, need to merge in our chain
6990 (t
6991 (js2-build-alist-trie (list tail) kids))))
6992 trie))
6993
6994 (defun js2-flatten-trie (trie)
6995 "Convert TRIE to imenu-format.
6996 Recurses through nodes, and for each one whose second element is a list,
6997 appends the list's flattened elements to the current element. Also
6998 changes the tails into conses. For instance, this pre-flattened trie
6999
7000 '(a ((b 20)
7001 (c ((d 30)
7002 (e 40)))))
7003
7004 becomes
7005
7006 '(a (b . 20)
7007 (c (d . 30)
7008 (e . 40)))
7009
7010 Note that the root of the trie has no key, just a list of chains.
7011 This is also true for the value of any key with multiple children,
7012 e.g. key 'c' in the example above."
7013 (cond
7014 ((listp (car trie))
7015 (mapcar #'js2-flatten-trie trie))
7016 (t
7017 (if (numberp (second trie))
7018 (cons (car trie) (second trie))
7019 ;; else pop list and append its kids
7020 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7021
7022 (defun js2-build-imenu-index ()
7023 "Turn `js2-imenu-recorder' into an imenu data structure."
7024 (unless (eq js2-imenu-recorder 'empty)
7025 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7026 (result (js2-build-alist-trie chains nil)))
7027 (js2-flatten-trie result))))
7028
7029 (defun js2-test-print-chains (chains)
7030 "Print a list of qname chains.
7031 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7032 i.e. one or more nodes, and an integer position as the list tail."
7033 (mapconcat (lambda (chain)
7034 (concat "("
7035 (mapconcat (lambda (elem)
7036 (if (js2-node-p elem)
7037 (or (js2-node-qname-component elem)
7038 "nil")
7039 (number-to-string elem)))
7040 chain
7041 " ")
7042 ")"))
7043 chains
7044 "\n"))
7045
7046 ;;; Parser
7047
7048 (defconst js2-version "1.8.5"
7049 "Version of JavaScript supported.")
7050
7051 (defun js2-record-face (face &optional token)
7052 "Record a style run of FACE for TOKEN or the current token."
7053 (unless token (setq token (js2-current-token)))
7054 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7055
7056 (defsubst js2-node-end (n)
7057 "Computes the absolute end of node N.
7058 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7059 is only true until the node is added to its parent; i.e., while parsing."
7060 (+ (js2-node-pos n)
7061 (js2-node-len n)))
7062
7063 (defun js2-record-comment (token)
7064 "Record a comment in `js2-scanned-comments'."
7065 (let ((ct (js2-token-comment-type token))
7066 (beg (js2-token-beg token))
7067 (end (js2-token-end token)))
7068 (push (make-js2-comment-node :len (- end beg)
7069 :format ct)
7070 js2-scanned-comments)
7071 (when js2-parse-ide-mode
7072 (js2-record-face (if (eq ct 'jsdoc)
7073 'font-lock-doc-face
7074 'font-lock-comment-face)
7075 token)
7076 (when (memq ct '(html preprocessor))
7077 ;; Tell cc-engine the bounds of the comment.
7078 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7079
7080 (defun js2-peek-token ()
7081 "Return the next token type without consuming it.
7082 If `js2-ti-lookahead' is positive, return the type of next token
7083 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7084 (if (not (zerop js2-ti-lookahead))
7085 (js2-token-type
7086 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7087 (let ((tt (js2-get-token-internal)))
7088 (js2-unget-token)
7089 tt)))
7090
7091 (defalias 'js2-next-token 'js2-get-token)
7092
7093 (defun js2-match-token (match &optional dont-unget)
7094 "Get next token and return t if it matches MATCH, a bytecode.
7095 Returns nil and consumes nothing if MATCH is not the next token."
7096 (if (/= (js2-get-token) match)
7097 (ignore (unless dont-unget (js2-unget-token)))
7098 t))
7099
7100 (defun js2-match-contextual-kwd (name)
7101 "Consume and return t if next token is `js2-NAME', and its
7102 string is NAME. Returns nil and keeps current token otherwise."
7103 (if (or (/= (js2-get-token) js2-NAME)
7104 (not (string= (js2-current-token-string) name)))
7105 (progn
7106 (js2-unget-token)
7107 nil)
7108 (js2-record-face 'font-lock-keyword-face)
7109 t))
7110
7111 (defun js2-valid-prop-name-token (tt)
7112 (or (= tt js2-NAME)
7113 (and js2-allow-keywords-as-property-names
7114 (plusp tt)
7115 (or (= tt js2-RESERVED)
7116 (aref js2-kwd-tokens tt)))))
7117
7118 (defun js2-match-prop-name ()
7119 "Consume token and return t if next token is a valid property name.
7120 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7121 is non-nil and it's a keyword token."
7122 (if (js2-valid-prop-name-token (js2-get-token))
7123 t
7124 (js2-unget-token)
7125 nil))
7126
7127 (defun js2-must-match-prop-name (msg-id &optional pos len)
7128 (if (js2-match-prop-name)
7129 t
7130 (js2-report-error msg-id nil pos len)
7131 nil))
7132
7133 (defun js2-peek-token-or-eol ()
7134 "Return js2-EOL if the next token immediately follows a newline.
7135 Else returns the next token. Used in situations where we don't
7136 consider certain token types valid if they are preceded by a newline.
7137 One example is the postfix ++ or -- operator, which has to be on the
7138 same line as its operand."
7139 (let ((tt (js2-get-token))
7140 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7141 (js2-unget-token)
7142 (if follows-eol
7143 js2-EOL
7144 tt)))
7145
7146 (defun js2-must-match (token msg-id &optional pos len)
7147 "Match next token to token code TOKEN, or record a syntax error.
7148 MSG-ID is the error message to report if the match fails.
7149 Returns t on match, nil if no match."
7150 (if (js2-match-token token t)
7151 t
7152 (js2-report-error msg-id nil pos len)
7153 (js2-unget-token)
7154 nil))
7155
7156 (defun js2-must-match-name (msg-id)
7157 (if (js2-match-token js2-NAME t)
7158 t
7159 (if (eq (js2-current-token-type) js2-RESERVED)
7160 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7161 (js2-report-error msg-id)
7162 (js2-unget-token))
7163 nil))
7164
7165 (defsubst js2-inside-function ()
7166 (plusp js2-nesting-of-function))
7167
7168 (defun js2-set-requires-activation ()
7169 (if (js2-function-node-p js2-current-script-or-fn)
7170 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7171
7172 (defun js2-check-activation-name (name _token)
7173 (when (js2-inside-function)
7174 ;; skip language-version 1.2 check from Rhino
7175 (if (or (string= "arguments" name)
7176 (and js2-compiler-activation-names ; only used in codegen
7177 (gethash name js2-compiler-activation-names)))
7178 (js2-set-requires-activation))))
7179
7180 (defun js2-set-is-generator ()
7181 (let ((fn-node js2-current-script-or-fn))
7182 (when (and (js2-function-node-p fn-node)
7183 (not (js2-function-node-generator-type fn-node)))
7184 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7185
7186 (defun js2-must-have-xml ()
7187 (unless js2-compiler-xml-available
7188 (js2-report-error "msg.XML.not.available")))
7189
7190 (defun js2-push-scope (scope)
7191 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7192 (assert (js2-scope-p scope))
7193 (assert (null (js2-scope-parent-scope scope)))
7194 (assert (not (eq js2-current-scope scope)))
7195 (setf (js2-scope-parent-scope scope) js2-current-scope
7196 js2-current-scope scope))
7197
7198 (defsubst js2-pop-scope ()
7199 (setq js2-current-scope
7200 (js2-scope-parent-scope js2-current-scope)))
7201
7202 (defun js2-enter-loop (loop-node)
7203 (push loop-node js2-loop-set)
7204 (push loop-node js2-loop-and-switch-set)
7205 (js2-push-scope loop-node)
7206 ;; Tell the current labeled statement (if any) its statement,
7207 ;; and set the jump target of the first label to the loop.
7208 ;; These are used in `js2-parse-continue' to verify that the
7209 ;; continue target is an actual labeled loop. (And for codegen.)
7210 (when js2-labeled-stmt
7211 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7212 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7213 js2-labeled-stmt))) loop-node)))
7214
7215 (defun js2-exit-loop ()
7216 (pop js2-loop-set)
7217 (pop js2-loop-and-switch-set)
7218 (js2-pop-scope))
7219
7220 (defsubst js2-enter-switch (switch-node)
7221 (push switch-node js2-loop-and-switch-set))
7222
7223 (defsubst js2-exit-switch ()
7224 (pop js2-loop-and-switch-set))
7225
7226 (defun js2-parse (&optional buf cb)
7227 "Tell the js2 parser to parse a region of JavaScript.
7228
7229 BUF is a buffer or buffer name containing the code to parse.
7230 Call `narrow-to-region' first to parse only part of the buffer.
7231
7232 The returned AST root node is given some additional properties:
7233 `node-count' - total number of nodes in the AST
7234 `buffer' - BUF. The buffer it refers to may change or be killed,
7235 so the value is not necessarily reliable.
7236
7237 An optional callback CB can be specified to report parsing
7238 progress. If `(functionp CB)' returns t, it will be called with
7239 the current line number once before parsing begins, then again
7240 each time the lexer reaches a new line number.
7241
7242 CB can also be a list of the form `(symbol cb ...)' to specify
7243 multiple callbacks with different criteria. Each symbol is a
7244 criterion keyword, and the following element is the callback to
7245 call
7246
7247 :line - called whenever the line number changes
7248 :token - called for each new token consumed
7249
7250 The list of criteria could be extended to include entering or
7251 leaving a statement, an expression, or a function definition."
7252 (if (and cb (not (functionp cb)))
7253 (error "criteria callbacks not yet implemented"))
7254 (let ((inhibit-point-motion-hooks t)
7255 (js2-compiler-xml-available (>= js2-language-version 160))
7256 ;; This is a recursive-descent parser, so give it a big stack.
7257 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7258 (max-specpdl-size (max max-specpdl-size 3000))
7259 (case-fold-search nil)
7260 ast)
7261 (with-current-buffer (or buf (current-buffer))
7262 (setq js2-scanned-comments nil
7263 js2-parsed-errors nil
7264 js2-parsed-warnings nil
7265 js2-imenu-recorder nil
7266 js2-imenu-function-map nil
7267 js2-label-set nil)
7268 (js2-init-scanner)
7269 (setq ast (with-silent-modifications
7270 (js2-do-parse)))
7271 (unless js2-ts-hit-eof
7272 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7273 (setf (js2-ast-root-errors ast) js2-parsed-errors
7274 (js2-ast-root-warnings ast) js2-parsed-warnings)
7275 ;; if we didn't find any declarations, put a dummy in this list so we
7276 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7277 (unless js2-imenu-recorder
7278 (setq js2-imenu-recorder 'empty))
7279 (run-hooks 'js2-parse-finished-hook)
7280 ast)))
7281
7282 ;; Corresponds to Rhino's Parser.parse() method.
7283 (defun js2-do-parse ()
7284 "Parse current buffer starting from current point.
7285 Scanner should be initialized."
7286 (let ((pos js2-ts-cursor)
7287 (end js2-ts-cursor) ; in case file is empty
7288 root n tt)
7289 ;; initialize buffer-local parsing vars
7290 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7291 js2-current-script-or-fn root
7292 js2-current-scope root
7293 js2-nesting-of-function 0
7294 js2-labeled-stmt nil
7295 js2-recorded-identifiers nil) ; for js2-highlight
7296 (while (/= (setq tt (js2-get-token)) js2-EOF)
7297 (if (= tt js2-FUNCTION)
7298 (progn
7299 (setq n (if js2-called-by-compile-function
7300 (js2-parse-function-expr)
7301 (js2-parse-function-stmt))))
7302 ;; not a function - parse a statement
7303 (js2-unget-token)
7304 (setq n (js2-parse-statement)))
7305 ;; add function or statement to script
7306 (setq end (js2-node-end n))
7307 (js2-block-node-push root n))
7308 ;; add comments to root in lexical order
7309 (when js2-scanned-comments
7310 ;; if we find a comment beyond end of normal kids, use its end
7311 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7312 (dolist (comment js2-scanned-comments)
7313 (push comment (js2-ast-root-comments root))
7314 (js2-node-add-children root comment)))
7315 (setf (js2-node-len root) (- end pos))
7316 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7317 ;; Give extensions a chance to muck with things before highlighting starts.
7318 (let ((js2-additional-externs js2-additional-externs))
7319 (save-excursion
7320 (run-hooks 'js2-post-parse-callbacks))
7321 (js2-highlight-undeclared-vars))
7322 root))
7323
7324 (defun js2-parse-function-closure-body (fn-node)
7325 "Parse a JavaScript 1.8 function closure body."
7326 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7327 (if js2-ts-hit-eof
7328 (js2-report-error "msg.no.brace.body" nil
7329 (js2-node-pos fn-node)
7330 (- js2-ts-cursor (js2-node-pos fn-node)))
7331 (js2-node-add-children fn-node
7332 (setf (js2-function-node-body fn-node)
7333 (js2-parse-expr t))))))
7334
7335 (defun js2-parse-function-body (fn-node)
7336 (js2-must-match js2-LC "msg.no.brace.body"
7337 (js2-node-pos fn-node)
7338 (- js2-ts-cursor (js2-node-pos fn-node)))
7339 (let ((pos (js2-current-token-beg)) ; LC position
7340 (pn (make-js2-block-node)) ; starts at LC position
7341 tt
7342 end)
7343 (incf js2-nesting-of-function)
7344 (unwind-protect
7345 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7346 (= tt js2-EOF)
7347 (= tt js2-RC)))
7348 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7349 (js2-parse-statement)
7350 (js2-get-token)
7351 (js2-parse-function-stmt))))
7352 (decf js2-nesting-of-function))
7353 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7354 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7355 (setq end (js2-current-token-end)))
7356 (setf (js2-node-pos pn) pos
7357 (js2-node-len pn) (- end pos))
7358 (setf (js2-function-node-body fn-node) pn)
7359 (js2-node-add-children fn-node pn)
7360 pn))
7361
7362 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7363 "Declare and fontify destructuring parameters inside NODE.
7364 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7365 (cond
7366 ((js2-name-node-p node)
7367 (let (leftpos)
7368 (js2-define-symbol decl-type (js2-name-node-name node)
7369 node ignore-not-in-block)
7370 (when face
7371 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7372 (+ leftpos (js2-node-len node))
7373 face 'record))))
7374 ((js2-object-node-p node)
7375 (dolist (elem (js2-object-node-elems node))
7376 (js2-define-destruct-symbols
7377 (if (js2-object-prop-node-p elem)
7378 (js2-object-prop-node-right elem)
7379 ;; abbreviated destructuring {a, b}
7380 elem)
7381 decl-type face ignore-not-in-block)))
7382 ((js2-array-node-p node)
7383 (dolist (elem (js2-array-node-elems node))
7384 (when elem
7385 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7386 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7387 (js2-node-len node)))))
7388
7389 (defun js2-parse-function-params (function-type fn-node pos)
7390 (if (js2-match-token js2-RP)
7391 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7392 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7393 (eq (js2-current-token-type) js2-NAME)))
7394 params param default-found rest-param-at)
7395 (when paren-free-arrow
7396 (js2-unget-token))
7397 (loop for tt = (js2-peek-token)
7398 do
7399 (cond
7400 ;; destructuring param
7401 ((and (not paren-free-arrow)
7402 (or (= tt js2-LB) (= tt js2-LC)))
7403 (js2-get-token)
7404 (when default-found
7405 (js2-report-error "msg.no.default.after.default.param"))
7406 (setq param (js2-parse-destruct-primary-expr))
7407 (js2-define-destruct-symbols param
7408 js2-LP
7409 'js2-function-param)
7410 (push param params))
7411 ;; variable name
7412 (t
7413 (when (and (>= js2-language-version 200)
7414 (not paren-free-arrow)
7415 (js2-match-token js2-TRIPLEDOT)
7416 (not rest-param-at))
7417 ;; to report errors if there are more parameters
7418 (setq rest-param-at (length params)))
7419 (js2-must-match-name "msg.no.parm")
7420 (js2-record-face 'js2-function-param)
7421 (setq param (js2-create-name-node))
7422 (js2-define-symbol js2-LP (js2-current-token-string) param)
7423 ;; default parameter value
7424 (when (or (and default-found
7425 (not rest-param-at)
7426 (js2-must-match js2-ASSIGN
7427 "msg.no.default.after.default.param"
7428 (js2-node-pos param)
7429 (js2-node-len param)))
7430 (and (>= js2-language-version 200)
7431 (js2-match-token js2-ASSIGN)))
7432 (assert (not paren-free-arrow))
7433 (let* ((pos (js2-node-pos param))
7434 (tt (js2-current-token-type))
7435 (op-pos (- (js2-current-token-beg) pos))
7436 (left param)
7437 (right (js2-parse-assign-expr))
7438 (len (- (js2-node-end right) pos)))
7439 (setq param (make-js2-assign-node
7440 :type tt :pos pos :len len :op-pos op-pos
7441 :left left :right right)
7442 default-found t)
7443 (js2-node-add-children param left right)))
7444 (push param params)))
7445 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7446 (js2-report-error "msg.param.after.rest" nil
7447 (js2-node-pos param) (js2-node-len param)))
7448 while
7449 (js2-match-token js2-COMMA))
7450 (when (and (not paren-free-arrow)
7451 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7452 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7453 (when rest-param-at
7454 (setf (js2-function-node-rest-p fn-node) t))
7455 (dolist (p params)
7456 (js2-node-add-children fn-node p)
7457 (push p (js2-function-node-params fn-node))))))
7458
7459 (defun js2-check-inconsistent-return-warning (fn-node name)
7460 "Possibly show inconsistent-return warning.
7461 Last token scanned is the close-curly for the function body."
7462 (when (and js2-mode-show-strict-warnings
7463 js2-strict-inconsistent-return-warning
7464 (not (js2-has-consistent-return-usage
7465 (js2-function-node-body fn-node))))
7466 ;; Have it extend from close-curly to bol or beginning of block.
7467 (let ((pos (save-excursion
7468 (goto-char (js2-current-token-end))
7469 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7470 (point-at-bol))))
7471 (end (js2-current-token-end)))
7472 (if (plusp (js2-name-node-length name))
7473 (js2-add-strict-warning "msg.no.return.value"
7474 (js2-name-node-name name) pos end)
7475 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7476
7477 (defun js2-parse-function-stmt ()
7478 (let ((pos (js2-current-token-beg))
7479 (star-p (js2-match-token js2-MUL)))
7480 (js2-must-match-name "msg.unnamed.function.stmt")
7481 (let ((name (js2-create-name-node t))
7482 pn member-expr)
7483 (cond
7484 ((js2-match-token js2-LP)
7485 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7486 (js2-allow-member-expr-as-function-name
7487 (setq member-expr (js2-parse-member-expr-tail nil name))
7488 (js2-parse-highlight-member-expr-fn-name member-expr)
7489 (js2-must-match js2-LP "msg.no.paren.parms")
7490 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7491 (js2-function-node-member-expr pn) member-expr)
7492 pn)
7493 (t
7494 (js2-report-error "msg.no.paren.parms")
7495 (make-js2-error-node))))))
7496
7497 (defun js2-parse-function-expr ()
7498 (let ((pos (js2-current-token-beg))
7499 (star-p (js2-match-token js2-MUL))
7500 name)
7501 (when (js2-match-token js2-NAME)
7502 (setq name (js2-create-name-node t)))
7503 (js2-must-match js2-LP "msg.no.paren.parms")
7504 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7505
7506 (defun js2-parse-function (function-type pos star-p &optional name)
7507 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7508 beginning of the first token (function keyword, unless it's an
7509 arrow function), NAME is js2-name-node."
7510 (let (fn-node lp)
7511 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7512 (setq lp (js2-current-token-beg)))
7513 (setf fn-node (make-js2-function-node :pos pos
7514 :name name
7515 :form function-type
7516 :lp (if lp (- lp pos))
7517 :generator-type (and star-p 'STAR)))
7518 (when name
7519 (js2-set-face (js2-node-pos name) (js2-node-end name)
7520 'font-lock-function-name-face 'record)
7521 (when (plusp (js2-name-node-length name))
7522 ;; Function statements define a symbol in the enclosing scope
7523 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7524 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7525 ;; 1. Nested functions are not affected by the dynamic scope flag
7526 ;; as dynamic scope is already a parent of their scope.
7527 ;; 2. Functions defined under the with statement also immune to
7528 ;; this setup, in which case dynamic scope is ignored in favor
7529 ;; of the with object.
7530 (setf (js2-function-node-ignore-dynamic fn-node) t))
7531 ;; dynamically bind all the per-function variables
7532 (let ((js2-current-script-or-fn fn-node)
7533 (js2-current-scope fn-node)
7534 (js2-nesting-of-with 0)
7535 (js2-end-flags 0)
7536 js2-label-set
7537 js2-loop-set
7538 js2-loop-and-switch-set)
7539 (js2-parse-function-params function-type fn-node pos)
7540 (when (eq function-type 'FUNCTION_ARROW)
7541 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7542 (if (and (>= js2-language-version 180)
7543 (/= (js2-peek-token) js2-LC))
7544 (js2-parse-function-closure-body fn-node)
7545 (js2-parse-function-body fn-node))
7546 (js2-check-inconsistent-return-warning fn-node name)
7547
7548 (when name
7549 (js2-node-add-children fn-node name)
7550 ;; Function expressions define a name only in the body of the
7551 ;; function, and only if not hidden by a parameter name
7552 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7553 (null (js2-scope-get-symbol js2-current-scope
7554 (js2-name-node-name name))))
7555 (js2-define-symbol js2-FUNCTION
7556 (js2-name-node-name name)
7557 fn-node))
7558 (when (eq function-type 'FUNCTION_STATEMENT)
7559 (js2-record-imenu-functions fn-node))))
7560
7561 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7562 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7563 ;; We wait until after parsing the function to set its parent scope,
7564 ;; since `js2-define-symbol' needs the defining-scope check to stop
7565 ;; at the function boundary when checking for redeclarations.
7566 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7567 fn-node))
7568
7569 (defun js2-parse-statements (&optional parent)
7570 "Parse a statement list. Last token consumed must be js2-LC.
7571
7572 PARENT can be a `js2-block-node', in which case the statements are
7573 appended to PARENT. Otherwise a new `js2-block-node' is created
7574 and returned.
7575
7576 This function does not match the closing js2-RC: the caller
7577 matches the RC so it can provide a suitable error message if not
7578 matched. This means it's up to the caller to set the length of
7579 the node to include the closing RC. The node start pos is set to
7580 the absolute buffer start position, and the caller should fix it
7581 up to be relative to the parent node. All children of this block
7582 node are given relative start positions and correct lengths."
7583 (let ((pn (or parent (make-js2-block-node)))
7584 tt)
7585 (setf (js2-node-pos pn) (js2-current-token-beg))
7586 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7587 (/= tt js2-RC))
7588 (js2-block-node-push pn (js2-parse-statement)))
7589 pn))
7590
7591 (defun js2-parse-statement ()
7592 (let (pn beg end)
7593 ;; coarse-grained user-interrupt check - needs work
7594 (and js2-parse-interruptable-p
7595 (zerop (% (incf js2-parse-stmt-count)
7596 js2-statements-per-pause))
7597 (input-pending-p)
7598 (throw 'interrupted t))
7599 (setq pn (js2-statement-helper))
7600 ;; no-side-effects warning check
7601 (unless (js2-node-has-side-effects pn)
7602 (setq end (js2-node-end pn))
7603 (save-excursion
7604 (goto-char end)
7605 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7606 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7607 pn))
7608
7609 ;; These correspond to the switch cases in Parser.statementHelper
7610 (defconst js2-parsers
7611 (let ((parsers (make-vector js2-num-tokens
7612 #'js2-parse-expr-stmt)))
7613 (aset parsers js2-BREAK #'js2-parse-break)
7614 (aset parsers js2-CONST #'js2-parse-const-var)
7615 (aset parsers js2-CONTINUE #'js2-parse-continue)
7616 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7617 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7618 (aset parsers js2-DO #'js2-parse-do)
7619 (aset parsers js2-FOR #'js2-parse-for)
7620 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
7621 (aset parsers js2-IF #'js2-parse-if)
7622 (aset parsers js2-LC #'js2-parse-block)
7623 (aset parsers js2-LET #'js2-parse-let-stmt)
7624 (aset parsers js2-NAME #'js2-parse-name-or-label)
7625 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7626 (aset parsers js2-SEMI #'js2-parse-semi)
7627 (aset parsers js2-SWITCH #'js2-parse-switch)
7628 (aset parsers js2-THROW #'js2-parse-throw)
7629 (aset parsers js2-TRY #'js2-parse-try)
7630 (aset parsers js2-VAR #'js2-parse-const-var)
7631 (aset parsers js2-WHILE #'js2-parse-while)
7632 (aset parsers js2-WITH #'js2-parse-with)
7633 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7634 parsers)
7635 "A vector mapping token types to parser functions.")
7636
7637 (defun js2-parse-warn-missing-semi (beg end)
7638 (and js2-mode-show-strict-warnings
7639 js2-strict-missing-semi-warning
7640 (js2-add-strict-warning
7641 "msg.missing.semi" nil
7642 ;; back up to beginning of statement or line
7643 (max beg (save-excursion
7644 (goto-char end)
7645 (point-at-bol)))
7646 end)))
7647
7648 (defconst js2-no-semi-insertion
7649 (list js2-IF
7650 js2-SWITCH
7651 js2-WHILE
7652 js2-DO
7653 js2-FOR
7654 js2-TRY
7655 js2-WITH
7656 js2-LC
7657 js2-ERROR
7658 js2-SEMI
7659 js2-FUNCTION)
7660 "List of tokens that don't do automatic semicolon insertion.")
7661
7662 (defconst js2-autoinsert-semi-and-warn
7663 (list js2-ERROR js2-EOF js2-RC))
7664
7665 (defun js2-statement-helper ()
7666 (let* ((tt (js2-get-token))
7667 (first-tt tt)
7668 (parser (if (= tt js2-ERROR)
7669 #'js2-parse-semi
7670 (aref js2-parsers tt)))
7671 pn)
7672 ;; If the statement is set, then it's been told its label by now.
7673 (and js2-labeled-stmt
7674 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7675 (setq js2-labeled-stmt nil))
7676 (setq pn (funcall parser))
7677 ;; Don't do auto semi insertion for certain statement types.
7678 (unless (or (memq first-tt js2-no-semi-insertion)
7679 (js2-labeled-stmt-node-p pn))
7680 (js2-auto-insert-semicolon pn))
7681 pn))
7682
7683 (defun js2-auto-insert-semicolon (pn)
7684 (let* ((tt (js2-get-token))
7685 (pos (js2-node-pos pn)))
7686 (cond
7687 ((= tt js2-SEMI)
7688 ;; extend the node bounds to include the semicolon.
7689 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
7690 ((memq tt js2-autoinsert-semi-and-warn)
7691 (js2-unget-token) ; Not ';', do not consume.
7692 ;; Autoinsert ;
7693 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7694 (t
7695 (if (not (js2-token-follows-eol-p (js2-current-token)))
7696 ;; Report error if no EOL or autoinsert ';' otherwise
7697 (js2-report-error "msg.no.semi.stmt")
7698 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7699 (js2-unget-token) ; Not ';', do not consume.
7700 ))))
7701
7702 (defun js2-parse-condition ()
7703 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7704 The parens are discarded and the expression node is returned.
7705 The `pos' field of the return value is set to an absolute position
7706 that must be fixed up by the caller.
7707 Return value is a list (EXPR LP RP), with absolute paren positions."
7708 (let (pn lp rp)
7709 (if (js2-must-match js2-LP "msg.no.paren.cond")
7710 (setq lp (js2-current-token-beg)))
7711 (setq pn (js2-parse-expr))
7712 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7713 (setq rp (js2-current-token-beg)))
7714 ;; Report strict warning on code like "if (a = 7) ..."
7715 (if (and js2-strict-cond-assign-warning
7716 (js2-assign-node-p pn))
7717 (js2-add-strict-warning "msg.equal.as.assign" nil
7718 (js2-node-pos pn)
7719 (+ (js2-node-pos pn)
7720 (js2-node-len pn))))
7721 (list pn lp rp)))
7722
7723 (defun js2-parse-if ()
7724 "Parser for if-statement. Last matched token must be js2-IF."
7725 (let ((pos (js2-current-token-beg))
7726 cond if-true if-false else-pos end pn)
7727 (setq cond (js2-parse-condition)
7728 if-true (js2-parse-statement)
7729 if-false (if (js2-match-token js2-ELSE)
7730 (progn
7731 (setq else-pos (- (js2-current-token-beg) pos))
7732 (js2-parse-statement)))
7733 end (js2-node-end (or if-false if-true))
7734 pn (make-js2-if-node :pos pos
7735 :len (- end pos)
7736 :condition (car cond)
7737 :then-part if-true
7738 :else-part if-false
7739 :else-pos else-pos
7740 :lp (js2-relpos (second cond) pos)
7741 :rp (js2-relpos (third cond) pos)))
7742 (js2-node-add-children pn (car cond) if-true if-false)
7743 pn))
7744
7745 (defun js2-parse-switch ()
7746 "Parser for switch-statement. Last matched token must be js2-SWITCH."
7747 (let ((pos (js2-current-token-beg))
7748 tt pn discriminant has-default case-expr case-node
7749 case-pos cases stmt lp)
7750 (if (js2-must-match js2-LP "msg.no.paren.switch")
7751 (setq lp (js2-current-token-beg)))
7752 (setq discriminant (js2-parse-expr)
7753 pn (make-js2-switch-node :discriminant discriminant
7754 :pos pos
7755 :lp (js2-relpos lp pos)))
7756 (js2-node-add-children pn discriminant)
7757 (js2-enter-switch pn)
7758 (unwind-protect
7759 (progn
7760 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7761 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
7762 (js2-must-match js2-LC "msg.no.brace.switch")
7763 (catch 'break
7764 (while t
7765 (setq tt (js2-next-token)
7766 case-pos (js2-current-token-beg))
7767 (cond
7768 ((= tt js2-RC)
7769 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
7770 (throw 'break nil)) ; done
7771 ((= tt js2-CASE)
7772 (setq case-expr (js2-parse-expr))
7773 (js2-must-match js2-COLON "msg.no.colon.case"))
7774 ((= tt js2-DEFAULT)
7775 (if has-default
7776 (js2-report-error "msg.double.switch.default"))
7777 (setq has-default t
7778 case-expr nil)
7779 (js2-must-match js2-COLON "msg.no.colon.case"))
7780 (t
7781 (js2-report-error "msg.bad.switch")
7782 (throw 'break nil)))
7783 (setq case-node (make-js2-case-node :pos case-pos
7784 :len (- (js2-current-token-end) case-pos)
7785 :expr case-expr))
7786 (js2-node-add-children case-node case-expr)
7787 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7788 (/= tt js2-CASE)
7789 (/= tt js2-DEFAULT)
7790 (/= tt js2-EOF))
7791 (setf stmt (js2-parse-statement)
7792 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7793 (js2-block-node-push case-node stmt))
7794 (push case-node cases)))
7795 ;; add cases last, as pushing reverses the order to be correct
7796 (dolist (kid cases)
7797 (js2-node-add-children pn kid)
7798 (push kid (js2-switch-node-cases pn)))
7799 pn) ; return value
7800 (js2-exit-switch))))
7801
7802 (defun js2-parse-while ()
7803 "Parser for while-statement. Last matched token must be js2-WHILE."
7804 (let ((pos (js2-current-token-beg))
7805 (pn (make-js2-while-node))
7806 cond body)
7807 (js2-enter-loop pn)
7808 (unwind-protect
7809 (progn
7810 (setf cond (js2-parse-condition)
7811 (js2-while-node-condition pn) (car cond)
7812 body (js2-parse-statement)
7813 (js2-while-node-body pn) body
7814 (js2-node-len pn) (- (js2-node-end body) pos)
7815 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7816 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7817 (js2-node-add-children pn body (car cond)))
7818 (js2-exit-loop))
7819 pn))
7820
7821 (defun js2-parse-do ()
7822 "Parser for do-statement. Last matched token must be js2-DO."
7823 (let ((pos (js2-current-token-beg))
7824 (pn (make-js2-do-node))
7825 cond body end)
7826 (js2-enter-loop pn)
7827 (unwind-protect
7828 (progn
7829 (setq body (js2-parse-statement))
7830 (js2-must-match js2-WHILE "msg.no.while.do")
7831 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
7832 cond (js2-parse-condition)
7833 (js2-do-node-condition pn) (car cond)
7834 (js2-do-node-body pn) body
7835 end js2-ts-cursor
7836 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7837 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7838 (js2-node-add-children pn (car cond) body))
7839 (js2-exit-loop))
7840 ;; Always auto-insert semicolon to follow SpiderMonkey:
7841 ;; It is required by ECMAScript but is ignored by the rest of
7842 ;; world; see bug 238945
7843 (if (js2-match-token js2-SEMI)
7844 (setq end js2-ts-cursor))
7845 (setf (js2-node-len pn) (- end pos))
7846 pn))
7847
7848 (defun js2-parse-for ()
7849 "Parser for for-statement. Last matched token must be js2-FOR.
7850 Parses for, for-in, and for each-in statements."
7851 (let ((for-pos (js2-current-token-beg))
7852 pn is-for-each is-for-in-or-of is-for-of
7853 in-pos each-pos tmp-pos
7854 init ; Node init is also foo in 'foo in object'
7855 cond ; Node cond is also object in 'foo in object'
7856 incr ; 3rd section of for-loop initializer
7857 body tt lp rp)
7858 ;; See if this is a for each () instead of just a for ()
7859 (when (js2-match-token js2-NAME)
7860 (if (string= "each" (js2-current-token-string))
7861 (progn
7862 (setq is-for-each t
7863 each-pos (- (js2-current-token-beg) for-pos)) ; relative
7864 (js2-record-face 'font-lock-keyword-face))
7865 (js2-report-error "msg.no.paren.for")))
7866 (if (js2-must-match js2-LP "msg.no.paren.for")
7867 (setq lp (- (js2-current-token-beg) for-pos)))
7868 (setq tt (js2-get-token))
7869 ;; 'for' makes local scope
7870 (js2-push-scope (make-js2-scope))
7871 (unwind-protect
7872 ;; parse init clause
7873 (let ((js2-in-for-init t)) ; set as dynamic variable
7874 (cond
7875 ((= tt js2-SEMI)
7876 (js2-unget-token)
7877 (setq init (make-js2-empty-expr-node)))
7878 ((or (= tt js2-VAR) (= tt js2-LET))
7879 (setq init (js2-parse-variables tt (js2-current-token-beg))))
7880 (t
7881 (js2-unget-token)
7882 (setq init (js2-parse-expr)))))
7883 (if (or (js2-match-token js2-IN)
7884 (and (>= js2-language-version 200)
7885 (js2-match-contextual-kwd "of")
7886 (setq is-for-of t)))
7887 (setq is-for-in-or-of t
7888 in-pos (- (js2-current-token-beg) for-pos)
7889 ;; scope of iteration target object is not the scope we've created above.
7890 ;; stash current scope temporary.
7891 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7892 (js2-parse-expr))) ; object over which we're iterating
7893 ;; else ordinary for loop - parse cond and incr
7894 (js2-must-match js2-SEMI "msg.no.semi.for")
7895 (setq cond (if (= (js2-peek-token) js2-SEMI)
7896 (make-js2-empty-expr-node) ; no loop condition
7897 (js2-parse-expr)))
7898 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7899 (setq tmp-pos (js2-current-token-end)
7900 incr (if (= (js2-peek-token) js2-RP)
7901 (make-js2-empty-expr-node :pos tmp-pos)
7902 (js2-parse-expr))))
7903 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7904 (setq rp (- (js2-current-token-beg) for-pos)))
7905 (if (not is-for-in-or-of)
7906 (setq pn (make-js2-for-node :init init
7907 :condition cond
7908 :update incr
7909 :lp lp
7910 :rp rp))
7911 ;; cond could be null if 'in obj' got eaten by the init node.
7912 (if (js2-infix-node-p init)
7913 ;; it was (foo in bar) instead of (var foo in bar)
7914 (setq cond (js2-infix-node-right init)
7915 init (js2-infix-node-left init))
7916 (if (and (js2-var-decl-node-p init)
7917 (> (length (js2-var-decl-node-kids init)) 1))
7918 (js2-report-error "msg.mult.index")))
7919 (setq pn (make-js2-for-in-node :iterator init
7920 :object cond
7921 :in-pos in-pos
7922 :foreach-p is-for-each
7923 :each-pos each-pos
7924 :forof-p is-for-of
7925 :lp lp
7926 :rp rp)))
7927 (unwind-protect
7928 (progn
7929 (js2-enter-loop pn)
7930 ;; We have to parse the body -after- creating the loop node,
7931 ;; so that the loop node appears in the js2-loop-set, allowing
7932 ;; break/continue statements to find the enclosing loop.
7933 (setf body (js2-parse-statement)
7934 (js2-loop-node-body pn) body
7935 (js2-node-pos pn) for-pos
7936 (js2-node-len pn) (- (js2-node-end body) for-pos))
7937 (js2-node-add-children pn init cond incr body))
7938 ;; finally
7939 (js2-exit-loop))
7940 (js2-pop-scope))
7941 pn))
7942
7943 (defun js2-parse-try ()
7944 "Parser for try-statement. Last matched token must be js2-TRY."
7945 (let ((try-pos (js2-current-token-beg))
7946 try-end
7947 try-block
7948 catch-blocks
7949 finally-block
7950 saw-default-catch
7951 peek
7952 param
7953 catch-cond
7954 catch-node
7955 guard-kwd
7956 catch-pos
7957 finally-pos
7958 pn
7959 block
7960 lp
7961 rp)
7962 (if (/= (js2-peek-token) js2-LC)
7963 (js2-report-error "msg.no.brace.try"))
7964 (setq try-block (js2-parse-statement)
7965 try-end (js2-node-end try-block)
7966 peek (js2-peek-token))
7967 (cond
7968 ((= peek js2-CATCH)
7969 (while (js2-match-token js2-CATCH)
7970 (setq catch-pos (js2-current-token-beg)
7971 guard-kwd nil
7972 catch-cond nil
7973 lp nil
7974 rp nil)
7975 (if saw-default-catch
7976 (js2-report-error "msg.catch.unreachable"))
7977 (if (js2-must-match js2-LP "msg.no.paren.catch")
7978 (setq lp (- (js2-current-token-beg) catch-pos)))
7979 (js2-push-scope (make-js2-scope))
7980 (let ((tt (js2-peek-token)))
7981 (cond
7982 ;; destructuring pattern
7983 ;; catch ({ message, file }) { ... }
7984 ((or (= tt js2-LB) (= tt js2-LC))
7985 (js2-get-token)
7986 (setq param (js2-parse-destruct-primary-expr))
7987 (js2-define-destruct-symbols param js2-LET nil))
7988 ;; simple name
7989 (t
7990 (js2-must-match-name "msg.bad.catchcond")
7991 (setq param (js2-create-name-node))
7992 (js2-define-symbol js2-LET (js2-current-token-string) param))))
7993 ;; pattern guard
7994 (if (js2-match-token js2-IF)
7995 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
7996 catch-cond (js2-parse-expr))
7997 (setq saw-default-catch t))
7998 (if (js2-must-match js2-RP "msg.bad.catchcond")
7999 (setq rp (- (js2-current-token-beg) catch-pos)))
8000 (js2-must-match js2-LC "msg.no.brace.catchblock")
8001 (setq block (js2-parse-statements)
8002 try-end (js2-node-end block)
8003 catch-node (make-js2-catch-node :pos catch-pos
8004 :param param
8005 :guard-expr catch-cond
8006 :guard-kwd guard-kwd
8007 :block block
8008 :lp lp
8009 :rp rp))
8010 (js2-pop-scope)
8011 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8012 (setq try-end (js2-current-token-beg)))
8013 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8014 (js2-node-len catch-node) (- try-end catch-pos))
8015 (js2-node-add-children catch-node param catch-cond block)
8016 (push catch-node catch-blocks)))
8017 ((/= peek js2-FINALLY)
8018 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8019 (js2-node-pos try-block)
8020 (- (setq try-end (js2-node-end try-block))
8021 (js2-node-pos try-block)))))
8022 (when (js2-match-token js2-FINALLY)
8023 (setq finally-pos (js2-current-token-beg)
8024 block (js2-parse-statement)
8025 try-end (js2-node-end block)
8026 finally-block (make-js2-finally-node :pos finally-pos
8027 :len (- try-end finally-pos)
8028 :body block))
8029 (js2-node-add-children finally-block block))
8030 (setq pn (make-js2-try-node :pos try-pos
8031 :len (- try-end try-pos)
8032 :try-block try-block
8033 :finally-block finally-block))
8034 (js2-node-add-children pn try-block finally-block)
8035 ;; push them onto the try-node, which reverses and corrects their order
8036 (dolist (cb catch-blocks)
8037 (js2-node-add-children pn cb)
8038 (push cb (js2-try-node-catch-clauses pn)))
8039 pn))
8040
8041 (defun js2-parse-throw ()
8042 "Parser for throw-statement. Last matched token must be js2-THROW."
8043 (let ((pos (js2-current-token-beg))
8044 expr pn)
8045 (if (= (js2-peek-token-or-eol) js2-EOL)
8046 ;; ECMAScript does not allow new lines before throw expression,
8047 ;; see bug 256617
8048 (js2-report-error "msg.bad.throw.eol"))
8049 (setq expr (js2-parse-expr)
8050 pn (make-js2-throw-node :pos pos
8051 :len (- (js2-node-end expr) pos)
8052 :expr expr))
8053 (js2-node-add-children pn expr)
8054 pn))
8055
8056 (defun js2-match-jump-label-name (label-name)
8057 "If break/continue specified a label, return that label's labeled stmt.
8058 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8059 does not match an existing label, reports an error and returns nil."
8060 (let ((bundle (cdr (assoc label-name js2-label-set))))
8061 (if (null bundle)
8062 (js2-report-error "msg.undef.label"))
8063 bundle))
8064
8065 (defun js2-parse-break ()
8066 "Parser for break-statement. Last matched token must be js2-BREAK."
8067 (let ((pos (js2-current-token-beg))
8068 (end (js2-current-token-end))
8069 break-target ; statement to break from
8070 break-label ; in "break foo", name-node representing the foo
8071 labels ; matching labeled statement to break to
8072 pn)
8073 (when (eq (js2-peek-token-or-eol) js2-NAME)
8074 (js2-get-token)
8075 (setq break-label (js2-create-name-node)
8076 end (js2-node-end break-label)
8077 ;; matchJumpLabelName only matches if there is one
8078 labels (js2-match-jump-label-name (js2-current-token-string))
8079 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8080 (unless (or break-target break-label)
8081 ;; no break target specified - try for innermost enclosing loop/switch
8082 (if (null js2-loop-and-switch-set)
8083 (unless break-label
8084 (js2-report-error "msg.bad.break" nil pos (length "break")))
8085 (setq break-target (car js2-loop-and-switch-set))))
8086 (setq pn (make-js2-break-node :pos pos
8087 :len (- end pos)
8088 :label break-label
8089 :target break-target))
8090 (js2-node-add-children pn break-label) ; but not break-target
8091 pn))
8092
8093 (defun js2-parse-continue ()
8094 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8095 (let ((pos (js2-current-token-beg))
8096 (end (js2-current-token-end))
8097 label ; optional user-specified label, a `js2-name-node'
8098 labels ; current matching labeled stmt, if any
8099 target ; the `js2-loop-node' target of this continue stmt
8100 pn)
8101 (when (= (js2-peek-token-or-eol) js2-NAME)
8102 (js2-get-token)
8103 (setq label (js2-create-name-node)
8104 end (js2-node-end label)
8105 ;; matchJumpLabelName only matches if there is one
8106 labels (js2-match-jump-label-name (js2-current-token-string))))
8107 (cond
8108 ((null labels) ; no current label to go to
8109 (if (null js2-loop-set) ; no loop to continue to
8110 (js2-report-error "msg.continue.outside" nil pos
8111 (length "continue"))
8112 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8113 (t
8114 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8115 (setq target (js2-labeled-stmt-node-stmt labels))
8116 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8117 (setq pn (make-js2-continue-node :pos pos
8118 :len (- end pos)
8119 :label label
8120 :target target))
8121 (js2-node-add-children pn label) ; but not target - it's not our child
8122 pn))
8123
8124 (defun js2-parse-with ()
8125 "Parser for with-statement. Last matched token must be js2-WITH."
8126 (let ((pos (js2-current-token-beg))
8127 obj body pn lp rp)
8128 (if (js2-must-match js2-LP "msg.no.paren.with")
8129 (setq lp (js2-current-token-beg)))
8130 (setq obj (js2-parse-expr))
8131 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8132 (setq rp (js2-current-token-beg)))
8133 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8134 (setq body (js2-parse-statement)))
8135 (setq pn (make-js2-with-node :pos pos
8136 :len (- (js2-node-end body) pos)
8137 :object obj
8138 :body body
8139 :lp (js2-relpos lp pos)
8140 :rp (js2-relpos rp pos)))
8141 (js2-node-add-children pn obj body)
8142 pn))
8143
8144 (defun js2-parse-const-var ()
8145 "Parser for var- or const-statement.
8146 Last matched token must be js2-CONST or js2-VAR."
8147 (let ((tt (js2-current-token-type))
8148 (pos (js2-current-token-beg))
8149 expr pn)
8150 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8151 pn (make-js2-expr-stmt-node :pos pos
8152 :len (- (js2-node-end expr) pos)
8153 :expr expr))
8154 (js2-node-add-children pn expr)
8155 pn))
8156
8157 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8158 (let ((pn (make-js2-expr-stmt-node :pos pos
8159 :len (js2-node-len expr)
8160 :type (if (js2-inside-function)
8161 js2-EXPR_VOID
8162 js2-EXPR_RESULT)
8163 :expr expr)))
8164 (if add-child
8165 (js2-node-add-children pn expr))
8166 pn))
8167
8168 (defun js2-parse-let-stmt ()
8169 "Parser for let-statement. Last matched token must be js2-LET."
8170 (let ((pos (js2-current-token-beg))
8171 expr pn)
8172 (if (= (js2-peek-token) js2-LP)
8173 ;; let expression in statement context
8174 (setq expr (js2-parse-let pos 'statement)
8175 pn (js2-wrap-with-expr-stmt pos expr t))
8176 ;; else we're looking at a statement like let x=6, y=7;
8177 (setf expr (js2-parse-variables js2-LET pos)
8178 pn (js2-wrap-with-expr-stmt pos expr t)
8179 (js2-node-type pn) js2-EXPR_RESULT))
8180 pn))
8181
8182 (defun js2-parse-ret-yield ()
8183 (js2-parse-return-or-yield (js2-current-token-type) nil))
8184
8185 (defconst js2-parse-return-stmt-enders
8186 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8187
8188 (defsubst js2-now-all-set (before after mask)
8189 "Return whether or not the bits in the mask have changed to all set.
8190 BEFORE is bits before change, AFTER is bits after change, and MASK is
8191 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8192 but not BEFORE."
8193 (and (/= (logand before mask) mask)
8194 (= (logand after mask) mask)))
8195
8196 (defun js2-parse-return-or-yield (tt expr-context)
8197 (let* ((pos (js2-current-token-beg))
8198 (end (js2-current-token-end))
8199 (before js2-end-flags)
8200 (inside-function (js2-inside-function))
8201 (gen-type (and inside-function (js2-function-node-generator-type
8202 js2-current-script-or-fn)))
8203 e ret name yield-star-p)
8204 (unless inside-function
8205 (js2-report-error (if (eq tt js2-RETURN)
8206 "msg.bad.return"
8207 "msg.bad.yield")))
8208 (when (and inside-function
8209 (eq gen-type 'STAR)
8210 (js2-match-token js2-MUL))
8211 (setq yield-star-p t))
8212 ;; This is ugly, but we don't want to require a semicolon.
8213 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8214 (setq e (js2-parse-expr)
8215 end (js2-node-end e)))
8216 (cond
8217 ((eq tt js2-RETURN)
8218 (js2-set-flag js2-end-flags (if (null e)
8219 js2-end-returns
8220 js2-end-returns-value))
8221 (setq ret (make-js2-return-node :pos pos
8222 :len (- end pos)
8223 :retval e))
8224 (js2-node-add-children ret e)
8225 ;; See if we need a strict mode warning.
8226 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8227 ;; more thorough and accurate than this before/after flag check.
8228 ;; E.g. if there's a finally-block that always returns, we shouldn't
8229 ;; show a warning generated by inconsistent returns in the catch blocks.
8230 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8231 ;; so we know which returns/yields to highlight, and we should get rid of
8232 ;; all the checking in `js2-parse-return-or-yield'.
8233 (if (and js2-strict-inconsistent-return-warning
8234 (js2-now-all-set before js2-end-flags
8235 (logior js2-end-returns js2-end-returns-value)))
8236 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8237 ((eq gen-type 'COMPREHENSION)
8238 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8239 ;; like SpiderMonkey does.
8240 (js2-report-error "msg.syntax" nil pos 5))
8241 (t
8242 (setq ret (make-js2-yield-node :pos pos
8243 :len (- end pos)
8244 :value e
8245 :star-p yield-star-p))
8246 (js2-node-add-children ret e)
8247 (unless expr-context
8248 (setq e ret
8249 ret (js2-wrap-with-expr-stmt pos e t))
8250 (js2-set-requires-activation)
8251 (js2-set-is-generator))))
8252 ;; see if we are mixing yields and value returns.
8253 (when (and inside-function
8254 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8255 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8256 'LEGACY))
8257 (setq name (js2-function-name js2-current-script-or-fn))
8258 (if (zerop (length name))
8259 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8260 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8261 ret))
8262
8263 (defun js2-parse-debugger ()
8264 (make-js2-keyword-node :type js2-DEBUGGER))
8265
8266 (defun js2-parse-block ()
8267 "Parser for a curly-delimited statement block.
8268 Last token matched must be `js2-LC'."
8269 (let ((pos (js2-current-token-beg))
8270 (pn (make-js2-scope)))
8271 (js2-push-scope pn)
8272 (unwind-protect
8273 (progn
8274 (js2-parse-statements pn)
8275 (js2-must-match js2-RC "msg.no.brace.block")
8276 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8277 (js2-pop-scope))
8278 pn))
8279
8280 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8281 (defun js2-parse-semi ()
8282 "Parse a statement or handle an error.
8283 Current token type is `js2-SEMI' or `js2-ERROR'."
8284 (let ((tt (js2-current-token-type)) pos len)
8285 (if (eq tt js2-SEMI)
8286 (make-js2-empty-expr-node :len 1)
8287 (setq pos (js2-current-token-beg)
8288 len (- (js2-current-token-end) pos))
8289 (js2-report-error "msg.syntax" nil pos len)
8290 (make-js2-error-node :pos pos :len len))))
8291
8292 (defun js2-parse-default-xml-namespace ()
8293 "Parse a `default xml namespace = <expr>' e4x statement."
8294 (let ((pos (js2-current-token-beg))
8295 end len expr unary)
8296 (js2-must-have-xml)
8297 (js2-set-requires-activation)
8298 (setq len (- js2-ts-cursor pos))
8299 (unless (and (js2-match-token js2-NAME)
8300 (string= (js2-current-token-string) "xml"))
8301 (js2-report-error "msg.bad.namespace" nil pos len))
8302 (unless (and (js2-match-token js2-NAME)
8303 (string= (js2-current-token-string) "namespace"))
8304 (js2-report-error "msg.bad.namespace" nil pos len))
8305 (unless (js2-match-token js2-ASSIGN)
8306 (js2-report-error "msg.bad.namespace" nil pos len))
8307 (setq expr (js2-parse-expr)
8308 end (js2-node-end expr)
8309 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8310 :pos pos
8311 :len (- end pos)
8312 :operand expr))
8313 (js2-node-add-children unary expr)
8314 (make-js2-expr-stmt-node :pos pos
8315 :len (- end pos)
8316 :expr unary)))
8317
8318 (defun js2-record-label (label bundle)
8319 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8320 (js2-get-token)
8321 (let ((name (js2-label-node-name label))
8322 labeled-stmt
8323 dup)
8324 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8325 ;; flag both labels if possible when used in editing mode
8326 (if (and js2-parse-ide-mode
8327 (setq dup (js2-get-label-by-name labeled-stmt name)))
8328 (js2-report-error "msg.dup.label" nil
8329 (js2-node-abs-pos dup) (js2-node-len dup)))
8330 (js2-report-error "msg.dup.label" nil
8331 (js2-node-pos label) (js2-node-len label)))
8332 (js2-labeled-stmt-node-add-label bundle label)
8333 (js2-node-add-children bundle label)
8334 ;; Add one reference to the bundle per label in `js2-label-set'
8335 (push (cons name bundle) js2-label-set)))
8336
8337 (defun js2-parse-name-or-label ()
8338 "Parser for identifier or label. Last token matched must be js2-NAME.
8339 Called when we found a name in a statement context. If it's a label, we gather
8340 up any following labels and the next non-label statement into a
8341 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8342 expression and return it wrapped in a `js2-expr-stmt-node'."
8343 (let ((pos (js2-current-token-beg))
8344 expr stmt bundle
8345 (continue t))
8346 ;; set check for label and call down to `js2-parse-primary-expr'
8347 (setq expr (js2-maybe-parse-label))
8348 (if (null expr)
8349 ;; Parse the non-label expression and wrap with expression stmt.
8350 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
8351 ;; else parsed a label
8352 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8353 (js2-record-label expr bundle)
8354 ;; look for more labels
8355 (while (and continue (= (js2-get-token) js2-NAME))
8356 (if (setq expr (js2-maybe-parse-label))
8357 (js2-record-label expr bundle)
8358 (setq expr (js2-parse-expr)
8359 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8360 continue nil)
8361 (js2-auto-insert-semicolon stmt)))
8362 ;; no more labels; now parse the labeled statement
8363 (unwind-protect
8364 (unless stmt
8365 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8366 (js2-unget-token)
8367 (setq stmt (js2-statement-helper))))
8368 ;; remove the labels for this statement from the global set
8369 (dolist (label (js2-labeled-stmt-node-labels bundle))
8370 (setq js2-label-set (remove label js2-label-set))))
8371 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8372 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8373 (js2-node-add-children bundle stmt)
8374 bundle)))
8375
8376 (defun js2-maybe-parse-label ()
8377 (assert (= (js2-current-token-type) js2-NAME))
8378 (let (label-pos
8379 (next-tt (js2-get-token))
8380 (label-end (js2-current-token-end)))
8381 ;; Do not consume colon, it is used as unwind indicator
8382 ;; to return to statementHelper.
8383 (js2-unget-token)
8384 (if (= next-tt js2-COLON)
8385 (prog2
8386 (setq label-pos (js2-current-token-beg))
8387 (make-js2-label-node :pos label-pos
8388 :len (- label-end label-pos)
8389 :name (js2-current-token-string))
8390 (js2-set-face label-pos
8391 label-end
8392 'font-lock-variable-name-face 'record))
8393 ;; Backtrack from the name token, too.
8394 (js2-unget-token)
8395 nil)))
8396
8397 (defun js2-parse-expr-stmt ()
8398 "Default parser in statement context, if no recognized statement found."
8399 (js2-wrap-with-expr-stmt (js2-current-token-beg)
8400 (progn
8401 (js2-unget-token)
8402 (js2-parse-expr)) t))
8403
8404 (defun js2-parse-variables (decl-type pos)
8405 "Parse a comma-separated list of variable declarations.
8406 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8407
8408 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8409 For 'var' or 'const', the keyword should be the token last scanned.
8410
8411 POS is the position where the node should start. It's sometimes the
8412 var/const/let keyword, and other times the beginning of the first token
8413 in the first variable declaration.
8414
8415 Returns the parsed `js2-var-decl-node' expression node."
8416 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8417 :pos pos))
8418 destructuring kid-pos tt init name end nbeg nend vi
8419 (continue t))
8420 ;; Example:
8421 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8422 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8423 ;; var {a, b} = baz;
8424 (while continue
8425 (setq destructuring nil
8426 name nil
8427 tt (js2-get-token)
8428 kid-pos (js2-current-token-beg)
8429 end (js2-current-token-end)
8430 init nil)
8431 (if (or (= tt js2-LB) (= tt js2-LC))
8432 ;; Destructuring assignment, e.g., var [a, b] = ...
8433 (setq destructuring (js2-parse-destruct-primary-expr)
8434 end (js2-node-end destructuring))
8435 ;; Simple variable name
8436 (js2-unget-token)
8437 (when (js2-must-match-name "msg.bad.var")
8438 (setq name (js2-create-name-node)
8439 nbeg (js2-current-token-beg)
8440 nend (js2-current-token-end)
8441 end nend)
8442 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
8443 (when (js2-match-token js2-ASSIGN)
8444 (setq init (js2-parse-assign-expr)
8445 end (js2-node-end init))
8446 (js2-record-imenu-functions init name))
8447 (when name
8448 (js2-set-face nbeg nend (if (js2-function-node-p init)
8449 'font-lock-function-name-face
8450 'font-lock-variable-name-face)
8451 'record))
8452 (setq vi (make-js2-var-init-node :pos kid-pos
8453 :len (- end kid-pos)
8454 :type decl-type))
8455 (if destructuring
8456 (progn
8457 (if (and (null init) (not js2-in-for-init))
8458 (js2-report-error "msg.destruct.assign.no.init"))
8459 (js2-define-destruct-symbols destructuring
8460 decl-type
8461 'font-lock-variable-name-face)
8462 (setf (js2-var-init-node-target vi) destructuring))
8463 (setf (js2-var-init-node-target vi) name))
8464 (setf (js2-var-init-node-initializer vi) init)
8465 (js2-node-add-children vi name destructuring init)
8466 (js2-block-node-push result vi)
8467 (unless (js2-match-token js2-COMMA)
8468 (setq continue nil)))
8469 (setf (js2-node-len result) (- end pos))
8470 result))
8471
8472 (defun js2-parse-let (pos &optional stmt-p)
8473 "Parse a let expression or statement.
8474 A let-expression is of the form `let (vars) expr'.
8475 A let-statment is of the form `let (vars) {statements}'.
8476 The third form of let is a variable declaration list, handled
8477 by `js2-parse-variables'."
8478 (let ((pn (make-js2-let-node :pos pos))
8479 beg vars body)
8480 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8481 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
8482 (js2-push-scope pn)
8483 (unwind-protect
8484 (progn
8485 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
8486 (if (js2-must-match js2-RP "msg.no.paren.let")
8487 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
8488 (if (and stmt-p (js2-match-token js2-LC))
8489 ;; let statement
8490 (progn
8491 (setf beg (js2-current-token-beg) ; position stmt at LC
8492 body (js2-parse-statements))
8493 (js2-must-match js2-RC "msg.no.curly.let")
8494 (setf (js2-node-len body) (- (js2-current-token-end) beg)
8495 (js2-node-len pn) (- (js2-current-token-end) pos)
8496 (js2-let-node-body pn) body
8497 (js2-node-type pn) js2-LET))
8498 ;; let expression
8499 (setf body (js2-parse-expr)
8500 (js2-node-len pn) (- (js2-node-end body) pos)
8501 (js2-let-node-body pn) body))
8502 (setf (js2-let-node-vars pn) vars)
8503 (js2-node-add-children pn vars body))
8504 (js2-pop-scope))
8505 pn))
8506
8507 (defun js2-define-new-symbol (decl-type name node &optional scope)
8508 (js2-scope-put-symbol (or scope js2-current-scope)
8509 name
8510 (make-js2-symbol decl-type name node)))
8511
8512 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8513 "Define a symbol in the current scope.
8514 If NODE is non-nil, it is the AST node associated with the symbol."
8515 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8516 (symbol (if defining-scope
8517 (js2-scope-get-symbol defining-scope name)))
8518 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8519 (cond
8520 ((and symbol ; already defined
8521 (or (= sdt js2-CONST) ; old version is const
8522 (= decl-type js2-CONST) ; new version is const
8523 ;; two let-bound vars in this block have same name
8524 (and (= sdt js2-LET)
8525 (eq defining-scope js2-current-scope))))
8526 (js2-report-error
8527 (cond
8528 ((= sdt js2-CONST) "msg.const.redecl")
8529 ((= sdt js2-LET) "msg.let.redecl")
8530 ((= sdt js2-VAR) "msg.var.redecl")
8531 ((= sdt js2-FUNCTION) "msg.function.redecl")
8532 (t "msg.parm.redecl"))
8533 name))
8534 ((= decl-type js2-LET)
8535 (if (and (not ignore-not-in-block)
8536 (or (= (js2-node-type js2-current-scope) js2-IF)
8537 (js2-loop-node-p js2-current-scope)))
8538 (js2-report-error "msg.let.decl.not.in.block")
8539 (js2-define-new-symbol decl-type name node)))
8540 ((or (= decl-type js2-VAR)
8541 (= decl-type js2-CONST)
8542 (= decl-type js2-FUNCTION))
8543 (if symbol
8544 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8545 (js2-add-strict-warning "msg.var.redecl" name)
8546 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8547 (js2-add-strict-warning "msg.var.hides.arg" name)))
8548 (js2-define-new-symbol decl-type name node
8549 js2-current-script-or-fn)))
8550 ((= decl-type js2-LP)
8551 (if symbol
8552 ;; must be duplicate parameter. Second parameter hides the
8553 ;; first, so go ahead and add the second pararameter
8554 (js2-report-warning "msg.dup.parms" name))
8555 (js2-define-new-symbol decl-type name node))
8556 (t (js2-code-bug)))))
8557
8558 (defun js2-parse-paren-expr-or-generator-comp ()
8559 (let ((px-pos (js2-current-token-beg)))
8560 (if (and (>= js2-language-version 200)
8561 (js2-match-token js2-FOR))
8562 (js2-parse-generator-comp px-pos)
8563 (let* ((js2-in-for-init nil)
8564 (expr (js2-parse-expr))
8565 (pn (make-js2-paren-node :pos px-pos
8566 :expr expr
8567 :len (- (js2-current-token-end)
8568 px-pos))))
8569 (js2-node-add-children pn (js2-paren-node-expr pn))
8570 (js2-must-match js2-RP "msg.no.paren")
8571 pn))))
8572
8573 (defun js2-parse-expr (&optional oneshot)
8574 (let* ((pn (js2-parse-assign-expr))
8575 (pos (js2-node-pos pn))
8576 left
8577 right
8578 op-pos)
8579 (while (and (not oneshot)
8580 (js2-match-token js2-COMMA))
8581 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
8582 (if (= (js2-peek-token) js2-YIELD)
8583 (js2-report-error "msg.yield.parenthesized"))
8584 (setq right (js2-parse-assign-expr)
8585 left pn
8586 pn (make-js2-infix-node :type js2-COMMA
8587 :pos pos
8588 :len (- js2-ts-cursor pos)
8589 :op-pos op-pos
8590 :left left
8591 :right right))
8592 (js2-node-add-children pn left right))
8593 pn))
8594
8595 (defun js2-parse-assign-expr ()
8596 (let ((tt (js2-get-token))
8597 (pos (js2-current-token-beg))
8598 pn left right op-pos
8599 ts-state recorded-identifiers parsed-errors)
8600 (if (= tt js2-YIELD)
8601 (js2-parse-return-or-yield tt t)
8602 ;; Save the tokenizer state in case we find an arrow function
8603 ;; and have to rewind.
8604 (setq ts-state (make-js2-ts-state)
8605 recorded-identifiers js2-recorded-identifiers
8606 parsed-errors js2-parsed-errors)
8607 ;; not yield - parse assignment expression
8608 (setq pn (js2-parse-cond-expr)
8609 tt (js2-get-token))
8610 (cond
8611 ((and (<= js2-first-assign tt)
8612 (<= tt js2-last-assign))
8613 ;; tt express assignment (=, |=, ^=, ..., %=)
8614 (setq op-pos (- (js2-current-token-beg) pos) ; relative
8615 left pn)
8616 (setq right (js2-parse-assign-expr)
8617 pn (make-js2-assign-node :type tt
8618 :pos pos
8619 :len (- (js2-node-end right) pos)
8620 :op-pos op-pos
8621 :left left
8622 :right right))
8623 (when js2-parse-ide-mode
8624 (js2-highlight-assign-targets pn left right)
8625 (js2-record-imenu-functions right left))
8626 ;; do this last so ide checks above can use absolute positions
8627 (js2-node-add-children pn left right))
8628 ((and (= tt js2-ARROW)
8629 (>= js2-language-version 200))
8630 (js2-ts-seek ts-state)
8631 (setq js2-recorded-identifiers recorded-identifiers
8632 js2-parsed-errors parsed-errors)
8633 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
8634 (t
8635 (js2-unget-token)))
8636 pn)))
8637
8638 (defun js2-parse-cond-expr ()
8639 (let ((pos (js2-current-token-beg))
8640 (pn (js2-parse-or-expr))
8641 test-expr
8642 if-true
8643 if-false
8644 q-pos
8645 c-pos)
8646 (when (js2-match-token js2-HOOK)
8647 (setq q-pos (- (js2-current-token-beg) pos)
8648 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
8649 (js2-must-match js2-COLON "msg.no.colon.cond")
8650 (setq c-pos (- (js2-current-token-beg) pos)
8651 if-false (js2-parse-assign-expr)
8652 test-expr pn
8653 pn (make-js2-cond-node :pos pos
8654 :len (- (js2-node-end if-false) pos)
8655 :test-expr test-expr
8656 :true-expr if-true
8657 :false-expr if-false
8658 :q-pos q-pos
8659 :c-pos c-pos))
8660 (js2-node-add-children pn test-expr if-true if-false))
8661 pn))
8662
8663 (defun js2-make-binary (type left parser)
8664 "Helper for constructing a binary-operator AST node.
8665 LEFT is the left-side-expression, already parsed, and the
8666 binary operator should have just been matched.
8667 PARSER is a function to call to parse the right operand,
8668 or a `js2-node' struct if it has already been parsed.
8669 FIXME: The latter option is unused?"
8670 (let* ((pos (js2-node-pos left))
8671 (op-pos (- (js2-current-token-beg) pos))
8672 (right (if (js2-node-p parser)
8673 parser
8674 (js2-get-token)
8675 (funcall parser)))
8676 (pn (make-js2-infix-node :type type
8677 :pos pos
8678 :len (- (js2-node-end right) pos)
8679 :op-pos op-pos
8680 :left left
8681 :right right)))
8682 (js2-node-add-children pn left right)
8683 pn))
8684
8685 (defun js2-parse-or-expr ()
8686 (let ((pn (js2-parse-and-expr)))
8687 (when (js2-match-token js2-OR)
8688 (setq pn (js2-make-binary js2-OR
8689 pn
8690 'js2-parse-or-expr)))
8691 pn))
8692
8693 (defun js2-parse-and-expr ()
8694 (let ((pn (js2-parse-bit-or-expr)))
8695 (when (js2-match-token js2-AND)
8696 (setq pn (js2-make-binary js2-AND
8697 pn
8698 'js2-parse-and-expr)))
8699 pn))
8700
8701 (defun js2-parse-bit-or-expr ()
8702 (let ((pn (js2-parse-bit-xor-expr)))
8703 (while (js2-match-token js2-BITOR)
8704 (setq pn (js2-make-binary js2-BITOR
8705 pn
8706 'js2-parse-bit-xor-expr)))
8707 pn))
8708
8709 (defun js2-parse-bit-xor-expr ()
8710 (let ((pn (js2-parse-bit-and-expr)))
8711 (while (js2-match-token js2-BITXOR)
8712 (setq pn (js2-make-binary js2-BITXOR
8713 pn
8714 'js2-parse-bit-and-expr)))
8715 pn))
8716
8717 (defun js2-parse-bit-and-expr ()
8718 (let ((pn (js2-parse-eq-expr)))
8719 (while (js2-match-token js2-BITAND)
8720 (setq pn (js2-make-binary js2-BITAND
8721 pn
8722 'js2-parse-eq-expr)))
8723 pn))
8724
8725 (defconst js2-parse-eq-ops
8726 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8727
8728 (defun js2-parse-eq-expr ()
8729 (let ((pn (js2-parse-rel-expr))
8730 tt)
8731 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
8732 (setq pn (js2-make-binary tt
8733 pn
8734 'js2-parse-rel-expr)))
8735 (js2-unget-token)
8736 pn))
8737
8738 (defconst js2-parse-rel-ops
8739 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8740
8741 (defun js2-parse-rel-expr ()
8742 (let ((pn (js2-parse-shift-expr))
8743 (continue t)
8744 tt)
8745 (while continue
8746 (setq tt (js2-get-token))
8747 (cond
8748 ((and js2-in-for-init (= tt js2-IN))
8749 (js2-unget-token)
8750 (setq continue nil))
8751 ((memq tt js2-parse-rel-ops)
8752 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8753 (t
8754 (js2-unget-token)
8755 (setq continue nil))))
8756 pn))
8757
8758 (defconst js2-parse-shift-ops
8759 (list js2-LSH js2-URSH js2-RSH))
8760
8761 (defun js2-parse-shift-expr ()
8762 (let ((pn (js2-parse-add-expr))
8763 tt
8764 (continue t))
8765 (while continue
8766 (setq tt (js2-get-token))
8767 (if (memq tt js2-parse-shift-ops)
8768 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
8769 (js2-unget-token)
8770 (setq continue nil)))
8771 pn))
8772
8773 (defun js2-parse-add-expr ()
8774 (let ((pn (js2-parse-mul-expr))
8775 tt
8776 (continue t))
8777 (while continue
8778 (setq tt (js2-get-token))
8779 (if (or (= tt js2-ADD) (= tt js2-SUB))
8780 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
8781 (js2-unget-token)
8782 (setq continue nil)))
8783 pn))
8784
8785 (defconst js2-parse-mul-ops
8786 (list js2-MUL js2-DIV js2-MOD))
8787
8788 (defun js2-parse-mul-expr ()
8789 (let ((pn (js2-parse-unary-expr))
8790 tt
8791 (continue t))
8792 (while continue
8793 (setq tt (js2-get-token))
8794 (if (memq tt js2-parse-mul-ops)
8795 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
8796 (js2-unget-token)
8797 (setq continue nil)))
8798 pn))
8799
8800 (defun js2-make-unary (type parser &rest args)
8801 "Make a unary node of type TYPE.
8802 PARSER is either a node (for postfix operators) or a function to call
8803 to parse the operand (for prefix operators)."
8804 (let* ((pos (js2-current-token-beg))
8805 (postfix (js2-node-p parser))
8806 (expr (if postfix
8807 parser
8808 (apply parser args)))
8809 end
8810 pn)
8811 (if postfix ; e.g. i++
8812 (setq pos (js2-node-pos expr)
8813 end (js2-current-token-end))
8814 (setq end (js2-node-end expr)))
8815 (setq pn (make-js2-unary-node :type type
8816 :pos pos
8817 :len (- end pos)
8818 :operand expr))
8819 (js2-node-add-children pn expr)
8820 pn))
8821
8822 (defconst js2-incrementable-node-types
8823 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8824 "Node types that can be the operand of a ++ or -- operator.")
8825
8826 (defun js2-check-bad-inc-dec (tt beg end unary)
8827 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8828 js2-incrementable-node-types)
8829 (js2-report-error (if (= tt js2-INC)
8830 "msg.bad.incr"
8831 "msg.bad.decr")
8832 nil beg (- end beg))))
8833
8834 (defun js2-parse-unary-expr ()
8835 (let ((tt (js2-current-token-type))
8836 pn expr beg end)
8837 (cond
8838 ((or (= tt js2-VOID)
8839 (= tt js2-NOT)
8840 (= tt js2-BITNOT)
8841 (= tt js2-TYPEOF))
8842 (js2-get-token)
8843 (js2-make-unary tt 'js2-parse-unary-expr))
8844 ((= tt js2-ADD)
8845 (js2-get-token)
8846 ;; Convert to special POS token in decompiler and parse tree
8847 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8848 ((= tt js2-SUB)
8849 (js2-get-token)
8850 ;; Convert to special NEG token in decompiler and parse tree
8851 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8852 ((or (= tt js2-INC)
8853 (= tt js2-DEC))
8854 (js2-get-token)
8855 (prog1
8856 (setq beg (js2-current-token-beg)
8857 end (js2-current-token-end)
8858 expr (js2-make-unary tt 'js2-parse-member-expr t))
8859 (js2-check-bad-inc-dec tt beg end expr)))
8860 ((= tt js2-DELPROP)
8861 (js2-get-token)
8862 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8863 ((= tt js2-ERROR)
8864 (js2-get-token)
8865 (make-js2-error-node)) ; try to continue
8866 ((and (= tt js2-LT)
8867 js2-compiler-xml-available)
8868 ;; XML stream encountered in expression.
8869 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8870 (t
8871 (setq pn (js2-parse-member-expr t)
8872 ;; Don't look across a newline boundary for a postfix incop.
8873 tt (js2-peek-token-or-eol))
8874 (when (or (= tt js2-INC) (= tt js2-DEC))
8875 (js2-get-token)
8876 (setf expr pn
8877 pn (js2-make-unary tt expr))
8878 (js2-node-set-prop pn 'postfix t)
8879 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
8880 pn))))
8881
8882 (defun js2-parse-xml-initializer ()
8883 "Parse an E4X XML initializer.
8884 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8885 Then I'll postprocess the result, depending on whether we're in IDE
8886 mode or codegen mode, and generate the appropriate rewritten AST.
8887 IDE mode uses a rich AST that models the XML structure. Codegen mode
8888 just concatenates everything and makes a new XML or XMLList out of it."
8889 (let ((tt (js2-get-first-xml-token))
8890 pn-xml pn expr kids expr-pos
8891 (continue t)
8892 (first-token t))
8893 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8894 (js2-report-error "msg.syntax"))
8895 (setq pn-xml (make-js2-xml-node))
8896 (while continue
8897 (if first-token
8898 (setq first-token nil)
8899 (setq tt (js2-get-next-xml-token)))
8900 (cond
8901 ;; js2-XML means we found a {expr} in the XML stream.
8902 ;; The token string is the XML up to the left-curly.
8903 ((= tt js2-XML)
8904 (push (make-js2-string-node :pos (js2-current-token-beg)
8905 :len (- js2-ts-cursor (js2-current-token-beg)))
8906 kids)
8907 (js2-must-match js2-LC "msg.syntax")
8908 (setq expr-pos js2-ts-cursor
8909 expr (if (eq (js2-peek-token) js2-RC)
8910 (make-js2-empty-expr-node :pos expr-pos)
8911 (js2-parse-expr)))
8912 (js2-must-match js2-RC "msg.syntax")
8913 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8914 :len (js2-node-len expr)
8915 :expr expr))
8916 (js2-node-add-children pn expr)
8917 (push pn kids))
8918 ;; a js2-XMLEND token means we hit the final close-tag.
8919 ((= tt js2-XMLEND)
8920 (push (make-js2-string-node :pos (js2-current-token-beg)
8921 :len (- js2-ts-cursor (js2-current-token-beg)))
8922 kids)
8923 (dolist (kid (nreverse kids))
8924 (js2-block-node-push pn-xml kid))
8925 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8926 (js2-node-pos pn-xml))
8927 continue nil))
8928 (t
8929 (js2-report-error "msg.syntax")
8930 (setq continue nil))))
8931 pn-xml))
8932
8933
8934 (defun js2-parse-argument-list ()
8935 "Parse an argument list and return it as a Lisp list of nodes.
8936 Returns the list in reverse order. Consumes the right-paren token."
8937 (let (result)
8938 (unless (js2-match-token js2-RP)
8939 (loop do
8940 (let ((tt (js2-get-token)))
8941 (if (= tt js2-YIELD)
8942 (js2-report-error "msg.yield.parenthesized"))
8943 (if (and (= tt js2-TRIPLEDOT)
8944 (>= js2-language-version 200))
8945 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
8946 (js2-unget-token)
8947 (push (js2-parse-assign-expr) result)))
8948 while
8949 (js2-match-token js2-COMMA))
8950 (js2-must-match js2-RP "msg.no.paren.arg")
8951 result)))
8952
8953 (defun js2-parse-member-expr (&optional allow-call-syntax)
8954 (let ((tt (js2-current-token-type))
8955 pn pos target args beg end init)
8956 (if (/= tt js2-NEW)
8957 (setq pn (js2-parse-primary-expr))
8958 ;; parse a 'new' expression
8959 (js2-get-token)
8960 (setq pos (js2-current-token-beg)
8961 beg pos
8962 target (js2-parse-member-expr)
8963 end (js2-node-end target)
8964 pn (make-js2-new-node :pos pos
8965 :target target
8966 :len (- end pos)))
8967 (js2-highlight-function-call (js2-current-token))
8968 (js2-node-add-children pn target)
8969 (when (js2-match-token js2-LP)
8970 ;; Add the arguments to pn, if any are supplied.
8971 (setf beg pos ; start of "new" keyword
8972 pos (js2-current-token-beg)
8973 args (nreverse (js2-parse-argument-list))
8974 (js2-new-node-args pn) args
8975 end (js2-current-token-end)
8976 (js2-new-node-lp pn) (- pos beg)
8977 (js2-new-node-rp pn) (- end 1 beg))
8978 (apply #'js2-node-add-children pn args))
8979 (when (and js2-allow-rhino-new-expr-initializer
8980 (js2-match-token js2-LC))
8981 (setf init (js2-parse-object-literal)
8982 end (js2-node-end init)
8983 (js2-new-node-initializer pn) init)
8984 (js2-node-add-children pn init))
8985 (setf (js2-node-len pn) (- end beg))) ; end outer if
8986 (js2-parse-member-expr-tail allow-call-syntax pn)))
8987
8988 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8989 "Parse a chain of property/array accesses or function calls.
8990 Includes parsing for E4X operators like `..' and `.@'.
8991 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8992 Returns an expression tree that includes PN, the parent node."
8993 (let (tt
8994 (continue t))
8995 (while continue
8996 (setq tt (js2-get-token))
8997 (cond
8998 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8999 (setq pn (js2-parse-property-access tt pn)))
9000 ((= tt js2-DOTQUERY)
9001 (setq pn (js2-parse-dot-query pn)))
9002 ((= tt js2-LB)
9003 (setq pn (js2-parse-element-get pn)))
9004 ((= tt js2-LP)
9005 (js2-unget-token)
9006 (if allow-call-syntax
9007 (setq pn (js2-parse-function-call pn))
9008 (setq continue nil)))
9009 (t
9010 (js2-unget-token)
9011 (setq continue nil))))
9012 (if (>= js2-highlight-level 2)
9013 (js2-parse-highlight-member-expr-node pn))
9014 pn))
9015
9016 (defun js2-parse-dot-query (pn)
9017 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9018 Last token parsed must be `js2-DOTQUERY'."
9019 (let ((pos (js2-node-pos pn))
9020 op-pos expr end)
9021 (js2-must-have-xml)
9022 (js2-set-requires-activation)
9023 (setq op-pos (js2-current-token-beg)
9024 expr (js2-parse-expr)
9025 end (js2-node-end expr)
9026 pn (make-js2-xml-dot-query-node :left pn
9027 :pos pos
9028 :op-pos op-pos
9029 :right expr))
9030 (js2-node-add-children pn
9031 (js2-xml-dot-query-node-left pn)
9032 (js2-xml-dot-query-node-right pn))
9033 (if (js2-must-match js2-RP "msg.no.paren")
9034 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9035 end (js2-current-token-end)))
9036 (setf (js2-node-len pn) (- end pos))
9037 pn))
9038
9039 (defun js2-parse-element-get (pn)
9040 "Parse an element-get expression, e.g. foo[bar].
9041 Last token parsed must be `js2-RB'."
9042 (let ((lb (js2-current-token-beg))
9043 (pos (js2-node-pos pn))
9044 rb expr)
9045 (setq expr (js2-parse-expr))
9046 (if (js2-must-match js2-RB "msg.no.bracket.index")
9047 (setq rb (js2-current-token-beg)))
9048 (setq pn (make-js2-elem-get-node :target pn
9049 :pos pos
9050 :element expr
9051 :lb (js2-relpos lb pos)
9052 :rb (js2-relpos rb pos)
9053 :len (- (js2-current-token-end) pos)))
9054 (js2-node-add-children pn
9055 (js2-elem-get-node-target pn)
9056 (js2-elem-get-node-element pn))
9057 pn))
9058
9059 (defun js2-highlight-function-call (token)
9060 (when (eq (js2-token-type token) js2-NAME)
9061 (js2-record-face 'js2-function-call token)))
9062
9063 (defun js2-parse-function-call (pn)
9064 (js2-highlight-function-call (js2-current-token))
9065 (js2-get-token)
9066 (let (args
9067 (pos (js2-node-pos pn)))
9068 (setq pn (make-js2-call-node :pos pos
9069 :target pn
9070 :lp (- (js2-current-token-beg) pos)))
9071 (js2-node-add-children pn (js2-call-node-target pn))
9072 ;; Add the arguments to pn, if any are supplied.
9073 (setf args (nreverse (js2-parse-argument-list))
9074 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9075 (js2-call-node-args pn) args)
9076 (apply #'js2-node-add-children pn args)
9077 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9078 pn))
9079
9080 (defun js2-parse-property-access (tt pn)
9081 "Parse a property access, XML descendants access, or XML attr access."
9082 (let ((member-type-flags 0)
9083 (dot-pos (js2-current-token-beg))
9084 (dot-len (if (= tt js2-DOTDOT) 2 1))
9085 name
9086 ref ; right side of . or .. operator
9087 result)
9088 (when (= tt js2-DOTDOT)
9089 (js2-must-have-xml)
9090 (setq member-type-flags js2-descendants-flag))
9091 (if (not js2-compiler-xml-available)
9092 (progn
9093 (js2-must-match-prop-name "msg.no.name.after.dot")
9094 (setq name (js2-create-name-node t js2-GETPROP)
9095 result (make-js2-prop-get-node :left pn
9096 :pos (js2-current-token-beg)
9097 :right name
9098 :len (js2-current-token-len)))
9099 (js2-node-add-children result pn name)
9100 result)
9101 ;; otherwise look for XML operators
9102 (setf result (if (= tt js2-DOT)
9103 (make-js2-prop-get-node)
9104 (make-js2-infix-node :type js2-DOTDOT))
9105 (js2-node-pos result) (js2-node-pos pn)
9106 (js2-infix-node-op-pos result) dot-pos
9107 (js2-infix-node-left result) pn ; do this after setting position
9108 tt (js2-next-token))
9109 (cond
9110 ;; needed for generator.throw()
9111 ((= tt js2-THROW)
9112 (setq ref (js2-parse-property-name nil nil member-type-flags)))
9113 ;; handles: name, ns::name, ns::*, ns::[expr]
9114 ((js2-valid-prop-name-token tt)
9115 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9116 ;; handles: *, *::name, *::*, *::[expr]
9117 ((= tt js2-MUL)
9118 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9119 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9120 ((= tt js2-XMLATTR)
9121 (setq result (js2-parse-attribute-access)))
9122 (t
9123 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9124 (if ref
9125 (setf (js2-node-len result) (- (js2-node-end ref)
9126 (js2-node-pos result))
9127 (js2-infix-node-right result) ref))
9128 (if (js2-infix-node-p result)
9129 (js2-node-add-children result
9130 (js2-infix-node-left result)
9131 (js2-infix-node-right result)))
9132 result)))
9133
9134 (defun js2-parse-attribute-access ()
9135 "Parse an E4X XML attribute expression.
9136 This includes expressions of the forms:
9137
9138 @attr @ns::attr @ns::*
9139 @* @*::attr @*::*
9140 @[expr] @*::[expr] @ns::[expr]
9141
9142 Called if we peeked an '@' token."
9143 (let ((tt (js2-next-token))
9144 (at-pos (js2-current-token-beg)))
9145 (cond
9146 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9147 ((js2-valid-prop-name-token tt)
9148 (js2-parse-property-name at-pos nil 0))
9149 ;; handles: @*, @*::name, @*::*, @*::[expr]
9150 ((= tt js2-MUL)
9151 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9152 ;; handles @[expr]
9153 ((= tt js2-LB)
9154 (js2-parse-xml-elem-ref at-pos))
9155 (t
9156 (js2-report-error "msg.no.name.after.xmlAttr")
9157 ;; Avoid cascaded errors that happen if we make an error node here.
9158 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9159
9160 (defun js2-parse-property-name (at-pos s member-type-flags)
9161 "Check if :: follows name in which case it becomes qualified name.
9162
9163 AT-POS is a natural number if we just read an '@' token, else nil.
9164 S is the name or string that was matched: an identifier, 'throw' or '*'.
9165 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9166
9167 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9168 operator, or the name is followed by ::. For a plain name, returns a
9169 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9170 (let ((pos (or at-pos (js2-current-token-beg)))
9171 colon-pos
9172 (name (js2-create-name-node t (js2-current-token-type) s))
9173 ns tt pn)
9174 (catch 'return
9175 (when (js2-match-token js2-COLONCOLON)
9176 (setq ns name
9177 colon-pos (js2-current-token-beg)
9178 tt (js2-next-token))
9179 (cond
9180 ;; handles name::name
9181 ((js2-valid-prop-name-token tt)
9182 (setq name (js2-create-name-node)))
9183 ;; handles name::*
9184 ((= tt js2-MUL)
9185 (setq name (js2-create-name-node nil nil "*")))
9186 ;; handles name::[expr]
9187 ((= tt js2-LB)
9188 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9189 (t
9190 (js2-report-error "msg.no.name.after.coloncolon"))))
9191 (if (and (null ns) (zerop member-type-flags))
9192 name
9193 (prog1
9194 (setq pn
9195 (make-js2-xml-prop-ref-node :pos pos
9196 :len (- (js2-node-end name) pos)
9197 :at-pos at-pos
9198 :colon-pos colon-pos
9199 :propname name))
9200 (js2-node-add-children pn name))))))
9201
9202 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9203 "Parse the [expr] portion of an xml element reference.
9204 For instance, @[expr], @*::[expr], or ns::[expr]."
9205 (let* ((lb (js2-current-token-beg))
9206 (pos (or at-pos lb))
9207 rb
9208 (expr (js2-parse-expr))
9209 (end (js2-node-end expr))
9210 pn)
9211 (if (js2-must-match js2-RB "msg.no.bracket.index")
9212 (setq rb (js2-current-token-beg)
9213 end (js2-current-token-end)))
9214 (prog1
9215 (setq pn
9216 (make-js2-xml-elem-ref-node :pos pos
9217 :len (- end pos)
9218 :namespace namespace
9219 :colon-pos colon-pos
9220 :at-pos at-pos
9221 :expr expr
9222 :lb (js2-relpos lb pos)
9223 :rb (js2-relpos rb pos)))
9224 (js2-node-add-children pn namespace expr))))
9225
9226 (defun js2-parse-destruct-primary-expr ()
9227 (let ((js2-is-in-destructuring t))
9228 (js2-parse-primary-expr)))
9229
9230 (defun js2-parse-primary-expr ()
9231 "Parse a literal (leaf) expression of some sort.
9232 Includes complex literals such as functions, object-literals,
9233 array-literals, array comprehensions and regular expressions."
9234 (let (pn ; parent node (usually return value)
9235 tt)
9236 (setq tt (js2-current-token-type))
9237 (cond
9238 ((= tt js2-FUNCTION)
9239 (js2-parse-function-expr))
9240 ((= tt js2-LB)
9241 (js2-parse-array-comp-or-literal))
9242 ((= tt js2-LC)
9243 (js2-parse-object-literal))
9244 ((= tt js2-LET)
9245 (js2-parse-let (js2-current-token-beg)))
9246 ((= tt js2-LP)
9247 (js2-parse-paren-expr-or-generator-comp))
9248 ((= tt js2-XMLATTR)
9249 (js2-must-have-xml)
9250 (js2-parse-attribute-access))
9251 ((= tt js2-NAME)
9252 (js2-parse-name tt))
9253 ((= tt js2-NUMBER)
9254 (make-js2-number-node))
9255 ((= tt js2-STRING)
9256 (prog1
9257 (make-js2-string-node)
9258 (js2-record-face 'font-lock-string-face)))
9259 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9260 ;; Got / or /= which in this context means a regexp literal
9261 (let ((px-pos (js2-current-token-beg))
9262 (flags (js2-read-regexp tt))
9263 (end (js2-current-token-end)))
9264 (prog1
9265 (make-js2-regexp-node :pos px-pos
9266 :len (- end px-pos)
9267 :value (js2-current-token-string)
9268 :flags flags)
9269 (js2-set-face px-pos end 'font-lock-string-face 'record)
9270 (js2-record-text-property px-pos end 'syntax-table '(2)))))
9271 ((or (= tt js2-NULL)
9272 (= tt js2-THIS)
9273 (= tt js2-FALSE)
9274 (= tt js2-TRUE))
9275 (make-js2-keyword-node :type tt))
9276 ((= tt js2-RP)
9277 ;; Not valid expression syntax, but this is valid in an arrow
9278 ;; function with no params: () => body.
9279 (if (eq (js2-peek-token) js2-ARROW)
9280 (progn
9281 (js2-unget-token) ; Put back the right paren.
9282 ;; Return whatever, it will hopefully be rewinded and
9283 ;; reparsed when we reach the =>.
9284 (make-js2-keyword-node :type js2-NULL))
9285 (js2-report-error "msg.syntax")
9286 (make-js2-error-node)))
9287 ((= tt js2-TRIPLEDOT)
9288 ;; Likewise, only valid in an arrow function with a rest param.
9289 (if (and (js2-match-token js2-NAME)
9290 (js2-match-token js2-RP)
9291 (eq (js2-peek-token) js2-ARROW))
9292 (progn
9293 (js2-unget-token) ; Put back the right paren.
9294 ;; See the previous case.
9295 (make-js2-keyword-node :type js2-NULL))
9296 (js2-report-error "msg.syntax")
9297 (make-js2-error-node)))
9298 ((= tt js2-RESERVED)
9299 (js2-report-error "msg.reserved.id")
9300 (make-js2-name-node))
9301 ((= tt js2-ERROR)
9302 ;; the scanner or one of its subroutines reported the error.
9303 (make-js2-error-node))
9304 ((= tt js2-EOF)
9305 (let* ((px-pos (point-at-bol))
9306 (len (- js2-ts-cursor px-pos)))
9307 (js2-report-error "msg.unexpected.eof" nil px-pos len))
9308 (make-js2-error-node :pos (1- js2-ts-cursor)))
9309 (t
9310 (js2-report-error "msg.syntax")
9311 (make-js2-error-node)))))
9312
9313 (defun js2-parse-name (_tt)
9314 (let ((name (js2-current-token-string))
9315 node)
9316 (setq node (if js2-compiler-xml-available
9317 (js2-parse-property-name nil name 0)
9318 (js2-create-name-node 'check-activation nil name)))
9319 (if js2-highlight-external-variables
9320 (js2-record-name-node node))
9321 node))
9322
9323 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9324 (js2-add-strict-warning
9325 msg nil
9326 ;; back up from comma to beginning of line or array/objlit
9327 (max (if elems
9328 (js2-node-pos (car elems))
9329 pos)
9330 (save-excursion
9331 (goto-char comma-pos)
9332 (back-to-indentation)
9333 (point)))
9334 comma-pos))
9335
9336 (defun js2-parse-array-comp-or-literal ()
9337 (let ((pos (js2-current-token-beg)))
9338 (if (and (>= js2-language-version 200)
9339 (js2-match-token js2-FOR))
9340 (js2-parse-array-comp pos)
9341 (js2-parse-array-literal pos))))
9342
9343 (defun js2-parse-array-literal (pos)
9344 (let ((after-lb-or-comma t)
9345 after-comma tt elems pn
9346 (continue t))
9347 (unless js2-is-in-destructuring
9348 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
9349 (while continue
9350 (setq tt (js2-get-token))
9351 (cond
9352 ;; comma
9353 ((= tt js2-COMMA)
9354 (setq after-comma (js2-current-token-end))
9355 (if (not after-lb-or-comma)
9356 (setq after-lb-or-comma t)
9357 (push nil elems)))
9358 ;; end of array
9359 ((or (= tt js2-RB)
9360 (= tt js2-EOF)) ; prevent infinite loop
9361 (if (= tt js2-EOF)
9362 (js2-report-error "msg.no.bracket.arg" nil pos))
9363 (when (and after-comma (< js2-language-version 170))
9364 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9365 pos (remove nil elems) after-comma))
9366 (setq continue nil
9367 pn (make-js2-array-node :pos pos
9368 :len (- js2-ts-cursor pos)
9369 :elems (nreverse elems)))
9370 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
9371 ;; destructuring binding
9372 (js2-is-in-destructuring
9373 (push (if (or (= tt js2-LC)
9374 (= tt js2-LB)
9375 (= tt js2-NAME))
9376 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9377 (js2-parse-destruct-primary-expr)
9378 ;; invalid pattern
9379 (js2-report-error "msg.bad.var")
9380 (make-js2-error-node))
9381 elems)
9382 (setq after-lb-or-comma nil
9383 after-comma nil))
9384 ;; array comp
9385 ((and (>= js2-language-version 170)
9386 (= tt js2-FOR) ; check for array comprehension
9387 (not after-lb-or-comma) ; "for" can't follow a comma
9388 elems ; must have at least 1 element
9389 (not (cdr elems))) ; but no 2nd element
9390 (js2-unget-token)
9391 (setf continue nil
9392 pn (js2-parse-legacy-array-comp (car elems) pos)))
9393 ;; another element
9394 (t
9395 (unless after-lb-or-comma
9396 (js2-report-error "msg.no.bracket.arg"))
9397 (if (and (= tt js2-TRIPLEDOT)
9398 (>= js2-language-version 200))
9399 ;; spread operator
9400 (push (js2-make-unary tt 'js2-parse-assign-expr)
9401 elems)
9402 (js2-unget-token)
9403 (push (js2-parse-assign-expr) elems))
9404 (setq after-lb-or-comma nil
9405 after-comma nil))))
9406 (unless js2-is-in-destructuring
9407 (js2-pop-scope))
9408 pn))
9409
9410 (defun js2-parse-legacy-array-comp (expr pos)
9411 "Parse a legacy array comprehension (JavaScript 1.7).
9412 EXPR is the first expression after the opening left-bracket.
9413 POS is the beginning of the LB token preceding EXPR.
9414 We should have just parsed the 'for' keyword before calling this function."
9415 (let ((current-scope js2-current-scope)
9416 loops first filter result)
9417 (unwind-protect
9418 (progn
9419 (while (js2-match-token js2-FOR)
9420 (let ((loop (make-js2-comp-loop-node)))
9421 (js2-push-scope loop)
9422 (push loop loops)
9423 (js2-parse-comp-loop loop)))
9424 ;; First loop takes expr scope's parent.
9425 (setf (js2-scope-parent-scope (setq first (car (last loops))))
9426 (js2-scope-parent-scope current-scope))
9427 ;; Set expr scope's parent to the last loop.
9428 (setf (js2-scope-parent-scope current-scope) (car loops))
9429 (if (/= (js2-get-token) js2-IF)
9430 (js2-unget-token)
9431 (setq filter (js2-parse-condition))))
9432 (dotimes (_ (1- (length loops)))
9433 (js2-pop-scope)))
9434 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9435 (setq result (make-js2-comp-node :pos pos
9436 :len (- js2-ts-cursor pos)
9437 :result expr
9438 :loops (nreverse loops)
9439 :filters (and filter (list (car filter)))
9440 :form 'LEGACY_ARRAY))
9441 (apply #'js2-node-add-children result expr (car filter)
9442 (js2-comp-node-loops result))
9443 result))
9444
9445 (defun js2-parse-array-comp (pos)
9446 "Parse an ES6 array comprehension.
9447 POS is the beginning of the LB token.
9448 We should have just parsed the 'for' keyword before calling this function."
9449 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
9450 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9451 pn))
9452
9453 (defun js2-parse-generator-comp (pos)
9454 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
9455 (js2-current-script-or-fn
9456 (make-js2-function-node :generator-type 'COMPREHENSION))
9457 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
9458 (js2-must-match js2-RP "msg.no.paren" pos)
9459 pn))
9460
9461 (defun js2-parse-comprehension (pos form)
9462 (let (loops filters expr result)
9463 (unwind-protect
9464 (progn
9465 (js2-unget-token)
9466 (while (js2-match-token js2-FOR)
9467 (let ((loop (make-js2-comp-loop-node)))
9468 (js2-push-scope loop)
9469 (push loop loops)
9470 (js2-parse-comp-loop loop)))
9471 (while (js2-match-token js2-IF)
9472 (push (car (js2-parse-condition)) filters))
9473 (setq expr (js2-parse-assign-expr)))
9474 (dolist (_ loops)
9475 (js2-pop-scope)))
9476 (setq result (make-js2-comp-node :pos pos
9477 :len (- js2-ts-cursor pos)
9478 :result expr
9479 :loops (nreverse loops)
9480 :filters (nreverse filters)
9481 :form form))
9482 (apply #'js2-node-add-children result (js2-comp-node-loops result))
9483 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
9484 result))
9485
9486 (defun js2-parse-comp-loop (pn &optional only-of-p)
9487 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9488 The current token should be the initial FOR.
9489 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
9490 (let ((pos (js2-comp-loop-node-pos pn))
9491 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9492 (when (and (not only-of-p) (js2-match-token js2-NAME))
9493 (if (string= (js2-current-token-string) "each")
9494 (progn
9495 (setq foreach-p t
9496 each-pos (- (js2-current-token-beg) pos)) ; relative
9497 (js2-record-face 'font-lock-keyword-face))
9498 (js2-report-error "msg.no.paren.for")))
9499 (if (js2-must-match js2-LP "msg.no.paren.for")
9500 (setq lp (- (js2-current-token-beg) pos)))
9501 (setq tt (js2-peek-token))
9502 (cond
9503 ((or (= tt js2-LB)
9504 (= tt js2-LC))
9505 (js2-get-token)
9506 (setq iter (js2-parse-destruct-primary-expr))
9507 (js2-define-destruct-symbols iter js2-LET
9508 'font-lock-variable-name-face t))
9509 ((js2-match-token js2-NAME)
9510 (setq iter (js2-create-name-node)))
9511 (t
9512 (js2-report-error "msg.bad.var")))
9513 ;; Define as a let since we want the scope of the variable to
9514 ;; be restricted to the array comprehension
9515 (if (js2-name-node-p iter)
9516 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9517 (if (or (and (not only-of-p) (js2-match-token js2-IN))
9518 (and (>= js2-language-version 200)
9519 (js2-match-contextual-kwd "of")
9520 (setq forof-p t)))
9521 (setq in-pos (- (js2-current-token-beg) pos))
9522 (js2-report-error "msg.in.after.for.name"))
9523 (setq obj (js2-parse-expr))
9524 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9525 (setq rp (- (js2-current-token-beg) pos)))
9526 (setf (js2-node-pos pn) pos
9527 (js2-node-len pn) (- js2-ts-cursor pos)
9528 (js2-comp-loop-node-iterator pn) iter
9529 (js2-comp-loop-node-object pn) obj
9530 (js2-comp-loop-node-in-pos pn) in-pos
9531 (js2-comp-loop-node-each-pos pn) each-pos
9532 (js2-comp-loop-node-foreach-p pn) foreach-p
9533 (js2-comp-loop-node-forof-p pn) forof-p
9534 (js2-comp-loop-node-lp pn) lp
9535 (js2-comp-loop-node-rp pn) rp)
9536 (js2-node-add-children pn iter obj)
9537 pn))
9538
9539 (defun js2-parse-object-literal ()
9540 (let ((pos (js2-current-token-beg))
9541 tt elems result after-comma
9542 (continue t))
9543 (while continue
9544 (setq tt (js2-get-token))
9545 (cond
9546 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9547 ;; {get foo() {...}}, {set foo(x) {...}}, or {foo(x) {...}}
9548 ;; TODO(sdh): support *foo() {...}
9549 ((or (js2-valid-prop-name-token tt)
9550 (= tt js2-STRING))
9551 (setq after-comma nil
9552 result (js2-parse-named-prop tt))
9553 (if (and (null result)
9554 (not js2-recover-from-parse-errors))
9555 (setq continue nil)
9556 (push result elems)))
9557 ;; {12: x} or {10.7: x}
9558 ((= tt js2-NUMBER)
9559 (setq after-comma nil)
9560 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9561 ;; trailing comma
9562 ((= tt js2-RC)
9563 (js2-unget-token)
9564 (setq continue nil)
9565 (if after-comma
9566 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9567 pos elems after-comma)))
9568 (t
9569 (js2-report-error "msg.bad.prop")
9570 (unless js2-recover-from-parse-errors
9571 (setq continue nil)))) ; end switch
9572 (if (js2-match-token js2-COMMA)
9573 (setq after-comma (js2-current-token-end))
9574 (setq continue nil))) ; end loop
9575 (js2-must-match js2-RC "msg.no.brace.prop")
9576 (setq result (make-js2-object-node :pos pos
9577 :len (- js2-ts-cursor pos)
9578 :elems (nreverse elems)))
9579 (apply #'js2-node-add-children result (js2-object-node-elems result))
9580 result))
9581
9582 (defun js2-parse-named-prop (tt)
9583 "Parse a name, string, or getter/setter object property.
9584 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9585 (let ((string-prop (and (= tt js2-STRING)
9586 (make-js2-string-node)))
9587 expr
9588 (ppos (js2-current-token-beg))
9589 (pend (js2-current-token-end))
9590 (name (js2-create-name-node))
9591 (prop (js2-current-token-string)))
9592 (cond
9593 ;; getter/setter prop
9594 ((and (= tt js2-NAME)
9595 (= (js2-peek-token) js2-NAME)
9596 (or (string= prop "get")
9597 (string= prop "set")))
9598 (js2-get-token)
9599 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9600 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9601 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9602 (js2-parse-getter-setter-prop ppos name prop))
9603 ;; method definition: {f() {...}}
9604 ((and (= (js2-peek-token) js2-LP)
9605 (>= js2-language-version 200))
9606 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; name
9607 (js2-parse-getter-setter-prop ppos name ""))
9608 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9609 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9610 ;; when patterns are used in variable declarations, function parameters,
9611 ;; catch-clause, and iterators.
9612 ;; We have to set `js2-is-in-destructuring' to t when the current
9613 ;; expressions are on the left side of any assignment, but it's difficult
9614 ;; because it requires looking ahead of expression.
9615 ((and js2-is-in-destructuring
9616 (= tt js2-NAME)
9617 (let ((ctk (js2-peek-token)))
9618 (or (= ctk js2-COMMA)
9619 (= ctk js2-RC)
9620 (js2-valid-prop-name-token ctk))))
9621 name)
9622 ;; regular prop
9623 (t
9624 (prog1
9625 (setq expr (js2-parse-plain-property (or string-prop name)))
9626 (js2-set-face ppos pend
9627 (if (js2-function-node-p
9628 (js2-object-prop-node-right expr))
9629 'font-lock-function-name-face
9630 'font-lock-variable-name-face)
9631 'record))))))
9632
9633 (defun js2-parse-plain-property (prop)
9634 "Parse a non-getter/setter property in an object literal.
9635 PROP is the node representing the property: a number, name or string."
9636 (let* ((tt (js2-get-token))
9637 (pos (js2-node-pos prop))
9638 colon expr result)
9639 (cond
9640 ;; Abbreviated property, as in {foo, bar}
9641 ((and (>= js2-language-version 200)
9642 (or (= tt js2-COMMA)
9643 (= tt js2-RC)))
9644 (js2-unget-token)
9645 (setq result (make-js2-object-prop-node
9646 :pos pos
9647 :left prop
9648 :right prop
9649 :op-pos (js2-current-token-len)))
9650 (js2-node-add-children result prop)
9651 (js2-node-set-prop result 'SHORTHAND t)
9652 result)
9653 ;; Normal property
9654 (t
9655 (if (= tt js2-COLON)
9656 (setq colon (- (js2-current-token-beg) pos)
9657 expr (js2-parse-assign-expr))
9658 (js2-report-error "msg.no.colon.prop")
9659 (setq expr (make-js2-error-node)))
9660 (setq result (make-js2-object-prop-node
9661 :pos pos
9662 ;; don't include last consumed token in length
9663 :len (- (+ (js2-node-pos expr)
9664 (js2-node-len expr))
9665 pos)
9666 :left prop
9667 :right expr
9668 :op-pos colon))
9669 (js2-node-add-children result prop expr)
9670 result))))
9671
9672 (defun js2-parse-getter-setter-prop (pos prop type-string)
9673 "Parse getter or setter property in an object literal.
9674 JavaScript syntax is:
9675
9676 { get foo() {...}, set foo(x) {...} }
9677
9678 and expression closure style is also supported
9679
9680 { get foo() x, set foo(x) _x = x }
9681
9682 POS is the start position of the `get' or `set' keyword.
9683 PROP is the `js2-name-node' representing the property name.
9684 GET-P is non-nil if the keyword was `get'."
9685 (let ((type (cond
9686 ((string= "get" type-string) js2-GET)
9687 ((string= "set" type-string) js2-SET)
9688 (t js2-FUNCTION)))
9689 result end
9690 (fn (js2-parse-function-expr)))
9691 ;; it has to be an anonymous function, as we already parsed the name
9692 (if (/= (js2-node-type fn) js2-FUNCTION)
9693 (js2-report-error "msg.bad.prop")
9694 (if (plusp (length (js2-function-name fn)))
9695 (js2-report-error "msg.bad.prop")))
9696 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9697 (setq end (js2-node-end fn)
9698 result (make-js2-getter-setter-node :type type
9699 :pos pos
9700 :len (- end pos)
9701 :left prop
9702 :right fn))
9703 (js2-node-add-children result prop fn)
9704 result))
9705
9706 (defun js2-create-name-node (&optional check-activation-p token string)
9707 "Create a name node using the current token and, optionally, STRING.
9708 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
9709 (let* ((beg (js2-current-token-beg))
9710 (tt (js2-current-token-type))
9711 (s (or string
9712 (if (= js2-NAME tt)
9713 (js2-current-token-string)
9714 (js2-tt-name tt))))
9715 name)
9716 (setq name (make-js2-name-node :pos beg
9717 :name s
9718 :len (length s)))
9719 (if check-activation-p
9720 (js2-check-activation-name s (or token js2-NAME)))
9721 name))
9722
9723 ;;; Indentation support
9724
9725 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9726 ;; Karl cleverly deduces that the desired indentation level is often a
9727 ;; function of paren/bracket/brace nesting depth, which can be determined
9728 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9729 ;; then does some equally clever checks to see if we're in the context of a
9730 ;; substatement of a possibly braceless statement keyword such as if, while,
9731 ;; or finally. This approach yields pretty good results.
9732
9733 ;; The indenter is often "wrong", however, and needs to be overridden.
9734 ;; The right long-term solution is probably to emulate (or integrate
9735 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9736 ;; parse tree from `js2-parse' is present, which is not true at the
9737 ;; moment the user is typing, computing indentation is still thousands
9738 ;; of lines of code to handle every possible syntactic edge case.
9739
9740 ;; In the meantime, the compromise solution is that we offer a "bounce
9741 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9742 ;; current line indent among various likely guess points. This approach
9743 ;; is far from perfect, but should at least make it slightly easier to
9744 ;; move the line towards its desired indentation when manually
9745 ;; overriding Karl's heuristic nesting guesser.
9746
9747 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9748 ;; extensions such as `let' and Array comprehensions. Major kudos to
9749 ;; Karl for coming up with the initial approach, which packs a lot of
9750 ;; punch for so little code.
9751
9752 (defconst js2-possibly-braceless-keywords-re
9753 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9754 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9755 "try" "while" "with" "let")))
9756 "Regular expression matching keywords that are optionally
9757 followed by an opening brace.")
9758
9759 (defconst js2-indent-operator-re
9760 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
9761 (regexp-opt '("in" "instanceof") 'words))
9762 "Regular expression matching operators that affect indentation
9763 of continued expressions.")
9764
9765 (defconst js2-declaration-keyword-re
9766 (regexp-opt '("var" "let" "const") 'words)
9767 "Regular expression matching variable declaration keywords.")
9768
9769 (defun js2-re-search-forward-inner (regexp &optional bound count)
9770 "Auxiliary function for `js2-re-search-forward'."
9771 (let (parse saved-point)
9772 (while (> count 0)
9773 (re-search-forward regexp bound)
9774 (setq parse (if saved-point
9775 (parse-partial-sexp saved-point (point))
9776 (syntax-ppss (point))))
9777 (cond ((nth 3 parse)
9778 (re-search-forward
9779 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
9780 (save-excursion (end-of-line) (point)) t))
9781 ((nth 7 parse)
9782 (forward-line))
9783 ((or (nth 4 parse)
9784 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9785 (re-search-forward "\\*/"))
9786 (t
9787 (setq count (1- count))))
9788 (setq saved-point (point))))
9789 (point))
9790
9791 (defun js2-re-search-forward (regexp &optional bound noerror count)
9792 "Search forward but ignore strings and comments.
9793 Invokes `re-search-forward' 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-forward-inner regexp bound 1))
9799 ((< count 0)
9800 (js2-re-search-backward-inner regexp bound (- count)))
9801 ((> count 0)
9802 (js2-re-search-forward-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-re-search-backward-inner (regexp &optional bound count)
9809 "Auxiliary function for `js2-re-search-backward'."
9810 (let (parse)
9811 (while (> count 0)
9812 (re-search-backward regexp bound)
9813 (setq parse (syntax-ppss (point)))
9814 (cond ((nth 3 parse)
9815 (re-search-backward
9816 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9817 (line-beginning-position) t))
9818 ((nth 7 parse)
9819 (goto-char (nth 8 parse)))
9820 ((or (nth 4 parse)
9821 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9822 (re-search-backward "/\\*"))
9823 (t
9824 (setq count (1- count))))))
9825 (point))
9826
9827 (defun js2-re-search-backward (regexp &optional bound noerror count)
9828 "Search backward but ignore strings and comments.
9829 Invokes `re-search-backward' but treats the buffer as if strings
9830 and comments have been removed."
9831 (let ((saved-point (point)))
9832 (condition-case err
9833 (cond ((null count)
9834 (js2-re-search-backward-inner regexp bound 1))
9835 ((< count 0)
9836 (js2-re-search-forward-inner regexp bound (- count)))
9837 ((> count 0)
9838 (js2-re-search-backward-inner regexp bound count)))
9839 (search-failed
9840 (goto-char saved-point)
9841 (unless noerror
9842 (error (error-message-string err)))))))
9843
9844 (defun js2-looking-at-operator-p ()
9845 "Return non-nil if text after point is a non-comma operator."
9846 (and (looking-at js2-indent-operator-re)
9847 (or (not (looking-at ":"))
9848 (save-excursion
9849 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9850 (looking-at "?"))))))
9851
9852 (defun js2-continued-expression-p ()
9853 "Return non-nil if the current line continues an expression."
9854 (save-excursion
9855 (back-to-indentation)
9856 (or (js2-looking-at-operator-p)
9857 (when (catch 'found
9858 (while (and (re-search-backward "\n" nil t)
9859 (let ((state (syntax-ppss)))
9860 (when (nth 4 state)
9861 (goto-char (nth 8 state))) ;; skip comments
9862 (skip-chars-backward " \t")
9863 (if (bolp)
9864 t
9865 (throw 'found t))))))
9866 (backward-char)
9867 (when (js2-looking-at-operator-p)
9868 (backward-char)
9869 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
9870
9871 (defun js2-end-of-do-while-loop-p ()
9872 "Return non-nil if word after point is `while' of a do-while
9873 statement, else returns nil. A braceless do-while statement
9874 spanning several lines requires that the start of the loop is
9875 indented to the same column as the current line."
9876 (interactive)
9877 (save-excursion
9878 (when (looking-at "\\s-*\\<while\\>")
9879 (if (save-excursion
9880 (skip-chars-backward "[ \t\n]*}")
9881 (looking-at "[ \t\n]*}"))
9882 (save-excursion
9883 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9884 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9885 (or (looking-at "\\<do\\>")
9886 (let ((saved-indent (current-indentation)))
9887 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9888 (/= (current-indentation) saved-indent)))
9889 (and (looking-at "[ \t]*\\<do\\>")
9890 (not (js2-re-search-forward
9891 "\\<while\\>" (point-at-eol) t))
9892 (= (current-indentation) saved-indent))))))))
9893
9894 (defun js2-multiline-decl-indentation ()
9895 "Return the declaration indentation column if the current line belongs
9896 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9897 (let (forward-sexp-function ; use Lisp version
9898 at-opening-bracket)
9899 (save-excursion
9900 (back-to-indentation)
9901 (when (not (looking-at js2-declaration-keyword-re))
9902 (when (looking-at js2-indent-operator-re)
9903 (goto-char (match-end 0))) ; continued expressions are ok
9904 (while (and (not at-opening-bracket)
9905 (not (bobp))
9906 (let ((pos (point)))
9907 (save-excursion
9908 (js2-backward-sws)
9909 (or (eq (char-before) ?,)
9910 (and (not (eq (char-before) ?\;))
9911 (prog2 (skip-syntax-backward ".")
9912 (looking-at js2-indent-operator-re)
9913 (js2-backward-sws))
9914 (not (eq (char-before) ?\;)))
9915 (js2-same-line pos)))))
9916 (condition-case _
9917 (backward-sexp)
9918 (scan-error (setq at-opening-bracket t))))
9919 (when (looking-at js2-declaration-keyword-re)
9920 (goto-char (match-end 0))
9921 (1+ (current-column)))))))
9922
9923 (defun js2-ctrl-statement-indentation ()
9924 "Return the proper indentation of current line if it is a control statement.
9925 Returns an indentation if this line starts the body of a control
9926 statement without braces, else returns nil."
9927 (let (forward-sexp-function)
9928 (save-excursion
9929 (back-to-indentation)
9930 (when (and (not (js2-same-line (point-min)))
9931 (not (looking-at "{"))
9932 (js2-re-search-backward "[[:graph:]]" nil t)
9933 (not (looking-at "[{([]"))
9934 (progn
9935 (forward-char)
9936 (when (= (char-before) ?\))
9937 ;; scan-sexps sometimes throws an error
9938 (ignore-errors (backward-sexp))
9939 (skip-chars-backward " \t" (point-at-bol)))
9940 (let ((pt (point)))
9941 (back-to-indentation)
9942 (when (looking-at "}[ \t]*")
9943 (goto-char (match-end 0)))
9944 (and (looking-at js2-possibly-braceless-keywords-re)
9945 (= (match-end 0) pt)
9946 (not (js2-end-of-do-while-loop-p))))))
9947 (+ (current-indentation) js2-basic-offset)))))
9948
9949 (defun js2-indent-in-array-comp (parse-status)
9950 "Return non-nil if we think we're in an array comprehension.
9951 In particular, return the buffer position of the first `for' kwd."
9952 (let ((bracket (nth 1 parse-status))
9953 (end (point)))
9954 (when bracket
9955 (save-excursion
9956 (goto-char bracket)
9957 (when (looking-at "\\[")
9958 (forward-char 1)
9959 (js2-forward-sws)
9960 (if (looking-at "[[{]")
9961 (let (forward-sexp-function) ; use Lisp version
9962 (forward-sexp) ; skip destructuring form
9963 (js2-forward-sws)
9964 (if (and (/= (char-after) ?,) ; regular array
9965 (looking-at "for"))
9966 (match-beginning 0)))
9967 ;; to skip arbitrary expressions we need the parser,
9968 ;; so we'll just guess at it.
9969 (if (and (> end (point)) ; not empty literal
9970 (re-search-forward "[^,]]* \\(for\\) " end t)
9971 ;; not inside comment or string literal
9972 (let ((state (parse-partial-sexp bracket (point))))
9973 (not (or (nth 3 state) (nth 4 state)))))
9974 (match-beginning 1))))))))
9975
9976 (defun js2-array-comp-indentation (parse-status for-kwd)
9977 (if (js2-same-line for-kwd)
9978 ;; first continuation line
9979 (save-excursion
9980 (goto-char (nth 1 parse-status))
9981 (forward-char 1)
9982 (skip-chars-forward " \t")
9983 (current-column))
9984 (save-excursion
9985 (goto-char for-kwd)
9986 (current-column))))
9987
9988 (defun js2-proper-indentation (parse-status)
9989 "Return the proper indentation for the current line."
9990 (save-excursion
9991 (back-to-indentation)
9992 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9993 (at-closing-bracket (looking-at "[]})]"))
9994 (same-indent-p (or at-closing-bracket
9995 (looking-at "\\<case\\>[^:]")
9996 (and (looking-at "\\<default:")
9997 (save-excursion
9998 (js2-backward-sws)
9999 (not (memq (char-before) '(?, ?{)))))))
10000 (continued-expr-p (js2-continued-expression-p))
10001 (declaration-indent (and js2-pretty-multiline-declarations
10002 (js2-multiline-decl-indentation)))
10003 (bracket (nth 1 parse-status))
10004 beg indent)
10005 (cond
10006 ;; indent array comprehension continuation lines specially
10007 ((and bracket
10008 (>= js2-language-version 170)
10009 (not (js2-same-line bracket))
10010 (setq beg (js2-indent-in-array-comp parse-status))
10011 (>= (point) (save-excursion
10012 (goto-char beg)
10013 (point-at-bol)))) ; at or after first loop?
10014 (js2-array-comp-indentation parse-status beg))
10015
10016 (ctrl-stmt-indent)
10017
10018 ((and declaration-indent continued-expr-p)
10019 (+ declaration-indent js2-basic-offset))
10020
10021 (declaration-indent)
10022
10023 (bracket
10024 (goto-char bracket)
10025 (cond
10026 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10027 (when (save-excursion (skip-chars-backward " \t)")
10028 (looking-at ")"))
10029 (backward-list))
10030 (back-to-indentation)
10031 (and (eq js2-pretty-multiline-declarations 'all)
10032 (looking-at js2-declaration-keyword-re)
10033 (goto-char (1+ (match-end 0))))
10034 (setq indent
10035 (cond (same-indent-p
10036 (current-column))
10037 (continued-expr-p
10038 (+ (current-column) (* 2 js2-basic-offset)))
10039 (t
10040 (+ (current-column) js2-basic-offset))))
10041 (if (and js2-indent-switch-body
10042 (not at-closing-bracket)
10043 (looking-at "\\_<switch\\_>"))
10044 (+ indent js2-basic-offset)
10045 indent))
10046 (t
10047 (unless same-indent-p
10048 (forward-char)
10049 (skip-chars-forward " \t"))
10050 (current-column))))
10051
10052 (continued-expr-p js2-basic-offset)
10053
10054 (t 0)))))
10055
10056 (defun js2-lineup-comment (parse-status)
10057 "Indent a multi-line block comment continuation line."
10058 (let* ((beg (nth 8 parse-status))
10059 (first-line (js2-same-line beg))
10060 (offset (save-excursion
10061 (goto-char beg)
10062 (if (looking-at "/\\*")
10063 (+ 1 (current-column))
10064 0))))
10065 (unless first-line
10066 (indent-line-to offset))))
10067
10068 (defun js2-backward-sws ()
10069 "Move backward through whitespace and comments."
10070 (interactive)
10071 (while (forward-comment -1)))
10072
10073 (defun js2-forward-sws ()
10074 "Move forward through whitespace and comments."
10075 (interactive)
10076 (while (forward-comment 1)))
10077
10078 (defun js2-current-indent (&optional pos)
10079 "Return column of indentation on current line.
10080 If POS is non-nil, go to that point and return indentation for that line."
10081 (save-excursion
10082 (if pos
10083 (goto-char pos))
10084 (back-to-indentation)
10085 (current-column)))
10086
10087 (defun js2-arglist-close ()
10088 "Return non-nil if we're on a line beginning with a close-paren/brace."
10089 (save-excursion
10090 (goto-char (point-at-bol))
10091 (js2-forward-sws)
10092 (looking-at "[])}]")))
10093
10094 (defun js2-indent-looks-like-label-p ()
10095 (goto-char (point-at-bol))
10096 (js2-forward-sws)
10097 (looking-at (concat js2-mode-identifier-re ":")))
10098
10099 (defun js2-indent-in-objlit-p (parse-status)
10100 "Return non-nil if this looks like an object-literal entry."
10101 (let ((start (nth 1 parse-status)))
10102 (and
10103 start
10104 (save-excursion
10105 (and (zerop (forward-line -1))
10106 (not (< (point) start)) ; crossed a {} boundary
10107 (js2-indent-looks-like-label-p)))
10108 (save-excursion
10109 (js2-indent-looks-like-label-p)))))
10110
10111 ;; If prev line looks like foobar({ then we're passing an object
10112 ;; literal to a function call, and people pretty much always want to
10113 ;; de-dent back to the previous line, so move the 'basic-offset'
10114 ;; position to the front.
10115 (defun js2-indent-objlit-arg-p (parse-status)
10116 (save-excursion
10117 (back-to-indentation)
10118 (js2-backward-sws)
10119 (and (eq (1- (point)) (nth 1 parse-status))
10120 (eq (char-before) ?{)
10121 (progn
10122 (forward-char -1)
10123 (skip-chars-backward " \t")
10124 (eq (char-before) ?\()))))
10125
10126 (defun js2-indent-case-block-p ()
10127 (save-excursion
10128 (back-to-indentation)
10129 (js2-backward-sws)
10130 (goto-char (point-at-bol))
10131 (skip-chars-forward " \t")
10132 (looking-at "case\\s-.+:")))
10133
10134 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10135 "Cycle among alternate computed indentation positions.
10136 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10137 of the buffer to the current point. NORMAL-COL is the indentation
10138 column computed by the heuristic guesser based on current paren,
10139 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10140 in reverse."
10141 (let ((cur-indent (js2-current-indent))
10142 (old-buffer-undo-list buffer-undo-list)
10143 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10144 (current-line (save-excursion
10145 (forward-line 0) ; move to bol
10146 (1+ (count-lines (point-min) (point)))))
10147 positions pos main-pos anchor arglist-cont same-indent
10148 basic-offset computed-pos)
10149 ;; temporarily don't record undo info, if user requested this
10150 (when js2-mode-indent-inhibit-undo
10151 (setq buffer-undo-list t))
10152 (unwind-protect
10153 (progn
10154 ;; First likely point: indent from beginning of previous code line
10155 (push (setq basic-offset
10156 (+ (save-excursion
10157 (back-to-indentation)
10158 (js2-backward-sws)
10159 (back-to-indentation)
10160 (current-column))
10161 js2-basic-offset))
10162 positions)
10163
10164 ;; (First + epsilon) likely point: indent 2x from beginning of
10165 ;; previous code line. Google does it this way.
10166 (push (setq basic-offset
10167 (+ (save-excursion
10168 (back-to-indentation)
10169 (js2-backward-sws)
10170 (back-to-indentation)
10171 (current-column))
10172 (* 2 js2-basic-offset)))
10173 positions)
10174
10175 ;; Second likely point: indent from assign-expr RHS. This
10176 ;; is just a crude guess based on finding " = " on the previous
10177 ;; line containing actual code.
10178 (setq pos (save-excursion
10179 (forward-line -1)
10180 (goto-char (point-at-bol))
10181 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10182 (point-at-eol) t)
10183 (goto-char (match-end 1))
10184 (skip-chars-forward " \t\r\n")
10185 (current-column))))
10186 (when pos
10187 (incf pos js2-basic-offset)
10188 (push pos positions))
10189
10190 ;; Third likely point: same indent as previous line of code.
10191 ;; Make it the first likely point if we're not on an
10192 ;; arglist-close line and previous line ends in a comma, or
10193 ;; both this line and prev line look like object-literal
10194 ;; elements.
10195 (setq pos (save-excursion
10196 (goto-char (point-at-bol))
10197 (js2-backward-sws)
10198 (back-to-indentation)
10199 (prog1
10200 (current-column)
10201 ;; while we're here, look for trailing comma
10202 (if (save-excursion
10203 (goto-char (point-at-eol))
10204 (js2-backward-sws)
10205 (eq (char-before) ?,))
10206 (setq arglist-cont (1- (point)))))))
10207 (when pos
10208 (if (and (or arglist-cont
10209 (js2-indent-in-objlit-p parse-status))
10210 (not (js2-arglist-close)))
10211 (setq same-indent pos))
10212 (push pos positions))
10213
10214 ;; Fourth likely point: first preceding code with less indentation.
10215 ;; than the immediately preceding code line.
10216 (setq pos (save-excursion
10217 (back-to-indentation)
10218 (js2-backward-sws)
10219 (back-to-indentation)
10220 (setq anchor (current-column))
10221 (while (and (zerop (forward-line -1))
10222 (>= (progn
10223 (back-to-indentation)
10224 (current-column))
10225 anchor)))
10226 (setq pos (current-column))))
10227 (push pos positions)
10228
10229 ;; nesting-heuristic position, main by default
10230 (push (setq main-pos normal-col) positions)
10231
10232 ;; delete duplicates and sort positions list
10233 (setq positions (sort (delete-dups positions) '<))
10234
10235 ;; comma-list continuation lines: prev line indent takes precedence
10236 (if same-indent
10237 (setq main-pos same-indent))
10238
10239 ;; common special cases where we want to indent in from previous line
10240 (if (or (js2-indent-case-block-p)
10241 (js2-indent-objlit-arg-p parse-status))
10242 (setq main-pos basic-offset))
10243
10244 ;; if bouncing backwards, reverse positions list
10245 (if backwards
10246 (setq positions (reverse positions)))
10247
10248 ;; record whether we're already sitting on one of the alternatives
10249 (setq pos (member cur-indent positions))
10250
10251 (cond
10252 ;; case 0: we're one one of the alternatives and this is the
10253 ;; first time they've pressed TAB on this line (best-guess).
10254 ((and js2-mode-indent-ignore-first-tab
10255 pos
10256 ;; first time pressing TAB on this line?
10257 (not (eq js2-mode-last-indented-line current-line)))
10258 ;; do nothing
10259 (setq computed-pos nil))
10260 ;; case 1: only one computed position => use it
10261 ((null (cdr positions))
10262 (setq computed-pos 0))
10263 ;; case 2: not on any of the computed spots => use main spot
10264 ((not pos)
10265 (setq computed-pos (js2-position main-pos positions)))
10266 ;; case 3: on last position: cycle to first position
10267 ((null (cdr pos))
10268 (setq computed-pos 0))
10269 ;; case 4: on intermediate position: cycle to next position
10270 (t
10271 (setq computed-pos (js2-position (second pos) positions))))
10272
10273 ;; see if any hooks want to indent; otherwise we do it
10274 (loop with result = nil
10275 for hook in js2-indent-hook
10276 while (null result)
10277 do
10278 (setq result (funcall hook positions computed-pos))
10279 finally do
10280 (unless (or result (null computed-pos))
10281 (indent-line-to (nth computed-pos positions)))))
10282
10283 ;; finally
10284 (if js2-mode-indent-inhibit-undo
10285 (setq buffer-undo-list old-buffer-undo-list))
10286 ;; see commentary for `js2-mode-last-indented-line'
10287 (setq js2-mode-last-indented-line current-line))))
10288
10289 (defun js2-indent-bounce-backwards ()
10290 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10291 cycles between the computed indentation positions in reverse order."
10292 (interactive)
10293 (js2-indent-line t))
10294
10295 (defun js2-1-line-comment-continuation-p ()
10296 "Return t if we're in a 1-line comment continuation.
10297 If so, we don't ever want to use bounce-indent."
10298 (save-excursion
10299 (and (progn
10300 (forward-line 0)
10301 (looking-at "\\s-*//"))
10302 (progn
10303 (forward-line -1)
10304 (forward-line 0)
10305 (when (looking-at "\\s-*$")
10306 (js2-backward-sws)
10307 (forward-line 0))
10308 (looking-at "\\s-*//")))))
10309
10310 (defun js2-indent-line (&optional bounce-backwards)
10311 "Indent the current line as JavaScript source text."
10312 (interactive)
10313 (let (parse-status offset indent-col
10314 ;; Don't whine about errors/warnings when we're indenting.
10315 ;; This has to be set before calling parse-partial-sexp below.
10316 (inhibit-point-motion-hooks t))
10317 (setq parse-status (save-excursion
10318 (syntax-ppss (point-at-bol)))
10319 offset (- (point) (save-excursion
10320 (back-to-indentation)
10321 (point))))
10322 (js2-with-underscore-as-word-syntax
10323 (if (nth 4 parse-status)
10324 (js2-lineup-comment parse-status)
10325 (setq indent-col (js2-proper-indentation parse-status))
10326 ;; See comments below about `js2-mode-last-indented-line'.
10327 (cond
10328 ;; bounce-indenting is disabled during electric-key indent.
10329 ;; It doesn't work well on first line of buffer.
10330 ((and js2-bounce-indent-p
10331 (not (js2-same-line (point-min)))
10332 (not (js2-1-line-comment-continuation-p)))
10333 (js2-bounce-indent indent-col parse-status bounce-backwards))
10334 ;; just indent to the guesser's likely spot
10335 (t (indent-line-to indent-col))))
10336 (when (plusp offset)
10337 (forward-char offset)))))
10338
10339 (defun js2-indent-region (start end)
10340 "Indent the region, but don't use bounce indenting."
10341 (let ((js2-bounce-indent-p nil)
10342 (indent-region-function nil)
10343 (after-change-functions (remq 'js2-mode-edit
10344 after-change-functions)))
10345 (indent-region start end nil) ; nil for byte-compiler
10346 (js2-mode-edit start end (- end start))))
10347
10348 (defvar js2-minor-mode-map
10349 (let ((map (make-sparse-keymap)))
10350 (define-key map (kbd "C-c C-`") #'js2-next-error)
10351 (define-key map [mouse-1] #'js2-mode-show-node)
10352 map)
10353 "Keymap used when `js2-minor-mode' is active.")
10354
10355 ;;;###autoload
10356 (define-minor-mode js2-minor-mode
10357 "Minor mode for running js2 as a background linter.
10358 This allows you to use a different major mode for JavaScript editing,
10359 such as `js-mode', while retaining the asynchronous error/warning
10360 highlighting features of `js2-mode'."
10361 :group 'js2-mode
10362 :lighter " js-lint"
10363 (if js2-minor-mode
10364 (js2-minor-mode-enter)
10365 (js2-minor-mode-exit)))
10366
10367 (defun js2-minor-mode-enter ()
10368 "Initialization for `js2-minor-mode'."
10369 (set (make-local-variable 'max-lisp-eval-depth)
10370 (max max-lisp-eval-depth 3000))
10371 (setq next-error-function #'js2-next-error)
10372 (js2-set-default-externs)
10373 ;; Experiment: make reparse-delay longer for longer files.
10374 (if (plusp js2-dynamic-idle-timer-adjust)
10375 (setq js2-idle-timer-delay
10376 (* js2-idle-timer-delay
10377 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10378 (setq js2-mode-buffer-dirty-p t
10379 js2-mode-parsing nil)
10380 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10381 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10382 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10383 (when js2-include-jslint-globals
10384 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10385 (run-hooks 'js2-init-hook)
10386 (js2-reparse))
10387
10388 (defun js2-minor-mode-exit ()
10389 "Turn off `js2-minor-mode'."
10390 (setq next-error-function nil)
10391 (remove-hook 'after-change-functions #'js2-mode-edit t)
10392 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10393 (when js2-mode-node-overlay
10394 (delete-overlay js2-mode-node-overlay)
10395 (setq js2-mode-node-overlay nil))
10396 (js2-remove-overlays)
10397 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
10398 (setq js2-mode-ast nil))
10399
10400 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10401 (make-variable-buffer-local 'js2-source-buffer)
10402
10403 (defun* js2-display-error-list ()
10404 "Display a navigable buffer listing parse errors/warnings."
10405 (interactive)
10406 (unless (js2-have-errors-p)
10407 (message "No errors")
10408 (return-from js2-display-error-list))
10409 (labels ((annotate-list
10410 (lst type)
10411 "Add diagnostic TYPE and line number to errs list"
10412 (mapcar (lambda (err)
10413 (list err type (line-number-at-pos (nth 1 err))))
10414 lst)))
10415 (let* ((srcbuf (current-buffer))
10416 (errbuf (get-buffer-create "*js-lint*"))
10417 (errors (annotate-list
10418 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10419 'js2-error)) ; must be a valid face name
10420 (warnings (annotate-list
10421 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10422 'js2-warning)) ; must be a valid face name
10423 (all-errs (sort (append errors warnings)
10424 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10425 (with-current-buffer errbuf
10426 (let ((inhibit-read-only t))
10427 (erase-buffer)
10428 (dolist (err all-errs)
10429 (destructuring-bind ((msg-key beg _end &rest) type line) err
10430 (insert-text-button
10431 (format "line %d: %s" line (js2-get-msg msg-key))
10432 'face type
10433 'follow-link "\C-m"
10434 'action 'js2-error-buffer-jump
10435 'js2-msg (js2-get-msg msg-key)
10436 'js2-pos beg)
10437 (insert "\n"))))
10438 (js2-error-buffer-mode)
10439 (setq js2-source-buffer srcbuf)
10440 (pop-to-buffer errbuf)
10441 (goto-char (point-min))
10442 (unless (eobp)
10443 (js2-error-buffer-view))))))
10444
10445 (defvar js2-error-buffer-mode-map
10446 (let ((map (make-sparse-keymap)))
10447 (define-key map "n" #'js2-error-buffer-next)
10448 (define-key map "p" #'js2-error-buffer-prev)
10449 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10450 (define-key map "o" #'js2-error-buffer-view)
10451 (define-key map "q" #'js2-error-buffer-quit)
10452 map)
10453 "Keymap used for js2 diagnostics buffers.")
10454
10455 (defun js2-error-buffer-mode ()
10456 "Major mode for js2 diagnostics buffers.
10457 Selecting an error will jump it to the corresponding source-buffer error.
10458 \\{js2-error-buffer-mode-map}"
10459 (interactive)
10460 (setq major-mode 'js2-error-buffer-mode
10461 mode-name "JS Lint Diagnostics")
10462 (use-local-map js2-error-buffer-mode-map)
10463 (setq truncate-lines t)
10464 (set-buffer-modified-p nil)
10465 (setq buffer-read-only t)
10466 (run-hooks 'js2-error-buffer-mode-hook))
10467
10468 (defun js2-error-buffer-next ()
10469 "Move to next error and view it."
10470 (interactive)
10471 (when (zerop (forward-line 1))
10472 (js2-error-buffer-view)))
10473
10474 (defun js2-error-buffer-prev ()
10475 "Move to previous error and view it."
10476 (interactive)
10477 (when (zerop (forward-line -1))
10478 (js2-error-buffer-view)))
10479
10480 (defun js2-error-buffer-quit ()
10481 "Kill the current buffer."
10482 (interactive)
10483 (kill-buffer))
10484
10485 (defun js2-error-buffer-jump (&rest ignored)
10486 "Jump cursor to current error in source buffer."
10487 (interactive)
10488 (when (js2-error-buffer-view)
10489 (pop-to-buffer js2-source-buffer)))
10490
10491 (defun js2-error-buffer-view ()
10492 "Scroll source buffer to show error at current line."
10493 (interactive)
10494 (cond
10495 ((not (eq major-mode 'js2-error-buffer-mode))
10496 (message "Not in a js2 errors buffer"))
10497 ((not (buffer-live-p js2-source-buffer))
10498 (message "Source buffer has been killed"))
10499 ((not (wholenump (get-text-property (point) 'js2-pos)))
10500 (message "There does not seem to be an error here"))
10501 (t
10502 (let ((pos (get-text-property (point) 'js2-pos))
10503 (msg (get-text-property (point) 'js2-msg)))
10504 (save-selected-window
10505 (pop-to-buffer js2-source-buffer)
10506 (goto-char pos)
10507 (message msg))))))
10508
10509 ;;;###autoload
10510 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10511 ;; FIXME: Should derive from js-mode.
10512 "Major mode for editing JavaScript code."
10513 ;; Used by comment-region; don't change it.
10514 (set (make-local-variable 'comment-start) "//")
10515 (set (make-local-variable 'comment-end) "")
10516 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
10517 (set (make-local-variable 'max-lisp-eval-depth)
10518 (max max-lisp-eval-depth 3000))
10519 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10520 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10521 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10522 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10523 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10524 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10525 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10526 ;; for characters inside regexp literals.
10527 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10528 ;; this is necessary to make `show-paren-function' work properly
10529 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10530 ;; needed for M-x rgrep, among other things
10531 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10532
10533 (set (make-local-variable 'electric-indent-chars)
10534 (append "{}()[]:;,*." electric-indent-chars))
10535 (set (make-local-variable 'electric-layout-rules)
10536 '((?\; . after) (?\{ . after) (?\} . before)))
10537
10538 ;; some variables needed by cc-engine for paragraph-fill, etc.
10539 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10540 c-comment-start-regexp "/[*/]\\|\\s|"
10541 c-line-comment-starter "//"
10542 c-paragraph-start js2-paragraph-start
10543 c-paragraph-separate "$"
10544 c-syntactic-ws-start js2-syntactic-ws-start
10545 c-syntactic-ws-end js2-syntactic-ws-end
10546 c-syntactic-eol js2-syntactic-eol)
10547
10548 (let ((c-buffer-is-cc-mode t))
10549 ;; Copied from `js-mode'. Also see Bug#6071.
10550 (make-local-variable 'paragraph-start)
10551 (make-local-variable 'paragraph-separate)
10552 (make-local-variable 'paragraph-ignore-fill-prefix)
10553 (make-local-variable 'adaptive-fill-mode)
10554 (make-local-variable 'adaptive-fill-regexp)
10555 (c-setup-paragraph-variables))
10556
10557 (setq font-lock-defaults '(nil t))
10558
10559 ;; Experiment: make reparse-delay longer for longer files.
10560 (when (plusp js2-dynamic-idle-timer-adjust)
10561 (setq js2-idle-timer-delay
10562 (* js2-idle-timer-delay
10563 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10564
10565 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10566 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10567 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10568 (setq next-error-function #'js2-next-error)
10569 (imenu-add-to-menubar (concat "IM-" mode-name))
10570 (add-to-invisibility-spec '(js2-outline . t))
10571 (set (make-local-variable 'line-move-ignore-invisible) t)
10572 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10573
10574 (setq js2-mode-functions-hidden nil
10575 js2-mode-comments-hidden nil
10576 js2-mode-buffer-dirty-p t
10577 js2-mode-parsing nil)
10578
10579 (js2-set-default-externs)
10580
10581 (when js2-include-jslint-globals
10582 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10583
10584 (run-hooks 'js2-init-hook)
10585
10586 (js2-reparse))
10587
10588 (defun js2-mode-exit ()
10589 "Exit `js2-mode' and clean up."
10590 (interactive)
10591 (when js2-mode-node-overlay
10592 (delete-overlay js2-mode-node-overlay)
10593 (setq js2-mode-node-overlay nil))
10594 (js2-remove-overlays)
10595 (setq js2-mode-ast nil)
10596 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10597 (remove-from-invisibility-spec '(js2-outline . t))
10598 (js2-mode-show-all)
10599 (with-silent-modifications
10600 (js2-clear-face (point-min) (point-max))))
10601
10602 (defun js2-mode-reset-timer ()
10603 "Cancel any existing parse timer and schedule a new one."
10604 (if js2-mode-parse-timer
10605 (cancel-timer js2-mode-parse-timer))
10606 (setq js2-mode-parsing nil)
10607 (let ((timer (timer-create)))
10608 (setq js2-mode-parse-timer timer)
10609 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10610 (timer-set-idle-time timer js2-idle-timer-delay)
10611 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10612 (timer-activate-when-idle timer nil)))
10613
10614 (defun js2-mode-idle-reparse (buffer)
10615 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10616 it to be reparsed when the buffer is selected."
10617 (cond ((eq buffer (current-buffer))
10618 (js2-reparse))
10619 ((buffer-live-p buffer)
10620 ;; reparse when the buffer is selected again
10621 (with-current-buffer buffer
10622 (add-hook 'window-configuration-change-hook
10623 #'js2-mode-idle-reparse-inner
10624 nil t)))))
10625
10626 (defun js2-mode-idle-reparse-inner ()
10627 (remove-hook 'window-configuration-change-hook
10628 #'js2-mode-idle-reparse-inner
10629 t)
10630 (js2-reparse))
10631
10632 (defun js2-mode-edit (_beg _end _len)
10633 "Schedule a new parse after buffer is edited.
10634 Buffer edit spans from BEG to END and is of length LEN."
10635 (setq js2-mode-buffer-dirty-p t)
10636 (js2-mode-hide-overlay)
10637 (js2-mode-reset-timer))
10638
10639 (defun js2-minor-mode-edit (_beg _end _len)
10640 "Callback for buffer edits in `js2-mode'.
10641 Schedules a new parse after buffer is edited.
10642 Buffer edit spans from BEG to END and is of length LEN."
10643 (setq js2-mode-buffer-dirty-p t)
10644 (js2-mode-hide-overlay)
10645 (js2-mode-reset-timer))
10646
10647 (defun js2-reparse (&optional force)
10648 "Re-parse current buffer after user finishes some data entry.
10649 If we get any user input while parsing, including cursor motion,
10650 we discard the parse and reschedule it. If FORCE is nil, then the
10651 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10652 (let (time
10653 interrupted-p
10654 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10655 (unless js2-mode-parsing
10656 (setq js2-mode-parsing t)
10657 (unwind-protect
10658 (when (or js2-mode-buffer-dirty-p force)
10659 (js2-remove-overlays)
10660 (with-silent-modifications
10661 (setq js2-mode-buffer-dirty-p nil
10662 js2-mode-fontifications nil
10663 js2-mode-deferred-properties nil)
10664 (if js2-mode-verbose-parse-p
10665 (message "parsing..."))
10666 (setq time
10667 (js2-time
10668 (setq interrupted-p
10669 (catch 'interrupted
10670 (js2-parse)
10671 ;; if parsing is interrupted, comments and regex
10672 ;; literals stay ignored by `parse-partial-sexp'
10673 (remove-text-properties (point-min) (point-max)
10674 '(syntax-table))
10675 (js2-mode-apply-deferred-properties)
10676 (js2-mode-remove-suppressed-warnings)
10677 (js2-mode-show-warnings)
10678 (js2-mode-show-errors)
10679 (if (>= js2-highlight-level 1)
10680 (js2-highlight-jsdoc js2-mode-ast))
10681 nil))))
10682 (if interrupted-p
10683 (progn
10684 ;; unfinished parse => try again
10685 (setq js2-mode-buffer-dirty-p t)
10686 (js2-mode-reset-timer))
10687 (if js2-mode-verbose-parse-p
10688 (message "Parse time: %s" time)))))
10689 (setq js2-mode-parsing nil)
10690 (unless interrupted-p
10691 (setq js2-mode-parse-timer nil))))))
10692
10693 (defun js2-mode-show-node (event)
10694 "Debugging aid: highlight selected AST node on mouse click."
10695 (interactive "e")
10696 (mouse-set-point event)
10697 (setq deactivate-mark t)
10698 (when js2-mode-show-overlay
10699 (let ((node (js2-node-at-point))
10700 beg end)
10701 (if (null node)
10702 (message "No node found at location %s" (point))
10703 (setq beg (js2-node-abs-pos node)
10704 end (+ beg (js2-node-len node)))
10705 (if js2-mode-node-overlay
10706 (move-overlay js2-mode-node-overlay beg end)
10707 (setq js2-mode-node-overlay (make-overlay beg end))
10708 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10709 (with-silent-modifications
10710 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10711 (message "%s, parent: %s"
10712 (js2-node-short-name node)
10713 (if (js2-node-parent node)
10714 (js2-node-short-name (js2-node-parent node))
10715 "nil"))))))
10716
10717 (defun js2-mode-hide-overlay (&optional _p1 p2)
10718 "Remove the debugging overlay when the point moves.
10719 P1 and P2 are the old and new values of point, respectively."
10720 (when js2-mode-node-overlay
10721 (let ((beg (overlay-start js2-mode-node-overlay))
10722 (end (overlay-end js2-mode-node-overlay)))
10723 ;; Sometimes we're called spuriously.
10724 (unless (and p2
10725 (>= p2 beg)
10726 (<= p2 end))
10727 (with-silent-modifications
10728 (remove-text-properties beg end '(point-left nil)))
10729 (delete-overlay js2-mode-node-overlay)
10730 (setq js2-mode-node-overlay nil)))))
10731
10732 (defun js2-mode-reset ()
10733 "Debugging helper: reset everything."
10734 (interactive)
10735 (js2-mode-exit)
10736 (js2-mode))
10737
10738 (defun js2-mode-show-warn-or-err (e face)
10739 "Highlight a warning or error E with FACE.
10740 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10741 The last element is optional. When present, use instead of FACE."
10742 (let* ((key (first e))
10743 (beg (second e))
10744 (end (+ beg (third e)))
10745 ;; Don't inadvertently go out of bounds.
10746 (beg (max (point-min) (min beg (point-max))))
10747 (end (max (point-min) (min end (point-max))))
10748 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10749 (ovl (make-overlay beg end)))
10750 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10751 (overlay-put ovl 'js2-error t)
10752 (put-text-property beg end 'help-echo (js2-get-msg key))
10753 (put-text-property beg end 'point-entered #'js2-echo-error)))
10754
10755 (defun js2-remove-overlays ()
10756 "Remove overlays from buffer that have a `js2-error' property."
10757 (let ((beg (point-min))
10758 (end (point-max)))
10759 (save-excursion
10760 (dolist (o (overlays-in beg end))
10761 (when (overlay-get o 'js2-error)
10762 (delete-overlay o))))))
10763
10764 (defun js2-error-at-point (&optional pos)
10765 "Return non-nil if there's an error overlay at POS.
10766 Defaults to point."
10767 (loop with pos = (or pos (point))
10768 for o in (overlays-at pos)
10769 thereis (overlay-get o 'js2-error)))
10770
10771 (defun js2-mode-apply-deferred-properties ()
10772 "Apply fontifications and other text properties recorded during parsing."
10773 (when (plusp js2-highlight-level)
10774 ;; We defer clearing faces as long as possible to eliminate flashing.
10775 (js2-clear-face (point-min) (point-max))
10776 ;; Have to reverse the recorded fontifications list so that errors
10777 ;; and warnings overwrite the normal fontifications.
10778 (dolist (f (nreverse js2-mode-fontifications))
10779 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10780 (setq js2-mode-fontifications nil))
10781 (dolist (p js2-mode-deferred-properties)
10782 (apply #'put-text-property p))
10783 (setq js2-mode-deferred-properties nil))
10784
10785 (defun js2-mode-show-errors ()
10786 "Highlight syntax errors."
10787 (when js2-mode-show-parse-errors
10788 (dolist (e (js2-ast-root-errors js2-mode-ast))
10789 (js2-mode-show-warn-or-err e 'js2-error))))
10790
10791 (defun js2-mode-remove-suppressed-warnings ()
10792 "Take suppressed warnings out of the AST warnings list.
10793 This ensures that the counts and `next-error' are correct."
10794 (setf (js2-ast-root-warnings js2-mode-ast)
10795 (js2-delete-if
10796 (lambda (e)
10797 (let ((key (caar e)))
10798 (or
10799 (and (not js2-strict-trailing-comma-warning)
10800 (string-match "trailing\\.comma" key))
10801 (and (not js2-strict-cond-assign-warning)
10802 (string= key "msg.equal.as.assign"))
10803 (and js2-missing-semi-one-line-override
10804 (string= key "msg.missing.semi")
10805 (let* ((beg (second e))
10806 (node (js2-node-at-point beg))
10807 (fn (js2-mode-find-parent-fn node))
10808 (body (and fn (js2-function-node-body fn)))
10809 (lc (and body (js2-node-abs-pos body)))
10810 (rc (and lc (+ lc (js2-node-len body)))))
10811 (and fn
10812 (or (null body)
10813 (save-excursion
10814 (goto-char beg)
10815 (and (js2-same-line lc)
10816 (js2-same-line rc))))))))))
10817 (js2-ast-root-warnings js2-mode-ast))))
10818
10819 (defun js2-mode-show-warnings ()
10820 "Highlight strict-mode warnings."
10821 (when js2-mode-show-strict-warnings
10822 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10823 (js2-mode-show-warn-or-err e 'js2-warning))))
10824
10825 (defun js2-echo-error (_old-point new-point)
10826 "Called by point-motion hooks."
10827 (let ((msg (get-text-property new-point 'help-echo)))
10828 (when (and (stringp msg)
10829 (not (active-minibuffer-window))
10830 (not (current-message)))
10831 (message msg))))
10832
10833 (defalias 'js2-echo-help #'js2-echo-error)
10834
10835 (defun js2-line-break (&optional _soft)
10836 "Break line at point and indent, continuing comment if within one.
10837 If inside a string, and `js2-concat-multiline-strings' is not
10838 nil, turn it into concatenation."
10839 (interactive)
10840 (let ((parse-status (syntax-ppss)))
10841 (cond
10842 ;; Check if we're inside a string.
10843 ((nth 3 parse-status)
10844 (if js2-concat-multiline-strings
10845 (js2-mode-split-string parse-status)
10846 (insert "\n")))
10847 ;; Check if inside a block comment.
10848 ((nth 4 parse-status)
10849 (js2-mode-extend-comment (nth 8 parse-status)))
10850 (t
10851 (newline-and-indent)))))
10852
10853 (defun js2-mode-split-string (parse-status)
10854 "Turn a newline in mid-string into a string concatenation.
10855 PARSE-STATUS is as documented in `parse-partial-sexp'."
10856 (let* ((quote-char (nth 3 parse-status))
10857 (at-eol (eq js2-concat-multiline-strings 'eol)))
10858 (insert quote-char)
10859 (insert (if at-eol " +\n" "\n"))
10860 (unless at-eol
10861 (insert "+ "))
10862 (js2-indent-line)
10863 (insert quote-char)
10864 (when (eolp)
10865 (insert quote-char)
10866 (backward-char 1))))
10867
10868 (defun js2-mode-extend-comment (start-pos)
10869 "Indent the line and, when inside a comment block, add comment prefix."
10870 (let (star single col first-line needs-close)
10871 (save-excursion
10872 (back-to-indentation)
10873 (when (< (point) start-pos)
10874 (goto-char start-pos))
10875 (cond
10876 ((looking-at "\\*[^/]")
10877 (setq star t
10878 col (current-column)))
10879 ((looking-at "/\\*")
10880 (setq star t
10881 first-line t
10882 col (1+ (current-column))))
10883 ((looking-at "//")
10884 (setq single t
10885 col (current-column)))))
10886 ;; Heuristic for whether we need to close the comment:
10887 ;; if we've got a parse error here, assume it's an unterminated
10888 ;; comment.
10889 (setq needs-close
10890 (or
10891 (eq (get-text-property (1- (point)) 'point-entered)
10892 'js2-echo-error)
10893 ;; The heuristic above doesn't work well when we're
10894 ;; creating a comment and there's another one downstream,
10895 ;; as our parser thinks this one ends at the end of the
10896 ;; next one. (You can have a /* inside a js block comment.)
10897 ;; So just close it if the next non-ws char isn't a *.
10898 (and first-line
10899 (eolp)
10900 (save-excursion
10901 (skip-chars-forward " \t\r\n")
10902 (not (eq (char-after) ?*))))))
10903 (delete-horizontal-space)
10904 (insert "\n")
10905 (cond
10906 (star
10907 (indent-to col)
10908 (insert "* ")
10909 (if (and first-line needs-close)
10910 (save-excursion
10911 (insert "\n")
10912 (indent-to col)
10913 (insert "*/"))))
10914 ((and single
10915 (save-excursion
10916 (and (zerop (forward-line 1))
10917 (looking-at "\\s-*//"))))
10918 (indent-to col)
10919 (insert "// ")))
10920 ;; Don't need to extend the comment after all.
10921 (js2-indent-line)))
10922
10923 (defun js2-beginning-of-line ()
10924 "Toggle point between bol and first non-whitespace char in line.
10925 Also moves past comment delimiters when inside comments."
10926 (interactive)
10927 (let (node)
10928 (cond
10929 ((bolp)
10930 (back-to-indentation))
10931 ((looking-at "//")
10932 (skip-chars-forward "/ \t"))
10933 ((and (eq (char-after) ?*)
10934 (setq node (js2-comment-at-point))
10935 (memq (js2-comment-node-format node) '(jsdoc block))
10936 (save-excursion
10937 (skip-chars-backward " \t")
10938 (bolp)))
10939 (skip-chars-forward "\* \t"))
10940 (t
10941 (goto-char (point-at-bol))))))
10942
10943 (defun js2-end-of-line ()
10944 "Toggle point between eol and last non-whitespace char in line."
10945 (interactive)
10946 (if (eolp)
10947 (skip-chars-backward " \t")
10948 (goto-char (point-at-eol))))
10949
10950 (defun js2-mode-wait-for-parse (callback)
10951 "Invoke CALLBACK when parsing is finished.
10952 If parsing is already finished, calls CALLBACK immediately."
10953 (if (not js2-mode-buffer-dirty-p)
10954 (funcall callback)
10955 (push callback js2-mode-pending-parse-callbacks)
10956 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10957
10958 (defun js2-mode-parse-finished ()
10959 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10960 ;; We can't let errors propagate up, since it prevents the
10961 ;; `js2-parse' method from completing normally and returning
10962 ;; the ast, which makes things mysteriously not work right.
10963 (unwind-protect
10964 (dolist (cb js2-mode-pending-parse-callbacks)
10965 (condition-case err
10966 (funcall cb)
10967 (error (message "%s" err))))
10968 (setq js2-mode-pending-parse-callbacks nil)))
10969
10970 (defun js2-mode-flag-region (from to flag)
10971 "Hide or show text from FROM to TO, according to FLAG.
10972 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10973 Returns the created overlay if FLAG is non-nil."
10974 (remove-overlays from to 'invisible 'js2-outline)
10975 (when flag
10976 (let ((o (make-overlay from to)))
10977 (overlay-put o 'invisible 'js2-outline)
10978 (overlay-put o 'isearch-open-invisible
10979 'js2-isearch-open-invisible)
10980 o)))
10981
10982 ;; Function to be set as an outline-isearch-open-invisible' property
10983 ;; to the overlay that makes the outline invisible (see
10984 ;; `js2-mode-flag-region').
10985 (defun js2-isearch-open-invisible (_overlay)
10986 ;; We rely on the fact that isearch places point on the matched text.
10987 (js2-mode-show-element))
10988
10989 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10990 "Return cons cell of bounds of folding overlay at POS.
10991 Returns nil if not found."
10992 (let ((overlays (overlays-at (or pos (point))))
10993 o)
10994 (while (and overlays
10995 (not o))
10996 (if (overlay-get (car overlays) 'invisible)
10997 (setq o (car overlays))
10998 (setq overlays (cdr overlays))))
10999 (if o
11000 (cons (overlay-start o) (overlay-end o)))))
11001
11002 (defun js2-mode-function-at-point (&optional pos)
11003 "Return the innermost function node enclosing current point.
11004 Returns nil if point is not in a function."
11005 (let ((node (js2-node-at-point pos)))
11006 (while (and node (not (js2-function-node-p node)))
11007 (setq node (js2-node-parent node)))
11008 (if (js2-function-node-p node)
11009 node)))
11010
11011 (defun js2-mode-toggle-element ()
11012 "Hide or show the foldable element at the point."
11013 (interactive)
11014 (let (comment fn pos)
11015 (save-excursion
11016 (cond
11017 ;; /* ... */ comment?
11018 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11019 (if (js2-mode-invisible-overlay-bounds
11020 (setq pos (+ 3 (js2-node-abs-pos comment))))
11021 (progn
11022 (goto-char pos)
11023 (js2-mode-show-element))
11024 (js2-mode-hide-element)))
11025 ;; //-comment?
11026 ((save-excursion
11027 (back-to-indentation)
11028 (looking-at js2-mode-//-comment-re))
11029 (js2-mode-toggle-//-comment))
11030 ;; function?
11031 ((setq fn (js2-mode-function-at-point))
11032 (setq pos (and (js2-function-node-body fn)
11033 (js2-node-abs-pos (js2-function-node-body fn))))
11034 (goto-char (1+ pos))
11035 (if (js2-mode-invisible-overlay-bounds)
11036 (js2-mode-show-element)
11037 (js2-mode-hide-element)))
11038 (t
11039 (message "Nothing at point to hide or show"))))))
11040
11041 (defun js2-mode-hide-element ()
11042 "Fold/hide contents of a block, showing ellipses.
11043 Show the hidden text with \\[js2-mode-show-element]."
11044 (interactive)
11045 (if js2-mode-buffer-dirty-p
11046 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11047 (let (node body beg end)
11048 (cond
11049 ((js2-mode-invisible-overlay-bounds)
11050 (message "already hidden"))
11051 (t
11052 (setq node (js2-node-at-point))
11053 (cond
11054 ((js2-block-comment-p node)
11055 (js2-mode-hide-comment node))
11056 (t
11057 (while (and node (not (js2-function-node-p node)))
11058 (setq node (js2-node-parent node)))
11059 (if (and node
11060 (setq body (js2-function-node-body node)))
11061 (progn
11062 (setq beg (js2-node-abs-pos body)
11063 end (+ beg (js2-node-len body)))
11064 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11065 (message "No collapsable element found at point"))))))))
11066
11067 (defun js2-mode-show-element ()
11068 "Show the hidden element at current point."
11069 (interactive)
11070 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11071 (if bounds
11072 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11073 (message "Nothing to un-hide"))))
11074
11075 (defun js2-mode-show-all ()
11076 "Show all of the text in the buffer."
11077 (interactive)
11078 (js2-mode-flag-region (point-min) (point-max) nil))
11079
11080 (defun js2-mode-toggle-hide-functions ()
11081 (interactive)
11082 (if js2-mode-functions-hidden
11083 (js2-mode-show-functions)
11084 (js2-mode-hide-functions)))
11085
11086 (defun js2-mode-hide-functions ()
11087 "Hides all non-nested function bodies in the buffer.
11088 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11089 to open an individual entry."
11090 (interactive)
11091 (if js2-mode-buffer-dirty-p
11092 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11093 (if (null js2-mode-ast)
11094 (message "Oops - parsing failed")
11095 (setq js2-mode-functions-hidden t)
11096 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11097
11098 (defun js2-mode-function-hider (n endp)
11099 (when (not endp)
11100 (let ((tt (js2-node-type n))
11101 body beg end)
11102 (cond
11103 ((and (= tt js2-FUNCTION)
11104 (setq body (js2-function-node-body n)))
11105 (setq beg (js2-node-abs-pos body)
11106 end (+ beg (js2-node-len body)))
11107 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11108 nil) ; don't process children of function
11109 (t
11110 t))))) ; keep processing other AST nodes
11111
11112 (defun js2-mode-show-functions ()
11113 "Un-hide any folded function bodies in the buffer."
11114 (interactive)
11115 (setq js2-mode-functions-hidden nil)
11116 (save-excursion
11117 (goto-char (point-min))
11118 (while (/= (goto-char (next-overlay-change (point)))
11119 (point-max))
11120 (dolist (o (overlays-at (point)))
11121 (when (and (overlay-get o 'invisible)
11122 (not (overlay-get o 'comment)))
11123 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11124
11125 (defun js2-mode-hide-comment (n)
11126 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11127 3 ; /**
11128 2)) ; /*
11129 (beg (+ (js2-node-abs-pos n) head))
11130 (end (- (+ beg (js2-node-len n)) head 2))
11131 (o (js2-mode-flag-region beg end 'hide)))
11132 (overlay-put o 'comment t)))
11133
11134 (defun js2-mode-toggle-hide-comments ()
11135 "Folds all block comments in the buffer.
11136 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11137 to open an individual entry."
11138 (interactive)
11139 (if js2-mode-comments-hidden
11140 (js2-mode-show-comments)
11141 (js2-mode-hide-comments)))
11142
11143 (defun js2-mode-hide-comments ()
11144 (interactive)
11145 (if js2-mode-buffer-dirty-p
11146 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11147 (if (null js2-mode-ast)
11148 (message "Oops - parsing failed")
11149 (setq js2-mode-comments-hidden t)
11150 (dolist (n (js2-ast-root-comments js2-mode-ast))
11151 (when (js2-block-comment-p n)
11152 (js2-mode-hide-comment n)))
11153 (js2-mode-hide-//-comments)))
11154
11155 (defun js2-mode-extend-//-comment (direction)
11156 "Find start or end of a block of similar //-comment lines.
11157 DIRECTION is -1 to look back, 1 to look forward.
11158 INDENT is the indentation level to match.
11159 Returns the end-of-line position of the furthest adjacent
11160 //-comment line with the same indentation as the current line.
11161 If there is no such matching line, returns current end of line."
11162 (let ((pos (point-at-eol))
11163 (indent (current-indentation)))
11164 (save-excursion
11165 (while (and (zerop (forward-line direction))
11166 (looking-at js2-mode-//-comment-re)
11167 (eq indent (length (match-string 1))))
11168 (setq pos (point-at-eol))
11169 pos))))
11170
11171 (defun js2-mode-hide-//-comments ()
11172 "Fold adjacent 1-line comments, showing only snippet of first one."
11173 (let (beg end)
11174 (save-excursion
11175 (goto-char (point-min))
11176 (while (re-search-forward js2-mode-//-comment-re nil t)
11177 (setq beg (point)
11178 end (js2-mode-extend-//-comment 1))
11179 (unless (eq beg end)
11180 (overlay-put (js2-mode-flag-region beg end 'hide)
11181 'comment t))
11182 (goto-char end)
11183 (forward-char 1)))))
11184
11185 (defun js2-mode-toggle-//-comment ()
11186 "Fold or un-fold any multi-line //-comment at point.
11187 Caller should have determined that this line starts with a //-comment."
11188 (let* ((beg (point-at-eol))
11189 (end beg))
11190 (save-excursion
11191 (goto-char end)
11192 (if (js2-mode-invisible-overlay-bounds)
11193 (js2-mode-show-element)
11194 ;; else hide the comment
11195 (setq beg (js2-mode-extend-//-comment -1)
11196 end (js2-mode-extend-//-comment 1))
11197 (unless (eq beg end)
11198 (overlay-put (js2-mode-flag-region beg end 'hide)
11199 'comment t))))))
11200
11201 (defun js2-mode-show-comments ()
11202 "Un-hide any hidden comments, leaving other hidden elements alone."
11203 (interactive)
11204 (setq js2-mode-comments-hidden nil)
11205 (save-excursion
11206 (goto-char (point-min))
11207 (while (/= (goto-char (next-overlay-change (point)))
11208 (point-max))
11209 (dolist (o (overlays-at (point)))
11210 (when (overlay-get o 'comment)
11211 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11212
11213 (defun js2-mode-display-warnings-and-errors ()
11214 "Turn on display of warnings and errors."
11215 (interactive)
11216 (setq js2-mode-show-parse-errors t
11217 js2-mode-show-strict-warnings t)
11218 (js2-reparse 'force))
11219
11220 (defun js2-mode-hide-warnings-and-errors ()
11221 "Turn off display of warnings and errors."
11222 (interactive)
11223 (setq js2-mode-show-parse-errors nil
11224 js2-mode-show-strict-warnings nil)
11225 (js2-reparse 'force))
11226
11227 (defun js2-mode-toggle-warnings-and-errors ()
11228 "Toggle the display of warnings and errors.
11229 Some users don't like having warnings/errors reported while they type."
11230 (interactive)
11231 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11232 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11233 (if (called-interactively-p 'any)
11234 (message "warnings and errors %s"
11235 (if js2-mode-show-parse-errors
11236 "enabled"
11237 "disabled")))
11238 (js2-reparse 'force))
11239
11240 (defun js2-mode-customize ()
11241 (interactive)
11242 (customize-group 'js2-mode))
11243
11244 (defun js2-mode-forward-sexp (&optional arg)
11245 "Move forward across one statement or balanced expression.
11246 With ARG, do it that many times. Negative arg -N means
11247 move backward across N balanced expressions."
11248 (interactive "p")
11249 (setq arg (or arg 1))
11250 (save-restriction
11251 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11252 (js2-reparse)
11253 (let (forward-sexp-function
11254 node (start (point)) pos lp rp child)
11255 (cond
11256 ;; backward-sexp
11257 ;; could probably make this better for some cases:
11258 ;; - if in statement block (e.g. function body), go to parent
11259 ;; - infix exprs like (foo in bar) - maybe go to beginning
11260 ;; of infix expr if in the right-side expression?
11261 ((and arg (minusp arg))
11262 (dotimes (_ (- arg))
11263 (js2-backward-sws)
11264 (forward-char -1) ; Enter the node we backed up to.
11265 (when (setq node (js2-node-at-point (point) t))
11266 (setq pos (js2-node-abs-pos node))
11267 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11268 (setq lp (car parens)
11269 rp (cdr parens)))
11270 (when (and lp (> start lp))
11271 (if (and rp (<= start rp))
11272 ;; Between parens, check if there's a child node we can jump.
11273 (when (setq child (js2-node-closest-child node (point) lp t))
11274 (setq pos (js2-node-abs-pos child)))
11275 ;; Before both parens.
11276 (setq pos lp)))
11277 (let ((state (parse-partial-sexp start pos)))
11278 (goto-char (if (not (zerop (car state)))
11279 ;; Stumble at the unbalanced paren if < 0, or
11280 ;; jump a bit further if > 0.
11281 (scan-sexps start -1)
11282 pos))))
11283 (unless pos (goto-char (point-min)))))
11284 (t
11285 ;; forward-sexp
11286 (dotimes (_ arg)
11287 (js2-forward-sws)
11288 (when (setq node (js2-node-at-point (point) t))
11289 (setq pos (js2-node-abs-pos node))
11290 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11291 (setq lp (car parens)
11292 rp (cdr parens)))
11293 (or
11294 (when (and rp (<= start rp))
11295 (if (> start lp)
11296 (when (setq child (js2-node-closest-child node (point) rp))
11297 (setq pos (js2-node-abs-end child)))
11298 (setq pos (1+ rp))))
11299 ;; No parens or child nodes, looks for the end of the curren node.
11300 (incf pos (js2-node-len
11301 (if (js2-expr-stmt-node-p (js2-node-parent node))
11302 ;; Stop after the semicolon.
11303 (js2-node-parent node)
11304 node))))
11305 (let ((state (save-excursion (parse-partial-sexp start pos))))
11306 (goto-char (if (not (zerop (car state)))
11307 (scan-sexps start 1)
11308 pos))))
11309 (unless pos (goto-char (point-max)))))))))
11310
11311 (defun js2-mode-forward-sexp-parens (node abs-pos)
11312 "Return a cons cell with positions of main parens in NODE."
11313 (cond
11314 ((or (js2-array-node-p node)
11315 (js2-object-node-p node)
11316 (js2-comp-node-p node)
11317 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11318 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11319 ((js2-paren-expr-node-p node)
11320 (let ((lp (js2-node-lp node))
11321 (rp (js2-node-rp node)))
11322 (cons (when lp (+ abs-pos lp))
11323 (when rp (+ abs-pos rp)))))))
11324
11325 (defun js2-node-closest-child (parent point limit &optional before)
11326 (let* ((parent-pos (js2-node-abs-pos parent))
11327 (rpoint (- point parent-pos))
11328 (rlimit (- limit parent-pos))
11329 (min (min rpoint rlimit))
11330 (max (max rpoint rlimit))
11331 found)
11332 (catch 'done
11333 (js2-visit-ast
11334 parent
11335 (lambda (node _end-p)
11336 (if (eq node parent)
11337 t
11338 (let ((pos (js2-node-pos node)) ;; Both relative values.
11339 (end (+ (js2-node-pos node) (js2-node-len node))))
11340 (when (and (>= pos min) (<= end max)
11341 (if before (< pos rpoint) (> end rpoint)))
11342 (setq found node))
11343 (when (> end rpoint)
11344 (throw 'done nil)))
11345 nil))))
11346 found))
11347
11348 (defun js2-errors ()
11349 "Return a list of errors found."
11350 (and js2-mode-ast
11351 (js2-ast-root-errors js2-mode-ast)))
11352
11353 (defun js2-warnings ()
11354 "Return a list of warnings found."
11355 (and js2-mode-ast
11356 (js2-ast-root-warnings js2-mode-ast)))
11357
11358 (defun js2-have-errors-p ()
11359 "Return non-nil if any parse errors or warnings were found."
11360 (or (js2-errors) (js2-warnings)))
11361
11362 (defun js2-errors-and-warnings ()
11363 "Return a copy of the concatenated errors and warnings lists.
11364 They are appended: first the errors, then the warnings.
11365 Entries are of the form (MSG BEG END)."
11366 (when js2-mode-ast
11367 (append (js2-ast-root-errors js2-mode-ast)
11368 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11369
11370 (defun js2-next-error (&optional arg reset)
11371 "Move to next parse error.
11372 Typically invoked via \\[next-error].
11373 ARG is the number of errors, forward or backward, to move.
11374 RESET means start over from the beginning."
11375 (interactive "p")
11376 (if (not (or (js2-errors) (js2-warnings)))
11377 (message "No errors")
11378 (when reset
11379 (goto-char (point-min)))
11380 (let* ((errs (js2-errors-and-warnings))
11381 (continue t)
11382 (start (point))
11383 (count (or arg 1))
11384 (backward (minusp count))
11385 (sorter (if backward '> '<))
11386 (stopper (if backward '< '>))
11387 (count (abs count))
11388 all-errs err)
11389 ;; Sort by start position.
11390 (setq errs (sort errs (lambda (e1 e2)
11391 (funcall sorter (second e1) (second e2))))
11392 all-errs errs)
11393 ;; Find nth error with pos > start.
11394 (while (and errs continue)
11395 (when (funcall stopper (cadar errs) start)
11396 (setq err (car errs))
11397 (if (zerop (decf count))
11398 (setq continue nil)))
11399 (setq errs (cdr errs)))
11400 ;; Clear for `js2-echo-error'.
11401 (message nil)
11402 (if err
11403 (goto-char (second err))
11404 ;; Wrap around to first error.
11405 (goto-char (second (car all-errs)))
11406 ;; If we were already on it, echo msg again.
11407 (if (= (point) start)
11408 (js2-echo-error (point) (point)))))))
11409
11410 (defun js2-down-mouse-3 ()
11411 "Make right-click move the point to the click location.
11412 This makes right-click context menu operations a bit more intuitive.
11413 The point will not move if the region is active, however, to avoid
11414 destroying the region selection."
11415 (interactive)
11416 (when (and js2-move-point-on-right-click
11417 (not mark-active))
11418 (let ((e last-input-event))
11419 (ignore-errors
11420 (goto-char (cadadr e))))))
11421
11422 (defun js2-mode-create-imenu-index ()
11423 "Return an alist for `imenu--index-alist'."
11424 ;; This is built up in `js2-parse-record-imenu' during parsing.
11425 (when js2-mode-ast
11426 ;; if we have an ast but no recorder, they're requesting a rescan
11427 (unless js2-imenu-recorder
11428 (js2-reparse 'force))
11429 (prog1
11430 (js2-build-imenu-index)
11431 (setq js2-imenu-recorder nil
11432 js2-imenu-function-map nil))))
11433
11434 (defun js2-mode-find-tag ()
11435 "Replacement for `find-tag-default'.
11436 `find-tag-default' returns a ridiculous answer inside comments."
11437 (let (beg end)
11438 (js2-with-underscore-as-word-syntax
11439 (save-excursion
11440 (if (and (not (looking-at "[[:alnum:]_$]"))
11441 (looking-back "[[:alnum:]_$]"))
11442 (setq beg (progn (forward-word -1) (point))
11443 end (progn (forward-word 1) (point)))
11444 (setq beg (progn (forward-word 1) (point))
11445 end (progn (forward-word -1) (point))))
11446 (replace-regexp-in-string
11447 "[\"']" ""
11448 (buffer-substring-no-properties beg end))))))
11449
11450 (defun js2-mode-forward-sibling ()
11451 "Move to the end of the sibling following point in parent.
11452 Returns non-nil if successful, or nil if there was no following sibling."
11453 (let* ((node (js2-node-at-point))
11454 (parent (js2-mode-find-enclosing-fn node))
11455 sib)
11456 (when (setq sib (js2-node-find-child-after (point) parent))
11457 (goto-char (+ (js2-node-abs-pos sib)
11458 (js2-node-len sib))))))
11459
11460 (defun js2-mode-backward-sibling ()
11461 "Move to the beginning of the sibling node preceding point in parent.
11462 Parent is defined as the enclosing script or function."
11463 (let* ((node (js2-node-at-point))
11464 (parent (js2-mode-find-enclosing-fn node))
11465 sib)
11466 (when (setq sib (js2-node-find-child-before (point) parent))
11467 (goto-char (js2-node-abs-pos sib)))))
11468
11469 (defun js2-beginning-of-defun (&optional arg)
11470 "Go to line on which current function starts, and return t on success.
11471 If we're not in a function or already at the beginning of one, go
11472 to beginning of previous script-level element.
11473 With ARG N, do that N times. If N is negative, move forward."
11474 (setq arg (or arg 1))
11475 (if (plusp arg)
11476 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11477 (when (cond
11478 ((js2-function-node-p parent)
11479 (goto-char (js2-node-abs-pos parent)))
11480 (t
11481 (js2-mode-backward-sibling)))
11482 (if (> arg 1)
11483 (js2-beginning-of-defun (1- arg))
11484 t)))
11485 (when (js2-end-of-defun)
11486 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
11487
11488 (defun js2-end-of-defun ()
11489 "Go to the char after the last position of the current function
11490 or script-level element."
11491 (let* ((node (js2-node-at-point))
11492 (parent (or (and (js2-function-node-p node) node)
11493 (js2-node-parent-script-or-fn node)))
11494 script)
11495 (unless (js2-function-node-p parent)
11496 ;; Use current script-level node, or, if none, the next one.
11497 (setq script (or parent node)
11498 parent (js2-node-find-child-before (point) script))
11499 (when (or (null parent)
11500 (>= (point) (+ (js2-node-abs-pos parent)
11501 (js2-node-len parent))))
11502 (setq parent (js2-node-find-child-after (point) script))))
11503 (when parent
11504 (goto-char (+ (js2-node-abs-pos parent)
11505 (js2-node-len parent))))))
11506
11507 (defun js2-mark-defun (&optional allow-extend)
11508 "Put mark at end of this function, point at beginning.
11509 The function marked is the one that contains point.
11510
11511 Interactively, if this command is repeated,
11512 or (in Transient Mark mode) if the mark is active,
11513 it marks the next defun after the ones already marked."
11514 (interactive "p")
11515 (let (extended)
11516 (when (and allow-extend
11517 (or (and (eq last-command this-command) (mark t))
11518 (and transient-mark-mode mark-active)))
11519 (let ((sib (save-excursion
11520 (goto-char (mark))
11521 (if (js2-mode-forward-sibling)
11522 (point)))))
11523 (if sib
11524 (progn
11525 (set-mark sib)
11526 (setq extended t))
11527 ;; no more siblings - try extending to enclosing node
11528 (goto-char (mark t)))))
11529 (when (not extended)
11530 (let ((node (js2-node-at-point (point) t)) ; skip comments
11531 ast fn stmt parent beg end)
11532 (when (js2-ast-root-p node)
11533 (setq ast node
11534 node (or (js2-node-find-child-after (point) node)
11535 (js2-node-find-child-before (point) node))))
11536 ;; only mark whole buffer if we can't find any children
11537 (if (null node)
11538 (setq node ast))
11539 (if (js2-function-node-p node)
11540 (setq parent node)
11541 (setq fn (js2-mode-find-enclosing-fn node)
11542 stmt (if (or (null fn)
11543 (js2-ast-root-p fn))
11544 (js2-mode-find-first-stmt node))
11545 parent (or stmt fn)))
11546 (setq beg (js2-node-abs-pos parent)
11547 end (+ beg (js2-node-len parent)))
11548 (push-mark beg)
11549 (goto-char end)
11550 (exchange-point-and-mark)))))
11551
11552 (defun js2-narrow-to-defun ()
11553 "Narrow to the function enclosing point."
11554 (interactive)
11555 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11556 (fn (if (js2-script-node-p node)
11557 node
11558 (js2-mode-find-enclosing-fn node)))
11559 (beg (js2-node-abs-pos fn)))
11560 (unless (js2-ast-root-p fn)
11561 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11562
11563 (provide 'js2-mode)
11564
11565 ;;; js2-mode.el ends here