]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Support short-hand object literals {foo, bar} everywhere.
[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 ;;; Variables
207
208 (defun js2-mark-safe-local (name pred)
209 "Make the variable NAME buffer-local and mark it as safe file-local
210 variable with predicate PRED."
211 (make-variable-buffer-local name)
212 (put name 'safe-local-variable pred))
213
214 (defcustom js2-highlight-level 2
215 "Amount of syntax highlighting to perform.
216 0 or a negative value means none.
217 1 adds basic syntax highlighting.
218 2 adds highlighting of some Ecma built-in properties.
219 3 adds highlighting of many Ecma built-in functions."
220 :group 'js2-mode
221 :type '(choice (const :tag "None" 0)
222 (const :tag "Basic" 1)
223 (const :tag "Include Properties" 2)
224 (const :tag "Include Functions" 3)))
225
226 (defvar js2-mode-dev-mode-p nil
227 "Non-nil if running in development mode. Normally nil.")
228
229 (defgroup js2-mode nil
230 "An improved JavaScript mode."
231 :group 'languages)
232
233 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
234 (numberp c-basic-offset))
235 c-basic-offset
236 4)
237 "Number of spaces to indent nested statements.
238 Similar to `c-basic-offset'."
239 :group 'js2-mode
240 :type 'integer)
241 (js2-mark-safe-local 'js2-basic-offset 'integerp)
242
243 (defcustom js2-bounce-indent-p nil
244 "Non-nil to have indent-line function choose among alternatives.
245 If nil, the indent-line function will indent to a predetermined column
246 based on heuristic guessing. If non-nil, then if the current line is
247 already indented to that predetermined column, indenting will choose
248 another likely column and indent to that spot. Repeated invocation of
249 the indent-line function will cycle among the computed alternatives.
250 See the function `js2-bounce-indent' for details. When it is non-nil,
251 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
252 :type 'boolean
253 :group 'js2-mode)
254
255 (defcustom js2-pretty-multiline-declarations t
256 "Non-nil to line up multiline declarations vertically:
257
258 var a = 10,
259 b = 20,
260 c = 30;
261
262 If the value is not `all', and the first assigned value in
263 declaration is a function/array/object literal spanning several
264 lines, it won't be indented additionally:
265
266 var o = { var bar = 2,
267 foo: 3 vs. o = {
268 }, foo: 3
269 bar = 2; };"
270 :group 'js2-mode
271 :type 'symbol)
272 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
273
274 (defcustom js2-indent-switch-body nil
275 "When nil, case labels are indented on the same level as the
276 containing switch statement. Otherwise, all lines inside
277 switch statement body are indented one additional level."
278 :type 'boolean
279 :group 'js2-mode)
280 (js2-mark-safe-local 'js2-indent-case-same-as-switch 'booleanp)
281
282 (defcustom js2-idle-timer-delay 0.2
283 "Delay in secs before re-parsing after user makes changes.
284 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
285 :type 'number
286 :group 'js2-mode)
287 (make-variable-buffer-local 'js2-idle-timer-delay)
288
289 (defcustom js2-dynamic-idle-timer-adjust 0
290 "Positive to adjust `js2-idle-timer-delay' based on file size.
291 The idea is that for short files, parsing is faster so we can be
292 more responsive to user edits without interfering with editing.
293 The buffer length in characters (typically bytes) is divided by
294 this value and used to multiply `js2-idle-timer-delay' for the
295 buffer. For example, a 21k file and 10k adjust yields 21k/10k
296 == 2, so js2-idle-timer-delay is multiplied by 2.
297 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
298 `js2-idle-timer-delay' is not dependent on the file size."
299 :type 'number
300 :group 'js2-mode)
301
302 (defcustom js2-concat-multiline-strings t
303 "When non-nil, `js2-line-break' in mid-string will make it a
304 string concatenation. When `eol', the '+' will be inserted at the
305 end of the line, otherwise, at the beginning of the next line."
306 :type '(choice (const t) (const eol) (const nil))
307 :group 'js2-mode)
308
309 (defcustom js2-mode-show-parse-errors t
310 "True to highlight parse errors."
311 :type 'boolean
312 :group 'js2-mode)
313
314 (defcustom js2-mode-show-strict-warnings t
315 "Non-nil to emit Ecma strict-mode warnings.
316 Some of the warnings can be individually disabled by other flags,
317 even if this flag is non-nil."
318 :type 'boolean
319 :group 'js2-mode)
320
321 (defcustom js2-strict-trailing-comma-warning t
322 "Non-nil to warn about trailing commas in array literals.
323 Ecma-262-5.1 allows them, but older versions of IE raise an error."
324 :type 'boolean
325 :group 'js2-mode)
326
327 (defcustom js2-strict-missing-semi-warning t
328 "Non-nil to warn about semicolon auto-insertion after statement.
329 Technically this is legal per Ecma-262, but some style guides disallow
330 depending on it."
331 :type 'boolean
332 :group 'js2-mode)
333
334 (defcustom js2-missing-semi-one-line-override nil
335 "Non-nil to permit missing semicolons in one-line functions.
336 In one-liner functions such as `function identity(x) {return x}'
337 people often omit the semicolon for a cleaner look. If you are
338 such a person, you can suppress the missing-semicolon warning
339 by setting this variable to t."
340 :type 'boolean
341 :group 'js2-mode)
342
343 (defcustom js2-strict-inconsistent-return-warning t
344 "Non-nil to warn about mixing returns with value-returns.
345 It's perfectly legal to have a `return' and a `return foo' in the
346 same function, but it's often an indicator of a bug, and it also
347 interferes with type inference (in systems that support it.)"
348 :type 'boolean
349 :group 'js2-mode)
350
351 (defcustom js2-strict-cond-assign-warning t
352 "Non-nil to warn about expressions like if (a = b).
353 This often should have been '==' instead of '='. If the warning
354 is enabled, you can suppress it on a per-expression basis by
355 parenthesizing the expression, e.g. if ((a = b)) ..."
356 :type 'boolean
357 :group 'js2-mode)
358
359 (defcustom js2-strict-var-redeclaration-warning t
360 "Non-nil to warn about redeclaring variables in a script or function."
361 :type 'boolean
362 :group 'js2-mode)
363
364 (defcustom js2-strict-var-hides-function-arg-warning t
365 "Non-nil to warn about a var decl hiding a function argument."
366 :type 'boolean
367 :group 'js2-mode)
368
369 (defcustom js2-skip-preprocessor-directives nil
370 "Non-nil to treat lines beginning with # as comments.
371 Useful for viewing Mozilla JavaScript source code."
372 :type 'boolean
373 :group 'js2-mode)
374
375 (defcustom js2-language-version 200
376 "Configures what JavaScript language version to recognize.
377 Currently versions 150, 160, 170, 180 and 200 are supported,
378 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
379 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
380 yield, and Array comprehensions, and 1.8 adds function closures."
381 :type 'integer
382 :group 'js2-mode)
383
384 (defcustom js2-allow-keywords-as-property-names t
385 "If non-nil, you can use JavaScript keywords as object property names.
386 Examples:
387
388 var foo = {int: 5, while: 6, continue: 7};
389 foo.return = 8;
390
391 Ecma-262 5.1 allows this syntax, but some engines still don't."
392 :type 'boolean
393 :group 'js2-mode)
394
395 (defcustom js2-instanceof-has-side-effects nil
396 "If non-nil, treats the instanceof operator as having side effects.
397 This is useful for xulrunner apps."
398 :type 'boolean
399 :group 'js2-mode)
400
401 (defcustom js2-move-point-on-right-click t
402 "Non-nil to move insertion point when you right-click.
403 This makes right-click context menu behavior a bit more intuitive,
404 since menu operations generally apply to the point. The exception
405 is if there is a region selection, in which case the point does -not-
406 move, so cut/copy/paste can work properly.
407
408 Note that IntelliJ moves the point, and Eclipse leaves it alone,
409 so this behavior is customizable."
410 :group 'js2-mode
411 :type 'boolean)
412
413 (defcustom js2-allow-rhino-new-expr-initializer t
414 "Non-nil to support a Rhino's experimental syntactic construct.
415
416 Rhino supports the ability to follow a `new' expression with an object
417 literal, which is used to set additional properties on the new object
418 after calling its constructor. Syntax:
419
420 new <expr> [ ( arglist ) ] [initializer]
421
422 Hence, this expression:
423
424 new Object {a: 1, b: 2}
425
426 results in an Object with properties a=1 and b=2. This syntax is
427 apparently not configurable in Rhino - it's currently always enabled,
428 as of Rhino version 1.7R2."
429 :type 'boolean
430 :group 'js2-mode)
431
432 (defcustom js2-allow-member-expr-as-function-name nil
433 "Non-nil to support experimental Rhino syntax for function names.
434
435 Rhino supports an experimental syntax configured via the Rhino Context
436 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
437
438 function <member-expr> ( [ arg-list ] ) { <body> }
439
440 Where member-expr is a non-parenthesized 'member expression', which
441 is anything at the grammar level of a new-expression or lower, meaning
442 any expression that does not involve infix or unary operators.
443
444 When <member-expr> is not a simple identifier, then it is syntactic
445 sugar for assigning the anonymous function to the <member-expr>. Hence,
446 this code:
447
448 function a.b().c[2] (x, y) { ... }
449
450 is rewritten as:
451
452 a.b().c[2] = function(x, y) {...}
453
454 which doesn't seem particularly useful, but Rhino permits it."
455 :type 'boolean
456 :group 'js2-mode)
457
458 ;; scanner variables
459
460 (defmacro js2-deflocal (name value &optional comment)
461 "Define a buffer-local variable NAME with VALUE and COMMENT."
462 `(progn
463 (defvar ,name ,value ,comment)
464 (make-variable-buffer-local ',name)))
465
466 (defvar js2-EOF_CHAR -1
467 "Represents end of stream. Distinct from js2-EOF token type.")
468
469 ;; I originally used symbols to represent tokens, but Rhino uses
470 ;; ints and then sets various flag bits in them, so ints it is.
471 ;; The upshot is that we need a `js2-' prefix in front of each name.
472 (defvar js2-ERROR -1)
473 (defvar js2-EOF 0)
474 (defvar js2-EOL 1)
475 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
476 (defvar js2-LEAVEWITH 3)
477 (defvar js2-RETURN 4)
478 (defvar js2-GOTO 5)
479 (defvar js2-IFEQ 6)
480 (defvar js2-IFNE 7)
481 (defvar js2-SETNAME 8)
482 (defvar js2-BITOR 9)
483 (defvar js2-BITXOR 10)
484 (defvar js2-BITAND 11)
485 (defvar js2-EQ 12)
486 (defvar js2-NE 13)
487 (defvar js2-LT 14)
488 (defvar js2-LE 15)
489 (defvar js2-GT 16)
490 (defvar js2-GE 17)
491 (defvar js2-LSH 18)
492 (defvar js2-RSH 19)
493 (defvar js2-URSH 20)
494 (defvar js2-ADD 21) ; infix plus
495 (defvar js2-SUB 22) ; infix minus
496 (defvar js2-MUL 23)
497 (defvar js2-DIV 24)
498 (defvar js2-MOD 25)
499 (defvar js2-NOT 26)
500 (defvar js2-BITNOT 27)
501 (defvar js2-POS 28) ; unary plus
502 (defvar js2-NEG 29) ; unary minus
503 (defvar js2-NEW 30)
504 (defvar js2-DELPROP 31)
505 (defvar js2-TYPEOF 32)
506 (defvar js2-GETPROP 33)
507 (defvar js2-GETPROPNOWARN 34)
508 (defvar js2-SETPROP 35)
509 (defvar js2-GETELEM 36)
510 (defvar js2-SETELEM 37)
511 (defvar js2-CALL 38)
512 (defvar js2-NAME 39) ; an identifier
513 (defvar js2-NUMBER 40)
514 (defvar js2-STRING 41)
515 (defvar js2-NULL 42)
516 (defvar js2-THIS 43)
517 (defvar js2-FALSE 44)
518 (defvar js2-TRUE 45)
519 (defvar js2-SHEQ 46) ; shallow equality (===)
520 (defvar js2-SHNE 47) ; shallow inequality (!==)
521 (defvar js2-REGEXP 48)
522 (defvar js2-BINDNAME 49)
523 (defvar js2-THROW 50)
524 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
525 (defvar js2-IN 52)
526 (defvar js2-INSTANCEOF 53)
527 (defvar js2-LOCAL_LOAD 54)
528 (defvar js2-GETVAR 55)
529 (defvar js2-SETVAR 56)
530 (defvar js2-CATCH_SCOPE 57)
531 (defvar js2-ENUM_INIT_KEYS 58)
532 (defvar js2-ENUM_INIT_VALUES 59)
533 (defvar js2-ENUM_INIT_ARRAY 60)
534 (defvar js2-ENUM_NEXT 61)
535 (defvar js2-ENUM_ID 62)
536 (defvar js2-THISFN 63)
537 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
538 (defvar js2-ARRAYLIT 65) ; array literal
539 (defvar js2-OBJECTLIT 66) ; object literal
540 (defvar js2-GET_REF 67) ; *reference
541 (defvar js2-SET_REF 68) ; *reference = something
542 (defvar js2-DEL_REF 69) ; delete reference
543 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
544 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
545 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
546
547 ;; XML support
548 (defvar js2-DEFAULTNAMESPACE 73)
549 (defvar js2-ESCXMLATTR 74)
550 (defvar js2-ESCXMLTEXT 75)
551 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
552 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
553 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
554 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
555
556 (defvar js2-first-bytecode js2-ENTERWITH)
557 (defvar js2-last-bytecode js2-REF_NS_NAME)
558
559 (defvar js2-TRY 80)
560 (defvar js2-SEMI 81) ; semicolon
561 (defvar js2-LB 82) ; left and right brackets
562 (defvar js2-RB 83)
563 (defvar js2-LC 84) ; left and right curly-braces
564 (defvar js2-RC 85)
565 (defvar js2-LP 86) ; left and right parens
566 (defvar js2-RP 87)
567 (defvar js2-COMMA 88) ; comma operator
568
569 (defvar js2-ASSIGN 89) ; simple assignment (=)
570 (defvar js2-ASSIGN_BITOR 90) ; |=
571 (defvar js2-ASSIGN_BITXOR 91) ; ^=
572 (defvar js2-ASSIGN_BITAND 92) ; &=
573 (defvar js2-ASSIGN_LSH 93) ; <<=
574 (defvar js2-ASSIGN_RSH 94) ; >>=
575 (defvar js2-ASSIGN_URSH 95) ; >>>=
576 (defvar js2-ASSIGN_ADD 96) ; +=
577 (defvar js2-ASSIGN_SUB 97) ; -=
578 (defvar js2-ASSIGN_MUL 98) ; *=
579 (defvar js2-ASSIGN_DIV 99) ; /=
580 (defvar js2-ASSIGN_MOD 100) ; %=
581
582 (defvar js2-first-assign js2-ASSIGN)
583 (defvar js2-last-assign js2-ASSIGN_MOD)
584
585 (defvar js2-HOOK 101) ; conditional (?:)
586 (defvar js2-COLON 102)
587 (defvar js2-OR 103) ; logical or (||)
588 (defvar js2-AND 104) ; logical and (&&)
589 (defvar js2-INC 105) ; increment/decrement (++ --)
590 (defvar js2-DEC 106)
591 (defvar js2-DOT 107) ; member operator (.)
592 (defvar js2-FUNCTION 108) ; function keyword
593 (defvar js2-EXPORT 109) ; export keyword
594 (defvar js2-IMPORT 110) ; import keyword
595 (defvar js2-IF 111) ; if keyword
596 (defvar js2-ELSE 112) ; else keyword
597 (defvar js2-SWITCH 113) ; switch keyword
598 (defvar js2-CASE 114) ; case keyword
599 (defvar js2-DEFAULT 115) ; default keyword
600 (defvar js2-WHILE 116) ; while keyword
601 (defvar js2-DO 117) ; do keyword
602 (defvar js2-FOR 118) ; for keyword
603 (defvar js2-BREAK 119) ; break keyword
604 (defvar js2-CONTINUE 120) ; continue keyword
605 (defvar js2-VAR 121) ; var keyword
606 (defvar js2-WITH 122) ; with keyword
607 (defvar js2-CATCH 123) ; catch keyword
608 (defvar js2-FINALLY 124) ; finally keyword
609 (defvar js2-VOID 125) ; void keyword
610 (defvar js2-RESERVED 126) ; reserved keywords
611
612 (defvar js2-EMPTY 127)
613
614 ;; Types used for the parse tree - never returned by scanner.
615
616 (defvar js2-BLOCK 128) ; statement block
617 (defvar js2-LABEL 129) ; label
618 (defvar js2-TARGET 130)
619 (defvar js2-LOOP 131)
620 (defvar js2-EXPR_VOID 132) ; expression statement in functions
621 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
622 (defvar js2-JSR 134)
623 (defvar js2-SCRIPT 135) ; top-level node for entire script
624 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
625 (defvar js2-USE_STACK 137)
626 (defvar js2-SETPROP_OP 138) ; x.y op= something
627 (defvar js2-SETELEM_OP 139) ; x[y] op= something
628 (defvar js2-LOCAL_BLOCK 140)
629 (defvar js2-SET_REF_OP 141) ; *reference op= something
630
631 ;; For XML support:
632 (defvar js2-DOTDOT 142) ; member operator (..)
633 (defvar js2-COLONCOLON 143) ; namespace::name
634 (defvar js2-XML 144) ; XML type
635 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
636 (defvar js2-XMLATTR 146) ; @
637 (defvar js2-XMLEND 147)
638
639 ;; Optimizer-only tokens
640 (defvar js2-TO_OBJECT 148)
641 (defvar js2-TO_DOUBLE 149)
642
643 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
644 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
645 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
646 (defvar js2-CONST 153)
647 (defvar js2-SETCONST 154)
648 (defvar js2-SETCONSTVAR 155)
649 (defvar js2-ARRAYCOMP 156)
650 (defvar js2-LETEXPR 157)
651 (defvar js2-WITHEXPR 158)
652 (defvar js2-DEBUGGER 159)
653
654 (defvar js2-COMMENT 160)
655 (defvar js2-ENUM 161) ; for "enum" reserved word
656 (defvar js2-TRIPLEDOT 162) ; for rest parameter
657 (defvar js2-ARROW 163) ; function arrow (=>)
658
659 (defconst js2-num-tokens (1+ js2-ARROW))
660
661 (defconst js2-debug-print-trees nil)
662
663 ;; Rhino accepts any string or stream as input. Emacs character
664 ;; processing works best in buffers, so we'll assume the input is a
665 ;; buffer. JavaScript strings can be copied into temp buffers before
666 ;; scanning them.
667
668 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
669 ;; They're the Emacs equivalent of instance variables, more or less.
670
671 (js2-deflocal js2-ts-dirty-line nil
672 "Token stream buffer-local variable.
673 Indicates stuff other than whitespace since start of line.")
674
675 (js2-deflocal js2-ts-hit-eof nil
676 "Token stream buffer-local variable.")
677
678 ;; FIXME: Unused.
679 (js2-deflocal js2-ts-line-start 0
680 "Token stream buffer-local variable.")
681
682 (js2-deflocal js2-ts-lineno 1
683 "Token stream buffer-local variable.")
684
685 ;; FIXME: Unused.
686 (js2-deflocal js2-ts-line-end-char -1
687 "Token stream buffer-local variable.")
688
689 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
690 "Token stream buffer-local variable.
691 Current scan position.")
692
693 ;; FIXME: Unused.
694 (js2-deflocal js2-ts-is-xml-attribute nil
695 "Token stream buffer-local variable.")
696
697 (js2-deflocal js2-ts-xml-is-tag-content nil
698 "Token stream buffer-local variable.")
699
700 (js2-deflocal js2-ts-xml-open-tags-count 0
701 "Token stream buffer-local variable.")
702
703 (js2-deflocal js2-ts-string-buffer nil
704 "Token stream buffer-local variable.
705 List of chars built up while scanning various tokens.")
706
707 (defstruct (js2-token
708 (:constructor nil)
709 (:constructor make-js2-token (beg)))
710 "Value returned from the token stream."
711 (type js2-EOF)
712 (beg 1)
713 (end -1)
714 (string "")
715 number
716 regexp-flags
717 comment-type
718 follows-eol-p)
719
720 (defstruct (js2-ts-state
721 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
722 (cursor js2-ts-cursor)
723 (tokens (copy-sequence js2-ti-tokens))
724 (tokens-cursor js2-ti-tokens-cursor)
725 (lookahead js2-ti-lookahead))))
726 lineno
727 cursor
728 tokens
729 tokens-cursor
730 lookahead)
731
732 ;;; Parser variables
733
734 (js2-deflocal js2-parsed-errors nil
735 "List of errors produced during scanning/parsing.")
736
737 (js2-deflocal js2-parsed-warnings nil
738 "List of warnings produced during scanning/parsing.")
739
740 (js2-deflocal js2-recover-from-parse-errors t
741 "Non-nil to continue parsing after a syntax error.
742
743 In recovery mode, the AST will be built in full, and any error
744 nodes will be flagged with appropriate error information. If
745 this flag is nil, a syntax error will result in an error being
746 signaled.
747
748 The variable is automatically buffer-local, because different
749 modes that use the parser will need different settings.")
750
751 (js2-deflocal js2-parse-hook nil
752 "List of callbacks for receiving parsing progress.")
753
754 (defvar js2-parse-finished-hook nil
755 "List of callbacks to notify when parsing finishes.
756 Not called if parsing was interrupted.")
757
758 (js2-deflocal js2-is-eval-code nil
759 "True if we're evaluating code in a string.
760 If non-nil, the tokenizer will record the token text, and the AST nodes
761 will record their source text. Off by default for IDE modes, since the
762 text is available in the buffer.")
763
764 (defvar js2-parse-ide-mode t
765 "Non-nil if the parser is being used for `js2-mode'.
766 If non-nil, the parser will set text properties for fontification
767 and the syntax table. The value should be nil when using the
768 parser as a frontend to an interpreter or byte compiler.")
769
770 ;;; Parser instance variables (buffer-local vars for js2-parse)
771
772 (defconst js2-ti-after-eol (lsh 1 16)
773 "Flag: first token of the source line.")
774
775 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
776
777 (js2-deflocal js2-compiler-generate-debug-info t)
778 (js2-deflocal js2-compiler-use-dynamic-scope nil)
779 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
780 (js2-deflocal js2-compiler-xml-available t)
781 (js2-deflocal js2-compiler-optimization-level 0)
782 (js2-deflocal js2-compiler-generating-source t)
783 (js2-deflocal js2-compiler-strict-mode nil)
784 (js2-deflocal js2-compiler-report-warning-as-error nil)
785 (js2-deflocal js2-compiler-generate-observer-count nil)
786 (js2-deflocal js2-compiler-activation-names nil)
787
788 ;; SKIP: sourceURI
789
790 ;; There's a compileFunction method in Context.java - may need it.
791 (js2-deflocal js2-called-by-compile-function nil
792 "True if `js2-parse' was called by `js2-compile-function'.
793 Will only be used when we finish implementing the interpreter.")
794
795 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
796
797 ;; SKIP: node factory - we're going to just call functions directly,
798 ;; and eventually go to a unified AST format.
799
800 (js2-deflocal js2-nesting-of-function 0)
801
802 (js2-deflocal js2-recorded-identifiers nil
803 "Tracks identifiers found during parsing.")
804
805 (js2-deflocal js2-is-in-destructuring nil
806 "True while parsing destructuring expression.")
807
808 (defcustom js2-global-externs nil
809 "A list of any extern names you'd like to consider always declared.
810 This list is global and is used by all `js2-mode' files.
811 You can create buffer-local externs list using `js2-additional-externs'.
812
813 There is also a buffer-local variable `js2-default-externs',
814 which is initialized by default to include the Ecma-262 externs
815 and the standard browser externs. The three lists are all
816 checked during highlighting."
817 :type 'list
818 :group 'js2-mode)
819
820 (js2-deflocal js2-default-externs nil
821 "Default external declarations.
822
823 These are currently only used for highlighting undeclared variables,
824 which only worries about top-level (unqualified) references.
825 As js2-mode's processing improves, we will flesh out this list.
826
827 The initial value is set to `js2-ecma-262-externs', unless some
828 of the `js2-include-?-externs' variables are set to t, in which
829 case the browser, Rhino and/or Node.js externs are also included.
830
831 See `js2-additional-externs' for more information.")
832
833 (defcustom js2-include-browser-externs t
834 "Non-nil to include browser externs in the master externs list.
835 If you work on JavaScript files that are not intended for browsers,
836 such as Mozilla Rhino server-side JavaScript, set this to nil.
837 See `js2-additional-externs' for more information about externs."
838 :type 'boolean
839 :group 'js2-mode)
840
841 (defcustom js2-include-rhino-externs nil
842 "Non-nil to include Mozilla Rhino externs in the master externs list.
843 See `js2-additional-externs' for more information about externs."
844 :type 'boolean
845 :group 'js2-mode)
846
847 (defcustom js2-include-node-externs nil
848 "Non-nil to include Node.js externs in the master externs list.
849 See `js2-additional-externs' for more information about externs."
850 :type 'boolean
851 :group 'js2-mode)
852
853 (js2-deflocal js2-additional-externs nil
854 "A buffer-local list of additional external declarations.
855 It is used to decide whether variables are considered undeclared
856 for purposes of highlighting.
857
858 Each entry is a Lisp string. The string should be the fully qualified
859 name of an external entity. All externs should be added to this list,
860 so that as js2-mode's processing improves it can take advantage of them.
861
862 You may want to declare your externs in three ways.
863 First, you can add externs that are valid for all your JavaScript files.
864 You should probably do this by adding them to `js2-global-externs', which
865 is a global list used for all js2-mode files.
866
867 Next, you can add a function to `js2-init-hook' that adds additional
868 externs appropriate for the specific file, perhaps based on its path.
869 These should go in `js2-additional-externs', which is buffer-local.
870
871 Third, you can use JSLint's global declaration, as long as
872 `js2-include-jslint-globals' is non-nil, which see.
873
874 Finally, you can add a function to `js2-post-parse-callbacks',
875 which is called after parsing completes, and `js2-mode-ast' is bound to
876 the root of the parse tree. At this stage you can set up an AST
877 node visitor using `js2-visit-ast' and examine the parse tree
878 for specific import patterns that may imply the existence of
879 other externs, possibly tied to your build system. These should also
880 be added to `js2-additional-externs'.
881
882 Your post-parse callback may of course also use the simpler and
883 faster (but perhaps less robust) approach of simply scanning the
884 buffer text for your imports, using regular expressions.")
885
886 ;; SKIP: decompiler
887 ;; SKIP: encoded-source
888
889 ;;; The following variables are per-function and should be saved/restored
890 ;;; during function parsing...
891
892 (js2-deflocal js2-current-script-or-fn nil)
893 (js2-deflocal js2-current-scope nil)
894 (js2-deflocal js2-nesting-of-with 0)
895 (js2-deflocal js2-label-set nil
896 "An alist mapping label names to nodes.")
897
898 (js2-deflocal js2-loop-set nil)
899 (js2-deflocal js2-loop-and-switch-set nil)
900 (js2-deflocal js2-has-return-value nil)
901 (js2-deflocal js2-end-flags 0)
902
903 ;;; ...end of per function variables
904
905 ;; These flags enumerate the possible ways a statement/function can
906 ;; terminate. These flags are used by endCheck() and by the Parser to
907 ;; detect inconsistent return usage.
908 ;;
909 ;; END_UNREACHED is reserved for code paths that are assumed to always be
910 ;; able to execute (example: throw, continue)
911 ;;
912 ;; END_DROPS_OFF indicates if the statement can transfer control to the
913 ;; next one. Statement such as return dont. A compound statement may have
914 ;; some branch that drops off control to the next statement.
915 ;;
916 ;; END_RETURNS indicates that the statement can return (without arguments)
917 ;; END_RETURNS_VALUE indicates that the statement can return a value.
918 ;;
919 ;; A compound statement such as
920 ;; if (condition) {
921 ;; return value;
922 ;; }
923 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
924
925 (defconst js2-end-unreached #x0)
926 (defconst js2-end-drops-off #x1)
927 (defconst js2-end-returns #x2)
928 (defconst js2-end-returns-value #x4)
929
930 ;; Rhino awkwardly passes a statementLabel parameter to the
931 ;; statementHelper() function, the main statement parser, which
932 ;; is then used by quite a few of the sub-parsers. We just make
933 ;; it a buffer-local variable and make sure it's cleaned up properly.
934 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
935
936 ;; Similarly, Rhino passes an inForInit boolean through about half
937 ;; the expression parsers. We use a dynamically-scoped variable,
938 ;; which makes it easier to funcall the parsers individually without
939 ;; worrying about whether they take the parameter or not.
940 (js2-deflocal js2-in-for-init nil)
941 (js2-deflocal js2-temp-name-counter 0)
942 (js2-deflocal js2-parse-stmt-count 0)
943
944 (defsubst js2-get-next-temp-name ()
945 (format "$%d" (incf js2-temp-name-counter)))
946
947 (defvar js2-parse-interruptable-p t
948 "Set this to nil to force parse to continue until finished.
949 This will mostly be useful for interpreters.")
950
951 (defvar js2-statements-per-pause 50
952 "Pause after this many statements to check for user input.
953 If user input is pending, stop the parse and discard the tree.
954 This makes for a smoother user experience for large files.
955 You may have to wait a second or two before the highlighting
956 and error-reporting appear, but you can always type ahead if
957 you wish. This appears to be more or less how Eclipse, IntelliJ
958 and other editors work.")
959
960 (js2-deflocal js2-record-comments t
961 "Instructs the scanner to record comments in `js2-scanned-comments'.")
962
963 (js2-deflocal js2-scanned-comments nil
964 "List of all comments from the current parse.")
965
966 (defcustom js2-mode-indent-inhibit-undo nil
967 "Non-nil to disable collection of Undo information when indenting lines.
968 Some users have requested this behavior. It's nil by default because
969 other Emacs modes don't work this way."
970 :type 'boolean
971 :group 'js2-mode)
972
973 (defcustom js2-mode-indent-ignore-first-tab nil
974 "If non-nil, ignore first TAB keypress if we look indented properly.
975 It's fairly common for users to navigate to an already-indented line
976 and press TAB for reassurance that it's been indented. For this class
977 of users, we want the first TAB press on a line to be ignored if the
978 line is already indented to one of the precomputed alternatives.
979
980 This behavior is only partly implemented. If you TAB-indent a line,
981 navigate to another line, and then navigate back, it fails to clear
982 the last-indented variable, so it thinks you've already hit TAB once,
983 and performs the indent. A full solution would involve getting on the
984 point-motion hooks for the entire buffer. If we come across another
985 use cases that requires watching point motion, I'll consider doing it.
986
987 If you set this variable to nil, then the TAB key will always change
988 the indentation of the current line, if more than one alternative
989 indentation spot exists."
990 :type 'boolean
991 :group 'js2-mode)
992
993 (defvar js2-indent-hook nil
994 "A hook for user-defined indentation rules.
995
996 Functions on this hook should expect two arguments: (LIST INDEX)
997 The LIST argument is the list of computed indentation points for
998 the current line. INDEX is the list index of the indentation point
999 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1000 indent function is not going to change the current line indentation.
1001
1002 If a hook function on this list returns a non-nil value, then
1003 `js2-bounce-indent' assumes the hook function has performed its own
1004 indentation, and will do nothing. If all hook functions on the list
1005 return nil, then `js2-bounce-indent' will use its computed indentation
1006 and reindent the line.
1007
1008 When hook functions on this hook list are called, the variable
1009 `js2-mode-ast' may or may not be set, depending on whether the
1010 parse tree is available. If the variable is nil, you can pass a
1011 callback to `js2-mode-wait-for-parse', and your callback will be
1012 called after the new parse tree is built. This can take some time
1013 in large files.")
1014
1015 (defface js2-warning
1016 `((((class color) (background light))
1017 (:underline "orange"))
1018 (((class color) (background dark))
1019 (:underline "orange"))
1020 (t (:underline t)))
1021 "Face for JavaScript warnings."
1022 :group 'js2-mode)
1023
1024 (defface js2-error
1025 `((((class color) (background light))
1026 (:foreground "red"))
1027 (((class color) (background dark))
1028 (:foreground "red"))
1029 (t (:foreground "red")))
1030 "Face for JavaScript errors."
1031 :group 'js2-mode)
1032
1033 (defface js2-jsdoc-tag
1034 '((t :foreground "SlateGray"))
1035 "Face used to highlight @whatever tags in jsdoc comments."
1036 :group 'js2-mode)
1037
1038 (defface js2-jsdoc-type
1039 '((t :foreground "SteelBlue"))
1040 "Face used to highlight {FooBar} types in jsdoc comments."
1041 :group 'js2-mode)
1042
1043 (defface js2-jsdoc-value
1044 '((t :foreground "PeachPuff3"))
1045 "Face used to highlight tag values in jsdoc comments."
1046 :group 'js2-mode)
1047
1048 (defface js2-function-param
1049 '((t :foreground "SeaGreen"))
1050 "Face used to highlight function parameters in javascript."
1051 :group 'js2-mode)
1052
1053 (defface js2-function-call
1054 '((t :inherit default))
1055 "Face used to highlight function name in calls."
1056 :group 'js2-mode)
1057
1058 (defface js2-instance-member
1059 '((t :foreground "DarkOrchid"))
1060 "Face used to highlight instance variables in javascript.
1061 Not currently used."
1062 :group 'js2-mode)
1063
1064 (defface js2-private-member
1065 '((t :foreground "PeachPuff3"))
1066 "Face used to highlight calls to private methods in javascript.
1067 Not currently used."
1068 :group 'js2-mode)
1069
1070 (defface js2-private-function-call
1071 '((t :foreground "goldenrod"))
1072 "Face used to highlight calls to private functions in javascript.
1073 Not currently used."
1074 :group 'js2-mode)
1075
1076 (defface js2-jsdoc-html-tag-name
1077 '((((class color) (min-colors 88) (background light))
1078 (:foreground "rosybrown"))
1079 (((class color) (min-colors 8) (background dark))
1080 (:foreground "yellow"))
1081 (((class color) (min-colors 8) (background light))
1082 (:foreground "magenta")))
1083 "Face used to highlight jsdoc html tag names"
1084 :group 'js2-mode)
1085
1086 (defface js2-jsdoc-html-tag-delimiter
1087 '((((class color) (min-colors 88) (background light))
1088 (:foreground "dark khaki"))
1089 (((class color) (min-colors 8) (background dark))
1090 (:foreground "green"))
1091 (((class color) (min-colors 8) (background light))
1092 (:foreground "green")))
1093 "Face used to highlight brackets in jsdoc html tags."
1094 :group 'js2-mode)
1095
1096 (defface js2-external-variable
1097 '((t :foreground "orange"))
1098 "Face used to highlight undeclared variable identifiers.")
1099
1100 (defcustom js2-init-hook nil
1101 "List of functions to be called after `js2-mode' or
1102 `js2-minor-mode' has initialized all variables, before parsing
1103 the buffer for the first time."
1104 :type 'hook
1105 :group 'js2-mode
1106 :version "20130608")
1107
1108 (defcustom js2-post-parse-callbacks nil
1109 "List of callback functions invoked after parsing finishes.
1110 Currently, the main use for this function is to add synthetic
1111 declarations to `js2-recorded-identifiers', which see."
1112 :type 'hook
1113 :group 'js2-mode)
1114
1115 (defcustom js2-highlight-external-variables t
1116 "Non-nil to highlight undeclared variable identifiers.
1117 An undeclared variable is any variable not declared with var or let
1118 in the current scope or any lexically enclosing scope. If you use
1119 such a variable, then you are either expecting it to originate from
1120 another file, or you've got a potential bug."
1121 :type 'boolean
1122 :group 'js2-mode)
1123
1124 (defcustom js2-include-jslint-globals t
1125 "Non-nil to include the identifiers from JSLint global
1126 declaration (see http://www.jslint.com/lint.html#global) in the
1127 buffer-local externs list. See `js2-additional-externs' for more
1128 information."
1129 :type 'boolean
1130 :group 'js2-mode)
1131
1132 (defvar js2-mode-map
1133 (let ((map (make-sparse-keymap)))
1134 (define-key map [mouse-1] #'js2-mode-show-node)
1135 (define-key map (kbd "M-j") #'js2-line-break)
1136 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1137 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1138 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1139 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1140 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1141 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1142 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1143 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1144 (when js2-bounce-indent-p
1145 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1146
1147 (define-key map [menu-bar javascript]
1148 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1149
1150 (define-key map [menu-bar javascript customize-js2-mode]
1151 '(menu-item "Customize js2-mode" js2-mode-customize
1152 :help "Customize the behavior of this mode"))
1153
1154 (define-key map [menu-bar javascript js2-force-refresh]
1155 '(menu-item "Force buffer refresh" js2-mode-reset
1156 :help "Re-parse the buffer from scratch"))
1157
1158 (define-key map [menu-bar javascript separator-2]
1159 '("--"))
1160
1161 (define-key map [menu-bar javascript next-error]
1162 '(menu-item "Next warning or error" next-error
1163 :enabled (and js2-mode-ast
1164 (or (js2-ast-root-errors js2-mode-ast)
1165 (js2-ast-root-warnings js2-mode-ast)))
1166 :help "Move to next warning or error"))
1167
1168 (define-key map [menu-bar javascript display-errors]
1169 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1170 :visible (not js2-mode-show-parse-errors)
1171 :help "Turn on display of warnings and errors"))
1172
1173 (define-key map [menu-bar javascript hide-errors]
1174 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1175 :visible js2-mode-show-parse-errors
1176 :help "Turn off display of warnings and errors"))
1177
1178 (define-key map [menu-bar javascript separator-1]
1179 '("--"))
1180
1181 (define-key map [menu-bar javascript js2-toggle-function]
1182 '(menu-item "Show/collapse element" js2-mode-toggle-element
1183 :help "Hide or show function body or comment"))
1184
1185 (define-key map [menu-bar javascript show-comments]
1186 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1187 :visible js2-mode-comments-hidden
1188 :help "Expand all hidden block comments"))
1189
1190 (define-key map [menu-bar javascript hide-comments]
1191 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1192 :visible (not js2-mode-comments-hidden)
1193 :help "Show block comments as /*...*/"))
1194
1195 (define-key map [menu-bar javascript show-all-functions]
1196 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1197 :visible js2-mode-functions-hidden
1198 :help "Expand all hidden function bodies"))
1199
1200 (define-key map [menu-bar javascript hide-all-functions]
1201 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1202 :visible (not js2-mode-functions-hidden)
1203 :help "Show {...} for all top-level function bodies"))
1204
1205 map)
1206 "Keymap used in `js2-mode' buffers.")
1207
1208 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1209
1210 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1211 "Matches a //-comment line. Must be first non-whitespace on line.
1212 First match-group is the leading whitespace.")
1213
1214 (defvar js2-mode-hook nil)
1215
1216 (js2-deflocal js2-mode-ast nil "Private variable.")
1217 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1218 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1219 (js2-deflocal js2-mode-parsing nil "Private variable.")
1220 (js2-deflocal js2-mode-node-overlay nil)
1221
1222 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1223 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1224
1225 (js2-deflocal js2-mode-fontifications nil "Private variable")
1226 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1227 (js2-deflocal js2-imenu-recorder nil "Private variable")
1228 (js2-deflocal js2-imenu-function-map nil "Private variable")
1229
1230 (defvar js2-paragraph-start
1231 "\\(@[[:alpha:]]+\\>\\|$\\)")
1232
1233 ;; Note that we also set a 'c-in-sws text property in html comments,
1234 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1235 (defvar js2-syntactic-ws-start
1236 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1237
1238 (defvar js2-syntactic-ws-end
1239 "\\s \\|[\n\r/]\\|\\s!")
1240
1241 (defvar js2-syntactic-eol
1242 (concat "\\s *\\(/\\*[^*\n\r]*"
1243 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1244 "\\*+/\\s *\\)*"
1245 "\\(//\\|/\\*[^*\n\r]*"
1246 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1247 "\\|\\\\$\\|$\\)")
1248 "Copied from `java-mode'. Needed for some cc-engine functions.")
1249
1250 (defvar js2-comment-prefix-regexp
1251 "//+\\|\\**")
1252
1253 (defvar js2-comment-start-skip
1254 "\\(//+\\|/\\*+\\)\\s *")
1255
1256 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1257 "Non-nil to emit status messages during parsing.")
1258
1259 (defvar js2-mode-functions-hidden nil "Private variable.")
1260 (defvar js2-mode-comments-hidden nil "Private variable.")
1261
1262 (defvar js2-mode-syntax-table
1263 (let ((table (make-syntax-table)))
1264 (c-populate-syntax-table table)
1265 table)
1266 "Syntax table used in `js2-mode' buffers.")
1267
1268 (defvar js2-mode-abbrev-table nil
1269 "Abbrev table in use in `js2-mode' buffers.")
1270 (define-abbrev-table 'js2-mode-abbrev-table ())
1271
1272 (defvar js2-mode-pending-parse-callbacks nil
1273 "List of functions waiting to be notified that parse is finished.")
1274
1275 (defvar js2-mode-last-indented-line -1)
1276
1277 ;;; Localizable error and warning messages
1278
1279 ;; Messages are copied from Rhino's Messages.properties.
1280 ;; Many of the Java-specific messages have been elided.
1281 ;; Add any js2-specific ones at the end, so we can keep
1282 ;; this file synced with changes to Rhino's.
1283
1284 (defvar js2-message-table
1285 (make-hash-table :test 'equal :size 250)
1286 "Contains localized messages for `js2-mode'.")
1287
1288 ;; TODO(stevey): construct this table at compile-time.
1289 (defmacro js2-msg (key &rest strings)
1290 `(puthash ,key (concat ,@strings)
1291 js2-message-table))
1292
1293 (defun js2-get-msg (msg-key)
1294 "Look up a localized message.
1295 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1296 the correct number of ARGS must be provided."
1297 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1298 (args (if (listp msg-key) (cdr msg-key)))
1299 (msg (gethash key js2-message-table)))
1300 (if msg
1301 (apply #'format msg args)
1302 key))) ; default to showing the key
1303
1304 (js2-msg "msg.dup.parms"
1305 "Duplicate parameter name '%s'.")
1306
1307 (js2-msg "msg.too.big.jump"
1308 "Program too complex: jump offset too big.")
1309
1310 (js2-msg "msg.too.big.index"
1311 "Program too complex: internal index exceeds 64K limit.")
1312
1313 (js2-msg "msg.while.compiling.fn"
1314 "Encountered code generation error while compiling function '%s': %s")
1315
1316 (js2-msg "msg.while.compiling.script"
1317 "Encountered code generation error while compiling script: %s")
1318
1319 ;; Context
1320 (js2-msg "msg.ctor.not.found"
1321 "Constructor for '%s' not found.")
1322
1323 (js2-msg "msg.not.ctor"
1324 "'%s' is not a constructor.")
1325
1326 ;; FunctionObject
1327 (js2-msg "msg.varargs.ctor"
1328 "Method or constructor '%s' must be static "
1329 "with the signature (Context cx, Object[] args, "
1330 "Function ctorObj, boolean inNewExpr) "
1331 "to define a variable arguments constructor.")
1332
1333 (js2-msg "msg.varargs.fun"
1334 "Method '%s' must be static with the signature "
1335 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1336 "to define a variable arguments function.")
1337
1338 (js2-msg "msg.incompat.call"
1339 "Method '%s' called on incompatible object.")
1340
1341 (js2-msg "msg.bad.parms"
1342 "Unsupported parameter type '%s' in method '%s'.")
1343
1344 (js2-msg "msg.bad.method.return"
1345 "Unsupported return type '%s' in method '%s'.")
1346
1347 (js2-msg "msg.bad.ctor.return"
1348 "Construction of objects of type '%s' is not supported.")
1349
1350 (js2-msg "msg.no.overload"
1351 "Method '%s' occurs multiple times in class '%s'.")
1352
1353 (js2-msg "msg.method.not.found"
1354 "Method '%s' not found in '%s'.")
1355
1356 ;; IRFactory
1357
1358 (js2-msg "msg.bad.for.in.lhs"
1359 "Invalid left-hand side of for..in loop.")
1360
1361 (js2-msg "msg.mult.index"
1362 "Only one variable allowed in for..in loop.")
1363
1364 (js2-msg "msg.bad.for.in.destruct"
1365 "Left hand side of for..in loop must be an array of "
1366 "length 2 to accept key/value pair.")
1367
1368 (js2-msg "msg.cant.convert"
1369 "Can't convert to type '%s'.")
1370
1371 (js2-msg "msg.bad.assign.left"
1372 "Invalid assignment left-hand side.")
1373
1374 (js2-msg "msg.bad.decr"
1375 "Invalid decerement operand.")
1376
1377 (js2-msg "msg.bad.incr"
1378 "Invalid increment operand.")
1379
1380 (js2-msg "msg.bad.yield"
1381 "yield must be in a function.")
1382
1383 (js2-msg "msg.yield.parenthesized"
1384 "yield expression must be parenthesized.")
1385
1386 ;; NativeGlobal
1387 (js2-msg "msg.cant.call.indirect"
1388 "Function '%s' must be called directly, and not by way of a "
1389 "function of another name.")
1390
1391 (js2-msg "msg.eval.nonstring"
1392 "Calling eval() with anything other than a primitive "
1393 "string value will simply return the value. "
1394 "Is this what you intended?")
1395
1396 (js2-msg "msg.eval.nonstring.strict"
1397 "Calling eval() with anything other than a primitive "
1398 "string value is not allowed in strict mode.")
1399
1400 (js2-msg "msg.bad.destruct.op"
1401 "Invalid destructuring assignment operator")
1402
1403 ;; NativeCall
1404 (js2-msg "msg.only.from.new"
1405 "'%s' may only be invoked from a `new' expression.")
1406
1407 (js2-msg "msg.deprec.ctor"
1408 "The '%s' constructor is deprecated.")
1409
1410 ;; NativeFunction
1411 (js2-msg "msg.no.function.ref.found"
1412 "no source found to decompile function reference %s")
1413
1414 (js2-msg "msg.arg.isnt.array"
1415 "second argument to Function.prototype.apply must be an array")
1416
1417 ;; NativeGlobal
1418 (js2-msg "msg.bad.esc.mask"
1419 "invalid string escape mask")
1420
1421 ;; NativeRegExp
1422 (js2-msg "msg.bad.quant"
1423 "Invalid quantifier %s")
1424
1425 (js2-msg "msg.overlarge.backref"
1426 "Overly large back reference %s")
1427
1428 (js2-msg "msg.overlarge.min"
1429 "Overly large minimum %s")
1430
1431 (js2-msg "msg.overlarge.max"
1432 "Overly large maximum %s")
1433
1434 (js2-msg "msg.zero.quant"
1435 "Zero quantifier %s")
1436
1437 (js2-msg "msg.max.lt.min"
1438 "Maximum %s less than minimum")
1439
1440 (js2-msg "msg.unterm.quant"
1441 "Unterminated quantifier %s")
1442
1443 (js2-msg "msg.unterm.paren"
1444 "Unterminated parenthetical %s")
1445
1446 (js2-msg "msg.unterm.class"
1447 "Unterminated character class %s")
1448
1449 (js2-msg "msg.bad.range"
1450 "Invalid range in character class.")
1451
1452 (js2-msg "msg.trail.backslash"
1453 "Trailing \\ in regular expression.")
1454
1455 (js2-msg "msg.re.unmatched.right.paren"
1456 "unmatched ) in regular expression.")
1457
1458 (js2-msg "msg.no.regexp"
1459 "Regular expressions are not available.")
1460
1461 (js2-msg "msg.bad.backref"
1462 "back-reference exceeds number of capturing parentheses.")
1463
1464 (js2-msg "msg.bad.regexp.compile"
1465 "Only one argument may be specified if the first "
1466 "argument to RegExp.prototype.compile is a RegExp object.")
1467
1468 ;; Parser
1469 (js2-msg "msg.got.syntax.errors"
1470 "Compilation produced %s syntax errors.")
1471
1472 (js2-msg "msg.var.redecl"
1473 "TypeError: redeclaration of var %s.")
1474
1475 (js2-msg "msg.const.redecl"
1476 "TypeError: redeclaration of const %s.")
1477
1478 (js2-msg "msg.let.redecl"
1479 "TypeError: redeclaration of variable %s.")
1480
1481 (js2-msg "msg.parm.redecl"
1482 "TypeError: redeclaration of formal parameter %s.")
1483
1484 (js2-msg "msg.fn.redecl"
1485 "TypeError: redeclaration of function %s.")
1486
1487 (js2-msg "msg.let.decl.not.in.block"
1488 "SyntaxError: let declaration not directly within block")
1489
1490 ;; NodeTransformer
1491 (js2-msg "msg.dup.label"
1492 "duplicated label")
1493
1494 (js2-msg "msg.undef.label"
1495 "undefined label")
1496
1497 (js2-msg "msg.bad.break"
1498 "unlabelled break must be inside loop or switch")
1499
1500 (js2-msg "msg.continue.outside"
1501 "continue must be inside loop")
1502
1503 (js2-msg "msg.continue.nonloop"
1504 "continue can only use labels of iteration statements")
1505
1506 (js2-msg "msg.bad.throw.eol"
1507 "Line terminator is not allowed between the throw "
1508 "keyword and throw expression.")
1509
1510 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1511 "function statement requires a name")
1512
1513 (js2-msg "msg.no.paren.parms"
1514 "missing ( before function parameters.")
1515
1516 (js2-msg "msg.no.parm"
1517 "missing formal parameter")
1518
1519 (js2-msg "msg.no.paren.after.parms"
1520 "missing ) after formal parameters")
1521
1522 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1523 "parameter without default follows parameter with default")
1524
1525 (js2-msg "msg.param.after.rest" ; added by js2-mode
1526 "parameter after rest parameter")
1527
1528 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1529 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1530
1531 (js2-msg "msg.no.brace.body"
1532 "missing '{' before function body")
1533
1534 (js2-msg "msg.no.brace.after.body"
1535 "missing } after function body")
1536
1537 (js2-msg "msg.no.paren.cond"
1538 "missing ( before condition")
1539
1540 (js2-msg "msg.no.paren.after.cond"
1541 "missing ) after condition")
1542
1543 (js2-msg "msg.no.semi.stmt"
1544 "missing ; before statement")
1545
1546 (js2-msg "msg.missing.semi"
1547 "missing ; after statement")
1548
1549 (js2-msg "msg.no.name.after.dot"
1550 "missing name after . operator")
1551
1552 (js2-msg "msg.no.name.after.coloncolon"
1553 "missing name after :: operator")
1554
1555 (js2-msg "msg.no.name.after.dotdot"
1556 "missing name after .. operator")
1557
1558 (js2-msg "msg.no.name.after.xmlAttr"
1559 "missing name after .@")
1560
1561 (js2-msg "msg.no.bracket.index"
1562 "missing ] in index expression")
1563
1564 (js2-msg "msg.no.paren.switch"
1565 "missing ( before switch expression")
1566
1567 (js2-msg "msg.no.paren.after.switch"
1568 "missing ) after switch expression")
1569
1570 (js2-msg "msg.no.brace.switch"
1571 "missing '{' before switch body")
1572
1573 (js2-msg "msg.bad.switch"
1574 "invalid switch statement")
1575
1576 (js2-msg "msg.no.colon.case"
1577 "missing : after case expression")
1578
1579 (js2-msg "msg.double.switch.default"
1580 "double default label in the switch statement")
1581
1582 (js2-msg "msg.no.while.do"
1583 "missing while after do-loop body")
1584
1585 (js2-msg "msg.no.paren.for"
1586 "missing ( after for")
1587
1588 (js2-msg "msg.no.semi.for"
1589 "missing ; after for-loop initializer")
1590
1591 (js2-msg "msg.no.semi.for.cond"
1592 "missing ; after for-loop condition")
1593
1594 (js2-msg "msg.in.after.for.name"
1595 "missing in or of after for")
1596
1597 (js2-msg "msg.no.paren.for.ctrl"
1598 "missing ) after for-loop control")
1599
1600 (js2-msg "msg.no.paren.with"
1601 "missing ( before with-statement object")
1602
1603 (js2-msg "msg.no.paren.after.with"
1604 "missing ) after with-statement object")
1605
1606 (js2-msg "msg.no.paren.after.let"
1607 "missing ( after let")
1608
1609 (js2-msg "msg.no.paren.let"
1610 "missing ) after variable list")
1611
1612 (js2-msg "msg.no.curly.let"
1613 "missing } after let statement")
1614
1615 (js2-msg "msg.bad.return"
1616 "invalid return")
1617
1618 (js2-msg "msg.no.brace.block"
1619 "missing } in compound statement")
1620
1621 (js2-msg "msg.bad.label"
1622 "invalid label")
1623
1624 (js2-msg "msg.bad.var"
1625 "missing variable name")
1626
1627 (js2-msg "msg.bad.var.init"
1628 "invalid variable initialization")
1629
1630 (js2-msg "msg.no.colon.cond"
1631 "missing : in conditional expression")
1632
1633 (js2-msg "msg.no.paren.arg"
1634 "missing ) after argument list")
1635
1636 (js2-msg "msg.no.bracket.arg"
1637 "missing ] after element list")
1638
1639 (js2-msg "msg.bad.prop"
1640 "invalid property id")
1641
1642 (js2-msg "msg.no.colon.prop"
1643 "missing : after property id")
1644
1645 (js2-msg "msg.no.brace.prop"
1646 "missing } after property list")
1647
1648 (js2-msg "msg.no.paren"
1649 "missing ) in parenthetical")
1650
1651 (js2-msg "msg.reserved.id"
1652 "'%s' is a reserved identifier")
1653
1654 (js2-msg "msg.no.paren.catch"
1655 "missing ( before catch-block condition")
1656
1657 (js2-msg "msg.bad.catchcond"
1658 "invalid catch block condition")
1659
1660 (js2-msg "msg.catch.unreachable"
1661 "any catch clauses following an unqualified catch are unreachable")
1662
1663 (js2-msg "msg.no.brace.try"
1664 "missing '{' before try block")
1665
1666 (js2-msg "msg.no.brace.catchblock"
1667 "missing '{' before catch-block body")
1668
1669 (js2-msg "msg.try.no.catchfinally"
1670 "'try' without 'catch' or 'finally'")
1671
1672 (js2-msg "msg.no.return.value"
1673 "function %s does not always return a value")
1674
1675 (js2-msg "msg.anon.no.return.value"
1676 "anonymous function does not always return a value")
1677
1678 (js2-msg "msg.return.inconsistent"
1679 "return statement is inconsistent with previous usage")
1680
1681 (js2-msg "msg.generator.returns"
1682 "TypeError: legacy generator function '%s' returns a value")
1683
1684 (js2-msg "msg.anon.generator.returns"
1685 "TypeError: anonymous legacy generator function returns a value")
1686
1687 (js2-msg "msg.syntax"
1688 "syntax error")
1689
1690 (js2-msg "msg.unexpected.eof"
1691 "Unexpected end of file")
1692
1693 (js2-msg "msg.XML.bad.form"
1694 "illegally formed XML syntax")
1695
1696 (js2-msg "msg.XML.not.available"
1697 "XML runtime not available")
1698
1699 (js2-msg "msg.too.deep.parser.recursion"
1700 "Too deep recursion while parsing")
1701
1702 (js2-msg "msg.no.side.effects"
1703 "Code has no side effects")
1704
1705 (js2-msg "msg.extra.trailing.comma"
1706 "Trailing comma is not supported in some browsers")
1707
1708 (js2-msg "msg.array.trailing.comma"
1709 "Trailing comma yields different behavior across browsers")
1710
1711 (js2-msg "msg.equal.as.assign"
1712 (concat "Test for equality (==) mistyped as assignment (=)?"
1713 " (parenthesize to suppress warning)"))
1714
1715 (js2-msg "msg.var.hides.arg"
1716 "Variable %s hides argument")
1717
1718 (js2-msg "msg.destruct.assign.no.init"
1719 "Missing = in destructuring declaration")
1720
1721 ;; ScriptRuntime
1722 (js2-msg "msg.no.properties"
1723 "%s has no properties.")
1724
1725 (js2-msg "msg.invalid.iterator"
1726 "Invalid iterator value")
1727
1728 (js2-msg "msg.iterator.primitive"
1729 "__iterator__ returned a primitive value")
1730
1731 (js2-msg "msg.assn.create.strict"
1732 "Assignment to undeclared variable %s")
1733
1734 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1735 "Undeclared variable or function '%s'")
1736
1737 (js2-msg "msg.ref.undefined.prop"
1738 "Reference to undefined property '%s'")
1739
1740 (js2-msg "msg.prop.not.found"
1741 "Property %s not found.")
1742
1743 (js2-msg "msg.invalid.type"
1744 "Invalid JavaScript value of type %s")
1745
1746 (js2-msg "msg.primitive.expected"
1747 "Primitive type expected (had %s instead)")
1748
1749 (js2-msg "msg.namespace.expected"
1750 "Namespace object expected to left of :: (found %s instead)")
1751
1752 (js2-msg "msg.null.to.object"
1753 "Cannot convert null to an object.")
1754
1755 (js2-msg "msg.undef.to.object"
1756 "Cannot convert undefined to an object.")
1757
1758 (js2-msg "msg.cyclic.value"
1759 "Cyclic %s value not allowed.")
1760
1761 (js2-msg "msg.is.not.defined"
1762 "'%s' is not defined.")
1763
1764 (js2-msg "msg.undef.prop.read"
1765 "Cannot read property '%s' from %s")
1766
1767 (js2-msg "msg.undef.prop.write"
1768 "Cannot set property '%s' of %s to '%s'")
1769
1770 (js2-msg "msg.undef.prop.delete"
1771 "Cannot delete property '%s' of %s")
1772
1773 (js2-msg "msg.undef.method.call"
1774 "Cannot call method '%s' of %s")
1775
1776 (js2-msg "msg.undef.with"
1777 "Cannot apply 'with' to %s")
1778
1779 (js2-msg "msg.isnt.function"
1780 "%s is not a function, it is %s.")
1781
1782 (js2-msg "msg.isnt.function.in"
1783 "Cannot call property %s in object %s. "
1784 "It is not a function, it is '%s'.")
1785
1786 (js2-msg "msg.function.not.found"
1787 "Cannot find function %s.")
1788
1789 (js2-msg "msg.function.not.found.in"
1790 "Cannot find function %s in object %s.")
1791
1792 (js2-msg "msg.isnt.xml.object"
1793 "%s is not an xml object.")
1794
1795 (js2-msg "msg.no.ref.to.get"
1796 "%s is not a reference to read reference value.")
1797
1798 (js2-msg "msg.no.ref.to.set"
1799 "%s is not a reference to set reference value to %s.")
1800
1801 (js2-msg "msg.no.ref.from.function"
1802 "Function %s can not be used as the left-hand "
1803 "side of assignment or as an operand of ++ or -- operator.")
1804
1805 (js2-msg "msg.bad.default.value"
1806 "Object's getDefaultValue() method returned an object.")
1807
1808 (js2-msg "msg.instanceof.not.object"
1809 "Can't use instanceof on a non-object.")
1810
1811 (js2-msg "msg.instanceof.bad.prototype"
1812 "'prototype' property of %s is not an object.")
1813
1814 (js2-msg "msg.bad.radix"
1815 "illegal radix %s.")
1816
1817 ;; ScriptableObject
1818 (js2-msg "msg.default.value"
1819 "Cannot find default value for object.")
1820
1821 (js2-msg "msg.zero.arg.ctor"
1822 "Cannot load class '%s' which has no zero-parameter constructor.")
1823
1824 (js2-msg "msg.ctor.multiple.parms"
1825 "Can't define constructor or class %s since more than "
1826 "one constructor has multiple parameters.")
1827
1828 (js2-msg "msg.extend.scriptable"
1829 "%s must extend ScriptableObject in order to define property %s.")
1830
1831 (js2-msg "msg.bad.getter.parms"
1832 "In order to define a property, getter %s must have zero "
1833 "parameters or a single ScriptableObject parameter.")
1834
1835 (js2-msg "msg.obj.getter.parms"
1836 "Expected static or delegated getter %s to take "
1837 "a ScriptableObject parameter.")
1838
1839 (js2-msg "msg.getter.static"
1840 "Getter and setter must both be static or neither be static.")
1841
1842 (js2-msg "msg.setter.return"
1843 "Setter must have void return type: %s")
1844
1845 (js2-msg "msg.setter2.parms"
1846 "Two-parameter setter must take a ScriptableObject as "
1847 "its first parameter.")
1848
1849 (js2-msg "msg.setter1.parms"
1850 "Expected single parameter setter for %s")
1851
1852 (js2-msg "msg.setter2.expected"
1853 "Expected static or delegated setter %s to take two parameters.")
1854
1855 (js2-msg "msg.setter.parms"
1856 "Expected either one or two parameters for setter.")
1857
1858 (js2-msg "msg.setter.bad.type"
1859 "Unsupported parameter type '%s' in setter '%s'.")
1860
1861 (js2-msg "msg.add.sealed"
1862 "Cannot add a property to a sealed object: %s.")
1863
1864 (js2-msg "msg.remove.sealed"
1865 "Cannot remove a property from a sealed object: %s.")
1866
1867 (js2-msg "msg.modify.sealed"
1868 "Cannot modify a property of a sealed object: %s.")
1869
1870 (js2-msg "msg.modify.readonly"
1871 "Cannot modify readonly property: %s.")
1872
1873 ;; TokenStream
1874 (js2-msg "msg.missing.exponent"
1875 "missing exponent")
1876
1877 (js2-msg "msg.caught.nfe"
1878 "number format error")
1879
1880 (js2-msg "msg.unterminated.string.lit"
1881 "unterminated string literal")
1882
1883 (js2-msg "msg.unterminated.comment"
1884 "unterminated comment")
1885
1886 (js2-msg "msg.unterminated.re.lit"
1887 "unterminated regular expression literal")
1888
1889 (js2-msg "msg.invalid.re.flag"
1890 "invalid flag after regular expression")
1891
1892 (js2-msg "msg.no.re.input.for"
1893 "no input for %s")
1894
1895 (js2-msg "msg.illegal.character"
1896 "illegal character")
1897
1898 (js2-msg "msg.invalid.escape"
1899 "invalid Unicode escape sequence")
1900
1901 (js2-msg "msg.bad.namespace"
1902 "not a valid default namespace statement. "
1903 "Syntax is: default xml namespace = EXPRESSION;")
1904
1905 ;; TokensStream warnings
1906 (js2-msg "msg.bad.octal.literal"
1907 "illegal octal literal digit %s; "
1908 "interpreting it as a decimal digit")
1909
1910 (js2-msg "msg.missing.hex.digits"
1911 "missing hexadecimal digits after '0x'")
1912
1913 (js2-msg "msg.missing.binary.digits"
1914 "missing binary digits after '0b'")
1915
1916 (js2-msg "msg.missing.octal.digits"
1917 "missing octal digits after '0o'")
1918
1919 (js2-msg "msg.script.is.not.constructor"
1920 "Script objects are not constructors.")
1921
1922 ;; Arrays
1923 (js2-msg "msg.arraylength.bad"
1924 "Inappropriate array length.")
1925
1926 ;; Arrays
1927 (js2-msg "msg.arraylength.too.big"
1928 "Array length %s exceeds supported capacity limit.")
1929
1930 ;; URI
1931 (js2-msg "msg.bad.uri"
1932 "Malformed URI sequence.")
1933
1934 ;; Number
1935 (js2-msg "msg.bad.precision"
1936 "Precision %s out of range.")
1937
1938 ;; NativeGenerator
1939 (js2-msg "msg.send.newborn"
1940 "Attempt to send value to newborn generator")
1941
1942 (js2-msg "msg.already.exec.gen"
1943 "Already executing generator")
1944
1945 (js2-msg "msg.StopIteration.invalid"
1946 "StopIteration may not be changed to an arbitrary object.")
1947
1948 ;; Interpreter
1949 (js2-msg "msg.yield.closing"
1950 "Yield from closing generator")
1951
1952 ;;; Tokens Buffer
1953
1954 (defconst js2-ti-max-lookahead 2)
1955 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1956
1957 ;; Have to call `js2-init-scanner' to initialize the values.
1958 (js2-deflocal js2-ti-tokens nil)
1959 (js2-deflocal js2-ti-tokens-cursor nil)
1960 (js2-deflocal js2-ti-lookahead nil)
1961
1962 (defun js2-new-token (offset)
1963 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
1964 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
1965 (aset js2-ti-tokens js2-ti-tokens-cursor token)
1966 token))
1967
1968 (defsubst js2-current-token ()
1969 (aref js2-ti-tokens js2-ti-tokens-cursor))
1970
1971 (defsubst js2-current-token-string ()
1972 (js2-token-string (js2-current-token)))
1973
1974 (defsubst js2-current-token-type ()
1975 (js2-token-type (js2-current-token)))
1976
1977 (defsubst js2-current-token-beg ()
1978 (js2-token-beg (js2-current-token)))
1979
1980 (defsubst js2-current-token-end ()
1981 (js2-token-end (js2-current-token)))
1982
1983 (defun js2-current-token-len ()
1984 (let ((token (js2-current-token)))
1985 (- (js2-token-end token)
1986 (js2-token-beg token))))
1987
1988 (defun js2-ts-seek (state)
1989 (setq js2-ts-lineno (js2-ts-state-lineno state)
1990 js2-ts-cursor (js2-ts-state-cursor state)
1991 js2-ti-tokens (js2-ts-state-tokens state)
1992 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
1993 js2-ti-lookahead (js2-ts-state-lookahead state)))
1994
1995 ;;; Utilities
1996
1997 (defun js2-delete-if (predicate list)
1998 "Remove all items satisfying PREDICATE in LIST."
1999 (loop for item in list
2000 if (not (funcall predicate item))
2001 collect item))
2002
2003 (defun js2-position (element list)
2004 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2005 Returns nil if element is not found in the list."
2006 (let ((count 0)
2007 found)
2008 (while (and list (not found))
2009 (if (eq element (car list))
2010 (setq found t)
2011 (setq count (1+ count)
2012 list (cdr list))))
2013 (if found count)))
2014
2015 (defun js2-find-if (predicate list)
2016 "Find first item satisfying PREDICATE in LIST."
2017 (let (result)
2018 (while (and list (not result))
2019 (if (funcall predicate (car list))
2020 (setq result (car list)))
2021 (setq list (cdr list)))
2022 result))
2023
2024 (defmacro js2-time (form)
2025 "Evaluate FORM, discard result, and return elapsed time in sec."
2026 (declare (debug t))
2027 (let ((beg (make-symbol "--js2-time-beg--"))
2028 (delta (make-symbol "--js2-time-end--")))
2029 `(let ((,beg (current-time))
2030 ,delta)
2031 ,form
2032 (/ (truncate (* (- (float-time (current-time))
2033 (float-time ,beg))
2034 10000))
2035 10000.0))))
2036
2037 (defsubst js2-same-line (pos)
2038 "Return t if POS is on the same line as current point."
2039 (and (>= pos (point-at-bol))
2040 (<= pos (point-at-eol))))
2041
2042 (defun js2-code-bug ()
2043 "Signal an error when we encounter an unexpected code path."
2044 (error "failed assertion"))
2045
2046 (defsubst js2-record-text-property (beg end prop value)
2047 "Record a text property to set when parsing finishes."
2048 (push (list beg end prop value) js2-mode-deferred-properties))
2049
2050 ;; I'd like to associate errors with nodes, but for now the
2051 ;; easiest thing to do is get the context info from the last token.
2052 (defun js2-record-parse-error (msg &optional arg pos len)
2053 (push (list (list msg arg)
2054 (or pos (js2-current-token-beg))
2055 (or len (js2-current-token-len)))
2056 js2-parsed-errors))
2057
2058 (defun js2-report-error (msg &optional msg-arg pos len)
2059 "Signal a syntax error or record a parse error."
2060 (if js2-recover-from-parse-errors
2061 (js2-record-parse-error msg msg-arg pos len)
2062 (signal 'js2-syntax-error
2063 (list msg
2064 js2-ts-lineno
2065 (save-excursion
2066 (goto-char js2-ts-cursor)
2067 (current-column))
2068 js2-ts-hit-eof))))
2069
2070 (defun js2-report-warning (msg &optional msg-arg pos len face)
2071 (if js2-compiler-report-warning-as-error
2072 (js2-report-error msg msg-arg pos len)
2073 (push (list (list msg msg-arg)
2074 (or pos (js2-current-token-beg))
2075 (or len (js2-current-token-len))
2076 face)
2077 js2-parsed-warnings)))
2078
2079 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2080 (if js2-compiler-strict-mode
2081 (js2-report-warning msg-id msg-arg beg
2082 (and beg end (- end beg)))))
2083
2084 (put 'js2-syntax-error 'error-conditions
2085 '(error syntax-error js2-syntax-error))
2086 (put 'js2-syntax-error 'error-message "Syntax error")
2087
2088 (put 'js2-parse-error 'error-conditions
2089 '(error parse-error js2-parse-error))
2090 (put 'js2-parse-error 'error-message "Parse error")
2091
2092 (defmacro js2-clear-flag (flags flag)
2093 `(setq ,flags (logand ,flags (lognot ,flag))))
2094
2095 (defmacro js2-set-flag (flags flag)
2096 "Logical-or FLAG into FLAGS."
2097 `(setq ,flags (logior ,flags ,flag)))
2098
2099 (defsubst js2-flag-set-p (flags flag)
2100 (/= 0 (logand flags flag)))
2101
2102 (defsubst js2-flag-not-set-p (flags flag)
2103 (zerop (logand flags flag)))
2104
2105 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2106 "Evaluate BODY with the _ character set to be word-syntax."
2107 (declare (indent 0) (debug t))
2108 (let ((old-syntax (make-symbol "old-syntax")))
2109 `(let ((,old-syntax (string (char-syntax ?_))))
2110 (unwind-protect
2111 (progn
2112 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2113 ,@body)
2114 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2115
2116 ;;; AST struct and function definitions
2117
2118 ;; flags for ast node property 'member-type (used for e4x operators)
2119 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2120 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2121 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2122
2123 (defsubst js2-relpos (pos anchor)
2124 "Convert POS to be relative to ANCHOR.
2125 If POS is nil, returns nil."
2126 (and pos (- pos anchor)))
2127
2128 (defun js2-make-pad (indent)
2129 (if (zerop indent)
2130 ""
2131 (make-string (* indent js2-basic-offset) ? )))
2132
2133 (defun js2-visit-ast (node callback)
2134 "Visit every node in ast NODE with visitor CALLBACK.
2135
2136 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2137 called twice: once to visit the node, and again after all the node's
2138 children have been processed. The END-P argument is nil on the first
2139 call and non-nil on the second call. The return value of the callback
2140 affects the traversal: if non-nil, the children of NODE are processed.
2141 If the callback returns nil, or if the node has no children, then the
2142 callback is called immediately with a non-nil END-P argument.
2143
2144 The node traversal is approximately lexical-order, although there
2145 are currently no guarantees around this."
2146 (when node
2147 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2148 ;; visit the node
2149 (when (funcall callback node nil)
2150 ;; visit the kids
2151 (cond
2152 ((eq vfunc 'js2-visit-none)
2153 nil) ; don't even bother calling it
2154 ;; Each AST node type has to define a `js2-visitor' function
2155 ;; that takes a node and a callback, and calls `js2-visit-ast'
2156 ;; on each child of the node.
2157 (vfunc
2158 (funcall vfunc node callback))
2159 (t
2160 (error "%s does not define a visitor-traversal function"
2161 (aref node 0)))))
2162 ;; call the end-visit
2163 (funcall callback node t))))
2164
2165 (defstruct (js2-node
2166 (:constructor nil)) ; abstract
2167 "Base AST node type."
2168 (type -1) ; token type
2169 (pos -1) ; start position of this AST node in parsed input
2170 (len 1) ; num characters spanned by the node
2171 props ; optional node property list (an alist)
2172 parent) ; link to parent node; null for root
2173
2174 (defsubst js2-node-get-prop (node prop &optional default)
2175 (or (cadr (assoc prop (js2-node-props node))) default))
2176
2177 (defsubst js2-node-set-prop (node prop value)
2178 (setf (js2-node-props node)
2179 (cons (list prop value) (js2-node-props node))))
2180
2181 (defun js2-fixup-starts (n nodes)
2182 "Adjust the start positions of NODES to be relative to N.
2183 Any node in the list may be nil, for convenience."
2184 (dolist (node nodes)
2185 (when node
2186 (setf (js2-node-pos node) (- (js2-node-pos node)
2187 (js2-node-pos n))))))
2188
2189 (defun js2-node-add-children (parent &rest nodes)
2190 "Set parent node of NODES to PARENT, and return PARENT.
2191 Does nothing if we're not recording parent links.
2192 If any given node in NODES is nil, doesn't record that link."
2193 (js2-fixup-starts parent nodes)
2194 (dolist (node nodes)
2195 (and node
2196 (setf (js2-node-parent node) parent))))
2197
2198 ;; Non-recursive since it's called a frightening number of times.
2199 (defun js2-node-abs-pos (n)
2200 (let ((pos (js2-node-pos n)))
2201 (while (setq n (js2-node-parent n))
2202 (setq pos (+ pos (js2-node-pos n))))
2203 pos))
2204
2205 (defsubst js2-node-abs-end (n)
2206 "Return absolute buffer position of end of N."
2207 (+ (js2-node-abs-pos n) (js2-node-len n)))
2208
2209 ;; It's important to make sure block nodes have a Lisp list for the
2210 ;; child nodes, to limit printing recursion depth in an AST that
2211 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2212 ;; a sufficiently large vector tree.
2213
2214 (defstruct (js2-block-node
2215 (:include js2-node)
2216 (:constructor nil)
2217 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2218 (pos (js2-current-token-beg))
2219 len
2220 props
2221 kids)))
2222 "A block of statements."
2223 kids) ; a Lisp list of the child statement nodes
2224
2225 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2226 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2227
2228 (defun js2-visit-block (ast callback)
2229 "Visit the `js2-block-node' children of AST."
2230 (dolist (kid (js2-block-node-kids ast))
2231 (js2-visit-ast kid callback)))
2232
2233 (defun js2-print-block (n i)
2234 (let ((pad (js2-make-pad i)))
2235 (insert pad "{\n")
2236 (dolist (kid (js2-block-node-kids n))
2237 (js2-print-ast kid (1+ i)))
2238 (insert pad "}")))
2239
2240 (defstruct (js2-scope
2241 (:include js2-block-node)
2242 (:constructor nil)
2243 (:constructor make-js2-scope (&key (type js2-BLOCK)
2244 (pos (js2-current-token-beg))
2245 len
2246 kids)))
2247 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2248 ;; I don't have one of those handy, so I'll use an alist for now.
2249 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2250 ;; and is much lighter-weight to construct (both CPU and mem).
2251 ;; The keys are interned strings (symbols) for faster lookup.
2252 ;; Should switch to hybrid alist/hashtable eventually.
2253 symbol-table ; an alist of (symbol . js2-symbol)
2254 parent-scope ; a `js2-scope'
2255 top) ; top-level `js2-scope' (script/function)
2256
2257 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2258 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2259
2260 (defun js2-node-get-enclosing-scope (node)
2261 "Return the innermost `js2-scope' node surrounding NODE.
2262 Returns nil if there is no enclosing scope node."
2263 (let ((parent (js2-node-parent node)))
2264 (while (not (js2-scope-p parent))
2265 (setq parent (js2-node-parent parent)))
2266 parent))
2267
2268 (defun js2-get-defining-scope (scope name)
2269 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2270 Returns `js2-scope' in which NAME is defined, or nil if not found."
2271 (let ((sym (if (symbolp name)
2272 name
2273 (intern name)))
2274 table
2275 result
2276 (continue t))
2277 (while (and scope continue)
2278 (if (and (setq table (js2-scope-symbol-table scope))
2279 (assq sym table))
2280 (setq continue nil
2281 result scope)
2282 (setq scope (js2-scope-parent-scope scope))))
2283 result))
2284
2285 (defun js2-scope-get-symbol (scope name)
2286 "Return symbol table entry for NAME in SCOPE.
2287 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2288 (and (js2-scope-symbol-table scope)
2289 (cdr (assq (if (symbolp name)
2290 name
2291 (intern name))
2292 (js2-scope-symbol-table scope)))))
2293
2294 (defun js2-scope-put-symbol (scope name symbol)
2295 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2296 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2297 (let* ((table (js2-scope-symbol-table scope))
2298 (sym (if (symbolp name) name (intern name)))
2299 (entry (assq sym table)))
2300 (if entry
2301 (setcdr entry symbol)
2302 (push (cons sym symbol)
2303 (js2-scope-symbol-table scope)))))
2304
2305 (defstruct (js2-symbol
2306 (:constructor nil)
2307 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2308 "A symbol table entry."
2309 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2310 ;; js2-LET, or js2-CONST
2311 decl-type
2312 name ; string
2313 ast-node) ; a `js2-node'
2314
2315 (defstruct (js2-error-node
2316 (:include js2-node)
2317 (:constructor nil) ; silence emacs21 byte-compiler
2318 (:constructor make-js2-error-node (&key (type js2-ERROR)
2319 (pos (js2-current-token-beg))
2320 len)))
2321 "AST node representing a parse error.")
2322
2323 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2324 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2325
2326 (defstruct (js2-script-node
2327 (:include js2-scope)
2328 (:constructor nil)
2329 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2330 (pos (js2-current-token-beg))
2331 len
2332 ;; FIXME: What are those?
2333 var-decls
2334 fun-decls)))
2335 functions ; Lisp list of nested functions
2336 regexps ; Lisp list of (string . flags)
2337 symbols ; alist (every symbol gets unique index)
2338 (param-count 0)
2339 var-names ; vector of string names
2340 consts ; bool-vector matching var-decls
2341 (temp-number 0)) ; for generating temp variables
2342
2343 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2344 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2345
2346 (defun js2-print-script (node indent)
2347 (dolist (kid (js2-block-node-kids node))
2348 (js2-print-ast kid indent)))
2349
2350 (defstruct (js2-ast-root
2351 (:include js2-script-node)
2352 (:constructor nil)
2353 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2354 (pos (js2-current-token-beg))
2355 len
2356 buffer)))
2357 "The root node of a js2 AST."
2358 buffer ; the source buffer from which the code was parsed
2359 comments ; a Lisp list of comments, ordered by start position
2360 errors ; a Lisp list of errors found during parsing
2361 warnings ; a Lisp list of warnings found during parsing
2362 node-count) ; number of nodes in the tree, including the root
2363
2364 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2365 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2366
2367 (defun js2-visit-ast-root (ast callback)
2368 (dolist (kid (js2-ast-root-kids ast))
2369 (js2-visit-ast kid callback))
2370 (dolist (comment (js2-ast-root-comments ast))
2371 (js2-visit-ast comment callback)))
2372
2373 (defstruct (js2-comment-node
2374 (:include js2-node)
2375 (:constructor nil)
2376 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2377 (pos (js2-current-token-beg))
2378 len
2379 format)))
2380 format) ; 'line, 'block, 'jsdoc or 'html
2381
2382 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2383 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2384
2385 (defun js2-print-comment (n i)
2386 ;; We really ought to link end-of-line comments to their nodes.
2387 ;; Or maybe we could add a new comment type, 'endline.
2388 (insert (js2-make-pad i)
2389 (js2-node-string n)))
2390
2391 (defstruct (js2-expr-stmt-node
2392 (:include js2-node)
2393 (:constructor nil)
2394 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2395 (pos js2-ts-cursor)
2396 len
2397 expr)))
2398 "An expression statement."
2399 expr)
2400
2401 (defsubst js2-expr-stmt-node-set-has-result (node)
2402 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2403 (setf (js2-node-type node) js2-EXPR_RESULT))
2404
2405 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2406 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2407
2408 (defun js2-visit-expr-stmt-node (n v)
2409 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2410
2411 (defun js2-print-expr-stmt-node (n indent)
2412 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2413 (insert ";\n"))
2414
2415 (defstruct (js2-loop-node
2416 (:include js2-scope)
2417 (:constructor nil))
2418 "Abstract supertype of loop nodes."
2419 body ; a `js2-block-node'
2420 lp ; position of left-paren, nil if omitted
2421 rp) ; position of right-paren, nil if omitted
2422
2423 (defstruct (js2-do-node
2424 (:include js2-loop-node)
2425 (:constructor nil)
2426 (:constructor make-js2-do-node (&key (type js2-DO)
2427 (pos (js2-current-token-beg))
2428 len
2429 body
2430 condition
2431 while-pos
2432 lp
2433 rp)))
2434 "AST node for do-loop."
2435 condition ; while (expression)
2436 while-pos) ; buffer position of 'while' keyword
2437
2438 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2439 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2440
2441 (defun js2-visit-do-node (n v)
2442 (js2-visit-ast (js2-do-node-body n) v)
2443 (js2-visit-ast (js2-do-node-condition n) v))
2444
2445 (defun js2-print-do-node (n i)
2446 (let ((pad (js2-make-pad i)))
2447 (insert pad "do {\n")
2448 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2449 (js2-print-ast kid (1+ i)))
2450 (insert pad "} while (")
2451 (js2-print-ast (js2-do-node-condition n) 0)
2452 (insert ");\n")))
2453
2454 (defstruct (js2-while-node
2455 (:include js2-loop-node)
2456 (:constructor nil)
2457 (:constructor make-js2-while-node (&key (type js2-WHILE)
2458 (pos (js2-current-token-beg))
2459 len body
2460 condition lp
2461 rp)))
2462 "AST node for while-loop."
2463 condition) ; while-condition
2464
2465 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2466 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2467
2468 (defun js2-visit-while-node (n v)
2469 (js2-visit-ast (js2-while-node-condition n) v)
2470 (js2-visit-ast (js2-while-node-body n) v))
2471
2472 (defun js2-print-while-node (n i)
2473 (let ((pad (js2-make-pad i)))
2474 (insert pad "while (")
2475 (js2-print-ast (js2-while-node-condition n) 0)
2476 (insert ") {\n")
2477 (js2-print-body (js2-while-node-body n) (1+ i))
2478 (insert pad "}\n")))
2479
2480 (defstruct (js2-for-node
2481 (:include js2-loop-node)
2482 (:constructor nil)
2483 (:constructor make-js2-for-node (&key (type js2-FOR)
2484 (pos js2-ts-cursor)
2485 len body init
2486 condition
2487 update lp rp)))
2488 "AST node for a C-style for-loop."
2489 init ; initialization expression
2490 condition ; loop condition
2491 update) ; update clause
2492
2493 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2494 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2495
2496 (defun js2-visit-for-node (n v)
2497 (js2-visit-ast (js2-for-node-init n) v)
2498 (js2-visit-ast (js2-for-node-condition n) v)
2499 (js2-visit-ast (js2-for-node-update n) v)
2500 (js2-visit-ast (js2-for-node-body n) v))
2501
2502 (defun js2-print-for-node (n i)
2503 (let ((pad (js2-make-pad i)))
2504 (insert pad "for (")
2505 (js2-print-ast (js2-for-node-init n) 0)
2506 (insert "; ")
2507 (js2-print-ast (js2-for-node-condition n) 0)
2508 (insert "; ")
2509 (js2-print-ast (js2-for-node-update n) 0)
2510 (insert ") {\n")
2511 (js2-print-body (js2-for-node-body n) (1+ i))
2512 (insert pad "}\n")))
2513
2514 (defstruct (js2-for-in-node
2515 (:include js2-loop-node)
2516 (:constructor nil)
2517 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2518 (pos js2-ts-cursor)
2519 len body
2520 iterator
2521 object
2522 in-pos
2523 each-pos
2524 foreach-p forof-p
2525 lp rp)))
2526 "AST node for a for..in loop."
2527 iterator ; [var] foo in ...
2528 object ; object over which we're iterating
2529 in-pos ; buffer position of 'in' keyword
2530 each-pos ; buffer position of 'each' keyword, if foreach-p
2531 foreach-p ; t if it's a for-each loop
2532 forof-p) ; t if it's a for-of loop
2533
2534 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2535 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2536
2537 (defun js2-visit-for-in-node (n v)
2538 (js2-visit-ast (js2-for-in-node-iterator n) v)
2539 (js2-visit-ast (js2-for-in-node-object n) v)
2540 (js2-visit-ast (js2-for-in-node-body n) v))
2541
2542 (defun js2-print-for-in-node (n i)
2543 (let ((pad (js2-make-pad i))
2544 (foreach (js2-for-in-node-foreach-p n))
2545 (forof (js2-for-in-node-forof-p n)))
2546 (insert pad "for ")
2547 (if foreach
2548 (insert "each "))
2549 (insert "(")
2550 (js2-print-ast (js2-for-in-node-iterator n) 0)
2551 (insert (if forof " of " " in "))
2552 (js2-print-ast (js2-for-in-node-object n) 0)
2553 (insert ") {\n")
2554 (js2-print-body (js2-for-in-node-body n) (1+ i))
2555 (insert pad "}\n")))
2556
2557 (defstruct (js2-return-node
2558 (:include js2-node)
2559 (:constructor nil)
2560 (:constructor make-js2-return-node (&key (type js2-RETURN)
2561 (pos js2-ts-cursor)
2562 len
2563 retval)))
2564 "AST node for a return statement."
2565 retval) ; expression to return, or 'undefined
2566
2567 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2568 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2569
2570 (defun js2-visit-return-node (n v)
2571 (js2-visit-ast (js2-return-node-retval n) v))
2572
2573 (defun js2-print-return-node (n i)
2574 (insert (js2-make-pad i) "return")
2575 (when (js2-return-node-retval n)
2576 (insert " ")
2577 (js2-print-ast (js2-return-node-retval n) 0))
2578 (insert ";\n"))
2579
2580 (defstruct (js2-if-node
2581 (:include js2-node)
2582 (:constructor nil)
2583 (:constructor make-js2-if-node (&key (type js2-IF)
2584 (pos js2-ts-cursor)
2585 len condition
2586 then-part
2587 else-pos
2588 else-part lp
2589 rp)))
2590 "AST node for an if-statement."
2591 condition ; expression
2592 then-part ; statement or block
2593 else-pos ; optional buffer position of 'else' keyword
2594 else-part ; optional statement or block
2595 lp ; position of left-paren, nil if omitted
2596 rp) ; position of right-paren, nil if omitted
2597
2598 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2599 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2600
2601 (defun js2-visit-if-node (n v)
2602 (js2-visit-ast (js2-if-node-condition n) v)
2603 (js2-visit-ast (js2-if-node-then-part n) v)
2604 (js2-visit-ast (js2-if-node-else-part n) v))
2605
2606 (defun js2-print-if-node (n i)
2607 (let ((pad (js2-make-pad i))
2608 (then-part (js2-if-node-then-part n))
2609 (else-part (js2-if-node-else-part n)))
2610 (insert pad "if (")
2611 (js2-print-ast (js2-if-node-condition n) 0)
2612 (insert ") {\n")
2613 (js2-print-body then-part (1+ i))
2614 (insert pad "}")
2615 (cond
2616 ((not else-part)
2617 (insert "\n"))
2618 ((js2-if-node-p else-part)
2619 (insert " else ")
2620 (js2-print-body else-part i))
2621 (t
2622 (insert " else {\n")
2623 (js2-print-body else-part (1+ i))
2624 (insert pad "}\n")))))
2625
2626 (defstruct (js2-try-node
2627 (:include js2-node)
2628 (:constructor nil)
2629 (:constructor make-js2-try-node (&key (type js2-TRY)
2630 (pos js2-ts-cursor)
2631 len
2632 try-block
2633 catch-clauses
2634 finally-block)))
2635 "AST node for a try-statement."
2636 try-block
2637 catch-clauses ; a Lisp list of `js2-catch-node'
2638 finally-block) ; a `js2-finally-node'
2639
2640 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2641 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2642
2643 (defun js2-visit-try-node (n v)
2644 (js2-visit-ast (js2-try-node-try-block n) v)
2645 (dolist (clause (js2-try-node-catch-clauses n))
2646 (js2-visit-ast clause v))
2647 (js2-visit-ast (js2-try-node-finally-block n) v))
2648
2649 (defun js2-print-try-node (n i)
2650 (let ((pad (js2-make-pad i))
2651 (catches (js2-try-node-catch-clauses n))
2652 (finally (js2-try-node-finally-block n)))
2653 (insert pad "try {\n")
2654 (js2-print-body (js2-try-node-try-block n) (1+ i))
2655 (insert pad "}")
2656 (when catches
2657 (dolist (catch catches)
2658 (js2-print-ast catch i)))
2659 (if finally
2660 (js2-print-ast finally i)
2661 (insert "\n"))))
2662
2663 (defstruct (js2-catch-node
2664 (:include js2-node)
2665 (:constructor nil)
2666 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2667 (pos js2-ts-cursor)
2668 len
2669 param
2670 guard-kwd
2671 guard-expr
2672 block lp
2673 rp)))
2674 "AST node for a catch clause."
2675 param ; destructuring form or simple name node
2676 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2677 guard-expr ; catch condition, a `js2-node'
2678 block ; statements, a `js2-block-node'
2679 lp ; buffer position of left-paren, nil if omitted
2680 rp) ; buffer position of right-paren, nil if omitted
2681
2682 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2683 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2684
2685 (defun js2-visit-catch-node (n v)
2686 (js2-visit-ast (js2-catch-node-param n) v)
2687 (when (js2-catch-node-guard-kwd n)
2688 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2689 (js2-visit-ast (js2-catch-node-block n) v))
2690
2691 (defun js2-print-catch-node (n i)
2692 (let ((pad (js2-make-pad i))
2693 (guard-kwd (js2-catch-node-guard-kwd n))
2694 (guard-expr (js2-catch-node-guard-expr n)))
2695 (insert " catch (")
2696 (js2-print-ast (js2-catch-node-param n) 0)
2697 (when guard-kwd
2698 (insert " if ")
2699 (js2-print-ast guard-expr 0))
2700 (insert ") {\n")
2701 (js2-print-body (js2-catch-node-block n) (1+ i))
2702 (insert pad "}")))
2703
2704 (defstruct (js2-finally-node
2705 (:include js2-node)
2706 (:constructor nil)
2707 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2708 (pos js2-ts-cursor)
2709 len body)))
2710 "AST node for a finally clause."
2711 body) ; a `js2-node', often but not always a block node
2712
2713 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2714 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2715
2716 (defun js2-visit-finally-node (n v)
2717 (js2-visit-ast (js2-finally-node-body n) v))
2718
2719 (defun js2-print-finally-node (n i)
2720 (let ((pad (js2-make-pad i)))
2721 (insert " finally {\n")
2722 (js2-print-body (js2-finally-node-body n) (1+ i))
2723 (insert pad "}\n")))
2724
2725 (defstruct (js2-switch-node
2726 (:include js2-node)
2727 (:constructor nil)
2728 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2729 (pos js2-ts-cursor)
2730 len
2731 discriminant
2732 cases lp
2733 rp)))
2734 "AST node for a switch statement."
2735 discriminant ; a `js2-node' (switch expression)
2736 cases ; a Lisp list of `js2-case-node'
2737 lp ; position of open-paren for discriminant, nil if omitted
2738 rp) ; position of close-paren for discriminant, nil if omitted
2739
2740 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2741 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2742
2743 (defun js2-visit-switch-node (n v)
2744 (js2-visit-ast (js2-switch-node-discriminant n) v)
2745 (dolist (c (js2-switch-node-cases n))
2746 (js2-visit-ast c v)))
2747
2748 (defun js2-print-switch-node (n i)
2749 (let ((pad (js2-make-pad i))
2750 (cases (js2-switch-node-cases n)))
2751 (insert pad "switch (")
2752 (js2-print-ast (js2-switch-node-discriminant n) 0)
2753 (insert ") {\n")
2754 (dolist (case cases)
2755 (js2-print-ast case i))
2756 (insert pad "}\n")))
2757
2758 (defstruct (js2-case-node
2759 (:include js2-block-node)
2760 (:constructor nil)
2761 (:constructor make-js2-case-node (&key (type js2-CASE)
2762 (pos js2-ts-cursor)
2763 len kids expr)))
2764 "AST node for a case clause of a switch statement."
2765 expr) ; the case expression (nil for default)
2766
2767 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2768 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2769
2770 (defun js2-visit-case-node (n v)
2771 (js2-visit-ast (js2-case-node-expr n) v)
2772 (js2-visit-block n v))
2773
2774 (defun js2-print-case-node (n i)
2775 (let ((pad (js2-make-pad i))
2776 (expr (js2-case-node-expr n)))
2777 (insert pad)
2778 (if (null expr)
2779 (insert "default:\n")
2780 (insert "case ")
2781 (js2-print-ast expr 0)
2782 (insert ":\n"))
2783 (dolist (kid (js2-case-node-kids n))
2784 (js2-print-ast kid (1+ i)))))
2785
2786 (defstruct (js2-throw-node
2787 (:include js2-node)
2788 (:constructor nil)
2789 (:constructor make-js2-throw-node (&key (type js2-THROW)
2790 (pos js2-ts-cursor)
2791 len expr)))
2792 "AST node for a throw statement."
2793 expr) ; the expression to throw
2794
2795 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2796 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2797
2798 (defun js2-visit-throw-node (n v)
2799 (js2-visit-ast (js2-throw-node-expr n) v))
2800
2801 (defun js2-print-throw-node (n i)
2802 (insert (js2-make-pad i) "throw ")
2803 (js2-print-ast (js2-throw-node-expr n) 0)
2804 (insert ";\n"))
2805
2806 (defstruct (js2-with-node
2807 (:include js2-node)
2808 (:constructor nil)
2809 (:constructor make-js2-with-node (&key (type js2-WITH)
2810 (pos js2-ts-cursor)
2811 len object
2812 body lp rp)))
2813 "AST node for a with-statement."
2814 object
2815 body
2816 lp ; buffer position of left-paren around object, nil if omitted
2817 rp) ; buffer position of right-paren around object, nil if omitted
2818
2819 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2820 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2821
2822 (defun js2-visit-with-node (n v)
2823 (js2-visit-ast (js2-with-node-object n) v)
2824 (js2-visit-ast (js2-with-node-body n) v))
2825
2826 (defun js2-print-with-node (n i)
2827 (let ((pad (js2-make-pad i)))
2828 (insert pad "with (")
2829 (js2-print-ast (js2-with-node-object n) 0)
2830 (insert ") {\n")
2831 (js2-print-body (js2-with-node-body n) (1+ i))
2832 (insert pad "}\n")))
2833
2834 (defstruct (js2-label-node
2835 (:include js2-node)
2836 (:constructor nil)
2837 (:constructor make-js2-label-node (&key (type js2-LABEL)
2838 (pos js2-ts-cursor)
2839 len name)))
2840 "AST node for a statement label or case label."
2841 name ; a string
2842 loop) ; for validating and code-generating continue-to-label
2843
2844 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2845 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2846
2847 (defun js2-print-label (n i)
2848 (insert (js2-make-pad i)
2849 (js2-label-node-name n)
2850 ":\n"))
2851
2852 (defstruct (js2-labeled-stmt-node
2853 (:include js2-node)
2854 (:constructor nil)
2855 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2856 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2857 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2858 (pos js2-ts-cursor)
2859 len labels stmt)))
2860 "AST node for a statement with one or more labels.
2861 Multiple labels for a statement are collapsed into the labels field."
2862 labels ; Lisp list of `js2-label-node'
2863 stmt) ; the statement these labels are for
2864
2865 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2866 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2867
2868 (defun js2-get-label-by-name (lbl-stmt name)
2869 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2870 Returns nil if no such label is in the list."
2871 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2872 result)
2873 (while (and label-list (not result))
2874 (if (string= (js2-label-node-name (car label-list)) name)
2875 (setq result (car label-list))
2876 (setq label-list (cdr label-list))))
2877 result))
2878
2879 (defun js2-visit-labeled-stmt (n v)
2880 (dolist (label (js2-labeled-stmt-node-labels n))
2881 (js2-visit-ast label v))
2882 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2883
2884 (defun js2-print-labeled-stmt (n i)
2885 (dolist (label (js2-labeled-stmt-node-labels n))
2886 (js2-print-ast label i))
2887 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
2888
2889 (defun js2-labeled-stmt-node-contains (node label)
2890 "Return t if NODE contains LABEL in its label set.
2891 NODE is a `js2-labels-node'. LABEL is an identifier."
2892 (loop for nl in (js2-labeled-stmt-node-labels node)
2893 if (string= label (js2-label-node-name nl))
2894 return t
2895 finally return nil))
2896
2897 (defsubst js2-labeled-stmt-node-add-label (node label)
2898 "Add a `js2-label-node' to the label set for this statement."
2899 (setf (js2-labeled-stmt-node-labels node)
2900 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2901
2902 (defstruct (js2-jump-node
2903 (:include js2-node)
2904 (:constructor nil))
2905 "Abstract supertype of break and continue nodes."
2906 label ; `js2-name-node' for location of label identifier, if present
2907 target) ; target js2-labels-node or loop/switch statement
2908
2909 (defun js2-visit-jump-node (n v)
2910 ;; We don't visit the target, since it's a back-link.
2911 (js2-visit-ast (js2-jump-node-label n) v))
2912
2913 (defstruct (js2-break-node
2914 (:include js2-jump-node)
2915 (:constructor nil)
2916 (:constructor make-js2-break-node (&key (type js2-BREAK)
2917 (pos js2-ts-cursor)
2918 len label target)))
2919 "AST node for a break statement.
2920 The label field is a `js2-name-node', possibly nil, for the named label
2921 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2922 is the target of the break - a label node or enclosing loop/switch statement.")
2923
2924 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2925 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2926
2927 (defun js2-print-break-node (n i)
2928 (insert (js2-make-pad i) "break")
2929 (when (js2-break-node-label n)
2930 (insert " ")
2931 (js2-print-ast (js2-break-node-label n) 0))
2932 (insert ";\n"))
2933
2934 (defstruct (js2-continue-node
2935 (:include js2-jump-node)
2936 (:constructor nil)
2937 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2938 (pos js2-ts-cursor)
2939 len label target)))
2940 "AST node for a continue statement.
2941 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2942 It is nil if continue specifies no label. The target field is the jump target:
2943 a `js2-label-node' or the innermost enclosing loop.")
2944
2945 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2946 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2947
2948 (defun js2-print-continue-node (n i)
2949 (insert (js2-make-pad i) "continue")
2950 (when (js2-continue-node-label n)
2951 (insert " ")
2952 (js2-print-ast (js2-continue-node-label n) 0))
2953 (insert ";\n"))
2954
2955 (defstruct (js2-function-node
2956 (:include js2-script-node)
2957 (:constructor nil)
2958 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2959 (pos js2-ts-cursor)
2960 len
2961 (ftype 'FUNCTION)
2962 (form 'FUNCTION_STATEMENT)
2963 (name "")
2964 params rest-p
2965 body
2966 generator-type
2967 lp rp)))
2968 "AST node for a function declaration.
2969 The `params' field is a Lisp list of nodes. Each node is either a simple
2970 `js2-name-node', or if it's a destructuring-assignment parameter, a
2971 `js2-array-node' or `js2-object-node'."
2972 ftype ; FUNCTION, GETTER or SETTER
2973 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
2974 name ; function name (a `js2-name-node', or nil if anonymous)
2975 params ; a Lisp list of destructuring forms or simple name nodes
2976 rest-p ; if t, the last parameter is rest parameter
2977 body ; a `js2-block-node' or expression node (1.8 only)
2978 lp ; position of arg-list open-paren, or nil if omitted
2979 rp ; position of arg-list close-paren, or nil if omitted
2980 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2981 needs-activation ; t if we need an activation object for this frame
2982 generator-type ; STAR, LEGACY, COMPREHENSION or nil
2983 member-expr) ; nonstandard Ecma extension from Rhino
2984
2985 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2986 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2987
2988 (defun js2-visit-function-node (n v)
2989 (js2-visit-ast (js2-function-node-name n) v)
2990 (dolist (p (js2-function-node-params n))
2991 (js2-visit-ast p v))
2992 (js2-visit-ast (js2-function-node-body n) v))
2993
2994 (defun js2-print-function-node (n i)
2995 (let* ((pad (js2-make-pad i))
2996 (getter (js2-node-get-prop n 'GETTER_SETTER))
2997 (name (or (js2-function-node-name n)
2998 (js2-function-node-member-expr n)))
2999 (params (js2-function-node-params n))
3000 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3001 (rest-p (js2-function-node-rest-p n))
3002 (body (js2-function-node-body n))
3003 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3004 (unless (or getter arrow)
3005 (insert pad "function")
3006 (when (eq (js2-function-node-generator-type n) 'STAR)
3007 (insert "*")))
3008 (when name
3009 (insert " ")
3010 (js2-print-ast name 0))
3011 (insert "(")
3012 (loop with len = (length params)
3013 for param in params
3014 for count from 1
3015 do
3016 (when (and rest-p (= count len))
3017 (insert "..."))
3018 (js2-print-ast param 0)
3019 (when (< count len)
3020 (insert ", ")))
3021 (insert ") ")
3022 (when arrow
3023 (insert "=> "))
3024 (insert "{")
3025 ;; TODO: fix this to be smarter about indenting, etc.
3026 (unless expr
3027 (insert "\n"))
3028 (if (js2-block-node-p body)
3029 (js2-print-body body (1+ i))
3030 (js2-print-ast body 0))
3031 (insert pad "}")
3032 (unless expr
3033 (insert "\n"))))
3034
3035 (defun js2-function-name (node)
3036 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3037 (and (js2-function-node-name node)
3038 (js2-name-node-name (js2-function-node-name node))))
3039
3040 ;; Having this be an expression node makes it more flexible.
3041 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3042 ;; that work better if you assume it's an expression. Whenever we have
3043 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3044 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3045 (defstruct (js2-var-decl-node
3046 (:include js2-node)
3047 (:constructor nil)
3048 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3049 (pos (js2-current-token-beg))
3050 len kids
3051 decl-type)))
3052 "AST node for a variable declaration list (VAR, CONST or LET).
3053 The node bounds differ depending on the declaration type. For VAR or
3054 CONST declarations, the bounds include the var/const keyword. For LET
3055 declarations, the node begins at the position of the first child."
3056 kids ; a Lisp list of `js2-var-init-node' structs.
3057 decl-type) ; js2-VAR, js2-CONST or js2-LET
3058
3059 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3060 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3061
3062 (defun js2-visit-var-decl (n v)
3063 (dolist (kid (js2-var-decl-node-kids n))
3064 (js2-visit-ast kid v)))
3065
3066 (defun js2-print-var-decl (n i)
3067 (let ((pad (js2-make-pad i))
3068 (tt (js2-var-decl-node-decl-type n)))
3069 (insert pad)
3070 (insert (cond
3071 ((= tt js2-VAR) "var ")
3072 ((= tt js2-LET) "let ")
3073 ((= tt js2-CONST) "const ")
3074 (t
3075 (error "malformed var-decl node"))))
3076 (loop with kids = (js2-var-decl-node-kids n)
3077 with len = (length kids)
3078 for kid in kids
3079 for count from 1
3080 do
3081 (js2-print-ast kid 0)
3082 (if (< count len)
3083 (insert ", ")))))
3084
3085 (defstruct (js2-var-init-node
3086 (:include js2-node)
3087 (:constructor nil)
3088 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3089 (pos js2-ts-cursor)
3090 len target
3091 initializer)))
3092 "AST node for a variable declaration.
3093 The type field will be js2-CONST for a const decl."
3094 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3095 initializer) ; initializer expression, a `js2-node'
3096
3097 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3098 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3099
3100 (defun js2-visit-var-init-node (n v)
3101 (js2-visit-ast (js2-var-init-node-target n) v)
3102 (js2-visit-ast (js2-var-init-node-initializer n) v))
3103
3104 (defun js2-print-var-init-node (n i)
3105 (let ((pad (js2-make-pad i))
3106 (name (js2-var-init-node-target n))
3107 (init (js2-var-init-node-initializer n)))
3108 (insert pad)
3109 (js2-print-ast name 0)
3110 (when init
3111 (insert " = ")
3112 (js2-print-ast init 0))))
3113
3114 (defstruct (js2-cond-node
3115 (:include js2-node)
3116 (:constructor nil)
3117 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3118 (pos js2-ts-cursor)
3119 len
3120 test-expr
3121 true-expr
3122 false-expr
3123 q-pos c-pos)))
3124 "AST node for the ternary operator"
3125 test-expr
3126 true-expr
3127 false-expr
3128 q-pos ; buffer position of ?
3129 c-pos) ; buffer position of :
3130
3131 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3132 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3133
3134 (defun js2-visit-cond-node (n v)
3135 (js2-visit-ast (js2-cond-node-test-expr n) v)
3136 (js2-visit-ast (js2-cond-node-true-expr n) v)
3137 (js2-visit-ast (js2-cond-node-false-expr n) v))
3138
3139 (defun js2-print-cond-node (n i)
3140 (let ((pad (js2-make-pad i)))
3141 (insert pad)
3142 (js2-print-ast (js2-cond-node-test-expr n) 0)
3143 (insert " ? ")
3144 (js2-print-ast (js2-cond-node-true-expr n) 0)
3145 (insert " : ")
3146 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3147
3148 (defstruct (js2-infix-node
3149 (:include js2-node)
3150 (:constructor nil)
3151 (:constructor make-js2-infix-node (&key type
3152 (pos js2-ts-cursor)
3153 len op-pos
3154 left right)))
3155 "Represents infix expressions.
3156 Includes assignment ops like `|=', and the comma operator.
3157 The type field inherited from `js2-node' holds the operator."
3158 op-pos ; buffer position where operator begins
3159 left ; any `js2-node'
3160 right) ; any `js2-node'
3161
3162 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3163 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3164
3165 (defun js2-visit-infix-node (n v)
3166 (js2-visit-ast (js2-infix-node-left n) v)
3167 (js2-visit-ast (js2-infix-node-right n) v))
3168
3169 (defconst js2-operator-tokens
3170 (let ((table (make-hash-table :test 'eq))
3171 (tokens
3172 (list (cons js2-IN "in")
3173 (cons js2-TYPEOF "typeof")
3174 (cons js2-INSTANCEOF "instanceof")
3175 (cons js2-DELPROP "delete")
3176 (cons js2-COMMA ",")
3177 (cons js2-COLON ":")
3178 (cons js2-OR "||")
3179 (cons js2-AND "&&")
3180 (cons js2-INC "++")
3181 (cons js2-DEC "--")
3182 (cons js2-BITOR "|")
3183 (cons js2-BITXOR "^")
3184 (cons js2-BITAND "&")
3185 (cons js2-EQ "==")
3186 (cons js2-NE "!=")
3187 (cons js2-LT "<")
3188 (cons js2-LE "<=")
3189 (cons js2-GT ">")
3190 (cons js2-GE ">=")
3191 (cons js2-LSH "<<")
3192 (cons js2-RSH ">>")
3193 (cons js2-URSH ">>>")
3194 (cons js2-ADD "+") ; infix plus
3195 (cons js2-SUB "-") ; infix minus
3196 (cons js2-MUL "*")
3197 (cons js2-DIV "/")
3198 (cons js2-MOD "%")
3199 (cons js2-NOT "!")
3200 (cons js2-BITNOT "~")
3201 (cons js2-POS "+") ; unary plus
3202 (cons js2-NEG "-") ; unary minus
3203 (cons js2-TRIPLEDOT "...")
3204 (cons js2-SHEQ "===") ; shallow equality
3205 (cons js2-SHNE "!==") ; shallow inequality
3206 (cons js2-ASSIGN "=")
3207 (cons js2-ASSIGN_BITOR "|=")
3208 (cons js2-ASSIGN_BITXOR "^=")
3209 (cons js2-ASSIGN_BITAND "&=")
3210 (cons js2-ASSIGN_LSH "<<=")
3211 (cons js2-ASSIGN_RSH ">>=")
3212 (cons js2-ASSIGN_URSH ">>>=")
3213 (cons js2-ASSIGN_ADD "+=")
3214 (cons js2-ASSIGN_SUB "-=")
3215 (cons js2-ASSIGN_MUL "*=")
3216 (cons js2-ASSIGN_DIV "/=")
3217 (cons js2-ASSIGN_MOD "%="))))
3218 (loop for (k . v) in tokens do
3219 (puthash k v table))
3220 table))
3221
3222 (defun js2-print-infix-node (n i)
3223 (let* ((tt (js2-node-type n))
3224 (op (gethash tt js2-operator-tokens)))
3225 (unless op
3226 (error "unrecognized infix operator %s" (js2-node-type n)))
3227 (insert (js2-make-pad i))
3228 (js2-print-ast (js2-infix-node-left n) 0)
3229 (unless (= tt js2-COMMA)
3230 (insert " "))
3231 (insert op)
3232 (insert " ")
3233 (js2-print-ast (js2-infix-node-right n) 0)))
3234
3235 (defstruct (js2-assign-node
3236 (:include js2-infix-node)
3237 (:constructor nil)
3238 (:constructor make-js2-assign-node (&key type
3239 (pos js2-ts-cursor)
3240 len op-pos
3241 left right)))
3242 "Represents any assignment.
3243 The type field holds the actual assignment operator.")
3244
3245 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3246 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3247
3248 (defstruct (js2-unary-node
3249 (:include js2-node)
3250 (:constructor nil)
3251 (:constructor make-js2-unary-node (&key type ; required
3252 (pos js2-ts-cursor)
3253 len operand)))
3254 "AST node type for unary operator nodes.
3255 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3256 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3257 property is added if the operator follows the operand."
3258 operand) ; a `js2-node' expression
3259
3260 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3261 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3262
3263 (defun js2-visit-unary-node (n v)
3264 (js2-visit-ast (js2-unary-node-operand n) v))
3265
3266 (defun js2-print-unary-node (n i)
3267 (let* ((tt (js2-node-type n))
3268 (op (gethash tt js2-operator-tokens))
3269 (postfix (js2-node-get-prop n 'postfix)))
3270 (unless op
3271 (error "unrecognized unary operator %s" tt))
3272 (insert (js2-make-pad i))
3273 (unless postfix
3274 (insert op))
3275 (if (or (= tt js2-TYPEOF)
3276 (= tt js2-DELPROP))
3277 (insert " "))
3278 (js2-print-ast (js2-unary-node-operand n) 0)
3279 (when postfix
3280 (insert op))))
3281
3282 (defstruct (js2-let-node
3283 (:include js2-scope)
3284 (:constructor nil)
3285 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3286 (pos (js2-current-token-beg))
3287 len vars body
3288 lp rp)))
3289 "AST node for a let expression or a let statement.
3290 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3291 vars ; a `js2-var-decl-node'
3292 body ; a `js2-node' representing the expression or body block
3293 lp
3294 rp)
3295
3296 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3297 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3298
3299 (defun js2-visit-let-node (n v)
3300 (js2-visit-ast (js2-let-node-vars n) v)
3301 (js2-visit-ast (js2-let-node-body n) v))
3302
3303 (defun js2-print-let-node (n i)
3304 (insert (js2-make-pad i) "let (")
3305 (let ((p (point)))
3306 (js2-print-ast (js2-let-node-vars n) 0)
3307 (delete-region p (+ p 4)))
3308 (insert ") ")
3309 (js2-print-ast (js2-let-node-body n) i))
3310
3311 (defstruct (js2-keyword-node
3312 (:include js2-node)
3313 (:constructor nil)
3314 (:constructor make-js2-keyword-node (&key type
3315 (pos (js2-current-token-beg))
3316 (len (- js2-ts-cursor pos)))))
3317 "AST node representing a literal keyword such as `null'.
3318 Used for `null', `this', `true', `false' and `debugger'.
3319 The node type is set to js2-NULL, js2-THIS, etc.")
3320
3321 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3322 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3323
3324 (defun js2-print-keyword-node (n i)
3325 (insert (js2-make-pad i)
3326 (let ((tt (js2-node-type n)))
3327 (cond
3328 ((= tt js2-THIS) "this")
3329 ((= tt js2-NULL) "null")
3330 ((= tt js2-TRUE) "true")
3331 ((= tt js2-FALSE) "false")
3332 ((= tt js2-DEBUGGER) "debugger")
3333 (t (error "Invalid keyword literal type: %d" tt))))))
3334
3335 (defsubst js2-this-node-p (node)
3336 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3337 (eq (js2-node-type node) js2-THIS))
3338
3339 (defstruct (js2-new-node
3340 (:include js2-node)
3341 (:constructor nil)
3342 (:constructor make-js2-new-node (&key (type js2-NEW)
3343 (pos (js2-current-token-beg))
3344 len target
3345 args initializer
3346 lp rp)))
3347 "AST node for new-expression such as new Foo()."
3348 target ; an identifier or reference
3349 args ; a Lisp list of argument nodes
3350 lp ; position of left-paren, nil if omitted
3351 rp ; position of right-paren, nil if omitted
3352 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3353
3354 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3355 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3356
3357 (defun js2-visit-new-node (n v)
3358 (js2-visit-ast (js2-new-node-target n) v)
3359 (dolist (arg (js2-new-node-args n))
3360 (js2-visit-ast arg v))
3361 (js2-visit-ast (js2-new-node-initializer n) v))
3362
3363 (defun js2-print-new-node (n i)
3364 (insert (js2-make-pad i) "new ")
3365 (js2-print-ast (js2-new-node-target n))
3366 (insert "(")
3367 (js2-print-list (js2-new-node-args n))
3368 (insert ")")
3369 (when (js2-new-node-initializer n)
3370 (insert " ")
3371 (js2-print-ast (js2-new-node-initializer n))))
3372
3373 (defstruct (js2-name-node
3374 (:include js2-node)
3375 (:constructor nil)
3376 (:constructor make-js2-name-node (&key (type js2-NAME)
3377 (pos (js2-current-token-beg))
3378 (len (- js2-ts-cursor
3379 (js2-current-token-beg)))
3380 (name (js2-current-token-string)))))
3381 "AST node for a JavaScript identifier"
3382 name ; a string
3383 scope) ; a `js2-scope' (optional, used for codegen)
3384
3385 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3386 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3387
3388 (defun js2-print-name-node (n i)
3389 (insert (js2-make-pad i)
3390 (js2-name-node-name n)))
3391
3392 (defsubst js2-name-node-length (node)
3393 "Return identifier length of NODE, a `js2-name-node'.
3394 Returns 0 if NODE is nil or its identifier field is nil."
3395 (if node
3396 (length (js2-name-node-name node))
3397 0))
3398
3399 (defstruct (js2-number-node
3400 (:include js2-node)
3401 (:constructor nil)
3402 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3403 (pos (js2-current-token-beg))
3404 (len (- js2-ts-cursor
3405 (js2-current-token-beg)))
3406 (value (js2-current-token-string))
3407 (num-value (js2-token-number
3408 (js2-current-token))))))
3409 "AST node for a number literal."
3410 value ; the original string, e.g. "6.02e23"
3411 num-value) ; the parsed number value
3412
3413 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3414 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3415
3416 (defun js2-print-number-node (n i)
3417 (insert (js2-make-pad i)
3418 (number-to-string (js2-number-node-num-value n))))
3419
3420 (defstruct (js2-regexp-node
3421 (:include js2-node)
3422 (:constructor nil)
3423 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3424 (pos (js2-current-token-beg))
3425 (len (- js2-ts-cursor
3426 (js2-current-token-beg)))
3427 value flags)))
3428 "AST node for a regular expression literal."
3429 value ; the regexp string, without // delimiters
3430 flags) ; a string of flags, e.g. `mi'.
3431
3432 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3433 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3434
3435 (defun js2-print-regexp (n i)
3436 (insert (js2-make-pad i)
3437 "/"
3438 (js2-regexp-node-value n)
3439 "/")
3440 (if (js2-regexp-node-flags n)
3441 (insert (js2-regexp-node-flags n))))
3442
3443 (defstruct (js2-string-node
3444 (:include js2-node)
3445 (:constructor nil)
3446 (:constructor make-js2-string-node (&key (type js2-STRING)
3447 (pos (js2-current-token-beg))
3448 (len (- js2-ts-cursor
3449 (js2-current-token-beg)))
3450 (value (js2-current-token-string)))))
3451 "String literal.
3452 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3453 You can tell the quote type by looking at the first character."
3454 value) ; the characters of the string, including the quotes
3455
3456 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3457 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3458
3459 (defun js2-print-string-node (n i)
3460 (insert (js2-make-pad i)
3461 (js2-node-string n)))
3462
3463 (defstruct (js2-array-node
3464 (:include js2-node)
3465 (:constructor nil)
3466 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3467 (pos js2-ts-cursor)
3468 len elems)))
3469 "AST node for an array literal."
3470 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3471
3472 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3473 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3474
3475 (defun js2-visit-array-node (n v)
3476 (dolist (e (js2-array-node-elems n))
3477 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3478
3479 (defun js2-print-array-node (n i)
3480 (insert (js2-make-pad i) "[")
3481 (let ((elems (js2-array-node-elems n)))
3482 (js2-print-list elems)
3483 (when (and elems (null (car (last elems))))
3484 (insert ",")))
3485 (insert "]"))
3486
3487 (defstruct (js2-object-node
3488 (:include js2-node)
3489 (:constructor nil)
3490 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3491 (pos js2-ts-cursor)
3492 len
3493 elems)))
3494 "AST node for an object literal expression.
3495 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3496 The latter represents abbreviation in destructuring expressions."
3497 elems)
3498
3499 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3500 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3501
3502 (defun js2-visit-object-node (n v)
3503 (dolist (e (js2-object-node-elems n))
3504 (js2-visit-ast e v)))
3505
3506 (defun js2-print-object-node (n i)
3507 (insert (js2-make-pad i) "{")
3508 (js2-print-list (js2-object-node-elems n))
3509 (insert "}"))
3510
3511 (defstruct (js2-object-prop-node
3512 (:include js2-infix-node)
3513 (:constructor nil)
3514 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3515 (pos js2-ts-cursor)
3516 len left
3517 right op-pos)))
3518 "AST node for an object literal prop:value entry.
3519 The `left' field is the property: a name node, string node or number node.
3520 The `right' field is a `js2-node' representing the initializer value.")
3521
3522 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3523 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3524
3525 (defun js2-print-object-prop-node (n i)
3526 (let* ((left (js2-object-prop-node-left n))
3527 (computed (not (or (js2-string-node-p left)
3528 (js2-number-node-p left)
3529 (js2-name-node-p left)))))
3530 (insert (js2-make-pad i))
3531 (if computed
3532 (insert "["))
3533 (js2-print-ast left 0)
3534 (if computed
3535 (insert "]"))
3536 (if (not (js2-node-get-prop n 'SHORTHAND))
3537 (progn
3538 (insert ": ")
3539 (js2-print-ast (js2-object-prop-node-right n) 0)))))
3540
3541 (defstruct (js2-getter-setter-node
3542 (:include js2-infix-node)
3543 (:constructor nil)
3544 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3545 (pos js2-ts-cursor)
3546 len left right)))
3547 "AST node for a getter/setter property in an object literal.
3548 The `left' field is the `js2-name-node' naming the getter/setter prop.
3549 The `right' field is always an anonymous `js2-function-node' with a node
3550 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3551
3552 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3553 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3554
3555 (defun js2-print-getter-setter (n i)
3556 (let ((pad (js2-make-pad i))
3557 (left (js2-getter-setter-node-left n))
3558 (right (js2-getter-setter-node-right n)))
3559 (insert pad)
3560 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3561 (js2-print-ast left 0)
3562 (js2-print-ast right 0)))
3563
3564 (defstruct (js2-prop-get-node
3565 (:include js2-infix-node)
3566 (:constructor nil)
3567 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3568 (pos js2-ts-cursor)
3569 len left right)))
3570 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3571
3572 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3573 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3574
3575 (defun js2-visit-prop-get-node (n v)
3576 (js2-visit-ast (js2-prop-get-node-left n) v)
3577 (js2-visit-ast (js2-prop-get-node-right n) v))
3578
3579 (defun js2-print-prop-get-node (n i)
3580 (insert (js2-make-pad i))
3581 (js2-print-ast (js2-prop-get-node-left n) 0)
3582 (insert ".")
3583 (js2-print-ast (js2-prop-get-node-right n) 0))
3584
3585 (defstruct (js2-elem-get-node
3586 (:include js2-node)
3587 (:constructor nil)
3588 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3589 (pos js2-ts-cursor)
3590 len target element
3591 lb rb)))
3592 "AST node for an array index expression such as foo[bar]."
3593 target ; a `js2-node' - the expression preceding the "."
3594 element ; a `js2-node' - the expression in brackets
3595 lb ; position of left-bracket, nil if omitted
3596 rb) ; position of right-bracket, nil if omitted
3597
3598 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3599 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3600
3601 (defun js2-visit-elem-get-node (n v)
3602 (js2-visit-ast (js2-elem-get-node-target n) v)
3603 (js2-visit-ast (js2-elem-get-node-element n) v))
3604
3605 (defun js2-print-elem-get-node (n i)
3606 (insert (js2-make-pad i))
3607 (js2-print-ast (js2-elem-get-node-target n) 0)
3608 (insert "[")
3609 (js2-print-ast (js2-elem-get-node-element n) 0)
3610 (insert "]"))
3611
3612 (defstruct (js2-call-node
3613 (:include js2-node)
3614 (:constructor nil)
3615 (:constructor make-js2-call-node (&key (type js2-CALL)
3616 (pos js2-ts-cursor)
3617 len target args
3618 lp rp)))
3619 "AST node for a JavaScript function call."
3620 target ; a `js2-node' evaluating to the function to call
3621 args ; a Lisp list of `js2-node' arguments
3622 lp ; position of open-paren, or nil if missing
3623 rp) ; position of close-paren, or nil if missing
3624
3625 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3626 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3627
3628 (defun js2-visit-call-node (n v)
3629 (js2-visit-ast (js2-call-node-target n) v)
3630 (dolist (arg (js2-call-node-args n))
3631 (js2-visit-ast arg v)))
3632
3633 (defun js2-print-call-node (n i)
3634 (insert (js2-make-pad i))
3635 (js2-print-ast (js2-call-node-target n) 0)
3636 (insert "(")
3637 (js2-print-list (js2-call-node-args n))
3638 (insert ")"))
3639
3640 (defstruct (js2-yield-node
3641 (:include js2-node)
3642 (:constructor nil)
3643 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3644 (pos js2-ts-cursor)
3645 len value star-p)))
3646 "AST node for yield statement or expression."
3647 star-p ; whether it's yield*
3648 value) ; optional: value to be yielded
3649
3650 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3651 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3652
3653 (defun js2-visit-yield-node (n v)
3654 (js2-visit-ast (js2-yield-node-value n) v))
3655
3656 (defun js2-print-yield-node (n i)
3657 (insert (js2-make-pad i))
3658 (insert "yield")
3659 (when (js2-yield-node-star-p n)
3660 (insert "*"))
3661 (when (js2-yield-node-value n)
3662 (insert " ")
3663 (js2-print-ast (js2-yield-node-value n) 0)))
3664
3665 (defstruct (js2-paren-node
3666 (:include js2-node)
3667 (:constructor nil)
3668 (:constructor make-js2-paren-node (&key (type js2-LP)
3669 (pos js2-ts-cursor)
3670 len expr)))
3671 "AST node for a parenthesized expression.
3672 In particular, used when the parens are syntactically optional,
3673 as opposed to required parens such as those enclosing an if-conditional."
3674 expr) ; `js2-node'
3675
3676 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3677 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3678
3679 (defun js2-visit-paren-node (n v)
3680 (js2-visit-ast (js2-paren-node-expr n) v))
3681
3682 (defun js2-print-paren-node (n i)
3683 (insert (js2-make-pad i))
3684 (insert "(")
3685 (js2-print-ast (js2-paren-node-expr n) 0)
3686 (insert ")"))
3687
3688 (defstruct (js2-comp-node
3689 (:include js2-scope)
3690 (:constructor nil)
3691 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
3692 (pos js2-ts-cursor)
3693 len result
3694 loops filters
3695 form)))
3696 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3697 result ; result expression (just after left-bracket)
3698 loops ; a Lisp list of `js2-comp-loop-node'
3699 filters ; a Lisp list of guard/filter expressions
3700 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
3701 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
3702 )
3703
3704 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
3705 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
3706
3707 (defun js2-visit-comp-node (n v)
3708 (js2-visit-ast (js2-comp-node-result n) v)
3709 (dolist (l (js2-comp-node-loops n))
3710 (js2-visit-ast l v))
3711 (dolist (f (js2-comp-node-filters n))
3712 (js2-visit-ast f v)))
3713
3714 (defun js2-print-comp-node (n i)
3715 (let ((pad (js2-make-pad i))
3716 (result (js2-comp-node-result n))
3717 (loops (js2-comp-node-loops n))
3718 (filters (js2-comp-node-filters n))
3719 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
3720 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
3721 (insert pad (if gen-p "(" "["))
3722 (when legacy-p
3723 (js2-print-ast result 0))
3724 (dolist (l loops)
3725 (when legacy-p
3726 (insert " "))
3727 (js2-print-ast l 0)
3728 (unless legacy-p
3729 (insert " ")))
3730 (dolist (f filters)
3731 (when legacy-p
3732 (insert " "))
3733 (insert "if (")
3734 (js2-print-ast f 0)
3735 (insert ")")
3736 (unless legacy-p
3737 (insert " ")))
3738 (unless legacy-p
3739 (js2-print-ast result 0))
3740 (insert (if gen-p ")" "]"))))
3741
3742 (defstruct (js2-comp-loop-node
3743 (:include js2-for-in-node)
3744 (:constructor nil)
3745 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
3746 (pos js2-ts-cursor)
3747 len iterator
3748 object in-pos
3749 foreach-p
3750 each-pos
3751 forof-p
3752 lp rp)))
3753 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3754
3755 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
3756 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
3757
3758 (defun js2-visit-comp-loop (n v)
3759 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
3760 (js2-visit-ast (js2-comp-loop-node-object n) v))
3761
3762 (defun js2-print-comp-loop (n _i)
3763 (insert "for ")
3764 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
3765 (insert "(")
3766 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
3767 (insert (if (js2-comp-loop-node-forof-p n)
3768 " of " " in "))
3769 (js2-print-ast (js2-comp-loop-node-object n) 0)
3770 (insert ")"))
3771
3772 (defstruct (js2-empty-expr-node
3773 (:include js2-node)
3774 (:constructor nil)
3775 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3776 (pos (js2-current-token-beg))
3777 len)))
3778 "AST node for an empty expression.")
3779
3780 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3781 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3782
3783 (defstruct (js2-xml-node
3784 (:include js2-block-node)
3785 (:constructor nil)
3786 (:constructor make-js2-xml-node (&key (type js2-XML)
3787 (pos (js2-current-token-beg))
3788 len kids)))
3789 "AST node for initial parse of E4X literals.
3790 The kids field is a list of XML fragments, each a `js2-string-node' or
3791 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3792
3793 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3794 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3795
3796 (defun js2-print-xml-node (n i)
3797 (dolist (kid (js2-xml-node-kids n))
3798 (js2-print-ast kid i)))
3799
3800 (defstruct (js2-xml-js-expr-node
3801 (:include js2-xml-node)
3802 (:constructor nil)
3803 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3804 (pos js2-ts-cursor)
3805 len expr)))
3806 "AST node for an embedded JavaScript {expression} in an E4X literal.
3807 The start and end fields correspond to the curly-braces."
3808 expr) ; a `js2-expr-node' of some sort
3809
3810 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3811 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3812
3813 (defun js2-visit-xml-js-expr (n v)
3814 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3815
3816 (defun js2-print-xml-js-expr (n i)
3817 (insert (js2-make-pad i))
3818 (insert "{")
3819 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3820 (insert "}"))
3821
3822 (defstruct (js2-xml-dot-query-node
3823 (:include js2-infix-node)
3824 (:constructor nil)
3825 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3826 (pos js2-ts-cursor)
3827 op-pos len left
3828 right rp)))
3829 "AST node for an E4X foo.(bar) filter expression.
3830 Note that the left-paren is automatically the character immediately
3831 following the dot (.) in the operator. No whitespace is permitted
3832 between the dot and the lp by the scanner."
3833 rp)
3834
3835 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3836 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3837
3838 (defun js2-print-xml-dot-query (n i)
3839 (insert (js2-make-pad i))
3840 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3841 (insert ".(")
3842 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3843 (insert ")"))
3844
3845 (defstruct (js2-xml-ref-node
3846 (:include js2-node)
3847 (:constructor nil)) ; abstract
3848 "Base type for E4X XML attribute-access or property-get expressions.
3849 Such expressions can take a variety of forms. The general syntax has
3850 three parts:
3851
3852 - (optional) an @ (specifying an attribute access)
3853 - (optional) a namespace (a `js2-name-node') and double-colon
3854 - (required) either a `js2-name-node' or a bracketed [expression]
3855
3856 The property-name expressions (examples: ns::name, @name) are
3857 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3858 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3859
3860 This node type (or more specifically, its subclasses) will sometimes
3861 be the right-hand child of a `js2-prop-get-node' or a
3862 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3863 The `js2-xml-ref-node' may also be a standalone primary expression with
3864 no explicit target, which is valid in certain expression contexts such as
3865
3866 company..employee.(@id < 100)
3867
3868 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3869 expression whose parent is a `js2-xml-dot-query-node'."
3870 namespace
3871 at-pos
3872 colon-pos)
3873
3874 (defsubst js2-xml-ref-node-attr-access-p (node)
3875 "Return non-nil if this expression began with an @-token."
3876 (and (numberp (js2-xml-ref-node-at-pos node))
3877 (plusp (js2-xml-ref-node-at-pos node))))
3878
3879 (defstruct (js2-xml-prop-ref-node
3880 (:include js2-xml-ref-node)
3881 (:constructor nil)
3882 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3883 (pos (js2-current-token-beg))
3884 len propname
3885 namespace at-pos
3886 colon-pos)))
3887 "AST node for an E4X XML [expr] property-ref expression.
3888 The JavaScript syntax is an optional @, an optional ns::, and a name.
3889
3890 [ '@' ] [ name '::' ] name
3891
3892 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3893 @ns::*, @*::attr, @*::*, and @*.
3894
3895 The node starts at the @ token, if present. Otherwise it starts at the
3896 namespace name. The node bounds extend through the closing right-bracket,
3897 or if it is missing due to a syntax error, through the end of the index
3898 expression."
3899 propname)
3900
3901 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3902 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3903
3904 (defun js2-visit-xml-prop-ref-node (n v)
3905 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3906 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3907
3908 (defun js2-print-xml-prop-ref-node (n i)
3909 (insert (js2-make-pad i))
3910 (if (js2-xml-ref-node-attr-access-p n)
3911 (insert "@"))
3912 (when (js2-xml-prop-ref-node-namespace n)
3913 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3914 (insert "::"))
3915 (if (js2-xml-prop-ref-node-propname n)
3916 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3917
3918 (defstruct (js2-xml-elem-ref-node
3919 (:include js2-xml-ref-node)
3920 (:constructor nil)
3921 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3922 (pos (js2-current-token-beg))
3923 len expr lb rb
3924 namespace at-pos
3925 colon-pos)))
3926 "AST node for an E4X XML [expr] member-ref expression.
3927 Syntax:
3928
3929 [ '@' ] [ name '::' ] '[' expr ']'
3930
3931 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3932
3933 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3934 is not a legal E4X XML element-ref expression, since it's already used
3935 for standard JavaScript element-get array indexing. Hence, a
3936 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3937 non-nil namespace node, or both.
3938
3939 The node starts at the @ token, if present. Otherwise it starts
3940 at the namespace name. The node bounds extend through the closing
3941 right-bracket, or if it is missing due to a syntax error, through the
3942 end of the index expression."
3943 expr ; the bracketed index expression
3944 lb
3945 rb)
3946
3947 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3948 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3949
3950 (defun js2-visit-xml-elem-ref-node (n v)
3951 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3952 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3953
3954 (defun js2-print-xml-elem-ref-node (n i)
3955 (insert (js2-make-pad i))
3956 (if (js2-xml-ref-node-attr-access-p n)
3957 (insert "@"))
3958 (when (js2-xml-elem-ref-node-namespace n)
3959 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3960 (insert "::"))
3961 (insert "[")
3962 (if (js2-xml-elem-ref-node-expr n)
3963 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3964 (insert "]"))
3965
3966 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3967
3968 (defstruct (js2-xml-start-tag-node
3969 (:include js2-xml-node)
3970 (:constructor nil)
3971 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3972 (pos js2-ts-cursor)
3973 len name attrs kids
3974 empty-p)))
3975 "AST node for an XML start-tag. Not currently used.
3976 The `kids' field is a Lisp list of child content nodes."
3977 name ; a `js2-xml-name-node'
3978 attrs ; a Lisp list of `js2-xml-attr-node'
3979 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3980
3981 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3982 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3983
3984 (defun js2-visit-xml-start-tag (n v)
3985 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3986 (dolist (attr (js2-xml-start-tag-node-attrs n))
3987 (js2-visit-ast attr v))
3988 (js2-visit-block n v))
3989
3990 (defun js2-print-xml-start-tag (n i)
3991 (insert (js2-make-pad i) "<")
3992 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3993 (when (js2-xml-start-tag-node-attrs n)
3994 (insert " ")
3995 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3996 (insert ">"))
3997
3998 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3999 ;; and add the end-tag to the kids list of the parent as well.
4000 (defstruct (js2-xml-end-tag-node
4001 (:include js2-xml-node)
4002 (:constructor nil)
4003 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4004 (pos js2-ts-cursor)
4005 len name)))
4006 "AST node for an XML end-tag. Not currently used."
4007 name) ; a `js2-xml-name-node'
4008
4009 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4010 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4011
4012 (defun js2-visit-xml-end-tag (n v)
4013 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4014
4015 (defun js2-print-xml-end-tag (n i)
4016 (insert (js2-make-pad i))
4017 (insert "</")
4018 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4019 (insert ">"))
4020
4021 (defstruct (js2-xml-name-node
4022 (:include js2-xml-node)
4023 (:constructor nil)
4024 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4025 (pos js2-ts-cursor)
4026 len namespace kids)))
4027 "AST node for an E4X XML name. Not currently used.
4028 Any XML name can be qualified with a namespace, hence the namespace field.
4029 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4030 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4031 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4032 namespace) ; a `js2-string-node'
4033
4034 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4035 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4036
4037 (defun js2-visit-xml-name-node (n v)
4038 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4039
4040 (defun js2-print-xml-name-node (n i)
4041 (insert (js2-make-pad i))
4042 (when (js2-xml-name-node-namespace n)
4043 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4044 (insert "::"))
4045 (dolist (kid (js2-xml-name-node-kids n))
4046 (js2-print-ast kid 0)))
4047
4048 (defstruct (js2-xml-pi-node
4049 (:include js2-xml-node)
4050 (:constructor nil)
4051 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4052 (pos js2-ts-cursor)
4053 len name attrs)))
4054 "AST node for an E4X XML processing instruction. Not currently used."
4055 name ; a `js2-xml-name-node'
4056 attrs) ; a list of `js2-xml-attr-node'
4057
4058 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4059 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4060
4061 (defun js2-visit-xml-pi-node (n v)
4062 (js2-visit-ast (js2-xml-pi-node-name n) v)
4063 (dolist (attr (js2-xml-pi-node-attrs n))
4064 (js2-visit-ast attr v)))
4065
4066 (defun js2-print-xml-pi-node (n i)
4067 (insert (js2-make-pad i) "<?")
4068 (js2-print-ast (js2-xml-pi-node-name n))
4069 (when (js2-xml-pi-node-attrs n)
4070 (insert " ")
4071 (js2-print-list (js2-xml-pi-node-attrs n)))
4072 (insert "?>"))
4073
4074 (defstruct (js2-xml-cdata-node
4075 (:include js2-xml-node)
4076 (:constructor nil)
4077 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4078 (pos js2-ts-cursor)
4079 len content)))
4080 "AST node for a CDATA escape section. Not currently used."
4081 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4082
4083 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4084 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4085
4086 (defun js2-visit-xml-cdata-node (n v)
4087 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4088
4089 (defun js2-print-xml-cdata-node (n i)
4090 (insert (js2-make-pad i))
4091 (js2-print-ast (js2-xml-cdata-node-content n)))
4092
4093 (defstruct (js2-xml-attr-node
4094 (:include js2-xml-node)
4095 (:constructor nil)
4096 (:constructor make-js2-attr-node (&key (type js2-XML)
4097 (pos js2-ts-cursor)
4098 len name value
4099 eq-pos quote-type)))
4100 "AST node representing a foo='bar' XML attribute value. Not yet used."
4101 name ; a `js2-xml-name-node'
4102 value ; a `js2-xml-name-node'
4103 eq-pos ; buffer position of "=" sign
4104 quote-type) ; 'single or 'double
4105
4106 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4107 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4108
4109 (defun js2-visit-xml-attr-node (n v)
4110 (js2-visit-ast (js2-xml-attr-node-name n) v)
4111 (js2-visit-ast (js2-xml-attr-node-value n) v))
4112
4113 (defun js2-print-xml-attr-node (n i)
4114 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4115 "'"
4116 "\"")))
4117 (insert (js2-make-pad i))
4118 (js2-print-ast (js2-xml-attr-node-name n) 0)
4119 (insert "=" quote)
4120 (js2-print-ast (js2-xml-attr-node-value n) 0)
4121 (insert quote)))
4122
4123 (defstruct (js2-xml-text-node
4124 (:include js2-xml-node)
4125 (:constructor nil)
4126 (:constructor make-js2-text-node (&key (type js2-XML)
4127 (pos js2-ts-cursor)
4128 len content)))
4129 "AST node for an E4X XML text node. Not currently used."
4130 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4131
4132 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4133 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4134
4135 (defun js2-visit-xml-text-node (n v)
4136 (js2-visit-ast (js2-xml-text-node-content n) v))
4137
4138 (defun js2-print-xml-text-node (n i)
4139 (insert (js2-make-pad i))
4140 (dolist (kid (js2-xml-text-node-content n))
4141 (js2-print-ast kid)))
4142
4143 (defstruct (js2-xml-comment-node
4144 (:include js2-xml-node)
4145 (:constructor nil)
4146 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4147 (pos js2-ts-cursor)
4148 len)))
4149 "AST node for E4X XML comment. Not currently used.")
4150
4151 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4152 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4153
4154 (defun js2-print-xml-comment (n i)
4155 (insert (js2-make-pad i)
4156 (js2-node-string n)))
4157
4158 ;;; Node utilities
4159
4160 (defsubst js2-node-line (n)
4161 "Fetch the source line number at the start of node N.
4162 This is O(n) in the length of the source buffer; use prudently."
4163 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4164
4165 (defsubst js2-block-node-kid (n i)
4166 "Return child I of node N, or nil if there aren't that many."
4167 (nth i (js2-block-node-kids n)))
4168
4169 (defsubst js2-block-node-first (n)
4170 "Return first child of block node N, or nil if there is none."
4171 (first (js2-block-node-kids n)))
4172
4173 (defun js2-node-root (n)
4174 "Return the root of the AST containing N.
4175 If N has no parent pointer, returns N."
4176 (let ((parent (js2-node-parent n)))
4177 (if parent
4178 (js2-node-root parent)
4179 n)))
4180
4181 (defsubst js2-node-short-name (n)
4182 "Return the short name of node N as a string, e.g. `js2-if-node'."
4183 (substring (symbol-name (aref n 0))
4184 (length "cl-struct-")))
4185
4186 (defun js2-node-child-list (node)
4187 "Return the child list for NODE, a Lisp list of nodes.
4188 Works for block nodes, array nodes, obj literals, funarg lists,
4189 var decls and try nodes (for catch clauses). Note that you should call
4190 `js2-block-node-kids' on the function body for the body statements.
4191 Returns nil for zero-length child lists or unsupported nodes."
4192 (cond
4193 ((js2-function-node-p node)
4194 (js2-function-node-params node))
4195 ((js2-block-node-p node)
4196 (js2-block-node-kids node))
4197 ((js2-try-node-p node)
4198 (js2-try-node-catch-clauses node))
4199 ((js2-array-node-p node)
4200 (js2-array-node-elems node))
4201 ((js2-object-node-p node)
4202 (js2-object-node-elems node))
4203 ((js2-call-node-p node)
4204 (js2-call-node-args node))
4205 ((js2-new-node-p node)
4206 (js2-new-node-args node))
4207 ((js2-var-decl-node-p node)
4208 (js2-var-decl-node-kids node))
4209 (t
4210 nil)))
4211
4212 (defun js2-node-set-child-list (node kids)
4213 "Set the child list for NODE to KIDS."
4214 (cond
4215 ((js2-function-node-p node)
4216 (setf (js2-function-node-params node) kids))
4217 ((js2-block-node-p node)
4218 (setf (js2-block-node-kids node) kids))
4219 ((js2-try-node-p node)
4220 (setf (js2-try-node-catch-clauses node) kids))
4221 ((js2-array-node-p node)
4222 (setf (js2-array-node-elems node) kids))
4223 ((js2-object-node-p node)
4224 (setf (js2-object-node-elems node) kids))
4225 ((js2-call-node-p node)
4226 (setf (js2-call-node-args node) kids))
4227 ((js2-new-node-p node)
4228 (setf (js2-new-node-args node) kids))
4229 ((js2-var-decl-node-p node)
4230 (setf (js2-var-decl-node-kids node) kids))
4231 (t
4232 (error "Unsupported node type: %s" (js2-node-short-name node))))
4233 kids)
4234
4235 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4236 (defconst js2-paren-expr-nodes
4237 '(cl-struct-js2-comp-loop-node
4238 cl-struct-js2-comp-node
4239 cl-struct-js2-call-node
4240 cl-struct-js2-catch-node
4241 cl-struct-js2-do-node
4242 cl-struct-js2-elem-get-node
4243 cl-struct-js2-for-in-node
4244 cl-struct-js2-for-node
4245 cl-struct-js2-function-node
4246 cl-struct-js2-if-node
4247 cl-struct-js2-let-node
4248 cl-struct-js2-new-node
4249 cl-struct-js2-paren-node
4250 cl-struct-js2-switch-node
4251 cl-struct-js2-while-node
4252 cl-struct-js2-with-node
4253 cl-struct-js2-xml-dot-query-node)
4254 "Node types that can have a parenthesized child expression.
4255 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4256
4257 (defsubst js2-paren-expr-node-p (node)
4258 "Return t for nodes that typically have a parenthesized child expression.
4259 Useful for computing the indentation anchors for arg-lists and conditions.
4260 Note that it may return a false positive, for instance when NODE is
4261 a `js2-new-node' and there are no arguments or parentheses."
4262 (memq (aref node 0) js2-paren-expr-nodes))
4263
4264 ;; Fake polymorphism... yech.
4265 (defun js2-node-lp (node)
4266 "Return relative left-paren position for NODE, if applicable.
4267 For `js2-elem-get-node' structs, returns left-bracket position.
4268 Note that the position may be nil in the case of a parse error."
4269 (cond
4270 ((js2-elem-get-node-p node)
4271 (js2-elem-get-node-lb node))
4272 ((js2-loop-node-p node)
4273 (js2-loop-node-lp node))
4274 ((js2-function-node-p node)
4275 (js2-function-node-lp node))
4276 ((js2-if-node-p node)
4277 (js2-if-node-lp node))
4278 ((js2-new-node-p node)
4279 (js2-new-node-lp node))
4280 ((js2-call-node-p node)
4281 (js2-call-node-lp node))
4282 ((js2-paren-node-p node)
4283 0)
4284 ((js2-switch-node-p node)
4285 (js2-switch-node-lp node))
4286 ((js2-catch-node-p node)
4287 (js2-catch-node-lp node))
4288 ((js2-let-node-p node)
4289 (js2-let-node-lp node))
4290 ((js2-comp-node-p node)
4291 0)
4292 ((js2-with-node-p node)
4293 (js2-with-node-lp node))
4294 ((js2-xml-dot-query-node-p node)
4295 (1+ (js2-infix-node-op-pos node)))
4296 (t
4297 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4298
4299 ;; Fake polymorphism... blech.
4300 (defun js2-node-rp (node)
4301 "Return relative right-paren position for NODE, if applicable.
4302 For `js2-elem-get-node' structs, returns right-bracket position.
4303 Note that the position may be nil in the case of a parse error."
4304 (cond
4305 ((js2-elem-get-node-p node)
4306 (js2-elem-get-node-rb node))
4307 ((js2-loop-node-p node)
4308 (js2-loop-node-rp node))
4309 ((js2-function-node-p node)
4310 (js2-function-node-rp node))
4311 ((js2-if-node-p node)
4312 (js2-if-node-rp node))
4313 ((js2-new-node-p node)
4314 (js2-new-node-rp node))
4315 ((js2-call-node-p node)
4316 (js2-call-node-rp node))
4317 ((js2-paren-node-p node)
4318 (1- (js2-node-len node)))
4319 ((js2-switch-node-p node)
4320 (js2-switch-node-rp node))
4321 ((js2-catch-node-p node)
4322 (js2-catch-node-rp node))
4323 ((js2-let-node-p node)
4324 (js2-let-node-rp node))
4325 ((js2-comp-node-p node)
4326 (1- (js2-node-len node)))
4327 ((js2-with-node-p node)
4328 (js2-with-node-rp node))
4329 ((js2-xml-dot-query-node-p node)
4330 (1+ (js2-xml-dot-query-node-rp node)))
4331 (t
4332 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4333
4334 (defsubst js2-node-first-child (node)
4335 "Return the first element of `js2-node-child-list' for NODE."
4336 (car (js2-node-child-list node)))
4337
4338 (defsubst js2-node-last-child (node)
4339 "Return the last element of `js2-node-last-child' for NODE."
4340 (car (last (js2-node-child-list node))))
4341
4342 (defun js2-node-prev-sibling (node)
4343 "Return the previous statement in parent.
4344 Works for parents supported by `js2-node-child-list'.
4345 Returns nil if NODE is not in the parent, or PARENT is
4346 not a supported node, or if NODE is the first child."
4347 (let* ((p (js2-node-parent node))
4348 (kids (js2-node-child-list p))
4349 (sib (car kids)))
4350 (while (and kids
4351 (not (eq node (cadr kids))))
4352 (setq kids (cdr kids)
4353 sib (car kids)))
4354 sib))
4355
4356 (defun js2-node-next-sibling (node)
4357 "Return the next statement in parent block.
4358 Returns nil if NODE is not in the block, or PARENT is not
4359 a block node, or if NODE is the last statement."
4360 (let* ((p (js2-node-parent node))
4361 (kids (js2-node-child-list p)))
4362 (while (and kids
4363 (not (eq node (car kids))))
4364 (setq kids (cdr kids)))
4365 (cadr kids)))
4366
4367 (defun js2-node-find-child-before (pos parent &optional after)
4368 "Find the last child that starts before POS in parent.
4369 If AFTER is non-nil, returns first child starting after POS.
4370 POS is an absolute buffer position. PARENT is any node
4371 supported by `js2-node-child-list'.
4372 Returns nil if no applicable child is found."
4373 (let ((kids (if (js2-function-node-p parent)
4374 (js2-block-node-kids (js2-function-node-body parent))
4375 (js2-node-child-list parent)))
4376 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4377 (js2-function-node-body parent)
4378 parent)))
4379 kid result fn
4380 (continue t))
4381 (setq fn (if after '>= '<))
4382 (while (and kids continue)
4383 (setq kid (car kids))
4384 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4385 (setq result kid
4386 continue (not after))
4387 (setq continue after))
4388 (setq kids (cdr kids)))
4389 result))
4390
4391 (defun js2-node-find-child-after (pos parent)
4392 "Find first child that starts after POS in parent.
4393 POS is an absolute buffer position. PARENT is any node
4394 supported by `js2-node-child-list'.
4395 Returns nil if no applicable child is found."
4396 (js2-node-find-child-before pos parent 'after))
4397
4398 (defun js2-node-replace-child (pos parent new-node)
4399 "Replace node at index POS in PARENT with NEW-NODE.
4400 Only works for parents supported by `js2-node-child-list'."
4401 (let ((kids (js2-node-child-list parent))
4402 (i 0))
4403 (while (< i pos)
4404 (setq kids (cdr kids)
4405 i (1+ i)))
4406 (setcar kids new-node)
4407 (js2-node-add-children parent new-node)))
4408
4409 (defun js2-node-buffer (n)
4410 "Return the buffer associated with AST N.
4411 Returns nil if the buffer is not set as a property on the root
4412 node, or if parent links were not recorded during parsing."
4413 (let ((root (js2-node-root n)))
4414 (and root
4415 (js2-ast-root-p root)
4416 (js2-ast-root-buffer root))))
4417
4418 (defun js2-block-node-push (n kid)
4419 "Push js2-node KID onto the end of js2-block-node N's child list.
4420 KID is always added to the -end- of the kids list.
4421 Function also calls `js2-node-add-children' to add the parent link."
4422 (let ((kids (js2-node-child-list n)))
4423 (if kids
4424 (setcdr kids (nconc (cdr kids) (list kid)))
4425 (js2-node-set-child-list n (list kid)))
4426 (js2-node-add-children n kid)))
4427
4428 (defun js2-node-string (node)
4429 (with-current-buffer (or (js2-node-buffer node)
4430 (error "No buffer available for node %s" node))
4431 (let ((pos (js2-node-abs-pos node)))
4432 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4433
4434 ;; Container for storing the node we're looking for in a traversal.
4435 (js2-deflocal js2-discovered-node nil)
4436
4437 ;; Keep track of absolute node position during traversals.
4438 (js2-deflocal js2-visitor-offset nil)
4439
4440 (js2-deflocal js2-node-search-point nil)
4441
4442 (when js2-mode-dev-mode-p
4443 (defun js2-find-node-at-point ()
4444 (interactive)
4445 (let ((node (js2-node-at-point)))
4446 (message "%s" (or node "No node found at point"))))
4447 (defun js2-node-name-at-point ()
4448 (interactive)
4449 (let ((node (js2-node-at-point)))
4450 (message "%s" (if node
4451 (js2-node-short-name node)
4452 "No node found at point.")))))
4453
4454 (defun js2-node-at-point (&optional pos skip-comments)
4455 "Return AST node at POS, a buffer position, defaulting to current point.
4456 The `js2-mode-ast' variable must be set to the current parse tree.
4457 Signals an error if the AST (`js2-mode-ast') is nil.
4458 Always returns a node - if it can't find one, it returns the root.
4459 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4460 (let ((ast js2-mode-ast)
4461 result)
4462 (unless ast
4463 (error "No JavaScript AST available"))
4464 ;; Look through comments first, since they may be inside nodes that
4465 ;; would otherwise report a match.
4466 (setq pos (or pos (point))
4467 result (if (> pos (js2-node-abs-end ast))
4468 ast
4469 (if (not skip-comments)
4470 (js2-comment-at-point pos))))
4471 (unless result
4472 (setq js2-discovered-node nil
4473 js2-visitor-offset 0
4474 js2-node-search-point pos)
4475 (unwind-protect
4476 (catch 'js2-visit-done
4477 (js2-visit-ast ast #'js2-node-at-point-visitor))
4478 (setq js2-visitor-offset nil
4479 js2-node-search-point nil))
4480 (setq result js2-discovered-node))
4481 ;; may have found a comment beyond end of last child node,
4482 ;; since visiting the ast-root looks at the comment-list last.
4483 (if (and skip-comments
4484 (js2-comment-node-p result))
4485 (setq result nil))
4486 (or result js2-mode-ast)))
4487
4488 (defun js2-node-at-point-visitor (node end-p)
4489 (let ((rel-pos (js2-node-pos node))
4490 abs-pos
4491 abs-end
4492 (point js2-node-search-point))
4493 (cond
4494 (end-p
4495 ;; this evaluates to a non-nil return value, even if it's zero
4496 (decf js2-visitor-offset rel-pos))
4497 ;; we already looked for comments before visiting, and don't want them now
4498 ((js2-comment-node-p node)
4499 nil)
4500 (t
4501 (setq abs-pos (incf js2-visitor-offset rel-pos)
4502 ;; we only want to use the node if the point is before
4503 ;; the last character position in the node, so we decrement
4504 ;; the absolute end by 1.
4505 abs-end (+ abs-pos (js2-node-len node) -1))
4506 (cond
4507 ;; If this node starts after search-point, stop the search.
4508 ((> abs-pos point)
4509 (throw 'js2-visit-done nil))
4510 ;; If this node ends before the search-point, don't check kids.
4511 ((> point abs-end)
4512 nil)
4513 (t
4514 ;; Otherwise point is within this node, possibly in a child.
4515 (setq js2-discovered-node node)
4516 t)))))) ; keep processing kids to look for more specific match
4517
4518 (defsubst js2-block-comment-p (node)
4519 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4520 (and (js2-comment-node-p node)
4521 (memq (js2-comment-node-format node) '(jsdoc block))))
4522
4523 ;; TODO: put the comments in a vector and binary-search them instead
4524 (defun js2-comment-at-point (&optional pos)
4525 "Look through scanned comment nodes for one containing POS.
4526 POS is a buffer position that defaults to current point.
4527 Function returns nil if POS was not in any comment node."
4528 (let ((ast js2-mode-ast)
4529 (x (or pos (point)))
4530 beg end)
4531 (unless ast
4532 (error "No JavaScript AST available"))
4533 (catch 'done
4534 ;; Comments are stored in lexical order.
4535 (dolist (comment (js2-ast-root-comments ast) nil)
4536 (setq beg (js2-node-abs-pos comment)
4537 end (+ beg (js2-node-len comment)))
4538 (if (and (>= x beg)
4539 (<= x end))
4540 (throw 'done comment))))))
4541
4542 (defun js2-mode-find-parent-fn (node)
4543 "Find function enclosing NODE.
4544 Returns nil if NODE is not inside a function."
4545 (setq node (js2-node-parent node))
4546 (while (and node (not (js2-function-node-p node)))
4547 (setq node (js2-node-parent node)))
4548 (and (js2-function-node-p node) node))
4549
4550 (defun js2-mode-find-enclosing-fn (node)
4551 "Find function or root enclosing NODE."
4552 (if (js2-ast-root-p node)
4553 node
4554 (setq node (js2-node-parent node))
4555 (while (not (or (js2-ast-root-p node)
4556 (js2-function-node-p node)))
4557 (setq node (js2-node-parent node)))
4558 node))
4559
4560 (defun js2-mode-find-enclosing-node (beg end)
4561 "Find node fully enclosing BEG and END."
4562 (let ((node (js2-node-at-point beg))
4563 pos
4564 (continue t))
4565 (while continue
4566 (if (or (js2-ast-root-p node)
4567 (and
4568 (<= (setq pos (js2-node-abs-pos node)) beg)
4569 (>= (+ pos (js2-node-len node)) end)))
4570 (setq continue nil)
4571 (setq node (js2-node-parent node))))
4572 node))
4573
4574 (defun js2-node-parent-script-or-fn (node)
4575 "Find script or function immediately enclosing NODE.
4576 If NODE is the ast-root, returns nil."
4577 (if (js2-ast-root-p node)
4578 nil
4579 (setq node (js2-node-parent node))
4580 (while (and node (not (or (js2-function-node-p node)
4581 (js2-script-node-p node))))
4582 (setq node (js2-node-parent node)))
4583 node))
4584
4585 (defun js2-node-is-descendant (node ancestor)
4586 "Return t if NODE is a descendant of ANCESTOR."
4587 (while (and node
4588 (not (eq node ancestor)))
4589 (setq node (js2-node-parent node)))
4590 node)
4591
4592 ;;; visitor infrastructure
4593
4594 (defun js2-visit-none (_node _callback)
4595 "Visitor for AST node that have no node children."
4596 nil)
4597
4598 (defun js2-print-none (_node _indent)
4599 "Visitor for AST node with no printed representation.")
4600
4601 (defun js2-print-body (node indent)
4602 "Print a statement, or a block without braces."
4603 (if (js2-block-node-p node)
4604 (dolist (kid (js2-block-node-kids node))
4605 (js2-print-ast kid indent))
4606 (js2-print-ast node indent)))
4607
4608 (defun js2-print-list (args &optional delimiter)
4609 (loop with len = (length args)
4610 for arg in args
4611 for count from 1
4612 do
4613 (when arg (js2-print-ast arg 0))
4614 (if (< count len)
4615 (insert (or delimiter ", ")))))
4616
4617 (defun js2-print-tree (ast)
4618 "Prints an AST to the current buffer.
4619 Makes `js2-ast-parent-nodes' available to the printer functions."
4620 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4621 (js2-print-ast ast)))
4622
4623 (defun js2-print-ast (node &optional indent)
4624 "Helper function for printing AST nodes.
4625 Requires `js2-ast-parent-nodes' to be non-nil.
4626 You should use `js2-print-tree' instead of this function."
4627 (let ((printer (get (aref node 0) 'js2-printer))
4628 (i (or indent 0)))
4629 ;; TODO: wedge comments in here somewhere
4630 (if printer
4631 (funcall printer node i))))
4632
4633 (defconst js2-side-effecting-tokens
4634 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4635 (dolist (tt (list js2-ASSIGN
4636 js2-ASSIGN_ADD
4637 js2-ASSIGN_BITAND
4638 js2-ASSIGN_BITOR
4639 js2-ASSIGN_BITXOR
4640 js2-ASSIGN_DIV
4641 js2-ASSIGN_LSH
4642 js2-ASSIGN_MOD
4643 js2-ASSIGN_MUL
4644 js2-ASSIGN_RSH
4645 js2-ASSIGN_SUB
4646 js2-ASSIGN_URSH
4647 js2-BLOCK
4648 js2-BREAK
4649 js2-CALL
4650 js2-CATCH
4651 js2-CATCH_SCOPE
4652 js2-CONST
4653 js2-CONTINUE
4654 js2-DEBUGGER
4655 js2-DEC
4656 js2-DELPROP
4657 js2-DEL_REF
4658 js2-DO
4659 js2-ELSE
4660 js2-EMPTY
4661 js2-ENTERWITH
4662 js2-EXPORT
4663 js2-EXPR_RESULT
4664 js2-FINALLY
4665 js2-FOR
4666 js2-FUNCTION
4667 js2-GOTO
4668 js2-IF
4669 js2-IFEQ
4670 js2-IFNE
4671 js2-IMPORT
4672 js2-INC
4673 js2-JSR
4674 js2-LABEL
4675 js2-LEAVEWITH
4676 js2-LET
4677 js2-LETEXPR
4678 js2-LOCAL_BLOCK
4679 js2-LOOP
4680 js2-NEW
4681 js2-REF_CALL
4682 js2-RETHROW
4683 js2-RETURN
4684 js2-RETURN_RESULT
4685 js2-SEMI
4686 js2-SETELEM
4687 js2-SETELEM_OP
4688 js2-SETNAME
4689 js2-SETPROP
4690 js2-SETPROP_OP
4691 js2-SETVAR
4692 js2-SET_REF
4693 js2-SET_REF_OP
4694 js2-SWITCH
4695 js2-TARGET
4696 js2-THROW
4697 js2-TRY
4698 js2-VAR
4699 js2-WHILE
4700 js2-WITH
4701 js2-WITHEXPR
4702 js2-YIELD))
4703 (aset tokens tt t))
4704 (if js2-instanceof-has-side-effects
4705 (aset tokens js2-INSTANCEOF t))
4706 tokens))
4707
4708 (defun js2-node-has-side-effects (node)
4709 "Return t if NODE has side effects."
4710 (when node ; makes it easier to handle malformed expressions
4711 (let ((tt (js2-node-type node)))
4712 (cond
4713 ;; This doubtless needs some work, since EXPR_VOID is used
4714 ;; in several ways in Rhino and I may not have caught them all.
4715 ;; I'll wait for people to notice incorrect warnings.
4716 ((and (= tt js2-EXPR_VOID)
4717 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4718 (let ((expr (js2-expr-stmt-node-expr node)))
4719 (or (js2-node-has-side-effects expr)
4720 (when (js2-string-node-p expr)
4721 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4722 ((= tt js2-COMMA)
4723 (js2-node-has-side-effects (js2-infix-node-right node)))
4724 ((or (= tt js2-AND)
4725 (= tt js2-OR))
4726 (or (js2-node-has-side-effects (js2-infix-node-right node))
4727 (js2-node-has-side-effects (js2-infix-node-left node))))
4728 ((= tt js2-HOOK)
4729 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4730 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4731 ((js2-paren-node-p node)
4732 (js2-node-has-side-effects (js2-paren-node-expr node)))
4733 ((= tt js2-ERROR) ; avoid cascaded error messages
4734 nil)
4735 (t
4736 (aref js2-side-effecting-tokens tt))))))
4737
4738 (defconst js2-stmt-node-types
4739 (list js2-BLOCK
4740 js2-BREAK
4741 js2-CONTINUE
4742 js2-DEFAULT ; e4x "default xml namespace" statement
4743 js2-DO
4744 js2-EXPR_RESULT
4745 js2-EXPR_VOID
4746 js2-FOR
4747 js2-IF
4748 js2-RETURN
4749 js2-SWITCH
4750 js2-THROW
4751 js2-TRY
4752 js2-WHILE
4753 js2-WITH)
4754 "Node types that only appear in statement contexts.
4755 The list does not include nodes that always appear as the child
4756 of another specific statement type, such as switch-cases,
4757 catch and finally blocks, and else-clauses. The list also excludes
4758 nodes like yield, let and var, which may appear in either expression
4759 or statement context, and in the latter context always have a
4760 `js2-expr-stmt-node' parent. Finally, the list does not include
4761 functions or scripts, which are treated separately from statements
4762 by the JavaScript parser and runtime.")
4763
4764 (defun js2-stmt-node-p (node)
4765 "Heuristic for figuring out if NODE is a statement.
4766 Some node types can appear in either an expression context or a
4767 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4768 For these node types in a statement context, the parent will be a
4769 `js2-expr-stmt-node'.
4770 Functions aren't included in the check."
4771 (memq (js2-node-type node) js2-stmt-node-types))
4772
4773 (defun js2-mode-find-first-stmt (node)
4774 "Search upward starting from NODE looking for a statement.
4775 For purposes of this function, a `js2-function-node' counts."
4776 (while (not (or (js2-stmt-node-p node)
4777 (js2-function-node-p node)))
4778 (setq node (js2-node-parent node)))
4779 node)
4780
4781 (defun js2-node-parent-stmt (node)
4782 "Return the node's first ancestor that is a statement.
4783 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4784 appearing in a statement context will have a parent that is a
4785 `js2-expr-stmt-node' that will be returned by this function."
4786 (let ((parent (js2-node-parent node)))
4787 (if (or (null parent)
4788 (js2-stmt-node-p parent)
4789 (and (js2-function-node-p parent)
4790 (not (eq (js2-function-node-form parent)
4791 'FUNCTION_EXPRESSION))))
4792 parent
4793 (js2-node-parent-stmt parent))))
4794
4795 ;; In the Mozilla Rhino sources, Roshan James writes:
4796 ;; Does consistent-return analysis on the function body when strict mode is
4797 ;; enabled.
4798 ;;
4799 ;; function (x) { return (x+1) }
4800 ;;
4801 ;; is ok, but
4802 ;;
4803 ;; function (x) { if (x < 0) return (x+1); }
4804 ;;
4805 ;; is not because the function can potentially return a value when the
4806 ;; condition is satisfied and if not, the function does not explicitly
4807 ;; return a value.
4808 ;;
4809 ;; This extends to checking mismatches such as "return" and "return <value>"
4810 ;; used in the same function. Warnings are not emitted if inconsistent
4811 ;; returns exist in code that can be statically shown to be unreachable.
4812 ;; Ex.
4813 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4814 ;;
4815 ;; emits no warning. However if the loop had a break statement, then a
4816 ;; warning would be emitted.
4817 ;;
4818 ;; The consistency analysis looks at control structures such as loops, ifs,
4819 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4820 ;; warns the user about an inconsistent set of termination possibilities.
4821 ;;
4822 ;; These flags enumerate the possible ways a statement/function can
4823 ;; terminate. These flags are used by endCheck() and by the Parser to
4824 ;; detect inconsistent return usage.
4825 ;;
4826 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4827 ;; able to execute (example: throw, continue)
4828 ;;
4829 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4830 ;; next one. Statement such as return dont. A compound statement may have
4831 ;; some branch that drops off control to the next statement.
4832 ;;
4833 ;; END_RETURNS indicates that the statement can return with no value.
4834 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4835 ;;
4836 ;; A compound statement such as
4837 ;; if (condition) {
4838 ;; return value;
4839 ;; }
4840 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4841
4842 (defconst js2-END_UNREACHED 0)
4843 (defconst js2-END_DROPS_OFF 1)
4844 (defconst js2-END_RETURNS 2)
4845 (defconst js2-END_RETURNS_VALUE 4)
4846 (defconst js2-END_YIELDS 8)
4847
4848 (defun js2-has-consistent-return-usage (node)
4849 "Check that every return usage in a function body is consistent.
4850 Returns t if the function satisfies strict mode requirement."
4851 (let ((n (js2-end-check node)))
4852 ;; either it doesn't return a value in any branch...
4853 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4854 ;; or it returns a value (or is unreached) at every branch
4855 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4856 js2-END_RETURNS
4857 js2-END_YIELDS)))))
4858
4859 (defun js2-end-check-if (node)
4860 "Ensure that return usage in then/else blocks is consistent.
4861 If there is no else block, then the return statement can fall through.
4862 Returns logical OR of END_* flags"
4863 (let ((th (js2-if-node-then-part node))
4864 (el (js2-if-node-else-part node)))
4865 (if (null th)
4866 js2-END_UNREACHED
4867 (logior (js2-end-check th) (if el
4868 (js2-end-check el)
4869 js2-END_DROPS_OFF)))))
4870
4871 (defun js2-end-check-switch (node)
4872 "Consistency of return statements is checked between the case statements.
4873 If there is no default, then the switch can fall through. If there is a
4874 default, we check to see if all code paths in the default return or if
4875 there is a code path that can fall through.
4876 Returns logical OR of END_* flags."
4877 (let ((rv js2-END_UNREACHED)
4878 default-case)
4879 ;; examine the cases
4880 (catch 'break
4881 (dolist (c (js2-switch-node-cases node))
4882 (if (js2-case-node-expr c)
4883 (js2-set-flag rv (js2-end-check-block c))
4884 (setq default-case c)
4885 (throw 'break nil))))
4886 ;; we don't care how the cases drop into each other
4887 (js2-clear-flag rv js2-END_DROPS_OFF)
4888 ;; examine the default
4889 (js2-set-flag rv (if default-case
4890 (js2-end-check default-case)
4891 js2-END_DROPS_OFF))
4892 rv))
4893
4894 (defun js2-end-check-try (node)
4895 "If the block has a finally, return consistency is checked in the
4896 finally block. If all code paths in the finally return, then the
4897 returns in the try-catch blocks don't matter. If there is a code path
4898 that does not return or if there is no finally block, the returns
4899 of the try and catch blocks are checked for mismatch.
4900 Returns logical OR of END_* flags."
4901 (let ((finally (js2-try-node-finally-block node))
4902 rv)
4903 ;; check the finally if it exists
4904 (setq rv (if finally
4905 (js2-end-check (js2-finally-node-body finally))
4906 js2-END_DROPS_OFF))
4907 ;; If the finally block always returns, then none of the returns
4908 ;; in the try or catch blocks matter.
4909 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4910 (js2-clear-flag rv js2-END_DROPS_OFF)
4911 ;; examine the try block
4912 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4913 ;; check each catch block
4914 (dolist (cb (js2-try-node-catch-clauses node))
4915 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4916 rv))
4917
4918 (defun js2-end-check-loop (node)
4919 "Return statement in the loop body must be consistent.
4920 The default assumption for any kind of a loop is that it will eventually
4921 terminate. The only exception is a loop with a constant true condition.
4922 Code that follows such a loop is examined only if one can determine
4923 statically that there is a break out of the loop.
4924
4925 for(... ; ... ; ...) {}
4926 for(... in ... ) {}
4927 while(...) { }
4928 do { } while(...)
4929
4930 Returns logical OR of END_* flags."
4931 (let ((rv (js2-end-check (js2-loop-node-body node)))
4932 (condition (cond
4933 ((js2-while-node-p node)
4934 (js2-while-node-condition node))
4935 ((js2-do-node-p node)
4936 (js2-do-node-condition node))
4937 ((js2-for-node-p node)
4938 (js2-for-node-condition node)))))
4939
4940 ;; check to see if the loop condition is always true
4941 (if (and condition
4942 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4943 (js2-clear-flag rv js2-END_DROPS_OFF))
4944
4945 ;; look for effect of breaks
4946 (js2-set-flag rv (js2-node-get-prop node
4947 'CONTROL_BLOCK_PROP
4948 js2-END_UNREACHED))
4949 rv))
4950
4951 (defun js2-end-check-block (node)
4952 "A general block of code is examined statement by statement.
4953 If any statement (even a compound one) returns in all branches, then
4954 subsequent statements are not examined.
4955 Returns logical OR of END_* flags."
4956 (let* ((rv js2-END_DROPS_OFF)
4957 (kids (js2-block-node-kids node))
4958 (n (car kids)))
4959 ;; Check each statment. If the statement can continue onto the next
4960 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4961 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4962 (js2-clear-flag rv js2-END_DROPS_OFF)
4963 (js2-set-flag rv (js2-end-check n))
4964 (setq kids (cdr kids)
4965 n (car kids)))
4966 rv))
4967
4968 (defun js2-end-check-label (node)
4969 "A labeled statement implies that there may be a break to the label.
4970 The function processes the labeled statement and then checks the
4971 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4972 particular label.
4973 Returns logical OR of END_* flags."
4974 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4975 (logior rv (js2-node-get-prop node
4976 'CONTROL_BLOCK_PROP
4977 js2-END_UNREACHED))))
4978
4979 (defun js2-end-check-break (node)
4980 "When a break is encountered annotate the statement being broken
4981 out of by setting its CONTROL_BLOCK_PROP property.
4982 Returns logical OR of END_* flags."
4983 (and (js2-break-node-target node)
4984 (js2-node-set-prop (js2-break-node-target node)
4985 'CONTROL_BLOCK_PROP
4986 js2-END_DROPS_OFF))
4987 js2-END_UNREACHED)
4988
4989 (defun js2-end-check (node)
4990 "Examine the body of a function, doing a basic reachability analysis.
4991 Returns a combination of flags END_* flags that indicate
4992 how the function execution can terminate. These constitute only the
4993 pessimistic set of termination conditions. It is possible that at
4994 runtime certain code paths will never be actually taken. Hence this
4995 analysis will flag errors in cases where there may not be errors.
4996 Returns logical OR of END_* flags"
4997 (let (kid)
4998 (cond
4999 ((js2-break-node-p node)
5000 (js2-end-check-break node))
5001 ((js2-expr-stmt-node-p node)
5002 (if (setq kid (js2-expr-stmt-node-expr node))
5003 (js2-end-check kid)
5004 js2-END_DROPS_OFF))
5005 ((or (js2-continue-node-p node)
5006 (js2-throw-node-p node))
5007 js2-END_UNREACHED)
5008 ((js2-return-node-p node)
5009 (if (setq kid (js2-return-node-retval node))
5010 js2-END_RETURNS_VALUE
5011 js2-END_RETURNS))
5012 ((js2-loop-node-p node)
5013 (js2-end-check-loop node))
5014 ((js2-switch-node-p node)
5015 (js2-end-check-switch node))
5016 ((js2-labeled-stmt-node-p node)
5017 (js2-end-check-label node))
5018 ((js2-if-node-p node)
5019 (js2-end-check-if node))
5020 ((js2-try-node-p node)
5021 (js2-end-check-try node))
5022 ((js2-block-node-p node)
5023 (if (null (js2-block-node-kids node))
5024 js2-END_DROPS_OFF
5025 (js2-end-check-block node)))
5026 ((js2-yield-node-p node)
5027 js2-END_YIELDS)
5028 (t
5029 js2-END_DROPS_OFF))))
5030
5031 (defun js2-always-defined-boolean-p (node)
5032 "Check if NODE always evaluates to true or false in boolean context.
5033 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5034 nor always false."
5035 (let ((tt (js2-node-type node))
5036 num)
5037 (cond
5038 ((or (= tt js2-FALSE) (= tt js2-NULL))
5039 'ALWAYS_FALSE)
5040 ((= tt js2-TRUE)
5041 'ALWAYS_TRUE)
5042 ((= tt js2-NUMBER)
5043 (setq num (js2-number-node-num-value node))
5044 (if (and (not (eq num 0.0e+NaN))
5045 (not (zerop num)))
5046 'ALWAYS_TRUE
5047 'ALWAYS_FALSE))
5048 (t
5049 nil))))
5050
5051 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5052 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5053
5054 (defvar js2-tokens nil
5055 "List of all defined token names.") ; initialized in `js2-token-names'
5056
5057 (defconst js2-token-names
5058 (let* ((names (make-vector js2-num-tokens -1))
5059 (case-fold-search nil) ; only match js2-UPPER_CASE
5060 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5061 (loop for sym in syms
5062 for i from 0
5063 do
5064 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5065 (not (boundp sym)))
5066 (aset names (symbol-value sym) ; code, e.g. 152
5067 (downcase
5068 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5069 (push sym js2-tokens)))
5070 names)
5071 "Vector mapping int values to token string names, sans `js2-' prefix.")
5072
5073 (defun js2-tt-name (tok)
5074 "Return a string name for TOK, a token symbol or code.
5075 Signals an error if it's not a recognized token."
5076 (let ((code tok))
5077 (if (symbolp tok)
5078 (setq code (symbol-value tok)))
5079 (if (eq code -1)
5080 "ERROR"
5081 (if (and (numberp code)
5082 (not (minusp code))
5083 (< code js2-num-tokens))
5084 (aref js2-token-names code)
5085 (error "Invalid token: %s" code)))))
5086
5087 (defsubst js2-tt-sym (tok)
5088 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5089 (intern (js2-tt-name tok)))
5090
5091 (defconst js2-token-codes
5092 (let ((table (make-hash-table :test 'eq :size 256)))
5093 (loop for name across js2-token-names
5094 for sym = (intern (concat "js2-" (upcase name)))
5095 do
5096 (puthash sym (symbol-value sym) table))
5097 ;; clean up a few that are "wrong" in Rhino's token codes
5098 (puthash 'js2-DELETE js2-DELPROP table)
5099 table)
5100 "Hashtable mapping token type symbols to their bytecodes.")
5101
5102 (defsubst js2-tt-code (sym)
5103 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5104 (or (gethash sym js2-token-codes)
5105 (error "Invalid token symbol: %s " sym))) ; signal code bug
5106
5107 (defun js2-report-scan-error (msg &optional no-throw beg len)
5108 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5109 (js2-report-error msg nil
5110 (or beg (js2-current-token-beg))
5111 (or len (js2-current-token-len)))
5112 (unless no-throw
5113 (throw 'return js2-ERROR)))
5114
5115 (defun js2-set-string-from-buffer (token)
5116 "Set `string' and `end' slots for TOKEN, return the string."
5117 (setf (js2-token-end token) js2-ts-cursor
5118 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5119
5120 ;; TODO: could potentially avoid a lot of consing by allocating a
5121 ;; char buffer the way Rhino does.
5122 (defsubst js2-add-to-string (c)
5123 (push c js2-ts-string-buffer))
5124
5125 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5126 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5127 ;; any other character: when it's not part of the current token, we
5128 ;; unget it, allowing it to be read again by the following call.
5129 (defsubst js2-unget-char ()
5130 (decf js2-ts-cursor))
5131
5132 ;; Rhino distinguishes \r and \n line endings. We don't need to
5133 ;; because we only scan from Emacs buffers, which always use \n.
5134 (defun js2-get-char ()
5135 "Read and return the next character from the input buffer.
5136 Increments `js2-ts-lineno' if the return value is a newline char.
5137 Updates `js2-ts-cursor' to the point after the returned char.
5138 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5139 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5140 (let (c)
5141 ;; check for end of buffer
5142 (if (>= js2-ts-cursor (point-max))
5143 (setq js2-ts-hit-eof t
5144 js2-ts-cursor (1+ js2-ts-cursor)
5145 c js2-EOF_CHAR) ; return value
5146 ;; otherwise read next char
5147 (setq c (char-before (incf js2-ts-cursor)))
5148 ;; if we read a newline, update counters
5149 (if (= c ?\n)
5150 (setq js2-ts-line-start js2-ts-cursor
5151 js2-ts-lineno (1+ js2-ts-lineno)))
5152 ;; TODO: skip over format characters
5153 c)))
5154
5155 (defun js2-read-unicode-escape ()
5156 "Read a \\uNNNN sequence from the input.
5157 Assumes the ?\ and ?u have already been read.
5158 Returns the unicode character, or nil if it wasn't a valid character.
5159 Doesn't change the values of any scanner variables."
5160 ;; I really wish I knew a better way to do this, but I can't
5161 ;; find the Emacs function that takes a 16-bit int and converts
5162 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5163 ;; Have to first check that it's 4 hex characters or it may stop
5164 ;; the read early.
5165 (ignore-errors
5166 (let ((s (buffer-substring-no-properties js2-ts-cursor
5167 (+ 4 js2-ts-cursor))))
5168 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5169 (read (concat "?\\u" s))))))
5170
5171 (defun js2-match-char (test)
5172 "Consume and return next character if it matches TEST, a character.
5173 Returns nil and consumes nothing if TEST is not the next character."
5174 (let ((c (js2-get-char)))
5175 (if (eq c test)
5176 t
5177 (js2-unget-char)
5178 nil)))
5179
5180 (defun js2-peek-char ()
5181 (prog1
5182 (js2-get-char)
5183 (js2-unget-char)))
5184
5185 (defun js2-identifier-start-p (c)
5186 "Is C a valid start to an ES5 Identifier?
5187 See http://es5.github.io/#x7.6"
5188 (or
5189 (memq c '(?$ ?_))
5190 (memq (get-char-code-property c 'general-category)
5191 ;; Letters
5192 '(Lu Ll Lt Lm Lo Nl))))
5193
5194 (defun js2-identifier-part-p (c)
5195 "Is C a valid part of an ES5 Identifier?
5196 See http://es5.github.io/#x7.6"
5197 (or
5198 (memq c '(?$ ?_ ?\u200c ?\u200d))
5199 (memq (get-char-code-property c 'general-category)
5200 '(;; Letters
5201 Lu Ll Lt Lm Lo Nl
5202 ;; Combining Marks
5203 Mn Mc
5204 ;; Digits
5205 Nd
5206 ;; Connector Punctuation
5207 Pc))))
5208
5209 (defun js2-alpha-p (c)
5210 (cond ((and (<= ?A c) (<= c ?Z)) t)
5211 ((and (<= ?a c) (<= c ?z)) t)
5212 (t nil)))
5213
5214 (defsubst js2-digit-p (c)
5215 (and (<= ?0 c) (<= c ?9)))
5216
5217 (defun js2-js-space-p (c)
5218 (if (<= c 127)
5219 (memq c '(#x20 #x9 #xB #xC #xD))
5220 (or
5221 (eq c #xA0)
5222 ;; TODO: change this nil to check for Unicode space character
5223 nil)))
5224
5225 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5226
5227 (defun js2-skip-line ()
5228 "Skip to end of line."
5229 (while (not (memq (js2-get-char) js2-eol-chars)))
5230 (js2-unget-char)
5231 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5232 (setq js2-token-end js2-ts-cursor))
5233
5234 (defun js2-init-scanner (&optional buf line)
5235 "Create token stream for BUF starting on LINE.
5236 BUF defaults to `current-buffer' and LINE defaults to 1.
5237
5238 A buffer can only have one scanner active at a time, which yields
5239 dramatically simpler code than using a defstruct. If you need to
5240 have simultaneous scanners in a buffer, copy the regions to scan
5241 into temp buffers."
5242 (with-current-buffer (or buf (current-buffer))
5243 (setq js2-ts-dirty-line nil
5244 js2-ts-hit-eof nil
5245 js2-ts-line-start 0
5246 js2-ts-lineno (or line 1)
5247 js2-ts-line-end-char -1
5248 js2-ts-cursor (point-min)
5249 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5250 js2-ti-tokens-cursor 0
5251 js2-ti-lookahead 0
5252 js2-ts-is-xml-attribute nil
5253 js2-ts-xml-is-tag-content nil
5254 js2-ts-xml-open-tags-count 0
5255 js2-ts-string-buffer nil)))
5256
5257 ;; This function uses the cached op, string and number fields in
5258 ;; TokenStream; if getToken has been called since the passed token
5259 ;; was scanned, the op or string printed may be incorrect.
5260 (defun js2-token-to-string (token)
5261 ;; Not sure where this function is used in Rhino. Not tested.
5262 (if (not js2-debug-print-trees)
5263 ""
5264 (let ((name (js2-tt-name token)))
5265 (cond
5266 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5267 (concat name " `" (js2-current-token-string) "'"))
5268 ((eq token js2-NUMBER)
5269 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5270 (t
5271 name)))))
5272
5273 (defconst js2-keywords
5274 '(break
5275 case catch const continue
5276 debugger default delete do
5277 else enum
5278 false finally for function
5279 if in instanceof import
5280 let
5281 new null
5282 return
5283 switch
5284 this throw true try typeof
5285 var void
5286 while with
5287 yield))
5288
5289 ;; Token names aren't exactly the same as the keywords, unfortunately.
5290 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5291 (defconst js2-kwd-tokens
5292 (let ((table (make-vector js2-num-tokens nil))
5293 (tokens
5294 (list js2-BREAK
5295 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5296 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5297 js2-ELSE
5298 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5299 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5300 js2-LET
5301 js2-NEW js2-NULL
5302 js2-RETURN
5303 js2-SWITCH
5304 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5305 js2-VAR
5306 js2-WHILE js2-WITH
5307 js2-YIELD)))
5308 (dolist (i tokens)
5309 (aset table i 'font-lock-keyword-face))
5310 (aset table js2-STRING 'font-lock-string-face)
5311 (aset table js2-REGEXP 'font-lock-string-face)
5312 (aset table js2-COMMENT 'font-lock-comment-face)
5313 (aset table js2-THIS 'font-lock-builtin-face)
5314 (aset table js2-VOID 'font-lock-constant-face)
5315 (aset table js2-NULL 'font-lock-constant-face)
5316 (aset table js2-TRUE 'font-lock-constant-face)
5317 (aset table js2-FALSE 'font-lock-constant-face)
5318 (aset table js2-NOT 'font-lock-negation-char-face)
5319 table)
5320 "Vector whose values are non-nil for tokens that are keywords.
5321 The values are default faces to use for highlighting the keywords.")
5322
5323 ;; FIXME: Support strict mode-only future reserved words, after we know
5324 ;; which parts scopes are in strict mode, and which are not.
5325 (defconst js2-reserved-words '(class export extends import super)
5326 "Future reserved keywords in ECMAScript 5.")
5327
5328 (defconst js2-keyword-names
5329 (let ((table (make-hash-table :test 'equal)))
5330 (loop for k in js2-keywords
5331 do (puthash
5332 (symbol-name k) ; instanceof
5333 (intern (concat "js2-"
5334 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5335 table))
5336 table)
5337 "JavaScript keywords by name, mapped to their symbols.")
5338
5339 (defconst js2-reserved-word-names
5340 (let ((table (make-hash-table :test 'equal)))
5341 (loop for k in js2-reserved-words
5342 do
5343 (puthash (symbol-name k) 'js2-RESERVED table))
5344 table)
5345 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5346
5347 (defun js2-collect-string (buf)
5348 "Convert BUF, a list of chars, to a string.
5349 Reverses BUF before converting."
5350 (if buf
5351 (apply #'string (nreverse buf))
5352 ""))
5353
5354 (defun js2-string-to-keyword (s)
5355 "Return token for S, a string, if S is a keyword or reserved word.
5356 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5357 (or (gethash s js2-keyword-names)
5358 (gethash s js2-reserved-word-names)))
5359
5360 (defsubst js2-ts-set-char-token-bounds (token)
5361 "Used when next token is one character."
5362 (setf (js2-token-beg token) (1- js2-ts-cursor)
5363 (js2-token-end token) js2-ts-cursor))
5364
5365 (defsubst js2-ts-return (token type)
5366 "Update the `end' and `type' slots of TOKEN,
5367 then throw `return' with value TYPE."
5368 (setf (js2-token-end token) js2-ts-cursor
5369 (js2-token-type token) type)
5370 (throw 'return type))
5371
5372 (defun js2-x-digit-to-int (c accumulator)
5373 "Build up a hex number.
5374 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5375 corresponding number. Otherwise return -1."
5376 (catch 'return
5377 (catch 'check
5378 ;; Use 0..9 < A..Z < a..z
5379 (cond
5380 ((<= c ?9)
5381 (decf c ?0)
5382 (if (<= 0 c)
5383 (throw 'check nil)))
5384 ((<= c ?F)
5385 (when (<= ?A c)
5386 (decf c (- ?A 10))
5387 (throw 'check nil)))
5388 ((<= c ?f)
5389 (when (<= ?a c)
5390 (decf c (- ?a 10))
5391 (throw 'check nil))))
5392 (throw 'return -1))
5393 (logior c (lsh accumulator 4))))
5394
5395 (defun js2-get-token ()
5396 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5397 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5398 next saved token.
5399
5400 This function will not return a newline (js2-EOL) - instead, it
5401 gobbles newlines until it finds a non-newline token. Call
5402 `js2-peek-token-or-eol' when you care about newlines.
5403
5404 This function will also not return a js2-COMMENT. Instead, it
5405 records comments found in `js2-scanned-comments'. If the token
5406 returned by this function immediately follows a jsdoc comment,
5407 the token is flagged as such."
5408 (if (zerop js2-ti-lookahead)
5409 (js2-get-token-internal)
5410 (decf js2-ti-lookahead)
5411 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5412 (let ((tt (js2-current-token-type)))
5413 (assert (not (= tt js2-EOL)))
5414 tt)))
5415
5416 (defun js2-unget-token ()
5417 (assert (< js2-ti-lookahead js2-ti-max-lookahead))
5418 (incf js2-ti-lookahead)
5419 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5420
5421 (defun js2-get-token-internal ()
5422 (let* ((token (js2-get-token-internal-1)) ; call scanner
5423 (tt (js2-token-type token))
5424 saw-eol
5425 face)
5426 ;; process comments
5427 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5428 (if (= tt js2-EOL)
5429 (setq saw-eol t)
5430 (setq saw-eol nil)
5431 (when js2-record-comments
5432 (js2-record-comment token)))
5433 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5434 (setq token (js2-get-token-internal-1) ; call scanner again
5435 tt (js2-token-type token)))
5436
5437 (when saw-eol
5438 (setf (js2-token-follows-eol-p token) t))
5439
5440 ;; perform lexical fontification as soon as token is scanned
5441 (when js2-parse-ide-mode
5442 (cond
5443 ((minusp tt)
5444 (js2-record-face 'js2-error token))
5445 ((setq face (aref js2-kwd-tokens tt))
5446 (js2-record-face face token))
5447 ((and (= tt js2-NAME)
5448 (equal (js2-token-string token) "undefined"))
5449 (js2-record-face 'font-lock-constant-face token))))
5450 tt))
5451
5452 (defun js2-get-token-internal-1 ()
5453 "Return next JavaScript token type, an int such as js2-RETURN.
5454 During operation, creates an instance of `js2-token' struct, sets
5455 its relevant fields and puts it into `js2-ti-tokens'."
5456 (let (c c1 identifier-start is-unicode-escape-start
5457 contains-escape escape-val str result base
5458 quote-char val look-for-slash continue tt
5459 (token (js2-new-token 0)))
5460 (setq
5461 tt
5462 (catch 'return
5463 (while t
5464 ;; Eat whitespace, possibly sensitive to newlines.
5465 (setq continue t)
5466 (while continue
5467 (setq c (js2-get-char))
5468 (cond
5469 ((eq c js2-EOF_CHAR)
5470 (js2-unget-char)
5471 (js2-ts-set-char-token-bounds token)
5472 (throw 'return js2-EOF))
5473 ((eq c ?\n)
5474 (js2-ts-set-char-token-bounds token)
5475 (setq js2-ts-dirty-line nil)
5476 (throw 'return js2-EOL))
5477 ((not (js2-js-space-p c))
5478 (if (/= c ?-) ; in case end of HTML comment
5479 (setq js2-ts-dirty-line t))
5480 (setq continue nil))))
5481 ;; Assume the token will be 1 char - fixed up below.
5482 (js2-ts-set-char-token-bounds token)
5483 (when (eq c ?@)
5484 (throw 'return js2-XMLATTR))
5485 ;; identifier/keyword/instanceof?
5486 ;; watch out for starting with a <backslash>
5487 (cond
5488 ((eq c ?\\)
5489 (setq c (js2-get-char))
5490 (if (eq c ?u)
5491 (setq identifier-start t
5492 is-unicode-escape-start t
5493 js2-ts-string-buffer nil)
5494 (setq identifier-start nil)
5495 (js2-unget-char)
5496 (setq c ?\\)))
5497 (t
5498 (when (setq identifier-start (js2-identifier-start-p c))
5499 (setq js2-ts-string-buffer nil)
5500 (js2-add-to-string c))))
5501 (when identifier-start
5502 (setq contains-escape is-unicode-escape-start)
5503 (catch 'break
5504 (while t
5505 (if is-unicode-escape-start
5506 ;; strictly speaking we should probably push-back
5507 ;; all the bad characters if the <backslash>uXXXX
5508 ;; sequence is malformed. But since there isn't a
5509 ;; correct context(is there?) for a bad Unicode
5510 ;; escape sequence in an identifier, we can report
5511 ;; an error here.
5512 (progn
5513 (setq escape-val 0)
5514 (dotimes (_ 4)
5515 (setq c (js2-get-char)
5516 escape-val (js2-x-digit-to-int c escape-val))
5517 ;; Next check takes care of c < 0 and bad escape
5518 (if (minusp escape-val)
5519 (throw 'break nil)))
5520 (if (minusp escape-val)
5521 (js2-report-scan-error "msg.invalid.escape" t))
5522 (js2-add-to-string escape-val)
5523 (setq is-unicode-escape-start nil))
5524 (setq c (js2-get-char))
5525 (cond
5526 ((eq c ?\\)
5527 (setq c (js2-get-char))
5528 (if (eq c ?u)
5529 (setq is-unicode-escape-start t
5530 contains-escape t)
5531 (js2-report-scan-error "msg.illegal.character" t)))
5532 (t
5533 (if (or (eq c js2-EOF_CHAR)
5534 (not (js2-identifier-part-p c)))
5535 (throw 'break nil))
5536 (js2-add-to-string c))))))
5537 (js2-unget-char)
5538 (setf str (js2-collect-string js2-ts-string-buffer)
5539 (js2-token-end token) js2-ts-cursor)
5540 ;; FIXME: Invalid in ES5 and ES6, see
5541 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5542 ;; Probably should just drop this conditional.
5543 (unless contains-escape
5544 ;; OPT we shouldn't have to make a string (object!) to
5545 ;; check if it's a keyword.
5546 ;; Return the corresponding token if it's a keyword
5547 (when (setq result (js2-string-to-keyword str))
5548 (if (and (< js2-language-version 170)
5549 (memq result '(js2-LET js2-YIELD)))
5550 ;; LET and YIELD are tokens only in 1.7 and later
5551 (setq result 'js2-NAME))
5552 (when (eq result 'js2-RESERVED)
5553 (setf (js2-token-string token) str))
5554 (throw 'return (js2-tt-code result))))
5555 ;; If we want to intern these as Rhino does, just use (intern str)
5556 (setf (js2-token-string token) str)
5557 (throw 'return js2-NAME)) ; end identifier/kwd check
5558 ;; is it a number?
5559 (when (or (js2-digit-p c)
5560 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5561 (setq js2-ts-string-buffer nil
5562 base 10)
5563 (when (eq c ?0)
5564 (setq c (js2-get-char))
5565 (cond
5566 ((or (eq c ?x) (eq c ?X))
5567 (setq base 16)
5568 (setq c (js2-get-char)))
5569 ((and (or (eq c ?b) (eq c ?B))
5570 (>= js2-language-version 200))
5571 (setq base 2)
5572 (setq c (js2-get-char)))
5573 ((and (or (eq c ?o) (eq c ?O))
5574 (>= js2-language-version 200))
5575 (setq base 8)
5576 (setq c (js2-get-char)))
5577 ((js2-digit-p c)
5578 (setq base 'maybe-8))
5579 (t
5580 (js2-add-to-string ?0))))
5581 (cond
5582 ((eq base 16)
5583 (if (> 0 (js2-x-digit-to-int c 0))
5584 (js2-report-scan-error "msg.missing.hex.digits")
5585 (while (<= 0 (js2-x-digit-to-int c 0))
5586 (js2-add-to-string c)
5587 (setq c (js2-get-char)))))
5588 ((eq base 2)
5589 (if (not (memq c '(?0 ?1)))
5590 (js2-report-scan-error "msg.missing.binary.digits")
5591 (while (memq c '(?0 ?1))
5592 (js2-add-to-string c)
5593 (setq c (js2-get-char)))))
5594 ((eq base 8)
5595 (if (or (> ?0 c) (< ?7 c))
5596 (js2-report-scan-error "msg.missing.octal.digits")
5597 (while (and (<= ?0 c) (>= ?7 c))
5598 (js2-add-to-string c)
5599 (setq c (js2-get-char)))))
5600 (t
5601 (while (and (<= ?0 c) (<= c ?9))
5602 ;; We permit 08 and 09 as decimal numbers, which
5603 ;; makes our behavior a superset of the ECMA
5604 ;; numeric grammar. We might not always be so
5605 ;; permissive, so we warn about it.
5606 (when (and (eq base 'maybe-8) (>= c ?8))
5607 (js2-report-warning "msg.bad.octal.literal"
5608 (if (eq c ?8) "8" "9"))
5609 (setq base 10))
5610 (js2-add-to-string c)
5611 (setq c (js2-get-char)))
5612 (when (eq base 'maybe-8)
5613 (setq base 8))))
5614 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5615 (when (eq c ?.)
5616 (loop do
5617 (js2-add-to-string c)
5618 (setq c (js2-get-char))
5619 while (js2-digit-p c)))
5620 (when (memq c '(?e ?E))
5621 (js2-add-to-string c)
5622 (setq c (js2-get-char))
5623 (when (memq c '(?+ ?-))
5624 (js2-add-to-string c)
5625 (setq c (js2-get-char)))
5626 (unless (js2-digit-p c)
5627 (js2-report-scan-error "msg.missing.exponent" t))
5628 (loop do
5629 (js2-add-to-string c)
5630 (setq c (js2-get-char))
5631 while (js2-digit-p c))))
5632 (js2-unget-char)
5633 (let ((str (js2-set-string-from-buffer token)))
5634 (setf (js2-token-number token)
5635 (js2-string-to-number str base)))
5636 (throw 'return js2-NUMBER))
5637 ;; is it a string?
5638 (when (memq c '(?\" ?\'))
5639 ;; We attempt to accumulate a string the fast way, by
5640 ;; building it directly out of the reader. But if there
5641 ;; are any escaped characters in the string, we revert to
5642 ;; building it out of a string buffer.
5643 (setq quote-char c
5644 js2-ts-string-buffer nil
5645 c (js2-get-char))
5646 (catch 'break
5647 (while (/= c quote-char)
5648 (catch 'continue
5649 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5650 (js2-unget-char)
5651 (setf (js2-token-end token) js2-ts-cursor)
5652 (js2-report-error "msg.unterminated.string.lit")
5653 (throw 'return js2-STRING))
5654 (when (eq c ?\\)
5655 ;; We've hit an escaped character
5656 (setq c (js2-get-char))
5657 (case c
5658 (?b (setq c ?\b))
5659 (?f (setq c ?\f))
5660 (?n (setq c ?\n))
5661 (?r (setq c ?\r))
5662 (?t (setq c ?\t))
5663 (?v (setq c ?\v))
5664 (?u
5665 (setq c1 (js2-read-unicode-escape))
5666 (if js2-parse-ide-mode
5667 (if c1
5668 (progn
5669 ;; just copy the string in IDE-mode
5670 (js2-add-to-string ?\\)
5671 (js2-add-to-string ?u)
5672 (dotimes (_ 3)
5673 (js2-add-to-string (js2-get-char)))
5674 (setq c (js2-get-char))) ; added at end of loop
5675 ;; flag it as an invalid escape
5676 (js2-report-warning "msg.invalid.escape"
5677 nil (- js2-ts-cursor 2) 6))
5678 ;; Get 4 hex digits; if the u escape is not
5679 ;; followed by 4 hex digits, use 'u' + the
5680 ;; literal character sequence that follows.
5681 (js2-add-to-string ?u)
5682 (setq escape-val 0)
5683 (dotimes (_ 4)
5684 (setq c (js2-get-char)
5685 escape-val (js2-x-digit-to-int c escape-val))
5686 (if (minusp escape-val)
5687 (throw 'continue nil))
5688 (js2-add-to-string c))
5689 ;; prepare for replace of stored 'u' sequence by escape value
5690 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5691 c escape-val)))
5692 (?x
5693 ;; Get 2 hex digits, defaulting to 'x'+literal
5694 ;; sequence, as above.
5695 (setq c (js2-get-char)
5696 escape-val (js2-x-digit-to-int c 0))
5697 (if (minusp escape-val)
5698 (progn
5699 (js2-add-to-string ?x)
5700 (throw 'continue nil))
5701 (setq c1 c
5702 c (js2-get-char)
5703 escape-val (js2-x-digit-to-int c escape-val))
5704 (if (minusp escape-val)
5705 (progn
5706 (js2-add-to-string ?x)
5707 (js2-add-to-string c1)
5708 (throw 'continue nil))
5709 ;; got 2 hex digits
5710 (setq c escape-val))))
5711 (?\n
5712 ;; Remove line terminator after escape to follow
5713 ;; SpiderMonkey and C/C++
5714 (setq c (js2-get-char))
5715 (throw 'continue nil))
5716 (t
5717 (when (and (<= ?0 c) (< c ?8))
5718 (setq val (- c ?0)
5719 c (js2-get-char))
5720 (when (and (<= ?0 c) (< c ?8))
5721 (setq val (- (+ (* 8 val) c) ?0)
5722 c (js2-get-char))
5723 (when (and (<= ?0 c)
5724 (< c ?8)
5725 (< val #o37))
5726 ;; c is 3rd char of octal sequence only
5727 ;; if the resulting val <= 0377
5728 (setq val (- (+ (* 8 val) c) ?0)
5729 c (js2-get-char))))
5730 (js2-unget-char)
5731 (setq c val)))))
5732 (js2-add-to-string c)
5733 (setq c (js2-get-char)))))
5734 (js2-set-string-from-buffer token)
5735 (throw 'return js2-STRING))
5736 (js2-ts-return token
5737 (case c
5738 (?\;
5739 (throw 'return js2-SEMI))
5740 (?\[
5741 (throw 'return js2-LB))
5742 (?\]
5743 (throw 'return js2-RB))
5744 (?{
5745 (throw 'return js2-LC))
5746 (?}
5747 (throw 'return js2-RC))
5748 (?\(
5749 (throw 'return js2-LP))
5750 (?\)
5751 (throw 'return js2-RP))
5752 (?,
5753 (throw 'return js2-COMMA))
5754 (??
5755 (throw 'return js2-HOOK))
5756 (?:
5757 (if (js2-match-char ?:)
5758 js2-COLONCOLON
5759 (throw 'return js2-COLON)))
5760 (?.
5761 (if (js2-match-char ?.)
5762 (if (js2-match-char ?.)
5763 js2-TRIPLEDOT js2-DOTDOT)
5764 (if (js2-match-char ?\()
5765 js2-DOTQUERY
5766 (throw 'return js2-DOT))))
5767 (?|
5768 (if (js2-match-char ?|)
5769 (throw 'return js2-OR)
5770 (if (js2-match-char ?=)
5771 js2-ASSIGN_BITOR
5772 (throw 'return js2-BITOR))))
5773 (?^
5774 (if (js2-match-char ?=)
5775 js2-ASSIGN_BITOR
5776 (throw 'return js2-BITXOR)))
5777 (?&
5778 (if (js2-match-char ?&)
5779 (throw 'return js2-AND)
5780 (if (js2-match-char ?=)
5781 js2-ASSIGN_BITAND
5782 (throw 'return js2-BITAND))))
5783 (?=
5784 (if (js2-match-char ?=)
5785 (if (js2-match-char ?=)
5786 js2-SHEQ
5787 (throw 'return js2-EQ))
5788 (if (js2-match-char ?>)
5789 (js2-ts-return token js2-ARROW)
5790 (throw 'return js2-ASSIGN))))
5791 (?!
5792 (if (js2-match-char ?=)
5793 (if (js2-match-char ?=)
5794 js2-SHNE
5795 js2-NE)
5796 (throw 'return js2-NOT)))
5797 (?<
5798 ;; NB:treat HTML begin-comment as comment-till-eol
5799 (when (js2-match-char ?!)
5800 (when (js2-match-char ?-)
5801 (when (js2-match-char ?-)
5802 (js2-skip-line)
5803 (setf (js2-token-comment-type (js2-current-token)) 'html)
5804 (throw 'return js2-COMMENT)))
5805 (js2-unget-char))
5806 (if (js2-match-char ?<)
5807 (if (js2-match-char ?=)
5808 js2-ASSIGN_LSH
5809 js2-LSH)
5810 (if (js2-match-char ?=)
5811 js2-LE
5812 (throw 'return js2-LT))))
5813 (?>
5814 (if (js2-match-char ?>)
5815 (if (js2-match-char ?>)
5816 (if (js2-match-char ?=)
5817 js2-ASSIGN_URSH
5818 js2-URSH)
5819 (if (js2-match-char ?=)
5820 js2-ASSIGN_RSH
5821 js2-RSH))
5822 (if (js2-match-char ?=)
5823 js2-GE
5824 (throw 'return js2-GT))))
5825 (?*
5826 (if (js2-match-char ?=)
5827 js2-ASSIGN_MUL
5828 (throw 'return js2-MUL)))
5829 (?/
5830 ;; is it a // comment?
5831 (when (js2-match-char ?/)
5832 (setf (js2-token-beg token) (- js2-ts-cursor 2))
5833 (js2-skip-line)
5834 (setf (js2-token-comment-type token) 'line)
5835 ;; include newline so highlighting goes to end of window
5836 (incf (js2-token-end token))
5837 (throw 'return js2-COMMENT))
5838 ;; is it a /* comment?
5839 (when (js2-match-char ?*)
5840 (setf look-for-slash nil
5841 (js2-token-beg token) (- js2-ts-cursor 2)
5842 (js2-token-comment-type token)
5843 (if (js2-match-char ?*)
5844 (progn
5845 (setq look-for-slash t)
5846 'jsdoc)
5847 'block))
5848 (while t
5849 (setq c (js2-get-char))
5850 (cond
5851 ((eq c js2-EOF_CHAR)
5852 (setf (js2-token-end token) (1- js2-ts-cursor))
5853 (js2-report-error "msg.unterminated.comment")
5854 (throw 'return js2-COMMENT))
5855 ((eq c ?*)
5856 (setq look-for-slash t))
5857 ((eq c ?/)
5858 (if look-for-slash
5859 (js2-ts-return token js2-COMMENT)))
5860 (t
5861 (setf look-for-slash nil
5862 (js2-token-end token) js2-ts-cursor)))))
5863 (if (js2-match-char ?=)
5864 js2-ASSIGN_DIV
5865 (throw 'return js2-DIV)))
5866 (?#
5867 (when js2-skip-preprocessor-directives
5868 (js2-skip-line)
5869 (setf (js2-token-comment-type token) 'preprocessor
5870 (js2-token-end token) js2-ts-cursor)
5871 (throw 'return js2-COMMENT))
5872 (throw 'return js2-ERROR))
5873 (?%
5874 (if (js2-match-char ?=)
5875 js2-ASSIGN_MOD
5876 (throw 'return js2-MOD)))
5877 (?~
5878 (throw 'return js2-BITNOT))
5879 (?+
5880 (if (js2-match-char ?=)
5881 js2-ASSIGN_ADD
5882 (if (js2-match-char ?+)
5883 js2-INC
5884 (throw 'return js2-ADD))))
5885 (?-
5886 (cond
5887 ((js2-match-char ?=)
5888 (setq c js2-ASSIGN_SUB))
5889 ((js2-match-char ?-)
5890 (unless js2-ts-dirty-line
5891 ;; treat HTML end-comment after possible whitespace
5892 ;; after line start as comment-until-eol
5893 (when (js2-match-char ?>)
5894 (js2-skip-line)
5895 (setf (js2-token-comment-type (js2-current-token)) 'html)
5896 (throw 'return js2-COMMENT)))
5897 (setq c js2-DEC))
5898 (t
5899 (setq c js2-SUB)))
5900 (setq js2-ts-dirty-line t)
5901 c)
5902 (otherwise
5903 (js2-report-scan-error "msg.illegal.character")))))))
5904 (setf (js2-token-type token) tt)
5905 token))
5906
5907 (defsubst js2-string-to-number (str base)
5908 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5909 (condition-case nil
5910 (string-to-number str base)
5911 (overflow-error -1)))
5912
5913 (defun js2-read-regexp (start-tt)
5914 "Called by parser when it gets / or /= in literal context."
5915 (let (c err
5916 in-class ; inside a '[' .. ']' character-class
5917 flags
5918 (continue t)
5919 (token (js2-new-token 0)))
5920 (setq js2-ts-string-buffer nil)
5921 (if (eq start-tt js2-ASSIGN_DIV)
5922 ;; mis-scanned /=
5923 (js2-add-to-string ?=)
5924 (if (not (eq start-tt js2-DIV))
5925 (error "failed assertion")))
5926 (while (and (not err)
5927 (or (/= (setq c (js2-get-char)) ?/)
5928 in-class))
5929 (cond
5930 ((or (= c ?\n)
5931 (= c js2-EOF_CHAR))
5932 (setf (js2-token-end token) (1- js2-ts-cursor)
5933 err t
5934 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
5935 (js2-report-error "msg.unterminated.re.lit"))
5936 (t (cond
5937 ((= c ?\\)
5938 (js2-add-to-string c)
5939 (setq c (js2-get-char)))
5940 ((= c ?\[)
5941 (setq in-class t))
5942 ((= c ?\])
5943 (setq in-class nil)))
5944 (js2-add-to-string c))))
5945 (unless err
5946 (while continue
5947 (cond
5948 ((js2-match-char ?g)
5949 (push ?g flags))
5950 ((js2-match-char ?i)
5951 (push ?i flags))
5952 ((js2-match-char ?m)
5953 (push ?m flags))
5954 (t
5955 (setq continue nil))))
5956 (if (js2-alpha-p (js2-peek-char))
5957 (js2-report-scan-error "msg.invalid.re.flag" t
5958 js2-ts-cursor 1))
5959 (js2-set-string-from-buffer token))
5960 (js2-collect-string flags)))
5961
5962 (defun js2-get-first-xml-token ()
5963 (setq js2-ts-xml-open-tags-count 0
5964 js2-ts-is-xml-attribute nil
5965 js2-ts-xml-is-tag-content nil)
5966 (js2-unget-char)
5967 (js2-get-next-xml-token))
5968
5969 (defun js2-xml-discard-string (token)
5970 "Throw away the string in progress and flag an XML parse error."
5971 (setf js2-ts-string-buffer nil
5972 (js2-token-string token) nil)
5973 (js2-report-scan-error "msg.XML.bad.form" t))
5974
5975 (defun js2-get-next-xml-token ()
5976 (setq js2-ts-string-buffer nil) ; for recording the XML
5977 (let ((token (js2-new-token 0))
5978 c result)
5979 (setq result
5980 (catch 'return
5981 (while t
5982 (setq c (js2-get-char))
5983 (cond
5984 ((= c js2-EOF_CHAR)
5985 (throw 'return js2-ERROR))
5986 (js2-ts-xml-is-tag-content
5987 (case c
5988 (?>
5989 (js2-add-to-string c)
5990 (setq js2-ts-xml-is-tag-content nil
5991 js2-ts-is-xml-attribute nil))
5992 (?/
5993 (js2-add-to-string c)
5994 (when (eq ?> (js2-peek-char))
5995 (setq c (js2-get-char))
5996 (js2-add-to-string c)
5997 (setq js2-ts-xml-is-tag-content nil)
5998 (decf js2-ts-xml-open-tags-count)))
5999 (?{
6000 (js2-unget-char)
6001 (js2-set-string-from-buffer token)
6002 (throw 'return js2-XML))
6003 ((?\' ?\")
6004 (js2-add-to-string c)
6005 (unless (js2-read-quoted-string c token)
6006 (throw 'return js2-ERROR)))
6007 (?=
6008 (js2-add-to-string c)
6009 (setq js2-ts-is-xml-attribute t))
6010 ((? ?\t ?\r ?\n)
6011 (js2-add-to-string c))
6012 (t
6013 (js2-add-to-string c)
6014 (setq js2-ts-is-xml-attribute nil)))
6015 (when (and (not js2-ts-xml-is-tag-content)
6016 (zerop js2-ts-xml-open-tags-count))
6017 (js2-set-string-from-buffer token)
6018 (throw 'return js2-XMLEND)))
6019 (t
6020 ;; else not tag content
6021 (case c
6022 (?<
6023 (js2-add-to-string c)
6024 (setq c (js2-peek-char))
6025 (case c
6026 (?!
6027 (setq c (js2-get-char)) ;; skip !
6028 (js2-add-to-string c)
6029 (setq c (js2-peek-char))
6030 (case c
6031 (?-
6032 (setq c (js2-get-char)) ;; skip -
6033 (js2-add-to-string c)
6034 (if (eq c ?-)
6035 (progn
6036 (js2-add-to-string c)
6037 (unless (js2-read-xml-comment token)
6038 (throw 'return js2-ERROR)))
6039 (js2-xml-discard-string token)
6040 (throw 'return js2-ERROR)))
6041 (?\[
6042 (setq c (js2-get-char)) ;; skip [
6043 (js2-add-to-string c)
6044 (if (and (= (js2-get-char) ?C)
6045 (= (js2-get-char) ?D)
6046 (= (js2-get-char) ?A)
6047 (= (js2-get-char) ?T)
6048 (= (js2-get-char) ?A)
6049 (= (js2-get-char) ?\[))
6050 (progn
6051 (js2-add-to-string ?C)
6052 (js2-add-to-string ?D)
6053 (js2-add-to-string ?A)
6054 (js2-add-to-string ?T)
6055 (js2-add-to-string ?A)
6056 (js2-add-to-string ?\[)
6057 (unless (js2-read-cdata token)
6058 (throw 'return js2-ERROR)))
6059 (js2-xml-discard-string token)
6060 (throw 'return js2-ERROR)))
6061 (t
6062 (unless (js2-read-entity token)
6063 (throw 'return js2-ERROR))))
6064 ;; Allow bare CDATA section, e.g.:
6065 ;; let xml = <![CDATA[ foo bar baz ]]>;
6066 (when (zerop js2-ts-xml-open-tags-count)
6067 (throw 'return js2-XMLEND)))
6068 (??
6069 (setq c (js2-get-char)) ;; skip ?
6070 (js2-add-to-string c)
6071 (unless (js2-read-PI token)
6072 (throw 'return js2-ERROR)))
6073 (?/
6074 ;; end tag
6075 (setq c (js2-get-char)) ;; skip /
6076 (js2-add-to-string c)
6077 (when (zerop js2-ts-xml-open-tags-count)
6078 (js2-xml-discard-string token)
6079 (throw 'return js2-ERROR))
6080 (setq js2-ts-xml-is-tag-content t)
6081 (decf js2-ts-xml-open-tags-count))
6082 (t
6083 ;; start tag
6084 (setq js2-ts-xml-is-tag-content t)
6085 (incf js2-ts-xml-open-tags-count))))
6086 (?{
6087 (js2-unget-char)
6088 (js2-set-string-from-buffer token)
6089 (throw 'return js2-XML))
6090 (t
6091 (js2-add-to-string c))))))))
6092 (setf (js2-token-end token) js2-ts-cursor)
6093 (setf (js2-token-type token) result)
6094 result))
6095
6096 (defun js2-read-quoted-string (quote token)
6097 (let (c)
6098 (catch 'return
6099 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6100 (js2-add-to-string c)
6101 (if (eq c quote)
6102 (throw 'return t)))
6103 (js2-xml-discard-string token) ;; throw away string in progress
6104 nil)))
6105
6106 (defun js2-read-xml-comment (token)
6107 (let ((c (js2-get-char)))
6108 (catch 'return
6109 (while (/= c js2-EOF_CHAR)
6110 (catch 'continue
6111 (js2-add-to-string c)
6112 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6113 (setq c (js2-get-char))
6114 (js2-add-to-string c)
6115 (if (eq (js2-peek-char) ?>)
6116 (progn
6117 (setq c (js2-get-char)) ;; skip >
6118 (js2-add-to-string c)
6119 (throw 'return t))
6120 (throw 'continue nil)))
6121 (setq c (js2-get-char))))
6122 (js2-xml-discard-string token)
6123 nil)))
6124
6125 (defun js2-read-cdata (token)
6126 (let ((c (js2-get-char)))
6127 (catch 'return
6128 (while (/= c js2-EOF_CHAR)
6129 (catch 'continue
6130 (js2-add-to-string c)
6131 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6132 (setq c (js2-get-char))
6133 (js2-add-to-string c)
6134 (if (eq (js2-peek-char) ?>)
6135 (progn
6136 (setq c (js2-get-char)) ;; Skip >
6137 (js2-add-to-string c)
6138 (throw 'return t))
6139 (throw 'continue nil)))
6140 (setq c (js2-get-char))))
6141 (js2-xml-discard-string token)
6142 nil)))
6143
6144 (defun js2-read-entity (token)
6145 (let ((decl-tags 1)
6146 c)
6147 (catch 'return
6148 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6149 (js2-add-to-string c)
6150 (case c
6151 (?<
6152 (incf decl-tags))
6153 (?>
6154 (decf decl-tags)
6155 (if (zerop decl-tags)
6156 (throw 'return t)))))
6157 (js2-xml-discard-string token)
6158 nil)))
6159
6160 (defun js2-read-PI (token)
6161 "Scan an XML processing instruction."
6162 (let (c)
6163 (catch 'return
6164 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6165 (js2-add-to-string c)
6166 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6167 (setq c (js2-get-char)) ;; Skip >
6168 (js2-add-to-string c)
6169 (throw 'return t)))
6170 (js2-xml-discard-string token)
6171 nil)))
6172
6173 ;;; Highlighting
6174
6175 (defun js2-set-face (beg end face &optional record)
6176 "Fontify a region. If RECORD is non-nil, record for later."
6177 (when (plusp js2-highlight-level)
6178 (setq beg (min (point-max) beg)
6179 beg (max (point-min) beg)
6180 end (min (point-max) end)
6181 end (max (point-min) end))
6182 (if record
6183 (push (list beg end face) js2-mode-fontifications)
6184 (put-text-property beg end 'font-lock-face face))))
6185
6186 (defsubst js2-clear-face (beg end)
6187 (remove-text-properties beg end '(font-lock-face nil
6188 help-echo nil
6189 point-entered nil
6190 c-in-sws nil)))
6191
6192 (defconst js2-ecma-global-props
6193 (concat "^"
6194 (regexp-opt
6195 '("Infinity" "NaN" "undefined" "arguments") t)
6196 "$")
6197 "Value properties of the Ecma-262 Global Object.
6198 Shown at or above `js2-highlight-level' 2.")
6199
6200 ;; might want to add the name "arguments" to this list?
6201 (defconst js2-ecma-object-props
6202 (concat "^"
6203 (regexp-opt
6204 '("prototype" "__proto__" "__parent__") t)
6205 "$")
6206 "Value properties of the Ecma-262 Object constructor.
6207 Shown at or above `js2-highlight-level' 2.")
6208
6209 (defconst js2-ecma-global-funcs
6210 (concat
6211 "^"
6212 (regexp-opt
6213 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6214 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6215 "$")
6216 "Function properties of the Ecma-262 Global object.
6217 Shown at or above `js2-highlight-level' 2.")
6218
6219 (defconst js2-ecma-number-props
6220 (concat "^"
6221 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6222 "NEGATIVE_INFINITY"
6223 "POSITIVE_INFINITY") t)
6224 "$")
6225 "Properties of the Ecma-262 Number constructor.
6226 Shown at or above `js2-highlight-level' 2.")
6227
6228 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6229 "Properties of the Ecma-262 Date constructor.
6230 Shown at or above `js2-highlight-level' 2.")
6231
6232 (defconst js2-ecma-math-props
6233 (concat "^"
6234 (regexp-opt
6235 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6236 t)
6237 "$")
6238 "Properties of the Ecma-262 Math object.
6239 Shown at or above `js2-highlight-level' 2.")
6240
6241 (defconst js2-ecma-math-funcs
6242 (concat "^"
6243 (regexp-opt
6244 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6245 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6246 "$")
6247 "Function properties of the Ecma-262 Math object.
6248 Shown at or above `js2-highlight-level' 2.")
6249
6250 (defconst js2-ecma-function-props
6251 (concat
6252 "^"
6253 (regexp-opt
6254 '(;; properties of the Object prototype object
6255 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6256 "toLocaleString" "toString" "valueOf"
6257 ;; properties of the Function prototype object
6258 "apply" "call"
6259 ;; properties of the Array prototype object
6260 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6261 "splice" "unshift"
6262 ;; properties of the String prototype object
6263 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6264 "localeCompare" "match" "replace" "search" "split" "substring"
6265 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6266 "toUpperCase"
6267 ;; properties of the Number prototype object
6268 "toExponential" "toFixed" "toPrecision"
6269 ;; properties of the Date prototype object
6270 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6271 "getMinutes" "getMonth" "getSeconds" "getTime"
6272 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6273 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6274 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6275 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6276 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6277 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6278 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6279 "toTimeString" "toUTCString"
6280 ;; properties of the RegExp prototype object
6281 "exec" "test"
6282 ;; properties of the JSON prototype object
6283 "parse" "stringify"
6284 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6285 "toSource" "__defineGetter__" "__defineSetter__"
6286 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6287 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6288 t)
6289 "$")
6290 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6291 Shown at or above `js2-highlight-level' 3.")
6292
6293 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6294 (let ((target-name (and target
6295 (js2-name-node-p target)
6296 (js2-name-node-name target)))
6297 (prop-name (if prop (js2-name-node-name prop)))
6298 (level2 (>= js2-highlight-level 2))
6299 (level3 (>= js2-highlight-level 3)))
6300 (when level2
6301 (let ((face
6302 (if call-p
6303 (cond
6304 ((and target prop)
6305 (cond
6306 ((and level3 (string-match js2-ecma-function-props prop-name))
6307 'font-lock-builtin-face)
6308 ((and target-name prop)
6309 (cond
6310 ((string= target-name "Date")
6311 (if (string-match js2-ecma-date-props prop-name)
6312 'font-lock-builtin-face))
6313 ((string= target-name "Math")
6314 (if (string-match js2-ecma-math-funcs prop-name)
6315 'font-lock-builtin-face))))))
6316 (prop
6317 (if (string-match js2-ecma-global-funcs prop-name)
6318 'font-lock-builtin-face)))
6319 (cond
6320 ((and target prop)
6321 (cond
6322 ((string= target-name "Number")
6323 (if (string-match js2-ecma-number-props prop-name)
6324 'font-lock-constant-face))
6325 ((string= target-name "Math")
6326 (if (string-match js2-ecma-math-props prop-name)
6327 'font-lock-constant-face))))
6328 (prop
6329 (if (string-match js2-ecma-object-props prop-name)
6330 'font-lock-constant-face))))))
6331 (when face
6332 (let ((pos (+ (js2-node-pos parent) ; absolute
6333 (js2-node-pos prop)))) ; relative
6334 (js2-set-face pos
6335 (+ pos (js2-node-len prop))
6336 face 'record)))))))
6337
6338 (defun js2-parse-highlight-member-expr-node (node)
6339 "Perform syntax highlighting of EcmaScript built-in properties.
6340 The variable `js2-highlight-level' governs this highighting."
6341 (let (face target prop name pos end parent call-p callee)
6342 (cond
6343 ;; case 1: simple name, e.g. foo
6344 ((js2-name-node-p node)
6345 (setq name (js2-name-node-name node))
6346 ;; possible for name to be nil in rare cases - saw it when
6347 ;; running js2-mode on an elisp buffer. Might as well try to
6348 ;; make it so js2-mode never barfs.
6349 (when name
6350 (setq face (if (string-match js2-ecma-global-props name)
6351 'font-lock-constant-face))
6352 (when face
6353 (setq pos (js2-node-pos node)
6354 end (+ pos (js2-node-len node)))
6355 (js2-set-face pos end face 'record))))
6356 ;; case 2: property access or function call
6357 ((or (js2-prop-get-node-p node)
6358 ;; highlight function call if expr is a prop-get node
6359 ;; or a plain name (i.e. unqualified function call)
6360 (and (setq call-p (js2-call-node-p node))
6361 (setq callee (js2-call-node-target node)) ; separate setq!
6362 (or (js2-prop-get-node-p callee)
6363 (js2-name-node-p callee))))
6364 (setq parent node
6365 node (if call-p callee node))
6366 (if (and call-p (js2-name-node-p callee))
6367 (setq prop callee)
6368 (setq target (js2-prop-get-node-left node)
6369 prop (js2-prop-get-node-right node)))
6370 (cond
6371 ((js2-name-node-p prop)
6372 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6373 (js2-parse-highlight-prop-get parent target prop call-p))
6374 ((js2-name-node-p target)
6375 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6376 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6377
6378 (defun js2-parse-highlight-member-expr-fn-name (expr)
6379 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6380 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6381 We currently only handle the case where the last component is a prop-get
6382 of a simple name. Called before EXPR has a parent node."
6383 (let (pos
6384 (name (and (js2-prop-get-node-p expr)
6385 (js2-prop-get-node-right expr))))
6386 (when (js2-name-node-p name)
6387 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6388 (js2-node-pos name)))
6389 (+ pos (js2-node-len name))
6390 'font-lock-function-name-face
6391 'record))))
6392
6393 ;; source: http://jsdoc.sourceforge.net/
6394 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6395 ;; allows type specifications, and needs work before entering the wild.
6396
6397 (defconst js2-jsdoc-param-tag-regexp
6398 (concat "^\\s-*\\*+\\s-*\\(@"
6399 "\\(?:param\\|argument\\)"
6400 "\\)"
6401 "\\s-*\\({[^}]+}\\)?" ; optional type
6402 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6403 "\\>")
6404 "Matches jsdoc tags with optional type and optional param name.")
6405
6406 (defconst js2-jsdoc-typed-tag-regexp
6407 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6408 (regexp-opt
6409 '("enum"
6410 "extends"
6411 "field"
6412 "id"
6413 "implements"
6414 "lends"
6415 "mods"
6416 "requires"
6417 "return"
6418 "returns"
6419 "throw"
6420 "throws"))
6421 "\\)\\)\\s-*\\({[^}]+}\\)?")
6422 "Matches jsdoc tags with optional type.")
6423
6424 (defconst js2-jsdoc-arg-tag-regexp
6425 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6426 (regexp-opt
6427 '("alias"
6428 "augments"
6429 "borrows"
6430 "bug"
6431 "base"
6432 "config"
6433 "default"
6434 "define"
6435 "exception"
6436 "function"
6437 "member"
6438 "memberOf"
6439 "name"
6440 "namespace"
6441 "property"
6442 "since"
6443 "suppress"
6444 "this"
6445 "throws"
6446 "type"
6447 "version"))
6448 "\\)\\)\\s-+\\([^ \t]+\\)")
6449 "Matches jsdoc tags with a single argument.")
6450
6451 (defconst js2-jsdoc-empty-tag-regexp
6452 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6453 (regexp-opt
6454 '("addon"
6455 "author"
6456 "class"
6457 "const"
6458 "constant"
6459 "constructor"
6460 "constructs"
6461 "deprecated"
6462 "desc"
6463 "description"
6464 "event"
6465 "example"
6466 "exec"
6467 "export"
6468 "fileoverview"
6469 "final"
6470 "function"
6471 "hidden"
6472 "ignore"
6473 "implicitCast"
6474 "inheritDoc"
6475 "inner"
6476 "interface"
6477 "license"
6478 "noalias"
6479 "noshadow"
6480 "notypecheck"
6481 "override"
6482 "owner"
6483 "preserve"
6484 "preserveTry"
6485 "private"
6486 "protected"
6487 "public"
6488 "static"
6489 "supported"
6490 ))
6491 "\\)\\)\\s-*")
6492 "Matches empty jsdoc tags.")
6493
6494 (defconst js2-jsdoc-link-tag-regexp
6495 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6496 "Matches a jsdoc link or code tag.")
6497
6498 (defconst js2-jsdoc-see-tag-regexp
6499 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6500 "Matches a jsdoc @see tag.")
6501
6502 (defconst js2-jsdoc-html-tag-regexp
6503 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6504 "Matches a simple (no attributes) html start- or end-tag.")
6505
6506 (defun js2-jsdoc-highlight-helper ()
6507 (js2-set-face (match-beginning 1)
6508 (match-end 1)
6509 'js2-jsdoc-tag)
6510 (if (match-beginning 2)
6511 (if (save-excursion
6512 (goto-char (match-beginning 2))
6513 (= (char-after) ?{))
6514 (js2-set-face (1+ (match-beginning 2))
6515 (1- (match-end 2))
6516 'js2-jsdoc-type)
6517 (js2-set-face (match-beginning 2)
6518 (match-end 2)
6519 'js2-jsdoc-value)))
6520 (if (match-beginning 3)
6521 (js2-set-face (match-beginning 3)
6522 (match-end 3)
6523 'js2-jsdoc-value)))
6524
6525 (defun js2-highlight-jsdoc (ast)
6526 "Highlight doc comment tags."
6527 (let ((comments (js2-ast-root-comments ast))
6528 beg end)
6529 (save-excursion
6530 (dolist (node comments)
6531 (when (eq (js2-comment-node-format node) 'jsdoc)
6532 (setq beg (js2-node-abs-pos node)
6533 end (+ beg (js2-node-len node)))
6534 (save-restriction
6535 (narrow-to-region beg end)
6536 (dolist (re (list js2-jsdoc-param-tag-regexp
6537 js2-jsdoc-typed-tag-regexp
6538 js2-jsdoc-arg-tag-regexp
6539 js2-jsdoc-link-tag-regexp
6540 js2-jsdoc-see-tag-regexp
6541 js2-jsdoc-empty-tag-regexp))
6542 (goto-char beg)
6543 (while (re-search-forward re nil t)
6544 (js2-jsdoc-highlight-helper)))
6545 ;; simple highlighting for html tags
6546 (goto-char beg)
6547 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6548 (js2-set-face (match-beginning 1)
6549 (match-end 1)
6550 'js2-jsdoc-html-tag-delimiter)
6551 (js2-set-face (match-beginning 2)
6552 (match-end 2)
6553 'js2-jsdoc-html-tag-name)
6554 (js2-set-face (match-beginning 3)
6555 (match-end 3)
6556 'js2-jsdoc-html-tag-delimiter))))))))
6557
6558 (defun js2-highlight-assign-targets (_node left right)
6559 "Highlight function properties and external variables."
6560 (let (leftpos name)
6561 ;; highlight vars and props assigned function values
6562 (when (js2-function-node-p right)
6563 (cond
6564 ;; var foo = function() {...}
6565 ((js2-name-node-p left)
6566 (setq name left))
6567 ;; foo.bar.baz = function() {...}
6568 ((and (js2-prop-get-node-p left)
6569 (js2-name-node-p (js2-prop-get-node-right left)))
6570 (setq name (js2-prop-get-node-right left))))
6571 (when name
6572 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6573 (+ leftpos (js2-node-len name))
6574 'font-lock-function-name-face
6575 'record)))))
6576
6577 (defun js2-record-name-node (node)
6578 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6579 later. NODE must be a name node."
6580 (let ((leftpos (js2-node-abs-pos node)))
6581 (push (list node js2-current-scope
6582 leftpos
6583 (+ leftpos (js2-node-len node)))
6584 js2-recorded-identifiers)))
6585
6586 (defun js2-highlight-undeclared-vars ()
6587 "After entire parse is finished, look for undeclared variable references.
6588 We have to wait until entire buffer is parsed, since JavaScript permits var
6589 decls to occur after they're used.
6590
6591 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6592 it is considered declared."
6593 (let (name)
6594 (dolist (entry js2-recorded-identifiers)
6595 (destructuring-bind (name-node scope pos end) entry
6596 (setq name (js2-name-node-name name-node))
6597 (unless (or (member name js2-global-externs)
6598 (member name js2-default-externs)
6599 (member name js2-additional-externs)
6600 (js2-get-defining-scope scope name))
6601 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6602 'js2-external-variable))))
6603 (setq js2-recorded-identifiers nil)))
6604
6605 (defun js2-set-default-externs ()
6606 "Set the value of `js2-default-externs' based on the various
6607 `js2-include-?-externs' variables."
6608 (setq js2-default-externs
6609 (append js2-ecma-262-externs
6610 (if js2-include-browser-externs js2-browser-externs)
6611 (if js2-include-rhino-externs js2-rhino-externs)
6612 (if js2-include-node-externs js2-node-externs)
6613 (if (or js2-include-browser-externs js2-include-node-externs)
6614 js2-typed-array-externs))))
6615
6616 (defun js2-apply-jslint-globals ()
6617 (setq js2-additional-externs
6618 (nconc (js2-get-jslint-globals)
6619 js2-additional-externs)))
6620
6621 (defun js2-get-jslint-globals ()
6622 (loop for node in (js2-ast-root-comments js2-mode-ast)
6623 when (and (eq 'block (js2-comment-node-format node))
6624 (save-excursion
6625 (goto-char (js2-node-abs-pos node))
6626 (looking-at "/\\*global ")))
6627 append (js2-get-jslint-globals-in
6628 (match-end 0)
6629 (js2-node-abs-end node))))
6630
6631 (defun js2-get-jslint-globals-in (beg end)
6632 (let (res)
6633 (save-excursion
6634 (goto-char beg)
6635 (while (re-search-forward js2-mode-identifier-re end t)
6636 (let ((match (match-string 0)))
6637 (unless (member match '("true" "false"))
6638 (push match res)))))
6639 (nreverse res)))
6640
6641 ;;; IMenu support
6642
6643 ;; We currently only support imenu, but eventually should support speedbar and
6644 ;; possibly other browsing mechanisms.
6645
6646 ;; The basic strategy is to identify function assignment targets of the form
6647 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6648 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6649 ;; for imenu after parsing is finished.
6650
6651 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6652 ;; JavaScript, and the general problem is undecidable. However, several forms
6653 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6654 ;; include:
6655
6656 ;; function foo() -- function declaration
6657 ;; foo = function() -- function expression assigned to variable
6658 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6659 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6660 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6661 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6662 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6663 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6664 ;; function foo() {function bar() {...}} -- nested function
6665 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6666
6667 ;; This list boils down to a few forms that can be combined recursively.
6668 ;; Top-level named function declarations include both the left-hand (name)
6669 ;; and the right-hand (function value) expressions needed to produce an imenu
6670 ;; entry. The other "right-hand" forms we need to look for are:
6671 ;; - functions declared as props/getters/setters in object literals
6672 ;; - nested named function declarations
6673 ;; The "left-hand" expressions that functions can be assigned to include:
6674 ;; - local/global variables
6675 ;; - nested property-get expressions like a.b.c.d
6676 ;; - element gets like foo[10] or foo['bar'] where the index
6677 ;; expression can be trivially converted to a property name. They
6678 ;; effectively then become property gets.
6679
6680 ;; All the different definition types are canonicalized into the form
6681 ;; foo.bar.baz = position-of-function-keyword
6682
6683 ;; We need to build a trie-like structure for imenu. As an example,
6684 ;; consider the following JavaScript code:
6685
6686 ;; a = function() {...} // function at position 5
6687 ;; b = function() {...} // function at position 25
6688 ;; foo = function() {...} // function at position 100
6689 ;; foo.bar = function() {...} // function at position 200
6690 ;; foo.bar.baz = function() {...} // function at position 300
6691 ;; foo.bar.zab = function() {...} // function at position 400
6692
6693 ;; During parsing we accumulate an entry for each definition in
6694 ;; the variable `js2-imenu-recorder', like so:
6695
6696 ;; '((fn a 5)
6697 ;; (fn b 25)
6698 ;; (fn foo 100)
6699 ;; (fn foo bar 200)
6700 ;; (fn foo bar baz 300)
6701 ;; (fn foo bar zab 400))
6702
6703 ;; Where 'fn' is the respective function node.
6704 ;; After parsing these entries are merged into this alist-trie:
6705
6706 ;; '((a . 1)
6707 ;; (b . 2)
6708 ;; (foo (<definition> . 3)
6709 ;; (bar (<definition> . 6)
6710 ;; (baz . 100)
6711 ;; (zab . 200))))
6712
6713 ;; Note the wacky need for a <definition> name. The token can be anything
6714 ;; that isn't a valid JavaScript identifier, because you might make foo
6715 ;; a function and then start setting properties on it that are also functions.
6716
6717 (defun js2-prop-node-name (node)
6718 "Return the name of a node that may be a property-get/property-name.
6719 If NODE is not a valid name-node, string-node or integral number-node,
6720 returns nil. Otherwise returns the string name/value of the node."
6721 (cond
6722 ((js2-name-node-p node)
6723 (js2-name-node-name node))
6724 ((js2-string-node-p node)
6725 (js2-string-node-value node))
6726 ((and (js2-number-node-p node)
6727 (string-match "^[0-9]+$" (js2-number-node-value node)))
6728 (js2-number-node-value node))
6729 ((js2-this-node-p node)
6730 "this")))
6731
6732 (defun js2-node-qname-component (node)
6733 "Return the name of this node, if it contributes to a qname.
6734 Returns nil if the node doesn't contribute."
6735 (copy-sequence
6736 (or (js2-prop-node-name node)
6737 (if (and (js2-function-node-p node)
6738 (js2-function-node-name node))
6739 (js2-name-node-name (js2-function-node-name node))))))
6740
6741 (defun js2-record-imenu-entry (fn-node qname pos)
6742 "Add an entry to `js2-imenu-recorder'.
6743 FN-NODE should be the current item's function node.
6744
6745 Associate FN-NODE with its QNAME for later lookup.
6746 This is used in postprocessing the chain list. For each chain, we find
6747 the parent function, look up its qname, then prepend a copy of it to the chain."
6748 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6749 (unless js2-imenu-function-map
6750 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6751 (puthash fn-node qname js2-imenu-function-map))
6752
6753 (defun js2-record-imenu-functions (node &optional var)
6754 "Record function definitions for imenu.
6755 NODE is a function node or an object literal.
6756 VAR, if non-nil, is the expression that NODE is being assigned to.
6757 When passed arguments of wrong type, does nothing."
6758 (when js2-parse-ide-mode
6759 (let ((fun-p (js2-function-node-p node))
6760 qname fname-node)
6761 (cond
6762 ;; non-anonymous function declaration?
6763 ((and fun-p
6764 (not var)
6765 (setq fname-node (js2-function-node-name node)))
6766 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6767 ;; for remaining forms, compute left-side tree branch first
6768 ((and var (setq qname (js2-compute-nested-prop-get var)))
6769 (cond
6770 ;; foo.bar.baz = function
6771 (fun-p
6772 (js2-record-imenu-entry node qname (js2-node-pos node)))
6773 ;; foo.bar.baz = object-literal
6774 ;; look for nested functions: {a: {b: function() {...} }}
6775 ((js2-object-node-p node)
6776 ;; Node position here is still absolute, since the parser
6777 ;; passes the assignment target and value expressions
6778 ;; to us before they are added as children of the assignment node.
6779 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6780
6781 (defun js2-compute-nested-prop-get (node)
6782 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6783 component nodes as a list. Otherwise return nil. Element-gets are treated
6784 as property-gets if the index expression is a string, or a positive integer."
6785 (let (left right head)
6786 (cond
6787 ((or (js2-name-node-p node)
6788 (js2-this-node-p node))
6789 (list node))
6790 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6791 ((js2-prop-get-node-p node) ; foo.bar
6792 (setq left (js2-prop-get-node-left node)
6793 right (js2-prop-get-node-right node))
6794 (if (setq head (js2-compute-nested-prop-get left))
6795 (nconc head (list right))))
6796 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6797 (setq left (js2-elem-get-node-target node)
6798 right (js2-elem-get-node-element node))
6799 (if (or (js2-string-node-p right) ; ['bar']
6800 (and (js2-number-node-p right) ; [10]
6801 (string-match "^[0-9]+$"
6802 (js2-number-node-value right))))
6803 (if (setq head (js2-compute-nested-prop-get left))
6804 (nconc head (list right))))))))
6805
6806 (defun js2-record-object-literal (node qname pos)
6807 "Recursively process an object literal looking for functions.
6808 NODE is an object literal that is the right-hand child of an assignment
6809 expression. QNAME is a list of nodes representing the assignment target,
6810 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6811 POS is the absolute position of the node.
6812 We do a depth-first traversal of NODE. For any functions we find,
6813 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6814 (let (right)
6815 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6816 (let ((left (js2-infix-node-left e))
6817 ;; Element positions are relative to the parent position.
6818 (pos (+ pos (js2-node-pos e))))
6819 (cond
6820 ;; foo: function() {...}
6821 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6822 (when (js2-prop-node-name left)
6823 ;; As a policy decision, we record the position of the property,
6824 ;; not the position of the `function' keyword, since the property
6825 ;; is effectively the name of the function.
6826 (js2-record-imenu-entry right (append qname (list left)) pos)))
6827 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6828 ((js2-object-node-p right)
6829 (js2-record-object-literal right
6830 (append qname (list (js2-infix-node-left e)))
6831 (+ pos (js2-node-pos right)))))))))
6832
6833 (defun js2-node-top-level-decl-p (node)
6834 "Return t if NODE's name is defined in the top-level scope.
6835 Also returns t if NODE's name is not defined in any scope, since it implies
6836 that it's an external variable, which must also be in the top-level scope."
6837 (let* ((name (js2-prop-node-name node))
6838 (this-scope (js2-node-get-enclosing-scope node))
6839 defining-scope)
6840 (cond
6841 ((js2-this-node-p node)
6842 nil)
6843 ((null this-scope)
6844 t)
6845 ((setq defining-scope (js2-get-defining-scope this-scope name))
6846 (js2-ast-root-p defining-scope))
6847 (t t))))
6848
6849 (defun js2-wrapper-function-p (node)
6850 "Return t if NODE is a function expression that's immediately invoked.
6851 NODE must be `js2-function-node'."
6852 (let ((parent (js2-node-parent node)))
6853 (or
6854 ;; function(){...}();
6855 (js2-call-node-p parent)
6856 (and (js2-paren-node-p parent)
6857 ;; (function(){...})();
6858 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6859 ;; (function(){...}).call(this);
6860 (and (js2-prop-get-node-p parent)
6861 (member (js2-name-node-name (js2-prop-get-node-right parent))
6862 '("call" "apply"))
6863 (js2-call-node-p (js2-node-parent parent))))))))
6864
6865 (defun js2-browse-postprocess-chains (entries)
6866 "Modify function-declaration name chains after parsing finishes.
6867 Some of the information is only available after the parse tree is complete.
6868 For instance, processing a nested scope requires a parent function node."
6869 (let (result fn parent-qname p elem)
6870 (dolist (entry entries)
6871 ;; function node goes first
6872 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6873 ;; Examine head's defining scope:
6874 ;; Pre-processed chain, or top-level/external, keep as-is.
6875 (if (or (stringp head) (js2-node-top-level-decl-p head))
6876 (push chain result)
6877 (when (js2-this-node-p head)
6878 (setq chain (cdr chain))) ; discard this-node
6879 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6880 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6881 (when (eq parent-qname 'not-found)
6882 ;; anonymous function expressions are not recorded
6883 ;; during the parse, so we need to handle this case here
6884 (setq parent-qname
6885 (if (js2-wrapper-function-p fn)
6886 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6887 (if (js2-ast-root-p grandparent)
6888 nil
6889 (gethash grandparent js2-imenu-function-map 'skip)))
6890 'skip))
6891 (puthash fn parent-qname js2-imenu-function-map))
6892 (unless (eq parent-qname 'skip)
6893 ;; prefix parent fn qname to this chain.
6894 (let ((qname (append parent-qname chain)))
6895 (puthash current-fn (butlast qname) js2-imenu-function-map)
6896 (push qname result)))))))
6897 ;; finally replace each node in each chain with its name.
6898 (dolist (chain result)
6899 (setq p chain)
6900 (while p
6901 (if (js2-node-p (setq elem (car p)))
6902 (setcar p (js2-node-qname-component elem)))
6903 (setq p (cdr p))))
6904 result))
6905
6906 ;; Merge name chains into a trie-like tree structure of nested lists.
6907 ;; To simplify construction of the trie, we first build it out using the rule
6908 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6909 ;; [key, num-or-list]. The second element can be a number; if so, this key
6910 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6911 ;; associated with the key at this level.) Otherwise the second element is
6912 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6913 ;; a simple recursive formulation.
6914 ;;
6915 ;; js2-mode is building the data structure for imenu. The imenu documentation
6916 ;; claims that it's the structure above, but in practice it wants the children
6917 ;; at the same list level as the key for that level, which is how I've drawn
6918 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6919 ;; list wrapper around the children at each level.
6920 ;;
6921 ;; A completed nested imenu-alist entry looks like this:
6922 ;; '(("foo"
6923 ;; ("<definition>" . 7)
6924 ;; ("bar"
6925 ;; ("a" . 40)
6926 ;; ("b" . 60))))
6927 ;;
6928 ;; In particular, the documentation for `imenu--index-alist' says that
6929 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6930 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6931
6932 (defun js2-treeify (lst)
6933 "Convert (a b c d) to (a ((b ((c d)))))."
6934 (if (null (cddr lst)) ; list length <= 2
6935 lst
6936 (list (car lst) (list (js2-treeify (cdr lst))))))
6937
6938 (defun js2-build-alist-trie (chains trie)
6939 "Merge declaration name chains into a trie-like alist structure for imenu.
6940 CHAINS is the qname chain list produced during parsing. TRIE is a
6941 list of elements built up so far."
6942 (let (head tail pos branch kids)
6943 (dolist (chain chains)
6944 (setq head (car chain)
6945 tail (cdr chain)
6946 pos (if (numberp (car tail)) (car tail))
6947 branch (js2-find-if (lambda (n)
6948 (string= (car n) head))
6949 trie)
6950 kids (second branch))
6951 (cond
6952 ;; case 1: this key isn't in the trie yet
6953 ((null branch)
6954 (if trie
6955 (setcdr (last trie) (list (js2-treeify chain)))
6956 (setq trie (list (js2-treeify chain)))))
6957 ;; case 2: key is present with a single number entry: replace w/ list
6958 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6959 ;; ("<definition>" 20)))
6960 ((numberp kids)
6961 (setcar (cdr branch)
6962 (list (list "<definition-1>" kids)
6963 (if pos
6964 (list "<definition-2>" pos)
6965 (js2-treeify tail)))))
6966 ;; case 3: key is there (with kids), and we're a number entry
6967 (pos
6968 (setcdr (last kids)
6969 (list
6970 (list (format "<definition-%d>"
6971 (1+ (loop for kid in kids
6972 count (eq ?< (aref (car kid) 0)))))
6973 pos))))
6974 ;; case 4: key is there with kids, need to merge in our chain
6975 (t
6976 (js2-build-alist-trie (list tail) kids))))
6977 trie))
6978
6979 (defun js2-flatten-trie (trie)
6980 "Convert TRIE to imenu-format.
6981 Recurses through nodes, and for each one whose second element is a list,
6982 appends the list's flattened elements to the current element. Also
6983 changes the tails into conses. For instance, this pre-flattened trie
6984
6985 '(a ((b 20)
6986 (c ((d 30)
6987 (e 40)))))
6988
6989 becomes
6990
6991 '(a (b . 20)
6992 (c (d . 30)
6993 (e . 40)))
6994
6995 Note that the root of the trie has no key, just a list of chains.
6996 This is also true for the value of any key with multiple children,
6997 e.g. key 'c' in the example above."
6998 (cond
6999 ((listp (car trie))
7000 (mapcar #'js2-flatten-trie trie))
7001 (t
7002 (if (numberp (second trie))
7003 (cons (car trie) (second trie))
7004 ;; else pop list and append its kids
7005 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7006
7007 (defun js2-build-imenu-index ()
7008 "Turn `js2-imenu-recorder' into an imenu data structure."
7009 (unless (eq js2-imenu-recorder 'empty)
7010 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7011 (result (js2-build-alist-trie chains nil)))
7012 (js2-flatten-trie result))))
7013
7014 (defun js2-test-print-chains (chains)
7015 "Print a list of qname chains.
7016 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7017 i.e. one or more nodes, and an integer position as the list tail."
7018 (mapconcat (lambda (chain)
7019 (concat "("
7020 (mapconcat (lambda (elem)
7021 (if (js2-node-p elem)
7022 (or (js2-node-qname-component elem)
7023 "nil")
7024 (number-to-string elem)))
7025 chain
7026 " ")
7027 ")"))
7028 chains
7029 "\n"))
7030
7031 ;;; Parser
7032
7033 (defconst js2-version "1.8.5"
7034 "Version of JavaScript supported.")
7035
7036 (defun js2-record-face (face &optional token)
7037 "Record a style run of FACE for TOKEN or the current token."
7038 (unless token (setq token (js2-current-token)))
7039 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7040
7041 (defsubst js2-node-end (n)
7042 "Computes the absolute end of node N.
7043 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7044 is only true until the node is added to its parent; i.e., while parsing."
7045 (+ (js2-node-pos n)
7046 (js2-node-len n)))
7047
7048 (defun js2-record-comment (token)
7049 "Record a comment in `js2-scanned-comments'."
7050 (let ((ct (js2-token-comment-type token))
7051 (beg (js2-token-beg token))
7052 (end (js2-token-end token)))
7053 (push (make-js2-comment-node :len (- end beg)
7054 :format ct)
7055 js2-scanned-comments)
7056 (when js2-parse-ide-mode
7057 (js2-record-face (if (eq ct 'jsdoc)
7058 'font-lock-doc-face
7059 'font-lock-comment-face)
7060 token)
7061 (when (memq ct '(html preprocessor))
7062 ;; Tell cc-engine the bounds of the comment.
7063 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7064
7065 (defun js2-peek-token ()
7066 "Return the next token type without consuming it.
7067 If `js2-ti-lookahead' is positive, return the type of next token
7068 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7069 (if (not (zerop js2-ti-lookahead))
7070 (js2-token-type
7071 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7072 (let ((tt (js2-get-token-internal)))
7073 (js2-unget-token)
7074 tt)))
7075
7076 (defalias 'js2-next-token 'js2-get-token)
7077
7078 (defun js2-match-token (match &optional dont-unget)
7079 "Get next token and return t if it matches MATCH, a bytecode.
7080 Returns nil and consumes nothing if MATCH is not the next token."
7081 (if (/= (js2-get-token) match)
7082 (ignore (unless dont-unget (js2-unget-token)))
7083 t))
7084
7085 (defun js2-match-contextual-kwd (name)
7086 "Consume and return t if next token is `js2-NAME', and its
7087 string is NAME. Returns nil and keeps current token otherwise."
7088 (if (or (/= (js2-get-token) js2-NAME)
7089 (not (string= (js2-current-token-string) name)))
7090 (progn
7091 (js2-unget-token)
7092 nil)
7093 (js2-record-face 'font-lock-keyword-face)
7094 t))
7095
7096 (defun js2-valid-prop-name-token (tt)
7097 (or (= tt js2-NAME)
7098 (and js2-allow-keywords-as-property-names
7099 (plusp tt)
7100 (or (= tt js2-RESERVED)
7101 (aref js2-kwd-tokens tt)))))
7102
7103 (defun js2-match-prop-name ()
7104 "Consume token and return t if next token is a valid property name.
7105 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7106 is non-nil and it's a keyword token."
7107 (if (js2-valid-prop-name-token (js2-get-token))
7108 t
7109 (js2-unget-token)
7110 nil))
7111
7112 (defun js2-must-match-prop-name (msg-id &optional pos len)
7113 (if (js2-match-prop-name)
7114 t
7115 (js2-report-error msg-id nil pos len)
7116 nil))
7117
7118 (defun js2-peek-token-or-eol ()
7119 "Return js2-EOL if the next token immediately follows a newline.
7120 Else returns the next token. Used in situations where we don't
7121 consider certain token types valid if they are preceded by a newline.
7122 One example is the postfix ++ or -- operator, which has to be on the
7123 same line as its operand."
7124 (let ((tt (js2-get-token))
7125 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7126 (js2-unget-token)
7127 (if follows-eol
7128 js2-EOL
7129 tt)))
7130
7131 (defun js2-must-match (token msg-id &optional pos len)
7132 "Match next token to token code TOKEN, or record a syntax error.
7133 MSG-ID is the error message to report if the match fails.
7134 Returns t on match, nil if no match."
7135 (if (js2-match-token token t)
7136 t
7137 (js2-report-error msg-id nil pos len)
7138 (js2-unget-token)
7139 nil))
7140
7141 (defun js2-must-match-name (msg-id)
7142 (if (js2-match-token js2-NAME t)
7143 t
7144 (if (eq (js2-current-token-type) js2-RESERVED)
7145 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7146 (js2-report-error msg-id)
7147 (js2-unget-token))
7148 nil))
7149
7150 (defsubst js2-inside-function ()
7151 (plusp js2-nesting-of-function))
7152
7153 (defun js2-set-requires-activation ()
7154 (if (js2-function-node-p js2-current-script-or-fn)
7155 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7156
7157 (defun js2-check-activation-name (name _token)
7158 (when (js2-inside-function)
7159 ;; skip language-version 1.2 check from Rhino
7160 (if (or (string= "arguments" name)
7161 (and js2-compiler-activation-names ; only used in codegen
7162 (gethash name js2-compiler-activation-names)))
7163 (js2-set-requires-activation))))
7164
7165 (defun js2-set-is-generator ()
7166 (let ((fn-node js2-current-script-or-fn))
7167 (when (and (js2-function-node-p fn-node)
7168 (not (js2-function-node-generator-type fn-node)))
7169 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7170
7171 (defun js2-must-have-xml ()
7172 (unless js2-compiler-xml-available
7173 (js2-report-error "msg.XML.not.available")))
7174
7175 (defun js2-push-scope (scope)
7176 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7177 (assert (js2-scope-p scope))
7178 (assert (null (js2-scope-parent-scope scope)))
7179 (assert (not (eq js2-current-scope scope)))
7180 (setf (js2-scope-parent-scope scope) js2-current-scope
7181 js2-current-scope scope))
7182
7183 (defsubst js2-pop-scope ()
7184 (setq js2-current-scope
7185 (js2-scope-parent-scope js2-current-scope)))
7186
7187 (defun js2-enter-loop (loop-node)
7188 (push loop-node js2-loop-set)
7189 (push loop-node js2-loop-and-switch-set)
7190 (js2-push-scope loop-node)
7191 ;; Tell the current labeled statement (if any) its statement,
7192 ;; and set the jump target of the first label to the loop.
7193 ;; These are used in `js2-parse-continue' to verify that the
7194 ;; continue target is an actual labeled loop. (And for codegen.)
7195 (when js2-labeled-stmt
7196 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7197 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7198 js2-labeled-stmt))) loop-node)))
7199
7200 (defun js2-exit-loop ()
7201 (pop js2-loop-set)
7202 (pop js2-loop-and-switch-set)
7203 (js2-pop-scope))
7204
7205 (defsubst js2-enter-switch (switch-node)
7206 (push switch-node js2-loop-and-switch-set))
7207
7208 (defsubst js2-exit-switch ()
7209 (pop js2-loop-and-switch-set))
7210
7211 (defun js2-parse (&optional buf cb)
7212 "Tell the js2 parser to parse a region of JavaScript.
7213
7214 BUF is a buffer or buffer name containing the code to parse.
7215 Call `narrow-to-region' first to parse only part of the buffer.
7216
7217 The returned AST root node is given some additional properties:
7218 `node-count' - total number of nodes in the AST
7219 `buffer' - BUF. The buffer it refers to may change or be killed,
7220 so the value is not necessarily reliable.
7221
7222 An optional callback CB can be specified to report parsing
7223 progress. If `(functionp CB)' returns t, it will be called with
7224 the current line number once before parsing begins, then again
7225 each time the lexer reaches a new line number.
7226
7227 CB can also be a list of the form `(symbol cb ...)' to specify
7228 multiple callbacks with different criteria. Each symbol is a
7229 criterion keyword, and the following element is the callback to
7230 call
7231
7232 :line - called whenever the line number changes
7233 :token - called for each new token consumed
7234
7235 The list of criteria could be extended to include entering or
7236 leaving a statement, an expression, or a function definition."
7237 (if (and cb (not (functionp cb)))
7238 (error "criteria callbacks not yet implemented"))
7239 (let ((inhibit-point-motion-hooks t)
7240 (js2-compiler-xml-available (>= js2-language-version 160))
7241 ;; This is a recursive-descent parser, so give it a big stack.
7242 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7243 (max-specpdl-size (max max-specpdl-size 3000))
7244 (case-fold-search nil)
7245 ast)
7246 (with-current-buffer (or buf (current-buffer))
7247 (setq js2-scanned-comments nil
7248 js2-parsed-errors nil
7249 js2-parsed-warnings nil
7250 js2-imenu-recorder nil
7251 js2-imenu-function-map nil
7252 js2-label-set nil)
7253 (js2-init-scanner)
7254 (setq ast (with-silent-modifications
7255 (js2-do-parse)))
7256 (unless js2-ts-hit-eof
7257 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7258 (setf (js2-ast-root-errors ast) js2-parsed-errors
7259 (js2-ast-root-warnings ast) js2-parsed-warnings)
7260 ;; if we didn't find any declarations, put a dummy in this list so we
7261 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7262 (unless js2-imenu-recorder
7263 (setq js2-imenu-recorder 'empty))
7264 (run-hooks 'js2-parse-finished-hook)
7265 ast)))
7266
7267 ;; Corresponds to Rhino's Parser.parse() method.
7268 (defun js2-do-parse ()
7269 "Parse current buffer starting from current point.
7270 Scanner should be initialized."
7271 (let ((pos js2-ts-cursor)
7272 (end js2-ts-cursor) ; in case file is empty
7273 root n tt)
7274 ;; initialize buffer-local parsing vars
7275 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7276 js2-current-script-or-fn root
7277 js2-current-scope root
7278 js2-nesting-of-function 0
7279 js2-labeled-stmt nil
7280 js2-recorded-identifiers nil) ; for js2-highlight
7281 (while (/= (setq tt (js2-get-token)) js2-EOF)
7282 (if (= tt js2-FUNCTION)
7283 (progn
7284 (setq n (if js2-called-by-compile-function
7285 (js2-parse-function-expr)
7286 (js2-parse-function-stmt))))
7287 ;; not a function - parse a statement
7288 (js2-unget-token)
7289 (setq n (js2-parse-statement)))
7290 ;; add function or statement to script
7291 (setq end (js2-node-end n))
7292 (js2-block-node-push root n))
7293 ;; add comments to root in lexical order
7294 (when js2-scanned-comments
7295 ;; if we find a comment beyond end of normal kids, use its end
7296 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7297 (dolist (comment js2-scanned-comments)
7298 (push comment (js2-ast-root-comments root))
7299 (js2-node-add-children root comment)))
7300 (setf (js2-node-len root) (- end pos))
7301 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7302 ;; Give extensions a chance to muck with things before highlighting starts.
7303 (let ((js2-additional-externs js2-additional-externs))
7304 (save-excursion
7305 (run-hooks 'js2-post-parse-callbacks))
7306 (js2-highlight-undeclared-vars))
7307 root))
7308
7309 (defun js2-parse-function-closure-body (fn-node)
7310 "Parse a JavaScript 1.8 function closure body."
7311 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7312 (if js2-ts-hit-eof
7313 (js2-report-error "msg.no.brace.body" nil
7314 (js2-node-pos fn-node)
7315 (- js2-ts-cursor (js2-node-pos fn-node)))
7316 (js2-node-add-children fn-node
7317 (setf (js2-function-node-body fn-node)
7318 (js2-parse-expr t))))))
7319
7320 (defun js2-parse-function-body (fn-node)
7321 (js2-must-match js2-LC "msg.no.brace.body"
7322 (js2-node-pos fn-node)
7323 (- js2-ts-cursor (js2-node-pos fn-node)))
7324 (let ((pos (js2-current-token-beg)) ; LC position
7325 (pn (make-js2-block-node)) ; starts at LC position
7326 tt
7327 end)
7328 (incf js2-nesting-of-function)
7329 (unwind-protect
7330 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7331 (= tt js2-EOF)
7332 (= tt js2-RC)))
7333 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7334 (js2-parse-statement)
7335 (js2-get-token)
7336 (js2-parse-function-stmt))))
7337 (decf js2-nesting-of-function))
7338 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7339 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7340 (setq end (js2-current-token-end)))
7341 (setf (js2-node-pos pn) pos
7342 (js2-node-len pn) (- end pos))
7343 (setf (js2-function-node-body fn-node) pn)
7344 (js2-node-add-children fn-node pn)
7345 pn))
7346
7347 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7348 "Declare and fontify destructuring parameters inside NODE.
7349 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7350 (cond
7351 ((js2-name-node-p node)
7352 (let (leftpos)
7353 (js2-define-symbol decl-type (js2-name-node-name node)
7354 node ignore-not-in-block)
7355 (when face
7356 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7357 (+ leftpos (js2-node-len node))
7358 face 'record))))
7359 ((js2-object-node-p node)
7360 (dolist (elem (js2-object-node-elems node))
7361 (js2-define-destruct-symbols
7362 (if (js2-object-prop-node-p elem)
7363 (js2-object-prop-node-right elem)
7364 ;; abbreviated destructuring {a, b}
7365 elem)
7366 decl-type face ignore-not-in-block)))
7367 ((js2-array-node-p node)
7368 (dolist (elem (js2-array-node-elems node))
7369 (when elem
7370 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7371 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7372 (js2-node-len node)))))
7373
7374 (defun js2-parse-function-params (function-type fn-node pos)
7375 (if (js2-match-token js2-RP)
7376 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7377 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7378 (eq (js2-current-token-type) js2-NAME)))
7379 params param default-found rest-param-at)
7380 (when paren-free-arrow
7381 (js2-unget-token))
7382 (loop for tt = (js2-peek-token)
7383 do
7384 (cond
7385 ;; destructuring param
7386 ((and (not paren-free-arrow)
7387 (or (= tt js2-LB) (= tt js2-LC)))
7388 (js2-get-token)
7389 (when default-found
7390 (js2-report-error "msg.no.default.after.default.param"))
7391 (setq param (js2-parse-destruct-primary-expr))
7392 (js2-define-destruct-symbols param
7393 js2-LP
7394 'js2-function-param)
7395 (push param params))
7396 ;; variable name
7397 (t
7398 (when (and (>= js2-language-version 200)
7399 (not paren-free-arrow)
7400 (js2-match-token js2-TRIPLEDOT)
7401 (not rest-param-at))
7402 ;; to report errors if there are more parameters
7403 (setq rest-param-at (length params)))
7404 (js2-must-match-name "msg.no.parm")
7405 (js2-record-face 'js2-function-param)
7406 (setq param (js2-create-name-node))
7407 (js2-define-symbol js2-LP (js2-current-token-string) param)
7408 ;; default parameter value
7409 (when (or (and default-found
7410 (not rest-param-at)
7411 (js2-must-match js2-ASSIGN
7412 "msg.no.default.after.default.param"
7413 (js2-node-pos param)
7414 (js2-node-len param)))
7415 (and (>= js2-language-version 200)
7416 (js2-match-token js2-ASSIGN)))
7417 (assert (not paren-free-arrow))
7418 (let* ((pos (js2-node-pos param))
7419 (tt (js2-current-token-type))
7420 (op-pos (- (js2-current-token-beg) pos))
7421 (left param)
7422 (right (js2-parse-assign-expr))
7423 (len (- (js2-node-end right) pos)))
7424 (setq param (make-js2-assign-node
7425 :type tt :pos pos :len len :op-pos op-pos
7426 :left left :right right)
7427 default-found t)
7428 (js2-node-add-children param left right)))
7429 (push param params)))
7430 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7431 (js2-report-error "msg.param.after.rest" nil
7432 (js2-node-pos param) (js2-node-len param)))
7433 while
7434 (js2-match-token js2-COMMA))
7435 (when (and (not paren-free-arrow)
7436 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7437 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7438 (when rest-param-at
7439 (setf (js2-function-node-rest-p fn-node) t))
7440 (dolist (p params)
7441 (js2-node-add-children fn-node p)
7442 (push p (js2-function-node-params fn-node))))))
7443
7444 (defun js2-check-inconsistent-return-warning (fn-node name)
7445 "Possibly show inconsistent-return warning.
7446 Last token scanned is the close-curly for the function body."
7447 (when (and js2-mode-show-strict-warnings
7448 js2-strict-inconsistent-return-warning
7449 (not (js2-has-consistent-return-usage
7450 (js2-function-node-body fn-node))))
7451 ;; Have it extend from close-curly to bol or beginning of block.
7452 (let ((pos (save-excursion
7453 (goto-char (js2-current-token-end))
7454 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7455 (point-at-bol))))
7456 (end (js2-current-token-end)))
7457 (if (plusp (js2-name-node-length name))
7458 (js2-add-strict-warning "msg.no.return.value"
7459 (js2-name-node-name name) pos end)
7460 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7461
7462 (defun js2-parse-function-stmt ()
7463 (let ((pos (js2-current-token-beg))
7464 (star-p (js2-match-token js2-MUL)))
7465 (js2-must-match-name "msg.unnamed.function.stmt")
7466 (let ((name (js2-create-name-node t))
7467 pn member-expr)
7468 (cond
7469 ((js2-match-token js2-LP)
7470 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7471 (js2-allow-member-expr-as-function-name
7472 (setq member-expr (js2-parse-member-expr-tail nil name))
7473 (js2-parse-highlight-member-expr-fn-name member-expr)
7474 (js2-must-match js2-LP "msg.no.paren.parms")
7475 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7476 (js2-function-node-member-expr pn) member-expr)
7477 pn)
7478 (t
7479 (js2-report-error "msg.no.paren.parms")
7480 (make-js2-error-node))))))
7481
7482 (defun js2-parse-function-expr ()
7483 (let ((pos (js2-current-token-beg))
7484 (star-p (js2-match-token js2-MUL))
7485 name)
7486 (when (js2-match-token js2-NAME)
7487 (setq name (js2-create-name-node t)))
7488 (js2-must-match js2-LP "msg.no.paren.parms")
7489 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7490
7491 (defun js2-parse-function (function-type pos star-p &optional name)
7492 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7493 beginning of the first token (function keyword, unless it's an
7494 arrow function), NAME is js2-name-node."
7495 (let (fn-node lp)
7496 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7497 (setq lp (js2-current-token-beg)))
7498 (setf fn-node (make-js2-function-node :pos pos
7499 :name name
7500 :form function-type
7501 :lp (if lp (- lp pos))
7502 :generator-type (and star-p 'STAR)))
7503 (when name
7504 (js2-set-face (js2-node-pos name) (js2-node-end name)
7505 'font-lock-function-name-face 'record)
7506 (when (plusp (js2-name-node-length name))
7507 ;; Function statements define a symbol in the enclosing scope
7508 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7509 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7510 ;; 1. Nested functions are not affected by the dynamic scope flag
7511 ;; as dynamic scope is already a parent of their scope.
7512 ;; 2. Functions defined under the with statement also immune to
7513 ;; this setup, in which case dynamic scope is ignored in favor
7514 ;; of the with object.
7515 (setf (js2-function-node-ignore-dynamic fn-node) t))
7516 ;; dynamically bind all the per-function variables
7517 (let ((js2-current-script-or-fn fn-node)
7518 (js2-current-scope fn-node)
7519 (js2-nesting-of-with 0)
7520 (js2-end-flags 0)
7521 js2-label-set
7522 js2-loop-set
7523 js2-loop-and-switch-set)
7524 (js2-parse-function-params function-type fn-node pos)
7525 (when (eq function-type 'FUNCTION_ARROW)
7526 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7527 (if (and (>= js2-language-version 180)
7528 (/= (js2-peek-token) js2-LC))
7529 (js2-parse-function-closure-body fn-node)
7530 (js2-parse-function-body fn-node))
7531 (js2-check-inconsistent-return-warning fn-node name)
7532
7533 (when name
7534 (js2-node-add-children fn-node name)
7535 ;; Function expressions define a name only in the body of the
7536 ;; function, and only if not hidden by a parameter name
7537 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7538 (null (js2-scope-get-symbol js2-current-scope
7539 (js2-name-node-name name))))
7540 (js2-define-symbol js2-FUNCTION
7541 (js2-name-node-name name)
7542 fn-node))
7543 (when (eq function-type 'FUNCTION_STATEMENT)
7544 (js2-record-imenu-functions fn-node))))
7545
7546 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7547 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7548 ;; We wait until after parsing the function to set its parent scope,
7549 ;; since `js2-define-symbol' needs the defining-scope check to stop
7550 ;; at the function boundary when checking for redeclarations.
7551 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7552 fn-node))
7553
7554 (defun js2-parse-statements (&optional parent)
7555 "Parse a statement list. Last token consumed must be js2-LC.
7556
7557 PARENT can be a `js2-block-node', in which case the statements are
7558 appended to PARENT. Otherwise a new `js2-block-node' is created
7559 and returned.
7560
7561 This function does not match the closing js2-RC: the caller
7562 matches the RC so it can provide a suitable error message if not
7563 matched. This means it's up to the caller to set the length of
7564 the node to include the closing RC. The node start pos is set to
7565 the absolute buffer start position, and the caller should fix it
7566 up to be relative to the parent node. All children of this block
7567 node are given relative start positions and correct lengths."
7568 (let ((pn (or parent (make-js2-block-node)))
7569 tt)
7570 (setf (js2-node-pos pn) (js2-current-token-beg))
7571 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7572 (/= tt js2-RC))
7573 (js2-block-node-push pn (js2-parse-statement)))
7574 pn))
7575
7576 (defun js2-parse-statement ()
7577 (let (pn beg end)
7578 ;; coarse-grained user-interrupt check - needs work
7579 (and js2-parse-interruptable-p
7580 (zerop (% (incf js2-parse-stmt-count)
7581 js2-statements-per-pause))
7582 (input-pending-p)
7583 (throw 'interrupted t))
7584 (setq pn (js2-statement-helper))
7585 ;; no-side-effects warning check
7586 (unless (js2-node-has-side-effects pn)
7587 (setq end (js2-node-end pn))
7588 (save-excursion
7589 (goto-char end)
7590 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7591 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7592 pn))
7593
7594 ;; These correspond to the switch cases in Parser.statementHelper
7595 (defconst js2-parsers
7596 (let ((parsers (make-vector js2-num-tokens
7597 #'js2-parse-expr-stmt)))
7598 (aset parsers js2-BREAK #'js2-parse-break)
7599 (aset parsers js2-CONST #'js2-parse-const-var)
7600 (aset parsers js2-CONTINUE #'js2-parse-continue)
7601 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7602 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7603 (aset parsers js2-DO #'js2-parse-do)
7604 (aset parsers js2-FOR #'js2-parse-for)
7605 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
7606 (aset parsers js2-IF #'js2-parse-if)
7607 (aset parsers js2-LC #'js2-parse-block)
7608 (aset parsers js2-LET #'js2-parse-let-stmt)
7609 (aset parsers js2-NAME #'js2-parse-name-or-label)
7610 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7611 (aset parsers js2-SEMI #'js2-parse-semi)
7612 (aset parsers js2-SWITCH #'js2-parse-switch)
7613 (aset parsers js2-THROW #'js2-parse-throw)
7614 (aset parsers js2-TRY #'js2-parse-try)
7615 (aset parsers js2-VAR #'js2-parse-const-var)
7616 (aset parsers js2-WHILE #'js2-parse-while)
7617 (aset parsers js2-WITH #'js2-parse-with)
7618 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7619 parsers)
7620 "A vector mapping token types to parser functions.")
7621
7622 (defun js2-parse-warn-missing-semi (beg end)
7623 (and js2-mode-show-strict-warnings
7624 js2-strict-missing-semi-warning
7625 (js2-add-strict-warning
7626 "msg.missing.semi" nil
7627 ;; back up to beginning of statement or line
7628 (max beg (save-excursion
7629 (goto-char end)
7630 (point-at-bol)))
7631 end)))
7632
7633 (defconst js2-no-semi-insertion
7634 (list js2-IF
7635 js2-SWITCH
7636 js2-WHILE
7637 js2-DO
7638 js2-FOR
7639 js2-TRY
7640 js2-WITH
7641 js2-LC
7642 js2-ERROR
7643 js2-SEMI
7644 js2-FUNCTION)
7645 "List of tokens that don't do automatic semicolon insertion.")
7646
7647 (defconst js2-autoinsert-semi-and-warn
7648 (list js2-ERROR js2-EOF js2-RC))
7649
7650 (defun js2-statement-helper ()
7651 (let* ((tt (js2-get-token))
7652 (first-tt tt)
7653 (parser (if (= tt js2-ERROR)
7654 #'js2-parse-semi
7655 (aref js2-parsers tt)))
7656 pn)
7657 ;; If the statement is set, then it's been told its label by now.
7658 (and js2-labeled-stmt
7659 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7660 (setq js2-labeled-stmt nil))
7661 (setq pn (funcall parser))
7662 ;; Don't do auto semi insertion for certain statement types.
7663 (unless (or (memq first-tt js2-no-semi-insertion)
7664 (js2-labeled-stmt-node-p pn))
7665 (js2-auto-insert-semicolon pn))
7666 pn))
7667
7668 (defun js2-auto-insert-semicolon (pn)
7669 (let* ((tt (js2-get-token))
7670 (pos (js2-node-pos pn)))
7671 (cond
7672 ((= tt js2-SEMI)
7673 ;; extend the node bounds to include the semicolon.
7674 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
7675 ((memq tt js2-autoinsert-semi-and-warn)
7676 (js2-unget-token) ; Not ';', do not consume.
7677 ;; Autoinsert ;
7678 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7679 (t
7680 (if (not (js2-token-follows-eol-p (js2-current-token)))
7681 ;; Report error if no EOL or autoinsert ';' otherwise
7682 (js2-report-error "msg.no.semi.stmt")
7683 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7684 (js2-unget-token) ; Not ';', do not consume.
7685 ))))
7686
7687 (defun js2-parse-condition ()
7688 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7689 The parens are discarded and the expression node is returned.
7690 The `pos' field of the return value is set to an absolute position
7691 that must be fixed up by the caller.
7692 Return value is a list (EXPR LP RP), with absolute paren positions."
7693 (let (pn lp rp)
7694 (if (js2-must-match js2-LP "msg.no.paren.cond")
7695 (setq lp (js2-current-token-beg)))
7696 (setq pn (js2-parse-expr))
7697 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7698 (setq rp (js2-current-token-beg)))
7699 ;; Report strict warning on code like "if (a = 7) ..."
7700 (if (and js2-strict-cond-assign-warning
7701 (js2-assign-node-p pn))
7702 (js2-add-strict-warning "msg.equal.as.assign" nil
7703 (js2-node-pos pn)
7704 (+ (js2-node-pos pn)
7705 (js2-node-len pn))))
7706 (list pn lp rp)))
7707
7708 (defun js2-parse-if ()
7709 "Parser for if-statement. Last matched token must be js2-IF."
7710 (let ((pos (js2-current-token-beg))
7711 cond if-true if-false else-pos end pn)
7712 (setq cond (js2-parse-condition)
7713 if-true (js2-parse-statement)
7714 if-false (if (js2-match-token js2-ELSE)
7715 (progn
7716 (setq else-pos (- (js2-current-token-beg) pos))
7717 (js2-parse-statement)))
7718 end (js2-node-end (or if-false if-true))
7719 pn (make-js2-if-node :pos pos
7720 :len (- end pos)
7721 :condition (car cond)
7722 :then-part if-true
7723 :else-part if-false
7724 :else-pos else-pos
7725 :lp (js2-relpos (second cond) pos)
7726 :rp (js2-relpos (third cond) pos)))
7727 (js2-node-add-children pn (car cond) if-true if-false)
7728 pn))
7729
7730 (defun js2-parse-switch ()
7731 "Parser for switch-statement. Last matched token must be js2-SWITCH."
7732 (let ((pos (js2-current-token-beg))
7733 tt pn discriminant has-default case-expr case-node
7734 case-pos cases stmt lp)
7735 (if (js2-must-match js2-LP "msg.no.paren.switch")
7736 (setq lp (js2-current-token-beg)))
7737 (setq discriminant (js2-parse-expr)
7738 pn (make-js2-switch-node :discriminant discriminant
7739 :pos pos
7740 :lp (js2-relpos lp pos)))
7741 (js2-node-add-children pn discriminant)
7742 (js2-enter-switch pn)
7743 (unwind-protect
7744 (progn
7745 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7746 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
7747 (js2-must-match js2-LC "msg.no.brace.switch")
7748 (catch 'break
7749 (while t
7750 (setq tt (js2-next-token)
7751 case-pos (js2-current-token-beg))
7752 (cond
7753 ((= tt js2-RC)
7754 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
7755 (throw 'break nil)) ; done
7756 ((= tt js2-CASE)
7757 (setq case-expr (js2-parse-expr))
7758 (js2-must-match js2-COLON "msg.no.colon.case"))
7759 ((= tt js2-DEFAULT)
7760 (if has-default
7761 (js2-report-error "msg.double.switch.default"))
7762 (setq has-default t
7763 case-expr nil)
7764 (js2-must-match js2-COLON "msg.no.colon.case"))
7765 (t
7766 (js2-report-error "msg.bad.switch")
7767 (throw 'break nil)))
7768 (setq case-node (make-js2-case-node :pos case-pos
7769 :len (- (js2-current-token-end) case-pos)
7770 :expr case-expr))
7771 (js2-node-add-children case-node case-expr)
7772 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7773 (/= tt js2-CASE)
7774 (/= tt js2-DEFAULT)
7775 (/= tt js2-EOF))
7776 (setf stmt (js2-parse-statement)
7777 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7778 (js2-block-node-push case-node stmt))
7779 (push case-node cases)))
7780 ;; add cases last, as pushing reverses the order to be correct
7781 (dolist (kid cases)
7782 (js2-node-add-children pn kid)
7783 (push kid (js2-switch-node-cases pn)))
7784 pn) ; return value
7785 (js2-exit-switch))))
7786
7787 (defun js2-parse-while ()
7788 "Parser for while-statement. Last matched token must be js2-WHILE."
7789 (let ((pos (js2-current-token-beg))
7790 (pn (make-js2-while-node))
7791 cond body)
7792 (js2-enter-loop pn)
7793 (unwind-protect
7794 (progn
7795 (setf cond (js2-parse-condition)
7796 (js2-while-node-condition pn) (car cond)
7797 body (js2-parse-statement)
7798 (js2-while-node-body pn) body
7799 (js2-node-len pn) (- (js2-node-end body) pos)
7800 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7801 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7802 (js2-node-add-children pn body (car cond)))
7803 (js2-exit-loop))
7804 pn))
7805
7806 (defun js2-parse-do ()
7807 "Parser for do-statement. Last matched token must be js2-DO."
7808 (let ((pos (js2-current-token-beg))
7809 (pn (make-js2-do-node))
7810 cond body end)
7811 (js2-enter-loop pn)
7812 (unwind-protect
7813 (progn
7814 (setq body (js2-parse-statement))
7815 (js2-must-match js2-WHILE "msg.no.while.do")
7816 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
7817 cond (js2-parse-condition)
7818 (js2-do-node-condition pn) (car cond)
7819 (js2-do-node-body pn) body
7820 end js2-ts-cursor
7821 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7822 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7823 (js2-node-add-children pn (car cond) body))
7824 (js2-exit-loop))
7825 ;; Always auto-insert semicolon to follow SpiderMonkey:
7826 ;; It is required by ECMAScript but is ignored by the rest of
7827 ;; world; see bug 238945
7828 (if (js2-match-token js2-SEMI)
7829 (setq end js2-ts-cursor))
7830 (setf (js2-node-len pn) (- end pos))
7831 pn))
7832
7833 (defun js2-parse-for ()
7834 "Parser for for-statement. Last matched token must be js2-FOR.
7835 Parses for, for-in, and for each-in statements."
7836 (let ((for-pos (js2-current-token-beg))
7837 pn is-for-each is-for-in-or-of is-for-of
7838 in-pos each-pos tmp-pos
7839 init ; Node init is also foo in 'foo in object'
7840 cond ; Node cond is also object in 'foo in object'
7841 incr ; 3rd section of for-loop initializer
7842 body tt lp rp)
7843 ;; See if this is a for each () instead of just a for ()
7844 (when (js2-match-token js2-NAME)
7845 (if (string= "each" (js2-current-token-string))
7846 (progn
7847 (setq is-for-each t
7848 each-pos (- (js2-current-token-beg) for-pos)) ; relative
7849 (js2-record-face 'font-lock-keyword-face))
7850 (js2-report-error "msg.no.paren.for")))
7851 (if (js2-must-match js2-LP "msg.no.paren.for")
7852 (setq lp (- (js2-current-token-beg) for-pos)))
7853 (setq tt (js2-get-token))
7854 ;; 'for' makes local scope
7855 (js2-push-scope (make-js2-scope))
7856 (unwind-protect
7857 ;; parse init clause
7858 (let ((js2-in-for-init t)) ; set as dynamic variable
7859 (cond
7860 ((= tt js2-SEMI)
7861 (js2-unget-token)
7862 (setq init (make-js2-empty-expr-node)))
7863 ((or (= tt js2-VAR) (= tt js2-LET))
7864 (setq init (js2-parse-variables tt (js2-current-token-beg))))
7865 (t
7866 (js2-unget-token)
7867 (setq init (js2-parse-expr)))))
7868 (if (or (js2-match-token js2-IN)
7869 (and (>= js2-language-version 200)
7870 (js2-match-contextual-kwd "of")
7871 (setq is-for-of t)))
7872 (setq is-for-in-or-of t
7873 in-pos (- (js2-current-token-beg) for-pos)
7874 ;; scope of iteration target object is not the scope we've created above.
7875 ;; stash current scope temporary.
7876 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7877 (js2-parse-expr))) ; object over which we're iterating
7878 ;; else ordinary for loop - parse cond and incr
7879 (js2-must-match js2-SEMI "msg.no.semi.for")
7880 (setq cond (if (= (js2-peek-token) js2-SEMI)
7881 (make-js2-empty-expr-node) ; no loop condition
7882 (js2-parse-expr)))
7883 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7884 (setq tmp-pos (js2-current-token-end)
7885 incr (if (= (js2-peek-token) js2-RP)
7886 (make-js2-empty-expr-node :pos tmp-pos)
7887 (js2-parse-expr))))
7888 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7889 (setq rp (- (js2-current-token-beg) for-pos)))
7890 (if (not is-for-in-or-of)
7891 (setq pn (make-js2-for-node :init init
7892 :condition cond
7893 :update incr
7894 :lp lp
7895 :rp rp))
7896 ;; cond could be null if 'in obj' got eaten by the init node.
7897 (if (js2-infix-node-p init)
7898 ;; it was (foo in bar) instead of (var foo in bar)
7899 (setq cond (js2-infix-node-right init)
7900 init (js2-infix-node-left init))
7901 (if (and (js2-var-decl-node-p init)
7902 (> (length (js2-var-decl-node-kids init)) 1))
7903 (js2-report-error "msg.mult.index")))
7904 (setq pn (make-js2-for-in-node :iterator init
7905 :object cond
7906 :in-pos in-pos
7907 :foreach-p is-for-each
7908 :each-pos each-pos
7909 :forof-p is-for-of
7910 :lp lp
7911 :rp rp)))
7912 (unwind-protect
7913 (progn
7914 (js2-enter-loop pn)
7915 ;; We have to parse the body -after- creating the loop node,
7916 ;; so that the loop node appears in the js2-loop-set, allowing
7917 ;; break/continue statements to find the enclosing loop.
7918 (setf body (js2-parse-statement)
7919 (js2-loop-node-body pn) body
7920 (js2-node-pos pn) for-pos
7921 (js2-node-len pn) (- (js2-node-end body) for-pos))
7922 (js2-node-add-children pn init cond incr body))
7923 ;; finally
7924 (js2-exit-loop))
7925 (js2-pop-scope))
7926 pn))
7927
7928 (defun js2-parse-try ()
7929 "Parser for try-statement. Last matched token must be js2-TRY."
7930 (let ((try-pos (js2-current-token-beg))
7931 try-end
7932 try-block
7933 catch-blocks
7934 finally-block
7935 saw-default-catch
7936 peek
7937 param
7938 catch-cond
7939 catch-node
7940 guard-kwd
7941 catch-pos
7942 finally-pos
7943 pn
7944 block
7945 lp
7946 rp)
7947 (if (/= (js2-peek-token) js2-LC)
7948 (js2-report-error "msg.no.brace.try"))
7949 (setq try-block (js2-parse-statement)
7950 try-end (js2-node-end try-block)
7951 peek (js2-peek-token))
7952 (cond
7953 ((= peek js2-CATCH)
7954 (while (js2-match-token js2-CATCH)
7955 (setq catch-pos (js2-current-token-beg)
7956 guard-kwd nil
7957 catch-cond nil
7958 lp nil
7959 rp nil)
7960 (if saw-default-catch
7961 (js2-report-error "msg.catch.unreachable"))
7962 (if (js2-must-match js2-LP "msg.no.paren.catch")
7963 (setq lp (- (js2-current-token-beg) catch-pos)))
7964 (js2-push-scope (make-js2-scope))
7965 (let ((tt (js2-peek-token)))
7966 (cond
7967 ;; destructuring pattern
7968 ;; catch ({ message, file }) { ... }
7969 ((or (= tt js2-LB) (= tt js2-LC))
7970 (js2-get-token)
7971 (setq param (js2-parse-destruct-primary-expr))
7972 (js2-define-destruct-symbols param js2-LET nil))
7973 ;; simple name
7974 (t
7975 (js2-must-match-name "msg.bad.catchcond")
7976 (setq param (js2-create-name-node))
7977 (js2-define-symbol js2-LET (js2-current-token-string) param))))
7978 ;; pattern guard
7979 (if (js2-match-token js2-IF)
7980 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
7981 catch-cond (js2-parse-expr))
7982 (setq saw-default-catch t))
7983 (if (js2-must-match js2-RP "msg.bad.catchcond")
7984 (setq rp (- (js2-current-token-beg) catch-pos)))
7985 (js2-must-match js2-LC "msg.no.brace.catchblock")
7986 (setq block (js2-parse-statements)
7987 try-end (js2-node-end block)
7988 catch-node (make-js2-catch-node :pos catch-pos
7989 :param param
7990 :guard-expr catch-cond
7991 :guard-kwd guard-kwd
7992 :block block
7993 :lp lp
7994 :rp rp))
7995 (js2-pop-scope)
7996 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7997 (setq try-end (js2-current-token-beg)))
7998 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7999 (js2-node-len catch-node) (- try-end catch-pos))
8000 (js2-node-add-children catch-node param catch-cond block)
8001 (push catch-node catch-blocks)))
8002 ((/= peek js2-FINALLY)
8003 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8004 (js2-node-pos try-block)
8005 (- (setq try-end (js2-node-end try-block))
8006 (js2-node-pos try-block)))))
8007 (when (js2-match-token js2-FINALLY)
8008 (setq finally-pos (js2-current-token-beg)
8009 block (js2-parse-statement)
8010 try-end (js2-node-end block)
8011 finally-block (make-js2-finally-node :pos finally-pos
8012 :len (- try-end finally-pos)
8013 :body block))
8014 (js2-node-add-children finally-block block))
8015 (setq pn (make-js2-try-node :pos try-pos
8016 :len (- try-end try-pos)
8017 :try-block try-block
8018 :finally-block finally-block))
8019 (js2-node-add-children pn try-block finally-block)
8020 ;; push them onto the try-node, which reverses and corrects their order
8021 (dolist (cb catch-blocks)
8022 (js2-node-add-children pn cb)
8023 (push cb (js2-try-node-catch-clauses pn)))
8024 pn))
8025
8026 (defun js2-parse-throw ()
8027 "Parser for throw-statement. Last matched token must be js2-THROW."
8028 (let ((pos (js2-current-token-beg))
8029 expr pn)
8030 (if (= (js2-peek-token-or-eol) js2-EOL)
8031 ;; ECMAScript does not allow new lines before throw expression,
8032 ;; see bug 256617
8033 (js2-report-error "msg.bad.throw.eol"))
8034 (setq expr (js2-parse-expr)
8035 pn (make-js2-throw-node :pos pos
8036 :len (- (js2-node-end expr) pos)
8037 :expr expr))
8038 (js2-node-add-children pn expr)
8039 pn))
8040
8041 (defun js2-match-jump-label-name (label-name)
8042 "If break/continue specified a label, return that label's labeled stmt.
8043 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8044 does not match an existing label, reports an error and returns nil."
8045 (let ((bundle (cdr (assoc label-name js2-label-set))))
8046 (if (null bundle)
8047 (js2-report-error "msg.undef.label"))
8048 bundle))
8049
8050 (defun js2-parse-break ()
8051 "Parser for break-statement. Last matched token must be js2-BREAK."
8052 (let ((pos (js2-current-token-beg))
8053 (end (js2-current-token-end))
8054 break-target ; statement to break from
8055 break-label ; in "break foo", name-node representing the foo
8056 labels ; matching labeled statement to break to
8057 pn)
8058 (when (eq (js2-peek-token-or-eol) js2-NAME)
8059 (js2-get-token)
8060 (setq break-label (js2-create-name-node)
8061 end (js2-node-end break-label)
8062 ;; matchJumpLabelName only matches if there is one
8063 labels (js2-match-jump-label-name (js2-current-token-string))
8064 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8065 (unless (or break-target break-label)
8066 ;; no break target specified - try for innermost enclosing loop/switch
8067 (if (null js2-loop-and-switch-set)
8068 (unless break-label
8069 (js2-report-error "msg.bad.break" nil pos (length "break")))
8070 (setq break-target (car js2-loop-and-switch-set))))
8071 (setq pn (make-js2-break-node :pos pos
8072 :len (- end pos)
8073 :label break-label
8074 :target break-target))
8075 (js2-node-add-children pn break-label) ; but not break-target
8076 pn))
8077
8078 (defun js2-parse-continue ()
8079 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8080 (let ((pos (js2-current-token-beg))
8081 (end (js2-current-token-end))
8082 label ; optional user-specified label, a `js2-name-node'
8083 labels ; current matching labeled stmt, if any
8084 target ; the `js2-loop-node' target of this continue stmt
8085 pn)
8086 (when (= (js2-peek-token-or-eol) js2-NAME)
8087 (js2-get-token)
8088 (setq label (js2-create-name-node)
8089 end (js2-node-end label)
8090 ;; matchJumpLabelName only matches if there is one
8091 labels (js2-match-jump-label-name (js2-current-token-string))))
8092 (cond
8093 ((null labels) ; no current label to go to
8094 (if (null js2-loop-set) ; no loop to continue to
8095 (js2-report-error "msg.continue.outside" nil pos
8096 (length "continue"))
8097 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8098 (t
8099 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8100 (setq target (js2-labeled-stmt-node-stmt labels))
8101 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8102 (setq pn (make-js2-continue-node :pos pos
8103 :len (- end pos)
8104 :label label
8105 :target target))
8106 (js2-node-add-children pn label) ; but not target - it's not our child
8107 pn))
8108
8109 (defun js2-parse-with ()
8110 "Parser for with-statement. Last matched token must be js2-WITH."
8111 (let ((pos (js2-current-token-beg))
8112 obj body pn lp rp)
8113 (if (js2-must-match js2-LP "msg.no.paren.with")
8114 (setq lp (js2-current-token-beg)))
8115 (setq obj (js2-parse-expr))
8116 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8117 (setq rp (js2-current-token-beg)))
8118 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8119 (setq body (js2-parse-statement)))
8120 (setq pn (make-js2-with-node :pos pos
8121 :len (- (js2-node-end body) pos)
8122 :object obj
8123 :body body
8124 :lp (js2-relpos lp pos)
8125 :rp (js2-relpos rp pos)))
8126 (js2-node-add-children pn obj body)
8127 pn))
8128
8129 (defun js2-parse-const-var ()
8130 "Parser for var- or const-statement.
8131 Last matched token must be js2-CONST or js2-VAR."
8132 (let ((tt (js2-current-token-type))
8133 (pos (js2-current-token-beg))
8134 expr pn)
8135 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8136 pn (make-js2-expr-stmt-node :pos pos
8137 :len (- (js2-node-end expr) pos)
8138 :expr expr))
8139 (js2-node-add-children pn expr)
8140 pn))
8141
8142 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8143 (let ((pn (make-js2-expr-stmt-node :pos pos
8144 :len (js2-node-len expr)
8145 :type (if (js2-inside-function)
8146 js2-EXPR_VOID
8147 js2-EXPR_RESULT)
8148 :expr expr)))
8149 (if add-child
8150 (js2-node-add-children pn expr))
8151 pn))
8152
8153 (defun js2-parse-let-stmt ()
8154 "Parser for let-statement. Last matched token must be js2-LET."
8155 (let ((pos (js2-current-token-beg))
8156 expr pn)
8157 (if (= (js2-peek-token) js2-LP)
8158 ;; let expression in statement context
8159 (setq expr (js2-parse-let pos 'statement)
8160 pn (js2-wrap-with-expr-stmt pos expr t))
8161 ;; else we're looking at a statement like let x=6, y=7;
8162 (setf expr (js2-parse-variables js2-LET pos)
8163 pn (js2-wrap-with-expr-stmt pos expr t)
8164 (js2-node-type pn) js2-EXPR_RESULT))
8165 pn))
8166
8167 (defun js2-parse-ret-yield ()
8168 (js2-parse-return-or-yield (js2-current-token-type) nil))
8169
8170 (defconst js2-parse-return-stmt-enders
8171 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8172
8173 (defsubst js2-now-all-set (before after mask)
8174 "Return whether or not the bits in the mask have changed to all set.
8175 BEFORE is bits before change, AFTER is bits after change, and MASK is
8176 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8177 but not BEFORE."
8178 (and (/= (logand before mask) mask)
8179 (= (logand after mask) mask)))
8180
8181 (defun js2-parse-return-or-yield (tt expr-context)
8182 (let* ((pos (js2-current-token-beg))
8183 (end (js2-current-token-end))
8184 (before js2-end-flags)
8185 (inside-function (js2-inside-function))
8186 (gen-type (and inside-function (js2-function-node-generator-type
8187 js2-current-script-or-fn)))
8188 e ret name yield-star-p)
8189 (unless inside-function
8190 (js2-report-error (if (eq tt js2-RETURN)
8191 "msg.bad.return"
8192 "msg.bad.yield")))
8193 (when (and inside-function
8194 (eq gen-type 'STAR)
8195 (js2-match-token js2-MUL))
8196 (setq yield-star-p t))
8197 ;; This is ugly, but we don't want to require a semicolon.
8198 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8199 (setq e (js2-parse-expr)
8200 end (js2-node-end e)))
8201 (cond
8202 ((eq tt js2-RETURN)
8203 (js2-set-flag js2-end-flags (if (null e)
8204 js2-end-returns
8205 js2-end-returns-value))
8206 (setq ret (make-js2-return-node :pos pos
8207 :len (- end pos)
8208 :retval e))
8209 (js2-node-add-children ret e)
8210 ;; See if we need a strict mode warning.
8211 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8212 ;; more thorough and accurate than this before/after flag check.
8213 ;; E.g. if there's a finally-block that always returns, we shouldn't
8214 ;; show a warning generated by inconsistent returns in the catch blocks.
8215 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8216 ;; so we know which returns/yields to highlight, and we should get rid of
8217 ;; all the checking in `js2-parse-return-or-yield'.
8218 (if (and js2-strict-inconsistent-return-warning
8219 (js2-now-all-set before js2-end-flags
8220 (logior js2-end-returns js2-end-returns-value)))
8221 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8222 ((eq gen-type 'COMPREHENSION)
8223 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8224 ;; like SpiderMonkey does.
8225 (js2-report-error "msg.syntax" nil pos 5))
8226 (t
8227 (setq ret (make-js2-yield-node :pos pos
8228 :len (- end pos)
8229 :value e
8230 :star-p yield-star-p))
8231 (js2-node-add-children ret e)
8232 (unless expr-context
8233 (setq e ret
8234 ret (js2-wrap-with-expr-stmt pos e t))
8235 (js2-set-requires-activation)
8236 (js2-set-is-generator))))
8237 ;; see if we are mixing yields and value returns.
8238 (when (and inside-function
8239 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8240 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8241 'LEGACY))
8242 (setq name (js2-function-name js2-current-script-or-fn))
8243 (if (zerop (length name))
8244 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8245 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8246 ret))
8247
8248 (defun js2-parse-debugger ()
8249 (make-js2-keyword-node :type js2-DEBUGGER))
8250
8251 (defun js2-parse-block ()
8252 "Parser for a curly-delimited statement block.
8253 Last token matched must be `js2-LC'."
8254 (let ((pos (js2-current-token-beg))
8255 (pn (make-js2-scope)))
8256 (js2-push-scope pn)
8257 (unwind-protect
8258 (progn
8259 (js2-parse-statements pn)
8260 (js2-must-match js2-RC "msg.no.brace.block")
8261 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8262 (js2-pop-scope))
8263 pn))
8264
8265 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8266 (defun js2-parse-semi ()
8267 "Parse a statement or handle an error.
8268 Current token type is `js2-SEMI' or `js2-ERROR'."
8269 (let ((tt (js2-current-token-type)) pos len)
8270 (if (eq tt js2-SEMI)
8271 (make-js2-empty-expr-node :len 1)
8272 (setq pos (js2-current-token-beg)
8273 len (- (js2-current-token-end) pos))
8274 (js2-report-error "msg.syntax" nil pos len)
8275 (make-js2-error-node :pos pos :len len))))
8276
8277 (defun js2-parse-default-xml-namespace ()
8278 "Parse a `default xml namespace = <expr>' e4x statement."
8279 (let ((pos (js2-current-token-beg))
8280 end len expr unary)
8281 (js2-must-have-xml)
8282 (js2-set-requires-activation)
8283 (setq len (- js2-ts-cursor pos))
8284 (unless (and (js2-match-token js2-NAME)
8285 (string= (js2-current-token-string) "xml"))
8286 (js2-report-error "msg.bad.namespace" nil pos len))
8287 (unless (and (js2-match-token js2-NAME)
8288 (string= (js2-current-token-string) "namespace"))
8289 (js2-report-error "msg.bad.namespace" nil pos len))
8290 (unless (js2-match-token js2-ASSIGN)
8291 (js2-report-error "msg.bad.namespace" nil pos len))
8292 (setq expr (js2-parse-expr)
8293 end (js2-node-end expr)
8294 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8295 :pos pos
8296 :len (- end pos)
8297 :operand expr))
8298 (js2-node-add-children unary expr)
8299 (make-js2-expr-stmt-node :pos pos
8300 :len (- end pos)
8301 :expr unary)))
8302
8303 (defun js2-record-label (label bundle)
8304 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8305 (js2-get-token)
8306 (let ((name (js2-label-node-name label))
8307 labeled-stmt
8308 dup)
8309 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8310 ;; flag both labels if possible when used in editing mode
8311 (if (and js2-parse-ide-mode
8312 (setq dup (js2-get-label-by-name labeled-stmt name)))
8313 (js2-report-error "msg.dup.label" nil
8314 (js2-node-abs-pos dup) (js2-node-len dup)))
8315 (js2-report-error "msg.dup.label" nil
8316 (js2-node-pos label) (js2-node-len label)))
8317 (js2-labeled-stmt-node-add-label bundle label)
8318 (js2-node-add-children bundle label)
8319 ;; Add one reference to the bundle per label in `js2-label-set'
8320 (push (cons name bundle) js2-label-set)))
8321
8322 (defun js2-parse-name-or-label ()
8323 "Parser for identifier or label. Last token matched must be js2-NAME.
8324 Called when we found a name in a statement context. If it's a label, we gather
8325 up any following labels and the next non-label statement into a
8326 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8327 expression and return it wrapped in a `js2-expr-stmt-node'."
8328 (let ((pos (js2-current-token-beg))
8329 expr stmt bundle
8330 (continue t))
8331 ;; set check for label and call down to `js2-parse-primary-expr'
8332 (setq expr (js2-maybe-parse-label))
8333 (if (null expr)
8334 ;; Parse the non-label expression and wrap with expression stmt.
8335 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
8336 ;; else parsed a label
8337 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8338 (js2-record-label expr bundle)
8339 ;; look for more labels
8340 (while (and continue (= (js2-get-token) js2-NAME))
8341 (if (setq expr (js2-maybe-parse-label))
8342 (js2-record-label expr bundle)
8343 (setq expr (js2-parse-expr)
8344 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8345 continue nil)
8346 (js2-auto-insert-semicolon stmt)))
8347 ;; no more labels; now parse the labeled statement
8348 (unwind-protect
8349 (unless stmt
8350 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8351 (js2-unget-token)
8352 (setq stmt (js2-statement-helper))))
8353 ;; remove the labels for this statement from the global set
8354 (dolist (label (js2-labeled-stmt-node-labels bundle))
8355 (setq js2-label-set (remove label js2-label-set))))
8356 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8357 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8358 (js2-node-add-children bundle stmt)
8359 bundle)))
8360
8361 (defun js2-maybe-parse-label ()
8362 (assert (= (js2-current-token-type) js2-NAME))
8363 (let (label-pos
8364 (next-tt (js2-get-token))
8365 (label-end (js2-current-token-end)))
8366 ;; Do not consume colon, it is used as unwind indicator
8367 ;; to return to statementHelper.
8368 (js2-unget-token)
8369 (if (= next-tt js2-COLON)
8370 (prog2
8371 (setq label-pos (js2-current-token-beg))
8372 (make-js2-label-node :pos label-pos
8373 :len (- label-end label-pos)
8374 :name (js2-current-token-string))
8375 (js2-set-face label-pos
8376 label-end
8377 'font-lock-variable-name-face 'record))
8378 ;; Backtrack from the name token, too.
8379 (js2-unget-token)
8380 nil)))
8381
8382 (defun js2-parse-expr-stmt ()
8383 "Default parser in statement context, if no recognized statement found."
8384 (js2-wrap-with-expr-stmt (js2-current-token-beg)
8385 (progn
8386 (js2-unget-token)
8387 (js2-parse-expr)) t))
8388
8389 (defun js2-parse-variables (decl-type pos)
8390 "Parse a comma-separated list of variable declarations.
8391 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8392
8393 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8394 For 'var' or 'const', the keyword should be the token last scanned.
8395
8396 POS is the position where the node should start. It's sometimes the
8397 var/const/let keyword, and other times the beginning of the first token
8398 in the first variable declaration.
8399
8400 Returns the parsed `js2-var-decl-node' expression node."
8401 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8402 :pos pos))
8403 destructuring kid-pos tt init name end nbeg nend vi
8404 (continue t))
8405 ;; Example:
8406 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8407 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8408 ;; var {a, b} = baz;
8409 (while continue
8410 (setq destructuring nil
8411 name nil
8412 tt (js2-get-token)
8413 kid-pos (js2-current-token-beg)
8414 end (js2-current-token-end)
8415 init nil)
8416 (if (or (= tt js2-LB) (= tt js2-LC))
8417 ;; Destructuring assignment, e.g., var [a, b] = ...
8418 (setq destructuring (js2-parse-destruct-primary-expr)
8419 end (js2-node-end destructuring))
8420 ;; Simple variable name
8421 (js2-unget-token)
8422 (when (js2-must-match-name "msg.bad.var")
8423 (setq name (js2-create-name-node)
8424 nbeg (js2-current-token-beg)
8425 nend (js2-current-token-end)
8426 end nend)
8427 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
8428 (when (js2-match-token js2-ASSIGN)
8429 (setq init (js2-parse-assign-expr)
8430 end (js2-node-end init))
8431 (js2-record-imenu-functions init name))
8432 (when name
8433 (js2-set-face nbeg nend (if (js2-function-node-p init)
8434 'font-lock-function-name-face
8435 'font-lock-variable-name-face)
8436 'record))
8437 (setq vi (make-js2-var-init-node :pos kid-pos
8438 :len (- end kid-pos)
8439 :type decl-type))
8440 (if destructuring
8441 (progn
8442 (if (and (null init) (not js2-in-for-init))
8443 (js2-report-error "msg.destruct.assign.no.init"))
8444 (js2-define-destruct-symbols destructuring
8445 decl-type
8446 'font-lock-variable-name-face)
8447 (setf (js2-var-init-node-target vi) destructuring))
8448 (setf (js2-var-init-node-target vi) name))
8449 (setf (js2-var-init-node-initializer vi) init)
8450 (js2-node-add-children vi name destructuring init)
8451 (js2-block-node-push result vi)
8452 (unless (js2-match-token js2-COMMA)
8453 (setq continue nil)))
8454 (setf (js2-node-len result) (- end pos))
8455 result))
8456
8457 (defun js2-parse-let (pos &optional stmt-p)
8458 "Parse a let expression or statement.
8459 A let-expression is of the form `let (vars) expr'.
8460 A let-statment is of the form `let (vars) {statements}'.
8461 The third form of let is a variable declaration list, handled
8462 by `js2-parse-variables'."
8463 (let ((pn (make-js2-let-node :pos pos))
8464 beg vars body)
8465 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8466 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
8467 (js2-push-scope pn)
8468 (unwind-protect
8469 (progn
8470 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
8471 (if (js2-must-match js2-RP "msg.no.paren.let")
8472 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
8473 (if (and stmt-p (js2-match-token js2-LC))
8474 ;; let statement
8475 (progn
8476 (setf beg (js2-current-token-beg) ; position stmt at LC
8477 body (js2-parse-statements))
8478 (js2-must-match js2-RC "msg.no.curly.let")
8479 (setf (js2-node-len body) (- (js2-current-token-end) beg)
8480 (js2-node-len pn) (- (js2-current-token-end) pos)
8481 (js2-let-node-body pn) body
8482 (js2-node-type pn) js2-LET))
8483 ;; let expression
8484 (setf body (js2-parse-expr)
8485 (js2-node-len pn) (- (js2-node-end body) pos)
8486 (js2-let-node-body pn) body))
8487 (setf (js2-let-node-vars pn) vars)
8488 (js2-node-add-children pn vars body))
8489 (js2-pop-scope))
8490 pn))
8491
8492 (defun js2-define-new-symbol (decl-type name node &optional scope)
8493 (js2-scope-put-symbol (or scope js2-current-scope)
8494 name
8495 (make-js2-symbol decl-type name node)))
8496
8497 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8498 "Define a symbol in the current scope.
8499 If NODE is non-nil, it is the AST node associated with the symbol."
8500 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8501 (symbol (if defining-scope
8502 (js2-scope-get-symbol defining-scope name)))
8503 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8504 (cond
8505 ((and symbol ; already defined
8506 (or (= sdt js2-CONST) ; old version is const
8507 (= decl-type js2-CONST) ; new version is const
8508 ;; two let-bound vars in this block have same name
8509 (and (= sdt js2-LET)
8510 (eq defining-scope js2-current-scope))))
8511 (js2-report-error
8512 (cond
8513 ((= sdt js2-CONST) "msg.const.redecl")
8514 ((= sdt js2-LET) "msg.let.redecl")
8515 ((= sdt js2-VAR) "msg.var.redecl")
8516 ((= sdt js2-FUNCTION) "msg.function.redecl")
8517 (t "msg.parm.redecl"))
8518 name))
8519 ((= decl-type js2-LET)
8520 (if (and (not ignore-not-in-block)
8521 (or (= (js2-node-type js2-current-scope) js2-IF)
8522 (js2-loop-node-p js2-current-scope)))
8523 (js2-report-error "msg.let.decl.not.in.block")
8524 (js2-define-new-symbol decl-type name node)))
8525 ((or (= decl-type js2-VAR)
8526 (= decl-type js2-CONST)
8527 (= decl-type js2-FUNCTION))
8528 (if symbol
8529 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8530 (js2-add-strict-warning "msg.var.redecl" name)
8531 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8532 (js2-add-strict-warning "msg.var.hides.arg" name)))
8533 (js2-define-new-symbol decl-type name node
8534 js2-current-script-or-fn)))
8535 ((= decl-type js2-LP)
8536 (if symbol
8537 ;; must be duplicate parameter. Second parameter hides the
8538 ;; first, so go ahead and add the second pararameter
8539 (js2-report-warning "msg.dup.parms" name))
8540 (js2-define-new-symbol decl-type name node))
8541 (t (js2-code-bug)))))
8542
8543 (defun js2-parse-paren-expr-or-generator-comp ()
8544 (let ((px-pos (js2-current-token-beg)))
8545 (if (and (>= js2-language-version 200)
8546 (js2-match-token js2-FOR))
8547 (js2-parse-generator-comp px-pos)
8548 (let* ((js2-in-for-init nil)
8549 (expr (js2-parse-expr))
8550 (pn (make-js2-paren-node :pos px-pos
8551 :expr expr
8552 :len (- (js2-current-token-end)
8553 px-pos))))
8554 (js2-node-add-children pn (js2-paren-node-expr pn))
8555 (js2-must-match js2-RP "msg.no.paren")
8556 pn))))
8557
8558 (defun js2-parse-expr (&optional oneshot)
8559 (let* ((pn (js2-parse-assign-expr))
8560 (pos (js2-node-pos pn))
8561 left
8562 right
8563 op-pos)
8564 (while (and (not oneshot)
8565 (js2-match-token js2-COMMA))
8566 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
8567 (if (= (js2-peek-token) js2-YIELD)
8568 (js2-report-error "msg.yield.parenthesized"))
8569 (setq right (js2-parse-assign-expr)
8570 left pn
8571 pn (make-js2-infix-node :type js2-COMMA
8572 :pos pos
8573 :len (- js2-ts-cursor pos)
8574 :op-pos op-pos
8575 :left left
8576 :right right))
8577 (js2-node-add-children pn left right))
8578 pn))
8579
8580 (defun js2-parse-assign-expr ()
8581 (let ((tt (js2-get-token))
8582 (pos (js2-current-token-beg))
8583 pn left right op-pos
8584 ts-state recorded-identifiers parsed-errors)
8585 (if (= tt js2-YIELD)
8586 (js2-parse-return-or-yield tt t)
8587 ;; Save the tokenizer state in case we find an arrow function
8588 ;; and have to rewind.
8589 (setq ts-state (make-js2-ts-state)
8590 recorded-identifiers js2-recorded-identifiers
8591 parsed-errors js2-parsed-errors)
8592 ;; not yield - parse assignment expression
8593 (setq pn (js2-parse-cond-expr)
8594 tt (js2-get-token))
8595 (cond
8596 ((and (<= js2-first-assign tt)
8597 (<= tt js2-last-assign))
8598 ;; tt express assignment (=, |=, ^=, ..., %=)
8599 (setq op-pos (- (js2-current-token-beg) pos) ; relative
8600 left pn)
8601 (setq right (js2-parse-assign-expr)
8602 pn (make-js2-assign-node :type tt
8603 :pos pos
8604 :len (- (js2-node-end right) pos)
8605 :op-pos op-pos
8606 :left left
8607 :right right))
8608 (when js2-parse-ide-mode
8609 (js2-highlight-assign-targets pn left right)
8610 (js2-record-imenu-functions right left))
8611 ;; do this last so ide checks above can use absolute positions
8612 (js2-node-add-children pn left right))
8613 ((and (= tt js2-ARROW)
8614 (>= js2-language-version 200))
8615 (js2-ts-seek ts-state)
8616 (setq js2-recorded-identifiers recorded-identifiers
8617 js2-parsed-errors parsed-errors)
8618 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
8619 (t
8620 (js2-unget-token)))
8621 pn)))
8622
8623 (defun js2-parse-cond-expr ()
8624 (let ((pos (js2-current-token-beg))
8625 (pn (js2-parse-or-expr))
8626 test-expr
8627 if-true
8628 if-false
8629 q-pos
8630 c-pos)
8631 (when (js2-match-token js2-HOOK)
8632 (setq q-pos (- (js2-current-token-beg) pos)
8633 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
8634 (js2-must-match js2-COLON "msg.no.colon.cond")
8635 (setq c-pos (- (js2-current-token-beg) pos)
8636 if-false (js2-parse-assign-expr)
8637 test-expr pn
8638 pn (make-js2-cond-node :pos pos
8639 :len (- (js2-node-end if-false) pos)
8640 :test-expr test-expr
8641 :true-expr if-true
8642 :false-expr if-false
8643 :q-pos q-pos
8644 :c-pos c-pos))
8645 (js2-node-add-children pn test-expr if-true if-false))
8646 pn))
8647
8648 (defun js2-make-binary (type left parser)
8649 "Helper for constructing a binary-operator AST node.
8650 LEFT is the left-side-expression, already parsed, and the
8651 binary operator should have just been matched.
8652 PARSER is a function to call to parse the right operand,
8653 or a `js2-node' struct if it has already been parsed.
8654 FIXME: The latter option is unused?"
8655 (let* ((pos (js2-node-pos left))
8656 (op-pos (- (js2-current-token-beg) pos))
8657 (right (if (js2-node-p parser)
8658 parser
8659 (js2-get-token)
8660 (funcall parser)))
8661 (pn (make-js2-infix-node :type type
8662 :pos pos
8663 :len (- (js2-node-end right) pos)
8664 :op-pos op-pos
8665 :left left
8666 :right right)))
8667 (js2-node-add-children pn left right)
8668 pn))
8669
8670 (defun js2-parse-or-expr ()
8671 (let ((pn (js2-parse-and-expr)))
8672 (when (js2-match-token js2-OR)
8673 (setq pn (js2-make-binary js2-OR
8674 pn
8675 'js2-parse-or-expr)))
8676 pn))
8677
8678 (defun js2-parse-and-expr ()
8679 (let ((pn (js2-parse-bit-or-expr)))
8680 (when (js2-match-token js2-AND)
8681 (setq pn (js2-make-binary js2-AND
8682 pn
8683 'js2-parse-and-expr)))
8684 pn))
8685
8686 (defun js2-parse-bit-or-expr ()
8687 (let ((pn (js2-parse-bit-xor-expr)))
8688 (while (js2-match-token js2-BITOR)
8689 (setq pn (js2-make-binary js2-BITOR
8690 pn
8691 'js2-parse-bit-xor-expr)))
8692 pn))
8693
8694 (defun js2-parse-bit-xor-expr ()
8695 (let ((pn (js2-parse-bit-and-expr)))
8696 (while (js2-match-token js2-BITXOR)
8697 (setq pn (js2-make-binary js2-BITXOR
8698 pn
8699 'js2-parse-bit-and-expr)))
8700 pn))
8701
8702 (defun js2-parse-bit-and-expr ()
8703 (let ((pn (js2-parse-eq-expr)))
8704 (while (js2-match-token js2-BITAND)
8705 (setq pn (js2-make-binary js2-BITAND
8706 pn
8707 'js2-parse-eq-expr)))
8708 pn))
8709
8710 (defconst js2-parse-eq-ops
8711 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8712
8713 (defun js2-parse-eq-expr ()
8714 (let ((pn (js2-parse-rel-expr))
8715 tt)
8716 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
8717 (setq pn (js2-make-binary tt
8718 pn
8719 'js2-parse-rel-expr)))
8720 (js2-unget-token)
8721 pn))
8722
8723 (defconst js2-parse-rel-ops
8724 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8725
8726 (defun js2-parse-rel-expr ()
8727 (let ((pn (js2-parse-shift-expr))
8728 (continue t)
8729 tt)
8730 (while continue
8731 (setq tt (js2-get-token))
8732 (cond
8733 ((and js2-in-for-init (= tt js2-IN))
8734 (js2-unget-token)
8735 (setq continue nil))
8736 ((memq tt js2-parse-rel-ops)
8737 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8738 (t
8739 (js2-unget-token)
8740 (setq continue nil))))
8741 pn))
8742
8743 (defconst js2-parse-shift-ops
8744 (list js2-LSH js2-URSH js2-RSH))
8745
8746 (defun js2-parse-shift-expr ()
8747 (let ((pn (js2-parse-add-expr))
8748 tt
8749 (continue t))
8750 (while continue
8751 (setq tt (js2-get-token))
8752 (if (memq tt js2-parse-shift-ops)
8753 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
8754 (js2-unget-token)
8755 (setq continue nil)))
8756 pn))
8757
8758 (defun js2-parse-add-expr ()
8759 (let ((pn (js2-parse-mul-expr))
8760 tt
8761 (continue t))
8762 (while continue
8763 (setq tt (js2-get-token))
8764 (if (or (= tt js2-ADD) (= tt js2-SUB))
8765 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
8766 (js2-unget-token)
8767 (setq continue nil)))
8768 pn))
8769
8770 (defconst js2-parse-mul-ops
8771 (list js2-MUL js2-DIV js2-MOD))
8772
8773 (defun js2-parse-mul-expr ()
8774 (let ((pn (js2-parse-unary-expr))
8775 tt
8776 (continue t))
8777 (while continue
8778 (setq tt (js2-get-token))
8779 (if (memq tt js2-parse-mul-ops)
8780 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
8781 (js2-unget-token)
8782 (setq continue nil)))
8783 pn))
8784
8785 (defun js2-make-unary (type parser &rest args)
8786 "Make a unary node of type TYPE.
8787 PARSER is either a node (for postfix operators) or a function to call
8788 to parse the operand (for prefix operators)."
8789 (let* ((pos (js2-current-token-beg))
8790 (postfix (js2-node-p parser))
8791 (expr (if postfix
8792 parser
8793 (apply parser args)))
8794 end
8795 pn)
8796 (if postfix ; e.g. i++
8797 (setq pos (js2-node-pos expr)
8798 end (js2-current-token-end))
8799 (setq end (js2-node-end expr)))
8800 (setq pn (make-js2-unary-node :type type
8801 :pos pos
8802 :len (- end pos)
8803 :operand expr))
8804 (js2-node-add-children pn expr)
8805 pn))
8806
8807 (defconst js2-incrementable-node-types
8808 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8809 "Node types that can be the operand of a ++ or -- operator.")
8810
8811 (defun js2-check-bad-inc-dec (tt beg end unary)
8812 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8813 js2-incrementable-node-types)
8814 (js2-report-error (if (= tt js2-INC)
8815 "msg.bad.incr"
8816 "msg.bad.decr")
8817 nil beg (- end beg))))
8818
8819 (defun js2-parse-unary-expr ()
8820 (let ((tt (js2-current-token-type))
8821 pn expr beg end)
8822 (cond
8823 ((or (= tt js2-VOID)
8824 (= tt js2-NOT)
8825 (= tt js2-BITNOT)
8826 (= tt js2-TYPEOF))
8827 (js2-get-token)
8828 (js2-make-unary tt 'js2-parse-unary-expr))
8829 ((= tt js2-ADD)
8830 (js2-get-token)
8831 ;; Convert to special POS token in decompiler and parse tree
8832 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8833 ((= tt js2-SUB)
8834 (js2-get-token)
8835 ;; Convert to special NEG token in decompiler and parse tree
8836 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8837 ((or (= tt js2-INC)
8838 (= tt js2-DEC))
8839 (js2-get-token)
8840 (prog1
8841 (setq beg (js2-current-token-beg)
8842 end (js2-current-token-end)
8843 expr (js2-make-unary tt 'js2-parse-member-expr t))
8844 (js2-check-bad-inc-dec tt beg end expr)))
8845 ((= tt js2-DELPROP)
8846 (js2-get-token)
8847 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8848 ((= tt js2-ERROR)
8849 (js2-get-token)
8850 (make-js2-error-node)) ; try to continue
8851 ((and (= tt js2-LT)
8852 js2-compiler-xml-available)
8853 ;; XML stream encountered in expression.
8854 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8855 (t
8856 (setq pn (js2-parse-member-expr t)
8857 ;; Don't look across a newline boundary for a postfix incop.
8858 tt (js2-peek-token-or-eol))
8859 (when (or (= tt js2-INC) (= tt js2-DEC))
8860 (js2-get-token)
8861 (setf expr pn
8862 pn (js2-make-unary tt expr))
8863 (js2-node-set-prop pn 'postfix t)
8864 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
8865 pn))))
8866
8867 (defun js2-parse-xml-initializer ()
8868 "Parse an E4X XML initializer.
8869 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8870 Then I'll postprocess the result, depending on whether we're in IDE
8871 mode or codegen mode, and generate the appropriate rewritten AST.
8872 IDE mode uses a rich AST that models the XML structure. Codegen mode
8873 just concatenates everything and makes a new XML or XMLList out of it."
8874 (let ((tt (js2-get-first-xml-token))
8875 pn-xml pn expr kids expr-pos
8876 (continue t)
8877 (first-token t))
8878 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8879 (js2-report-error "msg.syntax"))
8880 (setq pn-xml (make-js2-xml-node))
8881 (while continue
8882 (if first-token
8883 (setq first-token nil)
8884 (setq tt (js2-get-next-xml-token)))
8885 (cond
8886 ;; js2-XML means we found a {expr} in the XML stream.
8887 ;; The token string is the XML up to the left-curly.
8888 ((= tt js2-XML)
8889 (push (make-js2-string-node :pos (js2-current-token-beg)
8890 :len (- js2-ts-cursor (js2-current-token-beg)))
8891 kids)
8892 (js2-must-match js2-LC "msg.syntax")
8893 (setq expr-pos js2-ts-cursor
8894 expr (if (eq (js2-peek-token) js2-RC)
8895 (make-js2-empty-expr-node :pos expr-pos)
8896 (js2-parse-expr)))
8897 (js2-must-match js2-RC "msg.syntax")
8898 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8899 :len (js2-node-len expr)
8900 :expr expr))
8901 (js2-node-add-children pn expr)
8902 (push pn kids))
8903 ;; a js2-XMLEND token means we hit the final close-tag.
8904 ((= tt js2-XMLEND)
8905 (push (make-js2-string-node :pos (js2-current-token-beg)
8906 :len (- js2-ts-cursor (js2-current-token-beg)))
8907 kids)
8908 (dolist (kid (nreverse kids))
8909 (js2-block-node-push pn-xml kid))
8910 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8911 (js2-node-pos pn-xml))
8912 continue nil))
8913 (t
8914 (js2-report-error "msg.syntax")
8915 (setq continue nil))))
8916 pn-xml))
8917
8918
8919 (defun js2-parse-argument-list ()
8920 "Parse an argument list and return it as a Lisp list of nodes.
8921 Returns the list in reverse order. Consumes the right-paren token."
8922 (let (result)
8923 (unless (js2-match-token js2-RP)
8924 (loop do
8925 (let ((tt (js2-get-token)))
8926 (if (= tt js2-YIELD)
8927 (js2-report-error "msg.yield.parenthesized"))
8928 (if (and (= tt js2-TRIPLEDOT)
8929 (>= js2-language-version 200))
8930 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
8931 (js2-unget-token)
8932 (push (js2-parse-assign-expr) result)))
8933 while
8934 (js2-match-token js2-COMMA))
8935 (js2-must-match js2-RP "msg.no.paren.arg")
8936 result)))
8937
8938 (defun js2-parse-member-expr (&optional allow-call-syntax)
8939 (let ((tt (js2-current-token-type))
8940 pn pos target args beg end init)
8941 (if (/= tt js2-NEW)
8942 (setq pn (js2-parse-primary-expr))
8943 ;; parse a 'new' expression
8944 (js2-get-token)
8945 (setq pos (js2-current-token-beg)
8946 beg pos
8947 target (js2-parse-member-expr)
8948 end (js2-node-end target)
8949 pn (make-js2-new-node :pos pos
8950 :target target
8951 :len (- end pos)))
8952 (js2-highlight-function-call (js2-current-token))
8953 (js2-node-add-children pn target)
8954 (when (js2-match-token js2-LP)
8955 ;; Add the arguments to pn, if any are supplied.
8956 (setf beg pos ; start of "new" keyword
8957 pos (js2-current-token-beg)
8958 args (nreverse (js2-parse-argument-list))
8959 (js2-new-node-args pn) args
8960 end (js2-current-token-end)
8961 (js2-new-node-lp pn) (- pos beg)
8962 (js2-new-node-rp pn) (- end 1 beg))
8963 (apply #'js2-node-add-children pn args))
8964 (when (and js2-allow-rhino-new-expr-initializer
8965 (js2-match-token js2-LC))
8966 (setf init (js2-parse-object-literal)
8967 end (js2-node-end init)
8968 (js2-new-node-initializer pn) init)
8969 (js2-node-add-children pn init))
8970 (setf (js2-node-len pn) (- end beg))) ; end outer if
8971 (js2-parse-member-expr-tail allow-call-syntax pn)))
8972
8973 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8974 "Parse a chain of property/array accesses or function calls.
8975 Includes parsing for E4X operators like `..' and `.@'.
8976 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8977 Returns an expression tree that includes PN, the parent node."
8978 (let (tt
8979 (continue t))
8980 (while continue
8981 (setq tt (js2-get-token))
8982 (cond
8983 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8984 (setq pn (js2-parse-property-access tt pn)))
8985 ((= tt js2-DOTQUERY)
8986 (setq pn (js2-parse-dot-query pn)))
8987 ((= tt js2-LB)
8988 (setq pn (js2-parse-element-get pn)))
8989 ((= tt js2-LP)
8990 (js2-unget-token)
8991 (if allow-call-syntax
8992 (setq pn (js2-parse-function-call pn))
8993 (setq continue nil)))
8994 (t
8995 (js2-unget-token)
8996 (setq continue nil))))
8997 (if (>= js2-highlight-level 2)
8998 (js2-parse-highlight-member-expr-node pn))
8999 pn))
9000
9001 (defun js2-parse-dot-query (pn)
9002 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9003 Last token parsed must be `js2-DOTQUERY'."
9004 (let ((pos (js2-node-pos pn))
9005 op-pos expr end)
9006 (js2-must-have-xml)
9007 (js2-set-requires-activation)
9008 (setq op-pos (js2-current-token-beg)
9009 expr (js2-parse-expr)
9010 end (js2-node-end expr)
9011 pn (make-js2-xml-dot-query-node :left pn
9012 :pos pos
9013 :op-pos op-pos
9014 :right expr))
9015 (js2-node-add-children pn
9016 (js2-xml-dot-query-node-left pn)
9017 (js2-xml-dot-query-node-right pn))
9018 (if (js2-must-match js2-RP "msg.no.paren")
9019 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9020 end (js2-current-token-end)))
9021 (setf (js2-node-len pn) (- end pos))
9022 pn))
9023
9024 (defun js2-parse-element-get (pn)
9025 "Parse an element-get expression, e.g. foo[bar].
9026 Last token parsed must be `js2-RB'."
9027 (let ((lb (js2-current-token-beg))
9028 (pos (js2-node-pos pn))
9029 rb expr)
9030 (setq expr (js2-parse-expr))
9031 (if (js2-must-match js2-RB "msg.no.bracket.index")
9032 (setq rb (js2-current-token-beg)))
9033 (setq pn (make-js2-elem-get-node :target pn
9034 :pos pos
9035 :element expr
9036 :lb (js2-relpos lb pos)
9037 :rb (js2-relpos rb pos)
9038 :len (- (js2-current-token-end) pos)))
9039 (js2-node-add-children pn
9040 (js2-elem-get-node-target pn)
9041 (js2-elem-get-node-element pn))
9042 pn))
9043
9044 (defun js2-highlight-function-call (token)
9045 (when (eq (js2-token-type token) js2-NAME)
9046 (js2-record-face 'js2-function-call token)))
9047
9048 (defun js2-parse-function-call (pn)
9049 (js2-highlight-function-call (js2-current-token))
9050 (js2-get-token)
9051 (let (args
9052 (pos (js2-node-pos pn)))
9053 (setq pn (make-js2-call-node :pos pos
9054 :target pn
9055 :lp (- (js2-current-token-beg) pos)))
9056 (js2-node-add-children pn (js2-call-node-target pn))
9057 ;; Add the arguments to pn, if any are supplied.
9058 (setf args (nreverse (js2-parse-argument-list))
9059 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9060 (js2-call-node-args pn) args)
9061 (apply #'js2-node-add-children pn args)
9062 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9063 pn))
9064
9065 (defun js2-parse-property-access (tt pn)
9066 "Parse a property access, XML descendants access, or XML attr access."
9067 (let ((member-type-flags 0)
9068 (dot-pos (js2-current-token-beg))
9069 (dot-len (if (= tt js2-DOTDOT) 2 1))
9070 name
9071 ref ; right side of . or .. operator
9072 result)
9073 (when (= tt js2-DOTDOT)
9074 (js2-must-have-xml)
9075 (setq member-type-flags js2-descendants-flag))
9076 (if (not js2-compiler-xml-available)
9077 (progn
9078 (js2-must-match-prop-name "msg.no.name.after.dot")
9079 (setq name (js2-create-name-node t js2-GETPROP)
9080 result (make-js2-prop-get-node :left pn
9081 :pos (js2-current-token-beg)
9082 :right name
9083 :len (js2-current-token-len)))
9084 (js2-node-add-children result pn name)
9085 result)
9086 ;; otherwise look for XML operators
9087 (setf result (if (= tt js2-DOT)
9088 (make-js2-prop-get-node)
9089 (make-js2-infix-node :type js2-DOTDOT))
9090 (js2-node-pos result) (js2-node-pos pn)
9091 (js2-infix-node-op-pos result) dot-pos
9092 (js2-infix-node-left result) pn ; do this after setting position
9093 tt (js2-next-token))
9094 (cond
9095 ;; needed for generator.throw()
9096 ((= tt js2-THROW)
9097 (setq ref (js2-parse-property-name nil nil member-type-flags)))
9098 ;; handles: name, ns::name, ns::*, ns::[expr]
9099 ((js2-valid-prop-name-token tt)
9100 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9101 ;; handles: *, *::name, *::*, *::[expr]
9102 ((= tt js2-MUL)
9103 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9104 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9105 ((= tt js2-XMLATTR)
9106 (setq result (js2-parse-attribute-access)))
9107 (t
9108 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9109 (if ref
9110 (setf (js2-node-len result) (- (js2-node-end ref)
9111 (js2-node-pos result))
9112 (js2-infix-node-right result) ref))
9113 (if (js2-infix-node-p result)
9114 (js2-node-add-children result
9115 (js2-infix-node-left result)
9116 (js2-infix-node-right result)))
9117 result)))
9118
9119 (defun js2-parse-attribute-access ()
9120 "Parse an E4X XML attribute expression.
9121 This includes expressions of the forms:
9122
9123 @attr @ns::attr @ns::*
9124 @* @*::attr @*::*
9125 @[expr] @*::[expr] @ns::[expr]
9126
9127 Called if we peeked an '@' token."
9128 (let ((tt (js2-next-token))
9129 (at-pos (js2-current-token-beg)))
9130 (cond
9131 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9132 ((js2-valid-prop-name-token tt)
9133 (js2-parse-property-name at-pos nil 0))
9134 ;; handles: @*, @*::name, @*::*, @*::[expr]
9135 ((= tt js2-MUL)
9136 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9137 ;; handles @[expr]
9138 ((= tt js2-LB)
9139 (js2-parse-xml-elem-ref at-pos))
9140 (t
9141 (js2-report-error "msg.no.name.after.xmlAttr")
9142 ;; Avoid cascaded errors that happen if we make an error node here.
9143 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9144
9145 (defun js2-parse-property-name (at-pos s member-type-flags)
9146 "Check if :: follows name in which case it becomes qualified name.
9147
9148 AT-POS is a natural number if we just read an '@' token, else nil.
9149 S is the name or string that was matched: an identifier, 'throw' or '*'.
9150 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9151
9152 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9153 operator, or the name is followed by ::. For a plain name, returns a
9154 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9155 (let ((pos (or at-pos (js2-current-token-beg)))
9156 colon-pos
9157 (name (js2-create-name-node t (js2-current-token-type) s))
9158 ns tt pn)
9159 (catch 'return
9160 (when (js2-match-token js2-COLONCOLON)
9161 (setq ns name
9162 colon-pos (js2-current-token-beg)
9163 tt (js2-next-token))
9164 (cond
9165 ;; handles name::name
9166 ((js2-valid-prop-name-token tt)
9167 (setq name (js2-create-name-node)))
9168 ;; handles name::*
9169 ((= tt js2-MUL)
9170 (setq name (js2-create-name-node nil nil "*")))
9171 ;; handles name::[expr]
9172 ((= tt js2-LB)
9173 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9174 (t
9175 (js2-report-error "msg.no.name.after.coloncolon"))))
9176 (if (and (null ns) (zerop member-type-flags))
9177 name
9178 (prog1
9179 (setq pn
9180 (make-js2-xml-prop-ref-node :pos pos
9181 :len (- (js2-node-end name) pos)
9182 :at-pos at-pos
9183 :colon-pos colon-pos
9184 :propname name))
9185 (js2-node-add-children pn name))))))
9186
9187 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9188 "Parse the [expr] portion of an xml element reference.
9189 For instance, @[expr], @*::[expr], or ns::[expr]."
9190 (let* ((lb (js2-current-token-beg))
9191 (pos (or at-pos lb))
9192 rb
9193 (expr (js2-parse-expr))
9194 (end (js2-node-end expr))
9195 pn)
9196 (if (js2-must-match js2-RB "msg.no.bracket.index")
9197 (setq rb (js2-current-token-beg)
9198 end (js2-current-token-end)))
9199 (prog1
9200 (setq pn
9201 (make-js2-xml-elem-ref-node :pos pos
9202 :len (- end pos)
9203 :namespace namespace
9204 :colon-pos colon-pos
9205 :at-pos at-pos
9206 :expr expr
9207 :lb (js2-relpos lb pos)
9208 :rb (js2-relpos rb pos)))
9209 (js2-node-add-children pn namespace expr))))
9210
9211 (defun js2-parse-destruct-primary-expr ()
9212 (let ((js2-is-in-destructuring t))
9213 (js2-parse-primary-expr)))
9214
9215 (defun js2-parse-primary-expr ()
9216 "Parse a literal (leaf) expression of some sort.
9217 Includes complex literals such as functions, object-literals,
9218 array-literals, array comprehensions and regular expressions."
9219 (let (pn ; parent node (usually return value)
9220 tt)
9221 (setq tt (js2-current-token-type))
9222 (cond
9223 ((= tt js2-FUNCTION)
9224 (js2-parse-function-expr))
9225 ((= tt js2-LB)
9226 (js2-parse-array-comp-or-literal))
9227 ((= tt js2-LC)
9228 (js2-parse-object-literal))
9229 ((= tt js2-LET)
9230 (js2-parse-let (js2-current-token-beg)))
9231 ((= tt js2-LP)
9232 (js2-parse-paren-expr-or-generator-comp))
9233 ((= tt js2-XMLATTR)
9234 (js2-must-have-xml)
9235 (js2-parse-attribute-access))
9236 ((= tt js2-NAME)
9237 (js2-parse-name tt))
9238 ((= tt js2-NUMBER)
9239 (make-js2-number-node))
9240 ((= tt js2-STRING)
9241 (prog1
9242 (make-js2-string-node)
9243 (js2-record-face 'font-lock-string-face)))
9244 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9245 ;; Got / or /= which in this context means a regexp literal
9246 (let ((px-pos (js2-current-token-beg))
9247 (flags (js2-read-regexp tt))
9248 (end (js2-current-token-end)))
9249 (prog1
9250 (make-js2-regexp-node :pos px-pos
9251 :len (- end px-pos)
9252 :value (js2-current-token-string)
9253 :flags flags)
9254 (js2-set-face px-pos end 'font-lock-string-face 'record)
9255 (js2-record-text-property px-pos end 'syntax-table '(2)))))
9256 ((or (= tt js2-NULL)
9257 (= tt js2-THIS)
9258 (= tt js2-FALSE)
9259 (= tt js2-TRUE))
9260 (make-js2-keyword-node :type tt))
9261 ((= tt js2-RP)
9262 ;; Not valid expression syntax, but this is valid in an arrow
9263 ;; function with no params: () => body.
9264 (if (eq (js2-peek-token) js2-ARROW)
9265 (progn
9266 (js2-unget-token) ; Put back the right paren.
9267 ;; Return whatever, it will hopefully be rewinded and
9268 ;; reparsed when we reach the =>.
9269 (make-js2-keyword-node :type js2-NULL))
9270 (js2-report-error "msg.syntax")
9271 (make-js2-error-node)))
9272 ((= tt js2-TRIPLEDOT)
9273 ;; Likewise, only valid in an arrow function with a rest param.
9274 (if (and (js2-match-token js2-NAME)
9275 (js2-match-token js2-RP)
9276 (eq (js2-peek-token) js2-ARROW))
9277 (progn
9278 (js2-unget-token) ; Put back the right paren.
9279 ;; See the previous case.
9280 (make-js2-keyword-node :type js2-NULL))
9281 (js2-report-error "msg.syntax")
9282 (make-js2-error-node)))
9283 ((= tt js2-RESERVED)
9284 (js2-report-error "msg.reserved.id")
9285 (make-js2-name-node))
9286 ((= tt js2-ERROR)
9287 ;; the scanner or one of its subroutines reported the error.
9288 (make-js2-error-node))
9289 ((= tt js2-EOF)
9290 (let* ((px-pos (point-at-bol))
9291 (len (- js2-ts-cursor px-pos)))
9292 (js2-report-error "msg.unexpected.eof" nil px-pos len))
9293 (make-js2-error-node :pos (1- js2-ts-cursor)))
9294 (t
9295 (js2-report-error "msg.syntax")
9296 (make-js2-error-node)))))
9297
9298 (defun js2-parse-name (_tt)
9299 (let ((name (js2-current-token-string))
9300 node)
9301 (setq node (if js2-compiler-xml-available
9302 (js2-parse-property-name nil name 0)
9303 (js2-create-name-node 'check-activation nil name)))
9304 (if js2-highlight-external-variables
9305 (js2-record-name-node node))
9306 node))
9307
9308 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9309 (js2-add-strict-warning
9310 msg nil
9311 ;; back up from comma to beginning of line or array/objlit
9312 (max (if elems
9313 (js2-node-pos (car elems))
9314 pos)
9315 (save-excursion
9316 (goto-char comma-pos)
9317 (back-to-indentation)
9318 (point)))
9319 comma-pos))
9320
9321 (defun js2-parse-array-comp-or-literal ()
9322 (let ((pos (js2-current-token-beg)))
9323 (if (and (>= js2-language-version 200)
9324 (js2-match-token js2-FOR))
9325 (js2-parse-array-comp pos)
9326 (js2-parse-array-literal pos))))
9327
9328 (defun js2-parse-array-literal (pos)
9329 (let ((after-lb-or-comma t)
9330 after-comma tt elems pn
9331 (continue t))
9332 (unless js2-is-in-destructuring
9333 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
9334 (while continue
9335 (setq tt (js2-get-token))
9336 (cond
9337 ;; comma
9338 ((= tt js2-COMMA)
9339 (setq after-comma (js2-current-token-end))
9340 (if (not after-lb-or-comma)
9341 (setq after-lb-or-comma t)
9342 (push nil elems)))
9343 ;; end of array
9344 ((or (= tt js2-RB)
9345 (= tt js2-EOF)) ; prevent infinite loop
9346 (if (= tt js2-EOF)
9347 (js2-report-error "msg.no.bracket.arg" nil pos))
9348 (when (and after-comma (< js2-language-version 170))
9349 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9350 pos (remove nil elems) after-comma))
9351 (setq continue nil
9352 pn (make-js2-array-node :pos pos
9353 :len (- js2-ts-cursor pos)
9354 :elems (nreverse elems)))
9355 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
9356 ;; destructuring binding
9357 (js2-is-in-destructuring
9358 (push (if (or (= tt js2-LC)
9359 (= tt js2-LB)
9360 (= tt js2-NAME))
9361 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9362 (js2-parse-destruct-primary-expr)
9363 ;; invalid pattern
9364 (js2-report-error "msg.bad.var")
9365 (make-js2-error-node))
9366 elems)
9367 (setq after-lb-or-comma nil
9368 after-comma nil))
9369 ;; array comp
9370 ((and (>= js2-language-version 170)
9371 (= tt js2-FOR) ; check for array comprehension
9372 (not after-lb-or-comma) ; "for" can't follow a comma
9373 elems ; must have at least 1 element
9374 (not (cdr elems))) ; but no 2nd element
9375 (js2-unget-token)
9376 (setf continue nil
9377 pn (js2-parse-legacy-array-comp (car elems) pos)))
9378 ;; another element
9379 (t
9380 (unless after-lb-or-comma
9381 (js2-report-error "msg.no.bracket.arg"))
9382 (if (and (= tt js2-TRIPLEDOT)
9383 (>= js2-language-version 200))
9384 ;; spread operator
9385 (push (js2-make-unary tt 'js2-parse-assign-expr)
9386 elems)
9387 (js2-unget-token)
9388 (push (js2-parse-assign-expr) elems))
9389 (setq after-lb-or-comma nil
9390 after-comma nil))))
9391 (unless js2-is-in-destructuring
9392 (js2-pop-scope))
9393 pn))
9394
9395 (defun js2-parse-legacy-array-comp (expr pos)
9396 "Parse a legacy array comprehension (JavaScript 1.7).
9397 EXPR is the first expression after the opening left-bracket.
9398 POS is the beginning of the LB token preceding EXPR.
9399 We should have just parsed the 'for' keyword before calling this function."
9400 (let ((current-scope js2-current-scope)
9401 loops first filter result)
9402 (unwind-protect
9403 (progn
9404 (while (js2-match-token js2-FOR)
9405 (let ((loop (make-js2-comp-loop-node)))
9406 (js2-push-scope loop)
9407 (push loop loops)
9408 (js2-parse-comp-loop loop)))
9409 ;; First loop takes expr scope's parent.
9410 (setf (js2-scope-parent-scope (setq first (car (last loops))))
9411 (js2-scope-parent-scope current-scope))
9412 ;; Set expr scope's parent to the last loop.
9413 (setf (js2-scope-parent-scope current-scope) (car loops))
9414 (if (/= (js2-get-token) js2-IF)
9415 (js2-unget-token)
9416 (setq filter (js2-parse-condition))))
9417 (dotimes (_ (1- (length loops)))
9418 (js2-pop-scope)))
9419 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9420 (setq result (make-js2-comp-node :pos pos
9421 :len (- js2-ts-cursor pos)
9422 :result expr
9423 :loops (nreverse loops)
9424 :filters (and filter (list (car filter)))
9425 :form 'LEGACY_ARRAY))
9426 (apply #'js2-node-add-children result expr (car filter)
9427 (js2-comp-node-loops result))
9428 result))
9429
9430 (defun js2-parse-array-comp (pos)
9431 "Parse an ES6 array comprehension.
9432 POS is the beginning of the LB token.
9433 We should have just parsed the 'for' keyword before calling this function."
9434 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
9435 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9436 pn))
9437
9438 (defun js2-parse-generator-comp (pos)
9439 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
9440 (js2-current-script-or-fn
9441 (make-js2-function-node :generator-type 'COMPREHENSION))
9442 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
9443 (js2-must-match js2-RP "msg.no.paren" pos)
9444 pn))
9445
9446 (defun js2-parse-comprehension (pos form)
9447 (let (loops filters expr result)
9448 (unwind-protect
9449 (progn
9450 (js2-unget-token)
9451 (while (js2-match-token js2-FOR)
9452 (let ((loop (make-js2-comp-loop-node)))
9453 (js2-push-scope loop)
9454 (push loop loops)
9455 (js2-parse-comp-loop loop)))
9456 (while (js2-match-token js2-IF)
9457 (push (car (js2-parse-condition)) filters))
9458 (setq expr (js2-parse-assign-expr)))
9459 (dolist (_ loops)
9460 (js2-pop-scope)))
9461 (setq result (make-js2-comp-node :pos pos
9462 :len (- js2-ts-cursor pos)
9463 :result expr
9464 :loops (nreverse loops)
9465 :filters (nreverse filters)
9466 :form form))
9467 (apply #'js2-node-add-children result (js2-comp-node-loops result))
9468 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
9469 result))
9470
9471 (defun js2-parse-comp-loop (pn &optional only-of-p)
9472 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9473 The current token should be the initial FOR.
9474 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
9475 (let ((pos (js2-comp-loop-node-pos pn))
9476 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9477 (when (and (not only-of-p) (js2-match-token js2-NAME))
9478 (if (string= (js2-current-token-string) "each")
9479 (progn
9480 (setq foreach-p t
9481 each-pos (- (js2-current-token-beg) pos)) ; relative
9482 (js2-record-face 'font-lock-keyword-face))
9483 (js2-report-error "msg.no.paren.for")))
9484 (if (js2-must-match js2-LP "msg.no.paren.for")
9485 (setq lp (- (js2-current-token-beg) pos)))
9486 (setq tt (js2-peek-token))
9487 (cond
9488 ((or (= tt js2-LB)
9489 (= tt js2-LC))
9490 (js2-get-token)
9491 (setq iter (js2-parse-destruct-primary-expr))
9492 (js2-define-destruct-symbols iter js2-LET
9493 'font-lock-variable-name-face t))
9494 ((js2-match-token js2-NAME)
9495 (setq iter (js2-create-name-node)))
9496 (t
9497 (js2-report-error "msg.bad.var")))
9498 ;; Define as a let since we want the scope of the variable to
9499 ;; be restricted to the array comprehension
9500 (if (js2-name-node-p iter)
9501 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9502 (if (or (and (not only-of-p) (js2-match-token js2-IN))
9503 (and (>= js2-language-version 200)
9504 (js2-match-contextual-kwd "of")
9505 (setq forof-p t)))
9506 (setq in-pos (- (js2-current-token-beg) pos))
9507 (js2-report-error "msg.in.after.for.name"))
9508 (setq obj (js2-parse-expr))
9509 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9510 (setq rp (- (js2-current-token-beg) pos)))
9511 (setf (js2-node-pos pn) pos
9512 (js2-node-len pn) (- js2-ts-cursor pos)
9513 (js2-comp-loop-node-iterator pn) iter
9514 (js2-comp-loop-node-object pn) obj
9515 (js2-comp-loop-node-in-pos pn) in-pos
9516 (js2-comp-loop-node-each-pos pn) each-pos
9517 (js2-comp-loop-node-foreach-p pn) foreach-p
9518 (js2-comp-loop-node-forof-p pn) forof-p
9519 (js2-comp-loop-node-lp pn) lp
9520 (js2-comp-loop-node-rp pn) rp)
9521 (js2-node-add-children pn iter obj)
9522 pn))
9523
9524 (defun js2-parse-object-literal ()
9525 (let ((pos (js2-current-token-beg))
9526 tt elems result after-comma
9527 (continue t))
9528 (while continue
9529 (setq tt (js2-get-token))
9530 (cond
9531 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9532 ;; {get foo() {...}}, or {set foo(x) {...}}
9533 ((or (js2-valid-prop-name-token tt)
9534 (= tt js2-STRING))
9535 (setq after-comma nil
9536 result (js2-parse-named-prop tt))
9537 (if (and (null result)
9538 (not js2-recover-from-parse-errors))
9539 (setq continue nil)
9540 (push result elems)))
9541 ;; {12: x} or {10.7: x}
9542 ((= tt js2-NUMBER)
9543 (setq after-comma nil)
9544 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9545 ;; trailing comma
9546 ((= tt js2-RC)
9547 (js2-unget-token)
9548 (setq continue nil)
9549 (if after-comma
9550 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9551 pos elems after-comma)))
9552 (t
9553 (js2-report-error "msg.bad.prop")
9554 (unless js2-recover-from-parse-errors
9555 (setq continue nil)))) ; end switch
9556 (if (js2-match-token js2-COMMA)
9557 (setq after-comma (js2-current-token-end))
9558 (setq continue nil))) ; end loop
9559 (js2-must-match js2-RC "msg.no.brace.prop")
9560 (setq result (make-js2-object-node :pos pos
9561 :len (- js2-ts-cursor pos)
9562 :elems (nreverse elems)))
9563 (apply #'js2-node-add-children result (js2-object-node-elems result))
9564 result))
9565
9566 (defun js2-parse-named-prop (tt)
9567 "Parse a name, string, or getter/setter object property.
9568 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9569 (let ((string-prop (and (= tt js2-STRING)
9570 (make-js2-string-node)))
9571 expr
9572 (ppos (js2-current-token-beg))
9573 (pend (js2-current-token-end))
9574 (name (js2-create-name-node))
9575 (prop (js2-current-token-string)))
9576 (cond
9577 ;; getter/setter prop
9578 ((and (= tt js2-NAME)
9579 (= (js2-peek-token) js2-NAME)
9580 (or (string= prop "get")
9581 (string= prop "set")))
9582 (js2-get-token)
9583 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9584 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9585 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9586 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9587 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9588 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9589 ;; when patterns are used in variable declarations, function parameters,
9590 ;; catch-clause, and iterators.
9591 ;; We have to set `js2-is-in-destructuring' to t when the current
9592 ;; expressions are on the left side of any assignment, but it's difficult
9593 ;; because it requires looking ahead of expression.
9594 ((and js2-is-in-destructuring
9595 (= tt js2-NAME)
9596 (let ((ctk (js2-peek-token)))
9597 (or (= ctk js2-COMMA)
9598 (= ctk js2-RC)
9599 (js2-valid-prop-name-token ctk))))
9600 name)
9601 ;; regular prop
9602 (t
9603 (prog1
9604 (setq expr (js2-parse-plain-property (or string-prop name)))
9605 (js2-set-face ppos pend
9606 (if (js2-function-node-p
9607 (js2-object-prop-node-right expr))
9608 'font-lock-function-name-face
9609 'font-lock-variable-name-face)
9610 'record))))))
9611
9612 (defun js2-parse-plain-property (prop)
9613 "Parse a non-getter/setter property in an object literal.
9614 PROP is the node representing the property: a number, name or string."
9615 (let* ((tt (js2-get-token))
9616 (pos (js2-node-pos prop))
9617 colon expr result)
9618 (cond
9619 ;; Abbreviated property, as in {foo, bar}
9620 ((and (>= js2-language-version 200)
9621 (or (= tt js2-COMMA)
9622 (= tt js2-RC)))
9623 (js2-unget-token)
9624 (setq result (make-js2-object-prop-node
9625 :pos pos
9626 :left prop
9627 :right prop
9628 :op-pos (js2-current-token-len)))
9629 (js2-node-add-children result prop)
9630 (js2-node-set-prop result 'SHORTHAND t)
9631 result)
9632 ;; Normal property
9633 (t
9634 (if (= tt js2-COLON)
9635 (setq colon (- (js2-current-token-beg) pos)
9636 expr (js2-parse-assign-expr))
9637 (js2-report-error "msg.no.colon.prop")
9638 (setq expr (make-js2-error-node)))
9639 (setq result (make-js2-object-prop-node
9640 :pos pos
9641 ;; don't include last consumed token in length
9642 :len (- (+ (js2-node-pos expr)
9643 (js2-node-len expr))
9644 pos)
9645 :left prop
9646 :right expr
9647 :op-pos colon))
9648 (js2-node-add-children result prop expr)
9649 result))))
9650
9651 (defun js2-parse-getter-setter-prop (pos prop get-p)
9652 "Parse getter or setter property in an object literal.
9653 JavaScript syntax is:
9654
9655 { get foo() {...}, set foo(x) {...} }
9656
9657 and expression closure style is also supported
9658
9659 { get foo() x, set foo(x) _x = x }
9660
9661 POS is the start position of the `get' or `set' keyword.
9662 PROP is the `js2-name-node' representing the property name.
9663 GET-P is non-nil if the keyword was `get'."
9664 (let ((type (if get-p js2-GET js2-SET))
9665 result end
9666 (fn (js2-parse-function-expr)))
9667 ;; it has to be an anonymous function, as we already parsed the name
9668 (if (/= (js2-node-type fn) js2-FUNCTION)
9669 (js2-report-error "msg.bad.prop")
9670 (if (plusp (length (js2-function-name fn)))
9671 (js2-report-error "msg.bad.prop")))
9672 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9673 (setq end (js2-node-end fn)
9674 result (make-js2-getter-setter-node :type type
9675 :pos pos
9676 :len (- end pos)
9677 :left prop
9678 :right fn))
9679 (js2-node-add-children result prop fn)
9680 result))
9681
9682 (defun js2-create-name-node (&optional check-activation-p token string)
9683 "Create a name node using the current token and, optionally, STRING.
9684 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
9685 (let* ((beg (js2-current-token-beg))
9686 (tt (js2-current-token-type))
9687 (s (or string
9688 (if (= js2-NAME tt)
9689 (js2-current-token-string)
9690 (js2-tt-name tt))))
9691 name)
9692 (setq name (make-js2-name-node :pos beg
9693 :name s
9694 :len (length s)))
9695 (if check-activation-p
9696 (js2-check-activation-name s (or token js2-NAME)))
9697 name))
9698
9699 ;;; Indentation support
9700
9701 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9702 ;; Karl cleverly deduces that the desired indentation level is often a
9703 ;; function of paren/bracket/brace nesting depth, which can be determined
9704 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9705 ;; then does some equally clever checks to see if we're in the context of a
9706 ;; substatement of a possibly braceless statement keyword such as if, while,
9707 ;; or finally. This approach yields pretty good results.
9708
9709 ;; The indenter is often "wrong", however, and needs to be overridden.
9710 ;; The right long-term solution is probably to emulate (or integrate
9711 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9712 ;; parse tree from `js2-parse' is present, which is not true at the
9713 ;; moment the user is typing, computing indentation is still thousands
9714 ;; of lines of code to handle every possible syntactic edge case.
9715
9716 ;; In the meantime, the compromise solution is that we offer a "bounce
9717 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9718 ;; current line indent among various likely guess points. This approach
9719 ;; is far from perfect, but should at least make it slightly easier to
9720 ;; move the line towards its desired indentation when manually
9721 ;; overriding Karl's heuristic nesting guesser.
9722
9723 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9724 ;; extensions such as `let' and Array comprehensions. Major kudos to
9725 ;; Karl for coming up with the initial approach, which packs a lot of
9726 ;; punch for so little code.
9727
9728 (defconst js2-possibly-braceless-keywords-re
9729 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9730 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9731 "try" "while" "with" "let")))
9732 "Regular expression matching keywords that are optionally
9733 followed by an opening brace.")
9734
9735 (defconst js2-indent-operator-re
9736 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
9737 (regexp-opt '("in" "instanceof") 'words))
9738 "Regular expression matching operators that affect indentation
9739 of continued expressions.")
9740
9741 (defconst js2-declaration-keyword-re
9742 (regexp-opt '("var" "let" "const") 'words)
9743 "Regular expression matching variable declaration keywords.")
9744
9745 (defun js2-re-search-forward-inner (regexp &optional bound count)
9746 "Auxiliary function for `js2-re-search-forward'."
9747 (let (parse saved-point)
9748 (while (> count 0)
9749 (re-search-forward regexp bound)
9750 (setq parse (if saved-point
9751 (parse-partial-sexp saved-point (point))
9752 (syntax-ppss (point))))
9753 (cond ((nth 3 parse)
9754 (re-search-forward
9755 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
9756 (save-excursion (end-of-line) (point)) t))
9757 ((nth 7 parse)
9758 (forward-line))
9759 ((or (nth 4 parse)
9760 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9761 (re-search-forward "\\*/"))
9762 (t
9763 (setq count (1- count))))
9764 (setq saved-point (point))))
9765 (point))
9766
9767 (defun js2-re-search-forward (regexp &optional bound noerror count)
9768 "Search forward but ignore strings and comments.
9769 Invokes `re-search-forward' but treats the buffer as if strings
9770 and comments have been removed."
9771 (let ((saved-point (point)))
9772 (condition-case err
9773 (cond ((null count)
9774 (js2-re-search-forward-inner regexp bound 1))
9775 ((< count 0)
9776 (js2-re-search-backward-inner regexp bound (- count)))
9777 ((> count 0)
9778 (js2-re-search-forward-inner regexp bound count)))
9779 (search-failed
9780 (goto-char saved-point)
9781 (unless noerror
9782 (error (error-message-string err)))))))
9783
9784 (defun js2-re-search-backward-inner (regexp &optional bound count)
9785 "Auxiliary function for `js2-re-search-backward'."
9786 (let (parse)
9787 (while (> count 0)
9788 (re-search-backward regexp bound)
9789 (setq parse (syntax-ppss (point)))
9790 (cond ((nth 3 parse)
9791 (re-search-backward
9792 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9793 (line-beginning-position) t))
9794 ((nth 7 parse)
9795 (goto-char (nth 8 parse)))
9796 ((or (nth 4 parse)
9797 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9798 (re-search-backward "/\\*"))
9799 (t
9800 (setq count (1- count))))))
9801 (point))
9802
9803 (defun js2-re-search-backward (regexp &optional bound noerror count)
9804 "Search backward but ignore strings and comments.
9805 Invokes `re-search-backward' but treats the buffer as if strings
9806 and comments have been removed."
9807 (let ((saved-point (point)))
9808 (condition-case err
9809 (cond ((null count)
9810 (js2-re-search-backward-inner regexp bound 1))
9811 ((< count 0)
9812 (js2-re-search-forward-inner regexp bound (- count)))
9813 ((> count 0)
9814 (js2-re-search-backward-inner regexp bound count)))
9815 (search-failed
9816 (goto-char saved-point)
9817 (unless noerror
9818 (error (error-message-string err)))))))
9819
9820 (defun js2-looking-at-operator-p ()
9821 "Return non-nil if text after point is a non-comma operator."
9822 (and (looking-at js2-indent-operator-re)
9823 (or (not (looking-at ":"))
9824 (save-excursion
9825 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9826 (looking-at "?"))))))
9827
9828 (defun js2-continued-expression-p ()
9829 "Return non-nil if the current line continues an expression."
9830 (save-excursion
9831 (back-to-indentation)
9832 (or (js2-looking-at-operator-p)
9833 (when (catch 'found
9834 (while (and (re-search-backward "\n" nil t)
9835 (let ((state (syntax-ppss)))
9836 (when (nth 4 state)
9837 (goto-char (nth 8 state))) ;; skip comments
9838 (skip-chars-backward " \t")
9839 (if (bolp)
9840 t
9841 (throw 'found t))))))
9842 (backward-char)
9843 (when (js2-looking-at-operator-p)
9844 (backward-char)
9845 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
9846
9847 (defun js2-end-of-do-while-loop-p ()
9848 "Return non-nil if word after point is `while' of a do-while
9849 statement, else returns nil. A braceless do-while statement
9850 spanning several lines requires that the start of the loop is
9851 indented to the same column as the current line."
9852 (interactive)
9853 (save-excursion
9854 (when (looking-at "\\s-*\\<while\\>")
9855 (if (save-excursion
9856 (skip-chars-backward "[ \t\n]*}")
9857 (looking-at "[ \t\n]*}"))
9858 (save-excursion
9859 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9860 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9861 (or (looking-at "\\<do\\>")
9862 (let ((saved-indent (current-indentation)))
9863 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9864 (/= (current-indentation) saved-indent)))
9865 (and (looking-at "[ \t]*\\<do\\>")
9866 (not (js2-re-search-forward
9867 "\\<while\\>" (point-at-eol) t))
9868 (= (current-indentation) saved-indent))))))))
9869
9870 (defun js2-multiline-decl-indentation ()
9871 "Return the declaration indentation column if the current line belongs
9872 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9873 (let (forward-sexp-function ; use Lisp version
9874 at-opening-bracket)
9875 (save-excursion
9876 (back-to-indentation)
9877 (when (not (looking-at js2-declaration-keyword-re))
9878 (when (looking-at js2-indent-operator-re)
9879 (goto-char (match-end 0))) ; continued expressions are ok
9880 (while (and (not at-opening-bracket)
9881 (not (bobp))
9882 (let ((pos (point)))
9883 (save-excursion
9884 (js2-backward-sws)
9885 (or (eq (char-before) ?,)
9886 (and (not (eq (char-before) ?\;))
9887 (prog2 (skip-syntax-backward ".")
9888 (looking-at js2-indent-operator-re)
9889 (js2-backward-sws))
9890 (not (eq (char-before) ?\;)))
9891 (js2-same-line pos)))))
9892 (condition-case _
9893 (backward-sexp)
9894 (scan-error (setq at-opening-bracket t))))
9895 (when (looking-at js2-declaration-keyword-re)
9896 (goto-char (match-end 0))
9897 (1+ (current-column)))))))
9898
9899 (defun js2-ctrl-statement-indentation ()
9900 "Return the proper indentation of current line if it is a control statement.
9901 Returns an indentation if this line starts the body of a control
9902 statement without braces, else returns nil."
9903 (let (forward-sexp-function)
9904 (save-excursion
9905 (back-to-indentation)
9906 (when (and (not (js2-same-line (point-min)))
9907 (not (looking-at "{"))
9908 (js2-re-search-backward "[[:graph:]]" nil t)
9909 (not (looking-at "[{([]"))
9910 (progn
9911 (forward-char)
9912 (when (= (char-before) ?\))
9913 ;; scan-sexps sometimes throws an error
9914 (ignore-errors (backward-sexp))
9915 (skip-chars-backward " \t" (point-at-bol)))
9916 (let ((pt (point)))
9917 (back-to-indentation)
9918 (when (looking-at "}[ \t]*")
9919 (goto-char (match-end 0)))
9920 (and (looking-at js2-possibly-braceless-keywords-re)
9921 (= (match-end 0) pt)
9922 (not (js2-end-of-do-while-loop-p))))))
9923 (+ (current-indentation) js2-basic-offset)))))
9924
9925 (defun js2-indent-in-array-comp (parse-status)
9926 "Return non-nil if we think we're in an array comprehension.
9927 In particular, return the buffer position of the first `for' kwd."
9928 (let ((bracket (nth 1 parse-status))
9929 (end (point)))
9930 (when bracket
9931 (save-excursion
9932 (goto-char bracket)
9933 (when (looking-at "\\[")
9934 (forward-char 1)
9935 (js2-forward-sws)
9936 (if (looking-at "[[{]")
9937 (let (forward-sexp-function) ; use Lisp version
9938 (forward-sexp) ; skip destructuring form
9939 (js2-forward-sws)
9940 (if (and (/= (char-after) ?,) ; regular array
9941 (looking-at "for"))
9942 (match-beginning 0)))
9943 ;; to skip arbitrary expressions we need the parser,
9944 ;; so we'll just guess at it.
9945 (if (and (> end (point)) ; not empty literal
9946 (re-search-forward "[^,]]* \\(for\\) " end t)
9947 ;; not inside comment or string literal
9948 (let ((state (parse-partial-sexp bracket (point))))
9949 (not (or (nth 3 state) (nth 4 state)))))
9950 (match-beginning 1))))))))
9951
9952 (defun js2-array-comp-indentation (parse-status for-kwd)
9953 (if (js2-same-line for-kwd)
9954 ;; first continuation line
9955 (save-excursion
9956 (goto-char (nth 1 parse-status))
9957 (forward-char 1)
9958 (skip-chars-forward " \t")
9959 (current-column))
9960 (save-excursion
9961 (goto-char for-kwd)
9962 (current-column))))
9963
9964 (defun js2-proper-indentation (parse-status)
9965 "Return the proper indentation for the current line."
9966 (save-excursion
9967 (back-to-indentation)
9968 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9969 (at-closing-bracket (looking-at "[]})]"))
9970 (same-indent-p (or at-closing-bracket
9971 (looking-at "\\<case\\>[^:]")
9972 (and (looking-at "\\<default:")
9973 (save-excursion
9974 (js2-backward-sws)
9975 (not (memq (char-before) '(?, ?{)))))))
9976 (continued-expr-p (js2-continued-expression-p))
9977 (declaration-indent (and js2-pretty-multiline-declarations
9978 (js2-multiline-decl-indentation)))
9979 (bracket (nth 1 parse-status))
9980 beg indent)
9981 (cond
9982 ;; indent array comprehension continuation lines specially
9983 ((and bracket
9984 (>= js2-language-version 170)
9985 (not (js2-same-line bracket))
9986 (setq beg (js2-indent-in-array-comp parse-status))
9987 (>= (point) (save-excursion
9988 (goto-char beg)
9989 (point-at-bol)))) ; at or after first loop?
9990 (js2-array-comp-indentation parse-status beg))
9991
9992 (ctrl-stmt-indent)
9993
9994 ((and declaration-indent continued-expr-p)
9995 (+ declaration-indent js2-basic-offset))
9996
9997 (declaration-indent)
9998
9999 (bracket
10000 (goto-char bracket)
10001 (cond
10002 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10003 (when (save-excursion (skip-chars-backward " \t)")
10004 (looking-at ")"))
10005 (backward-list))
10006 (back-to-indentation)
10007 (and (eq js2-pretty-multiline-declarations 'all)
10008 (looking-at js2-declaration-keyword-re)
10009 (goto-char (1+ (match-end 0))))
10010 (setq indent
10011 (cond (same-indent-p
10012 (current-column))
10013 (continued-expr-p
10014 (+ (current-column) (* 2 js2-basic-offset)))
10015 (t
10016 (+ (current-column) js2-basic-offset))))
10017 (if (and js2-indent-switch-body
10018 (not at-closing-bracket)
10019 (looking-at "\\_<switch\\_>"))
10020 (+ indent js2-basic-offset)
10021 indent))
10022 (t
10023 (unless same-indent-p
10024 (forward-char)
10025 (skip-chars-forward " \t"))
10026 (current-column))))
10027
10028 (continued-expr-p js2-basic-offset)
10029
10030 (t 0)))))
10031
10032 (defun js2-lineup-comment (parse-status)
10033 "Indent a multi-line block comment continuation line."
10034 (let* ((beg (nth 8 parse-status))
10035 (first-line (js2-same-line beg))
10036 (offset (save-excursion
10037 (goto-char beg)
10038 (if (looking-at "/\\*")
10039 (+ 1 (current-column))
10040 0))))
10041 (unless first-line
10042 (indent-line-to offset))))
10043
10044 (defun js2-backward-sws ()
10045 "Move backward through whitespace and comments."
10046 (interactive)
10047 (while (forward-comment -1)))
10048
10049 (defun js2-forward-sws ()
10050 "Move forward through whitespace and comments."
10051 (interactive)
10052 (while (forward-comment 1)))
10053
10054 (defun js2-current-indent (&optional pos)
10055 "Return column of indentation on current line.
10056 If POS is non-nil, go to that point and return indentation for that line."
10057 (save-excursion
10058 (if pos
10059 (goto-char pos))
10060 (back-to-indentation)
10061 (current-column)))
10062
10063 (defun js2-arglist-close ()
10064 "Return non-nil if we're on a line beginning with a close-paren/brace."
10065 (save-excursion
10066 (goto-char (point-at-bol))
10067 (js2-forward-sws)
10068 (looking-at "[])}]")))
10069
10070 (defun js2-indent-looks-like-label-p ()
10071 (goto-char (point-at-bol))
10072 (js2-forward-sws)
10073 (looking-at (concat js2-mode-identifier-re ":")))
10074
10075 (defun js2-indent-in-objlit-p (parse-status)
10076 "Return non-nil if this looks like an object-literal entry."
10077 (let ((start (nth 1 parse-status)))
10078 (and
10079 start
10080 (save-excursion
10081 (and (zerop (forward-line -1))
10082 (not (< (point) start)) ; crossed a {} boundary
10083 (js2-indent-looks-like-label-p)))
10084 (save-excursion
10085 (js2-indent-looks-like-label-p)))))
10086
10087 ;; If prev line looks like foobar({ then we're passing an object
10088 ;; literal to a function call, and people pretty much always want to
10089 ;; de-dent back to the previous line, so move the 'basic-offset'
10090 ;; position to the front.
10091 (defun js2-indent-objlit-arg-p (parse-status)
10092 (save-excursion
10093 (back-to-indentation)
10094 (js2-backward-sws)
10095 (and (eq (1- (point)) (nth 1 parse-status))
10096 (eq (char-before) ?{)
10097 (progn
10098 (forward-char -1)
10099 (skip-chars-backward " \t")
10100 (eq (char-before) ?\()))))
10101
10102 (defun js2-indent-case-block-p ()
10103 (save-excursion
10104 (back-to-indentation)
10105 (js2-backward-sws)
10106 (goto-char (point-at-bol))
10107 (skip-chars-forward " \t")
10108 (looking-at "case\\s-.+:")))
10109
10110 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10111 "Cycle among alternate computed indentation positions.
10112 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10113 of the buffer to the current point. NORMAL-COL is the indentation
10114 column computed by the heuristic guesser based on current paren,
10115 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10116 in reverse."
10117 (let ((cur-indent (js2-current-indent))
10118 (old-buffer-undo-list buffer-undo-list)
10119 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10120 (current-line (save-excursion
10121 (forward-line 0) ; move to bol
10122 (1+ (count-lines (point-min) (point)))))
10123 positions pos main-pos anchor arglist-cont same-indent
10124 basic-offset computed-pos)
10125 ;; temporarily don't record undo info, if user requested this
10126 (when js2-mode-indent-inhibit-undo
10127 (setq buffer-undo-list t))
10128 (unwind-protect
10129 (progn
10130 ;; First likely point: indent from beginning of previous code line
10131 (push (setq basic-offset
10132 (+ (save-excursion
10133 (back-to-indentation)
10134 (js2-backward-sws)
10135 (back-to-indentation)
10136 (current-column))
10137 js2-basic-offset))
10138 positions)
10139
10140 ;; (First + epsilon) likely point: indent 2x from beginning of
10141 ;; previous code line. Google does it this way.
10142 (push (setq basic-offset
10143 (+ (save-excursion
10144 (back-to-indentation)
10145 (js2-backward-sws)
10146 (back-to-indentation)
10147 (current-column))
10148 (* 2 js2-basic-offset)))
10149 positions)
10150
10151 ;; Second likely point: indent from assign-expr RHS. This
10152 ;; is just a crude guess based on finding " = " on the previous
10153 ;; line containing actual code.
10154 (setq pos (save-excursion
10155 (forward-line -1)
10156 (goto-char (point-at-bol))
10157 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10158 (point-at-eol) t)
10159 (goto-char (match-end 1))
10160 (skip-chars-forward " \t\r\n")
10161 (current-column))))
10162 (when pos
10163 (incf pos js2-basic-offset)
10164 (push pos positions))
10165
10166 ;; Third likely point: same indent as previous line of code.
10167 ;; Make it the first likely point if we're not on an
10168 ;; arglist-close line and previous line ends in a comma, or
10169 ;; both this line and prev line look like object-literal
10170 ;; elements.
10171 (setq pos (save-excursion
10172 (goto-char (point-at-bol))
10173 (js2-backward-sws)
10174 (back-to-indentation)
10175 (prog1
10176 (current-column)
10177 ;; while we're here, look for trailing comma
10178 (if (save-excursion
10179 (goto-char (point-at-eol))
10180 (js2-backward-sws)
10181 (eq (char-before) ?,))
10182 (setq arglist-cont (1- (point)))))))
10183 (when pos
10184 (if (and (or arglist-cont
10185 (js2-indent-in-objlit-p parse-status))
10186 (not (js2-arglist-close)))
10187 (setq same-indent pos))
10188 (push pos positions))
10189
10190 ;; Fourth likely point: first preceding code with less indentation.
10191 ;; than the immediately preceding code line.
10192 (setq pos (save-excursion
10193 (back-to-indentation)
10194 (js2-backward-sws)
10195 (back-to-indentation)
10196 (setq anchor (current-column))
10197 (while (and (zerop (forward-line -1))
10198 (>= (progn
10199 (back-to-indentation)
10200 (current-column))
10201 anchor)))
10202 (setq pos (current-column))))
10203 (push pos positions)
10204
10205 ;; nesting-heuristic position, main by default
10206 (push (setq main-pos normal-col) positions)
10207
10208 ;; delete duplicates and sort positions list
10209 (setq positions (sort (delete-dups positions) '<))
10210
10211 ;; comma-list continuation lines: prev line indent takes precedence
10212 (if same-indent
10213 (setq main-pos same-indent))
10214
10215 ;; common special cases where we want to indent in from previous line
10216 (if (or (js2-indent-case-block-p)
10217 (js2-indent-objlit-arg-p parse-status))
10218 (setq main-pos basic-offset))
10219
10220 ;; if bouncing backwards, reverse positions list
10221 (if backwards
10222 (setq positions (reverse positions)))
10223
10224 ;; record whether we're already sitting on one of the alternatives
10225 (setq pos (member cur-indent positions))
10226
10227 (cond
10228 ;; case 0: we're one one of the alternatives and this is the
10229 ;; first time they've pressed TAB on this line (best-guess).
10230 ((and js2-mode-indent-ignore-first-tab
10231 pos
10232 ;; first time pressing TAB on this line?
10233 (not (eq js2-mode-last-indented-line current-line)))
10234 ;; do nothing
10235 (setq computed-pos nil))
10236 ;; case 1: only one computed position => use it
10237 ((null (cdr positions))
10238 (setq computed-pos 0))
10239 ;; case 2: not on any of the computed spots => use main spot
10240 ((not pos)
10241 (setq computed-pos (js2-position main-pos positions)))
10242 ;; case 3: on last position: cycle to first position
10243 ((null (cdr pos))
10244 (setq computed-pos 0))
10245 ;; case 4: on intermediate position: cycle to next position
10246 (t
10247 (setq computed-pos (js2-position (second pos) positions))))
10248
10249 ;; see if any hooks want to indent; otherwise we do it
10250 (loop with result = nil
10251 for hook in js2-indent-hook
10252 while (null result)
10253 do
10254 (setq result (funcall hook positions computed-pos))
10255 finally do
10256 (unless (or result (null computed-pos))
10257 (indent-line-to (nth computed-pos positions)))))
10258
10259 ;; finally
10260 (if js2-mode-indent-inhibit-undo
10261 (setq buffer-undo-list old-buffer-undo-list))
10262 ;; see commentary for `js2-mode-last-indented-line'
10263 (setq js2-mode-last-indented-line current-line))))
10264
10265 (defun js2-indent-bounce-backwards ()
10266 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10267 cycles between the computed indentation positions in reverse order."
10268 (interactive)
10269 (js2-indent-line t))
10270
10271 (defun js2-1-line-comment-continuation-p ()
10272 "Return t if we're in a 1-line comment continuation.
10273 If so, we don't ever want to use bounce-indent."
10274 (save-excursion
10275 (and (progn
10276 (forward-line 0)
10277 (looking-at "\\s-*//"))
10278 (progn
10279 (forward-line -1)
10280 (forward-line 0)
10281 (when (looking-at "\\s-*$")
10282 (js2-backward-sws)
10283 (forward-line 0))
10284 (looking-at "\\s-*//")))))
10285
10286 (defun js2-indent-line (&optional bounce-backwards)
10287 "Indent the current line as JavaScript source text."
10288 (interactive)
10289 (let (parse-status offset indent-col
10290 ;; Don't whine about errors/warnings when we're indenting.
10291 ;; This has to be set before calling parse-partial-sexp below.
10292 (inhibit-point-motion-hooks t))
10293 (setq parse-status (save-excursion
10294 (syntax-ppss (point-at-bol)))
10295 offset (- (point) (save-excursion
10296 (back-to-indentation)
10297 (point))))
10298 (js2-with-underscore-as-word-syntax
10299 (if (nth 4 parse-status)
10300 (js2-lineup-comment parse-status)
10301 (setq indent-col (js2-proper-indentation parse-status))
10302 ;; See comments below about `js2-mode-last-indented-line'.
10303 (cond
10304 ;; bounce-indenting is disabled during electric-key indent.
10305 ;; It doesn't work well on first line of buffer.
10306 ((and js2-bounce-indent-p
10307 (not (js2-same-line (point-min)))
10308 (not (js2-1-line-comment-continuation-p)))
10309 (js2-bounce-indent indent-col parse-status bounce-backwards))
10310 ;; just indent to the guesser's likely spot
10311 (t (indent-line-to indent-col))))
10312 (when (plusp offset)
10313 (forward-char offset)))))
10314
10315 (defun js2-indent-region (start end)
10316 "Indent the region, but don't use bounce indenting."
10317 (let ((js2-bounce-indent-p nil)
10318 (indent-region-function nil)
10319 (after-change-functions (remq 'js2-mode-edit
10320 after-change-functions)))
10321 (indent-region start end nil) ; nil for byte-compiler
10322 (js2-mode-edit start end (- end start))))
10323
10324 (defvar js2-minor-mode-map
10325 (let ((map (make-sparse-keymap)))
10326 (define-key map (kbd "C-c C-`") #'js2-next-error)
10327 (define-key map [mouse-1] #'js2-mode-show-node)
10328 map)
10329 "Keymap used when `js2-minor-mode' is active.")
10330
10331 ;;;###autoload
10332 (define-minor-mode js2-minor-mode
10333 "Minor mode for running js2 as a background linter.
10334 This allows you to use a different major mode for JavaScript editing,
10335 such as `js-mode', while retaining the asynchronous error/warning
10336 highlighting features of `js2-mode'."
10337 :group 'js2-mode
10338 :lighter " js-lint"
10339 (if js2-minor-mode
10340 (js2-minor-mode-enter)
10341 (js2-minor-mode-exit)))
10342
10343 (defun js2-minor-mode-enter ()
10344 "Initialization for `js2-minor-mode'."
10345 (set (make-local-variable 'max-lisp-eval-depth)
10346 (max max-lisp-eval-depth 3000))
10347 (setq next-error-function #'js2-next-error)
10348 (js2-set-default-externs)
10349 ;; Experiment: make reparse-delay longer for longer files.
10350 (if (plusp js2-dynamic-idle-timer-adjust)
10351 (setq js2-idle-timer-delay
10352 (* js2-idle-timer-delay
10353 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10354 (setq js2-mode-buffer-dirty-p t
10355 js2-mode-parsing nil)
10356 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10357 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10358 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10359 (when js2-include-jslint-globals
10360 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10361 (run-hooks 'js2-init-hook)
10362 (js2-reparse))
10363
10364 (defun js2-minor-mode-exit ()
10365 "Turn off `js2-minor-mode'."
10366 (setq next-error-function nil)
10367 (remove-hook 'after-change-functions #'js2-mode-edit t)
10368 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10369 (when js2-mode-node-overlay
10370 (delete-overlay js2-mode-node-overlay)
10371 (setq js2-mode-node-overlay nil))
10372 (js2-remove-overlays)
10373 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
10374 (setq js2-mode-ast nil))
10375
10376 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10377 (make-variable-buffer-local 'js2-source-buffer)
10378
10379 (defun* js2-display-error-list ()
10380 "Display a navigable buffer listing parse errors/warnings."
10381 (interactive)
10382 (unless (js2-have-errors-p)
10383 (message "No errors")
10384 (return-from js2-display-error-list))
10385 (labels ((annotate-list
10386 (lst type)
10387 "Add diagnostic TYPE and line number to errs list"
10388 (mapcar (lambda (err)
10389 (list err type (line-number-at-pos (nth 1 err))))
10390 lst)))
10391 (let* ((srcbuf (current-buffer))
10392 (errbuf (get-buffer-create "*js-lint*"))
10393 (errors (annotate-list
10394 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10395 'js2-error)) ; must be a valid face name
10396 (warnings (annotate-list
10397 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10398 'js2-warning)) ; must be a valid face name
10399 (all-errs (sort (append errors warnings)
10400 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10401 (with-current-buffer errbuf
10402 (let ((inhibit-read-only t))
10403 (erase-buffer)
10404 (dolist (err all-errs)
10405 (destructuring-bind ((msg-key beg _end &rest) type line) err
10406 (insert-text-button
10407 (format "line %d: %s" line (js2-get-msg msg-key))
10408 'face type
10409 'follow-link "\C-m"
10410 'action 'js2-error-buffer-jump
10411 'js2-msg (js2-get-msg msg-key)
10412 'js2-pos beg)
10413 (insert "\n"))))
10414 (js2-error-buffer-mode)
10415 (setq js2-source-buffer srcbuf)
10416 (pop-to-buffer errbuf)
10417 (goto-char (point-min))
10418 (unless (eobp)
10419 (js2-error-buffer-view))))))
10420
10421 (defvar js2-error-buffer-mode-map
10422 (let ((map (make-sparse-keymap)))
10423 (define-key map "n" #'js2-error-buffer-next)
10424 (define-key map "p" #'js2-error-buffer-prev)
10425 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10426 (define-key map "o" #'js2-error-buffer-view)
10427 (define-key map "q" #'js2-error-buffer-quit)
10428 map)
10429 "Keymap used for js2 diagnostics buffers.")
10430
10431 (defun js2-error-buffer-mode ()
10432 "Major mode for js2 diagnostics buffers.
10433 Selecting an error will jump it to the corresponding source-buffer error.
10434 \\{js2-error-buffer-mode-map}"
10435 (interactive)
10436 (setq major-mode 'js2-error-buffer-mode
10437 mode-name "JS Lint Diagnostics")
10438 (use-local-map js2-error-buffer-mode-map)
10439 (setq truncate-lines t)
10440 (set-buffer-modified-p nil)
10441 (setq buffer-read-only t)
10442 (run-hooks 'js2-error-buffer-mode-hook))
10443
10444 (defun js2-error-buffer-next ()
10445 "Move to next error and view it."
10446 (interactive)
10447 (when (zerop (forward-line 1))
10448 (js2-error-buffer-view)))
10449
10450 (defun js2-error-buffer-prev ()
10451 "Move to previous error and view it."
10452 (interactive)
10453 (when (zerop (forward-line -1))
10454 (js2-error-buffer-view)))
10455
10456 (defun js2-error-buffer-quit ()
10457 "Kill the current buffer."
10458 (interactive)
10459 (kill-buffer))
10460
10461 (defun js2-error-buffer-jump (&rest ignored)
10462 "Jump cursor to current error in source buffer."
10463 (interactive)
10464 (when (js2-error-buffer-view)
10465 (pop-to-buffer js2-source-buffer)))
10466
10467 (defun js2-error-buffer-view ()
10468 "Scroll source buffer to show error at current line."
10469 (interactive)
10470 (cond
10471 ((not (eq major-mode 'js2-error-buffer-mode))
10472 (message "Not in a js2 errors buffer"))
10473 ((not (buffer-live-p js2-source-buffer))
10474 (message "Source buffer has been killed"))
10475 ((not (wholenump (get-text-property (point) 'js2-pos)))
10476 (message "There does not seem to be an error here"))
10477 (t
10478 (let ((pos (get-text-property (point) 'js2-pos))
10479 (msg (get-text-property (point) 'js2-msg)))
10480 (save-selected-window
10481 (pop-to-buffer js2-source-buffer)
10482 (goto-char pos)
10483 (message msg))))))
10484
10485 ;;;###autoload
10486 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10487 ;; FIXME: Should derive from js-mode.
10488 "Major mode for editing JavaScript code."
10489 ;; Used by comment-region; don't change it.
10490 (set (make-local-variable 'comment-start) "//")
10491 (set (make-local-variable 'comment-end) "")
10492 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
10493 (set (make-local-variable 'max-lisp-eval-depth)
10494 (max max-lisp-eval-depth 3000))
10495 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10496 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10497 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10498 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10499 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10500 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10501 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10502 ;; for characters inside regexp literals.
10503 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10504 ;; this is necessary to make `show-paren-function' work properly
10505 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10506 ;; needed for M-x rgrep, among other things
10507 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10508
10509 (set (make-local-variable 'electric-indent-chars)
10510 (append "{}()[]:;,*." electric-indent-chars))
10511 (set (make-local-variable 'electric-layout-rules)
10512 '((?\; . after) (?\{ . after) (?\} . before)))
10513
10514 ;; some variables needed by cc-engine for paragraph-fill, etc.
10515 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10516 c-comment-start-regexp "/[*/]\\|\\s|"
10517 c-line-comment-starter "//"
10518 c-paragraph-start js2-paragraph-start
10519 c-paragraph-separate "$"
10520 c-syntactic-ws-start js2-syntactic-ws-start
10521 c-syntactic-ws-end js2-syntactic-ws-end
10522 c-syntactic-eol js2-syntactic-eol)
10523
10524 (let ((c-buffer-is-cc-mode t))
10525 ;; Copied from `js-mode'. Also see Bug#6071.
10526 (make-local-variable 'paragraph-start)
10527 (make-local-variable 'paragraph-separate)
10528 (make-local-variable 'paragraph-ignore-fill-prefix)
10529 (make-local-variable 'adaptive-fill-mode)
10530 (make-local-variable 'adaptive-fill-regexp)
10531 (c-setup-paragraph-variables))
10532
10533 (setq font-lock-defaults '(nil t))
10534
10535 ;; Experiment: make reparse-delay longer for longer files.
10536 (when (plusp js2-dynamic-idle-timer-adjust)
10537 (setq js2-idle-timer-delay
10538 (* js2-idle-timer-delay
10539 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10540
10541 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10542 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10543 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10544 (setq next-error-function #'js2-next-error)
10545 (imenu-add-to-menubar (concat "IM-" mode-name))
10546 (add-to-invisibility-spec '(js2-outline . t))
10547 (set (make-local-variable 'line-move-ignore-invisible) t)
10548 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10549
10550 (setq js2-mode-functions-hidden nil
10551 js2-mode-comments-hidden nil
10552 js2-mode-buffer-dirty-p t
10553 js2-mode-parsing nil)
10554
10555 (js2-set-default-externs)
10556
10557 (when js2-include-jslint-globals
10558 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10559
10560 (run-hooks 'js2-init-hook)
10561
10562 (js2-reparse))
10563
10564 (defun js2-mode-exit ()
10565 "Exit `js2-mode' and clean up."
10566 (interactive)
10567 (when js2-mode-node-overlay
10568 (delete-overlay js2-mode-node-overlay)
10569 (setq js2-mode-node-overlay nil))
10570 (js2-remove-overlays)
10571 (setq js2-mode-ast nil)
10572 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10573 (remove-from-invisibility-spec '(js2-outline . t))
10574 (js2-mode-show-all)
10575 (with-silent-modifications
10576 (js2-clear-face (point-min) (point-max))))
10577
10578 (defun js2-mode-reset-timer ()
10579 "Cancel any existing parse timer and schedule a new one."
10580 (if js2-mode-parse-timer
10581 (cancel-timer js2-mode-parse-timer))
10582 (setq js2-mode-parsing nil)
10583 (let ((timer (timer-create)))
10584 (setq js2-mode-parse-timer timer)
10585 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10586 (timer-set-idle-time timer js2-idle-timer-delay)
10587 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10588 (timer-activate-when-idle timer nil)))
10589
10590 (defun js2-mode-idle-reparse (buffer)
10591 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10592 it to be reparsed when the buffer is selected."
10593 (cond ((eq buffer (current-buffer))
10594 (js2-reparse))
10595 ((buffer-live-p buffer)
10596 ;; reparse when the buffer is selected again
10597 (with-current-buffer buffer
10598 (add-hook 'window-configuration-change-hook
10599 #'js2-mode-idle-reparse-inner
10600 nil t)))))
10601
10602 (defun js2-mode-idle-reparse-inner ()
10603 (remove-hook 'window-configuration-change-hook
10604 #'js2-mode-idle-reparse-inner
10605 t)
10606 (js2-reparse))
10607
10608 (defun js2-mode-edit (_beg _end _len)
10609 "Schedule a new parse after buffer is edited.
10610 Buffer edit spans from BEG to END and is of length LEN."
10611 (setq js2-mode-buffer-dirty-p t)
10612 (js2-mode-hide-overlay)
10613 (js2-mode-reset-timer))
10614
10615 (defun js2-minor-mode-edit (_beg _end _len)
10616 "Callback for buffer edits in `js2-mode'.
10617 Schedules a new parse after buffer is edited.
10618 Buffer edit spans from BEG to END and is of length LEN."
10619 (setq js2-mode-buffer-dirty-p t)
10620 (js2-mode-hide-overlay)
10621 (js2-mode-reset-timer))
10622
10623 (defun js2-reparse (&optional force)
10624 "Re-parse current buffer after user finishes some data entry.
10625 If we get any user input while parsing, including cursor motion,
10626 we discard the parse and reschedule it. If FORCE is nil, then the
10627 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10628 (let (time
10629 interrupted-p
10630 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10631 (unless js2-mode-parsing
10632 (setq js2-mode-parsing t)
10633 (unwind-protect
10634 (when (or js2-mode-buffer-dirty-p force)
10635 (js2-remove-overlays)
10636 (with-silent-modifications
10637 (setq js2-mode-buffer-dirty-p nil
10638 js2-mode-fontifications nil
10639 js2-mode-deferred-properties nil)
10640 (if js2-mode-verbose-parse-p
10641 (message "parsing..."))
10642 (setq time
10643 (js2-time
10644 (setq interrupted-p
10645 (catch 'interrupted
10646 (js2-parse)
10647 ;; if parsing is interrupted, comments and regex
10648 ;; literals stay ignored by `parse-partial-sexp'
10649 (remove-text-properties (point-min) (point-max)
10650 '(syntax-table))
10651 (js2-mode-apply-deferred-properties)
10652 (js2-mode-remove-suppressed-warnings)
10653 (js2-mode-show-warnings)
10654 (js2-mode-show-errors)
10655 (if (>= js2-highlight-level 1)
10656 (js2-highlight-jsdoc js2-mode-ast))
10657 nil))))
10658 (if interrupted-p
10659 (progn
10660 ;; unfinished parse => try again
10661 (setq js2-mode-buffer-dirty-p t)
10662 (js2-mode-reset-timer))
10663 (if js2-mode-verbose-parse-p
10664 (message "Parse time: %s" time)))))
10665 (setq js2-mode-parsing nil)
10666 (unless interrupted-p
10667 (setq js2-mode-parse-timer nil))))))
10668
10669 (defun js2-mode-show-node (event)
10670 "Debugging aid: highlight selected AST node on mouse click."
10671 (interactive "e")
10672 (mouse-set-point event)
10673 (setq deactivate-mark t)
10674 (when js2-mode-show-overlay
10675 (let ((node (js2-node-at-point))
10676 beg end)
10677 (if (null node)
10678 (message "No node found at location %s" (point))
10679 (setq beg (js2-node-abs-pos node)
10680 end (+ beg (js2-node-len node)))
10681 (if js2-mode-node-overlay
10682 (move-overlay js2-mode-node-overlay beg end)
10683 (setq js2-mode-node-overlay (make-overlay beg end))
10684 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10685 (with-silent-modifications
10686 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10687 (message "%s, parent: %s"
10688 (js2-node-short-name node)
10689 (if (js2-node-parent node)
10690 (js2-node-short-name (js2-node-parent node))
10691 "nil"))))))
10692
10693 (defun js2-mode-hide-overlay (&optional _p1 p2)
10694 "Remove the debugging overlay when the point moves.
10695 P1 and P2 are the old and new values of point, respectively."
10696 (when js2-mode-node-overlay
10697 (let ((beg (overlay-start js2-mode-node-overlay))
10698 (end (overlay-end js2-mode-node-overlay)))
10699 ;; Sometimes we're called spuriously.
10700 (unless (and p2
10701 (>= p2 beg)
10702 (<= p2 end))
10703 (with-silent-modifications
10704 (remove-text-properties beg end '(point-left nil)))
10705 (delete-overlay js2-mode-node-overlay)
10706 (setq js2-mode-node-overlay nil)))))
10707
10708 (defun js2-mode-reset ()
10709 "Debugging helper: reset everything."
10710 (interactive)
10711 (js2-mode-exit)
10712 (js2-mode))
10713
10714 (defun js2-mode-show-warn-or-err (e face)
10715 "Highlight a warning or error E with FACE.
10716 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10717 The last element is optional. When present, use instead of FACE."
10718 (let* ((key (first e))
10719 (beg (second e))
10720 (end (+ beg (third e)))
10721 ;; Don't inadvertently go out of bounds.
10722 (beg (max (point-min) (min beg (point-max))))
10723 (end (max (point-min) (min end (point-max))))
10724 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10725 (ovl (make-overlay beg end)))
10726 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10727 (overlay-put ovl 'js2-error t)
10728 (put-text-property beg end 'help-echo (js2-get-msg key))
10729 (put-text-property beg end 'point-entered #'js2-echo-error)))
10730
10731 (defun js2-remove-overlays ()
10732 "Remove overlays from buffer that have a `js2-error' property."
10733 (let ((beg (point-min))
10734 (end (point-max)))
10735 (save-excursion
10736 (dolist (o (overlays-in beg end))
10737 (when (overlay-get o 'js2-error)
10738 (delete-overlay o))))))
10739
10740 (defun js2-error-at-point (&optional pos)
10741 "Return non-nil if there's an error overlay at POS.
10742 Defaults to point."
10743 (loop with pos = (or pos (point))
10744 for o in (overlays-at pos)
10745 thereis (overlay-get o 'js2-error)))
10746
10747 (defun js2-mode-apply-deferred-properties ()
10748 "Apply fontifications and other text properties recorded during parsing."
10749 (when (plusp js2-highlight-level)
10750 ;; We defer clearing faces as long as possible to eliminate flashing.
10751 (js2-clear-face (point-min) (point-max))
10752 ;; Have to reverse the recorded fontifications list so that errors
10753 ;; and warnings overwrite the normal fontifications.
10754 (dolist (f (nreverse js2-mode-fontifications))
10755 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10756 (setq js2-mode-fontifications nil))
10757 (dolist (p js2-mode-deferred-properties)
10758 (apply #'put-text-property p))
10759 (setq js2-mode-deferred-properties nil))
10760
10761 (defun js2-mode-show-errors ()
10762 "Highlight syntax errors."
10763 (when js2-mode-show-parse-errors
10764 (dolist (e (js2-ast-root-errors js2-mode-ast))
10765 (js2-mode-show-warn-or-err e 'js2-error))))
10766
10767 (defun js2-mode-remove-suppressed-warnings ()
10768 "Take suppressed warnings out of the AST warnings list.
10769 This ensures that the counts and `next-error' are correct."
10770 (setf (js2-ast-root-warnings js2-mode-ast)
10771 (js2-delete-if
10772 (lambda (e)
10773 (let ((key (caar e)))
10774 (or
10775 (and (not js2-strict-trailing-comma-warning)
10776 (string-match "trailing\\.comma" key))
10777 (and (not js2-strict-cond-assign-warning)
10778 (string= key "msg.equal.as.assign"))
10779 (and js2-missing-semi-one-line-override
10780 (string= key "msg.missing.semi")
10781 (let* ((beg (second e))
10782 (node (js2-node-at-point beg))
10783 (fn (js2-mode-find-parent-fn node))
10784 (body (and fn (js2-function-node-body fn)))
10785 (lc (and body (js2-node-abs-pos body)))
10786 (rc (and lc (+ lc (js2-node-len body)))))
10787 (and fn
10788 (or (null body)
10789 (save-excursion
10790 (goto-char beg)
10791 (and (js2-same-line lc)
10792 (js2-same-line rc))))))))))
10793 (js2-ast-root-warnings js2-mode-ast))))
10794
10795 (defun js2-mode-show-warnings ()
10796 "Highlight strict-mode warnings."
10797 (when js2-mode-show-strict-warnings
10798 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10799 (js2-mode-show-warn-or-err e 'js2-warning))))
10800
10801 (defun js2-echo-error (_old-point new-point)
10802 "Called by point-motion hooks."
10803 (let ((msg (get-text-property new-point 'help-echo)))
10804 (when (and (stringp msg)
10805 (not (active-minibuffer-window))
10806 (not (current-message)))
10807 (message msg))))
10808
10809 (defalias 'js2-echo-help #'js2-echo-error)
10810
10811 (defun js2-line-break (&optional _soft)
10812 "Break line at point and indent, continuing comment if within one.
10813 If inside a string, and `js2-concat-multiline-strings' is not
10814 nil, turn it into concatenation."
10815 (interactive)
10816 (let ((parse-status (syntax-ppss)))
10817 (cond
10818 ;; Check if we're inside a string.
10819 ((nth 3 parse-status)
10820 (if js2-concat-multiline-strings
10821 (js2-mode-split-string parse-status)
10822 (insert "\n")))
10823 ;; Check if inside a block comment.
10824 ((nth 4 parse-status)
10825 (js2-mode-extend-comment (nth 8 parse-status)))
10826 (t
10827 (newline-and-indent)))))
10828
10829 (defun js2-mode-split-string (parse-status)
10830 "Turn a newline in mid-string into a string concatenation.
10831 PARSE-STATUS is as documented in `parse-partial-sexp'."
10832 (let* ((quote-char (nth 3 parse-status))
10833 (at-eol (eq js2-concat-multiline-strings 'eol)))
10834 (insert quote-char)
10835 (insert (if at-eol " +\n" "\n"))
10836 (unless at-eol
10837 (insert "+ "))
10838 (js2-indent-line)
10839 (insert quote-char)
10840 (when (eolp)
10841 (insert quote-char)
10842 (backward-char 1))))
10843
10844 (defun js2-mode-extend-comment (start-pos)
10845 "Indent the line and, when inside a comment block, add comment prefix."
10846 (let (star single col first-line needs-close)
10847 (save-excursion
10848 (back-to-indentation)
10849 (when (< (point) start-pos)
10850 (goto-char start-pos))
10851 (cond
10852 ((looking-at "\\*[^/]")
10853 (setq star t
10854 col (current-column)))
10855 ((looking-at "/\\*")
10856 (setq star t
10857 first-line t
10858 col (1+ (current-column))))
10859 ((looking-at "//")
10860 (setq single t
10861 col (current-column)))))
10862 ;; Heuristic for whether we need to close the comment:
10863 ;; if we've got a parse error here, assume it's an unterminated
10864 ;; comment.
10865 (setq needs-close
10866 (or
10867 (eq (get-text-property (1- (point)) 'point-entered)
10868 'js2-echo-error)
10869 ;; The heuristic above doesn't work well when we're
10870 ;; creating a comment and there's another one downstream,
10871 ;; as our parser thinks this one ends at the end of the
10872 ;; next one. (You can have a /* inside a js block comment.)
10873 ;; So just close it if the next non-ws char isn't a *.
10874 (and first-line
10875 (eolp)
10876 (save-excursion
10877 (skip-chars-forward " \t\r\n")
10878 (not (eq (char-after) ?*))))))
10879 (delete-horizontal-space)
10880 (insert "\n")
10881 (cond
10882 (star
10883 (indent-to col)
10884 (insert "* ")
10885 (if (and first-line needs-close)
10886 (save-excursion
10887 (insert "\n")
10888 (indent-to col)
10889 (insert "*/"))))
10890 ((and single
10891 (save-excursion
10892 (and (zerop (forward-line 1))
10893 (looking-at "\\s-*//"))))
10894 (indent-to col)
10895 (insert "// ")))
10896 ;; Don't need to extend the comment after all.
10897 (js2-indent-line)))
10898
10899 (defun js2-beginning-of-line ()
10900 "Toggle point between bol and first non-whitespace char in line.
10901 Also moves past comment delimiters when inside comments."
10902 (interactive)
10903 (let (node)
10904 (cond
10905 ((bolp)
10906 (back-to-indentation))
10907 ((looking-at "//")
10908 (skip-chars-forward "/ \t"))
10909 ((and (eq (char-after) ?*)
10910 (setq node (js2-comment-at-point))
10911 (memq (js2-comment-node-format node) '(jsdoc block))
10912 (save-excursion
10913 (skip-chars-backward " \t")
10914 (bolp)))
10915 (skip-chars-forward "\* \t"))
10916 (t
10917 (goto-char (point-at-bol))))))
10918
10919 (defun js2-end-of-line ()
10920 "Toggle point between eol and last non-whitespace char in line."
10921 (interactive)
10922 (if (eolp)
10923 (skip-chars-backward " \t")
10924 (goto-char (point-at-eol))))
10925
10926 (defun js2-mode-wait-for-parse (callback)
10927 "Invoke CALLBACK when parsing is finished.
10928 If parsing is already finished, calls CALLBACK immediately."
10929 (if (not js2-mode-buffer-dirty-p)
10930 (funcall callback)
10931 (push callback js2-mode-pending-parse-callbacks)
10932 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10933
10934 (defun js2-mode-parse-finished ()
10935 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10936 ;; We can't let errors propagate up, since it prevents the
10937 ;; `js2-parse' method from completing normally and returning
10938 ;; the ast, which makes things mysteriously not work right.
10939 (unwind-protect
10940 (dolist (cb js2-mode-pending-parse-callbacks)
10941 (condition-case err
10942 (funcall cb)
10943 (error (message "%s" err))))
10944 (setq js2-mode-pending-parse-callbacks nil)))
10945
10946 (defun js2-mode-flag-region (from to flag)
10947 "Hide or show text from FROM to TO, according to FLAG.
10948 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10949 Returns the created overlay if FLAG is non-nil."
10950 (remove-overlays from to 'invisible 'js2-outline)
10951 (when flag
10952 (let ((o (make-overlay from to)))
10953 (overlay-put o 'invisible 'js2-outline)
10954 (overlay-put o 'isearch-open-invisible
10955 'js2-isearch-open-invisible)
10956 o)))
10957
10958 ;; Function to be set as an outline-isearch-open-invisible' property
10959 ;; to the overlay that makes the outline invisible (see
10960 ;; `js2-mode-flag-region').
10961 (defun js2-isearch-open-invisible (_overlay)
10962 ;; We rely on the fact that isearch places point on the matched text.
10963 (js2-mode-show-element))
10964
10965 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10966 "Return cons cell of bounds of folding overlay at POS.
10967 Returns nil if not found."
10968 (let ((overlays (overlays-at (or pos (point))))
10969 o)
10970 (while (and overlays
10971 (not o))
10972 (if (overlay-get (car overlays) 'invisible)
10973 (setq o (car overlays))
10974 (setq overlays (cdr overlays))))
10975 (if o
10976 (cons (overlay-start o) (overlay-end o)))))
10977
10978 (defun js2-mode-function-at-point (&optional pos)
10979 "Return the innermost function node enclosing current point.
10980 Returns nil if point is not in a function."
10981 (let ((node (js2-node-at-point pos)))
10982 (while (and node (not (js2-function-node-p node)))
10983 (setq node (js2-node-parent node)))
10984 (if (js2-function-node-p node)
10985 node)))
10986
10987 (defun js2-mode-toggle-element ()
10988 "Hide or show the foldable element at the point."
10989 (interactive)
10990 (let (comment fn pos)
10991 (save-excursion
10992 (cond
10993 ;; /* ... */ comment?
10994 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10995 (if (js2-mode-invisible-overlay-bounds
10996 (setq pos (+ 3 (js2-node-abs-pos comment))))
10997 (progn
10998 (goto-char pos)
10999 (js2-mode-show-element))
11000 (js2-mode-hide-element)))
11001 ;; //-comment?
11002 ((save-excursion
11003 (back-to-indentation)
11004 (looking-at js2-mode-//-comment-re))
11005 (js2-mode-toggle-//-comment))
11006 ;; function?
11007 ((setq fn (js2-mode-function-at-point))
11008 (setq pos (and (js2-function-node-body fn)
11009 (js2-node-abs-pos (js2-function-node-body fn))))
11010 (goto-char (1+ pos))
11011 (if (js2-mode-invisible-overlay-bounds)
11012 (js2-mode-show-element)
11013 (js2-mode-hide-element)))
11014 (t
11015 (message "Nothing at point to hide or show"))))))
11016
11017 (defun js2-mode-hide-element ()
11018 "Fold/hide contents of a block, showing ellipses.
11019 Show the hidden text with \\[js2-mode-show-element]."
11020 (interactive)
11021 (if js2-mode-buffer-dirty-p
11022 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11023 (let (node body beg end)
11024 (cond
11025 ((js2-mode-invisible-overlay-bounds)
11026 (message "already hidden"))
11027 (t
11028 (setq node (js2-node-at-point))
11029 (cond
11030 ((js2-block-comment-p node)
11031 (js2-mode-hide-comment node))
11032 (t
11033 (while (and node (not (js2-function-node-p node)))
11034 (setq node (js2-node-parent node)))
11035 (if (and node
11036 (setq body (js2-function-node-body node)))
11037 (progn
11038 (setq beg (js2-node-abs-pos body)
11039 end (+ beg (js2-node-len body)))
11040 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11041 (message "No collapsable element found at point"))))))))
11042
11043 (defun js2-mode-show-element ()
11044 "Show the hidden element at current point."
11045 (interactive)
11046 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11047 (if bounds
11048 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11049 (message "Nothing to un-hide"))))
11050
11051 (defun js2-mode-show-all ()
11052 "Show all of the text in the buffer."
11053 (interactive)
11054 (js2-mode-flag-region (point-min) (point-max) nil))
11055
11056 (defun js2-mode-toggle-hide-functions ()
11057 (interactive)
11058 (if js2-mode-functions-hidden
11059 (js2-mode-show-functions)
11060 (js2-mode-hide-functions)))
11061
11062 (defun js2-mode-hide-functions ()
11063 "Hides all non-nested function bodies in the buffer.
11064 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11065 to open an individual entry."
11066 (interactive)
11067 (if js2-mode-buffer-dirty-p
11068 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11069 (if (null js2-mode-ast)
11070 (message "Oops - parsing failed")
11071 (setq js2-mode-functions-hidden t)
11072 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11073
11074 (defun js2-mode-function-hider (n endp)
11075 (when (not endp)
11076 (let ((tt (js2-node-type n))
11077 body beg end)
11078 (cond
11079 ((and (= tt js2-FUNCTION)
11080 (setq body (js2-function-node-body n)))
11081 (setq beg (js2-node-abs-pos body)
11082 end (+ beg (js2-node-len body)))
11083 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11084 nil) ; don't process children of function
11085 (t
11086 t))))) ; keep processing other AST nodes
11087
11088 (defun js2-mode-show-functions ()
11089 "Un-hide any folded function bodies in the buffer."
11090 (interactive)
11091 (setq js2-mode-functions-hidden nil)
11092 (save-excursion
11093 (goto-char (point-min))
11094 (while (/= (goto-char (next-overlay-change (point)))
11095 (point-max))
11096 (dolist (o (overlays-at (point)))
11097 (when (and (overlay-get o 'invisible)
11098 (not (overlay-get o 'comment)))
11099 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11100
11101 (defun js2-mode-hide-comment (n)
11102 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11103 3 ; /**
11104 2)) ; /*
11105 (beg (+ (js2-node-abs-pos n) head))
11106 (end (- (+ beg (js2-node-len n)) head 2))
11107 (o (js2-mode-flag-region beg end 'hide)))
11108 (overlay-put o 'comment t)))
11109
11110 (defun js2-mode-toggle-hide-comments ()
11111 "Folds all block comments in the buffer.
11112 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11113 to open an individual entry."
11114 (interactive)
11115 (if js2-mode-comments-hidden
11116 (js2-mode-show-comments)
11117 (js2-mode-hide-comments)))
11118
11119 (defun js2-mode-hide-comments ()
11120 (interactive)
11121 (if js2-mode-buffer-dirty-p
11122 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11123 (if (null js2-mode-ast)
11124 (message "Oops - parsing failed")
11125 (setq js2-mode-comments-hidden t)
11126 (dolist (n (js2-ast-root-comments js2-mode-ast))
11127 (when (js2-block-comment-p n)
11128 (js2-mode-hide-comment n)))
11129 (js2-mode-hide-//-comments)))
11130
11131 (defun js2-mode-extend-//-comment (direction)
11132 "Find start or end of a block of similar //-comment lines.
11133 DIRECTION is -1 to look back, 1 to look forward.
11134 INDENT is the indentation level to match.
11135 Returns the end-of-line position of the furthest adjacent
11136 //-comment line with the same indentation as the current line.
11137 If there is no such matching line, returns current end of line."
11138 (let ((pos (point-at-eol))
11139 (indent (current-indentation)))
11140 (save-excursion
11141 (while (and (zerop (forward-line direction))
11142 (looking-at js2-mode-//-comment-re)
11143 (eq indent (length (match-string 1))))
11144 (setq pos (point-at-eol))
11145 pos))))
11146
11147 (defun js2-mode-hide-//-comments ()
11148 "Fold adjacent 1-line comments, showing only snippet of first one."
11149 (let (beg end)
11150 (save-excursion
11151 (goto-char (point-min))
11152 (while (re-search-forward js2-mode-//-comment-re nil t)
11153 (setq beg (point)
11154 end (js2-mode-extend-//-comment 1))
11155 (unless (eq beg end)
11156 (overlay-put (js2-mode-flag-region beg end 'hide)
11157 'comment t))
11158 (goto-char end)
11159 (forward-char 1)))))
11160
11161 (defun js2-mode-toggle-//-comment ()
11162 "Fold or un-fold any multi-line //-comment at point.
11163 Caller should have determined that this line starts with a //-comment."
11164 (let* ((beg (point-at-eol))
11165 (end beg))
11166 (save-excursion
11167 (goto-char end)
11168 (if (js2-mode-invisible-overlay-bounds)
11169 (js2-mode-show-element)
11170 ;; else hide the comment
11171 (setq beg (js2-mode-extend-//-comment -1)
11172 end (js2-mode-extend-//-comment 1))
11173 (unless (eq beg end)
11174 (overlay-put (js2-mode-flag-region beg end 'hide)
11175 'comment t))))))
11176
11177 (defun js2-mode-show-comments ()
11178 "Un-hide any hidden comments, leaving other hidden elements alone."
11179 (interactive)
11180 (setq js2-mode-comments-hidden nil)
11181 (save-excursion
11182 (goto-char (point-min))
11183 (while (/= (goto-char (next-overlay-change (point)))
11184 (point-max))
11185 (dolist (o (overlays-at (point)))
11186 (when (overlay-get o 'comment)
11187 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11188
11189 (defun js2-mode-display-warnings-and-errors ()
11190 "Turn on display of warnings and errors."
11191 (interactive)
11192 (setq js2-mode-show-parse-errors t
11193 js2-mode-show-strict-warnings t)
11194 (js2-reparse 'force))
11195
11196 (defun js2-mode-hide-warnings-and-errors ()
11197 "Turn off display of warnings and errors."
11198 (interactive)
11199 (setq js2-mode-show-parse-errors nil
11200 js2-mode-show-strict-warnings nil)
11201 (js2-reparse 'force))
11202
11203 (defun js2-mode-toggle-warnings-and-errors ()
11204 "Toggle the display of warnings and errors.
11205 Some users don't like having warnings/errors reported while they type."
11206 (interactive)
11207 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11208 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11209 (if (called-interactively-p 'any)
11210 (message "warnings and errors %s"
11211 (if js2-mode-show-parse-errors
11212 "enabled"
11213 "disabled")))
11214 (js2-reparse 'force))
11215
11216 (defun js2-mode-customize ()
11217 (interactive)
11218 (customize-group 'js2-mode))
11219
11220 (defun js2-mode-forward-sexp (&optional arg)
11221 "Move forward across one statement or balanced expression.
11222 With ARG, do it that many times. Negative arg -N means
11223 move backward across N balanced expressions."
11224 (interactive "p")
11225 (setq arg (or arg 1))
11226 (save-restriction
11227 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11228 (js2-reparse)
11229 (let (forward-sexp-function
11230 node (start (point)) pos lp rp child)
11231 (cond
11232 ;; backward-sexp
11233 ;; could probably make this better for some cases:
11234 ;; - if in statement block (e.g. function body), go to parent
11235 ;; - infix exprs like (foo in bar) - maybe go to beginning
11236 ;; of infix expr if in the right-side expression?
11237 ((and arg (minusp arg))
11238 (dotimes (_ (- arg))
11239 (js2-backward-sws)
11240 (forward-char -1) ; Enter the node we backed up to.
11241 (when (setq node (js2-node-at-point (point) t))
11242 (setq pos (js2-node-abs-pos node))
11243 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11244 (setq lp (car parens)
11245 rp (cdr parens)))
11246 (when (and lp (> start lp))
11247 (if (and rp (<= start rp))
11248 ;; Between parens, check if there's a child node we can jump.
11249 (when (setq child (js2-node-closest-child node (point) lp t))
11250 (setq pos (js2-node-abs-pos child)))
11251 ;; Before both parens.
11252 (setq pos lp)))
11253 (let ((state (parse-partial-sexp start pos)))
11254 (goto-char (if (not (zerop (car state)))
11255 ;; Stumble at the unbalanced paren if < 0, or
11256 ;; jump a bit further if > 0.
11257 (scan-sexps start -1)
11258 pos))))
11259 (unless pos (goto-char (point-min)))))
11260 (t
11261 ;; forward-sexp
11262 (dotimes (_ arg)
11263 (js2-forward-sws)
11264 (when (setq node (js2-node-at-point (point) t))
11265 (setq pos (js2-node-abs-pos node))
11266 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11267 (setq lp (car parens)
11268 rp (cdr parens)))
11269 (or
11270 (when (and rp (<= start rp))
11271 (if (> start lp)
11272 (when (setq child (js2-node-closest-child node (point) rp))
11273 (setq pos (js2-node-abs-end child)))
11274 (setq pos (1+ rp))))
11275 ;; No parens or child nodes, looks for the end of the curren node.
11276 (incf pos (js2-node-len
11277 (if (js2-expr-stmt-node-p (js2-node-parent node))
11278 ;; Stop after the semicolon.
11279 (js2-node-parent node)
11280 node))))
11281 (let ((state (save-excursion (parse-partial-sexp start pos))))
11282 (goto-char (if (not (zerop (car state)))
11283 (scan-sexps start 1)
11284 pos))))
11285 (unless pos (goto-char (point-max)))))))))
11286
11287 (defun js2-mode-forward-sexp-parens (node abs-pos)
11288 "Return a cons cell with positions of main parens in NODE."
11289 (cond
11290 ((or (js2-array-node-p node)
11291 (js2-object-node-p node)
11292 (js2-comp-node-p node)
11293 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11294 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11295 ((js2-paren-expr-node-p node)
11296 (let ((lp (js2-node-lp node))
11297 (rp (js2-node-rp node)))
11298 (cons (when lp (+ abs-pos lp))
11299 (when rp (+ abs-pos rp)))))))
11300
11301 (defun js2-node-closest-child (parent point limit &optional before)
11302 (let* ((parent-pos (js2-node-abs-pos parent))
11303 (rpoint (- point parent-pos))
11304 (rlimit (- limit parent-pos))
11305 (min (min rpoint rlimit))
11306 (max (max rpoint rlimit))
11307 found)
11308 (catch 'done
11309 (js2-visit-ast
11310 parent
11311 (lambda (node _end-p)
11312 (if (eq node parent)
11313 t
11314 (let ((pos (js2-node-pos node)) ;; Both relative values.
11315 (end (+ (js2-node-pos node) (js2-node-len node))))
11316 (when (and (>= pos min) (<= end max)
11317 (if before (< pos rpoint) (> end rpoint)))
11318 (setq found node))
11319 (when (> end rpoint)
11320 (throw 'done nil)))
11321 nil))))
11322 found))
11323
11324 (defun js2-errors ()
11325 "Return a list of errors found."
11326 (and js2-mode-ast
11327 (js2-ast-root-errors js2-mode-ast)))
11328
11329 (defun js2-warnings ()
11330 "Return a list of warnings found."
11331 (and js2-mode-ast
11332 (js2-ast-root-warnings js2-mode-ast)))
11333
11334 (defun js2-have-errors-p ()
11335 "Return non-nil if any parse errors or warnings were found."
11336 (or (js2-errors) (js2-warnings)))
11337
11338 (defun js2-errors-and-warnings ()
11339 "Return a copy of the concatenated errors and warnings lists.
11340 They are appended: first the errors, then the warnings.
11341 Entries are of the form (MSG BEG END)."
11342 (when js2-mode-ast
11343 (append (js2-ast-root-errors js2-mode-ast)
11344 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11345
11346 (defun js2-next-error (&optional arg reset)
11347 "Move to next parse error.
11348 Typically invoked via \\[next-error].
11349 ARG is the number of errors, forward or backward, to move.
11350 RESET means start over from the beginning."
11351 (interactive "p")
11352 (if (not (or (js2-errors) (js2-warnings)))
11353 (message "No errors")
11354 (when reset
11355 (goto-char (point-min)))
11356 (let* ((errs (js2-errors-and-warnings))
11357 (continue t)
11358 (start (point))
11359 (count (or arg 1))
11360 (backward (minusp count))
11361 (sorter (if backward '> '<))
11362 (stopper (if backward '< '>))
11363 (count (abs count))
11364 all-errs err)
11365 ;; Sort by start position.
11366 (setq errs (sort errs (lambda (e1 e2)
11367 (funcall sorter (second e1) (second e2))))
11368 all-errs errs)
11369 ;; Find nth error with pos > start.
11370 (while (and errs continue)
11371 (when (funcall stopper (cadar errs) start)
11372 (setq err (car errs))
11373 (if (zerop (decf count))
11374 (setq continue nil)))
11375 (setq errs (cdr errs)))
11376 ;; Clear for `js2-echo-error'.
11377 (message nil)
11378 (if err
11379 (goto-char (second err))
11380 ;; Wrap around to first error.
11381 (goto-char (second (car all-errs)))
11382 ;; If we were already on it, echo msg again.
11383 (if (= (point) start)
11384 (js2-echo-error (point) (point)))))))
11385
11386 (defun js2-down-mouse-3 ()
11387 "Make right-click move the point to the click location.
11388 This makes right-click context menu operations a bit more intuitive.
11389 The point will not move if the region is active, however, to avoid
11390 destroying the region selection."
11391 (interactive)
11392 (when (and js2-move-point-on-right-click
11393 (not mark-active))
11394 (let ((e last-input-event))
11395 (ignore-errors
11396 (goto-char (cadadr e))))))
11397
11398 (defun js2-mode-create-imenu-index ()
11399 "Return an alist for `imenu--index-alist'."
11400 ;; This is built up in `js2-parse-record-imenu' during parsing.
11401 (when js2-mode-ast
11402 ;; if we have an ast but no recorder, they're requesting a rescan
11403 (unless js2-imenu-recorder
11404 (js2-reparse 'force))
11405 (prog1
11406 (js2-build-imenu-index)
11407 (setq js2-imenu-recorder nil
11408 js2-imenu-function-map nil))))
11409
11410 (defun js2-mode-find-tag ()
11411 "Replacement for `find-tag-default'.
11412 `find-tag-default' returns a ridiculous answer inside comments."
11413 (let (beg end)
11414 (js2-with-underscore-as-word-syntax
11415 (save-excursion
11416 (if (and (not (looking-at "[[:alnum:]_$]"))
11417 (looking-back "[[:alnum:]_$]"))
11418 (setq beg (progn (forward-word -1) (point))
11419 end (progn (forward-word 1) (point)))
11420 (setq beg (progn (forward-word 1) (point))
11421 end (progn (forward-word -1) (point))))
11422 (replace-regexp-in-string
11423 "[\"']" ""
11424 (buffer-substring-no-properties beg end))))))
11425
11426 (defun js2-mode-forward-sibling ()
11427 "Move to the end of the sibling following point in parent.
11428 Returns non-nil if successful, or nil if there was no following sibling."
11429 (let* ((node (js2-node-at-point))
11430 (parent (js2-mode-find-enclosing-fn node))
11431 sib)
11432 (when (setq sib (js2-node-find-child-after (point) parent))
11433 (goto-char (+ (js2-node-abs-pos sib)
11434 (js2-node-len sib))))))
11435
11436 (defun js2-mode-backward-sibling ()
11437 "Move to the beginning of the sibling node preceding point in parent.
11438 Parent is defined as the enclosing script or function."
11439 (let* ((node (js2-node-at-point))
11440 (parent (js2-mode-find-enclosing-fn node))
11441 sib)
11442 (when (setq sib (js2-node-find-child-before (point) parent))
11443 (goto-char (js2-node-abs-pos sib)))))
11444
11445 (defun js2-beginning-of-defun (&optional arg)
11446 "Go to line on which current function starts, and return t on success.
11447 If we're not in a function or already at the beginning of one, go
11448 to beginning of previous script-level element.
11449 With ARG N, do that N times. If N is negative, move forward."
11450 (setq arg (or arg 1))
11451 (if (plusp arg)
11452 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11453 (when (cond
11454 ((js2-function-node-p parent)
11455 (goto-char (js2-node-abs-pos parent)))
11456 (t
11457 (js2-mode-backward-sibling)))
11458 (if (> arg 1)
11459 (js2-beginning-of-defun (1- arg))
11460 t)))
11461 (when (js2-end-of-defun)
11462 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
11463
11464 (defun js2-end-of-defun ()
11465 "Go to the char after the last position of the current function
11466 or script-level element."
11467 (let* ((node (js2-node-at-point))
11468 (parent (or (and (js2-function-node-p node) node)
11469 (js2-node-parent-script-or-fn node)))
11470 script)
11471 (unless (js2-function-node-p parent)
11472 ;; Use current script-level node, or, if none, the next one.
11473 (setq script (or parent node)
11474 parent (js2-node-find-child-before (point) script))
11475 (when (or (null parent)
11476 (>= (point) (+ (js2-node-abs-pos parent)
11477 (js2-node-len parent))))
11478 (setq parent (js2-node-find-child-after (point) script))))
11479 (when parent
11480 (goto-char (+ (js2-node-abs-pos parent)
11481 (js2-node-len parent))))))
11482
11483 (defun js2-mark-defun (&optional allow-extend)
11484 "Put mark at end of this function, point at beginning.
11485 The function marked is the one that contains point.
11486
11487 Interactively, if this command is repeated,
11488 or (in Transient Mark mode) if the mark is active,
11489 it marks the next defun after the ones already marked."
11490 (interactive "p")
11491 (let (extended)
11492 (when (and allow-extend
11493 (or (and (eq last-command this-command) (mark t))
11494 (and transient-mark-mode mark-active)))
11495 (let ((sib (save-excursion
11496 (goto-char (mark))
11497 (if (js2-mode-forward-sibling)
11498 (point)))))
11499 (if sib
11500 (progn
11501 (set-mark sib)
11502 (setq extended t))
11503 ;; no more siblings - try extending to enclosing node
11504 (goto-char (mark t)))))
11505 (when (not extended)
11506 (let ((node (js2-node-at-point (point) t)) ; skip comments
11507 ast fn stmt parent beg end)
11508 (when (js2-ast-root-p node)
11509 (setq ast node
11510 node (or (js2-node-find-child-after (point) node)
11511 (js2-node-find-child-before (point) node))))
11512 ;; only mark whole buffer if we can't find any children
11513 (if (null node)
11514 (setq node ast))
11515 (if (js2-function-node-p node)
11516 (setq parent node)
11517 (setq fn (js2-mode-find-enclosing-fn node)
11518 stmt (if (or (null fn)
11519 (js2-ast-root-p fn))
11520 (js2-mode-find-first-stmt node))
11521 parent (or stmt fn)))
11522 (setq beg (js2-node-abs-pos parent)
11523 end (+ beg (js2-node-len parent)))
11524 (push-mark beg)
11525 (goto-char end)
11526 (exchange-point-and-mark)))))
11527
11528 (defun js2-narrow-to-defun ()
11529 "Narrow to the function enclosing point."
11530 (interactive)
11531 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11532 (fn (if (js2-script-node-p node)
11533 node
11534 (js2-mode-find-enclosing-fn node)))
11535 (beg (js2-node-abs-pos fn)))
11536 (unless (js2-ast-root-p fn)
11537 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11538
11539 (provide 'js2-mode)
11540
11541 ;;; js2-mode.el ends here