]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
c53c5b6b119ec8904afe236820328201bf54c91e
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2014 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
10 ;; Version: 20140114
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
65
66 ;; Notes:
67
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
71
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
76
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
81
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code has outdated information and is mostly
84 ;; unmaintained.
85
86 ;;; Code:
87
88 (eval-when-compile
89 (require 'cl))
90
91 (require 'imenu)
92 (require 'cc-cmds) ; for `c-fill-paragraph'
93
94 (eval-and-compile
95 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
96 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
97
98 (defvar electric-layout-rules)
99
100 ;;; Externs (variables presumed to be defined by the host system)
101
102 (defvar js2-ecma-262-externs
103 (mapcar 'symbol-name
104 '(Array Boolean Date Error EvalError Function Infinity JSON
105 Math NaN Number Object RangeError ReferenceError RegExp
106 String SyntaxError TypeError URIError arguments
107 decodeURI decodeURIComponent encodeURI
108 encodeURIComponent escape eval isFinite isNaN
109 parseFloat parseInt undefined unescape))
110 "Ecma-262 externs. Included in `js2-externs' by default.")
111
112 (defvar js2-browser-externs
113 (mapcar 'symbol-name
114 '(;; DOM level 1
115 Attr CDATASection CharacterData Comment DOMException
116 DOMImplementation Document DocumentFragment
117 DocumentType Element Entity EntityReference
118 ExceptionCode NamedNodeMap Node NodeList Notation
119 ProcessingInstruction Text
120
121 ;; DOM level 2
122 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
123 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
124 HTMLBodyElement HTMLButtonElement HTMLCollection
125 HTMLDListElement HTMLDirectoryElement HTMLDivElement
126 HTMLDocument HTMLElement HTMLFieldSetElement
127 HTMLFontElement HTMLFormElement HTMLFrameElement
128 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
129 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
130 HTMLImageElement HTMLInputElement HTMLIsIndexElement
131 HTMLLIElement HTMLLabelElement HTMLLegendElement
132 HTMLLinkElement HTMLMapElement HTMLMenuElement
133 HTMLMetaElement HTMLModElement HTMLOListElement
134 HTMLObjectElement HTMLOptGroupElement
135 HTMLOptionElement HTMLOptionsCollection
136 HTMLParagraphElement HTMLParamElement HTMLPreElement
137 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
138 HTMLStyleElement HTMLTableCaptionElement
139 HTMLTableCellElement HTMLTableColElement
140 HTMLTableElement HTMLTableRowElement
141 HTMLTableSectionElement HTMLTextAreaElement
142 HTMLTitleElement HTMLUListElement
143
144 ;; DOM level 3
145 DOMConfiguration DOMError DOMException
146 DOMImplementationList DOMImplementationSource
147 DOMLocator DOMStringList NameList TypeInfo
148 UserDataHandler
149
150 ;; Window
151 window alert confirm document java navigator prompt screen
152 self top
153
154 ;; W3C CSS
155 CSSCharsetRule CSSFontFace CSSFontFaceRule
156 CSSImportRule CSSMediaRule CSSPageRule
157 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
158 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
159 CSSValue CSSValueList Counter DOMImplementationCSS
160 DocumentCSS DocumentStyle ElementCSSInlineStyle
161 LinkStyle MediaList RGBColor Rect StyleSheet
162 StyleSheetList ViewCSS
163
164 ;; W3C Event
165 EventListener EventTarget Event DocumentEvent UIEvent
166 MouseEvent MutationEvent KeyboardEvent
167
168 ;; W3C Range
169 DocumentRange Range RangeException
170
171 ;; W3C XML
172 XPathResult XMLHttpRequest
173
174 ;; console object. Provided by at least Chrome and Firefox.
175 console))
176 "Browser externs.
177 You can cause these to be included or excluded with the custom
178 variable `js2-include-browser-externs'.")
179
180 (defvar js2-rhino-externs
181 (mapcar 'symbol-name
182 '(Packages importClass importPackage com org java
183 ;; Global object (shell) externs.
184 defineClass deserialize doctest gc help load
185 loadClass print quit readFile readUrl runCommand seal
186 serialize spawn sync toint32 version))
187 "Mozilla Rhino externs.
188 Set `js2-include-rhino-externs' to t to include them.")
189
190 (defvar js2-node-externs
191 (mapcar 'symbol-name
192 '(__dirname __filename Buffer clearInterval clearTimeout require
193 console exports global module process setInterval setTimeout))
194 "Node.js externs.
195 Set `js2-include-node-externs' to t to include them.")
196
197 (defvar js2-typed-array-externs
198 (mapcar 'symbol-name
199 '(ArrayBuffer Uint8ClampedArray DataView
200 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
201 Float32Array Float64Array))
202 "Khronos typed array externs. Available in most modern browsers and
203 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
204 are enabled, these will also be included.")
205
206 (defvar js2-harmony-externs
207 (mapcar 'symbol-name
208 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
209 "ES6 externs. If `js2-include-browser-externs' is enabled and
210 `js2-language-version' is sufficiently high, these will be included.")
211
212 ;;; Variables
213
214 (defun js2-mark-safe-local (name pred)
215 "Make the variable NAME buffer-local and mark it as safe file-local
216 variable with predicate PRED."
217 (make-variable-buffer-local name)
218 (put name 'safe-local-variable pred))
219
220 (defcustom js2-highlight-level 2
221 "Amount of syntax highlighting to perform.
222 0 or a negative value means none.
223 1 adds basic syntax highlighting.
224 2 adds highlighting of some Ecma built-in properties.
225 3 adds highlighting of many Ecma built-in functions."
226 :group 'js2-mode
227 :type '(choice (const :tag "None" 0)
228 (const :tag "Basic" 1)
229 (const :tag "Include Properties" 2)
230 (const :tag "Include Functions" 3)))
231
232 (defvar js2-mode-dev-mode-p nil
233 "Non-nil if running in development mode. Normally nil.")
234
235 (defgroup js2-mode nil
236 "An improved JavaScript mode."
237 :group 'languages)
238
239 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
240 (numberp c-basic-offset))
241 c-basic-offset
242 4)
243 "Number of spaces to indent nested statements.
244 Similar to `c-basic-offset'."
245 :group 'js2-mode
246 :type 'integer)
247 (js2-mark-safe-local 'js2-basic-offset 'integerp)
248
249 (defcustom js2-bounce-indent-p nil
250 "Non-nil to have indent-line function choose among alternatives.
251 If nil, the indent-line function will indent to a predetermined column
252 based on heuristic guessing. If non-nil, then if the current line is
253 already indented to that predetermined column, indenting will choose
254 another likely column and indent to that spot. Repeated invocation of
255 the indent-line function will cycle among the computed alternatives.
256 See the function `js2-bounce-indent' for details. When it is non-nil,
257 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
258 :type 'boolean
259 :group 'js2-mode)
260
261 (defcustom js2-pretty-multiline-declarations t
262 "Non-nil to line up multiline declarations vertically:
263
264 var a = 10,
265 b = 20,
266 c = 30;
267
268 If the value is not `all', and the first assigned value in
269 declaration is a function/array/object literal spanning several
270 lines, it won't be indented additionally:
271
272 var o = { var bar = 2,
273 foo: 3 vs. o = {
274 }, foo: 3
275 bar = 2; };"
276 :group 'js2-mode
277 :type 'symbol)
278 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
279
280 (defcustom js2-indent-switch-body nil
281 "When nil, case labels are indented on the same level as the
282 containing switch statement. Otherwise, all lines inside
283 switch statement body are indented one additional level."
284 :type 'boolean
285 :group 'js2-mode)
286 (js2-mark-safe-local 'js2-indent-case-same-as-switch 'booleanp)
287
288 (defcustom js2-idle-timer-delay 0.2
289 "Delay in secs before re-parsing after user makes changes.
290 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
291 :type 'number
292 :group 'js2-mode)
293 (make-variable-buffer-local 'js2-idle-timer-delay)
294
295 (defcustom js2-dynamic-idle-timer-adjust 0
296 "Positive to adjust `js2-idle-timer-delay' based on file size.
297 The idea is that for short files, parsing is faster so we can be
298 more responsive to user edits without interfering with editing.
299 The buffer length in characters (typically bytes) is divided by
300 this value and used to multiply `js2-idle-timer-delay' for the
301 buffer. For example, a 21k file and 10k adjust yields 21k/10k
302 == 2, so js2-idle-timer-delay is multiplied by 2.
303 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
304 `js2-idle-timer-delay' is not dependent on the file size."
305 :type 'number
306 :group 'js2-mode)
307
308 (defcustom js2-concat-multiline-strings t
309 "When non-nil, `js2-line-break' in mid-string will make it a
310 string concatenation. When `eol', the '+' will be inserted at the
311 end of the line, otherwise, at the beginning of the next line."
312 :type '(choice (const t) (const eol) (const nil))
313 :group 'js2-mode)
314
315 (defcustom js2-mode-show-parse-errors t
316 "True to highlight parse errors."
317 :type 'boolean
318 :group 'js2-mode)
319
320 (defcustom js2-mode-show-strict-warnings t
321 "Non-nil to emit Ecma strict-mode warnings.
322 Some of the warnings can be individually disabled by other flags,
323 even if this flag is non-nil."
324 :type 'boolean
325 :group 'js2-mode)
326
327 (defcustom js2-strict-trailing-comma-warning t
328 "Non-nil to warn about trailing commas in array literals.
329 Ecma-262-5.1 allows them, but older versions of IE raise an error."
330 :type 'boolean
331 :group 'js2-mode)
332
333 (defcustom js2-strict-missing-semi-warning t
334 "Non-nil to warn about semicolon auto-insertion after statement.
335 Technically this is legal per Ecma-262, but some style guides disallow
336 depending on it."
337 :type 'boolean
338 :group 'js2-mode)
339
340 (defcustom js2-missing-semi-one-line-override nil
341 "Non-nil to permit missing semicolons in one-line functions.
342 In one-liner functions such as `function identity(x) {return x}'
343 people often omit the semicolon for a cleaner look. If you are
344 such a person, you can suppress the missing-semicolon warning
345 by setting this variable to t."
346 :type 'boolean
347 :group 'js2-mode)
348
349 (defcustom js2-strict-inconsistent-return-warning t
350 "Non-nil to warn about mixing returns with value-returns.
351 It's perfectly legal to have a `return' and a `return foo' in the
352 same function, but it's often an indicator of a bug, and it also
353 interferes with type inference (in systems that support it.)"
354 :type 'boolean
355 :group 'js2-mode)
356
357 (defcustom js2-strict-cond-assign-warning t
358 "Non-nil to warn about expressions like if (a = b).
359 This often should have been '==' instead of '='. If the warning
360 is enabled, you can suppress it on a per-expression basis by
361 parenthesizing the expression, e.g. if ((a = b)) ..."
362 :type 'boolean
363 :group 'js2-mode)
364
365 (defcustom js2-strict-var-redeclaration-warning t
366 "Non-nil to warn about redeclaring variables in a script or function."
367 :type 'boolean
368 :group 'js2-mode)
369
370 (defcustom js2-strict-var-hides-function-arg-warning t
371 "Non-nil to warn about a var decl hiding a function argument."
372 :type 'boolean
373 :group 'js2-mode)
374
375 (defcustom js2-skip-preprocessor-directives nil
376 "Non-nil to treat lines beginning with # as comments.
377 Useful for viewing Mozilla JavaScript source code."
378 :type 'boolean
379 :group 'js2-mode)
380
381 (defcustom js2-language-version 200
382 "Configures what JavaScript language version to recognize.
383 Currently versions 150, 160, 170, 180 and 200 are supported,
384 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
385 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
386 yield, and Array comprehensions, and 1.8 adds function closures."
387 :type 'integer
388 :group 'js2-mode)
389
390 (defcustom js2-allow-keywords-as-property-names t
391 "If non-nil, you can use JavaScript keywords as object property names.
392 Examples:
393
394 var foo = {int: 5, while: 6, continue: 7};
395 foo.return = 8;
396
397 Ecma-262 5.1 allows this syntax, but some engines still don't."
398 :type 'boolean
399 :group 'js2-mode)
400
401 (defcustom js2-instanceof-has-side-effects nil
402 "If non-nil, treats the instanceof operator as having side effects.
403 This is useful for xulrunner apps."
404 :type 'boolean
405 :group 'js2-mode)
406
407 (defcustom js2-move-point-on-right-click t
408 "Non-nil to move insertion point when you right-click.
409 This makes right-click context menu behavior a bit more intuitive,
410 since menu operations generally apply to the point. The exception
411 is if there is a region selection, in which case the point does -not-
412 move, so cut/copy/paste can work properly.
413
414 Note that IntelliJ moves the point, and Eclipse leaves it alone,
415 so this behavior is customizable."
416 :group 'js2-mode
417 :type 'boolean)
418
419 (defcustom js2-allow-rhino-new-expr-initializer t
420 "Non-nil to support a Rhino's experimental syntactic construct.
421
422 Rhino supports the ability to follow a `new' expression with an object
423 literal, which is used to set additional properties on the new object
424 after calling its constructor. Syntax:
425
426 new <expr> [ ( arglist ) ] [initializer]
427
428 Hence, this expression:
429
430 new Object {a: 1, b: 2}
431
432 results in an Object with properties a=1 and b=2. This syntax is
433 apparently not configurable in Rhino - it's currently always enabled,
434 as of Rhino version 1.7R2."
435 :type 'boolean
436 :group 'js2-mode)
437
438 (defcustom js2-allow-member-expr-as-function-name nil
439 "Non-nil to support experimental Rhino syntax for function names.
440
441 Rhino supports an experimental syntax configured via the Rhino Context
442 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
443
444 function <member-expr> ( [ arg-list ] ) { <body> }
445
446 Where member-expr is a non-parenthesized 'member expression', which
447 is anything at the grammar level of a new-expression or lower, meaning
448 any expression that does not involve infix or unary operators.
449
450 When <member-expr> is not a simple identifier, then it is syntactic
451 sugar for assigning the anonymous function to the <member-expr>. Hence,
452 this code:
453
454 function a.b().c[2] (x, y) { ... }
455
456 is rewritten as:
457
458 a.b().c[2] = function(x, y) {...}
459
460 which doesn't seem particularly useful, but Rhino permits it."
461 :type 'boolean
462 :group 'js2-mode)
463
464 ;; scanner variables
465
466 (defmacro js2-deflocal (name value &optional comment)
467 "Define a buffer-local variable NAME with VALUE and COMMENT."
468 `(progn
469 (defvar ,name ,value ,comment)
470 (make-variable-buffer-local ',name)))
471
472 (defvar js2-EOF_CHAR -1
473 "Represents end of stream. Distinct from js2-EOF token type.")
474
475 ;; I originally used symbols to represent tokens, but Rhino uses
476 ;; ints and then sets various flag bits in them, so ints it is.
477 ;; The upshot is that we need a `js2-' prefix in front of each name.
478 (defvar js2-ERROR -1)
479 (defvar js2-EOF 0)
480 (defvar js2-EOL 1)
481 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
482 (defvar js2-LEAVEWITH 3)
483 (defvar js2-RETURN 4)
484 (defvar js2-GOTO 5)
485 (defvar js2-IFEQ 6)
486 (defvar js2-IFNE 7)
487 (defvar js2-SETNAME 8)
488 (defvar js2-BITOR 9)
489 (defvar js2-BITXOR 10)
490 (defvar js2-BITAND 11)
491 (defvar js2-EQ 12)
492 (defvar js2-NE 13)
493 (defvar js2-LT 14)
494 (defvar js2-LE 15)
495 (defvar js2-GT 16)
496 (defvar js2-GE 17)
497 (defvar js2-LSH 18)
498 (defvar js2-RSH 19)
499 (defvar js2-URSH 20)
500 (defvar js2-ADD 21) ; infix plus
501 (defvar js2-SUB 22) ; infix minus
502 (defvar js2-MUL 23)
503 (defvar js2-DIV 24)
504 (defvar js2-MOD 25)
505 (defvar js2-NOT 26)
506 (defvar js2-BITNOT 27)
507 (defvar js2-POS 28) ; unary plus
508 (defvar js2-NEG 29) ; unary minus
509 (defvar js2-NEW 30)
510 (defvar js2-DELPROP 31)
511 (defvar js2-TYPEOF 32)
512 (defvar js2-GETPROP 33)
513 (defvar js2-GETPROPNOWARN 34)
514 (defvar js2-SETPROP 35)
515 (defvar js2-GETELEM 36)
516 (defvar js2-SETELEM 37)
517 (defvar js2-CALL 38)
518 (defvar js2-NAME 39) ; an identifier
519 (defvar js2-NUMBER 40)
520 (defvar js2-STRING 41)
521 (defvar js2-NULL 42)
522 (defvar js2-THIS 43)
523 (defvar js2-FALSE 44)
524 (defvar js2-TRUE 45)
525 (defvar js2-SHEQ 46) ; shallow equality (===)
526 (defvar js2-SHNE 47) ; shallow inequality (!==)
527 (defvar js2-REGEXP 48)
528 (defvar js2-BINDNAME 49)
529 (defvar js2-THROW 50)
530 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
531 (defvar js2-IN 52)
532 (defvar js2-INSTANCEOF 53)
533 (defvar js2-LOCAL_LOAD 54)
534 (defvar js2-GETVAR 55)
535 (defvar js2-SETVAR 56)
536 (defvar js2-CATCH_SCOPE 57)
537 (defvar js2-ENUM_INIT_KEYS 58)
538 (defvar js2-ENUM_INIT_VALUES 59)
539 (defvar js2-ENUM_INIT_ARRAY 60)
540 (defvar js2-ENUM_NEXT 61)
541 (defvar js2-ENUM_ID 62)
542 (defvar js2-THISFN 63)
543 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
544 (defvar js2-ARRAYLIT 65) ; array literal
545 (defvar js2-OBJECTLIT 66) ; object literal
546 (defvar js2-GET_REF 67) ; *reference
547 (defvar js2-SET_REF 68) ; *reference = something
548 (defvar js2-DEL_REF 69) ; delete reference
549 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
550 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
551 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
552
553 ;; XML support
554 (defvar js2-DEFAULTNAMESPACE 73)
555 (defvar js2-ESCXMLATTR 74)
556 (defvar js2-ESCXMLTEXT 75)
557 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
558 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
559 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
560 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
561
562 (defvar js2-first-bytecode js2-ENTERWITH)
563 (defvar js2-last-bytecode js2-REF_NS_NAME)
564
565 (defvar js2-TRY 80)
566 (defvar js2-SEMI 81) ; semicolon
567 (defvar js2-LB 82) ; left and right brackets
568 (defvar js2-RB 83)
569 (defvar js2-LC 84) ; left and right curly-braces
570 (defvar js2-RC 85)
571 (defvar js2-LP 86) ; left and right parens
572 (defvar js2-RP 87)
573 (defvar js2-COMMA 88) ; comma operator
574
575 (defvar js2-ASSIGN 89) ; simple assignment (=)
576 (defvar js2-ASSIGN_BITOR 90) ; |=
577 (defvar js2-ASSIGN_BITXOR 91) ; ^=
578 (defvar js2-ASSIGN_BITAND 92) ; &=
579 (defvar js2-ASSIGN_LSH 93) ; <<=
580 (defvar js2-ASSIGN_RSH 94) ; >>=
581 (defvar js2-ASSIGN_URSH 95) ; >>>=
582 (defvar js2-ASSIGN_ADD 96) ; +=
583 (defvar js2-ASSIGN_SUB 97) ; -=
584 (defvar js2-ASSIGN_MUL 98) ; *=
585 (defvar js2-ASSIGN_DIV 99) ; /=
586 (defvar js2-ASSIGN_MOD 100) ; %=
587
588 (defvar js2-first-assign js2-ASSIGN)
589 (defvar js2-last-assign js2-ASSIGN_MOD)
590
591 (defvar js2-HOOK 101) ; conditional (?:)
592 (defvar js2-COLON 102)
593 (defvar js2-OR 103) ; logical or (||)
594 (defvar js2-AND 104) ; logical and (&&)
595 (defvar js2-INC 105) ; increment/decrement (++ --)
596 (defvar js2-DEC 106)
597 (defvar js2-DOT 107) ; member operator (.)
598 (defvar js2-FUNCTION 108) ; function keyword
599 (defvar js2-EXPORT 109) ; export keyword
600 (defvar js2-IMPORT 110) ; import keyword
601 (defvar js2-IF 111) ; if keyword
602 (defvar js2-ELSE 112) ; else keyword
603 (defvar js2-SWITCH 113) ; switch keyword
604 (defvar js2-CASE 114) ; case keyword
605 (defvar js2-DEFAULT 115) ; default keyword
606 (defvar js2-WHILE 116) ; while keyword
607 (defvar js2-DO 117) ; do keyword
608 (defvar js2-FOR 118) ; for keyword
609 (defvar js2-BREAK 119) ; break keyword
610 (defvar js2-CONTINUE 120) ; continue keyword
611 (defvar js2-VAR 121) ; var keyword
612 (defvar js2-WITH 122) ; with keyword
613 (defvar js2-CATCH 123) ; catch keyword
614 (defvar js2-FINALLY 124) ; finally keyword
615 (defvar js2-VOID 125) ; void keyword
616 (defvar js2-RESERVED 126) ; reserved keywords
617
618 (defvar js2-EMPTY 127)
619
620 ;; Types used for the parse tree - never returned by scanner.
621
622 (defvar js2-BLOCK 128) ; statement block
623 (defvar js2-LABEL 129) ; label
624 (defvar js2-TARGET 130)
625 (defvar js2-LOOP 131)
626 (defvar js2-EXPR_VOID 132) ; expression statement in functions
627 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
628 (defvar js2-JSR 134)
629 (defvar js2-SCRIPT 135) ; top-level node for entire script
630 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
631 (defvar js2-USE_STACK 137)
632 (defvar js2-SETPROP_OP 138) ; x.y op= something
633 (defvar js2-SETELEM_OP 139) ; x[y] op= something
634 (defvar js2-LOCAL_BLOCK 140)
635 (defvar js2-SET_REF_OP 141) ; *reference op= something
636
637 ;; For XML support:
638 (defvar js2-DOTDOT 142) ; member operator (..)
639 (defvar js2-COLONCOLON 143) ; namespace::name
640 (defvar js2-XML 144) ; XML type
641 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
642 (defvar js2-XMLATTR 146) ; @
643 (defvar js2-XMLEND 147)
644
645 ;; Optimizer-only tokens
646 (defvar js2-TO_OBJECT 148)
647 (defvar js2-TO_DOUBLE 149)
648
649 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
650 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
651 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
652 (defvar js2-CONST 153)
653 (defvar js2-SETCONST 154)
654 (defvar js2-SETCONSTVAR 155)
655 (defvar js2-ARRAYCOMP 156)
656 (defvar js2-LETEXPR 157)
657 (defvar js2-WITHEXPR 158)
658 (defvar js2-DEBUGGER 159)
659
660 (defvar js2-COMMENT 160)
661 (defvar js2-ENUM 161) ; for "enum" reserved word
662 (defvar js2-TRIPLEDOT 162) ; for rest parameter
663 (defvar js2-ARROW 163) ; function arrow (=>)
664
665 (defconst js2-num-tokens (1+ js2-ARROW))
666
667 (defconst js2-debug-print-trees nil)
668
669 ;; Rhino accepts any string or stream as input. Emacs character
670 ;; processing works best in buffers, so we'll assume the input is a
671 ;; buffer. JavaScript strings can be copied into temp buffers before
672 ;; scanning them.
673
674 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
675 ;; They're the Emacs equivalent of instance variables, more or less.
676
677 (js2-deflocal js2-ts-dirty-line nil
678 "Token stream buffer-local variable.
679 Indicates stuff other than whitespace since start of line.")
680
681 (js2-deflocal js2-ts-hit-eof nil
682 "Token stream buffer-local variable.")
683
684 ;; FIXME: Unused.
685 (js2-deflocal js2-ts-line-start 0
686 "Token stream buffer-local variable.")
687
688 (js2-deflocal js2-ts-lineno 1
689 "Token stream buffer-local variable.")
690
691 ;; FIXME: Unused.
692 (js2-deflocal js2-ts-line-end-char -1
693 "Token stream buffer-local variable.")
694
695 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
696 "Token stream buffer-local variable.
697 Current scan position.")
698
699 ;; FIXME: Unused.
700 (js2-deflocal js2-ts-is-xml-attribute nil
701 "Token stream buffer-local variable.")
702
703 (js2-deflocal js2-ts-xml-is-tag-content nil
704 "Token stream buffer-local variable.")
705
706 (js2-deflocal js2-ts-xml-open-tags-count 0
707 "Token stream buffer-local variable.")
708
709 (js2-deflocal js2-ts-string-buffer nil
710 "Token stream buffer-local variable.
711 List of chars built up while scanning various tokens.")
712
713 (defstruct (js2-token
714 (:constructor nil)
715 (:constructor make-js2-token (beg)))
716 "Value returned from the token stream."
717 (type js2-EOF)
718 (beg 1)
719 (end -1)
720 (string "")
721 number
722 regexp-flags
723 comment-type
724 follows-eol-p)
725
726 (defstruct (js2-ts-state
727 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
728 (cursor js2-ts-cursor)
729 (tokens (copy-sequence js2-ti-tokens))
730 (tokens-cursor js2-ti-tokens-cursor)
731 (lookahead js2-ti-lookahead))))
732 lineno
733 cursor
734 tokens
735 tokens-cursor
736 lookahead)
737
738 ;;; Parser variables
739
740 (js2-deflocal js2-parsed-errors nil
741 "List of errors produced during scanning/parsing.")
742
743 (js2-deflocal js2-parsed-warnings nil
744 "List of warnings produced during scanning/parsing.")
745
746 (js2-deflocal js2-recover-from-parse-errors t
747 "Non-nil to continue parsing after a syntax error.
748
749 In recovery mode, the AST will be built in full, and any error
750 nodes will be flagged with appropriate error information. If
751 this flag is nil, a syntax error will result in an error being
752 signaled.
753
754 The variable is automatically buffer-local, because different
755 modes that use the parser will need different settings.")
756
757 (js2-deflocal js2-parse-hook nil
758 "List of callbacks for receiving parsing progress.")
759
760 (defvar js2-parse-finished-hook nil
761 "List of callbacks to notify when parsing finishes.
762 Not called if parsing was interrupted.")
763
764 (js2-deflocal js2-is-eval-code nil
765 "True if we're evaluating code in a string.
766 If non-nil, the tokenizer will record the token text, and the AST nodes
767 will record their source text. Off by default for IDE modes, since the
768 text is available in the buffer.")
769
770 (defvar js2-parse-ide-mode t
771 "Non-nil if the parser is being used for `js2-mode'.
772 If non-nil, the parser will set text properties for fontification
773 and the syntax table. The value should be nil when using the
774 parser as a frontend to an interpreter or byte compiler.")
775
776 ;;; Parser instance variables (buffer-local vars for js2-parse)
777
778 (defconst js2-ti-after-eol (lsh 1 16)
779 "Flag: first token of the source line.")
780
781 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
782
783 (js2-deflocal js2-compiler-generate-debug-info t)
784 (js2-deflocal js2-compiler-use-dynamic-scope nil)
785 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
786 (js2-deflocal js2-compiler-xml-available t)
787 (js2-deflocal js2-compiler-optimization-level 0)
788 (js2-deflocal js2-compiler-generating-source t)
789 (js2-deflocal js2-compiler-strict-mode nil)
790 (js2-deflocal js2-compiler-report-warning-as-error nil)
791 (js2-deflocal js2-compiler-generate-observer-count nil)
792 (js2-deflocal js2-compiler-activation-names nil)
793
794 ;; SKIP: sourceURI
795
796 ;; There's a compileFunction method in Context.java - may need it.
797 (js2-deflocal js2-called-by-compile-function nil
798 "True if `js2-parse' was called by `js2-compile-function'.
799 Will only be used when we finish implementing the interpreter.")
800
801 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
802
803 ;; SKIP: node factory - we're going to just call functions directly,
804 ;; and eventually go to a unified AST format.
805
806 (js2-deflocal js2-nesting-of-function 0)
807
808 (js2-deflocal js2-recorded-identifiers nil
809 "Tracks identifiers found during parsing.")
810
811 (js2-deflocal js2-is-in-destructuring nil
812 "True while parsing destructuring expression.")
813
814 (defcustom js2-global-externs nil
815 "A list of any extern names you'd like to consider always declared.
816 This list is global and is used by all `js2-mode' files.
817 You can create buffer-local externs list using `js2-additional-externs'.
818
819 There is also a buffer-local variable `js2-default-externs',
820 which is initialized by default to include the Ecma-262 externs
821 and the standard browser externs. The three lists are all
822 checked during highlighting."
823 :type 'list
824 :group 'js2-mode)
825
826 (js2-deflocal js2-default-externs nil
827 "Default external declarations.
828
829 These are currently only used for highlighting undeclared variables,
830 which only worries about top-level (unqualified) references.
831 As js2-mode's processing improves, we will flesh out this list.
832
833 The initial value is set to `js2-ecma-262-externs', unless some
834 of the `js2-include-?-externs' variables are set to t, in which
835 case the browser, Rhino and/or Node.js externs are also included.
836
837 See `js2-additional-externs' for more information.")
838
839 (defcustom js2-include-browser-externs t
840 "Non-nil to include browser externs in the master externs list.
841 If you work on JavaScript files that are not intended for browsers,
842 such as Mozilla Rhino server-side JavaScript, set this to nil.
843 See `js2-additional-externs' for more information about externs."
844 :type 'boolean
845 :group 'js2-mode)
846
847 (defcustom js2-include-rhino-externs nil
848 "Non-nil to include Mozilla Rhino externs in the master externs list.
849 See `js2-additional-externs' for more information about externs."
850 :type 'boolean
851 :group 'js2-mode)
852
853 (defcustom js2-include-node-externs nil
854 "Non-nil to include Node.js externs in the master externs list.
855 See `js2-additional-externs' for more information about externs."
856 :type 'boolean
857 :group 'js2-mode)
858
859 (js2-deflocal js2-additional-externs nil
860 "A buffer-local list of additional external declarations.
861 It is used to decide whether variables are considered undeclared
862 for purposes of highlighting.
863
864 Each entry is a Lisp string. The string should be the fully qualified
865 name of an external entity. All externs should be added to this list,
866 so that as js2-mode's processing improves it can take advantage of them.
867
868 You may want to declare your externs in three ways.
869 First, you can add externs that are valid for all your JavaScript files.
870 You should probably do this by adding them to `js2-global-externs', which
871 is a global list used for all js2-mode files.
872
873 Next, you can add a function to `js2-init-hook' that adds additional
874 externs appropriate for the specific file, perhaps based on its path.
875 These should go in `js2-additional-externs', which is buffer-local.
876
877 Third, you can use JSLint's global declaration, as long as
878 `js2-include-jslint-globals' is non-nil, which see.
879
880 Finally, you can add a function to `js2-post-parse-callbacks',
881 which is called after parsing completes, and `js2-mode-ast' is bound to
882 the root of the parse tree. At this stage you can set up an AST
883 node visitor using `js2-visit-ast' and examine the parse tree
884 for specific import patterns that may imply the existence of
885 other externs, possibly tied to your build system. These should also
886 be added to `js2-additional-externs'.
887
888 Your post-parse callback may of course also use the simpler and
889 faster (but perhaps less robust) approach of simply scanning the
890 buffer text for your imports, using regular expressions.")
891
892 ;; SKIP: decompiler
893 ;; SKIP: encoded-source
894
895 ;;; The following variables are per-function and should be saved/restored
896 ;;; during function parsing...
897
898 (js2-deflocal js2-current-script-or-fn nil)
899 (js2-deflocal js2-current-scope nil)
900 (js2-deflocal js2-nesting-of-with 0)
901 (js2-deflocal js2-label-set nil
902 "An alist mapping label names to nodes.")
903
904 (js2-deflocal js2-loop-set nil)
905 (js2-deflocal js2-loop-and-switch-set nil)
906 (js2-deflocal js2-has-return-value nil)
907 (js2-deflocal js2-end-flags 0)
908
909 ;;; ...end of per function variables
910
911 ;; These flags enumerate the possible ways a statement/function can
912 ;; terminate. These flags are used by endCheck() and by the Parser to
913 ;; detect inconsistent return usage.
914 ;;
915 ;; END_UNREACHED is reserved for code paths that are assumed to always be
916 ;; able to execute (example: throw, continue)
917 ;;
918 ;; END_DROPS_OFF indicates if the statement can transfer control to the
919 ;; next one. Statement such as return dont. A compound statement may have
920 ;; some branch that drops off control to the next statement.
921 ;;
922 ;; END_RETURNS indicates that the statement can return (without arguments)
923 ;; END_RETURNS_VALUE indicates that the statement can return a value.
924 ;;
925 ;; A compound statement such as
926 ;; if (condition) {
927 ;; return value;
928 ;; }
929 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
930
931 (defconst js2-end-unreached #x0)
932 (defconst js2-end-drops-off #x1)
933 (defconst js2-end-returns #x2)
934 (defconst js2-end-returns-value #x4)
935
936 ;; Rhino awkwardly passes a statementLabel parameter to the
937 ;; statementHelper() function, the main statement parser, which
938 ;; is then used by quite a few of the sub-parsers. We just make
939 ;; it a buffer-local variable and make sure it's cleaned up properly.
940 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
941
942 ;; Similarly, Rhino passes an inForInit boolean through about half
943 ;; the expression parsers. We use a dynamically-scoped variable,
944 ;; which makes it easier to funcall the parsers individually without
945 ;; worrying about whether they take the parameter or not.
946 (js2-deflocal js2-in-for-init nil)
947 (js2-deflocal js2-temp-name-counter 0)
948 (js2-deflocal js2-parse-stmt-count 0)
949
950 (defsubst js2-get-next-temp-name ()
951 (format "$%d" (incf js2-temp-name-counter)))
952
953 (defvar js2-parse-interruptable-p t
954 "Set this to nil to force parse to continue until finished.
955 This will mostly be useful for interpreters.")
956
957 (defvar js2-statements-per-pause 50
958 "Pause after this many statements to check for user input.
959 If user input is pending, stop the parse and discard the tree.
960 This makes for a smoother user experience for large files.
961 You may have to wait a second or two before the highlighting
962 and error-reporting appear, but you can always type ahead if
963 you wish. This appears to be more or less how Eclipse, IntelliJ
964 and other editors work.")
965
966 (js2-deflocal js2-record-comments t
967 "Instructs the scanner to record comments in `js2-scanned-comments'.")
968
969 (js2-deflocal js2-scanned-comments nil
970 "List of all comments from the current parse.")
971
972 (defcustom js2-mode-indent-inhibit-undo nil
973 "Non-nil to disable collection of Undo information when indenting lines.
974 Some users have requested this behavior. It's nil by default because
975 other Emacs modes don't work this way."
976 :type 'boolean
977 :group 'js2-mode)
978
979 (defcustom js2-mode-indent-ignore-first-tab nil
980 "If non-nil, ignore first TAB keypress if we look indented properly.
981 It's fairly common for users to navigate to an already-indented line
982 and press TAB for reassurance that it's been indented. For this class
983 of users, we want the first TAB press on a line to be ignored if the
984 line is already indented to one of the precomputed alternatives.
985
986 This behavior is only partly implemented. If you TAB-indent a line,
987 navigate to another line, and then navigate back, it fails to clear
988 the last-indented variable, so it thinks you've already hit TAB once,
989 and performs the indent. A full solution would involve getting on the
990 point-motion hooks for the entire buffer. If we come across another
991 use cases that requires watching point motion, I'll consider doing it.
992
993 If you set this variable to nil, then the TAB key will always change
994 the indentation of the current line, if more than one alternative
995 indentation spot exists."
996 :type 'boolean
997 :group 'js2-mode)
998
999 (defvar js2-indent-hook nil
1000 "A hook for user-defined indentation rules.
1001
1002 Functions on this hook should expect two arguments: (LIST INDEX)
1003 The LIST argument is the list of computed indentation points for
1004 the current line. INDEX is the list index of the indentation point
1005 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1006 indent function is not going to change the current line indentation.
1007
1008 If a hook function on this list returns a non-nil value, then
1009 `js2-bounce-indent' assumes the hook function has performed its own
1010 indentation, and will do nothing. If all hook functions on the list
1011 return nil, then `js2-bounce-indent' will use its computed indentation
1012 and reindent the line.
1013
1014 When hook functions on this hook list are called, the variable
1015 `js2-mode-ast' may or may not be set, depending on whether the
1016 parse tree is available. If the variable is nil, you can pass a
1017 callback to `js2-mode-wait-for-parse', and your callback will be
1018 called after the new parse tree is built. This can take some time
1019 in large files.")
1020
1021 (defface js2-warning
1022 `((((class color) (background light))
1023 (:underline "orange"))
1024 (((class color) (background dark))
1025 (:underline "orange"))
1026 (t (:underline t)))
1027 "Face for JavaScript warnings."
1028 :group 'js2-mode)
1029
1030 (defface js2-error
1031 `((((class color) (background light))
1032 (:foreground "red"))
1033 (((class color) (background dark))
1034 (:foreground "red"))
1035 (t (:foreground "red")))
1036 "Face for JavaScript errors."
1037 :group 'js2-mode)
1038
1039 (defface js2-jsdoc-tag
1040 '((t :foreground "SlateGray"))
1041 "Face used to highlight @whatever tags in jsdoc comments."
1042 :group 'js2-mode)
1043
1044 (defface js2-jsdoc-type
1045 '((t :foreground "SteelBlue"))
1046 "Face used to highlight {FooBar} types in jsdoc comments."
1047 :group 'js2-mode)
1048
1049 (defface js2-jsdoc-value
1050 '((t :foreground "PeachPuff3"))
1051 "Face used to highlight tag values in jsdoc comments."
1052 :group 'js2-mode)
1053
1054 (defface js2-function-param
1055 '((t :foreground "SeaGreen"))
1056 "Face used to highlight function parameters in javascript."
1057 :group 'js2-mode)
1058
1059 (defface js2-function-call
1060 '((t :inherit default))
1061 "Face used to highlight function name in calls."
1062 :group 'js2-mode)
1063
1064 (defface js2-instance-member
1065 '((t :foreground "DarkOrchid"))
1066 "Face used to highlight instance variables in javascript.
1067 Not currently used."
1068 :group 'js2-mode)
1069
1070 (defface js2-private-member
1071 '((t :foreground "PeachPuff3"))
1072 "Face used to highlight calls to private methods in javascript.
1073 Not currently used."
1074 :group 'js2-mode)
1075
1076 (defface js2-private-function-call
1077 '((t :foreground "goldenrod"))
1078 "Face used to highlight calls to private functions in javascript.
1079 Not currently used."
1080 :group 'js2-mode)
1081
1082 (defface js2-jsdoc-html-tag-name
1083 '((((class color) (min-colors 88) (background light))
1084 (:foreground "rosybrown"))
1085 (((class color) (min-colors 8) (background dark))
1086 (:foreground "yellow"))
1087 (((class color) (min-colors 8) (background light))
1088 (:foreground "magenta")))
1089 "Face used to highlight jsdoc html tag names"
1090 :group 'js2-mode)
1091
1092 (defface js2-jsdoc-html-tag-delimiter
1093 '((((class color) (min-colors 88) (background light))
1094 (:foreground "dark khaki"))
1095 (((class color) (min-colors 8) (background dark))
1096 (:foreground "green"))
1097 (((class color) (min-colors 8) (background light))
1098 (:foreground "green")))
1099 "Face used to highlight brackets in jsdoc html tags."
1100 :group 'js2-mode)
1101
1102 (defface js2-external-variable
1103 '((t :foreground "orange"))
1104 "Face used to highlight undeclared variable identifiers.")
1105
1106 (defcustom js2-init-hook nil
1107 "List of functions to be called after `js2-mode' or
1108 `js2-minor-mode' has initialized all variables, before parsing
1109 the buffer for the first time."
1110 :type 'hook
1111 :group 'js2-mode
1112 :version "20130608")
1113
1114 (defcustom js2-post-parse-callbacks nil
1115 "List of callback functions invoked after parsing finishes.
1116 Currently, the main use for this function is to add synthetic
1117 declarations to `js2-recorded-identifiers', which see."
1118 :type 'hook
1119 :group 'js2-mode)
1120
1121 (defcustom js2-highlight-external-variables t
1122 "Non-nil to highlight undeclared variable identifiers.
1123 An undeclared variable is any variable not declared with var or let
1124 in the current scope or any lexically enclosing scope. If you use
1125 such a variable, then you are either expecting it to originate from
1126 another file, or you've got a potential bug."
1127 :type 'boolean
1128 :group 'js2-mode)
1129
1130 (defcustom js2-include-jslint-globals t
1131 "Non-nil to include the identifiers from JSLint global
1132 declaration (see http://www.jslint.com/lint.html#global) in the
1133 buffer-local externs list. See `js2-additional-externs' for more
1134 information."
1135 :type 'boolean
1136 :group 'js2-mode)
1137
1138 (defvar js2-mode-map
1139 (let ((map (make-sparse-keymap)))
1140 (define-key map [mouse-1] #'js2-mode-show-node)
1141 (define-key map (kbd "M-j") #'js2-line-break)
1142 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1143 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1144 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1145 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1146 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1147 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1148 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1149 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1150 (when js2-bounce-indent-p
1151 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1152
1153 (define-key map [menu-bar javascript]
1154 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1155
1156 (define-key map [menu-bar javascript customize-js2-mode]
1157 '(menu-item "Customize js2-mode" js2-mode-customize
1158 :help "Customize the behavior of this mode"))
1159
1160 (define-key map [menu-bar javascript js2-force-refresh]
1161 '(menu-item "Force buffer refresh" js2-mode-reset
1162 :help "Re-parse the buffer from scratch"))
1163
1164 (define-key map [menu-bar javascript separator-2]
1165 '("--"))
1166
1167 (define-key map [menu-bar javascript next-error]
1168 '(menu-item "Next warning or error" next-error
1169 :enabled (and js2-mode-ast
1170 (or (js2-ast-root-errors js2-mode-ast)
1171 (js2-ast-root-warnings js2-mode-ast)))
1172 :help "Move to next warning or error"))
1173
1174 (define-key map [menu-bar javascript display-errors]
1175 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1176 :visible (not js2-mode-show-parse-errors)
1177 :help "Turn on display of warnings and errors"))
1178
1179 (define-key map [menu-bar javascript hide-errors]
1180 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1181 :visible js2-mode-show-parse-errors
1182 :help "Turn off display of warnings and errors"))
1183
1184 (define-key map [menu-bar javascript separator-1]
1185 '("--"))
1186
1187 (define-key map [menu-bar javascript js2-toggle-function]
1188 '(menu-item "Show/collapse element" js2-mode-toggle-element
1189 :help "Hide or show function body or comment"))
1190
1191 (define-key map [menu-bar javascript show-comments]
1192 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1193 :visible js2-mode-comments-hidden
1194 :help "Expand all hidden block comments"))
1195
1196 (define-key map [menu-bar javascript hide-comments]
1197 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1198 :visible (not js2-mode-comments-hidden)
1199 :help "Show block comments as /*...*/"))
1200
1201 (define-key map [menu-bar javascript show-all-functions]
1202 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1203 :visible js2-mode-functions-hidden
1204 :help "Expand all hidden function bodies"))
1205
1206 (define-key map [menu-bar javascript hide-all-functions]
1207 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1208 :visible (not js2-mode-functions-hidden)
1209 :help "Show {...} for all top-level function bodies"))
1210
1211 map)
1212 "Keymap used in `js2-mode' buffers.")
1213
1214 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1215
1216 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1217 "Matches a //-comment line. Must be first non-whitespace on line.
1218 First match-group is the leading whitespace.")
1219
1220 (defvar js2-mode-hook nil)
1221
1222 (js2-deflocal js2-mode-ast nil "Private variable.")
1223 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1224 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1225 (js2-deflocal js2-mode-parsing nil "Private variable.")
1226 (js2-deflocal js2-mode-node-overlay nil)
1227
1228 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1229 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1230
1231 (js2-deflocal js2-mode-fontifications nil "Private variable")
1232 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1233 (js2-deflocal js2-imenu-recorder nil "Private variable")
1234 (js2-deflocal js2-imenu-function-map nil "Private variable")
1235
1236 (defvar js2-paragraph-start
1237 "\\(@[[:alpha:]]+\\>\\|$\\)")
1238
1239 ;; Note that we also set a 'c-in-sws text property in html comments,
1240 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1241 (defvar js2-syntactic-ws-start
1242 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1243
1244 (defvar js2-syntactic-ws-end
1245 "\\s \\|[\n\r/]\\|\\s!")
1246
1247 (defvar js2-syntactic-eol
1248 (concat "\\s *\\(/\\*[^*\n\r]*"
1249 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1250 "\\*+/\\s *\\)*"
1251 "\\(//\\|/\\*[^*\n\r]*"
1252 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1253 "\\|\\\\$\\|$\\)")
1254 "Copied from `java-mode'. Needed for some cc-engine functions.")
1255
1256 (defvar js2-comment-prefix-regexp
1257 "//+\\|\\**")
1258
1259 (defvar js2-comment-start-skip
1260 "\\(//+\\|/\\*+\\)\\s *")
1261
1262 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1263 "Non-nil to emit status messages during parsing.")
1264
1265 (defvar js2-mode-functions-hidden nil "Private variable.")
1266 (defvar js2-mode-comments-hidden nil "Private variable.")
1267
1268 (defvar js2-mode-syntax-table
1269 (let ((table (make-syntax-table)))
1270 (c-populate-syntax-table table)
1271 table)
1272 "Syntax table used in `js2-mode' buffers.")
1273
1274 (defvar js2-mode-abbrev-table nil
1275 "Abbrev table in use in `js2-mode' buffers.")
1276 (define-abbrev-table 'js2-mode-abbrev-table ())
1277
1278 (defvar js2-mode-pending-parse-callbacks nil
1279 "List of functions waiting to be notified that parse is finished.")
1280
1281 (defvar js2-mode-last-indented-line -1)
1282
1283 ;;; Localizable error and warning messages
1284
1285 ;; Messages are copied from Rhino's Messages.properties.
1286 ;; Many of the Java-specific messages have been elided.
1287 ;; Add any js2-specific ones at the end, so we can keep
1288 ;; this file synced with changes to Rhino's.
1289
1290 (defvar js2-message-table
1291 (make-hash-table :test 'equal :size 250)
1292 "Contains localized messages for `js2-mode'.")
1293
1294 ;; TODO(stevey): construct this table at compile-time.
1295 (defmacro js2-msg (key &rest strings)
1296 `(puthash ,key (concat ,@strings)
1297 js2-message-table))
1298
1299 (defun js2-get-msg (msg-key)
1300 "Look up a localized message.
1301 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1302 the correct number of ARGS must be provided."
1303 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1304 (args (if (listp msg-key) (cdr msg-key)))
1305 (msg (gethash key js2-message-table)))
1306 (if msg
1307 (apply #'format msg args)
1308 key))) ; default to showing the key
1309
1310 (js2-msg "msg.dup.parms"
1311 "Duplicate parameter name '%s'.")
1312
1313 (js2-msg "msg.too.big.jump"
1314 "Program too complex: jump offset too big.")
1315
1316 (js2-msg "msg.too.big.index"
1317 "Program too complex: internal index exceeds 64K limit.")
1318
1319 (js2-msg "msg.while.compiling.fn"
1320 "Encountered code generation error while compiling function '%s': %s")
1321
1322 (js2-msg "msg.while.compiling.script"
1323 "Encountered code generation error while compiling script: %s")
1324
1325 ;; Context
1326 (js2-msg "msg.ctor.not.found"
1327 "Constructor for '%s' not found.")
1328
1329 (js2-msg "msg.not.ctor"
1330 "'%s' is not a constructor.")
1331
1332 ;; FunctionObject
1333 (js2-msg "msg.varargs.ctor"
1334 "Method or constructor '%s' must be static "
1335 "with the signature (Context cx, Object[] args, "
1336 "Function ctorObj, boolean inNewExpr) "
1337 "to define a variable arguments constructor.")
1338
1339 (js2-msg "msg.varargs.fun"
1340 "Method '%s' must be static with the signature "
1341 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1342 "to define a variable arguments function.")
1343
1344 (js2-msg "msg.incompat.call"
1345 "Method '%s' called on incompatible object.")
1346
1347 (js2-msg "msg.bad.parms"
1348 "Unsupported parameter type '%s' in method '%s'.")
1349
1350 (js2-msg "msg.bad.method.return"
1351 "Unsupported return type '%s' in method '%s'.")
1352
1353 (js2-msg "msg.bad.ctor.return"
1354 "Construction of objects of type '%s' is not supported.")
1355
1356 (js2-msg "msg.no.overload"
1357 "Method '%s' occurs multiple times in class '%s'.")
1358
1359 (js2-msg "msg.method.not.found"
1360 "Method '%s' not found in '%s'.")
1361
1362 ;; IRFactory
1363
1364 (js2-msg "msg.bad.for.in.lhs"
1365 "Invalid left-hand side of for..in loop.")
1366
1367 (js2-msg "msg.mult.index"
1368 "Only one variable allowed in for..in loop.")
1369
1370 (js2-msg "msg.bad.for.in.destruct"
1371 "Left hand side of for..in loop must be an array of "
1372 "length 2 to accept key/value pair.")
1373
1374 (js2-msg "msg.cant.convert"
1375 "Can't convert to type '%s'.")
1376
1377 (js2-msg "msg.bad.assign.left"
1378 "Invalid assignment left-hand side.")
1379
1380 (js2-msg "msg.bad.decr"
1381 "Invalid decerement operand.")
1382
1383 (js2-msg "msg.bad.incr"
1384 "Invalid increment operand.")
1385
1386 (js2-msg "msg.bad.yield"
1387 "yield must be in a function.")
1388
1389 (js2-msg "msg.yield.parenthesized"
1390 "yield expression must be parenthesized.")
1391
1392 ;; NativeGlobal
1393 (js2-msg "msg.cant.call.indirect"
1394 "Function '%s' must be called directly, and not by way of a "
1395 "function of another name.")
1396
1397 (js2-msg "msg.eval.nonstring"
1398 "Calling eval() with anything other than a primitive "
1399 "string value will simply return the value. "
1400 "Is this what you intended?")
1401
1402 (js2-msg "msg.eval.nonstring.strict"
1403 "Calling eval() with anything other than a primitive "
1404 "string value is not allowed in strict mode.")
1405
1406 (js2-msg "msg.bad.destruct.op"
1407 "Invalid destructuring assignment operator")
1408
1409 ;; NativeCall
1410 (js2-msg "msg.only.from.new"
1411 "'%s' may only be invoked from a `new' expression.")
1412
1413 (js2-msg "msg.deprec.ctor"
1414 "The '%s' constructor is deprecated.")
1415
1416 ;; NativeFunction
1417 (js2-msg "msg.no.function.ref.found"
1418 "no source found to decompile function reference %s")
1419
1420 (js2-msg "msg.arg.isnt.array"
1421 "second argument to Function.prototype.apply must be an array")
1422
1423 ;; NativeGlobal
1424 (js2-msg "msg.bad.esc.mask"
1425 "invalid string escape mask")
1426
1427 ;; NativeRegExp
1428 (js2-msg "msg.bad.quant"
1429 "Invalid quantifier %s")
1430
1431 (js2-msg "msg.overlarge.backref"
1432 "Overly large back reference %s")
1433
1434 (js2-msg "msg.overlarge.min"
1435 "Overly large minimum %s")
1436
1437 (js2-msg "msg.overlarge.max"
1438 "Overly large maximum %s")
1439
1440 (js2-msg "msg.zero.quant"
1441 "Zero quantifier %s")
1442
1443 (js2-msg "msg.max.lt.min"
1444 "Maximum %s less than minimum")
1445
1446 (js2-msg "msg.unterm.quant"
1447 "Unterminated quantifier %s")
1448
1449 (js2-msg "msg.unterm.paren"
1450 "Unterminated parenthetical %s")
1451
1452 (js2-msg "msg.unterm.class"
1453 "Unterminated character class %s")
1454
1455 (js2-msg "msg.bad.range"
1456 "Invalid range in character class.")
1457
1458 (js2-msg "msg.trail.backslash"
1459 "Trailing \\ in regular expression.")
1460
1461 (js2-msg "msg.re.unmatched.right.paren"
1462 "unmatched ) in regular expression.")
1463
1464 (js2-msg "msg.no.regexp"
1465 "Regular expressions are not available.")
1466
1467 (js2-msg "msg.bad.backref"
1468 "back-reference exceeds number of capturing parentheses.")
1469
1470 (js2-msg "msg.bad.regexp.compile"
1471 "Only one argument may be specified if the first "
1472 "argument to RegExp.prototype.compile is a RegExp object.")
1473
1474 ;; Parser
1475 (js2-msg "msg.got.syntax.errors"
1476 "Compilation produced %s syntax errors.")
1477
1478 (js2-msg "msg.var.redecl"
1479 "TypeError: redeclaration of var %s.")
1480
1481 (js2-msg "msg.const.redecl"
1482 "TypeError: redeclaration of const %s.")
1483
1484 (js2-msg "msg.let.redecl"
1485 "TypeError: redeclaration of variable %s.")
1486
1487 (js2-msg "msg.parm.redecl"
1488 "TypeError: redeclaration of formal parameter %s.")
1489
1490 (js2-msg "msg.fn.redecl"
1491 "TypeError: redeclaration of function %s.")
1492
1493 (js2-msg "msg.let.decl.not.in.block"
1494 "SyntaxError: let declaration not directly within block")
1495
1496 ;; NodeTransformer
1497 (js2-msg "msg.dup.label"
1498 "duplicated label")
1499
1500 (js2-msg "msg.undef.label"
1501 "undefined label")
1502
1503 (js2-msg "msg.bad.break"
1504 "unlabelled break must be inside loop or switch")
1505
1506 (js2-msg "msg.continue.outside"
1507 "continue must be inside loop")
1508
1509 (js2-msg "msg.continue.nonloop"
1510 "continue can only use labels of iteration statements")
1511
1512 (js2-msg "msg.bad.throw.eol"
1513 "Line terminator is not allowed between the throw "
1514 "keyword and throw expression.")
1515
1516 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1517 "function statement requires a name")
1518
1519 (js2-msg "msg.no.paren.parms"
1520 "missing ( before function parameters.")
1521
1522 (js2-msg "msg.no.parm"
1523 "missing formal parameter")
1524
1525 (js2-msg "msg.no.paren.after.parms"
1526 "missing ) after formal parameters")
1527
1528 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1529 "parameter without default follows parameter with default")
1530
1531 (js2-msg "msg.param.after.rest" ; added by js2-mode
1532 "parameter after rest parameter")
1533
1534 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1535 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1536
1537 (js2-msg "msg.no.brace.body"
1538 "missing '{' before function body")
1539
1540 (js2-msg "msg.no.brace.after.body"
1541 "missing } after function body")
1542
1543 (js2-msg "msg.no.paren.cond"
1544 "missing ( before condition")
1545
1546 (js2-msg "msg.no.paren.after.cond"
1547 "missing ) after condition")
1548
1549 (js2-msg "msg.no.semi.stmt"
1550 "missing ; before statement")
1551
1552 (js2-msg "msg.missing.semi"
1553 "missing ; after statement")
1554
1555 (js2-msg "msg.no.name.after.dot"
1556 "missing name after . operator")
1557
1558 (js2-msg "msg.no.name.after.coloncolon"
1559 "missing name after :: operator")
1560
1561 (js2-msg "msg.no.name.after.dotdot"
1562 "missing name after .. operator")
1563
1564 (js2-msg "msg.no.name.after.xmlAttr"
1565 "missing name after .@")
1566
1567 (js2-msg "msg.no.bracket.index"
1568 "missing ] in index expression")
1569
1570 (js2-msg "msg.no.paren.switch"
1571 "missing ( before switch expression")
1572
1573 (js2-msg "msg.no.paren.after.switch"
1574 "missing ) after switch expression")
1575
1576 (js2-msg "msg.no.brace.switch"
1577 "missing '{' before switch body")
1578
1579 (js2-msg "msg.bad.switch"
1580 "invalid switch statement")
1581
1582 (js2-msg "msg.no.colon.case"
1583 "missing : after case expression")
1584
1585 (js2-msg "msg.double.switch.default"
1586 "double default label in the switch statement")
1587
1588 (js2-msg "msg.no.while.do"
1589 "missing while after do-loop body")
1590
1591 (js2-msg "msg.no.paren.for"
1592 "missing ( after for")
1593
1594 (js2-msg "msg.no.semi.for"
1595 "missing ; after for-loop initializer")
1596
1597 (js2-msg "msg.no.semi.for.cond"
1598 "missing ; after for-loop condition")
1599
1600 (js2-msg "msg.in.after.for.name"
1601 "missing in or of after for")
1602
1603 (js2-msg "msg.no.paren.for.ctrl"
1604 "missing ) after for-loop control")
1605
1606 (js2-msg "msg.no.paren.with"
1607 "missing ( before with-statement object")
1608
1609 (js2-msg "msg.no.paren.after.with"
1610 "missing ) after with-statement object")
1611
1612 (js2-msg "msg.no.paren.after.let"
1613 "missing ( after let")
1614
1615 (js2-msg "msg.no.paren.let"
1616 "missing ) after variable list")
1617
1618 (js2-msg "msg.no.curly.let"
1619 "missing } after let statement")
1620
1621 (js2-msg "msg.bad.return"
1622 "invalid return")
1623
1624 (js2-msg "msg.no.brace.block"
1625 "missing } in compound statement")
1626
1627 (js2-msg "msg.bad.label"
1628 "invalid label")
1629
1630 (js2-msg "msg.bad.var"
1631 "missing variable name")
1632
1633 (js2-msg "msg.bad.var.init"
1634 "invalid variable initialization")
1635
1636 (js2-msg "msg.no.colon.cond"
1637 "missing : in conditional expression")
1638
1639 (js2-msg "msg.no.paren.arg"
1640 "missing ) after argument list")
1641
1642 (js2-msg "msg.no.bracket.arg"
1643 "missing ] after element list")
1644
1645 (js2-msg "msg.bad.prop"
1646 "invalid property id")
1647
1648 (js2-msg "msg.no.colon.prop"
1649 "missing : after property id")
1650
1651 (js2-msg "msg.no.brace.prop"
1652 "missing } after property list")
1653
1654 (js2-msg "msg.no.paren"
1655 "missing ) in parenthetical")
1656
1657 (js2-msg "msg.reserved.id"
1658 "'%s' is a reserved identifier")
1659
1660 (js2-msg "msg.no.paren.catch"
1661 "missing ( before catch-block condition")
1662
1663 (js2-msg "msg.bad.catchcond"
1664 "invalid catch block condition")
1665
1666 (js2-msg "msg.catch.unreachable"
1667 "any catch clauses following an unqualified catch are unreachable")
1668
1669 (js2-msg "msg.no.brace.try"
1670 "missing '{' before try block")
1671
1672 (js2-msg "msg.no.brace.catchblock"
1673 "missing '{' before catch-block body")
1674
1675 (js2-msg "msg.try.no.catchfinally"
1676 "'try' without 'catch' or 'finally'")
1677
1678 (js2-msg "msg.no.return.value"
1679 "function %s does not always return a value")
1680
1681 (js2-msg "msg.anon.no.return.value"
1682 "anonymous function does not always return a value")
1683
1684 (js2-msg "msg.return.inconsistent"
1685 "return statement is inconsistent with previous usage")
1686
1687 (js2-msg "msg.generator.returns"
1688 "TypeError: legacy generator function '%s' returns a value")
1689
1690 (js2-msg "msg.anon.generator.returns"
1691 "TypeError: anonymous legacy generator function returns a value")
1692
1693 (js2-msg "msg.syntax"
1694 "syntax error")
1695
1696 (js2-msg "msg.unexpected.eof"
1697 "Unexpected end of file")
1698
1699 (js2-msg "msg.XML.bad.form"
1700 "illegally formed XML syntax")
1701
1702 (js2-msg "msg.XML.not.available"
1703 "XML runtime not available")
1704
1705 (js2-msg "msg.too.deep.parser.recursion"
1706 "Too deep recursion while parsing")
1707
1708 (js2-msg "msg.no.side.effects"
1709 "Code has no side effects")
1710
1711 (js2-msg "msg.extra.trailing.comma"
1712 "Trailing comma is not supported in some browsers")
1713
1714 (js2-msg "msg.array.trailing.comma"
1715 "Trailing comma yields different behavior across browsers")
1716
1717 (js2-msg "msg.equal.as.assign"
1718 (concat "Test for equality (==) mistyped as assignment (=)?"
1719 " (parenthesize to suppress warning)"))
1720
1721 (js2-msg "msg.var.hides.arg"
1722 "Variable %s hides argument")
1723
1724 (js2-msg "msg.destruct.assign.no.init"
1725 "Missing = in destructuring declaration")
1726
1727 ;; ScriptRuntime
1728 (js2-msg "msg.no.properties"
1729 "%s has no properties.")
1730
1731 (js2-msg "msg.invalid.iterator"
1732 "Invalid iterator value")
1733
1734 (js2-msg "msg.iterator.primitive"
1735 "__iterator__ returned a primitive value")
1736
1737 (js2-msg "msg.assn.create.strict"
1738 "Assignment to undeclared variable %s")
1739
1740 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1741 "Undeclared variable or function '%s'")
1742
1743 (js2-msg "msg.ref.undefined.prop"
1744 "Reference to undefined property '%s'")
1745
1746 (js2-msg "msg.prop.not.found"
1747 "Property %s not found.")
1748
1749 (js2-msg "msg.invalid.type"
1750 "Invalid JavaScript value of type %s")
1751
1752 (js2-msg "msg.primitive.expected"
1753 "Primitive type expected (had %s instead)")
1754
1755 (js2-msg "msg.namespace.expected"
1756 "Namespace object expected to left of :: (found %s instead)")
1757
1758 (js2-msg "msg.null.to.object"
1759 "Cannot convert null to an object.")
1760
1761 (js2-msg "msg.undef.to.object"
1762 "Cannot convert undefined to an object.")
1763
1764 (js2-msg "msg.cyclic.value"
1765 "Cyclic %s value not allowed.")
1766
1767 (js2-msg "msg.is.not.defined"
1768 "'%s' is not defined.")
1769
1770 (js2-msg "msg.undef.prop.read"
1771 "Cannot read property '%s' from %s")
1772
1773 (js2-msg "msg.undef.prop.write"
1774 "Cannot set property '%s' of %s to '%s'")
1775
1776 (js2-msg "msg.undef.prop.delete"
1777 "Cannot delete property '%s' of %s")
1778
1779 (js2-msg "msg.undef.method.call"
1780 "Cannot call method '%s' of %s")
1781
1782 (js2-msg "msg.undef.with"
1783 "Cannot apply 'with' to %s")
1784
1785 (js2-msg "msg.isnt.function"
1786 "%s is not a function, it is %s.")
1787
1788 (js2-msg "msg.isnt.function.in"
1789 "Cannot call property %s in object %s. "
1790 "It is not a function, it is '%s'.")
1791
1792 (js2-msg "msg.function.not.found"
1793 "Cannot find function %s.")
1794
1795 (js2-msg "msg.function.not.found.in"
1796 "Cannot find function %s in object %s.")
1797
1798 (js2-msg "msg.isnt.xml.object"
1799 "%s is not an xml object.")
1800
1801 (js2-msg "msg.no.ref.to.get"
1802 "%s is not a reference to read reference value.")
1803
1804 (js2-msg "msg.no.ref.to.set"
1805 "%s is not a reference to set reference value to %s.")
1806
1807 (js2-msg "msg.no.ref.from.function"
1808 "Function %s can not be used as the left-hand "
1809 "side of assignment or as an operand of ++ or -- operator.")
1810
1811 (js2-msg "msg.bad.default.value"
1812 "Object's getDefaultValue() method returned an object.")
1813
1814 (js2-msg "msg.instanceof.not.object"
1815 "Can't use instanceof on a non-object.")
1816
1817 (js2-msg "msg.instanceof.bad.prototype"
1818 "'prototype' property of %s is not an object.")
1819
1820 (js2-msg "msg.bad.radix"
1821 "illegal radix %s.")
1822
1823 ;; ScriptableObject
1824 (js2-msg "msg.default.value"
1825 "Cannot find default value for object.")
1826
1827 (js2-msg "msg.zero.arg.ctor"
1828 "Cannot load class '%s' which has no zero-parameter constructor.")
1829
1830 (js2-msg "msg.ctor.multiple.parms"
1831 "Can't define constructor or class %s since more than "
1832 "one constructor has multiple parameters.")
1833
1834 (js2-msg "msg.extend.scriptable"
1835 "%s must extend ScriptableObject in order to define property %s.")
1836
1837 (js2-msg "msg.bad.getter.parms"
1838 "In order to define a property, getter %s must have zero "
1839 "parameters or a single ScriptableObject parameter.")
1840
1841 (js2-msg "msg.obj.getter.parms"
1842 "Expected static or delegated getter %s to take "
1843 "a ScriptableObject parameter.")
1844
1845 (js2-msg "msg.getter.static"
1846 "Getter and setter must both be static or neither be static.")
1847
1848 (js2-msg "msg.setter.return"
1849 "Setter must have void return type: %s")
1850
1851 (js2-msg "msg.setter2.parms"
1852 "Two-parameter setter must take a ScriptableObject as "
1853 "its first parameter.")
1854
1855 (js2-msg "msg.setter1.parms"
1856 "Expected single parameter setter for %s")
1857
1858 (js2-msg "msg.setter2.expected"
1859 "Expected static or delegated setter %s to take two parameters.")
1860
1861 (js2-msg "msg.setter.parms"
1862 "Expected either one or two parameters for setter.")
1863
1864 (js2-msg "msg.setter.bad.type"
1865 "Unsupported parameter type '%s' in setter '%s'.")
1866
1867 (js2-msg "msg.add.sealed"
1868 "Cannot add a property to a sealed object: %s.")
1869
1870 (js2-msg "msg.remove.sealed"
1871 "Cannot remove a property from a sealed object: %s.")
1872
1873 (js2-msg "msg.modify.sealed"
1874 "Cannot modify a property of a sealed object: %s.")
1875
1876 (js2-msg "msg.modify.readonly"
1877 "Cannot modify readonly property: %s.")
1878
1879 ;; TokenStream
1880 (js2-msg "msg.missing.exponent"
1881 "missing exponent")
1882
1883 (js2-msg "msg.caught.nfe"
1884 "number format error")
1885
1886 (js2-msg "msg.unterminated.string.lit"
1887 "unterminated string literal")
1888
1889 (js2-msg "msg.unterminated.comment"
1890 "unterminated comment")
1891
1892 (js2-msg "msg.unterminated.re.lit"
1893 "unterminated regular expression literal")
1894
1895 (js2-msg "msg.invalid.re.flag"
1896 "invalid flag after regular expression")
1897
1898 (js2-msg "msg.no.re.input.for"
1899 "no input for %s")
1900
1901 (js2-msg "msg.illegal.character"
1902 "illegal character")
1903
1904 (js2-msg "msg.invalid.escape"
1905 "invalid Unicode escape sequence")
1906
1907 (js2-msg "msg.bad.namespace"
1908 "not a valid default namespace statement. "
1909 "Syntax is: default xml namespace = EXPRESSION;")
1910
1911 ;; TokensStream warnings
1912 (js2-msg "msg.bad.octal.literal"
1913 "illegal octal literal digit %s; "
1914 "interpreting it as a decimal digit")
1915
1916 (js2-msg "msg.missing.hex.digits"
1917 "missing hexadecimal digits after '0x'")
1918
1919 (js2-msg "msg.missing.binary.digits"
1920 "missing binary digits after '0b'")
1921
1922 (js2-msg "msg.missing.octal.digits"
1923 "missing octal digits after '0o'")
1924
1925 (js2-msg "msg.script.is.not.constructor"
1926 "Script objects are not constructors.")
1927
1928 ;; Arrays
1929 (js2-msg "msg.arraylength.bad"
1930 "Inappropriate array length.")
1931
1932 ;; Arrays
1933 (js2-msg "msg.arraylength.too.big"
1934 "Array length %s exceeds supported capacity limit.")
1935
1936 ;; URI
1937 (js2-msg "msg.bad.uri"
1938 "Malformed URI sequence.")
1939
1940 ;; Number
1941 (js2-msg "msg.bad.precision"
1942 "Precision %s out of range.")
1943
1944 ;; NativeGenerator
1945 (js2-msg "msg.send.newborn"
1946 "Attempt to send value to newborn generator")
1947
1948 (js2-msg "msg.already.exec.gen"
1949 "Already executing generator")
1950
1951 (js2-msg "msg.StopIteration.invalid"
1952 "StopIteration may not be changed to an arbitrary object.")
1953
1954 ;; Interpreter
1955 (js2-msg "msg.yield.closing"
1956 "Yield from closing generator")
1957
1958 ;; Classes
1959 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
1960 "missing ']' after computed property expression")
1961
1962 ;;; Tokens Buffer
1963
1964 (defconst js2-ti-max-lookahead 2)
1965 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1966
1967 ;; Have to call `js2-init-scanner' to initialize the values.
1968 (js2-deflocal js2-ti-tokens nil)
1969 (js2-deflocal js2-ti-tokens-cursor nil)
1970 (js2-deflocal js2-ti-lookahead nil)
1971
1972 (defun js2-new-token (offset)
1973 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
1974 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
1975 (aset js2-ti-tokens js2-ti-tokens-cursor token)
1976 token))
1977
1978 (defsubst js2-current-token ()
1979 (aref js2-ti-tokens js2-ti-tokens-cursor))
1980
1981 (defsubst js2-current-token-string ()
1982 (js2-token-string (js2-current-token)))
1983
1984 (defsubst js2-current-token-type ()
1985 (js2-token-type (js2-current-token)))
1986
1987 (defsubst js2-current-token-beg ()
1988 (js2-token-beg (js2-current-token)))
1989
1990 (defsubst js2-current-token-end ()
1991 (js2-token-end (js2-current-token)))
1992
1993 (defun js2-current-token-len ()
1994 (let ((token (js2-current-token)))
1995 (- (js2-token-end token)
1996 (js2-token-beg token))))
1997
1998 (defun js2-ts-seek (state)
1999 (setq js2-ts-lineno (js2-ts-state-lineno state)
2000 js2-ts-cursor (js2-ts-state-cursor state)
2001 js2-ti-tokens (js2-ts-state-tokens state)
2002 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2003 js2-ti-lookahead (js2-ts-state-lookahead state)))
2004
2005 ;;; Utilities
2006
2007 (defun js2-delete-if (predicate list)
2008 "Remove all items satisfying PREDICATE in LIST."
2009 (loop for item in list
2010 if (not (funcall predicate item))
2011 collect item))
2012
2013 (defun js2-position (element list)
2014 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2015 Returns nil if element is not found in the list."
2016 (let ((count 0)
2017 found)
2018 (while (and list (not found))
2019 (if (eq element (car list))
2020 (setq found t)
2021 (setq count (1+ count)
2022 list (cdr list))))
2023 (if found count)))
2024
2025 (defun js2-find-if (predicate list)
2026 "Find first item satisfying PREDICATE in LIST."
2027 (let (result)
2028 (while (and list (not result))
2029 (if (funcall predicate (car list))
2030 (setq result (car list)))
2031 (setq list (cdr list)))
2032 result))
2033
2034 (defmacro js2-time (form)
2035 "Evaluate FORM, discard result, and return elapsed time in sec."
2036 (declare (debug t))
2037 (let ((beg (make-symbol "--js2-time-beg--"))
2038 (delta (make-symbol "--js2-time-end--")))
2039 `(let ((,beg (current-time))
2040 ,delta)
2041 ,form
2042 (/ (truncate (* (- (float-time (current-time))
2043 (float-time ,beg))
2044 10000))
2045 10000.0))))
2046
2047 (defsubst js2-same-line (pos)
2048 "Return t if POS is on the same line as current point."
2049 (and (>= pos (point-at-bol))
2050 (<= pos (point-at-eol))))
2051
2052 (defun js2-code-bug ()
2053 "Signal an error when we encounter an unexpected code path."
2054 (error "failed assertion"))
2055
2056 (defsubst js2-record-text-property (beg end prop value)
2057 "Record a text property to set when parsing finishes."
2058 (push (list beg end prop value) js2-mode-deferred-properties))
2059
2060 ;; I'd like to associate errors with nodes, but for now the
2061 ;; easiest thing to do is get the context info from the last token.
2062 (defun js2-record-parse-error (msg &optional arg pos len)
2063 (push (list (list msg arg)
2064 (or pos (js2-current-token-beg))
2065 (or len (js2-current-token-len)))
2066 js2-parsed-errors))
2067
2068 (defun js2-report-error (msg &optional msg-arg pos len)
2069 "Signal a syntax error or record a parse error."
2070 (if js2-recover-from-parse-errors
2071 (js2-record-parse-error msg msg-arg pos len)
2072 (signal 'js2-syntax-error
2073 (list msg
2074 js2-ts-lineno
2075 (save-excursion
2076 (goto-char js2-ts-cursor)
2077 (current-column))
2078 js2-ts-hit-eof))))
2079
2080 (defun js2-report-warning (msg &optional msg-arg pos len face)
2081 (if js2-compiler-report-warning-as-error
2082 (js2-report-error msg msg-arg pos len)
2083 (push (list (list msg msg-arg)
2084 (or pos (js2-current-token-beg))
2085 (or len (js2-current-token-len))
2086 face)
2087 js2-parsed-warnings)))
2088
2089 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2090 (if js2-compiler-strict-mode
2091 (js2-report-warning msg-id msg-arg beg
2092 (and beg end (- end beg)))))
2093
2094 (put 'js2-syntax-error 'error-conditions
2095 '(error syntax-error js2-syntax-error))
2096 (put 'js2-syntax-error 'error-message "Syntax error")
2097
2098 (put 'js2-parse-error 'error-conditions
2099 '(error parse-error js2-parse-error))
2100 (put 'js2-parse-error 'error-message "Parse error")
2101
2102 (defmacro js2-clear-flag (flags flag)
2103 `(setq ,flags (logand ,flags (lognot ,flag))))
2104
2105 (defmacro js2-set-flag (flags flag)
2106 "Logical-or FLAG into FLAGS."
2107 `(setq ,flags (logior ,flags ,flag)))
2108
2109 (defsubst js2-flag-set-p (flags flag)
2110 (/= 0 (logand flags flag)))
2111
2112 (defsubst js2-flag-not-set-p (flags flag)
2113 (zerop (logand flags flag)))
2114
2115 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2116 "Evaluate BODY with the _ character set to be word-syntax."
2117 (declare (indent 0) (debug t))
2118 (let ((old-syntax (make-symbol "old-syntax")))
2119 `(let ((,old-syntax (string (char-syntax ?_))))
2120 (unwind-protect
2121 (progn
2122 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2123 ,@body)
2124 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2125
2126 ;;; AST struct and function definitions
2127
2128 ;; flags for ast node property 'member-type (used for e4x operators)
2129 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2130 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2131 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2132
2133 (defsubst js2-relpos (pos anchor)
2134 "Convert POS to be relative to ANCHOR.
2135 If POS is nil, returns nil."
2136 (and pos (- pos anchor)))
2137
2138 (defun js2-make-pad (indent)
2139 (if (zerop indent)
2140 ""
2141 (make-string (* indent js2-basic-offset) ? )))
2142
2143 (defun js2-visit-ast (node callback)
2144 "Visit every node in ast NODE with visitor CALLBACK.
2145
2146 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2147 called twice: once to visit the node, and again after all the node's
2148 children have been processed. The END-P argument is nil on the first
2149 call and non-nil on the second call. The return value of the callback
2150 affects the traversal: if non-nil, the children of NODE are processed.
2151 If the callback returns nil, or if the node has no children, then the
2152 callback is called immediately with a non-nil END-P argument.
2153
2154 The node traversal is approximately lexical-order, although there
2155 are currently no guarantees around this."
2156 (when node
2157 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2158 ;; visit the node
2159 (when (funcall callback node nil)
2160 ;; visit the kids
2161 (cond
2162 ((eq vfunc 'js2-visit-none)
2163 nil) ; don't even bother calling it
2164 ;; Each AST node type has to define a `js2-visitor' function
2165 ;; that takes a node and a callback, and calls `js2-visit-ast'
2166 ;; on each child of the node.
2167 (vfunc
2168 (funcall vfunc node callback))
2169 (t
2170 (error "%s does not define a visitor-traversal function"
2171 (aref node 0)))))
2172 ;; call the end-visit
2173 (funcall callback node t))))
2174
2175 (defstruct (js2-node
2176 (:constructor nil)) ; abstract
2177 "Base AST node type."
2178 (type -1) ; token type
2179 (pos -1) ; start position of this AST node in parsed input
2180 (len 1) ; num characters spanned by the node
2181 props ; optional node property list (an alist)
2182 parent) ; link to parent node; null for root
2183
2184 (defsubst js2-node-get-prop (node prop &optional default)
2185 (or (cadr (assoc prop (js2-node-props node))) default))
2186
2187 (defsubst js2-node-set-prop (node prop value)
2188 (setf (js2-node-props node)
2189 (cons (list prop value) (js2-node-props node))))
2190
2191 (defun js2-fixup-starts (n nodes)
2192 "Adjust the start positions of NODES to be relative to N.
2193 Any node in the list may be nil, for convenience."
2194 (dolist (node nodes)
2195 (when node
2196 (setf (js2-node-pos node) (- (js2-node-pos node)
2197 (js2-node-pos n))))))
2198
2199 (defun js2-node-add-children (parent &rest nodes)
2200 "Set parent node of NODES to PARENT, and return PARENT.
2201 Does nothing if we're not recording parent links.
2202 If any given node in NODES is nil, doesn't record that link."
2203 (js2-fixup-starts parent nodes)
2204 (dolist (node nodes)
2205 (and node
2206 (setf (js2-node-parent node) parent))))
2207
2208 ;; Non-recursive since it's called a frightening number of times.
2209 (defun js2-node-abs-pos (n)
2210 (let ((pos (js2-node-pos n)))
2211 (while (setq n (js2-node-parent n))
2212 (setq pos (+ pos (js2-node-pos n))))
2213 pos))
2214
2215 (defsubst js2-node-abs-end (n)
2216 "Return absolute buffer position of end of N."
2217 (+ (js2-node-abs-pos n) (js2-node-len n)))
2218
2219 ;; It's important to make sure block nodes have a Lisp list for the
2220 ;; child nodes, to limit printing recursion depth in an AST that
2221 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2222 ;; a sufficiently large vector tree.
2223
2224 (defstruct (js2-block-node
2225 (:include js2-node)
2226 (:constructor nil)
2227 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2228 (pos (js2-current-token-beg))
2229 len
2230 props
2231 kids)))
2232 "A block of statements."
2233 kids) ; a Lisp list of the child statement nodes
2234
2235 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2236 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2237
2238 (defun js2-visit-block (ast callback)
2239 "Visit the `js2-block-node' children of AST."
2240 (dolist (kid (js2-block-node-kids ast))
2241 (js2-visit-ast kid callback)))
2242
2243 (defun js2-print-block (n i)
2244 (let ((pad (js2-make-pad i)))
2245 (insert pad "{\n")
2246 (dolist (kid (js2-block-node-kids n))
2247 (js2-print-ast kid (1+ i)))
2248 (insert pad "}")))
2249
2250 (defstruct (js2-scope
2251 (:include js2-block-node)
2252 (:constructor nil)
2253 (:constructor make-js2-scope (&key (type js2-BLOCK)
2254 (pos (js2-current-token-beg))
2255 len
2256 kids)))
2257 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2258 ;; I don't have one of those handy, so I'll use an alist for now.
2259 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2260 ;; and is much lighter-weight to construct (both CPU and mem).
2261 ;; The keys are interned strings (symbols) for faster lookup.
2262 ;; Should switch to hybrid alist/hashtable eventually.
2263 symbol-table ; an alist of (symbol . js2-symbol)
2264 parent-scope ; a `js2-scope'
2265 top) ; top-level `js2-scope' (script/function)
2266
2267 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2268 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2269
2270 (defun js2-node-get-enclosing-scope (node)
2271 "Return the innermost `js2-scope' node surrounding NODE.
2272 Returns nil if there is no enclosing scope node."
2273 (let ((parent (js2-node-parent node)))
2274 (while (not (js2-scope-p parent))
2275 (setq parent (js2-node-parent parent)))
2276 parent))
2277
2278 (defun js2-get-defining-scope (scope name)
2279 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2280 Returns `js2-scope' in which NAME is defined, or nil if not found."
2281 (let ((sym (if (symbolp name)
2282 name
2283 (intern name)))
2284 table
2285 result
2286 (continue t))
2287 (while (and scope continue)
2288 (if (and (setq table (js2-scope-symbol-table scope))
2289 (assq sym table))
2290 (setq continue nil
2291 result scope)
2292 (setq scope (js2-scope-parent-scope scope))))
2293 result))
2294
2295 (defun js2-scope-get-symbol (scope name)
2296 "Return symbol table entry for NAME in SCOPE.
2297 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2298 (and (js2-scope-symbol-table scope)
2299 (cdr (assq (if (symbolp name)
2300 name
2301 (intern name))
2302 (js2-scope-symbol-table scope)))))
2303
2304 (defun js2-scope-put-symbol (scope name symbol)
2305 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2306 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2307 (let* ((table (js2-scope-symbol-table scope))
2308 (sym (if (symbolp name) name (intern name)))
2309 (entry (assq sym table)))
2310 (if entry
2311 (setcdr entry symbol)
2312 (push (cons sym symbol)
2313 (js2-scope-symbol-table scope)))))
2314
2315 (defstruct (js2-symbol
2316 (:constructor nil)
2317 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2318 "A symbol table entry."
2319 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2320 ;; js2-LET, or js2-CONST
2321 decl-type
2322 name ; string
2323 ast-node) ; a `js2-node'
2324
2325 (defstruct (js2-error-node
2326 (:include js2-node)
2327 (:constructor nil) ; silence emacs21 byte-compiler
2328 (:constructor make-js2-error-node (&key (type js2-ERROR)
2329 (pos (js2-current-token-beg))
2330 len)))
2331 "AST node representing a parse error.")
2332
2333 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2334 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2335
2336 (defstruct (js2-script-node
2337 (:include js2-scope)
2338 (:constructor nil)
2339 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2340 (pos (js2-current-token-beg))
2341 len
2342 ;; FIXME: What are those?
2343 var-decls
2344 fun-decls)))
2345 functions ; Lisp list of nested functions
2346 regexps ; Lisp list of (string . flags)
2347 symbols ; alist (every symbol gets unique index)
2348 (param-count 0)
2349 var-names ; vector of string names
2350 consts ; bool-vector matching var-decls
2351 (temp-number 0)) ; for generating temp variables
2352
2353 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2354 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2355
2356 (defun js2-print-script (node indent)
2357 (dolist (kid (js2-block-node-kids node))
2358 (js2-print-ast kid indent)))
2359
2360 (defstruct (js2-ast-root
2361 (:include js2-script-node)
2362 (:constructor nil)
2363 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2364 (pos (js2-current-token-beg))
2365 len
2366 buffer)))
2367 "The root node of a js2 AST."
2368 buffer ; the source buffer from which the code was parsed
2369 comments ; a Lisp list of comments, ordered by start position
2370 errors ; a Lisp list of errors found during parsing
2371 warnings ; a Lisp list of warnings found during parsing
2372 node-count) ; number of nodes in the tree, including the root
2373
2374 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2375 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2376
2377 (defun js2-visit-ast-root (ast callback)
2378 (dolist (kid (js2-ast-root-kids ast))
2379 (js2-visit-ast kid callback))
2380 (dolist (comment (js2-ast-root-comments ast))
2381 (js2-visit-ast comment callback)))
2382
2383 (defstruct (js2-comment-node
2384 (:include js2-node)
2385 (:constructor nil)
2386 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2387 (pos (js2-current-token-beg))
2388 len
2389 format)))
2390 format) ; 'line, 'block, 'jsdoc or 'html
2391
2392 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2393 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2394
2395 (defun js2-print-comment (n i)
2396 ;; We really ought to link end-of-line comments to their nodes.
2397 ;; Or maybe we could add a new comment type, 'endline.
2398 (insert (js2-make-pad i)
2399 (js2-node-string n)))
2400
2401 (defstruct (js2-expr-stmt-node
2402 (:include js2-node)
2403 (:constructor nil)
2404 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2405 (pos js2-ts-cursor)
2406 len
2407 expr)))
2408 "An expression statement."
2409 expr)
2410
2411 (defsubst js2-expr-stmt-node-set-has-result (node)
2412 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2413 (setf (js2-node-type node) js2-EXPR_RESULT))
2414
2415 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2416 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2417
2418 (defun js2-visit-expr-stmt-node (n v)
2419 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2420
2421 (defun js2-print-expr-stmt-node (n indent)
2422 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2423 (insert ";\n"))
2424
2425 (defstruct (js2-loop-node
2426 (:include js2-scope)
2427 (:constructor nil))
2428 "Abstract supertype of loop nodes."
2429 body ; a `js2-block-node'
2430 lp ; position of left-paren, nil if omitted
2431 rp) ; position of right-paren, nil if omitted
2432
2433 (defstruct (js2-do-node
2434 (:include js2-loop-node)
2435 (:constructor nil)
2436 (:constructor make-js2-do-node (&key (type js2-DO)
2437 (pos (js2-current-token-beg))
2438 len
2439 body
2440 condition
2441 while-pos
2442 lp
2443 rp)))
2444 "AST node for do-loop."
2445 condition ; while (expression)
2446 while-pos) ; buffer position of 'while' keyword
2447
2448 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2449 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2450
2451 (defun js2-visit-do-node (n v)
2452 (js2-visit-ast (js2-do-node-body n) v)
2453 (js2-visit-ast (js2-do-node-condition n) v))
2454
2455 (defun js2-print-do-node (n i)
2456 (let ((pad (js2-make-pad i)))
2457 (insert pad "do {\n")
2458 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2459 (js2-print-ast kid (1+ i)))
2460 (insert pad "} while (")
2461 (js2-print-ast (js2-do-node-condition n) 0)
2462 (insert ");\n")))
2463
2464 (defstruct (js2-while-node
2465 (:include js2-loop-node)
2466 (:constructor nil)
2467 (:constructor make-js2-while-node (&key (type js2-WHILE)
2468 (pos (js2-current-token-beg))
2469 len body
2470 condition lp
2471 rp)))
2472 "AST node for while-loop."
2473 condition) ; while-condition
2474
2475 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2476 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2477
2478 (defun js2-visit-while-node (n v)
2479 (js2-visit-ast (js2-while-node-condition n) v)
2480 (js2-visit-ast (js2-while-node-body n) v))
2481
2482 (defun js2-print-while-node (n i)
2483 (let ((pad (js2-make-pad i)))
2484 (insert pad "while (")
2485 (js2-print-ast (js2-while-node-condition n) 0)
2486 (insert ") {\n")
2487 (js2-print-body (js2-while-node-body n) (1+ i))
2488 (insert pad "}\n")))
2489
2490 (defstruct (js2-for-node
2491 (:include js2-loop-node)
2492 (:constructor nil)
2493 (:constructor make-js2-for-node (&key (type js2-FOR)
2494 (pos js2-ts-cursor)
2495 len body init
2496 condition
2497 update lp rp)))
2498 "AST node for a C-style for-loop."
2499 init ; initialization expression
2500 condition ; loop condition
2501 update) ; update clause
2502
2503 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2504 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2505
2506 (defun js2-visit-for-node (n v)
2507 (js2-visit-ast (js2-for-node-init n) v)
2508 (js2-visit-ast (js2-for-node-condition n) v)
2509 (js2-visit-ast (js2-for-node-update n) v)
2510 (js2-visit-ast (js2-for-node-body n) v))
2511
2512 (defun js2-print-for-node (n i)
2513 (let ((pad (js2-make-pad i)))
2514 (insert pad "for (")
2515 (js2-print-ast (js2-for-node-init n) 0)
2516 (insert "; ")
2517 (js2-print-ast (js2-for-node-condition n) 0)
2518 (insert "; ")
2519 (js2-print-ast (js2-for-node-update n) 0)
2520 (insert ") {\n")
2521 (js2-print-body (js2-for-node-body n) (1+ i))
2522 (insert pad "}\n")))
2523
2524 (defstruct (js2-for-in-node
2525 (:include js2-loop-node)
2526 (:constructor nil)
2527 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2528 (pos js2-ts-cursor)
2529 len body
2530 iterator
2531 object
2532 in-pos
2533 each-pos
2534 foreach-p forof-p
2535 lp rp)))
2536 "AST node for a for..in loop."
2537 iterator ; [var] foo in ...
2538 object ; object over which we're iterating
2539 in-pos ; buffer position of 'in' keyword
2540 each-pos ; buffer position of 'each' keyword, if foreach-p
2541 foreach-p ; t if it's a for-each loop
2542 forof-p) ; t if it's a for-of loop
2543
2544 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2545 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2546
2547 (defun js2-visit-for-in-node (n v)
2548 (js2-visit-ast (js2-for-in-node-iterator n) v)
2549 (js2-visit-ast (js2-for-in-node-object n) v)
2550 (js2-visit-ast (js2-for-in-node-body n) v))
2551
2552 (defun js2-print-for-in-node (n i)
2553 (let ((pad (js2-make-pad i))
2554 (foreach (js2-for-in-node-foreach-p n))
2555 (forof (js2-for-in-node-forof-p n)))
2556 (insert pad "for ")
2557 (if foreach
2558 (insert "each "))
2559 (insert "(")
2560 (js2-print-ast (js2-for-in-node-iterator n) 0)
2561 (insert (if forof " of " " in "))
2562 (js2-print-ast (js2-for-in-node-object n) 0)
2563 (insert ") {\n")
2564 (js2-print-body (js2-for-in-node-body n) (1+ i))
2565 (insert pad "}\n")))
2566
2567 (defstruct (js2-return-node
2568 (:include js2-node)
2569 (:constructor nil)
2570 (:constructor make-js2-return-node (&key (type js2-RETURN)
2571 (pos js2-ts-cursor)
2572 len
2573 retval)))
2574 "AST node for a return statement."
2575 retval) ; expression to return, or 'undefined
2576
2577 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2578 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2579
2580 (defun js2-visit-return-node (n v)
2581 (js2-visit-ast (js2-return-node-retval n) v))
2582
2583 (defun js2-print-return-node (n i)
2584 (insert (js2-make-pad i) "return")
2585 (when (js2-return-node-retval n)
2586 (insert " ")
2587 (js2-print-ast (js2-return-node-retval n) 0))
2588 (insert ";\n"))
2589
2590 (defstruct (js2-if-node
2591 (:include js2-node)
2592 (:constructor nil)
2593 (:constructor make-js2-if-node (&key (type js2-IF)
2594 (pos js2-ts-cursor)
2595 len condition
2596 then-part
2597 else-pos
2598 else-part lp
2599 rp)))
2600 "AST node for an if-statement."
2601 condition ; expression
2602 then-part ; statement or block
2603 else-pos ; optional buffer position of 'else' keyword
2604 else-part ; optional statement or block
2605 lp ; position of left-paren, nil if omitted
2606 rp) ; position of right-paren, nil if omitted
2607
2608 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2609 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2610
2611 (defun js2-visit-if-node (n v)
2612 (js2-visit-ast (js2-if-node-condition n) v)
2613 (js2-visit-ast (js2-if-node-then-part n) v)
2614 (js2-visit-ast (js2-if-node-else-part n) v))
2615
2616 (defun js2-print-if-node (n i)
2617 (let ((pad (js2-make-pad i))
2618 (then-part (js2-if-node-then-part n))
2619 (else-part (js2-if-node-else-part n)))
2620 (insert pad "if (")
2621 (js2-print-ast (js2-if-node-condition n) 0)
2622 (insert ") {\n")
2623 (js2-print-body then-part (1+ i))
2624 (insert pad "}")
2625 (cond
2626 ((not else-part)
2627 (insert "\n"))
2628 ((js2-if-node-p else-part)
2629 (insert " else ")
2630 (js2-print-body else-part i))
2631 (t
2632 (insert " else {\n")
2633 (js2-print-body else-part (1+ i))
2634 (insert pad "}\n")))))
2635
2636 (defstruct (js2-try-node
2637 (:include js2-node)
2638 (:constructor nil)
2639 (:constructor make-js2-try-node (&key (type js2-TRY)
2640 (pos js2-ts-cursor)
2641 len
2642 try-block
2643 catch-clauses
2644 finally-block)))
2645 "AST node for a try-statement."
2646 try-block
2647 catch-clauses ; a Lisp list of `js2-catch-node'
2648 finally-block) ; a `js2-finally-node'
2649
2650 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2651 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2652
2653 (defun js2-visit-try-node (n v)
2654 (js2-visit-ast (js2-try-node-try-block n) v)
2655 (dolist (clause (js2-try-node-catch-clauses n))
2656 (js2-visit-ast clause v))
2657 (js2-visit-ast (js2-try-node-finally-block n) v))
2658
2659 (defun js2-print-try-node (n i)
2660 (let ((pad (js2-make-pad i))
2661 (catches (js2-try-node-catch-clauses n))
2662 (finally (js2-try-node-finally-block n)))
2663 (insert pad "try {\n")
2664 (js2-print-body (js2-try-node-try-block n) (1+ i))
2665 (insert pad "}")
2666 (when catches
2667 (dolist (catch catches)
2668 (js2-print-ast catch i)))
2669 (if finally
2670 (js2-print-ast finally i)
2671 (insert "\n"))))
2672
2673 (defstruct (js2-catch-node
2674 (:include js2-node)
2675 (:constructor nil)
2676 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2677 (pos js2-ts-cursor)
2678 len
2679 param
2680 guard-kwd
2681 guard-expr
2682 block lp
2683 rp)))
2684 "AST node for a catch clause."
2685 param ; destructuring form or simple name node
2686 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2687 guard-expr ; catch condition, a `js2-node'
2688 block ; statements, a `js2-block-node'
2689 lp ; buffer position of left-paren, nil if omitted
2690 rp) ; buffer position of right-paren, nil if omitted
2691
2692 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2693 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2694
2695 (defun js2-visit-catch-node (n v)
2696 (js2-visit-ast (js2-catch-node-param n) v)
2697 (when (js2-catch-node-guard-kwd n)
2698 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2699 (js2-visit-ast (js2-catch-node-block n) v))
2700
2701 (defun js2-print-catch-node (n i)
2702 (let ((pad (js2-make-pad i))
2703 (guard-kwd (js2-catch-node-guard-kwd n))
2704 (guard-expr (js2-catch-node-guard-expr n)))
2705 (insert " catch (")
2706 (js2-print-ast (js2-catch-node-param n) 0)
2707 (when guard-kwd
2708 (insert " if ")
2709 (js2-print-ast guard-expr 0))
2710 (insert ") {\n")
2711 (js2-print-body (js2-catch-node-block n) (1+ i))
2712 (insert pad "}")))
2713
2714 (defstruct (js2-finally-node
2715 (:include js2-node)
2716 (:constructor nil)
2717 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2718 (pos js2-ts-cursor)
2719 len body)))
2720 "AST node for a finally clause."
2721 body) ; a `js2-node', often but not always a block node
2722
2723 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2724 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2725
2726 (defun js2-visit-finally-node (n v)
2727 (js2-visit-ast (js2-finally-node-body n) v))
2728
2729 (defun js2-print-finally-node (n i)
2730 (let ((pad (js2-make-pad i)))
2731 (insert " finally {\n")
2732 (js2-print-body (js2-finally-node-body n) (1+ i))
2733 (insert pad "}\n")))
2734
2735 (defstruct (js2-switch-node
2736 (:include js2-node)
2737 (:constructor nil)
2738 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2739 (pos js2-ts-cursor)
2740 len
2741 discriminant
2742 cases lp
2743 rp)))
2744 "AST node for a switch statement."
2745 discriminant ; a `js2-node' (switch expression)
2746 cases ; a Lisp list of `js2-case-node'
2747 lp ; position of open-paren for discriminant, nil if omitted
2748 rp) ; position of close-paren for discriminant, nil if omitted
2749
2750 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2751 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2752
2753 (defun js2-visit-switch-node (n v)
2754 (js2-visit-ast (js2-switch-node-discriminant n) v)
2755 (dolist (c (js2-switch-node-cases n))
2756 (js2-visit-ast c v)))
2757
2758 (defun js2-print-switch-node (n i)
2759 (let ((pad (js2-make-pad i))
2760 (cases (js2-switch-node-cases n)))
2761 (insert pad "switch (")
2762 (js2-print-ast (js2-switch-node-discriminant n) 0)
2763 (insert ") {\n")
2764 (dolist (case cases)
2765 (js2-print-ast case i))
2766 (insert pad "}\n")))
2767
2768 (defstruct (js2-case-node
2769 (:include js2-block-node)
2770 (:constructor nil)
2771 (:constructor make-js2-case-node (&key (type js2-CASE)
2772 (pos js2-ts-cursor)
2773 len kids expr)))
2774 "AST node for a case clause of a switch statement."
2775 expr) ; the case expression (nil for default)
2776
2777 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2778 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2779
2780 (defun js2-visit-case-node (n v)
2781 (js2-visit-ast (js2-case-node-expr n) v)
2782 (js2-visit-block n v))
2783
2784 (defun js2-print-case-node (n i)
2785 (let ((pad (js2-make-pad i))
2786 (expr (js2-case-node-expr n)))
2787 (insert pad)
2788 (if (null expr)
2789 (insert "default:\n")
2790 (insert "case ")
2791 (js2-print-ast expr 0)
2792 (insert ":\n"))
2793 (dolist (kid (js2-case-node-kids n))
2794 (js2-print-ast kid (1+ i)))))
2795
2796 (defstruct (js2-throw-node
2797 (:include js2-node)
2798 (:constructor nil)
2799 (:constructor make-js2-throw-node (&key (type js2-THROW)
2800 (pos js2-ts-cursor)
2801 len expr)))
2802 "AST node for a throw statement."
2803 expr) ; the expression to throw
2804
2805 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2806 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2807
2808 (defun js2-visit-throw-node (n v)
2809 (js2-visit-ast (js2-throw-node-expr n) v))
2810
2811 (defun js2-print-throw-node (n i)
2812 (insert (js2-make-pad i) "throw ")
2813 (js2-print-ast (js2-throw-node-expr n) 0)
2814 (insert ";\n"))
2815
2816 (defstruct (js2-with-node
2817 (:include js2-node)
2818 (:constructor nil)
2819 (:constructor make-js2-with-node (&key (type js2-WITH)
2820 (pos js2-ts-cursor)
2821 len object
2822 body lp rp)))
2823 "AST node for a with-statement."
2824 object
2825 body
2826 lp ; buffer position of left-paren around object, nil if omitted
2827 rp) ; buffer position of right-paren around object, nil if omitted
2828
2829 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2830 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2831
2832 (defun js2-visit-with-node (n v)
2833 (js2-visit-ast (js2-with-node-object n) v)
2834 (js2-visit-ast (js2-with-node-body n) v))
2835
2836 (defun js2-print-with-node (n i)
2837 (let ((pad (js2-make-pad i)))
2838 (insert pad "with (")
2839 (js2-print-ast (js2-with-node-object n) 0)
2840 (insert ") {\n")
2841 (js2-print-body (js2-with-node-body n) (1+ i))
2842 (insert pad "}\n")))
2843
2844 (defstruct (js2-label-node
2845 (:include js2-node)
2846 (:constructor nil)
2847 (:constructor make-js2-label-node (&key (type js2-LABEL)
2848 (pos js2-ts-cursor)
2849 len name)))
2850 "AST node for a statement label or case label."
2851 name ; a string
2852 loop) ; for validating and code-generating continue-to-label
2853
2854 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2855 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2856
2857 (defun js2-print-label (n i)
2858 (insert (js2-make-pad i)
2859 (js2-label-node-name n)
2860 ":\n"))
2861
2862 (defstruct (js2-labeled-stmt-node
2863 (:include js2-node)
2864 (:constructor nil)
2865 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2866 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2867 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2868 (pos js2-ts-cursor)
2869 len labels stmt)))
2870 "AST node for a statement with one or more labels.
2871 Multiple labels for a statement are collapsed into the labels field."
2872 labels ; Lisp list of `js2-label-node'
2873 stmt) ; the statement these labels are for
2874
2875 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2876 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2877
2878 (defun js2-get-label-by-name (lbl-stmt name)
2879 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2880 Returns nil if no such label is in the list."
2881 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2882 result)
2883 (while (and label-list (not result))
2884 (if (string= (js2-label-node-name (car label-list)) name)
2885 (setq result (car label-list))
2886 (setq label-list (cdr label-list))))
2887 result))
2888
2889 (defun js2-visit-labeled-stmt (n v)
2890 (dolist (label (js2-labeled-stmt-node-labels n))
2891 (js2-visit-ast label v))
2892 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2893
2894 (defun js2-print-labeled-stmt (n i)
2895 (dolist (label (js2-labeled-stmt-node-labels n))
2896 (js2-print-ast label i))
2897 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
2898
2899 (defun js2-labeled-stmt-node-contains (node label)
2900 "Return t if NODE contains LABEL in its label set.
2901 NODE is a `js2-labels-node'. LABEL is an identifier."
2902 (loop for nl in (js2-labeled-stmt-node-labels node)
2903 if (string= label (js2-label-node-name nl))
2904 return t
2905 finally return nil))
2906
2907 (defsubst js2-labeled-stmt-node-add-label (node label)
2908 "Add a `js2-label-node' to the label set for this statement."
2909 (setf (js2-labeled-stmt-node-labels node)
2910 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2911
2912 (defstruct (js2-jump-node
2913 (:include js2-node)
2914 (:constructor nil))
2915 "Abstract supertype of break and continue nodes."
2916 label ; `js2-name-node' for location of label identifier, if present
2917 target) ; target js2-labels-node or loop/switch statement
2918
2919 (defun js2-visit-jump-node (n v)
2920 ;; We don't visit the target, since it's a back-link.
2921 (js2-visit-ast (js2-jump-node-label n) v))
2922
2923 (defstruct (js2-break-node
2924 (:include js2-jump-node)
2925 (:constructor nil)
2926 (:constructor make-js2-break-node (&key (type js2-BREAK)
2927 (pos js2-ts-cursor)
2928 len label target)))
2929 "AST node for a break statement.
2930 The label field is a `js2-name-node', possibly nil, for the named label
2931 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2932 is the target of the break - a label node or enclosing loop/switch statement.")
2933
2934 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2935 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2936
2937 (defun js2-print-break-node (n i)
2938 (insert (js2-make-pad i) "break")
2939 (when (js2-break-node-label n)
2940 (insert " ")
2941 (js2-print-ast (js2-break-node-label n) 0))
2942 (insert ";\n"))
2943
2944 (defstruct (js2-continue-node
2945 (:include js2-jump-node)
2946 (:constructor nil)
2947 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2948 (pos js2-ts-cursor)
2949 len label target)))
2950 "AST node for a continue statement.
2951 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2952 It is nil if continue specifies no label. The target field is the jump target:
2953 a `js2-label-node' or the innermost enclosing loop.")
2954
2955 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2956 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2957
2958 (defun js2-print-continue-node (n i)
2959 (insert (js2-make-pad i) "continue")
2960 (when (js2-continue-node-label n)
2961 (insert " ")
2962 (js2-print-ast (js2-continue-node-label n) 0))
2963 (insert ";\n"))
2964
2965 (defstruct (js2-function-node
2966 (:include js2-script-node)
2967 (:constructor nil)
2968 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2969 (pos js2-ts-cursor)
2970 len
2971 (ftype 'FUNCTION)
2972 (form 'FUNCTION_STATEMENT)
2973 (name "")
2974 params rest-p
2975 body
2976 generator-type
2977 lp rp)))
2978 "AST node for a function declaration.
2979 The `params' field is a Lisp list of nodes. Each node is either a simple
2980 `js2-name-node', or if it's a destructuring-assignment parameter, a
2981 `js2-array-node' or `js2-object-node'."
2982 ftype ; FUNCTION, GETTER or SETTER
2983 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
2984 name ; function name (a `js2-name-node', or nil if anonymous)
2985 params ; a Lisp list of destructuring forms or simple name nodes
2986 rest-p ; if t, the last parameter is rest parameter
2987 body ; a `js2-block-node' or expression node (1.8 only)
2988 lp ; position of arg-list open-paren, or nil if omitted
2989 rp ; position of arg-list close-paren, or nil if omitted
2990 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2991 needs-activation ; t if we need an activation object for this frame
2992 generator-type ; STAR, LEGACY, COMPREHENSION or nil
2993 member-expr) ; nonstandard Ecma extension from Rhino
2994
2995 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2996 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2997
2998 (defun js2-visit-function-node (n v)
2999 (js2-visit-ast (js2-function-node-name n) v)
3000 (dolist (p (js2-function-node-params n))
3001 (js2-visit-ast p v))
3002 (js2-visit-ast (js2-function-node-body n) v))
3003
3004 (defun js2-print-function-node (n i)
3005 (let* ((pad (js2-make-pad i))
3006 (getter (js2-node-get-prop n 'GETTER_SETTER))
3007 (name (or (js2-function-node-name n)
3008 (js2-function-node-member-expr n)))
3009 (params (js2-function-node-params n))
3010 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3011 (rest-p (js2-function-node-rest-p n))
3012 (body (js2-function-node-body n))
3013 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3014 (unless (or getter arrow)
3015 (insert pad "function")
3016 (when (eq (js2-function-node-generator-type n) 'STAR)
3017 (insert "*")))
3018 (when name
3019 (insert " ")
3020 (js2-print-ast name 0))
3021 (insert "(")
3022 (loop with len = (length params)
3023 for param in params
3024 for count from 1
3025 do
3026 (when (and rest-p (= count len))
3027 (insert "..."))
3028 (js2-print-ast param 0)
3029 (when (< count len)
3030 (insert ", ")))
3031 (insert ") ")
3032 (when arrow
3033 (insert "=> "))
3034 (insert "{")
3035 ;; TODO: fix this to be smarter about indenting, etc.
3036 (unless expr
3037 (insert "\n"))
3038 (if (js2-block-node-p body)
3039 (js2-print-body body (1+ i))
3040 (js2-print-ast body 0))
3041 (insert pad "}")
3042 (unless expr
3043 (insert "\n"))))
3044
3045 (defun js2-function-name (node)
3046 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3047 (and (js2-function-node-name node)
3048 (js2-name-node-name (js2-function-node-name node))))
3049
3050 ;; Having this be an expression node makes it more flexible.
3051 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3052 ;; that work better if you assume it's an expression. Whenever we have
3053 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3054 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3055 (defstruct (js2-var-decl-node
3056 (:include js2-node)
3057 (:constructor nil)
3058 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3059 (pos (js2-current-token-beg))
3060 len kids
3061 decl-type)))
3062 "AST node for a variable declaration list (VAR, CONST or LET).
3063 The node bounds differ depending on the declaration type. For VAR or
3064 CONST declarations, the bounds include the var/const keyword. For LET
3065 declarations, the node begins at the position of the first child."
3066 kids ; a Lisp list of `js2-var-init-node' structs.
3067 decl-type) ; js2-VAR, js2-CONST or js2-LET
3068
3069 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3070 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3071
3072 (defun js2-visit-var-decl (n v)
3073 (dolist (kid (js2-var-decl-node-kids n))
3074 (js2-visit-ast kid v)))
3075
3076 (defun js2-print-var-decl (n i)
3077 (let ((pad (js2-make-pad i))
3078 (tt (js2-var-decl-node-decl-type n)))
3079 (insert pad)
3080 (insert (cond
3081 ((= tt js2-VAR) "var ")
3082 ((= tt js2-LET) "let ")
3083 ((= tt js2-CONST) "const ")
3084 (t
3085 (error "malformed var-decl node"))))
3086 (loop with kids = (js2-var-decl-node-kids n)
3087 with len = (length kids)
3088 for kid in kids
3089 for count from 1
3090 do
3091 (js2-print-ast kid 0)
3092 (if (< count len)
3093 (insert ", ")))))
3094
3095 (defstruct (js2-var-init-node
3096 (:include js2-node)
3097 (:constructor nil)
3098 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3099 (pos js2-ts-cursor)
3100 len target
3101 initializer)))
3102 "AST node for a variable declaration.
3103 The type field will be js2-CONST for a const decl."
3104 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3105 initializer) ; initializer expression, a `js2-node'
3106
3107 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3108 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3109
3110 (defun js2-visit-var-init-node (n v)
3111 (js2-visit-ast (js2-var-init-node-target n) v)
3112 (js2-visit-ast (js2-var-init-node-initializer n) v))
3113
3114 (defun js2-print-var-init-node (n i)
3115 (let ((pad (js2-make-pad i))
3116 (name (js2-var-init-node-target n))
3117 (init (js2-var-init-node-initializer n)))
3118 (insert pad)
3119 (js2-print-ast name 0)
3120 (when init
3121 (insert " = ")
3122 (js2-print-ast init 0))))
3123
3124 (defstruct (js2-cond-node
3125 (:include js2-node)
3126 (:constructor nil)
3127 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3128 (pos js2-ts-cursor)
3129 len
3130 test-expr
3131 true-expr
3132 false-expr
3133 q-pos c-pos)))
3134 "AST node for the ternary operator"
3135 test-expr
3136 true-expr
3137 false-expr
3138 q-pos ; buffer position of ?
3139 c-pos) ; buffer position of :
3140
3141 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3142 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3143
3144 (defun js2-visit-cond-node (n v)
3145 (js2-visit-ast (js2-cond-node-test-expr n) v)
3146 (js2-visit-ast (js2-cond-node-true-expr n) v)
3147 (js2-visit-ast (js2-cond-node-false-expr n) v))
3148
3149 (defun js2-print-cond-node (n i)
3150 (let ((pad (js2-make-pad i)))
3151 (insert pad)
3152 (js2-print-ast (js2-cond-node-test-expr n) 0)
3153 (insert " ? ")
3154 (js2-print-ast (js2-cond-node-true-expr n) 0)
3155 (insert " : ")
3156 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3157
3158 (defstruct (js2-infix-node
3159 (:include js2-node)
3160 (:constructor nil)
3161 (:constructor make-js2-infix-node (&key type
3162 (pos js2-ts-cursor)
3163 len op-pos
3164 left right)))
3165 "Represents infix expressions.
3166 Includes assignment ops like `|=', and the comma operator.
3167 The type field inherited from `js2-node' holds the operator."
3168 op-pos ; buffer position where operator begins
3169 left ; any `js2-node'
3170 right) ; any `js2-node'
3171
3172 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3173 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3174
3175 (defun js2-visit-infix-node (n v)
3176 (js2-visit-ast (js2-infix-node-left n) v)
3177 (js2-visit-ast (js2-infix-node-right n) v))
3178
3179 (defconst js2-operator-tokens
3180 (let ((table (make-hash-table :test 'eq))
3181 (tokens
3182 (list (cons js2-IN "in")
3183 (cons js2-TYPEOF "typeof")
3184 (cons js2-INSTANCEOF "instanceof")
3185 (cons js2-DELPROP "delete")
3186 (cons js2-COMMA ",")
3187 (cons js2-COLON ":")
3188 (cons js2-OR "||")
3189 (cons js2-AND "&&")
3190 (cons js2-INC "++")
3191 (cons js2-DEC "--")
3192 (cons js2-BITOR "|")
3193 (cons js2-BITXOR "^")
3194 (cons js2-BITAND "&")
3195 (cons js2-EQ "==")
3196 (cons js2-NE "!=")
3197 (cons js2-LT "<")
3198 (cons js2-LE "<=")
3199 (cons js2-GT ">")
3200 (cons js2-GE ">=")
3201 (cons js2-LSH "<<")
3202 (cons js2-RSH ">>")
3203 (cons js2-URSH ">>>")
3204 (cons js2-ADD "+") ; infix plus
3205 (cons js2-SUB "-") ; infix minus
3206 (cons js2-MUL "*")
3207 (cons js2-DIV "/")
3208 (cons js2-MOD "%")
3209 (cons js2-NOT "!")
3210 (cons js2-BITNOT "~")
3211 (cons js2-POS "+") ; unary plus
3212 (cons js2-NEG "-") ; unary minus
3213 (cons js2-TRIPLEDOT "...")
3214 (cons js2-SHEQ "===") ; shallow equality
3215 (cons js2-SHNE "!==") ; shallow inequality
3216 (cons js2-ASSIGN "=")
3217 (cons js2-ASSIGN_BITOR "|=")
3218 (cons js2-ASSIGN_BITXOR "^=")
3219 (cons js2-ASSIGN_BITAND "&=")
3220 (cons js2-ASSIGN_LSH "<<=")
3221 (cons js2-ASSIGN_RSH ">>=")
3222 (cons js2-ASSIGN_URSH ">>>=")
3223 (cons js2-ASSIGN_ADD "+=")
3224 (cons js2-ASSIGN_SUB "-=")
3225 (cons js2-ASSIGN_MUL "*=")
3226 (cons js2-ASSIGN_DIV "/=")
3227 (cons js2-ASSIGN_MOD "%="))))
3228 (loop for (k . v) in tokens do
3229 (puthash k v table))
3230 table))
3231
3232 (defun js2-print-infix-node (n i)
3233 (let* ((tt (js2-node-type n))
3234 (op (gethash tt js2-operator-tokens)))
3235 (unless op
3236 (error "unrecognized infix operator %s" (js2-node-type n)))
3237 (insert (js2-make-pad i))
3238 (js2-print-ast (js2-infix-node-left n) 0)
3239 (unless (= tt js2-COMMA)
3240 (insert " "))
3241 (insert op)
3242 (insert " ")
3243 (js2-print-ast (js2-infix-node-right n) 0)))
3244
3245 (defstruct (js2-assign-node
3246 (:include js2-infix-node)
3247 (:constructor nil)
3248 (:constructor make-js2-assign-node (&key type
3249 (pos js2-ts-cursor)
3250 len op-pos
3251 left right)))
3252 "Represents any assignment.
3253 The type field holds the actual assignment operator.")
3254
3255 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3256 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3257
3258 (defstruct (js2-unary-node
3259 (:include js2-node)
3260 (:constructor nil)
3261 (:constructor make-js2-unary-node (&key type ; required
3262 (pos js2-ts-cursor)
3263 len operand)))
3264 "AST node type for unary operator nodes.
3265 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3266 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3267 property is added if the operator follows the operand."
3268 operand) ; a `js2-node' expression
3269
3270 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3271 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3272
3273 (defun js2-visit-unary-node (n v)
3274 (js2-visit-ast (js2-unary-node-operand n) v))
3275
3276 (defun js2-print-unary-node (n i)
3277 (let* ((tt (js2-node-type n))
3278 (op (gethash tt js2-operator-tokens))
3279 (postfix (js2-node-get-prop n 'postfix)))
3280 (unless op
3281 (error "unrecognized unary operator %s" tt))
3282 (insert (js2-make-pad i))
3283 (unless postfix
3284 (insert op))
3285 (if (or (= tt js2-TYPEOF)
3286 (= tt js2-DELPROP))
3287 (insert " "))
3288 (js2-print-ast (js2-unary-node-operand n) 0)
3289 (when postfix
3290 (insert op))))
3291
3292 (defstruct (js2-let-node
3293 (:include js2-scope)
3294 (:constructor nil)
3295 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3296 (pos (js2-current-token-beg))
3297 len vars body
3298 lp rp)))
3299 "AST node for a let expression or a let statement.
3300 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3301 vars ; a `js2-var-decl-node'
3302 body ; a `js2-node' representing the expression or body block
3303 lp
3304 rp)
3305
3306 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3307 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3308
3309 (defun js2-visit-let-node (n v)
3310 (js2-visit-ast (js2-let-node-vars n) v)
3311 (js2-visit-ast (js2-let-node-body n) v))
3312
3313 (defun js2-print-let-node (n i)
3314 (insert (js2-make-pad i) "let (")
3315 (let ((p (point)))
3316 (js2-print-ast (js2-let-node-vars n) 0)
3317 (delete-region p (+ p 4)))
3318 (insert ") ")
3319 (js2-print-ast (js2-let-node-body n) i))
3320
3321 (defstruct (js2-keyword-node
3322 (:include js2-node)
3323 (:constructor nil)
3324 (:constructor make-js2-keyword-node (&key type
3325 (pos (js2-current-token-beg))
3326 (len (- js2-ts-cursor pos)))))
3327 "AST node representing a literal keyword such as `null'.
3328 Used for `null', `this', `true', `false' and `debugger'.
3329 The node type is set to js2-NULL, js2-THIS, etc.")
3330
3331 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3332 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3333
3334 (defun js2-print-keyword-node (n i)
3335 (insert (js2-make-pad i)
3336 (let ((tt (js2-node-type n)))
3337 (cond
3338 ((= tt js2-THIS) "this")
3339 ((= tt js2-NULL) "null")
3340 ((= tt js2-TRUE) "true")
3341 ((= tt js2-FALSE) "false")
3342 ((= tt js2-DEBUGGER) "debugger")
3343 (t (error "Invalid keyword literal type: %d" tt))))))
3344
3345 (defsubst js2-this-node-p (node)
3346 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3347 (eq (js2-node-type node) js2-THIS))
3348
3349 (defstruct (js2-new-node
3350 (:include js2-node)
3351 (:constructor nil)
3352 (:constructor make-js2-new-node (&key (type js2-NEW)
3353 (pos (js2-current-token-beg))
3354 len target
3355 args initializer
3356 lp rp)))
3357 "AST node for new-expression such as new Foo()."
3358 target ; an identifier or reference
3359 args ; a Lisp list of argument nodes
3360 lp ; position of left-paren, nil if omitted
3361 rp ; position of right-paren, nil if omitted
3362 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3363
3364 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3365 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3366
3367 (defun js2-visit-new-node (n v)
3368 (js2-visit-ast (js2-new-node-target n) v)
3369 (dolist (arg (js2-new-node-args n))
3370 (js2-visit-ast arg v))
3371 (js2-visit-ast (js2-new-node-initializer n) v))
3372
3373 (defun js2-print-new-node (n i)
3374 (insert (js2-make-pad i) "new ")
3375 (js2-print-ast (js2-new-node-target n))
3376 (insert "(")
3377 (js2-print-list (js2-new-node-args n))
3378 (insert ")")
3379 (when (js2-new-node-initializer n)
3380 (insert " ")
3381 (js2-print-ast (js2-new-node-initializer n))))
3382
3383 (defstruct (js2-name-node
3384 (:include js2-node)
3385 (:constructor nil)
3386 (:constructor make-js2-name-node (&key (type js2-NAME)
3387 (pos (js2-current-token-beg))
3388 (len (- js2-ts-cursor
3389 (js2-current-token-beg)))
3390 (name (js2-current-token-string)))))
3391 "AST node for a JavaScript identifier"
3392 name ; a string
3393 scope) ; a `js2-scope' (optional, used for codegen)
3394
3395 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3396 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3397
3398 (defun js2-print-name-node (n i)
3399 (insert (js2-make-pad i)
3400 (js2-name-node-name n)))
3401
3402 (defsubst js2-name-node-length (node)
3403 "Return identifier length of NODE, a `js2-name-node'.
3404 Returns 0 if NODE is nil or its identifier field is nil."
3405 (if node
3406 (length (js2-name-node-name node))
3407 0))
3408
3409 (defstruct (js2-number-node
3410 (:include js2-node)
3411 (:constructor nil)
3412 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3413 (pos (js2-current-token-beg))
3414 (len (- js2-ts-cursor
3415 (js2-current-token-beg)))
3416 (value (js2-current-token-string))
3417 (num-value (js2-token-number
3418 (js2-current-token))))))
3419 "AST node for a number literal."
3420 value ; the original string, e.g. "6.02e23"
3421 num-value) ; the parsed number value
3422
3423 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3424 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3425
3426 (defun js2-print-number-node (n i)
3427 (insert (js2-make-pad i)
3428 (number-to-string (js2-number-node-num-value n))))
3429
3430 (defstruct (js2-regexp-node
3431 (:include js2-node)
3432 (:constructor nil)
3433 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3434 (pos (js2-current-token-beg))
3435 (len (- js2-ts-cursor
3436 (js2-current-token-beg)))
3437 value flags)))
3438 "AST node for a regular expression literal."
3439 value ; the regexp string, without // delimiters
3440 flags) ; a string of flags, e.g. `mi'.
3441
3442 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3443 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3444
3445 (defun js2-print-regexp (n i)
3446 (insert (js2-make-pad i)
3447 "/"
3448 (js2-regexp-node-value n)
3449 "/")
3450 (if (js2-regexp-node-flags n)
3451 (insert (js2-regexp-node-flags n))))
3452
3453 (defstruct (js2-string-node
3454 (:include js2-node)
3455 (:constructor nil)
3456 (:constructor make-js2-string-node (&key (type js2-STRING)
3457 (pos (js2-current-token-beg))
3458 (len (- js2-ts-cursor
3459 (js2-current-token-beg)))
3460 (value (js2-current-token-string)))))
3461 "String literal.
3462 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3463 You can tell the quote type by looking at the first character."
3464 value) ; the characters of the string, including the quotes
3465
3466 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3467 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3468
3469 (defun js2-print-string-node (n i)
3470 (insert (js2-make-pad i)
3471 (js2-node-string n)))
3472
3473 (defstruct (js2-array-node
3474 (:include js2-node)
3475 (:constructor nil)
3476 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3477 (pos js2-ts-cursor)
3478 len elems)))
3479 "AST node for an array literal."
3480 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3481
3482 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3483 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3484
3485 (defun js2-visit-array-node (n v)
3486 (dolist (e (js2-array-node-elems n))
3487 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3488
3489 (defun js2-print-array-node (n i)
3490 (insert (js2-make-pad i) "[")
3491 (let ((elems (js2-array-node-elems n)))
3492 (js2-print-list elems)
3493 (when (and elems (null (car (last elems))))
3494 (insert ",")))
3495 (insert "]"))
3496
3497 (defstruct (js2-object-node
3498 (:include js2-node)
3499 (:constructor nil)
3500 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3501 (pos js2-ts-cursor)
3502 len
3503 elems)))
3504 "AST node for an object literal expression.
3505 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3506 The latter represents abbreviation in destructuring expressions."
3507 elems)
3508
3509 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3510 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3511
3512 (defun js2-visit-object-node (n v)
3513 (dolist (e (js2-object-node-elems n))
3514 (js2-visit-ast e v)))
3515
3516 (defun js2-print-object-node (n i)
3517 (insert (js2-make-pad i) "{")
3518 (js2-print-list (js2-object-node-elems n))
3519 (insert "}"))
3520
3521 (defstruct (js2-object-prop-node
3522 (:include js2-infix-node)
3523 (:constructor nil)
3524 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3525 (pos js2-ts-cursor)
3526 len left
3527 right op-pos)))
3528 "AST node for an object literal prop:value entry.
3529 The `left' field is the property: a name node, string node or number node.
3530 The `right' field is a `js2-node' representing the initializer value.")
3531
3532 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3533 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3534
3535 (defun js2-print-object-prop-node (n i)
3536 (let* ((left (js2-object-prop-node-left n))
3537 (computed (not (or (js2-string-node-p left)
3538 (js2-number-node-p left)
3539 (js2-name-node-p left)))))
3540 (insert (js2-make-pad i))
3541 (if computed
3542 (insert "["))
3543 (js2-print-ast left 0)
3544 (if computed
3545 (insert "]"))
3546 (if (not (js2-node-get-prop n 'SHORTHAND))
3547 (progn
3548 (insert ": ")
3549 (js2-print-ast (js2-object-prop-node-right n) 0)))))
3550
3551 (defstruct (js2-getter-setter-node
3552 (:include js2-infix-node)
3553 (:constructor nil)
3554 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3555 (pos js2-ts-cursor)
3556 len left right)))
3557 "AST node for a getter/setter property in an object literal.
3558 The `left' field is the `js2-name-node' naming the getter/setter prop.
3559 The `right' field is always an anonymous `js2-function-node' with a node
3560 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3561
3562 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3563 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3564
3565 (defun js2-print-getter-setter (n i)
3566 (let ((pad (js2-make-pad i))
3567 (left (js2-getter-setter-node-left n))
3568 (right (js2-getter-setter-node-right n)))
3569 (insert pad)
3570 (if (/= (js2-node-type n) js2-FUNCTION)
3571 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3572 (js2-print-ast left 0)
3573 (js2-print-ast right 0)))
3574
3575 (defstruct (js2-prop-get-node
3576 (:include js2-infix-node)
3577 (:constructor nil)
3578 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3579 (pos js2-ts-cursor)
3580 len left right)))
3581 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3582
3583 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3584 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3585
3586 (defun js2-visit-prop-get-node (n v)
3587 (js2-visit-ast (js2-prop-get-node-left n) v)
3588 (js2-visit-ast (js2-prop-get-node-right n) v))
3589
3590 (defun js2-print-prop-get-node (n i)
3591 (insert (js2-make-pad i))
3592 (js2-print-ast (js2-prop-get-node-left n) 0)
3593 (insert ".")
3594 (js2-print-ast (js2-prop-get-node-right n) 0))
3595
3596 (defstruct (js2-elem-get-node
3597 (:include js2-node)
3598 (:constructor nil)
3599 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3600 (pos js2-ts-cursor)
3601 len target element
3602 lb rb)))
3603 "AST node for an array index expression such as foo[bar]."
3604 target ; a `js2-node' - the expression preceding the "."
3605 element ; a `js2-node' - the expression in brackets
3606 lb ; position of left-bracket, nil if omitted
3607 rb) ; position of right-bracket, nil if omitted
3608
3609 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3610 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3611
3612 (defun js2-visit-elem-get-node (n v)
3613 (js2-visit-ast (js2-elem-get-node-target n) v)
3614 (js2-visit-ast (js2-elem-get-node-element n) v))
3615
3616 (defun js2-print-elem-get-node (n i)
3617 (insert (js2-make-pad i))
3618 (js2-print-ast (js2-elem-get-node-target n) 0)
3619 (insert "[")
3620 (js2-print-ast (js2-elem-get-node-element n) 0)
3621 (insert "]"))
3622
3623 (defstruct (js2-call-node
3624 (:include js2-node)
3625 (:constructor nil)
3626 (:constructor make-js2-call-node (&key (type js2-CALL)
3627 (pos js2-ts-cursor)
3628 len target args
3629 lp rp)))
3630 "AST node for a JavaScript function call."
3631 target ; a `js2-node' evaluating to the function to call
3632 args ; a Lisp list of `js2-node' arguments
3633 lp ; position of open-paren, or nil if missing
3634 rp) ; position of close-paren, or nil if missing
3635
3636 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3637 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3638
3639 (defun js2-visit-call-node (n v)
3640 (js2-visit-ast (js2-call-node-target n) v)
3641 (dolist (arg (js2-call-node-args n))
3642 (js2-visit-ast arg v)))
3643
3644 (defun js2-print-call-node (n i)
3645 (insert (js2-make-pad i))
3646 (js2-print-ast (js2-call-node-target n) 0)
3647 (insert "(")
3648 (js2-print-list (js2-call-node-args n))
3649 (insert ")"))
3650
3651 (defstruct (js2-yield-node
3652 (:include js2-node)
3653 (:constructor nil)
3654 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3655 (pos js2-ts-cursor)
3656 len value star-p)))
3657 "AST node for yield statement or expression."
3658 star-p ; whether it's yield*
3659 value) ; optional: value to be yielded
3660
3661 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3662 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3663
3664 (defun js2-visit-yield-node (n v)
3665 (js2-visit-ast (js2-yield-node-value n) v))
3666
3667 (defun js2-print-yield-node (n i)
3668 (insert (js2-make-pad i))
3669 (insert "yield")
3670 (when (js2-yield-node-star-p n)
3671 (insert "*"))
3672 (when (js2-yield-node-value n)
3673 (insert " ")
3674 (js2-print-ast (js2-yield-node-value n) 0)))
3675
3676 (defstruct (js2-paren-node
3677 (:include js2-node)
3678 (:constructor nil)
3679 (:constructor make-js2-paren-node (&key (type js2-LP)
3680 (pos js2-ts-cursor)
3681 len expr)))
3682 "AST node for a parenthesized expression.
3683 In particular, used when the parens are syntactically optional,
3684 as opposed to required parens such as those enclosing an if-conditional."
3685 expr) ; `js2-node'
3686
3687 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3688 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3689
3690 (defun js2-visit-paren-node (n v)
3691 (js2-visit-ast (js2-paren-node-expr n) v))
3692
3693 (defun js2-print-paren-node (n i)
3694 (insert (js2-make-pad i))
3695 (insert "(")
3696 (js2-print-ast (js2-paren-node-expr n) 0)
3697 (insert ")"))
3698
3699 (defstruct (js2-comp-node
3700 (:include js2-scope)
3701 (:constructor nil)
3702 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
3703 (pos js2-ts-cursor)
3704 len result
3705 loops filters
3706 form)))
3707 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3708 result ; result expression (just after left-bracket)
3709 loops ; a Lisp list of `js2-comp-loop-node'
3710 filters ; a Lisp list of guard/filter expressions
3711 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
3712 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
3713 )
3714
3715 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
3716 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
3717
3718 (defun js2-visit-comp-node (n v)
3719 (js2-visit-ast (js2-comp-node-result n) v)
3720 (dolist (l (js2-comp-node-loops n))
3721 (js2-visit-ast l v))
3722 (dolist (f (js2-comp-node-filters n))
3723 (js2-visit-ast f v)))
3724
3725 (defun js2-print-comp-node (n i)
3726 (let ((pad (js2-make-pad i))
3727 (result (js2-comp-node-result n))
3728 (loops (js2-comp-node-loops n))
3729 (filters (js2-comp-node-filters n))
3730 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
3731 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
3732 (insert pad (if gen-p "(" "["))
3733 (when legacy-p
3734 (js2-print-ast result 0))
3735 (dolist (l loops)
3736 (when legacy-p
3737 (insert " "))
3738 (js2-print-ast l 0)
3739 (unless legacy-p
3740 (insert " ")))
3741 (dolist (f filters)
3742 (when legacy-p
3743 (insert " "))
3744 (insert "if (")
3745 (js2-print-ast f 0)
3746 (insert ")")
3747 (unless legacy-p
3748 (insert " ")))
3749 (unless legacy-p
3750 (js2-print-ast result 0))
3751 (insert (if gen-p ")" "]"))))
3752
3753 (defstruct (js2-comp-loop-node
3754 (:include js2-for-in-node)
3755 (:constructor nil)
3756 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
3757 (pos js2-ts-cursor)
3758 len iterator
3759 object in-pos
3760 foreach-p
3761 each-pos
3762 forof-p
3763 lp rp)))
3764 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3765
3766 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
3767 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
3768
3769 (defun js2-visit-comp-loop (n v)
3770 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
3771 (js2-visit-ast (js2-comp-loop-node-object n) v))
3772
3773 (defun js2-print-comp-loop (n _i)
3774 (insert "for ")
3775 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
3776 (insert "(")
3777 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
3778 (insert (if (js2-comp-loop-node-forof-p n)
3779 " of " " in "))
3780 (js2-print-ast (js2-comp-loop-node-object n) 0)
3781 (insert ")"))
3782
3783 (defstruct (js2-empty-expr-node
3784 (:include js2-node)
3785 (:constructor nil)
3786 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3787 (pos (js2-current-token-beg))
3788 len)))
3789 "AST node for an empty expression.")
3790
3791 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3792 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3793
3794 (defstruct (js2-xml-node
3795 (:include js2-block-node)
3796 (:constructor nil)
3797 (:constructor make-js2-xml-node (&key (type js2-XML)
3798 (pos (js2-current-token-beg))
3799 len kids)))
3800 "AST node for initial parse of E4X literals.
3801 The kids field is a list of XML fragments, each a `js2-string-node' or
3802 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3803
3804 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3805 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3806
3807 (defun js2-print-xml-node (n i)
3808 (dolist (kid (js2-xml-node-kids n))
3809 (js2-print-ast kid i)))
3810
3811 (defstruct (js2-xml-js-expr-node
3812 (:include js2-xml-node)
3813 (:constructor nil)
3814 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3815 (pos js2-ts-cursor)
3816 len expr)))
3817 "AST node for an embedded JavaScript {expression} in an E4X literal.
3818 The start and end fields correspond to the curly-braces."
3819 expr) ; a `js2-expr-node' of some sort
3820
3821 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3822 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3823
3824 (defun js2-visit-xml-js-expr (n v)
3825 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3826
3827 (defun js2-print-xml-js-expr (n i)
3828 (insert (js2-make-pad i))
3829 (insert "{")
3830 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3831 (insert "}"))
3832
3833 (defstruct (js2-xml-dot-query-node
3834 (:include js2-infix-node)
3835 (:constructor nil)
3836 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3837 (pos js2-ts-cursor)
3838 op-pos len left
3839 right rp)))
3840 "AST node for an E4X foo.(bar) filter expression.
3841 Note that the left-paren is automatically the character immediately
3842 following the dot (.) in the operator. No whitespace is permitted
3843 between the dot and the lp by the scanner."
3844 rp)
3845
3846 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3847 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3848
3849 (defun js2-print-xml-dot-query (n i)
3850 (insert (js2-make-pad i))
3851 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3852 (insert ".(")
3853 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3854 (insert ")"))
3855
3856 (defstruct (js2-xml-ref-node
3857 (:include js2-node)
3858 (:constructor nil)) ; abstract
3859 "Base type for E4X XML attribute-access or property-get expressions.
3860 Such expressions can take a variety of forms. The general syntax has
3861 three parts:
3862
3863 - (optional) an @ (specifying an attribute access)
3864 - (optional) a namespace (a `js2-name-node') and double-colon
3865 - (required) either a `js2-name-node' or a bracketed [expression]
3866
3867 The property-name expressions (examples: ns::name, @name) are
3868 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3869 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3870
3871 This node type (or more specifically, its subclasses) will sometimes
3872 be the right-hand child of a `js2-prop-get-node' or a
3873 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3874 The `js2-xml-ref-node' may also be a standalone primary expression with
3875 no explicit target, which is valid in certain expression contexts such as
3876
3877 company..employee.(@id < 100)
3878
3879 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3880 expression whose parent is a `js2-xml-dot-query-node'."
3881 namespace
3882 at-pos
3883 colon-pos)
3884
3885 (defsubst js2-xml-ref-node-attr-access-p (node)
3886 "Return non-nil if this expression began with an @-token."
3887 (and (numberp (js2-xml-ref-node-at-pos node))
3888 (plusp (js2-xml-ref-node-at-pos node))))
3889
3890 (defstruct (js2-xml-prop-ref-node
3891 (:include js2-xml-ref-node)
3892 (:constructor nil)
3893 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3894 (pos (js2-current-token-beg))
3895 len propname
3896 namespace at-pos
3897 colon-pos)))
3898 "AST node for an E4X XML [expr] property-ref expression.
3899 The JavaScript syntax is an optional @, an optional ns::, and a name.
3900
3901 [ '@' ] [ name '::' ] name
3902
3903 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3904 @ns::*, @*::attr, @*::*, and @*.
3905
3906 The node starts at the @ token, if present. Otherwise it starts at the
3907 namespace name. The node bounds extend through the closing right-bracket,
3908 or if it is missing due to a syntax error, through the end of the index
3909 expression."
3910 propname)
3911
3912 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3913 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3914
3915 (defun js2-visit-xml-prop-ref-node (n v)
3916 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3917 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3918
3919 (defun js2-print-xml-prop-ref-node (n i)
3920 (insert (js2-make-pad i))
3921 (if (js2-xml-ref-node-attr-access-p n)
3922 (insert "@"))
3923 (when (js2-xml-prop-ref-node-namespace n)
3924 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3925 (insert "::"))
3926 (if (js2-xml-prop-ref-node-propname n)
3927 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3928
3929 (defstruct (js2-xml-elem-ref-node
3930 (:include js2-xml-ref-node)
3931 (:constructor nil)
3932 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3933 (pos (js2-current-token-beg))
3934 len expr lb rb
3935 namespace at-pos
3936 colon-pos)))
3937 "AST node for an E4X XML [expr] member-ref expression.
3938 Syntax:
3939
3940 [ '@' ] [ name '::' ] '[' expr ']'
3941
3942 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3943
3944 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3945 is not a legal E4X XML element-ref expression, since it's already used
3946 for standard JavaScript element-get array indexing. Hence, a
3947 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3948 non-nil namespace node, or both.
3949
3950 The node starts at the @ token, if present. Otherwise it starts
3951 at the namespace name. The node bounds extend through the closing
3952 right-bracket, or if it is missing due to a syntax error, through the
3953 end of the index expression."
3954 expr ; the bracketed index expression
3955 lb
3956 rb)
3957
3958 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3959 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3960
3961 (defun js2-visit-xml-elem-ref-node (n v)
3962 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3963 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3964
3965 (defun js2-print-xml-elem-ref-node (n i)
3966 (insert (js2-make-pad i))
3967 (if (js2-xml-ref-node-attr-access-p n)
3968 (insert "@"))
3969 (when (js2-xml-elem-ref-node-namespace n)
3970 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3971 (insert "::"))
3972 (insert "[")
3973 (if (js2-xml-elem-ref-node-expr n)
3974 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3975 (insert "]"))
3976
3977 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3978
3979 (defstruct (js2-xml-start-tag-node
3980 (:include js2-xml-node)
3981 (:constructor nil)
3982 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3983 (pos js2-ts-cursor)
3984 len name attrs kids
3985 empty-p)))
3986 "AST node for an XML start-tag. Not currently used.
3987 The `kids' field is a Lisp list of child content nodes."
3988 name ; a `js2-xml-name-node'
3989 attrs ; a Lisp list of `js2-xml-attr-node'
3990 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3991
3992 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3993 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3994
3995 (defun js2-visit-xml-start-tag (n v)
3996 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3997 (dolist (attr (js2-xml-start-tag-node-attrs n))
3998 (js2-visit-ast attr v))
3999 (js2-visit-block n v))
4000
4001 (defun js2-print-xml-start-tag (n i)
4002 (insert (js2-make-pad i) "<")
4003 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4004 (when (js2-xml-start-tag-node-attrs n)
4005 (insert " ")
4006 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4007 (insert ">"))
4008
4009 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4010 ;; and add the end-tag to the kids list of the parent as well.
4011 (defstruct (js2-xml-end-tag-node
4012 (:include js2-xml-node)
4013 (:constructor nil)
4014 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4015 (pos js2-ts-cursor)
4016 len name)))
4017 "AST node for an XML end-tag. Not currently used."
4018 name) ; a `js2-xml-name-node'
4019
4020 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4021 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4022
4023 (defun js2-visit-xml-end-tag (n v)
4024 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4025
4026 (defun js2-print-xml-end-tag (n i)
4027 (insert (js2-make-pad i))
4028 (insert "</")
4029 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4030 (insert ">"))
4031
4032 (defstruct (js2-xml-name-node
4033 (:include js2-xml-node)
4034 (:constructor nil)
4035 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4036 (pos js2-ts-cursor)
4037 len namespace kids)))
4038 "AST node for an E4X XML name. Not currently used.
4039 Any XML name can be qualified with a namespace, hence the namespace field.
4040 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4041 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4042 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4043 namespace) ; a `js2-string-node'
4044
4045 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4046 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4047
4048 (defun js2-visit-xml-name-node (n v)
4049 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4050
4051 (defun js2-print-xml-name-node (n i)
4052 (insert (js2-make-pad i))
4053 (when (js2-xml-name-node-namespace n)
4054 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4055 (insert "::"))
4056 (dolist (kid (js2-xml-name-node-kids n))
4057 (js2-print-ast kid 0)))
4058
4059 (defstruct (js2-xml-pi-node
4060 (:include js2-xml-node)
4061 (:constructor nil)
4062 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4063 (pos js2-ts-cursor)
4064 len name attrs)))
4065 "AST node for an E4X XML processing instruction. Not currently used."
4066 name ; a `js2-xml-name-node'
4067 attrs) ; a list of `js2-xml-attr-node'
4068
4069 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4070 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4071
4072 (defun js2-visit-xml-pi-node (n v)
4073 (js2-visit-ast (js2-xml-pi-node-name n) v)
4074 (dolist (attr (js2-xml-pi-node-attrs n))
4075 (js2-visit-ast attr v)))
4076
4077 (defun js2-print-xml-pi-node (n i)
4078 (insert (js2-make-pad i) "<?")
4079 (js2-print-ast (js2-xml-pi-node-name n))
4080 (when (js2-xml-pi-node-attrs n)
4081 (insert " ")
4082 (js2-print-list (js2-xml-pi-node-attrs n)))
4083 (insert "?>"))
4084
4085 (defstruct (js2-xml-cdata-node
4086 (:include js2-xml-node)
4087 (:constructor nil)
4088 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4089 (pos js2-ts-cursor)
4090 len content)))
4091 "AST node for a CDATA escape section. Not currently used."
4092 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4093
4094 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4095 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4096
4097 (defun js2-visit-xml-cdata-node (n v)
4098 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4099
4100 (defun js2-print-xml-cdata-node (n i)
4101 (insert (js2-make-pad i))
4102 (js2-print-ast (js2-xml-cdata-node-content n)))
4103
4104 (defstruct (js2-xml-attr-node
4105 (:include js2-xml-node)
4106 (:constructor nil)
4107 (:constructor make-js2-attr-node (&key (type js2-XML)
4108 (pos js2-ts-cursor)
4109 len name value
4110 eq-pos quote-type)))
4111 "AST node representing a foo='bar' XML attribute value. Not yet used."
4112 name ; a `js2-xml-name-node'
4113 value ; a `js2-xml-name-node'
4114 eq-pos ; buffer position of "=" sign
4115 quote-type) ; 'single or 'double
4116
4117 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4118 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4119
4120 (defun js2-visit-xml-attr-node (n v)
4121 (js2-visit-ast (js2-xml-attr-node-name n) v)
4122 (js2-visit-ast (js2-xml-attr-node-value n) v))
4123
4124 (defun js2-print-xml-attr-node (n i)
4125 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4126 "'"
4127 "\"")))
4128 (insert (js2-make-pad i))
4129 (js2-print-ast (js2-xml-attr-node-name n) 0)
4130 (insert "=" quote)
4131 (js2-print-ast (js2-xml-attr-node-value n) 0)
4132 (insert quote)))
4133
4134 (defstruct (js2-xml-text-node
4135 (:include js2-xml-node)
4136 (:constructor nil)
4137 (:constructor make-js2-text-node (&key (type js2-XML)
4138 (pos js2-ts-cursor)
4139 len content)))
4140 "AST node for an E4X XML text node. Not currently used."
4141 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4142
4143 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4144 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4145
4146 (defun js2-visit-xml-text-node (n v)
4147 (js2-visit-ast (js2-xml-text-node-content n) v))
4148
4149 (defun js2-print-xml-text-node (n i)
4150 (insert (js2-make-pad i))
4151 (dolist (kid (js2-xml-text-node-content n))
4152 (js2-print-ast kid)))
4153
4154 (defstruct (js2-xml-comment-node
4155 (:include js2-xml-node)
4156 (:constructor nil)
4157 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4158 (pos js2-ts-cursor)
4159 len)))
4160 "AST node for E4X XML comment. Not currently used.")
4161
4162 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4163 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4164
4165 (defun js2-print-xml-comment (n i)
4166 (insert (js2-make-pad i)
4167 (js2-node-string n)))
4168
4169 ;;; Node utilities
4170
4171 (defsubst js2-node-line (n)
4172 "Fetch the source line number at the start of node N.
4173 This is O(n) in the length of the source buffer; use prudently."
4174 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4175
4176 (defsubst js2-block-node-kid (n i)
4177 "Return child I of node N, or nil if there aren't that many."
4178 (nth i (js2-block-node-kids n)))
4179
4180 (defsubst js2-block-node-first (n)
4181 "Return first child of block node N, or nil if there is none."
4182 (first (js2-block-node-kids n)))
4183
4184 (defun js2-node-root (n)
4185 "Return the root of the AST containing N.
4186 If N has no parent pointer, returns N."
4187 (let ((parent (js2-node-parent n)))
4188 (if parent
4189 (js2-node-root parent)
4190 n)))
4191
4192 (defsubst js2-node-short-name (n)
4193 "Return the short name of node N as a string, e.g. `js2-if-node'."
4194 (substring (symbol-name (aref n 0))
4195 (length "cl-struct-")))
4196
4197 (defun js2-node-child-list (node)
4198 "Return the child list for NODE, a Lisp list of nodes.
4199 Works for block nodes, array nodes, obj literals, funarg lists,
4200 var decls and try nodes (for catch clauses). Note that you should call
4201 `js2-block-node-kids' on the function body for the body statements.
4202 Returns nil for zero-length child lists or unsupported nodes."
4203 (cond
4204 ((js2-function-node-p node)
4205 (js2-function-node-params node))
4206 ((js2-block-node-p node)
4207 (js2-block-node-kids node))
4208 ((js2-try-node-p node)
4209 (js2-try-node-catch-clauses node))
4210 ((js2-array-node-p node)
4211 (js2-array-node-elems node))
4212 ((js2-object-node-p node)
4213 (js2-object-node-elems node))
4214 ((js2-call-node-p node)
4215 (js2-call-node-args node))
4216 ((js2-new-node-p node)
4217 (js2-new-node-args node))
4218 ((js2-var-decl-node-p node)
4219 (js2-var-decl-node-kids node))
4220 (t
4221 nil)))
4222
4223 (defun js2-node-set-child-list (node kids)
4224 "Set the child list for NODE to KIDS."
4225 (cond
4226 ((js2-function-node-p node)
4227 (setf (js2-function-node-params node) kids))
4228 ((js2-block-node-p node)
4229 (setf (js2-block-node-kids node) kids))
4230 ((js2-try-node-p node)
4231 (setf (js2-try-node-catch-clauses node) kids))
4232 ((js2-array-node-p node)
4233 (setf (js2-array-node-elems node) kids))
4234 ((js2-object-node-p node)
4235 (setf (js2-object-node-elems node) kids))
4236 ((js2-call-node-p node)
4237 (setf (js2-call-node-args node) kids))
4238 ((js2-new-node-p node)
4239 (setf (js2-new-node-args node) kids))
4240 ((js2-var-decl-node-p node)
4241 (setf (js2-var-decl-node-kids node) kids))
4242 (t
4243 (error "Unsupported node type: %s" (js2-node-short-name node))))
4244 kids)
4245
4246 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4247 (defconst js2-paren-expr-nodes
4248 '(cl-struct-js2-comp-loop-node
4249 cl-struct-js2-comp-node
4250 cl-struct-js2-call-node
4251 cl-struct-js2-catch-node
4252 cl-struct-js2-do-node
4253 cl-struct-js2-elem-get-node
4254 cl-struct-js2-for-in-node
4255 cl-struct-js2-for-node
4256 cl-struct-js2-function-node
4257 cl-struct-js2-if-node
4258 cl-struct-js2-let-node
4259 cl-struct-js2-new-node
4260 cl-struct-js2-paren-node
4261 cl-struct-js2-switch-node
4262 cl-struct-js2-while-node
4263 cl-struct-js2-with-node
4264 cl-struct-js2-xml-dot-query-node)
4265 "Node types that can have a parenthesized child expression.
4266 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4267
4268 (defsubst js2-paren-expr-node-p (node)
4269 "Return t for nodes that typically have a parenthesized child expression.
4270 Useful for computing the indentation anchors for arg-lists and conditions.
4271 Note that it may return a false positive, for instance when NODE is
4272 a `js2-new-node' and there are no arguments or parentheses."
4273 (memq (aref node 0) js2-paren-expr-nodes))
4274
4275 ;; Fake polymorphism... yech.
4276 (defun js2-node-lp (node)
4277 "Return relative left-paren position for NODE, if applicable.
4278 For `js2-elem-get-node' structs, returns left-bracket position.
4279 Note that the position may be nil in the case of a parse error."
4280 (cond
4281 ((js2-elem-get-node-p node)
4282 (js2-elem-get-node-lb node))
4283 ((js2-loop-node-p node)
4284 (js2-loop-node-lp node))
4285 ((js2-function-node-p node)
4286 (js2-function-node-lp node))
4287 ((js2-if-node-p node)
4288 (js2-if-node-lp node))
4289 ((js2-new-node-p node)
4290 (js2-new-node-lp node))
4291 ((js2-call-node-p node)
4292 (js2-call-node-lp node))
4293 ((js2-paren-node-p node)
4294 0)
4295 ((js2-switch-node-p node)
4296 (js2-switch-node-lp node))
4297 ((js2-catch-node-p node)
4298 (js2-catch-node-lp node))
4299 ((js2-let-node-p node)
4300 (js2-let-node-lp node))
4301 ((js2-comp-node-p node)
4302 0)
4303 ((js2-with-node-p node)
4304 (js2-with-node-lp node))
4305 ((js2-xml-dot-query-node-p node)
4306 (1+ (js2-infix-node-op-pos node)))
4307 (t
4308 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4309
4310 ;; Fake polymorphism... blech.
4311 (defun js2-node-rp (node)
4312 "Return relative right-paren position for NODE, if applicable.
4313 For `js2-elem-get-node' structs, returns right-bracket position.
4314 Note that the position may be nil in the case of a parse error."
4315 (cond
4316 ((js2-elem-get-node-p node)
4317 (js2-elem-get-node-rb node))
4318 ((js2-loop-node-p node)
4319 (js2-loop-node-rp node))
4320 ((js2-function-node-p node)
4321 (js2-function-node-rp node))
4322 ((js2-if-node-p node)
4323 (js2-if-node-rp node))
4324 ((js2-new-node-p node)
4325 (js2-new-node-rp node))
4326 ((js2-call-node-p node)
4327 (js2-call-node-rp node))
4328 ((js2-paren-node-p node)
4329 (1- (js2-node-len node)))
4330 ((js2-switch-node-p node)
4331 (js2-switch-node-rp node))
4332 ((js2-catch-node-p node)
4333 (js2-catch-node-rp node))
4334 ((js2-let-node-p node)
4335 (js2-let-node-rp node))
4336 ((js2-comp-node-p node)
4337 (1- (js2-node-len node)))
4338 ((js2-with-node-p node)
4339 (js2-with-node-rp node))
4340 ((js2-xml-dot-query-node-p node)
4341 (1+ (js2-xml-dot-query-node-rp node)))
4342 (t
4343 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4344
4345 (defsubst js2-node-first-child (node)
4346 "Return the first element of `js2-node-child-list' for NODE."
4347 (car (js2-node-child-list node)))
4348
4349 (defsubst js2-node-last-child (node)
4350 "Return the last element of `js2-node-last-child' for NODE."
4351 (car (last (js2-node-child-list node))))
4352
4353 (defun js2-node-prev-sibling (node)
4354 "Return the previous statement in parent.
4355 Works for parents supported by `js2-node-child-list'.
4356 Returns nil if NODE is not in the parent, or PARENT is
4357 not a supported node, or if NODE is the first child."
4358 (let* ((p (js2-node-parent node))
4359 (kids (js2-node-child-list p))
4360 (sib (car kids)))
4361 (while (and kids
4362 (not (eq node (cadr kids))))
4363 (setq kids (cdr kids)
4364 sib (car kids)))
4365 sib))
4366
4367 (defun js2-node-next-sibling (node)
4368 "Return the next statement in parent block.
4369 Returns nil if NODE is not in the block, or PARENT is not
4370 a block node, or if NODE is the last statement."
4371 (let* ((p (js2-node-parent node))
4372 (kids (js2-node-child-list p)))
4373 (while (and kids
4374 (not (eq node (car kids))))
4375 (setq kids (cdr kids)))
4376 (cadr kids)))
4377
4378 (defun js2-node-find-child-before (pos parent &optional after)
4379 "Find the last child that starts before POS in parent.
4380 If AFTER is non-nil, returns first child starting after POS.
4381 POS is an absolute buffer position. PARENT is any node
4382 supported by `js2-node-child-list'.
4383 Returns nil if no applicable child is found."
4384 (let ((kids (if (js2-function-node-p parent)
4385 (js2-block-node-kids (js2-function-node-body parent))
4386 (js2-node-child-list parent)))
4387 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4388 (js2-function-node-body parent)
4389 parent)))
4390 kid result fn
4391 (continue t))
4392 (setq fn (if after '>= '<))
4393 (while (and kids continue)
4394 (setq kid (car kids))
4395 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4396 (setq result kid
4397 continue (not after))
4398 (setq continue after))
4399 (setq kids (cdr kids)))
4400 result))
4401
4402 (defun js2-node-find-child-after (pos parent)
4403 "Find first child that starts after POS in parent.
4404 POS is an absolute buffer position. PARENT is any node
4405 supported by `js2-node-child-list'.
4406 Returns nil if no applicable child is found."
4407 (js2-node-find-child-before pos parent 'after))
4408
4409 (defun js2-node-replace-child (pos parent new-node)
4410 "Replace node at index POS in PARENT with NEW-NODE.
4411 Only works for parents supported by `js2-node-child-list'."
4412 (let ((kids (js2-node-child-list parent))
4413 (i 0))
4414 (while (< i pos)
4415 (setq kids (cdr kids)
4416 i (1+ i)))
4417 (setcar kids new-node)
4418 (js2-node-add-children parent new-node)))
4419
4420 (defun js2-node-buffer (n)
4421 "Return the buffer associated with AST N.
4422 Returns nil if the buffer is not set as a property on the root
4423 node, or if parent links were not recorded during parsing."
4424 (let ((root (js2-node-root n)))
4425 (and root
4426 (js2-ast-root-p root)
4427 (js2-ast-root-buffer root))))
4428
4429 (defun js2-block-node-push (n kid)
4430 "Push js2-node KID onto the end of js2-block-node N's child list.
4431 KID is always added to the -end- of the kids list.
4432 Function also calls `js2-node-add-children' to add the parent link."
4433 (let ((kids (js2-node-child-list n)))
4434 (if kids
4435 (setcdr kids (nconc (cdr kids) (list kid)))
4436 (js2-node-set-child-list n (list kid)))
4437 (js2-node-add-children n kid)))
4438
4439 (defun js2-node-string (node)
4440 (with-current-buffer (or (js2-node-buffer node)
4441 (error "No buffer available for node %s" node))
4442 (let ((pos (js2-node-abs-pos node)))
4443 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4444
4445 ;; Container for storing the node we're looking for in a traversal.
4446 (js2-deflocal js2-discovered-node nil)
4447
4448 ;; Keep track of absolute node position during traversals.
4449 (js2-deflocal js2-visitor-offset nil)
4450
4451 (js2-deflocal js2-node-search-point nil)
4452
4453 (when js2-mode-dev-mode-p
4454 (defun js2-find-node-at-point ()
4455 (interactive)
4456 (let ((node (js2-node-at-point)))
4457 (message "%s" (or node "No node found at point"))))
4458 (defun js2-node-name-at-point ()
4459 (interactive)
4460 (let ((node (js2-node-at-point)))
4461 (message "%s" (if node
4462 (js2-node-short-name node)
4463 "No node found at point.")))))
4464
4465 (defun js2-node-at-point (&optional pos skip-comments)
4466 "Return AST node at POS, a buffer position, defaulting to current point.
4467 The `js2-mode-ast' variable must be set to the current parse tree.
4468 Signals an error if the AST (`js2-mode-ast') is nil.
4469 Always returns a node - if it can't find one, it returns the root.
4470 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4471 (let ((ast js2-mode-ast)
4472 result)
4473 (unless ast
4474 (error "No JavaScript AST available"))
4475 ;; Look through comments first, since they may be inside nodes that
4476 ;; would otherwise report a match.
4477 (setq pos (or pos (point))
4478 result (if (> pos (js2-node-abs-end ast))
4479 ast
4480 (if (not skip-comments)
4481 (js2-comment-at-point pos))))
4482 (unless result
4483 (setq js2-discovered-node nil
4484 js2-visitor-offset 0
4485 js2-node-search-point pos)
4486 (unwind-protect
4487 (catch 'js2-visit-done
4488 (js2-visit-ast ast #'js2-node-at-point-visitor))
4489 (setq js2-visitor-offset nil
4490 js2-node-search-point nil))
4491 (setq result js2-discovered-node))
4492 ;; may have found a comment beyond end of last child node,
4493 ;; since visiting the ast-root looks at the comment-list last.
4494 (if (and skip-comments
4495 (js2-comment-node-p result))
4496 (setq result nil))
4497 (or result js2-mode-ast)))
4498
4499 (defun js2-node-at-point-visitor (node end-p)
4500 (let ((rel-pos (js2-node-pos node))
4501 abs-pos
4502 abs-end
4503 (point js2-node-search-point))
4504 (cond
4505 (end-p
4506 ;; this evaluates to a non-nil return value, even if it's zero
4507 (decf js2-visitor-offset rel-pos))
4508 ;; we already looked for comments before visiting, and don't want them now
4509 ((js2-comment-node-p node)
4510 nil)
4511 (t
4512 (setq abs-pos (incf js2-visitor-offset rel-pos)
4513 ;; we only want to use the node if the point is before
4514 ;; the last character position in the node, so we decrement
4515 ;; the absolute end by 1.
4516 abs-end (+ abs-pos (js2-node-len node) -1))
4517 (cond
4518 ;; If this node starts after search-point, stop the search.
4519 ((> abs-pos point)
4520 (throw 'js2-visit-done nil))
4521 ;; If this node ends before the search-point, don't check kids.
4522 ((> point abs-end)
4523 nil)
4524 (t
4525 ;; Otherwise point is within this node, possibly in a child.
4526 (setq js2-discovered-node node)
4527 t)))))) ; keep processing kids to look for more specific match
4528
4529 (defsubst js2-block-comment-p (node)
4530 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4531 (and (js2-comment-node-p node)
4532 (memq (js2-comment-node-format node) '(jsdoc block))))
4533
4534 ;; TODO: put the comments in a vector and binary-search them instead
4535 (defun js2-comment-at-point (&optional pos)
4536 "Look through scanned comment nodes for one containing POS.
4537 POS is a buffer position that defaults to current point.
4538 Function returns nil if POS was not in any comment node."
4539 (let ((ast js2-mode-ast)
4540 (x (or pos (point)))
4541 beg end)
4542 (unless ast
4543 (error "No JavaScript AST available"))
4544 (catch 'done
4545 ;; Comments are stored in lexical order.
4546 (dolist (comment (js2-ast-root-comments ast) nil)
4547 (setq beg (js2-node-abs-pos comment)
4548 end (+ beg (js2-node-len comment)))
4549 (if (and (>= x beg)
4550 (<= x end))
4551 (throw 'done comment))))))
4552
4553 (defun js2-mode-find-parent-fn (node)
4554 "Find function enclosing NODE.
4555 Returns nil if NODE is not inside a function."
4556 (setq node (js2-node-parent node))
4557 (while (and node (not (js2-function-node-p node)))
4558 (setq node (js2-node-parent node)))
4559 (and (js2-function-node-p node) node))
4560
4561 (defun js2-mode-find-enclosing-fn (node)
4562 "Find function or root enclosing NODE."
4563 (if (js2-ast-root-p node)
4564 node
4565 (setq node (js2-node-parent node))
4566 (while (not (or (js2-ast-root-p node)
4567 (js2-function-node-p node)))
4568 (setq node (js2-node-parent node)))
4569 node))
4570
4571 (defun js2-mode-find-enclosing-node (beg end)
4572 "Find node fully enclosing BEG and END."
4573 (let ((node (js2-node-at-point beg))
4574 pos
4575 (continue t))
4576 (while continue
4577 (if (or (js2-ast-root-p node)
4578 (and
4579 (<= (setq pos (js2-node-abs-pos node)) beg)
4580 (>= (+ pos (js2-node-len node)) end)))
4581 (setq continue nil)
4582 (setq node (js2-node-parent node))))
4583 node))
4584
4585 (defun js2-node-parent-script-or-fn (node)
4586 "Find script or function immediately enclosing NODE.
4587 If NODE is the ast-root, returns nil."
4588 (if (js2-ast-root-p node)
4589 nil
4590 (setq node (js2-node-parent node))
4591 (while (and node (not (or (js2-function-node-p node)
4592 (js2-script-node-p node))))
4593 (setq node (js2-node-parent node)))
4594 node))
4595
4596 (defun js2-node-is-descendant (node ancestor)
4597 "Return t if NODE is a descendant of ANCESTOR."
4598 (while (and node
4599 (not (eq node ancestor)))
4600 (setq node (js2-node-parent node)))
4601 node)
4602
4603 ;;; visitor infrastructure
4604
4605 (defun js2-visit-none (_node _callback)
4606 "Visitor for AST node that have no node children."
4607 nil)
4608
4609 (defun js2-print-none (_node _indent)
4610 "Visitor for AST node with no printed representation.")
4611
4612 (defun js2-print-body (node indent)
4613 "Print a statement, or a block without braces."
4614 (if (js2-block-node-p node)
4615 (dolist (kid (js2-block-node-kids node))
4616 (js2-print-ast kid indent))
4617 (js2-print-ast node indent)))
4618
4619 (defun js2-print-list (args &optional delimiter)
4620 (loop with len = (length args)
4621 for arg in args
4622 for count from 1
4623 do
4624 (when arg (js2-print-ast arg 0))
4625 (if (< count len)
4626 (insert (or delimiter ", ")))))
4627
4628 (defun js2-print-tree (ast)
4629 "Prints an AST to the current buffer.
4630 Makes `js2-ast-parent-nodes' available to the printer functions."
4631 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4632 (js2-print-ast ast)))
4633
4634 (defun js2-print-ast (node &optional indent)
4635 "Helper function for printing AST nodes.
4636 Requires `js2-ast-parent-nodes' to be non-nil.
4637 You should use `js2-print-tree' instead of this function."
4638 (let ((printer (get (aref node 0) 'js2-printer))
4639 (i (or indent 0)))
4640 ;; TODO: wedge comments in here somewhere
4641 (if printer
4642 (funcall printer node i))))
4643
4644 (defconst js2-side-effecting-tokens
4645 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4646 (dolist (tt (list js2-ASSIGN
4647 js2-ASSIGN_ADD
4648 js2-ASSIGN_BITAND
4649 js2-ASSIGN_BITOR
4650 js2-ASSIGN_BITXOR
4651 js2-ASSIGN_DIV
4652 js2-ASSIGN_LSH
4653 js2-ASSIGN_MOD
4654 js2-ASSIGN_MUL
4655 js2-ASSIGN_RSH
4656 js2-ASSIGN_SUB
4657 js2-ASSIGN_URSH
4658 js2-BLOCK
4659 js2-BREAK
4660 js2-CALL
4661 js2-CATCH
4662 js2-CATCH_SCOPE
4663 js2-CONST
4664 js2-CONTINUE
4665 js2-DEBUGGER
4666 js2-DEC
4667 js2-DELPROP
4668 js2-DEL_REF
4669 js2-DO
4670 js2-ELSE
4671 js2-EMPTY
4672 js2-ENTERWITH
4673 js2-EXPORT
4674 js2-EXPR_RESULT
4675 js2-FINALLY
4676 js2-FOR
4677 js2-FUNCTION
4678 js2-GOTO
4679 js2-IF
4680 js2-IFEQ
4681 js2-IFNE
4682 js2-IMPORT
4683 js2-INC
4684 js2-JSR
4685 js2-LABEL
4686 js2-LEAVEWITH
4687 js2-LET
4688 js2-LETEXPR
4689 js2-LOCAL_BLOCK
4690 js2-LOOP
4691 js2-NEW
4692 js2-REF_CALL
4693 js2-RETHROW
4694 js2-RETURN
4695 js2-RETURN_RESULT
4696 js2-SEMI
4697 js2-SETELEM
4698 js2-SETELEM_OP
4699 js2-SETNAME
4700 js2-SETPROP
4701 js2-SETPROP_OP
4702 js2-SETVAR
4703 js2-SET_REF
4704 js2-SET_REF_OP
4705 js2-SWITCH
4706 js2-TARGET
4707 js2-THROW
4708 js2-TRY
4709 js2-VAR
4710 js2-WHILE
4711 js2-WITH
4712 js2-WITHEXPR
4713 js2-YIELD))
4714 (aset tokens tt t))
4715 (if js2-instanceof-has-side-effects
4716 (aset tokens js2-INSTANCEOF t))
4717 tokens))
4718
4719 (defun js2-node-has-side-effects (node)
4720 "Return t if NODE has side effects."
4721 (when node ; makes it easier to handle malformed expressions
4722 (let ((tt (js2-node-type node)))
4723 (cond
4724 ;; This doubtless needs some work, since EXPR_VOID is used
4725 ;; in several ways in Rhino and I may not have caught them all.
4726 ;; I'll wait for people to notice incorrect warnings.
4727 ((and (= tt js2-EXPR_VOID)
4728 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4729 (let ((expr (js2-expr-stmt-node-expr node)))
4730 (or (js2-node-has-side-effects expr)
4731 (when (js2-string-node-p expr)
4732 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4733 ((= tt js2-COMMA)
4734 (js2-node-has-side-effects (js2-infix-node-right node)))
4735 ((or (= tt js2-AND)
4736 (= tt js2-OR))
4737 (or (js2-node-has-side-effects (js2-infix-node-right node))
4738 (js2-node-has-side-effects (js2-infix-node-left node))))
4739 ((= tt js2-HOOK)
4740 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4741 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4742 ((js2-paren-node-p node)
4743 (js2-node-has-side-effects (js2-paren-node-expr node)))
4744 ((= tt js2-ERROR) ; avoid cascaded error messages
4745 nil)
4746 (t
4747 (aref js2-side-effecting-tokens tt))))))
4748
4749 (defconst js2-stmt-node-types
4750 (list js2-BLOCK
4751 js2-BREAK
4752 js2-CONTINUE
4753 js2-DEFAULT ; e4x "default xml namespace" statement
4754 js2-DO
4755 js2-EXPR_RESULT
4756 js2-EXPR_VOID
4757 js2-FOR
4758 js2-IF
4759 js2-RETURN
4760 js2-SWITCH
4761 js2-THROW
4762 js2-TRY
4763 js2-WHILE
4764 js2-WITH)
4765 "Node types that only appear in statement contexts.
4766 The list does not include nodes that always appear as the child
4767 of another specific statement type, such as switch-cases,
4768 catch and finally blocks, and else-clauses. The list also excludes
4769 nodes like yield, let and var, which may appear in either expression
4770 or statement context, and in the latter context always have a
4771 `js2-expr-stmt-node' parent. Finally, the list does not include
4772 functions or scripts, which are treated separately from statements
4773 by the JavaScript parser and runtime.")
4774
4775 (defun js2-stmt-node-p (node)
4776 "Heuristic for figuring out if NODE is a statement.
4777 Some node types can appear in either an expression context or a
4778 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4779 For these node types in a statement context, the parent will be a
4780 `js2-expr-stmt-node'.
4781 Functions aren't included in the check."
4782 (memq (js2-node-type node) js2-stmt-node-types))
4783
4784 (defun js2-mode-find-first-stmt (node)
4785 "Search upward starting from NODE looking for a statement.
4786 For purposes of this function, a `js2-function-node' counts."
4787 (while (not (or (js2-stmt-node-p node)
4788 (js2-function-node-p node)))
4789 (setq node (js2-node-parent node)))
4790 node)
4791
4792 (defun js2-node-parent-stmt (node)
4793 "Return the node's first ancestor that is a statement.
4794 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4795 appearing in a statement context will have a parent that is a
4796 `js2-expr-stmt-node' that will be returned by this function."
4797 (let ((parent (js2-node-parent node)))
4798 (if (or (null parent)
4799 (js2-stmt-node-p parent)
4800 (and (js2-function-node-p parent)
4801 (not (eq (js2-function-node-form parent)
4802 'FUNCTION_EXPRESSION))))
4803 parent
4804 (js2-node-parent-stmt parent))))
4805
4806 ;; In the Mozilla Rhino sources, Roshan James writes:
4807 ;; Does consistent-return analysis on the function body when strict mode is
4808 ;; enabled.
4809 ;;
4810 ;; function (x) { return (x+1) }
4811 ;;
4812 ;; is ok, but
4813 ;;
4814 ;; function (x) { if (x < 0) return (x+1); }
4815 ;;
4816 ;; is not because the function can potentially return a value when the
4817 ;; condition is satisfied and if not, the function does not explicitly
4818 ;; return a value.
4819 ;;
4820 ;; This extends to checking mismatches such as "return" and "return <value>"
4821 ;; used in the same function. Warnings are not emitted if inconsistent
4822 ;; returns exist in code that can be statically shown to be unreachable.
4823 ;; Ex.
4824 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4825 ;;
4826 ;; emits no warning. However if the loop had a break statement, then a
4827 ;; warning would be emitted.
4828 ;;
4829 ;; The consistency analysis looks at control structures such as loops, ifs,
4830 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4831 ;; warns the user about an inconsistent set of termination possibilities.
4832 ;;
4833 ;; These flags enumerate the possible ways a statement/function can
4834 ;; terminate. These flags are used by endCheck() and by the Parser to
4835 ;; detect inconsistent return usage.
4836 ;;
4837 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4838 ;; able to execute (example: throw, continue)
4839 ;;
4840 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4841 ;; next one. Statement such as return dont. A compound statement may have
4842 ;; some branch that drops off control to the next statement.
4843 ;;
4844 ;; END_RETURNS indicates that the statement can return with no value.
4845 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4846 ;;
4847 ;; A compound statement such as
4848 ;; if (condition) {
4849 ;; return value;
4850 ;; }
4851 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4852
4853 (defconst js2-END_UNREACHED 0)
4854 (defconst js2-END_DROPS_OFF 1)
4855 (defconst js2-END_RETURNS 2)
4856 (defconst js2-END_RETURNS_VALUE 4)
4857 (defconst js2-END_YIELDS 8)
4858
4859 (defun js2-has-consistent-return-usage (node)
4860 "Check that every return usage in a function body is consistent.
4861 Returns t if the function satisfies strict mode requirement."
4862 (let ((n (js2-end-check node)))
4863 ;; either it doesn't return a value in any branch...
4864 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4865 ;; or it returns a value (or is unreached) at every branch
4866 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4867 js2-END_RETURNS
4868 js2-END_YIELDS)))))
4869
4870 (defun js2-end-check-if (node)
4871 "Ensure that return usage in then/else blocks is consistent.
4872 If there is no else block, then the return statement can fall through.
4873 Returns logical OR of END_* flags"
4874 (let ((th (js2-if-node-then-part node))
4875 (el (js2-if-node-else-part node)))
4876 (if (null th)
4877 js2-END_UNREACHED
4878 (logior (js2-end-check th) (if el
4879 (js2-end-check el)
4880 js2-END_DROPS_OFF)))))
4881
4882 (defun js2-end-check-switch (node)
4883 "Consistency of return statements is checked between the case statements.
4884 If there is no default, then the switch can fall through. If there is a
4885 default, we check to see if all code paths in the default return or if
4886 there is a code path that can fall through.
4887 Returns logical OR of END_* flags."
4888 (let ((rv js2-END_UNREACHED)
4889 default-case)
4890 ;; examine the cases
4891 (catch 'break
4892 (dolist (c (js2-switch-node-cases node))
4893 (if (js2-case-node-expr c)
4894 (js2-set-flag rv (js2-end-check-block c))
4895 (setq default-case c)
4896 (throw 'break nil))))
4897 ;; we don't care how the cases drop into each other
4898 (js2-clear-flag rv js2-END_DROPS_OFF)
4899 ;; examine the default
4900 (js2-set-flag rv (if default-case
4901 (js2-end-check default-case)
4902 js2-END_DROPS_OFF))
4903 rv))
4904
4905 (defun js2-end-check-try (node)
4906 "If the block has a finally, return consistency is checked in the
4907 finally block. If all code paths in the finally return, then the
4908 returns in the try-catch blocks don't matter. If there is a code path
4909 that does not return or if there is no finally block, the returns
4910 of the try and catch blocks are checked for mismatch.
4911 Returns logical OR of END_* flags."
4912 (let ((finally (js2-try-node-finally-block node))
4913 rv)
4914 ;; check the finally if it exists
4915 (setq rv (if finally
4916 (js2-end-check (js2-finally-node-body finally))
4917 js2-END_DROPS_OFF))
4918 ;; If the finally block always returns, then none of the returns
4919 ;; in the try or catch blocks matter.
4920 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4921 (js2-clear-flag rv js2-END_DROPS_OFF)
4922 ;; examine the try block
4923 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4924 ;; check each catch block
4925 (dolist (cb (js2-try-node-catch-clauses node))
4926 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4927 rv))
4928
4929 (defun js2-end-check-loop (node)
4930 "Return statement in the loop body must be consistent.
4931 The default assumption for any kind of a loop is that it will eventually
4932 terminate. The only exception is a loop with a constant true condition.
4933 Code that follows such a loop is examined only if one can determine
4934 statically that there is a break out of the loop.
4935
4936 for(... ; ... ; ...) {}
4937 for(... in ... ) {}
4938 while(...) { }
4939 do { } while(...)
4940
4941 Returns logical OR of END_* flags."
4942 (let ((rv (js2-end-check (js2-loop-node-body node)))
4943 (condition (cond
4944 ((js2-while-node-p node)
4945 (js2-while-node-condition node))
4946 ((js2-do-node-p node)
4947 (js2-do-node-condition node))
4948 ((js2-for-node-p node)
4949 (js2-for-node-condition node)))))
4950
4951 ;; check to see if the loop condition is always true
4952 (if (and condition
4953 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4954 (js2-clear-flag rv js2-END_DROPS_OFF))
4955
4956 ;; look for effect of breaks
4957 (js2-set-flag rv (js2-node-get-prop node
4958 'CONTROL_BLOCK_PROP
4959 js2-END_UNREACHED))
4960 rv))
4961
4962 (defun js2-end-check-block (node)
4963 "A general block of code is examined statement by statement.
4964 If any statement (even a compound one) returns in all branches, then
4965 subsequent statements are not examined.
4966 Returns logical OR of END_* flags."
4967 (let* ((rv js2-END_DROPS_OFF)
4968 (kids (js2-block-node-kids node))
4969 (n (car kids)))
4970 ;; Check each statment. If the statement can continue onto the next
4971 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4972 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4973 (js2-clear-flag rv js2-END_DROPS_OFF)
4974 (js2-set-flag rv (js2-end-check n))
4975 (setq kids (cdr kids)
4976 n (car kids)))
4977 rv))
4978
4979 (defun js2-end-check-label (node)
4980 "A labeled statement implies that there may be a break to the label.
4981 The function processes the labeled statement and then checks the
4982 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4983 particular label.
4984 Returns logical OR of END_* flags."
4985 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4986 (logior rv (js2-node-get-prop node
4987 'CONTROL_BLOCK_PROP
4988 js2-END_UNREACHED))))
4989
4990 (defun js2-end-check-break (node)
4991 "When a break is encountered annotate the statement being broken
4992 out of by setting its CONTROL_BLOCK_PROP property.
4993 Returns logical OR of END_* flags."
4994 (and (js2-break-node-target node)
4995 (js2-node-set-prop (js2-break-node-target node)
4996 'CONTROL_BLOCK_PROP
4997 js2-END_DROPS_OFF))
4998 js2-END_UNREACHED)
4999
5000 (defun js2-end-check (node)
5001 "Examine the body of a function, doing a basic reachability analysis.
5002 Returns a combination of flags END_* flags that indicate
5003 how the function execution can terminate. These constitute only the
5004 pessimistic set of termination conditions. It is possible that at
5005 runtime certain code paths will never be actually taken. Hence this
5006 analysis will flag errors in cases where there may not be errors.
5007 Returns logical OR of END_* flags"
5008 (let (kid)
5009 (cond
5010 ((js2-break-node-p node)
5011 (js2-end-check-break node))
5012 ((js2-expr-stmt-node-p node)
5013 (if (setq kid (js2-expr-stmt-node-expr node))
5014 (js2-end-check kid)
5015 js2-END_DROPS_OFF))
5016 ((or (js2-continue-node-p node)
5017 (js2-throw-node-p node))
5018 js2-END_UNREACHED)
5019 ((js2-return-node-p node)
5020 (if (setq kid (js2-return-node-retval node))
5021 js2-END_RETURNS_VALUE
5022 js2-END_RETURNS))
5023 ((js2-loop-node-p node)
5024 (js2-end-check-loop node))
5025 ((js2-switch-node-p node)
5026 (js2-end-check-switch node))
5027 ((js2-labeled-stmt-node-p node)
5028 (js2-end-check-label node))
5029 ((js2-if-node-p node)
5030 (js2-end-check-if node))
5031 ((js2-try-node-p node)
5032 (js2-end-check-try node))
5033 ((js2-block-node-p node)
5034 (if (null (js2-block-node-kids node))
5035 js2-END_DROPS_OFF
5036 (js2-end-check-block node)))
5037 ((js2-yield-node-p node)
5038 js2-END_YIELDS)
5039 (t
5040 js2-END_DROPS_OFF))))
5041
5042 (defun js2-always-defined-boolean-p (node)
5043 "Check if NODE always evaluates to true or false in boolean context.
5044 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5045 nor always false."
5046 (let ((tt (js2-node-type node))
5047 num)
5048 (cond
5049 ((or (= tt js2-FALSE) (= tt js2-NULL))
5050 'ALWAYS_FALSE)
5051 ((= tt js2-TRUE)
5052 'ALWAYS_TRUE)
5053 ((= tt js2-NUMBER)
5054 (setq num (js2-number-node-num-value node))
5055 (if (and (not (eq num 0.0e+NaN))
5056 (not (zerop num)))
5057 'ALWAYS_TRUE
5058 'ALWAYS_FALSE))
5059 (t
5060 nil))))
5061
5062 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5063 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5064
5065 (defvar js2-tokens nil
5066 "List of all defined token names.") ; initialized in `js2-token-names'
5067
5068 (defconst js2-token-names
5069 (let* ((names (make-vector js2-num-tokens -1))
5070 (case-fold-search nil) ; only match js2-UPPER_CASE
5071 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5072 (loop for sym in syms
5073 for i from 0
5074 do
5075 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5076 (not (boundp sym)))
5077 (aset names (symbol-value sym) ; code, e.g. 152
5078 (downcase
5079 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5080 (push sym js2-tokens)))
5081 names)
5082 "Vector mapping int values to token string names, sans `js2-' prefix.")
5083
5084 (defun js2-tt-name (tok)
5085 "Return a string name for TOK, a token symbol or code.
5086 Signals an error if it's not a recognized token."
5087 (let ((code tok))
5088 (if (symbolp tok)
5089 (setq code (symbol-value tok)))
5090 (if (eq code -1)
5091 "ERROR"
5092 (if (and (numberp code)
5093 (not (minusp code))
5094 (< code js2-num-tokens))
5095 (aref js2-token-names code)
5096 (error "Invalid token: %s" code)))))
5097
5098 (defsubst js2-tt-sym (tok)
5099 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5100 (intern (js2-tt-name tok)))
5101
5102 (defconst js2-token-codes
5103 (let ((table (make-hash-table :test 'eq :size 256)))
5104 (loop for name across js2-token-names
5105 for sym = (intern (concat "js2-" (upcase name)))
5106 do
5107 (puthash sym (symbol-value sym) table))
5108 ;; clean up a few that are "wrong" in Rhino's token codes
5109 (puthash 'js2-DELETE js2-DELPROP table)
5110 table)
5111 "Hashtable mapping token type symbols to their bytecodes.")
5112
5113 (defsubst js2-tt-code (sym)
5114 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5115 (or (gethash sym js2-token-codes)
5116 (error "Invalid token symbol: %s " sym))) ; signal code bug
5117
5118 (defun js2-report-scan-error (msg &optional no-throw beg len)
5119 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5120 (js2-report-error msg nil
5121 (or beg (js2-current-token-beg))
5122 (or len (js2-current-token-len)))
5123 (unless no-throw
5124 (throw 'return js2-ERROR)))
5125
5126 (defun js2-set-string-from-buffer (token)
5127 "Set `string' and `end' slots for TOKEN, return the string."
5128 (setf (js2-token-end token) js2-ts-cursor
5129 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5130
5131 ;; TODO: could potentially avoid a lot of consing by allocating a
5132 ;; char buffer the way Rhino does.
5133 (defsubst js2-add-to-string (c)
5134 (push c js2-ts-string-buffer))
5135
5136 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5137 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5138 ;; any other character: when it's not part of the current token, we
5139 ;; unget it, allowing it to be read again by the following call.
5140 (defsubst js2-unget-char ()
5141 (decf js2-ts-cursor))
5142
5143 ;; Rhino distinguishes \r and \n line endings. We don't need to
5144 ;; because we only scan from Emacs buffers, which always use \n.
5145 (defun js2-get-char ()
5146 "Read and return the next character from the input buffer.
5147 Increments `js2-ts-lineno' if the return value is a newline char.
5148 Updates `js2-ts-cursor' to the point after the returned char.
5149 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5150 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5151 (let (c)
5152 ;; check for end of buffer
5153 (if (>= js2-ts-cursor (point-max))
5154 (setq js2-ts-hit-eof t
5155 js2-ts-cursor (1+ js2-ts-cursor)
5156 c js2-EOF_CHAR) ; return value
5157 ;; otherwise read next char
5158 (setq c (char-before (incf js2-ts-cursor)))
5159 ;; if we read a newline, update counters
5160 (if (= c ?\n)
5161 (setq js2-ts-line-start js2-ts-cursor
5162 js2-ts-lineno (1+ js2-ts-lineno)))
5163 ;; TODO: skip over format characters
5164 c)))
5165
5166 (defun js2-read-unicode-escape ()
5167 "Read a \\uNNNN sequence from the input.
5168 Assumes the ?\ and ?u have already been read.
5169 Returns the unicode character, or nil if it wasn't a valid character.
5170 Doesn't change the values of any scanner variables."
5171 ;; I really wish I knew a better way to do this, but I can't
5172 ;; find the Emacs function that takes a 16-bit int and converts
5173 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5174 ;; Have to first check that it's 4 hex characters or it may stop
5175 ;; the read early.
5176 (ignore-errors
5177 (let ((s (buffer-substring-no-properties js2-ts-cursor
5178 (+ 4 js2-ts-cursor))))
5179 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5180 (read (concat "?\\u" s))))))
5181
5182 (defun js2-match-char (test)
5183 "Consume and return next character if it matches TEST, a character.
5184 Returns nil and consumes nothing if TEST is not the next character."
5185 (let ((c (js2-get-char)))
5186 (if (eq c test)
5187 t
5188 (js2-unget-char)
5189 nil)))
5190
5191 (defun js2-peek-char ()
5192 (prog1
5193 (js2-get-char)
5194 (js2-unget-char)))
5195
5196 (defun js2-identifier-start-p (c)
5197 "Is C a valid start to an ES5 Identifier?
5198 See http://es5.github.io/#x7.6"
5199 (or
5200 (memq c '(?$ ?_))
5201 (memq (get-char-code-property c 'general-category)
5202 ;; Letters
5203 '(Lu Ll Lt Lm Lo Nl))))
5204
5205 (defun js2-identifier-part-p (c)
5206 "Is C a valid part of an ES5 Identifier?
5207 See http://es5.github.io/#x7.6"
5208 (or
5209 (memq c '(?$ ?_ ?\u200c ?\u200d))
5210 (memq (get-char-code-property c 'general-category)
5211 '(;; Letters
5212 Lu Ll Lt Lm Lo Nl
5213 ;; Combining Marks
5214 Mn Mc
5215 ;; Digits
5216 Nd
5217 ;; Connector Punctuation
5218 Pc))))
5219
5220 (defun js2-alpha-p (c)
5221 (cond ((and (<= ?A c) (<= c ?Z)) t)
5222 ((and (<= ?a c) (<= c ?z)) t)
5223 (t nil)))
5224
5225 (defsubst js2-digit-p (c)
5226 (and (<= ?0 c) (<= c ?9)))
5227
5228 (defun js2-js-space-p (c)
5229 (if (<= c 127)
5230 (memq c '(#x20 #x9 #xB #xC #xD))
5231 (or
5232 (eq c #xA0)
5233 ;; TODO: change this nil to check for Unicode space character
5234 nil)))
5235
5236 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5237
5238 (defun js2-skip-line ()
5239 "Skip to end of line."
5240 (while (not (memq (js2-get-char) js2-eol-chars)))
5241 (js2-unget-char)
5242 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5243 (setq js2-token-end js2-ts-cursor))
5244
5245 (defun js2-init-scanner (&optional buf line)
5246 "Create token stream for BUF starting on LINE.
5247 BUF defaults to `current-buffer' and LINE defaults to 1.
5248
5249 A buffer can only have one scanner active at a time, which yields
5250 dramatically simpler code than using a defstruct. If you need to
5251 have simultaneous scanners in a buffer, copy the regions to scan
5252 into temp buffers."
5253 (with-current-buffer (or buf (current-buffer))
5254 (setq js2-ts-dirty-line nil
5255 js2-ts-hit-eof nil
5256 js2-ts-line-start 0
5257 js2-ts-lineno (or line 1)
5258 js2-ts-line-end-char -1
5259 js2-ts-cursor (point-min)
5260 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5261 js2-ti-tokens-cursor 0
5262 js2-ti-lookahead 0
5263 js2-ts-is-xml-attribute nil
5264 js2-ts-xml-is-tag-content nil
5265 js2-ts-xml-open-tags-count 0
5266 js2-ts-string-buffer nil)))
5267
5268 ;; This function uses the cached op, string and number fields in
5269 ;; TokenStream; if getToken has been called since the passed token
5270 ;; was scanned, the op or string printed may be incorrect.
5271 (defun js2-token-to-string (token)
5272 ;; Not sure where this function is used in Rhino. Not tested.
5273 (if (not js2-debug-print-trees)
5274 ""
5275 (let ((name (js2-tt-name token)))
5276 (cond
5277 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5278 (concat name " `" (js2-current-token-string) "'"))
5279 ((eq token js2-NUMBER)
5280 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5281 (t
5282 name)))))
5283
5284 (defconst js2-keywords
5285 '(break
5286 case catch const continue
5287 debugger default delete do
5288 else enum
5289 false finally for function
5290 if in instanceof import
5291 let
5292 new null
5293 return
5294 switch
5295 this throw true try typeof
5296 var void
5297 while with
5298 yield))
5299
5300 ;; Token names aren't exactly the same as the keywords, unfortunately.
5301 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5302 (defconst js2-kwd-tokens
5303 (let ((table (make-vector js2-num-tokens nil))
5304 (tokens
5305 (list js2-BREAK
5306 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5307 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5308 js2-ELSE
5309 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5310 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5311 js2-LET
5312 js2-NEW js2-NULL
5313 js2-RETURN
5314 js2-SWITCH
5315 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5316 js2-VAR
5317 js2-WHILE js2-WITH
5318 js2-YIELD)))
5319 (dolist (i tokens)
5320 (aset table i 'font-lock-keyword-face))
5321 (aset table js2-STRING 'font-lock-string-face)
5322 (aset table js2-REGEXP 'font-lock-string-face)
5323 (aset table js2-COMMENT 'font-lock-comment-face)
5324 (aset table js2-THIS 'font-lock-builtin-face)
5325 (aset table js2-VOID 'font-lock-constant-face)
5326 (aset table js2-NULL 'font-lock-constant-face)
5327 (aset table js2-TRUE 'font-lock-constant-face)
5328 (aset table js2-FALSE 'font-lock-constant-face)
5329 (aset table js2-NOT 'font-lock-negation-char-face)
5330 table)
5331 "Vector whose values are non-nil for tokens that are keywords.
5332 The values are default faces to use for highlighting the keywords.")
5333
5334 ;; FIXME: Support strict mode-only future reserved words, after we know
5335 ;; which parts scopes are in strict mode, and which are not.
5336 (defconst js2-reserved-words '(class export extends import super)
5337 "Future reserved keywords in ECMAScript 5.")
5338
5339 (defconst js2-keyword-names
5340 (let ((table (make-hash-table :test 'equal)))
5341 (loop for k in js2-keywords
5342 do (puthash
5343 (symbol-name k) ; instanceof
5344 (intern (concat "js2-"
5345 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5346 table))
5347 table)
5348 "JavaScript keywords by name, mapped to their symbols.")
5349
5350 (defconst js2-reserved-word-names
5351 (let ((table (make-hash-table :test 'equal)))
5352 (loop for k in js2-reserved-words
5353 do
5354 (puthash (symbol-name k) 'js2-RESERVED table))
5355 table)
5356 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5357
5358 (defun js2-collect-string (buf)
5359 "Convert BUF, a list of chars, to a string.
5360 Reverses BUF before converting."
5361 (if buf
5362 (apply #'string (nreverse buf))
5363 ""))
5364
5365 (defun js2-string-to-keyword (s)
5366 "Return token for S, a string, if S is a keyword or reserved word.
5367 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5368 (or (gethash s js2-keyword-names)
5369 (gethash s js2-reserved-word-names)))
5370
5371 (defsubst js2-ts-set-char-token-bounds (token)
5372 "Used when next token is one character."
5373 (setf (js2-token-beg token) (1- js2-ts-cursor)
5374 (js2-token-end token) js2-ts-cursor))
5375
5376 (defsubst js2-ts-return (token type)
5377 "Update the `end' and `type' slots of TOKEN,
5378 then throw `return' with value TYPE."
5379 (setf (js2-token-end token) js2-ts-cursor
5380 (js2-token-type token) type)
5381 (throw 'return type))
5382
5383 (defun js2-x-digit-to-int (c accumulator)
5384 "Build up a hex number.
5385 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5386 corresponding number. Otherwise return -1."
5387 (catch 'return
5388 (catch 'check
5389 ;; Use 0..9 < A..Z < a..z
5390 (cond
5391 ((<= c ?9)
5392 (decf c ?0)
5393 (if (<= 0 c)
5394 (throw 'check nil)))
5395 ((<= c ?F)
5396 (when (<= ?A c)
5397 (decf c (- ?A 10))
5398 (throw 'check nil)))
5399 ((<= c ?f)
5400 (when (<= ?a c)
5401 (decf c (- ?a 10))
5402 (throw 'check nil))))
5403 (throw 'return -1))
5404 (logior c (lsh accumulator 4))))
5405
5406 (defun js2-get-token ()
5407 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5408 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5409 next saved token.
5410
5411 This function will not return a newline (js2-EOL) - instead, it
5412 gobbles newlines until it finds a non-newline token. Call
5413 `js2-peek-token-or-eol' when you care about newlines.
5414
5415 This function will also not return a js2-COMMENT. Instead, it
5416 records comments found in `js2-scanned-comments'. If the token
5417 returned by this function immediately follows a jsdoc comment,
5418 the token is flagged as such."
5419 (if (zerop js2-ti-lookahead)
5420 (js2-get-token-internal)
5421 (decf js2-ti-lookahead)
5422 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5423 (let ((tt (js2-current-token-type)))
5424 (assert (not (= tt js2-EOL)))
5425 tt)))
5426
5427 (defun js2-unget-token ()
5428 (assert (< js2-ti-lookahead js2-ti-max-lookahead))
5429 (incf js2-ti-lookahead)
5430 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5431
5432 (defun js2-get-token-internal ()
5433 (let* ((token (js2-get-token-internal-1)) ; call scanner
5434 (tt (js2-token-type token))
5435 saw-eol
5436 face)
5437 ;; process comments
5438 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5439 (if (= tt js2-EOL)
5440 (setq saw-eol t)
5441 (setq saw-eol nil)
5442 (when js2-record-comments
5443 (js2-record-comment token)))
5444 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5445 (setq token (js2-get-token-internal-1) ; call scanner again
5446 tt (js2-token-type token)))
5447
5448 (when saw-eol
5449 (setf (js2-token-follows-eol-p token) t))
5450
5451 ;; perform lexical fontification as soon as token is scanned
5452 (when js2-parse-ide-mode
5453 (cond
5454 ((minusp tt)
5455 (js2-record-face 'js2-error token))
5456 ((setq face (aref js2-kwd-tokens tt))
5457 (js2-record-face face token))
5458 ((and (= tt js2-NAME)
5459 (equal (js2-token-string token) "undefined"))
5460 (js2-record-face 'font-lock-constant-face token))))
5461 tt))
5462
5463 (defun js2-get-token-internal-1 ()
5464 "Return next JavaScript token type, an int such as js2-RETURN.
5465 During operation, creates an instance of `js2-token' struct, sets
5466 its relevant fields and puts it into `js2-ti-tokens'."
5467 (let (c c1 identifier-start is-unicode-escape-start
5468 contains-escape escape-val str result base
5469 quote-char val look-for-slash continue tt
5470 (token (js2-new-token 0)))
5471 (setq
5472 tt
5473 (catch 'return
5474 (while t
5475 ;; Eat whitespace, possibly sensitive to newlines.
5476 (setq continue t)
5477 (while continue
5478 (setq c (js2-get-char))
5479 (cond
5480 ((eq c js2-EOF_CHAR)
5481 (js2-unget-char)
5482 (js2-ts-set-char-token-bounds token)
5483 (throw 'return js2-EOF))
5484 ((eq c ?\n)
5485 (js2-ts-set-char-token-bounds token)
5486 (setq js2-ts-dirty-line nil)
5487 (throw 'return js2-EOL))
5488 ((not (js2-js-space-p c))
5489 (if (/= c ?-) ; in case end of HTML comment
5490 (setq js2-ts-dirty-line t))
5491 (setq continue nil))))
5492 ;; Assume the token will be 1 char - fixed up below.
5493 (js2-ts-set-char-token-bounds token)
5494 (when (eq c ?@)
5495 (throw 'return js2-XMLATTR))
5496 ;; identifier/keyword/instanceof?
5497 ;; watch out for starting with a <backslash>
5498 (cond
5499 ((eq c ?\\)
5500 (setq c (js2-get-char))
5501 (if (eq c ?u)
5502 (setq identifier-start t
5503 is-unicode-escape-start t
5504 js2-ts-string-buffer nil)
5505 (setq identifier-start nil)
5506 (js2-unget-char)
5507 (setq c ?\\)))
5508 (t
5509 (when (setq identifier-start (js2-identifier-start-p c))
5510 (setq js2-ts-string-buffer nil)
5511 (js2-add-to-string c))))
5512 (when identifier-start
5513 (setq contains-escape is-unicode-escape-start)
5514 (catch 'break
5515 (while t
5516 (if is-unicode-escape-start
5517 ;; strictly speaking we should probably push-back
5518 ;; all the bad characters if the <backslash>uXXXX
5519 ;; sequence is malformed. But since there isn't a
5520 ;; correct context(is there?) for a bad Unicode
5521 ;; escape sequence in an identifier, we can report
5522 ;; an error here.
5523 (progn
5524 (setq escape-val 0)
5525 (dotimes (_ 4)
5526 (setq c (js2-get-char)
5527 escape-val (js2-x-digit-to-int c escape-val))
5528 ;; Next check takes care of c < 0 and bad escape
5529 (if (minusp escape-val)
5530 (throw 'break nil)))
5531 (if (minusp escape-val)
5532 (js2-report-scan-error "msg.invalid.escape" t))
5533 (js2-add-to-string escape-val)
5534 (setq is-unicode-escape-start nil))
5535 (setq c (js2-get-char))
5536 (cond
5537 ((eq c ?\\)
5538 (setq c (js2-get-char))
5539 (if (eq c ?u)
5540 (setq is-unicode-escape-start t
5541 contains-escape t)
5542 (js2-report-scan-error "msg.illegal.character" t)))
5543 (t
5544 (if (or (eq c js2-EOF_CHAR)
5545 (not (js2-identifier-part-p c)))
5546 (throw 'break nil))
5547 (js2-add-to-string c))))))
5548 (js2-unget-char)
5549 (setf str (js2-collect-string js2-ts-string-buffer)
5550 (js2-token-end token) js2-ts-cursor)
5551 ;; FIXME: Invalid in ES5 and ES6, see
5552 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5553 ;; Probably should just drop this conditional.
5554 (unless contains-escape
5555 ;; OPT we shouldn't have to make a string (object!) to
5556 ;; check if it's a keyword.
5557 ;; Return the corresponding token if it's a keyword
5558 (when (setq result (js2-string-to-keyword str))
5559 (if (and (< js2-language-version 170)
5560 (memq result '(js2-LET js2-YIELD)))
5561 ;; LET and YIELD are tokens only in 1.7 and later
5562 (setq result 'js2-NAME))
5563 (when (eq result 'js2-RESERVED)
5564 (setf (js2-token-string token) str))
5565 (throw 'return (js2-tt-code result))))
5566 ;; If we want to intern these as Rhino does, just use (intern str)
5567 (setf (js2-token-string token) str)
5568 (throw 'return js2-NAME)) ; end identifier/kwd check
5569 ;; is it a number?
5570 (when (or (js2-digit-p c)
5571 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5572 (setq js2-ts-string-buffer nil
5573 base 10)
5574 (when (eq c ?0)
5575 (setq c (js2-get-char))
5576 (cond
5577 ((or (eq c ?x) (eq c ?X))
5578 (setq base 16)
5579 (setq c (js2-get-char)))
5580 ((and (or (eq c ?b) (eq c ?B))
5581 (>= js2-language-version 200))
5582 (setq base 2)
5583 (setq c (js2-get-char)))
5584 ((and (or (eq c ?o) (eq c ?O))
5585 (>= js2-language-version 200))
5586 (setq base 8)
5587 (setq c (js2-get-char)))
5588 ((js2-digit-p c)
5589 (setq base 'maybe-8))
5590 (t
5591 (js2-add-to-string ?0))))
5592 (cond
5593 ((eq base 16)
5594 (if (> 0 (js2-x-digit-to-int c 0))
5595 (js2-report-scan-error "msg.missing.hex.digits")
5596 (while (<= 0 (js2-x-digit-to-int c 0))
5597 (js2-add-to-string c)
5598 (setq c (js2-get-char)))))
5599 ((eq base 2)
5600 (if (not (memq c '(?0 ?1)))
5601 (js2-report-scan-error "msg.missing.binary.digits")
5602 (while (memq c '(?0 ?1))
5603 (js2-add-to-string c)
5604 (setq c (js2-get-char)))))
5605 ((eq base 8)
5606 (if (or (> ?0 c) (< ?7 c))
5607 (js2-report-scan-error "msg.missing.octal.digits")
5608 (while (and (<= ?0 c) (>= ?7 c))
5609 (js2-add-to-string c)
5610 (setq c (js2-get-char)))))
5611 (t
5612 (while (and (<= ?0 c) (<= c ?9))
5613 ;; We permit 08 and 09 as decimal numbers, which
5614 ;; makes our behavior a superset of the ECMA
5615 ;; numeric grammar. We might not always be so
5616 ;; permissive, so we warn about it.
5617 (when (and (eq base 'maybe-8) (>= c ?8))
5618 (js2-report-warning "msg.bad.octal.literal"
5619 (if (eq c ?8) "8" "9"))
5620 (setq base 10))
5621 (js2-add-to-string c)
5622 (setq c (js2-get-char)))
5623 (when (eq base 'maybe-8)
5624 (setq base 8))))
5625 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5626 (when (eq c ?.)
5627 (loop do
5628 (js2-add-to-string c)
5629 (setq c (js2-get-char))
5630 while (js2-digit-p c)))
5631 (when (memq c '(?e ?E))
5632 (js2-add-to-string c)
5633 (setq c (js2-get-char))
5634 (when (memq c '(?+ ?-))
5635 (js2-add-to-string c)
5636 (setq c (js2-get-char)))
5637 (unless (js2-digit-p c)
5638 (js2-report-scan-error "msg.missing.exponent" t))
5639 (loop do
5640 (js2-add-to-string c)
5641 (setq c (js2-get-char))
5642 while (js2-digit-p c))))
5643 (js2-unget-char)
5644 (let ((str (js2-set-string-from-buffer token)))
5645 (setf (js2-token-number token)
5646 (js2-string-to-number str base)))
5647 (throw 'return js2-NUMBER))
5648 ;; is it a string?
5649 (when (memq c '(?\" ?\'))
5650 ;; We attempt to accumulate a string the fast way, by
5651 ;; building it directly out of the reader. But if there
5652 ;; are any escaped characters in the string, we revert to
5653 ;; building it out of a string buffer.
5654 (setq quote-char c
5655 js2-ts-string-buffer nil
5656 c (js2-get-char))
5657 (catch 'break
5658 (while (/= c quote-char)
5659 (catch 'continue
5660 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5661 (js2-unget-char)
5662 (setf (js2-token-end token) js2-ts-cursor)
5663 (js2-report-error "msg.unterminated.string.lit")
5664 (throw 'return js2-STRING))
5665 (when (eq c ?\\)
5666 ;; We've hit an escaped character
5667 (setq c (js2-get-char))
5668 (case c
5669 (?b (setq c ?\b))
5670 (?f (setq c ?\f))
5671 (?n (setq c ?\n))
5672 (?r (setq c ?\r))
5673 (?t (setq c ?\t))
5674 (?v (setq c ?\v))
5675 (?u
5676 (setq c1 (js2-read-unicode-escape))
5677 (if js2-parse-ide-mode
5678 (if c1
5679 (progn
5680 ;; just copy the string in IDE-mode
5681 (js2-add-to-string ?\\)
5682 (js2-add-to-string ?u)
5683 (dotimes (_ 3)
5684 (js2-add-to-string (js2-get-char)))
5685 (setq c (js2-get-char))) ; added at end of loop
5686 ;; flag it as an invalid escape
5687 (js2-report-warning "msg.invalid.escape"
5688 nil (- js2-ts-cursor 2) 6))
5689 ;; Get 4 hex digits; if the u escape is not
5690 ;; followed by 4 hex digits, use 'u' + the
5691 ;; literal character sequence that follows.
5692 (js2-add-to-string ?u)
5693 (setq escape-val 0)
5694 (dotimes (_ 4)
5695 (setq c (js2-get-char)
5696 escape-val (js2-x-digit-to-int c escape-val))
5697 (if (minusp escape-val)
5698 (throw 'continue nil))
5699 (js2-add-to-string c))
5700 ;; prepare for replace of stored 'u' sequence by escape value
5701 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5702 c escape-val)))
5703 (?x
5704 ;; Get 2 hex digits, defaulting to 'x'+literal
5705 ;; sequence, as above.
5706 (setq c (js2-get-char)
5707 escape-val (js2-x-digit-to-int c 0))
5708 (if (minusp escape-val)
5709 (progn
5710 (js2-add-to-string ?x)
5711 (throw 'continue nil))
5712 (setq c1 c
5713 c (js2-get-char)
5714 escape-val (js2-x-digit-to-int c escape-val))
5715 (if (minusp escape-val)
5716 (progn
5717 (js2-add-to-string ?x)
5718 (js2-add-to-string c1)
5719 (throw 'continue nil))
5720 ;; got 2 hex digits
5721 (setq c escape-val))))
5722 (?\n
5723 ;; Remove line terminator after escape to follow
5724 ;; SpiderMonkey and C/C++
5725 (setq c (js2-get-char))
5726 (throw 'continue nil))
5727 (t
5728 (when (and (<= ?0 c) (< c ?8))
5729 (setq val (- c ?0)
5730 c (js2-get-char))
5731 (when (and (<= ?0 c) (< c ?8))
5732 (setq val (- (+ (* 8 val) c) ?0)
5733 c (js2-get-char))
5734 (when (and (<= ?0 c)
5735 (< c ?8)
5736 (< val #o37))
5737 ;; c is 3rd char of octal sequence only
5738 ;; if the resulting val <= 0377
5739 (setq val (- (+ (* 8 val) c) ?0)
5740 c (js2-get-char))))
5741 (js2-unget-char)
5742 (setq c val)))))
5743 (js2-add-to-string c)
5744 (setq c (js2-get-char)))))
5745 (js2-set-string-from-buffer token)
5746 (throw 'return js2-STRING))
5747 (js2-ts-return token
5748 (case c
5749 (?\;
5750 (throw 'return js2-SEMI))
5751 (?\[
5752 (throw 'return js2-LB))
5753 (?\]
5754 (throw 'return js2-RB))
5755 (?{
5756 (throw 'return js2-LC))
5757 (?}
5758 (throw 'return js2-RC))
5759 (?\(
5760 (throw 'return js2-LP))
5761 (?\)
5762 (throw 'return js2-RP))
5763 (?,
5764 (throw 'return js2-COMMA))
5765 (??
5766 (throw 'return js2-HOOK))
5767 (?:
5768 (if (js2-match-char ?:)
5769 js2-COLONCOLON
5770 (throw 'return js2-COLON)))
5771 (?.
5772 (if (js2-match-char ?.)
5773 (if (js2-match-char ?.)
5774 js2-TRIPLEDOT js2-DOTDOT)
5775 (if (js2-match-char ?\()
5776 js2-DOTQUERY
5777 (throw 'return js2-DOT))))
5778 (?|
5779 (if (js2-match-char ?|)
5780 (throw 'return js2-OR)
5781 (if (js2-match-char ?=)
5782 js2-ASSIGN_BITOR
5783 (throw 'return js2-BITOR))))
5784 (?^
5785 (if (js2-match-char ?=)
5786 js2-ASSIGN_BITOR
5787 (throw 'return js2-BITXOR)))
5788 (?&
5789 (if (js2-match-char ?&)
5790 (throw 'return js2-AND)
5791 (if (js2-match-char ?=)
5792 js2-ASSIGN_BITAND
5793 (throw 'return js2-BITAND))))
5794 (?=
5795 (if (js2-match-char ?=)
5796 (if (js2-match-char ?=)
5797 js2-SHEQ
5798 (throw 'return js2-EQ))
5799 (if (js2-match-char ?>)
5800 (js2-ts-return token js2-ARROW)
5801 (throw 'return js2-ASSIGN))))
5802 (?!
5803 (if (js2-match-char ?=)
5804 (if (js2-match-char ?=)
5805 js2-SHNE
5806 js2-NE)
5807 (throw 'return js2-NOT)))
5808 (?<
5809 ;; NB:treat HTML begin-comment as comment-till-eol
5810 (when (js2-match-char ?!)
5811 (when (js2-match-char ?-)
5812 (when (js2-match-char ?-)
5813 (js2-skip-line)
5814 (setf (js2-token-comment-type (js2-current-token)) 'html)
5815 (throw 'return js2-COMMENT)))
5816 (js2-unget-char))
5817 (if (js2-match-char ?<)
5818 (if (js2-match-char ?=)
5819 js2-ASSIGN_LSH
5820 js2-LSH)
5821 (if (js2-match-char ?=)
5822 js2-LE
5823 (throw 'return js2-LT))))
5824 (?>
5825 (if (js2-match-char ?>)
5826 (if (js2-match-char ?>)
5827 (if (js2-match-char ?=)
5828 js2-ASSIGN_URSH
5829 js2-URSH)
5830 (if (js2-match-char ?=)
5831 js2-ASSIGN_RSH
5832 js2-RSH))
5833 (if (js2-match-char ?=)
5834 js2-GE
5835 (throw 'return js2-GT))))
5836 (?*
5837 (if (js2-match-char ?=)
5838 js2-ASSIGN_MUL
5839 (throw 'return js2-MUL)))
5840 (?/
5841 ;; is it a // comment?
5842 (when (js2-match-char ?/)
5843 (setf (js2-token-beg token) (- js2-ts-cursor 2))
5844 (js2-skip-line)
5845 (setf (js2-token-comment-type token) 'line)
5846 ;; include newline so highlighting goes to end of window
5847 (incf (js2-token-end token))
5848 (throw 'return js2-COMMENT))
5849 ;; is it a /* comment?
5850 (when (js2-match-char ?*)
5851 (setf look-for-slash nil
5852 (js2-token-beg token) (- js2-ts-cursor 2)
5853 (js2-token-comment-type token)
5854 (if (js2-match-char ?*)
5855 (progn
5856 (setq look-for-slash t)
5857 'jsdoc)
5858 'block))
5859 (while t
5860 (setq c (js2-get-char))
5861 (cond
5862 ((eq c js2-EOF_CHAR)
5863 (setf (js2-token-end token) (1- js2-ts-cursor))
5864 (js2-report-error "msg.unterminated.comment")
5865 (throw 'return js2-COMMENT))
5866 ((eq c ?*)
5867 (setq look-for-slash t))
5868 ((eq c ?/)
5869 (if look-for-slash
5870 (js2-ts-return token js2-COMMENT)))
5871 (t
5872 (setf look-for-slash nil
5873 (js2-token-end token) js2-ts-cursor)))))
5874 (if (js2-match-char ?=)
5875 js2-ASSIGN_DIV
5876 (throw 'return js2-DIV)))
5877 (?#
5878 (when js2-skip-preprocessor-directives
5879 (js2-skip-line)
5880 (setf (js2-token-comment-type token) 'preprocessor
5881 (js2-token-end token) js2-ts-cursor)
5882 (throw 'return js2-COMMENT))
5883 (throw 'return js2-ERROR))
5884 (?%
5885 (if (js2-match-char ?=)
5886 js2-ASSIGN_MOD
5887 (throw 'return js2-MOD)))
5888 (?~
5889 (throw 'return js2-BITNOT))
5890 (?+
5891 (if (js2-match-char ?=)
5892 js2-ASSIGN_ADD
5893 (if (js2-match-char ?+)
5894 js2-INC
5895 (throw 'return js2-ADD))))
5896 (?-
5897 (cond
5898 ((js2-match-char ?=)
5899 (setq c js2-ASSIGN_SUB))
5900 ((js2-match-char ?-)
5901 (unless js2-ts-dirty-line
5902 ;; treat HTML end-comment after possible whitespace
5903 ;; after line start as comment-until-eol
5904 (when (js2-match-char ?>)
5905 (js2-skip-line)
5906 (setf (js2-token-comment-type (js2-current-token)) 'html)
5907 (throw 'return js2-COMMENT)))
5908 (setq c js2-DEC))
5909 (t
5910 (setq c js2-SUB)))
5911 (setq js2-ts-dirty-line t)
5912 c)
5913 (otherwise
5914 (js2-report-scan-error "msg.illegal.character")))))))
5915 (setf (js2-token-type token) tt)
5916 token))
5917
5918 (defsubst js2-string-to-number (str base)
5919 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5920 (condition-case nil
5921 (string-to-number str base)
5922 (overflow-error -1)))
5923
5924 (defun js2-read-regexp (start-tt)
5925 "Called by parser when it gets / or /= in literal context."
5926 (let (c err
5927 in-class ; inside a '[' .. ']' character-class
5928 flags
5929 (continue t)
5930 (token (js2-new-token 0)))
5931 (setq js2-ts-string-buffer nil)
5932 (if (eq start-tt js2-ASSIGN_DIV)
5933 ;; mis-scanned /=
5934 (js2-add-to-string ?=)
5935 (if (not (eq start-tt js2-DIV))
5936 (error "failed assertion")))
5937 (while (and (not err)
5938 (or (/= (setq c (js2-get-char)) ?/)
5939 in-class))
5940 (cond
5941 ((or (= c ?\n)
5942 (= c js2-EOF_CHAR))
5943 (setf (js2-token-end token) (1- js2-ts-cursor)
5944 err t
5945 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
5946 (js2-report-error "msg.unterminated.re.lit"))
5947 (t (cond
5948 ((= c ?\\)
5949 (js2-add-to-string c)
5950 (setq c (js2-get-char)))
5951 ((= c ?\[)
5952 (setq in-class t))
5953 ((= c ?\])
5954 (setq in-class nil)))
5955 (js2-add-to-string c))))
5956 (unless err
5957 (while continue
5958 (cond
5959 ((js2-match-char ?g)
5960 (push ?g flags))
5961 ((js2-match-char ?i)
5962 (push ?i flags))
5963 ((js2-match-char ?m)
5964 (push ?m flags))
5965 ((and (js2-match-char ?u)
5966 (>= js2-language-version 200))
5967 (push ?u flags))
5968 ((and (js2-match-char ?y)
5969 (>= js2-language-version 200))
5970 (push ?y flags))
5971 (t
5972 (setq continue nil))))
5973 (if (js2-alpha-p (js2-peek-char))
5974 (js2-report-scan-error "msg.invalid.re.flag" t
5975 js2-ts-cursor 1))
5976 (js2-set-string-from-buffer token))
5977 (js2-collect-string flags)))
5978
5979 (defun js2-get-first-xml-token ()
5980 (setq js2-ts-xml-open-tags-count 0
5981 js2-ts-is-xml-attribute nil
5982 js2-ts-xml-is-tag-content nil)
5983 (js2-unget-char)
5984 (js2-get-next-xml-token))
5985
5986 (defun js2-xml-discard-string (token)
5987 "Throw away the string in progress and flag an XML parse error."
5988 (setf js2-ts-string-buffer nil
5989 (js2-token-string token) nil)
5990 (js2-report-scan-error "msg.XML.bad.form" t))
5991
5992 (defun js2-get-next-xml-token ()
5993 (setq js2-ts-string-buffer nil) ; for recording the XML
5994 (let ((token (js2-new-token 0))
5995 c result)
5996 (setq result
5997 (catch 'return
5998 (while t
5999 (setq c (js2-get-char))
6000 (cond
6001 ((= c js2-EOF_CHAR)
6002 (throw 'return js2-ERROR))
6003 (js2-ts-xml-is-tag-content
6004 (case c
6005 (?>
6006 (js2-add-to-string c)
6007 (setq js2-ts-xml-is-tag-content nil
6008 js2-ts-is-xml-attribute nil))
6009 (?/
6010 (js2-add-to-string c)
6011 (when (eq ?> (js2-peek-char))
6012 (setq c (js2-get-char))
6013 (js2-add-to-string c)
6014 (setq js2-ts-xml-is-tag-content nil)
6015 (decf js2-ts-xml-open-tags-count)))
6016 (?{
6017 (js2-unget-char)
6018 (js2-set-string-from-buffer token)
6019 (throw 'return js2-XML))
6020 ((?\' ?\")
6021 (js2-add-to-string c)
6022 (unless (js2-read-quoted-string c token)
6023 (throw 'return js2-ERROR)))
6024 (?=
6025 (js2-add-to-string c)
6026 (setq js2-ts-is-xml-attribute t))
6027 ((? ?\t ?\r ?\n)
6028 (js2-add-to-string c))
6029 (t
6030 (js2-add-to-string c)
6031 (setq js2-ts-is-xml-attribute nil)))
6032 (when (and (not js2-ts-xml-is-tag-content)
6033 (zerop js2-ts-xml-open-tags-count))
6034 (js2-set-string-from-buffer token)
6035 (throw 'return js2-XMLEND)))
6036 (t
6037 ;; else not tag content
6038 (case c
6039 (?<
6040 (js2-add-to-string c)
6041 (setq c (js2-peek-char))
6042 (case c
6043 (?!
6044 (setq c (js2-get-char)) ;; skip !
6045 (js2-add-to-string c)
6046 (setq c (js2-peek-char))
6047 (case c
6048 (?-
6049 (setq c (js2-get-char)) ;; skip -
6050 (js2-add-to-string c)
6051 (if (eq c ?-)
6052 (progn
6053 (js2-add-to-string c)
6054 (unless (js2-read-xml-comment token)
6055 (throw 'return js2-ERROR)))
6056 (js2-xml-discard-string token)
6057 (throw 'return js2-ERROR)))
6058 (?\[
6059 (setq c (js2-get-char)) ;; skip [
6060 (js2-add-to-string c)
6061 (if (and (= (js2-get-char) ?C)
6062 (= (js2-get-char) ?D)
6063 (= (js2-get-char) ?A)
6064 (= (js2-get-char) ?T)
6065 (= (js2-get-char) ?A)
6066 (= (js2-get-char) ?\[))
6067 (progn
6068 (js2-add-to-string ?C)
6069 (js2-add-to-string ?D)
6070 (js2-add-to-string ?A)
6071 (js2-add-to-string ?T)
6072 (js2-add-to-string ?A)
6073 (js2-add-to-string ?\[)
6074 (unless (js2-read-cdata token)
6075 (throw 'return js2-ERROR)))
6076 (js2-xml-discard-string token)
6077 (throw 'return js2-ERROR)))
6078 (t
6079 (unless (js2-read-entity token)
6080 (throw 'return js2-ERROR))))
6081 ;; Allow bare CDATA section, e.g.:
6082 ;; let xml = <![CDATA[ foo bar baz ]]>;
6083 (when (zerop js2-ts-xml-open-tags-count)
6084 (throw 'return js2-XMLEND)))
6085 (??
6086 (setq c (js2-get-char)) ;; skip ?
6087 (js2-add-to-string c)
6088 (unless (js2-read-PI token)
6089 (throw 'return js2-ERROR)))
6090 (?/
6091 ;; end tag
6092 (setq c (js2-get-char)) ;; skip /
6093 (js2-add-to-string c)
6094 (when (zerop js2-ts-xml-open-tags-count)
6095 (js2-xml-discard-string token)
6096 (throw 'return js2-ERROR))
6097 (setq js2-ts-xml-is-tag-content t)
6098 (decf js2-ts-xml-open-tags-count))
6099 (t
6100 ;; start tag
6101 (setq js2-ts-xml-is-tag-content t)
6102 (incf js2-ts-xml-open-tags-count))))
6103 (?{
6104 (js2-unget-char)
6105 (js2-set-string-from-buffer token)
6106 (throw 'return js2-XML))
6107 (t
6108 (js2-add-to-string c))))))))
6109 (setf (js2-token-end token) js2-ts-cursor)
6110 (setf (js2-token-type token) result)
6111 result))
6112
6113 (defun js2-read-quoted-string (quote token)
6114 (let (c)
6115 (catch 'return
6116 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6117 (js2-add-to-string c)
6118 (if (eq c quote)
6119 (throw 'return t)))
6120 (js2-xml-discard-string token) ;; throw away string in progress
6121 nil)))
6122
6123 (defun js2-read-xml-comment (token)
6124 (let ((c (js2-get-char)))
6125 (catch 'return
6126 (while (/= c js2-EOF_CHAR)
6127 (catch 'continue
6128 (js2-add-to-string c)
6129 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6130 (setq c (js2-get-char))
6131 (js2-add-to-string c)
6132 (if (eq (js2-peek-char) ?>)
6133 (progn
6134 (setq c (js2-get-char)) ;; skip >
6135 (js2-add-to-string c)
6136 (throw 'return t))
6137 (throw 'continue nil)))
6138 (setq c (js2-get-char))))
6139 (js2-xml-discard-string token)
6140 nil)))
6141
6142 (defun js2-read-cdata (token)
6143 (let ((c (js2-get-char)))
6144 (catch 'return
6145 (while (/= c js2-EOF_CHAR)
6146 (catch 'continue
6147 (js2-add-to-string c)
6148 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6149 (setq c (js2-get-char))
6150 (js2-add-to-string c)
6151 (if (eq (js2-peek-char) ?>)
6152 (progn
6153 (setq c (js2-get-char)) ;; Skip >
6154 (js2-add-to-string c)
6155 (throw 'return t))
6156 (throw 'continue nil)))
6157 (setq c (js2-get-char))))
6158 (js2-xml-discard-string token)
6159 nil)))
6160
6161 (defun js2-read-entity (token)
6162 (let ((decl-tags 1)
6163 c)
6164 (catch 'return
6165 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6166 (js2-add-to-string c)
6167 (case c
6168 (?<
6169 (incf decl-tags))
6170 (?>
6171 (decf decl-tags)
6172 (if (zerop decl-tags)
6173 (throw 'return t)))))
6174 (js2-xml-discard-string token)
6175 nil)))
6176
6177 (defun js2-read-PI (token)
6178 "Scan an XML processing instruction."
6179 (let (c)
6180 (catch 'return
6181 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6182 (js2-add-to-string c)
6183 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6184 (setq c (js2-get-char)) ;; Skip >
6185 (js2-add-to-string c)
6186 (throw 'return t)))
6187 (js2-xml-discard-string token)
6188 nil)))
6189
6190 ;;; Highlighting
6191
6192 (defun js2-set-face (beg end face &optional record)
6193 "Fontify a region. If RECORD is non-nil, record for later."
6194 (when (plusp js2-highlight-level)
6195 (setq beg (min (point-max) beg)
6196 beg (max (point-min) beg)
6197 end (min (point-max) end)
6198 end (max (point-min) end))
6199 (if record
6200 (push (list beg end face) js2-mode-fontifications)
6201 (put-text-property beg end 'font-lock-face face))))
6202
6203 (defsubst js2-clear-face (beg end)
6204 (remove-text-properties beg end '(font-lock-face nil
6205 help-echo nil
6206 point-entered nil
6207 c-in-sws nil)))
6208
6209 (defconst js2-ecma-global-props
6210 (concat "^"
6211 (regexp-opt
6212 '("Infinity" "NaN" "undefined" "arguments") t)
6213 "$")
6214 "Value properties of the Ecma-262 Global Object.
6215 Shown at or above `js2-highlight-level' 2.")
6216
6217 ;; might want to add the name "arguments" to this list?
6218 (defconst js2-ecma-object-props
6219 (concat "^"
6220 (regexp-opt
6221 '("prototype" "__proto__" "__parent__") t)
6222 "$")
6223 "Value properties of the Ecma-262 Object constructor.
6224 Shown at or above `js2-highlight-level' 2.")
6225
6226 (defconst js2-ecma-global-funcs
6227 (concat
6228 "^"
6229 (regexp-opt
6230 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6231 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6232 "$")
6233 "Function properties of the Ecma-262 Global object.
6234 Shown at or above `js2-highlight-level' 2.")
6235
6236 (defconst js2-ecma-number-props
6237 (concat "^"
6238 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6239 "NEGATIVE_INFINITY"
6240 "POSITIVE_INFINITY") t)
6241 "$")
6242 "Properties of the Ecma-262 Number constructor.
6243 Shown at or above `js2-highlight-level' 2.")
6244
6245 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6246 "Properties of the Ecma-262 Date constructor.
6247 Shown at or above `js2-highlight-level' 2.")
6248
6249 (defconst js2-ecma-math-props
6250 (concat "^"
6251 (regexp-opt
6252 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6253 t)
6254 "$")
6255 "Properties of the Ecma-262 Math object.
6256 Shown at or above `js2-highlight-level' 2.")
6257
6258 (defconst js2-ecma-math-funcs
6259 (concat "^"
6260 (regexp-opt
6261 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6262 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6263 "$")
6264 "Function properties of the Ecma-262 Math object.
6265 Shown at or above `js2-highlight-level' 2.")
6266
6267 (defconst js2-ecma-function-props
6268 (concat
6269 "^"
6270 (regexp-opt
6271 '(;; properties of the Object prototype object
6272 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6273 "toLocaleString" "toString" "valueOf"
6274 ;; properties of the Function prototype object
6275 "apply" "call"
6276 ;; properties of the Array prototype object
6277 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6278 "splice" "unshift"
6279 ;; properties of the String prototype object
6280 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6281 "localeCompare" "match" "replace" "search" "split" "substring"
6282 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6283 "toUpperCase"
6284 ;; properties of the Number prototype object
6285 "toExponential" "toFixed" "toPrecision"
6286 ;; properties of the Date prototype object
6287 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6288 "getMinutes" "getMonth" "getSeconds" "getTime"
6289 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6290 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6291 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6292 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6293 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6294 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6295 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6296 "toTimeString" "toUTCString"
6297 ;; properties of the RegExp prototype object
6298 "exec" "test"
6299 ;; properties of the JSON prototype object
6300 "parse" "stringify"
6301 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6302 "toSource" "__defineGetter__" "__defineSetter__"
6303 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6304 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6305 t)
6306 "$")
6307 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6308 Shown at or above `js2-highlight-level' 3.")
6309
6310 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6311 (let ((target-name (and target
6312 (js2-name-node-p target)
6313 (js2-name-node-name target)))
6314 (prop-name (if prop (js2-name-node-name prop)))
6315 (level2 (>= js2-highlight-level 2))
6316 (level3 (>= js2-highlight-level 3)))
6317 (when level2
6318 (let ((face
6319 (if call-p
6320 (cond
6321 ((and target prop)
6322 (cond
6323 ((and level3 (string-match js2-ecma-function-props prop-name))
6324 'font-lock-builtin-face)
6325 ((and target-name prop)
6326 (cond
6327 ((string= target-name "Date")
6328 (if (string-match js2-ecma-date-props prop-name)
6329 'font-lock-builtin-face))
6330 ((string= target-name "Math")
6331 (if (string-match js2-ecma-math-funcs prop-name)
6332 'font-lock-builtin-face))))))
6333 (prop
6334 (if (string-match js2-ecma-global-funcs prop-name)
6335 'font-lock-builtin-face)))
6336 (cond
6337 ((and target prop)
6338 (cond
6339 ((string= target-name "Number")
6340 (if (string-match js2-ecma-number-props prop-name)
6341 'font-lock-constant-face))
6342 ((string= target-name "Math")
6343 (if (string-match js2-ecma-math-props prop-name)
6344 'font-lock-constant-face))))
6345 (prop
6346 (if (string-match js2-ecma-object-props prop-name)
6347 'font-lock-constant-face))))))
6348 (when face
6349 (let ((pos (+ (js2-node-pos parent) ; absolute
6350 (js2-node-pos prop)))) ; relative
6351 (js2-set-face pos
6352 (+ pos (js2-node-len prop))
6353 face 'record)))))))
6354
6355 (defun js2-parse-highlight-member-expr-node (node)
6356 "Perform syntax highlighting of EcmaScript built-in properties.
6357 The variable `js2-highlight-level' governs this highighting."
6358 (let (face target prop name pos end parent call-p callee)
6359 (cond
6360 ;; case 1: simple name, e.g. foo
6361 ((js2-name-node-p node)
6362 (setq name (js2-name-node-name node))
6363 ;; possible for name to be nil in rare cases - saw it when
6364 ;; running js2-mode on an elisp buffer. Might as well try to
6365 ;; make it so js2-mode never barfs.
6366 (when name
6367 (setq face (if (string-match js2-ecma-global-props name)
6368 'font-lock-constant-face))
6369 (when face
6370 (setq pos (js2-node-pos node)
6371 end (+ pos (js2-node-len node)))
6372 (js2-set-face pos end face 'record))))
6373 ;; case 2: property access or function call
6374 ((or (js2-prop-get-node-p node)
6375 ;; highlight function call if expr is a prop-get node
6376 ;; or a plain name (i.e. unqualified function call)
6377 (and (setq call-p (js2-call-node-p node))
6378 (setq callee (js2-call-node-target node)) ; separate setq!
6379 (or (js2-prop-get-node-p callee)
6380 (js2-name-node-p callee))))
6381 (setq parent node
6382 node (if call-p callee node))
6383 (if (and call-p (js2-name-node-p callee))
6384 (setq prop callee)
6385 (setq target (js2-prop-get-node-left node)
6386 prop (js2-prop-get-node-right node)))
6387 (cond
6388 ((js2-name-node-p prop)
6389 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6390 (js2-parse-highlight-prop-get parent target prop call-p))
6391 ((js2-name-node-p target)
6392 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6393 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6394
6395 (defun js2-parse-highlight-member-expr-fn-name (expr)
6396 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6397 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6398 We currently only handle the case where the last component is a prop-get
6399 of a simple name. Called before EXPR has a parent node."
6400 (let (pos
6401 (name (and (js2-prop-get-node-p expr)
6402 (js2-prop-get-node-right expr))))
6403 (when (js2-name-node-p name)
6404 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6405 (js2-node-pos name)))
6406 (+ pos (js2-node-len name))
6407 'font-lock-function-name-face
6408 'record))))
6409
6410 ;; source: http://jsdoc.sourceforge.net/
6411 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6412 ;; allows type specifications, and needs work before entering the wild.
6413
6414 (defconst js2-jsdoc-param-tag-regexp
6415 (concat "^\\s-*\\*+\\s-*\\(@"
6416 "\\(?:param\\|argument\\)"
6417 "\\)"
6418 "\\s-*\\({[^}]+}\\)?" ; optional type
6419 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6420 "\\>")
6421 "Matches jsdoc tags with optional type and optional param name.")
6422
6423 (defconst js2-jsdoc-typed-tag-regexp
6424 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6425 (regexp-opt
6426 '("enum"
6427 "extends"
6428 "field"
6429 "id"
6430 "implements"
6431 "lends"
6432 "mods"
6433 "requires"
6434 "return"
6435 "returns"
6436 "throw"
6437 "throws"))
6438 "\\)\\)\\s-*\\({[^}]+}\\)?")
6439 "Matches jsdoc tags with optional type.")
6440
6441 (defconst js2-jsdoc-arg-tag-regexp
6442 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6443 (regexp-opt
6444 '("alias"
6445 "augments"
6446 "borrows"
6447 "bug"
6448 "base"
6449 "config"
6450 "default"
6451 "define"
6452 "exception"
6453 "function"
6454 "member"
6455 "memberOf"
6456 "name"
6457 "namespace"
6458 "property"
6459 "since"
6460 "suppress"
6461 "this"
6462 "throws"
6463 "type"
6464 "version"))
6465 "\\)\\)\\s-+\\([^ \t]+\\)")
6466 "Matches jsdoc tags with a single argument.")
6467
6468 (defconst js2-jsdoc-empty-tag-regexp
6469 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6470 (regexp-opt
6471 '("addon"
6472 "author"
6473 "class"
6474 "const"
6475 "constant"
6476 "constructor"
6477 "constructs"
6478 "deprecated"
6479 "desc"
6480 "description"
6481 "event"
6482 "example"
6483 "exec"
6484 "export"
6485 "fileoverview"
6486 "final"
6487 "function"
6488 "hidden"
6489 "ignore"
6490 "implicitCast"
6491 "inheritDoc"
6492 "inner"
6493 "interface"
6494 "license"
6495 "noalias"
6496 "noshadow"
6497 "notypecheck"
6498 "override"
6499 "owner"
6500 "preserve"
6501 "preserveTry"
6502 "private"
6503 "protected"
6504 "public"
6505 "static"
6506 "supported"
6507 ))
6508 "\\)\\)\\s-*")
6509 "Matches empty jsdoc tags.")
6510
6511 (defconst js2-jsdoc-link-tag-regexp
6512 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6513 "Matches a jsdoc link or code tag.")
6514
6515 (defconst js2-jsdoc-see-tag-regexp
6516 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6517 "Matches a jsdoc @see tag.")
6518
6519 (defconst js2-jsdoc-html-tag-regexp
6520 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6521 "Matches a simple (no attributes) html start- or end-tag.")
6522
6523 (defun js2-jsdoc-highlight-helper ()
6524 (js2-set-face (match-beginning 1)
6525 (match-end 1)
6526 'js2-jsdoc-tag)
6527 (if (match-beginning 2)
6528 (if (save-excursion
6529 (goto-char (match-beginning 2))
6530 (= (char-after) ?{))
6531 (js2-set-face (1+ (match-beginning 2))
6532 (1- (match-end 2))
6533 'js2-jsdoc-type)
6534 (js2-set-face (match-beginning 2)
6535 (match-end 2)
6536 'js2-jsdoc-value)))
6537 (if (match-beginning 3)
6538 (js2-set-face (match-beginning 3)
6539 (match-end 3)
6540 'js2-jsdoc-value)))
6541
6542 (defun js2-highlight-jsdoc (ast)
6543 "Highlight doc comment tags."
6544 (let ((comments (js2-ast-root-comments ast))
6545 beg end)
6546 (save-excursion
6547 (dolist (node comments)
6548 (when (eq (js2-comment-node-format node) 'jsdoc)
6549 (setq beg (js2-node-abs-pos node)
6550 end (+ beg (js2-node-len node)))
6551 (save-restriction
6552 (narrow-to-region beg end)
6553 (dolist (re (list js2-jsdoc-param-tag-regexp
6554 js2-jsdoc-typed-tag-regexp
6555 js2-jsdoc-arg-tag-regexp
6556 js2-jsdoc-link-tag-regexp
6557 js2-jsdoc-see-tag-regexp
6558 js2-jsdoc-empty-tag-regexp))
6559 (goto-char beg)
6560 (while (re-search-forward re nil t)
6561 (js2-jsdoc-highlight-helper)))
6562 ;; simple highlighting for html tags
6563 (goto-char beg)
6564 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6565 (js2-set-face (match-beginning 1)
6566 (match-end 1)
6567 'js2-jsdoc-html-tag-delimiter)
6568 (js2-set-face (match-beginning 2)
6569 (match-end 2)
6570 'js2-jsdoc-html-tag-name)
6571 (js2-set-face (match-beginning 3)
6572 (match-end 3)
6573 'js2-jsdoc-html-tag-delimiter))))))))
6574
6575 (defun js2-highlight-assign-targets (_node left right)
6576 "Highlight function properties and external variables."
6577 (let (leftpos name)
6578 ;; highlight vars and props assigned function values
6579 (when (js2-function-node-p right)
6580 (cond
6581 ;; var foo = function() {...}
6582 ((js2-name-node-p left)
6583 (setq name left))
6584 ;; foo.bar.baz = function() {...}
6585 ((and (js2-prop-get-node-p left)
6586 (js2-name-node-p (js2-prop-get-node-right left)))
6587 (setq name (js2-prop-get-node-right left))))
6588 (when name
6589 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6590 (+ leftpos (js2-node-len name))
6591 'font-lock-function-name-face
6592 'record)))))
6593
6594 (defun js2-record-name-node (node)
6595 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6596 later. NODE must be a name node."
6597 (let ((leftpos (js2-node-abs-pos node)))
6598 (push (list node js2-current-scope
6599 leftpos
6600 (+ leftpos (js2-node-len node)))
6601 js2-recorded-identifiers)))
6602
6603 (defun js2-highlight-undeclared-vars ()
6604 "After entire parse is finished, look for undeclared variable references.
6605 We have to wait until entire buffer is parsed, since JavaScript permits var
6606 decls to occur after they're used.
6607
6608 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6609 it is considered declared."
6610 (let (name)
6611 (dolist (entry js2-recorded-identifiers)
6612 (destructuring-bind (name-node scope pos end) entry
6613 (setq name (js2-name-node-name name-node))
6614 (unless (or (member name js2-global-externs)
6615 (member name js2-default-externs)
6616 (member name js2-additional-externs)
6617 (js2-get-defining-scope scope name))
6618 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6619 'js2-external-variable))))
6620 (setq js2-recorded-identifiers nil)))
6621
6622 (defun js2-set-default-externs ()
6623 "Set the value of `js2-default-externs' based on the various
6624 `js2-include-?-externs' variables."
6625 (setq js2-default-externs
6626 (append js2-ecma-262-externs
6627 (if js2-include-browser-externs js2-browser-externs)
6628 (if (and js2-include-browser-externs
6629 (>= js2-language-version 200)) js2-harmony-externs)
6630 (if js2-include-rhino-externs js2-rhino-externs)
6631 (if js2-include-node-externs js2-node-externs)
6632 (if (or js2-include-browser-externs js2-include-node-externs)
6633 js2-typed-array-externs))))
6634
6635 (defun js2-apply-jslint-globals ()
6636 (setq js2-additional-externs
6637 (nconc (js2-get-jslint-globals)
6638 js2-additional-externs)))
6639
6640 (defun js2-get-jslint-globals ()
6641 (loop for node in (js2-ast-root-comments js2-mode-ast)
6642 when (and (eq 'block (js2-comment-node-format node))
6643 (save-excursion
6644 (goto-char (js2-node-abs-pos node))
6645 (looking-at "/\\*global ")))
6646 append (js2-get-jslint-globals-in
6647 (match-end 0)
6648 (js2-node-abs-end node))))
6649
6650 (defun js2-get-jslint-globals-in (beg end)
6651 (let (res)
6652 (save-excursion
6653 (goto-char beg)
6654 (while (re-search-forward js2-mode-identifier-re end t)
6655 (let ((match (match-string 0)))
6656 (unless (member match '("true" "false"))
6657 (push match res)))))
6658 (nreverse res)))
6659
6660 ;;; IMenu support
6661
6662 ;; We currently only support imenu, but eventually should support speedbar and
6663 ;; possibly other browsing mechanisms.
6664
6665 ;; The basic strategy is to identify function assignment targets of the form
6666 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6667 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6668 ;; for imenu after parsing is finished.
6669
6670 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6671 ;; JavaScript, and the general problem is undecidable. However, several forms
6672 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6673 ;; include:
6674
6675 ;; function foo() -- function declaration
6676 ;; foo = function() -- function expression assigned to variable
6677 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6678 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6679 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6680 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6681 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6682 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6683 ;; function foo() {function bar() {...}} -- nested function
6684 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6685
6686 ;; This list boils down to a few forms that can be combined recursively.
6687 ;; Top-level named function declarations include both the left-hand (name)
6688 ;; and the right-hand (function value) expressions needed to produce an imenu
6689 ;; entry. The other "right-hand" forms we need to look for are:
6690 ;; - functions declared as props/getters/setters in object literals
6691 ;; - nested named function declarations
6692 ;; The "left-hand" expressions that functions can be assigned to include:
6693 ;; - local/global variables
6694 ;; - nested property-get expressions like a.b.c.d
6695 ;; - element gets like foo[10] or foo['bar'] where the index
6696 ;; expression can be trivially converted to a property name. They
6697 ;; effectively then become property gets.
6698
6699 ;; All the different definition types are canonicalized into the form
6700 ;; foo.bar.baz = position-of-function-keyword
6701
6702 ;; We need to build a trie-like structure for imenu. As an example,
6703 ;; consider the following JavaScript code:
6704
6705 ;; a = function() {...} // function at position 5
6706 ;; b = function() {...} // function at position 25
6707 ;; foo = function() {...} // function at position 100
6708 ;; foo.bar = function() {...} // function at position 200
6709 ;; foo.bar.baz = function() {...} // function at position 300
6710 ;; foo.bar.zab = function() {...} // function at position 400
6711
6712 ;; During parsing we accumulate an entry for each definition in
6713 ;; the variable `js2-imenu-recorder', like so:
6714
6715 ;; '((fn a 5)
6716 ;; (fn b 25)
6717 ;; (fn foo 100)
6718 ;; (fn foo bar 200)
6719 ;; (fn foo bar baz 300)
6720 ;; (fn foo bar zab 400))
6721
6722 ;; Where 'fn' is the respective function node.
6723 ;; After parsing these entries are merged into this alist-trie:
6724
6725 ;; '((a . 1)
6726 ;; (b . 2)
6727 ;; (foo (<definition> . 3)
6728 ;; (bar (<definition> . 6)
6729 ;; (baz . 100)
6730 ;; (zab . 200))))
6731
6732 ;; Note the wacky need for a <definition> name. The token can be anything
6733 ;; that isn't a valid JavaScript identifier, because you might make foo
6734 ;; a function and then start setting properties on it that are also functions.
6735
6736 (defun js2-prop-node-name (node)
6737 "Return the name of a node that may be a property-get/property-name.
6738 If NODE is not a valid name-node, string-node or integral number-node,
6739 returns nil. Otherwise returns the string name/value of the node."
6740 (cond
6741 ((js2-name-node-p node)
6742 (js2-name-node-name node))
6743 ((js2-string-node-p node)
6744 (js2-string-node-value node))
6745 ((and (js2-number-node-p node)
6746 (string-match "^[0-9]+$" (js2-number-node-value node)))
6747 (js2-number-node-value node))
6748 ((js2-this-node-p node)
6749 "this")))
6750
6751 (defun js2-node-qname-component (node)
6752 "Return the name of this node, if it contributes to a qname.
6753 Returns nil if the node doesn't contribute."
6754 (copy-sequence
6755 (or (js2-prop-node-name node)
6756 (if (and (js2-function-node-p node)
6757 (js2-function-node-name node))
6758 (js2-name-node-name (js2-function-node-name node))))))
6759
6760 (defun js2-record-imenu-entry (fn-node qname pos)
6761 "Add an entry to `js2-imenu-recorder'.
6762 FN-NODE should be the current item's function node.
6763
6764 Associate FN-NODE with its QNAME for later lookup.
6765 This is used in postprocessing the chain list. For each chain, we find
6766 the parent function, look up its qname, then prepend a copy of it to the chain."
6767 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6768 (unless js2-imenu-function-map
6769 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6770 (puthash fn-node qname js2-imenu-function-map))
6771
6772 (defun js2-record-imenu-functions (node &optional var)
6773 "Record function definitions for imenu.
6774 NODE is a function node or an object literal.
6775 VAR, if non-nil, is the expression that NODE is being assigned to.
6776 When passed arguments of wrong type, does nothing."
6777 (when js2-parse-ide-mode
6778 (let ((fun-p (js2-function-node-p node))
6779 qname fname-node)
6780 (cond
6781 ;; non-anonymous function declaration?
6782 ((and fun-p
6783 (not var)
6784 (setq fname-node (js2-function-node-name node)))
6785 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6786 ;; for remaining forms, compute left-side tree branch first
6787 ((and var (setq qname (js2-compute-nested-prop-get var)))
6788 (cond
6789 ;; foo.bar.baz = function
6790 (fun-p
6791 (js2-record-imenu-entry node qname (js2-node-pos node)))
6792 ;; foo.bar.baz = object-literal
6793 ;; look for nested functions: {a: {b: function() {...} }}
6794 ((js2-object-node-p node)
6795 ;; Node position here is still absolute, since the parser
6796 ;; passes the assignment target and value expressions
6797 ;; to us before they are added as children of the assignment node.
6798 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6799
6800 (defun js2-compute-nested-prop-get (node)
6801 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6802 component nodes as a list. Otherwise return nil. Element-gets are treated
6803 as property-gets if the index expression is a string, or a positive integer."
6804 (let (left right head)
6805 (cond
6806 ((or (js2-name-node-p node)
6807 (js2-this-node-p node))
6808 (list node))
6809 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6810 ((js2-prop-get-node-p node) ; foo.bar
6811 (setq left (js2-prop-get-node-left node)
6812 right (js2-prop-get-node-right node))
6813 (if (setq head (js2-compute-nested-prop-get left))
6814 (nconc head (list right))))
6815 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6816 (setq left (js2-elem-get-node-target node)
6817 right (js2-elem-get-node-element node))
6818 (if (or (js2-string-node-p right) ; ['bar']
6819 (and (js2-number-node-p right) ; [10]
6820 (string-match "^[0-9]+$"
6821 (js2-number-node-value right))))
6822 (if (setq head (js2-compute-nested-prop-get left))
6823 (nconc head (list right))))))))
6824
6825 (defun js2-record-object-literal (node qname pos)
6826 "Recursively process an object literal looking for functions.
6827 NODE is an object literal that is the right-hand child of an assignment
6828 expression. QNAME is a list of nodes representing the assignment target,
6829 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6830 POS is the absolute position of the node.
6831 We do a depth-first traversal of NODE. For any functions we find,
6832 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6833 (let (right)
6834 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6835 (let ((left (js2-infix-node-left e))
6836 ;; Element positions are relative to the parent position.
6837 (pos (+ pos (js2-node-pos e))))
6838 (cond
6839 ;; foo: function() {...}
6840 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6841 (when (js2-prop-node-name left)
6842 ;; As a policy decision, we record the position of the property,
6843 ;; not the position of the `function' keyword, since the property
6844 ;; is effectively the name of the function.
6845 (js2-record-imenu-entry right (append qname (list left)) pos)))
6846 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6847 ((js2-object-node-p right)
6848 (js2-record-object-literal right
6849 (append qname (list (js2-infix-node-left e)))
6850 (+ pos (js2-node-pos right)))))))))
6851
6852 (defun js2-node-top-level-decl-p (node)
6853 "Return t if NODE's name is defined in the top-level scope.
6854 Also returns t if NODE's name is not defined in any scope, since it implies
6855 that it's an external variable, which must also be in the top-level scope."
6856 (let* ((name (js2-prop-node-name node))
6857 (this-scope (js2-node-get-enclosing-scope node))
6858 defining-scope)
6859 (cond
6860 ((js2-this-node-p node)
6861 nil)
6862 ((null this-scope)
6863 t)
6864 ((setq defining-scope (js2-get-defining-scope this-scope name))
6865 (js2-ast-root-p defining-scope))
6866 (t t))))
6867
6868 (defun js2-wrapper-function-p (node)
6869 "Return t if NODE is a function expression that's immediately invoked.
6870 NODE must be `js2-function-node'."
6871 (let ((parent (js2-node-parent node)))
6872 (or
6873 ;; function(){...}();
6874 (js2-call-node-p parent)
6875 (and (js2-paren-node-p parent)
6876 ;; (function(){...})();
6877 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6878 ;; (function(){...}).call(this);
6879 (and (js2-prop-get-node-p parent)
6880 (member (js2-name-node-name (js2-prop-get-node-right parent))
6881 '("call" "apply"))
6882 (js2-call-node-p (js2-node-parent parent))))))))
6883
6884 (defun js2-browse-postprocess-chains (entries)
6885 "Modify function-declaration name chains after parsing finishes.
6886 Some of the information is only available after the parse tree is complete.
6887 For instance, processing a nested scope requires a parent function node."
6888 (let (result fn parent-qname p elem)
6889 (dolist (entry entries)
6890 ;; function node goes first
6891 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6892 ;; Examine head's defining scope:
6893 ;; Pre-processed chain, or top-level/external, keep as-is.
6894 (if (or (stringp head) (js2-node-top-level-decl-p head))
6895 (push chain result)
6896 (when (js2-this-node-p head)
6897 (setq chain (cdr chain))) ; discard this-node
6898 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6899 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6900 (when (eq parent-qname 'not-found)
6901 ;; anonymous function expressions are not recorded
6902 ;; during the parse, so we need to handle this case here
6903 (setq parent-qname
6904 (if (js2-wrapper-function-p fn)
6905 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6906 (if (js2-ast-root-p grandparent)
6907 nil
6908 (gethash grandparent js2-imenu-function-map 'skip)))
6909 'skip))
6910 (puthash fn parent-qname js2-imenu-function-map))
6911 (unless (eq parent-qname 'skip)
6912 ;; prefix parent fn qname to this chain.
6913 (let ((qname (append parent-qname chain)))
6914 (puthash current-fn (butlast qname) js2-imenu-function-map)
6915 (push qname result)))))))
6916 ;; finally replace each node in each chain with its name.
6917 (dolist (chain result)
6918 (setq p chain)
6919 (while p
6920 (if (js2-node-p (setq elem (car p)))
6921 (setcar p (js2-node-qname-component elem)))
6922 (setq p (cdr p))))
6923 result))
6924
6925 ;; Merge name chains into a trie-like tree structure of nested lists.
6926 ;; To simplify construction of the trie, we first build it out using the rule
6927 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6928 ;; [key, num-or-list]. The second element can be a number; if so, this key
6929 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6930 ;; associated with the key at this level.) Otherwise the second element is
6931 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6932 ;; a simple recursive formulation.
6933 ;;
6934 ;; js2-mode is building the data structure for imenu. The imenu documentation
6935 ;; claims that it's the structure above, but in practice it wants the children
6936 ;; at the same list level as the key for that level, which is how I've drawn
6937 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6938 ;; list wrapper around the children at each level.
6939 ;;
6940 ;; A completed nested imenu-alist entry looks like this:
6941 ;; '(("foo"
6942 ;; ("<definition>" . 7)
6943 ;; ("bar"
6944 ;; ("a" . 40)
6945 ;; ("b" . 60))))
6946 ;;
6947 ;; In particular, the documentation for `imenu--index-alist' says that
6948 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6949 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6950
6951 (defun js2-treeify (lst)
6952 "Convert (a b c d) to (a ((b ((c d)))))."
6953 (if (null (cddr lst)) ; list length <= 2
6954 lst
6955 (list (car lst) (list (js2-treeify (cdr lst))))))
6956
6957 (defun js2-build-alist-trie (chains trie)
6958 "Merge declaration name chains into a trie-like alist structure for imenu.
6959 CHAINS is the qname chain list produced during parsing. TRIE is a
6960 list of elements built up so far."
6961 (let (head tail pos branch kids)
6962 (dolist (chain chains)
6963 (setq head (car chain)
6964 tail (cdr chain)
6965 pos (if (numberp (car tail)) (car tail))
6966 branch (js2-find-if (lambda (n)
6967 (string= (car n) head))
6968 trie)
6969 kids (second branch))
6970 (cond
6971 ;; case 1: this key isn't in the trie yet
6972 ((null branch)
6973 (if trie
6974 (setcdr (last trie) (list (js2-treeify chain)))
6975 (setq trie (list (js2-treeify chain)))))
6976 ;; case 2: key is present with a single number entry: replace w/ list
6977 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6978 ;; ("<definition>" 20)))
6979 ((numberp kids)
6980 (setcar (cdr branch)
6981 (list (list "<definition-1>" kids)
6982 (if pos
6983 (list "<definition-2>" pos)
6984 (js2-treeify tail)))))
6985 ;; case 3: key is there (with kids), and we're a number entry
6986 (pos
6987 (setcdr (last kids)
6988 (list
6989 (list (format "<definition-%d>"
6990 (1+ (loop for kid in kids
6991 count (eq ?< (aref (car kid) 0)))))
6992 pos))))
6993 ;; case 4: key is there with kids, need to merge in our chain
6994 (t
6995 (js2-build-alist-trie (list tail) kids))))
6996 trie))
6997
6998 (defun js2-flatten-trie (trie)
6999 "Convert TRIE to imenu-format.
7000 Recurses through nodes, and for each one whose second element is a list,
7001 appends the list's flattened elements to the current element. Also
7002 changes the tails into conses. For instance, this pre-flattened trie
7003
7004 '(a ((b 20)
7005 (c ((d 30)
7006 (e 40)))))
7007
7008 becomes
7009
7010 '(a (b . 20)
7011 (c (d . 30)
7012 (e . 40)))
7013
7014 Note that the root of the trie has no key, just a list of chains.
7015 This is also true for the value of any key with multiple children,
7016 e.g. key 'c' in the example above."
7017 (cond
7018 ((listp (car trie))
7019 (mapcar #'js2-flatten-trie trie))
7020 (t
7021 (if (numberp (second trie))
7022 (cons (car trie) (second trie))
7023 ;; else pop list and append its kids
7024 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7025
7026 (defun js2-build-imenu-index ()
7027 "Turn `js2-imenu-recorder' into an imenu data structure."
7028 (unless (eq js2-imenu-recorder 'empty)
7029 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7030 (result (js2-build-alist-trie chains nil)))
7031 (js2-flatten-trie result))))
7032
7033 (defun js2-test-print-chains (chains)
7034 "Print a list of qname chains.
7035 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7036 i.e. one or more nodes, and an integer position as the list tail."
7037 (mapconcat (lambda (chain)
7038 (concat "("
7039 (mapconcat (lambda (elem)
7040 (if (js2-node-p elem)
7041 (or (js2-node-qname-component elem)
7042 "nil")
7043 (number-to-string elem)))
7044 chain
7045 " ")
7046 ")"))
7047 chains
7048 "\n"))
7049
7050 ;;; Parser
7051
7052 (defconst js2-version "1.8.5"
7053 "Version of JavaScript supported.")
7054
7055 (defun js2-record-face (face &optional token)
7056 "Record a style run of FACE for TOKEN or the current token."
7057 (unless token (setq token (js2-current-token)))
7058 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7059
7060 (defsubst js2-node-end (n)
7061 "Computes the absolute end of node N.
7062 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7063 is only true until the node is added to its parent; i.e., while parsing."
7064 (+ (js2-node-pos n)
7065 (js2-node-len n)))
7066
7067 (defun js2-record-comment (token)
7068 "Record a comment in `js2-scanned-comments'."
7069 (let ((ct (js2-token-comment-type token))
7070 (beg (js2-token-beg token))
7071 (end (js2-token-end token)))
7072 (push (make-js2-comment-node :len (- end beg)
7073 :format ct)
7074 js2-scanned-comments)
7075 (when js2-parse-ide-mode
7076 (js2-record-face (if (eq ct 'jsdoc)
7077 'font-lock-doc-face
7078 'font-lock-comment-face)
7079 token)
7080 (when (memq ct '(html preprocessor))
7081 ;; Tell cc-engine the bounds of the comment.
7082 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7083
7084 (defun js2-peek-token ()
7085 "Return the next token type without consuming it.
7086 If `js2-ti-lookahead' is positive, return the type of next token
7087 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7088 (if (not (zerop js2-ti-lookahead))
7089 (js2-token-type
7090 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7091 (let ((tt (js2-get-token-internal)))
7092 (js2-unget-token)
7093 tt)))
7094
7095 (defalias 'js2-next-token 'js2-get-token)
7096
7097 (defun js2-match-token (match &optional dont-unget)
7098 "Get next token and return t if it matches MATCH, a bytecode.
7099 Returns nil and consumes nothing if MATCH is not the next token."
7100 (if (/= (js2-get-token) match)
7101 (ignore (unless dont-unget (js2-unget-token)))
7102 t))
7103
7104 (defun js2-match-contextual-kwd (name)
7105 "Consume and return t if next token is `js2-NAME', and its
7106 string is NAME. Returns nil and keeps current token otherwise."
7107 (if (or (/= (js2-get-token) js2-NAME)
7108 (not (string= (js2-current-token-string) name)))
7109 (progn
7110 (js2-unget-token)
7111 nil)
7112 (js2-record-face 'font-lock-keyword-face)
7113 t))
7114
7115 (defun js2-valid-prop-name-token (tt)
7116 (or (= tt js2-NAME)
7117 (and js2-allow-keywords-as-property-names
7118 (plusp tt)
7119 (or (= tt js2-RESERVED)
7120 (aref js2-kwd-tokens tt)))))
7121
7122 (defun js2-match-prop-name ()
7123 "Consume token and return t if next token is a valid property name.
7124 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7125 is non-nil and it's a keyword token."
7126 (if (js2-valid-prop-name-token (js2-get-token))
7127 t
7128 (js2-unget-token)
7129 nil))
7130
7131 (defun js2-must-match-prop-name (msg-id &optional pos len)
7132 (if (js2-match-prop-name)
7133 t
7134 (js2-report-error msg-id nil pos len)
7135 nil))
7136
7137 (defun js2-peek-token-or-eol ()
7138 "Return js2-EOL if the next token immediately follows a newline.
7139 Else returns the next token. Used in situations where we don't
7140 consider certain token types valid if they are preceded by a newline.
7141 One example is the postfix ++ or -- operator, which has to be on the
7142 same line as its operand."
7143 (let ((tt (js2-get-token))
7144 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7145 (js2-unget-token)
7146 (if follows-eol
7147 js2-EOL
7148 tt)))
7149
7150 (defun js2-must-match (token msg-id &optional pos len)
7151 "Match next token to token code TOKEN, or record a syntax error.
7152 MSG-ID is the error message to report if the match fails.
7153 Returns t on match, nil if no match."
7154 (if (js2-match-token token t)
7155 t
7156 (js2-report-error msg-id nil pos len)
7157 (js2-unget-token)
7158 nil))
7159
7160 (defun js2-must-match-name (msg-id)
7161 (if (js2-match-token js2-NAME t)
7162 t
7163 (if (eq (js2-current-token-type) js2-RESERVED)
7164 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7165 (js2-report-error msg-id)
7166 (js2-unget-token))
7167 nil))
7168
7169 (defsubst js2-inside-function ()
7170 (plusp js2-nesting-of-function))
7171
7172 (defun js2-set-requires-activation ()
7173 (if (js2-function-node-p js2-current-script-or-fn)
7174 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7175
7176 (defun js2-check-activation-name (name _token)
7177 (when (js2-inside-function)
7178 ;; skip language-version 1.2 check from Rhino
7179 (if (or (string= "arguments" name)
7180 (and js2-compiler-activation-names ; only used in codegen
7181 (gethash name js2-compiler-activation-names)))
7182 (js2-set-requires-activation))))
7183
7184 (defun js2-set-is-generator ()
7185 (let ((fn-node js2-current-script-or-fn))
7186 (when (and (js2-function-node-p fn-node)
7187 (not (js2-function-node-generator-type fn-node)))
7188 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7189
7190 (defun js2-must-have-xml ()
7191 (unless js2-compiler-xml-available
7192 (js2-report-error "msg.XML.not.available")))
7193
7194 (defun js2-push-scope (scope)
7195 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7196 (assert (js2-scope-p scope))
7197 (assert (null (js2-scope-parent-scope scope)))
7198 (assert (not (eq js2-current-scope scope)))
7199 (setf (js2-scope-parent-scope scope) js2-current-scope
7200 js2-current-scope scope))
7201
7202 (defsubst js2-pop-scope ()
7203 (setq js2-current-scope
7204 (js2-scope-parent-scope js2-current-scope)))
7205
7206 (defun js2-enter-loop (loop-node)
7207 (push loop-node js2-loop-set)
7208 (push loop-node js2-loop-and-switch-set)
7209 (js2-push-scope loop-node)
7210 ;; Tell the current labeled statement (if any) its statement,
7211 ;; and set the jump target of the first label to the loop.
7212 ;; These are used in `js2-parse-continue' to verify that the
7213 ;; continue target is an actual labeled loop. (And for codegen.)
7214 (when js2-labeled-stmt
7215 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7216 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7217 js2-labeled-stmt))) loop-node)))
7218
7219 (defun js2-exit-loop ()
7220 (pop js2-loop-set)
7221 (pop js2-loop-and-switch-set)
7222 (js2-pop-scope))
7223
7224 (defsubst js2-enter-switch (switch-node)
7225 (push switch-node js2-loop-and-switch-set))
7226
7227 (defsubst js2-exit-switch ()
7228 (pop js2-loop-and-switch-set))
7229
7230 (defun js2-parse (&optional buf cb)
7231 "Tell the js2 parser to parse a region of JavaScript.
7232
7233 BUF is a buffer or buffer name containing the code to parse.
7234 Call `narrow-to-region' first to parse only part of the buffer.
7235
7236 The returned AST root node is given some additional properties:
7237 `node-count' - total number of nodes in the AST
7238 `buffer' - BUF. The buffer it refers to may change or be killed,
7239 so the value is not necessarily reliable.
7240
7241 An optional callback CB can be specified to report parsing
7242 progress. If `(functionp CB)' returns t, it will be called with
7243 the current line number once before parsing begins, then again
7244 each time the lexer reaches a new line number.
7245
7246 CB can also be a list of the form `(symbol cb ...)' to specify
7247 multiple callbacks with different criteria. Each symbol is a
7248 criterion keyword, and the following element is the callback to
7249 call
7250
7251 :line - called whenever the line number changes
7252 :token - called for each new token consumed
7253
7254 The list of criteria could be extended to include entering or
7255 leaving a statement, an expression, or a function definition."
7256 (if (and cb (not (functionp cb)))
7257 (error "criteria callbacks not yet implemented"))
7258 (let ((inhibit-point-motion-hooks t)
7259 (js2-compiler-xml-available (>= js2-language-version 160))
7260 ;; This is a recursive-descent parser, so give it a big stack.
7261 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7262 (max-specpdl-size (max max-specpdl-size 3000))
7263 (case-fold-search nil)
7264 ast)
7265 (with-current-buffer (or buf (current-buffer))
7266 (setq js2-scanned-comments nil
7267 js2-parsed-errors nil
7268 js2-parsed-warnings nil
7269 js2-imenu-recorder nil
7270 js2-imenu-function-map nil
7271 js2-label-set nil)
7272 (js2-init-scanner)
7273 (setq ast (with-silent-modifications
7274 (js2-do-parse)))
7275 (unless js2-ts-hit-eof
7276 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7277 (setf (js2-ast-root-errors ast) js2-parsed-errors
7278 (js2-ast-root-warnings ast) js2-parsed-warnings)
7279 ;; if we didn't find any declarations, put a dummy in this list so we
7280 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7281 (unless js2-imenu-recorder
7282 (setq js2-imenu-recorder 'empty))
7283 (run-hooks 'js2-parse-finished-hook)
7284 ast)))
7285
7286 ;; Corresponds to Rhino's Parser.parse() method.
7287 (defun js2-do-parse ()
7288 "Parse current buffer starting from current point.
7289 Scanner should be initialized."
7290 (let ((pos js2-ts-cursor)
7291 (end js2-ts-cursor) ; in case file is empty
7292 root n tt)
7293 ;; initialize buffer-local parsing vars
7294 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7295 js2-current-script-or-fn root
7296 js2-current-scope root
7297 js2-nesting-of-function 0
7298 js2-labeled-stmt nil
7299 js2-recorded-identifiers nil) ; for js2-highlight
7300 (while (/= (setq tt (js2-get-token)) js2-EOF)
7301 (if (= tt js2-FUNCTION)
7302 (progn
7303 (setq n (if js2-called-by-compile-function
7304 (js2-parse-function-expr)
7305 (js2-parse-function-stmt))))
7306 ;; not a function - parse a statement
7307 (js2-unget-token)
7308 (setq n (js2-parse-statement)))
7309 ;; add function or statement to script
7310 (setq end (js2-node-end n))
7311 (js2-block-node-push root n))
7312 ;; add comments to root in lexical order
7313 (when js2-scanned-comments
7314 ;; if we find a comment beyond end of normal kids, use its end
7315 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7316 (dolist (comment js2-scanned-comments)
7317 (push comment (js2-ast-root-comments root))
7318 (js2-node-add-children root comment)))
7319 (setf (js2-node-len root) (- end pos))
7320 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7321 ;; Give extensions a chance to muck with things before highlighting starts.
7322 (let ((js2-additional-externs js2-additional-externs))
7323 (save-excursion
7324 (run-hooks 'js2-post-parse-callbacks))
7325 (js2-highlight-undeclared-vars))
7326 root))
7327
7328 (defun js2-parse-function-closure-body (fn-node)
7329 "Parse a JavaScript 1.8 function closure body."
7330 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7331 (if js2-ts-hit-eof
7332 (js2-report-error "msg.no.brace.body" nil
7333 (js2-node-pos fn-node)
7334 (- js2-ts-cursor (js2-node-pos fn-node)))
7335 (js2-node-add-children fn-node
7336 (setf (js2-function-node-body fn-node)
7337 (js2-parse-expr t))))))
7338
7339 (defun js2-parse-function-body (fn-node)
7340 (js2-must-match js2-LC "msg.no.brace.body"
7341 (js2-node-pos fn-node)
7342 (- js2-ts-cursor (js2-node-pos fn-node)))
7343 (let ((pos (js2-current-token-beg)) ; LC position
7344 (pn (make-js2-block-node)) ; starts at LC position
7345 tt
7346 end)
7347 (incf js2-nesting-of-function)
7348 (unwind-protect
7349 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7350 (= tt js2-EOF)
7351 (= tt js2-RC)))
7352 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7353 (js2-parse-statement)
7354 (js2-get-token)
7355 (js2-parse-function-stmt))))
7356 (decf js2-nesting-of-function))
7357 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7358 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7359 (setq end (js2-current-token-end)))
7360 (setf (js2-node-pos pn) pos
7361 (js2-node-len pn) (- end pos))
7362 (setf (js2-function-node-body fn-node) pn)
7363 (js2-node-add-children fn-node pn)
7364 pn))
7365
7366 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7367 "Declare and fontify destructuring parameters inside NODE.
7368 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7369 (cond
7370 ((js2-name-node-p node)
7371 (let (leftpos)
7372 (js2-define-symbol decl-type (js2-name-node-name node)
7373 node ignore-not-in-block)
7374 (when face
7375 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7376 (+ leftpos (js2-node-len node))
7377 face 'record))))
7378 ((js2-object-node-p node)
7379 (dolist (elem (js2-object-node-elems node))
7380 (js2-define-destruct-symbols
7381 (if (js2-object-prop-node-p elem)
7382 (js2-object-prop-node-right elem)
7383 ;; abbreviated destructuring {a, b}
7384 elem)
7385 decl-type face ignore-not-in-block)))
7386 ((js2-array-node-p node)
7387 (dolist (elem (js2-array-node-elems node))
7388 (when elem
7389 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7390 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7391 (js2-node-len node)))))
7392
7393 (defun js2-parse-function-params (function-type fn-node pos)
7394 (if (js2-match-token js2-RP)
7395 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7396 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7397 (eq (js2-current-token-type) js2-NAME)))
7398 params param default-found rest-param-at)
7399 (when paren-free-arrow
7400 (js2-unget-token))
7401 (loop for tt = (js2-peek-token)
7402 do
7403 (cond
7404 ;; destructuring param
7405 ((and (not paren-free-arrow)
7406 (or (= tt js2-LB) (= tt js2-LC)))
7407 (js2-get-token)
7408 (when default-found
7409 (js2-report-error "msg.no.default.after.default.param"))
7410 (setq param (js2-parse-destruct-primary-expr))
7411 (js2-define-destruct-symbols param
7412 js2-LP
7413 'js2-function-param)
7414 (push param params))
7415 ;; variable name
7416 (t
7417 (when (and (>= js2-language-version 200)
7418 (not paren-free-arrow)
7419 (js2-match-token js2-TRIPLEDOT)
7420 (not rest-param-at))
7421 ;; to report errors if there are more parameters
7422 (setq rest-param-at (length params)))
7423 (js2-must-match-name "msg.no.parm")
7424 (js2-record-face 'js2-function-param)
7425 (setq param (js2-create-name-node))
7426 (js2-define-symbol js2-LP (js2-current-token-string) param)
7427 ;; default parameter value
7428 (when (or (and default-found
7429 (not rest-param-at)
7430 (js2-must-match js2-ASSIGN
7431 "msg.no.default.after.default.param"
7432 (js2-node-pos param)
7433 (js2-node-len param)))
7434 (and (>= js2-language-version 200)
7435 (js2-match-token js2-ASSIGN)))
7436 (assert (not paren-free-arrow))
7437 (let* ((pos (js2-node-pos param))
7438 (tt (js2-current-token-type))
7439 (op-pos (- (js2-current-token-beg) pos))
7440 (left param)
7441 (right (js2-parse-assign-expr))
7442 (len (- (js2-node-end right) pos)))
7443 (setq param (make-js2-assign-node
7444 :type tt :pos pos :len len :op-pos op-pos
7445 :left left :right right)
7446 default-found t)
7447 (js2-node-add-children param left right)))
7448 (push param params)))
7449 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7450 (js2-report-error "msg.param.after.rest" nil
7451 (js2-node-pos param) (js2-node-len param)))
7452 while
7453 (js2-match-token js2-COMMA))
7454 (when (and (not paren-free-arrow)
7455 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7456 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7457 (when rest-param-at
7458 (setf (js2-function-node-rest-p fn-node) t))
7459 (dolist (p params)
7460 (js2-node-add-children fn-node p)
7461 (push p (js2-function-node-params fn-node))))))
7462
7463 (defun js2-check-inconsistent-return-warning (fn-node name)
7464 "Possibly show inconsistent-return warning.
7465 Last token scanned is the close-curly for the function body."
7466 (when (and js2-mode-show-strict-warnings
7467 js2-strict-inconsistent-return-warning
7468 (not (js2-has-consistent-return-usage
7469 (js2-function-node-body fn-node))))
7470 ;; Have it extend from close-curly to bol or beginning of block.
7471 (let ((pos (save-excursion
7472 (goto-char (js2-current-token-end))
7473 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7474 (point-at-bol))))
7475 (end (js2-current-token-end)))
7476 (if (plusp (js2-name-node-length name))
7477 (js2-add-strict-warning "msg.no.return.value"
7478 (js2-name-node-name name) pos end)
7479 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7480
7481 (defun js2-parse-function-stmt ()
7482 (let ((pos (js2-current-token-beg))
7483 (star-p (js2-match-token js2-MUL)))
7484 (js2-must-match-name "msg.unnamed.function.stmt")
7485 (let ((name (js2-create-name-node t))
7486 pn member-expr)
7487 (cond
7488 ((js2-match-token js2-LP)
7489 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7490 (js2-allow-member-expr-as-function-name
7491 (setq member-expr (js2-parse-member-expr-tail nil name))
7492 (js2-parse-highlight-member-expr-fn-name member-expr)
7493 (js2-must-match js2-LP "msg.no.paren.parms")
7494 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7495 (js2-function-node-member-expr pn) member-expr)
7496 pn)
7497 (t
7498 (js2-report-error "msg.no.paren.parms")
7499 (make-js2-error-node))))))
7500
7501 (defun js2-parse-function-expr ()
7502 (let ((pos (js2-current-token-beg))
7503 (star-p (js2-match-token js2-MUL))
7504 name)
7505 (when (js2-match-token js2-NAME)
7506 (setq name (js2-create-name-node t)))
7507 (js2-must-match js2-LP "msg.no.paren.parms")
7508 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7509
7510 (defun js2-parse-function (function-type pos star-p &optional name)
7511 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7512 beginning of the first token (function keyword, unless it's an
7513 arrow function), NAME is js2-name-node."
7514 (let (fn-node lp)
7515 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7516 (setq lp (js2-current-token-beg)))
7517 (setf fn-node (make-js2-function-node :pos pos
7518 :name name
7519 :form function-type
7520 :lp (if lp (- lp pos))
7521 :generator-type (and star-p 'STAR)))
7522 (when name
7523 (js2-set-face (js2-node-pos name) (js2-node-end name)
7524 'font-lock-function-name-face 'record)
7525 (when (plusp (js2-name-node-length name))
7526 ;; Function statements define a symbol in the enclosing scope
7527 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7528 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7529 ;; 1. Nested functions are not affected by the dynamic scope flag
7530 ;; as dynamic scope is already a parent of their scope.
7531 ;; 2. Functions defined under the with statement also immune to
7532 ;; this setup, in which case dynamic scope is ignored in favor
7533 ;; of the with object.
7534 (setf (js2-function-node-ignore-dynamic fn-node) t))
7535 ;; dynamically bind all the per-function variables
7536 (let ((js2-current-script-or-fn fn-node)
7537 (js2-current-scope fn-node)
7538 (js2-nesting-of-with 0)
7539 (js2-end-flags 0)
7540 js2-label-set
7541 js2-loop-set
7542 js2-loop-and-switch-set)
7543 (js2-parse-function-params function-type fn-node pos)
7544 (when (eq function-type 'FUNCTION_ARROW)
7545 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7546 (if (and (>= js2-language-version 180)
7547 (/= (js2-peek-token) js2-LC))
7548 (js2-parse-function-closure-body fn-node)
7549 (js2-parse-function-body fn-node))
7550 (js2-check-inconsistent-return-warning fn-node name)
7551
7552 (when name
7553 (js2-node-add-children fn-node name)
7554 ;; Function expressions define a name only in the body of the
7555 ;; function, and only if not hidden by a parameter name
7556 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7557 (null (js2-scope-get-symbol js2-current-scope
7558 (js2-name-node-name name))))
7559 (js2-define-symbol js2-FUNCTION
7560 (js2-name-node-name name)
7561 fn-node))
7562 (when (eq function-type 'FUNCTION_STATEMENT)
7563 (js2-record-imenu-functions fn-node))))
7564
7565 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7566 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7567 ;; We wait until after parsing the function to set its parent scope,
7568 ;; since `js2-define-symbol' needs the defining-scope check to stop
7569 ;; at the function boundary when checking for redeclarations.
7570 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7571 fn-node))
7572
7573 (defun js2-parse-statements (&optional parent)
7574 "Parse a statement list. Last token consumed must be js2-LC.
7575
7576 PARENT can be a `js2-block-node', in which case the statements are
7577 appended to PARENT. Otherwise a new `js2-block-node' is created
7578 and returned.
7579
7580 This function does not match the closing js2-RC: the caller
7581 matches the RC so it can provide a suitable error message if not
7582 matched. This means it's up to the caller to set the length of
7583 the node to include the closing RC. The node start pos is set to
7584 the absolute buffer start position, and the caller should fix it
7585 up to be relative to the parent node. All children of this block
7586 node are given relative start positions and correct lengths."
7587 (let ((pn (or parent (make-js2-block-node)))
7588 tt)
7589 (setf (js2-node-pos pn) (js2-current-token-beg))
7590 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7591 (/= tt js2-RC))
7592 (js2-block-node-push pn (js2-parse-statement)))
7593 pn))
7594
7595 (defun js2-parse-statement ()
7596 (let (pn beg end)
7597 ;; coarse-grained user-interrupt check - needs work
7598 (and js2-parse-interruptable-p
7599 (zerop (% (incf js2-parse-stmt-count)
7600 js2-statements-per-pause))
7601 (input-pending-p)
7602 (throw 'interrupted t))
7603 (setq pn (js2-statement-helper))
7604 ;; no-side-effects warning check
7605 (unless (js2-node-has-side-effects pn)
7606 (setq end (js2-node-end pn))
7607 (save-excursion
7608 (goto-char end)
7609 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7610 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7611 pn))
7612
7613 ;; These correspond to the switch cases in Parser.statementHelper
7614 (defconst js2-parsers
7615 (let ((parsers (make-vector js2-num-tokens
7616 #'js2-parse-expr-stmt)))
7617 (aset parsers js2-BREAK #'js2-parse-break)
7618 (aset parsers js2-CONST #'js2-parse-const-var)
7619 (aset parsers js2-CONTINUE #'js2-parse-continue)
7620 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7621 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7622 (aset parsers js2-DO #'js2-parse-do)
7623 (aset parsers js2-FOR #'js2-parse-for)
7624 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
7625 (aset parsers js2-IF #'js2-parse-if)
7626 (aset parsers js2-LC #'js2-parse-block)
7627 (aset parsers js2-LET #'js2-parse-let-stmt)
7628 (aset parsers js2-NAME #'js2-parse-name-or-label)
7629 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7630 (aset parsers js2-SEMI #'js2-parse-semi)
7631 (aset parsers js2-SWITCH #'js2-parse-switch)
7632 (aset parsers js2-THROW #'js2-parse-throw)
7633 (aset parsers js2-TRY #'js2-parse-try)
7634 (aset parsers js2-VAR #'js2-parse-const-var)
7635 (aset parsers js2-WHILE #'js2-parse-while)
7636 (aset parsers js2-WITH #'js2-parse-with)
7637 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7638 parsers)
7639 "A vector mapping token types to parser functions.")
7640
7641 (defun js2-parse-warn-missing-semi (beg end)
7642 (and js2-mode-show-strict-warnings
7643 js2-strict-missing-semi-warning
7644 (js2-add-strict-warning
7645 "msg.missing.semi" nil
7646 ;; back up to beginning of statement or line
7647 (max beg (save-excursion
7648 (goto-char end)
7649 (point-at-bol)))
7650 end)))
7651
7652 (defconst js2-no-semi-insertion
7653 (list js2-IF
7654 js2-SWITCH
7655 js2-WHILE
7656 js2-DO
7657 js2-FOR
7658 js2-TRY
7659 js2-WITH
7660 js2-LC
7661 js2-ERROR
7662 js2-SEMI
7663 js2-FUNCTION)
7664 "List of tokens that don't do automatic semicolon insertion.")
7665
7666 (defconst js2-autoinsert-semi-and-warn
7667 (list js2-ERROR js2-EOF js2-RC))
7668
7669 (defun js2-statement-helper ()
7670 (let* ((tt (js2-get-token))
7671 (first-tt tt)
7672 (parser (if (= tt js2-ERROR)
7673 #'js2-parse-semi
7674 (aref js2-parsers tt)))
7675 pn)
7676 ;; If the statement is set, then it's been told its label by now.
7677 (and js2-labeled-stmt
7678 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7679 (setq js2-labeled-stmt nil))
7680 (setq pn (funcall parser))
7681 ;; Don't do auto semi insertion for certain statement types.
7682 (unless (or (memq first-tt js2-no-semi-insertion)
7683 (js2-labeled-stmt-node-p pn))
7684 (js2-auto-insert-semicolon pn))
7685 pn))
7686
7687 (defun js2-auto-insert-semicolon (pn)
7688 (let* ((tt (js2-get-token))
7689 (pos (js2-node-pos pn)))
7690 (cond
7691 ((= tt js2-SEMI)
7692 ;; extend the node bounds to include the semicolon.
7693 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
7694 ((memq tt js2-autoinsert-semi-and-warn)
7695 (js2-unget-token) ; Not ';', do not consume.
7696 ;; Autoinsert ;
7697 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7698 (t
7699 (if (not (js2-token-follows-eol-p (js2-current-token)))
7700 ;; Report error if no EOL or autoinsert ';' otherwise
7701 (js2-report-error "msg.no.semi.stmt")
7702 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7703 (js2-unget-token) ; Not ';', do not consume.
7704 ))))
7705
7706 (defun js2-parse-condition ()
7707 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7708 The parens are discarded and the expression node is returned.
7709 The `pos' field of the return value is set to an absolute position
7710 that must be fixed up by the caller.
7711 Return value is a list (EXPR LP RP), with absolute paren positions."
7712 (let (pn lp rp)
7713 (if (js2-must-match js2-LP "msg.no.paren.cond")
7714 (setq lp (js2-current-token-beg)))
7715 (setq pn (js2-parse-expr))
7716 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7717 (setq rp (js2-current-token-beg)))
7718 ;; Report strict warning on code like "if (a = 7) ..."
7719 (if (and js2-strict-cond-assign-warning
7720 (js2-assign-node-p pn))
7721 (js2-add-strict-warning "msg.equal.as.assign" nil
7722 (js2-node-pos pn)
7723 (+ (js2-node-pos pn)
7724 (js2-node-len pn))))
7725 (list pn lp rp)))
7726
7727 (defun js2-parse-if ()
7728 "Parser for if-statement. Last matched token must be js2-IF."
7729 (let ((pos (js2-current-token-beg))
7730 cond if-true if-false else-pos end pn)
7731 (setq cond (js2-parse-condition)
7732 if-true (js2-parse-statement)
7733 if-false (if (js2-match-token js2-ELSE)
7734 (progn
7735 (setq else-pos (- (js2-current-token-beg) pos))
7736 (js2-parse-statement)))
7737 end (js2-node-end (or if-false if-true))
7738 pn (make-js2-if-node :pos pos
7739 :len (- end pos)
7740 :condition (car cond)
7741 :then-part if-true
7742 :else-part if-false
7743 :else-pos else-pos
7744 :lp (js2-relpos (second cond) pos)
7745 :rp (js2-relpos (third cond) pos)))
7746 (js2-node-add-children pn (car cond) if-true if-false)
7747 pn))
7748
7749 (defun js2-parse-switch ()
7750 "Parser for switch-statement. Last matched token must be js2-SWITCH."
7751 (let ((pos (js2-current-token-beg))
7752 tt pn discriminant has-default case-expr case-node
7753 case-pos cases stmt lp)
7754 (if (js2-must-match js2-LP "msg.no.paren.switch")
7755 (setq lp (js2-current-token-beg)))
7756 (setq discriminant (js2-parse-expr)
7757 pn (make-js2-switch-node :discriminant discriminant
7758 :pos pos
7759 :lp (js2-relpos lp pos)))
7760 (js2-node-add-children pn discriminant)
7761 (js2-enter-switch pn)
7762 (unwind-protect
7763 (progn
7764 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7765 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
7766 (js2-must-match js2-LC "msg.no.brace.switch")
7767 (catch 'break
7768 (while t
7769 (setq tt (js2-next-token)
7770 case-pos (js2-current-token-beg))
7771 (cond
7772 ((= tt js2-RC)
7773 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
7774 (throw 'break nil)) ; done
7775 ((= tt js2-CASE)
7776 (setq case-expr (js2-parse-expr))
7777 (js2-must-match js2-COLON "msg.no.colon.case"))
7778 ((= tt js2-DEFAULT)
7779 (if has-default
7780 (js2-report-error "msg.double.switch.default"))
7781 (setq has-default t
7782 case-expr nil)
7783 (js2-must-match js2-COLON "msg.no.colon.case"))
7784 (t
7785 (js2-report-error "msg.bad.switch")
7786 (throw 'break nil)))
7787 (setq case-node (make-js2-case-node :pos case-pos
7788 :len (- (js2-current-token-end) case-pos)
7789 :expr case-expr))
7790 (js2-node-add-children case-node case-expr)
7791 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7792 (/= tt js2-CASE)
7793 (/= tt js2-DEFAULT)
7794 (/= tt js2-EOF))
7795 (setf stmt (js2-parse-statement)
7796 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7797 (js2-block-node-push case-node stmt))
7798 (push case-node cases)))
7799 ;; add cases last, as pushing reverses the order to be correct
7800 (dolist (kid cases)
7801 (js2-node-add-children pn kid)
7802 (push kid (js2-switch-node-cases pn)))
7803 pn) ; return value
7804 (js2-exit-switch))))
7805
7806 (defun js2-parse-while ()
7807 "Parser for while-statement. Last matched token must be js2-WHILE."
7808 (let ((pos (js2-current-token-beg))
7809 (pn (make-js2-while-node))
7810 cond body)
7811 (js2-enter-loop pn)
7812 (unwind-protect
7813 (progn
7814 (setf cond (js2-parse-condition)
7815 (js2-while-node-condition pn) (car cond)
7816 body (js2-parse-statement)
7817 (js2-while-node-body pn) body
7818 (js2-node-len pn) (- (js2-node-end body) pos)
7819 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7820 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7821 (js2-node-add-children pn body (car cond)))
7822 (js2-exit-loop))
7823 pn))
7824
7825 (defun js2-parse-do ()
7826 "Parser for do-statement. Last matched token must be js2-DO."
7827 (let ((pos (js2-current-token-beg))
7828 (pn (make-js2-do-node))
7829 cond body end)
7830 (js2-enter-loop pn)
7831 (unwind-protect
7832 (progn
7833 (setq body (js2-parse-statement))
7834 (js2-must-match js2-WHILE "msg.no.while.do")
7835 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
7836 cond (js2-parse-condition)
7837 (js2-do-node-condition pn) (car cond)
7838 (js2-do-node-body pn) body
7839 end js2-ts-cursor
7840 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7841 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7842 (js2-node-add-children pn (car cond) body))
7843 (js2-exit-loop))
7844 ;; Always auto-insert semicolon to follow SpiderMonkey:
7845 ;; It is required by ECMAScript but is ignored by the rest of
7846 ;; world; see bug 238945
7847 (if (js2-match-token js2-SEMI)
7848 (setq end js2-ts-cursor))
7849 (setf (js2-node-len pn) (- end pos))
7850 pn))
7851
7852 (defun js2-parse-for ()
7853 "Parser for for-statement. Last matched token must be js2-FOR.
7854 Parses for, for-in, and for each-in statements."
7855 (let ((for-pos (js2-current-token-beg))
7856 pn is-for-each is-for-in-or-of is-for-of
7857 in-pos each-pos tmp-pos
7858 init ; Node init is also foo in 'foo in object'
7859 cond ; Node cond is also object in 'foo in object'
7860 incr ; 3rd section of for-loop initializer
7861 body tt lp rp)
7862 ;; See if this is a for each () instead of just a for ()
7863 (when (js2-match-token js2-NAME)
7864 (if (string= "each" (js2-current-token-string))
7865 (progn
7866 (setq is-for-each t
7867 each-pos (- (js2-current-token-beg) for-pos)) ; relative
7868 (js2-record-face 'font-lock-keyword-face))
7869 (js2-report-error "msg.no.paren.for")))
7870 (if (js2-must-match js2-LP "msg.no.paren.for")
7871 (setq lp (- (js2-current-token-beg) for-pos)))
7872 (setq tt (js2-get-token))
7873 ;; 'for' makes local scope
7874 (js2-push-scope (make-js2-scope))
7875 (unwind-protect
7876 ;; parse init clause
7877 (let ((js2-in-for-init t)) ; set as dynamic variable
7878 (cond
7879 ((= tt js2-SEMI)
7880 (js2-unget-token)
7881 (setq init (make-js2-empty-expr-node)))
7882 ((or (= tt js2-VAR) (= tt js2-LET))
7883 (setq init (js2-parse-variables tt (js2-current-token-beg))))
7884 (t
7885 (js2-unget-token)
7886 (setq init (js2-parse-expr)))))
7887 (if (or (js2-match-token js2-IN)
7888 (and (>= js2-language-version 200)
7889 (js2-match-contextual-kwd "of")
7890 (setq is-for-of t)))
7891 (setq is-for-in-or-of t
7892 in-pos (- (js2-current-token-beg) for-pos)
7893 ;; scope of iteration target object is not the scope we've created above.
7894 ;; stash current scope temporary.
7895 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7896 (js2-parse-expr))) ; object over which we're iterating
7897 ;; else ordinary for loop - parse cond and incr
7898 (js2-must-match js2-SEMI "msg.no.semi.for")
7899 (setq cond (if (= (js2-peek-token) js2-SEMI)
7900 (make-js2-empty-expr-node) ; no loop condition
7901 (js2-parse-expr)))
7902 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7903 (setq tmp-pos (js2-current-token-end)
7904 incr (if (= (js2-peek-token) js2-RP)
7905 (make-js2-empty-expr-node :pos tmp-pos)
7906 (js2-parse-expr))))
7907 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7908 (setq rp (- (js2-current-token-beg) for-pos)))
7909 (if (not is-for-in-or-of)
7910 (setq pn (make-js2-for-node :init init
7911 :condition cond
7912 :update incr
7913 :lp lp
7914 :rp rp))
7915 ;; cond could be null if 'in obj' got eaten by the init node.
7916 (if (js2-infix-node-p init)
7917 ;; it was (foo in bar) instead of (var foo in bar)
7918 (setq cond (js2-infix-node-right init)
7919 init (js2-infix-node-left init))
7920 (if (and (js2-var-decl-node-p init)
7921 (> (length (js2-var-decl-node-kids init)) 1))
7922 (js2-report-error "msg.mult.index")))
7923 (setq pn (make-js2-for-in-node :iterator init
7924 :object cond
7925 :in-pos in-pos
7926 :foreach-p is-for-each
7927 :each-pos each-pos
7928 :forof-p is-for-of
7929 :lp lp
7930 :rp rp)))
7931 (unwind-protect
7932 (progn
7933 (js2-enter-loop pn)
7934 ;; We have to parse the body -after- creating the loop node,
7935 ;; so that the loop node appears in the js2-loop-set, allowing
7936 ;; break/continue statements to find the enclosing loop.
7937 (setf body (js2-parse-statement)
7938 (js2-loop-node-body pn) body
7939 (js2-node-pos pn) for-pos
7940 (js2-node-len pn) (- (js2-node-end body) for-pos))
7941 (js2-node-add-children pn init cond incr body))
7942 ;; finally
7943 (js2-exit-loop))
7944 (js2-pop-scope))
7945 pn))
7946
7947 (defun js2-parse-try ()
7948 "Parser for try-statement. Last matched token must be js2-TRY."
7949 (let ((try-pos (js2-current-token-beg))
7950 try-end
7951 try-block
7952 catch-blocks
7953 finally-block
7954 saw-default-catch
7955 peek
7956 param
7957 catch-cond
7958 catch-node
7959 guard-kwd
7960 catch-pos
7961 finally-pos
7962 pn
7963 block
7964 lp
7965 rp)
7966 (if (/= (js2-peek-token) js2-LC)
7967 (js2-report-error "msg.no.brace.try"))
7968 (setq try-block (js2-parse-statement)
7969 try-end (js2-node-end try-block)
7970 peek (js2-peek-token))
7971 (cond
7972 ((= peek js2-CATCH)
7973 (while (js2-match-token js2-CATCH)
7974 (setq catch-pos (js2-current-token-beg)
7975 guard-kwd nil
7976 catch-cond nil
7977 lp nil
7978 rp nil)
7979 (if saw-default-catch
7980 (js2-report-error "msg.catch.unreachable"))
7981 (if (js2-must-match js2-LP "msg.no.paren.catch")
7982 (setq lp (- (js2-current-token-beg) catch-pos)))
7983 (js2-push-scope (make-js2-scope))
7984 (let ((tt (js2-peek-token)))
7985 (cond
7986 ;; destructuring pattern
7987 ;; catch ({ message, file }) { ... }
7988 ((or (= tt js2-LB) (= tt js2-LC))
7989 (js2-get-token)
7990 (setq param (js2-parse-destruct-primary-expr))
7991 (js2-define-destruct-symbols param js2-LET nil))
7992 ;; simple name
7993 (t
7994 (js2-must-match-name "msg.bad.catchcond")
7995 (setq param (js2-create-name-node))
7996 (js2-define-symbol js2-LET (js2-current-token-string) param))))
7997 ;; pattern guard
7998 (if (js2-match-token js2-IF)
7999 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8000 catch-cond (js2-parse-expr))
8001 (setq saw-default-catch t))
8002 (if (js2-must-match js2-RP "msg.bad.catchcond")
8003 (setq rp (- (js2-current-token-beg) catch-pos)))
8004 (js2-must-match js2-LC "msg.no.brace.catchblock")
8005 (setq block (js2-parse-statements)
8006 try-end (js2-node-end block)
8007 catch-node (make-js2-catch-node :pos catch-pos
8008 :param param
8009 :guard-expr catch-cond
8010 :guard-kwd guard-kwd
8011 :block block
8012 :lp lp
8013 :rp rp))
8014 (js2-pop-scope)
8015 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8016 (setq try-end (js2-current-token-beg)))
8017 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8018 (js2-node-len catch-node) (- try-end catch-pos))
8019 (js2-node-add-children catch-node param catch-cond block)
8020 (push catch-node catch-blocks)))
8021 ((/= peek js2-FINALLY)
8022 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8023 (js2-node-pos try-block)
8024 (- (setq try-end (js2-node-end try-block))
8025 (js2-node-pos try-block)))))
8026 (when (js2-match-token js2-FINALLY)
8027 (setq finally-pos (js2-current-token-beg)
8028 block (js2-parse-statement)
8029 try-end (js2-node-end block)
8030 finally-block (make-js2-finally-node :pos finally-pos
8031 :len (- try-end finally-pos)
8032 :body block))
8033 (js2-node-add-children finally-block block))
8034 (setq pn (make-js2-try-node :pos try-pos
8035 :len (- try-end try-pos)
8036 :try-block try-block
8037 :finally-block finally-block))
8038 (js2-node-add-children pn try-block finally-block)
8039 ;; push them onto the try-node, which reverses and corrects their order
8040 (dolist (cb catch-blocks)
8041 (js2-node-add-children pn cb)
8042 (push cb (js2-try-node-catch-clauses pn)))
8043 pn))
8044
8045 (defun js2-parse-throw ()
8046 "Parser for throw-statement. Last matched token must be js2-THROW."
8047 (let ((pos (js2-current-token-beg))
8048 expr pn)
8049 (if (= (js2-peek-token-or-eol) js2-EOL)
8050 ;; ECMAScript does not allow new lines before throw expression,
8051 ;; see bug 256617
8052 (js2-report-error "msg.bad.throw.eol"))
8053 (setq expr (js2-parse-expr)
8054 pn (make-js2-throw-node :pos pos
8055 :len (- (js2-node-end expr) pos)
8056 :expr expr))
8057 (js2-node-add-children pn expr)
8058 pn))
8059
8060 (defun js2-match-jump-label-name (label-name)
8061 "If break/continue specified a label, return that label's labeled stmt.
8062 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8063 does not match an existing label, reports an error and returns nil."
8064 (let ((bundle (cdr (assoc label-name js2-label-set))))
8065 (if (null bundle)
8066 (js2-report-error "msg.undef.label"))
8067 bundle))
8068
8069 (defun js2-parse-break ()
8070 "Parser for break-statement. Last matched token must be js2-BREAK."
8071 (let ((pos (js2-current-token-beg))
8072 (end (js2-current-token-end))
8073 break-target ; statement to break from
8074 break-label ; in "break foo", name-node representing the foo
8075 labels ; matching labeled statement to break to
8076 pn)
8077 (when (eq (js2-peek-token-or-eol) js2-NAME)
8078 (js2-get-token)
8079 (setq break-label (js2-create-name-node)
8080 end (js2-node-end break-label)
8081 ;; matchJumpLabelName only matches if there is one
8082 labels (js2-match-jump-label-name (js2-current-token-string))
8083 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8084 (unless (or break-target break-label)
8085 ;; no break target specified - try for innermost enclosing loop/switch
8086 (if (null js2-loop-and-switch-set)
8087 (unless break-label
8088 (js2-report-error "msg.bad.break" nil pos (length "break")))
8089 (setq break-target (car js2-loop-and-switch-set))))
8090 (setq pn (make-js2-break-node :pos pos
8091 :len (- end pos)
8092 :label break-label
8093 :target break-target))
8094 (js2-node-add-children pn break-label) ; but not break-target
8095 pn))
8096
8097 (defun js2-parse-continue ()
8098 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8099 (let ((pos (js2-current-token-beg))
8100 (end (js2-current-token-end))
8101 label ; optional user-specified label, a `js2-name-node'
8102 labels ; current matching labeled stmt, if any
8103 target ; the `js2-loop-node' target of this continue stmt
8104 pn)
8105 (when (= (js2-peek-token-or-eol) js2-NAME)
8106 (js2-get-token)
8107 (setq label (js2-create-name-node)
8108 end (js2-node-end label)
8109 ;; matchJumpLabelName only matches if there is one
8110 labels (js2-match-jump-label-name (js2-current-token-string))))
8111 (cond
8112 ((null labels) ; no current label to go to
8113 (if (null js2-loop-set) ; no loop to continue to
8114 (js2-report-error "msg.continue.outside" nil pos
8115 (length "continue"))
8116 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8117 (t
8118 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8119 (setq target (js2-labeled-stmt-node-stmt labels))
8120 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8121 (setq pn (make-js2-continue-node :pos pos
8122 :len (- end pos)
8123 :label label
8124 :target target))
8125 (js2-node-add-children pn label) ; but not target - it's not our child
8126 pn))
8127
8128 (defun js2-parse-with ()
8129 "Parser for with-statement. Last matched token must be js2-WITH."
8130 (let ((pos (js2-current-token-beg))
8131 obj body pn lp rp)
8132 (if (js2-must-match js2-LP "msg.no.paren.with")
8133 (setq lp (js2-current-token-beg)))
8134 (setq obj (js2-parse-expr))
8135 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8136 (setq rp (js2-current-token-beg)))
8137 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8138 (setq body (js2-parse-statement)))
8139 (setq pn (make-js2-with-node :pos pos
8140 :len (- (js2-node-end body) pos)
8141 :object obj
8142 :body body
8143 :lp (js2-relpos lp pos)
8144 :rp (js2-relpos rp pos)))
8145 (js2-node-add-children pn obj body)
8146 pn))
8147
8148 (defun js2-parse-const-var ()
8149 "Parser for var- or const-statement.
8150 Last matched token must be js2-CONST or js2-VAR."
8151 (let ((tt (js2-current-token-type))
8152 (pos (js2-current-token-beg))
8153 expr pn)
8154 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8155 pn (make-js2-expr-stmt-node :pos pos
8156 :len (- (js2-node-end expr) pos)
8157 :expr expr))
8158 (js2-node-add-children pn expr)
8159 pn))
8160
8161 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8162 (let ((pn (make-js2-expr-stmt-node :pos pos
8163 :len (js2-node-len expr)
8164 :type (if (js2-inside-function)
8165 js2-EXPR_VOID
8166 js2-EXPR_RESULT)
8167 :expr expr)))
8168 (if add-child
8169 (js2-node-add-children pn expr))
8170 pn))
8171
8172 (defun js2-parse-let-stmt ()
8173 "Parser for let-statement. Last matched token must be js2-LET."
8174 (let ((pos (js2-current-token-beg))
8175 expr pn)
8176 (if (= (js2-peek-token) js2-LP)
8177 ;; let expression in statement context
8178 (setq expr (js2-parse-let pos 'statement)
8179 pn (js2-wrap-with-expr-stmt pos expr t))
8180 ;; else we're looking at a statement like let x=6, y=7;
8181 (setf expr (js2-parse-variables js2-LET pos)
8182 pn (js2-wrap-with-expr-stmt pos expr t)
8183 (js2-node-type pn) js2-EXPR_RESULT))
8184 pn))
8185
8186 (defun js2-parse-ret-yield ()
8187 (js2-parse-return-or-yield (js2-current-token-type) nil))
8188
8189 (defconst js2-parse-return-stmt-enders
8190 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8191
8192 (defsubst js2-now-all-set (before after mask)
8193 "Return whether or not the bits in the mask have changed to all set.
8194 BEFORE is bits before change, AFTER is bits after change, and MASK is
8195 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8196 but not BEFORE."
8197 (and (/= (logand before mask) mask)
8198 (= (logand after mask) mask)))
8199
8200 (defun js2-parse-return-or-yield (tt expr-context)
8201 (let* ((pos (js2-current-token-beg))
8202 (end (js2-current-token-end))
8203 (before js2-end-flags)
8204 (inside-function (js2-inside-function))
8205 (gen-type (and inside-function (js2-function-node-generator-type
8206 js2-current-script-or-fn)))
8207 e ret name yield-star-p)
8208 (unless inside-function
8209 (js2-report-error (if (eq tt js2-RETURN)
8210 "msg.bad.return"
8211 "msg.bad.yield")))
8212 (when (and inside-function
8213 (eq gen-type 'STAR)
8214 (js2-match-token js2-MUL))
8215 (setq yield-star-p t))
8216 ;; This is ugly, but we don't want to require a semicolon.
8217 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8218 (setq e (js2-parse-expr)
8219 end (js2-node-end e)))
8220 (cond
8221 ((eq tt js2-RETURN)
8222 (js2-set-flag js2-end-flags (if (null e)
8223 js2-end-returns
8224 js2-end-returns-value))
8225 (setq ret (make-js2-return-node :pos pos
8226 :len (- end pos)
8227 :retval e))
8228 (js2-node-add-children ret e)
8229 ;; See if we need a strict mode warning.
8230 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8231 ;; more thorough and accurate than this before/after flag check.
8232 ;; E.g. if there's a finally-block that always returns, we shouldn't
8233 ;; show a warning generated by inconsistent returns in the catch blocks.
8234 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8235 ;; so we know which returns/yields to highlight, and we should get rid of
8236 ;; all the checking in `js2-parse-return-or-yield'.
8237 (if (and js2-strict-inconsistent-return-warning
8238 (js2-now-all-set before js2-end-flags
8239 (logior js2-end-returns js2-end-returns-value)))
8240 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8241 ((eq gen-type 'COMPREHENSION)
8242 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8243 ;; like SpiderMonkey does.
8244 (js2-report-error "msg.syntax" nil pos 5))
8245 (t
8246 (setq ret (make-js2-yield-node :pos pos
8247 :len (- end pos)
8248 :value e
8249 :star-p yield-star-p))
8250 (js2-node-add-children ret e)
8251 (unless expr-context
8252 (setq e ret
8253 ret (js2-wrap-with-expr-stmt pos e t))
8254 (js2-set-requires-activation)
8255 (js2-set-is-generator))))
8256 ;; see if we are mixing yields and value returns.
8257 (when (and inside-function
8258 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8259 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8260 'LEGACY))
8261 (setq name (js2-function-name js2-current-script-or-fn))
8262 (if (zerop (length name))
8263 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8264 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8265 ret))
8266
8267 (defun js2-parse-debugger ()
8268 (make-js2-keyword-node :type js2-DEBUGGER))
8269
8270 (defun js2-parse-block ()
8271 "Parser for a curly-delimited statement block.
8272 Last token matched must be `js2-LC'."
8273 (let ((pos (js2-current-token-beg))
8274 (pn (make-js2-scope)))
8275 (js2-push-scope pn)
8276 (unwind-protect
8277 (progn
8278 (js2-parse-statements pn)
8279 (js2-must-match js2-RC "msg.no.brace.block")
8280 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8281 (js2-pop-scope))
8282 pn))
8283
8284 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8285 (defun js2-parse-semi ()
8286 "Parse a statement or handle an error.
8287 Current token type is `js2-SEMI' or `js2-ERROR'."
8288 (let ((tt (js2-current-token-type)) pos len)
8289 (if (eq tt js2-SEMI)
8290 (make-js2-empty-expr-node :len 1)
8291 (setq pos (js2-current-token-beg)
8292 len (- (js2-current-token-end) pos))
8293 (js2-report-error "msg.syntax" nil pos len)
8294 (make-js2-error-node :pos pos :len len))))
8295
8296 (defun js2-parse-default-xml-namespace ()
8297 "Parse a `default xml namespace = <expr>' e4x statement."
8298 (let ((pos (js2-current-token-beg))
8299 end len expr unary)
8300 (js2-must-have-xml)
8301 (js2-set-requires-activation)
8302 (setq len (- js2-ts-cursor pos))
8303 (unless (and (js2-match-token js2-NAME)
8304 (string= (js2-current-token-string) "xml"))
8305 (js2-report-error "msg.bad.namespace" nil pos len))
8306 (unless (and (js2-match-token js2-NAME)
8307 (string= (js2-current-token-string) "namespace"))
8308 (js2-report-error "msg.bad.namespace" nil pos len))
8309 (unless (js2-match-token js2-ASSIGN)
8310 (js2-report-error "msg.bad.namespace" nil pos len))
8311 (setq expr (js2-parse-expr)
8312 end (js2-node-end expr)
8313 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8314 :pos pos
8315 :len (- end pos)
8316 :operand expr))
8317 (js2-node-add-children unary expr)
8318 (make-js2-expr-stmt-node :pos pos
8319 :len (- end pos)
8320 :expr unary)))
8321
8322 (defun js2-record-label (label bundle)
8323 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8324 (js2-get-token)
8325 (let ((name (js2-label-node-name label))
8326 labeled-stmt
8327 dup)
8328 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8329 ;; flag both labels if possible when used in editing mode
8330 (if (and js2-parse-ide-mode
8331 (setq dup (js2-get-label-by-name labeled-stmt name)))
8332 (js2-report-error "msg.dup.label" nil
8333 (js2-node-abs-pos dup) (js2-node-len dup)))
8334 (js2-report-error "msg.dup.label" nil
8335 (js2-node-pos label) (js2-node-len label)))
8336 (js2-labeled-stmt-node-add-label bundle label)
8337 (js2-node-add-children bundle label)
8338 ;; Add one reference to the bundle per label in `js2-label-set'
8339 (push (cons name bundle) js2-label-set)))
8340
8341 (defun js2-parse-name-or-label ()
8342 "Parser for identifier or label. Last token matched must be js2-NAME.
8343 Called when we found a name in a statement context. If it's a label, we gather
8344 up any following labels and the next non-label statement into a
8345 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8346 expression and return it wrapped in a `js2-expr-stmt-node'."
8347 (let ((pos (js2-current-token-beg))
8348 expr stmt bundle
8349 (continue t))
8350 ;; set check for label and call down to `js2-parse-primary-expr'
8351 (setq expr (js2-maybe-parse-label))
8352 (if (null expr)
8353 ;; Parse the non-label expression and wrap with expression stmt.
8354 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
8355 ;; else parsed a label
8356 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8357 (js2-record-label expr bundle)
8358 ;; look for more labels
8359 (while (and continue (= (js2-get-token) js2-NAME))
8360 (if (setq expr (js2-maybe-parse-label))
8361 (js2-record-label expr bundle)
8362 (setq expr (js2-parse-expr)
8363 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8364 continue nil)
8365 (js2-auto-insert-semicolon stmt)))
8366 ;; no more labels; now parse the labeled statement
8367 (unwind-protect
8368 (unless stmt
8369 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8370 (js2-unget-token)
8371 (setq stmt (js2-statement-helper))))
8372 ;; remove the labels for this statement from the global set
8373 (dolist (label (js2-labeled-stmt-node-labels bundle))
8374 (setq js2-label-set (remove label js2-label-set))))
8375 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8376 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8377 (js2-node-add-children bundle stmt)
8378 bundle)))
8379
8380 (defun js2-maybe-parse-label ()
8381 (assert (= (js2-current-token-type) js2-NAME))
8382 (let (label-pos
8383 (next-tt (js2-get-token))
8384 (label-end (js2-current-token-end)))
8385 ;; Do not consume colon, it is used as unwind indicator
8386 ;; to return to statementHelper.
8387 (js2-unget-token)
8388 (if (= next-tt js2-COLON)
8389 (prog2
8390 (setq label-pos (js2-current-token-beg))
8391 (make-js2-label-node :pos label-pos
8392 :len (- label-end label-pos)
8393 :name (js2-current-token-string))
8394 (js2-set-face label-pos
8395 label-end
8396 'font-lock-variable-name-face 'record))
8397 ;; Backtrack from the name token, too.
8398 (js2-unget-token)
8399 nil)))
8400
8401 (defun js2-parse-expr-stmt ()
8402 "Default parser in statement context, if no recognized statement found."
8403 (js2-wrap-with-expr-stmt (js2-current-token-beg)
8404 (progn
8405 (js2-unget-token)
8406 (js2-parse-expr)) t))
8407
8408 (defun js2-parse-variables (decl-type pos)
8409 "Parse a comma-separated list of variable declarations.
8410 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8411
8412 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8413 For 'var' or 'const', the keyword should be the token last scanned.
8414
8415 POS is the position where the node should start. It's sometimes the
8416 var/const/let keyword, and other times the beginning of the first token
8417 in the first variable declaration.
8418
8419 Returns the parsed `js2-var-decl-node' expression node."
8420 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8421 :pos pos))
8422 destructuring kid-pos tt init name end nbeg nend vi
8423 (continue t))
8424 ;; Example:
8425 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8426 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8427 ;; var {a, b} = baz;
8428 (while continue
8429 (setq destructuring nil
8430 name nil
8431 tt (js2-get-token)
8432 kid-pos (js2-current-token-beg)
8433 end (js2-current-token-end)
8434 init nil)
8435 (if (or (= tt js2-LB) (= tt js2-LC))
8436 ;; Destructuring assignment, e.g., var [a, b] = ...
8437 (setq destructuring (js2-parse-destruct-primary-expr)
8438 end (js2-node-end destructuring))
8439 ;; Simple variable name
8440 (js2-unget-token)
8441 (when (js2-must-match-name "msg.bad.var")
8442 (setq name (js2-create-name-node)
8443 nbeg (js2-current-token-beg)
8444 nend (js2-current-token-end)
8445 end nend)
8446 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
8447 (when (js2-match-token js2-ASSIGN)
8448 (setq init (js2-parse-assign-expr)
8449 end (js2-node-end init))
8450 (js2-record-imenu-functions init name))
8451 (when name
8452 (js2-set-face nbeg nend (if (js2-function-node-p init)
8453 'font-lock-function-name-face
8454 'font-lock-variable-name-face)
8455 'record))
8456 (setq vi (make-js2-var-init-node :pos kid-pos
8457 :len (- end kid-pos)
8458 :type decl-type))
8459 (if destructuring
8460 (progn
8461 (if (and (null init) (not js2-in-for-init))
8462 (js2-report-error "msg.destruct.assign.no.init"))
8463 (js2-define-destruct-symbols destructuring
8464 decl-type
8465 'font-lock-variable-name-face)
8466 (setf (js2-var-init-node-target vi) destructuring))
8467 (setf (js2-var-init-node-target vi) name))
8468 (setf (js2-var-init-node-initializer vi) init)
8469 (js2-node-add-children vi name destructuring init)
8470 (js2-block-node-push result vi)
8471 (unless (js2-match-token js2-COMMA)
8472 (setq continue nil)))
8473 (setf (js2-node-len result) (- end pos))
8474 result))
8475
8476 (defun js2-parse-let (pos &optional stmt-p)
8477 "Parse a let expression or statement.
8478 A let-expression is of the form `let (vars) expr'.
8479 A let-statment is of the form `let (vars) {statements}'.
8480 The third form of let is a variable declaration list, handled
8481 by `js2-parse-variables'."
8482 (let ((pn (make-js2-let-node :pos pos))
8483 beg vars body)
8484 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8485 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
8486 (js2-push-scope pn)
8487 (unwind-protect
8488 (progn
8489 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
8490 (if (js2-must-match js2-RP "msg.no.paren.let")
8491 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
8492 (if (and stmt-p (js2-match-token js2-LC))
8493 ;; let statement
8494 (progn
8495 (setf beg (js2-current-token-beg) ; position stmt at LC
8496 body (js2-parse-statements))
8497 (js2-must-match js2-RC "msg.no.curly.let")
8498 (setf (js2-node-len body) (- (js2-current-token-end) beg)
8499 (js2-node-len pn) (- (js2-current-token-end) pos)
8500 (js2-let-node-body pn) body
8501 (js2-node-type pn) js2-LET))
8502 ;; let expression
8503 (setf body (js2-parse-expr)
8504 (js2-node-len pn) (- (js2-node-end body) pos)
8505 (js2-let-node-body pn) body))
8506 (setf (js2-let-node-vars pn) vars)
8507 (js2-node-add-children pn vars body))
8508 (js2-pop-scope))
8509 pn))
8510
8511 (defun js2-define-new-symbol (decl-type name node &optional scope)
8512 (js2-scope-put-symbol (or scope js2-current-scope)
8513 name
8514 (make-js2-symbol decl-type name node)))
8515
8516 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8517 "Define a symbol in the current scope.
8518 If NODE is non-nil, it is the AST node associated with the symbol."
8519 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8520 (symbol (if defining-scope
8521 (js2-scope-get-symbol defining-scope name)))
8522 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8523 (cond
8524 ((and symbol ; already defined
8525 (or (= sdt js2-CONST) ; old version is const
8526 (= decl-type js2-CONST) ; new version is const
8527 ;; two let-bound vars in this block have same name
8528 (and (= sdt js2-LET)
8529 (eq defining-scope js2-current-scope))))
8530 (js2-report-error
8531 (cond
8532 ((= sdt js2-CONST) "msg.const.redecl")
8533 ((= sdt js2-LET) "msg.let.redecl")
8534 ((= sdt js2-VAR) "msg.var.redecl")
8535 ((= sdt js2-FUNCTION) "msg.function.redecl")
8536 (t "msg.parm.redecl"))
8537 name))
8538 ((= decl-type js2-LET)
8539 (if (and (not ignore-not-in-block)
8540 (or (= (js2-node-type js2-current-scope) js2-IF)
8541 (js2-loop-node-p js2-current-scope)))
8542 (js2-report-error "msg.let.decl.not.in.block")
8543 (js2-define-new-symbol decl-type name node)))
8544 ((or (= decl-type js2-VAR)
8545 (= decl-type js2-CONST)
8546 (= decl-type js2-FUNCTION))
8547 (if symbol
8548 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8549 (js2-add-strict-warning "msg.var.redecl" name)
8550 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8551 (js2-add-strict-warning "msg.var.hides.arg" name)))
8552 (js2-define-new-symbol decl-type name node
8553 js2-current-script-or-fn)))
8554 ((= decl-type js2-LP)
8555 (if symbol
8556 ;; must be duplicate parameter. Second parameter hides the
8557 ;; first, so go ahead and add the second pararameter
8558 (js2-report-warning "msg.dup.parms" name))
8559 (js2-define-new-symbol decl-type name node))
8560 (t (js2-code-bug)))))
8561
8562 (defun js2-parse-paren-expr-or-generator-comp ()
8563 (let ((px-pos (js2-current-token-beg)))
8564 (if (and (>= js2-language-version 200)
8565 (js2-match-token js2-FOR))
8566 (js2-parse-generator-comp px-pos)
8567 (let* ((js2-in-for-init nil)
8568 (expr (js2-parse-expr))
8569 (pn (make-js2-paren-node :pos px-pos
8570 :expr expr
8571 :len (- (js2-current-token-end)
8572 px-pos))))
8573 (js2-node-add-children pn (js2-paren-node-expr pn))
8574 (js2-must-match js2-RP "msg.no.paren")
8575 pn))))
8576
8577 (defun js2-parse-expr (&optional oneshot)
8578 (let* ((pn (js2-parse-assign-expr))
8579 (pos (js2-node-pos pn))
8580 left
8581 right
8582 op-pos)
8583 (while (and (not oneshot)
8584 (js2-match-token js2-COMMA))
8585 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
8586 (if (= (js2-peek-token) js2-YIELD)
8587 (js2-report-error "msg.yield.parenthesized"))
8588 (setq right (js2-parse-assign-expr)
8589 left pn
8590 pn (make-js2-infix-node :type js2-COMMA
8591 :pos pos
8592 :len (- js2-ts-cursor pos)
8593 :op-pos op-pos
8594 :left left
8595 :right right))
8596 (js2-node-add-children pn left right))
8597 pn))
8598
8599 (defun js2-parse-assign-expr ()
8600 (let ((tt (js2-get-token))
8601 (pos (js2-current-token-beg))
8602 pn left right op-pos
8603 ts-state recorded-identifiers parsed-errors)
8604 (if (= tt js2-YIELD)
8605 (js2-parse-return-or-yield tt t)
8606 ;; Save the tokenizer state in case we find an arrow function
8607 ;; and have to rewind.
8608 (setq ts-state (make-js2-ts-state)
8609 recorded-identifiers js2-recorded-identifiers
8610 parsed-errors js2-parsed-errors)
8611 ;; not yield - parse assignment expression
8612 (setq pn (js2-parse-cond-expr)
8613 tt (js2-get-token))
8614 (cond
8615 ((and (<= js2-first-assign tt)
8616 (<= tt js2-last-assign))
8617 ;; tt express assignment (=, |=, ^=, ..., %=)
8618 (setq op-pos (- (js2-current-token-beg) pos) ; relative
8619 left pn)
8620 (setq right (js2-parse-assign-expr)
8621 pn (make-js2-assign-node :type tt
8622 :pos pos
8623 :len (- (js2-node-end right) pos)
8624 :op-pos op-pos
8625 :left left
8626 :right right))
8627 (when js2-parse-ide-mode
8628 (js2-highlight-assign-targets pn left right)
8629 (js2-record-imenu-functions right left))
8630 ;; do this last so ide checks above can use absolute positions
8631 (js2-node-add-children pn left right))
8632 ((and (= tt js2-ARROW)
8633 (>= js2-language-version 200))
8634 (js2-ts-seek ts-state)
8635 (setq js2-recorded-identifiers recorded-identifiers
8636 js2-parsed-errors parsed-errors)
8637 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
8638 (t
8639 (js2-unget-token)))
8640 pn)))
8641
8642 (defun js2-parse-cond-expr ()
8643 (let ((pos (js2-current-token-beg))
8644 (pn (js2-parse-or-expr))
8645 test-expr
8646 if-true
8647 if-false
8648 q-pos
8649 c-pos)
8650 (when (js2-match-token js2-HOOK)
8651 (setq q-pos (- (js2-current-token-beg) pos)
8652 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
8653 (js2-must-match js2-COLON "msg.no.colon.cond")
8654 (setq c-pos (- (js2-current-token-beg) pos)
8655 if-false (js2-parse-assign-expr)
8656 test-expr pn
8657 pn (make-js2-cond-node :pos pos
8658 :len (- (js2-node-end if-false) pos)
8659 :test-expr test-expr
8660 :true-expr if-true
8661 :false-expr if-false
8662 :q-pos q-pos
8663 :c-pos c-pos))
8664 (js2-node-add-children pn test-expr if-true if-false))
8665 pn))
8666
8667 (defun js2-make-binary (type left parser)
8668 "Helper for constructing a binary-operator AST node.
8669 LEFT is the left-side-expression, already parsed, and the
8670 binary operator should have just been matched.
8671 PARSER is a function to call to parse the right operand,
8672 or a `js2-node' struct if it has already been parsed.
8673 FIXME: The latter option is unused?"
8674 (let* ((pos (js2-node-pos left))
8675 (op-pos (- (js2-current-token-beg) pos))
8676 (right (if (js2-node-p parser)
8677 parser
8678 (js2-get-token)
8679 (funcall parser)))
8680 (pn (make-js2-infix-node :type type
8681 :pos pos
8682 :len (- (js2-node-end right) pos)
8683 :op-pos op-pos
8684 :left left
8685 :right right)))
8686 (js2-node-add-children pn left right)
8687 pn))
8688
8689 (defun js2-parse-or-expr ()
8690 (let ((pn (js2-parse-and-expr)))
8691 (when (js2-match-token js2-OR)
8692 (setq pn (js2-make-binary js2-OR
8693 pn
8694 'js2-parse-or-expr)))
8695 pn))
8696
8697 (defun js2-parse-and-expr ()
8698 (let ((pn (js2-parse-bit-or-expr)))
8699 (when (js2-match-token js2-AND)
8700 (setq pn (js2-make-binary js2-AND
8701 pn
8702 'js2-parse-and-expr)))
8703 pn))
8704
8705 (defun js2-parse-bit-or-expr ()
8706 (let ((pn (js2-parse-bit-xor-expr)))
8707 (while (js2-match-token js2-BITOR)
8708 (setq pn (js2-make-binary js2-BITOR
8709 pn
8710 'js2-parse-bit-xor-expr)))
8711 pn))
8712
8713 (defun js2-parse-bit-xor-expr ()
8714 (let ((pn (js2-parse-bit-and-expr)))
8715 (while (js2-match-token js2-BITXOR)
8716 (setq pn (js2-make-binary js2-BITXOR
8717 pn
8718 'js2-parse-bit-and-expr)))
8719 pn))
8720
8721 (defun js2-parse-bit-and-expr ()
8722 (let ((pn (js2-parse-eq-expr)))
8723 (while (js2-match-token js2-BITAND)
8724 (setq pn (js2-make-binary js2-BITAND
8725 pn
8726 'js2-parse-eq-expr)))
8727 pn))
8728
8729 (defconst js2-parse-eq-ops
8730 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8731
8732 (defun js2-parse-eq-expr ()
8733 (let ((pn (js2-parse-rel-expr))
8734 tt)
8735 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
8736 (setq pn (js2-make-binary tt
8737 pn
8738 'js2-parse-rel-expr)))
8739 (js2-unget-token)
8740 pn))
8741
8742 (defconst js2-parse-rel-ops
8743 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8744
8745 (defun js2-parse-rel-expr ()
8746 (let ((pn (js2-parse-shift-expr))
8747 (continue t)
8748 tt)
8749 (while continue
8750 (setq tt (js2-get-token))
8751 (cond
8752 ((and js2-in-for-init (= tt js2-IN))
8753 (js2-unget-token)
8754 (setq continue nil))
8755 ((memq tt js2-parse-rel-ops)
8756 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8757 (t
8758 (js2-unget-token)
8759 (setq continue nil))))
8760 pn))
8761
8762 (defconst js2-parse-shift-ops
8763 (list js2-LSH js2-URSH js2-RSH))
8764
8765 (defun js2-parse-shift-expr ()
8766 (let ((pn (js2-parse-add-expr))
8767 tt
8768 (continue t))
8769 (while continue
8770 (setq tt (js2-get-token))
8771 (if (memq tt js2-parse-shift-ops)
8772 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
8773 (js2-unget-token)
8774 (setq continue nil)))
8775 pn))
8776
8777 (defun js2-parse-add-expr ()
8778 (let ((pn (js2-parse-mul-expr))
8779 tt
8780 (continue t))
8781 (while continue
8782 (setq tt (js2-get-token))
8783 (if (or (= tt js2-ADD) (= tt js2-SUB))
8784 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
8785 (js2-unget-token)
8786 (setq continue nil)))
8787 pn))
8788
8789 (defconst js2-parse-mul-ops
8790 (list js2-MUL js2-DIV js2-MOD))
8791
8792 (defun js2-parse-mul-expr ()
8793 (let ((pn (js2-parse-unary-expr))
8794 tt
8795 (continue t))
8796 (while continue
8797 (setq tt (js2-get-token))
8798 (if (memq tt js2-parse-mul-ops)
8799 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
8800 (js2-unget-token)
8801 (setq continue nil)))
8802 pn))
8803
8804 (defun js2-make-unary (type parser &rest args)
8805 "Make a unary node of type TYPE.
8806 PARSER is either a node (for postfix operators) or a function to call
8807 to parse the operand (for prefix operators)."
8808 (let* ((pos (js2-current-token-beg))
8809 (postfix (js2-node-p parser))
8810 (expr (if postfix
8811 parser
8812 (apply parser args)))
8813 end
8814 pn)
8815 (if postfix ; e.g. i++
8816 (setq pos (js2-node-pos expr)
8817 end (js2-current-token-end))
8818 (setq end (js2-node-end expr)))
8819 (setq pn (make-js2-unary-node :type type
8820 :pos pos
8821 :len (- end pos)
8822 :operand expr))
8823 (js2-node-add-children pn expr)
8824 pn))
8825
8826 (defconst js2-incrementable-node-types
8827 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8828 "Node types that can be the operand of a ++ or -- operator.")
8829
8830 (defun js2-check-bad-inc-dec (tt beg end unary)
8831 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8832 js2-incrementable-node-types)
8833 (js2-report-error (if (= tt js2-INC)
8834 "msg.bad.incr"
8835 "msg.bad.decr")
8836 nil beg (- end beg))))
8837
8838 (defun js2-parse-unary-expr ()
8839 (let ((tt (js2-current-token-type))
8840 pn expr beg end)
8841 (cond
8842 ((or (= tt js2-VOID)
8843 (= tt js2-NOT)
8844 (= tt js2-BITNOT)
8845 (= tt js2-TYPEOF))
8846 (js2-get-token)
8847 (js2-make-unary tt 'js2-parse-unary-expr))
8848 ((= tt js2-ADD)
8849 (js2-get-token)
8850 ;; Convert to special POS token in decompiler and parse tree
8851 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8852 ((= tt js2-SUB)
8853 (js2-get-token)
8854 ;; Convert to special NEG token in decompiler and parse tree
8855 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8856 ((or (= tt js2-INC)
8857 (= tt js2-DEC))
8858 (js2-get-token)
8859 (prog1
8860 (setq beg (js2-current-token-beg)
8861 end (js2-current-token-end)
8862 expr (js2-make-unary tt 'js2-parse-member-expr t))
8863 (js2-check-bad-inc-dec tt beg end expr)))
8864 ((= tt js2-DELPROP)
8865 (js2-get-token)
8866 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8867 ((= tt js2-ERROR)
8868 (js2-get-token)
8869 (make-js2-error-node)) ; try to continue
8870 ((and (= tt js2-LT)
8871 js2-compiler-xml-available)
8872 ;; XML stream encountered in expression.
8873 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8874 (t
8875 (setq pn (js2-parse-member-expr t)
8876 ;; Don't look across a newline boundary for a postfix incop.
8877 tt (js2-peek-token-or-eol))
8878 (when (or (= tt js2-INC) (= tt js2-DEC))
8879 (js2-get-token)
8880 (setf expr pn
8881 pn (js2-make-unary tt expr))
8882 (js2-node-set-prop pn 'postfix t)
8883 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
8884 pn))))
8885
8886 (defun js2-parse-xml-initializer ()
8887 "Parse an E4X XML initializer.
8888 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8889 Then I'll postprocess the result, depending on whether we're in IDE
8890 mode or codegen mode, and generate the appropriate rewritten AST.
8891 IDE mode uses a rich AST that models the XML structure. Codegen mode
8892 just concatenates everything and makes a new XML or XMLList out of it."
8893 (let ((tt (js2-get-first-xml-token))
8894 pn-xml pn expr kids expr-pos
8895 (continue t)
8896 (first-token t))
8897 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8898 (js2-report-error "msg.syntax"))
8899 (setq pn-xml (make-js2-xml-node))
8900 (while continue
8901 (if first-token
8902 (setq first-token nil)
8903 (setq tt (js2-get-next-xml-token)))
8904 (cond
8905 ;; js2-XML means we found a {expr} in the XML stream.
8906 ;; The token string is the XML up to the left-curly.
8907 ((= tt js2-XML)
8908 (push (make-js2-string-node :pos (js2-current-token-beg)
8909 :len (- js2-ts-cursor (js2-current-token-beg)))
8910 kids)
8911 (js2-must-match js2-LC "msg.syntax")
8912 (setq expr-pos js2-ts-cursor
8913 expr (if (eq (js2-peek-token) js2-RC)
8914 (make-js2-empty-expr-node :pos expr-pos)
8915 (js2-parse-expr)))
8916 (js2-must-match js2-RC "msg.syntax")
8917 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8918 :len (js2-node-len expr)
8919 :expr expr))
8920 (js2-node-add-children pn expr)
8921 (push pn kids))
8922 ;; a js2-XMLEND token means we hit the final close-tag.
8923 ((= tt js2-XMLEND)
8924 (push (make-js2-string-node :pos (js2-current-token-beg)
8925 :len (- js2-ts-cursor (js2-current-token-beg)))
8926 kids)
8927 (dolist (kid (nreverse kids))
8928 (js2-block-node-push pn-xml kid))
8929 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8930 (js2-node-pos pn-xml))
8931 continue nil))
8932 (t
8933 (js2-report-error "msg.syntax")
8934 (setq continue nil))))
8935 pn-xml))
8936
8937
8938 (defun js2-parse-argument-list ()
8939 "Parse an argument list and return it as a Lisp list of nodes.
8940 Returns the list in reverse order. Consumes the right-paren token."
8941 (let (result)
8942 (unless (js2-match-token js2-RP)
8943 (loop do
8944 (let ((tt (js2-get-token)))
8945 (if (= tt js2-YIELD)
8946 (js2-report-error "msg.yield.parenthesized"))
8947 (if (and (= tt js2-TRIPLEDOT)
8948 (>= js2-language-version 200))
8949 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
8950 (js2-unget-token)
8951 (push (js2-parse-assign-expr) result)))
8952 while
8953 (js2-match-token js2-COMMA))
8954 (js2-must-match js2-RP "msg.no.paren.arg")
8955 result)))
8956
8957 (defun js2-parse-member-expr (&optional allow-call-syntax)
8958 (let ((tt (js2-current-token-type))
8959 pn pos target args beg end init)
8960 (if (/= tt js2-NEW)
8961 (setq pn (js2-parse-primary-expr))
8962 ;; parse a 'new' expression
8963 (js2-get-token)
8964 (setq pos (js2-current-token-beg)
8965 beg pos
8966 target (js2-parse-member-expr)
8967 end (js2-node-end target)
8968 pn (make-js2-new-node :pos pos
8969 :target target
8970 :len (- end pos)))
8971 (js2-highlight-function-call (js2-current-token))
8972 (js2-node-add-children pn target)
8973 (when (js2-match-token js2-LP)
8974 ;; Add the arguments to pn, if any are supplied.
8975 (setf beg pos ; start of "new" keyword
8976 pos (js2-current-token-beg)
8977 args (nreverse (js2-parse-argument-list))
8978 (js2-new-node-args pn) args
8979 end (js2-current-token-end)
8980 (js2-new-node-lp pn) (- pos beg)
8981 (js2-new-node-rp pn) (- end 1 beg))
8982 (apply #'js2-node-add-children pn args))
8983 (when (and js2-allow-rhino-new-expr-initializer
8984 (js2-match-token js2-LC))
8985 (setf init (js2-parse-object-literal)
8986 end (js2-node-end init)
8987 (js2-new-node-initializer pn) init)
8988 (js2-node-add-children pn init))
8989 (setf (js2-node-len pn) (- end beg))) ; end outer if
8990 (js2-parse-member-expr-tail allow-call-syntax pn)))
8991
8992 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8993 "Parse a chain of property/array accesses or function calls.
8994 Includes parsing for E4X operators like `..' and `.@'.
8995 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8996 Returns an expression tree that includes PN, the parent node."
8997 (let (tt
8998 (continue t))
8999 (while continue
9000 (setq tt (js2-get-token))
9001 (cond
9002 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9003 (setq pn (js2-parse-property-access tt pn)))
9004 ((= tt js2-DOTQUERY)
9005 (setq pn (js2-parse-dot-query pn)))
9006 ((= tt js2-LB)
9007 (setq pn (js2-parse-element-get pn)))
9008 ((= tt js2-LP)
9009 (js2-unget-token)
9010 (if allow-call-syntax
9011 (setq pn (js2-parse-function-call pn))
9012 (setq continue nil)))
9013 (t
9014 (js2-unget-token)
9015 (setq continue nil))))
9016 (if (>= js2-highlight-level 2)
9017 (js2-parse-highlight-member-expr-node pn))
9018 pn))
9019
9020 (defun js2-parse-dot-query (pn)
9021 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9022 Last token parsed must be `js2-DOTQUERY'."
9023 (let ((pos (js2-node-pos pn))
9024 op-pos expr end)
9025 (js2-must-have-xml)
9026 (js2-set-requires-activation)
9027 (setq op-pos (js2-current-token-beg)
9028 expr (js2-parse-expr)
9029 end (js2-node-end expr)
9030 pn (make-js2-xml-dot-query-node :left pn
9031 :pos pos
9032 :op-pos op-pos
9033 :right expr))
9034 (js2-node-add-children pn
9035 (js2-xml-dot-query-node-left pn)
9036 (js2-xml-dot-query-node-right pn))
9037 (if (js2-must-match js2-RP "msg.no.paren")
9038 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9039 end (js2-current-token-end)))
9040 (setf (js2-node-len pn) (- end pos))
9041 pn))
9042
9043 (defun js2-parse-element-get (pn)
9044 "Parse an element-get expression, e.g. foo[bar].
9045 Last token parsed must be `js2-RB'."
9046 (let ((lb (js2-current-token-beg))
9047 (pos (js2-node-pos pn))
9048 rb expr)
9049 (setq expr (js2-parse-expr))
9050 (if (js2-must-match js2-RB "msg.no.bracket.index")
9051 (setq rb (js2-current-token-beg)))
9052 (setq pn (make-js2-elem-get-node :target pn
9053 :pos pos
9054 :element expr
9055 :lb (js2-relpos lb pos)
9056 :rb (js2-relpos rb pos)
9057 :len (- (js2-current-token-end) pos)))
9058 (js2-node-add-children pn
9059 (js2-elem-get-node-target pn)
9060 (js2-elem-get-node-element pn))
9061 pn))
9062
9063 (defun js2-highlight-function-call (token)
9064 (when (eq (js2-token-type token) js2-NAME)
9065 (js2-record-face 'js2-function-call token)))
9066
9067 (defun js2-parse-function-call (pn)
9068 (js2-highlight-function-call (js2-current-token))
9069 (js2-get-token)
9070 (let (args
9071 (pos (js2-node-pos pn)))
9072 (setq pn (make-js2-call-node :pos pos
9073 :target pn
9074 :lp (- (js2-current-token-beg) pos)))
9075 (js2-node-add-children pn (js2-call-node-target pn))
9076 ;; Add the arguments to pn, if any are supplied.
9077 (setf args (nreverse (js2-parse-argument-list))
9078 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9079 (js2-call-node-args pn) args)
9080 (apply #'js2-node-add-children pn args)
9081 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9082 pn))
9083
9084 (defun js2-parse-property-access (tt pn)
9085 "Parse a property access, XML descendants access, or XML attr access."
9086 (let ((member-type-flags 0)
9087 (dot-pos (js2-current-token-beg))
9088 (dot-len (if (= tt js2-DOTDOT) 2 1))
9089 name
9090 ref ; right side of . or .. operator
9091 result)
9092 (when (= tt js2-DOTDOT)
9093 (js2-must-have-xml)
9094 (setq member-type-flags js2-descendants-flag))
9095 (if (not js2-compiler-xml-available)
9096 (progn
9097 (js2-must-match-prop-name "msg.no.name.after.dot")
9098 (setq name (js2-create-name-node t js2-GETPROP)
9099 result (make-js2-prop-get-node :left pn
9100 :pos (js2-current-token-beg)
9101 :right name
9102 :len (js2-current-token-len)))
9103 (js2-node-add-children result pn name)
9104 result)
9105 ;; otherwise look for XML operators
9106 (setf result (if (= tt js2-DOT)
9107 (make-js2-prop-get-node)
9108 (make-js2-infix-node :type js2-DOTDOT))
9109 (js2-node-pos result) (js2-node-pos pn)
9110 (js2-infix-node-op-pos result) dot-pos
9111 (js2-infix-node-left result) pn ; do this after setting position
9112 tt (js2-next-token))
9113 (cond
9114 ;; needed for generator.throw()
9115 ((= tt js2-THROW)
9116 (setq ref (js2-parse-property-name nil nil member-type-flags)))
9117 ;; handles: name, ns::name, ns::*, ns::[expr]
9118 ((js2-valid-prop-name-token tt)
9119 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9120 ;; handles: *, *::name, *::*, *::[expr]
9121 ((= tt js2-MUL)
9122 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9123 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9124 ((= tt js2-XMLATTR)
9125 (setq result (js2-parse-attribute-access)))
9126 (t
9127 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9128 (if ref
9129 (setf (js2-node-len result) (- (js2-node-end ref)
9130 (js2-node-pos result))
9131 (js2-infix-node-right result) ref))
9132 (if (js2-infix-node-p result)
9133 (js2-node-add-children result
9134 (js2-infix-node-left result)
9135 (js2-infix-node-right result)))
9136 result)))
9137
9138 (defun js2-parse-attribute-access ()
9139 "Parse an E4X XML attribute expression.
9140 This includes expressions of the forms:
9141
9142 @attr @ns::attr @ns::*
9143 @* @*::attr @*::*
9144 @[expr] @*::[expr] @ns::[expr]
9145
9146 Called if we peeked an '@' token."
9147 (let ((tt (js2-next-token))
9148 (at-pos (js2-current-token-beg)))
9149 (cond
9150 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9151 ((js2-valid-prop-name-token tt)
9152 (js2-parse-property-name at-pos nil 0))
9153 ;; handles: @*, @*::name, @*::*, @*::[expr]
9154 ((= tt js2-MUL)
9155 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9156 ;; handles @[expr]
9157 ((= tt js2-LB)
9158 (js2-parse-xml-elem-ref at-pos))
9159 (t
9160 (js2-report-error "msg.no.name.after.xmlAttr")
9161 ;; Avoid cascaded errors that happen if we make an error node here.
9162 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9163
9164 (defun js2-parse-property-name (at-pos s member-type-flags)
9165 "Check if :: follows name in which case it becomes qualified name.
9166
9167 AT-POS is a natural number if we just read an '@' token, else nil.
9168 S is the name or string that was matched: an identifier, 'throw' or '*'.
9169 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9170
9171 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9172 operator, or the name is followed by ::. For a plain name, returns a
9173 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9174 (let ((pos (or at-pos (js2-current-token-beg)))
9175 colon-pos
9176 (name (js2-create-name-node t (js2-current-token-type) s))
9177 ns tt pn)
9178 (catch 'return
9179 (when (js2-match-token js2-COLONCOLON)
9180 (setq ns name
9181 colon-pos (js2-current-token-beg)
9182 tt (js2-next-token))
9183 (cond
9184 ;; handles name::name
9185 ((js2-valid-prop-name-token tt)
9186 (setq name (js2-create-name-node)))
9187 ;; handles name::*
9188 ((= tt js2-MUL)
9189 (setq name (js2-create-name-node nil nil "*")))
9190 ;; handles name::[expr]
9191 ((= tt js2-LB)
9192 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9193 (t
9194 (js2-report-error "msg.no.name.after.coloncolon"))))
9195 (if (and (null ns) (zerop member-type-flags))
9196 name
9197 (prog1
9198 (setq pn
9199 (make-js2-xml-prop-ref-node :pos pos
9200 :len (- (js2-node-end name) pos)
9201 :at-pos at-pos
9202 :colon-pos colon-pos
9203 :propname name))
9204 (js2-node-add-children pn name))))))
9205
9206 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9207 "Parse the [expr] portion of an xml element reference.
9208 For instance, @[expr], @*::[expr], or ns::[expr]."
9209 (let* ((lb (js2-current-token-beg))
9210 (pos (or at-pos lb))
9211 rb
9212 (expr (js2-parse-expr))
9213 (end (js2-node-end expr))
9214 pn)
9215 (if (js2-must-match js2-RB "msg.no.bracket.index")
9216 (setq rb (js2-current-token-beg)
9217 end (js2-current-token-end)))
9218 (prog1
9219 (setq pn
9220 (make-js2-xml-elem-ref-node :pos pos
9221 :len (- end pos)
9222 :namespace namespace
9223 :colon-pos colon-pos
9224 :at-pos at-pos
9225 :expr expr
9226 :lb (js2-relpos lb pos)
9227 :rb (js2-relpos rb pos)))
9228 (js2-node-add-children pn namespace expr))))
9229
9230 (defun js2-parse-destruct-primary-expr ()
9231 (let ((js2-is-in-destructuring t))
9232 (js2-parse-primary-expr)))
9233
9234 (defun js2-parse-primary-expr ()
9235 "Parse a literal (leaf) expression of some sort.
9236 Includes complex literals such as functions, object-literals,
9237 array-literals, array comprehensions and regular expressions."
9238 (let (pn ; parent node (usually return value)
9239 tt)
9240 (setq tt (js2-current-token-type))
9241 (cond
9242 ((= tt js2-FUNCTION)
9243 (js2-parse-function-expr))
9244 ((= tt js2-LB)
9245 (js2-parse-array-comp-or-literal))
9246 ((= tt js2-LC)
9247 (js2-parse-object-literal))
9248 ((= tt js2-LET)
9249 (js2-parse-let (js2-current-token-beg)))
9250 ((= tt js2-LP)
9251 (js2-parse-paren-expr-or-generator-comp))
9252 ((= tt js2-XMLATTR)
9253 (js2-must-have-xml)
9254 (js2-parse-attribute-access))
9255 ((= tt js2-NAME)
9256 (js2-parse-name tt))
9257 ((= tt js2-NUMBER)
9258 (make-js2-number-node))
9259 ((= tt js2-STRING)
9260 (prog1
9261 (make-js2-string-node)
9262 (js2-record-face 'font-lock-string-face)))
9263 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9264 ;; Got / or /= which in this context means a regexp literal
9265 (let ((px-pos (js2-current-token-beg))
9266 (flags (js2-read-regexp tt))
9267 (end (js2-current-token-end)))
9268 (prog1
9269 (make-js2-regexp-node :pos px-pos
9270 :len (- end px-pos)
9271 :value (js2-current-token-string)
9272 :flags flags)
9273 (js2-set-face px-pos end 'font-lock-string-face 'record)
9274 (js2-record-text-property px-pos end 'syntax-table '(2)))))
9275 ((or (= tt js2-NULL)
9276 (= tt js2-THIS)
9277 (= tt js2-FALSE)
9278 (= tt js2-TRUE))
9279 (make-js2-keyword-node :type tt))
9280 ((= tt js2-RP)
9281 ;; Not valid expression syntax, but this is valid in an arrow
9282 ;; function with no params: () => body.
9283 (if (eq (js2-peek-token) js2-ARROW)
9284 (progn
9285 (js2-unget-token) ; Put back the right paren.
9286 ;; Return whatever, it will hopefully be rewinded and
9287 ;; reparsed when we reach the =>.
9288 (make-js2-keyword-node :type js2-NULL))
9289 (js2-report-error "msg.syntax")
9290 (make-js2-error-node)))
9291 ((= tt js2-TRIPLEDOT)
9292 ;; Likewise, only valid in an arrow function with a rest param.
9293 (if (and (js2-match-token js2-NAME)
9294 (js2-match-token js2-RP)
9295 (eq (js2-peek-token) js2-ARROW))
9296 (progn
9297 (js2-unget-token) ; Put back the right paren.
9298 ;; See the previous case.
9299 (make-js2-keyword-node :type js2-NULL))
9300 (js2-report-error "msg.syntax")
9301 (make-js2-error-node)))
9302 ((= tt js2-RESERVED)
9303 (js2-report-error "msg.reserved.id")
9304 (make-js2-name-node))
9305 ((= tt js2-ERROR)
9306 ;; the scanner or one of its subroutines reported the error.
9307 (make-js2-error-node))
9308 ((= tt js2-EOF)
9309 (let* ((px-pos (point-at-bol))
9310 (len (- js2-ts-cursor px-pos)))
9311 (js2-report-error "msg.unexpected.eof" nil px-pos len))
9312 (make-js2-error-node :pos (1- js2-ts-cursor)))
9313 (t
9314 (js2-report-error "msg.syntax")
9315 (make-js2-error-node)))))
9316
9317 (defun js2-parse-name (_tt)
9318 (let ((name (js2-current-token-string))
9319 node)
9320 (setq node (if js2-compiler-xml-available
9321 (js2-parse-property-name nil name 0)
9322 (js2-create-name-node 'check-activation nil name)))
9323 (if js2-highlight-external-variables
9324 (js2-record-name-node node))
9325 node))
9326
9327 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9328 (js2-add-strict-warning
9329 msg nil
9330 ;; back up from comma to beginning of line or array/objlit
9331 (max (if elems
9332 (js2-node-pos (car elems))
9333 pos)
9334 (save-excursion
9335 (goto-char comma-pos)
9336 (back-to-indentation)
9337 (point)))
9338 comma-pos))
9339
9340 (defun js2-parse-array-comp-or-literal ()
9341 (let ((pos (js2-current-token-beg)))
9342 (if (and (>= js2-language-version 200)
9343 (js2-match-token js2-FOR))
9344 (js2-parse-array-comp pos)
9345 (js2-parse-array-literal pos))))
9346
9347 (defun js2-parse-array-literal (pos)
9348 (let ((after-lb-or-comma t)
9349 after-comma tt elems pn
9350 (continue t))
9351 (unless js2-is-in-destructuring
9352 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
9353 (while continue
9354 (setq tt (js2-get-token))
9355 (cond
9356 ;; comma
9357 ((= tt js2-COMMA)
9358 (setq after-comma (js2-current-token-end))
9359 (if (not after-lb-or-comma)
9360 (setq after-lb-or-comma t)
9361 (push nil elems)))
9362 ;; end of array
9363 ((or (= tt js2-RB)
9364 (= tt js2-EOF)) ; prevent infinite loop
9365 (if (= tt js2-EOF)
9366 (js2-report-error "msg.no.bracket.arg" nil pos))
9367 (when (and after-comma (< js2-language-version 170))
9368 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9369 pos (remove nil elems) after-comma))
9370 (setq continue nil
9371 pn (make-js2-array-node :pos pos
9372 :len (- js2-ts-cursor pos)
9373 :elems (nreverse elems)))
9374 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
9375 ;; destructuring binding
9376 (js2-is-in-destructuring
9377 (push (if (or (= tt js2-LC)
9378 (= tt js2-LB)
9379 (= tt js2-NAME))
9380 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9381 (js2-parse-destruct-primary-expr)
9382 ;; invalid pattern
9383 (js2-report-error "msg.bad.var")
9384 (make-js2-error-node))
9385 elems)
9386 (setq after-lb-or-comma nil
9387 after-comma nil))
9388 ;; array comp
9389 ((and (>= js2-language-version 170)
9390 (= tt js2-FOR) ; check for array comprehension
9391 (not after-lb-or-comma) ; "for" can't follow a comma
9392 elems ; must have at least 1 element
9393 (not (cdr elems))) ; but no 2nd element
9394 (js2-unget-token)
9395 (setf continue nil
9396 pn (js2-parse-legacy-array-comp (car elems) pos)))
9397 ;; another element
9398 (t
9399 (unless after-lb-or-comma
9400 (js2-report-error "msg.no.bracket.arg"))
9401 (if (and (= tt js2-TRIPLEDOT)
9402 (>= js2-language-version 200))
9403 ;; spread operator
9404 (push (js2-make-unary tt 'js2-parse-assign-expr)
9405 elems)
9406 (js2-unget-token)
9407 (push (js2-parse-assign-expr) elems))
9408 (setq after-lb-or-comma nil
9409 after-comma nil))))
9410 (unless js2-is-in-destructuring
9411 (js2-pop-scope))
9412 pn))
9413
9414 (defun js2-parse-legacy-array-comp (expr pos)
9415 "Parse a legacy array comprehension (JavaScript 1.7).
9416 EXPR is the first expression after the opening left-bracket.
9417 POS is the beginning of the LB token preceding EXPR.
9418 We should have just parsed the 'for' keyword before calling this function."
9419 (let ((current-scope js2-current-scope)
9420 loops first filter result)
9421 (unwind-protect
9422 (progn
9423 (while (js2-match-token js2-FOR)
9424 (let ((loop (make-js2-comp-loop-node)))
9425 (js2-push-scope loop)
9426 (push loop loops)
9427 (js2-parse-comp-loop loop)))
9428 ;; First loop takes expr scope's parent.
9429 (setf (js2-scope-parent-scope (setq first (car (last loops))))
9430 (js2-scope-parent-scope current-scope))
9431 ;; Set expr scope's parent to the last loop.
9432 (setf (js2-scope-parent-scope current-scope) (car loops))
9433 (if (/= (js2-get-token) js2-IF)
9434 (js2-unget-token)
9435 (setq filter (js2-parse-condition))))
9436 (dotimes (_ (1- (length loops)))
9437 (js2-pop-scope)))
9438 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9439 (setq result (make-js2-comp-node :pos pos
9440 :len (- js2-ts-cursor pos)
9441 :result expr
9442 :loops (nreverse loops)
9443 :filters (and filter (list (car filter)))
9444 :form 'LEGACY_ARRAY))
9445 (apply #'js2-node-add-children result expr (car filter)
9446 (js2-comp-node-loops result))
9447 result))
9448
9449 (defun js2-parse-array-comp (pos)
9450 "Parse an ES6 array comprehension.
9451 POS is the beginning of the LB token.
9452 We should have just parsed the 'for' keyword before calling this function."
9453 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
9454 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9455 pn))
9456
9457 (defun js2-parse-generator-comp (pos)
9458 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
9459 (js2-current-script-or-fn
9460 (make-js2-function-node :generator-type 'COMPREHENSION))
9461 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
9462 (js2-must-match js2-RP "msg.no.paren" pos)
9463 pn))
9464
9465 (defun js2-parse-comprehension (pos form)
9466 (let (loops filters expr result)
9467 (unwind-protect
9468 (progn
9469 (js2-unget-token)
9470 (while (js2-match-token js2-FOR)
9471 (let ((loop (make-js2-comp-loop-node)))
9472 (js2-push-scope loop)
9473 (push loop loops)
9474 (js2-parse-comp-loop loop)))
9475 (while (js2-match-token js2-IF)
9476 (push (car (js2-parse-condition)) filters))
9477 (setq expr (js2-parse-assign-expr)))
9478 (dolist (_ loops)
9479 (js2-pop-scope)))
9480 (setq result (make-js2-comp-node :pos pos
9481 :len (- js2-ts-cursor pos)
9482 :result expr
9483 :loops (nreverse loops)
9484 :filters (nreverse filters)
9485 :form form))
9486 (apply #'js2-node-add-children result (js2-comp-node-loops result))
9487 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
9488 result))
9489
9490 (defun js2-parse-comp-loop (pn &optional only-of-p)
9491 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9492 The current token should be the initial FOR.
9493 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
9494 (let ((pos (js2-comp-loop-node-pos pn))
9495 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9496 (when (and (not only-of-p) (js2-match-token js2-NAME))
9497 (if (string= (js2-current-token-string) "each")
9498 (progn
9499 (setq foreach-p t
9500 each-pos (- (js2-current-token-beg) pos)) ; relative
9501 (js2-record-face 'font-lock-keyword-face))
9502 (js2-report-error "msg.no.paren.for")))
9503 (if (js2-must-match js2-LP "msg.no.paren.for")
9504 (setq lp (- (js2-current-token-beg) pos)))
9505 (setq tt (js2-peek-token))
9506 (cond
9507 ((or (= tt js2-LB)
9508 (= tt js2-LC))
9509 (js2-get-token)
9510 (setq iter (js2-parse-destruct-primary-expr))
9511 (js2-define-destruct-symbols iter js2-LET
9512 'font-lock-variable-name-face t))
9513 ((js2-match-token js2-NAME)
9514 (setq iter (js2-create-name-node)))
9515 (t
9516 (js2-report-error "msg.bad.var")))
9517 ;; Define as a let since we want the scope of the variable to
9518 ;; be restricted to the array comprehension
9519 (if (js2-name-node-p iter)
9520 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9521 (if (or (and (not only-of-p) (js2-match-token js2-IN))
9522 (and (>= js2-language-version 200)
9523 (js2-match-contextual-kwd "of")
9524 (setq forof-p t)))
9525 (setq in-pos (- (js2-current-token-beg) pos))
9526 (js2-report-error "msg.in.after.for.name"))
9527 (setq obj (js2-parse-expr))
9528 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9529 (setq rp (- (js2-current-token-beg) pos)))
9530 (setf (js2-node-pos pn) pos
9531 (js2-node-len pn) (- js2-ts-cursor pos)
9532 (js2-comp-loop-node-iterator pn) iter
9533 (js2-comp-loop-node-object pn) obj
9534 (js2-comp-loop-node-in-pos pn) in-pos
9535 (js2-comp-loop-node-each-pos pn) each-pos
9536 (js2-comp-loop-node-foreach-p pn) foreach-p
9537 (js2-comp-loop-node-forof-p pn) forof-p
9538 (js2-comp-loop-node-lp pn) lp
9539 (js2-comp-loop-node-rp pn) rp)
9540 (js2-node-add-children pn iter obj)
9541 pn))
9542
9543 (defun js2-parse-object-literal ()
9544 (let ((pos (js2-current-token-beg))
9545 tt elems result after-comma
9546 (continue t))
9547 (while continue
9548 (setq tt (js2-get-token))
9549 (cond
9550 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9551 ;; {get foo() {...}}, {set foo(x) {...}}, or {foo(x) {...}}
9552 ;; TODO(sdh): support *foo() {...}
9553 ((or (js2-valid-prop-name-token tt)
9554 (= tt js2-STRING))
9555 (setq after-comma nil
9556 result (js2-parse-named-prop tt))
9557 (if (and (null result)
9558 (not js2-recover-from-parse-errors))
9559 (setq continue nil)
9560 (push result elems)))
9561 ;; {[Symbol.iterator]: ...}
9562 ((and (= tt js2-LB)
9563 (>= js2-language-version 200))
9564 (let ((expr (js2-parse-expr)))
9565 (js2-must-match js2-RB "msg.missing.computed.rb")
9566 (setq after-comma nil)
9567 (push (js2-parse-plain-property expr) elems)))
9568 ;; {12: x} or {10.7: x}
9569 ((= tt js2-NUMBER)
9570 (setq after-comma nil)
9571 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9572 ;; trailing comma
9573 ((= tt js2-RC)
9574 (js2-unget-token)
9575 (setq continue nil)
9576 (if after-comma
9577 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9578 pos elems after-comma)))
9579 (t
9580 (js2-report-error "msg.bad.prop")
9581 (unless js2-recover-from-parse-errors
9582 (setq continue nil)))) ; end switch
9583 (if (js2-match-token js2-COMMA)
9584 (setq after-comma (js2-current-token-end))
9585 (setq continue nil))) ; end loop
9586 (js2-must-match js2-RC "msg.no.brace.prop")
9587 (setq result (make-js2-object-node :pos pos
9588 :len (- js2-ts-cursor pos)
9589 :elems (nreverse elems)))
9590 (apply #'js2-node-add-children result (js2-object-node-elems result))
9591 result))
9592
9593 (defun js2-parse-named-prop (tt)
9594 "Parse a name, string, or getter/setter object property.
9595 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9596 (let ((string-prop (and (= tt js2-STRING)
9597 (make-js2-string-node)))
9598 expr
9599 (ppos (js2-current-token-beg))
9600 (pend (js2-current-token-end))
9601 (name (js2-create-name-node))
9602 (prop (js2-current-token-string)))
9603 (cond
9604 ;; getter/setter prop
9605 ((and (= tt js2-NAME)
9606 (= (js2-peek-token) js2-NAME)
9607 (or (string= prop "get")
9608 (string= prop "set")))
9609 (js2-get-token)
9610 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9611 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9612 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9613 (js2-parse-getter-setter-prop ppos name prop))
9614 ;; method definition: {f() {...}}
9615 ((and (= (js2-peek-token) js2-LP)
9616 (>= js2-language-version 200))
9617 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; name
9618 (js2-parse-getter-setter-prop ppos name ""))
9619 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9620 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9621 ;; when patterns are used in variable declarations, function parameters,
9622 ;; catch-clause, and iterators.
9623 ;; We have to set `js2-is-in-destructuring' to t when the current
9624 ;; expressions are on the left side of any assignment, but it's difficult
9625 ;; because it requires looking ahead of expression.
9626 ((and js2-is-in-destructuring
9627 (= tt js2-NAME)
9628 (let ((ctk (js2-peek-token)))
9629 (or (= ctk js2-COMMA)
9630 (= ctk js2-RC)
9631 (js2-valid-prop-name-token ctk))))
9632 name)
9633 ;; regular prop
9634 (t
9635 (prog1
9636 (setq expr (js2-parse-plain-property (or string-prop name)))
9637 (js2-set-face ppos pend
9638 (if (js2-function-node-p
9639 (js2-object-prop-node-right expr))
9640 'font-lock-function-name-face
9641 'font-lock-variable-name-face)
9642 'record))))))
9643
9644 (defun js2-parse-plain-property (prop)
9645 "Parse a non-getter/setter property in an object literal.
9646 PROP is the node representing the property: a number, name or string."
9647 (let* ((tt (js2-get-token))
9648 (pos (js2-node-pos prop))
9649 colon expr result)
9650 (cond
9651 ;; Abbreviated property, as in {foo, bar}
9652 ((and (>= js2-language-version 200)
9653 (or (= tt js2-COMMA)
9654 (= tt js2-RC)))
9655 (js2-unget-token)
9656 (setq result (make-js2-object-prop-node
9657 :pos pos
9658 :left prop
9659 :right prop
9660 :op-pos (js2-current-token-len)))
9661 (js2-node-add-children result prop)
9662 (js2-node-set-prop result 'SHORTHAND t)
9663 result)
9664 ;; Normal property
9665 (t
9666 (if (= tt js2-COLON)
9667 (setq colon (- (js2-current-token-beg) pos)
9668 expr (js2-parse-assign-expr))
9669 (js2-report-error "msg.no.colon.prop")
9670 (setq expr (make-js2-error-node)))
9671 (setq result (make-js2-object-prop-node
9672 :pos pos
9673 ;; don't include last consumed token in length
9674 :len (- (+ (js2-node-pos expr)
9675 (js2-node-len expr))
9676 pos)
9677 :left prop
9678 :right expr
9679 :op-pos colon))
9680 (js2-node-add-children result prop expr)
9681 result))))
9682
9683 (defun js2-parse-getter-setter-prop (pos prop type-string)
9684 "Parse getter or setter property in an object literal.
9685 JavaScript syntax is:
9686
9687 { get foo() {...}, set foo(x) {...} }
9688
9689 and expression closure style is also supported
9690
9691 { get foo() x, set foo(x) _x = x }
9692
9693 POS is the start position of the `get' or `set' keyword.
9694 PROP is the `js2-name-node' representing the property name.
9695 GET-P is non-nil if the keyword was `get'."
9696 (let ((type (cond
9697 ((string= "get" type-string) js2-GET)
9698 ((string= "set" type-string) js2-SET)
9699 (t js2-FUNCTION)))
9700 result end
9701 (fn (js2-parse-function-expr)))
9702 ;; it has to be an anonymous function, as we already parsed the name
9703 (if (/= (js2-node-type fn) js2-FUNCTION)
9704 (js2-report-error "msg.bad.prop")
9705 (if (plusp (length (js2-function-name fn)))
9706 (js2-report-error "msg.bad.prop")))
9707 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9708 (setq end (js2-node-end fn)
9709 result (make-js2-getter-setter-node :type type
9710 :pos pos
9711 :len (- end pos)
9712 :left prop
9713 :right fn))
9714 (js2-node-add-children result prop fn)
9715 result))
9716
9717 (defun js2-create-name-node (&optional check-activation-p token string)
9718 "Create a name node using the current token and, optionally, STRING.
9719 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
9720 (let* ((beg (js2-current-token-beg))
9721 (tt (js2-current-token-type))
9722 (s (or string
9723 (if (= js2-NAME tt)
9724 (js2-current-token-string)
9725 (js2-tt-name tt))))
9726 name)
9727 (setq name (make-js2-name-node :pos beg
9728 :name s
9729 :len (length s)))
9730 (if check-activation-p
9731 (js2-check-activation-name s (or token js2-NAME)))
9732 name))
9733
9734 ;;; Indentation support
9735
9736 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9737 ;; Karl cleverly deduces that the desired indentation level is often a
9738 ;; function of paren/bracket/brace nesting depth, which can be determined
9739 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9740 ;; then does some equally clever checks to see if we're in the context of a
9741 ;; substatement of a possibly braceless statement keyword such as if, while,
9742 ;; or finally. This approach yields pretty good results.
9743
9744 ;; The indenter is often "wrong", however, and needs to be overridden.
9745 ;; The right long-term solution is probably to emulate (or integrate
9746 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9747 ;; parse tree from `js2-parse' is present, which is not true at the
9748 ;; moment the user is typing, computing indentation is still thousands
9749 ;; of lines of code to handle every possible syntactic edge case.
9750
9751 ;; In the meantime, the compromise solution is that we offer a "bounce
9752 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9753 ;; current line indent among various likely guess points. This approach
9754 ;; is far from perfect, but should at least make it slightly easier to
9755 ;; move the line towards its desired indentation when manually
9756 ;; overriding Karl's heuristic nesting guesser.
9757
9758 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9759 ;; extensions such as `let' and Array comprehensions. Major kudos to
9760 ;; Karl for coming up with the initial approach, which packs a lot of
9761 ;; punch for so little code.
9762
9763 (defconst js2-possibly-braceless-keywords-re
9764 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9765 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9766 "try" "while" "with" "let")))
9767 "Regular expression matching keywords that are optionally
9768 followed by an opening brace.")
9769
9770 (defconst js2-indent-operator-re
9771 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
9772 (regexp-opt '("in" "instanceof") 'words))
9773 "Regular expression matching operators that affect indentation
9774 of continued expressions.")
9775
9776 (defconst js2-declaration-keyword-re
9777 (regexp-opt '("var" "let" "const") 'words)
9778 "Regular expression matching variable declaration keywords.")
9779
9780 (defun js2-re-search-forward-inner (regexp &optional bound count)
9781 "Auxiliary function for `js2-re-search-forward'."
9782 (let (parse saved-point)
9783 (while (> count 0)
9784 (re-search-forward regexp bound)
9785 (setq parse (if saved-point
9786 (parse-partial-sexp saved-point (point))
9787 (syntax-ppss (point))))
9788 (cond ((nth 3 parse)
9789 (re-search-forward
9790 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
9791 (save-excursion (end-of-line) (point)) t))
9792 ((nth 7 parse)
9793 (forward-line))
9794 ((or (nth 4 parse)
9795 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9796 (re-search-forward "\\*/"))
9797 (t
9798 (setq count (1- count))))
9799 (setq saved-point (point))))
9800 (point))
9801
9802 (defun js2-re-search-forward (regexp &optional bound noerror count)
9803 "Search forward but ignore strings and comments.
9804 Invokes `re-search-forward' but treats the buffer as if strings
9805 and comments have been removed."
9806 (let ((saved-point (point)))
9807 (condition-case err
9808 (cond ((null count)
9809 (js2-re-search-forward-inner regexp bound 1))
9810 ((< count 0)
9811 (js2-re-search-backward-inner regexp bound (- count)))
9812 ((> count 0)
9813 (js2-re-search-forward-inner regexp bound count)))
9814 (search-failed
9815 (goto-char saved-point)
9816 (unless noerror
9817 (error (error-message-string err)))))))
9818
9819 (defun js2-re-search-backward-inner (regexp &optional bound count)
9820 "Auxiliary function for `js2-re-search-backward'."
9821 (let (parse)
9822 (while (> count 0)
9823 (re-search-backward regexp bound)
9824 (setq parse (syntax-ppss (point)))
9825 (cond ((nth 3 parse)
9826 (re-search-backward
9827 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9828 (line-beginning-position) t))
9829 ((nth 7 parse)
9830 (goto-char (nth 8 parse)))
9831 ((or (nth 4 parse)
9832 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9833 (re-search-backward "/\\*"))
9834 (t
9835 (setq count (1- count))))))
9836 (point))
9837
9838 (defun js2-re-search-backward (regexp &optional bound noerror count)
9839 "Search backward but ignore strings and comments.
9840 Invokes `re-search-backward' but treats the buffer as if strings
9841 and comments have been removed."
9842 (let ((saved-point (point)))
9843 (condition-case err
9844 (cond ((null count)
9845 (js2-re-search-backward-inner regexp bound 1))
9846 ((< count 0)
9847 (js2-re-search-forward-inner regexp bound (- count)))
9848 ((> count 0)
9849 (js2-re-search-backward-inner regexp bound count)))
9850 (search-failed
9851 (goto-char saved-point)
9852 (unless noerror
9853 (error (error-message-string err)))))))
9854
9855 (defun js2-looking-at-operator-p ()
9856 "Return non-nil if text after point is a non-comma operator."
9857 (and (looking-at js2-indent-operator-re)
9858 (or (not (looking-at ":"))
9859 (save-excursion
9860 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9861 (looking-at "?"))))))
9862
9863 (defun js2-continued-expression-p ()
9864 "Return non-nil if the current line continues an expression."
9865 (save-excursion
9866 (back-to-indentation)
9867 (or (js2-looking-at-operator-p)
9868 (when (catch 'found
9869 (while (and (re-search-backward "\n" nil t)
9870 (let ((state (syntax-ppss)))
9871 (when (nth 4 state)
9872 (goto-char (nth 8 state))) ;; skip comments
9873 (skip-chars-backward " \t")
9874 (if (bolp)
9875 t
9876 (throw 'found t))))))
9877 (backward-char)
9878 (when (js2-looking-at-operator-p)
9879 (backward-char)
9880 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
9881
9882 (defun js2-end-of-do-while-loop-p ()
9883 "Return non-nil if word after point is `while' of a do-while
9884 statement, else returns nil. A braceless do-while statement
9885 spanning several lines requires that the start of the loop is
9886 indented to the same column as the current line."
9887 (interactive)
9888 (save-excursion
9889 (when (looking-at "\\s-*\\<while\\>")
9890 (if (save-excursion
9891 (skip-chars-backward "[ \t\n]*}")
9892 (looking-at "[ \t\n]*}"))
9893 (save-excursion
9894 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9895 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9896 (or (looking-at "\\<do\\>")
9897 (let ((saved-indent (current-indentation)))
9898 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9899 (/= (current-indentation) saved-indent)))
9900 (and (looking-at "[ \t]*\\<do\\>")
9901 (not (js2-re-search-forward
9902 "\\<while\\>" (point-at-eol) t))
9903 (= (current-indentation) saved-indent))))))))
9904
9905 (defun js2-multiline-decl-indentation ()
9906 "Return the declaration indentation column if the current line belongs
9907 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9908 (let (forward-sexp-function ; use Lisp version
9909 at-opening-bracket)
9910 (save-excursion
9911 (back-to-indentation)
9912 (when (not (looking-at js2-declaration-keyword-re))
9913 (when (looking-at js2-indent-operator-re)
9914 (goto-char (match-end 0))) ; continued expressions are ok
9915 (while (and (not at-opening-bracket)
9916 (not (bobp))
9917 (let ((pos (point)))
9918 (save-excursion
9919 (js2-backward-sws)
9920 (or (eq (char-before) ?,)
9921 (and (not (eq (char-before) ?\;))
9922 (prog2 (skip-syntax-backward ".")
9923 (looking-at js2-indent-operator-re)
9924 (js2-backward-sws))
9925 (not (eq (char-before) ?\;)))
9926 (js2-same-line pos)))))
9927 (condition-case _
9928 (backward-sexp)
9929 (scan-error (setq at-opening-bracket t))))
9930 (when (looking-at js2-declaration-keyword-re)
9931 (goto-char (match-end 0))
9932 (1+ (current-column)))))))
9933
9934 (defun js2-ctrl-statement-indentation ()
9935 "Return the proper indentation of current line if it is a control statement.
9936 Returns an indentation if this line starts the body of a control
9937 statement without braces, else returns nil."
9938 (let (forward-sexp-function)
9939 (save-excursion
9940 (back-to-indentation)
9941 (when (and (not (js2-same-line (point-min)))
9942 (not (looking-at "{"))
9943 (js2-re-search-backward "[[:graph:]]" nil t)
9944 (not (looking-at "[{([]"))
9945 (progn
9946 (forward-char)
9947 (when (= (char-before) ?\))
9948 ;; scan-sexps sometimes throws an error
9949 (ignore-errors (backward-sexp))
9950 (skip-chars-backward " \t" (point-at-bol)))
9951 (let ((pt (point)))
9952 (back-to-indentation)
9953 (when (looking-at "}[ \t]*")
9954 (goto-char (match-end 0)))
9955 (and (looking-at js2-possibly-braceless-keywords-re)
9956 (= (match-end 0) pt)
9957 (not (js2-end-of-do-while-loop-p))))))
9958 (+ (current-indentation) js2-basic-offset)))))
9959
9960 (defun js2-indent-in-array-comp (parse-status)
9961 "Return non-nil if we think we're in an array comprehension.
9962 In particular, return the buffer position of the first `for' kwd."
9963 (let ((bracket (nth 1 parse-status))
9964 (end (point)))
9965 (when bracket
9966 (save-excursion
9967 (goto-char bracket)
9968 (when (looking-at "\\[")
9969 (forward-char 1)
9970 (js2-forward-sws)
9971 (if (looking-at "[[{]")
9972 (let (forward-sexp-function) ; use Lisp version
9973 (forward-sexp) ; skip destructuring form
9974 (js2-forward-sws)
9975 (if (and (/= (char-after) ?,) ; regular array
9976 (looking-at "for"))
9977 (match-beginning 0)))
9978 ;; to skip arbitrary expressions we need the parser,
9979 ;; so we'll just guess at it.
9980 (if (and (> end (point)) ; not empty literal
9981 (re-search-forward "[^,]]* \\(for\\) " end t)
9982 ;; not inside comment or string literal
9983 (let ((state (parse-partial-sexp bracket (point))))
9984 (not (or (nth 3 state) (nth 4 state)))))
9985 (match-beginning 1))))))))
9986
9987 (defun js2-array-comp-indentation (parse-status for-kwd)
9988 (if (js2-same-line for-kwd)
9989 ;; first continuation line
9990 (save-excursion
9991 (goto-char (nth 1 parse-status))
9992 (forward-char 1)
9993 (skip-chars-forward " \t")
9994 (current-column))
9995 (save-excursion
9996 (goto-char for-kwd)
9997 (current-column))))
9998
9999 (defun js2-proper-indentation (parse-status)
10000 "Return the proper indentation for the current line."
10001 (save-excursion
10002 (back-to-indentation)
10003 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10004 (at-closing-bracket (looking-at "[]})]"))
10005 (same-indent-p (or at-closing-bracket
10006 (looking-at "\\<case\\>[^:]")
10007 (and (looking-at "\\<default:")
10008 (save-excursion
10009 (js2-backward-sws)
10010 (not (memq (char-before) '(?, ?{)))))))
10011 (continued-expr-p (js2-continued-expression-p))
10012 (declaration-indent (and js2-pretty-multiline-declarations
10013 (js2-multiline-decl-indentation)))
10014 (bracket (nth 1 parse-status))
10015 beg indent)
10016 (cond
10017 ;; indent array comprehension continuation lines specially
10018 ((and bracket
10019 (>= js2-language-version 170)
10020 (not (js2-same-line bracket))
10021 (setq beg (js2-indent-in-array-comp parse-status))
10022 (>= (point) (save-excursion
10023 (goto-char beg)
10024 (point-at-bol)))) ; at or after first loop?
10025 (js2-array-comp-indentation parse-status beg))
10026
10027 (ctrl-stmt-indent)
10028
10029 ((and declaration-indent continued-expr-p)
10030 (+ declaration-indent js2-basic-offset))
10031
10032 (declaration-indent)
10033
10034 (bracket
10035 (goto-char bracket)
10036 (cond
10037 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10038 (when (save-excursion (skip-chars-backward " \t)")
10039 (looking-at ")"))
10040 (backward-list))
10041 (back-to-indentation)
10042 (and (eq js2-pretty-multiline-declarations 'all)
10043 (looking-at js2-declaration-keyword-re)
10044 (goto-char (1+ (match-end 0))))
10045 (setq indent
10046 (cond (same-indent-p
10047 (current-column))
10048 (continued-expr-p
10049 (+ (current-column) (* 2 js2-basic-offset)))
10050 (t
10051 (+ (current-column) js2-basic-offset))))
10052 (if (and js2-indent-switch-body
10053 (not at-closing-bracket)
10054 (looking-at "\\_<switch\\_>"))
10055 (+ indent js2-basic-offset)
10056 indent))
10057 (t
10058 (unless same-indent-p
10059 (forward-char)
10060 (skip-chars-forward " \t"))
10061 (current-column))))
10062
10063 (continued-expr-p js2-basic-offset)
10064
10065 (t 0)))))
10066
10067 (defun js2-lineup-comment (parse-status)
10068 "Indent a multi-line block comment continuation line."
10069 (let* ((beg (nth 8 parse-status))
10070 (first-line (js2-same-line beg))
10071 (offset (save-excursion
10072 (goto-char beg)
10073 (if (looking-at "/\\*")
10074 (+ 1 (current-column))
10075 0))))
10076 (unless first-line
10077 (indent-line-to offset))))
10078
10079 (defun js2-backward-sws ()
10080 "Move backward through whitespace and comments."
10081 (interactive)
10082 (while (forward-comment -1)))
10083
10084 (defun js2-forward-sws ()
10085 "Move forward through whitespace and comments."
10086 (interactive)
10087 (while (forward-comment 1)))
10088
10089 (defun js2-current-indent (&optional pos)
10090 "Return column of indentation on current line.
10091 If POS is non-nil, go to that point and return indentation for that line."
10092 (save-excursion
10093 (if pos
10094 (goto-char pos))
10095 (back-to-indentation)
10096 (current-column)))
10097
10098 (defun js2-arglist-close ()
10099 "Return non-nil if we're on a line beginning with a close-paren/brace."
10100 (save-excursion
10101 (goto-char (point-at-bol))
10102 (js2-forward-sws)
10103 (looking-at "[])}]")))
10104
10105 (defun js2-indent-looks-like-label-p ()
10106 (goto-char (point-at-bol))
10107 (js2-forward-sws)
10108 (looking-at (concat js2-mode-identifier-re ":")))
10109
10110 (defun js2-indent-in-objlit-p (parse-status)
10111 "Return non-nil if this looks like an object-literal entry."
10112 (let ((start (nth 1 parse-status)))
10113 (and
10114 start
10115 (save-excursion
10116 (and (zerop (forward-line -1))
10117 (not (< (point) start)) ; crossed a {} boundary
10118 (js2-indent-looks-like-label-p)))
10119 (save-excursion
10120 (js2-indent-looks-like-label-p)))))
10121
10122 ;; If prev line looks like foobar({ then we're passing an object
10123 ;; literal to a function call, and people pretty much always want to
10124 ;; de-dent back to the previous line, so move the 'basic-offset'
10125 ;; position to the front.
10126 (defun js2-indent-objlit-arg-p (parse-status)
10127 (save-excursion
10128 (back-to-indentation)
10129 (js2-backward-sws)
10130 (and (eq (1- (point)) (nth 1 parse-status))
10131 (eq (char-before) ?{)
10132 (progn
10133 (forward-char -1)
10134 (skip-chars-backward " \t")
10135 (eq (char-before) ?\()))))
10136
10137 (defun js2-indent-case-block-p ()
10138 (save-excursion
10139 (back-to-indentation)
10140 (js2-backward-sws)
10141 (goto-char (point-at-bol))
10142 (skip-chars-forward " \t")
10143 (looking-at "case\\s-.+:")))
10144
10145 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10146 "Cycle among alternate computed indentation positions.
10147 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10148 of the buffer to the current point. NORMAL-COL is the indentation
10149 column computed by the heuristic guesser based on current paren,
10150 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10151 in reverse."
10152 (let ((cur-indent (js2-current-indent))
10153 (old-buffer-undo-list buffer-undo-list)
10154 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10155 (current-line (save-excursion
10156 (forward-line 0) ; move to bol
10157 (1+ (count-lines (point-min) (point)))))
10158 positions pos main-pos anchor arglist-cont same-indent
10159 basic-offset computed-pos)
10160 ;; temporarily don't record undo info, if user requested this
10161 (when js2-mode-indent-inhibit-undo
10162 (setq buffer-undo-list t))
10163 (unwind-protect
10164 (progn
10165 ;; First likely point: indent from beginning of previous code line
10166 (push (setq basic-offset
10167 (+ (save-excursion
10168 (back-to-indentation)
10169 (js2-backward-sws)
10170 (back-to-indentation)
10171 (current-column))
10172 js2-basic-offset))
10173 positions)
10174
10175 ;; (First + epsilon) likely point: indent 2x from beginning of
10176 ;; previous code line. Google does it this way.
10177 (push (setq basic-offset
10178 (+ (save-excursion
10179 (back-to-indentation)
10180 (js2-backward-sws)
10181 (back-to-indentation)
10182 (current-column))
10183 (* 2 js2-basic-offset)))
10184 positions)
10185
10186 ;; Second likely point: indent from assign-expr RHS. This
10187 ;; is just a crude guess based on finding " = " on the previous
10188 ;; line containing actual code.
10189 (setq pos (save-excursion
10190 (forward-line -1)
10191 (goto-char (point-at-bol))
10192 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10193 (point-at-eol) t)
10194 (goto-char (match-end 1))
10195 (skip-chars-forward " \t\r\n")
10196 (current-column))))
10197 (when pos
10198 (incf pos js2-basic-offset)
10199 (push pos positions))
10200
10201 ;; Third likely point: same indent as previous line of code.
10202 ;; Make it the first likely point if we're not on an
10203 ;; arglist-close line and previous line ends in a comma, or
10204 ;; both this line and prev line look like object-literal
10205 ;; elements.
10206 (setq pos (save-excursion
10207 (goto-char (point-at-bol))
10208 (js2-backward-sws)
10209 (back-to-indentation)
10210 (prog1
10211 (current-column)
10212 ;; while we're here, look for trailing comma
10213 (if (save-excursion
10214 (goto-char (point-at-eol))
10215 (js2-backward-sws)
10216 (eq (char-before) ?,))
10217 (setq arglist-cont (1- (point)))))))
10218 (when pos
10219 (if (and (or arglist-cont
10220 (js2-indent-in-objlit-p parse-status))
10221 (not (js2-arglist-close)))
10222 (setq same-indent pos))
10223 (push pos positions))
10224
10225 ;; Fourth likely point: first preceding code with less indentation.
10226 ;; than the immediately preceding code line.
10227 (setq pos (save-excursion
10228 (back-to-indentation)
10229 (js2-backward-sws)
10230 (back-to-indentation)
10231 (setq anchor (current-column))
10232 (while (and (zerop (forward-line -1))
10233 (>= (progn
10234 (back-to-indentation)
10235 (current-column))
10236 anchor)))
10237 (setq pos (current-column))))
10238 (push pos positions)
10239
10240 ;; nesting-heuristic position, main by default
10241 (push (setq main-pos normal-col) positions)
10242
10243 ;; delete duplicates and sort positions list
10244 (setq positions (sort (delete-dups positions) '<))
10245
10246 ;; comma-list continuation lines: prev line indent takes precedence
10247 (if same-indent
10248 (setq main-pos same-indent))
10249
10250 ;; common special cases where we want to indent in from previous line
10251 (if (or (js2-indent-case-block-p)
10252 (js2-indent-objlit-arg-p parse-status))
10253 (setq main-pos basic-offset))
10254
10255 ;; if bouncing backwards, reverse positions list
10256 (if backwards
10257 (setq positions (reverse positions)))
10258
10259 ;; record whether we're already sitting on one of the alternatives
10260 (setq pos (member cur-indent positions))
10261
10262 (cond
10263 ;; case 0: we're one one of the alternatives and this is the
10264 ;; first time they've pressed TAB on this line (best-guess).
10265 ((and js2-mode-indent-ignore-first-tab
10266 pos
10267 ;; first time pressing TAB on this line?
10268 (not (eq js2-mode-last-indented-line current-line)))
10269 ;; do nothing
10270 (setq computed-pos nil))
10271 ;; case 1: only one computed position => use it
10272 ((null (cdr positions))
10273 (setq computed-pos 0))
10274 ;; case 2: not on any of the computed spots => use main spot
10275 ((not pos)
10276 (setq computed-pos (js2-position main-pos positions)))
10277 ;; case 3: on last position: cycle to first position
10278 ((null (cdr pos))
10279 (setq computed-pos 0))
10280 ;; case 4: on intermediate position: cycle to next position
10281 (t
10282 (setq computed-pos (js2-position (second pos) positions))))
10283
10284 ;; see if any hooks want to indent; otherwise we do it
10285 (loop with result = nil
10286 for hook in js2-indent-hook
10287 while (null result)
10288 do
10289 (setq result (funcall hook positions computed-pos))
10290 finally do
10291 (unless (or result (null computed-pos))
10292 (indent-line-to (nth computed-pos positions)))))
10293
10294 ;; finally
10295 (if js2-mode-indent-inhibit-undo
10296 (setq buffer-undo-list old-buffer-undo-list))
10297 ;; see commentary for `js2-mode-last-indented-line'
10298 (setq js2-mode-last-indented-line current-line))))
10299
10300 (defun js2-indent-bounce-backwards ()
10301 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10302 cycles between the computed indentation positions in reverse order."
10303 (interactive)
10304 (js2-indent-line t))
10305
10306 (defun js2-1-line-comment-continuation-p ()
10307 "Return t if we're in a 1-line comment continuation.
10308 If so, we don't ever want to use bounce-indent."
10309 (save-excursion
10310 (and (progn
10311 (forward-line 0)
10312 (looking-at "\\s-*//"))
10313 (progn
10314 (forward-line -1)
10315 (forward-line 0)
10316 (when (looking-at "\\s-*$")
10317 (js2-backward-sws)
10318 (forward-line 0))
10319 (looking-at "\\s-*//")))))
10320
10321 (defun js2-indent-line (&optional bounce-backwards)
10322 "Indent the current line as JavaScript source text."
10323 (interactive)
10324 (let (parse-status offset indent-col
10325 ;; Don't whine about errors/warnings when we're indenting.
10326 ;; This has to be set before calling parse-partial-sexp below.
10327 (inhibit-point-motion-hooks t))
10328 (setq parse-status (save-excursion
10329 (syntax-ppss (point-at-bol)))
10330 offset (- (point) (save-excursion
10331 (back-to-indentation)
10332 (point))))
10333 (js2-with-underscore-as-word-syntax
10334 (if (nth 4 parse-status)
10335 (js2-lineup-comment parse-status)
10336 (setq indent-col (js2-proper-indentation parse-status))
10337 ;; See comments below about `js2-mode-last-indented-line'.
10338 (cond
10339 ;; bounce-indenting is disabled during electric-key indent.
10340 ;; It doesn't work well on first line of buffer.
10341 ((and js2-bounce-indent-p
10342 (not (js2-same-line (point-min)))
10343 (not (js2-1-line-comment-continuation-p)))
10344 (js2-bounce-indent indent-col parse-status bounce-backwards))
10345 ;; just indent to the guesser's likely spot
10346 (t (indent-line-to indent-col))))
10347 (when (plusp offset)
10348 (forward-char offset)))))
10349
10350 (defun js2-indent-region (start end)
10351 "Indent the region, but don't use bounce indenting."
10352 (let ((js2-bounce-indent-p nil)
10353 (indent-region-function nil)
10354 (after-change-functions (remq 'js2-mode-edit
10355 after-change-functions)))
10356 (indent-region start end nil) ; nil for byte-compiler
10357 (js2-mode-edit start end (- end start))))
10358
10359 (defvar js2-minor-mode-map
10360 (let ((map (make-sparse-keymap)))
10361 (define-key map (kbd "C-c C-`") #'js2-next-error)
10362 (define-key map [mouse-1] #'js2-mode-show-node)
10363 map)
10364 "Keymap used when `js2-minor-mode' is active.")
10365
10366 ;;;###autoload
10367 (define-minor-mode js2-minor-mode
10368 "Minor mode for running js2 as a background linter.
10369 This allows you to use a different major mode for JavaScript editing,
10370 such as `js-mode', while retaining the asynchronous error/warning
10371 highlighting features of `js2-mode'."
10372 :group 'js2-mode
10373 :lighter " js-lint"
10374 (if js2-minor-mode
10375 (js2-minor-mode-enter)
10376 (js2-minor-mode-exit)))
10377
10378 (defun js2-minor-mode-enter ()
10379 "Initialization for `js2-minor-mode'."
10380 (set (make-local-variable 'max-lisp-eval-depth)
10381 (max max-lisp-eval-depth 3000))
10382 (setq next-error-function #'js2-next-error)
10383 (js2-set-default-externs)
10384 ;; Experiment: make reparse-delay longer for longer files.
10385 (if (plusp js2-dynamic-idle-timer-adjust)
10386 (setq js2-idle-timer-delay
10387 (* js2-idle-timer-delay
10388 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10389 (setq js2-mode-buffer-dirty-p t
10390 js2-mode-parsing nil)
10391 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10392 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10393 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10394 (when js2-include-jslint-globals
10395 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10396 (run-hooks 'js2-init-hook)
10397 (js2-reparse))
10398
10399 (defun js2-minor-mode-exit ()
10400 "Turn off `js2-minor-mode'."
10401 (setq next-error-function nil)
10402 (remove-hook 'after-change-functions #'js2-mode-edit t)
10403 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10404 (when js2-mode-node-overlay
10405 (delete-overlay js2-mode-node-overlay)
10406 (setq js2-mode-node-overlay nil))
10407 (js2-remove-overlays)
10408 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
10409 (setq js2-mode-ast nil))
10410
10411 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10412 (make-variable-buffer-local 'js2-source-buffer)
10413
10414 (defun* js2-display-error-list ()
10415 "Display a navigable buffer listing parse errors/warnings."
10416 (interactive)
10417 (unless (js2-have-errors-p)
10418 (message "No errors")
10419 (return-from js2-display-error-list))
10420 (labels ((annotate-list
10421 (lst type)
10422 "Add diagnostic TYPE and line number to errs list"
10423 (mapcar (lambda (err)
10424 (list err type (line-number-at-pos (nth 1 err))))
10425 lst)))
10426 (let* ((srcbuf (current-buffer))
10427 (errbuf (get-buffer-create "*js-lint*"))
10428 (errors (annotate-list
10429 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10430 'js2-error)) ; must be a valid face name
10431 (warnings (annotate-list
10432 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10433 'js2-warning)) ; must be a valid face name
10434 (all-errs (sort (append errors warnings)
10435 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10436 (with-current-buffer errbuf
10437 (let ((inhibit-read-only t))
10438 (erase-buffer)
10439 (dolist (err all-errs)
10440 (destructuring-bind ((msg-key beg _end &rest) type line) err
10441 (insert-text-button
10442 (format "line %d: %s" line (js2-get-msg msg-key))
10443 'face type
10444 'follow-link "\C-m"
10445 'action 'js2-error-buffer-jump
10446 'js2-msg (js2-get-msg msg-key)
10447 'js2-pos beg)
10448 (insert "\n"))))
10449 (js2-error-buffer-mode)
10450 (setq js2-source-buffer srcbuf)
10451 (pop-to-buffer errbuf)
10452 (goto-char (point-min))
10453 (unless (eobp)
10454 (js2-error-buffer-view))))))
10455
10456 (defvar js2-error-buffer-mode-map
10457 (let ((map (make-sparse-keymap)))
10458 (define-key map "n" #'js2-error-buffer-next)
10459 (define-key map "p" #'js2-error-buffer-prev)
10460 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10461 (define-key map "o" #'js2-error-buffer-view)
10462 (define-key map "q" #'js2-error-buffer-quit)
10463 map)
10464 "Keymap used for js2 diagnostics buffers.")
10465
10466 (defun js2-error-buffer-mode ()
10467 "Major mode for js2 diagnostics buffers.
10468 Selecting an error will jump it to the corresponding source-buffer error.
10469 \\{js2-error-buffer-mode-map}"
10470 (interactive)
10471 (setq major-mode 'js2-error-buffer-mode
10472 mode-name "JS Lint Diagnostics")
10473 (use-local-map js2-error-buffer-mode-map)
10474 (setq truncate-lines t)
10475 (set-buffer-modified-p nil)
10476 (setq buffer-read-only t)
10477 (run-hooks 'js2-error-buffer-mode-hook))
10478
10479 (defun js2-error-buffer-next ()
10480 "Move to next error and view it."
10481 (interactive)
10482 (when (zerop (forward-line 1))
10483 (js2-error-buffer-view)))
10484
10485 (defun js2-error-buffer-prev ()
10486 "Move to previous error and view it."
10487 (interactive)
10488 (when (zerop (forward-line -1))
10489 (js2-error-buffer-view)))
10490
10491 (defun js2-error-buffer-quit ()
10492 "Kill the current buffer."
10493 (interactive)
10494 (kill-buffer))
10495
10496 (defun js2-error-buffer-jump (&rest ignored)
10497 "Jump cursor to current error in source buffer."
10498 (interactive)
10499 (when (js2-error-buffer-view)
10500 (pop-to-buffer js2-source-buffer)))
10501
10502 (defun js2-error-buffer-view ()
10503 "Scroll source buffer to show error at current line."
10504 (interactive)
10505 (cond
10506 ((not (eq major-mode 'js2-error-buffer-mode))
10507 (message "Not in a js2 errors buffer"))
10508 ((not (buffer-live-p js2-source-buffer))
10509 (message "Source buffer has been killed"))
10510 ((not (wholenump (get-text-property (point) 'js2-pos)))
10511 (message "There does not seem to be an error here"))
10512 (t
10513 (let ((pos (get-text-property (point) 'js2-pos))
10514 (msg (get-text-property (point) 'js2-msg)))
10515 (save-selected-window
10516 (pop-to-buffer js2-source-buffer)
10517 (goto-char pos)
10518 (message msg))))))
10519
10520 ;;;###autoload
10521 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10522 ;; FIXME: Should derive from js-mode.
10523 "Major mode for editing JavaScript code."
10524 ;; Used by comment-region; don't change it.
10525 (set (make-local-variable 'comment-start) "//")
10526 (set (make-local-variable 'comment-end) "")
10527 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
10528 (set (make-local-variable 'max-lisp-eval-depth)
10529 (max max-lisp-eval-depth 3000))
10530 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10531 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10532 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10533 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10534 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10535 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10536 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10537 ;; for characters inside regexp literals.
10538 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10539 ;; this is necessary to make `show-paren-function' work properly
10540 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10541 ;; needed for M-x rgrep, among other things
10542 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10543
10544 (set (make-local-variable 'electric-indent-chars)
10545 (append "{}()[]:;,*." electric-indent-chars))
10546 (set (make-local-variable 'electric-layout-rules)
10547 '((?\; . after) (?\{ . after) (?\} . before)))
10548
10549 ;; some variables needed by cc-engine for paragraph-fill, etc.
10550 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10551 c-comment-start-regexp "/[*/]\\|\\s|"
10552 c-line-comment-starter "//"
10553 c-paragraph-start js2-paragraph-start
10554 c-paragraph-separate "$"
10555 c-syntactic-ws-start js2-syntactic-ws-start
10556 c-syntactic-ws-end js2-syntactic-ws-end
10557 c-syntactic-eol js2-syntactic-eol)
10558
10559 (let ((c-buffer-is-cc-mode t))
10560 ;; Copied from `js-mode'. Also see Bug#6071.
10561 (make-local-variable 'paragraph-start)
10562 (make-local-variable 'paragraph-separate)
10563 (make-local-variable 'paragraph-ignore-fill-prefix)
10564 (make-local-variable 'adaptive-fill-mode)
10565 (make-local-variable 'adaptive-fill-regexp)
10566 (c-setup-paragraph-variables))
10567
10568 (setq font-lock-defaults '(nil t))
10569
10570 ;; Experiment: make reparse-delay longer for longer files.
10571 (when (plusp js2-dynamic-idle-timer-adjust)
10572 (setq js2-idle-timer-delay
10573 (* js2-idle-timer-delay
10574 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10575
10576 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10577 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10578 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10579 (setq next-error-function #'js2-next-error)
10580 (imenu-add-to-menubar (concat "IM-" mode-name))
10581 (add-to-invisibility-spec '(js2-outline . t))
10582 (set (make-local-variable 'line-move-ignore-invisible) t)
10583 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10584
10585 (setq js2-mode-functions-hidden nil
10586 js2-mode-comments-hidden nil
10587 js2-mode-buffer-dirty-p t
10588 js2-mode-parsing nil)
10589
10590 (js2-set-default-externs)
10591
10592 (when js2-include-jslint-globals
10593 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10594
10595 (run-hooks 'js2-init-hook)
10596
10597 (js2-reparse))
10598
10599 (defun js2-mode-exit ()
10600 "Exit `js2-mode' and clean up."
10601 (interactive)
10602 (when js2-mode-node-overlay
10603 (delete-overlay js2-mode-node-overlay)
10604 (setq js2-mode-node-overlay nil))
10605 (js2-remove-overlays)
10606 (setq js2-mode-ast nil)
10607 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10608 (remove-from-invisibility-spec '(js2-outline . t))
10609 (js2-mode-show-all)
10610 (with-silent-modifications
10611 (js2-clear-face (point-min) (point-max))))
10612
10613 (defun js2-mode-reset-timer ()
10614 "Cancel any existing parse timer and schedule a new one."
10615 (if js2-mode-parse-timer
10616 (cancel-timer js2-mode-parse-timer))
10617 (setq js2-mode-parsing nil)
10618 (let ((timer (timer-create)))
10619 (setq js2-mode-parse-timer timer)
10620 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10621 (timer-set-idle-time timer js2-idle-timer-delay)
10622 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10623 (timer-activate-when-idle timer nil)))
10624
10625 (defun js2-mode-idle-reparse (buffer)
10626 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10627 it to be reparsed when the buffer is selected."
10628 (cond ((eq buffer (current-buffer))
10629 (js2-reparse))
10630 ((buffer-live-p buffer)
10631 ;; reparse when the buffer is selected again
10632 (with-current-buffer buffer
10633 (add-hook 'window-configuration-change-hook
10634 #'js2-mode-idle-reparse-inner
10635 nil t)))))
10636
10637 (defun js2-mode-idle-reparse-inner ()
10638 (remove-hook 'window-configuration-change-hook
10639 #'js2-mode-idle-reparse-inner
10640 t)
10641 (js2-reparse))
10642
10643 (defun js2-mode-edit (_beg _end _len)
10644 "Schedule a new parse after buffer is edited.
10645 Buffer edit spans from BEG to END and is of length LEN."
10646 (setq js2-mode-buffer-dirty-p t)
10647 (js2-mode-hide-overlay)
10648 (js2-mode-reset-timer))
10649
10650 (defun js2-minor-mode-edit (_beg _end _len)
10651 "Callback for buffer edits in `js2-mode'.
10652 Schedules a new parse after buffer is edited.
10653 Buffer edit spans from BEG to END and is of length LEN."
10654 (setq js2-mode-buffer-dirty-p t)
10655 (js2-mode-hide-overlay)
10656 (js2-mode-reset-timer))
10657
10658 (defun js2-reparse (&optional force)
10659 "Re-parse current buffer after user finishes some data entry.
10660 If we get any user input while parsing, including cursor motion,
10661 we discard the parse and reschedule it. If FORCE is nil, then the
10662 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10663 (let (time
10664 interrupted-p
10665 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10666 (unless js2-mode-parsing
10667 (setq js2-mode-parsing t)
10668 (unwind-protect
10669 (when (or js2-mode-buffer-dirty-p force)
10670 (js2-remove-overlays)
10671 (with-silent-modifications
10672 (setq js2-mode-buffer-dirty-p nil
10673 js2-mode-fontifications nil
10674 js2-mode-deferred-properties nil)
10675 (if js2-mode-verbose-parse-p
10676 (message "parsing..."))
10677 (setq time
10678 (js2-time
10679 (setq interrupted-p
10680 (catch 'interrupted
10681 (js2-parse)
10682 ;; if parsing is interrupted, comments and regex
10683 ;; literals stay ignored by `parse-partial-sexp'
10684 (remove-text-properties (point-min) (point-max)
10685 '(syntax-table))
10686 (js2-mode-apply-deferred-properties)
10687 (js2-mode-remove-suppressed-warnings)
10688 (js2-mode-show-warnings)
10689 (js2-mode-show-errors)
10690 (if (>= js2-highlight-level 1)
10691 (js2-highlight-jsdoc js2-mode-ast))
10692 nil))))
10693 (if interrupted-p
10694 (progn
10695 ;; unfinished parse => try again
10696 (setq js2-mode-buffer-dirty-p t)
10697 (js2-mode-reset-timer))
10698 (if js2-mode-verbose-parse-p
10699 (message "Parse time: %s" time)))))
10700 (setq js2-mode-parsing nil)
10701 (unless interrupted-p
10702 (setq js2-mode-parse-timer nil))))))
10703
10704 (defun js2-mode-show-node (event)
10705 "Debugging aid: highlight selected AST node on mouse click."
10706 (interactive "e")
10707 (mouse-set-point event)
10708 (setq deactivate-mark t)
10709 (when js2-mode-show-overlay
10710 (let ((node (js2-node-at-point))
10711 beg end)
10712 (if (null node)
10713 (message "No node found at location %s" (point))
10714 (setq beg (js2-node-abs-pos node)
10715 end (+ beg (js2-node-len node)))
10716 (if js2-mode-node-overlay
10717 (move-overlay js2-mode-node-overlay beg end)
10718 (setq js2-mode-node-overlay (make-overlay beg end))
10719 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10720 (with-silent-modifications
10721 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10722 (message "%s, parent: %s"
10723 (js2-node-short-name node)
10724 (if (js2-node-parent node)
10725 (js2-node-short-name (js2-node-parent node))
10726 "nil"))))))
10727
10728 (defun js2-mode-hide-overlay (&optional _p1 p2)
10729 "Remove the debugging overlay when the point moves.
10730 P1 and P2 are the old and new values of point, respectively."
10731 (when js2-mode-node-overlay
10732 (let ((beg (overlay-start js2-mode-node-overlay))
10733 (end (overlay-end js2-mode-node-overlay)))
10734 ;; Sometimes we're called spuriously.
10735 (unless (and p2
10736 (>= p2 beg)
10737 (<= p2 end))
10738 (with-silent-modifications
10739 (remove-text-properties beg end '(point-left nil)))
10740 (delete-overlay js2-mode-node-overlay)
10741 (setq js2-mode-node-overlay nil)))))
10742
10743 (defun js2-mode-reset ()
10744 "Debugging helper: reset everything."
10745 (interactive)
10746 (js2-mode-exit)
10747 (js2-mode))
10748
10749 (defun js2-mode-show-warn-or-err (e face)
10750 "Highlight a warning or error E with FACE.
10751 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10752 The last element is optional. When present, use instead of FACE."
10753 (let* ((key (first e))
10754 (beg (second e))
10755 (end (+ beg (third e)))
10756 ;; Don't inadvertently go out of bounds.
10757 (beg (max (point-min) (min beg (point-max))))
10758 (end (max (point-min) (min end (point-max))))
10759 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10760 (ovl (make-overlay beg end)))
10761 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10762 (overlay-put ovl 'js2-error t)
10763 (put-text-property beg end 'help-echo (js2-get-msg key))
10764 (put-text-property beg end 'point-entered #'js2-echo-error)))
10765
10766 (defun js2-remove-overlays ()
10767 "Remove overlays from buffer that have a `js2-error' property."
10768 (let ((beg (point-min))
10769 (end (point-max)))
10770 (save-excursion
10771 (dolist (o (overlays-in beg end))
10772 (when (overlay-get o 'js2-error)
10773 (delete-overlay o))))))
10774
10775 (defun js2-error-at-point (&optional pos)
10776 "Return non-nil if there's an error overlay at POS.
10777 Defaults to point."
10778 (loop with pos = (or pos (point))
10779 for o in (overlays-at pos)
10780 thereis (overlay-get o 'js2-error)))
10781
10782 (defun js2-mode-apply-deferred-properties ()
10783 "Apply fontifications and other text properties recorded during parsing."
10784 (when (plusp js2-highlight-level)
10785 ;; We defer clearing faces as long as possible to eliminate flashing.
10786 (js2-clear-face (point-min) (point-max))
10787 ;; Have to reverse the recorded fontifications list so that errors
10788 ;; and warnings overwrite the normal fontifications.
10789 (dolist (f (nreverse js2-mode-fontifications))
10790 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10791 (setq js2-mode-fontifications nil))
10792 (dolist (p js2-mode-deferred-properties)
10793 (apply #'put-text-property p))
10794 (setq js2-mode-deferred-properties nil))
10795
10796 (defun js2-mode-show-errors ()
10797 "Highlight syntax errors."
10798 (when js2-mode-show-parse-errors
10799 (dolist (e (js2-ast-root-errors js2-mode-ast))
10800 (js2-mode-show-warn-or-err e 'js2-error))))
10801
10802 (defun js2-mode-remove-suppressed-warnings ()
10803 "Take suppressed warnings out of the AST warnings list.
10804 This ensures that the counts and `next-error' are correct."
10805 (setf (js2-ast-root-warnings js2-mode-ast)
10806 (js2-delete-if
10807 (lambda (e)
10808 (let ((key (caar e)))
10809 (or
10810 (and (not js2-strict-trailing-comma-warning)
10811 (string-match "trailing\\.comma" key))
10812 (and (not js2-strict-cond-assign-warning)
10813 (string= key "msg.equal.as.assign"))
10814 (and js2-missing-semi-one-line-override
10815 (string= key "msg.missing.semi")
10816 (let* ((beg (second e))
10817 (node (js2-node-at-point beg))
10818 (fn (js2-mode-find-parent-fn node))
10819 (body (and fn (js2-function-node-body fn)))
10820 (lc (and body (js2-node-abs-pos body)))
10821 (rc (and lc (+ lc (js2-node-len body)))))
10822 (and fn
10823 (or (null body)
10824 (save-excursion
10825 (goto-char beg)
10826 (and (js2-same-line lc)
10827 (js2-same-line rc))))))))))
10828 (js2-ast-root-warnings js2-mode-ast))))
10829
10830 (defun js2-mode-show-warnings ()
10831 "Highlight strict-mode warnings."
10832 (when js2-mode-show-strict-warnings
10833 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10834 (js2-mode-show-warn-or-err e 'js2-warning))))
10835
10836 (defun js2-echo-error (_old-point new-point)
10837 "Called by point-motion hooks."
10838 (let ((msg (get-text-property new-point 'help-echo)))
10839 (when (and (stringp msg)
10840 (not (active-minibuffer-window))
10841 (not (current-message)))
10842 (message msg))))
10843
10844 (defalias 'js2-echo-help #'js2-echo-error)
10845
10846 (defun js2-line-break (&optional _soft)
10847 "Break line at point and indent, continuing comment if within one.
10848 If inside a string, and `js2-concat-multiline-strings' is not
10849 nil, turn it into concatenation."
10850 (interactive)
10851 (let ((parse-status (syntax-ppss)))
10852 (cond
10853 ;; Check if we're inside a string.
10854 ((nth 3 parse-status)
10855 (if js2-concat-multiline-strings
10856 (js2-mode-split-string parse-status)
10857 (insert "\n")))
10858 ;; Check if inside a block comment.
10859 ((nth 4 parse-status)
10860 (js2-mode-extend-comment (nth 8 parse-status)))
10861 (t
10862 (newline-and-indent)))))
10863
10864 (defun js2-mode-split-string (parse-status)
10865 "Turn a newline in mid-string into a string concatenation.
10866 PARSE-STATUS is as documented in `parse-partial-sexp'."
10867 (let* ((quote-char (nth 3 parse-status))
10868 (at-eol (eq js2-concat-multiline-strings 'eol)))
10869 (insert quote-char)
10870 (insert (if at-eol " +\n" "\n"))
10871 (unless at-eol
10872 (insert "+ "))
10873 (js2-indent-line)
10874 (insert quote-char)
10875 (when (eolp)
10876 (insert quote-char)
10877 (backward-char 1))))
10878
10879 (defun js2-mode-extend-comment (start-pos)
10880 "Indent the line and, when inside a comment block, add comment prefix."
10881 (let (star single col first-line needs-close)
10882 (save-excursion
10883 (back-to-indentation)
10884 (when (< (point) start-pos)
10885 (goto-char start-pos))
10886 (cond
10887 ((looking-at "\\*[^/]")
10888 (setq star t
10889 col (current-column)))
10890 ((looking-at "/\\*")
10891 (setq star t
10892 first-line t
10893 col (1+ (current-column))))
10894 ((looking-at "//")
10895 (setq single t
10896 col (current-column)))))
10897 ;; Heuristic for whether we need to close the comment:
10898 ;; if we've got a parse error here, assume it's an unterminated
10899 ;; comment.
10900 (setq needs-close
10901 (or
10902 (eq (get-text-property (1- (point)) 'point-entered)
10903 'js2-echo-error)
10904 ;; The heuristic above doesn't work well when we're
10905 ;; creating a comment and there's another one downstream,
10906 ;; as our parser thinks this one ends at the end of the
10907 ;; next one. (You can have a /* inside a js block comment.)
10908 ;; So just close it if the next non-ws char isn't a *.
10909 (and first-line
10910 (eolp)
10911 (save-excursion
10912 (skip-chars-forward " \t\r\n")
10913 (not (eq (char-after) ?*))))))
10914 (delete-horizontal-space)
10915 (insert "\n")
10916 (cond
10917 (star
10918 (indent-to col)
10919 (insert "* ")
10920 (if (and first-line needs-close)
10921 (save-excursion
10922 (insert "\n")
10923 (indent-to col)
10924 (insert "*/"))))
10925 ((and single
10926 (save-excursion
10927 (and (zerop (forward-line 1))
10928 (looking-at "\\s-*//"))))
10929 (indent-to col)
10930 (insert "// ")))
10931 ;; Don't need to extend the comment after all.
10932 (js2-indent-line)))
10933
10934 (defun js2-beginning-of-line ()
10935 "Toggle point between bol and first non-whitespace char in line.
10936 Also moves past comment delimiters when inside comments."
10937 (interactive)
10938 (let (node)
10939 (cond
10940 ((bolp)
10941 (back-to-indentation))
10942 ((looking-at "//")
10943 (skip-chars-forward "/ \t"))
10944 ((and (eq (char-after) ?*)
10945 (setq node (js2-comment-at-point))
10946 (memq (js2-comment-node-format node) '(jsdoc block))
10947 (save-excursion
10948 (skip-chars-backward " \t")
10949 (bolp)))
10950 (skip-chars-forward "\* \t"))
10951 (t
10952 (goto-char (point-at-bol))))))
10953
10954 (defun js2-end-of-line ()
10955 "Toggle point between eol and last non-whitespace char in line."
10956 (interactive)
10957 (if (eolp)
10958 (skip-chars-backward " \t")
10959 (goto-char (point-at-eol))))
10960
10961 (defun js2-mode-wait-for-parse (callback)
10962 "Invoke CALLBACK when parsing is finished.
10963 If parsing is already finished, calls CALLBACK immediately."
10964 (if (not js2-mode-buffer-dirty-p)
10965 (funcall callback)
10966 (push callback js2-mode-pending-parse-callbacks)
10967 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10968
10969 (defun js2-mode-parse-finished ()
10970 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10971 ;; We can't let errors propagate up, since it prevents the
10972 ;; `js2-parse' method from completing normally and returning
10973 ;; the ast, which makes things mysteriously not work right.
10974 (unwind-protect
10975 (dolist (cb js2-mode-pending-parse-callbacks)
10976 (condition-case err
10977 (funcall cb)
10978 (error (message "%s" err))))
10979 (setq js2-mode-pending-parse-callbacks nil)))
10980
10981 (defun js2-mode-flag-region (from to flag)
10982 "Hide or show text from FROM to TO, according to FLAG.
10983 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10984 Returns the created overlay if FLAG is non-nil."
10985 (remove-overlays from to 'invisible 'js2-outline)
10986 (when flag
10987 (let ((o (make-overlay from to)))
10988 (overlay-put o 'invisible 'js2-outline)
10989 (overlay-put o 'isearch-open-invisible
10990 'js2-isearch-open-invisible)
10991 o)))
10992
10993 ;; Function to be set as an outline-isearch-open-invisible' property
10994 ;; to the overlay that makes the outline invisible (see
10995 ;; `js2-mode-flag-region').
10996 (defun js2-isearch-open-invisible (_overlay)
10997 ;; We rely on the fact that isearch places point on the matched text.
10998 (js2-mode-show-element))
10999
11000 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11001 "Return cons cell of bounds of folding overlay at POS.
11002 Returns nil if not found."
11003 (let ((overlays (overlays-at (or pos (point))))
11004 o)
11005 (while (and overlays
11006 (not o))
11007 (if (overlay-get (car overlays) 'invisible)
11008 (setq o (car overlays))
11009 (setq overlays (cdr overlays))))
11010 (if o
11011 (cons (overlay-start o) (overlay-end o)))))
11012
11013 (defun js2-mode-function-at-point (&optional pos)
11014 "Return the innermost function node enclosing current point.
11015 Returns nil if point is not in a function."
11016 (let ((node (js2-node-at-point pos)))
11017 (while (and node (not (js2-function-node-p node)))
11018 (setq node (js2-node-parent node)))
11019 (if (js2-function-node-p node)
11020 node)))
11021
11022 (defun js2-mode-toggle-element ()
11023 "Hide or show the foldable element at the point."
11024 (interactive)
11025 (let (comment fn pos)
11026 (save-excursion
11027 (cond
11028 ;; /* ... */ comment?
11029 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11030 (if (js2-mode-invisible-overlay-bounds
11031 (setq pos (+ 3 (js2-node-abs-pos comment))))
11032 (progn
11033 (goto-char pos)
11034 (js2-mode-show-element))
11035 (js2-mode-hide-element)))
11036 ;; //-comment?
11037 ((save-excursion
11038 (back-to-indentation)
11039 (looking-at js2-mode-//-comment-re))
11040 (js2-mode-toggle-//-comment))
11041 ;; function?
11042 ((setq fn (js2-mode-function-at-point))
11043 (setq pos (and (js2-function-node-body fn)
11044 (js2-node-abs-pos (js2-function-node-body fn))))
11045 (goto-char (1+ pos))
11046 (if (js2-mode-invisible-overlay-bounds)
11047 (js2-mode-show-element)
11048 (js2-mode-hide-element)))
11049 (t
11050 (message "Nothing at point to hide or show"))))))
11051
11052 (defun js2-mode-hide-element ()
11053 "Fold/hide contents of a block, showing ellipses.
11054 Show the hidden text with \\[js2-mode-show-element]."
11055 (interactive)
11056 (if js2-mode-buffer-dirty-p
11057 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11058 (let (node body beg end)
11059 (cond
11060 ((js2-mode-invisible-overlay-bounds)
11061 (message "already hidden"))
11062 (t
11063 (setq node (js2-node-at-point))
11064 (cond
11065 ((js2-block-comment-p node)
11066 (js2-mode-hide-comment node))
11067 (t
11068 (while (and node (not (js2-function-node-p node)))
11069 (setq node (js2-node-parent node)))
11070 (if (and node
11071 (setq body (js2-function-node-body node)))
11072 (progn
11073 (setq beg (js2-node-abs-pos body)
11074 end (+ beg (js2-node-len body)))
11075 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11076 (message "No collapsable element found at point"))))))))
11077
11078 (defun js2-mode-show-element ()
11079 "Show the hidden element at current point."
11080 (interactive)
11081 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11082 (if bounds
11083 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11084 (message "Nothing to un-hide"))))
11085
11086 (defun js2-mode-show-all ()
11087 "Show all of the text in the buffer."
11088 (interactive)
11089 (js2-mode-flag-region (point-min) (point-max) nil))
11090
11091 (defun js2-mode-toggle-hide-functions ()
11092 (interactive)
11093 (if js2-mode-functions-hidden
11094 (js2-mode-show-functions)
11095 (js2-mode-hide-functions)))
11096
11097 (defun js2-mode-hide-functions ()
11098 "Hides all non-nested function bodies in the buffer.
11099 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11100 to open an individual entry."
11101 (interactive)
11102 (if js2-mode-buffer-dirty-p
11103 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11104 (if (null js2-mode-ast)
11105 (message "Oops - parsing failed")
11106 (setq js2-mode-functions-hidden t)
11107 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11108
11109 (defun js2-mode-function-hider (n endp)
11110 (when (not endp)
11111 (let ((tt (js2-node-type n))
11112 body beg end)
11113 (cond
11114 ((and (= tt js2-FUNCTION)
11115 (setq body (js2-function-node-body n)))
11116 (setq beg (js2-node-abs-pos body)
11117 end (+ beg (js2-node-len body)))
11118 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11119 nil) ; don't process children of function
11120 (t
11121 t))))) ; keep processing other AST nodes
11122
11123 (defun js2-mode-show-functions ()
11124 "Un-hide any folded function bodies in the buffer."
11125 (interactive)
11126 (setq js2-mode-functions-hidden nil)
11127 (save-excursion
11128 (goto-char (point-min))
11129 (while (/= (goto-char (next-overlay-change (point)))
11130 (point-max))
11131 (dolist (o (overlays-at (point)))
11132 (when (and (overlay-get o 'invisible)
11133 (not (overlay-get o 'comment)))
11134 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11135
11136 (defun js2-mode-hide-comment (n)
11137 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11138 3 ; /**
11139 2)) ; /*
11140 (beg (+ (js2-node-abs-pos n) head))
11141 (end (- (+ beg (js2-node-len n)) head 2))
11142 (o (js2-mode-flag-region beg end 'hide)))
11143 (overlay-put o 'comment t)))
11144
11145 (defun js2-mode-toggle-hide-comments ()
11146 "Folds all block comments in the buffer.
11147 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11148 to open an individual entry."
11149 (interactive)
11150 (if js2-mode-comments-hidden
11151 (js2-mode-show-comments)
11152 (js2-mode-hide-comments)))
11153
11154 (defun js2-mode-hide-comments ()
11155 (interactive)
11156 (if js2-mode-buffer-dirty-p
11157 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11158 (if (null js2-mode-ast)
11159 (message "Oops - parsing failed")
11160 (setq js2-mode-comments-hidden t)
11161 (dolist (n (js2-ast-root-comments js2-mode-ast))
11162 (when (js2-block-comment-p n)
11163 (js2-mode-hide-comment n)))
11164 (js2-mode-hide-//-comments)))
11165
11166 (defun js2-mode-extend-//-comment (direction)
11167 "Find start or end of a block of similar //-comment lines.
11168 DIRECTION is -1 to look back, 1 to look forward.
11169 INDENT is the indentation level to match.
11170 Returns the end-of-line position of the furthest adjacent
11171 //-comment line with the same indentation as the current line.
11172 If there is no such matching line, returns current end of line."
11173 (let ((pos (point-at-eol))
11174 (indent (current-indentation)))
11175 (save-excursion
11176 (while (and (zerop (forward-line direction))
11177 (looking-at js2-mode-//-comment-re)
11178 (eq indent (length (match-string 1))))
11179 (setq pos (point-at-eol))
11180 pos))))
11181
11182 (defun js2-mode-hide-//-comments ()
11183 "Fold adjacent 1-line comments, showing only snippet of first one."
11184 (let (beg end)
11185 (save-excursion
11186 (goto-char (point-min))
11187 (while (re-search-forward js2-mode-//-comment-re nil t)
11188 (setq beg (point)
11189 end (js2-mode-extend-//-comment 1))
11190 (unless (eq beg end)
11191 (overlay-put (js2-mode-flag-region beg end 'hide)
11192 'comment t))
11193 (goto-char end)
11194 (forward-char 1)))))
11195
11196 (defun js2-mode-toggle-//-comment ()
11197 "Fold or un-fold any multi-line //-comment at point.
11198 Caller should have determined that this line starts with a //-comment."
11199 (let* ((beg (point-at-eol))
11200 (end beg))
11201 (save-excursion
11202 (goto-char end)
11203 (if (js2-mode-invisible-overlay-bounds)
11204 (js2-mode-show-element)
11205 ;; else hide the comment
11206 (setq beg (js2-mode-extend-//-comment -1)
11207 end (js2-mode-extend-//-comment 1))
11208 (unless (eq beg end)
11209 (overlay-put (js2-mode-flag-region beg end 'hide)
11210 'comment t))))))
11211
11212 (defun js2-mode-show-comments ()
11213 "Un-hide any hidden comments, leaving other hidden elements alone."
11214 (interactive)
11215 (setq js2-mode-comments-hidden nil)
11216 (save-excursion
11217 (goto-char (point-min))
11218 (while (/= (goto-char (next-overlay-change (point)))
11219 (point-max))
11220 (dolist (o (overlays-at (point)))
11221 (when (overlay-get o 'comment)
11222 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11223
11224 (defun js2-mode-display-warnings-and-errors ()
11225 "Turn on display of warnings and errors."
11226 (interactive)
11227 (setq js2-mode-show-parse-errors t
11228 js2-mode-show-strict-warnings t)
11229 (js2-reparse 'force))
11230
11231 (defun js2-mode-hide-warnings-and-errors ()
11232 "Turn off display of warnings and errors."
11233 (interactive)
11234 (setq js2-mode-show-parse-errors nil
11235 js2-mode-show-strict-warnings nil)
11236 (js2-reparse 'force))
11237
11238 (defun js2-mode-toggle-warnings-and-errors ()
11239 "Toggle the display of warnings and errors.
11240 Some users don't like having warnings/errors reported while they type."
11241 (interactive)
11242 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11243 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11244 (if (called-interactively-p 'any)
11245 (message "warnings and errors %s"
11246 (if js2-mode-show-parse-errors
11247 "enabled"
11248 "disabled")))
11249 (js2-reparse 'force))
11250
11251 (defun js2-mode-customize ()
11252 (interactive)
11253 (customize-group 'js2-mode))
11254
11255 (defun js2-mode-forward-sexp (&optional arg)
11256 "Move forward across one statement or balanced expression.
11257 With ARG, do it that many times. Negative arg -N means
11258 move backward across N balanced expressions."
11259 (interactive "p")
11260 (setq arg (or arg 1))
11261 (save-restriction
11262 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11263 (js2-reparse)
11264 (let (forward-sexp-function
11265 node (start (point)) pos lp rp child)
11266 (cond
11267 ;; backward-sexp
11268 ;; could probably make this better for some cases:
11269 ;; - if in statement block (e.g. function body), go to parent
11270 ;; - infix exprs like (foo in bar) - maybe go to beginning
11271 ;; of infix expr if in the right-side expression?
11272 ((and arg (minusp arg))
11273 (dotimes (_ (- arg))
11274 (js2-backward-sws)
11275 (forward-char -1) ; Enter the node we backed up to.
11276 (when (setq node (js2-node-at-point (point) t))
11277 (setq pos (js2-node-abs-pos node))
11278 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11279 (setq lp (car parens)
11280 rp (cdr parens)))
11281 (when (and lp (> start lp))
11282 (if (and rp (<= start rp))
11283 ;; Between parens, check if there's a child node we can jump.
11284 (when (setq child (js2-node-closest-child node (point) lp t))
11285 (setq pos (js2-node-abs-pos child)))
11286 ;; Before both parens.
11287 (setq pos lp)))
11288 (let ((state (parse-partial-sexp start pos)))
11289 (goto-char (if (not (zerop (car state)))
11290 ;; Stumble at the unbalanced paren if < 0, or
11291 ;; jump a bit further if > 0.
11292 (scan-sexps start -1)
11293 pos))))
11294 (unless pos (goto-char (point-min)))))
11295 (t
11296 ;; forward-sexp
11297 (dotimes (_ arg)
11298 (js2-forward-sws)
11299 (when (setq node (js2-node-at-point (point) t))
11300 (setq pos (js2-node-abs-pos node))
11301 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11302 (setq lp (car parens)
11303 rp (cdr parens)))
11304 (or
11305 (when (and rp (<= start rp))
11306 (if (> start lp)
11307 (when (setq child (js2-node-closest-child node (point) rp))
11308 (setq pos (js2-node-abs-end child)))
11309 (setq pos (1+ rp))))
11310 ;; No parens or child nodes, looks for the end of the curren node.
11311 (incf pos (js2-node-len
11312 (if (js2-expr-stmt-node-p (js2-node-parent node))
11313 ;; Stop after the semicolon.
11314 (js2-node-parent node)
11315 node))))
11316 (let ((state (save-excursion (parse-partial-sexp start pos))))
11317 (goto-char (if (not (zerop (car state)))
11318 (scan-sexps start 1)
11319 pos))))
11320 (unless pos (goto-char (point-max)))))))))
11321
11322 (defun js2-mode-forward-sexp-parens (node abs-pos)
11323 "Return a cons cell with positions of main parens in NODE."
11324 (cond
11325 ((or (js2-array-node-p node)
11326 (js2-object-node-p node)
11327 (js2-comp-node-p node)
11328 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11329 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11330 ((js2-paren-expr-node-p node)
11331 (let ((lp (js2-node-lp node))
11332 (rp (js2-node-rp node)))
11333 (cons (when lp (+ abs-pos lp))
11334 (when rp (+ abs-pos rp)))))))
11335
11336 (defun js2-node-closest-child (parent point limit &optional before)
11337 (let* ((parent-pos (js2-node-abs-pos parent))
11338 (rpoint (- point parent-pos))
11339 (rlimit (- limit parent-pos))
11340 (min (min rpoint rlimit))
11341 (max (max rpoint rlimit))
11342 found)
11343 (catch 'done
11344 (js2-visit-ast
11345 parent
11346 (lambda (node _end-p)
11347 (if (eq node parent)
11348 t
11349 (let ((pos (js2-node-pos node)) ;; Both relative values.
11350 (end (+ (js2-node-pos node) (js2-node-len node))))
11351 (when (and (>= pos min) (<= end max)
11352 (if before (< pos rpoint) (> end rpoint)))
11353 (setq found node))
11354 (when (> end rpoint)
11355 (throw 'done nil)))
11356 nil))))
11357 found))
11358
11359 (defun js2-errors ()
11360 "Return a list of errors found."
11361 (and js2-mode-ast
11362 (js2-ast-root-errors js2-mode-ast)))
11363
11364 (defun js2-warnings ()
11365 "Return a list of warnings found."
11366 (and js2-mode-ast
11367 (js2-ast-root-warnings js2-mode-ast)))
11368
11369 (defun js2-have-errors-p ()
11370 "Return non-nil if any parse errors or warnings were found."
11371 (or (js2-errors) (js2-warnings)))
11372
11373 (defun js2-errors-and-warnings ()
11374 "Return a copy of the concatenated errors and warnings lists.
11375 They are appended: first the errors, then the warnings.
11376 Entries are of the form (MSG BEG END)."
11377 (when js2-mode-ast
11378 (append (js2-ast-root-errors js2-mode-ast)
11379 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11380
11381 (defun js2-next-error (&optional arg reset)
11382 "Move to next parse error.
11383 Typically invoked via \\[next-error].
11384 ARG is the number of errors, forward or backward, to move.
11385 RESET means start over from the beginning."
11386 (interactive "p")
11387 (if (not (or (js2-errors) (js2-warnings)))
11388 (message "No errors")
11389 (when reset
11390 (goto-char (point-min)))
11391 (let* ((errs (js2-errors-and-warnings))
11392 (continue t)
11393 (start (point))
11394 (count (or arg 1))
11395 (backward (minusp count))
11396 (sorter (if backward '> '<))
11397 (stopper (if backward '< '>))
11398 (count (abs count))
11399 all-errs err)
11400 ;; Sort by start position.
11401 (setq errs (sort errs (lambda (e1 e2)
11402 (funcall sorter (second e1) (second e2))))
11403 all-errs errs)
11404 ;; Find nth error with pos > start.
11405 (while (and errs continue)
11406 (when (funcall stopper (cadar errs) start)
11407 (setq err (car errs))
11408 (if (zerop (decf count))
11409 (setq continue nil)))
11410 (setq errs (cdr errs)))
11411 ;; Clear for `js2-echo-error'.
11412 (message nil)
11413 (if err
11414 (goto-char (second err))
11415 ;; Wrap around to first error.
11416 (goto-char (second (car all-errs)))
11417 ;; If we were already on it, echo msg again.
11418 (if (= (point) start)
11419 (js2-echo-error (point) (point)))))))
11420
11421 (defun js2-down-mouse-3 ()
11422 "Make right-click move the point to the click location.
11423 This makes right-click context menu operations a bit more intuitive.
11424 The point will not move if the region is active, however, to avoid
11425 destroying the region selection."
11426 (interactive)
11427 (when (and js2-move-point-on-right-click
11428 (not mark-active))
11429 (let ((e last-input-event))
11430 (ignore-errors
11431 (goto-char (cadadr e))))))
11432
11433 (defun js2-mode-create-imenu-index ()
11434 "Return an alist for `imenu--index-alist'."
11435 ;; This is built up in `js2-parse-record-imenu' during parsing.
11436 (when js2-mode-ast
11437 ;; if we have an ast but no recorder, they're requesting a rescan
11438 (unless js2-imenu-recorder
11439 (js2-reparse 'force))
11440 (prog1
11441 (js2-build-imenu-index)
11442 (setq js2-imenu-recorder nil
11443 js2-imenu-function-map nil))))
11444
11445 (defun js2-mode-find-tag ()
11446 "Replacement for `find-tag-default'.
11447 `find-tag-default' returns a ridiculous answer inside comments."
11448 (let (beg end)
11449 (js2-with-underscore-as-word-syntax
11450 (save-excursion
11451 (if (and (not (looking-at "[[:alnum:]_$]"))
11452 (looking-back "[[:alnum:]_$]"))
11453 (setq beg (progn (forward-word -1) (point))
11454 end (progn (forward-word 1) (point)))
11455 (setq beg (progn (forward-word 1) (point))
11456 end (progn (forward-word -1) (point))))
11457 (replace-regexp-in-string
11458 "[\"']" ""
11459 (buffer-substring-no-properties beg end))))))
11460
11461 (defun js2-mode-forward-sibling ()
11462 "Move to the end of the sibling following point in parent.
11463 Returns non-nil if successful, or nil if there was no following sibling."
11464 (let* ((node (js2-node-at-point))
11465 (parent (js2-mode-find-enclosing-fn node))
11466 sib)
11467 (when (setq sib (js2-node-find-child-after (point) parent))
11468 (goto-char (+ (js2-node-abs-pos sib)
11469 (js2-node-len sib))))))
11470
11471 (defun js2-mode-backward-sibling ()
11472 "Move to the beginning of the sibling node preceding point in parent.
11473 Parent is defined as the enclosing script or function."
11474 (let* ((node (js2-node-at-point))
11475 (parent (js2-mode-find-enclosing-fn node))
11476 sib)
11477 (when (setq sib (js2-node-find-child-before (point) parent))
11478 (goto-char (js2-node-abs-pos sib)))))
11479
11480 (defun js2-beginning-of-defun (&optional arg)
11481 "Go to line on which current function starts, and return t on success.
11482 If we're not in a function or already at the beginning of one, go
11483 to beginning of previous script-level element.
11484 With ARG N, do that N times. If N is negative, move forward."
11485 (setq arg (or arg 1))
11486 (if (plusp arg)
11487 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11488 (when (cond
11489 ((js2-function-node-p parent)
11490 (goto-char (js2-node-abs-pos parent)))
11491 (t
11492 (js2-mode-backward-sibling)))
11493 (if (> arg 1)
11494 (js2-beginning-of-defun (1- arg))
11495 t)))
11496 (when (js2-end-of-defun)
11497 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
11498
11499 (defun js2-end-of-defun ()
11500 "Go to the char after the last position of the current function
11501 or script-level element."
11502 (let* ((node (js2-node-at-point))
11503 (parent (or (and (js2-function-node-p node) node)
11504 (js2-node-parent-script-or-fn node)))
11505 script)
11506 (unless (js2-function-node-p parent)
11507 ;; Use current script-level node, or, if none, the next one.
11508 (setq script (or parent node)
11509 parent (js2-node-find-child-before (point) script))
11510 (when (or (null parent)
11511 (>= (point) (+ (js2-node-abs-pos parent)
11512 (js2-node-len parent))))
11513 (setq parent (js2-node-find-child-after (point) script))))
11514 (when parent
11515 (goto-char (+ (js2-node-abs-pos parent)
11516 (js2-node-len parent))))))
11517
11518 (defun js2-mark-defun (&optional allow-extend)
11519 "Put mark at end of this function, point at beginning.
11520 The function marked is the one that contains point.
11521
11522 Interactively, if this command is repeated,
11523 or (in Transient Mark mode) if the mark is active,
11524 it marks the next defun after the ones already marked."
11525 (interactive "p")
11526 (let (extended)
11527 (when (and allow-extend
11528 (or (and (eq last-command this-command) (mark t))
11529 (and transient-mark-mode mark-active)))
11530 (let ((sib (save-excursion
11531 (goto-char (mark))
11532 (if (js2-mode-forward-sibling)
11533 (point)))))
11534 (if sib
11535 (progn
11536 (set-mark sib)
11537 (setq extended t))
11538 ;; no more siblings - try extending to enclosing node
11539 (goto-char (mark t)))))
11540 (when (not extended)
11541 (let ((node (js2-node-at-point (point) t)) ; skip comments
11542 ast fn stmt parent beg end)
11543 (when (js2-ast-root-p node)
11544 (setq ast node
11545 node (or (js2-node-find-child-after (point) node)
11546 (js2-node-find-child-before (point) node))))
11547 ;; only mark whole buffer if we can't find any children
11548 (if (null node)
11549 (setq node ast))
11550 (if (js2-function-node-p node)
11551 (setq parent node)
11552 (setq fn (js2-mode-find-enclosing-fn node)
11553 stmt (if (or (null fn)
11554 (js2-ast-root-p fn))
11555 (js2-mode-find-first-stmt node))
11556 parent (or stmt fn)))
11557 (setq beg (js2-node-abs-pos parent)
11558 end (+ beg (js2-node-len parent)))
11559 (push-mark beg)
11560 (goto-char end)
11561 (exchange-point-and-mark)))))
11562
11563 (defun js2-narrow-to-defun ()
11564 "Narrow to the function enclosing point."
11565 (interactive)
11566 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11567 (fn (if (js2-script-node-p node)
11568 node
11569 (js2-mode-find-enclosing-fn node)))
11570 (beg (js2-node-abs-pos fn)))
11571 (unless (js2-ast-root-p fn)
11572 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11573
11574 (provide 'js2-mode)
11575
11576 ;;; js2-mode.el ends here