]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Merge pull request #149 from lewang/dont-parse-killed-buffer
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2014 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
10 ;; Version: 20140114
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
65
66 ;; Notes:
67
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
71
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
76
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
81
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code has outdated information and is mostly
84 ;; unmaintained.
85
86 ;;; Code:
87
88 (eval-when-compile
89 (require 'cl))
90
91 (require 'imenu)
92 (require 'cc-cmds) ; for `c-fill-paragraph'
93
94 (eval-and-compile
95 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
96 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
97
98 (defvar electric-layout-rules)
99
100 ;;; Externs (variables presumed to be defined by the host system)
101
102 (defvar js2-ecma-262-externs
103 (mapcar 'symbol-name
104 '(Array Boolean Date Error EvalError Function Infinity JSON
105 Math NaN Number Object RangeError ReferenceError RegExp
106 String SyntaxError TypeError URIError arguments
107 decodeURI decodeURIComponent encodeURI
108 encodeURIComponent escape eval isFinite isNaN
109 parseFloat parseInt undefined unescape))
110 "Ecma-262 externs. Included in `js2-externs' by default.")
111
112 (defvar js2-browser-externs
113 (mapcar 'symbol-name
114 '(;; DOM level 1
115 Attr CDATASection CharacterData Comment DOMException
116 DOMImplementation Document DocumentFragment
117 DocumentType Element Entity EntityReference
118 ExceptionCode NamedNodeMap Node NodeList Notation
119 ProcessingInstruction Text
120
121 ;; DOM level 2
122 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
123 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
124 HTMLBodyElement HTMLButtonElement HTMLCollection
125 HTMLDListElement HTMLDirectoryElement HTMLDivElement
126 HTMLDocument HTMLElement HTMLFieldSetElement
127 HTMLFontElement HTMLFormElement HTMLFrameElement
128 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
129 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
130 HTMLImageElement HTMLInputElement HTMLIsIndexElement
131 HTMLLIElement HTMLLabelElement HTMLLegendElement
132 HTMLLinkElement HTMLMapElement HTMLMenuElement
133 HTMLMetaElement HTMLModElement HTMLOListElement
134 HTMLObjectElement HTMLOptGroupElement
135 HTMLOptionElement HTMLOptionsCollection
136 HTMLParagraphElement HTMLParamElement HTMLPreElement
137 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
138 HTMLStyleElement HTMLTableCaptionElement
139 HTMLTableCellElement HTMLTableColElement
140 HTMLTableElement HTMLTableRowElement
141 HTMLTableSectionElement HTMLTextAreaElement
142 HTMLTitleElement HTMLUListElement
143
144 ;; DOM level 3
145 DOMConfiguration DOMError DOMException
146 DOMImplementationList DOMImplementationSource
147 DOMLocator DOMStringList NameList TypeInfo
148 UserDataHandler
149
150 ;; Window
151 window alert confirm document java navigator prompt screen
152 self top
153
154 ;; W3C CSS
155 CSSCharsetRule CSSFontFace CSSFontFaceRule
156 CSSImportRule CSSMediaRule CSSPageRule
157 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
158 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
159 CSSValue CSSValueList Counter DOMImplementationCSS
160 DocumentCSS DocumentStyle ElementCSSInlineStyle
161 LinkStyle MediaList RGBColor Rect StyleSheet
162 StyleSheetList ViewCSS
163
164 ;; W3C Event
165 EventListener EventTarget Event DocumentEvent UIEvent
166 MouseEvent MutationEvent KeyboardEvent
167
168 ;; W3C Range
169 DocumentRange Range RangeException
170
171 ;; W3C XML
172 XPathResult XMLHttpRequest
173
174 ;; console object. Provided by at least Chrome and Firefox.
175 console))
176 "Browser externs.
177 You can cause these to be included or excluded with the custom
178 variable `js2-include-browser-externs'.")
179
180 (defvar js2-rhino-externs
181 (mapcar 'symbol-name
182 '(Packages importClass importPackage com org java
183 ;; Global object (shell) externs.
184 defineClass deserialize doctest gc help load
185 loadClass print quit readFile readUrl runCommand seal
186 serialize spawn sync toint32 version))
187 "Mozilla Rhino externs.
188 Set `js2-include-rhino-externs' to t to include them.")
189
190 (defvar js2-node-externs
191 (mapcar 'symbol-name
192 '(__dirname __filename Buffer clearInterval clearTimeout require
193 console exports global module process setInterval setTimeout))
194 "Node.js externs.
195 Set `js2-include-node-externs' to t to include them.")
196
197 (defvar js2-typed-array-externs
198 (mapcar 'symbol-name
199 '(ArrayBuffer Uint8ClampedArray DataView
200 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
201 Float32Array Float64Array))
202 "Khronos typed array externs. Available in most modern browsers and
203 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
204 are enabled, these will also be included.")
205
206 ;;; Variables
207
208 (defun js2-mark-safe-local (name pred)
209 "Make the variable NAME buffer-local and mark it as safe file-local
210 variable with predicate PRED."
211 (make-variable-buffer-local name)
212 (put name 'safe-local-variable pred))
213
214 (defcustom js2-highlight-level 2
215 "Amount of syntax highlighting to perform.
216 0 or a negative value means none.
217 1 adds basic syntax highlighting.
218 2 adds highlighting of some Ecma built-in properties.
219 3 adds highlighting of many Ecma built-in functions."
220 :group 'js2-mode
221 :type '(choice (const :tag "None" 0)
222 (const :tag "Basic" 1)
223 (const :tag "Include Properties" 2)
224 (const :tag "Include Functions" 3)))
225
226 (defvar js2-mode-dev-mode-p nil
227 "Non-nil if running in development mode. Normally nil.")
228
229 (defgroup js2-mode nil
230 "An improved JavaScript mode."
231 :group 'languages)
232
233 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
234 (numberp c-basic-offset))
235 c-basic-offset
236 4)
237 "Number of spaces to indent nested statements.
238 Similar to `c-basic-offset'."
239 :group 'js2-mode
240 :type 'integer)
241 (js2-mark-safe-local 'js2-basic-offset 'integerp)
242
243 (defcustom js2-bounce-indent-p nil
244 "Non-nil to have indent-line function choose among alternatives.
245 If nil, the indent-line function will indent to a predetermined column
246 based on heuristic guessing. If non-nil, then if the current line is
247 already indented to that predetermined column, indenting will choose
248 another likely column and indent to that spot. Repeated invocation of
249 the indent-line function will cycle among the computed alternatives.
250 See the function `js2-bounce-indent' for details. When it is non-nil,
251 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
252 :type 'boolean
253 :group 'js2-mode)
254
255 (defcustom js2-pretty-multiline-declarations t
256 "Non-nil to line up multiline declarations vertically:
257
258 var a = 10,
259 b = 20,
260 c = 30;
261
262 If the value is not `all', and the first assigned value in
263 declaration is a function/array/object literal spanning several
264 lines, it won't be indented additionally:
265
266 var o = { var bar = 2,
267 foo: 3 vs. o = {
268 }, foo: 3
269 bar = 2; };"
270 :group 'js2-mode
271 :type 'symbol)
272 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
273
274 (defcustom js2-indent-switch-body nil
275 "When nil, case labels are indented on the same level as the
276 containing switch statement. Otherwise, all lines inside
277 switch statement body are indented one additional level."
278 :type 'boolean
279 :group 'js2-mode)
280 (js2-mark-safe-local 'js2-indent-case-same-as-switch 'booleanp)
281
282 (defcustom js2-idle-timer-delay 0.2
283 "Delay in secs before re-parsing after user makes changes.
284 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
285 :type 'number
286 :group 'js2-mode)
287 (make-variable-buffer-local 'js2-idle-timer-delay)
288
289 (defcustom js2-dynamic-idle-timer-adjust 0
290 "Positive to adjust `js2-idle-timer-delay' based on file size.
291 The idea is that for short files, parsing is faster so we can be
292 more responsive to user edits without interfering with editing.
293 The buffer length in characters (typically bytes) is divided by
294 this value and used to multiply `js2-idle-timer-delay' for the
295 buffer. For example, a 21k file and 10k adjust yields 21k/10k
296 == 2, so js2-idle-timer-delay is multiplied by 2.
297 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
298 `js2-idle-timer-delay' is not dependent on the file size."
299 :type 'number
300 :group 'js2-mode)
301
302 (defcustom js2-concat-multiline-strings t
303 "When non-nil, `js2-line-break' in mid-string will make it a
304 string concatenation. When `eol', the '+' will be inserted at the
305 end of the line, otherwise, at the beginning of the next line."
306 :type '(choice (const t) (const eol) (const nil))
307 :group 'js2-mode)
308
309 (defcustom js2-mode-show-parse-errors t
310 "True to highlight parse errors."
311 :type 'boolean
312 :group 'js2-mode)
313
314 (defcustom js2-mode-show-strict-warnings t
315 "Non-nil to emit Ecma strict-mode warnings.
316 Some of the warnings can be individually disabled by other flags,
317 even if this flag is non-nil."
318 :type 'boolean
319 :group 'js2-mode)
320
321 (defcustom js2-strict-trailing-comma-warning t
322 "Non-nil to warn about trailing commas in array literals.
323 Ecma-262-5.1 allows them, but older versions of IE raise an error."
324 :type 'boolean
325 :group 'js2-mode)
326
327 (defcustom js2-strict-missing-semi-warning t
328 "Non-nil to warn about semicolon auto-insertion after statement.
329 Technically this is legal per Ecma-262, but some style guides disallow
330 depending on it."
331 :type 'boolean
332 :group 'js2-mode)
333
334 (defcustom js2-missing-semi-one-line-override nil
335 "Non-nil to permit missing semicolons in one-line functions.
336 In one-liner functions such as `function identity(x) {return x}'
337 people often omit the semicolon for a cleaner look. If you are
338 such a person, you can suppress the missing-semicolon warning
339 by setting this variable to t."
340 :type 'boolean
341 :group 'js2-mode)
342
343 (defcustom js2-strict-inconsistent-return-warning t
344 "Non-nil to warn about mixing returns with value-returns.
345 It's perfectly legal to have a `return' and a `return foo' in the
346 same function, but it's often an indicator of a bug, and it also
347 interferes with type inference (in systems that support it.)"
348 :type 'boolean
349 :group 'js2-mode)
350
351 (defcustom js2-strict-cond-assign-warning t
352 "Non-nil to warn about expressions like if (a = b).
353 This often should have been '==' instead of '='. If the warning
354 is enabled, you can suppress it on a per-expression basis by
355 parenthesizing the expression, e.g. if ((a = b)) ..."
356 :type 'boolean
357 :group 'js2-mode)
358
359 (defcustom js2-strict-var-redeclaration-warning t
360 "Non-nil to warn about redeclaring variables in a script or function."
361 :type 'boolean
362 :group 'js2-mode)
363
364 (defcustom js2-strict-var-hides-function-arg-warning t
365 "Non-nil to warn about a var decl hiding a function argument."
366 :type 'boolean
367 :group 'js2-mode)
368
369 (defcustom js2-skip-preprocessor-directives nil
370 "Non-nil to treat lines beginning with # as comments.
371 Useful for viewing Mozilla JavaScript source code."
372 :type 'boolean
373 :group 'js2-mode)
374
375 (defcustom js2-language-version 200
376 "Configures what JavaScript language version to recognize.
377 Currently versions 150, 160, 170, 180 and 200 are supported,
378 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
379 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
380 yield, and Array comprehensions, and 1.8 adds function closures."
381 :type 'integer
382 :group 'js2-mode)
383
384 (defcustom js2-allow-keywords-as-property-names t
385 "If non-nil, you can use JavaScript keywords as object property names.
386 Examples:
387
388 var foo = {int: 5, while: 6, continue: 7};
389 foo.return = 8;
390
391 Ecma-262 5.1 allows this syntax, but some engines still don't."
392 :type 'boolean
393 :group 'js2-mode)
394
395 (defcustom js2-instanceof-has-side-effects nil
396 "If non-nil, treats the instanceof operator as having side effects.
397 This is useful for xulrunner apps."
398 :type 'boolean
399 :group 'js2-mode)
400
401 (defcustom js2-move-point-on-right-click t
402 "Non-nil to move insertion point when you right-click.
403 This makes right-click context menu behavior a bit more intuitive,
404 since menu operations generally apply to the point. The exception
405 is if there is a region selection, in which case the point does -not-
406 move, so cut/copy/paste can work properly.
407
408 Note that IntelliJ moves the point, and Eclipse leaves it alone,
409 so this behavior is customizable."
410 :group 'js2-mode
411 :type 'boolean)
412
413 (defcustom js2-allow-rhino-new-expr-initializer t
414 "Non-nil to support a Rhino's experimental syntactic construct.
415
416 Rhino supports the ability to follow a `new' expression with an object
417 literal, which is used to set additional properties on the new object
418 after calling its constructor. Syntax:
419
420 new <expr> [ ( arglist ) ] [initializer]
421
422 Hence, this expression:
423
424 new Object {a: 1, b: 2}
425
426 results in an Object with properties a=1 and b=2. This syntax is
427 apparently not configurable in Rhino - it's currently always enabled,
428 as of Rhino version 1.7R2."
429 :type 'boolean
430 :group 'js2-mode)
431
432 (defcustom js2-allow-member-expr-as-function-name nil
433 "Non-nil to support experimental Rhino syntax for function names.
434
435 Rhino supports an experimental syntax configured via the Rhino Context
436 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
437
438 function <member-expr> ( [ arg-list ] ) { <body> }
439
440 Where member-expr is a non-parenthesized 'member expression', which
441 is anything at the grammar level of a new-expression or lower, meaning
442 any expression that does not involve infix or unary operators.
443
444 When <member-expr> is not a simple identifier, then it is syntactic
445 sugar for assigning the anonymous function to the <member-expr>. Hence,
446 this code:
447
448 function a.b().c[2] (x, y) { ... }
449
450 is rewritten as:
451
452 a.b().c[2] = function(x, y) {...}
453
454 which doesn't seem particularly useful, but Rhino permits it."
455 :type 'boolean
456 :group 'js2-mode)
457
458 ;; scanner variables
459
460 (defmacro js2-deflocal (name value &optional comment)
461 "Define a buffer-local variable NAME with VALUE and COMMENT."
462 `(progn
463 (defvar ,name ,value ,comment)
464 (make-variable-buffer-local ',name)))
465
466 (defvar js2-EOF_CHAR -1
467 "Represents end of stream. Distinct from js2-EOF token type.")
468
469 ;; I originally used symbols to represent tokens, but Rhino uses
470 ;; ints and then sets various flag bits in them, so ints it is.
471 ;; The upshot is that we need a `js2-' prefix in front of each name.
472 (defvar js2-ERROR -1)
473 (defvar js2-EOF 0)
474 (defvar js2-EOL 1)
475 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
476 (defvar js2-LEAVEWITH 3)
477 (defvar js2-RETURN 4)
478 (defvar js2-GOTO 5)
479 (defvar js2-IFEQ 6)
480 (defvar js2-IFNE 7)
481 (defvar js2-SETNAME 8)
482 (defvar js2-BITOR 9)
483 (defvar js2-BITXOR 10)
484 (defvar js2-BITAND 11)
485 (defvar js2-EQ 12)
486 (defvar js2-NE 13)
487 (defvar js2-LT 14)
488 (defvar js2-LE 15)
489 (defvar js2-GT 16)
490 (defvar js2-GE 17)
491 (defvar js2-LSH 18)
492 (defvar js2-RSH 19)
493 (defvar js2-URSH 20)
494 (defvar js2-ADD 21) ; infix plus
495 (defvar js2-SUB 22) ; infix minus
496 (defvar js2-MUL 23)
497 (defvar js2-DIV 24)
498 (defvar js2-MOD 25)
499 (defvar js2-NOT 26)
500 (defvar js2-BITNOT 27)
501 (defvar js2-POS 28) ; unary plus
502 (defvar js2-NEG 29) ; unary minus
503 (defvar js2-NEW 30)
504 (defvar js2-DELPROP 31)
505 (defvar js2-TYPEOF 32)
506 (defvar js2-GETPROP 33)
507 (defvar js2-GETPROPNOWARN 34)
508 (defvar js2-SETPROP 35)
509 (defvar js2-GETELEM 36)
510 (defvar js2-SETELEM 37)
511 (defvar js2-CALL 38)
512 (defvar js2-NAME 39) ; an identifier
513 (defvar js2-NUMBER 40)
514 (defvar js2-STRING 41)
515 (defvar js2-NULL 42)
516 (defvar js2-THIS 43)
517 (defvar js2-FALSE 44)
518 (defvar js2-TRUE 45)
519 (defvar js2-SHEQ 46) ; shallow equality (===)
520 (defvar js2-SHNE 47) ; shallow inequality (!==)
521 (defvar js2-REGEXP 48)
522 (defvar js2-BINDNAME 49)
523 (defvar js2-THROW 50)
524 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
525 (defvar js2-IN 52)
526 (defvar js2-INSTANCEOF 53)
527 (defvar js2-LOCAL_LOAD 54)
528 (defvar js2-GETVAR 55)
529 (defvar js2-SETVAR 56)
530 (defvar js2-CATCH_SCOPE 57)
531 (defvar js2-ENUM_INIT_KEYS 58)
532 (defvar js2-ENUM_INIT_VALUES 59)
533 (defvar js2-ENUM_INIT_ARRAY 60)
534 (defvar js2-ENUM_NEXT 61)
535 (defvar js2-ENUM_ID 62)
536 (defvar js2-THISFN 63)
537 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
538 (defvar js2-ARRAYLIT 65) ; array literal
539 (defvar js2-OBJECTLIT 66) ; object literal
540 (defvar js2-GET_REF 67) ; *reference
541 (defvar js2-SET_REF 68) ; *reference = something
542 (defvar js2-DEL_REF 69) ; delete reference
543 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
544 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
545 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
546
547 ;; XML support
548 (defvar js2-DEFAULTNAMESPACE 73)
549 (defvar js2-ESCXMLATTR 74)
550 (defvar js2-ESCXMLTEXT 75)
551 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
552 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
553 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
554 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
555
556 (defvar js2-first-bytecode js2-ENTERWITH)
557 (defvar js2-last-bytecode js2-REF_NS_NAME)
558
559 (defvar js2-TRY 80)
560 (defvar js2-SEMI 81) ; semicolon
561 (defvar js2-LB 82) ; left and right brackets
562 (defvar js2-RB 83)
563 (defvar js2-LC 84) ; left and right curly-braces
564 (defvar js2-RC 85)
565 (defvar js2-LP 86) ; left and right parens
566 (defvar js2-RP 87)
567 (defvar js2-COMMA 88) ; comma operator
568
569 (defvar js2-ASSIGN 89) ; simple assignment (=)
570 (defvar js2-ASSIGN_BITOR 90) ; |=
571 (defvar js2-ASSIGN_BITXOR 91) ; ^=
572 (defvar js2-ASSIGN_BITAND 92) ; &=
573 (defvar js2-ASSIGN_LSH 93) ; <<=
574 (defvar js2-ASSIGN_RSH 94) ; >>=
575 (defvar js2-ASSIGN_URSH 95) ; >>>=
576 (defvar js2-ASSIGN_ADD 96) ; +=
577 (defvar js2-ASSIGN_SUB 97) ; -=
578 (defvar js2-ASSIGN_MUL 98) ; *=
579 (defvar js2-ASSIGN_DIV 99) ; /=
580 (defvar js2-ASSIGN_MOD 100) ; %=
581
582 (defvar js2-first-assign js2-ASSIGN)
583 (defvar js2-last-assign js2-ASSIGN_MOD)
584
585 (defvar js2-HOOK 101) ; conditional (?:)
586 (defvar js2-COLON 102)
587 (defvar js2-OR 103) ; logical or (||)
588 (defvar js2-AND 104) ; logical and (&&)
589 (defvar js2-INC 105) ; increment/decrement (++ --)
590 (defvar js2-DEC 106)
591 (defvar js2-DOT 107) ; member operator (.)
592 (defvar js2-FUNCTION 108) ; function keyword
593 (defvar js2-EXPORT 109) ; export keyword
594 (defvar js2-IMPORT 110) ; import keyword
595 (defvar js2-IF 111) ; if keyword
596 (defvar js2-ELSE 112) ; else keyword
597 (defvar js2-SWITCH 113) ; switch keyword
598 (defvar js2-CASE 114) ; case keyword
599 (defvar js2-DEFAULT 115) ; default keyword
600 (defvar js2-WHILE 116) ; while keyword
601 (defvar js2-DO 117) ; do keyword
602 (defvar js2-FOR 118) ; for keyword
603 (defvar js2-BREAK 119) ; break keyword
604 (defvar js2-CONTINUE 120) ; continue keyword
605 (defvar js2-VAR 121) ; var keyword
606 (defvar js2-WITH 122) ; with keyword
607 (defvar js2-CATCH 123) ; catch keyword
608 (defvar js2-FINALLY 124) ; finally keyword
609 (defvar js2-VOID 125) ; void keyword
610 (defvar js2-RESERVED 126) ; reserved keywords
611
612 (defvar js2-EMPTY 127)
613
614 ;; Types used for the parse tree - never returned by scanner.
615
616 (defvar js2-BLOCK 128) ; statement block
617 (defvar js2-LABEL 129) ; label
618 (defvar js2-TARGET 130)
619 (defvar js2-LOOP 131)
620 (defvar js2-EXPR_VOID 132) ; expression statement in functions
621 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
622 (defvar js2-JSR 134)
623 (defvar js2-SCRIPT 135) ; top-level node for entire script
624 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
625 (defvar js2-USE_STACK 137)
626 (defvar js2-SETPROP_OP 138) ; x.y op= something
627 (defvar js2-SETELEM_OP 139) ; x[y] op= something
628 (defvar js2-LOCAL_BLOCK 140)
629 (defvar js2-SET_REF_OP 141) ; *reference op= something
630
631 ;; For XML support:
632 (defvar js2-DOTDOT 142) ; member operator (..)
633 (defvar js2-COLONCOLON 143) ; namespace::name
634 (defvar js2-XML 144) ; XML type
635 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
636 (defvar js2-XMLATTR 146) ; @
637 (defvar js2-XMLEND 147)
638
639 ;; Optimizer-only tokens
640 (defvar js2-TO_OBJECT 148)
641 (defvar js2-TO_DOUBLE 149)
642
643 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
644 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
645 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
646 (defvar js2-CONST 153)
647 (defvar js2-SETCONST 154)
648 (defvar js2-SETCONSTVAR 155)
649 (defvar js2-ARRAYCOMP 156)
650 (defvar js2-LETEXPR 157)
651 (defvar js2-WITHEXPR 158)
652 (defvar js2-DEBUGGER 159)
653
654 (defvar js2-COMMENT 160)
655 (defvar js2-ENUM 161) ; for "enum" reserved word
656 (defvar js2-TRIPLEDOT 162) ; for rest parameter
657 (defvar js2-ARROW 163) ; function arrow (=>)
658
659 (defconst js2-num-tokens (1+ js2-ARROW))
660
661 (defconst js2-debug-print-trees nil)
662
663 ;; Rhino accepts any string or stream as input. Emacs character
664 ;; processing works best in buffers, so we'll assume the input is a
665 ;; buffer. JavaScript strings can be copied into temp buffers before
666 ;; scanning them.
667
668 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
669 ;; They're the Emacs equivalent of instance variables, more or less.
670
671 (js2-deflocal js2-ts-dirty-line nil
672 "Token stream buffer-local variable.
673 Indicates stuff other than whitespace since start of line.")
674
675 (js2-deflocal js2-ts-hit-eof nil
676 "Token stream buffer-local variable.")
677
678 ;; FIXME: Unused.
679 (js2-deflocal js2-ts-line-start 0
680 "Token stream buffer-local variable.")
681
682 (js2-deflocal js2-ts-lineno 1
683 "Token stream buffer-local variable.")
684
685 ;; FIXME: Unused.
686 (js2-deflocal js2-ts-line-end-char -1
687 "Token stream buffer-local variable.")
688
689 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
690 "Token stream buffer-local variable.
691 Current scan position.")
692
693 ;; FIXME: Unused.
694 (js2-deflocal js2-ts-is-xml-attribute nil
695 "Token stream buffer-local variable.")
696
697 (js2-deflocal js2-ts-xml-is-tag-content nil
698 "Token stream buffer-local variable.")
699
700 (js2-deflocal js2-ts-xml-open-tags-count 0
701 "Token stream buffer-local variable.")
702
703 (js2-deflocal js2-ts-string-buffer nil
704 "Token stream buffer-local variable.
705 List of chars built up while scanning various tokens.")
706
707 (defstruct (js2-token
708 (:constructor nil)
709 (:constructor make-js2-token (beg)))
710 "Value returned from the token stream."
711 (type js2-EOF)
712 (beg 1)
713 (end -1)
714 (string "")
715 number
716 regexp-flags
717 comment-type
718 follows-eol-p)
719
720 (defstruct (js2-ts-state
721 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
722 (cursor js2-ts-cursor)
723 (tokens (copy-sequence js2-ti-tokens))
724 (tokens-cursor js2-ti-tokens-cursor)
725 (lookahead js2-ti-lookahead))))
726 lineno
727 cursor
728 tokens
729 tokens-cursor
730 lookahead)
731
732 ;;; Parser variables
733
734 (js2-deflocal js2-parsed-errors nil
735 "List of errors produced during scanning/parsing.")
736
737 (js2-deflocal js2-parsed-warnings nil
738 "List of warnings produced during scanning/parsing.")
739
740 (js2-deflocal js2-recover-from-parse-errors t
741 "Non-nil to continue parsing after a syntax error.
742
743 In recovery mode, the AST will be built in full, and any error
744 nodes will be flagged with appropriate error information. If
745 this flag is nil, a syntax error will result in an error being
746 signaled.
747
748 The variable is automatically buffer-local, because different
749 modes that use the parser will need different settings.")
750
751 (js2-deflocal js2-parse-hook nil
752 "List of callbacks for receiving parsing progress.")
753
754 (defvar js2-parse-finished-hook nil
755 "List of callbacks to notify when parsing finishes.
756 Not called if parsing was interrupted.")
757
758 (js2-deflocal js2-is-eval-code nil
759 "True if we're evaluating code in a string.
760 If non-nil, the tokenizer will record the token text, and the AST nodes
761 will record their source text. Off by default for IDE modes, since the
762 text is available in the buffer.")
763
764 (defvar js2-parse-ide-mode t
765 "Non-nil if the parser is being used for `js2-mode'.
766 If non-nil, the parser will set text properties for fontification
767 and the syntax table. The value should be nil when using the
768 parser as a frontend to an interpreter or byte compiler.")
769
770 ;;; Parser instance variables (buffer-local vars for js2-parse)
771
772 (defconst js2-ti-after-eol (lsh 1 16)
773 "Flag: first token of the source line.")
774
775 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
776
777 (js2-deflocal js2-compiler-generate-debug-info t)
778 (js2-deflocal js2-compiler-use-dynamic-scope nil)
779 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
780 (js2-deflocal js2-compiler-xml-available t)
781 (js2-deflocal js2-compiler-optimization-level 0)
782 (js2-deflocal js2-compiler-generating-source t)
783 (js2-deflocal js2-compiler-strict-mode nil)
784 (js2-deflocal js2-compiler-report-warning-as-error nil)
785 (js2-deflocal js2-compiler-generate-observer-count nil)
786 (js2-deflocal js2-compiler-activation-names nil)
787
788 ;; SKIP: sourceURI
789
790 ;; There's a compileFunction method in Context.java - may need it.
791 (js2-deflocal js2-called-by-compile-function nil
792 "True if `js2-parse' was called by `js2-compile-function'.
793 Will only be used when we finish implementing the interpreter.")
794
795 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
796
797 ;; SKIP: node factory - we're going to just call functions directly,
798 ;; and eventually go to a unified AST format.
799
800 (js2-deflocal js2-nesting-of-function 0)
801
802 (js2-deflocal js2-recorded-identifiers nil
803 "Tracks identifiers found during parsing.")
804
805 (js2-deflocal js2-is-in-destructuring nil
806 "True while parsing destructuring expression.")
807
808 (defcustom js2-global-externs nil
809 "A list of any extern names you'd like to consider always declared.
810 This list is global and is used by all `js2-mode' files.
811 You can create buffer-local externs list using `js2-additional-externs'.
812
813 There is also a buffer-local variable `js2-default-externs',
814 which is initialized by default to include the Ecma-262 externs
815 and the standard browser externs. The three lists are all
816 checked during highlighting."
817 :type 'list
818 :group 'js2-mode)
819
820 (js2-deflocal js2-default-externs nil
821 "Default external declarations.
822
823 These are currently only used for highlighting undeclared variables,
824 which only worries about top-level (unqualified) references.
825 As js2-mode's processing improves, we will flesh out this list.
826
827 The initial value is set to `js2-ecma-262-externs', unless some
828 of the `js2-include-?-externs' variables are set to t, in which
829 case the browser, Rhino and/or Node.js externs are also included.
830
831 See `js2-additional-externs' for more information.")
832
833 (defcustom js2-include-browser-externs t
834 "Non-nil to include browser externs in the master externs list.
835 If you work on JavaScript files that are not intended for browsers,
836 such as Mozilla Rhino server-side JavaScript, set this to nil.
837 See `js2-additional-externs' for more information about externs."
838 :type 'boolean
839 :group 'js2-mode)
840
841 (defcustom js2-include-rhino-externs nil
842 "Non-nil to include Mozilla Rhino externs in the master externs list.
843 See `js2-additional-externs' for more information about externs."
844 :type 'boolean
845 :group 'js2-mode)
846
847 (defcustom js2-include-node-externs nil
848 "Non-nil to include Node.js externs in the master externs list.
849 See `js2-additional-externs' for more information about externs."
850 :type 'boolean
851 :group 'js2-mode)
852
853 (js2-deflocal js2-additional-externs nil
854 "A buffer-local list of additional external declarations.
855 It is used to decide whether variables are considered undeclared
856 for purposes of highlighting.
857
858 Each entry is a Lisp string. The string should be the fully qualified
859 name of an external entity. All externs should be added to this list,
860 so that as js2-mode's processing improves it can take advantage of them.
861
862 You may want to declare your externs in three ways.
863 First, you can add externs that are valid for all your JavaScript files.
864 You should probably do this by adding them to `js2-global-externs', which
865 is a global list used for all js2-mode files.
866
867 Next, you can add a function to `js2-init-hook' that adds additional
868 externs appropriate for the specific file, perhaps based on its path.
869 These should go in `js2-additional-externs', which is buffer-local.
870
871 Third, you can use JSLint's global declaration, as long as
872 `js2-include-jslint-globals' is non-nil, which see.
873
874 Finally, you can add a function to `js2-post-parse-callbacks',
875 which is called after parsing completes, and `js2-mode-ast' is bound to
876 the root of the parse tree. At this stage you can set up an AST
877 node visitor using `js2-visit-ast' and examine the parse tree
878 for specific import patterns that may imply the existence of
879 other externs, possibly tied to your build system. These should also
880 be added to `js2-additional-externs'.
881
882 Your post-parse callback may of course also use the simpler and
883 faster (but perhaps less robust) approach of simply scanning the
884 buffer text for your imports, using regular expressions.")
885
886 ;; SKIP: decompiler
887 ;; SKIP: encoded-source
888
889 ;;; The following variables are per-function and should be saved/restored
890 ;;; during function parsing...
891
892 (js2-deflocal js2-current-script-or-fn nil)
893 (js2-deflocal js2-current-scope nil)
894 (js2-deflocal js2-nesting-of-with 0)
895 (js2-deflocal js2-label-set nil
896 "An alist mapping label names to nodes.")
897
898 (js2-deflocal js2-loop-set nil)
899 (js2-deflocal js2-loop-and-switch-set nil)
900 (js2-deflocal js2-has-return-value nil)
901 (js2-deflocal js2-end-flags 0)
902
903 ;;; ...end of per function variables
904
905 ;; These flags enumerate the possible ways a statement/function can
906 ;; terminate. These flags are used by endCheck() and by the Parser to
907 ;; detect inconsistent return usage.
908 ;;
909 ;; END_UNREACHED is reserved for code paths that are assumed to always be
910 ;; able to execute (example: throw, continue)
911 ;;
912 ;; END_DROPS_OFF indicates if the statement can transfer control to the
913 ;; next one. Statement such as return dont. A compound statement may have
914 ;; some branch that drops off control to the next statement.
915 ;;
916 ;; END_RETURNS indicates that the statement can return (without arguments)
917 ;; END_RETURNS_VALUE indicates that the statement can return a value.
918 ;;
919 ;; A compound statement such as
920 ;; if (condition) {
921 ;; return value;
922 ;; }
923 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
924
925 (defconst js2-end-unreached #x0)
926 (defconst js2-end-drops-off #x1)
927 (defconst js2-end-returns #x2)
928 (defconst js2-end-returns-value #x4)
929
930 ;; Rhino awkwardly passes a statementLabel parameter to the
931 ;; statementHelper() function, the main statement parser, which
932 ;; is then used by quite a few of the sub-parsers. We just make
933 ;; it a buffer-local variable and make sure it's cleaned up properly.
934 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
935
936 ;; Similarly, Rhino passes an inForInit boolean through about half
937 ;; the expression parsers. We use a dynamically-scoped variable,
938 ;; which makes it easier to funcall the parsers individually without
939 ;; worrying about whether they take the parameter or not.
940 (js2-deflocal js2-in-for-init nil)
941 (js2-deflocal js2-temp-name-counter 0)
942 (js2-deflocal js2-parse-stmt-count 0)
943
944 (defsubst js2-get-next-temp-name ()
945 (format "$%d" (incf js2-temp-name-counter)))
946
947 (defvar js2-parse-interruptable-p t
948 "Set this to nil to force parse to continue until finished.
949 This will mostly be useful for interpreters.")
950
951 (defvar js2-statements-per-pause 50
952 "Pause after this many statements to check for user input.
953 If user input is pending, stop the parse and discard the tree.
954 This makes for a smoother user experience for large files.
955 You may have to wait a second or two before the highlighting
956 and error-reporting appear, but you can always type ahead if
957 you wish. This appears to be more or less how Eclipse, IntelliJ
958 and other editors work.")
959
960 (js2-deflocal js2-record-comments t
961 "Instructs the scanner to record comments in `js2-scanned-comments'.")
962
963 (js2-deflocal js2-scanned-comments nil
964 "List of all comments from the current parse.")
965
966 (defcustom js2-mode-indent-inhibit-undo nil
967 "Non-nil to disable collection of Undo information when indenting lines.
968 Some users have requested this behavior. It's nil by default because
969 other Emacs modes don't work this way."
970 :type 'boolean
971 :group 'js2-mode)
972
973 (defcustom js2-mode-indent-ignore-first-tab nil
974 "If non-nil, ignore first TAB keypress if we look indented properly.
975 It's fairly common for users to navigate to an already-indented line
976 and press TAB for reassurance that it's been indented. For this class
977 of users, we want the first TAB press on a line to be ignored if the
978 line is already indented to one of the precomputed alternatives.
979
980 This behavior is only partly implemented. If you TAB-indent a line,
981 navigate to another line, and then navigate back, it fails to clear
982 the last-indented variable, so it thinks you've already hit TAB once,
983 and performs the indent. A full solution would involve getting on the
984 point-motion hooks for the entire buffer. If we come across another
985 use cases that requires watching point motion, I'll consider doing it.
986
987 If you set this variable to nil, then the TAB key will always change
988 the indentation of the current line, if more than one alternative
989 indentation spot exists."
990 :type 'boolean
991 :group 'js2-mode)
992
993 (defvar js2-indent-hook nil
994 "A hook for user-defined indentation rules.
995
996 Functions on this hook should expect two arguments: (LIST INDEX)
997 The LIST argument is the list of computed indentation points for
998 the current line. INDEX is the list index of the indentation point
999 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1000 indent function is not going to change the current line indentation.
1001
1002 If a hook function on this list returns a non-nil value, then
1003 `js2-bounce-indent' assumes the hook function has performed its own
1004 indentation, and will do nothing. If all hook functions on the list
1005 return nil, then `js2-bounce-indent' will use its computed indentation
1006 and reindent the line.
1007
1008 When hook functions on this hook list are called, the variable
1009 `js2-mode-ast' may or may not be set, depending on whether the
1010 parse tree is available. If the variable is nil, you can pass a
1011 callback to `js2-mode-wait-for-parse', and your callback will be
1012 called after the new parse tree is built. This can take some time
1013 in large files.")
1014
1015 (defface js2-warning
1016 `((((class color) (background light))
1017 (:underline "orange"))
1018 (((class color) (background dark))
1019 (:underline "orange"))
1020 (t (:underline t)))
1021 "Face for JavaScript warnings."
1022 :group 'js2-mode)
1023
1024 (defface js2-error
1025 `((((class color) (background light))
1026 (:foreground "red"))
1027 (((class color) (background dark))
1028 (:foreground "red"))
1029 (t (:foreground "red")))
1030 "Face for JavaScript errors."
1031 :group 'js2-mode)
1032
1033 (defface js2-jsdoc-tag
1034 '((t :foreground "SlateGray"))
1035 "Face used to highlight @whatever tags in jsdoc comments."
1036 :group 'js2-mode)
1037
1038 (defface js2-jsdoc-type
1039 '((t :foreground "SteelBlue"))
1040 "Face used to highlight {FooBar} types in jsdoc comments."
1041 :group 'js2-mode)
1042
1043 (defface js2-jsdoc-value
1044 '((t :foreground "PeachPuff3"))
1045 "Face used to highlight tag values in jsdoc comments."
1046 :group 'js2-mode)
1047
1048 (defface js2-function-param
1049 '((t :foreground "SeaGreen"))
1050 "Face used to highlight function parameters in javascript."
1051 :group 'js2-mode)
1052
1053 (defface js2-function-call
1054 '((t :inherit default))
1055 "Face used to highlight function name in calls."
1056 :group 'js2-mode)
1057
1058 (defface js2-instance-member
1059 '((t :foreground "DarkOrchid"))
1060 "Face used to highlight instance variables in javascript.
1061 Not currently used."
1062 :group 'js2-mode)
1063
1064 (defface js2-private-member
1065 '((t :foreground "PeachPuff3"))
1066 "Face used to highlight calls to private methods in javascript.
1067 Not currently used."
1068 :group 'js2-mode)
1069
1070 (defface js2-private-function-call
1071 '((t :foreground "goldenrod"))
1072 "Face used to highlight calls to private functions in javascript.
1073 Not currently used."
1074 :group 'js2-mode)
1075
1076 (defface js2-jsdoc-html-tag-name
1077 '((((class color) (min-colors 88) (background light))
1078 (:foreground "rosybrown"))
1079 (((class color) (min-colors 8) (background dark))
1080 (:foreground "yellow"))
1081 (((class color) (min-colors 8) (background light))
1082 (:foreground "magenta")))
1083 "Face used to highlight jsdoc html tag names"
1084 :group 'js2-mode)
1085
1086 (defface js2-jsdoc-html-tag-delimiter
1087 '((((class color) (min-colors 88) (background light))
1088 (:foreground "dark khaki"))
1089 (((class color) (min-colors 8) (background dark))
1090 (:foreground "green"))
1091 (((class color) (min-colors 8) (background light))
1092 (:foreground "green")))
1093 "Face used to highlight brackets in jsdoc html tags."
1094 :group 'js2-mode)
1095
1096 (defface js2-external-variable
1097 '((t :foreground "orange"))
1098 "Face used to highlight undeclared variable identifiers.")
1099
1100 (defcustom js2-init-hook nil
1101 "List of functions to be called after `js2-mode' or
1102 `js2-minor-mode' has initialized all variables, before parsing
1103 the buffer for the first time."
1104 :type 'hook
1105 :group 'js2-mode
1106 :version "20130608")
1107
1108 (defcustom js2-post-parse-callbacks nil
1109 "List of callback functions invoked after parsing finishes.
1110 Currently, the main use for this function is to add synthetic
1111 declarations to `js2-recorded-identifiers', which see."
1112 :type 'hook
1113 :group 'js2-mode)
1114
1115 (defcustom js2-highlight-external-variables t
1116 "Non-nil to highlight undeclared variable identifiers.
1117 An undeclared variable is any variable not declared with var or let
1118 in the current scope or any lexically enclosing scope. If you use
1119 such a variable, then you are either expecting it to originate from
1120 another file, or you've got a potential bug."
1121 :type 'boolean
1122 :group 'js2-mode)
1123
1124 (defcustom js2-include-jslint-globals t
1125 "Non-nil to include the identifiers from JSLint global
1126 declaration (see http://www.jslint.com/lint.html#global) in the
1127 buffer-local externs list. See `js2-additional-externs' for more
1128 information."
1129 :type 'boolean
1130 :group 'js2-mode)
1131
1132 (defvar js2-mode-map
1133 (let ((map (make-sparse-keymap)))
1134 (define-key map [mouse-1] #'js2-mode-show-node)
1135 (define-key map (kbd "M-j") #'js2-line-break)
1136 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1137 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1138 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1139 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1140 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1141 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1142 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1143 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1144 (when js2-bounce-indent-p
1145 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1146
1147 (define-key map [menu-bar javascript]
1148 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1149
1150 (define-key map [menu-bar javascript customize-js2-mode]
1151 '(menu-item "Customize js2-mode" js2-mode-customize
1152 :help "Customize the behavior of this mode"))
1153
1154 (define-key map [menu-bar javascript js2-force-refresh]
1155 '(menu-item "Force buffer refresh" js2-mode-reset
1156 :help "Re-parse the buffer from scratch"))
1157
1158 (define-key map [menu-bar javascript separator-2]
1159 '("--"))
1160
1161 (define-key map [menu-bar javascript next-error]
1162 '(menu-item "Next warning or error" next-error
1163 :enabled (and js2-mode-ast
1164 (or (js2-ast-root-errors js2-mode-ast)
1165 (js2-ast-root-warnings js2-mode-ast)))
1166 :help "Move to next warning or error"))
1167
1168 (define-key map [menu-bar javascript display-errors]
1169 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1170 :visible (not js2-mode-show-parse-errors)
1171 :help "Turn on display of warnings and errors"))
1172
1173 (define-key map [menu-bar javascript hide-errors]
1174 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1175 :visible js2-mode-show-parse-errors
1176 :help "Turn off display of warnings and errors"))
1177
1178 (define-key map [menu-bar javascript separator-1]
1179 '("--"))
1180
1181 (define-key map [menu-bar javascript js2-toggle-function]
1182 '(menu-item "Show/collapse element" js2-mode-toggle-element
1183 :help "Hide or show function body or comment"))
1184
1185 (define-key map [menu-bar javascript show-comments]
1186 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1187 :visible js2-mode-comments-hidden
1188 :help "Expand all hidden block comments"))
1189
1190 (define-key map [menu-bar javascript hide-comments]
1191 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1192 :visible (not js2-mode-comments-hidden)
1193 :help "Show block comments as /*...*/"))
1194
1195 (define-key map [menu-bar javascript show-all-functions]
1196 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1197 :visible js2-mode-functions-hidden
1198 :help "Expand all hidden function bodies"))
1199
1200 (define-key map [menu-bar javascript hide-all-functions]
1201 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1202 :visible (not js2-mode-functions-hidden)
1203 :help "Show {...} for all top-level function bodies"))
1204
1205 map)
1206 "Keymap used in `js2-mode' buffers.")
1207
1208 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1209
1210 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1211 "Matches a //-comment line. Must be first non-whitespace on line.
1212 First match-group is the leading whitespace.")
1213
1214 (defvar js2-mode-hook nil)
1215
1216 (js2-deflocal js2-mode-ast nil "Private variable.")
1217 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1218 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1219 (js2-deflocal js2-mode-parsing nil "Private variable.")
1220 (js2-deflocal js2-mode-node-overlay nil)
1221
1222 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1223 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1224
1225 (js2-deflocal js2-mode-fontifications nil "Private variable")
1226 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1227 (js2-deflocal js2-imenu-recorder nil "Private variable")
1228 (js2-deflocal js2-imenu-function-map nil "Private variable")
1229
1230 (defvar js2-paragraph-start
1231 "\\(@[[:alpha:]]+\\>\\|$\\)")
1232
1233 ;; Note that we also set a 'c-in-sws text property in html comments,
1234 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1235 (defvar js2-syntactic-ws-start
1236 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1237
1238 (defvar js2-syntactic-ws-end
1239 "\\s \\|[\n\r/]\\|\\s!")
1240
1241 (defvar js2-syntactic-eol
1242 (concat "\\s *\\(/\\*[^*\n\r]*"
1243 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1244 "\\*+/\\s *\\)*"
1245 "\\(//\\|/\\*[^*\n\r]*"
1246 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1247 "\\|\\\\$\\|$\\)")
1248 "Copied from `java-mode'. Needed for some cc-engine functions.")
1249
1250 (defvar js2-comment-prefix-regexp
1251 "//+\\|\\**")
1252
1253 (defvar js2-comment-start-skip
1254 "\\(//+\\|/\\*+\\)\\s *")
1255
1256 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1257 "Non-nil to emit status messages during parsing.")
1258
1259 (defvar js2-mode-functions-hidden nil "Private variable.")
1260 (defvar js2-mode-comments-hidden nil "Private variable.")
1261
1262 (defvar js2-mode-syntax-table
1263 (let ((table (make-syntax-table)))
1264 (c-populate-syntax-table table)
1265 table)
1266 "Syntax table used in `js2-mode' buffers.")
1267
1268 (defvar js2-mode-abbrev-table nil
1269 "Abbrev table in use in `js2-mode' buffers.")
1270 (define-abbrev-table 'js2-mode-abbrev-table ())
1271
1272 (defvar js2-mode-pending-parse-callbacks nil
1273 "List of functions waiting to be notified that parse is finished.")
1274
1275 (defvar js2-mode-last-indented-line -1)
1276
1277 ;;; Localizable error and warning messages
1278
1279 ;; Messages are copied from Rhino's Messages.properties.
1280 ;; Many of the Java-specific messages have been elided.
1281 ;; Add any js2-specific ones at the end, so we can keep
1282 ;; this file synced with changes to Rhino's.
1283
1284 (defvar js2-message-table
1285 (make-hash-table :test 'equal :size 250)
1286 "Contains localized messages for `js2-mode'.")
1287
1288 ;; TODO(stevey): construct this table at compile-time.
1289 (defmacro js2-msg (key &rest strings)
1290 `(puthash ,key (concat ,@strings)
1291 js2-message-table))
1292
1293 (defun js2-get-msg (msg-key)
1294 "Look up a localized message.
1295 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1296 the correct number of ARGS must be provided."
1297 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1298 (args (if (listp msg-key) (cdr msg-key)))
1299 (msg (gethash key js2-message-table)))
1300 (if msg
1301 (apply #'format msg args)
1302 key))) ; default to showing the key
1303
1304 (js2-msg "msg.dup.parms"
1305 "Duplicate parameter name '%s'.")
1306
1307 (js2-msg "msg.too.big.jump"
1308 "Program too complex: jump offset too big.")
1309
1310 (js2-msg "msg.too.big.index"
1311 "Program too complex: internal index exceeds 64K limit.")
1312
1313 (js2-msg "msg.while.compiling.fn"
1314 "Encountered code generation error while compiling function '%s': %s")
1315
1316 (js2-msg "msg.while.compiling.script"
1317 "Encountered code generation error while compiling script: %s")
1318
1319 ;; Context
1320 (js2-msg "msg.ctor.not.found"
1321 "Constructor for '%s' not found.")
1322
1323 (js2-msg "msg.not.ctor"
1324 "'%s' is not a constructor.")
1325
1326 ;; FunctionObject
1327 (js2-msg "msg.varargs.ctor"
1328 "Method or constructor '%s' must be static "
1329 "with the signature (Context cx, Object[] args, "
1330 "Function ctorObj, boolean inNewExpr) "
1331 "to define a variable arguments constructor.")
1332
1333 (js2-msg "msg.varargs.fun"
1334 "Method '%s' must be static with the signature "
1335 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1336 "to define a variable arguments function.")
1337
1338 (js2-msg "msg.incompat.call"
1339 "Method '%s' called on incompatible object.")
1340
1341 (js2-msg "msg.bad.parms"
1342 "Unsupported parameter type '%s' in method '%s'.")
1343
1344 (js2-msg "msg.bad.method.return"
1345 "Unsupported return type '%s' in method '%s'.")
1346
1347 (js2-msg "msg.bad.ctor.return"
1348 "Construction of objects of type '%s' is not supported.")
1349
1350 (js2-msg "msg.no.overload"
1351 "Method '%s' occurs multiple times in class '%s'.")
1352
1353 (js2-msg "msg.method.not.found"
1354 "Method '%s' not found in '%s'.")
1355
1356 ;; IRFactory
1357
1358 (js2-msg "msg.bad.for.in.lhs"
1359 "Invalid left-hand side of for..in loop.")
1360
1361 (js2-msg "msg.mult.index"
1362 "Only one variable allowed in for..in loop.")
1363
1364 (js2-msg "msg.bad.for.in.destruct"
1365 "Left hand side of for..in loop must be an array of "
1366 "length 2 to accept key/value pair.")
1367
1368 (js2-msg "msg.cant.convert"
1369 "Can't convert to type '%s'.")
1370
1371 (js2-msg "msg.bad.assign.left"
1372 "Invalid assignment left-hand side.")
1373
1374 (js2-msg "msg.bad.decr"
1375 "Invalid decerement operand.")
1376
1377 (js2-msg "msg.bad.incr"
1378 "Invalid increment operand.")
1379
1380 (js2-msg "msg.bad.yield"
1381 "yield must be in a function.")
1382
1383 (js2-msg "msg.yield.parenthesized"
1384 "yield expression must be parenthesized.")
1385
1386 ;; NativeGlobal
1387 (js2-msg "msg.cant.call.indirect"
1388 "Function '%s' must be called directly, and not by way of a "
1389 "function of another name.")
1390
1391 (js2-msg "msg.eval.nonstring"
1392 "Calling eval() with anything other than a primitive "
1393 "string value will simply return the value. "
1394 "Is this what you intended?")
1395
1396 (js2-msg "msg.eval.nonstring.strict"
1397 "Calling eval() with anything other than a primitive "
1398 "string value is not allowed in strict mode.")
1399
1400 (js2-msg "msg.bad.destruct.op"
1401 "Invalid destructuring assignment operator")
1402
1403 ;; NativeCall
1404 (js2-msg "msg.only.from.new"
1405 "'%s' may only be invoked from a `new' expression.")
1406
1407 (js2-msg "msg.deprec.ctor"
1408 "The '%s' constructor is deprecated.")
1409
1410 ;; NativeFunction
1411 (js2-msg "msg.no.function.ref.found"
1412 "no source found to decompile function reference %s")
1413
1414 (js2-msg "msg.arg.isnt.array"
1415 "second argument to Function.prototype.apply must be an array")
1416
1417 ;; NativeGlobal
1418 (js2-msg "msg.bad.esc.mask"
1419 "invalid string escape mask")
1420
1421 ;; NativeRegExp
1422 (js2-msg "msg.bad.quant"
1423 "Invalid quantifier %s")
1424
1425 (js2-msg "msg.overlarge.backref"
1426 "Overly large back reference %s")
1427
1428 (js2-msg "msg.overlarge.min"
1429 "Overly large minimum %s")
1430
1431 (js2-msg "msg.overlarge.max"
1432 "Overly large maximum %s")
1433
1434 (js2-msg "msg.zero.quant"
1435 "Zero quantifier %s")
1436
1437 (js2-msg "msg.max.lt.min"
1438 "Maximum %s less than minimum")
1439
1440 (js2-msg "msg.unterm.quant"
1441 "Unterminated quantifier %s")
1442
1443 (js2-msg "msg.unterm.paren"
1444 "Unterminated parenthetical %s")
1445
1446 (js2-msg "msg.unterm.class"
1447 "Unterminated character class %s")
1448
1449 (js2-msg "msg.bad.range"
1450 "Invalid range in character class.")
1451
1452 (js2-msg "msg.trail.backslash"
1453 "Trailing \\ in regular expression.")
1454
1455 (js2-msg "msg.re.unmatched.right.paren"
1456 "unmatched ) in regular expression.")
1457
1458 (js2-msg "msg.no.regexp"
1459 "Regular expressions are not available.")
1460
1461 (js2-msg "msg.bad.backref"
1462 "back-reference exceeds number of capturing parentheses.")
1463
1464 (js2-msg "msg.bad.regexp.compile"
1465 "Only one argument may be specified if the first "
1466 "argument to RegExp.prototype.compile is a RegExp object.")
1467
1468 ;; Parser
1469 (js2-msg "msg.got.syntax.errors"
1470 "Compilation produced %s syntax errors.")
1471
1472 (js2-msg "msg.var.redecl"
1473 "TypeError: redeclaration of var %s.")
1474
1475 (js2-msg "msg.const.redecl"
1476 "TypeError: redeclaration of const %s.")
1477
1478 (js2-msg "msg.let.redecl"
1479 "TypeError: redeclaration of variable %s.")
1480
1481 (js2-msg "msg.parm.redecl"
1482 "TypeError: redeclaration of formal parameter %s.")
1483
1484 (js2-msg "msg.fn.redecl"
1485 "TypeError: redeclaration of function %s.")
1486
1487 (js2-msg "msg.let.decl.not.in.block"
1488 "SyntaxError: let declaration not directly within block")
1489
1490 ;; NodeTransformer
1491 (js2-msg "msg.dup.label"
1492 "duplicated label")
1493
1494 (js2-msg "msg.undef.label"
1495 "undefined label")
1496
1497 (js2-msg "msg.bad.break"
1498 "unlabelled break must be inside loop or switch")
1499
1500 (js2-msg "msg.continue.outside"
1501 "continue must be inside loop")
1502
1503 (js2-msg "msg.continue.nonloop"
1504 "continue can only use labels of iteration statements")
1505
1506 (js2-msg "msg.bad.throw.eol"
1507 "Line terminator is not allowed between the throw "
1508 "keyword and throw expression.")
1509
1510 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1511 "function statement requires a name")
1512
1513 (js2-msg "msg.no.paren.parms"
1514 "missing ( before function parameters.")
1515
1516 (js2-msg "msg.no.parm"
1517 "missing formal parameter")
1518
1519 (js2-msg "msg.no.paren.after.parms"
1520 "missing ) after formal parameters")
1521
1522 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1523 "parameter without default follows parameter with default")
1524
1525 (js2-msg "msg.param.after.rest" ; added by js2-mode
1526 "parameter after rest parameter")
1527
1528 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1529 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1530
1531 (js2-msg "msg.no.brace.body"
1532 "missing '{' before function body")
1533
1534 (js2-msg "msg.no.brace.after.body"
1535 "missing } after function body")
1536
1537 (js2-msg "msg.no.paren.cond"
1538 "missing ( before condition")
1539
1540 (js2-msg "msg.no.paren.after.cond"
1541 "missing ) after condition")
1542
1543 (js2-msg "msg.no.semi.stmt"
1544 "missing ; before statement")
1545
1546 (js2-msg "msg.missing.semi"
1547 "missing ; after statement")
1548
1549 (js2-msg "msg.no.name.after.dot"
1550 "missing name after . operator")
1551
1552 (js2-msg "msg.no.name.after.coloncolon"
1553 "missing name after :: operator")
1554
1555 (js2-msg "msg.no.name.after.dotdot"
1556 "missing name after .. operator")
1557
1558 (js2-msg "msg.no.name.after.xmlAttr"
1559 "missing name after .@")
1560
1561 (js2-msg "msg.no.bracket.index"
1562 "missing ] in index expression")
1563
1564 (js2-msg "msg.no.paren.switch"
1565 "missing ( before switch expression")
1566
1567 (js2-msg "msg.no.paren.after.switch"
1568 "missing ) after switch expression")
1569
1570 (js2-msg "msg.no.brace.switch"
1571 "missing '{' before switch body")
1572
1573 (js2-msg "msg.bad.switch"
1574 "invalid switch statement")
1575
1576 (js2-msg "msg.no.colon.case"
1577 "missing : after case expression")
1578
1579 (js2-msg "msg.double.switch.default"
1580 "double default label in the switch statement")
1581
1582 (js2-msg "msg.no.while.do"
1583 "missing while after do-loop body")
1584
1585 (js2-msg "msg.no.paren.for"
1586 "missing ( after for")
1587
1588 (js2-msg "msg.no.semi.for"
1589 "missing ; after for-loop initializer")
1590
1591 (js2-msg "msg.no.semi.for.cond"
1592 "missing ; after for-loop condition")
1593
1594 (js2-msg "msg.in.after.for.name"
1595 "missing in or of after for")
1596
1597 (js2-msg "msg.no.paren.for.ctrl"
1598 "missing ) after for-loop control")
1599
1600 (js2-msg "msg.no.paren.with"
1601 "missing ( before with-statement object")
1602
1603 (js2-msg "msg.no.paren.after.with"
1604 "missing ) after with-statement object")
1605
1606 (js2-msg "msg.no.paren.after.let"
1607 "missing ( after let")
1608
1609 (js2-msg "msg.no.paren.let"
1610 "missing ) after variable list")
1611
1612 (js2-msg "msg.no.curly.let"
1613 "missing } after let statement")
1614
1615 (js2-msg "msg.bad.return"
1616 "invalid return")
1617
1618 (js2-msg "msg.no.brace.block"
1619 "missing } in compound statement")
1620
1621 (js2-msg "msg.bad.label"
1622 "invalid label")
1623
1624 (js2-msg "msg.bad.var"
1625 "missing variable name")
1626
1627 (js2-msg "msg.bad.var.init"
1628 "invalid variable initialization")
1629
1630 (js2-msg "msg.no.colon.cond"
1631 "missing : in conditional expression")
1632
1633 (js2-msg "msg.no.paren.arg"
1634 "missing ) after argument list")
1635
1636 (js2-msg "msg.no.bracket.arg"
1637 "missing ] after element list")
1638
1639 (js2-msg "msg.bad.prop"
1640 "invalid property id")
1641
1642 (js2-msg "msg.no.colon.prop"
1643 "missing : after property id")
1644
1645 (js2-msg "msg.no.brace.prop"
1646 "missing } after property list")
1647
1648 (js2-msg "msg.no.paren"
1649 "missing ) in parenthetical")
1650
1651 (js2-msg "msg.reserved.id"
1652 "'%s' is a reserved identifier")
1653
1654 (js2-msg "msg.no.paren.catch"
1655 "missing ( before catch-block condition")
1656
1657 (js2-msg "msg.bad.catchcond"
1658 "invalid catch block condition")
1659
1660 (js2-msg "msg.catch.unreachable"
1661 "any catch clauses following an unqualified catch are unreachable")
1662
1663 (js2-msg "msg.no.brace.try"
1664 "missing '{' before try block")
1665
1666 (js2-msg "msg.no.brace.catchblock"
1667 "missing '{' before catch-block body")
1668
1669 (js2-msg "msg.try.no.catchfinally"
1670 "'try' without 'catch' or 'finally'")
1671
1672 (js2-msg "msg.no.return.value"
1673 "function %s does not always return a value")
1674
1675 (js2-msg "msg.anon.no.return.value"
1676 "anonymous function does not always return a value")
1677
1678 (js2-msg "msg.return.inconsistent"
1679 "return statement is inconsistent with previous usage")
1680
1681 (js2-msg "msg.generator.returns"
1682 "TypeError: legacy generator function '%s' returns a value")
1683
1684 (js2-msg "msg.anon.generator.returns"
1685 "TypeError: anonymous legacy generator function returns a value")
1686
1687 (js2-msg "msg.syntax"
1688 "syntax error")
1689
1690 (js2-msg "msg.unexpected.eof"
1691 "Unexpected end of file")
1692
1693 (js2-msg "msg.XML.bad.form"
1694 "illegally formed XML syntax")
1695
1696 (js2-msg "msg.XML.not.available"
1697 "XML runtime not available")
1698
1699 (js2-msg "msg.too.deep.parser.recursion"
1700 "Too deep recursion while parsing")
1701
1702 (js2-msg "msg.no.side.effects"
1703 "Code has no side effects")
1704
1705 (js2-msg "msg.extra.trailing.comma"
1706 "Trailing comma is not supported in some browsers")
1707
1708 (js2-msg "msg.array.trailing.comma"
1709 "Trailing comma yields different behavior across browsers")
1710
1711 (js2-msg "msg.equal.as.assign"
1712 (concat "Test for equality (==) mistyped as assignment (=)?"
1713 " (parenthesize to suppress warning)"))
1714
1715 (js2-msg "msg.var.hides.arg"
1716 "Variable %s hides argument")
1717
1718 (js2-msg "msg.destruct.assign.no.init"
1719 "Missing = in destructuring declaration")
1720
1721 ;; ScriptRuntime
1722 (js2-msg "msg.no.properties"
1723 "%s has no properties.")
1724
1725 (js2-msg "msg.invalid.iterator"
1726 "Invalid iterator value")
1727
1728 (js2-msg "msg.iterator.primitive"
1729 "__iterator__ returned a primitive value")
1730
1731 (js2-msg "msg.assn.create.strict"
1732 "Assignment to undeclared variable %s")
1733
1734 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1735 "Undeclared variable or function '%s'")
1736
1737 (js2-msg "msg.ref.undefined.prop"
1738 "Reference to undefined property '%s'")
1739
1740 (js2-msg "msg.prop.not.found"
1741 "Property %s not found.")
1742
1743 (js2-msg "msg.invalid.type"
1744 "Invalid JavaScript value of type %s")
1745
1746 (js2-msg "msg.primitive.expected"
1747 "Primitive type expected (had %s instead)")
1748
1749 (js2-msg "msg.namespace.expected"
1750 "Namespace object expected to left of :: (found %s instead)")
1751
1752 (js2-msg "msg.null.to.object"
1753 "Cannot convert null to an object.")
1754
1755 (js2-msg "msg.undef.to.object"
1756 "Cannot convert undefined to an object.")
1757
1758 (js2-msg "msg.cyclic.value"
1759 "Cyclic %s value not allowed.")
1760
1761 (js2-msg "msg.is.not.defined"
1762 "'%s' is not defined.")
1763
1764 (js2-msg "msg.undef.prop.read"
1765 "Cannot read property '%s' from %s")
1766
1767 (js2-msg "msg.undef.prop.write"
1768 "Cannot set property '%s' of %s to '%s'")
1769
1770 (js2-msg "msg.undef.prop.delete"
1771 "Cannot delete property '%s' of %s")
1772
1773 (js2-msg "msg.undef.method.call"
1774 "Cannot call method '%s' of %s")
1775
1776 (js2-msg "msg.undef.with"
1777 "Cannot apply 'with' to %s")
1778
1779 (js2-msg "msg.isnt.function"
1780 "%s is not a function, it is %s.")
1781
1782 (js2-msg "msg.isnt.function.in"
1783 "Cannot call property %s in object %s. "
1784 "It is not a function, it is '%s'.")
1785
1786 (js2-msg "msg.function.not.found"
1787 "Cannot find function %s.")
1788
1789 (js2-msg "msg.function.not.found.in"
1790 "Cannot find function %s in object %s.")
1791
1792 (js2-msg "msg.isnt.xml.object"
1793 "%s is not an xml object.")
1794
1795 (js2-msg "msg.no.ref.to.get"
1796 "%s is not a reference to read reference value.")
1797
1798 (js2-msg "msg.no.ref.to.set"
1799 "%s is not a reference to set reference value to %s.")
1800
1801 (js2-msg "msg.no.ref.from.function"
1802 "Function %s can not be used as the left-hand "
1803 "side of assignment or as an operand of ++ or -- operator.")
1804
1805 (js2-msg "msg.bad.default.value"
1806 "Object's getDefaultValue() method returned an object.")
1807
1808 (js2-msg "msg.instanceof.not.object"
1809 "Can't use instanceof on a non-object.")
1810
1811 (js2-msg "msg.instanceof.bad.prototype"
1812 "'prototype' property of %s is not an object.")
1813
1814 (js2-msg "msg.bad.radix"
1815 "illegal radix %s.")
1816
1817 ;; ScriptableObject
1818 (js2-msg "msg.default.value"
1819 "Cannot find default value for object.")
1820
1821 (js2-msg "msg.zero.arg.ctor"
1822 "Cannot load class '%s' which has no zero-parameter constructor.")
1823
1824 (js2-msg "msg.ctor.multiple.parms"
1825 "Can't define constructor or class %s since more than "
1826 "one constructor has multiple parameters.")
1827
1828 (js2-msg "msg.extend.scriptable"
1829 "%s must extend ScriptableObject in order to define property %s.")
1830
1831 (js2-msg "msg.bad.getter.parms"
1832 "In order to define a property, getter %s must have zero "
1833 "parameters or a single ScriptableObject parameter.")
1834
1835 (js2-msg "msg.obj.getter.parms"
1836 "Expected static or delegated getter %s to take "
1837 "a ScriptableObject parameter.")
1838
1839 (js2-msg "msg.getter.static"
1840 "Getter and setter must both be static or neither be static.")
1841
1842 (js2-msg "msg.setter.return"
1843 "Setter must have void return type: %s")
1844
1845 (js2-msg "msg.setter2.parms"
1846 "Two-parameter setter must take a ScriptableObject as "
1847 "its first parameter.")
1848
1849 (js2-msg "msg.setter1.parms"
1850 "Expected single parameter setter for %s")
1851
1852 (js2-msg "msg.setter2.expected"
1853 "Expected static or delegated setter %s to take two parameters.")
1854
1855 (js2-msg "msg.setter.parms"
1856 "Expected either one or two parameters for setter.")
1857
1858 (js2-msg "msg.setter.bad.type"
1859 "Unsupported parameter type '%s' in setter '%s'.")
1860
1861 (js2-msg "msg.add.sealed"
1862 "Cannot add a property to a sealed object: %s.")
1863
1864 (js2-msg "msg.remove.sealed"
1865 "Cannot remove a property from a sealed object: %s.")
1866
1867 (js2-msg "msg.modify.sealed"
1868 "Cannot modify a property of a sealed object: %s.")
1869
1870 (js2-msg "msg.modify.readonly"
1871 "Cannot modify readonly property: %s.")
1872
1873 ;; TokenStream
1874 (js2-msg "msg.missing.exponent"
1875 "missing exponent")
1876
1877 (js2-msg "msg.caught.nfe"
1878 "number format error")
1879
1880 (js2-msg "msg.unterminated.string.lit"
1881 "unterminated string literal")
1882
1883 (js2-msg "msg.unterminated.comment"
1884 "unterminated comment")
1885
1886 (js2-msg "msg.unterminated.re.lit"
1887 "unterminated regular expression literal")
1888
1889 (js2-msg "msg.invalid.re.flag"
1890 "invalid flag after regular expression")
1891
1892 (js2-msg "msg.no.re.input.for"
1893 "no input for %s")
1894
1895 (js2-msg "msg.illegal.character"
1896 "illegal character")
1897
1898 (js2-msg "msg.invalid.escape"
1899 "invalid Unicode escape sequence")
1900
1901 (js2-msg "msg.bad.namespace"
1902 "not a valid default namespace statement. "
1903 "Syntax is: default xml namespace = EXPRESSION;")
1904
1905 ;; TokensStream warnings
1906 (js2-msg "msg.bad.octal.literal"
1907 "illegal octal literal digit %s; "
1908 "interpreting it as a decimal digit")
1909
1910 (js2-msg "msg.script.is.not.constructor"
1911 "Script objects are not constructors.")
1912
1913 ;; Arrays
1914 (js2-msg "msg.arraylength.bad"
1915 "Inappropriate array length.")
1916
1917 ;; Arrays
1918 (js2-msg "msg.arraylength.too.big"
1919 "Array length %s exceeds supported capacity limit.")
1920
1921 ;; URI
1922 (js2-msg "msg.bad.uri"
1923 "Malformed URI sequence.")
1924
1925 ;; Number
1926 (js2-msg "msg.bad.precision"
1927 "Precision %s out of range.")
1928
1929 ;; NativeGenerator
1930 (js2-msg "msg.send.newborn"
1931 "Attempt to send value to newborn generator")
1932
1933 (js2-msg "msg.already.exec.gen"
1934 "Already executing generator")
1935
1936 (js2-msg "msg.StopIteration.invalid"
1937 "StopIteration may not be changed to an arbitrary object.")
1938
1939 ;; Interpreter
1940 (js2-msg "msg.yield.closing"
1941 "Yield from closing generator")
1942
1943 ;;; Tokens Buffer
1944
1945 (defconst js2-ti-max-lookahead 2)
1946 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1947
1948 ;; Have to call `js2-init-scanner' to initialize the values.
1949 (js2-deflocal js2-ti-tokens nil)
1950 (js2-deflocal js2-ti-tokens-cursor nil)
1951 (js2-deflocal js2-ti-lookahead nil)
1952
1953 (defun js2-new-token (offset)
1954 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
1955 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
1956 (aset js2-ti-tokens js2-ti-tokens-cursor token)
1957 token))
1958
1959 (defsubst js2-current-token ()
1960 (aref js2-ti-tokens js2-ti-tokens-cursor))
1961
1962 (defsubst js2-current-token-string ()
1963 (js2-token-string (js2-current-token)))
1964
1965 (defsubst js2-current-token-type ()
1966 (js2-token-type (js2-current-token)))
1967
1968 (defsubst js2-current-token-beg ()
1969 (js2-token-beg (js2-current-token)))
1970
1971 (defsubst js2-current-token-end ()
1972 (js2-token-end (js2-current-token)))
1973
1974 (defun js2-current-token-len ()
1975 (let ((token (js2-current-token)))
1976 (- (js2-token-end token)
1977 (js2-token-beg token))))
1978
1979 (defun js2-ts-seek (state)
1980 (setq js2-ts-lineno (js2-ts-state-lineno state)
1981 js2-ts-cursor (js2-ts-state-cursor state)
1982 js2-ti-tokens (js2-ts-state-tokens state)
1983 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
1984 js2-ti-lookahead (js2-ts-state-lookahead state)))
1985
1986 ;;; Utilities
1987
1988 (defun js2-delete-if (predicate list)
1989 "Remove all items satisfying PREDICATE in LIST."
1990 (loop for item in list
1991 if (not (funcall predicate item))
1992 collect item))
1993
1994 (defun js2-position (element list)
1995 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1996 Returns nil if element is not found in the list."
1997 (let ((count 0)
1998 found)
1999 (while (and list (not found))
2000 (if (eq element (car list))
2001 (setq found t)
2002 (setq count (1+ count)
2003 list (cdr list))))
2004 (if found count)))
2005
2006 (defun js2-find-if (predicate list)
2007 "Find first item satisfying PREDICATE in LIST."
2008 (let (result)
2009 (while (and list (not result))
2010 (if (funcall predicate (car list))
2011 (setq result (car list)))
2012 (setq list (cdr list)))
2013 result))
2014
2015 (defmacro js2-time (form)
2016 "Evaluate FORM, discard result, and return elapsed time in sec."
2017 (declare (debug t))
2018 (let ((beg (make-symbol "--js2-time-beg--"))
2019 (delta (make-symbol "--js2-time-end--")))
2020 `(let ((,beg (current-time))
2021 ,delta)
2022 ,form
2023 (/ (truncate (* (- (float-time (current-time))
2024 (float-time ,beg))
2025 10000))
2026 10000.0))))
2027
2028 (defsubst js2-same-line (pos)
2029 "Return t if POS is on the same line as current point."
2030 (and (>= pos (point-at-bol))
2031 (<= pos (point-at-eol))))
2032
2033 (defun js2-code-bug ()
2034 "Signal an error when we encounter an unexpected code path."
2035 (error "failed assertion"))
2036
2037 (defsubst js2-record-text-property (beg end prop value)
2038 "Record a text property to set when parsing finishes."
2039 (push (list beg end prop value) js2-mode-deferred-properties))
2040
2041 ;; I'd like to associate errors with nodes, but for now the
2042 ;; easiest thing to do is get the context info from the last token.
2043 (defun js2-record-parse-error (msg &optional arg pos len)
2044 (push (list (list msg arg)
2045 (or pos (js2-current-token-beg))
2046 (or len (js2-current-token-len)))
2047 js2-parsed-errors))
2048
2049 (defun js2-report-error (msg &optional msg-arg pos len)
2050 "Signal a syntax error or record a parse error."
2051 (if js2-recover-from-parse-errors
2052 (js2-record-parse-error msg msg-arg pos len)
2053 (signal 'js2-syntax-error
2054 (list msg
2055 js2-ts-lineno
2056 (save-excursion
2057 (goto-char js2-ts-cursor)
2058 (current-column))
2059 js2-ts-hit-eof))))
2060
2061 (defun js2-report-warning (msg &optional msg-arg pos len face)
2062 (if js2-compiler-report-warning-as-error
2063 (js2-report-error msg msg-arg pos len)
2064 (push (list (list msg msg-arg)
2065 (or pos (js2-current-token-beg))
2066 (or len (js2-current-token-len))
2067 face)
2068 js2-parsed-warnings)))
2069
2070 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2071 (if js2-compiler-strict-mode
2072 (js2-report-warning msg-id msg-arg beg
2073 (and beg end (- end beg)))))
2074
2075 (put 'js2-syntax-error 'error-conditions
2076 '(error syntax-error js2-syntax-error))
2077 (put 'js2-syntax-error 'error-message "Syntax error")
2078
2079 (put 'js2-parse-error 'error-conditions
2080 '(error parse-error js2-parse-error))
2081 (put 'js2-parse-error 'error-message "Parse error")
2082
2083 (defmacro js2-clear-flag (flags flag)
2084 `(setq ,flags (logand ,flags (lognot ,flag))))
2085
2086 (defmacro js2-set-flag (flags flag)
2087 "Logical-or FLAG into FLAGS."
2088 `(setq ,flags (logior ,flags ,flag)))
2089
2090 (defsubst js2-flag-set-p (flags flag)
2091 (/= 0 (logand flags flag)))
2092
2093 (defsubst js2-flag-not-set-p (flags flag)
2094 (zerop (logand flags flag)))
2095
2096 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2097 "Evaluate BODY with the _ character set to be word-syntax."
2098 (declare (indent 0) (debug t))
2099 (let ((old-syntax (make-symbol "old-syntax")))
2100 `(let ((,old-syntax (string (char-syntax ?_))))
2101 (unwind-protect
2102 (progn
2103 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2104 ,@body)
2105 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2106
2107 ;;; AST struct and function definitions
2108
2109 ;; flags for ast node property 'member-type (used for e4x operators)
2110 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2111 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2112 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2113
2114 (defsubst js2-relpos (pos anchor)
2115 "Convert POS to be relative to ANCHOR.
2116 If POS is nil, returns nil."
2117 (and pos (- pos anchor)))
2118
2119 (defun js2-make-pad (indent)
2120 (if (zerop indent)
2121 ""
2122 (make-string (* indent js2-basic-offset) ? )))
2123
2124 (defun js2-visit-ast (node callback)
2125 "Visit every node in ast NODE with visitor CALLBACK.
2126
2127 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2128 called twice: once to visit the node, and again after all the node's
2129 children have been processed. The END-P argument is nil on the first
2130 call and non-nil on the second call. The return value of the callback
2131 affects the traversal: if non-nil, the children of NODE are processed.
2132 If the callback returns nil, or if the node has no children, then the
2133 callback is called immediately with a non-nil END-P argument.
2134
2135 The node traversal is approximately lexical-order, although there
2136 are currently no guarantees around this."
2137 (when node
2138 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2139 ;; visit the node
2140 (when (funcall callback node nil)
2141 ;; visit the kids
2142 (cond
2143 ((eq vfunc 'js2-visit-none)
2144 nil) ; don't even bother calling it
2145 ;; Each AST node type has to define a `js2-visitor' function
2146 ;; that takes a node and a callback, and calls `js2-visit-ast'
2147 ;; on each child of the node.
2148 (vfunc
2149 (funcall vfunc node callback))
2150 (t
2151 (error "%s does not define a visitor-traversal function"
2152 (aref node 0)))))
2153 ;; call the end-visit
2154 (funcall callback node t))))
2155
2156 (defstruct (js2-node
2157 (:constructor nil)) ; abstract
2158 "Base AST node type."
2159 (type -1) ; token type
2160 (pos -1) ; start position of this AST node in parsed input
2161 (len 1) ; num characters spanned by the node
2162 props ; optional node property list (an alist)
2163 parent) ; link to parent node; null for root
2164
2165 (defsubst js2-node-get-prop (node prop &optional default)
2166 (or (cadr (assoc prop (js2-node-props node))) default))
2167
2168 (defsubst js2-node-set-prop (node prop value)
2169 (setf (js2-node-props node)
2170 (cons (list prop value) (js2-node-props node))))
2171
2172 (defun js2-fixup-starts (n nodes)
2173 "Adjust the start positions of NODES to be relative to N.
2174 Any node in the list may be nil, for convenience."
2175 (dolist (node nodes)
2176 (when node
2177 (setf (js2-node-pos node) (- (js2-node-pos node)
2178 (js2-node-pos n))))))
2179
2180 (defun js2-node-add-children (parent &rest nodes)
2181 "Set parent node of NODES to PARENT, and return PARENT.
2182 Does nothing if we're not recording parent links.
2183 If any given node in NODES is nil, doesn't record that link."
2184 (js2-fixup-starts parent nodes)
2185 (dolist (node nodes)
2186 (and node
2187 (setf (js2-node-parent node) parent))))
2188
2189 ;; Non-recursive since it's called a frightening number of times.
2190 (defun js2-node-abs-pos (n)
2191 (let ((pos (js2-node-pos n)))
2192 (while (setq n (js2-node-parent n))
2193 (setq pos (+ pos (js2-node-pos n))))
2194 pos))
2195
2196 (defsubst js2-node-abs-end (n)
2197 "Return absolute buffer position of end of N."
2198 (+ (js2-node-abs-pos n) (js2-node-len n)))
2199
2200 ;; It's important to make sure block nodes have a Lisp list for the
2201 ;; child nodes, to limit printing recursion depth in an AST that
2202 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2203 ;; a sufficiently large vector tree.
2204
2205 (defstruct (js2-block-node
2206 (:include js2-node)
2207 (:constructor nil)
2208 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2209 (pos (js2-current-token-beg))
2210 len
2211 props
2212 kids)))
2213 "A block of statements."
2214 kids) ; a Lisp list of the child statement nodes
2215
2216 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2217 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2218
2219 (defun js2-visit-block (ast callback)
2220 "Visit the `js2-block-node' children of AST."
2221 (dolist (kid (js2-block-node-kids ast))
2222 (js2-visit-ast kid callback)))
2223
2224 (defun js2-print-block (n i)
2225 (let ((pad (js2-make-pad i)))
2226 (insert pad "{\n")
2227 (dolist (kid (js2-block-node-kids n))
2228 (js2-print-ast kid (1+ i)))
2229 (insert pad "}")))
2230
2231 (defstruct (js2-scope
2232 (:include js2-block-node)
2233 (:constructor nil)
2234 (:constructor make-js2-scope (&key (type js2-BLOCK)
2235 (pos (js2-current-token-beg))
2236 len
2237 kids)))
2238 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2239 ;; I don't have one of those handy, so I'll use an alist for now.
2240 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2241 ;; and is much lighter-weight to construct (both CPU and mem).
2242 ;; The keys are interned strings (symbols) for faster lookup.
2243 ;; Should switch to hybrid alist/hashtable eventually.
2244 symbol-table ; an alist of (symbol . js2-symbol)
2245 parent-scope ; a `js2-scope'
2246 top) ; top-level `js2-scope' (script/function)
2247
2248 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2249 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2250
2251 (defun js2-node-get-enclosing-scope (node)
2252 "Return the innermost `js2-scope' node surrounding NODE.
2253 Returns nil if there is no enclosing scope node."
2254 (let ((parent (js2-node-parent node)))
2255 (while (not (js2-scope-p parent))
2256 (setq parent (js2-node-parent parent)))
2257 parent))
2258
2259 (defun js2-get-defining-scope (scope name)
2260 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2261 Returns `js2-scope' in which NAME is defined, or nil if not found."
2262 (let ((sym (if (symbolp name)
2263 name
2264 (intern name)))
2265 table
2266 result
2267 (continue t))
2268 (while (and scope continue)
2269 (if (and (setq table (js2-scope-symbol-table scope))
2270 (assq sym table))
2271 (setq continue nil
2272 result scope)
2273 (setq scope (js2-scope-parent-scope scope))))
2274 result))
2275
2276 (defun js2-scope-get-symbol (scope name)
2277 "Return symbol table entry for NAME in SCOPE.
2278 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2279 (and (js2-scope-symbol-table scope)
2280 (cdr (assq (if (symbolp name)
2281 name
2282 (intern name))
2283 (js2-scope-symbol-table scope)))))
2284
2285 (defun js2-scope-put-symbol (scope name symbol)
2286 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2287 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2288 (let* ((table (js2-scope-symbol-table scope))
2289 (sym (if (symbolp name) name (intern name)))
2290 (entry (assq sym table)))
2291 (if entry
2292 (setcdr entry symbol)
2293 (push (cons sym symbol)
2294 (js2-scope-symbol-table scope)))))
2295
2296 (defstruct (js2-symbol
2297 (:constructor nil)
2298 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2299 "A symbol table entry."
2300 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2301 ;; js2-LET, or js2-CONST
2302 decl-type
2303 name ; string
2304 ast-node) ; a `js2-node'
2305
2306 (defstruct (js2-error-node
2307 (:include js2-node)
2308 (:constructor nil) ; silence emacs21 byte-compiler
2309 (:constructor make-js2-error-node (&key (type js2-ERROR)
2310 (pos (js2-current-token-beg))
2311 len)))
2312 "AST node representing a parse error.")
2313
2314 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2315 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2316
2317 (defstruct (js2-script-node
2318 (:include js2-scope)
2319 (:constructor nil)
2320 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2321 (pos (js2-current-token-beg))
2322 len
2323 ;; FIXME: What are those?
2324 var-decls
2325 fun-decls)))
2326 functions ; Lisp list of nested functions
2327 regexps ; Lisp list of (string . flags)
2328 symbols ; alist (every symbol gets unique index)
2329 (param-count 0)
2330 var-names ; vector of string names
2331 consts ; bool-vector matching var-decls
2332 (temp-number 0)) ; for generating temp variables
2333
2334 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2335 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2336
2337 (defun js2-print-script (node indent)
2338 (dolist (kid (js2-block-node-kids node))
2339 (js2-print-ast kid indent)))
2340
2341 (defstruct (js2-ast-root
2342 (:include js2-script-node)
2343 (:constructor nil)
2344 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2345 (pos (js2-current-token-beg))
2346 len
2347 buffer)))
2348 "The root node of a js2 AST."
2349 buffer ; the source buffer from which the code was parsed
2350 comments ; a Lisp list of comments, ordered by start position
2351 errors ; a Lisp list of errors found during parsing
2352 warnings ; a Lisp list of warnings found during parsing
2353 node-count) ; number of nodes in the tree, including the root
2354
2355 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2356 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2357
2358 (defun js2-visit-ast-root (ast callback)
2359 (dolist (kid (js2-ast-root-kids ast))
2360 (js2-visit-ast kid callback))
2361 (dolist (comment (js2-ast-root-comments ast))
2362 (js2-visit-ast comment callback)))
2363
2364 (defstruct (js2-comment-node
2365 (:include js2-node)
2366 (:constructor nil)
2367 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2368 (pos (js2-current-token-beg))
2369 len
2370 format)))
2371 format) ; 'line, 'block, 'jsdoc or 'html
2372
2373 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2374 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2375
2376 (defun js2-print-comment (n i)
2377 ;; We really ought to link end-of-line comments to their nodes.
2378 ;; Or maybe we could add a new comment type, 'endline.
2379 (insert (js2-make-pad i)
2380 (js2-node-string n)))
2381
2382 (defstruct (js2-expr-stmt-node
2383 (:include js2-node)
2384 (:constructor nil)
2385 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2386 (pos js2-ts-cursor)
2387 len
2388 expr)))
2389 "An expression statement."
2390 expr)
2391
2392 (defsubst js2-expr-stmt-node-set-has-result (node)
2393 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2394 (setf (js2-node-type node) js2-EXPR_RESULT))
2395
2396 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2397 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2398
2399 (defun js2-visit-expr-stmt-node (n v)
2400 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2401
2402 (defun js2-print-expr-stmt-node (n indent)
2403 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2404 (insert ";\n"))
2405
2406 (defstruct (js2-loop-node
2407 (:include js2-scope)
2408 (:constructor nil))
2409 "Abstract supertype of loop nodes."
2410 body ; a `js2-block-node'
2411 lp ; position of left-paren, nil if omitted
2412 rp) ; position of right-paren, nil if omitted
2413
2414 (defstruct (js2-do-node
2415 (:include js2-loop-node)
2416 (:constructor nil)
2417 (:constructor make-js2-do-node (&key (type js2-DO)
2418 (pos (js2-current-token-beg))
2419 len
2420 body
2421 condition
2422 while-pos
2423 lp
2424 rp)))
2425 "AST node for do-loop."
2426 condition ; while (expression)
2427 while-pos) ; buffer position of 'while' keyword
2428
2429 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2430 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2431
2432 (defun js2-visit-do-node (n v)
2433 (js2-visit-ast (js2-do-node-body n) v)
2434 (js2-visit-ast (js2-do-node-condition n) v))
2435
2436 (defun js2-print-do-node (n i)
2437 (let ((pad (js2-make-pad i)))
2438 (insert pad "do {\n")
2439 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2440 (js2-print-ast kid (1+ i)))
2441 (insert pad "} while (")
2442 (js2-print-ast (js2-do-node-condition n) 0)
2443 (insert ");\n")))
2444
2445 (defstruct (js2-while-node
2446 (:include js2-loop-node)
2447 (:constructor nil)
2448 (:constructor make-js2-while-node (&key (type js2-WHILE)
2449 (pos (js2-current-token-beg))
2450 len body
2451 condition lp
2452 rp)))
2453 "AST node for while-loop."
2454 condition) ; while-condition
2455
2456 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2457 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2458
2459 (defun js2-visit-while-node (n v)
2460 (js2-visit-ast (js2-while-node-condition n) v)
2461 (js2-visit-ast (js2-while-node-body n) v))
2462
2463 (defun js2-print-while-node (n i)
2464 (let ((pad (js2-make-pad i)))
2465 (insert pad "while (")
2466 (js2-print-ast (js2-while-node-condition n) 0)
2467 (insert ") {\n")
2468 (js2-print-body (js2-while-node-body n) (1+ i))
2469 (insert pad "}\n")))
2470
2471 (defstruct (js2-for-node
2472 (:include js2-loop-node)
2473 (:constructor nil)
2474 (:constructor make-js2-for-node (&key (type js2-FOR)
2475 (pos js2-ts-cursor)
2476 len body init
2477 condition
2478 update lp rp)))
2479 "AST node for a C-style for-loop."
2480 init ; initialization expression
2481 condition ; loop condition
2482 update) ; update clause
2483
2484 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2485 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2486
2487 (defun js2-visit-for-node (n v)
2488 (js2-visit-ast (js2-for-node-init n) v)
2489 (js2-visit-ast (js2-for-node-condition n) v)
2490 (js2-visit-ast (js2-for-node-update n) v)
2491 (js2-visit-ast (js2-for-node-body n) v))
2492
2493 (defun js2-print-for-node (n i)
2494 (let ((pad (js2-make-pad i)))
2495 (insert pad "for (")
2496 (js2-print-ast (js2-for-node-init n) 0)
2497 (insert "; ")
2498 (js2-print-ast (js2-for-node-condition n) 0)
2499 (insert "; ")
2500 (js2-print-ast (js2-for-node-update n) 0)
2501 (insert ") {\n")
2502 (js2-print-body (js2-for-node-body n) (1+ i))
2503 (insert pad "}\n")))
2504
2505 (defstruct (js2-for-in-node
2506 (:include js2-loop-node)
2507 (:constructor nil)
2508 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2509 (pos js2-ts-cursor)
2510 len body
2511 iterator
2512 object
2513 in-pos
2514 each-pos
2515 foreach-p forof-p
2516 lp rp)))
2517 "AST node for a for..in loop."
2518 iterator ; [var] foo in ...
2519 object ; object over which we're iterating
2520 in-pos ; buffer position of 'in' keyword
2521 each-pos ; buffer position of 'each' keyword, if foreach-p
2522 foreach-p ; t if it's a for-each loop
2523 forof-p) ; t if it's a for-of loop
2524
2525 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2526 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2527
2528 (defun js2-visit-for-in-node (n v)
2529 (js2-visit-ast (js2-for-in-node-iterator n) v)
2530 (js2-visit-ast (js2-for-in-node-object n) v)
2531 (js2-visit-ast (js2-for-in-node-body n) v))
2532
2533 (defun js2-print-for-in-node (n i)
2534 (let ((pad (js2-make-pad i))
2535 (foreach (js2-for-in-node-foreach-p n))
2536 (forof (js2-for-in-node-forof-p n)))
2537 (insert pad "for ")
2538 (if foreach
2539 (insert "each "))
2540 (insert "(")
2541 (js2-print-ast (js2-for-in-node-iterator n) 0)
2542 (insert (if forof " of " " in "))
2543 (js2-print-ast (js2-for-in-node-object n) 0)
2544 (insert ") {\n")
2545 (js2-print-body (js2-for-in-node-body n) (1+ i))
2546 (insert pad "}\n")))
2547
2548 (defstruct (js2-return-node
2549 (:include js2-node)
2550 (:constructor nil)
2551 (:constructor make-js2-return-node (&key (type js2-RETURN)
2552 (pos js2-ts-cursor)
2553 len
2554 retval)))
2555 "AST node for a return statement."
2556 retval) ; expression to return, or 'undefined
2557
2558 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2559 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2560
2561 (defun js2-visit-return-node (n v)
2562 (js2-visit-ast (js2-return-node-retval n) v))
2563
2564 (defun js2-print-return-node (n i)
2565 (insert (js2-make-pad i) "return")
2566 (when (js2-return-node-retval n)
2567 (insert " ")
2568 (js2-print-ast (js2-return-node-retval n) 0))
2569 (insert ";\n"))
2570
2571 (defstruct (js2-if-node
2572 (:include js2-node)
2573 (:constructor nil)
2574 (:constructor make-js2-if-node (&key (type js2-IF)
2575 (pos js2-ts-cursor)
2576 len condition
2577 then-part
2578 else-pos
2579 else-part lp
2580 rp)))
2581 "AST node for an if-statement."
2582 condition ; expression
2583 then-part ; statement or block
2584 else-pos ; optional buffer position of 'else' keyword
2585 else-part ; optional statement or block
2586 lp ; position of left-paren, nil if omitted
2587 rp) ; position of right-paren, nil if omitted
2588
2589 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2590 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2591
2592 (defun js2-visit-if-node (n v)
2593 (js2-visit-ast (js2-if-node-condition n) v)
2594 (js2-visit-ast (js2-if-node-then-part n) v)
2595 (js2-visit-ast (js2-if-node-else-part n) v))
2596
2597 (defun js2-print-if-node (n i)
2598 (let ((pad (js2-make-pad i))
2599 (then-part (js2-if-node-then-part n))
2600 (else-part (js2-if-node-else-part n)))
2601 (insert pad "if (")
2602 (js2-print-ast (js2-if-node-condition n) 0)
2603 (insert ") {\n")
2604 (js2-print-body then-part (1+ i))
2605 (insert pad "}")
2606 (cond
2607 ((not else-part)
2608 (insert "\n"))
2609 ((js2-if-node-p else-part)
2610 (insert " else ")
2611 (js2-print-body else-part i))
2612 (t
2613 (insert " else {\n")
2614 (js2-print-body else-part (1+ i))
2615 (insert pad "}\n")))))
2616
2617 (defstruct (js2-try-node
2618 (:include js2-node)
2619 (:constructor nil)
2620 (:constructor make-js2-try-node (&key (type js2-TRY)
2621 (pos js2-ts-cursor)
2622 len
2623 try-block
2624 catch-clauses
2625 finally-block)))
2626 "AST node for a try-statement."
2627 try-block
2628 catch-clauses ; a Lisp list of `js2-catch-node'
2629 finally-block) ; a `js2-finally-node'
2630
2631 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2632 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2633
2634 (defun js2-visit-try-node (n v)
2635 (js2-visit-ast (js2-try-node-try-block n) v)
2636 (dolist (clause (js2-try-node-catch-clauses n))
2637 (js2-visit-ast clause v))
2638 (js2-visit-ast (js2-try-node-finally-block n) v))
2639
2640 (defun js2-print-try-node (n i)
2641 (let ((pad (js2-make-pad i))
2642 (catches (js2-try-node-catch-clauses n))
2643 (finally (js2-try-node-finally-block n)))
2644 (insert pad "try {\n")
2645 (js2-print-body (js2-try-node-try-block n) (1+ i))
2646 (insert pad "}")
2647 (when catches
2648 (dolist (catch catches)
2649 (js2-print-ast catch i)))
2650 (if finally
2651 (js2-print-ast finally i)
2652 (insert "\n"))))
2653
2654 (defstruct (js2-catch-node
2655 (:include js2-node)
2656 (:constructor nil)
2657 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2658 (pos js2-ts-cursor)
2659 len
2660 param
2661 guard-kwd
2662 guard-expr
2663 block lp
2664 rp)))
2665 "AST node for a catch clause."
2666 param ; destructuring form or simple name node
2667 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2668 guard-expr ; catch condition, a `js2-node'
2669 block ; statements, a `js2-block-node'
2670 lp ; buffer position of left-paren, nil if omitted
2671 rp) ; buffer position of right-paren, nil if omitted
2672
2673 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2674 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2675
2676 (defun js2-visit-catch-node (n v)
2677 (js2-visit-ast (js2-catch-node-param n) v)
2678 (when (js2-catch-node-guard-kwd n)
2679 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2680 (js2-visit-ast (js2-catch-node-block n) v))
2681
2682 (defun js2-print-catch-node (n i)
2683 (let ((pad (js2-make-pad i))
2684 (guard-kwd (js2-catch-node-guard-kwd n))
2685 (guard-expr (js2-catch-node-guard-expr n)))
2686 (insert " catch (")
2687 (js2-print-ast (js2-catch-node-param n) 0)
2688 (when guard-kwd
2689 (insert " if ")
2690 (js2-print-ast guard-expr 0))
2691 (insert ") {\n")
2692 (js2-print-body (js2-catch-node-block n) (1+ i))
2693 (insert pad "}")))
2694
2695 (defstruct (js2-finally-node
2696 (:include js2-node)
2697 (:constructor nil)
2698 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2699 (pos js2-ts-cursor)
2700 len body)))
2701 "AST node for a finally clause."
2702 body) ; a `js2-node', often but not always a block node
2703
2704 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2705 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2706
2707 (defun js2-visit-finally-node (n v)
2708 (js2-visit-ast (js2-finally-node-body n) v))
2709
2710 (defun js2-print-finally-node (n i)
2711 (let ((pad (js2-make-pad i)))
2712 (insert " finally {\n")
2713 (js2-print-body (js2-finally-node-body n) (1+ i))
2714 (insert pad "}\n")))
2715
2716 (defstruct (js2-switch-node
2717 (:include js2-node)
2718 (:constructor nil)
2719 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2720 (pos js2-ts-cursor)
2721 len
2722 discriminant
2723 cases lp
2724 rp)))
2725 "AST node for a switch statement."
2726 discriminant ; a `js2-node' (switch expression)
2727 cases ; a Lisp list of `js2-case-node'
2728 lp ; position of open-paren for discriminant, nil if omitted
2729 rp) ; position of close-paren for discriminant, nil if omitted
2730
2731 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2732 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2733
2734 (defun js2-visit-switch-node (n v)
2735 (js2-visit-ast (js2-switch-node-discriminant n) v)
2736 (dolist (c (js2-switch-node-cases n))
2737 (js2-visit-ast c v)))
2738
2739 (defun js2-print-switch-node (n i)
2740 (let ((pad (js2-make-pad i))
2741 (cases (js2-switch-node-cases n)))
2742 (insert pad "switch (")
2743 (js2-print-ast (js2-switch-node-discriminant n) 0)
2744 (insert ") {\n")
2745 (dolist (case cases)
2746 (js2-print-ast case i))
2747 (insert pad "}\n")))
2748
2749 (defstruct (js2-case-node
2750 (:include js2-block-node)
2751 (:constructor nil)
2752 (:constructor make-js2-case-node (&key (type js2-CASE)
2753 (pos js2-ts-cursor)
2754 len kids expr)))
2755 "AST node for a case clause of a switch statement."
2756 expr) ; the case expression (nil for default)
2757
2758 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2759 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2760
2761 (defun js2-visit-case-node (n v)
2762 (js2-visit-ast (js2-case-node-expr n) v)
2763 (js2-visit-block n v))
2764
2765 (defun js2-print-case-node (n i)
2766 (let ((pad (js2-make-pad i))
2767 (expr (js2-case-node-expr n)))
2768 (insert pad)
2769 (if (null expr)
2770 (insert "default:\n")
2771 (insert "case ")
2772 (js2-print-ast expr 0)
2773 (insert ":\n"))
2774 (dolist (kid (js2-case-node-kids n))
2775 (js2-print-ast kid (1+ i)))))
2776
2777 (defstruct (js2-throw-node
2778 (:include js2-node)
2779 (:constructor nil)
2780 (:constructor make-js2-throw-node (&key (type js2-THROW)
2781 (pos js2-ts-cursor)
2782 len expr)))
2783 "AST node for a throw statement."
2784 expr) ; the expression to throw
2785
2786 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2787 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2788
2789 (defun js2-visit-throw-node (n v)
2790 (js2-visit-ast (js2-throw-node-expr n) v))
2791
2792 (defun js2-print-throw-node (n i)
2793 (insert (js2-make-pad i) "throw ")
2794 (js2-print-ast (js2-throw-node-expr n) 0)
2795 (insert ";\n"))
2796
2797 (defstruct (js2-with-node
2798 (:include js2-node)
2799 (:constructor nil)
2800 (:constructor make-js2-with-node (&key (type js2-WITH)
2801 (pos js2-ts-cursor)
2802 len object
2803 body lp rp)))
2804 "AST node for a with-statement."
2805 object
2806 body
2807 lp ; buffer position of left-paren around object, nil if omitted
2808 rp) ; buffer position of right-paren around object, nil if omitted
2809
2810 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2811 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2812
2813 (defun js2-visit-with-node (n v)
2814 (js2-visit-ast (js2-with-node-object n) v)
2815 (js2-visit-ast (js2-with-node-body n) v))
2816
2817 (defun js2-print-with-node (n i)
2818 (let ((pad (js2-make-pad i)))
2819 (insert pad "with (")
2820 (js2-print-ast (js2-with-node-object n) 0)
2821 (insert ") {\n")
2822 (js2-print-body (js2-with-node-body n) (1+ i))
2823 (insert pad "}\n")))
2824
2825 (defstruct (js2-label-node
2826 (:include js2-node)
2827 (:constructor nil)
2828 (:constructor make-js2-label-node (&key (type js2-LABEL)
2829 (pos js2-ts-cursor)
2830 len name)))
2831 "AST node for a statement label or case label."
2832 name ; a string
2833 loop) ; for validating and code-generating continue-to-label
2834
2835 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2836 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2837
2838 (defun js2-print-label (n i)
2839 (insert (js2-make-pad i)
2840 (js2-label-node-name n)
2841 ":\n"))
2842
2843 (defstruct (js2-labeled-stmt-node
2844 (:include js2-node)
2845 (:constructor nil)
2846 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2847 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2848 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2849 (pos js2-ts-cursor)
2850 len labels stmt)))
2851 "AST node for a statement with one or more labels.
2852 Multiple labels for a statement are collapsed into the labels field."
2853 labels ; Lisp list of `js2-label-node'
2854 stmt) ; the statement these labels are for
2855
2856 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2857 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2858
2859 (defun js2-get-label-by-name (lbl-stmt name)
2860 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2861 Returns nil if no such label is in the list."
2862 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2863 result)
2864 (while (and label-list (not result))
2865 (if (string= (js2-label-node-name (car label-list)) name)
2866 (setq result (car label-list))
2867 (setq label-list (cdr label-list))))
2868 result))
2869
2870 (defun js2-visit-labeled-stmt (n v)
2871 (dolist (label (js2-labeled-stmt-node-labels n))
2872 (js2-visit-ast label v))
2873 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2874
2875 (defun js2-print-labeled-stmt (n i)
2876 (dolist (label (js2-labeled-stmt-node-labels n))
2877 (js2-print-ast label i))
2878 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
2879
2880 (defun js2-labeled-stmt-node-contains (node label)
2881 "Return t if NODE contains LABEL in its label set.
2882 NODE is a `js2-labels-node'. LABEL is an identifier."
2883 (loop for nl in (js2-labeled-stmt-node-labels node)
2884 if (string= label (js2-label-node-name nl))
2885 return t
2886 finally return nil))
2887
2888 (defsubst js2-labeled-stmt-node-add-label (node label)
2889 "Add a `js2-label-node' to the label set for this statement."
2890 (setf (js2-labeled-stmt-node-labels node)
2891 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2892
2893 (defstruct (js2-jump-node
2894 (:include js2-node)
2895 (:constructor nil))
2896 "Abstract supertype of break and continue nodes."
2897 label ; `js2-name-node' for location of label identifier, if present
2898 target) ; target js2-labels-node or loop/switch statement
2899
2900 (defun js2-visit-jump-node (n v)
2901 ;; We don't visit the target, since it's a back-link.
2902 (js2-visit-ast (js2-jump-node-label n) v))
2903
2904 (defstruct (js2-break-node
2905 (:include js2-jump-node)
2906 (:constructor nil)
2907 (:constructor make-js2-break-node (&key (type js2-BREAK)
2908 (pos js2-ts-cursor)
2909 len label target)))
2910 "AST node for a break statement.
2911 The label field is a `js2-name-node', possibly nil, for the named label
2912 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2913 is the target of the break - a label node or enclosing loop/switch statement.")
2914
2915 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2916 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2917
2918 (defun js2-print-break-node (n i)
2919 (insert (js2-make-pad i) "break")
2920 (when (js2-break-node-label n)
2921 (insert " ")
2922 (js2-print-ast (js2-break-node-label n) 0))
2923 (insert ";\n"))
2924
2925 (defstruct (js2-continue-node
2926 (:include js2-jump-node)
2927 (:constructor nil)
2928 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2929 (pos js2-ts-cursor)
2930 len label target)))
2931 "AST node for a continue statement.
2932 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2933 It is nil if continue specifies no label. The target field is the jump target:
2934 a `js2-label-node' or the innermost enclosing loop.")
2935
2936 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2937 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2938
2939 (defun js2-print-continue-node (n i)
2940 (insert (js2-make-pad i) "continue")
2941 (when (js2-continue-node-label n)
2942 (insert " ")
2943 (js2-print-ast (js2-continue-node-label n) 0))
2944 (insert ";\n"))
2945
2946 (defstruct (js2-function-node
2947 (:include js2-script-node)
2948 (:constructor nil)
2949 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2950 (pos js2-ts-cursor)
2951 len
2952 (ftype 'FUNCTION)
2953 (form 'FUNCTION_STATEMENT)
2954 (name "")
2955 params rest-p
2956 body
2957 generator-type
2958 lp rp)))
2959 "AST node for a function declaration.
2960 The `params' field is a Lisp list of nodes. Each node is either a simple
2961 `js2-name-node', or if it's a destructuring-assignment parameter, a
2962 `js2-array-node' or `js2-object-node'."
2963 ftype ; FUNCTION, GETTER or SETTER
2964 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
2965 name ; function name (a `js2-name-node', or nil if anonymous)
2966 params ; a Lisp list of destructuring forms or simple name nodes
2967 rest-p ; if t, the last parameter is rest parameter
2968 body ; a `js2-block-node' or expression node (1.8 only)
2969 lp ; position of arg-list open-paren, or nil if omitted
2970 rp ; position of arg-list close-paren, or nil if omitted
2971 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2972 needs-activation ; t if we need an activation object for this frame
2973 generator-type ; STAR, LEGACY, COMPREHENSION or nil
2974 member-expr) ; nonstandard Ecma extension from Rhino
2975
2976 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2977 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2978
2979 (defun js2-visit-function-node (n v)
2980 (js2-visit-ast (js2-function-node-name n) v)
2981 (dolist (p (js2-function-node-params n))
2982 (js2-visit-ast p v))
2983 (js2-visit-ast (js2-function-node-body n) v))
2984
2985 (defun js2-print-function-node (n i)
2986 (let* ((pad (js2-make-pad i))
2987 (getter (js2-node-get-prop n 'GETTER_SETTER))
2988 (name (or (js2-function-node-name n)
2989 (js2-function-node-member-expr n)))
2990 (params (js2-function-node-params n))
2991 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
2992 (rest-p (js2-function-node-rest-p n))
2993 (body (js2-function-node-body n))
2994 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
2995 (unless (or getter arrow)
2996 (insert pad "function")
2997 (when (eq (js2-function-node-generator-type n) 'STAR)
2998 (insert "*")))
2999 (when name
3000 (insert " ")
3001 (js2-print-ast name 0))
3002 (insert "(")
3003 (loop with len = (length params)
3004 for param in params
3005 for count from 1
3006 do
3007 (when (and rest-p (= count len))
3008 (insert "..."))
3009 (js2-print-ast param 0)
3010 (when (< count len)
3011 (insert ", ")))
3012 (insert ") ")
3013 (when arrow
3014 (insert "=> "))
3015 (insert "{")
3016 ;; TODO: fix this to be smarter about indenting, etc.
3017 (unless expr
3018 (insert "\n"))
3019 (if (js2-block-node-p body)
3020 (js2-print-body body (1+ i))
3021 (js2-print-ast body 0))
3022 (insert pad "}")
3023 (unless expr
3024 (insert "\n"))))
3025
3026 (defun js2-function-name (node)
3027 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3028 (and (js2-function-node-name node)
3029 (js2-name-node-name (js2-function-node-name node))))
3030
3031 ;; Having this be an expression node makes it more flexible.
3032 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3033 ;; that work better if you assume it's an expression. Whenever we have
3034 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3035 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3036 (defstruct (js2-var-decl-node
3037 (:include js2-node)
3038 (:constructor nil)
3039 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3040 (pos (js2-current-token-beg))
3041 len kids
3042 decl-type)))
3043 "AST node for a variable declaration list (VAR, CONST or LET).
3044 The node bounds differ depending on the declaration type. For VAR or
3045 CONST declarations, the bounds include the var/const keyword. For LET
3046 declarations, the node begins at the position of the first child."
3047 kids ; a Lisp list of `js2-var-init-node' structs.
3048 decl-type) ; js2-VAR, js2-CONST or js2-LET
3049
3050 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3051 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3052
3053 (defun js2-visit-var-decl (n v)
3054 (dolist (kid (js2-var-decl-node-kids n))
3055 (js2-visit-ast kid v)))
3056
3057 (defun js2-print-var-decl (n i)
3058 (let ((pad (js2-make-pad i))
3059 (tt (js2-var-decl-node-decl-type n)))
3060 (insert pad)
3061 (insert (cond
3062 ((= tt js2-VAR) "var ")
3063 ((= tt js2-LET) "let ")
3064 ((= tt js2-CONST) "const ")
3065 (t
3066 (error "malformed var-decl node"))))
3067 (loop with kids = (js2-var-decl-node-kids n)
3068 with len = (length kids)
3069 for kid in kids
3070 for count from 1
3071 do
3072 (js2-print-ast kid 0)
3073 (if (< count len)
3074 (insert ", ")))))
3075
3076 (defstruct (js2-var-init-node
3077 (:include js2-node)
3078 (:constructor nil)
3079 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3080 (pos js2-ts-cursor)
3081 len target
3082 initializer)))
3083 "AST node for a variable declaration.
3084 The type field will be js2-CONST for a const decl."
3085 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3086 initializer) ; initializer expression, a `js2-node'
3087
3088 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3089 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3090
3091 (defun js2-visit-var-init-node (n v)
3092 (js2-visit-ast (js2-var-init-node-target n) v)
3093 (js2-visit-ast (js2-var-init-node-initializer n) v))
3094
3095 (defun js2-print-var-init-node (n i)
3096 (let ((pad (js2-make-pad i))
3097 (name (js2-var-init-node-target n))
3098 (init (js2-var-init-node-initializer n)))
3099 (insert pad)
3100 (js2-print-ast name 0)
3101 (when init
3102 (insert " = ")
3103 (js2-print-ast init 0))))
3104
3105 (defstruct (js2-cond-node
3106 (:include js2-node)
3107 (:constructor nil)
3108 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3109 (pos js2-ts-cursor)
3110 len
3111 test-expr
3112 true-expr
3113 false-expr
3114 q-pos c-pos)))
3115 "AST node for the ternary operator"
3116 test-expr
3117 true-expr
3118 false-expr
3119 q-pos ; buffer position of ?
3120 c-pos) ; buffer position of :
3121
3122 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3123 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3124
3125 (defun js2-visit-cond-node (n v)
3126 (js2-visit-ast (js2-cond-node-test-expr n) v)
3127 (js2-visit-ast (js2-cond-node-true-expr n) v)
3128 (js2-visit-ast (js2-cond-node-false-expr n) v))
3129
3130 (defun js2-print-cond-node (n i)
3131 (let ((pad (js2-make-pad i)))
3132 (insert pad)
3133 (js2-print-ast (js2-cond-node-test-expr n) 0)
3134 (insert " ? ")
3135 (js2-print-ast (js2-cond-node-true-expr n) 0)
3136 (insert " : ")
3137 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3138
3139 (defstruct (js2-infix-node
3140 (:include js2-node)
3141 (:constructor nil)
3142 (:constructor make-js2-infix-node (&key type
3143 (pos js2-ts-cursor)
3144 len op-pos
3145 left right)))
3146 "Represents infix expressions.
3147 Includes assignment ops like `|=', and the comma operator.
3148 The type field inherited from `js2-node' holds the operator."
3149 op-pos ; buffer position where operator begins
3150 left ; any `js2-node'
3151 right) ; any `js2-node'
3152
3153 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3154 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3155
3156 (defun js2-visit-infix-node (n v)
3157 (js2-visit-ast (js2-infix-node-left n) v)
3158 (js2-visit-ast (js2-infix-node-right n) v))
3159
3160 (defconst js2-operator-tokens
3161 (let ((table (make-hash-table :test 'eq))
3162 (tokens
3163 (list (cons js2-IN "in")
3164 (cons js2-TYPEOF "typeof")
3165 (cons js2-INSTANCEOF "instanceof")
3166 (cons js2-DELPROP "delete")
3167 (cons js2-COMMA ",")
3168 (cons js2-COLON ":")
3169 (cons js2-OR "||")
3170 (cons js2-AND "&&")
3171 (cons js2-INC "++")
3172 (cons js2-DEC "--")
3173 (cons js2-BITOR "|")
3174 (cons js2-BITXOR "^")
3175 (cons js2-BITAND "&")
3176 (cons js2-EQ "==")
3177 (cons js2-NE "!=")
3178 (cons js2-LT "<")
3179 (cons js2-LE "<=")
3180 (cons js2-GT ">")
3181 (cons js2-GE ">=")
3182 (cons js2-LSH "<<")
3183 (cons js2-RSH ">>")
3184 (cons js2-URSH ">>>")
3185 (cons js2-ADD "+") ; infix plus
3186 (cons js2-SUB "-") ; infix minus
3187 (cons js2-MUL "*")
3188 (cons js2-DIV "/")
3189 (cons js2-MOD "%")
3190 (cons js2-NOT "!")
3191 (cons js2-BITNOT "~")
3192 (cons js2-POS "+") ; unary plus
3193 (cons js2-NEG "-") ; unary minus
3194 (cons js2-TRIPLEDOT "...")
3195 (cons js2-SHEQ "===") ; shallow equality
3196 (cons js2-SHNE "!==") ; shallow inequality
3197 (cons js2-ASSIGN "=")
3198 (cons js2-ASSIGN_BITOR "|=")
3199 (cons js2-ASSIGN_BITXOR "^=")
3200 (cons js2-ASSIGN_BITAND "&=")
3201 (cons js2-ASSIGN_LSH "<<=")
3202 (cons js2-ASSIGN_RSH ">>=")
3203 (cons js2-ASSIGN_URSH ">>>=")
3204 (cons js2-ASSIGN_ADD "+=")
3205 (cons js2-ASSIGN_SUB "-=")
3206 (cons js2-ASSIGN_MUL "*=")
3207 (cons js2-ASSIGN_DIV "/=")
3208 (cons js2-ASSIGN_MOD "%="))))
3209 (loop for (k . v) in tokens do
3210 (puthash k v table))
3211 table))
3212
3213 (defun js2-print-infix-node (n i)
3214 (let* ((tt (js2-node-type n))
3215 (op (gethash tt js2-operator-tokens)))
3216 (unless op
3217 (error "unrecognized infix operator %s" (js2-node-type n)))
3218 (insert (js2-make-pad i))
3219 (js2-print-ast (js2-infix-node-left n) 0)
3220 (unless (= tt js2-COMMA)
3221 (insert " "))
3222 (insert op)
3223 (insert " ")
3224 (js2-print-ast (js2-infix-node-right n) 0)))
3225
3226 (defstruct (js2-assign-node
3227 (:include js2-infix-node)
3228 (:constructor nil)
3229 (:constructor make-js2-assign-node (&key type
3230 (pos js2-ts-cursor)
3231 len op-pos
3232 left right)))
3233 "Represents any assignment.
3234 The type field holds the actual assignment operator.")
3235
3236 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3237 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3238
3239 (defstruct (js2-unary-node
3240 (:include js2-node)
3241 (:constructor nil)
3242 (:constructor make-js2-unary-node (&key type ; required
3243 (pos js2-ts-cursor)
3244 len operand)))
3245 "AST node type for unary operator nodes.
3246 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3247 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3248 property is added if the operator follows the operand."
3249 operand) ; a `js2-node' expression
3250
3251 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3252 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3253
3254 (defun js2-visit-unary-node (n v)
3255 (js2-visit-ast (js2-unary-node-operand n) v))
3256
3257 (defun js2-print-unary-node (n i)
3258 (let* ((tt (js2-node-type n))
3259 (op (gethash tt js2-operator-tokens))
3260 (postfix (js2-node-get-prop n 'postfix)))
3261 (unless op
3262 (error "unrecognized unary operator %s" tt))
3263 (insert (js2-make-pad i))
3264 (unless postfix
3265 (insert op))
3266 (if (or (= tt js2-TYPEOF)
3267 (= tt js2-DELPROP))
3268 (insert " "))
3269 (js2-print-ast (js2-unary-node-operand n) 0)
3270 (when postfix
3271 (insert op))))
3272
3273 (defstruct (js2-let-node
3274 (:include js2-scope)
3275 (:constructor nil)
3276 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3277 (pos (js2-current-token-beg))
3278 len vars body
3279 lp rp)))
3280 "AST node for a let expression or a let statement.
3281 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3282 vars ; a `js2-var-decl-node'
3283 body ; a `js2-node' representing the expression or body block
3284 lp
3285 rp)
3286
3287 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3288 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3289
3290 (defun js2-visit-let-node (n v)
3291 (js2-visit-ast (js2-let-node-vars n) v)
3292 (js2-visit-ast (js2-let-node-body n) v))
3293
3294 (defun js2-print-let-node (n i)
3295 (insert (js2-make-pad i) "let (")
3296 (js2-print-ast (js2-let-node-vars n) 0)
3297 (insert ") ")
3298 (js2-print-ast (js2-let-node-body n) i))
3299
3300 (defstruct (js2-keyword-node
3301 (:include js2-node)
3302 (:constructor nil)
3303 (:constructor make-js2-keyword-node (&key type
3304 (pos (js2-current-token-beg))
3305 (len (- js2-ts-cursor pos)))))
3306 "AST node representing a literal keyword such as `null'.
3307 Used for `null', `this', `true', `false' and `debugger'.
3308 The node type is set to js2-NULL, js2-THIS, etc.")
3309
3310 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3311 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3312
3313 (defun js2-print-keyword-node (n i)
3314 (insert (js2-make-pad i)
3315 (let ((tt (js2-node-type n)))
3316 (cond
3317 ((= tt js2-THIS) "this")
3318 ((= tt js2-NULL) "null")
3319 ((= tt js2-TRUE) "true")
3320 ((= tt js2-FALSE) "false")
3321 ((= tt js2-DEBUGGER) "debugger")
3322 (t (error "Invalid keyword literal type: %d" tt))))))
3323
3324 (defsubst js2-this-node-p (node)
3325 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3326 (eq (js2-node-type node) js2-THIS))
3327
3328 (defstruct (js2-new-node
3329 (:include js2-node)
3330 (:constructor nil)
3331 (:constructor make-js2-new-node (&key (type js2-NEW)
3332 (pos (js2-current-token-beg))
3333 len target
3334 args initializer
3335 lp rp)))
3336 "AST node for new-expression such as new Foo()."
3337 target ; an identifier or reference
3338 args ; a Lisp list of argument nodes
3339 lp ; position of left-paren, nil if omitted
3340 rp ; position of right-paren, nil if omitted
3341 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3342
3343 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3344 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3345
3346 (defun js2-visit-new-node (n v)
3347 (js2-visit-ast (js2-new-node-target n) v)
3348 (dolist (arg (js2-new-node-args n))
3349 (js2-visit-ast arg v))
3350 (js2-visit-ast (js2-new-node-initializer n) v))
3351
3352 (defun js2-print-new-node (n i)
3353 (insert (js2-make-pad i) "new ")
3354 (js2-print-ast (js2-new-node-target n))
3355 (insert "(")
3356 (js2-print-list (js2-new-node-args n))
3357 (insert ")")
3358 (when (js2-new-node-initializer n)
3359 (insert " ")
3360 (js2-print-ast (js2-new-node-initializer n))))
3361
3362 (defstruct (js2-name-node
3363 (:include js2-node)
3364 (:constructor nil)
3365 (:constructor make-js2-name-node (&key (type js2-NAME)
3366 (pos (js2-current-token-beg))
3367 (len (- js2-ts-cursor
3368 (js2-current-token-beg)))
3369 (name (js2-current-token-string)))))
3370 "AST node for a JavaScript identifier"
3371 name ; a string
3372 scope) ; a `js2-scope' (optional, used for codegen)
3373
3374 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3375 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3376
3377 (defun js2-print-name-node (n i)
3378 (insert (js2-make-pad i)
3379 (js2-name-node-name n)))
3380
3381 (defsubst js2-name-node-length (node)
3382 "Return identifier length of NODE, a `js2-name-node'.
3383 Returns 0 if NODE is nil or its identifier field is nil."
3384 (if node
3385 (length (js2-name-node-name node))
3386 0))
3387
3388 (defstruct (js2-number-node
3389 (:include js2-node)
3390 (:constructor nil)
3391 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3392 (pos (js2-current-token-beg))
3393 (len (- js2-ts-cursor
3394 (js2-current-token-beg)))
3395 (value (js2-current-token-string))
3396 (num-value (js2-token-number
3397 (js2-current-token))))))
3398 "AST node for a number literal."
3399 value ; the original string, e.g. "6.02e23"
3400 num-value) ; the parsed number value
3401
3402 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3403 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3404
3405 (defun js2-print-number-node (n i)
3406 (insert (js2-make-pad i)
3407 (number-to-string (js2-number-node-num-value n))))
3408
3409 (defstruct (js2-regexp-node
3410 (:include js2-node)
3411 (:constructor nil)
3412 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3413 (pos (js2-current-token-beg))
3414 (len (- js2-ts-cursor
3415 (js2-current-token-beg)))
3416 value flags)))
3417 "AST node for a regular expression literal."
3418 value ; the regexp string, without // delimiters
3419 flags) ; a string of flags, e.g. `mi'.
3420
3421 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3422 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3423
3424 (defun js2-print-regexp (n i)
3425 (insert (js2-make-pad i)
3426 "/"
3427 (js2-regexp-node-value n)
3428 "/")
3429 (if (js2-regexp-node-flags n)
3430 (insert (js2-regexp-node-flags n))))
3431
3432 (defstruct (js2-string-node
3433 (:include js2-node)
3434 (:constructor nil)
3435 (:constructor make-js2-string-node (&key (type js2-STRING)
3436 (pos (js2-current-token-beg))
3437 (len (- js2-ts-cursor
3438 (js2-current-token-beg)))
3439 (value (js2-current-token-string)))))
3440 "String literal.
3441 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3442 You can tell the quote type by looking at the first character."
3443 value) ; the characters of the string, including the quotes
3444
3445 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3446 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3447
3448 (defun js2-print-string-node (n i)
3449 (insert (js2-make-pad i)
3450 (js2-node-string n)))
3451
3452 (defstruct (js2-array-node
3453 (:include js2-node)
3454 (:constructor nil)
3455 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3456 (pos js2-ts-cursor)
3457 len elems)))
3458 "AST node for an array literal."
3459 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3460
3461 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3462 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3463
3464 (defun js2-visit-array-node (n v)
3465 (dolist (e (js2-array-node-elems n))
3466 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3467
3468 (defun js2-print-array-node (n i)
3469 (insert (js2-make-pad i) "[")
3470 (let ((elems (js2-array-node-elems n)))
3471 (js2-print-list elems)
3472 (when (and elems (null (car (last elems))))
3473 (insert ",")))
3474 (insert "]"))
3475
3476 (defstruct (js2-object-node
3477 (:include js2-node)
3478 (:constructor nil)
3479 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3480 (pos js2-ts-cursor)
3481 len
3482 elems)))
3483 "AST node for an object literal expression.
3484 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3485 The latter represents abbreviation in destructuring expressions."
3486 elems)
3487
3488 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3489 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3490
3491 (defun js2-visit-object-node (n v)
3492 (dolist (e (js2-object-node-elems n))
3493 (js2-visit-ast e v)))
3494
3495 (defun js2-print-object-node (n i)
3496 (insert (js2-make-pad i) "{")
3497 (js2-print-list (js2-object-node-elems n))
3498 (insert "}"))
3499
3500 (defstruct (js2-object-prop-node
3501 (:include js2-infix-node)
3502 (:constructor nil)
3503 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3504 (pos js2-ts-cursor)
3505 len left
3506 right op-pos)))
3507 "AST node for an object literal prop:value entry.
3508 The `left' field is the property: a name node, string node or number node.
3509 The `right' field is a `js2-node' representing the initializer value.")
3510
3511 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3512 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3513
3514 (defun js2-print-object-prop-node (n i)
3515 (insert (js2-make-pad i))
3516 (js2-print-ast (js2-object-prop-node-left n) 0)
3517 (insert ": ")
3518 (js2-print-ast (js2-object-prop-node-right n) 0))
3519
3520 (defstruct (js2-getter-setter-node
3521 (:include js2-infix-node)
3522 (:constructor nil)
3523 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3524 (pos js2-ts-cursor)
3525 len left right)))
3526 "AST node for a getter/setter property in an object literal.
3527 The `left' field is the `js2-name-node' naming the getter/setter prop.
3528 The `right' field is always an anonymous `js2-function-node' with a node
3529 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3530
3531 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3532 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3533
3534 (defun js2-print-getter-setter (n i)
3535 (let ((pad (js2-make-pad i))
3536 (left (js2-getter-setter-node-left n))
3537 (right (js2-getter-setter-node-right n)))
3538 (insert pad)
3539 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3540 (js2-print-ast left 0)
3541 (js2-print-ast right 0)))
3542
3543 (defstruct (js2-prop-get-node
3544 (:include js2-infix-node)
3545 (:constructor nil)
3546 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3547 (pos js2-ts-cursor)
3548 len left right)))
3549 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3550
3551 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3552 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3553
3554 (defun js2-visit-prop-get-node (n v)
3555 (js2-visit-ast (js2-prop-get-node-left n) v)
3556 (js2-visit-ast (js2-prop-get-node-right n) v))
3557
3558 (defun js2-print-prop-get-node (n i)
3559 (insert (js2-make-pad i))
3560 (js2-print-ast (js2-prop-get-node-left n) 0)
3561 (insert ".")
3562 (js2-print-ast (js2-prop-get-node-right n) 0))
3563
3564 (defstruct (js2-elem-get-node
3565 (:include js2-node)
3566 (:constructor nil)
3567 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3568 (pos js2-ts-cursor)
3569 len target element
3570 lb rb)))
3571 "AST node for an array index expression such as foo[bar]."
3572 target ; a `js2-node' - the expression preceding the "."
3573 element ; a `js2-node' - the expression in brackets
3574 lb ; position of left-bracket, nil if omitted
3575 rb) ; position of right-bracket, nil if omitted
3576
3577 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3578 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3579
3580 (defun js2-visit-elem-get-node (n v)
3581 (js2-visit-ast (js2-elem-get-node-target n) v)
3582 (js2-visit-ast (js2-elem-get-node-element n) v))
3583
3584 (defun js2-print-elem-get-node (n i)
3585 (insert (js2-make-pad i))
3586 (js2-print-ast (js2-elem-get-node-target n) 0)
3587 (insert "[")
3588 (js2-print-ast (js2-elem-get-node-element n) 0)
3589 (insert "]"))
3590
3591 (defstruct (js2-call-node
3592 (:include js2-node)
3593 (:constructor nil)
3594 (:constructor make-js2-call-node (&key (type js2-CALL)
3595 (pos js2-ts-cursor)
3596 len target args
3597 lp rp)))
3598 "AST node for a JavaScript function call."
3599 target ; a `js2-node' evaluating to the function to call
3600 args ; a Lisp list of `js2-node' arguments
3601 lp ; position of open-paren, or nil if missing
3602 rp) ; position of close-paren, or nil if missing
3603
3604 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3605 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3606
3607 (defun js2-visit-call-node (n v)
3608 (js2-visit-ast (js2-call-node-target n) v)
3609 (dolist (arg (js2-call-node-args n))
3610 (js2-visit-ast arg v)))
3611
3612 (defun js2-print-call-node (n i)
3613 (insert (js2-make-pad i))
3614 (js2-print-ast (js2-call-node-target n) 0)
3615 (insert "(")
3616 (js2-print-list (js2-call-node-args n))
3617 (insert ")"))
3618
3619 (defstruct (js2-yield-node
3620 (:include js2-node)
3621 (:constructor nil)
3622 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3623 (pos js2-ts-cursor)
3624 len value star-p)))
3625 "AST node for yield statement or expression."
3626 star-p ; whether it's yield*
3627 value) ; optional: value to be yielded
3628
3629 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3630 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3631
3632 (defun js2-visit-yield-node (n v)
3633 (js2-visit-ast (js2-yield-node-value n) v))
3634
3635 (defun js2-print-yield-node (n i)
3636 (insert (js2-make-pad i))
3637 (insert "yield")
3638 (when (js2-yield-node-star-p n)
3639 (insert "*"))
3640 (when (js2-yield-node-value n)
3641 (insert " ")
3642 (js2-print-ast (js2-yield-node-value n) 0)))
3643
3644 (defstruct (js2-paren-node
3645 (:include js2-node)
3646 (:constructor nil)
3647 (:constructor make-js2-paren-node (&key (type js2-LP)
3648 (pos js2-ts-cursor)
3649 len expr)))
3650 "AST node for a parenthesized expression.
3651 In particular, used when the parens are syntactically optional,
3652 as opposed to required parens such as those enclosing an if-conditional."
3653 expr) ; `js2-node'
3654
3655 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3656 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3657
3658 (defun js2-visit-paren-node (n v)
3659 (js2-visit-ast (js2-paren-node-expr n) v))
3660
3661 (defun js2-print-paren-node (n i)
3662 (insert (js2-make-pad i))
3663 (insert "(")
3664 (js2-print-ast (js2-paren-node-expr n) 0)
3665 (insert ")"))
3666
3667 (defstruct (js2-comp-node
3668 (:include js2-scope)
3669 (:constructor nil)
3670 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
3671 (pos js2-ts-cursor)
3672 len result
3673 loops filters
3674 form)))
3675 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3676 result ; result expression (just after left-bracket)
3677 loops ; a Lisp list of `js2-comp-loop-node'
3678 filters ; a Lisp list of guard/filter expressions
3679 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
3680 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
3681 )
3682
3683 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
3684 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
3685
3686 (defun js2-visit-comp-node (n v)
3687 (js2-visit-ast (js2-comp-node-result n) v)
3688 (dolist (l (js2-comp-node-loops n))
3689 (js2-visit-ast l v))
3690 (dolist (f (js2-comp-node-filters n))
3691 (js2-visit-ast f v)))
3692
3693 (defun js2-print-comp-node (n i)
3694 (let ((pad (js2-make-pad i))
3695 (result (js2-comp-node-result n))
3696 (loops (js2-comp-node-loops n))
3697 (filters (js2-comp-node-filters n))
3698 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
3699 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
3700 (insert pad (if gen-p "(" "["))
3701 (when legacy-p
3702 (js2-print-ast result 0))
3703 (dolist (l loops)
3704 (when legacy-p
3705 (insert " "))
3706 (js2-print-ast l 0)
3707 (unless legacy-p
3708 (insert " ")))
3709 (dolist (f filters)
3710 (when legacy-p
3711 (insert " "))
3712 (insert "if (")
3713 (js2-print-ast f 0)
3714 (insert ")")
3715 (unless legacy-p
3716 (insert " ")))
3717 (unless legacy-p
3718 (js2-print-ast result 0))
3719 (insert (if gen-p ")" "]"))))
3720
3721 (defstruct (js2-comp-loop-node
3722 (:include js2-for-in-node)
3723 (:constructor nil)
3724 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
3725 (pos js2-ts-cursor)
3726 len iterator
3727 object in-pos
3728 foreach-p
3729 each-pos
3730 forof-p
3731 lp rp)))
3732 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3733
3734 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
3735 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
3736
3737 (defun js2-visit-comp-loop (n v)
3738 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
3739 (js2-visit-ast (js2-comp-loop-node-object n) v))
3740
3741 (defun js2-print-comp-loop (n _i)
3742 (insert "for ")
3743 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
3744 (insert "(")
3745 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
3746 (insert (if (js2-comp-loop-node-forof-p n)
3747 " of " " in "))
3748 (js2-print-ast (js2-comp-loop-node-object n) 0)
3749 (insert ")"))
3750
3751 (defstruct (js2-empty-expr-node
3752 (:include js2-node)
3753 (:constructor nil)
3754 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3755 (pos (js2-current-token-beg))
3756 len)))
3757 "AST node for an empty expression.")
3758
3759 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3760 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3761
3762 (defstruct (js2-xml-node
3763 (:include js2-block-node)
3764 (:constructor nil)
3765 (:constructor make-js2-xml-node (&key (type js2-XML)
3766 (pos (js2-current-token-beg))
3767 len kids)))
3768 "AST node for initial parse of E4X literals.
3769 The kids field is a list of XML fragments, each a `js2-string-node' or
3770 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3771
3772 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3773 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3774
3775 (defun js2-print-xml-node (n i)
3776 (dolist (kid (js2-xml-node-kids n))
3777 (js2-print-ast kid i)))
3778
3779 (defstruct (js2-xml-js-expr-node
3780 (:include js2-xml-node)
3781 (:constructor nil)
3782 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3783 (pos js2-ts-cursor)
3784 len expr)))
3785 "AST node for an embedded JavaScript {expression} in an E4X literal.
3786 The start and end fields correspond to the curly-braces."
3787 expr) ; a `js2-expr-node' of some sort
3788
3789 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3790 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3791
3792 (defun js2-visit-xml-js-expr (n v)
3793 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3794
3795 (defun js2-print-xml-js-expr (n i)
3796 (insert (js2-make-pad i))
3797 (insert "{")
3798 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3799 (insert "}"))
3800
3801 (defstruct (js2-xml-dot-query-node
3802 (:include js2-infix-node)
3803 (:constructor nil)
3804 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3805 (pos js2-ts-cursor)
3806 op-pos len left
3807 right rp)))
3808 "AST node for an E4X foo.(bar) filter expression.
3809 Note that the left-paren is automatically the character immediately
3810 following the dot (.) in the operator. No whitespace is permitted
3811 between the dot and the lp by the scanner."
3812 rp)
3813
3814 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3815 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3816
3817 (defun js2-print-xml-dot-query (n i)
3818 (insert (js2-make-pad i))
3819 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3820 (insert ".(")
3821 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3822 (insert ")"))
3823
3824 (defstruct (js2-xml-ref-node
3825 (:include js2-node)
3826 (:constructor nil)) ; abstract
3827 "Base type for E4X XML attribute-access or property-get expressions.
3828 Such expressions can take a variety of forms. The general syntax has
3829 three parts:
3830
3831 - (optional) an @ (specifying an attribute access)
3832 - (optional) a namespace (a `js2-name-node') and double-colon
3833 - (required) either a `js2-name-node' or a bracketed [expression]
3834
3835 The property-name expressions (examples: ns::name, @name) are
3836 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3837 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3838
3839 This node type (or more specifically, its subclasses) will sometimes
3840 be the right-hand child of a `js2-prop-get-node' or a
3841 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3842 The `js2-xml-ref-node' may also be a standalone primary expression with
3843 no explicit target, which is valid in certain expression contexts such as
3844
3845 company..employee.(@id < 100)
3846
3847 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3848 expression whose parent is a `js2-xml-dot-query-node'."
3849 namespace
3850 at-pos
3851 colon-pos)
3852
3853 (defsubst js2-xml-ref-node-attr-access-p (node)
3854 "Return non-nil if this expression began with an @-token."
3855 (and (numberp (js2-xml-ref-node-at-pos node))
3856 (plusp (js2-xml-ref-node-at-pos node))))
3857
3858 (defstruct (js2-xml-prop-ref-node
3859 (:include js2-xml-ref-node)
3860 (:constructor nil)
3861 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3862 (pos (js2-current-token-beg))
3863 len propname
3864 namespace at-pos
3865 colon-pos)))
3866 "AST node for an E4X XML [expr] property-ref expression.
3867 The JavaScript syntax is an optional @, an optional ns::, and a name.
3868
3869 [ '@' ] [ name '::' ] name
3870
3871 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3872 @ns::*, @*::attr, @*::*, and @*.
3873
3874 The node starts at the @ token, if present. Otherwise it starts at the
3875 namespace name. The node bounds extend through the closing right-bracket,
3876 or if it is missing due to a syntax error, through the end of the index
3877 expression."
3878 propname)
3879
3880 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3881 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3882
3883 (defun js2-visit-xml-prop-ref-node (n v)
3884 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3885 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3886
3887 (defun js2-print-xml-prop-ref-node (n i)
3888 (insert (js2-make-pad i))
3889 (if (js2-xml-ref-node-attr-access-p n)
3890 (insert "@"))
3891 (when (js2-xml-prop-ref-node-namespace n)
3892 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3893 (insert "::"))
3894 (if (js2-xml-prop-ref-node-propname n)
3895 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3896
3897 (defstruct (js2-xml-elem-ref-node
3898 (:include js2-xml-ref-node)
3899 (:constructor nil)
3900 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3901 (pos (js2-current-token-beg))
3902 len expr lb rb
3903 namespace at-pos
3904 colon-pos)))
3905 "AST node for an E4X XML [expr] member-ref expression.
3906 Syntax:
3907
3908 [ '@' ] [ name '::' ] '[' expr ']'
3909
3910 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3911
3912 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3913 is not a legal E4X XML element-ref expression, since it's already used
3914 for standard JavaScript element-get array indexing. Hence, a
3915 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3916 non-nil namespace node, or both.
3917
3918 The node starts at the @ token, if present. Otherwise it starts
3919 at the namespace name. The node bounds extend through the closing
3920 right-bracket, or if it is missing due to a syntax error, through the
3921 end of the index expression."
3922 expr ; the bracketed index expression
3923 lb
3924 rb)
3925
3926 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3927 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3928
3929 (defun js2-visit-xml-elem-ref-node (n v)
3930 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3931 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3932
3933 (defun js2-print-xml-elem-ref-node (n i)
3934 (insert (js2-make-pad i))
3935 (if (js2-xml-ref-node-attr-access-p n)
3936 (insert "@"))
3937 (when (js2-xml-elem-ref-node-namespace n)
3938 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3939 (insert "::"))
3940 (insert "[")
3941 (if (js2-xml-elem-ref-node-expr n)
3942 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3943 (insert "]"))
3944
3945 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3946
3947 (defstruct (js2-xml-start-tag-node
3948 (:include js2-xml-node)
3949 (:constructor nil)
3950 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3951 (pos js2-ts-cursor)
3952 len name attrs kids
3953 empty-p)))
3954 "AST node for an XML start-tag. Not currently used.
3955 The `kids' field is a Lisp list of child content nodes."
3956 name ; a `js2-xml-name-node'
3957 attrs ; a Lisp list of `js2-xml-attr-node'
3958 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3959
3960 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3961 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3962
3963 (defun js2-visit-xml-start-tag (n v)
3964 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3965 (dolist (attr (js2-xml-start-tag-node-attrs n))
3966 (js2-visit-ast attr v))
3967 (js2-visit-block n v))
3968
3969 (defun js2-print-xml-start-tag (n i)
3970 (insert (js2-make-pad i) "<")
3971 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3972 (when (js2-xml-start-tag-node-attrs n)
3973 (insert " ")
3974 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3975 (insert ">"))
3976
3977 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3978 ;; and add the end-tag to the kids list of the parent as well.
3979 (defstruct (js2-xml-end-tag-node
3980 (:include js2-xml-node)
3981 (:constructor nil)
3982 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
3983 (pos js2-ts-cursor)
3984 len name)))
3985 "AST node for an XML end-tag. Not currently used."
3986 name) ; a `js2-xml-name-node'
3987
3988 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
3989 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
3990
3991 (defun js2-visit-xml-end-tag (n v)
3992 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
3993
3994 (defun js2-print-xml-end-tag (n i)
3995 (insert (js2-make-pad i))
3996 (insert "</")
3997 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
3998 (insert ">"))
3999
4000 (defstruct (js2-xml-name-node
4001 (:include js2-xml-node)
4002 (:constructor nil)
4003 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4004 (pos js2-ts-cursor)
4005 len namespace kids)))
4006 "AST node for an E4X XML name. Not currently used.
4007 Any XML name can be qualified with a namespace, hence the namespace field.
4008 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4009 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4010 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4011 namespace) ; a `js2-string-node'
4012
4013 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4014 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4015
4016 (defun js2-visit-xml-name-node (n v)
4017 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4018
4019 (defun js2-print-xml-name-node (n i)
4020 (insert (js2-make-pad i))
4021 (when (js2-xml-name-node-namespace n)
4022 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4023 (insert "::"))
4024 (dolist (kid (js2-xml-name-node-kids n))
4025 (js2-print-ast kid 0)))
4026
4027 (defstruct (js2-xml-pi-node
4028 (:include js2-xml-node)
4029 (:constructor nil)
4030 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4031 (pos js2-ts-cursor)
4032 len name attrs)))
4033 "AST node for an E4X XML processing instruction. Not currently used."
4034 name ; a `js2-xml-name-node'
4035 attrs) ; a list of `js2-xml-attr-node'
4036
4037 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4038 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4039
4040 (defun js2-visit-xml-pi-node (n v)
4041 (js2-visit-ast (js2-xml-pi-node-name n) v)
4042 (dolist (attr (js2-xml-pi-node-attrs n))
4043 (js2-visit-ast attr v)))
4044
4045 (defun js2-print-xml-pi-node (n i)
4046 (insert (js2-make-pad i) "<?")
4047 (js2-print-ast (js2-xml-pi-node-name n))
4048 (when (js2-xml-pi-node-attrs n)
4049 (insert " ")
4050 (js2-print-list (js2-xml-pi-node-attrs n)))
4051 (insert "?>"))
4052
4053 (defstruct (js2-xml-cdata-node
4054 (:include js2-xml-node)
4055 (:constructor nil)
4056 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4057 (pos js2-ts-cursor)
4058 len content)))
4059 "AST node for a CDATA escape section. Not currently used."
4060 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4061
4062 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4063 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4064
4065 (defun js2-visit-xml-cdata-node (n v)
4066 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4067
4068 (defun js2-print-xml-cdata-node (n i)
4069 (insert (js2-make-pad i))
4070 (js2-print-ast (js2-xml-cdata-node-content n)))
4071
4072 (defstruct (js2-xml-attr-node
4073 (:include js2-xml-node)
4074 (:constructor nil)
4075 (:constructor make-js2-attr-node (&key (type js2-XML)
4076 (pos js2-ts-cursor)
4077 len name value
4078 eq-pos quote-type)))
4079 "AST node representing a foo='bar' XML attribute value. Not yet used."
4080 name ; a `js2-xml-name-node'
4081 value ; a `js2-xml-name-node'
4082 eq-pos ; buffer position of "=" sign
4083 quote-type) ; 'single or 'double
4084
4085 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4086 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4087
4088 (defun js2-visit-xml-attr-node (n v)
4089 (js2-visit-ast (js2-xml-attr-node-name n) v)
4090 (js2-visit-ast (js2-xml-attr-node-value n) v))
4091
4092 (defun js2-print-xml-attr-node (n i)
4093 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4094 "'"
4095 "\"")))
4096 (insert (js2-make-pad i))
4097 (js2-print-ast (js2-xml-attr-node-name n) 0)
4098 (insert "=" quote)
4099 (js2-print-ast (js2-xml-attr-node-value n) 0)
4100 (insert quote)))
4101
4102 (defstruct (js2-xml-text-node
4103 (:include js2-xml-node)
4104 (:constructor nil)
4105 (:constructor make-js2-text-node (&key (type js2-XML)
4106 (pos js2-ts-cursor)
4107 len content)))
4108 "AST node for an E4X XML text node. Not currently used."
4109 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4110
4111 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4112 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4113
4114 (defun js2-visit-xml-text-node (n v)
4115 (js2-visit-ast (js2-xml-text-node-content n) v))
4116
4117 (defun js2-print-xml-text-node (n i)
4118 (insert (js2-make-pad i))
4119 (dolist (kid (js2-xml-text-node-content n))
4120 (js2-print-ast kid)))
4121
4122 (defstruct (js2-xml-comment-node
4123 (:include js2-xml-node)
4124 (:constructor nil)
4125 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4126 (pos js2-ts-cursor)
4127 len)))
4128 "AST node for E4X XML comment. Not currently used.")
4129
4130 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4131 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4132
4133 (defun js2-print-xml-comment (n i)
4134 (insert (js2-make-pad i)
4135 (js2-node-string n)))
4136
4137 ;;; Node utilities
4138
4139 (defsubst js2-node-line (n)
4140 "Fetch the source line number at the start of node N.
4141 This is O(n) in the length of the source buffer; use prudently."
4142 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4143
4144 (defsubst js2-block-node-kid (n i)
4145 "Return child I of node N, or nil if there aren't that many."
4146 (nth i (js2-block-node-kids n)))
4147
4148 (defsubst js2-block-node-first (n)
4149 "Return first child of block node N, or nil if there is none."
4150 (first (js2-block-node-kids n)))
4151
4152 (defun js2-node-root (n)
4153 "Return the root of the AST containing N.
4154 If N has no parent pointer, returns N."
4155 (let ((parent (js2-node-parent n)))
4156 (if parent
4157 (js2-node-root parent)
4158 n)))
4159
4160 (defsubst js2-node-short-name (n)
4161 "Return the short name of node N as a string, e.g. `js2-if-node'."
4162 (substring (symbol-name (aref n 0))
4163 (length "cl-struct-")))
4164
4165 (defun js2-node-child-list (node)
4166 "Return the child list for NODE, a Lisp list of nodes.
4167 Works for block nodes, array nodes, obj literals, funarg lists,
4168 var decls and try nodes (for catch clauses). Note that you should call
4169 `js2-block-node-kids' on the function body for the body statements.
4170 Returns nil for zero-length child lists or unsupported nodes."
4171 (cond
4172 ((js2-function-node-p node)
4173 (js2-function-node-params node))
4174 ((js2-block-node-p node)
4175 (js2-block-node-kids node))
4176 ((js2-try-node-p node)
4177 (js2-try-node-catch-clauses node))
4178 ((js2-array-node-p node)
4179 (js2-array-node-elems node))
4180 ((js2-object-node-p node)
4181 (js2-object-node-elems node))
4182 ((js2-call-node-p node)
4183 (js2-call-node-args node))
4184 ((js2-new-node-p node)
4185 (js2-new-node-args node))
4186 ((js2-var-decl-node-p node)
4187 (js2-var-decl-node-kids node))
4188 (t
4189 nil)))
4190
4191 (defun js2-node-set-child-list (node kids)
4192 "Set the child list for NODE to KIDS."
4193 (cond
4194 ((js2-function-node-p node)
4195 (setf (js2-function-node-params node) kids))
4196 ((js2-block-node-p node)
4197 (setf (js2-block-node-kids node) kids))
4198 ((js2-try-node-p node)
4199 (setf (js2-try-node-catch-clauses node) kids))
4200 ((js2-array-node-p node)
4201 (setf (js2-array-node-elems node) kids))
4202 ((js2-object-node-p node)
4203 (setf (js2-object-node-elems node) kids))
4204 ((js2-call-node-p node)
4205 (setf (js2-call-node-args node) kids))
4206 ((js2-new-node-p node)
4207 (setf (js2-new-node-args node) kids))
4208 ((js2-var-decl-node-p node)
4209 (setf (js2-var-decl-node-kids node) kids))
4210 (t
4211 (error "Unsupported node type: %s" (js2-node-short-name node))))
4212 kids)
4213
4214 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4215 (defconst js2-paren-expr-nodes
4216 '(cl-struct-js2-comp-loop-node
4217 cl-struct-js2-comp-node
4218 cl-struct-js2-call-node
4219 cl-struct-js2-catch-node
4220 cl-struct-js2-do-node
4221 cl-struct-js2-elem-get-node
4222 cl-struct-js2-for-in-node
4223 cl-struct-js2-for-node
4224 cl-struct-js2-function-node
4225 cl-struct-js2-if-node
4226 cl-struct-js2-let-node
4227 cl-struct-js2-new-node
4228 cl-struct-js2-paren-node
4229 cl-struct-js2-switch-node
4230 cl-struct-js2-while-node
4231 cl-struct-js2-with-node
4232 cl-struct-js2-xml-dot-query-node)
4233 "Node types that can have a parenthesized child expression.
4234 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4235
4236 (defsubst js2-paren-expr-node-p (node)
4237 "Return t for nodes that typically have a parenthesized child expression.
4238 Useful for computing the indentation anchors for arg-lists and conditions.
4239 Note that it may return a false positive, for instance when NODE is
4240 a `js2-new-node' and there are no arguments or parentheses."
4241 (memq (aref node 0) js2-paren-expr-nodes))
4242
4243 ;; Fake polymorphism... yech.
4244 (defun js2-node-lp (node)
4245 "Return relative left-paren position for NODE, if applicable.
4246 For `js2-elem-get-node' structs, returns left-bracket position.
4247 Note that the position may be nil in the case of a parse error."
4248 (cond
4249 ((js2-elem-get-node-p node)
4250 (js2-elem-get-node-lb node))
4251 ((js2-loop-node-p node)
4252 (js2-loop-node-lp node))
4253 ((js2-function-node-p node)
4254 (js2-function-node-lp node))
4255 ((js2-if-node-p node)
4256 (js2-if-node-lp node))
4257 ((js2-new-node-p node)
4258 (js2-new-node-lp node))
4259 ((js2-call-node-p node)
4260 (js2-call-node-lp node))
4261 ((js2-paren-node-p node)
4262 0)
4263 ((js2-switch-node-p node)
4264 (js2-switch-node-lp node))
4265 ((js2-catch-node-p node)
4266 (js2-catch-node-lp node))
4267 ((js2-let-node-p node)
4268 (js2-let-node-lp node))
4269 ((js2-comp-node-p node)
4270 0)
4271 ((js2-with-node-p node)
4272 (js2-with-node-lp node))
4273 ((js2-xml-dot-query-node-p node)
4274 (1+ (js2-infix-node-op-pos node)))
4275 (t
4276 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4277
4278 ;; Fake polymorphism... blech.
4279 (defun js2-node-rp (node)
4280 "Return relative right-paren position for NODE, if applicable.
4281 For `js2-elem-get-node' structs, returns right-bracket position.
4282 Note that the position may be nil in the case of a parse error."
4283 (cond
4284 ((js2-elem-get-node-p node)
4285 (js2-elem-get-node-rb node))
4286 ((js2-loop-node-p node)
4287 (js2-loop-node-rp node))
4288 ((js2-function-node-p node)
4289 (js2-function-node-rp node))
4290 ((js2-if-node-p node)
4291 (js2-if-node-rp node))
4292 ((js2-new-node-p node)
4293 (js2-new-node-rp node))
4294 ((js2-call-node-p node)
4295 (js2-call-node-rp node))
4296 ((js2-paren-node-p node)
4297 (1- (js2-node-len node)))
4298 ((js2-switch-node-p node)
4299 (js2-switch-node-rp node))
4300 ((js2-catch-node-p node)
4301 (js2-catch-node-rp node))
4302 ((js2-let-node-p node)
4303 (js2-let-node-rp node))
4304 ((js2-comp-node-p node)
4305 (1- (js2-node-len node)))
4306 ((js2-with-node-p node)
4307 (js2-with-node-rp node))
4308 ((js2-xml-dot-query-node-p node)
4309 (1+ (js2-xml-dot-query-node-rp node)))
4310 (t
4311 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4312
4313 (defsubst js2-node-first-child (node)
4314 "Return the first element of `js2-node-child-list' for NODE."
4315 (car (js2-node-child-list node)))
4316
4317 (defsubst js2-node-last-child (node)
4318 "Return the last element of `js2-node-last-child' for NODE."
4319 (car (last (js2-node-child-list node))))
4320
4321 (defun js2-node-prev-sibling (node)
4322 "Return the previous statement in parent.
4323 Works for parents supported by `js2-node-child-list'.
4324 Returns nil if NODE is not in the parent, or PARENT is
4325 not a supported node, or if NODE is the first child."
4326 (let* ((p (js2-node-parent node))
4327 (kids (js2-node-child-list p))
4328 (sib (car kids)))
4329 (while (and kids
4330 (not (eq node (cadr kids))))
4331 (setq kids (cdr kids)
4332 sib (car kids)))
4333 sib))
4334
4335 (defun js2-node-next-sibling (node)
4336 "Return the next statement in parent block.
4337 Returns nil if NODE is not in the block, or PARENT is not
4338 a block node, or if NODE is the last statement."
4339 (let* ((p (js2-node-parent node))
4340 (kids (js2-node-child-list p)))
4341 (while (and kids
4342 (not (eq node (car kids))))
4343 (setq kids (cdr kids)))
4344 (cadr kids)))
4345
4346 (defun js2-node-find-child-before (pos parent &optional after)
4347 "Find the last child that starts before POS in parent.
4348 If AFTER is non-nil, returns first child starting after POS.
4349 POS is an absolute buffer position. PARENT is any node
4350 supported by `js2-node-child-list'.
4351 Returns nil if no applicable child is found."
4352 (let ((kids (if (js2-function-node-p parent)
4353 (js2-block-node-kids (js2-function-node-body parent))
4354 (js2-node-child-list parent)))
4355 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4356 (js2-function-node-body parent)
4357 parent)))
4358 kid result fn
4359 (continue t))
4360 (setq fn (if after '>= '<))
4361 (while (and kids continue)
4362 (setq kid (car kids))
4363 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4364 (setq result kid
4365 continue (not after))
4366 (setq continue after))
4367 (setq kids (cdr kids)))
4368 result))
4369
4370 (defun js2-node-find-child-after (pos parent)
4371 "Find first child that starts after POS in parent.
4372 POS is an absolute buffer position. PARENT is any node
4373 supported by `js2-node-child-list'.
4374 Returns nil if no applicable child is found."
4375 (js2-node-find-child-before pos parent 'after))
4376
4377 (defun js2-node-replace-child (pos parent new-node)
4378 "Replace node at index POS in PARENT with NEW-NODE.
4379 Only works for parents supported by `js2-node-child-list'."
4380 (let ((kids (js2-node-child-list parent))
4381 (i 0))
4382 (while (< i pos)
4383 (setq kids (cdr kids)
4384 i (1+ i)))
4385 (setcar kids new-node)
4386 (js2-node-add-children parent new-node)))
4387
4388 (defun js2-node-buffer (n)
4389 "Return the buffer associated with AST N.
4390 Returns nil if the buffer is not set as a property on the root
4391 node, or if parent links were not recorded during parsing."
4392 (let ((root (js2-node-root n)))
4393 (and root
4394 (js2-ast-root-p root)
4395 (js2-ast-root-buffer root))))
4396
4397 (defun js2-block-node-push (n kid)
4398 "Push js2-node KID onto the end of js2-block-node N's child list.
4399 KID is always added to the -end- of the kids list.
4400 Function also calls `js2-node-add-children' to add the parent link."
4401 (let ((kids (js2-node-child-list n)))
4402 (if kids
4403 (setcdr kids (nconc (cdr kids) (list kid)))
4404 (js2-node-set-child-list n (list kid)))
4405 (js2-node-add-children n kid)))
4406
4407 (defun js2-node-string (node)
4408 (with-current-buffer (or (js2-node-buffer node)
4409 (error "No buffer available for node %s" node))
4410 (let ((pos (js2-node-abs-pos node)))
4411 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4412
4413 ;; Container for storing the node we're looking for in a traversal.
4414 (js2-deflocal js2-discovered-node nil)
4415
4416 ;; Keep track of absolute node position during traversals.
4417 (js2-deflocal js2-visitor-offset nil)
4418
4419 (js2-deflocal js2-node-search-point nil)
4420
4421 (when js2-mode-dev-mode-p
4422 (defun js2-find-node-at-point ()
4423 (interactive)
4424 (let ((node (js2-node-at-point)))
4425 (message "%s" (or node "No node found at point"))))
4426 (defun js2-node-name-at-point ()
4427 (interactive)
4428 (let ((node (js2-node-at-point)))
4429 (message "%s" (if node
4430 (js2-node-short-name node)
4431 "No node found at point.")))))
4432
4433 (defun js2-node-at-point (&optional pos skip-comments)
4434 "Return AST node at POS, a buffer position, defaulting to current point.
4435 The `js2-mode-ast' variable must be set to the current parse tree.
4436 Signals an error if the AST (`js2-mode-ast') is nil.
4437 Always returns a node - if it can't find one, it returns the root.
4438 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4439 (let ((ast js2-mode-ast)
4440 result)
4441 (unless ast
4442 (error "No JavaScript AST available"))
4443 ;; Look through comments first, since they may be inside nodes that
4444 ;; would otherwise report a match.
4445 (setq pos (or pos (point))
4446 result (if (> pos (js2-node-abs-end ast))
4447 ast
4448 (if (not skip-comments)
4449 (js2-comment-at-point pos))))
4450 (unless result
4451 (setq js2-discovered-node nil
4452 js2-visitor-offset 0
4453 js2-node-search-point pos)
4454 (unwind-protect
4455 (catch 'js2-visit-done
4456 (js2-visit-ast ast #'js2-node-at-point-visitor))
4457 (setq js2-visitor-offset nil
4458 js2-node-search-point nil))
4459 (setq result js2-discovered-node))
4460 ;; may have found a comment beyond end of last child node,
4461 ;; since visiting the ast-root looks at the comment-list last.
4462 (if (and skip-comments
4463 (js2-comment-node-p result))
4464 (setq result nil))
4465 (or result js2-mode-ast)))
4466
4467 (defun js2-node-at-point-visitor (node end-p)
4468 (let ((rel-pos (js2-node-pos node))
4469 abs-pos
4470 abs-end
4471 (point js2-node-search-point))
4472 (cond
4473 (end-p
4474 ;; this evaluates to a non-nil return value, even if it's zero
4475 (decf js2-visitor-offset rel-pos))
4476 ;; we already looked for comments before visiting, and don't want them now
4477 ((js2-comment-node-p node)
4478 nil)
4479 (t
4480 (setq abs-pos (incf js2-visitor-offset rel-pos)
4481 ;; we only want to use the node if the point is before
4482 ;; the last character position in the node, so we decrement
4483 ;; the absolute end by 1.
4484 abs-end (+ abs-pos (js2-node-len node) -1))
4485 (cond
4486 ;; If this node starts after search-point, stop the search.
4487 ((> abs-pos point)
4488 (throw 'js2-visit-done nil))
4489 ;; If this node ends before the search-point, don't check kids.
4490 ((> point abs-end)
4491 nil)
4492 (t
4493 ;; Otherwise point is within this node, possibly in a child.
4494 (setq js2-discovered-node node)
4495 t)))))) ; keep processing kids to look for more specific match
4496
4497 (defsubst js2-block-comment-p (node)
4498 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4499 (and (js2-comment-node-p node)
4500 (memq (js2-comment-node-format node) '(jsdoc block))))
4501
4502 ;; TODO: put the comments in a vector and binary-search them instead
4503 (defun js2-comment-at-point (&optional pos)
4504 "Look through scanned comment nodes for one containing POS.
4505 POS is a buffer position that defaults to current point.
4506 Function returns nil if POS was not in any comment node."
4507 (let ((ast js2-mode-ast)
4508 (x (or pos (point)))
4509 beg end)
4510 (unless ast
4511 (error "No JavaScript AST available"))
4512 (catch 'done
4513 ;; Comments are stored in lexical order.
4514 (dolist (comment (js2-ast-root-comments ast) nil)
4515 (setq beg (js2-node-abs-pos comment)
4516 end (+ beg (js2-node-len comment)))
4517 (if (and (>= x beg)
4518 (<= x end))
4519 (throw 'done comment))))))
4520
4521 (defun js2-mode-find-parent-fn (node)
4522 "Find function enclosing NODE.
4523 Returns nil if NODE is not inside a function."
4524 (setq node (js2-node-parent node))
4525 (while (and node (not (js2-function-node-p node)))
4526 (setq node (js2-node-parent node)))
4527 (and (js2-function-node-p node) node))
4528
4529 (defun js2-mode-find-enclosing-fn (node)
4530 "Find function or root enclosing NODE."
4531 (if (js2-ast-root-p node)
4532 node
4533 (setq node (js2-node-parent node))
4534 (while (not (or (js2-ast-root-p node)
4535 (js2-function-node-p node)))
4536 (setq node (js2-node-parent node)))
4537 node))
4538
4539 (defun js2-mode-find-enclosing-node (beg end)
4540 "Find script or function fully enclosing BEG and END."
4541 (let ((node (js2-node-at-point beg))
4542 pos
4543 (continue t))
4544 (while continue
4545 (if (or (js2-ast-root-p node)
4546 (and (js2-function-node-p node)
4547 (<= (setq pos (js2-node-abs-pos node)) beg)
4548 (>= (+ pos (js2-node-len node)) end)))
4549 (setq continue nil)
4550 (setq node (js2-node-parent node))))
4551 node))
4552
4553 (defun js2-node-parent-script-or-fn (node)
4554 "Find script or function immediately enclosing NODE.
4555 If NODE is the ast-root, returns nil."
4556 (if (js2-ast-root-p node)
4557 nil
4558 (setq node (js2-node-parent node))
4559 (while (and node (not (or (js2-function-node-p node)
4560 (js2-script-node-p node))))
4561 (setq node (js2-node-parent node)))
4562 node))
4563
4564 (defun js2-node-is-descendant (node ancestor)
4565 "Return t if NODE is a descendant of ANCESTOR."
4566 (while (and node
4567 (not (eq node ancestor)))
4568 (setq node (js2-node-parent node)))
4569 node)
4570
4571 ;;; visitor infrastructure
4572
4573 (defun js2-visit-none (_node _callback)
4574 "Visitor for AST node that have no node children."
4575 nil)
4576
4577 (defun js2-print-none (_node _indent)
4578 "Visitor for AST node with no printed representation.")
4579
4580 (defun js2-print-body (node indent)
4581 "Print a statement, or a block without braces."
4582 (if (js2-block-node-p node)
4583 (dolist (kid (js2-block-node-kids node))
4584 (js2-print-ast kid indent))
4585 (js2-print-ast node indent)))
4586
4587 (defun js2-print-list (args &optional delimiter)
4588 (loop with len = (length args)
4589 for arg in args
4590 for count from 1
4591 do
4592 (when arg (js2-print-ast arg 0))
4593 (if (< count len)
4594 (insert (or delimiter ", ")))))
4595
4596 (defun js2-print-tree (ast)
4597 "Prints an AST to the current buffer.
4598 Makes `js2-ast-parent-nodes' available to the printer functions."
4599 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4600 (js2-print-ast ast)))
4601
4602 (defun js2-print-ast (node &optional indent)
4603 "Helper function for printing AST nodes.
4604 Requires `js2-ast-parent-nodes' to be non-nil.
4605 You should use `js2-print-tree' instead of this function."
4606 (let ((printer (get (aref node 0) 'js2-printer))
4607 (i (or indent 0)))
4608 ;; TODO: wedge comments in here somewhere
4609 (if printer
4610 (funcall printer node i))))
4611
4612 (defconst js2-side-effecting-tokens
4613 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4614 (dolist (tt (list js2-ASSIGN
4615 js2-ASSIGN_ADD
4616 js2-ASSIGN_BITAND
4617 js2-ASSIGN_BITOR
4618 js2-ASSIGN_BITXOR
4619 js2-ASSIGN_DIV
4620 js2-ASSIGN_LSH
4621 js2-ASSIGN_MOD
4622 js2-ASSIGN_MUL
4623 js2-ASSIGN_RSH
4624 js2-ASSIGN_SUB
4625 js2-ASSIGN_URSH
4626 js2-BLOCK
4627 js2-BREAK
4628 js2-CALL
4629 js2-CATCH
4630 js2-CATCH_SCOPE
4631 js2-CONST
4632 js2-CONTINUE
4633 js2-DEBUGGER
4634 js2-DEC
4635 js2-DELPROP
4636 js2-DEL_REF
4637 js2-DO
4638 js2-ELSE
4639 js2-EMPTY
4640 js2-ENTERWITH
4641 js2-EXPORT
4642 js2-EXPR_RESULT
4643 js2-FINALLY
4644 js2-FOR
4645 js2-FUNCTION
4646 js2-GOTO
4647 js2-IF
4648 js2-IFEQ
4649 js2-IFNE
4650 js2-IMPORT
4651 js2-INC
4652 js2-JSR
4653 js2-LABEL
4654 js2-LEAVEWITH
4655 js2-LET
4656 js2-LETEXPR
4657 js2-LOCAL_BLOCK
4658 js2-LOOP
4659 js2-NEW
4660 js2-REF_CALL
4661 js2-RETHROW
4662 js2-RETURN
4663 js2-RETURN_RESULT
4664 js2-SEMI
4665 js2-SETELEM
4666 js2-SETELEM_OP
4667 js2-SETNAME
4668 js2-SETPROP
4669 js2-SETPROP_OP
4670 js2-SETVAR
4671 js2-SET_REF
4672 js2-SET_REF_OP
4673 js2-SWITCH
4674 js2-TARGET
4675 js2-THROW
4676 js2-TRY
4677 js2-VAR
4678 js2-WHILE
4679 js2-WITH
4680 js2-WITHEXPR
4681 js2-YIELD))
4682 (aset tokens tt t))
4683 (if js2-instanceof-has-side-effects
4684 (aset tokens js2-INSTANCEOF t))
4685 tokens))
4686
4687 (defun js2-node-has-side-effects (node)
4688 "Return t if NODE has side effects."
4689 (when node ; makes it easier to handle malformed expressions
4690 (let ((tt (js2-node-type node)))
4691 (cond
4692 ;; This doubtless needs some work, since EXPR_VOID is used
4693 ;; in several ways in Rhino and I may not have caught them all.
4694 ;; I'll wait for people to notice incorrect warnings.
4695 ((and (= tt js2-EXPR_VOID)
4696 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4697 (let ((expr (js2-expr-stmt-node-expr node)))
4698 (or (js2-node-has-side-effects expr)
4699 (when (js2-string-node-p expr)
4700 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4701 ((= tt js2-COMMA)
4702 (js2-node-has-side-effects (js2-infix-node-right node)))
4703 ((or (= tt js2-AND)
4704 (= tt js2-OR))
4705 (or (js2-node-has-side-effects (js2-infix-node-right node))
4706 (js2-node-has-side-effects (js2-infix-node-left node))))
4707 ((= tt js2-HOOK)
4708 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4709 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4710 ((js2-paren-node-p node)
4711 (js2-node-has-side-effects (js2-paren-node-expr node)))
4712 ((= tt js2-ERROR) ; avoid cascaded error messages
4713 nil)
4714 (t
4715 (aref js2-side-effecting-tokens tt))))))
4716
4717 (defconst js2-stmt-node-types
4718 (list js2-BLOCK
4719 js2-BREAK
4720 js2-CONTINUE
4721 js2-DEFAULT ; e4x "default xml namespace" statement
4722 js2-DO
4723 js2-EXPR_RESULT
4724 js2-EXPR_VOID
4725 js2-FOR
4726 js2-IF
4727 js2-RETURN
4728 js2-SWITCH
4729 js2-THROW
4730 js2-TRY
4731 js2-WHILE
4732 js2-WITH)
4733 "Node types that only appear in statement contexts.
4734 The list does not include nodes that always appear as the child
4735 of another specific statement type, such as switch-cases,
4736 catch and finally blocks, and else-clauses. The list also excludes
4737 nodes like yield, let and var, which may appear in either expression
4738 or statement context, and in the latter context always have a
4739 `js2-expr-stmt-node' parent. Finally, the list does not include
4740 functions or scripts, which are treated separately from statements
4741 by the JavaScript parser and runtime.")
4742
4743 (defun js2-stmt-node-p (node)
4744 "Heuristic for figuring out if NODE is a statement.
4745 Some node types can appear in either an expression context or a
4746 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4747 For these node types in a statement context, the parent will be a
4748 `js2-expr-stmt-node'.
4749 Functions aren't included in the check."
4750 (memq (js2-node-type node) js2-stmt-node-types))
4751
4752 (defun js2-mode-find-first-stmt (node)
4753 "Search upward starting from NODE looking for a statement.
4754 For purposes of this function, a `js2-function-node' counts."
4755 (while (not (or (js2-stmt-node-p node)
4756 (js2-function-node-p node)))
4757 (setq node (js2-node-parent node)))
4758 node)
4759
4760 (defun js2-node-parent-stmt (node)
4761 "Return the node's first ancestor that is a statement.
4762 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4763 appearing in a statement context will have a parent that is a
4764 `js2-expr-stmt-node' that will be returned by this function."
4765 (let ((parent (js2-node-parent node)))
4766 (if (or (null parent)
4767 (js2-stmt-node-p parent)
4768 (and (js2-function-node-p parent)
4769 (not (eq (js2-function-node-form parent)
4770 'FUNCTION_EXPRESSION))))
4771 parent
4772 (js2-node-parent-stmt parent))))
4773
4774 ;; In the Mozilla Rhino sources, Roshan James writes:
4775 ;; Does consistent-return analysis on the function body when strict mode is
4776 ;; enabled.
4777 ;;
4778 ;; function (x) { return (x+1) }
4779 ;;
4780 ;; is ok, but
4781 ;;
4782 ;; function (x) { if (x < 0) return (x+1); }
4783 ;;
4784 ;; is not because the function can potentially return a value when the
4785 ;; condition is satisfied and if not, the function does not explicitly
4786 ;; return a value.
4787 ;;
4788 ;; This extends to checking mismatches such as "return" and "return <value>"
4789 ;; used in the same function. Warnings are not emitted if inconsistent
4790 ;; returns exist in code that can be statically shown to be unreachable.
4791 ;; Ex.
4792 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4793 ;;
4794 ;; emits no warning. However if the loop had a break statement, then a
4795 ;; warning would be emitted.
4796 ;;
4797 ;; The consistency analysis looks at control structures such as loops, ifs,
4798 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4799 ;; warns the user about an inconsistent set of termination possibilities.
4800 ;;
4801 ;; These flags enumerate the possible ways a statement/function can
4802 ;; terminate. These flags are used by endCheck() and by the Parser to
4803 ;; detect inconsistent return usage.
4804 ;;
4805 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4806 ;; able to execute (example: throw, continue)
4807 ;;
4808 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4809 ;; next one. Statement such as return dont. A compound statement may have
4810 ;; some branch that drops off control to the next statement.
4811 ;;
4812 ;; END_RETURNS indicates that the statement can return with no value.
4813 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4814 ;;
4815 ;; A compound statement such as
4816 ;; if (condition) {
4817 ;; return value;
4818 ;; }
4819 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4820
4821 (defconst js2-END_UNREACHED 0)
4822 (defconst js2-END_DROPS_OFF 1)
4823 (defconst js2-END_RETURNS 2)
4824 (defconst js2-END_RETURNS_VALUE 4)
4825 (defconst js2-END_YIELDS 8)
4826
4827 (defun js2-has-consistent-return-usage (node)
4828 "Check that every return usage in a function body is consistent.
4829 Returns t if the function satisfies strict mode requirement."
4830 (let ((n (js2-end-check node)))
4831 ;; either it doesn't return a value in any branch...
4832 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4833 ;; or it returns a value (or is unreached) at every branch
4834 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4835 js2-END_RETURNS
4836 js2-END_YIELDS)))))
4837
4838 (defun js2-end-check-if (node)
4839 "Ensure that return usage in then/else blocks is consistent.
4840 If there is no else block, then the return statement can fall through.
4841 Returns logical OR of END_* flags"
4842 (let ((th (js2-if-node-then-part node))
4843 (el (js2-if-node-else-part node)))
4844 (if (null th)
4845 js2-END_UNREACHED
4846 (logior (js2-end-check th) (if el
4847 (js2-end-check el)
4848 js2-END_DROPS_OFF)))))
4849
4850 (defun js2-end-check-switch (node)
4851 "Consistency of return statements is checked between the case statements.
4852 If there is no default, then the switch can fall through. If there is a
4853 default, we check to see if all code paths in the default return or if
4854 there is a code path that can fall through.
4855 Returns logical OR of END_* flags."
4856 (let ((rv js2-END_UNREACHED)
4857 default-case)
4858 ;; examine the cases
4859 (catch 'break
4860 (dolist (c (js2-switch-node-cases node))
4861 (if (js2-case-node-expr c)
4862 (js2-set-flag rv (js2-end-check-block c))
4863 (setq default-case c)
4864 (throw 'break nil))))
4865 ;; we don't care how the cases drop into each other
4866 (js2-clear-flag rv js2-END_DROPS_OFF)
4867 ;; examine the default
4868 (js2-set-flag rv (if default-case
4869 (js2-end-check default-case)
4870 js2-END_DROPS_OFF))
4871 rv))
4872
4873 (defun js2-end-check-try (node)
4874 "If the block has a finally, return consistency is checked in the
4875 finally block. If all code paths in the finally return, then the
4876 returns in the try-catch blocks don't matter. If there is a code path
4877 that does not return or if there is no finally block, the returns
4878 of the try and catch blocks are checked for mismatch.
4879 Returns logical OR of END_* flags."
4880 (let ((finally (js2-try-node-finally-block node))
4881 rv)
4882 ;; check the finally if it exists
4883 (setq rv (if finally
4884 (js2-end-check (js2-finally-node-body finally))
4885 js2-END_DROPS_OFF))
4886 ;; If the finally block always returns, then none of the returns
4887 ;; in the try or catch blocks matter.
4888 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4889 (js2-clear-flag rv js2-END_DROPS_OFF)
4890 ;; examine the try block
4891 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4892 ;; check each catch block
4893 (dolist (cb (js2-try-node-catch-clauses node))
4894 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4895 rv))
4896
4897 (defun js2-end-check-loop (node)
4898 "Return statement in the loop body must be consistent.
4899 The default assumption for any kind of a loop is that it will eventually
4900 terminate. The only exception is a loop with a constant true condition.
4901 Code that follows such a loop is examined only if one can determine
4902 statically that there is a break out of the loop.
4903
4904 for(... ; ... ; ...) {}
4905 for(... in ... ) {}
4906 while(...) { }
4907 do { } while(...)
4908
4909 Returns logical OR of END_* flags."
4910 (let ((rv (js2-end-check (js2-loop-node-body node)))
4911 (condition (cond
4912 ((js2-while-node-p node)
4913 (js2-while-node-condition node))
4914 ((js2-do-node-p node)
4915 (js2-do-node-condition node))
4916 ((js2-for-node-p node)
4917 (js2-for-node-condition node)))))
4918
4919 ;; check to see if the loop condition is always true
4920 (if (and condition
4921 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4922 (js2-clear-flag rv js2-END_DROPS_OFF))
4923
4924 ;; look for effect of breaks
4925 (js2-set-flag rv (js2-node-get-prop node
4926 'CONTROL_BLOCK_PROP
4927 js2-END_UNREACHED))
4928 rv))
4929
4930 (defun js2-end-check-block (node)
4931 "A general block of code is examined statement by statement.
4932 If any statement (even a compound one) returns in all branches, then
4933 subsequent statements are not examined.
4934 Returns logical OR of END_* flags."
4935 (let* ((rv js2-END_DROPS_OFF)
4936 (kids (js2-block-node-kids node))
4937 (n (car kids)))
4938 ;; Check each statment. If the statement can continue onto the next
4939 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4940 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4941 (js2-clear-flag rv js2-END_DROPS_OFF)
4942 (js2-set-flag rv (js2-end-check n))
4943 (setq kids (cdr kids)
4944 n (car kids)))
4945 rv))
4946
4947 (defun js2-end-check-label (node)
4948 "A labeled statement implies that there may be a break to the label.
4949 The function processes the labeled statement and then checks the
4950 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4951 particular label.
4952 Returns logical OR of END_* flags."
4953 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4954 (logior rv (js2-node-get-prop node
4955 'CONTROL_BLOCK_PROP
4956 js2-END_UNREACHED))))
4957
4958 (defun js2-end-check-break (node)
4959 "When a break is encountered annotate the statement being broken
4960 out of by setting its CONTROL_BLOCK_PROP property.
4961 Returns logical OR of END_* flags."
4962 (and (js2-break-node-target node)
4963 (js2-node-set-prop (js2-break-node-target node)
4964 'CONTROL_BLOCK_PROP
4965 js2-END_DROPS_OFF))
4966 js2-END_UNREACHED)
4967
4968 (defun js2-end-check (node)
4969 "Examine the body of a function, doing a basic reachability analysis.
4970 Returns a combination of flags END_* flags that indicate
4971 how the function execution can terminate. These constitute only the
4972 pessimistic set of termination conditions. It is possible that at
4973 runtime certain code paths will never be actually taken. Hence this
4974 analysis will flag errors in cases where there may not be errors.
4975 Returns logical OR of END_* flags"
4976 (let (kid)
4977 (cond
4978 ((js2-break-node-p node)
4979 (js2-end-check-break node))
4980 ((js2-expr-stmt-node-p node)
4981 (if (setq kid (js2-expr-stmt-node-expr node))
4982 (js2-end-check kid)
4983 js2-END_DROPS_OFF))
4984 ((or (js2-continue-node-p node)
4985 (js2-throw-node-p node))
4986 js2-END_UNREACHED)
4987 ((js2-return-node-p node)
4988 (if (setq kid (js2-return-node-retval node))
4989 js2-END_RETURNS_VALUE
4990 js2-END_RETURNS))
4991 ((js2-loop-node-p node)
4992 (js2-end-check-loop node))
4993 ((js2-switch-node-p node)
4994 (js2-end-check-switch node))
4995 ((js2-labeled-stmt-node-p node)
4996 (js2-end-check-label node))
4997 ((js2-if-node-p node)
4998 (js2-end-check-if node))
4999 ((js2-try-node-p node)
5000 (js2-end-check-try node))
5001 ((js2-block-node-p node)
5002 (if (null (js2-block-node-kids node))
5003 js2-END_DROPS_OFF
5004 (js2-end-check-block node)))
5005 ((js2-yield-node-p node)
5006 js2-END_YIELDS)
5007 (t
5008 js2-END_DROPS_OFF))))
5009
5010 (defun js2-always-defined-boolean-p (node)
5011 "Check if NODE always evaluates to true or false in boolean context.
5012 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5013 nor always false."
5014 (let ((tt (js2-node-type node))
5015 num)
5016 (cond
5017 ((or (= tt js2-FALSE) (= tt js2-NULL))
5018 'ALWAYS_FALSE)
5019 ((= tt js2-TRUE)
5020 'ALWAYS_TRUE)
5021 ((= tt js2-NUMBER)
5022 (setq num (js2-number-node-num-value node))
5023 (if (and (not (eq num 0.0e+NaN))
5024 (not (zerop num)))
5025 'ALWAYS_TRUE
5026 'ALWAYS_FALSE))
5027 (t
5028 nil))))
5029
5030 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5031 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5032
5033 (defvar js2-tokens nil
5034 "List of all defined token names.") ; initialized in `js2-token-names'
5035
5036 (defconst js2-token-names
5037 (let* ((names (make-vector js2-num-tokens -1))
5038 (case-fold-search nil) ; only match js2-UPPER_CASE
5039 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5040 (loop for sym in syms
5041 for i from 0
5042 do
5043 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5044 (not (boundp sym)))
5045 (aset names (symbol-value sym) ; code, e.g. 152
5046 (downcase
5047 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5048 (push sym js2-tokens)))
5049 names)
5050 "Vector mapping int values to token string names, sans `js2-' prefix.")
5051
5052 (defun js2-tt-name (tok)
5053 "Return a string name for TOK, a token symbol or code.
5054 Signals an error if it's not a recognized token."
5055 (let ((code tok))
5056 (if (symbolp tok)
5057 (setq code (symbol-value tok)))
5058 (if (eq code -1)
5059 "ERROR"
5060 (if (and (numberp code)
5061 (not (minusp code))
5062 (< code js2-num-tokens))
5063 (aref js2-token-names code)
5064 (error "Invalid token: %s" code)))))
5065
5066 (defsubst js2-tt-sym (tok)
5067 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5068 (intern (js2-tt-name tok)))
5069
5070 (defconst js2-token-codes
5071 (let ((table (make-hash-table :test 'eq :size 256)))
5072 (loop for name across js2-token-names
5073 for sym = (intern (concat "js2-" (upcase name)))
5074 do
5075 (puthash sym (symbol-value sym) table))
5076 ;; clean up a few that are "wrong" in Rhino's token codes
5077 (puthash 'js2-DELETE js2-DELPROP table)
5078 table)
5079 "Hashtable mapping token type symbols to their bytecodes.")
5080
5081 (defsubst js2-tt-code (sym)
5082 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5083 (or (gethash sym js2-token-codes)
5084 (error "Invalid token symbol: %s " sym))) ; signal code bug
5085
5086 (defun js2-report-scan-error (msg &optional no-throw beg len)
5087 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5088 (js2-report-error msg nil
5089 (or beg (js2-current-token-beg))
5090 (or len (js2-current-token-len)))
5091 (unless no-throw
5092 (throw 'return js2-ERROR)))
5093
5094 (defun js2-set-string-from-buffer (token)
5095 "Set `string' and `end' slots for TOKEN, return the string."
5096 (setf (js2-token-end token) js2-ts-cursor
5097 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5098
5099 ;; TODO: could potentially avoid a lot of consing by allocating a
5100 ;; char buffer the way Rhino does.
5101 (defsubst js2-add-to-string (c)
5102 (push c js2-ts-string-buffer))
5103
5104 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5105 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5106 ;; any other character: when it's not part of the current token, we
5107 ;; unget it, allowing it to be read again by the following call.
5108 (defsubst js2-unget-char ()
5109 (decf js2-ts-cursor))
5110
5111 ;; Rhino distinguishes \r and \n line endings. We don't need to
5112 ;; because we only scan from Emacs buffers, which always use \n.
5113 (defun js2-get-char ()
5114 "Read and return the next character from the input buffer.
5115 Increments `js2-ts-lineno' if the return value is a newline char.
5116 Updates `js2-ts-cursor' to the point after the returned char.
5117 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5118 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5119 (let (c)
5120 ;; check for end of buffer
5121 (if (>= js2-ts-cursor (point-max))
5122 (setq js2-ts-hit-eof t
5123 js2-ts-cursor (1+ js2-ts-cursor)
5124 c js2-EOF_CHAR) ; return value
5125 ;; otherwise read next char
5126 (setq c (char-before (incf js2-ts-cursor)))
5127 ;; if we read a newline, update counters
5128 (if (= c ?\n)
5129 (setq js2-ts-line-start js2-ts-cursor
5130 js2-ts-lineno (1+ js2-ts-lineno)))
5131 ;; TODO: skip over format characters
5132 c)))
5133
5134 (defun js2-read-unicode-escape ()
5135 "Read a \\uNNNN sequence from the input.
5136 Assumes the ?\ and ?u have already been read.
5137 Returns the unicode character, or nil if it wasn't a valid character.
5138 Doesn't change the values of any scanner variables."
5139 ;; I really wish I knew a better way to do this, but I can't
5140 ;; find the Emacs function that takes a 16-bit int and converts
5141 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5142 ;; Have to first check that it's 4 hex characters or it may stop
5143 ;; the read early.
5144 (ignore-errors
5145 (let ((s (buffer-substring-no-properties js2-ts-cursor
5146 (+ 4 js2-ts-cursor))))
5147 (if (string-match "[[:alnum:]]\\{4\\}" s)
5148 (read (concat "?\\u" s))))))
5149
5150 (defun js2-match-char (test)
5151 "Consume and return next character if it matches TEST, a character.
5152 Returns nil and consumes nothing if TEST is not the next character."
5153 (let ((c (js2-get-char)))
5154 (if (eq c test)
5155 t
5156 (js2-unget-char)
5157 nil)))
5158
5159 (defun js2-peek-char ()
5160 (prog1
5161 (js2-get-char)
5162 (js2-unget-char)))
5163
5164 (defun js2-identifier-start-p (c)
5165 "Is C a valid start to an ES5 Identifier
5166 http://es5.github.io/#x7.6"
5167 (or
5168 (memq c '(?$ ?_))
5169 (memq (get-char-code-property c 'general-category)
5170 ;; Letters
5171 '(Lu Ll Lt Lm Lo Nl))))
5172
5173 (defun js2-identifier-part-p (c)
5174 "Is C a valid part of an ES5 Identifier
5175 http://es5.github.io/#x7.6"
5176 (or
5177 (memq c '(?$ ?_ ?\u200c ?\u200d))
5178 (memq (get-char-code-property c 'general-category)
5179 '(;; Letters
5180 Lu Ll Lt Lm Lo Nl
5181 ;; Combining Marks
5182 Mn Mc
5183 ;; Digits
5184 Nd
5185 ;; Connector Punctuation
5186 Pc))))
5187
5188 (defun js2-alpha-p (c)
5189 (cond ((and (<= ?A c) (<= c ?Z)) t)
5190 ((and (<= ?a c) (<= c ?z)) t)
5191 (t nil)))
5192
5193 (defsubst js2-digit-p (c)
5194 (and (<= ?0 c) (<= c ?9)))
5195
5196 (defun js2-js-space-p (c)
5197 (if (<= c 127)
5198 (memq c '(#x20 #x9 #xB #xC #xD))
5199 (or
5200 (eq c #xA0)
5201 ;; TODO: change this nil to check for Unicode space character
5202 nil)))
5203
5204 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5205
5206 (defun js2-skip-line ()
5207 "Skip to end of line."
5208 (while (not (memq (js2-get-char) js2-eol-chars)))
5209 (js2-unget-char)
5210 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5211 (setq js2-token-end js2-ts-cursor))
5212
5213 (defun js2-init-scanner (&optional buf line)
5214 "Create token stream for BUF starting on LINE.
5215 BUF defaults to `current-buffer' and LINE defaults to 1.
5216
5217 A buffer can only have one scanner active at a time, which yields
5218 dramatically simpler code than using a defstruct. If you need to
5219 have simultaneous scanners in a buffer, copy the regions to scan
5220 into temp buffers."
5221 (with-current-buffer (or buf (current-buffer))
5222 (setq js2-ts-dirty-line nil
5223 js2-ts-hit-eof nil
5224 js2-ts-line-start 0
5225 js2-ts-lineno (or line 1)
5226 js2-ts-line-end-char -1
5227 js2-ts-cursor (point-min)
5228 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5229 js2-ti-tokens-cursor 0
5230 js2-ti-lookahead 0
5231 js2-ts-is-xml-attribute nil
5232 js2-ts-xml-is-tag-content nil
5233 js2-ts-xml-open-tags-count 0
5234 js2-ts-string-buffer nil)))
5235
5236 ;; This function uses the cached op, string and number fields in
5237 ;; TokenStream; if getToken has been called since the passed token
5238 ;; was scanned, the op or string printed may be incorrect.
5239 (defun js2-token-to-string (token)
5240 ;; Not sure where this function is used in Rhino. Not tested.
5241 (if (not js2-debug-print-trees)
5242 ""
5243 (let ((name (js2-tt-name token)))
5244 (cond
5245 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5246 (concat name " `" (js2-current-token-string) "'"))
5247 ((eq token js2-NUMBER)
5248 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5249 (t
5250 name)))))
5251
5252 (defconst js2-keywords
5253 '(break
5254 case catch const continue
5255 debugger default delete do
5256 else enum
5257 false finally for function
5258 if in instanceof import
5259 let
5260 new null
5261 return
5262 switch
5263 this throw true try typeof
5264 var void
5265 while with
5266 yield))
5267
5268 ;; Token names aren't exactly the same as the keywords, unfortunately.
5269 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5270 (defconst js2-kwd-tokens
5271 (let ((table (make-vector js2-num-tokens nil))
5272 (tokens
5273 (list js2-BREAK
5274 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5275 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5276 js2-ELSE
5277 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5278 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5279 js2-LET
5280 js2-NEW js2-NULL
5281 js2-RETURN
5282 js2-SWITCH
5283 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5284 js2-VAR
5285 js2-WHILE js2-WITH
5286 js2-YIELD)))
5287 (dolist (i tokens)
5288 (aset table i 'font-lock-keyword-face))
5289 (aset table js2-STRING 'font-lock-string-face)
5290 (aset table js2-REGEXP 'font-lock-string-face)
5291 (aset table js2-COMMENT 'font-lock-comment-face)
5292 (aset table js2-THIS 'font-lock-builtin-face)
5293 (aset table js2-VOID 'font-lock-constant-face)
5294 (aset table js2-NULL 'font-lock-constant-face)
5295 (aset table js2-TRUE 'font-lock-constant-face)
5296 (aset table js2-FALSE 'font-lock-constant-face)
5297 table)
5298 "Vector whose values are non-nil for tokens that are keywords.
5299 The values are default faces to use for highlighting the keywords.")
5300
5301 ;; FIXME: Support strict mode-only future reserved words, after we know
5302 ;; which parts scopes are in strict mode, and which are not.
5303 (defconst js2-reserved-words '(class export extends import super)
5304 "Future reserved keywords in ECMAScript 5.")
5305
5306 (defconst js2-keyword-names
5307 (let ((table (make-hash-table :test 'equal)))
5308 (loop for k in js2-keywords
5309 do (puthash
5310 (symbol-name k) ; instanceof
5311 (intern (concat "js2-"
5312 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5313 table))
5314 table)
5315 "JavaScript keywords by name, mapped to their symbols.")
5316
5317 (defconst js2-reserved-word-names
5318 (let ((table (make-hash-table :test 'equal)))
5319 (loop for k in js2-reserved-words
5320 do
5321 (puthash (symbol-name k) 'js2-RESERVED table))
5322 table)
5323 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5324
5325 (defun js2-collect-string (buf)
5326 "Convert BUF, a list of chars, to a string.
5327 Reverses BUF before converting."
5328 (if buf
5329 (apply #'string (nreverse buf))
5330 ""))
5331
5332 (defun js2-string-to-keyword (s)
5333 "Return token for S, a string, if S is a keyword or reserved word.
5334 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5335 (or (gethash s js2-keyword-names)
5336 (gethash s js2-reserved-word-names)))
5337
5338 (defsubst js2-ts-set-char-token-bounds (token)
5339 "Used when next token is one character."
5340 (setf (js2-token-beg token) (1- js2-ts-cursor)
5341 (js2-token-end token) js2-ts-cursor))
5342
5343 (defsubst js2-ts-return (token type)
5344 "Update the `end' and `type' slots of TOKEN,
5345 then throw `return' with value TYPE."
5346 (setf (js2-token-end token) js2-ts-cursor
5347 (js2-token-type token) type)
5348 (throw 'return type))
5349
5350 (defun js2-x-digit-to-int (c accumulator)
5351 "Build up a hex number.
5352 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5353 corresponding number. Otherwise return -1."
5354 (catch 'return
5355 (catch 'check
5356 ;; Use 0..9 < A..Z < a..z
5357 (cond
5358 ((<= c ?9)
5359 (decf c ?0)
5360 (if (<= 0 c)
5361 (throw 'check nil)))
5362 ((<= c ?F)
5363 (when (<= ?A c)
5364 (decf c (- ?A 10))
5365 (throw 'check nil)))
5366 ((<= c ?f)
5367 (when (<= ?a c)
5368 (decf c (- ?a 10))
5369 (throw 'check nil))))
5370 (throw 'return -1))
5371 (logior c (lsh accumulator 4))))
5372
5373 (defun js2-get-token ()
5374 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5375 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5376 next saved token.
5377
5378 This function will not return a newline (js2-EOL) - instead, it
5379 gobbles newlines until it finds a non-newline token. Call
5380 `js2-peek-token-or-eol' when you care about newlines.
5381
5382 This function will also not return a js2-COMMENT. Instead, it
5383 records comments found in `js2-scanned-comments'. If the token
5384 returned by this function immediately follows a jsdoc comment,
5385 the token is flagged as such."
5386 (if (zerop js2-ti-lookahead)
5387 (js2-get-token-internal)
5388 (decf js2-ti-lookahead)
5389 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5390 (let ((tt (js2-current-token-type)))
5391 (assert (not (= tt js2-EOL)))
5392 tt)))
5393
5394 (defun js2-unget-token ()
5395 (assert (< js2-ti-lookahead js2-ti-max-lookahead))
5396 (incf js2-ti-lookahead)
5397 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5398
5399 (defun js2-get-token-internal ()
5400 (let* ((token (js2-get-token-internal-1)) ; call scanner
5401 (tt (js2-token-type token))
5402 saw-eol
5403 face)
5404 ;; process comments
5405 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5406 (if (= tt js2-EOL)
5407 (setq saw-eol t)
5408 (setq saw-eol nil)
5409 (when js2-record-comments
5410 (js2-record-comment token)))
5411 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5412 (setq token (js2-get-token-internal-1) ; call scanner again
5413 tt (js2-token-type token)))
5414
5415 (when saw-eol
5416 (setf (js2-token-follows-eol-p token) t))
5417
5418 ;; perform lexical fontification as soon as token is scanned
5419 (when js2-parse-ide-mode
5420 (cond
5421 ((minusp tt)
5422 (js2-record-face 'js2-error token))
5423 ((setq face (aref js2-kwd-tokens tt))
5424 (js2-record-face face token))
5425 ((and (= tt js2-NAME)
5426 (equal (js2-token-string token) "undefined"))
5427 (js2-record-face 'font-lock-constant-face token))))
5428 tt))
5429
5430 (defun js2-get-token-internal-1 ()
5431 "Return next JavaScript token type, an int such as js2-RETURN.
5432 During operation, creates an instance of `js2-token' struct, sets
5433 its relevant fields and puts it into `js2-ti-tokens'."
5434 (let (c c1 identifier-start is-unicode-escape-start
5435 contains-escape escape-val str result base
5436 is-integer quote-char val look-for-slash continue tt
5437 (token (js2-new-token 0)))
5438 (setq
5439 tt
5440 (catch 'return
5441 (while t
5442 ;; Eat whitespace, possibly sensitive to newlines.
5443 (setq continue t)
5444 (while continue
5445 (setq c (js2-get-char))
5446 (cond
5447 ((eq c js2-EOF_CHAR)
5448 (js2-unget-char)
5449 (js2-ts-set-char-token-bounds token)
5450 (throw 'return js2-EOF))
5451 ((eq c ?\n)
5452 (js2-ts-set-char-token-bounds token)
5453 (setq js2-ts-dirty-line nil)
5454 (throw 'return js2-EOL))
5455 ((not (js2-js-space-p c))
5456 (if (/= c ?-) ; in case end of HTML comment
5457 (setq js2-ts-dirty-line t))
5458 (setq continue nil))))
5459 ;; Assume the token will be 1 char - fixed up below.
5460 (js2-ts-set-char-token-bounds token)
5461 (when (eq c ?@)
5462 (throw 'return js2-XMLATTR))
5463 ;; identifier/keyword/instanceof?
5464 ;; watch out for starting with a <backslash>
5465 (cond
5466 ((eq c ?\\)
5467 (setq c (js2-get-char))
5468 (if (eq c ?u)
5469 (setq identifier-start t
5470 is-unicode-escape-start t
5471 js2-ts-string-buffer nil)
5472 (setq identifier-start nil)
5473 (js2-unget-char)
5474 (setq c ?\\)))
5475 (t
5476 (when (setq identifier-start (js2-identifier-start-p c))
5477 (setq js2-ts-string-buffer nil)
5478 (js2-add-to-string c))))
5479 (when identifier-start
5480 (setq contains-escape is-unicode-escape-start)
5481 (catch 'break
5482 (while t
5483 (if is-unicode-escape-start
5484 ;; strictly speaking we should probably push-back
5485 ;; all the bad characters if the <backslash>uXXXX
5486 ;; sequence is malformed. But since there isn't a
5487 ;; correct context(is there?) for a bad Unicode
5488 ;; escape sequence in an identifier, we can report
5489 ;; an error here.
5490 (progn
5491 (setq escape-val 0)
5492 (dotimes (_ 4)
5493 (setq c (js2-get-char)
5494 escape-val (js2-x-digit-to-int c escape-val))
5495 ;; Next check takes care of c < 0 and bad escape
5496 (if (minusp escape-val)
5497 (throw 'break nil)))
5498 (if (minusp escape-val)
5499 (js2-report-scan-error "msg.invalid.escape" t))
5500 (js2-add-to-string escape-val)
5501 (setq is-unicode-escape-start nil))
5502 (setq c (js2-get-char))
5503 (cond
5504 ((eq c ?\\)
5505 (setq c (js2-get-char))
5506 (if (eq c ?u)
5507 (setq is-unicode-escape-start t
5508 contains-escape t)
5509 (js2-report-scan-error "msg.illegal.character" t)))
5510 (t
5511 (if (or (eq c js2-EOF_CHAR)
5512 (not (js2-identifier-part-p c)))
5513 (throw 'break nil))
5514 (js2-add-to-string c))))))
5515 (js2-unget-char)
5516 (setf str (js2-collect-string js2-ts-string-buffer)
5517 (js2-token-end token) js2-ts-cursor)
5518 (unless contains-escape
5519 ;; OPT we shouldn't have to make a string (object!) to
5520 ;; check if it's a keyword.
5521 ;; Return the corresponding token if it's a keyword
5522 (when (setq result (js2-string-to-keyword str))
5523 (if (and (< js2-language-version 170)
5524 (memq result '(js2-LET js2-YIELD)))
5525 ;; LET and YIELD are tokens only in 1.7 and later
5526 (setq result 'js2-NAME))
5527 (when (eq result 'js2-RESERVED)
5528 (setf (js2-token-string token) str))
5529 (throw 'return (js2-tt-code result))))
5530 ;; If we want to intern these as Rhino does, just use (intern str)
5531 (setf (js2-token-string token) str)
5532 (throw 'return js2-NAME)) ; end identifier/kwd check
5533 ;; is it a number?
5534 (when (or (js2-digit-p c)
5535 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5536 (setq js2-ts-string-buffer nil
5537 base 10)
5538 (when (eq c ?0)
5539 (setq c (js2-get-char))
5540 (cond
5541 ((or (eq c ?x) (eq c ?X))
5542 (setq base 16)
5543 (setq c (js2-get-char)))
5544 ((js2-digit-p c)
5545 (setq base 8))
5546 (t
5547 (js2-add-to-string ?0))))
5548 (if (eq base 16)
5549 (while (<= 0 (js2-x-digit-to-int c 0))
5550 (js2-add-to-string c)
5551 (setq c (js2-get-char)))
5552 (while (and (<= ?0 c) (<= c ?9))
5553 ;; We permit 08 and 09 as decimal numbers, which
5554 ;; makes our behavior a superset of the ECMA
5555 ;; numeric grammar. We might not always be so
5556 ;; permissive, so we warn about it.
5557 (when (and (eq base 8) (>= c ?8))
5558 (js2-report-warning "msg.bad.octal.literal"
5559 (if (eq c ?8) "8" "9"))
5560 (setq base 10))
5561 (js2-add-to-string c)
5562 (setq c (js2-get-char))))
5563 (setq is-integer t)
5564 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5565 (setq is-integer nil)
5566 (when (eq c ?.)
5567 (loop do
5568 (js2-add-to-string c)
5569 (setq c (js2-get-char))
5570 while (js2-digit-p c)))
5571 (when (memq c '(?e ?E))
5572 (js2-add-to-string c)
5573 (setq c (js2-get-char))
5574 (when (memq c '(?+ ?-))
5575 (js2-add-to-string c)
5576 (setq c (js2-get-char)))
5577 (unless (js2-digit-p c)
5578 (js2-report-scan-error "msg.missing.exponent" t))
5579 (loop do
5580 (js2-add-to-string c)
5581 (setq c (js2-get-char))
5582 while (js2-digit-p c))))
5583 (js2-unget-char)
5584 (let ((str (js2-set-string-from-buffer token)))
5585 (setf (js2-token-number token)
5586 (if (and (eq base 10) (not is-integer))
5587 (string-to-number str)
5588 ;; TODO: call runtime number-parser. Some of it is in
5589 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5590 (string-to-number str))))
5591 (throw 'return js2-NUMBER))
5592 ;; is it a string?
5593 (when (memq c '(?\" ?\'))
5594 ;; We attempt to accumulate a string the fast way, by
5595 ;; building it directly out of the reader. But if there
5596 ;; are any escaped characters in the string, we revert to
5597 ;; building it out of a string buffer.
5598 (setq quote-char c
5599 js2-ts-string-buffer nil
5600 c (js2-get-char))
5601 (catch 'break
5602 (while (/= c quote-char)
5603 (catch 'continue
5604 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5605 (js2-unget-char)
5606 (setf (js2-token-end token) js2-ts-cursor)
5607 (js2-report-error "msg.unterminated.string.lit")
5608 (throw 'return js2-STRING))
5609 (when (eq c ?\\)
5610 ;; We've hit an escaped character
5611 (setq c (js2-get-char))
5612 (case c
5613 (?b (setq c ?\b))
5614 (?f (setq c ?\f))
5615 (?n (setq c ?\n))
5616 (?r (setq c ?\r))
5617 (?t (setq c ?\t))
5618 (?v (setq c ?\v))
5619 (?u
5620 (setq c1 (js2-read-unicode-escape))
5621 (if js2-parse-ide-mode
5622 (if c1
5623 (progn
5624 ;; just copy the string in IDE-mode
5625 (js2-add-to-string ?\\)
5626 (js2-add-to-string ?u)
5627 (dotimes (_ 3)
5628 (js2-add-to-string (js2-get-char)))
5629 (setq c (js2-get-char))) ; added at end of loop
5630 ;; flag it as an invalid escape
5631 (js2-report-warning "msg.invalid.escape"
5632 nil (- js2-ts-cursor 2) 6))
5633 ;; Get 4 hex digits; if the u escape is not
5634 ;; followed by 4 hex digits, use 'u' + the
5635 ;; literal character sequence that follows.
5636 (js2-add-to-string ?u)
5637 (setq escape-val 0)
5638 (dotimes (_ 4)
5639 (setq c (js2-get-char)
5640 escape-val (js2-x-digit-to-int c escape-val))
5641 (if (minusp escape-val)
5642 (throw 'continue nil))
5643 (js2-add-to-string c))
5644 ;; prepare for replace of stored 'u' sequence by escape value
5645 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5646 c escape-val)))
5647 (?x
5648 ;; Get 2 hex digits, defaulting to 'x'+literal
5649 ;; sequence, as above.
5650 (setq c (js2-get-char)
5651 escape-val (js2-x-digit-to-int c 0))
5652 (if (minusp escape-val)
5653 (progn
5654 (js2-add-to-string ?x)
5655 (throw 'continue nil))
5656 (setq c1 c
5657 c (js2-get-char)
5658 escape-val (js2-x-digit-to-int c escape-val))
5659 (if (minusp escape-val)
5660 (progn
5661 (js2-add-to-string ?x)
5662 (js2-add-to-string c1)
5663 (throw 'continue nil))
5664 ;; got 2 hex digits
5665 (setq c escape-val))))
5666 (?\n
5667 ;; Remove line terminator after escape to follow
5668 ;; SpiderMonkey and C/C++
5669 (setq c (js2-get-char))
5670 (throw 'continue nil))
5671 (t
5672 (when (and (<= ?0 c) (< c ?8))
5673 (setq val (- c ?0)
5674 c (js2-get-char))
5675 (when (and (<= ?0 c) (< c ?8))
5676 (setq val (- (+ (* 8 val) c) ?0)
5677 c (js2-get-char))
5678 (when (and (<= ?0 c)
5679 (< c ?8)
5680 (< val #o37))
5681 ;; c is 3rd char of octal sequence only
5682 ;; if the resulting val <= 0377
5683 (setq val (- (+ (* 8 val) c) ?0)
5684 c (js2-get-char))))
5685 (js2-unget-char)
5686 (setq c val)))))
5687 (js2-add-to-string c)
5688 (setq c (js2-get-char)))))
5689 (js2-set-string-from-buffer token)
5690 (throw 'return js2-STRING))
5691 (js2-ts-return token
5692 (case c
5693 (?\;
5694 (throw 'return js2-SEMI))
5695 (?\[
5696 (throw 'return js2-LB))
5697 (?\]
5698 (throw 'return js2-RB))
5699 (?{
5700 (throw 'return js2-LC))
5701 (?}
5702 (throw 'return js2-RC))
5703 (?\(
5704 (throw 'return js2-LP))
5705 (?\)
5706 (throw 'return js2-RP))
5707 (?,
5708 (throw 'return js2-COMMA))
5709 (??
5710 (throw 'return js2-HOOK))
5711 (?:
5712 (if (js2-match-char ?:)
5713 js2-COLONCOLON
5714 (throw 'return js2-COLON)))
5715 (?.
5716 (if (js2-match-char ?.)
5717 (if (js2-match-char ?.)
5718 js2-TRIPLEDOT js2-DOTDOT)
5719 (if (js2-match-char ?\()
5720 js2-DOTQUERY
5721 (throw 'return js2-DOT))))
5722 (?|
5723 (if (js2-match-char ?|)
5724 (throw 'return js2-OR)
5725 (if (js2-match-char ?=)
5726 js2-ASSIGN_BITOR
5727 (throw 'return js2-BITOR))))
5728 (?^
5729 (if (js2-match-char ?=)
5730 js2-ASSIGN_BITOR
5731 (throw 'return js2-BITXOR)))
5732 (?&
5733 (if (js2-match-char ?&)
5734 (throw 'return js2-AND)
5735 (if (js2-match-char ?=)
5736 js2-ASSIGN_BITAND
5737 (throw 'return js2-BITAND))))
5738 (?=
5739 (if (js2-match-char ?=)
5740 (if (js2-match-char ?=)
5741 js2-SHEQ
5742 (throw 'return js2-EQ))
5743 (if (js2-match-char ?>)
5744 (js2-ts-return token js2-ARROW)
5745 (throw 'return js2-ASSIGN))))
5746 (?!
5747 (if (js2-match-char ?=)
5748 (if (js2-match-char ?=)
5749 js2-SHNE
5750 js2-NE)
5751 (throw 'return js2-NOT)))
5752 (?<
5753 ;; NB:treat HTML begin-comment as comment-till-eol
5754 (when (js2-match-char ?!)
5755 (when (js2-match-char ?-)
5756 (when (js2-match-char ?-)
5757 (js2-skip-line)
5758 (setf (js2-token-comment-type (js2-current-token)) 'html)
5759 (throw 'return js2-COMMENT)))
5760 (js2-unget-char))
5761 (if (js2-match-char ?<)
5762 (if (js2-match-char ?=)
5763 js2-ASSIGN_LSH
5764 js2-LSH)
5765 (if (js2-match-char ?=)
5766 js2-LE
5767 (throw 'return js2-LT))))
5768 (?>
5769 (if (js2-match-char ?>)
5770 (if (js2-match-char ?>)
5771 (if (js2-match-char ?=)
5772 js2-ASSIGN_URSH
5773 js2-URSH)
5774 (if (js2-match-char ?=)
5775 js2-ASSIGN_RSH
5776 js2-RSH))
5777 (if (js2-match-char ?=)
5778 js2-GE
5779 (throw 'return js2-GT))))
5780 (?*
5781 (if (js2-match-char ?=)
5782 js2-ASSIGN_MUL
5783 (throw 'return js2-MUL)))
5784 (?/
5785 ;; is it a // comment?
5786 (when (js2-match-char ?/)
5787 (setf (js2-token-beg token) (- js2-ts-cursor 2))
5788 (js2-skip-line)
5789 (setf (js2-token-comment-type token) 'line)
5790 ;; include newline so highlighting goes to end of window
5791 (incf (js2-token-end token))
5792 (throw 'return js2-COMMENT))
5793 ;; is it a /* comment?
5794 (when (js2-match-char ?*)
5795 (setf look-for-slash nil
5796 (js2-token-beg token) (- js2-ts-cursor 2)
5797 (js2-token-comment-type token)
5798 (if (js2-match-char ?*)
5799 (progn
5800 (setq look-for-slash t)
5801 'jsdoc)
5802 'block))
5803 (while t
5804 (setq c (js2-get-char))
5805 (cond
5806 ((eq c js2-EOF_CHAR)
5807 (setf (js2-token-end token) (1- js2-ts-cursor))
5808 (js2-report-error "msg.unterminated.comment")
5809 (throw 'return js2-COMMENT))
5810 ((eq c ?*)
5811 (setq look-for-slash t))
5812 ((eq c ?/)
5813 (if look-for-slash
5814 (js2-ts-return token js2-COMMENT)))
5815 (t
5816 (setf look-for-slash nil
5817 (js2-token-end token) js2-ts-cursor)))))
5818 (if (js2-match-char ?=)
5819 js2-ASSIGN_DIV
5820 (throw 'return js2-DIV)))
5821 (?#
5822 (when js2-skip-preprocessor-directives
5823 (js2-skip-line)
5824 (setf (js2-token-comment-type token) 'preprocessor
5825 (js2-token-end token) js2-ts-cursor)
5826 (throw 'return js2-COMMENT))
5827 (throw 'return js2-ERROR))
5828 (?%
5829 (if (js2-match-char ?=)
5830 js2-ASSIGN_MOD
5831 (throw 'return js2-MOD)))
5832 (?~
5833 (throw 'return js2-BITNOT))
5834 (?+
5835 (if (js2-match-char ?=)
5836 js2-ASSIGN_ADD
5837 (if (js2-match-char ?+)
5838 js2-INC
5839 (throw 'return js2-ADD))))
5840 (?-
5841 (cond
5842 ((js2-match-char ?=)
5843 (setq c js2-ASSIGN_SUB))
5844 ((js2-match-char ?-)
5845 (unless js2-ts-dirty-line
5846 ;; treat HTML end-comment after possible whitespace
5847 ;; after line start as comment-until-eol
5848 (when (js2-match-char ?>)
5849 (js2-skip-line)
5850 (setf (js2-token-comment-type (js2-current-token)) 'html)
5851 (throw 'return js2-COMMENT)))
5852 (setq c js2-DEC))
5853 (t
5854 (setq c js2-SUB)))
5855 (setq js2-ts-dirty-line t)
5856 c)
5857 (otherwise
5858 (js2-report-scan-error "msg.illegal.character")))))))
5859 (setf (js2-token-type token) tt)
5860 token))
5861
5862 (defun js2-read-regexp (start-tt)
5863 "Called by parser when it gets / or /= in literal context."
5864 (let (c err
5865 in-class ; inside a '[' .. ']' character-class
5866 flags
5867 (continue t)
5868 (token (js2-new-token 0)))
5869 (setq js2-ts-string-buffer nil)
5870 (if (eq start-tt js2-ASSIGN_DIV)
5871 ;; mis-scanned /=
5872 (js2-add-to-string ?=)
5873 (if (not (eq start-tt js2-DIV))
5874 (error "failed assertion")))
5875 (while (and (not err)
5876 (or (/= (setq c (js2-get-char)) ?/)
5877 in-class))
5878 (cond
5879 ((or (= c ?\n)
5880 (= c js2-EOF_CHAR))
5881 (setf (js2-token-end token) (1- js2-ts-cursor)
5882 err t
5883 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
5884 (js2-report-error "msg.unterminated.re.lit"))
5885 (t (cond
5886 ((= c ?\\)
5887 (js2-add-to-string c)
5888 (setq c (js2-get-char)))
5889 ((= c ?\[)
5890 (setq in-class t))
5891 ((= c ?\])
5892 (setq in-class nil)))
5893 (js2-add-to-string c))))
5894 (unless err
5895 (while continue
5896 (cond
5897 ((js2-match-char ?g)
5898 (push ?g flags))
5899 ((js2-match-char ?i)
5900 (push ?i flags))
5901 ((js2-match-char ?m)
5902 (push ?m flags))
5903 (t
5904 (setq continue nil))))
5905 (if (js2-alpha-p (js2-peek-char))
5906 (js2-report-scan-error "msg.invalid.re.flag" t
5907 js2-ts-cursor 1))
5908 (js2-set-string-from-buffer token)
5909 ;; tell `parse-partial-sexp' to ignore this range of chars
5910 (js2-record-text-property (js2-current-token-beg)
5911 (js2-current-token-end) 'syntax-class '(2)))
5912 (js2-collect-string flags)))
5913
5914 (defun js2-get-first-xml-token ()
5915 (setq js2-ts-xml-open-tags-count 0
5916 js2-ts-is-xml-attribute nil
5917 js2-ts-xml-is-tag-content nil)
5918 (js2-unget-char)
5919 (js2-get-next-xml-token))
5920
5921 (defun js2-xml-discard-string (token)
5922 "Throw away the string in progress and flag an XML parse error."
5923 (setf js2-ts-string-buffer nil
5924 (js2-token-string token) nil)
5925 (js2-report-scan-error "msg.XML.bad.form" t))
5926
5927 (defun js2-get-next-xml-token ()
5928 (setq js2-ts-string-buffer nil) ; for recording the XML
5929 (let ((token (js2-new-token 0))
5930 c result)
5931 (setq result
5932 (catch 'return
5933 (while t
5934 (setq c (js2-get-char))
5935 (cond
5936 ((= c js2-EOF_CHAR)
5937 (throw 'return js2-ERROR))
5938 (js2-ts-xml-is-tag-content
5939 (case c
5940 (?>
5941 (js2-add-to-string c)
5942 (setq js2-ts-xml-is-tag-content nil
5943 js2-ts-is-xml-attribute nil))
5944 (?/
5945 (js2-add-to-string c)
5946 (when (eq ?> (js2-peek-char))
5947 (setq c (js2-get-char))
5948 (js2-add-to-string c)
5949 (setq js2-ts-xml-is-tag-content nil)
5950 (decf js2-ts-xml-open-tags-count)))
5951 (?{
5952 (js2-unget-char)
5953 (js2-set-string-from-buffer token)
5954 (throw 'return js2-XML))
5955 ((?\' ?\")
5956 (js2-add-to-string c)
5957 (unless (js2-read-quoted-string c token)
5958 (throw 'return js2-ERROR)))
5959 (?=
5960 (js2-add-to-string c)
5961 (setq js2-ts-is-xml-attribute t))
5962 ((? ?\t ?\r ?\n)
5963 (js2-add-to-string c))
5964 (t
5965 (js2-add-to-string c)
5966 (setq js2-ts-is-xml-attribute nil)))
5967 (when (and (not js2-ts-xml-is-tag-content)
5968 (zerop js2-ts-xml-open-tags-count))
5969 (js2-set-string-from-buffer token)
5970 (throw 'return js2-XMLEND)))
5971 (t
5972 ;; else not tag content
5973 (case c
5974 (?<
5975 (js2-add-to-string c)
5976 (setq c (js2-peek-char))
5977 (case c
5978 (?!
5979 (setq c (js2-get-char)) ;; skip !
5980 (js2-add-to-string c)
5981 (setq c (js2-peek-char))
5982 (case c
5983 (?-
5984 (setq c (js2-get-char)) ;; skip -
5985 (js2-add-to-string c)
5986 (if (eq c ?-)
5987 (progn
5988 (js2-add-to-string c)
5989 (unless (js2-read-xml-comment token)
5990 (throw 'return js2-ERROR)))
5991 (js2-xml-discard-string token)
5992 (throw 'return js2-ERROR)))
5993 (?\[
5994 (setq c (js2-get-char)) ;; skip [
5995 (js2-add-to-string c)
5996 (if (and (= (js2-get-char) ?C)
5997 (= (js2-get-char) ?D)
5998 (= (js2-get-char) ?A)
5999 (= (js2-get-char) ?T)
6000 (= (js2-get-char) ?A)
6001 (= (js2-get-char) ?\[))
6002 (progn
6003 (js2-add-to-string ?C)
6004 (js2-add-to-string ?D)
6005 (js2-add-to-string ?A)
6006 (js2-add-to-string ?T)
6007 (js2-add-to-string ?A)
6008 (js2-add-to-string ?\[)
6009 (unless (js2-read-cdata token)
6010 (throw 'return js2-ERROR)))
6011 (js2-xml-discard-string token)
6012 (throw 'return js2-ERROR)))
6013 (t
6014 (unless (js2-read-entity token)
6015 (throw 'return js2-ERROR))))
6016 ;; Allow bare CDATA section, e.g.:
6017 ;; let xml = <![CDATA[ foo bar baz ]]>;
6018 (when (zerop js2-ts-xml-open-tags-count)
6019 (throw 'return js2-XMLEND)))
6020 (??
6021 (setq c (js2-get-char)) ;; skip ?
6022 (js2-add-to-string c)
6023 (unless (js2-read-PI token)
6024 (throw 'return js2-ERROR)))
6025 (?/
6026 ;; end tag
6027 (setq c (js2-get-char)) ;; skip /
6028 (js2-add-to-string c)
6029 (when (zerop js2-ts-xml-open-tags-count)
6030 (js2-xml-discard-string token)
6031 (throw 'return js2-ERROR))
6032 (setq js2-ts-xml-is-tag-content t)
6033 (decf js2-ts-xml-open-tags-count))
6034 (t
6035 ;; start tag
6036 (setq js2-ts-xml-is-tag-content t)
6037 (incf js2-ts-xml-open-tags-count))))
6038 (?{
6039 (js2-unget-char)
6040 (js2-set-string-from-buffer token)
6041 (throw 'return js2-XML))
6042 (t
6043 (js2-add-to-string c))))))))
6044 (setf (js2-token-end token) js2-ts-cursor)
6045 (setf (js2-token-type token) result)
6046 result))
6047
6048 (defun js2-read-quoted-string (quote token)
6049 (let (c)
6050 (catch 'return
6051 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6052 (js2-add-to-string c)
6053 (if (eq c quote)
6054 (throw 'return t)))
6055 (js2-xml-discard-string token) ;; throw away string in progress
6056 nil)))
6057
6058 (defun js2-read-xml-comment (token)
6059 (let ((c (js2-get-char)))
6060 (catch 'return
6061 (while (/= c js2-EOF_CHAR)
6062 (catch 'continue
6063 (js2-add-to-string c)
6064 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6065 (setq c (js2-get-char))
6066 (js2-add-to-string c)
6067 (if (eq (js2-peek-char) ?>)
6068 (progn
6069 (setq c (js2-get-char)) ;; skip >
6070 (js2-add-to-string c)
6071 (throw 'return t))
6072 (throw 'continue nil)))
6073 (setq c (js2-get-char))))
6074 (js2-xml-discard-string token)
6075 nil)))
6076
6077 (defun js2-read-cdata (token)
6078 (let ((c (js2-get-char)))
6079 (catch 'return
6080 (while (/= c js2-EOF_CHAR)
6081 (catch 'continue
6082 (js2-add-to-string c)
6083 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6084 (setq c (js2-get-char))
6085 (js2-add-to-string c)
6086 (if (eq (js2-peek-char) ?>)
6087 (progn
6088 (setq c (js2-get-char)) ;; Skip >
6089 (js2-add-to-string c)
6090 (throw 'return t))
6091 (throw 'continue nil)))
6092 (setq c (js2-get-char))))
6093 (js2-xml-discard-string token)
6094 nil)))
6095
6096 (defun js2-read-entity (token)
6097 (let ((decl-tags 1)
6098 c)
6099 (catch 'return
6100 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6101 (js2-add-to-string c)
6102 (case c
6103 (?<
6104 (incf decl-tags))
6105 (?>
6106 (decf decl-tags)
6107 (if (zerop decl-tags)
6108 (throw 'return t)))))
6109 (js2-xml-discard-string token)
6110 nil)))
6111
6112 (defun js2-read-PI (token)
6113 "Scan an XML processing instruction."
6114 (let (c)
6115 (catch 'return
6116 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6117 (js2-add-to-string c)
6118 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6119 (setq c (js2-get-char)) ;; Skip >
6120 (js2-add-to-string c)
6121 (throw 'return t)))
6122 (js2-xml-discard-string token)
6123 nil)))
6124
6125 ;;; Highlighting
6126
6127 (defun js2-set-face (beg end face &optional record)
6128 "Fontify a region. If RECORD is non-nil, record for later."
6129 (when (plusp js2-highlight-level)
6130 (setq beg (min (point-max) beg)
6131 beg (max (point-min) beg)
6132 end (min (point-max) end)
6133 end (max (point-min) end))
6134 (if record
6135 (push (list beg end face) js2-mode-fontifications)
6136 (put-text-property beg end 'font-lock-face face))))
6137
6138 (defsubst js2-clear-face (beg end)
6139 (remove-text-properties beg end '(font-lock-face nil
6140 help-echo nil
6141 point-entered nil
6142 c-in-sws nil)))
6143
6144 (defconst js2-ecma-global-props
6145 (concat "^"
6146 (regexp-opt
6147 '("Infinity" "NaN" "undefined" "arguments") t)
6148 "$")
6149 "Value properties of the Ecma-262 Global Object.
6150 Shown at or above `js2-highlight-level' 2.")
6151
6152 ;; might want to add the name "arguments" to this list?
6153 (defconst js2-ecma-object-props
6154 (concat "^"
6155 (regexp-opt
6156 '("prototype" "__proto__" "__parent__") t)
6157 "$")
6158 "Value properties of the Ecma-262 Object constructor.
6159 Shown at or above `js2-highlight-level' 2.")
6160
6161 (defconst js2-ecma-global-funcs
6162 (concat
6163 "^"
6164 (regexp-opt
6165 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6166 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6167 "$")
6168 "Function properties of the Ecma-262 Global object.
6169 Shown at or above `js2-highlight-level' 2.")
6170
6171 (defconst js2-ecma-number-props
6172 (concat "^"
6173 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6174 "NEGATIVE_INFINITY"
6175 "POSITIVE_INFINITY") t)
6176 "$")
6177 "Properties of the Ecma-262 Number constructor.
6178 Shown at or above `js2-highlight-level' 2.")
6179
6180 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6181 "Properties of the Ecma-262 Date constructor.
6182 Shown at or above `js2-highlight-level' 2.")
6183
6184 (defconst js2-ecma-math-props
6185 (concat "^"
6186 (regexp-opt
6187 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6188 t)
6189 "$")
6190 "Properties of the Ecma-262 Math object.
6191 Shown at or above `js2-highlight-level' 2.")
6192
6193 (defconst js2-ecma-math-funcs
6194 (concat "^"
6195 (regexp-opt
6196 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6197 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6198 "$")
6199 "Function properties of the Ecma-262 Math object.
6200 Shown at or above `js2-highlight-level' 2.")
6201
6202 (defconst js2-ecma-function-props
6203 (concat
6204 "^"
6205 (regexp-opt
6206 '(;; properties of the Object prototype object
6207 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6208 "toLocaleString" "toString" "valueOf"
6209 ;; properties of the Function prototype object
6210 "apply" "call"
6211 ;; properties of the Array prototype object
6212 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6213 "splice" "unshift"
6214 ;; properties of the String prototype object
6215 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6216 "localeCompare" "match" "replace" "search" "split" "substring"
6217 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6218 "toUpperCase"
6219 ;; properties of the Number prototype object
6220 "toExponential" "toFixed" "toPrecision"
6221 ;; properties of the Date prototype object
6222 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6223 "getMinutes" "getMonth" "getSeconds" "getTime"
6224 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6225 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6226 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6227 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6228 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6229 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6230 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6231 "toTimeString" "toUTCString"
6232 ;; properties of the RegExp prototype object
6233 "exec" "test"
6234 ;; properties of the JSON prototype object
6235 "parse" "stringify"
6236 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6237 "toSource" "__defineGetter__" "__defineSetter__"
6238 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6239 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6240 t)
6241 "$")
6242 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6243 Shown at or above `js2-highlight-level' 3.")
6244
6245 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6246 (let ((target-name (and target
6247 (js2-name-node-p target)
6248 (js2-name-node-name target)))
6249 (prop-name (if prop (js2-name-node-name prop)))
6250 (level2 (>= js2-highlight-level 2))
6251 (level3 (>= js2-highlight-level 3)))
6252 (when level2
6253 (let ((face
6254 (if call-p
6255 (cond
6256 ((and target prop)
6257 (cond
6258 ((and level3 (string-match js2-ecma-function-props prop-name))
6259 'font-lock-builtin-face)
6260 ((and target-name prop)
6261 (cond
6262 ((string= target-name "Date")
6263 (if (string-match js2-ecma-date-props prop-name)
6264 'font-lock-builtin-face))
6265 ((string= target-name "Math")
6266 (if (string-match js2-ecma-math-funcs prop-name)
6267 'font-lock-builtin-face))))))
6268 (prop
6269 (if (string-match js2-ecma-global-funcs prop-name)
6270 'font-lock-builtin-face)))
6271 (cond
6272 ((and target prop)
6273 (cond
6274 ((string= target-name "Number")
6275 (if (string-match js2-ecma-number-props prop-name)
6276 'font-lock-constant-face))
6277 ((string= target-name "Math")
6278 (if (string-match js2-ecma-math-props prop-name)
6279 'font-lock-constant-face))))
6280 (prop
6281 (if (string-match js2-ecma-object-props prop-name)
6282 'font-lock-constant-face))))))
6283 (when face
6284 (let ((pos (+ (js2-node-pos parent) ; absolute
6285 (js2-node-pos prop)))) ; relative
6286 (js2-set-face pos
6287 (+ pos (js2-node-len prop))
6288 face 'record)))))))
6289
6290 (defun js2-parse-highlight-member-expr-node (node)
6291 "Perform syntax highlighting of EcmaScript built-in properties.
6292 The variable `js2-highlight-level' governs this highighting."
6293 (let (face target prop name pos end parent call-p callee)
6294 (cond
6295 ;; case 1: simple name, e.g. foo
6296 ((js2-name-node-p node)
6297 (setq name (js2-name-node-name node))
6298 ;; possible for name to be nil in rare cases - saw it when
6299 ;; running js2-mode on an elisp buffer. Might as well try to
6300 ;; make it so js2-mode never barfs.
6301 (when name
6302 (setq face (if (string-match js2-ecma-global-props name)
6303 'font-lock-constant-face))
6304 (when face
6305 (setq pos (js2-node-pos node)
6306 end (+ pos (js2-node-len node)))
6307 (js2-set-face pos end face 'record))))
6308 ;; case 2: property access or function call
6309 ((or (js2-prop-get-node-p node)
6310 ;; highlight function call if expr is a prop-get node
6311 ;; or a plain name (i.e. unqualified function call)
6312 (and (setq call-p (js2-call-node-p node))
6313 (setq callee (js2-call-node-target node)) ; separate setq!
6314 (or (js2-prop-get-node-p callee)
6315 (js2-name-node-p callee))))
6316 (setq parent node
6317 node (if call-p callee node))
6318 (if (and call-p (js2-name-node-p callee))
6319 (setq prop callee)
6320 (setq target (js2-prop-get-node-left node)
6321 prop (js2-prop-get-node-right node)))
6322 (cond
6323 ((js2-name-node-p prop)
6324 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6325 (js2-parse-highlight-prop-get parent target prop call-p))
6326 ((js2-name-node-p target)
6327 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6328 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6329
6330 (defun js2-parse-highlight-member-expr-fn-name (expr)
6331 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6332 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6333 We currently only handle the case where the last component is a prop-get
6334 of a simple name. Called before EXPR has a parent node."
6335 (let (pos
6336 (name (and (js2-prop-get-node-p expr)
6337 (js2-prop-get-node-right expr))))
6338 (when (js2-name-node-p name)
6339 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6340 (js2-node-pos name)))
6341 (+ pos (js2-node-len name))
6342 'font-lock-function-name-face
6343 'record))))
6344
6345 ;; source: http://jsdoc.sourceforge.net/
6346 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6347 ;; allows type specifications, and needs work before entering the wild.
6348
6349 (defconst js2-jsdoc-param-tag-regexp
6350 (concat "^\\s-*\\*+\\s-*\\(@"
6351 "\\(?:param\\|argument\\)"
6352 "\\)"
6353 "\\s-*\\({[^}]+}\\)?" ; optional type
6354 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6355 "\\>")
6356 "Matches jsdoc tags with optional type and optional param name.")
6357
6358 (defconst js2-jsdoc-typed-tag-regexp
6359 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6360 (regexp-opt
6361 '("enum"
6362 "extends"
6363 "field"
6364 "id"
6365 "implements"
6366 "lends"
6367 "mods"
6368 "requires"
6369 "return"
6370 "returns"
6371 "throw"
6372 "throws"))
6373 "\\)\\)\\s-*\\({[^}]+}\\)?")
6374 "Matches jsdoc tags with optional type.")
6375
6376 (defconst js2-jsdoc-arg-tag-regexp
6377 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6378 (regexp-opt
6379 '("alias"
6380 "augments"
6381 "borrows"
6382 "bug"
6383 "base"
6384 "config"
6385 "default"
6386 "define"
6387 "exception"
6388 "function"
6389 "member"
6390 "memberOf"
6391 "name"
6392 "namespace"
6393 "property"
6394 "since"
6395 "suppress"
6396 "this"
6397 "throws"
6398 "type"
6399 "version"))
6400 "\\)\\)\\s-+\\([^ \t]+\\)")
6401 "Matches jsdoc tags with a single argument.")
6402
6403 (defconst js2-jsdoc-empty-tag-regexp
6404 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6405 (regexp-opt
6406 '("addon"
6407 "author"
6408 "class"
6409 "const"
6410 "constant"
6411 "constructor"
6412 "constructs"
6413 "deprecated"
6414 "desc"
6415 "description"
6416 "event"
6417 "example"
6418 "exec"
6419 "export"
6420 "fileoverview"
6421 "final"
6422 "function"
6423 "hidden"
6424 "ignore"
6425 "implicitCast"
6426 "inheritDoc"
6427 "inner"
6428 "interface"
6429 "license"
6430 "noalias"
6431 "noshadow"
6432 "notypecheck"
6433 "override"
6434 "owner"
6435 "preserve"
6436 "preserveTry"
6437 "private"
6438 "protected"
6439 "public"
6440 "static"
6441 "supported"
6442 ))
6443 "\\)\\)\\s-*")
6444 "Matches empty jsdoc tags.")
6445
6446 (defconst js2-jsdoc-link-tag-regexp
6447 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6448 "Matches a jsdoc link or code tag.")
6449
6450 (defconst js2-jsdoc-see-tag-regexp
6451 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6452 "Matches a jsdoc @see tag.")
6453
6454 (defconst js2-jsdoc-html-tag-regexp
6455 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6456 "Matches a simple (no attributes) html start- or end-tag.")
6457
6458 (defun js2-jsdoc-highlight-helper ()
6459 (js2-set-face (match-beginning 1)
6460 (match-end 1)
6461 'js2-jsdoc-tag)
6462 (if (match-beginning 2)
6463 (if (save-excursion
6464 (goto-char (match-beginning 2))
6465 (= (char-after) ?{))
6466 (js2-set-face (1+ (match-beginning 2))
6467 (1- (match-end 2))
6468 'js2-jsdoc-type)
6469 (js2-set-face (match-beginning 2)
6470 (match-end 2)
6471 'js2-jsdoc-value)))
6472 (if (match-beginning 3)
6473 (js2-set-face (match-beginning 3)
6474 (match-end 3)
6475 'js2-jsdoc-value)))
6476
6477 (defun js2-highlight-jsdoc (ast)
6478 "Highlight doc comment tags."
6479 (let ((comments (js2-ast-root-comments ast))
6480 beg end)
6481 (save-excursion
6482 (dolist (node comments)
6483 (when (eq (js2-comment-node-format node) 'jsdoc)
6484 (setq beg (js2-node-abs-pos node)
6485 end (+ beg (js2-node-len node)))
6486 (save-restriction
6487 (narrow-to-region beg end)
6488 (dolist (re (list js2-jsdoc-param-tag-regexp
6489 js2-jsdoc-typed-tag-regexp
6490 js2-jsdoc-arg-tag-regexp
6491 js2-jsdoc-link-tag-regexp
6492 js2-jsdoc-see-tag-regexp
6493 js2-jsdoc-empty-tag-regexp))
6494 (goto-char beg)
6495 (while (re-search-forward re nil t)
6496 (js2-jsdoc-highlight-helper)))
6497 ;; simple highlighting for html tags
6498 (goto-char beg)
6499 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6500 (js2-set-face (match-beginning 1)
6501 (match-end 1)
6502 'js2-jsdoc-html-tag-delimiter)
6503 (js2-set-face (match-beginning 2)
6504 (match-end 2)
6505 'js2-jsdoc-html-tag-name)
6506 (js2-set-face (match-beginning 3)
6507 (match-end 3)
6508 'js2-jsdoc-html-tag-delimiter))))))))
6509
6510 (defun js2-highlight-assign-targets (_node left right)
6511 "Highlight function properties and external variables."
6512 (let (leftpos name)
6513 ;; highlight vars and props assigned function values
6514 (when (js2-function-node-p right)
6515 (cond
6516 ;; var foo = function() {...}
6517 ((js2-name-node-p left)
6518 (setq name left))
6519 ;; foo.bar.baz = function() {...}
6520 ((and (js2-prop-get-node-p left)
6521 (js2-name-node-p (js2-prop-get-node-right left)))
6522 (setq name (js2-prop-get-node-right left))))
6523 (when name
6524 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6525 (+ leftpos (js2-node-len name))
6526 'font-lock-function-name-face
6527 'record)))))
6528
6529 (defun js2-record-name-node (node)
6530 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6531 later. NODE must be a name node."
6532 (let ((leftpos (js2-node-abs-pos node)))
6533 (push (list node js2-current-scope
6534 leftpos
6535 (+ leftpos (js2-node-len node)))
6536 js2-recorded-identifiers)))
6537
6538 (defun js2-highlight-undeclared-vars ()
6539 "After entire parse is finished, look for undeclared variable references.
6540 We have to wait until entire buffer is parsed, since JavaScript permits var
6541 decls to occur after they're used.
6542
6543 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6544 it is considered declared."
6545 (let (name)
6546 (dolist (entry js2-recorded-identifiers)
6547 (destructuring-bind (name-node scope pos end) entry
6548 (setq name (js2-name-node-name name-node))
6549 (unless (or (member name js2-global-externs)
6550 (member name js2-default-externs)
6551 (member name js2-additional-externs)
6552 (js2-get-defining-scope scope name))
6553 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6554 'js2-external-variable))))
6555 (setq js2-recorded-identifiers nil)))
6556
6557 (defun js2-set-default-externs ()
6558 "Set the value of `js2-default-externs' based on the various
6559 `js2-include-?-externs' variables."
6560 (setq js2-default-externs
6561 (append js2-ecma-262-externs
6562 (if js2-include-browser-externs js2-browser-externs)
6563 (if js2-include-rhino-externs js2-rhino-externs)
6564 (if js2-include-node-externs js2-node-externs)
6565 (if (or js2-include-browser-externs js2-include-node-externs)
6566 js2-typed-array-externs))))
6567
6568 (defun js2-apply-jslint-globals ()
6569 (setq js2-additional-externs
6570 (nconc (js2-get-jslint-globals)
6571 js2-additional-externs)))
6572
6573 (defun js2-get-jslint-globals ()
6574 (loop for node in (js2-ast-root-comments js2-mode-ast)
6575 when (and (eq 'block (js2-comment-node-format node))
6576 (save-excursion
6577 (goto-char (js2-node-abs-pos node))
6578 (looking-at "/\\*global ")))
6579 append (js2-get-jslint-globals-in
6580 (match-end 0)
6581 (js2-node-abs-end node))))
6582
6583 (defun js2-get-jslint-globals-in (beg end)
6584 (let (res)
6585 (save-excursion
6586 (goto-char beg)
6587 (while (re-search-forward js2-mode-identifier-re end t)
6588 (let ((match (match-string 0)))
6589 (unless (member match '("true" "false"))
6590 (push match res)))))
6591 (nreverse res)))
6592
6593 ;;; IMenu support
6594
6595 ;; We currently only support imenu, but eventually should support speedbar and
6596 ;; possibly other browsing mechanisms.
6597
6598 ;; The basic strategy is to identify function assignment targets of the form
6599 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6600 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6601 ;; for imenu after parsing is finished.
6602
6603 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6604 ;; JavaScript, and the general problem is undecidable. However, several forms
6605 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6606 ;; include:
6607
6608 ;; function foo() -- function declaration
6609 ;; foo = function() -- function expression assigned to variable
6610 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6611 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6612 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6613 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6614 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6615 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6616 ;; function foo() {function bar() {...}} -- nested function
6617 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6618
6619 ;; This list boils down to a few forms that can be combined recursively.
6620 ;; Top-level named function declarations include both the left-hand (name)
6621 ;; and the right-hand (function value) expressions needed to produce an imenu
6622 ;; entry. The other "right-hand" forms we need to look for are:
6623 ;; - functions declared as props/getters/setters in object literals
6624 ;; - nested named function declarations
6625 ;; The "left-hand" expressions that functions can be assigned to include:
6626 ;; - local/global variables
6627 ;; - nested property-get expressions like a.b.c.d
6628 ;; - element gets like foo[10] or foo['bar'] where the index
6629 ;; expression can be trivially converted to a property name. They
6630 ;; effectively then become property gets.
6631
6632 ;; All the different definition types are canonicalized into the form
6633 ;; foo.bar.baz = position-of-function-keyword
6634
6635 ;; We need to build a trie-like structure for imenu. As an example,
6636 ;; consider the following JavaScript code:
6637
6638 ;; a = function() {...} // function at position 5
6639 ;; b = function() {...} // function at position 25
6640 ;; foo = function() {...} // function at position 100
6641 ;; foo.bar = function() {...} // function at position 200
6642 ;; foo.bar.baz = function() {...} // function at position 300
6643 ;; foo.bar.zab = function() {...} // function at position 400
6644
6645 ;; During parsing we accumulate an entry for each definition in
6646 ;; the variable `js2-imenu-recorder', like so:
6647
6648 ;; '((fn a 5)
6649 ;; (fn b 25)
6650 ;; (fn foo 100)
6651 ;; (fn foo bar 200)
6652 ;; (fn foo bar baz 300)
6653 ;; (fn foo bar zab 400))
6654
6655 ;; Where 'fn' is the respective function node.
6656 ;; After parsing these entries are merged into this alist-trie:
6657
6658 ;; '((a . 1)
6659 ;; (b . 2)
6660 ;; (foo (<definition> . 3)
6661 ;; (bar (<definition> . 6)
6662 ;; (baz . 100)
6663 ;; (zab . 200))))
6664
6665 ;; Note the wacky need for a <definition> name. The token can be anything
6666 ;; that isn't a valid JavaScript identifier, because you might make foo
6667 ;; a function and then start setting properties on it that are also functions.
6668
6669 (defun js2-prop-node-name (node)
6670 "Return the name of a node that may be a property-get/property-name.
6671 If NODE is not a valid name-node, string-node or integral number-node,
6672 returns nil. Otherwise returns the string name/value of the node."
6673 (cond
6674 ((js2-name-node-p node)
6675 (js2-name-node-name node))
6676 ((js2-string-node-p node)
6677 (js2-string-node-value node))
6678 ((and (js2-number-node-p node)
6679 (string-match "^[0-9]+$" (js2-number-node-value node)))
6680 (js2-number-node-value node))
6681 ((js2-this-node-p node)
6682 "this")))
6683
6684 (defun js2-node-qname-component (node)
6685 "Return the name of this node, if it contributes to a qname.
6686 Returns nil if the node doesn't contribute."
6687 (copy-sequence
6688 (or (js2-prop-node-name node)
6689 (if (and (js2-function-node-p node)
6690 (js2-function-node-name node))
6691 (js2-name-node-name (js2-function-node-name node))))))
6692
6693 (defun js2-record-imenu-entry (fn-node qname pos)
6694 "Add an entry to `js2-imenu-recorder'.
6695 FN-NODE should be the current item's function node.
6696
6697 Associate FN-NODE with its QNAME for later lookup.
6698 This is used in postprocessing the chain list. For each chain, we find
6699 the parent function, look up its qname, then prepend a copy of it to the chain."
6700 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6701 (unless js2-imenu-function-map
6702 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6703 (puthash fn-node qname js2-imenu-function-map))
6704
6705 (defun js2-record-imenu-functions (node &optional var)
6706 "Record function definitions for imenu.
6707 NODE is a function node or an object literal.
6708 VAR, if non-nil, is the expression that NODE is being assigned to.
6709 When passed arguments of wrong type, does nothing."
6710 (when js2-parse-ide-mode
6711 (let ((fun-p (js2-function-node-p node))
6712 qname fname-node)
6713 (cond
6714 ;; non-anonymous function declaration?
6715 ((and fun-p
6716 (not var)
6717 (setq fname-node (js2-function-node-name node)))
6718 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6719 ;; for remaining forms, compute left-side tree branch first
6720 ((and var (setq qname (js2-compute-nested-prop-get var)))
6721 (cond
6722 ;; foo.bar.baz = function
6723 (fun-p
6724 (js2-record-imenu-entry node qname (js2-node-pos node)))
6725 ;; foo.bar.baz = object-literal
6726 ;; look for nested functions: {a: {b: function() {...} }}
6727 ((js2-object-node-p node)
6728 ;; Node position here is still absolute, since the parser
6729 ;; passes the assignment target and value expressions
6730 ;; to us before they are added as children of the assignment node.
6731 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6732
6733 (defun js2-compute-nested-prop-get (node)
6734 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6735 component nodes as a list. Otherwise return nil. Element-gets are treated
6736 as property-gets if the index expression is a string, or a positive integer."
6737 (let (left right head)
6738 (cond
6739 ((or (js2-name-node-p node)
6740 (js2-this-node-p node))
6741 (list node))
6742 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6743 ((js2-prop-get-node-p node) ; foo.bar
6744 (setq left (js2-prop-get-node-left node)
6745 right (js2-prop-get-node-right node))
6746 (if (setq head (js2-compute-nested-prop-get left))
6747 (nconc head (list right))))
6748 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6749 (setq left (js2-elem-get-node-target node)
6750 right (js2-elem-get-node-element node))
6751 (if (or (js2-string-node-p right) ; ['bar']
6752 (and (js2-number-node-p right) ; [10]
6753 (string-match "^[0-9]+$"
6754 (js2-number-node-value right))))
6755 (if (setq head (js2-compute-nested-prop-get left))
6756 (nconc head (list right))))))))
6757
6758 (defun js2-record-object-literal (node qname pos)
6759 "Recursively process an object literal looking for functions.
6760 NODE is an object literal that is the right-hand child of an assignment
6761 expression. QNAME is a list of nodes representing the assignment target,
6762 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6763 POS is the absolute position of the node.
6764 We do a depth-first traversal of NODE. For any functions we find,
6765 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6766 (let (right)
6767 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6768 (let ((left (js2-infix-node-left e))
6769 ;; Element positions are relative to the parent position.
6770 (pos (+ pos (js2-node-pos e))))
6771 (cond
6772 ;; foo: function() {...}
6773 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6774 (when (js2-prop-node-name left)
6775 ;; As a policy decision, we record the position of the property,
6776 ;; not the position of the `function' keyword, since the property
6777 ;; is effectively the name of the function.
6778 (js2-record-imenu-entry right (append qname (list left)) pos)))
6779 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6780 ((js2-object-node-p right)
6781 (js2-record-object-literal right
6782 (append qname (list (js2-infix-node-left e)))
6783 (+ pos (js2-node-pos right)))))))))
6784
6785 (defun js2-node-top-level-decl-p (node)
6786 "Return t if NODE's name is defined in the top-level scope.
6787 Also returns t if NODE's name is not defined in any scope, since it implies
6788 that it's an external variable, which must also be in the top-level scope."
6789 (let* ((name (js2-prop-node-name node))
6790 (this-scope (js2-node-get-enclosing-scope node))
6791 defining-scope)
6792 (cond
6793 ((js2-this-node-p node)
6794 nil)
6795 ((null this-scope)
6796 t)
6797 ((setq defining-scope (js2-get-defining-scope this-scope name))
6798 (js2-ast-root-p defining-scope))
6799 (t t))))
6800
6801 (defun js2-wrapper-function-p (node)
6802 "Return t if NODE is a function expression that's immediately invoked.
6803 NODE must be `js2-function-node'."
6804 (let ((parent (js2-node-parent node)))
6805 (or
6806 ;; function(){...}();
6807 (js2-call-node-p parent)
6808 (and (js2-paren-node-p parent)
6809 ;; (function(){...})();
6810 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6811 ;; (function(){...}).call(this);
6812 (and (js2-prop-get-node-p parent)
6813 (member (js2-name-node-name (js2-prop-get-node-right parent))
6814 '("call" "apply"))
6815 (js2-call-node-p (js2-node-parent parent))))))))
6816
6817 (defun js2-browse-postprocess-chains (entries)
6818 "Modify function-declaration name chains after parsing finishes.
6819 Some of the information is only available after the parse tree is complete.
6820 For instance, processing a nested scope requires a parent function node."
6821 (let (result fn parent-qname p elem)
6822 (dolist (entry entries)
6823 ;; function node goes first
6824 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6825 ;; Examine head's defining scope:
6826 ;; Pre-processed chain, or top-level/external, keep as-is.
6827 (if (or (stringp head) (js2-node-top-level-decl-p head))
6828 (push chain result)
6829 (when (js2-this-node-p head)
6830 (setq chain (cdr chain))) ; discard this-node
6831 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6832 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6833 (when (eq parent-qname 'not-found)
6834 ;; anonymous function expressions are not recorded
6835 ;; during the parse, so we need to handle this case here
6836 (setq parent-qname
6837 (if (js2-wrapper-function-p fn)
6838 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6839 (if (js2-ast-root-p grandparent)
6840 nil
6841 (gethash grandparent js2-imenu-function-map 'skip)))
6842 'skip))
6843 (puthash fn parent-qname js2-imenu-function-map))
6844 (unless (eq parent-qname 'skip)
6845 ;; prefix parent fn qname to this chain.
6846 (let ((qname (append parent-qname chain)))
6847 (puthash current-fn (butlast qname) js2-imenu-function-map)
6848 (push qname result)))))))
6849 ;; finally replace each node in each chain with its name.
6850 (dolist (chain result)
6851 (setq p chain)
6852 (while p
6853 (if (js2-node-p (setq elem (car p)))
6854 (setcar p (js2-node-qname-component elem)))
6855 (setq p (cdr p))))
6856 result))
6857
6858 ;; Merge name chains into a trie-like tree structure of nested lists.
6859 ;; To simplify construction of the trie, we first build it out using the rule
6860 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6861 ;; [key, num-or-list]. The second element can be a number; if so, this key
6862 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6863 ;; associated with the key at this level.) Otherwise the second element is
6864 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6865 ;; a simple recursive formulation.
6866 ;;
6867 ;; js2-mode is building the data structure for imenu. The imenu documentation
6868 ;; claims that it's the structure above, but in practice it wants the children
6869 ;; at the same list level as the key for that level, which is how I've drawn
6870 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6871 ;; list wrapper around the children at each level.
6872 ;;
6873 ;; A completed nested imenu-alist entry looks like this:
6874 ;; '(("foo"
6875 ;; ("<definition>" . 7)
6876 ;; ("bar"
6877 ;; ("a" . 40)
6878 ;; ("b" . 60))))
6879 ;;
6880 ;; In particular, the documentation for `imenu--index-alist' says that
6881 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6882 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6883
6884 (defun js2-treeify (lst)
6885 "Convert (a b c d) to (a ((b ((c d)))))."
6886 (if (null (cddr lst)) ; list length <= 2
6887 lst
6888 (list (car lst) (list (js2-treeify (cdr lst))))))
6889
6890 (defun js2-build-alist-trie (chains trie)
6891 "Merge declaration name chains into a trie-like alist structure for imenu.
6892 CHAINS is the qname chain list produced during parsing. TRIE is a
6893 list of elements built up so far."
6894 (let (head tail pos branch kids)
6895 (dolist (chain chains)
6896 (setq head (car chain)
6897 tail (cdr chain)
6898 pos (if (numberp (car tail)) (car tail))
6899 branch (js2-find-if (lambda (n)
6900 (string= (car n) head))
6901 trie)
6902 kids (second branch))
6903 (cond
6904 ;; case 1: this key isn't in the trie yet
6905 ((null branch)
6906 (if trie
6907 (setcdr (last trie) (list (js2-treeify chain)))
6908 (setq trie (list (js2-treeify chain)))))
6909 ;; case 2: key is present with a single number entry: replace w/ list
6910 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6911 ;; ("<definition>" 20)))
6912 ((numberp kids)
6913 (setcar (cdr branch)
6914 (list (list "<definition-1>" kids)
6915 (if pos
6916 (list "<definition-2>" pos)
6917 (js2-treeify tail)))))
6918 ;; case 3: key is there (with kids), and we're a number entry
6919 (pos
6920 (setcdr (last kids)
6921 (list
6922 (list (format "<definition-%d>"
6923 (1+ (loop for kid in kids
6924 count (eq ?< (aref (car kid) 0)))))
6925 pos))))
6926 ;; case 4: key is there with kids, need to merge in our chain
6927 (t
6928 (js2-build-alist-trie (list tail) kids))))
6929 trie))
6930
6931 (defun js2-flatten-trie (trie)
6932 "Convert TRIE to imenu-format.
6933 Recurses through nodes, and for each one whose second element is a list,
6934 appends the list's flattened elements to the current element. Also
6935 changes the tails into conses. For instance, this pre-flattened trie
6936
6937 '(a ((b 20)
6938 (c ((d 30)
6939 (e 40)))))
6940
6941 becomes
6942
6943 '(a (b . 20)
6944 (c (d . 30)
6945 (e . 40)))
6946
6947 Note that the root of the trie has no key, just a list of chains.
6948 This is also true for the value of any key with multiple children,
6949 e.g. key 'c' in the example above."
6950 (cond
6951 ((listp (car trie))
6952 (mapcar #'js2-flatten-trie trie))
6953 (t
6954 (if (numberp (second trie))
6955 (cons (car trie) (second trie))
6956 ;; else pop list and append its kids
6957 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6958
6959 (defun js2-build-imenu-index ()
6960 "Turn `js2-imenu-recorder' into an imenu data structure."
6961 (unless (eq js2-imenu-recorder 'empty)
6962 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
6963 (result (js2-build-alist-trie chains nil)))
6964 (js2-flatten-trie result))))
6965
6966 (defun js2-test-print-chains (chains)
6967 "Print a list of qname chains.
6968 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
6969 i.e. one or more nodes, and an integer position as the list tail."
6970 (mapconcat (lambda (chain)
6971 (concat "("
6972 (mapconcat (lambda (elem)
6973 (if (js2-node-p elem)
6974 (or (js2-node-qname-component elem)
6975 "nil")
6976 (number-to-string elem)))
6977 chain
6978 " ")
6979 ")"))
6980 chains
6981 "\n"))
6982
6983 ;;; Parser
6984
6985 (defconst js2-version "1.8.5"
6986 "Version of JavaScript supported.")
6987
6988 (defun js2-record-face (face &optional token)
6989 "Record a style run of FACE for TOKEN or the current token."
6990 (unless token (setq token (js2-current-token)))
6991 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
6992
6993 (defsubst js2-node-end (n)
6994 "Computes the absolute end of node N.
6995 Use with caution! Assumes `js2-node-pos' is -absolute-, which
6996 is only true until the node is added to its parent; i.e., while parsing."
6997 (+ (js2-node-pos n)
6998 (js2-node-len n)))
6999
7000 (defun js2-record-comment (token)
7001 "Record a comment in `js2-scanned-comments'."
7002 (let ((ct (js2-token-comment-type token))
7003 (beg (js2-token-beg token))
7004 (end (js2-token-end token)))
7005 (push (make-js2-comment-node :len (- end beg)
7006 :format ct)
7007 js2-scanned-comments)
7008 (when js2-parse-ide-mode
7009 (js2-record-face (if (eq ct 'jsdoc)
7010 'font-lock-doc-face
7011 'font-lock-comment-face)
7012 token)
7013 (when (memq ct '(html preprocessor))
7014 ;; Tell cc-engine the bounds of the comment.
7015 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7016
7017 (defun js2-peek-token ()
7018 "Return the next token type without consuming it.
7019 If `js2-ti-lookahead' is positive, return the type of next token
7020 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7021 (if (not (zerop js2-ti-lookahead))
7022 (js2-token-type
7023 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7024 (let ((tt (js2-get-token-internal)))
7025 (js2-unget-token)
7026 tt)))
7027
7028 (defalias 'js2-next-token 'js2-get-token)
7029
7030 (defun js2-match-token (match &optional dont-unget)
7031 "Get next token and return t if it matches MATCH, a bytecode.
7032 Returns nil and consumes nothing if MATCH is not the next token."
7033 (if (/= (js2-get-token) match)
7034 (ignore (unless dont-unget (js2-unget-token)))
7035 t))
7036
7037 (defun js2-match-contextual-kwd (name)
7038 "Consume and return t if next token is `js2-NAME', and its
7039 string is NAME. Returns nil and keeps current token otherwise."
7040 (if (or (/= (js2-get-token) js2-NAME)
7041 (not (string= (js2-current-token-string) name)))
7042 (progn
7043 (js2-unget-token)
7044 nil)
7045 (js2-record-face 'font-lock-keyword-face)
7046 t))
7047
7048 (defun js2-valid-prop-name-token (tt)
7049 (or (= tt js2-NAME)
7050 (and js2-allow-keywords-as-property-names
7051 (plusp tt)
7052 (or (= tt js2-RESERVED)
7053 (aref js2-kwd-tokens tt)))))
7054
7055 (defun js2-match-prop-name ()
7056 "Consume token and return t if next token is a valid property name.
7057 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7058 is non-nil and it's a keyword token."
7059 (if (js2-valid-prop-name-token (js2-get-token))
7060 t
7061 (js2-unget-token)
7062 nil))
7063
7064 (defun js2-must-match-prop-name (msg-id &optional pos len)
7065 (if (js2-match-prop-name)
7066 t
7067 (js2-report-error msg-id nil pos len)
7068 nil))
7069
7070 (defun js2-peek-token-or-eol ()
7071 "Return js2-EOL if the next token immediately follows a newline.
7072 Else returns the next token. Used in situations where we don't
7073 consider certain token types valid if they are preceded by a newline.
7074 One example is the postfix ++ or -- operator, which has to be on the
7075 same line as its operand."
7076 (let ((tt (js2-get-token))
7077 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7078 (js2-unget-token)
7079 (if follows-eol
7080 js2-EOL
7081 tt)))
7082
7083 (defun js2-must-match (token msg-id &optional pos len)
7084 "Match next token to token code TOKEN, or record a syntax error.
7085 MSG-ID is the error message to report if the match fails.
7086 Returns t on match, nil if no match."
7087 (if (js2-match-token token t)
7088 t
7089 (js2-report-error msg-id nil pos len)
7090 (js2-unget-token)
7091 nil))
7092
7093 (defun js2-must-match-name (msg-id)
7094 (if (js2-match-token js2-NAME t)
7095 t
7096 (if (eq (js2-current-token-type) js2-RESERVED)
7097 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7098 (js2-report-error msg-id)
7099 (js2-unget-token))
7100 nil))
7101
7102 (defsubst js2-inside-function ()
7103 (plusp js2-nesting-of-function))
7104
7105 (defun js2-set-requires-activation ()
7106 (if (js2-function-node-p js2-current-script-or-fn)
7107 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7108
7109 (defun js2-check-activation-name (name _token)
7110 (when (js2-inside-function)
7111 ;; skip language-version 1.2 check from Rhino
7112 (if (or (string= "arguments" name)
7113 (and js2-compiler-activation-names ; only used in codegen
7114 (gethash name js2-compiler-activation-names)))
7115 (js2-set-requires-activation))))
7116
7117 (defun js2-set-is-generator ()
7118 (let ((fn-node js2-current-script-or-fn))
7119 (when (and (js2-function-node-p fn-node)
7120 (not (js2-function-node-generator-type fn-node)))
7121 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7122
7123 (defun js2-must-have-xml ()
7124 (unless js2-compiler-xml-available
7125 (js2-report-error "msg.XML.not.available")))
7126
7127 (defun js2-push-scope (scope)
7128 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7129 (assert (js2-scope-p scope))
7130 (assert (null (js2-scope-parent-scope scope)))
7131 (assert (not (eq js2-current-scope scope)))
7132 (setf (js2-scope-parent-scope scope) js2-current-scope
7133 js2-current-scope scope))
7134
7135 (defsubst js2-pop-scope ()
7136 (setq js2-current-scope
7137 (js2-scope-parent-scope js2-current-scope)))
7138
7139 (defun js2-enter-loop (loop-node)
7140 (push loop-node js2-loop-set)
7141 (push loop-node js2-loop-and-switch-set)
7142 (js2-push-scope loop-node)
7143 ;; Tell the current labeled statement (if any) its statement,
7144 ;; and set the jump target of the first label to the loop.
7145 ;; These are used in `js2-parse-continue' to verify that the
7146 ;; continue target is an actual labeled loop. (And for codegen.)
7147 (when js2-labeled-stmt
7148 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7149 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7150 js2-labeled-stmt))) loop-node)))
7151
7152 (defun js2-exit-loop ()
7153 (pop js2-loop-set)
7154 (pop js2-loop-and-switch-set)
7155 (js2-pop-scope))
7156
7157 (defsubst js2-enter-switch (switch-node)
7158 (push switch-node js2-loop-and-switch-set))
7159
7160 (defsubst js2-exit-switch ()
7161 (pop js2-loop-and-switch-set))
7162
7163 (defun js2-parse (&optional buf cb)
7164 "Tell the js2 parser to parse a region of JavaScript.
7165
7166 BUF is a buffer or buffer name containing the code to parse.
7167 Call `narrow-to-region' first to parse only part of the buffer.
7168
7169 The returned AST root node is given some additional properties:
7170 `node-count' - total number of nodes in the AST
7171 `buffer' - BUF. The buffer it refers to may change or be killed,
7172 so the value is not necessarily reliable.
7173
7174 An optional callback CB can be specified to report parsing
7175 progress. If `(functionp CB)' returns t, it will be called with
7176 the current line number once before parsing begins, then again
7177 each time the lexer reaches a new line number.
7178
7179 CB can also be a list of the form `(symbol cb ...)' to specify
7180 multiple callbacks with different criteria. Each symbol is a
7181 criterion keyword, and the following element is the callback to
7182 call
7183
7184 :line - called whenever the line number changes
7185 :token - called for each new token consumed
7186
7187 The list of criteria could be extended to include entering or
7188 leaving a statement, an expression, or a function definition."
7189 (if (and cb (not (functionp cb)))
7190 (error "criteria callbacks not yet implemented"))
7191 (let ((inhibit-point-motion-hooks t)
7192 (js2-compiler-xml-available (>= js2-language-version 160))
7193 ;; This is a recursive-descent parser, so give it a big stack.
7194 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7195 (max-specpdl-size (max max-specpdl-size 3000))
7196 (case-fold-search nil)
7197 ast)
7198 (with-current-buffer (or buf (current-buffer))
7199 (setq js2-scanned-comments nil
7200 js2-parsed-errors nil
7201 js2-parsed-warnings nil
7202 js2-imenu-recorder nil
7203 js2-imenu-function-map nil
7204 js2-label-set nil)
7205 (js2-init-scanner)
7206 (setq ast (with-silent-modifications
7207 (js2-do-parse)))
7208 (unless js2-ts-hit-eof
7209 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7210 (setf (js2-ast-root-errors ast) js2-parsed-errors
7211 (js2-ast-root-warnings ast) js2-parsed-warnings)
7212 ;; if we didn't find any declarations, put a dummy in this list so we
7213 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7214 (unless js2-imenu-recorder
7215 (setq js2-imenu-recorder 'empty))
7216 (run-hooks 'js2-parse-finished-hook)
7217 ast)))
7218
7219 ;; Corresponds to Rhino's Parser.parse() method.
7220 (defun js2-do-parse ()
7221 "Parse current buffer starting from current point.
7222 Scanner should be initialized."
7223 (let ((pos js2-ts-cursor)
7224 (end js2-ts-cursor) ; in case file is empty
7225 root n tt)
7226 ;; initialize buffer-local parsing vars
7227 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7228 js2-current-script-or-fn root
7229 js2-current-scope root
7230 js2-nesting-of-function 0
7231 js2-labeled-stmt nil
7232 js2-recorded-identifiers nil) ; for js2-highlight
7233 (while (/= (setq tt (js2-get-token)) js2-EOF)
7234 (if (= tt js2-FUNCTION)
7235 (progn
7236 (setq n (if js2-called-by-compile-function
7237 (js2-parse-function-expr)
7238 (js2-parse-function-stmt))))
7239 ;; not a function - parse a statement
7240 (js2-unget-token)
7241 (setq n (js2-parse-statement)))
7242 ;; add function or statement to script
7243 (setq end (js2-node-end n))
7244 (js2-block-node-push root n))
7245 ;; add comments to root in lexical order
7246 (when js2-scanned-comments
7247 ;; if we find a comment beyond end of normal kids, use its end
7248 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7249 (dolist (comment js2-scanned-comments)
7250 (push comment (js2-ast-root-comments root))
7251 (js2-node-add-children root comment)))
7252 (setf (js2-node-len root) (- end pos))
7253 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7254 ;; Give extensions a chance to muck with things before highlighting starts.
7255 (let ((js2-additional-externs js2-additional-externs))
7256 (save-excursion
7257 (run-hooks 'js2-post-parse-callbacks))
7258 (js2-highlight-undeclared-vars))
7259 root))
7260
7261 (defun js2-parse-function-closure-body (fn-node)
7262 "Parse a JavaScript 1.8 function closure body."
7263 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7264 (if js2-ts-hit-eof
7265 (js2-report-error "msg.no.brace.body" nil
7266 (js2-node-pos fn-node)
7267 (- js2-ts-cursor (js2-node-pos fn-node)))
7268 (js2-node-add-children fn-node
7269 (setf (js2-function-node-body fn-node)
7270 (js2-parse-expr t))))))
7271
7272 (defun js2-parse-function-body (fn-node)
7273 (js2-must-match js2-LC "msg.no.brace.body"
7274 (js2-node-pos fn-node)
7275 (- js2-ts-cursor (js2-node-pos fn-node)))
7276 (let ((pos (js2-current-token-beg)) ; LC position
7277 (pn (make-js2-block-node)) ; starts at LC position
7278 tt
7279 end)
7280 (incf js2-nesting-of-function)
7281 (unwind-protect
7282 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7283 (= tt js2-EOF)
7284 (= tt js2-RC)))
7285 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7286 (js2-parse-statement)
7287 (js2-get-token)
7288 (js2-parse-function-stmt))))
7289 (decf js2-nesting-of-function))
7290 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7291 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7292 (setq end (js2-current-token-end)))
7293 (setf (js2-node-pos pn) pos
7294 (js2-node-len pn) (- end pos))
7295 (setf (js2-function-node-body fn-node) pn)
7296 (js2-node-add-children fn-node pn)
7297 pn))
7298
7299 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7300 "Declare and fontify destructuring parameters inside NODE.
7301 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7302 (cond
7303 ((js2-name-node-p node)
7304 (let (leftpos)
7305 (js2-define-symbol decl-type (js2-name-node-name node)
7306 node ignore-not-in-block)
7307 (when face
7308 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7309 (+ leftpos (js2-node-len node))
7310 face 'record))))
7311 ((js2-object-node-p node)
7312 (dolist (elem (js2-object-node-elems node))
7313 (js2-define-destruct-symbols
7314 (if (js2-object-prop-node-p elem)
7315 (js2-object-prop-node-right elem)
7316 ;; abbreviated destructuring {a, b}
7317 elem)
7318 decl-type face ignore-not-in-block)))
7319 ((js2-array-node-p node)
7320 (dolist (elem (js2-array-node-elems node))
7321 (when elem
7322 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7323 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7324 (js2-node-len node)))))
7325
7326 (defun js2-parse-function-params (function-type fn-node pos)
7327 (if (js2-match-token js2-RP)
7328 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7329 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7330 (eq (js2-current-token-type) js2-NAME)))
7331 params param default-found rest-param-at)
7332 (when paren-free-arrow
7333 (js2-unget-token))
7334 (loop for tt = (js2-peek-token)
7335 do
7336 (cond
7337 ;; destructuring param
7338 ((and (not paren-free-arrow)
7339 (or (= tt js2-LB) (= tt js2-LC)))
7340 (js2-get-token)
7341 (when default-found
7342 (js2-report-error "msg.no.default.after.default.param"))
7343 (setq param (js2-parse-destruct-primary-expr))
7344 (js2-define-destruct-symbols param
7345 js2-LP
7346 'js2-function-param)
7347 (push param params))
7348 ;; variable name
7349 (t
7350 (when (and (>= js2-language-version 200)
7351 (not paren-free-arrow)
7352 (js2-match-token js2-TRIPLEDOT)
7353 (not rest-param-at))
7354 ;; to report errors if there are more parameters
7355 (setq rest-param-at (length params)))
7356 (js2-must-match-name "msg.no.parm")
7357 (js2-record-face 'js2-function-param)
7358 (setq param (js2-create-name-node))
7359 (js2-define-symbol js2-LP (js2-current-token-string) param)
7360 ;; default parameter value
7361 (when (or (and default-found
7362 (not rest-param-at)
7363 (js2-must-match js2-ASSIGN
7364 "msg.no.default.after.default.param"
7365 (js2-node-pos param)
7366 (js2-node-len param)))
7367 (and (>= js2-language-version 200)
7368 (js2-match-token js2-ASSIGN)))
7369 (assert (not paren-free-arrow))
7370 (let* ((pos (js2-node-pos param))
7371 (tt (js2-current-token-type))
7372 (op-pos (- (js2-current-token-beg) pos))
7373 (left param)
7374 (right (js2-parse-assign-expr))
7375 (len (- (js2-node-end right) pos)))
7376 (setq param (make-js2-assign-node
7377 :type tt :pos pos :len len :op-pos op-pos
7378 :left left :right right)
7379 default-found t)
7380 (js2-node-add-children param left right)))
7381 (push param params)))
7382 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7383 (js2-report-error "msg.param.after.rest" nil
7384 (js2-node-pos param) (js2-node-len param)))
7385 while
7386 (js2-match-token js2-COMMA))
7387 (when (and (not paren-free-arrow)
7388 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7389 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7390 (when rest-param-at
7391 (setf (js2-function-node-rest-p fn-node) t))
7392 (dolist (p params)
7393 (js2-node-add-children fn-node p)
7394 (push p (js2-function-node-params fn-node))))))
7395
7396 (defun js2-check-inconsistent-return-warning (fn-node name)
7397 "Possibly show inconsistent-return warning.
7398 Last token scanned is the close-curly for the function body."
7399 (when (and js2-mode-show-strict-warnings
7400 js2-strict-inconsistent-return-warning
7401 (not (js2-has-consistent-return-usage
7402 (js2-function-node-body fn-node))))
7403 ;; Have it extend from close-curly to bol or beginning of block.
7404 (let ((pos (save-excursion
7405 (goto-char (js2-current-token-end))
7406 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7407 (point-at-bol))))
7408 (end (js2-current-token-end)))
7409 (if (plusp (js2-name-node-length name))
7410 (js2-add-strict-warning "msg.no.return.value"
7411 (js2-name-node-name name) pos end)
7412 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7413
7414 (defun js2-parse-function-stmt ()
7415 (let ((pos (js2-current-token-beg))
7416 (star-p (js2-match-token js2-MUL)))
7417 (js2-must-match-name "msg.unnamed.function.stmt")
7418 (let ((name (js2-create-name-node t))
7419 pn member-expr)
7420 (cond
7421 ((js2-match-token js2-LP)
7422 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7423 (js2-allow-member-expr-as-function-name
7424 (setq member-expr (js2-parse-member-expr-tail nil name))
7425 (js2-parse-highlight-member-expr-fn-name member-expr)
7426 (js2-must-match js2-LP "msg.no.paren.parms")
7427 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7428 (js2-function-node-member-expr pn) member-expr)
7429 pn)
7430 (t
7431 (js2-report-error "msg.no.paren.parms")
7432 (make-js2-error-node))))))
7433
7434 (defun js2-parse-function-expr ()
7435 (let ((pos (js2-current-token-beg))
7436 (star-p (js2-match-token js2-MUL))
7437 name)
7438 (when (js2-match-token js2-NAME)
7439 (setq name (js2-create-name-node t)))
7440 (js2-must-match js2-LP "msg.no.paren.parms")
7441 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7442
7443 (defun js2-parse-function (function-type pos star-p &optional name)
7444 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7445 beginning of the first token (function keyword, unless it's an
7446 arrow function), NAME is js2-name-node."
7447 (let (fn-node lp)
7448 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7449 (setq lp (js2-current-token-beg)))
7450 (setf fn-node (make-js2-function-node :pos pos
7451 :name name
7452 :form function-type
7453 :lp (if lp (- lp pos))
7454 :generator-type (and star-p 'STAR)))
7455 (when name
7456 (js2-set-face (js2-node-pos name) (js2-node-end name)
7457 'font-lock-function-name-face 'record)
7458 (when (plusp (js2-name-node-length name))
7459 ;; Function statements define a symbol in the enclosing scope
7460 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7461 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7462 ;; 1. Nested functions are not affected by the dynamic scope flag
7463 ;; as dynamic scope is already a parent of their scope.
7464 ;; 2. Functions defined under the with statement also immune to
7465 ;; this setup, in which case dynamic scope is ignored in favor
7466 ;; of the with object.
7467 (setf (js2-function-node-ignore-dynamic fn-node) t))
7468 ;; dynamically bind all the per-function variables
7469 (let ((js2-current-script-or-fn fn-node)
7470 (js2-current-scope fn-node)
7471 (js2-nesting-of-with 0)
7472 (js2-end-flags 0)
7473 js2-label-set
7474 js2-loop-set
7475 js2-loop-and-switch-set)
7476 (js2-parse-function-params function-type fn-node pos)
7477 (when (eq function-type 'FUNCTION_ARROW)
7478 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7479 (if (and (>= js2-language-version 180)
7480 (/= (js2-peek-token) js2-LC))
7481 (js2-parse-function-closure-body fn-node)
7482 (js2-parse-function-body fn-node))
7483 (js2-check-inconsistent-return-warning fn-node name)
7484
7485 (when name
7486 (js2-node-add-children fn-node name)
7487 ;; Function expressions define a name only in the body of the
7488 ;; function, and only if not hidden by a parameter name
7489 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7490 (null (js2-scope-get-symbol js2-current-scope
7491 (js2-name-node-name name))))
7492 (js2-define-symbol js2-FUNCTION
7493 (js2-name-node-name name)
7494 fn-node))
7495 (when (eq function-type 'FUNCTION_STATEMENT)
7496 (js2-record-imenu-functions fn-node))))
7497
7498 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7499 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7500 ;; We wait until after parsing the function to set its parent scope,
7501 ;; since `js2-define-symbol' needs the defining-scope check to stop
7502 ;; at the function boundary when checking for redeclarations.
7503 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7504 fn-node))
7505
7506 (defun js2-parse-statements (&optional parent)
7507 "Parse a statement list. Last token consumed must be js2-LC.
7508
7509 PARENT can be a `js2-block-node', in which case the statements are
7510 appended to PARENT. Otherwise a new `js2-block-node' is created
7511 and returned.
7512
7513 This function does not match the closing js2-RC: the caller
7514 matches the RC so it can provide a suitable error message if not
7515 matched. This means it's up to the caller to set the length of
7516 the node to include the closing RC. The node start pos is set to
7517 the absolute buffer start position, and the caller should fix it
7518 up to be relative to the parent node. All children of this block
7519 node are given relative start positions and correct lengths."
7520 (let ((pn (or parent (make-js2-block-node)))
7521 tt)
7522 (setf (js2-node-pos pn) (js2-current-token-beg))
7523 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7524 (/= tt js2-RC))
7525 (js2-block-node-push pn (js2-parse-statement)))
7526 pn))
7527
7528 (defun js2-parse-statement ()
7529 (let (pn beg end)
7530 ;; coarse-grained user-interrupt check - needs work
7531 (and js2-parse-interruptable-p
7532 (zerop (% (incf js2-parse-stmt-count)
7533 js2-statements-per-pause))
7534 (input-pending-p)
7535 (throw 'interrupted t))
7536 (setq pn (js2-statement-helper))
7537 ;; no-side-effects warning check
7538 (unless (js2-node-has-side-effects pn)
7539 (setq end (js2-node-end pn))
7540 (save-excursion
7541 (goto-char end)
7542 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7543 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7544 pn))
7545
7546 ;; These correspond to the switch cases in Parser.statementHelper
7547 (defconst js2-parsers
7548 (let ((parsers (make-vector js2-num-tokens
7549 #'js2-parse-expr-stmt)))
7550 (aset parsers js2-BREAK #'js2-parse-break)
7551 (aset parsers js2-CONST #'js2-parse-const-var)
7552 (aset parsers js2-CONTINUE #'js2-parse-continue)
7553 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7554 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7555 (aset parsers js2-DO #'js2-parse-do)
7556 (aset parsers js2-FOR #'js2-parse-for)
7557 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
7558 (aset parsers js2-IF #'js2-parse-if)
7559 (aset parsers js2-LC #'js2-parse-block)
7560 (aset parsers js2-LET #'js2-parse-let-stmt)
7561 (aset parsers js2-NAME #'js2-parse-name-or-label)
7562 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7563 (aset parsers js2-SEMI #'js2-parse-semi)
7564 (aset parsers js2-SWITCH #'js2-parse-switch)
7565 (aset parsers js2-THROW #'js2-parse-throw)
7566 (aset parsers js2-TRY #'js2-parse-try)
7567 (aset parsers js2-VAR #'js2-parse-const-var)
7568 (aset parsers js2-WHILE #'js2-parse-while)
7569 (aset parsers js2-WITH #'js2-parse-with)
7570 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7571 parsers)
7572 "A vector mapping token types to parser functions.")
7573
7574 (defun js2-parse-warn-missing-semi (beg end)
7575 (and js2-mode-show-strict-warnings
7576 js2-strict-missing-semi-warning
7577 (js2-add-strict-warning
7578 "msg.missing.semi" nil
7579 ;; back up to beginning of statement or line
7580 (max beg (save-excursion
7581 (goto-char end)
7582 (point-at-bol)))
7583 end)))
7584
7585 (defconst js2-no-semi-insertion
7586 (list js2-IF
7587 js2-SWITCH
7588 js2-WHILE
7589 js2-DO
7590 js2-FOR
7591 js2-TRY
7592 js2-WITH
7593 js2-LC
7594 js2-ERROR
7595 js2-SEMI
7596 js2-FUNCTION)
7597 "List of tokens that don't do automatic semicolon insertion.")
7598
7599 (defconst js2-autoinsert-semi-and-warn
7600 (list js2-ERROR js2-EOF js2-RC))
7601
7602 (defun js2-statement-helper ()
7603 (let* ((tt (js2-get-token))
7604 (first-tt tt)
7605 (parser (if (= tt js2-ERROR)
7606 #'js2-parse-semi
7607 (aref js2-parsers tt)))
7608 pn)
7609 ;; If the statement is set, then it's been told its label by now.
7610 (and js2-labeled-stmt
7611 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7612 (setq js2-labeled-stmt nil))
7613 (setq pn (funcall parser))
7614 ;; Don't do auto semi insertion for certain statement types.
7615 (unless (or (memq first-tt js2-no-semi-insertion)
7616 (js2-labeled-stmt-node-p pn))
7617 (js2-auto-insert-semicolon pn))
7618 pn))
7619
7620 (defun js2-auto-insert-semicolon (pn)
7621 (let* ((tt (js2-get-token))
7622 (pos (js2-node-pos pn)))
7623 (cond
7624 ((= tt js2-SEMI)
7625 ;; extend the node bounds to include the semicolon.
7626 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
7627 ((memq tt js2-autoinsert-semi-and-warn)
7628 (js2-unget-token) ; Not ';', do not consume.
7629 ;; Autoinsert ;
7630 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7631 (t
7632 (if (not (js2-token-follows-eol-p (js2-current-token)))
7633 ;; Report error if no EOL or autoinsert ';' otherwise
7634 (js2-report-error "msg.no.semi.stmt")
7635 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7636 (js2-unget-token) ; Not ';', do not consume.
7637 ))))
7638
7639 (defun js2-parse-condition ()
7640 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7641 The parens are discarded and the expression node is returned.
7642 The `pos' field of the return value is set to an absolute position
7643 that must be fixed up by the caller.
7644 Return value is a list (EXPR LP RP), with absolute paren positions."
7645 (let (pn lp rp)
7646 (if (js2-must-match js2-LP "msg.no.paren.cond")
7647 (setq lp (js2-current-token-beg)))
7648 (setq pn (js2-parse-expr))
7649 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7650 (setq rp (js2-current-token-beg)))
7651 ;; Report strict warning on code like "if (a = 7) ..."
7652 (if (and js2-strict-cond-assign-warning
7653 (js2-assign-node-p pn))
7654 (js2-add-strict-warning "msg.equal.as.assign" nil
7655 (js2-node-pos pn)
7656 (+ (js2-node-pos pn)
7657 (js2-node-len pn))))
7658 (list pn lp rp)))
7659
7660 (defun js2-parse-if ()
7661 "Parser for if-statement. Last matched token must be js2-IF."
7662 (let ((pos (js2-current-token-beg))
7663 cond if-true if-false else-pos end pn)
7664 (setq cond (js2-parse-condition)
7665 if-true (js2-parse-statement)
7666 if-false (if (js2-match-token js2-ELSE)
7667 (progn
7668 (setq else-pos (- (js2-current-token-beg) pos))
7669 (js2-parse-statement)))
7670 end (js2-node-end (or if-false if-true))
7671 pn (make-js2-if-node :pos pos
7672 :len (- end pos)
7673 :condition (car cond)
7674 :then-part if-true
7675 :else-part if-false
7676 :else-pos else-pos
7677 :lp (js2-relpos (second cond) pos)
7678 :rp (js2-relpos (third cond) pos)))
7679 (js2-node-add-children pn (car cond) if-true if-false)
7680 pn))
7681
7682 (defun js2-parse-switch ()
7683 "Parser for switch-statement. Last matched token must be js2-SWITCH."
7684 (let ((pos (js2-current-token-beg))
7685 tt pn discriminant has-default case-expr case-node
7686 case-pos cases stmt lp)
7687 (if (js2-must-match js2-LP "msg.no.paren.switch")
7688 (setq lp (js2-current-token-beg)))
7689 (setq discriminant (js2-parse-expr)
7690 pn (make-js2-switch-node :discriminant discriminant
7691 :pos pos
7692 :lp (js2-relpos lp pos)))
7693 (js2-node-add-children pn discriminant)
7694 (js2-enter-switch pn)
7695 (unwind-protect
7696 (progn
7697 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7698 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
7699 (js2-must-match js2-LC "msg.no.brace.switch")
7700 (catch 'break
7701 (while t
7702 (setq tt (js2-next-token)
7703 case-pos (js2-current-token-beg))
7704 (cond
7705 ((= tt js2-RC)
7706 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
7707 (throw 'break nil)) ; done
7708 ((= tt js2-CASE)
7709 (setq case-expr (js2-parse-expr))
7710 (js2-must-match js2-COLON "msg.no.colon.case"))
7711 ((= tt js2-DEFAULT)
7712 (if has-default
7713 (js2-report-error "msg.double.switch.default"))
7714 (setq has-default t
7715 case-expr nil)
7716 (js2-must-match js2-COLON "msg.no.colon.case"))
7717 (t
7718 (js2-report-error "msg.bad.switch")
7719 (throw 'break nil)))
7720 (setq case-node (make-js2-case-node :pos case-pos
7721 :len (- (js2-current-token-end) case-pos)
7722 :expr case-expr))
7723 (js2-node-add-children case-node case-expr)
7724 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7725 (/= tt js2-CASE)
7726 (/= tt js2-DEFAULT)
7727 (/= tt js2-EOF))
7728 (setf stmt (js2-parse-statement)
7729 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7730 (js2-block-node-push case-node stmt))
7731 (push case-node cases)))
7732 ;; add cases last, as pushing reverses the order to be correct
7733 (dolist (kid cases)
7734 (js2-node-add-children pn kid)
7735 (push kid (js2-switch-node-cases pn)))
7736 pn) ; return value
7737 (js2-exit-switch))))
7738
7739 (defun js2-parse-while ()
7740 "Parser for while-statement. Last matched token must be js2-WHILE."
7741 (let ((pos (js2-current-token-beg))
7742 (pn (make-js2-while-node))
7743 cond body)
7744 (js2-enter-loop pn)
7745 (unwind-protect
7746 (progn
7747 (setf cond (js2-parse-condition)
7748 (js2-while-node-condition pn) (car cond)
7749 body (js2-parse-statement)
7750 (js2-while-node-body pn) body
7751 (js2-node-len pn) (- (js2-node-end body) pos)
7752 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7753 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7754 (js2-node-add-children pn body (car cond)))
7755 (js2-exit-loop))
7756 pn))
7757
7758 (defun js2-parse-do ()
7759 "Parser for do-statement. Last matched token must be js2-DO."
7760 (let ((pos (js2-current-token-beg))
7761 (pn (make-js2-do-node))
7762 cond body end)
7763 (js2-enter-loop pn)
7764 (unwind-protect
7765 (progn
7766 (setq body (js2-parse-statement))
7767 (js2-must-match js2-WHILE "msg.no.while.do")
7768 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
7769 cond (js2-parse-condition)
7770 (js2-do-node-condition pn) (car cond)
7771 (js2-do-node-body pn) body
7772 end js2-ts-cursor
7773 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7774 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7775 (js2-node-add-children pn (car cond) body))
7776 (js2-exit-loop))
7777 ;; Always auto-insert semicolon to follow SpiderMonkey:
7778 ;; It is required by ECMAScript but is ignored by the rest of
7779 ;; world; see bug 238945
7780 (if (js2-match-token js2-SEMI)
7781 (setq end js2-ts-cursor))
7782 (setf (js2-node-len pn) (- end pos))
7783 pn))
7784
7785 (defun js2-parse-for ()
7786 "Parser for for-statement. Last matched token must be js2-FOR.
7787 Parses for, for-in, and for each-in statements."
7788 (let ((for-pos (js2-current-token-beg))
7789 pn is-for-each is-for-in-or-of is-for-of
7790 in-pos each-pos tmp-pos
7791 init ; Node init is also foo in 'foo in object'
7792 cond ; Node cond is also object in 'foo in object'
7793 incr ; 3rd section of for-loop initializer
7794 body tt lp rp)
7795 ;; See if this is a for each () instead of just a for ()
7796 (when (js2-match-token js2-NAME)
7797 (if (string= "each" (js2-current-token-string))
7798 (progn
7799 (setq is-for-each t
7800 each-pos (- (js2-current-token-beg) for-pos)) ; relative
7801 (js2-record-face 'font-lock-keyword-face))
7802 (js2-report-error "msg.no.paren.for")))
7803 (if (js2-must-match js2-LP "msg.no.paren.for")
7804 (setq lp (- (js2-current-token-beg) for-pos)))
7805 (setq tt (js2-get-token))
7806 ;; 'for' makes local scope
7807 (js2-push-scope (make-js2-scope))
7808 (unwind-protect
7809 ;; parse init clause
7810 (let ((js2-in-for-init t)) ; set as dynamic variable
7811 (cond
7812 ((= tt js2-SEMI)
7813 (js2-unget-token)
7814 (setq init (make-js2-empty-expr-node)))
7815 ((or (= tt js2-VAR) (= tt js2-LET))
7816 (setq init (js2-parse-variables tt (js2-current-token-beg))))
7817 (t
7818 (js2-unget-token)
7819 (setq init (js2-parse-expr)))))
7820 (if (or (js2-match-token js2-IN)
7821 (and (>= js2-language-version 200)
7822 (js2-match-contextual-kwd "of")
7823 (setq is-for-of t)))
7824 (setq is-for-in-or-of t
7825 in-pos (- (js2-current-token-beg) for-pos)
7826 ;; scope of iteration target object is not the scope we've created above.
7827 ;; stash current scope temporary.
7828 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7829 (js2-parse-expr))) ; object over which we're iterating
7830 ;; else ordinary for loop - parse cond and incr
7831 (js2-must-match js2-SEMI "msg.no.semi.for")
7832 (setq cond (if (= (js2-peek-token) js2-SEMI)
7833 (make-js2-empty-expr-node) ; no loop condition
7834 (js2-parse-expr)))
7835 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7836 (setq tmp-pos (js2-current-token-end)
7837 incr (if (= (js2-peek-token) js2-RP)
7838 (make-js2-empty-expr-node :pos tmp-pos)
7839 (js2-parse-expr))))
7840 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7841 (setq rp (- (js2-current-token-beg) for-pos)))
7842 (if (not is-for-in-or-of)
7843 (setq pn (make-js2-for-node :init init
7844 :condition cond
7845 :update incr
7846 :lp lp
7847 :rp rp))
7848 ;; cond could be null if 'in obj' got eaten by the init node.
7849 (if (js2-infix-node-p init)
7850 ;; it was (foo in bar) instead of (var foo in bar)
7851 (setq cond (js2-infix-node-right init)
7852 init (js2-infix-node-left init))
7853 (if (and (js2-var-decl-node-p init)
7854 (> (length (js2-var-decl-node-kids init)) 1))
7855 (js2-report-error "msg.mult.index")))
7856 (setq pn (make-js2-for-in-node :iterator init
7857 :object cond
7858 :in-pos in-pos
7859 :foreach-p is-for-each
7860 :each-pos each-pos
7861 :forof-p is-for-of
7862 :lp lp
7863 :rp rp)))
7864 (unwind-protect
7865 (progn
7866 (js2-enter-loop pn)
7867 ;; We have to parse the body -after- creating the loop node,
7868 ;; so that the loop node appears in the js2-loop-set, allowing
7869 ;; break/continue statements to find the enclosing loop.
7870 (setf body (js2-parse-statement)
7871 (js2-loop-node-body pn) body
7872 (js2-node-pos pn) for-pos
7873 (js2-node-len pn) (- (js2-node-end body) for-pos))
7874 (js2-node-add-children pn init cond incr body))
7875 ;; finally
7876 (js2-exit-loop))
7877 (js2-pop-scope))
7878 pn))
7879
7880 (defun js2-parse-try ()
7881 "Parser for try-statement. Last matched token must be js2-TRY."
7882 (let ((try-pos (js2-current-token-beg))
7883 try-end
7884 try-block
7885 catch-blocks
7886 finally-block
7887 saw-default-catch
7888 peek
7889 param
7890 catch-cond
7891 catch-node
7892 guard-kwd
7893 catch-pos
7894 finally-pos
7895 pn
7896 block
7897 lp
7898 rp)
7899 (if (/= (js2-peek-token) js2-LC)
7900 (js2-report-error "msg.no.brace.try"))
7901 (setq try-block (js2-parse-statement)
7902 try-end (js2-node-end try-block)
7903 peek (js2-peek-token))
7904 (cond
7905 ((= peek js2-CATCH)
7906 (while (js2-match-token js2-CATCH)
7907 (setq catch-pos (js2-current-token-beg)
7908 guard-kwd nil
7909 catch-cond nil
7910 lp nil
7911 rp nil)
7912 (if saw-default-catch
7913 (js2-report-error "msg.catch.unreachable"))
7914 (if (js2-must-match js2-LP "msg.no.paren.catch")
7915 (setq lp (- (js2-current-token-beg) catch-pos)))
7916 (js2-push-scope (make-js2-scope))
7917 (let ((tt (js2-peek-token)))
7918 (cond
7919 ;; destructuring pattern
7920 ;; catch ({ message, file }) { ... }
7921 ((or (= tt js2-LB) (= tt js2-LC))
7922 (js2-get-token)
7923 (setq param (js2-parse-destruct-primary-expr))
7924 (js2-define-destruct-symbols param js2-LET nil))
7925 ;; simple name
7926 (t
7927 (js2-must-match-name "msg.bad.catchcond")
7928 (setq param (js2-create-name-node))
7929 (js2-define-symbol js2-LET (js2-current-token-string) param))))
7930 ;; pattern guard
7931 (if (js2-match-token js2-IF)
7932 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
7933 catch-cond (js2-parse-expr))
7934 (setq saw-default-catch t))
7935 (if (js2-must-match js2-RP "msg.bad.catchcond")
7936 (setq rp (- (js2-current-token-beg) catch-pos)))
7937 (js2-must-match js2-LC "msg.no.brace.catchblock")
7938 (setq block (js2-parse-statements)
7939 try-end (js2-node-end block)
7940 catch-node (make-js2-catch-node :pos catch-pos
7941 :param param
7942 :guard-expr catch-cond
7943 :guard-kwd guard-kwd
7944 :block block
7945 :lp lp
7946 :rp rp))
7947 (js2-pop-scope)
7948 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7949 (setq try-end (js2-current-token-beg)))
7950 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7951 (js2-node-len catch-node) (- try-end catch-pos))
7952 (js2-node-add-children catch-node param catch-cond block)
7953 (push catch-node catch-blocks)))
7954 ((/= peek js2-FINALLY)
7955 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7956 (js2-node-pos try-block)
7957 (- (setq try-end (js2-node-end try-block))
7958 (js2-node-pos try-block)))))
7959 (when (js2-match-token js2-FINALLY)
7960 (setq finally-pos (js2-current-token-beg)
7961 block (js2-parse-statement)
7962 try-end (js2-node-end block)
7963 finally-block (make-js2-finally-node :pos finally-pos
7964 :len (- try-end finally-pos)
7965 :body block))
7966 (js2-node-add-children finally-block block))
7967 (setq pn (make-js2-try-node :pos try-pos
7968 :len (- try-end try-pos)
7969 :try-block try-block
7970 :finally-block finally-block))
7971 (js2-node-add-children pn try-block finally-block)
7972 ;; push them onto the try-node, which reverses and corrects their order
7973 (dolist (cb catch-blocks)
7974 (js2-node-add-children pn cb)
7975 (push cb (js2-try-node-catch-clauses pn)))
7976 pn))
7977
7978 (defun js2-parse-throw ()
7979 "Parser for throw-statement. Last matched token must be js2-THROW."
7980 (let ((pos (js2-current-token-beg))
7981 expr pn)
7982 (if (= (js2-peek-token-or-eol) js2-EOL)
7983 ;; ECMAScript does not allow new lines before throw expression,
7984 ;; see bug 256617
7985 (js2-report-error "msg.bad.throw.eol"))
7986 (setq expr (js2-parse-expr)
7987 pn (make-js2-throw-node :pos pos
7988 :len (- (js2-node-end expr) pos)
7989 :expr expr))
7990 (js2-node-add-children pn expr)
7991 pn))
7992
7993 (defun js2-match-jump-label-name (label-name)
7994 "If break/continue specified a label, return that label's labeled stmt.
7995 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
7996 does not match an existing label, reports an error and returns nil."
7997 (let ((bundle (cdr (assoc label-name js2-label-set))))
7998 (if (null bundle)
7999 (js2-report-error "msg.undef.label"))
8000 bundle))
8001
8002 (defun js2-parse-break ()
8003 "Parser for break-statement. Last matched token must be js2-BREAK."
8004 (let ((pos (js2-current-token-beg))
8005 (end (js2-current-token-end))
8006 break-target ; statement to break from
8007 break-label ; in "break foo", name-node representing the foo
8008 labels ; matching labeled statement to break to
8009 pn)
8010 (when (eq (js2-peek-token-or-eol) js2-NAME)
8011 (js2-get-token)
8012 (setq break-label (js2-create-name-node)
8013 end (js2-node-end break-label)
8014 ;; matchJumpLabelName only matches if there is one
8015 labels (js2-match-jump-label-name (js2-current-token-string))
8016 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8017 (unless (or break-target break-label)
8018 ;; no break target specified - try for innermost enclosing loop/switch
8019 (if (null js2-loop-and-switch-set)
8020 (unless break-label
8021 (js2-report-error "msg.bad.break" nil pos (length "break")))
8022 (setq break-target (car js2-loop-and-switch-set))))
8023 (setq pn (make-js2-break-node :pos pos
8024 :len (- end pos)
8025 :label break-label
8026 :target break-target))
8027 (js2-node-add-children pn break-label) ; but not break-target
8028 pn))
8029
8030 (defun js2-parse-continue ()
8031 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8032 (let ((pos (js2-current-token-beg))
8033 (end (js2-current-token-end))
8034 label ; optional user-specified label, a `js2-name-node'
8035 labels ; current matching labeled stmt, if any
8036 target ; the `js2-loop-node' target of this continue stmt
8037 pn)
8038 (when (= (js2-peek-token-or-eol) js2-NAME)
8039 (js2-get-token)
8040 (setq label (js2-create-name-node)
8041 end (js2-node-end label)
8042 ;; matchJumpLabelName only matches if there is one
8043 labels (js2-match-jump-label-name (js2-current-token-string))))
8044 (cond
8045 ((null labels) ; no current label to go to
8046 (if (null js2-loop-set) ; no loop to continue to
8047 (js2-report-error "msg.continue.outside" nil pos
8048 (length "continue"))
8049 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8050 (t
8051 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8052 (setq target (js2-labeled-stmt-node-stmt labels))
8053 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8054 (setq pn (make-js2-continue-node :pos pos
8055 :len (- end pos)
8056 :label label
8057 :target target))
8058 (js2-node-add-children pn label) ; but not target - it's not our child
8059 pn))
8060
8061 (defun js2-parse-with ()
8062 "Parser for with-statement. Last matched token must be js2-WITH."
8063 (let ((pos (js2-current-token-beg))
8064 obj body pn lp rp)
8065 (if (js2-must-match js2-LP "msg.no.paren.with")
8066 (setq lp (js2-current-token-beg)))
8067 (setq obj (js2-parse-expr))
8068 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8069 (setq rp (js2-current-token-beg)))
8070 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8071 (setq body (js2-parse-statement)))
8072 (setq pn (make-js2-with-node :pos pos
8073 :len (- (js2-node-end body) pos)
8074 :object obj
8075 :body body
8076 :lp (js2-relpos lp pos)
8077 :rp (js2-relpos rp pos)))
8078 (js2-node-add-children pn obj body)
8079 pn))
8080
8081 (defun js2-parse-const-var ()
8082 "Parser for var- or const-statement.
8083 Last matched token must be js2-CONST or js2-VAR."
8084 (let ((tt (js2-current-token-type))
8085 (pos (js2-current-token-beg))
8086 expr pn)
8087 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8088 pn (make-js2-expr-stmt-node :pos pos
8089 :len (- (js2-node-end expr) pos)
8090 :expr expr))
8091 (js2-node-add-children pn expr)
8092 pn))
8093
8094 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8095 (let ((pn (make-js2-expr-stmt-node :pos pos
8096 :len (js2-node-len expr)
8097 :type (if (js2-inside-function)
8098 js2-EXPR_VOID
8099 js2-EXPR_RESULT)
8100 :expr expr)))
8101 (if add-child
8102 (js2-node-add-children pn expr))
8103 pn))
8104
8105 (defun js2-parse-let-stmt ()
8106 "Parser for let-statement. Last matched token must be js2-LET."
8107 (let ((pos (js2-current-token-beg))
8108 expr pn)
8109 (if (= (js2-peek-token) js2-LP)
8110 ;; let expression in statement context
8111 (setq expr (js2-parse-let pos 'statement)
8112 pn (js2-wrap-with-expr-stmt pos expr t))
8113 ;; else we're looking at a statement like let x=6, y=7;
8114 (setf expr (js2-parse-variables js2-LET pos)
8115 pn (js2-wrap-with-expr-stmt pos expr t)
8116 (js2-node-type pn) js2-EXPR_RESULT))
8117 pn))
8118
8119 (defun js2-parse-ret-yield ()
8120 (js2-parse-return-or-yield (js2-current-token-type) nil))
8121
8122 (defconst js2-parse-return-stmt-enders
8123 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8124
8125 (defsubst js2-now-all-set (before after mask)
8126 "Return whether or not the bits in the mask have changed to all set.
8127 BEFORE is bits before change, AFTER is bits after change, and MASK is
8128 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8129 but not BEFORE."
8130 (and (/= (logand before mask) mask)
8131 (= (logand after mask) mask)))
8132
8133 (defun js2-parse-return-or-yield (tt expr-context)
8134 (let* ((pos (js2-current-token-beg))
8135 (end (js2-current-token-end))
8136 (before js2-end-flags)
8137 (inside-function (js2-inside-function))
8138 (gen-type (and inside-function (js2-function-node-generator-type
8139 js2-current-script-or-fn)))
8140 e ret name yield-star-p)
8141 (unless inside-function
8142 (js2-report-error (if (eq tt js2-RETURN)
8143 "msg.bad.return"
8144 "msg.bad.yield")))
8145 (when (and inside-function
8146 (eq gen-type 'STAR)
8147 (js2-match-token js2-MUL))
8148 (setq yield-star-p t))
8149 ;; This is ugly, but we don't want to require a semicolon.
8150 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8151 (setq e (js2-parse-expr)
8152 end (js2-node-end e)))
8153 (cond
8154 ((eq tt js2-RETURN)
8155 (js2-set-flag js2-end-flags (if (null e)
8156 js2-end-returns
8157 js2-end-returns-value))
8158 (setq ret (make-js2-return-node :pos pos
8159 :len (- end pos)
8160 :retval e))
8161 (js2-node-add-children ret e)
8162 ;; See if we need a strict mode warning.
8163 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8164 ;; more thorough and accurate than this before/after flag check.
8165 ;; E.g. if there's a finally-block that always returns, we shouldn't
8166 ;; show a warning generated by inconsistent returns in the catch blocks.
8167 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8168 ;; so we know which returns/yields to highlight, and we should get rid of
8169 ;; all the checking in `js2-parse-return-or-yield'.
8170 (if (and js2-strict-inconsistent-return-warning
8171 (js2-now-all-set before js2-end-flags
8172 (logior js2-end-returns js2-end-returns-value)))
8173 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8174 ((eq gen-type 'COMPREHENSION)
8175 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8176 ;; like SpiderMonkey does.
8177 (js2-report-error "msg.syntax" nil pos 5))
8178 (t
8179 (setq ret (make-js2-yield-node :pos pos
8180 :len (- end pos)
8181 :value e
8182 :star-p yield-star-p))
8183 (js2-node-add-children ret e)
8184 (unless expr-context
8185 (setq e ret
8186 ret (js2-wrap-with-expr-stmt pos e t))
8187 (js2-set-requires-activation)
8188 (js2-set-is-generator))))
8189 ;; see if we are mixing yields and value returns.
8190 (when (and inside-function
8191 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8192 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8193 'LEGACY))
8194 (setq name (js2-function-name js2-current-script-or-fn))
8195 (if (zerop (length name))
8196 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8197 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8198 ret))
8199
8200 (defun js2-parse-debugger ()
8201 (make-js2-keyword-node :type js2-DEBUGGER))
8202
8203 (defun js2-parse-block ()
8204 "Parser for a curly-delimited statement block.
8205 Last token matched must be `js2-LC'."
8206 (let ((pos (js2-current-token-beg))
8207 (pn (make-js2-scope)))
8208 (js2-push-scope pn)
8209 (unwind-protect
8210 (progn
8211 (js2-parse-statements pn)
8212 (js2-must-match js2-RC "msg.no.brace.block")
8213 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8214 (js2-pop-scope))
8215 pn))
8216
8217 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8218 (defun js2-parse-semi ()
8219 "Parse a statement or handle an error.
8220 Current token type is `js2-SEMI' or `js2-ERROR'."
8221 (let ((tt (js2-current-token-type)) pos len)
8222 (if (eq tt js2-SEMI)
8223 (make-js2-empty-expr-node :len 1)
8224 (setq pos (js2-current-token-beg)
8225 len (- (js2-current-token-end) pos))
8226 (js2-report-error "msg.syntax" nil pos len)
8227 (make-js2-error-node :pos pos :len len))))
8228
8229 (defun js2-parse-default-xml-namespace ()
8230 "Parse a `default xml namespace = <expr>' e4x statement."
8231 (let ((pos (js2-current-token-beg))
8232 end len expr unary)
8233 (js2-must-have-xml)
8234 (js2-set-requires-activation)
8235 (setq len (- js2-ts-cursor pos))
8236 (unless (and (js2-match-token js2-NAME)
8237 (string= (js2-current-token-string) "xml"))
8238 (js2-report-error "msg.bad.namespace" nil pos len))
8239 (unless (and (js2-match-token js2-NAME)
8240 (string= (js2-current-token-string) "namespace"))
8241 (js2-report-error "msg.bad.namespace" nil pos len))
8242 (unless (js2-match-token js2-ASSIGN)
8243 (js2-report-error "msg.bad.namespace" nil pos len))
8244 (setq expr (js2-parse-expr)
8245 end (js2-node-end expr)
8246 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8247 :pos pos
8248 :len (- end pos)
8249 :operand expr))
8250 (js2-node-add-children unary expr)
8251 (make-js2-expr-stmt-node :pos pos
8252 :len (- end pos)
8253 :expr unary)))
8254
8255 (defun js2-record-label (label bundle)
8256 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8257 (js2-get-token)
8258 (let ((name (js2-label-node-name label))
8259 labeled-stmt
8260 dup)
8261 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8262 ;; flag both labels if possible when used in editing mode
8263 (if (and js2-parse-ide-mode
8264 (setq dup (js2-get-label-by-name labeled-stmt name)))
8265 (js2-report-error "msg.dup.label" nil
8266 (js2-node-abs-pos dup) (js2-node-len dup)))
8267 (js2-report-error "msg.dup.label" nil
8268 (js2-node-pos label) (js2-node-len label)))
8269 (js2-labeled-stmt-node-add-label bundle label)
8270 (js2-node-add-children bundle label)
8271 ;; Add one reference to the bundle per label in `js2-label-set'
8272 (push (cons name bundle) js2-label-set)))
8273
8274 (defun js2-parse-name-or-label ()
8275 "Parser for identifier or label. Last token matched must be js2-NAME.
8276 Called when we found a name in a statement context. If it's a label, we gather
8277 up any following labels and the next non-label statement into a
8278 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8279 expression and return it wrapped in a `js2-expr-stmt-node'."
8280 (let ((pos (js2-current-token-beg))
8281 expr stmt bundle
8282 (continue t))
8283 ;; set check for label and call down to `js2-parse-primary-expr'
8284 (setq expr (js2-maybe-parse-label))
8285 (if (null expr)
8286 ;; Parse the non-label expression and wrap with expression stmt.
8287 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
8288 ;; else parsed a label
8289 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8290 (js2-record-label expr bundle)
8291 ;; look for more labels
8292 (while (and continue (= (js2-get-token) js2-NAME))
8293 (if (setq expr (js2-maybe-parse-label))
8294 (js2-record-label expr bundle)
8295 (setq expr (js2-parse-expr)
8296 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8297 continue nil)
8298 (js2-auto-insert-semicolon stmt)))
8299 ;; no more labels; now parse the labeled statement
8300 (unwind-protect
8301 (unless stmt
8302 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8303 (js2-unget-token)
8304 (setq stmt (js2-statement-helper))))
8305 ;; remove the labels for this statement from the global set
8306 (dolist (label (js2-labeled-stmt-node-labels bundle))
8307 (setq js2-label-set (remove label js2-label-set))))
8308 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8309 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8310 (js2-node-add-children bundle stmt)
8311 bundle)))
8312
8313 (defun js2-maybe-parse-label ()
8314 (assert (= (js2-current-token-type) js2-NAME))
8315 (let (label-pos
8316 (next-tt (js2-get-token))
8317 (label-end (js2-current-token-end)))
8318 ;; Do not consume colon, it is used as unwind indicator
8319 ;; to return to statementHelper.
8320 (js2-unget-token)
8321 (if (= next-tt js2-COLON)
8322 (prog2
8323 (setq label-pos (js2-current-token-beg))
8324 (make-js2-label-node :pos label-pos
8325 :len (- label-end label-pos)
8326 :name (js2-current-token-string))
8327 (js2-set-face label-pos
8328 label-end
8329 'font-lock-variable-name-face 'record))
8330 ;; Backtrack from the name token, too.
8331 (js2-unget-token)
8332 nil)))
8333
8334 (defun js2-parse-expr-stmt ()
8335 "Default parser in statement context, if no recognized statement found."
8336 (js2-wrap-with-expr-stmt (js2-current-token-beg)
8337 (progn
8338 (js2-unget-token)
8339 (js2-parse-expr)) t))
8340
8341 (defun js2-parse-variables (decl-type pos)
8342 "Parse a comma-separated list of variable declarations.
8343 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8344
8345 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8346 For 'var' or 'const', the keyword should be the token last scanned.
8347
8348 POS is the position where the node should start. It's sometimes the
8349 var/const/let keyword, and other times the beginning of the first token
8350 in the first variable declaration.
8351
8352 Returns the parsed `js2-var-decl-node' expression node."
8353 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8354 :pos pos))
8355 destructuring kid-pos tt init name end nbeg nend vi
8356 (continue t))
8357 ;; Example:
8358 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8359 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8360 ;; var {a, b} = baz;
8361 (while continue
8362 (setq destructuring nil
8363 name nil
8364 tt (js2-get-token)
8365 kid-pos (js2-current-token-beg)
8366 end (js2-current-token-end)
8367 init nil)
8368 (if (or (= tt js2-LB) (= tt js2-LC))
8369 ;; Destructuring assignment, e.g., var [a, b] = ...
8370 (setq destructuring (js2-parse-destruct-primary-expr)
8371 end (js2-node-end destructuring))
8372 ;; Simple variable name
8373 (js2-unget-token)
8374 (when (js2-must-match-name "msg.bad.var")
8375 (setq name (js2-create-name-node)
8376 nbeg (js2-current-token-beg)
8377 nend (js2-current-token-end)
8378 end nend)
8379 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
8380 (when (js2-match-token js2-ASSIGN)
8381 (setq init (js2-parse-assign-expr)
8382 end (js2-node-end init))
8383 (js2-record-imenu-functions init name))
8384 (when name
8385 (js2-set-face nbeg nend (if (js2-function-node-p init)
8386 'font-lock-function-name-face
8387 'font-lock-variable-name-face)
8388 'record))
8389 (setq vi (make-js2-var-init-node :pos kid-pos
8390 :len (- end kid-pos)
8391 :type decl-type))
8392 (if destructuring
8393 (progn
8394 (if (and (null init) (not js2-in-for-init))
8395 (js2-report-error "msg.destruct.assign.no.init"))
8396 (js2-define-destruct-symbols destructuring
8397 decl-type
8398 'font-lock-variable-name-face)
8399 (setf (js2-var-init-node-target vi) destructuring))
8400 (setf (js2-var-init-node-target vi) name))
8401 (setf (js2-var-init-node-initializer vi) init)
8402 (js2-node-add-children vi name destructuring init)
8403 (js2-block-node-push result vi)
8404 (unless (js2-match-token js2-COMMA)
8405 (setq continue nil)))
8406 (setf (js2-node-len result) (- end pos))
8407 result))
8408
8409 (defun js2-parse-let (pos &optional stmt-p)
8410 "Parse a let expression or statement.
8411 A let-expression is of the form `let (vars) expr'.
8412 A let-statment is of the form `let (vars) {statements}'.
8413 The third form of let is a variable declaration list, handled
8414 by `js2-parse-variables'."
8415 (let ((pn (make-js2-let-node :pos pos))
8416 beg vars body)
8417 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8418 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
8419 (js2-push-scope pn)
8420 (unwind-protect
8421 (progn
8422 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
8423 (if (js2-must-match js2-RP "msg.no.paren.let")
8424 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
8425 (if (and stmt-p (eq (js2-get-token) js2-LC))
8426 ;; let statement
8427 (progn
8428 (setf beg (js2-current-token-beg) ; position stmt at LC
8429 body (js2-parse-statements))
8430 (js2-must-match js2-RC "msg.no.curly.let")
8431 (setf (js2-node-len body) (- (js2-current-token-end) beg)
8432 (js2-node-len pn) (- (js2-current-token-end) pos)
8433 (js2-let-node-body pn) body
8434 (js2-node-type pn) js2-LET))
8435 ;; let expression
8436 (js2-unget-token)
8437 (setf body (js2-parse-expr)
8438 (js2-node-len pn) (- (js2-node-end body) pos)
8439 (js2-let-node-body pn) body))
8440 (js2-node-add-children pn vars body))
8441 (js2-pop-scope))
8442 pn))
8443
8444 (defun js2-define-new-symbol (decl-type name node &optional scope)
8445 (js2-scope-put-symbol (or scope js2-current-scope)
8446 name
8447 (make-js2-symbol decl-type name node)))
8448
8449 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8450 "Define a symbol in the current scope.
8451 If NODE is non-nil, it is the AST node associated with the symbol."
8452 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8453 (symbol (if defining-scope
8454 (js2-scope-get-symbol defining-scope name)))
8455 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8456 (cond
8457 ((and symbol ; already defined
8458 (or (= sdt js2-CONST) ; old version is const
8459 (= decl-type js2-CONST) ; new version is const
8460 ;; two let-bound vars in this block have same name
8461 (and (= sdt js2-LET)
8462 (eq defining-scope js2-current-scope))))
8463 (js2-report-error
8464 (cond
8465 ((= sdt js2-CONST) "msg.const.redecl")
8466 ((= sdt js2-LET) "msg.let.redecl")
8467 ((= sdt js2-VAR) "msg.var.redecl")
8468 ((= sdt js2-FUNCTION) "msg.function.redecl")
8469 (t "msg.parm.redecl"))
8470 name))
8471 ((= decl-type js2-LET)
8472 (if (and (not ignore-not-in-block)
8473 (or (= (js2-node-type js2-current-scope) js2-IF)
8474 (js2-loop-node-p js2-current-scope)))
8475 (js2-report-error "msg.let.decl.not.in.block")
8476 (js2-define-new-symbol decl-type name node)))
8477 ((or (= decl-type js2-VAR)
8478 (= decl-type js2-CONST)
8479 (= decl-type js2-FUNCTION))
8480 (if symbol
8481 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8482 (js2-add-strict-warning "msg.var.redecl" name)
8483 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8484 (js2-add-strict-warning "msg.var.hides.arg" name)))
8485 (js2-define-new-symbol decl-type name node
8486 js2-current-script-or-fn)))
8487 ((= decl-type js2-LP)
8488 (if symbol
8489 ;; must be duplicate parameter. Second parameter hides the
8490 ;; first, so go ahead and add the second pararameter
8491 (js2-report-warning "msg.dup.parms" name))
8492 (js2-define-new-symbol decl-type name node))
8493 (t (js2-code-bug)))))
8494
8495 (defun js2-parse-paren-expr-or-generator-comp ()
8496 (let ((px-pos (js2-current-token-beg)))
8497 (if (and (>= js2-language-version 200)
8498 (js2-match-token js2-FOR))
8499 (js2-parse-generator-comp px-pos)
8500 (let* ((expr (js2-parse-expr))
8501 (pn (make-js2-paren-node :pos px-pos
8502 :expr expr
8503 :len (- (js2-current-token-end)
8504 px-pos))))
8505 (js2-node-add-children pn (js2-paren-node-expr pn))
8506 (js2-must-match js2-RP "msg.no.paren")
8507 pn))))
8508
8509 (defun js2-parse-expr (&optional oneshot)
8510 (let* ((pn (js2-parse-assign-expr))
8511 (pos (js2-node-pos pn))
8512 left
8513 right
8514 op-pos)
8515 (while (and (not oneshot)
8516 (js2-match-token js2-COMMA))
8517 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
8518 (if (= (js2-peek-token) js2-YIELD)
8519 (js2-report-error "msg.yield.parenthesized"))
8520 (setq right (js2-parse-assign-expr)
8521 left pn
8522 pn (make-js2-infix-node :type js2-COMMA
8523 :pos pos
8524 :len (- js2-ts-cursor pos)
8525 :op-pos op-pos
8526 :left left
8527 :right right))
8528 (js2-node-add-children pn left right))
8529 pn))
8530
8531 (defun js2-parse-assign-expr ()
8532 (let ((tt (js2-get-token))
8533 (pos (js2-current-token-beg))
8534 pn left right op-pos
8535 ts-state recorded-identifiers)
8536 (if (= tt js2-YIELD)
8537 (js2-parse-return-or-yield tt t)
8538 ;; Save the tokenizer state in case we find an arrow function
8539 ;; and have to rewind.
8540 (setq ts-state (make-js2-ts-state)
8541 recorded-identifiers js2-recorded-identifiers)
8542 ;; not yield - parse assignment expression
8543 (setq pn (js2-parse-cond-expr)
8544 tt (js2-get-token))
8545 (cond
8546 ((and (<= js2-first-assign tt)
8547 (<= tt js2-last-assign))
8548 ;; tt express assignment (=, |=, ^=, ..., %=)
8549 (setq op-pos (- (js2-current-token-beg) pos) ; relative
8550 left pn)
8551 (setq right (js2-parse-assign-expr)
8552 pn (make-js2-assign-node :type tt
8553 :pos pos
8554 :len (- (js2-node-end right) pos)
8555 :op-pos op-pos
8556 :left left
8557 :right right))
8558 (when js2-parse-ide-mode
8559 (js2-highlight-assign-targets pn left right)
8560 (js2-record-imenu-functions right left))
8561 ;; do this last so ide checks above can use absolute positions
8562 (js2-node-add-children pn left right))
8563 ((and (= tt js2-ARROW)
8564 (>= js2-language-version 200))
8565 (js2-ts-seek ts-state)
8566 (setq js2-recorded-identifiers recorded-identifiers)
8567 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
8568 (t
8569 (js2-unget-token)))
8570 pn)))
8571
8572 (defun js2-parse-cond-expr ()
8573 (let ((pos (js2-current-token-beg))
8574 (pn (js2-parse-or-expr))
8575 test-expr
8576 if-true
8577 if-false
8578 q-pos
8579 c-pos)
8580 (when (js2-match-token js2-HOOK)
8581 (setq q-pos (- (js2-current-token-beg) pos)
8582 if-true (js2-parse-assign-expr))
8583 (js2-must-match js2-COLON "msg.no.colon.cond")
8584 (setq c-pos (- (js2-current-token-beg) pos)
8585 if-false (js2-parse-assign-expr)
8586 test-expr pn
8587 pn (make-js2-cond-node :pos pos
8588 :len (- (js2-node-end if-false) pos)
8589 :test-expr test-expr
8590 :true-expr if-true
8591 :false-expr if-false
8592 :q-pos q-pos
8593 :c-pos c-pos))
8594 (js2-node-add-children pn test-expr if-true if-false))
8595 pn))
8596
8597 (defun js2-make-binary (type left parser)
8598 "Helper for constructing a binary-operator AST node.
8599 LEFT is the left-side-expression, already parsed, and the
8600 binary operator should have just been matched.
8601 PARSER is a function to call to parse the right operand,
8602 or a `js2-node' struct if it has already been parsed.
8603 FIXME: The latter option is unused?"
8604 (let* ((pos (js2-node-pos left))
8605 (op-pos (- (js2-current-token-beg) pos))
8606 (right (if (js2-node-p parser)
8607 parser
8608 (js2-get-token)
8609 (funcall parser)))
8610 (pn (make-js2-infix-node :type type
8611 :pos pos
8612 :len (- (js2-node-end right) pos)
8613 :op-pos op-pos
8614 :left left
8615 :right right)))
8616 (js2-node-add-children pn left right)
8617 pn))
8618
8619 (defun js2-parse-or-expr ()
8620 (let ((pn (js2-parse-and-expr)))
8621 (when (js2-match-token js2-OR)
8622 (setq pn (js2-make-binary js2-OR
8623 pn
8624 'js2-parse-or-expr)))
8625 pn))
8626
8627 (defun js2-parse-and-expr ()
8628 (let ((pn (js2-parse-bit-or-expr)))
8629 (when (js2-match-token js2-AND)
8630 (setq pn (js2-make-binary js2-AND
8631 pn
8632 'js2-parse-and-expr)))
8633 pn))
8634
8635 (defun js2-parse-bit-or-expr ()
8636 (let ((pn (js2-parse-bit-xor-expr)))
8637 (while (js2-match-token js2-BITOR)
8638 (setq pn (js2-make-binary js2-BITOR
8639 pn
8640 'js2-parse-bit-xor-expr)))
8641 pn))
8642
8643 (defun js2-parse-bit-xor-expr ()
8644 (let ((pn (js2-parse-bit-and-expr)))
8645 (while (js2-match-token js2-BITXOR)
8646 (setq pn (js2-make-binary js2-BITXOR
8647 pn
8648 'js2-parse-bit-and-expr)))
8649 pn))
8650
8651 (defun js2-parse-bit-and-expr ()
8652 (let ((pn (js2-parse-eq-expr)))
8653 (while (js2-match-token js2-BITAND)
8654 (setq pn (js2-make-binary js2-BITAND
8655 pn
8656 'js2-parse-eq-expr)))
8657 pn))
8658
8659 (defconst js2-parse-eq-ops
8660 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8661
8662 (defun js2-parse-eq-expr ()
8663 (let ((pn (js2-parse-rel-expr))
8664 tt)
8665 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
8666 (setq pn (js2-make-binary tt
8667 pn
8668 'js2-parse-rel-expr)))
8669 (js2-unget-token)
8670 pn))
8671
8672 (defconst js2-parse-rel-ops
8673 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8674
8675 (defun js2-parse-rel-expr ()
8676 (let ((pn (js2-parse-shift-expr))
8677 (continue t)
8678 tt)
8679 (while continue
8680 (setq tt (js2-get-token))
8681 (cond
8682 ((and js2-in-for-init (= tt js2-IN))
8683 (js2-unget-token)
8684 (setq continue nil))
8685 ((memq tt js2-parse-rel-ops)
8686 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8687 (t
8688 (js2-unget-token)
8689 (setq continue nil))))
8690 pn))
8691
8692 (defconst js2-parse-shift-ops
8693 (list js2-LSH js2-URSH js2-RSH))
8694
8695 (defun js2-parse-shift-expr ()
8696 (let ((pn (js2-parse-add-expr))
8697 tt
8698 (continue t))
8699 (while continue
8700 (setq tt (js2-get-token))
8701 (if (memq tt js2-parse-shift-ops)
8702 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
8703 (js2-unget-token)
8704 (setq continue nil)))
8705 pn))
8706
8707 (defun js2-parse-add-expr ()
8708 (let ((pn (js2-parse-mul-expr))
8709 tt
8710 (continue t))
8711 (while continue
8712 (setq tt (js2-get-token))
8713 (if (or (= tt js2-ADD) (= tt js2-SUB))
8714 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
8715 (js2-unget-token)
8716 (setq continue nil)))
8717 pn))
8718
8719 (defconst js2-parse-mul-ops
8720 (list js2-MUL js2-DIV js2-MOD))
8721
8722 (defun js2-parse-mul-expr ()
8723 (let ((pn (js2-parse-unary-expr))
8724 tt
8725 (continue t))
8726 (while continue
8727 (setq tt (js2-get-token))
8728 (if (memq tt js2-parse-mul-ops)
8729 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
8730 (js2-unget-token)
8731 (setq continue nil)))
8732 pn))
8733
8734 (defun js2-make-unary (type parser &rest args)
8735 "Make a unary node of type TYPE.
8736 PARSER is either a node (for postfix operators) or a function to call
8737 to parse the operand (for prefix operators)."
8738 (let* ((pos (js2-current-token-beg))
8739 (postfix (js2-node-p parser))
8740 (expr (if postfix
8741 parser
8742 (apply parser args)))
8743 end
8744 pn)
8745 (if postfix ; e.g. i++
8746 (setq pos (js2-node-pos expr)
8747 end (js2-current-token-end))
8748 (setq end (js2-node-end expr)))
8749 (setq pn (make-js2-unary-node :type type
8750 :pos pos
8751 :len (- end pos)
8752 :operand expr))
8753 (js2-node-add-children pn expr)
8754 pn))
8755
8756 (defconst js2-incrementable-node-types
8757 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8758 "Node types that can be the operand of a ++ or -- operator.")
8759
8760 (defun js2-check-bad-inc-dec (tt beg end unary)
8761 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8762 js2-incrementable-node-types)
8763 (js2-report-error (if (= tt js2-INC)
8764 "msg.bad.incr"
8765 "msg.bad.decr")
8766 nil beg (- end beg))))
8767
8768 (defun js2-parse-unary-expr ()
8769 (let ((tt (js2-current-token-type))
8770 pn expr beg end)
8771 (cond
8772 ((or (= tt js2-VOID)
8773 (= tt js2-NOT)
8774 (= tt js2-BITNOT)
8775 (= tt js2-TYPEOF))
8776 (js2-get-token)
8777 (js2-make-unary tt 'js2-parse-unary-expr))
8778 ((= tt js2-ADD)
8779 (js2-get-token)
8780 ;; Convert to special POS token in decompiler and parse tree
8781 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8782 ((= tt js2-SUB)
8783 (js2-get-token)
8784 ;; Convert to special NEG token in decompiler and parse tree
8785 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8786 ((or (= tt js2-INC)
8787 (= tt js2-DEC))
8788 (js2-get-token)
8789 (prog1
8790 (setq beg (js2-current-token-beg)
8791 end (js2-current-token-end)
8792 expr (js2-make-unary tt 'js2-parse-member-expr t))
8793 (js2-check-bad-inc-dec tt beg end expr)))
8794 ((= tt js2-DELPROP)
8795 (js2-get-token)
8796 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8797 ((= tt js2-ERROR)
8798 (js2-get-token)
8799 (make-js2-error-node)) ; try to continue
8800 ((and (= tt js2-LT)
8801 js2-compiler-xml-available)
8802 ;; XML stream encountered in expression.
8803 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8804 (t
8805 (setq pn (js2-parse-member-expr t)
8806 ;; Don't look across a newline boundary for a postfix incop.
8807 tt (js2-peek-token-or-eol))
8808 (when (or (= tt js2-INC) (= tt js2-DEC))
8809 (js2-get-token)
8810 (setf expr pn
8811 pn (js2-make-unary tt expr))
8812 (js2-node-set-prop pn 'postfix t)
8813 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
8814 pn))))
8815
8816 (defun js2-parse-xml-initializer ()
8817 "Parse an E4X XML initializer.
8818 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8819 Then I'll postprocess the result, depending on whether we're in IDE
8820 mode or codegen mode, and generate the appropriate rewritten AST.
8821 IDE mode uses a rich AST that models the XML structure. Codegen mode
8822 just concatenates everything and makes a new XML or XMLList out of it."
8823 (let ((tt (js2-get-first-xml-token))
8824 pn-xml pn expr kids expr-pos
8825 (continue t)
8826 (first-token t))
8827 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8828 (js2-report-error "msg.syntax"))
8829 (setq pn-xml (make-js2-xml-node))
8830 (while continue
8831 (if first-token
8832 (setq first-token nil)
8833 (setq tt (js2-get-next-xml-token)))
8834 (cond
8835 ;; js2-XML means we found a {expr} in the XML stream.
8836 ;; The token string is the XML up to the left-curly.
8837 ((= tt js2-XML)
8838 (push (make-js2-string-node :pos (js2-current-token-beg)
8839 :len (- js2-ts-cursor (js2-current-token-beg)))
8840 kids)
8841 (js2-must-match js2-LC "msg.syntax")
8842 (setq expr-pos js2-ts-cursor
8843 expr (if (eq (js2-peek-token) js2-RC)
8844 (make-js2-empty-expr-node :pos expr-pos)
8845 (js2-parse-expr)))
8846 (js2-must-match js2-RC "msg.syntax")
8847 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8848 :len (js2-node-len expr)
8849 :expr expr))
8850 (js2-node-add-children pn expr)
8851 (push pn kids))
8852 ;; a js2-XMLEND token means we hit the final close-tag.
8853 ((= tt js2-XMLEND)
8854 (push (make-js2-string-node :pos (js2-current-token-beg)
8855 :len (- js2-ts-cursor (js2-current-token-beg)))
8856 kids)
8857 (dolist (kid (nreverse kids))
8858 (js2-block-node-push pn-xml kid))
8859 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8860 (js2-node-pos pn-xml))
8861 continue nil))
8862 (t
8863 (js2-report-error "msg.syntax")
8864 (setq continue nil))))
8865 pn-xml))
8866
8867
8868 (defun js2-parse-argument-list ()
8869 "Parse an argument list and return it as a Lisp list of nodes.
8870 Returns the list in reverse order. Consumes the right-paren token."
8871 (let (result)
8872 (unless (js2-match-token js2-RP)
8873 (loop do
8874 (let ((tt (js2-get-token)))
8875 (if (= tt js2-YIELD)
8876 (js2-report-error "msg.yield.parenthesized"))
8877 (if (and (= tt js2-TRIPLEDOT)
8878 (>= js2-language-version 200))
8879 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
8880 (js2-unget-token)
8881 (push (js2-parse-assign-expr) result)))
8882 while
8883 (js2-match-token js2-COMMA))
8884 (js2-must-match js2-RP "msg.no.paren.arg")
8885 result)))
8886
8887 (defun js2-parse-member-expr (&optional allow-call-syntax)
8888 (let ((tt (js2-current-token-type))
8889 pn pos target args beg end init)
8890 (if (/= tt js2-NEW)
8891 (setq pn (js2-parse-primary-expr))
8892 ;; parse a 'new' expression
8893 (js2-get-token)
8894 (setq pos (js2-current-token-beg)
8895 beg pos
8896 target (js2-parse-member-expr)
8897 end (js2-node-end target)
8898 pn (make-js2-new-node :pos pos
8899 :target target
8900 :len (- end pos)))
8901 (js2-highlight-function-call (js2-current-token))
8902 (js2-node-add-children pn target)
8903 (when (js2-match-token js2-LP)
8904 ;; Add the arguments to pn, if any are supplied.
8905 (setf beg pos ; start of "new" keyword
8906 pos (js2-current-token-beg)
8907 args (nreverse (js2-parse-argument-list))
8908 (js2-new-node-args pn) args
8909 end (js2-current-token-end)
8910 (js2-new-node-lp pn) (- pos beg)
8911 (js2-new-node-rp pn) (- end 1 beg))
8912 (apply #'js2-node-add-children pn args))
8913 (when (and js2-allow-rhino-new-expr-initializer
8914 (js2-match-token js2-LC))
8915 (setf init (js2-parse-object-literal)
8916 end (js2-node-end init)
8917 (js2-new-node-initializer pn) init)
8918 (js2-node-add-children pn init))
8919 (setf (js2-node-len pn) (- end beg))) ; end outer if
8920 (js2-parse-member-expr-tail allow-call-syntax pn)))
8921
8922 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8923 "Parse a chain of property/array accesses or function calls.
8924 Includes parsing for E4X operators like `..' and `.@'.
8925 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8926 Returns an expression tree that includes PN, the parent node."
8927 (let (tt
8928 (continue t))
8929 (while continue
8930 (setq tt (js2-get-token))
8931 (cond
8932 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8933 (setq pn (js2-parse-property-access tt pn)))
8934 ((= tt js2-DOTQUERY)
8935 (setq pn (js2-parse-dot-query pn)))
8936 ((= tt js2-LB)
8937 (setq pn (js2-parse-element-get pn)))
8938 ((= tt js2-LP)
8939 (js2-unget-token)
8940 (if allow-call-syntax
8941 (setq pn (js2-parse-function-call pn))
8942 (setq continue nil)))
8943 (t
8944 (js2-unget-token)
8945 (setq continue nil))))
8946 (if (>= js2-highlight-level 2)
8947 (js2-parse-highlight-member-expr-node pn))
8948 pn))
8949
8950 (defun js2-parse-dot-query (pn)
8951 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8952 Last token parsed must be `js2-DOTQUERY'."
8953 (let ((pos (js2-node-pos pn))
8954 op-pos expr end)
8955 (js2-must-have-xml)
8956 (js2-set-requires-activation)
8957 (setq op-pos (js2-current-token-beg)
8958 expr (js2-parse-expr)
8959 end (js2-node-end expr)
8960 pn (make-js2-xml-dot-query-node :left pn
8961 :pos pos
8962 :op-pos op-pos
8963 :right expr))
8964 (js2-node-add-children pn
8965 (js2-xml-dot-query-node-left pn)
8966 (js2-xml-dot-query-node-right pn))
8967 (if (js2-must-match js2-RP "msg.no.paren")
8968 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
8969 end (js2-current-token-end)))
8970 (setf (js2-node-len pn) (- end pos))
8971 pn))
8972
8973 (defun js2-parse-element-get (pn)
8974 "Parse an element-get expression, e.g. foo[bar].
8975 Last token parsed must be `js2-RB'."
8976 (let ((lb (js2-current-token-beg))
8977 (pos (js2-node-pos pn))
8978 rb expr)
8979 (setq expr (js2-parse-expr))
8980 (if (js2-must-match js2-RB "msg.no.bracket.index")
8981 (setq rb (js2-current-token-beg)))
8982 (setq pn (make-js2-elem-get-node :target pn
8983 :pos pos
8984 :element expr
8985 :lb (js2-relpos lb pos)
8986 :rb (js2-relpos rb pos)
8987 :len (- (js2-current-token-end) pos)))
8988 (js2-node-add-children pn
8989 (js2-elem-get-node-target pn)
8990 (js2-elem-get-node-element pn))
8991 pn))
8992
8993 (defun js2-highlight-function-call (token)
8994 (when (eq (js2-token-type token) js2-NAME)
8995 (js2-record-face 'js2-function-call token)))
8996
8997 (defun js2-parse-function-call (pn)
8998 (js2-highlight-function-call (js2-current-token))
8999 (js2-get-token)
9000 (let (args
9001 (pos (js2-node-pos pn)))
9002 (setq pn (make-js2-call-node :pos pos
9003 :target pn
9004 :lp (- (js2-current-token-beg) pos)))
9005 (js2-node-add-children pn (js2-call-node-target pn))
9006 ;; Add the arguments to pn, if any are supplied.
9007 (setf args (nreverse (js2-parse-argument-list))
9008 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9009 (js2-call-node-args pn) args)
9010 (apply #'js2-node-add-children pn args)
9011 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9012 pn))
9013
9014 (defun js2-parse-property-access (tt pn)
9015 "Parse a property access, XML descendants access, or XML attr access."
9016 (let ((member-type-flags 0)
9017 (dot-pos (js2-current-token-beg))
9018 (dot-len (if (= tt js2-DOTDOT) 2 1))
9019 name
9020 ref ; right side of . or .. operator
9021 result)
9022 (when (= tt js2-DOTDOT)
9023 (js2-must-have-xml)
9024 (setq member-type-flags js2-descendants-flag))
9025 (if (not js2-compiler-xml-available)
9026 (progn
9027 (js2-must-match-prop-name "msg.no.name.after.dot")
9028 (setq name (js2-create-name-node t js2-GETPROP)
9029 result (make-js2-prop-get-node :left pn
9030 :pos (js2-current-token-beg)
9031 :right name
9032 :len (js2-current-token-len)))
9033 (js2-node-add-children result pn name)
9034 result)
9035 ;; otherwise look for XML operators
9036 (setf result (if (= tt js2-DOT)
9037 (make-js2-prop-get-node)
9038 (make-js2-infix-node :type js2-DOTDOT))
9039 (js2-node-pos result) (js2-node-pos pn)
9040 (js2-infix-node-op-pos result) dot-pos
9041 (js2-infix-node-left result) pn ; do this after setting position
9042 tt (js2-next-token))
9043 (cond
9044 ;; needed for generator.throw()
9045 ((= tt js2-THROW)
9046 (setq ref (js2-parse-property-name nil nil member-type-flags)))
9047 ;; handles: name, ns::name, ns::*, ns::[expr]
9048 ((js2-valid-prop-name-token tt)
9049 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9050 ;; handles: *, *::name, *::*, *::[expr]
9051 ((= tt js2-MUL)
9052 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9053 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9054 ((= tt js2-XMLATTR)
9055 (setq result (js2-parse-attribute-access)))
9056 (t
9057 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9058 (if ref
9059 (setf (js2-node-len result) (- (js2-node-end ref)
9060 (js2-node-pos result))
9061 (js2-infix-node-right result) ref))
9062 (if (js2-infix-node-p result)
9063 (js2-node-add-children result
9064 (js2-infix-node-left result)
9065 (js2-infix-node-right result)))
9066 result)))
9067
9068 (defun js2-parse-attribute-access ()
9069 "Parse an E4X XML attribute expression.
9070 This includes expressions of the forms:
9071
9072 @attr @ns::attr @ns::*
9073 @* @*::attr @*::*
9074 @[expr] @*::[expr] @ns::[expr]
9075
9076 Called if we peeked an '@' token."
9077 (let ((tt (js2-next-token))
9078 (at-pos (js2-current-token-beg)))
9079 (cond
9080 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9081 ((js2-valid-prop-name-token tt)
9082 (js2-parse-property-name at-pos nil 0))
9083 ;; handles: @*, @*::name, @*::*, @*::[expr]
9084 ((= tt js2-MUL)
9085 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9086 ;; handles @[expr]
9087 ((= tt js2-LB)
9088 (js2-parse-xml-elem-ref at-pos))
9089 (t
9090 (js2-report-error "msg.no.name.after.xmlAttr")
9091 ;; Avoid cascaded errors that happen if we make an error node here.
9092 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9093
9094 (defun js2-parse-property-name (at-pos s member-type-flags)
9095 "Check if :: follows name in which case it becomes qualified name.
9096
9097 AT-POS is a natural number if we just read an '@' token, else nil.
9098 S is the name or string that was matched: an identifier, 'throw' or '*'.
9099 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9100
9101 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9102 operator, or the name is followed by ::. For a plain name, returns a
9103 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9104 (let ((pos (or at-pos (js2-current-token-beg)))
9105 colon-pos
9106 (name (js2-create-name-node t (js2-current-token-type) s))
9107 ns tt pn)
9108 (catch 'return
9109 (when (js2-match-token js2-COLONCOLON)
9110 (setq ns name
9111 colon-pos (js2-current-token-beg)
9112 tt (js2-next-token))
9113 (cond
9114 ;; handles name::name
9115 ((js2-valid-prop-name-token tt)
9116 (setq name (js2-create-name-node)))
9117 ;; handles name::*
9118 ((= tt js2-MUL)
9119 (setq name (js2-create-name-node nil nil "*")))
9120 ;; handles name::[expr]
9121 ((= tt js2-LB)
9122 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9123 (t
9124 (js2-report-error "msg.no.name.after.coloncolon"))))
9125 (if (and (null ns) (zerop member-type-flags))
9126 name
9127 (prog1
9128 (setq pn
9129 (make-js2-xml-prop-ref-node :pos pos
9130 :len (- (js2-node-end name) pos)
9131 :at-pos at-pos
9132 :colon-pos colon-pos
9133 :propname name))
9134 (js2-node-add-children pn name))))))
9135
9136 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9137 "Parse the [expr] portion of an xml element reference.
9138 For instance, @[expr], @*::[expr], or ns::[expr]."
9139 (let* ((lb (js2-current-token-beg))
9140 (pos (or at-pos lb))
9141 rb
9142 (expr (js2-parse-expr))
9143 (end (js2-node-end expr))
9144 pn)
9145 (if (js2-must-match js2-RB "msg.no.bracket.index")
9146 (setq rb (js2-current-token-beg)
9147 end (js2-current-token-end)))
9148 (prog1
9149 (setq pn
9150 (make-js2-xml-elem-ref-node :pos pos
9151 :len (- end pos)
9152 :namespace namespace
9153 :colon-pos colon-pos
9154 :at-pos at-pos
9155 :expr expr
9156 :lb (js2-relpos lb pos)
9157 :rb (js2-relpos rb pos)))
9158 (js2-node-add-children pn namespace expr))))
9159
9160 (defun js2-parse-destruct-primary-expr ()
9161 (let ((js2-is-in-destructuring t))
9162 (js2-parse-primary-expr)))
9163
9164 (defun js2-parse-primary-expr ()
9165 "Parse a literal (leaf) expression of some sort.
9166 Includes complex literals such as functions, object-literals,
9167 array-literals, array comprehensions and regular expressions."
9168 (let (pn ; parent node (usually return value)
9169 tt
9170 px-pos ; paren-expr pos
9171 len
9172 flags ; regexp flags
9173 expr)
9174 (setq tt (js2-current-token-type))
9175 (cond
9176 ((= tt js2-FUNCTION)
9177 (js2-parse-function-expr))
9178 ((= tt js2-LB)
9179 (js2-parse-array-comp-or-literal))
9180 ((= tt js2-LC)
9181 (js2-parse-object-literal))
9182 ((= tt js2-LET)
9183 (js2-parse-let (js2-current-token-beg)))
9184 ((= tt js2-LP)
9185 (js2-parse-paren-expr-or-generator-comp))
9186 ((= tt js2-XMLATTR)
9187 (js2-must-have-xml)
9188 (js2-parse-attribute-access))
9189 ((= tt js2-NAME)
9190 (js2-parse-name tt))
9191 ((= tt js2-NUMBER)
9192 (make-js2-number-node))
9193 ((= tt js2-STRING)
9194 (prog1
9195 (make-js2-string-node)
9196 (js2-record-face 'font-lock-string-face)))
9197 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9198 ;; Got / or /= which in this context means a regexp literal
9199 (setq px-pos (js2-current-token-beg))
9200 (setq flags (js2-read-regexp tt))
9201 (prog1
9202 (make-js2-regexp-node :pos px-pos
9203 :len (- js2-ts-cursor px-pos)
9204 :value (js2-current-token-string)
9205 :flags flags)
9206 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9207 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9208 ((or (= tt js2-NULL)
9209 (= tt js2-THIS)
9210 (= tt js2-FALSE)
9211 (= tt js2-TRUE))
9212 (make-js2-keyword-node :type tt))
9213 ((= tt js2-RP)
9214 ;; Not valid expression syntax, but this is valid in an arrow
9215 ;; function with no params: () => body.
9216 (if (eq (js2-peek-token) js2-ARROW)
9217 (progn
9218 (js2-unget-token) ; Put back the right paren.
9219 ;; Return whatever, it will hopefully be rewinded and
9220 ;; reparsed when we reach the =>.
9221 (make-js2-keyword-node :type js2-NULL))
9222 (js2-report-error "msg.syntax")
9223 (make-js2-error-node)))
9224 ((= tt js2-TRIPLEDOT)
9225 ;; Likewise, only valid in an arrow function with a rest param.
9226 (if (and (js2-match-token js2-NAME)
9227 (js2-match-token js2-RP)
9228 (eq (js2-peek-token) js2-ARROW))
9229 (progn
9230 (js2-unget-token) ; Put back the right paren.
9231 ;; See the previous case.
9232 (make-js2-keyword-node :type js2-NULL))
9233 (js2-report-error "msg.syntax")
9234 (make-js2-error-node)))
9235 ((= tt js2-RESERVED)
9236 (js2-report-error "msg.reserved.id")
9237 (make-js2-name-node))
9238 ((= tt js2-ERROR)
9239 ;; the scanner or one of its subroutines reported the error.
9240 (make-js2-error-node))
9241 ((= tt js2-EOF)
9242 (setq px-pos (point-at-bol)
9243 len (- js2-ts-cursor px-pos))
9244 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9245 (make-js2-error-node :pos (1- js2-ts-cursor)))
9246 (t
9247 (js2-report-error "msg.syntax")
9248 (make-js2-error-node)))))
9249
9250 (defun js2-parse-name (_tt)
9251 (let ((name (js2-current-token-string))
9252 node)
9253 (setq node (if js2-compiler-xml-available
9254 (js2-parse-property-name nil name 0)
9255 (js2-create-name-node 'check-activation nil name)))
9256 (if js2-highlight-external-variables
9257 (js2-record-name-node node))
9258 node))
9259
9260 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9261 (js2-add-strict-warning
9262 msg nil
9263 ;; back up from comma to beginning of line or array/objlit
9264 (max (if elems
9265 (js2-node-pos (car elems))
9266 pos)
9267 (save-excursion
9268 (goto-char comma-pos)
9269 (back-to-indentation)
9270 (point)))
9271 comma-pos))
9272
9273 (defun js2-parse-array-comp-or-literal ()
9274 (let ((pos (js2-current-token-beg)))
9275 (if (and (>= js2-language-version 200)
9276 (js2-match-token js2-FOR))
9277 (js2-parse-array-comp pos)
9278 (js2-parse-array-literal pos))))
9279
9280 (defun js2-parse-array-literal (pos)
9281 (let ((after-lb-or-comma t)
9282 after-comma tt elems pn
9283 (continue t))
9284 (unless js2-is-in-destructuring
9285 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
9286 (while continue
9287 (setq tt (js2-get-token))
9288 (cond
9289 ;; comma
9290 ((= tt js2-COMMA)
9291 (setq after-comma (js2-current-token-end))
9292 (if (not after-lb-or-comma)
9293 (setq after-lb-or-comma t)
9294 (push nil elems)))
9295 ;; end of array
9296 ((or (= tt js2-RB)
9297 (= tt js2-EOF)) ; prevent infinite loop
9298 (if (= tt js2-EOF)
9299 (js2-report-error "msg.no.bracket.arg" nil pos))
9300 (when (and after-comma (< js2-language-version 170))
9301 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9302 pos (remove nil elems) after-comma))
9303 (setq continue nil
9304 pn (make-js2-array-node :pos pos
9305 :len (- js2-ts-cursor pos)
9306 :elems (nreverse elems)))
9307 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
9308 ;; destructuring binding
9309 (js2-is-in-destructuring
9310 (push (if (or (= tt js2-LC)
9311 (= tt js2-LB)
9312 (= tt js2-NAME))
9313 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9314 (js2-parse-destruct-primary-expr)
9315 ;; invalid pattern
9316 (js2-report-error "msg.bad.var")
9317 (make-js2-error-node))
9318 elems)
9319 (setq after-lb-or-comma nil
9320 after-comma nil))
9321 ;; array comp
9322 ((and (>= js2-language-version 170)
9323 (= tt js2-FOR) ; check for array comprehension
9324 (not after-lb-or-comma) ; "for" can't follow a comma
9325 elems ; must have at least 1 element
9326 (not (cdr elems))) ; but no 2nd element
9327 (js2-unget-token)
9328 (setf continue nil
9329 pn (js2-parse-legacy-array-comp (car elems) pos)))
9330 ;; another element
9331 (t
9332 (unless after-lb-or-comma
9333 (js2-report-error "msg.no.bracket.arg"))
9334 (if (and (= tt js2-TRIPLEDOT)
9335 (>= js2-language-version 200))
9336 ;; spread operator
9337 (push (js2-make-unary tt 'js2-parse-assign-expr)
9338 elems)
9339 (js2-unget-token)
9340 (push (js2-parse-assign-expr) elems))
9341 (setq after-lb-or-comma nil
9342 after-comma nil))))
9343 (unless js2-is-in-destructuring
9344 (js2-pop-scope))
9345 pn))
9346
9347 (defun js2-parse-legacy-array-comp (expr pos)
9348 "Parse a legacy array comprehension (JavaScript 1.7).
9349 EXPR is the first expression after the opening left-bracket.
9350 POS is the beginning of the LB token preceding EXPR.
9351 We should have just parsed the 'for' keyword before calling this function."
9352 (let ((current-scope js2-current-scope)
9353 loops first filter result)
9354 (unwind-protect
9355 (progn
9356 (while (js2-match-token js2-FOR)
9357 (let ((loop (make-js2-comp-loop-node)))
9358 (js2-push-scope loop)
9359 (push loop loops)
9360 (js2-parse-comp-loop loop)))
9361 ;; First loop takes expr scope's parent.
9362 (setf (js2-scope-parent-scope (setq first (car (last loops))))
9363 (js2-scope-parent-scope current-scope))
9364 ;; Set expr scope's parent to the last loop.
9365 (setf (js2-scope-parent-scope current-scope) (car loops))
9366 (if (/= (js2-get-token) js2-IF)
9367 (js2-unget-token)
9368 (setq filter (js2-parse-condition))))
9369 (dotimes (_ (1- (length loops)))
9370 (js2-pop-scope)))
9371 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9372 (setq result (make-js2-comp-node :pos pos
9373 :len (- js2-ts-cursor pos)
9374 :result expr
9375 :loops (nreverse loops)
9376 :filters (and filter (list (car filter)))
9377 :form 'LEGACY_ARRAY))
9378 (apply #'js2-node-add-children result expr (car filter)
9379 (js2-comp-node-loops result))
9380 result))
9381
9382 (defun js2-parse-array-comp (pos)
9383 "Parse an ES6 array comprehension.
9384 POS is the beginning of the LB token.
9385 We should have just parsed the 'for' keyword before calling this function."
9386 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
9387 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9388 pn))
9389
9390 (defun js2-parse-generator-comp (pos)
9391 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
9392 (js2-current-script-or-fn
9393 (make-js2-function-node :generator-type 'COMPREHENSION))
9394 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
9395 (js2-must-match js2-RP "msg.no.paren" pos)
9396 pn))
9397
9398 (defun js2-parse-comprehension (pos form)
9399 (let (loops filters expr result)
9400 (unwind-protect
9401 (progn
9402 (js2-unget-token)
9403 (while (js2-match-token js2-FOR)
9404 (let ((loop (make-js2-comp-loop-node)))
9405 (js2-push-scope loop)
9406 (push loop loops)
9407 (js2-parse-comp-loop loop)))
9408 (while (js2-match-token js2-IF)
9409 (push (car (js2-parse-condition)) filters))
9410 (setq expr (js2-parse-assign-expr)))
9411 (dolist (_ loops)
9412 (js2-pop-scope)))
9413 (setq result (make-js2-comp-node :pos pos
9414 :len (- js2-ts-cursor pos)
9415 :result expr
9416 :loops (nreverse loops)
9417 :filters (nreverse filters)
9418 :form form))
9419 (apply #'js2-node-add-children result (js2-comp-node-loops result))
9420 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
9421 result))
9422
9423 (defun js2-parse-comp-loop (pn &optional only-of-p)
9424 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9425 The current token should be the initial FOR.
9426 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
9427 (let ((pos (js2-comp-loop-node-pos pn))
9428 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9429 (when (and (not only-of-p) (js2-match-token js2-NAME))
9430 (if (string= (js2-current-token-string) "each")
9431 (progn
9432 (setq foreach-p t
9433 each-pos (- (js2-current-token-beg) pos)) ; relative
9434 (js2-record-face 'font-lock-keyword-face))
9435 (js2-report-error "msg.no.paren.for")))
9436 (if (js2-must-match js2-LP "msg.no.paren.for")
9437 (setq lp (- (js2-current-token-beg) pos)))
9438 (setq tt (js2-peek-token))
9439 (cond
9440 ((or (= tt js2-LB)
9441 (= tt js2-LC))
9442 (js2-get-token)
9443 (setq iter (js2-parse-destruct-primary-expr))
9444 (js2-define-destruct-symbols iter js2-LET
9445 'font-lock-variable-name-face t))
9446 ((js2-match-token js2-NAME)
9447 (setq iter (js2-create-name-node)))
9448 (t
9449 (js2-report-error "msg.bad.var")))
9450 ;; Define as a let since we want the scope of the variable to
9451 ;; be restricted to the array comprehension
9452 (if (js2-name-node-p iter)
9453 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9454 (if (or (and (not only-of-p) (js2-match-token js2-IN))
9455 (and (>= js2-language-version 200)
9456 (js2-match-contextual-kwd "of")
9457 (setq forof-p t)))
9458 (setq in-pos (- (js2-current-token-beg) pos))
9459 (js2-report-error "msg.in.after.for.name"))
9460 (setq obj (js2-parse-expr))
9461 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9462 (setq rp (- (js2-current-token-beg) pos)))
9463 (setf (js2-node-pos pn) pos
9464 (js2-node-len pn) (- js2-ts-cursor pos)
9465 (js2-comp-loop-node-iterator pn) iter
9466 (js2-comp-loop-node-object pn) obj
9467 (js2-comp-loop-node-in-pos pn) in-pos
9468 (js2-comp-loop-node-each-pos pn) each-pos
9469 (js2-comp-loop-node-foreach-p pn) foreach-p
9470 (js2-comp-loop-node-forof-p pn) forof-p
9471 (js2-comp-loop-node-lp pn) lp
9472 (js2-comp-loop-node-rp pn) rp)
9473 (js2-node-add-children pn iter obj)
9474 pn))
9475
9476 (defun js2-parse-object-literal ()
9477 (let ((pos (js2-current-token-beg))
9478 tt elems result after-comma
9479 (continue t))
9480 (while continue
9481 (setq tt (js2-get-token))
9482 (cond
9483 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9484 ;; {get foo() {...}}, or {set foo(x) {...}}
9485 ((or (js2-valid-prop-name-token tt)
9486 (= tt js2-STRING))
9487 (setq after-comma nil
9488 result (js2-parse-named-prop tt))
9489 (if (and (null result)
9490 (not js2-recover-from-parse-errors))
9491 (setq continue nil)
9492 (push result elems)))
9493 ;; {12: x} or {10.7: x}
9494 ((= tt js2-NUMBER)
9495 (setq after-comma nil)
9496 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9497 ;; trailing comma
9498 ((= tt js2-RC)
9499 (js2-unget-token)
9500 (setq continue nil)
9501 (if after-comma
9502 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9503 pos elems after-comma)))
9504 (t
9505 (js2-report-error "msg.bad.prop")
9506 (unless js2-recover-from-parse-errors
9507 (setq continue nil)))) ; end switch
9508 (if (js2-match-token js2-COMMA)
9509 (setq after-comma (js2-current-token-end))
9510 (setq continue nil))) ; end loop
9511 (js2-must-match js2-RC "msg.no.brace.prop")
9512 (setq result (make-js2-object-node :pos pos
9513 :len (- js2-ts-cursor pos)
9514 :elems (nreverse elems)))
9515 (apply #'js2-node-add-children result (js2-object-node-elems result))
9516 result))
9517
9518 (defun js2-parse-named-prop (tt)
9519 "Parse a name, string, or getter/setter object property.
9520 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9521 (let ((string-prop (and (= tt js2-STRING)
9522 (make-js2-string-node)))
9523 expr
9524 (ppos (js2-current-token-beg))
9525 (pend (js2-current-token-end))
9526 (name (js2-create-name-node))
9527 (prop (js2-current-token-string)))
9528 (cond
9529 ;; getter/setter prop
9530 ((and (= tt js2-NAME)
9531 (= (js2-peek-token) js2-NAME)
9532 (or (string= prop "get")
9533 (string= prop "set")))
9534 (js2-get-token)
9535 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9536 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9537 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9538 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9539 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9540 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9541 ;; when patterns are used in variable declarations, function parameters,
9542 ;; catch-clause, and iterators.
9543 ;; We have to set `js2-is-in-destructuring' to t when the current
9544 ;; expressions are on the left side of any assignment, but it's difficult
9545 ;; because it requires looking ahead of expression.
9546 ((and js2-is-in-destructuring
9547 (= tt js2-NAME)
9548 (let ((ctk (js2-peek-token)))
9549 (or (= ctk js2-COMMA)
9550 (= ctk js2-RC)
9551 (js2-valid-prop-name-token ctk))))
9552 name)
9553 ;; regular prop
9554 (t
9555 (prog1
9556 (setq expr (js2-parse-plain-property (or string-prop name)))
9557 (js2-set-face ppos pend
9558 (if (js2-function-node-p
9559 (js2-object-prop-node-right expr))
9560 'font-lock-function-name-face
9561 'font-lock-variable-name-face)
9562 'record))))))
9563
9564 (defun js2-parse-plain-property (prop)
9565 "Parse a non-getter/setter property in an object literal.
9566 PROP is the node representing the property: a number, name or string."
9567 (js2-must-match js2-COLON "msg.no.colon.prop")
9568 (let* ((pos (js2-node-pos prop))
9569 (colon (- (js2-current-token-beg) pos))
9570 (expr (js2-parse-assign-expr))
9571 (result (make-js2-object-prop-node
9572 :pos pos
9573 ;; don't include last consumed token in length
9574 :len (- (+ (js2-node-pos expr)
9575 (js2-node-len expr))
9576 pos)
9577 :left prop
9578 :right expr
9579 :op-pos colon)))
9580 (js2-node-add-children result prop expr)
9581 result))
9582
9583 (defun js2-parse-getter-setter-prop (pos prop get-p)
9584 "Parse getter or setter property in an object literal.
9585 JavaScript syntax is:
9586
9587 { get foo() {...}, set foo(x) {...} }
9588
9589 and expression closure style is also supported
9590
9591 { get foo() x, set foo(x) _x = x }
9592
9593 POS is the start position of the `get' or `set' keyword.
9594 PROP is the `js2-name-node' representing the property name.
9595 GET-P is non-nil if the keyword was `get'."
9596 (let ((type (if get-p js2-GET js2-SET))
9597 result end
9598 (fn (js2-parse-function-expr)))
9599 ;; it has to be an anonymous function, as we already parsed the name
9600 (if (/= (js2-node-type fn) js2-FUNCTION)
9601 (js2-report-error "msg.bad.prop")
9602 (if (plusp (length (js2-function-name fn)))
9603 (js2-report-error "msg.bad.prop")))
9604 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9605 (setq end (js2-node-end fn)
9606 result (make-js2-getter-setter-node :type type
9607 :pos pos
9608 :len (- end pos)
9609 :left prop
9610 :right fn))
9611 (js2-node-add-children result prop fn)
9612 result))
9613
9614 (defun js2-create-name-node (&optional check-activation-p token string)
9615 "Create a name node using the current token and, optionally, STRING.
9616 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
9617 (let* ((beg (js2-current-token-beg))
9618 (tt (js2-current-token-type))
9619 (s (or string
9620 (if (= js2-NAME tt)
9621 (js2-current-token-string)
9622 (js2-tt-name tt))))
9623 name)
9624 (setq name (make-js2-name-node :pos beg
9625 :name s
9626 :len (length s)))
9627 (if check-activation-p
9628 (js2-check-activation-name s (or token js2-NAME)))
9629 name))
9630
9631 ;;; Indentation support
9632
9633 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9634 ;; Karl cleverly deduces that the desired indentation level is often a
9635 ;; function of paren/bracket/brace nesting depth, which can be determined
9636 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9637 ;; then does some equally clever checks to see if we're in the context of a
9638 ;; substatement of a possibly braceless statement keyword such as if, while,
9639 ;; or finally. This approach yields pretty good results.
9640
9641 ;; The indenter is often "wrong", however, and needs to be overridden.
9642 ;; The right long-term solution is probably to emulate (or integrate
9643 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9644 ;; parse tree from `js2-parse' is present, which is not true at the
9645 ;; moment the user is typing, computing indentation is still thousands
9646 ;; of lines of code to handle every possible syntactic edge case.
9647
9648 ;; In the meantime, the compromise solution is that we offer a "bounce
9649 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9650 ;; current line indent among various likely guess points. This approach
9651 ;; is far from perfect, but should at least make it slightly easier to
9652 ;; move the line towards its desired indentation when manually
9653 ;; overriding Karl's heuristic nesting guesser.
9654
9655 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9656 ;; extensions such as `let' and Array comprehensions. Major kudos to
9657 ;; Karl for coming up with the initial approach, which packs a lot of
9658 ;; punch for so little code.
9659
9660 (defconst js2-possibly-braceless-keywords-re
9661 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9662 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9663 "try" "while" "with" "let")))
9664 "Regular expression matching keywords that are optionally
9665 followed by an opening brace.")
9666
9667 (defconst js2-indent-operator-re
9668 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9669 (regexp-opt '("in" "instanceof") 'words))
9670 "Regular expression matching operators that affect indentation
9671 of continued expressions.")
9672
9673 (defconst js2-declaration-keyword-re
9674 (regexp-opt '("var" "let" "const") 'words)
9675 "Regular expression matching variable declaration keywords.")
9676
9677 (defun js2-re-search-forward-inner (regexp &optional bound count)
9678 "Auxiliary function for `js2-re-search-forward'."
9679 (let (parse saved-point)
9680 (while (> count 0)
9681 (re-search-forward regexp bound)
9682 (setq parse (if saved-point
9683 (parse-partial-sexp saved-point (point))
9684 (syntax-ppss (point))))
9685 (cond ((nth 3 parse)
9686 (re-search-forward
9687 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
9688 (save-excursion (end-of-line) (point)) t))
9689 ((nth 7 parse)
9690 (forward-line))
9691 ((or (nth 4 parse)
9692 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9693 (re-search-forward "\\*/"))
9694 (t
9695 (setq count (1- count))))
9696 (setq saved-point (point))))
9697 (point))
9698
9699 (defun js2-re-search-forward (regexp &optional bound noerror count)
9700 "Search forward but ignore strings and comments.
9701 Invokes `re-search-forward' but treats the buffer as if strings
9702 and comments have been removed."
9703 (let ((saved-point (point)))
9704 (condition-case err
9705 (cond ((null count)
9706 (js2-re-search-forward-inner regexp bound 1))
9707 ((< count 0)
9708 (js2-re-search-backward-inner regexp bound (- count)))
9709 ((> count 0)
9710 (js2-re-search-forward-inner regexp bound count)))
9711 (search-failed
9712 (goto-char saved-point)
9713 (unless noerror
9714 (error (error-message-string err)))))))
9715
9716 (defun js2-re-search-backward-inner (regexp &optional bound count)
9717 "Auxiliary function for `js2-re-search-backward'."
9718 (let (parse)
9719 (while (> count 0)
9720 (re-search-backward regexp bound)
9721 (setq parse (syntax-ppss (point)))
9722 (cond ((nth 3 parse)
9723 (re-search-backward
9724 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9725 (line-beginning-position) t))
9726 ((nth 7 parse)
9727 (goto-char (nth 8 parse)))
9728 ((or (nth 4 parse)
9729 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9730 (re-search-backward "/\\*"))
9731 (t
9732 (setq count (1- count))))))
9733 (point))
9734
9735 (defun js2-re-search-backward (regexp &optional bound noerror count)
9736 "Search backward but ignore strings and comments.
9737 Invokes `re-search-backward' but treats the buffer as if strings
9738 and comments have been removed."
9739 (let ((saved-point (point)))
9740 (condition-case err
9741 (cond ((null count)
9742 (js2-re-search-backward-inner regexp bound 1))
9743 ((< count 0)
9744 (js2-re-search-forward-inner regexp bound (- count)))
9745 ((> count 0)
9746 (js2-re-search-backward-inner regexp bound count)))
9747 (search-failed
9748 (goto-char saved-point)
9749 (unless noerror
9750 (error (error-message-string err)))))))
9751
9752 (defun js2-looking-at-operator-p ()
9753 "Return non-nil if text after point is a non-comma operator."
9754 (and (looking-at js2-indent-operator-re)
9755 (or (not (looking-at ":"))
9756 (save-excursion
9757 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9758 (looking-at "?"))))))
9759
9760 (defun js2-continued-expression-p ()
9761 "Return non-nil if the current line continues an expression."
9762 (save-excursion
9763 (back-to-indentation)
9764 (or (js2-looking-at-operator-p)
9765 (when (catch 'found
9766 (while (and (re-search-backward "\n" nil t)
9767 (let ((state (syntax-ppss)))
9768 (when (nth 4 state)
9769 (goto-char (nth 8 state))) ;; skip comments
9770 (skip-chars-backward " \t")
9771 (if (bolp)
9772 t
9773 (throw 'found t))))))
9774 (backward-char)
9775 (when (js2-looking-at-operator-p)
9776 (backward-char)
9777 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))
9778
9779 (defun js2-end-of-do-while-loop-p ()
9780 "Return non-nil if word after point is `while' of a do-while
9781 statement, else returns nil. A braceless do-while statement
9782 spanning several lines requires that the start of the loop is
9783 indented to the same column as the current line."
9784 (interactive)
9785 (save-excursion
9786 (when (looking-at "\\s-*\\<while\\>")
9787 (if (save-excursion
9788 (skip-chars-backward "[ \t\n]*}")
9789 (looking-at "[ \t\n]*}"))
9790 (save-excursion
9791 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9792 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9793 (or (looking-at "\\<do\\>")
9794 (let ((saved-indent (current-indentation)))
9795 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9796 (/= (current-indentation) saved-indent)))
9797 (and (looking-at "[ \t]*\\<do\\>")
9798 (not (js2-re-search-forward
9799 "\\<while\\>" (point-at-eol) t))
9800 (= (current-indentation) saved-indent))))))))
9801
9802 (defun js2-multiline-decl-indentation ()
9803 "Return the declaration indentation column if the current line belongs
9804 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9805 (let (forward-sexp-function ; use Lisp version
9806 at-opening-bracket)
9807 (save-excursion
9808 (back-to-indentation)
9809 (when (not (looking-at js2-declaration-keyword-re))
9810 (when (looking-at js2-indent-operator-re)
9811 (goto-char (match-end 0))) ; continued expressions are ok
9812 (while (and (not at-opening-bracket)
9813 (not (bobp))
9814 (let ((pos (point)))
9815 (save-excursion
9816 (js2-backward-sws)
9817 (or (eq (char-before) ?,)
9818 (and (not (eq (char-before) ?\;))
9819 (prog2 (skip-syntax-backward ".")
9820 (looking-at js2-indent-operator-re)
9821 (js2-backward-sws))
9822 (not (eq (char-before) ?\;)))
9823 (js2-same-line pos)))))
9824 (condition-case _
9825 (backward-sexp)
9826 (scan-error (setq at-opening-bracket t))))
9827 (when (looking-at js2-declaration-keyword-re)
9828 (goto-char (match-end 0))
9829 (1+ (current-column)))))))
9830
9831 (defun js2-ctrl-statement-indentation ()
9832 "Return the proper indentation of current line if it is a control statement.
9833 Returns an indentation if this line starts the body of a control
9834 statement without braces, else returns nil."
9835 (let (forward-sexp-function)
9836 (save-excursion
9837 (back-to-indentation)
9838 (when (and (not (js2-same-line (point-min)))
9839 (not (looking-at "{"))
9840 (js2-re-search-backward "[[:graph:]]" nil t)
9841 (not (looking-at "[{([]"))
9842 (progn
9843 (forward-char)
9844 (when (= (char-before) ?\))
9845 ;; scan-sexps sometimes throws an error
9846 (ignore-errors (backward-sexp))
9847 (skip-chars-backward " \t" (point-at-bol)))
9848 (let ((pt (point)))
9849 (back-to-indentation)
9850 (when (looking-at "}[ \t]*")
9851 (goto-char (match-end 0)))
9852 (and (looking-at js2-possibly-braceless-keywords-re)
9853 (= (match-end 0) pt)
9854 (not (js2-end-of-do-while-loop-p))))))
9855 (+ (current-indentation) js2-basic-offset)))))
9856
9857 (defun js2-indent-in-array-comp (parse-status)
9858 "Return non-nil if we think we're in an array comprehension.
9859 In particular, return the buffer position of the first `for' kwd."
9860 (let ((bracket (nth 1 parse-status))
9861 (end (point)))
9862 (when bracket
9863 (save-excursion
9864 (goto-char bracket)
9865 (when (looking-at "\\[")
9866 (forward-char 1)
9867 (js2-forward-sws)
9868 (if (looking-at "[[{]")
9869 (let (forward-sexp-function) ; use Lisp version
9870 (forward-sexp) ; skip destructuring form
9871 (js2-forward-sws)
9872 (if (and (/= (char-after) ?,) ; regular array
9873 (looking-at "for"))
9874 (match-beginning 0)))
9875 ;; to skip arbitrary expressions we need the parser,
9876 ;; so we'll just guess at it.
9877 (if (and (> end (point)) ; not empty literal
9878 (re-search-forward "[^,]]* \\(for\\) " end t)
9879 ;; not inside comment or string literal
9880 (let ((state (parse-partial-sexp bracket (point))))
9881 (not (or (nth 3 state) (nth 4 state)))))
9882 (match-beginning 1))))))))
9883
9884 (defun js2-array-comp-indentation (parse-status for-kwd)
9885 (if (js2-same-line for-kwd)
9886 ;; first continuation line
9887 (save-excursion
9888 (goto-char (nth 1 parse-status))
9889 (forward-char 1)
9890 (skip-chars-forward " \t")
9891 (current-column))
9892 (save-excursion
9893 (goto-char for-kwd)
9894 (current-column))))
9895
9896 (defun js2-proper-indentation (parse-status)
9897 "Return the proper indentation for the current line."
9898 (save-excursion
9899 (back-to-indentation)
9900 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9901 (at-closing-bracket (looking-at "[]})]"))
9902 (same-indent-p (or at-closing-bracket
9903 (looking-at "\\<case\\>[^:]")
9904 (and (looking-at "\\<default:")
9905 (save-excursion
9906 (js2-backward-sws)
9907 (not (memq (char-before) '(?, ?{)))))))
9908 (continued-expr-p (js2-continued-expression-p))
9909 (declaration-indent (and js2-pretty-multiline-declarations
9910 (js2-multiline-decl-indentation)))
9911 (bracket (nth 1 parse-status))
9912 beg indent)
9913 (cond
9914 ;; indent array comprehension continuation lines specially
9915 ((and bracket
9916 (>= js2-language-version 170)
9917 (not (js2-same-line bracket))
9918 (setq beg (js2-indent-in-array-comp parse-status))
9919 (>= (point) (save-excursion
9920 (goto-char beg)
9921 (point-at-bol)))) ; at or after first loop?
9922 (js2-array-comp-indentation parse-status beg))
9923
9924 (ctrl-stmt-indent)
9925
9926 ((and declaration-indent continued-expr-p)
9927 (+ declaration-indent js2-basic-offset))
9928
9929 (declaration-indent)
9930
9931 (bracket
9932 (goto-char bracket)
9933 (cond
9934 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9935 (when (save-excursion (skip-chars-backward " \t)")
9936 (looking-at ")"))
9937 (backward-list))
9938 (back-to-indentation)
9939 (and (eq js2-pretty-multiline-declarations 'all)
9940 (looking-at js2-declaration-keyword-re)
9941 (goto-char (1+ (match-end 0))))
9942 (setq indent
9943 (cond (same-indent-p
9944 (current-column))
9945 (continued-expr-p
9946 (+ (current-column) (* 2 js2-basic-offset)))
9947 (t
9948 (+ (current-column) js2-basic-offset))))
9949 (if (and js2-indent-switch-body
9950 (not at-closing-bracket)
9951 (looking-at "\\_<switch\\_>"))
9952 (+ indent js2-basic-offset)
9953 indent))
9954 (t
9955 (unless same-indent-p
9956 (forward-char)
9957 (skip-chars-forward " \t"))
9958 (current-column))))
9959
9960 (continued-expr-p js2-basic-offset)
9961
9962 (t 0)))))
9963
9964 (defun js2-lineup-comment (parse-status)
9965 "Indent a multi-line block comment continuation line."
9966 (let* ((beg (nth 8 parse-status))
9967 (first-line (js2-same-line beg))
9968 (offset (save-excursion
9969 (goto-char beg)
9970 (if (looking-at "/\\*")
9971 (+ 1 (current-column))
9972 0))))
9973 (unless first-line
9974 (indent-line-to offset))))
9975
9976 (defun js2-backward-sws ()
9977 "Move backward through whitespace and comments."
9978 (interactive)
9979 (while (forward-comment -1)))
9980
9981 (defun js2-forward-sws ()
9982 "Move forward through whitespace and comments."
9983 (interactive)
9984 (while (forward-comment 1)))
9985
9986 (defun js2-current-indent (&optional pos)
9987 "Return column of indentation on current line.
9988 If POS is non-nil, go to that point and return indentation for that line."
9989 (save-excursion
9990 (if pos
9991 (goto-char pos))
9992 (back-to-indentation)
9993 (current-column)))
9994
9995 (defun js2-arglist-close ()
9996 "Return non-nil if we're on a line beginning with a close-paren/brace."
9997 (save-excursion
9998 (goto-char (point-at-bol))
9999 (js2-forward-sws)
10000 (looking-at "[])}]")))
10001
10002 (defun js2-indent-looks-like-label-p ()
10003 (goto-char (point-at-bol))
10004 (js2-forward-sws)
10005 (looking-at (concat js2-mode-identifier-re ":")))
10006
10007 (defun js2-indent-in-objlit-p (parse-status)
10008 "Return non-nil if this looks like an object-literal entry."
10009 (let ((start (nth 1 parse-status)))
10010 (and
10011 start
10012 (save-excursion
10013 (and (zerop (forward-line -1))
10014 (not (< (point) start)) ; crossed a {} boundary
10015 (js2-indent-looks-like-label-p)))
10016 (save-excursion
10017 (js2-indent-looks-like-label-p)))))
10018
10019 ;; If prev line looks like foobar({ then we're passing an object
10020 ;; literal to a function call, and people pretty much always want to
10021 ;; de-dent back to the previous line, so move the 'basic-offset'
10022 ;; position to the front.
10023 (defun js2-indent-objlit-arg-p (parse-status)
10024 (save-excursion
10025 (back-to-indentation)
10026 (js2-backward-sws)
10027 (and (eq (1- (point)) (nth 1 parse-status))
10028 (eq (char-before) ?{)
10029 (progn
10030 (forward-char -1)
10031 (skip-chars-backward " \t")
10032 (eq (char-before) ?\()))))
10033
10034 (defun js2-indent-case-block-p ()
10035 (save-excursion
10036 (back-to-indentation)
10037 (js2-backward-sws)
10038 (goto-char (point-at-bol))
10039 (skip-chars-forward " \t")
10040 (looking-at "case\\s-.+:")))
10041
10042 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10043 "Cycle among alternate computed indentation positions.
10044 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10045 of the buffer to the current point. NORMAL-COL is the indentation
10046 column computed by the heuristic guesser based on current paren,
10047 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10048 in reverse."
10049 (let ((cur-indent (js2-current-indent))
10050 (old-buffer-undo-list buffer-undo-list)
10051 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10052 (current-line (save-excursion
10053 (forward-line 0) ; move to bol
10054 (1+ (count-lines (point-min) (point)))))
10055 positions pos main-pos anchor arglist-cont same-indent
10056 basic-offset computed-pos)
10057 ;; temporarily don't record undo info, if user requested this
10058 (when js2-mode-indent-inhibit-undo
10059 (setq buffer-undo-list t))
10060 (unwind-protect
10061 (progn
10062 ;; First likely point: indent from beginning of previous code line
10063 (push (setq basic-offset
10064 (+ (save-excursion
10065 (back-to-indentation)
10066 (js2-backward-sws)
10067 (back-to-indentation)
10068 (current-column))
10069 js2-basic-offset))
10070 positions)
10071
10072 ;; (First + epsilon) likely point: indent 2x from beginning of
10073 ;; previous code line. Google does it this way.
10074 (push (setq basic-offset
10075 (+ (save-excursion
10076 (back-to-indentation)
10077 (js2-backward-sws)
10078 (back-to-indentation)
10079 (current-column))
10080 (* 2 js2-basic-offset)))
10081 positions)
10082
10083 ;; Second likely point: indent from assign-expr RHS. This
10084 ;; is just a crude guess based on finding " = " on the previous
10085 ;; line containing actual code.
10086 (setq pos (save-excursion
10087 (forward-line -1)
10088 (goto-char (point-at-bol))
10089 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10090 (point-at-eol) t)
10091 (goto-char (match-end 1))
10092 (skip-chars-forward " \t\r\n")
10093 (current-column))))
10094 (when pos
10095 (incf pos js2-basic-offset)
10096 (push pos positions))
10097
10098 ;; Third likely point: same indent as previous line of code.
10099 ;; Make it the first likely point if we're not on an
10100 ;; arglist-close line and previous line ends in a comma, or
10101 ;; both this line and prev line look like object-literal
10102 ;; elements.
10103 (setq pos (save-excursion
10104 (goto-char (point-at-bol))
10105 (js2-backward-sws)
10106 (back-to-indentation)
10107 (prog1
10108 (current-column)
10109 ;; while we're here, look for trailing comma
10110 (if (save-excursion
10111 (goto-char (point-at-eol))
10112 (js2-backward-sws)
10113 (eq (char-before) ?,))
10114 (setq arglist-cont (1- (point)))))))
10115 (when pos
10116 (if (and (or arglist-cont
10117 (js2-indent-in-objlit-p parse-status))
10118 (not (js2-arglist-close)))
10119 (setq same-indent pos))
10120 (push pos positions))
10121
10122 ;; Fourth likely point: first preceding code with less indentation.
10123 ;; than the immediately preceding code line.
10124 (setq pos (save-excursion
10125 (back-to-indentation)
10126 (js2-backward-sws)
10127 (back-to-indentation)
10128 (setq anchor (current-column))
10129 (while (and (zerop (forward-line -1))
10130 (>= (progn
10131 (back-to-indentation)
10132 (current-column))
10133 anchor)))
10134 (setq pos (current-column))))
10135 (push pos positions)
10136
10137 ;; nesting-heuristic position, main by default
10138 (push (setq main-pos normal-col) positions)
10139
10140 ;; delete duplicates and sort positions list
10141 (setq positions (sort (delete-dups positions) '<))
10142
10143 ;; comma-list continuation lines: prev line indent takes precedence
10144 (if same-indent
10145 (setq main-pos same-indent))
10146
10147 ;; common special cases where we want to indent in from previous line
10148 (if (or (js2-indent-case-block-p)
10149 (js2-indent-objlit-arg-p parse-status))
10150 (setq main-pos basic-offset))
10151
10152 ;; if bouncing backwards, reverse positions list
10153 (if backwards
10154 (setq positions (reverse positions)))
10155
10156 ;; record whether we're already sitting on one of the alternatives
10157 (setq pos (member cur-indent positions))
10158
10159 (cond
10160 ;; case 0: we're one one of the alternatives and this is the
10161 ;; first time they've pressed TAB on this line (best-guess).
10162 ((and js2-mode-indent-ignore-first-tab
10163 pos
10164 ;; first time pressing TAB on this line?
10165 (not (eq js2-mode-last-indented-line current-line)))
10166 ;; do nothing
10167 (setq computed-pos nil))
10168 ;; case 1: only one computed position => use it
10169 ((null (cdr positions))
10170 (setq computed-pos 0))
10171 ;; case 2: not on any of the computed spots => use main spot
10172 ((not pos)
10173 (setq computed-pos (js2-position main-pos positions)))
10174 ;; case 3: on last position: cycle to first position
10175 ((null (cdr pos))
10176 (setq computed-pos 0))
10177 ;; case 4: on intermediate position: cycle to next position
10178 (t
10179 (setq computed-pos (js2-position (second pos) positions))))
10180
10181 ;; see if any hooks want to indent; otherwise we do it
10182 (loop with result = nil
10183 for hook in js2-indent-hook
10184 while (null result)
10185 do
10186 (setq result (funcall hook positions computed-pos))
10187 finally do
10188 (unless (or result (null computed-pos))
10189 (indent-line-to (nth computed-pos positions)))))
10190
10191 ;; finally
10192 (if js2-mode-indent-inhibit-undo
10193 (setq buffer-undo-list old-buffer-undo-list))
10194 ;; see commentary for `js2-mode-last-indented-line'
10195 (setq js2-mode-last-indented-line current-line))))
10196
10197 (defun js2-indent-bounce-backwards ()
10198 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10199 cycles between the computed indentation positions in reverse order."
10200 (interactive)
10201 (js2-indent-line t))
10202
10203 (defun js2-1-line-comment-continuation-p ()
10204 "Return t if we're in a 1-line comment continuation.
10205 If so, we don't ever want to use bounce-indent."
10206 (save-excursion
10207 (and (progn
10208 (forward-line 0)
10209 (looking-at "\\s-*//"))
10210 (progn
10211 (forward-line -1)
10212 (forward-line 0)
10213 (when (looking-at "\\s-*$")
10214 (js2-backward-sws)
10215 (forward-line 0))
10216 (looking-at "\\s-*//")))))
10217
10218 (defun js2-indent-line (&optional bounce-backwards)
10219 "Indent the current line as JavaScript source text."
10220 (interactive)
10221 (let (parse-status offset indent-col
10222 ;; Don't whine about errors/warnings when we're indenting.
10223 ;; This has to be set before calling parse-partial-sexp below.
10224 (inhibit-point-motion-hooks t))
10225 (setq parse-status (save-excursion
10226 (syntax-ppss (point-at-bol)))
10227 offset (- (point) (save-excursion
10228 (back-to-indentation)
10229 (point))))
10230 (js2-with-underscore-as-word-syntax
10231 (if (nth 4 parse-status)
10232 (js2-lineup-comment parse-status)
10233 (setq indent-col (js2-proper-indentation parse-status))
10234 ;; See comments below about `js2-mode-last-indented-line'.
10235 (cond
10236 ;; bounce-indenting is disabled during electric-key indent.
10237 ;; It doesn't work well on first line of buffer.
10238 ((and js2-bounce-indent-p
10239 (not (js2-same-line (point-min)))
10240 (not (js2-1-line-comment-continuation-p)))
10241 (js2-bounce-indent indent-col parse-status bounce-backwards))
10242 ;; just indent to the guesser's likely spot
10243 (t (indent-line-to indent-col))))
10244 (when (plusp offset)
10245 (forward-char offset)))))
10246
10247 (defun js2-indent-region (start end)
10248 "Indent the region, but don't use bounce indenting."
10249 (let ((js2-bounce-indent-p nil)
10250 (indent-region-function nil)
10251 (after-change-functions (remq 'js2-mode-edit
10252 after-change-functions)))
10253 (indent-region start end nil) ; nil for byte-compiler
10254 (js2-mode-edit start end (- end start))))
10255
10256 (defvar js2-minor-mode-map
10257 (let ((map (make-sparse-keymap)))
10258 (define-key map (kbd "C-c C-`") #'js2-next-error)
10259 (define-key map [mouse-1] #'js2-mode-show-node)
10260 map)
10261 "Keymap used when `js2-minor-mode' is active.")
10262
10263 ;;;###autoload
10264 (define-minor-mode js2-minor-mode
10265 "Minor mode for running js2 as a background linter.
10266 This allows you to use a different major mode for JavaScript editing,
10267 such as `js-mode', while retaining the asynchronous error/warning
10268 highlighting features of `js2-mode'."
10269 :group 'js2-mode
10270 :lighter " js-lint"
10271 (if js2-minor-mode
10272 (js2-minor-mode-enter)
10273 (js2-minor-mode-exit)))
10274
10275 (defun js2-minor-mode-enter ()
10276 "Initialization for `js2-minor-mode'."
10277 (set (make-local-variable 'max-lisp-eval-depth)
10278 (max max-lisp-eval-depth 3000))
10279 (setq next-error-function #'js2-next-error)
10280 (js2-set-default-externs)
10281 ;; Experiment: make reparse-delay longer for longer files.
10282 (if (plusp js2-dynamic-idle-timer-adjust)
10283 (setq js2-idle-timer-delay
10284 (* js2-idle-timer-delay
10285 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10286 (setq js2-mode-buffer-dirty-p t
10287 js2-mode-parsing nil)
10288 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10289 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10290 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10291 (when js2-include-jslint-globals
10292 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10293 (run-hooks 'js2-init-hook)
10294 (js2-reparse))
10295
10296 (defun js2-minor-mode-exit ()
10297 "Turn off `js2-minor-mode'."
10298 (setq next-error-function nil)
10299 (remove-hook 'after-change-functions #'js2-mode-edit t)
10300 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10301 (when js2-mode-node-overlay
10302 (delete-overlay js2-mode-node-overlay)
10303 (setq js2-mode-node-overlay nil))
10304 (js2-remove-overlays)
10305 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
10306 (setq js2-mode-ast nil))
10307
10308 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10309 (make-variable-buffer-local 'js2-source-buffer)
10310
10311 (defun* js2-display-error-list ()
10312 "Display a navigable buffer listing parse errors/warnings."
10313 (interactive)
10314 (unless (js2-have-errors-p)
10315 (message "No errors")
10316 (return-from js2-display-error-list))
10317 (labels ((annotate-list
10318 (lst type)
10319 "Add diagnostic TYPE and line number to errs list"
10320 (mapcar (lambda (err)
10321 (list err type (line-number-at-pos (nth 1 err))))
10322 lst)))
10323 (let* ((srcbuf (current-buffer))
10324 (errbuf (get-buffer-create "*js-lint*"))
10325 (errors (annotate-list
10326 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10327 'js2-error)) ; must be a valid face name
10328 (warnings (annotate-list
10329 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10330 'js2-warning)) ; must be a valid face name
10331 (all-errs (sort (append errors warnings)
10332 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10333 (with-current-buffer errbuf
10334 (let ((inhibit-read-only t))
10335 (erase-buffer)
10336 (dolist (err all-errs)
10337 (destructuring-bind ((msg-key beg _end &rest) type line) err
10338 (insert-text-button
10339 (format "line %d: %s" line (js2-get-msg msg-key))
10340 'face type
10341 'follow-link "\C-m"
10342 'action 'js2-error-buffer-jump
10343 'js2-msg (js2-get-msg msg-key)
10344 'js2-pos beg)
10345 (insert "\n"))))
10346 (js2-error-buffer-mode)
10347 (setq js2-source-buffer srcbuf)
10348 (pop-to-buffer errbuf)
10349 (goto-char (point-min))
10350 (unless (eobp)
10351 (js2-error-buffer-view))))))
10352
10353 (defvar js2-error-buffer-mode-map
10354 (let ((map (make-sparse-keymap)))
10355 (define-key map "n" #'js2-error-buffer-next)
10356 (define-key map "p" #'js2-error-buffer-prev)
10357 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10358 (define-key map "o" #'js2-error-buffer-view)
10359 (define-key map "q" #'js2-error-buffer-quit)
10360 map)
10361 "Keymap used for js2 diagnostics buffers.")
10362
10363 (defun js2-error-buffer-mode ()
10364 "Major mode for js2 diagnostics buffers.
10365 Selecting an error will jump it to the corresponding source-buffer error.
10366 \\{js2-error-buffer-mode-map}"
10367 (interactive)
10368 (setq major-mode 'js2-error-buffer-mode
10369 mode-name "JS Lint Diagnostics")
10370 (use-local-map js2-error-buffer-mode-map)
10371 (setq truncate-lines t)
10372 (set-buffer-modified-p nil)
10373 (setq buffer-read-only t)
10374 (run-hooks 'js2-error-buffer-mode-hook))
10375
10376 (defun js2-error-buffer-next ()
10377 "Move to next error and view it."
10378 (interactive)
10379 (when (zerop (forward-line 1))
10380 (js2-error-buffer-view)))
10381
10382 (defun js2-error-buffer-prev ()
10383 "Move to previous error and view it."
10384 (interactive)
10385 (when (zerop (forward-line -1))
10386 (js2-error-buffer-view)))
10387
10388 (defun js2-error-buffer-quit ()
10389 "Kill the current buffer."
10390 (interactive)
10391 (kill-buffer))
10392
10393 (defun js2-error-buffer-jump (&rest ignored)
10394 "Jump cursor to current error in source buffer."
10395 (interactive)
10396 (when (js2-error-buffer-view)
10397 (pop-to-buffer js2-source-buffer)))
10398
10399 (defun js2-error-buffer-view ()
10400 "Scroll source buffer to show error at current line."
10401 (interactive)
10402 (cond
10403 ((not (eq major-mode 'js2-error-buffer-mode))
10404 (message "Not in a js2 errors buffer"))
10405 ((not (buffer-live-p js2-source-buffer))
10406 (message "Source buffer has been killed"))
10407 ((not (wholenump (get-text-property (point) 'js2-pos)))
10408 (message "There does not seem to be an error here"))
10409 (t
10410 (let ((pos (get-text-property (point) 'js2-pos))
10411 (msg (get-text-property (point) 'js2-msg)))
10412 (save-selected-window
10413 (pop-to-buffer js2-source-buffer)
10414 (goto-char pos)
10415 (message msg))))))
10416
10417 ;;;###autoload
10418 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10419 ;; FIXME: Should derive from js-mode.
10420 "Major mode for editing JavaScript code."
10421 ;; Used by comment-region; don't change it.
10422 (set (make-local-variable 'comment-start) "//")
10423 (set (make-local-variable 'comment-end) "")
10424 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
10425 (set (make-local-variable 'max-lisp-eval-depth)
10426 (max max-lisp-eval-depth 3000))
10427 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10428 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10429 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10430 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10431 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10432 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10433 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10434 ;; for characters inside regexp literals.
10435 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10436 ;; this is necessary to make `show-paren-function' work properly
10437 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10438 ;; needed for M-x rgrep, among other things
10439 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10440
10441 (set (make-local-variable 'electric-indent-chars)
10442 (append "{}()[]:;,*." electric-indent-chars))
10443 (set (make-local-variable 'electric-layout-rules)
10444 '((?\; . after) (?\{ . after) (?\} . before)))
10445
10446 ;; some variables needed by cc-engine for paragraph-fill, etc.
10447 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10448 c-comment-start-regexp "/[*/]\\|\\s|"
10449 c-line-comment-starter "//"
10450 c-paragraph-start js2-paragraph-start
10451 c-paragraph-separate "$"
10452 c-syntactic-ws-start js2-syntactic-ws-start
10453 c-syntactic-ws-end js2-syntactic-ws-end
10454 c-syntactic-eol js2-syntactic-eol)
10455
10456 (let ((c-buffer-is-cc-mode t))
10457 ;; Copied from `js-mode'. Also see Bug#6071.
10458 (make-local-variable 'paragraph-start)
10459 (make-local-variable 'paragraph-separate)
10460 (make-local-variable 'paragraph-ignore-fill-prefix)
10461 (make-local-variable 'adaptive-fill-mode)
10462 (make-local-variable 'adaptive-fill-regexp)
10463 (c-setup-paragraph-variables))
10464
10465 (setq font-lock-defaults '(nil t))
10466
10467 ;; Experiment: make reparse-delay longer for longer files.
10468 (when (plusp js2-dynamic-idle-timer-adjust)
10469 (setq js2-idle-timer-delay
10470 (* js2-idle-timer-delay
10471 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10472
10473 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10474 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10475 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10476 (setq next-error-function #'js2-next-error)
10477 (imenu-add-to-menubar (concat "IM-" mode-name))
10478 (add-to-invisibility-spec '(js2-outline . t))
10479 (set (make-local-variable 'line-move-ignore-invisible) t)
10480 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10481
10482 (setq js2-mode-functions-hidden nil
10483 js2-mode-comments-hidden nil
10484 js2-mode-buffer-dirty-p t
10485 js2-mode-parsing nil)
10486
10487 (js2-set-default-externs)
10488
10489 (when js2-include-jslint-globals
10490 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10491
10492 (run-hooks 'js2-init-hook)
10493
10494 (js2-reparse))
10495
10496 (defun js2-mode-exit ()
10497 "Exit `js2-mode' and clean up."
10498 (interactive)
10499 (when js2-mode-node-overlay
10500 (delete-overlay js2-mode-node-overlay)
10501 (setq js2-mode-node-overlay nil))
10502 (js2-remove-overlays)
10503 (setq js2-mode-ast nil)
10504 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10505 (remove-from-invisibility-spec '(js2-outline . t))
10506 (js2-mode-show-all)
10507 (with-silent-modifications
10508 (js2-clear-face (point-min) (point-max))))
10509
10510 (defun js2-mode-reset-timer ()
10511 "Cancel any existing parse timer and schedule a new one."
10512 (if js2-mode-parse-timer
10513 (cancel-timer js2-mode-parse-timer))
10514 (setq js2-mode-parsing nil)
10515 (let ((timer (timer-create)))
10516 (setq js2-mode-parse-timer timer)
10517 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10518 (timer-set-idle-time timer js2-idle-timer-delay)
10519 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10520 (timer-activate-when-idle timer nil)))
10521
10522 (defun js2-mode-idle-reparse (buffer)
10523 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10524 it to be reparsed when the buffer is selected."
10525 (cond ((eq buffer (current-buffer))
10526 (js2-reparse))
10527 ((buffer-live-p buffer)
10528 ;; reparse when the buffer is selected again
10529 (with-current-buffer buffer
10530 (add-hook 'window-configuration-change-hook
10531 #'js2-mode-idle-reparse-inner
10532 nil t)))))
10533
10534 (defun js2-mode-idle-reparse-inner ()
10535 (remove-hook 'window-configuration-change-hook
10536 #'js2-mode-idle-reparse-inner
10537 t)
10538 (js2-reparse))
10539
10540 (defun js2-mode-edit (_beg _end _len)
10541 "Schedule a new parse after buffer is edited.
10542 Buffer edit spans from BEG to END and is of length LEN."
10543 (setq js2-mode-buffer-dirty-p t)
10544 (js2-mode-hide-overlay)
10545 (js2-mode-reset-timer))
10546
10547 (defun js2-minor-mode-edit (_beg _end _len)
10548 "Callback for buffer edits in `js2-mode'.
10549 Schedules a new parse after buffer is edited.
10550 Buffer edit spans from BEG to END and is of length LEN."
10551 (setq js2-mode-buffer-dirty-p t)
10552 (js2-mode-hide-overlay)
10553 (js2-mode-reset-timer))
10554
10555 (defun js2-reparse (&optional force)
10556 "Re-parse current buffer after user finishes some data entry.
10557 If we get any user input while parsing, including cursor motion,
10558 we discard the parse and reschedule it. If FORCE is nil, then the
10559 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10560 (let (time
10561 interrupted-p
10562 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10563 (unless js2-mode-parsing
10564 (setq js2-mode-parsing t)
10565 (unwind-protect
10566 (when (or js2-mode-buffer-dirty-p force)
10567 (js2-remove-overlays)
10568 (with-silent-modifications
10569 (setq js2-mode-buffer-dirty-p nil
10570 js2-mode-fontifications nil
10571 js2-mode-deferred-properties nil)
10572 (if js2-mode-verbose-parse-p
10573 (message "parsing..."))
10574 (setq time
10575 (js2-time
10576 (setq interrupted-p
10577 (catch 'interrupted
10578 (js2-parse)
10579 ;; if parsing is interrupted, comments and regex
10580 ;; literals stay ignored by `parse-partial-sexp'
10581 (remove-text-properties (point-min) (point-max)
10582 '(syntax-table))
10583 (js2-mode-apply-deferred-properties)
10584 (js2-mode-remove-suppressed-warnings)
10585 (js2-mode-show-warnings)
10586 (js2-mode-show-errors)
10587 (if (>= js2-highlight-level 1)
10588 (js2-highlight-jsdoc js2-mode-ast))
10589 nil))))
10590 (if interrupted-p
10591 (progn
10592 ;; unfinished parse => try again
10593 (setq js2-mode-buffer-dirty-p t)
10594 (js2-mode-reset-timer))
10595 (if js2-mode-verbose-parse-p
10596 (message "Parse time: %s" time)))))
10597 (setq js2-mode-parsing nil)
10598 (unless interrupted-p
10599 (setq js2-mode-parse-timer nil))))))
10600
10601 (defun js2-mode-show-node (event)
10602 "Debugging aid: highlight selected AST node on mouse click."
10603 (interactive "e")
10604 (mouse-set-point event)
10605 (setq deactivate-mark t)
10606 (when js2-mode-show-overlay
10607 (let ((node (js2-node-at-point))
10608 beg end)
10609 (if (null node)
10610 (message "No node found at location %s" (point))
10611 (setq beg (js2-node-abs-pos node)
10612 end (+ beg (js2-node-len node)))
10613 (if js2-mode-node-overlay
10614 (move-overlay js2-mode-node-overlay beg end)
10615 (setq js2-mode-node-overlay (make-overlay beg end))
10616 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10617 (with-silent-modifications
10618 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10619 (message "%s, parent: %s"
10620 (js2-node-short-name node)
10621 (if (js2-node-parent node)
10622 (js2-node-short-name (js2-node-parent node))
10623 "nil"))))))
10624
10625 (defun js2-mode-hide-overlay (&optional _p1 p2)
10626 "Remove the debugging overlay when the point moves.
10627 P1 and P2 are the old and new values of point, respectively."
10628 (when js2-mode-node-overlay
10629 (let ((beg (overlay-start js2-mode-node-overlay))
10630 (end (overlay-end js2-mode-node-overlay)))
10631 ;; Sometimes we're called spuriously.
10632 (unless (and p2
10633 (>= p2 beg)
10634 (<= p2 end))
10635 (with-silent-modifications
10636 (remove-text-properties beg end '(point-left nil)))
10637 (delete-overlay js2-mode-node-overlay)
10638 (setq js2-mode-node-overlay nil)))))
10639
10640 (defun js2-mode-reset ()
10641 "Debugging helper: reset everything."
10642 (interactive)
10643 (js2-mode-exit)
10644 (js2-mode))
10645
10646 (defun js2-mode-show-warn-or-err (e face)
10647 "Highlight a warning or error E with FACE.
10648 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10649 The last element is optional. When present, use instead of FACE."
10650 (let* ((key (first e))
10651 (beg (second e))
10652 (end (+ beg (third e)))
10653 ;; Don't inadvertently go out of bounds.
10654 (beg (max (point-min) (min beg (point-max))))
10655 (end (max (point-min) (min end (point-max))))
10656 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10657 (ovl (make-overlay beg end)))
10658 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10659 (overlay-put ovl 'js2-error t)
10660 (put-text-property beg end 'help-echo (js2-get-msg key))
10661 (put-text-property beg end 'point-entered #'js2-echo-error)))
10662
10663 (defun js2-remove-overlays ()
10664 "Remove overlays from buffer that have a `js2-error' property."
10665 (let ((beg (point-min))
10666 (end (point-max)))
10667 (save-excursion
10668 (dolist (o (overlays-in beg end))
10669 (when (overlay-get o 'js2-error)
10670 (delete-overlay o))))))
10671
10672 (defun js2-error-at-point (&optional pos)
10673 "Return non-nil if there's an error overlay at POS.
10674 Defaults to point."
10675 (loop with pos = (or pos (point))
10676 for o in (overlays-at pos)
10677 thereis (overlay-get o 'js2-error)))
10678
10679 (defun js2-mode-apply-deferred-properties ()
10680 "Apply fontifications and other text properties recorded during parsing."
10681 (when (plusp js2-highlight-level)
10682 ;; We defer clearing faces as long as possible to eliminate flashing.
10683 (js2-clear-face (point-min) (point-max))
10684 ;; Have to reverse the recorded fontifications list so that errors
10685 ;; and warnings overwrite the normal fontifications.
10686 (dolist (f (nreverse js2-mode-fontifications))
10687 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10688 (setq js2-mode-fontifications nil))
10689 (dolist (p js2-mode-deferred-properties)
10690 (apply #'put-text-property p))
10691 (setq js2-mode-deferred-properties nil))
10692
10693 (defun js2-mode-show-errors ()
10694 "Highlight syntax errors."
10695 (when js2-mode-show-parse-errors
10696 (dolist (e (js2-ast-root-errors js2-mode-ast))
10697 (js2-mode-show-warn-or-err e 'js2-error))))
10698
10699 (defun js2-mode-remove-suppressed-warnings ()
10700 "Take suppressed warnings out of the AST warnings list.
10701 This ensures that the counts and `next-error' are correct."
10702 (setf (js2-ast-root-warnings js2-mode-ast)
10703 (js2-delete-if
10704 (lambda (e)
10705 (let ((key (caar e)))
10706 (or
10707 (and (not js2-strict-trailing-comma-warning)
10708 (string-match "trailing\\.comma" key))
10709 (and (not js2-strict-cond-assign-warning)
10710 (string= key "msg.equal.as.assign"))
10711 (and js2-missing-semi-one-line-override
10712 (string= key "msg.missing.semi")
10713 (let* ((beg (second e))
10714 (node (js2-node-at-point beg))
10715 (fn (js2-mode-find-parent-fn node))
10716 (body (and fn (js2-function-node-body fn)))
10717 (lc (and body (js2-node-abs-pos body)))
10718 (rc (and lc (+ lc (js2-node-len body)))))
10719 (and fn
10720 (or (null body)
10721 (save-excursion
10722 (goto-char beg)
10723 (and (js2-same-line lc)
10724 (js2-same-line rc))))))))))
10725 (js2-ast-root-warnings js2-mode-ast))))
10726
10727 (defun js2-mode-show-warnings ()
10728 "Highlight strict-mode warnings."
10729 (when js2-mode-show-strict-warnings
10730 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10731 (js2-mode-show-warn-or-err e 'js2-warning))))
10732
10733 (defun js2-echo-error (_old-point new-point)
10734 "Called by point-motion hooks."
10735 (let ((msg (get-text-property new-point 'help-echo)))
10736 (when (and (stringp msg)
10737 (not (active-minibuffer-window))
10738 (not (current-message)))
10739 (message msg))))
10740
10741 (defalias 'js2-echo-help #'js2-echo-error)
10742
10743 (defun js2-line-break (&optional _soft)
10744 "Break line at point and indent, continuing comment if within one.
10745 If inside a string, and `js2-concat-multiline-strings' is not
10746 nil, turn it into concatenation."
10747 (interactive)
10748 (let ((parse-status (syntax-ppss)))
10749 (cond
10750 ;; Check if we're inside a string.
10751 ((nth 3 parse-status)
10752 (if js2-concat-multiline-strings
10753 (js2-mode-split-string parse-status)
10754 (insert "\n")))
10755 ;; Check if inside a block comment.
10756 ((nth 4 parse-status)
10757 (js2-mode-extend-comment (nth 8 parse-status)))
10758 (t
10759 (newline-and-indent)))))
10760
10761 (defun js2-mode-split-string (parse-status)
10762 "Turn a newline in mid-string into a string concatenation.
10763 PARSE-STATUS is as documented in `parse-partial-sexp'."
10764 (let* ((quote-char (nth 3 parse-status))
10765 (at-eol (eq js2-concat-multiline-strings 'eol)))
10766 (insert quote-char)
10767 (insert (if at-eol " +\n" "\n"))
10768 (unless at-eol
10769 (insert "+ "))
10770 (js2-indent-line)
10771 (insert quote-char)
10772 (when (eolp)
10773 (insert quote-char)
10774 (backward-char 1))))
10775
10776 (defun js2-mode-extend-comment (start-pos)
10777 "Indent the line and, when inside a comment block, add comment prefix."
10778 (let (star single col first-line needs-close)
10779 (save-excursion
10780 (back-to-indentation)
10781 (when (< (point) start-pos)
10782 (goto-char start-pos))
10783 (cond
10784 ((looking-at "\\*[^/]")
10785 (setq star t
10786 col (current-column)))
10787 ((looking-at "/\\*")
10788 (setq star t
10789 first-line t
10790 col (1+ (current-column))))
10791 ((looking-at "//")
10792 (setq single t
10793 col (current-column)))))
10794 ;; Heuristic for whether we need to close the comment:
10795 ;; if we've got a parse error here, assume it's an unterminated
10796 ;; comment.
10797 (setq needs-close
10798 (or
10799 (eq (get-text-property (1- (point)) 'point-entered)
10800 'js2-echo-error)
10801 ;; The heuristic above doesn't work well when we're
10802 ;; creating a comment and there's another one downstream,
10803 ;; as our parser thinks this one ends at the end of the
10804 ;; next one. (You can have a /* inside a js block comment.)
10805 ;; So just close it if the next non-ws char isn't a *.
10806 (and first-line
10807 (eolp)
10808 (save-excursion
10809 (skip-chars-forward " \t\r\n")
10810 (not (eq (char-after) ?*))))))
10811 (delete-horizontal-space)
10812 (insert "\n")
10813 (cond
10814 (star
10815 (indent-to col)
10816 (insert "* ")
10817 (if (and first-line needs-close)
10818 (save-excursion
10819 (insert "\n")
10820 (indent-to col)
10821 (insert "*/"))))
10822 ((and single
10823 (save-excursion
10824 (and (zerop (forward-line 1))
10825 (looking-at "\\s-*//"))))
10826 (indent-to col)
10827 (insert "// ")))
10828 ;; Don't need to extend the comment after all.
10829 (js2-indent-line)))
10830
10831 (defun js2-beginning-of-line ()
10832 "Toggle point between bol and first non-whitespace char in line.
10833 Also moves past comment delimiters when inside comments."
10834 (interactive)
10835 (let (node)
10836 (cond
10837 ((bolp)
10838 (back-to-indentation))
10839 ((looking-at "//")
10840 (skip-chars-forward "/ \t"))
10841 ((and (eq (char-after) ?*)
10842 (setq node (js2-comment-at-point))
10843 (memq (js2-comment-node-format node) '(jsdoc block))
10844 (save-excursion
10845 (skip-chars-backward " \t")
10846 (bolp)))
10847 (skip-chars-forward "\* \t"))
10848 (t
10849 (goto-char (point-at-bol))))))
10850
10851 (defun js2-end-of-line ()
10852 "Toggle point between eol and last non-whitespace char in line."
10853 (interactive)
10854 (if (eolp)
10855 (skip-chars-backward " \t")
10856 (goto-char (point-at-eol))))
10857
10858 (defun js2-mode-wait-for-parse (callback)
10859 "Invoke CALLBACK when parsing is finished.
10860 If parsing is already finished, calls CALLBACK immediately."
10861 (if (not js2-mode-buffer-dirty-p)
10862 (funcall callback)
10863 (push callback js2-mode-pending-parse-callbacks)
10864 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10865
10866 (defun js2-mode-parse-finished ()
10867 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10868 ;; We can't let errors propagate up, since it prevents the
10869 ;; `js2-parse' method from completing normally and returning
10870 ;; the ast, which makes things mysteriously not work right.
10871 (unwind-protect
10872 (dolist (cb js2-mode-pending-parse-callbacks)
10873 (condition-case err
10874 (funcall cb)
10875 (error (message "%s" err))))
10876 (setq js2-mode-pending-parse-callbacks nil)))
10877
10878 (defun js2-mode-flag-region (from to flag)
10879 "Hide or show text from FROM to TO, according to FLAG.
10880 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10881 Returns the created overlay if FLAG is non-nil."
10882 (remove-overlays from to 'invisible 'js2-outline)
10883 (when flag
10884 (let ((o (make-overlay from to)))
10885 (overlay-put o 'invisible 'js2-outline)
10886 (overlay-put o 'isearch-open-invisible
10887 'js2-isearch-open-invisible)
10888 o)))
10889
10890 ;; Function to be set as an outline-isearch-open-invisible' property
10891 ;; to the overlay that makes the outline invisible (see
10892 ;; `js2-mode-flag-region').
10893 (defun js2-isearch-open-invisible (_overlay)
10894 ;; We rely on the fact that isearch places point on the matched text.
10895 (js2-mode-show-element))
10896
10897 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10898 "Return cons cell of bounds of folding overlay at POS.
10899 Returns nil if not found."
10900 (let ((overlays (overlays-at (or pos (point))))
10901 o)
10902 (while (and overlays
10903 (not o))
10904 (if (overlay-get (car overlays) 'invisible)
10905 (setq o (car overlays))
10906 (setq overlays (cdr overlays))))
10907 (if o
10908 (cons (overlay-start o) (overlay-end o)))))
10909
10910 (defun js2-mode-function-at-point (&optional pos)
10911 "Return the innermost function node enclosing current point.
10912 Returns nil if point is not in a function."
10913 (let ((node (js2-node-at-point pos)))
10914 (while (and node (not (js2-function-node-p node)))
10915 (setq node (js2-node-parent node)))
10916 (if (js2-function-node-p node)
10917 node)))
10918
10919 (defun js2-mode-toggle-element ()
10920 "Hide or show the foldable element at the point."
10921 (interactive)
10922 (let (comment fn pos)
10923 (save-excursion
10924 (cond
10925 ;; /* ... */ comment?
10926 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10927 (if (js2-mode-invisible-overlay-bounds
10928 (setq pos (+ 3 (js2-node-abs-pos comment))))
10929 (progn
10930 (goto-char pos)
10931 (js2-mode-show-element))
10932 (js2-mode-hide-element)))
10933 ;; //-comment?
10934 ((save-excursion
10935 (back-to-indentation)
10936 (looking-at js2-mode-//-comment-re))
10937 (js2-mode-toggle-//-comment))
10938 ;; function?
10939 ((setq fn (js2-mode-function-at-point))
10940 (setq pos (and (js2-function-node-body fn)
10941 (js2-node-abs-pos (js2-function-node-body fn))))
10942 (goto-char (1+ pos))
10943 (if (js2-mode-invisible-overlay-bounds)
10944 (js2-mode-show-element)
10945 (js2-mode-hide-element)))
10946 (t
10947 (message "Nothing at point to hide or show"))))))
10948
10949 (defun js2-mode-hide-element ()
10950 "Fold/hide contents of a block, showing ellipses.
10951 Show the hidden text with \\[js2-mode-show-element]."
10952 (interactive)
10953 (if js2-mode-buffer-dirty-p
10954 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10955 (let (node body beg end)
10956 (cond
10957 ((js2-mode-invisible-overlay-bounds)
10958 (message "already hidden"))
10959 (t
10960 (setq node (js2-node-at-point))
10961 (cond
10962 ((js2-block-comment-p node)
10963 (js2-mode-hide-comment node))
10964 (t
10965 (while (and node (not (js2-function-node-p node)))
10966 (setq node (js2-node-parent node)))
10967 (if (and node
10968 (setq body (js2-function-node-body node)))
10969 (progn
10970 (setq beg (js2-node-abs-pos body)
10971 end (+ beg (js2-node-len body)))
10972 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10973 (message "No collapsable element found at point"))))))))
10974
10975 (defun js2-mode-show-element ()
10976 "Show the hidden element at current point."
10977 (interactive)
10978 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10979 (if bounds
10980 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
10981 (message "Nothing to un-hide"))))
10982
10983 (defun js2-mode-show-all ()
10984 "Show all of the text in the buffer."
10985 (interactive)
10986 (js2-mode-flag-region (point-min) (point-max) nil))
10987
10988 (defun js2-mode-toggle-hide-functions ()
10989 (interactive)
10990 (if js2-mode-functions-hidden
10991 (js2-mode-show-functions)
10992 (js2-mode-hide-functions)))
10993
10994 (defun js2-mode-hide-functions ()
10995 "Hides all non-nested function bodies in the buffer.
10996 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10997 to open an individual entry."
10998 (interactive)
10999 (if js2-mode-buffer-dirty-p
11000 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11001 (if (null js2-mode-ast)
11002 (message "Oops - parsing failed")
11003 (setq js2-mode-functions-hidden t)
11004 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11005
11006 (defun js2-mode-function-hider (n endp)
11007 (when (not endp)
11008 (let ((tt (js2-node-type n))
11009 body beg end)
11010 (cond
11011 ((and (= tt js2-FUNCTION)
11012 (setq body (js2-function-node-body n)))
11013 (setq beg (js2-node-abs-pos body)
11014 end (+ beg (js2-node-len body)))
11015 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11016 nil) ; don't process children of function
11017 (t
11018 t))))) ; keep processing other AST nodes
11019
11020 (defun js2-mode-show-functions ()
11021 "Un-hide any folded function bodies in the buffer."
11022 (interactive)
11023 (setq js2-mode-functions-hidden nil)
11024 (save-excursion
11025 (goto-char (point-min))
11026 (while (/= (goto-char (next-overlay-change (point)))
11027 (point-max))
11028 (dolist (o (overlays-at (point)))
11029 (when (and (overlay-get o 'invisible)
11030 (not (overlay-get o 'comment)))
11031 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11032
11033 (defun js2-mode-hide-comment (n)
11034 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11035 3 ; /**
11036 2)) ; /*
11037 (beg (+ (js2-node-abs-pos n) head))
11038 (end (- (+ beg (js2-node-len n)) head 2))
11039 (o (js2-mode-flag-region beg end 'hide)))
11040 (overlay-put o 'comment t)))
11041
11042 (defun js2-mode-toggle-hide-comments ()
11043 "Folds all block comments in the buffer.
11044 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11045 to open an individual entry."
11046 (interactive)
11047 (if js2-mode-comments-hidden
11048 (js2-mode-show-comments)
11049 (js2-mode-hide-comments)))
11050
11051 (defun js2-mode-hide-comments ()
11052 (interactive)
11053 (if js2-mode-buffer-dirty-p
11054 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11055 (if (null js2-mode-ast)
11056 (message "Oops - parsing failed")
11057 (setq js2-mode-comments-hidden t)
11058 (dolist (n (js2-ast-root-comments js2-mode-ast))
11059 (when (js2-block-comment-p n)
11060 (js2-mode-hide-comment n)))
11061 (js2-mode-hide-//-comments)))
11062
11063 (defun js2-mode-extend-//-comment (direction)
11064 "Find start or end of a block of similar //-comment lines.
11065 DIRECTION is -1 to look back, 1 to look forward.
11066 INDENT is the indentation level to match.
11067 Returns the end-of-line position of the furthest adjacent
11068 //-comment line with the same indentation as the current line.
11069 If there is no such matching line, returns current end of line."
11070 (let ((pos (point-at-eol))
11071 (indent (current-indentation)))
11072 (save-excursion
11073 (while (and (zerop (forward-line direction))
11074 (looking-at js2-mode-//-comment-re)
11075 (eq indent (length (match-string 1))))
11076 (setq pos (point-at-eol))
11077 pos))))
11078
11079 (defun js2-mode-hide-//-comments ()
11080 "Fold adjacent 1-line comments, showing only snippet of first one."
11081 (let (beg end)
11082 (save-excursion
11083 (goto-char (point-min))
11084 (while (re-search-forward js2-mode-//-comment-re nil t)
11085 (setq beg (point)
11086 end (js2-mode-extend-//-comment 1))
11087 (unless (eq beg end)
11088 (overlay-put (js2-mode-flag-region beg end 'hide)
11089 'comment t))
11090 (goto-char end)
11091 (forward-char 1)))))
11092
11093 (defun js2-mode-toggle-//-comment ()
11094 "Fold or un-fold any multi-line //-comment at point.
11095 Caller should have determined that this line starts with a //-comment."
11096 (let* ((beg (point-at-eol))
11097 (end beg))
11098 (save-excursion
11099 (goto-char end)
11100 (if (js2-mode-invisible-overlay-bounds)
11101 (js2-mode-show-element)
11102 ;; else hide the comment
11103 (setq beg (js2-mode-extend-//-comment -1)
11104 end (js2-mode-extend-//-comment 1))
11105 (unless (eq beg end)
11106 (overlay-put (js2-mode-flag-region beg end 'hide)
11107 'comment t))))))
11108
11109 (defun js2-mode-show-comments ()
11110 "Un-hide any hidden comments, leaving other hidden elements alone."
11111 (interactive)
11112 (setq js2-mode-comments-hidden nil)
11113 (save-excursion
11114 (goto-char (point-min))
11115 (while (/= (goto-char (next-overlay-change (point)))
11116 (point-max))
11117 (dolist (o (overlays-at (point)))
11118 (when (overlay-get o 'comment)
11119 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11120
11121 (defun js2-mode-display-warnings-and-errors ()
11122 "Turn on display of warnings and errors."
11123 (interactive)
11124 (setq js2-mode-show-parse-errors t
11125 js2-mode-show-strict-warnings t)
11126 (js2-reparse 'force))
11127
11128 (defun js2-mode-hide-warnings-and-errors ()
11129 "Turn off display of warnings and errors."
11130 (interactive)
11131 (setq js2-mode-show-parse-errors nil
11132 js2-mode-show-strict-warnings nil)
11133 (js2-reparse 'force))
11134
11135 (defun js2-mode-toggle-warnings-and-errors ()
11136 "Toggle the display of warnings and errors.
11137 Some users don't like having warnings/errors reported while they type."
11138 (interactive)
11139 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11140 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11141 (if (called-interactively-p 'any)
11142 (message "warnings and errors %s"
11143 (if js2-mode-show-parse-errors
11144 "enabled"
11145 "disabled")))
11146 (js2-reparse 'force))
11147
11148 (defun js2-mode-customize ()
11149 (interactive)
11150 (customize-group 'js2-mode))
11151
11152 (defun js2-mode-forward-sexp (&optional arg)
11153 "Move forward across one statement or balanced expression.
11154 With ARG, do it that many times. Negative arg -N means
11155 move backward across N balanced expressions."
11156 (interactive "p")
11157 (setq arg (or arg 1))
11158 (save-restriction
11159 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11160 (js2-reparse)
11161 (let (forward-sexp-function
11162 node (start (point)) pos lp rp child)
11163 (cond
11164 ;; backward-sexp
11165 ;; could probably make this better for some cases:
11166 ;; - if in statement block (e.g. function body), go to parent
11167 ;; - infix exprs like (foo in bar) - maybe go to beginning
11168 ;; of infix expr if in the right-side expression?
11169 ((and arg (minusp arg))
11170 (dotimes (_ (- arg))
11171 (js2-backward-sws)
11172 (forward-char -1) ; Enter the node we backed up to.
11173 (when (setq node (js2-node-at-point (point) t))
11174 (setq pos (js2-node-abs-pos node))
11175 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11176 (setq lp (car parens)
11177 rp (cdr parens)))
11178 (when (and lp (> start lp))
11179 (if (and rp (<= start rp))
11180 ;; Between parens, check if there's a child node we can jump.
11181 (when (setq child (js2-node-closest-child node (point) lp t))
11182 (setq pos (js2-node-abs-pos child)))
11183 ;; Before both parens.
11184 (setq pos lp)))
11185 (let ((state (parse-partial-sexp start pos)))
11186 (goto-char (if (not (zerop (car state)))
11187 ;; Stumble at the unbalanced paren if < 0, or
11188 ;; jump a bit further if > 0.
11189 (scan-sexps start -1)
11190 pos))))
11191 (unless pos (goto-char (point-min)))))
11192 (t
11193 ;; forward-sexp
11194 (dotimes (_ arg)
11195 (js2-forward-sws)
11196 (when (setq node (js2-node-at-point (point) t))
11197 (setq pos (js2-node-abs-pos node))
11198 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11199 (setq lp (car parens)
11200 rp (cdr parens)))
11201 (or
11202 (when (and rp (<= start rp))
11203 (if (> start lp)
11204 (when (setq child (js2-node-closest-child node (point) rp))
11205 (setq pos (js2-node-abs-end child)))
11206 (setq pos (1+ rp))))
11207 ;; No parens or child nodes, looks for the end of the curren node.
11208 (incf pos (js2-node-len
11209 (if (js2-expr-stmt-node-p (js2-node-parent node))
11210 ;; Stop after the semicolon.
11211 (js2-node-parent node)
11212 node))))
11213 (let ((state (save-excursion (parse-partial-sexp start pos))))
11214 (goto-char (if (not (zerop (car state)))
11215 (scan-sexps start 1)
11216 pos))))
11217 (unless pos (goto-char (point-max)))))))))
11218
11219 (defun js2-mode-forward-sexp-parens (node abs-pos)
11220 "Return a cons cell with positions of main parens in NODE."
11221 (cond
11222 ((or (js2-array-node-p node)
11223 (js2-object-node-p node)
11224 (js2-comp-node-p node)
11225 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11226 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11227 ((js2-paren-expr-node-p node)
11228 (let ((lp (js2-node-lp node))
11229 (rp (js2-node-rp node)))
11230 (cons (when lp (+ abs-pos lp))
11231 (when rp (+ abs-pos rp)))))))
11232
11233 (defun js2-node-closest-child (parent point limit &optional before)
11234 (let* ((parent-pos (js2-node-abs-pos parent))
11235 (rpoint (- point parent-pos))
11236 (rlimit (- limit parent-pos))
11237 (min (min rpoint rlimit))
11238 (max (max rpoint rlimit))
11239 found)
11240 (catch 'done
11241 (js2-visit-ast
11242 parent
11243 (lambda (node _end-p)
11244 (if (eq node parent)
11245 t
11246 (let ((pos (js2-node-pos node)) ;; Both relative values.
11247 (end (+ (js2-node-pos node) (js2-node-len node))))
11248 (when (and (>= pos min) (<= end max)
11249 (if before (< pos rpoint) (> end rpoint)))
11250 (setq found node))
11251 (when (> end rpoint)
11252 (throw 'done nil)))
11253 nil))))
11254 found))
11255
11256 (defun js2-errors ()
11257 "Return a list of errors found."
11258 (and js2-mode-ast
11259 (js2-ast-root-errors js2-mode-ast)))
11260
11261 (defun js2-warnings ()
11262 "Return a list of warnings found."
11263 (and js2-mode-ast
11264 (js2-ast-root-warnings js2-mode-ast)))
11265
11266 (defun js2-have-errors-p ()
11267 "Return non-nil if any parse errors or warnings were found."
11268 (or (js2-errors) (js2-warnings)))
11269
11270 (defun js2-errors-and-warnings ()
11271 "Return a copy of the concatenated errors and warnings lists.
11272 They are appended: first the errors, then the warnings.
11273 Entries are of the form (MSG BEG END)."
11274 (when js2-mode-ast
11275 (append (js2-ast-root-errors js2-mode-ast)
11276 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11277
11278 (defun js2-next-error (&optional arg reset)
11279 "Move to next parse error.
11280 Typically invoked via \\[next-error].
11281 ARG is the number of errors, forward or backward, to move.
11282 RESET means start over from the beginning."
11283 (interactive "p")
11284 (if (not (or (js2-errors) (js2-warnings)))
11285 (message "No errors")
11286 (when reset
11287 (goto-char (point-min)))
11288 (let* ((errs (js2-errors-and-warnings))
11289 (continue t)
11290 (start (point))
11291 (count (or arg 1))
11292 (backward (minusp count))
11293 (sorter (if backward '> '<))
11294 (stopper (if backward '< '>))
11295 (count (abs count))
11296 all-errs err)
11297 ;; Sort by start position.
11298 (setq errs (sort errs (lambda (e1 e2)
11299 (funcall sorter (second e1) (second e2))))
11300 all-errs errs)
11301 ;; Find nth error with pos > start.
11302 (while (and errs continue)
11303 (when (funcall stopper (cadar errs) start)
11304 (setq err (car errs))
11305 (if (zerop (decf count))
11306 (setq continue nil)))
11307 (setq errs (cdr errs)))
11308 ;; Clear for `js2-echo-error'.
11309 (message nil)
11310 (if err
11311 (goto-char (second err))
11312 ;; Wrap around to first error.
11313 (goto-char (second (car all-errs)))
11314 ;; If we were already on it, echo msg again.
11315 (if (= (point) start)
11316 (js2-echo-error (point) (point)))))))
11317
11318 (defun js2-down-mouse-3 ()
11319 "Make right-click move the point to the click location.
11320 This makes right-click context menu operations a bit more intuitive.
11321 The point will not move if the region is active, however, to avoid
11322 destroying the region selection."
11323 (interactive)
11324 (when (and js2-move-point-on-right-click
11325 (not mark-active))
11326 (let ((e last-input-event))
11327 (ignore-errors
11328 (goto-char (cadadr e))))))
11329
11330 (defun js2-mode-create-imenu-index ()
11331 "Return an alist for `imenu--index-alist'."
11332 ;; This is built up in `js2-parse-record-imenu' during parsing.
11333 (when js2-mode-ast
11334 ;; if we have an ast but no recorder, they're requesting a rescan
11335 (unless js2-imenu-recorder
11336 (js2-reparse 'force))
11337 (prog1
11338 (js2-build-imenu-index)
11339 (setq js2-imenu-recorder nil
11340 js2-imenu-function-map nil))))
11341
11342 (defun js2-mode-find-tag ()
11343 "Replacement for `find-tag-default'.
11344 `find-tag-default' returns a ridiculous answer inside comments."
11345 (let (beg end)
11346 (js2-with-underscore-as-word-syntax
11347 (save-excursion
11348 (if (and (not (looking-at "[[:alnum:]_$]"))
11349 (looking-back "[[:alnum:]_$]"))
11350 (setq beg (progn (forward-word -1) (point))
11351 end (progn (forward-word 1) (point)))
11352 (setq beg (progn (forward-word 1) (point))
11353 end (progn (forward-word -1) (point))))
11354 (replace-regexp-in-string
11355 "[\"']" ""
11356 (buffer-substring-no-properties beg end))))))
11357
11358 (defun js2-mode-forward-sibling ()
11359 "Move to the end of the sibling following point in parent.
11360 Returns non-nil if successful, or nil if there was no following sibling."
11361 (let* ((node (js2-node-at-point))
11362 (parent (js2-mode-find-enclosing-fn node))
11363 sib)
11364 (when (setq sib (js2-node-find-child-after (point) parent))
11365 (goto-char (+ (js2-node-abs-pos sib)
11366 (js2-node-len sib))))))
11367
11368 (defun js2-mode-backward-sibling ()
11369 "Move to the beginning of the sibling node preceding point in parent.
11370 Parent is defined as the enclosing script or function."
11371 (let* ((node (js2-node-at-point))
11372 (parent (js2-mode-find-enclosing-fn node))
11373 sib)
11374 (when (setq sib (js2-node-find-child-before (point) parent))
11375 (goto-char (js2-node-abs-pos sib)))))
11376
11377 (defun js2-beginning-of-defun (&optional arg)
11378 "Go to line on which current function starts, and return t on success.
11379 If we're not in a function or already at the beginning of one, go
11380 to beginning of previous script-level element.
11381 With ARG N, do that N times. If N is negative, move forward."
11382 (setq arg (or arg 1))
11383 (if (plusp arg)
11384 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11385 (when (cond
11386 ((js2-function-node-p parent)
11387 (goto-char (js2-node-abs-pos parent)))
11388 (t
11389 (js2-mode-backward-sibling)))
11390 (if (> arg 1)
11391 (js2-beginning-of-defun (1- arg))
11392 t)))
11393 (when (js2-end-of-defun)
11394 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
11395
11396 (defun js2-end-of-defun ()
11397 "Go to the char after the last position of the current function
11398 or script-level element."
11399 (let* ((node (js2-node-at-point))
11400 (parent (or (and (js2-function-node-p node) node)
11401 (js2-node-parent-script-or-fn node)))
11402 script)
11403 (unless (js2-function-node-p parent)
11404 ;; Use current script-level node, or, if none, the next one.
11405 (setq script (or parent node)
11406 parent (js2-node-find-child-before (point) script))
11407 (when (or (null parent)
11408 (>= (point) (+ (js2-node-abs-pos parent)
11409 (js2-node-len parent))))
11410 (setq parent (js2-node-find-child-after (point) script))))
11411 (when parent
11412 (goto-char (+ (js2-node-abs-pos parent)
11413 (js2-node-len parent))))))
11414
11415 (defun js2-mark-defun (&optional allow-extend)
11416 "Put mark at end of this function, point at beginning.
11417 The function marked is the one that contains point.
11418
11419 Interactively, if this command is repeated,
11420 or (in Transient Mark mode) if the mark is active,
11421 it marks the next defun after the ones already marked."
11422 (interactive "p")
11423 (let (extended)
11424 (when (and allow-extend
11425 (or (and (eq last-command this-command) (mark t))
11426 (and transient-mark-mode mark-active)))
11427 (let ((sib (save-excursion
11428 (goto-char (mark))
11429 (if (js2-mode-forward-sibling)
11430 (point)))))
11431 (if sib
11432 (progn
11433 (set-mark sib)
11434 (setq extended t))
11435 ;; no more siblings - try extending to enclosing node
11436 (goto-char (mark t)))))
11437 (when (not extended)
11438 (let ((node (js2-node-at-point (point) t)) ; skip comments
11439 ast fn stmt parent beg end)
11440 (when (js2-ast-root-p node)
11441 (setq ast node
11442 node (or (js2-node-find-child-after (point) node)
11443 (js2-node-find-child-before (point) node))))
11444 ;; only mark whole buffer if we can't find any children
11445 (if (null node)
11446 (setq node ast))
11447 (if (js2-function-node-p node)
11448 (setq parent node)
11449 (setq fn (js2-mode-find-enclosing-fn node)
11450 stmt (if (or (null fn)
11451 (js2-ast-root-p fn))
11452 (js2-mode-find-first-stmt node))
11453 parent (or stmt fn)))
11454 (setq beg (js2-node-abs-pos parent)
11455 end (+ beg (js2-node-len parent)))
11456 (push-mark beg)
11457 (goto-char end)
11458 (exchange-point-and-mark)))))
11459
11460 (defun js2-narrow-to-defun ()
11461 "Narrow to the function enclosing point."
11462 (interactive)
11463 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11464 (fn (if (js2-script-node-p node)
11465 node
11466 (js2-mode-find-enclosing-fn node)))
11467 (beg (js2-node-abs-pos fn)))
11468 (unless (js2-ast-root-p fn)
11469 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11470
11471 (provide 'js2-mode)
11472
11473 ;;; js2-mode.el ends here