]> code.delx.au - gnu-emacs-elpa/blob - packages/js2-mode/js2-mode.el
Merge commit '3db1ea76a02993663d40e90c58da989212b9e81a' into gnorb-1.0.1
[gnu-emacs-elpa] / packages / 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: 20140114
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
65
66 ;; Notes:
67
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
71
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
76
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
81
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code has outdated information and is mostly
84 ;; unmaintained.
85
86 ;;; Code:
87
88 (eval-when-compile
89 (require 'cl))
90
91 (require 'imenu)
92 (require 'cc-cmds) ; for `c-fill-paragraph'
93
94 (eval-and-compile
95 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
96 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
97
98 (defvar electric-layout-rules)
99
100 ;;; Externs (variables presumed to be defined by the host system)
101
102 (defvar js2-ecma-262-externs
103 (mapcar 'symbol-name
104 '(Array Boolean Date Error EvalError Function Infinity JSON
105 Math NaN Number Object RangeError ReferenceError RegExp
106 String SyntaxError TypeError URIError arguments
107 decodeURI decodeURIComponent encodeURI
108 encodeURIComponent escape eval isFinite isNaN
109 parseFloat parseInt undefined unescape))
110 "Ecma-262 externs. Included in `js2-externs' by default.")
111
112 (defvar js2-browser-externs
113 (mapcar 'symbol-name
114 '(;; DOM level 1
115 Attr CDATASection CharacterData Comment DOMException
116 DOMImplementation Document DocumentFragment
117 DocumentType Element Entity EntityReference
118 ExceptionCode NamedNodeMap Node NodeList Notation
119 ProcessingInstruction Text
120
121 ;; DOM level 2
122 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
123 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
124 HTMLBodyElement HTMLButtonElement HTMLCollection
125 HTMLDListElement HTMLDirectoryElement HTMLDivElement
126 HTMLDocument HTMLElement HTMLFieldSetElement
127 HTMLFontElement HTMLFormElement HTMLFrameElement
128 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
129 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
130 HTMLImageElement HTMLInputElement HTMLIsIndexElement
131 HTMLLIElement HTMLLabelElement HTMLLegendElement
132 HTMLLinkElement HTMLMapElement HTMLMenuElement
133 HTMLMetaElement HTMLModElement HTMLOListElement
134 HTMLObjectElement HTMLOptGroupElement
135 HTMLOptionElement HTMLOptionsCollection
136 HTMLParagraphElement HTMLParamElement HTMLPreElement
137 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
138 HTMLStyleElement HTMLTableCaptionElement
139 HTMLTableCellElement HTMLTableColElement
140 HTMLTableElement HTMLTableRowElement
141 HTMLTableSectionElement HTMLTextAreaElement
142 HTMLTitleElement HTMLUListElement
143
144 ;; DOM level 3
145 DOMConfiguration DOMError DOMException
146 DOMImplementationList DOMImplementationSource
147 DOMLocator DOMStringList NameList TypeInfo
148 UserDataHandler
149
150 ;; Window
151 window alert confirm document java navigator prompt screen
152 self top
153
154 ;; W3C CSS
155 CSSCharsetRule CSSFontFace CSSFontFaceRule
156 CSSImportRule CSSMediaRule CSSPageRule
157 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
158 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
159 CSSValue CSSValueList Counter DOMImplementationCSS
160 DocumentCSS DocumentStyle ElementCSSInlineStyle
161 LinkStyle MediaList RGBColor Rect StyleSheet
162 StyleSheetList ViewCSS
163
164 ;; W3C Event
165 EventListener EventTarget Event DocumentEvent UIEvent
166 MouseEvent MutationEvent KeyboardEvent
167
168 ;; W3C Range
169 DocumentRange Range RangeException
170
171 ;; W3C XML
172 XPathResult XMLHttpRequest
173
174 ;; console object. Provided by at least Chrome and Firefox.
175 console))
176 "Browser externs.
177 You can cause these to be included or excluded with the custom
178 variable `js2-include-browser-externs'.")
179
180 (defvar js2-rhino-externs
181 (mapcar 'symbol-name
182 '(Packages importClass importPackage com org java
183 ;; Global object (shell) externs.
184 defineClass deserialize doctest gc help load
185 loadClass print quit readFile readUrl runCommand seal
186 serialize spawn sync toint32 version))
187 "Mozilla Rhino externs.
188 Set `js2-include-rhino-externs' to t to include them.")
189
190 (defvar js2-node-externs
191 (mapcar 'symbol-name
192 '(__dirname __filename Buffer clearInterval clearTimeout require
193 console exports global module process setInterval setTimeout))
194 "Node.js externs.
195 Set `js2-include-node-externs' to t to include them.")
196
197 (defvar js2-typed-array-externs
198 (mapcar 'symbol-name
199 '(ArrayBuffer Uint8ClampedArray DataView
200 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
201 Float32Array Float64Array))
202 "Khronos typed array externs. Available in most modern browsers and
203 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
204 are enabled, these will also be included.")
205
206 ;;; Variables
207
208 (defun js2-mark-safe-local (name pred)
209 "Make the variable NAME buffer-local and mark it as safe file-local
210 variable with predicate PRED."
211 (make-variable-buffer-local name)
212 (put name 'safe-local-variable pred))
213
214 (defcustom js2-highlight-level 2
215 "Amount of syntax highlighting to perform.
216 0 or a negative value means none.
217 1 adds basic syntax highlighting.
218 2 adds highlighting of some Ecma built-in properties.
219 3 adds highlighting of many Ecma built-in functions."
220 :group 'js2-mode
221 :type '(choice (const :tag "None" 0)
222 (const :tag "Basic" 1)
223 (const :tag "Include Properties" 2)
224 (const :tag "Include Functions" 3)))
225
226 (defvar js2-mode-dev-mode-p nil
227 "Non-nil if running in development mode. Normally nil.")
228
229 (defgroup js2-mode nil
230 "An improved JavaScript mode."
231 :group 'languages)
232
233 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
234 (numberp c-basic-offset))
235 c-basic-offset
236 4)
237 "Number of spaces to indent nested statements.
238 Similar to `c-basic-offset'."
239 :group 'js2-mode
240 :type 'integer)
241 (js2-mark-safe-local 'js2-basic-offset 'integerp)
242
243 (defcustom js2-bounce-indent-p nil
244 "Non-nil to have indent-line function choose among alternatives.
245 If nil, the indent-line function will indent to a predetermined column
246 based on heuristic guessing. If non-nil, then if the current line is
247 already indented to that predetermined column, indenting will choose
248 another likely column and indent to that spot. Repeated invocation of
249 the indent-line function will cycle among the computed alternatives.
250 See the function `js2-bounce-indent' for details. When it is non-nil,
251 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
252 :type 'boolean
253 :group 'js2-mode)
254
255 (defcustom js2-pretty-multiline-declarations t
256 "Non-nil to line up multiline declarations vertically:
257
258 var a = 10,
259 b = 20,
260 c = 30;
261
262 If the value is not `all', and the first assigned value in
263 declaration is a function/array/object literal spanning several
264 lines, it won't be indented additionally:
265
266 var o = { var bar = 2,
267 foo: 3 vs. o = {
268 }, foo: 3
269 bar = 2; };"
270 :group 'js2-mode
271 :type 'symbol)
272 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
273
274 (defcustom js2-indent-switch-body nil
275 "When nil, case labels are indented on the same level as the
276 containing switch statement. Otherwise, all lines inside
277 switch statement body are indented one additional level."
278 :type 'boolean
279 :group 'js2-mode)
280 (js2-mark-safe-local 'js2-indent-case-same-as-switch 'booleanp)
281
282 (defcustom js2-idle-timer-delay 0.2
283 "Delay in secs before re-parsing after user makes changes.
284 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
285 :type 'number
286 :group 'js2-mode)
287 (make-variable-buffer-local 'js2-idle-timer-delay)
288
289 (defcustom js2-dynamic-idle-timer-adjust 0
290 "Positive to adjust `js2-idle-timer-delay' based on file size.
291 The idea is that for short files, parsing is faster so we can be
292 more responsive to user edits without interfering with editing.
293 The buffer length in characters (typically bytes) is divided by
294 this value and used to multiply `js2-idle-timer-delay' for the
295 buffer. For example, a 21k file and 10k adjust yields 21k/10k
296 == 2, so js2-idle-timer-delay is multiplied by 2.
297 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
298 `js2-idle-timer-delay' is not dependent on the file size."
299 :type 'number
300 :group 'js2-mode)
301
302 (defcustom js2-concat-multiline-strings t
303 "When non-nil, `js2-line-break' in mid-string will make it a
304 string concatenation. When `eol', the '+' will be inserted at the
305 end of the line, otherwise, at the beginning of the next line."
306 :type '(choice (const t) (const eol) (const nil))
307 :group 'js2-mode)
308
309 (defcustom js2-mode-show-parse-errors t
310 "True to highlight parse errors."
311 :type 'boolean
312 :group 'js2-mode)
313
314 (defcustom js2-mode-show-strict-warnings t
315 "Non-nil to emit Ecma strict-mode warnings.
316 Some of the warnings can be individually disabled by other flags,
317 even if this flag is non-nil."
318 :type 'boolean
319 :group 'js2-mode)
320
321 (defcustom js2-strict-trailing-comma-warning t
322 "Non-nil to warn about trailing commas in array literals.
323 Ecma-262-5.1 allows them, but older versions of IE raise an error."
324 :type 'boolean
325 :group 'js2-mode)
326
327 (defcustom js2-strict-missing-semi-warning t
328 "Non-nil to warn about semicolon auto-insertion after statement.
329 Technically this is legal per Ecma-262, but some style guides disallow
330 depending on it."
331 :type 'boolean
332 :group 'js2-mode)
333
334 (defcustom js2-missing-semi-one-line-override nil
335 "Non-nil to permit missing semicolons in one-line functions.
336 In one-liner functions such as `function identity(x) {return x}'
337 people often omit the semicolon for a cleaner look. If you are
338 such a person, you can suppress the missing-semicolon warning
339 by setting this variable to t."
340 :type 'boolean
341 :group 'js2-mode)
342
343 (defcustom js2-strict-inconsistent-return-warning t
344 "Non-nil to warn about mixing returns with value-returns.
345 It's perfectly legal to have a `return' and a `return foo' in the
346 same function, but it's often an indicator of a bug, and it also
347 interferes with type inference (in systems that support it.)"
348 :type 'boolean
349 :group 'js2-mode)
350
351 (defcustom js2-strict-cond-assign-warning t
352 "Non-nil to warn about expressions like if (a = b).
353 This often should have been '==' instead of '='. If the warning
354 is enabled, you can suppress it on a per-expression basis by
355 parenthesizing the expression, e.g. if ((a = b)) ..."
356 :type 'boolean
357 :group 'js2-mode)
358
359 (defcustom js2-strict-var-redeclaration-warning t
360 "Non-nil to warn about redeclaring variables in a script or function."
361 :type 'boolean
362 :group 'js2-mode)
363
364 (defcustom js2-strict-var-hides-function-arg-warning t
365 "Non-nil to warn about a var decl hiding a function argument."
366 :type 'boolean
367 :group 'js2-mode)
368
369 (defcustom js2-skip-preprocessor-directives nil
370 "Non-nil to treat lines beginning with # as comments.
371 Useful for viewing Mozilla JavaScript source code."
372 :type 'boolean
373 :group 'js2-mode)
374
375 (defcustom js2-language-version 200
376 "Configures what JavaScript language version to recognize.
377 Currently versions 150, 160, 170, 180 and 200 are supported,
378 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
379 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
380 yield, and Array comprehensions, and 1.8 adds function closures."
381 :type 'integer
382 :group 'js2-mode)
383
384 (defcustom js2-allow-keywords-as-property-names t
385 "If non-nil, you can use JavaScript keywords as object property names.
386 Examples:
387
388 var foo = {int: 5, while: 6, continue: 7};
389 foo.return = 8;
390
391 Ecma-262 5.1 allows this syntax, but some engines still don't."
392 :type 'boolean
393 :group 'js2-mode)
394
395 (defcustom js2-instanceof-has-side-effects nil
396 "If non-nil, treats the instanceof operator as having side effects.
397 This is useful for xulrunner apps."
398 :type 'boolean
399 :group 'js2-mode)
400
401 (defcustom js2-move-point-on-right-click t
402 "Non-nil to move insertion point when you right-click.
403 This makes right-click context menu behavior a bit more intuitive,
404 since menu operations generally apply to the point. The exception
405 is if there is a region selection, in which case the point does -not-
406 move, so cut/copy/paste can work properly.
407
408 Note that IntelliJ moves the point, and Eclipse leaves it alone,
409 so this behavior is customizable."
410 :group 'js2-mode
411 :type 'boolean)
412
413 (defcustom js2-allow-rhino-new-expr-initializer t
414 "Non-nil to support a Rhino's experimental syntactic construct.
415
416 Rhino supports the ability to follow a `new' expression with an object
417 literal, which is used to set additional properties on the new object
418 after calling its constructor. Syntax:
419
420 new <expr> [ ( arglist ) ] [initializer]
421
422 Hence, this expression:
423
424 new Object {a: 1, b: 2}
425
426 results in an Object with properties a=1 and b=2. This syntax is
427 apparently not configurable in Rhino - it's currently always enabled,
428 as of Rhino version 1.7R2."
429 :type 'boolean
430 :group 'js2-mode)
431
432 (defcustom js2-allow-member-expr-as-function-name nil
433 "Non-nil to support experimental Rhino syntax for function names.
434
435 Rhino supports an experimental syntax configured via the Rhino Context
436 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
437
438 function <member-expr> ( [ arg-list ] ) { <body> }
439
440 Where member-expr is a non-parenthesized 'member expression', which
441 is anything at the grammar level of a new-expression or lower, meaning
442 any expression that does not involve infix or unary operators.
443
444 When <member-expr> is not a simple identifier, then it is syntactic
445 sugar for assigning the anonymous function to the <member-expr>. Hence,
446 this code:
447
448 function a.b().c[2] (x, y) { ... }
449
450 is rewritten as:
451
452 a.b().c[2] = function(x, y) {...}
453
454 which doesn't seem particularly useful, but Rhino permits it."
455 :type 'boolean
456 :group 'js2-mode)
457
458 ;; scanner variables
459
460 (defmacro js2-deflocal (name value &optional comment)
461 "Define a buffer-local variable NAME with VALUE and COMMENT."
462 `(progn
463 (defvar ,name ,value ,comment)
464 (make-variable-buffer-local ',name)))
465
466 (defvar js2-EOF_CHAR -1
467 "Represents end of stream. Distinct from js2-EOF token type.")
468
469 ;; I originally used symbols to represent tokens, but Rhino uses
470 ;; ints and then sets various flag bits in them, so ints it is.
471 ;; The upshot is that we need a `js2-' prefix in front of each name.
472 (defvar js2-ERROR -1)
473 (defvar js2-EOF 0)
474 (defvar js2-EOL 1)
475 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
476 (defvar js2-LEAVEWITH 3)
477 (defvar js2-RETURN 4)
478 (defvar js2-GOTO 5)
479 (defvar js2-IFEQ 6)
480 (defvar js2-IFNE 7)
481 (defvar js2-SETNAME 8)
482 (defvar js2-BITOR 9)
483 (defvar js2-BITXOR 10)
484 (defvar js2-BITAND 11)
485 (defvar js2-EQ 12)
486 (defvar js2-NE 13)
487 (defvar js2-LT 14)
488 (defvar js2-LE 15)
489 (defvar js2-GT 16)
490 (defvar js2-GE 17)
491 (defvar js2-LSH 18)
492 (defvar js2-RSH 19)
493 (defvar js2-URSH 20)
494 (defvar js2-ADD 21) ; infix plus
495 (defvar js2-SUB 22) ; infix minus
496 (defvar js2-MUL 23)
497 (defvar js2-DIV 24)
498 (defvar js2-MOD 25)
499 (defvar js2-NOT 26)
500 (defvar js2-BITNOT 27)
501 (defvar js2-POS 28) ; unary plus
502 (defvar js2-NEG 29) ; unary minus
503 (defvar js2-NEW 30)
504 (defvar js2-DELPROP 31)
505 (defvar js2-TYPEOF 32)
506 (defvar js2-GETPROP 33)
507 (defvar js2-GETPROPNOWARN 34)
508 (defvar js2-SETPROP 35)
509 (defvar js2-GETELEM 36)
510 (defvar js2-SETELEM 37)
511 (defvar js2-CALL 38)
512 (defvar js2-NAME 39) ; an identifier
513 (defvar js2-NUMBER 40)
514 (defvar js2-STRING 41)
515 (defvar js2-NULL 42)
516 (defvar js2-THIS 43)
517 (defvar js2-FALSE 44)
518 (defvar js2-TRUE 45)
519 (defvar js2-SHEQ 46) ; shallow equality (===)
520 (defvar js2-SHNE 47) ; shallow inequality (!==)
521 (defvar js2-REGEXP 48)
522 (defvar js2-BINDNAME 49)
523 (defvar js2-THROW 50)
524 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
525 (defvar js2-IN 52)
526 (defvar js2-INSTANCEOF 53)
527 (defvar js2-LOCAL_LOAD 54)
528 (defvar js2-GETVAR 55)
529 (defvar js2-SETVAR 56)
530 (defvar js2-CATCH_SCOPE 57)
531 (defvar js2-ENUM_INIT_KEYS 58)
532 (defvar js2-ENUM_INIT_VALUES 59)
533 (defvar js2-ENUM_INIT_ARRAY 60)
534 (defvar js2-ENUM_NEXT 61)
535 (defvar js2-ENUM_ID 62)
536 (defvar js2-THISFN 63)
537 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
538 (defvar js2-ARRAYLIT 65) ; array literal
539 (defvar js2-OBJECTLIT 66) ; object literal
540 (defvar js2-GET_REF 67) ; *reference
541 (defvar js2-SET_REF 68) ; *reference = something
542 (defvar js2-DEL_REF 69) ; delete reference
543 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
544 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
545 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
546
547 ;; XML support
548 (defvar js2-DEFAULTNAMESPACE 73)
549 (defvar js2-ESCXMLATTR 74)
550 (defvar js2-ESCXMLTEXT 75)
551 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
552 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
553 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
554 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
555
556 (defvar js2-first-bytecode js2-ENTERWITH)
557 (defvar js2-last-bytecode js2-REF_NS_NAME)
558
559 (defvar js2-TRY 80)
560 (defvar js2-SEMI 81) ; semicolon
561 (defvar js2-LB 82) ; left and right brackets
562 (defvar js2-RB 83)
563 (defvar js2-LC 84) ; left and right curly-braces
564 (defvar js2-RC 85)
565 (defvar js2-LP 86) ; left and right parens
566 (defvar js2-RP 87)
567 (defvar js2-COMMA 88) ; comma operator
568
569 (defvar js2-ASSIGN 89) ; simple assignment (=)
570 (defvar js2-ASSIGN_BITOR 90) ; |=
571 (defvar js2-ASSIGN_BITXOR 91) ; ^=
572 (defvar js2-ASSIGN_BITAND 92) ; &=
573 (defvar js2-ASSIGN_LSH 93) ; <<=
574 (defvar js2-ASSIGN_RSH 94) ; >>=
575 (defvar js2-ASSIGN_URSH 95) ; >>>=
576 (defvar js2-ASSIGN_ADD 96) ; +=
577 (defvar js2-ASSIGN_SUB 97) ; -=
578 (defvar js2-ASSIGN_MUL 98) ; *=
579 (defvar js2-ASSIGN_DIV 99) ; /=
580 (defvar js2-ASSIGN_MOD 100) ; %=
581
582 (defvar js2-first-assign js2-ASSIGN)
583 (defvar js2-last-assign js2-ASSIGN_MOD)
584
585 (defvar js2-HOOK 101) ; conditional (?:)
586 (defvar js2-COLON 102)
587 (defvar js2-OR 103) ; logical or (||)
588 (defvar js2-AND 104) ; logical and (&&)
589 (defvar js2-INC 105) ; increment/decrement (++ --)
590 (defvar js2-DEC 106)
591 (defvar js2-DOT 107) ; member operator (.)
592 (defvar js2-FUNCTION 108) ; function keyword
593 (defvar js2-EXPORT 109) ; export keyword
594 (defvar js2-IMPORT 110) ; import keyword
595 (defvar js2-IF 111) ; if keyword
596 (defvar js2-ELSE 112) ; else keyword
597 (defvar js2-SWITCH 113) ; switch keyword
598 (defvar js2-CASE 114) ; case keyword
599 (defvar js2-DEFAULT 115) ; default keyword
600 (defvar js2-WHILE 116) ; while keyword
601 (defvar js2-DO 117) ; do keyword
602 (defvar js2-FOR 118) ; for keyword
603 (defvar js2-BREAK 119) ; break keyword
604 (defvar js2-CONTINUE 120) ; continue keyword
605 (defvar js2-VAR 121) ; var keyword
606 (defvar js2-WITH 122) ; with keyword
607 (defvar js2-CATCH 123) ; catch keyword
608 (defvar js2-FINALLY 124) ; finally keyword
609 (defvar js2-VOID 125) ; void keyword
610 (defvar js2-RESERVED 126) ; reserved keywords
611
612 (defvar js2-EMPTY 127)
613
614 ;; Types used for the parse tree - never returned by scanner.
615
616 (defvar js2-BLOCK 128) ; statement block
617 (defvar js2-LABEL 129) ; label
618 (defvar js2-TARGET 130)
619 (defvar js2-LOOP 131)
620 (defvar js2-EXPR_VOID 132) ; expression statement in functions
621 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
622 (defvar js2-JSR 134)
623 (defvar js2-SCRIPT 135) ; top-level node for entire script
624 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
625 (defvar js2-USE_STACK 137)
626 (defvar js2-SETPROP_OP 138) ; x.y op= something
627 (defvar js2-SETELEM_OP 139) ; x[y] op= something
628 (defvar js2-LOCAL_BLOCK 140)
629 (defvar js2-SET_REF_OP 141) ; *reference op= something
630
631 ;; For XML support:
632 (defvar js2-DOTDOT 142) ; member operator (..)
633 (defvar js2-COLONCOLON 143) ; namespace::name
634 (defvar js2-XML 144) ; XML type
635 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
636 (defvar js2-XMLATTR 146) ; @
637 (defvar js2-XMLEND 147)
638
639 ;; Optimizer-only tokens
640 (defvar js2-TO_OBJECT 148)
641 (defvar js2-TO_DOUBLE 149)
642
643 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
644 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
645 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
646 (defvar js2-CONST 153)
647 (defvar js2-SETCONST 154)
648 (defvar js2-SETCONSTVAR 155)
649 (defvar js2-ARRAYCOMP 156)
650 (defvar js2-LETEXPR 157)
651 (defvar js2-WITHEXPR 158)
652 (defvar js2-DEBUGGER 159)
653
654 (defvar js2-COMMENT 160)
655 (defvar js2-ENUM 161) ; for "enum" reserved word
656 (defvar js2-TRIPLEDOT 162) ; for rest parameter
657 (defvar js2-ARROW 163) ; function arrow (=>)
658
659 (defconst js2-num-tokens (1+ js2-ARROW))
660
661 (defconst js2-debug-print-trees nil)
662
663 ;; Rhino accepts any string or stream as input. Emacs character
664 ;; processing works best in buffers, so we'll assume the input is a
665 ;; buffer. JavaScript strings can be copied into temp buffers before
666 ;; scanning them.
667
668 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
669 ;; They're the Emacs equivalent of instance variables, more or less.
670
671 (js2-deflocal js2-ts-dirty-line nil
672 "Token stream buffer-local variable.
673 Indicates stuff other than whitespace since start of line.")
674
675 (js2-deflocal js2-ts-hit-eof nil
676 "Token stream buffer-local variable.")
677
678 ;; FIXME: Unused.
679 (js2-deflocal js2-ts-line-start 0
680 "Token stream buffer-local variable.")
681
682 (js2-deflocal js2-ts-lineno 1
683 "Token stream buffer-local variable.")
684
685 ;; FIXME: Unused.
686 (js2-deflocal js2-ts-line-end-char -1
687 "Token stream buffer-local variable.")
688
689 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
690 "Token stream buffer-local variable.
691 Current scan position.")
692
693 ;; FIXME: Unused.
694 (js2-deflocal js2-ts-is-xml-attribute nil
695 "Token stream buffer-local variable.")
696
697 (js2-deflocal js2-ts-xml-is-tag-content nil
698 "Token stream buffer-local variable.")
699
700 (js2-deflocal js2-ts-xml-open-tags-count 0
701 "Token stream buffer-local variable.")
702
703 (js2-deflocal js2-ts-string-buffer nil
704 "Token stream buffer-local variable.
705 List of chars built up while scanning various tokens.")
706
707 (defstruct (js2-token
708 (:constructor nil)
709 (:constructor make-js2-token (beg)))
710 "Value returned from the token stream."
711 (type js2-EOF)
712 (beg 1)
713 (end -1)
714 (string "")
715 number
716 regexp-flags
717 comment-type
718 follows-eol-p)
719
720 (defstruct (js2-ts-state
721 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
722 (cursor js2-ts-cursor)
723 (tokens (copy-sequence js2-ti-tokens))
724 (tokens-cursor js2-ti-tokens-cursor)
725 (lookahead js2-ti-lookahead))))
726 lineno
727 cursor
728 tokens
729 tokens-cursor
730 lookahead)
731
732 ;;; Parser variables
733
734 (js2-deflocal js2-parsed-errors nil
735 "List of errors produced during scanning/parsing.")
736
737 (js2-deflocal js2-parsed-warnings nil
738 "List of warnings produced during scanning/parsing.")
739
740 (js2-deflocal js2-recover-from-parse-errors t
741 "Non-nil to continue parsing after a syntax error.
742
743 In recovery mode, the AST will be built in full, and any error
744 nodes will be flagged with appropriate error information. If
745 this flag is nil, a syntax error will result in an error being
746 signaled.
747
748 The variable is automatically buffer-local, because different
749 modes that use the parser will need different settings.")
750
751 (js2-deflocal js2-parse-hook nil
752 "List of callbacks for receiving parsing progress.")
753
754 (defvar js2-parse-finished-hook nil
755 "List of callbacks to notify when parsing finishes.
756 Not called if parsing was interrupted.")
757
758 (js2-deflocal js2-is-eval-code nil
759 "True if we're evaluating code in a string.
760 If non-nil, the tokenizer will record the token text, and the AST nodes
761 will record their source text. Off by default for IDE modes, since the
762 text is available in the buffer.")
763
764 (defvar js2-parse-ide-mode t
765 "Non-nil if the parser is being used for `js2-mode'.
766 If non-nil, the parser will set text properties for fontification
767 and the syntax table. The value should be nil when using the
768 parser as a frontend to an interpreter or byte compiler.")
769
770 ;;; Parser instance variables (buffer-local vars for js2-parse)
771
772 (defconst js2-ti-after-eol (lsh 1 16)
773 "Flag: first token of the source line.")
774
775 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
776
777 (js2-deflocal js2-compiler-generate-debug-info t)
778 (js2-deflocal js2-compiler-use-dynamic-scope nil)
779 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
780 (js2-deflocal js2-compiler-xml-available t)
781 (js2-deflocal js2-compiler-optimization-level 0)
782 (js2-deflocal js2-compiler-generating-source t)
783 (js2-deflocal js2-compiler-strict-mode nil)
784 (js2-deflocal js2-compiler-report-warning-as-error nil)
785 (js2-deflocal js2-compiler-generate-observer-count nil)
786 (js2-deflocal js2-compiler-activation-names nil)
787
788 ;; SKIP: sourceURI
789
790 ;; There's a compileFunction method in Context.java - may need it.
791 (js2-deflocal js2-called-by-compile-function nil
792 "True if `js2-parse' was called by `js2-compile-function'.
793 Will only be used when we finish implementing the interpreter.")
794
795 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
796
797 ;; SKIP: node factory - we're going to just call functions directly,
798 ;; and eventually go to a unified AST format.
799
800 (js2-deflocal js2-nesting-of-function 0)
801
802 (js2-deflocal js2-recorded-identifiers nil
803 "Tracks identifiers found during parsing.")
804
805 (js2-deflocal js2-is-in-destructuring nil
806 "True while parsing destructuring expression.")
807
808 (defcustom js2-global-externs nil
809 "A list of any extern names you'd like to consider always declared.
810 This list is global and is used by all `js2-mode' files.
811 You can create buffer-local externs list using `js2-additional-externs'.
812
813 There is also a buffer-local variable `js2-default-externs',
814 which is initialized by default to include the Ecma-262 externs
815 and the standard browser externs. The three lists are all
816 checked during highlighting."
817 :type 'list
818 :group 'js2-mode)
819
820 (js2-deflocal js2-default-externs nil
821 "Default external declarations.
822
823 These are currently only used for highlighting undeclared variables,
824 which only worries about top-level (unqualified) references.
825 As js2-mode's processing improves, we will flesh out this list.
826
827 The initial value is set to `js2-ecma-262-externs', unless some
828 of the `js2-include-?-externs' variables are set to t, in which
829 case the browser, Rhino and/or Node.js externs are also included.
830
831 See `js2-additional-externs' for more information.")
832
833 (defcustom js2-include-browser-externs t
834 "Non-nil to include browser externs in the master externs list.
835 If you work on JavaScript files that are not intended for browsers,
836 such as Mozilla Rhino server-side JavaScript, set this to nil.
837 See `js2-additional-externs' for more information about externs."
838 :type 'boolean
839 :group 'js2-mode)
840
841 (defcustom js2-include-rhino-externs nil
842 "Non-nil to include Mozilla Rhino externs in the master externs list.
843 See `js2-additional-externs' for more information about externs."
844 :type 'boolean
845 :group 'js2-mode)
846
847 (defcustom js2-include-node-externs nil
848 "Non-nil to include Node.js externs in the master externs list.
849 See `js2-additional-externs' for more information about externs."
850 :type 'boolean
851 :group 'js2-mode)
852
853 (js2-deflocal js2-additional-externs nil
854 "A buffer-local list of additional external declarations.
855 It is used to decide whether variables are considered undeclared
856 for purposes of highlighting.
857
858 Each entry is a Lisp string. The string should be the fully qualified
859 name of an external entity. All externs should be added to this list,
860 so that as js2-mode's processing improves it can take advantage of them.
861
862 You may want to declare your externs in three ways.
863 First, you can add externs that are valid for all your JavaScript files.
864 You should probably do this by adding them to `js2-global-externs', which
865 is a global list used for all js2-mode files.
866
867 Next, you can add a function to `js2-init-hook' that adds additional
868 externs appropriate for the specific file, perhaps based on its path.
869 These should go in `js2-additional-externs', which is buffer-local.
870
871 Third, you can use JSLint's global declaration, as long as
872 `js2-include-jslint-globals' is non-nil, which see.
873
874 Finally, you can add a function to `js2-post-parse-callbacks',
875 which is called after parsing completes, and `js2-mode-ast' is bound to
876 the root of the parse tree. At this stage you can set up an AST
877 node visitor using `js2-visit-ast' and examine the parse tree
878 for specific import patterns that may imply the existence of
879 other externs, possibly tied to your build system. These should also
880 be added to `js2-additional-externs'.
881
882 Your post-parse callback may of course also use the simpler and
883 faster (but perhaps less robust) approach of simply scanning the
884 buffer text for your imports, using regular expressions.")
885
886 ;; SKIP: decompiler
887 ;; SKIP: encoded-source
888
889 ;;; The following variables are per-function and should be saved/restored
890 ;;; during function parsing...
891
892 (js2-deflocal js2-current-script-or-fn nil)
893 (js2-deflocal js2-current-scope nil)
894 (js2-deflocal js2-nesting-of-with 0)
895 (js2-deflocal js2-label-set nil
896 "An alist mapping label names to nodes.")
897
898 (js2-deflocal js2-loop-set nil)
899 (js2-deflocal js2-loop-and-switch-set nil)
900 (js2-deflocal js2-has-return-value nil)
901 (js2-deflocal js2-end-flags 0)
902
903 ;;; ...end of per function variables
904
905 ;; These flags enumerate the possible ways a statement/function can
906 ;; terminate. These flags are used by endCheck() and by the Parser to
907 ;; detect inconsistent return usage.
908 ;;
909 ;; END_UNREACHED is reserved for code paths that are assumed to always be
910 ;; able to execute (example: throw, continue)
911 ;;
912 ;; END_DROPS_OFF indicates if the statement can transfer control to the
913 ;; next one. Statement such as return dont. A compound statement may have
914 ;; some branch that drops off control to the next statement.
915 ;;
916 ;; END_RETURNS indicates that the statement can return (without arguments)
917 ;; END_RETURNS_VALUE indicates that the statement can return a value.
918 ;;
919 ;; A compound statement such as
920 ;; if (condition) {
921 ;; return value;
922 ;; }
923 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
924
925 (defconst js2-end-unreached #x0)
926 (defconst js2-end-drops-off #x1)
927 (defconst js2-end-returns #x2)
928 (defconst js2-end-returns-value #x4)
929
930 ;; Rhino awkwardly passes a statementLabel parameter to the
931 ;; statementHelper() function, the main statement parser, which
932 ;; is then used by quite a few of the sub-parsers. We just make
933 ;; it a buffer-local variable and make sure it's cleaned up properly.
934 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
935
936 ;; Similarly, Rhino passes an inForInit boolean through about half
937 ;; the expression parsers. We use a dynamically-scoped variable,
938 ;; which makes it easier to funcall the parsers individually without
939 ;; worrying about whether they take the parameter or not.
940 (js2-deflocal js2-in-for-init nil)
941 (js2-deflocal js2-temp-name-counter 0)
942 (js2-deflocal js2-parse-stmt-count 0)
943
944 (defsubst js2-get-next-temp-name ()
945 (format "$%d" (incf js2-temp-name-counter)))
946
947 (defvar js2-parse-interruptable-p t
948 "Set this to nil to force parse to continue until finished.
949 This will mostly be useful for interpreters.")
950
951 (defvar js2-statements-per-pause 50
952 "Pause after this many statements to check for user input.
953 If user input is pending, stop the parse and discard the tree.
954 This makes for a smoother user experience for large files.
955 You may have to wait a second or two before the highlighting
956 and error-reporting appear, but you can always type ahead if
957 you wish. This appears to be more or less how Eclipse, IntelliJ
958 and other editors work.")
959
960 (js2-deflocal js2-record-comments t
961 "Instructs the scanner to record comments in `js2-scanned-comments'.")
962
963 (js2-deflocal js2-scanned-comments nil
964 "List of all comments from the current parse.")
965
966 (defcustom js2-mode-indent-inhibit-undo nil
967 "Non-nil to disable collection of Undo information when indenting lines.
968 Some users have requested this behavior. It's nil by default because
969 other Emacs modes don't work this way."
970 :type 'boolean
971 :group 'js2-mode)
972
973 (defcustom js2-mode-indent-ignore-first-tab nil
974 "If non-nil, ignore first TAB keypress if we look indented properly.
975 It's fairly common for users to navigate to an already-indented line
976 and press TAB for reassurance that it's been indented. For this class
977 of users, we want the first TAB press on a line to be ignored if the
978 line is already indented to one of the precomputed alternatives.
979
980 This behavior is only partly implemented. If you TAB-indent a line,
981 navigate to another line, and then navigate back, it fails to clear
982 the last-indented variable, so it thinks you've already hit TAB once,
983 and performs the indent. A full solution would involve getting on the
984 point-motion hooks for the entire buffer. If we come across another
985 use cases that requires watching point motion, I'll consider doing it.
986
987 If you set this variable to nil, then the TAB key will always change
988 the indentation of the current line, if more than one alternative
989 indentation spot exists."
990 :type 'boolean
991 :group 'js2-mode)
992
993 (defvar js2-indent-hook nil
994 "A hook for user-defined indentation rules.
995
996 Functions on this hook should expect two arguments: (LIST INDEX)
997 The LIST argument is the list of computed indentation points for
998 the current line. INDEX is the list index of the indentation point
999 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1000 indent function is not going to change the current line indentation.
1001
1002 If a hook function on this list returns a non-nil value, then
1003 `js2-bounce-indent' assumes the hook function has performed its own
1004 indentation, and will do nothing. If all hook functions on the list
1005 return nil, then `js2-bounce-indent' will use its computed indentation
1006 and reindent the line.
1007
1008 When hook functions on this hook list are called, the variable
1009 `js2-mode-ast' may or may not be set, depending on whether the
1010 parse tree is available. If the variable is nil, you can pass a
1011 callback to `js2-mode-wait-for-parse', and your callback will be
1012 called after the new parse tree is built. This can take some time
1013 in large files.")
1014
1015 (defface js2-warning
1016 `((((class color) (background light))
1017 (:underline "orange"))
1018 (((class color) (background dark))
1019 (:underline "orange"))
1020 (t (:underline t)))
1021 "Face for JavaScript warnings."
1022 :group 'js2-mode)
1023
1024 (defface js2-error
1025 `((((class color) (background light))
1026 (:foreground "red"))
1027 (((class color) (background dark))
1028 (:foreground "red"))
1029 (t (:foreground "red")))
1030 "Face for JavaScript errors."
1031 :group 'js2-mode)
1032
1033 (defface js2-jsdoc-tag
1034 '((t :foreground "SlateGray"))
1035 "Face used to highlight @whatever tags in jsdoc comments."
1036 :group 'js2-mode)
1037
1038 (defface js2-jsdoc-type
1039 '((t :foreground "SteelBlue"))
1040 "Face used to highlight {FooBar} types in jsdoc comments."
1041 :group 'js2-mode)
1042
1043 (defface js2-jsdoc-value
1044 '((t :foreground "PeachPuff3"))
1045 "Face used to highlight tag values in jsdoc comments."
1046 :group 'js2-mode)
1047
1048 (defface js2-function-param
1049 '((t :foreground "SeaGreen"))
1050 "Face used to highlight function parameters in javascript."
1051 :group 'js2-mode)
1052
1053 (defface js2-function-call
1054 '((t :inherit default))
1055 "Face used to highlight function name in calls."
1056 :group 'js2-mode)
1057
1058 (defface js2-instance-member
1059 '((t :foreground "DarkOrchid"))
1060 "Face used to highlight instance variables in javascript.
1061 Not currently used."
1062 :group 'js2-mode)
1063
1064 (defface js2-private-member
1065 '((t :foreground "PeachPuff3"))
1066 "Face used to highlight calls to private methods in javascript.
1067 Not currently used."
1068 :group 'js2-mode)
1069
1070 (defface js2-private-function-call
1071 '((t :foreground "goldenrod"))
1072 "Face used to highlight calls to private functions in javascript.
1073 Not currently used."
1074 :group 'js2-mode)
1075
1076 (defface js2-jsdoc-html-tag-name
1077 '((((class color) (min-colors 88) (background light))
1078 (:foreground "rosybrown"))
1079 (((class color) (min-colors 8) (background dark))
1080 (:foreground "yellow"))
1081 (((class color) (min-colors 8) (background light))
1082 (:foreground "magenta")))
1083 "Face used to highlight jsdoc html tag names"
1084 :group 'js2-mode)
1085
1086 (defface js2-jsdoc-html-tag-delimiter
1087 '((((class color) (min-colors 88) (background light))
1088 (:foreground "dark khaki"))
1089 (((class color) (min-colors 8) (background dark))
1090 (:foreground "green"))
1091 (((class color) (min-colors 8) (background light))
1092 (:foreground "green")))
1093 "Face used to highlight brackets in jsdoc html tags."
1094 :group 'js2-mode)
1095
1096 (defface js2-external-variable
1097 '((t :foreground "orange"))
1098 "Face used to highlight undeclared variable identifiers.")
1099
1100 (defcustom js2-init-hook nil
1101 "List of functions to be called after `js2-mode' or
1102 `js2-minor-mode' has initialized all variables, before parsing
1103 the buffer for the first time."
1104 :type 'hook
1105 :group 'js2-mode
1106 :version "20130608")
1107
1108 (defcustom js2-post-parse-callbacks nil
1109 "List of callback functions invoked after parsing finishes.
1110 Currently, the main use for this function is to add synthetic
1111 declarations to `js2-recorded-identifiers', which see."
1112 :type 'hook
1113 :group 'js2-mode)
1114
1115 (defcustom js2-highlight-external-variables t
1116 "Non-nil to highlight undeclared variable identifiers.
1117 An undeclared variable is any variable not declared with var or let
1118 in the current scope or any lexically enclosing scope. If you use
1119 such a variable, then you are either expecting it to originate from
1120 another file, or you've got a potential bug."
1121 :type 'boolean
1122 :group 'js2-mode)
1123
1124 (defcustom js2-include-jslint-globals t
1125 "Non-nil to include the identifiers from JSLint global
1126 declaration (see http://www.jslint.com/lint.html#global) in the
1127 buffer-local externs list. See `js2-additional-externs' for more
1128 information."
1129 :type 'boolean
1130 :group 'js2-mode)
1131
1132 (defvar js2-mode-map
1133 (let ((map (make-sparse-keymap)))
1134 (define-key map [mouse-1] #'js2-mode-show-node)
1135 (define-key map (kbd "M-j") #'js2-line-break)
1136 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1137 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1138 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1139 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1140 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1141 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1142 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1143 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1144 (when js2-bounce-indent-p
1145 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1146
1147 (define-key map [menu-bar javascript]
1148 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1149
1150 (define-key map [menu-bar javascript customize-js2-mode]
1151 '(menu-item "Customize js2-mode" js2-mode-customize
1152 :help "Customize the behavior of this mode"))
1153
1154 (define-key map [menu-bar javascript js2-force-refresh]
1155 '(menu-item "Force buffer refresh" js2-mode-reset
1156 :help "Re-parse the buffer from scratch"))
1157
1158 (define-key map [menu-bar javascript separator-2]
1159 '("--"))
1160
1161 (define-key map [menu-bar javascript next-error]
1162 '(menu-item "Next warning or error" next-error
1163 :enabled (and js2-mode-ast
1164 (or (js2-ast-root-errors js2-mode-ast)
1165 (js2-ast-root-warnings js2-mode-ast)))
1166 :help "Move to next warning or error"))
1167
1168 (define-key map [menu-bar javascript display-errors]
1169 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1170 :visible (not js2-mode-show-parse-errors)
1171 :help "Turn on display of warnings and errors"))
1172
1173 (define-key map [menu-bar javascript hide-errors]
1174 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1175 :visible js2-mode-show-parse-errors
1176 :help "Turn off display of warnings and errors"))
1177
1178 (define-key map [menu-bar javascript separator-1]
1179 '("--"))
1180
1181 (define-key map [menu-bar javascript js2-toggle-function]
1182 '(menu-item "Show/collapse element" js2-mode-toggle-element
1183 :help "Hide or show function body or comment"))
1184
1185 (define-key map [menu-bar javascript show-comments]
1186 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1187 :visible js2-mode-comments-hidden
1188 :help "Expand all hidden block comments"))
1189
1190 (define-key map [menu-bar javascript hide-comments]
1191 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1192 :visible (not js2-mode-comments-hidden)
1193 :help "Show block comments as /*...*/"))
1194
1195 (define-key map [menu-bar javascript show-all-functions]
1196 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1197 :visible js2-mode-functions-hidden
1198 :help "Expand all hidden function bodies"))
1199
1200 (define-key map [menu-bar javascript hide-all-functions]
1201 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1202 :visible (not js2-mode-functions-hidden)
1203 :help "Show {...} for all top-level function bodies"))
1204
1205 map)
1206 "Keymap used in `js2-mode' buffers.")
1207
1208 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1209
1210 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1211 "Matches a //-comment line. Must be first non-whitespace on line.
1212 First match-group is the leading whitespace.")
1213
1214 (defvar js2-mode-hook nil)
1215
1216 (js2-deflocal js2-mode-ast nil "Private variable.")
1217 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1218 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1219 (js2-deflocal js2-mode-parsing nil "Private variable.")
1220 (js2-deflocal js2-mode-node-overlay nil)
1221
1222 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1223 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1224
1225 (js2-deflocal js2-mode-fontifications nil "Private variable")
1226 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1227 (js2-deflocal js2-imenu-recorder nil "Private variable")
1228 (js2-deflocal js2-imenu-function-map nil "Private variable")
1229
1230 (defvar js2-paragraph-start
1231 "\\(@[[:alpha:]]+\\>\\|$\\)")
1232
1233 ;; Note that we also set a 'c-in-sws text property in html comments,
1234 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1235 (defvar js2-syntactic-ws-start
1236 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1237
1238 (defvar js2-syntactic-ws-end
1239 "\\s \\|[\n\r/]\\|\\s!")
1240
1241 (defvar js2-syntactic-eol
1242 (concat "\\s *\\(/\\*[^*\n\r]*"
1243 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1244 "\\*+/\\s *\\)*"
1245 "\\(//\\|/\\*[^*\n\r]*"
1246 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1247 "\\|\\\\$\\|$\\)")
1248 "Copied from `java-mode'. Needed for some cc-engine functions.")
1249
1250 (defvar js2-comment-prefix-regexp
1251 "//+\\|\\**")
1252
1253 (defvar js2-comment-start-skip
1254 "\\(//+\\|/\\*+\\)\\s *")
1255
1256 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1257 "Non-nil to emit status messages during parsing.")
1258
1259 (defvar js2-mode-functions-hidden nil "Private variable.")
1260 (defvar js2-mode-comments-hidden nil "Private variable.")
1261
1262 (defvar js2-mode-syntax-table
1263 (let ((table (make-syntax-table)))
1264 (c-populate-syntax-table table)
1265 table)
1266 "Syntax table used in `js2-mode' buffers.")
1267
1268 (defvar js2-mode-abbrev-table nil
1269 "Abbrev table in use in `js2-mode' buffers.")
1270 (define-abbrev-table 'js2-mode-abbrev-table ())
1271
1272 (defvar js2-mode-pending-parse-callbacks nil
1273 "List of functions waiting to be notified that parse is finished.")
1274
1275 (defvar js2-mode-last-indented-line -1)
1276
1277 ;;; Localizable error and warning messages
1278
1279 ;; Messages are copied from Rhino's Messages.properties.
1280 ;; Many of the Java-specific messages have been elided.
1281 ;; Add any js2-specific ones at the end, so we can keep
1282 ;; this file synced with changes to Rhino's.
1283
1284 (defvar js2-message-table
1285 (make-hash-table :test 'equal :size 250)
1286 "Contains localized messages for `js2-mode'.")
1287
1288 ;; TODO(stevey): construct this table at compile-time.
1289 (defmacro js2-msg (key &rest strings)
1290 `(puthash ,key (concat ,@strings)
1291 js2-message-table))
1292
1293 (defun js2-get-msg (msg-key)
1294 "Look up a localized message.
1295 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1296 the correct number of ARGS must be provided."
1297 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1298 (args (if (listp msg-key) (cdr msg-key)))
1299 (msg (gethash key js2-message-table)))
1300 (if msg
1301 (apply #'format msg args)
1302 key))) ; default to showing the key
1303
1304 (js2-msg "msg.dup.parms"
1305 "Duplicate parameter name '%s'.")
1306
1307 (js2-msg "msg.too.big.jump"
1308 "Program too complex: jump offset too big.")
1309
1310 (js2-msg "msg.too.big.index"
1311 "Program too complex: internal index exceeds 64K limit.")
1312
1313 (js2-msg "msg.while.compiling.fn"
1314 "Encountered code generation error while compiling function '%s': %s")
1315
1316 (js2-msg "msg.while.compiling.script"
1317 "Encountered code generation error while compiling script: %s")
1318
1319 ;; Context
1320 (js2-msg "msg.ctor.not.found"
1321 "Constructor for '%s' not found.")
1322
1323 (js2-msg "msg.not.ctor"
1324 "'%s' is not a constructor.")
1325
1326 ;; FunctionObject
1327 (js2-msg "msg.varargs.ctor"
1328 "Method or constructor '%s' must be static "
1329 "with the signature (Context cx, Object[] args, "
1330 "Function ctorObj, boolean inNewExpr) "
1331 "to define a variable arguments constructor.")
1332
1333 (js2-msg "msg.varargs.fun"
1334 "Method '%s' must be static with the signature "
1335 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1336 "to define a variable arguments function.")
1337
1338 (js2-msg "msg.incompat.call"
1339 "Method '%s' called on incompatible object.")
1340
1341 (js2-msg "msg.bad.parms"
1342 "Unsupported parameter type '%s' in method '%s'.")
1343
1344 (js2-msg "msg.bad.method.return"
1345 "Unsupported return type '%s' in method '%s'.")
1346
1347 (js2-msg "msg.bad.ctor.return"
1348 "Construction of objects of type '%s' is not supported.")
1349
1350 (js2-msg "msg.no.overload"
1351 "Method '%s' occurs multiple times in class '%s'.")
1352
1353 (js2-msg "msg.method.not.found"
1354 "Method '%s' not found in '%s'.")
1355
1356 ;; IRFactory
1357
1358 (js2-msg "msg.bad.for.in.lhs"
1359 "Invalid left-hand side of for..in loop.")
1360
1361 (js2-msg "msg.mult.index"
1362 "Only one variable allowed in for..in loop.")
1363
1364 (js2-msg "msg.bad.for.in.destruct"
1365 "Left hand side of for..in loop must be an array of "
1366 "length 2 to accept key/value pair.")
1367
1368 (js2-msg "msg.cant.convert"
1369 "Can't convert to type '%s'.")
1370
1371 (js2-msg "msg.bad.assign.left"
1372 "Invalid assignment left-hand side.")
1373
1374 (js2-msg "msg.bad.decr"
1375 "Invalid decerement operand.")
1376
1377 (js2-msg "msg.bad.incr"
1378 "Invalid increment operand.")
1379
1380 (js2-msg "msg.bad.yield"
1381 "yield must be in a function.")
1382
1383 (js2-msg "msg.yield.parenthesized"
1384 "yield expression must be parenthesized.")
1385
1386 ;; NativeGlobal
1387 (js2-msg "msg.cant.call.indirect"
1388 "Function '%s' must be called directly, and not by way of a "
1389 "function of another name.")
1390
1391 (js2-msg "msg.eval.nonstring"
1392 "Calling eval() with anything other than a primitive "
1393 "string value will simply return the value. "
1394 "Is this what you intended?")
1395
1396 (js2-msg "msg.eval.nonstring.strict"
1397 "Calling eval() with anything other than a primitive "
1398 "string value is not allowed in strict mode.")
1399
1400 (js2-msg "msg.bad.destruct.op"
1401 "Invalid destructuring assignment operator")
1402
1403 ;; NativeCall
1404 (js2-msg "msg.only.from.new"
1405 "'%s' may only be invoked from a `new' expression.")
1406
1407 (js2-msg "msg.deprec.ctor"
1408 "The '%s' constructor is deprecated.")
1409
1410 ;; NativeFunction
1411 (js2-msg "msg.no.function.ref.found"
1412 "no source found to decompile function reference %s")
1413
1414 (js2-msg "msg.arg.isnt.array"
1415 "second argument to Function.prototype.apply must be an array")
1416
1417 ;; NativeGlobal
1418 (js2-msg "msg.bad.esc.mask"
1419 "invalid string escape mask")
1420
1421 ;; NativeRegExp
1422 (js2-msg "msg.bad.quant"
1423 "Invalid quantifier %s")
1424
1425 (js2-msg "msg.overlarge.backref"
1426 "Overly large back reference %s")
1427
1428 (js2-msg "msg.overlarge.min"
1429 "Overly large minimum %s")
1430
1431 (js2-msg "msg.overlarge.max"
1432 "Overly large maximum %s")
1433
1434 (js2-msg "msg.zero.quant"
1435 "Zero quantifier %s")
1436
1437 (js2-msg "msg.max.lt.min"
1438 "Maximum %s less than minimum")
1439
1440 (js2-msg "msg.unterm.quant"
1441 "Unterminated quantifier %s")
1442
1443 (js2-msg "msg.unterm.paren"
1444 "Unterminated parenthetical %s")
1445
1446 (js2-msg "msg.unterm.class"
1447 "Unterminated character class %s")
1448
1449 (js2-msg "msg.bad.range"
1450 "Invalid range in character class.")
1451
1452 (js2-msg "msg.trail.backslash"
1453 "Trailing \\ in regular expression.")
1454
1455 (js2-msg "msg.re.unmatched.right.paren"
1456 "unmatched ) in regular expression.")
1457
1458 (js2-msg "msg.no.regexp"
1459 "Regular expressions are not available.")
1460
1461 (js2-msg "msg.bad.backref"
1462 "back-reference exceeds number of capturing parentheses.")
1463
1464 (js2-msg "msg.bad.regexp.compile"
1465 "Only one argument may be specified if the first "
1466 "argument to RegExp.prototype.compile is a RegExp object.")
1467
1468 ;; Parser
1469 (js2-msg "msg.got.syntax.errors"
1470 "Compilation produced %s syntax errors.")
1471
1472 (js2-msg "msg.var.redecl"
1473 "TypeError: redeclaration of var %s.")
1474
1475 (js2-msg "msg.const.redecl"
1476 "TypeError: redeclaration of const %s.")
1477
1478 (js2-msg "msg.let.redecl"
1479 "TypeError: redeclaration of variable %s.")
1480
1481 (js2-msg "msg.parm.redecl"
1482 "TypeError: redeclaration of formal parameter %s.")
1483
1484 (js2-msg "msg.fn.redecl"
1485 "TypeError: redeclaration of function %s.")
1486
1487 (js2-msg "msg.let.decl.not.in.block"
1488 "SyntaxError: let declaration not directly within block")
1489
1490 ;; NodeTransformer
1491 (js2-msg "msg.dup.label"
1492 "duplicated label")
1493
1494 (js2-msg "msg.undef.label"
1495 "undefined label")
1496
1497 (js2-msg "msg.bad.break"
1498 "unlabelled break must be inside loop or switch")
1499
1500 (js2-msg "msg.continue.outside"
1501 "continue must be inside loop")
1502
1503 (js2-msg "msg.continue.nonloop"
1504 "continue can only use labels of iteration statements")
1505
1506 (js2-msg "msg.bad.throw.eol"
1507 "Line terminator is not allowed between the throw "
1508 "keyword and throw expression.")
1509
1510 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1511 "function statement requires a name")
1512
1513 (js2-msg "msg.no.paren.parms"
1514 "missing ( before function parameters.")
1515
1516 (js2-msg "msg.no.parm"
1517 "missing formal parameter")
1518
1519 (js2-msg "msg.no.paren.after.parms"
1520 "missing ) after formal parameters")
1521
1522 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1523 "parameter without default follows parameter with default")
1524
1525 (js2-msg "msg.param.after.rest" ; added by js2-mode
1526 "parameter after rest parameter")
1527
1528 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1529 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1530
1531 (js2-msg "msg.no.brace.body"
1532 "missing '{' before function body")
1533
1534 (js2-msg "msg.no.brace.after.body"
1535 "missing } after function body")
1536
1537 (js2-msg "msg.no.paren.cond"
1538 "missing ( before condition")
1539
1540 (js2-msg "msg.no.paren.after.cond"
1541 "missing ) after condition")
1542
1543 (js2-msg "msg.no.semi.stmt"
1544 "missing ; before statement")
1545
1546 (js2-msg "msg.missing.semi"
1547 "missing ; after statement")
1548
1549 (js2-msg "msg.no.name.after.dot"
1550 "missing name after . operator")
1551
1552 (js2-msg "msg.no.name.after.coloncolon"
1553 "missing name after :: operator")
1554
1555 (js2-msg "msg.no.name.after.dotdot"
1556 "missing name after .. operator")
1557
1558 (js2-msg "msg.no.name.after.xmlAttr"
1559 "missing name after .@")
1560
1561 (js2-msg "msg.no.bracket.index"
1562 "missing ] in index expression")
1563
1564 (js2-msg "msg.no.paren.switch"
1565 "missing ( before switch expression")
1566
1567 (js2-msg "msg.no.paren.after.switch"
1568 "missing ) after switch expression")
1569
1570 (js2-msg "msg.no.brace.switch"
1571 "missing '{' before switch body")
1572
1573 (js2-msg "msg.bad.switch"
1574 "invalid switch statement")
1575
1576 (js2-msg "msg.no.colon.case"
1577 "missing : after case expression")
1578
1579 (js2-msg "msg.double.switch.default"
1580 "double default label in the switch statement")
1581
1582 (js2-msg "msg.no.while.do"
1583 "missing while after do-loop body")
1584
1585 (js2-msg "msg.no.paren.for"
1586 "missing ( after for")
1587
1588 (js2-msg "msg.no.semi.for"
1589 "missing ; after for-loop initializer")
1590
1591 (js2-msg "msg.no.semi.for.cond"
1592 "missing ; after for-loop condition")
1593
1594 (js2-msg "msg.in.after.for.name"
1595 "missing in or of after for")
1596
1597 (js2-msg "msg.no.paren.for.ctrl"
1598 "missing ) after for-loop control")
1599
1600 (js2-msg "msg.no.paren.with"
1601 "missing ( before with-statement object")
1602
1603 (js2-msg "msg.no.paren.after.with"
1604 "missing ) after with-statement object")
1605
1606 (js2-msg "msg.no.paren.after.let"
1607 "missing ( after let")
1608
1609 (js2-msg "msg.no.paren.let"
1610 "missing ) after variable list")
1611
1612 (js2-msg "msg.no.curly.let"
1613 "missing } after let statement")
1614
1615 (js2-msg "msg.bad.return"
1616 "invalid return")
1617
1618 (js2-msg "msg.no.brace.block"
1619 "missing } in compound statement")
1620
1621 (js2-msg "msg.bad.label"
1622 "invalid label")
1623
1624 (js2-msg "msg.bad.var"
1625 "missing variable name")
1626
1627 (js2-msg "msg.bad.var.init"
1628 "invalid variable initialization")
1629
1630 (js2-msg "msg.no.colon.cond"
1631 "missing : in conditional expression")
1632
1633 (js2-msg "msg.no.paren.arg"
1634 "missing ) after argument list")
1635
1636 (js2-msg "msg.no.bracket.arg"
1637 "missing ] after element list")
1638
1639 (js2-msg "msg.bad.prop"
1640 "invalid property id")
1641
1642 (js2-msg "msg.no.colon.prop"
1643 "missing : after property id")
1644
1645 (js2-msg "msg.no.brace.prop"
1646 "missing } after property list")
1647
1648 (js2-msg "msg.no.paren"
1649 "missing ) in parenthetical")
1650
1651 (js2-msg "msg.reserved.id"
1652 "identifier is a reserved word")
1653
1654 (js2-msg "msg.no.paren.catch"
1655 "missing ( before catch-block condition")
1656
1657 (js2-msg "msg.bad.catchcond"
1658 "invalid catch block condition")
1659
1660 (js2-msg "msg.catch.unreachable"
1661 "any catch clauses following an unqualified catch are unreachable")
1662
1663 (js2-msg "msg.no.brace.try"
1664 "missing '{' before try block")
1665
1666 (js2-msg "msg.no.brace.catchblock"
1667 "missing '{' before catch-block body")
1668
1669 (js2-msg "msg.try.no.catchfinally"
1670 "'try' without 'catch' or 'finally'")
1671
1672 (js2-msg "msg.no.return.value"
1673 "function %s does not always return a value")
1674
1675 (js2-msg "msg.anon.no.return.value"
1676 "anonymous function does not always return a value")
1677
1678 (js2-msg "msg.return.inconsistent"
1679 "return statement is inconsistent with previous usage")
1680
1681 (js2-msg "msg.generator.returns"
1682 "TypeError: legacy generator function '%s' returns a value")
1683
1684 (js2-msg "msg.anon.generator.returns"
1685 "TypeError: anonymous legacy generator function returns a value")
1686
1687 (js2-msg "msg.syntax"
1688 "syntax error")
1689
1690 (js2-msg "msg.unexpected.eof"
1691 "Unexpected end of file")
1692
1693 (js2-msg "msg.XML.bad.form"
1694 "illegally formed XML syntax")
1695
1696 (js2-msg "msg.XML.not.available"
1697 "XML runtime not available")
1698
1699 (js2-msg "msg.too.deep.parser.recursion"
1700 "Too deep recursion while parsing")
1701
1702 (js2-msg "msg.no.side.effects"
1703 "Code has no side effects")
1704
1705 (js2-msg "msg.extra.trailing.comma"
1706 "Trailing comma is not supported in some browsers")
1707
1708 (js2-msg "msg.array.trailing.comma"
1709 "Trailing comma yields different behavior across browsers")
1710
1711 (js2-msg "msg.equal.as.assign"
1712 (concat "Test for equality (==) mistyped as assignment (=)?"
1713 " (parenthesize to suppress warning)"))
1714
1715 (js2-msg "msg.var.hides.arg"
1716 "Variable %s hides argument")
1717
1718 (js2-msg "msg.destruct.assign.no.init"
1719 "Missing = in destructuring declaration")
1720
1721 ;; ScriptRuntime
1722 (js2-msg "msg.no.properties"
1723 "%s has no properties.")
1724
1725 (js2-msg "msg.invalid.iterator"
1726 "Invalid iterator value")
1727
1728 (js2-msg "msg.iterator.primitive"
1729 "__iterator__ returned a primitive value")
1730
1731 (js2-msg "msg.assn.create.strict"
1732 "Assignment to undeclared variable %s")
1733
1734 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1735 "Undeclared variable or function '%s'")
1736
1737 (js2-msg "msg.ref.undefined.prop"
1738 "Reference to undefined property '%s'")
1739
1740 (js2-msg "msg.prop.not.found"
1741 "Property %s not found.")
1742
1743 (js2-msg "msg.invalid.type"
1744 "Invalid JavaScript value of type %s")
1745
1746 (js2-msg "msg.primitive.expected"
1747 "Primitive type expected (had %s instead)")
1748
1749 (js2-msg "msg.namespace.expected"
1750 "Namespace object expected to left of :: (found %s instead)")
1751
1752 (js2-msg "msg.null.to.object"
1753 "Cannot convert null to an object.")
1754
1755 (js2-msg "msg.undef.to.object"
1756 "Cannot convert undefined to an object.")
1757
1758 (js2-msg "msg.cyclic.value"
1759 "Cyclic %s value not allowed.")
1760
1761 (js2-msg "msg.is.not.defined"
1762 "'%s' is not defined.")
1763
1764 (js2-msg "msg.undef.prop.read"
1765 "Cannot read property '%s' from %s")
1766
1767 (js2-msg "msg.undef.prop.write"
1768 "Cannot set property '%s' of %s to '%s'")
1769
1770 (js2-msg "msg.undef.prop.delete"
1771 "Cannot delete property '%s' of %s")
1772
1773 (js2-msg "msg.undef.method.call"
1774 "Cannot call method '%s' of %s")
1775
1776 (js2-msg "msg.undef.with"
1777 "Cannot apply 'with' to %s")
1778
1779 (js2-msg "msg.isnt.function"
1780 "%s is not a function, it is %s.")
1781
1782 (js2-msg "msg.isnt.function.in"
1783 "Cannot call property %s in object %s. "
1784 "It is not a function, it is '%s'.")
1785
1786 (js2-msg "msg.function.not.found"
1787 "Cannot find function %s.")
1788
1789 (js2-msg "msg.function.not.found.in"
1790 "Cannot find function %s in object %s.")
1791
1792 (js2-msg "msg.isnt.xml.object"
1793 "%s is not an xml object.")
1794
1795 (js2-msg "msg.no.ref.to.get"
1796 "%s is not a reference to read reference value.")
1797
1798 (js2-msg "msg.no.ref.to.set"
1799 "%s is not a reference to set reference value to %s.")
1800
1801 (js2-msg "msg.no.ref.from.function"
1802 "Function %s can not be used as the left-hand "
1803 "side of assignment or as an operand of ++ or -- operator.")
1804
1805 (js2-msg "msg.bad.default.value"
1806 "Object's getDefaultValue() method returned an object.")
1807
1808 (js2-msg "msg.instanceof.not.object"
1809 "Can't use instanceof on a non-object.")
1810
1811 (js2-msg "msg.instanceof.bad.prototype"
1812 "'prototype' property of %s is not an object.")
1813
1814 (js2-msg "msg.bad.radix"
1815 "illegal radix %s.")
1816
1817 ;; ScriptableObject
1818 (js2-msg "msg.default.value"
1819 "Cannot find default value for object.")
1820
1821 (js2-msg "msg.zero.arg.ctor"
1822 "Cannot load class '%s' which has no zero-parameter constructor.")
1823
1824 (js2-msg "msg.ctor.multiple.parms"
1825 "Can't define constructor or class %s since more than "
1826 "one constructor has multiple parameters.")
1827
1828 (js2-msg "msg.extend.scriptable"
1829 "%s must extend ScriptableObject in order to define property %s.")
1830
1831 (js2-msg "msg.bad.getter.parms"
1832 "In order to define a property, getter %s must have zero "
1833 "parameters or a single ScriptableObject parameter.")
1834
1835 (js2-msg "msg.obj.getter.parms"
1836 "Expected static or delegated getter %s to take "
1837 "a ScriptableObject parameter.")
1838
1839 (js2-msg "msg.getter.static"
1840 "Getter and setter must both be static or neither be static.")
1841
1842 (js2-msg "msg.setter.return"
1843 "Setter must have void return type: %s")
1844
1845 (js2-msg "msg.setter2.parms"
1846 "Two-parameter setter must take a ScriptableObject as "
1847 "its first parameter.")
1848
1849 (js2-msg "msg.setter1.parms"
1850 "Expected single parameter setter for %s")
1851
1852 (js2-msg "msg.setter2.expected"
1853 "Expected static or delegated setter %s to take two parameters.")
1854
1855 (js2-msg "msg.setter.parms"
1856 "Expected either one or two parameters for setter.")
1857
1858 (js2-msg "msg.setter.bad.type"
1859 "Unsupported parameter type '%s' in setter '%s'.")
1860
1861 (js2-msg "msg.add.sealed"
1862 "Cannot add a property to a sealed object: %s.")
1863
1864 (js2-msg "msg.remove.sealed"
1865 "Cannot remove a property from a sealed object: %s.")
1866
1867 (js2-msg "msg.modify.sealed"
1868 "Cannot modify a property of a sealed object: %s.")
1869
1870 (js2-msg "msg.modify.readonly"
1871 "Cannot modify readonly property: %s.")
1872
1873 ;; TokenStream
1874 (js2-msg "msg.missing.exponent"
1875 "missing exponent")
1876
1877 (js2-msg "msg.caught.nfe"
1878 "number format error")
1879
1880 (js2-msg "msg.unterminated.string.lit"
1881 "unterminated string literal")
1882
1883 (js2-msg "msg.unterminated.comment"
1884 "unterminated comment")
1885
1886 (js2-msg "msg.unterminated.re.lit"
1887 "unterminated regular expression literal")
1888
1889 (js2-msg "msg.invalid.re.flag"
1890 "invalid flag after regular expression")
1891
1892 (js2-msg "msg.no.re.input.for"
1893 "no input for %s")
1894
1895 (js2-msg "msg.illegal.character"
1896 "illegal character")
1897
1898 (js2-msg "msg.invalid.escape"
1899 "invalid Unicode escape sequence")
1900
1901 (js2-msg "msg.bad.namespace"
1902 "not a valid default namespace statement. "
1903 "Syntax is: default xml namespace = EXPRESSION;")
1904
1905 ;; TokensStream warnings
1906 (js2-msg "msg.bad.octal.literal"
1907 "illegal octal literal digit %s; "
1908 "interpreting it as a decimal digit")
1909
1910 (js2-msg "msg.reserved.keyword"
1911 "illegal usage of future reserved keyword %s; "
1912 "interpreting it as ordinary identifier")
1913
1914 (js2-msg "msg.script.is.not.constructor"
1915 "Script objects are not constructors.")
1916
1917 ;; Arrays
1918 (js2-msg "msg.arraylength.bad"
1919 "Inappropriate array length.")
1920
1921 ;; Arrays
1922 (js2-msg "msg.arraylength.too.big"
1923 "Array length %s exceeds supported capacity limit.")
1924
1925 ;; URI
1926 (js2-msg "msg.bad.uri"
1927 "Malformed URI sequence.")
1928
1929 ;; Number
1930 (js2-msg "msg.bad.precision"
1931 "Precision %s out of range.")
1932
1933 ;; NativeGenerator
1934 (js2-msg "msg.send.newborn"
1935 "Attempt to send value to newborn generator")
1936
1937 (js2-msg "msg.already.exec.gen"
1938 "Already executing generator")
1939
1940 (js2-msg "msg.StopIteration.invalid"
1941 "StopIteration may not be changed to an arbitrary object.")
1942
1943 ;; Interpreter
1944 (js2-msg "msg.yield.closing"
1945 "Yield from closing generator")
1946
1947 ;;; Tokens Buffer
1948
1949 (defconst js2-ti-max-lookahead 2)
1950 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1951
1952 ;; Have to call `js2-init-scanner' to initialize the values.
1953 (js2-deflocal js2-ti-tokens nil)
1954 (js2-deflocal js2-ti-tokens-cursor nil)
1955 (js2-deflocal js2-ti-lookahead nil)
1956
1957 (defun js2-new-token (offset)
1958 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
1959 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
1960 (aset js2-ti-tokens js2-ti-tokens-cursor token)
1961 token))
1962
1963 (defsubst js2-current-token ()
1964 (aref js2-ti-tokens js2-ti-tokens-cursor))
1965
1966 (defsubst js2-current-token-string ()
1967 (js2-token-string (js2-current-token)))
1968
1969 (defsubst js2-current-token-type ()
1970 (js2-token-type (js2-current-token)))
1971
1972 (defsubst js2-current-token-beg ()
1973 (js2-token-beg (js2-current-token)))
1974
1975 (defsubst js2-current-token-end ()
1976 (js2-token-end (js2-current-token)))
1977
1978 (defun js2-current-token-len ()
1979 (let ((token (js2-current-token)))
1980 (- (js2-token-end token)
1981 (js2-token-beg token))))
1982
1983 (defun js2-ts-seek (state)
1984 (setq js2-ts-lineno (js2-ts-state-lineno state)
1985 js2-ts-cursor (js2-ts-state-cursor state)
1986 js2-ti-tokens (js2-ts-state-tokens state)
1987 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
1988 js2-ti-lookahead (js2-ts-state-lookahead state)))
1989
1990 ;;; Utilities
1991
1992 (defun js2-delete-if (predicate list)
1993 "Remove all items satisfying PREDICATE in LIST."
1994 (loop for item in list
1995 if (not (funcall predicate item))
1996 collect item))
1997
1998 (defun js2-position (element list)
1999 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2000 Returns nil if element is not found in the list."
2001 (let ((count 0)
2002 found)
2003 (while (and list (not found))
2004 (if (eq element (car list))
2005 (setq found t)
2006 (setq count (1+ count)
2007 list (cdr list))))
2008 (if found count)))
2009
2010 (defun js2-find-if (predicate list)
2011 "Find first item satisfying PREDICATE in LIST."
2012 (let (result)
2013 (while (and list (not result))
2014 (if (funcall predicate (car list))
2015 (setq result (car list)))
2016 (setq list (cdr list)))
2017 result))
2018
2019 (defmacro js2-time (form)
2020 "Evaluate FORM, discard result, and return elapsed time in sec."
2021 (declare (debug t))
2022 (let ((beg (make-symbol "--js2-time-beg--"))
2023 (delta (make-symbol "--js2-time-end--")))
2024 `(let ((,beg (current-time))
2025 ,delta)
2026 ,form
2027 (/ (truncate (* (- (float-time (current-time))
2028 (float-time ,beg))
2029 10000))
2030 10000.0))))
2031
2032 (defsubst js2-same-line (pos)
2033 "Return t if POS is on the same line as current point."
2034 (and (>= pos (point-at-bol))
2035 (<= pos (point-at-eol))))
2036
2037 (defun js2-code-bug ()
2038 "Signal an error when we encounter an unexpected code path."
2039 (error "failed assertion"))
2040
2041 (defsubst js2-record-text-property (beg end prop value)
2042 "Record a text property to set when parsing finishes."
2043 (push (list beg end prop value) js2-mode-deferred-properties))
2044
2045 ;; I'd like to associate errors with nodes, but for now the
2046 ;; easiest thing to do is get the context info from the last token.
2047 (defun js2-record-parse-error (msg &optional arg pos len)
2048 (push (list (list msg arg)
2049 (or pos (js2-current-token-beg))
2050 (or len (js2-current-token-len)))
2051 js2-parsed-errors))
2052
2053 (defun js2-report-error (msg &optional msg-arg pos len)
2054 "Signal a syntax error or record a parse error."
2055 (if js2-recover-from-parse-errors
2056 (js2-record-parse-error msg msg-arg pos len)
2057 (signal 'js2-syntax-error
2058 (list msg
2059 js2-ts-lineno
2060 (save-excursion
2061 (goto-char js2-ts-cursor)
2062 (current-column))
2063 js2-ts-hit-eof))))
2064
2065 (defun js2-report-warning (msg &optional msg-arg pos len face)
2066 (if js2-compiler-report-warning-as-error
2067 (js2-report-error msg msg-arg pos len)
2068 (push (list (list msg msg-arg)
2069 (or pos (js2-current-token-beg))
2070 (or len (js2-current-token-len))
2071 face)
2072 js2-parsed-warnings)))
2073
2074 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2075 (if js2-compiler-strict-mode
2076 (js2-report-warning msg-id msg-arg beg
2077 (and beg end (- end beg)))))
2078
2079 (put 'js2-syntax-error 'error-conditions
2080 '(error syntax-error js2-syntax-error))
2081 (put 'js2-syntax-error 'error-message "Syntax error")
2082
2083 (put 'js2-parse-error 'error-conditions
2084 '(error parse-error js2-parse-error))
2085 (put 'js2-parse-error 'error-message "Parse error")
2086
2087 (defmacro js2-clear-flag (flags flag)
2088 `(setq ,flags (logand ,flags (lognot ,flag))))
2089
2090 (defmacro js2-set-flag (flags flag)
2091 "Logical-or FLAG into FLAGS."
2092 `(setq ,flags (logior ,flags ,flag)))
2093
2094 (defsubst js2-flag-set-p (flags flag)
2095 (/= 0 (logand flags flag)))
2096
2097 (defsubst js2-flag-not-set-p (flags flag)
2098 (zerop (logand flags flag)))
2099
2100 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2101 "Evaluate BODY with the _ character set to be word-syntax."
2102 (declare (indent 0) (debug t))
2103 (let ((old-syntax (make-symbol "old-syntax")))
2104 `(let ((,old-syntax (string (char-syntax ?_))))
2105 (unwind-protect
2106 (progn
2107 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2108 ,@body)
2109 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2110
2111 (defsubst js2-char-uppercase-p (c)
2112 "Return t if C is an uppercase character.
2113 Handles unicode and latin chars properly."
2114 (/= c (downcase c)))
2115
2116 (defsubst js2-char-lowercase-p (c)
2117 "Return t if C is an uppercase character.
2118 Handles unicode and latin chars properly."
2119 (/= c (upcase c)))
2120
2121 ;;; AST struct and function definitions
2122
2123 ;; flags for ast node property 'member-type (used for e4x operators)
2124 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2125 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2126 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2127
2128 (defsubst js2-relpos (pos anchor)
2129 "Convert POS to be relative to ANCHOR.
2130 If POS is nil, returns nil."
2131 (and pos (- pos anchor)))
2132
2133 (defun js2-make-pad (indent)
2134 (if (zerop indent)
2135 ""
2136 (make-string (* indent js2-basic-offset) ? )))
2137
2138 (defun js2-visit-ast (node callback)
2139 "Visit every node in ast NODE with visitor CALLBACK.
2140
2141 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2142 called twice: once to visit the node, and again after all the node's
2143 children have been processed. The END-P argument is nil on the first
2144 call and non-nil on the second call. The return value of the callback
2145 affects the traversal: if non-nil, the children of NODE are processed.
2146 If the callback returns nil, or if the node has no children, then the
2147 callback is called immediately with a non-nil END-P argument.
2148
2149 The node traversal is approximately lexical-order, although there
2150 are currently no guarantees around this."
2151 (when node
2152 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2153 ;; visit the node
2154 (when (funcall callback node nil)
2155 ;; visit the kids
2156 (cond
2157 ((eq vfunc 'js2-visit-none)
2158 nil) ; don't even bother calling it
2159 ;; Each AST node type has to define a `js2-visitor' function
2160 ;; that takes a node and a callback, and calls `js2-visit-ast'
2161 ;; on each child of the node.
2162 (vfunc
2163 (funcall vfunc node callback))
2164 (t
2165 (error "%s does not define a visitor-traversal function"
2166 (aref node 0)))))
2167 ;; call the end-visit
2168 (funcall callback node t))))
2169
2170 (defstruct (js2-node
2171 (:constructor nil)) ; abstract
2172 "Base AST node type."
2173 (type -1) ; token type
2174 (pos -1) ; start position of this AST node in parsed input
2175 (len 1) ; num characters spanned by the node
2176 props ; optional node property list (an alist)
2177 parent) ; link to parent node; null for root
2178
2179 (defsubst js2-node-get-prop (node prop &optional default)
2180 (or (cadr (assoc prop (js2-node-props node))) default))
2181
2182 (defsubst js2-node-set-prop (node prop value)
2183 (setf (js2-node-props node)
2184 (cons (list prop value) (js2-node-props node))))
2185
2186 (defun js2-fixup-starts (n nodes)
2187 "Adjust the start positions of NODES to be relative to N.
2188 Any node in the list may be nil, for convenience."
2189 (dolist (node nodes)
2190 (when node
2191 (setf (js2-node-pos node) (- (js2-node-pos node)
2192 (js2-node-pos n))))))
2193
2194 (defun js2-node-add-children (parent &rest nodes)
2195 "Set parent node of NODES to PARENT, and return PARENT.
2196 Does nothing if we're not recording parent links.
2197 If any given node in NODES is nil, doesn't record that link."
2198 (js2-fixup-starts parent nodes)
2199 (dolist (node nodes)
2200 (and node
2201 (setf (js2-node-parent node) parent))))
2202
2203 ;; Non-recursive since it's called a frightening number of times.
2204 (defun js2-node-abs-pos (n)
2205 (let ((pos (js2-node-pos n)))
2206 (while (setq n (js2-node-parent n))
2207 (setq pos (+ pos (js2-node-pos n))))
2208 pos))
2209
2210 (defsubst js2-node-abs-end (n)
2211 "Return absolute buffer position of end of N."
2212 (+ (js2-node-abs-pos n) (js2-node-len n)))
2213
2214 ;; It's important to make sure block nodes have a Lisp list for the
2215 ;; child nodes, to limit printing recursion depth in an AST that
2216 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2217 ;; a sufficiently large vector tree.
2218
2219 (defstruct (js2-block-node
2220 (:include js2-node)
2221 (:constructor nil)
2222 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2223 (pos (js2-current-token-beg))
2224 len
2225 props
2226 kids)))
2227 "A block of statements."
2228 kids) ; a Lisp list of the child statement nodes
2229
2230 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2231 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2232
2233 (defun js2-visit-block (ast callback)
2234 "Visit the `js2-block-node' children of AST."
2235 (dolist (kid (js2-block-node-kids ast))
2236 (js2-visit-ast kid callback)))
2237
2238 (defun js2-print-block (n i)
2239 (let ((pad (js2-make-pad i)))
2240 (insert pad "{\n")
2241 (dolist (kid (js2-block-node-kids n))
2242 (js2-print-ast kid (1+ i)))
2243 (insert pad "}")))
2244
2245 (defstruct (js2-scope
2246 (:include js2-block-node)
2247 (:constructor nil)
2248 (:constructor make-js2-scope (&key (type js2-BLOCK)
2249 (pos (js2-current-token-beg))
2250 len
2251 kids)))
2252 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2253 ;; I don't have one of those handy, so I'll use an alist for now.
2254 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2255 ;; and is much lighter-weight to construct (both CPU and mem).
2256 ;; The keys are interned strings (symbols) for faster lookup.
2257 ;; Should switch to hybrid alist/hashtable eventually.
2258 symbol-table ; an alist of (symbol . js2-symbol)
2259 parent-scope ; a `js2-scope'
2260 top) ; top-level `js2-scope' (script/function)
2261
2262 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2263 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2264
2265 (defun js2-node-get-enclosing-scope (node)
2266 "Return the innermost `js2-scope' node surrounding NODE.
2267 Returns nil if there is no enclosing scope node."
2268 (let ((parent (js2-node-parent node)))
2269 (while (not (js2-scope-p parent))
2270 (setq parent (js2-node-parent parent)))
2271 parent))
2272
2273 (defun js2-get-defining-scope (scope name)
2274 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2275 Returns `js2-scope' in which NAME is defined, or nil if not found."
2276 (let ((sym (if (symbolp name)
2277 name
2278 (intern name)))
2279 table
2280 result
2281 (continue t))
2282 (while (and scope continue)
2283 (if (and (setq table (js2-scope-symbol-table scope))
2284 (assq sym table))
2285 (setq continue nil
2286 result scope)
2287 (setq scope (js2-scope-parent-scope scope))))
2288 result))
2289
2290 (defun js2-scope-get-symbol (scope name)
2291 "Return symbol table entry for NAME in SCOPE.
2292 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2293 (and (js2-scope-symbol-table scope)
2294 (cdr (assq (if (symbolp name)
2295 name
2296 (intern name))
2297 (js2-scope-symbol-table scope)))))
2298
2299 (defun js2-scope-put-symbol (scope name symbol)
2300 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2301 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2302 (let* ((table (js2-scope-symbol-table scope))
2303 (sym (if (symbolp name) name (intern name)))
2304 (entry (assq sym table)))
2305 (if entry
2306 (setcdr entry symbol)
2307 (push (cons sym symbol)
2308 (js2-scope-symbol-table scope)))))
2309
2310 (defstruct (js2-symbol
2311 (:constructor nil)
2312 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2313 "A symbol table entry."
2314 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2315 ;; js2-LET, or js2-CONST
2316 decl-type
2317 name ; string
2318 ast-node) ; a `js2-node'
2319
2320 (defstruct (js2-error-node
2321 (:include js2-node)
2322 (:constructor nil) ; silence emacs21 byte-compiler
2323 (:constructor make-js2-error-node (&key (type js2-ERROR)
2324 (pos (js2-current-token-beg))
2325 len)))
2326 "AST node representing a parse error.")
2327
2328 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2329 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2330
2331 (defstruct (js2-script-node
2332 (:include js2-scope)
2333 (:constructor nil)
2334 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2335 (pos (js2-current-token-beg))
2336 len
2337 ;; FIXME: What are those?
2338 var-decls
2339 fun-decls)))
2340 functions ; Lisp list of nested functions
2341 regexps ; Lisp list of (string . flags)
2342 symbols ; alist (every symbol gets unique index)
2343 (param-count 0)
2344 var-names ; vector of string names
2345 consts ; bool-vector matching var-decls
2346 (temp-number 0)) ; for generating temp variables
2347
2348 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2349 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2350
2351 (defun js2-print-script (node indent)
2352 (dolist (kid (js2-block-node-kids node))
2353 (js2-print-ast kid indent)))
2354
2355 (defstruct (js2-ast-root
2356 (:include js2-script-node)
2357 (:constructor nil)
2358 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2359 (pos (js2-current-token-beg))
2360 len
2361 buffer)))
2362 "The root node of a js2 AST."
2363 buffer ; the source buffer from which the code was parsed
2364 comments ; a Lisp list of comments, ordered by start position
2365 errors ; a Lisp list of errors found during parsing
2366 warnings ; a Lisp list of warnings found during parsing
2367 node-count) ; number of nodes in the tree, including the root
2368
2369 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2370 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2371
2372 (defun js2-visit-ast-root (ast callback)
2373 (dolist (kid (js2-ast-root-kids ast))
2374 (js2-visit-ast kid callback))
2375 (dolist (comment (js2-ast-root-comments ast))
2376 (js2-visit-ast comment callback)))
2377
2378 (defstruct (js2-comment-node
2379 (:include js2-node)
2380 (:constructor nil)
2381 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2382 (pos (js2-current-token-beg))
2383 len
2384 format)))
2385 format) ; 'line, 'block, 'jsdoc or 'html
2386
2387 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2388 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2389
2390 (defun js2-print-comment (n i)
2391 ;; We really ought to link end-of-line comments to their nodes.
2392 ;; Or maybe we could add a new comment type, 'endline.
2393 (insert (js2-make-pad i)
2394 (js2-node-string n)))
2395
2396 (defstruct (js2-expr-stmt-node
2397 (:include js2-node)
2398 (:constructor nil)
2399 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2400 (pos js2-ts-cursor)
2401 len
2402 expr)))
2403 "An expression statement."
2404 expr)
2405
2406 (defsubst js2-expr-stmt-node-set-has-result (node)
2407 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2408 (setf (js2-node-type node) js2-EXPR_RESULT))
2409
2410 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2411 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2412
2413 (defun js2-visit-expr-stmt-node (n v)
2414 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2415
2416 (defun js2-print-expr-stmt-node (n indent)
2417 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2418 (insert ";\n"))
2419
2420 (defstruct (js2-loop-node
2421 (:include js2-scope)
2422 (:constructor nil))
2423 "Abstract supertype of loop nodes."
2424 body ; a `js2-block-node'
2425 lp ; position of left-paren, nil if omitted
2426 rp) ; position of right-paren, nil if omitted
2427
2428 (defstruct (js2-do-node
2429 (:include js2-loop-node)
2430 (:constructor nil)
2431 (:constructor make-js2-do-node (&key (type js2-DO)
2432 (pos (js2-current-token-beg))
2433 len
2434 body
2435 condition
2436 while-pos
2437 lp
2438 rp)))
2439 "AST node for do-loop."
2440 condition ; while (expression)
2441 while-pos) ; buffer position of 'while' keyword
2442
2443 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2444 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2445
2446 (defun js2-visit-do-node (n v)
2447 (js2-visit-ast (js2-do-node-body n) v)
2448 (js2-visit-ast (js2-do-node-condition n) v))
2449
2450 (defun js2-print-do-node (n i)
2451 (let ((pad (js2-make-pad i)))
2452 (insert pad "do {\n")
2453 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2454 (js2-print-ast kid (1+ i)))
2455 (insert pad "} while (")
2456 (js2-print-ast (js2-do-node-condition n) 0)
2457 (insert ");\n")))
2458
2459 (defstruct (js2-while-node
2460 (:include js2-loop-node)
2461 (:constructor nil)
2462 (:constructor make-js2-while-node (&key (type js2-WHILE)
2463 (pos (js2-current-token-beg))
2464 len body
2465 condition lp
2466 rp)))
2467 "AST node for while-loop."
2468 condition) ; while-condition
2469
2470 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2471 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2472
2473 (defun js2-visit-while-node (n v)
2474 (js2-visit-ast (js2-while-node-condition n) v)
2475 (js2-visit-ast (js2-while-node-body n) v))
2476
2477 (defun js2-print-while-node (n i)
2478 (let ((pad (js2-make-pad i)))
2479 (insert pad "while (")
2480 (js2-print-ast (js2-while-node-condition n) 0)
2481 (insert ") {\n")
2482 (js2-print-body (js2-while-node-body n) (1+ i))
2483 (insert pad "}\n")))
2484
2485 (defstruct (js2-for-node
2486 (:include js2-loop-node)
2487 (:constructor nil)
2488 (:constructor make-js2-for-node (&key (type js2-FOR)
2489 (pos js2-ts-cursor)
2490 len body init
2491 condition
2492 update lp rp)))
2493 "AST node for a C-style for-loop."
2494 init ; initialization expression
2495 condition ; loop condition
2496 update) ; update clause
2497
2498 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2499 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2500
2501 (defun js2-visit-for-node (n v)
2502 (js2-visit-ast (js2-for-node-init n) v)
2503 (js2-visit-ast (js2-for-node-condition n) v)
2504 (js2-visit-ast (js2-for-node-update n) v)
2505 (js2-visit-ast (js2-for-node-body n) v))
2506
2507 (defun js2-print-for-node (n i)
2508 (let ((pad (js2-make-pad i)))
2509 (insert pad "for (")
2510 (js2-print-ast (js2-for-node-init n) 0)
2511 (insert "; ")
2512 (js2-print-ast (js2-for-node-condition n) 0)
2513 (insert "; ")
2514 (js2-print-ast (js2-for-node-update n) 0)
2515 (insert ") {\n")
2516 (js2-print-body (js2-for-node-body n) (1+ i))
2517 (insert pad "}\n")))
2518
2519 (defstruct (js2-for-in-node
2520 (:include js2-loop-node)
2521 (:constructor nil)
2522 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2523 (pos js2-ts-cursor)
2524 len body
2525 iterator
2526 object
2527 in-pos
2528 each-pos
2529 foreach-p forof-p
2530 lp rp)))
2531 "AST node for a for..in loop."
2532 iterator ; [var] foo in ...
2533 object ; object over which we're iterating
2534 in-pos ; buffer position of 'in' keyword
2535 each-pos ; buffer position of 'each' keyword, if foreach-p
2536 foreach-p ; t if it's a for-each loop
2537 forof-p) ; t if it's a for-of loop
2538
2539 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2540 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2541
2542 (defun js2-visit-for-in-node (n v)
2543 (js2-visit-ast (js2-for-in-node-iterator n) v)
2544 (js2-visit-ast (js2-for-in-node-object n) v)
2545 (js2-visit-ast (js2-for-in-node-body n) v))
2546
2547 (defun js2-print-for-in-node (n i)
2548 (let ((pad (js2-make-pad i))
2549 (foreach (js2-for-in-node-foreach-p n))
2550 (forof (js2-for-in-node-forof-p n)))
2551 (insert pad "for ")
2552 (if foreach
2553 (insert "each "))
2554 (insert "(")
2555 (js2-print-ast (js2-for-in-node-iterator n) 0)
2556 (insert (if forof " of " " in "))
2557 (js2-print-ast (js2-for-in-node-object n) 0)
2558 (insert ") {\n")
2559 (js2-print-body (js2-for-in-node-body n) (1+ i))
2560 (insert pad "}\n")))
2561
2562 (defstruct (js2-return-node
2563 (:include js2-node)
2564 (:constructor nil)
2565 (:constructor make-js2-return-node (&key (type js2-RETURN)
2566 (pos js2-ts-cursor)
2567 len
2568 retval)))
2569 "AST node for a return statement."
2570 retval) ; expression to return, or 'undefined
2571
2572 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2573 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2574
2575 (defun js2-visit-return-node (n v)
2576 (js2-visit-ast (js2-return-node-retval n) v))
2577
2578 (defun js2-print-return-node (n i)
2579 (insert (js2-make-pad i) "return")
2580 (when (js2-return-node-retval n)
2581 (insert " ")
2582 (js2-print-ast (js2-return-node-retval n) 0))
2583 (insert ";\n"))
2584
2585 (defstruct (js2-if-node
2586 (:include js2-node)
2587 (:constructor nil)
2588 (:constructor make-js2-if-node (&key (type js2-IF)
2589 (pos js2-ts-cursor)
2590 len condition
2591 then-part
2592 else-pos
2593 else-part lp
2594 rp)))
2595 "AST node for an if-statement."
2596 condition ; expression
2597 then-part ; statement or block
2598 else-pos ; optional buffer position of 'else' keyword
2599 else-part ; optional statement or block
2600 lp ; position of left-paren, nil if omitted
2601 rp) ; position of right-paren, nil if omitted
2602
2603 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2604 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2605
2606 (defun js2-visit-if-node (n v)
2607 (js2-visit-ast (js2-if-node-condition n) v)
2608 (js2-visit-ast (js2-if-node-then-part n) v)
2609 (js2-visit-ast (js2-if-node-else-part n) v))
2610
2611 (defun js2-print-if-node (n i)
2612 (let ((pad (js2-make-pad i))
2613 (then-part (js2-if-node-then-part n))
2614 (else-part (js2-if-node-else-part n)))
2615 (insert pad "if (")
2616 (js2-print-ast (js2-if-node-condition n) 0)
2617 (insert ") {\n")
2618 (js2-print-body then-part (1+ i))
2619 (insert pad "}")
2620 (cond
2621 ((not else-part)
2622 (insert "\n"))
2623 ((js2-if-node-p else-part)
2624 (insert " else ")
2625 (js2-print-body else-part i))
2626 (t
2627 (insert " else {\n")
2628 (js2-print-body else-part (1+ i))
2629 (insert pad "}\n")))))
2630
2631 (defstruct (js2-try-node
2632 (:include js2-node)
2633 (:constructor nil)
2634 (:constructor make-js2-try-node (&key (type js2-TRY)
2635 (pos js2-ts-cursor)
2636 len
2637 try-block
2638 catch-clauses
2639 finally-block)))
2640 "AST node for a try-statement."
2641 try-block
2642 catch-clauses ; a Lisp list of `js2-catch-node'
2643 finally-block) ; a `js2-finally-node'
2644
2645 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2646 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2647
2648 (defun js2-visit-try-node (n v)
2649 (js2-visit-ast (js2-try-node-try-block n) v)
2650 (dolist (clause (js2-try-node-catch-clauses n))
2651 (js2-visit-ast clause v))
2652 (js2-visit-ast (js2-try-node-finally-block n) v))
2653
2654 (defun js2-print-try-node (n i)
2655 (let ((pad (js2-make-pad i))
2656 (catches (js2-try-node-catch-clauses n))
2657 (finally (js2-try-node-finally-block n)))
2658 (insert pad "try {\n")
2659 (js2-print-body (js2-try-node-try-block n) (1+ i))
2660 (insert pad "}")
2661 (when catches
2662 (dolist (catch catches)
2663 (js2-print-ast catch i)))
2664 (if finally
2665 (js2-print-ast finally i)
2666 (insert "\n"))))
2667
2668 (defstruct (js2-catch-node
2669 (:include js2-node)
2670 (:constructor nil)
2671 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2672 (pos js2-ts-cursor)
2673 len
2674 param
2675 guard-kwd
2676 guard-expr
2677 block lp
2678 rp)))
2679 "AST node for a catch clause."
2680 param ; destructuring form or simple name node
2681 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2682 guard-expr ; catch condition, a `js2-node'
2683 block ; statements, a `js2-block-node'
2684 lp ; buffer position of left-paren, nil if omitted
2685 rp) ; buffer position of right-paren, nil if omitted
2686
2687 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2688 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2689
2690 (defun js2-visit-catch-node (n v)
2691 (js2-visit-ast (js2-catch-node-param n) v)
2692 (when (js2-catch-node-guard-kwd n)
2693 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2694 (js2-visit-ast (js2-catch-node-block n) v))
2695
2696 (defun js2-print-catch-node (n i)
2697 (let ((pad (js2-make-pad i))
2698 (guard-kwd (js2-catch-node-guard-kwd n))
2699 (guard-expr (js2-catch-node-guard-expr n)))
2700 (insert " catch (")
2701 (js2-print-ast (js2-catch-node-param n) 0)
2702 (when guard-kwd
2703 (insert " if ")
2704 (js2-print-ast guard-expr 0))
2705 (insert ") {\n")
2706 (js2-print-body (js2-catch-node-block n) (1+ i))
2707 (insert pad "}")))
2708
2709 (defstruct (js2-finally-node
2710 (:include js2-node)
2711 (:constructor nil)
2712 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2713 (pos js2-ts-cursor)
2714 len body)))
2715 "AST node for a finally clause."
2716 body) ; a `js2-node', often but not always a block node
2717
2718 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2719 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2720
2721 (defun js2-visit-finally-node (n v)
2722 (js2-visit-ast (js2-finally-node-body n) v))
2723
2724 (defun js2-print-finally-node (n i)
2725 (let ((pad (js2-make-pad i)))
2726 (insert " finally {\n")
2727 (js2-print-body (js2-finally-node-body n) (1+ i))
2728 (insert pad "}\n")))
2729
2730 (defstruct (js2-switch-node
2731 (:include js2-node)
2732 (:constructor nil)
2733 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2734 (pos js2-ts-cursor)
2735 len
2736 discriminant
2737 cases lp
2738 rp)))
2739 "AST node for a switch statement."
2740 discriminant ; a `js2-node' (switch expression)
2741 cases ; a Lisp list of `js2-case-node'
2742 lp ; position of open-paren for discriminant, nil if omitted
2743 rp) ; position of close-paren for discriminant, nil if omitted
2744
2745 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2746 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2747
2748 (defun js2-visit-switch-node (n v)
2749 (js2-visit-ast (js2-switch-node-discriminant n) v)
2750 (dolist (c (js2-switch-node-cases n))
2751 (js2-visit-ast c v)))
2752
2753 (defun js2-print-switch-node (n i)
2754 (let ((pad (js2-make-pad i))
2755 (cases (js2-switch-node-cases n)))
2756 (insert pad "switch (")
2757 (js2-print-ast (js2-switch-node-discriminant n) 0)
2758 (insert ") {\n")
2759 (dolist (case cases)
2760 (js2-print-ast case i))
2761 (insert pad "}\n")))
2762
2763 (defstruct (js2-case-node
2764 (:include js2-block-node)
2765 (:constructor nil)
2766 (:constructor make-js2-case-node (&key (type js2-CASE)
2767 (pos js2-ts-cursor)
2768 len kids expr)))
2769 "AST node for a case clause of a switch statement."
2770 expr) ; the case expression (nil for default)
2771
2772 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2773 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2774
2775 (defun js2-visit-case-node (n v)
2776 (js2-visit-ast (js2-case-node-expr n) v)
2777 (js2-visit-block n v))
2778
2779 (defun js2-print-case-node (n i)
2780 (let ((pad (js2-make-pad i))
2781 (expr (js2-case-node-expr n)))
2782 (insert pad)
2783 (if (null expr)
2784 (insert "default:\n")
2785 (insert "case ")
2786 (js2-print-ast expr 0)
2787 (insert ":\n"))
2788 (dolist (kid (js2-case-node-kids n))
2789 (js2-print-ast kid (1+ i)))))
2790
2791 (defstruct (js2-throw-node
2792 (:include js2-node)
2793 (:constructor nil)
2794 (:constructor make-js2-throw-node (&key (type js2-THROW)
2795 (pos js2-ts-cursor)
2796 len expr)))
2797 "AST node for a throw statement."
2798 expr) ; the expression to throw
2799
2800 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2801 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2802
2803 (defun js2-visit-throw-node (n v)
2804 (js2-visit-ast (js2-throw-node-expr n) v))
2805
2806 (defun js2-print-throw-node (n i)
2807 (insert (js2-make-pad i) "throw ")
2808 (js2-print-ast (js2-throw-node-expr n) 0)
2809 (insert ";\n"))
2810
2811 (defstruct (js2-with-node
2812 (:include js2-node)
2813 (:constructor nil)
2814 (:constructor make-js2-with-node (&key (type js2-WITH)
2815 (pos js2-ts-cursor)
2816 len object
2817 body lp rp)))
2818 "AST node for a with-statement."
2819 object
2820 body
2821 lp ; buffer position of left-paren around object, nil if omitted
2822 rp) ; buffer position of right-paren around object, nil if omitted
2823
2824 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2825 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2826
2827 (defun js2-visit-with-node (n v)
2828 (js2-visit-ast (js2-with-node-object n) v)
2829 (js2-visit-ast (js2-with-node-body n) v))
2830
2831 (defun js2-print-with-node (n i)
2832 (let ((pad (js2-make-pad i)))
2833 (insert pad "with (")
2834 (js2-print-ast (js2-with-node-object n) 0)
2835 (insert ") {\n")
2836 (js2-print-body (js2-with-node-body n) (1+ i))
2837 (insert pad "}\n")))
2838
2839 (defstruct (js2-label-node
2840 (:include js2-node)
2841 (:constructor nil)
2842 (:constructor make-js2-label-node (&key (type js2-LABEL)
2843 (pos js2-ts-cursor)
2844 len name)))
2845 "AST node for a statement label or case label."
2846 name ; a string
2847 loop) ; for validating and code-generating continue-to-label
2848
2849 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2850 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2851
2852 (defun js2-print-label (n i)
2853 (insert (js2-make-pad i)
2854 (js2-label-node-name n)
2855 ":\n"))
2856
2857 (defstruct (js2-labeled-stmt-node
2858 (:include js2-node)
2859 (:constructor nil)
2860 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2861 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2862 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2863 (pos js2-ts-cursor)
2864 len labels stmt)))
2865 "AST node for a statement with one or more labels.
2866 Multiple labels for a statement are collapsed into the labels field."
2867 labels ; Lisp list of `js2-label-node'
2868 stmt) ; the statement these labels are for
2869
2870 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2871 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2872
2873 (defun js2-get-label-by-name (lbl-stmt name)
2874 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2875 Returns nil if no such label is in the list."
2876 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2877 result)
2878 (while (and label-list (not result))
2879 (if (string= (js2-label-node-name (car label-list)) name)
2880 (setq result (car label-list))
2881 (setq label-list (cdr label-list))))
2882 result))
2883
2884 (defun js2-visit-labeled-stmt (n v)
2885 (dolist (label (js2-labeled-stmt-node-labels n))
2886 (js2-visit-ast label v))
2887 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2888
2889 (defun js2-print-labeled-stmt (n i)
2890 (dolist (label (js2-labeled-stmt-node-labels n))
2891 (js2-print-ast label i))
2892 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
2893
2894 (defun js2-labeled-stmt-node-contains (node label)
2895 "Return t if NODE contains LABEL in its label set.
2896 NODE is a `js2-labels-node'. LABEL is an identifier."
2897 (loop for nl in (js2-labeled-stmt-node-labels node)
2898 if (string= label (js2-label-node-name nl))
2899 return t
2900 finally return nil))
2901
2902 (defsubst js2-labeled-stmt-node-add-label (node label)
2903 "Add a `js2-label-node' to the label set for this statement."
2904 (setf (js2-labeled-stmt-node-labels node)
2905 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2906
2907 (defstruct (js2-jump-node
2908 (:include js2-node)
2909 (:constructor nil))
2910 "Abstract supertype of break and continue nodes."
2911 label ; `js2-name-node' for location of label identifier, if present
2912 target) ; target js2-labels-node or loop/switch statement
2913
2914 (defun js2-visit-jump-node (n v)
2915 ;; We don't visit the target, since it's a back-link.
2916 (js2-visit-ast (js2-jump-node-label n) v))
2917
2918 (defstruct (js2-break-node
2919 (:include js2-jump-node)
2920 (:constructor nil)
2921 (:constructor make-js2-break-node (&key (type js2-BREAK)
2922 (pos js2-ts-cursor)
2923 len label target)))
2924 "AST node for a break statement.
2925 The label field is a `js2-name-node', possibly nil, for the named label
2926 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2927 is the target of the break - a label node or enclosing loop/switch statement.")
2928
2929 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2930 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2931
2932 (defun js2-print-break-node (n i)
2933 (insert (js2-make-pad i) "break")
2934 (when (js2-break-node-label n)
2935 (insert " ")
2936 (js2-print-ast (js2-break-node-label n) 0))
2937 (insert ";\n"))
2938
2939 (defstruct (js2-continue-node
2940 (:include js2-jump-node)
2941 (:constructor nil)
2942 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2943 (pos js2-ts-cursor)
2944 len label target)))
2945 "AST node for a continue statement.
2946 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2947 It is nil if continue specifies no label. The target field is the jump target:
2948 a `js2-label-node' or the innermost enclosing loop.")
2949
2950 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2951 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2952
2953 (defun js2-print-continue-node (n i)
2954 (insert (js2-make-pad i) "continue")
2955 (when (js2-continue-node-label n)
2956 (insert " ")
2957 (js2-print-ast (js2-continue-node-label n) 0))
2958 (insert ";\n"))
2959
2960 (defstruct (js2-function-node
2961 (:include js2-script-node)
2962 (:constructor nil)
2963 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2964 (pos js2-ts-cursor)
2965 len
2966 (ftype 'FUNCTION)
2967 (form 'FUNCTION_STATEMENT)
2968 (name "")
2969 params rest-p
2970 body
2971 generator-type
2972 lp rp)))
2973 "AST node for a function declaration.
2974 The `params' field is a Lisp list of nodes. Each node is either a simple
2975 `js2-name-node', or if it's a destructuring-assignment parameter, a
2976 `js2-array-node' or `js2-object-node'."
2977 ftype ; FUNCTION, GETTER or SETTER
2978 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
2979 name ; function name (a `js2-name-node', or nil if anonymous)
2980 params ; a Lisp list of destructuring forms or simple name nodes
2981 rest-p ; if t, the last parameter is rest parameter
2982 body ; a `js2-block-node' or expression node (1.8 only)
2983 lp ; position of arg-list open-paren, or nil if omitted
2984 rp ; position of arg-list close-paren, or nil if omitted
2985 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2986 needs-activation ; t if we need an activation object for this frame
2987 generator-type ; STAR, LEGACY or nil
2988 member-expr) ; nonstandard Ecma extension from Rhino
2989
2990 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2991 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2992
2993 (defun js2-visit-function-node (n v)
2994 (js2-visit-ast (js2-function-node-name n) v)
2995 (dolist (p (js2-function-node-params n))
2996 (js2-visit-ast p v))
2997 (js2-visit-ast (js2-function-node-body n) v))
2998
2999 (defun js2-print-function-node (n i)
3000 (let* ((pad (js2-make-pad i))
3001 (getter (js2-node-get-prop n 'GETTER_SETTER))
3002 (name (or (js2-function-node-name n)
3003 (js2-function-node-member-expr n)))
3004 (params (js2-function-node-params n))
3005 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3006 (rest-p (js2-function-node-rest-p n))
3007 (body (js2-function-node-body n))
3008 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3009 (unless (or getter arrow)
3010 (insert pad "function")
3011 (when (eq (js2-function-node-generator-type n) 'STAR)
3012 (insert "*")))
3013 (when name
3014 (insert " ")
3015 (js2-print-ast name 0))
3016 (insert "(")
3017 (loop with len = (length params)
3018 for param in params
3019 for count from 1
3020 do
3021 (when (and rest-p (= count len))
3022 (insert "..."))
3023 (js2-print-ast param 0)
3024 (when (< count len)
3025 (insert ", ")))
3026 (insert ") ")
3027 (when arrow
3028 (insert "=> "))
3029 (insert "{")
3030 ;; TODO: fix this to be smarter about indenting, etc.
3031 (unless expr
3032 (insert "\n"))
3033 (if (js2-block-node-p body)
3034 (js2-print-body body (1+ i))
3035 (js2-print-ast body 0))
3036 (insert pad "}")
3037 (unless expr
3038 (insert "\n"))))
3039
3040 (defun js2-function-name (node)
3041 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3042 (and (js2-function-node-name node)
3043 (js2-name-node-name (js2-function-node-name node))))
3044
3045 ;; Having this be an expression node makes it more flexible.
3046 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3047 ;; that work better if you assume it's an expression. Whenever we have
3048 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3049 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3050 (defstruct (js2-var-decl-node
3051 (:include js2-node)
3052 (:constructor nil)
3053 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3054 (pos (js2-current-token-beg))
3055 len kids
3056 decl-type)))
3057 "AST node for a variable declaration list (VAR, CONST or LET).
3058 The node bounds differ depending on the declaration type. For VAR or
3059 CONST declarations, the bounds include the var/const keyword. For LET
3060 declarations, the node begins at the position of the first child."
3061 kids ; a Lisp list of `js2-var-init-node' structs.
3062 decl-type) ; js2-VAR, js2-CONST or js2-LET
3063
3064 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3065 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3066
3067 (defun js2-visit-var-decl (n v)
3068 (dolist (kid (js2-var-decl-node-kids n))
3069 (js2-visit-ast kid v)))
3070
3071 (defun js2-print-var-decl (n i)
3072 (let ((pad (js2-make-pad i))
3073 (tt (js2-var-decl-node-decl-type n)))
3074 (insert pad)
3075 (insert (cond
3076 ((= tt js2-VAR) "var ")
3077 ((= tt js2-LET) "let ")
3078 ((= tt js2-CONST) "const ")
3079 (t
3080 (error "malformed var-decl node"))))
3081 (loop with kids = (js2-var-decl-node-kids n)
3082 with len = (length kids)
3083 for kid in kids
3084 for count from 1
3085 do
3086 (js2-print-ast kid 0)
3087 (if (< count len)
3088 (insert ", ")))))
3089
3090 (defstruct (js2-var-init-node
3091 (:include js2-node)
3092 (:constructor nil)
3093 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3094 (pos js2-ts-cursor)
3095 len target
3096 initializer)))
3097 "AST node for a variable declaration.
3098 The type field will be js2-CONST for a const decl."
3099 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3100 initializer) ; initializer expression, a `js2-node'
3101
3102 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3103 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3104
3105 (defun js2-visit-var-init-node (n v)
3106 (js2-visit-ast (js2-var-init-node-target n) v)
3107 (js2-visit-ast (js2-var-init-node-initializer n) v))
3108
3109 (defun js2-print-var-init-node (n i)
3110 (let ((pad (js2-make-pad i))
3111 (name (js2-var-init-node-target n))
3112 (init (js2-var-init-node-initializer n)))
3113 (insert pad)
3114 (js2-print-ast name 0)
3115 (when init
3116 (insert " = ")
3117 (js2-print-ast init 0))))
3118
3119 (defstruct (js2-cond-node
3120 (:include js2-node)
3121 (:constructor nil)
3122 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3123 (pos js2-ts-cursor)
3124 len
3125 test-expr
3126 true-expr
3127 false-expr
3128 q-pos c-pos)))
3129 "AST node for the ternary operator"
3130 test-expr
3131 true-expr
3132 false-expr
3133 q-pos ; buffer position of ?
3134 c-pos) ; buffer position of :
3135
3136 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3137 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3138
3139 (defun js2-visit-cond-node (n v)
3140 (js2-visit-ast (js2-cond-node-test-expr n) v)
3141 (js2-visit-ast (js2-cond-node-true-expr n) v)
3142 (js2-visit-ast (js2-cond-node-false-expr n) v))
3143
3144 (defun js2-print-cond-node (n i)
3145 (let ((pad (js2-make-pad i)))
3146 (insert pad)
3147 (js2-print-ast (js2-cond-node-test-expr n) 0)
3148 (insert " ? ")
3149 (js2-print-ast (js2-cond-node-true-expr n) 0)
3150 (insert " : ")
3151 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3152
3153 (defstruct (js2-infix-node
3154 (:include js2-node)
3155 (:constructor nil)
3156 (:constructor make-js2-infix-node (&key type
3157 (pos js2-ts-cursor)
3158 len op-pos
3159 left right)))
3160 "Represents infix expressions.
3161 Includes assignment ops like `|=', and the comma operator.
3162 The type field inherited from `js2-node' holds the operator."
3163 op-pos ; buffer position where operator begins
3164 left ; any `js2-node'
3165 right) ; any `js2-node'
3166
3167 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3168 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3169
3170 (defun js2-visit-infix-node (n v)
3171 (js2-visit-ast (js2-infix-node-left n) v)
3172 (js2-visit-ast (js2-infix-node-right n) v))
3173
3174 (defconst js2-operator-tokens
3175 (let ((table (make-hash-table :test 'eq))
3176 (tokens
3177 (list (cons js2-IN "in")
3178 (cons js2-TYPEOF "typeof")
3179 (cons js2-INSTANCEOF "instanceof")
3180 (cons js2-DELPROP "delete")
3181 (cons js2-COMMA ",")
3182 (cons js2-COLON ":")
3183 (cons js2-OR "||")
3184 (cons js2-AND "&&")
3185 (cons js2-INC "++")
3186 (cons js2-DEC "--")
3187 (cons js2-BITOR "|")
3188 (cons js2-BITXOR "^")
3189 (cons js2-BITAND "&")
3190 (cons js2-EQ "==")
3191 (cons js2-NE "!=")
3192 (cons js2-LT "<")
3193 (cons js2-LE "<=")
3194 (cons js2-GT ">")
3195 (cons js2-GE ">=")
3196 (cons js2-LSH "<<")
3197 (cons js2-RSH ">>")
3198 (cons js2-URSH ">>>")
3199 (cons js2-ADD "+") ; infix plus
3200 (cons js2-SUB "-") ; infix minus
3201 (cons js2-MUL "*")
3202 (cons js2-DIV "/")
3203 (cons js2-MOD "%")
3204 (cons js2-NOT "!")
3205 (cons js2-BITNOT "~")
3206 (cons js2-POS "+") ; unary plus
3207 (cons js2-NEG "-") ; unary minus
3208 (cons js2-TRIPLEDOT "...")
3209 (cons js2-SHEQ "===") ; shallow equality
3210 (cons js2-SHNE "!==") ; shallow inequality
3211 (cons js2-ASSIGN "=")
3212 (cons js2-ASSIGN_BITOR "|=")
3213 (cons js2-ASSIGN_BITXOR "^=")
3214 (cons js2-ASSIGN_BITAND "&=")
3215 (cons js2-ASSIGN_LSH "<<=")
3216 (cons js2-ASSIGN_RSH ">>=")
3217 (cons js2-ASSIGN_URSH ">>>=")
3218 (cons js2-ASSIGN_ADD "+=")
3219 (cons js2-ASSIGN_SUB "-=")
3220 (cons js2-ASSIGN_MUL "*=")
3221 (cons js2-ASSIGN_DIV "/=")
3222 (cons js2-ASSIGN_MOD "%="))))
3223 (loop for (k . v) in tokens do
3224 (puthash k v table))
3225 table))
3226
3227 (defun js2-print-infix-node (n i)
3228 (let* ((tt (js2-node-type n))
3229 (op (gethash tt js2-operator-tokens)))
3230 (unless op
3231 (error "unrecognized infix operator %s" (js2-node-type n)))
3232 (insert (js2-make-pad i))
3233 (js2-print-ast (js2-infix-node-left n) 0)
3234 (unless (= tt js2-COMMA)
3235 (insert " "))
3236 (insert op)
3237 (insert " ")
3238 (js2-print-ast (js2-infix-node-right n) 0)))
3239
3240 (defstruct (js2-assign-node
3241 (:include js2-infix-node)
3242 (:constructor nil)
3243 (:constructor make-js2-assign-node (&key type
3244 (pos js2-ts-cursor)
3245 len op-pos
3246 left right)))
3247 "Represents any assignment.
3248 The type field holds the actual assignment operator.")
3249
3250 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3251 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3252
3253 (defstruct (js2-unary-node
3254 (:include js2-node)
3255 (:constructor nil)
3256 (:constructor make-js2-unary-node (&key type ; required
3257 (pos js2-ts-cursor)
3258 len operand)))
3259 "AST node type for unary operator nodes.
3260 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3261 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3262 property is added if the operator follows the operand."
3263 operand) ; a `js2-node' expression
3264
3265 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3266 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3267
3268 (defun js2-visit-unary-node (n v)
3269 (js2-visit-ast (js2-unary-node-operand n) v))
3270
3271 (defun js2-print-unary-node (n i)
3272 (let* ((tt (js2-node-type n))
3273 (op (gethash tt js2-operator-tokens))
3274 (postfix (js2-node-get-prop n 'postfix)))
3275 (unless op
3276 (error "unrecognized unary operator %s" tt))
3277 (insert (js2-make-pad i))
3278 (unless postfix
3279 (insert op))
3280 (if (or (= tt js2-TYPEOF)
3281 (= tt js2-DELPROP))
3282 (insert " "))
3283 (js2-print-ast (js2-unary-node-operand n) 0)
3284 (when postfix
3285 (insert op))))
3286
3287 (defstruct (js2-let-node
3288 (:include js2-scope)
3289 (:constructor nil)
3290 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3291 (pos (js2-current-token-beg))
3292 len vars body
3293 lp rp)))
3294 "AST node for a let expression or a let statement.
3295 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3296 vars ; a `js2-var-decl-node'
3297 body ; a `js2-node' representing the expression or body block
3298 lp
3299 rp)
3300
3301 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3302 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3303
3304 (defun js2-visit-let-node (n v)
3305 (js2-visit-ast (js2-let-node-vars n) v)
3306 (js2-visit-ast (js2-let-node-body n) v))
3307
3308 (defun js2-print-let-node (n i)
3309 (insert (js2-make-pad i) "let (")
3310 (js2-print-ast (js2-let-node-vars n) 0)
3311 (insert ") ")
3312 (js2-print-ast (js2-let-node-body n) i))
3313
3314 (defstruct (js2-keyword-node
3315 (:include js2-node)
3316 (:constructor nil)
3317 (:constructor make-js2-keyword-node (&key type
3318 (pos (js2-current-token-beg))
3319 (len (- js2-ts-cursor pos)))))
3320 "AST node representing a literal keyword such as `null'.
3321 Used for `null', `this', `true', `false' and `debugger'.
3322 The node type is set to js2-NULL, js2-THIS, etc.")
3323
3324 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3325 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3326
3327 (defun js2-print-keyword-node (n i)
3328 (insert (js2-make-pad i)
3329 (let ((tt (js2-node-type n)))
3330 (cond
3331 ((= tt js2-THIS) "this")
3332 ((= tt js2-NULL) "null")
3333 ((= tt js2-TRUE) "true")
3334 ((= tt js2-FALSE) "false")
3335 ((= tt js2-DEBUGGER) "debugger")
3336 (t (error "Invalid keyword literal type: %d" tt))))))
3337
3338 (defsubst js2-this-node-p (node)
3339 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3340 (eq (js2-node-type node) js2-THIS))
3341
3342 (defstruct (js2-new-node
3343 (:include js2-node)
3344 (:constructor nil)
3345 (:constructor make-js2-new-node (&key (type js2-NEW)
3346 (pos (js2-current-token-beg))
3347 len target
3348 args initializer
3349 lp rp)))
3350 "AST node for new-expression such as new Foo()."
3351 target ; an identifier or reference
3352 args ; a Lisp list of argument nodes
3353 lp ; position of left-paren, nil if omitted
3354 rp ; position of right-paren, nil if omitted
3355 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3356
3357 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3358 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3359
3360 (defun js2-visit-new-node (n v)
3361 (js2-visit-ast (js2-new-node-target n) v)
3362 (dolist (arg (js2-new-node-args n))
3363 (js2-visit-ast arg v))
3364 (js2-visit-ast (js2-new-node-initializer n) v))
3365
3366 (defun js2-print-new-node (n i)
3367 (insert (js2-make-pad i) "new ")
3368 (js2-print-ast (js2-new-node-target n))
3369 (insert "(")
3370 (js2-print-list (js2-new-node-args n))
3371 (insert ")")
3372 (when (js2-new-node-initializer n)
3373 (insert " ")
3374 (js2-print-ast (js2-new-node-initializer n))))
3375
3376 (defstruct (js2-name-node
3377 (:include js2-node)
3378 (:constructor nil)
3379 (:constructor make-js2-name-node (&key (type js2-NAME)
3380 (pos (js2-current-token-beg))
3381 (len (- js2-ts-cursor
3382 (js2-current-token-beg)))
3383 (name (js2-current-token-string)))))
3384 "AST node for a JavaScript identifier"
3385 name ; a string
3386 scope) ; a `js2-scope' (optional, used for codegen)
3387
3388 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3389 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3390
3391 (defun js2-print-name-node (n i)
3392 (insert (js2-make-pad i)
3393 (js2-name-node-name n)))
3394
3395 (defsubst js2-name-node-length (node)
3396 "Return identifier length of NODE, a `js2-name-node'.
3397 Returns 0 if NODE is nil or its identifier field is nil."
3398 (if node
3399 (length (js2-name-node-name node))
3400 0))
3401
3402 (defstruct (js2-number-node
3403 (:include js2-node)
3404 (:constructor nil)
3405 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3406 (pos (js2-current-token-beg))
3407 (len (- js2-ts-cursor
3408 (js2-current-token-beg)))
3409 (value (js2-current-token-string))
3410 (num-value (js2-token-number
3411 (js2-current-token))))))
3412 "AST node for a number literal."
3413 value ; the original string, e.g. "6.02e23"
3414 num-value) ; the parsed number value
3415
3416 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3417 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3418
3419 (defun js2-print-number-node (n i)
3420 (insert (js2-make-pad i)
3421 (number-to-string (js2-number-node-num-value n))))
3422
3423 (defstruct (js2-regexp-node
3424 (:include js2-node)
3425 (:constructor nil)
3426 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3427 (pos (js2-current-token-beg))
3428 (len (- js2-ts-cursor
3429 (js2-current-token-beg)))
3430 value flags)))
3431 "AST node for a regular expression literal."
3432 value ; the regexp string, without // delimiters
3433 flags) ; a string of flags, e.g. `mi'.
3434
3435 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3436 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3437
3438 (defun js2-print-regexp (n i)
3439 (insert (js2-make-pad i)
3440 "/"
3441 (js2-regexp-node-value n)
3442 "/")
3443 (if (js2-regexp-node-flags n)
3444 (insert (js2-regexp-node-flags n))))
3445
3446 (defstruct (js2-string-node
3447 (:include js2-node)
3448 (:constructor nil)
3449 (:constructor make-js2-string-node (&key (type js2-STRING)
3450 (pos (js2-current-token-beg))
3451 (len (- js2-ts-cursor
3452 (js2-current-token-beg)))
3453 (value (js2-current-token-string)))))
3454 "String literal.
3455 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3456 You can tell the quote type by looking at the first character."
3457 value) ; the characters of the string, including the quotes
3458
3459 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3460 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3461
3462 (defun js2-print-string-node (n i)
3463 (insert (js2-make-pad i)
3464 (js2-node-string n)))
3465
3466 (defstruct (js2-array-node
3467 (:include js2-node)
3468 (:constructor nil)
3469 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3470 (pos js2-ts-cursor)
3471 len elems)))
3472 "AST node for an array literal."
3473 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3474
3475 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3476 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3477
3478 (defun js2-visit-array-node (n v)
3479 (dolist (e (js2-array-node-elems n))
3480 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3481
3482 (defun js2-print-array-node (n i)
3483 (insert (js2-make-pad i) "[")
3484 (js2-print-list (js2-array-node-elems n))
3485 (insert "]"))
3486
3487 (defstruct (js2-object-node
3488 (:include js2-node)
3489 (:constructor nil)
3490 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3491 (pos js2-ts-cursor)
3492 len
3493 elems)))
3494 "AST node for an object literal expression.
3495 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3496 The latter represents abbreviation in destructuring expressions."
3497 elems)
3498
3499 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3500 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3501
3502 (defun js2-visit-object-node (n v)
3503 (dolist (e (js2-object-node-elems n))
3504 (js2-visit-ast e v)))
3505
3506 (defun js2-print-object-node (n i)
3507 (insert (js2-make-pad i) "{")
3508 (js2-print-list (js2-object-node-elems n))
3509 (insert "}"))
3510
3511 (defstruct (js2-object-prop-node
3512 (:include js2-infix-node)
3513 (:constructor nil)
3514 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3515 (pos js2-ts-cursor)
3516 len left
3517 right op-pos)))
3518 "AST node for an object literal prop:value entry.
3519 The `left' field is the property: a name node, string node or number node.
3520 The `right' field is a `js2-node' representing the initializer value.")
3521
3522 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3523 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3524
3525 (defun js2-print-object-prop-node (n i)
3526 (insert (js2-make-pad i))
3527 (js2-print-ast (js2-object-prop-node-left n) 0)
3528 (insert ": ")
3529 (js2-print-ast (js2-object-prop-node-right n) 0))
3530
3531 (defstruct (js2-getter-setter-node
3532 (:include js2-infix-node)
3533 (:constructor nil)
3534 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3535 (pos js2-ts-cursor)
3536 len left right)))
3537 "AST node for a getter/setter property in an object literal.
3538 The `left' field is the `js2-name-node' naming the getter/setter prop.
3539 The `right' field is always an anonymous `js2-function-node' with a node
3540 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3541
3542 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3543 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3544
3545 (defun js2-print-getter-setter (n i)
3546 (let ((pad (js2-make-pad i))
3547 (left (js2-getter-setter-node-left n))
3548 (right (js2-getter-setter-node-right n)))
3549 (insert pad)
3550 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3551 (js2-print-ast left 0)
3552 (js2-print-ast right 0)))
3553
3554 (defstruct (js2-prop-get-node
3555 (:include js2-infix-node)
3556 (:constructor nil)
3557 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3558 (pos js2-ts-cursor)
3559 len left right)))
3560 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3561
3562 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3563 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3564
3565 (defun js2-visit-prop-get-node (n v)
3566 (js2-visit-ast (js2-prop-get-node-left n) v)
3567 (js2-visit-ast (js2-prop-get-node-right n) v))
3568
3569 (defun js2-print-prop-get-node (n i)
3570 (insert (js2-make-pad i))
3571 (js2-print-ast (js2-prop-get-node-left n) 0)
3572 (insert ".")
3573 (js2-print-ast (js2-prop-get-node-right n) 0))
3574
3575 (defstruct (js2-elem-get-node
3576 (:include js2-node)
3577 (:constructor nil)
3578 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3579 (pos js2-ts-cursor)
3580 len target element
3581 lb rb)))
3582 "AST node for an array index expression such as foo[bar]."
3583 target ; a `js2-node' - the expression preceding the "."
3584 element ; a `js2-node' - the expression in brackets
3585 lb ; position of left-bracket, nil if omitted
3586 rb) ; position of right-bracket, nil if omitted
3587
3588 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3589 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3590
3591 (defun js2-visit-elem-get-node (n v)
3592 (js2-visit-ast (js2-elem-get-node-target n) v)
3593 (js2-visit-ast (js2-elem-get-node-element n) v))
3594
3595 (defun js2-print-elem-get-node (n i)
3596 (insert (js2-make-pad i))
3597 (js2-print-ast (js2-elem-get-node-target n) 0)
3598 (insert "[")
3599 (js2-print-ast (js2-elem-get-node-element n) 0)
3600 (insert "]"))
3601
3602 (defstruct (js2-call-node
3603 (:include js2-node)
3604 (:constructor nil)
3605 (:constructor make-js2-call-node (&key (type js2-CALL)
3606 (pos js2-ts-cursor)
3607 len target args
3608 lp rp)))
3609 "AST node for a JavaScript function call."
3610 target ; a `js2-node' evaluating to the function to call
3611 args ; a Lisp list of `js2-node' arguments
3612 lp ; position of open-paren, or nil if missing
3613 rp) ; position of close-paren, or nil if missing
3614
3615 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3616 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3617
3618 (defun js2-visit-call-node (n v)
3619 (js2-visit-ast (js2-call-node-target n) v)
3620 (dolist (arg (js2-call-node-args n))
3621 (js2-visit-ast arg v)))
3622
3623 (defun js2-print-call-node (n i)
3624 (insert (js2-make-pad i))
3625 (js2-print-ast (js2-call-node-target n) 0)
3626 (insert "(")
3627 (js2-print-list (js2-call-node-args n))
3628 (insert ")"))
3629
3630 (defstruct (js2-yield-node
3631 (:include js2-node)
3632 (:constructor nil)
3633 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3634 (pos js2-ts-cursor)
3635 len value)))
3636 "AST node for yield statement or expression."
3637 value) ; optional: value to be yielded
3638
3639 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3640 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3641
3642 (defun js2-visit-yield-node (n v)
3643 (js2-visit-ast (js2-yield-node-value n) v))
3644
3645 (defun js2-print-yield-node (n i)
3646 (insert (js2-make-pad i))
3647 (insert "yield")
3648 (when (js2-yield-node-value n)
3649 (insert " ")
3650 (js2-print-ast (js2-yield-node-value n) 0)))
3651
3652 (defstruct (js2-paren-node
3653 (:include js2-node)
3654 (:constructor nil)
3655 (:constructor make-js2-paren-node (&key (type js2-LP)
3656 (pos js2-ts-cursor)
3657 len expr)))
3658 "AST node for a parenthesized expression.
3659 In particular, used when the parens are syntactically optional,
3660 as opposed to required parens such as those enclosing an if-conditional."
3661 expr) ; `js2-node'
3662
3663 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3664 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3665
3666 (defun js2-visit-paren-node (n v)
3667 (js2-visit-ast (js2-paren-node-expr n) v))
3668
3669 (defun js2-print-paren-node (n i)
3670 (insert (js2-make-pad i))
3671 (insert "(")
3672 (js2-print-ast (js2-paren-node-expr n) 0)
3673 (insert ")"))
3674
3675 (defstruct (js2-array-comp-node
3676 (:include js2-scope)
3677 (:constructor nil)
3678 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3679 (pos js2-ts-cursor)
3680 len result
3681 loops filter
3682 if-pos lp rp)))
3683 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3684 result ; result expression (just after left-bracket)
3685 loops ; a Lisp list of `js2-array-comp-loop-node'
3686 filter ; guard/filter expression
3687 if-pos ; buffer pos of 'if' keyword, if present, else nil
3688 lp ; buffer position of if-guard left-paren, or nil if not present
3689 rp) ; buffer position of if-guard right-paren, or nil if not present
3690
3691 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3692 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3693
3694 (defun js2-visit-array-comp-node (n v)
3695 (js2-visit-ast (js2-array-comp-node-result n) v)
3696 (dolist (l (js2-array-comp-node-loops n))
3697 (js2-visit-ast l v))
3698 (js2-visit-ast (js2-array-comp-node-filter n) v))
3699
3700 (defun js2-print-array-comp-node (n i)
3701 (let ((pad (js2-make-pad i))
3702 (result (js2-array-comp-node-result n))
3703 (loops (js2-array-comp-node-loops n))
3704 (filter (js2-array-comp-node-filter n)))
3705 (insert pad "[")
3706 (js2-print-ast result 0)
3707 (dolist (l loops)
3708 (insert " ")
3709 (js2-print-ast l 0))
3710 (when filter
3711 (insert " if (")
3712 (js2-print-ast filter 0)
3713 (insert ")"))
3714 (insert "]")))
3715
3716 (defstruct (js2-array-comp-loop-node
3717 (:include js2-for-in-node)
3718 (:constructor nil)
3719 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3720 (pos js2-ts-cursor)
3721 len iterator
3722 object in-pos
3723 foreach-p
3724 each-pos
3725 forof-p
3726 lp rp)))
3727 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3728
3729 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3730 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3731
3732 (defun js2-visit-array-comp-loop (n v)
3733 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3734 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3735
3736 (defun js2-print-array-comp-loop (n _i)
3737 (insert "for ")
3738 (when (js2-array-comp-loop-node-foreach-p n) (insert "each "))
3739 (insert "(")
3740 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3741 (insert (if (js2-array-comp-loop-node-forof-p n)
3742 " of " " in "))
3743 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3744 (insert ")"))
3745
3746 (defstruct (js2-empty-expr-node
3747 (:include js2-node)
3748 (:constructor nil)
3749 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3750 (pos (js2-current-token-beg))
3751 len)))
3752 "AST node for an empty expression.")
3753
3754 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3755 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3756
3757 (defstruct (js2-xml-node
3758 (:include js2-block-node)
3759 (:constructor nil)
3760 (:constructor make-js2-xml-node (&key (type js2-XML)
3761 (pos (js2-current-token-beg))
3762 len kids)))
3763 "AST node for initial parse of E4X literals.
3764 The kids field is a list of XML fragments, each a `js2-string-node' or
3765 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3766
3767 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3768 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3769
3770 (defun js2-print-xml-node (n i)
3771 (dolist (kid (js2-xml-node-kids n))
3772 (js2-print-ast kid i)))
3773
3774 (defstruct (js2-xml-js-expr-node
3775 (:include js2-xml-node)
3776 (:constructor nil)
3777 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3778 (pos js2-ts-cursor)
3779 len expr)))
3780 "AST node for an embedded JavaScript {expression} in an E4X literal.
3781 The start and end fields correspond to the curly-braces."
3782 expr) ; a `js2-expr-node' of some sort
3783
3784 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3785 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3786
3787 (defun js2-visit-xml-js-expr (n v)
3788 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3789
3790 (defun js2-print-xml-js-expr (n i)
3791 (insert (js2-make-pad i))
3792 (insert "{")
3793 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3794 (insert "}"))
3795
3796 (defstruct (js2-xml-dot-query-node
3797 (:include js2-infix-node)
3798 (:constructor nil)
3799 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3800 (pos js2-ts-cursor)
3801 op-pos len left
3802 right rp)))
3803 "AST node for an E4X foo.(bar) filter expression.
3804 Note that the left-paren is automatically the character immediately
3805 following the dot (.) in the operator. No whitespace is permitted
3806 between the dot and the lp by the scanner."
3807 rp)
3808
3809 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3810 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3811
3812 (defun js2-print-xml-dot-query (n i)
3813 (insert (js2-make-pad i))
3814 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3815 (insert ".(")
3816 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3817 (insert ")"))
3818
3819 (defstruct (js2-xml-ref-node
3820 (:include js2-node)
3821 (:constructor nil)) ; abstract
3822 "Base type for E4X XML attribute-access or property-get expressions.
3823 Such expressions can take a variety of forms. The general syntax has
3824 three parts:
3825
3826 - (optional) an @ (specifying an attribute access)
3827 - (optional) a namespace (a `js2-name-node') and double-colon
3828 - (required) either a `js2-name-node' or a bracketed [expression]
3829
3830 The property-name expressions (examples: ns::name, @name) are
3831 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3832 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3833
3834 This node type (or more specifically, its subclasses) will sometimes
3835 be the right-hand child of a `js2-prop-get-node' or a
3836 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3837 The `js2-xml-ref-node' may also be a standalone primary expression with
3838 no explicit target, which is valid in certain expression contexts such as
3839
3840 company..employee.(@id < 100)
3841
3842 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3843 expression whose parent is a `js2-xml-dot-query-node'."
3844 namespace
3845 at-pos
3846 colon-pos)
3847
3848 (defsubst js2-xml-ref-node-attr-access-p (node)
3849 "Return non-nil if this expression began with an @-token."
3850 (and (numberp (js2-xml-ref-node-at-pos node))
3851 (plusp (js2-xml-ref-node-at-pos node))))
3852
3853 (defstruct (js2-xml-prop-ref-node
3854 (:include js2-xml-ref-node)
3855 (:constructor nil)
3856 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3857 (pos (js2-current-token-beg))
3858 len propname
3859 namespace at-pos
3860 colon-pos)))
3861 "AST node for an E4X XML [expr] property-ref expression.
3862 The JavaScript syntax is an optional @, an optional ns::, and a name.
3863
3864 [ '@' ] [ name '::' ] name
3865
3866 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3867 @ns::*, @*::attr, @*::*, and @*.
3868
3869 The node starts at the @ token, if present. Otherwise it starts at the
3870 namespace name. The node bounds extend through the closing right-bracket,
3871 or if it is missing due to a syntax error, through the end of the index
3872 expression."
3873 propname)
3874
3875 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3876 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3877
3878 (defun js2-visit-xml-prop-ref-node (n v)
3879 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3880 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3881
3882 (defun js2-print-xml-prop-ref-node (n i)
3883 (insert (js2-make-pad i))
3884 (if (js2-xml-ref-node-attr-access-p n)
3885 (insert "@"))
3886 (when (js2-xml-prop-ref-node-namespace n)
3887 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3888 (insert "::"))
3889 (if (js2-xml-prop-ref-node-propname n)
3890 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3891
3892 (defstruct (js2-xml-elem-ref-node
3893 (:include js2-xml-ref-node)
3894 (:constructor nil)
3895 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3896 (pos (js2-current-token-beg))
3897 len expr lb rb
3898 namespace at-pos
3899 colon-pos)))
3900 "AST node for an E4X XML [expr] member-ref expression.
3901 Syntax:
3902
3903 [ '@' ] [ name '::' ] '[' expr ']'
3904
3905 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3906
3907 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3908 is not a legal E4X XML element-ref expression, since it's already used
3909 for standard JavaScript element-get array indexing. Hence, a
3910 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3911 non-nil namespace node, or both.
3912
3913 The node starts at the @ token, if present. Otherwise it starts
3914 at the namespace name. The node bounds extend through the closing
3915 right-bracket, or if it is missing due to a syntax error, through the
3916 end of the index expression."
3917 expr ; the bracketed index expression
3918 lb
3919 rb)
3920
3921 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3922 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3923
3924 (defun js2-visit-xml-elem-ref-node (n v)
3925 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3926 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3927
3928 (defun js2-print-xml-elem-ref-node (n i)
3929 (insert (js2-make-pad i))
3930 (if (js2-xml-ref-node-attr-access-p n)
3931 (insert "@"))
3932 (when (js2-xml-elem-ref-node-namespace n)
3933 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3934 (insert "::"))
3935 (insert "[")
3936 (if (js2-xml-elem-ref-node-expr n)
3937 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3938 (insert "]"))
3939
3940 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3941
3942 (defstruct (js2-xml-start-tag-node
3943 (:include js2-xml-node)
3944 (:constructor nil)
3945 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3946 (pos js2-ts-cursor)
3947 len name attrs kids
3948 empty-p)))
3949 "AST node for an XML start-tag. Not currently used.
3950 The `kids' field is a Lisp list of child content nodes."
3951 name ; a `js2-xml-name-node'
3952 attrs ; a Lisp list of `js2-xml-attr-node'
3953 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3954
3955 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3956 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3957
3958 (defun js2-visit-xml-start-tag (n v)
3959 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3960 (dolist (attr (js2-xml-start-tag-node-attrs n))
3961 (js2-visit-ast attr v))
3962 (js2-visit-block n v))
3963
3964 (defun js2-print-xml-start-tag (n i)
3965 (insert (js2-make-pad i) "<")
3966 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3967 (when (js2-xml-start-tag-node-attrs n)
3968 (insert " ")
3969 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3970 (insert ">"))
3971
3972 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3973 ;; and add the end-tag to the kids list of the parent as well.
3974 (defstruct (js2-xml-end-tag-node
3975 (:include js2-xml-node)
3976 (:constructor nil)
3977 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
3978 (pos js2-ts-cursor)
3979 len name)))
3980 "AST node for an XML end-tag. Not currently used."
3981 name) ; a `js2-xml-name-node'
3982
3983 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
3984 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
3985
3986 (defun js2-visit-xml-end-tag (n v)
3987 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
3988
3989 (defun js2-print-xml-end-tag (n i)
3990 (insert (js2-make-pad i))
3991 (insert "</")
3992 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
3993 (insert ">"))
3994
3995 (defstruct (js2-xml-name-node
3996 (:include js2-xml-node)
3997 (:constructor nil)
3998 (:constructor make-js2-xml-name-node (&key (type js2-XML)
3999 (pos js2-ts-cursor)
4000 len namespace kids)))
4001 "AST node for an E4X XML name. Not currently used.
4002 Any XML name can be qualified with a namespace, hence the namespace field.
4003 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4004 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4005 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4006 namespace) ; a `js2-string-node'
4007
4008 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4009 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4010
4011 (defun js2-visit-xml-name-node (n v)
4012 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4013
4014 (defun js2-print-xml-name-node (n i)
4015 (insert (js2-make-pad i))
4016 (when (js2-xml-name-node-namespace n)
4017 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4018 (insert "::"))
4019 (dolist (kid (js2-xml-name-node-kids n))
4020 (js2-print-ast kid 0)))
4021
4022 (defstruct (js2-xml-pi-node
4023 (:include js2-xml-node)
4024 (:constructor nil)
4025 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4026 (pos js2-ts-cursor)
4027 len name attrs)))
4028 "AST node for an E4X XML processing instruction. Not currently used."
4029 name ; a `js2-xml-name-node'
4030 attrs) ; a list of `js2-xml-attr-node'
4031
4032 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4033 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4034
4035 (defun js2-visit-xml-pi-node (n v)
4036 (js2-visit-ast (js2-xml-pi-node-name n) v)
4037 (dolist (attr (js2-xml-pi-node-attrs n))
4038 (js2-visit-ast attr v)))
4039
4040 (defun js2-print-xml-pi-node (n i)
4041 (insert (js2-make-pad i) "<?")
4042 (js2-print-ast (js2-xml-pi-node-name n))
4043 (when (js2-xml-pi-node-attrs n)
4044 (insert " ")
4045 (js2-print-list (js2-xml-pi-node-attrs n)))
4046 (insert "?>"))
4047
4048 (defstruct (js2-xml-cdata-node
4049 (:include js2-xml-node)
4050 (:constructor nil)
4051 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4052 (pos js2-ts-cursor)
4053 len content)))
4054 "AST node for a CDATA escape section. Not currently used."
4055 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4056
4057 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4058 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4059
4060 (defun js2-visit-xml-cdata-node (n v)
4061 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4062
4063 (defun js2-print-xml-cdata-node (n i)
4064 (insert (js2-make-pad i))
4065 (js2-print-ast (js2-xml-cdata-node-content n)))
4066
4067 (defstruct (js2-xml-attr-node
4068 (:include js2-xml-node)
4069 (:constructor nil)
4070 (:constructor make-js2-attr-node (&key (type js2-XML)
4071 (pos js2-ts-cursor)
4072 len name value
4073 eq-pos quote-type)))
4074 "AST node representing a foo='bar' XML attribute value. Not yet used."
4075 name ; a `js2-xml-name-node'
4076 value ; a `js2-xml-name-node'
4077 eq-pos ; buffer position of "=" sign
4078 quote-type) ; 'single or 'double
4079
4080 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4081 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4082
4083 (defun js2-visit-xml-attr-node (n v)
4084 (js2-visit-ast (js2-xml-attr-node-name n) v)
4085 (js2-visit-ast (js2-xml-attr-node-value n) v))
4086
4087 (defun js2-print-xml-attr-node (n i)
4088 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4089 "'"
4090 "\"")))
4091 (insert (js2-make-pad i))
4092 (js2-print-ast (js2-xml-attr-node-name n) 0)
4093 (insert "=" quote)
4094 (js2-print-ast (js2-xml-attr-node-value n) 0)
4095 (insert quote)))
4096
4097 (defstruct (js2-xml-text-node
4098 (:include js2-xml-node)
4099 (:constructor nil)
4100 (:constructor make-js2-text-node (&key (type js2-XML)
4101 (pos js2-ts-cursor)
4102 len content)))
4103 "AST node for an E4X XML text node. Not currently used."
4104 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4105
4106 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4107 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4108
4109 (defun js2-visit-xml-text-node (n v)
4110 (js2-visit-ast (js2-xml-text-node-content n) v))
4111
4112 (defun js2-print-xml-text-node (n i)
4113 (insert (js2-make-pad i))
4114 (dolist (kid (js2-xml-text-node-content n))
4115 (js2-print-ast kid)))
4116
4117 (defstruct (js2-xml-comment-node
4118 (:include js2-xml-node)
4119 (:constructor nil)
4120 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4121 (pos js2-ts-cursor)
4122 len)))
4123 "AST node for E4X XML comment. Not currently used.")
4124
4125 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4126 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4127
4128 (defun js2-print-xml-comment (n i)
4129 (insert (js2-make-pad i)
4130 (js2-node-string n)))
4131
4132 ;;; Node utilities
4133
4134 (defsubst js2-node-line (n)
4135 "Fetch the source line number at the start of node N.
4136 This is O(n) in the length of the source buffer; use prudently."
4137 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4138
4139 (defsubst js2-block-node-kid (n i)
4140 "Return child I of node N, or nil if there aren't that many."
4141 (nth i (js2-block-node-kids n)))
4142
4143 (defsubst js2-block-node-first (n)
4144 "Return first child of block node N, or nil if there is none."
4145 (first (js2-block-node-kids n)))
4146
4147 (defun js2-node-root (n)
4148 "Return the root of the AST containing N.
4149 If N has no parent pointer, returns N."
4150 (let ((parent (js2-node-parent n)))
4151 (if parent
4152 (js2-node-root parent)
4153 n)))
4154
4155 (defsubst js2-node-short-name (n)
4156 "Return the short name of node N as a string, e.g. `js2-if-node'."
4157 (substring (symbol-name (aref n 0))
4158 (length "cl-struct-")))
4159
4160 (defun js2-node-child-list (node)
4161 "Return the child list for NODE, a Lisp list of nodes.
4162 Works for block nodes, array nodes, obj literals, funarg lists,
4163 var decls and try nodes (for catch clauses). Note that you should call
4164 `js2-block-node-kids' on the function body for the body statements.
4165 Returns nil for zero-length child lists or unsupported nodes."
4166 (cond
4167 ((js2-function-node-p node)
4168 (js2-function-node-params node))
4169 ((js2-block-node-p node)
4170 (js2-block-node-kids node))
4171 ((js2-try-node-p node)
4172 (js2-try-node-catch-clauses node))
4173 ((js2-array-node-p node)
4174 (js2-array-node-elems node))
4175 ((js2-object-node-p node)
4176 (js2-object-node-elems node))
4177 ((js2-call-node-p node)
4178 (js2-call-node-args node))
4179 ((js2-new-node-p node)
4180 (js2-new-node-args node))
4181 ((js2-var-decl-node-p node)
4182 (js2-var-decl-node-kids node))
4183 (t
4184 nil)))
4185
4186 (defun js2-node-set-child-list (node kids)
4187 "Set the child list for NODE to KIDS."
4188 (cond
4189 ((js2-function-node-p node)
4190 (setf (js2-function-node-params node) kids))
4191 ((js2-block-node-p node)
4192 (setf (js2-block-node-kids node) kids))
4193 ((js2-try-node-p node)
4194 (setf (js2-try-node-catch-clauses node) kids))
4195 ((js2-array-node-p node)
4196 (setf (js2-array-node-elems node) kids))
4197 ((js2-object-node-p node)
4198 (setf (js2-object-node-elems node) kids))
4199 ((js2-call-node-p node)
4200 (setf (js2-call-node-args node) kids))
4201 ((js2-new-node-p node)
4202 (setf (js2-new-node-args node) kids))
4203 ((js2-var-decl-node-p node)
4204 (setf (js2-var-decl-node-kids node) kids))
4205 (t
4206 (error "Unsupported node type: %s" (js2-node-short-name node))))
4207 kids)
4208
4209 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4210 (defconst js2-paren-expr-nodes
4211 '(cl-struct-js2-array-comp-loop-node
4212 cl-struct-js2-array-comp-node
4213 cl-struct-js2-call-node
4214 cl-struct-js2-catch-node
4215 cl-struct-js2-do-node
4216 cl-struct-js2-elem-get-node
4217 cl-struct-js2-for-in-node
4218 cl-struct-js2-for-node
4219 cl-struct-js2-function-node
4220 cl-struct-js2-if-node
4221 cl-struct-js2-let-node
4222 cl-struct-js2-new-node
4223 cl-struct-js2-paren-node
4224 cl-struct-js2-switch-node
4225 cl-struct-js2-while-node
4226 cl-struct-js2-with-node
4227 cl-struct-js2-xml-dot-query-node)
4228 "Node types that can have a parenthesized child expression.
4229 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4230
4231 (defsubst js2-paren-expr-node-p (node)
4232 "Return t for nodes that typically have a parenthesized child expression.
4233 Useful for computing the indentation anchors for arg-lists and conditions.
4234 Note that it may return a false positive, for instance when NODE is
4235 a `js2-new-node' and there are no arguments or parentheses."
4236 (memq (aref node 0) js2-paren-expr-nodes))
4237
4238 ;; Fake polymorphism... yech.
4239 (defun js2-node-lp (node)
4240 "Return relative left-paren position for NODE, if applicable.
4241 For `js2-elem-get-node' structs, returns left-bracket position.
4242 Note that the position may be nil in the case of a parse error."
4243 (cond
4244 ((js2-elem-get-node-p node)
4245 (js2-elem-get-node-lb node))
4246 ((js2-loop-node-p node)
4247 (js2-loop-node-lp node))
4248 ((js2-function-node-p node)
4249 (js2-function-node-lp node))
4250 ((js2-if-node-p node)
4251 (js2-if-node-lp node))
4252 ((js2-new-node-p node)
4253 (js2-new-node-lp node))
4254 ((js2-call-node-p node)
4255 (js2-call-node-lp node))
4256 ((js2-paren-node-p node)
4257 0)
4258 ((js2-switch-node-p node)
4259 (js2-switch-node-lp node))
4260 ((js2-catch-node-p node)
4261 (js2-catch-node-lp node))
4262 ((js2-let-node-p node)
4263 (js2-let-node-lp node))
4264 ((js2-array-comp-node-p node)
4265 (js2-array-comp-node-lp node))
4266 ((js2-with-node-p node)
4267 (js2-with-node-lp node))
4268 ((js2-xml-dot-query-node-p node)
4269 (1+ (js2-infix-node-op-pos node)))
4270 (t
4271 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4272
4273 ;; Fake polymorphism... blech.
4274 (defun js2-node-rp (node)
4275 "Return relative right-paren position for NODE, if applicable.
4276 For `js2-elem-get-node' structs, returns right-bracket position.
4277 Note that the position may be nil in the case of a parse error."
4278 (cond
4279 ((js2-elem-get-node-p node)
4280 (js2-elem-get-node-rb node))
4281 ((js2-loop-node-p node)
4282 (js2-loop-node-rp node))
4283 ((js2-function-node-p node)
4284 (js2-function-node-rp node))
4285 ((js2-if-node-p node)
4286 (js2-if-node-rp node))
4287 ((js2-new-node-p node)
4288 (js2-new-node-rp node))
4289 ((js2-call-node-p node)
4290 (js2-call-node-rp node))
4291 ((js2-paren-node-p node)
4292 (1- (js2-node-len node)))
4293 ((js2-switch-node-p node)
4294 (js2-switch-node-rp node))
4295 ((js2-catch-node-p node)
4296 (js2-catch-node-rp node))
4297 ((js2-let-node-p node)
4298 (js2-let-node-rp node))
4299 ((js2-array-comp-node-p node)
4300 (js2-array-comp-node-rp node))
4301 ((js2-with-node-p node)
4302 (js2-with-node-rp node))
4303 ((js2-xml-dot-query-node-p node)
4304 (1+ (js2-xml-dot-query-node-rp node)))
4305 (t
4306 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4307
4308 (defsubst js2-node-first-child (node)
4309 "Return the first element of `js2-node-child-list' for NODE."
4310 (car (js2-node-child-list node)))
4311
4312 (defsubst js2-node-last-child (node)
4313 "Return the last element of `js2-node-last-child' for NODE."
4314 (car (last (js2-node-child-list node))))
4315
4316 (defun js2-node-prev-sibling (node)
4317 "Return the previous statement in parent.
4318 Works for parents supported by `js2-node-child-list'.
4319 Returns nil if NODE is not in the parent, or PARENT is
4320 not a supported node, or if NODE is the first child."
4321 (let* ((p (js2-node-parent node))
4322 (kids (js2-node-child-list p))
4323 (sib (car kids)))
4324 (while (and kids
4325 (not (eq node (cadr kids))))
4326 (setq kids (cdr kids)
4327 sib (car kids)))
4328 sib))
4329
4330 (defun js2-node-next-sibling (node)
4331 "Return the next statement in parent block.
4332 Returns nil if NODE is not in the block, or PARENT is not
4333 a block node, or if NODE is the last statement."
4334 (let* ((p (js2-node-parent node))
4335 (kids (js2-node-child-list p)))
4336 (while (and kids
4337 (not (eq node (car kids))))
4338 (setq kids (cdr kids)))
4339 (cadr kids)))
4340
4341 (defun js2-node-find-child-before (pos parent &optional after)
4342 "Find the last child that starts before POS in parent.
4343 If AFTER is non-nil, returns first child starting after POS.
4344 POS is an absolute buffer position. PARENT is any node
4345 supported by `js2-node-child-list'.
4346 Returns nil if no applicable child is found."
4347 (let ((kids (if (js2-function-node-p parent)
4348 (js2-block-node-kids (js2-function-node-body parent))
4349 (js2-node-child-list parent)))
4350 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4351 (js2-function-node-body parent)
4352 parent)))
4353 kid result fn
4354 (continue t))
4355 (setq fn (if after '>= '<))
4356 (while (and kids continue)
4357 (setq kid (car kids))
4358 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4359 (setq result kid
4360 continue (not after))
4361 (setq continue after))
4362 (setq kids (cdr kids)))
4363 result))
4364
4365 (defun js2-node-find-child-after (pos parent)
4366 "Find first child that starts after POS in parent.
4367 POS is an absolute buffer position. PARENT is any node
4368 supported by `js2-node-child-list'.
4369 Returns nil if no applicable child is found."
4370 (js2-node-find-child-before pos parent 'after))
4371
4372 (defun js2-node-replace-child (pos parent new-node)
4373 "Replace node at index POS in PARENT with NEW-NODE.
4374 Only works for parents supported by `js2-node-child-list'."
4375 (let ((kids (js2-node-child-list parent))
4376 (i 0))
4377 (while (< i pos)
4378 (setq kids (cdr kids)
4379 i (1+ i)))
4380 (setcar kids new-node)
4381 (js2-node-add-children parent new-node)))
4382
4383 (defun js2-node-buffer (n)
4384 "Return the buffer associated with AST N.
4385 Returns nil if the buffer is not set as a property on the root
4386 node, or if parent links were not recorded during parsing."
4387 (let ((root (js2-node-root n)))
4388 (and root
4389 (js2-ast-root-p root)
4390 (js2-ast-root-buffer root))))
4391
4392 (defun js2-block-node-push (n kid)
4393 "Push js2-node KID onto the end of js2-block-node N's child list.
4394 KID is always added to the -end- of the kids list.
4395 Function also calls `js2-node-add-children' to add the parent link."
4396 (let ((kids (js2-node-child-list n)))
4397 (if kids
4398 (setcdr kids (nconc (cdr kids) (list kid)))
4399 (js2-node-set-child-list n (list kid)))
4400 (js2-node-add-children n kid)))
4401
4402 (defun js2-node-string (node)
4403 (with-current-buffer (or (js2-node-buffer node)
4404 (error "No buffer available for node %s" node))
4405 (let ((pos (js2-node-abs-pos node)))
4406 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4407
4408 ;; Container for storing the node we're looking for in a traversal.
4409 (js2-deflocal js2-discovered-node nil)
4410
4411 ;; Keep track of absolute node position during traversals.
4412 (js2-deflocal js2-visitor-offset nil)
4413
4414 (js2-deflocal js2-node-search-point nil)
4415
4416 (when js2-mode-dev-mode-p
4417 (defun js2-find-node-at-point ()
4418 (interactive)
4419 (let ((node (js2-node-at-point)))
4420 (message "%s" (or node "No node found at point"))))
4421 (defun js2-node-name-at-point ()
4422 (interactive)
4423 (let ((node (js2-node-at-point)))
4424 (message "%s" (if node
4425 (js2-node-short-name node)
4426 "No node found at point.")))))
4427
4428 (defun js2-node-at-point (&optional pos skip-comments)
4429 "Return AST node at POS, a buffer position, defaulting to current point.
4430 The `js2-mode-ast' variable must be set to the current parse tree.
4431 Signals an error if the AST (`js2-mode-ast') is nil.
4432 Always returns a node - if it can't find one, it returns the root.
4433 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4434 (let ((ast js2-mode-ast)
4435 result)
4436 (unless ast
4437 (error "No JavaScript AST available"))
4438 ;; Look through comments first, since they may be inside nodes that
4439 ;; would otherwise report a match.
4440 (setq pos (or pos (point))
4441 result (if (> pos (js2-node-abs-end ast))
4442 ast
4443 (if (not skip-comments)
4444 (js2-comment-at-point pos))))
4445 (unless result
4446 (setq js2-discovered-node nil
4447 js2-visitor-offset 0
4448 js2-node-search-point pos)
4449 (unwind-protect
4450 (catch 'js2-visit-done
4451 (js2-visit-ast ast #'js2-node-at-point-visitor))
4452 (setq js2-visitor-offset nil
4453 js2-node-search-point nil))
4454 (setq result js2-discovered-node))
4455 ;; may have found a comment beyond end of last child node,
4456 ;; since visiting the ast-root looks at the comment-list last.
4457 (if (and skip-comments
4458 (js2-comment-node-p result))
4459 (setq result nil))
4460 (or result js2-mode-ast)))
4461
4462 (defun js2-node-at-point-visitor (node end-p)
4463 (let ((rel-pos (js2-node-pos node))
4464 abs-pos
4465 abs-end
4466 (point js2-node-search-point))
4467 (cond
4468 (end-p
4469 ;; this evaluates to a non-nil return value, even if it's zero
4470 (decf js2-visitor-offset rel-pos))
4471 ;; we already looked for comments before visiting, and don't want them now
4472 ((js2-comment-node-p node)
4473 nil)
4474 (t
4475 (setq abs-pos (incf js2-visitor-offset rel-pos)
4476 ;; we only want to use the node if the point is before
4477 ;; the last character position in the node, so we decrement
4478 ;; the absolute end by 1.
4479 abs-end (+ abs-pos (js2-node-len node) -1))
4480 (cond
4481 ;; If this node starts after search-point, stop the search.
4482 ((> abs-pos point)
4483 (throw 'js2-visit-done nil))
4484 ;; If this node ends before the search-point, don't check kids.
4485 ((> point abs-end)
4486 nil)
4487 (t
4488 ;; Otherwise point is within this node, possibly in a child.
4489 (setq js2-discovered-node node)
4490 t)))))) ; keep processing kids to look for more specific match
4491
4492 (defsubst js2-block-comment-p (node)
4493 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4494 (and (js2-comment-node-p node)
4495 (memq (js2-comment-node-format node) '(jsdoc block))))
4496
4497 ;; TODO: put the comments in a vector and binary-search them instead
4498 (defun js2-comment-at-point (&optional pos)
4499 "Look through scanned comment nodes for one containing POS.
4500 POS is a buffer position that defaults to current point.
4501 Function returns nil if POS was not in any comment node."
4502 (let ((ast js2-mode-ast)
4503 (x (or pos (point)))
4504 beg end)
4505 (unless ast
4506 (error "No JavaScript AST available"))
4507 (catch 'done
4508 ;; Comments are stored in lexical order.
4509 (dolist (comment (js2-ast-root-comments ast) nil)
4510 (setq beg (js2-node-abs-pos comment)
4511 end (+ beg (js2-node-len comment)))
4512 (if (and (>= x beg)
4513 (<= x end))
4514 (throw 'done comment))))))
4515
4516 (defun js2-mode-find-parent-fn (node)
4517 "Find function enclosing NODE.
4518 Returns nil if NODE is not inside a function."
4519 (setq node (js2-node-parent node))
4520 (while (and node (not (js2-function-node-p node)))
4521 (setq node (js2-node-parent node)))
4522 (and (js2-function-node-p node) node))
4523
4524 (defun js2-mode-find-enclosing-fn (node)
4525 "Find function or root enclosing NODE."
4526 (if (js2-ast-root-p node)
4527 node
4528 (setq node (js2-node-parent node))
4529 (while (not (or (js2-ast-root-p node)
4530 (js2-function-node-p node)))
4531 (setq node (js2-node-parent node)))
4532 node))
4533
4534 (defun js2-mode-find-enclosing-node (beg end)
4535 "Find script or function fully enclosing BEG and END."
4536 (let ((node (js2-node-at-point beg))
4537 pos
4538 (continue t))
4539 (while continue
4540 (if (or (js2-ast-root-p node)
4541 (and (js2-function-node-p node)
4542 (<= (setq pos (js2-node-abs-pos node)) beg)
4543 (>= (+ pos (js2-node-len node)) end)))
4544 (setq continue nil)
4545 (setq node (js2-node-parent node))))
4546 node))
4547
4548 (defun js2-node-parent-script-or-fn (node)
4549 "Find script or function immediately enclosing NODE.
4550 If NODE is the ast-root, returns nil."
4551 (if (js2-ast-root-p node)
4552 nil
4553 (setq node (js2-node-parent node))
4554 (while (and node (not (or (js2-function-node-p node)
4555 (js2-script-node-p node))))
4556 (setq node (js2-node-parent node)))
4557 node))
4558
4559 (defun js2-node-is-descendant (node ancestor)
4560 "Return t if NODE is a descendant of ANCESTOR."
4561 (while (and node
4562 (not (eq node ancestor)))
4563 (setq node (js2-node-parent node)))
4564 node)
4565
4566 ;;; visitor infrastructure
4567
4568 (defun js2-visit-none (_node _callback)
4569 "Visitor for AST node that have no node children."
4570 nil)
4571
4572 (defun js2-print-none (_node _indent)
4573 "Visitor for AST node with no printed representation.")
4574
4575 (defun js2-print-body (node indent)
4576 "Print a statement, or a block without braces."
4577 (if (js2-block-node-p node)
4578 (dolist (kid (js2-block-node-kids node))
4579 (js2-print-ast kid indent))
4580 (js2-print-ast node indent)))
4581
4582 (defun js2-print-list (args &optional delimiter)
4583 (loop with len = (length args)
4584 for arg in args
4585 for count from 1
4586 do
4587 (when arg (js2-print-ast arg 0))
4588 (if (< count len)
4589 (insert (or delimiter ", ")))))
4590
4591 (defun js2-print-tree (ast)
4592 "Prints an AST to the current buffer.
4593 Makes `js2-ast-parent-nodes' available to the printer functions."
4594 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4595 (js2-print-ast ast)))
4596
4597 (defun js2-print-ast (node &optional indent)
4598 "Helper function for printing AST nodes.
4599 Requires `js2-ast-parent-nodes' to be non-nil.
4600 You should use `js2-print-tree' instead of this function."
4601 (let ((printer (get (aref node 0) 'js2-printer))
4602 (i (or indent 0)))
4603 ;; TODO: wedge comments in here somewhere
4604 (if printer
4605 (funcall printer node i))))
4606
4607 (defconst js2-side-effecting-tokens
4608 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4609 (dolist (tt (list js2-ASSIGN
4610 js2-ASSIGN_ADD
4611 js2-ASSIGN_BITAND
4612 js2-ASSIGN_BITOR
4613 js2-ASSIGN_BITXOR
4614 js2-ASSIGN_DIV
4615 js2-ASSIGN_LSH
4616 js2-ASSIGN_MOD
4617 js2-ASSIGN_MUL
4618 js2-ASSIGN_RSH
4619 js2-ASSIGN_SUB
4620 js2-ASSIGN_URSH
4621 js2-BLOCK
4622 js2-BREAK
4623 js2-CALL
4624 js2-CATCH
4625 js2-CATCH_SCOPE
4626 js2-CONST
4627 js2-CONTINUE
4628 js2-DEBUGGER
4629 js2-DEC
4630 js2-DELPROP
4631 js2-DEL_REF
4632 js2-DO
4633 js2-ELSE
4634 js2-EMPTY
4635 js2-ENTERWITH
4636 js2-EXPORT
4637 js2-EXPR_RESULT
4638 js2-FINALLY
4639 js2-FOR
4640 js2-FUNCTION
4641 js2-GOTO
4642 js2-IF
4643 js2-IFEQ
4644 js2-IFNE
4645 js2-IMPORT
4646 js2-INC
4647 js2-JSR
4648 js2-LABEL
4649 js2-LEAVEWITH
4650 js2-LET
4651 js2-LETEXPR
4652 js2-LOCAL_BLOCK
4653 js2-LOOP
4654 js2-NEW
4655 js2-REF_CALL
4656 js2-RETHROW
4657 js2-RETURN
4658 js2-RETURN_RESULT
4659 js2-SEMI
4660 js2-SETELEM
4661 js2-SETELEM_OP
4662 js2-SETNAME
4663 js2-SETPROP
4664 js2-SETPROP_OP
4665 js2-SETVAR
4666 js2-SET_REF
4667 js2-SET_REF_OP
4668 js2-SWITCH
4669 js2-TARGET
4670 js2-THROW
4671 js2-TRY
4672 js2-VAR
4673 js2-WHILE
4674 js2-WITH
4675 js2-WITHEXPR
4676 js2-YIELD))
4677 (aset tokens tt t))
4678 (if js2-instanceof-has-side-effects
4679 (aset tokens js2-INSTANCEOF t))
4680 tokens))
4681
4682 (defun js2-node-has-side-effects (node)
4683 "Return t if NODE has side effects."
4684 (when node ; makes it easier to handle malformed expressions
4685 (let ((tt (js2-node-type node)))
4686 (cond
4687 ;; This doubtless needs some work, since EXPR_VOID is used
4688 ;; in several ways in Rhino and I may not have caught them all.
4689 ;; I'll wait for people to notice incorrect warnings.
4690 ((and (= tt js2-EXPR_VOID)
4691 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4692 (let ((expr (js2-expr-stmt-node-expr node)))
4693 (or (js2-node-has-side-effects expr)
4694 (when (js2-string-node-p expr)
4695 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4696 ((= tt js2-COMMA)
4697 (js2-node-has-side-effects (js2-infix-node-right node)))
4698 ((or (= tt js2-AND)
4699 (= tt js2-OR))
4700 (or (js2-node-has-side-effects (js2-infix-node-right node))
4701 (js2-node-has-side-effects (js2-infix-node-left node))))
4702 ((= tt js2-HOOK)
4703 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4704 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4705 ((js2-paren-node-p node)
4706 (js2-node-has-side-effects (js2-paren-node-expr node)))
4707 ((= tt js2-ERROR) ; avoid cascaded error messages
4708 nil)
4709 (t
4710 (aref js2-side-effecting-tokens tt))))))
4711
4712 (defconst js2-stmt-node-types
4713 (list js2-BLOCK
4714 js2-BREAK
4715 js2-CONTINUE
4716 js2-DEFAULT ; e4x "default xml namespace" statement
4717 js2-DO
4718 js2-EXPR_RESULT
4719 js2-EXPR_VOID
4720 js2-FOR
4721 js2-IF
4722 js2-RETURN
4723 js2-SWITCH
4724 js2-THROW
4725 js2-TRY
4726 js2-WHILE
4727 js2-WITH)
4728 "Node types that only appear in statement contexts.
4729 The list does not include nodes that always appear as the child
4730 of another specific statement type, such as switch-cases,
4731 catch and finally blocks, and else-clauses. The list also excludes
4732 nodes like yield, let and var, which may appear in either expression
4733 or statement context, and in the latter context always have a
4734 `js2-expr-stmt-node' parent. Finally, the list does not include
4735 functions or scripts, which are treated separately from statements
4736 by the JavaScript parser and runtime.")
4737
4738 (defun js2-stmt-node-p (node)
4739 "Heuristic for figuring out if NODE is a statement.
4740 Some node types can appear in either an expression context or a
4741 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4742 For these node types in a statement context, the parent will be a
4743 `js2-expr-stmt-node'.
4744 Functions aren't included in the check."
4745 (memq (js2-node-type node) js2-stmt-node-types))
4746
4747 (defun js2-mode-find-first-stmt (node)
4748 "Search upward starting from NODE looking for a statement.
4749 For purposes of this function, a `js2-function-node' counts."
4750 (while (not (or (js2-stmt-node-p node)
4751 (js2-function-node-p node)))
4752 (setq node (js2-node-parent node)))
4753 node)
4754
4755 (defun js2-node-parent-stmt (node)
4756 "Return the node's first ancestor that is a statement.
4757 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4758 appearing in a statement context will have a parent that is a
4759 `js2-expr-stmt-node' that will be returned by this function."
4760 (let ((parent (js2-node-parent node)))
4761 (if (or (null parent)
4762 (js2-stmt-node-p parent)
4763 (and (js2-function-node-p parent)
4764 (not (eq (js2-function-node-form parent)
4765 'FUNCTION_EXPRESSION))))
4766 parent
4767 (js2-node-parent-stmt parent))))
4768
4769 ;; In the Mozilla Rhino sources, Roshan James writes:
4770 ;; Does consistent-return analysis on the function body when strict mode is
4771 ;; enabled.
4772 ;;
4773 ;; function (x) { return (x+1) }
4774 ;;
4775 ;; is ok, but
4776 ;;
4777 ;; function (x) { if (x < 0) return (x+1); }
4778 ;;
4779 ;; is not because the function can potentially return a value when the
4780 ;; condition is satisfied and if not, the function does not explicitly
4781 ;; return a value.
4782 ;;
4783 ;; This extends to checking mismatches such as "return" and "return <value>"
4784 ;; used in the same function. Warnings are not emitted if inconsistent
4785 ;; returns exist in code that can be statically shown to be unreachable.
4786 ;; Ex.
4787 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4788 ;;
4789 ;; emits no warning. However if the loop had a break statement, then a
4790 ;; warning would be emitted.
4791 ;;
4792 ;; The consistency analysis looks at control structures such as loops, ifs,
4793 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4794 ;; warns the user about an inconsistent set of termination possibilities.
4795 ;;
4796 ;; These flags enumerate the possible ways a statement/function can
4797 ;; terminate. These flags are used by endCheck() and by the Parser to
4798 ;; detect inconsistent return usage.
4799 ;;
4800 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4801 ;; able to execute (example: throw, continue)
4802 ;;
4803 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4804 ;; next one. Statement such as return dont. A compound statement may have
4805 ;; some branch that drops off control to the next statement.
4806 ;;
4807 ;; END_RETURNS indicates that the statement can return with no value.
4808 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4809 ;;
4810 ;; A compound statement such as
4811 ;; if (condition) {
4812 ;; return value;
4813 ;; }
4814 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4815
4816 (defconst js2-END_UNREACHED 0)
4817 (defconst js2-END_DROPS_OFF 1)
4818 (defconst js2-END_RETURNS 2)
4819 (defconst js2-END_RETURNS_VALUE 4)
4820 (defconst js2-END_YIELDS 8)
4821
4822 (defun js2-has-consistent-return-usage (node)
4823 "Check that every return usage in a function body is consistent.
4824 Returns t if the function satisfies strict mode requirement."
4825 (let ((n (js2-end-check node)))
4826 ;; either it doesn't return a value in any branch...
4827 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4828 ;; or it returns a value (or is unreached) at every branch
4829 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4830 js2-END_RETURNS
4831 js2-END_YIELDS)))))
4832
4833 (defun js2-end-check-if (node)
4834 "Ensure that return usage in then/else blocks is consistent.
4835 If there is no else block, then the return statement can fall through.
4836 Returns logical OR of END_* flags"
4837 (let ((th (js2-if-node-then-part node))
4838 (el (js2-if-node-else-part node)))
4839 (if (null th)
4840 js2-END_UNREACHED
4841 (logior (js2-end-check th) (if el
4842 (js2-end-check el)
4843 js2-END_DROPS_OFF)))))
4844
4845 (defun js2-end-check-switch (node)
4846 "Consistency of return statements is checked between the case statements.
4847 If there is no default, then the switch can fall through. If there is a
4848 default, we check to see if all code paths in the default return or if
4849 there is a code path that can fall through.
4850 Returns logical OR of END_* flags."
4851 (let ((rv js2-END_UNREACHED)
4852 default-case)
4853 ;; examine the cases
4854 (catch 'break
4855 (dolist (c (js2-switch-node-cases node))
4856 (if (js2-case-node-expr c)
4857 (js2-set-flag rv (js2-end-check-block c))
4858 (setq default-case c)
4859 (throw 'break nil))))
4860 ;; we don't care how the cases drop into each other
4861 (js2-clear-flag rv js2-END_DROPS_OFF)
4862 ;; examine the default
4863 (js2-set-flag rv (if default-case
4864 (js2-end-check default-case)
4865 js2-END_DROPS_OFF))
4866 rv))
4867
4868 (defun js2-end-check-try (node)
4869 "If the block has a finally, return consistency is checked in the
4870 finally block. If all code paths in the finally return, then the
4871 returns in the try-catch blocks don't matter. If there is a code path
4872 that does not return or if there is no finally block, the returns
4873 of the try and catch blocks are checked for mismatch.
4874 Returns logical OR of END_* flags."
4875 (let ((finally (js2-try-node-finally-block node))
4876 rv)
4877 ;; check the finally if it exists
4878 (setq rv (if finally
4879 (js2-end-check (js2-finally-node-body finally))
4880 js2-END_DROPS_OFF))
4881 ;; If the finally block always returns, then none of the returns
4882 ;; in the try or catch blocks matter.
4883 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4884 (js2-clear-flag rv js2-END_DROPS_OFF)
4885 ;; examine the try block
4886 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4887 ;; check each catch block
4888 (dolist (cb (js2-try-node-catch-clauses node))
4889 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4890 rv))
4891
4892 (defun js2-end-check-loop (node)
4893 "Return statement in the loop body must be consistent.
4894 The default assumption for any kind of a loop is that it will eventually
4895 terminate. The only exception is a loop with a constant true condition.
4896 Code that follows such a loop is examined only if one can determine
4897 statically that there is a break out of the loop.
4898
4899 for(... ; ... ; ...) {}
4900 for(... in ... ) {}
4901 while(...) { }
4902 do { } while(...)
4903
4904 Returns logical OR of END_* flags."
4905 (let ((rv (js2-end-check (js2-loop-node-body node)))
4906 (condition (cond
4907 ((js2-while-node-p node)
4908 (js2-while-node-condition node))
4909 ((js2-do-node-p node)
4910 (js2-do-node-condition node))
4911 ((js2-for-node-p node)
4912 (js2-for-node-condition node)))))
4913
4914 ;; check to see if the loop condition is always true
4915 (if (and condition
4916 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4917 (js2-clear-flag rv js2-END_DROPS_OFF))
4918
4919 ;; look for effect of breaks
4920 (js2-set-flag rv (js2-node-get-prop node
4921 'CONTROL_BLOCK_PROP
4922 js2-END_UNREACHED))
4923 rv))
4924
4925 (defun js2-end-check-block (node)
4926 "A general block of code is examined statement by statement.
4927 If any statement (even a compound one) returns in all branches, then
4928 subsequent statements are not examined.
4929 Returns logical OR of END_* flags."
4930 (let* ((rv js2-END_DROPS_OFF)
4931 (kids (js2-block-node-kids node))
4932 (n (car kids)))
4933 ;; Check each statment. If the statement can continue onto the next
4934 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4935 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4936 (js2-clear-flag rv js2-END_DROPS_OFF)
4937 (js2-set-flag rv (js2-end-check n))
4938 (setq kids (cdr kids)
4939 n (car kids)))
4940 rv))
4941
4942 (defun js2-end-check-label (node)
4943 "A labeled statement implies that there may be a break to the label.
4944 The function processes the labeled statement and then checks the
4945 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4946 particular label.
4947 Returns logical OR of END_* flags."
4948 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4949 (logior rv (js2-node-get-prop node
4950 'CONTROL_BLOCK_PROP
4951 js2-END_UNREACHED))))
4952
4953 (defun js2-end-check-break (node)
4954 "When a break is encountered annotate the statement being broken
4955 out of by setting its CONTROL_BLOCK_PROP property.
4956 Returns logical OR of END_* flags."
4957 (and (js2-break-node-target node)
4958 (js2-node-set-prop (js2-break-node-target node)
4959 'CONTROL_BLOCK_PROP
4960 js2-END_DROPS_OFF))
4961 js2-END_UNREACHED)
4962
4963 (defun js2-end-check (node)
4964 "Examine the body of a function, doing a basic reachability analysis.
4965 Returns a combination of flags END_* flags that indicate
4966 how the function execution can terminate. These constitute only the
4967 pessimistic set of termination conditions. It is possible that at
4968 runtime certain code paths will never be actually taken. Hence this
4969 analysis will flag errors in cases where there may not be errors.
4970 Returns logical OR of END_* flags"
4971 (let (kid)
4972 (cond
4973 ((js2-break-node-p node)
4974 (js2-end-check-break node))
4975 ((js2-expr-stmt-node-p node)
4976 (if (setq kid (js2-expr-stmt-node-expr node))
4977 (js2-end-check kid)
4978 js2-END_DROPS_OFF))
4979 ((or (js2-continue-node-p node)
4980 (js2-throw-node-p node))
4981 js2-END_UNREACHED)
4982 ((js2-return-node-p node)
4983 (if (setq kid (js2-return-node-retval node))
4984 js2-END_RETURNS_VALUE
4985 js2-END_RETURNS))
4986 ((js2-loop-node-p node)
4987 (js2-end-check-loop node))
4988 ((js2-switch-node-p node)
4989 (js2-end-check-switch node))
4990 ((js2-labeled-stmt-node-p node)
4991 (js2-end-check-label node))
4992 ((js2-if-node-p node)
4993 (js2-end-check-if node))
4994 ((js2-try-node-p node)
4995 (js2-end-check-try node))
4996 ((js2-block-node-p node)
4997 (if (null (js2-block-node-kids node))
4998 js2-END_DROPS_OFF
4999 (js2-end-check-block node)))
5000 ((js2-yield-node-p node)
5001 js2-END_YIELDS)
5002 (t
5003 js2-END_DROPS_OFF))))
5004
5005 (defun js2-always-defined-boolean-p (node)
5006 "Check if NODE always evaluates to true or false in boolean context.
5007 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5008 nor always false."
5009 (let ((tt (js2-node-type node))
5010 num)
5011 (cond
5012 ((or (= tt js2-FALSE) (= tt js2-NULL))
5013 'ALWAYS_FALSE)
5014 ((= tt js2-TRUE)
5015 'ALWAYS_TRUE)
5016 ((= tt js2-NUMBER)
5017 (setq num (js2-number-node-num-value node))
5018 (if (and (not (eq num 0.0e+NaN))
5019 (not (zerop num)))
5020 'ALWAYS_TRUE
5021 'ALWAYS_FALSE))
5022 (t
5023 nil))))
5024
5025 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5026 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5027
5028 (defvar js2-tokens nil
5029 "List of all defined token names.") ; initialized in `js2-token-names'
5030
5031 (defconst js2-token-names
5032 (let* ((names (make-vector js2-num-tokens -1))
5033 (case-fold-search nil) ; only match js2-UPPER_CASE
5034 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5035 (loop for sym in syms
5036 for i from 0
5037 do
5038 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5039 (not (boundp sym)))
5040 (aset names (symbol-value sym) ; code, e.g. 152
5041 (downcase
5042 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5043 (push sym js2-tokens)))
5044 names)
5045 "Vector mapping int values to token string names, sans `js2-' prefix.")
5046
5047 (defun js2-tt-name (tok)
5048 "Return a string name for TOK, a token symbol or code.
5049 Signals an error if it's not a recognized token."
5050 (let ((code tok))
5051 (if (symbolp tok)
5052 (setq code (symbol-value tok)))
5053 (if (eq code -1)
5054 "ERROR"
5055 (if (and (numberp code)
5056 (not (minusp code))
5057 (< code js2-num-tokens))
5058 (aref js2-token-names code)
5059 (error "Invalid token: %s" code)))))
5060
5061 (defsubst js2-tt-sym (tok)
5062 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5063 (intern (js2-tt-name tok)))
5064
5065 (defconst js2-token-codes
5066 (let ((table (make-hash-table :test 'eq :size 256)))
5067 (loop for name across js2-token-names
5068 for sym = (intern (concat "js2-" (upcase name)))
5069 do
5070 (puthash sym (symbol-value sym) table))
5071 ;; clean up a few that are "wrong" in Rhino's token codes
5072 (puthash 'js2-DELETE js2-DELPROP table)
5073 table)
5074 "Hashtable mapping token type symbols to their bytecodes.")
5075
5076 (defsubst js2-tt-code (sym)
5077 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5078 (or (gethash sym js2-token-codes)
5079 (error "Invalid token symbol: %s " sym))) ; signal code bug
5080
5081 (defun js2-report-scan-error (msg &optional no-throw beg len)
5082 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5083 (js2-report-error msg nil
5084 (or beg (js2-current-token-beg))
5085 (or len (js2-current-token-len)))
5086 (unless no-throw
5087 (throw 'return js2-ERROR)))
5088
5089 (defun js2-set-string-from-buffer (token)
5090 "Set `string' and `end' slots for TOKEN, return the string."
5091 (setf (js2-token-end token) js2-ts-cursor
5092 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5093
5094 ;; TODO: could potentially avoid a lot of consing by allocating a
5095 ;; char buffer the way Rhino does.
5096 (defsubst js2-add-to-string (c)
5097 (push c js2-ts-string-buffer))
5098
5099 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5100 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5101 ;; any other character: when it's not part of the current token, we
5102 ;; unget it, allowing it to be read again by the following call.
5103 (defsubst js2-unget-char ()
5104 (decf js2-ts-cursor))
5105
5106 ;; Rhino distinguishes \r and \n line endings. We don't need to
5107 ;; because we only scan from Emacs buffers, which always use \n.
5108 (defun js2-get-char ()
5109 "Read and return the next character from the input buffer.
5110 Increments `js2-ts-lineno' if the return value is a newline char.
5111 Updates `js2-ts-cursor' to the point after the returned char.
5112 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5113 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5114 (let (c)
5115 ;; check for end of buffer
5116 (if (>= js2-ts-cursor (point-max))
5117 (setq js2-ts-hit-eof t
5118 js2-ts-cursor (1+ js2-ts-cursor)
5119 c js2-EOF_CHAR) ; return value
5120 ;; otherwise read next char
5121 (setq c (char-before (incf js2-ts-cursor)))
5122 ;; if we read a newline, update counters
5123 (if (= c ?\n)
5124 (setq js2-ts-line-start js2-ts-cursor
5125 js2-ts-lineno (1+ js2-ts-lineno)))
5126 ;; TODO: skip over format characters
5127 c)))
5128
5129 (defun js2-read-unicode-escape ()
5130 "Read a \\uNNNN sequence from the input.
5131 Assumes the ?\ and ?u have already been read.
5132 Returns the unicode character, or nil if it wasn't a valid character.
5133 Doesn't change the values of any scanner variables."
5134 ;; I really wish I knew a better way to do this, but I can't
5135 ;; find the Emacs function that takes a 16-bit int and converts
5136 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5137 ;; Have to first check that it's 4 hex characters or it may stop
5138 ;; the read early.
5139 (ignore-errors
5140 (let ((s (buffer-substring-no-properties js2-ts-cursor
5141 (+ 4 js2-ts-cursor))))
5142 (if (string-match "[[:alnum:]]\\{4\\}" s)
5143 (read (concat "?\\u" s))))))
5144
5145 (defun js2-match-char (test)
5146 "Consume and return next character if it matches TEST, a character.
5147 Returns nil and consumes nothing if TEST is not the next character."
5148 (let ((c (js2-get-char)))
5149 (if (eq c test)
5150 t
5151 (js2-unget-char)
5152 nil)))
5153
5154 (defun js2-peek-char ()
5155 (prog1
5156 (js2-get-char)
5157 (js2-unget-char)))
5158
5159 (defun js2-java-identifier-start-p (c)
5160 (or
5161 (memq c '(?$ ?_))
5162 (js2-char-uppercase-p c)
5163 (js2-char-lowercase-p c)))
5164
5165 (defun js2-java-identifier-part-p (c)
5166 "Implementation of java.lang.Character.isJavaIdentifierPart()."
5167 ;; TODO: make me Unicode-friendly. See comments above.
5168 (or
5169 (memq c '(?$ ?_))
5170 (js2-char-uppercase-p c)
5171 (js2-char-lowercase-p c)
5172 (and (>= c ?0) (<= c ?9))))
5173
5174 (defun js2-alpha-p (c)
5175 (cond ((and (<= ?A c) (<= c ?Z)) t)
5176 ((and (<= ?a c) (<= c ?z)) t)
5177 (t nil)))
5178
5179 (defsubst js2-digit-p (c)
5180 (and (<= ?0 c) (<= c ?9)))
5181
5182 (defun js2-js-space-p (c)
5183 (if (<= c 127)
5184 (memq c '(#x20 #x9 #xB #xC #xD))
5185 (or
5186 (eq c #xA0)
5187 ;; TODO: change this nil to check for Unicode space character
5188 nil)))
5189
5190 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5191
5192 (defun js2-skip-line ()
5193 "Skip to end of line."
5194 (while (not (memq (js2-get-char) js2-eol-chars)))
5195 (js2-unget-char)
5196 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5197 (setq js2-token-end js2-ts-cursor))
5198
5199 (defun js2-init-scanner (&optional buf line)
5200 "Create token stream for BUF starting on LINE.
5201 BUF defaults to `current-buffer' and LINE defaults to 1.
5202
5203 A buffer can only have one scanner active at a time, which yields
5204 dramatically simpler code than using a defstruct. If you need to
5205 have simultaneous scanners in a buffer, copy the regions to scan
5206 into temp buffers."
5207 (with-current-buffer (or buf (current-buffer))
5208 (setq js2-ts-dirty-line nil
5209 js2-ts-hit-eof nil
5210 js2-ts-line-start 0
5211 js2-ts-lineno (or line 1)
5212 js2-ts-line-end-char -1
5213 js2-ts-cursor (point-min)
5214 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5215 js2-ti-tokens-cursor 0
5216 js2-ti-lookahead 0
5217 js2-ts-is-xml-attribute nil
5218 js2-ts-xml-is-tag-content nil
5219 js2-ts-xml-open-tags-count 0
5220 js2-ts-string-buffer nil)))
5221
5222 ;; This function uses the cached op, string and number fields in
5223 ;; TokenStream; if getToken has been called since the passed token
5224 ;; was scanned, the op or string printed may be incorrect.
5225 (defun js2-token-to-string (token)
5226 ;; Not sure where this function is used in Rhino. Not tested.
5227 (if (not js2-debug-print-trees)
5228 ""
5229 (let ((name (js2-tt-name token)))
5230 (cond
5231 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5232 (concat name " `" (js2-current-token-string) "'"))
5233 ((eq token js2-NUMBER)
5234 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5235 (t
5236 name)))))
5237
5238 (defconst js2-keywords
5239 '(break
5240 case catch const continue
5241 debugger default delete do
5242 else enum
5243 false finally for function
5244 if in instanceof import
5245 let
5246 new null
5247 return
5248 switch
5249 this throw true try typeof
5250 var void
5251 while with
5252 yield))
5253
5254 ;; Token names aren't exactly the same as the keywords, unfortunately.
5255 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5256 (defconst js2-kwd-tokens
5257 (let ((table (make-vector js2-num-tokens nil))
5258 (tokens
5259 (list js2-BREAK
5260 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5261 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5262 js2-ELSE
5263 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5264 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5265 js2-LET
5266 js2-NEW js2-NULL
5267 js2-RETURN
5268 js2-SWITCH
5269 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5270 js2-VAR
5271 js2-WHILE js2-WITH
5272 js2-YIELD)))
5273 (dolist (i tokens)
5274 (aset table i 'font-lock-keyword-face))
5275 (aset table js2-STRING 'font-lock-string-face)
5276 (aset table js2-REGEXP 'font-lock-string-face)
5277 (aset table js2-COMMENT 'font-lock-comment-face)
5278 (aset table js2-THIS 'font-lock-builtin-face)
5279 (aset table js2-VOID 'font-lock-constant-face)
5280 (aset table js2-NULL 'font-lock-constant-face)
5281 (aset table js2-TRUE 'font-lock-constant-face)
5282 (aset table js2-FALSE 'font-lock-constant-face)
5283 table)
5284 "Vector whose values are non-nil for tokens that are keywords.
5285 The values are default faces to use for highlighting the keywords.")
5286
5287 (defconst js2-reserved-words
5288 '(abstract
5289 boolean byte
5290 char class
5291 double
5292 enum export extends
5293 final float
5294 goto
5295 implements import int interface
5296 long
5297 native
5298 package private protected public
5299 short static super synchronized
5300 throws transient
5301 volatile))
5302
5303 (defconst js2-keyword-names
5304 (let ((table (make-hash-table :test 'equal)))
5305 (loop for k in js2-keywords
5306 do (puthash
5307 (symbol-name k) ; instanceof
5308 (intern (concat "js2-"
5309 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5310 table))
5311 table)
5312 "JavaScript keywords by name, mapped to their symbols.")
5313
5314 (defconst js2-reserved-word-names
5315 (let ((table (make-hash-table :test 'equal)))
5316 (loop for k in js2-reserved-words
5317 do
5318 (puthash (symbol-name k) 'js2-RESERVED table))
5319 table)
5320 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5321
5322 (defun js2-collect-string (buf)
5323 "Convert BUF, a list of chars, to a string.
5324 Reverses BUF before converting."
5325 (if buf
5326 (apply #'string (nreverse buf))
5327 ""))
5328
5329 (defun js2-string-to-keyword (s)
5330 "Return token for S, a string, if S is a keyword or reserved word.
5331 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5332 (or (gethash s js2-keyword-names)
5333 (gethash s js2-reserved-word-names)))
5334
5335 (defsubst js2-ts-set-char-token-bounds (token)
5336 "Used when next token is one character."
5337 (setf (js2-token-beg token) (1- js2-ts-cursor)
5338 (js2-token-end token) js2-ts-cursor))
5339
5340 (defsubst js2-ts-return (token type)
5341 "Update the `end' and `type' slots of TOKEN,
5342 then throw `return' with value TYPE."
5343 (setf (js2-token-end token) js2-ts-cursor
5344 (js2-token-type token) type)
5345 (throw 'return type))
5346
5347 (defun js2-x-digit-to-int (c accumulator)
5348 "Build up a hex number.
5349 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5350 corresponding number. Otherwise return -1."
5351 (catch 'return
5352 (catch 'check
5353 ;; Use 0..9 < A..Z < a..z
5354 (cond
5355 ((<= c ?9)
5356 (decf c ?0)
5357 (if (<= 0 c)
5358 (throw 'check nil)))
5359 ((<= c ?F)
5360 (when (<= ?A c)
5361 (decf c (- ?A 10))
5362 (throw 'check nil)))
5363 ((<= c ?f)
5364 (when (<= ?a c)
5365 (decf c (- ?a 10))
5366 (throw 'check nil))))
5367 (throw 'return -1))
5368 (logior c (lsh accumulator 4))))
5369
5370 (defun js2-get-token ()
5371 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5372 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5373 next saved token.
5374
5375 This function will not return a newline (js2-EOL) - instead, it
5376 gobbles newlines until it finds a non-newline token. Call
5377 `js2-peek-token-or-eol' when you care about newlines.
5378
5379 This function will also not return a js2-COMMENT. Instead, it
5380 records comments found in `js2-scanned-comments'. If the token
5381 returned by this function immediately follows a jsdoc comment,
5382 the token is flagged as such."
5383 (if (zerop js2-ti-lookahead)
5384 (js2-get-token-internal)
5385 (decf js2-ti-lookahead)
5386 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5387 (let ((tt (js2-current-token-type)))
5388 (assert (not (= tt js2-EOL)))
5389 tt)))
5390
5391 (defun js2-unget-token ()
5392 (assert (< js2-ti-lookahead js2-ti-max-lookahead))
5393 (incf js2-ti-lookahead)
5394 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5395
5396 (defun js2-get-token-internal ()
5397 (let* ((token (js2-get-token-internal-1)) ; call scanner
5398 (tt (js2-token-type token))
5399 saw-eol
5400 face)
5401 ;; process comments
5402 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5403 (if (= tt js2-EOL)
5404 (setq saw-eol t)
5405 (setq saw-eol nil)
5406 (when js2-record-comments
5407 (js2-record-comment token)))
5408 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5409 (setq token (js2-get-token-internal-1) ; call scanner again
5410 tt (js2-token-type token)))
5411
5412 (when saw-eol
5413 (setf (js2-token-follows-eol-p token) t))
5414
5415 ;; perform lexical fontification as soon as token is scanned
5416 (when js2-parse-ide-mode
5417 (cond
5418 ((minusp tt)
5419 (js2-record-face 'js2-error token))
5420 ((setq face (aref js2-kwd-tokens tt))
5421 (js2-record-face face token))
5422 ((and (= tt js2-NAME)
5423 (equal (js2-token-string token) "undefined"))
5424 (js2-record-face 'font-lock-constant-face token))))
5425 tt))
5426
5427 (defun js2-get-token-internal-1 ()
5428 "Return next JavaScript token type, an int such as js2-RETURN.
5429 During operation, creates an instance of `js2-token' struct, sets
5430 its relevant fields and puts it into `js2-ti-tokens'."
5431 (let (c c1 identifier-start is-unicode-escape-start
5432 contains-escape escape-val str result base
5433 is-integer quote-char val look-for-slash continue tt
5434 (token (js2-new-token 0)))
5435 (setq
5436 tt
5437 (catch 'return
5438 (while t
5439 ;; Eat whitespace, possibly sensitive to newlines.
5440 (setq continue t)
5441 (while continue
5442 (setq c (js2-get-char))
5443 (cond
5444 ((eq c js2-EOF_CHAR)
5445 (js2-unget-char)
5446 (js2-ts-set-char-token-bounds token)
5447 (throw 'return js2-EOF))
5448 ((eq c ?\n)
5449 (js2-ts-set-char-token-bounds token)
5450 (setq js2-ts-dirty-line nil)
5451 (throw 'return js2-EOL))
5452 ((not (js2-js-space-p c))
5453 (if (/= c ?-) ; in case end of HTML comment
5454 (setq js2-ts-dirty-line t))
5455 (setq continue nil))))
5456 ;; Assume the token will be 1 char - fixed up below.
5457 (js2-ts-set-char-token-bounds token)
5458 (when (eq c ?@)
5459 (throw 'return js2-XMLATTR))
5460 ;; identifier/keyword/instanceof?
5461 ;; watch out for starting with a <backslash>
5462 (cond
5463 ((eq c ?\\)
5464 (setq c (js2-get-char))
5465 (if (eq c ?u)
5466 (setq identifier-start t
5467 is-unicode-escape-start t
5468 js2-ts-string-buffer nil)
5469 (setq identifier-start nil)
5470 (js2-unget-char)
5471 (setq c ?\\)))
5472 (t
5473 (when (setq identifier-start (js2-java-identifier-start-p c))
5474 (setq js2-ts-string-buffer nil)
5475 (js2-add-to-string c))))
5476 (when identifier-start
5477 (setq contains-escape is-unicode-escape-start)
5478 (catch 'break
5479 (while t
5480 (if is-unicode-escape-start
5481 ;; strictly speaking we should probably push-back
5482 ;; all the bad characters if the <backslash>uXXXX
5483 ;; sequence is malformed. But since there isn't a
5484 ;; correct context(is there?) for a bad Unicode
5485 ;; escape sequence in an identifier, we can report
5486 ;; an error here.
5487 (progn
5488 (setq escape-val 0)
5489 (dotimes (_ 4)
5490 (setq c (js2-get-char)
5491 escape-val (js2-x-digit-to-int c escape-val))
5492 ;; Next check takes care of c < 0 and bad escape
5493 (if (minusp escape-val)
5494 (throw 'break nil)))
5495 (if (minusp escape-val)
5496 (js2-report-scan-error "msg.invalid.escape" t))
5497 (js2-add-to-string escape-val)
5498 (setq is-unicode-escape-start nil))
5499 (setq c (js2-get-char))
5500 (cond
5501 ((eq c ?\\)
5502 (setq c (js2-get-char))
5503 (if (eq c ?u)
5504 (setq is-unicode-escape-start t
5505 contains-escape t)
5506 (js2-report-scan-error "msg.illegal.character" t)))
5507 (t
5508 (if (or (eq c js2-EOF_CHAR)
5509 (not (js2-java-identifier-part-p c)))
5510 (throw 'break nil))
5511 (js2-add-to-string c))))))
5512 (js2-unget-char)
5513 (setf str (js2-collect-string js2-ts-string-buffer)
5514 (js2-token-end token) js2-ts-cursor)
5515 (unless contains-escape
5516 ;; OPT we shouldn't have to make a string (object!) to
5517 ;; check if it's a keyword.
5518 ;; Return the corresponding token if it's a keyword
5519 (when (setq result (js2-string-to-keyword str))
5520 (if (and (< js2-language-version 170)
5521 (memq result '(js2-LET js2-YIELD)))
5522 ;; LET and YIELD are tokens only in 1.7 and later
5523 (setq result 'js2-NAME))
5524 (if (not (eq result 'js2-RESERVED))
5525 (throw 'return (js2-tt-code result)))
5526 (js2-report-warning "msg.reserved.keyword" str)))
5527 ;; If we want to intern these as Rhino does, just use (intern str)
5528 (setf (js2-token-string token) str)
5529 (throw 'return js2-NAME)) ; end identifier/kwd check
5530 ;; is it a number?
5531 (when (or (js2-digit-p c)
5532 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5533 (setq js2-ts-string-buffer nil
5534 base 10)
5535 (when (eq c ?0)
5536 (setq c (js2-get-char))
5537 (cond
5538 ((or (eq c ?x) (eq c ?X))
5539 (setq base 16)
5540 (setq c (js2-get-char)))
5541 ((js2-digit-p c)
5542 (setq base 8))
5543 (t
5544 (js2-add-to-string ?0))))
5545 (if (eq base 16)
5546 (while (<= 0 (js2-x-digit-to-int c 0))
5547 (js2-add-to-string c)
5548 (setq c (js2-get-char)))
5549 (while (and (<= ?0 c) (<= c ?9))
5550 ;; We permit 08 and 09 as decimal numbers, which
5551 ;; makes our behavior a superset of the ECMA
5552 ;; numeric grammar. We might not always be so
5553 ;; permissive, so we warn about it.
5554 (when (and (eq base 8) (>= c ?8))
5555 (js2-report-warning "msg.bad.octal.literal"
5556 (if (eq c ?8) "8" "9"))
5557 (setq base 10))
5558 (js2-add-to-string c)
5559 (setq c (js2-get-char))))
5560 (setq is-integer t)
5561 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5562 (setq is-integer nil)
5563 (when (eq c ?.)
5564 (loop do
5565 (js2-add-to-string c)
5566 (setq c (js2-get-char))
5567 while (js2-digit-p c)))
5568 (when (memq c '(?e ?E))
5569 (js2-add-to-string c)
5570 (setq c (js2-get-char))
5571 (when (memq c '(?+ ?-))
5572 (js2-add-to-string c)
5573 (setq c (js2-get-char)))
5574 (unless (js2-digit-p c)
5575 (js2-report-scan-error "msg.missing.exponent" t))
5576 (loop do
5577 (js2-add-to-string c)
5578 (setq c (js2-get-char))
5579 while (js2-digit-p c))))
5580 (js2-unget-char)
5581 (let ((str (js2-set-string-from-buffer token)))
5582 (setf (js2-token-number token)
5583 (if (and (eq base 10) (not is-integer))
5584 (string-to-number str)
5585 ;; TODO: call runtime number-parser. Some of it is in
5586 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5587 (string-to-number str))))
5588 (throw 'return js2-NUMBER))
5589 ;; is it a string?
5590 (when (memq c '(?\" ?\'))
5591 ;; We attempt to accumulate a string the fast way, by
5592 ;; building it directly out of the reader. But if there
5593 ;; are any escaped characters in the string, we revert to
5594 ;; building it out of a string buffer.
5595 (setq quote-char c
5596 js2-ts-string-buffer nil
5597 c (js2-get-char))
5598 (catch 'break
5599 (while (/= c quote-char)
5600 (catch 'continue
5601 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5602 (js2-unget-char)
5603 (setf (js2-token-end token) js2-ts-cursor)
5604 (js2-report-error "msg.unterminated.string.lit")
5605 (throw 'return js2-STRING))
5606 (when (eq c ?\\)
5607 ;; We've hit an escaped character
5608 (setq c (js2-get-char))
5609 (case c
5610 (?b (setq c ?\b))
5611 (?f (setq c ?\f))
5612 (?n (setq c ?\n))
5613 (?r (setq c ?\r))
5614 (?t (setq c ?\t))
5615 (?v (setq c ?\v))
5616 (?u
5617 (setq c1 (js2-read-unicode-escape))
5618 (if js2-parse-ide-mode
5619 (if c1
5620 (progn
5621 ;; just copy the string in IDE-mode
5622 (js2-add-to-string ?\\)
5623 (js2-add-to-string ?u)
5624 (dotimes (_ 3)
5625 (js2-add-to-string (js2-get-char)))
5626 (setq c (js2-get-char))) ; added at end of loop
5627 ;; flag it as an invalid escape
5628 (js2-report-warning "msg.invalid.escape"
5629 nil (- js2-ts-cursor 2) 6))
5630 ;; Get 4 hex digits; if the u escape is not
5631 ;; followed by 4 hex digits, use 'u' + the
5632 ;; literal character sequence that follows.
5633 (js2-add-to-string ?u)
5634 (setq escape-val 0)
5635 (dotimes (_ 4)
5636 (setq c (js2-get-char)
5637 escape-val (js2-x-digit-to-int c escape-val))
5638 (if (minusp escape-val)
5639 (throw 'continue nil))
5640 (js2-add-to-string c))
5641 ;; prepare for replace of stored 'u' sequence by escape value
5642 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5643 c escape-val)))
5644 (?x
5645 ;; Get 2 hex digits, defaulting to 'x'+literal
5646 ;; sequence, as above.
5647 (setq c (js2-get-char)
5648 escape-val (js2-x-digit-to-int c 0))
5649 (if (minusp escape-val)
5650 (progn
5651 (js2-add-to-string ?x)
5652 (throw 'continue nil))
5653 (setq c1 c
5654 c (js2-get-char)
5655 escape-val (js2-x-digit-to-int c escape-val))
5656 (if (minusp escape-val)
5657 (progn
5658 (js2-add-to-string ?x)
5659 (js2-add-to-string c1)
5660 (throw 'continue nil))
5661 ;; got 2 hex digits
5662 (setq c escape-val))))
5663 (?\n
5664 ;; Remove line terminator after escape to follow
5665 ;; SpiderMonkey and C/C++
5666 (setq c (js2-get-char))
5667 (throw 'continue nil))
5668 (t
5669 (when (and (<= ?0 c) (< c ?8))
5670 (setq val (- c ?0)
5671 c (js2-get-char))
5672 (when (and (<= ?0 c) (< c ?8))
5673 (setq val (- (+ (* 8 val) c) ?0)
5674 c (js2-get-char))
5675 (when (and (<= ?0 c)
5676 (< c ?8)
5677 (< val #o37))
5678 ;; c is 3rd char of octal sequence only
5679 ;; if the resulting val <= 0377
5680 (setq val (- (+ (* 8 val) c) ?0)
5681 c (js2-get-char))))
5682 (js2-unget-char)
5683 (setq c val)))))
5684 (js2-add-to-string c)
5685 (setq c (js2-get-char)))))
5686 (js2-set-string-from-buffer token)
5687 (throw 'return js2-STRING))
5688 (js2-ts-return token
5689 (case c
5690 (?\;
5691 (throw 'return js2-SEMI))
5692 (?\[
5693 (throw 'return js2-LB))
5694 (?\]
5695 (throw 'return js2-RB))
5696 (?{
5697 (throw 'return js2-LC))
5698 (?}
5699 (throw 'return js2-RC))
5700 (?\(
5701 (throw 'return js2-LP))
5702 (?\)
5703 (throw 'return js2-RP))
5704 (?,
5705 (throw 'return js2-COMMA))
5706 (??
5707 (throw 'return js2-HOOK))
5708 (?:
5709 (if (js2-match-char ?:)
5710 js2-COLONCOLON
5711 (throw 'return js2-COLON)))
5712 (?.
5713 (if (js2-match-char ?.)
5714 (if (js2-match-char ?.)
5715 js2-TRIPLEDOT js2-DOTDOT)
5716 (if (js2-match-char ?\()
5717 js2-DOTQUERY
5718 (throw 'return js2-DOT))))
5719 (?|
5720 (if (js2-match-char ?|)
5721 (throw 'return js2-OR)
5722 (if (js2-match-char ?=)
5723 js2-ASSIGN_BITOR
5724 (throw 'return js2-BITOR))))
5725 (?^
5726 (if (js2-match-char ?=)
5727 js2-ASSIGN_BITOR
5728 (throw 'return js2-BITXOR)))
5729 (?&
5730 (if (js2-match-char ?&)
5731 (throw 'return js2-AND)
5732 (if (js2-match-char ?=)
5733 js2-ASSIGN_BITAND
5734 (throw 'return js2-BITAND))))
5735 (?=
5736 (if (js2-match-char ?=)
5737 (if (js2-match-char ?=)
5738 js2-SHEQ
5739 (throw 'return js2-EQ))
5740 (if (js2-match-char ?>)
5741 (js2-ts-return token js2-ARROW)
5742 (throw 'return js2-ASSIGN))))
5743 (?!
5744 (if (js2-match-char ?=)
5745 (if (js2-match-char ?=)
5746 js2-SHNE
5747 js2-NE)
5748 (throw 'return js2-NOT)))
5749 (?<
5750 ;; NB:treat HTML begin-comment as comment-till-eol
5751 (when (js2-match-char ?!)
5752 (when (js2-match-char ?-)
5753 (when (js2-match-char ?-)
5754 (js2-skip-line)
5755 (setf (js2-token-comment-type (js2-current-token)) 'html)
5756 (throw 'return js2-COMMENT)))
5757 (js2-unget-char))
5758 (if (js2-match-char ?<)
5759 (if (js2-match-char ?=)
5760 js2-ASSIGN_LSH
5761 js2-LSH)
5762 (if (js2-match-char ?=)
5763 js2-LE
5764 (throw 'return js2-LT))))
5765 (?>
5766 (if (js2-match-char ?>)
5767 (if (js2-match-char ?>)
5768 (if (js2-match-char ?=)
5769 js2-ASSIGN_URSH
5770 js2-URSH)
5771 (if (js2-match-char ?=)
5772 js2-ASSIGN_RSH
5773 js2-RSH))
5774 (if (js2-match-char ?=)
5775 js2-GE
5776 (throw 'return js2-GT))))
5777 (?*
5778 (if (js2-match-char ?=)
5779 js2-ASSIGN_MUL
5780 (throw 'return js2-MUL)))
5781 (?/
5782 ;; is it a // comment?
5783 (when (js2-match-char ?/)
5784 (setf (js2-token-beg token) (- js2-ts-cursor 2))
5785 (js2-skip-line)
5786 (setf (js2-token-comment-type token) 'line)
5787 ;; include newline so highlighting goes to end of window
5788 (incf (js2-token-end token))
5789 (throw 'return js2-COMMENT))
5790 ;; is it a /* comment?
5791 (when (js2-match-char ?*)
5792 (setf look-for-slash nil
5793 (js2-token-beg token) (- js2-ts-cursor 2)
5794 (js2-token-comment-type token)
5795 (if (js2-match-char ?*)
5796 (progn
5797 (setq look-for-slash t)
5798 'jsdoc)
5799 'block))
5800 (while t
5801 (setq c (js2-get-char))
5802 (cond
5803 ((eq c js2-EOF_CHAR)
5804 (setf (js2-token-end token) (1- js2-ts-cursor))
5805 (js2-report-error "msg.unterminated.comment")
5806 (throw 'return js2-COMMENT))
5807 ((eq c ?*)
5808 (setq look-for-slash t))
5809 ((eq c ?/)
5810 (if look-for-slash
5811 (js2-ts-return token js2-COMMENT)))
5812 (t
5813 (setf look-for-slash nil
5814 (js2-token-end token) js2-ts-cursor)))))
5815 (if (js2-match-char ?=)
5816 js2-ASSIGN_DIV
5817 (throw 'return js2-DIV)))
5818 (?#
5819 (when js2-skip-preprocessor-directives
5820 (js2-skip-line)
5821 (setf (js2-token-comment-type token) 'preprocessor
5822 (js2-token-end token) js2-ts-cursor)
5823 (throw 'return js2-COMMENT))
5824 (throw 'return js2-ERROR))
5825 (?%
5826 (if (js2-match-char ?=)
5827 js2-ASSIGN_MOD
5828 (throw 'return js2-MOD)))
5829 (?~
5830 (throw 'return js2-BITNOT))
5831 (?+
5832 (if (js2-match-char ?=)
5833 js2-ASSIGN_ADD
5834 (if (js2-match-char ?+)
5835 js2-INC
5836 (throw 'return js2-ADD))))
5837 (?-
5838 (cond
5839 ((js2-match-char ?=)
5840 (setq c js2-ASSIGN_SUB))
5841 ((js2-match-char ?-)
5842 (unless js2-ts-dirty-line
5843 ;; treat HTML end-comment after possible whitespace
5844 ;; after line start as comment-until-eol
5845 (when (js2-match-char ?>)
5846 (js2-skip-line)
5847 (setf (js2-token-comment-type (js2-current-token)) 'html)
5848 (throw 'return js2-COMMENT)))
5849 (setq c js2-DEC))
5850 (t
5851 (setq c js2-SUB)))
5852 (setq js2-ts-dirty-line t)
5853 c)
5854 (otherwise
5855 (js2-report-scan-error "msg.illegal.character")))))))
5856 (setf (js2-token-type token) tt)
5857 token))
5858
5859 (defun js2-read-regexp (start-tt)
5860 "Called by parser when it gets / or /= in literal context."
5861 (let (c err
5862 in-class ; inside a '[' .. ']' character-class
5863 flags
5864 (continue t)
5865 (token (js2-new-token 0)))
5866 (setq js2-ts-string-buffer nil)
5867 (if (eq start-tt js2-ASSIGN_DIV)
5868 ;; mis-scanned /=
5869 (js2-add-to-string ?=)
5870 (if (not (eq start-tt js2-DIV))
5871 (error "failed assertion")))
5872 (while (and (not err)
5873 (or (/= (setq c (js2-get-char)) ?/)
5874 in-class))
5875 (cond
5876 ((or (= c ?\n)
5877 (= c js2-EOF_CHAR))
5878 (setf (js2-token-end token) (1- js2-ts-cursor)
5879 err t
5880 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
5881 (js2-report-error "msg.unterminated.re.lit"))
5882 (t (cond
5883 ((= c ?\\)
5884 (js2-add-to-string c)
5885 (setq c (js2-get-char)))
5886 ((= c ?\[)
5887 (setq in-class t))
5888 ((= c ?\])
5889 (setq in-class nil)))
5890 (js2-add-to-string c))))
5891 (unless err
5892 (while continue
5893 (cond
5894 ((js2-match-char ?g)
5895 (push ?g flags))
5896 ((js2-match-char ?i)
5897 (push ?i flags))
5898 ((js2-match-char ?m)
5899 (push ?m flags))
5900 (t
5901 (setq continue nil))))
5902 (if (js2-alpha-p (js2-peek-char))
5903 (js2-report-scan-error "msg.invalid.re.flag" t
5904 js2-ts-cursor 1))
5905 (js2-set-string-from-buffer token)
5906 ;; tell `parse-partial-sexp' to ignore this range of chars
5907 (js2-record-text-property (js2-current-token-beg)
5908 (js2-current-token-end) 'syntax-class '(2)))
5909 (js2-collect-string flags)))
5910
5911 (defun js2-get-first-xml-token ()
5912 (setq js2-ts-xml-open-tags-count 0
5913 js2-ts-is-xml-attribute nil
5914 js2-ts-xml-is-tag-content nil)
5915 (js2-unget-char)
5916 (js2-get-next-xml-token))
5917
5918 (defun js2-xml-discard-string (token)
5919 "Throw away the string in progress and flag an XML parse error."
5920 (setf js2-ts-string-buffer nil
5921 (js2-token-string token) nil)
5922 (js2-report-scan-error "msg.XML.bad.form" t))
5923
5924 (defun js2-get-next-xml-token ()
5925 (setq js2-ts-string-buffer nil) ; for recording the XML
5926 (let ((token (js2-new-token 0))
5927 c result)
5928 (setq result
5929 (catch 'return
5930 (while t
5931 (setq c (js2-get-char))
5932 (cond
5933 ((= c js2-EOF_CHAR)
5934 (throw 'return js2-ERROR))
5935 (js2-ts-xml-is-tag-content
5936 (case c
5937 (?>
5938 (js2-add-to-string c)
5939 (setq js2-ts-xml-is-tag-content nil
5940 js2-ts-is-xml-attribute nil))
5941 (?/
5942 (js2-add-to-string c)
5943 (when (eq ?> (js2-peek-char))
5944 (setq c (js2-get-char))
5945 (js2-add-to-string c)
5946 (setq js2-ts-xml-is-tag-content nil)
5947 (decf js2-ts-xml-open-tags-count)))
5948 (?{
5949 (js2-unget-char)
5950 (js2-set-string-from-buffer token)
5951 (throw 'return js2-XML))
5952 ((?\' ?\")
5953 (js2-add-to-string c)
5954 (unless (js2-read-quoted-string c token)
5955 (throw 'return js2-ERROR)))
5956 (?=
5957 (js2-add-to-string c)
5958 (setq js2-ts-is-xml-attribute t))
5959 ((? ?\t ?\r ?\n)
5960 (js2-add-to-string c))
5961 (t
5962 (js2-add-to-string c)
5963 (setq js2-ts-is-xml-attribute nil)))
5964 (when (and (not js2-ts-xml-is-tag-content)
5965 (zerop js2-ts-xml-open-tags-count))
5966 (js2-set-string-from-buffer token)
5967 (throw 'return js2-XMLEND)))
5968 (t
5969 ;; else not tag content
5970 (case c
5971 (?<
5972 (js2-add-to-string c)
5973 (setq c (js2-peek-char))
5974 (case c
5975 (?!
5976 (setq c (js2-get-char)) ;; skip !
5977 (js2-add-to-string c)
5978 (setq c (js2-peek-char))
5979 (case c
5980 (?-
5981 (setq c (js2-get-char)) ;; skip -
5982 (js2-add-to-string c)
5983 (if (eq c ?-)
5984 (progn
5985 (js2-add-to-string c)
5986 (unless (js2-read-xml-comment token)
5987 (throw 'return js2-ERROR)))
5988 (js2-xml-discard-string token)
5989 (throw 'return js2-ERROR)))
5990 (?\[
5991 (setq c (js2-get-char)) ;; skip [
5992 (js2-add-to-string c)
5993 (if (and (= (js2-get-char) ?C)
5994 (= (js2-get-char) ?D)
5995 (= (js2-get-char) ?A)
5996 (= (js2-get-char) ?T)
5997 (= (js2-get-char) ?A)
5998 (= (js2-get-char) ?\[))
5999 (progn
6000 (js2-add-to-string ?C)
6001 (js2-add-to-string ?D)
6002 (js2-add-to-string ?A)
6003 (js2-add-to-string ?T)
6004 (js2-add-to-string ?A)
6005 (js2-add-to-string ?\[)
6006 (unless (js2-read-cdata token)
6007 (throw 'return js2-ERROR)))
6008 (js2-xml-discard-string token)
6009 (throw 'return js2-ERROR)))
6010 (t
6011 (unless (js2-read-entity token)
6012 (throw 'return js2-ERROR))))
6013 ;; Allow bare CDATA section, e.g.:
6014 ;; let xml = <![CDATA[ foo bar baz ]]>;
6015 (when (zerop js2-ts-xml-open-tags-count)
6016 (throw 'return js2-XMLEND)))
6017 (??
6018 (setq c (js2-get-char)) ;; skip ?
6019 (js2-add-to-string c)
6020 (unless (js2-read-PI token)
6021 (throw 'return js2-ERROR)))
6022 (?/
6023 ;; end tag
6024 (setq c (js2-get-char)) ;; skip /
6025 (js2-add-to-string c)
6026 (when (zerop js2-ts-xml-open-tags-count)
6027 (js2-xml-discard-string token)
6028 (throw 'return js2-ERROR))
6029 (setq js2-ts-xml-is-tag-content t)
6030 (decf js2-ts-xml-open-tags-count))
6031 (t
6032 ;; start tag
6033 (setq js2-ts-xml-is-tag-content t)
6034 (incf js2-ts-xml-open-tags-count))))
6035 (?{
6036 (js2-unget-char)
6037 (js2-set-string-from-buffer token)
6038 (throw 'return js2-XML))
6039 (t
6040 (js2-add-to-string c))))))))
6041 (setf (js2-token-end token) js2-ts-cursor)
6042 (setf (js2-token-type token) result)
6043 result))
6044
6045 (defun js2-read-quoted-string (quote token)
6046 (let (c)
6047 (catch 'return
6048 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6049 (js2-add-to-string c)
6050 (if (eq c quote)
6051 (throw 'return t)))
6052 (js2-xml-discard-string token) ;; throw away string in progress
6053 nil)))
6054
6055 (defun js2-read-xml-comment (token)
6056 (let ((c (js2-get-char)))
6057 (catch 'return
6058 (while (/= c js2-EOF_CHAR)
6059 (catch 'continue
6060 (js2-add-to-string c)
6061 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6062 (setq c (js2-get-char))
6063 (js2-add-to-string c)
6064 (if (eq (js2-peek-char) ?>)
6065 (progn
6066 (setq c (js2-get-char)) ;; skip >
6067 (js2-add-to-string c)
6068 (throw 'return t))
6069 (throw 'continue nil)))
6070 (setq c (js2-get-char))))
6071 (js2-xml-discard-string token)
6072 nil)))
6073
6074 (defun js2-read-cdata (token)
6075 (let ((c (js2-get-char)))
6076 (catch 'return
6077 (while (/= c js2-EOF_CHAR)
6078 (catch 'continue
6079 (js2-add-to-string c)
6080 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6081 (setq c (js2-get-char))
6082 (js2-add-to-string c)
6083 (if (eq (js2-peek-char) ?>)
6084 (progn
6085 (setq c (js2-get-char)) ;; Skip >
6086 (js2-add-to-string c)
6087 (throw 'return t))
6088 (throw 'continue nil)))
6089 (setq c (js2-get-char))))
6090 (js2-xml-discard-string token)
6091 nil)))
6092
6093 (defun js2-read-entity (token)
6094 (let ((decl-tags 1)
6095 c)
6096 (catch 'return
6097 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6098 (js2-add-to-string c)
6099 (case c
6100 (?<
6101 (incf decl-tags))
6102 (?>
6103 (decf decl-tags)
6104 (if (zerop decl-tags)
6105 (throw 'return t)))))
6106 (js2-xml-discard-string token)
6107 nil)))
6108
6109 (defun js2-read-PI (token)
6110 "Scan an XML processing instruction."
6111 (let (c)
6112 (catch 'return
6113 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6114 (js2-add-to-string c)
6115 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6116 (setq c (js2-get-char)) ;; Skip >
6117 (js2-add-to-string c)
6118 (throw 'return t)))
6119 (js2-xml-discard-string token)
6120 nil)))
6121
6122 ;;; Highlighting
6123
6124 (defun js2-set-face (beg end face &optional record)
6125 "Fontify a region. If RECORD is non-nil, record for later."
6126 (when (plusp js2-highlight-level)
6127 (setq beg (min (point-max) beg)
6128 beg (max (point-min) beg)
6129 end (min (point-max) end)
6130 end (max (point-min) end))
6131 (if record
6132 (push (list beg end face) js2-mode-fontifications)
6133 (put-text-property beg end 'font-lock-face face))))
6134
6135 (defsubst js2-clear-face (beg end)
6136 (remove-text-properties beg end '(font-lock-face nil
6137 help-echo nil
6138 point-entered nil
6139 c-in-sws nil)))
6140
6141 (defconst js2-ecma-global-props
6142 (concat "^"
6143 (regexp-opt
6144 '("Infinity" "NaN" "undefined" "arguments") t)
6145 "$")
6146 "Value properties of the Ecma-262 Global Object.
6147 Shown at or above `js2-highlight-level' 2.")
6148
6149 ;; might want to add the name "arguments" to this list?
6150 (defconst js2-ecma-object-props
6151 (concat "^"
6152 (regexp-opt
6153 '("prototype" "__proto__" "__parent__") t)
6154 "$")
6155 "Value properties of the Ecma-262 Object constructor.
6156 Shown at or above `js2-highlight-level' 2.")
6157
6158 (defconst js2-ecma-global-funcs
6159 (concat
6160 "^"
6161 (regexp-opt
6162 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6163 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6164 "$")
6165 "Function properties of the Ecma-262 Global object.
6166 Shown at or above `js2-highlight-level' 2.")
6167
6168 (defconst js2-ecma-number-props
6169 (concat "^"
6170 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6171 "NEGATIVE_INFINITY"
6172 "POSITIVE_INFINITY") t)
6173 "$")
6174 "Properties of the Ecma-262 Number constructor.
6175 Shown at or above `js2-highlight-level' 2.")
6176
6177 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6178 "Properties of the Ecma-262 Date constructor.
6179 Shown at or above `js2-highlight-level' 2.")
6180
6181 (defconst js2-ecma-math-props
6182 (concat "^"
6183 (regexp-opt
6184 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6185 t)
6186 "$")
6187 "Properties of the Ecma-262 Math object.
6188 Shown at or above `js2-highlight-level' 2.")
6189
6190 (defconst js2-ecma-math-funcs
6191 (concat "^"
6192 (regexp-opt
6193 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6194 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6195 "$")
6196 "Function properties of the Ecma-262 Math object.
6197 Shown at or above `js2-highlight-level' 2.")
6198
6199 (defconst js2-ecma-function-props
6200 (concat
6201 "^"
6202 (regexp-opt
6203 '(;; properties of the Object prototype object
6204 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6205 "toLocaleString" "toString" "valueOf"
6206 ;; properties of the Function prototype object
6207 "apply" "call"
6208 ;; properties of the Array prototype object
6209 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6210 "splice" "unshift"
6211 ;; properties of the String prototype object
6212 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6213 "localeCompare" "match" "replace" "search" "split" "substring"
6214 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6215 "toUpperCase"
6216 ;; properties of the Number prototype object
6217 "toExponential" "toFixed" "toPrecision"
6218 ;; properties of the Date prototype object
6219 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6220 "getMinutes" "getMonth" "getSeconds" "getTime"
6221 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6222 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6223 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6224 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6225 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6226 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6227 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6228 "toTimeString" "toUTCString"
6229 ;; properties of the RegExp prototype object
6230 "exec" "test"
6231 ;; properties of the JSON prototype object
6232 "parse" "stringify"
6233 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6234 "toSource" "__defineGetter__" "__defineSetter__"
6235 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6236 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6237 t)
6238 "$")
6239 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6240 Shown at or above `js2-highlight-level' 3.")
6241
6242 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6243 (let ((target-name (and target
6244 (js2-name-node-p target)
6245 (js2-name-node-name target)))
6246 (prop-name (if prop (js2-name-node-name prop)))
6247 (level2 (>= js2-highlight-level 2))
6248 (level3 (>= js2-highlight-level 3)))
6249 (when level2
6250 (let ((face
6251 (if call-p
6252 (cond
6253 ((and target prop)
6254 (cond
6255 ((and level3 (string-match js2-ecma-function-props prop-name))
6256 'font-lock-builtin-face)
6257 ((and target-name prop)
6258 (cond
6259 ((string= target-name "Date")
6260 (if (string-match js2-ecma-date-props prop-name)
6261 'font-lock-builtin-face))
6262 ((string= target-name "Math")
6263 (if (string-match js2-ecma-math-funcs prop-name)
6264 'font-lock-builtin-face))))))
6265 (prop
6266 (if (string-match js2-ecma-global-funcs prop-name)
6267 'font-lock-builtin-face)))
6268 (cond
6269 ((and target prop)
6270 (cond
6271 ((string= target-name "Number")
6272 (if (string-match js2-ecma-number-props prop-name)
6273 'font-lock-constant-face))
6274 ((string= target-name "Math")
6275 (if (string-match js2-ecma-math-props prop-name)
6276 'font-lock-constant-face))))
6277 (prop
6278 (if (string-match js2-ecma-object-props prop-name)
6279 'font-lock-constant-face))))))
6280 (when face
6281 (let ((pos (+ (js2-node-pos parent) ; absolute
6282 (js2-node-pos prop)))) ; relative
6283 (js2-set-face pos
6284 (+ pos (js2-node-len prop))
6285 face 'record)))))))
6286
6287 (defun js2-parse-highlight-member-expr-node (node)
6288 "Perform syntax highlighting of EcmaScript built-in properties.
6289 The variable `js2-highlight-level' governs this highighting."
6290 (let (face target prop name pos end parent call-p callee)
6291 (cond
6292 ;; case 1: simple name, e.g. foo
6293 ((js2-name-node-p node)
6294 (setq name (js2-name-node-name node))
6295 ;; possible for name to be nil in rare cases - saw it when
6296 ;; running js2-mode on an elisp buffer. Might as well try to
6297 ;; make it so js2-mode never barfs.
6298 (when name
6299 (setq face (if (string-match js2-ecma-global-props name)
6300 'font-lock-constant-face))
6301 (when face
6302 (setq pos (js2-node-pos node)
6303 end (+ pos (js2-node-len node)))
6304 (js2-set-face pos end face 'record))))
6305 ;; case 2: property access or function call
6306 ((or (js2-prop-get-node-p node)
6307 ;; highlight function call if expr is a prop-get node
6308 ;; or a plain name (i.e. unqualified function call)
6309 (and (setq call-p (js2-call-node-p node))
6310 (setq callee (js2-call-node-target node)) ; separate setq!
6311 (or (js2-prop-get-node-p callee)
6312 (js2-name-node-p callee))))
6313 (setq parent node
6314 node (if call-p callee node))
6315 (if (and call-p (js2-name-node-p callee))
6316 (setq prop callee)
6317 (setq target (js2-prop-get-node-left node)
6318 prop (js2-prop-get-node-right node)))
6319 (cond
6320 ((js2-name-node-p prop)
6321 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6322 (js2-parse-highlight-prop-get parent target prop call-p))
6323 ((js2-name-node-p target)
6324 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6325 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6326
6327 (defun js2-parse-highlight-member-expr-fn-name (expr)
6328 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6329 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6330 We currently only handle the case where the last component is a prop-get
6331 of a simple name. Called before EXPR has a parent node."
6332 (let (pos
6333 (name (and (js2-prop-get-node-p expr)
6334 (js2-prop-get-node-right expr))))
6335 (when (js2-name-node-p name)
6336 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6337 (js2-node-pos name)))
6338 (+ pos (js2-node-len name))
6339 'font-lock-function-name-face
6340 'record))))
6341
6342 ;; source: http://jsdoc.sourceforge.net/
6343 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6344 ;; allows type specifications, and needs work before entering the wild.
6345
6346 (defconst js2-jsdoc-param-tag-regexp
6347 (concat "^\\s-*\\*+\\s-*\\(@"
6348 "\\(?:param\\|argument\\)"
6349 "\\)"
6350 "\\s-*\\({[^}]+}\\)?" ; optional type
6351 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6352 "\\>")
6353 "Matches jsdoc tags with optional type and optional param name.")
6354
6355 (defconst js2-jsdoc-typed-tag-regexp
6356 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6357 (regexp-opt
6358 '("enum"
6359 "extends"
6360 "field"
6361 "id"
6362 "implements"
6363 "lends"
6364 "mods"
6365 "requires"
6366 "return"
6367 "returns"
6368 "throw"
6369 "throws"))
6370 "\\)\\)\\s-*\\({[^}]+}\\)?")
6371 "Matches jsdoc tags with optional type.")
6372
6373 (defconst js2-jsdoc-arg-tag-regexp
6374 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6375 (regexp-opt
6376 '("alias"
6377 "augments"
6378 "borrows"
6379 "bug"
6380 "base"
6381 "config"
6382 "default"
6383 "define"
6384 "exception"
6385 "function"
6386 "member"
6387 "memberOf"
6388 "name"
6389 "namespace"
6390 "property"
6391 "since"
6392 "suppress"
6393 "this"
6394 "throws"
6395 "type"
6396 "version"))
6397 "\\)\\)\\s-+\\([^ \t]+\\)")
6398 "Matches jsdoc tags with a single argument.")
6399
6400 (defconst js2-jsdoc-empty-tag-regexp
6401 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6402 (regexp-opt
6403 '("addon"
6404 "author"
6405 "class"
6406 "const"
6407 "constant"
6408 "constructor"
6409 "constructs"
6410 "deprecated"
6411 "desc"
6412 "description"
6413 "event"
6414 "example"
6415 "exec"
6416 "export"
6417 "fileoverview"
6418 "final"
6419 "function"
6420 "hidden"
6421 "ignore"
6422 "implicitCast"
6423 "inheritDoc"
6424 "inner"
6425 "interface"
6426 "license"
6427 "noalias"
6428 "noshadow"
6429 "notypecheck"
6430 "override"
6431 "owner"
6432 "preserve"
6433 "preserveTry"
6434 "private"
6435 "protected"
6436 "public"
6437 "static"
6438 "supported"
6439 ))
6440 "\\)\\)\\s-*")
6441 "Matches empty jsdoc tags.")
6442
6443 (defconst js2-jsdoc-link-tag-regexp
6444 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6445 "Matches a jsdoc link or code tag.")
6446
6447 (defconst js2-jsdoc-see-tag-regexp
6448 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6449 "Matches a jsdoc @see tag.")
6450
6451 (defconst js2-jsdoc-html-tag-regexp
6452 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6453 "Matches a simple (no attributes) html start- or end-tag.")
6454
6455 (defun js2-jsdoc-highlight-helper ()
6456 (js2-set-face (match-beginning 1)
6457 (match-end 1)
6458 'js2-jsdoc-tag)
6459 (if (match-beginning 2)
6460 (if (save-excursion
6461 (goto-char (match-beginning 2))
6462 (= (char-after) ?{))
6463 (js2-set-face (1+ (match-beginning 2))
6464 (1- (match-end 2))
6465 'js2-jsdoc-type)
6466 (js2-set-face (match-beginning 2)
6467 (match-end 2)
6468 'js2-jsdoc-value)))
6469 (if (match-beginning 3)
6470 (js2-set-face (match-beginning 3)
6471 (match-end 3)
6472 'js2-jsdoc-value)))
6473
6474 (defun js2-highlight-jsdoc (ast)
6475 "Highlight doc comment tags."
6476 (let ((comments (js2-ast-root-comments ast))
6477 beg end)
6478 (save-excursion
6479 (dolist (node comments)
6480 (when (eq (js2-comment-node-format node) 'jsdoc)
6481 (setq beg (js2-node-abs-pos node)
6482 end (+ beg (js2-node-len node)))
6483 (save-restriction
6484 (narrow-to-region beg end)
6485 (dolist (re (list js2-jsdoc-param-tag-regexp
6486 js2-jsdoc-typed-tag-regexp
6487 js2-jsdoc-arg-tag-regexp
6488 js2-jsdoc-link-tag-regexp
6489 js2-jsdoc-see-tag-regexp
6490 js2-jsdoc-empty-tag-regexp))
6491 (goto-char beg)
6492 (while (re-search-forward re nil t)
6493 (js2-jsdoc-highlight-helper)))
6494 ;; simple highlighting for html tags
6495 (goto-char beg)
6496 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6497 (js2-set-face (match-beginning 1)
6498 (match-end 1)
6499 'js2-jsdoc-html-tag-delimiter)
6500 (js2-set-face (match-beginning 2)
6501 (match-end 2)
6502 'js2-jsdoc-html-tag-name)
6503 (js2-set-face (match-beginning 3)
6504 (match-end 3)
6505 'js2-jsdoc-html-tag-delimiter))))))))
6506
6507 (defun js2-highlight-assign-targets (_node left right)
6508 "Highlight function properties and external variables."
6509 (let (leftpos name)
6510 ;; highlight vars and props assigned function values
6511 (when (js2-function-node-p right)
6512 (cond
6513 ;; var foo = function() {...}
6514 ((js2-name-node-p left)
6515 (setq name left))
6516 ;; foo.bar.baz = function() {...}
6517 ((and (js2-prop-get-node-p left)
6518 (js2-name-node-p (js2-prop-get-node-right left)))
6519 (setq name (js2-prop-get-node-right left))))
6520 (when name
6521 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6522 (+ leftpos (js2-node-len name))
6523 'font-lock-function-name-face
6524 'record)))))
6525
6526 (defun js2-record-name-node (node)
6527 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6528 later. NODE must be a name node."
6529 (let ((leftpos (js2-node-abs-pos node)))
6530 (push (list node js2-current-scope
6531 leftpos
6532 (+ leftpos (js2-node-len node)))
6533 js2-recorded-identifiers)))
6534
6535 (defun js2-highlight-undeclared-vars ()
6536 "After entire parse is finished, look for undeclared variable references.
6537 We have to wait until entire buffer is parsed, since JavaScript permits var
6538 decls to occur after they're used.
6539
6540 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6541 it is considered declared."
6542 (let (name)
6543 (dolist (entry js2-recorded-identifiers)
6544 (destructuring-bind (name-node scope pos end) entry
6545 (setq name (js2-name-node-name name-node))
6546 (unless (or (member name js2-global-externs)
6547 (member name js2-default-externs)
6548 (member name js2-additional-externs)
6549 (js2-get-defining-scope scope name))
6550 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6551 'js2-external-variable))))
6552 (setq js2-recorded-identifiers nil)))
6553
6554 (defun js2-set-default-externs ()
6555 "Set the value of `js2-default-externs' based on the various
6556 `js2-include-?-externs' variables."
6557 (setq js2-default-externs
6558 (append js2-ecma-262-externs
6559 (if js2-include-browser-externs js2-browser-externs)
6560 (if js2-include-rhino-externs js2-rhino-externs)
6561 (if js2-include-node-externs js2-node-externs)
6562 (if (or js2-include-browser-externs js2-include-node-externs)
6563 js2-typed-array-externs))))
6564
6565 (defun js2-apply-jslint-globals ()
6566 (setq js2-additional-externs
6567 (nconc (js2-get-jslint-globals)
6568 js2-additional-externs)))
6569
6570 (defun js2-get-jslint-globals ()
6571 (loop for node in (js2-ast-root-comments js2-mode-ast)
6572 when (and (eq 'block (js2-comment-node-format node))
6573 (save-excursion
6574 (goto-char (js2-node-abs-pos node))
6575 (looking-at "/\\*global ")))
6576 append (js2-get-jslint-globals-in
6577 (match-end 0)
6578 (js2-node-abs-end node))))
6579
6580 (defun js2-get-jslint-globals-in (beg end)
6581 (let (res)
6582 (save-excursion
6583 (goto-char beg)
6584 (while (re-search-forward js2-mode-identifier-re end t)
6585 (let ((match (match-string 0)))
6586 (unless (member match '("true" "false"))
6587 (push match res)))))
6588 (nreverse res)))
6589
6590 ;;; IMenu support
6591
6592 ;; We currently only support imenu, but eventually should support speedbar and
6593 ;; possibly other browsing mechanisms.
6594
6595 ;; The basic strategy is to identify function assignment targets of the form
6596 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6597 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6598 ;; for imenu after parsing is finished.
6599
6600 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6601 ;; JavaScript, and the general problem is undecidable. However, several forms
6602 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6603 ;; include:
6604
6605 ;; function foo() -- function declaration
6606 ;; foo = function() -- function expression assigned to variable
6607 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6608 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6609 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6610 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6611 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6612 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6613 ;; function foo() {function bar() {...}} -- nested function
6614 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6615
6616 ;; This list boils down to a few forms that can be combined recursively.
6617 ;; Top-level named function declarations include both the left-hand (name)
6618 ;; and the right-hand (function value) expressions needed to produce an imenu
6619 ;; entry. The other "right-hand" forms we need to look for are:
6620 ;; - functions declared as props/getters/setters in object literals
6621 ;; - nested named function declarations
6622 ;; The "left-hand" expressions that functions can be assigned to include:
6623 ;; - local/global variables
6624 ;; - nested property-get expressions like a.b.c.d
6625 ;; - element gets like foo[10] or foo['bar'] where the index
6626 ;; expression can be trivially converted to a property name. They
6627 ;; effectively then become property gets.
6628
6629 ;; All the different definition types are canonicalized into the form
6630 ;; foo.bar.baz = position-of-function-keyword
6631
6632 ;; We need to build a trie-like structure for imenu. As an example,
6633 ;; consider the following JavaScript code:
6634
6635 ;; a = function() {...} // function at position 5
6636 ;; b = function() {...} // function at position 25
6637 ;; foo = function() {...} // function at position 100
6638 ;; foo.bar = function() {...} // function at position 200
6639 ;; foo.bar.baz = function() {...} // function at position 300
6640 ;; foo.bar.zab = function() {...} // function at position 400
6641
6642 ;; During parsing we accumulate an entry for each definition in
6643 ;; the variable `js2-imenu-recorder', like so:
6644
6645 ;; '((fn a 5)
6646 ;; (fn b 25)
6647 ;; (fn foo 100)
6648 ;; (fn foo bar 200)
6649 ;; (fn foo bar baz 300)
6650 ;; (fn foo bar zab 400))
6651
6652 ;; Where 'fn' is the respective function node.
6653 ;; After parsing these entries are merged into this alist-trie:
6654
6655 ;; '((a . 1)
6656 ;; (b . 2)
6657 ;; (foo (<definition> . 3)
6658 ;; (bar (<definition> . 6)
6659 ;; (baz . 100)
6660 ;; (zab . 200))))
6661
6662 ;; Note the wacky need for a <definition> name. The token can be anything
6663 ;; that isn't a valid JavaScript identifier, because you might make foo
6664 ;; a function and then start setting properties on it that are also functions.
6665
6666 (defun js2-prop-node-name (node)
6667 "Return the name of a node that may be a property-get/property-name.
6668 If NODE is not a valid name-node, string-node or integral number-node,
6669 returns nil. Otherwise returns the string name/value of the node."
6670 (cond
6671 ((js2-name-node-p node)
6672 (js2-name-node-name node))
6673 ((js2-string-node-p node)
6674 (js2-string-node-value node))
6675 ((and (js2-number-node-p node)
6676 (string-match "^[0-9]+$" (js2-number-node-value node)))
6677 (js2-number-node-value node))
6678 ((js2-this-node-p node)
6679 "this")))
6680
6681 (defun js2-node-qname-component (node)
6682 "Return the name of this node, if it contributes to a qname.
6683 Returns nil if the node doesn't contribute."
6684 (copy-sequence
6685 (or (js2-prop-node-name node)
6686 (if (and (js2-function-node-p node)
6687 (js2-function-node-name node))
6688 (js2-name-node-name (js2-function-node-name node))))))
6689
6690 (defun js2-record-imenu-entry (fn-node qname pos)
6691 "Add an entry to `js2-imenu-recorder'.
6692 FN-NODE should be the current item's function node.
6693
6694 Associate FN-NODE with its QNAME for later lookup.
6695 This is used in postprocessing the chain list. For each chain, we find
6696 the parent function, look up its qname, then prepend a copy of it to the chain."
6697 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6698 (unless js2-imenu-function-map
6699 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6700 (puthash fn-node qname js2-imenu-function-map))
6701
6702 (defun js2-record-imenu-functions (node &optional var)
6703 "Record function definitions for imenu.
6704 NODE is a function node or an object literal.
6705 VAR, if non-nil, is the expression that NODE is being assigned to.
6706 When passed arguments of wrong type, does nothing."
6707 (when js2-parse-ide-mode
6708 (let ((fun-p (js2-function-node-p node))
6709 qname fname-node)
6710 (cond
6711 ;; non-anonymous function declaration?
6712 ((and fun-p
6713 (not var)
6714 (setq fname-node (js2-function-node-name node)))
6715 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6716 ;; for remaining forms, compute left-side tree branch first
6717 ((and var (setq qname (js2-compute-nested-prop-get var)))
6718 (cond
6719 ;; foo.bar.baz = function
6720 (fun-p
6721 (js2-record-imenu-entry node qname (js2-node-pos node)))
6722 ;; foo.bar.baz = object-literal
6723 ;; look for nested functions: {a: {b: function() {...} }}
6724 ((js2-object-node-p node)
6725 ;; Node position here is still absolute, since the parser
6726 ;; passes the assignment target and value expressions
6727 ;; to us before they are added as children of the assignment node.
6728 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6729
6730 (defun js2-compute-nested-prop-get (node)
6731 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6732 component nodes as a list. Otherwise return nil. Element-gets are treated
6733 as property-gets if the index expression is a string, or a positive integer."
6734 (let (left right head)
6735 (cond
6736 ((or (js2-name-node-p node)
6737 (js2-this-node-p node))
6738 (list node))
6739 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6740 ((js2-prop-get-node-p node) ; foo.bar
6741 (setq left (js2-prop-get-node-left node)
6742 right (js2-prop-get-node-right node))
6743 (if (setq head (js2-compute-nested-prop-get left))
6744 (nconc head (list right))))
6745 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6746 (setq left (js2-elem-get-node-target node)
6747 right (js2-elem-get-node-element node))
6748 (if (or (js2-string-node-p right) ; ['bar']
6749 (and (js2-number-node-p right) ; [10]
6750 (string-match "^[0-9]+$"
6751 (js2-number-node-value right))))
6752 (if (setq head (js2-compute-nested-prop-get left))
6753 (nconc head (list right))))))))
6754
6755 (defun js2-record-object-literal (node qname pos)
6756 "Recursively process an object literal looking for functions.
6757 NODE is an object literal that is the right-hand child of an assignment
6758 expression. QNAME is a list of nodes representing the assignment target,
6759 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6760 POS is the absolute position of the node.
6761 We do a depth-first traversal of NODE. For any functions we find,
6762 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6763 (let (right)
6764 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6765 (let ((left (js2-infix-node-left e))
6766 ;; Element positions are relative to the parent position.
6767 (pos (+ pos (js2-node-pos e))))
6768 (cond
6769 ;; foo: function() {...}
6770 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6771 (when (js2-prop-node-name left)
6772 ;; As a policy decision, we record the position of the property,
6773 ;; not the position of the `function' keyword, since the property
6774 ;; is effectively the name of the function.
6775 (js2-record-imenu-entry right (append qname (list left)) pos)))
6776 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6777 ((js2-object-node-p right)
6778 (js2-record-object-literal right
6779 (append qname (list (js2-infix-node-left e)))
6780 (+ pos (js2-node-pos right)))))))))
6781
6782 (defun js2-node-top-level-decl-p (node)
6783 "Return t if NODE's name is defined in the top-level scope.
6784 Also returns t if NODE's name is not defined in any scope, since it implies
6785 that it's an external variable, which must also be in the top-level scope."
6786 (let* ((name (js2-prop-node-name node))
6787 (this-scope (js2-node-get-enclosing-scope node))
6788 defining-scope)
6789 (cond
6790 ((js2-this-node-p node)
6791 nil)
6792 ((null this-scope)
6793 t)
6794 ((setq defining-scope (js2-get-defining-scope this-scope name))
6795 (js2-ast-root-p defining-scope))
6796 (t t))))
6797
6798 (defun js2-wrapper-function-p (node)
6799 "Return t if NODE is a function expression that's immediately invoked.
6800 NODE must be `js2-function-node'."
6801 (let ((parent (js2-node-parent node)))
6802 (or
6803 ;; function(){...}();
6804 (js2-call-node-p parent)
6805 (and (js2-paren-node-p parent)
6806 ;; (function(){...})();
6807 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6808 ;; (function(){...}).call(this);
6809 (and (js2-prop-get-node-p parent)
6810 (member (js2-name-node-name (js2-prop-get-node-right parent))
6811 '("call" "apply"))
6812 (js2-call-node-p (js2-node-parent parent))))))))
6813
6814 (defun js2-browse-postprocess-chains (entries)
6815 "Modify function-declaration name chains after parsing finishes.
6816 Some of the information is only available after the parse tree is complete.
6817 For instance, processing a nested scope requires a parent function node."
6818 (let (result fn parent-qname p elem)
6819 (dolist (entry entries)
6820 ;; function node goes first
6821 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6822 ;; Examine head's defining scope:
6823 ;; Pre-processed chain, or top-level/external, keep as-is.
6824 (if (or (stringp head) (js2-node-top-level-decl-p head))
6825 (push chain result)
6826 (when (js2-this-node-p head)
6827 (setq chain (cdr chain))) ; discard this-node
6828 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6829 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6830 (when (eq parent-qname 'not-found)
6831 ;; anonymous function expressions are not recorded
6832 ;; during the parse, so we need to handle this case here
6833 (setq parent-qname
6834 (if (js2-wrapper-function-p fn)
6835 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6836 (if (js2-ast-root-p grandparent)
6837 nil
6838 (gethash grandparent js2-imenu-function-map 'skip)))
6839 'skip))
6840 (puthash fn parent-qname js2-imenu-function-map))
6841 (unless (eq parent-qname 'skip)
6842 ;; prefix parent fn qname to this chain.
6843 (let ((qname (append parent-qname chain)))
6844 (puthash current-fn (butlast qname) js2-imenu-function-map)
6845 (push qname result)))))))
6846 ;; finally replace each node in each chain with its name.
6847 (dolist (chain result)
6848 (setq p chain)
6849 (while p
6850 (if (js2-node-p (setq elem (car p)))
6851 (setcar p (js2-node-qname-component elem)))
6852 (setq p (cdr p))))
6853 result))
6854
6855 ;; Merge name chains into a trie-like tree structure of nested lists.
6856 ;; To simplify construction of the trie, we first build it out using the rule
6857 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6858 ;; [key, num-or-list]. The second element can be a number; if so, this key
6859 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6860 ;; associated with the key at this level.) Otherwise the second element is
6861 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6862 ;; a simple recursive formulation.
6863 ;;
6864 ;; js2-mode is building the data structure for imenu. The imenu documentation
6865 ;; claims that it's the structure above, but in practice it wants the children
6866 ;; at the same list level as the key for that level, which is how I've drawn
6867 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6868 ;; list wrapper around the children at each level.
6869 ;;
6870 ;; A completed nested imenu-alist entry looks like this:
6871 ;; '(("foo"
6872 ;; ("<definition>" . 7)
6873 ;; ("bar"
6874 ;; ("a" . 40)
6875 ;; ("b" . 60))))
6876 ;;
6877 ;; In particular, the documentation for `imenu--index-alist' says that
6878 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6879 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6880
6881 (defun js2-treeify (lst)
6882 "Convert (a b c d) to (a ((b ((c d)))))."
6883 (if (null (cddr lst)) ; list length <= 2
6884 lst
6885 (list (car lst) (list (js2-treeify (cdr lst))))))
6886
6887 (defun js2-build-alist-trie (chains trie)
6888 "Merge declaration name chains into a trie-like alist structure for imenu.
6889 CHAINS is the qname chain list produced during parsing. TRIE is a
6890 list of elements built up so far."
6891 (let (head tail pos branch kids)
6892 (dolist (chain chains)
6893 (setq head (car chain)
6894 tail (cdr chain)
6895 pos (if (numberp (car tail)) (car tail))
6896 branch (js2-find-if (lambda (n)
6897 (string= (car n) head))
6898 trie)
6899 kids (second branch))
6900 (cond
6901 ;; case 1: this key isn't in the trie yet
6902 ((null branch)
6903 (if trie
6904 (setcdr (last trie) (list (js2-treeify chain)))
6905 (setq trie (list (js2-treeify chain)))))
6906 ;; case 2: key is present with a single number entry: replace w/ list
6907 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6908 ;; ("<definition>" 20)))
6909 ((numberp kids)
6910 (setcar (cdr branch)
6911 (list (list "<definition-1>" kids)
6912 (if pos
6913 (list "<definition-2>" pos)
6914 (js2-treeify tail)))))
6915 ;; case 3: key is there (with kids), and we're a number entry
6916 (pos
6917 (setcdr (last kids)
6918 (list
6919 (list (format "<definition-%d>"
6920 (1+ (loop for kid in kids
6921 count (eq ?< (aref (car kid) 0)))))
6922 pos))))
6923 ;; case 4: key is there with kids, need to merge in our chain
6924 (t
6925 (js2-build-alist-trie (list tail) kids))))
6926 trie))
6927
6928 (defun js2-flatten-trie (trie)
6929 "Convert TRIE to imenu-format.
6930 Recurses through nodes, and for each one whose second element is a list,
6931 appends the list's flattened elements to the current element. Also
6932 changes the tails into conses. For instance, this pre-flattened trie
6933
6934 '(a ((b 20)
6935 (c ((d 30)
6936 (e 40)))))
6937
6938 becomes
6939
6940 '(a (b . 20)
6941 (c (d . 30)
6942 (e . 40)))
6943
6944 Note that the root of the trie has no key, just a list of chains.
6945 This is also true for the value of any key with multiple children,
6946 e.g. key 'c' in the example above."
6947 (cond
6948 ((listp (car trie))
6949 (mapcar #'js2-flatten-trie trie))
6950 (t
6951 (if (numberp (second trie))
6952 (cons (car trie) (second trie))
6953 ;; else pop list and append its kids
6954 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6955
6956 (defun js2-build-imenu-index ()
6957 "Turn `js2-imenu-recorder' into an imenu data structure."
6958 (unless (eq js2-imenu-recorder 'empty)
6959 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
6960 (result (js2-build-alist-trie chains nil)))
6961 (js2-flatten-trie result))))
6962
6963 (defun js2-test-print-chains (chains)
6964 "Print a list of qname chains.
6965 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
6966 i.e. one or more nodes, and an integer position as the list tail."
6967 (mapconcat (lambda (chain)
6968 (concat "("
6969 (mapconcat (lambda (elem)
6970 (if (js2-node-p elem)
6971 (or (js2-node-qname-component elem)
6972 "nil")
6973 (number-to-string elem)))
6974 chain
6975 " ")
6976 ")"))
6977 chains
6978 "\n"))
6979
6980 ;;; Parser
6981
6982 (defconst js2-version "1.8.5"
6983 "Version of JavaScript supported.")
6984
6985 (defun js2-record-face (face &optional token)
6986 "Record a style run of FACE for TOKEN or the current token."
6987 (unless token (setq token (js2-current-token)))
6988 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
6989
6990 (defsubst js2-node-end (n)
6991 "Computes the absolute end of node N.
6992 Use with caution! Assumes `js2-node-pos' is -absolute-, which
6993 is only true until the node is added to its parent; i.e., while parsing."
6994 (+ (js2-node-pos n)
6995 (js2-node-len n)))
6996
6997 (defun js2-record-comment (token)
6998 "Record a comment in `js2-scanned-comments'."
6999 (let ((ct (js2-token-comment-type token))
7000 (beg (js2-token-beg token))
7001 (end (js2-token-end token)))
7002 (push (make-js2-comment-node :len (- end beg)
7003 :format ct)
7004 js2-scanned-comments)
7005 (when js2-parse-ide-mode
7006 (js2-record-face (if (eq ct 'jsdoc)
7007 'font-lock-doc-face
7008 'font-lock-comment-face)
7009 token)
7010 (when (memq ct '(html preprocessor))
7011 ;; Tell cc-engine the bounds of the comment.
7012 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7013
7014 (defun js2-peek-token ()
7015 "Return the next token type without consuming it.
7016 If `js2-ti-lookahead' is positive, return the type of next token
7017 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7018 (if (not (zerop js2-ti-lookahead))
7019 (js2-token-type
7020 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7021 (let ((tt (js2-get-token-internal)))
7022 (js2-unget-token)
7023 tt)))
7024
7025 (defalias 'js2-next-token 'js2-get-token)
7026
7027 (defun js2-match-token (match)
7028 "Get next token and return t if it matches MATCH, a bytecode.
7029 Returns nil and consumes nothing if MATCH is not the next token."
7030 (if (/= (js2-get-token) match)
7031 (ignore (js2-unget-token))
7032 t))
7033
7034 (defun js2-match-contextual-kwd (name)
7035 "Consume and return t if next token is `js2-NAME', and its
7036 string is NAME. Returns nil and keeps current token otherwise."
7037 (if (or (/= (js2-get-token) js2-NAME)
7038 (not (string= (js2-current-token-string) name)))
7039 (progn
7040 (js2-unget-token)
7041 nil)
7042 (js2-record-face 'font-lock-keyword-face)
7043 t))
7044
7045 (defun js2-valid-prop-name-token (tt)
7046 (or (= tt js2-NAME)
7047 (and js2-allow-keywords-as-property-names
7048 (plusp tt)
7049 (aref js2-kwd-tokens tt))))
7050
7051 (defun js2-match-prop-name ()
7052 "Consume token and return t if next token is a valid property name.
7053 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7054 is non-nil and it's a keyword token."
7055 (if (js2-valid-prop-name-token (js2-get-token))
7056 t
7057 (js2-unget-token)
7058 nil))
7059
7060 (defun js2-must-match-prop-name (msg-id &optional pos len)
7061 (if (js2-match-prop-name)
7062 t
7063 (js2-report-error msg-id nil pos len)
7064 nil))
7065
7066 (defun js2-peek-token-or-eol ()
7067 "Return js2-EOL if the next token immediately follows a newline.
7068 Else returns the next token. Used in situations where we don't
7069 consider certain token types valid if they are preceded by a newline.
7070 One example is the postfix ++ or -- operator, which has to be on the
7071 same line as its operand."
7072 (let ((tt (js2-get-token))
7073 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7074 (js2-unget-token)
7075 (if follows-eol
7076 js2-EOL
7077 tt)))
7078
7079 (defun js2-must-match (token msg-id &optional pos len)
7080 "Match next token to token code TOKEN, or record a syntax error.
7081 MSG-ID is the error message to report if the match fails.
7082 Returns t on match, nil if no match."
7083 (if (js2-match-token token)
7084 t
7085 (js2-report-error msg-id nil pos len)
7086 nil))
7087
7088 (defsubst js2-inside-function ()
7089 (plusp js2-nesting-of-function))
7090
7091 (defun js2-set-requires-activation ()
7092 (if (js2-function-node-p js2-current-script-or-fn)
7093 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7094
7095 (defun js2-check-activation-name (name _token)
7096 (when (js2-inside-function)
7097 ;; skip language-version 1.2 check from Rhino
7098 (if (or (string= "arguments" name)
7099 (and js2-compiler-activation-names ; only used in codegen
7100 (gethash name js2-compiler-activation-names)))
7101 (js2-set-requires-activation))))
7102
7103 (defun js2-set-is-generator ()
7104 (let ((fn-node js2-current-script-or-fn))
7105 (when (and (js2-function-node-p fn-node)
7106 (not (js2-function-node-generator-type fn-node)))
7107 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7108
7109 (defun js2-must-have-xml ()
7110 (unless js2-compiler-xml-available
7111 (js2-report-error "msg.XML.not.available")))
7112
7113 (defun js2-push-scope (scope)
7114 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7115 (assert (js2-scope-p scope))
7116 (assert (null (js2-scope-parent-scope scope)))
7117 (assert (not (eq js2-current-scope scope)))
7118 (setf (js2-scope-parent-scope scope) js2-current-scope
7119 js2-current-scope scope))
7120
7121 (defsubst js2-pop-scope ()
7122 (setq js2-current-scope
7123 (js2-scope-parent-scope js2-current-scope)))
7124
7125 (defun js2-enter-loop (loop-node)
7126 (push loop-node js2-loop-set)
7127 (push loop-node js2-loop-and-switch-set)
7128 (js2-push-scope loop-node)
7129 ;; Tell the current labeled statement (if any) its statement,
7130 ;; and set the jump target of the first label to the loop.
7131 ;; These are used in `js2-parse-continue' to verify that the
7132 ;; continue target is an actual labeled loop. (And for codegen.)
7133 (when js2-labeled-stmt
7134 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7135 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7136 js2-labeled-stmt))) loop-node)))
7137
7138 (defun js2-exit-loop ()
7139 (pop js2-loop-set)
7140 (pop js2-loop-and-switch-set)
7141 (js2-pop-scope))
7142
7143 (defsubst js2-enter-switch (switch-node)
7144 (push switch-node js2-loop-and-switch-set))
7145
7146 (defsubst js2-exit-switch ()
7147 (pop js2-loop-and-switch-set))
7148
7149 (defun js2-parse (&optional buf cb)
7150 "Tell the js2 parser to parse a region of JavaScript.
7151
7152 BUF is a buffer or buffer name containing the code to parse.
7153 Call `narrow-to-region' first to parse only part of the buffer.
7154
7155 The returned AST root node is given some additional properties:
7156 `node-count' - total number of nodes in the AST
7157 `buffer' - BUF. The buffer it refers to may change or be killed,
7158 so the value is not necessarily reliable.
7159
7160 An optional callback CB can be specified to report parsing
7161 progress. If `(functionp CB)' returns t, it will be called with
7162 the current line number once before parsing begins, then again
7163 each time the lexer reaches a new line number.
7164
7165 CB can also be a list of the form `(symbol cb ...)' to specify
7166 multiple callbacks with different criteria. Each symbol is a
7167 criterion keyword, and the following element is the callback to
7168 call
7169
7170 :line - called whenever the line number changes
7171 :token - called for each new token consumed
7172
7173 The list of criteria could be extended to include entering or
7174 leaving a statement, an expression, or a function definition."
7175 (if (and cb (not (functionp cb)))
7176 (error "criteria callbacks not yet implemented"))
7177 (let ((inhibit-point-motion-hooks t)
7178 (js2-compiler-xml-available (>= js2-language-version 160))
7179 ;; This is a recursive-descent parser, so give it a big stack.
7180 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7181 (max-specpdl-size (max max-specpdl-size 3000))
7182 (case-fold-search nil)
7183 ast)
7184 (with-current-buffer (or buf (current-buffer))
7185 (setq js2-scanned-comments nil
7186 js2-parsed-errors nil
7187 js2-parsed-warnings nil
7188 js2-imenu-recorder nil
7189 js2-imenu-function-map nil
7190 js2-label-set nil)
7191 (js2-init-scanner)
7192 (setq ast (with-silent-modifications
7193 (js2-do-parse)))
7194 (unless js2-ts-hit-eof
7195 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7196 (setf (js2-ast-root-errors ast) js2-parsed-errors
7197 (js2-ast-root-warnings ast) js2-parsed-warnings)
7198 ;; if we didn't find any declarations, put a dummy in this list so we
7199 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7200 (unless js2-imenu-recorder
7201 (setq js2-imenu-recorder 'empty))
7202 (run-hooks 'js2-parse-finished-hook)
7203 ast)))
7204
7205 ;; Corresponds to Rhino's Parser.parse() method.
7206 (defun js2-do-parse ()
7207 "Parse current buffer starting from current point.
7208 Scanner should be initialized."
7209 (let ((pos js2-ts-cursor)
7210 (end js2-ts-cursor) ; in case file is empty
7211 root n tt)
7212 ;; initialize buffer-local parsing vars
7213 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7214 js2-current-script-or-fn root
7215 js2-current-scope root
7216 js2-nesting-of-function 0
7217 js2-labeled-stmt nil
7218 js2-recorded-identifiers nil) ; for js2-highlight
7219 (while (/= (setq tt (js2-get-token)) js2-EOF)
7220 (if (= tt js2-FUNCTION)
7221 (progn
7222 (setq n (if js2-called-by-compile-function
7223 (js2-parse-function-expr)
7224 (js2-parse-function-stmt))))
7225 ;; not a function - parse a statement
7226 (js2-unget-token)
7227 (setq n (js2-parse-statement)))
7228 ;; add function or statement to script
7229 (setq end (js2-node-end n))
7230 (js2-block-node-push root n))
7231 ;; add comments to root in lexical order
7232 (when js2-scanned-comments
7233 ;; if we find a comment beyond end of normal kids, use its end
7234 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7235 (dolist (comment js2-scanned-comments)
7236 (push comment (js2-ast-root-comments root))
7237 (js2-node-add-children root comment)))
7238 (setf (js2-node-len root) (- end pos))
7239 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7240 ;; Give extensions a chance to muck with things before highlighting starts.
7241 (let ((js2-additional-externs js2-additional-externs))
7242 (save-excursion
7243 (run-hooks 'js2-post-parse-callbacks))
7244 (js2-highlight-undeclared-vars))
7245 root))
7246
7247 (defun js2-function-parser ()
7248 (js2-get-token)
7249 (js2-parse-function-stmt))
7250
7251 (defun js2-parse-function-closure-body (fn-node)
7252 "Parse a JavaScript 1.8 function closure body."
7253 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7254 (if js2-ts-hit-eof
7255 (js2-report-error "msg.no.brace.body" nil
7256 (js2-node-pos fn-node)
7257 (- js2-ts-cursor (js2-node-pos fn-node)))
7258 (js2-node-add-children fn-node
7259 (setf (js2-function-node-body fn-node)
7260 (js2-parse-expr t))))))
7261
7262 (defun js2-parse-function-body (fn-node)
7263 (js2-must-match js2-LC "msg.no.brace.body"
7264 (js2-node-pos fn-node)
7265 (- js2-ts-cursor (js2-node-pos fn-node)))
7266 (let ((pos (js2-current-token-beg)) ; LC position
7267 (pn (make-js2-block-node)) ; starts at LC position
7268 tt
7269 end)
7270 (incf js2-nesting-of-function)
7271 (unwind-protect
7272 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7273 (= tt js2-EOF)
7274 (= tt js2-RC)))
7275 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7276 (js2-parse-statement)
7277 (js2-get-token)
7278 (js2-parse-function-stmt))))
7279 (decf js2-nesting-of-function))
7280 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7281 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7282 (setq end (js2-current-token-end)))
7283 (setf (js2-node-pos pn) pos
7284 (js2-node-len pn) (- end pos))
7285 (setf (js2-function-node-body fn-node) pn)
7286 (js2-node-add-children fn-node pn)
7287 pn))
7288
7289 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7290 "Declare and fontify destructuring parameters inside NODE.
7291 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7292 (cond
7293 ((js2-name-node-p node)
7294 (let (leftpos)
7295 (js2-define-symbol decl-type (js2-name-node-name node)
7296 node ignore-not-in-block)
7297 (when face
7298 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7299 (+ leftpos (js2-node-len node))
7300 face 'record))))
7301 ((js2-object-node-p node)
7302 (dolist (elem (js2-object-node-elems node))
7303 (js2-define-destruct-symbols
7304 (if (js2-object-prop-node-p elem)
7305 (js2-object-prop-node-right elem)
7306 ;; abbreviated destructuring {a, b}
7307 elem)
7308 decl-type face ignore-not-in-block)))
7309 ((js2-array-node-p node)
7310 (dolist (elem (js2-array-node-elems node))
7311 (when elem
7312 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7313 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7314 (js2-node-len node)))))
7315
7316 (defun js2-parse-function-params (function-type fn-node pos)
7317 (if (js2-match-token js2-RP)
7318 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7319 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7320 (eq (js2-current-token-type) js2-NAME)))
7321 params param default-found rest-param-at)
7322 (when paren-free-arrow
7323 (js2-unget-token))
7324 (loop for tt = (js2-peek-token)
7325 do
7326 (cond
7327 ;; destructuring param
7328 ((and (not paren-free-arrow)
7329 (or (= tt js2-LB) (= tt js2-LC)))
7330 (js2-get-token)
7331 (when default-found
7332 (js2-report-error "msg.no.default.after.default.param"))
7333 (setq param (js2-parse-destruct-primary-expr))
7334 (js2-define-destruct-symbols param
7335 js2-LP
7336 'js2-function-param)
7337 (push param params))
7338 ;; variable name
7339 (t
7340 (when (and (>= js2-language-version 200)
7341 (not paren-free-arrow)
7342 (js2-match-token js2-TRIPLEDOT)
7343 (not rest-param-at))
7344 ;; to report errors if there are more parameters
7345 (setq rest-param-at (length params)))
7346 (js2-must-match js2-NAME "msg.no.parm")
7347 (js2-record-face 'js2-function-param)
7348 (setq param (js2-create-name-node))
7349 (js2-define-symbol js2-LP (js2-current-token-string) param)
7350 ;; default parameter value
7351 (when (or (and default-found
7352 (not rest-param-at)
7353 (js2-must-match js2-ASSIGN
7354 "msg.no.default.after.default.param"
7355 (js2-node-pos param)
7356 (js2-node-len param)))
7357 (and (>= js2-language-version 200)
7358 (js2-match-token js2-ASSIGN)))
7359 (assert (not paren-free-arrow))
7360 (let* ((pos (js2-node-pos param))
7361 (tt (js2-current-token-type))
7362 (op-pos (- (js2-current-token-beg) pos))
7363 (left param)
7364 (right (js2-parse-assign-expr))
7365 (len (- (js2-node-end right) pos)))
7366 (setq param (make-js2-assign-node
7367 :type tt :pos pos :len len :op-pos op-pos
7368 :left left :right right)
7369 default-found t)
7370 (js2-node-add-children param left right)))
7371 (push param params)))
7372 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7373 (js2-report-error "msg.param.after.rest" nil
7374 (js2-node-pos param) (js2-node-len param)))
7375 while
7376 (js2-match-token js2-COMMA))
7377 (when (and (not paren-free-arrow)
7378 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7379 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7380 (when rest-param-at
7381 (setf (js2-function-node-rest-p fn-node) t))
7382 (dolist (p params)
7383 (js2-node-add-children fn-node p)
7384 (push p (js2-function-node-params fn-node))))))
7385
7386 (defun js2-check-inconsistent-return-warning (fn-node name)
7387 "Possibly show inconsistent-return warning.
7388 Last token scanned is the close-curly for the function body."
7389 (when (and js2-mode-show-strict-warnings
7390 js2-strict-inconsistent-return-warning
7391 (not (js2-has-consistent-return-usage
7392 (js2-function-node-body fn-node))))
7393 ;; Have it extend from close-curly to bol or beginning of block.
7394 (let ((pos (save-excursion
7395 (goto-char (js2-current-token-end))
7396 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7397 (point-at-bol))))
7398 (end (js2-current-token-end)))
7399 (if (plusp (js2-name-node-length name))
7400 (js2-add-strict-warning "msg.no.return.value"
7401 (js2-name-node-name name) pos end)
7402 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7403
7404 (defun js2-parse-function-stmt ()
7405 (let ((pos (js2-current-token-beg))
7406 (star-p (js2-match-token js2-MUL)))
7407 (js2-must-match js2-NAME "msg.unnamed.function.stmt")
7408 (let ((name (js2-create-name-node t))
7409 pn member-expr)
7410 (cond
7411 ((js2-match-token js2-LP)
7412 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7413 (js2-allow-member-expr-as-function-name
7414 (setq member-expr (js2-parse-member-expr-tail nil name))
7415 (js2-parse-highlight-member-expr-fn-name member-expr)
7416 (js2-must-match js2-LP "msg.no.paren.parms")
7417 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7418 (js2-function-node-member-expr pn) member-expr)
7419 pn)
7420 (t
7421 (js2-report-error "msg.no.paren.parms")
7422 (make-js2-error-node))))))
7423
7424 (defun js2-parse-function-expr ()
7425 (let ((pos (js2-current-token-beg))
7426 (star-p (js2-match-token js2-MUL))
7427 name)
7428 (when (js2-match-token js2-NAME)
7429 (setq name (js2-create-name-node t)))
7430 (js2-must-match js2-LP "msg.no.paren.parms")
7431 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7432
7433 (defun js2-parse-function (function-type pos star-p &optional name)
7434 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7435 beginning of the first token (function keyword, unless it's an
7436 arrow function), NAME is js2-name-node."
7437 (let (fn-node lp)
7438 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7439 (setq lp (js2-current-token-beg)))
7440 (setf fn-node (make-js2-function-node :pos pos
7441 :name name
7442 :form function-type
7443 :lp (if lp (- lp pos))
7444 :generator-type (and star-p 'STAR)))
7445 (when name
7446 (js2-set-face (js2-node-pos name) (js2-node-end name)
7447 'font-lock-function-name-face 'record)
7448 (when (plusp (js2-name-node-length name))
7449 ;; Function statements define a symbol in the enclosing scope
7450 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7451 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7452 ;; 1. Nested functions are not affected by the dynamic scope flag
7453 ;; as dynamic scope is already a parent of their scope.
7454 ;; 2. Functions defined under the with statement also immune to
7455 ;; this setup, in which case dynamic scope is ignored in favor
7456 ;; of the with object.
7457 (setf (js2-function-node-ignore-dynamic fn-node) t))
7458 ;; dynamically bind all the per-function variables
7459 (let ((js2-current-script-or-fn fn-node)
7460 (js2-current-scope fn-node)
7461 (js2-nesting-of-with 0)
7462 (js2-end-flags 0)
7463 js2-label-set
7464 js2-loop-set
7465 js2-loop-and-switch-set)
7466 (js2-parse-function-params function-type fn-node pos)
7467 (when (eq function-type 'FUNCTION_ARROW)
7468 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7469 (if (and (>= js2-language-version 180)
7470 (/= (js2-peek-token) js2-LC))
7471 (js2-parse-function-closure-body fn-node)
7472 (js2-parse-function-body fn-node))
7473 (js2-check-inconsistent-return-warning fn-node name)
7474
7475 (when name
7476 (js2-node-add-children fn-node name)
7477 ;; Function expressions define a name only in the body of the
7478 ;; function, and only if not hidden by a parameter name
7479 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7480 (null (js2-scope-get-symbol js2-current-scope
7481 (js2-name-node-name name))))
7482 (js2-define-symbol js2-FUNCTION
7483 (js2-name-node-name name)
7484 fn-node))
7485 (when (eq function-type 'FUNCTION_STATEMENT)
7486 (js2-record-imenu-functions fn-node))))
7487
7488 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7489 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7490 ;; We wait until after parsing the function to set its parent scope,
7491 ;; since `js2-define-symbol' needs the defining-scope check to stop
7492 ;; at the function boundary when checking for redeclarations.
7493 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7494 fn-node))
7495
7496 (defun js2-parse-statements (&optional parent)
7497 "Parse a statement list. Last token consumed must be js2-LC.
7498
7499 PARENT can be a `js2-block-node', in which case the statements are
7500 appended to PARENT. Otherwise a new `js2-block-node' is created
7501 and returned.
7502
7503 This function does not match the closing js2-RC: the caller
7504 matches the RC so it can provide a suitable error message if not
7505 matched. This means it's up to the caller to set the length of
7506 the node to include the closing RC. The node start pos is set to
7507 the absolute buffer start position, and the caller should fix it
7508 up to be relative to the parent node. All children of this block
7509 node are given relative start positions and correct lengths."
7510 (let ((pn (or parent (make-js2-block-node)))
7511 tt)
7512 (setf (js2-node-pos pn) (js2-current-token-beg))
7513 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7514 (/= tt js2-RC))
7515 (js2-block-node-push pn (js2-parse-statement)))
7516 pn))
7517
7518 (defun js2-parse-statement ()
7519 (let (pn beg end)
7520 ;; coarse-grained user-interrupt check - needs work
7521 (and js2-parse-interruptable-p
7522 (zerop (% (incf js2-parse-stmt-count)
7523 js2-statements-per-pause))
7524 (input-pending-p)
7525 (throw 'interrupted t))
7526 (setq pn (js2-statement-helper))
7527 ;; no-side-effects warning check
7528 (unless (js2-node-has-side-effects pn)
7529 (setq end (js2-node-end pn))
7530 (save-excursion
7531 (goto-char end)
7532 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7533 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7534 pn))
7535
7536 ;; These correspond to the switch cases in Parser.statementHelper
7537 (defconst js2-parsers
7538 (let ((parsers (make-vector js2-num-tokens
7539 #'js2-parse-expr-stmt)))
7540 (aset parsers js2-BREAK #'js2-parse-break)
7541 (aset parsers js2-CONST #'js2-parse-const-var)
7542 (aset parsers js2-CONTINUE #'js2-parse-continue)
7543 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7544 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7545 (aset parsers js2-DO #'js2-parse-do)
7546 (aset parsers js2-FOR #'js2-parse-for)
7547 (aset parsers js2-FUNCTION #'js2-function-parser)
7548 (aset parsers js2-IF #'js2-parse-if)
7549 (aset parsers js2-LC #'js2-parse-block)
7550 (aset parsers js2-LET #'js2-parse-let-stmt)
7551 (aset parsers js2-NAME #'js2-parse-name-or-label)
7552 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7553 (aset parsers js2-SEMI #'js2-parse-semi)
7554 (aset parsers js2-SWITCH #'js2-parse-switch)
7555 (aset parsers js2-THROW #'js2-parse-throw)
7556 (aset parsers js2-TRY #'js2-parse-try)
7557 (aset parsers js2-VAR #'js2-parse-const-var)
7558 (aset parsers js2-WHILE #'js2-parse-while)
7559 (aset parsers js2-WITH #'js2-parse-with)
7560 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7561 parsers)
7562 "A vector mapping token types to parser functions.")
7563
7564 (defun js2-parse-warn-missing-semi (beg end)
7565 (and js2-mode-show-strict-warnings
7566 js2-strict-missing-semi-warning
7567 (js2-add-strict-warning
7568 "msg.missing.semi" nil
7569 ;; back up to beginning of statement or line
7570 (max beg (save-excursion
7571 (goto-char end)
7572 (point-at-bol)))
7573 end)))
7574
7575 (defconst js2-no-semi-insertion
7576 (list js2-IF
7577 js2-SWITCH
7578 js2-WHILE
7579 js2-DO
7580 js2-FOR
7581 js2-TRY
7582 js2-WITH
7583 js2-LC
7584 js2-ERROR
7585 js2-SEMI
7586 js2-FUNCTION)
7587 "List of tokens that don't do automatic semicolon insertion.")
7588
7589 (defconst js2-autoinsert-semi-and-warn
7590 (list js2-ERROR js2-EOF js2-RC))
7591
7592 (defun js2-statement-helper ()
7593 (let* ((tt (js2-get-token))
7594 (first-tt tt)
7595 (parser (if (= tt js2-ERROR)
7596 #'js2-parse-semi
7597 (aref js2-parsers tt)))
7598 pn)
7599 ;; If the statement is set, then it's been told its label by now.
7600 (and js2-labeled-stmt
7601 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7602 (setq js2-labeled-stmt nil))
7603 (setq pn (funcall parser))
7604 ;; Don't do auto semi insertion for certain statement types.
7605 (unless (or (memq first-tt js2-no-semi-insertion)
7606 (js2-labeled-stmt-node-p pn))
7607 (js2-auto-insert-semicolon pn))
7608 pn))
7609
7610 (defun js2-auto-insert-semicolon (pn)
7611 (let* ((tt (js2-get-token))
7612 (pos (js2-node-pos pn)))
7613 (cond
7614 ((= tt js2-SEMI)
7615 ;; extend the node bounds to include the semicolon.
7616 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
7617 ((memq tt js2-autoinsert-semi-and-warn)
7618 (js2-unget-token) ; Not ';', do not consume.
7619 ;; Autoinsert ;
7620 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7621 (t
7622 (if (not (js2-token-follows-eol-p (js2-current-token)))
7623 ;; Report error if no EOL or autoinsert ';' otherwise
7624 (js2-report-error "msg.no.semi.stmt")
7625 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7626 (js2-unget-token) ; Not ';', do not consume.
7627 ))))
7628
7629 (defun js2-parse-condition ()
7630 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7631 The parens are discarded and the expression node is returned.
7632 The `pos' field of the return value is set to an absolute position
7633 that must be fixed up by the caller.
7634 Return value is a list (EXPR LP RP), with absolute paren positions."
7635 (let (pn lp rp)
7636 (if (js2-must-match js2-LP "msg.no.paren.cond")
7637 (setq lp (js2-current-token-beg)))
7638 (setq pn (js2-parse-expr))
7639 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7640 (setq rp (js2-current-token-beg)))
7641 ;; Report strict warning on code like "if (a = 7) ..."
7642 (if (and js2-strict-cond-assign-warning
7643 (js2-assign-node-p pn))
7644 (js2-add-strict-warning "msg.equal.as.assign" nil
7645 (js2-node-pos pn)
7646 (+ (js2-node-pos pn)
7647 (js2-node-len pn))))
7648 (list pn lp rp)))
7649
7650 (defun js2-parse-if ()
7651 "Parser for if-statement. Last matched token must be js2-IF."
7652 (let ((pos (js2-current-token-beg))
7653 cond if-true if-false else-pos end pn)
7654 (setq cond (js2-parse-condition)
7655 if-true (js2-parse-statement)
7656 if-false (if (js2-match-token js2-ELSE)
7657 (progn
7658 (setq else-pos (- (js2-current-token-beg) pos))
7659 (js2-parse-statement)))
7660 end (js2-node-end (or if-false if-true))
7661 pn (make-js2-if-node :pos pos
7662 :len (- end pos)
7663 :condition (car cond)
7664 :then-part if-true
7665 :else-part if-false
7666 :else-pos else-pos
7667 :lp (js2-relpos (second cond) pos)
7668 :rp (js2-relpos (third cond) pos)))
7669 (js2-node-add-children pn (car cond) if-true if-false)
7670 pn))
7671
7672 (defun js2-parse-switch ()
7673 "Parser for switch-statement. Last matched token must be js2-SWITCH."
7674 (let ((pos (js2-current-token-beg))
7675 tt pn discriminant has-default case-expr case-node
7676 case-pos cases stmt lp)
7677 (if (js2-must-match js2-LP "msg.no.paren.switch")
7678 (setq lp (js2-current-token-beg)))
7679 (setq discriminant (js2-parse-expr)
7680 pn (make-js2-switch-node :discriminant discriminant
7681 :pos pos
7682 :lp (js2-relpos lp pos)))
7683 (js2-node-add-children pn discriminant)
7684 (js2-enter-switch pn)
7685 (unwind-protect
7686 (progn
7687 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7688 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
7689 (js2-must-match js2-LC "msg.no.brace.switch")
7690 (catch 'break
7691 (while t
7692 (setq tt (js2-next-token)
7693 case-pos (js2-current-token-beg))
7694 (cond
7695 ((= tt js2-RC)
7696 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
7697 (throw 'break nil)) ; done
7698 ((= tt js2-CASE)
7699 (setq case-expr (js2-parse-expr))
7700 (js2-must-match js2-COLON "msg.no.colon.case"))
7701 ((= tt js2-DEFAULT)
7702 (if has-default
7703 (js2-report-error "msg.double.switch.default"))
7704 (setq has-default t
7705 case-expr nil)
7706 (js2-must-match js2-COLON "msg.no.colon.case"))
7707 (t
7708 (js2-report-error "msg.bad.switch")
7709 (throw 'break nil)))
7710 (setq case-node (make-js2-case-node :pos case-pos
7711 :len (- (js2-current-token-end) case-pos)
7712 :expr case-expr))
7713 (js2-node-add-children case-node case-expr)
7714 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7715 (/= tt js2-CASE)
7716 (/= tt js2-DEFAULT)
7717 (/= tt js2-EOF))
7718 (setf stmt (js2-parse-statement)
7719 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7720 (js2-block-node-push case-node stmt))
7721 (push case-node cases)))
7722 ;; add cases last, as pushing reverses the order to be correct
7723 (dolist (kid cases)
7724 (js2-node-add-children pn kid)
7725 (push kid (js2-switch-node-cases pn)))
7726 pn) ; return value
7727 (js2-exit-switch))))
7728
7729 (defun js2-parse-while ()
7730 "Parser for while-statement. Last matched token must be js2-WHILE."
7731 (let ((pos (js2-current-token-beg))
7732 (pn (make-js2-while-node))
7733 cond body)
7734 (js2-enter-loop pn)
7735 (unwind-protect
7736 (progn
7737 (setf cond (js2-parse-condition)
7738 (js2-while-node-condition pn) (car cond)
7739 body (js2-parse-statement)
7740 (js2-while-node-body pn) body
7741 (js2-node-len pn) (- (js2-node-end body) pos)
7742 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7743 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7744 (js2-node-add-children pn body (car cond)))
7745 (js2-exit-loop))
7746 pn))
7747
7748 (defun js2-parse-do ()
7749 "Parser for do-statement. Last matched token must be js2-DO."
7750 (let ((pos (js2-current-token-beg))
7751 (pn (make-js2-do-node))
7752 cond body end)
7753 (js2-enter-loop pn)
7754 (unwind-protect
7755 (progn
7756 (setq body (js2-parse-statement))
7757 (js2-must-match js2-WHILE "msg.no.while.do")
7758 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
7759 cond (js2-parse-condition)
7760 (js2-do-node-condition pn) (car cond)
7761 (js2-do-node-body pn) body
7762 end js2-ts-cursor
7763 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7764 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7765 (js2-node-add-children pn (car cond) body))
7766 (js2-exit-loop))
7767 ;; Always auto-insert semicolon to follow SpiderMonkey:
7768 ;; It is required by ECMAScript but is ignored by the rest of
7769 ;; world; see bug 238945
7770 (if (js2-match-token js2-SEMI)
7771 (setq end js2-ts-cursor))
7772 (setf (js2-node-len pn) (- end pos))
7773 pn))
7774
7775 (defun js2-parse-for ()
7776 "Parser for for-statement. Last matched token must be js2-FOR.
7777 Parses for, for-in, and for each-in statements."
7778 (let ((for-pos (js2-current-token-beg))
7779 pn is-for-each is-for-in-or-of is-for-of
7780 in-pos each-pos tmp-pos
7781 init ; Node init is also foo in 'foo in object'
7782 cond ; Node cond is also object in 'foo in object'
7783 incr ; 3rd section of for-loop initializer
7784 body tt lp rp)
7785 ;; See if this is a for each () instead of just a for ()
7786 (when (js2-match-token js2-NAME)
7787 (if (string= "each" (js2-current-token-string))
7788 (progn
7789 (setq is-for-each t
7790 each-pos (- (js2-current-token-beg) for-pos)) ; relative
7791 (js2-record-face 'font-lock-keyword-face))
7792 (js2-report-error "msg.no.paren.for")))
7793 (if (js2-must-match js2-LP "msg.no.paren.for")
7794 (setq lp (- (js2-current-token-beg) for-pos)))
7795 (setq tt (js2-get-token))
7796 ;; 'for' makes local scope
7797 (js2-push-scope (make-js2-scope))
7798 (unwind-protect
7799 ;; parse init clause
7800 (let ((js2-in-for-init t)) ; set as dynamic variable
7801 (cond
7802 ((= tt js2-SEMI)
7803 (js2-unget-token)
7804 (setq init (make-js2-empty-expr-node)))
7805 ((or (= tt js2-VAR) (= tt js2-LET))
7806 (setq init (js2-parse-variables tt (js2-current-token-beg))))
7807 (t
7808 (js2-unget-token)
7809 (setq init (js2-parse-expr)))))
7810 (if (or (js2-match-token js2-IN)
7811 (and (>= js2-language-version 200)
7812 (js2-match-contextual-kwd "of")
7813 (setq is-for-of t)))
7814 (setq is-for-in-or-of t
7815 in-pos (- (js2-current-token-beg) for-pos)
7816 ;; scope of iteration target object is not the scope we've created above.
7817 ;; stash current scope temporary.
7818 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7819 (js2-parse-expr))) ; object over which we're iterating
7820 ;; else ordinary for loop - parse cond and incr
7821 (js2-must-match js2-SEMI "msg.no.semi.for")
7822 (setq cond (if (= (js2-peek-token) js2-SEMI)
7823 (make-js2-empty-expr-node) ; no loop condition
7824 (js2-parse-expr)))
7825 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7826 (setq tmp-pos (js2-current-token-end)
7827 incr (if (= (js2-peek-token) js2-RP)
7828 (make-js2-empty-expr-node :pos tmp-pos)
7829 (js2-parse-expr))))
7830 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7831 (setq rp (- (js2-current-token-beg) for-pos)))
7832 (if (not is-for-in-or-of)
7833 (setq pn (make-js2-for-node :init init
7834 :condition cond
7835 :update incr
7836 :lp lp
7837 :rp rp))
7838 ;; cond could be null if 'in obj' got eaten by the init node.
7839 (if (js2-infix-node-p init)
7840 ;; it was (foo in bar) instead of (var foo in bar)
7841 (setq cond (js2-infix-node-right init)
7842 init (js2-infix-node-left init))
7843 (if (and (js2-var-decl-node-p init)
7844 (> (length (js2-var-decl-node-kids init)) 1))
7845 (js2-report-error "msg.mult.index")))
7846 (setq pn (make-js2-for-in-node :iterator init
7847 :object cond
7848 :in-pos in-pos
7849 :foreach-p is-for-each
7850 :each-pos each-pos
7851 :forof-p is-for-of
7852 :lp lp
7853 :rp rp)))
7854 (unwind-protect
7855 (progn
7856 (js2-enter-loop pn)
7857 ;; We have to parse the body -after- creating the loop node,
7858 ;; so that the loop node appears in the js2-loop-set, allowing
7859 ;; break/continue statements to find the enclosing loop.
7860 (setf body (js2-parse-statement)
7861 (js2-loop-node-body pn) body
7862 (js2-node-pos pn) for-pos
7863 (js2-node-len pn) (- (js2-node-end body) for-pos))
7864 (js2-node-add-children pn init cond incr body))
7865 ;; finally
7866 (js2-exit-loop))
7867 (js2-pop-scope))
7868 pn))
7869
7870 (defun js2-parse-try ()
7871 "Parser for try-statement. Last matched token must be js2-TRY."
7872 (let ((try-pos (js2-current-token-beg))
7873 try-end
7874 try-block
7875 catch-blocks
7876 finally-block
7877 saw-default-catch
7878 peek
7879 param
7880 catch-cond
7881 catch-node
7882 guard-kwd
7883 catch-pos
7884 finally-pos
7885 pn
7886 block
7887 lp
7888 rp)
7889 (if (/= (js2-peek-token) js2-LC)
7890 (js2-report-error "msg.no.brace.try"))
7891 (setq try-block (js2-parse-statement)
7892 try-end (js2-node-end try-block)
7893 peek (js2-peek-token))
7894 (cond
7895 ((= peek js2-CATCH)
7896 (while (js2-match-token js2-CATCH)
7897 (setq catch-pos (js2-current-token-beg)
7898 guard-kwd nil
7899 catch-cond nil
7900 lp nil
7901 rp nil)
7902 (if saw-default-catch
7903 (js2-report-error "msg.catch.unreachable"))
7904 (if (js2-must-match js2-LP "msg.no.paren.catch")
7905 (setq lp (- (js2-current-token-beg) catch-pos)))
7906 (js2-push-scope (make-js2-scope))
7907 (let ((tt (js2-peek-token)))
7908 (cond
7909 ;; destructuring pattern
7910 ;; catch ({ message, file }) { ... }
7911 ((or (= tt js2-LB) (= tt js2-LC))
7912 (js2-get-token)
7913 (setq param (js2-parse-destruct-primary-expr))
7914 (js2-define-destruct-symbols param js2-LET nil))
7915 ;; simple name
7916 (t
7917 (js2-must-match js2-NAME "msg.bad.catchcond")
7918 (setq param (js2-create-name-node))
7919 (js2-define-symbol js2-LET (js2-current-token-string) param))))
7920 ;; pattern guard
7921 (if (js2-match-token js2-IF)
7922 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
7923 catch-cond (js2-parse-expr))
7924 (setq saw-default-catch t))
7925 (if (js2-must-match js2-RP "msg.bad.catchcond")
7926 (setq rp (- (js2-current-token-beg) catch-pos)))
7927 (js2-must-match js2-LC "msg.no.brace.catchblock")
7928 (setq block (js2-parse-statements)
7929 try-end (js2-node-end block)
7930 catch-node (make-js2-catch-node :pos catch-pos
7931 :param param
7932 :guard-expr catch-cond
7933 :guard-kwd guard-kwd
7934 :block block
7935 :lp lp
7936 :rp rp))
7937 (js2-pop-scope)
7938 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7939 (setq try-end (js2-current-token-beg)))
7940 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7941 (js2-node-len catch-node) (- try-end catch-pos))
7942 (js2-node-add-children catch-node param catch-cond block)
7943 (push catch-node catch-blocks)))
7944 ((/= peek js2-FINALLY)
7945 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7946 (js2-node-pos try-block)
7947 (- (setq try-end (js2-node-end try-block))
7948 (js2-node-pos try-block)))))
7949 (when (js2-match-token js2-FINALLY)
7950 (setq finally-pos (js2-current-token-beg)
7951 block (js2-parse-statement)
7952 try-end (js2-node-end block)
7953 finally-block (make-js2-finally-node :pos finally-pos
7954 :len (- try-end finally-pos)
7955 :body block))
7956 (js2-node-add-children finally-block block))
7957 (setq pn (make-js2-try-node :pos try-pos
7958 :len (- try-end try-pos)
7959 :try-block try-block
7960 :finally-block finally-block))
7961 (js2-node-add-children pn try-block finally-block)
7962 ;; push them onto the try-node, which reverses and corrects their order
7963 (dolist (cb catch-blocks)
7964 (js2-node-add-children pn cb)
7965 (push cb (js2-try-node-catch-clauses pn)))
7966 pn))
7967
7968 (defun js2-parse-throw ()
7969 "Parser for throw-statement. Last matched token must be js2-THROW."
7970 (let ((pos (js2-current-token-beg))
7971 expr pn)
7972 (if (= (js2-peek-token-or-eol) js2-EOL)
7973 ;; ECMAScript does not allow new lines before throw expression,
7974 ;; see bug 256617
7975 (js2-report-error "msg.bad.throw.eol"))
7976 (setq expr (js2-parse-expr)
7977 pn (make-js2-throw-node :pos pos
7978 :len (- (js2-node-end expr) pos)
7979 :expr expr))
7980 (js2-node-add-children pn expr)
7981 pn))
7982
7983 (defun js2-match-jump-label-name (label-name)
7984 "If break/continue specified a label, return that label's labeled stmt.
7985 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
7986 does not match an existing label, reports an error and returns nil."
7987 (let ((bundle (cdr (assoc label-name js2-label-set))))
7988 (if (null bundle)
7989 (js2-report-error "msg.undef.label"))
7990 bundle))
7991
7992 (defun js2-parse-break ()
7993 "Parser for break-statement. Last matched token must be js2-BREAK."
7994 (let ((pos (js2-current-token-beg))
7995 (end (js2-current-token-end))
7996 break-target ; statement to break from
7997 break-label ; in "break foo", name-node representing the foo
7998 labels ; matching labeled statement to break to
7999 pn)
8000 (when (eq (js2-peek-token-or-eol) js2-NAME)
8001 (js2-get-token)
8002 (setq break-label (js2-create-name-node)
8003 end (js2-node-end break-label)
8004 ;; matchJumpLabelName only matches if there is one
8005 labels (js2-match-jump-label-name (js2-current-token-string))
8006 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8007 (unless (or break-target break-label)
8008 ;; no break target specified - try for innermost enclosing loop/switch
8009 (if (null js2-loop-and-switch-set)
8010 (unless break-label
8011 (js2-report-error "msg.bad.break" nil pos (length "break")))
8012 (setq break-target (car js2-loop-and-switch-set))))
8013 (setq pn (make-js2-break-node :pos pos
8014 :len (- end pos)
8015 :label break-label
8016 :target break-target))
8017 (js2-node-add-children pn break-label) ; but not break-target
8018 pn))
8019
8020 (defun js2-parse-continue ()
8021 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8022 (let ((pos (js2-current-token-beg))
8023 (end (js2-current-token-end))
8024 label ; optional user-specified label, a `js2-name-node'
8025 labels ; current matching labeled stmt, if any
8026 target ; the `js2-loop-node' target of this continue stmt
8027 pn)
8028 (when (= (js2-peek-token-or-eol) js2-NAME)
8029 (js2-get-token)
8030 (setq label (js2-create-name-node)
8031 end (js2-node-end label)
8032 ;; matchJumpLabelName only matches if there is one
8033 labels (js2-match-jump-label-name (js2-current-token-string))))
8034 (cond
8035 ((null labels) ; no current label to go to
8036 (if (null js2-loop-set) ; no loop to continue to
8037 (js2-report-error "msg.continue.outside" nil pos
8038 (length "continue"))
8039 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8040 (t
8041 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8042 (setq target (js2-labeled-stmt-node-stmt labels))
8043 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8044 (setq pn (make-js2-continue-node :pos pos
8045 :len (- end pos)
8046 :label label
8047 :target target))
8048 (js2-node-add-children pn label) ; but not target - it's not our child
8049 pn))
8050
8051 (defun js2-parse-with ()
8052 "Parser for with-statement. Last matched token must be js2-WITH."
8053 (let ((pos (js2-current-token-beg))
8054 obj body pn lp rp)
8055 (if (js2-must-match js2-LP "msg.no.paren.with")
8056 (setq lp (js2-current-token-beg)))
8057 (setq obj (js2-parse-expr))
8058 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8059 (setq rp (js2-current-token-beg)))
8060 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8061 (setq body (js2-parse-statement)))
8062 (setq pn (make-js2-with-node :pos pos
8063 :len (- (js2-node-end body) pos)
8064 :object obj
8065 :body body
8066 :lp (js2-relpos lp pos)
8067 :rp (js2-relpos rp pos)))
8068 (js2-node-add-children pn obj body)
8069 pn))
8070
8071 (defun js2-parse-const-var ()
8072 "Parser for var- or const-statement.
8073 Last matched token must be js2-CONST or js2-VAR."
8074 (let ((tt (js2-current-token-type))
8075 (pos (js2-current-token-beg))
8076 expr pn)
8077 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8078 pn (make-js2-expr-stmt-node :pos pos
8079 :len (- (js2-node-end expr) pos)
8080 :expr expr))
8081 (js2-node-add-children pn expr)
8082 pn))
8083
8084 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8085 (let ((pn (make-js2-expr-stmt-node :pos pos
8086 :len (js2-node-len expr)
8087 :type (if (js2-inside-function)
8088 js2-EXPR_VOID
8089 js2-EXPR_RESULT)
8090 :expr expr)))
8091 (if add-child
8092 (js2-node-add-children pn expr))
8093 pn))
8094
8095 (defun js2-parse-let-stmt ()
8096 "Parser for let-statement. Last matched token must be js2-LET."
8097 (let ((pos (js2-current-token-beg))
8098 expr pn)
8099 (if (= (js2-peek-token) js2-LP)
8100 ;; let expression in statement context
8101 (setq expr (js2-parse-let pos 'statement)
8102 pn (js2-wrap-with-expr-stmt pos expr t))
8103 ;; else we're looking at a statement like let x=6, y=7;
8104 (setf expr (js2-parse-variables js2-LET pos)
8105 pn (js2-wrap-with-expr-stmt pos expr t)
8106 (js2-node-type pn) js2-EXPR_RESULT))
8107 pn))
8108
8109 (defun js2-parse-ret-yield ()
8110 (js2-parse-return-or-yield (js2-current-token-type) nil))
8111
8112 (defconst js2-parse-return-stmt-enders
8113 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8114
8115 (defsubst js2-now-all-set (before after mask)
8116 "Return whether or not the bits in the mask have changed to all set.
8117 BEFORE is bits before change, AFTER is bits after change, and MASK is
8118 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8119 but not BEFORE."
8120 (and (/= (logand before mask) mask)
8121 (= (logand after mask) mask)))
8122
8123 (defun js2-parse-return-or-yield (tt expr-context)
8124 (let ((pos (js2-current-token-beg))
8125 (end (js2-current-token-end))
8126 (before js2-end-flags)
8127 (inside-function (js2-inside-function))
8128 e ret name)
8129 (unless inside-function
8130 (js2-report-error (if (eq tt js2-RETURN)
8131 "msg.bad.return"
8132 "msg.bad.yield")))
8133 ;; This is ugly, but we don't want to require a semicolon.
8134 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8135 (setq e (js2-parse-expr)
8136 end (js2-node-end e)))
8137 (cond
8138 ((eq tt js2-RETURN)
8139 (js2-set-flag js2-end-flags (if (null e)
8140 js2-end-returns
8141 js2-end-returns-value))
8142 (setq ret (make-js2-return-node :pos pos
8143 :len (- end pos)
8144 :retval e))
8145 (js2-node-add-children ret e)
8146 ;; See if we need a strict mode warning.
8147 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8148 ;; more thorough and accurate than this before/after flag check.
8149 ;; E.g. if there's a finally-block that always returns, we shouldn't
8150 ;; show a warning generated by inconsistent returns in the catch blocks.
8151 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8152 ;; so we know which returns/yields to highlight, and we should get rid of
8153 ;; all the checking in `js2-parse-return-or-yield'.
8154 (if (and js2-strict-inconsistent-return-warning
8155 (js2-now-all-set before js2-end-flags
8156 (logior js2-end-returns js2-end-returns-value)))
8157 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8158 (t
8159 (unless (js2-inside-function)
8160 (js2-report-error "msg.bad.yield"))
8161 (setq ret (make-js2-yield-node :pos pos
8162 :len (- end pos)
8163 :value e))
8164 (js2-node-add-children ret e)
8165 (unless expr-context
8166 (setq e ret
8167 ret (js2-wrap-with-expr-stmt pos e t))
8168 (js2-set-requires-activation)
8169 (js2-set-is-generator))))
8170 ;; see if we are mixing yields and value returns.
8171 (when (and inside-function
8172 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8173 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8174 'LEGACY))
8175 (setq name (js2-function-name js2-current-script-or-fn))
8176 (if (zerop (length name))
8177 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8178 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8179 ret))
8180
8181 (defun js2-parse-debugger ()
8182 (make-js2-keyword-node :type js2-DEBUGGER))
8183
8184 (defun js2-parse-block ()
8185 "Parser for a curly-delimited statement block.
8186 Last token matched must be `js2-LC'."
8187 (let ((pos (js2-current-token-beg))
8188 (pn (make-js2-scope)))
8189 (js2-push-scope pn)
8190 (unwind-protect
8191 (progn
8192 (js2-parse-statements pn)
8193 (js2-must-match js2-RC "msg.no.brace.block")
8194 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8195 (js2-pop-scope))
8196 pn))
8197
8198 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8199 (defun js2-parse-semi ()
8200 "Parse a statement or handle an error.
8201 Current token type is `js2-SEMI' or `js2-ERROR'."
8202 (let ((tt (js2-current-token-type)) pos len)
8203 (if (eq tt js2-SEMI)
8204 (make-js2-empty-expr-node :len 1)
8205 (setq pos (js2-current-token-beg)
8206 len (- (js2-current-token-end) pos))
8207 (js2-report-error "msg.syntax" nil pos len)
8208 (make-js2-error-node :pos pos :len len))))
8209
8210 (defun js2-parse-default-xml-namespace ()
8211 "Parse a `default xml namespace = <expr>' e4x statement."
8212 (let ((pos (js2-current-token-beg))
8213 end len expr unary)
8214 (js2-must-have-xml)
8215 (js2-set-requires-activation)
8216 (setq len (- js2-ts-cursor pos))
8217 (unless (and (js2-match-token js2-NAME)
8218 (string= (js2-current-token-string) "xml"))
8219 (js2-report-error "msg.bad.namespace" nil pos len))
8220 (unless (and (js2-match-token js2-NAME)
8221 (string= (js2-current-token-string) "namespace"))
8222 (js2-report-error "msg.bad.namespace" nil pos len))
8223 (unless (js2-match-token js2-ASSIGN)
8224 (js2-report-error "msg.bad.namespace" nil pos len))
8225 (setq expr (js2-parse-expr)
8226 end (js2-node-end expr)
8227 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8228 :pos pos
8229 :len (- end pos)
8230 :operand expr))
8231 (js2-node-add-children unary expr)
8232 (make-js2-expr-stmt-node :pos pos
8233 :len (- end pos)
8234 :expr unary)))
8235
8236 (defun js2-record-label (label bundle)
8237 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8238 (js2-get-token)
8239 (let ((name (js2-label-node-name label))
8240 labeled-stmt
8241 dup)
8242 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8243 ;; flag both labels if possible when used in editing mode
8244 (if (and js2-parse-ide-mode
8245 (setq dup (js2-get-label-by-name labeled-stmt name)))
8246 (js2-report-error "msg.dup.label" nil
8247 (js2-node-abs-pos dup) (js2-node-len dup)))
8248 (js2-report-error "msg.dup.label" nil
8249 (js2-node-pos label) (js2-node-len label)))
8250 (js2-labeled-stmt-node-add-label bundle label)
8251 (js2-node-add-children bundle label)
8252 ;; Add one reference to the bundle per label in `js2-label-set'
8253 (push (cons name bundle) js2-label-set)))
8254
8255 (defun js2-parse-name-or-label ()
8256 "Parser for identifier or label. Last token matched must be js2-NAME.
8257 Called when we found a name in a statement context. If it's a label, we gather
8258 up any following labels and the next non-label statement into a
8259 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8260 expression and return it wrapped in a `js2-expr-stmt-node'."
8261 (let ((pos (js2-current-token-beg))
8262 expr stmt bundle
8263 (continue t))
8264 ;; set check for label and call down to `js2-parse-primary-expr'
8265 (setq expr (js2-maybe-parse-label))
8266 (if (null expr)
8267 ;; Parse the non-label expression and wrap with expression stmt.
8268 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
8269 ;; else parsed a label
8270 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8271 (js2-record-label expr bundle)
8272 ;; look for more labels
8273 (while (and continue (= (js2-get-token) js2-NAME))
8274 (if (setq expr (js2-maybe-parse-label))
8275 (js2-record-label expr bundle)
8276 (setq expr (js2-parse-expr)
8277 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8278 continue nil)
8279 (js2-auto-insert-semicolon stmt)))
8280 ;; no more labels; now parse the labeled statement
8281 (unwind-protect
8282 (unless stmt
8283 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8284 (js2-unget-token)
8285 (setq stmt (js2-statement-helper))))
8286 ;; remove the labels for this statement from the global set
8287 (dolist (label (js2-labeled-stmt-node-labels bundle))
8288 (setq js2-label-set (remove label js2-label-set))))
8289 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8290 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8291 (js2-node-add-children bundle stmt)
8292 bundle)))
8293
8294 (defun js2-maybe-parse-label ()
8295 (assert (= (js2-current-token-type) js2-NAME))
8296 (let (label-pos
8297 (next-tt (js2-get-token))
8298 (label-end (js2-current-token-end)))
8299 ;; Do not consume colon, it is used as unwind indicator
8300 ;; to return to statementHelper.
8301 (js2-unget-token)
8302 (if (= next-tt js2-COLON)
8303 (prog2
8304 (setq label-pos (js2-current-token-beg))
8305 (make-js2-label-node :pos label-pos
8306 :len (- label-end label-pos)
8307 :name (js2-current-token-string))
8308 (js2-set-face label-pos
8309 label-end
8310 'font-lock-variable-name-face 'record))
8311 ;; Backtrack from the name token, too.
8312 (js2-unget-token)
8313 nil)))
8314
8315 (defun js2-parse-expr-stmt ()
8316 "Default parser in statement context, if no recognized statement found."
8317 (js2-wrap-with-expr-stmt (js2-current-token-beg)
8318 (progn
8319 (js2-unget-token)
8320 (js2-parse-expr)) t))
8321
8322 (defun js2-parse-variables (decl-type pos)
8323 "Parse a comma-separated list of variable declarations.
8324 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8325
8326 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8327 For 'var' or 'const', the keyword should be the token last scanned.
8328
8329 POS is the position where the node should start. It's sometimes the
8330 var/const/let keyword, and other times the beginning of the first token
8331 in the first variable declaration.
8332
8333 Returns the parsed `js2-var-decl-node' expression node."
8334 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8335 :pos pos))
8336 destructuring kid-pos tt init name end nbeg nend vi
8337 (continue t))
8338 ;; Example:
8339 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8340 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8341 ;; var {a, b} = baz;
8342 (while continue
8343 (setq destructuring nil
8344 name nil
8345 tt (js2-get-token)
8346 kid-pos (js2-current-token-beg)
8347 end (js2-current-token-end)
8348 init nil)
8349 (if (or (= tt js2-LB) (= tt js2-LC))
8350 ;; Destructuring assignment, e.g., var [a, b] = ...
8351 (setq destructuring (js2-parse-destruct-primary-expr)
8352 end (js2-node-end destructuring))
8353 ;; Simple variable name
8354 (js2-unget-token)
8355 (when (js2-must-match js2-NAME "msg.bad.var")
8356 (setq name (js2-create-name-node)
8357 nbeg (js2-current-token-beg)
8358 nend (js2-current-token-end)
8359 end nend)
8360 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
8361 (when (js2-match-token js2-ASSIGN)
8362 (setq init (js2-parse-assign-expr)
8363 end (js2-node-end init))
8364 (js2-record-imenu-functions init name))
8365 (when name
8366 (js2-set-face nbeg nend (if (js2-function-node-p init)
8367 'font-lock-function-name-face
8368 'font-lock-variable-name-face)
8369 'record))
8370 (setq vi (make-js2-var-init-node :pos kid-pos
8371 :len (- end kid-pos)
8372 :type decl-type))
8373 (if destructuring
8374 (progn
8375 (if (and (null init) (not js2-in-for-init))
8376 (js2-report-error "msg.destruct.assign.no.init"))
8377 (js2-define-destruct-symbols destructuring
8378 decl-type
8379 'font-lock-variable-name-face)
8380 (setf (js2-var-init-node-target vi) destructuring))
8381 (setf (js2-var-init-node-target vi) name))
8382 (setf (js2-var-init-node-initializer vi) init)
8383 (js2-node-add-children vi name destructuring init)
8384 (js2-block-node-push result vi)
8385 (unless (js2-match-token js2-COMMA)
8386 (setq continue nil)))
8387 (setf (js2-node-len result) (- end pos))
8388 result))
8389
8390 (defun js2-parse-let (pos &optional stmt-p)
8391 "Parse a let expression or statement.
8392 A let-expression is of the form `let (vars) expr'.
8393 A let-statment is of the form `let (vars) {statements}'.
8394 The third form of let is a variable declaration list, handled
8395 by `js2-parse-variables'."
8396 (let ((pn (make-js2-let-node :pos pos))
8397 beg vars body)
8398 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8399 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
8400 (js2-push-scope pn)
8401 (unwind-protect
8402 (progn
8403 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
8404 (if (js2-must-match js2-RP "msg.no.paren.let")
8405 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
8406 (if (and stmt-p (eq (js2-get-token) js2-LC))
8407 ;; let statement
8408 (progn
8409 (setf beg (js2-current-token-beg) ; position stmt at LC
8410 body (js2-parse-statements))
8411 (js2-must-match js2-RC "msg.no.curly.let")
8412 (setf (js2-node-len body) (- (js2-current-token-end) beg)
8413 (js2-node-len pn) (- (js2-current-token-end) pos)
8414 (js2-let-node-body pn) body
8415 (js2-node-type pn) js2-LET))
8416 ;; let expression
8417 (js2-unget-token)
8418 (setf body (js2-parse-expr)
8419 (js2-node-len pn) (- (js2-node-end body) pos)
8420 (js2-let-node-body pn) body))
8421 (js2-node-add-children pn vars body))
8422 (js2-pop-scope))
8423 pn))
8424
8425 (defun js2-define-new-symbol (decl-type name node &optional scope)
8426 (js2-scope-put-symbol (or scope js2-current-scope)
8427 name
8428 (make-js2-symbol decl-type name node)))
8429
8430 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8431 "Define a symbol in the current scope.
8432 If NODE is non-nil, it is the AST node associated with the symbol."
8433 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8434 (symbol (if defining-scope
8435 (js2-scope-get-symbol defining-scope name)))
8436 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8437 (cond
8438 ((and symbol ; already defined
8439 (or (= sdt js2-CONST) ; old version is const
8440 (= decl-type js2-CONST) ; new version is const
8441 ;; two let-bound vars in this block have same name
8442 (and (= sdt js2-LET)
8443 (eq defining-scope js2-current-scope))))
8444 (js2-report-error
8445 (cond
8446 ((= sdt js2-CONST) "msg.const.redecl")
8447 ((= sdt js2-LET) "msg.let.redecl")
8448 ((= sdt js2-VAR) "msg.var.redecl")
8449 ((= sdt js2-FUNCTION) "msg.function.redecl")
8450 (t "msg.parm.redecl"))
8451 name))
8452 ((= decl-type js2-LET)
8453 (if (and (not ignore-not-in-block)
8454 (or (= (js2-node-type js2-current-scope) js2-IF)
8455 (js2-loop-node-p js2-current-scope)))
8456 (js2-report-error "msg.let.decl.not.in.block")
8457 (js2-define-new-symbol decl-type name node)))
8458 ((or (= decl-type js2-VAR)
8459 (= decl-type js2-CONST)
8460 (= decl-type js2-FUNCTION))
8461 (if symbol
8462 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8463 (js2-add-strict-warning "msg.var.redecl" name)
8464 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8465 (js2-add-strict-warning "msg.var.hides.arg" name)))
8466 (js2-define-new-symbol decl-type name node
8467 js2-current-script-or-fn)))
8468 ((= decl-type js2-LP)
8469 (if symbol
8470 ;; must be duplicate parameter. Second parameter hides the
8471 ;; first, so go ahead and add the second pararameter
8472 (js2-report-warning "msg.dup.parms" name))
8473 (js2-define-new-symbol decl-type name node))
8474 (t (js2-code-bug)))))
8475
8476 (defun js2-parse-expr (&optional oneshot)
8477 (let* ((pn (js2-parse-assign-expr))
8478 (pos (js2-node-pos pn))
8479 left
8480 right
8481 op-pos)
8482 (while (and (not oneshot)
8483 (js2-match-token js2-COMMA))
8484 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
8485 (if (= (js2-peek-token) js2-YIELD)
8486 (js2-report-error "msg.yield.parenthesized"))
8487 (setq right (js2-parse-assign-expr)
8488 left pn
8489 pn (make-js2-infix-node :type js2-COMMA
8490 :pos pos
8491 :len (- js2-ts-cursor pos)
8492 :op-pos op-pos
8493 :left left
8494 :right right))
8495 (js2-node-add-children pn left right))
8496 pn))
8497
8498 (defun js2-parse-assign-expr ()
8499 (let ((tt (js2-get-token))
8500 (pos (js2-current-token-beg))
8501 pn left right op-pos
8502 ts-state recorded-identifiers)
8503 (if (= tt js2-YIELD)
8504 (js2-parse-return-or-yield tt t)
8505 ;; Save the tokenizer state in case we find an arrow function
8506 ;; and have to rewind.
8507 (setq ts-state (make-js2-ts-state)
8508 recorded-identifiers js2-recorded-identifiers)
8509 ;; not yield - parse assignment expression
8510 (setq pn (js2-parse-cond-expr)
8511 tt (js2-get-token))
8512 (cond
8513 ((and (<= js2-first-assign tt)
8514 (<= tt js2-last-assign))
8515 ;; tt express assignment (=, |=, ^=, ..., %=)
8516 (setq op-pos (- (js2-current-token-beg) pos) ; relative
8517 left pn)
8518 (setq right (js2-parse-assign-expr)
8519 pn (make-js2-assign-node :type tt
8520 :pos pos
8521 :len (- (js2-node-end right) pos)
8522 :op-pos op-pos
8523 :left left
8524 :right right))
8525 (when js2-parse-ide-mode
8526 (js2-highlight-assign-targets pn left right)
8527 (js2-record-imenu-functions right left))
8528 ;; do this last so ide checks above can use absolute positions
8529 (js2-node-add-children pn left right))
8530 ((and (= tt js2-ARROW)
8531 (>= js2-language-version 200))
8532 (js2-ts-seek ts-state)
8533 (setq js2-recorded-identifiers recorded-identifiers)
8534 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
8535 (t
8536 (js2-unget-token)))
8537 pn)))
8538
8539 (defun js2-parse-cond-expr ()
8540 (let ((pos (js2-current-token-beg))
8541 (pn (js2-parse-or-expr))
8542 test-expr
8543 if-true
8544 if-false
8545 q-pos
8546 c-pos)
8547 (when (js2-match-token js2-HOOK)
8548 (setq q-pos (- (js2-current-token-beg) pos)
8549 if-true (js2-parse-assign-expr))
8550 (js2-must-match js2-COLON "msg.no.colon.cond")
8551 (setq c-pos (- (js2-current-token-beg) pos)
8552 if-false (js2-parse-assign-expr)
8553 test-expr pn
8554 pn (make-js2-cond-node :pos pos
8555 :len (- (js2-node-end if-false) pos)
8556 :test-expr test-expr
8557 :true-expr if-true
8558 :false-expr if-false
8559 :q-pos q-pos
8560 :c-pos c-pos))
8561 (js2-node-add-children pn test-expr if-true if-false))
8562 pn))
8563
8564 (defun js2-make-binary (type left parser)
8565 "Helper for constructing a binary-operator AST node.
8566 LEFT is the left-side-expression, already parsed, and the
8567 binary operator should have just been matched.
8568 PARSER is a function to call to parse the right operand,
8569 or a `js2-node' struct if it has already been parsed.
8570 FIXME: The latter option is unused?"
8571 (let* ((pos (js2-node-pos left))
8572 (op-pos (- (js2-current-token-beg) pos))
8573 (right (if (js2-node-p parser)
8574 parser
8575 (js2-get-token)
8576 (funcall parser)))
8577 (pn (make-js2-infix-node :type type
8578 :pos pos
8579 :len (- (js2-node-end right) pos)
8580 :op-pos op-pos
8581 :left left
8582 :right right)))
8583 (js2-node-add-children pn left right)
8584 pn))
8585
8586 (defun js2-parse-or-expr ()
8587 (let ((pn (js2-parse-and-expr)))
8588 (when (js2-match-token js2-OR)
8589 (setq pn (js2-make-binary js2-OR
8590 pn
8591 'js2-parse-or-expr)))
8592 pn))
8593
8594 (defun js2-parse-and-expr ()
8595 (let ((pn (js2-parse-bit-or-expr)))
8596 (when (js2-match-token js2-AND)
8597 (setq pn (js2-make-binary js2-AND
8598 pn
8599 'js2-parse-and-expr)))
8600 pn))
8601
8602 (defun js2-parse-bit-or-expr ()
8603 (let ((pn (js2-parse-bit-xor-expr)))
8604 (while (js2-match-token js2-BITOR)
8605 (setq pn (js2-make-binary js2-BITOR
8606 pn
8607 'js2-parse-bit-xor-expr)))
8608 pn))
8609
8610 (defun js2-parse-bit-xor-expr ()
8611 (let ((pn (js2-parse-bit-and-expr)))
8612 (while (js2-match-token js2-BITXOR)
8613 (setq pn (js2-make-binary js2-BITXOR
8614 pn
8615 'js2-parse-bit-and-expr)))
8616 pn))
8617
8618 (defun js2-parse-bit-and-expr ()
8619 (let ((pn (js2-parse-eq-expr)))
8620 (while (js2-match-token js2-BITAND)
8621 (setq pn (js2-make-binary js2-BITAND
8622 pn
8623 'js2-parse-eq-expr)))
8624 pn))
8625
8626 (defconst js2-parse-eq-ops
8627 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8628
8629 (defun js2-parse-eq-expr ()
8630 (let ((pn (js2-parse-rel-expr))
8631 tt)
8632 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
8633 (setq pn (js2-make-binary tt
8634 pn
8635 'js2-parse-rel-expr)))
8636 (js2-unget-token)
8637 pn))
8638
8639 (defconst js2-parse-rel-ops
8640 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8641
8642 (defun js2-parse-rel-expr ()
8643 (let ((pn (js2-parse-shift-expr))
8644 (continue t)
8645 tt)
8646 (while continue
8647 (setq tt (js2-get-token))
8648 (cond
8649 ((and js2-in-for-init (= tt js2-IN))
8650 (js2-unget-token)
8651 (setq continue nil))
8652 ((memq tt js2-parse-rel-ops)
8653 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8654 (t
8655 (js2-unget-token)
8656 (setq continue nil))))
8657 pn))
8658
8659 (defconst js2-parse-shift-ops
8660 (list js2-LSH js2-URSH js2-RSH))
8661
8662 (defun js2-parse-shift-expr ()
8663 (let ((pn (js2-parse-add-expr))
8664 tt
8665 (continue t))
8666 (while continue
8667 (setq tt (js2-get-token))
8668 (if (memq tt js2-parse-shift-ops)
8669 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
8670 (js2-unget-token)
8671 (setq continue nil)))
8672 pn))
8673
8674 (defun js2-parse-add-expr ()
8675 (let ((pn (js2-parse-mul-expr))
8676 tt
8677 (continue t))
8678 (while continue
8679 (setq tt (js2-get-token))
8680 (if (or (= tt js2-ADD) (= tt js2-SUB))
8681 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
8682 (js2-unget-token)
8683 (setq continue nil)))
8684 pn))
8685
8686 (defconst js2-parse-mul-ops
8687 (list js2-MUL js2-DIV js2-MOD))
8688
8689 (defun js2-parse-mul-expr ()
8690 (let ((pn (js2-parse-unary-expr))
8691 tt
8692 (continue t))
8693 (while continue
8694 (setq tt (js2-get-token))
8695 (if (memq tt js2-parse-mul-ops)
8696 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
8697 (js2-unget-token)
8698 (setq continue nil)))
8699 pn))
8700
8701 (defun js2-make-unary (type parser &rest args)
8702 "Make a unary node of type TYPE.
8703 PARSER is either a node (for postfix operators) or a function to call
8704 to parse the operand (for prefix operators)."
8705 (let* ((pos (js2-current-token-beg))
8706 (postfix (js2-node-p parser))
8707 (expr (if postfix
8708 parser
8709 (apply parser args)))
8710 end
8711 pn)
8712 (if postfix ; e.g. i++
8713 (setq pos (js2-node-pos expr)
8714 end (js2-current-token-end))
8715 (setq end (js2-node-end expr)))
8716 (setq pn (make-js2-unary-node :type type
8717 :pos pos
8718 :len (- end pos)
8719 :operand expr))
8720 (js2-node-add-children pn expr)
8721 pn))
8722
8723 (defconst js2-incrementable-node-types
8724 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8725 "Node types that can be the operand of a ++ or -- operator.")
8726
8727 (defun js2-check-bad-inc-dec (tt beg end unary)
8728 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8729 js2-incrementable-node-types)
8730 (js2-report-error (if (= tt js2-INC)
8731 "msg.bad.incr"
8732 "msg.bad.decr")
8733 nil beg (- end beg))))
8734
8735 (defun js2-parse-unary-expr ()
8736 (let ((tt (js2-current-token-type))
8737 pn expr beg end)
8738 (cond
8739 ((or (= tt js2-VOID)
8740 (= tt js2-NOT)
8741 (= tt js2-BITNOT)
8742 (= tt js2-TYPEOF))
8743 (js2-get-token)
8744 (js2-make-unary tt 'js2-parse-unary-expr))
8745 ((= tt js2-ADD)
8746 (js2-get-token)
8747 ;; Convert to special POS token in decompiler and parse tree
8748 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8749 ((= tt js2-SUB)
8750 (js2-get-token)
8751 ;; Convert to special NEG token in decompiler and parse tree
8752 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8753 ((or (= tt js2-INC)
8754 (= tt js2-DEC))
8755 (js2-get-token)
8756 (prog1
8757 (setq beg (js2-current-token-beg)
8758 end (js2-current-token-end)
8759 expr (js2-make-unary tt 'js2-parse-member-expr t))
8760 (js2-check-bad-inc-dec tt beg end expr)))
8761 ((= tt js2-DELPROP)
8762 (js2-get-token)
8763 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8764 ((= tt js2-ERROR)
8765 (js2-get-token)
8766 (make-js2-error-node)) ; try to continue
8767 ((and (= tt js2-LT)
8768 js2-compiler-xml-available)
8769 ;; XML stream encountered in expression.
8770 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8771 (t
8772 (setq pn (js2-parse-member-expr t)
8773 ;; Don't look across a newline boundary for a postfix incop.
8774 tt (js2-peek-token-or-eol))
8775 (when (or (= tt js2-INC) (= tt js2-DEC))
8776 (js2-get-token)
8777 (setf expr pn
8778 pn (js2-make-unary tt expr))
8779 (js2-node-set-prop pn 'postfix t)
8780 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
8781 pn))))
8782
8783 (defun js2-parse-xml-initializer ()
8784 "Parse an E4X XML initializer.
8785 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8786 Then I'll postprocess the result, depending on whether we're in IDE
8787 mode or codegen mode, and generate the appropriate rewritten AST.
8788 IDE mode uses a rich AST that models the XML structure. Codegen mode
8789 just concatenates everything and makes a new XML or XMLList out of it."
8790 (let ((tt (js2-get-first-xml-token))
8791 pn-xml pn expr kids expr-pos
8792 (continue t)
8793 (first-token t))
8794 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8795 (js2-report-error "msg.syntax"))
8796 (setq pn-xml (make-js2-xml-node))
8797 (while continue
8798 (if first-token
8799 (setq first-token nil)
8800 (setq tt (js2-get-next-xml-token)))
8801 (cond
8802 ;; js2-XML means we found a {expr} in the XML stream.
8803 ;; The token string is the XML up to the left-curly.
8804 ((= tt js2-XML)
8805 (push (make-js2-string-node :pos (js2-current-token-beg)
8806 :len (- js2-ts-cursor (js2-current-token-beg)))
8807 kids)
8808 (js2-must-match js2-LC "msg.syntax")
8809 (setq expr-pos js2-ts-cursor
8810 expr (if (eq (js2-peek-token) js2-RC)
8811 (make-js2-empty-expr-node :pos expr-pos)
8812 (js2-parse-expr)))
8813 (js2-must-match js2-RC "msg.syntax")
8814 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8815 :len (js2-node-len expr)
8816 :expr expr))
8817 (js2-node-add-children pn expr)
8818 (push pn kids))
8819 ;; a js2-XMLEND token means we hit the final close-tag.
8820 ((= tt js2-XMLEND)
8821 (push (make-js2-string-node :pos (js2-current-token-beg)
8822 :len (- js2-ts-cursor (js2-current-token-beg)))
8823 kids)
8824 (dolist (kid (nreverse kids))
8825 (js2-block-node-push pn-xml kid))
8826 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8827 (js2-node-pos pn-xml))
8828 continue nil))
8829 (t
8830 (js2-report-error "msg.syntax")
8831 (setq continue nil))))
8832 pn-xml))
8833
8834
8835 (defun js2-parse-argument-list ()
8836 "Parse an argument list and return it as a Lisp list of nodes.
8837 Returns the list in reverse order. Consumes the right-paren token."
8838 (let (result)
8839 (unless (js2-match-token js2-RP)
8840 (loop do
8841 (let ((tt (js2-get-token)))
8842 (if (= tt js2-YIELD)
8843 (js2-report-error "msg.yield.parenthesized"))
8844 (if (and (= tt js2-TRIPLEDOT)
8845 (>= js2-language-version 200))
8846 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
8847 (js2-unget-token)
8848 (push (js2-parse-assign-expr) result)))
8849 while
8850 (js2-match-token js2-COMMA))
8851 (js2-must-match js2-RP "msg.no.paren.arg")
8852 result)))
8853
8854 (defun js2-parse-member-expr (&optional allow-call-syntax)
8855 (let ((tt (js2-current-token-type))
8856 pn pos target args beg end init)
8857 (if (/= tt js2-NEW)
8858 (setq pn (js2-parse-primary-expr))
8859 ;; parse a 'new' expression
8860 (js2-get-token)
8861 (setq pos (js2-current-token-beg)
8862 beg pos
8863 target (js2-parse-member-expr)
8864 end (js2-node-end target)
8865 pn (make-js2-new-node :pos pos
8866 :target target
8867 :len (- end pos)))
8868 (js2-highlight-function-call (js2-current-token))
8869 (js2-node-add-children pn target)
8870 (when (js2-match-token js2-LP)
8871 ;; Add the arguments to pn, if any are supplied.
8872 (setf beg pos ; start of "new" keyword
8873 pos (js2-current-token-beg)
8874 args (nreverse (js2-parse-argument-list))
8875 (js2-new-node-args pn) args
8876 end (js2-current-token-end)
8877 (js2-new-node-lp pn) (- pos beg)
8878 (js2-new-node-rp pn) (- end 1 beg))
8879 (apply #'js2-node-add-children pn args))
8880 (when (and js2-allow-rhino-new-expr-initializer
8881 (js2-match-token js2-LC))
8882 (setf init (js2-parse-object-literal)
8883 end (js2-node-end init)
8884 (js2-new-node-initializer pn) init)
8885 (js2-node-add-children pn init))
8886 (setf (js2-node-len pn) (- end beg))) ; end outer if
8887 (js2-parse-member-expr-tail allow-call-syntax pn)))
8888
8889 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8890 "Parse a chain of property/array accesses or function calls.
8891 Includes parsing for E4X operators like `..' and `.@'.
8892 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8893 Returns an expression tree that includes PN, the parent node."
8894 (let (tt
8895 (continue t))
8896 (while continue
8897 (setq tt (js2-get-token))
8898 (cond
8899 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8900 (setq pn (js2-parse-property-access tt pn)))
8901 ((= tt js2-DOTQUERY)
8902 (setq pn (js2-parse-dot-query pn)))
8903 ((= tt js2-LB)
8904 (setq pn (js2-parse-element-get pn)))
8905 ((= tt js2-LP)
8906 (js2-unget-token)
8907 (if allow-call-syntax
8908 (setq pn (js2-parse-function-call pn))
8909 (setq continue nil)))
8910 (t
8911 (js2-unget-token)
8912 (setq continue nil))))
8913 (if (>= js2-highlight-level 2)
8914 (js2-parse-highlight-member-expr-node pn))
8915 pn))
8916
8917 (defun js2-parse-dot-query (pn)
8918 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8919 Last token parsed must be `js2-DOTQUERY'."
8920 (let ((pos (js2-node-pos pn))
8921 op-pos expr end)
8922 (js2-must-have-xml)
8923 (js2-set-requires-activation)
8924 (setq op-pos (js2-current-token-beg)
8925 expr (js2-parse-expr)
8926 end (js2-node-end expr)
8927 pn (make-js2-xml-dot-query-node :left pn
8928 :pos pos
8929 :op-pos op-pos
8930 :right expr))
8931 (js2-node-add-children pn
8932 (js2-xml-dot-query-node-left pn)
8933 (js2-xml-dot-query-node-right pn))
8934 (if (js2-must-match js2-RP "msg.no.paren")
8935 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
8936 end (js2-current-token-end)))
8937 (setf (js2-node-len pn) (- end pos))
8938 pn))
8939
8940 (defun js2-parse-element-get (pn)
8941 "Parse an element-get expression, e.g. foo[bar].
8942 Last token parsed must be `js2-RB'."
8943 (let ((lb (js2-current-token-beg))
8944 (pos (js2-node-pos pn))
8945 rb expr)
8946 (setq expr (js2-parse-expr))
8947 (if (js2-must-match js2-RB "msg.no.bracket.index")
8948 (setq rb (js2-current-token-beg)))
8949 (setq pn (make-js2-elem-get-node :target pn
8950 :pos pos
8951 :element expr
8952 :lb (js2-relpos lb pos)
8953 :rb (js2-relpos rb pos)
8954 :len (- (js2-current-token-end) pos)))
8955 (js2-node-add-children pn
8956 (js2-elem-get-node-target pn)
8957 (js2-elem-get-node-element pn))
8958 pn))
8959
8960 (defun js2-highlight-function-call (token)
8961 (when (eq (js2-token-type token) js2-NAME)
8962 (js2-record-face 'js2-function-call token)))
8963
8964 (defun js2-parse-function-call (pn)
8965 (js2-highlight-function-call (js2-current-token))
8966 (js2-get-token)
8967 (let (args
8968 (pos (js2-node-pos pn)))
8969 (setq pn (make-js2-call-node :pos pos
8970 :target pn
8971 :lp (- (js2-current-token-beg) pos)))
8972 (js2-node-add-children pn (js2-call-node-target pn))
8973 ;; Add the arguments to pn, if any are supplied.
8974 (setf args (nreverse (js2-parse-argument-list))
8975 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
8976 (js2-call-node-args pn) args)
8977 (apply #'js2-node-add-children pn args)
8978 (setf (js2-node-len pn) (- js2-ts-cursor pos))
8979 pn))
8980
8981 (defun js2-parse-property-access (tt pn)
8982 "Parse a property access, XML descendants access, or XML attr access."
8983 (let ((member-type-flags 0)
8984 (dot-pos (js2-current-token-beg))
8985 (dot-len (if (= tt js2-DOTDOT) 2 1))
8986 name
8987 ref ; right side of . or .. operator
8988 result)
8989 (when (= tt js2-DOTDOT)
8990 (js2-must-have-xml)
8991 (setq member-type-flags js2-descendants-flag))
8992 (if (not js2-compiler-xml-available)
8993 (progn
8994 (js2-must-match-prop-name "msg.no.name.after.dot")
8995 (setq name (js2-create-name-node t js2-GETPROP)
8996 result (make-js2-prop-get-node :left pn
8997 :pos (js2-current-token-beg)
8998 :right name
8999 :len (js2-current-token-len)))
9000 (js2-node-add-children result pn name)
9001 result)
9002 ;; otherwise look for XML operators
9003 (setf result (if (= tt js2-DOT)
9004 (make-js2-prop-get-node)
9005 (make-js2-infix-node :type js2-DOTDOT))
9006 (js2-node-pos result) (js2-node-pos pn)
9007 (js2-infix-node-op-pos result) dot-pos
9008 (js2-infix-node-left result) pn ; do this after setting position
9009 tt (js2-next-token))
9010 (cond
9011 ;; needed for generator.throw()
9012 ((= tt js2-THROW)
9013 (setq ref (js2-parse-property-name nil nil member-type-flags)))
9014 ;; handles: name, ns::name, ns::*, ns::[expr]
9015 ((js2-valid-prop-name-token tt)
9016 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9017 ;; handles: *, *::name, *::*, *::[expr]
9018 ((= tt js2-MUL)
9019 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9020 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9021 ((= tt js2-XMLATTR)
9022 (setq result (js2-parse-attribute-access)))
9023 (t
9024 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9025 (if ref
9026 (setf (js2-node-len result) (- (js2-node-end ref)
9027 (js2-node-pos result))
9028 (js2-infix-node-right result) ref))
9029 (if (js2-infix-node-p result)
9030 (js2-node-add-children result
9031 (js2-infix-node-left result)
9032 (js2-infix-node-right result)))
9033 result)))
9034
9035 (defun js2-parse-attribute-access ()
9036 "Parse an E4X XML attribute expression.
9037 This includes expressions of the forms:
9038
9039 @attr @ns::attr @ns::*
9040 @* @*::attr @*::*
9041 @[expr] @*::[expr] @ns::[expr]
9042
9043 Called if we peeked an '@' token."
9044 (let ((tt (js2-next-token))
9045 (at-pos (js2-current-token-beg)))
9046 (cond
9047 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9048 ((js2-valid-prop-name-token tt)
9049 (js2-parse-property-name at-pos nil 0))
9050 ;; handles: @*, @*::name, @*::*, @*::[expr]
9051 ((= tt js2-MUL)
9052 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9053 ;; handles @[expr]
9054 ((= tt js2-LB)
9055 (js2-parse-xml-elem-ref at-pos))
9056 (t
9057 (js2-report-error "msg.no.name.after.xmlAttr")
9058 ;; Avoid cascaded errors that happen if we make an error node here.
9059 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9060
9061 (defun js2-parse-property-name (at-pos s member-type-flags)
9062 "Check if :: follows name in which case it becomes qualified name.
9063
9064 AT-POS is a natural number if we just read an '@' token, else nil.
9065 S is the name or string that was matched: an identifier, 'throw' or '*'.
9066 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9067
9068 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9069 operator, or the name is followed by ::. For a plain name, returns a
9070 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9071 (let ((pos (or at-pos (js2-current-token-beg)))
9072 colon-pos
9073 (name (js2-create-name-node t (js2-current-token-type) s))
9074 ns tt pn)
9075 (catch 'return
9076 (when (js2-match-token js2-COLONCOLON)
9077 (setq ns name
9078 colon-pos (js2-current-token-beg)
9079 tt (js2-next-token))
9080 (cond
9081 ;; handles name::name
9082 ((js2-valid-prop-name-token tt)
9083 (setq name (js2-create-name-node)))
9084 ;; handles name::*
9085 ((= tt js2-MUL)
9086 (setq name (js2-create-name-node nil nil "*")))
9087 ;; handles name::[expr]
9088 ((= tt js2-LB)
9089 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9090 (t
9091 (js2-report-error "msg.no.name.after.coloncolon"))))
9092 (if (and (null ns) (zerop member-type-flags))
9093 name
9094 (prog1
9095 (setq pn
9096 (make-js2-xml-prop-ref-node :pos pos
9097 :len (- (js2-node-end name) pos)
9098 :at-pos at-pos
9099 :colon-pos colon-pos
9100 :propname name))
9101 (js2-node-add-children pn name))))))
9102
9103 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9104 "Parse the [expr] portion of an xml element reference.
9105 For instance, @[expr], @*::[expr], or ns::[expr]."
9106 (let* ((lb (js2-current-token-beg))
9107 (pos (or at-pos lb))
9108 rb
9109 (expr (js2-parse-expr))
9110 (end (js2-node-end expr))
9111 pn)
9112 (if (js2-must-match js2-RB "msg.no.bracket.index")
9113 (setq rb (js2-current-token-beg)
9114 end (js2-current-token-end)))
9115 (prog1
9116 (setq pn
9117 (make-js2-xml-elem-ref-node :pos pos
9118 :len (- end pos)
9119 :namespace namespace
9120 :colon-pos colon-pos
9121 :at-pos at-pos
9122 :expr expr
9123 :lb (js2-relpos lb pos)
9124 :rb (js2-relpos rb pos)))
9125 (js2-node-add-children pn namespace expr))))
9126
9127 (defun js2-parse-destruct-primary-expr ()
9128 (let ((js2-is-in-destructuring t))
9129 (js2-parse-primary-expr)))
9130
9131 (defun js2-parse-primary-expr ()
9132 "Parse a literal (leaf) expression of some sort.
9133 Includes complex literals such as functions, object-literals,
9134 array-literals, array comprehensions and regular expressions."
9135 (let (pn ; parent node (usually return value)
9136 tt
9137 px-pos ; paren-expr pos
9138 len
9139 flags ; regexp flags
9140 expr)
9141 (setq tt (js2-current-token-type))
9142 (cond
9143 ((= tt js2-FUNCTION)
9144 (js2-parse-function-expr))
9145 ((= tt js2-LB)
9146 (js2-parse-array-literal))
9147 ((= tt js2-LC)
9148 (js2-parse-object-literal))
9149 ((= tt js2-LET)
9150 (js2-parse-let (js2-current-token-beg)))
9151 ((= tt js2-LP)
9152 (setq px-pos (js2-current-token-beg)
9153 expr (js2-parse-expr))
9154 (js2-must-match js2-RP "msg.no.paren")
9155 (setq pn (make-js2-paren-node :pos px-pos
9156 :expr expr
9157 :len (- (js2-current-token-end) px-pos)))
9158 (js2-node-add-children pn (js2-paren-node-expr pn))
9159 pn)
9160 ((= tt js2-XMLATTR)
9161 (js2-must-have-xml)
9162 (js2-parse-attribute-access))
9163 ((= tt js2-NAME)
9164 (js2-parse-name tt))
9165 ((= tt js2-NUMBER)
9166 (make-js2-number-node))
9167 ((= tt js2-STRING)
9168 (prog1
9169 (make-js2-string-node)
9170 (js2-record-face 'font-lock-string-face)))
9171 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9172 ;; Got / or /= which in this context means a regexp literal
9173 (setq px-pos (js2-current-token-beg))
9174 (setq flags (js2-read-regexp tt))
9175 (prog1
9176 (make-js2-regexp-node :pos px-pos
9177 :len (- js2-ts-cursor px-pos)
9178 :value (js2-current-token-string)
9179 :flags flags)
9180 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9181 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9182 ((or (= tt js2-NULL)
9183 (= tt js2-THIS)
9184 (= tt js2-FALSE)
9185 (= tt js2-TRUE))
9186 (make-js2-keyword-node :type tt))
9187 ((= tt js2-RP)
9188 ;; Not valid expression syntax, but this is valid in an arrow
9189 ;; function with no params: () => body.
9190 (if (eq (js2-peek-token) js2-ARROW)
9191 (progn
9192 (js2-unget-token) ; Put back the right paren.
9193 ;; Return whatever, it will hopefully be rewinded and
9194 ;; reparsed when we reach the =>.
9195 (make-js2-keyword-node :type js2-NULL))
9196 (js2-report-error "msg.syntax")
9197 (make-js2-error-node)))
9198 ((= tt js2-TRIPLEDOT)
9199 ;; Likewise, only valid in an arrow function with a rest param.
9200 (if (and (js2-match-token js2-NAME)
9201 (js2-match-token js2-RP)
9202 (eq (js2-peek-token) js2-ARROW))
9203 (progn
9204 (js2-unget-token) ; Put back the right paren.
9205 ;; See the previous case.
9206 (make-js2-keyword-node :type js2-NULL))
9207 (js2-report-error "msg.syntax")
9208 (make-js2-error-node)))
9209 ((= tt js2-RESERVED)
9210 (js2-report-error "msg.reserved.id")
9211 (make-js2-name-node))
9212 ((= tt js2-ERROR)
9213 ;; the scanner or one of its subroutines reported the error.
9214 (make-js2-error-node))
9215 ((= tt js2-EOF)
9216 (setq px-pos (point-at-bol)
9217 len (- js2-ts-cursor px-pos))
9218 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9219 (make-js2-error-node :pos (1- js2-ts-cursor)))
9220 (t
9221 (js2-report-error "msg.syntax")
9222 (make-js2-error-node)))))
9223
9224 (defun js2-parse-name (_tt)
9225 (let ((name (js2-current-token-string))
9226 node)
9227 (setq node (if js2-compiler-xml-available
9228 (js2-parse-property-name nil name 0)
9229 (js2-create-name-node 'check-activation nil name)))
9230 (if js2-highlight-external-variables
9231 (js2-record-name-node node))
9232 node))
9233
9234 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9235 (js2-add-strict-warning
9236 msg nil
9237 ;; back up from comma to beginning of line or array/objlit
9238 (max (if elems
9239 (js2-node-pos (car elems))
9240 pos)
9241 (save-excursion
9242 (goto-char comma-pos)
9243 (back-to-indentation)
9244 (point)))
9245 comma-pos))
9246
9247 (defun js2-parse-array-literal ()
9248 (let ((pos (js2-current-token-beg))
9249 (after-lb-or-comma t)
9250 after-comma tt elems pn
9251 (continue t))
9252 (unless js2-is-in-destructuring
9253 (js2-push-scope (make-js2-scope))) ; for array comp
9254 (while continue
9255 (setq tt (js2-get-token))
9256 (cond
9257 ;; comma
9258 ((= tt js2-COMMA)
9259 (setq after-comma (js2-current-token-end))
9260 (if (not after-lb-or-comma)
9261 (setq after-lb-or-comma t)
9262 (push nil elems)))
9263 ;; end of array
9264 ((or (= tt js2-RB)
9265 (= tt js2-EOF)) ; prevent infinite loop
9266 (if (= tt js2-EOF)
9267 (js2-report-error "msg.no.bracket.arg" nil pos))
9268 (setq continue nil
9269 pn (make-js2-array-node :pos pos
9270 :len (- js2-ts-cursor pos)
9271 :elems (nreverse elems)))
9272 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9273 (when (and after-comma (not js2-is-in-destructuring))
9274 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9275 pos elems after-comma)))
9276 ;; destructuring binding
9277 (js2-is-in-destructuring
9278 (push (if (or (= tt js2-LC)
9279 (= tt js2-LB)
9280 (= tt js2-NAME))
9281 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9282 (js2-parse-destruct-primary-expr)
9283 ;; invalid pattern
9284 (js2-report-error "msg.bad.var")
9285 (make-js2-error-node))
9286 elems)
9287 (setq after-lb-or-comma nil
9288 after-comma nil))
9289 ;; array comp
9290 ((and (>= js2-language-version 170)
9291 (= tt js2-FOR) ; check for array comprehension
9292 (not after-lb-or-comma) ; "for" can't follow a comma
9293 elems ; must have at least 1 element
9294 (not (cdr elems))) ; but no 2nd element
9295 (js2-unget-token)
9296 (setf continue nil
9297 pn (js2-parse-array-comprehension (car elems) pos)))
9298 ;; another element
9299 (t
9300 (unless after-lb-or-comma
9301 (js2-report-error "msg.no.bracket.arg"))
9302 (if (and (= tt js2-TRIPLEDOT)
9303 (>= js2-language-version 200))
9304 ;; spread operator
9305 (push (js2-make-unary tt 'js2-parse-assign-expr)
9306 elems)
9307 (js2-unget-token)
9308 (push (js2-parse-assign-expr) elems))
9309 (setq after-lb-or-comma nil
9310 after-comma nil))))
9311 (unless js2-is-in-destructuring
9312 (js2-pop-scope))
9313 pn))
9314
9315 (defun js2-parse-array-comprehension (expr pos)
9316 "Parse a JavaScript 1.7 Array Comprehension.
9317 EXPR is the first expression after the opening left-bracket.
9318 POS is the beginning of the LB token preceding EXPR.
9319 We should have just parsed the 'for' keyword before calling this function."
9320 (let (loops loop first filter if-pos result)
9321 (while (= (js2-get-token) js2-FOR)
9322 (let ((prev (car loops))) ; rearrange scope chain
9323 (push (setq loop (js2-parse-array-comp-loop)) loops)
9324 (if prev ; each loop is parent scope to the next one
9325 (setf (js2-scope-parent-scope loop) prev)
9326 ; first loop takes expr scope's parent
9327 (setf (js2-scope-parent-scope (setq first loop))
9328 (js2-scope-parent-scope js2-current-scope)))))
9329 (js2-unget-token)
9330 ;; set expr scope's parent to the last loop
9331 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9332 (if (/= (js2-get-token) js2-IF)
9333 (js2-unget-token)
9334 (setq if-pos (- (js2-current-token-beg) pos) ; relative
9335 filter (js2-parse-condition)))
9336 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9337 (setq result (make-js2-array-comp-node :pos pos
9338 :len (- js2-ts-cursor pos)
9339 :result expr
9340 :loops (nreverse loops)
9341 :filter (car filter)
9342 :lp (js2-relpos (second filter) pos)
9343 :rp (js2-relpos (third filter) pos)
9344 :if-pos if-pos))
9345 (apply #'js2-node-add-children result expr (car filter)
9346 (js2-array-comp-node-loops result))
9347 (setq js2-current-scope first) ; pop to the first loop
9348 result))
9349
9350 (defun js2-parse-array-comp-loop ()
9351 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9352 Last token peeked should be the initial FOR."
9353 (let ((pos (js2-current-token-beg))
9354 (pn (make-js2-array-comp-loop-node))
9355 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9356 (assert (= (js2-current-token-type) js2-FOR))
9357 (js2-push-scope pn)
9358 (unwind-protect
9359 (progn
9360 (when (js2-match-token js2-NAME)
9361 (if (string= (js2-current-token-string) "each")
9362 (progn
9363 (setq foreach-p t
9364 each-pos (- (js2-current-token-beg) pos)) ; relative
9365 (js2-record-face 'font-lock-keyword-face))
9366 (js2-report-error "msg.no.paren.for")))
9367 (if (js2-must-match js2-LP "msg.no.paren.for")
9368 (setq lp (- (js2-current-token-beg) pos)))
9369 (setq tt (js2-peek-token))
9370 (cond
9371 ((or (= tt js2-LB)
9372 (= tt js2-LC))
9373 (js2-get-token)
9374 (setq iter (js2-parse-destruct-primary-expr))
9375 (js2-define-destruct-symbols iter js2-LET
9376 'font-lock-variable-name-face t))
9377 ((js2-match-token js2-NAME)
9378 (setq iter (js2-create-name-node)))
9379 (t
9380 (js2-report-error "msg.bad.var")))
9381 ;; Define as a let since we want the scope of the variable to
9382 ;; be restricted to the array comprehension
9383 (if (js2-name-node-p iter)
9384 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9385 (if (or (js2-match-token js2-IN)
9386 (and (>= js2-language-version 200)
9387 (js2-match-contextual-kwd "of")
9388 (setq forof-p t)))
9389 (setq in-pos (- (js2-current-token-beg) pos))
9390 (js2-report-error "msg.in.after.for.name"))
9391 (setq obj (js2-parse-expr))
9392 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9393 (setq rp (- (js2-current-token-beg) pos)))
9394 (setf (js2-node-pos pn) pos
9395 (js2-node-len pn) (- js2-ts-cursor pos)
9396 (js2-array-comp-loop-node-iterator pn) iter
9397 (js2-array-comp-loop-node-object pn) obj
9398 (js2-array-comp-loop-node-in-pos pn) in-pos
9399 (js2-array-comp-loop-node-each-pos pn) each-pos
9400 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9401 (js2-array-comp-loop-node-forof-p pn) forof-p
9402 (js2-array-comp-loop-node-lp pn) lp
9403 (js2-array-comp-loop-node-rp pn) rp)
9404 (js2-node-add-children pn iter obj))
9405 (js2-pop-scope))
9406 pn))
9407
9408 (defun js2-parse-object-literal ()
9409 (let ((pos (js2-current-token-beg))
9410 tt elems result after-comma
9411 (continue t))
9412 (while continue
9413 (setq tt (js2-get-token))
9414 (cond
9415 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9416 ;; {get foo() {...}}, or {set foo(x) {...}}
9417 ((or (js2-valid-prop-name-token tt)
9418 (= tt js2-STRING))
9419 (setq after-comma nil
9420 result (js2-parse-named-prop tt))
9421 (if (and (null result)
9422 (not js2-recover-from-parse-errors))
9423 (setq continue nil)
9424 (push result elems)))
9425 ;; {12: x} or {10.7: x}
9426 ((= tt js2-NUMBER)
9427 (setq after-comma nil)
9428 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9429 ;; trailing comma
9430 ((= tt js2-RC)
9431 (js2-unget-token)
9432 (setq continue nil)
9433 (if after-comma
9434 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9435 pos elems after-comma)))
9436 (t
9437 (js2-report-error "msg.bad.prop")
9438 (unless js2-recover-from-parse-errors
9439 (setq continue nil)))) ; end switch
9440 (if (js2-match-token js2-COMMA)
9441 (setq after-comma (js2-current-token-end))
9442 (setq continue nil))) ; end loop
9443 (js2-must-match js2-RC "msg.no.brace.prop")
9444 (setq result (make-js2-object-node :pos pos
9445 :len (- js2-ts-cursor pos)
9446 :elems (nreverse elems)))
9447 (apply #'js2-node-add-children result (js2-object-node-elems result))
9448 result))
9449
9450 (defun js2-parse-named-prop (tt)
9451 "Parse a name, string, or getter/setter object property.
9452 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9453 (let ((string-prop (and (= tt js2-STRING)
9454 (make-js2-string-node)))
9455 expr
9456 (ppos (js2-current-token-beg))
9457 (pend (js2-current-token-end))
9458 (name (js2-create-name-node))
9459 (prop (js2-current-token-string)))
9460 (cond
9461 ;; getter/setter prop
9462 ((and (= tt js2-NAME)
9463 (= (js2-peek-token) js2-NAME)
9464 (or (string= prop "get")
9465 (string= prop "set")))
9466 (js2-get-token)
9467 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9468 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9469 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9470 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9471 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9472 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9473 ;; when patterns are used in variable declarations, function parameters,
9474 ;; catch-clause, and iterators.
9475 ;; We have to set `js2-is-in-destructuring' to t when the current
9476 ;; expressions are on the left side of any assignment, but it's difficult
9477 ;; because it requires looking ahead of expression.
9478 ((and js2-is-in-destructuring
9479 (= tt js2-NAME)
9480 (let ((ctk (js2-peek-token)))
9481 (or (= ctk js2-COMMA)
9482 (= ctk js2-RC)
9483 (js2-valid-prop-name-token ctk))))
9484 name)
9485 ;; regular prop
9486 (t
9487 (prog1
9488 (setq expr (js2-parse-plain-property (or string-prop name)))
9489 (js2-set-face ppos pend
9490 (if (js2-function-node-p
9491 (js2-object-prop-node-right expr))
9492 'font-lock-function-name-face
9493 'font-lock-variable-name-face)
9494 'record))))))
9495
9496 (defun js2-parse-plain-property (prop)
9497 "Parse a non-getter/setter property in an object literal.
9498 PROP is the node representing the property: a number, name or string."
9499 (js2-must-match js2-COLON "msg.no.colon.prop")
9500 (let* ((pos (js2-node-pos prop))
9501 (colon (- (js2-current-token-beg) pos))
9502 (expr (js2-parse-assign-expr))
9503 (result (make-js2-object-prop-node
9504 :pos pos
9505 ;; don't include last consumed token in length
9506 :len (- (+ (js2-node-pos expr)
9507 (js2-node-len expr))
9508 pos)
9509 :left prop
9510 :right expr
9511 :op-pos colon)))
9512 (js2-node-add-children result prop expr)
9513 result))
9514
9515 (defun js2-parse-getter-setter-prop (pos prop get-p)
9516 "Parse getter or setter property in an object literal.
9517 JavaScript syntax is:
9518
9519 { get foo() {...}, set foo(x) {...} }
9520
9521 and expression closure style is also supported
9522
9523 { get foo() x, set foo(x) _x = x }
9524
9525 POS is the start position of the `get' or `set' keyword.
9526 PROP is the `js2-name-node' representing the property name.
9527 GET-P is non-nil if the keyword was `get'."
9528 (let ((type (if get-p js2-GET js2-SET))
9529 result end
9530 (fn (js2-parse-function-expr)))
9531 ;; it has to be an anonymous function, as we already parsed the name
9532 (if (/= (js2-node-type fn) js2-FUNCTION)
9533 (js2-report-error "msg.bad.prop")
9534 (if (plusp (length (js2-function-name fn)))
9535 (js2-report-error "msg.bad.prop")))
9536 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9537 (setq end (js2-node-end fn)
9538 result (make-js2-getter-setter-node :type type
9539 :pos pos
9540 :len (- end pos)
9541 :left prop
9542 :right fn))
9543 (js2-node-add-children result prop fn)
9544 result))
9545
9546 (defun js2-create-name-node (&optional check-activation-p token string)
9547 "Create a name node using the current token and, optionally, STRING.
9548 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
9549 (let* ((beg (js2-current-token-beg))
9550 (tt (js2-current-token-type))
9551 (s (or string
9552 (if (= js2-NAME tt)
9553 (js2-current-token-string)
9554 (js2-tt-name tt))))
9555 name)
9556 (setq name (make-js2-name-node :pos beg
9557 :name s
9558 :len (length s)))
9559 (if check-activation-p
9560 (js2-check-activation-name s (or token js2-NAME)))
9561 name))
9562
9563 ;;; Indentation support
9564
9565 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9566 ;; Karl cleverly deduces that the desired indentation level is often a
9567 ;; function of paren/bracket/brace nesting depth, which can be determined
9568 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9569 ;; then does some equally clever checks to see if we're in the context of a
9570 ;; substatement of a possibly braceless statement keyword such as if, while,
9571 ;; or finally. This approach yields pretty good results.
9572
9573 ;; The indenter is often "wrong", however, and needs to be overridden.
9574 ;; The right long-term solution is probably to emulate (or integrate
9575 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9576 ;; parse tree from `js2-parse' is present, which is not true at the
9577 ;; moment the user is typing, computing indentation is still thousands
9578 ;; of lines of code to handle every possible syntactic edge case.
9579
9580 ;; In the meantime, the compromise solution is that we offer a "bounce
9581 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9582 ;; current line indent among various likely guess points. This approach
9583 ;; is far from perfect, but should at least make it slightly easier to
9584 ;; move the line towards its desired indentation when manually
9585 ;; overriding Karl's heuristic nesting guesser.
9586
9587 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9588 ;; extensions such as `let' and Array comprehensions. Major kudos to
9589 ;; Karl for coming up with the initial approach, which packs a lot of
9590 ;; punch for so little code.
9591
9592 (defconst js2-possibly-braceless-keywords-re
9593 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9594 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9595 "try" "while" "with" "let")))
9596 "Regular expression matching keywords that are optionally
9597 followed by an opening brace.")
9598
9599 (defconst js2-indent-operator-re
9600 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9601 (regexp-opt '("in" "instanceof") 'words))
9602 "Regular expression matching operators that affect indentation
9603 of continued expressions.")
9604
9605 (defconst js2-declaration-keyword-re
9606 (regexp-opt '("var" "let" "const") 'words)
9607 "Regular expression matching variable declaration keywords.")
9608
9609 (defun js2-re-search-forward-inner (regexp &optional bound count)
9610 "Auxiliary function for `js2-re-search-forward'."
9611 (let (parse saved-point)
9612 (while (> count 0)
9613 (re-search-forward regexp bound)
9614 (setq parse (if saved-point
9615 (parse-partial-sexp saved-point (point))
9616 (syntax-ppss (point))))
9617 (cond ((nth 3 parse)
9618 (re-search-forward
9619 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
9620 (save-excursion (end-of-line) (point)) t))
9621 ((nth 7 parse)
9622 (forward-line))
9623 ((or (nth 4 parse)
9624 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9625 (re-search-forward "\\*/"))
9626 (t
9627 (setq count (1- count))))
9628 (setq saved-point (point))))
9629 (point))
9630
9631 (defun js2-re-search-forward (regexp &optional bound noerror count)
9632 "Search forward but ignore strings and comments.
9633 Invokes `re-search-forward' but treats the buffer as if strings
9634 and comments have been removed."
9635 (let ((saved-point (point)))
9636 (condition-case err
9637 (cond ((null count)
9638 (js2-re-search-forward-inner regexp bound 1))
9639 ((< count 0)
9640 (js2-re-search-backward-inner regexp bound (- count)))
9641 ((> count 0)
9642 (js2-re-search-forward-inner regexp bound count)))
9643 (search-failed
9644 (goto-char saved-point)
9645 (unless noerror
9646 (error (error-message-string err)))))))
9647
9648 (defun js2-re-search-backward-inner (regexp &optional bound count)
9649 "Auxiliary function for `js2-re-search-backward'."
9650 (let (parse)
9651 (while (> count 0)
9652 (re-search-backward regexp bound)
9653 (setq parse (syntax-ppss (point)))
9654 (cond ((nth 3 parse)
9655 (re-search-backward
9656 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9657 (line-beginning-position) t))
9658 ((nth 7 parse)
9659 (goto-char (nth 8 parse)))
9660 ((or (nth 4 parse)
9661 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9662 (re-search-backward "/\\*"))
9663 (t
9664 (setq count (1- count))))))
9665 (point))
9666
9667 (defun js2-re-search-backward (regexp &optional bound noerror count)
9668 "Search backward but ignore strings and comments.
9669 Invokes `re-search-backward' but treats the buffer as if strings
9670 and comments have been removed."
9671 (let ((saved-point (point)))
9672 (condition-case err
9673 (cond ((null count)
9674 (js2-re-search-backward-inner regexp bound 1))
9675 ((< count 0)
9676 (js2-re-search-forward-inner regexp bound (- count)))
9677 ((> count 0)
9678 (js2-re-search-backward-inner regexp bound count)))
9679 (search-failed
9680 (goto-char saved-point)
9681 (unless noerror
9682 (error (error-message-string err)))))))
9683
9684 (defun js2-looking-at-operator-p ()
9685 "Return non-nil if text after point is a non-comma operator."
9686 (and (looking-at js2-indent-operator-re)
9687 (or (not (looking-at ":"))
9688 (save-excursion
9689 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9690 (looking-at "?"))))))
9691
9692 (defun js2-continued-expression-p ()
9693 "Return non-nil if the current line continues an expression."
9694 (save-excursion
9695 (back-to-indentation)
9696 (or (js2-looking-at-operator-p)
9697 (when (catch 'found
9698 (while (and (re-search-backward "\n" nil t)
9699 (let ((state (syntax-ppss)))
9700 (when (nth 4 state)
9701 (goto-char (nth 8 state))) ;; skip comments
9702 (skip-chars-backward " \t")
9703 (if (bolp)
9704 t
9705 (throw 'found t))))))
9706 (backward-char)
9707 (when (js2-looking-at-operator-p)
9708 (backward-char)
9709 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))
9710
9711 (defun js2-end-of-do-while-loop-p ()
9712 "Return non-nil if word after point is `while' of a do-while
9713 statement, else returns nil. A braceless do-while statement
9714 spanning several lines requires that the start of the loop is
9715 indented to the same column as the current line."
9716 (interactive)
9717 (save-excursion
9718 (when (looking-at "\\s-*\\<while\\>")
9719 (if (save-excursion
9720 (skip-chars-backward "[ \t\n]*}")
9721 (looking-at "[ \t\n]*}"))
9722 (save-excursion
9723 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9724 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9725 (or (looking-at "\\<do\\>")
9726 (let ((saved-indent (current-indentation)))
9727 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9728 (/= (current-indentation) saved-indent)))
9729 (and (looking-at "[ \t]*\\<do\\>")
9730 (not (js2-re-search-forward
9731 "\\<while\\>" (point-at-eol) t))
9732 (= (current-indentation) saved-indent))))))))
9733
9734 (defun js2-multiline-decl-indentation ()
9735 "Return the declaration indentation column if the current line belongs
9736 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9737 (let (forward-sexp-function ; use Lisp version
9738 at-opening-bracket)
9739 (save-excursion
9740 (back-to-indentation)
9741 (when (not (looking-at js2-declaration-keyword-re))
9742 (when (looking-at js2-indent-operator-re)
9743 (goto-char (match-end 0))) ; continued expressions are ok
9744 (while (and (not at-opening-bracket)
9745 (not (bobp))
9746 (let ((pos (point)))
9747 (save-excursion
9748 (js2-backward-sws)
9749 (or (eq (char-before) ?,)
9750 (and (not (eq (char-before) ?\;))
9751 (prog2 (skip-syntax-backward ".")
9752 (looking-at js2-indent-operator-re)
9753 (js2-backward-sws))
9754 (not (eq (char-before) ?\;)))
9755 (js2-same-line pos)))))
9756 (condition-case _
9757 (backward-sexp)
9758 (scan-error (setq at-opening-bracket t))))
9759 (when (looking-at js2-declaration-keyword-re)
9760 (goto-char (match-end 0))
9761 (1+ (current-column)))))))
9762
9763 (defun js2-ctrl-statement-indentation ()
9764 "Return the proper indentation of current line if it is a control statement.
9765 Returns an indentation if this line starts the body of a control
9766 statement without braces, else returns nil."
9767 (let (forward-sexp-function)
9768 (save-excursion
9769 (back-to-indentation)
9770 (when (and (not (js2-same-line (point-min)))
9771 (not (looking-at "{"))
9772 (js2-re-search-backward "[[:graph:]]" nil t)
9773 (not (looking-at "[{([]"))
9774 (progn
9775 (forward-char)
9776 (when (= (char-before) ?\))
9777 ;; scan-sexps sometimes throws an error
9778 (ignore-errors (backward-sexp))
9779 (skip-chars-backward " \t" (point-at-bol)))
9780 (let ((pt (point)))
9781 (back-to-indentation)
9782 (when (looking-at "}[ \t]*")
9783 (goto-char (match-end 0)))
9784 (and (looking-at js2-possibly-braceless-keywords-re)
9785 (= (match-end 0) pt)
9786 (not (js2-end-of-do-while-loop-p))))))
9787 (+ (current-indentation) js2-basic-offset)))))
9788
9789 (defun js2-indent-in-array-comp (parse-status)
9790 "Return non-nil if we think we're in an array comprehension.
9791 In particular, return the buffer position of the first `for' kwd."
9792 (let ((bracket (nth 1 parse-status))
9793 (end (point)))
9794 (when bracket
9795 (save-excursion
9796 (goto-char bracket)
9797 (when (looking-at "\\[")
9798 (forward-char 1)
9799 (js2-forward-sws)
9800 (if (looking-at "[[{]")
9801 (let (forward-sexp-function) ; use Lisp version
9802 (forward-sexp) ; skip destructuring form
9803 (js2-forward-sws)
9804 (if (and (/= (char-after) ?,) ; regular array
9805 (looking-at "for"))
9806 (match-beginning 0)))
9807 ;; to skip arbitrary expressions we need the parser,
9808 ;; so we'll just guess at it.
9809 (if (and (> end (point)) ; not empty literal
9810 (re-search-forward "[^,]]* \\(for\\) " end t)
9811 ;; not inside comment or string literal
9812 (let ((state (parse-partial-sexp bracket (point))))
9813 (not (or (nth 3 state) (nth 4 state)))))
9814 (match-beginning 1))))))))
9815
9816 (defun js2-array-comp-indentation (parse-status for-kwd)
9817 (if (js2-same-line for-kwd)
9818 ;; first continuation line
9819 (save-excursion
9820 (goto-char (nth 1 parse-status))
9821 (forward-char 1)
9822 (skip-chars-forward " \t")
9823 (current-column))
9824 (save-excursion
9825 (goto-char for-kwd)
9826 (current-column))))
9827
9828 (defun js2-proper-indentation (parse-status)
9829 "Return the proper indentation for the current line."
9830 (save-excursion
9831 (back-to-indentation)
9832 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9833 (at-closing-bracket (looking-at "[]})]"))
9834 (same-indent-p (or at-closing-bracket
9835 (looking-at "\\<case\\>[^:]")
9836 (and (looking-at "\\<default:")
9837 (save-excursion
9838 (js2-backward-sws)
9839 (not (memq (char-before) '(?, ?{)))))))
9840 (continued-expr-p (js2-continued-expression-p))
9841 (declaration-indent (and js2-pretty-multiline-declarations
9842 (js2-multiline-decl-indentation)))
9843 (bracket (nth 1 parse-status))
9844 beg indent)
9845 (cond
9846 ;; indent array comprehension continuation lines specially
9847 ((and bracket
9848 (>= js2-language-version 170)
9849 (not (js2-same-line bracket))
9850 (setq beg (js2-indent-in-array-comp parse-status))
9851 (>= (point) (save-excursion
9852 (goto-char beg)
9853 (point-at-bol)))) ; at or after first loop?
9854 (js2-array-comp-indentation parse-status beg))
9855
9856 (ctrl-stmt-indent)
9857
9858 ((and declaration-indent continued-expr-p)
9859 (+ declaration-indent js2-basic-offset))
9860
9861 (declaration-indent)
9862
9863 (bracket
9864 (goto-char bracket)
9865 (cond
9866 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9867 (when (save-excursion (skip-chars-backward " \t)")
9868 (looking-at ")"))
9869 (backward-list))
9870 (back-to-indentation)
9871 (and (eq js2-pretty-multiline-declarations 'all)
9872 (looking-at js2-declaration-keyword-re)
9873 (goto-char (1+ (match-end 0))))
9874 (setq indent
9875 (cond (same-indent-p
9876 (current-column))
9877 (continued-expr-p
9878 (+ (current-column) (* 2 js2-basic-offset)))
9879 (t
9880 (+ (current-column) js2-basic-offset))))
9881 (if (and js2-indent-switch-body
9882 (not at-closing-bracket)
9883 (looking-at "\\_<switch\\_>"))
9884 (+ indent js2-basic-offset)
9885 indent))
9886 (t
9887 (unless same-indent-p
9888 (forward-char)
9889 (skip-chars-forward " \t"))
9890 (current-column))))
9891
9892 (continued-expr-p js2-basic-offset)
9893
9894 (t 0)))))
9895
9896 (defun js2-lineup-comment (parse-status)
9897 "Indent a multi-line block comment continuation line."
9898 (let* ((beg (nth 8 parse-status))
9899 (first-line (js2-same-line beg))
9900 (offset (save-excursion
9901 (goto-char beg)
9902 (if (looking-at "/\\*")
9903 (+ 1 (current-column))
9904 0))))
9905 (unless first-line
9906 (indent-line-to offset))))
9907
9908 (defun js2-backward-sws ()
9909 "Move backward through whitespace and comments."
9910 (interactive)
9911 (while (forward-comment -1)))
9912
9913 (defun js2-forward-sws ()
9914 "Move forward through whitespace and comments."
9915 (interactive)
9916 (while (forward-comment 1)))
9917
9918 (defun js2-current-indent (&optional pos)
9919 "Return column of indentation on current line.
9920 If POS is non-nil, go to that point and return indentation for that line."
9921 (save-excursion
9922 (if pos
9923 (goto-char pos))
9924 (back-to-indentation)
9925 (current-column)))
9926
9927 (defun js2-arglist-close ()
9928 "Return non-nil if we're on a line beginning with a close-paren/brace."
9929 (save-excursion
9930 (goto-char (point-at-bol))
9931 (js2-forward-sws)
9932 (looking-at "[])}]")))
9933
9934 (defun js2-indent-looks-like-label-p ()
9935 (goto-char (point-at-bol))
9936 (js2-forward-sws)
9937 (looking-at (concat js2-mode-identifier-re ":")))
9938
9939 (defun js2-indent-in-objlit-p (parse-status)
9940 "Return non-nil if this looks like an object-literal entry."
9941 (let ((start (nth 1 parse-status)))
9942 (and
9943 start
9944 (save-excursion
9945 (and (zerop (forward-line -1))
9946 (not (< (point) start)) ; crossed a {} boundary
9947 (js2-indent-looks-like-label-p)))
9948 (save-excursion
9949 (js2-indent-looks-like-label-p)))))
9950
9951 ;; If prev line looks like foobar({ then we're passing an object
9952 ;; literal to a function call, and people pretty much always want to
9953 ;; de-dent back to the previous line, so move the 'basic-offset'
9954 ;; position to the front.
9955 (defun js2-indent-objlit-arg-p (parse-status)
9956 (save-excursion
9957 (back-to-indentation)
9958 (js2-backward-sws)
9959 (and (eq (1- (point)) (nth 1 parse-status))
9960 (eq (char-before) ?{)
9961 (progn
9962 (forward-char -1)
9963 (skip-chars-backward " \t")
9964 (eq (char-before) ?\()))))
9965
9966 (defun js2-indent-case-block-p ()
9967 (save-excursion
9968 (back-to-indentation)
9969 (js2-backward-sws)
9970 (goto-char (point-at-bol))
9971 (skip-chars-forward " \t")
9972 (looking-at "case\\s-.+:")))
9973
9974 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
9975 "Cycle among alternate computed indentation positions.
9976 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9977 of the buffer to the current point. NORMAL-COL is the indentation
9978 column computed by the heuristic guesser based on current paren,
9979 bracket, brace and statement nesting. If BACKWARDS, cycle positions
9980 in reverse."
9981 (let ((cur-indent (js2-current-indent))
9982 (old-buffer-undo-list buffer-undo-list)
9983 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9984 (current-line (save-excursion
9985 (forward-line 0) ; move to bol
9986 (1+ (count-lines (point-min) (point)))))
9987 positions pos main-pos anchor arglist-cont same-indent
9988 basic-offset computed-pos)
9989 ;; temporarily don't record undo info, if user requested this
9990 (when js2-mode-indent-inhibit-undo
9991 (setq buffer-undo-list t))
9992 (unwind-protect
9993 (progn
9994 ;; First likely point: indent from beginning of previous code line
9995 (push (setq basic-offset
9996 (+ (save-excursion
9997 (back-to-indentation)
9998 (js2-backward-sws)
9999 (back-to-indentation)
10000 (current-column))
10001 js2-basic-offset))
10002 positions)
10003
10004 ;; (First + epsilon) likely point: indent 2x from beginning of
10005 ;; previous code line. Google does it this way.
10006 (push (setq basic-offset
10007 (+ (save-excursion
10008 (back-to-indentation)
10009 (js2-backward-sws)
10010 (back-to-indentation)
10011 (current-column))
10012 (* 2 js2-basic-offset)))
10013 positions)
10014
10015 ;; Second likely point: indent from assign-expr RHS. This
10016 ;; is just a crude guess based on finding " = " on the previous
10017 ;; line containing actual code.
10018 (setq pos (save-excursion
10019 (forward-line -1)
10020 (goto-char (point-at-bol))
10021 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10022 (point-at-eol) t)
10023 (goto-char (match-end 1))
10024 (skip-chars-forward " \t\r\n")
10025 (current-column))))
10026 (when pos
10027 (incf pos js2-basic-offset)
10028 (push pos positions))
10029
10030 ;; Third likely point: same indent as previous line of code.
10031 ;; Make it the first likely point if we're not on an
10032 ;; arglist-close line and previous line ends in a comma, or
10033 ;; both this line and prev line look like object-literal
10034 ;; elements.
10035 (setq pos (save-excursion
10036 (goto-char (point-at-bol))
10037 (js2-backward-sws)
10038 (back-to-indentation)
10039 (prog1
10040 (current-column)
10041 ;; while we're here, look for trailing comma
10042 (if (save-excursion
10043 (goto-char (point-at-eol))
10044 (js2-backward-sws)
10045 (eq (char-before) ?,))
10046 (setq arglist-cont (1- (point)))))))
10047 (when pos
10048 (if (and (or arglist-cont
10049 (js2-indent-in-objlit-p parse-status))
10050 (not (js2-arglist-close)))
10051 (setq same-indent pos))
10052 (push pos positions))
10053
10054 ;; Fourth likely point: first preceding code with less indentation.
10055 ;; than the immediately preceding code line.
10056 (setq pos (save-excursion
10057 (back-to-indentation)
10058 (js2-backward-sws)
10059 (back-to-indentation)
10060 (setq anchor (current-column))
10061 (while (and (zerop (forward-line -1))
10062 (>= (progn
10063 (back-to-indentation)
10064 (current-column))
10065 anchor)))
10066 (setq pos (current-column))))
10067 (push pos positions)
10068
10069 ;; nesting-heuristic position, main by default
10070 (push (setq main-pos normal-col) positions)
10071
10072 ;; delete duplicates and sort positions list
10073 (setq positions (sort (delete-dups positions) '<))
10074
10075 ;; comma-list continuation lines: prev line indent takes precedence
10076 (if same-indent
10077 (setq main-pos same-indent))
10078
10079 ;; common special cases where we want to indent in from previous line
10080 (if (or (js2-indent-case-block-p)
10081 (js2-indent-objlit-arg-p parse-status))
10082 (setq main-pos basic-offset))
10083
10084 ;; if bouncing backwards, reverse positions list
10085 (if backwards
10086 (setq positions (reverse positions)))
10087
10088 ;; record whether we're already sitting on one of the alternatives
10089 (setq pos (member cur-indent positions))
10090
10091 (cond
10092 ;; case 0: we're one one of the alternatives and this is the
10093 ;; first time they've pressed TAB on this line (best-guess).
10094 ((and js2-mode-indent-ignore-first-tab
10095 pos
10096 ;; first time pressing TAB on this line?
10097 (not (eq js2-mode-last-indented-line current-line)))
10098 ;; do nothing
10099 (setq computed-pos nil))
10100 ;; case 1: only one computed position => use it
10101 ((null (cdr positions))
10102 (setq computed-pos 0))
10103 ;; case 2: not on any of the computed spots => use main spot
10104 ((not pos)
10105 (setq computed-pos (js2-position main-pos positions)))
10106 ;; case 3: on last position: cycle to first position
10107 ((null (cdr pos))
10108 (setq computed-pos 0))
10109 ;; case 4: on intermediate position: cycle to next position
10110 (t
10111 (setq computed-pos (js2-position (second pos) positions))))
10112
10113 ;; see if any hooks want to indent; otherwise we do it
10114 (loop with result = nil
10115 for hook in js2-indent-hook
10116 while (null result)
10117 do
10118 (setq result (funcall hook positions computed-pos))
10119 finally do
10120 (unless (or result (null computed-pos))
10121 (indent-line-to (nth computed-pos positions)))))
10122
10123 ;; finally
10124 (if js2-mode-indent-inhibit-undo
10125 (setq buffer-undo-list old-buffer-undo-list))
10126 ;; see commentary for `js2-mode-last-indented-line'
10127 (setq js2-mode-last-indented-line current-line))))
10128
10129 (defun js2-indent-bounce-backwards ()
10130 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10131 cycles between the computed indentation positions in reverse order."
10132 (interactive)
10133 (js2-indent-line t))
10134
10135 (defun js2-1-line-comment-continuation-p ()
10136 "Return t if we're in a 1-line comment continuation.
10137 If so, we don't ever want to use bounce-indent."
10138 (save-excursion
10139 (and (progn
10140 (forward-line 0)
10141 (looking-at "\\s-*//"))
10142 (progn
10143 (forward-line -1)
10144 (forward-line 0)
10145 (when (looking-at "\\s-*$")
10146 (js2-backward-sws)
10147 (forward-line 0))
10148 (looking-at "\\s-*//")))))
10149
10150 (defun js2-indent-line (&optional bounce-backwards)
10151 "Indent the current line as JavaScript source text."
10152 (interactive)
10153 (let (parse-status offset indent-col
10154 ;; Don't whine about errors/warnings when we're indenting.
10155 ;; This has to be set before calling parse-partial-sexp below.
10156 (inhibit-point-motion-hooks t))
10157 (setq parse-status (save-excursion
10158 (syntax-ppss (point-at-bol)))
10159 offset (- (point) (save-excursion
10160 (back-to-indentation)
10161 (point))))
10162 (js2-with-underscore-as-word-syntax
10163 (if (nth 4 parse-status)
10164 (js2-lineup-comment parse-status)
10165 (setq indent-col (js2-proper-indentation parse-status))
10166 ;; See comments below about `js2-mode-last-indented-line'.
10167 (cond
10168 ;; bounce-indenting is disabled during electric-key indent.
10169 ;; It doesn't work well on first line of buffer.
10170 ((and js2-bounce-indent-p
10171 (not (js2-same-line (point-min)))
10172 (not (js2-1-line-comment-continuation-p)))
10173 (js2-bounce-indent indent-col parse-status bounce-backwards))
10174 ;; just indent to the guesser's likely spot
10175 (t (indent-line-to indent-col))))
10176 (when (plusp offset)
10177 (forward-char offset)))))
10178
10179 (defun js2-indent-region (start end)
10180 "Indent the region, but don't use bounce indenting."
10181 (let ((js2-bounce-indent-p nil)
10182 (indent-region-function nil)
10183 (after-change-functions (remq 'js2-mode-edit
10184 after-change-functions)))
10185 (indent-region start end nil) ; nil for byte-compiler
10186 (js2-mode-edit start end (- end start))))
10187
10188 (defvar js2-minor-mode-map
10189 (let ((map (make-sparse-keymap)))
10190 (define-key map (kbd "C-c C-`") #'js2-next-error)
10191 (define-key map [mouse-1] #'js2-mode-show-node)
10192 map)
10193 "Keymap used when `js2-minor-mode' is active.")
10194
10195 ;;;###autoload
10196 (define-minor-mode js2-minor-mode
10197 "Minor mode for running js2 as a background linter.
10198 This allows you to use a different major mode for JavaScript editing,
10199 such as `espresso-mode', while retaining the asynchronous error/warning
10200 highlighting features of `js2-mode'."
10201 :group 'js2-mode
10202 :lighter " js-lint"
10203 (if js2-minor-mode
10204 (js2-minor-mode-enter)
10205 (js2-minor-mode-exit)))
10206
10207 (defun js2-minor-mode-enter ()
10208 "Initialization for `js2-minor-mode'."
10209 (set (make-local-variable 'max-lisp-eval-depth)
10210 (max max-lisp-eval-depth 3000))
10211 (setq next-error-function #'js2-next-error)
10212 (js2-set-default-externs)
10213 ;; Experiment: make reparse-delay longer for longer files.
10214 (if (plusp js2-dynamic-idle-timer-adjust)
10215 (setq js2-idle-timer-delay
10216 (* js2-idle-timer-delay
10217 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10218 (setq js2-mode-buffer-dirty-p t
10219 js2-mode-parsing nil)
10220 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10221 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10222 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10223 (when js2-include-jslint-globals
10224 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10225 (run-hooks 'js2-init-hook)
10226 (js2-reparse))
10227
10228 (defun js2-minor-mode-exit ()
10229 "Turn off `js2-minor-mode'."
10230 (setq next-error-function nil)
10231 (remove-hook 'after-change-functions #'js2-mode-edit t)
10232 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10233 (when js2-mode-node-overlay
10234 (delete-overlay js2-mode-node-overlay)
10235 (setq js2-mode-node-overlay nil))
10236 (js2-remove-overlays)
10237 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
10238 (setq js2-mode-ast nil))
10239
10240 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10241 (make-variable-buffer-local 'js2-source-buffer)
10242
10243 (defun* js2-display-error-list ()
10244 "Display a navigable buffer listing parse errors/warnings."
10245 (interactive)
10246 (unless (js2-have-errors-p)
10247 (message "No errors")
10248 (return-from js2-display-error-list))
10249 (labels ((annotate-list
10250 (lst type)
10251 "Add diagnostic TYPE and line number to errs list"
10252 (mapcar (lambda (err)
10253 (list err type (line-number-at-pos (nth 1 err))))
10254 lst)))
10255 (let* ((srcbuf (current-buffer))
10256 (errbuf (get-buffer-create "*js-lint*"))
10257 (errors (annotate-list
10258 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10259 'js2-error)) ; must be a valid face name
10260 (warnings (annotate-list
10261 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10262 'js2-warning)) ; must be a valid face name
10263 (all-errs (sort (append errors warnings)
10264 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10265 (with-current-buffer errbuf
10266 (let ((inhibit-read-only t))
10267 (erase-buffer)
10268 (dolist (err all-errs)
10269 (destructuring-bind ((msg-key beg _end &rest) type line) err
10270 (insert-text-button
10271 (format "line %d: %s" line (js2-get-msg msg-key))
10272 'face type
10273 'follow-link "\C-m"
10274 'action 'js2-error-buffer-jump
10275 'js2-msg (js2-get-msg msg-key)
10276 'js2-pos beg)
10277 (insert "\n"))))
10278 (js2-error-buffer-mode)
10279 (setq js2-source-buffer srcbuf)
10280 (pop-to-buffer errbuf)
10281 (goto-char (point-min))
10282 (unless (eobp)
10283 (js2-error-buffer-view))))))
10284
10285 (defvar js2-error-buffer-mode-map
10286 (let ((map (make-sparse-keymap)))
10287 (define-key map "n" #'js2-error-buffer-next)
10288 (define-key map "p" #'js2-error-buffer-prev)
10289 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10290 (define-key map "o" #'js2-error-buffer-view)
10291 (define-key map "q" #'js2-error-buffer-quit)
10292 map)
10293 "Keymap used for js2 diagnostics buffers.")
10294
10295 (defun js2-error-buffer-mode ()
10296 "Major mode for js2 diagnostics buffers.
10297 Selecting an error will jump it to the corresponding source-buffer error.
10298 \\{js2-error-buffer-mode-map}"
10299 (interactive)
10300 (setq major-mode 'js2-error-buffer-mode
10301 mode-name "JS Lint Diagnostics")
10302 (use-local-map js2-error-buffer-mode-map)
10303 (setq truncate-lines t)
10304 (set-buffer-modified-p nil)
10305 (setq buffer-read-only t)
10306 (run-hooks 'js2-error-buffer-mode-hook))
10307
10308 (defun js2-error-buffer-next ()
10309 "Move to next error and view it."
10310 (interactive)
10311 (when (zerop (forward-line 1))
10312 (js2-error-buffer-view)))
10313
10314 (defun js2-error-buffer-prev ()
10315 "Move to previous error and view it."
10316 (interactive)
10317 (when (zerop (forward-line -1))
10318 (js2-error-buffer-view)))
10319
10320 (defun js2-error-buffer-quit ()
10321 "Kill the current buffer."
10322 (interactive)
10323 (kill-buffer))
10324
10325 (defun js2-error-buffer-jump (&rest ignored)
10326 "Jump cursor to current error in source buffer."
10327 (interactive)
10328 (when (js2-error-buffer-view)
10329 (pop-to-buffer js2-source-buffer)))
10330
10331 (defun js2-error-buffer-view ()
10332 "Scroll source buffer to show error at current line."
10333 (interactive)
10334 (cond
10335 ((not (eq major-mode 'js2-error-buffer-mode))
10336 (message "Not in a js2 errors buffer"))
10337 ((not (buffer-live-p js2-source-buffer))
10338 (message "Source buffer has been killed"))
10339 ((not (wholenump (get-text-property (point) 'js2-pos)))
10340 (message "There does not seem to be an error here"))
10341 (t
10342 (let ((pos (get-text-property (point) 'js2-pos))
10343 (msg (get-text-property (point) 'js2-msg)))
10344 (save-selected-window
10345 (pop-to-buffer js2-source-buffer)
10346 (goto-char pos)
10347 (message msg))))))
10348
10349 ;;;###autoload
10350 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10351 ;; FIXME: Should derive from js-mode.
10352 "Major mode for editing JavaScript code."
10353 ;; Used by comment-region; don't change it.
10354 (set (make-local-variable 'comment-start) "//")
10355 (set (make-local-variable 'comment-end) "")
10356 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
10357 (set (make-local-variable 'max-lisp-eval-depth)
10358 (max max-lisp-eval-depth 3000))
10359 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10360 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10361 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10362 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10363 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10364 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10365 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10366 ;; for characters inside regexp literals.
10367 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10368 ;; this is necessary to make `show-paren-function' work properly
10369 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10370 ;; needed for M-x rgrep, among other things
10371 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10372
10373 (set (make-local-variable 'electric-indent-chars)
10374 (append '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
10375 electric-indent-chars))
10376 (set (make-local-variable 'electric-layout-rules)
10377 '((?\; . after) (?\{ . after) (?\} . before)))
10378
10379 ;; some variables needed by cc-engine for paragraph-fill, etc.
10380 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10381 c-comment-start-regexp "/[*/]\\|\\s|"
10382 c-line-comment-starter "//"
10383 c-paragraph-start js2-paragraph-start
10384 c-paragraph-separate "$"
10385 c-syntactic-ws-start js2-syntactic-ws-start
10386 c-syntactic-ws-end js2-syntactic-ws-end
10387 c-syntactic-eol js2-syntactic-eol)
10388
10389 (let ((c-buffer-is-cc-mode t))
10390 ;; Copied from `js-mode'. Also see Bug#6071.
10391 (make-local-variable 'paragraph-start)
10392 (make-local-variable 'paragraph-separate)
10393 (make-local-variable 'paragraph-ignore-fill-prefix)
10394 (make-local-variable 'adaptive-fill-mode)
10395 (make-local-variable 'adaptive-fill-regexp)
10396 (c-setup-paragraph-variables))
10397
10398 (setq font-lock-defaults '(nil t))
10399
10400 ;; Experiment: make reparse-delay longer for longer files.
10401 (when (plusp js2-dynamic-idle-timer-adjust)
10402 (setq js2-idle-timer-delay
10403 (* js2-idle-timer-delay
10404 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10405
10406 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10407 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10408 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10409 (setq next-error-function #'js2-next-error)
10410 (imenu-add-to-menubar (concat "IM-" mode-name))
10411 (add-to-invisibility-spec '(js2-outline . t))
10412 (set (make-local-variable 'line-move-ignore-invisible) t)
10413 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10414
10415 (setq js2-mode-functions-hidden nil
10416 js2-mode-comments-hidden nil
10417 js2-mode-buffer-dirty-p t
10418 js2-mode-parsing nil)
10419
10420 (js2-set-default-externs)
10421
10422 (when js2-include-jslint-globals
10423 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10424
10425 (run-hooks 'js2-init-hook)
10426
10427 (js2-reparse))
10428
10429 (defun js2-mode-exit ()
10430 "Exit `js2-mode' and clean up."
10431 (interactive)
10432 (when js2-mode-node-overlay
10433 (delete-overlay js2-mode-node-overlay)
10434 (setq js2-mode-node-overlay nil))
10435 (js2-remove-overlays)
10436 (setq js2-mode-ast nil)
10437 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10438 (remove-from-invisibility-spec '(js2-outline . t))
10439 (js2-mode-show-all)
10440 (with-silent-modifications
10441 (js2-clear-face (point-min) (point-max))))
10442
10443 (defun js2-mode-reset-timer ()
10444 "Cancel any existing parse timer and schedule a new one."
10445 (if js2-mode-parse-timer
10446 (cancel-timer js2-mode-parse-timer))
10447 (setq js2-mode-parsing nil)
10448 (let ((timer (timer-create)))
10449 (setq js2-mode-parse-timer timer)
10450 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10451 (timer-set-idle-time timer js2-idle-timer-delay)
10452 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10453 (timer-activate-when-idle timer nil)))
10454
10455 (defun js2-mode-idle-reparse (buffer)
10456 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10457 it to be reparsed when the buffer is selected."
10458 (if (eq buffer (current-buffer))
10459 (js2-reparse)
10460 ;; reparse when the buffer is selected again
10461 (with-current-buffer buffer
10462 (add-hook 'window-configuration-change-hook
10463 #'js2-mode-idle-reparse-inner
10464 nil t))))
10465
10466 (defun js2-mode-idle-reparse-inner ()
10467 (remove-hook 'window-configuration-change-hook
10468 #'js2-mode-idle-reparse-inner
10469 t)
10470 (js2-reparse))
10471
10472 (defun js2-mode-edit (_beg _end _len)
10473 "Schedule a new parse after buffer is edited.
10474 Buffer edit spans from BEG to END and is of length LEN."
10475 (setq js2-mode-buffer-dirty-p t)
10476 (js2-mode-hide-overlay)
10477 (js2-mode-reset-timer))
10478
10479 (defun js2-minor-mode-edit (_beg _end _len)
10480 "Callback for buffer edits in `js2-mode'.
10481 Schedules a new parse after buffer is edited.
10482 Buffer edit spans from BEG to END and is of length LEN."
10483 (setq js2-mode-buffer-dirty-p t)
10484 (js2-mode-hide-overlay)
10485 (js2-mode-reset-timer))
10486
10487 (defun js2-reparse (&optional force)
10488 "Re-parse current buffer after user finishes some data entry.
10489 If we get any user input while parsing, including cursor motion,
10490 we discard the parse and reschedule it. If FORCE is nil, then the
10491 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10492 (let (time
10493 interrupted-p
10494 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10495 (unless js2-mode-parsing
10496 (setq js2-mode-parsing t)
10497 (unwind-protect
10498 (when (or js2-mode-buffer-dirty-p force)
10499 (js2-remove-overlays)
10500 (with-silent-modifications
10501 (setq js2-mode-buffer-dirty-p nil
10502 js2-mode-fontifications nil
10503 js2-mode-deferred-properties nil)
10504 (if js2-mode-verbose-parse-p
10505 (message "parsing..."))
10506 (setq time
10507 (js2-time
10508 (setq interrupted-p
10509 (catch 'interrupted
10510 (js2-parse)
10511 ;; if parsing is interrupted, comments and regex
10512 ;; literals stay ignored by `parse-partial-sexp'
10513 (remove-text-properties (point-min) (point-max)
10514 '(syntax-table))
10515 (js2-mode-apply-deferred-properties)
10516 (js2-mode-remove-suppressed-warnings)
10517 (js2-mode-show-warnings)
10518 (js2-mode-show-errors)
10519 (if (>= js2-highlight-level 1)
10520 (js2-highlight-jsdoc js2-mode-ast))
10521 nil))))
10522 (if interrupted-p
10523 (progn
10524 ;; unfinished parse => try again
10525 (setq js2-mode-buffer-dirty-p t)
10526 (js2-mode-reset-timer))
10527 (if js2-mode-verbose-parse-p
10528 (message "Parse time: %s" time)))))
10529 (setq js2-mode-parsing nil)
10530 (unless interrupted-p
10531 (setq js2-mode-parse-timer nil))))))
10532
10533 (defun js2-mode-show-node (event)
10534 "Debugging aid: highlight selected AST node on mouse click."
10535 (interactive "e")
10536 (mouse-set-point event)
10537 (setq deactivate-mark t)
10538 (when js2-mode-show-overlay
10539 (let ((node (js2-node-at-point))
10540 beg end)
10541 (if (null node)
10542 (message "No node found at location %s" (point))
10543 (setq beg (js2-node-abs-pos node)
10544 end (+ beg (js2-node-len node)))
10545 (if js2-mode-node-overlay
10546 (move-overlay js2-mode-node-overlay beg end)
10547 (setq js2-mode-node-overlay (make-overlay beg end))
10548 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10549 (with-silent-modifications
10550 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10551 (message "%s, parent: %s"
10552 (js2-node-short-name node)
10553 (if (js2-node-parent node)
10554 (js2-node-short-name (js2-node-parent node))
10555 "nil"))))))
10556
10557 (defun js2-mode-hide-overlay (&optional _p1 p2)
10558 "Remove the debugging overlay when the point moves.
10559 P1 and P2 are the old and new values of point, respectively."
10560 (when js2-mode-node-overlay
10561 (let ((beg (overlay-start js2-mode-node-overlay))
10562 (end (overlay-end js2-mode-node-overlay)))
10563 ;; Sometimes we're called spuriously.
10564 (unless (and p2
10565 (>= p2 beg)
10566 (<= p2 end))
10567 (with-silent-modifications
10568 (remove-text-properties beg end '(point-left nil)))
10569 (delete-overlay js2-mode-node-overlay)
10570 (setq js2-mode-node-overlay nil)))))
10571
10572 (defun js2-mode-reset ()
10573 "Debugging helper: reset everything."
10574 (interactive)
10575 (js2-mode-exit)
10576 (js2-mode))
10577
10578 (defun js2-mode-show-warn-or-err (e face)
10579 "Highlight a warning or error E with FACE.
10580 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10581 The last element is optional. When present, use instead of FACE."
10582 (let* ((key (first e))
10583 (beg (second e))
10584 (end (+ beg (third e)))
10585 ;; Don't inadvertently go out of bounds.
10586 (beg (max (point-min) (min beg (point-max))))
10587 (end (max (point-min) (min end (point-max))))
10588 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10589 (ovl (make-overlay beg end)))
10590 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10591 (overlay-put ovl 'js2-error t)
10592 (put-text-property beg end 'help-echo (js2-get-msg key))
10593 (put-text-property beg end 'point-entered #'js2-echo-error)))
10594
10595 (defun js2-remove-overlays ()
10596 "Remove overlays from buffer that have a `js2-error' property."
10597 (let ((beg (point-min))
10598 (end (point-max)))
10599 (save-excursion
10600 (dolist (o (overlays-in beg end))
10601 (when (overlay-get o 'js2-error)
10602 (delete-overlay o))))))
10603
10604 (defun js2-error-at-point (&optional pos)
10605 "Return non-nil if there's an error overlay at POS.
10606 Defaults to point."
10607 (loop with pos = (or pos (point))
10608 for o in (overlays-at pos)
10609 thereis (overlay-get o 'js2-error)))
10610
10611 (defun js2-mode-apply-deferred-properties ()
10612 "Apply fontifications and other text properties recorded during parsing."
10613 (when (plusp js2-highlight-level)
10614 ;; We defer clearing faces as long as possible to eliminate flashing.
10615 (js2-clear-face (point-min) (point-max))
10616 ;; Have to reverse the recorded fontifications list so that errors
10617 ;; and warnings overwrite the normal fontifications.
10618 (dolist (f (nreverse js2-mode-fontifications))
10619 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10620 (setq js2-mode-fontifications nil))
10621 (dolist (p js2-mode-deferred-properties)
10622 (apply #'put-text-property p))
10623 (setq js2-mode-deferred-properties nil))
10624
10625 (defun js2-mode-show-errors ()
10626 "Highlight syntax errors."
10627 (when js2-mode-show-parse-errors
10628 (dolist (e (js2-ast-root-errors js2-mode-ast))
10629 (js2-mode-show-warn-or-err e 'js2-error))))
10630
10631 (defun js2-mode-remove-suppressed-warnings ()
10632 "Take suppressed warnings out of the AST warnings list.
10633 This ensures that the counts and `next-error' are correct."
10634 (setf (js2-ast-root-warnings js2-mode-ast)
10635 (js2-delete-if
10636 (lambda (e)
10637 (let ((key (caar e)))
10638 (or
10639 (and (not js2-strict-trailing-comma-warning)
10640 (string-match "trailing\\.comma" key))
10641 (and (not js2-strict-cond-assign-warning)
10642 (string= key "msg.equal.as.assign"))
10643 (and js2-missing-semi-one-line-override
10644 (string= key "msg.missing.semi")
10645 (let* ((beg (second e))
10646 (node (js2-node-at-point beg))
10647 (fn (js2-mode-find-parent-fn node))
10648 (body (and fn (js2-function-node-body fn)))
10649 (lc (and body (js2-node-abs-pos body)))
10650 (rc (and lc (+ lc (js2-node-len body)))))
10651 (and fn
10652 (or (null body)
10653 (save-excursion
10654 (goto-char beg)
10655 (and (js2-same-line lc)
10656 (js2-same-line rc))))))))))
10657 (js2-ast-root-warnings js2-mode-ast))))
10658
10659 (defun js2-mode-show-warnings ()
10660 "Highlight strict-mode warnings."
10661 (when js2-mode-show-strict-warnings
10662 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10663 (js2-mode-show-warn-or-err e 'js2-warning))))
10664
10665 (defun js2-echo-error (_old-point new-point)
10666 "Called by point-motion hooks."
10667 (let ((msg (get-text-property new-point 'help-echo)))
10668 (when (and (stringp msg)
10669 (not (active-minibuffer-window))
10670 (not (current-message)))
10671 (message msg))))
10672
10673 (defalias 'js2-echo-help #'js2-echo-error)
10674
10675 (defun js2-line-break (&optional _soft)
10676 "Break line at point and indent, continuing comment if within one.
10677 If inside a string, and `js2-concat-multiline-strings' is not
10678 nil, turn it into concatenation."
10679 (interactive)
10680 (let ((parse-status (syntax-ppss)))
10681 (cond
10682 ;; Check if we're inside a string.
10683 ((nth 3 parse-status)
10684 (if js2-concat-multiline-strings
10685 (js2-mode-split-string parse-status)
10686 (insert "\n")))
10687 ;; Check if inside a block comment.
10688 ((nth 4 parse-status)
10689 (js2-mode-extend-comment (nth 8 parse-status)))
10690 (t
10691 (newline-and-indent)))))
10692
10693 (defun js2-mode-split-string (parse-status)
10694 "Turn a newline in mid-string into a string concatenation.
10695 PARSE-STATUS is as documented in `parse-partial-sexp'."
10696 (let* ((quote-char (nth 3 parse-status))
10697 (at-eol (eq js2-concat-multiline-strings 'eol)))
10698 (insert quote-char)
10699 (insert (if at-eol " +\n" "\n"))
10700 (unless at-eol
10701 (insert "+ "))
10702 (js2-indent-line)
10703 (insert quote-char)
10704 (when (eolp)
10705 (insert quote-char)
10706 (backward-char 1))))
10707
10708 (defun js2-mode-extend-comment (start-pos)
10709 "Indent the line and, when inside a comment block, add comment prefix."
10710 (let (star single col first-line needs-close)
10711 (save-excursion
10712 (back-to-indentation)
10713 (when (< (point) start-pos)
10714 (goto-char start-pos))
10715 (cond
10716 ((looking-at "\\*[^/]")
10717 (setq star t
10718 col (current-column)))
10719 ((looking-at "/\\*")
10720 (setq star t
10721 first-line t
10722 col (1+ (current-column))))
10723 ((looking-at "//")
10724 (setq single t
10725 col (current-column)))))
10726 ;; Heuristic for whether we need to close the comment:
10727 ;; if we've got a parse error here, assume it's an unterminated
10728 ;; comment.
10729 (setq needs-close
10730 (or
10731 (eq (get-text-property (1- (point)) 'point-entered)
10732 'js2-echo-error)
10733 ;; The heuristic above doesn't work well when we're
10734 ;; creating a comment and there's another one downstream,
10735 ;; as our parser thinks this one ends at the end of the
10736 ;; next one. (You can have a /* inside a js block comment.)
10737 ;; So just close it if the next non-ws char isn't a *.
10738 (and first-line
10739 (eolp)
10740 (save-excursion
10741 (skip-chars-forward " \t\r\n")
10742 (not (eq (char-after) ?*))))))
10743 (delete-horizontal-space)
10744 (insert "\n")
10745 (cond
10746 (star
10747 (indent-to col)
10748 (insert "* ")
10749 (if (and first-line needs-close)
10750 (save-excursion
10751 (insert "\n")
10752 (indent-to col)
10753 (insert "*/"))))
10754 ((and single
10755 (save-excursion
10756 (and (zerop (forward-line 1))
10757 (looking-at "\\s-*//"))))
10758 (indent-to col)
10759 (insert "// ")))
10760 ;; Don't need to extend the comment after all.
10761 (js2-indent-line)))
10762
10763 (defun js2-beginning-of-line ()
10764 "Toggle point between bol and first non-whitespace char in line.
10765 Also moves past comment delimiters when inside comments."
10766 (interactive)
10767 (let (node)
10768 (cond
10769 ((bolp)
10770 (back-to-indentation))
10771 ((looking-at "//")
10772 (skip-chars-forward "/ \t"))
10773 ((and (eq (char-after) ?*)
10774 (setq node (js2-comment-at-point))
10775 (memq (js2-comment-node-format node) '(jsdoc block))
10776 (save-excursion
10777 (skip-chars-backward " \t")
10778 (bolp)))
10779 (skip-chars-forward "\* \t"))
10780 (t
10781 (goto-char (point-at-bol))))))
10782
10783 (defun js2-end-of-line ()
10784 "Toggle point between eol and last non-whitespace char in line."
10785 (interactive)
10786 (if (eolp)
10787 (skip-chars-backward " \t")
10788 (goto-char (point-at-eol))))
10789
10790 (defun js2-mode-wait-for-parse (callback)
10791 "Invoke CALLBACK when parsing is finished.
10792 If parsing is already finished, calls CALLBACK immediately."
10793 (if (not js2-mode-buffer-dirty-p)
10794 (funcall callback)
10795 (push callback js2-mode-pending-parse-callbacks)
10796 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10797
10798 (defun js2-mode-parse-finished ()
10799 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10800 ;; We can't let errors propagate up, since it prevents the
10801 ;; `js2-parse' method from completing normally and returning
10802 ;; the ast, which makes things mysteriously not work right.
10803 (unwind-protect
10804 (dolist (cb js2-mode-pending-parse-callbacks)
10805 (condition-case err
10806 (funcall cb)
10807 (error (message "%s" err))))
10808 (setq js2-mode-pending-parse-callbacks nil)))
10809
10810 (defun js2-mode-flag-region (from to flag)
10811 "Hide or show text from FROM to TO, according to FLAG.
10812 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10813 Returns the created overlay if FLAG is non-nil."
10814 (remove-overlays from to 'invisible 'js2-outline)
10815 (when flag
10816 (let ((o (make-overlay from to)))
10817 (overlay-put o 'invisible 'js2-outline)
10818 (overlay-put o 'isearch-open-invisible
10819 'js2-isearch-open-invisible)
10820 o)))
10821
10822 ;; Function to be set as an outline-isearch-open-invisible' property
10823 ;; to the overlay that makes the outline invisible (see
10824 ;; `js2-mode-flag-region').
10825 (defun js2-isearch-open-invisible (_overlay)
10826 ;; We rely on the fact that isearch places point on the matched text.
10827 (js2-mode-show-element))
10828
10829 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10830 "Return cons cell of bounds of folding overlay at POS.
10831 Returns nil if not found."
10832 (let ((overlays (overlays-at (or pos (point))))
10833 o)
10834 (while (and overlays
10835 (not o))
10836 (if (overlay-get (car overlays) 'invisible)
10837 (setq o (car overlays))
10838 (setq overlays (cdr overlays))))
10839 (if o
10840 (cons (overlay-start o) (overlay-end o)))))
10841
10842 (defun js2-mode-function-at-point (&optional pos)
10843 "Return the innermost function node enclosing current point.
10844 Returns nil if point is not in a function."
10845 (let ((node (js2-node-at-point pos)))
10846 (while (and node (not (js2-function-node-p node)))
10847 (setq node (js2-node-parent node)))
10848 (if (js2-function-node-p node)
10849 node)))
10850
10851 (defun js2-mode-toggle-element ()
10852 "Hide or show the foldable element at the point."
10853 (interactive)
10854 (let (comment fn pos)
10855 (save-excursion
10856 (cond
10857 ;; /* ... */ comment?
10858 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10859 (if (js2-mode-invisible-overlay-bounds
10860 (setq pos (+ 3 (js2-node-abs-pos comment))))
10861 (progn
10862 (goto-char pos)
10863 (js2-mode-show-element))
10864 (js2-mode-hide-element)))
10865 ;; //-comment?
10866 ((save-excursion
10867 (back-to-indentation)
10868 (looking-at js2-mode-//-comment-re))
10869 (js2-mode-toggle-//-comment))
10870 ;; function?
10871 ((setq fn (js2-mode-function-at-point))
10872 (setq pos (and (js2-function-node-body fn)
10873 (js2-node-abs-pos (js2-function-node-body fn))))
10874 (goto-char (1+ pos))
10875 (if (js2-mode-invisible-overlay-bounds)
10876 (js2-mode-show-element)
10877 (js2-mode-hide-element)))
10878 (t
10879 (message "Nothing at point to hide or show"))))))
10880
10881 (defun js2-mode-hide-element ()
10882 "Fold/hide contents of a block, showing ellipses.
10883 Show the hidden text with \\[js2-mode-show-element]."
10884 (interactive)
10885 (if js2-mode-buffer-dirty-p
10886 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10887 (let (node body beg end)
10888 (cond
10889 ((js2-mode-invisible-overlay-bounds)
10890 (message "already hidden"))
10891 (t
10892 (setq node (js2-node-at-point))
10893 (cond
10894 ((js2-block-comment-p node)
10895 (js2-mode-hide-comment node))
10896 (t
10897 (while (and node (not (js2-function-node-p node)))
10898 (setq node (js2-node-parent node)))
10899 (if (and node
10900 (setq body (js2-function-node-body node)))
10901 (progn
10902 (setq beg (js2-node-abs-pos body)
10903 end (+ beg (js2-node-len body)))
10904 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10905 (message "No collapsable element found at point"))))))))
10906
10907 (defun js2-mode-show-element ()
10908 "Show the hidden element at current point."
10909 (interactive)
10910 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10911 (if bounds
10912 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
10913 (message "Nothing to un-hide"))))
10914
10915 (defun js2-mode-show-all ()
10916 "Show all of the text in the buffer."
10917 (interactive)
10918 (js2-mode-flag-region (point-min) (point-max) nil))
10919
10920 (defun js2-mode-toggle-hide-functions ()
10921 (interactive)
10922 (if js2-mode-functions-hidden
10923 (js2-mode-show-functions)
10924 (js2-mode-hide-functions)))
10925
10926 (defun js2-mode-hide-functions ()
10927 "Hides all non-nested function bodies in the buffer.
10928 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10929 to open an individual entry."
10930 (interactive)
10931 (if js2-mode-buffer-dirty-p
10932 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
10933 (if (null js2-mode-ast)
10934 (message "Oops - parsing failed")
10935 (setq js2-mode-functions-hidden t)
10936 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
10937
10938 (defun js2-mode-function-hider (n endp)
10939 (when (not endp)
10940 (let ((tt (js2-node-type n))
10941 body beg end)
10942 (cond
10943 ((and (= tt js2-FUNCTION)
10944 (setq body (js2-function-node-body n)))
10945 (setq beg (js2-node-abs-pos body)
10946 end (+ beg (js2-node-len body)))
10947 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
10948 nil) ; don't process children of function
10949 (t
10950 t))))) ; keep processing other AST nodes
10951
10952 (defun js2-mode-show-functions ()
10953 "Un-hide any folded function bodies in the buffer."
10954 (interactive)
10955 (setq js2-mode-functions-hidden nil)
10956 (save-excursion
10957 (goto-char (point-min))
10958 (while (/= (goto-char (next-overlay-change (point)))
10959 (point-max))
10960 (dolist (o (overlays-at (point)))
10961 (when (and (overlay-get o 'invisible)
10962 (not (overlay-get o 'comment)))
10963 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10964
10965 (defun js2-mode-hide-comment (n)
10966 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
10967 3 ; /**
10968 2)) ; /*
10969 (beg (+ (js2-node-abs-pos n) head))
10970 (end (- (+ beg (js2-node-len n)) head 2))
10971 (o (js2-mode-flag-region beg end 'hide)))
10972 (overlay-put o 'comment t)))
10973
10974 (defun js2-mode-toggle-hide-comments ()
10975 "Folds all block comments in the buffer.
10976 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10977 to open an individual entry."
10978 (interactive)
10979 (if js2-mode-comments-hidden
10980 (js2-mode-show-comments)
10981 (js2-mode-hide-comments)))
10982
10983 (defun js2-mode-hide-comments ()
10984 (interactive)
10985 (if js2-mode-buffer-dirty-p
10986 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
10987 (if (null js2-mode-ast)
10988 (message "Oops - parsing failed")
10989 (setq js2-mode-comments-hidden t)
10990 (dolist (n (js2-ast-root-comments js2-mode-ast))
10991 (when (js2-block-comment-p n)
10992 (js2-mode-hide-comment n)))
10993 (js2-mode-hide-//-comments)))
10994
10995 (defun js2-mode-extend-//-comment (direction)
10996 "Find start or end of a block of similar //-comment lines.
10997 DIRECTION is -1 to look back, 1 to look forward.
10998 INDENT is the indentation level to match.
10999 Returns the end-of-line position of the furthest adjacent
11000 //-comment line with the same indentation as the current line.
11001 If there is no such matching line, returns current end of line."
11002 (let ((pos (point-at-eol))
11003 (indent (current-indentation)))
11004 (save-excursion
11005 (while (and (zerop (forward-line direction))
11006 (looking-at js2-mode-//-comment-re)
11007 (eq indent (length (match-string 1))))
11008 (setq pos (point-at-eol))
11009 pos))))
11010
11011 (defun js2-mode-hide-//-comments ()
11012 "Fold adjacent 1-line comments, showing only snippet of first one."
11013 (let (beg end)
11014 (save-excursion
11015 (goto-char (point-min))
11016 (while (re-search-forward js2-mode-//-comment-re nil t)
11017 (setq beg (point)
11018 end (js2-mode-extend-//-comment 1))
11019 (unless (eq beg end)
11020 (overlay-put (js2-mode-flag-region beg end 'hide)
11021 'comment t))
11022 (goto-char end)
11023 (forward-char 1)))))
11024
11025 (defun js2-mode-toggle-//-comment ()
11026 "Fold or un-fold any multi-line //-comment at point.
11027 Caller should have determined that this line starts with a //-comment."
11028 (let* ((beg (point-at-eol))
11029 (end beg))
11030 (save-excursion
11031 (goto-char end)
11032 (if (js2-mode-invisible-overlay-bounds)
11033 (js2-mode-show-element)
11034 ;; else hide the comment
11035 (setq beg (js2-mode-extend-//-comment -1)
11036 end (js2-mode-extend-//-comment 1))
11037 (unless (eq beg end)
11038 (overlay-put (js2-mode-flag-region beg end 'hide)
11039 'comment t))))))
11040
11041 (defun js2-mode-show-comments ()
11042 "Un-hide any hidden comments, leaving other hidden elements alone."
11043 (interactive)
11044 (setq js2-mode-comments-hidden nil)
11045 (save-excursion
11046 (goto-char (point-min))
11047 (while (/= (goto-char (next-overlay-change (point)))
11048 (point-max))
11049 (dolist (o (overlays-at (point)))
11050 (when (overlay-get o 'comment)
11051 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11052
11053 (defun js2-mode-display-warnings-and-errors ()
11054 "Turn on display of warnings and errors."
11055 (interactive)
11056 (setq js2-mode-show-parse-errors t
11057 js2-mode-show-strict-warnings t)
11058 (js2-reparse 'force))
11059
11060 (defun js2-mode-hide-warnings-and-errors ()
11061 "Turn off display of warnings and errors."
11062 (interactive)
11063 (setq js2-mode-show-parse-errors nil
11064 js2-mode-show-strict-warnings nil)
11065 (js2-reparse 'force))
11066
11067 (defun js2-mode-toggle-warnings-and-errors ()
11068 "Toggle the display of warnings and errors.
11069 Some users don't like having warnings/errors reported while they type."
11070 (interactive)
11071 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11072 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11073 (if (called-interactively-p 'any)
11074 (message "warnings and errors %s"
11075 (if js2-mode-show-parse-errors
11076 "enabled"
11077 "disabled")))
11078 (js2-reparse 'force))
11079
11080 (defun js2-mode-customize ()
11081 (interactive)
11082 (customize-group 'js2-mode))
11083
11084 (defun js2-mode-forward-sexp (&optional arg)
11085 "Move forward across one statement or balanced expression.
11086 With ARG, do it that many times. Negative arg -N means
11087 move backward across N balanced expressions."
11088 (interactive "p")
11089 (setq arg (or arg 1))
11090 (save-restriction
11091 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11092 (js2-reparse)
11093 (let (forward-sexp-function
11094 node (start (point)) pos lp rp child)
11095 (cond
11096 ;; backward-sexp
11097 ;; could probably make this better for some cases:
11098 ;; - if in statement block (e.g. function body), go to parent
11099 ;; - infix exprs like (foo in bar) - maybe go to beginning
11100 ;; of infix expr if in the right-side expression?
11101 ((and arg (minusp arg))
11102 (dotimes (_ (- arg))
11103 (js2-backward-sws)
11104 (forward-char -1) ; Enter the node we backed up to.
11105 (when (setq node (js2-node-at-point (point) t))
11106 (setq pos (js2-node-abs-pos node))
11107 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11108 (setq lp (car parens)
11109 rp (cdr parens)))
11110 (when (and lp (> start lp))
11111 (if (and rp (<= start rp))
11112 ;; Between parens, check if there's a child node we can jump.
11113 (when (setq child (js2-node-closest-child node (point) lp t))
11114 (setq pos (js2-node-abs-pos child)))
11115 ;; Before both parens.
11116 (setq pos lp)))
11117 (let ((state (parse-partial-sexp start pos)))
11118 (goto-char (if (not (zerop (car state)))
11119 ;; Stumble at the unbalanced paren if < 0, or
11120 ;; jump a bit further if > 0.
11121 (scan-sexps start -1)
11122 pos))))
11123 (unless pos (goto-char (point-min)))))
11124 (t
11125 ;; forward-sexp
11126 (dotimes (_ arg)
11127 (js2-forward-sws)
11128 (when (setq node (js2-node-at-point (point) t))
11129 (setq pos (js2-node-abs-pos node))
11130 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11131 (setq lp (car parens)
11132 rp (cdr parens)))
11133 (or
11134 (when (and rp (<= start rp))
11135 (if (> start lp)
11136 (when (setq child (js2-node-closest-child node (point) rp))
11137 (setq pos (js2-node-abs-end child)))
11138 (setq pos (1+ rp))))
11139 ;; No parens or child nodes, looks for the end of the curren node.
11140 (incf pos (js2-node-len
11141 (if (js2-expr-stmt-node-p (js2-node-parent node))
11142 ;; Stop after the semicolon.
11143 (js2-node-parent node)
11144 node))))
11145 (let ((state (save-excursion (parse-partial-sexp start pos))))
11146 (goto-char (if (not (zerop (car state)))
11147 (scan-sexps start 1)
11148 pos))))
11149 (unless pos (goto-char (point-max)))))))))
11150
11151 (defun js2-mode-forward-sexp-parens (node abs-pos)
11152 "Return a cons cell with positions of main parens in NODE."
11153 (cond
11154 ((or (js2-array-node-p node)
11155 (js2-object-node-p node)
11156 (js2-array-comp-node-p node)
11157 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11158 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11159 ((js2-paren-expr-node-p node)
11160 (let ((lp (js2-node-lp node))
11161 (rp (js2-node-rp node)))
11162 (cons (when lp (+ abs-pos lp))
11163 (when rp (+ abs-pos rp)))))))
11164
11165 (defun js2-node-closest-child (parent point limit &optional before)
11166 (let* ((parent-pos (js2-node-abs-pos parent))
11167 (rpoint (- point parent-pos))
11168 (rlimit (- limit parent-pos))
11169 (min (min rpoint rlimit))
11170 (max (max rpoint rlimit))
11171 found)
11172 (catch 'done
11173 (js2-visit-ast
11174 parent
11175 (lambda (node _end-p)
11176 (if (eq node parent)
11177 t
11178 (let ((pos (js2-node-pos node)) ;; Both relative values.
11179 (end (+ (js2-node-pos node) (js2-node-len node))))
11180 (when (and (>= pos min) (<= end max)
11181 (if before (< pos rpoint) (> end rpoint)))
11182 (setq found node))
11183 (when (> end rpoint)
11184 (throw 'done nil)))
11185 nil))))
11186 found))
11187
11188 (defun js2-errors ()
11189 "Return a list of errors found."
11190 (and js2-mode-ast
11191 (js2-ast-root-errors js2-mode-ast)))
11192
11193 (defun js2-warnings ()
11194 "Return a list of warnings found."
11195 (and js2-mode-ast
11196 (js2-ast-root-warnings js2-mode-ast)))
11197
11198 (defun js2-have-errors-p ()
11199 "Return non-nil if any parse errors or warnings were found."
11200 (or (js2-errors) (js2-warnings)))
11201
11202 (defun js2-errors-and-warnings ()
11203 "Return a copy of the concatenated errors and warnings lists.
11204 They are appended: first the errors, then the warnings.
11205 Entries are of the form (MSG BEG END)."
11206 (when js2-mode-ast
11207 (append (js2-ast-root-errors js2-mode-ast)
11208 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11209
11210 (defun js2-next-error (&optional arg reset)
11211 "Move to next parse error.
11212 Typically invoked via \\[next-error].
11213 ARG is the number of errors, forward or backward, to move.
11214 RESET means start over from the beginning."
11215 (interactive "p")
11216 (if (not (or (js2-errors) (js2-warnings)))
11217 (message "No errors")
11218 (when reset
11219 (goto-char (point-min)))
11220 (let* ((errs (js2-errors-and-warnings))
11221 (continue t)
11222 (start (point))
11223 (count (or arg 1))
11224 (backward (minusp count))
11225 (sorter (if backward '> '<))
11226 (stopper (if backward '< '>))
11227 (count (abs count))
11228 all-errs err)
11229 ;; Sort by start position.
11230 (setq errs (sort errs (lambda (e1 e2)
11231 (funcall sorter (second e1) (second e2))))
11232 all-errs errs)
11233 ;; Find nth error with pos > start.
11234 (while (and errs continue)
11235 (when (funcall stopper (cadar errs) start)
11236 (setq err (car errs))
11237 (if (zerop (decf count))
11238 (setq continue nil)))
11239 (setq errs (cdr errs)))
11240 ;; Clear for `js2-echo-error'.
11241 (message nil)
11242 (if err
11243 (goto-char (second err))
11244 ;; Wrap around to first error.
11245 (goto-char (second (car all-errs)))
11246 ;; If we were already on it, echo msg again.
11247 (if (= (point) start)
11248 (js2-echo-error (point) (point)))))))
11249
11250 (defun js2-down-mouse-3 ()
11251 "Make right-click move the point to the click location.
11252 This makes right-click context menu operations a bit more intuitive.
11253 The point will not move if the region is active, however, to avoid
11254 destroying the region selection."
11255 (interactive)
11256 (when (and js2-move-point-on-right-click
11257 (not mark-active))
11258 (let ((e last-input-event))
11259 (ignore-errors
11260 (goto-char (cadadr e))))))
11261
11262 (defun js2-mode-create-imenu-index ()
11263 "Return an alist for `imenu--index-alist'."
11264 ;; This is built up in `js2-parse-record-imenu' during parsing.
11265 (when js2-mode-ast
11266 ;; if we have an ast but no recorder, they're requesting a rescan
11267 (unless js2-imenu-recorder
11268 (js2-reparse 'force))
11269 (prog1
11270 (js2-build-imenu-index)
11271 (setq js2-imenu-recorder nil
11272 js2-imenu-function-map nil))))
11273
11274 (defun js2-mode-find-tag ()
11275 "Replacement for `find-tag-default'.
11276 `find-tag-default' returns a ridiculous answer inside comments."
11277 (let (beg end)
11278 (js2-with-underscore-as-word-syntax
11279 (save-excursion
11280 (if (and (not (looking-at "[[:alnum:]_$]"))
11281 (looking-back "[[:alnum:]_$]"))
11282 (setq beg (progn (forward-word -1) (point))
11283 end (progn (forward-word 1) (point)))
11284 (setq beg (progn (forward-word 1) (point))
11285 end (progn (forward-word -1) (point))))
11286 (replace-regexp-in-string
11287 "[\"']" ""
11288 (buffer-substring-no-properties beg end))))))
11289
11290 (defun js2-mode-forward-sibling ()
11291 "Move to the end of the sibling following point in parent.
11292 Returns non-nil if successful, or nil if there was no following sibling."
11293 (let* ((node (js2-node-at-point))
11294 (parent (js2-mode-find-enclosing-fn node))
11295 sib)
11296 (when (setq sib (js2-node-find-child-after (point) parent))
11297 (goto-char (+ (js2-node-abs-pos sib)
11298 (js2-node-len sib))))))
11299
11300 (defun js2-mode-backward-sibling ()
11301 "Move to the beginning of the sibling node preceding point in parent.
11302 Parent is defined as the enclosing script or function."
11303 (let* ((node (js2-node-at-point))
11304 (parent (js2-mode-find-enclosing-fn node))
11305 sib)
11306 (when (setq sib (js2-node-find-child-before (point) parent))
11307 (goto-char (js2-node-abs-pos sib)))))
11308
11309 (defun js2-beginning-of-defun (&optional arg)
11310 "Go to line on which current function starts, and return t on success.
11311 If we're not in a function or already at the beginning of one, go
11312 to beginning of previous script-level element.
11313 With ARG N, do that N times. If N is negative, move forward."
11314 (setq arg (or arg 1))
11315 (if (plusp arg)
11316 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11317 (when (cond
11318 ((js2-function-node-p parent)
11319 (goto-char (js2-node-abs-pos parent)))
11320 (t
11321 (js2-mode-backward-sibling)))
11322 (if (> arg 1)
11323 (js2-beginning-of-defun (1- arg))
11324 t)))
11325 (when (js2-end-of-defun)
11326 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
11327
11328 (defun js2-end-of-defun ()
11329 "Go to the char after the last position of the current function
11330 or script-level element."
11331 (let* ((node (js2-node-at-point))
11332 (parent (or (and (js2-function-node-p node) node)
11333 (js2-node-parent-script-or-fn node)))
11334 script)
11335 (unless (js2-function-node-p parent)
11336 ;; Use current script-level node, or, if none, the next one.
11337 (setq script (or parent node)
11338 parent (js2-node-find-child-before (point) script))
11339 (when (or (null parent)
11340 (>= (point) (+ (js2-node-abs-pos parent)
11341 (js2-node-len parent))))
11342 (setq parent (js2-node-find-child-after (point) script))))
11343 (when parent
11344 (goto-char (+ (js2-node-abs-pos parent)
11345 (js2-node-len parent))))))
11346
11347 (defun js2-mark-defun (&optional allow-extend)
11348 "Put mark at end of this function, point at beginning.
11349 The function marked is the one that contains point.
11350
11351 Interactively, if this command is repeated,
11352 or (in Transient Mark mode) if the mark is active,
11353 it marks the next defun after the ones already marked."
11354 (interactive "p")
11355 (let (extended)
11356 (when (and allow-extend
11357 (or (and (eq last-command this-command) (mark t))
11358 (and transient-mark-mode mark-active)))
11359 (let ((sib (save-excursion
11360 (goto-char (mark))
11361 (if (js2-mode-forward-sibling)
11362 (point)))))
11363 (if sib
11364 (progn
11365 (set-mark sib)
11366 (setq extended t))
11367 ;; no more siblings - try extending to enclosing node
11368 (goto-char (mark t)))))
11369 (when (not extended)
11370 (let ((node (js2-node-at-point (point) t)) ; skip comments
11371 ast fn stmt parent beg end)
11372 (when (js2-ast-root-p node)
11373 (setq ast node
11374 node (or (js2-node-find-child-after (point) node)
11375 (js2-node-find-child-before (point) node))))
11376 ;; only mark whole buffer if we can't find any children
11377 (if (null node)
11378 (setq node ast))
11379 (if (js2-function-node-p node)
11380 (setq parent node)
11381 (setq fn (js2-mode-find-enclosing-fn node)
11382 stmt (if (or (null fn)
11383 (js2-ast-root-p fn))
11384 (js2-mode-find-first-stmt node))
11385 parent (or stmt fn)))
11386 (setq beg (js2-node-abs-pos parent)
11387 end (+ beg (js2-node-len parent)))
11388 (push-mark beg)
11389 (goto-char end)
11390 (exchange-point-and-mark)))))
11391
11392 (defun js2-narrow-to-defun ()
11393 "Narrow to the function enclosing point."
11394 (interactive)
11395 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11396 (fn (if (js2-script-node-p node)
11397 node
11398 (js2-mode-find-enclosing-fn node)))
11399 (beg (js2-node-abs-pos fn)))
11400 (unless (js2-ast-root-p fn)
11401 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11402
11403 (provide 'js2-mode)
11404
11405 ;;; js2-mode.el ends here