]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Support Harmony generators (closes #119)
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2013 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: 20130619
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-instance-member
1054 '((t :foreground "DarkOrchid"))
1055 "Face used to highlight instance variables in javascript.
1056 Not currently used."
1057 :group 'js2-mode)
1058
1059 (defface js2-private-member
1060 '((t :foreground "PeachPuff3"))
1061 "Face used to highlight calls to private methods in javascript.
1062 Not currently used."
1063 :group 'js2-mode)
1064
1065 (defface js2-private-function-call
1066 '((t :foreground "goldenrod"))
1067 "Face used to highlight calls to private functions in javascript.
1068 Not currently used."
1069 :group 'js2-mode)
1070
1071 (defface js2-jsdoc-html-tag-name
1072 '((((class color) (min-colors 88) (background light))
1073 (:foreground "rosybrown"))
1074 (((class color) (min-colors 8) (background dark))
1075 (:foreground "yellow"))
1076 (((class color) (min-colors 8) (background light))
1077 (:foreground "magenta")))
1078 "Face used to highlight jsdoc html tag names"
1079 :group 'js2-mode)
1080
1081 (defface js2-jsdoc-html-tag-delimiter
1082 '((((class color) (min-colors 88) (background light))
1083 (:foreground "dark khaki"))
1084 (((class color) (min-colors 8) (background dark))
1085 (:foreground "green"))
1086 (((class color) (min-colors 8) (background light))
1087 (:foreground "green")))
1088 "Face used to highlight brackets in jsdoc html tags."
1089 :group 'js2-mode)
1090
1091 (defface js2-external-variable
1092 '((t :foreground "orange"))
1093 "Face used to highlight undeclared variable identifiers.")
1094
1095 (defcustom js2-init-hook nil
1096 "List of functions to be called after `js2-mode' or
1097 `js2-minor-mode' has initialized all variables, before parsing
1098 the buffer for the first time."
1099 :type 'hook
1100 :group 'js2-mode
1101 :version "20130608")
1102
1103 (defcustom js2-post-parse-callbacks nil
1104 "List of callback functions invoked after parsing finishes.
1105 Currently, the main use for this function is to add synthetic
1106 declarations to `js2-recorded-identifiers', which see."
1107 :type 'hook
1108 :group 'js2-mode)
1109
1110 (defcustom js2-highlight-external-variables t
1111 "Non-nil to highlight undeclared variable identifiers.
1112 An undeclared variable is any variable not declared with var or let
1113 in the current scope or any lexically enclosing scope. If you use
1114 such a variable, then you are either expecting it to originate from
1115 another file, or you've got a potential bug."
1116 :type 'boolean
1117 :group 'js2-mode)
1118
1119 (defcustom js2-include-jslint-globals t
1120 "Non-nil to include the identifiers from JSLint global
1121 declaration (see http://www.jslint.com/lint.html#global) in the
1122 buffer-local externs list. See `js2-additional-externs' for more
1123 information."
1124 :type 'boolean
1125 :group 'js2-mode)
1126
1127 (defvar js2-mode-map
1128 (let ((map (make-sparse-keymap)))
1129 (define-key map [mouse-1] #'js2-mode-show-node)
1130 (define-key map (kbd "M-j") #'js2-line-break)
1131 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1132 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1133 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1134 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1135 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1136 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1137 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1138 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1139 (when js2-bounce-indent-p
1140 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1141
1142 (define-key map [menu-bar javascript]
1143 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1144
1145 (define-key map [menu-bar javascript customize-js2-mode]
1146 '(menu-item "Customize js2-mode" js2-mode-customize
1147 :help "Customize the behavior of this mode"))
1148
1149 (define-key map [menu-bar javascript js2-force-refresh]
1150 '(menu-item "Force buffer refresh" js2-mode-reset
1151 :help "Re-parse the buffer from scratch"))
1152
1153 (define-key map [menu-bar javascript separator-2]
1154 '("--"))
1155
1156 (define-key map [menu-bar javascript next-error]
1157 '(menu-item "Next warning or error" next-error
1158 :enabled (and js2-mode-ast
1159 (or (js2-ast-root-errors js2-mode-ast)
1160 (js2-ast-root-warnings js2-mode-ast)))
1161 :help "Move to next warning or error"))
1162
1163 (define-key map [menu-bar javascript display-errors]
1164 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1165 :visible (not js2-mode-show-parse-errors)
1166 :help "Turn on display of warnings and errors"))
1167
1168 (define-key map [menu-bar javascript hide-errors]
1169 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1170 :visible js2-mode-show-parse-errors
1171 :help "Turn off display of warnings and errors"))
1172
1173 (define-key map [menu-bar javascript separator-1]
1174 '("--"))
1175
1176 (define-key map [menu-bar javascript js2-toggle-function]
1177 '(menu-item "Show/collapse element" js2-mode-toggle-element
1178 :help "Hide or show function body or comment"))
1179
1180 (define-key map [menu-bar javascript show-comments]
1181 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1182 :visible js2-mode-comments-hidden
1183 :help "Expand all hidden block comments"))
1184
1185 (define-key map [menu-bar javascript hide-comments]
1186 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1187 :visible (not js2-mode-comments-hidden)
1188 :help "Show block comments as /*...*/"))
1189
1190 (define-key map [menu-bar javascript show-all-functions]
1191 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1192 :visible js2-mode-functions-hidden
1193 :help "Expand all hidden function bodies"))
1194
1195 (define-key map [menu-bar javascript hide-all-functions]
1196 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1197 :visible (not js2-mode-functions-hidden)
1198 :help "Show {...} for all top-level function bodies"))
1199
1200 map)
1201 "Keymap used in `js2-mode' buffers.")
1202
1203 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1204
1205 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1206 "Matches a //-comment line. Must be first non-whitespace on line.
1207 First match-group is the leading whitespace.")
1208
1209 (defvar js2-mode-hook nil)
1210
1211 (js2-deflocal js2-mode-ast nil "Private variable.")
1212 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1213 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1214 (js2-deflocal js2-mode-parsing nil "Private variable.")
1215 (js2-deflocal js2-mode-node-overlay nil)
1216
1217 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1218 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1219
1220 (js2-deflocal js2-mode-fontifications nil "Private variable")
1221 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1222 (js2-deflocal js2-imenu-recorder nil "Private variable")
1223 (js2-deflocal js2-imenu-function-map nil "Private variable")
1224
1225 (defvar js2-paragraph-start
1226 "\\(@[[:alpha:]]+\\>\\|$\\)")
1227
1228 ;; Note that we also set a 'c-in-sws text property in html comments,
1229 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1230 (defvar js2-syntactic-ws-start
1231 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1232
1233 (defvar js2-syntactic-ws-end
1234 "\\s \\|[\n\r/]\\|\\s!")
1235
1236 (defvar js2-syntactic-eol
1237 (concat "\\s *\\(/\\*[^*\n\r]*"
1238 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1239 "\\*+/\\s *\\)*"
1240 "\\(//\\|/\\*[^*\n\r]*"
1241 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1242 "\\|\\\\$\\|$\\)")
1243 "Copied from `java-mode'. Needed for some cc-engine functions.")
1244
1245 (defvar js2-comment-prefix-regexp
1246 "//+\\|\\**")
1247
1248 (defvar js2-comment-start-skip
1249 "\\(//+\\|/\\*+\\)\\s *")
1250
1251 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1252 "Non-nil to emit status messages during parsing.")
1253
1254 (defvar js2-mode-functions-hidden nil "Private variable.")
1255 (defvar js2-mode-comments-hidden nil "Private variable.")
1256
1257 (defvar js2-mode-syntax-table
1258 (let ((table (make-syntax-table)))
1259 (c-populate-syntax-table table)
1260 table)
1261 "Syntax table used in `js2-mode' buffers.")
1262
1263 (defvar js2-mode-abbrev-table nil
1264 "Abbrev table in use in `js2-mode' buffers.")
1265 (define-abbrev-table 'js2-mode-abbrev-table ())
1266
1267 (defvar js2-mode-pending-parse-callbacks nil
1268 "List of functions waiting to be notified that parse is finished.")
1269
1270 (defvar js2-mode-last-indented-line -1)
1271
1272 ;;; Localizable error and warning messages
1273
1274 ;; Messages are copied from Rhino's Messages.properties.
1275 ;; Many of the Java-specific messages have been elided.
1276 ;; Add any js2-specific ones at the end, so we can keep
1277 ;; this file synced with changes to Rhino's.
1278
1279 (defvar js2-message-table
1280 (make-hash-table :test 'equal :size 250)
1281 "Contains localized messages for `js2-mode'.")
1282
1283 ;; TODO(stevey): construct this table at compile-time.
1284 (defmacro js2-msg (key &rest strings)
1285 `(puthash ,key (concat ,@strings)
1286 js2-message-table))
1287
1288 (defun js2-get-msg (msg-key)
1289 "Look up a localized message.
1290 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1291 the correct number of ARGS must be provided."
1292 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1293 (args (if (listp msg-key) (cdr msg-key)))
1294 (msg (gethash key js2-message-table)))
1295 (if msg
1296 (apply #'format msg args)
1297 key))) ; default to showing the key
1298
1299 (js2-msg "msg.dup.parms"
1300 "Duplicate parameter name '%s'.")
1301
1302 (js2-msg "msg.too.big.jump"
1303 "Program too complex: jump offset too big.")
1304
1305 (js2-msg "msg.too.big.index"
1306 "Program too complex: internal index exceeds 64K limit.")
1307
1308 (js2-msg "msg.while.compiling.fn"
1309 "Encountered code generation error while compiling function '%s': %s")
1310
1311 (js2-msg "msg.while.compiling.script"
1312 "Encountered code generation error while compiling script: %s")
1313
1314 ;; Context
1315 (js2-msg "msg.ctor.not.found"
1316 "Constructor for '%s' not found.")
1317
1318 (js2-msg "msg.not.ctor"
1319 "'%s' is not a constructor.")
1320
1321 ;; FunctionObject
1322 (js2-msg "msg.varargs.ctor"
1323 "Method or constructor '%s' must be static "
1324 "with the signature (Context cx, Object[] args, "
1325 "Function ctorObj, boolean inNewExpr) "
1326 "to define a variable arguments constructor.")
1327
1328 (js2-msg "msg.varargs.fun"
1329 "Method '%s' must be static with the signature "
1330 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1331 "to define a variable arguments function.")
1332
1333 (js2-msg "msg.incompat.call"
1334 "Method '%s' called on incompatible object.")
1335
1336 (js2-msg "msg.bad.parms"
1337 "Unsupported parameter type '%s' in method '%s'.")
1338
1339 (js2-msg "msg.bad.method.return"
1340 "Unsupported return type '%s' in method '%s'.")
1341
1342 (js2-msg "msg.bad.ctor.return"
1343 "Construction of objects of type '%s' is not supported.")
1344
1345 (js2-msg "msg.no.overload"
1346 "Method '%s' occurs multiple times in class '%s'.")
1347
1348 (js2-msg "msg.method.not.found"
1349 "Method '%s' not found in '%s'.")
1350
1351 ;; IRFactory
1352
1353 (js2-msg "msg.bad.for.in.lhs"
1354 "Invalid left-hand side of for..in loop.")
1355
1356 (js2-msg "msg.mult.index"
1357 "Only one variable allowed in for..in loop.")
1358
1359 (js2-msg "msg.bad.for.in.destruct"
1360 "Left hand side of for..in loop must be an array of "
1361 "length 2 to accept key/value pair.")
1362
1363 (js2-msg "msg.cant.convert"
1364 "Can't convert to type '%s'.")
1365
1366 (js2-msg "msg.bad.assign.left"
1367 "Invalid assignment left-hand side.")
1368
1369 (js2-msg "msg.bad.decr"
1370 "Invalid decerement operand.")
1371
1372 (js2-msg "msg.bad.incr"
1373 "Invalid increment operand.")
1374
1375 (js2-msg "msg.bad.yield"
1376 "yield must be in a function.")
1377
1378 (js2-msg "msg.yield.parenthesized"
1379 "yield expression must be parenthesized.")
1380
1381 ;; NativeGlobal
1382 (js2-msg "msg.cant.call.indirect"
1383 "Function '%s' must be called directly, and not by way of a "
1384 "function of another name.")
1385
1386 (js2-msg "msg.eval.nonstring"
1387 "Calling eval() with anything other than a primitive "
1388 "string value will simply return the value. "
1389 "Is this what you intended?")
1390
1391 (js2-msg "msg.eval.nonstring.strict"
1392 "Calling eval() with anything other than a primitive "
1393 "string value is not allowed in strict mode.")
1394
1395 (js2-msg "msg.bad.destruct.op"
1396 "Invalid destructuring assignment operator")
1397
1398 ;; NativeCall
1399 (js2-msg "msg.only.from.new"
1400 "'%s' may only be invoked from a `new' expression.")
1401
1402 (js2-msg "msg.deprec.ctor"
1403 "The '%s' constructor is deprecated.")
1404
1405 ;; NativeFunction
1406 (js2-msg "msg.no.function.ref.found"
1407 "no source found to decompile function reference %s")
1408
1409 (js2-msg "msg.arg.isnt.array"
1410 "second argument to Function.prototype.apply must be an array")
1411
1412 ;; NativeGlobal
1413 (js2-msg "msg.bad.esc.mask"
1414 "invalid string escape mask")
1415
1416 ;; NativeRegExp
1417 (js2-msg "msg.bad.quant"
1418 "Invalid quantifier %s")
1419
1420 (js2-msg "msg.overlarge.backref"
1421 "Overly large back reference %s")
1422
1423 (js2-msg "msg.overlarge.min"
1424 "Overly large minimum %s")
1425
1426 (js2-msg "msg.overlarge.max"
1427 "Overly large maximum %s")
1428
1429 (js2-msg "msg.zero.quant"
1430 "Zero quantifier %s")
1431
1432 (js2-msg "msg.max.lt.min"
1433 "Maximum %s less than minimum")
1434
1435 (js2-msg "msg.unterm.quant"
1436 "Unterminated quantifier %s")
1437
1438 (js2-msg "msg.unterm.paren"
1439 "Unterminated parenthetical %s")
1440
1441 (js2-msg "msg.unterm.class"
1442 "Unterminated character class %s")
1443
1444 (js2-msg "msg.bad.range"
1445 "Invalid range in character class.")
1446
1447 (js2-msg "msg.trail.backslash"
1448 "Trailing \\ in regular expression.")
1449
1450 (js2-msg "msg.re.unmatched.right.paren"
1451 "unmatched ) in regular expression.")
1452
1453 (js2-msg "msg.no.regexp"
1454 "Regular expressions are not available.")
1455
1456 (js2-msg "msg.bad.backref"
1457 "back-reference exceeds number of capturing parentheses.")
1458
1459 (js2-msg "msg.bad.regexp.compile"
1460 "Only one argument may be specified if the first "
1461 "argument to RegExp.prototype.compile is a RegExp object.")
1462
1463 ;; Parser
1464 (js2-msg "msg.got.syntax.errors"
1465 "Compilation produced %s syntax errors.")
1466
1467 (js2-msg "msg.var.redecl"
1468 "TypeError: redeclaration of var %s.")
1469
1470 (js2-msg "msg.const.redecl"
1471 "TypeError: redeclaration of const %s.")
1472
1473 (js2-msg "msg.let.redecl"
1474 "TypeError: redeclaration of variable %s.")
1475
1476 (js2-msg "msg.parm.redecl"
1477 "TypeError: redeclaration of formal parameter %s.")
1478
1479 (js2-msg "msg.fn.redecl"
1480 "TypeError: redeclaration of function %s.")
1481
1482 (js2-msg "msg.let.decl.not.in.block"
1483 "SyntaxError: let declaration not directly within block")
1484
1485 ;; NodeTransformer
1486 (js2-msg "msg.dup.label"
1487 "duplicated label")
1488
1489 (js2-msg "msg.undef.label"
1490 "undefined label")
1491
1492 (js2-msg "msg.bad.break"
1493 "unlabelled break must be inside loop or switch")
1494
1495 (js2-msg "msg.continue.outside"
1496 "continue must be inside loop")
1497
1498 (js2-msg "msg.continue.nonloop"
1499 "continue can only use labels of iteration statements")
1500
1501 (js2-msg "msg.bad.throw.eol"
1502 "Line terminator is not allowed between the throw "
1503 "keyword and throw expression.")
1504
1505 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1506 "function statement requires a name")
1507
1508 (js2-msg "msg.no.paren.parms"
1509 "missing ( before function parameters.")
1510
1511 (js2-msg "msg.no.parm"
1512 "missing formal parameter")
1513
1514 (js2-msg "msg.no.paren.after.parms"
1515 "missing ) after formal parameters")
1516
1517 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1518 "parameter without default follows parameter with default")
1519
1520 (js2-msg "msg.param.after.rest" ; added by js2-mode
1521 "parameter after rest parameter")
1522
1523 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1524 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1525
1526 (js2-msg "msg.no.brace.body"
1527 "missing '{' before function body")
1528
1529 (js2-msg "msg.no.brace.after.body"
1530 "missing } after function body")
1531
1532 (js2-msg "msg.no.paren.cond"
1533 "missing ( before condition")
1534
1535 (js2-msg "msg.no.paren.after.cond"
1536 "missing ) after condition")
1537
1538 (js2-msg "msg.no.semi.stmt"
1539 "missing ; before statement")
1540
1541 (js2-msg "msg.missing.semi"
1542 "missing ; after statement")
1543
1544 (js2-msg "msg.no.name.after.dot"
1545 "missing name after . operator")
1546
1547 (js2-msg "msg.no.name.after.coloncolon"
1548 "missing name after :: operator")
1549
1550 (js2-msg "msg.no.name.after.dotdot"
1551 "missing name after .. operator")
1552
1553 (js2-msg "msg.no.name.after.xmlAttr"
1554 "missing name after .@")
1555
1556 (js2-msg "msg.no.bracket.index"
1557 "missing ] in index expression")
1558
1559 (js2-msg "msg.no.paren.switch"
1560 "missing ( before switch expression")
1561
1562 (js2-msg "msg.no.paren.after.switch"
1563 "missing ) after switch expression")
1564
1565 (js2-msg "msg.no.brace.switch"
1566 "missing '{' before switch body")
1567
1568 (js2-msg "msg.bad.switch"
1569 "invalid switch statement")
1570
1571 (js2-msg "msg.no.colon.case"
1572 "missing : after case expression")
1573
1574 (js2-msg "msg.double.switch.default"
1575 "double default label in the switch statement")
1576
1577 (js2-msg "msg.no.while.do"
1578 "missing while after do-loop body")
1579
1580 (js2-msg "msg.no.paren.for"
1581 "missing ( after for")
1582
1583 (js2-msg "msg.no.semi.for"
1584 "missing ; after for-loop initializer")
1585
1586 (js2-msg "msg.no.semi.for.cond"
1587 "missing ; after for-loop condition")
1588
1589 (js2-msg "msg.in.after.for.name"
1590 "missing in or of after for")
1591
1592 (js2-msg "msg.no.paren.for.ctrl"
1593 "missing ) after for-loop control")
1594
1595 (js2-msg "msg.no.paren.with"
1596 "missing ( before with-statement object")
1597
1598 (js2-msg "msg.no.paren.after.with"
1599 "missing ) after with-statement object")
1600
1601 (js2-msg "msg.no.paren.after.let"
1602 "missing ( after let")
1603
1604 (js2-msg "msg.no.paren.let"
1605 "missing ) after variable list")
1606
1607 (js2-msg "msg.no.curly.let"
1608 "missing } after let statement")
1609
1610 (js2-msg "msg.bad.return"
1611 "invalid return")
1612
1613 (js2-msg "msg.no.brace.block"
1614 "missing } in compound statement")
1615
1616 (js2-msg "msg.bad.label"
1617 "invalid label")
1618
1619 (js2-msg "msg.bad.var"
1620 "missing variable name")
1621
1622 (js2-msg "msg.bad.var.init"
1623 "invalid variable initialization")
1624
1625 (js2-msg "msg.no.colon.cond"
1626 "missing : in conditional expression")
1627
1628 (js2-msg "msg.no.paren.arg"
1629 "missing ) after argument list")
1630
1631 (js2-msg "msg.no.bracket.arg"
1632 "missing ] after element list")
1633
1634 (js2-msg "msg.bad.prop"
1635 "invalid property id")
1636
1637 (js2-msg "msg.no.colon.prop"
1638 "missing : after property id")
1639
1640 (js2-msg "msg.no.brace.prop"
1641 "missing } after property list")
1642
1643 (js2-msg "msg.no.paren"
1644 "missing ) in parenthetical")
1645
1646 (js2-msg "msg.reserved.id"
1647 "identifier is a reserved word")
1648
1649 (js2-msg "msg.no.paren.catch"
1650 "missing ( before catch-block condition")
1651
1652 (js2-msg "msg.bad.catchcond"
1653 "invalid catch block condition")
1654
1655 (js2-msg "msg.catch.unreachable"
1656 "any catch clauses following an unqualified catch are unreachable")
1657
1658 (js2-msg "msg.no.brace.try"
1659 "missing '{' before try block")
1660
1661 (js2-msg "msg.no.brace.catchblock"
1662 "missing '{' before catch-block body")
1663
1664 (js2-msg "msg.try.no.catchfinally"
1665 "'try' without 'catch' or 'finally'")
1666
1667 (js2-msg "msg.no.return.value"
1668 "function %s does not always return a value")
1669
1670 (js2-msg "msg.anon.no.return.value"
1671 "anonymous function does not always return a value")
1672
1673 (js2-msg "msg.return.inconsistent"
1674 "return statement is inconsistent with previous usage")
1675
1676 (js2-msg "msg.generator.returns"
1677 "TypeError: legacy generator function '%s' returns a value")
1678
1679 (js2-msg "msg.anon.generator.returns"
1680 "TypeError: anonymous legacy generator function returns a value")
1681
1682 (js2-msg "msg.syntax"
1683 "syntax error")
1684
1685 (js2-msg "msg.unexpected.eof"
1686 "Unexpected end of file")
1687
1688 (js2-msg "msg.XML.bad.form"
1689 "illegally formed XML syntax")
1690
1691 (js2-msg "msg.XML.not.available"
1692 "XML runtime not available")
1693
1694 (js2-msg "msg.too.deep.parser.recursion"
1695 "Too deep recursion while parsing")
1696
1697 (js2-msg "msg.no.side.effects"
1698 "Code has no side effects")
1699
1700 (js2-msg "msg.extra.trailing.comma"
1701 "Trailing comma is not supported in some browsers")
1702
1703 (js2-msg "msg.array.trailing.comma"
1704 "Trailing comma yields different behavior across browsers")
1705
1706 (js2-msg "msg.equal.as.assign"
1707 (concat "Test for equality (==) mistyped as assignment (=)?"
1708 " (parenthesize to suppress warning)"))
1709
1710 (js2-msg "msg.var.hides.arg"
1711 "Variable %s hides argument")
1712
1713 (js2-msg "msg.destruct.assign.no.init"
1714 "Missing = in destructuring declaration")
1715
1716 ;; ScriptRuntime
1717 (js2-msg "msg.no.properties"
1718 "%s has no properties.")
1719
1720 (js2-msg "msg.invalid.iterator"
1721 "Invalid iterator value")
1722
1723 (js2-msg "msg.iterator.primitive"
1724 "__iterator__ returned a primitive value")
1725
1726 (js2-msg "msg.assn.create.strict"
1727 "Assignment to undeclared variable %s")
1728
1729 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1730 "Undeclared variable or function '%s'")
1731
1732 (js2-msg "msg.ref.undefined.prop"
1733 "Reference to undefined property '%s'")
1734
1735 (js2-msg "msg.prop.not.found"
1736 "Property %s not found.")
1737
1738 (js2-msg "msg.invalid.type"
1739 "Invalid JavaScript value of type %s")
1740
1741 (js2-msg "msg.primitive.expected"
1742 "Primitive type expected (had %s instead)")
1743
1744 (js2-msg "msg.namespace.expected"
1745 "Namespace object expected to left of :: (found %s instead)")
1746
1747 (js2-msg "msg.null.to.object"
1748 "Cannot convert null to an object.")
1749
1750 (js2-msg "msg.undef.to.object"
1751 "Cannot convert undefined to an object.")
1752
1753 (js2-msg "msg.cyclic.value"
1754 "Cyclic %s value not allowed.")
1755
1756 (js2-msg "msg.is.not.defined"
1757 "'%s' is not defined.")
1758
1759 (js2-msg "msg.undef.prop.read"
1760 "Cannot read property '%s' from %s")
1761
1762 (js2-msg "msg.undef.prop.write"
1763 "Cannot set property '%s' of %s to '%s'")
1764
1765 (js2-msg "msg.undef.prop.delete"
1766 "Cannot delete property '%s' of %s")
1767
1768 (js2-msg "msg.undef.method.call"
1769 "Cannot call method '%s' of %s")
1770
1771 (js2-msg "msg.undef.with"
1772 "Cannot apply 'with' to %s")
1773
1774 (js2-msg "msg.isnt.function"
1775 "%s is not a function, it is %s.")
1776
1777 (js2-msg "msg.isnt.function.in"
1778 "Cannot call property %s in object %s. "
1779 "It is not a function, it is '%s'.")
1780
1781 (js2-msg "msg.function.not.found"
1782 "Cannot find function %s.")
1783
1784 (js2-msg "msg.function.not.found.in"
1785 "Cannot find function %s in object %s.")
1786
1787 (js2-msg "msg.isnt.xml.object"
1788 "%s is not an xml object.")
1789
1790 (js2-msg "msg.no.ref.to.get"
1791 "%s is not a reference to read reference value.")
1792
1793 (js2-msg "msg.no.ref.to.set"
1794 "%s is not a reference to set reference value to %s.")
1795
1796 (js2-msg "msg.no.ref.from.function"
1797 "Function %s can not be used as the left-hand "
1798 "side of assignment or as an operand of ++ or -- operator.")
1799
1800 (js2-msg "msg.bad.default.value"
1801 "Object's getDefaultValue() method returned an object.")
1802
1803 (js2-msg "msg.instanceof.not.object"
1804 "Can't use instanceof on a non-object.")
1805
1806 (js2-msg "msg.instanceof.bad.prototype"
1807 "'prototype' property of %s is not an object.")
1808
1809 (js2-msg "msg.bad.radix"
1810 "illegal radix %s.")
1811
1812 ;; ScriptableObject
1813 (js2-msg "msg.default.value"
1814 "Cannot find default value for object.")
1815
1816 (js2-msg "msg.zero.arg.ctor"
1817 "Cannot load class '%s' which has no zero-parameter constructor.")
1818
1819 (js2-msg "msg.ctor.multiple.parms"
1820 "Can't define constructor or class %s since more than "
1821 "one constructor has multiple parameters.")
1822
1823 (js2-msg "msg.extend.scriptable"
1824 "%s must extend ScriptableObject in order to define property %s.")
1825
1826 (js2-msg "msg.bad.getter.parms"
1827 "In order to define a property, getter %s must have zero "
1828 "parameters or a single ScriptableObject parameter.")
1829
1830 (js2-msg "msg.obj.getter.parms"
1831 "Expected static or delegated getter %s to take "
1832 "a ScriptableObject parameter.")
1833
1834 (js2-msg "msg.getter.static"
1835 "Getter and setter must both be static or neither be static.")
1836
1837 (js2-msg "msg.setter.return"
1838 "Setter must have void return type: %s")
1839
1840 (js2-msg "msg.setter2.parms"
1841 "Two-parameter setter must take a ScriptableObject as "
1842 "its first parameter.")
1843
1844 (js2-msg "msg.setter1.parms"
1845 "Expected single parameter setter for %s")
1846
1847 (js2-msg "msg.setter2.expected"
1848 "Expected static or delegated setter %s to take two parameters.")
1849
1850 (js2-msg "msg.setter.parms"
1851 "Expected either one or two parameters for setter.")
1852
1853 (js2-msg "msg.setter.bad.type"
1854 "Unsupported parameter type '%s' in setter '%s'.")
1855
1856 (js2-msg "msg.add.sealed"
1857 "Cannot add a property to a sealed object: %s.")
1858
1859 (js2-msg "msg.remove.sealed"
1860 "Cannot remove a property from a sealed object: %s.")
1861
1862 (js2-msg "msg.modify.sealed"
1863 "Cannot modify a property of a sealed object: %s.")
1864
1865 (js2-msg "msg.modify.readonly"
1866 "Cannot modify readonly property: %s.")
1867
1868 ;; TokenStream
1869 (js2-msg "msg.missing.exponent"
1870 "missing exponent")
1871
1872 (js2-msg "msg.caught.nfe"
1873 "number format error")
1874
1875 (js2-msg "msg.unterminated.string.lit"
1876 "unterminated string literal")
1877
1878 (js2-msg "msg.unterminated.comment"
1879 "unterminated comment")
1880
1881 (js2-msg "msg.unterminated.re.lit"
1882 "unterminated regular expression literal")
1883
1884 (js2-msg "msg.invalid.re.flag"
1885 "invalid flag after regular expression")
1886
1887 (js2-msg "msg.no.re.input.for"
1888 "no input for %s")
1889
1890 (js2-msg "msg.illegal.character"
1891 "illegal character")
1892
1893 (js2-msg "msg.invalid.escape"
1894 "invalid Unicode escape sequence")
1895
1896 (js2-msg "msg.bad.namespace"
1897 "not a valid default namespace statement. "
1898 "Syntax is: default xml namespace = EXPRESSION;")
1899
1900 ;; TokensStream warnings
1901 (js2-msg "msg.bad.octal.literal"
1902 "illegal octal literal digit %s; "
1903 "interpreting it as a decimal digit")
1904
1905 (js2-msg "msg.reserved.keyword"
1906 "illegal usage of future reserved keyword %s; "
1907 "interpreting it as ordinary identifier")
1908
1909 (js2-msg "msg.script.is.not.constructor"
1910 "Script objects are not constructors.")
1911
1912 ;; Arrays
1913 (js2-msg "msg.arraylength.bad"
1914 "Inappropriate array length.")
1915
1916 ;; Arrays
1917 (js2-msg "msg.arraylength.too.big"
1918 "Array length %s exceeds supported capacity limit.")
1919
1920 ;; URI
1921 (js2-msg "msg.bad.uri"
1922 "Malformed URI sequence.")
1923
1924 ;; Number
1925 (js2-msg "msg.bad.precision"
1926 "Precision %s out of range.")
1927
1928 ;; NativeGenerator
1929 (js2-msg "msg.send.newborn"
1930 "Attempt to send value to newborn generator")
1931
1932 (js2-msg "msg.already.exec.gen"
1933 "Already executing generator")
1934
1935 (js2-msg "msg.StopIteration.invalid"
1936 "StopIteration may not be changed to an arbitrary object.")
1937
1938 ;; Interpreter
1939 (js2-msg "msg.yield.closing"
1940 "Yield from closing generator")
1941
1942 ;;; Tokens Buffer
1943
1944 (defconst js2-ti-max-lookahead 2)
1945 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1946
1947 ;; Have to call `js2-init-scanner' to initialize the values.
1948 (js2-deflocal js2-ti-tokens nil)
1949 (js2-deflocal js2-ti-tokens-cursor nil)
1950 (js2-deflocal js2-ti-lookahead nil)
1951
1952 (defun js2-new-token (offset)
1953 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
1954 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
1955 (aset js2-ti-tokens js2-ti-tokens-cursor token)
1956 token))
1957
1958 (defsubst js2-current-token ()
1959 (aref js2-ti-tokens js2-ti-tokens-cursor))
1960
1961 (defsubst js2-current-token-string ()
1962 (js2-token-string (js2-current-token)))
1963
1964 (defsubst js2-current-token-type ()
1965 (js2-token-type (js2-current-token)))
1966
1967 (defsubst js2-current-token-beg ()
1968 (js2-token-beg (js2-current-token)))
1969
1970 (defsubst js2-current-token-end ()
1971 (js2-token-end (js2-current-token)))
1972
1973 (defun js2-current-token-len ()
1974 (let ((token (js2-current-token)))
1975 (- (js2-token-end token)
1976 (js2-token-beg token))))
1977
1978 (defun js2-ts-seek (state)
1979 (setq js2-ts-lineno (js2-ts-state-lineno state)
1980 js2-ts-cursor (js2-ts-state-cursor state)
1981 js2-ti-tokens (js2-ts-state-tokens state)
1982 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
1983 js2-ti-lookahead (js2-ts-state-lookahead state)))
1984
1985 ;;; Utilities
1986
1987 (defun js2-delete-if (predicate list)
1988 "Remove all items satisfying PREDICATE in LIST."
1989 (loop for item in list
1990 if (not (funcall predicate item))
1991 collect item))
1992
1993 (defun js2-position (element list)
1994 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1995 Returns nil if element is not found in the list."
1996 (let ((count 0)
1997 found)
1998 (while (and list (not found))
1999 (if (eq element (car list))
2000 (setq found t)
2001 (setq count (1+ count)
2002 list (cdr list))))
2003 (if found count)))
2004
2005 (defun js2-find-if (predicate list)
2006 "Find first item satisfying PREDICATE in LIST."
2007 (let (result)
2008 (while (and list (not result))
2009 (if (funcall predicate (car list))
2010 (setq result (car list)))
2011 (setq list (cdr list)))
2012 result))
2013
2014 (defmacro js2-time (form)
2015 "Evaluate FORM, discard result, and return elapsed time in sec."
2016 (declare (debug t))
2017 (let ((beg (make-symbol "--js2-time-beg--"))
2018 (delta (make-symbol "--js2-time-end--")))
2019 `(let ((,beg (current-time))
2020 ,delta)
2021 ,form
2022 (/ (truncate (* (- (float-time (current-time))
2023 (float-time ,beg))
2024 10000))
2025 10000.0))))
2026
2027 (defsubst js2-same-line (pos)
2028 "Return t if POS is on the same line as current point."
2029 (and (>= pos (point-at-bol))
2030 (<= pos (point-at-eol))))
2031
2032 (defun js2-code-bug ()
2033 "Signal an error when we encounter an unexpected code path."
2034 (error "failed assertion"))
2035
2036 (defsubst js2-record-text-property (beg end prop value)
2037 "Record a text property to set when parsing finishes."
2038 (push (list beg end prop value) js2-mode-deferred-properties))
2039
2040 ;; I'd like to associate errors with nodes, but for now the
2041 ;; easiest thing to do is get the context info from the last token.
2042 (defun js2-record-parse-error (msg &optional arg pos len)
2043 (push (list (list msg arg)
2044 (or pos (js2-current-token-beg))
2045 (or len (js2-current-token-len)))
2046 js2-parsed-errors))
2047
2048 (defun js2-report-error (msg &optional msg-arg pos len)
2049 "Signal a syntax error or record a parse error."
2050 (if js2-recover-from-parse-errors
2051 (js2-record-parse-error msg msg-arg pos len)
2052 (signal 'js2-syntax-error
2053 (list msg
2054 js2-ts-lineno
2055 (save-excursion
2056 (goto-char js2-ts-cursor)
2057 (current-column))
2058 js2-ts-hit-eof))))
2059
2060 (defun js2-report-warning (msg &optional msg-arg pos len face)
2061 (if js2-compiler-report-warning-as-error
2062 (js2-report-error msg msg-arg pos len)
2063 (push (list (list msg msg-arg)
2064 (or pos (js2-current-token-beg))
2065 (or len (js2-current-token-len))
2066 face)
2067 js2-parsed-warnings)))
2068
2069 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2070 (if js2-compiler-strict-mode
2071 (js2-report-warning msg-id msg-arg beg
2072 (and beg end (- end beg)))))
2073
2074 (put 'js2-syntax-error 'error-conditions
2075 '(error syntax-error js2-syntax-error))
2076 (put 'js2-syntax-error 'error-message "Syntax error")
2077
2078 (put 'js2-parse-error 'error-conditions
2079 '(error parse-error js2-parse-error))
2080 (put 'js2-parse-error 'error-message "Parse error")
2081
2082 (defmacro js2-clear-flag (flags flag)
2083 `(setq ,flags (logand ,flags (lognot ,flag))))
2084
2085 (defmacro js2-set-flag (flags flag)
2086 "Logical-or FLAG into FLAGS."
2087 `(setq ,flags (logior ,flags ,flag)))
2088
2089 (defsubst js2-flag-set-p (flags flag)
2090 (/= 0 (logand flags flag)))
2091
2092 (defsubst js2-flag-not-set-p (flags flag)
2093 (zerop (logand flags flag)))
2094
2095 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2096 "Evaluate BODY with the _ character set to be word-syntax."
2097 (declare (indent 0) (debug t))
2098 (let ((old-syntax (make-symbol "old-syntax")))
2099 `(let ((,old-syntax (string (char-syntax ?_))))
2100 (unwind-protect
2101 (progn
2102 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2103 ,@body)
2104 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2105
2106 (defsubst js2-char-uppercase-p (c)
2107 "Return t if C is an uppercase character.
2108 Handles unicode and latin chars properly."
2109 (/= c (downcase c)))
2110
2111 (defsubst js2-char-lowercase-p (c)
2112 "Return t if C is an uppercase character.
2113 Handles unicode and latin chars properly."
2114 (/= c (upcase c)))
2115
2116 ;;; AST struct and function definitions
2117
2118 ;; flags for ast node property 'member-type (used for e4x operators)
2119 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2120 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2121 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2122
2123 (defsubst js2-relpos (pos anchor)
2124 "Convert POS to be relative to ANCHOR.
2125 If POS is nil, returns nil."
2126 (and pos (- pos anchor)))
2127
2128 (defun js2-make-pad (indent)
2129 (if (zerop indent)
2130 ""
2131 (make-string (* indent js2-basic-offset) ? )))
2132
2133 (defun js2-visit-ast (node callback)
2134 "Visit every node in ast NODE with visitor CALLBACK.
2135
2136 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2137 called twice: once to visit the node, and again after all the node's
2138 children have been processed. The END-P argument is nil on the first
2139 call and non-nil on the second call. The return value of the callback
2140 affects the traversal: if non-nil, the children of NODE are processed.
2141 If the callback returns nil, or if the node has no children, then the
2142 callback is called immediately with a non-nil END-P argument.
2143
2144 The node traversal is approximately lexical-order, although there
2145 are currently no guarantees around this."
2146 (when node
2147 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2148 ;; visit the node
2149 (when (funcall callback node nil)
2150 ;; visit the kids
2151 (cond
2152 ((eq vfunc 'js2-visit-none)
2153 nil) ; don't even bother calling it
2154 ;; Each AST node type has to define a `js2-visitor' function
2155 ;; that takes a node and a callback, and calls `js2-visit-ast'
2156 ;; on each child of the node.
2157 (vfunc
2158 (funcall vfunc node callback))
2159 (t
2160 (error "%s does not define a visitor-traversal function"
2161 (aref node 0)))))
2162 ;; call the end-visit
2163 (funcall callback node t))))
2164
2165 (defstruct (js2-node
2166 (:constructor nil)) ; abstract
2167 "Base AST node type."
2168 (type -1) ; token type
2169 (pos -1) ; start position of this AST node in parsed input
2170 (len 1) ; num characters spanned by the node
2171 props ; optional node property list (an alist)
2172 parent) ; link to parent node; null for root
2173
2174 (defsubst js2-node-get-prop (node prop &optional default)
2175 (or (cadr (assoc prop (js2-node-props node))) default))
2176
2177 (defsubst js2-node-set-prop (node prop value)
2178 (setf (js2-node-props node)
2179 (cons (list prop value) (js2-node-props node))))
2180
2181 (defun js2-fixup-starts (n nodes)
2182 "Adjust the start positions of NODES to be relative to N.
2183 Any node in the list may be nil, for convenience."
2184 (dolist (node nodes)
2185 (when node
2186 (setf (js2-node-pos node) (- (js2-node-pos node)
2187 (js2-node-pos n))))))
2188
2189 (defun js2-node-add-children (parent &rest nodes)
2190 "Set parent node of NODES to PARENT, and return PARENT.
2191 Does nothing if we're not recording parent links.
2192 If any given node in NODES is nil, doesn't record that link."
2193 (js2-fixup-starts parent nodes)
2194 (dolist (node nodes)
2195 (and node
2196 (setf (js2-node-parent node) parent))))
2197
2198 ;; Non-recursive since it's called a frightening number of times.
2199 (defun js2-node-abs-pos (n)
2200 (let ((pos (js2-node-pos n)))
2201 (while (setq n (js2-node-parent n))
2202 (setq pos (+ pos (js2-node-pos n))))
2203 pos))
2204
2205 (defsubst js2-node-abs-end (n)
2206 "Return absolute buffer position of end of N."
2207 (+ (js2-node-abs-pos n) (js2-node-len n)))
2208
2209 ;; It's important to make sure block nodes have a Lisp list for the
2210 ;; child nodes, to limit printing recursion depth in an AST that
2211 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2212 ;; a sufficiently large vector tree.
2213
2214 (defstruct (js2-block-node
2215 (:include js2-node)
2216 (:constructor nil)
2217 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2218 (pos (js2-current-token-beg))
2219 len
2220 props
2221 kids)))
2222 "A block of statements."
2223 kids) ; a Lisp list of the child statement nodes
2224
2225 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2226 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2227
2228 (defun js2-visit-block (ast callback)
2229 "Visit the `js2-block-node' children of AST."
2230 (dolist (kid (js2-block-node-kids ast))
2231 (js2-visit-ast kid callback)))
2232
2233 (defun js2-print-block (n i)
2234 (let ((pad (js2-make-pad i)))
2235 (insert pad "{\n")
2236 (dolist (kid (js2-block-node-kids n))
2237 (js2-print-ast kid (1+ i)))
2238 (insert pad "}")))
2239
2240 (defstruct (js2-scope
2241 (:include js2-block-node)
2242 (:constructor nil)
2243 (:constructor make-js2-scope (&key (type js2-BLOCK)
2244 (pos (js2-current-token-beg))
2245 len
2246 kids)))
2247 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2248 ;; I don't have one of those handy, so I'll use an alist for now.
2249 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2250 ;; and is much lighter-weight to construct (both CPU and mem).
2251 ;; The keys are interned strings (symbols) for faster lookup.
2252 ;; Should switch to hybrid alist/hashtable eventually.
2253 symbol-table ; an alist of (symbol . js2-symbol)
2254 parent-scope ; a `js2-scope'
2255 top) ; top-level `js2-scope' (script/function)
2256
2257 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2258 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2259
2260 (defun js2-node-get-enclosing-scope (node)
2261 "Return the innermost `js2-scope' node surrounding NODE.
2262 Returns nil if there is no enclosing scope node."
2263 (let ((parent (js2-node-parent node)))
2264 (while (not (js2-scope-p parent))
2265 (setq parent (js2-node-parent parent)))
2266 parent))
2267
2268 (defun js2-get-defining-scope (scope name)
2269 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2270 Returns `js2-scope' in which NAME is defined, or nil if not found."
2271 (let ((sym (if (symbolp name)
2272 name
2273 (intern name)))
2274 table
2275 result
2276 (continue t))
2277 (while (and scope continue)
2278 (if (and (setq table (js2-scope-symbol-table scope))
2279 (assq sym table))
2280 (setq continue nil
2281 result scope)
2282 (setq scope (js2-scope-parent-scope scope))))
2283 result))
2284
2285 (defun js2-scope-get-symbol (scope name)
2286 "Return symbol table entry for NAME in SCOPE.
2287 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2288 (and (js2-scope-symbol-table scope)
2289 (cdr (assq (if (symbolp name)
2290 name
2291 (intern name))
2292 (js2-scope-symbol-table scope)))))
2293
2294 (defun js2-scope-put-symbol (scope name symbol)
2295 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2296 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2297 (let* ((table (js2-scope-symbol-table scope))
2298 (sym (if (symbolp name) name (intern name)))
2299 (entry (assq sym table)))
2300 (if entry
2301 (setcdr entry symbol)
2302 (push (cons sym symbol)
2303 (js2-scope-symbol-table scope)))))
2304
2305 (defstruct (js2-symbol
2306 (:constructor nil)
2307 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2308 "A symbol table entry."
2309 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2310 ;; js2-LET, or js2-CONST
2311 decl-type
2312 name ; string
2313 ast-node) ; a `js2-node'
2314
2315 (defstruct (js2-error-node
2316 (:include js2-node)
2317 (:constructor nil) ; silence emacs21 byte-compiler
2318 (:constructor make-js2-error-node (&key (type js2-ERROR)
2319 (pos (js2-current-token-beg))
2320 len)))
2321 "AST node representing a parse error.")
2322
2323 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2324 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2325
2326 (defstruct (js2-script-node
2327 (:include js2-scope)
2328 (:constructor nil)
2329 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2330 (pos (js2-current-token-beg))
2331 len
2332 ;; FIXME: What are those?
2333 var-decls
2334 fun-decls)))
2335 functions ; Lisp list of nested functions
2336 regexps ; Lisp list of (string . flags)
2337 symbols ; alist (every symbol gets unique index)
2338 (param-count 0)
2339 var-names ; vector of string names
2340 consts ; bool-vector matching var-decls
2341 (temp-number 0)) ; for generating temp variables
2342
2343 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2344 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2345
2346 (defun js2-print-script (node indent)
2347 (dolist (kid (js2-block-node-kids node))
2348 (js2-print-ast kid indent)))
2349
2350 (defstruct (js2-ast-root
2351 (:include js2-script-node)
2352 (:constructor nil)
2353 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2354 (pos (js2-current-token-beg))
2355 len
2356 buffer)))
2357 "The root node of a js2 AST."
2358 buffer ; the source buffer from which the code was parsed
2359 comments ; a Lisp list of comments, ordered by start position
2360 errors ; a Lisp list of errors found during parsing
2361 warnings ; a Lisp list of warnings found during parsing
2362 node-count) ; number of nodes in the tree, including the root
2363
2364 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2365 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2366
2367 (defun js2-visit-ast-root (ast callback)
2368 (dolist (kid (js2-ast-root-kids ast))
2369 (js2-visit-ast kid callback))
2370 (dolist (comment (js2-ast-root-comments ast))
2371 (js2-visit-ast comment callback)))
2372
2373 (defstruct (js2-comment-node
2374 (:include js2-node)
2375 (:constructor nil)
2376 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2377 (pos (js2-current-token-beg))
2378 len
2379 format)))
2380 format) ; 'line, 'block, 'jsdoc or 'html
2381
2382 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2383 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2384
2385 (defun js2-print-comment (n i)
2386 ;; We really ought to link end-of-line comments to their nodes.
2387 ;; Or maybe we could add a new comment type, 'endline.
2388 (insert (js2-make-pad i)
2389 (js2-node-string n)))
2390
2391 (defstruct (js2-expr-stmt-node
2392 (:include js2-node)
2393 (:constructor nil)
2394 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2395 (pos js2-ts-cursor)
2396 len
2397 expr)))
2398 "An expression statement."
2399 expr)
2400
2401 (defsubst js2-expr-stmt-node-set-has-result (node)
2402 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2403 (setf (js2-node-type node) js2-EXPR_RESULT))
2404
2405 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2406 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2407
2408 (defun js2-visit-expr-stmt-node (n v)
2409 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2410
2411 (defun js2-print-expr-stmt-node (n indent)
2412 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2413 (insert ";\n"))
2414
2415 (defstruct (js2-loop-node
2416 (:include js2-scope)
2417 (:constructor nil))
2418 "Abstract supertype of loop nodes."
2419 body ; a `js2-block-node'
2420 lp ; position of left-paren, nil if omitted
2421 rp) ; position of right-paren, nil if omitted
2422
2423 (defstruct (js2-do-node
2424 (:include js2-loop-node)
2425 (:constructor nil)
2426 (:constructor make-js2-do-node (&key (type js2-DO)
2427 (pos (js2-current-token-beg))
2428 len
2429 body
2430 condition
2431 while-pos
2432 lp
2433 rp)))
2434 "AST node for do-loop."
2435 condition ; while (expression)
2436 while-pos) ; buffer position of 'while' keyword
2437
2438 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2439 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2440
2441 (defun js2-visit-do-node (n v)
2442 (js2-visit-ast (js2-do-node-body n) v)
2443 (js2-visit-ast (js2-do-node-condition n) v))
2444
2445 (defun js2-print-do-node (n i)
2446 (let ((pad (js2-make-pad i)))
2447 (insert pad "do {\n")
2448 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2449 (js2-print-ast kid (1+ i)))
2450 (insert pad "} while (")
2451 (js2-print-ast (js2-do-node-condition n) 0)
2452 (insert ");\n")))
2453
2454 (defstruct (js2-while-node
2455 (:include js2-loop-node)
2456 (:constructor nil)
2457 (:constructor make-js2-while-node (&key (type js2-WHILE)
2458 (pos (js2-current-token-beg))
2459 len body
2460 condition lp
2461 rp)))
2462 "AST node for while-loop."
2463 condition) ; while-condition
2464
2465 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2466 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2467
2468 (defun js2-visit-while-node (n v)
2469 (js2-visit-ast (js2-while-node-condition n) v)
2470 (js2-visit-ast (js2-while-node-body n) v))
2471
2472 (defun js2-print-while-node (n i)
2473 (let ((pad (js2-make-pad i)))
2474 (insert pad "while (")
2475 (js2-print-ast (js2-while-node-condition n) 0)
2476 (insert ") {\n")
2477 (js2-print-body (js2-while-node-body n) (1+ i))
2478 (insert pad "}\n")))
2479
2480 (defstruct (js2-for-node
2481 (:include js2-loop-node)
2482 (:constructor nil)
2483 (:constructor make-js2-for-node (&key (type js2-FOR)
2484 (pos js2-ts-cursor)
2485 len body init
2486 condition
2487 update lp rp)))
2488 "AST node for a C-style for-loop."
2489 init ; initialization expression
2490 condition ; loop condition
2491 update) ; update clause
2492
2493 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2494 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2495
2496 (defun js2-visit-for-node (n v)
2497 (js2-visit-ast (js2-for-node-init n) v)
2498 (js2-visit-ast (js2-for-node-condition n) v)
2499 (js2-visit-ast (js2-for-node-update n) v)
2500 (js2-visit-ast (js2-for-node-body n) v))
2501
2502 (defun js2-print-for-node (n i)
2503 (let ((pad (js2-make-pad i)))
2504 (insert pad "for (")
2505 (js2-print-ast (js2-for-node-init n) 0)
2506 (insert "; ")
2507 (js2-print-ast (js2-for-node-condition n) 0)
2508 (insert "; ")
2509 (js2-print-ast (js2-for-node-update n) 0)
2510 (insert ") {\n")
2511 (js2-print-body (js2-for-node-body n) (1+ i))
2512 (insert pad "}\n")))
2513
2514 (defstruct (js2-for-in-node
2515 (:include js2-loop-node)
2516 (:constructor nil)
2517 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2518 (pos js2-ts-cursor)
2519 len body
2520 iterator
2521 object
2522 in-pos
2523 each-pos
2524 foreach-p forof-p
2525 lp rp)))
2526 "AST node for a for..in loop."
2527 iterator ; [var] foo in ...
2528 object ; object over which we're iterating
2529 in-pos ; buffer position of 'in' keyword
2530 each-pos ; buffer position of 'each' keyword, if foreach-p
2531 foreach-p ; t if it's a for-each loop
2532 forof-p) ; t if it's a for-of loop
2533
2534 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2535 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2536
2537 (defun js2-visit-for-in-node (n v)
2538 (js2-visit-ast (js2-for-in-node-iterator n) v)
2539 (js2-visit-ast (js2-for-in-node-object n) v)
2540 (js2-visit-ast (js2-for-in-node-body n) v))
2541
2542 (defun js2-print-for-in-node (n i)
2543 (let ((pad (js2-make-pad i))
2544 (foreach (js2-for-in-node-foreach-p n))
2545 (forof (js2-for-in-node-forof-p n)))
2546 (insert pad "for ")
2547 (if foreach
2548 (insert "each "))
2549 (insert "(")
2550 (js2-print-ast (js2-for-in-node-iterator n) 0)
2551 (insert (if forof " of " " in "))
2552 (js2-print-ast (js2-for-in-node-object n) 0)
2553 (insert ") {\n")
2554 (js2-print-body (js2-for-in-node-body n) (1+ i))
2555 (insert pad "}\n")))
2556
2557 (defstruct (js2-return-node
2558 (:include js2-node)
2559 (:constructor nil)
2560 (:constructor make-js2-return-node (&key (type js2-RETURN)
2561 (pos js2-ts-cursor)
2562 len
2563 retval)))
2564 "AST node for a return statement."
2565 retval) ; expression to return, or 'undefined
2566
2567 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2568 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2569
2570 (defun js2-visit-return-node (n v)
2571 (js2-visit-ast (js2-return-node-retval n) v))
2572
2573 (defun js2-print-return-node (n i)
2574 (insert (js2-make-pad i) "return")
2575 (when (js2-return-node-retval n)
2576 (insert " ")
2577 (js2-print-ast (js2-return-node-retval n) 0))
2578 (insert ";\n"))
2579
2580 (defstruct (js2-if-node
2581 (:include js2-node)
2582 (:constructor nil)
2583 (:constructor make-js2-if-node (&key (type js2-IF)
2584 (pos js2-ts-cursor)
2585 len condition
2586 then-part
2587 else-pos
2588 else-part lp
2589 rp)))
2590 "AST node for an if-statement."
2591 condition ; expression
2592 then-part ; statement or block
2593 else-pos ; optional buffer position of 'else' keyword
2594 else-part ; optional statement or block
2595 lp ; position of left-paren, nil if omitted
2596 rp) ; position of right-paren, nil if omitted
2597
2598 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2599 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2600
2601 (defun js2-visit-if-node (n v)
2602 (js2-visit-ast (js2-if-node-condition n) v)
2603 (js2-visit-ast (js2-if-node-then-part n) v)
2604 (js2-visit-ast (js2-if-node-else-part n) v))
2605
2606 (defun js2-print-if-node (n i)
2607 (let ((pad (js2-make-pad i))
2608 (then-part (js2-if-node-then-part n))
2609 (else-part (js2-if-node-else-part n)))
2610 (insert pad "if (")
2611 (js2-print-ast (js2-if-node-condition n) 0)
2612 (insert ") {\n")
2613 (js2-print-body then-part (1+ i))
2614 (insert pad "}")
2615 (cond
2616 ((not else-part)
2617 (insert "\n"))
2618 ((js2-if-node-p else-part)
2619 (insert " else ")
2620 (js2-print-body else-part i))
2621 (t
2622 (insert " else {\n")
2623 (js2-print-body else-part (1+ i))
2624 (insert pad "}\n")))))
2625
2626 (defstruct (js2-try-node
2627 (:include js2-node)
2628 (:constructor nil)
2629 (:constructor make-js2-try-node (&key (type js2-TRY)
2630 (pos js2-ts-cursor)
2631 len
2632 try-block
2633 catch-clauses
2634 finally-block)))
2635 "AST node for a try-statement."
2636 try-block
2637 catch-clauses ; a Lisp list of `js2-catch-node'
2638 finally-block) ; a `js2-finally-node'
2639
2640 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2641 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2642
2643 (defun js2-visit-try-node (n v)
2644 (js2-visit-ast (js2-try-node-try-block n) v)
2645 (dolist (clause (js2-try-node-catch-clauses n))
2646 (js2-visit-ast clause v))
2647 (js2-visit-ast (js2-try-node-finally-block n) v))
2648
2649 (defun js2-print-try-node (n i)
2650 (let ((pad (js2-make-pad i))
2651 (catches (js2-try-node-catch-clauses n))
2652 (finally (js2-try-node-finally-block n)))
2653 (insert pad "try {\n")
2654 (js2-print-body (js2-try-node-try-block n) (1+ i))
2655 (insert pad "}")
2656 (when catches
2657 (dolist (catch catches)
2658 (js2-print-ast catch i)))
2659 (if finally
2660 (js2-print-ast finally i)
2661 (insert "\n"))))
2662
2663 (defstruct (js2-catch-node
2664 (:include js2-node)
2665 (:constructor nil)
2666 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2667 (pos js2-ts-cursor)
2668 len
2669 param
2670 guard-kwd
2671 guard-expr
2672 block lp
2673 rp)))
2674 "AST node for a catch clause."
2675 param ; destructuring form or simple name node
2676 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2677 guard-expr ; catch condition, a `js2-node'
2678 block ; statements, a `js2-block-node'
2679 lp ; buffer position of left-paren, nil if omitted
2680 rp) ; buffer position of right-paren, nil if omitted
2681
2682 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2683 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2684
2685 (defun js2-visit-catch-node (n v)
2686 (js2-visit-ast (js2-catch-node-param n) v)
2687 (when (js2-catch-node-guard-kwd n)
2688 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2689 (js2-visit-ast (js2-catch-node-block n) v))
2690
2691 (defun js2-print-catch-node (n i)
2692 (let ((pad (js2-make-pad i))
2693 (guard-kwd (js2-catch-node-guard-kwd n))
2694 (guard-expr (js2-catch-node-guard-expr n)))
2695 (insert " catch (")
2696 (js2-print-ast (js2-catch-node-param n) 0)
2697 (when guard-kwd
2698 (insert " if ")
2699 (js2-print-ast guard-expr 0))
2700 (insert ") {\n")
2701 (js2-print-body (js2-catch-node-block n) (1+ i))
2702 (insert pad "}")))
2703
2704 (defstruct (js2-finally-node
2705 (:include js2-node)
2706 (:constructor nil)
2707 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2708 (pos js2-ts-cursor)
2709 len body)))
2710 "AST node for a finally clause."
2711 body) ; a `js2-node', often but not always a block node
2712
2713 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2714 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2715
2716 (defun js2-visit-finally-node (n v)
2717 (js2-visit-ast (js2-finally-node-body n) v))
2718
2719 (defun js2-print-finally-node (n i)
2720 (let ((pad (js2-make-pad i)))
2721 (insert " finally {\n")
2722 (js2-print-body (js2-finally-node-body n) (1+ i))
2723 (insert pad "}\n")))
2724
2725 (defstruct (js2-switch-node
2726 (:include js2-node)
2727 (:constructor nil)
2728 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2729 (pos js2-ts-cursor)
2730 len
2731 discriminant
2732 cases lp
2733 rp)))
2734 "AST node for a switch statement."
2735 discriminant ; a `js2-node' (switch expression)
2736 cases ; a Lisp list of `js2-case-node'
2737 lp ; position of open-paren for discriminant, nil if omitted
2738 rp) ; position of close-paren for discriminant, nil if omitted
2739
2740 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2741 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2742
2743 (defun js2-visit-switch-node (n v)
2744 (js2-visit-ast (js2-switch-node-discriminant n) v)
2745 (dolist (c (js2-switch-node-cases n))
2746 (js2-visit-ast c v)))
2747
2748 (defun js2-print-switch-node (n i)
2749 (let ((pad (js2-make-pad i))
2750 (cases (js2-switch-node-cases n)))
2751 (insert pad "switch (")
2752 (js2-print-ast (js2-switch-node-discriminant n) 0)
2753 (insert ") {\n")
2754 (dolist (case cases)
2755 (js2-print-ast case i))
2756 (insert pad "}\n")))
2757
2758 (defstruct (js2-case-node
2759 (:include js2-block-node)
2760 (:constructor nil)
2761 (:constructor make-js2-case-node (&key (type js2-CASE)
2762 (pos js2-ts-cursor)
2763 len kids expr)))
2764 "AST node for a case clause of a switch statement."
2765 expr) ; the case expression (nil for default)
2766
2767 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2768 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2769
2770 (defun js2-visit-case-node (n v)
2771 (js2-visit-ast (js2-case-node-expr n) v)
2772 (js2-visit-block n v))
2773
2774 (defun js2-print-case-node (n i)
2775 (let ((pad (js2-make-pad i))
2776 (expr (js2-case-node-expr n)))
2777 (insert pad)
2778 (if (null expr)
2779 (insert "default:\n")
2780 (insert "case ")
2781 (js2-print-ast expr 0)
2782 (insert ":\n"))
2783 (dolist (kid (js2-case-node-kids n))
2784 (js2-print-ast kid (1+ i)))))
2785
2786 (defstruct (js2-throw-node
2787 (:include js2-node)
2788 (:constructor nil)
2789 (:constructor make-js2-throw-node (&key (type js2-THROW)
2790 (pos js2-ts-cursor)
2791 len expr)))
2792 "AST node for a throw statement."
2793 expr) ; the expression to throw
2794
2795 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2796 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2797
2798 (defun js2-visit-throw-node (n v)
2799 (js2-visit-ast (js2-throw-node-expr n) v))
2800
2801 (defun js2-print-throw-node (n i)
2802 (insert (js2-make-pad i) "throw ")
2803 (js2-print-ast (js2-throw-node-expr n) 0)
2804 (insert ";\n"))
2805
2806 (defstruct (js2-with-node
2807 (:include js2-node)
2808 (:constructor nil)
2809 (:constructor make-js2-with-node (&key (type js2-WITH)
2810 (pos js2-ts-cursor)
2811 len object
2812 body lp rp)))
2813 "AST node for a with-statement."
2814 object
2815 body
2816 lp ; buffer position of left-paren around object, nil if omitted
2817 rp) ; buffer position of right-paren around object, nil if omitted
2818
2819 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2820 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2821
2822 (defun js2-visit-with-node (n v)
2823 (js2-visit-ast (js2-with-node-object n) v)
2824 (js2-visit-ast (js2-with-node-body n) v))
2825
2826 (defun js2-print-with-node (n i)
2827 (let ((pad (js2-make-pad i)))
2828 (insert pad "with (")
2829 (js2-print-ast (js2-with-node-object n) 0)
2830 (insert ") {\n")
2831 (js2-print-body (js2-with-node-body n) (1+ i))
2832 (insert pad "}\n")))
2833
2834 (defstruct (js2-label-node
2835 (:include js2-node)
2836 (:constructor nil)
2837 (:constructor make-js2-label-node (&key (type js2-LABEL)
2838 (pos js2-ts-cursor)
2839 len name)))
2840 "AST node for a statement label or case label."
2841 name ; a string
2842 loop) ; for validating and code-generating continue-to-label
2843
2844 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2845 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2846
2847 (defun js2-print-label (n i)
2848 (insert (js2-make-pad i)
2849 (js2-label-node-name n)
2850 ":\n"))
2851
2852 (defstruct (js2-labeled-stmt-node
2853 (:include js2-node)
2854 (:constructor nil)
2855 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2856 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2857 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2858 (pos js2-ts-cursor)
2859 len labels stmt)))
2860 "AST node for a statement with one or more labels.
2861 Multiple labels for a statement are collapsed into the labels field."
2862 labels ; Lisp list of `js2-label-node'
2863 stmt) ; the statement these labels are for
2864
2865 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2866 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2867
2868 (defun js2-get-label-by-name (lbl-stmt name)
2869 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2870 Returns nil if no such label is in the list."
2871 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2872 result)
2873 (while (and label-list (not result))
2874 (if (string= (js2-label-node-name (car label-list)) name)
2875 (setq result (car label-list))
2876 (setq label-list (cdr label-list))))
2877 result))
2878
2879 (defun js2-visit-labeled-stmt (n v)
2880 (dolist (label (js2-labeled-stmt-node-labels n))
2881 (js2-visit-ast label v))
2882 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2883
2884 (defun js2-print-labeled-stmt (n i)
2885 (dolist (label (js2-labeled-stmt-node-labels n))
2886 (js2-print-ast label i))
2887 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
2888
2889 (defun js2-labeled-stmt-node-contains (node label)
2890 "Return t if NODE contains LABEL in its label set.
2891 NODE is a `js2-labels-node'. LABEL is an identifier."
2892 (loop for nl in (js2-labeled-stmt-node-labels node)
2893 if (string= label (js2-label-node-name nl))
2894 return t
2895 finally return nil))
2896
2897 (defsubst js2-labeled-stmt-node-add-label (node label)
2898 "Add a `js2-label-node' to the label set for this statement."
2899 (setf (js2-labeled-stmt-node-labels node)
2900 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2901
2902 (defstruct (js2-jump-node
2903 (:include js2-node)
2904 (:constructor nil))
2905 "Abstract supertype of break and continue nodes."
2906 label ; `js2-name-node' for location of label identifier, if present
2907 target) ; target js2-labels-node or loop/switch statement
2908
2909 (defun js2-visit-jump-node (n v)
2910 ;; We don't visit the target, since it's a back-link.
2911 (js2-visit-ast (js2-jump-node-label n) v))
2912
2913 (defstruct (js2-break-node
2914 (:include js2-jump-node)
2915 (:constructor nil)
2916 (:constructor make-js2-break-node (&key (type js2-BREAK)
2917 (pos js2-ts-cursor)
2918 len label target)))
2919 "AST node for a break statement.
2920 The label field is a `js2-name-node', possibly nil, for the named label
2921 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2922 is the target of the break - a label node or enclosing loop/switch statement.")
2923
2924 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2925 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2926
2927 (defun js2-print-break-node (n i)
2928 (insert (js2-make-pad i) "break")
2929 (when (js2-break-node-label n)
2930 (insert " ")
2931 (js2-print-ast (js2-break-node-label n) 0))
2932 (insert ";\n"))
2933
2934 (defstruct (js2-continue-node
2935 (:include js2-jump-node)
2936 (:constructor nil)
2937 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2938 (pos js2-ts-cursor)
2939 len label target)))
2940 "AST node for a continue statement.
2941 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2942 It is nil if continue specifies no label. The target field is the jump target:
2943 a `js2-label-node' or the innermost enclosing loop.")
2944
2945 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2946 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2947
2948 (defun js2-print-continue-node (n i)
2949 (insert (js2-make-pad i) "continue")
2950 (when (js2-continue-node-label n)
2951 (insert " ")
2952 (js2-print-ast (js2-continue-node-label n) 0))
2953 (insert ";\n"))
2954
2955 (defstruct (js2-function-node
2956 (:include js2-script-node)
2957 (:constructor nil)
2958 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2959 (pos js2-ts-cursor)
2960 len
2961 (ftype 'FUNCTION)
2962 (form 'FUNCTION_STATEMENT)
2963 (name "")
2964 params rest-p
2965 body
2966 generator-type
2967 lp rp)))
2968 "AST node for a function declaration.
2969 The `params' field is a Lisp list of nodes. Each node is either a simple
2970 `js2-name-node', or if it's a destructuring-assignment parameter, a
2971 `js2-array-node' or `js2-object-node'."
2972 ftype ; FUNCTION, GETTER or SETTER
2973 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
2974 name ; function name (a `js2-name-node', or nil if anonymous)
2975 params ; a Lisp list of destructuring forms or simple name nodes
2976 rest-p ; if t, the last parameter is rest parameter
2977 body ; a `js2-block-node' or expression node (1.8 only)
2978 lp ; position of arg-list open-paren, or nil if omitted
2979 rp ; position of arg-list close-paren, or nil if omitted
2980 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2981 needs-activation ; t if we need an activation object for this frame
2982 generator-type ; STAR, LEGACY or nil
2983 member-expr) ; nonstandard Ecma extension from Rhino
2984
2985 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2986 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2987
2988 (defun js2-visit-function-node (n v)
2989 (js2-visit-ast (js2-function-node-name n) v)
2990 (dolist (p (js2-function-node-params n))
2991 (js2-visit-ast p v))
2992 (js2-visit-ast (js2-function-node-body n) v))
2993
2994 (defun js2-print-function-node (n i)
2995 (let* ((pad (js2-make-pad i))
2996 (getter (js2-node-get-prop n 'GETTER_SETTER))
2997 (name (or (js2-function-node-name n)
2998 (js2-function-node-member-expr n)))
2999 (params (js2-function-node-params n))
3000 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3001 (rest-p (js2-function-node-rest-p n))
3002 (body (js2-function-node-body n))
3003 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3004 (unless (or getter arrow)
3005 (insert pad "function")
3006 (when (eq (js2-function-node-generator-type n) 'STAR)
3007 (insert "*")))
3008 (when name
3009 (insert " ")
3010 (js2-print-ast name 0))
3011 (insert "(")
3012 (loop with len = (length params)
3013 for param in params
3014 for count from 1
3015 do
3016 (when (and rest-p (= count len))
3017 (insert "..."))
3018 (js2-print-ast param 0)
3019 (when (< count len)
3020 (insert ", ")))
3021 (insert ") ")
3022 (when arrow
3023 (insert "=> "))
3024 (insert "{")
3025 ;; TODO: fix this to be smarter about indenting, etc.
3026 (unless expr
3027 (insert "\n"))
3028 (if (js2-block-node-p body)
3029 (js2-print-body body (1+ i))
3030 (js2-print-ast body 0))
3031 (insert pad "}")
3032 (unless expr
3033 (insert "\n"))))
3034
3035 (defun js2-function-name (node)
3036 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3037 (and (js2-function-node-name node)
3038 (js2-name-node-name (js2-function-node-name node))))
3039
3040 ;; Having this be an expression node makes it more flexible.
3041 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3042 ;; that work better if you assume it's an expression. Whenever we have
3043 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3044 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3045 (defstruct (js2-var-decl-node
3046 (:include js2-node)
3047 (:constructor nil)
3048 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3049 (pos (js2-current-token-beg))
3050 len kids
3051 decl-type)))
3052 "AST node for a variable declaration list (VAR, CONST or LET).
3053 The node bounds differ depending on the declaration type. For VAR or
3054 CONST declarations, the bounds include the var/const keyword. For LET
3055 declarations, the node begins at the position of the first child."
3056 kids ; a Lisp list of `js2-var-init-node' structs.
3057 decl-type) ; js2-VAR, js2-CONST or js2-LET
3058
3059 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3060 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3061
3062 (defun js2-visit-var-decl (n v)
3063 (dolist (kid (js2-var-decl-node-kids n))
3064 (js2-visit-ast kid v)))
3065
3066 (defun js2-print-var-decl (n i)
3067 (let ((pad (js2-make-pad i))
3068 (tt (js2-var-decl-node-decl-type n)))
3069 (insert pad)
3070 (insert (cond
3071 ((= tt js2-VAR) "var ")
3072 ((= tt js2-LET) "let ")
3073 ((= tt js2-CONST) "const ")
3074 (t
3075 (error "malformed var-decl node"))))
3076 (loop with kids = (js2-var-decl-node-kids n)
3077 with len = (length kids)
3078 for kid in kids
3079 for count from 1
3080 do
3081 (js2-print-ast kid 0)
3082 (if (< count len)
3083 (insert ", ")))))
3084
3085 (defstruct (js2-var-init-node
3086 (:include js2-node)
3087 (:constructor nil)
3088 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3089 (pos js2-ts-cursor)
3090 len target
3091 initializer)))
3092 "AST node for a variable declaration.
3093 The type field will be js2-CONST for a const decl."
3094 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3095 initializer) ; initializer expression, a `js2-node'
3096
3097 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3098 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3099
3100 (defun js2-visit-var-init-node (n v)
3101 (js2-visit-ast (js2-var-init-node-target n) v)
3102 (js2-visit-ast (js2-var-init-node-initializer n) v))
3103
3104 (defun js2-print-var-init-node (n i)
3105 (let ((pad (js2-make-pad i))
3106 (name (js2-var-init-node-target n))
3107 (init (js2-var-init-node-initializer n)))
3108 (insert pad)
3109 (js2-print-ast name 0)
3110 (when init
3111 (insert " = ")
3112 (js2-print-ast init 0))))
3113
3114 (defstruct (js2-cond-node
3115 (:include js2-node)
3116 (:constructor nil)
3117 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3118 (pos js2-ts-cursor)
3119 len
3120 test-expr
3121 true-expr
3122 false-expr
3123 q-pos c-pos)))
3124 "AST node for the ternary operator"
3125 test-expr
3126 true-expr
3127 false-expr
3128 q-pos ; buffer position of ?
3129 c-pos) ; buffer position of :
3130
3131 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3132 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3133
3134 (defun js2-visit-cond-node (n v)
3135 (js2-visit-ast (js2-cond-node-test-expr n) v)
3136 (js2-visit-ast (js2-cond-node-true-expr n) v)
3137 (js2-visit-ast (js2-cond-node-false-expr n) v))
3138
3139 (defun js2-print-cond-node (n i)
3140 (let ((pad (js2-make-pad i)))
3141 (insert pad)
3142 (js2-print-ast (js2-cond-node-test-expr n) 0)
3143 (insert " ? ")
3144 (js2-print-ast (js2-cond-node-true-expr n) 0)
3145 (insert " : ")
3146 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3147
3148 (defstruct (js2-infix-node
3149 (:include js2-node)
3150 (:constructor nil)
3151 (:constructor make-js2-infix-node (&key type
3152 (pos js2-ts-cursor)
3153 len op-pos
3154 left right)))
3155 "Represents infix expressions.
3156 Includes assignment ops like `|=', and the comma operator.
3157 The type field inherited from `js2-node' holds the operator."
3158 op-pos ; buffer position where operator begins
3159 left ; any `js2-node'
3160 right) ; any `js2-node'
3161
3162 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3163 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3164
3165 (defun js2-visit-infix-node (n v)
3166 (js2-visit-ast (js2-infix-node-left n) v)
3167 (js2-visit-ast (js2-infix-node-right n) v))
3168
3169 (defconst js2-operator-tokens
3170 (let ((table (make-hash-table :test 'eq))
3171 (tokens
3172 (list (cons js2-IN "in")
3173 (cons js2-TYPEOF "typeof")
3174 (cons js2-INSTANCEOF "instanceof")
3175 (cons js2-DELPROP "delete")
3176 (cons js2-COMMA ",")
3177 (cons js2-COLON ":")
3178 (cons js2-OR "||")
3179 (cons js2-AND "&&")
3180 (cons js2-INC "++")
3181 (cons js2-DEC "--")
3182 (cons js2-BITOR "|")
3183 (cons js2-BITXOR "^")
3184 (cons js2-BITAND "&")
3185 (cons js2-EQ "==")
3186 (cons js2-NE "!=")
3187 (cons js2-LT "<")
3188 (cons js2-LE "<=")
3189 (cons js2-GT ">")
3190 (cons js2-GE ">=")
3191 (cons js2-LSH "<<")
3192 (cons js2-RSH ">>")
3193 (cons js2-URSH ">>>")
3194 (cons js2-ADD "+") ; infix plus
3195 (cons js2-SUB "-") ; infix minus
3196 (cons js2-MUL "*")
3197 (cons js2-DIV "/")
3198 (cons js2-MOD "%")
3199 (cons js2-NOT "!")
3200 (cons js2-BITNOT "~")
3201 (cons js2-POS "+") ; unary plus
3202 (cons js2-NEG "-") ; unary minus
3203 (cons js2-SHEQ "===") ; shallow equality
3204 (cons js2-SHNE "!==") ; shallow inequality
3205 (cons js2-ASSIGN "=")
3206 (cons js2-ASSIGN_BITOR "|=")
3207 (cons js2-ASSIGN_BITXOR "^=")
3208 (cons js2-ASSIGN_BITAND "&=")
3209 (cons js2-ASSIGN_LSH "<<=")
3210 (cons js2-ASSIGN_RSH ">>=")
3211 (cons js2-ASSIGN_URSH ">>>=")
3212 (cons js2-ASSIGN_ADD "+=")
3213 (cons js2-ASSIGN_SUB "-=")
3214 (cons js2-ASSIGN_MUL "*=")
3215 (cons js2-ASSIGN_DIV "/=")
3216 (cons js2-ASSIGN_MOD "%="))))
3217 (loop for (k . v) in tokens do
3218 (puthash k v table))
3219 table))
3220
3221 (defun js2-print-infix-node (n i)
3222 (let* ((tt (js2-node-type n))
3223 (op (gethash tt js2-operator-tokens)))
3224 (unless op
3225 (error "unrecognized infix operator %s" (js2-node-type n)))
3226 (insert (js2-make-pad i))
3227 (js2-print-ast (js2-infix-node-left n) 0)
3228 (unless (= tt js2-COMMA)
3229 (insert " "))
3230 (insert op)
3231 (insert " ")
3232 (js2-print-ast (js2-infix-node-right n) 0)))
3233
3234 (defstruct (js2-assign-node
3235 (:include js2-infix-node)
3236 (:constructor nil)
3237 (:constructor make-js2-assign-node (&key type
3238 (pos js2-ts-cursor)
3239 len op-pos
3240 left right)))
3241 "Represents any assignment.
3242 The type field holds the actual assignment operator.")
3243
3244 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3245 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3246
3247 (defstruct (js2-unary-node
3248 (:include js2-node)
3249 (:constructor nil)
3250 (:constructor make-js2-unary-node (&key type ; required
3251 (pos js2-ts-cursor)
3252 len operand)))
3253 "AST node type for unary operator nodes.
3254 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3255 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3256 property is added if the operator follows the operand."
3257 operand) ; a `js2-node' expression
3258
3259 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3260 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3261
3262 (defun js2-visit-unary-node (n v)
3263 (js2-visit-ast (js2-unary-node-operand n) v))
3264
3265 (defun js2-print-unary-node (n i)
3266 (let* ((tt (js2-node-type n))
3267 (op (gethash tt js2-operator-tokens))
3268 (postfix (js2-node-get-prop n 'postfix)))
3269 (unless op
3270 (error "unrecognized unary operator %s" tt))
3271 (insert (js2-make-pad i))
3272 (unless postfix
3273 (insert op))
3274 (if (or (= tt js2-TYPEOF)
3275 (= tt js2-DELPROP))
3276 (insert " "))
3277 (js2-print-ast (js2-unary-node-operand n) 0)
3278 (when postfix
3279 (insert op))))
3280
3281 (defstruct (js2-let-node
3282 (:include js2-scope)
3283 (:constructor nil)
3284 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3285 (pos (js2-current-token-beg))
3286 len vars body
3287 lp rp)))
3288 "AST node for a let expression or a let statement.
3289 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3290 vars ; a `js2-var-decl-node'
3291 body ; a `js2-node' representing the expression or body block
3292 lp
3293 rp)
3294
3295 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3296 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3297
3298 (defun js2-visit-let-node (n v)
3299 (js2-visit-ast (js2-let-node-vars n) v)
3300 (js2-visit-ast (js2-let-node-body n) v))
3301
3302 (defun js2-print-let-node (n i)
3303 (insert (js2-make-pad i) "let (")
3304 (js2-print-ast (js2-let-node-vars n) 0)
3305 (insert ") ")
3306 (js2-print-ast (js2-let-node-body n) i))
3307
3308 (defstruct (js2-keyword-node
3309 (:include js2-node)
3310 (:constructor nil)
3311 (:constructor make-js2-keyword-node (&key type
3312 (pos (js2-current-token-beg))
3313 (len (- js2-ts-cursor pos)))))
3314 "AST node representing a literal keyword such as `null'.
3315 Used for `null', `this', `true', `false' and `debugger'.
3316 The node type is set to js2-NULL, js2-THIS, etc.")
3317
3318 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3319 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3320
3321 (defun js2-print-keyword-node (n i)
3322 (insert (js2-make-pad i)
3323 (let ((tt (js2-node-type n)))
3324 (cond
3325 ((= tt js2-THIS) "this")
3326 ((= tt js2-NULL) "null")
3327 ((= tt js2-TRUE) "true")
3328 ((= tt js2-FALSE) "false")
3329 ((= tt js2-DEBUGGER) "debugger")
3330 (t (error "Invalid keyword literal type: %d" tt))))))
3331
3332 (defsubst js2-this-node-p (node)
3333 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3334 (eq (js2-node-type node) js2-THIS))
3335
3336 (defstruct (js2-new-node
3337 (:include js2-node)
3338 (:constructor nil)
3339 (:constructor make-js2-new-node (&key (type js2-NEW)
3340 (pos (js2-current-token-beg))
3341 len target
3342 args initializer
3343 lp rp)))
3344 "AST node for new-expression such as new Foo()."
3345 target ; an identifier or reference
3346 args ; a Lisp list of argument nodes
3347 lp ; position of left-paren, nil if omitted
3348 rp ; position of right-paren, nil if omitted
3349 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3350
3351 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3352 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3353
3354 (defun js2-visit-new-node (n v)
3355 (js2-visit-ast (js2-new-node-target n) v)
3356 (dolist (arg (js2-new-node-args n))
3357 (js2-visit-ast arg v))
3358 (js2-visit-ast (js2-new-node-initializer n) v))
3359
3360 (defun js2-print-new-node (n i)
3361 (insert (js2-make-pad i) "new ")
3362 (js2-print-ast (js2-new-node-target n))
3363 (insert "(")
3364 (js2-print-list (js2-new-node-args n))
3365 (insert ")")
3366 (when (js2-new-node-initializer n)
3367 (insert " ")
3368 (js2-print-ast (js2-new-node-initializer n))))
3369
3370 (defstruct (js2-name-node
3371 (:include js2-node)
3372 (:constructor nil)
3373 (:constructor make-js2-name-node (&key (type js2-NAME)
3374 (pos (js2-current-token-beg))
3375 (len (- js2-ts-cursor
3376 (js2-current-token-beg)))
3377 (name (js2-current-token-string)))))
3378 "AST node for a JavaScript identifier"
3379 name ; a string
3380 scope) ; a `js2-scope' (optional, used for codegen)
3381
3382 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3383 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3384
3385 (defun js2-print-name-node (n i)
3386 (insert (js2-make-pad i)
3387 (js2-name-node-name n)))
3388
3389 (defsubst js2-name-node-length (node)
3390 "Return identifier length of NODE, a `js2-name-node'.
3391 Returns 0 if NODE is nil or its identifier field is nil."
3392 (if node
3393 (length (js2-name-node-name node))
3394 0))
3395
3396 (defstruct (js2-number-node
3397 (:include js2-node)
3398 (:constructor nil)
3399 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3400 (pos (js2-current-token-beg))
3401 (len (- js2-ts-cursor
3402 (js2-current-token-beg)))
3403 (value (js2-current-token-string))
3404 (num-value (js2-token-number
3405 (js2-current-token))))))
3406 "AST node for a number literal."
3407 value ; the original string, e.g. "6.02e23"
3408 num-value) ; the parsed number value
3409
3410 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3411 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3412
3413 (defun js2-print-number-node (n i)
3414 (insert (js2-make-pad i)
3415 (number-to-string (js2-number-node-num-value n))))
3416
3417 (defstruct (js2-regexp-node
3418 (:include js2-node)
3419 (:constructor nil)
3420 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3421 (pos (js2-current-token-beg))
3422 (len (- js2-ts-cursor
3423 (js2-current-token-beg)))
3424 value flags)))
3425 "AST node for a regular expression literal."
3426 value ; the regexp string, without // delimiters
3427 flags) ; a string of flags, e.g. `mi'.
3428
3429 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3430 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3431
3432 (defun js2-print-regexp (n i)
3433 (insert (js2-make-pad i)
3434 "/"
3435 (js2-regexp-node-value n)
3436 "/")
3437 (if (js2-regexp-node-flags n)
3438 (insert (js2-regexp-node-flags n))))
3439
3440 (defstruct (js2-string-node
3441 (:include js2-node)
3442 (:constructor nil)
3443 (:constructor make-js2-string-node (&key (type js2-STRING)
3444 (pos (js2-current-token-beg))
3445 (len (- js2-ts-cursor
3446 (js2-current-token-beg)))
3447 (value (js2-current-token-string)))))
3448 "String literal.
3449 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3450 You can tell the quote type by looking at the first character."
3451 value) ; the characters of the string, including the quotes
3452
3453 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3454 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3455
3456 (defun js2-print-string-node (n i)
3457 (insert (js2-make-pad i)
3458 (js2-node-string n)))
3459
3460 (defstruct (js2-array-node
3461 (:include js2-node)
3462 (:constructor nil)
3463 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3464 (pos js2-ts-cursor)
3465 len elems)))
3466 "AST node for an array literal."
3467 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3468
3469 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3470 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3471
3472 (defun js2-visit-array-node (n v)
3473 (dolist (e (js2-array-node-elems n))
3474 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3475
3476 (defun js2-print-array-node (n i)
3477 (insert (js2-make-pad i) "[")
3478 (js2-print-list (js2-array-node-elems n))
3479 (insert "]"))
3480
3481 (defstruct (js2-object-node
3482 (:include js2-node)
3483 (:constructor nil)
3484 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3485 (pos js2-ts-cursor)
3486 len
3487 elems)))
3488 "AST node for an object literal expression.
3489 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3490 The latter represents abbreviation in destructuring expressions."
3491 elems)
3492
3493 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3494 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3495
3496 (defun js2-visit-object-node (n v)
3497 (dolist (e (js2-object-node-elems n))
3498 (js2-visit-ast e v)))
3499
3500 (defun js2-print-object-node (n i)
3501 (insert (js2-make-pad i) "{")
3502 (js2-print-list (js2-object-node-elems n))
3503 (insert "}"))
3504
3505 (defstruct (js2-object-prop-node
3506 (:include js2-infix-node)
3507 (:constructor nil)
3508 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3509 (pos js2-ts-cursor)
3510 len left
3511 right op-pos)))
3512 "AST node for an object literal prop:value entry.
3513 The `left' field is the property: a name node, string node or number node.
3514 The `right' field is a `js2-node' representing the initializer value.")
3515
3516 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3517 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3518
3519 (defun js2-print-object-prop-node (n i)
3520 (insert (js2-make-pad i))
3521 (js2-print-ast (js2-object-prop-node-left n) 0)
3522 (insert ": ")
3523 (js2-print-ast (js2-object-prop-node-right n) 0))
3524
3525 (defstruct (js2-getter-setter-node
3526 (:include js2-infix-node)
3527 (:constructor nil)
3528 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3529 (pos js2-ts-cursor)
3530 len left right)))
3531 "AST node for a getter/setter property in an object literal.
3532 The `left' field is the `js2-name-node' naming the getter/setter prop.
3533 The `right' field is always an anonymous `js2-function-node' with a node
3534 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3535
3536 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3537 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3538
3539 (defun js2-print-getter-setter (n i)
3540 (let ((pad (js2-make-pad i))
3541 (left (js2-getter-setter-node-left n))
3542 (right (js2-getter-setter-node-right n)))
3543 (insert pad)
3544 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3545 (js2-print-ast left 0)
3546 (js2-print-ast right 0)))
3547
3548 (defstruct (js2-prop-get-node
3549 (:include js2-infix-node)
3550 (:constructor nil)
3551 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3552 (pos js2-ts-cursor)
3553 len left right)))
3554 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3555
3556 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3557 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3558
3559 (defun js2-visit-prop-get-node (n v)
3560 (js2-visit-ast (js2-prop-get-node-left n) v)
3561 (js2-visit-ast (js2-prop-get-node-right n) v))
3562
3563 (defun js2-print-prop-get-node (n i)
3564 (insert (js2-make-pad i))
3565 (js2-print-ast (js2-prop-get-node-left n) 0)
3566 (insert ".")
3567 (js2-print-ast (js2-prop-get-node-right n) 0))
3568
3569 (defstruct (js2-elem-get-node
3570 (:include js2-node)
3571 (:constructor nil)
3572 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3573 (pos js2-ts-cursor)
3574 len target element
3575 lb rb)))
3576 "AST node for an array index expression such as foo[bar]."
3577 target ; a `js2-node' - the expression preceding the "."
3578 element ; a `js2-node' - the expression in brackets
3579 lb ; position of left-bracket, nil if omitted
3580 rb) ; position of right-bracket, nil if omitted
3581
3582 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3583 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3584
3585 (defun js2-visit-elem-get-node (n v)
3586 (js2-visit-ast (js2-elem-get-node-target n) v)
3587 (js2-visit-ast (js2-elem-get-node-element n) v))
3588
3589 (defun js2-print-elem-get-node (n i)
3590 (insert (js2-make-pad i))
3591 (js2-print-ast (js2-elem-get-node-target n) 0)
3592 (insert "[")
3593 (js2-print-ast (js2-elem-get-node-element n) 0)
3594 (insert "]"))
3595
3596 (defstruct (js2-call-node
3597 (:include js2-node)
3598 (:constructor nil)
3599 (:constructor make-js2-call-node (&key (type js2-CALL)
3600 (pos js2-ts-cursor)
3601 len target args
3602 lp rp)))
3603 "AST node for a JavaScript function call."
3604 target ; a `js2-node' evaluating to the function to call
3605 args ; a Lisp list of `js2-node' arguments
3606 lp ; position of open-paren, or nil if missing
3607 rp) ; position of close-paren, or nil if missing
3608
3609 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3610 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3611
3612 (defun js2-visit-call-node (n v)
3613 (js2-visit-ast (js2-call-node-target n) v)
3614 (dolist (arg (js2-call-node-args n))
3615 (js2-visit-ast arg v)))
3616
3617 (defun js2-print-call-node (n i)
3618 (insert (js2-make-pad i))
3619 (js2-print-ast (js2-call-node-target n) 0)
3620 (insert "(")
3621 (js2-print-list (js2-call-node-args n))
3622 (insert ")"))
3623
3624 (defstruct (js2-yield-node
3625 (:include js2-node)
3626 (:constructor nil)
3627 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3628 (pos js2-ts-cursor)
3629 len value)))
3630 "AST node for yield statement or expression."
3631 value) ; optional: value to be yielded
3632
3633 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3634 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3635
3636 (defun js2-visit-yield-node (n v)
3637 (js2-visit-ast (js2-yield-node-value n) v))
3638
3639 (defun js2-print-yield-node (n i)
3640 (insert (js2-make-pad i))
3641 (insert "yield")
3642 (when (js2-yield-node-value n)
3643 (insert " ")
3644 (js2-print-ast (js2-yield-node-value n) 0)))
3645
3646 (defstruct (js2-paren-node
3647 (:include js2-node)
3648 (:constructor nil)
3649 (:constructor make-js2-paren-node (&key (type js2-LP)
3650 (pos js2-ts-cursor)
3651 len expr)))
3652 "AST node for a parenthesized expression.
3653 In particular, used when the parens are syntactically optional,
3654 as opposed to required parens such as those enclosing an if-conditional."
3655 expr) ; `js2-node'
3656
3657 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3658 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3659
3660 (defun js2-visit-paren-node (n v)
3661 (js2-visit-ast (js2-paren-node-expr n) v))
3662
3663 (defun js2-print-paren-node (n i)
3664 (insert (js2-make-pad i))
3665 (insert "(")
3666 (js2-print-ast (js2-paren-node-expr n) 0)
3667 (insert ")"))
3668
3669 (defstruct (js2-array-comp-node
3670 (:include js2-scope)
3671 (:constructor nil)
3672 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3673 (pos js2-ts-cursor)
3674 len result
3675 loops filter
3676 if-pos lp rp)))
3677 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3678 result ; result expression (just after left-bracket)
3679 loops ; a Lisp list of `js2-array-comp-loop-node'
3680 filter ; guard/filter expression
3681 if-pos ; buffer pos of 'if' keyword, if present, else nil
3682 lp ; buffer position of if-guard left-paren, or nil if not present
3683 rp) ; buffer position of if-guard right-paren, or nil if not present
3684
3685 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3686 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3687
3688 (defun js2-visit-array-comp-node (n v)
3689 (js2-visit-ast (js2-array-comp-node-result n) v)
3690 (dolist (l (js2-array-comp-node-loops n))
3691 (js2-visit-ast l v))
3692 (js2-visit-ast (js2-array-comp-node-filter n) v))
3693
3694 (defun js2-print-array-comp-node (n i)
3695 (let ((pad (js2-make-pad i))
3696 (result (js2-array-comp-node-result n))
3697 (loops (js2-array-comp-node-loops n))
3698 (filter (js2-array-comp-node-filter n)))
3699 (insert pad "[")
3700 (js2-print-ast result 0)
3701 (dolist (l loops)
3702 (insert " ")
3703 (js2-print-ast l 0))
3704 (when filter
3705 (insert " if (")
3706 (js2-print-ast filter 0)
3707 (insert ")"))
3708 (insert "]")))
3709
3710 (defstruct (js2-array-comp-loop-node
3711 (:include js2-for-in-node)
3712 (:constructor nil)
3713 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3714 (pos js2-ts-cursor)
3715 len iterator
3716 object in-pos
3717 foreach-p
3718 each-pos
3719 forof-p
3720 lp rp)))
3721 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3722
3723 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3724 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3725
3726 (defun js2-visit-array-comp-loop (n v)
3727 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3728 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3729
3730 (defun js2-print-array-comp-loop (n _i)
3731 (insert "for ")
3732 (when (js2-array-comp-loop-node-foreach-p n) (insert "each "))
3733 (insert "(")
3734 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3735 (insert (if (js2-array-comp-loop-node-forof-p n)
3736 " of " " in "))
3737 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3738 (insert ")"))
3739
3740 (defstruct (js2-empty-expr-node
3741 (:include js2-node)
3742 (:constructor nil)
3743 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3744 (pos (js2-current-token-beg))
3745 len)))
3746 "AST node for an empty expression.")
3747
3748 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3749 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3750
3751 (defstruct (js2-xml-node
3752 (:include js2-block-node)
3753 (:constructor nil)
3754 (:constructor make-js2-xml-node (&key (type js2-XML)
3755 (pos (js2-current-token-beg))
3756 len kids)))
3757 "AST node for initial parse of E4X literals.
3758 The kids field is a list of XML fragments, each a `js2-string-node' or
3759 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3760
3761 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3762 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3763
3764 (defun js2-print-xml-node (n i)
3765 (dolist (kid (js2-xml-node-kids n))
3766 (js2-print-ast kid i)))
3767
3768 (defstruct (js2-xml-js-expr-node
3769 (:include js2-xml-node)
3770 (:constructor nil)
3771 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3772 (pos js2-ts-cursor)
3773 len expr)))
3774 "AST node for an embedded JavaScript {expression} in an E4X literal.
3775 The start and end fields correspond to the curly-braces."
3776 expr) ; a `js2-expr-node' of some sort
3777
3778 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3779 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3780
3781 (defun js2-visit-xml-js-expr (n v)
3782 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3783
3784 (defun js2-print-xml-js-expr (n i)
3785 (insert (js2-make-pad i))
3786 (insert "{")
3787 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3788 (insert "}"))
3789
3790 (defstruct (js2-xml-dot-query-node
3791 (:include js2-infix-node)
3792 (:constructor nil)
3793 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3794 (pos js2-ts-cursor)
3795 op-pos len left
3796 right rp)))
3797 "AST node for an E4X foo.(bar) filter expression.
3798 Note that the left-paren is automatically the character immediately
3799 following the dot (.) in the operator. No whitespace is permitted
3800 between the dot and the lp by the scanner."
3801 rp)
3802
3803 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3804 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3805
3806 (defun js2-print-xml-dot-query (n i)
3807 (insert (js2-make-pad i))
3808 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3809 (insert ".(")
3810 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3811 (insert ")"))
3812
3813 (defstruct (js2-xml-ref-node
3814 (:include js2-node)
3815 (:constructor nil)) ; abstract
3816 "Base type for E4X XML attribute-access or property-get expressions.
3817 Such expressions can take a variety of forms. The general syntax has
3818 three parts:
3819
3820 - (optional) an @ (specifying an attribute access)
3821 - (optional) a namespace (a `js2-name-node') and double-colon
3822 - (required) either a `js2-name-node' or a bracketed [expression]
3823
3824 The property-name expressions (examples: ns::name, @name) are
3825 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3826 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3827
3828 This node type (or more specifically, its subclasses) will sometimes
3829 be the right-hand child of a `js2-prop-get-node' or a
3830 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3831 The `js2-xml-ref-node' may also be a standalone primary expression with
3832 no explicit target, which is valid in certain expression contexts such as
3833
3834 company..employee.(@id < 100)
3835
3836 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3837 expression whose parent is a `js2-xml-dot-query-node'."
3838 namespace
3839 at-pos
3840 colon-pos)
3841
3842 (defsubst js2-xml-ref-node-attr-access-p (node)
3843 "Return non-nil if this expression began with an @-token."
3844 (and (numberp (js2-xml-ref-node-at-pos node))
3845 (plusp (js2-xml-ref-node-at-pos node))))
3846
3847 (defstruct (js2-xml-prop-ref-node
3848 (:include js2-xml-ref-node)
3849 (:constructor nil)
3850 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3851 (pos (js2-current-token-beg))
3852 len propname
3853 namespace at-pos
3854 colon-pos)))
3855 "AST node for an E4X XML [expr] property-ref expression.
3856 The JavaScript syntax is an optional @, an optional ns::, and a name.
3857
3858 [ '@' ] [ name '::' ] name
3859
3860 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3861 @ns::*, @*::attr, @*::*, and @*.
3862
3863 The node starts at the @ token, if present. Otherwise it starts at the
3864 namespace name. The node bounds extend through the closing right-bracket,
3865 or if it is missing due to a syntax error, through the end of the index
3866 expression."
3867 propname)
3868
3869 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3870 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3871
3872 (defun js2-visit-xml-prop-ref-node (n v)
3873 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3874 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3875
3876 (defun js2-print-xml-prop-ref-node (n i)
3877 (insert (js2-make-pad i))
3878 (if (js2-xml-ref-node-attr-access-p n)
3879 (insert "@"))
3880 (when (js2-xml-prop-ref-node-namespace n)
3881 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3882 (insert "::"))
3883 (if (js2-xml-prop-ref-node-propname n)
3884 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3885
3886 (defstruct (js2-xml-elem-ref-node
3887 (:include js2-xml-ref-node)
3888 (:constructor nil)
3889 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3890 (pos (js2-current-token-beg))
3891 len expr lb rb
3892 namespace at-pos
3893 colon-pos)))
3894 "AST node for an E4X XML [expr] member-ref expression.
3895 Syntax:
3896
3897 [ '@' ] [ name '::' ] '[' expr ']'
3898
3899 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3900
3901 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3902 is not a legal E4X XML element-ref expression, since it's already used
3903 for standard JavaScript element-get array indexing. Hence, a
3904 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3905 non-nil namespace node, or both.
3906
3907 The node starts at the @ token, if present. Otherwise it starts
3908 at the namespace name. The node bounds extend through the closing
3909 right-bracket, or if it is missing due to a syntax error, through the
3910 end of the index expression."
3911 expr ; the bracketed index expression
3912 lb
3913 rb)
3914
3915 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3916 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3917
3918 (defun js2-visit-xml-elem-ref-node (n v)
3919 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3920 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3921
3922 (defun js2-print-xml-elem-ref-node (n i)
3923 (insert (js2-make-pad i))
3924 (if (js2-xml-ref-node-attr-access-p n)
3925 (insert "@"))
3926 (when (js2-xml-elem-ref-node-namespace n)
3927 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3928 (insert "::"))
3929 (insert "[")
3930 (if (js2-xml-elem-ref-node-expr n)
3931 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3932 (insert "]"))
3933
3934 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3935
3936 (defstruct (js2-xml-start-tag-node
3937 (:include js2-xml-node)
3938 (:constructor nil)
3939 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3940 (pos js2-ts-cursor)
3941 len name attrs kids
3942 empty-p)))
3943 "AST node for an XML start-tag. Not currently used.
3944 The `kids' field is a Lisp list of child content nodes."
3945 name ; a `js2-xml-name-node'
3946 attrs ; a Lisp list of `js2-xml-attr-node'
3947 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3948
3949 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3950 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3951
3952 (defun js2-visit-xml-start-tag (n v)
3953 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3954 (dolist (attr (js2-xml-start-tag-node-attrs n))
3955 (js2-visit-ast attr v))
3956 (js2-visit-block n v))
3957
3958 (defun js2-print-xml-start-tag (n i)
3959 (insert (js2-make-pad i) "<")
3960 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3961 (when (js2-xml-start-tag-node-attrs n)
3962 (insert " ")
3963 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3964 (insert ">"))
3965
3966 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3967 ;; and add the end-tag to the kids list of the parent as well.
3968 (defstruct (js2-xml-end-tag-node
3969 (:include js2-xml-node)
3970 (:constructor nil)
3971 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
3972 (pos js2-ts-cursor)
3973 len name)))
3974 "AST node for an XML end-tag. Not currently used."
3975 name) ; a `js2-xml-name-node'
3976
3977 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
3978 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
3979
3980 (defun js2-visit-xml-end-tag (n v)
3981 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
3982
3983 (defun js2-print-xml-end-tag (n i)
3984 (insert (js2-make-pad i))
3985 (insert "</")
3986 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
3987 (insert ">"))
3988
3989 (defstruct (js2-xml-name-node
3990 (:include js2-xml-node)
3991 (:constructor nil)
3992 (:constructor make-js2-xml-name-node (&key (type js2-XML)
3993 (pos js2-ts-cursor)
3994 len namespace kids)))
3995 "AST node for an E4X XML name. Not currently used.
3996 Any XML name can be qualified with a namespace, hence the namespace field.
3997 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
3998 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
3999 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4000 namespace) ; a `js2-string-node'
4001
4002 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4003 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4004
4005 (defun js2-visit-xml-name-node (n v)
4006 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4007
4008 (defun js2-print-xml-name-node (n i)
4009 (insert (js2-make-pad i))
4010 (when (js2-xml-name-node-namespace n)
4011 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4012 (insert "::"))
4013 (dolist (kid (js2-xml-name-node-kids n))
4014 (js2-print-ast kid 0)))
4015
4016 (defstruct (js2-xml-pi-node
4017 (:include js2-xml-node)
4018 (:constructor nil)
4019 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4020 (pos js2-ts-cursor)
4021 len name attrs)))
4022 "AST node for an E4X XML processing instruction. Not currently used."
4023 name ; a `js2-xml-name-node'
4024 attrs) ; a list of `js2-xml-attr-node'
4025
4026 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4027 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4028
4029 (defun js2-visit-xml-pi-node (n v)
4030 (js2-visit-ast (js2-xml-pi-node-name n) v)
4031 (dolist (attr (js2-xml-pi-node-attrs n))
4032 (js2-visit-ast attr v)))
4033
4034 (defun js2-print-xml-pi-node (n i)
4035 (insert (js2-make-pad i) "<?")
4036 (js2-print-ast (js2-xml-pi-node-name n))
4037 (when (js2-xml-pi-node-attrs n)
4038 (insert " ")
4039 (js2-print-list (js2-xml-pi-node-attrs n)))
4040 (insert "?>"))
4041
4042 (defstruct (js2-xml-cdata-node
4043 (:include js2-xml-node)
4044 (:constructor nil)
4045 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4046 (pos js2-ts-cursor)
4047 len content)))
4048 "AST node for a CDATA escape section. Not currently used."
4049 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4050
4051 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4052 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4053
4054 (defun js2-visit-xml-cdata-node (n v)
4055 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4056
4057 (defun js2-print-xml-cdata-node (n i)
4058 (insert (js2-make-pad i))
4059 (js2-print-ast (js2-xml-cdata-node-content n)))
4060
4061 (defstruct (js2-xml-attr-node
4062 (:include js2-xml-node)
4063 (:constructor nil)
4064 (:constructor make-js2-attr-node (&key (type js2-XML)
4065 (pos js2-ts-cursor)
4066 len name value
4067 eq-pos quote-type)))
4068 "AST node representing a foo='bar' XML attribute value. Not yet used."
4069 name ; a `js2-xml-name-node'
4070 value ; a `js2-xml-name-node'
4071 eq-pos ; buffer position of "=" sign
4072 quote-type) ; 'single or 'double
4073
4074 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4075 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4076
4077 (defun js2-visit-xml-attr-node (n v)
4078 (js2-visit-ast (js2-xml-attr-node-name n) v)
4079 (js2-visit-ast (js2-xml-attr-node-value n) v))
4080
4081 (defun js2-print-xml-attr-node (n i)
4082 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4083 "'"
4084 "\"")))
4085 (insert (js2-make-pad i))
4086 (js2-print-ast (js2-xml-attr-node-name n) 0)
4087 (insert "=" quote)
4088 (js2-print-ast (js2-xml-attr-node-value n) 0)
4089 (insert quote)))
4090
4091 (defstruct (js2-xml-text-node
4092 (:include js2-xml-node)
4093 (:constructor nil)
4094 (:constructor make-js2-text-node (&key (type js2-XML)
4095 (pos js2-ts-cursor)
4096 len content)))
4097 "AST node for an E4X XML text node. Not currently used."
4098 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4099
4100 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4101 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4102
4103 (defun js2-visit-xml-text-node (n v)
4104 (js2-visit-ast (js2-xml-text-node-content n) v))
4105
4106 (defun js2-print-xml-text-node (n i)
4107 (insert (js2-make-pad i))
4108 (dolist (kid (js2-xml-text-node-content n))
4109 (js2-print-ast kid)))
4110
4111 (defstruct (js2-xml-comment-node
4112 (:include js2-xml-node)
4113 (:constructor nil)
4114 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4115 (pos js2-ts-cursor)
4116 len)))
4117 "AST node for E4X XML comment. Not currently used.")
4118
4119 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4120 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4121
4122 (defun js2-print-xml-comment (n i)
4123 (insert (js2-make-pad i)
4124 (js2-node-string n)))
4125
4126 ;;; Node utilities
4127
4128 (defsubst js2-node-line (n)
4129 "Fetch the source line number at the start of node N.
4130 This is O(n) in the length of the source buffer; use prudently."
4131 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4132
4133 (defsubst js2-block-node-kid (n i)
4134 "Return child I of node N, or nil if there aren't that many."
4135 (nth i (js2-block-node-kids n)))
4136
4137 (defsubst js2-block-node-first (n)
4138 "Return first child of block node N, or nil if there is none."
4139 (first (js2-block-node-kids n)))
4140
4141 (defun js2-node-root (n)
4142 "Return the root of the AST containing N.
4143 If N has no parent pointer, returns N."
4144 (let ((parent (js2-node-parent n)))
4145 (if parent
4146 (js2-node-root parent)
4147 n)))
4148
4149 (defsubst js2-node-short-name (n)
4150 "Return the short name of node N as a string, e.g. `js2-if-node'."
4151 (substring (symbol-name (aref n 0))
4152 (length "cl-struct-")))
4153
4154 (defun js2-node-child-list (node)
4155 "Return the child list for NODE, a Lisp list of nodes.
4156 Works for block nodes, array nodes, obj literals, funarg lists,
4157 var decls and try nodes (for catch clauses). Note that you should call
4158 `js2-block-node-kids' on the function body for the body statements.
4159 Returns nil for zero-length child lists or unsupported nodes."
4160 (cond
4161 ((js2-function-node-p node)
4162 (js2-function-node-params node))
4163 ((js2-block-node-p node)
4164 (js2-block-node-kids node))
4165 ((js2-try-node-p node)
4166 (js2-try-node-catch-clauses node))
4167 ((js2-array-node-p node)
4168 (js2-array-node-elems node))
4169 ((js2-object-node-p node)
4170 (js2-object-node-elems node))
4171 ((js2-call-node-p node)
4172 (js2-call-node-args node))
4173 ((js2-new-node-p node)
4174 (js2-new-node-args node))
4175 ((js2-var-decl-node-p node)
4176 (js2-var-decl-node-kids node))
4177 (t
4178 nil)))
4179
4180 (defun js2-node-set-child-list (node kids)
4181 "Set the child list for NODE to KIDS."
4182 (cond
4183 ((js2-function-node-p node)
4184 (setf (js2-function-node-params node) kids))
4185 ((js2-block-node-p node)
4186 (setf (js2-block-node-kids node) kids))
4187 ((js2-try-node-p node)
4188 (setf (js2-try-node-catch-clauses node) kids))
4189 ((js2-array-node-p node)
4190 (setf (js2-array-node-elems node) kids))
4191 ((js2-object-node-p node)
4192 (setf (js2-object-node-elems node) kids))
4193 ((js2-call-node-p node)
4194 (setf (js2-call-node-args node) kids))
4195 ((js2-new-node-p node)
4196 (setf (js2-new-node-args node) kids))
4197 ((js2-var-decl-node-p node)
4198 (setf (js2-var-decl-node-kids node) kids))
4199 (t
4200 (error "Unsupported node type: %s" (js2-node-short-name node))))
4201 kids)
4202
4203 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4204 (defconst js2-paren-expr-nodes
4205 '(cl-struct-js2-array-comp-loop-node
4206 cl-struct-js2-array-comp-node
4207 cl-struct-js2-call-node
4208 cl-struct-js2-catch-node
4209 cl-struct-js2-do-node
4210 cl-struct-js2-elem-get-node
4211 cl-struct-js2-for-in-node
4212 cl-struct-js2-for-node
4213 cl-struct-js2-function-node
4214 cl-struct-js2-if-node
4215 cl-struct-js2-let-node
4216 cl-struct-js2-new-node
4217 cl-struct-js2-paren-node
4218 cl-struct-js2-switch-node
4219 cl-struct-js2-while-node
4220 cl-struct-js2-with-node
4221 cl-struct-js2-xml-dot-query-node)
4222 "Node types that can have a parenthesized child expression.
4223 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4224
4225 (defsubst js2-paren-expr-node-p (node)
4226 "Return t for nodes that typically have a parenthesized child expression.
4227 Useful for computing the indentation anchors for arg-lists and conditions.
4228 Note that it may return a false positive, for instance when NODE is
4229 a `js2-new-node' and there are no arguments or parentheses."
4230 (memq (aref node 0) js2-paren-expr-nodes))
4231
4232 ;; Fake polymorphism... yech.
4233 (defun js2-node-lp (node)
4234 "Return relative left-paren position for NODE, if applicable.
4235 For `js2-elem-get-node' structs, returns left-bracket position.
4236 Note that the position may be nil in the case of a parse error."
4237 (cond
4238 ((js2-elem-get-node-p node)
4239 (js2-elem-get-node-lb node))
4240 ((js2-loop-node-p node)
4241 (js2-loop-node-lp node))
4242 ((js2-function-node-p node)
4243 (js2-function-node-lp node))
4244 ((js2-if-node-p node)
4245 (js2-if-node-lp node))
4246 ((js2-new-node-p node)
4247 (js2-new-node-lp node))
4248 ((js2-call-node-p node)
4249 (js2-call-node-lp node))
4250 ((js2-paren-node-p node)
4251 0)
4252 ((js2-switch-node-p node)
4253 (js2-switch-node-lp node))
4254 ((js2-catch-node-p node)
4255 (js2-catch-node-lp node))
4256 ((js2-let-node-p node)
4257 (js2-let-node-lp node))
4258 ((js2-array-comp-node-p node)
4259 (js2-array-comp-node-lp node))
4260 ((js2-with-node-p node)
4261 (js2-with-node-lp node))
4262 ((js2-xml-dot-query-node-p node)
4263 (1+ (js2-infix-node-op-pos node)))
4264 (t
4265 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4266
4267 ;; Fake polymorphism... blech.
4268 (defun js2-node-rp (node)
4269 "Return relative right-paren position for NODE, if applicable.
4270 For `js2-elem-get-node' structs, returns right-bracket position.
4271 Note that the position may be nil in the case of a parse error."
4272 (cond
4273 ((js2-elem-get-node-p node)
4274 (js2-elem-get-node-rb node))
4275 ((js2-loop-node-p node)
4276 (js2-loop-node-rp node))
4277 ((js2-function-node-p node)
4278 (js2-function-node-rp node))
4279 ((js2-if-node-p node)
4280 (js2-if-node-rp node))
4281 ((js2-new-node-p node)
4282 (js2-new-node-rp node))
4283 ((js2-call-node-p node)
4284 (js2-call-node-rp node))
4285 ((js2-paren-node-p node)
4286 (1- (js2-node-len node)))
4287 ((js2-switch-node-p node)
4288 (js2-switch-node-rp node))
4289 ((js2-catch-node-p node)
4290 (js2-catch-node-rp node))
4291 ((js2-let-node-p node)
4292 (js2-let-node-rp node))
4293 ((js2-array-comp-node-p node)
4294 (js2-array-comp-node-rp node))
4295 ((js2-with-node-p node)
4296 (js2-with-node-rp node))
4297 ((js2-xml-dot-query-node-p node)
4298 (1+ (js2-xml-dot-query-node-rp node)))
4299 (t
4300 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4301
4302 (defsubst js2-node-first-child (node)
4303 "Return the first element of `js2-node-child-list' for NODE."
4304 (car (js2-node-child-list node)))
4305
4306 (defsubst js2-node-last-child (node)
4307 "Return the last element of `js2-node-last-child' for NODE."
4308 (car (last (js2-node-child-list node))))
4309
4310 (defun js2-node-prev-sibling (node)
4311 "Return the previous statement in parent.
4312 Works for parents supported by `js2-node-child-list'.
4313 Returns nil if NODE is not in the parent, or PARENT is
4314 not a supported node, or if NODE is the first child."
4315 (let* ((p (js2-node-parent node))
4316 (kids (js2-node-child-list p))
4317 (sib (car kids)))
4318 (while (and kids
4319 (not (eq node (cadr kids))))
4320 (setq kids (cdr kids)
4321 sib (car kids)))
4322 sib))
4323
4324 (defun js2-node-next-sibling (node)
4325 "Return the next statement in parent block.
4326 Returns nil if NODE is not in the block, or PARENT is not
4327 a block node, or if NODE is the last statement."
4328 (let* ((p (js2-node-parent node))
4329 (kids (js2-node-child-list p)))
4330 (while (and kids
4331 (not (eq node (car kids))))
4332 (setq kids (cdr kids)))
4333 (cadr kids)))
4334
4335 (defun js2-node-find-child-before (pos parent &optional after)
4336 "Find the last child that starts before POS in parent.
4337 If AFTER is non-nil, returns first child starting after POS.
4338 POS is an absolute buffer position. PARENT is any node
4339 supported by `js2-node-child-list'.
4340 Returns nil if no applicable child is found."
4341 (let ((kids (if (js2-function-node-p parent)
4342 (js2-block-node-kids (js2-function-node-body parent))
4343 (js2-node-child-list parent)))
4344 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4345 (js2-function-node-body parent)
4346 parent)))
4347 kid result fn
4348 (continue t))
4349 (setq fn (if after '>= '<))
4350 (while (and kids continue)
4351 (setq kid (car kids))
4352 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4353 (setq result kid
4354 continue (not after))
4355 (setq continue after))
4356 (setq kids (cdr kids)))
4357 result))
4358
4359 (defun js2-node-find-child-after (pos parent)
4360 "Find first child that starts after POS in parent.
4361 POS is an absolute buffer position. PARENT is any node
4362 supported by `js2-node-child-list'.
4363 Returns nil if no applicable child is found."
4364 (js2-node-find-child-before pos parent 'after))
4365
4366 (defun js2-node-replace-child (pos parent new-node)
4367 "Replace node at index POS in PARENT with NEW-NODE.
4368 Only works for parents supported by `js2-node-child-list'."
4369 (let ((kids (js2-node-child-list parent))
4370 (i 0))
4371 (while (< i pos)
4372 (setq kids (cdr kids)
4373 i (1+ i)))
4374 (setcar kids new-node)
4375 (js2-node-add-children parent new-node)))
4376
4377 (defun js2-node-buffer (n)
4378 "Return the buffer associated with AST N.
4379 Returns nil if the buffer is not set as a property on the root
4380 node, or if parent links were not recorded during parsing."
4381 (let ((root (js2-node-root n)))
4382 (and root
4383 (js2-ast-root-p root)
4384 (js2-ast-root-buffer root))))
4385
4386 (defun js2-block-node-push (n kid)
4387 "Push js2-node KID onto the end of js2-block-node N's child list.
4388 KID is always added to the -end- of the kids list.
4389 Function also calls `js2-node-add-children' to add the parent link."
4390 (let ((kids (js2-node-child-list n)))
4391 (if kids
4392 (setcdr kids (nconc (cdr kids) (list kid)))
4393 (js2-node-set-child-list n (list kid)))
4394 (js2-node-add-children n kid)))
4395
4396 (defun js2-node-string (node)
4397 (with-current-buffer (or (js2-node-buffer node)
4398 (error "No buffer available for node %s" node))
4399 (let ((pos (js2-node-abs-pos node)))
4400 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4401
4402 ;; Container for storing the node we're looking for in a traversal.
4403 (js2-deflocal js2-discovered-node nil)
4404
4405 ;; Keep track of absolute node position during traversals.
4406 (js2-deflocal js2-visitor-offset nil)
4407
4408 (js2-deflocal js2-node-search-point nil)
4409
4410 (when js2-mode-dev-mode-p
4411 (defun js2-find-node-at-point ()
4412 (interactive)
4413 (let ((node (js2-node-at-point)))
4414 (message "%s" (or node "No node found at point"))))
4415 (defun js2-node-name-at-point ()
4416 (interactive)
4417 (let ((node (js2-node-at-point)))
4418 (message "%s" (if node
4419 (js2-node-short-name node)
4420 "No node found at point.")))))
4421
4422 (defun js2-node-at-point (&optional pos skip-comments)
4423 "Return AST node at POS, a buffer position, defaulting to current point.
4424 The `js2-mode-ast' variable must be set to the current parse tree.
4425 Signals an error if the AST (`js2-mode-ast') is nil.
4426 Always returns a node - if it can't find one, it returns the root.
4427 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4428 (let ((ast js2-mode-ast)
4429 result)
4430 (unless ast
4431 (error "No JavaScript AST available"))
4432 ;; Look through comments first, since they may be inside nodes that
4433 ;; would otherwise report a match.
4434 (setq pos (or pos (point))
4435 result (if (> pos (js2-node-abs-end ast))
4436 ast
4437 (if (not skip-comments)
4438 (js2-comment-at-point pos))))
4439 (unless result
4440 (setq js2-discovered-node nil
4441 js2-visitor-offset 0
4442 js2-node-search-point pos)
4443 (unwind-protect
4444 (catch 'js2-visit-done
4445 (js2-visit-ast ast #'js2-node-at-point-visitor))
4446 (setq js2-visitor-offset nil
4447 js2-node-search-point nil))
4448 (setq result js2-discovered-node))
4449 ;; may have found a comment beyond end of last child node,
4450 ;; since visiting the ast-root looks at the comment-list last.
4451 (if (and skip-comments
4452 (js2-comment-node-p result))
4453 (setq result nil))
4454 (or result js2-mode-ast)))
4455
4456 (defun js2-node-at-point-visitor (node end-p)
4457 (let ((rel-pos (js2-node-pos node))
4458 abs-pos
4459 abs-end
4460 (point js2-node-search-point))
4461 (cond
4462 (end-p
4463 ;; this evaluates to a non-nil return value, even if it's zero
4464 (decf js2-visitor-offset rel-pos))
4465 ;; we already looked for comments before visiting, and don't want them now
4466 ((js2-comment-node-p node)
4467 nil)
4468 (t
4469 (setq abs-pos (incf js2-visitor-offset rel-pos)
4470 ;; we only want to use the node if the point is before
4471 ;; the last character position in the node, so we decrement
4472 ;; the absolute end by 1.
4473 abs-end (+ abs-pos (js2-node-len node) -1))
4474 (cond
4475 ;; If this node starts after search-point, stop the search.
4476 ((> abs-pos point)
4477 (throw 'js2-visit-done nil))
4478 ;; If this node ends before the search-point, don't check kids.
4479 ((> point abs-end)
4480 nil)
4481 (t
4482 ;; Otherwise point is within this node, possibly in a child.
4483 (setq js2-discovered-node node)
4484 t)))))) ; keep processing kids to look for more specific match
4485
4486 (defsubst js2-block-comment-p (node)
4487 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4488 (and (js2-comment-node-p node)
4489 (memq (js2-comment-node-format node) '(jsdoc block))))
4490
4491 ;; TODO: put the comments in a vector and binary-search them instead
4492 (defun js2-comment-at-point (&optional pos)
4493 "Look through scanned comment nodes for one containing POS.
4494 POS is a buffer position that defaults to current point.
4495 Function returns nil if POS was not in any comment node."
4496 (let ((ast js2-mode-ast)
4497 (x (or pos (point)))
4498 beg end)
4499 (unless ast
4500 (error "No JavaScript AST available"))
4501 (catch 'done
4502 ;; Comments are stored in lexical order.
4503 (dolist (comment (js2-ast-root-comments ast) nil)
4504 (setq beg (js2-node-abs-pos comment)
4505 end (+ beg (js2-node-len comment)))
4506 (if (and (>= x beg)
4507 (<= x end))
4508 (throw 'done comment))))))
4509
4510 (defun js2-mode-find-parent-fn (node)
4511 "Find function enclosing NODE.
4512 Returns nil if NODE is not inside a function."
4513 (setq node (js2-node-parent node))
4514 (while (and node (not (js2-function-node-p node)))
4515 (setq node (js2-node-parent node)))
4516 (and (js2-function-node-p node) node))
4517
4518 (defun js2-mode-find-enclosing-fn (node)
4519 "Find function or root enclosing NODE."
4520 (if (js2-ast-root-p node)
4521 node
4522 (setq node (js2-node-parent node))
4523 (while (not (or (js2-ast-root-p node)
4524 (js2-function-node-p node)))
4525 (setq node (js2-node-parent node)))
4526 node))
4527
4528 (defun js2-mode-find-enclosing-node (beg end)
4529 "Find script or function fully enclosing BEG and END."
4530 (let ((node (js2-node-at-point beg))
4531 pos
4532 (continue t))
4533 (while continue
4534 (if (or (js2-ast-root-p node)
4535 (and (js2-function-node-p node)
4536 (<= (setq pos (js2-node-abs-pos node)) beg)
4537 (>= (+ pos (js2-node-len node)) end)))
4538 (setq continue nil)
4539 (setq node (js2-node-parent node))))
4540 node))
4541
4542 (defun js2-node-parent-script-or-fn (node)
4543 "Find script or function immediately enclosing NODE.
4544 If NODE is the ast-root, returns nil."
4545 (if (js2-ast-root-p node)
4546 nil
4547 (setq node (js2-node-parent node))
4548 (while (and node (not (or (js2-function-node-p node)
4549 (js2-script-node-p node))))
4550 (setq node (js2-node-parent node)))
4551 node))
4552
4553 (defun js2-node-is-descendant (node ancestor)
4554 "Return t if NODE is a descendant of ANCESTOR."
4555 (while (and node
4556 (not (eq node ancestor)))
4557 (setq node (js2-node-parent node)))
4558 node)
4559
4560 ;;; visitor infrastructure
4561
4562 (defun js2-visit-none (_node _callback)
4563 "Visitor for AST node that have no node children."
4564 nil)
4565
4566 (defun js2-print-none (_node _indent)
4567 "Visitor for AST node with no printed representation.")
4568
4569 (defun js2-print-body (node indent)
4570 "Print a statement, or a block without braces."
4571 (if (js2-block-node-p node)
4572 (dolist (kid (js2-block-node-kids node))
4573 (js2-print-ast kid indent))
4574 (js2-print-ast node indent)))
4575
4576 (defun js2-print-list (args &optional delimiter)
4577 (loop with len = (length args)
4578 for arg in args
4579 for count from 1
4580 do
4581 (when arg (js2-print-ast arg 0))
4582 (if (< count len)
4583 (insert (or delimiter ", ")))))
4584
4585 (defun js2-print-tree (ast)
4586 "Prints an AST to the current buffer.
4587 Makes `js2-ast-parent-nodes' available to the printer functions."
4588 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4589 (js2-print-ast ast)))
4590
4591 (defun js2-print-ast (node &optional indent)
4592 "Helper function for printing AST nodes.
4593 Requires `js2-ast-parent-nodes' to be non-nil.
4594 You should use `js2-print-tree' instead of this function."
4595 (let ((printer (get (aref node 0) 'js2-printer))
4596 (i (or indent 0)))
4597 ;; TODO: wedge comments in here somewhere
4598 (if printer
4599 (funcall printer node i))))
4600
4601 (defconst js2-side-effecting-tokens
4602 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4603 (dolist (tt (list js2-ASSIGN
4604 js2-ASSIGN_ADD
4605 js2-ASSIGN_BITAND
4606 js2-ASSIGN_BITOR
4607 js2-ASSIGN_BITXOR
4608 js2-ASSIGN_DIV
4609 js2-ASSIGN_LSH
4610 js2-ASSIGN_MOD
4611 js2-ASSIGN_MUL
4612 js2-ASSIGN_RSH
4613 js2-ASSIGN_SUB
4614 js2-ASSIGN_URSH
4615 js2-BLOCK
4616 js2-BREAK
4617 js2-CALL
4618 js2-CATCH
4619 js2-CATCH_SCOPE
4620 js2-CONST
4621 js2-CONTINUE
4622 js2-DEBUGGER
4623 js2-DEC
4624 js2-DELPROP
4625 js2-DEL_REF
4626 js2-DO
4627 js2-ELSE
4628 js2-EMPTY
4629 js2-ENTERWITH
4630 js2-EXPORT
4631 js2-EXPR_RESULT
4632 js2-FINALLY
4633 js2-FOR
4634 js2-FUNCTION
4635 js2-GOTO
4636 js2-IF
4637 js2-IFEQ
4638 js2-IFNE
4639 js2-IMPORT
4640 js2-INC
4641 js2-JSR
4642 js2-LABEL
4643 js2-LEAVEWITH
4644 js2-LET
4645 js2-LETEXPR
4646 js2-LOCAL_BLOCK
4647 js2-LOOP
4648 js2-NEW
4649 js2-REF_CALL
4650 js2-RETHROW
4651 js2-RETURN
4652 js2-RETURN_RESULT
4653 js2-SEMI
4654 js2-SETELEM
4655 js2-SETELEM_OP
4656 js2-SETNAME
4657 js2-SETPROP
4658 js2-SETPROP_OP
4659 js2-SETVAR
4660 js2-SET_REF
4661 js2-SET_REF_OP
4662 js2-SWITCH
4663 js2-TARGET
4664 js2-THROW
4665 js2-TRY
4666 js2-VAR
4667 js2-WHILE
4668 js2-WITH
4669 js2-WITHEXPR
4670 js2-YIELD))
4671 (aset tokens tt t))
4672 (if js2-instanceof-has-side-effects
4673 (aset tokens js2-INSTANCEOF t))
4674 tokens))
4675
4676 (defun js2-node-has-side-effects (node)
4677 "Return t if NODE has side effects."
4678 (when node ; makes it easier to handle malformed expressions
4679 (let ((tt (js2-node-type node)))
4680 (cond
4681 ;; This doubtless needs some work, since EXPR_VOID is used
4682 ;; in several ways in Rhino and I may not have caught them all.
4683 ;; I'll wait for people to notice incorrect warnings.
4684 ((and (= tt js2-EXPR_VOID)
4685 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4686 (let ((expr (js2-expr-stmt-node-expr node)))
4687 (or (js2-node-has-side-effects expr)
4688 (when (js2-string-node-p expr)
4689 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4690 ((= tt js2-COMMA)
4691 (js2-node-has-side-effects (js2-infix-node-right node)))
4692 ((or (= tt js2-AND)
4693 (= tt js2-OR))
4694 (or (js2-node-has-side-effects (js2-infix-node-right node))
4695 (js2-node-has-side-effects (js2-infix-node-left node))))
4696 ((= tt js2-HOOK)
4697 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4698 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4699 ((js2-paren-node-p node)
4700 (js2-node-has-side-effects (js2-paren-node-expr node)))
4701 ((= tt js2-ERROR) ; avoid cascaded error messages
4702 nil)
4703 (t
4704 (aref js2-side-effecting-tokens tt))))))
4705
4706 (defconst js2-stmt-node-types
4707 (list js2-BLOCK
4708 js2-BREAK
4709 js2-CONTINUE
4710 js2-DEFAULT ; e4x "default xml namespace" statement
4711 js2-DO
4712 js2-EXPR_RESULT
4713 js2-EXPR_VOID
4714 js2-FOR
4715 js2-IF
4716 js2-RETURN
4717 js2-SWITCH
4718 js2-THROW
4719 js2-TRY
4720 js2-WHILE
4721 js2-WITH)
4722 "Node types that only appear in statement contexts.
4723 The list does not include nodes that always appear as the child
4724 of another specific statement type, such as switch-cases,
4725 catch and finally blocks, and else-clauses. The list also excludes
4726 nodes like yield, let and var, which may appear in either expression
4727 or statement context, and in the latter context always have a
4728 `js2-expr-stmt-node' parent. Finally, the list does not include
4729 functions or scripts, which are treated separately from statements
4730 by the JavaScript parser and runtime.")
4731
4732 (defun js2-stmt-node-p (node)
4733 "Heuristic for figuring out if NODE is a statement.
4734 Some node types can appear in either an expression context or a
4735 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4736 For these node types in a statement context, the parent will be a
4737 `js2-expr-stmt-node'.
4738 Functions aren't included in the check."
4739 (memq (js2-node-type node) js2-stmt-node-types))
4740
4741 (defun js2-mode-find-first-stmt (node)
4742 "Search upward starting from NODE looking for a statement.
4743 For purposes of this function, a `js2-function-node' counts."
4744 (while (not (or (js2-stmt-node-p node)
4745 (js2-function-node-p node)))
4746 (setq node (js2-node-parent node)))
4747 node)
4748
4749 (defun js2-node-parent-stmt (node)
4750 "Return the node's first ancestor that is a statement.
4751 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4752 appearing in a statement context will have a parent that is a
4753 `js2-expr-stmt-node' that will be returned by this function."
4754 (let ((parent (js2-node-parent node)))
4755 (if (or (null parent)
4756 (js2-stmt-node-p parent)
4757 (and (js2-function-node-p parent)
4758 (not (eq (js2-function-node-form parent)
4759 'FUNCTION_EXPRESSION))))
4760 parent
4761 (js2-node-parent-stmt parent))))
4762
4763 ;; In the Mozilla Rhino sources, Roshan James writes:
4764 ;; Does consistent-return analysis on the function body when strict mode is
4765 ;; enabled.
4766 ;;
4767 ;; function (x) { return (x+1) }
4768 ;;
4769 ;; is ok, but
4770 ;;
4771 ;; function (x) { if (x < 0) return (x+1); }
4772 ;;
4773 ;; is not because the function can potentially return a value when the
4774 ;; condition is satisfied and if not, the function does not explicitly
4775 ;; return a value.
4776 ;;
4777 ;; This extends to checking mismatches such as "return" and "return <value>"
4778 ;; used in the same function. Warnings are not emitted if inconsistent
4779 ;; returns exist in code that can be statically shown to be unreachable.
4780 ;; Ex.
4781 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4782 ;;
4783 ;; emits no warning. However if the loop had a break statement, then a
4784 ;; warning would be emitted.
4785 ;;
4786 ;; The consistency analysis looks at control structures such as loops, ifs,
4787 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4788 ;; warns the user about an inconsistent set of termination possibilities.
4789 ;;
4790 ;; These flags enumerate the possible ways a statement/function can
4791 ;; terminate. These flags are used by endCheck() and by the Parser to
4792 ;; detect inconsistent return usage.
4793 ;;
4794 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4795 ;; able to execute (example: throw, continue)
4796 ;;
4797 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4798 ;; next one. Statement such as return dont. A compound statement may have
4799 ;; some branch that drops off control to the next statement.
4800 ;;
4801 ;; END_RETURNS indicates that the statement can return with no value.
4802 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4803 ;;
4804 ;; A compound statement such as
4805 ;; if (condition) {
4806 ;; return value;
4807 ;; }
4808 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4809
4810 (defconst js2-END_UNREACHED 0)
4811 (defconst js2-END_DROPS_OFF 1)
4812 (defconst js2-END_RETURNS 2)
4813 (defconst js2-END_RETURNS_VALUE 4)
4814 (defconst js2-END_YIELDS 8)
4815
4816 (defun js2-has-consistent-return-usage (node)
4817 "Check that every return usage in a function body is consistent.
4818 Returns t if the function satisfies strict mode requirement."
4819 (let ((n (js2-end-check node)))
4820 ;; either it doesn't return a value in any branch...
4821 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4822 ;; or it returns a value (or is unreached) at every branch
4823 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4824 js2-END_RETURNS
4825 js2-END_YIELDS)))))
4826
4827 (defun js2-end-check-if (node)
4828 "Ensure that return usage in then/else blocks is consistent.
4829 If there is no else block, then the return statement can fall through.
4830 Returns logical OR of END_* flags"
4831 (let ((th (js2-if-node-then-part node))
4832 (el (js2-if-node-else-part node)))
4833 (if (null th)
4834 js2-END_UNREACHED
4835 (logior (js2-end-check th) (if el
4836 (js2-end-check el)
4837 js2-END_DROPS_OFF)))))
4838
4839 (defun js2-end-check-switch (node)
4840 "Consistency of return statements is checked between the case statements.
4841 If there is no default, then the switch can fall through. If there is a
4842 default, we check to see if all code paths in the default return or if
4843 there is a code path that can fall through.
4844 Returns logical OR of END_* flags."
4845 (let ((rv js2-END_UNREACHED)
4846 default-case)
4847 ;; examine the cases
4848 (catch 'break
4849 (dolist (c (js2-switch-node-cases node))
4850 (if (js2-case-node-expr c)
4851 (js2-set-flag rv (js2-end-check-block c))
4852 (setq default-case c)
4853 (throw 'break nil))))
4854 ;; we don't care how the cases drop into each other
4855 (js2-clear-flag rv js2-END_DROPS_OFF)
4856 ;; examine the default
4857 (js2-set-flag rv (if default-case
4858 (js2-end-check default-case)
4859 js2-END_DROPS_OFF))
4860 rv))
4861
4862 (defun js2-end-check-try (node)
4863 "If the block has a finally, return consistency is checked in the
4864 finally block. If all code paths in the finally return, then the
4865 returns in the try-catch blocks don't matter. If there is a code path
4866 that does not return or if there is no finally block, the returns
4867 of the try and catch blocks are checked for mismatch.
4868 Returns logical OR of END_* flags."
4869 (let ((finally (js2-try-node-finally-block node))
4870 rv)
4871 ;; check the finally if it exists
4872 (setq rv (if finally
4873 (js2-end-check (js2-finally-node-body finally))
4874 js2-END_DROPS_OFF))
4875 ;; If the finally block always returns, then none of the returns
4876 ;; in the try or catch blocks matter.
4877 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4878 (js2-clear-flag rv js2-END_DROPS_OFF)
4879 ;; examine the try block
4880 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4881 ;; check each catch block
4882 (dolist (cb (js2-try-node-catch-clauses node))
4883 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4884 rv))
4885
4886 (defun js2-end-check-loop (node)
4887 "Return statement in the loop body must be consistent.
4888 The default assumption for any kind of a loop is that it will eventually
4889 terminate. The only exception is a loop with a constant true condition.
4890 Code that follows such a loop is examined only if one can determine
4891 statically that there is a break out of the loop.
4892
4893 for(... ; ... ; ...) {}
4894 for(... in ... ) {}
4895 while(...) { }
4896 do { } while(...)
4897
4898 Returns logical OR of END_* flags."
4899 (let ((rv (js2-end-check (js2-loop-node-body node)))
4900 (condition (cond
4901 ((js2-while-node-p node)
4902 (js2-while-node-condition node))
4903 ((js2-do-node-p node)
4904 (js2-do-node-condition node))
4905 ((js2-for-node-p node)
4906 (js2-for-node-condition node)))))
4907
4908 ;; check to see if the loop condition is always true
4909 (if (and condition
4910 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4911 (js2-clear-flag rv js2-END_DROPS_OFF))
4912
4913 ;; look for effect of breaks
4914 (js2-set-flag rv (js2-node-get-prop node
4915 'CONTROL_BLOCK_PROP
4916 js2-END_UNREACHED))
4917 rv))
4918
4919 (defun js2-end-check-block (node)
4920 "A general block of code is examined statement by statement.
4921 If any statement (even a compound one) returns in all branches, then
4922 subsequent statements are not examined.
4923 Returns logical OR of END_* flags."
4924 (let* ((rv js2-END_DROPS_OFF)
4925 (kids (js2-block-node-kids node))
4926 (n (car kids)))
4927 ;; Check each statment. If the statement can continue onto the next
4928 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4929 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4930 (js2-clear-flag rv js2-END_DROPS_OFF)
4931 (js2-set-flag rv (js2-end-check n))
4932 (setq kids (cdr kids)
4933 n (car kids)))
4934 rv))
4935
4936 (defun js2-end-check-label (node)
4937 "A labeled statement implies that there may be a break to the label.
4938 The function processes the labeled statement and then checks the
4939 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4940 particular label.
4941 Returns logical OR of END_* flags."
4942 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4943 (logior rv (js2-node-get-prop node
4944 'CONTROL_BLOCK_PROP
4945 js2-END_UNREACHED))))
4946
4947 (defun js2-end-check-break (node)
4948 "When a break is encountered annotate the statement being broken
4949 out of by setting its CONTROL_BLOCK_PROP property.
4950 Returns logical OR of END_* flags."
4951 (and (js2-break-node-target node)
4952 (js2-node-set-prop (js2-break-node-target node)
4953 'CONTROL_BLOCK_PROP
4954 js2-END_DROPS_OFF))
4955 js2-END_UNREACHED)
4956
4957 (defun js2-end-check (node)
4958 "Examine the body of a function, doing a basic reachability analysis.
4959 Returns a combination of flags END_* flags that indicate
4960 how the function execution can terminate. These constitute only the
4961 pessimistic set of termination conditions. It is possible that at
4962 runtime certain code paths will never be actually taken. Hence this
4963 analysis will flag errors in cases where there may not be errors.
4964 Returns logical OR of END_* flags"
4965 (let (kid)
4966 (cond
4967 ((js2-break-node-p node)
4968 (js2-end-check-break node))
4969 ((js2-expr-stmt-node-p node)
4970 (if (setq kid (js2-expr-stmt-node-expr node))
4971 (js2-end-check kid)
4972 js2-END_DROPS_OFF))
4973 ((or (js2-continue-node-p node)
4974 (js2-throw-node-p node))
4975 js2-END_UNREACHED)
4976 ((js2-return-node-p node)
4977 (if (setq kid (js2-return-node-retval node))
4978 js2-END_RETURNS_VALUE
4979 js2-END_RETURNS))
4980 ((js2-loop-node-p node)
4981 (js2-end-check-loop node))
4982 ((js2-switch-node-p node)
4983 (js2-end-check-switch node))
4984 ((js2-labeled-stmt-node-p node)
4985 (js2-end-check-label node))
4986 ((js2-if-node-p node)
4987 (js2-end-check-if node))
4988 ((js2-try-node-p node)
4989 (js2-end-check-try node))
4990 ((js2-block-node-p node)
4991 (if (null (js2-block-node-kids node))
4992 js2-END_DROPS_OFF
4993 (js2-end-check-block node)))
4994 ((js2-yield-node-p node)
4995 js2-END_YIELDS)
4996 (t
4997 js2-END_DROPS_OFF))))
4998
4999 (defun js2-always-defined-boolean-p (node)
5000 "Check if NODE always evaluates to true or false in boolean context.
5001 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5002 nor always false."
5003 (let ((tt (js2-node-type node))
5004 num)
5005 (cond
5006 ((or (= tt js2-FALSE) (= tt js2-NULL))
5007 'ALWAYS_FALSE)
5008 ((= tt js2-TRUE)
5009 'ALWAYS_TRUE)
5010 ((= tt js2-NUMBER)
5011 (setq num (js2-number-node-num-value node))
5012 (if (and (not (eq num 0.0e+NaN))
5013 (not (zerop num)))
5014 'ALWAYS_TRUE
5015 'ALWAYS_FALSE))
5016 (t
5017 nil))))
5018
5019 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5020 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5021
5022 (defvar js2-tokens nil
5023 "List of all defined token names.") ; initialized in `js2-token-names'
5024
5025 (defconst js2-token-names
5026 (let* ((names (make-vector js2-num-tokens -1))
5027 (case-fold-search nil) ; only match js2-UPPER_CASE
5028 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5029 (loop for sym in syms
5030 for i from 0
5031 do
5032 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5033 (not (boundp sym)))
5034 (aset names (symbol-value sym) ; code, e.g. 152
5035 (downcase
5036 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5037 (push sym js2-tokens)))
5038 names)
5039 "Vector mapping int values to token string names, sans `js2-' prefix.")
5040
5041 (defun js2-tt-name (tok)
5042 "Return a string name for TOK, a token symbol or code.
5043 Signals an error if it's not a recognized token."
5044 (let ((code tok))
5045 (if (symbolp tok)
5046 (setq code (symbol-value tok)))
5047 (if (eq code -1)
5048 "ERROR"
5049 (if (and (numberp code)
5050 (not (minusp code))
5051 (< code js2-num-tokens))
5052 (aref js2-token-names code)
5053 (error "Invalid token: %s" code)))))
5054
5055 (defsubst js2-tt-sym (tok)
5056 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5057 (intern (js2-tt-name tok)))
5058
5059 (defconst js2-token-codes
5060 (let ((table (make-hash-table :test 'eq :size 256)))
5061 (loop for name across js2-token-names
5062 for sym = (intern (concat "js2-" (upcase name)))
5063 do
5064 (puthash sym (symbol-value sym) table))
5065 ;; clean up a few that are "wrong" in Rhino's token codes
5066 (puthash 'js2-DELETE js2-DELPROP table)
5067 table)
5068 "Hashtable mapping token type symbols to their bytecodes.")
5069
5070 (defsubst js2-tt-code (sym)
5071 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5072 (or (gethash sym js2-token-codes)
5073 (error "Invalid token symbol: %s " sym))) ; signal code bug
5074
5075 (defun js2-report-scan-error (msg &optional no-throw beg len)
5076 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5077 (js2-report-error msg nil
5078 (or beg (js2-current-token-beg))
5079 (or len (js2-current-token-len)))
5080 (unless no-throw
5081 (throw 'return js2-ERROR)))
5082
5083 (defun js2-set-string-from-buffer (token)
5084 "Set `string' and `end' slots for TOKEN, return the string."
5085 (setf (js2-token-end token) js2-ts-cursor
5086 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5087
5088 ;; TODO: could potentially avoid a lot of consing by allocating a
5089 ;; char buffer the way Rhino does.
5090 (defsubst js2-add-to-string (c)
5091 (push c js2-ts-string-buffer))
5092
5093 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5094 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5095 ;; any other character: when it's not part of the current token, we
5096 ;; unget it, allowing it to be read again by the following call.
5097 (defsubst js2-unget-char ()
5098 (decf js2-ts-cursor))
5099
5100 ;; Rhino distinguishes \r and \n line endings. We don't need to
5101 ;; because we only scan from Emacs buffers, which always use \n.
5102 (defun js2-get-char ()
5103 "Read and return the next character from the input buffer.
5104 Increments `js2-ts-lineno' if the return value is a newline char.
5105 Updates `js2-ts-cursor' to the point after the returned char.
5106 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5107 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5108 (let (c)
5109 ;; check for end of buffer
5110 (if (>= js2-ts-cursor (point-max))
5111 (setq js2-ts-hit-eof t
5112 js2-ts-cursor (1+ js2-ts-cursor)
5113 c js2-EOF_CHAR) ; return value
5114 ;; otherwise read next char
5115 (setq c (char-before (incf js2-ts-cursor)))
5116 ;; if we read a newline, update counters
5117 (if (= c ?\n)
5118 (setq js2-ts-line-start js2-ts-cursor
5119 js2-ts-lineno (1+ js2-ts-lineno)))
5120 ;; TODO: skip over format characters
5121 c)))
5122
5123 (defun js2-read-unicode-escape ()
5124 "Read a \\uNNNN sequence from the input.
5125 Assumes the ?\ and ?u have already been read.
5126 Returns the unicode character, or nil if it wasn't a valid character.
5127 Doesn't change the values of any scanner variables."
5128 ;; I really wish I knew a better way to do this, but I can't
5129 ;; find the Emacs function that takes a 16-bit int and converts
5130 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5131 ;; Have to first check that it's 4 hex characters or it may stop
5132 ;; the read early.
5133 (ignore-errors
5134 (let ((s (buffer-substring-no-properties js2-ts-cursor
5135 (+ 4 js2-ts-cursor))))
5136 (if (string-match "[[:alnum:]]\\{4\\}" s)
5137 (read (concat "?\\u" s))))))
5138
5139 (defun js2-match-char (test)
5140 "Consume and return next character if it matches TEST, a character.
5141 Returns nil and consumes nothing if TEST is not the next character."
5142 (let ((c (js2-get-char)))
5143 (if (eq c test)
5144 t
5145 (js2-unget-char)
5146 nil)))
5147
5148 (defun js2-peek-char ()
5149 (prog1
5150 (js2-get-char)
5151 (js2-unget-char)))
5152
5153 (defun js2-java-identifier-start-p (c)
5154 (or
5155 (memq c '(?$ ?_))
5156 (js2-char-uppercase-p c)
5157 (js2-char-lowercase-p c)))
5158
5159 (defun js2-java-identifier-part-p (c)
5160 "Implementation of java.lang.Character.isJavaIdentifierPart()."
5161 ;; TODO: make me Unicode-friendly. See comments above.
5162 (or
5163 (memq c '(?$ ?_))
5164 (js2-char-uppercase-p c)
5165 (js2-char-lowercase-p c)
5166 (and (>= c ?0) (<= c ?9))))
5167
5168 (defun js2-alpha-p (c)
5169 (cond ((and (<= ?A c) (<= c ?Z)) t)
5170 ((and (<= ?a c) (<= c ?z)) t)
5171 (t nil)))
5172
5173 (defsubst js2-digit-p (c)
5174 (and (<= ?0 c) (<= c ?9)))
5175
5176 (defun js2-js-space-p (c)
5177 (if (<= c 127)
5178 (memq c '(#x20 #x9 #xB #xC #xD))
5179 (or
5180 (eq c #xA0)
5181 ;; TODO: change this nil to check for Unicode space character
5182 nil)))
5183
5184 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5185
5186 (defun js2-skip-line ()
5187 "Skip to end of line."
5188 (while (not (memq (js2-get-char) js2-eol-chars)))
5189 (js2-unget-char)
5190 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5191 (setq js2-token-end js2-ts-cursor))
5192
5193 (defun js2-init-scanner (&optional buf line)
5194 "Create token stream for BUF starting on LINE.
5195 BUF defaults to `current-buffer' and LINE defaults to 1.
5196
5197 A buffer can only have one scanner active at a time, which yields
5198 dramatically simpler code than using a defstruct. If you need to
5199 have simultaneous scanners in a buffer, copy the regions to scan
5200 into temp buffers."
5201 (with-current-buffer (or buf (current-buffer))
5202 (setq js2-ts-dirty-line nil
5203 js2-ts-hit-eof nil
5204 js2-ts-line-start 0
5205 js2-ts-lineno (or line 1)
5206 js2-ts-line-end-char -1
5207 js2-ts-cursor (point-min)
5208 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5209 js2-ti-tokens-cursor 0
5210 js2-ti-lookahead 0
5211 js2-ts-is-xml-attribute nil
5212 js2-ts-xml-is-tag-content nil
5213 js2-ts-xml-open-tags-count 0
5214 js2-ts-string-buffer nil)))
5215
5216 ;; This function uses the cached op, string and number fields in
5217 ;; TokenStream; if getToken has been called since the passed token
5218 ;; was scanned, the op or string printed may be incorrect.
5219 (defun js2-token-to-string (token)
5220 ;; Not sure where this function is used in Rhino. Not tested.
5221 (if (not js2-debug-print-trees)
5222 ""
5223 (let ((name (js2-tt-name token)))
5224 (cond
5225 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5226 (concat name " `" (js2-current-token-string) "'"))
5227 ((eq token js2-NUMBER)
5228 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5229 (t
5230 name)))))
5231
5232 (defconst js2-keywords
5233 '(break
5234 case catch const continue
5235 debugger default delete do
5236 else enum
5237 false finally for function
5238 if in instanceof import
5239 let
5240 new null
5241 return
5242 switch
5243 this throw true try typeof
5244 var void
5245 while with
5246 yield))
5247
5248 ;; Token names aren't exactly the same as the keywords, unfortunately.
5249 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5250 (defconst js2-kwd-tokens
5251 (let ((table (make-vector js2-num-tokens nil))
5252 (tokens
5253 (list js2-BREAK
5254 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5255 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5256 js2-ELSE
5257 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5258 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5259 js2-LET
5260 js2-NEW js2-NULL
5261 js2-RETURN
5262 js2-SWITCH
5263 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5264 js2-VAR
5265 js2-WHILE js2-WITH
5266 js2-YIELD)))
5267 (dolist (i tokens)
5268 (aset table i 'font-lock-keyword-face))
5269 (aset table js2-STRING 'font-lock-string-face)
5270 (aset table js2-REGEXP 'font-lock-string-face)
5271 (aset table js2-COMMENT 'font-lock-comment-face)
5272 (aset table js2-THIS 'font-lock-builtin-face)
5273 (aset table js2-VOID 'font-lock-constant-face)
5274 (aset table js2-NULL 'font-lock-constant-face)
5275 (aset table js2-TRUE 'font-lock-constant-face)
5276 (aset table js2-FALSE 'font-lock-constant-face)
5277 table)
5278 "Vector whose values are non-nil for tokens that are keywords.
5279 The values are default faces to use for highlighting the keywords.")
5280
5281 (defconst js2-reserved-words
5282 '(abstract
5283 boolean byte
5284 char class
5285 double
5286 enum export extends
5287 final float
5288 goto
5289 implements import int interface
5290 long
5291 native
5292 package private protected public
5293 short static super synchronized
5294 throws transient
5295 volatile))
5296
5297 (defconst js2-keyword-names
5298 (let ((table (make-hash-table :test 'equal)))
5299 (loop for k in js2-keywords
5300 do (puthash
5301 (symbol-name k) ; instanceof
5302 (intern (concat "js2-"
5303 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5304 table))
5305 table)
5306 "JavaScript keywords by name, mapped to their symbols.")
5307
5308 (defconst js2-reserved-word-names
5309 (let ((table (make-hash-table :test 'equal)))
5310 (loop for k in js2-reserved-words
5311 do
5312 (puthash (symbol-name k) 'js2-RESERVED table))
5313 table)
5314 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5315
5316 (defun js2-collect-string (buf)
5317 "Convert BUF, a list of chars, to a string.
5318 Reverses BUF before converting."
5319 (if buf
5320 (apply #'string (nreverse buf))
5321 ""))
5322
5323 (defun js2-string-to-keyword (s)
5324 "Return token for S, a string, if S is a keyword or reserved word.
5325 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5326 (or (gethash s js2-keyword-names)
5327 (gethash s js2-reserved-word-names)))
5328
5329 (defsubst js2-ts-set-char-token-bounds (token)
5330 "Used when next token is one character."
5331 (setf (js2-token-beg token) (1- js2-ts-cursor)
5332 (js2-token-end token) js2-ts-cursor))
5333
5334 (defsubst js2-ts-return (token type)
5335 "Update the `end' and `type' slots of TOKEN,
5336 then throw `return' with value TYPE."
5337 (setf (js2-token-end token) js2-ts-cursor
5338 (js2-token-type token) type)
5339 (throw 'return type))
5340
5341 (defun js2-x-digit-to-int (c accumulator)
5342 "Build up a hex number.
5343 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5344 corresponding number. Otherwise return -1."
5345 (catch 'return
5346 (catch 'check
5347 ;; Use 0..9 < A..Z < a..z
5348 (cond
5349 ((<= c ?9)
5350 (decf c ?0)
5351 (if (<= 0 c)
5352 (throw 'check nil)))
5353 ((<= c ?F)
5354 (when (<= ?A c)
5355 (decf c (- ?A 10))
5356 (throw 'check nil)))
5357 ((<= c ?f)
5358 (when (<= ?a c)
5359 (decf c (- ?a 10))
5360 (throw 'check nil))))
5361 (throw 'return -1))
5362 (logior c (lsh accumulator 4))))
5363
5364 (defun js2-get-token ()
5365 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5366 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5367 next saved token.
5368
5369 This function will not return a newline (js2-EOL) - instead, it
5370 gobbles newlines until it finds a non-newline token. Call
5371 `js2-peek-token-or-eol' when you care about newlines.
5372
5373 This function will also not return a js2-COMMENT. Instead, it
5374 records comments found in `js2-scanned-comments'. If the token
5375 returned by this function immediately follows a jsdoc comment,
5376 the token is flagged as such."
5377 (if (zerop js2-ti-lookahead)
5378 (js2-get-token-internal)
5379 (decf js2-ti-lookahead)
5380 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5381 (let ((tt (js2-current-token-type)))
5382 (assert (not (= tt js2-EOL)))
5383 tt)))
5384
5385 (defun js2-unget-token ()
5386 (assert (< js2-ti-lookahead js2-ti-max-lookahead))
5387 (incf js2-ti-lookahead)
5388 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5389
5390 (defun js2-get-token-internal ()
5391 (let* ((token (js2-get-token-internal-1)) ; call scanner
5392 (tt (js2-token-type token))
5393 saw-eol
5394 face)
5395 ;; process comments
5396 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5397 (if (= tt js2-EOL)
5398 (setq saw-eol t)
5399 (setq saw-eol nil)
5400 (when js2-record-comments
5401 (js2-record-comment token)))
5402 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5403 (setq token (js2-get-token-internal-1) ; call scanner again
5404 tt (js2-token-type token)))
5405
5406 (when saw-eol
5407 (setf (js2-token-follows-eol-p token) t))
5408
5409 ;; perform lexical fontification as soon as token is scanned
5410 (when js2-parse-ide-mode
5411 (cond
5412 ((minusp tt)
5413 (js2-record-face 'js2-error token))
5414 ((setq face (aref js2-kwd-tokens tt))
5415 (js2-record-face face token))
5416 ((and (= tt js2-NAME)
5417 (equal (js2-token-string token) "undefined"))
5418 (js2-record-face 'font-lock-constant-face token))))
5419 tt))
5420
5421 (defun js2-get-token-internal-1 ()
5422 "Return next JavaScript token type, an int such as js2-RETURN.
5423 During operation, creates an instance of `js2-token' struct, sets
5424 its relevant fields and puts it into `js2-ti-tokens'."
5425 (let (c c1 identifier-start is-unicode-escape-start
5426 contains-escape escape-val str result base
5427 is-integer quote-char val look-for-slash continue tt
5428 (token (js2-new-token 0)))
5429 (setq
5430 tt
5431 (catch 'return
5432 (while t
5433 ;; Eat whitespace, possibly sensitive to newlines.
5434 (setq continue t)
5435 (while continue
5436 (setq c (js2-get-char))
5437 (cond
5438 ((eq c js2-EOF_CHAR)
5439 (js2-unget-char)
5440 (js2-ts-set-char-token-bounds token)
5441 (throw 'return js2-EOF))
5442 ((eq c ?\n)
5443 (js2-ts-set-char-token-bounds token)
5444 (setq js2-ts-dirty-line nil)
5445 (throw 'return js2-EOL))
5446 ((not (js2-js-space-p c))
5447 (if (/= c ?-) ; in case end of HTML comment
5448 (setq js2-ts-dirty-line t))
5449 (setq continue nil))))
5450 ;; Assume the token will be 1 char - fixed up below.
5451 (js2-ts-set-char-token-bounds token)
5452 (when (eq c ?@)
5453 (throw 'return js2-XMLATTR))
5454 ;; identifier/keyword/instanceof?
5455 ;; watch out for starting with a <backslash>
5456 (cond
5457 ((eq c ?\\)
5458 (setq c (js2-get-char))
5459 (if (eq c ?u)
5460 (setq identifier-start t
5461 is-unicode-escape-start t
5462 js2-ts-string-buffer nil)
5463 (setq identifier-start nil)
5464 (js2-unget-char)
5465 (setq c ?\\)))
5466 (t
5467 (when (setq identifier-start (js2-java-identifier-start-p c))
5468 (setq js2-ts-string-buffer nil)
5469 (js2-add-to-string c))))
5470 (when identifier-start
5471 (setq contains-escape is-unicode-escape-start)
5472 (catch 'break
5473 (while t
5474 (if is-unicode-escape-start
5475 ;; strictly speaking we should probably push-back
5476 ;; all the bad characters if the <backslash>uXXXX
5477 ;; sequence is malformed. But since there isn't a
5478 ;; correct context(is there?) for a bad Unicode
5479 ;; escape sequence in an identifier, we can report
5480 ;; an error here.
5481 (progn
5482 (setq escape-val 0)
5483 (dotimes (_ 4)
5484 (setq c (js2-get-char)
5485 escape-val (js2-x-digit-to-int c escape-val))
5486 ;; Next check takes care of c < 0 and bad escape
5487 (if (minusp escape-val)
5488 (throw 'break nil)))
5489 (if (minusp escape-val)
5490 (js2-report-scan-error "msg.invalid.escape" t))
5491 (js2-add-to-string escape-val)
5492 (setq is-unicode-escape-start nil))
5493 (setq c (js2-get-char))
5494 (cond
5495 ((eq c ?\\)
5496 (setq c (js2-get-char))
5497 (if (eq c ?u)
5498 (setq is-unicode-escape-start t
5499 contains-escape t)
5500 (js2-report-scan-error "msg.illegal.character" t)))
5501 (t
5502 (if (or (eq c js2-EOF_CHAR)
5503 (not (js2-java-identifier-part-p c)))
5504 (throw 'break nil))
5505 (js2-add-to-string c))))))
5506 (js2-unget-char)
5507 (setf str (js2-collect-string js2-ts-string-buffer)
5508 (js2-token-end token) js2-ts-cursor)
5509 (unless contains-escape
5510 ;; OPT we shouldn't have to make a string (object!) to
5511 ;; check if it's a keyword.
5512 ;; Return the corresponding token if it's a keyword
5513 (when (setq result (js2-string-to-keyword str))
5514 (if (and (< js2-language-version 170)
5515 (memq result '(js2-LET js2-YIELD)))
5516 ;; LET and YIELD are tokens only in 1.7 and later
5517 (setq result 'js2-NAME))
5518 (if (not (eq result 'js2-RESERVED))
5519 (throw 'return (js2-tt-code result)))
5520 (js2-report-warning "msg.reserved.keyword" str)))
5521 ;; If we want to intern these as Rhino does, just use (intern str)
5522 (setf (js2-token-string token) str)
5523 (throw 'return js2-NAME)) ; end identifier/kwd check
5524 ;; is it a number?
5525 (when (or (js2-digit-p c)
5526 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5527 (setq js2-ts-string-buffer nil
5528 base 10)
5529 (when (eq c ?0)
5530 (setq c (js2-get-char))
5531 (cond
5532 ((or (eq c ?x) (eq c ?X))
5533 (setq base 16)
5534 (setq c (js2-get-char)))
5535 ((js2-digit-p c)
5536 (setq base 8))
5537 (t
5538 (js2-add-to-string ?0))))
5539 (if (eq base 16)
5540 (while (<= 0 (js2-x-digit-to-int c 0))
5541 (js2-add-to-string c)
5542 (setq c (js2-get-char)))
5543 (while (and (<= ?0 c) (<= c ?9))
5544 ;; We permit 08 and 09 as decimal numbers, which
5545 ;; makes our behavior a superset of the ECMA
5546 ;; numeric grammar. We might not always be so
5547 ;; permissive, so we warn about it.
5548 (when (and (eq base 8) (>= c ?8))
5549 (js2-report-warning "msg.bad.octal.literal"
5550 (if (eq c ?8) "8" "9"))
5551 (setq base 10))
5552 (js2-add-to-string c)
5553 (setq c (js2-get-char))))
5554 (setq is-integer t)
5555 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5556 (setq is-integer nil)
5557 (when (eq c ?.)
5558 (loop do
5559 (js2-add-to-string c)
5560 (setq c (js2-get-char))
5561 while (js2-digit-p c)))
5562 (when (memq c '(?e ?E))
5563 (js2-add-to-string c)
5564 (setq c (js2-get-char))
5565 (when (memq c '(?+ ?-))
5566 (js2-add-to-string c)
5567 (setq c (js2-get-char)))
5568 (unless (js2-digit-p c)
5569 (js2-report-scan-error "msg.missing.exponent" t))
5570 (loop do
5571 (js2-add-to-string c)
5572 (setq c (js2-get-char))
5573 while (js2-digit-p c))))
5574 (js2-unget-char)
5575 (let ((str (js2-set-string-from-buffer token)))
5576 (setf (js2-token-number token)
5577 (if (and (eq base 10) (not is-integer))
5578 (string-to-number str)
5579 ;; TODO: call runtime number-parser. Some of it is in
5580 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5581 (string-to-number str))))
5582 (throw 'return js2-NUMBER))
5583 ;; is it a string?
5584 (when (memq c '(?\" ?\'))
5585 ;; We attempt to accumulate a string the fast way, by
5586 ;; building it directly out of the reader. But if there
5587 ;; are any escaped characters in the string, we revert to
5588 ;; building it out of a string buffer.
5589 (setq quote-char c
5590 js2-ts-string-buffer nil
5591 c (js2-get-char))
5592 (catch 'break
5593 (while (/= c quote-char)
5594 (catch 'continue
5595 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5596 (js2-unget-char)
5597 (setf (js2-token-end token) js2-ts-cursor)
5598 (js2-report-error "msg.unterminated.string.lit")
5599 (throw 'return js2-STRING))
5600 (when (eq c ?\\)
5601 ;; We've hit an escaped character
5602 (setq c (js2-get-char))
5603 (case c
5604 (?b (setq c ?\b))
5605 (?f (setq c ?\f))
5606 (?n (setq c ?\n))
5607 (?r (setq c ?\r))
5608 (?t (setq c ?\t))
5609 (?v (setq c ?\v))
5610 (?u
5611 (setq c1 (js2-read-unicode-escape))
5612 (if js2-parse-ide-mode
5613 (if c1
5614 (progn
5615 ;; just copy the string in IDE-mode
5616 (js2-add-to-string ?\\)
5617 (js2-add-to-string ?u)
5618 (dotimes (_ 3)
5619 (js2-add-to-string (js2-get-char)))
5620 (setq c (js2-get-char))) ; added at end of loop
5621 ;; flag it as an invalid escape
5622 (js2-report-warning "msg.invalid.escape"
5623 nil (- js2-ts-cursor 2) 6))
5624 ;; Get 4 hex digits; if the u escape is not
5625 ;; followed by 4 hex digits, use 'u' + the
5626 ;; literal character sequence that follows.
5627 (js2-add-to-string ?u)
5628 (setq escape-val 0)
5629 (dotimes (_ 4)
5630 (setq c (js2-get-char)
5631 escape-val (js2-x-digit-to-int c escape-val))
5632 (if (minusp escape-val)
5633 (throw 'continue nil))
5634 (js2-add-to-string c))
5635 ;; prepare for replace of stored 'u' sequence by escape value
5636 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5637 c escape-val)))
5638 (?x
5639 ;; Get 2 hex digits, defaulting to 'x'+literal
5640 ;; sequence, as above.
5641 (setq c (js2-get-char)
5642 escape-val (js2-x-digit-to-int c 0))
5643 (if (minusp escape-val)
5644 (progn
5645 (js2-add-to-string ?x)
5646 (throw 'continue nil))
5647 (setq c1 c
5648 c (js2-get-char)
5649 escape-val (js2-x-digit-to-int c escape-val))
5650 (if (minusp escape-val)
5651 (progn
5652 (js2-add-to-string ?x)
5653 (js2-add-to-string c1)
5654 (throw 'continue nil))
5655 ;; got 2 hex digits
5656 (setq c escape-val))))
5657 (?\n
5658 ;; Remove line terminator after escape to follow
5659 ;; SpiderMonkey and C/C++
5660 (setq c (js2-get-char))
5661 (throw 'continue nil))
5662 (t
5663 (when (and (<= ?0 c) (< c ?8))
5664 (setq val (- c ?0)
5665 c (js2-get-char))
5666 (when (and (<= ?0 c) (< c ?8))
5667 (setq val (- (+ (* 8 val) c) ?0)
5668 c (js2-get-char))
5669 (when (and (<= ?0 c)
5670 (< c ?8)
5671 (< val #o37))
5672 ;; c is 3rd char of octal sequence only
5673 ;; if the resulting val <= 0377
5674 (setq val (- (+ (* 8 val) c) ?0)
5675 c (js2-get-char))))
5676 (js2-unget-char)
5677 (setq c val)))))
5678 (js2-add-to-string c)
5679 (setq c (js2-get-char)))))
5680 (js2-set-string-from-buffer token)
5681 (throw 'return js2-STRING))
5682 (js2-ts-return token
5683 (case c
5684 (?\;
5685 (throw 'return js2-SEMI))
5686 (?\[
5687 (throw 'return js2-LB))
5688 (?\]
5689 (throw 'return js2-RB))
5690 (?{
5691 (throw 'return js2-LC))
5692 (?}
5693 (throw 'return js2-RC))
5694 (?\(
5695 (throw 'return js2-LP))
5696 (?\)
5697 (throw 'return js2-RP))
5698 (?,
5699 (throw 'return js2-COMMA))
5700 (??
5701 (throw 'return js2-HOOK))
5702 (?:
5703 (if (js2-match-char ?:)
5704 js2-COLONCOLON
5705 (throw 'return js2-COLON)))
5706 (?.
5707 (if (js2-match-char ?.)
5708 (if (js2-match-char ?.)
5709 js2-TRIPLEDOT js2-DOTDOT)
5710 (if (js2-match-char ?\()
5711 js2-DOTQUERY
5712 (throw 'return js2-DOT))))
5713 (?|
5714 (if (js2-match-char ?|)
5715 (throw 'return js2-OR)
5716 (if (js2-match-char ?=)
5717 js2-ASSIGN_BITOR
5718 (throw 'return js2-BITOR))))
5719 (?^
5720 (if (js2-match-char ?=)
5721 js2-ASSIGN_BITOR
5722 (throw 'return js2-BITXOR)))
5723 (?&
5724 (if (js2-match-char ?&)
5725 (throw 'return js2-AND)
5726 (if (js2-match-char ?=)
5727 js2-ASSIGN_BITAND
5728 (throw 'return js2-BITAND))))
5729 (?=
5730 (if (js2-match-char ?=)
5731 (if (js2-match-char ?=)
5732 js2-SHEQ
5733 (throw 'return js2-EQ))
5734 (if (js2-match-char ?>)
5735 (js2-ts-return token js2-ARROW)
5736 (throw 'return js2-ASSIGN))))
5737 (?!
5738 (if (js2-match-char ?=)
5739 (if (js2-match-char ?=)
5740 js2-SHNE
5741 js2-NE)
5742 (throw 'return js2-NOT)))
5743 (?<
5744 ;; NB:treat HTML begin-comment as comment-till-eol
5745 (when (js2-match-char ?!)
5746 (when (js2-match-char ?-)
5747 (when (js2-match-char ?-)
5748 (js2-skip-line)
5749 (setf (js2-token-comment-type (js2-current-token)) 'html)
5750 (throw 'return js2-COMMENT)))
5751 (js2-unget-char))
5752 (if (js2-match-char ?<)
5753 (if (js2-match-char ?=)
5754 js2-ASSIGN_LSH
5755 js2-LSH)
5756 (if (js2-match-char ?=)
5757 js2-LE
5758 (throw 'return js2-LT))))
5759 (?>
5760 (if (js2-match-char ?>)
5761 (if (js2-match-char ?>)
5762 (if (js2-match-char ?=)
5763 js2-ASSIGN_URSH
5764 js2-URSH)
5765 (if (js2-match-char ?=)
5766 js2-ASSIGN_RSH
5767 js2-RSH))
5768 (if (js2-match-char ?=)
5769 js2-GE
5770 (throw 'return js2-GT))))
5771 (?*
5772 (if (js2-match-char ?=)
5773 js2-ASSIGN_MUL
5774 (throw 'return js2-MUL)))
5775 (?/
5776 ;; is it a // comment?
5777 (when (js2-match-char ?/)
5778 (setf (js2-token-beg token) (- js2-ts-cursor 2))
5779 (js2-skip-line)
5780 (setf (js2-token-comment-type token) 'line)
5781 ;; include newline so highlighting goes to end of window
5782 (incf (js2-token-end token))
5783 (throw 'return js2-COMMENT))
5784 ;; is it a /* comment?
5785 (when (js2-match-char ?*)
5786 (setf look-for-slash nil
5787 (js2-token-beg token) (- js2-ts-cursor 2)
5788 (js2-token-comment-type token)
5789 (if (js2-match-char ?*)
5790 (progn
5791 (setq look-for-slash t)
5792 'jsdoc)
5793 'block))
5794 (while t
5795 (setq c (js2-get-char))
5796 (cond
5797 ((eq c js2-EOF_CHAR)
5798 (setf (js2-token-end token) (1- js2-ts-cursor))
5799 (js2-report-error "msg.unterminated.comment")
5800 (throw 'return js2-COMMENT))
5801 ((eq c ?*)
5802 (setq look-for-slash t))
5803 ((eq c ?/)
5804 (if look-for-slash
5805 (js2-ts-return token js2-COMMENT)))
5806 (t
5807 (setf look-for-slash nil
5808 (js2-token-end token) js2-ts-cursor)))))
5809 (if (js2-match-char ?=)
5810 js2-ASSIGN_DIV
5811 (throw 'return js2-DIV)))
5812 (?#
5813 (when js2-skip-preprocessor-directives
5814 (js2-skip-line)
5815 (setf (js2-token-comment-type token) 'preprocessor
5816 (js2-token-end token) js2-ts-cursor)
5817 (throw 'return js2-COMMENT))
5818 (throw 'return js2-ERROR))
5819 (?%
5820 (if (js2-match-char ?=)
5821 js2-ASSIGN_MOD
5822 (throw 'return js2-MOD)))
5823 (?~
5824 (throw 'return js2-BITNOT))
5825 (?+
5826 (if (js2-match-char ?=)
5827 js2-ASSIGN_ADD
5828 (if (js2-match-char ?+)
5829 js2-INC
5830 (throw 'return js2-ADD))))
5831 (?-
5832 (cond
5833 ((js2-match-char ?=)
5834 (setq c js2-ASSIGN_SUB))
5835 ((js2-match-char ?-)
5836 (unless js2-ts-dirty-line
5837 ;; treat HTML end-comment after possible whitespace
5838 ;; after line start as comment-until-eol
5839 (when (js2-match-char ?>)
5840 (js2-skip-line)
5841 (setf (js2-token-comment-type (js2-current-token)) 'html)
5842 (throw 'return js2-COMMENT)))
5843 (setq c js2-DEC))
5844 (t
5845 (setq c js2-SUB)))
5846 (setq js2-ts-dirty-line t)
5847 c)
5848 (otherwise
5849 (js2-report-scan-error "msg.illegal.character")))))))
5850 (setf (js2-token-type token) tt)
5851 token))
5852
5853 (defun js2-read-regexp (start-tt)
5854 "Called by parser when it gets / or /= in literal context."
5855 (let (c err
5856 in-class ; inside a '[' .. ']' character-class
5857 flags
5858 (continue t)
5859 (token (js2-new-token 0)))
5860 (setq js2-ts-string-buffer nil)
5861 (if (eq start-tt js2-ASSIGN_DIV)
5862 ;; mis-scanned /=
5863 (js2-add-to-string ?=)
5864 (if (not (eq start-tt js2-DIV))
5865 (error "failed assertion")))
5866 (while (and (not err)
5867 (or (/= (setq c (js2-get-char)) ?/)
5868 in-class))
5869 (cond
5870 ((or (= c ?\n)
5871 (= c js2-EOF_CHAR))
5872 (setf (js2-token-end token) (1- js2-ts-cursor)
5873 err t
5874 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
5875 (js2-report-error "msg.unterminated.re.lit"))
5876 (t (cond
5877 ((= c ?\\)
5878 (js2-add-to-string c)
5879 (setq c (js2-get-char)))
5880 ((= c ?\[)
5881 (setq in-class t))
5882 ((= c ?\])
5883 (setq in-class nil)))
5884 (js2-add-to-string c))))
5885 (unless err
5886 (while continue
5887 (cond
5888 ((js2-match-char ?g)
5889 (push ?g flags))
5890 ((js2-match-char ?i)
5891 (push ?i flags))
5892 ((js2-match-char ?m)
5893 (push ?m flags))
5894 (t
5895 (setq continue nil))))
5896 (if (js2-alpha-p (js2-peek-char))
5897 (js2-report-scan-error "msg.invalid.re.flag" t
5898 js2-ts-cursor 1))
5899 (js2-set-string-from-buffer token)
5900 ;; tell `parse-partial-sexp' to ignore this range of chars
5901 (js2-record-text-property (js2-current-token-beg)
5902 (js2-current-token-end) 'syntax-class '(2)))
5903 (js2-collect-string flags)))
5904
5905 (defun js2-get-first-xml-token ()
5906 (setq js2-ts-xml-open-tags-count 0
5907 js2-ts-is-xml-attribute nil
5908 js2-ts-xml-is-tag-content nil)
5909 (js2-unget-char)
5910 (js2-get-next-xml-token))
5911
5912 (defun js2-xml-discard-string (token)
5913 "Throw away the string in progress and flag an XML parse error."
5914 (setf js2-ts-string-buffer nil
5915 (js2-token-string token) nil)
5916 (js2-report-scan-error "msg.XML.bad.form" t))
5917
5918 (defun js2-get-next-xml-token ()
5919 (setq js2-ts-string-buffer nil) ; for recording the XML
5920 (let ((token (js2-new-token 0))
5921 c result)
5922 (setq result
5923 (catch 'return
5924 (while t
5925 (setq c (js2-get-char))
5926 (cond
5927 ((= c js2-EOF_CHAR)
5928 (throw 'return js2-ERROR))
5929 (js2-ts-xml-is-tag-content
5930 (case c
5931 (?>
5932 (js2-add-to-string c)
5933 (setq js2-ts-xml-is-tag-content nil
5934 js2-ts-is-xml-attribute nil))
5935 (?/
5936 (js2-add-to-string c)
5937 (when (eq ?> (js2-peek-char))
5938 (setq c (js2-get-char))
5939 (js2-add-to-string c)
5940 (setq js2-ts-xml-is-tag-content nil)
5941 (decf js2-ts-xml-open-tags-count)))
5942 (?{
5943 (js2-unget-char)
5944 (js2-set-string-from-buffer token)
5945 (throw 'return js2-XML))
5946 ((?\' ?\")
5947 (js2-add-to-string c)
5948 (unless (js2-read-quoted-string c token)
5949 (throw 'return js2-ERROR)))
5950 (?=
5951 (js2-add-to-string c)
5952 (setq js2-ts-is-xml-attribute t))
5953 ((? ?\t ?\r ?\n)
5954 (js2-add-to-string c))
5955 (t
5956 (js2-add-to-string c)
5957 (setq js2-ts-is-xml-attribute nil)))
5958 (when (and (not js2-ts-xml-is-tag-content)
5959 (zerop js2-ts-xml-open-tags-count))
5960 (js2-set-string-from-buffer token)
5961 (throw 'return js2-XMLEND)))
5962 (t
5963 ;; else not tag content
5964 (case c
5965 (?<
5966 (js2-add-to-string c)
5967 (setq c (js2-peek-char))
5968 (case c
5969 (?!
5970 (setq c (js2-get-char)) ;; skip !
5971 (js2-add-to-string c)
5972 (setq c (js2-peek-char))
5973 (case c
5974 (?-
5975 (setq c (js2-get-char)) ;; skip -
5976 (js2-add-to-string c)
5977 (if (eq c ?-)
5978 (progn
5979 (js2-add-to-string c)
5980 (unless (js2-read-xml-comment token)
5981 (throw 'return js2-ERROR)))
5982 (js2-xml-discard-string token)
5983 (throw 'return js2-ERROR)))
5984 (?\[
5985 (setq c (js2-get-char)) ;; skip [
5986 (js2-add-to-string c)
5987 (if (and (= (js2-get-char) ?C)
5988 (= (js2-get-char) ?D)
5989 (= (js2-get-char) ?A)
5990 (= (js2-get-char) ?T)
5991 (= (js2-get-char) ?A)
5992 (= (js2-get-char) ?\[))
5993 (progn
5994 (js2-add-to-string ?C)
5995 (js2-add-to-string ?D)
5996 (js2-add-to-string ?A)
5997 (js2-add-to-string ?T)
5998 (js2-add-to-string ?A)
5999 (js2-add-to-string ?\[)
6000 (unless (js2-read-cdata token)
6001 (throw 'return js2-ERROR)))
6002 (js2-xml-discard-string token)
6003 (throw 'return js2-ERROR)))
6004 (t
6005 (unless (js2-read-entity token)
6006 (throw 'return js2-ERROR))))
6007 ;; Allow bare CDATA section, e.g.:
6008 ;; let xml = <![CDATA[ foo bar baz ]]>;
6009 (when (zerop js2-ts-xml-open-tags-count)
6010 (throw 'return js2-XMLEND)))
6011 (??
6012 (setq c (js2-get-char)) ;; skip ?
6013 (js2-add-to-string c)
6014 (unless (js2-read-PI token)
6015 (throw 'return js2-ERROR)))
6016 (?/
6017 ;; end tag
6018 (setq c (js2-get-char)) ;; skip /
6019 (js2-add-to-string c)
6020 (when (zerop js2-ts-xml-open-tags-count)
6021 (js2-xml-discard-string token)
6022 (throw 'return js2-ERROR))
6023 (setq js2-ts-xml-is-tag-content t)
6024 (decf js2-ts-xml-open-tags-count))
6025 (t
6026 ;; start tag
6027 (setq js2-ts-xml-is-tag-content t)
6028 (incf js2-ts-xml-open-tags-count))))
6029 (?{
6030 (js2-unget-char)
6031 (js2-set-string-from-buffer token)
6032 (throw 'return js2-XML))
6033 (t
6034 (js2-add-to-string c))))))))
6035 (setf (js2-token-end token) js2-ts-cursor)
6036 (setf (js2-token-type token) result)
6037 result))
6038
6039 (defun js2-read-quoted-string (quote token)
6040 (let (c)
6041 (catch 'return
6042 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6043 (js2-add-to-string c)
6044 (if (eq c quote)
6045 (throw 'return t)))
6046 (js2-xml-discard-string token) ;; throw away string in progress
6047 nil)))
6048
6049 (defun js2-read-xml-comment (token)
6050 (let ((c (js2-get-char)))
6051 (catch 'return
6052 (while (/= c js2-EOF_CHAR)
6053 (catch 'continue
6054 (js2-add-to-string c)
6055 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6056 (setq c (js2-get-char))
6057 (js2-add-to-string c)
6058 (if (eq (js2-peek-char) ?>)
6059 (progn
6060 (setq c (js2-get-char)) ;; skip >
6061 (js2-add-to-string c)
6062 (throw 'return t))
6063 (throw 'continue nil)))
6064 (setq c (js2-get-char))))
6065 (js2-xml-discard-string token)
6066 nil)))
6067
6068 (defun js2-read-cdata (token)
6069 (let ((c (js2-get-char)))
6070 (catch 'return
6071 (while (/= c js2-EOF_CHAR)
6072 (catch 'continue
6073 (js2-add-to-string c)
6074 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6075 (setq c (js2-get-char))
6076 (js2-add-to-string c)
6077 (if (eq (js2-peek-char) ?>)
6078 (progn
6079 (setq c (js2-get-char)) ;; Skip >
6080 (js2-add-to-string c)
6081 (throw 'return t))
6082 (throw 'continue nil)))
6083 (setq c (js2-get-char))))
6084 (js2-xml-discard-string token)
6085 nil)))
6086
6087 (defun js2-read-entity (token)
6088 (let ((decl-tags 1)
6089 c)
6090 (catch 'return
6091 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6092 (js2-add-to-string c)
6093 (case c
6094 (?<
6095 (incf decl-tags))
6096 (?>
6097 (decf decl-tags)
6098 (if (zerop decl-tags)
6099 (throw 'return t)))))
6100 (js2-xml-discard-string token)
6101 nil)))
6102
6103 (defun js2-read-PI (token)
6104 "Scan an XML processing instruction."
6105 (let (c)
6106 (catch 'return
6107 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6108 (js2-add-to-string c)
6109 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6110 (setq c (js2-get-char)) ;; Skip >
6111 (js2-add-to-string c)
6112 (throw 'return t)))
6113 (js2-xml-discard-string token)
6114 nil)))
6115
6116 ;;; Highlighting
6117
6118 (defun js2-set-face (beg end face &optional record)
6119 "Fontify a region. If RECORD is non-nil, record for later."
6120 (when (plusp js2-highlight-level)
6121 (setq beg (min (point-max) beg)
6122 beg (max (point-min) beg)
6123 end (min (point-max) end)
6124 end (max (point-min) end))
6125 (if record
6126 (push (list beg end face) js2-mode-fontifications)
6127 (put-text-property beg end 'font-lock-face face))))
6128
6129 (defsubst js2-clear-face (beg end)
6130 (remove-text-properties beg end '(font-lock-face nil
6131 help-echo nil
6132 point-entered nil
6133 c-in-sws nil)))
6134
6135 (defconst js2-ecma-global-props
6136 (concat "^"
6137 (regexp-opt
6138 '("Infinity" "NaN" "undefined" "arguments") t)
6139 "$")
6140 "Value properties of the Ecma-262 Global Object.
6141 Shown at or above `js2-highlight-level' 2.")
6142
6143 ;; might want to add the name "arguments" to this list?
6144 (defconst js2-ecma-object-props
6145 (concat "^"
6146 (regexp-opt
6147 '("prototype" "__proto__" "__parent__") t)
6148 "$")
6149 "Value properties of the Ecma-262 Object constructor.
6150 Shown at or above `js2-highlight-level' 2.")
6151
6152 (defconst js2-ecma-global-funcs
6153 (concat
6154 "^"
6155 (regexp-opt
6156 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6157 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6158 "$")
6159 "Function properties of the Ecma-262 Global object.
6160 Shown at or above `js2-highlight-level' 2.")
6161
6162 (defconst js2-ecma-number-props
6163 (concat "^"
6164 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6165 "NEGATIVE_INFINITY"
6166 "POSITIVE_INFINITY") t)
6167 "$")
6168 "Properties of the Ecma-262 Number constructor.
6169 Shown at or above `js2-highlight-level' 2.")
6170
6171 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6172 "Properties of the Ecma-262 Date constructor.
6173 Shown at or above `js2-highlight-level' 2.")
6174
6175 (defconst js2-ecma-math-props
6176 (concat "^"
6177 (regexp-opt
6178 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6179 t)
6180 "$")
6181 "Properties of the Ecma-262 Math object.
6182 Shown at or above `js2-highlight-level' 2.")
6183
6184 (defconst js2-ecma-math-funcs
6185 (concat "^"
6186 (regexp-opt
6187 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6188 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6189 "$")
6190 "Function properties of the Ecma-262 Math object.
6191 Shown at or above `js2-highlight-level' 2.")
6192
6193 (defconst js2-ecma-function-props
6194 (concat
6195 "^"
6196 (regexp-opt
6197 '(;; properties of the Object prototype object
6198 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6199 "toLocaleString" "toString" "valueOf"
6200 ;; properties of the Function prototype object
6201 "apply" "call"
6202 ;; properties of the Array prototype object
6203 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6204 "splice" "unshift"
6205 ;; properties of the String prototype object
6206 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6207 "localeCompare" "match" "replace" "search" "split" "substring"
6208 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6209 "toUpperCase"
6210 ;; properties of the Number prototype object
6211 "toExponential" "toFixed" "toPrecision"
6212 ;; properties of the Date prototype object
6213 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6214 "getMinutes" "getMonth" "getSeconds" "getTime"
6215 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6216 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6217 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6218 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6219 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6220 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6221 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6222 "toTimeString" "toUTCString"
6223 ;; properties of the RegExp prototype object
6224 "exec" "test"
6225 ;; properties of the JSON prototype object
6226 "parse" "stringify"
6227 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6228 "toSource" "__defineGetter__" "__defineSetter__"
6229 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6230 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6231 t)
6232 "$")
6233 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6234 Shown at or above `js2-highlight-level' 3.")
6235
6236 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6237 (let ((target-name (and target
6238 (js2-name-node-p target)
6239 (js2-name-node-name target)))
6240 (prop-name (if prop (js2-name-node-name prop)))
6241 (level2 (>= js2-highlight-level 2))
6242 (level3 (>= js2-highlight-level 3)))
6243 (when level2
6244 (let ((face
6245 (if call-p
6246 (cond
6247 ((and target prop)
6248 (cond
6249 ((and level3 (string-match js2-ecma-function-props prop-name))
6250 'font-lock-builtin-face)
6251 ((and target-name prop)
6252 (cond
6253 ((string= target-name "Date")
6254 (if (string-match js2-ecma-date-props prop-name)
6255 'font-lock-builtin-face))
6256 ((string= target-name "Math")
6257 (if (string-match js2-ecma-math-funcs prop-name)
6258 'font-lock-builtin-face))))))
6259 (prop
6260 (if (string-match js2-ecma-global-funcs prop-name)
6261 'font-lock-builtin-face)))
6262 (cond
6263 ((and target prop)
6264 (cond
6265 ((string= target-name "Number")
6266 (if (string-match js2-ecma-number-props prop-name)
6267 'font-lock-constant-face))
6268 ((string= target-name "Math")
6269 (if (string-match js2-ecma-math-props prop-name)
6270 'font-lock-constant-face))))
6271 (prop
6272 (if (string-match js2-ecma-object-props prop-name)
6273 'font-lock-constant-face))))))
6274 (when face
6275 (let ((pos (+ (js2-node-pos parent) ; absolute
6276 (js2-node-pos prop)))) ; relative
6277 (js2-set-face pos
6278 (+ pos (js2-node-len prop))
6279 face 'record)))))))
6280
6281 (defun js2-parse-highlight-member-expr-node (node)
6282 "Perform syntax highlighting of EcmaScript built-in properties.
6283 The variable `js2-highlight-level' governs this highighting."
6284 (let (face target prop name pos end parent call-p callee)
6285 (cond
6286 ;; case 1: simple name, e.g. foo
6287 ((js2-name-node-p node)
6288 (setq name (js2-name-node-name node))
6289 ;; possible for name to be nil in rare cases - saw it when
6290 ;; running js2-mode on an elisp buffer. Might as well try to
6291 ;; make it so js2-mode never barfs.
6292 (when name
6293 (setq face (if (string-match js2-ecma-global-props name)
6294 'font-lock-constant-face))
6295 (when face
6296 (setq pos (js2-node-pos node)
6297 end (+ pos (js2-node-len node)))
6298 (js2-set-face pos end face 'record))))
6299 ;; case 2: property access or function call
6300 ((or (js2-prop-get-node-p node)
6301 ;; highlight function call if expr is a prop-get node
6302 ;; or a plain name (i.e. unqualified function call)
6303 (and (setq call-p (js2-call-node-p node))
6304 (setq callee (js2-call-node-target node)) ; separate setq!
6305 (or (js2-prop-get-node-p callee)
6306 (js2-name-node-p callee))))
6307 (setq parent node
6308 node (if call-p callee node))
6309 (if (and call-p (js2-name-node-p callee))
6310 (setq prop callee)
6311 (setq target (js2-prop-get-node-left node)
6312 prop (js2-prop-get-node-right node)))
6313 (cond
6314 ((js2-name-node-p prop)
6315 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6316 (js2-parse-highlight-prop-get parent target prop call-p))
6317 ((js2-name-node-p target)
6318 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6319 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6320
6321 (defun js2-parse-highlight-member-expr-fn-name (expr)
6322 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6323 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6324 We currently only handle the case where the last component is a prop-get
6325 of a simple name. Called before EXPR has a parent node."
6326 (let (pos
6327 (name (and (js2-prop-get-node-p expr)
6328 (js2-prop-get-node-right expr))))
6329 (when (js2-name-node-p name)
6330 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6331 (js2-node-pos name)))
6332 (+ pos (js2-node-len name))
6333 'font-lock-function-name-face
6334 'record))))
6335
6336 ;; source: http://jsdoc.sourceforge.net/
6337 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6338 ;; allows type specifications, and needs work before entering the wild.
6339
6340 (defconst js2-jsdoc-param-tag-regexp
6341 (concat "^\\s-*\\*+\\s-*\\(@"
6342 "\\(?:param\\|argument\\)"
6343 "\\)"
6344 "\\s-*\\({[^}]+}\\)?" ; optional type
6345 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6346 "\\>")
6347 "Matches jsdoc tags with optional type and optional param name.")
6348
6349 (defconst js2-jsdoc-typed-tag-regexp
6350 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6351 (regexp-opt
6352 '("enum"
6353 "extends"
6354 "field"
6355 "id"
6356 "implements"
6357 "lends"
6358 "mods"
6359 "requires"
6360 "return"
6361 "returns"
6362 "throw"
6363 "throws"))
6364 "\\)\\)\\s-*\\({[^}]+}\\)?")
6365 "Matches jsdoc tags with optional type.")
6366
6367 (defconst js2-jsdoc-arg-tag-regexp
6368 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6369 (regexp-opt
6370 '("alias"
6371 "augments"
6372 "borrows"
6373 "bug"
6374 "base"
6375 "config"
6376 "default"
6377 "define"
6378 "exception"
6379 "function"
6380 "member"
6381 "memberOf"
6382 "name"
6383 "namespace"
6384 "property"
6385 "since"
6386 "suppress"
6387 "this"
6388 "throws"
6389 "type"
6390 "version"))
6391 "\\)\\)\\s-+\\([^ \t]+\\)")
6392 "Matches jsdoc tags with a single argument.")
6393
6394 (defconst js2-jsdoc-empty-tag-regexp
6395 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6396 (regexp-opt
6397 '("addon"
6398 "author"
6399 "class"
6400 "const"
6401 "constant"
6402 "constructor"
6403 "constructs"
6404 "deprecated"
6405 "desc"
6406 "description"
6407 "event"
6408 "example"
6409 "exec"
6410 "export"
6411 "fileoverview"
6412 "final"
6413 "function"
6414 "hidden"
6415 "ignore"
6416 "implicitCast"
6417 "inheritDoc"
6418 "inner"
6419 "interface"
6420 "license"
6421 "noalias"
6422 "noshadow"
6423 "notypecheck"
6424 "override"
6425 "owner"
6426 "preserve"
6427 "preserveTry"
6428 "private"
6429 "protected"
6430 "public"
6431 "static"
6432 "supported"
6433 ))
6434 "\\)\\)\\s-*")
6435 "Matches empty jsdoc tags.")
6436
6437 (defconst js2-jsdoc-link-tag-regexp
6438 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6439 "Matches a jsdoc link or code tag.")
6440
6441 (defconst js2-jsdoc-see-tag-regexp
6442 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6443 "Matches a jsdoc @see tag.")
6444
6445 (defconst js2-jsdoc-html-tag-regexp
6446 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6447 "Matches a simple (no attributes) html start- or end-tag.")
6448
6449 (defun js2-jsdoc-highlight-helper ()
6450 (js2-set-face (match-beginning 1)
6451 (match-end 1)
6452 'js2-jsdoc-tag)
6453 (if (match-beginning 2)
6454 (if (save-excursion
6455 (goto-char (match-beginning 2))
6456 (= (char-after) ?{))
6457 (js2-set-face (1+ (match-beginning 2))
6458 (1- (match-end 2))
6459 'js2-jsdoc-type)
6460 (js2-set-face (match-beginning 2)
6461 (match-end 2)
6462 'js2-jsdoc-value)))
6463 (if (match-beginning 3)
6464 (js2-set-face (match-beginning 3)
6465 (match-end 3)
6466 'js2-jsdoc-value)))
6467
6468 (defun js2-highlight-jsdoc (ast)
6469 "Highlight doc comment tags."
6470 (let ((comments (js2-ast-root-comments ast))
6471 beg end)
6472 (save-excursion
6473 (dolist (node comments)
6474 (when (eq (js2-comment-node-format node) 'jsdoc)
6475 (setq beg (js2-node-abs-pos node)
6476 end (+ beg (js2-node-len node)))
6477 (save-restriction
6478 (narrow-to-region beg end)
6479 (dolist (re (list js2-jsdoc-param-tag-regexp
6480 js2-jsdoc-typed-tag-regexp
6481 js2-jsdoc-arg-tag-regexp
6482 js2-jsdoc-link-tag-regexp
6483 js2-jsdoc-see-tag-regexp
6484 js2-jsdoc-empty-tag-regexp))
6485 (goto-char beg)
6486 (while (re-search-forward re nil t)
6487 (js2-jsdoc-highlight-helper)))
6488 ;; simple highlighting for html tags
6489 (goto-char beg)
6490 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6491 (js2-set-face (match-beginning 1)
6492 (match-end 1)
6493 'js2-jsdoc-html-tag-delimiter)
6494 (js2-set-face (match-beginning 2)
6495 (match-end 2)
6496 'js2-jsdoc-html-tag-name)
6497 (js2-set-face (match-beginning 3)
6498 (match-end 3)
6499 'js2-jsdoc-html-tag-delimiter))))))))
6500
6501 (defun js2-highlight-assign-targets (_node left right)
6502 "Highlight function properties and external variables."
6503 (let (leftpos name)
6504 ;; highlight vars and props assigned function values
6505 (when (js2-function-node-p right)
6506 (cond
6507 ;; var foo = function() {...}
6508 ((js2-name-node-p left)
6509 (setq name left))
6510 ;; foo.bar.baz = function() {...}
6511 ((and (js2-prop-get-node-p left)
6512 (js2-name-node-p (js2-prop-get-node-right left)))
6513 (setq name (js2-prop-get-node-right left))))
6514 (when name
6515 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6516 (+ leftpos (js2-node-len name))
6517 'font-lock-function-name-face
6518 'record)))))
6519
6520 (defun js2-record-name-node (node)
6521 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6522 later. NODE must be a name node."
6523 (let ((leftpos (js2-node-abs-pos node)))
6524 (push (list node js2-current-scope
6525 leftpos
6526 (+ leftpos (js2-node-len node)))
6527 js2-recorded-identifiers)))
6528
6529 (defun js2-highlight-undeclared-vars ()
6530 "After entire parse is finished, look for undeclared variable references.
6531 We have to wait until entire buffer is parsed, since JavaScript permits var
6532 decls to occur after they're used.
6533
6534 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6535 it is considered declared."
6536 (let (name)
6537 (dolist (entry js2-recorded-identifiers)
6538 (destructuring-bind (name-node scope pos end) entry
6539 (setq name (js2-name-node-name name-node))
6540 (unless (or (member name js2-global-externs)
6541 (member name js2-default-externs)
6542 (member name js2-additional-externs)
6543 (js2-get-defining-scope scope name))
6544 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6545 'js2-external-variable))))
6546 (setq js2-recorded-identifiers nil)))
6547
6548 (defun js2-set-default-externs ()
6549 "Set the value of `js2-default-externs' based on the various
6550 `js2-include-?-externs' variables."
6551 (setq js2-default-externs
6552 (append js2-ecma-262-externs
6553 (if js2-include-browser-externs js2-browser-externs)
6554 (if js2-include-rhino-externs js2-rhino-externs)
6555 (if js2-include-node-externs js2-node-externs)
6556 (if (or js2-include-browser-externs js2-include-node-externs)
6557 js2-typed-array-externs))))
6558
6559 (defun js2-apply-jslint-globals ()
6560 (setq js2-additional-externs
6561 (nconc (js2-get-jslint-globals)
6562 js2-additional-externs)))
6563
6564 (defun js2-get-jslint-globals ()
6565 (loop for node in (js2-ast-root-comments js2-mode-ast)
6566 when (and (eq 'block (js2-comment-node-format node))
6567 (save-excursion
6568 (goto-char (js2-node-abs-pos node))
6569 (looking-at "/\\*global ")))
6570 append (js2-get-jslint-globals-in
6571 (match-end 0)
6572 (js2-node-abs-end node))))
6573
6574 (defun js2-get-jslint-globals-in (beg end)
6575 (let (res)
6576 (save-excursion
6577 (goto-char beg)
6578 (while (re-search-forward js2-mode-identifier-re end t)
6579 (let ((match (match-string 0)))
6580 (unless (member match '("true" "false"))
6581 (push match res)))))
6582 (nreverse res)))
6583
6584 ;;; IMenu support
6585
6586 ;; We currently only support imenu, but eventually should support speedbar and
6587 ;; possibly other browsing mechanisms.
6588
6589 ;; The basic strategy is to identify function assignment targets of the form
6590 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6591 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6592 ;; for imenu after parsing is finished.
6593
6594 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6595 ;; JavaScript, and the general problem is undecidable. However, several forms
6596 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6597 ;; include:
6598
6599 ;; function foo() -- function declaration
6600 ;; foo = function() -- function expression assigned to variable
6601 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6602 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6603 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6604 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6605 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6606 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6607 ;; function foo() {function bar() {...}} -- nested function
6608 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6609
6610 ;; This list boils down to a few forms that can be combined recursively.
6611 ;; Top-level named function declarations include both the left-hand (name)
6612 ;; and the right-hand (function value) expressions needed to produce an imenu
6613 ;; entry. The other "right-hand" forms we need to look for are:
6614 ;; - functions declared as props/getters/setters in object literals
6615 ;; - nested named function declarations
6616 ;; The "left-hand" expressions that functions can be assigned to include:
6617 ;; - local/global variables
6618 ;; - nested property-get expressions like a.b.c.d
6619 ;; - element gets like foo[10] or foo['bar'] where the index
6620 ;; expression can be trivially converted to a property name. They
6621 ;; effectively then become property gets.
6622
6623 ;; All the different definition types are canonicalized into the form
6624 ;; foo.bar.baz = position-of-function-keyword
6625
6626 ;; We need to build a trie-like structure for imenu. As an example,
6627 ;; consider the following JavaScript code:
6628
6629 ;; a = function() {...} // function at position 5
6630 ;; b = function() {...} // function at position 25
6631 ;; foo = function() {...} // function at position 100
6632 ;; foo.bar = function() {...} // function at position 200
6633 ;; foo.bar.baz = function() {...} // function at position 300
6634 ;; foo.bar.zab = function() {...} // function at position 400
6635
6636 ;; During parsing we accumulate an entry for each definition in
6637 ;; the variable `js2-imenu-recorder', like so:
6638
6639 ;; '((fn a 5)
6640 ;; (fn b 25)
6641 ;; (fn foo 100)
6642 ;; (fn foo bar 200)
6643 ;; (fn foo bar baz 300)
6644 ;; (fn foo bar zab 400))
6645
6646 ;; Where 'fn' is the respective function node.
6647 ;; After parsing these entries are merged into this alist-trie:
6648
6649 ;; '((a . 1)
6650 ;; (b . 2)
6651 ;; (foo (<definition> . 3)
6652 ;; (bar (<definition> . 6)
6653 ;; (baz . 100)
6654 ;; (zab . 200))))
6655
6656 ;; Note the wacky need for a <definition> name. The token can be anything
6657 ;; that isn't a valid JavaScript identifier, because you might make foo
6658 ;; a function and then start setting properties on it that are also functions.
6659
6660 (defun js2-prop-node-name (node)
6661 "Return the name of a node that may be a property-get/property-name.
6662 If NODE is not a valid name-node, string-node or integral number-node,
6663 returns nil. Otherwise returns the string name/value of the node."
6664 (cond
6665 ((js2-name-node-p node)
6666 (js2-name-node-name node))
6667 ((js2-string-node-p node)
6668 (js2-string-node-value node))
6669 ((and (js2-number-node-p node)
6670 (string-match "^[0-9]+$" (js2-number-node-value node)))
6671 (js2-number-node-value node))
6672 ((js2-this-node-p node)
6673 "this")))
6674
6675 (defun js2-node-qname-component (node)
6676 "Return the name of this node, if it contributes to a qname.
6677 Returns nil if the node doesn't contribute."
6678 (copy-sequence
6679 (or (js2-prop-node-name node)
6680 (if (and (js2-function-node-p node)
6681 (js2-function-node-name node))
6682 (js2-name-node-name (js2-function-node-name node))))))
6683
6684 (defun js2-record-imenu-entry (fn-node qname pos)
6685 "Add an entry to `js2-imenu-recorder'.
6686 FN-NODE should be the current item's function node.
6687
6688 Associate FN-NODE with its QNAME for later lookup.
6689 This is used in postprocessing the chain list. For each chain, we find
6690 the parent function, look up its qname, then prepend a copy of it to the chain."
6691 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6692 (unless js2-imenu-function-map
6693 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6694 (puthash fn-node qname js2-imenu-function-map))
6695
6696 (defun js2-record-imenu-functions (node &optional var)
6697 "Record function definitions for imenu.
6698 NODE is a function node or an object literal.
6699 VAR, if non-nil, is the expression that NODE is being assigned to.
6700 When passed arguments of wrong type, does nothing."
6701 (when js2-parse-ide-mode
6702 (let ((fun-p (js2-function-node-p node))
6703 qname fname-node)
6704 (cond
6705 ;; non-anonymous function declaration?
6706 ((and fun-p
6707 (not var)
6708 (setq fname-node (js2-function-node-name node)))
6709 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6710 ;; for remaining forms, compute left-side tree branch first
6711 ((and var (setq qname (js2-compute-nested-prop-get var)))
6712 (cond
6713 ;; foo.bar.baz = function
6714 (fun-p
6715 (js2-record-imenu-entry node qname (js2-node-pos node)))
6716 ;; foo.bar.baz = object-literal
6717 ;; look for nested functions: {a: {b: function() {...} }}
6718 ((js2-object-node-p node)
6719 ;; Node position here is still absolute, since the parser
6720 ;; passes the assignment target and value expressions
6721 ;; to us before they are added as children of the assignment node.
6722 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6723
6724 (defun js2-compute-nested-prop-get (node)
6725 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6726 component nodes as a list. Otherwise return nil. Element-gets are treated
6727 as property-gets if the index expression is a string, or a positive integer."
6728 (let (left right head)
6729 (cond
6730 ((or (js2-name-node-p node)
6731 (js2-this-node-p node))
6732 (list node))
6733 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6734 ((js2-prop-get-node-p node) ; foo.bar
6735 (setq left (js2-prop-get-node-left node)
6736 right (js2-prop-get-node-right node))
6737 (if (setq head (js2-compute-nested-prop-get left))
6738 (nconc head (list right))))
6739 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6740 (setq left (js2-elem-get-node-target node)
6741 right (js2-elem-get-node-element node))
6742 (if (or (js2-string-node-p right) ; ['bar']
6743 (and (js2-number-node-p right) ; [10]
6744 (string-match "^[0-9]+$"
6745 (js2-number-node-value right))))
6746 (if (setq head (js2-compute-nested-prop-get left))
6747 (nconc head (list right))))))))
6748
6749 (defun js2-record-object-literal (node qname pos)
6750 "Recursively process an object literal looking for functions.
6751 NODE is an object literal that is the right-hand child of an assignment
6752 expression. QNAME is a list of nodes representing the assignment target,
6753 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6754 POS is the absolute position of the node.
6755 We do a depth-first traversal of NODE. For any functions we find,
6756 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6757 (let (right)
6758 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6759 (let ((left (js2-infix-node-left e))
6760 ;; Element positions are relative to the parent position.
6761 (pos (+ pos (js2-node-pos e))))
6762 (cond
6763 ;; foo: function() {...}
6764 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6765 (when (js2-prop-node-name left)
6766 ;; As a policy decision, we record the position of the property,
6767 ;; not the position of the `function' keyword, since the property
6768 ;; is effectively the name of the function.
6769 (js2-record-imenu-entry right (append qname (list left)) pos)))
6770 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6771 ((js2-object-node-p right)
6772 (js2-record-object-literal right
6773 (append qname (list (js2-infix-node-left e)))
6774 (+ pos (js2-node-pos right)))))))))
6775
6776 (defun js2-node-top-level-decl-p (node)
6777 "Return t if NODE's name is defined in the top-level scope.
6778 Also returns t if NODE's name is not defined in any scope, since it implies
6779 that it's an external variable, which must also be in the top-level scope."
6780 (let* ((name (js2-prop-node-name node))
6781 (this-scope (js2-node-get-enclosing-scope node))
6782 defining-scope)
6783 (cond
6784 ((js2-this-node-p node)
6785 nil)
6786 ((null this-scope)
6787 t)
6788 ((setq defining-scope (js2-get-defining-scope this-scope name))
6789 (js2-ast-root-p defining-scope))
6790 (t t))))
6791
6792 (defun js2-wrapper-function-p (node)
6793 "Return t if NODE is a function expression that's immediately invoked.
6794 NODE must be `js2-function-node'."
6795 (let ((parent (js2-node-parent node)))
6796 (or
6797 ;; function(){...}();
6798 (js2-call-node-p parent)
6799 (and (js2-paren-node-p parent)
6800 ;; (function(){...})();
6801 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6802 ;; (function(){...}).call(this);
6803 (and (js2-prop-get-node-p parent)
6804 (member (js2-name-node-name (js2-prop-get-node-right parent))
6805 '("call" "apply"))
6806 (js2-call-node-p (js2-node-parent parent))))))))
6807
6808 (defun js2-browse-postprocess-chains (entries)
6809 "Modify function-declaration name chains after parsing finishes.
6810 Some of the information is only available after the parse tree is complete.
6811 For instance, processing a nested scope requires a parent function node."
6812 (let (result fn parent-qname p elem)
6813 (dolist (entry entries)
6814 ;; function node goes first
6815 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6816 ;; Examine head's defining scope:
6817 ;; Pre-processed chain, or top-level/external, keep as-is.
6818 (if (or (stringp head) (js2-node-top-level-decl-p head))
6819 (push chain result)
6820 (when (js2-this-node-p head)
6821 (setq chain (cdr chain))) ; discard this-node
6822 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6823 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6824 (when (eq parent-qname 'not-found)
6825 ;; anonymous function expressions are not recorded
6826 ;; during the parse, so we need to handle this case here
6827 (setq parent-qname
6828 (if (js2-wrapper-function-p fn)
6829 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6830 (if (js2-ast-root-p grandparent)
6831 nil
6832 (gethash grandparent js2-imenu-function-map 'skip)))
6833 'skip))
6834 (puthash fn parent-qname js2-imenu-function-map))
6835 (unless (eq parent-qname 'skip)
6836 ;; prefix parent fn qname to this chain.
6837 (let ((qname (append parent-qname chain)))
6838 (puthash current-fn (butlast qname) js2-imenu-function-map)
6839 (push qname result)))))))
6840 ;; finally replace each node in each chain with its name.
6841 (dolist (chain result)
6842 (setq p chain)
6843 (while p
6844 (if (js2-node-p (setq elem (car p)))
6845 (setcar p (js2-node-qname-component elem)))
6846 (setq p (cdr p))))
6847 result))
6848
6849 ;; Merge name chains into a trie-like tree structure of nested lists.
6850 ;; To simplify construction of the trie, we first build it out using the rule
6851 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6852 ;; [key, num-or-list]. The second element can be a number; if so, this key
6853 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6854 ;; associated with the key at this level.) Otherwise the second element is
6855 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6856 ;; a simple recursive formulation.
6857 ;;
6858 ;; js2-mode is building the data structure for imenu. The imenu documentation
6859 ;; claims that it's the structure above, but in practice it wants the children
6860 ;; at the same list level as the key for that level, which is how I've drawn
6861 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6862 ;; list wrapper around the children at each level.
6863 ;;
6864 ;; A completed nested imenu-alist entry looks like this:
6865 ;; '(("foo"
6866 ;; ("<definition>" . 7)
6867 ;; ("bar"
6868 ;; ("a" . 40)
6869 ;; ("b" . 60))))
6870 ;;
6871 ;; In particular, the documentation for `imenu--index-alist' says that
6872 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6873 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6874
6875 (defun js2-treeify (lst)
6876 "Convert (a b c d) to (a ((b ((c d)))))."
6877 (if (null (cddr lst)) ; list length <= 2
6878 lst
6879 (list (car lst) (list (js2-treeify (cdr lst))))))
6880
6881 (defun js2-build-alist-trie (chains trie)
6882 "Merge declaration name chains into a trie-like alist structure for imenu.
6883 CHAINS is the qname chain list produced during parsing. TRIE is a
6884 list of elements built up so far."
6885 (let (head tail pos branch kids)
6886 (dolist (chain chains)
6887 (setq head (car chain)
6888 tail (cdr chain)
6889 pos (if (numberp (car tail)) (car tail))
6890 branch (js2-find-if (lambda (n)
6891 (string= (car n) head))
6892 trie)
6893 kids (second branch))
6894 (cond
6895 ;; case 1: this key isn't in the trie yet
6896 ((null branch)
6897 (if trie
6898 (setcdr (last trie) (list (js2-treeify chain)))
6899 (setq trie (list (js2-treeify chain)))))
6900 ;; case 2: key is present with a single number entry: replace w/ list
6901 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6902 ;; ("<definition>" 20)))
6903 ((numberp kids)
6904 (setcar (cdr branch)
6905 (list (list "<definition-1>" kids)
6906 (if pos
6907 (list "<definition-2>" pos)
6908 (js2-treeify tail)))))
6909 ;; case 3: key is there (with kids), and we're a number entry
6910 (pos
6911 (setcdr (last kids)
6912 (list
6913 (list (format "<definition-%d>"
6914 (1+ (loop for kid in kids
6915 count (eq ?< (aref (car kid) 0)))))
6916 pos))))
6917 ;; case 4: key is there with kids, need to merge in our chain
6918 (t
6919 (js2-build-alist-trie (list tail) kids))))
6920 trie))
6921
6922 (defun js2-flatten-trie (trie)
6923 "Convert TRIE to imenu-format.
6924 Recurses through nodes, and for each one whose second element is a list,
6925 appends the list's flattened elements to the current element. Also
6926 changes the tails into conses. For instance, this pre-flattened trie
6927
6928 '(a ((b 20)
6929 (c ((d 30)
6930 (e 40)))))
6931
6932 becomes
6933
6934 '(a (b . 20)
6935 (c (d . 30)
6936 (e . 40)))
6937
6938 Note that the root of the trie has no key, just a list of chains.
6939 This is also true for the value of any key with multiple children,
6940 e.g. key 'c' in the example above."
6941 (cond
6942 ((listp (car trie))
6943 (mapcar #'js2-flatten-trie trie))
6944 (t
6945 (if (numberp (second trie))
6946 (cons (car trie) (second trie))
6947 ;; else pop list and append its kids
6948 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6949
6950 (defun js2-build-imenu-index ()
6951 "Turn `js2-imenu-recorder' into an imenu data structure."
6952 (unless (eq js2-imenu-recorder 'empty)
6953 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
6954 (result (js2-build-alist-trie chains nil)))
6955 (js2-flatten-trie result))))
6956
6957 (defun js2-test-print-chains (chains)
6958 "Print a list of qname chains.
6959 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
6960 i.e. one or more nodes, and an integer position as the list tail."
6961 (mapconcat (lambda (chain)
6962 (concat "("
6963 (mapconcat (lambda (elem)
6964 (if (js2-node-p elem)
6965 (or (js2-node-qname-component elem)
6966 "nil")
6967 (number-to-string elem)))
6968 chain
6969 " ")
6970 ")"))
6971 chains
6972 "\n"))
6973
6974 ;;; Parser
6975
6976 (defconst js2-version "1.8.5"
6977 "Version of JavaScript supported.")
6978
6979 (defun js2-record-face (face &optional token)
6980 "Record a style run of FACE for TOKEN or the current token."
6981 (unless token (setq token (js2-current-token)))
6982 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
6983
6984 (defsubst js2-node-end (n)
6985 "Computes the absolute end of node N.
6986 Use with caution! Assumes `js2-node-pos' is -absolute-, which
6987 is only true until the node is added to its parent; i.e., while parsing."
6988 (+ (js2-node-pos n)
6989 (js2-node-len n)))
6990
6991 (defun js2-record-comment (token)
6992 "Record a comment in `js2-scanned-comments'."
6993 (let ((ct (js2-token-comment-type token))
6994 (beg (js2-token-beg token))
6995 (end (js2-token-end token)))
6996 (push (make-js2-comment-node :len (- end beg)
6997 :format ct)
6998 js2-scanned-comments)
6999 (when js2-parse-ide-mode
7000 (js2-record-face (if (eq ct 'jsdoc)
7001 'font-lock-doc-face
7002 'font-lock-comment-face)
7003 token)
7004 (when (memq ct '(html preprocessor))
7005 ;; Tell cc-engine the bounds of the comment.
7006 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7007
7008 (defun js2-peek-token ()
7009 "Return the next token type without consuming it.
7010 If `js2-ti-lookahead' is positive, return the type of next token
7011 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7012 (if (not (zerop js2-ti-lookahead))
7013 (js2-token-type
7014 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7015 (let ((tt (js2-get-token-internal)))
7016 (js2-unget-token)
7017 tt)))
7018
7019 (defalias 'js2-next-token 'js2-get-token)
7020
7021 (defun js2-match-token (match)
7022 "Get next token and return t if it matches MATCH, a bytecode.
7023 Returns nil and consumes nothing if MATCH is not the next token."
7024 (if (/= (js2-get-token) match)
7025 (ignore (js2-unget-token))
7026 t))
7027
7028 (defun js2-match-contextual-kwd (name)
7029 "Consume and return t if next token is `js2-NAME', and its
7030 string is NAME. Returns nil and keeps current token otherwise."
7031 (if (or (/= (js2-get-token) js2-NAME)
7032 (not (string= (js2-current-token-string) name)))
7033 (progn
7034 (js2-unget-token)
7035 nil)
7036 (js2-record-face 'font-lock-keyword-face)
7037 t))
7038
7039 (defun js2-valid-prop-name-token (tt)
7040 (or (= tt js2-NAME)
7041 (and js2-allow-keywords-as-property-names
7042 (plusp tt)
7043 (aref js2-kwd-tokens tt))))
7044
7045 (defun js2-match-prop-name ()
7046 "Consume token and return t if next token is a valid property name.
7047 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7048 is non-nil and it's a keyword token."
7049 (if (js2-valid-prop-name-token (js2-get-token))
7050 t
7051 (js2-unget-token)
7052 nil))
7053
7054 (defun js2-must-match-prop-name (msg-id &optional pos len)
7055 (if (js2-match-prop-name)
7056 t
7057 (js2-report-error msg-id nil pos len)
7058 nil))
7059
7060 (defun js2-peek-token-or-eol ()
7061 "Return js2-EOL if the next token immediately follows a newline.
7062 Else returns the next token. Used in situations where we don't
7063 consider certain token types valid if they are preceded by a newline.
7064 One example is the postfix ++ or -- operator, which has to be on the
7065 same line as its operand."
7066 (let ((tt (js2-get-token))
7067 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7068 (js2-unget-token)
7069 (if follows-eol
7070 js2-EOL
7071 tt)))
7072
7073 (defun js2-must-match (token msg-id &optional pos len)
7074 "Match next token to token code TOKEN, or record a syntax error.
7075 MSG-ID is the error message to report if the match fails.
7076 Returns t on match, nil if no match."
7077 (if (js2-match-token token)
7078 t
7079 (js2-report-error msg-id nil pos len)
7080 nil))
7081
7082 (defsubst js2-inside-function ()
7083 (plusp js2-nesting-of-function))
7084
7085 (defun js2-set-requires-activation ()
7086 (if (js2-function-node-p js2-current-script-or-fn)
7087 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7088
7089 (defun js2-check-activation-name (name _token)
7090 (when (js2-inside-function)
7091 ;; skip language-version 1.2 check from Rhino
7092 (if (or (string= "arguments" name)
7093 (and js2-compiler-activation-names ; only used in codegen
7094 (gethash name js2-compiler-activation-names)))
7095 (js2-set-requires-activation))))
7096
7097 (defun js2-set-is-generator ()
7098 (let ((fn-node js2-current-script-or-fn))
7099 (when (and (js2-function-node-p fn-node)
7100 (not (js2-function-node-generator-type fn-node)))
7101 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7102
7103 (defun js2-must-have-xml ()
7104 (unless js2-compiler-xml-available
7105 (js2-report-error "msg.XML.not.available")))
7106
7107 (defun js2-push-scope (scope)
7108 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7109 (assert (js2-scope-p scope))
7110 (assert (null (js2-scope-parent-scope scope)))
7111 (assert (not (eq js2-current-scope scope)))
7112 (setf (js2-scope-parent-scope scope) js2-current-scope
7113 js2-current-scope scope))
7114
7115 (defsubst js2-pop-scope ()
7116 (setq js2-current-scope
7117 (js2-scope-parent-scope js2-current-scope)))
7118
7119 (defun js2-enter-loop (loop-node)
7120 (push loop-node js2-loop-set)
7121 (push loop-node js2-loop-and-switch-set)
7122 (js2-push-scope loop-node)
7123 ;; Tell the current labeled statement (if any) its statement,
7124 ;; and set the jump target of the first label to the loop.
7125 ;; These are used in `js2-parse-continue' to verify that the
7126 ;; continue target is an actual labeled loop. (And for codegen.)
7127 (when js2-labeled-stmt
7128 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7129 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7130 js2-labeled-stmt))) loop-node)))
7131
7132 (defun js2-exit-loop ()
7133 (pop js2-loop-set)
7134 (pop js2-loop-and-switch-set)
7135 (js2-pop-scope))
7136
7137 (defsubst js2-enter-switch (switch-node)
7138 (push switch-node js2-loop-and-switch-set))
7139
7140 (defsubst js2-exit-switch ()
7141 (pop js2-loop-and-switch-set))
7142
7143 (defun js2-parse (&optional buf cb)
7144 "Tell the js2 parser to parse a region of JavaScript.
7145
7146 BUF is a buffer or buffer name containing the code to parse.
7147 Call `narrow-to-region' first to parse only part of the buffer.
7148
7149 The returned AST root node is given some additional properties:
7150 `node-count' - total number of nodes in the AST
7151 `buffer' - BUF. The buffer it refers to may change or be killed,
7152 so the value is not necessarily reliable.
7153
7154 An optional callback CB can be specified to report parsing
7155 progress. If `(functionp CB)' returns t, it will be called with
7156 the current line number once before parsing begins, then again
7157 each time the lexer reaches a new line number.
7158
7159 CB can also be a list of the form `(symbol cb ...)' to specify
7160 multiple callbacks with different criteria. Each symbol is a
7161 criterion keyword, and the following element is the callback to
7162 call
7163
7164 :line - called whenever the line number changes
7165 :token - called for each new token consumed
7166
7167 The list of criteria could be extended to include entering or
7168 leaving a statement, an expression, or a function definition."
7169 (if (and cb (not (functionp cb)))
7170 (error "criteria callbacks not yet implemented"))
7171 (let ((inhibit-point-motion-hooks t)
7172 (js2-compiler-xml-available (>= js2-language-version 160))
7173 ;; This is a recursive-descent parser, so give it a big stack.
7174 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7175 (max-specpdl-size (max max-specpdl-size 3000))
7176 (case-fold-search nil)
7177 ast)
7178 (message nil) ; clear any error message from previous parse
7179 (with-current-buffer (or buf (current-buffer))
7180 (setq js2-scanned-comments nil
7181 js2-parsed-errors nil
7182 js2-parsed-warnings nil
7183 js2-imenu-recorder nil
7184 js2-imenu-function-map nil
7185 js2-label-set nil)
7186 (js2-init-scanner)
7187 (setq ast (with-silent-modifications
7188 (js2-do-parse)))
7189 (unless js2-ts-hit-eof
7190 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7191 (setf (js2-ast-root-errors ast) js2-parsed-errors
7192 (js2-ast-root-warnings ast) js2-parsed-warnings)
7193 ;; if we didn't find any declarations, put a dummy in this list so we
7194 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7195 (unless js2-imenu-recorder
7196 (setq js2-imenu-recorder 'empty))
7197 (run-hooks 'js2-parse-finished-hook)
7198 ast)))
7199
7200 ;; Corresponds to Rhino's Parser.parse() method.
7201 (defun js2-do-parse ()
7202 "Parse current buffer starting from current point.
7203 Scanner should be initialized."
7204 (let ((pos js2-ts-cursor)
7205 (end js2-ts-cursor) ; in case file is empty
7206 root n tt)
7207 ;; initialize buffer-local parsing vars
7208 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7209 js2-current-script-or-fn root
7210 js2-current-scope root
7211 js2-nesting-of-function 0
7212 js2-labeled-stmt nil
7213 js2-recorded-identifiers nil) ; for js2-highlight
7214 (while (/= (setq tt (js2-get-token)) js2-EOF)
7215 (if (= tt js2-FUNCTION)
7216 (progn
7217 (setq n (if js2-called-by-compile-function
7218 (js2-parse-function-expr)
7219 (js2-parse-function-stmt))))
7220 ;; not a function - parse a statement
7221 (js2-unget-token)
7222 (setq n (js2-parse-statement)))
7223 ;; add function or statement to script
7224 (setq end (js2-node-end n))
7225 (js2-block-node-push root n))
7226 ;; add comments to root in lexical order
7227 (when js2-scanned-comments
7228 ;; if we find a comment beyond end of normal kids, use its end
7229 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7230 (dolist (comment js2-scanned-comments)
7231 (push comment (js2-ast-root-comments root))
7232 (js2-node-add-children root comment)))
7233 (setf (js2-node-len root) (- end pos))
7234 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7235 ;; Give extensions a chance to muck with things before highlighting starts.
7236 (let ((js2-additional-externs js2-additional-externs))
7237 (save-excursion
7238 (run-hooks 'js2-post-parse-callbacks))
7239 (js2-highlight-undeclared-vars))
7240 root))
7241
7242 (defun js2-function-parser ()
7243 (js2-get-token)
7244 (js2-parse-function-stmt))
7245
7246 (defun js2-parse-function-closure-body (fn-node)
7247 "Parse a JavaScript 1.8 function closure body."
7248 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7249 (if js2-ts-hit-eof
7250 (js2-report-error "msg.no.brace.body" nil
7251 (js2-node-pos fn-node)
7252 (- js2-ts-cursor (js2-node-pos fn-node)))
7253 (js2-node-add-children fn-node
7254 (setf (js2-function-node-body fn-node)
7255 (js2-parse-expr t))))))
7256
7257 (defun js2-parse-function-body (fn-node)
7258 (js2-must-match js2-LC "msg.no.brace.body"
7259 (js2-node-pos fn-node)
7260 (- js2-ts-cursor (js2-node-pos fn-node)))
7261 (let ((pos (js2-current-token-beg)) ; LC position
7262 (pn (make-js2-block-node)) ; starts at LC position
7263 tt
7264 end)
7265 (incf js2-nesting-of-function)
7266 (unwind-protect
7267 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7268 (= tt js2-EOF)
7269 (= tt js2-RC)))
7270 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7271 (js2-parse-statement)
7272 (js2-get-token)
7273 (js2-parse-function-stmt))))
7274 (decf js2-nesting-of-function))
7275 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7276 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7277 (setq end (js2-current-token-end)))
7278 (setf (js2-node-pos pn) pos
7279 (js2-node-len pn) (- end pos))
7280 (setf (js2-function-node-body fn-node) pn)
7281 (js2-node-add-children fn-node pn)
7282 pn))
7283
7284 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7285 "Declare and fontify destructuring parameters inside NODE.
7286 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7287 (cond
7288 ((js2-name-node-p node)
7289 (let (leftpos)
7290 (js2-define-symbol decl-type (js2-name-node-name node)
7291 node ignore-not-in-block)
7292 (when face
7293 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7294 (+ leftpos (js2-node-len node))
7295 face 'record))))
7296 ((js2-object-node-p node)
7297 (dolist (elem (js2-object-node-elems node))
7298 (js2-define-destruct-symbols
7299 (if (js2-object-prop-node-p elem)
7300 (js2-object-prop-node-right elem)
7301 ;; abbreviated destructuring {a, b}
7302 elem)
7303 decl-type face ignore-not-in-block)))
7304 ((js2-array-node-p node)
7305 (dolist (elem (js2-array-node-elems node))
7306 (when elem
7307 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7308 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7309 (js2-node-len node)))))
7310
7311 (defun js2-parse-function-params (function-type fn-node pos)
7312 (if (js2-match-token js2-RP)
7313 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7314 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7315 (eq (js2-current-token-type) js2-NAME)))
7316 params param default-found rest-param-at)
7317 (when paren-free-arrow
7318 (js2-unget-token))
7319 (loop for tt = (js2-peek-token)
7320 do
7321 (cond
7322 ;; destructuring param
7323 ((and (not paren-free-arrow)
7324 (or (= tt js2-LB) (= tt js2-LC)))
7325 (js2-get-token)
7326 (when default-found
7327 (js2-report-error "msg.no.default.after.default.param"))
7328 (setq param (js2-parse-destruct-primary-expr))
7329 (js2-define-destruct-symbols param
7330 js2-LP
7331 'js2-function-param)
7332 (push param params))
7333 ;; variable name
7334 (t
7335 (when (and (>= js2-language-version 200)
7336 (not paren-free-arrow)
7337 (js2-match-token js2-TRIPLEDOT)
7338 (not rest-param-at))
7339 ;; to report errors if there are more parameters
7340 (setq rest-param-at (length params)))
7341 (js2-must-match js2-NAME "msg.no.parm")
7342 (js2-record-face 'js2-function-param)
7343 (setq param (js2-create-name-node))
7344 (js2-define-symbol js2-LP (js2-current-token-string) param)
7345 ;; default parameter value
7346 (when (or (and default-found
7347 (not rest-param-at)
7348 (js2-must-match js2-ASSIGN
7349 "msg.no.default.after.default.param"
7350 (js2-node-pos param)
7351 (js2-node-len param)))
7352 (and (>= js2-language-version 200)
7353 (js2-match-token js2-ASSIGN)))
7354 (assert (not paren-free-arrow))
7355 (let* ((pos (js2-node-pos param))
7356 (tt (js2-current-token-type))
7357 (op-pos (- (js2-current-token-beg) pos))
7358 (left param)
7359 (right (js2-parse-assign-expr))
7360 (len (- (js2-node-end right) pos)))
7361 (setq param (make-js2-assign-node
7362 :type tt :pos pos :len len :op-pos op-pos
7363 :left left :right right)
7364 default-found t)
7365 (js2-node-add-children param left right)))
7366 (push param params)))
7367 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7368 (js2-report-error "msg.param.after.rest" nil
7369 (js2-node-pos param) (js2-node-len param)))
7370 while
7371 (js2-match-token js2-COMMA))
7372 (when (and (not paren-free-arrow)
7373 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7374 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7375 (when rest-param-at
7376 (setf (js2-function-node-rest-p fn-node) t))
7377 (dolist (p params)
7378 (js2-node-add-children fn-node p)
7379 (push p (js2-function-node-params fn-node))))))
7380
7381 (defun js2-check-inconsistent-return-warning (fn-node name)
7382 "Possibly show inconsistent-return warning.
7383 Last token scanned is the close-curly for the function body."
7384 (when (and js2-mode-show-strict-warnings
7385 js2-strict-inconsistent-return-warning
7386 (not (js2-has-consistent-return-usage
7387 (js2-function-node-body fn-node))))
7388 ;; Have it extend from close-curly to bol or beginning of block.
7389 (let ((pos (save-excursion
7390 (goto-char (js2-current-token-end))
7391 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7392 (point-at-bol))))
7393 (end (js2-current-token-end)))
7394 (if (plusp (js2-name-node-length name))
7395 (js2-add-strict-warning "msg.no.return.value"
7396 (js2-name-node-name name) pos end)
7397 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7398
7399 (defun js2-parse-function-stmt ()
7400 (let ((pos (js2-current-token-beg))
7401 (star-p (js2-match-token js2-MUL)))
7402 (js2-must-match js2-NAME "msg.unnamed.function.stmt")
7403 (let ((name (js2-create-name-node t))
7404 pn member-expr)
7405 (cond
7406 ((js2-match-token js2-LP)
7407 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7408 (js2-allow-member-expr-as-function-name
7409 (setq member-expr (js2-parse-member-expr-tail nil name))
7410 (js2-parse-highlight-member-expr-fn-name member-expr)
7411 (js2-must-match js2-LP "msg.no.paren.parms")
7412 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7413 (js2-function-node-member-expr pn) member-expr)
7414 pn)
7415 (t
7416 (js2-report-error "msg.no.paren.parms")
7417 (make-js2-error-node))))))
7418
7419 (defun js2-parse-function-expr ()
7420 (let ((pos (js2-current-token-beg))
7421 (star-p (js2-match-token js2-MUL))
7422 name)
7423 (when (js2-match-token js2-NAME)
7424 (setq name (js2-create-name-node t)))
7425 (js2-must-match js2-LP "msg.no.paren.parms")
7426 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7427
7428 (defun js2-parse-function (function-type pos star-p &optional name)
7429 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7430 beginning of the first token (function keyword, unless it's an
7431 arrow function), NAME is js2-name-node."
7432 (let (fn-node lp)
7433 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7434 (setq lp (js2-current-token-beg)))
7435 (setf fn-node (make-js2-function-node :pos pos
7436 :name name
7437 :form function-type
7438 :lp (if lp (- lp pos))
7439 :generator-type (and star-p 'STAR)))
7440 (when name
7441 (js2-set-face (js2-node-pos name) (js2-node-end name)
7442 'font-lock-function-name-face 'record)
7443 (when (plusp (js2-name-node-length name))
7444 ;; Function statements define a symbol in the enclosing scope
7445 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7446 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7447 ;; 1. Nested functions are not affected by the dynamic scope flag
7448 ;; as dynamic scope is already a parent of their scope.
7449 ;; 2. Functions defined under the with statement also immune to
7450 ;; this setup, in which case dynamic scope is ignored in favor
7451 ;; of the with object.
7452 (setf (js2-function-node-ignore-dynamic fn-node) t))
7453 ;; dynamically bind all the per-function variables
7454 (let ((js2-current-script-or-fn fn-node)
7455 (js2-current-scope fn-node)
7456 (js2-nesting-of-with 0)
7457 (js2-end-flags 0)
7458 js2-label-set
7459 js2-loop-set
7460 js2-loop-and-switch-set)
7461 (js2-parse-function-params function-type fn-node pos)
7462 (when (eq function-type 'FUNCTION_ARROW)
7463 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7464 (if (and (>= js2-language-version 180)
7465 (/= (js2-peek-token) js2-LC))
7466 (js2-parse-function-closure-body fn-node)
7467 (js2-parse-function-body fn-node))
7468 (js2-check-inconsistent-return-warning fn-node name)
7469
7470 (when name
7471 (js2-node-add-children fn-node name)
7472 ;; Function expressions define a name only in the body of the
7473 ;; function, and only if not hidden by a parameter name
7474 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7475 (null (js2-scope-get-symbol js2-current-scope
7476 (js2-name-node-name name))))
7477 (js2-define-symbol js2-FUNCTION
7478 (js2-name-node-name name)
7479 fn-node))
7480 (when (eq function-type 'FUNCTION_STATEMENT)
7481 (js2-record-imenu-functions fn-node))))
7482
7483 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7484 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7485 ;; We wait until after parsing the function to set its parent scope,
7486 ;; since `js2-define-symbol' needs the defining-scope check to stop
7487 ;; at the function boundary when checking for redeclarations.
7488 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7489 fn-node))
7490
7491 (defun js2-parse-statements (&optional parent)
7492 "Parse a statement list. Last token consumed must be js2-LC.
7493
7494 PARENT can be a `js2-block-node', in which case the statements are
7495 appended to PARENT. Otherwise a new `js2-block-node' is created
7496 and returned.
7497
7498 This function does not match the closing js2-RC: the caller
7499 matches the RC so it can provide a suitable error message if not
7500 matched. This means it's up to the caller to set the length of
7501 the node to include the closing RC. The node start pos is set to
7502 the absolute buffer start position, and the caller should fix it
7503 up to be relative to the parent node. All children of this block
7504 node are given relative start positions and correct lengths."
7505 (let ((pn (or parent (make-js2-block-node)))
7506 tt)
7507 (setf (js2-node-pos pn) (js2-current-token-beg))
7508 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7509 (/= tt js2-RC))
7510 (js2-block-node-push pn (js2-parse-statement)))
7511 pn))
7512
7513 (defun js2-parse-statement ()
7514 (let (pn beg end)
7515 ;; coarse-grained user-interrupt check - needs work
7516 (and js2-parse-interruptable-p
7517 (zerop (% (incf js2-parse-stmt-count)
7518 js2-statements-per-pause))
7519 (input-pending-p)
7520 (throw 'interrupted t))
7521 (setq pn (js2-statement-helper))
7522 ;; no-side-effects warning check
7523 (unless (js2-node-has-side-effects pn)
7524 (setq end (js2-node-end pn))
7525 (save-excursion
7526 (goto-char end)
7527 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7528 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7529 pn))
7530
7531 ;; These correspond to the switch cases in Parser.statementHelper
7532 (defconst js2-parsers
7533 (let ((parsers (make-vector js2-num-tokens
7534 #'js2-parse-expr-stmt)))
7535 (aset parsers js2-BREAK #'js2-parse-break)
7536 (aset parsers js2-CONST #'js2-parse-const-var)
7537 (aset parsers js2-CONTINUE #'js2-parse-continue)
7538 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7539 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7540 (aset parsers js2-DO #'js2-parse-do)
7541 (aset parsers js2-FOR #'js2-parse-for)
7542 (aset parsers js2-FUNCTION #'js2-function-parser)
7543 (aset parsers js2-IF #'js2-parse-if)
7544 (aset parsers js2-LC #'js2-parse-block)
7545 (aset parsers js2-LET #'js2-parse-let-stmt)
7546 (aset parsers js2-NAME #'js2-parse-name-or-label)
7547 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7548 (aset parsers js2-SEMI #'js2-parse-semi)
7549 (aset parsers js2-SWITCH #'js2-parse-switch)
7550 (aset parsers js2-THROW #'js2-parse-throw)
7551 (aset parsers js2-TRY #'js2-parse-try)
7552 (aset parsers js2-VAR #'js2-parse-const-var)
7553 (aset parsers js2-WHILE #'js2-parse-while)
7554 (aset parsers js2-WITH #'js2-parse-with)
7555 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7556 parsers)
7557 "A vector mapping token types to parser functions.")
7558
7559 (defun js2-parse-warn-missing-semi (beg end)
7560 (and js2-mode-show-strict-warnings
7561 js2-strict-missing-semi-warning
7562 (js2-add-strict-warning
7563 "msg.missing.semi" nil
7564 ;; back up to beginning of statement or line
7565 (max beg (save-excursion
7566 (goto-char end)
7567 (point-at-bol)))
7568 end)))
7569
7570 (defconst js2-no-semi-insertion
7571 (list js2-IF
7572 js2-SWITCH
7573 js2-WHILE
7574 js2-DO
7575 js2-FOR
7576 js2-TRY
7577 js2-WITH
7578 js2-LC
7579 js2-ERROR
7580 js2-SEMI
7581 js2-FUNCTION)
7582 "List of tokens that don't do automatic semicolon insertion.")
7583
7584 (defconst js2-autoinsert-semi-and-warn
7585 (list js2-ERROR js2-EOF js2-RC))
7586
7587 (defun js2-statement-helper ()
7588 (let* ((tt (js2-get-token))
7589 (first-tt tt)
7590 (parser (if (= tt js2-ERROR)
7591 #'js2-parse-semi
7592 (aref js2-parsers tt)))
7593 pn)
7594 ;; If the statement is set, then it's been told its label by now.
7595 (and js2-labeled-stmt
7596 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7597 (setq js2-labeled-stmt nil))
7598 (setq pn (funcall parser))
7599 ;; Don't do auto semi insertion for certain statement types.
7600 (unless (or (memq first-tt js2-no-semi-insertion)
7601 (js2-labeled-stmt-node-p pn))
7602 (js2-auto-insert-semicolon pn))
7603 pn))
7604
7605 (defun js2-auto-insert-semicolon (pn)
7606 (let* ((tt (js2-get-token))
7607 (pos (js2-node-pos pn)))
7608 (cond
7609 ((= tt js2-SEMI)
7610 ;; extend the node bounds to include the semicolon.
7611 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
7612 ((memq tt js2-autoinsert-semi-and-warn)
7613 (js2-unget-token) ; Not ';', do not consume.
7614 ;; Autoinsert ;
7615 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7616 (t
7617 (if (not (js2-token-follows-eol-p (js2-current-token)))
7618 ;; Report error if no EOL or autoinsert ';' otherwise
7619 (js2-report-error "msg.no.semi.stmt")
7620 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7621 (js2-unget-token) ; Not ';', do not consume.
7622 ))))
7623
7624 (defun js2-parse-condition ()
7625 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7626 The parens are discarded and the expression node is returned.
7627 The `pos' field of the return value is set to an absolute position
7628 that must be fixed up by the caller.
7629 Return value is a list (EXPR LP RP), with absolute paren positions."
7630 (let (pn lp rp)
7631 (if (js2-must-match js2-LP "msg.no.paren.cond")
7632 (setq lp (js2-current-token-beg)))
7633 (setq pn (js2-parse-expr))
7634 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7635 (setq rp (js2-current-token-beg)))
7636 ;; Report strict warning on code like "if (a = 7) ..."
7637 (if (and js2-strict-cond-assign-warning
7638 (js2-assign-node-p pn))
7639 (js2-add-strict-warning "msg.equal.as.assign" nil
7640 (js2-node-pos pn)
7641 (+ (js2-node-pos pn)
7642 (js2-node-len pn))))
7643 (list pn lp rp)))
7644
7645 (defun js2-parse-if ()
7646 "Parser for if-statement. Last matched token must be js2-IF."
7647 (let ((pos (js2-current-token-beg))
7648 cond if-true if-false else-pos end pn)
7649 (setq cond (js2-parse-condition)
7650 if-true (js2-parse-statement)
7651 if-false (if (js2-match-token js2-ELSE)
7652 (progn
7653 (setq else-pos (- (js2-current-token-beg) pos))
7654 (js2-parse-statement)))
7655 end (js2-node-end (or if-false if-true))
7656 pn (make-js2-if-node :pos pos
7657 :len (- end pos)
7658 :condition (car cond)
7659 :then-part if-true
7660 :else-part if-false
7661 :else-pos else-pos
7662 :lp (js2-relpos (second cond) pos)
7663 :rp (js2-relpos (third cond) pos)))
7664 (js2-node-add-children pn (car cond) if-true if-false)
7665 pn))
7666
7667 (defun js2-parse-switch ()
7668 "Parser for switch-statement. Last matched token must be js2-SWITCH."
7669 (let ((pos (js2-current-token-beg))
7670 tt pn discriminant has-default case-expr case-node
7671 case-pos cases stmt lp)
7672 (if (js2-must-match js2-LP "msg.no.paren.switch")
7673 (setq lp (js2-current-token-beg)))
7674 (setq discriminant (js2-parse-expr)
7675 pn (make-js2-switch-node :discriminant discriminant
7676 :pos pos
7677 :lp (js2-relpos lp pos)))
7678 (js2-node-add-children pn discriminant)
7679 (js2-enter-switch pn)
7680 (unwind-protect
7681 (progn
7682 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7683 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
7684 (js2-must-match js2-LC "msg.no.brace.switch")
7685 (catch 'break
7686 (while t
7687 (setq tt (js2-next-token)
7688 case-pos (js2-current-token-beg))
7689 (cond
7690 ((= tt js2-RC)
7691 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
7692 (throw 'break nil)) ; done
7693 ((= tt js2-CASE)
7694 (setq case-expr (js2-parse-expr))
7695 (js2-must-match js2-COLON "msg.no.colon.case"))
7696 ((= tt js2-DEFAULT)
7697 (if has-default
7698 (js2-report-error "msg.double.switch.default"))
7699 (setq has-default t
7700 case-expr nil)
7701 (js2-must-match js2-COLON "msg.no.colon.case"))
7702 (t
7703 (js2-report-error "msg.bad.switch")
7704 (throw 'break nil)))
7705 (setq case-node (make-js2-case-node :pos case-pos
7706 :len (- (js2-current-token-end) case-pos)
7707 :expr case-expr))
7708 (js2-node-add-children case-node case-expr)
7709 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7710 (/= tt js2-CASE)
7711 (/= tt js2-DEFAULT)
7712 (/= tt js2-EOF))
7713 (setf stmt (js2-parse-statement)
7714 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7715 (js2-block-node-push case-node stmt))
7716 (push case-node cases)))
7717 ;; add cases last, as pushing reverses the order to be correct
7718 (dolist (kid cases)
7719 (js2-node-add-children pn kid)
7720 (push kid (js2-switch-node-cases pn)))
7721 pn) ; return value
7722 (js2-exit-switch))))
7723
7724 (defun js2-parse-while ()
7725 "Parser for while-statement. Last matched token must be js2-WHILE."
7726 (let ((pos (js2-current-token-beg))
7727 (pn (make-js2-while-node))
7728 cond body)
7729 (js2-enter-loop pn)
7730 (unwind-protect
7731 (progn
7732 (setf cond (js2-parse-condition)
7733 (js2-while-node-condition pn) (car cond)
7734 body (js2-parse-statement)
7735 (js2-while-node-body pn) body
7736 (js2-node-len pn) (- (js2-node-end body) pos)
7737 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7738 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7739 (js2-node-add-children pn body (car cond)))
7740 (js2-exit-loop))
7741 pn))
7742
7743 (defun js2-parse-do ()
7744 "Parser for do-statement. Last matched token must be js2-DO."
7745 (let ((pos (js2-current-token-beg))
7746 (pn (make-js2-do-node))
7747 cond body end)
7748 (js2-enter-loop pn)
7749 (unwind-protect
7750 (progn
7751 (setq body (js2-parse-statement))
7752 (js2-must-match js2-WHILE "msg.no.while.do")
7753 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
7754 cond (js2-parse-condition)
7755 (js2-do-node-condition pn) (car cond)
7756 (js2-do-node-body pn) body
7757 end js2-ts-cursor
7758 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7759 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7760 (js2-node-add-children pn (car cond) body))
7761 (js2-exit-loop))
7762 ;; Always auto-insert semicolon to follow SpiderMonkey:
7763 ;; It is required by ECMAScript but is ignored by the rest of
7764 ;; world; see bug 238945
7765 (if (js2-match-token js2-SEMI)
7766 (setq end js2-ts-cursor))
7767 (setf (js2-node-len pn) (- end pos))
7768 pn))
7769
7770 (defun js2-parse-for ()
7771 "Parser for for-statement. Last matched token must be js2-FOR.
7772 Parses for, for-in, and for each-in statements."
7773 (let ((for-pos (js2-current-token-beg))
7774 pn is-for-each is-for-in-or-of is-for-of
7775 in-pos each-pos tmp-pos
7776 init ; Node init is also foo in 'foo in object'
7777 cond ; Node cond is also object in 'foo in object'
7778 incr ; 3rd section of for-loop initializer
7779 body tt lp rp)
7780 ;; See if this is a for each () instead of just a for ()
7781 (when (js2-match-token js2-NAME)
7782 (if (string= "each" (js2-current-token-string))
7783 (progn
7784 (setq is-for-each t
7785 each-pos (- (js2-current-token-beg) for-pos)) ; relative
7786 (js2-record-face 'font-lock-keyword-face))
7787 (js2-report-error "msg.no.paren.for")))
7788 (if (js2-must-match js2-LP "msg.no.paren.for")
7789 (setq lp (- (js2-current-token-beg) for-pos)))
7790 (setq tt (js2-get-token))
7791 ;; 'for' makes local scope
7792 (js2-push-scope (make-js2-scope))
7793 (unwind-protect
7794 ;; parse init clause
7795 (let ((js2-in-for-init t)) ; set as dynamic variable
7796 (cond
7797 ((= tt js2-SEMI)
7798 (js2-unget-token)
7799 (setq init (make-js2-empty-expr-node)))
7800 ((or (= tt js2-VAR) (= tt js2-LET))
7801 (setq init (js2-parse-variables tt (js2-current-token-beg))))
7802 (t
7803 (js2-unget-token)
7804 (setq init (js2-parse-expr)))))
7805 (if (or (js2-match-token js2-IN)
7806 (and (>= js2-language-version 200)
7807 (js2-match-contextual-kwd "of")
7808 (setq is-for-of t)))
7809 (setq is-for-in-or-of t
7810 in-pos (- (js2-current-token-beg) for-pos)
7811 ;; scope of iteration target object is not the scope we've created above.
7812 ;; stash current scope temporary.
7813 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7814 (js2-parse-expr))) ; object over which we're iterating
7815 ;; else ordinary for loop - parse cond and incr
7816 (js2-must-match js2-SEMI "msg.no.semi.for")
7817 (setq cond (if (= (js2-peek-token) js2-SEMI)
7818 (make-js2-empty-expr-node) ; no loop condition
7819 (js2-parse-expr)))
7820 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7821 (setq tmp-pos (js2-current-token-end)
7822 incr (if (= (js2-peek-token) js2-RP)
7823 (make-js2-empty-expr-node :pos tmp-pos)
7824 (js2-parse-expr))))
7825 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7826 (setq rp (- (js2-current-token-beg) for-pos)))
7827 (if (not is-for-in-or-of)
7828 (setq pn (make-js2-for-node :init init
7829 :condition cond
7830 :update incr
7831 :lp lp
7832 :rp rp))
7833 ;; cond could be null if 'in obj' got eaten by the init node.
7834 (if (js2-infix-node-p init)
7835 ;; it was (foo in bar) instead of (var foo in bar)
7836 (setq cond (js2-infix-node-right init)
7837 init (js2-infix-node-left init))
7838 (if (and (js2-var-decl-node-p init)
7839 (> (length (js2-var-decl-node-kids init)) 1))
7840 (js2-report-error "msg.mult.index")))
7841 (setq pn (make-js2-for-in-node :iterator init
7842 :object cond
7843 :in-pos in-pos
7844 :foreach-p is-for-each
7845 :each-pos each-pos
7846 :forof-p is-for-of
7847 :lp lp
7848 :rp rp)))
7849 (unwind-protect
7850 (progn
7851 (js2-enter-loop pn)
7852 ;; We have to parse the body -after- creating the loop node,
7853 ;; so that the loop node appears in the js2-loop-set, allowing
7854 ;; break/continue statements to find the enclosing loop.
7855 (setf body (js2-parse-statement)
7856 (js2-loop-node-body pn) body
7857 (js2-node-pos pn) for-pos
7858 (js2-node-len pn) (- (js2-node-end body) for-pos))
7859 (js2-node-add-children pn init cond incr body))
7860 ;; finally
7861 (js2-exit-loop))
7862 (js2-pop-scope))
7863 pn))
7864
7865 (defun js2-parse-try ()
7866 "Parser for try-statement. Last matched token must be js2-TRY."
7867 (let ((try-pos (js2-current-token-beg))
7868 try-end
7869 try-block
7870 catch-blocks
7871 finally-block
7872 saw-default-catch
7873 peek
7874 param
7875 catch-cond
7876 catch-node
7877 guard-kwd
7878 catch-pos
7879 finally-pos
7880 pn
7881 block
7882 lp
7883 rp)
7884 (if (/= (js2-peek-token) js2-LC)
7885 (js2-report-error "msg.no.brace.try"))
7886 (setq try-block (js2-parse-statement)
7887 try-end (js2-node-end try-block)
7888 peek (js2-peek-token))
7889 (cond
7890 ((= peek js2-CATCH)
7891 (while (js2-match-token js2-CATCH)
7892 (setq catch-pos (js2-current-token-beg)
7893 guard-kwd nil
7894 catch-cond nil
7895 lp nil
7896 rp nil)
7897 (if saw-default-catch
7898 (js2-report-error "msg.catch.unreachable"))
7899 (if (js2-must-match js2-LP "msg.no.paren.catch")
7900 (setq lp (- (js2-current-token-beg) catch-pos)))
7901 (js2-push-scope (make-js2-scope))
7902 (let ((tt (js2-peek-token)))
7903 (cond
7904 ;; destructuring pattern
7905 ;; catch ({ message, file }) { ... }
7906 ((or (= tt js2-LB) (= tt js2-LC))
7907 (js2-get-token)
7908 (setq param (js2-parse-destruct-primary-expr))
7909 (js2-define-destruct-symbols param js2-LET nil))
7910 ;; simple name
7911 (t
7912 (js2-must-match js2-NAME "msg.bad.catchcond")
7913 (setq param (js2-create-name-node))
7914 (js2-define-symbol js2-LET (js2-current-token-string) param))))
7915 ;; pattern guard
7916 (if (js2-match-token js2-IF)
7917 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
7918 catch-cond (js2-parse-expr))
7919 (setq saw-default-catch t))
7920 (if (js2-must-match js2-RP "msg.bad.catchcond")
7921 (setq rp (- (js2-current-token-beg) catch-pos)))
7922 (js2-must-match js2-LC "msg.no.brace.catchblock")
7923 (setq block (js2-parse-statements)
7924 try-end (js2-node-end block)
7925 catch-node (make-js2-catch-node :pos catch-pos
7926 :param param
7927 :guard-expr catch-cond
7928 :guard-kwd guard-kwd
7929 :block block
7930 :lp lp
7931 :rp rp))
7932 (js2-pop-scope)
7933 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7934 (setq try-end (js2-current-token-beg)))
7935 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7936 (js2-node-len catch-node) (- try-end catch-pos))
7937 (js2-node-add-children catch-node param catch-cond block)
7938 (push catch-node catch-blocks)))
7939 ((/= peek js2-FINALLY)
7940 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7941 (js2-node-pos try-block)
7942 (- (setq try-end (js2-node-end try-block))
7943 (js2-node-pos try-block)))))
7944 (when (js2-match-token js2-FINALLY)
7945 (setq finally-pos (js2-current-token-beg)
7946 block (js2-parse-statement)
7947 try-end (js2-node-end block)
7948 finally-block (make-js2-finally-node :pos finally-pos
7949 :len (- try-end finally-pos)
7950 :body block))
7951 (js2-node-add-children finally-block block))
7952 (setq pn (make-js2-try-node :pos try-pos
7953 :len (- try-end try-pos)
7954 :try-block try-block
7955 :finally-block finally-block))
7956 (js2-node-add-children pn try-block finally-block)
7957 ;; push them onto the try-node, which reverses and corrects their order
7958 (dolist (cb catch-blocks)
7959 (js2-node-add-children pn cb)
7960 (push cb (js2-try-node-catch-clauses pn)))
7961 pn))
7962
7963 (defun js2-parse-throw ()
7964 "Parser for throw-statement. Last matched token must be js2-THROW."
7965 (let ((pos (js2-current-token-beg))
7966 expr pn)
7967 (if (= (js2-peek-token-or-eol) js2-EOL)
7968 ;; ECMAScript does not allow new lines before throw expression,
7969 ;; see bug 256617
7970 (js2-report-error "msg.bad.throw.eol"))
7971 (setq expr (js2-parse-expr)
7972 pn (make-js2-throw-node :pos pos
7973 :len (- (js2-node-end expr) pos)
7974 :expr expr))
7975 (js2-node-add-children pn expr)
7976 pn))
7977
7978 (defun js2-match-jump-label-name (label-name)
7979 "If break/continue specified a label, return that label's labeled stmt.
7980 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
7981 does not match an existing label, reports an error and returns nil."
7982 (let ((bundle (cdr (assoc label-name js2-label-set))))
7983 (if (null bundle)
7984 (js2-report-error "msg.undef.label"))
7985 bundle))
7986
7987 (defun js2-parse-break ()
7988 "Parser for break-statement. Last matched token must be js2-BREAK."
7989 (let ((pos (js2-current-token-beg))
7990 (end (js2-current-token-end))
7991 break-target ; statement to break from
7992 break-label ; in "break foo", name-node representing the foo
7993 labels ; matching labeled statement to break to
7994 pn)
7995 (when (eq (js2-peek-token-or-eol) js2-NAME)
7996 (js2-get-token)
7997 (setq break-label (js2-create-name-node)
7998 end (js2-node-end break-label)
7999 ;; matchJumpLabelName only matches if there is one
8000 labels (js2-match-jump-label-name (js2-current-token-string))
8001 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8002 (unless (or break-target break-label)
8003 ;; no break target specified - try for innermost enclosing loop/switch
8004 (if (null js2-loop-and-switch-set)
8005 (unless break-label
8006 (js2-report-error "msg.bad.break" nil pos (length "break")))
8007 (setq break-target (car js2-loop-and-switch-set))))
8008 (setq pn (make-js2-break-node :pos pos
8009 :len (- end pos)
8010 :label break-label
8011 :target break-target))
8012 (js2-node-add-children pn break-label) ; but not break-target
8013 pn))
8014
8015 (defun js2-parse-continue ()
8016 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8017 (let ((pos (js2-current-token-beg))
8018 (end (js2-current-token-end))
8019 label ; optional user-specified label, a `js2-name-node'
8020 labels ; current matching labeled stmt, if any
8021 target ; the `js2-loop-node' target of this continue stmt
8022 pn)
8023 (when (= (js2-peek-token-or-eol) js2-NAME)
8024 (js2-get-token)
8025 (setq label (js2-create-name-node)
8026 end (js2-node-end label)
8027 ;; matchJumpLabelName only matches if there is one
8028 labels (js2-match-jump-label-name (js2-current-token-string))))
8029 (cond
8030 ((null labels) ; no current label to go to
8031 (if (null js2-loop-set) ; no loop to continue to
8032 (js2-report-error "msg.continue.outside" nil pos
8033 (length "continue"))
8034 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8035 (t
8036 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8037 (setq target (js2-labeled-stmt-node-stmt labels))
8038 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8039 (setq pn (make-js2-continue-node :pos pos
8040 :len (- end pos)
8041 :label label
8042 :target target))
8043 (js2-node-add-children pn label) ; but not target - it's not our child
8044 pn))
8045
8046 (defun js2-parse-with ()
8047 "Parser for with-statement. Last matched token must be js2-WITH."
8048 (let ((pos (js2-current-token-beg))
8049 obj body pn lp rp)
8050 (if (js2-must-match js2-LP "msg.no.paren.with")
8051 (setq lp (js2-current-token-beg)))
8052 (setq obj (js2-parse-expr))
8053 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8054 (setq rp (js2-current-token-beg)))
8055 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8056 (setq body (js2-parse-statement)))
8057 (setq pn (make-js2-with-node :pos pos
8058 :len (- (js2-node-end body) pos)
8059 :object obj
8060 :body body
8061 :lp (js2-relpos lp pos)
8062 :rp (js2-relpos rp pos)))
8063 (js2-node-add-children pn obj body)
8064 pn))
8065
8066 (defun js2-parse-const-var ()
8067 "Parser for var- or const-statement.
8068 Last matched token must be js2-CONST or js2-VAR."
8069 (let ((tt (js2-current-token-type))
8070 (pos (js2-current-token-beg))
8071 expr pn)
8072 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8073 pn (make-js2-expr-stmt-node :pos pos
8074 :len (- (js2-node-end expr) pos)
8075 :expr expr))
8076 (js2-node-add-children pn expr)
8077 pn))
8078
8079 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8080 (let ((pn (make-js2-expr-stmt-node :pos pos
8081 :len (js2-node-len expr)
8082 :type (if (js2-inside-function)
8083 js2-EXPR_VOID
8084 js2-EXPR_RESULT)
8085 :expr expr)))
8086 (if add-child
8087 (js2-node-add-children pn expr))
8088 pn))
8089
8090 (defun js2-parse-let-stmt ()
8091 "Parser for let-statement. Last matched token must be js2-LET."
8092 (let ((pos (js2-current-token-beg))
8093 expr pn)
8094 (if (= (js2-peek-token) js2-LP)
8095 ;; let expression in statement context
8096 (setq expr (js2-parse-let pos 'statement)
8097 pn (js2-wrap-with-expr-stmt pos expr t))
8098 ;; else we're looking at a statement like let x=6, y=7;
8099 (setf expr (js2-parse-variables js2-LET pos)
8100 pn (js2-wrap-with-expr-stmt pos expr t)
8101 (js2-node-type pn) js2-EXPR_RESULT))
8102 pn))
8103
8104 (defun js2-parse-ret-yield ()
8105 (js2-parse-return-or-yield (js2-current-token-type) nil))
8106
8107 (defconst js2-parse-return-stmt-enders
8108 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8109
8110 (defsubst js2-now-all-set (before after mask)
8111 "Return whether or not the bits in the mask have changed to all set.
8112 BEFORE is bits before change, AFTER is bits after change, and MASK is
8113 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8114 but not BEFORE."
8115 (and (/= (logand before mask) mask)
8116 (= (logand after mask) mask)))
8117
8118 (defun js2-parse-return-or-yield (tt expr-context)
8119 (let ((pos (js2-current-token-beg))
8120 (end (js2-current-token-end))
8121 (before js2-end-flags)
8122 (inside-function (js2-inside-function))
8123 e ret name)
8124 (unless inside-function
8125 (js2-report-error (if (eq tt js2-RETURN)
8126 "msg.bad.return"
8127 "msg.bad.yield")))
8128 ;; This is ugly, but we don't want to require a semicolon.
8129 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8130 (setq e (js2-parse-expr)
8131 end (js2-node-end e)))
8132 (cond
8133 ((eq tt js2-RETURN)
8134 (js2-set-flag js2-end-flags (if (null e)
8135 js2-end-returns
8136 js2-end-returns-value))
8137 (setq ret (make-js2-return-node :pos pos
8138 :len (- end pos)
8139 :retval e))
8140 (js2-node-add-children ret e)
8141 ;; See if we need a strict mode warning.
8142 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8143 ;; more thorough and accurate than this before/after flag check.
8144 ;; E.g. if there's a finally-block that always returns, we shouldn't
8145 ;; show a warning generated by inconsistent returns in the catch blocks.
8146 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8147 ;; so we know which returns/yields to highlight, and we should get rid of
8148 ;; all the checking in `js2-parse-return-or-yield'.
8149 (if (and js2-strict-inconsistent-return-warning
8150 (js2-now-all-set before js2-end-flags
8151 (logior js2-end-returns js2-end-returns-value)))
8152 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8153 (t
8154 (unless (js2-inside-function)
8155 (js2-report-error "msg.bad.yield"))
8156 (setq ret (make-js2-yield-node :pos pos
8157 :len (- end pos)
8158 :value e))
8159 (js2-node-add-children ret e)
8160 (unless expr-context
8161 (setq e ret
8162 ret (js2-wrap-with-expr-stmt pos e t))
8163 (js2-set-requires-activation)
8164 (js2-set-is-generator))))
8165 ;; see if we are mixing yields and value returns.
8166 (when (and inside-function
8167 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8168 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8169 'LEGACY))
8170 (setq name (js2-function-name js2-current-script-or-fn))
8171 (if (zerop (length name))
8172 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8173 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8174 ret))
8175
8176 (defun js2-parse-debugger ()
8177 (make-js2-keyword-node :type js2-DEBUGGER))
8178
8179 (defun js2-parse-block ()
8180 "Parser for a curly-delimited statement block.
8181 Last token matched must be `js2-LC'."
8182 (let ((pos (js2-current-token-beg))
8183 (pn (make-js2-scope)))
8184 (js2-push-scope pn)
8185 (unwind-protect
8186 (progn
8187 (js2-parse-statements pn)
8188 (js2-must-match js2-RC "msg.no.brace.block")
8189 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8190 (js2-pop-scope))
8191 pn))
8192
8193 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8194 (defun js2-parse-semi ()
8195 "Parse a statement or handle an error.
8196 Current token type is `js2-SEMI' or `js2-ERROR'."
8197 (let ((tt (js2-current-token-type)) pos len)
8198 (if (eq tt js2-SEMI)
8199 (make-js2-empty-expr-node :len 1)
8200 (setq pos (js2-current-token-beg)
8201 len (- (js2-current-token-end) pos))
8202 (js2-report-error "msg.syntax" nil pos len)
8203 (make-js2-error-node :pos pos :len len))))
8204
8205 (defun js2-parse-default-xml-namespace ()
8206 "Parse a `default xml namespace = <expr>' e4x statement."
8207 (let ((pos (js2-current-token-beg))
8208 end len expr unary)
8209 (js2-must-have-xml)
8210 (js2-set-requires-activation)
8211 (setq len (- js2-ts-cursor pos))
8212 (unless (and (js2-match-token js2-NAME)
8213 (string= (js2-current-token-string) "xml"))
8214 (js2-report-error "msg.bad.namespace" nil pos len))
8215 (unless (and (js2-match-token js2-NAME)
8216 (string= (js2-current-token-string) "namespace"))
8217 (js2-report-error "msg.bad.namespace" nil pos len))
8218 (unless (js2-match-token js2-ASSIGN)
8219 (js2-report-error "msg.bad.namespace" nil pos len))
8220 (setq expr (js2-parse-expr)
8221 end (js2-node-end expr)
8222 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8223 :pos pos
8224 :len (- end pos)
8225 :operand expr))
8226 (js2-node-add-children unary expr)
8227 (make-js2-expr-stmt-node :pos pos
8228 :len (- end pos)
8229 :expr unary)))
8230
8231 (defun js2-record-label (label bundle)
8232 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8233 (js2-get-token)
8234 (let ((name (js2-label-node-name label))
8235 labeled-stmt
8236 dup)
8237 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8238 ;; flag both labels if possible when used in editing mode
8239 (if (and js2-parse-ide-mode
8240 (setq dup (js2-get-label-by-name labeled-stmt name)))
8241 (js2-report-error "msg.dup.label" nil
8242 (js2-node-abs-pos dup) (js2-node-len dup)))
8243 (js2-report-error "msg.dup.label" nil
8244 (js2-node-pos label) (js2-node-len label)))
8245 (js2-labeled-stmt-node-add-label bundle label)
8246 (js2-node-add-children bundle label)
8247 ;; Add one reference to the bundle per label in `js2-label-set'
8248 (push (cons name bundle) js2-label-set)))
8249
8250 (defun js2-parse-name-or-label ()
8251 "Parser for identifier or label. Last token matched must be js2-NAME.
8252 Called when we found a name in a statement context. If it's a label, we gather
8253 up any following labels and the next non-label statement into a
8254 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8255 expression and return it wrapped in a `js2-expr-stmt-node'."
8256 (let ((pos (js2-current-token-beg))
8257 expr stmt bundle
8258 (continue t))
8259 ;; set check for label and call down to `js2-parse-primary-expr'
8260 (setq expr (js2-maybe-parse-label))
8261 (if (null expr)
8262 ;; Parse the non-label expression and wrap with expression stmt.
8263 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
8264 ;; else parsed a label
8265 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8266 (js2-record-label expr bundle)
8267 ;; look for more labels
8268 (while (and continue (= (js2-get-token) js2-NAME))
8269 (if (setq expr (js2-maybe-parse-label))
8270 (js2-record-label expr bundle)
8271 (setq expr (js2-parse-expr)
8272 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8273 continue nil)
8274 (js2-auto-insert-semicolon stmt)))
8275 ;; no more labels; now parse the labeled statement
8276 (unwind-protect
8277 (unless stmt
8278 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8279 (js2-unget-token)
8280 (setq stmt (js2-statement-helper))))
8281 ;; remove the labels for this statement from the global set
8282 (dolist (label (js2-labeled-stmt-node-labels bundle))
8283 (setq js2-label-set (remove label js2-label-set))))
8284 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8285 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8286 (js2-node-add-children bundle stmt)
8287 bundle)))
8288
8289 (defun js2-maybe-parse-label ()
8290 (assert (= (js2-current-token-type) js2-NAME))
8291 (let (label-pos
8292 (next-tt (js2-get-token))
8293 (label-end (js2-current-token-end)))
8294 ;; Do not consume colon, it is used as unwind indicator
8295 ;; to return to statementHelper.
8296 (js2-unget-token)
8297 (if (= next-tt js2-COLON)
8298 (prog2
8299 (setq label-pos (js2-current-token-beg))
8300 (make-js2-label-node :pos label-pos
8301 :len (- label-end label-pos)
8302 :name (js2-current-token-string))
8303 (js2-set-face label-pos
8304 label-end
8305 'font-lock-variable-name-face 'record))
8306 ;; Backtrack from the name token, too.
8307 (js2-unget-token)
8308 nil)))
8309
8310 (defun js2-parse-expr-stmt ()
8311 "Default parser in statement context, if no recognized statement found."
8312 (js2-wrap-with-expr-stmt (js2-current-token-beg)
8313 (progn
8314 (js2-unget-token)
8315 (js2-parse-expr)) t))
8316
8317 (defun js2-parse-variables (decl-type pos)
8318 "Parse a comma-separated list of variable declarations.
8319 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8320
8321 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8322 For 'var' or 'const', the keyword should be the token last scanned.
8323
8324 POS is the position where the node should start. It's sometimes the
8325 var/const/let keyword, and other times the beginning of the first token
8326 in the first variable declaration.
8327
8328 Returns the parsed `js2-var-decl-node' expression node."
8329 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8330 :pos pos))
8331 destructuring kid-pos tt init name end nbeg nend vi
8332 (continue t))
8333 ;; Example:
8334 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8335 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8336 ;; var {a, b} = baz;
8337 (while continue
8338 (setq destructuring nil
8339 name nil
8340 tt (js2-get-token)
8341 kid-pos (js2-current-token-beg)
8342 end (js2-current-token-end)
8343 init nil)
8344 (if (or (= tt js2-LB) (= tt js2-LC))
8345 ;; Destructuring assignment, e.g., var [a, b] = ...
8346 (setq destructuring (js2-parse-destruct-primary-expr)
8347 end (js2-node-end destructuring))
8348 ;; Simple variable name
8349 (js2-unget-token)
8350 (when (js2-must-match js2-NAME "msg.bad.var")
8351 (setq name (js2-create-name-node)
8352 nbeg (js2-current-token-beg)
8353 nend (js2-current-token-end)
8354 end nend)
8355 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
8356 (when (js2-match-token js2-ASSIGN)
8357 (setq init (js2-parse-assign-expr)
8358 end (js2-node-end init))
8359 (js2-record-imenu-functions init name))
8360 (when name
8361 (js2-set-face nbeg nend (if (js2-function-node-p init)
8362 'font-lock-function-name-face
8363 'font-lock-variable-name-face)
8364 'record))
8365 (setq vi (make-js2-var-init-node :pos kid-pos
8366 :len (- end kid-pos)
8367 :type decl-type))
8368 (if destructuring
8369 (progn
8370 (if (and (null init) (not js2-in-for-init))
8371 (js2-report-error "msg.destruct.assign.no.init"))
8372 (js2-define-destruct-symbols destructuring
8373 decl-type
8374 'font-lock-variable-name-face)
8375 (setf (js2-var-init-node-target vi) destructuring))
8376 (setf (js2-var-init-node-target vi) name))
8377 (setf (js2-var-init-node-initializer vi) init)
8378 (js2-node-add-children vi name destructuring init)
8379 (js2-block-node-push result vi)
8380 (unless (js2-match-token js2-COMMA)
8381 (setq continue nil)))
8382 (setf (js2-node-len result) (- end pos))
8383 result))
8384
8385 (defun js2-parse-let (pos &optional stmt-p)
8386 "Parse a let expression or statement.
8387 A let-expression is of the form `let (vars) expr'.
8388 A let-statment is of the form `let (vars) {statements}'.
8389 The third form of let is a variable declaration list, handled
8390 by `js2-parse-variables'."
8391 (let ((pn (make-js2-let-node :pos pos))
8392 beg vars body)
8393 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8394 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
8395 (js2-push-scope pn)
8396 (unwind-protect
8397 (progn
8398 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
8399 (if (js2-must-match js2-RP "msg.no.paren.let")
8400 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
8401 (if (and stmt-p (eq (js2-get-token) js2-LC))
8402 ;; let statement
8403 (progn
8404 (setf beg (js2-current-token-beg) ; position stmt at LC
8405 body (js2-parse-statements))
8406 (js2-must-match js2-RC "msg.no.curly.let")
8407 (setf (js2-node-len body) (- (js2-current-token-end) beg)
8408 (js2-node-len pn) (- (js2-current-token-end) pos)
8409 (js2-let-node-body pn) body
8410 (js2-node-type pn) js2-LET))
8411 ;; let expression
8412 (js2-unget-token)
8413 (setf body (js2-parse-expr)
8414 (js2-node-len pn) (- (js2-node-end body) pos)
8415 (js2-let-node-body pn) body))
8416 (js2-node-add-children pn vars body))
8417 (js2-pop-scope))
8418 pn))
8419
8420 (defun js2-define-new-symbol (decl-type name node &optional scope)
8421 (js2-scope-put-symbol (or scope js2-current-scope)
8422 name
8423 (make-js2-symbol decl-type name node)))
8424
8425 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8426 "Define a symbol in the current scope.
8427 If NODE is non-nil, it is the AST node associated with the symbol."
8428 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8429 (symbol (if defining-scope
8430 (js2-scope-get-symbol defining-scope name)))
8431 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8432 (cond
8433 ((and symbol ; already defined
8434 (or (= sdt js2-CONST) ; old version is const
8435 (= decl-type js2-CONST) ; new version is const
8436 ;; two let-bound vars in this block have same name
8437 (and (= sdt js2-LET)
8438 (eq defining-scope js2-current-scope))))
8439 (js2-report-error
8440 (cond
8441 ((= sdt js2-CONST) "msg.const.redecl")
8442 ((= sdt js2-LET) "msg.let.redecl")
8443 ((= sdt js2-VAR) "msg.var.redecl")
8444 ((= sdt js2-FUNCTION) "msg.function.redecl")
8445 (t "msg.parm.redecl"))
8446 name))
8447 ((= decl-type js2-LET)
8448 (if (and (not ignore-not-in-block)
8449 (or (= (js2-node-type js2-current-scope) js2-IF)
8450 (js2-loop-node-p js2-current-scope)))
8451 (js2-report-error "msg.let.decl.not.in.block")
8452 (js2-define-new-symbol decl-type name node)))
8453 ((or (= decl-type js2-VAR)
8454 (= decl-type js2-CONST)
8455 (= decl-type js2-FUNCTION))
8456 (if symbol
8457 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8458 (js2-add-strict-warning "msg.var.redecl" name)
8459 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8460 (js2-add-strict-warning "msg.var.hides.arg" name)))
8461 (js2-define-new-symbol decl-type name node
8462 js2-current-script-or-fn)))
8463 ((= decl-type js2-LP)
8464 (if symbol
8465 ;; must be duplicate parameter. Second parameter hides the
8466 ;; first, so go ahead and add the second pararameter
8467 (js2-report-warning "msg.dup.parms" name))
8468 (js2-define-new-symbol decl-type name node))
8469 (t (js2-code-bug)))))
8470
8471 (defun js2-parse-expr (&optional oneshot)
8472 (let* ((pn (js2-parse-assign-expr))
8473 (pos (js2-node-pos pn))
8474 left
8475 right
8476 op-pos)
8477 (while (and (not oneshot)
8478 (js2-match-token js2-COMMA))
8479 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
8480 (if (= (js2-peek-token) js2-YIELD)
8481 (js2-report-error "msg.yield.parenthesized"))
8482 (setq right (js2-parse-assign-expr)
8483 left pn
8484 pn (make-js2-infix-node :type js2-COMMA
8485 :pos pos
8486 :len (- js2-ts-cursor pos)
8487 :op-pos op-pos
8488 :left left
8489 :right right))
8490 (js2-node-add-children pn left right))
8491 pn))
8492
8493 (defun js2-parse-assign-expr ()
8494 (let ((tt (js2-get-token))
8495 (pos (js2-current-token-beg))
8496 pn left right op-pos
8497 ts-state recorded-identifiers)
8498 (if (= tt js2-YIELD)
8499 (js2-parse-return-or-yield tt t)
8500 ;; Save the tokenizer state in case we find an arrow function
8501 ;; and have to rewind.
8502 (setq ts-state (make-js2-ts-state)
8503 recorded-identifiers js2-recorded-identifiers)
8504 ;; not yield - parse assignment expression
8505 (setq pn (js2-parse-cond-expr)
8506 tt (js2-get-token))
8507 (cond
8508 ((and (<= js2-first-assign tt)
8509 (<= tt js2-last-assign))
8510 ;; tt express assignment (=, |=, ^=, ..., %=)
8511 (setq op-pos (- (js2-current-token-beg) pos) ; relative
8512 left pn)
8513 (setq right (js2-parse-assign-expr)
8514 pn (make-js2-assign-node :type tt
8515 :pos pos
8516 :len (- (js2-node-end right) pos)
8517 :op-pos op-pos
8518 :left left
8519 :right right))
8520 (when js2-parse-ide-mode
8521 (js2-highlight-assign-targets pn left right)
8522 (js2-record-imenu-functions right left))
8523 ;; do this last so ide checks above can use absolute positions
8524 (js2-node-add-children pn left right))
8525 ((and (= tt js2-ARROW)
8526 (>= js2-language-version 200))
8527 (js2-ts-seek ts-state)
8528 (setq js2-recorded-identifiers recorded-identifiers)
8529 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
8530 (t
8531 (js2-unget-token)))
8532 pn)))
8533
8534 (defun js2-parse-cond-expr ()
8535 (let ((pos (js2-current-token-beg))
8536 (pn (js2-parse-or-expr))
8537 test-expr
8538 if-true
8539 if-false
8540 q-pos
8541 c-pos)
8542 (when (js2-match-token js2-HOOK)
8543 (setq q-pos (- (js2-current-token-beg) pos)
8544 if-true (js2-parse-assign-expr))
8545 (js2-must-match js2-COLON "msg.no.colon.cond")
8546 (setq c-pos (- (js2-current-token-beg) pos)
8547 if-false (js2-parse-assign-expr)
8548 test-expr pn
8549 pn (make-js2-cond-node :pos pos
8550 :len (- (js2-node-end if-false) pos)
8551 :test-expr test-expr
8552 :true-expr if-true
8553 :false-expr if-false
8554 :q-pos q-pos
8555 :c-pos c-pos))
8556 (js2-node-add-children pn test-expr if-true if-false))
8557 pn))
8558
8559 (defun js2-make-binary (type left parser)
8560 "Helper for constructing a binary-operator AST node.
8561 LEFT is the left-side-expression, already parsed, and the
8562 binary operator should have just been matched.
8563 PARSER is a function to call to parse the right operand,
8564 or a `js2-node' struct if it has already been parsed.
8565 FIXME: The latter option is unused?"
8566 (let* ((pos (js2-node-pos left))
8567 (op-pos (- (js2-current-token-beg) pos))
8568 (right (if (js2-node-p parser)
8569 parser
8570 (js2-get-token)
8571 (funcall parser)))
8572 (pn (make-js2-infix-node :type type
8573 :pos pos
8574 :len (- (js2-node-end right) pos)
8575 :op-pos op-pos
8576 :left left
8577 :right right)))
8578 (js2-node-add-children pn left right)
8579 pn))
8580
8581 (defun js2-parse-or-expr ()
8582 (let ((pn (js2-parse-and-expr)))
8583 (when (js2-match-token js2-OR)
8584 (setq pn (js2-make-binary js2-OR
8585 pn
8586 'js2-parse-or-expr)))
8587 pn))
8588
8589 (defun js2-parse-and-expr ()
8590 (let ((pn (js2-parse-bit-or-expr)))
8591 (when (js2-match-token js2-AND)
8592 (setq pn (js2-make-binary js2-AND
8593 pn
8594 'js2-parse-and-expr)))
8595 pn))
8596
8597 (defun js2-parse-bit-or-expr ()
8598 (let ((pn (js2-parse-bit-xor-expr)))
8599 (while (js2-match-token js2-BITOR)
8600 (setq pn (js2-make-binary js2-BITOR
8601 pn
8602 'js2-parse-bit-xor-expr)))
8603 pn))
8604
8605 (defun js2-parse-bit-xor-expr ()
8606 (let ((pn (js2-parse-bit-and-expr)))
8607 (while (js2-match-token js2-BITXOR)
8608 (setq pn (js2-make-binary js2-BITXOR
8609 pn
8610 'js2-parse-bit-and-expr)))
8611 pn))
8612
8613 (defun js2-parse-bit-and-expr ()
8614 (let ((pn (js2-parse-eq-expr)))
8615 (while (js2-match-token js2-BITAND)
8616 (setq pn (js2-make-binary js2-BITAND
8617 pn
8618 'js2-parse-eq-expr)))
8619 pn))
8620
8621 (defconst js2-parse-eq-ops
8622 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8623
8624 (defun js2-parse-eq-expr ()
8625 (let ((pn (js2-parse-rel-expr))
8626 tt)
8627 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
8628 (setq pn (js2-make-binary tt
8629 pn
8630 'js2-parse-rel-expr)))
8631 (js2-unget-token)
8632 pn))
8633
8634 (defconst js2-parse-rel-ops
8635 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8636
8637 (defun js2-parse-rel-expr ()
8638 (let ((pn (js2-parse-shift-expr))
8639 (continue t)
8640 tt)
8641 (while continue
8642 (setq tt (js2-get-token))
8643 (cond
8644 ((and js2-in-for-init (= tt js2-IN))
8645 (js2-unget-token)
8646 (setq continue nil))
8647 ((memq tt js2-parse-rel-ops)
8648 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8649 (t
8650 (js2-unget-token)
8651 (setq continue nil))))
8652 pn))
8653
8654 (defconst js2-parse-shift-ops
8655 (list js2-LSH js2-URSH js2-RSH))
8656
8657 (defun js2-parse-shift-expr ()
8658 (let ((pn (js2-parse-add-expr))
8659 tt
8660 (continue t))
8661 (while continue
8662 (setq tt (js2-get-token))
8663 (if (memq tt js2-parse-shift-ops)
8664 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
8665 (js2-unget-token)
8666 (setq continue nil)))
8667 pn))
8668
8669 (defun js2-parse-add-expr ()
8670 (let ((pn (js2-parse-mul-expr))
8671 tt
8672 (continue t))
8673 (while continue
8674 (setq tt (js2-get-token))
8675 (if (or (= tt js2-ADD) (= tt js2-SUB))
8676 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
8677 (js2-unget-token)
8678 (setq continue nil)))
8679 pn))
8680
8681 (defconst js2-parse-mul-ops
8682 (list js2-MUL js2-DIV js2-MOD))
8683
8684 (defun js2-parse-mul-expr ()
8685 (let ((pn (js2-parse-unary-expr))
8686 tt
8687 (continue t))
8688 (while continue
8689 (setq tt (js2-get-token))
8690 (if (memq tt js2-parse-mul-ops)
8691 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
8692 (js2-unget-token)
8693 (setq continue nil)))
8694 pn))
8695
8696 (defun js2-make-unary (type parser &rest args)
8697 "Make a unary node of type TYPE.
8698 PARSER is either a node (for postfix operators) or a function to call
8699 to parse the operand (for prefix operators)."
8700 (let* ((pos (js2-current-token-beg))
8701 (postfix (js2-node-p parser))
8702 (expr (if postfix
8703 parser
8704 (apply parser args)))
8705 end
8706 pn)
8707 (if postfix ; e.g. i++
8708 (setq pos (js2-node-pos expr)
8709 end (js2-current-token-end))
8710 (setq end (js2-node-end expr)))
8711 (setq pn (make-js2-unary-node :type type
8712 :pos pos
8713 :len (- end pos)
8714 :operand expr))
8715 (js2-node-add-children pn expr)
8716 pn))
8717
8718 (defconst js2-incrementable-node-types
8719 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8720 "Node types that can be the operand of a ++ or -- operator.")
8721
8722 (defun js2-check-bad-inc-dec (tt beg end unary)
8723 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8724 js2-incrementable-node-types)
8725 (js2-report-error (if (= tt js2-INC)
8726 "msg.bad.incr"
8727 "msg.bad.decr")
8728 nil beg (- end beg))))
8729
8730 (defun js2-parse-unary-expr ()
8731 (let ((tt (js2-current-token-type))
8732 pn expr beg end)
8733 (cond
8734 ((or (= tt js2-VOID)
8735 (= tt js2-NOT)
8736 (= tt js2-BITNOT)
8737 (= tt js2-TYPEOF))
8738 (js2-get-token)
8739 (js2-make-unary tt 'js2-parse-unary-expr))
8740 ((= tt js2-ADD)
8741 (js2-get-token)
8742 ;; Convert to special POS token in decompiler and parse tree
8743 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8744 ((= tt js2-SUB)
8745 (js2-get-token)
8746 ;; Convert to special NEG token in decompiler and parse tree
8747 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8748 ((or (= tt js2-INC)
8749 (= tt js2-DEC))
8750 (js2-get-token)
8751 (prog1
8752 (setq beg (js2-current-token-beg)
8753 end (js2-current-token-end)
8754 expr (js2-make-unary tt 'js2-parse-member-expr t))
8755 (js2-check-bad-inc-dec tt beg end expr)))
8756 ((= tt js2-DELPROP)
8757 (js2-get-token)
8758 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8759 ((= tt js2-ERROR)
8760 (js2-get-token)
8761 (make-js2-error-node)) ; try to continue
8762 ((and (= tt js2-LT)
8763 js2-compiler-xml-available)
8764 ;; XML stream encountered in expression.
8765 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8766 (t
8767 (setq pn (js2-parse-member-expr t)
8768 ;; Don't look across a newline boundary for a postfix incop.
8769 tt (js2-peek-token-or-eol))
8770 (when (or (= tt js2-INC) (= tt js2-DEC))
8771 (js2-get-token)
8772 (setf expr pn
8773 pn (js2-make-unary tt expr))
8774 (js2-node-set-prop pn 'postfix t)
8775 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
8776 pn))))
8777
8778 (defun js2-parse-xml-initializer ()
8779 "Parse an E4X XML initializer.
8780 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8781 Then I'll postprocess the result, depending on whether we're in IDE
8782 mode or codegen mode, and generate the appropriate rewritten AST.
8783 IDE mode uses a rich AST that models the XML structure. Codegen mode
8784 just concatenates everything and makes a new XML or XMLList out of it."
8785 (let ((tt (js2-get-first-xml-token))
8786 pn-xml pn expr kids expr-pos
8787 (continue t)
8788 (first-token t))
8789 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8790 (js2-report-error "msg.syntax"))
8791 (setq pn-xml (make-js2-xml-node))
8792 (while continue
8793 (if first-token
8794 (setq first-token nil)
8795 (setq tt (js2-get-next-xml-token)))
8796 (cond
8797 ;; js2-XML means we found a {expr} in the XML stream.
8798 ;; The token string is the XML up to the left-curly.
8799 ((= tt js2-XML)
8800 (push (make-js2-string-node :pos (js2-current-token-beg)
8801 :len (- js2-ts-cursor (js2-current-token-beg)))
8802 kids)
8803 (js2-must-match js2-LC "msg.syntax")
8804 (setq expr-pos js2-ts-cursor
8805 expr (if (eq (js2-peek-token) js2-RC)
8806 (make-js2-empty-expr-node :pos expr-pos)
8807 (js2-parse-expr)))
8808 (js2-must-match js2-RC "msg.syntax")
8809 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8810 :len (js2-node-len expr)
8811 :expr expr))
8812 (js2-node-add-children pn expr)
8813 (push pn kids))
8814 ;; a js2-XMLEND token means we hit the final close-tag.
8815 ((= tt js2-XMLEND)
8816 (push (make-js2-string-node :pos (js2-current-token-beg)
8817 :len (- js2-ts-cursor (js2-current-token-beg)))
8818 kids)
8819 (dolist (kid (nreverse kids))
8820 (js2-block-node-push pn-xml kid))
8821 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8822 (js2-node-pos pn-xml))
8823 continue nil))
8824 (t
8825 (js2-report-error "msg.syntax")
8826 (setq continue nil))))
8827 pn-xml))
8828
8829
8830 (defun js2-parse-argument-list ()
8831 "Parse an argument list and return it as a Lisp list of nodes.
8832 Returns the list in reverse order. Consumes the right-paren token."
8833 (let (result)
8834 (unless (js2-match-token js2-RP)
8835 (loop do
8836 (if (= (js2-peek-token) js2-YIELD)
8837 (js2-report-error "msg.yield.parenthesized"))
8838 (push (js2-parse-assign-expr) result)
8839 while
8840 (js2-match-token js2-COMMA))
8841 (js2-must-match js2-RP "msg.no.paren.arg")
8842 result)))
8843
8844 (defun js2-parse-member-expr (&optional allow-call-syntax)
8845 (let ((tt (js2-current-token-type))
8846 pn pos target args beg end init)
8847 (if (/= tt js2-NEW)
8848 (setq pn (js2-parse-primary-expr))
8849 ;; parse a 'new' expression
8850 (js2-get-token)
8851 (setq pos (js2-current-token-beg)
8852 beg pos
8853 target (js2-parse-member-expr)
8854 end (js2-node-end target)
8855 pn (make-js2-new-node :pos pos
8856 :target target
8857 :len (- end pos)))
8858 (js2-node-add-children pn target)
8859 (when (js2-match-token js2-LP)
8860 ;; Add the arguments to pn, if any are supplied.
8861 (setf beg pos ; start of "new" keyword
8862 pos (js2-current-token-beg)
8863 args (nreverse (js2-parse-argument-list))
8864 (js2-new-node-args pn) args
8865 end (js2-current-token-end)
8866 (js2-new-node-lp pn) (- pos beg)
8867 (js2-new-node-rp pn) (- end 1 beg))
8868 (apply #'js2-node-add-children pn args))
8869 (when (and js2-allow-rhino-new-expr-initializer
8870 (js2-match-token js2-LC))
8871 (setf init (js2-parse-object-literal)
8872 end (js2-node-end init)
8873 (js2-new-node-initializer pn) init)
8874 (js2-node-add-children pn init))
8875 (setf (js2-node-len pn) (- end beg))) ; end outer if
8876 (js2-parse-member-expr-tail allow-call-syntax pn)))
8877
8878 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8879 "Parse a chain of property/array accesses or function calls.
8880 Includes parsing for E4X operators like `..' and `.@'.
8881 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8882 Returns an expression tree that includes PN, the parent node."
8883 (let (tt
8884 (continue t))
8885 (while continue
8886 (setq tt (js2-get-token))
8887 (cond
8888 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8889 (setq pn (js2-parse-property-access tt pn)))
8890 ((= tt js2-DOTQUERY)
8891 (setq pn (js2-parse-dot-query pn)))
8892 ((= tt js2-LB)
8893 (setq pn (js2-parse-element-get pn)))
8894 ((= tt js2-LP)
8895 (if allow-call-syntax
8896 (setq pn (js2-parse-function-call pn))
8897 (js2-unget-token)
8898 (setq continue nil)))
8899 (t
8900 (js2-unget-token)
8901 (setq continue nil))))
8902 (if (>= js2-highlight-level 2)
8903 (js2-parse-highlight-member-expr-node pn))
8904 pn))
8905
8906 (defun js2-parse-dot-query (pn)
8907 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8908 Last token parsed must be `js2-DOTQUERY'."
8909 (let ((pos (js2-node-pos pn))
8910 op-pos expr end)
8911 (js2-must-have-xml)
8912 (js2-set-requires-activation)
8913 (setq op-pos (js2-current-token-beg)
8914 expr (js2-parse-expr)
8915 end (js2-node-end expr)
8916 pn (make-js2-xml-dot-query-node :left pn
8917 :pos pos
8918 :op-pos op-pos
8919 :right expr))
8920 (js2-node-add-children pn
8921 (js2-xml-dot-query-node-left pn)
8922 (js2-xml-dot-query-node-right pn))
8923 (if (js2-must-match js2-RP "msg.no.paren")
8924 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
8925 end (js2-current-token-end)))
8926 (setf (js2-node-len pn) (- end pos))
8927 pn))
8928
8929 (defun js2-parse-element-get (pn)
8930 "Parse an element-get expression, e.g. foo[bar].
8931 Last token parsed must be `js2-RB'."
8932 (let ((lb (js2-current-token-beg))
8933 (pos (js2-node-pos pn))
8934 rb expr)
8935 (setq expr (js2-parse-expr))
8936 (if (js2-must-match js2-RB "msg.no.bracket.index")
8937 (setq rb (js2-current-token-beg)))
8938 (setq pn (make-js2-elem-get-node :target pn
8939 :pos pos
8940 :element expr
8941 :lb (js2-relpos lb pos)
8942 :rb (js2-relpos rb pos)
8943 :len (- (js2-current-token-end) pos)))
8944 (js2-node-add-children pn
8945 (js2-elem-get-node-target pn)
8946 (js2-elem-get-node-element pn))
8947 pn))
8948
8949 (defun js2-parse-function-call (pn)
8950 (let (args
8951 (pos (js2-node-pos pn)))
8952 (setq pn (make-js2-call-node :pos pos
8953 :target pn
8954 :lp (- (js2-current-token-beg) pos)))
8955 (js2-node-add-children pn (js2-call-node-target pn))
8956 ;; Add the arguments to pn, if any are supplied.
8957 (setf args (nreverse (js2-parse-argument-list))
8958 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
8959 (js2-call-node-args pn) args)
8960 (apply #'js2-node-add-children pn args)
8961 (setf (js2-node-len pn) (- js2-ts-cursor pos))
8962 pn))
8963
8964 (defun js2-parse-property-access (tt pn)
8965 "Parse a property access, XML descendants access, or XML attr access."
8966 (let ((member-type-flags 0)
8967 (dot-pos (js2-current-token-beg))
8968 (dot-len (if (= tt js2-DOTDOT) 2 1))
8969 name
8970 ref ; right side of . or .. operator
8971 result)
8972 (when (= tt js2-DOTDOT)
8973 (js2-must-have-xml)
8974 (setq member-type-flags js2-descendants-flag))
8975 (if (not js2-compiler-xml-available)
8976 (progn
8977 (js2-must-match-prop-name "msg.no.name.after.dot")
8978 (setq name (js2-create-name-node t js2-GETPROP)
8979 result (make-js2-prop-get-node :left pn
8980 :pos (js2-current-token-beg)
8981 :right name
8982 :len (js2-current-token-len)))
8983 (js2-node-add-children result pn name)
8984 result)
8985 ;; otherwise look for XML operators
8986 (setf result (if (= tt js2-DOT)
8987 (make-js2-prop-get-node)
8988 (make-js2-infix-node :type js2-DOTDOT))
8989 (js2-node-pos result) (js2-node-pos pn)
8990 (js2-infix-node-op-pos result) dot-pos
8991 (js2-infix-node-left result) pn ; do this after setting position
8992 tt (js2-next-token))
8993 (cond
8994 ;; needed for generator.throw()
8995 ((= tt js2-THROW)
8996 (setq ref (js2-parse-property-name nil nil member-type-flags)))
8997 ;; handles: name, ns::name, ns::*, ns::[expr]
8998 ((js2-valid-prop-name-token tt)
8999 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9000 ;; handles: *, *::name, *::*, *::[expr]
9001 ((= tt js2-MUL)
9002 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9003 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9004 ((= tt js2-XMLATTR)
9005 (setq result (js2-parse-attribute-access)))
9006 (t
9007 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9008 (if ref
9009 (setf (js2-node-len result) (- (js2-node-end ref)
9010 (js2-node-pos result))
9011 (js2-infix-node-right result) ref))
9012 (if (js2-infix-node-p result)
9013 (js2-node-add-children result
9014 (js2-infix-node-left result)
9015 (js2-infix-node-right result)))
9016 result)))
9017
9018 (defun js2-parse-attribute-access ()
9019 "Parse an E4X XML attribute expression.
9020 This includes expressions of the forms:
9021
9022 @attr @ns::attr @ns::*
9023 @* @*::attr @*::*
9024 @[expr] @*::[expr] @ns::[expr]
9025
9026 Called if we peeked an '@' token."
9027 (let ((tt (js2-next-token))
9028 (at-pos (js2-current-token-beg)))
9029 (cond
9030 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9031 ((js2-valid-prop-name-token tt)
9032 (js2-parse-property-name at-pos nil 0))
9033 ;; handles: @*, @*::name, @*::*, @*::[expr]
9034 ((= tt js2-MUL)
9035 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9036 ;; handles @[expr]
9037 ((= tt js2-LB)
9038 (js2-parse-xml-elem-ref at-pos))
9039 (t
9040 (js2-report-error "msg.no.name.after.xmlAttr")
9041 ;; Avoid cascaded errors that happen if we make an error node here.
9042 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9043
9044 (defun js2-parse-property-name (at-pos s member-type-flags)
9045 "Check if :: follows name in which case it becomes qualified name.
9046
9047 AT-POS is a natural number if we just read an '@' token, else nil.
9048 S is the name or string that was matched: an identifier, 'throw' or '*'.
9049 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9050
9051 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9052 operator, or the name is followed by ::. For a plain name, returns a
9053 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9054 (let ((pos (or at-pos (js2-current-token-beg)))
9055 colon-pos
9056 (name (js2-create-name-node t (js2-current-token-type) s))
9057 ns tt pn)
9058 (catch 'return
9059 (when (js2-match-token js2-COLONCOLON)
9060 (setq ns name
9061 colon-pos (js2-current-token-beg)
9062 tt (js2-next-token))
9063 (cond
9064 ;; handles name::name
9065 ((js2-valid-prop-name-token tt)
9066 (setq name (js2-create-name-node)))
9067 ;; handles name::*
9068 ((= tt js2-MUL)
9069 (setq name (js2-create-name-node nil nil "*")))
9070 ;; handles name::[expr]
9071 ((= tt js2-LB)
9072 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9073 (t
9074 (js2-report-error "msg.no.name.after.coloncolon"))))
9075 (if (and (null ns) (zerop member-type-flags))
9076 name
9077 (prog1
9078 (setq pn
9079 (make-js2-xml-prop-ref-node :pos pos
9080 :len (- (js2-node-end name) pos)
9081 :at-pos at-pos
9082 :colon-pos colon-pos
9083 :propname name))
9084 (js2-node-add-children pn name))))))
9085
9086 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9087 "Parse the [expr] portion of an xml element reference.
9088 For instance, @[expr], @*::[expr], or ns::[expr]."
9089 (let* ((lb (js2-current-token-beg))
9090 (pos (or at-pos lb))
9091 rb
9092 (expr (js2-parse-expr))
9093 (end (js2-node-end expr))
9094 pn)
9095 (if (js2-must-match js2-RB "msg.no.bracket.index")
9096 (setq rb (js2-current-token-beg)
9097 end (js2-current-token-end)))
9098 (prog1
9099 (setq pn
9100 (make-js2-xml-elem-ref-node :pos pos
9101 :len (- end pos)
9102 :namespace namespace
9103 :colon-pos colon-pos
9104 :at-pos at-pos
9105 :expr expr
9106 :lb (js2-relpos lb pos)
9107 :rb (js2-relpos rb pos)))
9108 (js2-node-add-children pn namespace expr))))
9109
9110 (defun js2-parse-destruct-primary-expr ()
9111 (let ((js2-is-in-destructuring t))
9112 (js2-parse-primary-expr)))
9113
9114 (defun js2-parse-primary-expr ()
9115 "Parse a literal (leaf) expression of some sort.
9116 Includes complex literals such as functions, object-literals,
9117 array-literals, array comprehensions and regular expressions."
9118 (let (pn ; parent node (usually return value)
9119 tt
9120 px-pos ; paren-expr pos
9121 len
9122 flags ; regexp flags
9123 expr)
9124 (setq tt (js2-current-token-type))
9125 (cond
9126 ((= tt js2-FUNCTION)
9127 (js2-parse-function-expr))
9128 ((= tt js2-LB)
9129 (js2-parse-array-literal))
9130 ((= tt js2-LC)
9131 (js2-parse-object-literal))
9132 ((= tt js2-LET)
9133 (js2-parse-let (js2-current-token-beg)))
9134 ((= tt js2-LP)
9135 (setq px-pos (js2-current-token-beg)
9136 expr (js2-parse-expr))
9137 (js2-must-match js2-RP "msg.no.paren")
9138 (setq pn (make-js2-paren-node :pos px-pos
9139 :expr expr
9140 :len (- (js2-current-token-end) px-pos)))
9141 (js2-node-add-children pn (js2-paren-node-expr pn))
9142 pn)
9143 ((= tt js2-XMLATTR)
9144 (js2-must-have-xml)
9145 (js2-parse-attribute-access))
9146 ((= tt js2-NAME)
9147 (js2-parse-name tt))
9148 ((= tt js2-NUMBER)
9149 (make-js2-number-node))
9150 ((= tt js2-STRING)
9151 (prog1
9152 (make-js2-string-node)
9153 (js2-record-face 'font-lock-string-face)))
9154 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9155 ;; Got / or /= which in this context means a regexp literal
9156 (setq px-pos (js2-current-token-beg))
9157 (setq flags (js2-read-regexp tt))
9158 (prog1
9159 (make-js2-regexp-node :pos px-pos
9160 :len (- js2-ts-cursor px-pos)
9161 :value (js2-current-token-string)
9162 :flags flags)
9163 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9164 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9165 ((or (= tt js2-NULL)
9166 (= tt js2-THIS)
9167 (= tt js2-FALSE)
9168 (= tt js2-TRUE))
9169 (make-js2-keyword-node :type tt))
9170 ((= tt js2-RP)
9171 ;; Not valid expression syntax, but this is valid in an arrow
9172 ;; function with no params: () => body.
9173 (if (eq (js2-peek-token) js2-ARROW)
9174 (progn
9175 (js2-unget-token) ; Put back the right paren.
9176 ;; Return whatever, it will hopefully be rewinded and
9177 ;; reparsed when we reach the =>.
9178 (make-js2-keyword-node :type js2-NULL))
9179 (js2-report-error "msg.syntax")
9180 (make-js2-error-node)))
9181 ((= tt js2-TRIPLEDOT)
9182 ;; Likewise, only valid in an arrow function with a rest param.
9183 (if (and (js2-match-token js2-NAME)
9184 (js2-match-token js2-RP)
9185 (eq (js2-peek-token) js2-ARROW))
9186 (progn
9187 (js2-unget-token) ; Put back the right paren.
9188 ;; See the previous case.
9189 (make-js2-keyword-node :type js2-NULL))
9190 (js2-report-error "msg.syntax")
9191 (make-js2-error-node)))
9192 ((= tt js2-RESERVED)
9193 (js2-report-error "msg.reserved.id")
9194 (make-js2-name-node))
9195 ((= tt js2-ERROR)
9196 ;; the scanner or one of its subroutines reported the error.
9197 (make-js2-error-node))
9198 ((= tt js2-EOF)
9199 (setq px-pos (point-at-bol)
9200 len (- js2-ts-cursor px-pos))
9201 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9202 (make-js2-error-node :pos (1- js2-ts-cursor)))
9203 (t
9204 (js2-report-error "msg.syntax")
9205 (make-js2-error-node)))))
9206
9207 (defun js2-parse-name (_tt)
9208 (let ((name (js2-current-token-string))
9209 node)
9210 (setq node (if js2-compiler-xml-available
9211 (js2-parse-property-name nil name 0)
9212 (js2-create-name-node 'check-activation nil name)))
9213 (if js2-highlight-external-variables
9214 (js2-record-name-node node))
9215 node))
9216
9217 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9218 (js2-add-strict-warning
9219 msg nil
9220 ;; back up from comma to beginning of line or array/objlit
9221 (max (if elems
9222 (js2-node-pos (car elems))
9223 pos)
9224 (save-excursion
9225 (goto-char comma-pos)
9226 (back-to-indentation)
9227 (point)))
9228 comma-pos))
9229
9230 (defun js2-parse-array-literal ()
9231 (let ((pos (js2-current-token-beg))
9232 (after-lb-or-comma t)
9233 after-comma tt elems pn
9234 (continue t))
9235 (unless js2-is-in-destructuring
9236 (js2-push-scope (make-js2-scope))) ; for array comp
9237 (while continue
9238 (setq tt (js2-get-token))
9239 (cond
9240 ;; comma
9241 ((= tt js2-COMMA)
9242 (setq after-comma (js2-current-token-end))
9243 (if (not after-lb-or-comma)
9244 (setq after-lb-or-comma t)
9245 (push nil elems)))
9246 ;; end of array
9247 ((or (= tt js2-RB)
9248 (= tt js2-EOF)) ; prevent infinite loop
9249 (if (= tt js2-EOF)
9250 (js2-report-error "msg.no.bracket.arg" nil pos))
9251 (setq continue nil
9252 pn (make-js2-array-node :pos pos
9253 :len (- js2-ts-cursor pos)
9254 :elems (nreverse elems)))
9255 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9256 (when (and after-comma (not js2-is-in-destructuring))
9257 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9258 pos elems after-comma)))
9259 ;; destructuring binding
9260 (js2-is-in-destructuring
9261 (push (if (or (= tt js2-LC)
9262 (= tt js2-LB)
9263 (= tt js2-NAME))
9264 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9265 (js2-parse-destruct-primary-expr)
9266 ;; invalid pattern
9267 (js2-report-error "msg.bad.var")
9268 (make-js2-error-node))
9269 elems)
9270 (setq after-lb-or-comma nil
9271 after-comma nil))
9272 ;; array comp
9273 ((and (>= js2-language-version 170)
9274 (= tt js2-FOR) ; check for array comprehension
9275 (not after-lb-or-comma) ; "for" can't follow a comma
9276 elems ; must have at least 1 element
9277 (not (cdr elems))) ; but no 2nd element
9278 (js2-unget-token)
9279 (setf continue nil
9280 pn (js2-parse-array-comprehension (car elems) pos)))
9281
9282 ;; another element
9283 (t
9284 (unless after-lb-or-comma
9285 (js2-report-error "msg.no.bracket.arg"))
9286 (js2-unget-token)
9287 (push (js2-parse-assign-expr) elems)
9288 (setq after-lb-or-comma nil
9289 after-comma nil))))
9290 (unless js2-is-in-destructuring
9291 (js2-pop-scope))
9292 pn))
9293
9294 (defun js2-parse-array-comprehension (expr pos)
9295 "Parse a JavaScript 1.7 Array Comprehension.
9296 EXPR is the first expression after the opening left-bracket.
9297 POS is the beginning of the LB token preceding EXPR.
9298 We should have just parsed the 'for' keyword before calling this function."
9299 (let (loops loop first filter if-pos result)
9300 (while (= (js2-get-token) js2-FOR)
9301 (let ((prev (car loops))) ; rearrange scope chain
9302 (push (setq loop (js2-parse-array-comp-loop)) loops)
9303 (if prev ; each loop is parent scope to the next one
9304 (setf (js2-scope-parent-scope loop) prev)
9305 ; first loop takes expr scope's parent
9306 (setf (js2-scope-parent-scope (setq first loop))
9307 (js2-scope-parent-scope js2-current-scope)))))
9308 (js2-unget-token)
9309 ;; set expr scope's parent to the last loop
9310 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9311 (if (/= (js2-get-token) js2-IF)
9312 (js2-unget-token)
9313 (setq if-pos (- (js2-current-token-beg) pos) ; relative
9314 filter (js2-parse-condition)))
9315 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9316 (setq result (make-js2-array-comp-node :pos pos
9317 :len (- js2-ts-cursor pos)
9318 :result expr
9319 :loops (nreverse loops)
9320 :filter (car filter)
9321 :lp (js2-relpos (second filter) pos)
9322 :rp (js2-relpos (third filter) pos)
9323 :if-pos if-pos))
9324 (apply #'js2-node-add-children result expr (car filter)
9325 (js2-array-comp-node-loops result))
9326 (setq js2-current-scope first) ; pop to the first loop
9327 result))
9328
9329 (defun js2-parse-array-comp-loop ()
9330 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9331 Last token peeked should be the initial FOR."
9332 (let ((pos (js2-current-token-beg))
9333 (pn (make-js2-array-comp-loop-node))
9334 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9335 (assert (= (js2-current-token-type) js2-FOR))
9336 (js2-push-scope pn)
9337 (unwind-protect
9338 (progn
9339 (when (js2-match-token js2-NAME)
9340 (if (string= (js2-current-token-string) "each")
9341 (progn
9342 (setq foreach-p t
9343 each-pos (- (js2-current-token-beg) pos)) ; relative
9344 (js2-record-face 'font-lock-keyword-face))
9345 (js2-report-error "msg.no.paren.for")))
9346 (if (js2-must-match js2-LP "msg.no.paren.for")
9347 (setq lp (- (js2-current-token-beg) pos)))
9348 (setq tt (js2-peek-token))
9349 (cond
9350 ((or (= tt js2-LB)
9351 (= tt js2-LC))
9352 (js2-get-token)
9353 (setq iter (js2-parse-destruct-primary-expr))
9354 (js2-define-destruct-symbols iter js2-LET
9355 'font-lock-variable-name-face t))
9356 ((js2-match-token js2-NAME)
9357 (setq iter (js2-create-name-node)))
9358 (t
9359 (js2-report-error "msg.bad.var")))
9360 ;; Define as a let since we want the scope of the variable to
9361 ;; be restricted to the array comprehension
9362 (if (js2-name-node-p iter)
9363 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9364 (if (or (js2-match-token js2-IN)
9365 (and (>= js2-language-version 200)
9366 (js2-match-contextual-kwd "of")
9367 (setq forof-p t)))
9368 (setq in-pos (- (js2-current-token-beg) pos))
9369 (js2-report-error "msg.in.after.for.name"))
9370 (setq obj (js2-parse-expr))
9371 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9372 (setq rp (- (js2-current-token-beg) pos)))
9373 (setf (js2-node-pos pn) pos
9374 (js2-node-len pn) (- js2-ts-cursor pos)
9375 (js2-array-comp-loop-node-iterator pn) iter
9376 (js2-array-comp-loop-node-object pn) obj
9377 (js2-array-comp-loop-node-in-pos pn) in-pos
9378 (js2-array-comp-loop-node-each-pos pn) each-pos
9379 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9380 (js2-array-comp-loop-node-forof-p pn) forof-p
9381 (js2-array-comp-loop-node-lp pn) lp
9382 (js2-array-comp-loop-node-rp pn) rp)
9383 (js2-node-add-children pn iter obj))
9384 (js2-pop-scope))
9385 pn))
9386
9387 (defun js2-parse-object-literal ()
9388 (let ((pos (js2-current-token-beg))
9389 tt elems result after-comma
9390 (continue t))
9391 (while continue
9392 (setq tt (js2-get-token))
9393 (cond
9394 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9395 ;; {get foo() {...}}, or {set foo(x) {...}}
9396 ((or (js2-valid-prop-name-token tt)
9397 (= tt js2-STRING))
9398 (setq after-comma nil
9399 result (js2-parse-named-prop tt))
9400 (if (and (null result)
9401 (not js2-recover-from-parse-errors))
9402 (setq continue nil)
9403 (push result elems)))
9404 ;; {12: x} or {10.7: x}
9405 ((= tt js2-NUMBER)
9406 (setq after-comma nil)
9407 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9408 ;; trailing comma
9409 ((= tt js2-RC)
9410 (js2-unget-token)
9411 (setq continue nil)
9412 (if after-comma
9413 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9414 pos elems after-comma)))
9415 (t
9416 (js2-report-error "msg.bad.prop")
9417 (unless js2-recover-from-parse-errors
9418 (setq continue nil)))) ; end switch
9419 (if (js2-match-token js2-COMMA)
9420 (setq after-comma (js2-current-token-end))
9421 (setq continue nil))) ; end loop
9422 (js2-must-match js2-RC "msg.no.brace.prop")
9423 (setq result (make-js2-object-node :pos pos
9424 :len (- js2-ts-cursor pos)
9425 :elems (nreverse elems)))
9426 (apply #'js2-node-add-children result (js2-object-node-elems result))
9427 result))
9428
9429 (defun js2-parse-named-prop (tt)
9430 "Parse a name, string, or getter/setter object property.
9431 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9432 (let ((string-prop (and (= tt js2-STRING)
9433 (make-js2-string-node)))
9434 expr
9435 (ppos (js2-current-token-beg))
9436 (pend (js2-current-token-end))
9437 (name (js2-create-name-node))
9438 (prop (js2-current-token-string)))
9439 (cond
9440 ;; getter/setter prop
9441 ((and (= tt js2-NAME)
9442 (= (js2-peek-token) js2-NAME)
9443 (or (string= prop "get")
9444 (string= prop "set")))
9445 (js2-get-token)
9446 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9447 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9448 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9449 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9450 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9451 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9452 ;; when patterns are used in variable declarations, function parameters,
9453 ;; catch-clause, and iterators.
9454 ;; We have to set `js2-is-in-destructuring' to t when the current
9455 ;; expressions are on the left side of any assignment, but it's difficult
9456 ;; because it requires looking ahead of expression.
9457 ((and js2-is-in-destructuring
9458 (= tt js2-NAME)
9459 (let ((ctk (js2-peek-token)))
9460 (or (= ctk js2-COMMA)
9461 (= ctk js2-RC)
9462 (js2-valid-prop-name-token ctk))))
9463 name)
9464 ;; regular prop
9465 (t
9466 (prog1
9467 (setq expr (js2-parse-plain-property (or string-prop name)))
9468 (js2-set-face ppos pend
9469 (if (js2-function-node-p
9470 (js2-object-prop-node-right expr))
9471 'font-lock-function-name-face
9472 'font-lock-variable-name-face)
9473 'record))))))
9474
9475 (defun js2-parse-plain-property (prop)
9476 "Parse a non-getter/setter property in an object literal.
9477 PROP is the node representing the property: a number, name or string."
9478 (js2-must-match js2-COLON "msg.no.colon.prop")
9479 (let* ((pos (js2-node-pos prop))
9480 (colon (- (js2-current-token-beg) pos))
9481 (expr (js2-parse-assign-expr))
9482 (result (make-js2-object-prop-node
9483 :pos pos
9484 ;; don't include last consumed token in length
9485 :len (- (+ (js2-node-pos expr)
9486 (js2-node-len expr))
9487 pos)
9488 :left prop
9489 :right expr
9490 :op-pos colon)))
9491 (js2-node-add-children result prop expr)
9492 result))
9493
9494 (defun js2-parse-getter-setter-prop (pos prop get-p)
9495 "Parse getter or setter property in an object literal.
9496 JavaScript syntax is:
9497
9498 { get foo() {...}, set foo(x) {...} }
9499
9500 and expression closure style is also supported
9501
9502 { get foo() x, set foo(x) _x = x }
9503
9504 POS is the start position of the `get' or `set' keyword.
9505 PROP is the `js2-name-node' representing the property name.
9506 GET-P is non-nil if the keyword was `get'."
9507 (let ((type (if get-p js2-GET js2-SET))
9508 result end
9509 (fn (js2-parse-function-expr)))
9510 ;; it has to be an anonymous function, as we already parsed the name
9511 (if (/= (js2-node-type fn) js2-FUNCTION)
9512 (js2-report-error "msg.bad.prop")
9513 (if (plusp (length (js2-function-name fn)))
9514 (js2-report-error "msg.bad.prop")))
9515 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9516 (setq end (js2-node-end fn)
9517 result (make-js2-getter-setter-node :type type
9518 :pos pos
9519 :len (- end pos)
9520 :left prop
9521 :right fn))
9522 (js2-node-add-children result prop fn)
9523 result))
9524
9525 (defun js2-create-name-node (&optional check-activation-p token string)
9526 "Create a name node using the current token and, optionally, STRING.
9527 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
9528 (let* ((beg (js2-current-token-beg))
9529 (tt (js2-current-token-type))
9530 (s (or string
9531 (if (= js2-NAME tt)
9532 (js2-current-token-string)
9533 (js2-tt-name tt))))
9534 name)
9535 (setq name (make-js2-name-node :pos beg
9536 :name s
9537 :len (length s)))
9538 (if check-activation-p
9539 (js2-check-activation-name s (or token js2-NAME)))
9540 name))
9541
9542 ;;; Indentation support
9543
9544 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9545 ;; Karl cleverly deduces that the desired indentation level is often a
9546 ;; function of paren/bracket/brace nesting depth, which can be determined
9547 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9548 ;; then does some equally clever checks to see if we're in the context of a
9549 ;; substatement of a possibly braceless statement keyword such as if, while,
9550 ;; or finally. This approach yields pretty good results.
9551
9552 ;; The indenter is often "wrong", however, and needs to be overridden.
9553 ;; The right long-term solution is probably to emulate (or integrate
9554 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9555 ;; parse tree from `js2-parse' is present, which is not true at the
9556 ;; moment the user is typing, computing indentation is still thousands
9557 ;; of lines of code to handle every possible syntactic edge case.
9558
9559 ;; In the meantime, the compromise solution is that we offer a "bounce
9560 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9561 ;; current line indent among various likely guess points. This approach
9562 ;; is far from perfect, but should at least make it slightly easier to
9563 ;; move the line towards its desired indentation when manually
9564 ;; overriding Karl's heuristic nesting guesser.
9565
9566 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9567 ;; extensions such as `let' and Array comprehensions. Major kudos to
9568 ;; Karl for coming up with the initial approach, which packs a lot of
9569 ;; punch for so little code.
9570
9571 (defconst js2-possibly-braceless-keywords-re
9572 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9573 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9574 "try" "while" "with" "let")))
9575 "Regular expression matching keywords that are optionally
9576 followed by an opening brace.")
9577
9578 (defconst js2-indent-operator-re
9579 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9580 (regexp-opt '("in" "instanceof") 'words))
9581 "Regular expression matching operators that affect indentation
9582 of continued expressions.")
9583
9584 (defconst js2-declaration-keyword-re
9585 (regexp-opt '("var" "let" "const") 'words)
9586 "Regular expression matching variable declaration keywords.")
9587
9588 (defun js2-re-search-forward-inner (regexp &optional bound count)
9589 "Auxiliary function for `js2-re-search-forward'."
9590 (let (parse saved-point)
9591 (while (> count 0)
9592 (re-search-forward regexp bound)
9593 (setq parse (if saved-point
9594 (parse-partial-sexp saved-point (point))
9595 (syntax-ppss (point))))
9596 (cond ((nth 3 parse)
9597 (re-search-forward
9598 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9599 (save-excursion (end-of-line) (point)) t))
9600 ((nth 7 parse)
9601 (forward-line))
9602 ((or (nth 4 parse)
9603 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9604 (re-search-forward "\\*/"))
9605 (t
9606 (setq count (1- count))))
9607 (setq saved-point (point))))
9608 (point))
9609
9610 (defun js2-re-search-forward (regexp &optional bound noerror count)
9611 "Search forward but ignore strings and comments.
9612 Invokes `re-search-forward' but treats the buffer as if strings
9613 and comments have been removed."
9614 (let ((saved-point (point)))
9615 (condition-case err
9616 (cond ((null count)
9617 (js2-re-search-forward-inner regexp bound 1))
9618 ((< count 0)
9619 (js2-re-search-backward-inner regexp bound (- count)))
9620 ((> count 0)
9621 (js2-re-search-forward-inner regexp bound count)))
9622 (search-failed
9623 (goto-char saved-point)
9624 (unless noerror
9625 (error (error-message-string err)))))))
9626
9627 (defun js2-re-search-backward-inner (regexp &optional bound count)
9628 "Auxiliary function for `js2-re-search-backward'."
9629 (let (parse)
9630 (while (> count 0)
9631 (re-search-backward regexp bound)
9632 (setq parse (syntax-ppss (point)))
9633 (cond ((nth 3 parse)
9634 (re-search-backward
9635 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9636 (line-beginning-position) t))
9637 ((nth 7 parse)
9638 (goto-char (nth 8 parse)))
9639 ((or (nth 4 parse)
9640 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9641 (re-search-backward "/\\*"))
9642 (t
9643 (setq count (1- count))))))
9644 (point))
9645
9646 (defun js2-re-search-backward (regexp &optional bound noerror count)
9647 "Search backward but ignore strings and comments.
9648 Invokes `re-search-backward' but treats the buffer as if strings
9649 and comments have been removed."
9650 (let ((saved-point (point)))
9651 (condition-case err
9652 (cond ((null count)
9653 (js2-re-search-backward-inner regexp bound 1))
9654 ((< count 0)
9655 (js2-re-search-forward-inner regexp bound (- count)))
9656 ((> count 0)
9657 (js2-re-search-backward-inner regexp bound count)))
9658 (search-failed
9659 (goto-char saved-point)
9660 (unless noerror
9661 (error (error-message-string err)))))))
9662
9663 (defun js2-looking-at-operator-p ()
9664 "Return non-nil if text after point is a non-comma operator."
9665 (and (looking-at js2-indent-operator-re)
9666 (or (not (looking-at ":"))
9667 (save-excursion
9668 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9669 (looking-at "?"))))))
9670
9671 (defun js2-continued-expression-p ()
9672 "Return non-nil if the current line continues an expression."
9673 (save-excursion
9674 (back-to-indentation)
9675 (or (js2-looking-at-operator-p)
9676 (when (catch 'found
9677 (while (and (re-search-backward "\n" nil t)
9678 (let ((state (syntax-ppss)))
9679 (when (nth 4 state)
9680 (goto-char (nth 8 state))) ;; skip comments
9681 (skip-chars-backward " \t")
9682 (if (bolp)
9683 t
9684 (throw 'found t))))))
9685 (backward-char)
9686 (when (js2-looking-at-operator-p)
9687 (backward-char)
9688 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))
9689
9690 (defun js2-end-of-do-while-loop-p ()
9691 "Return non-nil if word after point is `while' of a do-while
9692 statement, else returns nil. A braceless do-while statement
9693 spanning several lines requires that the start of the loop is
9694 indented to the same column as the current line."
9695 (interactive)
9696 (save-excursion
9697 (when (looking-at "\\s-*\\<while\\>")
9698 (if (save-excursion
9699 (skip-chars-backward "[ \t\n]*}")
9700 (looking-at "[ \t\n]*}"))
9701 (save-excursion
9702 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9703 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9704 (or (looking-at "\\<do\\>")
9705 (let ((saved-indent (current-indentation)))
9706 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9707 (/= (current-indentation) saved-indent)))
9708 (and (looking-at "[ \t]*\\<do\\>")
9709 (not (js2-re-search-forward
9710 "\\<while\\>" (point-at-eol) t))
9711 (= (current-indentation) saved-indent))))))))
9712
9713 (defun js2-multiline-decl-indentation ()
9714 "Return the declaration indentation column if the current line belongs
9715 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9716 (let (forward-sexp-function ; use Lisp version
9717 at-opening-bracket)
9718 (save-excursion
9719 (back-to-indentation)
9720 (when (not (looking-at js2-declaration-keyword-re))
9721 (when (looking-at js2-indent-operator-re)
9722 (goto-char (match-end 0))) ; continued expressions are ok
9723 (while (and (not at-opening-bracket)
9724 (not (bobp))
9725 (let ((pos (point)))
9726 (save-excursion
9727 (js2-backward-sws)
9728 (or (eq (char-before) ?,)
9729 (and (not (eq (char-before) ?\;))
9730 (prog2 (skip-syntax-backward ".")
9731 (looking-at js2-indent-operator-re)
9732 (js2-backward-sws))
9733 (not (eq (char-before) ?\;)))
9734 (js2-same-line pos)))))
9735 (condition-case _
9736 (backward-sexp)
9737 (scan-error (setq at-opening-bracket t))))
9738 (when (looking-at js2-declaration-keyword-re)
9739 (goto-char (match-end 0))
9740 (1+ (current-column)))))))
9741
9742 (defun js2-ctrl-statement-indentation ()
9743 "Return the proper indentation of current line if it is a control statement.
9744 Returns an indentation if this line starts the body of a control
9745 statement without braces, else returns nil."
9746 (let (forward-sexp-function)
9747 (save-excursion
9748 (back-to-indentation)
9749 (when (and (not (js2-same-line (point-min)))
9750 (not (looking-at "{"))
9751 (js2-re-search-backward "[[:graph:]]" nil t)
9752 (not (looking-at "[{([]"))
9753 (progn
9754 (forward-char)
9755 (when (= (char-before) ?\))
9756 ;; scan-sexps sometimes throws an error
9757 (ignore-errors (backward-sexp))
9758 (skip-chars-backward " \t" (point-at-bol)))
9759 (let ((pt (point)))
9760 (back-to-indentation)
9761 (when (looking-at "}[ \t]*")
9762 (goto-char (match-end 0)))
9763 (and (looking-at js2-possibly-braceless-keywords-re)
9764 (= (match-end 0) pt)
9765 (not (js2-end-of-do-while-loop-p))))))
9766 (+ (current-indentation) js2-basic-offset)))))
9767
9768 (defun js2-indent-in-array-comp (parse-status)
9769 "Return non-nil if we think we're in an array comprehension.
9770 In particular, return the buffer position of the first `for' kwd."
9771 (let ((bracket (nth 1 parse-status))
9772 (end (point)))
9773 (when bracket
9774 (save-excursion
9775 (goto-char bracket)
9776 (when (looking-at "\\[")
9777 (forward-char 1)
9778 (js2-forward-sws)
9779 (if (looking-at "[[{]")
9780 (let (forward-sexp-function) ; use Lisp version
9781 (forward-sexp) ; skip destructuring form
9782 (js2-forward-sws)
9783 (if (and (/= (char-after) ?,) ; regular array
9784 (looking-at "for"))
9785 (match-beginning 0)))
9786 ;; to skip arbitrary expressions we need the parser,
9787 ;; so we'll just guess at it.
9788 (if (and (> end (point)) ; not empty literal
9789 (re-search-forward "[^,]]* \\(for\\) " end t)
9790 ;; not inside comment or string literal
9791 (let ((state (parse-partial-sexp bracket (point))))
9792 (not (or (nth 3 state) (nth 4 state)))))
9793 (match-beginning 1))))))))
9794
9795 (defun js2-array-comp-indentation (parse-status for-kwd)
9796 (if (js2-same-line for-kwd)
9797 ;; first continuation line
9798 (save-excursion
9799 (goto-char (nth 1 parse-status))
9800 (forward-char 1)
9801 (skip-chars-forward " \t")
9802 (current-column))
9803 (save-excursion
9804 (goto-char for-kwd)
9805 (current-column))))
9806
9807 (defun js2-proper-indentation (parse-status)
9808 "Return the proper indentation for the current line."
9809 (save-excursion
9810 (back-to-indentation)
9811 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9812 (at-closing-bracket (looking-at "[]})]"))
9813 (same-indent-p (or at-closing-bracket
9814 (looking-at "\\<case\\>[^:]")
9815 (and (looking-at "\\<default:")
9816 (save-excursion
9817 (js2-backward-sws)
9818 (not (memq (char-before) '(?, ?{)))))))
9819 (continued-expr-p (js2-continued-expression-p))
9820 (declaration-indent (and js2-pretty-multiline-declarations
9821 (js2-multiline-decl-indentation)))
9822 (bracket (nth 1 parse-status))
9823 beg indent)
9824 (cond
9825 ;; indent array comprehension continuation lines specially
9826 ((and bracket
9827 (>= js2-language-version 170)
9828 (not (js2-same-line bracket))
9829 (setq beg (js2-indent-in-array-comp parse-status))
9830 (>= (point) (save-excursion
9831 (goto-char beg)
9832 (point-at-bol)))) ; at or after first loop?
9833 (js2-array-comp-indentation parse-status beg))
9834
9835 (ctrl-stmt-indent)
9836
9837 ((and declaration-indent continued-expr-p)
9838 (+ declaration-indent js2-basic-offset))
9839
9840 (declaration-indent)
9841
9842 (bracket
9843 (goto-char bracket)
9844 (cond
9845 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9846 (when (save-excursion (skip-chars-backward " \t)")
9847 (looking-at ")"))
9848 (backward-list))
9849 (back-to-indentation)
9850 (and (eq js2-pretty-multiline-declarations 'all)
9851 (looking-at js2-declaration-keyword-re)
9852 (goto-char (1+ (match-end 0))))
9853 (setq indent
9854 (cond (same-indent-p
9855 (current-column))
9856 (continued-expr-p
9857 (+ (current-column) (* 2 js2-basic-offset)))
9858 (t
9859 (+ (current-column) js2-basic-offset))))
9860 (if (and js2-indent-switch-body
9861 (not at-closing-bracket)
9862 (looking-at "\\_<switch\\_>"))
9863 (+ indent js2-basic-offset)
9864 indent))
9865 (t
9866 (unless same-indent-p
9867 (forward-char)
9868 (skip-chars-forward " \t"))
9869 (current-column))))
9870
9871 (continued-expr-p js2-basic-offset)
9872
9873 (t 0)))))
9874
9875 (defun js2-lineup-comment (parse-status)
9876 "Indent a multi-line block comment continuation line."
9877 (let* ((beg (nth 8 parse-status))
9878 (first-line (js2-same-line beg))
9879 (offset (save-excursion
9880 (goto-char beg)
9881 (if (looking-at "/\\*")
9882 (+ 1 (current-column))
9883 0))))
9884 (unless first-line
9885 (indent-line-to offset))))
9886
9887 (defun js2-backward-sws ()
9888 "Move backward through whitespace and comments."
9889 (interactive)
9890 (while (forward-comment -1)))
9891
9892 (defun js2-forward-sws ()
9893 "Move forward through whitespace and comments."
9894 (interactive)
9895 (while (forward-comment 1)))
9896
9897 (defun js2-current-indent (&optional pos)
9898 "Return column of indentation on current line.
9899 If POS is non-nil, go to that point and return indentation for that line."
9900 (save-excursion
9901 (if pos
9902 (goto-char pos))
9903 (back-to-indentation)
9904 (current-column)))
9905
9906 (defun js2-arglist-close ()
9907 "Return non-nil if we're on a line beginning with a close-paren/brace."
9908 (save-excursion
9909 (goto-char (point-at-bol))
9910 (js2-forward-sws)
9911 (looking-at "[])}]")))
9912
9913 (defun js2-indent-looks-like-label-p ()
9914 (goto-char (point-at-bol))
9915 (js2-forward-sws)
9916 (looking-at (concat js2-mode-identifier-re ":")))
9917
9918 (defun js2-indent-in-objlit-p (parse-status)
9919 "Return non-nil if this looks like an object-literal entry."
9920 (let ((start (nth 1 parse-status)))
9921 (and
9922 start
9923 (save-excursion
9924 (and (zerop (forward-line -1))
9925 (not (< (point) start)) ; crossed a {} boundary
9926 (js2-indent-looks-like-label-p)))
9927 (save-excursion
9928 (js2-indent-looks-like-label-p)))))
9929
9930 ;; If prev line looks like foobar({ then we're passing an object
9931 ;; literal to a function call, and people pretty much always want to
9932 ;; de-dent back to the previous line, so move the 'basic-offset'
9933 ;; position to the front.
9934 (defun js2-indent-objlit-arg-p (parse-status)
9935 (save-excursion
9936 (back-to-indentation)
9937 (js2-backward-sws)
9938 (and (eq (1- (point)) (nth 1 parse-status))
9939 (eq (char-before) ?{)
9940 (progn
9941 (forward-char -1)
9942 (skip-chars-backward " \t")
9943 (eq (char-before) ?\()))))
9944
9945 (defun js2-indent-case-block-p ()
9946 (save-excursion
9947 (back-to-indentation)
9948 (js2-backward-sws)
9949 (goto-char (point-at-bol))
9950 (skip-chars-forward " \t")
9951 (looking-at "case\\s-.+:")))
9952
9953 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
9954 "Cycle among alternate computed indentation positions.
9955 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9956 of the buffer to the current point. NORMAL-COL is the indentation
9957 column computed by the heuristic guesser based on current paren,
9958 bracket, brace and statement nesting. If BACKWARDS, cycle positions
9959 in reverse."
9960 (let ((cur-indent (js2-current-indent))
9961 (old-buffer-undo-list buffer-undo-list)
9962 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9963 (current-line (save-excursion
9964 (forward-line 0) ; move to bol
9965 (1+ (count-lines (point-min) (point)))))
9966 positions pos main-pos anchor arglist-cont same-indent
9967 basic-offset computed-pos)
9968 ;; temporarily don't record undo info, if user requested this
9969 (when js2-mode-indent-inhibit-undo
9970 (setq buffer-undo-list t))
9971 (unwind-protect
9972 (progn
9973 ;; First likely point: indent from beginning of previous code line
9974 (push (setq basic-offset
9975 (+ (save-excursion
9976 (back-to-indentation)
9977 (js2-backward-sws)
9978 (back-to-indentation)
9979 (current-column))
9980 js2-basic-offset))
9981 positions)
9982
9983 ;; (First + epsilon) likely point: indent 2x from beginning of
9984 ;; previous code line. Google does it this way.
9985 (push (setq basic-offset
9986 (+ (save-excursion
9987 (back-to-indentation)
9988 (js2-backward-sws)
9989 (back-to-indentation)
9990 (current-column))
9991 (* 2 js2-basic-offset)))
9992 positions)
9993
9994 ;; Second likely point: indent from assign-expr RHS. This
9995 ;; is just a crude guess based on finding " = " on the previous
9996 ;; line containing actual code.
9997 (setq pos (save-excursion
9998 (forward-line -1)
9999 (goto-char (point-at-bol))
10000 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10001 (point-at-eol) t)
10002 (goto-char (match-end 1))
10003 (skip-chars-forward " \t\r\n")
10004 (current-column))))
10005 (when pos
10006 (incf pos js2-basic-offset)
10007 (push pos positions))
10008
10009 ;; Third likely point: same indent as previous line of code.
10010 ;; Make it the first likely point if we're not on an
10011 ;; arglist-close line and previous line ends in a comma, or
10012 ;; both this line and prev line look like object-literal
10013 ;; elements.
10014 (setq pos (save-excursion
10015 (goto-char (point-at-bol))
10016 (js2-backward-sws)
10017 (back-to-indentation)
10018 (prog1
10019 (current-column)
10020 ;; while we're here, look for trailing comma
10021 (if (save-excursion
10022 (goto-char (point-at-eol))
10023 (js2-backward-sws)
10024 (eq (char-before) ?,))
10025 (setq arglist-cont (1- (point)))))))
10026 (when pos
10027 (if (and (or arglist-cont
10028 (js2-indent-in-objlit-p parse-status))
10029 (not (js2-arglist-close)))
10030 (setq same-indent pos))
10031 (push pos positions))
10032
10033 ;; Fourth likely point: first preceding code with less indentation.
10034 ;; than the immediately preceding code line.
10035 (setq pos (save-excursion
10036 (back-to-indentation)
10037 (js2-backward-sws)
10038 (back-to-indentation)
10039 (setq anchor (current-column))
10040 (while (and (zerop (forward-line -1))
10041 (>= (progn
10042 (back-to-indentation)
10043 (current-column))
10044 anchor)))
10045 (setq pos (current-column))))
10046 (push pos positions)
10047
10048 ;; nesting-heuristic position, main by default
10049 (push (setq main-pos normal-col) positions)
10050
10051 ;; delete duplicates and sort positions list
10052 (setq positions (sort (delete-dups positions) '<))
10053
10054 ;; comma-list continuation lines: prev line indent takes precedence
10055 (if same-indent
10056 (setq main-pos same-indent))
10057
10058 ;; common special cases where we want to indent in from previous line
10059 (if (or (js2-indent-case-block-p)
10060 (js2-indent-objlit-arg-p parse-status))
10061 (setq main-pos basic-offset))
10062
10063 ;; if bouncing backwards, reverse positions list
10064 (if backwards
10065 (setq positions (reverse positions)))
10066
10067 ;; record whether we're already sitting on one of the alternatives
10068 (setq pos (member cur-indent positions))
10069
10070 (cond
10071 ;; case 0: we're one one of the alternatives and this is the
10072 ;; first time they've pressed TAB on this line (best-guess).
10073 ((and js2-mode-indent-ignore-first-tab
10074 pos
10075 ;; first time pressing TAB on this line?
10076 (not (eq js2-mode-last-indented-line current-line)))
10077 ;; do nothing
10078 (setq computed-pos nil))
10079 ;; case 1: only one computed position => use it
10080 ((null (cdr positions))
10081 (setq computed-pos 0))
10082 ;; case 2: not on any of the computed spots => use main spot
10083 ((not pos)
10084 (setq computed-pos (js2-position main-pos positions)))
10085 ;; case 3: on last position: cycle to first position
10086 ((null (cdr pos))
10087 (setq computed-pos 0))
10088 ;; case 4: on intermediate position: cycle to next position
10089 (t
10090 (setq computed-pos (js2-position (second pos) positions))))
10091
10092 ;; see if any hooks want to indent; otherwise we do it
10093 (loop with result = nil
10094 for hook in js2-indent-hook
10095 while (null result)
10096 do
10097 (setq result (funcall hook positions computed-pos))
10098 finally do
10099 (unless (or result (null computed-pos))
10100 (indent-line-to (nth computed-pos positions)))))
10101
10102 ;; finally
10103 (if js2-mode-indent-inhibit-undo
10104 (setq buffer-undo-list old-buffer-undo-list))
10105 ;; see commentary for `js2-mode-last-indented-line'
10106 (setq js2-mode-last-indented-line current-line))))
10107
10108 (defun js2-indent-bounce-backwards ()
10109 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10110 cycles between the computed indentation positions in reverse order."
10111 (interactive)
10112 (js2-indent-line t))
10113
10114 (defun js2-1-line-comment-continuation-p ()
10115 "Return t if we're in a 1-line comment continuation.
10116 If so, we don't ever want to use bounce-indent."
10117 (save-excursion
10118 (and (progn
10119 (forward-line 0)
10120 (looking-at "\\s-*//"))
10121 (progn
10122 (forward-line -1)
10123 (forward-line 0)
10124 (when (looking-at "\\s-*$")
10125 (js2-backward-sws)
10126 (forward-line 0))
10127 (looking-at "\\s-*//")))))
10128
10129 (defun js2-indent-line (&optional bounce-backwards)
10130 "Indent the current line as JavaScript source text."
10131 (interactive)
10132 (let (parse-status offset indent-col
10133 ;; Don't whine about errors/warnings when we're indenting.
10134 ;; This has to be set before calling parse-partial-sexp below.
10135 (inhibit-point-motion-hooks t))
10136 (setq parse-status (save-excursion
10137 (syntax-ppss (point-at-bol)))
10138 offset (- (point) (save-excursion
10139 (back-to-indentation)
10140 (point))))
10141 (js2-with-underscore-as-word-syntax
10142 (if (nth 4 parse-status)
10143 (js2-lineup-comment parse-status)
10144 (setq indent-col (js2-proper-indentation parse-status))
10145 ;; See comments below about `js2-mode-last-indented-line'.
10146 (cond
10147 ;; bounce-indenting is disabled during electric-key indent.
10148 ;; It doesn't work well on first line of buffer.
10149 ((and js2-bounce-indent-p
10150 (not (js2-same-line (point-min)))
10151 (not (js2-1-line-comment-continuation-p)))
10152 (js2-bounce-indent indent-col parse-status bounce-backwards))
10153 ;; just indent to the guesser's likely spot
10154 (t (indent-line-to indent-col))))
10155 (when (plusp offset)
10156 (forward-char offset)))))
10157
10158 (defun js2-indent-region (start end)
10159 "Indent the region, but don't use bounce indenting."
10160 (let ((js2-bounce-indent-p nil)
10161 (indent-region-function nil)
10162 (after-change-functions (remq 'js2-mode-edit
10163 after-change-functions)))
10164 (indent-region start end nil) ; nil for byte-compiler
10165 (js2-mode-edit start end (- end start))))
10166
10167 (defvar js2-minor-mode-map
10168 (let ((map (make-sparse-keymap)))
10169 (define-key map (kbd "C-c C-`") #'js2-next-error)
10170 (define-key map [mouse-1] #'js2-mode-show-node)
10171 map)
10172 "Keymap used when `js2-minor-mode' is active.")
10173
10174 ;;;###autoload
10175 (define-minor-mode js2-minor-mode
10176 "Minor mode for running js2 as a background linter.
10177 This allows you to use a different major mode for JavaScript editing,
10178 such as `espresso-mode', while retaining the asynchronous error/warning
10179 highlighting features of `js2-mode'."
10180 :group 'js2-mode
10181 :lighter " js-lint"
10182 (if js2-minor-mode
10183 (js2-minor-mode-enter)
10184 (js2-minor-mode-exit)))
10185
10186 (defun js2-minor-mode-enter ()
10187 "Initialization for `js2-minor-mode'."
10188 (set (make-local-variable 'max-lisp-eval-depth)
10189 (max max-lisp-eval-depth 3000))
10190 (setq next-error-function #'js2-next-error)
10191 (js2-set-default-externs)
10192 ;; Experiment: make reparse-delay longer for longer files.
10193 (if (plusp js2-dynamic-idle-timer-adjust)
10194 (setq js2-idle-timer-delay
10195 (* js2-idle-timer-delay
10196 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10197 (setq js2-mode-buffer-dirty-p t
10198 js2-mode-parsing nil)
10199 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10200 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10201 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10202 (when js2-include-jslint-globals
10203 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10204 (run-hooks 'js2-init-hook)
10205 (js2-reparse))
10206
10207 (defun js2-minor-mode-exit ()
10208 "Turn off `js2-minor-mode'."
10209 (setq next-error-function nil)
10210 (remove-hook 'after-change-functions #'js2-mode-edit t)
10211 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10212 (when js2-mode-node-overlay
10213 (delete-overlay js2-mode-node-overlay)
10214 (setq js2-mode-node-overlay nil))
10215 (js2-remove-overlays)
10216 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
10217 (setq js2-mode-ast nil))
10218
10219 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10220 (make-variable-buffer-local 'js2-source-buffer)
10221
10222 (defun* js2-display-error-list ()
10223 "Display a navigable buffer listing parse errors/warnings."
10224 (interactive)
10225 (unless (js2-have-errors-p)
10226 (message "No errors")
10227 (return-from js2-display-error-list))
10228 (labels ((annotate-list
10229 (lst type)
10230 "Add diagnostic TYPE and line number to errs list"
10231 (mapcar (lambda (err)
10232 (list err type (line-number-at-pos (nth 1 err))))
10233 lst)))
10234 (let* ((srcbuf (current-buffer))
10235 (errbuf (get-buffer-create "*js-lint*"))
10236 (errors (annotate-list
10237 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10238 'js2-error)) ; must be a valid face name
10239 (warnings (annotate-list
10240 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10241 'js2-warning)) ; must be a valid face name
10242 (all-errs (sort (append errors warnings)
10243 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10244 (with-current-buffer errbuf
10245 (let ((inhibit-read-only t))
10246 (erase-buffer)
10247 (dolist (err all-errs)
10248 (destructuring-bind ((msg-key beg _end &rest) type line) err
10249 (insert-text-button
10250 (format "line %d: %s" line (js2-get-msg msg-key))
10251 'face type
10252 'follow-link "\C-m"
10253 'action 'js2-error-buffer-jump
10254 'js2-msg (js2-get-msg msg-key)
10255 'js2-pos beg)
10256 (insert "\n"))))
10257 (js2-error-buffer-mode)
10258 (setq js2-source-buffer srcbuf)
10259 (pop-to-buffer errbuf)
10260 (goto-char (point-min))
10261 (unless (eobp)
10262 (js2-error-buffer-view))))))
10263
10264 (defvar js2-error-buffer-mode-map
10265 (let ((map (make-sparse-keymap)))
10266 (define-key map "n" #'js2-error-buffer-next)
10267 (define-key map "p" #'js2-error-buffer-prev)
10268 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10269 (define-key map "o" #'js2-error-buffer-view)
10270 (define-key map "q" #'js2-error-buffer-quit)
10271 map)
10272 "Keymap used for js2 diagnostics buffers.")
10273
10274 (defun js2-error-buffer-mode ()
10275 "Major mode for js2 diagnostics buffers.
10276 Selecting an error will jump it to the corresponding source-buffer error.
10277 \\{js2-error-buffer-mode-map}"
10278 (interactive)
10279 (setq major-mode 'js2-error-buffer-mode
10280 mode-name "JS Lint Diagnostics")
10281 (use-local-map js2-error-buffer-mode-map)
10282 (setq truncate-lines t)
10283 (set-buffer-modified-p nil)
10284 (setq buffer-read-only t)
10285 (run-hooks 'js2-error-buffer-mode-hook))
10286
10287 (defun js2-error-buffer-next ()
10288 "Move to next error and view it."
10289 (interactive)
10290 (when (zerop (forward-line 1))
10291 (js2-error-buffer-view)))
10292
10293 (defun js2-error-buffer-prev ()
10294 "Move to previous error and view it."
10295 (interactive)
10296 (when (zerop (forward-line -1))
10297 (js2-error-buffer-view)))
10298
10299 (defun js2-error-buffer-quit ()
10300 "Kill the current buffer."
10301 (interactive)
10302 (kill-buffer))
10303
10304 (defun js2-error-buffer-jump (&rest ignored)
10305 "Jump cursor to current error in source buffer."
10306 (interactive)
10307 (when (js2-error-buffer-view)
10308 (pop-to-buffer js2-source-buffer)))
10309
10310 (defun js2-error-buffer-view ()
10311 "Scroll source buffer to show error at current line."
10312 (interactive)
10313 (cond
10314 ((not (eq major-mode 'js2-error-buffer-mode))
10315 (message "Not in a js2 errors buffer"))
10316 ((not (buffer-live-p js2-source-buffer))
10317 (message "Source buffer has been killed"))
10318 ((not (wholenump (get-text-property (point) 'js2-pos)))
10319 (message "There does not seem to be an error here"))
10320 (t
10321 (let ((pos (get-text-property (point) 'js2-pos))
10322 (msg (get-text-property (point) 'js2-msg)))
10323 (save-selected-window
10324 (pop-to-buffer js2-source-buffer)
10325 (goto-char pos)
10326 (message msg))))))
10327
10328 ;;;###autoload
10329 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10330 ;; FIXME: Should derive from js-mode.
10331 "Major mode for editing JavaScript code."
10332 ;; Used by comment-region; don't change it.
10333 (set (make-local-variable 'comment-start) "//")
10334 (set (make-local-variable 'comment-end) "")
10335 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
10336 (set (make-local-variable 'max-lisp-eval-depth)
10337 (max max-lisp-eval-depth 3000))
10338 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10339 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10340 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10341 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10342 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10343 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10344 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10345 ;; for characters inside regexp literals.
10346 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10347 ;; this is necessary to make `show-paren-function' work properly
10348 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10349 ;; needed for M-x rgrep, among other things
10350 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10351
10352 (set (make-local-variable 'electric-indent-chars)
10353 (append '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
10354 electric-indent-chars))
10355 (set (make-local-variable 'electric-layout-rules)
10356 '((?\; . after) (?\{ . after) (?\} . before)))
10357
10358 ;; some variables needed by cc-engine for paragraph-fill, etc.
10359 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10360 c-comment-start-regexp "/[*/]\\|\\s|"
10361 c-line-comment-starter "//"
10362 c-paragraph-start js2-paragraph-start
10363 c-paragraph-separate "$"
10364 c-syntactic-ws-start js2-syntactic-ws-start
10365 c-syntactic-ws-end js2-syntactic-ws-end
10366 c-syntactic-eol js2-syntactic-eol)
10367
10368 (let ((c-buffer-is-cc-mode t))
10369 ;; Copied from `js-mode'. Also see Bug#6071.
10370 (make-local-variable 'paragraph-start)
10371 (make-local-variable 'paragraph-separate)
10372 (make-local-variable 'paragraph-ignore-fill-prefix)
10373 (make-local-variable 'adaptive-fill-mode)
10374 (make-local-variable 'adaptive-fill-regexp)
10375 (c-setup-paragraph-variables))
10376
10377 (setq font-lock-defaults '(nil t))
10378
10379 ;; Experiment: make reparse-delay longer for longer files.
10380 (when (plusp js2-dynamic-idle-timer-adjust)
10381 (setq js2-idle-timer-delay
10382 (* js2-idle-timer-delay
10383 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10384
10385 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10386 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10387 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10388 (setq next-error-function #'js2-next-error)
10389 (imenu-add-to-menubar (concat "IM-" mode-name))
10390 (add-to-invisibility-spec '(js2-outline . t))
10391 (set (make-local-variable 'line-move-ignore-invisible) t)
10392 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10393
10394 (setq js2-mode-functions-hidden nil
10395 js2-mode-comments-hidden nil
10396 js2-mode-buffer-dirty-p t
10397 js2-mode-parsing nil)
10398
10399 (js2-set-default-externs)
10400
10401 (when js2-include-jslint-globals
10402 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10403
10404 (run-hooks 'js2-init-hook)
10405
10406 (js2-reparse))
10407
10408 (defun js2-mode-exit ()
10409 "Exit `js2-mode' and clean up."
10410 (interactive)
10411 (when js2-mode-node-overlay
10412 (delete-overlay js2-mode-node-overlay)
10413 (setq js2-mode-node-overlay nil))
10414 (js2-remove-overlays)
10415 (setq js2-mode-ast nil)
10416 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10417 (remove-from-invisibility-spec '(js2-outline . t))
10418 (js2-mode-show-all)
10419 (with-silent-modifications
10420 (js2-clear-face (point-min) (point-max))))
10421
10422 (defun js2-mode-reset-timer ()
10423 "Cancel any existing parse timer and schedule a new one."
10424 (if js2-mode-parse-timer
10425 (cancel-timer js2-mode-parse-timer))
10426 (setq js2-mode-parsing nil)
10427 (let ((timer (timer-create)))
10428 (setq js2-mode-parse-timer timer)
10429 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10430 (timer-set-idle-time timer js2-idle-timer-delay)
10431 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10432 (timer-activate-when-idle timer nil)))
10433
10434 (defun js2-mode-idle-reparse (buffer)
10435 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10436 it to be reparsed when the buffer is selected."
10437 (if (eq buffer (current-buffer))
10438 (js2-reparse)
10439 ;; reparse when the buffer is selected again
10440 (with-current-buffer buffer
10441 (add-hook 'window-configuration-change-hook
10442 #'js2-mode-idle-reparse-inner
10443 nil t))))
10444
10445 (defun js2-mode-idle-reparse-inner ()
10446 (remove-hook 'window-configuration-change-hook
10447 #'js2-mode-idle-reparse-inner
10448 t)
10449 (js2-reparse))
10450
10451 (defun js2-mode-edit (_beg _end _len)
10452 "Schedule a new parse after buffer is edited.
10453 Buffer edit spans from BEG to END and is of length LEN."
10454 (setq js2-mode-buffer-dirty-p t)
10455 (js2-mode-hide-overlay)
10456 (js2-mode-reset-timer))
10457
10458 (defun js2-minor-mode-edit (_beg _end _len)
10459 "Callback for buffer edits in `js2-mode'.
10460 Schedules a new parse after buffer is edited.
10461 Buffer edit spans from BEG to END and is of length LEN."
10462 (setq js2-mode-buffer-dirty-p t)
10463 (js2-mode-hide-overlay)
10464 (js2-mode-reset-timer))
10465
10466 (defun js2-reparse (&optional force)
10467 "Re-parse current buffer after user finishes some data entry.
10468 If we get any user input while parsing, including cursor motion,
10469 we discard the parse and reschedule it. If FORCE is nil, then the
10470 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10471 (let (time
10472 interrupted-p
10473 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10474 (unless js2-mode-parsing
10475 (setq js2-mode-parsing t)
10476 (unwind-protect
10477 (when (or js2-mode-buffer-dirty-p force)
10478 (js2-remove-overlays)
10479 (with-silent-modifications
10480 (setq js2-mode-buffer-dirty-p nil
10481 js2-mode-fontifications nil
10482 js2-mode-deferred-properties nil)
10483 (if js2-mode-verbose-parse-p
10484 (message "parsing..."))
10485 (setq time
10486 (js2-time
10487 (setq interrupted-p
10488 (catch 'interrupted
10489 (js2-parse)
10490 ;; if parsing is interrupted, comments and regex
10491 ;; literals stay ignored by `parse-partial-sexp'
10492 (remove-text-properties (point-min) (point-max)
10493 '(syntax-table))
10494 (js2-mode-apply-deferred-properties)
10495 (js2-mode-remove-suppressed-warnings)
10496 (js2-mode-show-warnings)
10497 (js2-mode-show-errors)
10498 (if (>= js2-highlight-level 1)
10499 (js2-highlight-jsdoc js2-mode-ast))
10500 nil))))
10501 (if interrupted-p
10502 (progn
10503 ;; unfinished parse => try again
10504 (setq js2-mode-buffer-dirty-p t)
10505 (js2-mode-reset-timer))
10506 (if js2-mode-verbose-parse-p
10507 (message "Parse time: %s" time)))))
10508 (setq js2-mode-parsing nil)
10509 (unless interrupted-p
10510 (setq js2-mode-parse-timer nil))))))
10511
10512 (defun js2-mode-show-node (event)
10513 "Debugging aid: highlight selected AST node on mouse click."
10514 (interactive "e")
10515 (mouse-set-point event)
10516 (setq deactivate-mark t)
10517 (when js2-mode-show-overlay
10518 (let ((node (js2-node-at-point))
10519 beg end)
10520 (if (null node)
10521 (message "No node found at location %s" (point))
10522 (setq beg (js2-node-abs-pos node)
10523 end (+ beg (js2-node-len node)))
10524 (if js2-mode-node-overlay
10525 (move-overlay js2-mode-node-overlay beg end)
10526 (setq js2-mode-node-overlay (make-overlay beg end))
10527 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10528 (with-silent-modifications
10529 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10530 (message "%s, parent: %s"
10531 (js2-node-short-name node)
10532 (if (js2-node-parent node)
10533 (js2-node-short-name (js2-node-parent node))
10534 "nil"))))))
10535
10536 (defun js2-mode-hide-overlay (&optional _p1 p2)
10537 "Remove the debugging overlay when the point moves.
10538 P1 and P2 are the old and new values of point, respectively."
10539 (when js2-mode-node-overlay
10540 (let ((beg (overlay-start js2-mode-node-overlay))
10541 (end (overlay-end js2-mode-node-overlay)))
10542 ;; Sometimes we're called spuriously.
10543 (unless (and p2
10544 (>= p2 beg)
10545 (<= p2 end))
10546 (with-silent-modifications
10547 (remove-text-properties beg end '(point-left nil)))
10548 (delete-overlay js2-mode-node-overlay)
10549 (setq js2-mode-node-overlay nil)))))
10550
10551 (defun js2-mode-reset ()
10552 "Debugging helper: reset everything."
10553 (interactive)
10554 (js2-mode-exit)
10555 (js2-mode))
10556
10557 (defun js2-mode-show-warn-or-err (e face)
10558 "Highlight a warning or error E with FACE.
10559 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10560 The last element is optional. When present, use instead of FACE."
10561 (let* ((key (first e))
10562 (beg (second e))
10563 (end (+ beg (third e)))
10564 ;; Don't inadvertently go out of bounds.
10565 (beg (max (point-min) (min beg (point-max))))
10566 (end (max (point-min) (min end (point-max))))
10567 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10568 (ovl (make-overlay beg end)))
10569 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10570 (overlay-put ovl 'js2-error t)
10571 (put-text-property beg end 'help-echo (js2-get-msg key))
10572 (put-text-property beg end 'point-entered #'js2-echo-error)))
10573
10574 (defun js2-remove-overlays ()
10575 "Remove overlays from buffer that have a `js2-error' property."
10576 (let ((beg (point-min))
10577 (end (point-max)))
10578 (save-excursion
10579 (dolist (o (overlays-in beg end))
10580 (when (overlay-get o 'js2-error)
10581 (delete-overlay o))))))
10582
10583 (defun js2-error-at-point (&optional pos)
10584 "Return non-nil if there's an error overlay at POS.
10585 Defaults to point."
10586 (loop with pos = (or pos (point))
10587 for o in (overlays-at pos)
10588 thereis (overlay-get o 'js2-error)))
10589
10590 (defun js2-mode-apply-deferred-properties ()
10591 "Apply fontifications and other text properties recorded during parsing."
10592 (when (plusp js2-highlight-level)
10593 ;; We defer clearing faces as long as possible to eliminate flashing.
10594 (js2-clear-face (point-min) (point-max))
10595 ;; Have to reverse the recorded fontifications list so that errors
10596 ;; and warnings overwrite the normal fontifications.
10597 (dolist (f (nreverse js2-mode-fontifications))
10598 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10599 (setq js2-mode-fontifications nil))
10600 (dolist (p js2-mode-deferred-properties)
10601 (apply #'put-text-property p))
10602 (setq js2-mode-deferred-properties nil))
10603
10604 (defun js2-mode-show-errors ()
10605 "Highlight syntax errors."
10606 (when js2-mode-show-parse-errors
10607 (dolist (e (js2-ast-root-errors js2-mode-ast))
10608 (js2-mode-show-warn-or-err e 'js2-error))))
10609
10610 (defun js2-mode-remove-suppressed-warnings ()
10611 "Take suppressed warnings out of the AST warnings list.
10612 This ensures that the counts and `next-error' are correct."
10613 (setf (js2-ast-root-warnings js2-mode-ast)
10614 (js2-delete-if
10615 (lambda (e)
10616 (let ((key (caar e)))
10617 (or
10618 (and (not js2-strict-trailing-comma-warning)
10619 (string-match "trailing\\.comma" key))
10620 (and (not js2-strict-cond-assign-warning)
10621 (string= key "msg.equal.as.assign"))
10622 (and js2-missing-semi-one-line-override
10623 (string= key "msg.missing.semi")
10624 (let* ((beg (second e))
10625 (node (js2-node-at-point beg))
10626 (fn (js2-mode-find-parent-fn node))
10627 (body (and fn (js2-function-node-body fn)))
10628 (lc (and body (js2-node-abs-pos body)))
10629 (rc (and lc (+ lc (js2-node-len body)))))
10630 (and fn
10631 (or (null body)
10632 (save-excursion
10633 (goto-char beg)
10634 (and (js2-same-line lc)
10635 (js2-same-line rc))))))))))
10636 (js2-ast-root-warnings js2-mode-ast))))
10637
10638 (defun js2-mode-show-warnings ()
10639 "Highlight strict-mode warnings."
10640 (when js2-mode-show-strict-warnings
10641 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10642 (js2-mode-show-warn-or-err e 'js2-warning))))
10643
10644 (defun js2-echo-error (_old-point new-point)
10645 "Called by point-motion hooks."
10646 (let ((msg (get-text-property new-point 'help-echo)))
10647 (when (and (stringp msg)
10648 (not (active-minibuffer-window))
10649 (not (current-message)))
10650 (message msg))))
10651
10652 (defalias 'js2-echo-help #'js2-echo-error)
10653
10654 (defun js2-line-break (&optional _soft)
10655 "Break line at point and indent, continuing comment if within one.
10656 If inside a string, and `js2-concat-multiline-strings' is not
10657 nil, turn it into concatenation."
10658 (interactive)
10659 (let ((parse-status (syntax-ppss)))
10660 (cond
10661 ;; Check if we're inside a string.
10662 ((nth 3 parse-status)
10663 (if js2-concat-multiline-strings
10664 (js2-mode-split-string parse-status)
10665 (insert "\n")))
10666 ;; Check if inside a block comment.
10667 ((nth 4 parse-status)
10668 (js2-mode-extend-comment (nth 8 parse-status)))
10669 (t
10670 (newline-and-indent)))))
10671
10672 (defun js2-mode-split-string (parse-status)
10673 "Turn a newline in mid-string into a string concatenation.
10674 PARSE-STATUS is as documented in `parse-partial-sexp'."
10675 (let* ((quote-char (nth 3 parse-status))
10676 (at-eol (eq js2-concat-multiline-strings 'eol)))
10677 (insert quote-char)
10678 (insert (if at-eol " +\n" "\n"))
10679 (unless at-eol
10680 (insert "+ "))
10681 (js2-indent-line)
10682 (insert quote-char)
10683 (when (eolp)
10684 (insert quote-char)
10685 (backward-char 1))))
10686
10687 (defun js2-mode-extend-comment (start-pos)
10688 "Indent the line and, when inside a comment block, add comment prefix."
10689 (let (star single col first-line needs-close)
10690 (save-excursion
10691 (back-to-indentation)
10692 (when (< (point) start-pos)
10693 (goto-char start-pos))
10694 (cond
10695 ((looking-at "\\*[^/]")
10696 (setq star t
10697 col (current-column)))
10698 ((looking-at "/\\*")
10699 (setq star t
10700 first-line t
10701 col (1+ (current-column))))
10702 ((looking-at "//")
10703 (setq single t
10704 col (current-column)))))
10705 ;; Heuristic for whether we need to close the comment:
10706 ;; if we've got a parse error here, assume it's an unterminated
10707 ;; comment.
10708 (setq needs-close
10709 (or
10710 (eq (get-text-property (1- (point)) 'point-entered)
10711 'js2-echo-error)
10712 ;; The heuristic above doesn't work well when we're
10713 ;; creating a comment and there's another one downstream,
10714 ;; as our parser thinks this one ends at the end of the
10715 ;; next one. (You can have a /* inside a js block comment.)
10716 ;; So just close it if the next non-ws char isn't a *.
10717 (and first-line
10718 (eolp)
10719 (save-excursion
10720 (skip-chars-forward " \t\r\n")
10721 (not (eq (char-after) ?*))))))
10722 (delete-horizontal-space)
10723 (insert "\n")
10724 (cond
10725 (star
10726 (indent-to col)
10727 (insert "* ")
10728 (if (and first-line needs-close)
10729 (save-excursion
10730 (insert "\n")
10731 (indent-to col)
10732 (insert "*/"))))
10733 ((and single
10734 (save-excursion
10735 (and (zerop (forward-line 1))
10736 (looking-at "\\s-*//"))))
10737 (indent-to col)
10738 (insert "// ")))
10739 ;; Don't need to extend the comment after all.
10740 (js2-indent-line)))
10741
10742 (defun js2-beginning-of-line ()
10743 "Toggle point between bol and first non-whitespace char in line.
10744 Also moves past comment delimiters when inside comments."
10745 (interactive)
10746 (let (node)
10747 (cond
10748 ((bolp)
10749 (back-to-indentation))
10750 ((looking-at "//")
10751 (skip-chars-forward "/ \t"))
10752 ((and (eq (char-after) ?*)
10753 (setq node (js2-comment-at-point))
10754 (memq (js2-comment-node-format node) '(jsdoc block))
10755 (save-excursion
10756 (skip-chars-backward " \t")
10757 (bolp)))
10758 (skip-chars-forward "\* \t"))
10759 (t
10760 (goto-char (point-at-bol))))))
10761
10762 (defun js2-end-of-line ()
10763 "Toggle point between eol and last non-whitespace char in line."
10764 (interactive)
10765 (if (eolp)
10766 (skip-chars-backward " \t")
10767 (goto-char (point-at-eol))))
10768
10769 (defun js2-mode-wait-for-parse (callback)
10770 "Invoke CALLBACK when parsing is finished.
10771 If parsing is already finished, calls CALLBACK immediately."
10772 (if (not js2-mode-buffer-dirty-p)
10773 (funcall callback)
10774 (push callback js2-mode-pending-parse-callbacks)
10775 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10776
10777 (defun js2-mode-parse-finished ()
10778 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10779 ;; We can't let errors propagate up, since it prevents the
10780 ;; `js2-parse' method from completing normally and returning
10781 ;; the ast, which makes things mysteriously not work right.
10782 (unwind-protect
10783 (dolist (cb js2-mode-pending-parse-callbacks)
10784 (condition-case err
10785 (funcall cb)
10786 (error (message "%s" err))))
10787 (setq js2-mode-pending-parse-callbacks nil)))
10788
10789 (defun js2-mode-flag-region (from to flag)
10790 "Hide or show text from FROM to TO, according to FLAG.
10791 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10792 Returns the created overlay if FLAG is non-nil."
10793 (remove-overlays from to 'invisible 'js2-outline)
10794 (when flag
10795 (let ((o (make-overlay from to)))
10796 (overlay-put o 'invisible 'js2-outline)
10797 (overlay-put o 'isearch-open-invisible
10798 'js2-isearch-open-invisible)
10799 o)))
10800
10801 ;; Function to be set as an outline-isearch-open-invisible' property
10802 ;; to the overlay that makes the outline invisible (see
10803 ;; `js2-mode-flag-region').
10804 (defun js2-isearch-open-invisible (_overlay)
10805 ;; We rely on the fact that isearch places point on the matched text.
10806 (js2-mode-show-element))
10807
10808 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10809 "Return cons cell of bounds of folding overlay at POS.
10810 Returns nil if not found."
10811 (let ((overlays (overlays-at (or pos (point))))
10812 o)
10813 (while (and overlays
10814 (not o))
10815 (if (overlay-get (car overlays) 'invisible)
10816 (setq o (car overlays))
10817 (setq overlays (cdr overlays))))
10818 (if o
10819 (cons (overlay-start o) (overlay-end o)))))
10820
10821 (defun js2-mode-function-at-point (&optional pos)
10822 "Return the innermost function node enclosing current point.
10823 Returns nil if point is not in a function."
10824 (let ((node (js2-node-at-point pos)))
10825 (while (and node (not (js2-function-node-p node)))
10826 (setq node (js2-node-parent node)))
10827 (if (js2-function-node-p node)
10828 node)))
10829
10830 (defun js2-mode-toggle-element ()
10831 "Hide or show the foldable element at the point."
10832 (interactive)
10833 (let (comment fn pos)
10834 (save-excursion
10835 (cond
10836 ;; /* ... */ comment?
10837 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10838 (if (js2-mode-invisible-overlay-bounds
10839 (setq pos (+ 3 (js2-node-abs-pos comment))))
10840 (progn
10841 (goto-char pos)
10842 (js2-mode-show-element))
10843 (js2-mode-hide-element)))
10844 ;; //-comment?
10845 ((save-excursion
10846 (back-to-indentation)
10847 (looking-at js2-mode-//-comment-re))
10848 (js2-mode-toggle-//-comment))
10849 ;; function?
10850 ((setq fn (js2-mode-function-at-point))
10851 (setq pos (and (js2-function-node-body fn)
10852 (js2-node-abs-pos (js2-function-node-body fn))))
10853 (goto-char (1+ pos))
10854 (if (js2-mode-invisible-overlay-bounds)
10855 (js2-mode-show-element)
10856 (js2-mode-hide-element)))
10857 (t
10858 (message "Nothing at point to hide or show"))))))
10859
10860 (defun js2-mode-hide-element ()
10861 "Fold/hide contents of a block, showing ellipses.
10862 Show the hidden text with \\[js2-mode-show-element]."
10863 (interactive)
10864 (if js2-mode-buffer-dirty-p
10865 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10866 (let (node body beg end)
10867 (cond
10868 ((js2-mode-invisible-overlay-bounds)
10869 (message "already hidden"))
10870 (t
10871 (setq node (js2-node-at-point))
10872 (cond
10873 ((js2-block-comment-p node)
10874 (js2-mode-hide-comment node))
10875 (t
10876 (while (and node (not (js2-function-node-p node)))
10877 (setq node (js2-node-parent node)))
10878 (if (and node
10879 (setq body (js2-function-node-body node)))
10880 (progn
10881 (setq beg (js2-node-abs-pos body)
10882 end (+ beg (js2-node-len body)))
10883 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10884 (message "No collapsable element found at point"))))))))
10885
10886 (defun js2-mode-show-element ()
10887 "Show the hidden element at current point."
10888 (interactive)
10889 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10890 (if bounds
10891 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
10892 (message "Nothing to un-hide"))))
10893
10894 (defun js2-mode-show-all ()
10895 "Show all of the text in the buffer."
10896 (interactive)
10897 (js2-mode-flag-region (point-min) (point-max) nil))
10898
10899 (defun js2-mode-toggle-hide-functions ()
10900 (interactive)
10901 (if js2-mode-functions-hidden
10902 (js2-mode-show-functions)
10903 (js2-mode-hide-functions)))
10904
10905 (defun js2-mode-hide-functions ()
10906 "Hides all non-nested function bodies in the buffer.
10907 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10908 to open an individual entry."
10909 (interactive)
10910 (if js2-mode-buffer-dirty-p
10911 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
10912 (if (null js2-mode-ast)
10913 (message "Oops - parsing failed")
10914 (setq js2-mode-functions-hidden t)
10915 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
10916
10917 (defun js2-mode-function-hider (n endp)
10918 (when (not endp)
10919 (let ((tt (js2-node-type n))
10920 body beg end)
10921 (cond
10922 ((and (= tt js2-FUNCTION)
10923 (setq body (js2-function-node-body n)))
10924 (setq beg (js2-node-abs-pos body)
10925 end (+ beg (js2-node-len body)))
10926 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
10927 nil) ; don't process children of function
10928 (t
10929 t))))) ; keep processing other AST nodes
10930
10931 (defun js2-mode-show-functions ()
10932 "Un-hide any folded function bodies in the buffer."
10933 (interactive)
10934 (setq js2-mode-functions-hidden nil)
10935 (save-excursion
10936 (goto-char (point-min))
10937 (while (/= (goto-char (next-overlay-change (point)))
10938 (point-max))
10939 (dolist (o (overlays-at (point)))
10940 (when (and (overlay-get o 'invisible)
10941 (not (overlay-get o 'comment)))
10942 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10943
10944 (defun js2-mode-hide-comment (n)
10945 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
10946 3 ; /**
10947 2)) ; /*
10948 (beg (+ (js2-node-abs-pos n) head))
10949 (end (- (+ beg (js2-node-len n)) head 2))
10950 (o (js2-mode-flag-region beg end 'hide)))
10951 (overlay-put o 'comment t)))
10952
10953 (defun js2-mode-toggle-hide-comments ()
10954 "Folds all block comments in the buffer.
10955 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10956 to open an individual entry."
10957 (interactive)
10958 (if js2-mode-comments-hidden
10959 (js2-mode-show-comments)
10960 (js2-mode-hide-comments)))
10961
10962 (defun js2-mode-hide-comments ()
10963 (interactive)
10964 (if js2-mode-buffer-dirty-p
10965 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
10966 (if (null js2-mode-ast)
10967 (message "Oops - parsing failed")
10968 (setq js2-mode-comments-hidden t)
10969 (dolist (n (js2-ast-root-comments js2-mode-ast))
10970 (when (js2-block-comment-p n)
10971 (js2-mode-hide-comment n)))
10972 (js2-mode-hide-//-comments)))
10973
10974 (defun js2-mode-extend-//-comment (direction)
10975 "Find start or end of a block of similar //-comment lines.
10976 DIRECTION is -1 to look back, 1 to look forward.
10977 INDENT is the indentation level to match.
10978 Returns the end-of-line position of the furthest adjacent
10979 //-comment line with the same indentation as the current line.
10980 If there is no such matching line, returns current end of line."
10981 (let ((pos (point-at-eol))
10982 (indent (current-indentation)))
10983 (save-excursion
10984 (while (and (zerop (forward-line direction))
10985 (looking-at js2-mode-//-comment-re)
10986 (eq indent (length (match-string 1))))
10987 (setq pos (point-at-eol))
10988 pos))))
10989
10990 (defun js2-mode-hide-//-comments ()
10991 "Fold adjacent 1-line comments, showing only snippet of first one."
10992 (let (beg end)
10993 (save-excursion
10994 (goto-char (point-min))
10995 (while (re-search-forward js2-mode-//-comment-re nil t)
10996 (setq beg (point)
10997 end (js2-mode-extend-//-comment 1))
10998 (unless (eq beg end)
10999 (overlay-put (js2-mode-flag-region beg end 'hide)
11000 'comment t))
11001 (goto-char end)
11002 (forward-char 1)))))
11003
11004 (defun js2-mode-toggle-//-comment ()
11005 "Fold or un-fold any multi-line //-comment at point.
11006 Caller should have determined that this line starts with a //-comment."
11007 (let* ((beg (point-at-eol))
11008 (end beg))
11009 (save-excursion
11010 (goto-char end)
11011 (if (js2-mode-invisible-overlay-bounds)
11012 (js2-mode-show-element)
11013 ;; else hide the comment
11014 (setq beg (js2-mode-extend-//-comment -1)
11015 end (js2-mode-extend-//-comment 1))
11016 (unless (eq beg end)
11017 (overlay-put (js2-mode-flag-region beg end 'hide)
11018 'comment t))))))
11019
11020 (defun js2-mode-show-comments ()
11021 "Un-hide any hidden comments, leaving other hidden elements alone."
11022 (interactive)
11023 (setq js2-mode-comments-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 (overlay-get o 'comment)
11030 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11031
11032 (defun js2-mode-display-warnings-and-errors ()
11033 "Turn on display of warnings and errors."
11034 (interactive)
11035 (setq js2-mode-show-parse-errors t
11036 js2-mode-show-strict-warnings t)
11037 (js2-reparse 'force))
11038
11039 (defun js2-mode-hide-warnings-and-errors ()
11040 "Turn off display of warnings and errors."
11041 (interactive)
11042 (setq js2-mode-show-parse-errors nil
11043 js2-mode-show-strict-warnings nil)
11044 (js2-reparse 'force))
11045
11046 (defun js2-mode-toggle-warnings-and-errors ()
11047 "Toggle the display of warnings and errors.
11048 Some users don't like having warnings/errors reported while they type."
11049 (interactive)
11050 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11051 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11052 (if (called-interactively-p 'any)
11053 (message "warnings and errors %s"
11054 (if js2-mode-show-parse-errors
11055 "enabled"
11056 "disabled")))
11057 (js2-reparse 'force))
11058
11059 (defun js2-mode-customize ()
11060 (interactive)
11061 (customize-group 'js2-mode))
11062
11063 (defun js2-mode-forward-sexp (&optional arg)
11064 "Move forward across one statement or balanced expression.
11065 With ARG, do it that many times. Negative arg -N means
11066 move backward across N balanced expressions."
11067 (interactive "p")
11068 (setq arg (or arg 1))
11069 (save-restriction
11070 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11071 (js2-reparse)
11072 (let (forward-sexp-function
11073 node (start (point)) pos lp rp child)
11074 (cond
11075 ;; backward-sexp
11076 ;; could probably make this better for some cases:
11077 ;; - if in statement block (e.g. function body), go to parent
11078 ;; - infix exprs like (foo in bar) - maybe go to beginning
11079 ;; of infix expr if in the right-side expression?
11080 ((and arg (minusp arg))
11081 (dotimes (_ (- arg))
11082 (js2-backward-sws)
11083 (forward-char -1) ; Enter the node we backed up to.
11084 (when (setq node (js2-node-at-point (point) t))
11085 (setq pos (js2-node-abs-pos node))
11086 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11087 (setq lp (car parens)
11088 rp (cdr parens)))
11089 (when (and lp (> start lp))
11090 (if (and rp (<= start rp))
11091 ;; Between parens, check if there's a child node we can jump.
11092 (when (setq child (js2-node-closest-child node (point) lp t))
11093 (setq pos (js2-node-abs-pos child)))
11094 ;; Before both parens.
11095 (setq pos lp)))
11096 (let ((state (parse-partial-sexp start pos)))
11097 (goto-char (if (not (zerop (car state)))
11098 ;; Stumble at the unbalanced paren if < 0, or
11099 ;; jump a bit further if > 0.
11100 (scan-sexps start -1)
11101 pos))))
11102 (unless pos (goto-char (point-min)))))
11103 (t
11104 ;; forward-sexp
11105 (dotimes (_ arg)
11106 (js2-forward-sws)
11107 (when (setq node (js2-node-at-point (point) t))
11108 (setq pos (js2-node-abs-pos node))
11109 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11110 (setq lp (car parens)
11111 rp (cdr parens)))
11112 (or
11113 (when (and rp (<= start rp))
11114 (if (> start lp)
11115 (when (setq child (js2-node-closest-child node (point) rp))
11116 (setq pos (js2-node-abs-end child)))
11117 (setq pos (1+ rp))))
11118 ;; No parens or child nodes, looks for the end of the curren node.
11119 (incf pos (js2-node-len
11120 (if (js2-expr-stmt-node-p (js2-node-parent node))
11121 ;; Stop after the semicolon.
11122 (js2-node-parent node)
11123 node))))
11124 (let ((state (save-excursion (parse-partial-sexp start pos))))
11125 (goto-char (if (not (zerop (car state)))
11126 (scan-sexps start 1)
11127 pos))))
11128 (unless pos (goto-char (point-max)))))))))
11129
11130 (defun js2-mode-forward-sexp-parens (node abs-pos)
11131 "Return a cons cell with positions of main parens in NODE."
11132 (cond
11133 ((or (js2-array-node-p node)
11134 (js2-object-node-p node)
11135 (js2-array-comp-node-p node)
11136 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11137 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11138 ((js2-paren-expr-node-p node)
11139 (let ((lp (js2-node-lp node))
11140 (rp (js2-node-rp node)))
11141 (cons (when lp (+ abs-pos lp))
11142 (when rp (+ abs-pos rp)))))))
11143
11144 (defun js2-node-closest-child (parent point limit &optional before)
11145 (let* ((parent-pos (js2-node-abs-pos parent))
11146 (rpoint (- point parent-pos))
11147 (rlimit (- limit parent-pos))
11148 (min (min rpoint rlimit))
11149 (max (max rpoint rlimit))
11150 found)
11151 (catch 'done
11152 (js2-visit-ast
11153 parent
11154 (lambda (node _end-p)
11155 (if (eq node parent)
11156 t
11157 (let ((pos (js2-node-pos node)) ;; Both relative values.
11158 (end (+ (js2-node-pos node) (js2-node-len node))))
11159 (when (and (>= pos min) (<= end max)
11160 (if before (< pos rpoint) (> end rpoint)))
11161 (setq found node))
11162 (when (> end rpoint)
11163 (throw 'done nil)))
11164 nil))))
11165 found))
11166
11167 (defun js2-errors ()
11168 "Return a list of errors found."
11169 (and js2-mode-ast
11170 (js2-ast-root-errors js2-mode-ast)))
11171
11172 (defun js2-warnings ()
11173 "Return a list of warnings found."
11174 (and js2-mode-ast
11175 (js2-ast-root-warnings js2-mode-ast)))
11176
11177 (defun js2-have-errors-p ()
11178 "Return non-nil if any parse errors or warnings were found."
11179 (or (js2-errors) (js2-warnings)))
11180
11181 (defun js2-errors-and-warnings ()
11182 "Return a copy of the concatenated errors and warnings lists.
11183 They are appended: first the errors, then the warnings.
11184 Entries are of the form (MSG BEG END)."
11185 (when js2-mode-ast
11186 (append (js2-ast-root-errors js2-mode-ast)
11187 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11188
11189 (defun js2-next-error (&optional arg reset)
11190 "Move to next parse error.
11191 Typically invoked via \\[next-error].
11192 ARG is the number of errors, forward or backward, to move.
11193 RESET means start over from the beginning."
11194 (interactive "p")
11195 (if (not (or (js2-errors) (js2-warnings)))
11196 (message "No errors")
11197 (when reset
11198 (goto-char (point-min)))
11199 (let* ((errs (js2-errors-and-warnings))
11200 (continue t)
11201 (start (point))
11202 (count (or arg 1))
11203 (backward (minusp count))
11204 (sorter (if backward '> '<))
11205 (stopper (if backward '< '>))
11206 (count (abs count))
11207 all-errs err)
11208 ;; Sort by start position.
11209 (setq errs (sort errs (lambda (e1 e2)
11210 (funcall sorter (second e1) (second e2))))
11211 all-errs errs)
11212 ;; Find nth error with pos > start.
11213 (while (and errs continue)
11214 (when (funcall stopper (cadar errs) start)
11215 (setq err (car errs))
11216 (if (zerop (decf count))
11217 (setq continue nil)))
11218 (setq errs (cdr errs)))
11219 ;; Clear for `js2-echo-error'.
11220 (message nil)
11221 (if err
11222 (goto-char (second err))
11223 ;; Wrap around to first error.
11224 (goto-char (second (car all-errs)))
11225 ;; If we were already on it, echo msg again.
11226 (if (= (point) start)
11227 (js2-echo-error (point) (point)))))))
11228
11229 (defun js2-down-mouse-3 ()
11230 "Make right-click move the point to the click location.
11231 This makes right-click context menu operations a bit more intuitive.
11232 The point will not move if the region is active, however, to avoid
11233 destroying the region selection."
11234 (interactive)
11235 (when (and js2-move-point-on-right-click
11236 (not mark-active))
11237 (let ((e last-input-event))
11238 (ignore-errors
11239 (goto-char (cadadr e))))))
11240
11241 (defun js2-mode-create-imenu-index ()
11242 "Return an alist for `imenu--index-alist'."
11243 ;; This is built up in `js2-parse-record-imenu' during parsing.
11244 (when js2-mode-ast
11245 ;; if we have an ast but no recorder, they're requesting a rescan
11246 (unless js2-imenu-recorder
11247 (js2-reparse 'force))
11248 (prog1
11249 (js2-build-imenu-index)
11250 (setq js2-imenu-recorder nil
11251 js2-imenu-function-map nil))))
11252
11253 (defun js2-mode-find-tag ()
11254 "Replacement for `find-tag-default'.
11255 `find-tag-default' returns a ridiculous answer inside comments."
11256 (let (beg end)
11257 (js2-with-underscore-as-word-syntax
11258 (save-excursion
11259 (if (and (not (looking-at "[[:alnum:]_$]"))
11260 (looking-back "[[:alnum:]_$]"))
11261 (setq beg (progn (forward-word -1) (point))
11262 end (progn (forward-word 1) (point)))
11263 (setq beg (progn (forward-word 1) (point))
11264 end (progn (forward-word -1) (point))))
11265 (replace-regexp-in-string
11266 "[\"']" ""
11267 (buffer-substring-no-properties beg end))))))
11268
11269 (defun js2-mode-forward-sibling ()
11270 "Move to the end of the sibling following point in parent.
11271 Returns non-nil if successful, or nil if there was no following sibling."
11272 (let* ((node (js2-node-at-point))
11273 (parent (js2-mode-find-enclosing-fn node))
11274 sib)
11275 (when (setq sib (js2-node-find-child-after (point) parent))
11276 (goto-char (+ (js2-node-abs-pos sib)
11277 (js2-node-len sib))))))
11278
11279 (defun js2-mode-backward-sibling ()
11280 "Move to the beginning of the sibling node preceding point in parent.
11281 Parent is defined as the enclosing script or function."
11282 (let* ((node (js2-node-at-point))
11283 (parent (js2-mode-find-enclosing-fn node))
11284 sib)
11285 (when (setq sib (js2-node-find-child-before (point) parent))
11286 (goto-char (js2-node-abs-pos sib)))))
11287
11288 (defun js2-beginning-of-defun (&optional arg)
11289 "Go to line on which current function starts, and return t on success.
11290 If we're not in a function or already at the beginning of one, go
11291 to beginning of previous script-level element.
11292 With ARG N, do that N times. If N is negative, move forward."
11293 (setq arg (or arg 1))
11294 (if (plusp arg)
11295 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11296 (when (cond
11297 ((js2-function-node-p parent)
11298 (goto-char (js2-node-abs-pos parent)))
11299 (t
11300 (js2-mode-backward-sibling)))
11301 (if (> arg 1)
11302 (js2-beginning-of-defun (1- arg))
11303 t)))
11304 (when (js2-end-of-defun)
11305 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
11306
11307 (defun js2-end-of-defun ()
11308 "Go to the char after the last position of the current function
11309 or script-level element."
11310 (let* ((node (js2-node-at-point))
11311 (parent (or (and (js2-function-node-p node) node)
11312 (js2-node-parent-script-or-fn node)))
11313 script)
11314 (unless (js2-function-node-p parent)
11315 ;; Use current script-level node, or, if none, the next one.
11316 (setq script (or parent node)
11317 parent (js2-node-find-child-before (point) script))
11318 (when (or (null parent)
11319 (>= (point) (+ (js2-node-abs-pos parent)
11320 (js2-node-len parent))))
11321 (setq parent (js2-node-find-child-after (point) script))))
11322 (when parent
11323 (goto-char (+ (js2-node-abs-pos parent)
11324 (js2-node-len parent))))))
11325
11326 (defun js2-mark-defun (&optional allow-extend)
11327 "Put mark at end of this function, point at beginning.
11328 The function marked is the one that contains point.
11329
11330 Interactively, if this command is repeated,
11331 or (in Transient Mark mode) if the mark is active,
11332 it marks the next defun after the ones already marked."
11333 (interactive "p")
11334 (let (extended)
11335 (when (and allow-extend
11336 (or (and (eq last-command this-command) (mark t))
11337 (and transient-mark-mode mark-active)))
11338 (let ((sib (save-excursion
11339 (goto-char (mark))
11340 (if (js2-mode-forward-sibling)
11341 (point)))))
11342 (if sib
11343 (progn
11344 (set-mark sib)
11345 (setq extended t))
11346 ;; no more siblings - try extending to enclosing node
11347 (goto-char (mark t)))))
11348 (when (not extended)
11349 (let ((node (js2-node-at-point (point) t)) ; skip comments
11350 ast fn stmt parent beg end)
11351 (when (js2-ast-root-p node)
11352 (setq ast node
11353 node (or (js2-node-find-child-after (point) node)
11354 (js2-node-find-child-before (point) node))))
11355 ;; only mark whole buffer if we can't find any children
11356 (if (null node)
11357 (setq node ast))
11358 (if (js2-function-node-p node)
11359 (setq parent node)
11360 (setq fn (js2-mode-find-enclosing-fn node)
11361 stmt (if (or (null fn)
11362 (js2-ast-root-p fn))
11363 (js2-mode-find-first-stmt node))
11364 parent (or stmt fn)))
11365 (setq beg (js2-node-abs-pos parent)
11366 end (+ beg (js2-node-len parent)))
11367 (push-mark beg)
11368 (goto-char end)
11369 (exchange-point-and-mark)))))
11370
11371 (defun js2-narrow-to-defun ()
11372 "Narrow to the function enclosing point."
11373 (interactive)
11374 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11375 (fn (if (js2-script-node-p node)
11376 node
11377 (js2-mode-find-enclosing-fn node)))
11378 (beg (js2-node-abs-pos fn)))
11379 (unless (js2-ast-root-p fn)
11380 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11381
11382 (provide 'js2-mode)
11383
11384 ;;; js2-mode.el ends here