]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Bump the version date
[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: 20130510
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 ;; Alternately, 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 is mentioned here for posterity, it has
84 ;; outdated information and is mostly 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-idle-timer-delay 0.2
275 "Delay in secs before re-parsing after user makes changes.
276 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
277 :type 'number
278 :group 'js2-mode)
279 (make-variable-buffer-local 'js2-idle-timer-delay)
280
281 (defcustom js2-dynamic-idle-timer-adjust 0
282 "Positive to adjust `js2-idle-timer-delay' based on file size.
283 The idea is that for short files, parsing is faster so we can be
284 more responsive to user edits without interfering with editing.
285 The buffer length in characters (typically bytes) is divided by
286 this value and used to multiply `js2-idle-timer-delay' for the
287 buffer. For example, a 21k file and 10k adjust yields 21k/10k
288 == 2, so js2-idle-timer-delay is multiplied by 2.
289 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
290 `js2-idle-timer-delay' is not dependent on the file size."
291 :type 'number
292 :group 'js2-mode)
293
294 (defcustom js2-concat-multiline-strings t
295 "Non-nil to automatically turn a newline in mid-string into a
296 string concatenation. When `eol', the '+' will be inserted at the
297 end of the line, otherwise, at the beginning of the next line."
298 :type '(choice (const t) (const eol) (const nil))
299 :group 'js2-mode)
300
301 (defcustom js2-mode-show-parse-errors t
302 "True to highlight parse errors."
303 :type 'boolean
304 :group 'js2-mode)
305
306 (defcustom js2-mode-show-strict-warnings t
307 "Non-nil to emit Ecma strict-mode warnings.
308 Some of the warnings can be individually disabled by other flags,
309 even if this flag is non-nil."
310 :type 'boolean
311 :group 'js2-mode)
312
313 (defcustom js2-strict-trailing-comma-warning t
314 "Non-nil to warn about trailing commas in array literals.
315 Ecma-262-5.1 allows them, but older versions of IE raise an error."
316 :type 'boolean
317 :group 'js2-mode)
318
319 (defcustom js2-strict-missing-semi-warning t
320 "Non-nil to warn about semicolon auto-insertion after statement.
321 Technically this is legal per Ecma-262, but some style guides disallow
322 depending on it."
323 :type 'boolean
324 :group 'js2-mode)
325
326 (defcustom js2-missing-semi-one-line-override nil
327 "Non-nil to permit missing semicolons in one-line functions.
328 In one-liner functions such as `function identity(x) {return x}'
329 people often omit the semicolon for a cleaner look. If you are
330 such a person, you can suppress the missing-semicolon warning
331 by setting this variable to t."
332 :type 'boolean
333 :group 'js2-mode)
334
335 (defcustom js2-strict-inconsistent-return-warning t
336 "Non-nil to warn about mixing returns with value-returns.
337 It's perfectly legal to have a `return' and a `return foo' in the
338 same function, but it's often an indicator of a bug, and it also
339 interferes with type inference (in systems that support it.)"
340 :type 'boolean
341 :group 'js2-mode)
342
343 (defcustom js2-strict-cond-assign-warning t
344 "Non-nil to warn about expressions like if (a = b).
345 This often should have been '==' instead of '='. If the warning
346 is enabled, you can suppress it on a per-expression basis by
347 parenthesizing the expression, e.g. if ((a = b)) ..."
348 :type 'boolean
349 :group 'js2-mode)
350
351 (defcustom js2-strict-var-redeclaration-warning t
352 "Non-nil to warn about redeclaring variables in a script or function."
353 :type 'boolean
354 :group 'js2-mode)
355
356 (defcustom js2-strict-var-hides-function-arg-warning t
357 "Non-nil to warn about a var decl hiding a function argument."
358 :type 'boolean
359 :group 'js2-mode)
360
361 (defcustom js2-skip-preprocessor-directives nil
362 "Non-nil to treat lines beginning with # as comments.
363 Useful for viewing Mozilla JavaScript source code."
364 :type 'boolean
365 :group 'js2-mode)
366
367 (defcustom js2-language-version 200
368 "Configures what JavaScript language version to recognize.
369 Currently versions 150, 160, 170, 180 and 200 are supported,
370 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
371 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
372 yield, and Array comprehensions, and 1.8 adds function closures."
373 :type 'integer
374 :group 'js2-mode)
375
376 (defcustom js2-allow-keywords-as-property-names t
377 "If non-nil, you can use JavaScript keywords as object property names.
378 Examples:
379
380 var foo = {int: 5, while: 6, continue: 7};
381 foo.return = 8;
382
383 Ecma-262 5.1 allows this syntax, but some engines still don't."
384 :type 'boolean
385 :group 'js2-mode)
386
387 (defcustom js2-instanceof-has-side-effects nil
388 "If non-nil, treats the instanceof operator as having side effects.
389 This is useful for xulrunner apps."
390 :type 'boolean
391 :group 'js2-mode)
392
393 (defcustom js2-move-point-on-right-click t
394 "Non-nil to move insertion point when you right-click.
395 This makes right-click context menu behavior a bit more intuitive,
396 since menu operations generally apply to the point. The exception
397 is if there is a region selection, in which case the point does -not-
398 move, so cut/copy/paste can work properly.
399
400 Note that IntelliJ moves the point, and Eclipse leaves it alone,
401 so this behavior is customizable."
402 :group 'js2-mode
403 :type 'boolean)
404
405 (defcustom js2-allow-rhino-new-expr-initializer t
406 "Non-nil to support a Rhino's experimental syntactic construct.
407
408 Rhino supports the ability to follow a `new' expression with an object
409 literal, which is used to set additional properties on the new object
410 after calling its constructor. Syntax:
411
412 new <expr> [ ( arglist ) ] [initializer]
413
414 Hence, this expression:
415
416 new Object {a: 1, b: 2}
417
418 results in an Object with properties a=1 and b=2. This syntax is
419 apparently not configurable in Rhino - it's currently always enabled,
420 as of Rhino version 1.7R2."
421 :type 'boolean
422 :group 'js2-mode)
423
424 (defcustom js2-allow-member-expr-as-function-name nil
425 "Non-nil to support experimental Rhino syntax for function names.
426
427 Rhino supports an experimental syntax configured via the Rhino Context
428 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
429
430 function <member-expr> ( [ arg-list ] ) { <body> }
431
432 Where member-expr is a non-parenthesized 'member expression', which
433 is anything at the grammar level of a new-expression or lower, meaning
434 any expression that does not involve infix or unary operators.
435
436 When <member-expr> is not a simple identifier, then it is syntactic
437 sugar for assigning the anonymous function to the <member-expr>. Hence,
438 this code:
439
440 function a.b().c[2] (x, y) { ... }
441
442 is rewritten as:
443
444 a.b().c[2] = function(x, y) {...}
445
446 which doesn't seem particularly useful, but Rhino permits it."
447 :type 'boolean
448 :group 'js2-mode)
449
450 ;; scanner variables
451
452 (defmacro js2-deflocal (name value &optional comment)
453 "Define a buffer-local variable NAME with VALUE and COMMENT."
454 `(progn
455 (defvar ,name ,value ,comment)
456 (make-variable-buffer-local ',name)))
457
458 ;; We record the start and end position of each token.
459 (js2-deflocal js2-token-beg 1)
460 (js2-deflocal js2-token-end -1)
461
462 (defvar js2-EOF_CHAR -1
463 "Represents end of stream. Distinct from js2-EOF token type.")
464
465 ;; I originally used symbols to represent tokens, but Rhino uses
466 ;; ints and then sets various flag bits in them, so ints it is.
467 ;; The upshot is that we need a `js2-' prefix in front of each name.
468 (defvar js2-ERROR -1)
469 (defvar js2-EOF 0)
470 (defvar js2-EOL 1)
471 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
472 (defvar js2-LEAVEWITH 3)
473 (defvar js2-RETURN 4)
474 (defvar js2-GOTO 5)
475 (defvar js2-IFEQ 6)
476 (defvar js2-IFNE 7)
477 (defvar js2-SETNAME 8)
478 (defvar js2-BITOR 9)
479 (defvar js2-BITXOR 10)
480 (defvar js2-BITAND 11)
481 (defvar js2-EQ 12)
482 (defvar js2-NE 13)
483 (defvar js2-LT 14)
484 (defvar js2-LE 15)
485 (defvar js2-GT 16)
486 (defvar js2-GE 17)
487 (defvar js2-LSH 18)
488 (defvar js2-RSH 19)
489 (defvar js2-URSH 20)
490 (defvar js2-ADD 21) ; infix plus
491 (defvar js2-SUB 22) ; infix minus
492 (defvar js2-MUL 23)
493 (defvar js2-DIV 24)
494 (defvar js2-MOD 25)
495 (defvar js2-NOT 26)
496 (defvar js2-BITNOT 27)
497 (defvar js2-POS 28) ; unary plus
498 (defvar js2-NEG 29) ; unary minus
499 (defvar js2-NEW 30)
500 (defvar js2-DELPROP 31)
501 (defvar js2-TYPEOF 32)
502 (defvar js2-GETPROP 33)
503 (defvar js2-GETPROPNOWARN 34)
504 (defvar js2-SETPROP 35)
505 (defvar js2-GETELEM 36)
506 (defvar js2-SETELEM 37)
507 (defvar js2-CALL 38)
508 (defvar js2-NAME 39) ; an identifier
509 (defvar js2-NUMBER 40)
510 (defvar js2-STRING 41)
511 (defvar js2-NULL 42)
512 (defvar js2-THIS 43)
513 (defvar js2-FALSE 44)
514 (defvar js2-TRUE 45)
515 (defvar js2-SHEQ 46) ; shallow equality (===)
516 (defvar js2-SHNE 47) ; shallow inequality (!==)
517 (defvar js2-REGEXP 48)
518 (defvar js2-BINDNAME 49)
519 (defvar js2-THROW 50)
520 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
521 (defvar js2-IN 52)
522 (defvar js2-INSTANCEOF 53)
523 (defvar js2-LOCAL_LOAD 54)
524 (defvar js2-GETVAR 55)
525 (defvar js2-SETVAR 56)
526 (defvar js2-CATCH_SCOPE 57)
527 (defvar js2-ENUM_INIT_KEYS 58)
528 (defvar js2-ENUM_INIT_VALUES 59)
529 (defvar js2-ENUM_INIT_ARRAY 60)
530 (defvar js2-ENUM_NEXT 61)
531 (defvar js2-ENUM_ID 62)
532 (defvar js2-THISFN 63)
533 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
534 (defvar js2-ARRAYLIT 65) ; array literal
535 (defvar js2-OBJECTLIT 66) ; object literal
536 (defvar js2-GET_REF 67) ; *reference
537 (defvar js2-SET_REF 68) ; *reference = something
538 (defvar js2-DEL_REF 69) ; delete reference
539 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
540 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
541 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
542
543 ;; XML support
544 (defvar js2-DEFAULTNAMESPACE 73)
545 (defvar js2-ESCXMLATTR 74)
546 (defvar js2-ESCXMLTEXT 75)
547 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
548 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
549 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
550 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
551
552 (defvar js2-first-bytecode js2-ENTERWITH)
553 (defvar js2-last-bytecode js2-REF_NS_NAME)
554
555 (defvar js2-TRY 80)
556 (defvar js2-SEMI 81) ; semicolon
557 (defvar js2-LB 82) ; left and right brackets
558 (defvar js2-RB 83)
559 (defvar js2-LC 84) ; left and right curly-braces
560 (defvar js2-RC 85)
561 (defvar js2-LP 86) ; left and right parens
562 (defvar js2-RP 87)
563 (defvar js2-COMMA 88) ; comma operator
564
565 (defvar js2-ASSIGN 89) ; simple assignment (=)
566 (defvar js2-ASSIGN_BITOR 90) ; |=
567 (defvar js2-ASSIGN_BITXOR 91) ; ^=
568 (defvar js2-ASSIGN_BITAND 92) ; &=
569 (defvar js2-ASSIGN_LSH 93) ; <<=
570 (defvar js2-ASSIGN_RSH 94) ; >>=
571 (defvar js2-ASSIGN_URSH 95) ; >>>=
572 (defvar js2-ASSIGN_ADD 96) ; +=
573 (defvar js2-ASSIGN_SUB 97) ; -=
574 (defvar js2-ASSIGN_MUL 98) ; *=
575 (defvar js2-ASSIGN_DIV 99) ; /=
576 (defvar js2-ASSIGN_MOD 100) ; %=
577
578 (defvar js2-first-assign js2-ASSIGN)
579 (defvar js2-last-assign js2-ASSIGN_MOD)
580
581 (defvar js2-HOOK 101) ; conditional (?:)
582 (defvar js2-COLON 102)
583 (defvar js2-OR 103) ; logical or (||)
584 (defvar js2-AND 104) ; logical and (&&)
585 (defvar js2-INC 105) ; increment/decrement (++ --)
586 (defvar js2-DEC 106)
587 (defvar js2-DOT 107) ; member operator (.)
588 (defvar js2-FUNCTION 108) ; function keyword
589 (defvar js2-EXPORT 109) ; export keyword
590 (defvar js2-IMPORT 110) ; import keyword
591 (defvar js2-IF 111) ; if keyword
592 (defvar js2-ELSE 112) ; else keyword
593 (defvar js2-SWITCH 113) ; switch keyword
594 (defvar js2-CASE 114) ; case keyword
595 (defvar js2-DEFAULT 115) ; default keyword
596 (defvar js2-WHILE 116) ; while keyword
597 (defvar js2-DO 117) ; do keyword
598 (defvar js2-FOR 118) ; for keyword
599 (defvar js2-BREAK 119) ; break keyword
600 (defvar js2-CONTINUE 120) ; continue keyword
601 (defvar js2-VAR 121) ; var keyword
602 (defvar js2-WITH 122) ; with keyword
603 (defvar js2-CATCH 123) ; catch keyword
604 (defvar js2-FINALLY 124) ; finally keyword
605 (defvar js2-VOID 125) ; void keyword
606 (defvar js2-RESERVED 126) ; reserved keywords
607
608 (defvar js2-EMPTY 127)
609
610 ;; Types used for the parse tree - never returned by scanner.
611
612 (defvar js2-BLOCK 128) ; statement block
613 (defvar js2-LABEL 129) ; label
614 (defvar js2-TARGET 130)
615 (defvar js2-LOOP 131)
616 (defvar js2-EXPR_VOID 132) ; expression statement in functions
617 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
618 (defvar js2-JSR 134)
619 (defvar js2-SCRIPT 135) ; top-level node for entire script
620 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
621 (defvar js2-USE_STACK 137)
622 (defvar js2-SETPROP_OP 138) ; x.y op= something
623 (defvar js2-SETELEM_OP 139) ; x[y] op= something
624 (defvar js2-LOCAL_BLOCK 140)
625 (defvar js2-SET_REF_OP 141) ; *reference op= something
626
627 ;; For XML support:
628 (defvar js2-DOTDOT 142) ; member operator (..)
629 (defvar js2-COLONCOLON 143) ; namespace::name
630 (defvar js2-XML 144) ; XML type
631 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
632 (defvar js2-XMLATTR 146) ; @
633 (defvar js2-XMLEND 147)
634
635 ;; Optimizer-only tokens
636 (defvar js2-TO_OBJECT 148)
637 (defvar js2-TO_DOUBLE 149)
638
639 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
640 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
641 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
642 (defvar js2-CONST 153)
643 (defvar js2-SETCONST 154)
644 (defvar js2-SETCONSTVAR 155)
645 (defvar js2-ARRAYCOMP 156)
646 (defvar js2-LETEXPR 157)
647 (defvar js2-WITHEXPR 158)
648 (defvar js2-DEBUGGER 159)
649
650 (defvar js2-COMMENT 160)
651 (defvar js2-ENUM 161) ; for "enum" reserved word
652 (defvar js2-TRIPLEDOT 162) ; for rest parameter
653
654 (defconst js2-num-tokens (1+ js2-TRIPLEDOT))
655
656 (defconst js2-debug-print-trees nil)
657
658 ;; Rhino accepts any string or stream as input. Emacs character
659 ;; processing works best in buffers, so we'll assume the input is a
660 ;; buffer. JavaScript strings can be copied into temp buffers before
661 ;; scanning them.
662
663 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
664 ;; They're the Emacs equivalent of instance variables, more or less.
665
666 (js2-deflocal js2-ts-dirty-line nil
667 "Token stream buffer-local variable.
668 Indicates stuff other than whitespace since start of line.")
669
670 (js2-deflocal js2-ts-regexp-flags nil
671 "Token stream buffer-local variable.")
672
673 (js2-deflocal js2-ts-string ""
674 "Token stream buffer-local variable.
675 Last string scanned.")
676
677 (js2-deflocal js2-ts-number nil
678 "Token stream buffer-local variable.
679 Last literal number scanned.")
680
681 (js2-deflocal js2-ts-hit-eof nil
682 "Token stream buffer-local variable.")
683
684 (js2-deflocal js2-ts-line-start 0
685 "Token stream buffer-local variable.")
686
687 (js2-deflocal js2-ts-lineno 1
688 "Token stream buffer-local variable.")
689
690 (js2-deflocal js2-ts-line-end-char -1
691 "Token stream buffer-local variable.")
692
693 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
694 "Token stream buffer-local variable.
695 Current scan position.")
696
697 (js2-deflocal js2-ts-is-xml-attribute nil
698 "Token stream buffer-local variable.")
699
700 (js2-deflocal js2-ts-xml-is-tag-content nil
701 "Token stream buffer-local variable.")
702
703 (js2-deflocal js2-ts-xml-open-tags-count 0
704 "Token stream buffer-local variable.")
705
706 (js2-deflocal js2-ts-string-buffer nil
707 "Token stream buffer-local variable.
708 List of chars built up while scanning various tokens.")
709
710 (js2-deflocal js2-ts-comment-type nil
711 "Token stream buffer-local variable.")
712
713 ;;; Parser variables
714
715 (js2-deflocal js2-parsed-errors nil
716 "List of errors produced during scanning/parsing.")
717
718 (js2-deflocal js2-parsed-warnings nil
719 "List of warnings produced during scanning/parsing.")
720
721 (js2-deflocal js2-recover-from-parse-errors t
722 "Non-nil to continue parsing after a syntax error.
723
724 In recovery mode, the AST will be built in full, and any error
725 nodes will be flagged with appropriate error information. If
726 this flag is nil, a syntax error will result in an error being
727 signaled.
728
729 The variable is automatically buffer-local, because different
730 modes that use the parser will need different settings.")
731
732 (js2-deflocal js2-parse-hook nil
733 "List of callbacks for receiving parsing progress.")
734
735 (defvar js2-parse-finished-hook nil
736 "List of callbacks to notify when parsing finishes.
737 Not called if parsing was interrupted.")
738
739 (js2-deflocal js2-is-eval-code nil
740 "True if we're evaluating code in a string.
741 If non-nil, the tokenizer will record the token text, and the AST nodes
742 will record their source text. Off by default for IDE modes, since the
743 text is available in the buffer.")
744
745 (defvar js2-parse-ide-mode t
746 "Non-nil if the parser is being used for `js2-mode'.
747 If non-nil, the parser will set text properties for fontification
748 and the syntax table. The value should be nil when using the
749 parser as a frontend to an interpreter or byte compiler.")
750
751 ;;; Parser instance variables (buffer-local vars for js2-parse)
752
753 (defconst js2-clear-ti-mask #xFFFF
754 "Mask to clear token information bits.")
755
756 (defconst js2-ti-after-eol (lsh 1 16)
757 "Flag: first token of the source line.")
758
759 (defconst js2-ti-check-label (lsh 1 17)
760 "Flag: indicates to check for label.")
761
762 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
763
764 (js2-deflocal js2-compiler-generate-debug-info t)
765 (js2-deflocal js2-compiler-use-dynamic-scope nil)
766 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
767 (js2-deflocal js2-compiler-xml-available t)
768 (js2-deflocal js2-compiler-optimization-level 0)
769 (js2-deflocal js2-compiler-generating-source t)
770 (js2-deflocal js2-compiler-strict-mode nil)
771 (js2-deflocal js2-compiler-report-warning-as-error nil)
772 (js2-deflocal js2-compiler-generate-observer-count nil)
773 (js2-deflocal js2-compiler-activation-names nil)
774
775 ;; SKIP: sourceURI
776
777 ;; There's a compileFunction method in Context.java - may need it.
778 (js2-deflocal js2-called-by-compile-function nil
779 "True if `js2-parse' was called by `js2-compile-function'.
780 Will only be used when we finish implementing the interpreter.")
781
782 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
783
784 (js2-deflocal js2-current-flagged-token js2-EOF)
785 (js2-deflocal js2-current-token js2-EOF)
786
787 ;; SKIP: node factory - we're going to just call functions directly,
788 ;; and eventually go to a unified AST format.
789
790 (js2-deflocal js2-nesting-of-function 0)
791
792 (js2-deflocal js2-recorded-identifiers nil
793 "Tracks identifiers found during parsing.")
794
795 (js2-deflocal js2-is-in-destructuring nil
796 "True while parsing destructuring expression.")
797
798 (defcustom js2-global-externs nil
799 "A list of any extern names you'd like to consider always declared.
800 This list is global and is used by all `js2-mode' files.
801 You can create buffer-local externs list using `js2-additional-externs'.
802
803 There is also a buffer-local variable `js2-default-externs',
804 which is initialized by default to include the Ecma-262 externs
805 and the standard browser externs. The three lists are all
806 checked during highlighting."
807 :type 'list
808 :group 'js2-mode)
809
810 (js2-deflocal js2-default-externs nil
811 "Default external declarations.
812
813 These are currently only used for highlighting undeclared variables,
814 which only worries about top-level (unqualified) references.
815 As js2-mode's processing improves, we will flesh out this list.
816
817 The initial value is set to `js2-ecma-262-externs', unless some
818 of the `js2-include-?-externs' variables are set to t, in which
819 case the browser, Rhino and/or Node.js externs are also included.
820
821 See `js2-additional-externs' for more information.")
822
823 (defcustom js2-include-browser-externs t
824 "Non-nil to include browser externs in the master externs list.
825 If you work on JavaScript files that are not intended for browsers,
826 such as Mozilla Rhino server-side JavaScript, set this to nil.
827 See `js2-additional-externs' for more information about externs."
828 :type 'boolean
829 :group 'js2-mode)
830
831 (defcustom js2-include-rhino-externs nil
832 "Non-nil to include Mozilla Rhino externs in the master externs list.
833 See `js2-additional-externs' for more information about externs."
834 :type 'boolean
835 :group 'js2-mode)
836
837 (defcustom js2-include-node-externs nil
838 "Non-nil to include Node.js externs in the master externs list.
839 See `js2-additional-externs' for more information about externs."
840 :type 'boolean
841 :group 'js2-mode)
842
843 (js2-deflocal js2-additional-externs nil
844 "A buffer-local list of additional external declarations.
845 It is used to decide whether variables are considered undeclared
846 for purposes of highlighting.
847
848 Each entry is a Lisp string. The string should be the fully qualified
849 name of an external entity. All externs should be added to this list,
850 so that as js2-mode's processing improves it can take advantage of them.
851
852 You may want to declare your externs in three ways.
853 First, you can add externs that are valid for all your JavaScript files.
854 You should probably do this by adding them to `js2-global-externs', which
855 is a global list used for all js2-mode files.
856
857 Next, you can add a function to `js2-mode-hook' that adds additional
858 externs appropriate for the specific file, perhaps based on its path.
859 These should go in `js2-additional-externs', which is buffer-local.
860
861 Third, you can use JSLint's global declaration, as long as
862 `js2-include-jslint-globals' is non-nil, which see.
863
864 Finally, you can add a function to `js2-post-parse-callbacks',
865 which is called after parsing completes, and `js2-mode-ast' is bound to
866 the root of the parse tree. At this stage you can set up an AST
867 node visitor using `js2-visit-ast' and examine the parse tree
868 for specific import patterns that may imply the existence of
869 other externs, possibly tied to your build system. These should also
870 be added to `js2-additional-externs'.
871
872 Your post-parse callback may of course also use the simpler and
873 faster (but perhaps less robust) approach of simply scanning the
874 buffer text for your imports, using regular expressions.")
875
876 ;; SKIP: decompiler
877 ;; SKIP: encoded-source
878
879 ;;; The following variables are per-function and should be saved/restored
880 ;;; during function parsing...
881
882 (js2-deflocal js2-current-script-or-fn nil)
883 (js2-deflocal js2-current-scope nil)
884 (js2-deflocal js2-nesting-of-with 0)
885 (js2-deflocal js2-label-set nil
886 "An alist mapping label names to nodes.")
887
888 (js2-deflocal js2-loop-set nil)
889 (js2-deflocal js2-loop-and-switch-set nil)
890 (js2-deflocal js2-has-return-value nil)
891 (js2-deflocal js2-end-flags 0)
892
893 ;;; ...end of per function variables
894
895 ;; Without 2-token lookahead, labels are a problem.
896 ;; These vars store the token info of the last matched name,
897 ;; iff it wasn't the last matched token. Only valid in some contexts.
898 (defvar js2-prev-name-token-start nil)
899 (defvar js2-prev-name-token-string nil)
900
901 (defsubst js2-save-name-token-data (pos name)
902 (setq js2-prev-name-token-start pos
903 js2-prev-name-token-string name))
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 (defconst js2-end-yields #x8)
930
931 ;; Rhino awkwardly passes a statementLabel parameter to the
932 ;; statementHelper() function, the main statement parser, which
933 ;; is then used by quite a few of the sub-parsers. We just make
934 ;; it a buffer-local variable and make sure it's cleaned up properly.
935 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
936
937 ;; Similarly, Rhino passes an inForInit boolean through about half
938 ;; the expression parsers. We use a dynamically-scoped variable,
939 ;; which makes it easier to funcall the parsers individually without
940 ;; worrying about whether they take the parameter or not.
941 (js2-deflocal js2-in-for-init nil)
942 (js2-deflocal js2-temp-name-counter 0)
943 (js2-deflocal js2-parse-stmt-count 0)
944
945 (defsubst js2-get-next-temp-name ()
946 (format "$%d" (incf js2-temp-name-counter)))
947
948 (defvar js2-parse-interruptable-p t
949 "Set this to nil to force parse to continue until finished.
950 This will mostly be useful for interpreters.")
951
952 (defvar js2-statements-per-pause 50
953 "Pause after this many statements to check for user input.
954 If user input is pending, stop the parse and discard the tree.
955 This makes for a smoother user experience for large files.
956 You may have to wait a second or two before the highlighting
957 and error-reporting appear, but you can always type ahead if
958 you wish. This appears to be more or less how Eclipse, IntelliJ
959 and other editors work.")
960
961 (js2-deflocal js2-record-comments t
962 "Instructs the scanner to record comments in `js2-scanned-comments'.")
963
964 (js2-deflocal js2-scanned-comments nil
965 "List of all comments from the current parse.")
966
967 (defcustom js2-mode-indent-inhibit-undo nil
968 "Non-nil to disable collection of Undo information when indenting lines.
969 Some users have requested this behavior. It's nil by default because
970 other Emacs modes don't work this way."
971 :type 'boolean
972 :group 'js2-mode)
973
974 (defcustom js2-mode-indent-ignore-first-tab nil
975 "If non-nil, ignore first TAB keypress if we look indented properly.
976 It's fairly common for users to navigate to an already-indented line
977 and press TAB for reassurance that it's been indented. For this class
978 of users, we want the first TAB press on a line to be ignored if the
979 line is already indented to one of the precomputed alternatives.
980
981 This behavior is only partly implemented. If you TAB-indent a line,
982 navigate to another line, and then navigate back, it fails to clear
983 the last-indented variable, so it thinks you've already hit TAB once,
984 and performs the indent. A full solution would involve getting on the
985 point-motion hooks for the entire buffer. If we come across another
986 use cases that requires watching point motion, I'll consider doing it.
987
988 If you set this variable to nil, then the TAB key will always change
989 the indentation of the current line, if more than one alternative
990 indentation spot exists."
991 :type 'boolean
992 :group 'js2-mode)
993
994 (defvar js2-indent-hook nil
995 "A hook for user-defined indentation rules.
996
997 Functions on this hook should expect two arguments: (LIST INDEX)
998 The LIST argument is the list of computed indentation points for
999 the current line. INDEX is the list index of the indentation point
1000 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1001 indent function is not going to change the current line indentation.
1002
1003 If a hook function on this list returns a non-nil value, then
1004 `js2-bounce-indent' assumes the hook function has performed its own
1005 indentation, and will do nothing. If all hook functions on the list
1006 return nil, then `js2-bounce-indent' will use its computed indentation
1007 and reindent the line.
1008
1009 When hook functions on this hook list are called, the variable
1010 `js2-mode-ast' may or may not be set, depending on whether the
1011 parse tree is available. If the variable is nil, you can pass a
1012 callback to `js2-mode-wait-for-parse', and your callback will be
1013 called after the new parse tree is built. This can take some time
1014 in large files.")
1015
1016 (defface js2-warning
1017 `((((class color) (background light))
1018 (:underline "orange"))
1019 (((class color) (background dark))
1020 (:underline "orange"))
1021 (t (:underline t)))
1022 "Face for JavaScript warnings."
1023 :group 'js2-mode)
1024
1025 (defface js2-error
1026 `((((class color) (background light))
1027 (:foreground "red"))
1028 (((class color) (background dark))
1029 (:foreground "red"))
1030 (t (:foreground "red")))
1031 "Face for JavaScript errors."
1032 :group 'js2-mode)
1033
1034 (defface js2-jsdoc-tag
1035 '((t :foreground "SlateGray"))
1036 "Face used to highlight @whatever tags in jsdoc comments."
1037 :group 'js2-mode)
1038
1039 (defface js2-jsdoc-type
1040 '((t :foreground "SteelBlue"))
1041 "Face used to highlight {FooBar} types in jsdoc comments."
1042 :group 'js2-mode)
1043
1044 (defface js2-jsdoc-value
1045 '((t :foreground "PeachPuff3"))
1046 "Face used to highlight tag values in jsdoc comments."
1047 :group 'js2-mode)
1048
1049 (defface js2-function-param
1050 '((t :foreground "SeaGreen"))
1051 "Face used to highlight function parameters in javascript."
1052 :group 'js2-mode)
1053
1054 (defface js2-instance-member
1055 '((t :foreground "DarkOrchid"))
1056 "Face used to highlight instance variables in javascript.
1057 Not currently used."
1058 :group 'js2-mode)
1059
1060 (defface js2-private-member
1061 '((t :foreground "PeachPuff3"))
1062 "Face used to highlight calls to private methods in javascript.
1063 Not currently used."
1064 :group 'js2-mode)
1065
1066 (defface js2-private-function-call
1067 '((t :foreground "goldenrod"))
1068 "Face used to highlight calls to private functions in javascript.
1069 Not currently used."
1070 :group 'js2-mode)
1071
1072 (defface js2-jsdoc-html-tag-name
1073 '((((class color) (min-colors 88) (background light))
1074 (:foreground "rosybrown"))
1075 (((class color) (min-colors 8) (background dark))
1076 (:foreground "yellow"))
1077 (((class color) (min-colors 8) (background light))
1078 (:foreground "magenta")))
1079 "Face used to highlight jsdoc html tag names"
1080 :group 'js2-mode)
1081
1082 (defface js2-jsdoc-html-tag-delimiter
1083 '((((class color) (min-colors 88) (background light))
1084 (:foreground "dark khaki"))
1085 (((class color) (min-colors 8) (background dark))
1086 (:foreground "green"))
1087 (((class color) (min-colors 8) (background light))
1088 (:foreground "green")))
1089 "Face used to highlight brackets in jsdoc html tags."
1090 :group 'js2-mode)
1091
1092 (defface js2-external-variable
1093 '((t :foreground "orange"))
1094 "Face used to highlight undeclared variable identifiers.")
1095
1096 (defcustom js2-post-parse-callbacks nil
1097 "A list of callback functions invoked after parsing finishes.
1098 Currently, the main use for this function is to add synthetic
1099 declarations to `js2-recorded-identifiers', which see."
1100 :type 'list
1101 :group 'js2-mode)
1102
1103 (defcustom js2-highlight-external-variables t
1104 "Non-nil to highlight undeclared variable identifiers.
1105 An undeclared variable is any variable not declared with var or let
1106 in the current scope or any lexically enclosing scope. If you use
1107 such a variable, then you are either expecting it to originate from
1108 another file, or you've got a potential bug."
1109 :type 'boolean
1110 :group 'js2-mode)
1111
1112 (defcustom js2-include-jslint-globals t
1113 "Non-nil to include the identifiers from JSLint global
1114 declaration (see http://www.jslint.com/lint.html#global) in the
1115 buffer-local externs list. See `js2-additional-externs' for more
1116 information."
1117 :type 'boolean
1118 :group 'js2-mode)
1119
1120 (defvar js2-mode-map
1121 (let ((map (make-sparse-keymap))
1122 keys)
1123 (define-key map [mouse-1] #'js2-mode-show-node)
1124 (define-key map (kbd "M-j") #'js2-line-break)
1125 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1126 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1127 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1128 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1129 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1130 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1131 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1132 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1133 (when js2-bounce-indent-p
1134 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1135
1136 (define-key map [menu-bar javascript]
1137 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1138
1139 (define-key map [menu-bar javascript customize-js2-mode]
1140 '(menu-item "Customize js2-mode" js2-mode-customize
1141 :help "Customize the behavior of this mode"))
1142
1143 (define-key map [menu-bar javascript js2-force-refresh]
1144 '(menu-item "Force buffer refresh" js2-mode-reset
1145 :help "Re-parse the buffer from scratch"))
1146
1147 (define-key map [menu-bar javascript separator-2]
1148 '("--"))
1149
1150 (define-key map [menu-bar javascript next-error]
1151 '(menu-item "Next warning or error" next-error
1152 :enabled (and js2-mode-ast
1153 (or (js2-ast-root-errors js2-mode-ast)
1154 (js2-ast-root-warnings js2-mode-ast)))
1155 :help "Move to next warning or error"))
1156
1157 (define-key map [menu-bar javascript display-errors]
1158 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1159 :visible (not js2-mode-show-parse-errors)
1160 :help "Turn on display of warnings and errors"))
1161
1162 (define-key map [menu-bar javascript hide-errors]
1163 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1164 :visible js2-mode-show-parse-errors
1165 :help "Turn off display of warnings and errors"))
1166
1167 (define-key map [menu-bar javascript separator-1]
1168 '("--"))
1169
1170 (define-key map [menu-bar javascript js2-toggle-function]
1171 '(menu-item "Show/collapse element" js2-mode-toggle-element
1172 :help "Hide or show function body or comment"))
1173
1174 (define-key map [menu-bar javascript show-comments]
1175 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1176 :visible js2-mode-comments-hidden
1177 :help "Expand all hidden block comments"))
1178
1179 (define-key map [menu-bar javascript hide-comments]
1180 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1181 :visible (not js2-mode-comments-hidden)
1182 :help "Show block comments as /*...*/"))
1183
1184 (define-key map [menu-bar javascript show-all-functions]
1185 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1186 :visible js2-mode-functions-hidden
1187 :help "Expand all hidden function bodies"))
1188
1189 (define-key map [menu-bar javascript hide-all-functions]
1190 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1191 :visible (not js2-mode-functions-hidden)
1192 :help "Show {...} for all top-level function bodies"))
1193
1194 map)
1195 "Keymap used in `js2-mode' buffers.")
1196
1197 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1198
1199 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1200 "Matches a //-comment line. Must be first non-whitespace on line.
1201 First match-group is the leading whitespace.")
1202
1203 (defvar js2-mode-hook nil)
1204
1205 (js2-deflocal js2-mode-ast nil "Private variable.")
1206 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1207 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1208 (js2-deflocal js2-mode-parsing nil "Private variable.")
1209 (js2-deflocal js2-mode-node-overlay nil)
1210
1211 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1212 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1213
1214 (js2-deflocal js2-mode-fontifications nil "Private variable")
1215 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1216 (js2-deflocal js2-imenu-recorder nil "Private variable")
1217 (js2-deflocal js2-imenu-function-map nil "Private variable")
1218
1219 (defvar js2-paragraph-start
1220 "\\(@[a-zA-Z]+\\>\\|$\\)")
1221
1222 ;; Note that we also set a 'c-in-sws text property in html comments,
1223 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1224 (defvar js2-syntactic-ws-start
1225 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1226
1227 (defvar js2-syntactic-ws-end
1228 "\\s \\|[\n\r/]\\|\\s!")
1229
1230 (defvar js2-syntactic-eol
1231 (concat "\\s *\\(/\\*[^*\n\r]*"
1232 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1233 "\\*+/\\s *\\)*"
1234 "\\(//\\|/\\*[^*\n\r]*"
1235 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1236 "\\|\\\\$\\|$\\)")
1237 "Copied from `java-mode'. Needed for some cc-engine functions.")
1238
1239 (defvar js2-comment-prefix-regexp
1240 "//+\\|\\**")
1241
1242 (defvar js2-comment-start-skip
1243 "\\(//+\\|/\\*+\\)\\s *")
1244
1245 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1246 "Non-nil to emit status messages during parsing.")
1247
1248 (defvar js2-mode-functions-hidden nil "Private variable.")
1249 (defvar js2-mode-comments-hidden nil "Private variable.")
1250
1251 (defvar js2-mode-syntax-table
1252 (let ((table (make-syntax-table)))
1253 (c-populate-syntax-table table)
1254 table)
1255 "Syntax table used in `js2-mode' buffers.")
1256
1257 (defvar js2-mode-abbrev-table nil
1258 "Abbrev table in use in `js2-mode' buffers.")
1259 (define-abbrev-table 'js2-mode-abbrev-table ())
1260
1261 (defvar js2-mode-pending-parse-callbacks nil
1262 "List of functions waiting to be notified that parse is finished.")
1263
1264 (defvar js2-mode-last-indented-line -1)
1265
1266 ;;; Localizable error and warning messages
1267
1268 ;; Messages are copied from Rhino's Messages.properties.
1269 ;; Many of the Java-specific messages have been elided.
1270 ;; Add any js2-specific ones at the end, so we can keep
1271 ;; this file synced with changes to Rhino's.
1272
1273 (defvar js2-message-table
1274 (make-hash-table :test 'equal :size 250)
1275 "Contains localized messages for `js2-mode'.")
1276
1277 ;; TODO(stevey): construct this table at compile-time.
1278 (defmacro js2-msg (key &rest strings)
1279 `(puthash ,key (concat ,@strings)
1280 js2-message-table))
1281
1282 (defun js2-get-msg (msg-key)
1283 "Look up a localized message.
1284 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1285 the correct number of ARGS must be provided."
1286 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1287 (args (if (listp msg-key) (cdr msg-key)))
1288 (msg (gethash key js2-message-table)))
1289 (if msg
1290 (apply #'format msg args)
1291 key))) ; default to showing the key
1292
1293 (js2-msg "msg.dup.parms"
1294 "Duplicate parameter name '%s'.")
1295
1296 (js2-msg "msg.too.big.jump"
1297 "Program too complex: jump offset too big.")
1298
1299 (js2-msg "msg.too.big.index"
1300 "Program too complex: internal index exceeds 64K limit.")
1301
1302 (js2-msg "msg.while.compiling.fn"
1303 "Encountered code generation error while compiling function '%s': %s")
1304
1305 (js2-msg "msg.while.compiling.script"
1306 "Encountered code generation error while compiling script: %s")
1307
1308 ;; Context
1309 (js2-msg "msg.ctor.not.found"
1310 "Constructor for '%s' not found.")
1311
1312 (js2-msg "msg.not.ctor"
1313 "'%s' is not a constructor.")
1314
1315 ;; FunctionObject
1316 (js2-msg "msg.varargs.ctor"
1317 "Method or constructor '%s' must be static "
1318 "with the signature (Context cx, Object[] args, "
1319 "Function ctorObj, boolean inNewExpr) "
1320 "to define a variable arguments constructor.")
1321
1322 (js2-msg "msg.varargs.fun"
1323 "Method '%s' must be static with the signature "
1324 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1325 "to define a variable arguments function.")
1326
1327 (js2-msg "msg.incompat.call"
1328 "Method '%s' called on incompatible object.")
1329
1330 (js2-msg "msg.bad.parms"
1331 "Unsupported parameter type '%s' in method '%s'.")
1332
1333 (js2-msg "msg.bad.method.return"
1334 "Unsupported return type '%s' in method '%s'.")
1335
1336 (js2-msg "msg.bad.ctor.return"
1337 "Construction of objects of type '%s' is not supported.")
1338
1339 (js2-msg "msg.no.overload"
1340 "Method '%s' occurs multiple times in class '%s'.")
1341
1342 (js2-msg "msg.method.not.found"
1343 "Method '%s' not found in '%s'.")
1344
1345 ;; IRFactory
1346
1347 (js2-msg "msg.bad.for.in.lhs"
1348 "Invalid left-hand side of for..in loop.")
1349
1350 (js2-msg "msg.mult.index"
1351 "Only one variable allowed in for..in loop.")
1352
1353 (js2-msg "msg.bad.for.in.destruct"
1354 "Left hand side of for..in loop must be an array of "
1355 "length 2 to accept key/value pair.")
1356
1357 (js2-msg "msg.cant.convert"
1358 "Can't convert to type '%s'.")
1359
1360 (js2-msg "msg.bad.assign.left"
1361 "Invalid assignment left-hand side.")
1362
1363 (js2-msg "msg.bad.decr"
1364 "Invalid decerement operand.")
1365
1366 (js2-msg "msg.bad.incr"
1367 "Invalid increment operand.")
1368
1369 (js2-msg "msg.bad.yield"
1370 "yield must be in a function.")
1371
1372 (js2-msg "msg.yield.parenthesized"
1373 "yield expression must be parenthesized.")
1374
1375 ;; NativeGlobal
1376 (js2-msg "msg.cant.call.indirect"
1377 "Function '%s' must be called directly, and not by way of a "
1378 "function of another name.")
1379
1380 (js2-msg "msg.eval.nonstring"
1381 "Calling eval() with anything other than a primitive "
1382 "string value will simply return the value. "
1383 "Is this what you intended?")
1384
1385 (js2-msg "msg.eval.nonstring.strict"
1386 "Calling eval() with anything other than a primitive "
1387 "string value is not allowed in strict mode.")
1388
1389 (js2-msg "msg.bad.destruct.op"
1390 "Invalid destructuring assignment operator")
1391
1392 ;; NativeCall
1393 (js2-msg "msg.only.from.new"
1394 "'%s' may only be invoked from a `new' expression.")
1395
1396 (js2-msg "msg.deprec.ctor"
1397 "The '%s' constructor is deprecated.")
1398
1399 ;; NativeFunction
1400 (js2-msg "msg.no.function.ref.found"
1401 "no source found to decompile function reference %s")
1402
1403 (js2-msg "msg.arg.isnt.array"
1404 "second argument to Function.prototype.apply must be an array")
1405
1406 ;; NativeGlobal
1407 (js2-msg "msg.bad.esc.mask"
1408 "invalid string escape mask")
1409
1410 ;; NativeRegExp
1411 (js2-msg "msg.bad.quant"
1412 "Invalid quantifier %s")
1413
1414 (js2-msg "msg.overlarge.backref"
1415 "Overly large back reference %s")
1416
1417 (js2-msg "msg.overlarge.min"
1418 "Overly large minimum %s")
1419
1420 (js2-msg "msg.overlarge.max"
1421 "Overly large maximum %s")
1422
1423 (js2-msg "msg.zero.quant"
1424 "Zero quantifier %s")
1425
1426 (js2-msg "msg.max.lt.min"
1427 "Maximum %s less than minimum")
1428
1429 (js2-msg "msg.unterm.quant"
1430 "Unterminated quantifier %s")
1431
1432 (js2-msg "msg.unterm.paren"
1433 "Unterminated parenthetical %s")
1434
1435 (js2-msg "msg.unterm.class"
1436 "Unterminated character class %s")
1437
1438 (js2-msg "msg.bad.range"
1439 "Invalid range in character class.")
1440
1441 (js2-msg "msg.trail.backslash"
1442 "Trailing \\ in regular expression.")
1443
1444 (js2-msg "msg.re.unmatched.right.paren"
1445 "unmatched ) in regular expression.")
1446
1447 (js2-msg "msg.no.regexp"
1448 "Regular expressions are not available.")
1449
1450 (js2-msg "msg.bad.backref"
1451 "back-reference exceeds number of capturing parentheses.")
1452
1453 (js2-msg "msg.bad.regexp.compile"
1454 "Only one argument may be specified if the first "
1455 "argument to RegExp.prototype.compile is a RegExp object.")
1456
1457 ;; Parser
1458 (js2-msg "msg.got.syntax.errors"
1459 "Compilation produced %s syntax errors.")
1460
1461 (js2-msg "msg.var.redecl"
1462 "TypeError: redeclaration of var %s.")
1463
1464 (js2-msg "msg.const.redecl"
1465 "TypeError: redeclaration of const %s.")
1466
1467 (js2-msg "msg.let.redecl"
1468 "TypeError: redeclaration of variable %s.")
1469
1470 (js2-msg "msg.parm.redecl"
1471 "TypeError: redeclaration of formal parameter %s.")
1472
1473 (js2-msg "msg.fn.redecl"
1474 "TypeError: redeclaration of function %s.")
1475
1476 (js2-msg "msg.let.decl.not.in.block"
1477 "SyntaxError: let declaration not directly within block")
1478
1479 ;; NodeTransformer
1480 (js2-msg "msg.dup.label"
1481 "duplicated label")
1482
1483 (js2-msg "msg.undef.label"
1484 "undefined label")
1485
1486 (js2-msg "msg.bad.break"
1487 "unlabelled break must be inside loop or switch")
1488
1489 (js2-msg "msg.continue.outside"
1490 "continue must be inside loop")
1491
1492 (js2-msg "msg.continue.nonloop"
1493 "continue can only use labels of iteration statements")
1494
1495 (js2-msg "msg.bad.throw.eol"
1496 "Line terminator is not allowed between the throw "
1497 "keyword and throw expression.")
1498
1499 (js2-msg "msg.no.paren.parms"
1500 "missing ( before function parameters.")
1501
1502 (js2-msg "msg.no.parm"
1503 "missing formal parameter")
1504
1505 (js2-msg "msg.no.paren.after.parms"
1506 "missing ) after formal parameters")
1507
1508 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1509 "parameter without default follows parameter with default")
1510
1511 (js2-msg "msg.param.after.rest" ; added by js2-mode
1512 "parameter after rest parameter")
1513
1514 (js2-msg "msg.no.brace.body"
1515 "missing '{' before function body")
1516
1517 (js2-msg "msg.no.brace.after.body"
1518 "missing } after function body")
1519
1520 (js2-msg "msg.no.paren.cond"
1521 "missing ( before condition")
1522
1523 (js2-msg "msg.no.paren.after.cond"
1524 "missing ) after condition")
1525
1526 (js2-msg "msg.no.semi.stmt"
1527 "missing ; before statement")
1528
1529 (js2-msg "msg.missing.semi"
1530 "missing ; after statement")
1531
1532 (js2-msg "msg.no.name.after.dot"
1533 "missing name after . operator")
1534
1535 (js2-msg "msg.no.name.after.coloncolon"
1536 "missing name after :: operator")
1537
1538 (js2-msg "msg.no.name.after.dotdot"
1539 "missing name after .. operator")
1540
1541 (js2-msg "msg.no.name.after.xmlAttr"
1542 "missing name after .@")
1543
1544 (js2-msg "msg.no.bracket.index"
1545 "missing ] in index expression")
1546
1547 (js2-msg "msg.no.paren.switch"
1548 "missing ( before switch expression")
1549
1550 (js2-msg "msg.no.paren.after.switch"
1551 "missing ) after switch expression")
1552
1553 (js2-msg "msg.no.brace.switch"
1554 "missing '{' before switch body")
1555
1556 (js2-msg "msg.bad.switch"
1557 "invalid switch statement")
1558
1559 (js2-msg "msg.no.colon.case"
1560 "missing : after case expression")
1561
1562 (js2-msg "msg.double.switch.default"
1563 "double default label in the switch statement")
1564
1565 (js2-msg "msg.no.while.do"
1566 "missing while after do-loop body")
1567
1568 (js2-msg "msg.no.paren.for"
1569 "missing ( after for")
1570
1571 (js2-msg "msg.no.semi.for"
1572 "missing ; after for-loop initializer")
1573
1574 (js2-msg "msg.no.semi.for.cond"
1575 "missing ; after for-loop condition")
1576
1577 (js2-msg "msg.in.after.for.name"
1578 "missing in or of after for")
1579
1580 (js2-msg "msg.no.paren.for.ctrl"
1581 "missing ) after for-loop control")
1582
1583 (js2-msg "msg.no.paren.with"
1584 "missing ( before with-statement object")
1585
1586 (js2-msg "msg.no.paren.after.with"
1587 "missing ) after with-statement object")
1588
1589 (js2-msg "msg.no.paren.after.let"
1590 "missing ( after let")
1591
1592 (js2-msg "msg.no.paren.let"
1593 "missing ) after variable list")
1594
1595 (js2-msg "msg.no.curly.let"
1596 "missing } after let statement")
1597
1598 (js2-msg "msg.bad.return"
1599 "invalid return")
1600
1601 (js2-msg "msg.no.brace.block"
1602 "missing } in compound statement")
1603
1604 (js2-msg "msg.bad.label"
1605 "invalid label")
1606
1607 (js2-msg "msg.bad.var"
1608 "missing variable name")
1609
1610 (js2-msg "msg.bad.var.init"
1611 "invalid variable initialization")
1612
1613 (js2-msg "msg.no.colon.cond"
1614 "missing : in conditional expression")
1615
1616 (js2-msg "msg.no.paren.arg"
1617 "missing ) after argument list")
1618
1619 (js2-msg "msg.no.bracket.arg"
1620 "missing ] after element list")
1621
1622 (js2-msg "msg.bad.prop"
1623 "invalid property id")
1624
1625 (js2-msg "msg.no.colon.prop"
1626 "missing : after property id")
1627
1628 (js2-msg "msg.no.brace.prop"
1629 "missing } after property list")
1630
1631 (js2-msg "msg.no.paren"
1632 "missing ) in parenthetical")
1633
1634 (js2-msg "msg.reserved.id"
1635 "identifier is a reserved word")
1636
1637 (js2-msg "msg.no.paren.catch"
1638 "missing ( before catch-block condition")
1639
1640 (js2-msg "msg.bad.catchcond"
1641 "invalid catch block condition")
1642
1643 (js2-msg "msg.catch.unreachable"
1644 "any catch clauses following an unqualified catch are unreachable")
1645
1646 (js2-msg "msg.no.brace.try"
1647 "missing '{' before try block")
1648
1649 (js2-msg "msg.no.brace.catchblock"
1650 "missing '{' before catch-block body")
1651
1652 (js2-msg "msg.try.no.catchfinally"
1653 "'try' without 'catch' or 'finally'")
1654
1655 (js2-msg "msg.no.return.value"
1656 "function %s does not always return a value")
1657
1658 (js2-msg "msg.anon.no.return.value"
1659 "anonymous function does not always return a value")
1660
1661 (js2-msg "msg.return.inconsistent"
1662 "return statement is inconsistent with previous usage")
1663
1664 (js2-msg "msg.generator.returns"
1665 "TypeError: generator function '%s' returns a value")
1666
1667 (js2-msg "msg.anon.generator.returns"
1668 "TypeError: anonymous generator function returns a value")
1669
1670 (js2-msg "msg.syntax"
1671 "syntax error")
1672
1673 (js2-msg "msg.unexpected.eof"
1674 "Unexpected end of file")
1675
1676 (js2-msg "msg.XML.bad.form"
1677 "illegally formed XML syntax")
1678
1679 (js2-msg "msg.XML.not.available"
1680 "XML runtime not available")
1681
1682 (js2-msg "msg.too.deep.parser.recursion"
1683 "Too deep recursion while parsing")
1684
1685 (js2-msg "msg.no.side.effects"
1686 "Code has no side effects")
1687
1688 (js2-msg "msg.extra.trailing.comma"
1689 "Trailing comma is not supported in some browsers")
1690
1691 (js2-msg "msg.array.trailing.comma"
1692 "Trailing comma yields different behavior across browsers")
1693
1694 (js2-msg "msg.equal.as.assign"
1695 (concat "Test for equality (==) mistyped as assignment (=)?"
1696 " (parenthesize to suppress warning)"))
1697
1698 (js2-msg "msg.var.hides.arg"
1699 "Variable %s hides argument")
1700
1701 (js2-msg "msg.destruct.assign.no.init"
1702 "Missing = in destructuring declaration")
1703
1704 ;; ScriptRuntime
1705 (js2-msg "msg.no.properties"
1706 "%s has no properties.")
1707
1708 (js2-msg "msg.invalid.iterator"
1709 "Invalid iterator value")
1710
1711 (js2-msg "msg.iterator.primitive"
1712 "__iterator__ returned a primitive value")
1713
1714 (js2-msg "msg.assn.create.strict"
1715 "Assignment to undeclared variable %s")
1716
1717 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1718 "Undeclared variable or function '%s'")
1719
1720 (js2-msg "msg.ref.undefined.prop"
1721 "Reference to undefined property '%s'")
1722
1723 (js2-msg "msg.prop.not.found"
1724 "Property %s not found.")
1725
1726 (js2-msg "msg.invalid.type"
1727 "Invalid JavaScript value of type %s")
1728
1729 (js2-msg "msg.primitive.expected"
1730 "Primitive type expected (had %s instead)")
1731
1732 (js2-msg "msg.namespace.expected"
1733 "Namespace object expected to left of :: (found %s instead)")
1734
1735 (js2-msg "msg.null.to.object"
1736 "Cannot convert null to an object.")
1737
1738 (js2-msg "msg.undef.to.object"
1739 "Cannot convert undefined to an object.")
1740
1741 (js2-msg "msg.cyclic.value"
1742 "Cyclic %s value not allowed.")
1743
1744 (js2-msg "msg.is.not.defined"
1745 "'%s' is not defined.")
1746
1747 (js2-msg "msg.undef.prop.read"
1748 "Cannot read property '%s' from %s")
1749
1750 (js2-msg "msg.undef.prop.write"
1751 "Cannot set property '%s' of %s to '%s'")
1752
1753 (js2-msg "msg.undef.prop.delete"
1754 "Cannot delete property '%s' of %s")
1755
1756 (js2-msg "msg.undef.method.call"
1757 "Cannot call method '%s' of %s")
1758
1759 (js2-msg "msg.undef.with"
1760 "Cannot apply 'with' to %s")
1761
1762 (js2-msg "msg.isnt.function"
1763 "%s is not a function, it is %s.")
1764
1765 (js2-msg "msg.isnt.function.in"
1766 "Cannot call property %s in object %s. "
1767 "It is not a function, it is '%s'.")
1768
1769 (js2-msg "msg.function.not.found"
1770 "Cannot find function %s.")
1771
1772 (js2-msg "msg.function.not.found.in"
1773 "Cannot find function %s in object %s.")
1774
1775 (js2-msg "msg.isnt.xml.object"
1776 "%s is not an xml object.")
1777
1778 (js2-msg "msg.no.ref.to.get"
1779 "%s is not a reference to read reference value.")
1780
1781 (js2-msg "msg.no.ref.to.set"
1782 "%s is not a reference to set reference value to %s.")
1783
1784 (js2-msg "msg.no.ref.from.function"
1785 "Function %s can not be used as the left-hand "
1786 "side of assignment or as an operand of ++ or -- operator.")
1787
1788 (js2-msg "msg.bad.default.value"
1789 "Object's getDefaultValue() method returned an object.")
1790
1791 (js2-msg "msg.instanceof.not.object"
1792 "Can't use instanceof on a non-object.")
1793
1794 (js2-msg "msg.instanceof.bad.prototype"
1795 "'prototype' property of %s is not an object.")
1796
1797 (js2-msg "msg.bad.radix"
1798 "illegal radix %s.")
1799
1800 ;; ScriptableObject
1801 (js2-msg "msg.default.value"
1802 "Cannot find default value for object.")
1803
1804 (js2-msg "msg.zero.arg.ctor"
1805 "Cannot load class '%s' which has no zero-parameter constructor.")
1806
1807 (js2-msg "msg.ctor.multiple.parms"
1808 "Can't define constructor or class %s since more than "
1809 "one constructor has multiple parameters.")
1810
1811 (js2-msg "msg.extend.scriptable"
1812 "%s must extend ScriptableObject in order to define property %s.")
1813
1814 (js2-msg "msg.bad.getter.parms"
1815 "In order to define a property, getter %s must have zero "
1816 "parameters or a single ScriptableObject parameter.")
1817
1818 (js2-msg "msg.obj.getter.parms"
1819 "Expected static or delegated getter %s to take "
1820 "a ScriptableObject parameter.")
1821
1822 (js2-msg "msg.getter.static"
1823 "Getter and setter must both be static or neither be static.")
1824
1825 (js2-msg "msg.setter.return"
1826 "Setter must have void return type: %s")
1827
1828 (js2-msg "msg.setter2.parms"
1829 "Two-parameter setter must take a ScriptableObject as "
1830 "its first parameter.")
1831
1832 (js2-msg "msg.setter1.parms"
1833 "Expected single parameter setter for %s")
1834
1835 (js2-msg "msg.setter2.expected"
1836 "Expected static or delegated setter %s to take two parameters.")
1837
1838 (js2-msg "msg.setter.parms"
1839 "Expected either one or two parameters for setter.")
1840
1841 (js2-msg "msg.setter.bad.type"
1842 "Unsupported parameter type '%s' in setter '%s'.")
1843
1844 (js2-msg "msg.add.sealed"
1845 "Cannot add a property to a sealed object: %s.")
1846
1847 (js2-msg "msg.remove.sealed"
1848 "Cannot remove a property from a sealed object: %s.")
1849
1850 (js2-msg "msg.modify.sealed"
1851 "Cannot modify a property of a sealed object: %s.")
1852
1853 (js2-msg "msg.modify.readonly"
1854 "Cannot modify readonly property: %s.")
1855
1856 ;; TokenStream
1857 (js2-msg "msg.missing.exponent"
1858 "missing exponent")
1859
1860 (js2-msg "msg.caught.nfe"
1861 "number format error")
1862
1863 (js2-msg "msg.unterminated.string.lit"
1864 "unterminated string literal")
1865
1866 (js2-msg "msg.unterminated.comment"
1867 "unterminated comment")
1868
1869 (js2-msg "msg.unterminated.re.lit"
1870 "unterminated regular expression literal")
1871
1872 (js2-msg "msg.invalid.re.flag"
1873 "invalid flag after regular expression")
1874
1875 (js2-msg "msg.no.re.input.for"
1876 "no input for %s")
1877
1878 (js2-msg "msg.illegal.character"
1879 "illegal character")
1880
1881 (js2-msg "msg.invalid.escape"
1882 "invalid Unicode escape sequence")
1883
1884 (js2-msg "msg.bad.namespace"
1885 "not a valid default namespace statement. "
1886 "Syntax is: default xml namespace = EXPRESSION;")
1887
1888 ;; TokensStream warnings
1889 (js2-msg "msg.bad.octal.literal"
1890 "illegal octal literal digit %s; "
1891 "interpreting it as a decimal digit")
1892
1893 (js2-msg "msg.reserved.keyword"
1894 "illegal usage of future reserved keyword %s; "
1895 "interpreting it as ordinary identifier")
1896
1897 (js2-msg "msg.script.is.not.constructor"
1898 "Script objects are not constructors.")
1899
1900 ;; Arrays
1901 (js2-msg "msg.arraylength.bad"
1902 "Inappropriate array length.")
1903
1904 ;; Arrays
1905 (js2-msg "msg.arraylength.too.big"
1906 "Array length %s exceeds supported capacity limit.")
1907
1908 ;; URI
1909 (js2-msg "msg.bad.uri"
1910 "Malformed URI sequence.")
1911
1912 ;; Number
1913 (js2-msg "msg.bad.precision"
1914 "Precision %s out of range.")
1915
1916 ;; NativeGenerator
1917 (js2-msg "msg.send.newborn"
1918 "Attempt to send value to newborn generator")
1919
1920 (js2-msg "msg.already.exec.gen"
1921 "Already executing generator")
1922
1923 (js2-msg "msg.StopIteration.invalid"
1924 "StopIteration may not be changed to an arbitrary object.")
1925
1926 ;; Interpreter
1927 (js2-msg "msg.yield.closing"
1928 "Yield from closing generator")
1929
1930 ;;; Utilities
1931
1932 (defun js2-delete-if (predicate list)
1933 "Remove all items satisfying PREDICATE in LIST."
1934 (loop for item in list
1935 if (not (funcall predicate item))
1936 collect item))
1937
1938 (defun js2-position (element list)
1939 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1940 Returns nil if element is not found in the list."
1941 (let ((count 0)
1942 found)
1943 (while (and list (not found))
1944 (if (eq element (car list))
1945 (setq found t)
1946 (setq count (1+ count)
1947 list (cdr list))))
1948 (if found count)))
1949
1950 (defun js2-find-if (predicate list)
1951 "Find first item satisfying PREDICATE in LIST."
1952 (let (result)
1953 (while (and list (not result))
1954 (if (funcall predicate (car list))
1955 (setq result (car list)))
1956 (setq list (cdr list)))
1957 result))
1958
1959 (defmacro js2-time (form)
1960 "Evaluate FORM, discard result, and return elapsed time in sec."
1961 (declare (debug t))
1962 (let ((beg (make-symbol "--js2-time-beg--"))
1963 (delta (make-symbol "--js2-time-end--")))
1964 `(let ((,beg (current-time))
1965 ,delta)
1966 ,form
1967 (/ (truncate (* (- (float-time (current-time))
1968 (float-time ,beg))
1969 10000))
1970 10000.0))))
1971
1972 (defsubst js2-same-line (pos)
1973 "Return t if POS is on the same line as current point."
1974 (and (>= pos (point-at-bol))
1975 (<= pos (point-at-eol))))
1976
1977 (defun js2-code-bug ()
1978 "Signal an error when we encounter an unexpected code path."
1979 (error "failed assertion"))
1980
1981 (defsubst js2-record-text-property (beg end prop value)
1982 "Record a text property to set when parsing finishes."
1983 (push (list beg end prop value) js2-mode-deferred-properties))
1984
1985 ;; I'd like to associate errors with nodes, but for now the
1986 ;; easiest thing to do is get the context info from the last token.
1987 (defun js2-record-parse-error (msg &optional arg pos len)
1988 (push (list (list msg arg)
1989 (or pos js2-token-beg)
1990 (or len (- js2-token-end js2-token-beg)))
1991 js2-parsed-errors))
1992
1993 (defun js2-report-error (msg &optional msg-arg pos len)
1994 "Signal a syntax error or record a parse error."
1995 (if js2-recover-from-parse-errors
1996 (js2-record-parse-error msg msg-arg pos len)
1997 (signal 'js2-syntax-error
1998 (list msg
1999 js2-ts-lineno
2000 (save-excursion
2001 (goto-char js2-ts-cursor)
2002 (current-column))
2003 js2-ts-hit-eof))))
2004
2005 (defun js2-report-warning (msg &optional msg-arg pos len face)
2006 (if js2-compiler-report-warning-as-error
2007 (js2-report-error msg msg-arg pos len)
2008 (push (list (list msg msg-arg)
2009 (or pos js2-token-beg)
2010 (or len (- js2-token-end js2-token-beg))
2011 face)
2012 js2-parsed-warnings)))
2013
2014 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2015 (if js2-compiler-strict-mode
2016 (js2-report-warning msg-id msg-arg beg
2017 (and beg end (- end beg)))))
2018
2019 (put 'js2-syntax-error 'error-conditions
2020 '(error syntax-error js2-syntax-error))
2021 (put 'js2-syntax-error 'error-message "Syntax error")
2022
2023 (put 'js2-parse-error 'error-conditions
2024 '(error parse-error js2-parse-error))
2025 (put 'js2-parse-error 'error-message "Parse error")
2026
2027 (defmacro js2-clear-flag (flags flag)
2028 `(setq ,flags (logand ,flags (lognot ,flag))))
2029
2030 (defmacro js2-set-flag (flags flag)
2031 "Logical-or FLAG into FLAGS."
2032 `(setq ,flags (logior ,flags ,flag)))
2033
2034 (defsubst js2-flag-set-p (flags flag)
2035 (/= 0 (logand flags flag)))
2036
2037 (defsubst js2-flag-not-set-p (flags flag)
2038 (zerop (logand flags flag)))
2039
2040 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2041 "Evaluate BODY with the _ character set to be word-syntax."
2042 (declare (indent 0) (debug t))
2043 (let ((old-syntax (make-symbol "old-syntax")))
2044 `(let ((,old-syntax (string (char-syntax ?_))))
2045 (unwind-protect
2046 (progn
2047 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2048 ,@body)
2049 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2050
2051 (defsubst js2-char-uppercase-p (c)
2052 "Return t if C is an uppercase character.
2053 Handles unicode and latin chars properly."
2054 (/= c (downcase c)))
2055
2056 (defsubst js2-char-lowercase-p (c)
2057 "Return t if C is an uppercase character.
2058 Handles unicode and latin chars properly."
2059 (/= c (upcase c)))
2060
2061 ;;; AST struct and function definitions
2062
2063 ;; flags for ast node property 'member-type (used for e4x operators)
2064 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2065 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2066 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2067
2068 (defsubst js2-relpos (pos anchor)
2069 "Convert POS to be relative to ANCHOR.
2070 If POS is nil, returns nil."
2071 (and pos (- pos anchor)))
2072
2073 (defun js2-make-pad (indent)
2074 (if (zerop indent)
2075 ""
2076 (make-string (* indent js2-basic-offset) ? )))
2077
2078 (defun js2-visit-ast (node callback)
2079 "Visit every node in ast NODE with visitor CALLBACK.
2080
2081 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2082 called twice: once to visit the node, and again after all the node's
2083 children have been processed. The END-P argument is nil on the first
2084 call and non-nil on the second call. The return value of the callback
2085 affects the traversal: if non-nil, the children of NODE are processed.
2086 If the callback returns nil, or if the node has no children, then the
2087 callback is called immediately with a non-nil END-P argument.
2088
2089 The node traversal is approximately lexical-order, although there
2090 are currently no guarantees around this."
2091 (when node
2092 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2093 ;; visit the node
2094 (when (funcall callback node nil)
2095 ;; visit the kids
2096 (cond
2097 ((eq vfunc 'js2-visit-none)
2098 nil) ; don't even bother calling it
2099 ;; Each AST node type has to define a `js2-visitor' function
2100 ;; that takes a node and a callback, and calls `js2-visit-ast'
2101 ;; on each child of the node.
2102 (vfunc
2103 (funcall vfunc node callback))
2104 (t
2105 (error "%s does not define a visitor-traversal function"
2106 (aref node 0)))))
2107 ;; call the end-visit
2108 (funcall callback node t))))
2109
2110 (defstruct (js2-node
2111 (:constructor nil)) ; abstract
2112 "Base AST node type."
2113 (type -1) ; token type
2114 (pos -1) ; start position of this AST node in parsed input
2115 (len 1) ; num characters spanned by the node
2116 props ; optional node property list (an alist)
2117 parent) ; link to parent node; null for root
2118
2119 (defsubst js2-node-get-prop (node prop &optional default)
2120 (or (cadr (assoc prop (js2-node-props node))) default))
2121
2122 (defsubst js2-node-set-prop (node prop value)
2123 (setf (js2-node-props node)
2124 (cons (list prop value) (js2-node-props node))))
2125
2126 (defun js2-fixup-starts (n nodes)
2127 "Adjust the start positions of NODES to be relative to N.
2128 Any node in the list may be nil, for convenience."
2129 (dolist (node nodes)
2130 (when node
2131 (setf (js2-node-pos node) (- (js2-node-pos node)
2132 (js2-node-pos n))))))
2133
2134 (defun js2-node-add-children (parent &rest nodes)
2135 "Set parent node of NODES to PARENT, and return PARENT.
2136 Does nothing if we're not recording parent links.
2137 If any given node in NODES is nil, doesn't record that link."
2138 (js2-fixup-starts parent nodes)
2139 (dolist (node nodes)
2140 (and node
2141 (setf (js2-node-parent node) parent))))
2142
2143 ;; Non-recursive since it's called a frightening number of times.
2144 (defun js2-node-abs-pos (n)
2145 (let ((pos (js2-node-pos n)))
2146 (while (setq n (js2-node-parent n))
2147 (setq pos (+ pos (js2-node-pos n))))
2148 pos))
2149
2150 (defsubst js2-node-abs-end (n)
2151 "Return absolute buffer position of end of N."
2152 (+ (js2-node-abs-pos n) (js2-node-len n)))
2153
2154 ;; It's important to make sure block nodes have a Lisp list for the
2155 ;; child nodes, to limit printing recursion depth in an AST that
2156 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2157 ;; a sufficiently large vector tree.
2158
2159 (defstruct (js2-block-node
2160 (:include js2-node)
2161 (:constructor nil)
2162 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2163 (pos js2-token-beg)
2164 len
2165 props
2166 kids)))
2167 "A block of statements."
2168 kids) ; a Lisp list of the child statement nodes
2169
2170 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2171 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2172
2173 (defun js2-visit-block (ast callback)
2174 "Visit the `js2-block-node' children of AST."
2175 (dolist (kid (js2-block-node-kids ast))
2176 (js2-visit-ast kid callback)))
2177
2178 (defun js2-print-block (n i)
2179 (let ((pad (js2-make-pad i)))
2180 (insert pad "{\n")
2181 (dolist (kid (js2-block-node-kids n))
2182 (js2-print-ast kid (1+ i)))
2183 (insert pad "}")))
2184
2185 (defstruct (js2-scope
2186 (:include js2-block-node)
2187 (:constructor nil)
2188 (:constructor make-js2-scope (&key (type js2-BLOCK)
2189 (pos js2-token-beg)
2190 len
2191 kids)))
2192 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2193 ;; I don't have one of those handy, so I'll use an alist for now.
2194 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2195 ;; and is much lighter-weight to construct (both CPU and mem).
2196 ;; The keys are interned strings (symbols) for faster lookup.
2197 ;; Should switch to hybrid alist/hashtable eventually.
2198 symbol-table ; an alist of (symbol . js2-symbol)
2199 parent-scope ; a `js2-scope'
2200 top) ; top-level `js2-scope' (script/function)
2201
2202 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2203 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2204
2205 (defun js2-node-get-enclosing-scope (node)
2206 "Return the innermost `js2-scope' node surrounding NODE.
2207 Returns nil if there is no enclosing scope node."
2208 (let ((parent (js2-node-parent node)))
2209 (while (not (js2-scope-p parent))
2210 (setq parent (js2-node-parent parent)))
2211 parent))
2212
2213 (defun js2-get-defining-scope (scope name)
2214 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2215 Returns `js2-scope' in which NAME is defined, or nil if not found."
2216 (let ((sym (if (symbolp name)
2217 name
2218 (intern name)))
2219 table
2220 result
2221 (continue t))
2222 (while (and scope continue)
2223 (if (and (setq table (js2-scope-symbol-table scope))
2224 (assq sym table))
2225 (setq continue nil
2226 result scope)
2227 (setq scope (js2-scope-parent-scope scope))))
2228 result))
2229
2230 (defun js2-scope-get-symbol (scope name)
2231 "Return symbol table entry for NAME in SCOPE.
2232 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2233 (and (js2-scope-symbol-table scope)
2234 (cdr (assq (if (symbolp name)
2235 name
2236 (intern name))
2237 (js2-scope-symbol-table scope)))))
2238
2239 (defun js2-scope-put-symbol (scope name symbol)
2240 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2241 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2242 (let* ((table (js2-scope-symbol-table scope))
2243 (sym (if (symbolp name) name (intern name)))
2244 (entry (assq sym table)))
2245 (if entry
2246 (setcdr entry symbol)
2247 (push (cons sym symbol)
2248 (js2-scope-symbol-table scope)))))
2249
2250 (defstruct (js2-symbol
2251 (:constructor nil)
2252 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2253 "A symbol table entry."
2254 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2255 ;; js2-LET, or js2-CONST
2256 decl-type
2257 name ; string
2258 ast-node) ; a `js2-node'
2259
2260 (defstruct (js2-error-node
2261 (:include js2-node)
2262 (:constructor nil) ; silence emacs21 byte-compiler
2263 (:constructor make-js2-error-node (&key (type js2-ERROR)
2264 (pos js2-token-beg)
2265 len)))
2266 "AST node representing a parse error.")
2267
2268 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2269 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2270
2271 (defstruct (js2-script-node
2272 (:include js2-scope)
2273 (:constructor nil)
2274 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2275 (pos js2-token-beg)
2276 len
2277 var-decls
2278 fun-decls)))
2279 functions ; Lisp list of nested functions
2280 regexps ; Lisp list of (string . flags)
2281 symbols ; alist (every symbol gets unique index)
2282 (param-count 0)
2283 var-names ; vector of string names
2284 consts ; bool-vector matching var-decls
2285 (temp-number 0)) ; for generating temp variables
2286
2287 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2288 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2289
2290 (defun js2-print-script (node indent)
2291 (dolist (kid (js2-block-node-kids node))
2292 (js2-print-ast kid indent)))
2293
2294 (defstruct (js2-ast-root
2295 (:include js2-script-node)
2296 (:constructor nil)
2297 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2298 (pos js2-token-beg)
2299 len
2300 buffer)))
2301 "The root node of a js2 AST."
2302 buffer ; the source buffer from which the code was parsed
2303 comments ; a Lisp list of comments, ordered by start position
2304 errors ; a Lisp list of errors found during parsing
2305 warnings ; a Lisp list of warnings found during parsing
2306 node-count) ; number of nodes in the tree, including the root
2307
2308 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2309 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2310
2311 (defun js2-visit-ast-root (ast callback)
2312 (dolist (kid (js2-ast-root-kids ast))
2313 (js2-visit-ast kid callback))
2314 (dolist (comment (js2-ast-root-comments ast))
2315 (js2-visit-ast comment callback)))
2316
2317 (defstruct (js2-comment-node
2318 (:include js2-node)
2319 (:constructor nil)
2320 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2321 (pos js2-token-beg)
2322 len
2323 (format js2-ts-comment-type))))
2324 format) ; 'line, 'block, 'jsdoc or 'html
2325
2326 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2327 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2328
2329 (defun js2-print-comment (n i)
2330 ;; We really ought to link end-of-line comments to their nodes.
2331 ;; Or maybe we could add a new comment type, 'endline.
2332 (insert (js2-make-pad i)
2333 (js2-node-string n)))
2334
2335 (defstruct (js2-expr-stmt-node
2336 (:include js2-node)
2337 (:constructor nil)
2338 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2339 (pos js2-ts-cursor)
2340 len
2341 expr)))
2342 "An expression statement."
2343 expr)
2344
2345 (defsubst js2-expr-stmt-node-set-has-result (node)
2346 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2347 (setf (js2-node-type node) js2-EXPR_RESULT))
2348
2349 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2350 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2351
2352 (defun js2-visit-expr-stmt-node (n v)
2353 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2354
2355 (defun js2-print-expr-stmt-node (n indent)
2356 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2357 (insert ";\n"))
2358
2359 (defstruct (js2-loop-node
2360 (:include js2-scope)
2361 (:constructor nil))
2362 "Abstract supertype of loop nodes."
2363 body ; a `js2-block-node'
2364 lp ; position of left-paren, nil if omitted
2365 rp) ; position of right-paren, nil if omitted
2366
2367 (defstruct (js2-do-node
2368 (:include js2-loop-node)
2369 (:constructor nil)
2370 (:constructor make-js2-do-node (&key (type js2-DO)
2371 (pos js2-token-beg)
2372 len
2373 body
2374 condition
2375 while-pos
2376 lp
2377 rp)))
2378 "AST node for do-loop."
2379 condition ; while (expression)
2380 while-pos) ; buffer position of 'while' keyword
2381
2382 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2383 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2384
2385 (defun js2-visit-do-node (n v)
2386 (js2-visit-ast (js2-do-node-body n) v)
2387 (js2-visit-ast (js2-do-node-condition n) v))
2388
2389 (defun js2-print-do-node (n i)
2390 (let ((pad (js2-make-pad i)))
2391 (insert pad "do {\n")
2392 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2393 (js2-print-ast kid (1+ i)))
2394 (insert pad "} while (")
2395 (js2-print-ast (js2-do-node-condition n) 0)
2396 (insert ");\n")))
2397
2398 (defstruct (js2-while-node
2399 (:include js2-loop-node)
2400 (:constructor nil)
2401 (:constructor make-js2-while-node (&key (type js2-WHILE)
2402 (pos js2-token-beg)
2403 len body
2404 condition lp
2405 rp)))
2406 "AST node for while-loop."
2407 condition) ; while-condition
2408
2409 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2410 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2411
2412 (defun js2-visit-while-node (n v)
2413 (js2-visit-ast (js2-while-node-condition n) v)
2414 (js2-visit-ast (js2-while-node-body n) v))
2415
2416 (defun js2-print-while-node (n i)
2417 (let ((pad (js2-make-pad i)))
2418 (insert pad "while (")
2419 (js2-print-ast (js2-while-node-condition n) 0)
2420 (insert ") {\n")
2421 (js2-print-body (js2-while-node-body n) (1+ i))
2422 (insert pad "}\n")))
2423
2424 (defstruct (js2-for-node
2425 (:include js2-loop-node)
2426 (:constructor nil)
2427 (:constructor make-js2-for-node (&key (type js2-FOR)
2428 (pos js2-ts-cursor)
2429 len body init
2430 condition
2431 update lp rp)))
2432 "AST node for a C-style for-loop."
2433 init ; initialization expression
2434 condition ; loop condition
2435 update) ; update clause
2436
2437 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2438 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2439
2440 (defun js2-visit-for-node (n v)
2441 (js2-visit-ast (js2-for-node-init n) v)
2442 (js2-visit-ast (js2-for-node-condition n) v)
2443 (js2-visit-ast (js2-for-node-update n) v)
2444 (js2-visit-ast (js2-for-node-body n) v))
2445
2446 (defun js2-print-for-node (n i)
2447 (let ((pad (js2-make-pad i)))
2448 (insert pad "for (")
2449 (js2-print-ast (js2-for-node-init n) 0)
2450 (insert "; ")
2451 (js2-print-ast (js2-for-node-condition n) 0)
2452 (insert "; ")
2453 (js2-print-ast (js2-for-node-update n) 0)
2454 (insert ") {\n")
2455 (js2-print-body (js2-for-node-body n) (1+ i))
2456 (insert pad "}\n")))
2457
2458 (defstruct (js2-for-in-node
2459 (:include js2-loop-node)
2460 (:constructor nil)
2461 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2462 (pos js2-ts-cursor)
2463 len body
2464 iterator
2465 object
2466 in-pos
2467 each-pos
2468 foreach-p forof-p
2469 lp rp)))
2470 "AST node for a for..in loop."
2471 iterator ; [var] foo in ...
2472 object ; object over which we're iterating
2473 in-pos ; buffer position of 'in' keyword
2474 each-pos ; buffer position of 'each' keyword, if foreach-p
2475 foreach-p ; t if it's a for-each loop
2476 forof-p) ; t if it's a for-of loop
2477
2478 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2479 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2480
2481 (defun js2-visit-for-in-node (n v)
2482 (js2-visit-ast (js2-for-in-node-iterator n) v)
2483 (js2-visit-ast (js2-for-in-node-object n) v)
2484 (js2-visit-ast (js2-for-in-node-body n) v))
2485
2486 (defun js2-print-for-in-node (n i)
2487 (let ((pad (js2-make-pad i))
2488 (foreach (js2-for-in-node-foreach-p n))
2489 (forof (js2-for-in-node-forof-p n)))
2490 (insert pad "for ")
2491 (if foreach
2492 (insert "each "))
2493 (insert "(")
2494 (js2-print-ast (js2-for-in-node-iterator n) 0)
2495 (if forof
2496 (insert " of ")
2497 (insert " in "))
2498 (js2-print-ast (js2-for-in-node-object n) 0)
2499 (insert ") {\n")
2500 (js2-print-body (js2-for-in-node-body n) (1+ i))
2501 (insert pad "}\n")))
2502
2503 (defstruct (js2-return-node
2504 (:include js2-node)
2505 (:constructor nil)
2506 (:constructor make-js2-return-node (&key (type js2-RETURN)
2507 (pos js2-ts-cursor)
2508 len
2509 retval)))
2510 "AST node for a return statement."
2511 retval) ; expression to return, or 'undefined
2512
2513 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2514 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2515
2516 (defun js2-visit-return-node (n v)
2517 (js2-visit-ast (js2-return-node-retval n) v))
2518
2519 (defun js2-print-return-node (n i)
2520 (insert (js2-make-pad i) "return")
2521 (when (js2-return-node-retval n)
2522 (insert " ")
2523 (js2-print-ast (js2-return-node-retval n) 0))
2524 (insert ";\n"))
2525
2526 (defstruct (js2-if-node
2527 (:include js2-node)
2528 (:constructor nil)
2529 (:constructor make-js2-if-node (&key (type js2-IF)
2530 (pos js2-ts-cursor)
2531 len condition
2532 then-part
2533 else-pos
2534 else-part lp
2535 rp)))
2536 "AST node for an if-statement."
2537 condition ; expression
2538 then-part ; statement or block
2539 else-pos ; optional buffer position of 'else' keyword
2540 else-part ; optional statement or block
2541 lp ; position of left-paren, nil if omitted
2542 rp) ; position of right-paren, nil if omitted
2543
2544 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2545 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2546
2547 (defun js2-visit-if-node (n v)
2548 (js2-visit-ast (js2-if-node-condition n) v)
2549 (js2-visit-ast (js2-if-node-then-part n) v)
2550 (js2-visit-ast (js2-if-node-else-part n) v))
2551
2552 (defun js2-print-if-node (n i)
2553 (let ((pad (js2-make-pad i))
2554 (then-part (js2-if-node-then-part n))
2555 (else-part (js2-if-node-else-part n)))
2556 (insert pad "if (")
2557 (js2-print-ast (js2-if-node-condition n) 0)
2558 (insert ") {\n")
2559 (js2-print-body then-part (1+ i))
2560 (insert pad "}")
2561 (cond
2562 ((not else-part)
2563 (insert "\n"))
2564 ((js2-if-node-p else-part)
2565 (insert " else ")
2566 (js2-print-body else-part i))
2567 (t
2568 (insert " else {\n")
2569 (js2-print-body else-part (1+ i))
2570 (insert pad "}\n")))))
2571
2572 (defstruct (js2-try-node
2573 (:include js2-node)
2574 (:constructor nil)
2575 (:constructor make-js2-try-node (&key (type js2-TRY)
2576 (pos js2-ts-cursor)
2577 len
2578 try-block
2579 catch-clauses
2580 finally-block)))
2581 "AST node for a try-statement."
2582 try-block
2583 catch-clauses ; a Lisp list of `js2-catch-node'
2584 finally-block) ; a `js2-finally-node'
2585
2586 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2587 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2588
2589 (defun js2-visit-try-node (n v)
2590 (js2-visit-ast (js2-try-node-try-block n) v)
2591 (dolist (clause (js2-try-node-catch-clauses n))
2592 (js2-visit-ast clause v))
2593 (js2-visit-ast (js2-try-node-finally-block n) v))
2594
2595 (defun js2-print-try-node (n i)
2596 (let ((pad (js2-make-pad i))
2597 (catches (js2-try-node-catch-clauses n))
2598 (finally (js2-try-node-finally-block n)))
2599 (insert pad "try {\n")
2600 (js2-print-body (js2-try-node-try-block n) (1+ i))
2601 (insert pad "}")
2602 (when catches
2603 (dolist (catch catches)
2604 (js2-print-ast catch i)))
2605 (if finally
2606 (js2-print-ast finally i)
2607 (insert "\n"))))
2608
2609 (defstruct (js2-catch-node
2610 (:include js2-node)
2611 (:constructor nil)
2612 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2613 (pos js2-ts-cursor)
2614 len
2615 param
2616 guard-kwd
2617 guard-expr
2618 block lp
2619 rp)))
2620 "AST node for a catch clause."
2621 param ; destructuring form or simple name node
2622 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2623 guard-expr ; catch condition, a `js2-node'
2624 block ; statements, a `js2-block-node'
2625 lp ; buffer position of left-paren, nil if omitted
2626 rp) ; buffer position of right-paren, nil if omitted
2627
2628 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2629 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2630
2631 (defun js2-visit-catch-node (n v)
2632 (js2-visit-ast (js2-catch-node-param n) v)
2633 (when (js2-catch-node-guard-kwd n)
2634 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2635 (js2-visit-ast (js2-catch-node-block n) v))
2636
2637 (defun js2-print-catch-node (n i)
2638 (let ((pad (js2-make-pad i))
2639 (guard-kwd (js2-catch-node-guard-kwd n))
2640 (guard-expr (js2-catch-node-guard-expr n)))
2641 (insert " catch (")
2642 (js2-print-ast (js2-catch-node-param n) 0)
2643 (when guard-kwd
2644 (insert " if ")
2645 (js2-print-ast guard-expr 0))
2646 (insert ") {\n")
2647 (js2-print-body (js2-catch-node-block n) (1+ i))
2648 (insert pad "}")))
2649
2650 (defstruct (js2-finally-node
2651 (:include js2-node)
2652 (:constructor nil)
2653 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2654 (pos js2-ts-cursor)
2655 len body)))
2656 "AST node for a finally clause."
2657 body) ; a `js2-node', often but not always a block node
2658
2659 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2660 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2661
2662 (defun js2-visit-finally-node (n v)
2663 (js2-visit-ast (js2-finally-node-body n) v))
2664
2665 (defun js2-print-finally-node (n i)
2666 (let ((pad (js2-make-pad i)))
2667 (insert " finally {\n")
2668 (js2-print-body (js2-finally-node-body n) (1+ i))
2669 (insert pad "}\n")))
2670
2671 (defstruct (js2-switch-node
2672 (:include js2-node)
2673 (:constructor nil)
2674 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2675 (pos js2-ts-cursor)
2676 len
2677 discriminant
2678 cases lp
2679 rp)))
2680 "AST node for a switch statement."
2681 discriminant ; a `js2-node' (switch expression)
2682 cases ; a Lisp list of `js2-case-node'
2683 lp ; position of open-paren for discriminant, nil if omitted
2684 rp) ; position of close-paren for discriminant, nil if omitted
2685
2686 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2687 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2688
2689 (defun js2-visit-switch-node (n v)
2690 (js2-visit-ast (js2-switch-node-discriminant n) v)
2691 (dolist (c (js2-switch-node-cases n))
2692 (js2-visit-ast c v)))
2693
2694 (defun js2-print-switch-node (n i)
2695 (let ((pad (js2-make-pad i))
2696 (cases (js2-switch-node-cases n)))
2697 (insert pad "switch (")
2698 (js2-print-ast (js2-switch-node-discriminant n) 0)
2699 (insert ") {\n")
2700 (dolist (case cases)
2701 (js2-print-ast case i))
2702 (insert pad "}\n")))
2703
2704 (defstruct (js2-case-node
2705 (:include js2-block-node)
2706 (:constructor nil)
2707 (:constructor make-js2-case-node (&key (type js2-CASE)
2708 (pos js2-ts-cursor)
2709 len kids expr)))
2710 "AST node for a case clause of a switch statement."
2711 expr) ; the case expression (nil for default)
2712
2713 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2714 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2715
2716 (defun js2-visit-case-node (n v)
2717 (js2-visit-ast (js2-case-node-expr n) v)
2718 (js2-visit-block n v))
2719
2720 (defun js2-print-case-node (n i)
2721 (let ((pad (js2-make-pad i))
2722 (expr (js2-case-node-expr n)))
2723 (insert pad)
2724 (if (null expr)
2725 (insert "default:\n")
2726 (insert "case ")
2727 (js2-print-ast expr 0)
2728 (insert ":\n"))
2729 (dolist (kid (js2-case-node-kids n))
2730 (js2-print-ast kid (1+ i)))))
2731
2732 (defstruct (js2-throw-node
2733 (:include js2-node)
2734 (:constructor nil)
2735 (:constructor make-js2-throw-node (&key (type js2-THROW)
2736 (pos js2-ts-cursor)
2737 len expr)))
2738 "AST node for a throw statement."
2739 expr) ; the expression to throw
2740
2741 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2742 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2743
2744 (defun js2-visit-throw-node (n v)
2745 (js2-visit-ast (js2-throw-node-expr n) v))
2746
2747 (defun js2-print-throw-node (n i)
2748 (insert (js2-make-pad i) "throw ")
2749 (js2-print-ast (js2-throw-node-expr n) 0)
2750 (insert ";\n"))
2751
2752 (defstruct (js2-with-node
2753 (:include js2-node)
2754 (:constructor nil)
2755 (:constructor make-js2-with-node (&key (type js2-WITH)
2756 (pos js2-ts-cursor)
2757 len object
2758 body lp rp)))
2759 "AST node for a with-statement."
2760 object
2761 body
2762 lp ; buffer position of left-paren around object, nil if omitted
2763 rp) ; buffer position of right-paren around object, nil if omitted
2764
2765 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2766 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2767
2768 (defun js2-visit-with-node (n v)
2769 (js2-visit-ast (js2-with-node-object n) v)
2770 (js2-visit-ast (js2-with-node-body n) v))
2771
2772 (defun js2-print-with-node (n i)
2773 (let ((pad (js2-make-pad i)))
2774 (insert pad "with (")
2775 (js2-print-ast (js2-with-node-object n) 0)
2776 (insert ") {\n")
2777 (js2-print-body (js2-with-node-body n) (1+ i))
2778 (insert pad "}\n")))
2779
2780 (defstruct (js2-label-node
2781 (:include js2-node)
2782 (:constructor nil)
2783 (:constructor make-js2-label-node (&key (type js2-LABEL)
2784 (pos js2-ts-cursor)
2785 len name)))
2786 "AST node for a statement label or case label."
2787 name ; a string
2788 loop) ; for validating and code-generating continue-to-label
2789
2790 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2791 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2792
2793 (defun js2-print-label (n i)
2794 (insert (js2-make-pad i)
2795 (js2-label-node-name n)
2796 ":\n"))
2797
2798 (defstruct (js2-labeled-stmt-node
2799 (:include js2-node)
2800 (:constructor nil)
2801 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2802 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2803 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2804 (pos js2-ts-cursor)
2805 len labels stmt)))
2806 "AST node for a statement with one or more labels.
2807 Multiple labels for a statement are collapsed into the labels field."
2808 labels ; Lisp list of `js2-label-node'
2809 stmt) ; the statement these labels are for
2810
2811 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2812 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2813
2814 (defun js2-get-label-by-name (lbl-stmt name)
2815 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2816 Returns nil if no such label is in the list."
2817 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2818 result)
2819 (while (and label-list (not result))
2820 (if (string= (js2-label-node-name (car label-list)) name)
2821 (setq result (car label-list))
2822 (setq label-list (cdr label-list))))
2823 result))
2824
2825 (defun js2-visit-labeled-stmt (n v)
2826 (dolist (label (js2-labeled-stmt-node-labels n))
2827 (js2-visit-ast label v))
2828 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2829
2830 (defun js2-print-labeled-stmt (n i)
2831 (dolist (label (js2-labeled-stmt-node-labels n))
2832 (js2-print-ast label i))
2833 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2834
2835 (defun js2-labeled-stmt-node-contains (node label)
2836 "Return t if NODE contains LABEL in its label set.
2837 NODE is a `js2-labels-node'. LABEL is an identifier."
2838 (loop for nl in (js2-labeled-stmt-node-labels node)
2839 if (string= label (js2-label-node-name nl))
2840 return t
2841 finally return nil))
2842
2843 (defsubst js2-labeled-stmt-node-add-label (node label)
2844 "Add a `js2-label-node' to the label set for this statement."
2845 (setf (js2-labeled-stmt-node-labels node)
2846 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2847
2848 (defstruct (js2-jump-node
2849 (:include js2-node)
2850 (:constructor nil))
2851 "Abstract supertype of break and continue nodes."
2852 label ; `js2-name-node' for location of label identifier, if present
2853 target) ; target js2-labels-node or loop/switch statement
2854
2855 (defun js2-visit-jump-node (n v)
2856 ;; We don't visit the target, since it's a back-link.
2857 (js2-visit-ast (js2-jump-node-label n) v))
2858
2859 (defstruct (js2-break-node
2860 (:include js2-jump-node)
2861 (:constructor nil)
2862 (:constructor make-js2-break-node (&key (type js2-BREAK)
2863 (pos js2-ts-cursor)
2864 len label target)))
2865 "AST node for a break statement.
2866 The label field is a `js2-name-node', possibly nil, for the named label
2867 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2868 is the target of the break - a label node or enclosing loop/switch statement.")
2869
2870 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2871 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2872
2873 (defun js2-print-break-node (n i)
2874 (insert (js2-make-pad i) "break")
2875 (when (js2-break-node-label n)
2876 (insert " ")
2877 (js2-print-ast (js2-break-node-label n) 0))
2878 (insert ";\n"))
2879
2880 (defstruct (js2-continue-node
2881 (:include js2-jump-node)
2882 (:constructor nil)
2883 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2884 (pos js2-ts-cursor)
2885 len label target)))
2886 "AST node for a continue statement.
2887 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2888 It is nil if continue specifies no label. The target field is the jump target:
2889 a `js2-label-node' or the innermost enclosing loop.")
2890
2891 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2892 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2893
2894 (defun js2-print-continue-node (n i)
2895 (insert (js2-make-pad i) "continue")
2896 (when (js2-continue-node-label n)
2897 (insert " ")
2898 (js2-print-ast (js2-continue-node-label n) 0))
2899 (insert ";\n"))
2900
2901 (defstruct (js2-function-node
2902 (:include js2-script-node)
2903 (:constructor nil)
2904 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2905 (pos js2-ts-cursor)
2906 len
2907 (ftype 'FUNCTION)
2908 (form 'FUNCTION_STATEMENT)
2909 (name "")
2910 params rest-p
2911 body
2912 lp rp)))
2913 "AST node for a function declaration.
2914 The `params' field is a Lisp list of nodes. Each node is either a simple
2915 `js2-name-node', or if it's a destructuring-assignment parameter, a
2916 `js2-array-node' or `js2-object-node'."
2917 ftype ; FUNCTION, GETTER or SETTER
2918 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
2919 name ; function name (a `js2-name-node', or nil if anonymous)
2920 params ; a Lisp list of destructuring forms or simple name nodes
2921 rest-p ; if t, the last parameter is rest parameter
2922 body ; a `js2-block-node' or expression node (1.8 only)
2923 lp ; position of arg-list open-paren, or nil if omitted
2924 rp ; position of arg-list close-paren, or nil if omitted
2925 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2926 needs-activation ; t if we need an activation object for this frame
2927 is-generator ; t if this function contains a yield
2928 member-expr) ; nonstandard Ecma extension from Rhino
2929
2930 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2931 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2932
2933 (defun js2-visit-function-node (n v)
2934 (js2-visit-ast (js2-function-node-name n) v)
2935 (dolist (p (js2-function-node-params n))
2936 (js2-visit-ast p v))
2937 (js2-visit-ast (js2-function-node-body n) v))
2938
2939 (defun js2-print-function-node (n i)
2940 (let ((pad (js2-make-pad i))
2941 (getter (js2-node-get-prop n 'GETTER_SETTER))
2942 (name (js2-function-node-name n))
2943 (params (js2-function-node-params n))
2944 (rest-p (js2-function-node-rest-p n))
2945 (body (js2-function-node-body n))
2946 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
2947 (unless getter
2948 (insert pad "function"))
2949 (when name
2950 (insert " ")
2951 (js2-print-ast name 0))
2952 (insert "(")
2953 (loop with len = (length params)
2954 for param in params
2955 for count from 1
2956 do
2957 (when (and rest-p (= count len))
2958 (insert "..."))
2959 (js2-print-ast param 0)
2960 (when (< count len)
2961 (insert ", ")))
2962 (insert ") {")
2963 (unless expr
2964 (insert "\n"))
2965 ;; TODO: fix this to be smarter about indenting, etc.
2966 (js2-print-body body (1+ i))
2967 (insert pad "}")
2968 (unless expr
2969 (insert "\n"))))
2970
2971 (defun js2-function-name (node)
2972 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
2973 (and (js2-function-node-name node)
2974 (js2-name-node-name (js2-function-node-name node))))
2975
2976 ;; Having this be an expression node makes it more flexible.
2977 ;; There are IDE contexts, such as indentation in a for-loop initializer,
2978 ;; that work better if you assume it's an expression. Whenever we have
2979 ;; a standalone var/const declaration, we just wrap with an expr stmt.
2980 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
2981 (defstruct (js2-var-decl-node
2982 (:include js2-node)
2983 (:constructor nil)
2984 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
2985 (pos js2-token-beg)
2986 len kids
2987 decl-type)))
2988 "AST node for a variable declaration list (VAR, CONST or LET).
2989 The node bounds differ depending on the declaration type. For VAR or
2990 CONST declarations, the bounds include the var/const keyword. For LET
2991 declarations, the node begins at the position of the first child."
2992 kids ; a Lisp list of `js2-var-init-node' structs.
2993 decl-type) ; js2-VAR, js2-CONST or js2-LET
2994
2995 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
2996 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
2997
2998 (defun js2-visit-var-decl (n v)
2999 (dolist (kid (js2-var-decl-node-kids n))
3000 (js2-visit-ast kid v)))
3001
3002 (defun js2-print-var-decl (n i)
3003 (let ((pad (js2-make-pad i))
3004 (tt (js2-var-decl-node-decl-type n)))
3005 (insert pad)
3006 (insert (cond
3007 ((= tt js2-VAR) "var ")
3008 ((= tt js2-LET) "let ")
3009 ((= tt js2-CONST) "const ")
3010 (t
3011 (error "malformed var-decl node"))))
3012 (loop with kids = (js2-var-decl-node-kids n)
3013 with len = (length kids)
3014 for kid in kids
3015 for count from 1
3016 do
3017 (js2-print-ast kid 0)
3018 (if (< count len)
3019 (insert ", ")))))
3020
3021 (defstruct (js2-var-init-node
3022 (:include js2-node)
3023 (:constructor nil)
3024 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3025 (pos js2-ts-cursor)
3026 len target
3027 initializer)))
3028 "AST node for a variable declaration.
3029 The type field will be js2-CONST for a const decl."
3030 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3031 initializer) ; initializer expression, a `js2-node'
3032
3033 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3034 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3035
3036 (defun js2-visit-var-init-node (n v)
3037 (js2-visit-ast (js2-var-init-node-target n) v)
3038 (js2-visit-ast (js2-var-init-node-initializer n) v))
3039
3040 (defun js2-print-var-init-node (n i)
3041 (let ((pad (js2-make-pad i))
3042 (name (js2-var-init-node-target n))
3043 (init (js2-var-init-node-initializer n)))
3044 (insert pad)
3045 (js2-print-ast name 0)
3046 (when init
3047 (insert " = ")
3048 (js2-print-ast init 0))))
3049
3050 (defstruct (js2-cond-node
3051 (:include js2-node)
3052 (:constructor nil)
3053 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3054 (pos js2-ts-cursor)
3055 len
3056 test-expr
3057 true-expr
3058 false-expr
3059 q-pos c-pos)))
3060 "AST node for the ternary operator"
3061 test-expr
3062 true-expr
3063 false-expr
3064 q-pos ; buffer position of ?
3065 c-pos) ; buffer position of :
3066
3067 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3068 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3069
3070 (defun js2-visit-cond-node (n v)
3071 (js2-visit-ast (js2-cond-node-test-expr n) v)
3072 (js2-visit-ast (js2-cond-node-true-expr n) v)
3073 (js2-visit-ast (js2-cond-node-false-expr n) v))
3074
3075 (defun js2-print-cond-node (n i)
3076 (let ((pad (js2-make-pad i)))
3077 (insert pad)
3078 (js2-print-ast (js2-cond-node-test-expr n) 0)
3079 (insert " ? ")
3080 (js2-print-ast (js2-cond-node-true-expr n) 0)
3081 (insert " : ")
3082 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3083
3084 (defstruct (js2-infix-node
3085 (:include js2-node)
3086 (:constructor nil)
3087 (:constructor make-js2-infix-node (&key type
3088 (pos js2-ts-cursor)
3089 len op-pos
3090 left right)))
3091 "Represents infix expressions.
3092 Includes assignment ops like `|=', and the comma operator.
3093 The type field inherited from `js2-node' holds the operator."
3094 op-pos ; buffer position where operator begins
3095 left ; any `js2-node'
3096 right) ; any `js2-node'
3097
3098 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3099 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3100
3101 (defun js2-visit-infix-node (n v)
3102 (js2-visit-ast (js2-infix-node-left n) v)
3103 (js2-visit-ast (js2-infix-node-right n) v))
3104
3105 (defconst js2-operator-tokens
3106 (let ((table (make-hash-table :test 'eq))
3107 (tokens
3108 (list (cons js2-IN "in")
3109 (cons js2-TYPEOF "typeof")
3110 (cons js2-INSTANCEOF "instanceof")
3111 (cons js2-DELPROP "delete")
3112 (cons js2-COMMA ",")
3113 (cons js2-COLON ":")
3114 (cons js2-OR "||")
3115 (cons js2-AND "&&")
3116 (cons js2-INC "++")
3117 (cons js2-DEC "--")
3118 (cons js2-BITOR "|")
3119 (cons js2-BITXOR "^")
3120 (cons js2-BITAND "&")
3121 (cons js2-EQ "==")
3122 (cons js2-NE "!=")
3123 (cons js2-LT "<")
3124 (cons js2-LE "<=")
3125 (cons js2-GT ">")
3126 (cons js2-GE ">=")
3127 (cons js2-LSH "<<")
3128 (cons js2-RSH ">>")
3129 (cons js2-URSH ">>>")
3130 (cons js2-ADD "+") ; infix plus
3131 (cons js2-SUB "-") ; infix minus
3132 (cons js2-MUL "*")
3133 (cons js2-DIV "/")
3134 (cons js2-MOD "%")
3135 (cons js2-NOT "!")
3136 (cons js2-BITNOT "~")
3137 (cons js2-POS "+") ; unary plus
3138 (cons js2-NEG "-") ; unary minus
3139 (cons js2-SHEQ "===") ; shallow equality
3140 (cons js2-SHNE "!==") ; shallow inequality
3141 (cons js2-ASSIGN "=")
3142 (cons js2-ASSIGN_BITOR "|=")
3143 (cons js2-ASSIGN_BITXOR "^=")
3144 (cons js2-ASSIGN_BITAND "&=")
3145 (cons js2-ASSIGN_LSH "<<=")
3146 (cons js2-ASSIGN_RSH ">>=")
3147 (cons js2-ASSIGN_URSH ">>>=")
3148 (cons js2-ASSIGN_ADD "+=")
3149 (cons js2-ASSIGN_SUB "-=")
3150 (cons js2-ASSIGN_MUL "*=")
3151 (cons js2-ASSIGN_DIV "/=")
3152 (cons js2-ASSIGN_MOD "%="))))
3153 (loop for (k . v) in tokens do
3154 (puthash k v table))
3155 table))
3156
3157 (defun js2-print-infix-node (n i)
3158 (let* ((tt (js2-node-type n))
3159 (op (gethash tt js2-operator-tokens)))
3160 (unless op
3161 (error "unrecognized infix operator %s" (js2-node-type n)))
3162 (insert (js2-make-pad i))
3163 (js2-print-ast (js2-infix-node-left n) 0)
3164 (unless (= tt js2-COMMA)
3165 (insert " "))
3166 (insert op)
3167 (insert " ")
3168 (js2-print-ast (js2-infix-node-right n) 0)))
3169
3170 (defstruct (js2-assign-node
3171 (:include js2-infix-node)
3172 (:constructor nil)
3173 (:constructor make-js2-assign-node (&key type
3174 (pos js2-ts-cursor)
3175 len op-pos
3176 left right)))
3177 "Represents any assignment.
3178 The type field holds the actual assignment operator.")
3179
3180 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3181 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3182
3183 (defstruct (js2-unary-node
3184 (:include js2-node)
3185 (:constructor nil)
3186 (:constructor make-js2-unary-node (&key type ; required
3187 (pos js2-ts-cursor)
3188 len operand)))
3189 "AST node type for unary operator nodes.
3190 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3191 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3192 property is added if the operator follows the operand."
3193 operand) ; a `js2-node' expression
3194
3195 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3196 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3197
3198 (defun js2-visit-unary-node (n v)
3199 (js2-visit-ast (js2-unary-node-operand n) v))
3200
3201 (defun js2-print-unary-node (n i)
3202 (let* ((tt (js2-node-type n))
3203 (op (gethash tt js2-operator-tokens))
3204 (postfix (js2-node-get-prop n 'postfix)))
3205 (unless op
3206 (error "unrecognized unary operator %s" tt))
3207 (insert (js2-make-pad i))
3208 (unless postfix
3209 (insert op))
3210 (if (or (= tt js2-TYPEOF)
3211 (= tt js2-DELPROP))
3212 (insert " "))
3213 (js2-print-ast (js2-unary-node-operand n) 0)
3214 (when postfix
3215 (insert op))))
3216
3217 (defstruct (js2-let-node
3218 (:include js2-scope)
3219 (:constructor nil)
3220 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3221 (pos js2-token-beg)
3222 len vars body
3223 lp rp)))
3224 "AST node for a let expression or a let statement.
3225 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3226 vars ; a `js2-var-decl-node'
3227 body ; a `js2-node' representing the expression or body block
3228 lp
3229 rp)
3230
3231 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3232 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3233
3234 (defun js2-visit-let-node (n v)
3235 (js2-visit-ast (js2-let-node-vars n) v)
3236 (js2-visit-ast (js2-let-node-body n) v))
3237
3238 (defun js2-print-let-node (n i)
3239 (insert (js2-make-pad i) "let (")
3240 (js2-print-ast (js2-let-node-vars n) 0)
3241 (insert ") ")
3242 (js2-print-ast (js2-let-node-body n) i))
3243
3244 (defstruct (js2-keyword-node
3245 (:include js2-node)
3246 (:constructor nil)
3247 (:constructor make-js2-keyword-node (&key type
3248 (pos js2-token-beg)
3249 (len (- js2-ts-cursor pos)))))
3250 "AST node representing a literal keyword such as `null'.
3251 Used for `null', `this', `true', `false' and `debugger'.
3252 The node type is set to js2-NULL, js2-THIS, etc.")
3253
3254 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3255 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3256
3257 (defun js2-print-keyword-node (n i)
3258 (insert (js2-make-pad i)
3259 (let ((tt (js2-node-type n)))
3260 (cond
3261 ((= tt js2-THIS) "this")
3262 ((= tt js2-NULL) "null")
3263 ((= tt js2-TRUE) "true")
3264 ((= tt js2-FALSE) "false")
3265 ((= tt js2-DEBUGGER) "debugger")
3266 (t (error "Invalid keyword literal type: %d" tt))))))
3267
3268 (defsubst js2-this-node-p (node)
3269 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3270 (eq (js2-node-type node) js2-THIS))
3271
3272 (defstruct (js2-new-node
3273 (:include js2-node)
3274 (:constructor nil)
3275 (:constructor make-js2-new-node (&key (type js2-NEW)
3276 (pos js2-token-beg)
3277 len target
3278 args initializer
3279 lp rp)))
3280 "AST node for new-expression such as new Foo()."
3281 target ; an identifier or reference
3282 args ; a Lisp list of argument nodes
3283 lp ; position of left-paren, nil if omitted
3284 rp ; position of right-paren, nil if omitted
3285 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3286
3287 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3288 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3289
3290 (defun js2-visit-new-node (n v)
3291 (js2-visit-ast (js2-new-node-target n) v)
3292 (dolist (arg (js2-new-node-args n))
3293 (js2-visit-ast arg v))
3294 (js2-visit-ast (js2-new-node-initializer n) v))
3295
3296 (defun js2-print-new-node (n i)
3297 (insert (js2-make-pad i) "new ")
3298 (js2-print-ast (js2-new-node-target n))
3299 (insert "(")
3300 (js2-print-list (js2-new-node-args n))
3301 (insert ")")
3302 (when (js2-new-node-initializer n)
3303 (insert " ")
3304 (js2-print-ast (js2-new-node-initializer n))))
3305
3306 (defstruct (js2-name-node
3307 (:include js2-node)
3308 (:constructor nil)
3309 (:constructor make-js2-name-node (&key (type js2-NAME)
3310 (pos js2-token-beg)
3311 (len (- js2-ts-cursor
3312 js2-token-beg))
3313 (name js2-ts-string))))
3314 "AST node for a JavaScript identifier"
3315 name ; a string
3316 scope) ; a `js2-scope' (optional, used for codegen)
3317
3318 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3319 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3320
3321 (defun js2-print-name-node (n i)
3322 (insert (js2-make-pad i)
3323 (js2-name-node-name n)))
3324
3325 (defsubst js2-name-node-length (node)
3326 "Return identifier length of NODE, a `js2-name-node'.
3327 Returns 0 if NODE is nil or its identifier field is nil."
3328 (if node
3329 (length (js2-name-node-name node))
3330 0))
3331
3332 (defstruct (js2-number-node
3333 (:include js2-node)
3334 (:constructor nil)
3335 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3336 (pos js2-token-beg)
3337 (len (- js2-ts-cursor
3338 js2-token-beg))
3339 (value js2-ts-string)
3340 (num-value js2-ts-number))))
3341 "AST node for a number literal."
3342 value ; the original string, e.g. "6.02e23"
3343 num-value) ; the parsed number value
3344
3345 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3346 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3347
3348 (defun js2-print-number-node (n i)
3349 (insert (js2-make-pad i)
3350 (number-to-string (js2-number-node-num-value n))))
3351
3352 (defstruct (js2-regexp-node
3353 (:include js2-node)
3354 (:constructor nil)
3355 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3356 (pos js2-token-beg)
3357 (len (- js2-ts-cursor
3358 js2-token-beg))
3359 value flags)))
3360 "AST node for a regular expression literal."
3361 value ; the regexp string, without // delimiters
3362 flags) ; a string of flags, e.g. `mi'.
3363
3364 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3365 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3366
3367 (defun js2-print-regexp (n i)
3368 (insert (js2-make-pad i)
3369 "/"
3370 (js2-regexp-node-value n)
3371 "/")
3372 (if (js2-regexp-node-flags n)
3373 (insert (js2-regexp-node-flags n))))
3374
3375 (defstruct (js2-string-node
3376 (:include js2-node)
3377 (:constructor nil)
3378 (:constructor make-js2-string-node (&key (type js2-STRING)
3379 (pos js2-token-beg)
3380 (len (- js2-ts-cursor
3381 js2-token-beg))
3382 (value js2-ts-string))))
3383 "String literal.
3384 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3385 You can tell the quote type by looking at the first character."
3386 value) ; the characters of the string, including the quotes
3387
3388 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3389 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3390
3391 (defun js2-print-string-node (n i)
3392 (insert (js2-make-pad i)
3393 (js2-node-string n)))
3394
3395 (defstruct (js2-array-node
3396 (:include js2-node)
3397 (:constructor nil)
3398 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3399 (pos js2-ts-cursor)
3400 len elems)))
3401 "AST node for an array literal."
3402 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3403
3404 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3405 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3406
3407 (defun js2-visit-array-node (n v)
3408 (dolist (e (js2-array-node-elems n))
3409 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3410
3411 (defun js2-print-array-node (n i)
3412 (insert (js2-make-pad i) "[")
3413 (js2-print-list (js2-array-node-elems n))
3414 (insert "]"))
3415
3416 (defstruct (js2-object-node
3417 (:include js2-node)
3418 (:constructor nil)
3419 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3420 (pos js2-ts-cursor)
3421 len
3422 elems)))
3423 "AST node for an object literal expression.
3424 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3425 The latter represents abbreviation in destructuring expressions."
3426 elems)
3427
3428 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3429 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3430
3431 (defun js2-visit-object-node (n v)
3432 (dolist (e (js2-object-node-elems n))
3433 (js2-visit-ast e v)))
3434
3435 (defun js2-print-object-node (n i)
3436 (insert (js2-make-pad i) "{")
3437 (js2-print-list (js2-object-node-elems n))
3438 (insert "}"))
3439
3440 (defstruct (js2-object-prop-node
3441 (:include js2-infix-node)
3442 (:constructor nil)
3443 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3444 (pos js2-ts-cursor)
3445 len left
3446 right op-pos)))
3447 "AST node for an object literal prop:value entry.
3448 The `left' field is the property: a name node, string node or number node.
3449 The `right' field is a `js2-node' representing the initializer value.")
3450
3451 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3452 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3453
3454 (defun js2-print-object-prop-node (n i)
3455 (insert (js2-make-pad i))
3456 (js2-print-ast (js2-object-prop-node-left n) 0)
3457 (insert ": ")
3458 (js2-print-ast (js2-object-prop-node-right n) 0))
3459
3460 (defstruct (js2-getter-setter-node
3461 (:include js2-infix-node)
3462 (:constructor nil)
3463 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3464 (pos js2-ts-cursor)
3465 len left right)))
3466 "AST node for a getter/setter property in an object literal.
3467 The `left' field is the `js2-name-node' naming the getter/setter prop.
3468 The `right' field is always an anonymous `js2-function-node' with a node
3469 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3470
3471 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3472 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3473
3474 (defun js2-print-getter-setter (n i)
3475 (let ((pad (js2-make-pad i))
3476 (left (js2-getter-setter-node-left n))
3477 (right (js2-getter-setter-node-right n)))
3478 (insert pad)
3479 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3480 (js2-print-ast left 0)
3481 (js2-print-ast right 0)))
3482
3483 (defstruct (js2-prop-get-node
3484 (:include js2-infix-node)
3485 (:constructor nil)
3486 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3487 (pos js2-ts-cursor)
3488 len left right)))
3489 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3490
3491 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3492 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3493
3494 (defun js2-visit-prop-get-node (n v)
3495 (js2-visit-ast (js2-prop-get-node-left n) v)
3496 (js2-visit-ast (js2-prop-get-node-right n) v))
3497
3498 (defun js2-print-prop-get-node (n i)
3499 (insert (js2-make-pad i))
3500 (js2-print-ast (js2-prop-get-node-left n) 0)
3501 (insert ".")
3502 (js2-print-ast (js2-prop-get-node-right n) 0))
3503
3504 (defstruct (js2-elem-get-node
3505 (:include js2-node)
3506 (:constructor nil)
3507 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3508 (pos js2-ts-cursor)
3509 len target element
3510 lb rb)))
3511 "AST node for an array index expression such as foo[bar]."
3512 target ; a `js2-node' - the expression preceding the "."
3513 element ; a `js2-node' - the expression in brackets
3514 lb ; position of left-bracket, nil if omitted
3515 rb) ; position of right-bracket, nil if omitted
3516
3517 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3518 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3519
3520 (defun js2-visit-elem-get-node (n v)
3521 (js2-visit-ast (js2-elem-get-node-target n) v)
3522 (js2-visit-ast (js2-elem-get-node-element n) v))
3523
3524 (defun js2-print-elem-get-node (n i)
3525 (insert (js2-make-pad i))
3526 (js2-print-ast (js2-elem-get-node-target n) 0)
3527 (insert "[")
3528 (js2-print-ast (js2-elem-get-node-element n) 0)
3529 (insert "]"))
3530
3531 (defstruct (js2-call-node
3532 (:include js2-node)
3533 (:constructor nil)
3534 (:constructor make-js2-call-node (&key (type js2-CALL)
3535 (pos js2-ts-cursor)
3536 len target args
3537 lp rp)))
3538 "AST node for a JavaScript function call."
3539 target ; a `js2-node' evaluating to the function to call
3540 args ; a Lisp list of `js2-node' arguments
3541 lp ; position of open-paren, or nil if missing
3542 rp) ; position of close-paren, or nil if missing
3543
3544 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3545 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3546
3547 (defun js2-visit-call-node (n v)
3548 (js2-visit-ast (js2-call-node-target n) v)
3549 (dolist (arg (js2-call-node-args n))
3550 (js2-visit-ast arg v)))
3551
3552 (defun js2-print-call-node (n i)
3553 (insert (js2-make-pad i))
3554 (js2-print-ast (js2-call-node-target n) 0)
3555 (insert "(")
3556 (js2-print-list (js2-call-node-args n))
3557 (insert ")"))
3558
3559 (defstruct (js2-yield-node
3560 (:include js2-node)
3561 (:constructor nil)
3562 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3563 (pos js2-ts-cursor)
3564 len value)))
3565 "AST node for yield statement or expression."
3566 value) ; optional: value to be yielded
3567
3568 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3569 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3570
3571 (defun js2-visit-yield-node (n v)
3572 (js2-visit-ast (js2-yield-node-value n) v))
3573
3574 (defun js2-print-yield-node (n i)
3575 (insert (js2-make-pad i))
3576 (insert "yield")
3577 (when (js2-yield-node-value n)
3578 (insert " ")
3579 (js2-print-ast (js2-yield-node-value n) 0)))
3580
3581 (defstruct (js2-paren-node
3582 (:include js2-node)
3583 (:constructor nil)
3584 (:constructor make-js2-paren-node (&key (type js2-LP)
3585 (pos js2-ts-cursor)
3586 len expr)))
3587 "AST node for a parenthesized expression.
3588 In particular, used when the parens are syntactically optional,
3589 as opposed to required parens such as those enclosing an if-conditional."
3590 expr) ; `js2-node'
3591
3592 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3593 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3594
3595 (defun js2-visit-paren-node (n v)
3596 (js2-visit-ast (js2-paren-node-expr n) v))
3597
3598 (defun js2-print-paren-node (n i)
3599 (insert (js2-make-pad i))
3600 (insert "(")
3601 (js2-print-ast (js2-paren-node-expr n) 0)
3602 (insert ")"))
3603
3604 (defstruct (js2-array-comp-node
3605 (:include js2-scope)
3606 (:constructor nil)
3607 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3608 (pos js2-ts-cursor)
3609 len result
3610 loops filter
3611 if-pos lp rp)))
3612 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3613 result ; result expression (just after left-bracket)
3614 loops ; a Lisp list of `js2-array-comp-loop-node'
3615 filter ; guard/filter expression
3616 if-pos ; buffer pos of 'if' keyword, if present, else nil
3617 lp ; buffer position of if-guard left-paren, or nil if not present
3618 rp) ; buffer position of if-guard right-paren, or nil if not present
3619
3620 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3621 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3622
3623 (defun js2-visit-array-comp-node (n v)
3624 (js2-visit-ast (js2-array-comp-node-result n) v)
3625 (dolist (l (js2-array-comp-node-loops n))
3626 (js2-visit-ast l v))
3627 (js2-visit-ast (js2-array-comp-node-filter n) v))
3628
3629 (defun js2-print-array-comp-node (n i)
3630 (let ((pad (js2-make-pad i))
3631 (result (js2-array-comp-node-result n))
3632 (loops (js2-array-comp-node-loops n))
3633 (filter (js2-array-comp-node-filter n)))
3634 (insert pad "[")
3635 (js2-print-ast result 0)
3636 (dolist (l loops)
3637 (insert " ")
3638 (js2-print-ast l 0))
3639 (when filter
3640 (insert " if (")
3641 (js2-print-ast filter 0)
3642 (insert ")"))
3643 (insert "]")))
3644
3645 (defstruct (js2-array-comp-loop-node
3646 (:include js2-for-in-node)
3647 (:constructor nil)
3648 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3649 (pos js2-ts-cursor)
3650 len iterator
3651 object in-pos
3652 foreach-p
3653 each-pos
3654 forof-p
3655 lp rp)))
3656 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3657
3658 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3659 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3660
3661 (defun js2-visit-array-comp-loop (n v)
3662 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3663 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3664
3665 (defun js2-print-array-comp-loop (n i)
3666 (insert "for ")
3667 (when (js2-array-comp-loop-node-foreach-p n) (insert "each "))
3668 (insert "(")
3669 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3670 (if (js2-array-comp-loop-node-forof-p n)
3671 (insert " of ")
3672 (insert " in "))
3673 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3674 (insert ")"))
3675
3676 (defstruct (js2-empty-expr-node
3677 (:include js2-node)
3678 (:constructor nil)
3679 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3680 (pos js2-token-beg)
3681 len)))
3682 "AST node for an empty expression.")
3683
3684 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3685 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3686
3687 (defstruct (js2-xml-node
3688 (:include js2-block-node)
3689 (:constructor nil)
3690 (:constructor make-js2-xml-node (&key (type js2-XML)
3691 (pos js2-token-beg)
3692 len kids)))
3693 "AST node for initial parse of E4X literals.
3694 The kids field is a list of XML fragments, each a `js2-string-node' or
3695 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3696
3697 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3698 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3699
3700 (defun js2-print-xml-node (n i)
3701 (dolist (kid (js2-xml-node-kids n))
3702 (js2-print-ast kid i)))
3703
3704 (defstruct (js2-xml-js-expr-node
3705 (:include js2-xml-node)
3706 (:constructor nil)
3707 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3708 (pos js2-ts-cursor)
3709 len expr)))
3710 "AST node for an embedded JavaScript {expression} in an E4X literal.
3711 The start and end fields correspond to the curly-braces."
3712 expr) ; a `js2-expr-node' of some sort
3713
3714 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3715 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3716
3717 (defun js2-visit-xml-js-expr (n v)
3718 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3719
3720 (defun js2-print-xml-js-expr (n i)
3721 (insert (js2-make-pad i))
3722 (insert "{")
3723 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3724 (insert "}"))
3725
3726 (defstruct (js2-xml-dot-query-node
3727 (:include js2-infix-node)
3728 (:constructor nil)
3729 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3730 (pos js2-ts-cursor)
3731 op-pos len left
3732 right rp)))
3733 "AST node for an E4X foo.(bar) filter expression.
3734 Note that the left-paren is automatically the character immediately
3735 following the dot (.) in the operator. No whitespace is permitted
3736 between the dot and the lp by the scanner."
3737 rp)
3738
3739 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3740 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3741
3742 (defun js2-print-xml-dot-query (n i)
3743 (insert (js2-make-pad i))
3744 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3745 (insert ".(")
3746 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3747 (insert ")"))
3748
3749 (defstruct (js2-xml-ref-node
3750 (:include js2-node)
3751 (:constructor nil)) ; abstract
3752 "Base type for E4X XML attribute-access or property-get expressions.
3753 Such expressions can take a variety of forms. The general syntax has
3754 three parts:
3755
3756 - (optional) an @ (specifying an attribute access)
3757 - (optional) a namespace (a `js2-name-node') and double-colon
3758 - (required) either a `js2-name-node' or a bracketed [expression]
3759
3760 The property-name expressions (examples: ns::name, @name) are
3761 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3762 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3763
3764 This node type (or more specifically, its subclasses) will sometimes
3765 be the right-hand child of a `js2-prop-get-node' or a
3766 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3767 The `js2-xml-ref-node' may also be a standalone primary expression with
3768 no explicit target, which is valid in certain expression contexts such as
3769
3770 company..employee.(@id < 100)
3771
3772 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3773 expression whose parent is a `js2-xml-dot-query-node'."
3774 namespace
3775 at-pos
3776 colon-pos)
3777
3778 (defsubst js2-xml-ref-node-attr-access-p (node)
3779 "Return non-nil if this expression began with an @-token."
3780 (and (numberp (js2-xml-ref-node-at-pos node))
3781 (plusp (js2-xml-ref-node-at-pos node))))
3782
3783 (defstruct (js2-xml-prop-ref-node
3784 (:include js2-xml-ref-node)
3785 (:constructor nil)
3786 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3787 (pos js2-token-beg)
3788 len propname
3789 namespace at-pos
3790 colon-pos)))
3791 "AST node for an E4X XML [expr] property-ref expression.
3792 The JavaScript syntax is an optional @, an optional ns::, and a name.
3793
3794 [ '@' ] [ name '::' ] name
3795
3796 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3797 @ns::*, @*::attr, @*::*, and @*.
3798
3799 The node starts at the @ token, if present. Otherwise it starts at the
3800 namespace name. The node bounds extend through the closing right-bracket,
3801 or if it is missing due to a syntax error, through the end of the index
3802 expression."
3803 propname)
3804
3805 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3806 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3807
3808 (defun js2-visit-xml-prop-ref-node (n v)
3809 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3810 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3811
3812 (defun js2-print-xml-prop-ref-node (n i)
3813 (insert (js2-make-pad i))
3814 (if (js2-xml-ref-node-attr-access-p n)
3815 (insert "@"))
3816 (when (js2-xml-prop-ref-node-namespace n)
3817 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3818 (insert "::"))
3819 (if (js2-xml-prop-ref-node-propname n)
3820 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3821
3822 (defstruct (js2-xml-elem-ref-node
3823 (:include js2-xml-ref-node)
3824 (:constructor nil)
3825 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3826 (pos js2-token-beg)
3827 len expr lb rb
3828 namespace at-pos
3829 colon-pos)))
3830 "AST node for an E4X XML [expr] member-ref expression.
3831 Syntax:
3832
3833 [ '@' ] [ name '::' ] '[' expr ']'
3834
3835 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3836
3837 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3838 is not a legal E4X XML element-ref expression, since it's already used
3839 for standard JavaScript element-get array indexing. Hence, a
3840 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3841 non-nil namespace node, or both.
3842
3843 The node starts at the @ token, if present. Otherwise it starts
3844 at the namespace name. The node bounds extend through the closing
3845 right-bracket, or if it is missing due to a syntax error, through the
3846 end of the index expression."
3847 expr ; the bracketed index expression
3848 lb
3849 rb)
3850
3851 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3852 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3853
3854 (defun js2-visit-xml-elem-ref-node (n v)
3855 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3856 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3857
3858 (defun js2-print-xml-elem-ref-node (n i)
3859 (insert (js2-make-pad i))
3860 (if (js2-xml-ref-node-attr-access-p n)
3861 (insert "@"))
3862 (when (js2-xml-elem-ref-node-namespace n)
3863 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3864 (insert "::"))
3865 (insert "[")
3866 (if (js2-xml-elem-ref-node-expr n)
3867 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3868 (insert "]"))
3869
3870 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3871
3872 (defstruct (js2-xml-start-tag-node
3873 (:include js2-xml-node)
3874 (:constructor nil)
3875 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3876 (pos js2-ts-cursor)
3877 len name attrs kids
3878 empty-p)))
3879 "AST node for an XML start-tag. Not currently used.
3880 The `kids' field is a Lisp list of child content nodes."
3881 name ; a `js2-xml-name-node'
3882 attrs ; a Lisp list of `js2-xml-attr-node'
3883 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3884
3885 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3886 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3887
3888 (defun js2-visit-xml-start-tag (n v)
3889 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3890 (dolist (attr (js2-xml-start-tag-node-attrs n))
3891 (js2-visit-ast attr v))
3892 (js2-visit-block n v))
3893
3894 (defun js2-print-xml-start-tag (n i)
3895 (insert (js2-make-pad i) "<")
3896 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3897 (when (js2-xml-start-tag-node-attrs n)
3898 (insert " ")
3899 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3900 (insert ">"))
3901
3902 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3903 ;; and add the end-tag to the kids list of the parent as well.
3904 (defstruct (js2-xml-end-tag-node
3905 (:include js2-xml-node)
3906 (:constructor nil)
3907 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
3908 (pos js2-ts-cursor)
3909 len name)))
3910 "AST node for an XML end-tag. Not currently used."
3911 name) ; a `js2-xml-name-node'
3912
3913 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
3914 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
3915
3916 (defun js2-visit-xml-end-tag (n v)
3917 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
3918
3919 (defun js2-print-xml-end-tag (n i)
3920 (insert (js2-make-pad i))
3921 (insert "</")
3922 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
3923 (insert ">"))
3924
3925 (defstruct (js2-xml-name-node
3926 (:include js2-xml-node)
3927 (:constructor nil)
3928 (:constructor make-js2-xml-name-node (&key (type js2-XML)
3929 (pos js2-ts-cursor)
3930 len namespace kids)))
3931 "AST node for an E4X XML name. Not currently used.
3932 Any XML name can be qualified with a namespace, hence the namespace field.
3933 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
3934 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
3935 For a simple name, the kids list has exactly one node, a `js2-name-node'."
3936 namespace) ; a `js2-string-node'
3937
3938 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
3939 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
3940
3941 (defun js2-visit-xml-name-node (n v)
3942 (js2-visit-ast (js2-xml-name-node-namespace n) v))
3943
3944 (defun js2-print-xml-name-node (n i)
3945 (insert (js2-make-pad i))
3946 (when (js2-xml-name-node-namespace n)
3947 (js2-print-ast (js2-xml-name-node-namespace n) 0)
3948 (insert "::"))
3949 (dolist (kid (js2-xml-name-node-kids n))
3950 (js2-print-ast kid 0)))
3951
3952 (defstruct (js2-xml-pi-node
3953 (:include js2-xml-node)
3954 (:constructor nil)
3955 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
3956 (pos js2-ts-cursor)
3957 len name attrs)))
3958 "AST node for an E4X XML processing instruction. Not currently used."
3959 name ; a `js2-xml-name-node'
3960 attrs) ; a list of `js2-xml-attr-node'
3961
3962 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
3963 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
3964
3965 (defun js2-visit-xml-pi-node (n v)
3966 (js2-visit-ast (js2-xml-pi-node-name n) v)
3967 (dolist (attr (js2-xml-pi-node-attrs n))
3968 (js2-visit-ast attr v)))
3969
3970 (defun js2-print-xml-pi-node (n i)
3971 (insert (js2-make-pad i) "<?")
3972 (js2-print-ast (js2-xml-pi-node-name n))
3973 (when (js2-xml-pi-node-attrs n)
3974 (insert " ")
3975 (js2-print-list (js2-xml-pi-node-attrs n)))
3976 (insert "?>"))
3977
3978 (defstruct (js2-xml-cdata-node
3979 (:include js2-xml-node)
3980 (:constructor nil)
3981 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
3982 (pos js2-ts-cursor)
3983 len content)))
3984 "AST node for a CDATA escape section. Not currently used."
3985 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
3986
3987 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
3988 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
3989
3990 (defun js2-visit-xml-cdata-node (n v)
3991 (js2-visit-ast (js2-xml-cdata-node-content n) v))
3992
3993 (defun js2-print-xml-cdata-node (n i)
3994 (insert (js2-make-pad i))
3995 (js2-print-ast (js2-xml-cdata-node-content n)))
3996
3997 (defstruct (js2-xml-attr-node
3998 (:include js2-xml-node)
3999 (:constructor nil)
4000 (:constructor make-js2-attr-node (&key (type js2-XML)
4001 (pos js2-ts-cursor)
4002 len name value
4003 eq-pos quote-type)))
4004 "AST node representing a foo='bar' XML attribute value. Not yet used."
4005 name ; a `js2-xml-name-node'
4006 value ; a `js2-xml-name-node'
4007 eq-pos ; buffer position of "=" sign
4008 quote-type) ; 'single or 'double
4009
4010 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4011 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4012
4013 (defun js2-visit-xml-attr-node (n v)
4014 (js2-visit-ast (js2-xml-attr-node-name n) v)
4015 (js2-visit-ast (js2-xml-attr-node-value n) v))
4016
4017 (defun js2-print-xml-attr-node (n i)
4018 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4019 "'"
4020 "\"")))
4021 (insert (js2-make-pad i))
4022 (js2-print-ast (js2-xml-attr-node-name n) 0)
4023 (insert "=" quote)
4024 (js2-print-ast (js2-xml-attr-node-value n) 0)
4025 (insert quote)))
4026
4027 (defstruct (js2-xml-text-node
4028 (:include js2-xml-node)
4029 (:constructor nil)
4030 (:constructor make-js2-text-node (&key (type js2-XML)
4031 (pos js2-ts-cursor)
4032 len content)))
4033 "AST node for an E4X XML text node. Not currently used."
4034 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4035
4036 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4037 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4038
4039 (defun js2-visit-xml-text-node (n v)
4040 (js2-visit-ast (js2-xml-text-node-content n) v))
4041
4042 (defun js2-print-xml-text-node (n i)
4043 (insert (js2-make-pad i))
4044 (dolist (kid (js2-xml-text-node-content n))
4045 (js2-print-ast kid)))
4046
4047 (defstruct (js2-xml-comment-node
4048 (:include js2-xml-node)
4049 (:constructor nil)
4050 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4051 (pos js2-ts-cursor)
4052 len)))
4053 "AST node for E4X XML comment. Not currently used.")
4054
4055 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4056 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4057
4058 (defun js2-print-xml-comment (n i)
4059 (insert (js2-make-pad i)
4060 (js2-node-string n)))
4061
4062 ;;; Node utilities
4063
4064 (defsubst js2-node-line (n)
4065 "Fetch the source line number at the start of node N.
4066 This is O(n) in the length of the source buffer; use prudently."
4067 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4068
4069 (defsubst js2-block-node-kid (n i)
4070 "Return child I of node N, or nil if there aren't that many."
4071 (nth i (js2-block-node-kids n)))
4072
4073 (defsubst js2-block-node-first (n)
4074 "Return first child of block node N, or nil if there is none."
4075 (first (js2-block-node-kids n)))
4076
4077 (defun js2-node-root (n)
4078 "Return the root of the AST containing N.
4079 If N has no parent pointer, returns N."
4080 (let ((parent (js2-node-parent n)))
4081 (if parent
4082 (js2-node-root parent)
4083 n)))
4084
4085 (defsubst js2-node-short-name (n)
4086 "Return the short name of node N as a string, e.g. `js2-if-node'."
4087 (substring (symbol-name (aref n 0))
4088 (length "cl-struct-")))
4089
4090 (defun js2-node-child-list (node)
4091 "Return the child list for NODE, a Lisp list of nodes.
4092 Works for block nodes, array nodes, obj literals, funarg lists,
4093 var decls and try nodes (for catch clauses). Note that you should call
4094 `js2-block-node-kids' on the function body for the body statements.
4095 Returns nil for zero-length child lists or unsupported nodes."
4096 (cond
4097 ((js2-function-node-p node)
4098 (js2-function-node-params node))
4099 ((js2-block-node-p node)
4100 (js2-block-node-kids node))
4101 ((js2-try-node-p node)
4102 (js2-try-node-catch-clauses node))
4103 ((js2-array-node-p node)
4104 (js2-array-node-elems node))
4105 ((js2-object-node-p node)
4106 (js2-object-node-elems node))
4107 ((js2-call-node-p node)
4108 (js2-call-node-args node))
4109 ((js2-new-node-p node)
4110 (js2-new-node-args node))
4111 ((js2-var-decl-node-p node)
4112 (js2-var-decl-node-kids node))
4113 (t
4114 nil)))
4115
4116 (defun js2-node-set-child-list (node kids)
4117 "Set the child list for NODE to KIDS."
4118 (cond
4119 ((js2-function-node-p node)
4120 (setf (js2-function-node-params node) kids))
4121 ((js2-block-node-p node)
4122 (setf (js2-block-node-kids node) kids))
4123 ((js2-try-node-p node)
4124 (setf (js2-try-node-catch-clauses node) kids))
4125 ((js2-array-node-p node)
4126 (setf (js2-array-node-elems node) kids))
4127 ((js2-object-node-p node)
4128 (setf (js2-object-node-elems node) kids))
4129 ((js2-call-node-p node)
4130 (setf (js2-call-node-args node) kids))
4131 ((js2-new-node-p node)
4132 (setf (js2-new-node-args node) kids))
4133 ((js2-var-decl-node-p node)
4134 (setf (js2-var-decl-node-kids node) kids))
4135 (t
4136 (error "Unsupported node type: %s" (js2-node-short-name node))))
4137 kids)
4138
4139 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4140 (defconst js2-paren-expr-nodes
4141 '(cl-struct-js2-array-comp-loop-node
4142 cl-struct-js2-array-comp-node
4143 cl-struct-js2-call-node
4144 cl-struct-js2-catch-node
4145 cl-struct-js2-do-node
4146 cl-struct-js2-elem-get-node
4147 cl-struct-js2-for-in-node
4148 cl-struct-js2-for-node
4149 cl-struct-js2-function-node
4150 cl-struct-js2-if-node
4151 cl-struct-js2-let-node
4152 cl-struct-js2-new-node
4153 cl-struct-js2-paren-node
4154 cl-struct-js2-switch-node
4155 cl-struct-js2-while-node
4156 cl-struct-js2-with-node
4157 cl-struct-js2-xml-dot-query-node)
4158 "Node types that can have a parenthesized child expression.
4159 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4160
4161 (defsubst js2-paren-expr-node-p (node)
4162 "Return t for nodes that typically have a parenthesized child expression.
4163 Useful for computing the indentation anchors for arg-lists and conditions.
4164 Note that it may return a false positive, for instance when NODE is
4165 a `js2-new-node' and there are no arguments or parentheses."
4166 (memq (aref node 0) js2-paren-expr-nodes))
4167
4168 ;; Fake polymorphism... yech.
4169 (defun js2-node-lp (node)
4170 "Return relative left-paren position for NODE, if applicable.
4171 For `js2-elem-get-node' structs, returns left-bracket position.
4172 Note that the position may be nil in the case of a parse error."
4173 (cond
4174 ((js2-elem-get-node-p node)
4175 (js2-elem-get-node-lb node))
4176 ((js2-loop-node-p node)
4177 (js2-loop-node-lp node))
4178 ((js2-function-node-p node)
4179 (js2-function-node-lp node))
4180 ((js2-if-node-p node)
4181 (js2-if-node-lp node))
4182 ((js2-new-node-p node)
4183 (js2-new-node-lp node))
4184 ((js2-call-node-p node)
4185 (js2-call-node-lp node))
4186 ((js2-paren-node-p node)
4187 0)
4188 ((js2-switch-node-p node)
4189 (js2-switch-node-lp node))
4190 ((js2-catch-node-p node)
4191 (js2-catch-node-lp node))
4192 ((js2-let-node-p node)
4193 (js2-let-node-lp node))
4194 ((js2-array-comp-node-p node)
4195 (js2-array-comp-node-lp node))
4196 ((js2-with-node-p node)
4197 (js2-with-node-lp node))
4198 ((js2-xml-dot-query-node-p node)
4199 (1+ (js2-infix-node-op-pos node)))
4200 (t
4201 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4202
4203 ;; Fake polymorphism... blech.
4204 (defun js2-node-rp (node)
4205 "Return relative right-paren position for NODE, if applicable.
4206 For `js2-elem-get-node' structs, returns right-bracket position.
4207 Note that the position may be nil in the case of a parse error."
4208 (cond
4209 ((js2-elem-get-node-p node)
4210 (js2-elem-get-node-rb node))
4211 ((js2-loop-node-p node)
4212 (js2-loop-node-rp node))
4213 ((js2-function-node-p node)
4214 (js2-function-node-rp node))
4215 ((js2-if-node-p node)
4216 (js2-if-node-rp node))
4217 ((js2-new-node-p node)
4218 (js2-new-node-rp node))
4219 ((js2-call-node-p node)
4220 (js2-call-node-rp node))
4221 ((js2-paren-node-p node)
4222 (1- (js2-node-len node)))
4223 ((js2-switch-node-p node)
4224 (js2-switch-node-rp node))
4225 ((js2-catch-node-p node)
4226 (js2-catch-node-rp node))
4227 ((js2-let-node-p node)
4228 (js2-let-node-rp node))
4229 ((js2-array-comp-node-p node)
4230 (js2-array-comp-node-rp node))
4231 ((js2-with-node-p node)
4232 (js2-with-node-rp node))
4233 ((js2-xml-dot-query-node-p node)
4234 (1+ (js2-xml-dot-query-node-rp node)))
4235 (t
4236 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4237
4238 (defsubst js2-node-first-child (node)
4239 "Return the first element of `js2-node-child-list' for NODE."
4240 (car (js2-node-child-list node)))
4241
4242 (defsubst js2-node-last-child (node)
4243 "Return the last element of `js2-node-last-child' for NODE."
4244 (car (last (js2-node-child-list node))))
4245
4246 (defun js2-node-prev-sibling (node)
4247 "Return the previous statement in parent.
4248 Works for parents supported by `js2-node-child-list'.
4249 Returns nil if NODE is not in the parent, or PARENT is
4250 not a supported node, or if NODE is the first child."
4251 (let* ((p (js2-node-parent node))
4252 (kids (js2-node-child-list p))
4253 (sib (car kids)))
4254 (while (and kids
4255 (not (eq node (cadr kids))))
4256 (setq kids (cdr kids)
4257 sib (car kids)))
4258 sib))
4259
4260 (defun js2-node-next-sibling (node)
4261 "Return the next statement in parent block.
4262 Returns nil if NODE is not in the block, or PARENT is not
4263 a block node, or if NODE is the last statement."
4264 (let* ((p (js2-node-parent node))
4265 (kids (js2-node-child-list p)))
4266 (while (and kids
4267 (not (eq node (car kids))))
4268 (setq kids (cdr kids)))
4269 (cadr kids)))
4270
4271 (defun js2-node-find-child-before (pos parent &optional after)
4272 "Find the last child that starts before POS in parent.
4273 If AFTER is non-nil, returns first child starting after POS.
4274 POS is an absolute buffer position. PARENT is any node
4275 supported by `js2-node-child-list'.
4276 Returns nil if no applicable child is found."
4277 (let ((kids (if (js2-function-node-p parent)
4278 (js2-block-node-kids (js2-function-node-body parent))
4279 (js2-node-child-list parent)))
4280 (beg (if (js2-function-node-p parent)
4281 (js2-node-abs-pos (js2-function-node-body parent))
4282 (js2-node-abs-pos parent)))
4283 kid result fn
4284 (continue t))
4285 (setq fn (if after '>= '<))
4286 (while (and kids continue)
4287 (setq kid (car kids))
4288 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4289 (setq result kid
4290 continue (if after nil t))
4291 (setq continue (if after t nil)))
4292 (setq kids (cdr kids)))
4293 result))
4294
4295 (defun js2-node-find-child-after (pos parent)
4296 "Find first child that starts after POS in parent.
4297 POS is an absolute buffer position. PARENT is any node
4298 supported by `js2-node-child-list'.
4299 Returns nil if no applicable child is found."
4300 (js2-node-find-child-before pos parent 'after))
4301
4302 (defun js2-node-replace-child (pos parent new-node)
4303 "Replace node at index POS in PARENT with NEW-NODE.
4304 Only works for parents supported by `js2-node-child-list'."
4305 (let ((kids (js2-node-child-list parent))
4306 (i 0))
4307 (while (< i pos)
4308 (setq kids (cdr kids)
4309 i (1+ i)))
4310 (setcar kids new-node)
4311 (js2-node-add-children parent new-node)))
4312
4313 (defun js2-node-buffer (n)
4314 "Return the buffer associated with AST N.
4315 Returns nil if the buffer is not set as a property on the root
4316 node, or if parent links were not recorded during parsing."
4317 (let ((root (js2-node-root n)))
4318 (and root
4319 (js2-ast-root-p root)
4320 (js2-ast-root-buffer root))))
4321
4322 (defun js2-block-node-push (n kid)
4323 "Push js2-node KID onto the end of js2-block-node N's child list.
4324 KID is always added to the -end- of the kids list.
4325 Function also calls `js2-node-add-children' to add the parent link."
4326 (let ((kids (js2-node-child-list n)))
4327 (if kids
4328 (setcdr kids (nconc (cdr kids) (list kid)))
4329 (js2-node-set-child-list n (list kid)))
4330 (js2-node-add-children n kid)))
4331
4332 (defun js2-node-string (node)
4333 (with-current-buffer (or (js2-node-buffer node)
4334 (error "No buffer available for node %s" node))
4335 (let ((pos (js2-node-abs-pos node)))
4336 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4337
4338 ;; Container for storing the node we're looking for in a traversal.
4339 (js2-deflocal js2-discovered-node nil)
4340
4341 ;; Keep track of absolute node position during traversals.
4342 (js2-deflocal js2-visitor-offset nil)
4343
4344 (js2-deflocal js2-node-search-point nil)
4345
4346 (when js2-mode-dev-mode-p
4347 (defun js2-find-node-at-point ()
4348 (interactive)
4349 (let ((node (js2-node-at-point)))
4350 (message "%s" (or node "No node found at point"))))
4351 (defun js2-node-name-at-point ()
4352 (interactive)
4353 (let ((node (js2-node-at-point)))
4354 (message "%s" (if node
4355 (js2-node-short-name node)
4356 "No node found at point.")))))
4357
4358 (defun js2-node-at-point (&optional pos skip-comments)
4359 "Return AST node at POS, a buffer position, defaulting to current point.
4360 The `js2-mode-ast' variable must be set to the current parse tree.
4361 Signals an error if the AST (`js2-mode-ast') is nil.
4362 Always returns a node - if it can't find one, it returns the root.
4363 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4364 (let ((ast js2-mode-ast)
4365 result)
4366 (unless ast
4367 (error "No JavaScript AST available"))
4368 ;; Look through comments first, since they may be inside nodes that
4369 ;; would otherwise report a match.
4370 (setq pos (or pos (point))
4371 result (if (> pos (js2-node-abs-end ast))
4372 ast
4373 (if (not skip-comments)
4374 (js2-comment-at-point pos))))
4375 (unless result
4376 (setq js2-discovered-node nil
4377 js2-visitor-offset 0
4378 js2-node-search-point pos)
4379 (unwind-protect
4380 (catch 'js2-visit-done
4381 (js2-visit-ast ast #'js2-node-at-point-visitor))
4382 (setq js2-visitor-offset nil
4383 js2-node-search-point nil))
4384 (setq result js2-discovered-node))
4385 ;; may have found a comment beyond end of last child node,
4386 ;; since visiting the ast-root looks at the comment-list last.
4387 (if (and skip-comments
4388 (js2-comment-node-p result))
4389 (setq result nil))
4390 (or result js2-mode-ast)))
4391
4392 (defun js2-node-at-point-visitor (node end-p)
4393 (let ((rel-pos (js2-node-pos node))
4394 abs-pos
4395 abs-end
4396 (point js2-node-search-point))
4397 (cond
4398 (end-p
4399 ;; this evaluates to a non-nil return value, even if it's zero
4400 (decf js2-visitor-offset rel-pos))
4401 ;; we already looked for comments before visiting, and don't want them now
4402 ((js2-comment-node-p node)
4403 nil)
4404 (t
4405 (setq abs-pos (incf js2-visitor-offset rel-pos)
4406 ;; we only want to use the node if the point is before
4407 ;; the last character position in the node, so we decrement
4408 ;; the absolute end by 1.
4409 abs-end (+ abs-pos (js2-node-len node) -1))
4410 (cond
4411 ;; If this node starts after search-point, stop the search.
4412 ((> abs-pos point)
4413 (throw 'js2-visit-done nil))
4414 ;; If this node ends before the search-point, don't check kids.
4415 ((> point abs-end)
4416 nil)
4417 (t
4418 ;; Otherwise point is within this node, possibly in a child.
4419 (setq js2-discovered-node node)
4420 t)))))) ; keep processing kids to look for more specific match
4421
4422 (defsubst js2-block-comment-p (node)
4423 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4424 (and (js2-comment-node-p node)
4425 (memq (js2-comment-node-format node) '(jsdoc block))))
4426
4427 ;; TODO: put the comments in a vector and binary-search them instead
4428 (defun js2-comment-at-point (&optional pos)
4429 "Look through scanned comment nodes for one containing POS.
4430 POS is a buffer position that defaults to current point.
4431 Function returns nil if POS was not in any comment node."
4432 (let ((ast js2-mode-ast)
4433 (x (or pos (point)))
4434 beg end)
4435 (unless ast
4436 (error "No JavaScript AST available"))
4437 (catch 'done
4438 ;; Comments are stored in lexical order.
4439 (dolist (comment (js2-ast-root-comments ast) nil)
4440 (setq beg (js2-node-abs-pos comment)
4441 end (+ beg (js2-node-len comment)))
4442 (if (and (>= x beg)
4443 (<= x end))
4444 (throw 'done comment))))))
4445
4446 (defun js2-mode-find-parent-fn (node)
4447 "Find function enclosing NODE.
4448 Returns nil if NODE is not inside a function."
4449 (setq node (js2-node-parent node))
4450 (while (and node (not (js2-function-node-p node)))
4451 (setq node (js2-node-parent node)))
4452 (and (js2-function-node-p node) node))
4453
4454 (defun js2-mode-find-enclosing-fn (node)
4455 "Find function or root enclosing NODE."
4456 (if (js2-ast-root-p node)
4457 node
4458 (setq node (js2-node-parent node))
4459 (while (not (or (js2-ast-root-p node)
4460 (js2-function-node-p node)))
4461 (setq node (js2-node-parent node)))
4462 node))
4463
4464 (defun js2-mode-find-enclosing-node (beg end)
4465 "Find script or function fully enclosing BEG and END."
4466 (let ((node (js2-node-at-point beg))
4467 pos
4468 (continue t))
4469 (while continue
4470 (if (or (js2-ast-root-p node)
4471 (and (js2-function-node-p node)
4472 (<= (setq pos (js2-node-abs-pos node)) beg)
4473 (>= (+ pos (js2-node-len node)) end)))
4474 (setq continue nil)
4475 (setq node (js2-node-parent node))))
4476 node))
4477
4478 (defun js2-node-parent-script-or-fn (node)
4479 "Find script or function immediately enclosing NODE.
4480 If NODE is the ast-root, returns nil."
4481 (if (js2-ast-root-p node)
4482 nil
4483 (setq node (js2-node-parent node))
4484 (while (and node (not (or (js2-function-node-p node)
4485 (js2-script-node-p node))))
4486 (setq node (js2-node-parent node)))
4487 node))
4488
4489 (defun js2-node-is-descendant (node ancestor)
4490 "Return t if NODE is a descendant of ANCESTOR."
4491 (while (and node
4492 (not (eq node ancestor)))
4493 (setq node (js2-node-parent node)))
4494 node)
4495
4496 ;;; visitor infrastructure
4497
4498 (defun js2-visit-none (node callback)
4499 "Visitor for AST node that have no node children."
4500 nil)
4501
4502 (defun js2-print-none (node indent)
4503 "Visitor for AST node with no printed representation.")
4504
4505 (defun js2-print-body (node indent)
4506 "Print a statement, or a block without braces."
4507 (if (js2-block-node-p node)
4508 (dolist (kid (js2-block-node-kids node))
4509 (js2-print-ast kid indent))
4510 (js2-print-ast node indent)))
4511
4512 (defun js2-print-list (args &optional delimiter)
4513 (loop with len = (length args)
4514 for arg in args
4515 for count from 1
4516 do
4517 (when arg (js2-print-ast arg 0))
4518 (if (< count len)
4519 (insert (or delimiter ", ")))))
4520
4521 (defun js2-print-tree (ast)
4522 "Prints an AST to the current buffer.
4523 Makes `js2-ast-parent-nodes' available to the printer functions."
4524 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4525 (js2-print-ast ast)))
4526
4527 (defun js2-print-ast (node &optional indent)
4528 "Helper function for printing AST nodes.
4529 Requires `js2-ast-parent-nodes' to be non-nil.
4530 You should use `js2-print-tree' instead of this function."
4531 (let ((printer (get (aref node 0) 'js2-printer))
4532 (i (or indent 0))
4533 (pos (js2-node-abs-pos node)))
4534 ;; TODO: wedge comments in here somewhere
4535 (if printer
4536 (funcall printer node i))))
4537
4538 (defconst js2-side-effecting-tokens
4539 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4540 (dolist (tt (list js2-ASSIGN
4541 js2-ASSIGN_ADD
4542 js2-ASSIGN_BITAND
4543 js2-ASSIGN_BITOR
4544 js2-ASSIGN_BITXOR
4545 js2-ASSIGN_DIV
4546 js2-ASSIGN_LSH
4547 js2-ASSIGN_MOD
4548 js2-ASSIGN_MUL
4549 js2-ASSIGN_RSH
4550 js2-ASSIGN_SUB
4551 js2-ASSIGN_URSH
4552 js2-BLOCK
4553 js2-BREAK
4554 js2-CALL
4555 js2-CATCH
4556 js2-CATCH_SCOPE
4557 js2-CONST
4558 js2-CONTINUE
4559 js2-DEBUGGER
4560 js2-DEC
4561 js2-DELPROP
4562 js2-DEL_REF
4563 js2-DO
4564 js2-ELSE
4565 js2-EMPTY
4566 js2-ENTERWITH
4567 js2-EXPORT
4568 js2-EXPR_RESULT
4569 js2-FINALLY
4570 js2-FOR
4571 js2-FUNCTION
4572 js2-GOTO
4573 js2-IF
4574 js2-IFEQ
4575 js2-IFNE
4576 js2-IMPORT
4577 js2-INC
4578 js2-JSR
4579 js2-LABEL
4580 js2-LEAVEWITH
4581 js2-LET
4582 js2-LETEXPR
4583 js2-LOCAL_BLOCK
4584 js2-LOOP
4585 js2-NEW
4586 js2-REF_CALL
4587 js2-RETHROW
4588 js2-RETURN
4589 js2-RETURN_RESULT
4590 js2-SEMI
4591 js2-SETELEM
4592 js2-SETELEM_OP
4593 js2-SETNAME
4594 js2-SETPROP
4595 js2-SETPROP_OP
4596 js2-SETVAR
4597 js2-SET_REF
4598 js2-SET_REF_OP
4599 js2-SWITCH
4600 js2-TARGET
4601 js2-THROW
4602 js2-TRY
4603 js2-VAR
4604 js2-WHILE
4605 js2-WITH
4606 js2-WITHEXPR
4607 js2-YIELD))
4608 (aset tokens tt t))
4609 (if js2-instanceof-has-side-effects
4610 (aset tokens js2-INSTANCEOF t))
4611 tokens))
4612
4613 (defun js2-node-has-side-effects (node)
4614 "Return t if NODE has side effects."
4615 (when node ; makes it easier to handle malformed expressions
4616 (let ((tt (js2-node-type node)))
4617 (cond
4618 ;; This doubtless needs some work, since EXPR_VOID is used
4619 ;; in several ways in Rhino and I may not have caught them all.
4620 ;; I'll wait for people to notice incorrect warnings.
4621 ((and (= tt js2-EXPR_VOID)
4622 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4623 (let ((expr (js2-expr-stmt-node-expr node)))
4624 (or (js2-node-has-side-effects expr)
4625 (when (js2-string-node-p expr)
4626 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4627 ((= tt js2-COMMA)
4628 (js2-node-has-side-effects (js2-infix-node-right node)))
4629 ((or (= tt js2-AND)
4630 (= tt js2-OR))
4631 (or (js2-node-has-side-effects (js2-infix-node-right node))
4632 (js2-node-has-side-effects (js2-infix-node-left node))))
4633 ((= tt js2-HOOK)
4634 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4635 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4636 ((js2-paren-node-p node)
4637 (js2-node-has-side-effects (js2-paren-node-expr node)))
4638 ((= tt js2-ERROR) ; avoid cascaded error messages
4639 nil)
4640 (t
4641 (aref js2-side-effecting-tokens tt))))))
4642
4643 (defconst js2-stmt-node-types
4644 (list js2-BLOCK
4645 js2-BREAK
4646 js2-CONTINUE
4647 js2-DEFAULT ; e4x "default xml namespace" statement
4648 js2-DO
4649 js2-EXPR_RESULT
4650 js2-EXPR_VOID
4651 js2-FOR
4652 js2-IF
4653 js2-RETURN
4654 js2-SWITCH
4655 js2-THROW
4656 js2-TRY
4657 js2-WHILE
4658 js2-WITH)
4659 "Node types that only appear in statement contexts.
4660 The list does not include nodes that always appear as the child
4661 of another specific statement type, such as switch-cases,
4662 catch and finally blocks, and else-clauses. The list also excludes
4663 nodes like yield, let and var, which may appear in either expression
4664 or statement context, and in the latter context always have a
4665 `js2-expr-stmt-node' parent. Finally, the list does not include
4666 functions or scripts, which are treated separately from statements
4667 by the JavaScript parser and runtime.")
4668
4669 (defun js2-stmt-node-p (node)
4670 "Heuristic for figuring out if NODE is a statement.
4671 Some node types can appear in either an expression context or a
4672 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4673 For these node types in a statement context, the parent will be a
4674 `js2-expr-stmt-node'.
4675 Functions aren't included in the check."
4676 (memq (js2-node-type node) js2-stmt-node-types))
4677
4678 (defun js2-mode-find-first-stmt (node)
4679 "Search upward starting from NODE looking for a statement.
4680 For purposes of this function, a `js2-function-node' counts."
4681 (while (not (or (js2-stmt-node-p node)
4682 (js2-function-node-p node)))
4683 (setq node (js2-node-parent node)))
4684 node)
4685
4686 (defun js2-node-parent-stmt (node)
4687 "Return the node's first ancestor that is a statement.
4688 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4689 appearing in a statement context will have a parent that is a
4690 `js2-expr-stmt-node' that will be returned by this function."
4691 (let ((parent (js2-node-parent node)))
4692 (if (or (null parent)
4693 (js2-stmt-node-p parent)
4694 (and (js2-function-node-p parent)
4695 (not (eq (js2-function-node-form parent)
4696 'FUNCTION_EXPRESSION))))
4697 parent
4698 (js2-node-parent-stmt parent))))
4699
4700 ;; In the Mozilla Rhino sources, Roshan James writes:
4701 ;; Does consistent-return analysis on the function body when strict mode is
4702 ;; enabled.
4703 ;;
4704 ;; function (x) { return (x+1) }
4705 ;;
4706 ;; is ok, but
4707 ;;
4708 ;; function (x) { if (x < 0) return (x+1); }
4709 ;;
4710 ;; is not because the function can potentially return a value when the
4711 ;; condition is satisfied and if not, the function does not explicitly
4712 ;; return a value.
4713 ;;
4714 ;; This extends to checking mismatches such as "return" and "return <value>"
4715 ;; used in the same function. Warnings are not emitted if inconsistent
4716 ;; returns exist in code that can be statically shown to be unreachable.
4717 ;; Ex.
4718 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4719 ;;
4720 ;; emits no warning. However if the loop had a break statement, then a
4721 ;; warning would be emitted.
4722 ;;
4723 ;; The consistency analysis looks at control structures such as loops, ifs,
4724 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4725 ;; warns the user about an inconsistent set of termination possibilities.
4726 ;;
4727 ;; These flags enumerate the possible ways a statement/function can
4728 ;; terminate. These flags are used by endCheck() and by the Parser to
4729 ;; detect inconsistent return usage.
4730 ;;
4731 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4732 ;; able to execute (example: throw, continue)
4733 ;;
4734 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4735 ;; next one. Statement such as return dont. A compound statement may have
4736 ;; some branch that drops off control to the next statement.
4737 ;;
4738 ;; END_RETURNS indicates that the statement can return with no value.
4739 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4740 ;;
4741 ;; A compound statement such as
4742 ;; if (condition) {
4743 ;; return value;
4744 ;; }
4745 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4746
4747 (defconst js2-END_UNREACHED 0)
4748 (defconst js2-END_DROPS_OFF 1)
4749 (defconst js2-END_RETURNS 2)
4750 (defconst js2-END_RETURNS_VALUE 4)
4751 (defconst js2-END_YIELDS 8)
4752
4753 (defun js2-has-consistent-return-usage (node)
4754 "Check that every return usage in a function body is consistent.
4755 Returns t if the function satisfies strict mode requirement."
4756 (let ((n (js2-end-check node)))
4757 ;; either it doesn't return a value in any branch...
4758 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4759 ;; or it returns a value (or is unreached) at every branch
4760 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4761 js2-END_RETURNS
4762 js2-END_YIELDS)))))
4763
4764 (defun js2-end-check-if (node)
4765 "Ensure that return usage in then/else blocks is consistent.
4766 If there is no else block, then the return statement can fall through.
4767 Returns logical OR of END_* flags"
4768 (let ((th (js2-if-node-then-part node))
4769 (el (js2-if-node-else-part node)))
4770 (if (null th)
4771 js2-END_UNREACHED
4772 (logior (js2-end-check th) (if el
4773 (js2-end-check el)
4774 js2-END_DROPS_OFF)))))
4775
4776 (defun js2-end-check-switch (node)
4777 "Consistency of return statements is checked between the case statements.
4778 If there is no default, then the switch can fall through. If there is a
4779 default, we check to see if all code paths in the default return or if
4780 there is a code path that can fall through.
4781 Returns logical OR of END_* flags."
4782 (let ((rv js2-END_UNREACHED)
4783 default-case)
4784 ;; examine the cases
4785 (catch 'break
4786 (dolist (c (js2-switch-node-cases node))
4787 (if (js2-case-node-expr c)
4788 (js2-set-flag rv (js2-end-check-block c))
4789 (setq default-case c)
4790 (throw 'break nil))))
4791 ;; we don't care how the cases drop into each other
4792 (js2-clear-flag rv js2-END_DROPS_OFF)
4793 ;; examine the default
4794 (js2-set-flag rv (if default-case
4795 (js2-end-check default-case)
4796 js2-END_DROPS_OFF))
4797 rv))
4798
4799 (defun js2-end-check-try (node)
4800 "If the block has a finally, return consistency is checked in the
4801 finally block. If all code paths in the finally return, then the
4802 returns in the try-catch blocks don't matter. If there is a code path
4803 that does not return or if there is no finally block, the returns
4804 of the try and catch blocks are checked for mismatch.
4805 Returns logical OR of END_* flags."
4806 (let ((finally (js2-try-node-finally-block node))
4807 rv)
4808 ;; check the finally if it exists
4809 (setq rv (if finally
4810 (js2-end-check (js2-finally-node-body finally))
4811 js2-END_DROPS_OFF))
4812 ;; If the finally block always returns, then none of the returns
4813 ;; in the try or catch blocks matter.
4814 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4815 (js2-clear-flag rv js2-END_DROPS_OFF)
4816 ;; examine the try block
4817 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4818 ;; check each catch block
4819 (dolist (cb (js2-try-node-catch-clauses node))
4820 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4821 rv))
4822
4823 (defun js2-end-check-loop (node)
4824 "Return statement in the loop body must be consistent.
4825 The default assumption for any kind of a loop is that it will eventually
4826 terminate. The only exception is a loop with a constant true condition.
4827 Code that follows such a loop is examined only if one can determine
4828 statically that there is a break out of the loop.
4829
4830 for(... ; ... ; ...) {}
4831 for(... in ... ) {}
4832 while(...) { }
4833 do { } while(...)
4834
4835 Returns logical OR of END_* flags."
4836 (let ((rv (js2-end-check (js2-loop-node-body node)))
4837 (condition (cond
4838 ((js2-while-node-p node)
4839 (js2-while-node-condition node))
4840 ((js2-do-node-p node)
4841 (js2-do-node-condition node))
4842 ((js2-for-node-p node)
4843 (js2-for-node-condition node)))))
4844
4845 ;; check to see if the loop condition is always true
4846 (if (and condition
4847 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4848 (js2-clear-flag rv js2-END_DROPS_OFF))
4849
4850 ;; look for effect of breaks
4851 (js2-set-flag rv (js2-node-get-prop node
4852 'CONTROL_BLOCK_PROP
4853 js2-END_UNREACHED))
4854 rv))
4855
4856 (defun js2-end-check-block (node)
4857 "A general block of code is examined statement by statement.
4858 If any statement (even a compound one) returns in all branches, then
4859 subsequent statements are not examined.
4860 Returns logical OR of END_* flags."
4861 (let* ((rv js2-END_DROPS_OFF)
4862 (kids (js2-block-node-kids node))
4863 (n (car kids)))
4864 ;; Check each statment. If the statement can continue onto the next
4865 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4866 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4867 (js2-clear-flag rv js2-END_DROPS_OFF)
4868 (js2-set-flag rv (js2-end-check n))
4869 (setq kids (cdr kids)
4870 n (car kids)))
4871 rv))
4872
4873 (defun js2-end-check-label (node)
4874 "A labeled statement implies that there may be a break to the label.
4875 The function processes the labeled statement and then checks the
4876 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4877 particular label.
4878 Returns logical OR of END_* flags."
4879 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4880 (logior rv (js2-node-get-prop node
4881 'CONTROL_BLOCK_PROP
4882 js2-END_UNREACHED))))
4883
4884 (defun js2-end-check-break (node)
4885 "When a break is encountered annotate the statement being broken
4886 out of by setting its CONTROL_BLOCK_PROP property.
4887 Returns logical OR of END_* flags."
4888 (and (js2-break-node-target node)
4889 (js2-node-set-prop (js2-break-node-target node)
4890 'CONTROL_BLOCK_PROP
4891 js2-END_DROPS_OFF))
4892 js2-END_UNREACHED)
4893
4894 (defun js2-end-check (node)
4895 "Examine the body of a function, doing a basic reachability analysis.
4896 Returns a combination of flags END_* flags that indicate
4897 how the function execution can terminate. These constitute only the
4898 pessimistic set of termination conditions. It is possible that at
4899 runtime certain code paths will never be actually taken. Hence this
4900 analysis will flag errors in cases where there may not be errors.
4901 Returns logical OR of END_* flags"
4902 (let (kid)
4903 (cond
4904 ((js2-break-node-p node)
4905 (js2-end-check-break node))
4906 ((js2-expr-stmt-node-p node)
4907 (if (setq kid (js2-expr-stmt-node-expr node))
4908 (js2-end-check kid)
4909 js2-END_DROPS_OFF))
4910 ((or (js2-continue-node-p node)
4911 (js2-throw-node-p node))
4912 js2-END_UNREACHED)
4913 ((js2-return-node-p node)
4914 (if (setq kid (js2-return-node-retval node))
4915 js2-END_RETURNS_VALUE
4916 js2-END_RETURNS))
4917 ((js2-loop-node-p node)
4918 (js2-end-check-loop node))
4919 ((js2-switch-node-p node)
4920 (js2-end-check-switch node))
4921 ((js2-labeled-stmt-node-p node)
4922 (js2-end-check-label node))
4923 ((js2-if-node-p node)
4924 (js2-end-check-if node))
4925 ((js2-try-node-p node)
4926 (js2-end-check-try node))
4927 ((js2-block-node-p node)
4928 (if (null (js2-block-node-kids node))
4929 js2-END_DROPS_OFF
4930 (js2-end-check-block node)))
4931 ((js2-yield-node-p node)
4932 js2-END_YIELDS)
4933 (t
4934 js2-END_DROPS_OFF))))
4935
4936 (defun js2-always-defined-boolean-p (node)
4937 "Check if NODE always evaluates to true or false in boolean context.
4938 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
4939 nor always false."
4940 (let ((tt (js2-node-type node))
4941 num)
4942 (cond
4943 ((or (= tt js2-FALSE) (= tt js2-NULL))
4944 'ALWAYS_FALSE)
4945 ((= tt js2-TRUE)
4946 'ALWAYS_TRUE)
4947 ((= tt js2-NUMBER)
4948 (setq num (js2-number-node-num-value node))
4949 (if (and (not (eq num 0.0e+NaN))
4950 (not (zerop num)))
4951 'ALWAYS_TRUE
4952 'ALWAYS_FALSE))
4953 (t
4954 nil))))
4955
4956 ;;; Scanner -- a port of Mozilla Rhino's lexer.
4957 ;; Corresponds to Rhino files Token.java and TokenStream.java.
4958
4959 (defvar js2-tokens nil
4960 "List of all defined token names.") ; initialized in `js2-token-names'
4961
4962 (defconst js2-token-names
4963 (let* ((names (make-vector js2-num-tokens -1))
4964 (case-fold-search nil) ; only match js2-UPPER_CASE
4965 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
4966 (loop for sym in syms
4967 for i from 0
4968 do
4969 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
4970 (not (boundp sym)))
4971 (aset names (symbol-value sym) ; code, e.g. 152
4972 (downcase
4973 (substring (symbol-name sym) 4))) ; name, e.g. "let"
4974 (push sym js2-tokens)))
4975 names)
4976 "Vector mapping int values to token string names, sans `js2-' prefix.")
4977
4978 (defun js2-token-name (tok)
4979 "Return a string name for TOK, a token symbol or code.
4980 Signals an error if it's not a recognized token."
4981 (let ((code tok))
4982 (if (symbolp tok)
4983 (setq code (symbol-value tok)))
4984 (if (eq code -1)
4985 "ERROR"
4986 (if (and (numberp code)
4987 (not (minusp code))
4988 (< code js2-num-tokens))
4989 (aref js2-token-names code)
4990 (error "Invalid token: %s" code)))))
4991
4992 (defsubst js2-token-sym (tok)
4993 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
4994 (intern (js2-token-name tok)))
4995
4996 (defconst js2-token-codes
4997 (let ((table (make-hash-table :test 'eq :size 256)))
4998 (loop for name across js2-token-names
4999 for sym = (intern (concat "js2-" (upcase name)))
5000 do
5001 (puthash sym (symbol-value sym) table))
5002 ;; clean up a few that are "wrong" in Rhino's token codes
5003 (puthash 'js2-DELETE js2-DELPROP table)
5004 table)
5005 "Hashtable mapping token symbols to their bytecodes.")
5006
5007 (defsubst js2-token-code (sym)
5008 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5009 (or (gethash sym js2-token-codes)
5010 (error "Invalid token symbol: %s " sym))) ; signal code bug
5011
5012 (defun js2-report-scan-error (msg &optional no-throw beg len)
5013 (setq js2-token-end js2-ts-cursor)
5014 (js2-report-error msg nil
5015 (or beg js2-token-beg)
5016 (or len (- js2-token-end js2-token-beg)))
5017 (unless no-throw
5018 (throw 'return js2-ERROR)))
5019
5020 (defun js2-get-string-from-buffer ()
5021 "Reverse the char accumulator and return it as a string."
5022 (setq js2-token-end js2-ts-cursor)
5023 (if js2-ts-string-buffer
5024 (apply #'string (nreverse js2-ts-string-buffer))
5025 ""))
5026
5027 ;; TODO: could potentially avoid a lot of consing by allocating a
5028 ;; char buffer the way Rhino does.
5029 (defsubst js2-add-to-string (c)
5030 (push c js2-ts-string-buffer))
5031
5032 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5033 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5034 ;; any other character: when it's not part of the current token, we
5035 ;; unget it, allowing it to be read again by the following call.
5036 (defsubst js2-unget-char ()
5037 (decf js2-ts-cursor))
5038
5039 ;; Rhino distinguishes \r and \n line endings. We don't need to
5040 ;; because we only scan from Emacs buffers, which always use \n.
5041 (defun js2-get-char ()
5042 "Read and return the next character from the input buffer.
5043 Increments `js2-ts-lineno' if the return value is a newline char.
5044 Updates `js2-ts-cursor' to the point after the returned char.
5045 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5046 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5047 (let (c)
5048 ;; check for end of buffer
5049 (if (>= js2-ts-cursor (point-max))
5050 (setq js2-ts-hit-eof t
5051 js2-ts-cursor (1+ js2-ts-cursor)
5052 c js2-EOF_CHAR) ; return value
5053 ;; otherwise read next char
5054 (setq c (char-before (incf js2-ts-cursor)))
5055 ;; if we read a newline, update counters
5056 (if (= c ?\n)
5057 (setq js2-ts-line-start js2-ts-cursor
5058 js2-ts-lineno (1+ js2-ts-lineno)))
5059 ;; TODO: skip over format characters
5060 c)))
5061
5062 (defun js2-read-unicode-escape ()
5063 "Read a \\uNNNN sequence from the input.
5064 Assumes the ?\ and ?u have already been read.
5065 Returns the unicode character, or nil if it wasn't a valid character.
5066 Doesn't change the values of any scanner variables."
5067 ;; I really wish I knew a better way to do this, but I can't
5068 ;; find the Emacs function that takes a 16-bit int and converts
5069 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5070 ;; Have to first check that it's 4 hex characters or it may stop
5071 ;; the read early.
5072 (ignore-errors
5073 (let ((s (buffer-substring-no-properties js2-ts-cursor
5074 (+ 4 js2-ts-cursor))))
5075 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5076 (read (concat "?\\u" s))))))
5077
5078 (defun js2-match-char (test)
5079 "Consume and return next character if it matches TEST, a character.
5080 Returns nil and consumes nothing if TEST is not the next character."
5081 (let ((c (js2-get-char)))
5082 (if (eq c test)
5083 t
5084 (js2-unget-char)
5085 nil)))
5086
5087 (defun js2-peek-char ()
5088 (prog1
5089 (js2-get-char)
5090 (js2-unget-char)))
5091
5092 (defun js2-java-identifier-start-p (c)
5093 (or
5094 (memq c '(?$ ?_))
5095 (js2-char-uppercase-p c)
5096 (js2-char-lowercase-p c)))
5097
5098 (defun js2-java-identifier-part-p (c)
5099 "Implementation of java.lang.Character.isJavaIdentifierPart()."
5100 ;; TODO: make me Unicode-friendly. See comments above.
5101 (or
5102 (memq c '(?$ ?_))
5103 (js2-char-uppercase-p c)
5104 (js2-char-lowercase-p c)
5105 (and (>= c ?0) (<= c ?9))))
5106
5107 (defun js2-alpha-p (c)
5108 (cond ((and (<= ?A c) (<= c ?Z)) t)
5109 ((and (<= ?a c) (<= c ?z)) t)
5110 (t nil)))
5111
5112 (defsubst js2-digit-p (c)
5113 (and (<= ?0 c) (<= c ?9)))
5114
5115 (defun js2-js-space-p (c)
5116 (if (<= c 127)
5117 (memq c '(#x20 #x9 #xB #xC #xD))
5118 (or
5119 (eq c #xA0)
5120 ;; TODO: change this nil to check for Unicode space character
5121 nil)))
5122
5123 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5124
5125 (defun js2-skip-line ()
5126 "Skip to end of line."
5127 (let (c)
5128 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5129 (js2-unget-char)
5130 (setq js2-token-end js2-ts-cursor)))
5131
5132 (defun js2-init-scanner (&optional buf line)
5133 "Create token stream for BUF starting on LINE.
5134 BUF defaults to `current-buffer' and LINE defaults to 1.
5135
5136 A buffer can only have one scanner active at a time, which yields
5137 dramatically simpler code than using a defstruct. If you need to
5138 have simultaneous scanners in a buffer, copy the regions to scan
5139 into temp buffers."
5140 (with-current-buffer (or buf (current-buffer))
5141 (setq js2-ts-dirty-line nil
5142 js2-ts-regexp-flags nil
5143 js2-ts-string ""
5144 js2-ts-number nil
5145 js2-ts-hit-eof nil
5146 js2-ts-line-start 0
5147 js2-ts-lineno (or line 1)
5148 js2-ts-line-end-char -1
5149 js2-ts-cursor (point-min)
5150 js2-ts-is-xml-attribute nil
5151 js2-ts-xml-is-tag-content nil
5152 js2-ts-xml-open-tags-count 0
5153 js2-ts-string-buffer nil)))
5154
5155 ;; This function uses the cached op, string and number fields in
5156 ;; TokenStream; if getToken has been called since the passed token
5157 ;; was scanned, the op or string printed may be incorrect.
5158 (defun js2-token-to-string (token)
5159 ;; Not sure where this function is used in Rhino. Not tested.
5160 (if (not js2-debug-print-trees)
5161 ""
5162 (let ((name (js2-token-name token)))
5163 (cond
5164 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5165 (concat name " `" js2-ts-string "'"))
5166 ((eq token js2-NUMBER)
5167 (format "NUMBER %g" js2-ts-number))
5168 (t
5169 name)))))
5170
5171 (defconst js2-keywords
5172 '(break
5173 case catch const continue
5174 debugger default delete do
5175 else enum
5176 false finally for function
5177 if in instanceof import
5178 let
5179 new null
5180 return
5181 switch
5182 this throw true try typeof
5183 var void
5184 while with
5185 yield))
5186
5187 ;; Token names aren't exactly the same as the keywords, unfortunately.
5188 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5189 (defconst js2-kwd-tokens
5190 (let ((table (make-vector js2-num-tokens nil))
5191 (tokens
5192 (list js2-BREAK
5193 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5194 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5195 js2-ELSE
5196 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5197 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5198 js2-LET
5199 js2-NEW js2-NULL
5200 js2-RETURN
5201 js2-SWITCH
5202 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5203 js2-VAR
5204 js2-WHILE js2-WITH
5205 js2-YIELD)))
5206 (dolist (i tokens)
5207 (aset table i 'font-lock-keyword-face))
5208 (aset table js2-STRING 'font-lock-string-face)
5209 (aset table js2-REGEXP 'font-lock-string-face)
5210 (aset table js2-COMMENT 'font-lock-comment-face)
5211 (aset table js2-THIS 'font-lock-builtin-face)
5212 (aset table js2-VOID 'font-lock-constant-face)
5213 (aset table js2-NULL 'font-lock-constant-face)
5214 (aset table js2-TRUE 'font-lock-constant-face)
5215 (aset table js2-FALSE 'font-lock-constant-face)
5216 table)
5217 "Vector whose values are non-nil for tokens that are keywords.
5218 The values are default faces to use for highlighting the keywords.")
5219
5220 (defconst js2-reserved-words
5221 '(abstract
5222 boolean byte
5223 char class
5224 double
5225 enum export extends
5226 final float
5227 goto
5228 implements import int interface
5229 long
5230 native
5231 package private protected public
5232 short static super synchronized
5233 throws transient
5234 volatile))
5235
5236 (defconst js2-keyword-names
5237 (let ((table (make-hash-table :test 'equal)))
5238 (loop for k in js2-keywords
5239 do (puthash
5240 (symbol-name k) ; instanceof
5241 (intern (concat "js2-"
5242 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5243 table))
5244 table)
5245 "JavaScript keywords by name, mapped to their symbols.")
5246
5247 (defconst js2-reserved-word-names
5248 (let ((table (make-hash-table :test 'equal)))
5249 (loop for k in js2-reserved-words
5250 do
5251 (puthash (symbol-name k) 'js2-RESERVED table))
5252 table)
5253 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5254
5255 (defun js2-collect-string (buf)
5256 "Convert BUF, a list of chars, to a string.
5257 Reverses BUF before converting."
5258 (cond
5259 ((stringp buf)
5260 buf)
5261 ((null buf) ; for emacs21 compat
5262 "")
5263 (t
5264 (if buf
5265 (apply #'string (nreverse buf))
5266 ""))))
5267
5268 (defun js2-string-to-keyword (s)
5269 "Return token for S, a string, if S is a keyword or reserved word.
5270 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5271 (or (gethash s js2-keyword-names)
5272 (gethash s js2-reserved-word-names)))
5273
5274 (defsubst js2-ts-set-char-token-bounds ()
5275 "Used when next token is one character."
5276 (setq js2-token-beg (1- js2-ts-cursor)
5277 js2-token-end js2-ts-cursor))
5278
5279 (defsubst js2-ts-return (token)
5280 "Return an N-character TOKEN from `js2-get-token'.
5281 Updates `js2-token-end' accordingly."
5282 (setq js2-token-end js2-ts-cursor)
5283 (throw 'return token))
5284
5285 (defun js2-x-digit-to-int (c accumulator)
5286 "Build up a hex number.
5287 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5288 corresponding number. Otherwise return -1."
5289 (catch 'return
5290 (catch 'check
5291 ;; Use 0..9 < A..Z < a..z
5292 (cond
5293 ((<= c ?9)
5294 (decf c ?0)
5295 (if (<= 0 c)
5296 (throw 'check nil)))
5297 ((<= c ?F)
5298 (when (<= ?A c)
5299 (decf c (- ?A 10))
5300 (throw 'check nil)))
5301 ((<= c ?f)
5302 (when (<= ?a c)
5303 (decf c (- ?a 10))
5304 (throw 'check nil))))
5305 (throw 'return -1))
5306 (logior c (lsh accumulator 4))))
5307
5308 (defun js2-get-token ()
5309 "Return next JavaScript token, an int such as js2-RETURN."
5310 (let (c c1 identifier-start is-unicode-escape-start
5311 contains-escape escape-val escape-start str result base
5312 is-integer quote-char val look-for-slash continue)
5313 (catch 'return
5314 (while t
5315 ;; Eat whitespace, possibly sensitive to newlines.
5316 (setq continue t)
5317 (while continue
5318 (setq c (js2-get-char))
5319 (cond
5320 ((eq c js2-EOF_CHAR)
5321 (js2-ts-set-char-token-bounds)
5322 (throw 'return js2-EOF))
5323 ((eq c ?\n)
5324 (js2-ts-set-char-token-bounds)
5325 (setq js2-ts-dirty-line nil)
5326 (throw 'return js2-EOL))
5327 ((not (js2-js-space-p c))
5328 (if (/= c ?-) ; in case end of HTML comment
5329 (setq js2-ts-dirty-line t))
5330 (setq continue nil))))
5331 ;; Assume the token will be 1 char - fixed up below.
5332 (js2-ts-set-char-token-bounds)
5333 (when (eq c ?@)
5334 (throw 'return js2-XMLATTR))
5335 ;; identifier/keyword/instanceof?
5336 ;; watch out for starting with a <backslash>
5337 (cond
5338 ((eq c ?\\)
5339 (setq c (js2-get-char))
5340 (if (eq c ?u)
5341 (setq identifier-start t
5342 is-unicode-escape-start t
5343 js2-ts-string-buffer nil)
5344 (setq identifier-start nil)
5345 (js2-unget-char)
5346 (setq c ?\\)))
5347 (t
5348 (when (setq identifier-start (js2-java-identifier-start-p c))
5349 (setq js2-ts-string-buffer nil)
5350 (js2-add-to-string c))))
5351 (when identifier-start
5352 (setq contains-escape is-unicode-escape-start)
5353 (catch 'break
5354 (while t
5355 (if is-unicode-escape-start
5356 ;; strictly speaking we should probably push-back
5357 ;; all the bad characters if the <backslash>uXXXX
5358 ;; sequence is malformed. But since there isn't a
5359 ;; correct context(is there?) for a bad Unicode
5360 ;; escape sequence in an identifier, we can report
5361 ;; an error here.
5362 (progn
5363 (setq escape-val 0)
5364 (dotimes (i 4)
5365 (setq c (js2-get-char)
5366 escape-val (js2-x-digit-to-int c escape-val))
5367 ;; Next check takes care of c < 0 and bad escape
5368 (if (minusp escape-val)
5369 (throw 'break nil)))
5370 (if (minusp escape-val)
5371 (js2-report-scan-error "msg.invalid.escape" t))
5372 (js2-add-to-string escape-val)
5373 (setq is-unicode-escape-start nil))
5374 (setq c (js2-get-char))
5375 (cond
5376 ((eq c ?\\)
5377 (setq c (js2-get-char))
5378 (if (eq c ?u)
5379 (setq is-unicode-escape-start t
5380 contains-escape t)
5381 (js2-report-scan-error "msg.illegal.character" t)))
5382 (t
5383 (if (or (eq c js2-EOF_CHAR)
5384 (not (js2-java-identifier-part-p c)))
5385 (throw 'break nil))
5386 (js2-add-to-string c))))))
5387 (js2-unget-char)
5388 (setq str (js2-get-string-from-buffer))
5389 (unless contains-escape
5390 ;; OPT we shouldn't have to make a string (object!) to
5391 ;; check if it's a keyword.
5392 ;; Return the corresponding token if it's a keyword
5393 (when (setq result (js2-string-to-keyword str))
5394 (if (and (< js2-language-version 170)
5395 (memq result '(js2-LET js2-YIELD)))
5396 ;; LET and YIELD are tokens only in 1.7 and later
5397 (setq result 'js2-NAME))
5398 (if (not (eq result 'js2-RESERVED))
5399 (throw 'return (js2-token-code result)))
5400 (js2-report-warning "msg.reserved.keyword" str)))
5401 ;; If we want to intern these as Rhino does, just use (intern str)
5402 (setq js2-ts-string str)
5403 (throw 'return js2-NAME)) ; end identifier/kwd check
5404 ;; is it a number?
5405 (when (or (js2-digit-p c)
5406 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5407 (setq js2-ts-string-buffer nil
5408 base 10)
5409 (when (eq c ?0)
5410 (setq c (js2-get-char))
5411 (cond
5412 ((or (eq c ?x) (eq c ?X))
5413 (setq base 16)
5414 (setq c (js2-get-char)))
5415 ((js2-digit-p c)
5416 (setq base 8))
5417 (t
5418 (js2-add-to-string ?0))))
5419 (if (eq base 16)
5420 (while (<= 0 (js2-x-digit-to-int c 0))
5421 (js2-add-to-string c)
5422 (setq c (js2-get-char)))
5423 (while (and (<= ?0 c) (<= c ?9))
5424 ;; We permit 08 and 09 as decimal numbers, which
5425 ;; makes our behavior a superset of the ECMA
5426 ;; numeric grammar. We might not always be so
5427 ;; permissive, so we warn about it.
5428 (when (and (eq base 8) (>= c ?8))
5429 (js2-report-warning "msg.bad.octal.literal"
5430 (if (eq c ?8) "8" "9"))
5431 (setq base 10))
5432 (js2-add-to-string c)
5433 (setq c (js2-get-char))))
5434 (setq is-integer t)
5435 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5436 (setq is-integer nil)
5437 (when (eq c ?.)
5438 (loop do
5439 (js2-add-to-string c)
5440 (setq c (js2-get-char))
5441 while (js2-digit-p c)))
5442 (when (memq c '(?e ?E))
5443 (js2-add-to-string c)
5444 (setq c (js2-get-char))
5445 (when (memq c '(?+ ?-))
5446 (js2-add-to-string c)
5447 (setq c (js2-get-char)))
5448 (unless (js2-digit-p c)
5449 (js2-report-scan-error "msg.missing.exponent" t))
5450 (loop do
5451 (js2-add-to-string c)
5452 (setq c (js2-get-char))
5453 while (js2-digit-p c))))
5454 (js2-unget-char)
5455 (setq js2-ts-string (js2-get-string-from-buffer)
5456 js2-ts-number
5457 (if (and (eq base 10) (not is-integer))
5458 (string-to-number js2-ts-string)
5459 ;; TODO: call runtime number-parser. Some of it is in
5460 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5461 (string-to-number js2-ts-string)))
5462 (throw 'return js2-NUMBER))
5463 ;; is it a string?
5464 (when (memq c '(?\" ?\'))
5465 ;; We attempt to accumulate a string the fast way, by
5466 ;; building it directly out of the reader. But if there
5467 ;; are any escaped characters in the string, we revert to
5468 ;; building it out of a string buffer.
5469 (setq quote-char c
5470 js2-ts-string-buffer nil
5471 c (js2-get-char))
5472 (catch 'break
5473 (while (/= c quote-char)
5474 (catch 'continue
5475 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5476 (js2-unget-char)
5477 (setq js2-token-end js2-ts-cursor)
5478 (js2-report-error "msg.unterminated.string.lit")
5479 (throw 'return js2-STRING))
5480 (when (eq c ?\\)
5481 ;; We've hit an escaped character
5482 (setq c (js2-get-char))
5483 (case c
5484 (?b (setq c ?\b))
5485 (?f (setq c ?\f))
5486 (?n (setq c ?\n))
5487 (?r (setq c ?\r))
5488 (?t (setq c ?\t))
5489 (?v (setq c ?\v))
5490 (?u
5491 (setq c1 (js2-read-unicode-escape))
5492 (if js2-parse-ide-mode
5493 (if c1
5494 (progn
5495 ;; just copy the string in IDE-mode
5496 (js2-add-to-string ?\\)
5497 (js2-add-to-string ?u)
5498 (dotimes (i 3)
5499 (js2-add-to-string (js2-get-char)))
5500 (setq c (js2-get-char))) ; added at end of loop
5501 ;; flag it as an invalid escape
5502 (js2-report-warning "msg.invalid.escape"
5503 nil (- js2-ts-cursor 2) 6))
5504 ;; Get 4 hex digits; if the u escape is not
5505 ;; followed by 4 hex digits, use 'u' + the
5506 ;; literal character sequence that follows.
5507 (js2-add-to-string ?u)
5508 (setq escape-val 0)
5509 (dotimes (i 4)
5510 (setq c (js2-get-char)
5511 escape-val (js2-x-digit-to-int c escape-val))
5512 (if (minusp escape-val)
5513 (throw 'continue nil))
5514 (js2-add-to-string c))
5515 ;; prepare for replace of stored 'u' sequence by escape value
5516 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5517 c escape-val)))
5518 (?x
5519 ;; Get 2 hex digits, defaulting to 'x'+literal
5520 ;; sequence, as above.
5521 (setq c (js2-get-char)
5522 escape-val (js2-x-digit-to-int c 0))
5523 (if (minusp escape-val)
5524 (progn
5525 (js2-add-to-string ?x)
5526 (throw 'continue nil))
5527 (setq c1 c
5528 c (js2-get-char)
5529 escape-val (js2-x-digit-to-int c escape-val))
5530 (if (minusp escape-val)
5531 (progn
5532 (js2-add-to-string ?x)
5533 (js2-add-to-string c1)
5534 (throw 'continue nil))
5535 ;; got 2 hex digits
5536 (setq c escape-val))))
5537 (?\n
5538 ;; Remove line terminator after escape to follow
5539 ;; SpiderMonkey and C/C++
5540 (setq c (js2-get-char))
5541 (throw 'continue nil))
5542 (t
5543 (when (and (<= ?0 c) (< c ?8))
5544 (setq val (- c ?0)
5545 c (js2-get-char))
5546 (when (and (<= ?0 c) (< c ?8))
5547 (setq val (- (+ (* 8 val) c) ?0)
5548 c (js2-get-char))
5549 (when (and (<= ?0 c)
5550 (< c ?8)
5551 (< val #o37))
5552 ;; c is 3rd char of octal sequence only
5553 ;; if the resulting val <= 0377
5554 (setq val (- (+ (* 8 val) c) ?0)
5555 c (js2-get-char))))
5556 (js2-unget-char)
5557 (setq c val)))))
5558 (js2-add-to-string c)
5559 (setq c (js2-get-char)))))
5560 (setq js2-ts-string (js2-get-string-from-buffer))
5561 (throw 'return js2-STRING))
5562 (case c
5563 (?\;
5564 (throw 'return js2-SEMI))
5565 (?\[
5566 (throw 'return js2-LB))
5567 (?\]
5568 (throw 'return js2-RB))
5569 (?{
5570 (throw 'return js2-LC))
5571 (?}
5572 (throw 'return js2-RC))
5573 (?\(
5574 (throw 'return js2-LP))
5575 (?\)
5576 (throw 'return js2-RP))
5577 (?,
5578 (throw 'return js2-COMMA))
5579 (??
5580 (throw 'return js2-HOOK))
5581 (?:
5582 (if (js2-match-char ?:)
5583 (js2-ts-return js2-COLONCOLON)
5584 (throw 'return js2-COLON)))
5585 (?.
5586 (if (js2-match-char ?.)
5587 (if (js2-match-char ?.)
5588 (js2-ts-return js2-TRIPLEDOT)
5589 (js2-ts-return js2-DOTDOT))
5590 (if (js2-match-char ?\()
5591 (js2-ts-return js2-DOTQUERY)
5592 (throw 'return js2-DOT))))
5593 (?|
5594 (if (js2-match-char ?|)
5595 (throw 'return js2-OR)
5596 (if (js2-match-char ?=)
5597 (js2-ts-return js2-ASSIGN_BITOR)
5598 (throw 'return js2-BITOR))))
5599 (?^
5600 (if (js2-match-char ?=)
5601 (js2-ts-return js2-ASSIGN_BITOR)
5602 (throw 'return js2-BITXOR)))
5603 (?&
5604 (if (js2-match-char ?&)
5605 (throw 'return js2-AND)
5606 (if (js2-match-char ?=)
5607 (js2-ts-return js2-ASSIGN_BITAND)
5608 (throw 'return js2-BITAND))))
5609 (?=
5610 (if (js2-match-char ?=)
5611 (if (js2-match-char ?=)
5612 (js2-ts-return js2-SHEQ)
5613 (throw 'return js2-EQ))
5614 (throw 'return js2-ASSIGN)))
5615 (?!
5616 (if (js2-match-char ?=)
5617 (if (js2-match-char ?=)
5618 (js2-ts-return js2-SHNE)
5619 (js2-ts-return js2-NE))
5620 (throw 'return js2-NOT)))
5621 (?<
5622 ;; NB:treat HTML begin-comment as comment-till-eol
5623 (when (js2-match-char ?!)
5624 (when (js2-match-char ?-)
5625 (when (js2-match-char ?-)
5626 (js2-skip-line)
5627 (setq js2-ts-comment-type 'html)
5628 (throw 'return js2-COMMENT)))
5629 (js2-unget-char))
5630 (if (js2-match-char ?<)
5631 (if (js2-match-char ?=)
5632 (js2-ts-return js2-ASSIGN_LSH)
5633 (js2-ts-return js2-LSH))
5634 (if (js2-match-char ?=)
5635 (js2-ts-return js2-LE)
5636 (throw 'return js2-LT))))
5637 (?>
5638 (if (js2-match-char ?>)
5639 (if (js2-match-char ?>)
5640 (if (js2-match-char ?=)
5641 (js2-ts-return js2-ASSIGN_URSH)
5642 (js2-ts-return js2-URSH))
5643 (if (js2-match-char ?=)
5644 (js2-ts-return js2-ASSIGN_RSH)
5645 (js2-ts-return js2-RSH)))
5646 (if (js2-match-char ?=)
5647 (js2-ts-return js2-GE)
5648 (throw 'return js2-GT))))
5649 (?*
5650 (if (js2-match-char ?=)
5651 (js2-ts-return js2-ASSIGN_MUL)
5652 (throw 'return js2-MUL)))
5653 (?/
5654 ;; is it a // comment?
5655 (when (js2-match-char ?/)
5656 (setq js2-token-beg (- js2-ts-cursor 2))
5657 (js2-skip-line)
5658 (setq js2-ts-comment-type 'line)
5659 ;; include newline so highlighting goes to end of window
5660 (incf js2-token-end)
5661 (throw 'return js2-COMMENT))
5662 ;; is it a /* comment?
5663 (when (js2-match-char ?*)
5664 (setq look-for-slash nil
5665 js2-token-beg (- js2-ts-cursor 2)
5666 js2-ts-comment-type
5667 (if (js2-match-char ?*)
5668 (progn
5669 (setq look-for-slash t)
5670 'jsdoc)
5671 'block))
5672 (while t
5673 (setq c (js2-get-char))
5674 (cond
5675 ((eq c js2-EOF_CHAR)
5676 (setq js2-token-end (1- js2-ts-cursor))
5677 (js2-report-error "msg.unterminated.comment")
5678 (throw 'return js2-COMMENT))
5679 ((eq c ?*)
5680 (setq look-for-slash t))
5681 ((eq c ?/)
5682 (if look-for-slash
5683 (js2-ts-return js2-COMMENT)))
5684 (t
5685 (setq look-for-slash nil
5686 js2-token-end js2-ts-cursor)))))
5687 (if (js2-match-char ?=)
5688 (js2-ts-return js2-ASSIGN_DIV)
5689 (throw 'return js2-DIV)))
5690 (?#
5691 (when js2-skip-preprocessor-directives
5692 (js2-skip-line)
5693 (setq js2-ts-comment-type 'preprocessor
5694 js2-token-end js2-ts-cursor)
5695 (throw 'return js2-COMMENT))
5696 (throw 'return js2-ERROR))
5697 (?%
5698 (if (js2-match-char ?=)
5699 (js2-ts-return js2-ASSIGN_MOD)
5700 (throw 'return js2-MOD)))
5701 (?~
5702 (throw 'return js2-BITNOT))
5703 (?+
5704 (if (js2-match-char ?=)
5705 (js2-ts-return js2-ASSIGN_ADD)
5706 (if (js2-match-char ?+)
5707 (js2-ts-return js2-INC)
5708 (throw 'return js2-ADD))))
5709 (?-
5710 (cond
5711 ((js2-match-char ?=)
5712 (setq c js2-ASSIGN_SUB))
5713 ((js2-match-char ?-)
5714 (unless js2-ts-dirty-line
5715 ;; treat HTML end-comment after possible whitespace
5716 ;; after line start as comment-until-eol
5717 (when (js2-match-char ?>)
5718 (js2-skip-line)
5719 (setq js2-ts-comment-type 'html)
5720 (throw 'return js2-COMMENT)))
5721 (setq c js2-DEC))
5722 (t
5723 (setq c js2-SUB)))
5724 (setq js2-ts-dirty-line t)
5725 (js2-ts-return c))
5726 (otherwise
5727 (js2-report-scan-error "msg.illegal.character")))))))
5728
5729 (defun js2-read-regexp (start-token)
5730 "Called by parser when it gets / or /= in literal context."
5731 (let (c err
5732 in-class ; inside a '[' .. ']' character-class
5733 flags
5734 (continue t))
5735 (setq js2-token-beg js2-ts-cursor
5736 js2-ts-string-buffer nil
5737 js2-ts-regexp-flags nil)
5738 (if (eq start-token js2-ASSIGN_DIV)
5739 ;; mis-scanned /=
5740 (js2-add-to-string ?=)
5741 (if (not (eq start-token js2-DIV))
5742 (error "failed assertion")))
5743 (while (and (not err)
5744 (or (/= (setq c (js2-get-char)) ?/)
5745 in-class))
5746 (cond
5747 ((or (= c ?\n)
5748 (= c js2-EOF_CHAR))
5749 (setq js2-token-end (1- js2-ts-cursor)
5750 err t
5751 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5752 (js2-report-error "msg.unterminated.re.lit"))
5753 (t (cond
5754 ((= c ?\\)
5755 (js2-add-to-string c)
5756 (setq c (js2-get-char)))
5757 ((= c ?\[)
5758 (setq in-class t))
5759 ((= c ?\])
5760 (setq in-class nil)))
5761 (js2-add-to-string c))))
5762 (unless err
5763 (while continue
5764 (cond
5765 ((js2-match-char ?g)
5766 (push ?g flags))
5767 ((js2-match-char ?i)
5768 (push ?i flags))
5769 ((js2-match-char ?m)
5770 (push ?m flags))
5771 (t
5772 (setq continue nil))))
5773 (if (js2-alpha-p (js2-peek-char))
5774 (js2-report-scan-error "msg.invalid.re.flag" t
5775 js2-ts-cursor 1))
5776 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5777 js2-ts-regexp-flags (js2-collect-string flags)
5778 js2-token-end js2-ts-cursor)
5779 ;; tell `parse-partial-sexp' to ignore this range of chars
5780 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
5781
5782 (defun js2-get-first-xml-token ()
5783 (setq js2-ts-xml-open-tags-count 0
5784 js2-ts-is-xml-attribute nil
5785 js2-ts-xml-is-tag-content nil)
5786 (js2-unget-char)
5787 (js2-get-next-xml-token))
5788
5789 (defun js2-xml-discard-string ()
5790 "Throw away the string in progress and flag an XML parse error."
5791 (setq js2-ts-string-buffer nil
5792 js2-ts-string nil)
5793 (js2-report-scan-error "msg.XML.bad.form" t))
5794
5795 (defun js2-get-next-xml-token ()
5796 (setq js2-ts-string-buffer nil ; for recording the XML
5797 js2-token-beg js2-ts-cursor)
5798 (let (c result)
5799 (setq result
5800 (catch 'return
5801 (while t
5802 (setq c (js2-get-char))
5803 (cond
5804 ((= c js2-EOF_CHAR)
5805 (throw 'return js2-ERROR))
5806 (js2-ts-xml-is-tag-content
5807 (case c
5808 (?>
5809 (js2-add-to-string c)
5810 (setq js2-ts-xml-is-tag-content nil
5811 js2-ts-is-xml-attribute nil))
5812 (?/
5813 (js2-add-to-string c)
5814 (when (eq ?> (js2-peek-char))
5815 (setq c (js2-get-char))
5816 (js2-add-to-string c)
5817 (setq js2-ts-xml-is-tag-content nil)
5818 (decf js2-ts-xml-open-tags-count)))
5819 (?{
5820 (js2-unget-char)
5821 (setq js2-ts-string (js2-get-string-from-buffer))
5822 (throw 'return js2-XML))
5823 ((?\' ?\")
5824 (js2-add-to-string c)
5825 (unless (js2-read-quoted-string c)
5826 (throw 'return js2-ERROR)))
5827 (?=
5828 (js2-add-to-string c)
5829 (setq js2-ts-is-xml-attribute t))
5830 ((? ?\t ?\r ?\n)
5831 (js2-add-to-string c))
5832 (t
5833 (js2-add-to-string c)
5834 (setq js2-ts-is-xml-attribute nil)))
5835 (when (and (not js2-ts-xml-is-tag-content)
5836 (zerop js2-ts-xml-open-tags-count))
5837 (setq js2-ts-string (js2-get-string-from-buffer))
5838 (throw 'return js2-XMLEND)))
5839 (t
5840 ;; else not tag content
5841 (case c
5842 (?<
5843 (js2-add-to-string c)
5844 (setq c (js2-peek-char))
5845 (case c
5846 (?!
5847 (setq c (js2-get-char)) ;; skip !
5848 (js2-add-to-string c)
5849 (setq c (js2-peek-char))
5850 (case c
5851 (?-
5852 (setq c (js2-get-char)) ;; skip -
5853 (js2-add-to-string c)
5854 (if (eq c ?-)
5855 (progn
5856 (js2-add-to-string c)
5857 (unless (js2-read-xml-comment)
5858 (throw 'return js2-ERROR)))
5859 (js2-xml-discard-string)
5860 (throw 'return js2-ERROR)))
5861 (?\[
5862 (setq c (js2-get-char)) ;; skip [
5863 (js2-add-to-string c)
5864 (if (and (= (js2-get-char) ?C)
5865 (= (js2-get-char) ?D)
5866 (= (js2-get-char) ?A)
5867 (= (js2-get-char) ?T)
5868 (= (js2-get-char) ?A)
5869 (= (js2-get-char) ?\[))
5870 (progn
5871 (js2-add-to-string ?C)
5872 (js2-add-to-string ?D)
5873 (js2-add-to-string ?A)
5874 (js2-add-to-string ?T)
5875 (js2-add-to-string ?A)
5876 (js2-add-to-string ?\[)
5877 (unless (js2-read-cdata)
5878 (throw 'return js2-ERROR)))
5879 (js2-xml-discard-string)
5880 (throw 'return js2-ERROR)))
5881 (t
5882 (unless (js2-read-entity)
5883 (throw 'return js2-ERROR))))
5884 ;; Allow bare CDATA section, e.g.:
5885 ;; let xml = <![CDATA[ foo bar baz ]]>;
5886 (when (zerop js2-ts-xml-open-tags-count)
5887 (throw 'return js2-XMLEND)))
5888 (??
5889 (setq c (js2-get-char)) ;; skip ?
5890 (js2-add-to-string c)
5891 (unless (js2-read-PI)
5892 (throw 'return js2-ERROR)))
5893 (?/
5894 ;; end tag
5895 (setq c (js2-get-char)) ;; skip /
5896 (js2-add-to-string c)
5897 (when (zerop js2-ts-xml-open-tags-count)
5898 (js2-xml-discard-string)
5899 (throw 'return js2-ERROR))
5900 (setq js2-ts-xml-is-tag-content t)
5901 (decf js2-ts-xml-open-tags-count))
5902 (t
5903 ;; start tag
5904 (setq js2-ts-xml-is-tag-content t)
5905 (incf js2-ts-xml-open-tags-count))))
5906 (?{
5907 (js2-unget-char)
5908 (setq js2-ts-string (js2-get-string-from-buffer))
5909 (throw 'return js2-XML))
5910 (t
5911 (js2-add-to-string c))))))))
5912 (setq js2-token-end js2-ts-cursor)
5913 result))
5914
5915 (defun js2-read-quoted-string (quote)
5916 (let (c)
5917 (catch 'return
5918 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
5919 (js2-add-to-string c)
5920 (if (eq c quote)
5921 (throw 'return t)))
5922 (js2-xml-discard-string) ;; throw away string in progress
5923 nil)))
5924
5925 (defun js2-read-xml-comment ()
5926 (let ((c (js2-get-char)))
5927 (catch 'return
5928 (while (/= c js2-EOF_CHAR)
5929 (catch 'continue
5930 (js2-add-to-string c)
5931 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
5932 (setq c (js2-get-char))
5933 (js2-add-to-string c)
5934 (if (eq (js2-peek-char) ?>)
5935 (progn
5936 (setq c (js2-get-char)) ;; skip >
5937 (js2-add-to-string c)
5938 (throw 'return t))
5939 (throw 'continue nil)))
5940 (setq c (js2-get-char))))
5941 (js2-xml-discard-string)
5942 nil)))
5943
5944 (defun js2-read-cdata ()
5945 (let ((c (js2-get-char)))
5946 (catch 'return
5947 (while (/= c js2-EOF_CHAR)
5948 (catch 'continue
5949 (js2-add-to-string c)
5950 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
5951 (setq c (js2-get-char))
5952 (js2-add-to-string c)
5953 (if (eq (js2-peek-char) ?>)
5954 (progn
5955 (setq c (js2-get-char)) ;; Skip >
5956 (js2-add-to-string c)
5957 (throw 'return t))
5958 (throw 'continue nil)))
5959 (setq c (js2-get-char))))
5960 (js2-xml-discard-string)
5961 nil)))
5962
5963 (defun js2-read-entity ()
5964 (let ((decl-tags 1)
5965 c)
5966 (catch 'return
5967 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
5968 (js2-add-to-string c)
5969 (case c
5970 (?<
5971 (incf decl-tags))
5972 (?>
5973 (decf decl-tags)
5974 (if (zerop decl-tags)
5975 (throw 'return t)))))
5976 (js2-xml-discard-string)
5977 nil)))
5978
5979 (defun js2-read-PI ()
5980 "Scan an XML processing instruction."
5981 (let (c)
5982 (catch 'return
5983 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
5984 (js2-add-to-string c)
5985 (when (and (eq c ??) (eq (js2-peek-char) ?>))
5986 (setq c (js2-get-char)) ;; Skip >
5987 (js2-add-to-string c)
5988 (throw 'return t)))
5989 (js2-xml-discard-string)
5990 nil)))
5991
5992 ;;; Highlighting
5993
5994 (defun js2-set-face (beg end face &optional record)
5995 "Fontify a region. If RECORD is non-nil, record for later."
5996 (when (plusp js2-highlight-level)
5997 (setq beg (min (point-max) beg)
5998 beg (max (point-min) beg)
5999 end (min (point-max) end)
6000 end (max (point-min) end))
6001 (if record
6002 (push (list beg end face) js2-mode-fontifications)
6003 (put-text-property beg end 'font-lock-face face))))
6004
6005 (defsubst js2-clear-face (beg end)
6006 (remove-text-properties beg end '(font-lock-face nil
6007 help-echo nil
6008 point-entered nil
6009 c-in-sws nil)))
6010
6011 (defconst js2-ecma-global-props
6012 (concat "^"
6013 (regexp-opt
6014 '("Infinity" "NaN" "undefined" "arguments") t)
6015 "$")
6016 "Value properties of the Ecma-262 Global Object.
6017 Shown at or above `js2-highlight-level' 2.")
6018
6019 ;; might want to add the name "arguments" to this list?
6020 (defconst js2-ecma-object-props
6021 (concat "^"
6022 (regexp-opt
6023 '("prototype" "__proto__" "__parent__") t)
6024 "$")
6025 "Value properties of the Ecma-262 Object constructor.
6026 Shown at or above `js2-highlight-level' 2.")
6027
6028 (defconst js2-ecma-global-funcs
6029 (concat
6030 "^"
6031 (regexp-opt
6032 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6033 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6034 "$")
6035 "Function properties of the Ecma-262 Global object.
6036 Shown at or above `js2-highlight-level' 2.")
6037
6038 (defconst js2-ecma-number-props
6039 (concat "^"
6040 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6041 "NEGATIVE_INFINITY"
6042 "POSITIVE_INFINITY") t)
6043 "$")
6044 "Properties of the Ecma-262 Number constructor.
6045 Shown at or above `js2-highlight-level' 2.")
6046
6047 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6048 "Properties of the Ecma-262 Date constructor.
6049 Shown at or above `js2-highlight-level' 2.")
6050
6051 (defconst js2-ecma-math-props
6052 (concat "^"
6053 (regexp-opt
6054 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6055 t)
6056 "$")
6057 "Properties of the Ecma-262 Math object.
6058 Shown at or above `js2-highlight-level' 2.")
6059
6060 (defconst js2-ecma-math-funcs
6061 (concat "^"
6062 (regexp-opt
6063 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6064 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6065 "$")
6066 "Function properties of the Ecma-262 Math object.
6067 Shown at or above `js2-highlight-level' 2.")
6068
6069 (defconst js2-ecma-function-props
6070 (concat
6071 "^"
6072 (regexp-opt
6073 '(;; properties of the Object prototype object
6074 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6075 "toLocaleString" "toString" "valueOf"
6076 ;; properties of the Function prototype object
6077 "apply" "call"
6078 ;; properties of the Array prototype object
6079 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6080 "splice" "unshift"
6081 ;; properties of the String prototype object
6082 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6083 "localeCompare" "match" "replace" "search" "split" "substring"
6084 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6085 "toUpperCase"
6086 ;; properties of the Number prototype object
6087 "toExponential" "toFixed" "toPrecision"
6088 ;; properties of the Date prototype object
6089 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6090 "getMinutes" "getMonth" "getSeconds" "getTime"
6091 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6092 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6093 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6094 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6095 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6096 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6097 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6098 "toTimeString" "toUTCString"
6099 ;; properties of the RegExp prototype object
6100 "exec" "test"
6101 ;; properties of the JSON prototype object
6102 "parse" "stringify"
6103 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6104 "toSource" "__defineGetter__" "__defineSetter__"
6105 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6106 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6107 t)
6108 "$")
6109 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6110 Shown at or above `js2-highlight-level' 3.")
6111
6112 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6113 (let ((target-name (and target
6114 (js2-name-node-p target)
6115 (js2-name-node-name target)))
6116 (prop-name (if prop (js2-name-node-name prop)))
6117 (level1 (>= js2-highlight-level 1))
6118 (level2 (>= js2-highlight-level 2))
6119 (level3 (>= js2-highlight-level 3))
6120 pos face)
6121 (when level2
6122 (if call-p
6123 (cond
6124 ((and target prop)
6125 (cond
6126 ((and level3 (string-match js2-ecma-function-props prop-name))
6127 (setq face 'font-lock-builtin-face))
6128 ((and target-name prop)
6129 (cond
6130 ((string= target-name "Date")
6131 (if (string-match js2-ecma-date-props prop-name)
6132 (setq face 'font-lock-builtin-face)))
6133 ((string= target-name "Math")
6134 (if (string-match js2-ecma-math-funcs prop-name)
6135 (setq face 'font-lock-builtin-face)))))))
6136 (prop
6137 (if (string-match js2-ecma-global-funcs prop-name)
6138 (setq face 'font-lock-builtin-face))))
6139 (cond
6140 ((and target prop)
6141 (cond
6142 ((string= target-name "Number")
6143 (if (string-match js2-ecma-number-props prop-name)
6144 (setq face 'font-lock-constant-face)))
6145 ((string= target-name "Math")
6146 (if (string-match js2-ecma-math-props prop-name)
6147 (setq face 'font-lock-constant-face)))))
6148 (prop
6149 (if (string-match js2-ecma-object-props prop-name)
6150 (setq face 'font-lock-constant-face)))))
6151 (when face
6152 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6153 (js2-node-pos prop))) ; relative
6154 (+ pos (js2-node-len prop))
6155 face 'record)))))
6156
6157 (defun js2-parse-highlight-member-expr-node (node)
6158 "Perform syntax highlighting of EcmaScript built-in properties.
6159 The variable `js2-highlight-level' governs this highighting."
6160 (let (face target prop name pos end parent call-p callee)
6161 (cond
6162 ;; case 1: simple name, e.g. foo
6163 ((js2-name-node-p node)
6164 (setq name (js2-name-node-name node))
6165 ;; possible for name to be nil in rare cases - saw it when
6166 ;; running js2-mode on an elisp buffer. Might as well try to
6167 ;; make it so js2-mode never barfs.
6168 (when name
6169 (setq face (if (string-match js2-ecma-global-props name)
6170 'font-lock-constant-face))
6171 (when face
6172 (setq pos (js2-node-pos node)
6173 end (+ pos (js2-node-len node)))
6174 (js2-set-face pos end face 'record))))
6175 ;; case 2: property access or function call
6176 ((or (js2-prop-get-node-p node)
6177 ;; highlight function call if expr is a prop-get node
6178 ;; or a plain name (i.e. unqualified function call)
6179 (and (setq call-p (js2-call-node-p node))
6180 (setq callee (js2-call-node-target node)) ; separate setq!
6181 (or (js2-prop-get-node-p callee)
6182 (js2-name-node-p callee))))
6183 (setq parent node
6184 node (if call-p callee node))
6185 (if (and call-p (js2-name-node-p callee))
6186 (setq prop callee)
6187 (setq target (js2-prop-get-node-left node)
6188 prop (js2-prop-get-node-right node)))
6189 (cond
6190 ((js2-name-node-p target)
6191 (if (js2-name-node-p prop)
6192 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6193 (js2-parse-highlight-prop-get parent target prop call-p)
6194 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6195 (js2-parse-highlight-prop-get parent target nil call-p)))
6196 ((js2-name-node-p prop)
6197 ;; case 2c: complex target, simple name, e.g. x[y].bar
6198 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6199
6200 (defun js2-parse-highlight-member-expr-fn-name (expr)
6201 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6202 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6203 We currently only handle the case where the last component is a prop-get
6204 of a simple name. Called before EXPR has a parent node."
6205 (let (pos
6206 (name (and (js2-prop-get-node-p expr)
6207 (js2-prop-get-node-right expr))))
6208 (when (js2-name-node-p name)
6209 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6210 (js2-node-pos name)))
6211 (+ pos (js2-node-len name))
6212 'font-lock-function-name-face
6213 'record))))
6214
6215 ;; source: http://jsdoc.sourceforge.net/
6216 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6217 ;; allows type specifications, and needs work before entering the wild.
6218
6219 (defconst js2-jsdoc-param-tag-regexp
6220 (concat "^\\s-*\\*+\\s-*\\(@"
6221 "\\(?:param\\|argument\\)"
6222 "\\)"
6223 "\\s-*\\({[^}]+}\\)?" ; optional type
6224 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6225 "\\>")
6226 "Matches jsdoc tags with optional type and optional param name.")
6227
6228 (defconst js2-jsdoc-typed-tag-regexp
6229 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6230 (regexp-opt
6231 '("enum"
6232 "extends"
6233 "field"
6234 "id"
6235 "implements"
6236 "lends"
6237 "mods"
6238 "requires"
6239 "return"
6240 "returns"
6241 "throw"
6242 "throws"))
6243 "\\)\\)\\s-*\\({[^}]+}\\)?")
6244 "Matches jsdoc tags with optional type.")
6245
6246 (defconst js2-jsdoc-arg-tag-regexp
6247 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6248 (regexp-opt
6249 '("alias"
6250 "augments"
6251 "borrows"
6252 "bug"
6253 "base"
6254 "config"
6255 "default"
6256 "define"
6257 "exception"
6258 "function"
6259 "member"
6260 "memberOf"
6261 "name"
6262 "namespace"
6263 "property"
6264 "since"
6265 "suppress"
6266 "this"
6267 "throws"
6268 "type"
6269 "version"))
6270 "\\)\\)\\s-+\\([^ \t]+\\)")
6271 "Matches jsdoc tags with a single argument.")
6272
6273 (defconst js2-jsdoc-empty-tag-regexp
6274 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6275 (regexp-opt
6276 '("addon"
6277 "author"
6278 "class"
6279 "const"
6280 "constant"
6281 "constructor"
6282 "constructs"
6283 "deprecated"
6284 "desc"
6285 "description"
6286 "event"
6287 "example"
6288 "exec"
6289 "export"
6290 "fileoverview"
6291 "final"
6292 "function"
6293 "hidden"
6294 "ignore"
6295 "implicitCast"
6296 "inheritDoc"
6297 "inner"
6298 "interface"
6299 "license"
6300 "noalias"
6301 "noshadow"
6302 "notypecheck"
6303 "override"
6304 "owner"
6305 "preserve"
6306 "preserveTry"
6307 "private"
6308 "protected"
6309 "public"
6310 "static"
6311 "supported"
6312 ))
6313 "\\)\\)\\s-*")
6314 "Matches empty jsdoc tags.")
6315
6316 (defconst js2-jsdoc-link-tag-regexp
6317 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6318 "Matches a jsdoc link or code tag.")
6319
6320 (defconst js2-jsdoc-see-tag-regexp
6321 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6322 "Matches a jsdoc @see tag.")
6323
6324 (defconst js2-jsdoc-html-tag-regexp
6325 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6326 "Matches a simple (no attributes) html start- or end-tag.")
6327
6328 (defun js2-jsdoc-highlight-helper ()
6329 (js2-set-face (match-beginning 1)
6330 (match-end 1)
6331 'js2-jsdoc-tag)
6332 (if (match-beginning 2)
6333 (if (save-excursion
6334 (goto-char (match-beginning 2))
6335 (= (char-after) ?{))
6336 (js2-set-face (1+ (match-beginning 2))
6337 (1- (match-end 2))
6338 'js2-jsdoc-type)
6339 (js2-set-face (match-beginning 2)
6340 (match-end 2)
6341 'js2-jsdoc-value)))
6342 (if (match-beginning 3)
6343 (js2-set-face (match-beginning 3)
6344 (match-end 3)
6345 'js2-jsdoc-value)))
6346
6347 (defun js2-highlight-jsdoc (ast)
6348 "Highlight doc comment tags."
6349 (let ((comments (js2-ast-root-comments ast))
6350 beg end)
6351 (save-excursion
6352 (dolist (node comments)
6353 (when (eq (js2-comment-node-format node) 'jsdoc)
6354 (setq beg (js2-node-abs-pos node)
6355 end (+ beg (js2-node-len node)))
6356 (save-restriction
6357 (narrow-to-region beg end)
6358 (dolist (re (list js2-jsdoc-param-tag-regexp
6359 js2-jsdoc-typed-tag-regexp
6360 js2-jsdoc-arg-tag-regexp
6361 js2-jsdoc-link-tag-regexp
6362 js2-jsdoc-see-tag-regexp
6363 js2-jsdoc-empty-tag-regexp))
6364 (goto-char beg)
6365 (while (re-search-forward re nil t)
6366 (js2-jsdoc-highlight-helper)))
6367 ;; simple highlighting for html tags
6368 (goto-char beg)
6369 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6370 (js2-set-face (match-beginning 1)
6371 (match-end 1)
6372 'js2-jsdoc-html-tag-delimiter)
6373 (js2-set-face (match-beginning 2)
6374 (match-end 2)
6375 'js2-jsdoc-html-tag-name)
6376 (js2-set-face (match-beginning 3)
6377 (match-end 3)
6378 'js2-jsdoc-html-tag-delimiter))))))))
6379
6380 (defun js2-highlight-assign-targets (node left right)
6381 "Highlight function properties and external variables."
6382 (let (leftpos end name)
6383 ;; highlight vars and props assigned function values
6384 (when (js2-function-node-p right)
6385 (cond
6386 ;; var foo = function() {...}
6387 ((js2-name-node-p left)
6388 (setq name left))
6389 ;; foo.bar.baz = function() {...}
6390 ((and (js2-prop-get-node-p left)
6391 (js2-name-node-p (js2-prop-get-node-right left)))
6392 (setq name (js2-prop-get-node-right left))))
6393 (when name
6394 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6395 (+ leftpos (js2-node-len name))
6396 'font-lock-function-name-face
6397 'record)))))
6398
6399 (defun js2-record-name-node (node)
6400 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6401 later. NODE must be a name node."
6402 (let (leftpos end)
6403 (push (list node js2-current-scope
6404 (setq leftpos (js2-node-abs-pos node))
6405 (setq end (+ leftpos (js2-node-len node))))
6406 js2-recorded-identifiers)))
6407
6408 (defun js2-highlight-undeclared-vars ()
6409 "After entire parse is finished, look for undeclared variable references.
6410 We have to wait until entire buffer is parsed, since JavaScript permits var
6411 decls to occur after they're used.
6412
6413 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6414 it is considered declared."
6415 (let (name)
6416 (dolist (entry js2-recorded-identifiers)
6417 (destructuring-bind (name-node scope pos end) entry
6418 (setq name (js2-name-node-name name-node))
6419 (unless (or (member name js2-global-externs)
6420 (member name js2-default-externs)
6421 (member name js2-additional-externs)
6422 (js2-get-defining-scope scope name))
6423 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6424 'js2-external-variable))))
6425 (setq js2-recorded-identifiers nil)))
6426
6427 (defun js2-set-default-externs ()
6428 "Set the value of `js2-default-externs' based on the various
6429 `js2-include-?-externs' variables."
6430 (setq js2-default-externs
6431 (append js2-ecma-262-externs
6432 (if js2-include-browser-externs js2-browser-externs)
6433 (if js2-include-rhino-externs js2-rhino-externs)
6434 (if js2-include-node-externs js2-node-externs)
6435 (if (or js2-include-browser-externs js2-include-node-externs)
6436 js2-typed-array-externs))))
6437
6438 (defun js2-apply-jslint-globals ()
6439 (setq js2-additional-externs
6440 (nconc (js2-get-jslint-globals)
6441 js2-additional-externs)))
6442
6443 (defun js2-get-jslint-globals ()
6444 (loop for node in (js2-ast-root-comments js2-mode-ast)
6445 when (and (eq 'block (js2-comment-node-format node))
6446 (save-excursion
6447 (goto-char (js2-node-abs-pos node))
6448 (looking-at "/\\*global ")))
6449 append (js2-get-jslint-globals-in
6450 (match-end 0)
6451 (js2-node-abs-end node))))
6452
6453 (defun js2-get-jslint-globals-in (beg end)
6454 (let (res)
6455 (save-excursion
6456 (goto-char beg)
6457 (while (re-search-forward js2-mode-identifier-re end t)
6458 (let ((match (match-string 0)))
6459 (unless (member match '("true" "false"))
6460 (push match res)))))
6461 (nreverse res)))
6462
6463 ;;; IMenu support
6464
6465 ;; We currently only support imenu, but eventually should support speedbar and
6466 ;; possibly other browsing mechanisms.
6467
6468 ;; The basic strategy is to identify function assignment targets of the form
6469 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6470 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6471 ;; for imenu after parsing is finished.
6472
6473 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6474 ;; JavaScript, and the general problem is undecidable. However, several forms
6475 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6476 ;; include:
6477
6478 ;; function foo() -- function declaration
6479 ;; foo = function() -- function expression assigned to variable
6480 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6481 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6482 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6483 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6484 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6485 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6486 ;; function foo() {function bar() {...}} -- nested function
6487 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6488
6489 ;; This list boils down to a few forms that can be combined recursively.
6490 ;; Top-level named function declarations include both the left-hand (name)
6491 ;; and the right-hand (function value) expressions needed to produce an imenu
6492 ;; entry. The other "right-hand" forms we need to look for are:
6493 ;; - functions declared as props/getters/setters in object literals
6494 ;; - nested named function declarations
6495 ;; The "left-hand" expressions that functions can be assigned to include:
6496 ;; - local/global variables
6497 ;; - nested property-get expressions like a.b.c.d
6498 ;; - element gets like foo[10] or foo['bar'] where the index
6499 ;; expression can be trivially converted to a property name. They
6500 ;; effectively then become property gets.
6501
6502 ;; All the different definition types are canonicalized into the form
6503 ;; foo.bar.baz = position-of-function-keyword
6504
6505 ;; We need to build a trie-like structure for imenu. As an example,
6506 ;; consider the following JavaScript code:
6507
6508 ;; a = function() {...} // function at position 5
6509 ;; b = function() {...} // function at position 25
6510 ;; foo = function() {...} // function at position 100
6511 ;; foo.bar = function() {...} // function at position 200
6512 ;; foo.bar.baz = function() {...} // function at position 300
6513 ;; foo.bar.zab = function() {...} // function at position 400
6514
6515 ;; During parsing we accumulate an entry for each definition in
6516 ;; the variable `js2-imenu-recorder', like so:
6517
6518 ;; '((fn a 5)
6519 ;; (fn b 25)
6520 ;; (fn foo 100)
6521 ;; (fn foo bar 200)
6522 ;; (fn foo bar baz 300)
6523 ;; (fn foo bar zab 400))
6524
6525 ;; Where 'fn' is the respective function node.
6526 ;; After parsing these entries are merged into this alist-trie:
6527
6528 ;; '((a . 1)
6529 ;; (b . 2)
6530 ;; (foo (<definition> . 3)
6531 ;; (bar (<definition> . 6)
6532 ;; (baz . 100)
6533 ;; (zab . 200))))
6534
6535 ;; Note the wacky need for a <definition> name. The token can be anything
6536 ;; that isn't a valid JavaScript identifier, because you might make foo
6537 ;; a function and then start setting properties on it that are also functions.
6538
6539 (defun js2-prop-node-name (node)
6540 "Return the name of a node that may be a property-get/property-name.
6541 If NODE is not a valid name-node, string-node or integral number-node,
6542 returns nil. Otherwise returns the string name/value of the node."
6543 (cond
6544 ((js2-name-node-p node)
6545 (js2-name-node-name node))
6546 ((js2-string-node-p node)
6547 (js2-string-node-value node))
6548 ((and (js2-number-node-p node)
6549 (string-match "^[0-9]+$" (js2-number-node-value node)))
6550 (js2-number-node-value node))
6551 ((js2-this-node-p node)
6552 "this")))
6553
6554 (defun js2-node-qname-component (node)
6555 "Return the name of this node, if it contributes to a qname.
6556 Returns nil if the node doesn't contribute."
6557 (copy-sequence
6558 (or (js2-prop-node-name node)
6559 (if (and (js2-function-node-p node)
6560 (js2-function-node-name node))
6561 (js2-name-node-name (js2-function-node-name node))))))
6562
6563 (defun js2-record-imenu-entry (fn-node qname pos)
6564 "Add an entry to `js2-imenu-recorder'.
6565 FN-NODE should be the current item's function node.
6566
6567 Associate FN-NODE with its QNAME for later lookup.
6568 This is used in postprocessing the chain list. For each chain, we find
6569 the parent function, look up its qname, then prepend a copy of it to the chain."
6570 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6571 (unless js2-imenu-function-map
6572 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6573 (puthash fn-node qname js2-imenu-function-map))
6574
6575 (defun js2-record-imenu-functions (node &optional var)
6576 "Record function definitions for imenu.
6577 NODE is a function node or an object literal.
6578 VAR, if non-nil, is the expression that NODE is being assigned to.
6579 When passed arguments of wrong type, does nothing."
6580 (when js2-parse-ide-mode
6581 (let ((fun-p (js2-function-node-p node))
6582 qname left fname-node pos)
6583 (cond
6584 ;; non-anonymous function declaration?
6585 ((and fun-p
6586 (not var)
6587 (setq fname-node (js2-function-node-name node)))
6588 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6589 ;; for remaining forms, compute left-side tree branch first
6590 ((and var (setq qname (js2-compute-nested-prop-get var)))
6591 (cond
6592 ;; foo.bar.baz = function
6593 (fun-p
6594 (js2-record-imenu-entry node qname (js2-node-pos node)))
6595 ;; foo.bar.baz = object-literal
6596 ;; look for nested functions: {a: {b: function() {...} }}
6597 ((js2-object-node-p node)
6598 ;; Node position here is still absolute, since the parser
6599 ;; passes the assignment target and value expressions
6600 ;; to us before they are added as children of the assignment node.
6601 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6602
6603 (defun js2-compute-nested-prop-get (node)
6604 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6605 component nodes as a list. Otherwise return nil. Element-gets are treated
6606 as property-gets if the index expression is a string, or a positive integer."
6607 (let (left right head)
6608 (cond
6609 ((or (js2-name-node-p node)
6610 (js2-this-node-p node))
6611 (list node))
6612 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6613 ((js2-prop-get-node-p node) ; foo.bar
6614 (setq left (js2-prop-get-node-left node)
6615 right (js2-prop-get-node-right node))
6616 (if (setq head (js2-compute-nested-prop-get left))
6617 (nconc head (list right))))
6618 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6619 (setq left (js2-elem-get-node-target node)
6620 right (js2-elem-get-node-element node))
6621 (if (or (js2-string-node-p right) ; ['bar']
6622 (and (js2-number-node-p right) ; [10]
6623 (string-match "^[0-9]+$"
6624 (js2-number-node-value right))))
6625 (if (setq head (js2-compute-nested-prop-get left))
6626 (nconc head (list right))))))))
6627
6628 (defun js2-record-object-literal (node qname pos)
6629 "Recursively process an object literal looking for functions.
6630 NODE is an object literal that is the right-hand child of an assignment
6631 expression. QNAME is a list of nodes representing the assignment target,
6632 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6633 POS is the absolute position of the node.
6634 We do a depth-first traversal of NODE. For any functions we find,
6635 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6636 (let (left right prop-qname)
6637 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6638 (let ((left (js2-infix-node-left e))
6639 ;; Element positions are relative to the parent position.
6640 (pos (+ pos (js2-node-pos e))))
6641 (cond
6642 ;; foo: function() {...}
6643 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6644 (when (js2-prop-node-name left)
6645 ;; As a policy decision, we record the position of the property,
6646 ;; not the position of the `function' keyword, since the property
6647 ;; is effectively the name of the function.
6648 (js2-record-imenu-entry right (append qname (list left)) pos)))
6649 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6650 ((js2-object-node-p right)
6651 (js2-record-object-literal right
6652 (append qname (list (js2-infix-node-left e)))
6653 (+ pos (js2-node-pos right)))))))))
6654
6655 (defun js2-node-top-level-decl-p (node)
6656 "Return t if NODE's name is defined in the top-level scope.
6657 Also returns t if NODE's name is not defined in any scope, since it implies
6658 that it's an external variable, which must also be in the top-level scope."
6659 (let* ((name (js2-prop-node-name node))
6660 (this-scope (js2-node-get-enclosing-scope node))
6661 defining-scope)
6662 (cond
6663 ((js2-this-node-p node)
6664 nil)
6665 ((null this-scope)
6666 t)
6667 ((setq defining-scope (js2-get-defining-scope this-scope name))
6668 (js2-ast-root-p defining-scope))
6669 (t t))))
6670
6671 (defun js2-wrapper-function-p (node)
6672 "Return t if NODE is a function expression that's immediately invoked.
6673 NODE must be `js2-function-node'."
6674 (let ((parent (js2-node-parent node)))
6675 (or
6676 ;; function(){...}();
6677 (js2-call-node-p parent)
6678 (and (js2-paren-node-p parent)
6679 ;; (function(){...})();
6680 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6681 ;; (function(){...}).call(this);
6682 (and (js2-prop-get-node-p parent)
6683 (member (js2-name-node-name (js2-prop-get-node-right parent))
6684 '("call" "apply"))
6685 (js2-call-node-p (js2-node-parent parent))))))))
6686
6687 (defun js2-browse-postprocess-chains (entries)
6688 "Modify function-declaration name chains after parsing finishes.
6689 Some of the information is only available after the parse tree is complete.
6690 For instance, processing a nested scope requires a parent function node."
6691 (let (result head fn current-fn parent-qname qname p elem)
6692 (dolist (entry entries)
6693 ;; function node goes first
6694 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6695 ;; Examine head's defining scope:
6696 ;; Pre-processed chain, or top-level/external, keep as-is.
6697 (if (or (stringp head) (js2-node-top-level-decl-p head))
6698 (push chain result)
6699 (when (js2-this-node-p head)
6700 (setq chain (cdr chain))) ; discard this-node
6701 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6702 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6703 (when (eq parent-qname 'not-found)
6704 ;; anonymous function expressions are not recorded
6705 ;; during the parse, so we need to handle this case here
6706 (setq parent-qname
6707 (if (js2-wrapper-function-p fn)
6708 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6709 (if (js2-ast-root-p grandparent)
6710 nil
6711 (gethash grandparent js2-imenu-function-map 'skip)))
6712 'skip))
6713 (puthash fn parent-qname js2-imenu-function-map))
6714 (unless (eq parent-qname 'skip)
6715 ;; prefix parent fn qname to this chain.
6716 (let ((qname (append parent-qname chain)))
6717 (puthash current-fn (butlast qname) js2-imenu-function-map)
6718 (push qname result)))))))
6719 ;; finally replace each node in each chain with its name.
6720 (dolist (chain result)
6721 (setq p chain)
6722 (while p
6723 (if (js2-node-p (setq elem (car p)))
6724 (setcar p (js2-node-qname-component elem)))
6725 (setq p (cdr p))))
6726 result))
6727
6728 ;; Merge name chains into a trie-like tree structure of nested lists.
6729 ;; To simplify construction of the trie, we first build it out using the rule
6730 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6731 ;; [key, num-or-list]. The second element can be a number; if so, this key
6732 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6733 ;; associated with the key at this level.) Otherwise the second element is
6734 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6735 ;; a simple recursive formulation.
6736 ;;
6737 ;; js2-mode is building the data structure for imenu. The imenu documentation
6738 ;; claims that it's the structure above, but in practice it wants the children
6739 ;; at the same list level as the key for that level, which is how I've drawn
6740 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6741 ;; list wrapper around the children at each level.
6742 ;;
6743 ;; A completed nested imenu-alist entry looks like this:
6744 ;; '(("foo"
6745 ;; ("<definition>" . 7)
6746 ;; ("bar"
6747 ;; ("a" . 40)
6748 ;; ("b" . 60))))
6749 ;;
6750 ;; In particular, the documentation for `imenu--index-alist' says that
6751 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6752 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6753
6754 (defun js2-treeify (lst)
6755 "Convert (a b c d) to (a ((b ((c d)))))."
6756 (if (null (cddr lst)) ; list length <= 2
6757 lst
6758 (list (car lst) (list (js2-treeify (cdr lst))))))
6759
6760 (defun js2-build-alist-trie (chains trie)
6761 "Merge declaration name chains into a trie-like alist structure for imenu.
6762 CHAINS is the qname chain list produced during parsing. TRIE is a
6763 list of elements built up so far."
6764 (let (head tail pos branch kids)
6765 (dolist (chain chains)
6766 (setq head (car chain)
6767 tail (cdr chain)
6768 pos (if (numberp (car tail)) (car tail))
6769 branch (js2-find-if (lambda (n)
6770 (string= (car n) head))
6771 trie)
6772 kids (second branch))
6773 (cond
6774 ;; case 1: this key isn't in the trie yet
6775 ((null branch)
6776 (if trie
6777 (setcdr (last trie) (list (js2-treeify chain)))
6778 (setq trie (list (js2-treeify chain)))))
6779 ;; case 2: key is present with a single number entry: replace w/ list
6780 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6781 ;; ("<definition>" 20)))
6782 ((numberp kids)
6783 (setcar (cdr branch)
6784 (list (list "<definition-1>" kids)
6785 (if pos
6786 (list "<definition-2>" pos)
6787 (js2-treeify tail)))))
6788 ;; case 3: key is there (with kids), and we're a number entry
6789 (pos
6790 (setcdr (last kids)
6791 (list
6792 (list (format "<definition-%d>"
6793 (1+ (loop for kid in kids
6794 count (eq ?< (aref (car kid) 0)))))
6795 pos))))
6796 ;; case 4: key is there with kids, need to merge in our chain
6797 (t
6798 (js2-build-alist-trie (list tail) kids))))
6799 trie))
6800
6801 (defun js2-flatten-trie (trie)
6802 "Convert TRIE to imenu-format.
6803 Recurses through nodes, and for each one whose second element is a list,
6804 appends the list's flattened elements to the current element. Also
6805 changes the tails into conses. For instance, this pre-flattened trie
6806
6807 '(a ((b 20)
6808 (c ((d 30)
6809 (e 40)))))
6810
6811 becomes
6812
6813 '(a (b . 20)
6814 (c (d . 30)
6815 (e . 40)))
6816
6817 Note that the root of the trie has no key, just a list of chains.
6818 This is also true for the value of any key with multiple children,
6819 e.g. key 'c' in the example above."
6820 (cond
6821 ((listp (car trie))
6822 (mapcar #'js2-flatten-trie trie))
6823 (t
6824 (if (numberp (second trie))
6825 (cons (car trie) (second trie))
6826 ;; else pop list and append its kids
6827 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6828
6829 (defun js2-build-imenu-index ()
6830 "Turn `js2-imenu-recorder' into an imenu data structure."
6831 (unless (eq js2-imenu-recorder 'empty)
6832 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
6833 (result (js2-build-alist-trie chains nil)))
6834 (js2-flatten-trie result))))
6835
6836 (defun js2-test-print-chains (chains)
6837 "Print a list of qname chains.
6838 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
6839 i.e. one or more nodes, and an integer position as the list tail."
6840 (mapconcat (lambda (chain)
6841 (concat "("
6842 (mapconcat (lambda (elem)
6843 (if (js2-node-p elem)
6844 (or (js2-node-qname-component elem)
6845 "nil")
6846 (number-to-string elem)))
6847 chain
6848 " ")
6849 ")"))
6850 chains
6851 "\n"))
6852
6853 ;;; Parser
6854
6855 (defconst js2-version "1.8.5"
6856 "Version of JavaScript supported.")
6857
6858 (defmacro js2-record-face (face)
6859 "Record a style run of FACE for the current token."
6860 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
6861
6862 (defsubst js2-node-end (n)
6863 "Computes the absolute end of node N.
6864 Use with caution! Assumes `js2-node-pos' is -absolute-, which
6865 is only true until the node is added to its parent; i.e., while parsing."
6866 (+ (js2-node-pos n)
6867 (js2-node-len n)))
6868
6869 (defun js2-record-comment ()
6870 "Record a comment in `js2-scanned-comments'."
6871 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
6872 :format js2-ts-comment-type)
6873 js2-scanned-comments)
6874 (when js2-parse-ide-mode
6875 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
6876 'font-lock-doc-face
6877 'font-lock-comment-face))
6878 (when (memq js2-ts-comment-type '(html preprocessor))
6879 ;; Tell cc-engine the bounds of the comment.
6880 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
6881
6882 ;; This function is called depressingly often, so it should be fast.
6883 ;; Most of the time it's looking at the same token it peeked before.
6884 (defun js2-peek-token ()
6885 "Return the next token without consuming it.
6886 If previous token was consumed, calls scanner to get new token.
6887 If previous token was -not- consumed, returns it (idempotent).
6888
6889 This function will not return a newline (js2-EOL) - instead, it
6890 gobbles newlines until it finds a non-newline token, and flags
6891 that token as appearing just after a newline.
6892
6893 This function will also not return a js2-COMMENT. Instead, it
6894 records comments found in `js2-scanned-comments'. If the token
6895 returned by this function immediately follows a jsdoc comment,
6896 the token is flagged as such.
6897
6898 Note that this function always returned the un-flagged token!
6899 The flags, if any, are saved in `js2-current-flagged-token'."
6900 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
6901 js2-current-token ; most common case - return already-peeked token
6902 (let ((tt (js2-get-token)) ; call scanner
6903 saw-eol
6904 face)
6905 ;; process comments and whitespace
6906 (while (or (= tt js2-EOL)
6907 (= tt js2-COMMENT))
6908 (if (= tt js2-EOL)
6909 (setq saw-eol t)
6910 (setq saw-eol nil)
6911 (if js2-record-comments
6912 (js2-record-comment)))
6913 (setq tt (js2-get-token))) ; call scanner
6914 (setq js2-current-token tt
6915 js2-current-flagged-token (if saw-eol
6916 (logior tt js2-ti-after-eol)
6917 tt))
6918 ;; perform lexical fontification as soon as token is scanned
6919 (when js2-parse-ide-mode
6920 (cond
6921 ((minusp tt)
6922 (js2-record-face 'js2-error))
6923 ((setq face (aref js2-kwd-tokens tt))
6924 (js2-record-face face))
6925 ((and (= tt js2-NAME)
6926 (equal js2-ts-string "undefined"))
6927 (js2-record-face 'font-lock-constant-face))))
6928 tt))) ; return unflagged token
6929
6930 (defun js2-peek-flagged-token ()
6931 "Return the current token along with any flags set for it."
6932 (js2-peek-token)
6933 js2-current-flagged-token)
6934
6935 (defsubst js2-consume-token ()
6936 (setq js2-current-flagged-token js2-EOF))
6937
6938 (defun js2-next-token ()
6939 (prog1
6940 (js2-peek-token)
6941 (js2-consume-token)))
6942
6943 (defun js2-next-flagged-token ()
6944 (js2-peek-token)
6945 (prog1 js2-current-flagged-token
6946 (js2-consume-token)))
6947
6948 (defun js2-match-token (match)
6949 "Consume and return t if next token matches MATCH, a bytecode.
6950 Returns nil and consumes nothing if MATCH is not the next token."
6951 (if (/= (js2-peek-token) match)
6952 nil
6953 (js2-consume-token)
6954 t))
6955
6956 (defun js2-match-contextual-kwd (name)
6957 "Consume and return t if next token is `js2-NAME', and its
6958 string is NAME. Returns nil and does nothing otherwise."
6959 (if (or (/= (js2-peek-token) js2-NAME)
6960 (not (string= js2-ts-string name)))
6961 nil
6962 (js2-consume-token)
6963 (js2-record-face 'font-lock-keyword-face)
6964 t))
6965
6966 (defun js2-valid-prop-name-token (tt)
6967 (or (= tt js2-NAME)
6968 (when (and js2-allow-keywords-as-property-names
6969 (plusp tt)
6970 (aref js2-kwd-tokens tt))
6971 (js2-save-name-token-data js2-token-beg (js2-token-name tt))
6972 t)))
6973
6974 (defun js2-match-prop-name ()
6975 "Consume token and return t if next token is a valid property name.
6976 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
6977 is non-nil and it's a keyword token."
6978 (if (js2-valid-prop-name-token (js2-peek-token))
6979 (progn
6980 (js2-consume-token)
6981 t)
6982 nil))
6983
6984 (defun js2-must-match-prop-name (msg-id &optional pos len)
6985 (if (js2-match-prop-name)
6986 t
6987 (js2-report-error msg-id nil pos len)
6988 nil))
6989
6990 (defun js2-peek-token-or-eol ()
6991 "Return js2-EOL if the current token immediately follows a newline.
6992 Else returns the current token. Used in situations where we don't
6993 consider certain token types valid if they are preceded by a newline.
6994 One example is the postfix ++ or -- operator, which has to be on the
6995 same line as its operand."
6996 (let ((tt (js2-peek-token)))
6997 ;; Check for last peeked token flags
6998 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
6999 js2-EOL
7000 tt)))
7001
7002 (defun js2-set-check-for-label ()
7003 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7004 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7005
7006 (defun js2-must-match (token msg-id &optional pos len)
7007 "Match next token to token code TOKEN, or record a syntax error.
7008 MSG-ID is the error message to report if the match fails.
7009 Returns t on match, nil if no match."
7010 (if (js2-match-token token)
7011 t
7012 (js2-report-error msg-id nil pos len)
7013 nil))
7014
7015 (defsubst js2-inside-function ()
7016 (plusp js2-nesting-of-function))
7017
7018 (defun js2-set-requires-activation ()
7019 (if (js2-function-node-p js2-current-script-or-fn)
7020 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7021
7022 (defun js2-check-activation-name (name token)
7023 (when (js2-inside-function)
7024 ;; skip language-version 1.2 check from Rhino
7025 (if (or (string= "arguments" name)
7026 (and js2-compiler-activation-names ; only used in codegen
7027 (gethash name js2-compiler-activation-names)))
7028 (js2-set-requires-activation))))
7029
7030 (defun js2-set-is-generator ()
7031 (if (js2-function-node-p js2-current-script-or-fn)
7032 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7033
7034 (defun js2-must-have-xml ()
7035 (unless js2-compiler-xml-available
7036 (js2-report-error "msg.XML.not.available")))
7037
7038 (defun js2-push-scope (scope)
7039 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7040 (assert (js2-scope-p scope))
7041 (assert (null (js2-scope-parent-scope scope)))
7042 (assert (not (eq js2-current-scope scope)))
7043 (setf (js2-scope-parent-scope scope) js2-current-scope
7044 js2-current-scope scope))
7045
7046 (defsubst js2-pop-scope ()
7047 (setq js2-current-scope
7048 (js2-scope-parent-scope js2-current-scope)))
7049
7050 (defun js2-enter-loop (loop-node)
7051 (push loop-node js2-loop-set)
7052 (push loop-node js2-loop-and-switch-set)
7053 (js2-push-scope loop-node)
7054 ;; Tell the current labeled statement (if any) its statement,
7055 ;; and set the jump target of the first label to the loop.
7056 ;; These are used in `js2-parse-continue' to verify that the
7057 ;; continue target is an actual labeled loop. (And for codegen.)
7058 (when js2-labeled-stmt
7059 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7060 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7061 js2-labeled-stmt))) loop-node)))
7062
7063 (defun js2-exit-loop ()
7064 (pop js2-loop-set)
7065 (pop js2-loop-and-switch-set)
7066 (js2-pop-scope))
7067
7068 (defsubst js2-enter-switch (switch-node)
7069 (push switch-node js2-loop-and-switch-set))
7070
7071 (defsubst js2-exit-switch ()
7072 (pop js2-loop-and-switch-set))
7073
7074 (defun js2-parse (&optional buf cb)
7075 "Tell the js2 parser to parse a region of JavaScript.
7076
7077 BUF is a buffer or buffer name containing the code to parse.
7078 Call `narrow-to-region' first to parse only part of the buffer.
7079
7080 The returned AST root node is given some additional properties:
7081 `node-count' - total number of nodes in the AST
7082 `buffer' - BUF. The buffer it refers to may change or be killed,
7083 so the value is not necessarily reliable.
7084
7085 An optional callback CB can be specified to report parsing
7086 progress. If `(functionp CB)' returns t, it will be called with
7087 the current line number once before parsing begins, then again
7088 each time the lexer reaches a new line number.
7089
7090 CB can also be a list of the form `(symbol cb ...)' to specify
7091 multiple callbacks with different criteria. Each symbol is a
7092 criterion keyword, and the following element is the callback to
7093 call
7094
7095 :line - called whenever the line number changes
7096 :token - called for each new token consumed
7097
7098 The list of criteria could be extended to include entering or
7099 leaving a statement, an expression, or a function definition."
7100 (if (and cb (not (functionp cb)))
7101 (error "criteria callbacks not yet implemented"))
7102 (let ((inhibit-point-motion-hooks t)
7103 (js2-compiler-xml-available (>= js2-language-version 160))
7104 ;; This is a recursive-descent parser, so give it a big stack.
7105 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7106 (max-specpdl-size (max max-specpdl-size 3000))
7107 (case-fold-search nil)
7108 ast)
7109 (message nil) ; clear any error message from previous parse
7110 (with-current-buffer (or buf (current-buffer))
7111 (setq js2-scanned-comments nil
7112 js2-parsed-errors nil
7113 js2-parsed-warnings nil
7114 js2-imenu-recorder nil
7115 js2-imenu-function-map nil
7116 js2-label-set nil)
7117 (js2-init-scanner)
7118 (setq ast (with-silent-modifications
7119 (js2-do-parse)))
7120 (unless js2-ts-hit-eof
7121 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7122 (setf (js2-ast-root-errors ast) js2-parsed-errors
7123 (js2-ast-root-warnings ast) js2-parsed-warnings)
7124 ;; if we didn't find any declarations, put a dummy in this list so we
7125 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7126 (unless js2-imenu-recorder
7127 (setq js2-imenu-recorder 'empty))
7128 (run-hooks 'js2-parse-finished-hook)
7129 ast)))
7130
7131 ;; Corresponds to Rhino's Parser.parse() method.
7132 (defun js2-do-parse ()
7133 "Parse current buffer starting from current point.
7134 Scanner should be initialized."
7135 (let ((pos js2-ts-cursor)
7136 (end js2-ts-cursor) ; in case file is empty
7137 root n tt)
7138 ;; initialize buffer-local parsing vars
7139 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7140 js2-current-script-or-fn root
7141 js2-current-scope root
7142 js2-current-flagged-token js2-EOF
7143 js2-nesting-of-function 0
7144 js2-labeled-stmt nil
7145 js2-recorded-identifiers nil) ; for js2-highlight
7146 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7147 (if (= tt js2-FUNCTION)
7148 (progn
7149 (js2-consume-token)
7150 (setq n (js2-parse-function (if js2-called-by-compile-function
7151 'FUNCTION_EXPRESSION
7152 'FUNCTION_STATEMENT))))
7153 ;; not a function - parse a statement
7154 (setq n (js2-parse-statement)))
7155 ;; add function or statement to script
7156 (setq end (js2-node-end n))
7157 (js2-block-node-push root n))
7158 ;; add comments to root in lexical order
7159 (when js2-scanned-comments
7160 ;; if we find a comment beyond end of normal kids, use its end
7161 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7162 (dolist (comment js2-scanned-comments)
7163 (push comment (js2-ast-root-comments root))
7164 (js2-node-add-children root comment)))
7165 (setf (js2-node-len root) (- end pos))
7166 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7167 ;; Give extensions a chance to muck with things before highlighting starts.
7168 (let ((js2-additional-externs js2-additional-externs))
7169 (save-excursion
7170 (run-hooks 'js2-post-parse-callbacks))
7171 (js2-highlight-undeclared-vars))
7172 root))
7173
7174 (defun js2-function-parser ()
7175 (js2-consume-token)
7176 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7177
7178 (defun js2-parse-function-closure-body (fn-node)
7179 "Parse a JavaScript 1.8 function closure body."
7180 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7181 (if js2-ts-hit-eof
7182 (js2-report-error "msg.no.brace.body" nil
7183 (js2-node-pos fn-node)
7184 (- js2-ts-cursor (js2-node-pos fn-node)))
7185 (js2-node-add-children fn-node
7186 (setf (js2-function-node-body fn-node)
7187 (js2-parse-expr t))))))
7188
7189 (defun js2-parse-function-body (fn-node)
7190 (js2-must-match js2-LC "msg.no.brace.body"
7191 (js2-node-pos fn-node)
7192 (- js2-ts-cursor (js2-node-pos fn-node)))
7193 (let ((pos js2-token-beg) ; LC position
7194 (pn (make-js2-block-node)) ; starts at LC position
7195 tt
7196 end)
7197 (incf js2-nesting-of-function)
7198 (unwind-protect
7199 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7200 (= tt js2-EOF)
7201 (= tt js2-RC)))
7202 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7203 (js2-parse-statement)
7204 (js2-consume-token)
7205 (js2-parse-function 'FUNCTION_STATEMENT))))
7206 (decf js2-nesting-of-function))
7207 (setq end js2-token-end) ; assume no curly and leave at current token
7208 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7209 (setq end js2-token-end))
7210 (setf (js2-node-pos pn) pos
7211 (js2-node-len pn) (- end pos))
7212 (setf (js2-function-node-body fn-node) pn)
7213 (js2-node-add-children fn-node pn)
7214 pn))
7215
7216 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7217 "Declare and fontify destructuring parameters inside NODE.
7218 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7219 (cond
7220 ((js2-name-node-p node)
7221 (let (leftpos)
7222 (js2-define-symbol decl-type (js2-name-node-name node)
7223 node ignore-not-in-block)
7224 (when face
7225 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7226 (+ leftpos (js2-node-len node))
7227 face 'record))))
7228 ((js2-object-node-p node)
7229 (dolist (elem (js2-object-node-elems node))
7230 (js2-define-destruct-symbols
7231 (if (js2-object-prop-node-p elem)
7232 (js2-object-prop-node-right elem)
7233 ;; abbreviated destructuring {a, b}
7234 elem)
7235 decl-type face ignore-not-in-block)))
7236 ((js2-array-node-p node)
7237 (dolist (elem (js2-array-node-elems node))
7238 (when elem
7239 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7240 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7241 (js2-node-len node)))))
7242
7243 (defun js2-parse-function-params (fn-node pos)
7244 (if (js2-match-token js2-RP)
7245 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7246 (let (params len param default-found rest-param-at)
7247 (loop for tt = (js2-peek-token)
7248 do
7249 (cond
7250 ;; destructuring param
7251 ((or (= tt js2-LB) (= tt js2-LC))
7252 (when default-found
7253 (js2-report-error "msg.no.default.after.default.param"))
7254 (setq param (js2-parse-destruct-primary-expr))
7255 (js2-define-destruct-symbols param
7256 js2-LP
7257 'js2-function-param)
7258 (push param params))
7259 ;; variable name
7260 (t
7261 (when (and (>= js2-language-version 200)
7262 (js2-match-token js2-TRIPLEDOT)
7263 (not rest-param-at))
7264 ;; to report errors if there are more parameters
7265 (setq rest-param-at (length params)))
7266 (js2-must-match js2-NAME "msg.no.parm")
7267 (js2-record-face 'js2-function-param)
7268 (setq param (js2-create-name-node))
7269 (js2-define-symbol js2-LP js2-ts-string param)
7270 ;; default parameter value
7271 (when (or (and default-found
7272 (not rest-param-at)
7273 (js2-must-match js2-ASSIGN
7274 "msg.no.default.after.default.param"
7275 (js2-node-pos param)
7276 (js2-node-len param)))
7277 (and (>= js2-language-version 200)
7278 (js2-match-token js2-ASSIGN)))
7279 (let* ((pos (js2-node-pos param))
7280 (tt js2-current-token)
7281 (op-pos (- js2-token-beg pos))
7282 (left param)
7283 (right (js2-parse-assign-expr))
7284 (len (- (js2-node-end right) pos)))
7285 (setq param (make-js2-assign-node
7286 :type tt :pos pos :len len :op-pos op-pos
7287 :left left :right right)
7288 default-found t)
7289 (js2-node-add-children param left right)))
7290 (push param params)))
7291 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7292 (js2-report-error "msg.param.after.rest" nil
7293 (js2-node-pos param) (js2-node-len param)))
7294 while
7295 (js2-match-token js2-COMMA))
7296 (when (js2-must-match js2-RP "msg.no.paren.after.parms")
7297 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7298 (when rest-param-at
7299 (setf (js2-function-node-rest-p fn-node) t))
7300 (dolist (p params)
7301 (js2-node-add-children fn-node p)
7302 (push p (js2-function-node-params fn-node))))))
7303
7304 (defun js2-check-inconsistent-return-warning (fn-node name)
7305 "Possibly show inconsistent-return warning.
7306 Last token scanned is the close-curly for the function body."
7307 (when (and js2-mode-show-strict-warnings
7308 js2-strict-inconsistent-return-warning
7309 (not (js2-has-consistent-return-usage
7310 (js2-function-node-body fn-node))))
7311 ;; Have it extend from close-curly to bol or beginning of block.
7312 (let ((pos (save-excursion
7313 (goto-char js2-token-end)
7314 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7315 (point-at-bol))))
7316 (end js2-token-end))
7317 (if (plusp (js2-name-node-length name))
7318 (js2-add-strict-warning "msg.no.return.value"
7319 (js2-name-node-name name) pos end)
7320 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7321
7322 (defun js2-parse-function (function-type)
7323 "Function parser. FUNCTION-TYPE is a symbol."
7324 (let ((pos js2-token-beg) ; start of 'function' keyword
7325 name name-beg name-end fn-node lp
7326 (synthetic-type function-type)
7327 member-expr-node)
7328 ;; parse function name, expression, or non-name (anonymous)
7329 (cond
7330 ;; function foo(...)
7331 ((js2-match-token js2-NAME)
7332 (setq name (js2-create-name-node t)
7333 name-beg js2-token-beg
7334 name-end js2-token-end)
7335 (unless (js2-match-token js2-LP)
7336 (when js2-allow-member-expr-as-function-name
7337 ;; function foo.bar(...)
7338 (setq member-expr-node name
7339 name nil
7340 member-expr-node (js2-parse-member-expr-tail
7341 nil member-expr-node)))
7342 (js2-must-match js2-LP "msg.no.paren.parms")))
7343 ((js2-match-token js2-LP)
7344 nil) ; anonymous function: leave name as null
7345 (t
7346 ;; function random-member-expr(...)
7347 (when js2-allow-member-expr-as-function-name
7348 ;; Note that memberExpr can not start with '(' like
7349 ;; in function (1+2).toString(), because 'function (' already
7350 ;; processed as anonymous function
7351 (setq member-expr-node (js2-parse-member-expr)))
7352 (js2-must-match js2-LP "msg.no.paren.parms")))
7353 (if (= js2-current-token js2-LP) ; eventually matched LP?
7354 (setq lp js2-token-beg))
7355 (if member-expr-node
7356 (progn
7357 (setq synthetic-type 'FUNCTION_EXPRESSION)
7358 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7359 (if name
7360 (js2-set-face name-beg name-end
7361 'font-lock-function-name-face 'record)))
7362 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7363 (plusp (js2-name-node-length name)))
7364 ;; Function statements define a symbol in the enclosing scope
7365 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7366 (setf fn-node (make-js2-function-node :pos pos
7367 :name name
7368 :form function-type
7369 :lp (if lp (- lp pos))))
7370 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7371 ;; 1. Nested functions are not affected by the dynamic scope flag
7372 ;; as dynamic scope is already a parent of their scope.
7373 ;; 2. Functions defined under the with statement also immune to
7374 ;; this setup, in which case dynamic scope is ignored in favor
7375 ;; of the with object.
7376 (setf (js2-function-node-ignore-dynamic fn-node) t))
7377 ;; dynamically bind all the per-function variables
7378 (let ((js2-current-script-or-fn fn-node)
7379 (js2-current-scope fn-node)
7380 (js2-nesting-of-with 0)
7381 (js2-end-flags 0)
7382 js2-label-set
7383 js2-loop-set
7384 js2-loop-and-switch-set)
7385 (js2-parse-function-params fn-node pos)
7386 (if (and (>= js2-language-version 180)
7387 (/= (js2-peek-token) js2-LC))
7388 (js2-parse-function-closure-body fn-node)
7389 (js2-parse-function-body fn-node))
7390 (if name
7391 (js2-node-add-children fn-node name))
7392 (js2-check-inconsistent-return-warning fn-node name)
7393 ;; Function expressions define a name only in the body of the
7394 ;; function, and only if not hidden by a parameter name
7395 (if (and name
7396 (eq synthetic-type 'FUNCTION_EXPRESSION)
7397 (null (js2-scope-get-symbol js2-current-scope
7398 (js2-name-node-name name))))
7399 (js2-define-symbol js2-FUNCTION
7400 (js2-name-node-name name)
7401 fn-node))
7402 (if (and name
7403 (not (eq function-type 'FUNCTION_EXPRESSION)))
7404 (js2-record-imenu-functions fn-node)))
7405 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7406 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7407 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7408 ;; We wait until after parsing the function to set its parent scope,
7409 ;; since `js2-define-symbol' needs the defining-scope check to stop
7410 ;; at the function boundary when checking for redeclarations.
7411 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7412 fn-node))
7413
7414 (defun js2-parse-statements (&optional parent)
7415 "Parse a statement list. Last token consumed must be js2-LC.
7416
7417 PARENT can be a `js2-block-node', in which case the statements are
7418 appended to PARENT. Otherwise a new `js2-block-node' is created
7419 and returned.
7420
7421 This function does not match the closing js2-RC: the caller
7422 matches the RC so it can provide a suitable error message if not
7423 matched. This means it's up to the caller to set the length of
7424 the node to include the closing RC. The node start pos is set to
7425 the absolute buffer start position, and the caller should fix it
7426 up to be relative to the parent node. All children of this block
7427 node are given relative start positions and correct lengths."
7428 (let ((pn (or parent (make-js2-block-node)))
7429 tt)
7430 (setf (js2-node-pos pn) js2-token-beg)
7431 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7432 (/= tt js2-RC))
7433 (js2-block-node-push pn (js2-parse-statement)))
7434 pn))
7435
7436 (defun js2-parse-statement ()
7437 (let (tt pn beg end)
7438 ;; coarse-grained user-interrupt check - needs work
7439 (and js2-parse-interruptable-p
7440 (zerop (% (incf js2-parse-stmt-count)
7441 js2-statements-per-pause))
7442 (input-pending-p)
7443 (throw 'interrupted t))
7444 (setq pn (js2-statement-helper))
7445 ;; no-side-effects warning check
7446 (unless (js2-node-has-side-effects pn)
7447 (setq end (js2-node-end pn))
7448 (save-excursion
7449 (goto-char end)
7450 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7451 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7452 pn))
7453
7454 ;; These correspond to the switch cases in Parser.statementHelper
7455 (defconst js2-parsers
7456 (let ((parsers (make-vector js2-num-tokens
7457 #'js2-parse-expr-stmt)))
7458 (aset parsers js2-BREAK #'js2-parse-break)
7459 (aset parsers js2-CONST #'js2-parse-const-var)
7460 (aset parsers js2-CONTINUE #'js2-parse-continue)
7461 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7462 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7463 (aset parsers js2-DO #'js2-parse-do)
7464 (aset parsers js2-FOR #'js2-parse-for)
7465 (aset parsers js2-FUNCTION #'js2-function-parser)
7466 (aset parsers js2-IF #'js2-parse-if)
7467 (aset parsers js2-LC #'js2-parse-block)
7468 (aset parsers js2-LET #'js2-parse-let-stmt)
7469 (aset parsers js2-NAME #'js2-parse-name-or-label)
7470 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7471 (aset parsers js2-SEMI #'js2-parse-semi)
7472 (aset parsers js2-SWITCH #'js2-parse-switch)
7473 (aset parsers js2-THROW #'js2-parse-throw)
7474 (aset parsers js2-TRY #'js2-parse-try)
7475 (aset parsers js2-VAR #'js2-parse-const-var)
7476 (aset parsers js2-WHILE #'js2-parse-while)
7477 (aset parsers js2-WITH #'js2-parse-with)
7478 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7479 parsers)
7480 "A vector mapping token types to parser functions.")
7481
7482 (defun js2-parse-warn-missing-semi (beg end)
7483 (and js2-mode-show-strict-warnings
7484 js2-strict-missing-semi-warning
7485 (js2-add-strict-warning
7486 "msg.missing.semi" nil
7487 ;; back up to beginning of statement or line
7488 (max beg (save-excursion
7489 (goto-char end)
7490 (point-at-bol)))
7491 end)))
7492
7493 (defconst js2-no-semi-insertion
7494 (list js2-IF
7495 js2-SWITCH
7496 js2-WHILE
7497 js2-DO
7498 js2-FOR
7499 js2-TRY
7500 js2-WITH
7501 js2-LC
7502 js2-ERROR
7503 js2-SEMI
7504 js2-FUNCTION)
7505 "List of tokens that don't do automatic semicolon insertion.")
7506
7507 (defconst js2-autoinsert-semi-and-warn
7508 (list js2-ERROR js2-EOF js2-RC))
7509
7510 (defun js2-statement-helper ()
7511 (let* ((tt (js2-peek-token))
7512 (first-tt tt)
7513 (beg js2-token-beg)
7514 (parser (if (= tt js2-ERROR)
7515 #'js2-parse-semi
7516 (aref js2-parsers tt)))
7517 pn
7518 tt-flagged)
7519 ;; If the statement is set, then it's been told its label by now.
7520 (and js2-labeled-stmt
7521 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7522 (setq js2-labeled-stmt nil))
7523 (setq pn (funcall parser))
7524 ;; Don't do auto semi insertion for certain statement types.
7525 (unless (or (memq first-tt js2-no-semi-insertion)
7526 (js2-labeled-stmt-node-p pn))
7527 (js2-auto-insert-semicolon pn))
7528 pn))
7529
7530 (defun js2-auto-insert-semicolon (pn)
7531 (let* ((tt-flagged (js2-peek-flagged-token))
7532 (tt (logand tt-flagged js2-clear-ti-mask))
7533 (pos (js2-node-pos pn)))
7534 (cond
7535 ((= tt js2-SEMI)
7536 ;; Consume ';' as a part of expression
7537 (js2-consume-token)
7538 ;; extend the node bounds to include the semicolon.
7539 (setf (js2-node-len pn) (- js2-token-end pos)))
7540 ((memq tt js2-autoinsert-semi-and-warn)
7541 ;; Autoinsert ;
7542 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7543 (t
7544 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7545 ;; Report error if no EOL or autoinsert ';' otherwise
7546 (js2-report-error "msg.no.semi.stmt")
7547 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7548
7549 (defun js2-parse-condition ()
7550 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7551 The parens are discarded and the expression node is returned.
7552 The `pos' field of the return value is set to an absolute position
7553 that must be fixed up by the caller.
7554 Return value is a list (EXPR LP RP), with absolute paren positions."
7555 (let (pn lp rp)
7556 (if (js2-must-match js2-LP "msg.no.paren.cond")
7557 (setq lp js2-token-beg))
7558 (setq pn (js2-parse-expr))
7559 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7560 (setq rp js2-token-beg))
7561 ;; Report strict warning on code like "if (a = 7) ..."
7562 (if (and js2-strict-cond-assign-warning
7563 (js2-assign-node-p pn))
7564 (js2-add-strict-warning "msg.equal.as.assign" nil
7565 (js2-node-pos pn)
7566 (+ (js2-node-pos pn)
7567 (js2-node-len pn))))
7568 (list pn lp rp)))
7569
7570 (defun js2-parse-if ()
7571 "Parser for if-statement. Last matched token must be js2-IF."
7572 (let ((pos js2-token-beg)
7573 cond if-true if-false else-pos end pn)
7574 (js2-consume-token)
7575 (setq cond (js2-parse-condition)
7576 if-true (js2-parse-statement)
7577 if-false (if (js2-match-token js2-ELSE)
7578 (progn
7579 (setq else-pos (- js2-token-beg pos))
7580 (js2-parse-statement)))
7581 end (js2-node-end (or if-false if-true))
7582 pn (make-js2-if-node :pos pos
7583 :len (- end pos)
7584 :condition (car cond)
7585 :then-part if-true
7586 :else-part if-false
7587 :else-pos else-pos
7588 :lp (js2-relpos (second cond) pos)
7589 :rp (js2-relpos (third cond) pos)))
7590 (js2-node-add-children pn (car cond) if-true if-false)
7591 pn))
7592
7593 (defun js2-parse-switch ()
7594 "Parser for if-statement. Last matched token must be js2-SWITCH."
7595 (let ((pos js2-token-beg)
7596 tt pn discriminant has-default case-expr case-node
7597 case-pos cases stmt lp rp)
7598 (js2-consume-token)
7599 (if (js2-must-match js2-LP "msg.no.paren.switch")
7600 (setq lp js2-token-beg))
7601 (setq discriminant (js2-parse-expr)
7602 pn (make-js2-switch-node :discriminant discriminant
7603 :pos pos
7604 :lp (js2-relpos lp pos)))
7605 (js2-node-add-children pn discriminant)
7606 (js2-enter-switch pn)
7607 (unwind-protect
7608 (progn
7609 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7610 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7611 (js2-must-match js2-LC "msg.no.brace.switch")
7612 (catch 'break
7613 (while t
7614 (setq tt (js2-next-token)
7615 case-pos js2-token-beg)
7616 (cond
7617 ((= tt js2-RC)
7618 (setf (js2-node-len pn) (- js2-token-end pos))
7619 (throw 'break nil)) ; done
7620 ((= tt js2-CASE)
7621 (setq case-expr (js2-parse-expr))
7622 (js2-must-match js2-COLON "msg.no.colon.case"))
7623 ((= tt js2-DEFAULT)
7624 (if has-default
7625 (js2-report-error "msg.double.switch.default"))
7626 (setq has-default t
7627 case-expr nil)
7628 (js2-must-match js2-COLON "msg.no.colon.case"))
7629 (t
7630 (js2-report-error "msg.bad.switch")
7631 (throw 'break nil)))
7632 (setq case-node (make-js2-case-node :pos case-pos
7633 :len (- js2-token-end case-pos)
7634 :expr case-expr))
7635 (js2-node-add-children case-node case-expr)
7636 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7637 (/= tt js2-CASE)
7638 (/= tt js2-DEFAULT)
7639 (/= tt js2-EOF))
7640 (setf stmt (js2-parse-statement)
7641 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7642 (js2-block-node-push case-node stmt))
7643 (push case-node cases)))
7644 ;; add cases last, as pushing reverses the order to be correct
7645 (dolist (kid cases)
7646 (js2-node-add-children pn kid)
7647 (push kid (js2-switch-node-cases pn)))
7648 pn) ; return value
7649 (js2-exit-switch))))
7650
7651 (defun js2-parse-while ()
7652 "Parser for while-statement. Last matched token must be js2-WHILE."
7653 (let ((pos js2-token-beg)
7654 (pn (make-js2-while-node))
7655 cond body)
7656 (js2-consume-token)
7657 (js2-enter-loop pn)
7658 (unwind-protect
7659 (progn
7660 (setf cond (js2-parse-condition)
7661 (js2-while-node-condition pn) (car cond)
7662 body (js2-parse-statement)
7663 (js2-while-node-body pn) body
7664 (js2-node-len pn) (- (js2-node-end body) pos)
7665 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7666 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7667 (js2-node-add-children pn body (car cond)))
7668 (js2-exit-loop))
7669 pn))
7670
7671 (defun js2-parse-do ()
7672 "Parser for do-statement. Last matched token must be js2-DO."
7673 (let ((pos js2-token-beg)
7674 (pn (make-js2-do-node))
7675 cond body end)
7676 (js2-consume-token)
7677 (js2-enter-loop pn)
7678 (unwind-protect
7679 (progn
7680 (setq body (js2-parse-statement))
7681 (js2-must-match js2-WHILE "msg.no.while.do")
7682 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7683 cond (js2-parse-condition)
7684 (js2-do-node-condition pn) (car cond)
7685 (js2-do-node-body pn) body
7686 end js2-ts-cursor
7687 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7688 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7689 (js2-node-add-children pn (car cond) body))
7690 (js2-exit-loop))
7691 ;; Always auto-insert semicolon to follow SpiderMonkey:
7692 ;; It is required by ECMAScript but is ignored by the rest of
7693 ;; world; see bug 238945
7694 (if (js2-match-token js2-SEMI)
7695 (setq end js2-ts-cursor))
7696 (setf (js2-node-len pn) (- end pos))
7697 pn))
7698
7699 (defun js2-parse-for ()
7700 "Parser for for-statement. Last matched token must be js2-FOR.
7701 Parses for, for-in, and for each-in statements."
7702 (let ((for-pos js2-token-beg)
7703 pn is-for-each is-for-in-or-of is-for-of
7704 in-pos each-pos tmp-pos
7705 init ; Node init is also foo in 'foo in object'
7706 cond ; Node cond is also object in 'foo in object'
7707 incr ; 3rd section of for-loop initializer
7708 body tt lp rp)
7709 (js2-consume-token)
7710 ;; See if this is a for each () instead of just a for ()
7711 (when (js2-match-token js2-NAME)
7712 (if (string= "each" js2-ts-string)
7713 (progn
7714 (setq is-for-each t
7715 each-pos (- js2-token-beg for-pos)) ; relative
7716 (js2-record-face 'font-lock-keyword-face))
7717 (js2-report-error "msg.no.paren.for")))
7718 (if (js2-must-match js2-LP "msg.no.paren.for")
7719 (setq lp (- js2-token-beg for-pos)))
7720 (setq tt (js2-peek-token))
7721 ;; 'for' makes local scope
7722 (js2-push-scope (make-js2-scope))
7723 (unwind-protect
7724 ;; parse init clause
7725 (let ((js2-in-for-init t)) ; set as dynamic variable
7726 (cond
7727 ((= tt js2-SEMI)
7728 (setq init (make-js2-empty-expr-node)))
7729 ((or (= tt js2-VAR) (= tt js2-LET))
7730 (js2-consume-token)
7731 (setq init (js2-parse-variables tt js2-token-beg)))
7732 (t
7733 (setq init (js2-parse-expr)))))
7734 (if (or (js2-match-token js2-IN)
7735 (and (>= js2-language-version 200)
7736 (js2-match-contextual-kwd "of")
7737 (setq is-for-of t)))
7738 (setq is-for-in-or-of t
7739 in-pos (- js2-token-beg for-pos)
7740 ;; scope of iteration target object is not the scope we've created above.
7741 ;; stash current scope temporary.
7742 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7743 (js2-parse-expr))) ; object over which we're iterating
7744 ;; else ordinary for loop - parse cond and incr
7745 (js2-must-match js2-SEMI "msg.no.semi.for")
7746 (setq cond (if (= (js2-peek-token) js2-SEMI)
7747 (make-js2-empty-expr-node) ; no loop condition
7748 (js2-parse-expr)))
7749 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7750 (setq tmp-pos js2-token-end
7751 incr (if (= (js2-peek-token) js2-RP)
7752 (make-js2-empty-expr-node :pos tmp-pos)
7753 (js2-parse-expr))))
7754 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7755 (setq rp (- js2-token-beg for-pos)))
7756 (if (not is-for-in-or-of)
7757 (setq pn (make-js2-for-node :init init
7758 :condition cond
7759 :update incr
7760 :lp lp
7761 :rp rp))
7762 ;; cond could be null if 'in obj' got eaten by the init node.
7763 (if (js2-infix-node-p init)
7764 ;; it was (foo in bar) instead of (var foo in bar)
7765 (setq cond (js2-infix-node-right init)
7766 init (js2-infix-node-left init))
7767 (if (and (js2-var-decl-node-p init)
7768 (> (length (js2-var-decl-node-kids init)) 1))
7769 (js2-report-error "msg.mult.index")))
7770 (setq pn (make-js2-for-in-node :iterator init
7771 :object cond
7772 :in-pos in-pos
7773 :foreach-p is-for-each
7774 :each-pos each-pos
7775 :forof-p is-for-of
7776 :lp lp
7777 :rp rp)))
7778 (unwind-protect
7779 (progn
7780 (js2-enter-loop pn)
7781 ;; We have to parse the body -after- creating the loop node,
7782 ;; so that the loop node appears in the js2-loop-set, allowing
7783 ;; break/continue statements to find the enclosing loop.
7784 (setf body (js2-parse-statement)
7785 (js2-loop-node-body pn) body
7786 (js2-node-pos pn) for-pos
7787 (js2-node-len pn) (- (js2-node-end body) for-pos))
7788 (js2-node-add-children pn init cond incr body))
7789 ;; finally
7790 (js2-exit-loop))
7791 (js2-pop-scope))
7792 pn))
7793
7794 (defun js2-parse-try ()
7795 "Parser for try-statement. Last matched token must be js2-TRY."
7796 (let ((try-pos js2-token-beg)
7797 try-end
7798 try-block
7799 catch-blocks
7800 finally-block
7801 saw-default-catch
7802 peek
7803 param
7804 catch-cond
7805 catch-node
7806 guard-kwd
7807 catch-pos
7808 finally-pos
7809 pn
7810 block
7811 lp
7812 rp)
7813 (js2-consume-token)
7814 (if (/= (js2-peek-token) js2-LC)
7815 (js2-report-error "msg.no.brace.try"))
7816 (setq try-block (js2-parse-statement)
7817 try-end (js2-node-end try-block)
7818 peek (js2-peek-token))
7819 (cond
7820 ((= peek js2-CATCH)
7821 (while (js2-match-token js2-CATCH)
7822 (setq catch-pos js2-token-beg
7823 guard-kwd nil
7824 catch-cond nil
7825 lp nil
7826 rp nil)
7827 (if saw-default-catch
7828 (js2-report-error "msg.catch.unreachable"))
7829 (if (js2-must-match js2-LP "msg.no.paren.catch")
7830 (setq lp (- js2-token-beg catch-pos)))
7831 (js2-push-scope (make-js2-scope))
7832 (let ((tt (js2-peek-token)))
7833 (cond
7834 ;; destructuring pattern
7835 ;; catch ({ message, file }) { ... }
7836 ((or (= tt js2-LB) (= tt js2-LC))
7837 (setq param (js2-parse-destruct-primary-expr))
7838 (js2-define-destruct-symbols param js2-LET nil))
7839 ;; simple name
7840 (t
7841 (js2-must-match js2-NAME "msg.bad.catchcond")
7842 (setq param (js2-create-name-node))
7843 (js2-define-symbol js2-LET js2-ts-string param))))
7844 ;; pattern guard
7845 (if (js2-match-token js2-IF)
7846 (setq guard-kwd (- js2-token-beg catch-pos)
7847 catch-cond (js2-parse-expr))
7848 (setq saw-default-catch t))
7849 (if (js2-must-match js2-RP "msg.bad.catchcond")
7850 (setq rp (- js2-token-beg catch-pos)))
7851 (js2-must-match js2-LC "msg.no.brace.catchblock")
7852 (setq block (js2-parse-statements)
7853 try-end (js2-node-end block)
7854 catch-node (make-js2-catch-node :pos catch-pos
7855 :param param
7856 :guard-expr catch-cond
7857 :guard-kwd guard-kwd
7858 :block block
7859 :lp lp
7860 :rp rp))
7861 (js2-pop-scope)
7862 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7863 (setq try-end js2-token-beg))
7864 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7865 (js2-node-len catch-node) (- try-end catch-pos))
7866 (js2-node-add-children catch-node param catch-cond block)
7867 (push catch-node catch-blocks)))
7868 ((/= peek js2-FINALLY)
7869 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7870 (js2-node-pos try-block)
7871 (- (setq try-end (js2-node-end try-block))
7872 (js2-node-pos try-block)))))
7873 (when (js2-match-token js2-FINALLY)
7874 (setq finally-pos js2-token-beg
7875 block (js2-parse-statement)
7876 try-end (js2-node-end block)
7877 finally-block (make-js2-finally-node :pos finally-pos
7878 :len (- try-end finally-pos)
7879 :body block))
7880 (js2-node-add-children finally-block block))
7881 (setq pn (make-js2-try-node :pos try-pos
7882 :len (- try-end try-pos)
7883 :try-block try-block
7884 :finally-block finally-block))
7885 (js2-node-add-children pn try-block finally-block)
7886 ;; push them onto the try-node, which reverses and corrects their order
7887 (dolist (cb catch-blocks)
7888 (js2-node-add-children pn cb)
7889 (push cb (js2-try-node-catch-clauses pn)))
7890 pn))
7891
7892 (defun js2-parse-throw ()
7893 "Parser for throw-statement. Last matched token must be js2-THROW."
7894 (let ((pos js2-token-beg)
7895 expr pn)
7896 (js2-consume-token)
7897 (if (= (js2-peek-token-or-eol) js2-EOL)
7898 ;; ECMAScript does not allow new lines before throw expression,
7899 ;; see bug 256617
7900 (js2-report-error "msg.bad.throw.eol"))
7901 (setq expr (js2-parse-expr)
7902 pn (make-js2-throw-node :pos pos
7903 :len (- (js2-node-end expr) pos)
7904 :expr expr))
7905 (js2-node-add-children pn expr)
7906 pn))
7907
7908 (defun js2-match-jump-label-name (label-name)
7909 "If break/continue specified a label, return that label's labeled stmt.
7910 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
7911 does not match an existing label, reports an error and returns nil."
7912 (let ((bundle (cdr (assoc label-name js2-label-set))))
7913 (if (null bundle)
7914 (js2-report-error "msg.undef.label"))
7915 bundle))
7916
7917 (defun js2-parse-break ()
7918 "Parser for break-statement. Last matched token must be js2-BREAK."
7919 (let ((pos js2-token-beg)
7920 (end js2-token-end)
7921 break-target ; statement to break from
7922 break-label ; in "break foo", name-node representing the foo
7923 labels ; matching labeled statement to break to
7924 pn)
7925 (js2-consume-token) ; `break'
7926 (when (eq (js2-peek-token-or-eol) js2-NAME)
7927 (js2-consume-token)
7928 (setq break-label (js2-create-name-node)
7929 end (js2-node-end break-label)
7930 ;; matchJumpLabelName only matches if there is one
7931 labels (js2-match-jump-label-name js2-ts-string)
7932 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
7933 (unless (or break-target break-label)
7934 ;; no break target specified - try for innermost enclosing loop/switch
7935 (if (null js2-loop-and-switch-set)
7936 (unless break-label
7937 (js2-report-error "msg.bad.break" nil pos (length "break")))
7938 (setq break-target (car js2-loop-and-switch-set))))
7939 (setq pn (make-js2-break-node :pos pos
7940 :len (- end pos)
7941 :label break-label
7942 :target break-target))
7943 (js2-node-add-children pn break-label) ; but not break-target
7944 pn))
7945
7946 (defun js2-parse-continue ()
7947 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
7948 (let ((pos js2-token-beg)
7949 (end js2-token-end)
7950 label ; optional user-specified label, a `js2-name-node'
7951 labels ; current matching labeled stmt, if any
7952 target ; the `js2-loop-node' target of this continue stmt
7953 pn)
7954 (js2-consume-token) ; `continue'
7955 (when (= (js2-peek-token-or-eol) js2-NAME)
7956 (js2-consume-token)
7957 (setq label (js2-create-name-node)
7958 end (js2-node-end label)
7959 ;; matchJumpLabelName only matches if there is one
7960 labels (js2-match-jump-label-name js2-ts-string)))
7961 (cond
7962 ((null labels) ; no current label to go to
7963 (if (null js2-loop-set) ; no loop to continue to
7964 (js2-report-error "msg.continue.outside" nil pos
7965 (length "continue"))
7966 (setq target (car js2-loop-set)))) ; innermost enclosing loop
7967 (t
7968 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
7969 (setq target (js2-labeled-stmt-node-stmt labels))
7970 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
7971 (setq pn (make-js2-continue-node :pos pos
7972 :len (- end pos)
7973 :label label
7974 :target target))
7975 (js2-node-add-children pn label) ; but not target - it's not our child
7976 pn))
7977
7978 (defun js2-parse-with ()
7979 "Parser for with-statement. Last matched token must be js2-WITH."
7980 (js2-consume-token)
7981 (let ((pos js2-token-beg)
7982 obj body pn lp rp)
7983 (if (js2-must-match js2-LP "msg.no.paren.with")
7984 (setq lp js2-token-beg))
7985 (setq obj (js2-parse-expr))
7986 (if (js2-must-match js2-RP "msg.no.paren.after.with")
7987 (setq rp js2-token-beg))
7988 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
7989 (setq body (js2-parse-statement)))
7990 (setq pn (make-js2-with-node :pos pos
7991 :len (- (js2-node-end body) pos)
7992 :object obj
7993 :body body
7994 :lp (js2-relpos lp pos)
7995 :rp (js2-relpos rp pos)))
7996 (js2-node-add-children pn obj body)
7997 pn))
7998
7999 (defun js2-parse-const-var ()
8000 "Parser for var- or const-statement.
8001 Last matched token must be js2-CONST or js2-VAR."
8002 (let ((tt (js2-peek-token))
8003 (pos js2-token-beg)
8004 expr pn)
8005 (js2-consume-token)
8006 (setq expr (js2-parse-variables tt js2-token-beg)
8007 pn (make-js2-expr-stmt-node :pos pos
8008 :len (- (js2-node-end expr) pos)
8009 :expr expr))
8010 (js2-node-add-children pn expr)
8011 pn))
8012
8013 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8014 (let ((pn (make-js2-expr-stmt-node :pos pos
8015 :len (js2-node-len expr)
8016 :type (if (js2-inside-function)
8017 js2-EXPR_VOID
8018 js2-EXPR_RESULT)
8019 :expr expr)))
8020 (if add-child
8021 (js2-node-add-children pn expr))
8022 pn))
8023
8024 (defun js2-parse-let-stmt ()
8025 "Parser for let-statement. Last matched token must be js2-LET."
8026 (js2-consume-token)
8027 (let ((pos js2-token-beg)
8028 expr pn)
8029 (if (= (js2-peek-token) js2-LP)
8030 ;; let expression in statement context
8031 (setq expr (js2-parse-let pos 'statement)
8032 pn (js2-wrap-with-expr-stmt pos expr t))
8033 ;; else we're looking at a statement like let x=6, y=7;
8034 (setf expr (js2-parse-variables js2-LET pos)
8035 pn (js2-wrap-with-expr-stmt pos expr t)
8036 (js2-node-type pn) js2-EXPR_RESULT))
8037 pn))
8038
8039 (defun js2-parse-ret-yield ()
8040 (js2-parse-return-or-yield (js2-peek-token) nil))
8041
8042 (defconst js2-parse-return-stmt-enders
8043 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8044
8045 (defsubst js2-now-all-set (before after mask)
8046 "Return whether or not the bits in the mask have changed to all set.
8047 BEFORE is bits before change, AFTER is bits after change, and MASK is
8048 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8049 but not BEFORE."
8050 (and (/= (logand before mask) mask)
8051 (= (logand after mask) mask)))
8052
8053 (defun js2-parse-return-or-yield (tt expr-context)
8054 (let ((pos js2-token-beg)
8055 (end js2-token-end)
8056 (before js2-end-flags)
8057 (inside-function (js2-inside-function))
8058 e ret name)
8059 (unless inside-function
8060 (js2-report-error (if (eq tt js2-RETURN)
8061 "msg.bad.return"
8062 "msg.bad.yield")))
8063 (js2-consume-token)
8064 ;; This is ugly, but we don't want to require a semicolon.
8065 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8066 (setq e (js2-parse-expr)
8067 end (js2-node-end e)))
8068 (cond
8069 ((eq tt js2-RETURN)
8070 (js2-set-flag js2-end-flags (if (null e)
8071 js2-end-returns
8072 js2-end-returns-value))
8073 (setq ret (make-js2-return-node :pos pos
8074 :len (- end pos)
8075 :retval e))
8076 (js2-node-add-children ret e)
8077 ;; See if we need a strict mode warning.
8078 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8079 ;; more thorough and accurate than this before/after flag check.
8080 ;; E.g. if there's a finally-block that always returns, we shouldn't
8081 ;; show a warning generated by inconsistent returns in the catch blocks.
8082 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8083 ;; so we know which returns/yields to highlight, and we should get rid of
8084 ;; all the checking in `js2-parse-return-or-yield'.
8085 (if (and js2-strict-inconsistent-return-warning
8086 (js2-now-all-set before js2-end-flags
8087 (logior js2-end-returns js2-end-returns-value)))
8088 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8089 (t
8090 (unless (js2-inside-function)
8091 (js2-report-error "msg.bad.yield"))
8092 (js2-set-flag js2-end-flags js2-end-yields)
8093 (setq ret (make-js2-yield-node :pos pos
8094 :len (- end pos)
8095 :value e))
8096 (js2-node-add-children ret e)
8097 (unless expr-context
8098 (setq e ret
8099 ret (js2-wrap-with-expr-stmt pos e t))
8100 (js2-set-requires-activation)
8101 (js2-set-is-generator))))
8102 ;; see if we are mixing yields and value returns.
8103 (when (and inside-function
8104 (js2-now-all-set before js2-end-flags
8105 (logior js2-end-yields js2-end-returns-value)))
8106 (setq name (js2-function-name js2-current-script-or-fn))
8107 (if (zerop (length name))
8108 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8109 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8110 ret))
8111
8112 (defun js2-parse-debugger ()
8113 (js2-consume-token)
8114 (make-js2-keyword-node :type js2-DEBUGGER))
8115
8116 (defun js2-parse-block ()
8117 "Parser for a curly-delimited statement block.
8118 Last token matched must be `js2-LC'."
8119 (let ((pos js2-token-beg)
8120 (pn (make-js2-scope)))
8121 (js2-consume-token)
8122 (js2-push-scope pn)
8123 (unwind-protect
8124 (progn
8125 (js2-parse-statements pn)
8126 (js2-must-match js2-RC "msg.no.brace.block")
8127 (setf (js2-node-len pn) (- js2-token-end pos)))
8128 (js2-pop-scope))
8129 pn))
8130
8131 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8132 (defun js2-parse-semi ()
8133 "Parse a statement or handle an error.
8134 Last matched token is `js2-SEMI' or `js2-ERROR'."
8135 (let ((tt (js2-peek-token)) pos len)
8136 (js2-consume-token)
8137 (if (eq tt js2-SEMI)
8138 (make-js2-empty-expr-node :len 1)
8139 (setq pos js2-token-beg
8140 len (- js2-token-beg pos))
8141 (js2-report-error "msg.syntax" nil pos len)
8142 (make-js2-error-node :pos pos :len len))))
8143
8144 (defun js2-parse-default-xml-namespace ()
8145 "Parse a `default xml namespace = <expr>' e4x statement."
8146 (let ((pos js2-token-beg)
8147 end len expr unary es)
8148 (js2-consume-token)
8149 (js2-must-have-xml)
8150 (js2-set-requires-activation)
8151 (setq len (- js2-ts-cursor pos))
8152 (unless (and (js2-match-token js2-NAME)
8153 (string= js2-ts-string "xml"))
8154 (js2-report-error "msg.bad.namespace" nil pos len))
8155 (unless (and (js2-match-token js2-NAME)
8156 (string= js2-ts-string "namespace"))
8157 (js2-report-error "msg.bad.namespace" nil pos len))
8158 (unless (js2-match-token js2-ASSIGN)
8159 (js2-report-error "msg.bad.namespace" nil pos len))
8160 (setq expr (js2-parse-expr)
8161 end (js2-node-end expr)
8162 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8163 :pos pos
8164 :len (- end pos)
8165 :operand expr))
8166 (js2-node-add-children unary expr)
8167 (make-js2-expr-stmt-node :pos pos
8168 :len (- end pos)
8169 :expr unary)))
8170
8171 (defun js2-record-label (label bundle)
8172 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8173 (js2-consume-token)
8174 (let ((name (js2-label-node-name label))
8175 labeled-stmt
8176 dup)
8177 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8178 ;; flag both labels if possible when used in editing mode
8179 (if (and js2-parse-ide-mode
8180 (setq dup (js2-get-label-by-name labeled-stmt name)))
8181 (js2-report-error "msg.dup.label" nil
8182 (js2-node-abs-pos dup) (js2-node-len dup)))
8183 (js2-report-error "msg.dup.label" nil
8184 (js2-node-pos label) (js2-node-len label)))
8185 (js2-labeled-stmt-node-add-label bundle label)
8186 (js2-node-add-children bundle label)
8187 ;; Add one reference to the bundle per label in `js2-label-set'
8188 (push (cons name bundle) js2-label-set)))
8189
8190 (defun js2-parse-name-or-label ()
8191 "Parser for identifier or label. Last token matched must be js2-NAME.
8192 Called when we found a name in a statement context. If it's a label, we gather
8193 up any following labels and the next non-label statement into a
8194 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8195 expression and return it wrapped in a `js2-expr-stmt-node'."
8196 (let ((pos js2-token-beg)
8197 (end js2-token-end)
8198 expr stmt pn bundle
8199 (continue t))
8200 ;; set check for label and call down to `js2-parse-primary-expr'
8201 (js2-set-check-for-label)
8202 (setq expr (js2-parse-expr))
8203 (if (/= (js2-node-type expr) js2-LABEL)
8204 ;; Parsed non-label expression - wrap with expression stmt.
8205 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8206 ;; else parsed a label
8207 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8208 (js2-record-label expr bundle)
8209 ;; look for more labels
8210 (while (and continue (= (js2-peek-token) js2-NAME))
8211 (js2-set-check-for-label)
8212 (setq expr (js2-parse-expr))
8213 (if (/= (js2-node-type expr) js2-LABEL)
8214 (progn
8215 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8216 continue nil)
8217 (js2-auto-insert-semicolon stmt))
8218 (js2-record-label expr bundle)))
8219 ;; no more labels; now parse the labeled statement
8220 (unwind-protect
8221 (unless stmt
8222 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8223 (setq stmt (js2-statement-helper))))
8224 ;; remove the labels for this statement from the global set
8225 (dolist (label (js2-labeled-stmt-node-labels bundle))
8226 (setq js2-label-set (remove label js2-label-set))))
8227 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8228 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8229 (js2-node-add-children bundle stmt)
8230 bundle)))
8231
8232 (defun js2-parse-expr-stmt ()
8233 "Default parser in statement context, if no recognized statement found."
8234 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8235
8236 (defun js2-parse-variables (decl-type pos)
8237 "Parse a comma-separated list of variable declarations.
8238 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8239
8240 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8241 For 'var' or 'const', the keyword should be the token last scanned.
8242
8243 POS is the position where the node should start. It's sometimes the
8244 var/const/let keyword, and other times the beginning of the first token
8245 in the first variable declaration.
8246
8247 Returns the parsed `js2-var-decl-node' expression node."
8248 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8249 :pos pos))
8250 destructuring kid-pos tt init name end nbeg nend vi
8251 (continue t))
8252 ;; Example:
8253 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8254 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8255 ;; var {a, b} = baz;
8256 (while continue
8257 (setq destructuring nil
8258 name nil
8259 tt (js2-peek-token)
8260 kid-pos js2-token-beg
8261 end js2-token-end
8262 init nil)
8263 (if (or (= tt js2-LB) (= tt js2-LC))
8264 ;; Destructuring assignment, e.g., var [a, b] = ...
8265 (setq destructuring (js2-parse-destruct-primary-expr)
8266 end (js2-node-end destructuring))
8267 ;; Simple variable name
8268 (when (js2-must-match js2-NAME "msg.bad.var")
8269 (setq name (js2-create-name-node)
8270 nbeg js2-token-beg
8271 nend js2-token-end
8272 end nend)
8273 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8274 (when (js2-match-token js2-ASSIGN)
8275 (setq init (js2-parse-assign-expr)
8276 end (js2-node-end init))
8277 (js2-record-imenu-functions init name))
8278 (when name
8279 (js2-set-face nbeg nend (if (js2-function-node-p init)
8280 'font-lock-function-name-face
8281 'font-lock-variable-name-face)
8282 'record))
8283 (setq vi (make-js2-var-init-node :pos kid-pos
8284 :len (- end kid-pos)
8285 :type decl-type))
8286 (if destructuring
8287 (progn
8288 (if (and (null init) (not js2-in-for-init))
8289 (js2-report-error "msg.destruct.assign.no.init"))
8290 (js2-define-destruct-symbols destructuring
8291 decl-type
8292 'font-lock-variable-name-face)
8293 (setf (js2-var-init-node-target vi) destructuring))
8294 (setf (js2-var-init-node-target vi) name))
8295 (setf (js2-var-init-node-initializer vi) init)
8296 (js2-node-add-children vi name destructuring init)
8297 (js2-block-node-push result vi)
8298 (unless (js2-match-token js2-COMMA)
8299 (setq continue nil)))
8300 (setf (js2-node-len result) (- end pos))
8301 result))
8302
8303 (defun js2-parse-let (pos &optional stmt-p)
8304 "Parse a let expression or statement.
8305 A let-expression is of the form `let (vars) expr'.
8306 A let-statment is of the form `let (vars) {statements}'.
8307 The third form of let is a variable declaration list, handled
8308 by `js2-parse-variables'."
8309 (let ((pn (make-js2-let-node :pos pos))
8310 beg vars body)
8311 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8312 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8313 (js2-push-scope pn)
8314 (unwind-protect
8315 (progn
8316 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8317 (if (js2-must-match js2-RP "msg.no.paren.let")
8318 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8319 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8320 ;; let statement
8321 (progn
8322 (js2-consume-token)
8323 (setf beg js2-token-beg ; position stmt at LC
8324 body (js2-parse-statements))
8325 (js2-must-match js2-RC "msg.no.curly.let")
8326 (setf (js2-node-len body) (- js2-token-end beg)
8327 (js2-node-len pn) (- js2-token-end pos)
8328 (js2-let-node-body pn) body
8329 (js2-node-type pn) js2-LET))
8330 ;; let expression
8331 (setf body (js2-parse-expr)
8332 (js2-node-len pn) (- (js2-node-end body) pos)
8333 (js2-let-node-body pn) body))
8334 (js2-node-add-children pn vars body))
8335 (js2-pop-scope))
8336 pn))
8337
8338 (defun js2-define-new-symbol (decl-type name node &optional scope)
8339 (js2-scope-put-symbol (or scope js2-current-scope)
8340 name
8341 (make-js2-symbol decl-type name node)))
8342
8343 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8344 "Define a symbol in the current scope.
8345 If NODE is non-nil, it is the AST node associated with the symbol."
8346 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8347 (symbol (if defining-scope
8348 (js2-scope-get-symbol defining-scope name)))
8349 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8350 (cond
8351 ((and symbol ; already defined
8352 (or (= sdt js2-CONST) ; old version is const
8353 (= decl-type js2-CONST) ; new version is const
8354 ;; two let-bound vars in this block have same name
8355 (and (= sdt js2-LET)
8356 (eq defining-scope js2-current-scope))))
8357 (js2-report-error
8358 (cond
8359 ((= sdt js2-CONST) "msg.const.redecl")
8360 ((= sdt js2-LET) "msg.let.redecl")
8361 ((= sdt js2-VAR) "msg.var.redecl")
8362 ((= sdt js2-FUNCTION) "msg.function.redecl")
8363 (t "msg.parm.redecl"))
8364 name))
8365 ((= decl-type js2-LET)
8366 (if (and (not ignore-not-in-block)
8367 (or (= (js2-node-type js2-current-scope) js2-IF)
8368 (js2-loop-node-p js2-current-scope)))
8369 (js2-report-error "msg.let.decl.not.in.block")
8370 (js2-define-new-symbol decl-type name node)))
8371 ((or (= decl-type js2-VAR)
8372 (= decl-type js2-CONST)
8373 (= decl-type js2-FUNCTION))
8374 (if symbol
8375 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8376 (js2-add-strict-warning "msg.var.redecl" name)
8377 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8378 (js2-add-strict-warning "msg.var.hides.arg" name)))
8379 (js2-define-new-symbol decl-type name node
8380 js2-current-script-or-fn)))
8381 ((= decl-type js2-LP)
8382 (if symbol
8383 ;; must be duplicate parameter. Second parameter hides the
8384 ;; first, so go ahead and add the second pararameter
8385 (js2-report-warning "msg.dup.parms" name))
8386 (js2-define-new-symbol decl-type name node))
8387 (t (js2-code-bug)))))
8388
8389 (defun js2-parse-expr (&optional oneshot)
8390 (let* ((pn (js2-parse-assign-expr))
8391 (pos (js2-node-pos pn))
8392 left
8393 right
8394 op-pos)
8395 (while (and (not oneshot)
8396 (js2-match-token js2-COMMA))
8397 (setq op-pos (- js2-token-beg pos)) ; relative
8398 (if (= (js2-peek-token) js2-YIELD)
8399 (js2-report-error "msg.yield.parenthesized"))
8400 (setq right (js2-parse-assign-expr)
8401 left pn
8402 pn (make-js2-infix-node :type js2-COMMA
8403 :pos pos
8404 :len (- js2-ts-cursor pos)
8405 :op-pos op-pos
8406 :left left
8407 :right right))
8408 (js2-node-add-children pn left right))
8409 pn))
8410
8411 (defun js2-parse-assign-expr ()
8412 (let ((tt (js2-peek-token))
8413 (pos js2-token-beg)
8414 pn left right op-pos)
8415 (if (= tt js2-YIELD)
8416 (js2-parse-return-or-yield tt t)
8417 ;; not yield - parse assignment expression
8418 (setq pn (js2-parse-cond-expr)
8419 tt (js2-peek-token))
8420 (when (and (<= js2-first-assign tt)
8421 (<= tt js2-last-assign))
8422 ;; tt express assignment (=, |=, ^=, ..., %=)
8423 (js2-consume-token)
8424 (setq op-pos (- js2-token-beg pos) ; relative
8425 left pn
8426 right (js2-parse-assign-expr)
8427 pn (make-js2-assign-node :type tt
8428 :pos pos
8429 :len (- (js2-node-end right) pos)
8430 :op-pos op-pos
8431 :left left
8432 :right right))
8433 (when js2-parse-ide-mode
8434 (js2-highlight-assign-targets pn left right)
8435 (js2-record-imenu-functions right left))
8436 ;; do this last so ide checks above can use absolute positions
8437 (js2-node-add-children pn left right))
8438 pn)))
8439
8440 (defun js2-parse-cond-expr ()
8441 (let ((pos js2-token-beg)
8442 (pn (js2-parse-or-expr))
8443 test-expr
8444 if-true
8445 if-false
8446 q-pos
8447 c-pos)
8448 (when (js2-match-token js2-HOOK)
8449 (setq q-pos (- js2-token-beg pos)
8450 if-true (js2-parse-assign-expr))
8451 (js2-must-match js2-COLON "msg.no.colon.cond")
8452 (setq c-pos (- js2-token-beg pos)
8453 if-false (js2-parse-assign-expr)
8454 test-expr pn
8455 pn (make-js2-cond-node :pos pos
8456 :len (- (js2-node-end if-false) pos)
8457 :test-expr test-expr
8458 :true-expr if-true
8459 :false-expr if-false
8460 :q-pos q-pos
8461 :c-pos c-pos))
8462 (js2-node-add-children pn test-expr if-true if-false))
8463 pn))
8464
8465 (defun js2-make-binary (type left parser)
8466 "Helper for constructing a binary-operator AST node.
8467 LEFT is the left-side-expression, already parsed, and the
8468 binary operator should have just been matched.
8469 PARSER is a function to call to parse the right operand,
8470 or a `js2-node' struct if it has already been parsed."
8471 (let* ((pos (js2-node-pos left))
8472 (op-pos (- js2-token-beg pos))
8473 (right (if (js2-node-p parser)
8474 parser
8475 (funcall parser)))
8476 (pn (make-js2-infix-node :type type
8477 :pos pos
8478 :len (- (js2-node-end right) pos)
8479 :op-pos op-pos
8480 :left left
8481 :right right)))
8482 (js2-node-add-children pn left right)
8483 pn))
8484
8485 (defun js2-parse-or-expr ()
8486 (let ((pn (js2-parse-and-expr)))
8487 (when (js2-match-token js2-OR)
8488 (setq pn (js2-make-binary js2-OR
8489 pn
8490 'js2-parse-or-expr)))
8491 pn))
8492
8493 (defun js2-parse-and-expr ()
8494 (let ((pn (js2-parse-bit-or-expr)))
8495 (when (js2-match-token js2-AND)
8496 (setq pn (js2-make-binary js2-AND
8497 pn
8498 'js2-parse-and-expr)))
8499 pn))
8500
8501 (defun js2-parse-bit-or-expr ()
8502 (let ((pn (js2-parse-bit-xor-expr)))
8503 (while (js2-match-token js2-BITOR)
8504 (setq pn (js2-make-binary js2-BITOR
8505 pn
8506 'js2-parse-bit-xor-expr)))
8507 pn))
8508
8509 (defun js2-parse-bit-xor-expr ()
8510 (let ((pn (js2-parse-bit-and-expr)))
8511 (while (js2-match-token js2-BITXOR)
8512 (setq pn (js2-make-binary js2-BITXOR
8513 pn
8514 'js2-parse-bit-and-expr)))
8515 pn))
8516
8517 (defun js2-parse-bit-and-expr ()
8518 (let ((pn (js2-parse-eq-expr)))
8519 (while (js2-match-token js2-BITAND)
8520 (setq pn (js2-make-binary js2-BITAND
8521 pn
8522 'js2-parse-eq-expr)))
8523 pn))
8524
8525 (defconst js2-parse-eq-ops
8526 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8527
8528 (defun js2-parse-eq-expr ()
8529 (let ((pn (js2-parse-rel-expr))
8530 tt)
8531 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8532 (js2-consume-token)
8533 (setq pn (js2-make-binary tt
8534 pn
8535 'js2-parse-rel-expr)))
8536 pn))
8537
8538 (defconst js2-parse-rel-ops
8539 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8540
8541 (defun js2-parse-rel-expr ()
8542 (let ((pn (js2-parse-shift-expr))
8543 (continue t)
8544 tt)
8545 (while continue
8546 (setq tt (js2-peek-token))
8547 (cond
8548 ((and js2-in-for-init (= tt js2-IN))
8549 (setq continue nil))
8550 ((memq tt js2-parse-rel-ops)
8551 (js2-consume-token)
8552 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8553 (t
8554 (setq continue nil))))
8555 pn))
8556
8557 (defconst js2-parse-shift-ops
8558 (list js2-LSH js2-URSH js2-RSH))
8559
8560 (defun js2-parse-shift-expr ()
8561 (let ((pn (js2-parse-add-expr))
8562 tt
8563 (continue t))
8564 (while continue
8565 (setq tt (js2-peek-token))
8566 (if (memq tt js2-parse-shift-ops)
8567 (progn
8568 (js2-consume-token)
8569 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8570 (setq continue nil)))
8571 pn))
8572
8573 (defun js2-parse-add-expr ()
8574 (let ((pn (js2-parse-mul-expr))
8575 tt
8576 (continue t))
8577 (while continue
8578 (setq tt (js2-peek-token))
8579 (if (or (= tt js2-ADD) (= tt js2-SUB))
8580 (progn
8581 (js2-consume-token)
8582 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8583 (setq continue nil)))
8584 pn))
8585
8586 (defconst js2-parse-mul-ops
8587 (list js2-MUL js2-DIV js2-MOD))
8588
8589 (defun js2-parse-mul-expr ()
8590 (let ((pn (js2-parse-unary-expr))
8591 tt
8592 (continue t))
8593 (while continue
8594 (setq tt (js2-peek-token))
8595 (if (memq tt js2-parse-mul-ops)
8596 (progn
8597 (js2-consume-token)
8598 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8599 (setq continue nil)))
8600 pn))
8601
8602 (defun js2-make-unary (type parser &rest args)
8603 "Make a unary node of type TYPE.
8604 PARSER is either a node (for postfix operators) or a function to call
8605 to parse the operand (for prefix operators)."
8606 (let* ((pos js2-token-beg)
8607 (postfix (js2-node-p parser))
8608 (expr (if postfix
8609 parser
8610 (apply parser args)))
8611 end
8612 pn)
8613 (if postfix ; e.g. i++
8614 (setq pos (js2-node-pos expr)
8615 end js2-token-end)
8616 (setq end (js2-node-end expr)))
8617 (setq pn (make-js2-unary-node :type type
8618 :pos pos
8619 :len (- end pos)
8620 :operand expr))
8621 (js2-node-add-children pn expr)
8622 pn))
8623
8624 (defconst js2-incrementable-node-types
8625 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8626 "Node types that can be the operand of a ++ or -- operator.")
8627
8628 (defun js2-check-bad-inc-dec (tt beg end unary)
8629 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8630 js2-incrementable-node-types)
8631 (js2-report-error (if (= tt js2-INC)
8632 "msg.bad.incr"
8633 "msg.bad.decr")
8634 nil beg (- end beg))))
8635
8636 (defun js2-parse-unary-expr ()
8637 (let ((tt (js2-peek-token))
8638 pn expr beg end)
8639 (cond
8640 ((or (= tt js2-VOID)
8641 (= tt js2-NOT)
8642 (= tt js2-BITNOT)
8643 (= tt js2-TYPEOF))
8644 (js2-consume-token)
8645 (js2-make-unary tt 'js2-parse-unary-expr))
8646 ((= tt js2-ADD)
8647 (js2-consume-token)
8648 ;; Convert to special POS token in decompiler and parse tree
8649 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8650 ((= tt js2-SUB)
8651 (js2-consume-token)
8652 ;; Convert to special NEG token in decompiler and parse tree
8653 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8654 ((or (= tt js2-INC)
8655 (= tt js2-DEC))
8656 (js2-consume-token)
8657 (prog1
8658 (setq beg js2-token-beg
8659 end js2-token-end
8660 expr (js2-make-unary tt 'js2-parse-member-expr t))
8661 (js2-check-bad-inc-dec tt beg end expr)))
8662 ((= tt js2-DELPROP)
8663 (js2-consume-token)
8664 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8665 ((= tt js2-ERROR)
8666 (js2-consume-token)
8667 (make-js2-error-node)) ; try to continue
8668 ((and (= tt js2-LT)
8669 js2-compiler-xml-available)
8670 ;; XML stream encountered in expression.
8671 (js2-consume-token)
8672 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8673 (t
8674 (setq pn (js2-parse-member-expr t)
8675 ;; Don't look across a newline boundary for a postfix incop.
8676 tt (js2-peek-token-or-eol))
8677 (when (or (= tt js2-INC) (= tt js2-DEC))
8678 (js2-consume-token)
8679 (setf expr pn
8680 pn (js2-make-unary tt expr))
8681 (js2-node-set-prop pn 'postfix t)
8682 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8683 pn))))
8684
8685 (defun js2-parse-xml-initializer ()
8686 "Parse an E4X XML initializer.
8687 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8688 Then I'll postprocess the result, depending on whether we're in IDE
8689 mode or codegen mode, and generate the appropriate rewritten AST.
8690 IDE mode uses a rich AST that models the XML structure. Codegen mode
8691 just concatenates everything and makes a new XML or XMLList out of it."
8692 (let ((tt (js2-get-first-xml-token))
8693 pn-xml pn expr kids expr-pos
8694 (continue t)
8695 (first-token t))
8696 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8697 (js2-report-error "msg.syntax"))
8698 (setq pn-xml (make-js2-xml-node))
8699 (while continue
8700 (if first-token
8701 (setq first-token nil)
8702 (setq tt (js2-get-next-xml-token)))
8703 (cond
8704 ;; js2-XML means we found a {expr} in the XML stream.
8705 ;; The js2-ts-string is the XML up to the left-curly.
8706 ((= tt js2-XML)
8707 (push (make-js2-string-node :pos js2-token-beg
8708 :len (- js2-ts-cursor js2-token-beg))
8709 kids)
8710 (js2-must-match js2-LC "msg.syntax")
8711 (setq expr-pos js2-ts-cursor
8712 expr (if (eq (js2-peek-token) js2-RC)
8713 (make-js2-empty-expr-node :pos expr-pos)
8714 (js2-parse-expr)))
8715 (js2-must-match js2-RC "msg.syntax")
8716 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8717 :len (js2-node-len expr)
8718 :expr expr))
8719 (js2-node-add-children pn expr)
8720 (push pn kids))
8721 ;; a js2-XMLEND token means we hit the final close-tag.
8722 ((= tt js2-XMLEND)
8723 (push (make-js2-string-node :pos js2-token-beg
8724 :len (- js2-ts-cursor js2-token-beg))
8725 kids)
8726 (dolist (kid (nreverse kids))
8727 (js2-block-node-push pn-xml kid))
8728 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8729 (js2-node-pos pn-xml))
8730 continue nil))
8731 (t
8732 (js2-report-error "msg.syntax")
8733 (setq continue nil))))
8734 pn-xml))
8735
8736
8737 (defun js2-parse-argument-list ()
8738 "Parse an argument list and return it as a Lisp list of nodes.
8739 Returns the list in reverse order. Consumes the right-paren token."
8740 (let (result)
8741 (unless (js2-match-token js2-RP)
8742 (loop do
8743 (if (= (js2-peek-token) js2-YIELD)
8744 (js2-report-error "msg.yield.parenthesized"))
8745 (push (js2-parse-assign-expr) result)
8746 while
8747 (js2-match-token js2-COMMA))
8748 (js2-must-match js2-RP "msg.no.paren.arg")
8749 result)))
8750
8751 (defun js2-parse-member-expr (&optional allow-call-syntax)
8752 (let ((tt (js2-peek-token))
8753 pn pos target args beg end init tail)
8754 (if (/= tt js2-NEW)
8755 (setq pn (js2-parse-primary-expr))
8756 ;; parse a 'new' expression
8757 (js2-consume-token)
8758 (setq pos js2-token-beg
8759 beg pos
8760 target (js2-parse-member-expr)
8761 end (js2-node-end target)
8762 pn (make-js2-new-node :pos pos
8763 :target target
8764 :len (- end pos)))
8765 (js2-node-add-children pn target)
8766 (when (js2-match-token js2-LP)
8767 ;; Add the arguments to pn, if any are supplied.
8768 (setf beg pos ; start of "new" keyword
8769 pos js2-token-beg
8770 args (nreverse (js2-parse-argument-list))
8771 (js2-new-node-args pn) args
8772 end js2-token-end
8773 (js2-new-node-lp pn) (- pos beg)
8774 (js2-new-node-rp pn) (- end 1 beg))
8775 (apply #'js2-node-add-children pn args))
8776 (when (and js2-allow-rhino-new-expr-initializer
8777 (js2-match-token js2-LC))
8778 (setf init (js2-parse-object-literal)
8779 end (js2-node-end init)
8780 (js2-new-node-initializer pn) init)
8781 (js2-node-add-children pn init))
8782 (setf (js2-node-len pn) (- end beg))) ; end outer if
8783 (js2-parse-member-expr-tail allow-call-syntax pn)))
8784
8785 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8786 "Parse a chain of property/array accesses or function calls.
8787 Includes parsing for E4X operators like `..' and `.@'.
8788 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8789 Returns an expression tree that includes PN, the parent node."
8790 (let ((beg (js2-node-pos pn))
8791 tt
8792 (continue t))
8793 (while continue
8794 (setq tt (js2-peek-token))
8795 (cond
8796 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8797 (setq pn (js2-parse-property-access tt pn)))
8798 ((= tt js2-DOTQUERY)
8799 (setq pn (js2-parse-dot-query pn)))
8800 ((= tt js2-LB)
8801 (setq pn (js2-parse-element-get pn)))
8802 ((= tt js2-LP)
8803 (if allow-call-syntax
8804 (setq pn (js2-parse-function-call pn))
8805 (setq continue nil)))
8806 (t
8807 (setq continue nil))))
8808 (if (>= js2-highlight-level 2)
8809 (js2-parse-highlight-member-expr-node pn))
8810 pn))
8811
8812 (defun js2-parse-dot-query (pn)
8813 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8814 Last token parsed must be `js2-DOTQUERY'."
8815 (let ((pos (js2-node-pos pn))
8816 op-pos expr end)
8817 (js2-consume-token)
8818 (js2-must-have-xml)
8819 (js2-set-requires-activation)
8820 (setq op-pos js2-token-beg
8821 expr (js2-parse-expr)
8822 end (js2-node-end expr)
8823 pn (make-js2-xml-dot-query-node :left pn
8824 :pos pos
8825 :op-pos op-pos
8826 :right expr))
8827 (js2-node-add-children pn
8828 (js2-xml-dot-query-node-left pn)
8829 (js2-xml-dot-query-node-right pn))
8830 (if (js2-must-match js2-RP "msg.no.paren")
8831 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
8832 end js2-token-end))
8833 (setf (js2-node-len pn) (- end pos))
8834 pn))
8835
8836 (defun js2-parse-element-get (pn)
8837 "Parse an element-get expression, e.g. foo[bar].
8838 Last token parsed must be `js2-RB'."
8839 (let ((lb js2-token-beg)
8840 (pos (js2-node-pos pn))
8841 rb expr)
8842 (js2-consume-token)
8843 (setq expr (js2-parse-expr))
8844 (if (js2-must-match js2-RB "msg.no.bracket.index")
8845 (setq rb js2-token-beg))
8846 (setq pn (make-js2-elem-get-node :target pn
8847 :pos pos
8848 :element expr
8849 :lb (js2-relpos lb pos)
8850 :rb (js2-relpos rb pos)
8851 :len (- js2-token-end pos)))
8852 (js2-node-add-children pn
8853 (js2-elem-get-node-target pn)
8854 (js2-elem-get-node-element pn))
8855 pn))
8856
8857 (defun js2-parse-function-call (pn)
8858 (let (args
8859 (pos (js2-node-pos pn)))
8860 (js2-consume-token)
8861 (setq pn (make-js2-call-node :pos pos
8862 :target pn
8863 :lp (- js2-token-beg pos)))
8864 (js2-node-add-children pn (js2-call-node-target pn))
8865 ;; Add the arguments to pn, if any are supplied.
8866 (setf args (nreverse (js2-parse-argument-list))
8867 (js2-call-node-rp pn) (- js2-token-beg pos)
8868 (js2-call-node-args pn) args)
8869 (apply #'js2-node-add-children pn args)
8870 (setf (js2-node-len pn) (- js2-ts-cursor pos))
8871 pn))
8872
8873 (defun js2-parse-property-access (tt pn)
8874 "Parse a property access, XML descendants access, or XML attr access."
8875 (let ((member-type-flags 0)
8876 (dot-pos js2-token-beg)
8877 (dot-len (if (= tt js2-DOTDOT) 2 1))
8878 name
8879 ref ; right side of . or .. operator
8880 result)
8881 (js2-consume-token)
8882 (when (= tt js2-DOTDOT)
8883 (js2-must-have-xml)
8884 (setq member-type-flags js2-descendants-flag))
8885 (if (not js2-compiler-xml-available)
8886 (progn
8887 (js2-must-match-prop-name "msg.no.name.after.dot")
8888 (setq name (js2-create-name-node t js2-GETPROP)
8889 result (make-js2-prop-get-node :left pn
8890 :pos js2-token-beg
8891 :right name
8892 :len (- js2-token-end
8893 js2-token-beg)))
8894 (js2-node-add-children result pn name)
8895 result)
8896 ;; otherwise look for XML operators
8897 (setf result (if (= tt js2-DOT)
8898 (make-js2-prop-get-node)
8899 (make-js2-infix-node :type js2-DOTDOT))
8900 (js2-node-pos result) (js2-node-pos pn)
8901 (js2-infix-node-op-pos result) dot-pos
8902 (js2-infix-node-left result) pn ; do this after setting position
8903 tt (js2-next-token))
8904 (cond
8905 ;; needed for generator.throw()
8906 ((= tt js2-THROW)
8907 (js2-save-name-token-data js2-token-beg "throw")
8908 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
8909 ;; handles: name, ns::name, ns::*, ns::[expr]
8910 ((js2-valid-prop-name-token tt)
8911 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
8912 ;; handles: *, *::name, *::*, *::[expr]
8913 ((= tt js2-MUL)
8914 (js2-save-name-token-data js2-token-beg "*")
8915 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
8916 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
8917 ((= tt js2-XMLATTR)
8918 (setq result (js2-parse-attribute-access)))
8919 (t
8920 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
8921 (if ref
8922 (setf (js2-node-len result) (- (js2-node-end ref)
8923 (js2-node-pos result))
8924 (js2-infix-node-right result) ref))
8925 (if (js2-infix-node-p result)
8926 (js2-node-add-children result
8927 (js2-infix-node-left result)
8928 (js2-infix-node-right result)))
8929 result)))
8930
8931 (defun js2-parse-attribute-access ()
8932 "Parse an E4X XML attribute expression.
8933 This includes expressions of the forms:
8934
8935 @attr @ns::attr @ns::*
8936 @* @*::attr @*::*
8937 @[expr] @*::[expr] @ns::[expr]
8938
8939 Called if we peeked an '@' token."
8940 (let ((tt (js2-next-token))
8941 (at-pos js2-token-beg))
8942 (cond
8943 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
8944 ((js2-valid-prop-name-token tt)
8945 (js2-parse-property-name at-pos js2-ts-string 0))
8946 ;; handles: @*, @*::name, @*::*, @*::[expr]
8947 ((= tt js2-MUL)
8948 (js2-save-name-token-data js2-token-beg "*")
8949 (js2-parse-property-name js2-token-beg "*" 0))
8950 ;; handles @[expr]
8951 ((= tt js2-LB)
8952 (js2-parse-xml-elem-ref at-pos))
8953 (t
8954 (js2-report-error "msg.no.name.after.xmlAttr")
8955 ;; Avoid cascaded errors that happen if we make an error node here.
8956 (js2-save-name-token-data js2-token-beg "")
8957 (js2-parse-property-name js2-token-beg "" 0)))))
8958
8959 (defun js2-parse-property-name (at-pos s member-type-flags)
8960 "Check if :: follows name in which case it becomes qualified name.
8961
8962 AT-POS is a natural number if we just read an '@' token, else nil.
8963 S is the name or string that was matched: an identifier, 'throw' or '*'.
8964 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
8965
8966 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
8967 operator, or the name is followed by ::. For a plain name, returns a
8968 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
8969 (let ((pos (or at-pos js2-token-beg))
8970 colon-pos
8971 (name (js2-create-name-node t js2-current-token))
8972 ns tt ref pn)
8973 (catch 'return
8974 (when (js2-match-token js2-COLONCOLON)
8975 (setq ns name
8976 colon-pos js2-token-beg
8977 tt (js2-next-token))
8978 (cond
8979 ;; handles name::name
8980 ((js2-valid-prop-name-token tt)
8981 (setq name (js2-create-name-node)))
8982 ;; handles name::*
8983 ((= tt js2-MUL)
8984 (js2-save-name-token-data js2-token-beg "*")
8985 (setq name (js2-create-name-node)))
8986 ;; handles name::[expr]
8987 ((= tt js2-LB)
8988 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
8989 (t
8990 (js2-report-error "msg.no.name.after.coloncolon"))))
8991 (if (and (null ns) (zerop member-type-flags))
8992 name
8993 (prog1
8994 (setq pn
8995 (make-js2-xml-prop-ref-node :pos pos
8996 :len (- (js2-node-end name) pos)
8997 :at-pos at-pos
8998 :colon-pos colon-pos
8999 :propname name))
9000 (js2-node-add-children pn name))))))
9001
9002 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9003 "Parse the [expr] portion of an xml element reference.
9004 For instance, @[expr], @*::[expr], or ns::[expr]."
9005 (let* ((lb js2-token-beg)
9006 (pos (or at-pos lb))
9007 rb
9008 (expr (js2-parse-expr))
9009 (end (js2-node-end expr))
9010 pn)
9011 (if (js2-must-match js2-RB "msg.no.bracket.index")
9012 (setq rb js2-token-beg
9013 end js2-token-end))
9014 (prog1
9015 (setq pn
9016 (make-js2-xml-elem-ref-node :pos pos
9017 :len (- end pos)
9018 :namespace namespace
9019 :colon-pos colon-pos
9020 :at-pos at-pos
9021 :expr expr
9022 :lb (js2-relpos lb pos)
9023 :rb (js2-relpos rb pos)))
9024 (js2-node-add-children pn namespace expr))))
9025
9026 (defun js2-parse-destruct-primary-expr ()
9027 (let ((js2-is-in-destructuring t))
9028 (js2-parse-primary-expr)))
9029
9030 (defun js2-parse-primary-expr ()
9031 "Parse a literal (leaf) expression of some sort.
9032 Includes complex literals such as functions, object-literals,
9033 array-literals, array comprehensions and regular expressions."
9034 (let ((tt-flagged (js2-next-flagged-token))
9035 pn ; parent node (usually return value)
9036 tt
9037 px-pos ; paren-expr pos
9038 len
9039 flags ; regexp flags
9040 expr)
9041 (setq tt js2-current-token)
9042 (cond
9043 ((= tt js2-FUNCTION)
9044 (js2-parse-function 'FUNCTION_EXPRESSION))
9045 ((= tt js2-LB)
9046 (js2-parse-array-literal))
9047 ((= tt js2-LC)
9048 (js2-parse-object-literal))
9049 ((= tt js2-LET)
9050 (js2-parse-let js2-token-beg))
9051 ((= tt js2-LP)
9052 (setq px-pos js2-token-beg
9053 expr (js2-parse-expr))
9054 (js2-must-match js2-RP "msg.no.paren")
9055 (setq pn (make-js2-paren-node :pos px-pos
9056 :expr expr
9057 :len (- js2-token-end px-pos)))
9058 (js2-node-add-children pn (js2-paren-node-expr pn))
9059 pn)
9060 ((= tt js2-XMLATTR)
9061 (js2-must-have-xml)
9062 (js2-parse-attribute-access))
9063 ((= tt js2-NAME)
9064 (js2-parse-name tt-flagged tt))
9065 ((= tt js2-NUMBER)
9066 (make-js2-number-node))
9067 ((= tt js2-STRING)
9068 (prog1
9069 (make-js2-string-node)
9070 (js2-record-face 'font-lock-string-face)))
9071 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9072 ;; Got / or /= which in this context means a regexp literal
9073 (setq px-pos js2-token-beg)
9074 (js2-read-regexp tt)
9075 (setq flags js2-ts-regexp-flags
9076 js2-ts-regexp-flags nil)
9077 (prog1
9078 (make-js2-regexp-node :pos px-pos
9079 :len (- js2-ts-cursor px-pos)
9080 :value js2-ts-string
9081 :flags flags)
9082 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9083 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9084 ((or (= tt js2-NULL)
9085 (= tt js2-THIS)
9086 (= tt js2-FALSE)
9087 (= tt js2-TRUE))
9088 (make-js2-keyword-node :type tt))
9089 ((= tt js2-RESERVED)
9090 (js2-report-error "msg.reserved.id")
9091 (make-js2-name-node))
9092 ((= tt js2-ERROR)
9093 ;; the scanner or one of its subroutines reported the error.
9094 (make-js2-error-node))
9095 ((= tt js2-EOF)
9096 (setq px-pos (point-at-bol)
9097 len (- js2-ts-cursor px-pos))
9098 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9099 (make-js2-error-node :pos px-pos :len len))
9100 (t
9101 (js2-report-error "msg.syntax")
9102 (make-js2-error-node)))))
9103
9104 (defun js2-parse-name (tt-flagged tt)
9105 (let ((name js2-ts-string)
9106 (name-pos js2-token-beg)
9107 node)
9108 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9109 (= (js2-peek-token) js2-COLON))
9110 (prog1
9111 ;; Do not consume colon, it is used as unwind indicator
9112 ;; to return to statementHelper.
9113 (make-js2-label-node :pos name-pos
9114 :len (- js2-token-end name-pos)
9115 :name name)
9116 (js2-set-face name-pos
9117 js2-token-end
9118 'font-lock-variable-name-face 'record))
9119 ;; Otherwise not a label, just a name. Unfortunately peeking
9120 ;; the next token to check for a colon has biffed js2-token-beg
9121 ;; and js2-token-end. We store the name's bounds in buffer vars
9122 ;; and `js2-create-name-node' uses them.
9123 (js2-save-name-token-data name-pos name)
9124 (setq node (if js2-compiler-xml-available
9125 (js2-parse-property-name nil name 0)
9126 (js2-create-name-node 'check-activation)))
9127 (if js2-highlight-external-variables
9128 (js2-record-name-node node))
9129 node)))
9130
9131 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9132 (js2-add-strict-warning
9133 msg nil
9134 ;; back up from comma to beginning of line or array/objlit
9135 (max (if elems
9136 (js2-node-pos (car elems))
9137 pos)
9138 (save-excursion
9139 (goto-char comma-pos)
9140 (back-to-indentation)
9141 (point)))
9142 comma-pos))
9143
9144 (defun js2-parse-array-literal ()
9145 (let ((pos js2-token-beg)
9146 (end js2-token-end)
9147 (after-lb-or-comma t)
9148 after-comma tt elems pn
9149 (continue t))
9150 (unless js2-is-in-destructuring
9151 (js2-push-scope (make-js2-scope))) ; for array comp
9152 (while continue
9153 (setq tt (js2-peek-token))
9154 (cond
9155 ;; comma
9156 ((= tt js2-COMMA)
9157 (js2-consume-token)
9158 (setq after-comma js2-token-end)
9159 (if (not after-lb-or-comma)
9160 (setq after-lb-or-comma t)
9161 (push nil elems)))
9162 ;; end of array
9163 ((or (= tt js2-RB)
9164 (= tt js2-EOF)) ; prevent infinite loop
9165 (if (= tt js2-EOF)
9166 (js2-report-error "msg.no.bracket.arg" nil pos)
9167 (js2-consume-token))
9168 (setq continue nil
9169 end js2-token-end
9170 pn (make-js2-array-node :pos pos
9171 :len (- js2-ts-cursor pos)
9172 :elems (nreverse elems)))
9173 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9174 (when (and after-comma (not js2-is-in-destructuring))
9175 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9176 pos elems after-comma)))
9177 ;; destructuring binding
9178 (js2-is-in-destructuring
9179 (push (if (or (= tt js2-LC)
9180 (= tt js2-LB)
9181 (= tt js2-NAME))
9182 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9183 (js2-parse-destruct-primary-expr)
9184 ;; invalid pattern
9185 (js2-consume-token)
9186 (js2-report-error "msg.bad.var")
9187 (make-js2-error-node))
9188 elems)
9189 (setq after-lb-or-comma nil
9190 after-comma nil))
9191 ;; array comp
9192 ((and (>= js2-language-version 170)
9193 (= tt js2-FOR) ; check for array comprehension
9194 (not after-lb-or-comma) ; "for" can't follow a comma
9195 elems ; must have at least 1 element
9196 (not (cdr elems))) ; but no 2nd element
9197 (setf continue nil
9198 pn (js2-parse-array-comprehension (car elems) pos)))
9199
9200 ;; another element
9201 (t
9202 (unless after-lb-or-comma
9203 (js2-report-error "msg.no.bracket.arg"))
9204 (push (js2-parse-assign-expr) elems)
9205 (setq after-lb-or-comma nil
9206 after-comma nil))))
9207 (unless js2-is-in-destructuring
9208 (js2-pop-scope))
9209 pn))
9210
9211 (defun js2-parse-array-comprehension (expr pos)
9212 "Parse a JavaScript 1.7 Array Comprehension.
9213 EXPR is the first expression after the opening left-bracket.
9214 POS is the beginning of the LB token preceding EXPR.
9215 We should have just parsed the 'for' keyword before calling this function."
9216 (let (loops loop first prev filter if-pos result)
9217 (while (= (js2-peek-token) js2-FOR)
9218 (let ((prev (car loops))) ; rearrange scope chain
9219 (push (setq loop (js2-parse-array-comp-loop)) loops)
9220 (if prev ; each loop is parent scope to the next one
9221 (setf (js2-scope-parent-scope loop) prev)
9222 ; first loop takes expr scope's parent
9223 (setf (js2-scope-parent-scope (setq first loop))
9224 (js2-scope-parent-scope js2-current-scope)))))
9225 ;; set expr scope's parent to the last loop
9226 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9227 (when (= (js2-peek-token) js2-IF)
9228 (js2-consume-token)
9229 (setq if-pos (- js2-token-beg pos) ; relative
9230 filter (js2-parse-condition)))
9231 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9232 (setq result (make-js2-array-comp-node :pos pos
9233 :len (- js2-ts-cursor pos)
9234 :result expr
9235 :loops (nreverse loops)
9236 :filter (car filter)
9237 :lp (js2-relpos (second filter) pos)
9238 :rp (js2-relpos (third filter) pos)
9239 :if-pos if-pos))
9240 (apply #'js2-node-add-children result expr (car filter)
9241 (js2-array-comp-node-loops result))
9242 (setq js2-current-scope first) ; pop to the first loop
9243 result))
9244
9245 (defun js2-parse-array-comp-loop ()
9246 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9247 Last token peeked should be the initial FOR."
9248 (let ((pos js2-token-beg)
9249 (pn (make-js2-array-comp-loop-node))
9250 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9251 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9252 (js2-push-scope pn)
9253 (unwind-protect
9254 (progn
9255 (when (js2-match-token js2-NAME)
9256 (if (string= js2-ts-string "each")
9257 (progn
9258 (setq foreach-p t
9259 each-pos (- js2-token-beg pos)) ; relative
9260 (js2-record-face 'font-lock-keyword-face))
9261 (js2-report-error "msg.no.paren.for")))
9262 (if (js2-must-match js2-LP "msg.no.paren.for")
9263 (setq lp (- js2-token-beg pos)))
9264 (setq tt (js2-peek-token))
9265 (cond
9266 ((or (= tt js2-LB)
9267 (= tt js2-LC))
9268 (setq iter (js2-parse-destruct-primary-expr))
9269 (js2-define-destruct-symbols iter js2-LET
9270 'font-lock-variable-name-face t))
9271 ((js2-match-token js2-NAME)
9272 (setq iter (js2-create-name-node)))
9273 (t
9274 (js2-report-error "msg.bad.var")))
9275 ;; Define as a let since we want the scope of the variable to
9276 ;; be restricted to the array comprehension
9277 (if (js2-name-node-p iter)
9278 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9279 (if (or (js2-match-token js2-IN)
9280 (and (>= js2-language-version 200)
9281 (js2-match-contextual-kwd "of")
9282 (setq forof-p t)))
9283 (setq in-pos (- js2-token-beg pos))
9284 (js2-report-error "msg.in.after.for.name"))
9285 (setq obj (js2-parse-expr))
9286 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9287 (setq rp (- js2-token-beg pos)))
9288 (setf (js2-node-pos pn) pos
9289 (js2-node-len pn) (- js2-ts-cursor pos)
9290 (js2-array-comp-loop-node-iterator pn) iter
9291 (js2-array-comp-loop-node-object pn) obj
9292 (js2-array-comp-loop-node-in-pos pn) in-pos
9293 (js2-array-comp-loop-node-each-pos pn) each-pos
9294 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9295 (js2-array-comp-loop-node-forof-p pn) forof-p
9296 (js2-array-comp-loop-node-lp pn) lp
9297 (js2-array-comp-loop-node-rp pn) rp)
9298 (js2-node-add-children pn iter obj))
9299 (js2-pop-scope))
9300 pn))
9301
9302 (defun js2-parse-object-literal ()
9303 (let ((pos js2-token-beg)
9304 tt elems result after-comma
9305 (continue t))
9306 (while continue
9307 (setq tt (js2-peek-token))
9308 (cond
9309 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9310 ;; {get foo() {...}}, or {set foo(x) {...}}
9311 ((or (js2-valid-prop-name-token tt)
9312 (= tt js2-STRING))
9313 (setq after-comma nil
9314 result (js2-parse-named-prop tt))
9315 (if (and (null result)
9316 (not js2-recover-from-parse-errors))
9317 (setq continue nil)
9318 (push result elems)))
9319 ;; {12: x} or {10.7: x}
9320 ((= tt js2-NUMBER)
9321 (js2-consume-token)
9322 (setq after-comma nil)
9323 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9324 ;; trailing comma
9325 ((= tt js2-RC)
9326 (setq continue nil)
9327 (if after-comma
9328 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9329 pos elems after-comma)))
9330 (t
9331 (js2-report-error "msg.bad.prop")
9332 (unless js2-recover-from-parse-errors
9333 (setq continue nil)))) ; end switch
9334 (if (js2-match-token js2-COMMA)
9335 (setq after-comma js2-token-end)
9336 (setq continue nil))) ; end loop
9337 (js2-must-match js2-RC "msg.no.brace.prop")
9338 (setq result (make-js2-object-node :pos pos
9339 :len (- js2-ts-cursor pos)
9340 :elems (nreverse elems)))
9341 (apply #'js2-node-add-children result (js2-object-node-elems result))
9342 result))
9343
9344 (defun js2-parse-named-prop (tt)
9345 "Parse a name, string, or getter/setter object property.
9346 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9347 (js2-consume-token)
9348 (let ((string-prop (and (= tt js2-STRING)
9349 (make-js2-string-node)))
9350 expr
9351 (ppos js2-token-beg)
9352 (pend js2-token-end)
9353 (name (js2-create-name-node))
9354 (prop js2-ts-string))
9355 (cond
9356 ;; getter/setter prop
9357 ((and (= tt js2-NAME)
9358 (= (js2-peek-token) js2-NAME)
9359 (or (string= prop "get")
9360 (string= prop "set")))
9361 (js2-consume-token)
9362 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9363 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9364 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9365 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9366 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9367 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9368 ;; when patterns are used in variable declarations, function parameters,
9369 ;; catch-clause, and iterators.
9370 ;; We have to set `js2-is-in-destructuring' to t when the current
9371 ;; expressions are on the left side of any assignment, but it's difficult
9372 ;; because it requires looking ahead of expression.
9373 ((and js2-is-in-destructuring
9374 (= tt js2-NAME)
9375 (let ((ctk (js2-peek-token)))
9376 (or (= ctk js2-COMMA)
9377 (= ctk js2-RC)
9378 (js2-valid-prop-name-token ctk))))
9379 name)
9380 ;; regular prop
9381 (t
9382 (prog1
9383 (setq expr (js2-parse-plain-property (or string-prop name)))
9384 (js2-set-face ppos pend
9385 (if (js2-function-node-p
9386 (js2-object-prop-node-right expr))
9387 'font-lock-function-name-face
9388 'font-lock-variable-name-face)
9389 'record))))))
9390
9391 (defun js2-parse-plain-property (prop)
9392 "Parse a non-getter/setter property in an object literal.
9393 PROP is the node representing the property: a number, name or string."
9394 (js2-must-match js2-COLON "msg.no.colon.prop")
9395 (let* ((pos (js2-node-pos prop))
9396 (colon (- js2-token-beg pos))
9397 (expr (js2-parse-assign-expr))
9398 (result (make-js2-object-prop-node
9399 :pos pos
9400 ;; don't include last consumed token in length
9401 :len (- (+ (js2-node-pos expr)
9402 (js2-node-len expr))
9403 pos)
9404 :left prop
9405 :right expr
9406 :op-pos colon)))
9407 (js2-node-add-children result prop expr)
9408 result))
9409
9410 (defun js2-parse-getter-setter-prop (pos prop get-p)
9411 "Parse getter or setter property in an object literal.
9412 JavaScript syntax is:
9413
9414 { get foo() {...}, set foo(x) {...} }
9415
9416 and expression closure style is also supported
9417
9418 { get foo() x, set foo(x) _x = x }
9419
9420 POS is the start position of the `get' or `set' keyword.
9421 PROP is the `js2-name-node' representing the property name.
9422 GET-P is non-nil if the keyword was `get'."
9423 (let ((type (if get-p js2-GET js2-SET))
9424 result end
9425 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9426 ;; it has to be an anonymous function, as we already parsed the name
9427 (if (/= (js2-node-type fn) js2-FUNCTION)
9428 (js2-report-error "msg.bad.prop")
9429 (if (plusp (length (js2-function-name fn)))
9430 (js2-report-error "msg.bad.prop")))
9431 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9432 (setq end (js2-node-end fn)
9433 result (make-js2-getter-setter-node :type type
9434 :pos pos
9435 :len (- end pos)
9436 :left prop
9437 :right fn))
9438 (js2-node-add-children result prop fn)
9439 result))
9440
9441 (defun js2-create-name-node (&optional check-activation-p token)
9442 "Create a name node using the token info from last scanned name.
9443 In some cases we need to either synthesize a name node, or we lost
9444 the name token information by peeking. If the TOKEN parameter is
9445 not `js2-NAME', then we use the token info saved in instance vars."
9446 (let ((beg js2-token-beg)
9447 (s js2-ts-string)
9448 name)
9449 (when (/= js2-current-token js2-NAME)
9450 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9451 s js2-prev-name-token-string
9452 js2-prev-name-token-start nil
9453 js2-prev-name-token-string nil))
9454 (setq name (make-js2-name-node :pos beg
9455 :name s
9456 :len (length s)))
9457 (if check-activation-p
9458 (js2-check-activation-name s (or token js2-NAME)))
9459 name))
9460
9461 ;;; Indentation support
9462
9463 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9464 ;; Karl cleverly deduces that the desired indentation level is often a
9465 ;; function of paren/bracket/brace nesting depth, which can be determined
9466 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9467 ;; then does some equally clever checks to see if we're in the context of a
9468 ;; substatement of a possibly braceless statement keyword such as if, while,
9469 ;; or finally. This approach yields pretty good results.
9470
9471 ;; The indenter is often "wrong", however, and needs to be overridden.
9472 ;; The right long-term solution is probably to emulate (or integrate
9473 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9474 ;; parse tree from `js2-parse' is present, which is not true at the
9475 ;; moment the user is typing, computing indentation is still thousands
9476 ;; of lines of code to handle every possible syntactic edge case.
9477
9478 ;; In the meantime, the compromise solution is that we offer a "bounce
9479 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9480 ;; current line indent among various likely guess points. This approach
9481 ;; is far from perfect, but should at least make it slightly easier to
9482 ;; move the line towards its desired indentation when manually
9483 ;; overriding Karl's heuristic nesting guesser.
9484
9485 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9486 ;; extensions such as `let' and Array comprehensions. Major kudos to
9487 ;; Karl for coming up with the initial approach, which packs a lot of
9488 ;; punch for so little code.
9489
9490 (defconst js2-possibly-braceless-keywords-re
9491 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9492 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9493 "try" "while" "with" "let")))
9494 "Regular expression matching keywords that are optionally
9495 followed by an opening brace.")
9496
9497 (defconst js2-indent-operator-re
9498 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9499 (regexp-opt '("in" "instanceof") 'words))
9500 "Regular expression matching operators that affect indentation
9501 of continued expressions.")
9502
9503 (defconst js2-declaration-keyword-re
9504 (regexp-opt '("var" "let" "const") 'words)
9505 "Regular expression matching variable declaration keywords.")
9506
9507 (defun js2-re-search-forward-inner (regexp &optional bound count)
9508 "Auxiliary function for `js2-re-search-forward'."
9509 (let (parse saved-point)
9510 (while (> count 0)
9511 (re-search-forward regexp bound)
9512 (setq parse (if saved-point
9513 (parse-partial-sexp saved-point (point))
9514 (syntax-ppss (point))))
9515 (cond ((nth 3 parse)
9516 (re-search-forward
9517 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9518 (save-excursion (end-of-line) (point)) t))
9519 ((nth 7 parse)
9520 (forward-line))
9521 ((or (nth 4 parse)
9522 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9523 (re-search-forward "\\*/"))
9524 (t
9525 (setq count (1- count))))
9526 (setq saved-point (point))))
9527 (point))
9528
9529 (defun js2-re-search-forward (regexp &optional bound noerror count)
9530 "Search forward but ignore strings and comments.
9531 Invokes `re-search-forward' but treats the buffer as if strings
9532 and comments have been removed."
9533 (let ((saved-point (point))
9534 (search-expr
9535 (cond ((null count)
9536 '(js2-re-search-forward-inner regexp bound 1))
9537 ((< count 0)
9538 '(js2-re-search-backward-inner regexp bound (- count)))
9539 ((> count 0)
9540 '(js2-re-search-forward-inner regexp bound count)))))
9541 (condition-case err
9542 (eval search-expr)
9543 (search-failed
9544 (goto-char saved-point)
9545 (unless noerror
9546 (error (error-message-string err)))))))
9547
9548 (defun js2-re-search-backward-inner (regexp &optional bound count)
9549 "Auxiliary function for `js2-re-search-backward'."
9550 (let (parse)
9551 (while (> count 0)
9552 (re-search-backward regexp bound)
9553 (setq parse (syntax-ppss (point)))
9554 (cond ((nth 3 parse)
9555 (re-search-backward
9556 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9557 (line-beginning-position) t))
9558 ((nth 7 parse)
9559 (goto-char (nth 8 parse)))
9560 ((or (nth 4 parse)
9561 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9562 (re-search-backward "/\\*"))
9563 (t
9564 (setq count (1- count))))))
9565 (point))
9566
9567 (defun js2-re-search-backward (regexp &optional bound noerror count)
9568 "Search backward but ignore strings and comments.
9569 Invokes `re-search-backward' but treats the buffer as if strings
9570 and comments have been removed."
9571 (let ((saved-point (point))
9572 (search-expr
9573 (cond ((null count)
9574 '(js2-re-search-backward-inner regexp bound 1))
9575 ((< count 0)
9576 '(js2-re-search-forward-inner regexp bound (- count)))
9577 ((> count 0)
9578 '(js2-re-search-backward-inner regexp bound count)))))
9579 (condition-case err
9580 (eval search-expr)
9581 (search-failed
9582 (goto-char saved-point)
9583 (unless noerror
9584 (error (error-message-string err)))))))
9585
9586 (defun js2-looking-at-operator-p ()
9587 "Return non-nil if text after point is a non-comma operator."
9588 (and (looking-at js2-indent-operator-re)
9589 (or (not (looking-at ":"))
9590 (save-excursion
9591 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9592 (looking-at "?"))))))
9593
9594 (defun js2-continued-expression-p ()
9595 "Return non-nil if the current line continues an expression."
9596 (save-excursion
9597 (back-to-indentation)
9598 (or (js2-looking-at-operator-p)
9599 (when (catch 'found
9600 (while (and (re-search-backward "\n" nil t)
9601 (let ((state (syntax-ppss)))
9602 (when (nth 4 state)
9603 (goto-char (nth 8 state))) ;; skip comments
9604 (skip-chars-backward " \t")
9605 (if (bolp)
9606 t
9607 (throw 'found t))))))
9608 (backward-char)
9609 (when (js2-looking-at-operator-p)
9610 (backward-char)
9611 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))
9612
9613 (defun js2-end-of-do-while-loop-p ()
9614 "Return non-nil if word after point is `while' of a do-while
9615 statement, else returns nil. A braceless do-while statement
9616 spanning several lines requires that the start of the loop is
9617 indented to the same column as the current line."
9618 (interactive)
9619 (save-excursion
9620 (when (looking-at "\\s-*\\<while\\>")
9621 (if (save-excursion
9622 (skip-chars-backward "[ \t\n]*}")
9623 (looking-at "[ \t\n]*}"))
9624 (save-excursion
9625 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9626 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9627 (or (looking-at "\\<do\\>")
9628 (let ((saved-indent (current-indentation)))
9629 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9630 (/= (current-indentation) saved-indent)))
9631 (and (looking-at "[ \t]*\\<do\\>")
9632 (not (js2-re-search-forward
9633 "\\<while\\>" (point-at-eol) t))
9634 (= (current-indentation) saved-indent))))))))
9635
9636 (defun js2-multiline-decl-indentation ()
9637 "Return the declaration indentation column if the current line belongs
9638 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9639 (let (forward-sexp-function ; use Lisp version
9640 at-opening-bracket)
9641 (save-excursion
9642 (back-to-indentation)
9643 (when (not (looking-at js2-declaration-keyword-re))
9644 (when (looking-at js2-indent-operator-re)
9645 (goto-char (match-end 0))) ; continued expressions are ok
9646 (while (and (not at-opening-bracket)
9647 (not (bobp))
9648 (let ((pos (point)))
9649 (save-excursion
9650 (js2-backward-sws)
9651 (or (eq (char-before) ?,)
9652 (and (not (eq (char-before) ?\;))
9653 (prog2 (skip-syntax-backward ".")
9654 (looking-at js2-indent-operator-re)
9655 (js2-backward-sws))
9656 (not (eq (char-before) ?\;)))
9657 (js2-same-line pos)))))
9658 (condition-case err
9659 (backward-sexp)
9660 (scan-error (setq at-opening-bracket t))))
9661 (when (looking-at js2-declaration-keyword-re)
9662 (goto-char (match-end 0))
9663 (1+ (current-column)))))))
9664
9665 (defun js2-ctrl-statement-indentation ()
9666 "Return the proper indentation of current line if it is a control statement.
9667 Returns an indentation if this line starts the body of a control
9668 statement without braces, else returns nil."
9669 (let (forward-sexp-function)
9670 (save-excursion
9671 (back-to-indentation)
9672 (when (and (not (js2-same-line (point-min)))
9673 (not (looking-at "{"))
9674 (js2-re-search-backward "[[:graph:]]" nil t)
9675 (not (looking-at "[{([]"))
9676 (progn
9677 (forward-char)
9678 (when (= (char-before) ?\))
9679 ;; scan-sexps sometimes throws an error
9680 (ignore-errors (backward-sexp))
9681 (skip-chars-backward " \t" (point-at-bol)))
9682 (let ((pt (point)))
9683 (back-to-indentation)
9684 (when (looking-at "}[ \t]*")
9685 (goto-char (match-end 0)))
9686 (and (looking-at js2-possibly-braceless-keywords-re)
9687 (= (match-end 0) pt)
9688 (not (js2-end-of-do-while-loop-p))))))
9689 (+ (current-indentation) js2-basic-offset)))))
9690
9691 (defun js2-indent-in-array-comp (parse-status)
9692 "Return non-nil if we think we're in an array comprehension.
9693 In particular, return the buffer position of the first `for' kwd."
9694 (let ((bracket (nth 1 parse-status))
9695 (end (point)))
9696 (when bracket
9697 (save-excursion
9698 (goto-char bracket)
9699 (when (looking-at "\\[")
9700 (forward-char 1)
9701 (js2-forward-sws)
9702 (if (looking-at "[[{]")
9703 (let (forward-sexp-function) ; use Lisp version
9704 (forward-sexp) ; skip destructuring form
9705 (js2-forward-sws)
9706 (if (and (/= (char-after) ?,) ; regular array
9707 (looking-at "for"))
9708 (match-beginning 0)))
9709 ;; to skip arbitrary expressions we need the parser,
9710 ;; so we'll just guess at it.
9711 (if (and (> end (point)) ; not empty literal
9712 (re-search-forward "[^,]]* \\(for\\) " end t)
9713 ;; not inside comment or string literal
9714 (let ((state (parse-partial-sexp bracket (point))))
9715 (not (or (nth 3 state) (nth 4 state)))))
9716 (match-beginning 1))))))))
9717
9718 (defun js2-array-comp-indentation (parse-status for-kwd)
9719 (if (js2-same-line for-kwd)
9720 ;; first continuation line
9721 (save-excursion
9722 (goto-char (nth 1 parse-status))
9723 (forward-char 1)
9724 (skip-chars-forward " \t")
9725 (current-column))
9726 (save-excursion
9727 (goto-char for-kwd)
9728 (current-column))))
9729
9730 (defun js2-proper-indentation (parse-status)
9731 "Return the proper indentation for the current line."
9732 (save-excursion
9733 (back-to-indentation)
9734 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9735 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9736 (continued-expr-p (js2-continued-expression-p))
9737 (declaration-indent (and js2-pretty-multiline-declarations
9738 (js2-multiline-decl-indentation)))
9739 (bracket (nth 1 parse-status))
9740 beg)
9741 (cond
9742 ;; indent array comprehension continuation lines specially
9743 ((and bracket
9744 (>= js2-language-version 170)
9745 (not (js2-same-line bracket))
9746 (setq beg (js2-indent-in-array-comp parse-status))
9747 (>= (point) (save-excursion
9748 (goto-char beg)
9749 (point-at-bol)))) ; at or after first loop?
9750 (js2-array-comp-indentation parse-status beg))
9751
9752 (ctrl-stmt-indent)
9753
9754 ((and declaration-indent continued-expr-p)
9755 (+ declaration-indent js2-basic-offset))
9756
9757 (declaration-indent)
9758
9759 (bracket
9760 (goto-char bracket)
9761 (cond
9762 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9763 (when (save-excursion (skip-chars-backward " \t)")
9764 (looking-at ")"))
9765 (backward-list))
9766 (back-to-indentation)
9767 (and (eq js2-pretty-multiline-declarations 'all)
9768 (looking-at js2-declaration-keyword-re)
9769 (goto-char (1+ (match-end 0))))
9770 (cond (same-indent-p
9771 (current-column))
9772 (continued-expr-p
9773 (+ (current-column) (* 2 js2-basic-offset)))
9774 (t
9775 (+ (current-column) js2-basic-offset))))
9776 (t
9777 (unless same-indent-p
9778 (forward-char)
9779 (skip-chars-forward " \t"))
9780 (current-column))))
9781
9782 (continued-expr-p js2-basic-offset)
9783
9784 (t 0)))))
9785
9786 (defun js2-lineup-comment (parse-status)
9787 "Indent a multi-line block comment continuation line."
9788 (let* ((beg (nth 8 parse-status))
9789 (first-line (js2-same-line beg))
9790 (offset (save-excursion
9791 (goto-char beg)
9792 (if (looking-at "/\\*")
9793 (+ 1 (current-column))
9794 0))))
9795 (unless first-line
9796 (indent-line-to offset))))
9797
9798 (defun js2-backward-sws ()
9799 "Move backward through whitespace and comments."
9800 (interactive)
9801 (while (forward-comment -1)))
9802
9803 (defun js2-forward-sws ()
9804 "Move forward through whitespace and comments."
9805 (interactive)
9806 (while (forward-comment 1)))
9807
9808 (defun js2-current-indent (&optional pos)
9809 "Return column of indentation on current line.
9810 If POS is non-nil, go to that point and return indentation for that line."
9811 (save-excursion
9812 (if pos
9813 (goto-char pos))
9814 (back-to-indentation)
9815 (current-column)))
9816
9817 (defun js2-arglist-close ()
9818 "Return non-nil if we're on a line beginning with a close-paren/brace."
9819 (save-excursion
9820 (goto-char (point-at-bol))
9821 (js2-forward-sws)
9822 (looking-at "[])}]")))
9823
9824 (defun js2-indent-looks-like-label-p ()
9825 (goto-char (point-at-bol))
9826 (js2-forward-sws)
9827 (looking-at (concat js2-mode-identifier-re ":")))
9828
9829 (defun js2-indent-in-objlit-p (parse-status)
9830 "Return non-nil if this looks like an object-literal entry."
9831 (let ((start (nth 1 parse-status)))
9832 (and
9833 start
9834 (save-excursion
9835 (and (zerop (forward-line -1))
9836 (not (< (point) start)) ; crossed a {} boundary
9837 (js2-indent-looks-like-label-p)))
9838 (save-excursion
9839 (js2-indent-looks-like-label-p)))))
9840
9841 ;; If prev line looks like foobar({ then we're passing an object
9842 ;; literal to a function call, and people pretty much always want to
9843 ;; de-dent back to the previous line, so move the 'basic-offset'
9844 ;; position to the front.
9845 (defun js2-indent-objlit-arg-p (parse-status)
9846 (save-excursion
9847 (back-to-indentation)
9848 (js2-backward-sws)
9849 (and (eq (1- (point)) (nth 1 parse-status))
9850 (eq (char-before) ?{)
9851 (progn
9852 (forward-char -1)
9853 (skip-chars-backward " \t")
9854 (eq (char-before) ?\()))))
9855
9856 (defun js2-indent-case-block-p ()
9857 (save-excursion
9858 (back-to-indentation)
9859 (js2-backward-sws)
9860 (goto-char (point-at-bol))
9861 (skip-chars-forward " \t")
9862 (looking-at "case\\s-.+:")))
9863
9864 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
9865 "Cycle among alternate computed indentation positions.
9866 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9867 of the buffer to the current point. NORMAL-COL is the indentation
9868 column computed by the heuristic guesser based on current paren,
9869 bracket, brace and statement nesting. If BACKWARDS, cycle positions
9870 in reverse."
9871 (let ((cur-indent (js2-current-indent))
9872 (old-buffer-undo-list buffer-undo-list)
9873 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9874 (current-line (save-excursion
9875 (forward-line 0) ; move to bol
9876 (1+ (count-lines (point-min) (point)))))
9877 positions pos main-pos anchor arglist-cont same-indent
9878 prev-line-col basic-offset computed-pos)
9879 ;; temporarily don't record undo info, if user requested this
9880 (when js2-mode-indent-inhibit-undo
9881 (setq buffer-undo-list t))
9882 (unwind-protect
9883 (progn
9884 ;; First likely point: indent from beginning of previous code line
9885 (push (setq basic-offset
9886 (+ (save-excursion
9887 (back-to-indentation)
9888 (js2-backward-sws)
9889 (back-to-indentation)
9890 (setq prev-line-col (current-column)))
9891 js2-basic-offset))
9892 positions)
9893
9894 ;; (First + epsilon) likely point: indent 2x from beginning of
9895 ;; previous code line. Google does it this way.
9896 (push (setq basic-offset
9897 (+ (save-excursion
9898 (back-to-indentation)
9899 (js2-backward-sws)
9900 (back-to-indentation)
9901 (setq prev-line-col (current-column)))
9902 (* 2 js2-basic-offset)))
9903 positions)
9904
9905 ;; Second likely point: indent from assign-expr RHS. This
9906 ;; is just a crude guess based on finding " = " on the previous
9907 ;; line containing actual code.
9908 (setq pos (save-excursion
9909 (forward-line -1)
9910 (goto-char (point-at-bol))
9911 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
9912 (point-at-eol) t)
9913 (goto-char (match-end 1))
9914 (skip-chars-forward " \t\r\n")
9915 (current-column))))
9916 (when pos
9917 (incf pos js2-basic-offset)
9918 (push pos positions))
9919
9920 ;; Third likely point: same indent as previous line of code.
9921 ;; Make it the first likely point if we're not on an
9922 ;; arglist-close line and previous line ends in a comma, or
9923 ;; both this line and prev line look like object-literal
9924 ;; elements.
9925 (setq pos (save-excursion
9926 (goto-char (point-at-bol))
9927 (js2-backward-sws)
9928 (back-to-indentation)
9929 (prog1
9930 (current-column)
9931 ;; while we're here, look for trailing comma
9932 (if (save-excursion
9933 (goto-char (point-at-eol))
9934 (js2-backward-sws)
9935 (eq (char-before) ?,))
9936 (setq arglist-cont (1- (point)))))))
9937 (when pos
9938 (if (and (or arglist-cont
9939 (js2-indent-in-objlit-p parse-status))
9940 (not (js2-arglist-close)))
9941 (setq same-indent pos))
9942 (push pos positions))
9943
9944 ;; Fourth likely point: first preceding code with less indentation.
9945 ;; than the immediately preceding code line.
9946 (setq pos (save-excursion
9947 (back-to-indentation)
9948 (js2-backward-sws)
9949 (back-to-indentation)
9950 (setq anchor (current-column))
9951 (while (and (zerop (forward-line -1))
9952 (>= (progn
9953 (back-to-indentation)
9954 (current-column))
9955 anchor)))
9956 (setq pos (current-column))))
9957 (push pos positions)
9958
9959 ;; nesting-heuristic position, main by default
9960 (push (setq main-pos normal-col) positions)
9961
9962 ;; delete duplicates and sort positions list
9963 (setq positions (sort (delete-dups positions) '<))
9964
9965 ;; comma-list continuation lines: prev line indent takes precedence
9966 (if same-indent
9967 (setq main-pos same-indent))
9968
9969 ;; common special cases where we want to indent in from previous line
9970 (if (or (js2-indent-case-block-p)
9971 (js2-indent-objlit-arg-p parse-status))
9972 (setq main-pos basic-offset))
9973
9974 ;; if bouncing backwards, reverse positions list
9975 (if backwards
9976 (setq positions (reverse positions)))
9977
9978 ;; record whether we're already sitting on one of the alternatives
9979 (setq pos (member cur-indent positions))
9980
9981 (cond
9982 ;; case 0: we're one one of the alternatives and this is the
9983 ;; first time they've pressed TAB on this line (best-guess).
9984 ((and js2-mode-indent-ignore-first-tab
9985 pos
9986 ;; first time pressing TAB on this line?
9987 (not (eq js2-mode-last-indented-line current-line)))
9988 ;; do nothing
9989 (setq computed-pos nil))
9990 ;; case 1: only one computed position => use it
9991 ((null (cdr positions))
9992 (setq computed-pos 0))
9993 ;; case 2: not on any of the computed spots => use main spot
9994 ((not pos)
9995 (setq computed-pos (js2-position main-pos positions)))
9996 ;; case 3: on last position: cycle to first position
9997 ((null (cdr pos))
9998 (setq computed-pos 0))
9999 ;; case 4: on intermediate position: cycle to next position
10000 (t
10001 (setq computed-pos (js2-position (second pos) positions))))
10002
10003 ;; see if any hooks want to indent; otherwise we do it
10004 (loop with result = nil
10005 for hook in js2-indent-hook
10006 while (null result)
10007 do
10008 (setq result (funcall hook positions computed-pos))
10009 finally do
10010 (unless (or result (null computed-pos))
10011 (indent-line-to (nth computed-pos positions)))))
10012
10013 ;; finally
10014 (if js2-mode-indent-inhibit-undo
10015 (setq buffer-undo-list old-buffer-undo-list))
10016 ;; see commentary for `js2-mode-last-indented-line'
10017 (setq js2-mode-last-indented-line current-line))))
10018
10019 (defun js2-indent-bounce-backwards ()
10020 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10021 cycles between the computed indentation positions in reverse order."
10022 (interactive)
10023 (js2-indent-line t))
10024
10025 (defun js2-1-line-comment-continuation-p ()
10026 "Return t if we're in a 1-line comment continuation.
10027 If so, we don't ever want to use bounce-indent."
10028 (save-excursion
10029 (and (progn
10030 (forward-line 0)
10031 (looking-at "\\s-*//"))
10032 (progn
10033 (forward-line -1)
10034 (forward-line 0)
10035 (when (looking-at "\\s-*$")
10036 (js2-backward-sws)
10037 (forward-line 0))
10038 (looking-at "\\s-*//")))))
10039
10040 (defun js2-indent-line (&optional bounce-backwards)
10041 "Indent the current line as JavaScript source text."
10042 (interactive)
10043 (let (parse-status current-indent offset indent-col moved
10044 ;; Don't whine about errors/warnings when we're indenting.
10045 ;; This has to be set before calling parse-partial-sexp below.
10046 (inhibit-point-motion-hooks t))
10047 (setq parse-status (save-excursion
10048 (syntax-ppss (point-at-bol)))
10049 offset (- (point) (save-excursion
10050 (back-to-indentation)
10051 (point))))
10052 (js2-with-underscore-as-word-syntax
10053 (if (nth 4 parse-status)
10054 (js2-lineup-comment parse-status)
10055 (setq indent-col (js2-proper-indentation parse-status))
10056 ;; See comments below about `js2-mode-last-indented-line'.
10057 (cond
10058 ;; bounce-indenting is disabled during electric-key indent.
10059 ;; It doesn't work well on first line of buffer.
10060 ((and js2-bounce-indent-p
10061 (not (js2-same-line (point-min)))
10062 (not (js2-1-line-comment-continuation-p)))
10063 (js2-bounce-indent indent-col parse-status bounce-backwards))
10064 ;; just indent to the guesser's likely spot
10065 (t (indent-line-to indent-col))))
10066 (when (plusp offset)
10067 (forward-char offset)))))
10068
10069 (defun js2-indent-region (start end)
10070 "Indent the region, but don't use bounce indenting."
10071 (let ((js2-bounce-indent-p nil)
10072 (indent-region-function nil)
10073 (after-change-functions (remq 'js2-mode-edit
10074 after-change-functions)))
10075 (indent-region start end nil) ; nil for byte-compiler
10076 (js2-mode-edit start end (- end start))))
10077
10078 (defvar js2-minor-mode-map
10079 (let ((map (make-sparse-keymap)))
10080 (define-key map (kbd "C-c C-`") #'js2-next-error)
10081 (define-key map [mouse-1] #'js2-mode-show-node)
10082 map)
10083 "Keymap used when `js2-minor-mode' is active.")
10084
10085 ;;;###autoload
10086 (define-minor-mode js2-minor-mode
10087 "Minor mode for running js2 as a background linter.
10088 This allows you to use a different major mode for JavaScript editing,
10089 such as `espresso-mode', while retaining the asynchronous error/warning
10090 highlighting features of `js2-mode'."
10091 :group 'js2-mode
10092 :lighter " js-lint"
10093 (if js2-minor-mode
10094 (js2-minor-mode-enter)
10095 (js2-minor-mode-exit)))
10096
10097 (defun js2-minor-mode-enter ()
10098 "Initialization for `js2-minor-mode'."
10099 (set (make-local-variable 'max-lisp-eval-depth)
10100 (max max-lisp-eval-depth 3000))
10101 (setq next-error-function #'js2-next-error)
10102 (js2-set-default-externs)
10103 ;; Experiment: make reparse-delay longer for longer files.
10104 (if (plusp js2-dynamic-idle-timer-adjust)
10105 (setq js2-idle-timer-delay
10106 (* js2-idle-timer-delay
10107 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10108 (setq js2-mode-buffer-dirty-p t
10109 js2-mode-parsing nil)
10110 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10111 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10112 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10113 (when js2-include-jslint-globals
10114 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10115 (js2-reparse))
10116
10117 (defun js2-minor-mode-exit ()
10118 "Turn off `js2-minor-mode'."
10119 (setq next-error-function nil)
10120 (remove-hook 'after-change-functions #'js2-mode-edit t)
10121 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10122 (when js2-mode-node-overlay
10123 (delete-overlay js2-mode-node-overlay)
10124 (setq js2-mode-node-overlay nil))
10125 (js2-remove-overlays)
10126 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
10127 (setq js2-mode-ast nil))
10128
10129 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10130 (make-variable-buffer-local 'js2-source-buffer)
10131
10132 (defun* js2-display-error-list ()
10133 "Display a navigable buffer listing parse errors/warnings."
10134 (interactive)
10135 (unless (js2-have-errors-p)
10136 (message "No errors")
10137 (return-from js2-display-error-list))
10138 (labels ((annotate-list
10139 (lst type)
10140 "Add diagnostic TYPE and line number to errs list"
10141 (mapcar (lambda (err)
10142 (list err type (line-number-at-pos (nth 1 err))))
10143 lst)))
10144 (let* ((srcbuf (current-buffer))
10145 (errbuf (get-buffer-create "*js-lint*"))
10146 (errors (annotate-list
10147 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10148 'js2-error)) ; must be a valid face name
10149 (warnings (annotate-list
10150 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10151 'js2-warning)) ; must be a valid face name
10152 (all-errs (sort (append errors warnings)
10153 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10154 (with-current-buffer errbuf
10155 (let ((inhibit-read-only t))
10156 (erase-buffer)
10157 (dolist (err all-errs)
10158 (destructuring-bind ((msg-key beg end &rest) type line) err
10159 (insert-text-button
10160 (format "line %d: %s" line (js2-get-msg msg-key))
10161 'face type
10162 'follow-link "\C-m"
10163 'action 'js2-error-buffer-jump
10164 'js2-msg (js2-get-msg msg-key)
10165 'js2-pos beg)
10166 (insert "\n"))))
10167 (js2-error-buffer-mode)
10168 (setq js2-source-buffer srcbuf)
10169 (pop-to-buffer errbuf)
10170 (goto-char (point-min))
10171 (unless (eobp)
10172 (js2-error-buffer-view))))))
10173
10174 (defvar js2-error-buffer-mode-map
10175 (let ((map (make-sparse-keymap)))
10176 (define-key map "n" #'js2-error-buffer-next)
10177 (define-key map "p" #'js2-error-buffer-prev)
10178 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10179 (define-key map "o" #'js2-error-buffer-view)
10180 (define-key map "q" #'js2-error-buffer-quit)
10181 map)
10182 "Keymap used for js2 diagnostics buffers.")
10183
10184 (defun js2-error-buffer-mode ()
10185 "Major mode for js2 diagnostics buffers.
10186 Selecting an error will jump it to the corresponding source-buffer error.
10187 \\{js2-error-buffer-mode-map}"
10188 (interactive)
10189 (setq major-mode 'js2-error-buffer-mode
10190 mode-name "JS Lint Diagnostics")
10191 (use-local-map js2-error-buffer-mode-map)
10192 (setq truncate-lines t)
10193 (set-buffer-modified-p nil)
10194 (setq buffer-read-only t)
10195 (run-hooks 'js2-error-buffer-mode-hook))
10196
10197 (defun js2-error-buffer-next ()
10198 "Move to next error and view it."
10199 (interactive)
10200 (when (zerop (forward-line 1))
10201 (js2-error-buffer-view)))
10202
10203 (defun js2-error-buffer-prev ()
10204 "Move to previous error and view it."
10205 (interactive)
10206 (when (zerop (forward-line -1))
10207 (js2-error-buffer-view)))
10208
10209 (defun js2-error-buffer-quit ()
10210 "Kill the current buffer."
10211 (interactive)
10212 (kill-buffer))
10213
10214 (defun js2-error-buffer-jump (&rest ignored)
10215 "Jump cursor to current error in source buffer."
10216 (interactive)
10217 (when (js2-error-buffer-view)
10218 (pop-to-buffer js2-source-buffer)))
10219
10220 (defun js2-error-buffer-view ()
10221 "Scroll source buffer to show error at current line."
10222 (interactive)
10223 (cond
10224 ((not (eq major-mode 'js2-error-buffer-mode))
10225 (message "Not in a js2 errors buffer"))
10226 ((not (buffer-live-p js2-source-buffer))
10227 (message "Source buffer has been killed"))
10228 ((not (wholenump (get-text-property (point) 'js2-pos)))
10229 (message "There does not seem to be an error here"))
10230 (t
10231 (let ((pos (get-text-property (point) 'js2-pos))
10232 (msg (get-text-property (point) 'js2-msg)))
10233 (save-selected-window
10234 (pop-to-buffer js2-source-buffer)
10235 (goto-char pos)
10236 (message msg))))))
10237
10238 ;;;###autoload
10239 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10240 ;; FIXME: Should derive from js-mode.
10241 "Major mode for editing JavaScript code."
10242 (setq comment-start "//" ; used by comment-region; don't change it
10243 comment-end "")
10244 (set (make-local-variable 'max-lisp-eval-depth)
10245 (max max-lisp-eval-depth 3000))
10246 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10247 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10248 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10249 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10250 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10251 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10252 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10253 ;; for characters inside regexp literals.
10254 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10255 ;; this is necessary to make `show-paren-function' work properly
10256 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10257 ;; needed for M-x rgrep, among other things
10258 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10259
10260 (set (make-local-variable 'electric-indent-chars)
10261 (append '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
10262 electric-indent-chars))
10263 (set (make-local-variable 'electric-layout-rules)
10264 '((?\; . after) (?\{ . after) (?\} . before)))
10265
10266 ;; some variables needed by cc-engine for paragraph-fill, etc.
10267 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10268 c-comment-start-regexp "/[*/]\\|\\s|"
10269 c-line-comment-starter "//"
10270 c-paragraph-start js2-paragraph-start
10271 c-paragraph-separate "$"
10272 comment-start-skip js2-comment-start-skip
10273 c-syntactic-ws-start js2-syntactic-ws-start
10274 c-syntactic-ws-end js2-syntactic-ws-end
10275 c-syntactic-eol js2-syntactic-eol)
10276
10277 (let ((c-buffer-is-cc-mode t))
10278 ;; Copied from `js-mode'. Also see Bug#6071.
10279 (make-local-variable 'paragraph-start)
10280 (make-local-variable 'paragraph-separate)
10281 (make-local-variable 'paragraph-ignore-fill-prefix)
10282 (make-local-variable 'adaptive-fill-mode)
10283 (make-local-variable 'adaptive-fill-regexp)
10284 (c-setup-paragraph-variables))
10285
10286 (setq font-lock-defaults '(nil t))
10287
10288 ;; Experiment: make reparse-delay longer for longer files.
10289 (when (plusp js2-dynamic-idle-timer-adjust)
10290 (setq js2-idle-timer-delay
10291 (* js2-idle-timer-delay
10292 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10293
10294 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10295 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10296 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10297 (setq next-error-function #'js2-next-error)
10298 (imenu-add-to-menubar (concat "IM-" mode-name))
10299 (add-to-invisibility-spec '(js2-outline . t))
10300 (set (make-local-variable 'line-move-ignore-invisible) t)
10301 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10302
10303 (setq js2-mode-functions-hidden nil
10304 js2-mode-comments-hidden nil
10305 js2-mode-buffer-dirty-p t
10306 js2-mode-parsing nil)
10307
10308 (js2-set-default-externs)
10309
10310 (when js2-include-jslint-globals
10311 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10312
10313 (js2-reparse))
10314
10315 (defun js2-mode-exit ()
10316 "Exit `js2-mode' and clean up."
10317 (interactive)
10318 (when js2-mode-node-overlay
10319 (delete-overlay js2-mode-node-overlay)
10320 (setq js2-mode-node-overlay nil))
10321 (js2-remove-overlays)
10322 (setq js2-mode-ast nil)
10323 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10324 (remove-from-invisibility-spec '(js2-outline . t))
10325 (js2-mode-show-all)
10326 (with-silent-modifications
10327 (js2-clear-face (point-min) (point-max))))
10328
10329 (defun js2-mode-reset-timer ()
10330 "Cancel any existing parse timer and schedule a new one."
10331 (if js2-mode-parse-timer
10332 (cancel-timer js2-mode-parse-timer))
10333 (setq js2-mode-parsing nil)
10334 (let ((timer (timer-create)))
10335 (setq js2-mode-parse-timer timer)
10336 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10337 (timer-set-idle-time timer js2-idle-timer-delay)
10338 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10339 (timer-activate-when-idle timer nil)))
10340
10341 (defun js2-mode-idle-reparse (buffer)
10342 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10343 it to be reparsed when the buffer is selected."
10344 (if (eq buffer (current-buffer))
10345 (js2-reparse)
10346 ;; reparse when the buffer is selected again
10347 (with-current-buffer buffer
10348 (add-hook 'window-configuration-change-hook
10349 #'js2-mode-idle-reparse-inner
10350 nil t))))
10351
10352 (defun js2-mode-idle-reparse-inner ()
10353 (remove-hook 'window-configuration-change-hook
10354 #'js2-mode-idle-reparse-inner
10355 t)
10356 (js2-reparse))
10357
10358 (defun js2-mode-edit (beg end len)
10359 "Schedule a new parse after buffer is edited.
10360 Buffer edit spans from BEG to END and is of length LEN."
10361 (setq js2-mode-buffer-dirty-p t)
10362 (js2-mode-hide-overlay)
10363 (js2-mode-reset-timer))
10364
10365 (defun js2-minor-mode-edit (beg end len)
10366 "Callback for buffer edits in `js2-mode'.
10367 Schedules a new parse after buffer is edited.
10368 Buffer edit spans from BEG to END and is of length LEN."
10369 (setq js2-mode-buffer-dirty-p t)
10370 (js2-mode-hide-overlay)
10371 (js2-mode-reset-timer))
10372
10373 (defun js2-reparse (&optional force)
10374 "Re-parse current buffer after user finishes some data entry.
10375 If we get any user input while parsing, including cursor motion,
10376 we discard the parse and reschedule it. If FORCE is nil, then the
10377 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10378 (let (time
10379 interrupted-p
10380 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10381 (unless js2-mode-parsing
10382 (setq js2-mode-parsing t)
10383 (unwind-protect
10384 (when (or js2-mode-buffer-dirty-p force)
10385 (js2-remove-overlays)
10386 (with-silent-modifications
10387 (setq js2-mode-buffer-dirty-p nil
10388 js2-mode-fontifications nil
10389 js2-mode-deferred-properties nil)
10390 (if js2-mode-verbose-parse-p
10391 (message "parsing..."))
10392 (setq time
10393 (js2-time
10394 (setq interrupted-p
10395 (catch 'interrupted
10396 (js2-parse)
10397 ;; if parsing is interrupted, comments and regex
10398 ;; literals stay ignored by `parse-partial-sexp'
10399 (remove-text-properties (point-min) (point-max)
10400 '(syntax-table))
10401 (js2-mode-apply-deferred-properties)
10402 (js2-mode-remove-suppressed-warnings)
10403 (js2-mode-show-warnings)
10404 (js2-mode-show-errors)
10405 (if (>= js2-highlight-level 1)
10406 (js2-highlight-jsdoc js2-mode-ast))
10407 nil))))
10408 (if interrupted-p
10409 (progn
10410 ;; unfinished parse => try again
10411 (setq js2-mode-buffer-dirty-p t)
10412 (js2-mode-reset-timer))
10413 (if js2-mode-verbose-parse-p
10414 (message "Parse time: %s" time)))))
10415 (setq js2-mode-parsing nil)
10416 (unless interrupted-p
10417 (setq js2-mode-parse-timer nil))))))
10418
10419 (defun js2-mode-show-node (event)
10420 "Debugging aid: highlight selected AST node on mouse click."
10421 (interactive "e")
10422 (mouse-set-point event)
10423 (setq deactivate-mark t)
10424 (when js2-mode-show-overlay
10425 (let ((node (js2-node-at-point))
10426 beg end)
10427 (if (null node)
10428 (message "No node found at location %s" (point))
10429 (setq beg (js2-node-abs-pos node)
10430 end (+ beg (js2-node-len node)))
10431 (if js2-mode-node-overlay
10432 (move-overlay js2-mode-node-overlay beg end)
10433 (setq js2-mode-node-overlay (make-overlay beg end))
10434 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10435 (with-silent-modifications
10436 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10437 (message "%s, parent: %s"
10438 (js2-node-short-name node)
10439 (if (js2-node-parent node)
10440 (js2-node-short-name (js2-node-parent node))
10441 "nil"))))))
10442
10443 (defun js2-mode-hide-overlay (&optional p1 p2)
10444 "Remove the debugging overlay when the point moves.
10445 P1 and P2 are the old and new values of point, respectively."
10446 (when js2-mode-node-overlay
10447 (let ((beg (overlay-start js2-mode-node-overlay))
10448 (end (overlay-end js2-mode-node-overlay)))
10449 ;; Sometimes we're called spuriously.
10450 (unless (and p2
10451 (>= p2 beg)
10452 (<= p2 end))
10453 (with-silent-modifications
10454 (remove-text-properties beg end '(point-left nil)))
10455 (delete-overlay js2-mode-node-overlay)
10456 (setq js2-mode-node-overlay nil)))))
10457
10458 (defun js2-mode-reset ()
10459 "Debugging helper: reset everything."
10460 (interactive)
10461 (js2-mode-exit)
10462 (js2-mode))
10463
10464 (defun js2-mode-show-warn-or-err (e face)
10465 "Highlight a warning or error E with FACE.
10466 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10467 The last element is optional. When present, use instead of FACE."
10468 (let* ((key (first e))
10469 (beg (second e))
10470 (end (+ beg (third e)))
10471 ;; Don't inadvertently go out of bounds.
10472 (beg (max (point-min) (min beg (point-max))))
10473 (end (max (point-min) (min end (point-max))))
10474 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10475 (ovl (make-overlay beg end)))
10476 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10477 (overlay-put ovl 'js2-error t)
10478 (put-text-property beg end 'help-echo (js2-get-msg key))
10479 (put-text-property beg end 'point-entered #'js2-echo-error)))
10480
10481 (defun js2-remove-overlays ()
10482 "Remove overlays from buffer that have a `js2-error' property."
10483 (let ((beg (point-min))
10484 (end (point-max)))
10485 (save-excursion
10486 (dolist (o (overlays-in beg end))
10487 (when (overlay-get o 'js2-error)
10488 (delete-overlay o))))))
10489
10490 (defun js2-error-at-point (&optional pos)
10491 "Return non-nil if there's an error overlay at POS.
10492 Defaults to point."
10493 (loop with pos = (or pos (point))
10494 for o in (overlays-at pos)
10495 thereis (overlay-get o 'js2-error)))
10496
10497 (defun js2-mode-apply-deferred-properties ()
10498 "Apply fontifications and other text properties recorded during parsing."
10499 (when (plusp js2-highlight-level)
10500 ;; We defer clearing faces as long as possible to eliminate flashing.
10501 (js2-clear-face (point-min) (point-max))
10502 ;; Have to reverse the recorded fontifications list so that errors
10503 ;; and warnings overwrite the normal fontifications.
10504 (dolist (f (nreverse js2-mode-fontifications))
10505 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10506 (setq js2-mode-fontifications nil))
10507 (dolist (p js2-mode-deferred-properties)
10508 (apply #'put-text-property p))
10509 (setq js2-mode-deferred-properties nil))
10510
10511 (defun js2-mode-show-errors ()
10512 "Highlight syntax errors."
10513 (when js2-mode-show-parse-errors
10514 (dolist (e (js2-ast-root-errors js2-mode-ast))
10515 (js2-mode-show-warn-or-err e 'js2-error))))
10516
10517 (defun js2-mode-remove-suppressed-warnings ()
10518 "Take suppressed warnings out of the AST warnings list.
10519 This ensures that the counts and `next-error' are correct."
10520 (setf (js2-ast-root-warnings js2-mode-ast)
10521 (js2-delete-if
10522 (lambda (e)
10523 (let ((key (caar e)))
10524 (or
10525 (and (not js2-strict-trailing-comma-warning)
10526 (string-match "trailing\\.comma" key))
10527 (and (not js2-strict-cond-assign-warning)
10528 (string= key "msg.equal.as.assign"))
10529 (and js2-missing-semi-one-line-override
10530 (string= key "msg.missing.semi")
10531 (let* ((beg (second e))
10532 (node (js2-node-at-point beg))
10533 (fn (js2-mode-find-parent-fn node))
10534 (body (and fn (js2-function-node-body fn)))
10535 (lc (and body (js2-node-abs-pos body)))
10536 (rc (and lc (+ lc (js2-node-len body)))))
10537 (and fn
10538 (or (null body)
10539 (save-excursion
10540 (goto-char beg)
10541 (and (js2-same-line lc)
10542 (js2-same-line rc))))))))))
10543 (js2-ast-root-warnings js2-mode-ast))))
10544
10545 (defun js2-mode-show-warnings ()
10546 "Highlight strict-mode warnings."
10547 (when js2-mode-show-strict-warnings
10548 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10549 (js2-mode-show-warn-or-err e 'js2-warning))))
10550
10551 (defun js2-echo-error (old-point new-point)
10552 "Called by point-motion hooks."
10553 (let ((msg (get-text-property new-point 'help-echo)))
10554 (when (and (stringp msg) (or (not (current-message))
10555 (string= (current-message) "Quit")))
10556 (message msg))))
10557
10558 (defalias #'js2-echo-help #'js2-echo-error)
10559
10560 (defun js2-line-break (&optional soft)
10561 "Break line at point and indent, continuing comment if within one.
10562 If inside a string, and `js2-concat-multiline-strings' is not
10563 nil, turn it into concatenation."
10564 (interactive)
10565 (let ((parse-status (syntax-ppss)))
10566 (cond
10567 ;; Check if we're inside a string.
10568 ((nth 3 parse-status)
10569 (if js2-concat-multiline-strings
10570 (js2-mode-split-string parse-status)
10571 (insert "\n")))
10572 ;; Check if inside a block comment.
10573 ((nth 4 parse-status)
10574 (js2-mode-extend-comment (nth 8 parse-status)))
10575 (t
10576 (newline-and-indent)))))
10577
10578 (defun js2-mode-split-string (parse-status)
10579 "Turn a newline in mid-string into a string concatenation.
10580 PARSE-STATUS is as documented in `parse-partial-sexp'."
10581 (let* ((col (current-column))
10582 (quote-char (nth 3 parse-status))
10583 (string-beg (nth 8 parse-status))
10584 (at-eol (eq js2-concat-multiline-strings 'eol)))
10585 (insert quote-char)
10586 (if at-eol
10587 (insert " +\n")
10588 (insert "\n"))
10589 (unless at-eol
10590 (insert "+ "))
10591 (js2-indent-line)
10592 (insert quote-char)
10593 (when (eolp)
10594 (insert quote-char)
10595 (backward-char 1))))
10596
10597 (defun js2-mode-extend-comment (start-pos)
10598 "Indent the line and, when inside a comment block, add comment prefix."
10599 (let (star single col first-line needs-close)
10600 (save-excursion
10601 (back-to-indentation)
10602 (when (< (point) start-pos)
10603 (goto-char start-pos))
10604 (cond
10605 ((looking-at "\\*[^/]")
10606 (setq star t
10607 col (current-column)))
10608 ((looking-at "/\\*")
10609 (setq star t
10610 first-line t
10611 col (1+ (current-column))))
10612 ((looking-at "//")
10613 (setq single t
10614 col (current-column)))))
10615 ;; Heuristic for whether we need to close the comment:
10616 ;; if we've got a parse error here, assume it's an unterminated
10617 ;; comment.
10618 (setq needs-close
10619 (or
10620 (eq (get-text-property (1- (point)) 'point-entered)
10621 'js2-echo-error)
10622 ;; The heuristic above doesn't work well when we're
10623 ;; creating a comment and there's another one downstream,
10624 ;; as our parser thinks this one ends at the end of the
10625 ;; next one. (You can have a /* inside a js block comment.)
10626 ;; So just close it if the next non-ws char isn't a *.
10627 (and first-line
10628 (eolp)
10629 (save-excursion
10630 (skip-chars-forward " \t\r\n")
10631 (not (eq (char-after) ?*))))))
10632 (delete-horizontal-space)
10633 (insert "\n")
10634 (cond
10635 (star
10636 (indent-to col)
10637 (insert "* ")
10638 (if (and first-line needs-close)
10639 (save-excursion
10640 (insert "\n")
10641 (indent-to col)
10642 (insert "*/"))))
10643 ((and single
10644 (save-excursion
10645 (and (zerop (forward-line 1))
10646 (looking-at "\\s-*//"))))
10647 (indent-to col)
10648 (insert "// ")))
10649 ;; Don't need to extend the comment after all.
10650 (js2-indent-line)))
10651
10652 (defun js2-beginning-of-line ()
10653 "Toggle point between bol and first non-whitespace char in line.
10654 Also moves past comment delimiters when inside comments."
10655 (interactive)
10656 (let (node beg)
10657 (cond
10658 ((bolp)
10659 (back-to-indentation))
10660 ((looking-at "//")
10661 (skip-chars-forward "/ \t"))
10662 ((and (eq (char-after) ?*)
10663 (setq node (js2-comment-at-point))
10664 (memq (js2-comment-node-format node) '(jsdoc block))
10665 (save-excursion
10666 (skip-chars-backward " \t")
10667 (bolp)))
10668 (skip-chars-forward "\* \t"))
10669 (t
10670 (goto-char (point-at-bol))))))
10671
10672 (defun js2-end-of-line ()
10673 "Toggle point between eol and last non-whitespace char in line."
10674 (interactive)
10675 (if (eolp)
10676 (skip-chars-backward " \t")
10677 (goto-char (point-at-eol))))
10678
10679 (defun js2-mode-wait-for-parse (callback)
10680 "Invoke CALLBACK when parsing is finished.
10681 If parsing is already finished, calls CALLBACK immediately."
10682 (if (not js2-mode-buffer-dirty-p)
10683 (funcall callback)
10684 (push callback js2-mode-pending-parse-callbacks)
10685 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10686
10687 (defun js2-mode-parse-finished ()
10688 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10689 ;; We can't let errors propagate up, since it prevents the
10690 ;; `js2-parse' method from completing normally and returning
10691 ;; the ast, which makes things mysteriously not work right.
10692 (unwind-protect
10693 (dolist (cb js2-mode-pending-parse-callbacks)
10694 (condition-case err
10695 (funcall cb)
10696 (error (message "%s" err))))
10697 (setq js2-mode-pending-parse-callbacks nil)))
10698
10699 (defun js2-mode-flag-region (from to flag)
10700 "Hide or show text from FROM to TO, according to FLAG.
10701 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10702 Returns the created overlay if FLAG is non-nil."
10703 (remove-overlays from to 'invisible 'js2-outline)
10704 (when flag
10705 (let ((o (make-overlay from to)))
10706 (overlay-put o 'invisible 'js2-outline)
10707 (overlay-put o 'isearch-open-invisible
10708 'js2-isearch-open-invisible)
10709 o)))
10710
10711 ;; Function to be set as an outline-isearch-open-invisible' property
10712 ;; to the overlay that makes the outline invisible (see
10713 ;; `js2-mode-flag-region').
10714 (defun js2-isearch-open-invisible (overlay)
10715 ;; We rely on the fact that isearch places point on the matched text.
10716 (js2-mode-show-element))
10717
10718 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10719 "Return cons cell of bounds of folding overlay at POS.
10720 Returns nil if not found."
10721 (let ((overlays (overlays-at (or pos (point))))
10722 o)
10723 (while (and overlays
10724 (not o))
10725 (if (overlay-get (car overlays) 'invisible)
10726 (setq o (car overlays))
10727 (setq overlays (cdr overlays))))
10728 (if o
10729 (cons (overlay-start o) (overlay-end o)))))
10730
10731 (defun js2-mode-function-at-point (&optional pos)
10732 "Return the innermost function node enclosing current point.
10733 Returns nil if point is not in a function."
10734 (let ((node (js2-node-at-point pos)))
10735 (while (and node (not (js2-function-node-p node)))
10736 (setq node (js2-node-parent node)))
10737 (if (js2-function-node-p node)
10738 node)))
10739
10740 (defun js2-mode-toggle-element ()
10741 "Hide or show the foldable element at the point."
10742 (interactive)
10743 (let (comment fn pos)
10744 (save-excursion
10745 (cond
10746 ;; /* ... */ comment?
10747 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10748 (if (js2-mode-invisible-overlay-bounds
10749 (setq pos (+ 3 (js2-node-abs-pos comment))))
10750 (progn
10751 (goto-char pos)
10752 (js2-mode-show-element))
10753 (js2-mode-hide-element)))
10754 ;; //-comment?
10755 ((save-excursion
10756 (back-to-indentation)
10757 (looking-at js2-mode-//-comment-re))
10758 (js2-mode-toggle-//-comment))
10759 ;; function?
10760 ((setq fn (js2-mode-function-at-point))
10761 (setq pos (and (js2-function-node-body fn)
10762 (js2-node-abs-pos (js2-function-node-body fn))))
10763 (goto-char (1+ pos))
10764 (if (js2-mode-invisible-overlay-bounds)
10765 (js2-mode-show-element)
10766 (js2-mode-hide-element)))
10767 (t
10768 (message "Nothing at point to hide or show"))))))
10769
10770 (defun js2-mode-hide-element ()
10771 "Fold/hide contents of a block, showing ellipses.
10772 Show the hidden text with \\[js2-mode-show-element]."
10773 (interactive)
10774 (if js2-mode-buffer-dirty-p
10775 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10776 (let (node body beg end)
10777 (cond
10778 ((js2-mode-invisible-overlay-bounds)
10779 (message "already hidden"))
10780 (t
10781 (setq node (js2-node-at-point))
10782 (cond
10783 ((js2-block-comment-p node)
10784 (js2-mode-hide-comment node))
10785 (t
10786 (while (and node (not (js2-function-node-p node)))
10787 (setq node (js2-node-parent node)))
10788 (if (and node
10789 (setq body (js2-function-node-body node)))
10790 (progn
10791 (setq beg (js2-node-abs-pos body)
10792 end (+ beg (js2-node-len body)))
10793 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10794 (message "No collapsable element found at point"))))))))
10795
10796 (defun js2-mode-show-element ()
10797 "Show the hidden element at current point."
10798 (interactive)
10799 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10800 (if bounds
10801 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
10802 (message "Nothing to un-hide"))))
10803
10804 (defun js2-mode-show-all ()
10805 "Show all of the text in the buffer."
10806 (interactive)
10807 (js2-mode-flag-region (point-min) (point-max) nil))
10808
10809 (defun js2-mode-toggle-hide-functions ()
10810 (interactive)
10811 (if js2-mode-functions-hidden
10812 (js2-mode-show-functions)
10813 (js2-mode-hide-functions)))
10814
10815 (defun js2-mode-hide-functions ()
10816 "Hides all non-nested function bodies in the buffer.
10817 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10818 to open an individual entry."
10819 (interactive)
10820 (if js2-mode-buffer-dirty-p
10821 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
10822 (if (null js2-mode-ast)
10823 (message "Oops - parsing failed")
10824 (setq js2-mode-functions-hidden t)
10825 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
10826
10827 (defun js2-mode-function-hider (n endp)
10828 (when (not endp)
10829 (let ((tt (js2-node-type n))
10830 body beg end)
10831 (cond
10832 ((and (= tt js2-FUNCTION)
10833 (setq body (js2-function-node-body n)))
10834 (setq beg (js2-node-abs-pos body)
10835 end (+ beg (js2-node-len body)))
10836 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
10837 nil) ; don't process children of function
10838 (t
10839 t))))) ; keep processing other AST nodes
10840
10841 (defun js2-mode-show-functions ()
10842 "Un-hide any folded function bodies in the buffer."
10843 (interactive)
10844 (setq js2-mode-functions-hidden nil)
10845 (save-excursion
10846 (goto-char (point-min))
10847 (while (/= (goto-char (next-overlay-change (point)))
10848 (point-max))
10849 (dolist (o (overlays-at (point)))
10850 (when (and (overlay-get o 'invisible)
10851 (not (overlay-get o 'comment)))
10852 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10853
10854 (defun js2-mode-hide-comment (n)
10855 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
10856 3 ; /**
10857 2)) ; /*
10858 (beg (+ (js2-node-abs-pos n) head))
10859 (end (- (+ beg (js2-node-len n)) head 2))
10860 (o (js2-mode-flag-region beg end 'hide)))
10861 (overlay-put o 'comment t)))
10862
10863 (defun js2-mode-toggle-hide-comments ()
10864 "Folds all block comments in the buffer.
10865 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10866 to open an individual entry."
10867 (interactive)
10868 (if js2-mode-comments-hidden
10869 (js2-mode-show-comments)
10870 (js2-mode-hide-comments)))
10871
10872 (defun js2-mode-hide-comments ()
10873 (interactive)
10874 (if js2-mode-buffer-dirty-p
10875 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
10876 (if (null js2-mode-ast)
10877 (message "Oops - parsing failed")
10878 (setq js2-mode-comments-hidden t)
10879 (dolist (n (js2-ast-root-comments js2-mode-ast))
10880 (let ((format (js2-comment-node-format n)))
10881 (when (js2-block-comment-p n)
10882 (js2-mode-hide-comment n))))
10883 (js2-mode-hide-//-comments)))
10884
10885 (defun js2-mode-extend-//-comment (direction)
10886 "Find start or end of a block of similar //-comment lines.
10887 DIRECTION is -1 to look back, 1 to look forward.
10888 INDENT is the indentation level to match.
10889 Returns the end-of-line position of the furthest adjacent
10890 //-comment line with the same indentation as the current line.
10891 If there is no such matching line, returns current end of line."
10892 (let ((pos (point-at-eol))
10893 (indent (current-indentation)))
10894 (save-excursion
10895 (while (and (zerop (forward-line direction))
10896 (looking-at js2-mode-//-comment-re)
10897 (eq indent (length (match-string 1))))
10898 (setq pos (point-at-eol))
10899 pos))))
10900
10901 (defun js2-mode-hide-//-comments ()
10902 "Fold adjacent 1-line comments, showing only snippet of first one."
10903 (let (beg end)
10904 (save-excursion
10905 (goto-char (point-min))
10906 (while (re-search-forward js2-mode-//-comment-re nil t)
10907 (setq beg (point)
10908 end (js2-mode-extend-//-comment 1))
10909 (unless (eq beg end)
10910 (overlay-put (js2-mode-flag-region beg end 'hide)
10911 'comment t))
10912 (goto-char end)
10913 (forward-char 1)))))
10914
10915 (defun js2-mode-toggle-//-comment ()
10916 "Fold or un-fold any multi-line //-comment at point.
10917 Caller should have determined that this line starts with a //-comment."
10918 (let* ((beg (point-at-eol))
10919 (end beg))
10920 (save-excursion
10921 (goto-char end)
10922 (if (js2-mode-invisible-overlay-bounds)
10923 (js2-mode-show-element)
10924 ;; else hide the comment
10925 (setq beg (js2-mode-extend-//-comment -1)
10926 end (js2-mode-extend-//-comment 1))
10927 (unless (eq beg end)
10928 (overlay-put (js2-mode-flag-region beg end 'hide)
10929 'comment t))))))
10930
10931 (defun js2-mode-show-comments ()
10932 "Un-hide any hidden comments, leaving other hidden elements alone."
10933 (interactive)
10934 (setq js2-mode-comments-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 (overlay-get o 'comment)
10941 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10942
10943 (defun js2-mode-display-warnings-and-errors ()
10944 "Turn on display of warnings and errors."
10945 (interactive)
10946 (setq js2-mode-show-parse-errors t
10947 js2-mode-show-strict-warnings t)
10948 (js2-reparse 'force))
10949
10950 (defun js2-mode-hide-warnings-and-errors ()
10951 "Turn off display of warnings and errors."
10952 (interactive)
10953 (setq js2-mode-show-parse-errors nil
10954 js2-mode-show-strict-warnings nil)
10955 (js2-reparse 'force))
10956
10957 (defun js2-mode-toggle-warnings-and-errors ()
10958 "Toggle the display of warnings and errors.
10959 Some users don't like having warnings/errors reported while they type."
10960 (interactive)
10961 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
10962 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
10963 (if (called-interactively-p 'any)
10964 (message "warnings and errors %s"
10965 (if js2-mode-show-parse-errors
10966 "enabled"
10967 "disabled")))
10968 (js2-reparse 'force))
10969
10970 (defun js2-mode-customize ()
10971 (interactive)
10972 (customize-group 'js2-mode))
10973
10974 (defun js2-mode-forward-sexp (&optional arg)
10975 "Move forward across one statement or balanced expression.
10976 With ARG, do it that many times. Negative arg -N means
10977 move backward across N balanced expressions."
10978 (interactive "p")
10979 (setq arg (or arg 1))
10980 (save-restriction
10981 (widen) ;; `blink-matching-open' calls `narrow-to-region'
10982 (js2-reparse))
10983 (let (forward-sexp-function
10984 node (start (point)) pos lp rp child)
10985 (cond
10986 ;; backward-sexp
10987 ;; could probably make this better for some cases:
10988 ;; - if in statement block (e.g. function body), go to parent
10989 ;; - infix exprs like (foo in bar) - maybe go to beginning
10990 ;; of infix expr if in the right-side expression?
10991 ((and arg (minusp arg))
10992 (dotimes (i (- arg))
10993 (js2-backward-sws)
10994 (forward-char -1) ; Enter the node we backed up to.
10995 (when (setq node (js2-node-at-point (point) t))
10996 (setq pos (js2-node-abs-pos node))
10997 (let ((parens (js2-mode-forward-sexp-parens node pos)))
10998 (setq lp (car parens)
10999 rp (cdr parens)))
11000 (when (and lp (> start lp))
11001 (if (and rp (<= start rp))
11002 ;; Between parens, check if there's a child node we can jump.
11003 (when (setq child (js2-node-closest-child node (point) lp t))
11004 (setq pos (js2-node-abs-pos child)))
11005 ;; Before both parens.
11006 (setq pos lp)))
11007 (let ((state (parse-partial-sexp start pos)))
11008 (goto-char (if (not (zerop (car state)))
11009 ;; Stumble at the unbalanced paren if < 0, or
11010 ;; jump a bit further if > 0.
11011 (scan-sexps start -1)
11012 pos))))
11013 (unless pos (goto-char (point-min)))))
11014 (t
11015 ;; forward-sexp
11016 (dotimes (i arg)
11017 (js2-forward-sws)
11018 (when (setq node (js2-node-at-point (point) t))
11019 (setq pos (js2-node-abs-pos node))
11020 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11021 (setq lp (car parens)
11022 rp (cdr parens)))
11023 (or
11024 (when (and rp (<= start rp))
11025 (if (> start lp)
11026 (when (setq child (js2-node-closest-child node (point) rp))
11027 (setq pos (js2-node-abs-end child)))
11028 (setq pos (1+ rp))))
11029 ;; No parens or child nodes, looks for the end of the curren node.
11030 (incf pos (js2-node-len
11031 (if (js2-expr-stmt-node-p (js2-node-parent node))
11032 ;; Stop after the semicolon.
11033 (js2-node-parent node)
11034 node))))
11035 (let ((state (save-excursion (parse-partial-sexp start pos))))
11036 (goto-char (if (not (zerop (car state)))
11037 (scan-sexps start 1)
11038 pos))))
11039 (unless pos (goto-char (point-max))))))))
11040
11041 (defun js2-mode-forward-sexp-parens (node abs-pos)
11042 "Return a cons cell with positions of main parens in NODE."
11043 (cond
11044 ((or (js2-array-node-p node)
11045 (js2-object-node-p node)
11046 (js2-array-comp-node-p node)
11047 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11048 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11049 ((js2-paren-expr-node-p node)
11050 (let ((lp (js2-node-lp node))
11051 (rp (js2-node-rp node)))
11052 (cons (when lp (+ abs-pos lp))
11053 (when rp (+ abs-pos rp)))))))
11054
11055 (defun js2-node-closest-child (parent point limit &optional before)
11056 (let* ((parent-pos (js2-node-abs-pos parent))
11057 (rpoint (- point parent-pos))
11058 (rlimit (- limit parent-pos))
11059 (min (min rpoint rlimit))
11060 (max (max rpoint rlimit))
11061 found)
11062 (catch 'done
11063 (js2-visit-ast
11064 parent
11065 (lambda (node end-p)
11066 (if (eq node parent)
11067 t
11068 (let ((pos (js2-node-pos node)) ;; Both relative values.
11069 (end (+ (js2-node-pos node) (js2-node-len node))))
11070 (when (and (>= pos min) (<= end max)
11071 (if before (< pos rpoint) (> end rpoint)))
11072 (setq found node))
11073 (when (> end rpoint)
11074 (throw 'done nil)))
11075 nil))))
11076 found))
11077
11078 (defun js2-errors ()
11079 "Return a list of errors found."
11080 (and js2-mode-ast
11081 (js2-ast-root-errors js2-mode-ast)))
11082
11083 (defun js2-warnings ()
11084 "Return a list of warnings found."
11085 (and js2-mode-ast
11086 (js2-ast-root-warnings js2-mode-ast)))
11087
11088 (defun js2-have-errors-p ()
11089 "Return non-nil if any parse errors or warnings were found."
11090 (or (js2-errors) (js2-warnings)))
11091
11092 (defun js2-errors-and-warnings ()
11093 "Return a copy of the concatenated errors and warnings lists.
11094 They are appended: first the errors, then the warnings.
11095 Entries are of the form (MSG BEG END)."
11096 (when js2-mode-ast
11097 (append (js2-ast-root-errors js2-mode-ast)
11098 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11099
11100 (defun js2-next-error (&optional arg reset)
11101 "Move to next parse error.
11102 Typically invoked via \\[next-error].
11103 ARG is the number of errors, forward or backward, to move.
11104 RESET means start over from the beginning."
11105 (interactive "p")
11106 (if (not (or (js2-errors) (js2-warnings)))
11107 (message "No errors")
11108 (when reset
11109 (goto-char (point-min)))
11110 (let* ((errs (js2-errors-and-warnings))
11111 (continue t)
11112 (start (point))
11113 (count (or arg 1))
11114 (backward (minusp count))
11115 (sorter (if backward '> '<))
11116 (stopper (if backward '< '>))
11117 (count (abs count))
11118 all-errs err)
11119 ;; Sort by start position.
11120 (setq errs (sort errs (lambda (e1 e2)
11121 (funcall sorter (second e1) (second e2))))
11122 all-errs errs)
11123 ;; Find nth error with pos > start.
11124 (while (and errs continue)
11125 (when (funcall stopper (cadar errs) start)
11126 (setq err (car errs))
11127 (if (zerop (decf count))
11128 (setq continue nil)))
11129 (setq errs (cdr errs)))
11130 (if err
11131 (goto-char (second err))
11132 ;; Wrap around to first error.
11133 (goto-char (second (car all-errs)))
11134 ;; If we were already on it, echo msg again.
11135 (if (= (point) start)
11136 (js2-echo-error (point) (point)))))))
11137
11138 (defun js2-down-mouse-3 ()
11139 "Make right-click move the point to the click location.
11140 This makes right-click context menu operations a bit more intuitive.
11141 The point will not move if the region is active, however, to avoid
11142 destroying the region selection."
11143 (interactive)
11144 (when (and js2-move-point-on-right-click
11145 (not mark-active))
11146 (let ((e last-input-event))
11147 (ignore-errors
11148 (goto-char (cadadr e))))))
11149
11150 (defun js2-mode-create-imenu-index ()
11151 "Return an alist for `imenu--index-alist'."
11152 ;; This is built up in `js2-parse-record-imenu' during parsing.
11153 (when js2-mode-ast
11154 ;; if we have an ast but no recorder, they're requesting a rescan
11155 (unless js2-imenu-recorder
11156 (js2-reparse 'force))
11157 (prog1
11158 (js2-build-imenu-index)
11159 (setq js2-imenu-recorder nil
11160 js2-imenu-function-map nil))))
11161
11162 (defun js2-mode-find-tag ()
11163 "Replacement for `find-tag-default'.
11164 `find-tag-default' returns a ridiculous answer inside comments."
11165 (let (beg end)
11166 (js2-with-underscore-as-word-syntax
11167 (save-excursion
11168 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11169 (looking-back "[A-Za-z0-9_$]"))
11170 (setq beg (progn (forward-word -1) (point))
11171 end (progn (forward-word 1) (point)))
11172 (setq beg (progn (forward-word 1) (point))
11173 end (progn (forward-word -1) (point))))
11174 (replace-regexp-in-string
11175 "[\"']" ""
11176 (buffer-substring-no-properties beg end))))))
11177
11178 (defun js2-mode-forward-sibling ()
11179 "Move to the end of the sibling following point in parent.
11180 Returns non-nil if successful, or nil if there was no following sibling."
11181 (let* ((node (js2-node-at-point))
11182 (parent (js2-mode-find-enclosing-fn node))
11183 sib)
11184 (when (setq sib (js2-node-find-child-after (point) parent))
11185 (goto-char (+ (js2-node-abs-pos sib)
11186 (js2-node-len sib))))))
11187
11188 (defun js2-mode-backward-sibling ()
11189 "Move to the beginning of the sibling node preceding point in parent.
11190 Parent is defined as the enclosing script or function."
11191 (let* ((node (js2-node-at-point))
11192 (parent (js2-mode-find-enclosing-fn node))
11193 sib)
11194 (when (setq sib (js2-node-find-child-before (point) parent))
11195 (goto-char (js2-node-abs-pos sib)))))
11196
11197 (defun js2-beginning-of-defun (&optional arg)
11198 "Go to line on which current function starts, and return t on success.
11199 If we're not in a function or already at the beginning of one, go
11200 to beginning of previous script-level element.
11201 With ARG N, do that N times. If N is negative, move forward."
11202 (setq arg (or arg 1))
11203 (if (plusp arg)
11204 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11205 (when (cond
11206 ((js2-function-node-p parent)
11207 (goto-char (js2-node-abs-pos parent)))
11208 (t
11209 (js2-mode-backward-sibling)))
11210 (if (> arg 1)
11211 (js2-beginning-of-defun (1- arg))
11212 t)))
11213 (when (js2-end-of-defun)
11214 (if (>= arg -1)
11215 (js2-beginning-of-defun 1)
11216 (js2-beginning-of-defun (1+ arg))))))
11217
11218 (defun js2-end-of-defun ()
11219 "Go to the char after the last position of the current function
11220 or script-level element."
11221 (let* ((node (js2-node-at-point))
11222 (parent (or (and (js2-function-node-p node) node)
11223 (js2-node-parent-script-or-fn node)))
11224 script)
11225 (unless (js2-function-node-p parent)
11226 ;; Use current script-level node, or, if none, the next one.
11227 (setq script (or parent node)
11228 parent (js2-node-find-child-before (point) script))
11229 (when (or (null parent)
11230 (>= (point) (+ (js2-node-abs-pos parent)
11231 (js2-node-len parent))))
11232 (setq parent (js2-node-find-child-after (point) script))))
11233 (when parent
11234 (goto-char (+ (js2-node-abs-pos parent)
11235 (js2-node-len parent))))))
11236
11237 (defun js2-mark-defun (&optional allow-extend)
11238 "Put mark at end of this function, point at beginning.
11239 The function marked is the one that contains point.
11240
11241 Interactively, if this command is repeated,
11242 or (in Transient Mark mode) if the mark is active,
11243 it marks the next defun after the ones already marked."
11244 (interactive "p")
11245 (let (extended)
11246 (when (and allow-extend
11247 (or (and (eq last-command this-command) (mark t))
11248 (and transient-mark-mode mark-active)))
11249 (let ((sib (save-excursion
11250 (goto-char (mark))
11251 (if (js2-mode-forward-sibling)
11252 (point))))
11253 node)
11254 (if sib
11255 (progn
11256 (set-mark sib)
11257 (setq extended t))
11258 ;; no more siblings - try extending to enclosing node
11259 (goto-char (mark t)))))
11260 (when (not extended)
11261 (let ((node (js2-node-at-point (point) t)) ; skip comments
11262 ast fn stmt parent beg end)
11263 (when (js2-ast-root-p node)
11264 (setq ast node
11265 node (or (js2-node-find-child-after (point) node)
11266 (js2-node-find-child-before (point) node))))
11267 ;; only mark whole buffer if we can't find any children
11268 (if (null node)
11269 (setq node ast))
11270 (if (js2-function-node-p node)
11271 (setq parent node)
11272 (setq fn (js2-mode-find-enclosing-fn node)
11273 stmt (if (or (null fn)
11274 (js2-ast-root-p fn))
11275 (js2-mode-find-first-stmt node))
11276 parent (or stmt fn)))
11277 (setq beg (js2-node-abs-pos parent)
11278 end (+ beg (js2-node-len parent)))
11279 (push-mark beg)
11280 (goto-char end)
11281 (exchange-point-and-mark)))))
11282
11283 (defun js2-narrow-to-defun ()
11284 "Narrow to the function enclosing point."
11285 (interactive)
11286 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11287 (fn (if (js2-script-node-p node)
11288 node
11289 (js2-mode-find-enclosing-fn node)))
11290 (beg (js2-node-abs-pos fn)))
11291 (unless (js2-ast-root-p fn)
11292 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11293
11294 (provide 'js2-mode)
11295
11296 ;;; js2-mode.el ends here