]> code.delx.au - gnu-emacs-elpa/blob - lib/js2-mode/js2-mode.el
Update compilation.
[gnu-emacs-elpa] / lib / js2-mode / 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: 20141118
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
65
66 ;; Notes:
67
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
71
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
76
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
81
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code has outdated information and is mostly
84 ;; unmaintained.
85
86 ;;; Code:
87
88 (eval-when-compile
89 (require 'cl))
90
91 (require 'imenu)
92 (require 'cc-cmds) ; for `c-fill-paragraph'
93
94 (eval-and-compile
95 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
96 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
97
98 (defvar electric-layout-rules)
99
100 ;;; Externs (variables presumed to be defined by the host system)
101
102 (defvar js2-ecma-262-externs
103 (mapcar 'symbol-name
104 '(Array Boolean Date Error EvalError Function Infinity JSON
105 Math NaN Number Object RangeError ReferenceError RegExp
106 String SyntaxError TypeError URIError arguments
107 decodeURI decodeURIComponent encodeURI
108 encodeURIComponent escape eval isFinite isNaN
109 parseFloat parseInt undefined unescape))
110 "Ecma-262 externs. Included in `js2-externs' by default.")
111
112 (defvar js2-browser-externs
113 (mapcar 'symbol-name
114 '(;; DOM level 1
115 Attr CDATASection CharacterData Comment DOMException
116 DOMImplementation Document DocumentFragment
117 DocumentType Element Entity EntityReference
118 ExceptionCode NamedNodeMap Node NodeList Notation
119 ProcessingInstruction Text
120
121 ;; DOM level 2
122 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
123 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
124 HTMLBodyElement HTMLButtonElement HTMLCollection
125 HTMLDListElement HTMLDirectoryElement HTMLDivElement
126 HTMLDocument HTMLElement HTMLFieldSetElement
127 HTMLFontElement HTMLFormElement HTMLFrameElement
128 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
129 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
130 HTMLImageElement HTMLInputElement HTMLIsIndexElement
131 HTMLLIElement HTMLLabelElement HTMLLegendElement
132 HTMLLinkElement HTMLMapElement HTMLMenuElement
133 HTMLMetaElement HTMLModElement HTMLOListElement
134 HTMLObjectElement HTMLOptGroupElement
135 HTMLOptionElement HTMLOptionsCollection
136 HTMLParagraphElement HTMLParamElement HTMLPreElement
137 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
138 HTMLStyleElement HTMLTableCaptionElement
139 HTMLTableCellElement HTMLTableColElement
140 HTMLTableElement HTMLTableRowElement
141 HTMLTableSectionElement HTMLTextAreaElement
142 HTMLTitleElement HTMLUListElement
143
144 ;; DOM level 3
145 DOMConfiguration DOMError DOMException
146 DOMImplementationList DOMImplementationSource
147 DOMLocator DOMStringList NameList TypeInfo
148 UserDataHandler
149
150 ;; Window
151 window alert confirm document java navigator prompt screen
152 self top
153
154 ;; W3C CSS
155 CSSCharsetRule CSSFontFace CSSFontFaceRule
156 CSSImportRule CSSMediaRule CSSPageRule
157 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
158 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
159 CSSValue CSSValueList Counter DOMImplementationCSS
160 DocumentCSS DocumentStyle ElementCSSInlineStyle
161 LinkStyle MediaList RGBColor Rect StyleSheet
162 StyleSheetList ViewCSS
163
164 ;; W3C Event
165 EventListener EventTarget Event DocumentEvent UIEvent
166 MouseEvent MutationEvent KeyboardEvent
167
168 ;; W3C Range
169 DocumentRange Range RangeException
170
171 ;; W3C XML
172 XPathResult XMLHttpRequest
173
174 ;; console object. Provided by at least Chrome and Firefox.
175 console))
176 "Browser externs.
177 You can cause these to be included or excluded with the custom
178 variable `js2-include-browser-externs'.")
179
180 (defvar js2-rhino-externs
181 (mapcar 'symbol-name
182 '(Packages importClass importPackage com org java
183 ;; Global object (shell) externs.
184 defineClass deserialize doctest gc help load
185 loadClass print quit readFile readUrl runCommand seal
186 serialize spawn sync toint32 version))
187 "Mozilla Rhino externs.
188 Set `js2-include-rhino-externs' to t to include them.")
189
190 (defvar js2-node-externs
191 (mapcar 'symbol-name
192 '(__dirname __filename Buffer clearInterval clearTimeout require
193 console exports global module process setInterval setTimeout))
194 "Node.js externs.
195 Set `js2-include-node-externs' to t to include them.")
196
197 (defvar js2-typed-array-externs
198 (mapcar 'symbol-name
199 '(ArrayBuffer Uint8ClampedArray DataView
200 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
201 Float32Array Float64Array))
202 "Khronos typed array externs. Available in most modern browsers and
203 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
204 are enabled, these will also be included.")
205
206 ;;; Variables
207
208 (defun js2-mark-safe-local (name pred)
209 "Make the variable NAME buffer-local and mark it as safe file-local
210 variable with predicate PRED."
211 (make-variable-buffer-local name)
212 (put name 'safe-local-variable pred))
213
214 (defcustom js2-highlight-level 2
215 "Amount of syntax highlighting to perform.
216 0 or a negative value means none.
217 1 adds basic syntax highlighting.
218 2 adds highlighting of some Ecma built-in properties.
219 3 adds highlighting of many Ecma built-in functions."
220 :group 'js2-mode
221 :type '(choice (const :tag "None" 0)
222 (const :tag "Basic" 1)
223 (const :tag "Include Properties" 2)
224 (const :tag "Include Functions" 3)))
225
226 (defvar js2-mode-dev-mode-p nil
227 "Non-nil if running in development mode. Normally nil.")
228
229 (defgroup js2-mode nil
230 "An improved JavaScript mode."
231 :group 'languages)
232
233 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
234 (numberp c-basic-offset))
235 c-basic-offset
236 4)
237 "Number of spaces to indent nested statements.
238 Similar to `c-basic-offset'."
239 :group 'js2-mode
240 :type 'integer)
241 (js2-mark-safe-local 'js2-basic-offset 'integerp)
242
243 (defcustom js2-bounce-indent-p nil
244 "Non-nil to have indent-line function choose among alternatives.
245 If nil, the indent-line function will indent to a predetermined column
246 based on heuristic guessing. If non-nil, then if the current line is
247 already indented to that predetermined column, indenting will choose
248 another likely column and indent to that spot. Repeated invocation of
249 the indent-line function will cycle among the computed alternatives.
250 See the function `js2-bounce-indent' for details. When it is non-nil,
251 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
252 :type 'boolean
253 :group 'js2-mode)
254
255 (defcustom js2-pretty-multiline-declarations t
256 "Non-nil to line up multiline declarations vertically:
257
258 var a = 10,
259 b = 20,
260 c = 30;
261
262 If the value is not `all', and the first assigned value in
263 declaration is a function/array/object literal spanning several
264 lines, it won't be indented additionally:
265
266 var o = { var bar = 2,
267 foo: 3 vs. o = {
268 }, foo: 3
269 bar = 2; };"
270 :group 'js2-mode
271 :type 'symbol)
272 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
273
274 (defcustom js2-indent-switch-body nil
275 "When nil, case labels are indented on the same level as the
276 containing switch statement. Otherwise, all lines inside
277 switch statement body are indented one additional level."
278 :type 'boolean
279 :group 'js2-mode)
280 (js2-mark-safe-local 'js2-indent-case-same-as-switch 'booleanp)
281
282 (defcustom js2-idle-timer-delay 0.2
283 "Delay in secs before re-parsing after user makes changes.
284 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
285 :type 'number
286 :group 'js2-mode)
287 (make-variable-buffer-local 'js2-idle-timer-delay)
288
289 (defcustom js2-dynamic-idle-timer-adjust 0
290 "Positive to adjust `js2-idle-timer-delay' based on file size.
291 The idea is that for short files, parsing is faster so we can be
292 more responsive to user edits without interfering with editing.
293 The buffer length in characters (typically bytes) is divided by
294 this value and used to multiply `js2-idle-timer-delay' for the
295 buffer. For example, a 21k file and 10k adjust yields 21k/10k
296 == 2, so js2-idle-timer-delay is multiplied by 2.
297 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
298 `js2-idle-timer-delay' is not dependent on the file size."
299 :type 'number
300 :group 'js2-mode)
301
302 (defcustom js2-concat-multiline-strings t
303 "When non-nil, `js2-line-break' in mid-string will make it a
304 string concatenation. When `eol', the '+' will be inserted at the
305 end of the line, otherwise, at the beginning of the next line."
306 :type '(choice (const t) (const eol) (const nil))
307 :group 'js2-mode)
308
309 (defcustom js2-mode-show-parse-errors t
310 "True to highlight parse errors."
311 :type 'boolean
312 :group 'js2-mode)
313
314 (defcustom js2-mode-show-strict-warnings t
315 "Non-nil to emit Ecma strict-mode warnings.
316 Some of the warnings can be individually disabled by other flags,
317 even if this flag is non-nil."
318 :type 'boolean
319 :group 'js2-mode)
320
321 (defcustom js2-strict-trailing-comma-warning t
322 "Non-nil to warn about trailing commas in array literals.
323 Ecma-262-5.1 allows them, but older versions of IE raise an error."
324 :type 'boolean
325 :group 'js2-mode)
326
327 (defcustom js2-strict-missing-semi-warning t
328 "Non-nil to warn about semicolon auto-insertion after statement.
329 Technically this is legal per Ecma-262, but some style guides disallow
330 depending on it."
331 :type 'boolean
332 :group 'js2-mode)
333
334 (defcustom js2-missing-semi-one-line-override nil
335 "Non-nil to permit missing semicolons in one-line functions.
336 In one-liner functions such as `function identity(x) {return x}'
337 people often omit the semicolon for a cleaner look. If you are
338 such a person, you can suppress the missing-semicolon warning
339 by setting this variable to t."
340 :type 'boolean
341 :group 'js2-mode)
342
343 (defcustom js2-strict-inconsistent-return-warning t
344 "Non-nil to warn about mixing returns with value-returns.
345 It's perfectly legal to have a `return' and a `return foo' in the
346 same function, but it's often an indicator of a bug, and it also
347 interferes with type inference (in systems that support it.)"
348 :type 'boolean
349 :group 'js2-mode)
350
351 (defcustom js2-strict-cond-assign-warning t
352 "Non-nil to warn about expressions like if (a = b).
353 This often should have been '==' instead of '='. If the warning
354 is enabled, you can suppress it on a per-expression basis by
355 parenthesizing the expression, e.g. if ((a = b)) ..."
356 :type 'boolean
357 :group 'js2-mode)
358
359 (defcustom js2-strict-var-redeclaration-warning t
360 "Non-nil to warn about redeclaring variables in a script or function."
361 :type 'boolean
362 :group 'js2-mode)
363
364 (defcustom js2-strict-var-hides-function-arg-warning t
365 "Non-nil to warn about a var decl hiding a function argument."
366 :type 'boolean
367 :group 'js2-mode)
368
369 (defcustom js2-skip-preprocessor-directives nil
370 "Non-nil to treat lines beginning with # as comments.
371 Useful for viewing Mozilla JavaScript source code."
372 :type 'boolean
373 :group 'js2-mode)
374
375 (defcustom js2-language-version 200
376 "Configures what JavaScript language version to recognize.
377 Currently versions 150, 160, 170, 180 and 200 are supported,
378 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
379 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
380 yield, and Array comprehensions, and 1.8 adds function closures."
381 :type 'integer
382 :group 'js2-mode)
383
384 (defcustom js2-allow-keywords-as-property-names t
385 "If non-nil, you can use JavaScript keywords as object property names.
386 Examples:
387
388 var foo = {int: 5, while: 6, continue: 7};
389 foo.return = 8;
390
391 Ecma-262 5.1 allows this syntax, but some engines still don't."
392 :type 'boolean
393 :group 'js2-mode)
394
395 (defcustom js2-instanceof-has-side-effects nil
396 "If non-nil, treats the instanceof operator as having side effects.
397 This is useful for xulrunner apps."
398 :type 'boolean
399 :group 'js2-mode)
400
401 (defcustom js2-move-point-on-right-click t
402 "Non-nil to move insertion point when you right-click.
403 This makes right-click context menu behavior a bit more intuitive,
404 since menu operations generally apply to the point. The exception
405 is if there is a region selection, in which case the point does -not-
406 move, so cut/copy/paste can work properly.
407
408 Note that IntelliJ moves the point, and Eclipse leaves it alone,
409 so this behavior is customizable."
410 :group 'js2-mode
411 :type 'boolean)
412
413 (defcustom js2-allow-rhino-new-expr-initializer t
414 "Non-nil to support a Rhino's experimental syntactic construct.
415
416 Rhino supports the ability to follow a `new' expression with an object
417 literal, which is used to set additional properties on the new object
418 after calling its constructor. Syntax:
419
420 new <expr> [ ( arglist ) ] [initializer]
421
422 Hence, this expression:
423
424 new Object {a: 1, b: 2}
425
426 results in an Object with properties a=1 and b=2. This syntax is
427 apparently not configurable in Rhino - it's currently always enabled,
428 as of Rhino version 1.7R2."
429 :type 'boolean
430 :group 'js2-mode)
431
432 (defcustom js2-allow-member-expr-as-function-name nil
433 "Non-nil to support experimental Rhino syntax for function names.
434
435 Rhino supports an experimental syntax configured via the Rhino Context
436 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
437
438 function <member-expr> ( [ arg-list ] ) { <body> }
439
440 Where member-expr is a non-parenthesized 'member expression', which
441 is anything at the grammar level of a new-expression or lower, meaning
442 any expression that does not involve infix or unary operators.
443
444 When <member-expr> is not a simple identifier, then it is syntactic
445 sugar for assigning the anonymous function to the <member-expr>. Hence,
446 this code:
447
448 function a.b().c[2] (x, y) { ... }
449
450 is rewritten as:
451
452 a.b().c[2] = function(x, y) {...}
453
454 which doesn't seem particularly useful, but Rhino permits it."
455 :type 'boolean
456 :group 'js2-mode)
457
458 ;; scanner variables
459
460 (defmacro js2-deflocal (name value &optional comment)
461 "Define a buffer-local variable NAME with VALUE and COMMENT."
462 `(progn
463 (defvar ,name ,value ,comment)
464 (make-variable-buffer-local ',name)))
465
466 (defvar js2-EOF_CHAR -1
467 "Represents end of stream. Distinct from js2-EOF token type.")
468
469 ;; I originally used symbols to represent tokens, but Rhino uses
470 ;; ints and then sets various flag bits in them, so ints it is.
471 ;; The upshot is that we need a `js2-' prefix in front of each name.
472 (defvar js2-ERROR -1)
473 (defvar js2-EOF 0)
474 (defvar js2-EOL 1)
475 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
476 (defvar js2-LEAVEWITH 3)
477 (defvar js2-RETURN 4)
478 (defvar js2-GOTO 5)
479 (defvar js2-IFEQ 6)
480 (defvar js2-IFNE 7)
481 (defvar js2-SETNAME 8)
482 (defvar js2-BITOR 9)
483 (defvar js2-BITXOR 10)
484 (defvar js2-BITAND 11)
485 (defvar js2-EQ 12)
486 (defvar js2-NE 13)
487 (defvar js2-LT 14)
488 (defvar js2-LE 15)
489 (defvar js2-GT 16)
490 (defvar js2-GE 17)
491 (defvar js2-LSH 18)
492 (defvar js2-RSH 19)
493 (defvar js2-URSH 20)
494 (defvar js2-ADD 21) ; infix plus
495 (defvar js2-SUB 22) ; infix minus
496 (defvar js2-MUL 23)
497 (defvar js2-DIV 24)
498 (defvar js2-MOD 25)
499 (defvar js2-NOT 26)
500 (defvar js2-BITNOT 27)
501 (defvar js2-POS 28) ; unary plus
502 (defvar js2-NEG 29) ; unary minus
503 (defvar js2-NEW 30)
504 (defvar js2-DELPROP 31)
505 (defvar js2-TYPEOF 32)
506 (defvar js2-GETPROP 33)
507 (defvar js2-GETPROPNOWARN 34)
508 (defvar js2-SETPROP 35)
509 (defvar js2-GETELEM 36)
510 (defvar js2-SETELEM 37)
511 (defvar js2-CALL 38)
512 (defvar js2-NAME 39) ; an identifier
513 (defvar js2-NUMBER 40)
514 (defvar js2-STRING 41)
515 (defvar js2-NULL 42)
516 (defvar js2-THIS 43)
517 (defvar js2-FALSE 44)
518 (defvar js2-TRUE 45)
519 (defvar js2-SHEQ 46) ; shallow equality (===)
520 (defvar js2-SHNE 47) ; shallow inequality (!==)
521 (defvar js2-REGEXP 48)
522 (defvar js2-BINDNAME 49)
523 (defvar js2-THROW 50)
524 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
525 (defvar js2-IN 52)
526 (defvar js2-INSTANCEOF 53)
527 (defvar js2-LOCAL_LOAD 54)
528 (defvar js2-GETVAR 55)
529 (defvar js2-SETVAR 56)
530 (defvar js2-CATCH_SCOPE 57)
531 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
532 (defvar js2-ENUM_INIT_VALUES 59)
533 (defvar js2-ENUM_INIT_ARRAY 60)
534 (defvar js2-ENUM_NEXT 61)
535 (defvar js2-ENUM_ID 62)
536 (defvar js2-THISFN 63)
537 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
538 (defvar js2-ARRAYLIT 65) ; array literal
539 (defvar js2-OBJECTLIT 66) ; object literal
540 (defvar js2-GET_REF 67) ; *reference
541 (defvar js2-SET_REF 68) ; *reference = something
542 (defvar js2-DEL_REF 69) ; delete reference
543 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
544 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
545 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
546
547 ;; XML support
548 (defvar js2-DEFAULTNAMESPACE 73)
549 (defvar js2-ESCXMLATTR 74)
550 (defvar js2-ESCXMLTEXT 75)
551 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
552 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
553 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
554 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
555
556 (defvar js2-first-bytecode js2-ENTERWITH)
557 (defvar js2-last-bytecode js2-REF_NS_NAME)
558
559 (defvar js2-TRY 80)
560 (defvar js2-SEMI 81) ; semicolon
561 (defvar js2-LB 82) ; left and right brackets
562 (defvar js2-RB 83)
563 (defvar js2-LC 84) ; left and right curly-braces
564 (defvar js2-RC 85)
565 (defvar js2-LP 86) ; left and right parens
566 (defvar js2-RP 87)
567 (defvar js2-COMMA 88) ; comma operator
568
569 (defvar js2-ASSIGN 89) ; simple assignment (=)
570 (defvar js2-ASSIGN_BITOR 90) ; |=
571 (defvar js2-ASSIGN_BITXOR 91) ; ^=
572 (defvar js2-ASSIGN_BITAND 92) ; &=
573 (defvar js2-ASSIGN_LSH 93) ; <<=
574 (defvar js2-ASSIGN_RSH 94) ; >>=
575 (defvar js2-ASSIGN_URSH 95) ; >>>=
576 (defvar js2-ASSIGN_ADD 96) ; +=
577 (defvar js2-ASSIGN_SUB 97) ; -=
578 (defvar js2-ASSIGN_MUL 98) ; *=
579 (defvar js2-ASSIGN_DIV 99) ; /=
580 (defvar js2-ASSIGN_MOD 100) ; %=
581
582 (defvar js2-first-assign js2-ASSIGN)
583 (defvar js2-last-assign js2-ASSIGN_MOD)
584
585 (defvar js2-HOOK 101) ; conditional (?:)
586 (defvar js2-COLON 102)
587 (defvar js2-OR 103) ; logical or (||)
588 (defvar js2-AND 104) ; logical and (&&)
589 (defvar js2-INC 105) ; increment/decrement (++ --)
590 (defvar js2-DEC 106)
591 (defvar js2-DOT 107) ; member operator (.)
592 (defvar js2-FUNCTION 108) ; function keyword
593 (defvar js2-EXPORT 109) ; export keyword
594 (defvar js2-IMPORT 110) ; import keyword
595 (defvar js2-IF 111) ; if keyword
596 (defvar js2-ELSE 112) ; else keyword
597 (defvar js2-SWITCH 113) ; switch keyword
598 (defvar js2-CASE 114) ; case keyword
599 (defvar js2-DEFAULT 115) ; default keyword
600 (defvar js2-WHILE 116) ; while keyword
601 (defvar js2-DO 117) ; do keyword
602 (defvar js2-FOR 118) ; for keyword
603 (defvar js2-BREAK 119) ; break keyword
604 (defvar js2-CONTINUE 120) ; continue keyword
605 (defvar js2-VAR 121) ; var keyword
606 (defvar js2-WITH 122) ; with keyword
607 (defvar js2-CATCH 123) ; catch keyword
608 (defvar js2-FINALLY 124) ; finally keyword
609 (defvar js2-VOID 125) ; void keyword
610 (defvar js2-RESERVED 126) ; reserved keywords
611
612 (defvar js2-EMPTY 127)
613
614 ;; Types used for the parse tree - never returned by scanner.
615
616 (defvar js2-BLOCK 128) ; statement block
617 (defvar js2-LABEL 129) ; label
618 (defvar js2-TARGET 130)
619 (defvar js2-LOOP 131)
620 (defvar js2-EXPR_VOID 132) ; expression statement in functions
621 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
622 (defvar js2-JSR 134)
623 (defvar js2-SCRIPT 135) ; top-level node for entire script
624 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
625 (defvar js2-USE_STACK 137)
626 (defvar js2-SETPROP_OP 138) ; x.y op= something
627 (defvar js2-SETELEM_OP 139) ; x[y] op= something
628 (defvar js2-LOCAL_BLOCK 140)
629 (defvar js2-SET_REF_OP 141) ; *reference op= something
630
631 ;; For XML support:
632 (defvar js2-DOTDOT 142) ; member operator (..)
633 (defvar js2-COLONCOLON 143) ; namespace::name
634 (defvar js2-XML 144) ; XML type
635 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
636 (defvar js2-XMLATTR 146) ; @
637 (defvar js2-XMLEND 147)
638
639 ;; Optimizer-only tokens
640 (defvar js2-TO_OBJECT 148)
641 (defvar js2-TO_DOUBLE 149)
642
643 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
644 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
645 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
646 (defvar js2-CONST 153)
647 (defvar js2-SETCONST 154)
648 (defvar js2-SETCONSTVAR 155)
649 (defvar js2-ARRAYCOMP 156)
650 (defvar js2-LETEXPR 157)
651 (defvar js2-WITHEXPR 158)
652 (defvar js2-DEBUGGER 159)
653
654 (defvar js2-COMMENT 160)
655 (defvar js2-TRIPLEDOT 161) ; for rest parameter
656 (defvar js2-ARROW 162) ; function arrow (=>)
657
658 (defconst js2-num-tokens (1+ js2-ARROW))
659
660 (defconst js2-debug-print-trees nil)
661
662 ;; Rhino accepts any string or stream as input. Emacs character
663 ;; processing works best in buffers, so we'll assume the input is a
664 ;; buffer. JavaScript strings can be copied into temp buffers before
665 ;; scanning them.
666
667 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
668 ;; They're the Emacs equivalent of instance variables, more or less.
669
670 (js2-deflocal js2-ts-dirty-line nil
671 "Token stream buffer-local variable.
672 Indicates stuff other than whitespace since start of line.")
673
674 (js2-deflocal js2-ts-hit-eof nil
675 "Token stream buffer-local variable.")
676
677 ;; FIXME: Unused.
678 (js2-deflocal js2-ts-line-start 0
679 "Token stream buffer-local variable.")
680
681 (js2-deflocal js2-ts-lineno 1
682 "Token stream buffer-local variable.")
683
684 ;; FIXME: Unused.
685 (js2-deflocal js2-ts-line-end-char -1
686 "Token stream buffer-local variable.")
687
688 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
689 "Token stream buffer-local variable.
690 Current scan position.")
691
692 ;; FIXME: Unused.
693 (js2-deflocal js2-ts-is-xml-attribute nil
694 "Token stream buffer-local variable.")
695
696 (js2-deflocal js2-ts-xml-is-tag-content nil
697 "Token stream buffer-local variable.")
698
699 (js2-deflocal js2-ts-xml-open-tags-count 0
700 "Token stream buffer-local variable.")
701
702 (js2-deflocal js2-ts-string-buffer nil
703 "Token stream buffer-local variable.
704 List of chars built up while scanning various tokens.")
705
706 (defstruct (js2-token
707 (:constructor nil)
708 (:constructor make-js2-token (beg)))
709 "Value returned from the token stream."
710 (type js2-EOF)
711 (beg 1)
712 (end -1)
713 (string "")
714 number
715 regexp-flags
716 comment-type
717 follows-eol-p)
718
719 (defstruct (js2-ts-state
720 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
721 (cursor js2-ts-cursor)
722 (tokens (copy-sequence js2-ti-tokens))
723 (tokens-cursor js2-ti-tokens-cursor)
724 (lookahead js2-ti-lookahead))))
725 lineno
726 cursor
727 tokens
728 tokens-cursor
729 lookahead)
730
731 ;;; Parser variables
732
733 (js2-deflocal js2-parsed-errors nil
734 "List of errors produced during scanning/parsing.")
735
736 (js2-deflocal js2-parsed-warnings nil
737 "List of warnings produced during scanning/parsing.")
738
739 (js2-deflocal js2-recover-from-parse-errors t
740 "Non-nil to continue parsing after a syntax error.
741
742 In recovery mode, the AST will be built in full, and any error
743 nodes will be flagged with appropriate error information. If
744 this flag is nil, a syntax error will result in an error being
745 signaled.
746
747 The variable is automatically buffer-local, because different
748 modes that use the parser will need different settings.")
749
750 (js2-deflocal js2-parse-hook nil
751 "List of callbacks for receiving parsing progress.")
752
753 (defvar js2-parse-finished-hook nil
754 "List of callbacks to notify when parsing finishes.
755 Not called if parsing was interrupted.")
756
757 (js2-deflocal js2-is-eval-code nil
758 "True if we're evaluating code in a string.
759 If non-nil, the tokenizer will record the token text, and the AST nodes
760 will record their source text. Off by default for IDE modes, since the
761 text is available in the buffer.")
762
763 (defvar js2-parse-ide-mode t
764 "Non-nil if the parser is being used for `js2-mode'.
765 If non-nil, the parser will set text properties for fontification
766 and the syntax table. The value should be nil when using the
767 parser as a frontend to an interpreter or byte compiler.")
768
769 ;;; Parser instance variables (buffer-local vars for js2-parse)
770
771 (defconst js2-ti-after-eol (lsh 1 16)
772 "Flag: first token of the source line.")
773
774 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
775
776 (js2-deflocal js2-compiler-generate-debug-info t)
777 (js2-deflocal js2-compiler-use-dynamic-scope nil)
778 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
779 (js2-deflocal js2-compiler-xml-available t)
780 (js2-deflocal js2-compiler-optimization-level 0)
781 (js2-deflocal js2-compiler-generating-source t)
782 (js2-deflocal js2-compiler-strict-mode nil)
783 (js2-deflocal js2-compiler-report-warning-as-error nil)
784 (js2-deflocal js2-compiler-generate-observer-count nil)
785 (js2-deflocal js2-compiler-activation-names nil)
786
787 ;; SKIP: sourceURI
788
789 ;; There's a compileFunction method in Context.java - may need it.
790 (js2-deflocal js2-called-by-compile-function nil
791 "True if `js2-parse' was called by `js2-compile-function'.
792 Will only be used when we finish implementing the interpreter.")
793
794 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
795
796 ;; SKIP: node factory - we're going to just call functions directly,
797 ;; and eventually go to a unified AST format.
798
799 (js2-deflocal js2-nesting-of-function 0)
800
801 (js2-deflocal js2-recorded-identifiers nil
802 "Tracks identifiers found during parsing.")
803
804 (js2-deflocal js2-is-in-destructuring nil
805 "True while parsing destructuring expression.")
806
807 (defcustom js2-global-externs nil
808 "A list of any extern names you'd like to consider always declared.
809 This list is global and is used by all `js2-mode' files.
810 You can create buffer-local externs list using `js2-additional-externs'.
811
812 There is also a buffer-local variable `js2-default-externs',
813 which is initialized by default to include the Ecma-262 externs
814 and the standard browser externs. The three lists are all
815 checked during highlighting."
816 :type 'list
817 :group 'js2-mode)
818
819 (js2-deflocal js2-default-externs nil
820 "Default external declarations.
821
822 These are currently only used for highlighting undeclared variables,
823 which only worries about top-level (unqualified) references.
824 As js2-mode's processing improves, we will flesh out this list.
825
826 The initial value is set to `js2-ecma-262-externs', unless some
827 of the `js2-include-?-externs' variables are set to t, in which
828 case the browser, Rhino and/or Node.js externs are also included.
829
830 See `js2-additional-externs' for more information.")
831
832 (defcustom js2-include-browser-externs t
833 "Non-nil to include browser externs in the master externs list.
834 If you work on JavaScript files that are not intended for browsers,
835 such as Mozilla Rhino server-side JavaScript, set this to nil.
836 See `js2-additional-externs' for more information about externs."
837 :type 'boolean
838 :group 'js2-mode)
839
840 (defcustom js2-include-rhino-externs nil
841 "Non-nil to include Mozilla Rhino externs in the master externs list.
842 See `js2-additional-externs' for more information about externs."
843 :type 'boolean
844 :group 'js2-mode)
845
846 (defcustom js2-include-node-externs nil
847 "Non-nil to include Node.js externs in the master externs list.
848 See `js2-additional-externs' for more information about externs."
849 :type 'boolean
850 :group 'js2-mode)
851
852 (js2-deflocal js2-additional-externs nil
853 "A buffer-local list of additional external declarations.
854 It is used to decide whether variables are considered undeclared
855 for purposes of highlighting.
856
857 Each entry is a Lisp string. The string should be the fully qualified
858 name of an external entity. All externs should be added to this list,
859 so that as js2-mode's processing improves it can take advantage of them.
860
861 You may want to declare your externs in three ways.
862 First, you can add externs that are valid for all your JavaScript files.
863 You should probably do this by adding them to `js2-global-externs', which
864 is a global list used for all js2-mode files.
865
866 Next, you can add a function to `js2-init-hook' that adds additional
867 externs appropriate for the specific file, perhaps based on its path.
868 These should go in `js2-additional-externs', which is buffer-local.
869
870 Third, you can use JSLint's global declaration, as long as
871 `js2-include-jslint-globals' is non-nil, which see.
872
873 Finally, you can add a function to `js2-post-parse-callbacks',
874 which is called after parsing completes, and `js2-mode-ast' is bound to
875 the root of the parse tree. At this stage you can set up an AST
876 node visitor using `js2-visit-ast' and examine the parse tree
877 for specific import patterns that may imply the existence of
878 other externs, possibly tied to your build system. These should also
879 be added to `js2-additional-externs'.
880
881 Your post-parse callback may of course also use the simpler and
882 faster (but perhaps less robust) approach of simply scanning the
883 buffer text for your imports, using regular expressions.")
884
885 ;; SKIP: decompiler
886 ;; SKIP: encoded-source
887
888 ;;; The following variables are per-function and should be saved/restored
889 ;;; during function parsing...
890
891 (js2-deflocal js2-current-script-or-fn nil)
892 (js2-deflocal js2-current-scope nil)
893 (js2-deflocal js2-nesting-of-with 0)
894 (js2-deflocal js2-label-set nil
895 "An alist mapping label names to nodes.")
896
897 (js2-deflocal js2-loop-set nil)
898 (js2-deflocal js2-loop-and-switch-set nil)
899 (js2-deflocal js2-has-return-value nil)
900 (js2-deflocal js2-end-flags 0)
901
902 ;;; ...end of per function variables
903
904 ;; These flags enumerate the possible ways a statement/function can
905 ;; terminate. These flags are used by endCheck() and by the Parser to
906 ;; detect inconsistent return usage.
907 ;;
908 ;; END_UNREACHED is reserved for code paths that are assumed to always be
909 ;; able to execute (example: throw, continue)
910 ;;
911 ;; END_DROPS_OFF indicates if the statement can transfer control to the
912 ;; next one. Statement such as return dont. A compound statement may have
913 ;; some branch that drops off control to the next statement.
914 ;;
915 ;; END_RETURNS indicates that the statement can return (without arguments)
916 ;; END_RETURNS_VALUE indicates that the statement can return a value.
917 ;;
918 ;; A compound statement such as
919 ;; if (condition) {
920 ;; return value;
921 ;; }
922 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
923
924 (defconst js2-end-unreached #x0)
925 (defconst js2-end-drops-off #x1)
926 (defconst js2-end-returns #x2)
927 (defconst js2-end-returns-value #x4)
928
929 ;; Rhino awkwardly passes a statementLabel parameter to the
930 ;; statementHelper() function, the main statement parser, which
931 ;; is then used by quite a few of the sub-parsers. We just make
932 ;; it a buffer-local variable and make sure it's cleaned up properly.
933 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
934
935 ;; Similarly, Rhino passes an inForInit boolean through about half
936 ;; the expression parsers. We use a dynamically-scoped variable,
937 ;; which makes it easier to funcall the parsers individually without
938 ;; worrying about whether they take the parameter or not.
939 (js2-deflocal js2-in-for-init nil)
940 (js2-deflocal js2-temp-name-counter 0)
941 (js2-deflocal js2-parse-stmt-count 0)
942
943 (defsubst js2-get-next-temp-name ()
944 (format "$%d" (incf js2-temp-name-counter)))
945
946 (defvar js2-parse-interruptable-p t
947 "Set this to nil to force parse to continue until finished.
948 This will mostly be useful for interpreters.")
949
950 (defvar js2-statements-per-pause 50
951 "Pause after this many statements to check for user input.
952 If user input is pending, stop the parse and discard the tree.
953 This makes for a smoother user experience for large files.
954 You may have to wait a second or two before the highlighting
955 and error-reporting appear, but you can always type ahead if
956 you wish. This appears to be more or less how Eclipse, IntelliJ
957 and other editors work.")
958
959 (js2-deflocal js2-record-comments t
960 "Instructs the scanner to record comments in `js2-scanned-comments'.")
961
962 (js2-deflocal js2-scanned-comments nil
963 "List of all comments from the current parse.")
964
965 (defcustom js2-mode-indent-inhibit-undo nil
966 "Non-nil to disable collection of Undo information when indenting lines.
967 Some users have requested this behavior. It's nil by default because
968 other Emacs modes don't work this way."
969 :type 'boolean
970 :group 'js2-mode)
971
972 (defcustom js2-mode-indent-ignore-first-tab nil
973 "If non-nil, ignore first TAB keypress if we look indented properly.
974 It's fairly common for users to navigate to an already-indented line
975 and press TAB for reassurance that it's been indented. For this class
976 of users, we want the first TAB press on a line to be ignored if the
977 line is already indented to one of the precomputed alternatives.
978
979 This behavior is only partly implemented. If you TAB-indent a line,
980 navigate to another line, and then navigate back, it fails to clear
981 the last-indented variable, so it thinks you've already hit TAB once,
982 and performs the indent. A full solution would involve getting on the
983 point-motion hooks for the entire buffer. If we come across another
984 use cases that requires watching point motion, I'll consider doing it.
985
986 If you set this variable to nil, then the TAB key will always change
987 the indentation of the current line, if more than one alternative
988 indentation spot exists."
989 :type 'boolean
990 :group 'js2-mode)
991
992 (defvar js2-indent-hook nil
993 "A hook for user-defined indentation rules.
994
995 Functions on this hook should expect two arguments: (LIST INDEX)
996 The LIST argument is the list of computed indentation points for
997 the current line. INDEX is the list index of the indentation point
998 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
999 indent function is not going to change the current line indentation.
1000
1001 If a hook function on this list returns a non-nil value, then
1002 `js2-bounce-indent' assumes the hook function has performed its own
1003 indentation, and will do nothing. If all hook functions on the list
1004 return nil, then `js2-bounce-indent' will use its computed indentation
1005 and reindent the line.
1006
1007 When hook functions on this hook list are called, the variable
1008 `js2-mode-ast' may or may not be set, depending on whether the
1009 parse tree is available. If the variable is nil, you can pass a
1010 callback to `js2-mode-wait-for-parse', and your callback will be
1011 called after the new parse tree is built. This can take some time
1012 in large files.")
1013
1014 (defface js2-warning
1015 `((((class color) (background light))
1016 (:underline "orange"))
1017 (((class color) (background dark))
1018 (:underline "orange"))
1019 (t (:underline t)))
1020 "Face for JavaScript warnings."
1021 :group 'js2-mode)
1022
1023 (defface js2-error
1024 `((((class color) (background light))
1025 (:foreground "red"))
1026 (((class color) (background dark))
1027 (:foreground "red"))
1028 (t (:foreground "red")))
1029 "Face for JavaScript errors."
1030 :group 'js2-mode)
1031
1032 (defface js2-jsdoc-tag
1033 '((t :foreground "SlateGray"))
1034 "Face used to highlight @whatever tags in jsdoc comments."
1035 :group 'js2-mode)
1036
1037 (defface js2-jsdoc-type
1038 '((t :foreground "SteelBlue"))
1039 "Face used to highlight {FooBar} types in jsdoc comments."
1040 :group 'js2-mode)
1041
1042 (defface js2-jsdoc-value
1043 '((t :foreground "PeachPuff3"))
1044 "Face used to highlight tag values in jsdoc comments."
1045 :group 'js2-mode)
1046
1047 (defface js2-function-param
1048 '((t :foreground "SeaGreen"))
1049 "Face used to highlight function parameters in javascript."
1050 :group 'js2-mode)
1051
1052 (defface js2-function-call
1053 '((t :inherit default))
1054 "Face used to highlight function name in calls."
1055 :group 'js2-mode)
1056
1057 (defface js2-instance-member
1058 '((t :foreground "DarkOrchid"))
1059 "Face used to highlight instance variables in javascript.
1060 Not currently used."
1061 :group 'js2-mode)
1062
1063 (defface js2-private-member
1064 '((t :foreground "PeachPuff3"))
1065 "Face used to highlight calls to private methods in javascript.
1066 Not currently used."
1067 :group 'js2-mode)
1068
1069 (defface js2-private-function-call
1070 '((t :foreground "goldenrod"))
1071 "Face used to highlight calls to private functions in javascript.
1072 Not currently used."
1073 :group 'js2-mode)
1074
1075 (defface js2-jsdoc-html-tag-name
1076 '((((class color) (min-colors 88) (background light))
1077 (:foreground "rosybrown"))
1078 (((class color) (min-colors 8) (background dark))
1079 (:foreground "yellow"))
1080 (((class color) (min-colors 8) (background light))
1081 (:foreground "magenta")))
1082 "Face used to highlight jsdoc html tag names"
1083 :group 'js2-mode)
1084
1085 (defface js2-jsdoc-html-tag-delimiter
1086 '((((class color) (min-colors 88) (background light))
1087 (:foreground "dark khaki"))
1088 (((class color) (min-colors 8) (background dark))
1089 (:foreground "green"))
1090 (((class color) (min-colors 8) (background light))
1091 (:foreground "green")))
1092 "Face used to highlight brackets in jsdoc html tags."
1093 :group 'js2-mode)
1094
1095 (defface js2-external-variable
1096 '((t :foreground "orange"))
1097 "Face used to highlight undeclared variable identifiers.")
1098
1099 (defcustom js2-init-hook nil
1100 "List of functions to be called after `js2-mode' or
1101 `js2-minor-mode' has initialized all variables, before parsing
1102 the buffer for the first time."
1103 :type 'hook
1104 :group 'js2-mode
1105 :version "20130608")
1106
1107 (defcustom js2-post-parse-callbacks nil
1108 "List of callback functions invoked after parsing finishes.
1109 Currently, the main use for this function is to add synthetic
1110 declarations to `js2-recorded-identifiers', which see."
1111 :type 'hook
1112 :group 'js2-mode)
1113
1114 (defcustom js2-build-imenu-callbacks nil
1115 "List of functions called during Imenu index generation.
1116 It's a good place to add additional entries to it, using
1117 `js2-record-imenu-entry'."
1118 :type 'hook
1119 :group 'js2-mode)
1120
1121 (defcustom js2-highlight-external-variables t
1122 "Non-nil to highlight undeclared variable identifiers.
1123 An undeclared variable is any variable not declared with var or let
1124 in the current scope or any lexically enclosing scope. If you use
1125 such a variable, then you are either expecting it to originate from
1126 another file, or you've got a potential bug."
1127 :type 'boolean
1128 :group 'js2-mode)
1129
1130 (defcustom js2-include-jslint-globals t
1131 "Non-nil to include the identifiers from JSLint global
1132 declaration (see http://www.jslint.com/lint.html#global) in the
1133 buffer-local externs list. See `js2-additional-externs' for more
1134 information."
1135 :type 'boolean
1136 :group 'js2-mode)
1137
1138 (defvar js2-mode-map
1139 (let ((map (make-sparse-keymap)))
1140 (define-key map [mouse-1] #'js2-mode-show-node)
1141 (define-key map (kbd "M-j") #'js2-line-break)
1142 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1143 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1144 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1145 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1146 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1147 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1148 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1149 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1150 (when js2-bounce-indent-p
1151 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1152
1153 (define-key map [menu-bar javascript]
1154 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1155
1156 (define-key map [menu-bar javascript customize-js2-mode]
1157 '(menu-item "Customize js2-mode" js2-mode-customize
1158 :help "Customize the behavior of this mode"))
1159
1160 (define-key map [menu-bar javascript js2-force-refresh]
1161 '(menu-item "Force buffer refresh" js2-mode-reset
1162 :help "Re-parse the buffer from scratch"))
1163
1164 (define-key map [menu-bar javascript separator-2]
1165 '("--"))
1166
1167 (define-key map [menu-bar javascript next-error]
1168 '(menu-item "Next warning or error" next-error
1169 :enabled (and js2-mode-ast
1170 (or (js2-ast-root-errors js2-mode-ast)
1171 (js2-ast-root-warnings js2-mode-ast)))
1172 :help "Move to next warning or error"))
1173
1174 (define-key map [menu-bar javascript display-errors]
1175 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1176 :visible (not js2-mode-show-parse-errors)
1177 :help "Turn on display of warnings and errors"))
1178
1179 (define-key map [menu-bar javascript hide-errors]
1180 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1181 :visible js2-mode-show-parse-errors
1182 :help "Turn off display of warnings and errors"))
1183
1184 (define-key map [menu-bar javascript separator-1]
1185 '("--"))
1186
1187 (define-key map [menu-bar javascript js2-toggle-function]
1188 '(menu-item "Show/collapse element" js2-mode-toggle-element
1189 :help "Hide or show function body or comment"))
1190
1191 (define-key map [menu-bar javascript show-comments]
1192 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1193 :visible js2-mode-comments-hidden
1194 :help "Expand all hidden block comments"))
1195
1196 (define-key map [menu-bar javascript hide-comments]
1197 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1198 :visible (not js2-mode-comments-hidden)
1199 :help "Show block comments as /*...*/"))
1200
1201 (define-key map [menu-bar javascript show-all-functions]
1202 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1203 :visible js2-mode-functions-hidden
1204 :help "Expand all hidden function bodies"))
1205
1206 (define-key map [menu-bar javascript hide-all-functions]
1207 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1208 :visible (not js2-mode-functions-hidden)
1209 :help "Show {...} for all top-level function bodies"))
1210
1211 map)
1212 "Keymap used in `js2-mode' buffers.")
1213
1214 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1215
1216 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1217 "Matches a //-comment line. Must be first non-whitespace on line.
1218 First match-group is the leading whitespace.")
1219
1220 (defvar js2-mode-hook nil)
1221
1222 (js2-deflocal js2-mode-ast nil "Private variable.")
1223 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1224 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1225 (js2-deflocal js2-mode-parsing nil "Private variable.")
1226 (js2-deflocal js2-mode-node-overlay nil)
1227
1228 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1229 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1230
1231 (js2-deflocal js2-mode-fontifications nil "Private variable")
1232 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1233 (js2-deflocal js2-imenu-recorder nil "Private variable")
1234 (js2-deflocal js2-imenu-function-map nil "Private variable")
1235
1236 (defvar js2-paragraph-start
1237 "\\(@[[:alpha:]]+\\>\\|$\\)")
1238
1239 ;; Note that we also set a 'c-in-sws text property in html comments,
1240 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1241 (defvar js2-syntactic-ws-start
1242 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1243
1244 (defvar js2-syntactic-ws-end
1245 "\\s \\|[\n\r/]\\|\\s!")
1246
1247 (defvar js2-syntactic-eol
1248 (concat "\\s *\\(/\\*[^*\n\r]*"
1249 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1250 "\\*+/\\s *\\)*"
1251 "\\(//\\|/\\*[^*\n\r]*"
1252 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1253 "\\|\\\\$\\|$\\)")
1254 "Copied from `java-mode'. Needed for some cc-engine functions.")
1255
1256 (defvar js2-comment-prefix-regexp
1257 "//+\\|\\**")
1258
1259 (defvar js2-comment-start-skip
1260 "\\(//+\\|/\\*+\\)\\s *")
1261
1262 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1263 "Non-nil to emit status messages during parsing.")
1264
1265 (defvar js2-mode-functions-hidden nil "Private variable.")
1266 (defvar js2-mode-comments-hidden nil "Private variable.")
1267
1268 (defvar js2-mode-syntax-table
1269 (let ((table (make-syntax-table)))
1270 (c-populate-syntax-table table)
1271 table)
1272 "Syntax table used in `js2-mode' buffers.")
1273
1274 (defvar js2-mode-abbrev-table nil
1275 "Abbrev table in use in `js2-mode' buffers.")
1276 (define-abbrev-table 'js2-mode-abbrev-table ())
1277
1278 (defvar js2-mode-pending-parse-callbacks nil
1279 "List of functions waiting to be notified that parse is finished.")
1280
1281 (defvar js2-mode-last-indented-line -1)
1282
1283 ;;; Localizable error and warning messages
1284
1285 ;; Messages are copied from Rhino's Messages.properties.
1286 ;; Many of the Java-specific messages have been elided.
1287 ;; Add any js2-specific ones at the end, so we can keep
1288 ;; this file synced with changes to Rhino's.
1289
1290 (defvar js2-message-table
1291 (make-hash-table :test 'equal :size 250)
1292 "Contains localized messages for `js2-mode'.")
1293
1294 ;; TODO(stevey): construct this table at compile-time.
1295 (defmacro js2-msg (key &rest strings)
1296 `(puthash ,key (concat ,@strings)
1297 js2-message-table))
1298
1299 (defun js2-get-msg (msg-key)
1300 "Look up a localized message.
1301 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1302 the correct number of ARGS must be provided."
1303 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1304 (args (if (listp msg-key) (cdr msg-key)))
1305 (msg (gethash key js2-message-table)))
1306 (if msg
1307 (apply #'format msg args)
1308 key))) ; default to showing the key
1309
1310 (js2-msg "msg.dup.parms"
1311 "Duplicate parameter name '%s'.")
1312
1313 (js2-msg "msg.too.big.jump"
1314 "Program too complex: jump offset too big.")
1315
1316 (js2-msg "msg.too.big.index"
1317 "Program too complex: internal index exceeds 64K limit.")
1318
1319 (js2-msg "msg.while.compiling.fn"
1320 "Encountered code generation error while compiling function '%s': %s")
1321
1322 (js2-msg "msg.while.compiling.script"
1323 "Encountered code generation error while compiling script: %s")
1324
1325 ;; Context
1326 (js2-msg "msg.ctor.not.found"
1327 "Constructor for '%s' not found.")
1328
1329 (js2-msg "msg.not.ctor"
1330 "'%s' is not a constructor.")
1331
1332 ;; FunctionObject
1333 (js2-msg "msg.varargs.ctor"
1334 "Method or constructor '%s' must be static "
1335 "with the signature (Context cx, Object[] args, "
1336 "Function ctorObj, boolean inNewExpr) "
1337 "to define a variable arguments constructor.")
1338
1339 (js2-msg "msg.varargs.fun"
1340 "Method '%s' must be static with the signature "
1341 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1342 "to define a variable arguments function.")
1343
1344 (js2-msg "msg.incompat.call"
1345 "Method '%s' called on incompatible object.")
1346
1347 (js2-msg "msg.bad.parms"
1348 "Unsupported parameter type '%s' in method '%s'.")
1349
1350 (js2-msg "msg.bad.method.return"
1351 "Unsupported return type '%s' in method '%s'.")
1352
1353 (js2-msg "msg.bad.ctor.return"
1354 "Construction of objects of type '%s' is not supported.")
1355
1356 (js2-msg "msg.no.overload"
1357 "Method '%s' occurs multiple times in class '%s'.")
1358
1359 (js2-msg "msg.method.not.found"
1360 "Method '%s' not found in '%s'.")
1361
1362 ;; IRFactory
1363
1364 (js2-msg "msg.bad.for.in.lhs"
1365 "Invalid left-hand side of for..in loop.")
1366
1367 (js2-msg "msg.mult.index"
1368 "Only one variable allowed in for..in loop.")
1369
1370 (js2-msg "msg.bad.for.in.destruct"
1371 "Left hand side of for..in loop must be an array of "
1372 "length 2 to accept key/value pair.")
1373
1374 (js2-msg "msg.cant.convert"
1375 "Can't convert to type '%s'.")
1376
1377 (js2-msg "msg.bad.assign.left"
1378 "Invalid assignment left-hand side.")
1379
1380 (js2-msg "msg.bad.decr"
1381 "Invalid decerement operand.")
1382
1383 (js2-msg "msg.bad.incr"
1384 "Invalid increment operand.")
1385
1386 (js2-msg "msg.bad.yield"
1387 "yield must be in a function.")
1388
1389 (js2-msg "msg.yield.parenthesized"
1390 "yield expression must be parenthesized.")
1391
1392 ;; NativeGlobal
1393 (js2-msg "msg.cant.call.indirect"
1394 "Function '%s' must be called directly, and not by way of a "
1395 "function of another name.")
1396
1397 (js2-msg "msg.eval.nonstring"
1398 "Calling eval() with anything other than a primitive "
1399 "string value will simply return the value. "
1400 "Is this what you intended?")
1401
1402 (js2-msg "msg.eval.nonstring.strict"
1403 "Calling eval() with anything other than a primitive "
1404 "string value is not allowed in strict mode.")
1405
1406 (js2-msg "msg.bad.destruct.op"
1407 "Invalid destructuring assignment operator")
1408
1409 ;; NativeCall
1410 (js2-msg "msg.only.from.new"
1411 "'%s' may only be invoked from a `new' expression.")
1412
1413 (js2-msg "msg.deprec.ctor"
1414 "The '%s' constructor is deprecated.")
1415
1416 ;; NativeFunction
1417 (js2-msg "msg.no.function.ref.found"
1418 "no source found to decompile function reference %s")
1419
1420 (js2-msg "msg.arg.isnt.array"
1421 "second argument to Function.prototype.apply must be an array")
1422
1423 ;; NativeGlobal
1424 (js2-msg "msg.bad.esc.mask"
1425 "invalid string escape mask")
1426
1427 ;; NativeRegExp
1428 (js2-msg "msg.bad.quant"
1429 "Invalid quantifier %s")
1430
1431 (js2-msg "msg.overlarge.backref"
1432 "Overly large back reference %s")
1433
1434 (js2-msg "msg.overlarge.min"
1435 "Overly large minimum %s")
1436
1437 (js2-msg "msg.overlarge.max"
1438 "Overly large maximum %s")
1439
1440 (js2-msg "msg.zero.quant"
1441 "Zero quantifier %s")
1442
1443 (js2-msg "msg.max.lt.min"
1444 "Maximum %s less than minimum")
1445
1446 (js2-msg "msg.unterm.quant"
1447 "Unterminated quantifier %s")
1448
1449 (js2-msg "msg.unterm.paren"
1450 "Unterminated parenthetical %s")
1451
1452 (js2-msg "msg.unterm.class"
1453 "Unterminated character class %s")
1454
1455 (js2-msg "msg.bad.range"
1456 "Invalid range in character class.")
1457
1458 (js2-msg "msg.trail.backslash"
1459 "Trailing \\ in regular expression.")
1460
1461 (js2-msg "msg.re.unmatched.right.paren"
1462 "unmatched ) in regular expression.")
1463
1464 (js2-msg "msg.no.regexp"
1465 "Regular expressions are not available.")
1466
1467 (js2-msg "msg.bad.backref"
1468 "back-reference exceeds number of capturing parentheses.")
1469
1470 (js2-msg "msg.bad.regexp.compile"
1471 "Only one argument may be specified if the first "
1472 "argument to RegExp.prototype.compile is a RegExp object.")
1473
1474 ;; Parser
1475 (js2-msg "msg.got.syntax.errors"
1476 "Compilation produced %s syntax errors.")
1477
1478 (js2-msg "msg.var.redecl"
1479 "TypeError: redeclaration of var %s.")
1480
1481 (js2-msg "msg.const.redecl"
1482 "TypeError: redeclaration of const %s.")
1483
1484 (js2-msg "msg.let.redecl"
1485 "TypeError: redeclaration of variable %s.")
1486
1487 (js2-msg "msg.parm.redecl"
1488 "TypeError: redeclaration of formal parameter %s.")
1489
1490 (js2-msg "msg.fn.redecl"
1491 "TypeError: redeclaration of function %s.")
1492
1493 (js2-msg "msg.let.decl.not.in.block"
1494 "SyntaxError: let declaration not directly within block")
1495
1496 ;; NodeTransformer
1497 (js2-msg "msg.dup.label"
1498 "duplicated label")
1499
1500 (js2-msg "msg.undef.label"
1501 "undefined label")
1502
1503 (js2-msg "msg.bad.break"
1504 "unlabelled break must be inside loop or switch")
1505
1506 (js2-msg "msg.continue.outside"
1507 "continue must be inside loop")
1508
1509 (js2-msg "msg.continue.nonloop"
1510 "continue can only use labels of iteration statements")
1511
1512 (js2-msg "msg.bad.throw.eol"
1513 "Line terminator is not allowed between the throw "
1514 "keyword and throw expression.")
1515
1516 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1517 "function statement requires a name")
1518
1519 (js2-msg "msg.no.paren.parms"
1520 "missing ( before function parameters.")
1521
1522 (js2-msg "msg.no.parm"
1523 "missing formal parameter")
1524
1525 (js2-msg "msg.no.paren.after.parms"
1526 "missing ) after formal parameters")
1527
1528 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1529 "parameter without default follows parameter with default")
1530
1531 (js2-msg "msg.param.after.rest" ; added by js2-mode
1532 "parameter after rest parameter")
1533
1534 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1535 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1536
1537 (js2-msg "msg.no.brace.body"
1538 "missing '{' before function body")
1539
1540 (js2-msg "msg.no.brace.after.body"
1541 "missing } after function body")
1542
1543 (js2-msg "msg.no.paren.cond"
1544 "missing ( before condition")
1545
1546 (js2-msg "msg.no.paren.after.cond"
1547 "missing ) after condition")
1548
1549 (js2-msg "msg.no.semi.stmt"
1550 "missing ; before statement")
1551
1552 (js2-msg "msg.missing.semi"
1553 "missing ; after statement")
1554
1555 (js2-msg "msg.no.name.after.dot"
1556 "missing name after . operator")
1557
1558 (js2-msg "msg.no.name.after.coloncolon"
1559 "missing name after :: operator")
1560
1561 (js2-msg "msg.no.name.after.dotdot"
1562 "missing name after .. operator")
1563
1564 (js2-msg "msg.no.name.after.xmlAttr"
1565 "missing name after .@")
1566
1567 (js2-msg "msg.no.bracket.index"
1568 "missing ] in index expression")
1569
1570 (js2-msg "msg.no.paren.switch"
1571 "missing ( before switch expression")
1572
1573 (js2-msg "msg.no.paren.after.switch"
1574 "missing ) after switch expression")
1575
1576 (js2-msg "msg.no.brace.switch"
1577 "missing '{' before switch body")
1578
1579 (js2-msg "msg.bad.switch"
1580 "invalid switch statement")
1581
1582 (js2-msg "msg.no.colon.case"
1583 "missing : after case expression")
1584
1585 (js2-msg "msg.double.switch.default"
1586 "double default label in the switch statement")
1587
1588 (js2-msg "msg.no.while.do"
1589 "missing while after do-loop body")
1590
1591 (js2-msg "msg.no.paren.for"
1592 "missing ( after for")
1593
1594 (js2-msg "msg.no.semi.for"
1595 "missing ; after for-loop initializer")
1596
1597 (js2-msg "msg.no.semi.for.cond"
1598 "missing ; after for-loop condition")
1599
1600 (js2-msg "msg.in.after.for.name"
1601 "missing in or of after for")
1602
1603 (js2-msg "msg.no.paren.for.ctrl"
1604 "missing ) after for-loop control")
1605
1606 (js2-msg "msg.no.paren.with"
1607 "missing ( before with-statement object")
1608
1609 (js2-msg "msg.no.paren.after.with"
1610 "missing ) after with-statement object")
1611
1612 (js2-msg "msg.no.paren.after.let"
1613 "missing ( after let")
1614
1615 (js2-msg "msg.no.paren.let"
1616 "missing ) after variable list")
1617
1618 (js2-msg "msg.no.curly.let"
1619 "missing } after let statement")
1620
1621 (js2-msg "msg.bad.return"
1622 "invalid return")
1623
1624 (js2-msg "msg.no.brace.block"
1625 "missing } in compound statement")
1626
1627 (js2-msg "msg.bad.label"
1628 "invalid label")
1629
1630 (js2-msg "msg.bad.var"
1631 "missing variable name")
1632
1633 (js2-msg "msg.bad.var.init"
1634 "invalid variable initialization")
1635
1636 (js2-msg "msg.no.colon.cond"
1637 "missing : in conditional expression")
1638
1639 (js2-msg "msg.no.paren.arg"
1640 "missing ) after argument list")
1641
1642 (js2-msg "msg.no.bracket.arg"
1643 "missing ] after element list")
1644
1645 (js2-msg "msg.bad.prop"
1646 "invalid property id")
1647
1648 (js2-msg "msg.no.colon.prop"
1649 "missing : after property id")
1650
1651 (js2-msg "msg.no.brace.prop"
1652 "missing } after property list")
1653
1654 (js2-msg "msg.no.paren"
1655 "missing ) in parenthetical")
1656
1657 (js2-msg "msg.reserved.id"
1658 "'%s' is a reserved identifier")
1659
1660 (js2-msg "msg.no.paren.catch"
1661 "missing ( before catch-block condition")
1662
1663 (js2-msg "msg.bad.catchcond"
1664 "invalid catch block condition")
1665
1666 (js2-msg "msg.catch.unreachable"
1667 "any catch clauses following an unqualified catch are unreachable")
1668
1669 (js2-msg "msg.no.brace.try"
1670 "missing '{' before try block")
1671
1672 (js2-msg "msg.no.brace.catchblock"
1673 "missing '{' before catch-block body")
1674
1675 (js2-msg "msg.try.no.catchfinally"
1676 "'try' without 'catch' or 'finally'")
1677
1678 (js2-msg "msg.no.return.value"
1679 "function %s does not always return a value")
1680
1681 (js2-msg "msg.anon.no.return.value"
1682 "anonymous function does not always return a value")
1683
1684 (js2-msg "msg.return.inconsistent"
1685 "return statement is inconsistent with previous usage")
1686
1687 (js2-msg "msg.generator.returns"
1688 "TypeError: legacy generator function '%s' returns a value")
1689
1690 (js2-msg "msg.anon.generator.returns"
1691 "TypeError: anonymous legacy generator function returns a value")
1692
1693 (js2-msg "msg.syntax"
1694 "syntax error")
1695
1696 (js2-msg "msg.unexpected.eof"
1697 "Unexpected end of file")
1698
1699 (js2-msg "msg.XML.bad.form"
1700 "illegally formed XML syntax")
1701
1702 (js2-msg "msg.XML.not.available"
1703 "XML runtime not available")
1704
1705 (js2-msg "msg.too.deep.parser.recursion"
1706 "Too deep recursion while parsing")
1707
1708 (js2-msg "msg.no.side.effects"
1709 "Code has no side effects")
1710
1711 (js2-msg "msg.extra.trailing.comma"
1712 "Trailing comma is not supported in some browsers")
1713
1714 (js2-msg "msg.array.trailing.comma"
1715 "Trailing comma yields different behavior across browsers")
1716
1717 (js2-msg "msg.equal.as.assign"
1718 (concat "Test for equality (==) mistyped as assignment (=)?"
1719 " (parenthesize to suppress warning)"))
1720
1721 (js2-msg "msg.var.hides.arg"
1722 "Variable %s hides argument")
1723
1724 (js2-msg "msg.destruct.assign.no.init"
1725 "Missing = in destructuring declaration")
1726
1727 ;; ScriptRuntime
1728 (js2-msg "msg.no.properties"
1729 "%s has no properties.")
1730
1731 (js2-msg "msg.invalid.iterator"
1732 "Invalid iterator value")
1733
1734 (js2-msg "msg.iterator.primitive"
1735 "__iterator__ returned a primitive value")
1736
1737 (js2-msg "msg.assn.create.strict"
1738 "Assignment to undeclared variable %s")
1739
1740 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1741 "Undeclared variable or function '%s'")
1742
1743 (js2-msg "msg.ref.undefined.prop"
1744 "Reference to undefined property '%s'")
1745
1746 (js2-msg "msg.prop.not.found"
1747 "Property %s not found.")
1748
1749 (js2-msg "msg.invalid.type"
1750 "Invalid JavaScript value of type %s")
1751
1752 (js2-msg "msg.primitive.expected"
1753 "Primitive type expected (had %s instead)")
1754
1755 (js2-msg "msg.namespace.expected"
1756 "Namespace object expected to left of :: (found %s instead)")
1757
1758 (js2-msg "msg.null.to.object"
1759 "Cannot convert null to an object.")
1760
1761 (js2-msg "msg.undef.to.object"
1762 "Cannot convert undefined to an object.")
1763
1764 (js2-msg "msg.cyclic.value"
1765 "Cyclic %s value not allowed.")
1766
1767 (js2-msg "msg.is.not.defined"
1768 "'%s' is not defined.")
1769
1770 (js2-msg "msg.undef.prop.read"
1771 "Cannot read property '%s' from %s")
1772
1773 (js2-msg "msg.undef.prop.write"
1774 "Cannot set property '%s' of %s to '%s'")
1775
1776 (js2-msg "msg.undef.prop.delete"
1777 "Cannot delete property '%s' of %s")
1778
1779 (js2-msg "msg.undef.method.call"
1780 "Cannot call method '%s' of %s")
1781
1782 (js2-msg "msg.undef.with"
1783 "Cannot apply 'with' to %s")
1784
1785 (js2-msg "msg.isnt.function"
1786 "%s is not a function, it is %s.")
1787
1788 (js2-msg "msg.isnt.function.in"
1789 "Cannot call property %s in object %s. "
1790 "It is not a function, it is '%s'.")
1791
1792 (js2-msg "msg.function.not.found"
1793 "Cannot find function %s.")
1794
1795 (js2-msg "msg.function.not.found.in"
1796 "Cannot find function %s in object %s.")
1797
1798 (js2-msg "msg.isnt.xml.object"
1799 "%s is not an xml object.")
1800
1801 (js2-msg "msg.no.ref.to.get"
1802 "%s is not a reference to read reference value.")
1803
1804 (js2-msg "msg.no.ref.to.set"
1805 "%s is not a reference to set reference value to %s.")
1806
1807 (js2-msg "msg.no.ref.from.function"
1808 "Function %s can not be used as the left-hand "
1809 "side of assignment or as an operand of ++ or -- operator.")
1810
1811 (js2-msg "msg.bad.default.value"
1812 "Object's getDefaultValue() method returned an object.")
1813
1814 (js2-msg "msg.instanceof.not.object"
1815 "Can't use instanceof on a non-object.")
1816
1817 (js2-msg "msg.instanceof.bad.prototype"
1818 "'prototype' property of %s is not an object.")
1819
1820 (js2-msg "msg.bad.radix"
1821 "illegal radix %s.")
1822
1823 ;; ScriptableObject
1824 (js2-msg "msg.default.value"
1825 "Cannot find default value for object.")
1826
1827 (js2-msg "msg.zero.arg.ctor"
1828 "Cannot load class '%s' which has no zero-parameter constructor.")
1829
1830 (js2-msg "msg.ctor.multiple.parms"
1831 "Can't define constructor or class %s since more than "
1832 "one constructor has multiple parameters.")
1833
1834 (js2-msg "msg.extend.scriptable"
1835 "%s must extend ScriptableObject in order to define property %s.")
1836
1837 (js2-msg "msg.bad.getter.parms"
1838 "In order to define a property, getter %s must have zero "
1839 "parameters or a single ScriptableObject parameter.")
1840
1841 (js2-msg "msg.obj.getter.parms"
1842 "Expected static or delegated getter %s to take "
1843 "a ScriptableObject parameter.")
1844
1845 (js2-msg "msg.getter.static"
1846 "Getter and setter must both be static or neither be static.")
1847
1848 (js2-msg "msg.setter.return"
1849 "Setter must have void return type: %s")
1850
1851 (js2-msg "msg.setter2.parms"
1852 "Two-parameter setter must take a ScriptableObject as "
1853 "its first parameter.")
1854
1855 (js2-msg "msg.setter1.parms"
1856 "Expected single parameter setter for %s")
1857
1858 (js2-msg "msg.setter2.expected"
1859 "Expected static or delegated setter %s to take two parameters.")
1860
1861 (js2-msg "msg.setter.parms"
1862 "Expected either one or two parameters for setter.")
1863
1864 (js2-msg "msg.setter.bad.type"
1865 "Unsupported parameter type '%s' in setter '%s'.")
1866
1867 (js2-msg "msg.add.sealed"
1868 "Cannot add a property to a sealed object: %s.")
1869
1870 (js2-msg "msg.remove.sealed"
1871 "Cannot remove a property from a sealed object: %s.")
1872
1873 (js2-msg "msg.modify.sealed"
1874 "Cannot modify a property of a sealed object: %s.")
1875
1876 (js2-msg "msg.modify.readonly"
1877 "Cannot modify readonly property: %s.")
1878
1879 ;; TokenStream
1880 (js2-msg "msg.missing.exponent"
1881 "missing exponent")
1882
1883 (js2-msg "msg.caught.nfe"
1884 "number format error")
1885
1886 (js2-msg "msg.unterminated.string.lit"
1887 "unterminated string literal")
1888
1889 (js2-msg "msg.unterminated.comment"
1890 "unterminated comment")
1891
1892 (js2-msg "msg.unterminated.re.lit"
1893 "unterminated regular expression literal")
1894
1895 (js2-msg "msg.invalid.re.flag"
1896 "invalid flag after regular expression")
1897
1898 (js2-msg "msg.no.re.input.for"
1899 "no input for %s")
1900
1901 (js2-msg "msg.illegal.character"
1902 "illegal character")
1903
1904 (js2-msg "msg.invalid.escape"
1905 "invalid Unicode escape sequence")
1906
1907 (js2-msg "msg.bad.namespace"
1908 "not a valid default namespace statement. "
1909 "Syntax is: default xml namespace = EXPRESSION;")
1910
1911 ;; TokensStream warnings
1912 (js2-msg "msg.bad.octal.literal"
1913 "illegal octal literal digit %s; "
1914 "interpreting it as a decimal digit")
1915
1916 (js2-msg "msg.missing.hex.digits"
1917 "missing hexadecimal digits after '0x'")
1918
1919 (js2-msg "msg.missing.binary.digits"
1920 "missing binary digits after '0b'")
1921
1922 (js2-msg "msg.missing.octal.digits"
1923 "missing octal digits after '0o'")
1924
1925 (js2-msg "msg.script.is.not.constructor"
1926 "Script objects are not constructors.")
1927
1928 ;; Arrays
1929 (js2-msg "msg.arraylength.bad"
1930 "Inappropriate array length.")
1931
1932 ;; Arrays
1933 (js2-msg "msg.arraylength.too.big"
1934 "Array length %s exceeds supported capacity limit.")
1935
1936 ;; URI
1937 (js2-msg "msg.bad.uri"
1938 "Malformed URI sequence.")
1939
1940 ;; Number
1941 (js2-msg "msg.bad.precision"
1942 "Precision %s out of range.")
1943
1944 ;; NativeGenerator
1945 (js2-msg "msg.send.newborn"
1946 "Attempt to send value to newborn generator")
1947
1948 (js2-msg "msg.already.exec.gen"
1949 "Already executing generator")
1950
1951 (js2-msg "msg.StopIteration.invalid"
1952 "StopIteration may not be changed to an arbitrary object.")
1953
1954 ;; Interpreter
1955 (js2-msg "msg.yield.closing"
1956 "Yield from closing generator")
1957
1958 ;;; Tokens Buffer
1959
1960 (defconst js2-ti-max-lookahead 2)
1961 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1962
1963 ;; Have to call `js2-init-scanner' to initialize the values.
1964 (js2-deflocal js2-ti-tokens nil)
1965 (js2-deflocal js2-ti-tokens-cursor nil)
1966 (js2-deflocal js2-ti-lookahead nil)
1967
1968 (defun js2-new-token (offset)
1969 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
1970 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
1971 (aset js2-ti-tokens js2-ti-tokens-cursor token)
1972 token))
1973
1974 (defsubst js2-current-token ()
1975 (aref js2-ti-tokens js2-ti-tokens-cursor))
1976
1977 (defsubst js2-current-token-string ()
1978 (js2-token-string (js2-current-token)))
1979
1980 (defsubst js2-current-token-type ()
1981 (js2-token-type (js2-current-token)))
1982
1983 (defsubst js2-current-token-beg ()
1984 (js2-token-beg (js2-current-token)))
1985
1986 (defsubst js2-current-token-end ()
1987 (js2-token-end (js2-current-token)))
1988
1989 (defun js2-current-token-len ()
1990 (let ((token (js2-current-token)))
1991 (- (js2-token-end token)
1992 (js2-token-beg token))))
1993
1994 (defun js2-ts-seek (state)
1995 (setq js2-ts-lineno (js2-ts-state-lineno state)
1996 js2-ts-cursor (js2-ts-state-cursor state)
1997 js2-ti-tokens (js2-ts-state-tokens state)
1998 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
1999 js2-ti-lookahead (js2-ts-state-lookahead state)))
2000
2001 ;;; Utilities
2002
2003 (defun js2-delete-if (predicate list)
2004 "Remove all items satisfying PREDICATE in LIST."
2005 (loop for item in list
2006 if (not (funcall predicate item))
2007 collect item))
2008
2009 (defun js2-position (element list)
2010 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2011 Returns nil if element is not found in the list."
2012 (let ((count 0)
2013 found)
2014 (while (and list (not found))
2015 (if (eq element (car list))
2016 (setq found t)
2017 (setq count (1+ count)
2018 list (cdr list))))
2019 (if found count)))
2020
2021 (defun js2-find-if (predicate list)
2022 "Find first item satisfying PREDICATE in LIST."
2023 (let (result)
2024 (while (and list (not result))
2025 (if (funcall predicate (car list))
2026 (setq result (car list)))
2027 (setq list (cdr list)))
2028 result))
2029
2030 (defmacro js2-time (form)
2031 "Evaluate FORM, discard result, and return elapsed time in sec."
2032 (declare (debug t))
2033 (let ((beg (make-symbol "--js2-time-beg--"))
2034 (delta (make-symbol "--js2-time-end--")))
2035 `(let ((,beg (current-time))
2036 ,delta)
2037 ,form
2038 (/ (truncate (* (- (float-time (current-time))
2039 (float-time ,beg))
2040 10000))
2041 10000.0))))
2042
2043 (defsubst js2-same-line (pos)
2044 "Return t if POS is on the same line as current point."
2045 (and (>= pos (point-at-bol))
2046 (<= pos (point-at-eol))))
2047
2048 (defun js2-code-bug ()
2049 "Signal an error when we encounter an unexpected code path."
2050 (error "failed assertion"))
2051
2052 (defsubst js2-record-text-property (beg end prop value)
2053 "Record a text property to set when parsing finishes."
2054 (push (list beg end prop value) js2-mode-deferred-properties))
2055
2056 ;; I'd like to associate errors with nodes, but for now the
2057 ;; easiest thing to do is get the context info from the last token.
2058 (defun js2-record-parse-error (msg &optional arg pos len)
2059 (push (list (list msg arg)
2060 (or pos (js2-current-token-beg))
2061 (or len (js2-current-token-len)))
2062 js2-parsed-errors))
2063
2064 (defun js2-report-error (msg &optional msg-arg pos len)
2065 "Signal a syntax error or record a parse error."
2066 (if js2-recover-from-parse-errors
2067 (js2-record-parse-error msg msg-arg pos len)
2068 (signal 'js2-syntax-error
2069 (list msg
2070 js2-ts-lineno
2071 (save-excursion
2072 (goto-char js2-ts-cursor)
2073 (current-column))
2074 js2-ts-hit-eof))))
2075
2076 (defun js2-report-warning (msg &optional msg-arg pos len face)
2077 (if js2-compiler-report-warning-as-error
2078 (js2-report-error msg msg-arg pos len)
2079 (push (list (list msg msg-arg)
2080 (or pos (js2-current-token-beg))
2081 (or len (js2-current-token-len))
2082 face)
2083 js2-parsed-warnings)))
2084
2085 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2086 (if js2-compiler-strict-mode
2087 (js2-report-warning msg-id msg-arg beg
2088 (and beg end (- end beg)))))
2089
2090 (put 'js2-syntax-error 'error-conditions
2091 '(error syntax-error js2-syntax-error))
2092 (put 'js2-syntax-error 'error-message "Syntax error")
2093
2094 (put 'js2-parse-error 'error-conditions
2095 '(error parse-error js2-parse-error))
2096 (put 'js2-parse-error 'error-message "Parse error")
2097
2098 (defmacro js2-clear-flag (flags flag)
2099 `(setq ,flags (logand ,flags (lognot ,flag))))
2100
2101 (defmacro js2-set-flag (flags flag)
2102 "Logical-or FLAG into FLAGS."
2103 `(setq ,flags (logior ,flags ,flag)))
2104
2105 (defsubst js2-flag-set-p (flags flag)
2106 (/= 0 (logand flags flag)))
2107
2108 (defsubst js2-flag-not-set-p (flags flag)
2109 (zerop (logand flags flag)))
2110
2111 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2112 "Evaluate BODY with the _ character set to be word-syntax."
2113 (declare (indent 0) (debug t))
2114 (let ((old-syntax (make-symbol "old-syntax")))
2115 `(let ((,old-syntax (string (char-syntax ?_))))
2116 (unwind-protect
2117 (progn
2118 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2119 ,@body)
2120 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2121
2122 ;;; AST struct and function definitions
2123
2124 ;; flags for ast node property 'member-type (used for e4x operators)
2125 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2126 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2127 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2128
2129 (defsubst js2-relpos (pos anchor)
2130 "Convert POS to be relative to ANCHOR.
2131 If POS is nil, returns nil."
2132 (and pos (- pos anchor)))
2133
2134 (defun js2-make-pad (indent)
2135 (if (zerop indent)
2136 ""
2137 (make-string (* indent js2-basic-offset) ? )))
2138
2139 (defun js2-visit-ast (node callback)
2140 "Visit every node in ast NODE with visitor CALLBACK.
2141
2142 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2143 called twice: once to visit the node, and again after all the node's
2144 children have been processed. The END-P argument is nil on the first
2145 call and non-nil on the second call. The return value of the callback
2146 affects the traversal: if non-nil, the children of NODE are processed.
2147 If the callback returns nil, or if the node has no children, then the
2148 callback is called immediately with a non-nil END-P argument.
2149
2150 The node traversal is approximately lexical-order, although there
2151 are currently no guarantees around this."
2152 (when node
2153 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2154 ;; visit the node
2155 (when (funcall callback node nil)
2156 ;; visit the kids
2157 (cond
2158 ((eq vfunc 'js2-visit-none)
2159 nil) ; don't even bother calling it
2160 ;; Each AST node type has to define a `js2-visitor' function
2161 ;; that takes a node and a callback, and calls `js2-visit-ast'
2162 ;; on each child of the node.
2163 (vfunc
2164 (funcall vfunc node callback))
2165 (t
2166 (error "%s does not define a visitor-traversal function"
2167 (aref node 0)))))
2168 ;; call the end-visit
2169 (funcall callback node t))))
2170
2171 (defstruct (js2-node
2172 (:constructor nil)) ; abstract
2173 "Base AST node type."
2174 (type -1) ; token type
2175 (pos -1) ; start position of this AST node in parsed input
2176 (len 1) ; num characters spanned by the node
2177 props ; optional node property list (an alist)
2178 parent) ; link to parent node; null for root
2179
2180 (defsubst js2-node-get-prop (node prop &optional default)
2181 (or (cadr (assoc prop (js2-node-props node))) default))
2182
2183 (defsubst js2-node-set-prop (node prop value)
2184 (setf (js2-node-props node)
2185 (cons (list prop value) (js2-node-props node))))
2186
2187 (defun js2-fixup-starts (n nodes)
2188 "Adjust the start positions of NODES to be relative to N.
2189 Any node in the list may be nil, for convenience."
2190 (dolist (node nodes)
2191 (when node
2192 (setf (js2-node-pos node) (- (js2-node-pos node)
2193 (js2-node-pos n))))))
2194
2195 (defun js2-node-add-children (parent &rest nodes)
2196 "Set parent node of NODES to PARENT, and return PARENT.
2197 Does nothing if we're not recording parent links.
2198 If any given node in NODES is nil, doesn't record that link."
2199 (js2-fixup-starts parent nodes)
2200 (dolist (node nodes)
2201 (and node
2202 (setf (js2-node-parent node) parent))))
2203
2204 ;; Non-recursive since it's called a frightening number of times.
2205 (defun js2-node-abs-pos (n)
2206 (let ((pos (js2-node-pos n)))
2207 (while (setq n (js2-node-parent n))
2208 (setq pos (+ pos (js2-node-pos n))))
2209 pos))
2210
2211 (defsubst js2-node-abs-end (n)
2212 "Return absolute buffer position of end of N."
2213 (+ (js2-node-abs-pos n) (js2-node-len n)))
2214
2215 ;; It's important to make sure block nodes have a Lisp list for the
2216 ;; child nodes, to limit printing recursion depth in an AST that
2217 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2218 ;; a sufficiently large vector tree.
2219
2220 (defstruct (js2-block-node
2221 (:include js2-node)
2222 (:constructor nil)
2223 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2224 (pos (js2-current-token-beg))
2225 len
2226 props
2227 kids)))
2228 "A block of statements."
2229 kids) ; a Lisp list of the child statement nodes
2230
2231 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2232 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2233
2234 (defun js2-visit-block (ast callback)
2235 "Visit the `js2-block-node' children of AST."
2236 (dolist (kid (js2-block-node-kids ast))
2237 (js2-visit-ast kid callback)))
2238
2239 (defun js2-print-block (n i)
2240 (let ((pad (js2-make-pad i)))
2241 (insert pad "{\n")
2242 (dolist (kid (js2-block-node-kids n))
2243 (js2-print-ast kid (1+ i)))
2244 (insert pad "}")))
2245
2246 (defstruct (js2-scope
2247 (:include js2-block-node)
2248 (:constructor nil)
2249 (:constructor make-js2-scope (&key (type js2-BLOCK)
2250 (pos (js2-current-token-beg))
2251 len
2252 kids)))
2253 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2254 ;; I don't have one of those handy, so I'll use an alist for now.
2255 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2256 ;; and is much lighter-weight to construct (both CPU and mem).
2257 ;; The keys are interned strings (symbols) for faster lookup.
2258 ;; Should switch to hybrid alist/hashtable eventually.
2259 symbol-table ; an alist of (symbol . js2-symbol)
2260 parent-scope ; a `js2-scope'
2261 top) ; top-level `js2-scope' (script/function)
2262
2263 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2264 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2265
2266 (defun js2-node-get-enclosing-scope (node)
2267 "Return the innermost `js2-scope' node surrounding NODE.
2268 Returns nil if there is no enclosing scope node."
2269 (let ((parent (js2-node-parent node)))
2270 (while (not (js2-scope-p parent))
2271 (setq parent (js2-node-parent parent)))
2272 parent))
2273
2274 (defun js2-get-defining-scope (scope name)
2275 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2276 Returns `js2-scope' in which NAME is defined, or nil if not found."
2277 (let ((sym (if (symbolp name)
2278 name
2279 (intern name)))
2280 table
2281 result
2282 (continue t))
2283 (while (and scope continue)
2284 (if (and (setq table (js2-scope-symbol-table scope))
2285 (assq sym table))
2286 (setq continue nil
2287 result scope)
2288 (setq scope (js2-scope-parent-scope scope))))
2289 result))
2290
2291 (defun js2-scope-get-symbol (scope name)
2292 "Return symbol table entry for NAME in SCOPE.
2293 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2294 (and (js2-scope-symbol-table scope)
2295 (cdr (assq (if (symbolp name)
2296 name
2297 (intern name))
2298 (js2-scope-symbol-table scope)))))
2299
2300 (defun js2-scope-put-symbol (scope name symbol)
2301 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2302 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2303 (let* ((table (js2-scope-symbol-table scope))
2304 (sym (if (symbolp name) name (intern name)))
2305 (entry (assq sym table)))
2306 (if entry
2307 (setcdr entry symbol)
2308 (push (cons sym symbol)
2309 (js2-scope-symbol-table scope)))))
2310
2311 (defstruct (js2-symbol
2312 (:constructor nil)
2313 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2314 "A symbol table entry."
2315 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2316 ;; js2-LET, or js2-CONST
2317 decl-type
2318 name ; string
2319 ast-node) ; a `js2-node'
2320
2321 (defstruct (js2-error-node
2322 (:include js2-node)
2323 (:constructor nil) ; silence emacs21 byte-compiler
2324 (:constructor make-js2-error-node (&key (type js2-ERROR)
2325 (pos (js2-current-token-beg))
2326 len)))
2327 "AST node representing a parse error.")
2328
2329 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2330 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2331
2332 (defstruct (js2-script-node
2333 (:include js2-scope)
2334 (:constructor nil)
2335 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2336 (pos (js2-current-token-beg))
2337 len
2338 ;; FIXME: What are those?
2339 var-decls
2340 fun-decls)))
2341 functions ; Lisp list of nested functions
2342 regexps ; Lisp list of (string . flags)
2343 symbols ; alist (every symbol gets unique index)
2344 (param-count 0)
2345 var-names ; vector of string names
2346 consts ; bool-vector matching var-decls
2347 (temp-number 0)) ; for generating temp variables
2348
2349 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2350 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2351
2352 (defun js2-print-script (node indent)
2353 (dolist (kid (js2-block-node-kids node))
2354 (js2-print-ast kid indent)))
2355
2356 (defstruct (js2-ast-root
2357 (:include js2-script-node)
2358 (:constructor nil)
2359 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2360 (pos (js2-current-token-beg))
2361 len
2362 buffer)))
2363 "The root node of a js2 AST."
2364 buffer ; the source buffer from which the code was parsed
2365 comments ; a Lisp list of comments, ordered by start position
2366 errors ; a Lisp list of errors found during parsing
2367 warnings ; a Lisp list of warnings found during parsing
2368 node-count) ; number of nodes in the tree, including the root
2369
2370 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2371 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2372
2373 (defun js2-visit-ast-root (ast callback)
2374 (dolist (kid (js2-ast-root-kids ast))
2375 (js2-visit-ast kid callback))
2376 (dolist (comment (js2-ast-root-comments ast))
2377 (js2-visit-ast comment callback)))
2378
2379 (defstruct (js2-comment-node
2380 (:include js2-node)
2381 (:constructor nil)
2382 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2383 (pos (js2-current-token-beg))
2384 len
2385 format)))
2386 format) ; 'line, 'block, 'jsdoc or 'html
2387
2388 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2389 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2390
2391 (defun js2-print-comment (n i)
2392 ;; We really ought to link end-of-line comments to their nodes.
2393 ;; Or maybe we could add a new comment type, 'endline.
2394 (insert (js2-make-pad i)
2395 (js2-node-string n)))
2396
2397 (defstruct (js2-expr-stmt-node
2398 (:include js2-node)
2399 (:constructor nil)
2400 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2401 (pos js2-ts-cursor)
2402 len
2403 expr)))
2404 "An expression statement."
2405 expr)
2406
2407 (defsubst js2-expr-stmt-node-set-has-result (node)
2408 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2409 (setf (js2-node-type node) js2-EXPR_RESULT))
2410
2411 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2412 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2413
2414 (defun js2-visit-expr-stmt-node (n v)
2415 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2416
2417 (defun js2-print-expr-stmt-node (n indent)
2418 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2419 (insert ";\n"))
2420
2421 (defstruct (js2-loop-node
2422 (:include js2-scope)
2423 (:constructor nil))
2424 "Abstract supertype of loop nodes."
2425 body ; a `js2-block-node'
2426 lp ; position of left-paren, nil if omitted
2427 rp) ; position of right-paren, nil if omitted
2428
2429 (defstruct (js2-do-node
2430 (:include js2-loop-node)
2431 (:constructor nil)
2432 (:constructor make-js2-do-node (&key (type js2-DO)
2433 (pos (js2-current-token-beg))
2434 len
2435 body
2436 condition
2437 while-pos
2438 lp
2439 rp)))
2440 "AST node for do-loop."
2441 condition ; while (expression)
2442 while-pos) ; buffer position of 'while' keyword
2443
2444 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2445 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2446
2447 (defun js2-visit-do-node (n v)
2448 (js2-visit-ast (js2-do-node-body n) v)
2449 (js2-visit-ast (js2-do-node-condition n) v))
2450
2451 (defun js2-print-do-node (n i)
2452 (let ((pad (js2-make-pad i)))
2453 (insert pad "do {\n")
2454 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2455 (js2-print-ast kid (1+ i)))
2456 (insert pad "} while (")
2457 (js2-print-ast (js2-do-node-condition n) 0)
2458 (insert ");\n")))
2459
2460 (defstruct (js2-while-node
2461 (:include js2-loop-node)
2462 (:constructor nil)
2463 (:constructor make-js2-while-node (&key (type js2-WHILE)
2464 (pos (js2-current-token-beg))
2465 len body
2466 condition lp
2467 rp)))
2468 "AST node for while-loop."
2469 condition) ; while-condition
2470
2471 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2472 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2473
2474 (defun js2-visit-while-node (n v)
2475 (js2-visit-ast (js2-while-node-condition n) v)
2476 (js2-visit-ast (js2-while-node-body n) v))
2477
2478 (defun js2-print-while-node (n i)
2479 (let ((pad (js2-make-pad i)))
2480 (insert pad "while (")
2481 (js2-print-ast (js2-while-node-condition n) 0)
2482 (insert ") {\n")
2483 (js2-print-body (js2-while-node-body n) (1+ i))
2484 (insert pad "}\n")))
2485
2486 (defstruct (js2-for-node
2487 (:include js2-loop-node)
2488 (:constructor nil)
2489 (:constructor make-js2-for-node (&key (type js2-FOR)
2490 (pos js2-ts-cursor)
2491 len body init
2492 condition
2493 update lp rp)))
2494 "AST node for a C-style for-loop."
2495 init ; initialization expression
2496 condition ; loop condition
2497 update) ; update clause
2498
2499 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2500 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2501
2502 (defun js2-visit-for-node (n v)
2503 (js2-visit-ast (js2-for-node-init n) v)
2504 (js2-visit-ast (js2-for-node-condition n) v)
2505 (js2-visit-ast (js2-for-node-update n) v)
2506 (js2-visit-ast (js2-for-node-body n) v))
2507
2508 (defun js2-print-for-node (n i)
2509 (let ((pad (js2-make-pad i)))
2510 (insert pad "for (")
2511 (js2-print-ast (js2-for-node-init n) 0)
2512 (insert "; ")
2513 (js2-print-ast (js2-for-node-condition n) 0)
2514 (insert "; ")
2515 (js2-print-ast (js2-for-node-update n) 0)
2516 (insert ") {\n")
2517 (js2-print-body (js2-for-node-body n) (1+ i))
2518 (insert pad "}\n")))
2519
2520 (defstruct (js2-for-in-node
2521 (:include js2-loop-node)
2522 (:constructor nil)
2523 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2524 (pos js2-ts-cursor)
2525 len body
2526 iterator
2527 object
2528 in-pos
2529 each-pos
2530 foreach-p forof-p
2531 lp rp)))
2532 "AST node for a for..in loop."
2533 iterator ; [var] foo in ...
2534 object ; object over which we're iterating
2535 in-pos ; buffer position of 'in' keyword
2536 each-pos ; buffer position of 'each' keyword, if foreach-p
2537 foreach-p ; t if it's a for-each loop
2538 forof-p) ; t if it's a for-of loop
2539
2540 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2541 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2542
2543 (defun js2-visit-for-in-node (n v)
2544 (js2-visit-ast (js2-for-in-node-iterator n) v)
2545 (js2-visit-ast (js2-for-in-node-object n) v)
2546 (js2-visit-ast (js2-for-in-node-body n) v))
2547
2548 (defun js2-print-for-in-node (n i)
2549 (let ((pad (js2-make-pad i))
2550 (foreach (js2-for-in-node-foreach-p n))
2551 (forof (js2-for-in-node-forof-p n)))
2552 (insert pad "for ")
2553 (if foreach
2554 (insert "each "))
2555 (insert "(")
2556 (js2-print-ast (js2-for-in-node-iterator n) 0)
2557 (insert (if forof " of " " in "))
2558 (js2-print-ast (js2-for-in-node-object n) 0)
2559 (insert ") {\n")
2560 (js2-print-body (js2-for-in-node-body n) (1+ i))
2561 (insert pad "}\n")))
2562
2563 (defstruct (js2-return-node
2564 (:include js2-node)
2565 (:constructor nil)
2566 (:constructor make-js2-return-node (&key (type js2-RETURN)
2567 (pos js2-ts-cursor)
2568 len
2569 retval)))
2570 "AST node for a return statement."
2571 retval) ; expression to return, or 'undefined
2572
2573 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2574 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2575
2576 (defun js2-visit-return-node (n v)
2577 (js2-visit-ast (js2-return-node-retval n) v))
2578
2579 (defun js2-print-return-node (n i)
2580 (insert (js2-make-pad i) "return")
2581 (when (js2-return-node-retval n)
2582 (insert " ")
2583 (js2-print-ast (js2-return-node-retval n) 0))
2584 (insert ";\n"))
2585
2586 (defstruct (js2-if-node
2587 (:include js2-node)
2588 (:constructor nil)
2589 (:constructor make-js2-if-node (&key (type js2-IF)
2590 (pos js2-ts-cursor)
2591 len condition
2592 then-part
2593 else-pos
2594 else-part lp
2595 rp)))
2596 "AST node for an if-statement."
2597 condition ; expression
2598 then-part ; statement or block
2599 else-pos ; optional buffer position of 'else' keyword
2600 else-part ; optional statement or block
2601 lp ; position of left-paren, nil if omitted
2602 rp) ; position of right-paren, nil if omitted
2603
2604 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2605 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2606
2607 (defun js2-visit-if-node (n v)
2608 (js2-visit-ast (js2-if-node-condition n) v)
2609 (js2-visit-ast (js2-if-node-then-part n) v)
2610 (js2-visit-ast (js2-if-node-else-part n) v))
2611
2612 (defun js2-print-if-node (n i)
2613 (let ((pad (js2-make-pad i))
2614 (then-part (js2-if-node-then-part n))
2615 (else-part (js2-if-node-else-part n)))
2616 (insert pad "if (")
2617 (js2-print-ast (js2-if-node-condition n) 0)
2618 (insert ") {\n")
2619 (js2-print-body then-part (1+ i))
2620 (insert pad "}")
2621 (cond
2622 ((not else-part)
2623 (insert "\n"))
2624 ((js2-if-node-p else-part)
2625 (insert " else ")
2626 (js2-print-body else-part i))
2627 (t
2628 (insert " else {\n")
2629 (js2-print-body else-part (1+ i))
2630 (insert pad "}\n")))))
2631
2632 (defstruct (js2-try-node
2633 (:include js2-node)
2634 (:constructor nil)
2635 (:constructor make-js2-try-node (&key (type js2-TRY)
2636 (pos js2-ts-cursor)
2637 len
2638 try-block
2639 catch-clauses
2640 finally-block)))
2641 "AST node for a try-statement."
2642 try-block
2643 catch-clauses ; a Lisp list of `js2-catch-node'
2644 finally-block) ; a `js2-finally-node'
2645
2646 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2647 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2648
2649 (defun js2-visit-try-node (n v)
2650 (js2-visit-ast (js2-try-node-try-block n) v)
2651 (dolist (clause (js2-try-node-catch-clauses n))
2652 (js2-visit-ast clause v))
2653 (js2-visit-ast (js2-try-node-finally-block n) v))
2654
2655 (defun js2-print-try-node (n i)
2656 (let ((pad (js2-make-pad i))
2657 (catches (js2-try-node-catch-clauses n))
2658 (finally (js2-try-node-finally-block n)))
2659 (insert pad "try {\n")
2660 (js2-print-body (js2-try-node-try-block n) (1+ i))
2661 (insert pad "}")
2662 (when catches
2663 (dolist (catch catches)
2664 (js2-print-ast catch i)))
2665 (if finally
2666 (js2-print-ast finally i)
2667 (insert "\n"))))
2668
2669 (defstruct (js2-catch-node
2670 (:include js2-node)
2671 (:constructor nil)
2672 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2673 (pos js2-ts-cursor)
2674 len
2675 param
2676 guard-kwd
2677 guard-expr
2678 block lp
2679 rp)))
2680 "AST node for a catch clause."
2681 param ; destructuring form or simple name node
2682 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2683 guard-expr ; catch condition, a `js2-node'
2684 block ; statements, a `js2-block-node'
2685 lp ; buffer position of left-paren, nil if omitted
2686 rp) ; buffer position of right-paren, nil if omitted
2687
2688 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2689 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2690
2691 (defun js2-visit-catch-node (n v)
2692 (js2-visit-ast (js2-catch-node-param n) v)
2693 (when (js2-catch-node-guard-kwd n)
2694 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2695 (js2-visit-ast (js2-catch-node-block n) v))
2696
2697 (defun js2-print-catch-node (n i)
2698 (let ((pad (js2-make-pad i))
2699 (guard-kwd (js2-catch-node-guard-kwd n))
2700 (guard-expr (js2-catch-node-guard-expr n)))
2701 (insert " catch (")
2702 (js2-print-ast (js2-catch-node-param n) 0)
2703 (when guard-kwd
2704 (insert " if ")
2705 (js2-print-ast guard-expr 0))
2706 (insert ") {\n")
2707 (js2-print-body (js2-catch-node-block n) (1+ i))
2708 (insert pad "}")))
2709
2710 (defstruct (js2-finally-node
2711 (:include js2-node)
2712 (:constructor nil)
2713 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2714 (pos js2-ts-cursor)
2715 len body)))
2716 "AST node for a finally clause."
2717 body) ; a `js2-node', often but not always a block node
2718
2719 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2720 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2721
2722 (defun js2-visit-finally-node (n v)
2723 (js2-visit-ast (js2-finally-node-body n) v))
2724
2725 (defun js2-print-finally-node (n i)
2726 (let ((pad (js2-make-pad i)))
2727 (insert " finally {\n")
2728 (js2-print-body (js2-finally-node-body n) (1+ i))
2729 (insert pad "}\n")))
2730
2731 (defstruct (js2-switch-node
2732 (:include js2-node)
2733 (:constructor nil)
2734 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2735 (pos js2-ts-cursor)
2736 len
2737 discriminant
2738 cases lp
2739 rp)))
2740 "AST node for a switch statement."
2741 discriminant ; a `js2-node' (switch expression)
2742 cases ; a Lisp list of `js2-case-node'
2743 lp ; position of open-paren for discriminant, nil if omitted
2744 rp) ; position of close-paren for discriminant, nil if omitted
2745
2746 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2747 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2748
2749 (defun js2-visit-switch-node (n v)
2750 (js2-visit-ast (js2-switch-node-discriminant n) v)
2751 (dolist (c (js2-switch-node-cases n))
2752 (js2-visit-ast c v)))
2753
2754 (defun js2-print-switch-node (n i)
2755 (let ((pad (js2-make-pad i))
2756 (cases (js2-switch-node-cases n)))
2757 (insert pad "switch (")
2758 (js2-print-ast (js2-switch-node-discriminant n) 0)
2759 (insert ") {\n")
2760 (dolist (case cases)
2761 (js2-print-ast case i))
2762 (insert pad "}\n")))
2763
2764 (defstruct (js2-case-node
2765 (:include js2-block-node)
2766 (:constructor nil)
2767 (:constructor make-js2-case-node (&key (type js2-CASE)
2768 (pos js2-ts-cursor)
2769 len kids expr)))
2770 "AST node for a case clause of a switch statement."
2771 expr) ; the case expression (nil for default)
2772
2773 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2774 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2775
2776 (defun js2-visit-case-node (n v)
2777 (js2-visit-ast (js2-case-node-expr n) v)
2778 (js2-visit-block n v))
2779
2780 (defun js2-print-case-node (n i)
2781 (let ((pad (js2-make-pad i))
2782 (expr (js2-case-node-expr n)))
2783 (insert pad)
2784 (if (null expr)
2785 (insert "default:\n")
2786 (insert "case ")
2787 (js2-print-ast expr 0)
2788 (insert ":\n"))
2789 (dolist (kid (js2-case-node-kids n))
2790 (js2-print-ast kid (1+ i)))))
2791
2792 (defstruct (js2-throw-node
2793 (:include js2-node)
2794 (:constructor nil)
2795 (:constructor make-js2-throw-node (&key (type js2-THROW)
2796 (pos js2-ts-cursor)
2797 len expr)))
2798 "AST node for a throw statement."
2799 expr) ; the expression to throw
2800
2801 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2802 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2803
2804 (defun js2-visit-throw-node (n v)
2805 (js2-visit-ast (js2-throw-node-expr n) v))
2806
2807 (defun js2-print-throw-node (n i)
2808 (insert (js2-make-pad i) "throw ")
2809 (js2-print-ast (js2-throw-node-expr n) 0)
2810 (insert ";\n"))
2811
2812 (defstruct (js2-with-node
2813 (:include js2-node)
2814 (:constructor nil)
2815 (:constructor make-js2-with-node (&key (type js2-WITH)
2816 (pos js2-ts-cursor)
2817 len object
2818 body lp rp)))
2819 "AST node for a with-statement."
2820 object
2821 body
2822 lp ; buffer position of left-paren around object, nil if omitted
2823 rp) ; buffer position of right-paren around object, nil if omitted
2824
2825 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2826 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2827
2828 (defun js2-visit-with-node (n v)
2829 (js2-visit-ast (js2-with-node-object n) v)
2830 (js2-visit-ast (js2-with-node-body n) v))
2831
2832 (defun js2-print-with-node (n i)
2833 (let ((pad (js2-make-pad i)))
2834 (insert pad "with (")
2835 (js2-print-ast (js2-with-node-object n) 0)
2836 (insert ") {\n")
2837 (js2-print-body (js2-with-node-body n) (1+ i))
2838 (insert pad "}\n")))
2839
2840 (defstruct (js2-label-node
2841 (:include js2-node)
2842 (:constructor nil)
2843 (:constructor make-js2-label-node (&key (type js2-LABEL)
2844 (pos js2-ts-cursor)
2845 len name)))
2846 "AST node for a statement label or case label."
2847 name ; a string
2848 loop) ; for validating and code-generating continue-to-label
2849
2850 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2851 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2852
2853 (defun js2-print-label (n i)
2854 (insert (js2-make-pad i)
2855 (js2-label-node-name n)
2856 ":\n"))
2857
2858 (defstruct (js2-labeled-stmt-node
2859 (:include js2-node)
2860 (:constructor nil)
2861 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2862 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2863 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2864 (pos js2-ts-cursor)
2865 len labels stmt)))
2866 "AST node for a statement with one or more labels.
2867 Multiple labels for a statement are collapsed into the labels field."
2868 labels ; Lisp list of `js2-label-node'
2869 stmt) ; the statement these labels are for
2870
2871 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2872 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2873
2874 (defun js2-get-label-by-name (lbl-stmt name)
2875 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2876 Returns nil if no such label is in the list."
2877 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2878 result)
2879 (while (and label-list (not result))
2880 (if (string= (js2-label-node-name (car label-list)) name)
2881 (setq result (car label-list))
2882 (setq label-list (cdr label-list))))
2883 result))
2884
2885 (defun js2-visit-labeled-stmt (n v)
2886 (dolist (label (js2-labeled-stmt-node-labels n))
2887 (js2-visit-ast label v))
2888 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2889
2890 (defun js2-print-labeled-stmt (n i)
2891 (dolist (label (js2-labeled-stmt-node-labels n))
2892 (js2-print-ast label i))
2893 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
2894
2895 (defun js2-labeled-stmt-node-contains (node label)
2896 "Return t if NODE contains LABEL in its label set.
2897 NODE is a `js2-labels-node'. LABEL is an identifier."
2898 (loop for nl in (js2-labeled-stmt-node-labels node)
2899 if (string= label (js2-label-node-name nl))
2900 return t
2901 finally return nil))
2902
2903 (defsubst js2-labeled-stmt-node-add-label (node label)
2904 "Add a `js2-label-node' to the label set for this statement."
2905 (setf (js2-labeled-stmt-node-labels node)
2906 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2907
2908 (defstruct (js2-jump-node
2909 (:include js2-node)
2910 (:constructor nil))
2911 "Abstract supertype of break and continue nodes."
2912 label ; `js2-name-node' for location of label identifier, if present
2913 target) ; target js2-labels-node or loop/switch statement
2914
2915 (defun js2-visit-jump-node (n v)
2916 ;; We don't visit the target, since it's a back-link.
2917 (js2-visit-ast (js2-jump-node-label n) v))
2918
2919 (defstruct (js2-break-node
2920 (:include js2-jump-node)
2921 (:constructor nil)
2922 (:constructor make-js2-break-node (&key (type js2-BREAK)
2923 (pos js2-ts-cursor)
2924 len label target)))
2925 "AST node for a break statement.
2926 The label field is a `js2-name-node', possibly nil, for the named label
2927 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2928 is the target of the break - a label node or enclosing loop/switch statement.")
2929
2930 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2931 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2932
2933 (defun js2-print-break-node (n i)
2934 (insert (js2-make-pad i) "break")
2935 (when (js2-break-node-label n)
2936 (insert " ")
2937 (js2-print-ast (js2-break-node-label n) 0))
2938 (insert ";\n"))
2939
2940 (defstruct (js2-continue-node
2941 (:include js2-jump-node)
2942 (:constructor nil)
2943 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2944 (pos js2-ts-cursor)
2945 len label target)))
2946 "AST node for a continue statement.
2947 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2948 It is nil if continue specifies no label. The target field is the jump target:
2949 a `js2-label-node' or the innermost enclosing loop.")
2950
2951 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2952 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2953
2954 (defun js2-print-continue-node (n i)
2955 (insert (js2-make-pad i) "continue")
2956 (when (js2-continue-node-label n)
2957 (insert " ")
2958 (js2-print-ast (js2-continue-node-label n) 0))
2959 (insert ";\n"))
2960
2961 (defstruct (js2-function-node
2962 (:include js2-script-node)
2963 (:constructor nil)
2964 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2965 (pos js2-ts-cursor)
2966 len
2967 (ftype 'FUNCTION)
2968 (form 'FUNCTION_STATEMENT)
2969 (name "")
2970 params rest-p
2971 body
2972 generator-type
2973 lp rp)))
2974 "AST node for a function declaration.
2975 The `params' field is a Lisp list of nodes. Each node is either a simple
2976 `js2-name-node', or if it's a destructuring-assignment parameter, a
2977 `js2-array-node' or `js2-object-node'."
2978 ftype ; FUNCTION, GETTER or SETTER
2979 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
2980 name ; function name (a `js2-name-node', or nil if anonymous)
2981 params ; a Lisp list of destructuring forms or simple name nodes
2982 rest-p ; if t, the last parameter is rest parameter
2983 body ; a `js2-block-node' or expression node (1.8 only)
2984 lp ; position of arg-list open-paren, or nil if omitted
2985 rp ; position of arg-list close-paren, or nil if omitted
2986 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2987 needs-activation ; t if we need an activation object for this frame
2988 generator-type ; STAR, LEGACY, COMPREHENSION or nil
2989 member-expr) ; nonstandard Ecma extension from Rhino
2990
2991 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2992 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2993
2994 (defun js2-visit-function-node (n v)
2995 (js2-visit-ast (js2-function-node-name n) v)
2996 (dolist (p (js2-function-node-params n))
2997 (js2-visit-ast p v))
2998 (js2-visit-ast (js2-function-node-body n) v))
2999
3000 (defun js2-print-function-node (n i)
3001 (let* ((pad (js2-make-pad i))
3002 (getter (js2-node-get-prop n 'GETTER_SETTER))
3003 (name (or (js2-function-node-name n)
3004 (js2-function-node-member-expr n)))
3005 (params (js2-function-node-params n))
3006 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3007 (rest-p (js2-function-node-rest-p n))
3008 (body (js2-function-node-body n))
3009 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3010 (unless (or getter arrow)
3011 (insert pad "function")
3012 (when (eq (js2-function-node-generator-type n) 'STAR)
3013 (insert "*")))
3014 (when name
3015 (insert " ")
3016 (js2-print-ast name 0))
3017 (insert "(")
3018 (loop with len = (length params)
3019 for param in params
3020 for count from 1
3021 do
3022 (when (and rest-p (= count len))
3023 (insert "..."))
3024 (js2-print-ast param 0)
3025 (when (< count len)
3026 (insert ", ")))
3027 (insert ") ")
3028 (when arrow
3029 (insert "=> "))
3030 (insert "{")
3031 ;; TODO: fix this to be smarter about indenting, etc.
3032 (unless expr
3033 (insert "\n"))
3034 (if (js2-block-node-p body)
3035 (js2-print-body body (1+ i))
3036 (js2-print-ast body 0))
3037 (insert pad "}")
3038 (unless expr
3039 (insert "\n"))))
3040
3041 (defun js2-function-name (node)
3042 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3043 (and (js2-function-node-name node)
3044 (js2-name-node-name (js2-function-node-name node))))
3045
3046 ;; Having this be an expression node makes it more flexible.
3047 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3048 ;; that work better if you assume it's an expression. Whenever we have
3049 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3050 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3051 (defstruct (js2-var-decl-node
3052 (:include js2-node)
3053 (:constructor nil)
3054 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3055 (pos (js2-current-token-beg))
3056 len kids
3057 decl-type)))
3058 "AST node for a variable declaration list (VAR, CONST or LET).
3059 The node bounds differ depending on the declaration type. For VAR or
3060 CONST declarations, the bounds include the var/const keyword. For LET
3061 declarations, the node begins at the position of the first child."
3062 kids ; a Lisp list of `js2-var-init-node' structs.
3063 decl-type) ; js2-VAR, js2-CONST or js2-LET
3064
3065 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3066 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3067
3068 (defun js2-visit-var-decl (n v)
3069 (dolist (kid (js2-var-decl-node-kids n))
3070 (js2-visit-ast kid v)))
3071
3072 (defun js2-print-var-decl (n i)
3073 (let ((pad (js2-make-pad i))
3074 (tt (js2-var-decl-node-decl-type n)))
3075 (insert pad)
3076 (insert (cond
3077 ((= tt js2-VAR) "var ")
3078 ((= tt js2-LET) "let ")
3079 ((= tt js2-CONST) "const ")
3080 (t
3081 (error "malformed var-decl node"))))
3082 (loop with kids = (js2-var-decl-node-kids n)
3083 with len = (length kids)
3084 for kid in kids
3085 for count from 1
3086 do
3087 (js2-print-ast kid 0)
3088 (if (< count len)
3089 (insert ", ")))))
3090
3091 (defstruct (js2-var-init-node
3092 (:include js2-node)
3093 (:constructor nil)
3094 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3095 (pos js2-ts-cursor)
3096 len target
3097 initializer)))
3098 "AST node for a variable declaration.
3099 The type field will be js2-CONST for a const decl."
3100 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3101 initializer) ; initializer expression, a `js2-node'
3102
3103 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3104 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3105
3106 (defun js2-visit-var-init-node (n v)
3107 (js2-visit-ast (js2-var-init-node-target n) v)
3108 (js2-visit-ast (js2-var-init-node-initializer n) v))
3109
3110 (defun js2-print-var-init-node (n i)
3111 (let ((pad (js2-make-pad i))
3112 (name (js2-var-init-node-target n))
3113 (init (js2-var-init-node-initializer n)))
3114 (insert pad)
3115 (js2-print-ast name 0)
3116 (when init
3117 (insert " = ")
3118 (js2-print-ast init 0))))
3119
3120 (defstruct (js2-cond-node
3121 (:include js2-node)
3122 (:constructor nil)
3123 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3124 (pos js2-ts-cursor)
3125 len
3126 test-expr
3127 true-expr
3128 false-expr
3129 q-pos c-pos)))
3130 "AST node for the ternary operator"
3131 test-expr
3132 true-expr
3133 false-expr
3134 q-pos ; buffer position of ?
3135 c-pos) ; buffer position of :
3136
3137 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3138 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3139
3140 (defun js2-visit-cond-node (n v)
3141 (js2-visit-ast (js2-cond-node-test-expr n) v)
3142 (js2-visit-ast (js2-cond-node-true-expr n) v)
3143 (js2-visit-ast (js2-cond-node-false-expr n) v))
3144
3145 (defun js2-print-cond-node (n i)
3146 (let ((pad (js2-make-pad i)))
3147 (insert pad)
3148 (js2-print-ast (js2-cond-node-test-expr n) 0)
3149 (insert " ? ")
3150 (js2-print-ast (js2-cond-node-true-expr n) 0)
3151 (insert " : ")
3152 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3153
3154 (defstruct (js2-infix-node
3155 (:include js2-node)
3156 (:constructor nil)
3157 (:constructor make-js2-infix-node (&key type
3158 (pos js2-ts-cursor)
3159 len op-pos
3160 left right)))
3161 "Represents infix expressions.
3162 Includes assignment ops like `|=', and the comma operator.
3163 The type field inherited from `js2-node' holds the operator."
3164 op-pos ; buffer position where operator begins
3165 left ; any `js2-node'
3166 right) ; any `js2-node'
3167
3168 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3169 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3170
3171 (defun js2-visit-infix-node (n v)
3172 (js2-visit-ast (js2-infix-node-left n) v)
3173 (js2-visit-ast (js2-infix-node-right n) v))
3174
3175 (defconst js2-operator-tokens
3176 (let ((table (make-hash-table :test 'eq))
3177 (tokens
3178 (list (cons js2-IN "in")
3179 (cons js2-TYPEOF "typeof")
3180 (cons js2-INSTANCEOF "instanceof")
3181 (cons js2-DELPROP "delete")
3182 (cons js2-COMMA ",")
3183 (cons js2-COLON ":")
3184 (cons js2-OR "||")
3185 (cons js2-AND "&&")
3186 (cons js2-INC "++")
3187 (cons js2-DEC "--")
3188 (cons js2-BITOR "|")
3189 (cons js2-BITXOR "^")
3190 (cons js2-BITAND "&")
3191 (cons js2-EQ "==")
3192 (cons js2-NE "!=")
3193 (cons js2-LT "<")
3194 (cons js2-LE "<=")
3195 (cons js2-GT ">")
3196 (cons js2-GE ">=")
3197 (cons js2-LSH "<<")
3198 (cons js2-RSH ">>")
3199 (cons js2-URSH ">>>")
3200 (cons js2-ADD "+") ; infix plus
3201 (cons js2-SUB "-") ; infix minus
3202 (cons js2-MUL "*")
3203 (cons js2-DIV "/")
3204 (cons js2-MOD "%")
3205 (cons js2-NOT "!")
3206 (cons js2-BITNOT "~")
3207 (cons js2-POS "+") ; unary plus
3208 (cons js2-NEG "-") ; unary minus
3209 (cons js2-TRIPLEDOT "...")
3210 (cons js2-SHEQ "===") ; shallow equality
3211 (cons js2-SHNE "!==") ; shallow inequality
3212 (cons js2-ASSIGN "=")
3213 (cons js2-ASSIGN_BITOR "|=")
3214 (cons js2-ASSIGN_BITXOR "^=")
3215 (cons js2-ASSIGN_BITAND "&=")
3216 (cons js2-ASSIGN_LSH "<<=")
3217 (cons js2-ASSIGN_RSH ">>=")
3218 (cons js2-ASSIGN_URSH ">>>=")
3219 (cons js2-ASSIGN_ADD "+=")
3220 (cons js2-ASSIGN_SUB "-=")
3221 (cons js2-ASSIGN_MUL "*=")
3222 (cons js2-ASSIGN_DIV "/=")
3223 (cons js2-ASSIGN_MOD "%="))))
3224 (loop for (k . v) in tokens do
3225 (puthash k v table))
3226 table))
3227
3228 (defun js2-print-infix-node (n i)
3229 (let* ((tt (js2-node-type n))
3230 (op (gethash tt js2-operator-tokens)))
3231 (unless op
3232 (error "unrecognized infix operator %s" (js2-node-type n)))
3233 (insert (js2-make-pad i))
3234 (js2-print-ast (js2-infix-node-left n) 0)
3235 (unless (= tt js2-COMMA)
3236 (insert " "))
3237 (insert op)
3238 (insert " ")
3239 (js2-print-ast (js2-infix-node-right n) 0)))
3240
3241 (defstruct (js2-assign-node
3242 (:include js2-infix-node)
3243 (:constructor nil)
3244 (:constructor make-js2-assign-node (&key type
3245 (pos js2-ts-cursor)
3246 len op-pos
3247 left right)))
3248 "Represents any assignment.
3249 The type field holds the actual assignment operator.")
3250
3251 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3252 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3253
3254 (defstruct (js2-unary-node
3255 (:include js2-node)
3256 (:constructor nil)
3257 (:constructor make-js2-unary-node (&key type ; required
3258 (pos js2-ts-cursor)
3259 len operand)))
3260 "AST node type for unary operator nodes.
3261 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3262 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3263 property is added if the operator follows the operand."
3264 operand) ; a `js2-node' expression
3265
3266 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3267 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3268
3269 (defun js2-visit-unary-node (n v)
3270 (js2-visit-ast (js2-unary-node-operand n) v))
3271
3272 (defun js2-print-unary-node (n i)
3273 (let* ((tt (js2-node-type n))
3274 (op (gethash tt js2-operator-tokens))
3275 (postfix (js2-node-get-prop n 'postfix)))
3276 (unless op
3277 (error "unrecognized unary operator %s" tt))
3278 (insert (js2-make-pad i))
3279 (unless postfix
3280 (insert op))
3281 (if (or (= tt js2-TYPEOF)
3282 (= tt js2-DELPROP))
3283 (insert " "))
3284 (js2-print-ast (js2-unary-node-operand n) 0)
3285 (when postfix
3286 (insert op))))
3287
3288 (defstruct (js2-let-node
3289 (:include js2-scope)
3290 (:constructor nil)
3291 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3292 (pos (js2-current-token-beg))
3293 len vars body
3294 lp rp)))
3295 "AST node for a let expression or a let statement.
3296 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3297 vars ; a `js2-var-decl-node'
3298 body ; a `js2-node' representing the expression or body block
3299 lp
3300 rp)
3301
3302 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3303 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3304
3305 (defun js2-visit-let-node (n v)
3306 (js2-visit-ast (js2-let-node-vars n) v)
3307 (js2-visit-ast (js2-let-node-body n) v))
3308
3309 (defun js2-print-let-node (n i)
3310 (insert (js2-make-pad i) "let (")
3311 (let ((p (point)))
3312 (js2-print-ast (js2-let-node-vars n) 0)
3313 (delete-region p (+ p 4)))
3314 (insert ") ")
3315 (js2-print-ast (js2-let-node-body n) i))
3316
3317 (defstruct (js2-keyword-node
3318 (:include js2-node)
3319 (:constructor nil)
3320 (:constructor make-js2-keyword-node (&key type
3321 (pos (js2-current-token-beg))
3322 (len (- js2-ts-cursor pos)))))
3323 "AST node representing a literal keyword such as `null'.
3324 Used for `null', `this', `true', `false' and `debugger'.
3325 The node type is set to js2-NULL, js2-THIS, etc.")
3326
3327 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3328 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3329
3330 (defun js2-print-keyword-node (n i)
3331 (insert (js2-make-pad i)
3332 (let ((tt (js2-node-type n)))
3333 (cond
3334 ((= tt js2-THIS) "this")
3335 ((= tt js2-NULL) "null")
3336 ((= tt js2-TRUE) "true")
3337 ((= tt js2-FALSE) "false")
3338 ((= tt js2-DEBUGGER) "debugger")
3339 (t (error "Invalid keyword literal type: %d" tt))))))
3340
3341 (defsubst js2-this-node-p (node)
3342 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3343 (eq (js2-node-type node) js2-THIS))
3344
3345 (defstruct (js2-new-node
3346 (:include js2-node)
3347 (:constructor nil)
3348 (:constructor make-js2-new-node (&key (type js2-NEW)
3349 (pos (js2-current-token-beg))
3350 len target
3351 args initializer
3352 lp rp)))
3353 "AST node for new-expression such as new Foo()."
3354 target ; an identifier or reference
3355 args ; a Lisp list of argument nodes
3356 lp ; position of left-paren, nil if omitted
3357 rp ; position of right-paren, nil if omitted
3358 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3359
3360 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3361 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3362
3363 (defun js2-visit-new-node (n v)
3364 (js2-visit-ast (js2-new-node-target n) v)
3365 (dolist (arg (js2-new-node-args n))
3366 (js2-visit-ast arg v))
3367 (js2-visit-ast (js2-new-node-initializer n) v))
3368
3369 (defun js2-print-new-node (n i)
3370 (insert (js2-make-pad i) "new ")
3371 (js2-print-ast (js2-new-node-target n))
3372 (insert "(")
3373 (js2-print-list (js2-new-node-args n))
3374 (insert ")")
3375 (when (js2-new-node-initializer n)
3376 (insert " ")
3377 (js2-print-ast (js2-new-node-initializer n))))
3378
3379 (defstruct (js2-name-node
3380 (:include js2-node)
3381 (:constructor nil)
3382 (:constructor make-js2-name-node (&key (type js2-NAME)
3383 (pos (js2-current-token-beg))
3384 (len (- js2-ts-cursor
3385 (js2-current-token-beg)))
3386 (name (js2-current-token-string)))))
3387 "AST node for a JavaScript identifier"
3388 name ; a string
3389 scope) ; a `js2-scope' (optional, used for codegen)
3390
3391 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3392 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3393
3394 (defun js2-print-name-node (n i)
3395 (insert (js2-make-pad i)
3396 (js2-name-node-name n)))
3397
3398 (defsubst js2-name-node-length (node)
3399 "Return identifier length of NODE, a `js2-name-node'.
3400 Returns 0 if NODE is nil or its identifier field is nil."
3401 (if node
3402 (length (js2-name-node-name node))
3403 0))
3404
3405 (defstruct (js2-number-node
3406 (:include js2-node)
3407 (:constructor nil)
3408 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3409 (pos (js2-current-token-beg))
3410 (len (- js2-ts-cursor
3411 (js2-current-token-beg)))
3412 (value (js2-current-token-string))
3413 (num-value (js2-token-number
3414 (js2-current-token))))))
3415 "AST node for a number literal."
3416 value ; the original string, e.g. "6.02e23"
3417 num-value) ; the parsed number value
3418
3419 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3420 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3421
3422 (defun js2-print-number-node (n i)
3423 (insert (js2-make-pad i)
3424 (number-to-string (js2-number-node-num-value n))))
3425
3426 (defstruct (js2-regexp-node
3427 (:include js2-node)
3428 (:constructor nil)
3429 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3430 (pos (js2-current-token-beg))
3431 (len (- js2-ts-cursor
3432 (js2-current-token-beg)))
3433 value flags)))
3434 "AST node for a regular expression literal."
3435 value ; the regexp string, without // delimiters
3436 flags) ; a string of flags, e.g. `mi'.
3437
3438 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3439 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3440
3441 (defun js2-print-regexp (n i)
3442 (insert (js2-make-pad i)
3443 "/"
3444 (js2-regexp-node-value n)
3445 "/")
3446 (if (js2-regexp-node-flags n)
3447 (insert (js2-regexp-node-flags n))))
3448
3449 (defstruct (js2-string-node
3450 (:include js2-node)
3451 (:constructor nil)
3452 (:constructor make-js2-string-node (&key (type js2-STRING)
3453 (pos (js2-current-token-beg))
3454 (len (- js2-ts-cursor
3455 (js2-current-token-beg)))
3456 (value (js2-current-token-string)))))
3457 "String literal.
3458 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3459 You can tell the quote type by looking at the first character."
3460 value) ; the characters of the string, including the quotes
3461
3462 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3463 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3464
3465 (defun js2-print-string-node (n i)
3466 (insert (js2-make-pad i)
3467 (js2-node-string n)))
3468
3469 (defstruct (js2-array-node
3470 (:include js2-node)
3471 (:constructor nil)
3472 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3473 (pos js2-ts-cursor)
3474 len elems)))
3475 "AST node for an array literal."
3476 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3477
3478 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3479 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3480
3481 (defun js2-visit-array-node (n v)
3482 (dolist (e (js2-array-node-elems n))
3483 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3484
3485 (defun js2-print-array-node (n i)
3486 (insert (js2-make-pad i) "[")
3487 (let ((elems (js2-array-node-elems n)))
3488 (js2-print-list elems)
3489 (when (and elems (null (car (last elems))))
3490 (insert ",")))
3491 (insert "]"))
3492
3493 (defstruct (js2-object-node
3494 (:include js2-node)
3495 (:constructor nil)
3496 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3497 (pos js2-ts-cursor)
3498 len
3499 elems)))
3500 "AST node for an object literal expression.
3501 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3502 The latter represents abbreviation in destructuring expressions."
3503 elems)
3504
3505 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3506 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3507
3508 (defun js2-visit-object-node (n v)
3509 (dolist (e (js2-object-node-elems n))
3510 (js2-visit-ast e v)))
3511
3512 (defun js2-print-object-node (n i)
3513 (insert (js2-make-pad i) "{")
3514 (js2-print-list (js2-object-node-elems n))
3515 (insert "}"))
3516
3517 (defstruct (js2-object-prop-node
3518 (:include js2-infix-node)
3519 (:constructor nil)
3520 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3521 (pos js2-ts-cursor)
3522 len left
3523 right op-pos)))
3524 "AST node for an object literal prop:value entry.
3525 The `left' field is the property: a name node, string node or number node.
3526 The `right' field is a `js2-node' representing the initializer value.")
3527
3528 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3529 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3530
3531 (defun js2-print-object-prop-node (n i)
3532 (insert (js2-make-pad i))
3533 (js2-print-ast (js2-object-prop-node-left n) 0)
3534 (insert ": ")
3535 (js2-print-ast (js2-object-prop-node-right n) 0))
3536
3537 (defstruct (js2-getter-setter-node
3538 (:include js2-infix-node)
3539 (:constructor nil)
3540 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3541 (pos js2-ts-cursor)
3542 len left right)))
3543 "AST node for a getter/setter property in an object literal.
3544 The `left' field is the `js2-name-node' naming the getter/setter prop.
3545 The `right' field is always an anonymous `js2-function-node' with a node
3546 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3547
3548 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3549 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3550
3551 (defun js2-print-getter-setter (n i)
3552 (let ((pad (js2-make-pad i))
3553 (left (js2-getter-setter-node-left n))
3554 (right (js2-getter-setter-node-right n)))
3555 (insert pad)
3556 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3557 (js2-print-ast left 0)
3558 (js2-print-ast right 0)))
3559
3560 (defstruct (js2-prop-get-node
3561 (:include js2-infix-node)
3562 (:constructor nil)
3563 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3564 (pos js2-ts-cursor)
3565 len left right)))
3566 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3567
3568 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3569 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3570
3571 (defun js2-visit-prop-get-node (n v)
3572 (js2-visit-ast (js2-prop-get-node-left n) v)
3573 (js2-visit-ast (js2-prop-get-node-right n) v))
3574
3575 (defun js2-print-prop-get-node (n i)
3576 (insert (js2-make-pad i))
3577 (js2-print-ast (js2-prop-get-node-left n) 0)
3578 (insert ".")
3579 (js2-print-ast (js2-prop-get-node-right n) 0))
3580
3581 (defstruct (js2-elem-get-node
3582 (:include js2-node)
3583 (:constructor nil)
3584 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3585 (pos js2-ts-cursor)
3586 len target element
3587 lb rb)))
3588 "AST node for an array index expression such as foo[bar]."
3589 target ; a `js2-node' - the expression preceding the "."
3590 element ; a `js2-node' - the expression in brackets
3591 lb ; position of left-bracket, nil if omitted
3592 rb) ; position of right-bracket, nil if omitted
3593
3594 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3595 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3596
3597 (defun js2-visit-elem-get-node (n v)
3598 (js2-visit-ast (js2-elem-get-node-target n) v)
3599 (js2-visit-ast (js2-elem-get-node-element n) v))
3600
3601 (defun js2-print-elem-get-node (n i)
3602 (insert (js2-make-pad i))
3603 (js2-print-ast (js2-elem-get-node-target n) 0)
3604 (insert "[")
3605 (js2-print-ast (js2-elem-get-node-element n) 0)
3606 (insert "]"))
3607
3608 (defstruct (js2-call-node
3609 (:include js2-node)
3610 (:constructor nil)
3611 (:constructor make-js2-call-node (&key (type js2-CALL)
3612 (pos js2-ts-cursor)
3613 len target args
3614 lp rp)))
3615 "AST node for a JavaScript function call."
3616 target ; a `js2-node' evaluating to the function to call
3617 args ; a Lisp list of `js2-node' arguments
3618 lp ; position of open-paren, or nil if missing
3619 rp) ; position of close-paren, or nil if missing
3620
3621 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3622 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3623
3624 (defun js2-visit-call-node (n v)
3625 (js2-visit-ast (js2-call-node-target n) v)
3626 (dolist (arg (js2-call-node-args n))
3627 (js2-visit-ast arg v)))
3628
3629 (defun js2-print-call-node (n i)
3630 (insert (js2-make-pad i))
3631 (js2-print-ast (js2-call-node-target n) 0)
3632 (insert "(")
3633 (js2-print-list (js2-call-node-args n))
3634 (insert ")"))
3635
3636 (defstruct (js2-yield-node
3637 (:include js2-node)
3638 (:constructor nil)
3639 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3640 (pos js2-ts-cursor)
3641 len value star-p)))
3642 "AST node for yield statement or expression."
3643 star-p ; whether it's yield*
3644 value) ; optional: value to be yielded
3645
3646 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3647 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3648
3649 (defun js2-visit-yield-node (n v)
3650 (js2-visit-ast (js2-yield-node-value n) v))
3651
3652 (defun js2-print-yield-node (n i)
3653 (insert (js2-make-pad i))
3654 (insert "yield")
3655 (when (js2-yield-node-star-p n)
3656 (insert "*"))
3657 (when (js2-yield-node-value n)
3658 (insert " ")
3659 (js2-print-ast (js2-yield-node-value n) 0)))
3660
3661 (defstruct (js2-paren-node
3662 (:include js2-node)
3663 (:constructor nil)
3664 (:constructor make-js2-paren-node (&key (type js2-LP)
3665 (pos js2-ts-cursor)
3666 len expr)))
3667 "AST node for a parenthesized expression.
3668 In particular, used when the parens are syntactically optional,
3669 as opposed to required parens such as those enclosing an if-conditional."
3670 expr) ; `js2-node'
3671
3672 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3673 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3674
3675 (defun js2-visit-paren-node (n v)
3676 (js2-visit-ast (js2-paren-node-expr n) v))
3677
3678 (defun js2-print-paren-node (n i)
3679 (insert (js2-make-pad i))
3680 (insert "(")
3681 (js2-print-ast (js2-paren-node-expr n) 0)
3682 (insert ")"))
3683
3684 (defstruct (js2-comp-node
3685 (:include js2-scope)
3686 (:constructor nil)
3687 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
3688 (pos js2-ts-cursor)
3689 len result
3690 loops filters
3691 form)))
3692 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3693 result ; result expression (just after left-bracket)
3694 loops ; a Lisp list of `js2-comp-loop-node'
3695 filters ; a Lisp list of guard/filter expressions
3696 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
3697 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
3698 )
3699
3700 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
3701 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
3702
3703 (defun js2-visit-comp-node (n v)
3704 (js2-visit-ast (js2-comp-node-result n) v)
3705 (dolist (l (js2-comp-node-loops n))
3706 (js2-visit-ast l v))
3707 (dolist (f (js2-comp-node-filters n))
3708 (js2-visit-ast f v)))
3709
3710 (defun js2-print-comp-node (n i)
3711 (let ((pad (js2-make-pad i))
3712 (result (js2-comp-node-result n))
3713 (loops (js2-comp-node-loops n))
3714 (filters (js2-comp-node-filters n))
3715 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
3716 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
3717 (insert pad (if gen-p "(" "["))
3718 (when legacy-p
3719 (js2-print-ast result 0))
3720 (dolist (l loops)
3721 (when legacy-p
3722 (insert " "))
3723 (js2-print-ast l 0)
3724 (unless legacy-p
3725 (insert " ")))
3726 (dolist (f filters)
3727 (when legacy-p
3728 (insert " "))
3729 (insert "if (")
3730 (js2-print-ast f 0)
3731 (insert ")")
3732 (unless legacy-p
3733 (insert " ")))
3734 (unless legacy-p
3735 (js2-print-ast result 0))
3736 (insert (if gen-p ")" "]"))))
3737
3738 (defstruct (js2-comp-loop-node
3739 (:include js2-for-in-node)
3740 (:constructor nil)
3741 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
3742 (pos js2-ts-cursor)
3743 len iterator
3744 object in-pos
3745 foreach-p
3746 each-pos
3747 forof-p
3748 lp rp)))
3749 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3750
3751 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
3752 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
3753
3754 (defun js2-visit-comp-loop (n v)
3755 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
3756 (js2-visit-ast (js2-comp-loop-node-object n) v))
3757
3758 (defun js2-print-comp-loop (n _i)
3759 (insert "for ")
3760 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
3761 (insert "(")
3762 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
3763 (insert (if (js2-comp-loop-node-forof-p n)
3764 " of " " in "))
3765 (js2-print-ast (js2-comp-loop-node-object n) 0)
3766 (insert ")"))
3767
3768 (defstruct (js2-empty-expr-node
3769 (:include js2-node)
3770 (:constructor nil)
3771 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3772 (pos (js2-current-token-beg))
3773 len)))
3774 "AST node for an empty expression.")
3775
3776 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3777 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3778
3779 (defstruct (js2-xml-node
3780 (:include js2-block-node)
3781 (:constructor nil)
3782 (:constructor make-js2-xml-node (&key (type js2-XML)
3783 (pos (js2-current-token-beg))
3784 len kids)))
3785 "AST node for initial parse of E4X literals.
3786 The kids field is a list of XML fragments, each a `js2-string-node' or
3787 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3788
3789 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3790 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3791
3792 (defun js2-print-xml-node (n i)
3793 (dolist (kid (js2-xml-node-kids n))
3794 (js2-print-ast kid i)))
3795
3796 (defstruct (js2-xml-js-expr-node
3797 (:include js2-xml-node)
3798 (:constructor nil)
3799 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3800 (pos js2-ts-cursor)
3801 len expr)))
3802 "AST node for an embedded JavaScript {expression} in an E4X literal.
3803 The start and end fields correspond to the curly-braces."
3804 expr) ; a `js2-expr-node' of some sort
3805
3806 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3807 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3808
3809 (defun js2-visit-xml-js-expr (n v)
3810 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3811
3812 (defun js2-print-xml-js-expr (n i)
3813 (insert (js2-make-pad i))
3814 (insert "{")
3815 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3816 (insert "}"))
3817
3818 (defstruct (js2-xml-dot-query-node
3819 (:include js2-infix-node)
3820 (:constructor nil)
3821 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3822 (pos js2-ts-cursor)
3823 op-pos len left
3824 right rp)))
3825 "AST node for an E4X foo.(bar) filter expression.
3826 Note that the left-paren is automatically the character immediately
3827 following the dot (.) in the operator. No whitespace is permitted
3828 between the dot and the lp by the scanner."
3829 rp)
3830
3831 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3832 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3833
3834 (defun js2-print-xml-dot-query (n i)
3835 (insert (js2-make-pad i))
3836 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3837 (insert ".(")
3838 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3839 (insert ")"))
3840
3841 (defstruct (js2-xml-ref-node
3842 (:include js2-node)
3843 (:constructor nil)) ; abstract
3844 "Base type for E4X XML attribute-access or property-get expressions.
3845 Such expressions can take a variety of forms. The general syntax has
3846 three parts:
3847
3848 - (optional) an @ (specifying an attribute access)
3849 - (optional) a namespace (a `js2-name-node') and double-colon
3850 - (required) either a `js2-name-node' or a bracketed [expression]
3851
3852 The property-name expressions (examples: ns::name, @name) are
3853 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3854 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3855
3856 This node type (or more specifically, its subclasses) will sometimes
3857 be the right-hand child of a `js2-prop-get-node' or a
3858 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3859 The `js2-xml-ref-node' may also be a standalone primary expression with
3860 no explicit target, which is valid in certain expression contexts such as
3861
3862 company..employee.(@id < 100)
3863
3864 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3865 expression whose parent is a `js2-xml-dot-query-node'."
3866 namespace
3867 at-pos
3868 colon-pos)
3869
3870 (defsubst js2-xml-ref-node-attr-access-p (node)
3871 "Return non-nil if this expression began with an @-token."
3872 (and (numberp (js2-xml-ref-node-at-pos node))
3873 (plusp (js2-xml-ref-node-at-pos node))))
3874
3875 (defstruct (js2-xml-prop-ref-node
3876 (:include js2-xml-ref-node)
3877 (:constructor nil)
3878 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3879 (pos (js2-current-token-beg))
3880 len propname
3881 namespace at-pos
3882 colon-pos)))
3883 "AST node for an E4X XML [expr] property-ref expression.
3884 The JavaScript syntax is an optional @, an optional ns::, and a name.
3885
3886 [ '@' ] [ name '::' ] name
3887
3888 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3889 @ns::*, @*::attr, @*::*, and @*.
3890
3891 The node starts at the @ token, if present. Otherwise it starts at the
3892 namespace name. The node bounds extend through the closing right-bracket,
3893 or if it is missing due to a syntax error, through the end of the index
3894 expression."
3895 propname)
3896
3897 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3898 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3899
3900 (defun js2-visit-xml-prop-ref-node (n v)
3901 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3902 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3903
3904 (defun js2-print-xml-prop-ref-node (n i)
3905 (insert (js2-make-pad i))
3906 (if (js2-xml-ref-node-attr-access-p n)
3907 (insert "@"))
3908 (when (js2-xml-prop-ref-node-namespace n)
3909 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3910 (insert "::"))
3911 (if (js2-xml-prop-ref-node-propname n)
3912 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3913
3914 (defstruct (js2-xml-elem-ref-node
3915 (:include js2-xml-ref-node)
3916 (:constructor nil)
3917 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3918 (pos (js2-current-token-beg))
3919 len expr lb rb
3920 namespace at-pos
3921 colon-pos)))
3922 "AST node for an E4X XML [expr] member-ref expression.
3923 Syntax:
3924
3925 [ '@' ] [ name '::' ] '[' expr ']'
3926
3927 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3928
3929 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3930 is not a legal E4X XML element-ref expression, since it's already used
3931 for standard JavaScript element-get array indexing. Hence, a
3932 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3933 non-nil namespace node, or both.
3934
3935 The node starts at the @ token, if present. Otherwise it starts
3936 at the namespace name. The node bounds extend through the closing
3937 right-bracket, or if it is missing due to a syntax error, through the
3938 end of the index expression."
3939 expr ; the bracketed index expression
3940 lb
3941 rb)
3942
3943 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3944 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3945
3946 (defun js2-visit-xml-elem-ref-node (n v)
3947 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3948 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3949
3950 (defun js2-print-xml-elem-ref-node (n i)
3951 (insert (js2-make-pad i))
3952 (if (js2-xml-ref-node-attr-access-p n)
3953 (insert "@"))
3954 (when (js2-xml-elem-ref-node-namespace n)
3955 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3956 (insert "::"))
3957 (insert "[")
3958 (if (js2-xml-elem-ref-node-expr n)
3959 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3960 (insert "]"))
3961
3962 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3963
3964 (defstruct (js2-xml-start-tag-node
3965 (:include js2-xml-node)
3966 (:constructor nil)
3967 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3968 (pos js2-ts-cursor)
3969 len name attrs kids
3970 empty-p)))
3971 "AST node for an XML start-tag. Not currently used.
3972 The `kids' field is a Lisp list of child content nodes."
3973 name ; a `js2-xml-name-node'
3974 attrs ; a Lisp list of `js2-xml-attr-node'
3975 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3976
3977 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3978 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3979
3980 (defun js2-visit-xml-start-tag (n v)
3981 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3982 (dolist (attr (js2-xml-start-tag-node-attrs n))
3983 (js2-visit-ast attr v))
3984 (js2-visit-block n v))
3985
3986 (defun js2-print-xml-start-tag (n i)
3987 (insert (js2-make-pad i) "<")
3988 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3989 (when (js2-xml-start-tag-node-attrs n)
3990 (insert " ")
3991 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3992 (insert ">"))
3993
3994 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3995 ;; and add the end-tag to the kids list of the parent as well.
3996 (defstruct (js2-xml-end-tag-node
3997 (:include js2-xml-node)
3998 (:constructor nil)
3999 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4000 (pos js2-ts-cursor)
4001 len name)))
4002 "AST node for an XML end-tag. Not currently used."
4003 name) ; a `js2-xml-name-node'
4004
4005 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4006 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4007
4008 (defun js2-visit-xml-end-tag (n v)
4009 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4010
4011 (defun js2-print-xml-end-tag (n i)
4012 (insert (js2-make-pad i))
4013 (insert "</")
4014 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4015 (insert ">"))
4016
4017 (defstruct (js2-xml-name-node
4018 (:include js2-xml-node)
4019 (:constructor nil)
4020 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4021 (pos js2-ts-cursor)
4022 len namespace kids)))
4023 "AST node for an E4X XML name. Not currently used.
4024 Any XML name can be qualified with a namespace, hence the namespace field.
4025 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4026 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4027 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4028 namespace) ; a `js2-string-node'
4029
4030 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4031 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4032
4033 (defun js2-visit-xml-name-node (n v)
4034 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4035
4036 (defun js2-print-xml-name-node (n i)
4037 (insert (js2-make-pad i))
4038 (when (js2-xml-name-node-namespace n)
4039 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4040 (insert "::"))
4041 (dolist (kid (js2-xml-name-node-kids n))
4042 (js2-print-ast kid 0)))
4043
4044 (defstruct (js2-xml-pi-node
4045 (:include js2-xml-node)
4046 (:constructor nil)
4047 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4048 (pos js2-ts-cursor)
4049 len name attrs)))
4050 "AST node for an E4X XML processing instruction. Not currently used."
4051 name ; a `js2-xml-name-node'
4052 attrs) ; a list of `js2-xml-attr-node'
4053
4054 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4055 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4056
4057 (defun js2-visit-xml-pi-node (n v)
4058 (js2-visit-ast (js2-xml-pi-node-name n) v)
4059 (dolist (attr (js2-xml-pi-node-attrs n))
4060 (js2-visit-ast attr v)))
4061
4062 (defun js2-print-xml-pi-node (n i)
4063 (insert (js2-make-pad i) "<?")
4064 (js2-print-ast (js2-xml-pi-node-name n))
4065 (when (js2-xml-pi-node-attrs n)
4066 (insert " ")
4067 (js2-print-list (js2-xml-pi-node-attrs n)))
4068 (insert "?>"))
4069
4070 (defstruct (js2-xml-cdata-node
4071 (:include js2-xml-node)
4072 (:constructor nil)
4073 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4074 (pos js2-ts-cursor)
4075 len content)))
4076 "AST node for a CDATA escape section. Not currently used."
4077 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4078
4079 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4080 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4081
4082 (defun js2-visit-xml-cdata-node (n v)
4083 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4084
4085 (defun js2-print-xml-cdata-node (n i)
4086 (insert (js2-make-pad i))
4087 (js2-print-ast (js2-xml-cdata-node-content n)))
4088
4089 (defstruct (js2-xml-attr-node
4090 (:include js2-xml-node)
4091 (:constructor nil)
4092 (:constructor make-js2-attr-node (&key (type js2-XML)
4093 (pos js2-ts-cursor)
4094 len name value
4095 eq-pos quote-type)))
4096 "AST node representing a foo='bar' XML attribute value. Not yet used."
4097 name ; a `js2-xml-name-node'
4098 value ; a `js2-xml-name-node'
4099 eq-pos ; buffer position of "=" sign
4100 quote-type) ; 'single or 'double
4101
4102 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4103 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4104
4105 (defun js2-visit-xml-attr-node (n v)
4106 (js2-visit-ast (js2-xml-attr-node-name n) v)
4107 (js2-visit-ast (js2-xml-attr-node-value n) v))
4108
4109 (defun js2-print-xml-attr-node (n i)
4110 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4111 "'"
4112 "\"")))
4113 (insert (js2-make-pad i))
4114 (js2-print-ast (js2-xml-attr-node-name n) 0)
4115 (insert "=" quote)
4116 (js2-print-ast (js2-xml-attr-node-value n) 0)
4117 (insert quote)))
4118
4119 (defstruct (js2-xml-text-node
4120 (:include js2-xml-node)
4121 (:constructor nil)
4122 (:constructor make-js2-text-node (&key (type js2-XML)
4123 (pos js2-ts-cursor)
4124 len content)))
4125 "AST node for an E4X XML text node. Not currently used."
4126 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4127
4128 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4129 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4130
4131 (defun js2-visit-xml-text-node (n v)
4132 (js2-visit-ast (js2-xml-text-node-content n) v))
4133
4134 (defun js2-print-xml-text-node (n i)
4135 (insert (js2-make-pad i))
4136 (dolist (kid (js2-xml-text-node-content n))
4137 (js2-print-ast kid)))
4138
4139 (defstruct (js2-xml-comment-node
4140 (:include js2-xml-node)
4141 (:constructor nil)
4142 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4143 (pos js2-ts-cursor)
4144 len)))
4145 "AST node for E4X XML comment. Not currently used.")
4146
4147 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4148 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4149
4150 (defun js2-print-xml-comment (n i)
4151 (insert (js2-make-pad i)
4152 (js2-node-string n)))
4153
4154 ;;; Node utilities
4155
4156 (defsubst js2-node-line (n)
4157 "Fetch the source line number at the start of node N.
4158 This is O(n) in the length of the source buffer; use prudently."
4159 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4160
4161 (defsubst js2-block-node-kid (n i)
4162 "Return child I of node N, or nil if there aren't that many."
4163 (nth i (js2-block-node-kids n)))
4164
4165 (defsubst js2-block-node-first (n)
4166 "Return first child of block node N, or nil if there is none."
4167 (first (js2-block-node-kids n)))
4168
4169 (defun js2-node-root (n)
4170 "Return the root of the AST containing N.
4171 If N has no parent pointer, returns N."
4172 (let ((parent (js2-node-parent n)))
4173 (if parent
4174 (js2-node-root parent)
4175 n)))
4176
4177 (defsubst js2-node-short-name (n)
4178 "Return the short name of node N as a string, e.g. `js2-if-node'."
4179 (substring (symbol-name (aref n 0))
4180 (length "cl-struct-")))
4181
4182 (defun js2-node-child-list (node)
4183 "Return the child list for NODE, a Lisp list of nodes.
4184 Works for block nodes, array nodes, obj literals, funarg lists,
4185 var decls and try nodes (for catch clauses). Note that you should call
4186 `js2-block-node-kids' on the function body for the body statements.
4187 Returns nil for zero-length child lists or unsupported nodes."
4188 (cond
4189 ((js2-function-node-p node)
4190 (js2-function-node-params node))
4191 ((js2-block-node-p node)
4192 (js2-block-node-kids node))
4193 ((js2-try-node-p node)
4194 (js2-try-node-catch-clauses node))
4195 ((js2-array-node-p node)
4196 (js2-array-node-elems node))
4197 ((js2-object-node-p node)
4198 (js2-object-node-elems node))
4199 ((js2-call-node-p node)
4200 (js2-call-node-args node))
4201 ((js2-new-node-p node)
4202 (js2-new-node-args node))
4203 ((js2-var-decl-node-p node)
4204 (js2-var-decl-node-kids node))
4205 (t
4206 nil)))
4207
4208 (defun js2-node-set-child-list (node kids)
4209 "Set the child list for NODE to KIDS."
4210 (cond
4211 ((js2-function-node-p node)
4212 (setf (js2-function-node-params node) kids))
4213 ((js2-block-node-p node)
4214 (setf (js2-block-node-kids node) kids))
4215 ((js2-try-node-p node)
4216 (setf (js2-try-node-catch-clauses node) kids))
4217 ((js2-array-node-p node)
4218 (setf (js2-array-node-elems node) kids))
4219 ((js2-object-node-p node)
4220 (setf (js2-object-node-elems node) kids))
4221 ((js2-call-node-p node)
4222 (setf (js2-call-node-args node) kids))
4223 ((js2-new-node-p node)
4224 (setf (js2-new-node-args node) kids))
4225 ((js2-var-decl-node-p node)
4226 (setf (js2-var-decl-node-kids node) kids))
4227 (t
4228 (error "Unsupported node type: %s" (js2-node-short-name node))))
4229 kids)
4230
4231 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4232 (defconst js2-paren-expr-nodes
4233 '(cl-struct-js2-comp-loop-node
4234 cl-struct-js2-comp-node
4235 cl-struct-js2-call-node
4236 cl-struct-js2-catch-node
4237 cl-struct-js2-do-node
4238 cl-struct-js2-elem-get-node
4239 cl-struct-js2-for-in-node
4240 cl-struct-js2-for-node
4241 cl-struct-js2-function-node
4242 cl-struct-js2-if-node
4243 cl-struct-js2-let-node
4244 cl-struct-js2-new-node
4245 cl-struct-js2-paren-node
4246 cl-struct-js2-switch-node
4247 cl-struct-js2-while-node
4248 cl-struct-js2-with-node
4249 cl-struct-js2-xml-dot-query-node)
4250 "Node types that can have a parenthesized child expression.
4251 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4252
4253 (defsubst js2-paren-expr-node-p (node)
4254 "Return t for nodes that typically have a parenthesized child expression.
4255 Useful for computing the indentation anchors for arg-lists and conditions.
4256 Note that it may return a false positive, for instance when NODE is
4257 a `js2-new-node' and there are no arguments or parentheses."
4258 (memq (aref node 0) js2-paren-expr-nodes))
4259
4260 ;; Fake polymorphism... yech.
4261 (defun js2-node-lp (node)
4262 "Return relative left-paren position for NODE, if applicable.
4263 For `js2-elem-get-node' structs, returns left-bracket position.
4264 Note that the position may be nil in the case of a parse error."
4265 (cond
4266 ((js2-elem-get-node-p node)
4267 (js2-elem-get-node-lb node))
4268 ((js2-loop-node-p node)
4269 (js2-loop-node-lp node))
4270 ((js2-function-node-p node)
4271 (js2-function-node-lp node))
4272 ((js2-if-node-p node)
4273 (js2-if-node-lp node))
4274 ((js2-new-node-p node)
4275 (js2-new-node-lp node))
4276 ((js2-call-node-p node)
4277 (js2-call-node-lp node))
4278 ((js2-paren-node-p node)
4279 0)
4280 ((js2-switch-node-p node)
4281 (js2-switch-node-lp node))
4282 ((js2-catch-node-p node)
4283 (js2-catch-node-lp node))
4284 ((js2-let-node-p node)
4285 (js2-let-node-lp node))
4286 ((js2-comp-node-p node)
4287 0)
4288 ((js2-with-node-p node)
4289 (js2-with-node-lp node))
4290 ((js2-xml-dot-query-node-p node)
4291 (1+ (js2-infix-node-op-pos node)))
4292 (t
4293 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4294
4295 ;; Fake polymorphism... blech.
4296 (defun js2-node-rp (node)
4297 "Return relative right-paren position for NODE, if applicable.
4298 For `js2-elem-get-node' structs, returns right-bracket position.
4299 Note that the position may be nil in the case of a parse error."
4300 (cond
4301 ((js2-elem-get-node-p node)
4302 (js2-elem-get-node-rb node))
4303 ((js2-loop-node-p node)
4304 (js2-loop-node-rp node))
4305 ((js2-function-node-p node)
4306 (js2-function-node-rp node))
4307 ((js2-if-node-p node)
4308 (js2-if-node-rp node))
4309 ((js2-new-node-p node)
4310 (js2-new-node-rp node))
4311 ((js2-call-node-p node)
4312 (js2-call-node-rp node))
4313 ((js2-paren-node-p node)
4314 (1- (js2-node-len node)))
4315 ((js2-switch-node-p node)
4316 (js2-switch-node-rp node))
4317 ((js2-catch-node-p node)
4318 (js2-catch-node-rp node))
4319 ((js2-let-node-p node)
4320 (js2-let-node-rp node))
4321 ((js2-comp-node-p node)
4322 (1- (js2-node-len node)))
4323 ((js2-with-node-p node)
4324 (js2-with-node-rp node))
4325 ((js2-xml-dot-query-node-p node)
4326 (1+ (js2-xml-dot-query-node-rp node)))
4327 (t
4328 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4329
4330 (defsubst js2-node-first-child (node)
4331 "Return the first element of `js2-node-child-list' for NODE."
4332 (car (js2-node-child-list node)))
4333
4334 (defsubst js2-node-last-child (node)
4335 "Return the last element of `js2-node-last-child' for NODE."
4336 (car (last (js2-node-child-list node))))
4337
4338 (defun js2-node-prev-sibling (node)
4339 "Return the previous statement in parent.
4340 Works for parents supported by `js2-node-child-list'.
4341 Returns nil if NODE is not in the parent, or PARENT is
4342 not a supported node, or if NODE is the first child."
4343 (let* ((p (js2-node-parent node))
4344 (kids (js2-node-child-list p))
4345 (sib (car kids)))
4346 (while (and kids
4347 (not (eq node (cadr kids))))
4348 (setq kids (cdr kids)
4349 sib (car kids)))
4350 sib))
4351
4352 (defun js2-node-next-sibling (node)
4353 "Return the next statement in parent block.
4354 Returns nil if NODE is not in the block, or PARENT is not
4355 a block node, or if NODE is the last statement."
4356 (let* ((p (js2-node-parent node))
4357 (kids (js2-node-child-list p)))
4358 (while (and kids
4359 (not (eq node (car kids))))
4360 (setq kids (cdr kids)))
4361 (cadr kids)))
4362
4363 (defun js2-node-find-child-before (pos parent &optional after)
4364 "Find the last child that starts before POS in parent.
4365 If AFTER is non-nil, returns first child starting after POS.
4366 POS is an absolute buffer position. PARENT is any node
4367 supported by `js2-node-child-list'.
4368 Returns nil if no applicable child is found."
4369 (let ((kids (if (js2-function-node-p parent)
4370 (js2-block-node-kids (js2-function-node-body parent))
4371 (js2-node-child-list parent)))
4372 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4373 (js2-function-node-body parent)
4374 parent)))
4375 kid result fn
4376 (continue t))
4377 (setq fn (if after '>= '<))
4378 (while (and kids continue)
4379 (setq kid (car kids))
4380 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4381 (setq result kid
4382 continue (not after))
4383 (setq continue after))
4384 (setq kids (cdr kids)))
4385 result))
4386
4387 (defun js2-node-find-child-after (pos parent)
4388 "Find first child that starts after POS in parent.
4389 POS is an absolute buffer position. PARENT is any node
4390 supported by `js2-node-child-list'.
4391 Returns nil if no applicable child is found."
4392 (js2-node-find-child-before pos parent 'after))
4393
4394 (defun js2-node-replace-child (pos parent new-node)
4395 "Replace node at index POS in PARENT with NEW-NODE.
4396 Only works for parents supported by `js2-node-child-list'."
4397 (let ((kids (js2-node-child-list parent))
4398 (i 0))
4399 (while (< i pos)
4400 (setq kids (cdr kids)
4401 i (1+ i)))
4402 (setcar kids new-node)
4403 (js2-node-add-children parent new-node)))
4404
4405 (defun js2-node-buffer (n)
4406 "Return the buffer associated with AST N.
4407 Returns nil if the buffer is not set as a property on the root
4408 node, or if parent links were not recorded during parsing."
4409 (let ((root (js2-node-root n)))
4410 (and root
4411 (js2-ast-root-p root)
4412 (js2-ast-root-buffer root))))
4413
4414 (defun js2-block-node-push (n kid)
4415 "Push js2-node KID onto the end of js2-block-node N's child list.
4416 KID is always added to the -end- of the kids list.
4417 Function also calls `js2-node-add-children' to add the parent link."
4418 (let ((kids (js2-node-child-list n)))
4419 (if kids
4420 (setcdr kids (nconc (cdr kids) (list kid)))
4421 (js2-node-set-child-list n (list kid)))
4422 (js2-node-add-children n kid)))
4423
4424 (defun js2-node-string (node)
4425 (with-current-buffer (or (js2-node-buffer node)
4426 (error "No buffer available for node %s" node))
4427 (let ((pos (js2-node-abs-pos node)))
4428 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4429
4430 ;; Container for storing the node we're looking for in a traversal.
4431 (js2-deflocal js2-discovered-node nil)
4432
4433 ;; Keep track of absolute node position during traversals.
4434 (js2-deflocal js2-visitor-offset nil)
4435
4436 (js2-deflocal js2-node-search-point nil)
4437
4438 (when js2-mode-dev-mode-p
4439 (defun js2-find-node-at-point ()
4440 (interactive)
4441 (let ((node (js2-node-at-point)))
4442 (message "%s" (or node "No node found at point"))))
4443 (defun js2-node-name-at-point ()
4444 (interactive)
4445 (let ((node (js2-node-at-point)))
4446 (message "%s" (if node
4447 (js2-node-short-name node)
4448 "No node found at point.")))))
4449
4450 (defun js2-node-at-point (&optional pos skip-comments)
4451 "Return AST node at POS, a buffer position, defaulting to current point.
4452 The `js2-mode-ast' variable must be set to the current parse tree.
4453 Signals an error if the AST (`js2-mode-ast') is nil.
4454 Always returns a node - if it can't find one, it returns the root.
4455 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4456 (let ((ast js2-mode-ast)
4457 result)
4458 (unless ast
4459 (error "No JavaScript AST available"))
4460 ;; Look through comments first, since they may be inside nodes that
4461 ;; would otherwise report a match.
4462 (setq pos (or pos (point))
4463 result (if (> pos (js2-node-abs-end ast))
4464 ast
4465 (if (not skip-comments)
4466 (js2-comment-at-point pos))))
4467 (unless result
4468 (setq js2-discovered-node nil
4469 js2-visitor-offset 0
4470 js2-node-search-point pos)
4471 (unwind-protect
4472 (catch 'js2-visit-done
4473 (js2-visit-ast ast #'js2-node-at-point-visitor))
4474 (setq js2-visitor-offset nil
4475 js2-node-search-point nil))
4476 (setq result js2-discovered-node))
4477 ;; may have found a comment beyond end of last child node,
4478 ;; since visiting the ast-root looks at the comment-list last.
4479 (if (and skip-comments
4480 (js2-comment-node-p result))
4481 (setq result nil))
4482 (or result js2-mode-ast)))
4483
4484 (defun js2-node-at-point-visitor (node end-p)
4485 (let ((rel-pos (js2-node-pos node))
4486 abs-pos
4487 abs-end
4488 (point js2-node-search-point))
4489 (cond
4490 (end-p
4491 ;; this evaluates to a non-nil return value, even if it's zero
4492 (decf js2-visitor-offset rel-pos))
4493 ;; we already looked for comments before visiting, and don't want them now
4494 ((js2-comment-node-p node)
4495 nil)
4496 (t
4497 (setq abs-pos (incf js2-visitor-offset rel-pos)
4498 ;; we only want to use the node if the point is before
4499 ;; the last character position in the node, so we decrement
4500 ;; the absolute end by 1.
4501 abs-end (+ abs-pos (js2-node-len node) -1))
4502 (cond
4503 ;; If this node starts after search-point, stop the search.
4504 ((> abs-pos point)
4505 (throw 'js2-visit-done nil))
4506 ;; If this node ends before the search-point, don't check kids.
4507 ((> point abs-end)
4508 nil)
4509 (t
4510 ;; Otherwise point is within this node, possibly in a child.
4511 (setq js2-discovered-node node)
4512 t)))))) ; keep processing kids to look for more specific match
4513
4514 (defsubst js2-block-comment-p (node)
4515 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4516 (and (js2-comment-node-p node)
4517 (memq (js2-comment-node-format node) '(jsdoc block))))
4518
4519 ;; TODO: put the comments in a vector and binary-search them instead
4520 (defun js2-comment-at-point (&optional pos)
4521 "Look through scanned comment nodes for one containing POS.
4522 POS is a buffer position that defaults to current point.
4523 Function returns nil if POS was not in any comment node."
4524 (let ((ast js2-mode-ast)
4525 (x (or pos (point)))
4526 beg end)
4527 (unless ast
4528 (error "No JavaScript AST available"))
4529 (catch 'done
4530 ;; Comments are stored in lexical order.
4531 (dolist (comment (js2-ast-root-comments ast) nil)
4532 (setq beg (js2-node-abs-pos comment)
4533 end (+ beg (js2-node-len comment)))
4534 (if (and (>= x beg)
4535 (<= x end))
4536 (throw 'done comment))))))
4537
4538 (defun js2-mode-find-parent-fn (node)
4539 "Find function enclosing NODE.
4540 Returns nil if NODE is not inside a function."
4541 (setq node (js2-node-parent node))
4542 (while (and node (not (js2-function-node-p node)))
4543 (setq node (js2-node-parent node)))
4544 (and (js2-function-node-p node) node))
4545
4546 (defun js2-mode-find-enclosing-fn (node)
4547 "Find function or root enclosing NODE."
4548 (if (js2-ast-root-p node)
4549 node
4550 (setq node (js2-node-parent node))
4551 (while (not (or (js2-ast-root-p node)
4552 (js2-function-node-p node)))
4553 (setq node (js2-node-parent node)))
4554 node))
4555
4556 (defun js2-mode-find-enclosing-node (beg end)
4557 "Find node fully enclosing BEG and END."
4558 (let ((node (js2-node-at-point beg))
4559 pos
4560 (continue t))
4561 (while continue
4562 (if (or (js2-ast-root-p node)
4563 (and
4564 (<= (setq pos (js2-node-abs-pos node)) beg)
4565 (>= (+ pos (js2-node-len node)) end)))
4566 (setq continue nil)
4567 (setq node (js2-node-parent node))))
4568 node))
4569
4570 (defun js2-node-parent-script-or-fn (node)
4571 "Find script or function immediately enclosing NODE.
4572 If NODE is the ast-root, returns nil."
4573 (if (js2-ast-root-p node)
4574 nil
4575 (setq node (js2-node-parent node))
4576 (while (and node (not (or (js2-function-node-p node)
4577 (js2-script-node-p node))))
4578 (setq node (js2-node-parent node)))
4579 node))
4580
4581 (defun js2-node-is-descendant (node ancestor)
4582 "Return t if NODE is a descendant of ANCESTOR."
4583 (while (and node
4584 (not (eq node ancestor)))
4585 (setq node (js2-node-parent node)))
4586 node)
4587
4588 ;;; visitor infrastructure
4589
4590 (defun js2-visit-none (_node _callback)
4591 "Visitor for AST node that have no node children."
4592 nil)
4593
4594 (defun js2-print-none (_node _indent)
4595 "Visitor for AST node with no printed representation.")
4596
4597 (defun js2-print-body (node indent)
4598 "Print a statement, or a block without braces."
4599 (if (js2-block-node-p node)
4600 (dolist (kid (js2-block-node-kids node))
4601 (js2-print-ast kid indent))
4602 (js2-print-ast node indent)))
4603
4604 (defun js2-print-list (args &optional delimiter)
4605 (loop with len = (length args)
4606 for arg in args
4607 for count from 1
4608 do
4609 (when arg (js2-print-ast arg 0))
4610 (if (< count len)
4611 (insert (or delimiter ", ")))))
4612
4613 (defun js2-print-tree (ast)
4614 "Prints an AST to the current buffer.
4615 Makes `js2-ast-parent-nodes' available to the printer functions."
4616 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4617 (js2-print-ast ast)))
4618
4619 (defun js2-print-ast (node &optional indent)
4620 "Helper function for printing AST nodes.
4621 Requires `js2-ast-parent-nodes' to be non-nil.
4622 You should use `js2-print-tree' instead of this function."
4623 (let ((printer (get (aref node 0) 'js2-printer))
4624 (i (or indent 0)))
4625 ;; TODO: wedge comments in here somewhere
4626 (if printer
4627 (funcall printer node i))))
4628
4629 (defconst js2-side-effecting-tokens
4630 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4631 (dolist (tt (list js2-ASSIGN
4632 js2-ASSIGN_ADD
4633 js2-ASSIGN_BITAND
4634 js2-ASSIGN_BITOR
4635 js2-ASSIGN_BITXOR
4636 js2-ASSIGN_DIV
4637 js2-ASSIGN_LSH
4638 js2-ASSIGN_MOD
4639 js2-ASSIGN_MUL
4640 js2-ASSIGN_RSH
4641 js2-ASSIGN_SUB
4642 js2-ASSIGN_URSH
4643 js2-BLOCK
4644 js2-BREAK
4645 js2-CALL
4646 js2-CATCH
4647 js2-CATCH_SCOPE
4648 js2-CONST
4649 js2-CONTINUE
4650 js2-DEBUGGER
4651 js2-DEC
4652 js2-DELPROP
4653 js2-DEL_REF
4654 js2-DO
4655 js2-ELSE
4656 js2-EMPTY
4657 js2-ENTERWITH
4658 js2-EXPORT
4659 js2-EXPR_RESULT
4660 js2-FINALLY
4661 js2-FOR
4662 js2-FUNCTION
4663 js2-GOTO
4664 js2-IF
4665 js2-IFEQ
4666 js2-IFNE
4667 js2-IMPORT
4668 js2-INC
4669 js2-JSR
4670 js2-LABEL
4671 js2-LEAVEWITH
4672 js2-LET
4673 js2-LETEXPR
4674 js2-LOCAL_BLOCK
4675 js2-LOOP
4676 js2-NEW
4677 js2-REF_CALL
4678 js2-RETHROW
4679 js2-RETURN
4680 js2-RETURN_RESULT
4681 js2-SEMI
4682 js2-SETELEM
4683 js2-SETELEM_OP
4684 js2-SETNAME
4685 js2-SETPROP
4686 js2-SETPROP_OP
4687 js2-SETVAR
4688 js2-SET_REF
4689 js2-SET_REF_OP
4690 js2-SWITCH
4691 js2-TARGET
4692 js2-THROW
4693 js2-TRY
4694 js2-VAR
4695 js2-WHILE
4696 js2-WITH
4697 js2-WITHEXPR
4698 js2-YIELD))
4699 (aset tokens tt t))
4700 (if js2-instanceof-has-side-effects
4701 (aset tokens js2-INSTANCEOF t))
4702 tokens))
4703
4704 (defun js2-node-has-side-effects (node)
4705 "Return t if NODE has side effects."
4706 (when node ; makes it easier to handle malformed expressions
4707 (let ((tt (js2-node-type node)))
4708 (cond
4709 ;; This doubtless needs some work, since EXPR_VOID is used
4710 ;; in several ways in Rhino and I may not have caught them all.
4711 ;; I'll wait for people to notice incorrect warnings.
4712 ((and (= tt js2-EXPR_VOID)
4713 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4714 (let ((expr (js2-expr-stmt-node-expr node)))
4715 (or (js2-node-has-side-effects expr)
4716 (when (js2-string-node-p expr)
4717 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4718 ((= tt js2-COMMA)
4719 (js2-node-has-side-effects (js2-infix-node-right node)))
4720 ((or (= tt js2-AND)
4721 (= tt js2-OR))
4722 (or (js2-node-has-side-effects (js2-infix-node-right node))
4723 (js2-node-has-side-effects (js2-infix-node-left node))))
4724 ((= tt js2-HOOK)
4725 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4726 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4727 ((js2-paren-node-p node)
4728 (js2-node-has-side-effects (js2-paren-node-expr node)))
4729 ((= tt js2-ERROR) ; avoid cascaded error messages
4730 nil)
4731 (t
4732 (aref js2-side-effecting-tokens tt))))))
4733
4734 (defconst js2-stmt-node-types
4735 (list js2-BLOCK
4736 js2-BREAK
4737 js2-CONTINUE
4738 js2-DEFAULT ; e4x "default xml namespace" statement
4739 js2-DO
4740 js2-EXPR_RESULT
4741 js2-EXPR_VOID
4742 js2-FOR
4743 js2-IF
4744 js2-RETURN
4745 js2-SWITCH
4746 js2-THROW
4747 js2-TRY
4748 js2-WHILE
4749 js2-WITH)
4750 "Node types that only appear in statement contexts.
4751 The list does not include nodes that always appear as the child
4752 of another specific statement type, such as switch-cases,
4753 catch and finally blocks, and else-clauses. The list also excludes
4754 nodes like yield, let and var, which may appear in either expression
4755 or statement context, and in the latter context always have a
4756 `js2-expr-stmt-node' parent. Finally, the list does not include
4757 functions or scripts, which are treated separately from statements
4758 by the JavaScript parser and runtime.")
4759
4760 (defun js2-stmt-node-p (node)
4761 "Heuristic for figuring out if NODE is a statement.
4762 Some node types can appear in either an expression context or a
4763 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4764 For these node types in a statement context, the parent will be a
4765 `js2-expr-stmt-node'.
4766 Functions aren't included in the check."
4767 (memq (js2-node-type node) js2-stmt-node-types))
4768
4769 (defun js2-mode-find-first-stmt (node)
4770 "Search upward starting from NODE looking for a statement.
4771 For purposes of this function, a `js2-function-node' counts."
4772 (while (not (or (js2-stmt-node-p node)
4773 (js2-function-node-p node)))
4774 (setq node (js2-node-parent node)))
4775 node)
4776
4777 (defun js2-node-parent-stmt (node)
4778 "Return the node's first ancestor that is a statement.
4779 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4780 appearing in a statement context will have a parent that is a
4781 `js2-expr-stmt-node' that will be returned by this function."
4782 (let ((parent (js2-node-parent node)))
4783 (if (or (null parent)
4784 (js2-stmt-node-p parent)
4785 (and (js2-function-node-p parent)
4786 (not (eq (js2-function-node-form parent)
4787 'FUNCTION_EXPRESSION))))
4788 parent
4789 (js2-node-parent-stmt parent))))
4790
4791 ;; In the Mozilla Rhino sources, Roshan James writes:
4792 ;; Does consistent-return analysis on the function body when strict mode is
4793 ;; enabled.
4794 ;;
4795 ;; function (x) { return (x+1) }
4796 ;;
4797 ;; is ok, but
4798 ;;
4799 ;; function (x) { if (x < 0) return (x+1); }
4800 ;;
4801 ;; is not because the function can potentially return a value when the
4802 ;; condition is satisfied and if not, the function does not explicitly
4803 ;; return a value.
4804 ;;
4805 ;; This extends to checking mismatches such as "return" and "return <value>"
4806 ;; used in the same function. Warnings are not emitted if inconsistent
4807 ;; returns exist in code that can be statically shown to be unreachable.
4808 ;; Ex.
4809 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4810 ;;
4811 ;; emits no warning. However if the loop had a break statement, then a
4812 ;; warning would be emitted.
4813 ;;
4814 ;; The consistency analysis looks at control structures such as loops, ifs,
4815 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4816 ;; warns the user about an inconsistent set of termination possibilities.
4817 ;;
4818 ;; These flags enumerate the possible ways a statement/function can
4819 ;; terminate. These flags are used by endCheck() and by the Parser to
4820 ;; detect inconsistent return usage.
4821 ;;
4822 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4823 ;; able to execute (example: throw, continue)
4824 ;;
4825 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4826 ;; next one. Statement such as return dont. A compound statement may have
4827 ;; some branch that drops off control to the next statement.
4828 ;;
4829 ;; END_RETURNS indicates that the statement can return with no value.
4830 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4831 ;;
4832 ;; A compound statement such as
4833 ;; if (condition) {
4834 ;; return value;
4835 ;; }
4836 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4837
4838 (defconst js2-END_UNREACHED 0)
4839 (defconst js2-END_DROPS_OFF 1)
4840 (defconst js2-END_RETURNS 2)
4841 (defconst js2-END_RETURNS_VALUE 4)
4842 (defconst js2-END_YIELDS 8)
4843
4844 (defun js2-has-consistent-return-usage (node)
4845 "Check that every return usage in a function body is consistent.
4846 Returns t if the function satisfies strict mode requirement."
4847 (let ((n (js2-end-check node)))
4848 ;; either it doesn't return a value in any branch...
4849 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4850 ;; or it returns a value (or is unreached) at every branch
4851 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4852 js2-END_RETURNS
4853 js2-END_YIELDS)))))
4854
4855 (defun js2-end-check-if (node)
4856 "Ensure that return usage in then/else blocks is consistent.
4857 If there is no else block, then the return statement can fall through.
4858 Returns logical OR of END_* flags"
4859 (let ((th (js2-if-node-then-part node))
4860 (el (js2-if-node-else-part node)))
4861 (if (null th)
4862 js2-END_UNREACHED
4863 (logior (js2-end-check th) (if el
4864 (js2-end-check el)
4865 js2-END_DROPS_OFF)))))
4866
4867 (defun js2-end-check-switch (node)
4868 "Consistency of return statements is checked between the case statements.
4869 If there is no default, then the switch can fall through. If there is a
4870 default, we check to see if all code paths in the default return or if
4871 there is a code path that can fall through.
4872 Returns logical OR of END_* flags."
4873 (let ((rv js2-END_UNREACHED)
4874 default-case)
4875 ;; examine the cases
4876 (catch 'break
4877 (dolist (c (js2-switch-node-cases node))
4878 (if (js2-case-node-expr c)
4879 (js2-set-flag rv (js2-end-check-block c))
4880 (setq default-case c)
4881 (throw 'break nil))))
4882 ;; we don't care how the cases drop into each other
4883 (js2-clear-flag rv js2-END_DROPS_OFF)
4884 ;; examine the default
4885 (js2-set-flag rv (if default-case
4886 (js2-end-check default-case)
4887 js2-END_DROPS_OFF))
4888 rv))
4889
4890 (defun js2-end-check-try (node)
4891 "If the block has a finally, return consistency is checked in the
4892 finally block. If all code paths in the finally return, then the
4893 returns in the try-catch blocks don't matter. If there is a code path
4894 that does not return or if there is no finally block, the returns
4895 of the try and catch blocks are checked for mismatch.
4896 Returns logical OR of END_* flags."
4897 (let ((finally (js2-try-node-finally-block node))
4898 rv)
4899 ;; check the finally if it exists
4900 (setq rv (if finally
4901 (js2-end-check (js2-finally-node-body finally))
4902 js2-END_DROPS_OFF))
4903 ;; If the finally block always returns, then none of the returns
4904 ;; in the try or catch blocks matter.
4905 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4906 (js2-clear-flag rv js2-END_DROPS_OFF)
4907 ;; examine the try block
4908 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4909 ;; check each catch block
4910 (dolist (cb (js2-try-node-catch-clauses node))
4911 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4912 rv))
4913
4914 (defun js2-end-check-loop (node)
4915 "Return statement in the loop body must be consistent.
4916 The default assumption for any kind of a loop is that it will eventually
4917 terminate. The only exception is a loop with a constant true condition.
4918 Code that follows such a loop is examined only if one can determine
4919 statically that there is a break out of the loop.
4920
4921 for(... ; ... ; ...) {}
4922 for(... in ... ) {}
4923 while(...) { }
4924 do { } while(...)
4925
4926 Returns logical OR of END_* flags."
4927 (let ((rv (js2-end-check (js2-loop-node-body node)))
4928 (condition (cond
4929 ((js2-while-node-p node)
4930 (js2-while-node-condition node))
4931 ((js2-do-node-p node)
4932 (js2-do-node-condition node))
4933 ((js2-for-node-p node)
4934 (js2-for-node-condition node)))))
4935
4936 ;; check to see if the loop condition is always true
4937 (if (and condition
4938 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4939 (js2-clear-flag rv js2-END_DROPS_OFF))
4940
4941 ;; look for effect of breaks
4942 (js2-set-flag rv (js2-node-get-prop node
4943 'CONTROL_BLOCK_PROP
4944 js2-END_UNREACHED))
4945 rv))
4946
4947 (defun js2-end-check-block (node)
4948 "A general block of code is examined statement by statement.
4949 If any statement (even a compound one) returns in all branches, then
4950 subsequent statements are not examined.
4951 Returns logical OR of END_* flags."
4952 (let* ((rv js2-END_DROPS_OFF)
4953 (kids (js2-block-node-kids node))
4954 (n (car kids)))
4955 ;; Check each statment. If the statement can continue onto the next
4956 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4957 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4958 (js2-clear-flag rv js2-END_DROPS_OFF)
4959 (js2-set-flag rv (js2-end-check n))
4960 (setq kids (cdr kids)
4961 n (car kids)))
4962 rv))
4963
4964 (defun js2-end-check-label (node)
4965 "A labeled statement implies that there may be a break to the label.
4966 The function processes the labeled statement and then checks the
4967 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4968 particular label.
4969 Returns logical OR of END_* flags."
4970 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4971 (logior rv (js2-node-get-prop node
4972 'CONTROL_BLOCK_PROP
4973 js2-END_UNREACHED))))
4974
4975 (defun js2-end-check-break (node)
4976 "When a break is encountered annotate the statement being broken
4977 out of by setting its CONTROL_BLOCK_PROP property.
4978 Returns logical OR of END_* flags."
4979 (and (js2-break-node-target node)
4980 (js2-node-set-prop (js2-break-node-target node)
4981 'CONTROL_BLOCK_PROP
4982 js2-END_DROPS_OFF))
4983 js2-END_UNREACHED)
4984
4985 (defun js2-end-check (node)
4986 "Examine the body of a function, doing a basic reachability analysis.
4987 Returns a combination of flags END_* flags that indicate
4988 how the function execution can terminate. These constitute only the
4989 pessimistic set of termination conditions. It is possible that at
4990 runtime certain code paths will never be actually taken. Hence this
4991 analysis will flag errors in cases where there may not be errors.
4992 Returns logical OR of END_* flags"
4993 (let (kid)
4994 (cond
4995 ((js2-break-node-p node)
4996 (js2-end-check-break node))
4997 ((js2-expr-stmt-node-p node)
4998 (if (setq kid (js2-expr-stmt-node-expr node))
4999 (js2-end-check kid)
5000 js2-END_DROPS_OFF))
5001 ((or (js2-continue-node-p node)
5002 (js2-throw-node-p node))
5003 js2-END_UNREACHED)
5004 ((js2-return-node-p node)
5005 (if (setq kid (js2-return-node-retval node))
5006 js2-END_RETURNS_VALUE
5007 js2-END_RETURNS))
5008 ((js2-loop-node-p node)
5009 (js2-end-check-loop node))
5010 ((js2-switch-node-p node)
5011 (js2-end-check-switch node))
5012 ((js2-labeled-stmt-node-p node)
5013 (js2-end-check-label node))
5014 ((js2-if-node-p node)
5015 (js2-end-check-if node))
5016 ((js2-try-node-p node)
5017 (js2-end-check-try node))
5018 ((js2-block-node-p node)
5019 (if (null (js2-block-node-kids node))
5020 js2-END_DROPS_OFF
5021 (js2-end-check-block node)))
5022 ((js2-yield-node-p node)
5023 js2-END_YIELDS)
5024 (t
5025 js2-END_DROPS_OFF))))
5026
5027 (defun js2-always-defined-boolean-p (node)
5028 "Check if NODE always evaluates to true or false in boolean context.
5029 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5030 nor always false."
5031 (let ((tt (js2-node-type node))
5032 num)
5033 (cond
5034 ((or (= tt js2-FALSE) (= tt js2-NULL))
5035 'ALWAYS_FALSE)
5036 ((= tt js2-TRUE)
5037 'ALWAYS_TRUE)
5038 ((= tt js2-NUMBER)
5039 (setq num (js2-number-node-num-value node))
5040 (if (and (not (eq num 0.0e+NaN))
5041 (not (zerop num)))
5042 'ALWAYS_TRUE
5043 'ALWAYS_FALSE))
5044 (t
5045 nil))))
5046
5047 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5048 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5049
5050 (defvar js2-tokens nil
5051 "List of all defined token names.") ; initialized in `js2-token-names'
5052
5053 (defconst js2-token-names
5054 (let* ((names (make-vector js2-num-tokens -1))
5055 (case-fold-search nil) ; only match js2-UPPER_CASE
5056 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5057 (loop for sym in syms
5058 for i from 0
5059 do
5060 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5061 (not (boundp sym)))
5062 (aset names (symbol-value sym) ; code, e.g. 152
5063 (downcase
5064 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5065 (push sym js2-tokens)))
5066 names)
5067 "Vector mapping int values to token string names, sans `js2-' prefix.")
5068
5069 (defun js2-tt-name (tok)
5070 "Return a string name for TOK, a token symbol or code.
5071 Signals an error if it's not a recognized token."
5072 (let ((code tok))
5073 (if (symbolp tok)
5074 (setq code (symbol-value tok)))
5075 (if (eq code -1)
5076 "ERROR"
5077 (if (and (numberp code)
5078 (not (minusp code))
5079 (< code js2-num-tokens))
5080 (aref js2-token-names code)
5081 (error "Invalid token: %s" code)))))
5082
5083 (defsubst js2-tt-sym (tok)
5084 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5085 (intern (js2-tt-name tok)))
5086
5087 (defconst js2-token-codes
5088 (let ((table (make-hash-table :test 'eq :size 256)))
5089 (loop for name across js2-token-names
5090 for sym = (intern (concat "js2-" (upcase name)))
5091 do
5092 (puthash sym (symbol-value sym) table))
5093 ;; clean up a few that are "wrong" in Rhino's token codes
5094 (puthash 'js2-DELETE js2-DELPROP table)
5095 table)
5096 "Hashtable mapping token type symbols to their bytecodes.")
5097
5098 (defsubst js2-tt-code (sym)
5099 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5100 (or (gethash sym js2-token-codes)
5101 (error "Invalid token symbol: %s " sym))) ; signal code bug
5102
5103 (defun js2-report-scan-error (msg &optional no-throw beg len)
5104 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5105 (js2-report-error msg nil
5106 (or beg (js2-current-token-beg))
5107 (or len (js2-current-token-len)))
5108 (unless no-throw
5109 (throw 'return js2-ERROR)))
5110
5111 (defun js2-set-string-from-buffer (token)
5112 "Set `string' and `end' slots for TOKEN, return the string."
5113 (setf (js2-token-end token) js2-ts-cursor
5114 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5115
5116 ;; TODO: could potentially avoid a lot of consing by allocating a
5117 ;; char buffer the way Rhino does.
5118 (defsubst js2-add-to-string (c)
5119 (push c js2-ts-string-buffer))
5120
5121 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5122 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5123 ;; any other character: when it's not part of the current token, we
5124 ;; unget it, allowing it to be read again by the following call.
5125 (defsubst js2-unget-char ()
5126 (decf js2-ts-cursor))
5127
5128 ;; Rhino distinguishes \r and \n line endings. We don't need to
5129 ;; because we only scan from Emacs buffers, which always use \n.
5130 (defun js2-get-char ()
5131 "Read and return the next character from the input buffer.
5132 Increments `js2-ts-lineno' if the return value is a newline char.
5133 Updates `js2-ts-cursor' to the point after the returned char.
5134 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5135 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5136 (let (c)
5137 ;; check for end of buffer
5138 (if (>= js2-ts-cursor (point-max))
5139 (setq js2-ts-hit-eof t
5140 js2-ts-cursor (1+ js2-ts-cursor)
5141 c js2-EOF_CHAR) ; return value
5142 ;; otherwise read next char
5143 (setq c (char-before (incf js2-ts-cursor)))
5144 ;; if we read a newline, update counters
5145 (if (= c ?\n)
5146 (setq js2-ts-line-start js2-ts-cursor
5147 js2-ts-lineno (1+ js2-ts-lineno)))
5148 ;; TODO: skip over format characters
5149 c)))
5150
5151 (defun js2-read-unicode-escape ()
5152 "Read a \\uNNNN sequence from the input.
5153 Assumes the ?\ and ?u have already been read.
5154 Returns the unicode character, or nil if it wasn't a valid character.
5155 Doesn't change the values of any scanner variables."
5156 ;; I really wish I knew a better way to do this, but I can't
5157 ;; find the Emacs function that takes a 16-bit int and converts
5158 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5159 ;; Have to first check that it's 4 hex characters or it may stop
5160 ;; the read early.
5161 (ignore-errors
5162 (let ((s (buffer-substring-no-properties js2-ts-cursor
5163 (+ 4 js2-ts-cursor))))
5164 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5165 (read (concat "?\\u" s))))))
5166
5167 (defun js2-match-char (test)
5168 "Consume and return next character if it matches TEST, a character.
5169 Returns nil and consumes nothing if TEST is not the next character."
5170 (let ((c (js2-get-char)))
5171 (if (eq c test)
5172 t
5173 (js2-unget-char)
5174 nil)))
5175
5176 (defun js2-peek-char ()
5177 (prog1
5178 (js2-get-char)
5179 (js2-unget-char)))
5180
5181 (defun js2-identifier-start-p (c)
5182 "Is C a valid start to an ES5 Identifier?
5183 See http://es5.github.io/#x7.6"
5184 (or
5185 (memq c '(?$ ?_))
5186 (memq (get-char-code-property c 'general-category)
5187 ;; Letters
5188 '(Lu Ll Lt Lm Lo Nl))))
5189
5190 (defun js2-identifier-part-p (c)
5191 "Is C a valid part of an ES5 Identifier?
5192 See http://es5.github.io/#x7.6"
5193 (or
5194 (memq c '(?$ ?_ ?\u200c ?\u200d))
5195 (memq (get-char-code-property c 'general-category)
5196 '(;; Letters
5197 Lu Ll Lt Lm Lo Nl
5198 ;; Combining Marks
5199 Mn Mc
5200 ;; Digits
5201 Nd
5202 ;; Connector Punctuation
5203 Pc))))
5204
5205 (defun js2-alpha-p (c)
5206 (cond ((and (<= ?A c) (<= c ?Z)) t)
5207 ((and (<= ?a c) (<= c ?z)) t)
5208 (t nil)))
5209
5210 (defsubst js2-digit-p (c)
5211 (and (<= ?0 c) (<= c ?9)))
5212
5213 (defun js2-js-space-p (c)
5214 (if (<= c 127)
5215 (memq c '(#x20 #x9 #xB #xC #xD))
5216 (or
5217 (eq c #xA0)
5218 ;; TODO: change this nil to check for Unicode space character
5219 nil)))
5220
5221 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5222
5223 (defun js2-skip-line ()
5224 "Skip to end of line."
5225 (while (not (memq (js2-get-char) js2-eol-chars)))
5226 (js2-unget-char)
5227 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5228 (setq js2-token-end js2-ts-cursor))
5229
5230 (defun js2-init-scanner (&optional buf line)
5231 "Create token stream for BUF starting on LINE.
5232 BUF defaults to `current-buffer' and LINE defaults to 1.
5233
5234 A buffer can only have one scanner active at a time, which yields
5235 dramatically simpler code than using a defstruct. If you need to
5236 have simultaneous scanners in a buffer, copy the regions to scan
5237 into temp buffers."
5238 (with-current-buffer (or buf (current-buffer))
5239 (setq js2-ts-dirty-line nil
5240 js2-ts-hit-eof nil
5241 js2-ts-line-start 0
5242 js2-ts-lineno (or line 1)
5243 js2-ts-line-end-char -1
5244 js2-ts-cursor (point-min)
5245 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5246 js2-ti-tokens-cursor 0
5247 js2-ti-lookahead 0
5248 js2-ts-is-xml-attribute nil
5249 js2-ts-xml-is-tag-content nil
5250 js2-ts-xml-open-tags-count 0
5251 js2-ts-string-buffer nil)))
5252
5253 ;; This function uses the cached op, string and number fields in
5254 ;; TokenStream; if getToken has been called since the passed token
5255 ;; was scanned, the op or string printed may be incorrect.
5256 (defun js2-token-to-string (token)
5257 ;; Not sure where this function is used in Rhino. Not tested.
5258 (if (not js2-debug-print-trees)
5259 ""
5260 (let ((name (js2-tt-name token)))
5261 (cond
5262 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5263 (concat name " `" (js2-current-token-string) "'"))
5264 ((eq token js2-NUMBER)
5265 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5266 (t
5267 name)))))
5268
5269 (defconst js2-keywords
5270 '(break
5271 case catch const continue
5272 debugger default delete do
5273 else
5274 false finally for function
5275 if in instanceof import
5276 let
5277 new null
5278 return
5279 switch
5280 this throw true try typeof
5281 var void
5282 while with
5283 yield))
5284
5285 ;; Token names aren't exactly the same as the keywords, unfortunately.
5286 ;; E.g. delete is js2-DELPROP.
5287 (defconst js2-kwd-tokens
5288 (let ((table (make-vector js2-num-tokens nil))
5289 (tokens
5290 (list js2-BREAK
5291 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5292 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5293 js2-ELSE
5294 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5295 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5296 js2-LET
5297 js2-NEW js2-NULL
5298 js2-RETURN
5299 js2-SWITCH
5300 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5301 js2-VAR
5302 js2-WHILE js2-WITH
5303 js2-YIELD)))
5304 (dolist (i tokens)
5305 (aset table i 'font-lock-keyword-face))
5306 (aset table js2-STRING 'font-lock-string-face)
5307 (aset table js2-REGEXP 'font-lock-string-face)
5308 (aset table js2-COMMENT 'font-lock-comment-face)
5309 (aset table js2-THIS 'font-lock-builtin-face)
5310 (aset table js2-VOID 'font-lock-constant-face)
5311 (aset table js2-NULL 'font-lock-constant-face)
5312 (aset table js2-TRUE 'font-lock-constant-face)
5313 (aset table js2-FALSE 'font-lock-constant-face)
5314 (aset table js2-NOT 'font-lock-negation-char-face)
5315 table)
5316 "Vector whose values are non-nil for tokens that are keywords.
5317 The values are default faces to use for highlighting the keywords.")
5318
5319 ;; FIXME: Support strict mode-only future reserved words, after we know
5320 ;; which parts scopes are in strict mode, and which are not.
5321 (defconst js2-reserved-words '(class enum export extends import super)
5322 "Future reserved keywords in ECMAScript 5.1.")
5323
5324 (defconst js2-keyword-names
5325 (let ((table (make-hash-table :test 'equal)))
5326 (loop for k in js2-keywords
5327 do (puthash
5328 (symbol-name k) ; instanceof
5329 (intern (concat "js2-"
5330 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5331 table))
5332 table)
5333 "JavaScript keywords by name, mapped to their symbols.")
5334
5335 (defconst js2-reserved-word-names
5336 (let ((table (make-hash-table :test 'equal)))
5337 (loop for k in js2-reserved-words
5338 do
5339 (puthash (symbol-name k) 'js2-RESERVED table))
5340 table)
5341 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5342
5343 (defun js2-collect-string (buf)
5344 "Convert BUF, a list of chars, to a string.
5345 Reverses BUF before converting."
5346 (if buf
5347 (apply #'string (nreverse buf))
5348 ""))
5349
5350 (defun js2-string-to-keyword (s)
5351 "Return token for S, a string, if S is a keyword or reserved word.
5352 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5353 (or (gethash s js2-keyword-names)
5354 (gethash s js2-reserved-word-names)))
5355
5356 (defsubst js2-ts-set-char-token-bounds (token)
5357 "Used when next token is one character."
5358 (setf (js2-token-beg token) (1- js2-ts-cursor)
5359 (js2-token-end token) js2-ts-cursor))
5360
5361 (defsubst js2-ts-return (token type)
5362 "Update the `end' and `type' slots of TOKEN,
5363 then throw `return' with value TYPE."
5364 (setf (js2-token-end token) js2-ts-cursor
5365 (js2-token-type token) type)
5366 (throw 'return type))
5367
5368 (defun js2-x-digit-to-int (c accumulator)
5369 "Build up a hex number.
5370 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5371 corresponding number. Otherwise return -1."
5372 (catch 'return
5373 (catch 'check
5374 ;; Use 0..9 < A..Z < a..z
5375 (cond
5376 ((<= c ?9)
5377 (decf c ?0)
5378 (if (<= 0 c)
5379 (throw 'check nil)))
5380 ((<= c ?F)
5381 (when (<= ?A c)
5382 (decf c (- ?A 10))
5383 (throw 'check nil)))
5384 ((<= c ?f)
5385 (when (<= ?a c)
5386 (decf c (- ?a 10))
5387 (throw 'check nil))))
5388 (throw 'return -1))
5389 (logior c (lsh accumulator 4))))
5390
5391 (defun js2-get-token ()
5392 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5393 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5394 next saved token.
5395
5396 This function will not return a newline (js2-EOL) - instead, it
5397 gobbles newlines until it finds a non-newline token. Call
5398 `js2-peek-token-or-eol' when you care about newlines.
5399
5400 This function will also not return a js2-COMMENT. Instead, it
5401 records comments found in `js2-scanned-comments'. If the token
5402 returned by this function immediately follows a jsdoc comment,
5403 the token is flagged as such."
5404 (if (zerop js2-ti-lookahead)
5405 (js2-get-token-internal)
5406 (decf js2-ti-lookahead)
5407 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5408 (let ((tt (js2-current-token-type)))
5409 (assert (not (= tt js2-EOL)))
5410 tt)))
5411
5412 (defun js2-unget-token ()
5413 (assert (< js2-ti-lookahead js2-ti-max-lookahead))
5414 (incf js2-ti-lookahead)
5415 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5416
5417 (defun js2-get-token-internal ()
5418 (let* ((token (js2-get-token-internal-1)) ; call scanner
5419 (tt (js2-token-type token))
5420 saw-eol
5421 face)
5422 ;; process comments
5423 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5424 (if (= tt js2-EOL)
5425 (setq saw-eol t)
5426 (setq saw-eol nil)
5427 (when js2-record-comments
5428 (js2-record-comment token)))
5429 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5430 (setq token (js2-get-token-internal-1) ; call scanner again
5431 tt (js2-token-type token)))
5432
5433 (when saw-eol
5434 (setf (js2-token-follows-eol-p token) t))
5435
5436 ;; perform lexical fontification as soon as token is scanned
5437 (when js2-parse-ide-mode
5438 (cond
5439 ((minusp tt)
5440 (js2-record-face 'js2-error token))
5441 ((setq face (aref js2-kwd-tokens tt))
5442 (js2-record-face face token))
5443 ((and (= tt js2-NAME)
5444 (equal (js2-token-string token) "undefined"))
5445 (js2-record-face 'font-lock-constant-face token))))
5446 tt))
5447
5448 (defun js2-get-token-internal-1 ()
5449 "Return next JavaScript token type, an int such as js2-RETURN.
5450 During operation, creates an instance of `js2-token' struct, sets
5451 its relevant fields and puts it into `js2-ti-tokens'."
5452 (let (c c1 identifier-start is-unicode-escape-start
5453 contains-escape escape-val str result base
5454 quote-char val look-for-slash continue tt
5455 (token (js2-new-token 0)))
5456 (setq
5457 tt
5458 (catch 'return
5459 (while t
5460 ;; Eat whitespace, possibly sensitive to newlines.
5461 (setq continue t)
5462 (while continue
5463 (setq c (js2-get-char))
5464 (cond
5465 ((eq c js2-EOF_CHAR)
5466 (js2-unget-char)
5467 (js2-ts-set-char-token-bounds token)
5468 (throw 'return js2-EOF))
5469 ((eq c ?\n)
5470 (js2-ts-set-char-token-bounds token)
5471 (setq js2-ts-dirty-line nil)
5472 (throw 'return js2-EOL))
5473 ((not (js2-js-space-p c))
5474 (if (/= c ?-) ; in case end of HTML comment
5475 (setq js2-ts-dirty-line t))
5476 (setq continue nil))))
5477 ;; Assume the token will be 1 char - fixed up below.
5478 (js2-ts-set-char-token-bounds token)
5479 (when (eq c ?@)
5480 (throw 'return js2-XMLATTR))
5481 ;; identifier/keyword/instanceof?
5482 ;; watch out for starting with a <backslash>
5483 (cond
5484 ((eq c ?\\)
5485 (setq c (js2-get-char))
5486 (if (eq c ?u)
5487 (setq identifier-start t
5488 is-unicode-escape-start t
5489 js2-ts-string-buffer nil)
5490 (setq identifier-start nil)
5491 (js2-unget-char)
5492 (setq c ?\\)))
5493 (t
5494 (when (setq identifier-start (js2-identifier-start-p c))
5495 (setq js2-ts-string-buffer nil)
5496 (js2-add-to-string c))))
5497 (when identifier-start
5498 (setq contains-escape is-unicode-escape-start)
5499 (catch 'break
5500 (while t
5501 (if is-unicode-escape-start
5502 ;; strictly speaking we should probably push-back
5503 ;; all the bad characters if the <backslash>uXXXX
5504 ;; sequence is malformed. But since there isn't a
5505 ;; correct context(is there?) for a bad Unicode
5506 ;; escape sequence in an identifier, we can report
5507 ;; an error here.
5508 (progn
5509 (setq escape-val 0)
5510 (dotimes (_ 4)
5511 (setq c (js2-get-char)
5512 escape-val (js2-x-digit-to-int c escape-val))
5513 ;; Next check takes care of c < 0 and bad escape
5514 (if (minusp escape-val)
5515 (throw 'break nil)))
5516 (if (minusp escape-val)
5517 (js2-report-scan-error "msg.invalid.escape" t))
5518 (js2-add-to-string escape-val)
5519 (setq is-unicode-escape-start nil))
5520 (setq c (js2-get-char))
5521 (cond
5522 ((eq c ?\\)
5523 (setq c (js2-get-char))
5524 (if (eq c ?u)
5525 (setq is-unicode-escape-start t
5526 contains-escape t)
5527 (js2-report-scan-error "msg.illegal.character" t)))
5528 (t
5529 (if (or (eq c js2-EOF_CHAR)
5530 (not (js2-identifier-part-p c)))
5531 (throw 'break nil))
5532 (js2-add-to-string c))))))
5533 (js2-unget-char)
5534 (setf str (js2-collect-string js2-ts-string-buffer)
5535 (js2-token-end token) js2-ts-cursor)
5536 ;; FIXME: Invalid in ES5 and ES6, see
5537 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5538 ;; Probably should just drop this conditional.
5539 (unless contains-escape
5540 ;; OPT we shouldn't have to make a string (object!) to
5541 ;; check if it's a keyword.
5542 ;; Return the corresponding token if it's a keyword
5543 (when (setq result (js2-string-to-keyword str))
5544 (if (and (< js2-language-version 170)
5545 (memq result '(js2-LET js2-YIELD)))
5546 ;; LET and YIELD are tokens only in 1.7 and later
5547 (setq result 'js2-NAME))
5548 (when (eq result 'js2-RESERVED)
5549 (setf (js2-token-string token) str))
5550 (throw 'return (js2-tt-code result))))
5551 ;; If we want to intern these as Rhino does, just use (intern str)
5552 (setf (js2-token-string token) str)
5553 (throw 'return js2-NAME)) ; end identifier/kwd check
5554 ;; is it a number?
5555 (when (or (js2-digit-p c)
5556 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5557 (setq js2-ts-string-buffer nil
5558 base 10)
5559 (when (eq c ?0)
5560 (setq c (js2-get-char))
5561 (cond
5562 ((or (eq c ?x) (eq c ?X))
5563 (setq base 16)
5564 (setq c (js2-get-char)))
5565 ((and (or (eq c ?b) (eq c ?B))
5566 (>= js2-language-version 200))
5567 (setq base 2)
5568 (setq c (js2-get-char)))
5569 ((and (or (eq c ?o) (eq c ?O))
5570 (>= js2-language-version 200))
5571 (setq base 8)
5572 (setq c (js2-get-char)))
5573 ((js2-digit-p c)
5574 (setq base 'maybe-8))
5575 (t
5576 (js2-add-to-string ?0))))
5577 (cond
5578 ((eq base 16)
5579 (if (> 0 (js2-x-digit-to-int c 0))
5580 (js2-report-scan-error "msg.missing.hex.digits")
5581 (while (<= 0 (js2-x-digit-to-int c 0))
5582 (js2-add-to-string c)
5583 (setq c (js2-get-char)))))
5584 ((eq base 2)
5585 (if (not (memq c '(?0 ?1)))
5586 (js2-report-scan-error "msg.missing.binary.digits")
5587 (while (memq c '(?0 ?1))
5588 (js2-add-to-string c)
5589 (setq c (js2-get-char)))))
5590 ((eq base 8)
5591 (if (or (> ?0 c) (< ?7 c))
5592 (js2-report-scan-error "msg.missing.octal.digits")
5593 (while (and (<= ?0 c) (>= ?7 c))
5594 (js2-add-to-string c)
5595 (setq c (js2-get-char)))))
5596 (t
5597 (while (and (<= ?0 c) (<= c ?9))
5598 ;; We permit 08 and 09 as decimal numbers, which
5599 ;; makes our behavior a superset of the ECMA
5600 ;; numeric grammar. We might not always be so
5601 ;; permissive, so we warn about it.
5602 (when (and (eq base 'maybe-8) (>= c ?8))
5603 (js2-report-warning "msg.bad.octal.literal"
5604 (if (eq c ?8) "8" "9"))
5605 (setq base 10))
5606 (js2-add-to-string c)
5607 (setq c (js2-get-char)))
5608 (when (eq base 'maybe-8)
5609 (setq base 8))))
5610 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5611 (when (eq c ?.)
5612 (loop do
5613 (js2-add-to-string c)
5614 (setq c (js2-get-char))
5615 while (js2-digit-p c)))
5616 (when (memq c '(?e ?E))
5617 (js2-add-to-string c)
5618 (setq c (js2-get-char))
5619 (when (memq c '(?+ ?-))
5620 (js2-add-to-string c)
5621 (setq c (js2-get-char)))
5622 (unless (js2-digit-p c)
5623 (js2-report-scan-error "msg.missing.exponent" t))
5624 (loop do
5625 (js2-add-to-string c)
5626 (setq c (js2-get-char))
5627 while (js2-digit-p c))))
5628 (js2-unget-char)
5629 (let ((str (js2-set-string-from-buffer token)))
5630 (setf (js2-token-number token)
5631 (js2-string-to-number str base)))
5632 (throw 'return js2-NUMBER))
5633 ;; is it a string?
5634 (when (memq c '(?\" ?\'))
5635 ;; We attempt to accumulate a string the fast way, by
5636 ;; building it directly out of the reader. But if there
5637 ;; are any escaped characters in the string, we revert to
5638 ;; building it out of a string buffer.
5639 (setq quote-char c
5640 js2-ts-string-buffer nil
5641 c (js2-get-char))
5642 (catch 'break
5643 (while (/= c quote-char)
5644 (catch 'continue
5645 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5646 (js2-unget-char)
5647 (setf (js2-token-end token) js2-ts-cursor)
5648 (js2-report-error "msg.unterminated.string.lit")
5649 (throw 'return js2-STRING))
5650 (when (eq c ?\\)
5651 ;; We've hit an escaped character
5652 (setq c (js2-get-char))
5653 (case c
5654 (?b (setq c ?\b))
5655 (?f (setq c ?\f))
5656 (?n (setq c ?\n))
5657 (?r (setq c ?\r))
5658 (?t (setq c ?\t))
5659 (?v (setq c ?\v))
5660 (?u
5661 (setq c1 (js2-read-unicode-escape))
5662 (if js2-parse-ide-mode
5663 (if c1
5664 (progn
5665 ;; just copy the string in IDE-mode
5666 (js2-add-to-string ?\\)
5667 (js2-add-to-string ?u)
5668 (dotimes (_ 3)
5669 (js2-add-to-string (js2-get-char)))
5670 (setq c (js2-get-char))) ; added at end of loop
5671 ;; flag it as an invalid escape
5672 (js2-report-warning "msg.invalid.escape"
5673 nil (- js2-ts-cursor 2) 6))
5674 ;; Get 4 hex digits; if the u escape is not
5675 ;; followed by 4 hex digits, use 'u' + the
5676 ;; literal character sequence that follows.
5677 (js2-add-to-string ?u)
5678 (setq escape-val 0)
5679 (dotimes (_ 4)
5680 (setq c (js2-get-char)
5681 escape-val (js2-x-digit-to-int c escape-val))
5682 (if (minusp escape-val)
5683 (throw 'continue nil))
5684 (js2-add-to-string c))
5685 ;; prepare for replace of stored 'u' sequence by escape value
5686 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5687 c escape-val)))
5688 (?x
5689 ;; Get 2 hex digits, defaulting to 'x'+literal
5690 ;; sequence, as above.
5691 (setq c (js2-get-char)
5692 escape-val (js2-x-digit-to-int c 0))
5693 (if (minusp escape-val)
5694 (progn
5695 (js2-add-to-string ?x)
5696 (throw 'continue nil))
5697 (setq c1 c
5698 c (js2-get-char)
5699 escape-val (js2-x-digit-to-int c escape-val))
5700 (if (minusp escape-val)
5701 (progn
5702 (js2-add-to-string ?x)
5703 (js2-add-to-string c1)
5704 (throw 'continue nil))
5705 ;; got 2 hex digits
5706 (setq c escape-val))))
5707 (?\n
5708 ;; Remove line terminator after escape to follow
5709 ;; SpiderMonkey and C/C++
5710 (setq c (js2-get-char))
5711 (throw 'continue nil))
5712 (t
5713 (when (and (<= ?0 c) (< c ?8))
5714 (setq val (- c ?0)
5715 c (js2-get-char))
5716 (when (and (<= ?0 c) (< c ?8))
5717 (setq val (- (+ (* 8 val) c) ?0)
5718 c (js2-get-char))
5719 (when (and (<= ?0 c)
5720 (< c ?8)
5721 (< val #o37))
5722 ;; c is 3rd char of octal sequence only
5723 ;; if the resulting val <= 0377
5724 (setq val (- (+ (* 8 val) c) ?0)
5725 c (js2-get-char))))
5726 (js2-unget-char)
5727 (setq c val)))))
5728 (js2-add-to-string c)
5729 (setq c (js2-get-char)))))
5730 (js2-set-string-from-buffer token)
5731 (throw 'return js2-STRING))
5732 (js2-ts-return token
5733 (case c
5734 (?\;
5735 (throw 'return js2-SEMI))
5736 (?\[
5737 (throw 'return js2-LB))
5738 (?\]
5739 (throw 'return js2-RB))
5740 (?{
5741 (throw 'return js2-LC))
5742 (?}
5743 (throw 'return js2-RC))
5744 (?\(
5745 (throw 'return js2-LP))
5746 (?\)
5747 (throw 'return js2-RP))
5748 (?,
5749 (throw 'return js2-COMMA))
5750 (??
5751 (throw 'return js2-HOOK))
5752 (?:
5753 (if (js2-match-char ?:)
5754 js2-COLONCOLON
5755 (throw 'return js2-COLON)))
5756 (?.
5757 (if (js2-match-char ?.)
5758 (if (js2-match-char ?.)
5759 js2-TRIPLEDOT js2-DOTDOT)
5760 (if (js2-match-char ?\()
5761 js2-DOTQUERY
5762 (throw 'return js2-DOT))))
5763 (?|
5764 (if (js2-match-char ?|)
5765 (throw 'return js2-OR)
5766 (if (js2-match-char ?=)
5767 js2-ASSIGN_BITOR
5768 (throw 'return js2-BITOR))))
5769 (?^
5770 (if (js2-match-char ?=)
5771 js2-ASSIGN_BITOR
5772 (throw 'return js2-BITXOR)))
5773 (?&
5774 (if (js2-match-char ?&)
5775 (throw 'return js2-AND)
5776 (if (js2-match-char ?=)
5777 js2-ASSIGN_BITAND
5778 (throw 'return js2-BITAND))))
5779 (?=
5780 (if (js2-match-char ?=)
5781 (if (js2-match-char ?=)
5782 js2-SHEQ
5783 (throw 'return js2-EQ))
5784 (if (js2-match-char ?>)
5785 (js2-ts-return token js2-ARROW)
5786 (throw 'return js2-ASSIGN))))
5787 (?!
5788 (if (js2-match-char ?=)
5789 (if (js2-match-char ?=)
5790 js2-SHNE
5791 js2-NE)
5792 (throw 'return js2-NOT)))
5793 (?<
5794 ;; NB:treat HTML begin-comment as comment-till-eol
5795 (when (js2-match-char ?!)
5796 (when (js2-match-char ?-)
5797 (when (js2-match-char ?-)
5798 (js2-skip-line)
5799 (setf (js2-token-comment-type (js2-current-token)) 'html)
5800 (throw 'return js2-COMMENT)))
5801 (js2-unget-char))
5802 (if (js2-match-char ?<)
5803 (if (js2-match-char ?=)
5804 js2-ASSIGN_LSH
5805 js2-LSH)
5806 (if (js2-match-char ?=)
5807 js2-LE
5808 (throw 'return js2-LT))))
5809 (?>
5810 (if (js2-match-char ?>)
5811 (if (js2-match-char ?>)
5812 (if (js2-match-char ?=)
5813 js2-ASSIGN_URSH
5814 js2-URSH)
5815 (if (js2-match-char ?=)
5816 js2-ASSIGN_RSH
5817 js2-RSH))
5818 (if (js2-match-char ?=)
5819 js2-GE
5820 (throw 'return js2-GT))))
5821 (?*
5822 (if (js2-match-char ?=)
5823 js2-ASSIGN_MUL
5824 (throw 'return js2-MUL)))
5825 (?/
5826 ;; is it a // comment?
5827 (when (js2-match-char ?/)
5828 (setf (js2-token-beg token) (- js2-ts-cursor 2))
5829 (js2-skip-line)
5830 (setf (js2-token-comment-type token) 'line)
5831 ;; include newline so highlighting goes to end of window
5832 (incf (js2-token-end token))
5833 (throw 'return js2-COMMENT))
5834 ;; is it a /* comment?
5835 (when (js2-match-char ?*)
5836 (setf look-for-slash nil
5837 (js2-token-beg token) (- js2-ts-cursor 2)
5838 (js2-token-comment-type token)
5839 (if (js2-match-char ?*)
5840 (progn
5841 (setq look-for-slash t)
5842 'jsdoc)
5843 'block))
5844 (while t
5845 (setq c (js2-get-char))
5846 (cond
5847 ((eq c js2-EOF_CHAR)
5848 (setf (js2-token-end token) (1- js2-ts-cursor))
5849 (js2-report-error "msg.unterminated.comment")
5850 (throw 'return js2-COMMENT))
5851 ((eq c ?*)
5852 (setq look-for-slash t))
5853 ((eq c ?/)
5854 (if look-for-slash
5855 (js2-ts-return token js2-COMMENT)))
5856 (t
5857 (setf look-for-slash nil
5858 (js2-token-end token) js2-ts-cursor)))))
5859 (if (js2-match-char ?=)
5860 js2-ASSIGN_DIV
5861 (throw 'return js2-DIV)))
5862 (?#
5863 (when js2-skip-preprocessor-directives
5864 (js2-skip-line)
5865 (setf (js2-token-comment-type token) 'preprocessor
5866 (js2-token-end token) js2-ts-cursor)
5867 (throw 'return js2-COMMENT))
5868 (throw 'return js2-ERROR))
5869 (?%
5870 (if (js2-match-char ?=)
5871 js2-ASSIGN_MOD
5872 (throw 'return js2-MOD)))
5873 (?~
5874 (throw 'return js2-BITNOT))
5875 (?+
5876 (if (js2-match-char ?=)
5877 js2-ASSIGN_ADD
5878 (if (js2-match-char ?+)
5879 js2-INC
5880 (throw 'return js2-ADD))))
5881 (?-
5882 (cond
5883 ((js2-match-char ?=)
5884 (setq c js2-ASSIGN_SUB))
5885 ((js2-match-char ?-)
5886 (unless js2-ts-dirty-line
5887 ;; treat HTML end-comment after possible whitespace
5888 ;; after line start as comment-until-eol
5889 (when (js2-match-char ?>)
5890 (js2-skip-line)
5891 (setf (js2-token-comment-type (js2-current-token)) 'html)
5892 (throw 'return js2-COMMENT)))
5893 (setq c js2-DEC))
5894 (t
5895 (setq c js2-SUB)))
5896 (setq js2-ts-dirty-line t)
5897 c)
5898 (otherwise
5899 (js2-report-scan-error "msg.illegal.character")))))))
5900 (setf (js2-token-type token) tt)
5901 token))
5902
5903 (defsubst js2-string-to-number (str base)
5904 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5905 (condition-case nil
5906 (string-to-number str base)
5907 (overflow-error -1)))
5908
5909 (defun js2-read-regexp (start-tt)
5910 "Called by parser when it gets / or /= in literal context."
5911 (let (c err
5912 in-class ; inside a '[' .. ']' character-class
5913 flags
5914 (continue t)
5915 (token (js2-new-token 0)))
5916 (setq js2-ts-string-buffer nil)
5917 (if (eq start-tt js2-ASSIGN_DIV)
5918 ;; mis-scanned /=
5919 (js2-add-to-string ?=)
5920 (if (not (eq start-tt js2-DIV))
5921 (error "failed assertion")))
5922 (while (and (not err)
5923 (or (/= (setq c (js2-get-char)) ?/)
5924 in-class))
5925 (cond
5926 ((or (= c ?\n)
5927 (= c js2-EOF_CHAR))
5928 (setf (js2-token-end token) (1- js2-ts-cursor)
5929 err t
5930 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
5931 (js2-report-error "msg.unterminated.re.lit"))
5932 (t (cond
5933 ((= c ?\\)
5934 (js2-add-to-string c)
5935 (setq c (js2-get-char)))
5936 ((= c ?\[)
5937 (setq in-class t))
5938 ((= c ?\])
5939 (setq in-class nil)))
5940 (js2-add-to-string c))))
5941 (unless err
5942 (while continue
5943 (cond
5944 ((js2-match-char ?g)
5945 (push ?g flags))
5946 ((js2-match-char ?i)
5947 (push ?i flags))
5948 ((js2-match-char ?m)
5949 (push ?m flags))
5950 (t
5951 (setq continue nil))))
5952 (if (js2-alpha-p (js2-peek-char))
5953 (js2-report-scan-error "msg.invalid.re.flag" t
5954 js2-ts-cursor 1))
5955 (js2-set-string-from-buffer token))
5956 (js2-collect-string flags)))
5957
5958 (defun js2-get-first-xml-token ()
5959 (setq js2-ts-xml-open-tags-count 0
5960 js2-ts-is-xml-attribute nil
5961 js2-ts-xml-is-tag-content nil)
5962 (js2-unget-char)
5963 (js2-get-next-xml-token))
5964
5965 (defun js2-xml-discard-string (token)
5966 "Throw away the string in progress and flag an XML parse error."
5967 (setf js2-ts-string-buffer nil
5968 (js2-token-string token) nil)
5969 (js2-report-scan-error "msg.XML.bad.form" t))
5970
5971 (defun js2-get-next-xml-token ()
5972 (setq js2-ts-string-buffer nil) ; for recording the XML
5973 (let ((token (js2-new-token 0))
5974 c result)
5975 (setq result
5976 (catch 'return
5977 (while t
5978 (setq c (js2-get-char))
5979 (cond
5980 ((= c js2-EOF_CHAR)
5981 (throw 'return js2-ERROR))
5982 (js2-ts-xml-is-tag-content
5983 (case c
5984 (?>
5985 (js2-add-to-string c)
5986 (setq js2-ts-xml-is-tag-content nil
5987 js2-ts-is-xml-attribute nil))
5988 (?/
5989 (js2-add-to-string c)
5990 (when (eq ?> (js2-peek-char))
5991 (setq c (js2-get-char))
5992 (js2-add-to-string c)
5993 (setq js2-ts-xml-is-tag-content nil)
5994 (decf js2-ts-xml-open-tags-count)))
5995 (?{
5996 (js2-unget-char)
5997 (js2-set-string-from-buffer token)
5998 (throw 'return js2-XML))
5999 ((?\' ?\")
6000 (js2-add-to-string c)
6001 (unless (js2-read-quoted-string c token)
6002 (throw 'return js2-ERROR)))
6003 (?=
6004 (js2-add-to-string c)
6005 (setq js2-ts-is-xml-attribute t))
6006 ((? ?\t ?\r ?\n)
6007 (js2-add-to-string c))
6008 (t
6009 (js2-add-to-string c)
6010 (setq js2-ts-is-xml-attribute nil)))
6011 (when (and (not js2-ts-xml-is-tag-content)
6012 (zerop js2-ts-xml-open-tags-count))
6013 (js2-set-string-from-buffer token)
6014 (throw 'return js2-XMLEND)))
6015 (t
6016 ;; else not tag content
6017 (case c
6018 (?<
6019 (js2-add-to-string c)
6020 (setq c (js2-peek-char))
6021 (case c
6022 (?!
6023 (setq c (js2-get-char)) ;; skip !
6024 (js2-add-to-string c)
6025 (setq c (js2-peek-char))
6026 (case c
6027 (?-
6028 (setq c (js2-get-char)) ;; skip -
6029 (js2-add-to-string c)
6030 (if (eq c ?-)
6031 (progn
6032 (js2-add-to-string c)
6033 (unless (js2-read-xml-comment token)
6034 (throw 'return js2-ERROR)))
6035 (js2-xml-discard-string token)
6036 (throw 'return js2-ERROR)))
6037 (?\[
6038 (setq c (js2-get-char)) ;; skip [
6039 (js2-add-to-string c)
6040 (if (and (= (js2-get-char) ?C)
6041 (= (js2-get-char) ?D)
6042 (= (js2-get-char) ?A)
6043 (= (js2-get-char) ?T)
6044 (= (js2-get-char) ?A)
6045 (= (js2-get-char) ?\[))
6046 (progn
6047 (js2-add-to-string ?C)
6048 (js2-add-to-string ?D)
6049 (js2-add-to-string ?A)
6050 (js2-add-to-string ?T)
6051 (js2-add-to-string ?A)
6052 (js2-add-to-string ?\[)
6053 (unless (js2-read-cdata token)
6054 (throw 'return js2-ERROR)))
6055 (js2-xml-discard-string token)
6056 (throw 'return js2-ERROR)))
6057 (t
6058 (unless (js2-read-entity token)
6059 (throw 'return js2-ERROR))))
6060 ;; Allow bare CDATA section, e.g.:
6061 ;; let xml = <![CDATA[ foo bar baz ]]>;
6062 (when (zerop js2-ts-xml-open-tags-count)
6063 (throw 'return js2-XMLEND)))
6064 (??
6065 (setq c (js2-get-char)) ;; skip ?
6066 (js2-add-to-string c)
6067 (unless (js2-read-PI token)
6068 (throw 'return js2-ERROR)))
6069 (?/
6070 ;; end tag
6071 (setq c (js2-get-char)) ;; skip /
6072 (js2-add-to-string c)
6073 (when (zerop js2-ts-xml-open-tags-count)
6074 (js2-xml-discard-string token)
6075 (throw 'return js2-ERROR))
6076 (setq js2-ts-xml-is-tag-content t)
6077 (decf js2-ts-xml-open-tags-count))
6078 (t
6079 ;; start tag
6080 (setq js2-ts-xml-is-tag-content t)
6081 (incf js2-ts-xml-open-tags-count))))
6082 (?{
6083 (js2-unget-char)
6084 (js2-set-string-from-buffer token)
6085 (throw 'return js2-XML))
6086 (t
6087 (js2-add-to-string c))))))))
6088 (setf (js2-token-end token) js2-ts-cursor)
6089 (setf (js2-token-type token) result)
6090 result))
6091
6092 (defun js2-read-quoted-string (quote token)
6093 (let (c)
6094 (catch 'return
6095 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6096 (js2-add-to-string c)
6097 (if (eq c quote)
6098 (throw 'return t)))
6099 (js2-xml-discard-string token) ;; throw away string in progress
6100 nil)))
6101
6102 (defun js2-read-xml-comment (token)
6103 (let ((c (js2-get-char)))
6104 (catch 'return
6105 (while (/= c js2-EOF_CHAR)
6106 (catch 'continue
6107 (js2-add-to-string c)
6108 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6109 (setq c (js2-get-char))
6110 (js2-add-to-string c)
6111 (if (eq (js2-peek-char) ?>)
6112 (progn
6113 (setq c (js2-get-char)) ;; skip >
6114 (js2-add-to-string c)
6115 (throw 'return t))
6116 (throw 'continue nil)))
6117 (setq c (js2-get-char))))
6118 (js2-xml-discard-string token)
6119 nil)))
6120
6121 (defun js2-read-cdata (token)
6122 (let ((c (js2-get-char)))
6123 (catch 'return
6124 (while (/= c js2-EOF_CHAR)
6125 (catch 'continue
6126 (js2-add-to-string c)
6127 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6128 (setq c (js2-get-char))
6129 (js2-add-to-string c)
6130 (if (eq (js2-peek-char) ?>)
6131 (progn
6132 (setq c (js2-get-char)) ;; Skip >
6133 (js2-add-to-string c)
6134 (throw 'return t))
6135 (throw 'continue nil)))
6136 (setq c (js2-get-char))))
6137 (js2-xml-discard-string token)
6138 nil)))
6139
6140 (defun js2-read-entity (token)
6141 (let ((decl-tags 1)
6142 c)
6143 (catch 'return
6144 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6145 (js2-add-to-string c)
6146 (case c
6147 (?<
6148 (incf decl-tags))
6149 (?>
6150 (decf decl-tags)
6151 (if (zerop decl-tags)
6152 (throw 'return t)))))
6153 (js2-xml-discard-string token)
6154 nil)))
6155
6156 (defun js2-read-PI (token)
6157 "Scan an XML processing instruction."
6158 (let (c)
6159 (catch 'return
6160 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6161 (js2-add-to-string c)
6162 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6163 (setq c (js2-get-char)) ;; Skip >
6164 (js2-add-to-string c)
6165 (throw 'return t)))
6166 (js2-xml-discard-string token)
6167 nil)))
6168
6169 ;;; Highlighting
6170
6171 (defun js2-set-face (beg end face &optional record)
6172 "Fontify a region. If RECORD is non-nil, record for later."
6173 (when (plusp js2-highlight-level)
6174 (setq beg (min (point-max) beg)
6175 beg (max (point-min) beg)
6176 end (min (point-max) end)
6177 end (max (point-min) end))
6178 (if record
6179 (push (list beg end face) js2-mode-fontifications)
6180 (put-text-property beg end 'font-lock-face face))))
6181
6182 (defsubst js2-clear-face (beg end)
6183 (remove-text-properties beg end '(font-lock-face nil
6184 help-echo nil
6185 point-entered nil
6186 c-in-sws nil)))
6187
6188 (defconst js2-ecma-global-props
6189 (concat "^"
6190 (regexp-opt
6191 '("Infinity" "NaN" "undefined" "arguments") t)
6192 "$")
6193 "Value properties of the Ecma-262 Global Object.
6194 Shown at or above `js2-highlight-level' 2.")
6195
6196 ;; might want to add the name "arguments" to this list?
6197 (defconst js2-ecma-object-props
6198 (concat "^"
6199 (regexp-opt
6200 '("prototype" "__proto__" "__parent__") t)
6201 "$")
6202 "Value properties of the Ecma-262 Object constructor.
6203 Shown at or above `js2-highlight-level' 2.")
6204
6205 (defconst js2-ecma-global-funcs
6206 (concat
6207 "^"
6208 (regexp-opt
6209 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6210 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6211 "$")
6212 "Function properties of the Ecma-262 Global object.
6213 Shown at or above `js2-highlight-level' 2.")
6214
6215 (defconst js2-ecma-number-props
6216 (concat "^"
6217 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6218 "NEGATIVE_INFINITY"
6219 "POSITIVE_INFINITY") t)
6220 "$")
6221 "Properties of the Ecma-262 Number constructor.
6222 Shown at or above `js2-highlight-level' 2.")
6223
6224 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6225 "Properties of the Ecma-262 Date constructor.
6226 Shown at or above `js2-highlight-level' 2.")
6227
6228 (defconst js2-ecma-math-props
6229 (concat "^"
6230 (regexp-opt
6231 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6232 t)
6233 "$")
6234 "Properties of the Ecma-262 Math object.
6235 Shown at or above `js2-highlight-level' 2.")
6236
6237 (defconst js2-ecma-math-funcs
6238 (concat "^"
6239 (regexp-opt
6240 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6241 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6242 "$")
6243 "Function properties of the Ecma-262 Math object.
6244 Shown at or above `js2-highlight-level' 2.")
6245
6246 (defconst js2-ecma-function-props
6247 (concat
6248 "^"
6249 (regexp-opt
6250 '(;; properties of the Object prototype object
6251 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6252 "toLocaleString" "toString" "valueOf"
6253 ;; properties of the Function prototype object
6254 "apply" "call"
6255 ;; properties of the Array prototype object
6256 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6257 "splice" "unshift"
6258 ;; properties of the String prototype object
6259 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6260 "localeCompare" "match" "replace" "search" "split" "substring"
6261 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6262 "toUpperCase"
6263 ;; properties of the Number prototype object
6264 "toExponential" "toFixed" "toPrecision"
6265 ;; properties of the Date prototype object
6266 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6267 "getMinutes" "getMonth" "getSeconds" "getTime"
6268 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6269 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6270 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6271 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6272 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6273 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6274 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6275 "toTimeString" "toUTCString"
6276 ;; properties of the RegExp prototype object
6277 "exec" "test"
6278 ;; properties of the JSON prototype object
6279 "parse" "stringify"
6280 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6281 "toSource" "__defineGetter__" "__defineSetter__"
6282 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6283 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6284 t)
6285 "$")
6286 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6287 Shown at or above `js2-highlight-level' 3.")
6288
6289 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6290 (let ((target-name (and target
6291 (js2-name-node-p target)
6292 (js2-name-node-name target)))
6293 (prop-name (if prop (js2-name-node-name prop)))
6294 (level2 (>= js2-highlight-level 2))
6295 (level3 (>= js2-highlight-level 3)))
6296 (when level2
6297 (let ((face
6298 (if call-p
6299 (cond
6300 ((and target prop)
6301 (cond
6302 ((and level3 (string-match js2-ecma-function-props prop-name))
6303 'font-lock-builtin-face)
6304 ((and target-name prop)
6305 (cond
6306 ((string= target-name "Date")
6307 (if (string-match js2-ecma-date-props prop-name)
6308 'font-lock-builtin-face))
6309 ((string= target-name "Math")
6310 (if (string-match js2-ecma-math-funcs prop-name)
6311 'font-lock-builtin-face))))))
6312 (prop
6313 (if (string-match js2-ecma-global-funcs prop-name)
6314 'font-lock-builtin-face)))
6315 (cond
6316 ((and target prop)
6317 (cond
6318 ((string= target-name "Number")
6319 (if (string-match js2-ecma-number-props prop-name)
6320 'font-lock-constant-face))
6321 ((string= target-name "Math")
6322 (if (string-match js2-ecma-math-props prop-name)
6323 'font-lock-constant-face))))
6324 (prop
6325 (if (string-match js2-ecma-object-props prop-name)
6326 'font-lock-constant-face))))))
6327 (when face
6328 (let ((pos (+ (js2-node-pos parent) ; absolute
6329 (js2-node-pos prop)))) ; relative
6330 (js2-set-face pos
6331 (+ pos (js2-node-len prop))
6332 face 'record)))))))
6333
6334 (defun js2-parse-highlight-member-expr-node (node)
6335 "Perform syntax highlighting of EcmaScript built-in properties.
6336 The variable `js2-highlight-level' governs this highighting."
6337 (let (face target prop name pos end parent call-p callee)
6338 (cond
6339 ;; case 1: simple name, e.g. foo
6340 ((js2-name-node-p node)
6341 (setq name (js2-name-node-name node))
6342 ;; possible for name to be nil in rare cases - saw it when
6343 ;; running js2-mode on an elisp buffer. Might as well try to
6344 ;; make it so js2-mode never barfs.
6345 (when name
6346 (setq face (if (string-match js2-ecma-global-props name)
6347 'font-lock-constant-face))
6348 (when face
6349 (setq pos (js2-node-pos node)
6350 end (+ pos (js2-node-len node)))
6351 (js2-set-face pos end face 'record))))
6352 ;; case 2: property access or function call
6353 ((or (js2-prop-get-node-p node)
6354 ;; highlight function call if expr is a prop-get node
6355 ;; or a plain name (i.e. unqualified function call)
6356 (and (setq call-p (js2-call-node-p node))
6357 (setq callee (js2-call-node-target node)) ; separate setq!
6358 (or (js2-prop-get-node-p callee)
6359 (js2-name-node-p callee))))
6360 (setq parent node
6361 node (if call-p callee node))
6362 (if (and call-p (js2-name-node-p callee))
6363 (setq prop callee)
6364 (setq target (js2-prop-get-node-left node)
6365 prop (js2-prop-get-node-right node)))
6366 (cond
6367 ((js2-name-node-p prop)
6368 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6369 (js2-parse-highlight-prop-get parent target prop call-p))
6370 ((js2-name-node-p target)
6371 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6372 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6373
6374 (defun js2-parse-highlight-member-expr-fn-name (expr)
6375 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6376 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6377 We currently only handle the case where the last component is a prop-get
6378 of a simple name. Called before EXPR has a parent node."
6379 (let (pos
6380 (name (and (js2-prop-get-node-p expr)
6381 (js2-prop-get-node-right expr))))
6382 (when (js2-name-node-p name)
6383 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6384 (js2-node-pos name)))
6385 (+ pos (js2-node-len name))
6386 'font-lock-function-name-face
6387 'record))))
6388
6389 ;; source: http://jsdoc.sourceforge.net/
6390 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6391 ;; allows type specifications, and needs work before entering the wild.
6392
6393 (defconst js2-jsdoc-param-tag-regexp
6394 (concat "^\\s-*\\*+\\s-*\\(@"
6395 "\\(?:param\\|argument\\)"
6396 "\\)"
6397 "\\s-*\\({[^}]+}\\)?" ; optional type
6398 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6399 "\\>")
6400 "Matches jsdoc tags with optional type and optional param name.")
6401
6402 (defconst js2-jsdoc-typed-tag-regexp
6403 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6404 (regexp-opt
6405 '("enum"
6406 "extends"
6407 "field"
6408 "id"
6409 "implements"
6410 "lends"
6411 "mods"
6412 "requires"
6413 "return"
6414 "returns"
6415 "throw"
6416 "throws"))
6417 "\\)\\)\\s-*\\({[^}]+}\\)?")
6418 "Matches jsdoc tags with optional type.")
6419
6420 (defconst js2-jsdoc-arg-tag-regexp
6421 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6422 (regexp-opt
6423 '("alias"
6424 "augments"
6425 "borrows"
6426 "bug"
6427 "base"
6428 "config"
6429 "default"
6430 "define"
6431 "exception"
6432 "function"
6433 "member"
6434 "memberOf"
6435 "name"
6436 "namespace"
6437 "property"
6438 "since"
6439 "suppress"
6440 "this"
6441 "throws"
6442 "type"
6443 "version"))
6444 "\\)\\)\\s-+\\([^ \t]+\\)")
6445 "Matches jsdoc tags with a single argument.")
6446
6447 (defconst js2-jsdoc-empty-tag-regexp
6448 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6449 (regexp-opt
6450 '("addon"
6451 "author"
6452 "class"
6453 "const"
6454 "constant"
6455 "constructor"
6456 "constructs"
6457 "deprecated"
6458 "desc"
6459 "description"
6460 "event"
6461 "example"
6462 "exec"
6463 "export"
6464 "fileoverview"
6465 "final"
6466 "function"
6467 "hidden"
6468 "ignore"
6469 "implicitCast"
6470 "inheritDoc"
6471 "inner"
6472 "interface"
6473 "license"
6474 "noalias"
6475 "noshadow"
6476 "notypecheck"
6477 "override"
6478 "owner"
6479 "preserve"
6480 "preserveTry"
6481 "private"
6482 "protected"
6483 "public"
6484 "static"
6485 "supported"
6486 ))
6487 "\\)\\)\\s-*")
6488 "Matches empty jsdoc tags.")
6489
6490 (defconst js2-jsdoc-link-tag-regexp
6491 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6492 "Matches a jsdoc link or code tag.")
6493
6494 (defconst js2-jsdoc-see-tag-regexp
6495 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6496 "Matches a jsdoc @see tag.")
6497
6498 (defconst js2-jsdoc-html-tag-regexp
6499 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6500 "Matches a simple (no attributes) html start- or end-tag.")
6501
6502 (defun js2-jsdoc-highlight-helper ()
6503 (js2-set-face (match-beginning 1)
6504 (match-end 1)
6505 'js2-jsdoc-tag)
6506 (if (match-beginning 2)
6507 (if (save-excursion
6508 (goto-char (match-beginning 2))
6509 (= (char-after) ?{))
6510 (js2-set-face (1+ (match-beginning 2))
6511 (1- (match-end 2))
6512 'js2-jsdoc-type)
6513 (js2-set-face (match-beginning 2)
6514 (match-end 2)
6515 'js2-jsdoc-value)))
6516 (if (match-beginning 3)
6517 (js2-set-face (match-beginning 3)
6518 (match-end 3)
6519 'js2-jsdoc-value)))
6520
6521 (defun js2-highlight-jsdoc (ast)
6522 "Highlight doc comment tags."
6523 (let ((comments (js2-ast-root-comments ast))
6524 beg end)
6525 (save-excursion
6526 (dolist (node comments)
6527 (when (eq (js2-comment-node-format node) 'jsdoc)
6528 (setq beg (js2-node-abs-pos node)
6529 end (+ beg (js2-node-len node)))
6530 (save-restriction
6531 (narrow-to-region beg end)
6532 (dolist (re (list js2-jsdoc-param-tag-regexp
6533 js2-jsdoc-typed-tag-regexp
6534 js2-jsdoc-arg-tag-regexp
6535 js2-jsdoc-link-tag-regexp
6536 js2-jsdoc-see-tag-regexp
6537 js2-jsdoc-empty-tag-regexp))
6538 (goto-char beg)
6539 (while (re-search-forward re nil t)
6540 (js2-jsdoc-highlight-helper)))
6541 ;; simple highlighting for html tags
6542 (goto-char beg)
6543 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6544 (js2-set-face (match-beginning 1)
6545 (match-end 1)
6546 'js2-jsdoc-html-tag-delimiter)
6547 (js2-set-face (match-beginning 2)
6548 (match-end 2)
6549 'js2-jsdoc-html-tag-name)
6550 (js2-set-face (match-beginning 3)
6551 (match-end 3)
6552 'js2-jsdoc-html-tag-delimiter))))))))
6553
6554 (defun js2-highlight-assign-targets (_node left right)
6555 "Highlight function properties and external variables."
6556 (let (leftpos name)
6557 ;; highlight vars and props assigned function values
6558 (when (js2-function-node-p right)
6559 (cond
6560 ;; var foo = function() {...}
6561 ((js2-name-node-p left)
6562 (setq name left))
6563 ;; foo.bar.baz = function() {...}
6564 ((and (js2-prop-get-node-p left)
6565 (js2-name-node-p (js2-prop-get-node-right left)))
6566 (setq name (js2-prop-get-node-right left))))
6567 (when name
6568 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6569 (+ leftpos (js2-node-len name))
6570 'font-lock-function-name-face
6571 'record)))))
6572
6573 (defun js2-record-name-node (node)
6574 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6575 later. NODE must be a name node."
6576 (let ((leftpos (js2-node-abs-pos node)))
6577 (push (list node js2-current-scope
6578 leftpos
6579 (+ leftpos (js2-node-len node)))
6580 js2-recorded-identifiers)))
6581
6582 (defun js2-highlight-undeclared-vars ()
6583 "After entire parse is finished, look for undeclared variable references.
6584 We have to wait until entire buffer is parsed, since JavaScript permits var
6585 decls to occur after they're used.
6586
6587 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6588 it is considered declared."
6589 (let (name)
6590 (dolist (entry js2-recorded-identifiers)
6591 (destructuring-bind (name-node scope pos end) entry
6592 (setq name (js2-name-node-name name-node))
6593 (unless (or (member name js2-global-externs)
6594 (member name js2-default-externs)
6595 (member name js2-additional-externs)
6596 (js2-get-defining-scope scope name))
6597 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6598 'js2-external-variable))))
6599 (setq js2-recorded-identifiers nil)))
6600
6601 (defun js2-set-default-externs ()
6602 "Set the value of `js2-default-externs' based on the various
6603 `js2-include-?-externs' variables."
6604 (setq js2-default-externs
6605 (append js2-ecma-262-externs
6606 (if js2-include-browser-externs js2-browser-externs)
6607 (if js2-include-rhino-externs js2-rhino-externs)
6608 (if js2-include-node-externs js2-node-externs)
6609 (if (or js2-include-browser-externs js2-include-node-externs)
6610 js2-typed-array-externs))))
6611
6612 (defun js2-apply-jslint-globals ()
6613 (setq js2-additional-externs
6614 (nconc (js2-get-jslint-globals)
6615 js2-additional-externs)))
6616
6617 (defun js2-get-jslint-globals ()
6618 (loop for node in (js2-ast-root-comments js2-mode-ast)
6619 when (and (eq 'block (js2-comment-node-format node))
6620 (save-excursion
6621 (goto-char (js2-node-abs-pos node))
6622 (looking-at "/\\*global ")))
6623 append (js2-get-jslint-globals-in
6624 (match-end 0)
6625 (js2-node-abs-end node))))
6626
6627 (defun js2-get-jslint-globals-in (beg end)
6628 (let (res)
6629 (save-excursion
6630 (goto-char beg)
6631 (while (re-search-forward js2-mode-identifier-re end t)
6632 (let ((match (match-string 0)))
6633 (unless (member match '("true" "false"))
6634 (push match res)))))
6635 (nreverse res)))
6636
6637 ;;; IMenu support
6638
6639 ;; We currently only support imenu, but eventually should support speedbar and
6640 ;; possibly other browsing mechanisms.
6641
6642 ;; The basic strategy is to identify function assignment targets of the form
6643 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6644 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6645 ;; for imenu after parsing is finished.
6646
6647 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6648 ;; JavaScript, and the general problem is undecidable. However, several forms
6649 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6650 ;; include:
6651
6652 ;; function foo() -- function declaration
6653 ;; foo = function() -- function expression assigned to variable
6654 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6655 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6656 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6657 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6658 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6659 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6660 ;; function foo() {function bar() {...}} -- nested function
6661 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6662
6663 ;; This list boils down to a few forms that can be combined recursively.
6664 ;; Top-level named function declarations include both the left-hand (name)
6665 ;; and the right-hand (function value) expressions needed to produce an imenu
6666 ;; entry. The other "right-hand" forms we need to look for are:
6667 ;; - functions declared as props/getters/setters in object literals
6668 ;; - nested named function declarations
6669 ;; The "left-hand" expressions that functions can be assigned to include:
6670 ;; - local/global variables
6671 ;; - nested property-get expressions like a.b.c.d
6672 ;; - element gets like foo[10] or foo['bar'] where the index
6673 ;; expression can be trivially converted to a property name. They
6674 ;; effectively then become property gets.
6675
6676 ;; All the different definition types are canonicalized into the form
6677 ;; foo.bar.baz = position-of-function-keyword
6678
6679 ;; We need to build a trie-like structure for imenu. As an example,
6680 ;; consider the following JavaScript code:
6681
6682 ;; a = function() {...} // function at position 5
6683 ;; b = function() {...} // function at position 25
6684 ;; foo = function() {...} // function at position 100
6685 ;; foo.bar = function() {...} // function at position 200
6686 ;; foo.bar.baz = function() {...} // function at position 300
6687 ;; foo.bar.zab = function() {...} // function at position 400
6688
6689 ;; During parsing we accumulate an entry for each definition in
6690 ;; the variable `js2-imenu-recorder', like so:
6691
6692 ;; '((fn a 5)
6693 ;; (fn b 25)
6694 ;; (fn foo 100)
6695 ;; (fn foo bar 200)
6696 ;; (fn foo bar baz 300)
6697 ;; (fn foo bar zab 400))
6698
6699 ;; Where 'fn' is the respective function node.
6700 ;; After parsing these entries are merged into this alist-trie:
6701
6702 ;; '((a . 1)
6703 ;; (b . 2)
6704 ;; (foo (<definition> . 3)
6705 ;; (bar (<definition> . 6)
6706 ;; (baz . 100)
6707 ;; (zab . 200))))
6708
6709 ;; Note the wacky need for a <definition> name. The token can be anything
6710 ;; that isn't a valid JavaScript identifier, because you might make foo
6711 ;; a function and then start setting properties on it that are also functions.
6712
6713 (defun js2-prop-node-name (node)
6714 "Return the name of a node that may be a property-get/property-name.
6715 If NODE is not a valid name-node, string-node or integral number-node,
6716 returns nil. Otherwise returns the string name/value of the node."
6717 (cond
6718 ((js2-name-node-p node)
6719 (js2-name-node-name node))
6720 ((js2-string-node-p node)
6721 (js2-string-node-value node))
6722 ((and (js2-number-node-p node)
6723 (string-match "^[0-9]+$" (js2-number-node-value node)))
6724 (js2-number-node-value node))
6725 ((js2-this-node-p node)
6726 "this")))
6727
6728 (defun js2-node-qname-component (node)
6729 "Return the name of this node, if it contributes to a qname.
6730 Returns nil if the node doesn't contribute."
6731 (copy-sequence
6732 (or (js2-prop-node-name node)
6733 (if (and (js2-function-node-p node)
6734 (js2-function-node-name node))
6735 (js2-name-node-name (js2-function-node-name node))))))
6736
6737 (defun js2-record-imenu-entry (fn-node qname pos)
6738 "Add an entry to `js2-imenu-recorder'.
6739 FN-NODE should be the current item's function node.
6740
6741 Associate FN-NODE with its QNAME for later lookup.
6742 This is used in postprocessing the chain list. For each chain, we find
6743 the parent function, look up its qname, then prepend a copy of it to the chain."
6744 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6745 (unless js2-imenu-function-map
6746 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6747 (puthash fn-node qname js2-imenu-function-map))
6748
6749 (defun js2-record-imenu-functions (node &optional var)
6750 "Record function definitions for imenu.
6751 NODE is a function node or an object literal.
6752 VAR, if non-nil, is the expression that NODE is being assigned to.
6753 When passed arguments of wrong type, does nothing."
6754 (when js2-parse-ide-mode
6755 (let ((fun-p (js2-function-node-p node))
6756 qname fname-node)
6757 (cond
6758 ;; non-anonymous function declaration?
6759 ((and fun-p
6760 (not var)
6761 (setq fname-node (js2-function-node-name node)))
6762 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6763 ;; for remaining forms, compute left-side tree branch first
6764 ((and var (setq qname (js2-compute-nested-prop-get var)))
6765 (cond
6766 ;; foo.bar.baz = function
6767 (fun-p
6768 (js2-record-imenu-entry node qname (js2-node-pos node)))
6769 ;; foo.bar.baz = object-literal
6770 ;; look for nested functions: {a: {b: function() {...} }}
6771 ((js2-object-node-p node)
6772 ;; Node position here is still absolute, since the parser
6773 ;; passes the assignment target and value expressions
6774 ;; to us before they are added as children of the assignment node.
6775 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6776
6777 (defun js2-compute-nested-prop-get (node)
6778 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6779 component nodes as a list. Otherwise return nil. Element-gets are treated
6780 as property-gets if the index expression is a string, or a positive integer."
6781 (let (left right head)
6782 (cond
6783 ((or (js2-name-node-p node)
6784 (js2-this-node-p node))
6785 (list node))
6786 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6787 ((js2-prop-get-node-p node) ; foo.bar
6788 (setq left (js2-prop-get-node-left node)
6789 right (js2-prop-get-node-right node))
6790 (if (setq head (js2-compute-nested-prop-get left))
6791 (nconc head (list right))))
6792 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6793 (setq left (js2-elem-get-node-target node)
6794 right (js2-elem-get-node-element node))
6795 (if (or (js2-string-node-p right) ; ['bar']
6796 (and (js2-number-node-p right) ; [10]
6797 (string-match "^[0-9]+$"
6798 (js2-number-node-value right))))
6799 (if (setq head (js2-compute-nested-prop-get left))
6800 (nconc head (list right))))))))
6801
6802 (defun js2-record-object-literal (node qname pos)
6803 "Recursively process an object literal looking for functions.
6804 NODE is an object literal that is the right-hand child of an assignment
6805 expression. QNAME is a list of nodes representing the assignment target,
6806 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6807 POS is the absolute position of the node.
6808 We do a depth-first traversal of NODE. For any functions we find,
6809 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6810 (let (right)
6811 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6812 (let ((left (js2-infix-node-left e))
6813 ;; Element positions are relative to the parent position.
6814 (pos (+ pos (js2-node-pos e))))
6815 (cond
6816 ;; foo: function() {...}
6817 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6818 (when (js2-prop-node-name left)
6819 ;; As a policy decision, we record the position of the property,
6820 ;; not the position of the `function' keyword, since the property
6821 ;; is effectively the name of the function.
6822 (js2-record-imenu-entry right (append qname (list left)) pos)))
6823 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6824 ((js2-object-node-p right)
6825 (js2-record-object-literal right
6826 (append qname (list (js2-infix-node-left e)))
6827 (+ pos (js2-node-pos right)))))))))
6828
6829 (defun js2-node-top-level-decl-p (node)
6830 "Return t if NODE's name is defined in the top-level scope.
6831 Also returns t if NODE's name is not defined in any scope, since it implies
6832 that it's an external variable, which must also be in the top-level scope."
6833 (let* ((name (js2-prop-node-name node))
6834 (this-scope (js2-node-get-enclosing-scope node))
6835 defining-scope)
6836 (cond
6837 ((js2-this-node-p node)
6838 nil)
6839 ((null this-scope)
6840 t)
6841 ((setq defining-scope (js2-get-defining-scope this-scope name))
6842 (js2-ast-root-p defining-scope))
6843 (t t))))
6844
6845 (defun js2-wrapper-function-p (node)
6846 "Return t if NODE is a function expression that's immediately invoked.
6847 NODE must be `js2-function-node'."
6848 (let ((parent (js2-node-parent node)))
6849 (or
6850 ;; function(){...}();
6851 (and (js2-call-node-p parent)
6852 (eq node (js2-call-node-target parent)))
6853 (and (js2-paren-node-p parent)
6854 ;; (function(){...})();
6855 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6856 ;; (function(){...}).call(this);
6857 (and (js2-prop-get-node-p parent)
6858 (member (js2-name-node-name (js2-prop-get-node-right parent))
6859 '("call" "apply"))
6860 (js2-call-node-p (js2-node-parent parent))))))))
6861
6862 (defun js2-browse-postprocess-chains ()
6863 "Modify function-declaration name chains after parsing finishes.
6864 Some of the information is only available after the parse tree is complete.
6865 For instance, processing a nested scope requires a parent function node."
6866 (let (result fn parent-qname p elem)
6867 (dolist (entry js2-imenu-recorder)
6868 ;; function node goes first
6869 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6870 ;; Examine head's defining scope:
6871 ;; Pre-processed chain, or top-level/external, keep as-is.
6872 (if (or (stringp head) (js2-node-top-level-decl-p head))
6873 (push chain result)
6874 (when (js2-this-node-p head)
6875 (setq chain (cdr chain))) ; discard this-node
6876 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6877 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6878 (when (eq parent-qname 'not-found)
6879 ;; anonymous function expressions are not recorded
6880 ;; during the parse, so we need to handle this case here
6881 (setq parent-qname
6882 (if (js2-wrapper-function-p fn)
6883 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6884 (if (js2-ast-root-p grandparent)
6885 nil
6886 (gethash grandparent js2-imenu-function-map 'skip)))
6887 'skip))
6888 (puthash fn parent-qname js2-imenu-function-map))
6889 (if (eq parent-qname 'skip)
6890 ;; We don't show it, let's record that fact.
6891 (remhash current-fn js2-imenu-function-map)
6892 ;; Prepend parent fn qname to this chain.
6893 (let ((qname (append parent-qname chain)))
6894 (puthash current-fn (butlast qname) js2-imenu-function-map)
6895 (push qname result)))))))
6896 ;; Collect chains obtained by third-party code.
6897 (let (js2-imenu-recorder)
6898 (run-hooks 'js2-build-imenu-callbacks)
6899 (dolist (entry js2-imenu-recorder)
6900 (push (cdr entry) result)))
6901 ;; Finally replace each node in each chain with its name.
6902 (dolist (chain result)
6903 (setq p chain)
6904 (while p
6905 (if (js2-node-p (setq elem (car p)))
6906 (setcar p (js2-node-qname-component elem)))
6907 (setq p (cdr p))))
6908 result))
6909
6910 ;; Merge name chains into a trie-like tree structure of nested lists.
6911 ;; To simplify construction of the trie, we first build it out using the rule
6912 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6913 ;; [key, num-or-list]. The second element can be a number; if so, this key
6914 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6915 ;; associated with the key at this level.) Otherwise the second element is
6916 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6917 ;; a simple recursive formulation.
6918 ;;
6919 ;; js2-mode is building the data structure for imenu. The imenu documentation
6920 ;; claims that it's the structure above, but in practice it wants the children
6921 ;; at the same list level as the key for that level, which is how I've drawn
6922 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6923 ;; list wrapper around the children at each level.
6924 ;;
6925 ;; A completed nested imenu-alist entry looks like this:
6926 ;; '(("foo"
6927 ;; ("<definition>" . 7)
6928 ;; ("bar"
6929 ;; ("a" . 40)
6930 ;; ("b" . 60))))
6931 ;;
6932 ;; In particular, the documentation for `imenu--index-alist' says that
6933 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6934 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6935
6936 (defun js2-treeify (lst)
6937 "Convert (a b c d) to (a ((b ((c d)))))."
6938 (if (null (cddr lst)) ; list length <= 2
6939 lst
6940 (list (car lst) (list (js2-treeify (cdr lst))))))
6941
6942 (defun js2-build-alist-trie (chains trie)
6943 "Merge declaration name chains into a trie-like alist structure for imenu.
6944 CHAINS is the qname chain list produced during parsing. TRIE is a
6945 list of elements built up so far."
6946 (let (head tail pos branch kids)
6947 (dolist (chain chains)
6948 (setq head (car chain)
6949 tail (cdr chain)
6950 pos (if (numberp (car tail)) (car tail))
6951 branch (js2-find-if (lambda (n)
6952 (string= (car n) head))
6953 trie)
6954 kids (second branch))
6955 (cond
6956 ;; case 1: this key isn't in the trie yet
6957 ((null branch)
6958 (if trie
6959 (setcdr (last trie) (list (js2-treeify chain)))
6960 (setq trie (list (js2-treeify chain)))))
6961 ;; case 2: key is present with a single number entry: replace w/ list
6962 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6963 ;; ("<definition>" 20)))
6964 ((numberp kids)
6965 (setcar (cdr branch)
6966 (list (list "<definition-1>" kids)
6967 (if pos
6968 (list "<definition-2>" pos)
6969 (js2-treeify tail)))))
6970 ;; case 3: key is there (with kids), and we're a number entry
6971 (pos
6972 (setcdr (last kids)
6973 (list
6974 (list (format "<definition-%d>"
6975 (1+ (loop for kid in kids
6976 count (eq ?< (aref (car kid) 0)))))
6977 pos))))
6978 ;; case 4: key is there with kids, need to merge in our chain
6979 (t
6980 (js2-build-alist-trie (list tail) kids))))
6981 trie))
6982
6983 (defun js2-flatten-trie (trie)
6984 "Convert TRIE to imenu-format.
6985 Recurses through nodes, and for each one whose second element is a list,
6986 appends the list's flattened elements to the current element. Also
6987 changes the tails into conses. For instance, this pre-flattened trie
6988
6989 '(a ((b 20)
6990 (c ((d 30)
6991 (e 40)))))
6992
6993 becomes
6994
6995 '(a (b . 20)
6996 (c (d . 30)
6997 (e . 40)))
6998
6999 Note that the root of the trie has no key, just a list of chains.
7000 This is also true for the value of any key with multiple children,
7001 e.g. key 'c' in the example above."
7002 (cond
7003 ((listp (car trie))
7004 (mapcar #'js2-flatten-trie trie))
7005 (t
7006 (if (numberp (second trie))
7007 (cons (car trie) (second trie))
7008 ;; else pop list and append its kids
7009 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7010
7011 (defun js2-build-imenu-index ()
7012 "Turn `js2-imenu-recorder' into an imenu data structure."
7013 (when (eq js2-imenu-recorder 'empty)
7014 (setq js2-imenu-recorder nil))
7015 (let* ((chains (js2-browse-postprocess-chains))
7016 (result (js2-build-alist-trie chains nil)))
7017 (js2-flatten-trie result)))
7018
7019 (defun js2-test-print-chains (chains)
7020 "Print a list of qname chains.
7021 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7022 i.e. one or more nodes, and an integer position as the list tail."
7023 (mapconcat (lambda (chain)
7024 (concat "("
7025 (mapconcat (lambda (elem)
7026 (if (js2-node-p elem)
7027 (or (js2-node-qname-component elem)
7028 "nil")
7029 (number-to-string elem)))
7030 chain
7031 " ")
7032 ")"))
7033 chains
7034 "\n"))
7035
7036 ;;; Parser
7037
7038 (defconst js2-version "1.8.5"
7039 "Version of JavaScript supported.")
7040
7041 (defun js2-record-face (face &optional token)
7042 "Record a style run of FACE for TOKEN or the current token."
7043 (unless token (setq token (js2-current-token)))
7044 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7045
7046 (defsubst js2-node-end (n)
7047 "Computes the absolute end of node N.
7048 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7049 is only true until the node is added to its parent; i.e., while parsing."
7050 (+ (js2-node-pos n)
7051 (js2-node-len n)))
7052
7053 (defun js2-record-comment (token)
7054 "Record a comment in `js2-scanned-comments'."
7055 (let ((ct (js2-token-comment-type token))
7056 (beg (js2-token-beg token))
7057 (end (js2-token-end token)))
7058 (push (make-js2-comment-node :len (- end beg)
7059 :format ct)
7060 js2-scanned-comments)
7061 (when js2-parse-ide-mode
7062 (js2-record-face (if (eq ct 'jsdoc)
7063 'font-lock-doc-face
7064 'font-lock-comment-face)
7065 token)
7066 (when (memq ct '(html preprocessor))
7067 ;; Tell cc-engine the bounds of the comment.
7068 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7069
7070 (defun js2-peek-token ()
7071 "Return the next token type without consuming it.
7072 If `js2-ti-lookahead' is positive, return the type of next token
7073 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7074 (if (not (zerop js2-ti-lookahead))
7075 (js2-token-type
7076 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7077 (let ((tt (js2-get-token-internal)))
7078 (js2-unget-token)
7079 tt)))
7080
7081 (defalias 'js2-next-token 'js2-get-token)
7082
7083 (defun js2-match-token (match &optional dont-unget)
7084 "Get next token and return t if it matches MATCH, a bytecode.
7085 Returns nil and consumes nothing if MATCH is not the next token."
7086 (if (/= (js2-get-token) match)
7087 (ignore (unless dont-unget (js2-unget-token)))
7088 t))
7089
7090 (defun js2-match-contextual-kwd (name)
7091 "Consume and return t if next token is `js2-NAME', and its
7092 string is NAME. Returns nil and keeps current token otherwise."
7093 (if (or (/= (js2-get-token) js2-NAME)
7094 (not (string= (js2-current-token-string) name)))
7095 (progn
7096 (js2-unget-token)
7097 nil)
7098 (js2-record-face 'font-lock-keyword-face)
7099 t))
7100
7101 (defun js2-valid-prop-name-token (tt)
7102 (or (= tt js2-NAME)
7103 (and js2-allow-keywords-as-property-names
7104 (plusp tt)
7105 (or (= tt js2-RESERVED)
7106 (aref js2-kwd-tokens tt)))))
7107
7108 (defun js2-match-prop-name ()
7109 "Consume token and return t if next token is a valid property name.
7110 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7111 is non-nil and it's a keyword token."
7112 (if (js2-valid-prop-name-token (js2-get-token))
7113 t
7114 (js2-unget-token)
7115 nil))
7116
7117 (defun js2-must-match-prop-name (msg-id &optional pos len)
7118 (if (js2-match-prop-name)
7119 t
7120 (js2-report-error msg-id nil pos len)
7121 nil))
7122
7123 (defun js2-peek-token-or-eol ()
7124 "Return js2-EOL if the next token immediately follows a newline.
7125 Else returns the next token. Used in situations where we don't
7126 consider certain token types valid if they are preceded by a newline.
7127 One example is the postfix ++ or -- operator, which has to be on the
7128 same line as its operand."
7129 (let ((tt (js2-get-token))
7130 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7131 (js2-unget-token)
7132 (if follows-eol
7133 js2-EOL
7134 tt)))
7135
7136 (defun js2-must-match (token msg-id &optional pos len)
7137 "Match next token to token code TOKEN, or record a syntax error.
7138 MSG-ID is the error message to report if the match fails.
7139 Returns t on match, nil if no match."
7140 (if (js2-match-token token t)
7141 t
7142 (js2-report-error msg-id nil pos len)
7143 (js2-unget-token)
7144 nil))
7145
7146 (defun js2-must-match-name (msg-id)
7147 (if (js2-match-token js2-NAME t)
7148 t
7149 (if (eq (js2-current-token-type) js2-RESERVED)
7150 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7151 (js2-report-error msg-id)
7152 (js2-unget-token))
7153 nil))
7154
7155 (defsubst js2-inside-function ()
7156 (plusp js2-nesting-of-function))
7157
7158 (defun js2-set-requires-activation ()
7159 (if (js2-function-node-p js2-current-script-or-fn)
7160 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7161
7162 (defun js2-check-activation-name (name _token)
7163 (when (js2-inside-function)
7164 ;; skip language-version 1.2 check from Rhino
7165 (if (or (string= "arguments" name)
7166 (and js2-compiler-activation-names ; only used in codegen
7167 (gethash name js2-compiler-activation-names)))
7168 (js2-set-requires-activation))))
7169
7170 (defun js2-set-is-generator ()
7171 (let ((fn-node js2-current-script-or-fn))
7172 (when (and (js2-function-node-p fn-node)
7173 (not (js2-function-node-generator-type fn-node)))
7174 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7175
7176 (defun js2-must-have-xml ()
7177 (unless js2-compiler-xml-available
7178 (js2-report-error "msg.XML.not.available")))
7179
7180 (defun js2-push-scope (scope)
7181 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7182 (assert (js2-scope-p scope))
7183 (assert (null (js2-scope-parent-scope scope)))
7184 (assert (not (eq js2-current-scope scope)))
7185 (setf (js2-scope-parent-scope scope) js2-current-scope
7186 js2-current-scope scope))
7187
7188 (defsubst js2-pop-scope ()
7189 (setq js2-current-scope
7190 (js2-scope-parent-scope js2-current-scope)))
7191
7192 (defun js2-enter-loop (loop-node)
7193 (push loop-node js2-loop-set)
7194 (push loop-node js2-loop-and-switch-set)
7195 (js2-push-scope loop-node)
7196 ;; Tell the current labeled statement (if any) its statement,
7197 ;; and set the jump target of the first label to the loop.
7198 ;; These are used in `js2-parse-continue' to verify that the
7199 ;; continue target is an actual labeled loop. (And for codegen.)
7200 (when js2-labeled-stmt
7201 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7202 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7203 js2-labeled-stmt))) loop-node)))
7204
7205 (defun js2-exit-loop ()
7206 (pop js2-loop-set)
7207 (pop js2-loop-and-switch-set)
7208 (js2-pop-scope))
7209
7210 (defsubst js2-enter-switch (switch-node)
7211 (push switch-node js2-loop-and-switch-set))
7212
7213 (defsubst js2-exit-switch ()
7214 (pop js2-loop-and-switch-set))
7215
7216 (defun js2-parse (&optional buf cb)
7217 "Tell the js2 parser to parse a region of JavaScript.
7218
7219 BUF is a buffer or buffer name containing the code to parse.
7220 Call `narrow-to-region' first to parse only part of the buffer.
7221
7222 The returned AST root node is given some additional properties:
7223 `node-count' - total number of nodes in the AST
7224 `buffer' - BUF. The buffer it refers to may change or be killed,
7225 so the value is not necessarily reliable.
7226
7227 An optional callback CB can be specified to report parsing
7228 progress. If `(functionp CB)' returns t, it will be called with
7229 the current line number once before parsing begins, then again
7230 each time the lexer reaches a new line number.
7231
7232 CB can also be a list of the form `(symbol cb ...)' to specify
7233 multiple callbacks with different criteria. Each symbol is a
7234 criterion keyword, and the following element is the callback to
7235 call
7236
7237 :line - called whenever the line number changes
7238 :token - called for each new token consumed
7239
7240 The list of criteria could be extended to include entering or
7241 leaving a statement, an expression, or a function definition."
7242 (if (and cb (not (functionp cb)))
7243 (error "criteria callbacks not yet implemented"))
7244 (let ((inhibit-point-motion-hooks t)
7245 (js2-compiler-xml-available (>= js2-language-version 160))
7246 ;; This is a recursive-descent parser, so give it a big stack.
7247 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7248 (max-specpdl-size (max max-specpdl-size 3000))
7249 (case-fold-search nil)
7250 ast)
7251 (with-current-buffer (or buf (current-buffer))
7252 (setq js2-scanned-comments nil
7253 js2-parsed-errors nil
7254 js2-parsed-warnings nil
7255 js2-imenu-recorder nil
7256 js2-imenu-function-map nil
7257 js2-label-set nil)
7258 (js2-init-scanner)
7259 (setq ast (with-silent-modifications
7260 (js2-do-parse)))
7261 (unless js2-ts-hit-eof
7262 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7263 (setf (js2-ast-root-errors ast) js2-parsed-errors
7264 (js2-ast-root-warnings ast) js2-parsed-warnings)
7265 ;; if we didn't find any declarations, put a dummy in this list so we
7266 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7267 (unless js2-imenu-recorder
7268 (setq js2-imenu-recorder 'empty))
7269 (run-hooks 'js2-parse-finished-hook)
7270 ast)))
7271
7272 ;; Corresponds to Rhino's Parser.parse() method.
7273 (defun js2-do-parse ()
7274 "Parse current buffer starting from current point.
7275 Scanner should be initialized."
7276 (let ((pos js2-ts-cursor)
7277 (end js2-ts-cursor) ; in case file is empty
7278 root n tt)
7279 ;; initialize buffer-local parsing vars
7280 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7281 js2-current-script-or-fn root
7282 js2-current-scope root
7283 js2-nesting-of-function 0
7284 js2-labeled-stmt nil
7285 js2-recorded-identifiers nil) ; for js2-highlight
7286 (while (/= (setq tt (js2-get-token)) js2-EOF)
7287 (if (= tt js2-FUNCTION)
7288 (progn
7289 (setq n (if js2-called-by-compile-function
7290 (js2-parse-function-expr)
7291 (js2-parse-function-stmt))))
7292 ;; not a function - parse a statement
7293 (js2-unget-token)
7294 (setq n (js2-parse-statement)))
7295 ;; add function or statement to script
7296 (setq end (js2-node-end n))
7297 (js2-block-node-push root n))
7298 ;; add comments to root in lexical order
7299 (when js2-scanned-comments
7300 ;; if we find a comment beyond end of normal kids, use its end
7301 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7302 (dolist (comment js2-scanned-comments)
7303 (push comment (js2-ast-root-comments root))
7304 (js2-node-add-children root comment)))
7305 (setf (js2-node-len root) (- end pos))
7306 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7307 ;; Give extensions a chance to muck with things before highlighting starts.
7308 (let ((js2-additional-externs js2-additional-externs))
7309 (save-excursion
7310 (run-hooks 'js2-post-parse-callbacks))
7311 (js2-highlight-undeclared-vars))
7312 root))
7313
7314 (defun js2-parse-function-closure-body (fn-node)
7315 "Parse a JavaScript 1.8 function closure body."
7316 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7317 (if js2-ts-hit-eof
7318 (js2-report-error "msg.no.brace.body" nil
7319 (js2-node-pos fn-node)
7320 (- js2-ts-cursor (js2-node-pos fn-node)))
7321 (js2-node-add-children fn-node
7322 (setf (js2-function-node-body fn-node)
7323 (js2-parse-expr t))))))
7324
7325 (defun js2-parse-function-body (fn-node)
7326 (js2-must-match js2-LC "msg.no.brace.body"
7327 (js2-node-pos fn-node)
7328 (- js2-ts-cursor (js2-node-pos fn-node)))
7329 (let ((pos (js2-current-token-beg)) ; LC position
7330 (pn (make-js2-block-node)) ; starts at LC position
7331 tt
7332 end)
7333 (incf js2-nesting-of-function)
7334 (unwind-protect
7335 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7336 (= tt js2-EOF)
7337 (= tt js2-RC)))
7338 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7339 (js2-parse-statement)
7340 (js2-get-token)
7341 (js2-parse-function-stmt))))
7342 (decf js2-nesting-of-function))
7343 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7344 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7345 (setq end (js2-current-token-end)))
7346 (setf (js2-node-pos pn) pos
7347 (js2-node-len pn) (- end pos))
7348 (setf (js2-function-node-body fn-node) pn)
7349 (js2-node-add-children fn-node pn)
7350 pn))
7351
7352 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7353 "Declare and fontify destructuring parameters inside NODE.
7354 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7355 (cond
7356 ((js2-name-node-p node)
7357 (let (leftpos)
7358 (js2-define-symbol decl-type (js2-name-node-name node)
7359 node ignore-not-in-block)
7360 (when face
7361 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7362 (+ leftpos (js2-node-len node))
7363 face 'record))))
7364 ((js2-object-node-p node)
7365 (dolist (elem (js2-object-node-elems node))
7366 (js2-define-destruct-symbols
7367 (if (js2-object-prop-node-p elem)
7368 (js2-object-prop-node-right elem)
7369 ;; abbreviated destructuring {a, b}
7370 elem)
7371 decl-type face ignore-not-in-block)))
7372 ((js2-array-node-p node)
7373 (dolist (elem (js2-array-node-elems node))
7374 (when elem
7375 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7376 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7377 (js2-node-len node)))))
7378
7379 (defun js2-parse-function-params (function-type fn-node pos)
7380 (if (js2-match-token js2-RP)
7381 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7382 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7383 (eq (js2-current-token-type) js2-NAME)))
7384 params param default-found rest-param-at)
7385 (when paren-free-arrow
7386 (js2-unget-token))
7387 (loop for tt = (js2-peek-token)
7388 do
7389 (cond
7390 ;; destructuring param
7391 ((and (not paren-free-arrow)
7392 (or (= tt js2-LB) (= tt js2-LC)))
7393 (js2-get-token)
7394 (when default-found
7395 (js2-report-error "msg.no.default.after.default.param"))
7396 (setq param (js2-parse-destruct-primary-expr))
7397 (js2-define-destruct-symbols param
7398 js2-LP
7399 'js2-function-param)
7400 (push param params))
7401 ;; variable name
7402 (t
7403 (when (and (>= js2-language-version 200)
7404 (not paren-free-arrow)
7405 (js2-match-token js2-TRIPLEDOT)
7406 (not rest-param-at))
7407 ;; to report errors if there are more parameters
7408 (setq rest-param-at (length params)))
7409 (js2-must-match-name "msg.no.parm")
7410 (js2-record-face 'js2-function-param)
7411 (setq param (js2-create-name-node))
7412 (js2-define-symbol js2-LP (js2-current-token-string) param)
7413 ;; default parameter value
7414 (when (or (and default-found
7415 (not rest-param-at)
7416 (js2-must-match js2-ASSIGN
7417 "msg.no.default.after.default.param"
7418 (js2-node-pos param)
7419 (js2-node-len param)))
7420 (and (>= js2-language-version 200)
7421 (js2-match-token js2-ASSIGN)))
7422 (assert (not paren-free-arrow))
7423 (let* ((pos (js2-node-pos param))
7424 (tt (js2-current-token-type))
7425 (op-pos (- (js2-current-token-beg) pos))
7426 (left param)
7427 (right (js2-parse-assign-expr))
7428 (len (- (js2-node-end right) pos)))
7429 (setq param (make-js2-assign-node
7430 :type tt :pos pos :len len :op-pos op-pos
7431 :left left :right right)
7432 default-found t)
7433 (js2-node-add-children param left right)))
7434 (push param params)))
7435 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7436 (js2-report-error "msg.param.after.rest" nil
7437 (js2-node-pos param) (js2-node-len param)))
7438 while
7439 (js2-match-token js2-COMMA))
7440 (when (and (not paren-free-arrow)
7441 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7442 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7443 (when rest-param-at
7444 (setf (js2-function-node-rest-p fn-node) t))
7445 (dolist (p params)
7446 (js2-node-add-children fn-node p)
7447 (push p (js2-function-node-params fn-node))))))
7448
7449 (defun js2-check-inconsistent-return-warning (fn-node name)
7450 "Possibly show inconsistent-return warning.
7451 Last token scanned is the close-curly for the function body."
7452 (when (and js2-mode-show-strict-warnings
7453 js2-strict-inconsistent-return-warning
7454 (not (js2-has-consistent-return-usage
7455 (js2-function-node-body fn-node))))
7456 ;; Have it extend from close-curly to bol or beginning of block.
7457 (let ((pos (save-excursion
7458 (goto-char (js2-current-token-end))
7459 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7460 (point-at-bol))))
7461 (end (js2-current-token-end)))
7462 (if (plusp (js2-name-node-length name))
7463 (js2-add-strict-warning "msg.no.return.value"
7464 (js2-name-node-name name) pos end)
7465 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7466
7467 (defun js2-parse-function-stmt ()
7468 (let ((pos (js2-current-token-beg))
7469 (star-p (js2-match-token js2-MUL)))
7470 (js2-must-match-name "msg.unnamed.function.stmt")
7471 (let ((name (js2-create-name-node t))
7472 pn member-expr)
7473 (cond
7474 ((js2-match-token js2-LP)
7475 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7476 (js2-allow-member-expr-as-function-name
7477 (setq member-expr (js2-parse-member-expr-tail nil name))
7478 (js2-parse-highlight-member-expr-fn-name member-expr)
7479 (js2-must-match js2-LP "msg.no.paren.parms")
7480 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7481 (js2-function-node-member-expr pn) member-expr)
7482 pn)
7483 (t
7484 (js2-report-error "msg.no.paren.parms")
7485 (make-js2-error-node))))))
7486
7487 (defun js2-parse-function-expr ()
7488 (let ((pos (js2-current-token-beg))
7489 (star-p (js2-match-token js2-MUL))
7490 name)
7491 (when (js2-match-token js2-NAME)
7492 (setq name (js2-create-name-node t)))
7493 (js2-must-match js2-LP "msg.no.paren.parms")
7494 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7495
7496 (defun js2-parse-function (function-type pos star-p &optional name)
7497 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7498 beginning of the first token (function keyword, unless it's an
7499 arrow function), NAME is js2-name-node."
7500 (let (fn-node lp)
7501 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7502 (setq lp (js2-current-token-beg)))
7503 (setf fn-node (make-js2-function-node :pos pos
7504 :name name
7505 :form function-type
7506 :lp (if lp (- lp pos))
7507 :generator-type (and star-p 'STAR)))
7508 (when name
7509 (js2-set-face (js2-node-pos name) (js2-node-end name)
7510 'font-lock-function-name-face 'record)
7511 (when (plusp (js2-name-node-length name))
7512 ;; Function statements define a symbol in the enclosing scope
7513 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7514 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7515 ;; 1. Nested functions are not affected by the dynamic scope flag
7516 ;; as dynamic scope is already a parent of their scope.
7517 ;; 2. Functions defined under the with statement also immune to
7518 ;; this setup, in which case dynamic scope is ignored in favor
7519 ;; of the with object.
7520 (setf (js2-function-node-ignore-dynamic fn-node) t))
7521 ;; dynamically bind all the per-function variables
7522 (let ((js2-current-script-or-fn fn-node)
7523 (js2-current-scope fn-node)
7524 (js2-nesting-of-with 0)
7525 (js2-end-flags 0)
7526 js2-label-set
7527 js2-loop-set
7528 js2-loop-and-switch-set)
7529 (js2-parse-function-params function-type fn-node pos)
7530 (when (eq function-type 'FUNCTION_ARROW)
7531 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7532 (if (and (>= js2-language-version 180)
7533 (/= (js2-peek-token) js2-LC))
7534 (js2-parse-function-closure-body fn-node)
7535 (js2-parse-function-body fn-node))
7536 (js2-check-inconsistent-return-warning fn-node name)
7537
7538 (when name
7539 (js2-node-add-children fn-node name)
7540 ;; Function expressions define a name only in the body of the
7541 ;; function, and only if not hidden by a parameter name
7542 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7543 (null (js2-scope-get-symbol js2-current-scope
7544 (js2-name-node-name name))))
7545 (js2-define-symbol js2-FUNCTION
7546 (js2-name-node-name name)
7547 fn-node))
7548 (when (eq function-type 'FUNCTION_STATEMENT)
7549 (js2-record-imenu-functions fn-node))))
7550
7551 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7552 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7553 ;; We wait until after parsing the function to set its parent scope,
7554 ;; since `js2-define-symbol' needs the defining-scope check to stop
7555 ;; at the function boundary when checking for redeclarations.
7556 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7557 fn-node))
7558
7559 (defun js2-parse-statements (&optional parent)
7560 "Parse a statement list. Last token consumed must be js2-LC.
7561
7562 PARENT can be a `js2-block-node', in which case the statements are
7563 appended to PARENT. Otherwise a new `js2-block-node' is created
7564 and returned.
7565
7566 This function does not match the closing js2-RC: the caller
7567 matches the RC so it can provide a suitable error message if not
7568 matched. This means it's up to the caller to set the length of
7569 the node to include the closing RC. The node start pos is set to
7570 the absolute buffer start position, and the caller should fix it
7571 up to be relative to the parent node. All children of this block
7572 node are given relative start positions and correct lengths."
7573 (let ((pn (or parent (make-js2-block-node)))
7574 tt)
7575 (setf (js2-node-pos pn) (js2-current-token-beg))
7576 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7577 (/= tt js2-RC))
7578 (js2-block-node-push pn (js2-parse-statement)))
7579 pn))
7580
7581 (defun js2-parse-statement ()
7582 (let (pn beg end)
7583 ;; coarse-grained user-interrupt check - needs work
7584 (and js2-parse-interruptable-p
7585 (zerop (% (incf js2-parse-stmt-count)
7586 js2-statements-per-pause))
7587 (input-pending-p)
7588 (throw 'interrupted t))
7589 (setq pn (js2-statement-helper))
7590 ;; no-side-effects warning check
7591 (unless (js2-node-has-side-effects pn)
7592 (setq end (js2-node-end pn))
7593 (save-excursion
7594 (goto-char end)
7595 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7596 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7597 pn))
7598
7599 ;; These correspond to the switch cases in Parser.statementHelper
7600 (defconst js2-parsers
7601 (let ((parsers (make-vector js2-num-tokens
7602 #'js2-parse-expr-stmt)))
7603 (aset parsers js2-BREAK #'js2-parse-break)
7604 (aset parsers js2-CONST #'js2-parse-const-var)
7605 (aset parsers js2-CONTINUE #'js2-parse-continue)
7606 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7607 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7608 (aset parsers js2-DO #'js2-parse-do)
7609 (aset parsers js2-FOR #'js2-parse-for)
7610 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
7611 (aset parsers js2-IF #'js2-parse-if)
7612 (aset parsers js2-LC #'js2-parse-block)
7613 (aset parsers js2-LET #'js2-parse-let-stmt)
7614 (aset parsers js2-NAME #'js2-parse-name-or-label)
7615 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7616 (aset parsers js2-SEMI #'js2-parse-semi)
7617 (aset parsers js2-SWITCH #'js2-parse-switch)
7618 (aset parsers js2-THROW #'js2-parse-throw)
7619 (aset parsers js2-TRY #'js2-parse-try)
7620 (aset parsers js2-VAR #'js2-parse-const-var)
7621 (aset parsers js2-WHILE #'js2-parse-while)
7622 (aset parsers js2-WITH #'js2-parse-with)
7623 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7624 parsers)
7625 "A vector mapping token types to parser functions.")
7626
7627 (defun js2-parse-warn-missing-semi (beg end)
7628 (and js2-mode-show-strict-warnings
7629 js2-strict-missing-semi-warning
7630 (js2-add-strict-warning
7631 "msg.missing.semi" nil
7632 ;; back up to beginning of statement or line
7633 (max beg (save-excursion
7634 (goto-char end)
7635 (point-at-bol)))
7636 end)))
7637
7638 (defconst js2-no-semi-insertion
7639 (list js2-IF
7640 js2-SWITCH
7641 js2-WHILE
7642 js2-DO
7643 js2-FOR
7644 js2-TRY
7645 js2-WITH
7646 js2-LC
7647 js2-ERROR
7648 js2-SEMI
7649 js2-FUNCTION)
7650 "List of tokens that don't do automatic semicolon insertion.")
7651
7652 (defconst js2-autoinsert-semi-and-warn
7653 (list js2-ERROR js2-EOF js2-RC))
7654
7655 (defun js2-statement-helper ()
7656 (let* ((tt (js2-get-token))
7657 (first-tt tt)
7658 (parser (if (= tt js2-ERROR)
7659 #'js2-parse-semi
7660 (aref js2-parsers tt)))
7661 pn)
7662 ;; If the statement is set, then it's been told its label by now.
7663 (and js2-labeled-stmt
7664 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7665 (setq js2-labeled-stmt nil))
7666 (setq pn (funcall parser))
7667 ;; Don't do auto semi insertion for certain statement types.
7668 (unless (or (memq first-tt js2-no-semi-insertion)
7669 (js2-labeled-stmt-node-p pn))
7670 (js2-auto-insert-semicolon pn))
7671 pn))
7672
7673 (defun js2-auto-insert-semicolon (pn)
7674 (let* ((tt (js2-get-token))
7675 (pos (js2-node-pos pn)))
7676 (cond
7677 ((= tt js2-SEMI)
7678 ;; extend the node bounds to include the semicolon.
7679 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
7680 ((memq tt js2-autoinsert-semi-and-warn)
7681 (js2-unget-token) ; Not ';', do not consume.
7682 ;; Autoinsert ;
7683 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7684 (t
7685 (if (not (js2-token-follows-eol-p (js2-current-token)))
7686 ;; Report error if no EOL or autoinsert ';' otherwise
7687 (js2-report-error "msg.no.semi.stmt")
7688 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7689 (js2-unget-token) ; Not ';', do not consume.
7690 ))))
7691
7692 (defun js2-parse-condition ()
7693 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7694 The parens are discarded and the expression node is returned.
7695 The `pos' field of the return value is set to an absolute position
7696 that must be fixed up by the caller.
7697 Return value is a list (EXPR LP RP), with absolute paren positions."
7698 (let (pn lp rp)
7699 (if (js2-must-match js2-LP "msg.no.paren.cond")
7700 (setq lp (js2-current-token-beg)))
7701 (setq pn (js2-parse-expr))
7702 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7703 (setq rp (js2-current-token-beg)))
7704 ;; Report strict warning on code like "if (a = 7) ..."
7705 (if (and js2-strict-cond-assign-warning
7706 (js2-assign-node-p pn))
7707 (js2-add-strict-warning "msg.equal.as.assign" nil
7708 (js2-node-pos pn)
7709 (+ (js2-node-pos pn)
7710 (js2-node-len pn))))
7711 (list pn lp rp)))
7712
7713 (defun js2-parse-if ()
7714 "Parser for if-statement. Last matched token must be js2-IF."
7715 (let ((pos (js2-current-token-beg))
7716 cond if-true if-false else-pos end pn)
7717 (setq cond (js2-parse-condition)
7718 if-true (js2-parse-statement)
7719 if-false (if (js2-match-token js2-ELSE)
7720 (progn
7721 (setq else-pos (- (js2-current-token-beg) pos))
7722 (js2-parse-statement)))
7723 end (js2-node-end (or if-false if-true))
7724 pn (make-js2-if-node :pos pos
7725 :len (- end pos)
7726 :condition (car cond)
7727 :then-part if-true
7728 :else-part if-false
7729 :else-pos else-pos
7730 :lp (js2-relpos (second cond) pos)
7731 :rp (js2-relpos (third cond) pos)))
7732 (js2-node-add-children pn (car cond) if-true if-false)
7733 pn))
7734
7735 (defun js2-parse-switch ()
7736 "Parser for switch-statement. Last matched token must be js2-SWITCH."
7737 (let ((pos (js2-current-token-beg))
7738 tt pn discriminant has-default case-expr case-node
7739 case-pos cases stmt lp)
7740 (if (js2-must-match js2-LP "msg.no.paren.switch")
7741 (setq lp (js2-current-token-beg)))
7742 (setq discriminant (js2-parse-expr)
7743 pn (make-js2-switch-node :discriminant discriminant
7744 :pos pos
7745 :lp (js2-relpos lp pos)))
7746 (js2-node-add-children pn discriminant)
7747 (js2-enter-switch pn)
7748 (unwind-protect
7749 (progn
7750 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7751 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
7752 (js2-must-match js2-LC "msg.no.brace.switch")
7753 (catch 'break
7754 (while t
7755 (setq tt (js2-next-token)
7756 case-pos (js2-current-token-beg))
7757 (cond
7758 ((= tt js2-RC)
7759 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
7760 (throw 'break nil)) ; done
7761 ((= tt js2-CASE)
7762 (setq case-expr (js2-parse-expr))
7763 (js2-must-match js2-COLON "msg.no.colon.case"))
7764 ((= tt js2-DEFAULT)
7765 (if has-default
7766 (js2-report-error "msg.double.switch.default"))
7767 (setq has-default t
7768 case-expr nil)
7769 (js2-must-match js2-COLON "msg.no.colon.case"))
7770 (t
7771 (js2-report-error "msg.bad.switch")
7772 (throw 'break nil)))
7773 (setq case-node (make-js2-case-node :pos case-pos
7774 :len (- (js2-current-token-end) case-pos)
7775 :expr case-expr))
7776 (js2-node-add-children case-node case-expr)
7777 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7778 (/= tt js2-CASE)
7779 (/= tt js2-DEFAULT)
7780 (/= tt js2-EOF))
7781 (setf stmt (js2-parse-statement)
7782 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7783 (js2-block-node-push case-node stmt))
7784 (push case-node cases)))
7785 ;; add cases last, as pushing reverses the order to be correct
7786 (dolist (kid cases)
7787 (js2-node-add-children pn kid)
7788 (push kid (js2-switch-node-cases pn)))
7789 pn) ; return value
7790 (js2-exit-switch))))
7791
7792 (defun js2-parse-while ()
7793 "Parser for while-statement. Last matched token must be js2-WHILE."
7794 (let ((pos (js2-current-token-beg))
7795 (pn (make-js2-while-node))
7796 cond body)
7797 (js2-enter-loop pn)
7798 (unwind-protect
7799 (progn
7800 (setf cond (js2-parse-condition)
7801 (js2-while-node-condition pn) (car cond)
7802 body (js2-parse-statement)
7803 (js2-while-node-body pn) body
7804 (js2-node-len pn) (- (js2-node-end body) pos)
7805 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7806 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7807 (js2-node-add-children pn body (car cond)))
7808 (js2-exit-loop))
7809 pn))
7810
7811 (defun js2-parse-do ()
7812 "Parser for do-statement. Last matched token must be js2-DO."
7813 (let ((pos (js2-current-token-beg))
7814 (pn (make-js2-do-node))
7815 cond body end)
7816 (js2-enter-loop pn)
7817 (unwind-protect
7818 (progn
7819 (setq body (js2-parse-statement))
7820 (js2-must-match js2-WHILE "msg.no.while.do")
7821 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
7822 cond (js2-parse-condition)
7823 (js2-do-node-condition pn) (car cond)
7824 (js2-do-node-body pn) body
7825 end js2-ts-cursor
7826 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7827 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7828 (js2-node-add-children pn (car cond) body))
7829 (js2-exit-loop))
7830 ;; Always auto-insert semicolon to follow SpiderMonkey:
7831 ;; It is required by ECMAScript but is ignored by the rest of
7832 ;; world; see bug 238945
7833 (if (js2-match-token js2-SEMI)
7834 (setq end js2-ts-cursor))
7835 (setf (js2-node-len pn) (- end pos))
7836 pn))
7837
7838 (defun js2-parse-for ()
7839 "Parser for for-statement. Last matched token must be js2-FOR.
7840 Parses for, for-in, and for each-in statements."
7841 (let ((for-pos (js2-current-token-beg))
7842 pn is-for-each is-for-in-or-of is-for-of
7843 in-pos each-pos tmp-pos
7844 init ; Node init is also foo in 'foo in object'
7845 cond ; Node cond is also object in 'foo in object'
7846 incr ; 3rd section of for-loop initializer
7847 body tt lp rp)
7848 ;; See if this is a for each () instead of just a for ()
7849 (when (js2-match-token js2-NAME)
7850 (if (string= "each" (js2-current-token-string))
7851 (progn
7852 (setq is-for-each t
7853 each-pos (- (js2-current-token-beg) for-pos)) ; relative
7854 (js2-record-face 'font-lock-keyword-face))
7855 (js2-report-error "msg.no.paren.for")))
7856 (if (js2-must-match js2-LP "msg.no.paren.for")
7857 (setq lp (- (js2-current-token-beg) for-pos)))
7858 (setq tt (js2-get-token))
7859 ;; 'for' makes local scope
7860 (js2-push-scope (make-js2-scope))
7861 (unwind-protect
7862 ;; parse init clause
7863 (let ((js2-in-for-init t)) ; set as dynamic variable
7864 (cond
7865 ((= tt js2-SEMI)
7866 (js2-unget-token)
7867 (setq init (make-js2-empty-expr-node)))
7868 ((or (= tt js2-VAR) (= tt js2-LET))
7869 (setq init (js2-parse-variables tt (js2-current-token-beg))))
7870 (t
7871 (js2-unget-token)
7872 (setq init (js2-parse-expr)))))
7873 (if (or (js2-match-token js2-IN)
7874 (and (>= js2-language-version 200)
7875 (js2-match-contextual-kwd "of")
7876 (setq is-for-of t)))
7877 (setq is-for-in-or-of t
7878 in-pos (- (js2-current-token-beg) for-pos)
7879 ;; scope of iteration target object is not the scope we've created above.
7880 ;; stash current scope temporary.
7881 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7882 (js2-parse-expr))) ; object over which we're iterating
7883 ;; else ordinary for loop - parse cond and incr
7884 (js2-must-match js2-SEMI "msg.no.semi.for")
7885 (setq cond (if (= (js2-peek-token) js2-SEMI)
7886 (make-js2-empty-expr-node) ; no loop condition
7887 (js2-parse-expr)))
7888 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7889 (setq tmp-pos (js2-current-token-end)
7890 incr (if (= (js2-peek-token) js2-RP)
7891 (make-js2-empty-expr-node :pos tmp-pos)
7892 (js2-parse-expr))))
7893 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7894 (setq rp (- (js2-current-token-beg) for-pos)))
7895 (if (not is-for-in-or-of)
7896 (setq pn (make-js2-for-node :init init
7897 :condition cond
7898 :update incr
7899 :lp lp
7900 :rp rp))
7901 ;; cond could be null if 'in obj' got eaten by the init node.
7902 (if (js2-infix-node-p init)
7903 ;; it was (foo in bar) instead of (var foo in bar)
7904 (setq cond (js2-infix-node-right init)
7905 init (js2-infix-node-left init))
7906 (if (and (js2-var-decl-node-p init)
7907 (> (length (js2-var-decl-node-kids init)) 1))
7908 (js2-report-error "msg.mult.index")))
7909 (setq pn (make-js2-for-in-node :iterator init
7910 :object cond
7911 :in-pos in-pos
7912 :foreach-p is-for-each
7913 :each-pos each-pos
7914 :forof-p is-for-of
7915 :lp lp
7916 :rp rp)))
7917 (unwind-protect
7918 (progn
7919 (js2-enter-loop pn)
7920 ;; We have to parse the body -after- creating the loop node,
7921 ;; so that the loop node appears in the js2-loop-set, allowing
7922 ;; break/continue statements to find the enclosing loop.
7923 (setf body (js2-parse-statement)
7924 (js2-loop-node-body pn) body
7925 (js2-node-pos pn) for-pos
7926 (js2-node-len pn) (- (js2-node-end body) for-pos))
7927 (js2-node-add-children pn init cond incr body))
7928 ;; finally
7929 (js2-exit-loop))
7930 (js2-pop-scope))
7931 pn))
7932
7933 (defun js2-parse-try ()
7934 "Parser for try-statement. Last matched token must be js2-TRY."
7935 (let ((try-pos (js2-current-token-beg))
7936 try-end
7937 try-block
7938 catch-blocks
7939 finally-block
7940 saw-default-catch
7941 peek
7942 param
7943 catch-cond
7944 catch-node
7945 guard-kwd
7946 catch-pos
7947 finally-pos
7948 pn
7949 block
7950 lp
7951 rp)
7952 (if (/= (js2-peek-token) js2-LC)
7953 (js2-report-error "msg.no.brace.try"))
7954 (setq try-block (js2-parse-statement)
7955 try-end (js2-node-end try-block)
7956 peek (js2-peek-token))
7957 (cond
7958 ((= peek js2-CATCH)
7959 (while (js2-match-token js2-CATCH)
7960 (setq catch-pos (js2-current-token-beg)
7961 guard-kwd nil
7962 catch-cond nil
7963 lp nil
7964 rp nil)
7965 (if saw-default-catch
7966 (js2-report-error "msg.catch.unreachable"))
7967 (if (js2-must-match js2-LP "msg.no.paren.catch")
7968 (setq lp (- (js2-current-token-beg) catch-pos)))
7969 (js2-push-scope (make-js2-scope))
7970 (let ((tt (js2-peek-token)))
7971 (cond
7972 ;; destructuring pattern
7973 ;; catch ({ message, file }) { ... }
7974 ((or (= tt js2-LB) (= tt js2-LC))
7975 (js2-get-token)
7976 (setq param (js2-parse-destruct-primary-expr))
7977 (js2-define-destruct-symbols param js2-LET nil))
7978 ;; simple name
7979 (t
7980 (js2-must-match-name "msg.bad.catchcond")
7981 (setq param (js2-create-name-node))
7982 (js2-define-symbol js2-LET (js2-current-token-string) param))))
7983 ;; pattern guard
7984 (if (js2-match-token js2-IF)
7985 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
7986 catch-cond (js2-parse-expr))
7987 (setq saw-default-catch t))
7988 (if (js2-must-match js2-RP "msg.bad.catchcond")
7989 (setq rp (- (js2-current-token-beg) catch-pos)))
7990 (js2-must-match js2-LC "msg.no.brace.catchblock")
7991 (setq block (js2-parse-statements)
7992 try-end (js2-node-end block)
7993 catch-node (make-js2-catch-node :pos catch-pos
7994 :param param
7995 :guard-expr catch-cond
7996 :guard-kwd guard-kwd
7997 :block block
7998 :lp lp
7999 :rp rp))
8000 (js2-pop-scope)
8001 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8002 (setq try-end (js2-current-token-beg)))
8003 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8004 (js2-node-len catch-node) (- try-end catch-pos))
8005 (js2-node-add-children catch-node param catch-cond block)
8006 (push catch-node catch-blocks)))
8007 ((/= peek js2-FINALLY)
8008 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8009 (js2-node-pos try-block)
8010 (- (setq try-end (js2-node-end try-block))
8011 (js2-node-pos try-block)))))
8012 (when (js2-match-token js2-FINALLY)
8013 (setq finally-pos (js2-current-token-beg)
8014 block (js2-parse-statement)
8015 try-end (js2-node-end block)
8016 finally-block (make-js2-finally-node :pos finally-pos
8017 :len (- try-end finally-pos)
8018 :body block))
8019 (js2-node-add-children finally-block block))
8020 (setq pn (make-js2-try-node :pos try-pos
8021 :len (- try-end try-pos)
8022 :try-block try-block
8023 :finally-block finally-block))
8024 (js2-node-add-children pn try-block finally-block)
8025 ;; push them onto the try-node, which reverses and corrects their order
8026 (dolist (cb catch-blocks)
8027 (js2-node-add-children pn cb)
8028 (push cb (js2-try-node-catch-clauses pn)))
8029 pn))
8030
8031 (defun js2-parse-throw ()
8032 "Parser for throw-statement. Last matched token must be js2-THROW."
8033 (let ((pos (js2-current-token-beg))
8034 expr pn)
8035 (if (= (js2-peek-token-or-eol) js2-EOL)
8036 ;; ECMAScript does not allow new lines before throw expression,
8037 ;; see bug 256617
8038 (js2-report-error "msg.bad.throw.eol"))
8039 (setq expr (js2-parse-expr)
8040 pn (make-js2-throw-node :pos pos
8041 :len (- (js2-node-end expr) pos)
8042 :expr expr))
8043 (js2-node-add-children pn expr)
8044 pn))
8045
8046 (defun js2-match-jump-label-name (label-name)
8047 "If break/continue specified a label, return that label's labeled stmt.
8048 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8049 does not match an existing label, reports an error and returns nil."
8050 (let ((bundle (cdr (assoc label-name js2-label-set))))
8051 (if (null bundle)
8052 (js2-report-error "msg.undef.label"))
8053 bundle))
8054
8055 (defun js2-parse-break ()
8056 "Parser for break-statement. Last matched token must be js2-BREAK."
8057 (let ((pos (js2-current-token-beg))
8058 (end (js2-current-token-end))
8059 break-target ; statement to break from
8060 break-label ; in "break foo", name-node representing the foo
8061 labels ; matching labeled statement to break to
8062 pn)
8063 (when (eq (js2-peek-token-or-eol) js2-NAME)
8064 (js2-get-token)
8065 (setq break-label (js2-create-name-node)
8066 end (js2-node-end break-label)
8067 ;; matchJumpLabelName only matches if there is one
8068 labels (js2-match-jump-label-name (js2-current-token-string))
8069 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8070 (unless (or break-target break-label)
8071 ;; no break target specified - try for innermost enclosing loop/switch
8072 (if (null js2-loop-and-switch-set)
8073 (unless break-label
8074 (js2-report-error "msg.bad.break" nil pos (length "break")))
8075 (setq break-target (car js2-loop-and-switch-set))))
8076 (setq pn (make-js2-break-node :pos pos
8077 :len (- end pos)
8078 :label break-label
8079 :target break-target))
8080 (js2-node-add-children pn break-label) ; but not break-target
8081 pn))
8082
8083 (defun js2-parse-continue ()
8084 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8085 (let ((pos (js2-current-token-beg))
8086 (end (js2-current-token-end))
8087 label ; optional user-specified label, a `js2-name-node'
8088 labels ; current matching labeled stmt, if any
8089 target ; the `js2-loop-node' target of this continue stmt
8090 pn)
8091 (when (= (js2-peek-token-or-eol) js2-NAME)
8092 (js2-get-token)
8093 (setq label (js2-create-name-node)
8094 end (js2-node-end label)
8095 ;; matchJumpLabelName only matches if there is one
8096 labels (js2-match-jump-label-name (js2-current-token-string))))
8097 (cond
8098 ((null labels) ; no current label to go to
8099 (if (null js2-loop-set) ; no loop to continue to
8100 (js2-report-error "msg.continue.outside" nil pos
8101 (length "continue"))
8102 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8103 (t
8104 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8105 (setq target (js2-labeled-stmt-node-stmt labels))
8106 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8107 (setq pn (make-js2-continue-node :pos pos
8108 :len (- end pos)
8109 :label label
8110 :target target))
8111 (js2-node-add-children pn label) ; but not target - it's not our child
8112 pn))
8113
8114 (defun js2-parse-with ()
8115 "Parser for with-statement. Last matched token must be js2-WITH."
8116 (let ((pos (js2-current-token-beg))
8117 obj body pn lp rp)
8118 (if (js2-must-match js2-LP "msg.no.paren.with")
8119 (setq lp (js2-current-token-beg)))
8120 (setq obj (js2-parse-expr))
8121 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8122 (setq rp (js2-current-token-beg)))
8123 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8124 (setq body (js2-parse-statement)))
8125 (setq pn (make-js2-with-node :pos pos
8126 :len (- (js2-node-end body) pos)
8127 :object obj
8128 :body body
8129 :lp (js2-relpos lp pos)
8130 :rp (js2-relpos rp pos)))
8131 (js2-node-add-children pn obj body)
8132 pn))
8133
8134 (defun js2-parse-const-var ()
8135 "Parser for var- or const-statement.
8136 Last matched token must be js2-CONST or js2-VAR."
8137 (let ((tt (js2-current-token-type))
8138 (pos (js2-current-token-beg))
8139 expr pn)
8140 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8141 pn (make-js2-expr-stmt-node :pos pos
8142 :len (- (js2-node-end expr) pos)
8143 :expr expr))
8144 (js2-node-add-children pn expr)
8145 pn))
8146
8147 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8148 (let ((pn (make-js2-expr-stmt-node :pos pos
8149 :len (js2-node-len expr)
8150 :type (if (js2-inside-function)
8151 js2-EXPR_VOID
8152 js2-EXPR_RESULT)
8153 :expr expr)))
8154 (if add-child
8155 (js2-node-add-children pn expr))
8156 pn))
8157
8158 (defun js2-parse-let-stmt ()
8159 "Parser for let-statement. Last matched token must be js2-LET."
8160 (let ((pos (js2-current-token-beg))
8161 expr pn)
8162 (if (= (js2-peek-token) js2-LP)
8163 ;; let expression in statement context
8164 (setq expr (js2-parse-let pos 'statement)
8165 pn (js2-wrap-with-expr-stmt pos expr t))
8166 ;; else we're looking at a statement like let x=6, y=7;
8167 (setf expr (js2-parse-variables js2-LET pos)
8168 pn (js2-wrap-with-expr-stmt pos expr t)
8169 (js2-node-type pn) js2-EXPR_RESULT))
8170 pn))
8171
8172 (defun js2-parse-ret-yield ()
8173 (js2-parse-return-or-yield (js2-current-token-type) nil))
8174
8175 (defconst js2-parse-return-stmt-enders
8176 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8177
8178 (defsubst js2-now-all-set (before after mask)
8179 "Return whether or not the bits in the mask have changed to all set.
8180 BEFORE is bits before change, AFTER is bits after change, and MASK is
8181 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8182 but not BEFORE."
8183 (and (/= (logand before mask) mask)
8184 (= (logand after mask) mask)))
8185
8186 (defun js2-parse-return-or-yield (tt expr-context)
8187 (let* ((pos (js2-current-token-beg))
8188 (end (js2-current-token-end))
8189 (before js2-end-flags)
8190 (inside-function (js2-inside-function))
8191 (gen-type (and inside-function (js2-function-node-generator-type
8192 js2-current-script-or-fn)))
8193 e ret name yield-star-p)
8194 (unless inside-function
8195 (js2-report-error (if (eq tt js2-RETURN)
8196 "msg.bad.return"
8197 "msg.bad.yield")))
8198 (when (and inside-function
8199 (eq gen-type 'STAR)
8200 (js2-match-token js2-MUL))
8201 (setq yield-star-p t))
8202 ;; This is ugly, but we don't want to require a semicolon.
8203 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8204 (setq e (js2-parse-expr)
8205 end (js2-node-end e)))
8206 (cond
8207 ((eq tt js2-RETURN)
8208 (js2-set-flag js2-end-flags (if (null e)
8209 js2-end-returns
8210 js2-end-returns-value))
8211 (setq ret (make-js2-return-node :pos pos
8212 :len (- end pos)
8213 :retval e))
8214 (js2-node-add-children ret e)
8215 ;; See if we need a strict mode warning.
8216 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8217 ;; more thorough and accurate than this before/after flag check.
8218 ;; E.g. if there's a finally-block that always returns, we shouldn't
8219 ;; show a warning generated by inconsistent returns in the catch blocks.
8220 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8221 ;; so we know which returns/yields to highlight, and we should get rid of
8222 ;; all the checking in `js2-parse-return-or-yield'.
8223 (if (and js2-strict-inconsistent-return-warning
8224 (js2-now-all-set before js2-end-flags
8225 (logior js2-end-returns js2-end-returns-value)))
8226 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8227 ((eq gen-type 'COMPREHENSION)
8228 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8229 ;; like SpiderMonkey does.
8230 (js2-report-error "msg.syntax" nil pos 5))
8231 (t
8232 (setq ret (make-js2-yield-node :pos pos
8233 :len (- end pos)
8234 :value e
8235 :star-p yield-star-p))
8236 (js2-node-add-children ret e)
8237 (unless expr-context
8238 (setq e ret
8239 ret (js2-wrap-with-expr-stmt pos e t))
8240 (js2-set-requires-activation)
8241 (js2-set-is-generator))))
8242 ;; see if we are mixing yields and value returns.
8243 (when (and inside-function
8244 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8245 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8246 'LEGACY))
8247 (setq name (js2-function-name js2-current-script-or-fn))
8248 (if (zerop (length name))
8249 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8250 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8251 ret))
8252
8253 (defun js2-parse-debugger ()
8254 (make-js2-keyword-node :type js2-DEBUGGER))
8255
8256 (defun js2-parse-block ()
8257 "Parser for a curly-delimited statement block.
8258 Last token matched must be `js2-LC'."
8259 (let ((pos (js2-current-token-beg))
8260 (pn (make-js2-scope)))
8261 (js2-push-scope pn)
8262 (unwind-protect
8263 (progn
8264 (js2-parse-statements pn)
8265 (js2-must-match js2-RC "msg.no.brace.block")
8266 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8267 (js2-pop-scope))
8268 pn))
8269
8270 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8271 (defun js2-parse-semi ()
8272 "Parse a statement or handle an error.
8273 Current token type is `js2-SEMI' or `js2-ERROR'."
8274 (let ((tt (js2-current-token-type)) pos len)
8275 (if (eq tt js2-SEMI)
8276 (make-js2-empty-expr-node :len 1)
8277 (setq pos (js2-current-token-beg)
8278 len (- (js2-current-token-end) pos))
8279 (js2-report-error "msg.syntax" nil pos len)
8280 (make-js2-error-node :pos pos :len len))))
8281
8282 (defun js2-parse-default-xml-namespace ()
8283 "Parse a `default xml namespace = <expr>' e4x statement."
8284 (let ((pos (js2-current-token-beg))
8285 end len expr unary)
8286 (js2-must-have-xml)
8287 (js2-set-requires-activation)
8288 (setq len (- js2-ts-cursor pos))
8289 (unless (and (js2-match-token js2-NAME)
8290 (string= (js2-current-token-string) "xml"))
8291 (js2-report-error "msg.bad.namespace" nil pos len))
8292 (unless (and (js2-match-token js2-NAME)
8293 (string= (js2-current-token-string) "namespace"))
8294 (js2-report-error "msg.bad.namespace" nil pos len))
8295 (unless (js2-match-token js2-ASSIGN)
8296 (js2-report-error "msg.bad.namespace" nil pos len))
8297 (setq expr (js2-parse-expr)
8298 end (js2-node-end expr)
8299 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8300 :pos pos
8301 :len (- end pos)
8302 :operand expr))
8303 (js2-node-add-children unary expr)
8304 (make-js2-expr-stmt-node :pos pos
8305 :len (- end pos)
8306 :expr unary)))
8307
8308 (defun js2-record-label (label bundle)
8309 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8310 (js2-get-token)
8311 (let ((name (js2-label-node-name label))
8312 labeled-stmt
8313 dup)
8314 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8315 ;; flag both labels if possible when used in editing mode
8316 (if (and js2-parse-ide-mode
8317 (setq dup (js2-get-label-by-name labeled-stmt name)))
8318 (js2-report-error "msg.dup.label" nil
8319 (js2-node-abs-pos dup) (js2-node-len dup)))
8320 (js2-report-error "msg.dup.label" nil
8321 (js2-node-pos label) (js2-node-len label)))
8322 (js2-labeled-stmt-node-add-label bundle label)
8323 (js2-node-add-children bundle label)
8324 ;; Add one reference to the bundle per label in `js2-label-set'
8325 (push (cons name bundle) js2-label-set)))
8326
8327 (defun js2-parse-name-or-label ()
8328 "Parser for identifier or label. Last token matched must be js2-NAME.
8329 Called when we found a name in a statement context. If it's a label, we gather
8330 up any following labels and the next non-label statement into a
8331 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8332 expression and return it wrapped in a `js2-expr-stmt-node'."
8333 (let ((pos (js2-current-token-beg))
8334 expr stmt bundle
8335 (continue t))
8336 ;; set check for label and call down to `js2-parse-primary-expr'
8337 (setq expr (js2-maybe-parse-label))
8338 (if (null expr)
8339 ;; Parse the non-label expression and wrap with expression stmt.
8340 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
8341 ;; else parsed a label
8342 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8343 (js2-record-label expr bundle)
8344 ;; look for more labels
8345 (while (and continue (= (js2-get-token) js2-NAME))
8346 (if (setq expr (js2-maybe-parse-label))
8347 (js2-record-label expr bundle)
8348 (setq expr (js2-parse-expr)
8349 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8350 continue nil)
8351 (js2-auto-insert-semicolon stmt)))
8352 ;; no more labels; now parse the labeled statement
8353 (unwind-protect
8354 (unless stmt
8355 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8356 (js2-unget-token)
8357 (setq stmt (js2-statement-helper))))
8358 ;; remove the labels for this statement from the global set
8359 (dolist (label (js2-labeled-stmt-node-labels bundle))
8360 (setq js2-label-set (remove label js2-label-set))))
8361 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8362 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8363 (js2-node-add-children bundle stmt)
8364 bundle)))
8365
8366 (defun js2-maybe-parse-label ()
8367 (assert (= (js2-current-token-type) js2-NAME))
8368 (let (label-pos
8369 (next-tt (js2-get-token))
8370 (label-end (js2-current-token-end)))
8371 ;; Do not consume colon, it is used as unwind indicator
8372 ;; to return to statementHelper.
8373 (js2-unget-token)
8374 (if (= next-tt js2-COLON)
8375 (prog2
8376 (setq label-pos (js2-current-token-beg))
8377 (make-js2-label-node :pos label-pos
8378 :len (- label-end label-pos)
8379 :name (js2-current-token-string))
8380 (js2-set-face label-pos
8381 label-end
8382 'font-lock-variable-name-face 'record))
8383 ;; Backtrack from the name token, too.
8384 (js2-unget-token)
8385 nil)))
8386
8387 (defun js2-parse-expr-stmt ()
8388 "Default parser in statement context, if no recognized statement found."
8389 (js2-wrap-with-expr-stmt (js2-current-token-beg)
8390 (progn
8391 (js2-unget-token)
8392 (js2-parse-expr)) t))
8393
8394 (defun js2-parse-variables (decl-type pos)
8395 "Parse a comma-separated list of variable declarations.
8396 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8397
8398 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8399 For 'var' or 'const', the keyword should be the token last scanned.
8400
8401 POS is the position where the node should start. It's sometimes the
8402 var/const/let keyword, and other times the beginning of the first token
8403 in the first variable declaration.
8404
8405 Returns the parsed `js2-var-decl-node' expression node."
8406 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8407 :pos pos))
8408 destructuring kid-pos tt init name end nbeg nend vi
8409 (continue t))
8410 ;; Example:
8411 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8412 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8413 ;; var {a, b} = baz;
8414 (while continue
8415 (setq destructuring nil
8416 name nil
8417 tt (js2-get-token)
8418 kid-pos (js2-current-token-beg)
8419 end (js2-current-token-end)
8420 init nil)
8421 (if (or (= tt js2-LB) (= tt js2-LC))
8422 ;; Destructuring assignment, e.g., var [a, b] = ...
8423 (setq destructuring (js2-parse-destruct-primary-expr)
8424 end (js2-node-end destructuring))
8425 ;; Simple variable name
8426 (js2-unget-token)
8427 (when (js2-must-match-name "msg.bad.var")
8428 (setq name (js2-create-name-node)
8429 nbeg (js2-current-token-beg)
8430 nend (js2-current-token-end)
8431 end nend)
8432 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
8433 (when (js2-match-token js2-ASSIGN)
8434 (setq init (js2-parse-assign-expr)
8435 end (js2-node-end init))
8436 (js2-record-imenu-functions init name))
8437 (when name
8438 (js2-set-face nbeg nend (if (js2-function-node-p init)
8439 'font-lock-function-name-face
8440 'font-lock-variable-name-face)
8441 'record))
8442 (setq vi (make-js2-var-init-node :pos kid-pos
8443 :len (- end kid-pos)
8444 :type decl-type))
8445 (if destructuring
8446 (progn
8447 (if (and (null init) (not js2-in-for-init))
8448 (js2-report-error "msg.destruct.assign.no.init"))
8449 (js2-define-destruct-symbols destructuring
8450 decl-type
8451 'font-lock-variable-name-face)
8452 (setf (js2-var-init-node-target vi) destructuring))
8453 (setf (js2-var-init-node-target vi) name))
8454 (setf (js2-var-init-node-initializer vi) init)
8455 (js2-node-add-children vi name destructuring init)
8456 (js2-block-node-push result vi)
8457 (unless (js2-match-token js2-COMMA)
8458 (setq continue nil)))
8459 (setf (js2-node-len result) (- end pos))
8460 result))
8461
8462 (defun js2-parse-let (pos &optional stmt-p)
8463 "Parse a let expression or statement.
8464 A let-expression is of the form `let (vars) expr'.
8465 A let-statment is of the form `let (vars) {statements}'.
8466 The third form of let is a variable declaration list, handled
8467 by `js2-parse-variables'."
8468 (let ((pn (make-js2-let-node :pos pos))
8469 beg vars body)
8470 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8471 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
8472 (js2-push-scope pn)
8473 (unwind-protect
8474 (progn
8475 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
8476 (if (js2-must-match js2-RP "msg.no.paren.let")
8477 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
8478 (if (and stmt-p (js2-match-token js2-LC))
8479 ;; let statement
8480 (progn
8481 (setf beg (js2-current-token-beg) ; position stmt at LC
8482 body (js2-parse-statements))
8483 (js2-must-match js2-RC "msg.no.curly.let")
8484 (setf (js2-node-len body) (- (js2-current-token-end) beg)
8485 (js2-node-len pn) (- (js2-current-token-end) pos)
8486 (js2-let-node-body pn) body
8487 (js2-node-type pn) js2-LET))
8488 ;; let expression
8489 (setf body (js2-parse-expr)
8490 (js2-node-len pn) (- (js2-node-end body) pos)
8491 (js2-let-node-body pn) body))
8492 (setf (js2-let-node-vars pn) vars)
8493 (js2-node-add-children pn vars body))
8494 (js2-pop-scope))
8495 pn))
8496
8497 (defun js2-define-new-symbol (decl-type name node &optional scope)
8498 (js2-scope-put-symbol (or scope js2-current-scope)
8499 name
8500 (make-js2-symbol decl-type name node)))
8501
8502 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8503 "Define a symbol in the current scope.
8504 If NODE is non-nil, it is the AST node associated with the symbol."
8505 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8506 (symbol (if defining-scope
8507 (js2-scope-get-symbol defining-scope name)))
8508 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8509 (cond
8510 ((and symbol ; already defined
8511 (or (= sdt js2-CONST) ; old version is const
8512 (= decl-type js2-CONST) ; new version is const
8513 ;; two let-bound vars in this block have same name
8514 (and (= sdt js2-LET)
8515 (eq defining-scope js2-current-scope))))
8516 (js2-report-error
8517 (cond
8518 ((= sdt js2-CONST) "msg.const.redecl")
8519 ((= sdt js2-LET) "msg.let.redecl")
8520 ((= sdt js2-VAR) "msg.var.redecl")
8521 ((= sdt js2-FUNCTION) "msg.function.redecl")
8522 (t "msg.parm.redecl"))
8523 name))
8524 ((= decl-type js2-LET)
8525 (if (and (not ignore-not-in-block)
8526 (or (= (js2-node-type js2-current-scope) js2-IF)
8527 (js2-loop-node-p js2-current-scope)))
8528 (js2-report-error "msg.let.decl.not.in.block")
8529 (js2-define-new-symbol decl-type name node)))
8530 ((or (= decl-type js2-VAR)
8531 (= decl-type js2-CONST)
8532 (= decl-type js2-FUNCTION))
8533 (if symbol
8534 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8535 (js2-add-strict-warning "msg.var.redecl" name)
8536 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8537 (js2-add-strict-warning "msg.var.hides.arg" name)))
8538 (js2-define-new-symbol decl-type name node
8539 js2-current-script-or-fn)))
8540 ((= decl-type js2-LP)
8541 (if symbol
8542 ;; must be duplicate parameter. Second parameter hides the
8543 ;; first, so go ahead and add the second pararameter
8544 (js2-report-warning "msg.dup.parms" name))
8545 (js2-define-new-symbol decl-type name node))
8546 (t (js2-code-bug)))))
8547
8548 (defun js2-parse-paren-expr-or-generator-comp ()
8549 (let ((px-pos (js2-current-token-beg)))
8550 (if (and (>= js2-language-version 200)
8551 (js2-match-token js2-FOR))
8552 (js2-parse-generator-comp px-pos)
8553 (let* ((js2-in-for-init nil)
8554 (expr (js2-parse-expr))
8555 (pn (make-js2-paren-node :pos px-pos
8556 :expr expr
8557 :len (- (js2-current-token-end)
8558 px-pos))))
8559 (js2-node-add-children pn (js2-paren-node-expr pn))
8560 (js2-must-match js2-RP "msg.no.paren")
8561 pn))))
8562
8563 (defun js2-parse-expr (&optional oneshot)
8564 (let* ((pn (js2-parse-assign-expr))
8565 (pos (js2-node-pos pn))
8566 left
8567 right
8568 op-pos)
8569 (while (and (not oneshot)
8570 (js2-match-token js2-COMMA))
8571 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
8572 (if (= (js2-peek-token) js2-YIELD)
8573 (js2-report-error "msg.yield.parenthesized"))
8574 (setq right (js2-parse-assign-expr)
8575 left pn
8576 pn (make-js2-infix-node :type js2-COMMA
8577 :pos pos
8578 :len (- js2-ts-cursor pos)
8579 :op-pos op-pos
8580 :left left
8581 :right right))
8582 (js2-node-add-children pn left right))
8583 pn))
8584
8585 (defun js2-parse-assign-expr ()
8586 (let ((tt (js2-get-token))
8587 (pos (js2-current-token-beg))
8588 pn left right op-pos
8589 ts-state recorded-identifiers parsed-errors)
8590 (if (= tt js2-YIELD)
8591 (js2-parse-return-or-yield tt t)
8592 ;; Save the tokenizer state in case we find an arrow function
8593 ;; and have to rewind.
8594 (setq ts-state (make-js2-ts-state)
8595 recorded-identifiers js2-recorded-identifiers
8596 parsed-errors js2-parsed-errors)
8597 ;; not yield - parse assignment expression
8598 (setq pn (js2-parse-cond-expr)
8599 tt (js2-get-token))
8600 (cond
8601 ((and (<= js2-first-assign tt)
8602 (<= tt js2-last-assign))
8603 ;; tt express assignment (=, |=, ^=, ..., %=)
8604 (setq op-pos (- (js2-current-token-beg) pos) ; relative
8605 left pn)
8606 (setq right (js2-parse-assign-expr)
8607 pn (make-js2-assign-node :type tt
8608 :pos pos
8609 :len (- (js2-node-end right) pos)
8610 :op-pos op-pos
8611 :left left
8612 :right right))
8613 (when js2-parse-ide-mode
8614 (js2-highlight-assign-targets pn left right)
8615 (js2-record-imenu-functions right left))
8616 ;; do this last so ide checks above can use absolute positions
8617 (js2-node-add-children pn left right))
8618 ((and (= tt js2-ARROW)
8619 (>= js2-language-version 200))
8620 (js2-ts-seek ts-state)
8621 (setq js2-recorded-identifiers recorded-identifiers
8622 js2-parsed-errors parsed-errors)
8623 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
8624 (t
8625 (js2-unget-token)))
8626 pn)))
8627
8628 (defun js2-parse-cond-expr ()
8629 (let ((pos (js2-current-token-beg))
8630 (pn (js2-parse-or-expr))
8631 test-expr
8632 if-true
8633 if-false
8634 q-pos
8635 c-pos)
8636 (when (js2-match-token js2-HOOK)
8637 (setq q-pos (- (js2-current-token-beg) pos)
8638 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
8639 (js2-must-match js2-COLON "msg.no.colon.cond")
8640 (setq c-pos (- (js2-current-token-beg) pos)
8641 if-false (js2-parse-assign-expr)
8642 test-expr pn
8643 pn (make-js2-cond-node :pos pos
8644 :len (- (js2-node-end if-false) pos)
8645 :test-expr test-expr
8646 :true-expr if-true
8647 :false-expr if-false
8648 :q-pos q-pos
8649 :c-pos c-pos))
8650 (js2-node-add-children pn test-expr if-true if-false))
8651 pn))
8652
8653 (defun js2-make-binary (type left parser)
8654 "Helper for constructing a binary-operator AST node.
8655 LEFT is the left-side-expression, already parsed, and the
8656 binary operator should have just been matched.
8657 PARSER is a function to call to parse the right operand,
8658 or a `js2-node' struct if it has already been parsed.
8659 FIXME: The latter option is unused?"
8660 (let* ((pos (js2-node-pos left))
8661 (op-pos (- (js2-current-token-beg) pos))
8662 (right (if (js2-node-p parser)
8663 parser
8664 (js2-get-token)
8665 (funcall parser)))
8666 (pn (make-js2-infix-node :type type
8667 :pos pos
8668 :len (- (js2-node-end right) pos)
8669 :op-pos op-pos
8670 :left left
8671 :right right)))
8672 (js2-node-add-children pn left right)
8673 pn))
8674
8675 (defun js2-parse-or-expr ()
8676 (let ((pn (js2-parse-and-expr)))
8677 (when (js2-match-token js2-OR)
8678 (setq pn (js2-make-binary js2-OR
8679 pn
8680 'js2-parse-or-expr)))
8681 pn))
8682
8683 (defun js2-parse-and-expr ()
8684 (let ((pn (js2-parse-bit-or-expr)))
8685 (when (js2-match-token js2-AND)
8686 (setq pn (js2-make-binary js2-AND
8687 pn
8688 'js2-parse-and-expr)))
8689 pn))
8690
8691 (defun js2-parse-bit-or-expr ()
8692 (let ((pn (js2-parse-bit-xor-expr)))
8693 (while (js2-match-token js2-BITOR)
8694 (setq pn (js2-make-binary js2-BITOR
8695 pn
8696 'js2-parse-bit-xor-expr)))
8697 pn))
8698
8699 (defun js2-parse-bit-xor-expr ()
8700 (let ((pn (js2-parse-bit-and-expr)))
8701 (while (js2-match-token js2-BITXOR)
8702 (setq pn (js2-make-binary js2-BITXOR
8703 pn
8704 'js2-parse-bit-and-expr)))
8705 pn))
8706
8707 (defun js2-parse-bit-and-expr ()
8708 (let ((pn (js2-parse-eq-expr)))
8709 (while (js2-match-token js2-BITAND)
8710 (setq pn (js2-make-binary js2-BITAND
8711 pn
8712 'js2-parse-eq-expr)))
8713 pn))
8714
8715 (defconst js2-parse-eq-ops
8716 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8717
8718 (defun js2-parse-eq-expr ()
8719 (let ((pn (js2-parse-rel-expr))
8720 tt)
8721 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
8722 (setq pn (js2-make-binary tt
8723 pn
8724 'js2-parse-rel-expr)))
8725 (js2-unget-token)
8726 pn))
8727
8728 (defconst js2-parse-rel-ops
8729 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8730
8731 (defun js2-parse-rel-expr ()
8732 (let ((pn (js2-parse-shift-expr))
8733 (continue t)
8734 tt)
8735 (while continue
8736 (setq tt (js2-get-token))
8737 (cond
8738 ((and js2-in-for-init (= tt js2-IN))
8739 (js2-unget-token)
8740 (setq continue nil))
8741 ((memq tt js2-parse-rel-ops)
8742 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8743 (t
8744 (js2-unget-token)
8745 (setq continue nil))))
8746 pn))
8747
8748 (defconst js2-parse-shift-ops
8749 (list js2-LSH js2-URSH js2-RSH))
8750
8751 (defun js2-parse-shift-expr ()
8752 (let ((pn (js2-parse-add-expr))
8753 tt
8754 (continue t))
8755 (while continue
8756 (setq tt (js2-get-token))
8757 (if (memq tt js2-parse-shift-ops)
8758 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
8759 (js2-unget-token)
8760 (setq continue nil)))
8761 pn))
8762
8763 (defun js2-parse-add-expr ()
8764 (let ((pn (js2-parse-mul-expr))
8765 tt
8766 (continue t))
8767 (while continue
8768 (setq tt (js2-get-token))
8769 (if (or (= tt js2-ADD) (= tt js2-SUB))
8770 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
8771 (js2-unget-token)
8772 (setq continue nil)))
8773 pn))
8774
8775 (defconst js2-parse-mul-ops
8776 (list js2-MUL js2-DIV js2-MOD))
8777
8778 (defun js2-parse-mul-expr ()
8779 (let ((pn (js2-parse-unary-expr))
8780 tt
8781 (continue t))
8782 (while continue
8783 (setq tt (js2-get-token))
8784 (if (memq tt js2-parse-mul-ops)
8785 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
8786 (js2-unget-token)
8787 (setq continue nil)))
8788 pn))
8789
8790 (defun js2-make-unary (type parser &rest args)
8791 "Make a unary node of type TYPE.
8792 PARSER is either a node (for postfix operators) or a function to call
8793 to parse the operand (for prefix operators)."
8794 (let* ((pos (js2-current-token-beg))
8795 (postfix (js2-node-p parser))
8796 (expr (if postfix
8797 parser
8798 (apply parser args)))
8799 end
8800 pn)
8801 (if postfix ; e.g. i++
8802 (setq pos (js2-node-pos expr)
8803 end (js2-current-token-end))
8804 (setq end (js2-node-end expr)))
8805 (setq pn (make-js2-unary-node :type type
8806 :pos pos
8807 :len (- end pos)
8808 :operand expr))
8809 (js2-node-add-children pn expr)
8810 pn))
8811
8812 (defconst js2-incrementable-node-types
8813 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8814 "Node types that can be the operand of a ++ or -- operator.")
8815
8816 (defun js2-check-bad-inc-dec (tt beg end unary)
8817 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8818 js2-incrementable-node-types)
8819 (js2-report-error (if (= tt js2-INC)
8820 "msg.bad.incr"
8821 "msg.bad.decr")
8822 nil beg (- end beg))))
8823
8824 (defun js2-parse-unary-expr ()
8825 (let ((tt (js2-current-token-type))
8826 pn expr beg end)
8827 (cond
8828 ((or (= tt js2-VOID)
8829 (= tt js2-NOT)
8830 (= tt js2-BITNOT)
8831 (= tt js2-TYPEOF))
8832 (js2-get-token)
8833 (js2-make-unary tt 'js2-parse-unary-expr))
8834 ((= tt js2-ADD)
8835 (js2-get-token)
8836 ;; Convert to special POS token in decompiler and parse tree
8837 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8838 ((= tt js2-SUB)
8839 (js2-get-token)
8840 ;; Convert to special NEG token in decompiler and parse tree
8841 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8842 ((or (= tt js2-INC)
8843 (= tt js2-DEC))
8844 (js2-get-token)
8845 (prog1
8846 (setq beg (js2-current-token-beg)
8847 end (js2-current-token-end)
8848 expr (js2-make-unary tt 'js2-parse-member-expr t))
8849 (js2-check-bad-inc-dec tt beg end expr)))
8850 ((= tt js2-DELPROP)
8851 (js2-get-token)
8852 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8853 ((= tt js2-ERROR)
8854 (js2-get-token)
8855 (make-js2-error-node)) ; try to continue
8856 ((and (= tt js2-LT)
8857 js2-compiler-xml-available)
8858 ;; XML stream encountered in expression.
8859 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8860 (t
8861 (setq pn (js2-parse-member-expr t)
8862 ;; Don't look across a newline boundary for a postfix incop.
8863 tt (js2-peek-token-or-eol))
8864 (when (or (= tt js2-INC) (= tt js2-DEC))
8865 (js2-get-token)
8866 (setf expr pn
8867 pn (js2-make-unary tt expr))
8868 (js2-node-set-prop pn 'postfix t)
8869 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
8870 pn))))
8871
8872 (defun js2-parse-xml-initializer ()
8873 "Parse an E4X XML initializer.
8874 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8875 Then I'll postprocess the result, depending on whether we're in IDE
8876 mode or codegen mode, and generate the appropriate rewritten AST.
8877 IDE mode uses a rich AST that models the XML structure. Codegen mode
8878 just concatenates everything and makes a new XML or XMLList out of it."
8879 (let ((tt (js2-get-first-xml-token))
8880 pn-xml pn expr kids expr-pos
8881 (continue t)
8882 (first-token t))
8883 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8884 (js2-report-error "msg.syntax"))
8885 (setq pn-xml (make-js2-xml-node))
8886 (while continue
8887 (if first-token
8888 (setq first-token nil)
8889 (setq tt (js2-get-next-xml-token)))
8890 (cond
8891 ;; js2-XML means we found a {expr} in the XML stream.
8892 ;; The token string is the XML up to the left-curly.
8893 ((= tt js2-XML)
8894 (push (make-js2-string-node :pos (js2-current-token-beg)
8895 :len (- js2-ts-cursor (js2-current-token-beg)))
8896 kids)
8897 (js2-must-match js2-LC "msg.syntax")
8898 (setq expr-pos js2-ts-cursor
8899 expr (if (eq (js2-peek-token) js2-RC)
8900 (make-js2-empty-expr-node :pos expr-pos)
8901 (js2-parse-expr)))
8902 (js2-must-match js2-RC "msg.syntax")
8903 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8904 :len (js2-node-len expr)
8905 :expr expr))
8906 (js2-node-add-children pn expr)
8907 (push pn kids))
8908 ;; a js2-XMLEND token means we hit the final close-tag.
8909 ((= tt js2-XMLEND)
8910 (push (make-js2-string-node :pos (js2-current-token-beg)
8911 :len (- js2-ts-cursor (js2-current-token-beg)))
8912 kids)
8913 (dolist (kid (nreverse kids))
8914 (js2-block-node-push pn-xml kid))
8915 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8916 (js2-node-pos pn-xml))
8917 continue nil))
8918 (t
8919 (js2-report-error "msg.syntax")
8920 (setq continue nil))))
8921 pn-xml))
8922
8923
8924 (defun js2-parse-argument-list ()
8925 "Parse an argument list and return it as a Lisp list of nodes.
8926 Returns the list in reverse order. Consumes the right-paren token."
8927 (let (result)
8928 (unless (js2-match-token js2-RP)
8929 (loop do
8930 (let ((tt (js2-get-token)))
8931 (if (= tt js2-YIELD)
8932 (js2-report-error "msg.yield.parenthesized"))
8933 (if (and (= tt js2-TRIPLEDOT)
8934 (>= js2-language-version 200))
8935 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
8936 (js2-unget-token)
8937 (push (js2-parse-assign-expr) result)))
8938 while
8939 (js2-match-token js2-COMMA))
8940 (js2-must-match js2-RP "msg.no.paren.arg")
8941 result)))
8942
8943 (defun js2-parse-member-expr (&optional allow-call-syntax)
8944 (let ((tt (js2-current-token-type))
8945 pn pos target args beg end init)
8946 (if (/= tt js2-NEW)
8947 (setq pn (js2-parse-primary-expr))
8948 ;; parse a 'new' expression
8949 (js2-get-token)
8950 (setq pos (js2-current-token-beg)
8951 beg pos
8952 target (js2-parse-member-expr)
8953 end (js2-node-end target)
8954 pn (make-js2-new-node :pos pos
8955 :target target
8956 :len (- end pos)))
8957 (js2-highlight-function-call (js2-current-token))
8958 (js2-node-add-children pn target)
8959 (when (js2-match-token js2-LP)
8960 ;; Add the arguments to pn, if any are supplied.
8961 (setf beg pos ; start of "new" keyword
8962 pos (js2-current-token-beg)
8963 args (nreverse (js2-parse-argument-list))
8964 (js2-new-node-args pn) args
8965 end (js2-current-token-end)
8966 (js2-new-node-lp pn) (- pos beg)
8967 (js2-new-node-rp pn) (- end 1 beg))
8968 (apply #'js2-node-add-children pn args))
8969 (when (and js2-allow-rhino-new-expr-initializer
8970 (js2-match-token js2-LC))
8971 (setf init (js2-parse-object-literal)
8972 end (js2-node-end init)
8973 (js2-new-node-initializer pn) init)
8974 (js2-node-add-children pn init))
8975 (setf (js2-node-len pn) (- end beg))) ; end outer if
8976 (js2-parse-member-expr-tail allow-call-syntax pn)))
8977
8978 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8979 "Parse a chain of property/array accesses or function calls.
8980 Includes parsing for E4X operators like `..' and `.@'.
8981 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8982 Returns an expression tree that includes PN, the parent node."
8983 (let (tt
8984 (continue t))
8985 (while continue
8986 (setq tt (js2-get-token))
8987 (cond
8988 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8989 (setq pn (js2-parse-property-access tt pn)))
8990 ((= tt js2-DOTQUERY)
8991 (setq pn (js2-parse-dot-query pn)))
8992 ((= tt js2-LB)
8993 (setq pn (js2-parse-element-get pn)))
8994 ((= tt js2-LP)
8995 (js2-unget-token)
8996 (if allow-call-syntax
8997 (setq pn (js2-parse-function-call pn))
8998 (setq continue nil)))
8999 (t
9000 (js2-unget-token)
9001 (setq continue nil))))
9002 (if (>= js2-highlight-level 2)
9003 (js2-parse-highlight-member-expr-node pn))
9004 pn))
9005
9006 (defun js2-parse-dot-query (pn)
9007 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9008 Last token parsed must be `js2-DOTQUERY'."
9009 (let ((pos (js2-node-pos pn))
9010 op-pos expr end)
9011 (js2-must-have-xml)
9012 (js2-set-requires-activation)
9013 (setq op-pos (js2-current-token-beg)
9014 expr (js2-parse-expr)
9015 end (js2-node-end expr)
9016 pn (make-js2-xml-dot-query-node :left pn
9017 :pos pos
9018 :op-pos op-pos
9019 :right expr))
9020 (js2-node-add-children pn
9021 (js2-xml-dot-query-node-left pn)
9022 (js2-xml-dot-query-node-right pn))
9023 (if (js2-must-match js2-RP "msg.no.paren")
9024 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9025 end (js2-current-token-end)))
9026 (setf (js2-node-len pn) (- end pos))
9027 pn))
9028
9029 (defun js2-parse-element-get (pn)
9030 "Parse an element-get expression, e.g. foo[bar].
9031 Last token parsed must be `js2-RB'."
9032 (let ((lb (js2-current-token-beg))
9033 (pos (js2-node-pos pn))
9034 rb expr)
9035 (setq expr (js2-parse-expr))
9036 (if (js2-must-match js2-RB "msg.no.bracket.index")
9037 (setq rb (js2-current-token-beg)))
9038 (setq pn (make-js2-elem-get-node :target pn
9039 :pos pos
9040 :element expr
9041 :lb (js2-relpos lb pos)
9042 :rb (js2-relpos rb pos)
9043 :len (- (js2-current-token-end) pos)))
9044 (js2-node-add-children pn
9045 (js2-elem-get-node-target pn)
9046 (js2-elem-get-node-element pn))
9047 pn))
9048
9049 (defun js2-highlight-function-call (token)
9050 (when (eq (js2-token-type token) js2-NAME)
9051 (js2-record-face 'js2-function-call token)))
9052
9053 (defun js2-parse-function-call (pn)
9054 (js2-highlight-function-call (js2-current-token))
9055 (js2-get-token)
9056 (let (args
9057 (pos (js2-node-pos pn)))
9058 (setq pn (make-js2-call-node :pos pos
9059 :target pn
9060 :lp (- (js2-current-token-beg) pos)))
9061 (js2-node-add-children pn (js2-call-node-target pn))
9062 ;; Add the arguments to pn, if any are supplied.
9063 (setf args (nreverse (js2-parse-argument-list))
9064 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9065 (js2-call-node-args pn) args)
9066 (apply #'js2-node-add-children pn args)
9067 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9068 pn))
9069
9070 (defun js2-parse-property-access (tt pn)
9071 "Parse a property access, XML descendants access, or XML attr access."
9072 (let ((member-type-flags 0)
9073 (dot-pos (js2-current-token-beg))
9074 (dot-len (if (= tt js2-DOTDOT) 2 1))
9075 name
9076 ref ; right side of . or .. operator
9077 result)
9078 (when (= tt js2-DOTDOT)
9079 (js2-must-have-xml)
9080 (setq member-type-flags js2-descendants-flag))
9081 (if (not js2-compiler-xml-available)
9082 (progn
9083 (js2-must-match-prop-name "msg.no.name.after.dot")
9084 (setq name (js2-create-name-node t js2-GETPROP)
9085 result (make-js2-prop-get-node :left pn
9086 :pos (js2-current-token-beg)
9087 :right name
9088 :len (js2-current-token-len)))
9089 (js2-node-add-children result pn name)
9090 result)
9091 ;; otherwise look for XML operators
9092 (setf result (if (= tt js2-DOT)
9093 (make-js2-prop-get-node)
9094 (make-js2-infix-node :type js2-DOTDOT))
9095 (js2-node-pos result) (js2-node-pos pn)
9096 (js2-infix-node-op-pos result) dot-pos
9097 (js2-infix-node-left result) pn ; do this after setting position
9098 tt (js2-next-token))
9099 (cond
9100 ;; needed for generator.throw()
9101 ((= tt js2-THROW)
9102 (setq ref (js2-parse-property-name nil nil member-type-flags)))
9103 ;; handles: name, ns::name, ns::*, ns::[expr]
9104 ((js2-valid-prop-name-token tt)
9105 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9106 ;; handles: *, *::name, *::*, *::[expr]
9107 ((= tt js2-MUL)
9108 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9109 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9110 ((= tt js2-XMLATTR)
9111 (setq result (js2-parse-attribute-access)))
9112 (t
9113 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9114 (if ref
9115 (setf (js2-node-len result) (- (js2-node-end ref)
9116 (js2-node-pos result))
9117 (js2-infix-node-right result) ref))
9118 (if (js2-infix-node-p result)
9119 (js2-node-add-children result
9120 (js2-infix-node-left result)
9121 (js2-infix-node-right result)))
9122 result)))
9123
9124 (defun js2-parse-attribute-access ()
9125 "Parse an E4X XML attribute expression.
9126 This includes expressions of the forms:
9127
9128 @attr @ns::attr @ns::*
9129 @* @*::attr @*::*
9130 @[expr] @*::[expr] @ns::[expr]
9131
9132 Called if we peeked an '@' token."
9133 (let ((tt (js2-next-token))
9134 (at-pos (js2-current-token-beg)))
9135 (cond
9136 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9137 ((js2-valid-prop-name-token tt)
9138 (js2-parse-property-name at-pos nil 0))
9139 ;; handles: @*, @*::name, @*::*, @*::[expr]
9140 ((= tt js2-MUL)
9141 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9142 ;; handles @[expr]
9143 ((= tt js2-LB)
9144 (js2-parse-xml-elem-ref at-pos))
9145 (t
9146 (js2-report-error "msg.no.name.after.xmlAttr")
9147 ;; Avoid cascaded errors that happen if we make an error node here.
9148 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9149
9150 (defun js2-parse-property-name (at-pos s member-type-flags)
9151 "Check if :: follows name in which case it becomes qualified name.
9152
9153 AT-POS is a natural number if we just read an '@' token, else nil.
9154 S is the name or string that was matched: an identifier, 'throw' or '*'.
9155 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9156
9157 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9158 operator, or the name is followed by ::. For a plain name, returns a
9159 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9160 (let ((pos (or at-pos (js2-current-token-beg)))
9161 colon-pos
9162 (name (js2-create-name-node t (js2-current-token-type) s))
9163 ns tt pn)
9164 (catch 'return
9165 (when (js2-match-token js2-COLONCOLON)
9166 (setq ns name
9167 colon-pos (js2-current-token-beg)
9168 tt (js2-next-token))
9169 (cond
9170 ;; handles name::name
9171 ((js2-valid-prop-name-token tt)
9172 (setq name (js2-create-name-node)))
9173 ;; handles name::*
9174 ((= tt js2-MUL)
9175 (setq name (js2-create-name-node nil nil "*")))
9176 ;; handles name::[expr]
9177 ((= tt js2-LB)
9178 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9179 (t
9180 (js2-report-error "msg.no.name.after.coloncolon"))))
9181 (if (and (null ns) (zerop member-type-flags))
9182 name
9183 (prog1
9184 (setq pn
9185 (make-js2-xml-prop-ref-node :pos pos
9186 :len (- (js2-node-end name) pos)
9187 :at-pos at-pos
9188 :colon-pos colon-pos
9189 :propname name))
9190 (js2-node-add-children pn name))))))
9191
9192 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9193 "Parse the [expr] portion of an xml element reference.
9194 For instance, @[expr], @*::[expr], or ns::[expr]."
9195 (let* ((lb (js2-current-token-beg))
9196 (pos (or at-pos lb))
9197 rb
9198 (expr (js2-parse-expr))
9199 (end (js2-node-end expr))
9200 pn)
9201 (if (js2-must-match js2-RB "msg.no.bracket.index")
9202 (setq rb (js2-current-token-beg)
9203 end (js2-current-token-end)))
9204 (prog1
9205 (setq pn
9206 (make-js2-xml-elem-ref-node :pos pos
9207 :len (- end pos)
9208 :namespace namespace
9209 :colon-pos colon-pos
9210 :at-pos at-pos
9211 :expr expr
9212 :lb (js2-relpos lb pos)
9213 :rb (js2-relpos rb pos)))
9214 (js2-node-add-children pn namespace expr))))
9215
9216 (defun js2-parse-destruct-primary-expr ()
9217 (let ((js2-is-in-destructuring t))
9218 (js2-parse-primary-expr)))
9219
9220 (defun js2-parse-primary-expr ()
9221 "Parse a literal (leaf) expression of some sort.
9222 Includes complex literals such as functions, object-literals,
9223 array-literals, array comprehensions and regular expressions."
9224 (let (pn ; parent node (usually return value)
9225 tt)
9226 (setq tt (js2-current-token-type))
9227 (cond
9228 ((= tt js2-FUNCTION)
9229 (js2-parse-function-expr))
9230 ((= tt js2-LB)
9231 (js2-parse-array-comp-or-literal))
9232 ((= tt js2-LC)
9233 (js2-parse-object-literal))
9234 ((= tt js2-LET)
9235 (js2-parse-let (js2-current-token-beg)))
9236 ((= tt js2-LP)
9237 (js2-parse-paren-expr-or-generator-comp))
9238 ((= tt js2-XMLATTR)
9239 (js2-must-have-xml)
9240 (js2-parse-attribute-access))
9241 ((= tt js2-NAME)
9242 (js2-parse-name tt))
9243 ((= tt js2-NUMBER)
9244 (make-js2-number-node))
9245 ((= tt js2-STRING)
9246 (prog1
9247 (make-js2-string-node)
9248 (js2-record-face 'font-lock-string-face)))
9249 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9250 ;; Got / or /= which in this context means a regexp literal
9251 (let ((px-pos (js2-current-token-beg))
9252 (flags (js2-read-regexp tt))
9253 (end (js2-current-token-end)))
9254 (prog1
9255 (make-js2-regexp-node :pos px-pos
9256 :len (- end px-pos)
9257 :value (js2-current-token-string)
9258 :flags flags)
9259 (js2-set-face px-pos end 'font-lock-string-face 'record)
9260 (js2-record-text-property px-pos end 'syntax-table '(2)))))
9261 ((or (= tt js2-NULL)
9262 (= tt js2-THIS)
9263 (= tt js2-FALSE)
9264 (= tt js2-TRUE))
9265 (make-js2-keyword-node :type tt))
9266 ((= tt js2-RP)
9267 ;; Not valid expression syntax, but this is valid in an arrow
9268 ;; function with no params: () => body.
9269 (if (eq (js2-peek-token) js2-ARROW)
9270 (progn
9271 (js2-unget-token) ; Put back the right paren.
9272 ;; Return whatever, it will hopefully be rewinded and
9273 ;; reparsed when we reach the =>.
9274 (make-js2-keyword-node :type js2-NULL))
9275 (js2-report-error "msg.syntax")
9276 (make-js2-error-node)))
9277 ((= tt js2-TRIPLEDOT)
9278 ;; Likewise, only valid in an arrow function with a rest param.
9279 (if (and (js2-match-token js2-NAME)
9280 (js2-match-token js2-RP)
9281 (eq (js2-peek-token) js2-ARROW))
9282 (progn
9283 (js2-unget-token) ; Put back the right paren.
9284 ;; See the previous case.
9285 (make-js2-keyword-node :type js2-NULL))
9286 (js2-report-error "msg.syntax")
9287 (make-js2-error-node)))
9288 ((= tt js2-RESERVED)
9289 (js2-report-error "msg.reserved.id")
9290 (make-js2-name-node))
9291 ((= tt js2-ERROR)
9292 ;; the scanner or one of its subroutines reported the error.
9293 (make-js2-error-node))
9294 ((= tt js2-EOF)
9295 (let* ((px-pos (point-at-bol))
9296 (len (- js2-ts-cursor px-pos)))
9297 (js2-report-error "msg.unexpected.eof" nil px-pos len))
9298 (make-js2-error-node :pos (1- js2-ts-cursor)))
9299 (t
9300 (js2-report-error "msg.syntax")
9301 (make-js2-error-node)))))
9302
9303 (defun js2-parse-name (_tt)
9304 (let ((name (js2-current-token-string))
9305 node)
9306 (setq node (if js2-compiler-xml-available
9307 (js2-parse-property-name nil name 0)
9308 (js2-create-name-node 'check-activation nil name)))
9309 (if js2-highlight-external-variables
9310 (js2-record-name-node node))
9311 node))
9312
9313 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9314 (js2-add-strict-warning
9315 msg nil
9316 ;; back up from comma to beginning of line or array/objlit
9317 (max (if elems
9318 (js2-node-pos (car elems))
9319 pos)
9320 (save-excursion
9321 (goto-char comma-pos)
9322 (back-to-indentation)
9323 (point)))
9324 comma-pos))
9325
9326 (defun js2-parse-array-comp-or-literal ()
9327 (let ((pos (js2-current-token-beg)))
9328 (if (and (>= js2-language-version 200)
9329 (js2-match-token js2-FOR))
9330 (js2-parse-array-comp pos)
9331 (js2-parse-array-literal pos))))
9332
9333 (defun js2-parse-array-literal (pos)
9334 (let ((after-lb-or-comma t)
9335 after-comma tt elems pn
9336 (continue t))
9337 (unless js2-is-in-destructuring
9338 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
9339 (while continue
9340 (setq tt (js2-get-token))
9341 (cond
9342 ;; comma
9343 ((= tt js2-COMMA)
9344 (setq after-comma (js2-current-token-end))
9345 (if (not after-lb-or-comma)
9346 (setq after-lb-or-comma t)
9347 (push nil elems)))
9348 ;; end of array
9349 ((or (= tt js2-RB)
9350 (= tt js2-EOF)) ; prevent infinite loop
9351 (if (= tt js2-EOF)
9352 (js2-report-error "msg.no.bracket.arg" nil pos))
9353 (when (and after-comma (< js2-language-version 170))
9354 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9355 pos (remove nil elems) after-comma))
9356 (setq continue nil
9357 pn (make-js2-array-node :pos pos
9358 :len (- js2-ts-cursor pos)
9359 :elems (nreverse elems)))
9360 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
9361 ;; destructuring binding
9362 (js2-is-in-destructuring
9363 (push (if (or (= tt js2-LC)
9364 (= tt js2-LB)
9365 (= tt js2-NAME))
9366 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9367 (js2-parse-destruct-primary-expr)
9368 ;; invalid pattern
9369 (js2-report-error "msg.bad.var")
9370 (make-js2-error-node))
9371 elems)
9372 (setq after-lb-or-comma nil
9373 after-comma nil))
9374 ;; array comp
9375 ((and (>= js2-language-version 170)
9376 (= tt js2-FOR) ; check for array comprehension
9377 (not after-lb-or-comma) ; "for" can't follow a comma
9378 elems ; must have at least 1 element
9379 (not (cdr elems))) ; but no 2nd element
9380 (js2-unget-token)
9381 (setf continue nil
9382 pn (js2-parse-legacy-array-comp (car elems) pos)))
9383 ;; another element
9384 (t
9385 (unless after-lb-or-comma
9386 (js2-report-error "msg.no.bracket.arg"))
9387 (if (and (= tt js2-TRIPLEDOT)
9388 (>= js2-language-version 200))
9389 ;; spread operator
9390 (push (js2-make-unary tt 'js2-parse-assign-expr)
9391 elems)
9392 (js2-unget-token)
9393 (push (js2-parse-assign-expr) elems))
9394 (setq after-lb-or-comma nil
9395 after-comma nil))))
9396 (unless js2-is-in-destructuring
9397 (js2-pop-scope))
9398 pn))
9399
9400 (defun js2-parse-legacy-array-comp (expr pos)
9401 "Parse a legacy array comprehension (JavaScript 1.7).
9402 EXPR is the first expression after the opening left-bracket.
9403 POS is the beginning of the LB token preceding EXPR.
9404 We should have just parsed the 'for' keyword before calling this function."
9405 (let ((current-scope js2-current-scope)
9406 loops first filter result)
9407 (unwind-protect
9408 (progn
9409 (while (js2-match-token js2-FOR)
9410 (let ((loop (make-js2-comp-loop-node)))
9411 (js2-push-scope loop)
9412 (push loop loops)
9413 (js2-parse-comp-loop loop)))
9414 ;; First loop takes expr scope's parent.
9415 (setf (js2-scope-parent-scope (setq first (car (last loops))))
9416 (js2-scope-parent-scope current-scope))
9417 ;; Set expr scope's parent to the last loop.
9418 (setf (js2-scope-parent-scope current-scope) (car loops))
9419 (if (/= (js2-get-token) js2-IF)
9420 (js2-unget-token)
9421 (setq filter (js2-parse-condition))))
9422 (dotimes (_ (1- (length loops)))
9423 (js2-pop-scope)))
9424 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9425 (setq result (make-js2-comp-node :pos pos
9426 :len (- js2-ts-cursor pos)
9427 :result expr
9428 :loops (nreverse loops)
9429 :filters (and filter (list (car filter)))
9430 :form 'LEGACY_ARRAY))
9431 (apply #'js2-node-add-children result expr (car filter)
9432 (js2-comp-node-loops result))
9433 result))
9434
9435 (defun js2-parse-array-comp (pos)
9436 "Parse an ES6 array comprehension.
9437 POS is the beginning of the LB token.
9438 We should have just parsed the 'for' keyword before calling this function."
9439 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
9440 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9441 pn))
9442
9443 (defun js2-parse-generator-comp (pos)
9444 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
9445 (js2-current-script-or-fn
9446 (make-js2-function-node :generator-type 'COMPREHENSION))
9447 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
9448 (js2-must-match js2-RP "msg.no.paren" pos)
9449 pn))
9450
9451 (defun js2-parse-comprehension (pos form)
9452 (let (loops filters expr result)
9453 (unwind-protect
9454 (progn
9455 (js2-unget-token)
9456 (while (js2-match-token js2-FOR)
9457 (let ((loop (make-js2-comp-loop-node)))
9458 (js2-push-scope loop)
9459 (push loop loops)
9460 (js2-parse-comp-loop loop)))
9461 (while (js2-match-token js2-IF)
9462 (push (car (js2-parse-condition)) filters))
9463 (setq expr (js2-parse-assign-expr)))
9464 (dolist (_ loops)
9465 (js2-pop-scope)))
9466 (setq result (make-js2-comp-node :pos pos
9467 :len (- js2-ts-cursor pos)
9468 :result expr
9469 :loops (nreverse loops)
9470 :filters (nreverse filters)
9471 :form form))
9472 (apply #'js2-node-add-children result (js2-comp-node-loops result))
9473 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
9474 result))
9475
9476 (defun js2-parse-comp-loop (pn &optional only-of-p)
9477 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9478 The current token should be the initial FOR.
9479 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
9480 (let ((pos (js2-comp-loop-node-pos pn))
9481 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9482 (when (and (not only-of-p) (js2-match-token js2-NAME))
9483 (if (string= (js2-current-token-string) "each")
9484 (progn
9485 (setq foreach-p t
9486 each-pos (- (js2-current-token-beg) pos)) ; relative
9487 (js2-record-face 'font-lock-keyword-face))
9488 (js2-report-error "msg.no.paren.for")))
9489 (if (js2-must-match js2-LP "msg.no.paren.for")
9490 (setq lp (- (js2-current-token-beg) pos)))
9491 (setq tt (js2-peek-token))
9492 (cond
9493 ((or (= tt js2-LB)
9494 (= tt js2-LC))
9495 (js2-get-token)
9496 (setq iter (js2-parse-destruct-primary-expr))
9497 (js2-define-destruct-symbols iter js2-LET
9498 'font-lock-variable-name-face t))
9499 ((js2-match-token js2-NAME)
9500 (setq iter (js2-create-name-node)))
9501 (t
9502 (js2-report-error "msg.bad.var")))
9503 ;; Define as a let since we want the scope of the variable to
9504 ;; be restricted to the array comprehension
9505 (if (js2-name-node-p iter)
9506 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9507 (if (or (and (not only-of-p) (js2-match-token js2-IN))
9508 (and (>= js2-language-version 200)
9509 (js2-match-contextual-kwd "of")
9510 (setq forof-p t)))
9511 (setq in-pos (- (js2-current-token-beg) pos))
9512 (js2-report-error "msg.in.after.for.name"))
9513 (setq obj (js2-parse-expr))
9514 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9515 (setq rp (- (js2-current-token-beg) pos)))
9516 (setf (js2-node-pos pn) pos
9517 (js2-node-len pn) (- js2-ts-cursor pos)
9518 (js2-comp-loop-node-iterator pn) iter
9519 (js2-comp-loop-node-object pn) obj
9520 (js2-comp-loop-node-in-pos pn) in-pos
9521 (js2-comp-loop-node-each-pos pn) each-pos
9522 (js2-comp-loop-node-foreach-p pn) foreach-p
9523 (js2-comp-loop-node-forof-p pn) forof-p
9524 (js2-comp-loop-node-lp pn) lp
9525 (js2-comp-loop-node-rp pn) rp)
9526 (js2-node-add-children pn iter obj)
9527 pn))
9528
9529 (defun js2-parse-object-literal ()
9530 (let ((pos (js2-current-token-beg))
9531 tt elems result after-comma
9532 (continue t))
9533 (while continue
9534 (setq tt (js2-get-token))
9535 (cond
9536 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9537 ;; {get foo() {...}}, or {set foo(x) {...}}
9538 ((or (js2-valid-prop-name-token tt)
9539 (= tt js2-STRING))
9540 (setq after-comma nil
9541 result (js2-parse-named-prop tt))
9542 (if (and (null result)
9543 (not js2-recover-from-parse-errors))
9544 (setq continue nil)
9545 (push result elems)))
9546 ;; {12: x} or {10.7: x}
9547 ((= tt js2-NUMBER)
9548 (setq after-comma nil)
9549 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9550 ;; trailing comma
9551 ((= tt js2-RC)
9552 (js2-unget-token)
9553 (setq continue nil)
9554 (if after-comma
9555 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9556 pos elems after-comma)))
9557 (t
9558 (js2-report-error "msg.bad.prop")
9559 (unless js2-recover-from-parse-errors
9560 (setq continue nil)))) ; end switch
9561 (if (js2-match-token js2-COMMA)
9562 (setq after-comma (js2-current-token-end))
9563 (setq continue nil))) ; end loop
9564 (js2-must-match js2-RC "msg.no.brace.prop")
9565 (setq result (make-js2-object-node :pos pos
9566 :len (- js2-ts-cursor pos)
9567 :elems (nreverse elems)))
9568 (apply #'js2-node-add-children result (js2-object-node-elems result))
9569 result))
9570
9571 (defun js2-parse-named-prop (tt)
9572 "Parse a name, string, or getter/setter object property.
9573 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9574 (let ((string-prop (and (= tt js2-STRING)
9575 (make-js2-string-node)))
9576 expr
9577 (ppos (js2-current-token-beg))
9578 (pend (js2-current-token-end))
9579 (name (js2-create-name-node))
9580 (prop (js2-current-token-string)))
9581 (cond
9582 ;; getter/setter prop
9583 ((and (= tt js2-NAME)
9584 (= (js2-peek-token) js2-NAME)
9585 (or (string= prop "get")
9586 (string= prop "set")))
9587 (js2-get-token)
9588 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9589 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9590 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9591 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9592 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9593 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9594 ;; when patterns are used in variable declarations, function parameters,
9595 ;; catch-clause, and iterators.
9596 ;; We have to set `js2-is-in-destructuring' to t when the current
9597 ;; expressions are on the left side of any assignment, but it's difficult
9598 ;; because it requires looking ahead of expression.
9599 ((and js2-is-in-destructuring
9600 (= tt js2-NAME)
9601 (let ((ctk (js2-peek-token)))
9602 (or (= ctk js2-COMMA)
9603 (= ctk js2-RC)
9604 (js2-valid-prop-name-token ctk))))
9605 name)
9606 ;; regular prop
9607 (t
9608 (prog1
9609 (setq expr (js2-parse-plain-property (or string-prop name)))
9610 (js2-set-face ppos pend
9611 (if (js2-function-node-p
9612 (js2-object-prop-node-right expr))
9613 'font-lock-function-name-face
9614 'font-lock-variable-name-face)
9615 'record))))))
9616
9617 (defun js2-parse-plain-property (prop)
9618 "Parse a non-getter/setter property in an object literal.
9619 PROP is the node representing the property: a number, name or string."
9620 (let ((pos (js2-node-pos prop))
9621 colon expr)
9622 (if (js2-must-match js2-COLON "msg.no.colon.prop")
9623 (setq colon (- (js2-current-token-beg) pos)
9624 expr (js2-parse-assign-expr))
9625 (setq expr (make-js2-error-node)))
9626 (let ((result (make-js2-object-prop-node
9627 :pos pos
9628 ;; don't include last consumed token in length
9629 :len (- (+ (js2-node-pos expr)
9630 (js2-node-len expr))
9631 pos)
9632 :left prop
9633 :right expr
9634 :op-pos colon)))
9635 (js2-node-add-children result prop expr)
9636 result)))
9637
9638 (defun js2-parse-getter-setter-prop (pos prop get-p)
9639 "Parse getter or setter property in an object literal.
9640 JavaScript syntax is:
9641
9642 { get foo() {...}, set foo(x) {...} }
9643
9644 and expression closure style is also supported
9645
9646 { get foo() x, set foo(x) _x = x }
9647
9648 POS is the start position of the `get' or `set' keyword.
9649 PROP is the `js2-name-node' representing the property name.
9650 GET-P is non-nil if the keyword was `get'."
9651 (let ((type (if get-p js2-GET js2-SET))
9652 result end
9653 (fn (js2-parse-function-expr)))
9654 ;; it has to be an anonymous function, as we already parsed the name
9655 (if (/= (js2-node-type fn) js2-FUNCTION)
9656 (js2-report-error "msg.bad.prop")
9657 (if (plusp (length (js2-function-name fn)))
9658 (js2-report-error "msg.bad.prop")))
9659 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9660 (setq end (js2-node-end fn)
9661 result (make-js2-getter-setter-node :type type
9662 :pos pos
9663 :len (- end pos)
9664 :left prop
9665 :right fn))
9666 (js2-node-add-children result prop fn)
9667 result))
9668
9669 (defun js2-create-name-node (&optional check-activation-p token string)
9670 "Create a name node using the current token and, optionally, STRING.
9671 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
9672 (let* ((beg (js2-current-token-beg))
9673 (tt (js2-current-token-type))
9674 (s (or string
9675 (if (= js2-NAME tt)
9676 (js2-current-token-string)
9677 (js2-tt-name tt))))
9678 name)
9679 (setq name (make-js2-name-node :pos beg
9680 :name s
9681 :len (length s)))
9682 (if check-activation-p
9683 (js2-check-activation-name s (or token js2-NAME)))
9684 name))
9685
9686 ;;; Indentation support
9687
9688 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9689 ;; Karl cleverly deduces that the desired indentation level is often a
9690 ;; function of paren/bracket/brace nesting depth, which can be determined
9691 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9692 ;; then does some equally clever checks to see if we're in the context of a
9693 ;; substatement of a possibly braceless statement keyword such as if, while,
9694 ;; or finally. This approach yields pretty good results.
9695
9696 ;; The indenter is often "wrong", however, and needs to be overridden.
9697 ;; The right long-term solution is probably to emulate (or integrate
9698 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9699 ;; parse tree from `js2-parse' is present, which is not true at the
9700 ;; moment the user is typing, computing indentation is still thousands
9701 ;; of lines of code to handle every possible syntactic edge case.
9702
9703 ;; In the meantime, the compromise solution is that we offer a "bounce
9704 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9705 ;; current line indent among various likely guess points. This approach
9706 ;; is far from perfect, but should at least make it slightly easier to
9707 ;; move the line towards its desired indentation when manually
9708 ;; overriding Karl's heuristic nesting guesser.
9709
9710 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9711 ;; extensions such as `let' and Array comprehensions. Major kudos to
9712 ;; Karl for coming up with the initial approach, which packs a lot of
9713 ;; punch for so little code.
9714
9715 (defconst js2-possibly-braceless-keywords-re
9716 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9717 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9718 "try" "while" "with" "let")))
9719 "Regular expression matching keywords that are optionally
9720 followed by an opening brace.")
9721
9722 (defconst js2-indent-operator-re
9723 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
9724 (regexp-opt '("in" "instanceof") 'words))
9725 "Regular expression matching operators that affect indentation
9726 of continued expressions.")
9727
9728 (defconst js2-declaration-keyword-re
9729 (regexp-opt '("var" "let" "const") 'words)
9730 "Regular expression matching variable declaration keywords.")
9731
9732 (defun js2-re-search-forward-inner (regexp &optional bound count)
9733 "Auxiliary function for `js2-re-search-forward'."
9734 (let (parse saved-point)
9735 (while (> count 0)
9736 (re-search-forward regexp bound)
9737 (setq parse (if saved-point
9738 (parse-partial-sexp saved-point (point))
9739 (syntax-ppss (point))))
9740 (cond ((nth 3 parse)
9741 (re-search-forward
9742 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
9743 (save-excursion (end-of-line) (point)) t))
9744 ((nth 7 parse)
9745 (forward-line))
9746 ((or (nth 4 parse)
9747 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9748 (re-search-forward "\\*/"))
9749 (t
9750 (setq count (1- count))))
9751 (setq saved-point (point))))
9752 (point))
9753
9754 (defun js2-re-search-forward (regexp &optional bound noerror count)
9755 "Search forward but ignore strings and comments.
9756 Invokes `re-search-forward' but treats the buffer as if strings
9757 and comments have been removed."
9758 (let ((saved-point (point)))
9759 (condition-case err
9760 (cond ((null count)
9761 (js2-re-search-forward-inner regexp bound 1))
9762 ((< count 0)
9763 (js2-re-search-backward-inner regexp bound (- count)))
9764 ((> count 0)
9765 (js2-re-search-forward-inner regexp bound count)))
9766 (search-failed
9767 (goto-char saved-point)
9768 (unless noerror
9769 (error (error-message-string err)))))))
9770
9771 (defun js2-re-search-backward-inner (regexp &optional bound count)
9772 "Auxiliary function for `js2-re-search-backward'."
9773 (let (parse)
9774 (while (> count 0)
9775 (re-search-backward regexp bound)
9776 (setq parse (syntax-ppss (point)))
9777 (cond ((nth 3 parse)
9778 (re-search-backward
9779 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9780 (line-beginning-position) t))
9781 ((nth 7 parse)
9782 (goto-char (nth 8 parse)))
9783 ((or (nth 4 parse)
9784 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9785 (re-search-backward "/\\*"))
9786 (t
9787 (setq count (1- count))))))
9788 (point))
9789
9790 (defun js2-re-search-backward (regexp &optional bound noerror count)
9791 "Search backward but ignore strings and comments.
9792 Invokes `re-search-backward' but treats the buffer as if strings
9793 and comments have been removed."
9794 (let ((saved-point (point)))
9795 (condition-case err
9796 (cond ((null count)
9797 (js2-re-search-backward-inner regexp bound 1))
9798 ((< count 0)
9799 (js2-re-search-forward-inner regexp bound (- count)))
9800 ((> count 0)
9801 (js2-re-search-backward-inner regexp bound count)))
9802 (search-failed
9803 (goto-char saved-point)
9804 (unless noerror
9805 (error (error-message-string err)))))))
9806
9807 (defun js2-looking-at-operator-p ()
9808 "Return non-nil if text after point is a non-comma operator."
9809 (and (looking-at js2-indent-operator-re)
9810 (or (not (looking-at ":"))
9811 (save-excursion
9812 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9813 (looking-at "?"))))))
9814
9815 (defun js2-continued-expression-p ()
9816 "Return non-nil if the current line continues an expression."
9817 (save-excursion
9818 (back-to-indentation)
9819 (or (js2-looking-at-operator-p)
9820 (when (catch 'found
9821 (while (and (re-search-backward "\n" nil t)
9822 (let ((state (syntax-ppss)))
9823 (when (nth 4 state)
9824 (goto-char (nth 8 state))) ;; skip comments
9825 (skip-chars-backward " \t")
9826 (if (bolp)
9827 t
9828 (throw 'found t))))))
9829 (backward-char)
9830 (when (js2-looking-at-operator-p)
9831 (backward-char)
9832 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
9833
9834 (defun js2-end-of-do-while-loop-p ()
9835 "Return non-nil if word after point is `while' of a do-while
9836 statement, else returns nil. A braceless do-while statement
9837 spanning several lines requires that the start of the loop is
9838 indented to the same column as the current line."
9839 (interactive)
9840 (save-excursion
9841 (when (looking-at "\\s-*\\<while\\>")
9842 (if (save-excursion
9843 (skip-chars-backward "[ \t\n]*}")
9844 (looking-at "[ \t\n]*}"))
9845 (save-excursion
9846 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9847 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9848 (or (looking-at "\\<do\\>")
9849 (let ((saved-indent (current-indentation)))
9850 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9851 (/= (current-indentation) saved-indent)))
9852 (and (looking-at "[ \t]*\\<do\\>")
9853 (not (js2-re-search-forward
9854 "\\<while\\>" (point-at-eol) t))
9855 (= (current-indentation) saved-indent))))))))
9856
9857 (defun js2-multiline-decl-indentation ()
9858 "Return the declaration indentation column if the current line belongs
9859 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9860 (let (forward-sexp-function ; use Lisp version
9861 at-opening-bracket)
9862 (save-excursion
9863 (back-to-indentation)
9864 (when (not (looking-at js2-declaration-keyword-re))
9865 (when (looking-at js2-indent-operator-re)
9866 (goto-char (match-end 0))) ; continued expressions are ok
9867 (while (and (not at-opening-bracket)
9868 (not (bobp))
9869 (let ((pos (point)))
9870 (save-excursion
9871 (js2-backward-sws)
9872 (or (eq (char-before) ?,)
9873 (and (not (eq (char-before) ?\;))
9874 (prog2 (skip-syntax-backward ".")
9875 (looking-at js2-indent-operator-re)
9876 (js2-backward-sws))
9877 (not (eq (char-before) ?\;)))
9878 (js2-same-line pos)))))
9879 (condition-case _
9880 (backward-sexp)
9881 (scan-error (setq at-opening-bracket t))))
9882 (when (looking-at js2-declaration-keyword-re)
9883 (goto-char (match-end 0))
9884 (1+ (current-column)))))))
9885
9886 (defun js2-ctrl-statement-indentation ()
9887 "Return the proper indentation of current line if it is a control statement.
9888 Returns an indentation if this line starts the body of a control
9889 statement without braces, else returns nil."
9890 (let (forward-sexp-function)
9891 (save-excursion
9892 (back-to-indentation)
9893 (when (and (not (js2-same-line (point-min)))
9894 (not (looking-at "{"))
9895 (js2-re-search-backward "[[:graph:]]" nil t)
9896 (not (looking-at "[{([]"))
9897 (progn
9898 (forward-char)
9899 (when (= (char-before) ?\))
9900 ;; scan-sexps sometimes throws an error
9901 (ignore-errors (backward-sexp))
9902 (skip-chars-backward " \t" (point-at-bol)))
9903 (let ((pt (point)))
9904 (back-to-indentation)
9905 (when (looking-at "}[ \t]*")
9906 (goto-char (match-end 0)))
9907 (and (looking-at js2-possibly-braceless-keywords-re)
9908 (= (match-end 0) pt)
9909 (not (js2-end-of-do-while-loop-p))))))
9910 (+ (current-indentation) js2-basic-offset)))))
9911
9912 (defun js2-indent-in-array-comp (parse-status)
9913 "Return non-nil if we think we're in an array comprehension.
9914 In particular, return the buffer position of the first `for' kwd."
9915 (let ((bracket (nth 1 parse-status))
9916 (end (point)))
9917 (when bracket
9918 (save-excursion
9919 (goto-char bracket)
9920 (when (looking-at "\\[")
9921 (forward-char 1)
9922 (js2-forward-sws)
9923 (if (looking-at "[[{]")
9924 (let (forward-sexp-function) ; use Lisp version
9925 (forward-sexp) ; skip destructuring form
9926 (js2-forward-sws)
9927 (if (and (/= (char-after) ?,) ; regular array
9928 (looking-at "for"))
9929 (match-beginning 0)))
9930 ;; to skip arbitrary expressions we need the parser,
9931 ;; so we'll just guess at it.
9932 (if (and (> end (point)) ; not empty literal
9933 (re-search-forward "[^,]]* \\(for\\) " end t)
9934 ;; not inside comment or string literal
9935 (let ((state (parse-partial-sexp bracket (point))))
9936 (not (or (nth 3 state) (nth 4 state)))))
9937 (match-beginning 1))))))))
9938
9939 (defun js2-array-comp-indentation (parse-status for-kwd)
9940 (if (js2-same-line for-kwd)
9941 ;; first continuation line
9942 (save-excursion
9943 (goto-char (nth 1 parse-status))
9944 (forward-char 1)
9945 (skip-chars-forward " \t")
9946 (current-column))
9947 (save-excursion
9948 (goto-char for-kwd)
9949 (current-column))))
9950
9951 (defun js2-proper-indentation (parse-status)
9952 "Return the proper indentation for the current line."
9953 (save-excursion
9954 (back-to-indentation)
9955 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9956 (at-closing-bracket (looking-at "[]})]"))
9957 (same-indent-p (or at-closing-bracket
9958 (looking-at "\\<case\\>[^:]")
9959 (and (looking-at "\\<default:")
9960 (save-excursion
9961 (js2-backward-sws)
9962 (not (memq (char-before) '(?, ?{)))))))
9963 (continued-expr-p (js2-continued-expression-p))
9964 (declaration-indent (and js2-pretty-multiline-declarations
9965 (js2-multiline-decl-indentation)))
9966 (bracket (nth 1 parse-status))
9967 beg indent)
9968 (cond
9969 ;; indent array comprehension continuation lines specially
9970 ((and bracket
9971 (>= js2-language-version 170)
9972 (not (js2-same-line bracket))
9973 (setq beg (js2-indent-in-array-comp parse-status))
9974 (>= (point) (save-excursion
9975 (goto-char beg)
9976 (point-at-bol)))) ; at or after first loop?
9977 (js2-array-comp-indentation parse-status beg))
9978
9979 (ctrl-stmt-indent)
9980
9981 ((and declaration-indent continued-expr-p)
9982 (+ declaration-indent js2-basic-offset))
9983
9984 (declaration-indent)
9985
9986 (bracket
9987 (goto-char bracket)
9988 (cond
9989 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9990 (when (save-excursion (skip-chars-backward " \t)")
9991 (looking-at ")"))
9992 (backward-list))
9993 (back-to-indentation)
9994 (and (eq js2-pretty-multiline-declarations 'all)
9995 (looking-at js2-declaration-keyword-re)
9996 (goto-char (1+ (match-end 0))))
9997 (setq indent
9998 (cond (same-indent-p
9999 (current-column))
10000 (continued-expr-p
10001 (+ (current-column) (* 2 js2-basic-offset)))
10002 (t
10003 (+ (current-column) js2-basic-offset))))
10004 (if (and js2-indent-switch-body
10005 (not at-closing-bracket)
10006 (looking-at "\\_<switch\\_>"))
10007 (+ indent js2-basic-offset)
10008 indent))
10009 (t
10010 (unless same-indent-p
10011 (forward-char)
10012 (skip-chars-forward " \t"))
10013 (current-column))))
10014
10015 (continued-expr-p js2-basic-offset)
10016
10017 (t 0)))))
10018
10019 (defun js2-lineup-comment (parse-status)
10020 "Indent a multi-line block comment continuation line."
10021 (let* ((beg (nth 8 parse-status))
10022 (first-line (js2-same-line beg))
10023 (offset (save-excursion
10024 (goto-char beg)
10025 (if (looking-at "/\\*")
10026 (+ 1 (current-column))
10027 0))))
10028 (unless first-line
10029 (indent-line-to offset))))
10030
10031 (defun js2-backward-sws ()
10032 "Move backward through whitespace and comments."
10033 (interactive)
10034 (while (forward-comment -1)))
10035
10036 (defun js2-forward-sws ()
10037 "Move forward through whitespace and comments."
10038 (interactive)
10039 (while (forward-comment 1)))
10040
10041 (defun js2-current-indent (&optional pos)
10042 "Return column of indentation on current line.
10043 If POS is non-nil, go to that point and return indentation for that line."
10044 (save-excursion
10045 (if pos
10046 (goto-char pos))
10047 (back-to-indentation)
10048 (current-column)))
10049
10050 (defun js2-arglist-close ()
10051 "Return non-nil if we're on a line beginning with a close-paren/brace."
10052 (save-excursion
10053 (goto-char (point-at-bol))
10054 (js2-forward-sws)
10055 (looking-at "[])}]")))
10056
10057 (defun js2-indent-looks-like-label-p ()
10058 (goto-char (point-at-bol))
10059 (js2-forward-sws)
10060 (looking-at (concat js2-mode-identifier-re ":")))
10061
10062 (defun js2-indent-in-objlit-p (parse-status)
10063 "Return non-nil if this looks like an object-literal entry."
10064 (let ((start (nth 1 parse-status)))
10065 (and
10066 start
10067 (save-excursion
10068 (and (zerop (forward-line -1))
10069 (not (< (point) start)) ; crossed a {} boundary
10070 (js2-indent-looks-like-label-p)))
10071 (save-excursion
10072 (js2-indent-looks-like-label-p)))))
10073
10074 ;; If prev line looks like foobar({ then we're passing an object
10075 ;; literal to a function call, and people pretty much always want to
10076 ;; de-dent back to the previous line, so move the 'basic-offset'
10077 ;; position to the front.
10078 (defun js2-indent-objlit-arg-p (parse-status)
10079 (save-excursion
10080 (back-to-indentation)
10081 (js2-backward-sws)
10082 (and (eq (1- (point)) (nth 1 parse-status))
10083 (eq (char-before) ?{)
10084 (progn
10085 (forward-char -1)
10086 (skip-chars-backward " \t")
10087 (eq (char-before) ?\()))))
10088
10089 (defun js2-indent-case-block-p ()
10090 (save-excursion
10091 (back-to-indentation)
10092 (js2-backward-sws)
10093 (goto-char (point-at-bol))
10094 (skip-chars-forward " \t")
10095 (looking-at "case\\s-.+:")))
10096
10097 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10098 "Cycle among alternate computed indentation positions.
10099 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10100 of the buffer to the current point. NORMAL-COL is the indentation
10101 column computed by the heuristic guesser based on current paren,
10102 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10103 in reverse."
10104 (let ((cur-indent (js2-current-indent))
10105 (old-buffer-undo-list buffer-undo-list)
10106 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10107 (current-line (save-excursion
10108 (forward-line 0) ; move to bol
10109 (1+ (count-lines (point-min) (point)))))
10110 positions pos main-pos anchor arglist-cont same-indent
10111 basic-offset computed-pos)
10112 ;; temporarily don't record undo info, if user requested this
10113 (when js2-mode-indent-inhibit-undo
10114 (setq buffer-undo-list t))
10115 (unwind-protect
10116 (progn
10117 ;; First likely point: indent from beginning of previous code line
10118 (push (setq basic-offset
10119 (+ (save-excursion
10120 (back-to-indentation)
10121 (js2-backward-sws)
10122 (back-to-indentation)
10123 (current-column))
10124 js2-basic-offset))
10125 positions)
10126
10127 ;; (First + epsilon) likely point: indent 2x from beginning of
10128 ;; previous code line. Google does it this way.
10129 (push (setq basic-offset
10130 (+ (save-excursion
10131 (back-to-indentation)
10132 (js2-backward-sws)
10133 (back-to-indentation)
10134 (current-column))
10135 (* 2 js2-basic-offset)))
10136 positions)
10137
10138 ;; Second likely point: indent from assign-expr RHS. This
10139 ;; is just a crude guess based on finding " = " on the previous
10140 ;; line containing actual code.
10141 (setq pos (save-excursion
10142 (forward-line -1)
10143 (goto-char (point-at-bol))
10144 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10145 (point-at-eol) t)
10146 (goto-char (match-end 1))
10147 (skip-chars-forward " \t\r\n")
10148 (current-column))))
10149 (when pos
10150 (incf pos js2-basic-offset)
10151 (push pos positions))
10152
10153 ;; Third likely point: same indent as previous line of code.
10154 ;; Make it the first likely point if we're not on an
10155 ;; arglist-close line and previous line ends in a comma, or
10156 ;; both this line and prev line look like object-literal
10157 ;; elements.
10158 (setq pos (save-excursion
10159 (goto-char (point-at-bol))
10160 (js2-backward-sws)
10161 (back-to-indentation)
10162 (prog1
10163 (current-column)
10164 ;; while we're here, look for trailing comma
10165 (if (save-excursion
10166 (goto-char (point-at-eol))
10167 (js2-backward-sws)
10168 (eq (char-before) ?,))
10169 (setq arglist-cont (1- (point)))))))
10170 (when pos
10171 (if (and (or arglist-cont
10172 (js2-indent-in-objlit-p parse-status))
10173 (not (js2-arglist-close)))
10174 (setq same-indent pos))
10175 (push pos positions))
10176
10177 ;; Fourth likely point: first preceding code with less indentation.
10178 ;; than the immediately preceding code line.
10179 (setq pos (save-excursion
10180 (back-to-indentation)
10181 (js2-backward-sws)
10182 (back-to-indentation)
10183 (setq anchor (current-column))
10184 (while (and (zerop (forward-line -1))
10185 (>= (progn
10186 (back-to-indentation)
10187 (current-column))
10188 anchor)))
10189 (setq pos (current-column))))
10190 (push pos positions)
10191
10192 ;; nesting-heuristic position, main by default
10193 (push (setq main-pos normal-col) positions)
10194
10195 ;; delete duplicates and sort positions list
10196 (setq positions (sort (delete-dups positions) '<))
10197
10198 ;; comma-list continuation lines: prev line indent takes precedence
10199 (if same-indent
10200 (setq main-pos same-indent))
10201
10202 ;; common special cases where we want to indent in from previous line
10203 (if (or (js2-indent-case-block-p)
10204 (js2-indent-objlit-arg-p parse-status))
10205 (setq main-pos basic-offset))
10206
10207 ;; if bouncing backwards, reverse positions list
10208 (if backwards
10209 (setq positions (reverse positions)))
10210
10211 ;; record whether we're already sitting on one of the alternatives
10212 (setq pos (member cur-indent positions))
10213
10214 (cond
10215 ;; case 0: we're one one of the alternatives and this is the
10216 ;; first time they've pressed TAB on this line (best-guess).
10217 ((and js2-mode-indent-ignore-first-tab
10218 pos
10219 ;; first time pressing TAB on this line?
10220 (not (eq js2-mode-last-indented-line current-line)))
10221 ;; do nothing
10222 (setq computed-pos nil))
10223 ;; case 1: only one computed position => use it
10224 ((null (cdr positions))
10225 (setq computed-pos 0))
10226 ;; case 2: not on any of the computed spots => use main spot
10227 ((not pos)
10228 (setq computed-pos (js2-position main-pos positions)))
10229 ;; case 3: on last position: cycle to first position
10230 ((null (cdr pos))
10231 (setq computed-pos 0))
10232 ;; case 4: on intermediate position: cycle to next position
10233 (t
10234 (setq computed-pos (js2-position (second pos) positions))))
10235
10236 ;; see if any hooks want to indent; otherwise we do it
10237 (loop with result = nil
10238 for hook in js2-indent-hook
10239 while (null result)
10240 do
10241 (setq result (funcall hook positions computed-pos))
10242 finally do
10243 (unless (or result (null computed-pos))
10244 (indent-line-to (nth computed-pos positions)))))
10245
10246 ;; finally
10247 (if js2-mode-indent-inhibit-undo
10248 (setq buffer-undo-list old-buffer-undo-list))
10249 ;; see commentary for `js2-mode-last-indented-line'
10250 (setq js2-mode-last-indented-line current-line))))
10251
10252 (defun js2-indent-bounce-backwards ()
10253 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10254 cycles between the computed indentation positions in reverse order."
10255 (interactive)
10256 (js2-indent-line t))
10257
10258 (defun js2-1-line-comment-continuation-p ()
10259 "Return t if we're in a 1-line comment continuation.
10260 If so, we don't ever want to use bounce-indent."
10261 (save-excursion
10262 (and (progn
10263 (forward-line 0)
10264 (looking-at "\\s-*//"))
10265 (progn
10266 (forward-line -1)
10267 (forward-line 0)
10268 (when (looking-at "\\s-*$")
10269 (js2-backward-sws)
10270 (forward-line 0))
10271 (looking-at "\\s-*//")))))
10272
10273 (defun js2-indent-line (&optional bounce-backwards)
10274 "Indent the current line as JavaScript source text."
10275 (interactive)
10276 (let (parse-status offset indent-col
10277 ;; Don't whine about errors/warnings when we're indenting.
10278 ;; This has to be set before calling parse-partial-sexp below.
10279 (inhibit-point-motion-hooks t))
10280 (setq parse-status (save-excursion
10281 (syntax-ppss (point-at-bol)))
10282 offset (- (point) (save-excursion
10283 (back-to-indentation)
10284 (point))))
10285 (js2-with-underscore-as-word-syntax
10286 (if (nth 4 parse-status)
10287 (js2-lineup-comment parse-status)
10288 (setq indent-col (js2-proper-indentation parse-status))
10289 ;; See comments below about `js2-mode-last-indented-line'.
10290 (cond
10291 ;; bounce-indenting is disabled during electric-key indent.
10292 ;; It doesn't work well on first line of buffer.
10293 ((and js2-bounce-indent-p
10294 (not (js2-same-line (point-min)))
10295 (not (js2-1-line-comment-continuation-p)))
10296 (js2-bounce-indent indent-col parse-status bounce-backwards))
10297 ;; just indent to the guesser's likely spot
10298 (t (indent-line-to indent-col))))
10299 (when (plusp offset)
10300 (forward-char offset)))))
10301
10302 (defun js2-indent-region (start end)
10303 "Indent the region, but don't use bounce indenting."
10304 (let ((js2-bounce-indent-p nil)
10305 (indent-region-function nil)
10306 (after-change-functions (remq 'js2-mode-edit
10307 after-change-functions)))
10308 (indent-region start end nil) ; nil for byte-compiler
10309 (js2-mode-edit start end (- end start))))
10310
10311 (defvar js2-minor-mode-map
10312 (let ((map (make-sparse-keymap)))
10313 (define-key map (kbd "C-c C-`") #'js2-next-error)
10314 (define-key map [mouse-1] #'js2-mode-show-node)
10315 map)
10316 "Keymap used when `js2-minor-mode' is active.")
10317
10318 ;;;###autoload
10319 (define-minor-mode js2-minor-mode
10320 "Minor mode for running js2 as a background linter.
10321 This allows you to use a different major mode for JavaScript editing,
10322 such as `js-mode', while retaining the asynchronous error/warning
10323 highlighting features of `js2-mode'."
10324 :group 'js2-mode
10325 :lighter " js-lint"
10326 (if js2-minor-mode
10327 (js2-minor-mode-enter)
10328 (js2-minor-mode-exit)))
10329
10330 (defun js2-minor-mode-enter ()
10331 "Initialization for `js2-minor-mode'."
10332 (set (make-local-variable 'max-lisp-eval-depth)
10333 (max max-lisp-eval-depth 3000))
10334 (setq next-error-function #'js2-next-error)
10335 (js2-set-default-externs)
10336 ;; Experiment: make reparse-delay longer for longer files.
10337 (if (plusp js2-dynamic-idle-timer-adjust)
10338 (setq js2-idle-timer-delay
10339 (* js2-idle-timer-delay
10340 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10341 (setq js2-mode-buffer-dirty-p t
10342 js2-mode-parsing nil)
10343 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10344 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10345 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10346 (when js2-include-jslint-globals
10347 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10348 (run-hooks 'js2-init-hook)
10349 (js2-reparse))
10350
10351 (defun js2-minor-mode-exit ()
10352 "Turn off `js2-minor-mode'."
10353 (setq next-error-function nil)
10354 (remove-hook 'after-change-functions #'js2-mode-edit t)
10355 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10356 (when js2-mode-node-overlay
10357 (delete-overlay js2-mode-node-overlay)
10358 (setq js2-mode-node-overlay nil))
10359 (js2-remove-overlays)
10360 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
10361 (setq js2-mode-ast nil))
10362
10363 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10364 (make-variable-buffer-local 'js2-source-buffer)
10365
10366 (defun* js2-display-error-list ()
10367 "Display a navigable buffer listing parse errors/warnings."
10368 (interactive)
10369 (unless (js2-have-errors-p)
10370 (message "No errors")
10371 (return-from js2-display-error-list))
10372 (labels ((annotate-list
10373 (lst type)
10374 "Add diagnostic TYPE and line number to errs list"
10375 (mapcar (lambda (err)
10376 (list err type (line-number-at-pos (nth 1 err))))
10377 lst)))
10378 (let* ((srcbuf (current-buffer))
10379 (errbuf (get-buffer-create "*js-lint*"))
10380 (errors (annotate-list
10381 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10382 'js2-error)) ; must be a valid face name
10383 (warnings (annotate-list
10384 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10385 'js2-warning)) ; must be a valid face name
10386 (all-errs (sort (append errors warnings)
10387 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10388 (with-current-buffer errbuf
10389 (let ((inhibit-read-only t))
10390 (erase-buffer)
10391 (dolist (err all-errs)
10392 (destructuring-bind ((msg-key beg _end &rest) type line) err
10393 (insert-text-button
10394 (format "line %d: %s" line (js2-get-msg msg-key))
10395 'face type
10396 'follow-link "\C-m"
10397 'action 'js2-error-buffer-jump
10398 'js2-msg (js2-get-msg msg-key)
10399 'js2-pos beg)
10400 (insert "\n"))))
10401 (js2-error-buffer-mode)
10402 (setq js2-source-buffer srcbuf)
10403 (pop-to-buffer errbuf)
10404 (goto-char (point-min))
10405 (unless (eobp)
10406 (js2-error-buffer-view))))))
10407
10408 (defvar js2-error-buffer-mode-map
10409 (let ((map (make-sparse-keymap)))
10410 (define-key map "n" #'js2-error-buffer-next)
10411 (define-key map "p" #'js2-error-buffer-prev)
10412 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10413 (define-key map "o" #'js2-error-buffer-view)
10414 (define-key map "q" #'js2-error-buffer-quit)
10415 map)
10416 "Keymap used for js2 diagnostics buffers.")
10417
10418 (defun js2-error-buffer-mode ()
10419 "Major mode for js2 diagnostics buffers.
10420 Selecting an error will jump it to the corresponding source-buffer error.
10421 \\{js2-error-buffer-mode-map}"
10422 (interactive)
10423 (setq major-mode 'js2-error-buffer-mode
10424 mode-name "JS Lint Diagnostics")
10425 (use-local-map js2-error-buffer-mode-map)
10426 (setq truncate-lines t)
10427 (set-buffer-modified-p nil)
10428 (setq buffer-read-only t)
10429 (run-hooks 'js2-error-buffer-mode-hook))
10430
10431 (defun js2-error-buffer-next ()
10432 "Move to next error and view it."
10433 (interactive)
10434 (when (zerop (forward-line 1))
10435 (js2-error-buffer-view)))
10436
10437 (defun js2-error-buffer-prev ()
10438 "Move to previous error and view it."
10439 (interactive)
10440 (when (zerop (forward-line -1))
10441 (js2-error-buffer-view)))
10442
10443 (defun js2-error-buffer-quit ()
10444 "Kill the current buffer."
10445 (interactive)
10446 (kill-buffer))
10447
10448 (defun js2-error-buffer-jump (&rest ignored)
10449 "Jump cursor to current error in source buffer."
10450 (interactive)
10451 (when (js2-error-buffer-view)
10452 (pop-to-buffer js2-source-buffer)))
10453
10454 (defun js2-error-buffer-view ()
10455 "Scroll source buffer to show error at current line."
10456 (interactive)
10457 (cond
10458 ((not (eq major-mode 'js2-error-buffer-mode))
10459 (message "Not in a js2 errors buffer"))
10460 ((not (buffer-live-p js2-source-buffer))
10461 (message "Source buffer has been killed"))
10462 ((not (wholenump (get-text-property (point) 'js2-pos)))
10463 (message "There does not seem to be an error here"))
10464 (t
10465 (let ((pos (get-text-property (point) 'js2-pos))
10466 (msg (get-text-property (point) 'js2-msg)))
10467 (save-selected-window
10468 (pop-to-buffer js2-source-buffer)
10469 (goto-char pos)
10470 (message msg))))))
10471
10472 ;;;###autoload
10473 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10474 ;; FIXME: Should derive from js-mode.
10475 "Major mode for editing JavaScript code."
10476 ;; Used by comment-region; don't change it.
10477 (set (make-local-variable 'comment-start) "//")
10478 (set (make-local-variable 'comment-end) "")
10479 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
10480 (set (make-local-variable 'max-lisp-eval-depth)
10481 (max max-lisp-eval-depth 3000))
10482 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10483 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10484 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10485 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10486 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10487 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10488 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10489 ;; for characters inside regexp literals.
10490 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10491 ;; this is necessary to make `show-paren-function' work properly
10492 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10493 ;; needed for M-x rgrep, among other things
10494 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10495
10496 (set (make-local-variable 'electric-indent-chars)
10497 (append "{}()[]:;,*." electric-indent-chars))
10498 (set (make-local-variable 'electric-layout-rules)
10499 '((?\; . after) (?\{ . after) (?\} . before)))
10500
10501 ;; some variables needed by cc-engine for paragraph-fill, etc.
10502 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10503 c-comment-start-regexp "/[*/]\\|\\s|"
10504 c-line-comment-starter "//"
10505 c-paragraph-start js2-paragraph-start
10506 c-paragraph-separate "$"
10507 c-syntactic-ws-start js2-syntactic-ws-start
10508 c-syntactic-ws-end js2-syntactic-ws-end
10509 c-syntactic-eol js2-syntactic-eol)
10510
10511 (let ((c-buffer-is-cc-mode t))
10512 ;; Copied from `js-mode'. Also see Bug#6071.
10513 (make-local-variable 'paragraph-start)
10514 (make-local-variable 'paragraph-separate)
10515 (make-local-variable 'paragraph-ignore-fill-prefix)
10516 (make-local-variable 'adaptive-fill-mode)
10517 (make-local-variable 'adaptive-fill-regexp)
10518 (c-setup-paragraph-variables))
10519
10520 (setq font-lock-defaults '(nil t))
10521
10522 ;; Experiment: make reparse-delay longer for longer files.
10523 (when (plusp js2-dynamic-idle-timer-adjust)
10524 (setq js2-idle-timer-delay
10525 (* js2-idle-timer-delay
10526 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10527
10528 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10529 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10530 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10531 (setq next-error-function #'js2-next-error)
10532 (imenu-add-to-menubar (concat "IM-" mode-name))
10533 (add-to-invisibility-spec '(js2-outline . t))
10534 (set (make-local-variable 'line-move-ignore-invisible) t)
10535 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10536
10537 (setq js2-mode-functions-hidden nil
10538 js2-mode-comments-hidden nil
10539 js2-mode-buffer-dirty-p t
10540 js2-mode-parsing nil)
10541
10542 (js2-set-default-externs)
10543
10544 (when js2-include-jslint-globals
10545 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10546
10547 (run-hooks 'js2-init-hook)
10548
10549 (js2-reparse))
10550
10551 (defun js2-mode-exit ()
10552 "Exit `js2-mode' and clean up."
10553 (interactive)
10554 (when js2-mode-node-overlay
10555 (delete-overlay js2-mode-node-overlay)
10556 (setq js2-mode-node-overlay nil))
10557 (js2-remove-overlays)
10558 (setq js2-mode-ast nil)
10559 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10560 (remove-from-invisibility-spec '(js2-outline . t))
10561 (js2-mode-show-all)
10562 (with-silent-modifications
10563 (js2-clear-face (point-min) (point-max))))
10564
10565 (defun js2-mode-reset-timer ()
10566 "Cancel any existing parse timer and schedule a new one."
10567 (if js2-mode-parse-timer
10568 (cancel-timer js2-mode-parse-timer))
10569 (setq js2-mode-parsing nil)
10570 (let ((timer (timer-create)))
10571 (setq js2-mode-parse-timer timer)
10572 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10573 (timer-set-idle-time timer js2-idle-timer-delay)
10574 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10575 (timer-activate-when-idle timer nil)))
10576
10577 (defun js2-mode-idle-reparse (buffer)
10578 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10579 it to be reparsed when the buffer is selected."
10580 (cond ((eq buffer (current-buffer))
10581 (js2-reparse))
10582 ((buffer-live-p buffer)
10583 ;; reparse when the buffer is selected again
10584 (with-current-buffer buffer
10585 (add-hook 'window-configuration-change-hook
10586 #'js2-mode-idle-reparse-inner
10587 nil t)))))
10588
10589 (defun js2-mode-idle-reparse-inner ()
10590 (remove-hook 'window-configuration-change-hook
10591 #'js2-mode-idle-reparse-inner
10592 t)
10593 (js2-reparse))
10594
10595 (defun js2-mode-edit (_beg _end _len)
10596 "Schedule a new parse after buffer is edited.
10597 Buffer edit spans from BEG to END and is of length LEN."
10598 (setq js2-mode-buffer-dirty-p t)
10599 (js2-mode-hide-overlay)
10600 (js2-mode-reset-timer))
10601
10602 (defun js2-minor-mode-edit (_beg _end _len)
10603 "Callback for buffer edits in `js2-mode'.
10604 Schedules a new parse after buffer is edited.
10605 Buffer edit spans from BEG to END and is of length LEN."
10606 (setq js2-mode-buffer-dirty-p t)
10607 (js2-mode-hide-overlay)
10608 (js2-mode-reset-timer))
10609
10610 (defun js2-reparse (&optional force)
10611 "Re-parse current buffer after user finishes some data entry.
10612 If we get any user input while parsing, including cursor motion,
10613 we discard the parse and reschedule it. If FORCE is nil, then the
10614 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10615 (let (time
10616 interrupted-p
10617 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10618 (unless js2-mode-parsing
10619 (setq js2-mode-parsing t)
10620 (unwind-protect
10621 (when (or js2-mode-buffer-dirty-p force)
10622 (js2-remove-overlays)
10623 (with-silent-modifications
10624 (setq js2-mode-buffer-dirty-p nil
10625 js2-mode-fontifications nil
10626 js2-mode-deferred-properties nil)
10627 (if js2-mode-verbose-parse-p
10628 (message "parsing..."))
10629 (setq time
10630 (js2-time
10631 (setq interrupted-p
10632 (catch 'interrupted
10633 (js2-parse)
10634 ;; if parsing is interrupted, comments and regex
10635 ;; literals stay ignored by `parse-partial-sexp'
10636 (remove-text-properties (point-min) (point-max)
10637 '(syntax-table))
10638 (js2-mode-apply-deferred-properties)
10639 (js2-mode-remove-suppressed-warnings)
10640 (js2-mode-show-warnings)
10641 (js2-mode-show-errors)
10642 (if (>= js2-highlight-level 1)
10643 (js2-highlight-jsdoc js2-mode-ast))
10644 nil))))
10645 (if interrupted-p
10646 (progn
10647 ;; unfinished parse => try again
10648 (setq js2-mode-buffer-dirty-p t)
10649 (js2-mode-reset-timer))
10650 (if js2-mode-verbose-parse-p
10651 (message "Parse time: %s" time)))))
10652 (setq js2-mode-parsing nil)
10653 (unless interrupted-p
10654 (setq js2-mode-parse-timer nil))))))
10655
10656 (defun js2-mode-show-node (event)
10657 "Debugging aid: highlight selected AST node on mouse click."
10658 (interactive "e")
10659 (mouse-set-point event)
10660 (setq deactivate-mark t)
10661 (when js2-mode-show-overlay
10662 (let ((node (js2-node-at-point))
10663 beg end)
10664 (if (null node)
10665 (message "No node found at location %s" (point))
10666 (setq beg (js2-node-abs-pos node)
10667 end (+ beg (js2-node-len node)))
10668 (if js2-mode-node-overlay
10669 (move-overlay js2-mode-node-overlay beg end)
10670 (setq js2-mode-node-overlay (make-overlay beg end))
10671 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10672 (with-silent-modifications
10673 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10674 (message "%s, parent: %s"
10675 (js2-node-short-name node)
10676 (if (js2-node-parent node)
10677 (js2-node-short-name (js2-node-parent node))
10678 "nil"))))))
10679
10680 (defun js2-mode-hide-overlay (&optional _p1 p2)
10681 "Remove the debugging overlay when the point moves.
10682 P1 and P2 are the old and new values of point, respectively."
10683 (when js2-mode-node-overlay
10684 (let ((beg (overlay-start js2-mode-node-overlay))
10685 (end (overlay-end js2-mode-node-overlay)))
10686 ;; Sometimes we're called spuriously.
10687 (unless (and p2
10688 (>= p2 beg)
10689 (<= p2 end))
10690 (with-silent-modifications
10691 (remove-text-properties beg end '(point-left nil)))
10692 (delete-overlay js2-mode-node-overlay)
10693 (setq js2-mode-node-overlay nil)))))
10694
10695 (defun js2-mode-reset ()
10696 "Debugging helper: reset everything."
10697 (interactive)
10698 (js2-mode-exit)
10699 (js2-mode))
10700
10701 (defun js2-mode-show-warn-or-err (e face)
10702 "Highlight a warning or error E with FACE.
10703 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10704 The last element is optional. When present, use instead of FACE."
10705 (let* ((key (first e))
10706 (beg (second e))
10707 (end (+ beg (third e)))
10708 ;; Don't inadvertently go out of bounds.
10709 (beg (max (point-min) (min beg (point-max))))
10710 (end (max (point-min) (min end (point-max))))
10711 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10712 (ovl (make-overlay beg end)))
10713 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10714 (overlay-put ovl 'js2-error t)
10715 (put-text-property beg end 'help-echo (js2-get-msg key))
10716 (put-text-property beg end 'point-entered #'js2-echo-error)))
10717
10718 (defun js2-remove-overlays ()
10719 "Remove overlays from buffer that have a `js2-error' property."
10720 (let ((beg (point-min))
10721 (end (point-max)))
10722 (save-excursion
10723 (dolist (o (overlays-in beg end))
10724 (when (overlay-get o 'js2-error)
10725 (delete-overlay o))))))
10726
10727 (defun js2-error-at-point (&optional pos)
10728 "Return non-nil if there's an error overlay at POS.
10729 Defaults to point."
10730 (loop with pos = (or pos (point))
10731 for o in (overlays-at pos)
10732 thereis (overlay-get o 'js2-error)))
10733
10734 (defun js2-mode-apply-deferred-properties ()
10735 "Apply fontifications and other text properties recorded during parsing."
10736 (when (plusp js2-highlight-level)
10737 ;; We defer clearing faces as long as possible to eliminate flashing.
10738 (js2-clear-face (point-min) (point-max))
10739 ;; Have to reverse the recorded fontifications list so that errors
10740 ;; and warnings overwrite the normal fontifications.
10741 (dolist (f (nreverse js2-mode-fontifications))
10742 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10743 (setq js2-mode-fontifications nil))
10744 (dolist (p js2-mode-deferred-properties)
10745 (apply #'put-text-property p))
10746 (setq js2-mode-deferred-properties nil))
10747
10748 (defun js2-mode-show-errors ()
10749 "Highlight syntax errors."
10750 (when js2-mode-show-parse-errors
10751 (dolist (e (js2-ast-root-errors js2-mode-ast))
10752 (js2-mode-show-warn-or-err e 'js2-error))))
10753
10754 (defun js2-mode-remove-suppressed-warnings ()
10755 "Take suppressed warnings out of the AST warnings list.
10756 This ensures that the counts and `next-error' are correct."
10757 (setf (js2-ast-root-warnings js2-mode-ast)
10758 (js2-delete-if
10759 (lambda (e)
10760 (let ((key (caar e)))
10761 (or
10762 (and (not js2-strict-trailing-comma-warning)
10763 (string-match "trailing\\.comma" key))
10764 (and (not js2-strict-cond-assign-warning)
10765 (string= key "msg.equal.as.assign"))
10766 (and js2-missing-semi-one-line-override
10767 (string= key "msg.missing.semi")
10768 (let* ((beg (second e))
10769 (node (js2-node-at-point beg))
10770 (fn (js2-mode-find-parent-fn node))
10771 (body (and fn (js2-function-node-body fn)))
10772 (lc (and body (js2-node-abs-pos body)))
10773 (rc (and lc (+ lc (js2-node-len body)))))
10774 (and fn
10775 (or (null body)
10776 (save-excursion
10777 (goto-char beg)
10778 (and (js2-same-line lc)
10779 (js2-same-line rc))))))))))
10780 (js2-ast-root-warnings js2-mode-ast))))
10781
10782 (defun js2-mode-show-warnings ()
10783 "Highlight strict-mode warnings."
10784 (when js2-mode-show-strict-warnings
10785 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10786 (js2-mode-show-warn-or-err e 'js2-warning))))
10787
10788 (defun js2-echo-error (_old-point new-point)
10789 "Called by point-motion hooks."
10790 (let ((msg (get-text-property new-point 'help-echo)))
10791 (when (and (stringp msg)
10792 (not (active-minibuffer-window))
10793 (not (current-message)))
10794 (message msg))))
10795
10796 (defalias 'js2-echo-help #'js2-echo-error)
10797
10798 (defun js2-line-break (&optional _soft)
10799 "Break line at point and indent, continuing comment if within one.
10800 If inside a string, and `js2-concat-multiline-strings' is not
10801 nil, turn it into concatenation."
10802 (interactive)
10803 (let ((parse-status (syntax-ppss)))
10804 (cond
10805 ;; Check if we're inside a string.
10806 ((nth 3 parse-status)
10807 (if js2-concat-multiline-strings
10808 (js2-mode-split-string parse-status)
10809 (insert "\n")))
10810 ;; Check if inside a block comment.
10811 ((nth 4 parse-status)
10812 (js2-mode-extend-comment (nth 8 parse-status)))
10813 (t
10814 (newline-and-indent)))))
10815
10816 (defun js2-mode-split-string (parse-status)
10817 "Turn a newline in mid-string into a string concatenation.
10818 PARSE-STATUS is as documented in `parse-partial-sexp'."
10819 (let* ((quote-char (nth 3 parse-status))
10820 (at-eol (eq js2-concat-multiline-strings 'eol)))
10821 (insert quote-char)
10822 (insert (if at-eol " +\n" "\n"))
10823 (unless at-eol
10824 (insert "+ "))
10825 (js2-indent-line)
10826 (insert quote-char)
10827 (when (eolp)
10828 (insert quote-char)
10829 (backward-char 1))))
10830
10831 (defun js2-mode-extend-comment (start-pos)
10832 "Indent the line and, when inside a comment block, add comment prefix."
10833 (let (star single col first-line needs-close)
10834 (save-excursion
10835 (back-to-indentation)
10836 (when (< (point) start-pos)
10837 (goto-char start-pos))
10838 (cond
10839 ((looking-at "\\*[^/]")
10840 (setq star t
10841 col (current-column)))
10842 ((looking-at "/\\*")
10843 (setq star t
10844 first-line t
10845 col (1+ (current-column))))
10846 ((looking-at "//")
10847 (setq single t
10848 col (current-column)))))
10849 ;; Heuristic for whether we need to close the comment:
10850 ;; if we've got a parse error here, assume it's an unterminated
10851 ;; comment.
10852 (setq needs-close
10853 (or
10854 (eq (get-text-property (1- (point)) 'point-entered)
10855 'js2-echo-error)
10856 ;; The heuristic above doesn't work well when we're
10857 ;; creating a comment and there's another one downstream,
10858 ;; as our parser thinks this one ends at the end of the
10859 ;; next one. (You can have a /* inside a js block comment.)
10860 ;; So just close it if the next non-ws char isn't a *.
10861 (and first-line
10862 (eolp)
10863 (save-excursion
10864 (skip-chars-forward " \t\r\n")
10865 (not (eq (char-after) ?*))))))
10866 (delete-horizontal-space)
10867 (insert "\n")
10868 (cond
10869 (star
10870 (indent-to col)
10871 (insert "* ")
10872 (if (and first-line needs-close)
10873 (save-excursion
10874 (insert "\n")
10875 (indent-to col)
10876 (insert "*/"))))
10877 ((and single
10878 (save-excursion
10879 (and (zerop (forward-line 1))
10880 (looking-at "\\s-*//"))))
10881 (indent-to col)
10882 (insert "// ")))
10883 ;; Don't need to extend the comment after all.
10884 (js2-indent-line)))
10885
10886 (defun js2-beginning-of-line ()
10887 "Toggle point between bol and first non-whitespace char in line.
10888 Also moves past comment delimiters when inside comments."
10889 (interactive)
10890 (let (node)
10891 (cond
10892 ((bolp)
10893 (back-to-indentation))
10894 ((looking-at "//")
10895 (skip-chars-forward "/ \t"))
10896 ((and (eq (char-after) ?*)
10897 (setq node (js2-comment-at-point))
10898 (memq (js2-comment-node-format node) '(jsdoc block))
10899 (save-excursion
10900 (skip-chars-backward " \t")
10901 (bolp)))
10902 (skip-chars-forward "\* \t"))
10903 (t
10904 (goto-char (point-at-bol))))))
10905
10906 (defun js2-end-of-line ()
10907 "Toggle point between eol and last non-whitespace char in line."
10908 (interactive)
10909 (if (eolp)
10910 (skip-chars-backward " \t")
10911 (goto-char (point-at-eol))))
10912
10913 (defun js2-mode-wait-for-parse (callback)
10914 "Invoke CALLBACK when parsing is finished.
10915 If parsing is already finished, calls CALLBACK immediately."
10916 (if (not js2-mode-buffer-dirty-p)
10917 (funcall callback)
10918 (push callback js2-mode-pending-parse-callbacks)
10919 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10920
10921 (defun js2-mode-parse-finished ()
10922 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10923 ;; We can't let errors propagate up, since it prevents the
10924 ;; `js2-parse' method from completing normally and returning
10925 ;; the ast, which makes things mysteriously not work right.
10926 (unwind-protect
10927 (dolist (cb js2-mode-pending-parse-callbacks)
10928 (condition-case err
10929 (funcall cb)
10930 (error (message "%s" err))))
10931 (setq js2-mode-pending-parse-callbacks nil)))
10932
10933 (defun js2-mode-flag-region (from to flag)
10934 "Hide or show text from FROM to TO, according to FLAG.
10935 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10936 Returns the created overlay if FLAG is non-nil."
10937 (remove-overlays from to 'invisible 'js2-outline)
10938 (when flag
10939 (let ((o (make-overlay from to)))
10940 (overlay-put o 'invisible 'js2-outline)
10941 (overlay-put o 'isearch-open-invisible
10942 'js2-isearch-open-invisible)
10943 o)))
10944
10945 ;; Function to be set as an outline-isearch-open-invisible' property
10946 ;; to the overlay that makes the outline invisible (see
10947 ;; `js2-mode-flag-region').
10948 (defun js2-isearch-open-invisible (_overlay)
10949 ;; We rely on the fact that isearch places point on the matched text.
10950 (js2-mode-show-element))
10951
10952 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10953 "Return cons cell of bounds of folding overlay at POS.
10954 Returns nil if not found."
10955 (let ((overlays (overlays-at (or pos (point))))
10956 o)
10957 (while (and overlays
10958 (not o))
10959 (if (overlay-get (car overlays) 'invisible)
10960 (setq o (car overlays))
10961 (setq overlays (cdr overlays))))
10962 (if o
10963 (cons (overlay-start o) (overlay-end o)))))
10964
10965 (defun js2-mode-function-at-point (&optional pos)
10966 "Return the innermost function node enclosing current point.
10967 Returns nil if point is not in a function."
10968 (let ((node (js2-node-at-point pos)))
10969 (while (and node (not (js2-function-node-p node)))
10970 (setq node (js2-node-parent node)))
10971 (if (js2-function-node-p node)
10972 node)))
10973
10974 (defun js2-mode-toggle-element ()
10975 "Hide or show the foldable element at the point."
10976 (interactive)
10977 (let (comment fn pos)
10978 (save-excursion
10979 (cond
10980 ;; /* ... */ comment?
10981 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10982 (if (js2-mode-invisible-overlay-bounds
10983 (setq pos (+ 3 (js2-node-abs-pos comment))))
10984 (progn
10985 (goto-char pos)
10986 (js2-mode-show-element))
10987 (js2-mode-hide-element)))
10988 ;; //-comment?
10989 ((save-excursion
10990 (back-to-indentation)
10991 (looking-at js2-mode-//-comment-re))
10992 (js2-mode-toggle-//-comment))
10993 ;; function?
10994 ((setq fn (js2-mode-function-at-point))
10995 (setq pos (and (js2-function-node-body fn)
10996 (js2-node-abs-pos (js2-function-node-body fn))))
10997 (goto-char (1+ pos))
10998 (if (js2-mode-invisible-overlay-bounds)
10999 (js2-mode-show-element)
11000 (js2-mode-hide-element)))
11001 (t
11002 (message "Nothing at point to hide or show"))))))
11003
11004 (defun js2-mode-hide-element ()
11005 "Fold/hide contents of a block, showing ellipses.
11006 Show the hidden text with \\[js2-mode-show-element]."
11007 (interactive)
11008 (if js2-mode-buffer-dirty-p
11009 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11010 (let (node body beg end)
11011 (cond
11012 ((js2-mode-invisible-overlay-bounds)
11013 (message "already hidden"))
11014 (t
11015 (setq node (js2-node-at-point))
11016 (cond
11017 ((js2-block-comment-p node)
11018 (js2-mode-hide-comment node))
11019 (t
11020 (while (and node (not (js2-function-node-p node)))
11021 (setq node (js2-node-parent node)))
11022 (if (and node
11023 (setq body (js2-function-node-body node)))
11024 (progn
11025 (setq beg (js2-node-abs-pos body)
11026 end (+ beg (js2-node-len body)))
11027 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11028 (message "No collapsable element found at point"))))))))
11029
11030 (defun js2-mode-show-element ()
11031 "Show the hidden element at current point."
11032 (interactive)
11033 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11034 (if bounds
11035 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11036 (message "Nothing to un-hide"))))
11037
11038 (defun js2-mode-show-all ()
11039 "Show all of the text in the buffer."
11040 (interactive)
11041 (js2-mode-flag-region (point-min) (point-max) nil))
11042
11043 (defun js2-mode-toggle-hide-functions ()
11044 (interactive)
11045 (if js2-mode-functions-hidden
11046 (js2-mode-show-functions)
11047 (js2-mode-hide-functions)))
11048
11049 (defun js2-mode-hide-functions ()
11050 "Hides all non-nested function bodies in the buffer.
11051 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11052 to open an individual entry."
11053 (interactive)
11054 (if js2-mode-buffer-dirty-p
11055 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11056 (if (null js2-mode-ast)
11057 (message "Oops - parsing failed")
11058 (setq js2-mode-functions-hidden t)
11059 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11060
11061 (defun js2-mode-function-hider (n endp)
11062 (when (not endp)
11063 (let ((tt (js2-node-type n))
11064 body beg end)
11065 (cond
11066 ((and (= tt js2-FUNCTION)
11067 (setq body (js2-function-node-body n)))
11068 (setq beg (js2-node-abs-pos body)
11069 end (+ beg (js2-node-len body)))
11070 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11071 nil) ; don't process children of function
11072 (t
11073 t))))) ; keep processing other AST nodes
11074
11075 (defun js2-mode-show-functions ()
11076 "Un-hide any folded function bodies in the buffer."
11077 (interactive)
11078 (setq js2-mode-functions-hidden nil)
11079 (save-excursion
11080 (goto-char (point-min))
11081 (while (/= (goto-char (next-overlay-change (point)))
11082 (point-max))
11083 (dolist (o (overlays-at (point)))
11084 (when (and (overlay-get o 'invisible)
11085 (not (overlay-get o 'comment)))
11086 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11087
11088 (defun js2-mode-hide-comment (n)
11089 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11090 3 ; /**
11091 2)) ; /*
11092 (beg (+ (js2-node-abs-pos n) head))
11093 (end (- (+ beg (js2-node-len n)) head 2))
11094 (o (js2-mode-flag-region beg end 'hide)))
11095 (overlay-put o 'comment t)))
11096
11097 (defun js2-mode-toggle-hide-comments ()
11098 "Folds all block comments 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-comments-hidden
11103 (js2-mode-show-comments)
11104 (js2-mode-hide-comments)))
11105
11106 (defun js2-mode-hide-comments ()
11107 (interactive)
11108 (if js2-mode-buffer-dirty-p
11109 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11110 (if (null js2-mode-ast)
11111 (message "Oops - parsing failed")
11112 (setq js2-mode-comments-hidden t)
11113 (dolist (n (js2-ast-root-comments js2-mode-ast))
11114 (when (js2-block-comment-p n)
11115 (js2-mode-hide-comment n)))
11116 (js2-mode-hide-//-comments)))
11117
11118 (defun js2-mode-extend-//-comment (direction)
11119 "Find start or end of a block of similar //-comment lines.
11120 DIRECTION is -1 to look back, 1 to look forward.
11121 INDENT is the indentation level to match.
11122 Returns the end-of-line position of the furthest adjacent
11123 //-comment line with the same indentation as the current line.
11124 If there is no such matching line, returns current end of line."
11125 (let ((pos (point-at-eol))
11126 (indent (current-indentation)))
11127 (save-excursion
11128 (while (and (zerop (forward-line direction))
11129 (looking-at js2-mode-//-comment-re)
11130 (eq indent (length (match-string 1))))
11131 (setq pos (point-at-eol)))
11132 pos)))
11133
11134 (defun js2-mode-hide-//-comments ()
11135 "Fold adjacent 1-line comments, showing only snippet of first one."
11136 (let (beg end)
11137 (save-excursion
11138 (goto-char (point-min))
11139 (while (re-search-forward js2-mode-//-comment-re nil t)
11140 (setq beg (point)
11141 end (js2-mode-extend-//-comment 1))
11142 (unless (eq beg end)
11143 (overlay-put (js2-mode-flag-region beg end 'hide)
11144 'comment t))
11145 (goto-char end)
11146 (forward-char 1)))))
11147
11148 (defun js2-mode-toggle-//-comment ()
11149 "Fold or un-fold any multi-line //-comment at point.
11150 Caller should have determined that this line starts with a //-comment."
11151 (let* ((beg (point-at-eol))
11152 (end beg))
11153 (save-excursion
11154 (goto-char end)
11155 (if (js2-mode-invisible-overlay-bounds)
11156 (js2-mode-show-element)
11157 ;; else hide the comment
11158 (setq beg (js2-mode-extend-//-comment -1)
11159 end (js2-mode-extend-//-comment 1))
11160 (unless (eq beg end)
11161 (overlay-put (js2-mode-flag-region beg end 'hide)
11162 'comment t))))))
11163
11164 (defun js2-mode-show-comments ()
11165 "Un-hide any hidden comments, leaving other hidden elements alone."
11166 (interactive)
11167 (setq js2-mode-comments-hidden nil)
11168 (save-excursion
11169 (goto-char (point-min))
11170 (while (/= (goto-char (next-overlay-change (point)))
11171 (point-max))
11172 (dolist (o (overlays-at (point)))
11173 (when (overlay-get o 'comment)
11174 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11175
11176 (defun js2-mode-display-warnings-and-errors ()
11177 "Turn on display of warnings and errors."
11178 (interactive)
11179 (setq js2-mode-show-parse-errors t
11180 js2-mode-show-strict-warnings t)
11181 (js2-reparse 'force))
11182
11183 (defun js2-mode-hide-warnings-and-errors ()
11184 "Turn off display of warnings and errors."
11185 (interactive)
11186 (setq js2-mode-show-parse-errors nil
11187 js2-mode-show-strict-warnings nil)
11188 (js2-reparse 'force))
11189
11190 (defun js2-mode-toggle-warnings-and-errors ()
11191 "Toggle the display of warnings and errors.
11192 Some users don't like having warnings/errors reported while they type."
11193 (interactive)
11194 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11195 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11196 (if (called-interactively-p 'any)
11197 (message "warnings and errors %s"
11198 (if js2-mode-show-parse-errors
11199 "enabled"
11200 "disabled")))
11201 (js2-reparse 'force))
11202
11203 (defun js2-mode-customize ()
11204 (interactive)
11205 (customize-group 'js2-mode))
11206
11207 (defun js2-mode-forward-sexp (&optional arg)
11208 "Move forward across one statement or balanced expression.
11209 With ARG, do it that many times. Negative arg -N means
11210 move backward across N balanced expressions."
11211 (interactive "p")
11212 (setq arg (or arg 1))
11213 (save-restriction
11214 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11215 (js2-reparse)
11216 (let (forward-sexp-function
11217 node (start (point)) pos lp rp child)
11218 (cond
11219 ;; backward-sexp
11220 ;; could probably make this better for some cases:
11221 ;; - if in statement block (e.g. function body), go to parent
11222 ;; - infix exprs like (foo in bar) - maybe go to beginning
11223 ;; of infix expr if in the right-side expression?
11224 ((and arg (minusp arg))
11225 (dotimes (_ (- arg))
11226 (js2-backward-sws)
11227 (forward-char -1) ; Enter the node we backed up to.
11228 (when (setq node (js2-node-at-point (point) t))
11229 (setq pos (js2-node-abs-pos node))
11230 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11231 (setq lp (car parens)
11232 rp (cdr parens)))
11233 (when (and lp (> start lp))
11234 (if (and rp (<= start rp))
11235 ;; Between parens, check if there's a child node we can jump.
11236 (when (setq child (js2-node-closest-child node (point) lp t))
11237 (setq pos (js2-node-abs-pos child)))
11238 ;; Before both parens.
11239 (setq pos lp)))
11240 (let ((state (parse-partial-sexp start pos)))
11241 (goto-char (if (not (zerop (car state)))
11242 ;; Stumble at the unbalanced paren if < 0, or
11243 ;; jump a bit further if > 0.
11244 (scan-sexps start -1)
11245 pos))))
11246 (unless pos (goto-char (point-min)))))
11247 (t
11248 ;; forward-sexp
11249 (dotimes (_ arg)
11250 (js2-forward-sws)
11251 (when (setq node (js2-node-at-point (point) t))
11252 (setq pos (js2-node-abs-pos node))
11253 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11254 (setq lp (car parens)
11255 rp (cdr parens)))
11256 (or
11257 (when (and rp (<= start rp))
11258 (if (> start lp)
11259 (when (setq child (js2-node-closest-child node (point) rp))
11260 (setq pos (js2-node-abs-end child)))
11261 (setq pos (1+ rp))))
11262 ;; No parens or child nodes, looks for the end of the curren node.
11263 (incf pos (js2-node-len
11264 (if (js2-expr-stmt-node-p (js2-node-parent node))
11265 ;; Stop after the semicolon.
11266 (js2-node-parent node)
11267 node))))
11268 (let ((state (save-excursion (parse-partial-sexp start pos))))
11269 (goto-char (if (not (zerop (car state)))
11270 (scan-sexps start 1)
11271 pos))))
11272 (unless pos (goto-char (point-max)))))))))
11273
11274 (defun js2-mode-forward-sexp-parens (node abs-pos)
11275 "Return a cons cell with positions of main parens in NODE."
11276 (cond
11277 ((or (js2-array-node-p node)
11278 (js2-object-node-p node)
11279 (js2-comp-node-p node)
11280 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11281 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11282 ((js2-paren-expr-node-p node)
11283 (let ((lp (js2-node-lp node))
11284 (rp (js2-node-rp node)))
11285 (cons (when lp (+ abs-pos lp))
11286 (when rp (+ abs-pos rp)))))))
11287
11288 (defun js2-node-closest-child (parent point limit &optional before)
11289 (let* ((parent-pos (js2-node-abs-pos parent))
11290 (rpoint (- point parent-pos))
11291 (rlimit (- limit parent-pos))
11292 (min (min rpoint rlimit))
11293 (max (max rpoint rlimit))
11294 found)
11295 (catch 'done
11296 (js2-visit-ast
11297 parent
11298 (lambda (node _end-p)
11299 (if (eq node parent)
11300 t
11301 (let ((pos (js2-node-pos node)) ;; Both relative values.
11302 (end (+ (js2-node-pos node) (js2-node-len node))))
11303 (when (and (>= pos min) (<= end max)
11304 (if before (< pos rpoint) (> end rpoint)))
11305 (setq found node))
11306 (when (> end rpoint)
11307 (throw 'done nil)))
11308 nil))))
11309 found))
11310
11311 (defun js2-errors ()
11312 "Return a list of errors found."
11313 (and js2-mode-ast
11314 (js2-ast-root-errors js2-mode-ast)))
11315
11316 (defun js2-warnings ()
11317 "Return a list of warnings found."
11318 (and js2-mode-ast
11319 (js2-ast-root-warnings js2-mode-ast)))
11320
11321 (defun js2-have-errors-p ()
11322 "Return non-nil if any parse errors or warnings were found."
11323 (or (js2-errors) (js2-warnings)))
11324
11325 (defun js2-errors-and-warnings ()
11326 "Return a copy of the concatenated errors and warnings lists.
11327 They are appended: first the errors, then the warnings.
11328 Entries are of the form (MSG BEG END)."
11329 (when js2-mode-ast
11330 (append (js2-ast-root-errors js2-mode-ast)
11331 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11332
11333 (defun js2-next-error (&optional arg reset)
11334 "Move to next parse error.
11335 Typically invoked via \\[next-error].
11336 ARG is the number of errors, forward or backward, to move.
11337 RESET means start over from the beginning."
11338 (interactive "p")
11339 (if (not (or (js2-errors) (js2-warnings)))
11340 (message "No errors")
11341 (when reset
11342 (goto-char (point-min)))
11343 (let* ((errs (js2-errors-and-warnings))
11344 (continue t)
11345 (start (point))
11346 (count (or arg 1))
11347 (backward (minusp count))
11348 (sorter (if backward '> '<))
11349 (stopper (if backward '< '>))
11350 (count (abs count))
11351 all-errs err)
11352 ;; Sort by start position.
11353 (setq errs (sort errs (lambda (e1 e2)
11354 (funcall sorter (second e1) (second e2))))
11355 all-errs errs)
11356 ;; Find nth error with pos > start.
11357 (while (and errs continue)
11358 (when (funcall stopper (cadar errs) start)
11359 (setq err (car errs))
11360 (if (zerop (decf count))
11361 (setq continue nil)))
11362 (setq errs (cdr errs)))
11363 ;; Clear for `js2-echo-error'.
11364 (message nil)
11365 (if err
11366 (goto-char (second err))
11367 ;; Wrap around to first error.
11368 (goto-char (second (car all-errs)))
11369 ;; If we were already on it, echo msg again.
11370 (if (= (point) start)
11371 (js2-echo-error (point) (point)))))))
11372
11373 (defun js2-down-mouse-3 ()
11374 "Make right-click move the point to the click location.
11375 This makes right-click context menu operations a bit more intuitive.
11376 The point will not move if the region is active, however, to avoid
11377 destroying the region selection."
11378 (interactive)
11379 (when (and js2-move-point-on-right-click
11380 (not mark-active))
11381 (let ((e last-input-event))
11382 (ignore-errors
11383 (goto-char (cadadr e))))))
11384
11385 (defun js2-mode-create-imenu-index ()
11386 "Return an alist for `imenu--index-alist'."
11387 ;; This is built up in `js2-parse-record-imenu' during parsing.
11388 (when js2-mode-ast
11389 ;; if we have an ast but no recorder, they're requesting a rescan
11390 (unless js2-imenu-recorder
11391 (js2-reparse 'force))
11392 (prog1
11393 (js2-build-imenu-index)
11394 (setq js2-imenu-recorder nil
11395 js2-imenu-function-map nil))))
11396
11397 (defun js2-mode-find-tag ()
11398 "Replacement for `find-tag-default'.
11399 `find-tag-default' returns a ridiculous answer inside comments."
11400 (let (beg end)
11401 (js2-with-underscore-as-word-syntax
11402 (save-excursion
11403 (if (and (not (looking-at "[[:alnum:]_$]"))
11404 (looking-back "[[:alnum:]_$]"))
11405 (setq beg (progn (forward-word -1) (point))
11406 end (progn (forward-word 1) (point)))
11407 (setq beg (progn (forward-word 1) (point))
11408 end (progn (forward-word -1) (point))))
11409 (replace-regexp-in-string
11410 "[\"']" ""
11411 (buffer-substring-no-properties beg end))))))
11412
11413 (defun js2-mode-forward-sibling ()
11414 "Move to the end of the sibling following point in parent.
11415 Returns non-nil if successful, or nil if there was no following sibling."
11416 (let* ((node (js2-node-at-point))
11417 (parent (js2-mode-find-enclosing-fn node))
11418 sib)
11419 (when (setq sib (js2-node-find-child-after (point) parent))
11420 (goto-char (+ (js2-node-abs-pos sib)
11421 (js2-node-len sib))))))
11422
11423 (defun js2-mode-backward-sibling ()
11424 "Move to the beginning of the sibling node preceding point in parent.
11425 Parent is defined as the enclosing script or function."
11426 (let* ((node (js2-node-at-point))
11427 (parent (js2-mode-find-enclosing-fn node))
11428 sib)
11429 (when (setq sib (js2-node-find-child-before (point) parent))
11430 (goto-char (js2-node-abs-pos sib)))))
11431
11432 (defun js2-beginning-of-defun (&optional arg)
11433 "Go to line on which current function starts, and return t on success.
11434 If we're not in a function or already at the beginning of one, go
11435 to beginning of previous script-level element.
11436 With ARG N, do that N times. If N is negative, move forward."
11437 (setq arg (or arg 1))
11438 (if (plusp arg)
11439 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11440 (when (cond
11441 ((js2-function-node-p parent)
11442 (goto-char (js2-node-abs-pos parent)))
11443 (t
11444 (js2-mode-backward-sibling)))
11445 (if (> arg 1)
11446 (js2-beginning-of-defun (1- arg))
11447 t)))
11448 (when (js2-end-of-defun)
11449 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
11450
11451 (defun js2-end-of-defun ()
11452 "Go to the char after the last position of the current function
11453 or script-level element."
11454 (let* ((node (js2-node-at-point))
11455 (parent (or (and (js2-function-node-p node) node)
11456 (js2-node-parent-script-or-fn node)))
11457 script)
11458 (unless (js2-function-node-p parent)
11459 ;; Use current script-level node, or, if none, the next one.
11460 (setq script (or parent node)
11461 parent (js2-node-find-child-before (point) script))
11462 (when (or (null parent)
11463 (>= (point) (+ (js2-node-abs-pos parent)
11464 (js2-node-len parent))))
11465 (setq parent (js2-node-find-child-after (point) script))))
11466 (when parent
11467 (goto-char (+ (js2-node-abs-pos parent)
11468 (js2-node-len parent))))))
11469
11470 (defun js2-mark-defun (&optional allow-extend)
11471 "Put mark at end of this function, point at beginning.
11472 The function marked is the one that contains point.
11473
11474 Interactively, if this command is repeated,
11475 or (in Transient Mark mode) if the mark is active,
11476 it marks the next defun after the ones already marked."
11477 (interactive "p")
11478 (let (extended)
11479 (when (and allow-extend
11480 (or (and (eq last-command this-command) (mark t))
11481 (and transient-mark-mode mark-active)))
11482 (let ((sib (save-excursion
11483 (goto-char (mark))
11484 (if (js2-mode-forward-sibling)
11485 (point)))))
11486 (if sib
11487 (progn
11488 (set-mark sib)
11489 (setq extended t))
11490 ;; no more siblings - try extending to enclosing node
11491 (goto-char (mark t)))))
11492 (when (not extended)
11493 (let ((node (js2-node-at-point (point) t)) ; skip comments
11494 ast fn stmt parent beg end)
11495 (when (js2-ast-root-p node)
11496 (setq ast node
11497 node (or (js2-node-find-child-after (point) node)
11498 (js2-node-find-child-before (point) node))))
11499 ;; only mark whole buffer if we can't find any children
11500 (if (null node)
11501 (setq node ast))
11502 (if (js2-function-node-p node)
11503 (setq parent node)
11504 (setq fn (js2-mode-find-enclosing-fn node)
11505 stmt (if (or (null fn)
11506 (js2-ast-root-p fn))
11507 (js2-mode-find-first-stmt node))
11508 parent (or stmt fn)))
11509 (setq beg (js2-node-abs-pos parent)
11510 end (+ beg (js2-node-len parent)))
11511 (push-mark beg)
11512 (goto-char end)
11513 (exchange-point-and-mark)))))
11514
11515 (defun js2-narrow-to-defun ()
11516 "Narrow to the function enclosing point."
11517 (interactive)
11518 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11519 (fn (if (js2-script-node-p node)
11520 node
11521 (js2-mode-find-enclosing-fn node)))
11522 (beg (js2-node-abs-pos fn)))
11523 (unless (js2-ast-root-p fn)
11524 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11525
11526 (provide 'js2-mode)
11527
11528 ;;; js2-mode.el ends here