]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
b48945864d0b5c32abad1673f8daee5e0b026cd8
[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: 20130307
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 Finally, you can add a function to `js2-post-parse-callbacks',
862 which is called after parsing completes, and `js2-mode-ast' is bound to
863 the root of the parse tree. At this stage you can set up an AST
864 node visitor using `js2-visit-ast' and examine the parse tree
865 for specific import patterns that may imply the existence of
866 other externs, possibly tied to your build system. These should also
867 be added to `js2-additional-externs'.
868
869 Your post-parse callback may of course also use the simpler and
870 faster (but perhaps less robust) approach of simply scanning the
871 buffer text for your imports, using regular expressions.")
872
873 ;; SKIP: decompiler
874 ;; SKIP: encoded-source
875
876 ;;; The following variables are per-function and should be saved/restored
877 ;;; during function parsing...
878
879 (js2-deflocal js2-current-script-or-fn nil)
880 (js2-deflocal js2-current-scope nil)
881 (js2-deflocal js2-nesting-of-with 0)
882 (js2-deflocal js2-label-set nil
883 "An alist mapping label names to nodes.")
884
885 (js2-deflocal js2-loop-set nil)
886 (js2-deflocal js2-loop-and-switch-set nil)
887 (js2-deflocal js2-has-return-value nil)
888 (js2-deflocal js2-end-flags 0)
889
890 ;;; ...end of per function variables
891
892 ;; Without 2-token lookahead, labels are a problem.
893 ;; These vars store the token info of the last matched name,
894 ;; iff it wasn't the last matched token. Only valid in some contexts.
895 (defvar js2-prev-name-token-start nil)
896 (defvar js2-prev-name-token-string nil)
897
898 (defsubst js2-save-name-token-data (pos name)
899 (setq js2-prev-name-token-start pos
900 js2-prev-name-token-string name))
901
902 ;; These flags enumerate the possible ways a statement/function can
903 ;; terminate. These flags are used by endCheck() and by the Parser to
904 ;; detect inconsistent return usage.
905 ;;
906 ;; END_UNREACHED is reserved for code paths that are assumed to always be
907 ;; able to execute (example: throw, continue)
908 ;;
909 ;; END_DROPS_OFF indicates if the statement can transfer control to the
910 ;; next one. Statement such as return dont. A compound statement may have
911 ;; some branch that drops off control to the next statement.
912 ;;
913 ;; END_RETURNS indicates that the statement can return (without arguments)
914 ;; END_RETURNS_VALUE indicates that the statement can return a value.
915 ;;
916 ;; A compound statement such as
917 ;; if (condition) {
918 ;; return value;
919 ;; }
920 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
921
922 (defconst js2-end-unreached #x0)
923 (defconst js2-end-drops-off #x1)
924 (defconst js2-end-returns #x2)
925 (defconst js2-end-returns-value #x4)
926 (defconst js2-end-yields #x8)
927
928 ;; Rhino awkwardly passes a statementLabel parameter to the
929 ;; statementHelper() function, the main statement parser, which
930 ;; is then used by quite a few of the sub-parsers. We just make
931 ;; it a buffer-local variable and make sure it's cleaned up properly.
932 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
933
934 ;; Similarly, Rhino passes an inForInit boolean through about half
935 ;; the expression parsers. We use a dynamically-scoped variable,
936 ;; which makes it easier to funcall the parsers individually without
937 ;; worrying about whether they take the parameter or not.
938 (js2-deflocal js2-in-for-init nil)
939 (js2-deflocal js2-temp-name-counter 0)
940 (js2-deflocal js2-parse-stmt-count 0)
941
942 (defsubst js2-get-next-temp-name ()
943 (format "$%d" (incf js2-temp-name-counter)))
944
945 (defvar js2-parse-interruptable-p t
946 "Set this to nil to force parse to continue until finished.
947 This will mostly be useful for interpreters.")
948
949 (defvar js2-statements-per-pause 50
950 "Pause after this many statements to check for user input.
951 If user input is pending, stop the parse and discard the tree.
952 This makes for a smoother user experience for large files.
953 You may have to wait a second or two before the highlighting
954 and error-reporting appear, but you can always type ahead if
955 you wish. This appears to be more or less how Eclipse, IntelliJ
956 and other editors work.")
957
958 (js2-deflocal js2-record-comments t
959 "Instructs the scanner to record comments in `js2-scanned-comments'.")
960
961 (js2-deflocal js2-scanned-comments nil
962 "List of all comments from the current parse.")
963
964 (defcustom js2-mode-indent-inhibit-undo nil
965 "Non-nil to disable collection of Undo information when indenting lines.
966 Some users have requested this behavior. It's nil by default because
967 other Emacs modes don't work this way."
968 :type 'boolean
969 :group 'js2-mode)
970
971 (defcustom js2-mode-indent-ignore-first-tab nil
972 "If non-nil, ignore first TAB keypress if we look indented properly.
973 It's fairly common for users to navigate to an already-indented line
974 and press TAB for reassurance that it's been indented. For this class
975 of users, we want the first TAB press on a line to be ignored if the
976 line is already indented to one of the precomputed alternatives.
977
978 This behavior is only partly implemented. If you TAB-indent a line,
979 navigate to another line, and then navigate back, it fails to clear
980 the last-indented variable, so it thinks you've already hit TAB once,
981 and performs the indent. A full solution would involve getting on the
982 point-motion hooks for the entire buffer. If we come across another
983 use cases that requires watching point motion, I'll consider doing it.
984
985 If you set this variable to nil, then the TAB key will always change
986 the indentation of the current line, if more than one alternative
987 indentation spot exists."
988 :type 'boolean
989 :group 'js2-mode)
990
991 (defvar js2-indent-hook nil
992 "A hook for user-defined indentation rules.
993
994 Functions on this hook should expect two arguments: (LIST INDEX)
995 The LIST argument is the list of computed indentation points for
996 the current line. INDEX is the list index of the indentation point
997 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
998 indent function is not going to change the current line indentation.
999
1000 If a hook function on this list returns a non-nil value, then
1001 `js2-bounce-indent' assumes the hook function has performed its own
1002 indentation, and will do nothing. If all hook functions on the list
1003 return nil, then `js2-bounce-indent' will use its computed indentation
1004 and reindent the line.
1005
1006 When hook functions on this hook list are called, the variable
1007 `js2-mode-ast' may or may not be set, depending on whether the
1008 parse tree is available. If the variable is nil, you can pass a
1009 callback to `js2-mode-wait-for-parse', and your callback will be
1010 called after the new parse tree is built. This can take some time
1011 in large files.")
1012
1013 (defface js2-warning
1014 `((((class color) (background light))
1015 (:underline "orange"))
1016 (((class color) (background dark))
1017 (:underline "orange"))
1018 (t (:underline t)))
1019 "Face for JavaScript warnings."
1020 :group 'js2-mode)
1021
1022 (defface js2-error
1023 `((((class color) (background light))
1024 (:foreground "red"))
1025 (((class color) (background dark))
1026 (:foreground "red"))
1027 (t (:foreground "red")))
1028 "Face for JavaScript errors."
1029 :group 'js2-mode)
1030
1031 (defface js2-jsdoc-tag
1032 '((t :foreground "SlateGray"))
1033 "Face used to highlight @whatever tags in jsdoc comments."
1034 :group 'js2-mode)
1035
1036 (defface js2-jsdoc-type
1037 '((t :foreground "SteelBlue"))
1038 "Face used to highlight {FooBar} types in jsdoc comments."
1039 :group 'js2-mode)
1040
1041 (defface js2-jsdoc-value
1042 '((t :foreground "PeachPuff3"))
1043 "Face used to highlight tag values in jsdoc comments."
1044 :group 'js2-mode)
1045
1046 (defface js2-function-param
1047 '((t :foreground "SeaGreen"))
1048 "Face used to highlight function parameters in javascript."
1049 :group 'js2-mode)
1050
1051 (defface js2-instance-member
1052 '((t :foreground "DarkOrchid"))
1053 "Face used to highlight instance variables in javascript.
1054 Not currently used."
1055 :group 'js2-mode)
1056
1057 (defface js2-private-member
1058 '((t :foreground "PeachPuff3"))
1059 "Face used to highlight calls to private methods in javascript.
1060 Not currently used."
1061 :group 'js2-mode)
1062
1063 (defface js2-private-function-call
1064 '((t :foreground "goldenrod"))
1065 "Face used to highlight calls to private functions in javascript.
1066 Not currently used."
1067 :group 'js2-mode)
1068
1069 (defface js2-jsdoc-html-tag-name
1070 '((((class color) (min-colors 88) (background light))
1071 (:foreground "rosybrown"))
1072 (((class color) (min-colors 8) (background dark))
1073 (:foreground "yellow"))
1074 (((class color) (min-colors 8) (background light))
1075 (:foreground "magenta")))
1076 "Face used to highlight jsdoc html tag names"
1077 :group 'js2-mode)
1078
1079 (defface js2-jsdoc-html-tag-delimiter
1080 '((((class color) (min-colors 88) (background light))
1081 (:foreground "dark khaki"))
1082 (((class color) (min-colors 8) (background dark))
1083 (:foreground "green"))
1084 (((class color) (min-colors 8) (background light))
1085 (:foreground "green")))
1086 "Face used to highlight brackets in jsdoc html tags."
1087 :group 'js2-mode)
1088
1089 (defface js2-external-variable
1090 '((t :foreground "orange"))
1091 "Face used to highlight undeclared variable identifiers.")
1092
1093 (defcustom js2-post-parse-callbacks nil
1094 "A list of callback functions invoked after parsing finishes.
1095 Currently, the main use for this function is to add synthetic
1096 declarations to `js2-recorded-identifiers', which see."
1097 :type 'list
1098 :group 'js2-mode)
1099
1100 (defcustom js2-highlight-external-variables t
1101 "Non-nil to highlight undeclared variable identifiers.
1102 An undeclared variable is any variable not declared with var or let
1103 in the current scope or any lexically enclosing scope. If you use
1104 such a variable, then you are either expecting it to originate from
1105 another file, or you've got a potential bug."
1106 :type 'boolean
1107 :group 'js2-mode)
1108
1109 (defcustom js2-auto-insert-catch-block t
1110 "Non-nil to insert matching catch block on open-curly after `try'."
1111 :type 'boolean
1112 :group 'js2-mode)
1113
1114 (defvar js2-mode-map
1115 (let ((map (make-sparse-keymap))
1116 keys)
1117 (define-key map [mouse-1] #'js2-mode-show-node)
1118 (define-key map (kbd "M-j") #'js2-line-break)
1119 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1120 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1121 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1122 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1123 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1124 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1125 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1126 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1127 (when js2-bounce-indent-p
1128 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1129
1130 (define-key map [menu-bar javascript]
1131 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1132
1133 (define-key map [menu-bar javascript customize-js2-mode]
1134 '(menu-item "Customize js2-mode" js2-mode-customize
1135 :help "Customize the behavior of this mode"))
1136
1137 (define-key map [menu-bar javascript js2-force-refresh]
1138 '(menu-item "Force buffer refresh" js2-mode-reset
1139 :help "Re-parse the buffer from scratch"))
1140
1141 (define-key map [menu-bar javascript separator-2]
1142 '("--"))
1143
1144 (define-key map [menu-bar javascript next-error]
1145 '(menu-item "Next warning or error" next-error
1146 :enabled (and js2-mode-ast
1147 (or (js2-ast-root-errors js2-mode-ast)
1148 (js2-ast-root-warnings js2-mode-ast)))
1149 :help "Move to next warning or error"))
1150
1151 (define-key map [menu-bar javascript display-errors]
1152 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1153 :visible (not js2-mode-show-parse-errors)
1154 :help "Turn on display of warnings and errors"))
1155
1156 (define-key map [menu-bar javascript hide-errors]
1157 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1158 :visible js2-mode-show-parse-errors
1159 :help "Turn off display of warnings and errors"))
1160
1161 (define-key map [menu-bar javascript separator-1]
1162 '("--"))
1163
1164 (define-key map [menu-bar javascript js2-toggle-function]
1165 '(menu-item "Show/collapse element" js2-mode-toggle-element
1166 :help "Hide or show function body or comment"))
1167
1168 (define-key map [menu-bar javascript show-comments]
1169 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1170 :visible js2-mode-comments-hidden
1171 :help "Expand all hidden block comments"))
1172
1173 (define-key map [menu-bar javascript hide-comments]
1174 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1175 :visible (not js2-mode-comments-hidden)
1176 :help "Show block comments as /*...*/"))
1177
1178 (define-key map [menu-bar javascript show-all-functions]
1179 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1180 :visible js2-mode-functions-hidden
1181 :help "Expand all hidden function bodies"))
1182
1183 (define-key map [menu-bar javascript hide-all-functions]
1184 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1185 :visible (not js2-mode-functions-hidden)
1186 :help "Show {...} for all top-level function bodies"))
1187
1188 map)
1189 "Keymap used in `js2-mode' buffers.")
1190
1191 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1192
1193 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1194 "Matches a //-comment line. Must be first non-whitespace on line.
1195 First match-group is the leading whitespace.")
1196
1197 (defvar js2-mode-hook nil)
1198
1199 (js2-deflocal js2-mode-ast nil "Private variable.")
1200 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1201 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1202 (js2-deflocal js2-mode-parsing nil "Private variable.")
1203 (js2-deflocal js2-mode-node-overlay nil)
1204
1205 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1206 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1207
1208 (js2-deflocal js2-mode-fontifications nil "Private variable")
1209 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1210 (js2-deflocal js2-imenu-recorder nil "Private variable")
1211 (js2-deflocal js2-imenu-function-map nil "Private variable")
1212
1213 (defvar js2-paragraph-start
1214 "\\(@[a-zA-Z]+\\>\\|$\\)")
1215
1216 ;; Note that we also set a 'c-in-sws text property in html comments,
1217 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1218 (defvar js2-syntactic-ws-start
1219 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1220
1221 (defvar js2-syntactic-ws-end
1222 "\\s \\|[\n\r/]\\|\\s!")
1223
1224 (defvar js2-syntactic-eol
1225 (concat "\\s *\\(/\\*[^*\n\r]*"
1226 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1227 "\\*+/\\s *\\)*"
1228 "\\(//\\|/\\*[^*\n\r]*"
1229 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1230 "\\|\\\\$\\|$\\)")
1231 "Copied from `java-mode'. Needed for some cc-engine functions.")
1232
1233 (defvar js2-comment-prefix-regexp
1234 "//+\\|\\**")
1235
1236 (defvar js2-comment-start-skip
1237 "\\(//+\\|/\\*+\\)\\s *")
1238
1239 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1240 "Non-nil to emit status messages during parsing.")
1241
1242 (defvar js2-mode-functions-hidden nil "Private variable.")
1243 (defvar js2-mode-comments-hidden nil "Private variable.")
1244
1245 (defvar js2-mode-syntax-table
1246 (let ((table (make-syntax-table)))
1247 (c-populate-syntax-table table)
1248 table)
1249 "Syntax table used in `js2-mode' buffers.")
1250
1251 (defvar js2-mode-abbrev-table nil
1252 "Abbrev table in use in `js2-mode' buffers.")
1253 (define-abbrev-table 'js2-mode-abbrev-table ())
1254
1255 (defvar js2-mode-pending-parse-callbacks nil
1256 "List of functions waiting to be notified that parse is finished.")
1257
1258 (defvar js2-mode-last-indented-line -1)
1259
1260 ;;; Localizable error and warning messages
1261
1262 ;; Messages are copied from Rhino's Messages.properties.
1263 ;; Many of the Java-specific messages have been elided.
1264 ;; Add any js2-specific ones at the end, so we can keep
1265 ;; this file synced with changes to Rhino's.
1266
1267 (defvar js2-message-table
1268 (make-hash-table :test 'equal :size 250)
1269 "Contains localized messages for `js2-mode'.")
1270
1271 ;; TODO(stevey): construct this table at compile-time.
1272 (defmacro js2-msg (key &rest strings)
1273 `(puthash ,key (concat ,@strings)
1274 js2-message-table))
1275
1276 (defun js2-get-msg (msg-key)
1277 "Look up a localized message.
1278 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1279 the correct number of ARGS must be provided."
1280 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1281 (args (if (listp msg-key) (cdr msg-key)))
1282 (msg (gethash key js2-message-table)))
1283 (if msg
1284 (apply #'format msg args)
1285 key))) ; default to showing the key
1286
1287 (js2-msg "msg.dup.parms"
1288 "Duplicate parameter name '%s'.")
1289
1290 (js2-msg "msg.too.big.jump"
1291 "Program too complex: jump offset too big.")
1292
1293 (js2-msg "msg.too.big.index"
1294 "Program too complex: internal index exceeds 64K limit.")
1295
1296 (js2-msg "msg.while.compiling.fn"
1297 "Encountered code generation error while compiling function '%s': %s")
1298
1299 (js2-msg "msg.while.compiling.script"
1300 "Encountered code generation error while compiling script: %s")
1301
1302 ;; Context
1303 (js2-msg "msg.ctor.not.found"
1304 "Constructor for '%s' not found.")
1305
1306 (js2-msg "msg.not.ctor"
1307 "'%s' is not a constructor.")
1308
1309 ;; FunctionObject
1310 (js2-msg "msg.varargs.ctor"
1311 "Method or constructor '%s' must be static "
1312 "with the signature (Context cx, Object[] args, "
1313 "Function ctorObj, boolean inNewExpr) "
1314 "to define a variable arguments constructor.")
1315
1316 (js2-msg "msg.varargs.fun"
1317 "Method '%s' must be static with the signature "
1318 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1319 "to define a variable arguments function.")
1320
1321 (js2-msg "msg.incompat.call"
1322 "Method '%s' called on incompatible object.")
1323
1324 (js2-msg "msg.bad.parms"
1325 "Unsupported parameter type '%s' in method '%s'.")
1326
1327 (js2-msg "msg.bad.method.return"
1328 "Unsupported return type '%s' in method '%s'.")
1329
1330 (js2-msg "msg.bad.ctor.return"
1331 "Construction of objects of type '%s' is not supported.")
1332
1333 (js2-msg "msg.no.overload"
1334 "Method '%s' occurs multiple times in class '%s'.")
1335
1336 (js2-msg "msg.method.not.found"
1337 "Method '%s' not found in '%s'.")
1338
1339 ;; IRFactory
1340
1341 (js2-msg "msg.bad.for.in.lhs"
1342 "Invalid left-hand side of for..in loop.")
1343
1344 (js2-msg "msg.mult.index"
1345 "Only one variable allowed in for..in loop.")
1346
1347 (js2-msg "msg.bad.for.in.destruct"
1348 "Left hand side of for..in loop must be an array of "
1349 "length 2 to accept key/value pair.")
1350
1351 (js2-msg "msg.cant.convert"
1352 "Can't convert to type '%s'.")
1353
1354 (js2-msg "msg.bad.assign.left"
1355 "Invalid assignment left-hand side.")
1356
1357 (js2-msg "msg.bad.decr"
1358 "Invalid decerement operand.")
1359
1360 (js2-msg "msg.bad.incr"
1361 "Invalid increment operand.")
1362
1363 (js2-msg "msg.bad.yield"
1364 "yield must be in a function.")
1365
1366 (js2-msg "msg.yield.parenthesized"
1367 "yield expression must be parenthesized.")
1368
1369 ;; NativeGlobal
1370 (js2-msg "msg.cant.call.indirect"
1371 "Function '%s' must be called directly, and not by way of a "
1372 "function of another name.")
1373
1374 (js2-msg "msg.eval.nonstring"
1375 "Calling eval() with anything other than a primitive "
1376 "string value will simply return the value. "
1377 "Is this what you intended?")
1378
1379 (js2-msg "msg.eval.nonstring.strict"
1380 "Calling eval() with anything other than a primitive "
1381 "string value is not allowed in strict mode.")
1382
1383 (js2-msg "msg.bad.destruct.op"
1384 "Invalid destructuring assignment operator")
1385
1386 ;; NativeCall
1387 (js2-msg "msg.only.from.new"
1388 "'%s' may only be invoked from a `new' expression.")
1389
1390 (js2-msg "msg.deprec.ctor"
1391 "The '%s' constructor is deprecated.")
1392
1393 ;; NativeFunction
1394 (js2-msg "msg.no.function.ref.found"
1395 "no source found to decompile function reference %s")
1396
1397 (js2-msg "msg.arg.isnt.array"
1398 "second argument to Function.prototype.apply must be an array")
1399
1400 ;; NativeGlobal
1401 (js2-msg "msg.bad.esc.mask"
1402 "invalid string escape mask")
1403
1404 ;; NativeRegExp
1405 (js2-msg "msg.bad.quant"
1406 "Invalid quantifier %s")
1407
1408 (js2-msg "msg.overlarge.backref"
1409 "Overly large back reference %s")
1410
1411 (js2-msg "msg.overlarge.min"
1412 "Overly large minimum %s")
1413
1414 (js2-msg "msg.overlarge.max"
1415 "Overly large maximum %s")
1416
1417 (js2-msg "msg.zero.quant"
1418 "Zero quantifier %s")
1419
1420 (js2-msg "msg.max.lt.min"
1421 "Maximum %s less than minimum")
1422
1423 (js2-msg "msg.unterm.quant"
1424 "Unterminated quantifier %s")
1425
1426 (js2-msg "msg.unterm.paren"
1427 "Unterminated parenthetical %s")
1428
1429 (js2-msg "msg.unterm.class"
1430 "Unterminated character class %s")
1431
1432 (js2-msg "msg.bad.range"
1433 "Invalid range in character class.")
1434
1435 (js2-msg "msg.trail.backslash"
1436 "Trailing \\ in regular expression.")
1437
1438 (js2-msg "msg.re.unmatched.right.paren"
1439 "unmatched ) in regular expression.")
1440
1441 (js2-msg "msg.no.regexp"
1442 "Regular expressions are not available.")
1443
1444 (js2-msg "msg.bad.backref"
1445 "back-reference exceeds number of capturing parentheses.")
1446
1447 (js2-msg "msg.bad.regexp.compile"
1448 "Only one argument may be specified if the first "
1449 "argument to RegExp.prototype.compile is a RegExp object.")
1450
1451 ;; Parser
1452 (js2-msg "msg.got.syntax.errors"
1453 "Compilation produced %s syntax errors.")
1454
1455 (js2-msg "msg.var.redecl"
1456 "TypeError: redeclaration of var %s.")
1457
1458 (js2-msg "msg.const.redecl"
1459 "TypeError: redeclaration of const %s.")
1460
1461 (js2-msg "msg.let.redecl"
1462 "TypeError: redeclaration of variable %s.")
1463
1464 (js2-msg "msg.parm.redecl"
1465 "TypeError: redeclaration of formal parameter %s.")
1466
1467 (js2-msg "msg.fn.redecl"
1468 "TypeError: redeclaration of function %s.")
1469
1470 (js2-msg "msg.let.decl.not.in.block"
1471 "SyntaxError: let declaration not directly within block")
1472
1473 ;; NodeTransformer
1474 (js2-msg "msg.dup.label"
1475 "duplicated label")
1476
1477 (js2-msg "msg.undef.label"
1478 "undefined label")
1479
1480 (js2-msg "msg.bad.break"
1481 "unlabelled break must be inside loop or switch")
1482
1483 (js2-msg "msg.continue.outside"
1484 "continue must be inside loop")
1485
1486 (js2-msg "msg.continue.nonloop"
1487 "continue can only use labels of iteration statements")
1488
1489 (js2-msg "msg.bad.throw.eol"
1490 "Line terminator is not allowed between the throw "
1491 "keyword and throw expression.")
1492
1493 (js2-msg "msg.no.paren.parms"
1494 "missing ( before function parameters.")
1495
1496 (js2-msg "msg.no.parm"
1497 "missing formal parameter")
1498
1499 (js2-msg "msg.no.paren.after.parms"
1500 "missing ) after formal parameters")
1501
1502 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1503 "parameter without default follows parameter with default")
1504
1505 (js2-msg "msg.param.after.rest" ; added by js2-mode
1506 "parameter after rest parameter")
1507
1508 (js2-msg "msg.no.brace.body"
1509 "missing '{' before function body")
1510
1511 (js2-msg "msg.no.brace.after.body"
1512 "missing } after function body")
1513
1514 (js2-msg "msg.no.paren.cond"
1515 "missing ( before condition")
1516
1517 (js2-msg "msg.no.paren.after.cond"
1518 "missing ) after condition")
1519
1520 (js2-msg "msg.no.semi.stmt"
1521 "missing ; before statement")
1522
1523 (js2-msg "msg.missing.semi"
1524 "missing ; after statement")
1525
1526 (js2-msg "msg.no.name.after.dot"
1527 "missing name after . operator")
1528
1529 (js2-msg "msg.no.name.after.coloncolon"
1530 "missing name after :: operator")
1531
1532 (js2-msg "msg.no.name.after.dotdot"
1533 "missing name after .. operator")
1534
1535 (js2-msg "msg.no.name.after.xmlAttr"
1536 "missing name after .@")
1537
1538 (js2-msg "msg.no.bracket.index"
1539 "missing ] in index expression")
1540
1541 (js2-msg "msg.no.paren.switch"
1542 "missing ( before switch expression")
1543
1544 (js2-msg "msg.no.paren.after.switch"
1545 "missing ) after switch expression")
1546
1547 (js2-msg "msg.no.brace.switch"
1548 "missing '{' before switch body")
1549
1550 (js2-msg "msg.bad.switch"
1551 "invalid switch statement")
1552
1553 (js2-msg "msg.no.colon.case"
1554 "missing : after case expression")
1555
1556 (js2-msg "msg.double.switch.default"
1557 "double default label in the switch statement")
1558
1559 (js2-msg "msg.no.while.do"
1560 "missing while after do-loop body")
1561
1562 (js2-msg "msg.no.paren.for"
1563 "missing ( after for")
1564
1565 (js2-msg "msg.no.semi.for"
1566 "missing ; after for-loop initializer")
1567
1568 (js2-msg "msg.no.semi.for.cond"
1569 "missing ; after for-loop condition")
1570
1571 (js2-msg "msg.in.after.for.name"
1572 "missing in or of after for")
1573
1574 (js2-msg "msg.no.paren.for.ctrl"
1575 "missing ) after for-loop control")
1576
1577 (js2-msg "msg.no.paren.with"
1578 "missing ( before with-statement object")
1579
1580 (js2-msg "msg.no.paren.after.with"
1581 "missing ) after with-statement object")
1582
1583 (js2-msg "msg.no.paren.after.let"
1584 "missing ( after let")
1585
1586 (js2-msg "msg.no.paren.let"
1587 "missing ) after variable list")
1588
1589 (js2-msg "msg.no.curly.let"
1590 "missing } after let statement")
1591
1592 (js2-msg "msg.bad.return"
1593 "invalid return")
1594
1595 (js2-msg "msg.no.brace.block"
1596 "missing } in compound statement")
1597
1598 (js2-msg "msg.bad.label"
1599 "invalid label")
1600
1601 (js2-msg "msg.bad.var"
1602 "missing variable name")
1603
1604 (js2-msg "msg.bad.var.init"
1605 "invalid variable initialization")
1606
1607 (js2-msg "msg.no.colon.cond"
1608 "missing : in conditional expression")
1609
1610 (js2-msg "msg.no.paren.arg"
1611 "missing ) after argument list")
1612
1613 (js2-msg "msg.no.bracket.arg"
1614 "missing ] after element list")
1615
1616 (js2-msg "msg.bad.prop"
1617 "invalid property id")
1618
1619 (js2-msg "msg.no.colon.prop"
1620 "missing : after property id")
1621
1622 (js2-msg "msg.no.brace.prop"
1623 "missing } after property list")
1624
1625 (js2-msg "msg.no.paren"
1626 "missing ) in parenthetical")
1627
1628 (js2-msg "msg.reserved.id"
1629 "identifier is a reserved word")
1630
1631 (js2-msg "msg.no.paren.catch"
1632 "missing ( before catch-block condition")
1633
1634 (js2-msg "msg.bad.catchcond"
1635 "invalid catch block condition")
1636
1637 (js2-msg "msg.catch.unreachable"
1638 "any catch clauses following an unqualified catch are unreachable")
1639
1640 (js2-msg "msg.no.brace.try"
1641 "missing '{' before try block")
1642
1643 (js2-msg "msg.no.brace.catchblock"
1644 "missing '{' before catch-block body")
1645
1646 (js2-msg "msg.try.no.catchfinally"
1647 "'try' without 'catch' or 'finally'")
1648
1649 (js2-msg "msg.no.return.value"
1650 "function %s does not always return a value")
1651
1652 (js2-msg "msg.anon.no.return.value"
1653 "anonymous function does not always return a value")
1654
1655 (js2-msg "msg.return.inconsistent"
1656 "return statement is inconsistent with previous usage")
1657
1658 (js2-msg "msg.generator.returns"
1659 "TypeError: generator function '%s' returns a value")
1660
1661 (js2-msg "msg.anon.generator.returns"
1662 "TypeError: anonymous generator function returns a value")
1663
1664 (js2-msg "msg.syntax"
1665 "syntax error")
1666
1667 (js2-msg "msg.unexpected.eof"
1668 "Unexpected end of file")
1669
1670 (js2-msg "msg.XML.bad.form"
1671 "illegally formed XML syntax")
1672
1673 (js2-msg "msg.XML.not.available"
1674 "XML runtime not available")
1675
1676 (js2-msg "msg.too.deep.parser.recursion"
1677 "Too deep recursion while parsing")
1678
1679 (js2-msg "msg.no.side.effects"
1680 "Code has no side effects")
1681
1682 (js2-msg "msg.extra.trailing.comma"
1683 "Trailing comma is not supported in some browsers")
1684
1685 (js2-msg "msg.array.trailing.comma"
1686 "Trailing comma yields different behavior across browsers")
1687
1688 (js2-msg "msg.equal.as.assign"
1689 (concat "Test for equality (==) mistyped as assignment (=)?"
1690 " (parenthesize to suppress warning)"))
1691
1692 (js2-msg "msg.var.hides.arg"
1693 "Variable %s hides argument")
1694
1695 (js2-msg "msg.destruct.assign.no.init"
1696 "Missing = in destructuring declaration")
1697
1698 ;; ScriptRuntime
1699 (js2-msg "msg.no.properties"
1700 "%s has no properties.")
1701
1702 (js2-msg "msg.invalid.iterator"
1703 "Invalid iterator value")
1704
1705 (js2-msg "msg.iterator.primitive"
1706 "__iterator__ returned a primitive value")
1707
1708 (js2-msg "msg.assn.create.strict"
1709 "Assignment to undeclared variable %s")
1710
1711 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1712 "Undeclared variable or function '%s'")
1713
1714 (js2-msg "msg.ref.undefined.prop"
1715 "Reference to undefined property '%s'")
1716
1717 (js2-msg "msg.prop.not.found"
1718 "Property %s not found.")
1719
1720 (js2-msg "msg.invalid.type"
1721 "Invalid JavaScript value of type %s")
1722
1723 (js2-msg "msg.primitive.expected"
1724 "Primitive type expected (had %s instead)")
1725
1726 (js2-msg "msg.namespace.expected"
1727 "Namespace object expected to left of :: (found %s instead)")
1728
1729 (js2-msg "msg.null.to.object"
1730 "Cannot convert null to an object.")
1731
1732 (js2-msg "msg.undef.to.object"
1733 "Cannot convert undefined to an object.")
1734
1735 (js2-msg "msg.cyclic.value"
1736 "Cyclic %s value not allowed.")
1737
1738 (js2-msg "msg.is.not.defined"
1739 "'%s' is not defined.")
1740
1741 (js2-msg "msg.undef.prop.read"
1742 "Cannot read property '%s' from %s")
1743
1744 (js2-msg "msg.undef.prop.write"
1745 "Cannot set property '%s' of %s to '%s'")
1746
1747 (js2-msg "msg.undef.prop.delete"
1748 "Cannot delete property '%s' of %s")
1749
1750 (js2-msg "msg.undef.method.call"
1751 "Cannot call method '%s' of %s")
1752
1753 (js2-msg "msg.undef.with"
1754 "Cannot apply 'with' to %s")
1755
1756 (js2-msg "msg.isnt.function"
1757 "%s is not a function, it is %s.")
1758
1759 (js2-msg "msg.isnt.function.in"
1760 "Cannot call property %s in object %s. "
1761 "It is not a function, it is '%s'.")
1762
1763 (js2-msg "msg.function.not.found"
1764 "Cannot find function %s.")
1765
1766 (js2-msg "msg.function.not.found.in"
1767 "Cannot find function %s in object %s.")
1768
1769 (js2-msg "msg.isnt.xml.object"
1770 "%s is not an xml object.")
1771
1772 (js2-msg "msg.no.ref.to.get"
1773 "%s is not a reference to read reference value.")
1774
1775 (js2-msg "msg.no.ref.to.set"
1776 "%s is not a reference to set reference value to %s.")
1777
1778 (js2-msg "msg.no.ref.from.function"
1779 "Function %s can not be used as the left-hand "
1780 "side of assignment or as an operand of ++ or -- operator.")
1781
1782 (js2-msg "msg.bad.default.value"
1783 "Object's getDefaultValue() method returned an object.")
1784
1785 (js2-msg "msg.instanceof.not.object"
1786 "Can't use instanceof on a non-object.")
1787
1788 (js2-msg "msg.instanceof.bad.prototype"
1789 "'prototype' property of %s is not an object.")
1790
1791 (js2-msg "msg.bad.radix"
1792 "illegal radix %s.")
1793
1794 ;; ScriptableObject
1795 (js2-msg "msg.default.value"
1796 "Cannot find default value for object.")
1797
1798 (js2-msg "msg.zero.arg.ctor"
1799 "Cannot load class '%s' which has no zero-parameter constructor.")
1800
1801 (js2-msg "msg.ctor.multiple.parms"
1802 "Can't define constructor or class %s since more than "
1803 "one constructor has multiple parameters.")
1804
1805 (js2-msg "msg.extend.scriptable"
1806 "%s must extend ScriptableObject in order to define property %s.")
1807
1808 (js2-msg "msg.bad.getter.parms"
1809 "In order to define a property, getter %s must have zero "
1810 "parameters or a single ScriptableObject parameter.")
1811
1812 (js2-msg "msg.obj.getter.parms"
1813 "Expected static or delegated getter %s to take "
1814 "a ScriptableObject parameter.")
1815
1816 (js2-msg "msg.getter.static"
1817 "Getter and setter must both be static or neither be static.")
1818
1819 (js2-msg "msg.setter.return"
1820 "Setter must have void return type: %s")
1821
1822 (js2-msg "msg.setter2.parms"
1823 "Two-parameter setter must take a ScriptableObject as "
1824 "its first parameter.")
1825
1826 (js2-msg "msg.setter1.parms"
1827 "Expected single parameter setter for %s")
1828
1829 (js2-msg "msg.setter2.expected"
1830 "Expected static or delegated setter %s to take two parameters.")
1831
1832 (js2-msg "msg.setter.parms"
1833 "Expected either one or two parameters for setter.")
1834
1835 (js2-msg "msg.setter.bad.type"
1836 "Unsupported parameter type '%s' in setter '%s'.")
1837
1838 (js2-msg "msg.add.sealed"
1839 "Cannot add a property to a sealed object: %s.")
1840
1841 (js2-msg "msg.remove.sealed"
1842 "Cannot remove a property from a sealed object: %s.")
1843
1844 (js2-msg "msg.modify.sealed"
1845 "Cannot modify a property of a sealed object: %s.")
1846
1847 (js2-msg "msg.modify.readonly"
1848 "Cannot modify readonly property: %s.")
1849
1850 ;; TokenStream
1851 (js2-msg "msg.missing.exponent"
1852 "missing exponent")
1853
1854 (js2-msg "msg.caught.nfe"
1855 "number format error")
1856
1857 (js2-msg "msg.unterminated.string.lit"
1858 "unterminated string literal")
1859
1860 (js2-msg "msg.unterminated.comment"
1861 "unterminated comment")
1862
1863 (js2-msg "msg.unterminated.re.lit"
1864 "unterminated regular expression literal")
1865
1866 (js2-msg "msg.invalid.re.flag"
1867 "invalid flag after regular expression")
1868
1869 (js2-msg "msg.no.re.input.for"
1870 "no input for %s")
1871
1872 (js2-msg "msg.illegal.character"
1873 "illegal character")
1874
1875 (js2-msg "msg.invalid.escape"
1876 "invalid Unicode escape sequence")
1877
1878 (js2-msg "msg.bad.namespace"
1879 "not a valid default namespace statement. "
1880 "Syntax is: default xml namespace = EXPRESSION;")
1881
1882 ;; TokensStream warnings
1883 (js2-msg "msg.bad.octal.literal"
1884 "illegal octal literal digit %s; "
1885 "interpreting it as a decimal digit")
1886
1887 (js2-msg "msg.reserved.keyword"
1888 "illegal usage of future reserved keyword %s; "
1889 "interpreting it as ordinary identifier")
1890
1891 (js2-msg "msg.script.is.not.constructor"
1892 "Script objects are not constructors.")
1893
1894 ;; Arrays
1895 (js2-msg "msg.arraylength.bad"
1896 "Inappropriate array length.")
1897
1898 ;; Arrays
1899 (js2-msg "msg.arraylength.too.big"
1900 "Array length %s exceeds supported capacity limit.")
1901
1902 ;; URI
1903 (js2-msg "msg.bad.uri"
1904 "Malformed URI sequence.")
1905
1906 ;; Number
1907 (js2-msg "msg.bad.precision"
1908 "Precision %s out of range.")
1909
1910 ;; NativeGenerator
1911 (js2-msg "msg.send.newborn"
1912 "Attempt to send value to newborn generator")
1913
1914 (js2-msg "msg.already.exec.gen"
1915 "Already executing generator")
1916
1917 (js2-msg "msg.StopIteration.invalid"
1918 "StopIteration may not be changed to an arbitrary object.")
1919
1920 ;; Interpreter
1921 (js2-msg "msg.yield.closing"
1922 "Yield from closing generator")
1923
1924 ;;; Utilities
1925
1926 (defun js2-delete-if (predicate list)
1927 "Remove all items satisfying PREDICATE in LIST."
1928 (loop for item in list
1929 if (not (funcall predicate item))
1930 collect item))
1931
1932 (defun js2-position (element list)
1933 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1934 Returns nil if element is not found in the list."
1935 (let ((count 0)
1936 found)
1937 (while (and list (not found))
1938 (if (eq element (car list))
1939 (setq found t)
1940 (setq count (1+ count)
1941 list (cdr list))))
1942 (if found count)))
1943
1944 (defun js2-find-if (predicate list)
1945 "Find first item satisfying PREDICATE in LIST."
1946 (let (result)
1947 (while (and list (not result))
1948 (if (funcall predicate (car list))
1949 (setq result (car list)))
1950 (setq list (cdr list)))
1951 result))
1952
1953 (defmacro js2-time (form)
1954 "Evaluate FORM, discard result, and return elapsed time in sec."
1955 (declare (debug t))
1956 (let ((beg (make-symbol "--js2-time-beg--"))
1957 (delta (make-symbol "--js2-time-end--")))
1958 `(let ((,beg (current-time))
1959 ,delta)
1960 ,form
1961 (/ (truncate (* (- (float-time (current-time))
1962 (float-time ,beg))
1963 10000))
1964 10000.0))))
1965
1966 (defsubst js2-same-line (pos)
1967 "Return t if POS is on the same line as current point."
1968 (and (>= pos (point-at-bol))
1969 (<= pos (point-at-eol))))
1970
1971 (defun js2-code-bug ()
1972 "Signal an error when we encounter an unexpected code path."
1973 (error "failed assertion"))
1974
1975 (defsubst js2-record-text-property (beg end prop value)
1976 "Record a text property to set when parsing finishes."
1977 (push (list beg end prop value) js2-mode-deferred-properties))
1978
1979 ;; I'd like to associate errors with nodes, but for now the
1980 ;; easiest thing to do is get the context info from the last token.
1981 (defun js2-record-parse-error (msg &optional arg pos len)
1982 (push (list (list msg arg)
1983 (or pos js2-token-beg)
1984 (or len (- js2-token-end js2-token-beg)))
1985 js2-parsed-errors))
1986
1987 (defun js2-report-error (msg &optional msg-arg pos len)
1988 "Signal a syntax error or record a parse error."
1989 (if js2-recover-from-parse-errors
1990 (js2-record-parse-error msg msg-arg pos len)
1991 (signal 'js2-syntax-error
1992 (list msg
1993 js2-ts-lineno
1994 (save-excursion
1995 (goto-char js2-ts-cursor)
1996 (current-column))
1997 js2-ts-hit-eof))))
1998
1999 (defun js2-report-warning (msg &optional msg-arg pos len face)
2000 (if js2-compiler-report-warning-as-error
2001 (js2-report-error msg msg-arg pos len)
2002 (push (list (list msg msg-arg)
2003 (or pos js2-token-beg)
2004 (or len (- js2-token-end js2-token-beg))
2005 face)
2006 js2-parsed-warnings)))
2007
2008 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2009 (if js2-compiler-strict-mode
2010 (js2-report-warning msg-id msg-arg beg
2011 (and beg end (- end beg)))))
2012
2013 (put 'js2-syntax-error 'error-conditions
2014 '(error syntax-error js2-syntax-error))
2015 (put 'js2-syntax-error 'error-message "Syntax error")
2016
2017 (put 'js2-parse-error 'error-conditions
2018 '(error parse-error js2-parse-error))
2019 (put 'js2-parse-error 'error-message "Parse error")
2020
2021 (defmacro js2-clear-flag (flags flag)
2022 `(setq ,flags (logand ,flags (lognot ,flag))))
2023
2024 (defmacro js2-set-flag (flags flag)
2025 "Logical-or FLAG into FLAGS."
2026 `(setq ,flags (logior ,flags ,flag)))
2027
2028 (defsubst js2-flag-set-p (flags flag)
2029 (/= 0 (logand flags flag)))
2030
2031 (defsubst js2-flag-not-set-p (flags flag)
2032 (zerop (logand flags flag)))
2033
2034 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2035 "Evaluate BODY with the _ character set to be word-syntax."
2036 (declare (indent 0) (debug t))
2037 (let ((old-syntax (make-symbol "old-syntax")))
2038 `(let ((,old-syntax (string (char-syntax ?_))))
2039 (unwind-protect
2040 (progn
2041 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2042 ,@body)
2043 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2044
2045 (defsubst js2-char-uppercase-p (c)
2046 "Return t if C is an uppercase character.
2047 Handles unicode and latin chars properly."
2048 (/= c (downcase c)))
2049
2050 (defsubst js2-char-lowercase-p (c)
2051 "Return t if C is an uppercase character.
2052 Handles unicode and latin chars properly."
2053 (/= c (upcase c)))
2054
2055 ;;; AST struct and function definitions
2056
2057 ;; flags for ast node property 'member-type (used for e4x operators)
2058 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2059 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2060 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2061
2062 (defsubst js2-relpos (pos anchor)
2063 "Convert POS to be relative to ANCHOR.
2064 If POS is nil, returns nil."
2065 (and pos (- pos anchor)))
2066
2067 (defun js2-make-pad (indent)
2068 (if (zerop indent)
2069 ""
2070 (make-string (* indent js2-basic-offset) ? )))
2071
2072 (defun js2-visit-ast (node callback)
2073 "Visit every node in ast NODE with visitor CALLBACK.
2074
2075 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2076 called twice: once to visit the node, and again after all the node's
2077 children have been processed. The END-P argument is nil on the first
2078 call and non-nil on the second call. The return value of the callback
2079 affects the traversal: if non-nil, the children of NODE are processed.
2080 If the callback returns nil, or if the node has no children, then the
2081 callback is called immediately with a non-nil END-P argument.
2082
2083 The node traversal is approximately lexical-order, although there
2084 are currently no guarantees around this."
2085 (when node
2086 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2087 ;; visit the node
2088 (when (funcall callback node nil)
2089 ;; visit the kids
2090 (cond
2091 ((eq vfunc 'js2-visit-none)
2092 nil) ; don't even bother calling it
2093 ;; Each AST node type has to define a `js2-visitor' function
2094 ;; that takes a node and a callback, and calls `js2-visit-ast'
2095 ;; on each child of the node.
2096 (vfunc
2097 (funcall vfunc node callback))
2098 (t
2099 (error "%s does not define a visitor-traversal function"
2100 (aref node 0)))))
2101 ;; call the end-visit
2102 (funcall callback node t))))
2103
2104 (defstruct (js2-node
2105 (:constructor nil)) ; abstract
2106 "Base AST node type."
2107 (type -1) ; token type
2108 (pos -1) ; start position of this AST node in parsed input
2109 (len 1) ; num characters spanned by the node
2110 props ; optional node property list (an alist)
2111 parent) ; link to parent node; null for root
2112
2113 (defsubst js2-node-get-prop (node prop &optional default)
2114 (or (cadr (assoc prop (js2-node-props node))) default))
2115
2116 (defsubst js2-node-set-prop (node prop value)
2117 (setf (js2-node-props node)
2118 (cons (list prop value) (js2-node-props node))))
2119
2120 (defun js2-fixup-starts (n nodes)
2121 "Adjust the start positions of NODES to be relative to N.
2122 Any node in the list may be nil, for convenience."
2123 (dolist (node nodes)
2124 (when node
2125 (setf (js2-node-pos node) (- (js2-node-pos node)
2126 (js2-node-pos n))))))
2127
2128 (defun js2-node-add-children (parent &rest nodes)
2129 "Set parent node of NODES to PARENT, and return PARENT.
2130 Does nothing if we're not recording parent links.
2131 If any given node in NODES is nil, doesn't record that link."
2132 (js2-fixup-starts parent nodes)
2133 (dolist (node nodes)
2134 (and node
2135 (setf (js2-node-parent node) parent))))
2136
2137 ;; Non-recursive since it's called a frightening number of times.
2138 (defun js2-node-abs-pos (n)
2139 (let ((pos (js2-node-pos n)))
2140 (while (setq n (js2-node-parent n))
2141 (setq pos (+ pos (js2-node-pos n))))
2142 pos))
2143
2144 (defsubst js2-node-abs-end (n)
2145 "Return absolute buffer position of end of N."
2146 (+ (js2-node-abs-pos n) (js2-node-len n)))
2147
2148 ;; It's important to make sure block nodes have a Lisp list for the
2149 ;; child nodes, to limit printing recursion depth in an AST that
2150 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2151 ;; a sufficiently large vector tree.
2152
2153 (defstruct (js2-block-node
2154 (:include js2-node)
2155 (:constructor nil)
2156 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2157 (pos js2-token-beg)
2158 len
2159 props
2160 kids)))
2161 "A block of statements."
2162 kids) ; a Lisp list of the child statement nodes
2163
2164 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2165 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2166
2167 (defun js2-visit-block (ast callback)
2168 "Visit the `js2-block-node' children of AST."
2169 (dolist (kid (js2-block-node-kids ast))
2170 (js2-visit-ast kid callback)))
2171
2172 (defun js2-print-block (n i)
2173 (let ((pad (js2-make-pad i)))
2174 (insert pad "{\n")
2175 (dolist (kid (js2-block-node-kids n))
2176 (js2-print-ast kid (1+ i)))
2177 (insert pad "}")))
2178
2179 (defstruct (js2-scope
2180 (:include js2-block-node)
2181 (:constructor nil)
2182 (:constructor make-js2-scope (&key (type js2-BLOCK)
2183 (pos js2-token-beg)
2184 len
2185 kids)))
2186 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2187 ;; I don't have one of those handy, so I'll use an alist for now.
2188 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2189 ;; and is much lighter-weight to construct (both CPU and mem).
2190 ;; The keys are interned strings (symbols) for faster lookup.
2191 ;; Should switch to hybrid alist/hashtable eventually.
2192 symbol-table ; an alist of (symbol . js2-symbol)
2193 parent-scope ; a `js2-scope'
2194 top) ; top-level `js2-scope' (script/function)
2195
2196 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2197 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2198
2199 (defun js2-node-get-enclosing-scope (node)
2200 "Return the innermost `js2-scope' node surrounding NODE.
2201 Returns nil if there is no enclosing scope node."
2202 (let ((parent (js2-node-parent node)))
2203 (while (not (js2-scope-p parent))
2204 (setq parent (js2-node-parent parent)))
2205 parent))
2206
2207 (defun js2-get-defining-scope (scope name)
2208 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2209 Returns `js2-scope' in which NAME is defined, or nil if not found."
2210 (let ((sym (if (symbolp name)
2211 name
2212 (intern name)))
2213 table
2214 result
2215 (continue t))
2216 (while (and scope continue)
2217 (if (and (setq table (js2-scope-symbol-table scope))
2218 (assq sym table))
2219 (setq continue nil
2220 result scope)
2221 (setq scope (js2-scope-parent-scope scope))))
2222 result))
2223
2224 (defun js2-scope-get-symbol (scope name)
2225 "Return symbol table entry for NAME in SCOPE.
2226 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2227 (and (js2-scope-symbol-table scope)
2228 (cdr (assq (if (symbolp name)
2229 name
2230 (intern name))
2231 (js2-scope-symbol-table scope)))))
2232
2233 (defun js2-scope-put-symbol (scope name symbol)
2234 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2235 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2236 (let* ((table (js2-scope-symbol-table scope))
2237 (sym (if (symbolp name) name (intern name)))
2238 (entry (assq sym table)))
2239 (if entry
2240 (setcdr entry symbol)
2241 (push (cons sym symbol)
2242 (js2-scope-symbol-table scope)))))
2243
2244 (defstruct (js2-symbol
2245 (:constructor nil)
2246 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2247 "A symbol table entry."
2248 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2249 ;; js2-LET, or js2-CONST
2250 decl-type
2251 name ; string
2252 ast-node) ; a `js2-node'
2253
2254 (defstruct (js2-error-node
2255 (:include js2-node)
2256 (:constructor nil) ; silence emacs21 byte-compiler
2257 (:constructor make-js2-error-node (&key (type js2-ERROR)
2258 (pos js2-token-beg)
2259 len)))
2260 "AST node representing a parse error.")
2261
2262 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2263 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2264
2265 (defstruct (js2-script-node
2266 (:include js2-scope)
2267 (:constructor nil)
2268 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2269 (pos js2-token-beg)
2270 len
2271 var-decls
2272 fun-decls)))
2273 functions ; Lisp list of nested functions
2274 regexps ; Lisp list of (string . flags)
2275 symbols ; alist (every symbol gets unique index)
2276 (param-count 0)
2277 var-names ; vector of string names
2278 consts ; bool-vector matching var-decls
2279 (temp-number 0)) ; for generating temp variables
2280
2281 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2282 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2283
2284 (defun js2-print-script (node indent)
2285 (dolist (kid (js2-block-node-kids node))
2286 (js2-print-ast kid indent)))
2287
2288 (defstruct (js2-ast-root
2289 (:include js2-script-node)
2290 (:constructor nil)
2291 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2292 (pos js2-token-beg)
2293 len
2294 buffer)))
2295 "The root node of a js2 AST."
2296 buffer ; the source buffer from which the code was parsed
2297 comments ; a Lisp list of comments, ordered by start position
2298 errors ; a Lisp list of errors found during parsing
2299 warnings ; a Lisp list of warnings found during parsing
2300 node-count) ; number of nodes in the tree, including the root
2301
2302 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2303 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2304
2305 (defun js2-visit-ast-root (ast callback)
2306 (dolist (kid (js2-ast-root-kids ast))
2307 (js2-visit-ast kid callback))
2308 (dolist (comment (js2-ast-root-comments ast))
2309 (js2-visit-ast comment callback)))
2310
2311 (defstruct (js2-comment-node
2312 (:include js2-node)
2313 (:constructor nil)
2314 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2315 (pos js2-token-beg)
2316 len
2317 (format js2-ts-comment-type))))
2318 format) ; 'line, 'block, 'jsdoc or 'html
2319
2320 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2321 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2322
2323 (defun js2-print-comment (n i)
2324 ;; We really ought to link end-of-line comments to their nodes.
2325 ;; Or maybe we could add a new comment type, 'endline.
2326 (insert (js2-make-pad i)
2327 (js2-node-string n)))
2328
2329 (defstruct (js2-expr-stmt-node
2330 (:include js2-node)
2331 (:constructor nil)
2332 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2333 (pos js2-ts-cursor)
2334 len
2335 expr)))
2336 "An expression statement."
2337 expr)
2338
2339 (defsubst js2-expr-stmt-node-set-has-result (node)
2340 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2341 (setf (js2-node-type node) js2-EXPR_RESULT))
2342
2343 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2344 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2345
2346 (defun js2-visit-expr-stmt-node (n v)
2347 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2348
2349 (defun js2-print-expr-stmt-node (n indent)
2350 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2351 (insert ";\n"))
2352
2353 (defstruct (js2-loop-node
2354 (:include js2-scope)
2355 (:constructor nil))
2356 "Abstract supertype of loop nodes."
2357 body ; a `js2-block-node'
2358 lp ; position of left-paren, nil if omitted
2359 rp) ; position of right-paren, nil if omitted
2360
2361 (defstruct (js2-do-node
2362 (:include js2-loop-node)
2363 (:constructor nil)
2364 (:constructor make-js2-do-node (&key (type js2-DO)
2365 (pos js2-token-beg)
2366 len
2367 body
2368 condition
2369 while-pos
2370 lp
2371 rp)))
2372 "AST node for do-loop."
2373 condition ; while (expression)
2374 while-pos) ; buffer position of 'while' keyword
2375
2376 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2377 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2378
2379 (defun js2-visit-do-node (n v)
2380 (js2-visit-ast (js2-do-node-body n) v)
2381 (js2-visit-ast (js2-do-node-condition n) v))
2382
2383 (defun js2-print-do-node (n i)
2384 (let ((pad (js2-make-pad i)))
2385 (insert pad "do {\n")
2386 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2387 (js2-print-ast kid (1+ i)))
2388 (insert pad "} while (")
2389 (js2-print-ast (js2-do-node-condition n) 0)
2390 (insert ");\n")))
2391
2392 (defstruct (js2-while-node
2393 (:include js2-loop-node)
2394 (:constructor nil)
2395 (:constructor make-js2-while-node (&key (type js2-WHILE)
2396 (pos js2-token-beg)
2397 len body
2398 condition lp
2399 rp)))
2400 "AST node for while-loop."
2401 condition) ; while-condition
2402
2403 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2404 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2405
2406 (defun js2-visit-while-node (n v)
2407 (js2-visit-ast (js2-while-node-condition n) v)
2408 (js2-visit-ast (js2-while-node-body n) v))
2409
2410 (defun js2-print-while-node (n i)
2411 (let ((pad (js2-make-pad i)))
2412 (insert pad "while (")
2413 (js2-print-ast (js2-while-node-condition n) 0)
2414 (insert ") {\n")
2415 (js2-print-body (js2-while-node-body n) (1+ i))
2416 (insert pad "}\n")))
2417
2418 (defstruct (js2-for-node
2419 (:include js2-loop-node)
2420 (:constructor nil)
2421 (:constructor make-js2-for-node (&key (type js2-FOR)
2422 (pos js2-ts-cursor)
2423 len body init
2424 condition
2425 update lp rp)))
2426 "AST node for a C-style for-loop."
2427 init ; initialization expression
2428 condition ; loop condition
2429 update) ; update clause
2430
2431 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2432 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2433
2434 (defun js2-visit-for-node (n v)
2435 (js2-visit-ast (js2-for-node-init n) v)
2436 (js2-visit-ast (js2-for-node-condition n) v)
2437 (js2-visit-ast (js2-for-node-update n) v)
2438 (js2-visit-ast (js2-for-node-body n) v))
2439
2440 (defun js2-print-for-node (n i)
2441 (let ((pad (js2-make-pad i)))
2442 (insert pad "for (")
2443 (js2-print-ast (js2-for-node-init n) 0)
2444 (insert "; ")
2445 (js2-print-ast (js2-for-node-condition n) 0)
2446 (insert "; ")
2447 (js2-print-ast (js2-for-node-update n) 0)
2448 (insert ") {\n")
2449 (js2-print-body (js2-for-node-body n) (1+ i))
2450 (insert pad "}\n")))
2451
2452 (defstruct (js2-for-in-node
2453 (:include js2-loop-node)
2454 (:constructor nil)
2455 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2456 (pos js2-ts-cursor)
2457 len body
2458 iterator
2459 object
2460 in-pos
2461 each-pos
2462 foreach-p forof-p
2463 lp rp)))
2464 "AST node for a for..in loop."
2465 iterator ; [var] foo in ...
2466 object ; object over which we're iterating
2467 in-pos ; buffer position of 'in' keyword
2468 each-pos ; buffer position of 'each' keyword, if foreach-p
2469 foreach-p ; t if it's a for-each loop
2470 forof-p) ; t if it's a for-of loop
2471
2472 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2473 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2474
2475 (defun js2-visit-for-in-node (n v)
2476 (js2-visit-ast (js2-for-in-node-iterator n) v)
2477 (js2-visit-ast (js2-for-in-node-object n) v)
2478 (js2-visit-ast (js2-for-in-node-body n) v))
2479
2480 (defun js2-print-for-in-node (n i)
2481 (let ((pad (js2-make-pad i))
2482 (foreach (js2-for-in-node-foreach-p n))
2483 (forof (js2-for-in-node-forof-p n)))
2484 (insert pad "for ")
2485 (if foreach
2486 (insert "each "))
2487 (insert "(")
2488 (js2-print-ast (js2-for-in-node-iterator n) 0)
2489 (if forof
2490 (insert " of ")
2491 (insert " in "))
2492 (js2-print-ast (js2-for-in-node-object n) 0)
2493 (insert ") {\n")
2494 (js2-print-body (js2-for-in-node-body n) (1+ i))
2495 (insert pad "}\n")))
2496
2497 (defstruct (js2-return-node
2498 (:include js2-node)
2499 (:constructor nil)
2500 (:constructor make-js2-return-node (&key (type js2-RETURN)
2501 (pos js2-ts-cursor)
2502 len
2503 retval)))
2504 "AST node for a return statement."
2505 retval) ; expression to return, or 'undefined
2506
2507 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2508 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2509
2510 (defun js2-visit-return-node (n v)
2511 (js2-visit-ast (js2-return-node-retval n) v))
2512
2513 (defun js2-print-return-node (n i)
2514 (insert (js2-make-pad i) "return")
2515 (when (js2-return-node-retval n)
2516 (insert " ")
2517 (js2-print-ast (js2-return-node-retval n) 0))
2518 (insert ";\n"))
2519
2520 (defstruct (js2-if-node
2521 (:include js2-node)
2522 (:constructor nil)
2523 (:constructor make-js2-if-node (&key (type js2-IF)
2524 (pos js2-ts-cursor)
2525 len condition
2526 then-part
2527 else-pos
2528 else-part lp
2529 rp)))
2530 "AST node for an if-statement."
2531 condition ; expression
2532 then-part ; statement or block
2533 else-pos ; optional buffer position of 'else' keyword
2534 else-part ; optional statement or block
2535 lp ; position of left-paren, nil if omitted
2536 rp) ; position of right-paren, nil if omitted
2537
2538 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2539 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2540
2541 (defun js2-visit-if-node (n v)
2542 (js2-visit-ast (js2-if-node-condition n) v)
2543 (js2-visit-ast (js2-if-node-then-part n) v)
2544 (js2-visit-ast (js2-if-node-else-part n) v))
2545
2546 (defun js2-print-if-node (n i)
2547 (let ((pad (js2-make-pad i))
2548 (then-part (js2-if-node-then-part n))
2549 (else-part (js2-if-node-else-part n)))
2550 (insert pad "if (")
2551 (js2-print-ast (js2-if-node-condition n) 0)
2552 (insert ") {\n")
2553 (js2-print-body then-part (1+ i))
2554 (insert pad "}")
2555 (cond
2556 ((not else-part)
2557 (insert "\n"))
2558 ((js2-if-node-p else-part)
2559 (insert " else ")
2560 (js2-print-body else-part i))
2561 (t
2562 (insert " else {\n")
2563 (js2-print-body else-part (1+ i))
2564 (insert pad "}\n")))))
2565
2566 (defstruct (js2-try-node
2567 (:include js2-node)
2568 (:constructor nil)
2569 (:constructor make-js2-try-node (&key (type js2-TRY)
2570 (pos js2-ts-cursor)
2571 len
2572 try-block
2573 catch-clauses
2574 finally-block)))
2575 "AST node for a try-statement."
2576 try-block
2577 catch-clauses ; a Lisp list of `js2-catch-node'
2578 finally-block) ; a `js2-finally-node'
2579
2580 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2581 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2582
2583 (defun js2-visit-try-node (n v)
2584 (js2-visit-ast (js2-try-node-try-block n) v)
2585 (dolist (clause (js2-try-node-catch-clauses n))
2586 (js2-visit-ast clause v))
2587 (js2-visit-ast (js2-try-node-finally-block n) v))
2588
2589 (defun js2-print-try-node (n i)
2590 (let ((pad (js2-make-pad i))
2591 (catches (js2-try-node-catch-clauses n))
2592 (finally (js2-try-node-finally-block n)))
2593 (insert pad "try {\n")
2594 (js2-print-body (js2-try-node-try-block n) (1+ i))
2595 (insert pad "}")
2596 (when catches
2597 (dolist (catch catches)
2598 (js2-print-ast catch i)))
2599 (if finally
2600 (js2-print-ast finally i)
2601 (insert "\n"))))
2602
2603 (defstruct (js2-catch-node
2604 (:include js2-node)
2605 (:constructor nil)
2606 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2607 (pos js2-ts-cursor)
2608 len
2609 param
2610 guard-kwd
2611 guard-expr
2612 block lp
2613 rp)))
2614 "AST node for a catch clause."
2615 param ; destructuring form or simple name node
2616 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2617 guard-expr ; catch condition, a `js2-node'
2618 block ; statements, a `js2-block-node'
2619 lp ; buffer position of left-paren, nil if omitted
2620 rp) ; buffer position of right-paren, nil if omitted
2621
2622 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2623 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2624
2625 (defun js2-visit-catch-node (n v)
2626 (js2-visit-ast (js2-catch-node-param n) v)
2627 (when (js2-catch-node-guard-kwd n)
2628 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2629 (js2-visit-ast (js2-catch-node-block n) v))
2630
2631 (defun js2-print-catch-node (n i)
2632 (let ((pad (js2-make-pad i))
2633 (guard-kwd (js2-catch-node-guard-kwd n))
2634 (guard-expr (js2-catch-node-guard-expr n)))
2635 (insert " catch (")
2636 (js2-print-ast (js2-catch-node-param n) 0)
2637 (when guard-kwd
2638 (insert " if ")
2639 (js2-print-ast guard-expr 0))
2640 (insert ") {\n")
2641 (js2-print-body (js2-catch-node-block n) (1+ i))
2642 (insert pad "}")))
2643
2644 (defstruct (js2-finally-node
2645 (:include js2-node)
2646 (:constructor nil)
2647 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2648 (pos js2-ts-cursor)
2649 len body)))
2650 "AST node for a finally clause."
2651 body) ; a `js2-node', often but not always a block node
2652
2653 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2654 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2655
2656 (defun js2-visit-finally-node (n v)
2657 (js2-visit-ast (js2-finally-node-body n) v))
2658
2659 (defun js2-print-finally-node (n i)
2660 (let ((pad (js2-make-pad i)))
2661 (insert " finally {\n")
2662 (js2-print-body (js2-finally-node-body n) (1+ i))
2663 (insert pad "}\n")))
2664
2665 (defstruct (js2-switch-node
2666 (:include js2-node)
2667 (:constructor nil)
2668 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2669 (pos js2-ts-cursor)
2670 len
2671 discriminant
2672 cases lp
2673 rp)))
2674 "AST node for a switch statement."
2675 discriminant ; a `js2-node' (switch expression)
2676 cases ; a Lisp list of `js2-case-node'
2677 lp ; position of open-paren for discriminant, nil if omitted
2678 rp) ; position of close-paren for discriminant, nil if omitted
2679
2680 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2681 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2682
2683 (defun js2-visit-switch-node (n v)
2684 (js2-visit-ast (js2-switch-node-discriminant n) v)
2685 (dolist (c (js2-switch-node-cases n))
2686 (js2-visit-ast c v)))
2687
2688 (defun js2-print-switch-node (n i)
2689 (let ((pad (js2-make-pad i))
2690 (cases (js2-switch-node-cases n)))
2691 (insert pad "switch (")
2692 (js2-print-ast (js2-switch-node-discriminant n) 0)
2693 (insert ") {\n")
2694 (dolist (case cases)
2695 (js2-print-ast case i))
2696 (insert pad "}\n")))
2697
2698 (defstruct (js2-case-node
2699 (:include js2-block-node)
2700 (:constructor nil)
2701 (:constructor make-js2-case-node (&key (type js2-CASE)
2702 (pos js2-ts-cursor)
2703 len kids expr)))
2704 "AST node for a case clause of a switch statement."
2705 expr) ; the case expression (nil for default)
2706
2707 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2708 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2709
2710 (defun js2-visit-case-node (n v)
2711 (js2-visit-ast (js2-case-node-expr n) v)
2712 (js2-visit-block n v))
2713
2714 (defun js2-print-case-node (n i)
2715 (let ((pad (js2-make-pad i))
2716 (expr (js2-case-node-expr n)))
2717 (insert pad)
2718 (if (null expr)
2719 (insert "default:\n")
2720 (insert "case ")
2721 (js2-print-ast expr 0)
2722 (insert ":\n"))
2723 (dolist (kid (js2-case-node-kids n))
2724 (js2-print-ast kid (1+ i)))))
2725
2726 (defstruct (js2-throw-node
2727 (:include js2-node)
2728 (:constructor nil)
2729 (:constructor make-js2-throw-node (&key (type js2-THROW)
2730 (pos js2-ts-cursor)
2731 len expr)))
2732 "AST node for a throw statement."
2733 expr) ; the expression to throw
2734
2735 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2736 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2737
2738 (defun js2-visit-throw-node (n v)
2739 (js2-visit-ast (js2-throw-node-expr n) v))
2740
2741 (defun js2-print-throw-node (n i)
2742 (insert (js2-make-pad i) "throw ")
2743 (js2-print-ast (js2-throw-node-expr n) 0)
2744 (insert ";\n"))
2745
2746 (defstruct (js2-with-node
2747 (:include js2-node)
2748 (:constructor nil)
2749 (:constructor make-js2-with-node (&key (type js2-WITH)
2750 (pos js2-ts-cursor)
2751 len object
2752 body lp rp)))
2753 "AST node for a with-statement."
2754 object
2755 body
2756 lp ; buffer position of left-paren around object, nil if omitted
2757 rp) ; buffer position of right-paren around object, nil if omitted
2758
2759 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2760 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2761
2762 (defun js2-visit-with-node (n v)
2763 (js2-visit-ast (js2-with-node-object n) v)
2764 (js2-visit-ast (js2-with-node-body n) v))
2765
2766 (defun js2-print-with-node (n i)
2767 (let ((pad (js2-make-pad i)))
2768 (insert pad "with (")
2769 (js2-print-ast (js2-with-node-object n) 0)
2770 (insert ") {\n")
2771 (js2-print-body (js2-with-node-body n) (1+ i))
2772 (insert pad "}\n")))
2773
2774 (defstruct (js2-label-node
2775 (:include js2-node)
2776 (:constructor nil)
2777 (:constructor make-js2-label-node (&key (type js2-LABEL)
2778 (pos js2-ts-cursor)
2779 len name)))
2780 "AST node for a statement label or case label."
2781 name ; a string
2782 loop) ; for validating and code-generating continue-to-label
2783
2784 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2785 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2786
2787 (defun js2-print-label (n i)
2788 (insert (js2-make-pad i)
2789 (js2-label-node-name n)
2790 ":\n"))
2791
2792 (defstruct (js2-labeled-stmt-node
2793 (:include js2-node)
2794 (:constructor nil)
2795 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2796 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2797 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2798 (pos js2-ts-cursor)
2799 len labels stmt)))
2800 "AST node for a statement with one or more labels.
2801 Multiple labels for a statement are collapsed into the labels field."
2802 labels ; Lisp list of `js2-label-node'
2803 stmt) ; the statement these labels are for
2804
2805 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2806 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2807
2808 (defun js2-get-label-by-name (lbl-stmt name)
2809 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2810 Returns nil if no such label is in the list."
2811 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2812 result)
2813 (while (and label-list (not result))
2814 (if (string= (js2-label-node-name (car label-list)) name)
2815 (setq result (car label-list))
2816 (setq label-list (cdr label-list))))
2817 result))
2818
2819 (defun js2-visit-labeled-stmt (n v)
2820 (dolist (label (js2-labeled-stmt-node-labels n))
2821 (js2-visit-ast label v))
2822 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2823
2824 (defun js2-print-labeled-stmt (n i)
2825 (dolist (label (js2-labeled-stmt-node-labels n))
2826 (js2-print-ast label i))
2827 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2828
2829 (defun js2-labeled-stmt-node-contains (node label)
2830 "Return t if NODE contains LABEL in its label set.
2831 NODE is a `js2-labels-node'. LABEL is an identifier."
2832 (loop for nl in (js2-labeled-stmt-node-labels node)
2833 if (string= label (js2-label-node-name nl))
2834 return t
2835 finally return nil))
2836
2837 (defsubst js2-labeled-stmt-node-add-label (node label)
2838 "Add a `js2-label-node' to the label set for this statement."
2839 (setf (js2-labeled-stmt-node-labels node)
2840 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2841
2842 (defstruct (js2-jump-node
2843 (:include js2-node)
2844 (:constructor nil))
2845 "Abstract supertype of break and continue nodes."
2846 label ; `js2-name-node' for location of label identifier, if present
2847 target) ; target js2-labels-node or loop/switch statement
2848
2849 (defun js2-visit-jump-node (n v)
2850 ;; We don't visit the target, since it's a back-link.
2851 (js2-visit-ast (js2-jump-node-label n) v))
2852
2853 (defstruct (js2-break-node
2854 (:include js2-jump-node)
2855 (:constructor nil)
2856 (:constructor make-js2-break-node (&key (type js2-BREAK)
2857 (pos js2-ts-cursor)
2858 len label target)))
2859 "AST node for a break statement.
2860 The label field is a `js2-name-node', possibly nil, for the named label
2861 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2862 is the target of the break - a label node or enclosing loop/switch statement.")
2863
2864 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2865 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2866
2867 (defun js2-print-break-node (n i)
2868 (insert (js2-make-pad i) "break")
2869 (when (js2-break-node-label n)
2870 (insert " ")
2871 (js2-print-ast (js2-break-node-label n) 0))
2872 (insert ";\n"))
2873
2874 (defstruct (js2-continue-node
2875 (:include js2-jump-node)
2876 (:constructor nil)
2877 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2878 (pos js2-ts-cursor)
2879 len label target)))
2880 "AST node for a continue statement.
2881 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2882 It is nil if continue specifies no label. The target field is the jump target:
2883 a `js2-label-node' or the innermost enclosing loop.")
2884
2885 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2886 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2887
2888 (defun js2-print-continue-node (n i)
2889 (insert (js2-make-pad i) "continue")
2890 (when (js2-continue-node-label n)
2891 (insert " ")
2892 (js2-print-ast (js2-continue-node-label n) 0))
2893 (insert ";\n"))
2894
2895 (defstruct (js2-function-node
2896 (:include js2-script-node)
2897 (:constructor nil)
2898 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2899 (pos js2-ts-cursor)
2900 len
2901 (ftype 'FUNCTION)
2902 (form 'FUNCTION_STATEMENT)
2903 (name "")
2904 params rest-p
2905 body
2906 lp rp)))
2907 "AST node for a function declaration.
2908 The `params' field is a Lisp list of nodes. Each node is either a simple
2909 `js2-name-node', or if it's a destructuring-assignment parameter, a
2910 `js2-array-node' or `js2-object-node'."
2911 ftype ; FUNCTION, GETTER or SETTER
2912 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
2913 name ; function name (a `js2-name-node', or nil if anonymous)
2914 params ; a Lisp list of destructuring forms or simple name nodes
2915 rest-p ; if t, the last parameter is rest parameter
2916 body ; a `js2-block-node' or expression node (1.8 only)
2917 lp ; position of arg-list open-paren, or nil if omitted
2918 rp ; position of arg-list close-paren, or nil if omitted
2919 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2920 needs-activation ; t if we need an activation object for this frame
2921 is-generator ; t if this function contains a yield
2922 member-expr) ; nonstandard Ecma extension from Rhino
2923
2924 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2925 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2926
2927 (defun js2-visit-function-node (n v)
2928 (js2-visit-ast (js2-function-node-name n) v)
2929 (dolist (p (js2-function-node-params n))
2930 (js2-visit-ast p v))
2931 (js2-visit-ast (js2-function-node-body n) v))
2932
2933 (defun js2-print-function-node (n i)
2934 (let ((pad (js2-make-pad i))
2935 (getter (js2-node-get-prop n 'GETTER_SETTER))
2936 (name (js2-function-node-name n))
2937 (params (js2-function-node-params n))
2938 (rest-p (js2-function-node-rest-p n))
2939 (body (js2-function-node-body n))
2940 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
2941 (unless getter
2942 (insert pad "function"))
2943 (when name
2944 (insert " ")
2945 (js2-print-ast name 0))
2946 (insert "(")
2947 (loop with len = (length params)
2948 for param in params
2949 for count from 1
2950 do
2951 (when (and rest-p (= count len))
2952 (insert "..."))
2953 (js2-print-ast param 0)
2954 (when (< count len)
2955 (insert ", ")))
2956 (insert ") {")
2957 (unless expr
2958 (insert "\n"))
2959 ;; TODO: fix this to be smarter about indenting, etc.
2960 (js2-print-body body (1+ i))
2961 (insert pad "}")
2962 (unless expr
2963 (insert "\n"))))
2964
2965 (defun js2-function-name (node)
2966 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
2967 (and (js2-function-node-name node)
2968 (js2-name-node-name (js2-function-node-name node))))
2969
2970 ;; Having this be an expression node makes it more flexible.
2971 ;; There are IDE contexts, such as indentation in a for-loop initializer,
2972 ;; that work better if you assume it's an expression. Whenever we have
2973 ;; a standalone var/const declaration, we just wrap with an expr stmt.
2974 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
2975 (defstruct (js2-var-decl-node
2976 (:include js2-node)
2977 (:constructor nil)
2978 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
2979 (pos js2-token-beg)
2980 len kids
2981 decl-type)))
2982 "AST node for a variable declaration list (VAR, CONST or LET).
2983 The node bounds differ depending on the declaration type. For VAR or
2984 CONST declarations, the bounds include the var/const keyword. For LET
2985 declarations, the node begins at the position of the first child."
2986 kids ; a Lisp list of `js2-var-init-node' structs.
2987 decl-type) ; js2-VAR, js2-CONST or js2-LET
2988
2989 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
2990 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
2991
2992 (defun js2-visit-var-decl (n v)
2993 (dolist (kid (js2-var-decl-node-kids n))
2994 (js2-visit-ast kid v)))
2995
2996 (defun js2-print-var-decl (n i)
2997 (let ((pad (js2-make-pad i))
2998 (tt (js2-var-decl-node-decl-type n)))
2999 (insert pad)
3000 (insert (cond
3001 ((= tt js2-VAR) "var ")
3002 ((= tt js2-LET) "let ")
3003 ((= tt js2-CONST) "const ")
3004 (t
3005 (error "malformed var-decl node"))))
3006 (loop with kids = (js2-var-decl-node-kids n)
3007 with len = (length kids)
3008 for kid in kids
3009 for count from 1
3010 do
3011 (js2-print-ast kid 0)
3012 (if (< count len)
3013 (insert ", ")))))
3014
3015 (defstruct (js2-var-init-node
3016 (:include js2-node)
3017 (:constructor nil)
3018 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3019 (pos js2-ts-cursor)
3020 len target
3021 initializer)))
3022 "AST node for a variable declaration.
3023 The type field will be js2-CONST for a const decl."
3024 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3025 initializer) ; initializer expression, a `js2-node'
3026
3027 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3028 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3029
3030 (defun js2-visit-var-init-node (n v)
3031 (js2-visit-ast (js2-var-init-node-target n) v)
3032 (js2-visit-ast (js2-var-init-node-initializer n) v))
3033
3034 (defun js2-print-var-init-node (n i)
3035 (let ((pad (js2-make-pad i))
3036 (name (js2-var-init-node-target n))
3037 (init (js2-var-init-node-initializer n)))
3038 (insert pad)
3039 (js2-print-ast name 0)
3040 (when init
3041 (insert " = ")
3042 (js2-print-ast init 0))))
3043
3044 (defstruct (js2-cond-node
3045 (:include js2-node)
3046 (:constructor nil)
3047 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3048 (pos js2-ts-cursor)
3049 len
3050 test-expr
3051 true-expr
3052 false-expr
3053 q-pos c-pos)))
3054 "AST node for the ternary operator"
3055 test-expr
3056 true-expr
3057 false-expr
3058 q-pos ; buffer position of ?
3059 c-pos) ; buffer position of :
3060
3061 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3062 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3063
3064 (defun js2-visit-cond-node (n v)
3065 (js2-visit-ast (js2-cond-node-test-expr n) v)
3066 (js2-visit-ast (js2-cond-node-true-expr n) v)
3067 (js2-visit-ast (js2-cond-node-false-expr n) v))
3068
3069 (defun js2-print-cond-node (n i)
3070 (let ((pad (js2-make-pad i)))
3071 (insert pad)
3072 (js2-print-ast (js2-cond-node-test-expr n) 0)
3073 (insert " ? ")
3074 (js2-print-ast (js2-cond-node-true-expr n) 0)
3075 (insert " : ")
3076 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3077
3078 (defstruct (js2-infix-node
3079 (:include js2-node)
3080 (:constructor nil)
3081 (:constructor make-js2-infix-node (&key type
3082 (pos js2-ts-cursor)
3083 len op-pos
3084 left right)))
3085 "Represents infix expressions.
3086 Includes assignment ops like `|=', and the comma operator.
3087 The type field inherited from `js2-node' holds the operator."
3088 op-pos ; buffer position where operator begins
3089 left ; any `js2-node'
3090 right) ; any `js2-node'
3091
3092 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3093 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3094
3095 (defun js2-visit-infix-node (n v)
3096 (js2-visit-ast (js2-infix-node-left n) v)
3097 (js2-visit-ast (js2-infix-node-right n) v))
3098
3099 (defconst js2-operator-tokens
3100 (let ((table (make-hash-table :test 'eq))
3101 (tokens
3102 (list (cons js2-IN "in")
3103 (cons js2-TYPEOF "typeof")
3104 (cons js2-INSTANCEOF "instanceof")
3105 (cons js2-DELPROP "delete")
3106 (cons js2-COMMA ",")
3107 (cons js2-COLON ":")
3108 (cons js2-OR "||")
3109 (cons js2-AND "&&")
3110 (cons js2-INC "++")
3111 (cons js2-DEC "--")
3112 (cons js2-BITOR "|")
3113 (cons js2-BITXOR "^")
3114 (cons js2-BITAND "&")
3115 (cons js2-EQ "==")
3116 (cons js2-NE "!=")
3117 (cons js2-LT "<")
3118 (cons js2-LE "<=")
3119 (cons js2-GT ">")
3120 (cons js2-GE ">=")
3121 (cons js2-LSH "<<")
3122 (cons js2-RSH ">>")
3123 (cons js2-URSH ">>>")
3124 (cons js2-ADD "+") ; infix plus
3125 (cons js2-SUB "-") ; infix minus
3126 (cons js2-MUL "*")
3127 (cons js2-DIV "/")
3128 (cons js2-MOD "%")
3129 (cons js2-NOT "!")
3130 (cons js2-BITNOT "~")
3131 (cons js2-POS "+") ; unary plus
3132 (cons js2-NEG "-") ; unary minus
3133 (cons js2-SHEQ "===") ; shallow equality
3134 (cons js2-SHNE "!==") ; shallow inequality
3135 (cons js2-ASSIGN "=")
3136 (cons js2-ASSIGN_BITOR "|=")
3137 (cons js2-ASSIGN_BITXOR "^=")
3138 (cons js2-ASSIGN_BITAND "&=")
3139 (cons js2-ASSIGN_LSH "<<=")
3140 (cons js2-ASSIGN_RSH ">>=")
3141 (cons js2-ASSIGN_URSH ">>>=")
3142 (cons js2-ASSIGN_ADD "+=")
3143 (cons js2-ASSIGN_SUB "-=")
3144 (cons js2-ASSIGN_MUL "*=")
3145 (cons js2-ASSIGN_DIV "/=")
3146 (cons js2-ASSIGN_MOD "%="))))
3147 (loop for (k . v) in tokens do
3148 (puthash k v table))
3149 table))
3150
3151 (defun js2-print-infix-node (n i)
3152 (let* ((tt (js2-node-type n))
3153 (op (gethash tt js2-operator-tokens)))
3154 (unless op
3155 (error "unrecognized infix operator %s" (js2-node-type n)))
3156 (insert (js2-make-pad i))
3157 (js2-print-ast (js2-infix-node-left n) 0)
3158 (unless (= tt js2-COMMA)
3159 (insert " "))
3160 (insert op)
3161 (insert " ")
3162 (js2-print-ast (js2-infix-node-right n) 0)))
3163
3164 (defstruct (js2-assign-node
3165 (:include js2-infix-node)
3166 (:constructor nil)
3167 (:constructor make-js2-assign-node (&key type
3168 (pos js2-ts-cursor)
3169 len op-pos
3170 left right)))
3171 "Represents any assignment.
3172 The type field holds the actual assignment operator.")
3173
3174 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3175 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3176
3177 (defstruct (js2-unary-node
3178 (:include js2-node)
3179 (:constructor nil)
3180 (:constructor make-js2-unary-node (&key type ; required
3181 (pos js2-ts-cursor)
3182 len operand)))
3183 "AST node type for unary operator nodes.
3184 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3185 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3186 property is added if the operator follows the operand."
3187 operand) ; a `js2-node' expression
3188
3189 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3190 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3191
3192 (defun js2-visit-unary-node (n v)
3193 (js2-visit-ast (js2-unary-node-operand n) v))
3194
3195 (defun js2-print-unary-node (n i)
3196 (let* ((tt (js2-node-type n))
3197 (op (gethash tt js2-operator-tokens))
3198 (postfix (js2-node-get-prop n 'postfix)))
3199 (unless op
3200 (error "unrecognized unary operator %s" tt))
3201 (insert (js2-make-pad i))
3202 (unless postfix
3203 (insert op))
3204 (if (or (= tt js2-TYPEOF)
3205 (= tt js2-DELPROP))
3206 (insert " "))
3207 (js2-print-ast (js2-unary-node-operand n) 0)
3208 (when postfix
3209 (insert op))))
3210
3211 (defstruct (js2-let-node
3212 (:include js2-scope)
3213 (:constructor nil)
3214 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3215 (pos js2-token-beg)
3216 len vars body
3217 lp rp)))
3218 "AST node for a let expression or a let statement.
3219 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3220 vars ; a `js2-var-decl-node'
3221 body ; a `js2-node' representing the expression or body block
3222 lp
3223 rp)
3224
3225 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3226 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3227
3228 (defun js2-visit-let-node (n v)
3229 (js2-visit-ast (js2-let-node-vars n) v)
3230 (js2-visit-ast (js2-let-node-body n) v))
3231
3232 (defun js2-print-let-node (n i)
3233 (insert (js2-make-pad i) "let (")
3234 (js2-print-ast (js2-let-node-vars n) 0)
3235 (insert ") ")
3236 (js2-print-ast (js2-let-node-body n) i))
3237
3238 (defstruct (js2-keyword-node
3239 (:include js2-node)
3240 (:constructor nil)
3241 (:constructor make-js2-keyword-node (&key type
3242 (pos js2-token-beg)
3243 (len (- js2-ts-cursor pos)))))
3244 "AST node representing a literal keyword such as `null'.
3245 Used for `null', `this', `true', `false' and `debugger'.
3246 The node type is set to js2-NULL, js2-THIS, etc.")
3247
3248 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3249 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3250
3251 (defun js2-print-keyword-node (n i)
3252 (insert (js2-make-pad i)
3253 (let ((tt (js2-node-type n)))
3254 (cond
3255 ((= tt js2-THIS) "this")
3256 ((= tt js2-NULL) "null")
3257 ((= tt js2-TRUE) "true")
3258 ((= tt js2-FALSE) "false")
3259 ((= tt js2-DEBUGGER) "debugger")
3260 (t (error "Invalid keyword literal type: %d" tt))))))
3261
3262 (defsubst js2-this-node-p (node)
3263 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3264 (eq (js2-node-type node) js2-THIS))
3265
3266 (defstruct (js2-new-node
3267 (:include js2-node)
3268 (:constructor nil)
3269 (:constructor make-js2-new-node (&key (type js2-NEW)
3270 (pos js2-token-beg)
3271 len target
3272 args initializer
3273 lp rp)))
3274 "AST node for new-expression such as new Foo()."
3275 target ; an identifier or reference
3276 args ; a Lisp list of argument nodes
3277 lp ; position of left-paren, nil if omitted
3278 rp ; position of right-paren, nil if omitted
3279 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3280
3281 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3282 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3283
3284 (defun js2-visit-new-node (n v)
3285 (js2-visit-ast (js2-new-node-target n) v)
3286 (dolist (arg (js2-new-node-args n))
3287 (js2-visit-ast arg v))
3288 (js2-visit-ast (js2-new-node-initializer n) v))
3289
3290 (defun js2-print-new-node (n i)
3291 (insert (js2-make-pad i) "new ")
3292 (js2-print-ast (js2-new-node-target n))
3293 (insert "(")
3294 (js2-print-list (js2-new-node-args n))
3295 (insert ")")
3296 (when (js2-new-node-initializer n)
3297 (insert " ")
3298 (js2-print-ast (js2-new-node-initializer n))))
3299
3300 (defstruct (js2-name-node
3301 (:include js2-node)
3302 (:constructor nil)
3303 (:constructor make-js2-name-node (&key (type js2-NAME)
3304 (pos js2-token-beg)
3305 (len (- js2-ts-cursor
3306 js2-token-beg))
3307 (name js2-ts-string))))
3308 "AST node for a JavaScript identifier"
3309 name ; a string
3310 scope) ; a `js2-scope' (optional, used for codegen)
3311
3312 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3313 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3314
3315 (defun js2-print-name-node (n i)
3316 (insert (js2-make-pad i)
3317 (js2-name-node-name n)))
3318
3319 (defsubst js2-name-node-length (node)
3320 "Return identifier length of NODE, a `js2-name-node'.
3321 Returns 0 if NODE is nil or its identifier field is nil."
3322 (if node
3323 (length (js2-name-node-name node))
3324 0))
3325
3326 (defstruct (js2-number-node
3327 (:include js2-node)
3328 (:constructor nil)
3329 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3330 (pos js2-token-beg)
3331 (len (- js2-ts-cursor
3332 js2-token-beg))
3333 (value js2-ts-string)
3334 (num-value js2-ts-number))))
3335 "AST node for a number literal."
3336 value ; the original string, e.g. "6.02e23"
3337 num-value) ; the parsed number value
3338
3339 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3340 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3341
3342 (defun js2-print-number-node (n i)
3343 (insert (js2-make-pad i)
3344 (number-to-string (js2-number-node-num-value n))))
3345
3346 (defstruct (js2-regexp-node
3347 (:include js2-node)
3348 (:constructor nil)
3349 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3350 (pos js2-token-beg)
3351 (len (- js2-ts-cursor
3352 js2-token-beg))
3353 value flags)))
3354 "AST node for a regular expression literal."
3355 value ; the regexp string, without // delimiters
3356 flags) ; a string of flags, e.g. `mi'.
3357
3358 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3359 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3360
3361 (defun js2-print-regexp (n i)
3362 (insert (js2-make-pad i)
3363 "/"
3364 (js2-regexp-node-value n)
3365 "/")
3366 (if (js2-regexp-node-flags n)
3367 (insert (js2-regexp-node-flags n))))
3368
3369 (defstruct (js2-string-node
3370 (:include js2-node)
3371 (:constructor nil)
3372 (:constructor make-js2-string-node (&key (type js2-STRING)
3373 (pos js2-token-beg)
3374 (len (- js2-ts-cursor
3375 js2-token-beg))
3376 (value js2-ts-string))))
3377 "String literal.
3378 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3379 You can tell the quote type by looking at the first character."
3380 value) ; the characters of the string, including the quotes
3381
3382 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3383 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3384
3385 (defun js2-print-string-node (n i)
3386 (insert (js2-make-pad i)
3387 (js2-node-string n)))
3388
3389 (defstruct (js2-array-node
3390 (:include js2-node)
3391 (:constructor nil)
3392 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3393 (pos js2-ts-cursor)
3394 len elems)))
3395 "AST node for an array literal."
3396 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3397
3398 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3399 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3400
3401 (defun js2-visit-array-node (n v)
3402 (dolist (e (js2-array-node-elems n))
3403 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3404
3405 (defun js2-print-array-node (n i)
3406 (insert (js2-make-pad i) "[")
3407 (js2-print-list (js2-array-node-elems n))
3408 (insert "]"))
3409
3410 (defstruct (js2-object-node
3411 (:include js2-node)
3412 (:constructor nil)
3413 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3414 (pos js2-ts-cursor)
3415 len
3416 elems)))
3417 "AST node for an object literal expression.
3418 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3419 The latter represents abbreviation in destructuring expressions."
3420 elems)
3421
3422 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3423 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3424
3425 (defun js2-visit-object-node (n v)
3426 (dolist (e (js2-object-node-elems n))
3427 (js2-visit-ast e v)))
3428
3429 (defun js2-print-object-node (n i)
3430 (insert (js2-make-pad i) "{")
3431 (js2-print-list (js2-object-node-elems n))
3432 (insert "}"))
3433
3434 (defstruct (js2-object-prop-node
3435 (:include js2-infix-node)
3436 (:constructor nil)
3437 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3438 (pos js2-ts-cursor)
3439 len left
3440 right op-pos)))
3441 "AST node for an object literal prop:value entry.
3442 The `left' field is the property: a name node, string node or number node.
3443 The `right' field is a `js2-node' representing the initializer value.")
3444
3445 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3446 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3447
3448 (defun js2-print-object-prop-node (n i)
3449 (insert (js2-make-pad i))
3450 (js2-print-ast (js2-object-prop-node-left n) 0)
3451 (insert ": ")
3452 (js2-print-ast (js2-object-prop-node-right n) 0))
3453
3454 (defstruct (js2-getter-setter-node
3455 (:include js2-infix-node)
3456 (:constructor nil)
3457 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3458 (pos js2-ts-cursor)
3459 len left right)))
3460 "AST node for a getter/setter property in an object literal.
3461 The `left' field is the `js2-name-node' naming the getter/setter prop.
3462 The `right' field is always an anonymous `js2-function-node' with a node
3463 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3464
3465 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3466 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3467
3468 (defun js2-print-getter-setter (n i)
3469 (let ((pad (js2-make-pad i))
3470 (left (js2-getter-setter-node-left n))
3471 (right (js2-getter-setter-node-right n)))
3472 (insert pad)
3473 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3474 (js2-print-ast left 0)
3475 (js2-print-ast right 0)))
3476
3477 (defstruct (js2-prop-get-node
3478 (:include js2-infix-node)
3479 (:constructor nil)
3480 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3481 (pos js2-ts-cursor)
3482 len left right)))
3483 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3484
3485 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3486 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3487
3488 (defun js2-visit-prop-get-node (n v)
3489 (js2-visit-ast (js2-prop-get-node-left n) v)
3490 (js2-visit-ast (js2-prop-get-node-right n) v))
3491
3492 (defun js2-print-prop-get-node (n i)
3493 (insert (js2-make-pad i))
3494 (js2-print-ast (js2-prop-get-node-left n) 0)
3495 (insert ".")
3496 (js2-print-ast (js2-prop-get-node-right n) 0))
3497
3498 (defstruct (js2-elem-get-node
3499 (:include js2-node)
3500 (:constructor nil)
3501 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3502 (pos js2-ts-cursor)
3503 len target element
3504 lb rb)))
3505 "AST node for an array index expression such as foo[bar]."
3506 target ; a `js2-node' - the expression preceding the "."
3507 element ; a `js2-node' - the expression in brackets
3508 lb ; position of left-bracket, nil if omitted
3509 rb) ; position of right-bracket, nil if omitted
3510
3511 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3512 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3513
3514 (defun js2-visit-elem-get-node (n v)
3515 (js2-visit-ast (js2-elem-get-node-target n) v)
3516 (js2-visit-ast (js2-elem-get-node-element n) v))
3517
3518 (defun js2-print-elem-get-node (n i)
3519 (insert (js2-make-pad i))
3520 (js2-print-ast (js2-elem-get-node-target n) 0)
3521 (insert "[")
3522 (js2-print-ast (js2-elem-get-node-element n) 0)
3523 (insert "]"))
3524
3525 (defstruct (js2-call-node
3526 (:include js2-node)
3527 (:constructor nil)
3528 (:constructor make-js2-call-node (&key (type js2-CALL)
3529 (pos js2-ts-cursor)
3530 len target args
3531 lp rp)))
3532 "AST node for a JavaScript function call."
3533 target ; a `js2-node' evaluating to the function to call
3534 args ; a Lisp list of `js2-node' arguments
3535 lp ; position of open-paren, or nil if missing
3536 rp) ; position of close-paren, or nil if missing
3537
3538 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3539 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3540
3541 (defun js2-visit-call-node (n v)
3542 (js2-visit-ast (js2-call-node-target n) v)
3543 (dolist (arg (js2-call-node-args n))
3544 (js2-visit-ast arg v)))
3545
3546 (defun js2-print-call-node (n i)
3547 (insert (js2-make-pad i))
3548 (js2-print-ast (js2-call-node-target n) 0)
3549 (insert "(")
3550 (js2-print-list (js2-call-node-args n))
3551 (insert ")"))
3552
3553 (defstruct (js2-yield-node
3554 (:include js2-node)
3555 (:constructor nil)
3556 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3557 (pos js2-ts-cursor)
3558 len value)))
3559 "AST node for yield statement or expression."
3560 value) ; optional: value to be yielded
3561
3562 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3563 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3564
3565 (defun js2-visit-yield-node (n v)
3566 (js2-visit-ast (js2-yield-node-value n) v))
3567
3568 (defun js2-print-yield-node (n i)
3569 (insert (js2-make-pad i))
3570 (insert "yield")
3571 (when (js2-yield-node-value n)
3572 (insert " ")
3573 (js2-print-ast (js2-yield-node-value n) 0)))
3574
3575 (defstruct (js2-paren-node
3576 (:include js2-node)
3577 (:constructor nil)
3578 (:constructor make-js2-paren-node (&key (type js2-LP)
3579 (pos js2-ts-cursor)
3580 len expr)))
3581 "AST node for a parenthesized expression.
3582 In particular, used when the parens are syntactically optional,
3583 as opposed to required parens such as those enclosing an if-conditional."
3584 expr) ; `js2-node'
3585
3586 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3587 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3588
3589 (defun js2-visit-paren-node (n v)
3590 (js2-visit-ast (js2-paren-node-expr n) v))
3591
3592 (defun js2-print-paren-node (n i)
3593 (insert (js2-make-pad i))
3594 (insert "(")
3595 (js2-print-ast (js2-paren-node-expr n) 0)
3596 (insert ")"))
3597
3598 (defstruct (js2-array-comp-node
3599 (:include js2-scope)
3600 (:constructor nil)
3601 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3602 (pos js2-ts-cursor)
3603 len result
3604 loops filter
3605 if-pos lp rp)))
3606 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3607 result ; result expression (just after left-bracket)
3608 loops ; a Lisp list of `js2-array-comp-loop-node'
3609 filter ; guard/filter expression
3610 if-pos ; buffer pos of 'if' keyword, if present, else nil
3611 lp ; buffer position of if-guard left-paren, or nil if not present
3612 rp) ; buffer position of if-guard right-paren, or nil if not present
3613
3614 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3615 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3616
3617 (defun js2-visit-array-comp-node (n v)
3618 (js2-visit-ast (js2-array-comp-node-result n) v)
3619 (dolist (l (js2-array-comp-node-loops n))
3620 (js2-visit-ast l v))
3621 (js2-visit-ast (js2-array-comp-node-filter n) v))
3622
3623 (defun js2-print-array-comp-node (n i)
3624 (let ((pad (js2-make-pad i))
3625 (result (js2-array-comp-node-result n))
3626 (loops (js2-array-comp-node-loops n))
3627 (filter (js2-array-comp-node-filter n)))
3628 (insert pad "[")
3629 (js2-print-ast result 0)
3630 (dolist (l loops)
3631 (insert " ")
3632 (js2-print-ast l 0))
3633 (when filter
3634 (insert " if (")
3635 (js2-print-ast filter 0)
3636 (insert ")"))
3637 (insert "]")))
3638
3639 (defstruct (js2-array-comp-loop-node
3640 (:include js2-for-in-node)
3641 (:constructor nil)
3642 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3643 (pos js2-ts-cursor)
3644 len iterator
3645 object in-pos
3646 foreach-p
3647 each-pos
3648 forof-p
3649 lp rp)))
3650 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3651
3652 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3653 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3654
3655 (defun js2-visit-array-comp-loop (n v)
3656 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3657 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3658
3659 (defun js2-print-array-comp-loop (n i)
3660 (insert "for ")
3661 (when (js2-array-comp-loop-node-foreach-p n) (insert "each "))
3662 (insert "(")
3663 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3664 (if (js2-array-comp-loop-node-forof-p n)
3665 (insert " of ")
3666 (insert " in "))
3667 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3668 (insert ")"))
3669
3670 (defstruct (js2-empty-expr-node
3671 (:include js2-node)
3672 (:constructor nil)
3673 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3674 (pos js2-token-beg)
3675 len)))
3676 "AST node for an empty expression.")
3677
3678 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3679 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3680
3681 (defstruct (js2-xml-node
3682 (:include js2-block-node)
3683 (:constructor nil)
3684 (:constructor make-js2-xml-node (&key (type js2-XML)
3685 (pos js2-token-beg)
3686 len kids)))
3687 "AST node for initial parse of E4X literals.
3688 The kids field is a list of XML fragments, each a `js2-string-node' or
3689 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3690
3691 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3692 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3693
3694 (defun js2-print-xml-node (n i)
3695 (dolist (kid (js2-xml-node-kids n))
3696 (js2-print-ast kid i)))
3697
3698 (defstruct (js2-xml-js-expr-node
3699 (:include js2-xml-node)
3700 (:constructor nil)
3701 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3702 (pos js2-ts-cursor)
3703 len expr)))
3704 "AST node for an embedded JavaScript {expression} in an E4X literal.
3705 The start and end fields correspond to the curly-braces."
3706 expr) ; a `js2-expr-node' of some sort
3707
3708 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3709 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3710
3711 (defun js2-visit-xml-js-expr (n v)
3712 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3713
3714 (defun js2-print-xml-js-expr (n i)
3715 (insert (js2-make-pad i))
3716 (insert "{")
3717 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3718 (insert "}"))
3719
3720 (defstruct (js2-xml-dot-query-node
3721 (:include js2-infix-node)
3722 (:constructor nil)
3723 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3724 (pos js2-ts-cursor)
3725 op-pos len left
3726 right rp)))
3727 "AST node for an E4X foo.(bar) filter expression.
3728 Note that the left-paren is automatically the character immediately
3729 following the dot (.) in the operator. No whitespace is permitted
3730 between the dot and the lp by the scanner."
3731 rp)
3732
3733 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3734 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3735
3736 (defun js2-print-xml-dot-query (n i)
3737 (insert (js2-make-pad i))
3738 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3739 (insert ".(")
3740 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3741 (insert ")"))
3742
3743 (defstruct (js2-xml-ref-node
3744 (:include js2-node)
3745 (:constructor nil)) ; abstract
3746 "Base type for E4X XML attribute-access or property-get expressions.
3747 Such expressions can take a variety of forms. The general syntax has
3748 three parts:
3749
3750 - (optional) an @ (specifying an attribute access)
3751 - (optional) a namespace (a `js2-name-node') and double-colon
3752 - (required) either a `js2-name-node' or a bracketed [expression]
3753
3754 The property-name expressions (examples: ns::name, @name) are
3755 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3756 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3757
3758 This node type (or more specifically, its subclasses) will sometimes
3759 be the right-hand child of a `js2-prop-get-node' or a
3760 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3761 The `js2-xml-ref-node' may also be a standalone primary expression with
3762 no explicit target, which is valid in certain expression contexts such as
3763
3764 company..employee.(@id < 100)
3765
3766 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3767 expression whose parent is a `js2-xml-dot-query-node'."
3768 namespace
3769 at-pos
3770 colon-pos)
3771
3772 (defsubst js2-xml-ref-node-attr-access-p (node)
3773 "Return non-nil if this expression began with an @-token."
3774 (and (numberp (js2-xml-ref-node-at-pos node))
3775 (plusp (js2-xml-ref-node-at-pos node))))
3776
3777 (defstruct (js2-xml-prop-ref-node
3778 (:include js2-xml-ref-node)
3779 (:constructor nil)
3780 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3781 (pos js2-token-beg)
3782 len propname
3783 namespace at-pos
3784 colon-pos)))
3785 "AST node for an E4X XML [expr] property-ref expression.
3786 The JavaScript syntax is an optional @, an optional ns::, and a name.
3787
3788 [ '@' ] [ name '::' ] name
3789
3790 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3791 @ns::*, @*::attr, @*::*, and @*.
3792
3793 The node starts at the @ token, if present. Otherwise it starts at the
3794 namespace name. The node bounds extend through the closing right-bracket,
3795 or if it is missing due to a syntax error, through the end of the index
3796 expression."
3797 propname)
3798
3799 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3800 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3801
3802 (defun js2-visit-xml-prop-ref-node (n v)
3803 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3804 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3805
3806 (defun js2-print-xml-prop-ref-node (n i)
3807 (insert (js2-make-pad i))
3808 (if (js2-xml-ref-node-attr-access-p n)
3809 (insert "@"))
3810 (when (js2-xml-prop-ref-node-namespace n)
3811 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3812 (insert "::"))
3813 (if (js2-xml-prop-ref-node-propname n)
3814 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3815
3816 (defstruct (js2-xml-elem-ref-node
3817 (:include js2-xml-ref-node)
3818 (:constructor nil)
3819 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3820 (pos js2-token-beg)
3821 len expr lb rb
3822 namespace at-pos
3823 colon-pos)))
3824 "AST node for an E4X XML [expr] member-ref expression.
3825 Syntax:
3826
3827 [ '@' ] [ name '::' ] '[' expr ']'
3828
3829 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3830
3831 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3832 is not a legal E4X XML element-ref expression, since it's already used
3833 for standard JavaScript element-get array indexing. Hence, a
3834 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3835 non-nil namespace node, or both.
3836
3837 The node starts at the @ token, if present. Otherwise it starts
3838 at the namespace name. The node bounds extend through the closing
3839 right-bracket, or if it is missing due to a syntax error, through the
3840 end of the index expression."
3841 expr ; the bracketed index expression
3842 lb
3843 rb)
3844
3845 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3846 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3847
3848 (defun js2-visit-xml-elem-ref-node (n v)
3849 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3850 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3851
3852 (defun js2-print-xml-elem-ref-node (n i)
3853 (insert (js2-make-pad i))
3854 (if (js2-xml-ref-node-attr-access-p n)
3855 (insert "@"))
3856 (when (js2-xml-elem-ref-node-namespace n)
3857 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3858 (insert "::"))
3859 (insert "[")
3860 (if (js2-xml-elem-ref-node-expr n)
3861 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3862 (insert "]"))
3863
3864 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3865
3866 (defstruct (js2-xml-start-tag-node
3867 (:include js2-xml-node)
3868 (:constructor nil)
3869 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3870 (pos js2-ts-cursor)
3871 len name attrs kids
3872 empty-p)))
3873 "AST node for an XML start-tag. Not currently used.
3874 The `kids' field is a Lisp list of child content nodes."
3875 name ; a `js2-xml-name-node'
3876 attrs ; a Lisp list of `js2-xml-attr-node'
3877 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3878
3879 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3880 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3881
3882 (defun js2-visit-xml-start-tag (n v)
3883 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3884 (dolist (attr (js2-xml-start-tag-node-attrs n))
3885 (js2-visit-ast attr v))
3886 (js2-visit-block n v))
3887
3888 (defun js2-print-xml-start-tag (n i)
3889 (insert (js2-make-pad i) "<")
3890 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3891 (when (js2-xml-start-tag-node-attrs n)
3892 (insert " ")
3893 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3894 (insert ">"))
3895
3896 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3897 ;; and add the end-tag to the kids list of the parent as well.
3898 (defstruct (js2-xml-end-tag-node
3899 (:include js2-xml-node)
3900 (:constructor nil)
3901 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
3902 (pos js2-ts-cursor)
3903 len name)))
3904 "AST node for an XML end-tag. Not currently used."
3905 name) ; a `js2-xml-name-node'
3906
3907 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
3908 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
3909
3910 (defun js2-visit-xml-end-tag (n v)
3911 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
3912
3913 (defun js2-print-xml-end-tag (n i)
3914 (insert (js2-make-pad i))
3915 (insert "</")
3916 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
3917 (insert ">"))
3918
3919 (defstruct (js2-xml-name-node
3920 (:include js2-xml-node)
3921 (:constructor nil)
3922 (:constructor make-js2-xml-name-node (&key (type js2-XML)
3923 (pos js2-ts-cursor)
3924 len namespace kids)))
3925 "AST node for an E4X XML name. Not currently used.
3926 Any XML name can be qualified with a namespace, hence the namespace field.
3927 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
3928 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
3929 For a simple name, the kids list has exactly one node, a `js2-name-node'."
3930 namespace) ; a `js2-string-node'
3931
3932 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
3933 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
3934
3935 (defun js2-visit-xml-name-node (n v)
3936 (js2-visit-ast (js2-xml-name-node-namespace n) v))
3937
3938 (defun js2-print-xml-name-node (n i)
3939 (insert (js2-make-pad i))
3940 (when (js2-xml-name-node-namespace n)
3941 (js2-print-ast (js2-xml-name-node-namespace n) 0)
3942 (insert "::"))
3943 (dolist (kid (js2-xml-name-node-kids n))
3944 (js2-print-ast kid 0)))
3945
3946 (defstruct (js2-xml-pi-node
3947 (:include js2-xml-node)
3948 (:constructor nil)
3949 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
3950 (pos js2-ts-cursor)
3951 len name attrs)))
3952 "AST node for an E4X XML processing instruction. Not currently used."
3953 name ; a `js2-xml-name-node'
3954 attrs) ; a list of `js2-xml-attr-node'
3955
3956 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
3957 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
3958
3959 (defun js2-visit-xml-pi-node (n v)
3960 (js2-visit-ast (js2-xml-pi-node-name n) v)
3961 (dolist (attr (js2-xml-pi-node-attrs n))
3962 (js2-visit-ast attr v)))
3963
3964 (defun js2-print-xml-pi-node (n i)
3965 (insert (js2-make-pad i) "<?")
3966 (js2-print-ast (js2-xml-pi-node-name n))
3967 (when (js2-xml-pi-node-attrs n)
3968 (insert " ")
3969 (js2-print-list (js2-xml-pi-node-attrs n)))
3970 (insert "?>"))
3971
3972 (defstruct (js2-xml-cdata-node
3973 (:include js2-xml-node)
3974 (:constructor nil)
3975 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
3976 (pos js2-ts-cursor)
3977 len content)))
3978 "AST node for a CDATA escape section. Not currently used."
3979 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
3980
3981 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
3982 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
3983
3984 (defun js2-visit-xml-cdata-node (n v)
3985 (js2-visit-ast (js2-xml-cdata-node-content n) v))
3986
3987 (defun js2-print-xml-cdata-node (n i)
3988 (insert (js2-make-pad i))
3989 (js2-print-ast (js2-xml-cdata-node-content n)))
3990
3991 (defstruct (js2-xml-attr-node
3992 (:include js2-xml-node)
3993 (:constructor nil)
3994 (:constructor make-js2-attr-node (&key (type js2-XML)
3995 (pos js2-ts-cursor)
3996 len name value
3997 eq-pos quote-type)))
3998 "AST node representing a foo='bar' XML attribute value. Not yet used."
3999 name ; a `js2-xml-name-node'
4000 value ; a `js2-xml-name-node'
4001 eq-pos ; buffer position of "=" sign
4002 quote-type) ; 'single or 'double
4003
4004 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4005 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4006
4007 (defun js2-visit-xml-attr-node (n v)
4008 (js2-visit-ast (js2-xml-attr-node-name n) v)
4009 (js2-visit-ast (js2-xml-attr-node-value n) v))
4010
4011 (defun js2-print-xml-attr-node (n i)
4012 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4013 "'"
4014 "\"")))
4015 (insert (js2-make-pad i))
4016 (js2-print-ast (js2-xml-attr-node-name n) 0)
4017 (insert "=" quote)
4018 (js2-print-ast (js2-xml-attr-node-value n) 0)
4019 (insert quote)))
4020
4021 (defstruct (js2-xml-text-node
4022 (:include js2-xml-node)
4023 (:constructor nil)
4024 (:constructor make-js2-text-node (&key (type js2-XML)
4025 (pos js2-ts-cursor)
4026 len content)))
4027 "AST node for an E4X XML text node. Not currently used."
4028 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4029
4030 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4031 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4032
4033 (defun js2-visit-xml-text-node (n v)
4034 (js2-visit-ast (js2-xml-text-node-content n) v))
4035
4036 (defun js2-print-xml-text-node (n i)
4037 (insert (js2-make-pad i))
4038 (dolist (kid (js2-xml-text-node-content n))
4039 (js2-print-ast kid)))
4040
4041 (defstruct (js2-xml-comment-node
4042 (:include js2-xml-node)
4043 (:constructor nil)
4044 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4045 (pos js2-ts-cursor)
4046 len)))
4047 "AST node for E4X XML comment. Not currently used.")
4048
4049 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4050 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4051
4052 (defun js2-print-xml-comment (n i)
4053 (insert (js2-make-pad i)
4054 (js2-node-string n)))
4055
4056 ;;; Node utilities
4057
4058 (defsubst js2-node-line (n)
4059 "Fetch the source line number at the start of node N.
4060 This is O(n) in the length of the source buffer; use prudently."
4061 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4062
4063 (defsubst js2-block-node-kid (n i)
4064 "Return child I of node N, or nil if there aren't that many."
4065 (nth i (js2-block-node-kids n)))
4066
4067 (defsubst js2-block-node-first (n)
4068 "Return first child of block node N, or nil if there is none."
4069 (first (js2-block-node-kids n)))
4070
4071 (defun js2-node-root (n)
4072 "Return the root of the AST containing N.
4073 If N has no parent pointer, returns N."
4074 (let ((parent (js2-node-parent n)))
4075 (if parent
4076 (js2-node-root parent)
4077 n)))
4078
4079 (defsubst js2-node-short-name (n)
4080 "Return the short name of node N as a string, e.g. `js2-if-node'."
4081 (substring (symbol-name (aref n 0))
4082 (length "cl-struct-")))
4083
4084 (defun js2-node-child-list (node)
4085 "Return the child list for NODE, a Lisp list of nodes.
4086 Works for block nodes, array nodes, obj literals, funarg lists,
4087 var decls and try nodes (for catch clauses). Note that you should call
4088 `js2-block-node-kids' on the function body for the body statements.
4089 Returns nil for zero-length child lists or unsupported nodes."
4090 (cond
4091 ((js2-function-node-p node)
4092 (js2-function-node-params node))
4093 ((js2-block-node-p node)
4094 (js2-block-node-kids node))
4095 ((js2-try-node-p node)
4096 (js2-try-node-catch-clauses node))
4097 ((js2-array-node-p node)
4098 (js2-array-node-elems node))
4099 ((js2-object-node-p node)
4100 (js2-object-node-elems node))
4101 ((js2-call-node-p node)
4102 (js2-call-node-args node))
4103 ((js2-new-node-p node)
4104 (js2-new-node-args node))
4105 ((js2-var-decl-node-p node)
4106 (js2-var-decl-node-kids node))
4107 (t
4108 nil)))
4109
4110 (defun js2-node-set-child-list (node kids)
4111 "Set the child list for NODE to KIDS."
4112 (cond
4113 ((js2-function-node-p node)
4114 (setf (js2-function-node-params node) kids))
4115 ((js2-block-node-p node)
4116 (setf (js2-block-node-kids node) kids))
4117 ((js2-try-node-p node)
4118 (setf (js2-try-node-catch-clauses node) kids))
4119 ((js2-array-node-p node)
4120 (setf (js2-array-node-elems node) kids))
4121 ((js2-object-node-p node)
4122 (setf (js2-object-node-elems node) kids))
4123 ((js2-call-node-p node)
4124 (setf (js2-call-node-args node) kids))
4125 ((js2-new-node-p node)
4126 (setf (js2-new-node-args node) kids))
4127 ((js2-var-decl-node-p node)
4128 (setf (js2-var-decl-node-kids node) kids))
4129 (t
4130 (error "Unsupported node type: %s" (js2-node-short-name node))))
4131 kids)
4132
4133 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4134 (defconst js2-paren-expr-nodes
4135 '(cl-struct-js2-array-comp-loop-node
4136 cl-struct-js2-array-comp-node
4137 cl-struct-js2-call-node
4138 cl-struct-js2-catch-node
4139 cl-struct-js2-do-node
4140 cl-struct-js2-elem-get-node
4141 cl-struct-js2-for-in-node
4142 cl-struct-js2-for-node
4143 cl-struct-js2-function-node
4144 cl-struct-js2-if-node
4145 cl-struct-js2-let-node
4146 cl-struct-js2-new-node
4147 cl-struct-js2-paren-node
4148 cl-struct-js2-switch-node
4149 cl-struct-js2-while-node
4150 cl-struct-js2-with-node
4151 cl-struct-js2-xml-dot-query-node)
4152 "Node types that can have a parenthesized child expression.
4153 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4154
4155 (defsubst js2-paren-expr-node-p (node)
4156 "Return t for nodes that typically have a parenthesized child expression.
4157 Useful for computing the indentation anchors for arg-lists and conditions.
4158 Note that it may return a false positive, for instance when NODE is
4159 a `js2-new-node' and there are no arguments or parentheses."
4160 (memq (aref node 0) js2-paren-expr-nodes))
4161
4162 ;; Fake polymorphism... yech.
4163 (defun js2-node-lp (node)
4164 "Return relative left-paren position for NODE, if applicable.
4165 For `js2-elem-get-node' structs, returns left-bracket position.
4166 Note that the position may be nil in the case of a parse error."
4167 (cond
4168 ((js2-elem-get-node-p node)
4169 (js2-elem-get-node-lb node))
4170 ((js2-loop-node-p node)
4171 (js2-loop-node-lp node))
4172 ((js2-function-node-p node)
4173 (js2-function-node-lp node))
4174 ((js2-if-node-p node)
4175 (js2-if-node-lp node))
4176 ((js2-new-node-p node)
4177 (js2-new-node-lp node))
4178 ((js2-call-node-p node)
4179 (js2-call-node-lp node))
4180 ((js2-paren-node-p node)
4181 0)
4182 ((js2-switch-node-p node)
4183 (js2-switch-node-lp node))
4184 ((js2-catch-node-p node)
4185 (js2-catch-node-lp node))
4186 ((js2-let-node-p node)
4187 (js2-let-node-lp node))
4188 ((js2-array-comp-node-p node)
4189 (js2-array-comp-node-lp node))
4190 ((js2-with-node-p node)
4191 (js2-with-node-lp node))
4192 ((js2-xml-dot-query-node-p node)
4193 (1+ (js2-infix-node-op-pos node)))
4194 (t
4195 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4196
4197 ;; Fake polymorphism... blech.
4198 (defun js2-node-rp (node)
4199 "Return relative right-paren position for NODE, if applicable.
4200 For `js2-elem-get-node' structs, returns right-bracket position.
4201 Note that the position may be nil in the case of a parse error."
4202 (cond
4203 ((js2-elem-get-node-p node)
4204 (js2-elem-get-node-rb node))
4205 ((js2-loop-node-p node)
4206 (js2-loop-node-rp node))
4207 ((js2-function-node-p node)
4208 (js2-function-node-rp node))
4209 ((js2-if-node-p node)
4210 (js2-if-node-rp node))
4211 ((js2-new-node-p node)
4212 (js2-new-node-rp node))
4213 ((js2-call-node-p node)
4214 (js2-call-node-rp node))
4215 ((js2-paren-node-p node)
4216 (1- (js2-node-len node)))
4217 ((js2-switch-node-p node)
4218 (js2-switch-node-rp node))
4219 ((js2-catch-node-p node)
4220 (js2-catch-node-rp node))
4221 ((js2-let-node-p node)
4222 (js2-let-node-rp node))
4223 ((js2-array-comp-node-p node)
4224 (js2-array-comp-node-rp node))
4225 ((js2-with-node-p node)
4226 (js2-with-node-rp node))
4227 ((js2-xml-dot-query-node-p node)
4228 (1+ (js2-xml-dot-query-node-rp node)))
4229 (t
4230 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4231
4232 (defsubst js2-node-first-child (node)
4233 "Return the first element of `js2-node-child-list' for NODE."
4234 (car (js2-node-child-list node)))
4235
4236 (defsubst js2-node-last-child (node)
4237 "Return the last element of `js2-node-last-child' for NODE."
4238 (car (last (js2-node-child-list node))))
4239
4240 (defun js2-node-prev-sibling (node)
4241 "Return the previous statement in parent.
4242 Works for parents supported by `js2-node-child-list'.
4243 Returns nil if NODE is not in the parent, or PARENT is
4244 not a supported node, or if NODE is the first child."
4245 (let* ((p (js2-node-parent node))
4246 (kids (js2-node-child-list p))
4247 (sib (car kids)))
4248 (while (and kids
4249 (not (eq node (cadr kids))))
4250 (setq kids (cdr kids)
4251 sib (car kids)))
4252 sib))
4253
4254 (defun js2-node-next-sibling (node)
4255 "Return the next statement in parent block.
4256 Returns nil if NODE is not in the block, or PARENT is not
4257 a block node, or if NODE is the last statement."
4258 (let* ((p (js2-node-parent node))
4259 (kids (js2-node-child-list p)))
4260 (while (and kids
4261 (not (eq node (car kids))))
4262 (setq kids (cdr kids)))
4263 (cadr kids)))
4264
4265 (defun js2-node-find-child-before (pos parent &optional after)
4266 "Find the last child that starts before POS in parent.
4267 If AFTER is non-nil, returns first child starting after POS.
4268 POS is an absolute buffer position. PARENT is any node
4269 supported by `js2-node-child-list'.
4270 Returns nil if no applicable child is found."
4271 (let ((kids (if (js2-function-node-p parent)
4272 (js2-block-node-kids (js2-function-node-body parent))
4273 (js2-node-child-list parent)))
4274 (beg (if (js2-function-node-p parent)
4275 (js2-node-abs-pos (js2-function-node-body parent))
4276 (js2-node-abs-pos parent)))
4277 kid result fn
4278 (continue t))
4279 (setq fn (if after '>= '<))
4280 (while (and kids continue)
4281 (setq kid (car kids))
4282 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4283 (setq result kid
4284 continue (if after nil t))
4285 (setq continue (if after t nil)))
4286 (setq kids (cdr kids)))
4287 result))
4288
4289 (defun js2-node-find-child-after (pos parent)
4290 "Find first child that starts after POS in parent.
4291 POS is an absolute buffer position. PARENT is any node
4292 supported by `js2-node-child-list'.
4293 Returns nil if no applicable child is found."
4294 (js2-node-find-child-before pos parent 'after))
4295
4296 (defun js2-node-replace-child (pos parent new-node)
4297 "Replace node at index POS in PARENT with NEW-NODE.
4298 Only works for parents supported by `js2-node-child-list'."
4299 (let ((kids (js2-node-child-list parent))
4300 (i 0))
4301 (while (< i pos)
4302 (setq kids (cdr kids)
4303 i (1+ i)))
4304 (setcar kids new-node)
4305 (js2-node-add-children parent new-node)))
4306
4307 (defun js2-node-buffer (n)
4308 "Return the buffer associated with AST N.
4309 Returns nil if the buffer is not set as a property on the root
4310 node, or if parent links were not recorded during parsing."
4311 (let ((root (js2-node-root n)))
4312 (and root
4313 (js2-ast-root-p root)
4314 (js2-ast-root-buffer root))))
4315
4316 (defun js2-block-node-push (n kid)
4317 "Push js2-node KID onto the end of js2-block-node N's child list.
4318 KID is always added to the -end- of the kids list.
4319 Function also calls `js2-node-add-children' to add the parent link."
4320 (let ((kids (js2-node-child-list n)))
4321 (if kids
4322 (setcdr kids (nconc (cdr kids) (list kid)))
4323 (js2-node-set-child-list n (list kid)))
4324 (js2-node-add-children n kid)))
4325
4326 (defun js2-node-string (node)
4327 (with-current-buffer (or (js2-node-buffer node)
4328 (error "No buffer available for node %s" node))
4329 (let ((pos (js2-node-abs-pos node)))
4330 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4331
4332 ;; Container for storing the node we're looking for in a traversal.
4333 (js2-deflocal js2-discovered-node nil)
4334
4335 ;; Keep track of absolute node position during traversals.
4336 (js2-deflocal js2-visitor-offset nil)
4337
4338 (js2-deflocal js2-node-search-point nil)
4339
4340 (when js2-mode-dev-mode-p
4341 (defun js2-find-node-at-point ()
4342 (interactive)
4343 (let ((node (js2-node-at-point)))
4344 (message "%s" (or node "No node found at point"))))
4345 (defun js2-node-name-at-point ()
4346 (interactive)
4347 (let ((node (js2-node-at-point)))
4348 (message "%s" (if node
4349 (js2-node-short-name node)
4350 "No node found at point.")))))
4351
4352 (defun js2-node-at-point (&optional pos skip-comments)
4353 "Return AST node at POS, a buffer position, defaulting to current point.
4354 The `js2-mode-ast' variable must be set to the current parse tree.
4355 Signals an error if the AST (`js2-mode-ast') is nil.
4356 Always returns a node - if it can't find one, it returns the root.
4357 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4358 (let ((ast js2-mode-ast)
4359 result)
4360 (unless ast
4361 (error "No JavaScript AST available"))
4362 ;; Look through comments first, since they may be inside nodes that
4363 ;; would otherwise report a match.
4364 (setq pos (or pos (point))
4365 result (if (> pos (js2-node-abs-end ast))
4366 ast
4367 (if (not skip-comments)
4368 (js2-comment-at-point pos))))
4369 (unless result
4370 (setq js2-discovered-node nil
4371 js2-visitor-offset 0
4372 js2-node-search-point pos)
4373 (unwind-protect
4374 (catch 'js2-visit-done
4375 (js2-visit-ast ast #'js2-node-at-point-visitor))
4376 (setq js2-visitor-offset nil
4377 js2-node-search-point nil))
4378 (setq result js2-discovered-node))
4379 ;; may have found a comment beyond end of last child node,
4380 ;; since visiting the ast-root looks at the comment-list last.
4381 (if (and skip-comments
4382 (js2-comment-node-p result))
4383 (setq result nil))
4384 (or result js2-mode-ast)))
4385
4386 (defun js2-node-at-point-visitor (node end-p)
4387 (let ((rel-pos (js2-node-pos node))
4388 abs-pos
4389 abs-end
4390 (point js2-node-search-point))
4391 (cond
4392 (end-p
4393 ;; this evaluates to a non-nil return value, even if it's zero
4394 (decf js2-visitor-offset rel-pos))
4395 ;; we already looked for comments before visiting, and don't want them now
4396 ((js2-comment-node-p node)
4397 nil)
4398 (t
4399 (setq abs-pos (incf js2-visitor-offset rel-pos)
4400 ;; we only want to use the node if the point is before
4401 ;; the last character position in the node, so we decrement
4402 ;; the absolute end by 1.
4403 abs-end (+ abs-pos (js2-node-len node) -1))
4404 (cond
4405 ;; If this node starts after search-point, stop the search.
4406 ((> abs-pos point)
4407 (throw 'js2-visit-done nil))
4408 ;; If this node ends before the search-point, don't check kids.
4409 ((> point abs-end)
4410 nil)
4411 (t
4412 ;; Otherwise point is within this node, possibly in a child.
4413 (setq js2-discovered-node node)
4414 t)))))) ; keep processing kids to look for more specific match
4415
4416 (defsubst js2-block-comment-p (node)
4417 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4418 (and (js2-comment-node-p node)
4419 (memq (js2-comment-node-format node) '(jsdoc block))))
4420
4421 ;; TODO: put the comments in a vector and binary-search them instead
4422 (defun js2-comment-at-point (&optional pos)
4423 "Look through scanned comment nodes for one containing POS.
4424 POS is a buffer position that defaults to current point.
4425 Function returns nil if POS was not in any comment node."
4426 (let ((ast js2-mode-ast)
4427 (x (or pos (point)))
4428 beg end)
4429 (unless ast
4430 (error "No JavaScript AST available"))
4431 (catch 'done
4432 ;; Comments are stored in lexical order.
4433 (dolist (comment (js2-ast-root-comments ast) nil)
4434 (setq beg (js2-node-abs-pos comment)
4435 end (+ beg (js2-node-len comment)))
4436 (if (and (>= x beg)
4437 (<= x end))
4438 (throw 'done comment))))))
4439
4440 (defun js2-mode-find-parent-fn (node)
4441 "Find function enclosing NODE.
4442 Returns nil if NODE is not inside a function."
4443 (setq node (js2-node-parent node))
4444 (while (and node (not (js2-function-node-p node)))
4445 (setq node (js2-node-parent node)))
4446 (and (js2-function-node-p node) node))
4447
4448 (defun js2-mode-find-enclosing-fn (node)
4449 "Find function or root enclosing NODE."
4450 (if (js2-ast-root-p node)
4451 node
4452 (setq node (js2-node-parent node))
4453 (while (not (or (js2-ast-root-p node)
4454 (js2-function-node-p node)))
4455 (setq node (js2-node-parent node)))
4456 node))
4457
4458 (defun js2-mode-find-enclosing-node (beg end)
4459 "Find script or function fully enclosing BEG and END."
4460 (let ((node (js2-node-at-point beg))
4461 pos
4462 (continue t))
4463 (while continue
4464 (if (or (js2-ast-root-p node)
4465 (and (js2-function-node-p node)
4466 (<= (setq pos (js2-node-abs-pos node)) beg)
4467 (>= (+ pos (js2-node-len node)) end)))
4468 (setq continue nil)
4469 (setq node (js2-node-parent node))))
4470 node))
4471
4472 (defun js2-node-parent-script-or-fn (node)
4473 "Find script or function immediately enclosing NODE.
4474 If NODE is the ast-root, returns nil."
4475 (if (js2-ast-root-p node)
4476 nil
4477 (setq node (js2-node-parent node))
4478 (while (and node (not (or (js2-function-node-p node)
4479 (js2-script-node-p node))))
4480 (setq node (js2-node-parent node)))
4481 node))
4482
4483 (defun js2-node-is-descendant (node ancestor)
4484 "Return t if NODE is a descendant of ANCESTOR."
4485 (while (and node
4486 (not (eq node ancestor)))
4487 (setq node (js2-node-parent node)))
4488 node)
4489
4490 ;;; visitor infrastructure
4491
4492 (defun js2-visit-none (node callback)
4493 "Visitor for AST node that have no node children."
4494 nil)
4495
4496 (defun js2-print-none (node indent)
4497 "Visitor for AST node with no printed representation.")
4498
4499 (defun js2-print-body (node indent)
4500 "Print a statement, or a block without braces."
4501 (if (js2-block-node-p node)
4502 (dolist (kid (js2-block-node-kids node))
4503 (js2-print-ast kid indent))
4504 (js2-print-ast node indent)))
4505
4506 (defun js2-print-list (args &optional delimiter)
4507 (loop with len = (length args)
4508 for arg in args
4509 for count from 1
4510 do
4511 (when arg (js2-print-ast arg 0))
4512 (if (< count len)
4513 (insert (or delimiter ", ")))))
4514
4515 (defun js2-print-tree (ast)
4516 "Prints an AST to the current buffer.
4517 Makes `js2-ast-parent-nodes' available to the printer functions."
4518 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4519 (js2-print-ast ast)))
4520
4521 (defun js2-print-ast (node &optional indent)
4522 "Helper function for printing AST nodes.
4523 Requires `js2-ast-parent-nodes' to be non-nil.
4524 You should use `js2-print-tree' instead of this function."
4525 (let ((printer (get (aref node 0) 'js2-printer))
4526 (i (or indent 0))
4527 (pos (js2-node-abs-pos node)))
4528 ;; TODO: wedge comments in here somewhere
4529 (if printer
4530 (funcall printer node i))))
4531
4532 (defconst js2-side-effecting-tokens
4533 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4534 (dolist (tt (list js2-ASSIGN
4535 js2-ASSIGN_ADD
4536 js2-ASSIGN_BITAND
4537 js2-ASSIGN_BITOR
4538 js2-ASSIGN_BITXOR
4539 js2-ASSIGN_DIV
4540 js2-ASSIGN_LSH
4541 js2-ASSIGN_MOD
4542 js2-ASSIGN_MUL
4543 js2-ASSIGN_RSH
4544 js2-ASSIGN_SUB
4545 js2-ASSIGN_URSH
4546 js2-BLOCK
4547 js2-BREAK
4548 js2-CALL
4549 js2-CATCH
4550 js2-CATCH_SCOPE
4551 js2-CONST
4552 js2-CONTINUE
4553 js2-DEBUGGER
4554 js2-DEC
4555 js2-DELPROP
4556 js2-DEL_REF
4557 js2-DO
4558 js2-ELSE
4559 js2-EMPTY
4560 js2-ENTERWITH
4561 js2-EXPORT
4562 js2-EXPR_RESULT
4563 js2-FINALLY
4564 js2-FOR
4565 js2-FUNCTION
4566 js2-GOTO
4567 js2-IF
4568 js2-IFEQ
4569 js2-IFNE
4570 js2-IMPORT
4571 js2-INC
4572 js2-JSR
4573 js2-LABEL
4574 js2-LEAVEWITH
4575 js2-LET
4576 js2-LETEXPR
4577 js2-LOCAL_BLOCK
4578 js2-LOOP
4579 js2-NEW
4580 js2-REF_CALL
4581 js2-RETHROW
4582 js2-RETURN
4583 js2-RETURN_RESULT
4584 js2-SEMI
4585 js2-SETELEM
4586 js2-SETELEM_OP
4587 js2-SETNAME
4588 js2-SETPROP
4589 js2-SETPROP_OP
4590 js2-SETVAR
4591 js2-SET_REF
4592 js2-SET_REF_OP
4593 js2-SWITCH
4594 js2-TARGET
4595 js2-THROW
4596 js2-TRY
4597 js2-VAR
4598 js2-WHILE
4599 js2-WITH
4600 js2-WITHEXPR
4601 js2-YIELD))
4602 (aset tokens tt t))
4603 (if js2-instanceof-has-side-effects
4604 (aset tokens js2-INSTANCEOF t))
4605 tokens))
4606
4607 (defun js2-node-has-side-effects (node)
4608 "Return t if NODE has side effects."
4609 (when node ; makes it easier to handle malformed expressions
4610 (let ((tt (js2-node-type node)))
4611 (cond
4612 ;; This doubtless needs some work, since EXPR_VOID is used
4613 ;; in several ways in Rhino and I may not have caught them all.
4614 ;; I'll wait for people to notice incorrect warnings.
4615 ((and (= tt js2-EXPR_VOID)
4616 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4617 (let ((expr (js2-expr-stmt-node-expr node)))
4618 (or (js2-node-has-side-effects expr)
4619 (when (js2-string-node-p expr)
4620 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4621 ((= tt js2-COMMA)
4622 (js2-node-has-side-effects (js2-infix-node-right node)))
4623 ((or (= tt js2-AND)
4624 (= tt js2-OR))
4625 (or (js2-node-has-side-effects (js2-infix-node-right node))
4626 (js2-node-has-side-effects (js2-infix-node-left node))))
4627 ((= tt js2-HOOK)
4628 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4629 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4630 ((js2-paren-node-p node)
4631 (js2-node-has-side-effects (js2-paren-node-expr node)))
4632 ((= tt js2-ERROR) ; avoid cascaded error messages
4633 nil)
4634 (t
4635 (aref js2-side-effecting-tokens tt))))))
4636
4637 (defconst js2-stmt-node-types
4638 (list js2-BLOCK
4639 js2-BREAK
4640 js2-CONTINUE
4641 js2-DEFAULT ; e4x "default xml namespace" statement
4642 js2-DO
4643 js2-EXPR_RESULT
4644 js2-EXPR_VOID
4645 js2-FOR
4646 js2-IF
4647 js2-RETURN
4648 js2-SWITCH
4649 js2-THROW
4650 js2-TRY
4651 js2-WHILE
4652 js2-WITH)
4653 "Node types that only appear in statement contexts.
4654 The list does not include nodes that always appear as the child
4655 of another specific statement type, such as switch-cases,
4656 catch and finally blocks, and else-clauses. The list also excludes
4657 nodes like yield, let and var, which may appear in either expression
4658 or statement context, and in the latter context always have a
4659 `js2-expr-stmt-node' parent. Finally, the list does not include
4660 functions or scripts, which are treated separately from statements
4661 by the JavaScript parser and runtime.")
4662
4663 (defun js2-stmt-node-p (node)
4664 "Heuristic for figuring out if NODE is a statement.
4665 Some node types can appear in either an expression context or a
4666 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4667 For these node types in a statement context, the parent will be a
4668 `js2-expr-stmt-node'.
4669 Functions aren't included in the check."
4670 (memq (js2-node-type node) js2-stmt-node-types))
4671
4672 (defun js2-mode-find-first-stmt (node)
4673 "Search upward starting from NODE looking for a statement.
4674 For purposes of this function, a `js2-function-node' counts."
4675 (while (not (or (js2-stmt-node-p node)
4676 (js2-function-node-p node)))
4677 (setq node (js2-node-parent node)))
4678 node)
4679
4680 (defun js2-node-parent-stmt (node)
4681 "Return the node's first ancestor that is a statement.
4682 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4683 appearing in a statement context will have a parent that is a
4684 `js2-expr-stmt-node' that will be returned by this function."
4685 (let ((parent (js2-node-parent node)))
4686 (if (or (null parent)
4687 (js2-stmt-node-p parent)
4688 (and (js2-function-node-p parent)
4689 (not (eq (js2-function-node-form parent)
4690 'FUNCTION_EXPRESSION))))
4691 parent
4692 (js2-node-parent-stmt parent))))
4693
4694 ;; In the Mozilla Rhino sources, Roshan James writes:
4695 ;; Does consistent-return analysis on the function body when strict mode is
4696 ;; enabled.
4697 ;;
4698 ;; function (x) { return (x+1) }
4699 ;;
4700 ;; is ok, but
4701 ;;
4702 ;; function (x) { if (x < 0) return (x+1); }
4703 ;;
4704 ;; is not because the function can potentially return a value when the
4705 ;; condition is satisfied and if not, the function does not explicitly
4706 ;; return a value.
4707 ;;
4708 ;; This extends to checking mismatches such as "return" and "return <value>"
4709 ;; used in the same function. Warnings are not emitted if inconsistent
4710 ;; returns exist in code that can be statically shown to be unreachable.
4711 ;; Ex.
4712 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4713 ;;
4714 ;; emits no warning. However if the loop had a break statement, then a
4715 ;; warning would be emitted.
4716 ;;
4717 ;; The consistency analysis looks at control structures such as loops, ifs,
4718 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4719 ;; warns the user about an inconsistent set of termination possibilities.
4720 ;;
4721 ;; These flags enumerate the possible ways a statement/function can
4722 ;; terminate. These flags are used by endCheck() and by the Parser to
4723 ;; detect inconsistent return usage.
4724 ;;
4725 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4726 ;; able to execute (example: throw, continue)
4727 ;;
4728 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4729 ;; next one. Statement such as return dont. A compound statement may have
4730 ;; some branch that drops off control to the next statement.
4731 ;;
4732 ;; END_RETURNS indicates that the statement can return with no value.
4733 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4734 ;;
4735 ;; A compound statement such as
4736 ;; if (condition) {
4737 ;; return value;
4738 ;; }
4739 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4740
4741 (defconst js2-END_UNREACHED 0)
4742 (defconst js2-END_DROPS_OFF 1)
4743 (defconst js2-END_RETURNS 2)
4744 (defconst js2-END_RETURNS_VALUE 4)
4745 (defconst js2-END_YIELDS 8)
4746
4747 (defun js2-has-consistent-return-usage (node)
4748 "Check that every return usage in a function body is consistent.
4749 Returns t if the function satisfies strict mode requirement."
4750 (let ((n (js2-end-check node)))
4751 ;; either it doesn't return a value in any branch...
4752 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4753 ;; or it returns a value (or is unreached) at every branch
4754 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4755 js2-END_RETURNS
4756 js2-END_YIELDS)))))
4757
4758 (defun js2-end-check-if (node)
4759 "Ensure that return usage in then/else blocks is consistent.
4760 If there is no else block, then the return statement can fall through.
4761 Returns logical OR of END_* flags"
4762 (let ((th (js2-if-node-then-part node))
4763 (el (js2-if-node-else-part node)))
4764 (if (null th)
4765 js2-END_UNREACHED
4766 (logior (js2-end-check th) (if el
4767 (js2-end-check el)
4768 js2-END_DROPS_OFF)))))
4769
4770 (defun js2-end-check-switch (node)
4771 "Consistency of return statements is checked between the case statements.
4772 If there is no default, then the switch can fall through. If there is a
4773 default, we check to see if all code paths in the default return or if
4774 there is a code path that can fall through.
4775 Returns logical OR of END_* flags."
4776 (let ((rv js2-END_UNREACHED)
4777 default-case)
4778 ;; examine the cases
4779 (catch 'break
4780 (dolist (c (js2-switch-node-cases node))
4781 (if (js2-case-node-expr c)
4782 (js2-set-flag rv (js2-end-check-block c))
4783 (setq default-case c)
4784 (throw 'break nil))))
4785 ;; we don't care how the cases drop into each other
4786 (js2-clear-flag rv js2-END_DROPS_OFF)
4787 ;; examine the default
4788 (js2-set-flag rv (if default-case
4789 (js2-end-check default-case)
4790 js2-END_DROPS_OFF))
4791 rv))
4792
4793 (defun js2-end-check-try (node)
4794 "If the block has a finally, return consistency is checked in the
4795 finally block. If all code paths in the finally return, then the
4796 returns in the try-catch blocks don't matter. If there is a code path
4797 that does not return or if there is no finally block, the returns
4798 of the try and catch blocks are checked for mismatch.
4799 Returns logical OR of END_* flags."
4800 (let ((finally (js2-try-node-finally-block node))
4801 rv)
4802 ;; check the finally if it exists
4803 (setq rv (if finally
4804 (js2-end-check (js2-finally-node-body finally))
4805 js2-END_DROPS_OFF))
4806 ;; If the finally block always returns, then none of the returns
4807 ;; in the try or catch blocks matter.
4808 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4809 (js2-clear-flag rv js2-END_DROPS_OFF)
4810 ;; examine the try block
4811 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4812 ;; check each catch block
4813 (dolist (cb (js2-try-node-catch-clauses node))
4814 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4815 rv))
4816
4817 (defun js2-end-check-loop (node)
4818 "Return statement in the loop body must be consistent.
4819 The default assumption for any kind of a loop is that it will eventually
4820 terminate. The only exception is a loop with a constant true condition.
4821 Code that follows such a loop is examined only if one can determine
4822 statically that there is a break out of the loop.
4823
4824 for(... ; ... ; ...) {}
4825 for(... in ... ) {}
4826 while(...) { }
4827 do { } while(...)
4828
4829 Returns logical OR of END_* flags."
4830 (let ((rv (js2-end-check (js2-loop-node-body node)))
4831 (condition (cond
4832 ((js2-while-node-p node)
4833 (js2-while-node-condition node))
4834 ((js2-do-node-p node)
4835 (js2-do-node-condition node))
4836 ((js2-for-node-p node)
4837 (js2-for-node-condition node)))))
4838
4839 ;; check to see if the loop condition is always true
4840 (if (and condition
4841 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4842 (js2-clear-flag rv js2-END_DROPS_OFF))
4843
4844 ;; look for effect of breaks
4845 (js2-set-flag rv (js2-node-get-prop node
4846 'CONTROL_BLOCK_PROP
4847 js2-END_UNREACHED))
4848 rv))
4849
4850 (defun js2-end-check-block (node)
4851 "A general block of code is examined statement by statement.
4852 If any statement (even a compound one) returns in all branches, then
4853 subsequent statements are not examined.
4854 Returns logical OR of END_* flags."
4855 (let* ((rv js2-END_DROPS_OFF)
4856 (kids (js2-block-node-kids node))
4857 (n (car kids)))
4858 ;; Check each statment. If the statement can continue onto the next
4859 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4860 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4861 (js2-clear-flag rv js2-END_DROPS_OFF)
4862 (js2-set-flag rv (js2-end-check n))
4863 (setq kids (cdr kids)
4864 n (car kids)))
4865 rv))
4866
4867 (defun js2-end-check-label (node)
4868 "A labeled statement implies that there may be a break to the label.
4869 The function processes the labeled statement and then checks the
4870 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4871 particular label.
4872 Returns logical OR of END_* flags."
4873 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4874 (logior rv (js2-node-get-prop node
4875 'CONTROL_BLOCK_PROP
4876 js2-END_UNREACHED))))
4877
4878 (defun js2-end-check-break (node)
4879 "When a break is encountered annotate the statement being broken
4880 out of by setting its CONTROL_BLOCK_PROP property.
4881 Returns logical OR of END_* flags."
4882 (and (js2-break-node-target node)
4883 (js2-node-set-prop (js2-break-node-target node)
4884 'CONTROL_BLOCK_PROP
4885 js2-END_DROPS_OFF))
4886 js2-END_UNREACHED)
4887
4888 (defun js2-end-check (node)
4889 "Examine the body of a function, doing a basic reachability analysis.
4890 Returns a combination of flags END_* flags that indicate
4891 how the function execution can terminate. These constitute only the
4892 pessimistic set of termination conditions. It is possible that at
4893 runtime certain code paths will never be actually taken. Hence this
4894 analysis will flag errors in cases where there may not be errors.
4895 Returns logical OR of END_* flags"
4896 (let (kid)
4897 (cond
4898 ((js2-break-node-p node)
4899 (js2-end-check-break node))
4900 ((js2-expr-stmt-node-p node)
4901 (if (setq kid (js2-expr-stmt-node-expr node))
4902 (js2-end-check kid)
4903 js2-END_DROPS_OFF))
4904 ((or (js2-continue-node-p node)
4905 (js2-throw-node-p node))
4906 js2-END_UNREACHED)
4907 ((js2-return-node-p node)
4908 (if (setq kid (js2-return-node-retval node))
4909 js2-END_RETURNS_VALUE
4910 js2-END_RETURNS))
4911 ((js2-loop-node-p node)
4912 (js2-end-check-loop node))
4913 ((js2-switch-node-p node)
4914 (js2-end-check-switch node))
4915 ((js2-labeled-stmt-node-p node)
4916 (js2-end-check-label node))
4917 ((js2-if-node-p node)
4918 (js2-end-check-if node))
4919 ((js2-try-node-p node)
4920 (js2-end-check-try node))
4921 ((js2-block-node-p node)
4922 (if (null (js2-block-node-kids node))
4923 js2-END_DROPS_OFF
4924 (js2-end-check-block node)))
4925 ((js2-yield-node-p node)
4926 js2-END_YIELDS)
4927 (t
4928 js2-END_DROPS_OFF))))
4929
4930 (defun js2-always-defined-boolean-p (node)
4931 "Check if NODE always evaluates to true or false in boolean context.
4932 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
4933 nor always false."
4934 (let ((tt (js2-node-type node))
4935 num)
4936 (cond
4937 ((or (= tt js2-FALSE) (= tt js2-NULL))
4938 'ALWAYS_FALSE)
4939 ((= tt js2-TRUE)
4940 'ALWAYS_TRUE)
4941 ((= tt js2-NUMBER)
4942 (setq num (js2-number-node-num-value node))
4943 (if (and (not (eq num 0.0e+NaN))
4944 (not (zerop num)))
4945 'ALWAYS_TRUE
4946 'ALWAYS_FALSE))
4947 (t
4948 nil))))
4949
4950 ;;; Scanner -- a port of Mozilla Rhino's lexer.
4951 ;; Corresponds to Rhino files Token.java and TokenStream.java.
4952
4953 (defvar js2-tokens nil
4954 "List of all defined token names.") ; initialized in `js2-token-names'
4955
4956 (defconst js2-token-names
4957 (let* ((names (make-vector js2-num-tokens -1))
4958 (case-fold-search nil) ; only match js2-UPPER_CASE
4959 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
4960 (loop for sym in syms
4961 for i from 0
4962 do
4963 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
4964 (not (boundp sym)))
4965 (aset names (symbol-value sym) ; code, e.g. 152
4966 (downcase
4967 (substring (symbol-name sym) 4))) ; name, e.g. "let"
4968 (push sym js2-tokens)))
4969 names)
4970 "Vector mapping int values to token string names, sans `js2-' prefix.")
4971
4972 (defun js2-token-name (tok)
4973 "Return a string name for TOK, a token symbol or code.
4974 Signals an error if it's not a recognized token."
4975 (let ((code tok))
4976 (if (symbolp tok)
4977 (setq code (symbol-value tok)))
4978 (if (eq code -1)
4979 "ERROR"
4980 (if (and (numberp code)
4981 (not (minusp code))
4982 (< code js2-num-tokens))
4983 (aref js2-token-names code)
4984 (error "Invalid token: %s" code)))))
4985
4986 (defsubst js2-token-sym (tok)
4987 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
4988 (intern (js2-token-name tok)))
4989
4990 (defconst js2-token-codes
4991 (let ((table (make-hash-table :test 'eq :size 256)))
4992 (loop for name across js2-token-names
4993 for sym = (intern (concat "js2-" (upcase name)))
4994 do
4995 (puthash sym (symbol-value sym) table))
4996 ;; clean up a few that are "wrong" in Rhino's token codes
4997 (puthash 'js2-DELETE js2-DELPROP table)
4998 table)
4999 "Hashtable mapping token symbols to their bytecodes.")
5000
5001 (defsubst js2-token-code (sym)
5002 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5003 (or (gethash sym js2-token-codes)
5004 (error "Invalid token symbol: %s " sym))) ; signal code bug
5005
5006 (defun js2-report-scan-error (msg &optional no-throw beg len)
5007 (setq js2-token-end js2-ts-cursor)
5008 (js2-report-error msg nil
5009 (or beg js2-token-beg)
5010 (or len (- js2-token-end js2-token-beg)))
5011 (unless no-throw
5012 (throw 'return js2-ERROR)))
5013
5014 (defun js2-get-string-from-buffer ()
5015 "Reverse the char accumulator and return it as a string."
5016 (setq js2-token-end js2-ts-cursor)
5017 (if js2-ts-string-buffer
5018 (apply #'string (nreverse js2-ts-string-buffer))
5019 ""))
5020
5021 ;; TODO: could potentially avoid a lot of consing by allocating a
5022 ;; char buffer the way Rhino does.
5023 (defsubst js2-add-to-string (c)
5024 (push c js2-ts-string-buffer))
5025
5026 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5027 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5028 ;; any other character: when it's not part of the current token, we
5029 ;; unget it, allowing it to be read again by the following call.
5030 (defsubst js2-unget-char ()
5031 (decf js2-ts-cursor))
5032
5033 ;; Rhino distinguishes \r and \n line endings. We don't need to
5034 ;; because we only scan from Emacs buffers, which always use \n.
5035 (defun js2-get-char ()
5036 "Read and return the next character from the input buffer.
5037 Increments `js2-ts-lineno' if the return value is a newline char.
5038 Updates `js2-ts-cursor' to the point after the returned char.
5039 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5040 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5041 (let (c)
5042 ;; check for end of buffer
5043 (if (>= js2-ts-cursor (point-max))
5044 (setq js2-ts-hit-eof t
5045 js2-ts-cursor (1+ js2-ts-cursor)
5046 c js2-EOF_CHAR) ; return value
5047 ;; otherwise read next char
5048 (setq c (char-before (incf js2-ts-cursor)))
5049 ;; if we read a newline, update counters
5050 (if (= c ?\n)
5051 (setq js2-ts-line-start js2-ts-cursor
5052 js2-ts-lineno (1+ js2-ts-lineno)))
5053 ;; TODO: skip over format characters
5054 c)))
5055
5056 (defun js2-read-unicode-escape ()
5057 "Read a \\uNNNN sequence from the input.
5058 Assumes the ?\ and ?u have already been read.
5059 Returns the unicode character, or nil if it wasn't a valid character.
5060 Doesn't change the values of any scanner variables."
5061 ;; I really wish I knew a better way to do this, but I can't
5062 ;; find the Emacs function that takes a 16-bit int and converts
5063 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5064 ;; Have to first check that it's 4 hex characters or it may stop
5065 ;; the read early.
5066 (ignore-errors
5067 (let ((s (buffer-substring-no-properties js2-ts-cursor
5068 (+ 4 js2-ts-cursor))))
5069 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5070 (read (concat "?\\u" s))))))
5071
5072 (defun js2-match-char (test)
5073 "Consume and return next character if it matches TEST, a character.
5074 Returns nil and consumes nothing if TEST is not the next character."
5075 (let ((c (js2-get-char)))
5076 (if (eq c test)
5077 t
5078 (js2-unget-char)
5079 nil)))
5080
5081 (defun js2-peek-char ()
5082 (prog1
5083 (js2-get-char)
5084 (js2-unget-char)))
5085
5086 (defun js2-java-identifier-start-p (c)
5087 (or
5088 (memq c '(?$ ?_))
5089 (js2-char-uppercase-p c)
5090 (js2-char-lowercase-p c)))
5091
5092 (defun js2-java-identifier-part-p (c)
5093 "Implementation of java.lang.Character.isJavaIdentifierPart()."
5094 ;; TODO: make me Unicode-friendly. See comments above.
5095 (or
5096 (memq c '(?$ ?_))
5097 (js2-char-uppercase-p c)
5098 (js2-char-lowercase-p c)
5099 (and (>= c ?0) (<= c ?9))))
5100
5101 (defun js2-alpha-p (c)
5102 (cond ((and (<= ?A c) (<= c ?Z)) t)
5103 ((and (<= ?a c) (<= c ?z)) t)
5104 (t nil)))
5105
5106 (defsubst js2-digit-p (c)
5107 (and (<= ?0 c) (<= c ?9)))
5108
5109 (defun js2-js-space-p (c)
5110 (if (<= c 127)
5111 (memq c '(#x20 #x9 #xB #xC #xD))
5112 (or
5113 (eq c #xA0)
5114 ;; TODO: change this nil to check for Unicode space character
5115 nil)))
5116
5117 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5118
5119 (defun js2-skip-line ()
5120 "Skip to end of line."
5121 (let (c)
5122 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5123 (js2-unget-char)
5124 (setq js2-token-end js2-ts-cursor)))
5125
5126 (defun js2-init-scanner (&optional buf line)
5127 "Create token stream for BUF starting on LINE.
5128 BUF defaults to `current-buffer' and LINE defaults to 1.
5129
5130 A buffer can only have one scanner active at a time, which yields
5131 dramatically simpler code than using a defstruct. If you need to
5132 have simultaneous scanners in a buffer, copy the regions to scan
5133 into temp buffers."
5134 (with-current-buffer (or buf (current-buffer))
5135 (setq js2-ts-dirty-line nil
5136 js2-ts-regexp-flags nil
5137 js2-ts-string ""
5138 js2-ts-number nil
5139 js2-ts-hit-eof nil
5140 js2-ts-line-start 0
5141 js2-ts-lineno (or line 1)
5142 js2-ts-line-end-char -1
5143 js2-ts-cursor (point-min)
5144 js2-ts-is-xml-attribute nil
5145 js2-ts-xml-is-tag-content nil
5146 js2-ts-xml-open-tags-count 0
5147 js2-ts-string-buffer nil)))
5148
5149 ;; This function uses the cached op, string and number fields in
5150 ;; TokenStream; if getToken has been called since the passed token
5151 ;; was scanned, the op or string printed may be incorrect.
5152 (defun js2-token-to-string (token)
5153 ;; Not sure where this function is used in Rhino. Not tested.
5154 (if (not js2-debug-print-trees)
5155 ""
5156 (let ((name (js2-token-name token)))
5157 (cond
5158 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5159 (concat name " `" js2-ts-string "'"))
5160 ((eq token js2-NUMBER)
5161 (format "NUMBER %g" js2-ts-number))
5162 (t
5163 name)))))
5164
5165 (defconst js2-keywords
5166 '(break
5167 case catch const continue
5168 debugger default delete do
5169 else enum
5170 false finally for function
5171 if in instanceof import
5172 let
5173 new null
5174 return
5175 switch
5176 this throw true try typeof
5177 var void
5178 while with
5179 yield))
5180
5181 ;; Token names aren't exactly the same as the keywords, unfortunately.
5182 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5183 (defconst js2-kwd-tokens
5184 (let ((table (make-vector js2-num-tokens nil))
5185 (tokens
5186 (list js2-BREAK
5187 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5188 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5189 js2-ELSE
5190 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5191 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5192 js2-LET
5193 js2-NEW js2-NULL
5194 js2-RETURN
5195 js2-SWITCH
5196 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5197 js2-VAR
5198 js2-WHILE js2-WITH
5199 js2-YIELD)))
5200 (dolist (i tokens)
5201 (aset table i 'font-lock-keyword-face))
5202 (aset table js2-STRING 'font-lock-string-face)
5203 (aset table js2-REGEXP 'font-lock-string-face)
5204 (aset table js2-COMMENT 'font-lock-comment-face)
5205 (aset table js2-THIS 'font-lock-builtin-face)
5206 (aset table js2-VOID 'font-lock-constant-face)
5207 (aset table js2-NULL 'font-lock-constant-face)
5208 (aset table js2-TRUE 'font-lock-constant-face)
5209 (aset table js2-FALSE 'font-lock-constant-face)
5210 table)
5211 "Vector whose values are non-nil for tokens that are keywords.
5212 The values are default faces to use for highlighting the keywords.")
5213
5214 (defconst js2-reserved-words
5215 '(abstract
5216 boolean byte
5217 char class
5218 double
5219 enum export extends
5220 final float
5221 goto
5222 implements import int interface
5223 long
5224 native
5225 package private protected public
5226 short static super synchronized
5227 throws transient
5228 volatile))
5229
5230 (defconst js2-keyword-names
5231 (let ((table (make-hash-table :test 'equal)))
5232 (loop for k in js2-keywords
5233 do (puthash
5234 (symbol-name k) ; instanceof
5235 (intern (concat "js2-"
5236 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5237 table))
5238 table)
5239 "JavaScript keywords by name, mapped to their symbols.")
5240
5241 (defconst js2-reserved-word-names
5242 (let ((table (make-hash-table :test 'equal)))
5243 (loop for k in js2-reserved-words
5244 do
5245 (puthash (symbol-name k) 'js2-RESERVED table))
5246 table)
5247 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5248
5249 (defun js2-collect-string (buf)
5250 "Convert BUF, a list of chars, to a string.
5251 Reverses BUF before converting."
5252 (cond
5253 ((stringp buf)
5254 buf)
5255 ((null buf) ; for emacs21 compat
5256 "")
5257 (t
5258 (if buf
5259 (apply #'string (nreverse buf))
5260 ""))))
5261
5262 (defun js2-string-to-keyword (s)
5263 "Return token for S, a string, if S is a keyword or reserved word.
5264 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5265 (or (gethash s js2-keyword-names)
5266 (gethash s js2-reserved-word-names)))
5267
5268 (defsubst js2-ts-set-char-token-bounds ()
5269 "Used when next token is one character."
5270 (setq js2-token-beg (1- js2-ts-cursor)
5271 js2-token-end js2-ts-cursor))
5272
5273 (defsubst js2-ts-return (token)
5274 "Return an N-character TOKEN from `js2-get-token'.
5275 Updates `js2-token-end' accordingly."
5276 (setq js2-token-end js2-ts-cursor)
5277 (throw 'return token))
5278
5279 (defun js2-x-digit-to-int (c accumulator)
5280 "Build up a hex number.
5281 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5282 corresponding number. Otherwise return -1."
5283 (catch 'return
5284 (catch 'check
5285 ;; Use 0..9 < A..Z < a..z
5286 (cond
5287 ((<= c ?9)
5288 (decf c ?0)
5289 (if (<= 0 c)
5290 (throw 'check nil)))
5291 ((<= c ?F)
5292 (when (<= ?A c)
5293 (decf c (- ?A 10))
5294 (throw 'check nil)))
5295 ((<= c ?f)
5296 (when (<= ?a c)
5297 (decf c (- ?a 10))
5298 (throw 'check nil))))
5299 (throw 'return -1))
5300 (logior c (lsh accumulator 4))))
5301
5302 (defun js2-get-token ()
5303 "Return next JavaScript token, an int such as js2-RETURN."
5304 (let (c c1 identifier-start is-unicode-escape-start
5305 contains-escape escape-val escape-start str result base
5306 is-integer quote-char val look-for-slash continue)
5307 (catch 'return
5308 (while t
5309 ;; Eat whitespace, possibly sensitive to newlines.
5310 (setq continue t)
5311 (while continue
5312 (setq c (js2-get-char))
5313 (cond
5314 ((eq c js2-EOF_CHAR)
5315 (js2-ts-set-char-token-bounds)
5316 (throw 'return js2-EOF))
5317 ((eq c ?\n)
5318 (js2-ts-set-char-token-bounds)
5319 (setq js2-ts-dirty-line nil)
5320 (throw 'return js2-EOL))
5321 ((not (js2-js-space-p c))
5322 (if (/= c ?-) ; in case end of HTML comment
5323 (setq js2-ts-dirty-line t))
5324 (setq continue nil))))
5325 ;; Assume the token will be 1 char - fixed up below.
5326 (js2-ts-set-char-token-bounds)
5327 (when (eq c ?@)
5328 (throw 'return js2-XMLATTR))
5329 ;; identifier/keyword/instanceof?
5330 ;; watch out for starting with a <backslash>
5331 (cond
5332 ((eq c ?\\)
5333 (setq c (js2-get-char))
5334 (if (eq c ?u)
5335 (setq identifier-start t
5336 is-unicode-escape-start t
5337 js2-ts-string-buffer nil)
5338 (setq identifier-start nil)
5339 (js2-unget-char)
5340 (setq c ?\\)))
5341 (t
5342 (when (setq identifier-start (js2-java-identifier-start-p c))
5343 (setq js2-ts-string-buffer nil)
5344 (js2-add-to-string c))))
5345 (when identifier-start
5346 (setq contains-escape is-unicode-escape-start)
5347 (catch 'break
5348 (while t
5349 (if is-unicode-escape-start
5350 ;; strictly speaking we should probably push-back
5351 ;; all the bad characters if the <backslash>uXXXX
5352 ;; sequence is malformed. But since there isn't a
5353 ;; correct context(is there?) for a bad Unicode
5354 ;; escape sequence in an identifier, we can report
5355 ;; an error here.
5356 (progn
5357 (setq escape-val 0)
5358 (dotimes (i 4)
5359 (setq c (js2-get-char)
5360 escape-val (js2-x-digit-to-int c escape-val))
5361 ;; Next check takes care of c < 0 and bad escape
5362 (if (minusp escape-val)
5363 (throw 'break nil)))
5364 (if (minusp escape-val)
5365 (js2-report-scan-error "msg.invalid.escape" t))
5366 (js2-add-to-string escape-val)
5367 (setq is-unicode-escape-start nil))
5368 (setq c (js2-get-char))
5369 (cond
5370 ((eq c ?\\)
5371 (setq c (js2-get-char))
5372 (if (eq c ?u)
5373 (setq is-unicode-escape-start t
5374 contains-escape t)
5375 (js2-report-scan-error "msg.illegal.character" t)))
5376 (t
5377 (if (or (eq c js2-EOF_CHAR)
5378 (not (js2-java-identifier-part-p c)))
5379 (throw 'break nil))
5380 (js2-add-to-string c))))))
5381 (js2-unget-char)
5382 (setq str (js2-get-string-from-buffer))
5383 (unless contains-escape
5384 ;; OPT we shouldn't have to make a string (object!) to
5385 ;; check if it's a keyword.
5386 ;; Return the corresponding token if it's a keyword
5387 (when (setq result (js2-string-to-keyword str))
5388 (if (and (< js2-language-version 170)
5389 (memq result '(js2-LET js2-YIELD)))
5390 ;; LET and YIELD are tokens only in 1.7 and later
5391 (setq result 'js2-NAME))
5392 (if (not (eq result 'js2-RESERVED))
5393 (throw 'return (js2-token-code result)))
5394 (js2-report-warning "msg.reserved.keyword" str)))
5395 ;; If we want to intern these as Rhino does, just use (intern str)
5396 (setq js2-ts-string str)
5397 (throw 'return js2-NAME)) ; end identifier/kwd check
5398 ;; is it a number?
5399 (when (or (js2-digit-p c)
5400 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5401 (setq js2-ts-string-buffer nil
5402 base 10)
5403 (when (eq c ?0)
5404 (setq c (js2-get-char))
5405 (cond
5406 ((or (eq c ?x) (eq c ?X))
5407 (setq base 16)
5408 (setq c (js2-get-char)))
5409 ((js2-digit-p c)
5410 (setq base 8))
5411 (t
5412 (js2-add-to-string ?0))))
5413 (if (eq base 16)
5414 (while (<= 0 (js2-x-digit-to-int c 0))
5415 (js2-add-to-string c)
5416 (setq c (js2-get-char)))
5417 (while (and (<= ?0 c) (<= c ?9))
5418 ;; We permit 08 and 09 as decimal numbers, which
5419 ;; makes our behavior a superset of the ECMA
5420 ;; numeric grammar. We might not always be so
5421 ;; permissive, so we warn about it.
5422 (when (and (eq base 8) (>= c ?8))
5423 (js2-report-warning "msg.bad.octal.literal"
5424 (if (eq c ?8) "8" "9"))
5425 (setq base 10))
5426 (js2-add-to-string c)
5427 (setq c (js2-get-char))))
5428 (setq is-integer t)
5429 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5430 (setq is-integer nil)
5431 (when (eq c ?.)
5432 (loop do
5433 (js2-add-to-string c)
5434 (setq c (js2-get-char))
5435 while (js2-digit-p c)))
5436 (when (memq c '(?e ?E))
5437 (js2-add-to-string c)
5438 (setq c (js2-get-char))
5439 (when (memq c '(?+ ?-))
5440 (js2-add-to-string c)
5441 (setq c (js2-get-char)))
5442 (unless (js2-digit-p c)
5443 (js2-report-scan-error "msg.missing.exponent" t))
5444 (loop do
5445 (js2-add-to-string c)
5446 (setq c (js2-get-char))
5447 while (js2-digit-p c))))
5448 (js2-unget-char)
5449 (setq js2-ts-string (js2-get-string-from-buffer)
5450 js2-ts-number
5451 (if (and (eq base 10) (not is-integer))
5452 (string-to-number js2-ts-string)
5453 ;; TODO: call runtime number-parser. Some of it is in
5454 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5455 (string-to-number js2-ts-string)))
5456 (throw 'return js2-NUMBER))
5457 ;; is it a string?
5458 (when (memq c '(?\" ?\'))
5459 ;; We attempt to accumulate a string the fast way, by
5460 ;; building it directly out of the reader. But if there
5461 ;; are any escaped characters in the string, we revert to
5462 ;; building it out of a string buffer.
5463 (setq quote-char c
5464 js2-ts-string-buffer nil
5465 c (js2-get-char))
5466 (catch 'break
5467 (while (/= c quote-char)
5468 (catch 'continue
5469 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5470 (js2-unget-char)
5471 (setq js2-token-end js2-ts-cursor)
5472 (js2-report-error "msg.unterminated.string.lit")
5473 (throw 'return js2-STRING))
5474 (when (eq c ?\\)
5475 ;; We've hit an escaped character
5476 (setq c (js2-get-char))
5477 (case c
5478 (?b (setq c ?\b))
5479 (?f (setq c ?\f))
5480 (?n (setq c ?\n))
5481 (?r (setq c ?\r))
5482 (?t (setq c ?\t))
5483 (?v (setq c ?\v))
5484 (?u
5485 (setq c1 (js2-read-unicode-escape))
5486 (if js2-parse-ide-mode
5487 (if c1
5488 (progn
5489 ;; just copy the string in IDE-mode
5490 (js2-add-to-string ?\\)
5491 (js2-add-to-string ?u)
5492 (dotimes (i 3)
5493 (js2-add-to-string (js2-get-char)))
5494 (setq c (js2-get-char))) ; added at end of loop
5495 ;; flag it as an invalid escape
5496 (js2-report-warning "msg.invalid.escape"
5497 nil (- js2-ts-cursor 2) 6))
5498 ;; Get 4 hex digits; if the u escape is not
5499 ;; followed by 4 hex digits, use 'u' + the
5500 ;; literal character sequence that follows.
5501 (js2-add-to-string ?u)
5502 (setq escape-val 0)
5503 (dotimes (i 4)
5504 (setq c (js2-get-char)
5505 escape-val (js2-x-digit-to-int c escape-val))
5506 (if (minusp escape-val)
5507 (throw 'continue nil))
5508 (js2-add-to-string c))
5509 ;; prepare for replace of stored 'u' sequence by escape value
5510 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5511 c escape-val)))
5512 (?x
5513 ;; Get 2 hex digits, defaulting to 'x'+literal
5514 ;; sequence, as above.
5515 (setq c (js2-get-char)
5516 escape-val (js2-x-digit-to-int c 0))
5517 (if (minusp escape-val)
5518 (progn
5519 (js2-add-to-string ?x)
5520 (throw 'continue nil))
5521 (setq c1 c
5522 c (js2-get-char)
5523 escape-val (js2-x-digit-to-int c escape-val))
5524 (if (minusp escape-val)
5525 (progn
5526 (js2-add-to-string ?x)
5527 (js2-add-to-string c1)
5528 (throw 'continue nil))
5529 ;; got 2 hex digits
5530 (setq c escape-val))))
5531 (?\n
5532 ;; Remove line terminator after escape to follow
5533 ;; SpiderMonkey and C/C++
5534 (setq c (js2-get-char))
5535 (throw 'continue nil))
5536 (t
5537 (when (and (<= ?0 c) (< c ?8))
5538 (setq val (- c ?0)
5539 c (js2-get-char))
5540 (when (and (<= ?0 c) (< c ?8))
5541 (setq val (- (+ (* 8 val) c) ?0)
5542 c (js2-get-char))
5543 (when (and (<= ?0 c)
5544 (< c ?8)
5545 (< val #o37))
5546 ;; c is 3rd char of octal sequence only
5547 ;; if the resulting val <= 0377
5548 (setq val (- (+ (* 8 val) c) ?0)
5549 c (js2-get-char))))
5550 (js2-unget-char)
5551 (setq c val)))))
5552 (js2-add-to-string c)
5553 (setq c (js2-get-char)))))
5554 (setq js2-ts-string (js2-get-string-from-buffer))
5555 (throw 'return js2-STRING))
5556 (case c
5557 (?\;
5558 (throw 'return js2-SEMI))
5559 (?\[
5560 (throw 'return js2-LB))
5561 (?\]
5562 (throw 'return js2-RB))
5563 (?{
5564 (throw 'return js2-LC))
5565 (?}
5566 (throw 'return js2-RC))
5567 (?\(
5568 (throw 'return js2-LP))
5569 (?\)
5570 (throw 'return js2-RP))
5571 (?,
5572 (throw 'return js2-COMMA))
5573 (??
5574 (throw 'return js2-HOOK))
5575 (?:
5576 (if (js2-match-char ?:)
5577 (js2-ts-return js2-COLONCOLON)
5578 (throw 'return js2-COLON)))
5579 (?.
5580 (if (js2-match-char ?.)
5581 (if (js2-match-char ?.)
5582 (js2-ts-return js2-TRIPLEDOT)
5583 (js2-ts-return js2-DOTDOT))
5584 (if (js2-match-char ?\()
5585 (js2-ts-return js2-DOTQUERY)
5586 (throw 'return js2-DOT))))
5587 (?|
5588 (if (js2-match-char ?|)
5589 (throw 'return js2-OR)
5590 (if (js2-match-char ?=)
5591 (js2-ts-return js2-ASSIGN_BITOR)
5592 (throw 'return js2-BITOR))))
5593 (?^
5594 (if (js2-match-char ?=)
5595 (js2-ts-return js2-ASSIGN_BITOR)
5596 (throw 'return js2-BITXOR)))
5597 (?&
5598 (if (js2-match-char ?&)
5599 (throw 'return js2-AND)
5600 (if (js2-match-char ?=)
5601 (js2-ts-return js2-ASSIGN_BITAND)
5602 (throw 'return js2-BITAND))))
5603 (?=
5604 (if (js2-match-char ?=)
5605 (if (js2-match-char ?=)
5606 (js2-ts-return js2-SHEQ)
5607 (throw 'return js2-EQ))
5608 (throw 'return js2-ASSIGN)))
5609 (?!
5610 (if (js2-match-char ?=)
5611 (if (js2-match-char ?=)
5612 (js2-ts-return js2-SHNE)
5613 (js2-ts-return js2-NE))
5614 (throw 'return js2-NOT)))
5615 (?<
5616 ;; NB:treat HTML begin-comment as comment-till-eol
5617 (when (js2-match-char ?!)
5618 (when (js2-match-char ?-)
5619 (when (js2-match-char ?-)
5620 (js2-skip-line)
5621 (setq js2-ts-comment-type 'html)
5622 (throw 'return js2-COMMENT)))
5623 (js2-unget-char))
5624 (if (js2-match-char ?<)
5625 (if (js2-match-char ?=)
5626 (js2-ts-return js2-ASSIGN_LSH)
5627 (js2-ts-return js2-LSH))
5628 (if (js2-match-char ?=)
5629 (js2-ts-return js2-LE)
5630 (throw 'return js2-LT))))
5631 (?>
5632 (if (js2-match-char ?>)
5633 (if (js2-match-char ?>)
5634 (if (js2-match-char ?=)
5635 (js2-ts-return js2-ASSIGN_URSH)
5636 (js2-ts-return js2-URSH))
5637 (if (js2-match-char ?=)
5638 (js2-ts-return js2-ASSIGN_RSH)
5639 (js2-ts-return js2-RSH)))
5640 (if (js2-match-char ?=)
5641 (js2-ts-return js2-GE)
5642 (throw 'return js2-GT))))
5643 (?*
5644 (if (js2-match-char ?=)
5645 (js2-ts-return js2-ASSIGN_MUL)
5646 (throw 'return js2-MUL)))
5647 (?/
5648 ;; is it a // comment?
5649 (when (js2-match-char ?/)
5650 (setq js2-token-beg (- js2-ts-cursor 2))
5651 (js2-skip-line)
5652 (setq js2-ts-comment-type 'line)
5653 ;; include newline so highlighting goes to end of window
5654 (incf js2-token-end)
5655 (throw 'return js2-COMMENT))
5656 ;; is it a /* comment?
5657 (when (js2-match-char ?*)
5658 (setq look-for-slash nil
5659 js2-token-beg (- js2-ts-cursor 2)
5660 js2-ts-comment-type
5661 (if (js2-match-char ?*)
5662 (progn
5663 (setq look-for-slash t)
5664 'jsdoc)
5665 'block))
5666 (while t
5667 (setq c (js2-get-char))
5668 (cond
5669 ((eq c js2-EOF_CHAR)
5670 (setq js2-token-end (1- js2-ts-cursor))
5671 (js2-report-error "msg.unterminated.comment")
5672 (throw 'return js2-COMMENT))
5673 ((eq c ?*)
5674 (setq look-for-slash t))
5675 ((eq c ?/)
5676 (if look-for-slash
5677 (js2-ts-return js2-COMMENT)))
5678 (t
5679 (setq look-for-slash nil
5680 js2-token-end js2-ts-cursor)))))
5681 (if (js2-match-char ?=)
5682 (js2-ts-return js2-ASSIGN_DIV)
5683 (throw 'return js2-DIV)))
5684 (?#
5685 (when js2-skip-preprocessor-directives
5686 (js2-skip-line)
5687 (setq js2-ts-comment-type 'preprocessor
5688 js2-token-end js2-ts-cursor)
5689 (throw 'return js2-COMMENT))
5690 (throw 'return js2-ERROR))
5691 (?%
5692 (if (js2-match-char ?=)
5693 (js2-ts-return js2-ASSIGN_MOD)
5694 (throw 'return js2-MOD)))
5695 (?~
5696 (throw 'return js2-BITNOT))
5697 (?+
5698 (if (js2-match-char ?=)
5699 (js2-ts-return js2-ASSIGN_ADD)
5700 (if (js2-match-char ?+)
5701 (js2-ts-return js2-INC)
5702 (throw 'return js2-ADD))))
5703 (?-
5704 (cond
5705 ((js2-match-char ?=)
5706 (setq c js2-ASSIGN_SUB))
5707 ((js2-match-char ?-)
5708 (unless js2-ts-dirty-line
5709 ;; treat HTML end-comment after possible whitespace
5710 ;; after line start as comment-until-eol
5711 (when (js2-match-char ?>)
5712 (js2-skip-line)
5713 (setq js2-ts-comment-type 'html)
5714 (throw 'return js2-COMMENT)))
5715 (setq c js2-DEC))
5716 (t
5717 (setq c js2-SUB)))
5718 (setq js2-ts-dirty-line t)
5719 (js2-ts-return c))
5720 (otherwise
5721 (js2-report-scan-error "msg.illegal.character")))))))
5722
5723 (defun js2-read-regexp (start-token)
5724 "Called by parser when it gets / or /= in literal context."
5725 (let (c err
5726 in-class ; inside a '[' .. ']' character-class
5727 flags
5728 (continue t))
5729 (setq js2-token-beg js2-ts-cursor
5730 js2-ts-string-buffer nil
5731 js2-ts-regexp-flags nil)
5732 (if (eq start-token js2-ASSIGN_DIV)
5733 ;; mis-scanned /=
5734 (js2-add-to-string ?=)
5735 (if (not (eq start-token js2-DIV))
5736 (error "failed assertion")))
5737 (while (and (not err)
5738 (or (/= (setq c (js2-get-char)) ?/)
5739 in-class))
5740 (cond
5741 ((or (= c ?\n)
5742 (= c js2-EOF_CHAR))
5743 (setq js2-token-end (1- js2-ts-cursor)
5744 err t
5745 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5746 (js2-report-error "msg.unterminated.re.lit"))
5747 (t (cond
5748 ((= c ?\\)
5749 (js2-add-to-string c)
5750 (setq c (js2-get-char)))
5751 ((= c ?\[)
5752 (setq in-class t))
5753 ((= c ?\])
5754 (setq in-class nil)))
5755 (js2-add-to-string c))))
5756 (unless err
5757 (while continue
5758 (cond
5759 ((js2-match-char ?g)
5760 (push ?g flags))
5761 ((js2-match-char ?i)
5762 (push ?i flags))
5763 ((js2-match-char ?m)
5764 (push ?m flags))
5765 (t
5766 (setq continue nil))))
5767 (if (js2-alpha-p (js2-peek-char))
5768 (js2-report-scan-error "msg.invalid.re.flag" t
5769 js2-ts-cursor 1))
5770 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5771 js2-ts-regexp-flags (js2-collect-string flags)
5772 js2-token-end js2-ts-cursor)
5773 ;; tell `parse-partial-sexp' to ignore this range of chars
5774 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
5775
5776 (defun js2-get-first-xml-token ()
5777 (setq js2-ts-xml-open-tags-count 0
5778 js2-ts-is-xml-attribute nil
5779 js2-ts-xml-is-tag-content nil)
5780 (js2-unget-char)
5781 (js2-get-next-xml-token))
5782
5783 (defun js2-xml-discard-string ()
5784 "Throw away the string in progress and flag an XML parse error."
5785 (setq js2-ts-string-buffer nil
5786 js2-ts-string nil)
5787 (js2-report-scan-error "msg.XML.bad.form" t))
5788
5789 (defun js2-get-next-xml-token ()
5790 (setq js2-ts-string-buffer nil ; for recording the XML
5791 js2-token-beg js2-ts-cursor)
5792 (let (c result)
5793 (setq result
5794 (catch 'return
5795 (while t
5796 (setq c (js2-get-char))
5797 (cond
5798 ((= c js2-EOF_CHAR)
5799 (throw 'return js2-ERROR))
5800 (js2-ts-xml-is-tag-content
5801 (case c
5802 (?>
5803 (js2-add-to-string c)
5804 (setq js2-ts-xml-is-tag-content nil
5805 js2-ts-is-xml-attribute nil))
5806 (?/
5807 (js2-add-to-string c)
5808 (when (eq ?> (js2-peek-char))
5809 (setq c (js2-get-char))
5810 (js2-add-to-string c)
5811 (setq js2-ts-xml-is-tag-content nil)
5812 (decf js2-ts-xml-open-tags-count)))
5813 (?{
5814 (js2-unget-char)
5815 (setq js2-ts-string (js2-get-string-from-buffer))
5816 (throw 'return js2-XML))
5817 ((?\' ?\")
5818 (js2-add-to-string c)
5819 (unless (js2-read-quoted-string c)
5820 (throw 'return js2-ERROR)))
5821 (?=
5822 (js2-add-to-string c)
5823 (setq js2-ts-is-xml-attribute t))
5824 ((? ?\t ?\r ?\n)
5825 (js2-add-to-string c))
5826 (t
5827 (js2-add-to-string c)
5828 (setq js2-ts-is-xml-attribute nil)))
5829 (when (and (not js2-ts-xml-is-tag-content)
5830 (zerop js2-ts-xml-open-tags-count))
5831 (setq js2-ts-string (js2-get-string-from-buffer))
5832 (throw 'return js2-XMLEND)))
5833 (t
5834 ;; else not tag content
5835 (case c
5836 (?<
5837 (js2-add-to-string c)
5838 (setq c (js2-peek-char))
5839 (case c
5840 (?!
5841 (setq c (js2-get-char)) ;; skip !
5842 (js2-add-to-string c)
5843 (setq c (js2-peek-char))
5844 (case c
5845 (?-
5846 (setq c (js2-get-char)) ;; skip -
5847 (js2-add-to-string c)
5848 (if (eq c ?-)
5849 (progn
5850 (js2-add-to-string c)
5851 (unless (js2-read-xml-comment)
5852 (throw 'return js2-ERROR)))
5853 (js2-xml-discard-string)
5854 (throw 'return js2-ERROR)))
5855 (?\[
5856 (setq c (js2-get-char)) ;; skip [
5857 (js2-add-to-string c)
5858 (if (and (= (js2-get-char) ?C)
5859 (= (js2-get-char) ?D)
5860 (= (js2-get-char) ?A)
5861 (= (js2-get-char) ?T)
5862 (= (js2-get-char) ?A)
5863 (= (js2-get-char) ?\[))
5864 (progn
5865 (js2-add-to-string ?C)
5866 (js2-add-to-string ?D)
5867 (js2-add-to-string ?A)
5868 (js2-add-to-string ?T)
5869 (js2-add-to-string ?A)
5870 (js2-add-to-string ?\[)
5871 (unless (js2-read-cdata)
5872 (throw 'return js2-ERROR)))
5873 (js2-xml-discard-string)
5874 (throw 'return js2-ERROR)))
5875 (t
5876 (unless (js2-read-entity)
5877 (throw 'return js2-ERROR))))
5878 ;; Allow bare CDATA section, e.g.:
5879 ;; let xml = <![CDATA[ foo bar baz ]]>;
5880 (when (zerop js2-ts-xml-open-tags-count)
5881 (throw 'return js2-XMLEND)))
5882 (??
5883 (setq c (js2-get-char)) ;; skip ?
5884 (js2-add-to-string c)
5885 (unless (js2-read-PI)
5886 (throw 'return js2-ERROR)))
5887 (?/
5888 ;; end tag
5889 (setq c (js2-get-char)) ;; skip /
5890 (js2-add-to-string c)
5891 (when (zerop js2-ts-xml-open-tags-count)
5892 (js2-xml-discard-string)
5893 (throw 'return js2-ERROR))
5894 (setq js2-ts-xml-is-tag-content t)
5895 (decf js2-ts-xml-open-tags-count))
5896 (t
5897 ;; start tag
5898 (setq js2-ts-xml-is-tag-content t)
5899 (incf js2-ts-xml-open-tags-count))))
5900 (?{
5901 (js2-unget-char)
5902 (setq js2-ts-string (js2-get-string-from-buffer))
5903 (throw 'return js2-XML))
5904 (t
5905 (js2-add-to-string c))))))))
5906 (setq js2-token-end js2-ts-cursor)
5907 result))
5908
5909 (defun js2-read-quoted-string (quote)
5910 (let (c)
5911 (catch 'return
5912 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
5913 (js2-add-to-string c)
5914 (if (eq c quote)
5915 (throw 'return t)))
5916 (js2-xml-discard-string) ;; throw away string in progress
5917 nil)))
5918
5919 (defun js2-read-xml-comment ()
5920 (let ((c (js2-get-char)))
5921 (catch 'return
5922 (while (/= c js2-EOF_CHAR)
5923 (catch 'continue
5924 (js2-add-to-string c)
5925 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
5926 (setq c (js2-get-char))
5927 (js2-add-to-string c)
5928 (if (eq (js2-peek-char) ?>)
5929 (progn
5930 (setq c (js2-get-char)) ;; skip >
5931 (js2-add-to-string c)
5932 (throw 'return t))
5933 (throw 'continue nil)))
5934 (setq c (js2-get-char))))
5935 (js2-xml-discard-string)
5936 nil)))
5937
5938 (defun js2-read-cdata ()
5939 (let ((c (js2-get-char)))
5940 (catch 'return
5941 (while (/= c js2-EOF_CHAR)
5942 (catch 'continue
5943 (js2-add-to-string c)
5944 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
5945 (setq c (js2-get-char))
5946 (js2-add-to-string c)
5947 (if (eq (js2-peek-char) ?>)
5948 (progn
5949 (setq c (js2-get-char)) ;; Skip >
5950 (js2-add-to-string c)
5951 (throw 'return t))
5952 (throw 'continue nil)))
5953 (setq c (js2-get-char))))
5954 (js2-xml-discard-string)
5955 nil)))
5956
5957 (defun js2-read-entity ()
5958 (let ((decl-tags 1)
5959 c)
5960 (catch 'return
5961 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
5962 (js2-add-to-string c)
5963 (case c
5964 (?<
5965 (incf decl-tags))
5966 (?>
5967 (decf decl-tags)
5968 (if (zerop decl-tags)
5969 (throw 'return t)))))
5970 (js2-xml-discard-string)
5971 nil)))
5972
5973 (defun js2-read-PI ()
5974 "Scan an XML processing instruction."
5975 (let (c)
5976 (catch 'return
5977 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
5978 (js2-add-to-string c)
5979 (when (and (eq c ??) (eq (js2-peek-char) ?>))
5980 (setq c (js2-get-char)) ;; Skip >
5981 (js2-add-to-string c)
5982 (throw 'return t)))
5983 (js2-xml-discard-string)
5984 nil)))
5985
5986 ;;; Highlighting
5987
5988 (defun js2-set-face (beg end face &optional record)
5989 "Fontify a region. If RECORD is non-nil, record for later."
5990 (when (plusp js2-highlight-level)
5991 (setq beg (min (point-max) beg)
5992 beg (max (point-min) beg)
5993 end (min (point-max) end)
5994 end (max (point-min) end))
5995 (if record
5996 (push (list beg end face) js2-mode-fontifications)
5997 (put-text-property beg end 'font-lock-face face))))
5998
5999 (defsubst js2-clear-face (beg end)
6000 (remove-text-properties beg end '(font-lock-face nil
6001 help-echo nil
6002 point-entered nil
6003 c-in-sws nil)))
6004
6005 (defconst js2-ecma-global-props
6006 (concat "^"
6007 (regexp-opt
6008 '("Infinity" "NaN" "undefined" "arguments") t)
6009 "$")
6010 "Value properties of the Ecma-262 Global Object.
6011 Shown at or above `js2-highlight-level' 2.")
6012
6013 ;; might want to add the name "arguments" to this list?
6014 (defconst js2-ecma-object-props
6015 (concat "^"
6016 (regexp-opt
6017 '("prototype" "__proto__" "__parent__") t)
6018 "$")
6019 "Value properties of the Ecma-262 Object constructor.
6020 Shown at or above `js2-highlight-level' 2.")
6021
6022 (defconst js2-ecma-global-funcs
6023 (concat
6024 "^"
6025 (regexp-opt
6026 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6027 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6028 "$")
6029 "Function properties of the Ecma-262 Global object.
6030 Shown at or above `js2-highlight-level' 2.")
6031
6032 (defconst js2-ecma-number-props
6033 (concat "^"
6034 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6035 "NEGATIVE_INFINITY"
6036 "POSITIVE_INFINITY") t)
6037 "$")
6038 "Properties of the Ecma-262 Number constructor.
6039 Shown at or above `js2-highlight-level' 2.")
6040
6041 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6042 "Properties of the Ecma-262 Date constructor.
6043 Shown at or above `js2-highlight-level' 2.")
6044
6045 (defconst js2-ecma-math-props
6046 (concat "^"
6047 (regexp-opt
6048 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6049 t)
6050 "$")
6051 "Properties of the Ecma-262 Math object.
6052 Shown at or above `js2-highlight-level' 2.")
6053
6054 (defconst js2-ecma-math-funcs
6055 (concat "^"
6056 (regexp-opt
6057 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6058 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6059 "$")
6060 "Function properties of the Ecma-262 Math object.
6061 Shown at or above `js2-highlight-level' 2.")
6062
6063 (defconst js2-ecma-function-props
6064 (concat
6065 "^"
6066 (regexp-opt
6067 '(;; properties of the Object prototype object
6068 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6069 "toLocaleString" "toString" "valueOf"
6070 ;; properties of the Function prototype object
6071 "apply" "call"
6072 ;; properties of the Array prototype object
6073 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6074 "splice" "unshift"
6075 ;; properties of the String prototype object
6076 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6077 "localeCompare" "match" "replace" "search" "split" "substring"
6078 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6079 "toUpperCase"
6080 ;; properties of the Number prototype object
6081 "toExponential" "toFixed" "toPrecision"
6082 ;; properties of the Date prototype object
6083 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6084 "getMinutes" "getMonth" "getSeconds" "getTime"
6085 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6086 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6087 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6088 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6089 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6090 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6091 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6092 "toTimeString" "toUTCString"
6093 ;; properties of the RegExp prototype object
6094 "exec" "test"
6095 ;; properties of the JSON prototype object
6096 "parse" "stringify"
6097 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6098 "toSource" "__defineGetter__" "__defineSetter__"
6099 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6100 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6101 t)
6102 "$")
6103 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6104 Shown at or above `js2-highlight-level' 3.")
6105
6106 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6107 (let ((target-name (and target
6108 (js2-name-node-p target)
6109 (js2-name-node-name target)))
6110 (prop-name (if prop (js2-name-node-name prop)))
6111 (level1 (>= js2-highlight-level 1))
6112 (level2 (>= js2-highlight-level 2))
6113 (level3 (>= js2-highlight-level 3))
6114 pos face)
6115 (when level2
6116 (if call-p
6117 (cond
6118 ((and target prop)
6119 (cond
6120 ((and level3 (string-match js2-ecma-function-props prop-name))
6121 (setq face 'font-lock-builtin-face))
6122 ((and target-name prop)
6123 (cond
6124 ((string= target-name "Date")
6125 (if (string-match js2-ecma-date-props prop-name)
6126 (setq face 'font-lock-builtin-face)))
6127 ((string= target-name "Math")
6128 (if (string-match js2-ecma-math-funcs prop-name)
6129 (setq face 'font-lock-builtin-face)))))))
6130 (prop
6131 (if (string-match js2-ecma-global-funcs prop-name)
6132 (setq face 'font-lock-builtin-face))))
6133 (cond
6134 ((and target prop)
6135 (cond
6136 ((string= target-name "Number")
6137 (if (string-match js2-ecma-number-props prop-name)
6138 (setq face 'font-lock-constant-face)))
6139 ((string= target-name "Math")
6140 (if (string-match js2-ecma-math-props prop-name)
6141 (setq face 'font-lock-constant-face)))))
6142 (prop
6143 (if (string-match js2-ecma-object-props prop-name)
6144 (setq face 'font-lock-constant-face)))))
6145 (when face
6146 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6147 (js2-node-pos prop))) ; relative
6148 (+ pos (js2-node-len prop))
6149 face 'record)))))
6150
6151 (defun js2-parse-highlight-member-expr-node (node)
6152 "Perform syntax highlighting of EcmaScript built-in properties.
6153 The variable `js2-highlight-level' governs this highighting."
6154 (let (face target prop name pos end parent call-p callee)
6155 (cond
6156 ;; case 1: simple name, e.g. foo
6157 ((js2-name-node-p node)
6158 (setq name (js2-name-node-name node))
6159 ;; possible for name to be nil in rare cases - saw it when
6160 ;; running js2-mode on an elisp buffer. Might as well try to
6161 ;; make it so js2-mode never barfs.
6162 (when name
6163 (setq face (if (string-match js2-ecma-global-props name)
6164 'font-lock-constant-face))
6165 (when face
6166 (setq pos (js2-node-pos node)
6167 end (+ pos (js2-node-len node)))
6168 (js2-set-face pos end face 'record))))
6169 ;; case 2: property access or function call
6170 ((or (js2-prop-get-node-p node)
6171 ;; highlight function call if expr is a prop-get node
6172 ;; or a plain name (i.e. unqualified function call)
6173 (and (setq call-p (js2-call-node-p node))
6174 (setq callee (js2-call-node-target node)) ; separate setq!
6175 (or (js2-prop-get-node-p callee)
6176 (js2-name-node-p callee))))
6177 (setq parent node
6178 node (if call-p callee node))
6179 (if (and call-p (js2-name-node-p callee))
6180 (setq prop callee)
6181 (setq target (js2-prop-get-node-left node)
6182 prop (js2-prop-get-node-right node)))
6183 (cond
6184 ((js2-name-node-p target)
6185 (if (js2-name-node-p prop)
6186 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6187 (js2-parse-highlight-prop-get parent target prop call-p)
6188 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6189 (js2-parse-highlight-prop-get parent target nil call-p)))
6190 ((js2-name-node-p prop)
6191 ;; case 2c: complex target, simple name, e.g. x[y].bar
6192 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6193
6194 (defun js2-parse-highlight-member-expr-fn-name (expr)
6195 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6196 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6197 We currently only handle the case where the last component is a prop-get
6198 of a simple name. Called before EXPR has a parent node."
6199 (let (pos
6200 (name (and (js2-prop-get-node-p expr)
6201 (js2-prop-get-node-right expr))))
6202 (when (js2-name-node-p name)
6203 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6204 (js2-node-pos name)))
6205 (+ pos (js2-node-len name))
6206 'font-lock-function-name-face
6207 'record))))
6208
6209 ;; source: http://jsdoc.sourceforge.net/
6210 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6211 ;; allows type specifications, and needs work before entering the wild.
6212
6213 (defconst js2-jsdoc-param-tag-regexp
6214 (concat "^\\s-*\\*+\\s-*\\(@"
6215 "\\(?:param\\|argument\\)"
6216 "\\)"
6217 "\\s-*\\({[^}]+}\\)?" ; optional type
6218 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6219 "\\>")
6220 "Matches jsdoc tags with optional type and optional param name.")
6221
6222 (defconst js2-jsdoc-typed-tag-regexp
6223 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6224 (regexp-opt
6225 '("enum"
6226 "extends"
6227 "field"
6228 "id"
6229 "implements"
6230 "lends"
6231 "mods"
6232 "requires"
6233 "return"
6234 "returns"
6235 "throw"
6236 "throws"))
6237 "\\)\\)\\s-*\\({[^}]+}\\)?")
6238 "Matches jsdoc tags with optional type.")
6239
6240 (defconst js2-jsdoc-arg-tag-regexp
6241 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6242 (regexp-opt
6243 '("alias"
6244 "augments"
6245 "borrows"
6246 "bug"
6247 "base"
6248 "config"
6249 "default"
6250 "define"
6251 "exception"
6252 "function"
6253 "member"
6254 "memberOf"
6255 "name"
6256 "namespace"
6257 "property"
6258 "since"
6259 "suppress"
6260 "this"
6261 "throws"
6262 "type"
6263 "version"))
6264 "\\)\\)\\s-+\\([^ \t]+\\)")
6265 "Matches jsdoc tags with a single argument.")
6266
6267 (defconst js2-jsdoc-empty-tag-regexp
6268 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6269 (regexp-opt
6270 '("addon"
6271 "author"
6272 "class"
6273 "const"
6274 "constant"
6275 "constructor"
6276 "constructs"
6277 "deprecated"
6278 "desc"
6279 "description"
6280 "event"
6281 "example"
6282 "exec"
6283 "export"
6284 "fileoverview"
6285 "final"
6286 "function"
6287 "hidden"
6288 "ignore"
6289 "implicitCast"
6290 "inheritDoc"
6291 "inner"
6292 "interface"
6293 "license"
6294 "noalias"
6295 "noshadow"
6296 "notypecheck"
6297 "override"
6298 "owner"
6299 "preserve"
6300 "preserveTry"
6301 "private"
6302 "protected"
6303 "public"
6304 "static"
6305 "supported"
6306 ))
6307 "\\)\\)\\s-*")
6308 "Matches empty jsdoc tags.")
6309
6310 (defconst js2-jsdoc-link-tag-regexp
6311 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6312 "Matches a jsdoc link or code tag.")
6313
6314 (defconst js2-jsdoc-see-tag-regexp
6315 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6316 "Matches a jsdoc @see tag.")
6317
6318 (defconst js2-jsdoc-html-tag-regexp
6319 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6320 "Matches a simple (no attributes) html start- or end-tag.")
6321
6322 (defun js2-jsdoc-highlight-helper ()
6323 (js2-set-face (match-beginning 1)
6324 (match-end 1)
6325 'js2-jsdoc-tag)
6326 (if (match-beginning 2)
6327 (if (save-excursion
6328 (goto-char (match-beginning 2))
6329 (= (char-after) ?{))
6330 (js2-set-face (1+ (match-beginning 2))
6331 (1- (match-end 2))
6332 'js2-jsdoc-type)
6333 (js2-set-face (match-beginning 2)
6334 (match-end 2)
6335 'js2-jsdoc-value)))
6336 (if (match-beginning 3)
6337 (js2-set-face (match-beginning 3)
6338 (match-end 3)
6339 'js2-jsdoc-value)))
6340
6341 (defun js2-highlight-jsdoc (ast)
6342 "Highlight doc comment tags."
6343 (let ((comments (js2-ast-root-comments ast))
6344 beg end)
6345 (save-excursion
6346 (dolist (node comments)
6347 (when (eq (js2-comment-node-format node) 'jsdoc)
6348 (setq beg (js2-node-abs-pos node)
6349 end (+ beg (js2-node-len node)))
6350 (save-restriction
6351 (narrow-to-region beg end)
6352 (dolist (re (list js2-jsdoc-param-tag-regexp
6353 js2-jsdoc-typed-tag-regexp
6354 js2-jsdoc-arg-tag-regexp
6355 js2-jsdoc-link-tag-regexp
6356 js2-jsdoc-see-tag-regexp
6357 js2-jsdoc-empty-tag-regexp))
6358 (goto-char beg)
6359 (while (re-search-forward re nil t)
6360 (js2-jsdoc-highlight-helper)))
6361 ;; simple highlighting for html tags
6362 (goto-char beg)
6363 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6364 (js2-set-face (match-beginning 1)
6365 (match-end 1)
6366 'js2-jsdoc-html-tag-delimiter)
6367 (js2-set-face (match-beginning 2)
6368 (match-end 2)
6369 'js2-jsdoc-html-tag-name)
6370 (js2-set-face (match-beginning 3)
6371 (match-end 3)
6372 'js2-jsdoc-html-tag-delimiter))))))))
6373
6374 (defun js2-highlight-assign-targets (node left right)
6375 "Highlight function properties and external variables."
6376 (let (leftpos end name)
6377 ;; highlight vars and props assigned function values
6378 (when (js2-function-node-p right)
6379 (cond
6380 ;; var foo = function() {...}
6381 ((js2-name-node-p left)
6382 (setq name left))
6383 ;; foo.bar.baz = function() {...}
6384 ((and (js2-prop-get-node-p left)
6385 (js2-name-node-p (js2-prop-get-node-right left)))
6386 (setq name (js2-prop-get-node-right left))))
6387 (when name
6388 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6389 (+ leftpos (js2-node-len name))
6390 'font-lock-function-name-face
6391 'record)))))
6392
6393 (defun js2-record-name-node (node)
6394 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6395 later. NODE must be a name node."
6396 (let (leftpos end)
6397 (push (list node js2-current-scope
6398 (setq leftpos (js2-node-abs-pos node))
6399 (setq end (+ leftpos (js2-node-len node))))
6400 js2-recorded-identifiers)))
6401
6402 (defun js2-highlight-undeclared-vars ()
6403 "After entire parse is finished, look for undeclared variable references.
6404 We have to wait until entire buffer is parsed, since JavaScript permits var
6405 decls to occur after they're used.
6406
6407 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6408 it is considered declared."
6409 (let (name)
6410 (dolist (entry js2-recorded-identifiers)
6411 (destructuring-bind (name-node scope pos end) entry
6412 (setq name (js2-name-node-name name-node))
6413 (unless (or (member name js2-global-externs)
6414 (member name js2-default-externs)
6415 (member name js2-additional-externs)
6416 (js2-get-defining-scope scope name))
6417 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6418 'js2-external-variable))))
6419 (setq js2-recorded-identifiers nil)))
6420
6421 (defun js2-set-default-externs ()
6422 "Set the value of `js2-default-externs' based on the various
6423 `js2-include-?-externs' variables."
6424 (setq js2-default-externs
6425 (append js2-ecma-262-externs
6426 (if js2-include-browser-externs js2-browser-externs)
6427 (if js2-include-rhino-externs js2-rhino-externs)
6428 (if js2-include-node-externs js2-node-externs)
6429 (if (or js2-include-browser-externs js2-include-node-externs)
6430 js2-typed-array-externs))))
6431
6432 ;;; IMenu support
6433
6434 ;; We currently only support imenu, but eventually should support speedbar and
6435 ;; possibly other browsing mechanisms.
6436
6437 ;; The basic strategy is to identify function assignment targets of the form
6438 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6439 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6440 ;; for imenu after parsing is finished.
6441
6442 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6443 ;; JavaScript, and the general problem is undecidable. However, several forms
6444 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6445 ;; include:
6446
6447 ;; function foo() -- function declaration
6448 ;; foo = function() -- function expression assigned to variable
6449 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6450 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6451 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6452 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6453 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6454 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6455 ;; function foo() {function bar() {...}} -- nested function
6456 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6457
6458 ;; This list boils down to a few forms that can be combined recursively.
6459 ;; Top-level named function declarations include both the left-hand (name)
6460 ;; and the right-hand (function value) expressions needed to produce an imenu
6461 ;; entry. The other "right-hand" forms we need to look for are:
6462 ;; - functions declared as props/getters/setters in object literals
6463 ;; - nested named function declarations
6464 ;; The "left-hand" expressions that functions can be assigned to include:
6465 ;; - local/global variables
6466 ;; - nested property-get expressions like a.b.c.d
6467 ;; - element gets like foo[10] or foo['bar'] where the index
6468 ;; expression can be trivially converted to a property name. They
6469 ;; effectively then become property gets.
6470
6471 ;; All the different definition types are canonicalized into the form
6472 ;; foo.bar.baz = position-of-function-keyword
6473
6474 ;; We need to build a trie-like structure for imenu. As an example,
6475 ;; consider the following JavaScript code:
6476
6477 ;; a = function() {...} // function at position 5
6478 ;; b = function() {...} // function at position 25
6479 ;; foo = function() {...} // function at position 100
6480 ;; foo.bar = function() {...} // function at position 200
6481 ;; foo.bar.baz = function() {...} // function at position 300
6482 ;; foo.bar.zab = function() {...} // function at position 400
6483
6484 ;; During parsing we accumulate an entry for each definition in
6485 ;; the variable `js2-imenu-recorder', like so:
6486
6487 ;; '((fn a 5)
6488 ;; (fn b 25)
6489 ;; (fn foo 100)
6490 ;; (fn foo bar 200)
6491 ;; (fn foo bar baz 300)
6492 ;; (fn foo bar zab 400))
6493
6494 ;; Where 'fn' is the respective function node.
6495 ;; After parsing these entries are merged into this alist-trie:
6496
6497 ;; '((a . 1)
6498 ;; (b . 2)
6499 ;; (foo (<definition> . 3)
6500 ;; (bar (<definition> . 6)
6501 ;; (baz . 100)
6502 ;; (zab . 200))))
6503
6504 ;; Note the wacky need for a <definition> name. The token can be anything
6505 ;; that isn't a valid JavaScript identifier, because you might make foo
6506 ;; a function and then start setting properties on it that are also functions.
6507
6508 (defun js2-prop-node-name (node)
6509 "Return the name of a node that may be a property-get/property-name.
6510 If NODE is not a valid name-node, string-node or integral number-node,
6511 returns nil. Otherwise returns the string name/value of the node."
6512 (cond
6513 ((js2-name-node-p node)
6514 (js2-name-node-name node))
6515 ((js2-string-node-p node)
6516 (js2-string-node-value node))
6517 ((and (js2-number-node-p node)
6518 (string-match "^[0-9]+$" (js2-number-node-value node)))
6519 (js2-number-node-value node))
6520 ((js2-this-node-p node)
6521 "this")))
6522
6523 (defun js2-node-qname-component (node)
6524 "Return the name of this node, if it contributes to a qname.
6525 Returns nil if the node doesn't contribute."
6526 (copy-sequence
6527 (or (js2-prop-node-name node)
6528 (if (and (js2-function-node-p node)
6529 (js2-function-node-name node))
6530 (js2-name-node-name (js2-function-node-name node))))))
6531
6532 (defun js2-record-imenu-entry (fn-node qname pos)
6533 "Add an entry to `js2-imenu-recorder'.
6534 FN-NODE should be the current item's function node.
6535
6536 Associate FN-NODE with its QNAME for later lookup.
6537 This is used in postprocessing the chain list. For each chain, we find
6538 the parent function, look up its qname, then prepend a copy of it to the chain."
6539 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6540 (unless js2-imenu-function-map
6541 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6542 (puthash fn-node qname js2-imenu-function-map))
6543
6544 (defun js2-record-imenu-functions (node &optional var)
6545 "Record function definitions for imenu.
6546 NODE is a function node or an object literal.
6547 VAR, if non-nil, is the expression that NODE is being assigned to.
6548 When passed arguments of wrong type, does nothing."
6549 (when js2-parse-ide-mode
6550 (let ((fun-p (js2-function-node-p node))
6551 qname left fname-node pos)
6552 (cond
6553 ;; non-anonymous function declaration?
6554 ((and fun-p
6555 (not var)
6556 (setq fname-node (js2-function-node-name node)))
6557 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6558 ;; for remaining forms, compute left-side tree branch first
6559 ((and var (setq qname (js2-compute-nested-prop-get var)))
6560 (cond
6561 ;; foo.bar.baz = function
6562 (fun-p
6563 (js2-record-imenu-entry node qname (js2-node-pos node)))
6564 ;; foo.bar.baz = object-literal
6565 ;; look for nested functions: {a: {b: function() {...} }}
6566 ((js2-object-node-p node)
6567 ;; Node position here is still absolute, since the parser
6568 ;; passes the assignment target and value expressions
6569 ;; to us before they are added as children of the assignment node.
6570 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6571
6572 (defun js2-compute-nested-prop-get (node)
6573 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6574 component nodes as a list. Otherwise return nil. Element-gets are treated
6575 as property-gets if the index expression is a string, or a positive integer."
6576 (let (left right head)
6577 (cond
6578 ((or (js2-name-node-p node)
6579 (js2-this-node-p node))
6580 (list node))
6581 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6582 ((js2-prop-get-node-p node) ; foo.bar
6583 (setq left (js2-prop-get-node-left node)
6584 right (js2-prop-get-node-right node))
6585 (if (setq head (js2-compute-nested-prop-get left))
6586 (nconc head (list right))))
6587 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6588 (setq left (js2-elem-get-node-target node)
6589 right (js2-elem-get-node-element node))
6590 (if (or (js2-string-node-p right) ; ['bar']
6591 (and (js2-number-node-p right) ; [10]
6592 (string-match "^[0-9]+$"
6593 (js2-number-node-value right))))
6594 (if (setq head (js2-compute-nested-prop-get left))
6595 (nconc head (list right))))))))
6596
6597 (defun js2-record-object-literal (node qname pos)
6598 "Recursively process an object literal looking for functions.
6599 NODE is an object literal that is the right-hand child of an assignment
6600 expression. QNAME is a list of nodes representing the assignment target,
6601 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6602 POS is the absolute position of the node.
6603 We do a depth-first traversal of NODE. For any functions we find,
6604 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6605 (let (left right prop-qname)
6606 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6607 (let ((left (js2-infix-node-left e))
6608 ;; Element positions are relative to the parent position.
6609 (pos (+ pos (js2-node-pos e))))
6610 (cond
6611 ;; foo: function() {...}
6612 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6613 (when (js2-prop-node-name left)
6614 ;; As a policy decision, we record the position of the property,
6615 ;; not the position of the `function' keyword, since the property
6616 ;; is effectively the name of the function.
6617 (js2-record-imenu-entry right (append qname (list left)) pos)))
6618 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6619 ((js2-object-node-p right)
6620 (js2-record-object-literal right
6621 (append qname (list (js2-infix-node-left e)))
6622 (+ pos (js2-node-pos right)))))))))
6623
6624 (defun js2-node-top-level-decl-p (node)
6625 "Return t if NODE's name is defined in the top-level scope.
6626 Also returns t if NODE's name is not defined in any scope, since it implies
6627 that it's an external variable, which must also be in the top-level scope."
6628 (let* ((name (js2-prop-node-name node))
6629 (this-scope (js2-node-get-enclosing-scope node))
6630 defining-scope)
6631 (cond
6632 ((js2-this-node-p node)
6633 nil)
6634 ((null this-scope)
6635 t)
6636 ((setq defining-scope (js2-get-defining-scope this-scope name))
6637 (js2-ast-root-p defining-scope))
6638 (t t))))
6639
6640 (defun js2-wrapper-function-p (node)
6641 "Return t if NODE is a function expression that's immediately invoked.
6642 NODE must be `js2-function-node'."
6643 (let ((parent (js2-node-parent node)))
6644 (or
6645 ;; function(){...}();
6646 (js2-call-node-p parent)
6647 (and (js2-paren-node-p parent)
6648 ;; (function(){...})();
6649 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6650 ;; (function(){...}).call(this);
6651 (and (js2-prop-get-node-p parent)
6652 (member (js2-name-node-name (js2-prop-get-node-right parent))
6653 '("call" "apply"))
6654 (js2-call-node-p (js2-node-parent parent))))))))
6655
6656 (defun js2-browse-postprocess-chains (entries)
6657 "Modify function-declaration name chains after parsing finishes.
6658 Some of the information is only available after the parse tree is complete.
6659 For instance, processing a nested scope requires a parent function node."
6660 (let (result head fn current-fn parent-qname qname p elem)
6661 (dolist (entry entries)
6662 ;; function node goes first
6663 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6664 ;; Examine head's defining scope:
6665 ;; Pre-processed chain, or top-level/external, keep as-is.
6666 (if (or (stringp head) (js2-node-top-level-decl-p head))
6667 (push chain result)
6668 (when (js2-this-node-p head)
6669 (setq chain (cdr chain))) ; discard this-node
6670 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6671 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6672 (when (eq parent-qname 'not-found)
6673 ;; anonymous function expressions are not recorded
6674 ;; during the parse, so we need to handle this case here
6675 (setq parent-qname
6676 (if (js2-wrapper-function-p fn)
6677 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6678 (if (js2-ast-root-p grandparent)
6679 nil
6680 (gethash grandparent js2-imenu-function-map 'skip)))
6681 'skip))
6682 (puthash fn parent-qname js2-imenu-function-map))
6683 (unless (eq parent-qname 'skip)
6684 ;; prefix parent fn qname to this chain.
6685 (let ((qname (append parent-qname chain)))
6686 (puthash current-fn (butlast qname) js2-imenu-function-map)
6687 (push qname result)))))))
6688 ;; finally replace each node in each chain with its name.
6689 (dolist (chain result)
6690 (setq p chain)
6691 (while p
6692 (if (js2-node-p (setq elem (car p)))
6693 (setcar p (js2-node-qname-component elem)))
6694 (setq p (cdr p))))
6695 result))
6696
6697 ;; Merge name chains into a trie-like tree structure of nested lists.
6698 ;; To simplify construction of the trie, we first build it out using the rule
6699 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6700 ;; [key, num-or-list]. The second element can be a number; if so, this key
6701 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6702 ;; associated with the key at this level.) Otherwise the second element is
6703 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6704 ;; a simple recursive formulation.
6705 ;;
6706 ;; js2-mode is building the data structure for imenu. The imenu documentation
6707 ;; claims that it's the structure above, but in practice it wants the children
6708 ;; at the same list level as the key for that level, which is how I've drawn
6709 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6710 ;; list wrapper around the children at each level.
6711 ;;
6712 ;; A completed nested imenu-alist entry looks like this:
6713 ;; '(("foo"
6714 ;; ("<definition>" . 7)
6715 ;; ("bar"
6716 ;; ("a" . 40)
6717 ;; ("b" . 60))))
6718 ;;
6719 ;; In particular, the documentation for `imenu--index-alist' says that
6720 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6721 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6722
6723 (defun js2-treeify (lst)
6724 "Convert (a b c d) to (a ((b ((c d)))))."
6725 (if (null (cddr lst)) ; list length <= 2
6726 lst
6727 (list (car lst) (list (js2-treeify (cdr lst))))))
6728
6729 (defun js2-build-alist-trie (chains trie)
6730 "Merge declaration name chains into a trie-like alist structure for imenu.
6731 CHAINS is the qname chain list produced during parsing. TRIE is a
6732 list of elements built up so far."
6733 (let (head tail pos branch kids)
6734 (dolist (chain chains)
6735 (setq head (car chain)
6736 tail (cdr chain)
6737 pos (if (numberp (car tail)) (car tail))
6738 branch (js2-find-if (lambda (n)
6739 (string= (car n) head))
6740 trie)
6741 kids (second branch))
6742 (cond
6743 ;; case 1: this key isn't in the trie yet
6744 ((null branch)
6745 (if trie
6746 (setcdr (last trie) (list (js2-treeify chain)))
6747 (setq trie (list (js2-treeify chain)))))
6748 ;; case 2: key is present with a single number entry: replace w/ list
6749 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6750 ;; ("<definition>" 20)))
6751 ((numberp kids)
6752 (setcar (cdr branch)
6753 (list (list "<definition-1>" kids)
6754 (if pos
6755 (list "<definition-2>" pos)
6756 (js2-treeify tail)))))
6757 ;; case 3: key is there (with kids), and we're a number entry
6758 (pos
6759 (setcdr (last kids)
6760 (list
6761 (list (format "<definition-%d>"
6762 (1+ (loop for kid in kids
6763 count (eq ?< (aref (car kid) 0)))))
6764 pos))))
6765 ;; case 4: key is there with kids, need to merge in our chain
6766 (t
6767 (js2-build-alist-trie (list tail) kids))))
6768 trie))
6769
6770 (defun js2-flatten-trie (trie)
6771 "Convert TRIE to imenu-format.
6772 Recurses through nodes, and for each one whose second element is a list,
6773 appends the list's flattened elements to the current element. Also
6774 changes the tails into conses. For instance, this pre-flattened trie
6775
6776 '(a ((b 20)
6777 (c ((d 30)
6778 (e 40)))))
6779
6780 becomes
6781
6782 '(a (b . 20)
6783 (c (d . 30)
6784 (e . 40)))
6785
6786 Note that the root of the trie has no key, just a list of chains.
6787 This is also true for the value of any key with multiple children,
6788 e.g. key 'c' in the example above."
6789 (cond
6790 ((listp (car trie))
6791 (mapcar #'js2-flatten-trie trie))
6792 (t
6793 (if (numberp (second trie))
6794 (cons (car trie) (second trie))
6795 ;; else pop list and append its kids
6796 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6797
6798 (defun js2-build-imenu-index ()
6799 "Turn `js2-imenu-recorder' into an imenu data structure."
6800 (unless (eq js2-imenu-recorder 'empty)
6801 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
6802 (result (js2-build-alist-trie chains nil)))
6803 (js2-flatten-trie result))))
6804
6805 (defun js2-test-print-chains (chains)
6806 "Print a list of qname chains.
6807 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
6808 i.e. one or more nodes, and an integer position as the list tail."
6809 (mapconcat (lambda (chain)
6810 (concat "("
6811 (mapconcat (lambda (elem)
6812 (if (js2-node-p elem)
6813 (or (js2-node-qname-component elem)
6814 "nil")
6815 (number-to-string elem)))
6816 chain
6817 " ")
6818 ")"))
6819 chains
6820 "\n"))
6821
6822 ;;; Parser
6823
6824 (defconst js2-version "1.8.5"
6825 "Version of JavaScript supported.")
6826
6827 (defmacro js2-record-face (face)
6828 "Record a style run of FACE for the current token."
6829 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
6830
6831 (defsubst js2-node-end (n)
6832 "Computes the absolute end of node N.
6833 Use with caution! Assumes `js2-node-pos' is -absolute-, which
6834 is only true until the node is added to its parent; i.e., while parsing."
6835 (+ (js2-node-pos n)
6836 (js2-node-len n)))
6837
6838 (defun js2-record-comment ()
6839 "Record a comment in `js2-scanned-comments'."
6840 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
6841 :format js2-ts-comment-type)
6842 js2-scanned-comments)
6843 (when js2-parse-ide-mode
6844 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
6845 'font-lock-doc-face
6846 'font-lock-comment-face))
6847 (when (memq js2-ts-comment-type '(html preprocessor))
6848 ;; Tell cc-engine the bounds of the comment.
6849 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
6850
6851 ;; This function is called depressingly often, so it should be fast.
6852 ;; Most of the time it's looking at the same token it peeked before.
6853 (defun js2-peek-token ()
6854 "Return the next token without consuming it.
6855 If previous token was consumed, calls scanner to get new token.
6856 If previous token was -not- consumed, returns it (idempotent).
6857
6858 This function will not return a newline (js2-EOL) - instead, it
6859 gobbles newlines until it finds a non-newline token, and flags
6860 that token as appearing just after a newline.
6861
6862 This function will also not return a js2-COMMENT. Instead, it
6863 records comments found in `js2-scanned-comments'. If the token
6864 returned by this function immediately follows a jsdoc comment,
6865 the token is flagged as such.
6866
6867 Note that this function always returned the un-flagged token!
6868 The flags, if any, are saved in `js2-current-flagged-token'."
6869 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
6870 js2-current-token ; most common case - return already-peeked token
6871 (let ((tt (js2-get-token)) ; call scanner
6872 saw-eol
6873 face)
6874 ;; process comments and whitespace
6875 (while (or (= tt js2-EOL)
6876 (= tt js2-COMMENT))
6877 (if (= tt js2-EOL)
6878 (setq saw-eol t)
6879 (setq saw-eol nil)
6880 (if js2-record-comments
6881 (js2-record-comment)))
6882 (setq tt (js2-get-token))) ; call scanner
6883 (setq js2-current-token tt
6884 js2-current-flagged-token (if saw-eol
6885 (logior tt js2-ti-after-eol)
6886 tt))
6887 ;; perform lexical fontification as soon as token is scanned
6888 (when js2-parse-ide-mode
6889 (cond
6890 ((minusp tt)
6891 (js2-record-face 'js2-error))
6892 ((setq face (aref js2-kwd-tokens tt))
6893 (js2-record-face face))
6894 ((and (= tt js2-NAME)
6895 (equal js2-ts-string "undefined"))
6896 (js2-record-face 'font-lock-constant-face))))
6897 tt))) ; return unflagged token
6898
6899 (defun js2-peek-flagged-token ()
6900 "Return the current token along with any flags set for it."
6901 (js2-peek-token)
6902 js2-current-flagged-token)
6903
6904 (defsubst js2-consume-token ()
6905 (setq js2-current-flagged-token js2-EOF))
6906
6907 (defun js2-next-token ()
6908 (prog1
6909 (js2-peek-token)
6910 (js2-consume-token)))
6911
6912 (defun js2-next-flagged-token ()
6913 (js2-peek-token)
6914 (prog1 js2-current-flagged-token
6915 (js2-consume-token)))
6916
6917 (defun js2-match-token (match)
6918 "Consume and return t if next token matches MATCH, a bytecode.
6919 Returns nil and consumes nothing if MATCH is not the next token."
6920 (if (/= (js2-peek-token) match)
6921 nil
6922 (js2-consume-token)
6923 t))
6924
6925 (defun js2-match-contextual-kwd (name)
6926 "Consume and return t if next token is `js2-NAME', and its
6927 string is NAME. Returns nil and does nothing otherwise."
6928 (if (or (/= (js2-peek-token) js2-NAME)
6929 (not (string= js2-ts-string name)))
6930 nil
6931 (js2-consume-token)
6932 (js2-record-face 'font-lock-keyword-face)
6933 t))
6934
6935 (defun js2-valid-prop-name-token (tt)
6936 (or (= tt js2-NAME)
6937 (when (and js2-allow-keywords-as-property-names
6938 (plusp tt)
6939 (aref js2-kwd-tokens tt))
6940 (js2-save-name-token-data js2-token-beg (js2-token-name tt))
6941 t)))
6942
6943 (defun js2-match-prop-name ()
6944 "Consume token and return t if next token is a valid property name.
6945 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
6946 is non-nil and it's a keyword token."
6947 (if (js2-valid-prop-name-token (js2-peek-token))
6948 (progn
6949 (js2-consume-token)
6950 t)
6951 nil))
6952
6953 (defun js2-must-match-prop-name (msg-id &optional pos len)
6954 (if (js2-match-prop-name)
6955 t
6956 (js2-report-error msg-id nil pos len)
6957 nil))
6958
6959 (defun js2-peek-token-or-eol ()
6960 "Return js2-EOL if the current token immediately follows a newline.
6961 Else returns the current token. Used in situations where we don't
6962 consider certain token types valid if they are preceded by a newline.
6963 One example is the postfix ++ or -- operator, which has to be on the
6964 same line as its operand."
6965 (let ((tt (js2-peek-token)))
6966 ;; Check for last peeked token flags
6967 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
6968 js2-EOL
6969 tt)))
6970
6971 (defun js2-set-check-for-label ()
6972 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
6973 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
6974
6975 (defun js2-must-match (token msg-id &optional pos len)
6976 "Match next token to token code TOKEN, or record a syntax error.
6977 MSG-ID is the error message to report if the match fails.
6978 Returns t on match, nil if no match."
6979 (if (js2-match-token token)
6980 t
6981 (js2-report-error msg-id nil pos len)
6982 nil))
6983
6984 (defsubst js2-inside-function ()
6985 (plusp js2-nesting-of-function))
6986
6987 (defun js2-set-requires-activation ()
6988 (if (js2-function-node-p js2-current-script-or-fn)
6989 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
6990
6991 (defun js2-check-activation-name (name token)
6992 (when (js2-inside-function)
6993 ;; skip language-version 1.2 check from Rhino
6994 (if (or (string= "arguments" name)
6995 (and js2-compiler-activation-names ; only used in codegen
6996 (gethash name js2-compiler-activation-names)))
6997 (js2-set-requires-activation))))
6998
6999 (defun js2-set-is-generator ()
7000 (if (js2-function-node-p js2-current-script-or-fn)
7001 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7002
7003 (defun js2-must-have-xml ()
7004 (unless js2-compiler-xml-available
7005 (js2-report-error "msg.XML.not.available")))
7006
7007 (defun js2-push-scope (scope)
7008 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7009 (assert (js2-scope-p scope))
7010 (assert (null (js2-scope-parent-scope scope)))
7011 (assert (not (eq js2-current-scope scope)))
7012 (setf (js2-scope-parent-scope scope) js2-current-scope
7013 js2-current-scope scope))
7014
7015 (defsubst js2-pop-scope ()
7016 (setq js2-current-scope
7017 (js2-scope-parent-scope js2-current-scope)))
7018
7019 (defun js2-enter-loop (loop-node)
7020 (push loop-node js2-loop-set)
7021 (push loop-node js2-loop-and-switch-set)
7022 (js2-push-scope loop-node)
7023 ;; Tell the current labeled statement (if any) its statement,
7024 ;; and set the jump target of the first label to the loop.
7025 ;; These are used in `js2-parse-continue' to verify that the
7026 ;; continue target is an actual labeled loop. (And for codegen.)
7027 (when js2-labeled-stmt
7028 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7029 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7030 js2-labeled-stmt))) loop-node)))
7031
7032 (defun js2-exit-loop ()
7033 (pop js2-loop-set)
7034 (pop js2-loop-and-switch-set)
7035 (js2-pop-scope))
7036
7037 (defsubst js2-enter-switch (switch-node)
7038 (push switch-node js2-loop-and-switch-set))
7039
7040 (defsubst js2-exit-switch ()
7041 (pop js2-loop-and-switch-set))
7042
7043 (defun js2-parse (&optional buf cb)
7044 "Tell the js2 parser to parse a region of JavaScript.
7045
7046 BUF is a buffer or buffer name containing the code to parse.
7047 Call `narrow-to-region' first to parse only part of the buffer.
7048
7049 The returned AST root node is given some additional properties:
7050 `node-count' - total number of nodes in the AST
7051 `buffer' - BUF. The buffer it refers to may change or be killed,
7052 so the value is not necessarily reliable.
7053
7054 An optional callback CB can be specified to report parsing
7055 progress. If `(functionp CB)' returns t, it will be called with
7056 the current line number once before parsing begins, then again
7057 each time the lexer reaches a new line number.
7058
7059 CB can also be a list of the form `(symbol cb ...)' to specify
7060 multiple callbacks with different criteria. Each symbol is a
7061 criterion keyword, and the following element is the callback to
7062 call
7063
7064 :line - called whenever the line number changes
7065 :token - called for each new token consumed
7066
7067 The list of criteria could be extended to include entering or
7068 leaving a statement, an expression, or a function definition."
7069 (if (and cb (not (functionp cb)))
7070 (error "criteria callbacks not yet implemented"))
7071 (let ((inhibit-point-motion-hooks t)
7072 (js2-compiler-xml-available (>= js2-language-version 160))
7073 ;; This is a recursive-descent parser, so give it a big stack.
7074 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7075 (max-specpdl-size (max max-specpdl-size 3000))
7076 (case-fold-search nil)
7077 ast)
7078 (message nil) ; clear any error message from previous parse
7079 (with-current-buffer (or buf (current-buffer))
7080 (setq js2-scanned-comments nil
7081 js2-parsed-errors nil
7082 js2-parsed-warnings nil
7083 js2-imenu-recorder nil
7084 js2-imenu-function-map nil
7085 js2-label-set nil)
7086 (js2-init-scanner)
7087 (setq ast (with-silent-modifications
7088 (js2-do-parse)))
7089 (unless js2-ts-hit-eof
7090 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7091 (setf (js2-ast-root-errors ast) js2-parsed-errors
7092 (js2-ast-root-warnings ast) js2-parsed-warnings)
7093 ;; if we didn't find any declarations, put a dummy in this list so we
7094 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7095 (unless js2-imenu-recorder
7096 (setq js2-imenu-recorder 'empty))
7097 (run-hooks 'js2-parse-finished-hook)
7098 ast)))
7099
7100 ;; Corresponds to Rhino's Parser.parse() method.
7101 (defun js2-do-parse ()
7102 "Parse current buffer starting from current point.
7103 Scanner should be initialized."
7104 (let ((pos js2-ts-cursor)
7105 (end js2-ts-cursor) ; in case file is empty
7106 root n tt)
7107 ;; initialize buffer-local parsing vars
7108 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7109 js2-current-script-or-fn root
7110 js2-current-scope root
7111 js2-current-flagged-token js2-EOF
7112 js2-nesting-of-function 0
7113 js2-labeled-stmt nil
7114 js2-recorded-identifiers nil) ; for js2-highlight
7115 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7116 (if (= tt js2-FUNCTION)
7117 (progn
7118 (js2-consume-token)
7119 (setq n (js2-parse-function (if js2-called-by-compile-function
7120 'FUNCTION_EXPRESSION
7121 'FUNCTION_STATEMENT))))
7122 ;; not a function - parse a statement
7123 (setq n (js2-parse-statement)))
7124 ;; add function or statement to script
7125 (setq end (js2-node-end n))
7126 (js2-block-node-push root n))
7127 ;; add comments to root in lexical order
7128 (when js2-scanned-comments
7129 ;; if we find a comment beyond end of normal kids, use its end
7130 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7131 (dolist (comment js2-scanned-comments)
7132 (push comment (js2-ast-root-comments root))
7133 (js2-node-add-children root comment)))
7134 (setf (js2-node-len root) (- end pos))
7135 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7136 ;; Give extensions a chance to muck with things before highlighting starts.
7137 (let ((js2-additional-externs js2-additional-externs))
7138 (save-excursion
7139 (dolist (callback js2-post-parse-callbacks)
7140 (funcall callback)))
7141 (js2-highlight-undeclared-vars))
7142 root))
7143
7144 (defun js2-function-parser ()
7145 (js2-consume-token)
7146 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7147
7148 (defun js2-parse-function-closure-body (fn-node)
7149 "Parse a JavaScript 1.8 function closure body."
7150 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7151 (if js2-ts-hit-eof
7152 (js2-report-error "msg.no.brace.body" nil
7153 (js2-node-pos fn-node)
7154 (- js2-ts-cursor (js2-node-pos fn-node)))
7155 (js2-node-add-children fn-node
7156 (setf (js2-function-node-body fn-node)
7157 (js2-parse-expr t))))))
7158
7159 (defun js2-parse-function-body (fn-node)
7160 (js2-must-match js2-LC "msg.no.brace.body"
7161 (js2-node-pos fn-node)
7162 (- js2-ts-cursor (js2-node-pos fn-node)))
7163 (let ((pos js2-token-beg) ; LC position
7164 (pn (make-js2-block-node)) ; starts at LC position
7165 tt
7166 end)
7167 (incf js2-nesting-of-function)
7168 (unwind-protect
7169 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7170 (= tt js2-EOF)
7171 (= tt js2-RC)))
7172 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7173 (js2-parse-statement)
7174 (js2-consume-token)
7175 (js2-parse-function 'FUNCTION_STATEMENT))))
7176 (decf js2-nesting-of-function))
7177 (setq end js2-token-end) ; assume no curly and leave at current token
7178 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7179 (setq end js2-token-end))
7180 (setf (js2-node-pos pn) pos
7181 (js2-node-len pn) (- end pos))
7182 (setf (js2-function-node-body fn-node) pn)
7183 (js2-node-add-children fn-node pn)
7184 pn))
7185
7186 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7187 "Declare and fontify destructuring parameters inside NODE.
7188 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7189 (cond
7190 ((js2-name-node-p node)
7191 (let (leftpos)
7192 (js2-define-symbol decl-type (js2-name-node-name node)
7193 node ignore-not-in-block)
7194 (when face
7195 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7196 (+ leftpos (js2-node-len node))
7197 face 'record))))
7198 ((js2-object-node-p node)
7199 (dolist (elem (js2-object-node-elems node))
7200 (js2-define-destruct-symbols
7201 (if (js2-object-prop-node-p elem)
7202 (js2-object-prop-node-right elem)
7203 ;; abbreviated destructuring {a, b}
7204 elem)
7205 decl-type face ignore-not-in-block)))
7206 ((js2-array-node-p node)
7207 (dolist (elem (js2-array-node-elems node))
7208 (when elem
7209 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7210 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7211 (js2-node-len node)))))
7212
7213 (defun js2-parse-function-params (fn-node pos)
7214 (if (js2-match-token js2-RP)
7215 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7216 (let (params len param default-found rest-param-at)
7217 (loop for tt = (js2-peek-token)
7218 do
7219 (cond
7220 ;; destructuring param
7221 ((or (= tt js2-LB) (= tt js2-LC))
7222 (when default-found
7223 (js2-report-error "msg.no.default.after.default.param"))
7224 (setq param (js2-parse-destruct-primary-expr))
7225 (js2-define-destruct-symbols param
7226 js2-LP
7227 'js2-function-param)
7228 (push param params))
7229 ;; variable name
7230 (t
7231 (when (and (>= js2-language-version 200)
7232 (js2-match-token js2-TRIPLEDOT)
7233 (not rest-param-at))
7234 ;; to report errors if there are more parameters
7235 (setq rest-param-at (length params)))
7236 (js2-must-match js2-NAME "msg.no.parm")
7237 (js2-record-face 'js2-function-param)
7238 (setq param (js2-create-name-node))
7239 (js2-define-symbol js2-LP js2-ts-string param)
7240 ;; default parameter value
7241 (when (or (and default-found
7242 (not rest-param-at)
7243 (js2-must-match js2-ASSIGN
7244 "msg.no.default.after.default.param"
7245 (js2-node-pos param)
7246 (js2-node-len param)))
7247 (and (>= js2-language-version 200)
7248 (js2-match-token js2-ASSIGN)))
7249 (let* ((pos (js2-node-pos param))
7250 (tt js2-current-token)
7251 (op-pos (- js2-token-beg pos))
7252 (left param)
7253 (right (js2-parse-assign-expr))
7254 (len (- (js2-node-end right) pos)))
7255 (setq param (make-js2-assign-node
7256 :type tt :pos pos :len len :op-pos op-pos
7257 :left left :right right)
7258 default-found t)
7259 (js2-node-add-children param left right)))
7260 (push param params)))
7261 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7262 (js2-report-error "msg.param.after.rest" nil
7263 (js2-node-pos param) (js2-node-len param)))
7264 while
7265 (js2-match-token js2-COMMA))
7266 (when (js2-must-match js2-RP "msg.no.paren.after.parms")
7267 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7268 (when rest-param-at
7269 (setf (js2-function-node-rest-p fn-node) t))
7270 (dolist (p params)
7271 (js2-node-add-children fn-node p)
7272 (push p (js2-function-node-params fn-node))))))
7273
7274 (defun js2-check-inconsistent-return-warning (fn-node name)
7275 "Possibly show inconsistent-return warning.
7276 Last token scanned is the close-curly for the function body."
7277 (when (and js2-mode-show-strict-warnings
7278 js2-strict-inconsistent-return-warning
7279 (not (js2-has-consistent-return-usage
7280 (js2-function-node-body fn-node))))
7281 ;; Have it extend from close-curly to bol or beginning of block.
7282 (let ((pos (save-excursion
7283 (goto-char js2-token-end)
7284 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7285 (point-at-bol))))
7286 (end js2-token-end))
7287 (if (plusp (js2-name-node-length name))
7288 (js2-add-strict-warning "msg.no.return.value"
7289 (js2-name-node-name name) pos end)
7290 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7291
7292 (defun js2-parse-function (function-type)
7293 "Function parser. FUNCTION-TYPE is a symbol."
7294 (let ((pos js2-token-beg) ; start of 'function' keyword
7295 name name-beg name-end fn-node lp
7296 (synthetic-type function-type)
7297 member-expr-node)
7298 ;; parse function name, expression, or non-name (anonymous)
7299 (cond
7300 ;; function foo(...)
7301 ((js2-match-token js2-NAME)
7302 (setq name (js2-create-name-node t)
7303 name-beg js2-token-beg
7304 name-end js2-token-end)
7305 (unless (js2-match-token js2-LP)
7306 (when js2-allow-member-expr-as-function-name
7307 ;; function foo.bar(...)
7308 (setq member-expr-node name
7309 name nil
7310 member-expr-node (js2-parse-member-expr-tail
7311 nil member-expr-node)))
7312 (js2-must-match js2-LP "msg.no.paren.parms")))
7313 ((js2-match-token js2-LP)
7314 nil) ; anonymous function: leave name as null
7315 (t
7316 ;; function random-member-expr(...)
7317 (when js2-allow-member-expr-as-function-name
7318 ;; Note that memberExpr can not start with '(' like
7319 ;; in function (1+2).toString(), because 'function (' already
7320 ;; processed as anonymous function
7321 (setq member-expr-node (js2-parse-member-expr)))
7322 (js2-must-match js2-LP "msg.no.paren.parms")))
7323 (if (= js2-current-token js2-LP) ; eventually matched LP?
7324 (setq lp js2-token-beg))
7325 (if member-expr-node
7326 (progn
7327 (setq synthetic-type 'FUNCTION_EXPRESSION)
7328 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7329 (if name
7330 (js2-set-face name-beg name-end
7331 'font-lock-function-name-face 'record)))
7332 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7333 (plusp (js2-name-node-length name)))
7334 ;; Function statements define a symbol in the enclosing scope
7335 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7336 (setf fn-node (make-js2-function-node :pos pos
7337 :name name
7338 :form function-type
7339 :lp (if lp (- lp pos))))
7340 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7341 ;; 1. Nested functions are not affected by the dynamic scope flag
7342 ;; as dynamic scope is already a parent of their scope.
7343 ;; 2. Functions defined under the with statement also immune to
7344 ;; this setup, in which case dynamic scope is ignored in favor
7345 ;; of the with object.
7346 (setf (js2-function-node-ignore-dynamic fn-node) t))
7347 ;; dynamically bind all the per-function variables
7348 (let ((js2-current-script-or-fn fn-node)
7349 (js2-current-scope fn-node)
7350 (js2-nesting-of-with 0)
7351 (js2-end-flags 0)
7352 js2-label-set
7353 js2-loop-set
7354 js2-loop-and-switch-set)
7355 (js2-parse-function-params fn-node pos)
7356 (if (and (>= js2-language-version 180)
7357 (/= (js2-peek-token) js2-LC))
7358 (js2-parse-function-closure-body fn-node)
7359 (js2-parse-function-body fn-node))
7360 (if name
7361 (js2-node-add-children fn-node name))
7362 (js2-check-inconsistent-return-warning fn-node name)
7363 ;; Function expressions define a name only in the body of the
7364 ;; function, and only if not hidden by a parameter name
7365 (if (and name
7366 (eq synthetic-type 'FUNCTION_EXPRESSION)
7367 (null (js2-scope-get-symbol js2-current-scope
7368 (js2-name-node-name name))))
7369 (js2-define-symbol js2-FUNCTION
7370 (js2-name-node-name name)
7371 fn-node))
7372 (if (and name
7373 (not (eq function-type 'FUNCTION_EXPRESSION)))
7374 (js2-record-imenu-functions fn-node)))
7375 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7376 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7377 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7378 ;; We wait until after parsing the function to set its parent scope,
7379 ;; since `js2-define-symbol' needs the defining-scope check to stop
7380 ;; at the function boundary when checking for redeclarations.
7381 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7382 fn-node))
7383
7384 (defun js2-parse-statements (&optional parent)
7385 "Parse a statement list. Last token consumed must be js2-LC.
7386
7387 PARENT can be a `js2-block-node', in which case the statements are
7388 appended to PARENT. Otherwise a new `js2-block-node' is created
7389 and returned.
7390
7391 This function does not match the closing js2-RC: the caller
7392 matches the RC so it can provide a suitable error message if not
7393 matched. This means it's up to the caller to set the length of
7394 the node to include the closing RC. The node start pos is set to
7395 the absolute buffer start position, and the caller should fix it
7396 up to be relative to the parent node. All children of this block
7397 node are given relative start positions and correct lengths."
7398 (let ((pn (or parent (make-js2-block-node)))
7399 tt)
7400 (setf (js2-node-pos pn) js2-token-beg)
7401 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7402 (/= tt js2-RC))
7403 (js2-block-node-push pn (js2-parse-statement)))
7404 pn))
7405
7406 (defun js2-parse-statement ()
7407 (let (tt pn beg end)
7408 ;; coarse-grained user-interrupt check - needs work
7409 (and js2-parse-interruptable-p
7410 (zerop (% (incf js2-parse-stmt-count)
7411 js2-statements-per-pause))
7412 (input-pending-p)
7413 (throw 'interrupted t))
7414 (setq pn (js2-statement-helper))
7415 ;; no-side-effects warning check
7416 (unless (js2-node-has-side-effects pn)
7417 (setq end (js2-node-end pn))
7418 (save-excursion
7419 (goto-char end)
7420 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7421 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7422 pn))
7423
7424 ;; These correspond to the switch cases in Parser.statementHelper
7425 (defconst js2-parsers
7426 (let ((parsers (make-vector js2-num-tokens
7427 #'js2-parse-expr-stmt)))
7428 (aset parsers js2-BREAK #'js2-parse-break)
7429 (aset parsers js2-CONST #'js2-parse-const-var)
7430 (aset parsers js2-CONTINUE #'js2-parse-continue)
7431 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7432 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7433 (aset parsers js2-DO #'js2-parse-do)
7434 (aset parsers js2-FOR #'js2-parse-for)
7435 (aset parsers js2-FUNCTION #'js2-function-parser)
7436 (aset parsers js2-IF #'js2-parse-if)
7437 (aset parsers js2-LC #'js2-parse-block)
7438 (aset parsers js2-LET #'js2-parse-let-stmt)
7439 (aset parsers js2-NAME #'js2-parse-name-or-label)
7440 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7441 (aset parsers js2-SEMI #'js2-parse-semi)
7442 (aset parsers js2-SWITCH #'js2-parse-switch)
7443 (aset parsers js2-THROW #'js2-parse-throw)
7444 (aset parsers js2-TRY #'js2-parse-try)
7445 (aset parsers js2-VAR #'js2-parse-const-var)
7446 (aset parsers js2-WHILE #'js2-parse-while)
7447 (aset parsers js2-WITH #'js2-parse-with)
7448 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7449 parsers)
7450 "A vector mapping token types to parser functions.")
7451
7452 (defun js2-parse-warn-missing-semi (beg end)
7453 (and js2-mode-show-strict-warnings
7454 js2-strict-missing-semi-warning
7455 (js2-add-strict-warning
7456 "msg.missing.semi" nil
7457 ;; back up to beginning of statement or line
7458 (max beg (save-excursion
7459 (goto-char end)
7460 (point-at-bol)))
7461 end)))
7462
7463 (defconst js2-no-semi-insertion
7464 (list js2-IF
7465 js2-SWITCH
7466 js2-WHILE
7467 js2-DO
7468 js2-FOR
7469 js2-TRY
7470 js2-WITH
7471 js2-LC
7472 js2-ERROR
7473 js2-SEMI
7474 js2-FUNCTION)
7475 "List of tokens that don't do automatic semicolon insertion.")
7476
7477 (defconst js2-autoinsert-semi-and-warn
7478 (list js2-ERROR js2-EOF js2-RC))
7479
7480 (defun js2-statement-helper ()
7481 (let* ((tt (js2-peek-token))
7482 (first-tt tt)
7483 (beg js2-token-beg)
7484 (parser (if (= tt js2-ERROR)
7485 #'js2-parse-semi
7486 (aref js2-parsers tt)))
7487 pn
7488 tt-flagged)
7489 ;; If the statement is set, then it's been told its label by now.
7490 (and js2-labeled-stmt
7491 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7492 (setq js2-labeled-stmt nil))
7493 (setq pn (funcall parser))
7494 ;; Don't do auto semi insertion for certain statement types.
7495 (unless (or (memq first-tt js2-no-semi-insertion)
7496 (js2-labeled-stmt-node-p pn))
7497 (js2-auto-insert-semicolon pn))
7498 pn))
7499
7500 (defun js2-auto-insert-semicolon (pn)
7501 (let* ((tt-flagged (js2-peek-flagged-token))
7502 (tt (logand tt-flagged js2-clear-ti-mask))
7503 (pos (js2-node-pos pn)))
7504 (cond
7505 ((= tt js2-SEMI)
7506 ;; Consume ';' as a part of expression
7507 (js2-consume-token)
7508 ;; extend the node bounds to include the semicolon.
7509 (setf (js2-node-len pn) (- js2-token-end pos)))
7510 ((memq tt js2-autoinsert-semi-and-warn)
7511 ;; Autoinsert ;
7512 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7513 (t
7514 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7515 ;; Report error if no EOL or autoinsert ';' otherwise
7516 (js2-report-error "msg.no.semi.stmt")
7517 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7518
7519 (defun js2-parse-condition ()
7520 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7521 The parens are discarded and the expression node is returned.
7522 The `pos' field of the return value is set to an absolute position
7523 that must be fixed up by the caller.
7524 Return value is a list (EXPR LP RP), with absolute paren positions."
7525 (let (pn lp rp)
7526 (if (js2-must-match js2-LP "msg.no.paren.cond")
7527 (setq lp js2-token-beg))
7528 (setq pn (js2-parse-expr))
7529 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7530 (setq rp js2-token-beg))
7531 ;; Report strict warning on code like "if (a = 7) ..."
7532 (if (and js2-strict-cond-assign-warning
7533 (js2-assign-node-p pn))
7534 (js2-add-strict-warning "msg.equal.as.assign" nil
7535 (js2-node-pos pn)
7536 (+ (js2-node-pos pn)
7537 (js2-node-len pn))))
7538 (list pn lp rp)))
7539
7540 (defun js2-parse-if ()
7541 "Parser for if-statement. Last matched token must be js2-IF."
7542 (let ((pos js2-token-beg)
7543 cond if-true if-false else-pos end pn)
7544 (js2-consume-token)
7545 (setq cond (js2-parse-condition)
7546 if-true (js2-parse-statement)
7547 if-false (if (js2-match-token js2-ELSE)
7548 (progn
7549 (setq else-pos (- js2-token-beg pos))
7550 (js2-parse-statement)))
7551 end (js2-node-end (or if-false if-true))
7552 pn (make-js2-if-node :pos pos
7553 :len (- end pos)
7554 :condition (car cond)
7555 :then-part if-true
7556 :else-part if-false
7557 :else-pos else-pos
7558 :lp (js2-relpos (second cond) pos)
7559 :rp (js2-relpos (third cond) pos)))
7560 (js2-node-add-children pn (car cond) if-true if-false)
7561 pn))
7562
7563 (defun js2-parse-switch ()
7564 "Parser for if-statement. Last matched token must be js2-SWITCH."
7565 (let ((pos js2-token-beg)
7566 tt pn discriminant has-default case-expr case-node
7567 case-pos cases stmt lp rp)
7568 (js2-consume-token)
7569 (if (js2-must-match js2-LP "msg.no.paren.switch")
7570 (setq lp js2-token-beg))
7571 (setq discriminant (js2-parse-expr)
7572 pn (make-js2-switch-node :discriminant discriminant
7573 :pos pos
7574 :lp (js2-relpos lp pos)))
7575 (js2-node-add-children pn discriminant)
7576 (js2-enter-switch pn)
7577 (unwind-protect
7578 (progn
7579 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7580 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7581 (js2-must-match js2-LC "msg.no.brace.switch")
7582 (catch 'break
7583 (while t
7584 (setq tt (js2-next-token)
7585 case-pos js2-token-beg)
7586 (cond
7587 ((= tt js2-RC)
7588 (setf (js2-node-len pn) (- js2-token-end pos))
7589 (throw 'break nil)) ; done
7590 ((= tt js2-CASE)
7591 (setq case-expr (js2-parse-expr))
7592 (js2-must-match js2-COLON "msg.no.colon.case"))
7593 ((= tt js2-DEFAULT)
7594 (if has-default
7595 (js2-report-error "msg.double.switch.default"))
7596 (setq has-default t
7597 case-expr nil)
7598 (js2-must-match js2-COLON "msg.no.colon.case"))
7599 (t
7600 (js2-report-error "msg.bad.switch")
7601 (throw 'break nil)))
7602 (setq case-node (make-js2-case-node :pos case-pos
7603 :len (- js2-token-end case-pos)
7604 :expr case-expr))
7605 (js2-node-add-children case-node case-expr)
7606 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7607 (/= tt js2-CASE)
7608 (/= tt js2-DEFAULT)
7609 (/= tt js2-EOF))
7610 (setf stmt (js2-parse-statement)
7611 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7612 (js2-block-node-push case-node stmt))
7613 (push case-node cases)))
7614 ;; add cases last, as pushing reverses the order to be correct
7615 (dolist (kid cases)
7616 (js2-node-add-children pn kid)
7617 (push kid (js2-switch-node-cases pn)))
7618 pn) ; return value
7619 (js2-exit-switch))))
7620
7621 (defun js2-parse-while ()
7622 "Parser for while-statement. Last matched token must be js2-WHILE."
7623 (let ((pos js2-token-beg)
7624 (pn (make-js2-while-node))
7625 cond body)
7626 (js2-consume-token)
7627 (js2-enter-loop pn)
7628 (unwind-protect
7629 (progn
7630 (setf cond (js2-parse-condition)
7631 (js2-while-node-condition pn) (car cond)
7632 body (js2-parse-statement)
7633 (js2-while-node-body pn) body
7634 (js2-node-len pn) (- (js2-node-end body) pos)
7635 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7636 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7637 (js2-node-add-children pn body (car cond)))
7638 (js2-exit-loop))
7639 pn))
7640
7641 (defun js2-parse-do ()
7642 "Parser for do-statement. Last matched token must be js2-DO."
7643 (let ((pos js2-token-beg)
7644 (pn (make-js2-do-node))
7645 cond body end)
7646 (js2-consume-token)
7647 (js2-enter-loop pn)
7648 (unwind-protect
7649 (progn
7650 (setq body (js2-parse-statement))
7651 (js2-must-match js2-WHILE "msg.no.while.do")
7652 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7653 cond (js2-parse-condition)
7654 (js2-do-node-condition pn) (car cond)
7655 (js2-do-node-body pn) body
7656 end js2-ts-cursor
7657 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7658 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7659 (js2-node-add-children pn (car cond) body))
7660 (js2-exit-loop))
7661 ;; Always auto-insert semicolon to follow SpiderMonkey:
7662 ;; It is required by ECMAScript but is ignored by the rest of
7663 ;; world; see bug 238945
7664 (if (js2-match-token js2-SEMI)
7665 (setq end js2-ts-cursor))
7666 (setf (js2-node-len pn) (- end pos))
7667 pn))
7668
7669 (defun js2-parse-for ()
7670 "Parser for for-statement. Last matched token must be js2-FOR.
7671 Parses for, for-in, and for each-in statements."
7672 (let ((for-pos js2-token-beg)
7673 pn is-for-each is-for-in-or-of is-for-of
7674 in-pos each-pos tmp-pos
7675 init ; Node init is also foo in 'foo in object'
7676 cond ; Node cond is also object in 'foo in object'
7677 incr ; 3rd section of for-loop initializer
7678 body tt lp rp)
7679 (js2-consume-token)
7680 ;; See if this is a for each () instead of just a for ()
7681 (when (js2-match-token js2-NAME)
7682 (if (string= "each" js2-ts-string)
7683 (progn
7684 (setq is-for-each t
7685 each-pos (- js2-token-beg for-pos)) ; relative
7686 (js2-record-face 'font-lock-keyword-face))
7687 (js2-report-error "msg.no.paren.for")))
7688 (if (js2-must-match js2-LP "msg.no.paren.for")
7689 (setq lp (- js2-token-beg for-pos)))
7690 (setq tt (js2-peek-token))
7691 ;; 'for' makes local scope
7692 (js2-push-scope (make-js2-scope))
7693 (unwind-protect
7694 ;; parse init clause
7695 (let ((js2-in-for-init t)) ; set as dynamic variable
7696 (cond
7697 ((= tt js2-SEMI)
7698 (setq init (make-js2-empty-expr-node)))
7699 ((or (= tt js2-VAR) (= tt js2-LET))
7700 (js2-consume-token)
7701 (setq init (js2-parse-variables tt js2-token-beg)))
7702 (t
7703 (setq init (js2-parse-expr)))))
7704 (if (or (js2-match-token js2-IN)
7705 (and (>= js2-language-version 200)
7706 (js2-match-contextual-kwd "of")
7707 (setq is-for-of t)))
7708 (setq is-for-in-or-of t
7709 in-pos (- js2-token-beg for-pos)
7710 ;; scope of iteration target object is not the scope we've created above.
7711 ;; stash current scope temporary.
7712 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7713 (js2-parse-expr))) ; object over which we're iterating
7714 ;; else ordinary for loop - parse cond and incr
7715 (js2-must-match js2-SEMI "msg.no.semi.for")
7716 (setq cond (if (= (js2-peek-token) js2-SEMI)
7717 (make-js2-empty-expr-node) ; no loop condition
7718 (js2-parse-expr)))
7719 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7720 (setq tmp-pos js2-token-end
7721 incr (if (= (js2-peek-token) js2-RP)
7722 (make-js2-empty-expr-node :pos tmp-pos)
7723 (js2-parse-expr))))
7724 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7725 (setq rp (- js2-token-beg for-pos)))
7726 (if (not is-for-in-or-of)
7727 (setq pn (make-js2-for-node :init init
7728 :condition cond
7729 :update incr
7730 :lp lp
7731 :rp rp))
7732 ;; cond could be null if 'in obj' got eaten by the init node.
7733 (if (js2-infix-node-p init)
7734 ;; it was (foo in bar) instead of (var foo in bar)
7735 (setq cond (js2-infix-node-right init)
7736 init (js2-infix-node-left init))
7737 (if (and (js2-var-decl-node-p init)
7738 (> (length (js2-var-decl-node-kids init)) 1))
7739 (js2-report-error "msg.mult.index")))
7740 (setq pn (make-js2-for-in-node :iterator init
7741 :object cond
7742 :in-pos in-pos
7743 :foreach-p is-for-each
7744 :each-pos each-pos
7745 :forof-p is-for-of
7746 :lp lp
7747 :rp rp)))
7748 (unwind-protect
7749 (progn
7750 (js2-enter-loop pn)
7751 ;; We have to parse the body -after- creating the loop node,
7752 ;; so that the loop node appears in the js2-loop-set, allowing
7753 ;; break/continue statements to find the enclosing loop.
7754 (setf body (js2-parse-statement)
7755 (js2-loop-node-body pn) body
7756 (js2-node-pos pn) for-pos
7757 (js2-node-len pn) (- (js2-node-end body) for-pos))
7758 (js2-node-add-children pn init cond incr body))
7759 ;; finally
7760 (js2-exit-loop))
7761 (js2-pop-scope))
7762 pn))
7763
7764 (defun js2-parse-try ()
7765 "Parser for try-statement. Last matched token must be js2-TRY."
7766 (let ((try-pos js2-token-beg)
7767 try-end
7768 try-block
7769 catch-blocks
7770 finally-block
7771 saw-default-catch
7772 peek
7773 param
7774 catch-cond
7775 catch-node
7776 guard-kwd
7777 catch-pos
7778 finally-pos
7779 pn
7780 block
7781 lp
7782 rp)
7783 (js2-consume-token)
7784 (if (/= (js2-peek-token) js2-LC)
7785 (js2-report-error "msg.no.brace.try"))
7786 (setq try-block (js2-parse-statement)
7787 try-end (js2-node-end try-block)
7788 peek (js2-peek-token))
7789 (cond
7790 ((= peek js2-CATCH)
7791 (while (js2-match-token js2-CATCH)
7792 (setq catch-pos js2-token-beg
7793 guard-kwd nil
7794 catch-cond nil
7795 lp nil
7796 rp nil)
7797 (if saw-default-catch
7798 (js2-report-error "msg.catch.unreachable"))
7799 (if (js2-must-match js2-LP "msg.no.paren.catch")
7800 (setq lp (- js2-token-beg catch-pos)))
7801 (js2-push-scope (make-js2-scope))
7802 (let ((tt (js2-peek-token)))
7803 (cond
7804 ;; destructuring pattern
7805 ;; catch ({ message, file }) { ... }
7806 ((or (= tt js2-LB) (= tt js2-LC))
7807 (setq param (js2-parse-destruct-primary-expr))
7808 (js2-define-destruct-symbols param js2-LET nil))
7809 ;; simple name
7810 (t
7811 (js2-must-match js2-NAME "msg.bad.catchcond")
7812 (setq param (js2-create-name-node))
7813 (js2-define-symbol js2-LET js2-ts-string param))))
7814 ;; pattern guard
7815 (if (js2-match-token js2-IF)
7816 (setq guard-kwd (- js2-token-beg catch-pos)
7817 catch-cond (js2-parse-expr))
7818 (setq saw-default-catch t))
7819 (if (js2-must-match js2-RP "msg.bad.catchcond")
7820 (setq rp (- js2-token-beg catch-pos)))
7821 (js2-must-match js2-LC "msg.no.brace.catchblock")
7822 (setq block (js2-parse-statements)
7823 try-end (js2-node-end block)
7824 catch-node (make-js2-catch-node :pos catch-pos
7825 :param param
7826 :guard-expr catch-cond
7827 :guard-kwd guard-kwd
7828 :block block
7829 :lp lp
7830 :rp rp))
7831 (js2-pop-scope)
7832 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7833 (setq try-end js2-token-beg))
7834 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7835 (js2-node-len catch-node) (- try-end catch-pos))
7836 (js2-node-add-children catch-node param catch-cond block)
7837 (push catch-node catch-blocks)))
7838 ((/= peek js2-FINALLY)
7839 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7840 (js2-node-pos try-block)
7841 (- (setq try-end (js2-node-end try-block))
7842 (js2-node-pos try-block)))))
7843 (when (js2-match-token js2-FINALLY)
7844 (setq finally-pos js2-token-beg
7845 block (js2-parse-statement)
7846 try-end (js2-node-end block)
7847 finally-block (make-js2-finally-node :pos finally-pos
7848 :len (- try-end finally-pos)
7849 :body block))
7850 (js2-node-add-children finally-block block))
7851 (setq pn (make-js2-try-node :pos try-pos
7852 :len (- try-end try-pos)
7853 :try-block try-block
7854 :finally-block finally-block))
7855 (js2-node-add-children pn try-block finally-block)
7856 ;; push them onto the try-node, which reverses and corrects their order
7857 (dolist (cb catch-blocks)
7858 (js2-node-add-children pn cb)
7859 (push cb (js2-try-node-catch-clauses pn)))
7860 pn))
7861
7862 (defun js2-parse-throw ()
7863 "Parser for throw-statement. Last matched token must be js2-THROW."
7864 (let ((pos js2-token-beg)
7865 expr pn)
7866 (js2-consume-token)
7867 (if (= (js2-peek-token-or-eol) js2-EOL)
7868 ;; ECMAScript does not allow new lines before throw expression,
7869 ;; see bug 256617
7870 (js2-report-error "msg.bad.throw.eol"))
7871 (setq expr (js2-parse-expr)
7872 pn (make-js2-throw-node :pos pos
7873 :len (- (js2-node-end expr) pos)
7874 :expr expr))
7875 (js2-node-add-children pn expr)
7876 pn))
7877
7878 (defun js2-match-jump-label-name (label-name)
7879 "If break/continue specified a label, return that label's labeled stmt.
7880 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
7881 does not match an existing label, reports an error and returns nil."
7882 (let ((bundle (cdr (assoc label-name js2-label-set))))
7883 (if (null bundle)
7884 (js2-report-error "msg.undef.label"))
7885 bundle))
7886
7887 (defun js2-parse-break ()
7888 "Parser for break-statement. Last matched token must be js2-BREAK."
7889 (let ((pos js2-token-beg)
7890 (end js2-token-end)
7891 break-target ; statement to break from
7892 break-label ; in "break foo", name-node representing the foo
7893 labels ; matching labeled statement to break to
7894 pn)
7895 (js2-consume-token) ; `break'
7896 (when (eq (js2-peek-token-or-eol) js2-NAME)
7897 (js2-consume-token)
7898 (setq break-label (js2-create-name-node)
7899 end (js2-node-end break-label)
7900 ;; matchJumpLabelName only matches if there is one
7901 labels (js2-match-jump-label-name js2-ts-string)
7902 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
7903 (unless (or break-target break-label)
7904 ;; no break target specified - try for innermost enclosing loop/switch
7905 (if (null js2-loop-and-switch-set)
7906 (unless break-label
7907 (js2-report-error "msg.bad.break" nil pos (length "break")))
7908 (setq break-target (car js2-loop-and-switch-set))))
7909 (setq pn (make-js2-break-node :pos pos
7910 :len (- end pos)
7911 :label break-label
7912 :target break-target))
7913 (js2-node-add-children pn break-label) ; but not break-target
7914 pn))
7915
7916 (defun js2-parse-continue ()
7917 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
7918 (let ((pos js2-token-beg)
7919 (end js2-token-end)
7920 label ; optional user-specified label, a `js2-name-node'
7921 labels ; current matching labeled stmt, if any
7922 target ; the `js2-loop-node' target of this continue stmt
7923 pn)
7924 (js2-consume-token) ; `continue'
7925 (when (= (js2-peek-token-or-eol) js2-NAME)
7926 (js2-consume-token)
7927 (setq label (js2-create-name-node)
7928 end (js2-node-end label)
7929 ;; matchJumpLabelName only matches if there is one
7930 labels (js2-match-jump-label-name js2-ts-string)))
7931 (cond
7932 ((null labels) ; no current label to go to
7933 (if (null js2-loop-set) ; no loop to continue to
7934 (js2-report-error "msg.continue.outside" nil pos
7935 (length "continue"))
7936 (setq target (car js2-loop-set)))) ; innermost enclosing loop
7937 (t
7938 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
7939 (setq target (js2-labeled-stmt-node-stmt labels))
7940 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
7941 (setq pn (make-js2-continue-node :pos pos
7942 :len (- end pos)
7943 :label label
7944 :target target))
7945 (js2-node-add-children pn label) ; but not target - it's not our child
7946 pn))
7947
7948 (defun js2-parse-with ()
7949 "Parser for with-statement. Last matched token must be js2-WITH."
7950 (js2-consume-token)
7951 (let ((pos js2-token-beg)
7952 obj body pn lp rp)
7953 (if (js2-must-match js2-LP "msg.no.paren.with")
7954 (setq lp js2-token-beg))
7955 (setq obj (js2-parse-expr))
7956 (if (js2-must-match js2-RP "msg.no.paren.after.with")
7957 (setq rp js2-token-beg))
7958 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
7959 (setq body (js2-parse-statement)))
7960 (setq pn (make-js2-with-node :pos pos
7961 :len (- (js2-node-end body) pos)
7962 :object obj
7963 :body body
7964 :lp (js2-relpos lp pos)
7965 :rp (js2-relpos rp pos)))
7966 (js2-node-add-children pn obj body)
7967 pn))
7968
7969 (defun js2-parse-const-var ()
7970 "Parser for var- or const-statement.
7971 Last matched token must be js2-CONST or js2-VAR."
7972 (let ((tt (js2-peek-token))
7973 (pos js2-token-beg)
7974 expr pn)
7975 (js2-consume-token)
7976 (setq expr (js2-parse-variables tt js2-token-beg)
7977 pn (make-js2-expr-stmt-node :pos pos
7978 :len (- (js2-node-end expr) pos)
7979 :expr expr))
7980 (js2-node-add-children pn expr)
7981 pn))
7982
7983 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
7984 (let ((pn (make-js2-expr-stmt-node :pos pos
7985 :len (js2-node-len expr)
7986 :type (if (js2-inside-function)
7987 js2-EXPR_VOID
7988 js2-EXPR_RESULT)
7989 :expr expr)))
7990 (if add-child
7991 (js2-node-add-children pn expr))
7992 pn))
7993
7994 (defun js2-parse-let-stmt ()
7995 "Parser for let-statement. Last matched token must be js2-LET."
7996 (js2-consume-token)
7997 (let ((pos js2-token-beg)
7998 expr pn)
7999 (if (= (js2-peek-token) js2-LP)
8000 ;; let expression in statement context
8001 (setq expr (js2-parse-let pos 'statement)
8002 pn (js2-wrap-with-expr-stmt pos expr t))
8003 ;; else we're looking at a statement like let x=6, y=7;
8004 (setf expr (js2-parse-variables js2-LET pos)
8005 pn (js2-wrap-with-expr-stmt pos expr t)
8006 (js2-node-type pn) js2-EXPR_RESULT))
8007 pn))
8008
8009 (defun js2-parse-ret-yield ()
8010 (js2-parse-return-or-yield (js2-peek-token) nil))
8011
8012 (defconst js2-parse-return-stmt-enders
8013 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8014
8015 (defsubst js2-now-all-set (before after mask)
8016 "Return whether or not the bits in the mask have changed to all set.
8017 BEFORE is bits before change, AFTER is bits after change, and MASK is
8018 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8019 but not BEFORE."
8020 (and (/= (logand before mask) mask)
8021 (= (logand after mask) mask)))
8022
8023 (defun js2-parse-return-or-yield (tt expr-context)
8024 (let ((pos js2-token-beg)
8025 (end js2-token-end)
8026 (before js2-end-flags)
8027 (inside-function (js2-inside-function))
8028 e ret name)
8029 (unless inside-function
8030 (js2-report-error (if (eq tt js2-RETURN)
8031 "msg.bad.return"
8032 "msg.bad.yield")))
8033 (js2-consume-token)
8034 ;; This is ugly, but we don't want to require a semicolon.
8035 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8036 (setq e (js2-parse-expr)
8037 end (js2-node-end e)))
8038 (cond
8039 ((eq tt js2-RETURN)
8040 (js2-set-flag js2-end-flags (if (null e)
8041 js2-end-returns
8042 js2-end-returns-value))
8043 (setq ret (make-js2-return-node :pos pos
8044 :len (- end pos)
8045 :retval e))
8046 (js2-node-add-children ret e)
8047 ;; See if we need a strict mode warning.
8048 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8049 ;; more thorough and accurate than this before/after flag check.
8050 ;; E.g. if there's a finally-block that always returns, we shouldn't
8051 ;; show a warning generated by inconsistent returns in the catch blocks.
8052 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8053 ;; so we know which returns/yields to highlight, and we should get rid of
8054 ;; all the checking in `js2-parse-return-or-yield'.
8055 (if (and js2-strict-inconsistent-return-warning
8056 (js2-now-all-set before js2-end-flags
8057 (logior js2-end-returns js2-end-returns-value)))
8058 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8059 (t
8060 (unless (js2-inside-function)
8061 (js2-report-error "msg.bad.yield"))
8062 (js2-set-flag js2-end-flags js2-end-yields)
8063 (setq ret (make-js2-yield-node :pos pos
8064 :len (- end pos)
8065 :value e))
8066 (js2-node-add-children ret e)
8067 (unless expr-context
8068 (setq e ret
8069 ret (js2-wrap-with-expr-stmt pos e t))
8070 (js2-set-requires-activation)
8071 (js2-set-is-generator))))
8072 ;; see if we are mixing yields and value returns.
8073 (when (and inside-function
8074 (js2-now-all-set before js2-end-flags
8075 (logior js2-end-yields js2-end-returns-value)))
8076 (setq name (js2-function-name js2-current-script-or-fn))
8077 (if (zerop (length name))
8078 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8079 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8080 ret))
8081
8082 (defun js2-parse-debugger ()
8083 (js2-consume-token)
8084 (make-js2-keyword-node :type js2-DEBUGGER))
8085
8086 (defun js2-parse-block ()
8087 "Parser for a curly-delimited statement block.
8088 Last token matched must be `js2-LC'."
8089 (let ((pos js2-token-beg)
8090 (pn (make-js2-scope)))
8091 (js2-consume-token)
8092 (js2-push-scope pn)
8093 (unwind-protect
8094 (progn
8095 (js2-parse-statements pn)
8096 (js2-must-match js2-RC "msg.no.brace.block")
8097 (setf (js2-node-len pn) (- js2-token-end pos)))
8098 (js2-pop-scope))
8099 pn))
8100
8101 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8102 (defun js2-parse-semi ()
8103 "Parse a statement or handle an error.
8104 Last matched token is `js2-SEMI' or `js2-ERROR'."
8105 (let ((tt (js2-peek-token)) pos len)
8106 (js2-consume-token)
8107 (if (eq tt js2-SEMI)
8108 (make-js2-empty-expr-node :len 1)
8109 (setq pos js2-token-beg
8110 len (- js2-token-beg pos))
8111 (js2-report-error "msg.syntax" nil pos len)
8112 (make-js2-error-node :pos pos :len len))))
8113
8114 (defun js2-parse-default-xml-namespace ()
8115 "Parse a `default xml namespace = <expr>' e4x statement."
8116 (let ((pos js2-token-beg)
8117 end len expr unary es)
8118 (js2-consume-token)
8119 (js2-must-have-xml)
8120 (js2-set-requires-activation)
8121 (setq len (- js2-ts-cursor pos))
8122 (unless (and (js2-match-token js2-NAME)
8123 (string= js2-ts-string "xml"))
8124 (js2-report-error "msg.bad.namespace" nil pos len))
8125 (unless (and (js2-match-token js2-NAME)
8126 (string= js2-ts-string "namespace"))
8127 (js2-report-error "msg.bad.namespace" nil pos len))
8128 (unless (js2-match-token js2-ASSIGN)
8129 (js2-report-error "msg.bad.namespace" nil pos len))
8130 (setq expr (js2-parse-expr)
8131 end (js2-node-end expr)
8132 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8133 :pos pos
8134 :len (- end pos)
8135 :operand expr))
8136 (js2-node-add-children unary expr)
8137 (make-js2-expr-stmt-node :pos pos
8138 :len (- end pos)
8139 :expr unary)))
8140
8141 (defun js2-record-label (label bundle)
8142 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8143 (js2-consume-token)
8144 (let ((name (js2-label-node-name label))
8145 labeled-stmt
8146 dup)
8147 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8148 ;; flag both labels if possible when used in editing mode
8149 (if (and js2-parse-ide-mode
8150 (setq dup (js2-get-label-by-name labeled-stmt name)))
8151 (js2-report-error "msg.dup.label" nil
8152 (js2-node-abs-pos dup) (js2-node-len dup)))
8153 (js2-report-error "msg.dup.label" nil
8154 (js2-node-pos label) (js2-node-len label)))
8155 (js2-labeled-stmt-node-add-label bundle label)
8156 (js2-node-add-children bundle label)
8157 ;; Add one reference to the bundle per label in `js2-label-set'
8158 (push (cons name bundle) js2-label-set)))
8159
8160 (defun js2-parse-name-or-label ()
8161 "Parser for identifier or label. Last token matched must be js2-NAME.
8162 Called when we found a name in a statement context. If it's a label, we gather
8163 up any following labels and the next non-label statement into a
8164 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8165 expression and return it wrapped in a `js2-expr-stmt-node'."
8166 (let ((pos js2-token-beg)
8167 (end js2-token-end)
8168 expr stmt pn bundle
8169 (continue t))
8170 ;; set check for label and call down to `js2-parse-primary-expr'
8171 (js2-set-check-for-label)
8172 (setq expr (js2-parse-expr))
8173 (if (/= (js2-node-type expr) js2-LABEL)
8174 ;; Parsed non-label expression - wrap with expression stmt.
8175 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8176 ;; else parsed a label
8177 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8178 (js2-record-label expr bundle)
8179 ;; look for more labels
8180 (while (and continue (= (js2-peek-token) js2-NAME))
8181 (js2-set-check-for-label)
8182 (setq expr (js2-parse-expr))
8183 (if (/= (js2-node-type expr) js2-LABEL)
8184 (progn
8185 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8186 continue nil)
8187 (js2-auto-insert-semicolon stmt))
8188 (js2-record-label expr bundle)))
8189 ;; no more labels; now parse the labeled statement
8190 (unwind-protect
8191 (unless stmt
8192 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8193 (setq stmt (js2-statement-helper))))
8194 ;; remove the labels for this statement from the global set
8195 (dolist (label (js2-labeled-stmt-node-labels bundle))
8196 (setq js2-label-set (remove label js2-label-set))))
8197 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8198 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8199 (js2-node-add-children bundle stmt)
8200 bundle)))
8201
8202 (defun js2-parse-expr-stmt ()
8203 "Default parser in statement context, if no recognized statement found."
8204 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8205
8206 (defun js2-parse-variables (decl-type pos)
8207 "Parse a comma-separated list of variable declarations.
8208 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8209
8210 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8211 For 'var' or 'const', the keyword should be the token last scanned.
8212
8213 POS is the position where the node should start. It's sometimes the
8214 var/const/let keyword, and other times the beginning of the first token
8215 in the first variable declaration.
8216
8217 Returns the parsed `js2-var-decl-node' expression node."
8218 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8219 :pos pos))
8220 destructuring kid-pos tt init name end nbeg nend vi
8221 (continue t))
8222 ;; Example:
8223 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8224 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8225 ;; var {a, b} = baz;
8226 (while continue
8227 (setq destructuring nil
8228 name nil
8229 tt (js2-peek-token)
8230 kid-pos js2-token-beg
8231 end js2-token-end
8232 init nil)
8233 (if (or (= tt js2-LB) (= tt js2-LC))
8234 ;; Destructuring assignment, e.g., var [a, b] = ...
8235 (setq destructuring (js2-parse-destruct-primary-expr)
8236 end (js2-node-end destructuring))
8237 ;; Simple variable name
8238 (when (js2-must-match js2-NAME "msg.bad.var")
8239 (setq name (js2-create-name-node)
8240 nbeg js2-token-beg
8241 nend js2-token-end
8242 end nend)
8243 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8244 (when (js2-match-token js2-ASSIGN)
8245 (setq init (js2-parse-assign-expr)
8246 end (js2-node-end init))
8247 (js2-record-imenu-functions init name))
8248 (when name
8249 (js2-set-face nbeg nend (if (js2-function-node-p init)
8250 'font-lock-function-name-face
8251 'font-lock-variable-name-face)
8252 'record))
8253 (setq vi (make-js2-var-init-node :pos kid-pos
8254 :len (- end kid-pos)
8255 :type decl-type))
8256 (if destructuring
8257 (progn
8258 (if (and (null init) (not js2-in-for-init))
8259 (js2-report-error "msg.destruct.assign.no.init"))
8260 (js2-define-destruct-symbols destructuring
8261 decl-type
8262 'font-lock-variable-name-face)
8263 (setf (js2-var-init-node-target vi) destructuring))
8264 (setf (js2-var-init-node-target vi) name))
8265 (setf (js2-var-init-node-initializer vi) init)
8266 (js2-node-add-children vi name destructuring init)
8267 (js2-block-node-push result vi)
8268 (unless (js2-match-token js2-COMMA)
8269 (setq continue nil)))
8270 (setf (js2-node-len result) (- end pos))
8271 result))
8272
8273 (defun js2-parse-let (pos &optional stmt-p)
8274 "Parse a let expression or statement.
8275 A let-expression is of the form `let (vars) expr'.
8276 A let-statment is of the form `let (vars) {statements}'.
8277 The third form of let is a variable declaration list, handled
8278 by `js2-parse-variables'."
8279 (let ((pn (make-js2-let-node :pos pos))
8280 beg vars body)
8281 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8282 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8283 (js2-push-scope pn)
8284 (unwind-protect
8285 (progn
8286 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8287 (if (js2-must-match js2-RP "msg.no.paren.let")
8288 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8289 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8290 ;; let statement
8291 (progn
8292 (js2-consume-token)
8293 (setf beg js2-token-beg ; position stmt at LC
8294 body (js2-parse-statements))
8295 (js2-must-match js2-RC "msg.no.curly.let")
8296 (setf (js2-node-len body) (- js2-token-end beg)
8297 (js2-node-len pn) (- js2-token-end pos)
8298 (js2-let-node-body pn) body
8299 (js2-node-type pn) js2-LET))
8300 ;; let expression
8301 (setf body (js2-parse-expr)
8302 (js2-node-len pn) (- (js2-node-end body) pos)
8303 (js2-let-node-body pn) body))
8304 (js2-node-add-children pn vars body))
8305 (js2-pop-scope))
8306 pn))
8307
8308 (defun js2-define-new-symbol (decl-type name node &optional scope)
8309 (js2-scope-put-symbol (or scope js2-current-scope)
8310 name
8311 (make-js2-symbol decl-type name node)))
8312
8313 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8314 "Define a symbol in the current scope.
8315 If NODE is non-nil, it is the AST node associated with the symbol."
8316 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8317 (symbol (if defining-scope
8318 (js2-scope-get-symbol defining-scope name)))
8319 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8320 (cond
8321 ((and symbol ; already defined
8322 (or (= sdt js2-CONST) ; old version is const
8323 (= decl-type js2-CONST) ; new version is const
8324 ;; two let-bound vars in this block have same name
8325 (and (= sdt js2-LET)
8326 (eq defining-scope js2-current-scope))))
8327 (js2-report-error
8328 (cond
8329 ((= sdt js2-CONST) "msg.const.redecl")
8330 ((= sdt js2-LET) "msg.let.redecl")
8331 ((= sdt js2-VAR) "msg.var.redecl")
8332 ((= sdt js2-FUNCTION) "msg.function.redecl")
8333 (t "msg.parm.redecl"))
8334 name))
8335 ((= decl-type js2-LET)
8336 (if (and (not ignore-not-in-block)
8337 (or (= (js2-node-type js2-current-scope) js2-IF)
8338 (js2-loop-node-p js2-current-scope)))
8339 (js2-report-error "msg.let.decl.not.in.block")
8340 (js2-define-new-symbol decl-type name node)))
8341 ((or (= decl-type js2-VAR)
8342 (= decl-type js2-CONST)
8343 (= decl-type js2-FUNCTION))
8344 (if symbol
8345 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8346 (js2-add-strict-warning "msg.var.redecl" name)
8347 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8348 (js2-add-strict-warning "msg.var.hides.arg" name)))
8349 (js2-define-new-symbol decl-type name node
8350 js2-current-script-or-fn)))
8351 ((= decl-type js2-LP)
8352 (if symbol
8353 ;; must be duplicate parameter. Second parameter hides the
8354 ;; first, so go ahead and add the second pararameter
8355 (js2-report-warning "msg.dup.parms" name))
8356 (js2-define-new-symbol decl-type name node))
8357 (t (js2-code-bug)))))
8358
8359 (defun js2-parse-expr (&optional oneshot)
8360 (let* ((pn (js2-parse-assign-expr))
8361 (pos (js2-node-pos pn))
8362 left
8363 right
8364 op-pos)
8365 (while (and (not oneshot)
8366 (js2-match-token js2-COMMA))
8367 (setq op-pos (- js2-token-beg pos)) ; relative
8368 (if (= (js2-peek-token) js2-YIELD)
8369 (js2-report-error "msg.yield.parenthesized"))
8370 (setq right (js2-parse-assign-expr)
8371 left pn
8372 pn (make-js2-infix-node :type js2-COMMA
8373 :pos pos
8374 :len (- js2-ts-cursor pos)
8375 :op-pos op-pos
8376 :left left
8377 :right right))
8378 (js2-node-add-children pn left right))
8379 pn))
8380
8381 (defun js2-parse-assign-expr ()
8382 (let ((tt (js2-peek-token))
8383 (pos js2-token-beg)
8384 pn left right op-pos)
8385 (if (= tt js2-YIELD)
8386 (js2-parse-return-or-yield tt t)
8387 ;; not yield - parse assignment expression
8388 (setq pn (js2-parse-cond-expr)
8389 tt (js2-peek-token))
8390 (when (and (<= js2-first-assign tt)
8391 (<= tt js2-last-assign))
8392 ;; tt express assignment (=, |=, ^=, ..., %=)
8393 (js2-consume-token)
8394 (setq op-pos (- js2-token-beg pos) ; relative
8395 left pn
8396 right (js2-parse-assign-expr)
8397 pn (make-js2-assign-node :type tt
8398 :pos pos
8399 :len (- (js2-node-end right) pos)
8400 :op-pos op-pos
8401 :left left
8402 :right right))
8403 (when js2-parse-ide-mode
8404 (js2-highlight-assign-targets pn left right)
8405 (js2-record-imenu-functions right left))
8406 ;; do this last so ide checks above can use absolute positions
8407 (js2-node-add-children pn left right))
8408 pn)))
8409
8410 (defun js2-parse-cond-expr ()
8411 (let ((pos js2-token-beg)
8412 (pn (js2-parse-or-expr))
8413 test-expr
8414 if-true
8415 if-false
8416 q-pos
8417 c-pos)
8418 (when (js2-match-token js2-HOOK)
8419 (setq q-pos (- js2-token-beg pos)
8420 if-true (js2-parse-assign-expr))
8421 (js2-must-match js2-COLON "msg.no.colon.cond")
8422 (setq c-pos (- js2-token-beg pos)
8423 if-false (js2-parse-assign-expr)
8424 test-expr pn
8425 pn (make-js2-cond-node :pos pos
8426 :len (- (js2-node-end if-false) pos)
8427 :test-expr test-expr
8428 :true-expr if-true
8429 :false-expr if-false
8430 :q-pos q-pos
8431 :c-pos c-pos))
8432 (js2-node-add-children pn test-expr if-true if-false))
8433 pn))
8434
8435 (defun js2-make-binary (type left parser)
8436 "Helper for constructing a binary-operator AST node.
8437 LEFT is the left-side-expression, already parsed, and the
8438 binary operator should have just been matched.
8439 PARSER is a function to call to parse the right operand,
8440 or a `js2-node' struct if it has already been parsed."
8441 (let* ((pos (js2-node-pos left))
8442 (op-pos (- js2-token-beg pos))
8443 (right (if (js2-node-p parser)
8444 parser
8445 (funcall parser)))
8446 (pn (make-js2-infix-node :type type
8447 :pos pos
8448 :len (- (js2-node-end right) pos)
8449 :op-pos op-pos
8450 :left left
8451 :right right)))
8452 (js2-node-add-children pn left right)
8453 pn))
8454
8455 (defun js2-parse-or-expr ()
8456 (let ((pn (js2-parse-and-expr)))
8457 (when (js2-match-token js2-OR)
8458 (setq pn (js2-make-binary js2-OR
8459 pn
8460 'js2-parse-or-expr)))
8461 pn))
8462
8463 (defun js2-parse-and-expr ()
8464 (let ((pn (js2-parse-bit-or-expr)))
8465 (when (js2-match-token js2-AND)
8466 (setq pn (js2-make-binary js2-AND
8467 pn
8468 'js2-parse-and-expr)))
8469 pn))
8470
8471 (defun js2-parse-bit-or-expr ()
8472 (let ((pn (js2-parse-bit-xor-expr)))
8473 (while (js2-match-token js2-BITOR)
8474 (setq pn (js2-make-binary js2-BITOR
8475 pn
8476 'js2-parse-bit-xor-expr)))
8477 pn))
8478
8479 (defun js2-parse-bit-xor-expr ()
8480 (let ((pn (js2-parse-bit-and-expr)))
8481 (while (js2-match-token js2-BITXOR)
8482 (setq pn (js2-make-binary js2-BITXOR
8483 pn
8484 'js2-parse-bit-and-expr)))
8485 pn))
8486
8487 (defun js2-parse-bit-and-expr ()
8488 (let ((pn (js2-parse-eq-expr)))
8489 (while (js2-match-token js2-BITAND)
8490 (setq pn (js2-make-binary js2-BITAND
8491 pn
8492 'js2-parse-eq-expr)))
8493 pn))
8494
8495 (defconst js2-parse-eq-ops
8496 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8497
8498 (defun js2-parse-eq-expr ()
8499 (let ((pn (js2-parse-rel-expr))
8500 tt)
8501 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8502 (js2-consume-token)
8503 (setq pn (js2-make-binary tt
8504 pn
8505 'js2-parse-rel-expr)))
8506 pn))
8507
8508 (defconst js2-parse-rel-ops
8509 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8510
8511 (defun js2-parse-rel-expr ()
8512 (let ((pn (js2-parse-shift-expr))
8513 (continue t)
8514 tt)
8515 (while continue
8516 (setq tt (js2-peek-token))
8517 (cond
8518 ((and js2-in-for-init (= tt js2-IN))
8519 (setq continue nil))
8520 ((memq tt js2-parse-rel-ops)
8521 (js2-consume-token)
8522 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8523 (t
8524 (setq continue nil))))
8525 pn))
8526
8527 (defconst js2-parse-shift-ops
8528 (list js2-LSH js2-URSH js2-RSH))
8529
8530 (defun js2-parse-shift-expr ()
8531 (let ((pn (js2-parse-add-expr))
8532 tt
8533 (continue t))
8534 (while continue
8535 (setq tt (js2-peek-token))
8536 (if (memq tt js2-parse-shift-ops)
8537 (progn
8538 (js2-consume-token)
8539 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8540 (setq continue nil)))
8541 pn))
8542
8543 (defun js2-parse-add-expr ()
8544 (let ((pn (js2-parse-mul-expr))
8545 tt
8546 (continue t))
8547 (while continue
8548 (setq tt (js2-peek-token))
8549 (if (or (= tt js2-ADD) (= tt js2-SUB))
8550 (progn
8551 (js2-consume-token)
8552 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8553 (setq continue nil)))
8554 pn))
8555
8556 (defconst js2-parse-mul-ops
8557 (list js2-MUL js2-DIV js2-MOD))
8558
8559 (defun js2-parse-mul-expr ()
8560 (let ((pn (js2-parse-unary-expr))
8561 tt
8562 (continue t))
8563 (while continue
8564 (setq tt (js2-peek-token))
8565 (if (memq tt js2-parse-mul-ops)
8566 (progn
8567 (js2-consume-token)
8568 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8569 (setq continue nil)))
8570 pn))
8571
8572 (defun js2-make-unary (type parser &rest args)
8573 "Make a unary node of type TYPE.
8574 PARSER is either a node (for postfix operators) or a function to call
8575 to parse the operand (for prefix operators)."
8576 (let* ((pos js2-token-beg)
8577 (postfix (js2-node-p parser))
8578 (expr (if postfix
8579 parser
8580 (apply parser args)))
8581 end
8582 pn)
8583 (if postfix ; e.g. i++
8584 (setq pos (js2-node-pos expr)
8585 end js2-token-end)
8586 (setq end (js2-node-end expr)))
8587 (setq pn (make-js2-unary-node :type type
8588 :pos pos
8589 :len (- end pos)
8590 :operand expr))
8591 (js2-node-add-children pn expr)
8592 pn))
8593
8594 (defconst js2-incrementable-node-types
8595 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8596 "Node types that can be the operand of a ++ or -- operator.")
8597
8598 (defun js2-check-bad-inc-dec (tt beg end unary)
8599 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8600 js2-incrementable-node-types)
8601 (js2-report-error (if (= tt js2-INC)
8602 "msg.bad.incr"
8603 "msg.bad.decr")
8604 nil beg (- end beg))))
8605
8606 (defun js2-parse-unary-expr ()
8607 (let ((tt (js2-peek-token))
8608 pn expr beg end)
8609 (cond
8610 ((or (= tt js2-VOID)
8611 (= tt js2-NOT)
8612 (= tt js2-BITNOT)
8613 (= tt js2-TYPEOF))
8614 (js2-consume-token)
8615 (js2-make-unary tt 'js2-parse-unary-expr))
8616 ((= tt js2-ADD)
8617 (js2-consume-token)
8618 ;; Convert to special POS token in decompiler and parse tree
8619 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8620 ((= tt js2-SUB)
8621 (js2-consume-token)
8622 ;; Convert to special NEG token in decompiler and parse tree
8623 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8624 ((or (= tt js2-INC)
8625 (= tt js2-DEC))
8626 (js2-consume-token)
8627 (prog1
8628 (setq beg js2-token-beg
8629 end js2-token-end
8630 expr (js2-make-unary tt 'js2-parse-member-expr t))
8631 (js2-check-bad-inc-dec tt beg end expr)))
8632 ((= tt js2-DELPROP)
8633 (js2-consume-token)
8634 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8635 ((= tt js2-ERROR)
8636 (js2-consume-token)
8637 (make-js2-error-node)) ; try to continue
8638 ((and (= tt js2-LT)
8639 js2-compiler-xml-available)
8640 ;; XML stream encountered in expression.
8641 (js2-consume-token)
8642 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8643 (t
8644 (setq pn (js2-parse-member-expr t)
8645 ;; Don't look across a newline boundary for a postfix incop.
8646 tt (js2-peek-token-or-eol))
8647 (when (or (= tt js2-INC) (= tt js2-DEC))
8648 (js2-consume-token)
8649 (setf expr pn
8650 pn (js2-make-unary tt expr))
8651 (js2-node-set-prop pn 'postfix t)
8652 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8653 pn))))
8654
8655 (defun js2-parse-xml-initializer ()
8656 "Parse an E4X XML initializer.
8657 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8658 Then I'll postprocess the result, depending on whether we're in IDE
8659 mode or codegen mode, and generate the appropriate rewritten AST.
8660 IDE mode uses a rich AST that models the XML structure. Codegen mode
8661 just concatenates everything and makes a new XML or XMLList out of it."
8662 (let ((tt (js2-get-first-xml-token))
8663 pn-xml pn expr kids expr-pos
8664 (continue t)
8665 (first-token t))
8666 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8667 (js2-report-error "msg.syntax"))
8668 (setq pn-xml (make-js2-xml-node))
8669 (while continue
8670 (if first-token
8671 (setq first-token nil)
8672 (setq tt (js2-get-next-xml-token)))
8673 (cond
8674 ;; js2-XML means we found a {expr} in the XML stream.
8675 ;; The js2-ts-string is the XML up to the left-curly.
8676 ((= tt js2-XML)
8677 (push (make-js2-string-node :pos js2-token-beg
8678 :len (- js2-ts-cursor js2-token-beg))
8679 kids)
8680 (js2-must-match js2-LC "msg.syntax")
8681 (setq expr-pos js2-ts-cursor
8682 expr (if (eq (js2-peek-token) js2-RC)
8683 (make-js2-empty-expr-node :pos expr-pos)
8684 (js2-parse-expr)))
8685 (js2-must-match js2-RC "msg.syntax")
8686 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8687 :len (js2-node-len expr)
8688 :expr expr))
8689 (js2-node-add-children pn expr)
8690 (push pn kids))
8691 ;; a js2-XMLEND token means we hit the final close-tag.
8692 ((= tt js2-XMLEND)
8693 (push (make-js2-string-node :pos js2-token-beg
8694 :len (- js2-ts-cursor js2-token-beg))
8695 kids)
8696 (dolist (kid (nreverse kids))
8697 (js2-block-node-push pn-xml kid))
8698 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8699 (js2-node-pos pn-xml))
8700 continue nil))
8701 (t
8702 (js2-report-error "msg.syntax")
8703 (setq continue nil))))
8704 pn-xml))
8705
8706
8707 (defun js2-parse-argument-list ()
8708 "Parse an argument list and return it as a Lisp list of nodes.
8709 Returns the list in reverse order. Consumes the right-paren token."
8710 (let (result)
8711 (unless (js2-match-token js2-RP)
8712 (loop do
8713 (if (= (js2-peek-token) js2-YIELD)
8714 (js2-report-error "msg.yield.parenthesized"))
8715 (push (js2-parse-assign-expr) result)
8716 while
8717 (js2-match-token js2-COMMA))
8718 (js2-must-match js2-RP "msg.no.paren.arg")
8719 result)))
8720
8721 (defun js2-parse-member-expr (&optional allow-call-syntax)
8722 (let ((tt (js2-peek-token))
8723 pn pos target args beg end init tail)
8724 (if (/= tt js2-NEW)
8725 (setq pn (js2-parse-primary-expr))
8726 ;; parse a 'new' expression
8727 (js2-consume-token)
8728 (setq pos js2-token-beg
8729 beg pos
8730 target (js2-parse-member-expr)
8731 end (js2-node-end target)
8732 pn (make-js2-new-node :pos pos
8733 :target target
8734 :len (- end pos)))
8735 (js2-node-add-children pn target)
8736 (when (js2-match-token js2-LP)
8737 ;; Add the arguments to pn, if any are supplied.
8738 (setf beg pos ; start of "new" keyword
8739 pos js2-token-beg
8740 args (nreverse (js2-parse-argument-list))
8741 (js2-new-node-args pn) args
8742 end js2-token-end
8743 (js2-new-node-lp pn) (- pos beg)
8744 (js2-new-node-rp pn) (- end 1 beg))
8745 (apply #'js2-node-add-children pn args))
8746 (when (and js2-allow-rhino-new-expr-initializer
8747 (js2-match-token js2-LC))
8748 (setf init (js2-parse-object-literal)
8749 end (js2-node-end init)
8750 (js2-new-node-initializer pn) init)
8751 (js2-node-add-children pn init))
8752 (setf (js2-node-len pn) (- end beg))) ; end outer if
8753 (js2-parse-member-expr-tail allow-call-syntax pn)))
8754
8755 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8756 "Parse a chain of property/array accesses or function calls.
8757 Includes parsing for E4X operators like `..' and `.@'.
8758 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8759 Returns an expression tree that includes PN, the parent node."
8760 (let ((beg (js2-node-pos pn))
8761 tt
8762 (continue t))
8763 (while continue
8764 (setq tt (js2-peek-token))
8765 (cond
8766 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8767 (setq pn (js2-parse-property-access tt pn)))
8768 ((= tt js2-DOTQUERY)
8769 (setq pn (js2-parse-dot-query pn)))
8770 ((= tt js2-LB)
8771 (setq pn (js2-parse-element-get pn)))
8772 ((= tt js2-LP)
8773 (if allow-call-syntax
8774 (setq pn (js2-parse-function-call pn))
8775 (setq continue nil)))
8776 (t
8777 (setq continue nil))))
8778 (if (>= js2-highlight-level 2)
8779 (js2-parse-highlight-member-expr-node pn))
8780 pn))
8781
8782 (defun js2-parse-dot-query (pn)
8783 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8784 Last token parsed must be `js2-DOTQUERY'."
8785 (let ((pos (js2-node-pos pn))
8786 op-pos expr end)
8787 (js2-consume-token)
8788 (js2-must-have-xml)
8789 (js2-set-requires-activation)
8790 (setq op-pos js2-token-beg
8791 expr (js2-parse-expr)
8792 end (js2-node-end expr)
8793 pn (make-js2-xml-dot-query-node :left pn
8794 :pos pos
8795 :op-pos op-pos
8796 :right expr))
8797 (js2-node-add-children pn
8798 (js2-xml-dot-query-node-left pn)
8799 (js2-xml-dot-query-node-right pn))
8800 (if (js2-must-match js2-RP "msg.no.paren")
8801 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
8802 end js2-token-end))
8803 (setf (js2-node-len pn) (- end pos))
8804 pn))
8805
8806 (defun js2-parse-element-get (pn)
8807 "Parse an element-get expression, e.g. foo[bar].
8808 Last token parsed must be `js2-RB'."
8809 (let ((lb js2-token-beg)
8810 (pos (js2-node-pos pn))
8811 rb expr)
8812 (js2-consume-token)
8813 (setq expr (js2-parse-expr))
8814 (if (js2-must-match js2-RB "msg.no.bracket.index")
8815 (setq rb js2-token-beg))
8816 (setq pn (make-js2-elem-get-node :target pn
8817 :pos pos
8818 :element expr
8819 :lb (js2-relpos lb pos)
8820 :rb (js2-relpos rb pos)
8821 :len (- js2-token-end pos)))
8822 (js2-node-add-children pn
8823 (js2-elem-get-node-target pn)
8824 (js2-elem-get-node-element pn))
8825 pn))
8826
8827 (defun js2-parse-function-call (pn)
8828 (let (args
8829 (pos (js2-node-pos pn)))
8830 (js2-consume-token)
8831 (setq pn (make-js2-call-node :pos pos
8832 :target pn
8833 :lp (- js2-token-beg pos)))
8834 (js2-node-add-children pn (js2-call-node-target pn))
8835 ;; Add the arguments to pn, if any are supplied.
8836 (setf args (nreverse (js2-parse-argument-list))
8837 (js2-call-node-rp pn) (- js2-token-beg pos)
8838 (js2-call-node-args pn) args)
8839 (apply #'js2-node-add-children pn args)
8840 (setf (js2-node-len pn) (- js2-ts-cursor pos))
8841 pn))
8842
8843 (defun js2-parse-property-access (tt pn)
8844 "Parse a property access, XML descendants access, or XML attr access."
8845 (let ((member-type-flags 0)
8846 (dot-pos js2-token-beg)
8847 (dot-len (if (= tt js2-DOTDOT) 2 1))
8848 name
8849 ref ; right side of . or .. operator
8850 result)
8851 (js2-consume-token)
8852 (when (= tt js2-DOTDOT)
8853 (js2-must-have-xml)
8854 (setq member-type-flags js2-descendants-flag))
8855 (if (not js2-compiler-xml-available)
8856 (progn
8857 (js2-must-match-prop-name "msg.no.name.after.dot")
8858 (setq name (js2-create-name-node t js2-GETPROP)
8859 result (make-js2-prop-get-node :left pn
8860 :pos js2-token-beg
8861 :right name
8862 :len (- js2-token-end
8863 js2-token-beg)))
8864 (js2-node-add-children result pn name)
8865 result)
8866 ;; otherwise look for XML operators
8867 (setf result (if (= tt js2-DOT)
8868 (make-js2-prop-get-node)
8869 (make-js2-infix-node :type js2-DOTDOT))
8870 (js2-node-pos result) (js2-node-pos pn)
8871 (js2-infix-node-op-pos result) dot-pos
8872 (js2-infix-node-left result) pn ; do this after setting position
8873 tt (js2-next-token))
8874 (cond
8875 ;; needed for generator.throw()
8876 ((= tt js2-THROW)
8877 (js2-save-name-token-data js2-token-beg "throw")
8878 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
8879 ;; handles: name, ns::name, ns::*, ns::[expr]
8880 ((js2-valid-prop-name-token tt)
8881 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
8882 ;; handles: *, *::name, *::*, *::[expr]
8883 ((= tt js2-MUL)
8884 (js2-save-name-token-data js2-token-beg "*")
8885 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
8886 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
8887 ((= tt js2-XMLATTR)
8888 (setq result (js2-parse-attribute-access)))
8889 (t
8890 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
8891 (if ref
8892 (setf (js2-node-len result) (- (js2-node-end ref)
8893 (js2-node-pos result))
8894 (js2-infix-node-right result) ref))
8895 (if (js2-infix-node-p result)
8896 (js2-node-add-children result
8897 (js2-infix-node-left result)
8898 (js2-infix-node-right result)))
8899 result)))
8900
8901 (defun js2-parse-attribute-access ()
8902 "Parse an E4X XML attribute expression.
8903 This includes expressions of the forms:
8904
8905 @attr @ns::attr @ns::*
8906 @* @*::attr @*::*
8907 @[expr] @*::[expr] @ns::[expr]
8908
8909 Called if we peeked an '@' token."
8910 (let ((tt (js2-next-token))
8911 (at-pos js2-token-beg))
8912 (cond
8913 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
8914 ((js2-valid-prop-name-token tt)
8915 (js2-parse-property-name at-pos js2-ts-string 0))
8916 ;; handles: @*, @*::name, @*::*, @*::[expr]
8917 ((= tt js2-MUL)
8918 (js2-save-name-token-data js2-token-beg "*")
8919 (js2-parse-property-name js2-token-beg "*" 0))
8920 ;; handles @[expr]
8921 ((= tt js2-LB)
8922 (js2-parse-xml-elem-ref at-pos))
8923 (t
8924 (js2-report-error "msg.no.name.after.xmlAttr")
8925 ;; Avoid cascaded errors that happen if we make an error node here.
8926 (js2-save-name-token-data js2-token-beg "")
8927 (js2-parse-property-name js2-token-beg "" 0)))))
8928
8929 (defun js2-parse-property-name (at-pos s member-type-flags)
8930 "Check if :: follows name in which case it becomes qualified name.
8931
8932 AT-POS is a natural number if we just read an '@' token, else nil.
8933 S is the name or string that was matched: an identifier, 'throw' or '*'.
8934 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
8935
8936 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
8937 operator, or the name is followed by ::. For a plain name, returns a
8938 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
8939 (let ((pos (or at-pos js2-token-beg))
8940 colon-pos
8941 (name (js2-create-name-node t js2-current-token))
8942 ns tt ref pn)
8943 (catch 'return
8944 (when (js2-match-token js2-COLONCOLON)
8945 (setq ns name
8946 colon-pos js2-token-beg
8947 tt (js2-next-token))
8948 (cond
8949 ;; handles name::name
8950 ((js2-valid-prop-name-token tt)
8951 (setq name (js2-create-name-node)))
8952 ;; handles name::*
8953 ((= tt js2-MUL)
8954 (js2-save-name-token-data js2-token-beg "*")
8955 (setq name (js2-create-name-node)))
8956 ;; handles name::[expr]
8957 ((= tt js2-LB)
8958 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
8959 (t
8960 (js2-report-error "msg.no.name.after.coloncolon"))))
8961 (if (and (null ns) (zerop member-type-flags))
8962 name
8963 (prog1
8964 (setq pn
8965 (make-js2-xml-prop-ref-node :pos pos
8966 :len (- (js2-node-end name) pos)
8967 :at-pos at-pos
8968 :colon-pos colon-pos
8969 :propname name))
8970 (js2-node-add-children pn name))))))
8971
8972 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
8973 "Parse the [expr] portion of an xml element reference.
8974 For instance, @[expr], @*::[expr], or ns::[expr]."
8975 (let* ((lb js2-token-beg)
8976 (pos (or at-pos lb))
8977 rb
8978 (expr (js2-parse-expr))
8979 (end (js2-node-end expr))
8980 pn)
8981 (if (js2-must-match js2-RB "msg.no.bracket.index")
8982 (setq rb js2-token-beg
8983 end js2-token-end))
8984 (prog1
8985 (setq pn
8986 (make-js2-xml-elem-ref-node :pos pos
8987 :len (- end pos)
8988 :namespace namespace
8989 :colon-pos colon-pos
8990 :at-pos at-pos
8991 :expr expr
8992 :lb (js2-relpos lb pos)
8993 :rb (js2-relpos rb pos)))
8994 (js2-node-add-children pn namespace expr))))
8995
8996 (defun js2-parse-destruct-primary-expr ()
8997 (let ((js2-is-in-destructuring t))
8998 (js2-parse-primary-expr)))
8999
9000 (defun js2-parse-primary-expr ()
9001 "Parse a literal (leaf) expression of some sort.
9002 Includes complex literals such as functions, object-literals,
9003 array-literals, array comprehensions and regular expressions."
9004 (let ((tt-flagged (js2-next-flagged-token))
9005 pn ; parent node (usually return value)
9006 tt
9007 px-pos ; paren-expr pos
9008 len
9009 flags ; regexp flags
9010 expr)
9011 (setq tt js2-current-token)
9012 (cond
9013 ((= tt js2-FUNCTION)
9014 (js2-parse-function 'FUNCTION_EXPRESSION))
9015 ((= tt js2-LB)
9016 (js2-parse-array-literal))
9017 ((= tt js2-LC)
9018 (js2-parse-object-literal))
9019 ((= tt js2-LET)
9020 (js2-parse-let js2-token-beg))
9021 ((= tt js2-LP)
9022 (setq px-pos js2-token-beg
9023 expr (js2-parse-expr))
9024 (js2-must-match js2-RP "msg.no.paren")
9025 (setq pn (make-js2-paren-node :pos px-pos
9026 :expr expr
9027 :len (- js2-token-end px-pos)))
9028 (js2-node-add-children pn (js2-paren-node-expr pn))
9029 pn)
9030 ((= tt js2-XMLATTR)
9031 (js2-must-have-xml)
9032 (js2-parse-attribute-access))
9033 ((= tt js2-NAME)
9034 (js2-parse-name tt-flagged tt))
9035 ((= tt js2-NUMBER)
9036 (make-js2-number-node))
9037 ((= tt js2-STRING)
9038 (prog1
9039 (make-js2-string-node)
9040 (js2-record-face 'font-lock-string-face)))
9041 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9042 ;; Got / or /= which in this context means a regexp literal
9043 (setq px-pos js2-token-beg)
9044 (js2-read-regexp tt)
9045 (setq flags js2-ts-regexp-flags
9046 js2-ts-regexp-flags nil)
9047 (prog1
9048 (make-js2-regexp-node :pos px-pos
9049 :len (- js2-ts-cursor px-pos)
9050 :value js2-ts-string
9051 :flags flags)
9052 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9053 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9054 ((or (= tt js2-NULL)
9055 (= tt js2-THIS)
9056 (= tt js2-FALSE)
9057 (= tt js2-TRUE))
9058 (make-js2-keyword-node :type tt))
9059 ((= tt js2-RESERVED)
9060 (js2-report-error "msg.reserved.id")
9061 (make-js2-name-node))
9062 ((= tt js2-ERROR)
9063 ;; the scanner or one of its subroutines reported the error.
9064 (make-js2-error-node))
9065 ((= tt js2-EOF)
9066 (setq px-pos (point-at-bol)
9067 len (- js2-ts-cursor px-pos))
9068 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9069 (make-js2-error-node :pos px-pos :len len))
9070 (t
9071 (js2-report-error "msg.syntax")
9072 (make-js2-error-node)))))
9073
9074 (defun js2-parse-name (tt-flagged tt)
9075 (let ((name js2-ts-string)
9076 (name-pos js2-token-beg)
9077 node)
9078 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9079 (= (js2-peek-token) js2-COLON))
9080 (prog1
9081 ;; Do not consume colon, it is used as unwind indicator
9082 ;; to return to statementHelper.
9083 (make-js2-label-node :pos name-pos
9084 :len (- js2-token-end name-pos)
9085 :name name)
9086 (js2-set-face name-pos
9087 js2-token-end
9088 'font-lock-variable-name-face 'record))
9089 ;; Otherwise not a label, just a name. Unfortunately peeking
9090 ;; the next token to check for a colon has biffed js2-token-beg
9091 ;; and js2-token-end. We store the name's bounds in buffer vars
9092 ;; and `js2-create-name-node' uses them.
9093 (js2-save-name-token-data name-pos name)
9094 (setq node (if js2-compiler-xml-available
9095 (js2-parse-property-name nil name 0)
9096 (js2-create-name-node 'check-activation)))
9097 (if js2-highlight-external-variables
9098 (js2-record-name-node node))
9099 node)))
9100
9101 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9102 (js2-add-strict-warning
9103 msg nil
9104 ;; back up from comma to beginning of line or array/objlit
9105 (max (if elems
9106 (js2-node-pos (car elems))
9107 pos)
9108 (save-excursion
9109 (goto-char comma-pos)
9110 (back-to-indentation)
9111 (point)))
9112 comma-pos))
9113
9114 (defun js2-parse-array-literal ()
9115 (let ((pos js2-token-beg)
9116 (end js2-token-end)
9117 (after-lb-or-comma t)
9118 after-comma tt elems pn
9119 (continue t))
9120 (unless js2-is-in-destructuring
9121 (js2-push-scope (make-js2-scope))) ; for array comp
9122 (while continue
9123 (setq tt (js2-peek-token))
9124 (cond
9125 ;; comma
9126 ((= tt js2-COMMA)
9127 (js2-consume-token)
9128 (setq after-comma js2-token-end)
9129 (if (not after-lb-or-comma)
9130 (setq after-lb-or-comma t)
9131 (push nil elems)))
9132 ;; end of array
9133 ((or (= tt js2-RB)
9134 (= tt js2-EOF)) ; prevent infinite loop
9135 (if (= tt js2-EOF)
9136 (js2-report-error "msg.no.bracket.arg" nil pos)
9137 (js2-consume-token))
9138 (setq continue nil
9139 end js2-token-end
9140 pn (make-js2-array-node :pos pos
9141 :len (- js2-ts-cursor pos)
9142 :elems (nreverse elems)))
9143 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9144 (when (and after-comma (not js2-is-in-destructuring))
9145 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9146 pos elems after-comma)))
9147 ;; destructuring binding
9148 (js2-is-in-destructuring
9149 (push (if (or (= tt js2-LC)
9150 (= tt js2-LB)
9151 (= tt js2-NAME))
9152 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9153 (js2-parse-destruct-primary-expr)
9154 ;; invalid pattern
9155 (js2-consume-token)
9156 (js2-report-error "msg.bad.var")
9157 (make-js2-error-node))
9158 elems)
9159 (setq after-lb-or-comma nil
9160 after-comma nil))
9161 ;; array comp
9162 ((and (>= js2-language-version 170)
9163 (= tt js2-FOR) ; check for array comprehension
9164 (not after-lb-or-comma) ; "for" can't follow a comma
9165 elems ; must have at least 1 element
9166 (not (cdr elems))) ; but no 2nd element
9167 (setf continue nil
9168 pn (js2-parse-array-comprehension (car elems) pos)))
9169
9170 ;; another element
9171 (t
9172 (unless after-lb-or-comma
9173 (js2-report-error "msg.no.bracket.arg"))
9174 (push (js2-parse-assign-expr) elems)
9175 (setq after-lb-or-comma nil
9176 after-comma nil))))
9177 (unless js2-is-in-destructuring
9178 (js2-pop-scope))
9179 pn))
9180
9181 (defun js2-parse-array-comprehension (expr pos)
9182 "Parse a JavaScript 1.7 Array Comprehension.
9183 EXPR is the first expression after the opening left-bracket.
9184 POS is the beginning of the LB token preceding EXPR.
9185 We should have just parsed the 'for' keyword before calling this function."
9186 (let (loops loop first prev filter if-pos result)
9187 (while (= (js2-peek-token) js2-FOR)
9188 (let ((prev (car loops))) ; rearrange scope chain
9189 (push (setq loop (js2-parse-array-comp-loop)) loops)
9190 (if prev ; each loop is parent scope to the next one
9191 (setf (js2-scope-parent-scope loop) prev)
9192 ; first loop takes expr scope's parent
9193 (setf (js2-scope-parent-scope (setq first loop))
9194 (js2-scope-parent-scope js2-current-scope)))))
9195 ;; set expr scope's parent to the last loop
9196 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9197 (when (= (js2-peek-token) js2-IF)
9198 (js2-consume-token)
9199 (setq if-pos (- js2-token-beg pos) ; relative
9200 filter (js2-parse-condition)))
9201 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9202 (setq result (make-js2-array-comp-node :pos pos
9203 :len (- js2-ts-cursor pos)
9204 :result expr
9205 :loops (nreverse loops)
9206 :filter (car filter)
9207 :lp (js2-relpos (second filter) pos)
9208 :rp (js2-relpos (third filter) pos)
9209 :if-pos if-pos))
9210 (apply #'js2-node-add-children result expr (car filter)
9211 (js2-array-comp-node-loops result))
9212 (setq js2-current-scope first) ; pop to the first loop
9213 result))
9214
9215 (defun js2-parse-array-comp-loop ()
9216 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9217 Last token peeked should be the initial FOR."
9218 (let ((pos js2-token-beg)
9219 (pn (make-js2-array-comp-loop-node))
9220 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9221 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9222 (js2-push-scope pn)
9223 (unwind-protect
9224 (progn
9225 (when (js2-match-token js2-NAME)
9226 (if (string= js2-ts-string "each")
9227 (progn
9228 (setq foreach-p t
9229 each-pos (- js2-token-beg pos)) ; relative
9230 (js2-record-face 'font-lock-keyword-face))
9231 (js2-report-error "msg.no.paren.for")))
9232 (if (js2-must-match js2-LP "msg.no.paren.for")
9233 (setq lp (- js2-token-beg pos)))
9234 (setq tt (js2-peek-token))
9235 (cond
9236 ((or (= tt js2-LB)
9237 (= tt js2-LC))
9238 (setq iter (js2-parse-destruct-primary-expr))
9239 (js2-define-destruct-symbols iter js2-LET
9240 'font-lock-variable-name-face t))
9241 ((js2-match-token js2-NAME)
9242 (setq iter (js2-create-name-node)))
9243 (t
9244 (js2-report-error "msg.bad.var")))
9245 ;; Define as a let since we want the scope of the variable to
9246 ;; be restricted to the array comprehension
9247 (if (js2-name-node-p iter)
9248 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9249 (if (or (js2-match-token js2-IN)
9250 (and (>= js2-language-version 200)
9251 (js2-match-contextual-kwd "of")
9252 (setq forof-p t)))
9253 (setq in-pos (- js2-token-beg pos))
9254 (js2-report-error "msg.in.after.for.name"))
9255 (setq obj (js2-parse-expr))
9256 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9257 (setq rp (- js2-token-beg pos)))
9258 (setf (js2-node-pos pn) pos
9259 (js2-node-len pn) (- js2-ts-cursor pos)
9260 (js2-array-comp-loop-node-iterator pn) iter
9261 (js2-array-comp-loop-node-object pn) obj
9262 (js2-array-comp-loop-node-in-pos pn) in-pos
9263 (js2-array-comp-loop-node-each-pos pn) each-pos
9264 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9265 (js2-array-comp-loop-node-forof-p pn) forof-p
9266 (js2-array-comp-loop-node-lp pn) lp
9267 (js2-array-comp-loop-node-rp pn) rp)
9268 (js2-node-add-children pn iter obj))
9269 (js2-pop-scope))
9270 pn))
9271
9272 (defun js2-parse-object-literal ()
9273 (let ((pos js2-token-beg)
9274 tt elems result after-comma
9275 (continue t))
9276 (while continue
9277 (setq tt (js2-peek-token))
9278 (cond
9279 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9280 ;; {get foo() {...}}, or {set foo(x) {...}}
9281 ((or (js2-valid-prop-name-token tt)
9282 (= tt js2-STRING))
9283 (setq after-comma nil
9284 result (js2-parse-named-prop tt))
9285 (if (and (null result)
9286 (not js2-recover-from-parse-errors))
9287 (setq continue nil)
9288 (push result elems)))
9289 ;; {12: x} or {10.7: x}
9290 ((= tt js2-NUMBER)
9291 (js2-consume-token)
9292 (setq after-comma nil)
9293 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9294 ;; trailing comma
9295 ((= tt js2-RC)
9296 (setq continue nil)
9297 (if after-comma
9298 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9299 pos elems after-comma)))
9300 (t
9301 (js2-report-error "msg.bad.prop")
9302 (unless js2-recover-from-parse-errors
9303 (setq continue nil)))) ; end switch
9304 (if (js2-match-token js2-COMMA)
9305 (setq after-comma js2-token-end)
9306 (setq continue nil))) ; end loop
9307 (js2-must-match js2-RC "msg.no.brace.prop")
9308 (setq result (make-js2-object-node :pos pos
9309 :len (- js2-ts-cursor pos)
9310 :elems (nreverse elems)))
9311 (apply #'js2-node-add-children result (js2-object-node-elems result))
9312 result))
9313
9314 (defun js2-parse-named-prop (tt)
9315 "Parse a name, string, or getter/setter object property.
9316 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9317 (js2-consume-token)
9318 (let ((string-prop (and (= tt js2-STRING)
9319 (make-js2-string-node)))
9320 expr
9321 (ppos js2-token-beg)
9322 (pend js2-token-end)
9323 (name (js2-create-name-node))
9324 (prop js2-ts-string))
9325 (cond
9326 ;; getter/setter prop
9327 ((and (= tt js2-NAME)
9328 (= (js2-peek-token) js2-NAME)
9329 (or (string= prop "get")
9330 (string= prop "set")))
9331 (js2-consume-token)
9332 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9333 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9334 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9335 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9336 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9337 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9338 ;; when patterns are used in variable declarations, function parameters,
9339 ;; catch-clause, and iterators.
9340 ;; We have to set `js2-is-in-destructuring' to t when the current
9341 ;; expressions are on the left side of any assignment, but it's difficult
9342 ;; because it requires looking ahead of expression.
9343 ((and js2-is-in-destructuring
9344 (= tt js2-NAME)
9345 (let ((ctk (js2-peek-token)))
9346 (or (= ctk js2-COMMA)
9347 (= ctk js2-RC)
9348 (js2-valid-prop-name-token ctk))))
9349 name)
9350 ;; regular prop
9351 (t
9352 (prog1
9353 (setq expr (js2-parse-plain-property (or string-prop name)))
9354 (js2-set-face ppos pend
9355 (if (js2-function-node-p
9356 (js2-object-prop-node-right expr))
9357 'font-lock-function-name-face
9358 'font-lock-variable-name-face)
9359 'record))))))
9360
9361 (defun js2-parse-plain-property (prop)
9362 "Parse a non-getter/setter property in an object literal.
9363 PROP is the node representing the property: a number, name or string."
9364 (js2-must-match js2-COLON "msg.no.colon.prop")
9365 (let* ((pos (js2-node-pos prop))
9366 (colon (- js2-token-beg pos))
9367 (expr (js2-parse-assign-expr))
9368 (result (make-js2-object-prop-node
9369 :pos pos
9370 ;; don't include last consumed token in length
9371 :len (- (+ (js2-node-pos expr)
9372 (js2-node-len expr))
9373 pos)
9374 :left prop
9375 :right expr
9376 :op-pos colon)))
9377 (js2-node-add-children result prop expr)
9378 result))
9379
9380 (defun js2-parse-getter-setter-prop (pos prop get-p)
9381 "Parse getter or setter property in an object literal.
9382 JavaScript syntax is:
9383
9384 { get foo() {...}, set foo(x) {...} }
9385
9386 and expression closure style is also supported
9387
9388 { get foo() x, set foo(x) _x = x }
9389
9390 POS is the start position of the `get' or `set' keyword.
9391 PROP is the `js2-name-node' representing the property name.
9392 GET-P is non-nil if the keyword was `get'."
9393 (let ((type (if get-p js2-GET js2-SET))
9394 result end
9395 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9396 ;; it has to be an anonymous function, as we already parsed the name
9397 (if (/= (js2-node-type fn) js2-FUNCTION)
9398 (js2-report-error "msg.bad.prop")
9399 (if (plusp (length (js2-function-name fn)))
9400 (js2-report-error "msg.bad.prop")))
9401 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9402 (setq end (js2-node-end fn)
9403 result (make-js2-getter-setter-node :type type
9404 :pos pos
9405 :len (- end pos)
9406 :left prop
9407 :right fn))
9408 (js2-node-add-children result prop fn)
9409 result))
9410
9411 (defun js2-create-name-node (&optional check-activation-p token)
9412 "Create a name node using the token info from last scanned name.
9413 In some cases we need to either synthesize a name node, or we lost
9414 the name token information by peeking. If the TOKEN parameter is
9415 not `js2-NAME', then we use the token info saved in instance vars."
9416 (let ((beg js2-token-beg)
9417 (s js2-ts-string)
9418 name)
9419 (when (/= js2-current-token js2-NAME)
9420 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9421 s js2-prev-name-token-string
9422 js2-prev-name-token-start nil
9423 js2-prev-name-token-string nil))
9424 (setq name (make-js2-name-node :pos beg
9425 :name s
9426 :len (length s)))
9427 (if check-activation-p
9428 (js2-check-activation-name s (or token js2-NAME)))
9429 name))
9430
9431 ;;; Indentation support
9432
9433 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9434 ;; Karl cleverly deduces that the desired indentation level is often a
9435 ;; function of paren/bracket/brace nesting depth, which can be determined
9436 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9437 ;; then does some equally clever checks to see if we're in the context of a
9438 ;; substatement of a possibly braceless statement keyword such as if, while,
9439 ;; or finally. This approach yields pretty good results.
9440
9441 ;; The indenter is often "wrong", however, and needs to be overridden.
9442 ;; The right long-term solution is probably to emulate (or integrate
9443 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9444 ;; parse tree from `js2-parse' is present, which is not true at the
9445 ;; moment the user is typing, computing indentation is still thousands
9446 ;; of lines of code to handle every possible syntactic edge case.
9447
9448 ;; In the meantime, the compromise solution is that we offer a "bounce
9449 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9450 ;; current line indent among various likely guess points. This approach
9451 ;; is far from perfect, but should at least make it slightly easier to
9452 ;; move the line towards its desired indentation when manually
9453 ;; overriding Karl's heuristic nesting guesser.
9454
9455 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9456 ;; extensions such as `let' and Array comprehensions. Major kudos to
9457 ;; Karl for coming up with the initial approach, which packs a lot of
9458 ;; punch for so little code.
9459
9460 (defconst js2-possibly-braceless-keywords-re
9461 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9462 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9463 "try" "while" "with" "let")))
9464 "Regular expression matching keywords that are optionally
9465 followed by an opening brace.")
9466
9467 (defconst js2-indent-operator-re
9468 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9469 (regexp-opt '("in" "instanceof") 'words))
9470 "Regular expression matching operators that affect indentation
9471 of continued expressions.")
9472
9473 (defconst js2-declaration-keyword-re
9474 (regexp-opt '("var" "let" "const") 'words)
9475 "Regular expression matching variable declaration keywords.")
9476
9477 (defun js2-re-search-forward-inner (regexp &optional bound count)
9478 "Auxiliary function for `js2-re-search-forward'."
9479 (let (parse saved-point)
9480 (while (> count 0)
9481 (re-search-forward regexp bound)
9482 (setq parse (if saved-point
9483 (parse-partial-sexp saved-point (point))
9484 (syntax-ppss (point))))
9485 (cond ((nth 3 parse)
9486 (re-search-forward
9487 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9488 (save-excursion (end-of-line) (point)) t))
9489 ((nth 7 parse)
9490 (forward-line))
9491 ((or (nth 4 parse)
9492 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9493 (re-search-forward "\\*/"))
9494 (t
9495 (setq count (1- count))))
9496 (setq saved-point (point))))
9497 (point))
9498
9499 (defun js2-re-search-forward (regexp &optional bound noerror count)
9500 "Search forward but ignore strings and comments.
9501 Invokes `re-search-forward' but treats the buffer as if strings
9502 and comments have been removed."
9503 (let ((saved-point (point))
9504 (search-expr
9505 (cond ((null count)
9506 '(js2-re-search-forward-inner regexp bound 1))
9507 ((< count 0)
9508 '(js2-re-search-backward-inner regexp bound (- count)))
9509 ((> count 0)
9510 '(js2-re-search-forward-inner regexp bound count)))))
9511 (condition-case err
9512 (eval search-expr)
9513 (search-failed
9514 (goto-char saved-point)
9515 (unless noerror
9516 (error (error-message-string err)))))))
9517
9518 (defun js2-re-search-backward-inner (regexp &optional bound count)
9519 "Auxiliary function for `js2-re-search-backward'."
9520 (let (parse)
9521 (while (> count 0)
9522 (re-search-backward regexp bound)
9523 (setq parse (syntax-ppss (point)))
9524 (cond ((nth 3 parse)
9525 (re-search-backward
9526 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9527 (line-beginning-position) t))
9528 ((nth 7 parse)
9529 (goto-char (nth 8 parse)))
9530 ((or (nth 4 parse)
9531 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9532 (re-search-backward "/\\*"))
9533 (t
9534 (setq count (1- count))))))
9535 (point))
9536
9537 (defun js2-re-search-backward (regexp &optional bound noerror count)
9538 "Search backward but ignore strings and comments.
9539 Invokes `re-search-backward' but treats the buffer as if strings
9540 and comments have been removed."
9541 (let ((saved-point (point))
9542 (search-expr
9543 (cond ((null count)
9544 '(js2-re-search-backward-inner regexp bound 1))
9545 ((< count 0)
9546 '(js2-re-search-forward-inner regexp bound (- count)))
9547 ((> count 0)
9548 '(js2-re-search-backward-inner regexp bound count)))))
9549 (condition-case err
9550 (eval search-expr)
9551 (search-failed
9552 (goto-char saved-point)
9553 (unless noerror
9554 (error (error-message-string err)))))))
9555
9556 (defun js2-looking-at-operator-p ()
9557 "Return non-nil if text after point is a non-comma operator."
9558 (and (looking-at js2-indent-operator-re)
9559 (or (not (looking-at ":"))
9560 (save-excursion
9561 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9562 (looking-at "?"))))))
9563
9564 (defun js2-continued-expression-p ()
9565 "Return non-nil if the current line continues an expression."
9566 (save-excursion
9567 (back-to-indentation)
9568 (or (js2-looking-at-operator-p)
9569 (when (catch 'found
9570 (while (and (re-search-backward "\n" nil t)
9571 (let ((state (syntax-ppss)))
9572 (when (nth 4 state)
9573 (goto-char (nth 8 state))) ;; skip comments
9574 (skip-chars-backward " \t")
9575 (if (bolp)
9576 t
9577 (throw 'found t))))))
9578 (backward-char)
9579 (when (js2-looking-at-operator-p)
9580 (backward-char)
9581 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))
9582
9583 (defun js2-end-of-do-while-loop-p ()
9584 "Return non-nil if word after point is `while' of a do-while
9585 statement, else returns nil. A braceless do-while statement
9586 spanning several lines requires that the start of the loop is
9587 indented to the same column as the current line."
9588 (interactive)
9589 (save-excursion
9590 (when (looking-at "\\s-*\\<while\\>")
9591 (if (save-excursion
9592 (skip-chars-backward "[ \t\n]*}")
9593 (looking-at "[ \t\n]*}"))
9594 (save-excursion
9595 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9596 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9597 (or (looking-at "\\<do\\>")
9598 (let ((saved-indent (current-indentation)))
9599 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9600 (/= (current-indentation) saved-indent)))
9601 (and (looking-at "[ \t]*\\<do\\>")
9602 (not (js2-re-search-forward
9603 "\\<while\\>" (point-at-eol) t))
9604 (= (current-indentation) saved-indent))))))))
9605
9606 (defun js2-multiline-decl-indentation ()
9607 "Return the declaration indentation column if the current line belongs
9608 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9609 (let (forward-sexp-function ; use Lisp version
9610 at-opening-bracket)
9611 (save-excursion
9612 (back-to-indentation)
9613 (when (not (looking-at js2-declaration-keyword-re))
9614 (when (looking-at js2-indent-operator-re)
9615 (goto-char (match-end 0))) ; continued expressions are ok
9616 (while (and (not at-opening-bracket)
9617 (not (bobp))
9618 (let ((pos (point)))
9619 (save-excursion
9620 (js2-backward-sws)
9621 (or (eq (char-before) ?,)
9622 (and (not (eq (char-before) ?\;))
9623 (prog2 (skip-syntax-backward ".")
9624 (looking-at js2-indent-operator-re)
9625 (js2-backward-sws))
9626 (not (eq (char-before) ?\;)))
9627 (js2-same-line pos)))))
9628 (condition-case err
9629 (backward-sexp)
9630 (scan-error (setq at-opening-bracket t))))
9631 (when (looking-at js2-declaration-keyword-re)
9632 (goto-char (match-end 0))
9633 (1+ (current-column)))))))
9634
9635 (defun js2-ctrl-statement-indentation ()
9636 "Return the proper indentation of current line if it is a control statement.
9637 Returns an indentation if this line starts the body of a control
9638 statement without braces, else returns nil."
9639 (let (forward-sexp-function)
9640 (save-excursion
9641 (back-to-indentation)
9642 (when (and (not (js2-same-line (point-min)))
9643 (not (looking-at "{"))
9644 (js2-re-search-backward "[[:graph:]]" nil t)
9645 (not (looking-at "[{([]"))
9646 (progn
9647 (forward-char)
9648 (when (= (char-before) ?\))
9649 ;; scan-sexps sometimes throws an error
9650 (ignore-errors (backward-sexp))
9651 (skip-chars-backward " \t" (point-at-bol)))
9652 (let ((pt (point)))
9653 (back-to-indentation)
9654 (when (looking-at "}[ \t]*")
9655 (goto-char (match-end 0)))
9656 (and (looking-at js2-possibly-braceless-keywords-re)
9657 (= (match-end 0) pt)
9658 (not (js2-end-of-do-while-loop-p))))))
9659 (+ (current-indentation) js2-basic-offset)))))
9660
9661 (defun js2-indent-in-array-comp (parse-status)
9662 "Return non-nil if we think we're in an array comprehension.
9663 In particular, return the buffer position of the first `for' kwd."
9664 (let ((bracket (nth 1 parse-status))
9665 (end (point)))
9666 (when bracket
9667 (save-excursion
9668 (goto-char bracket)
9669 (when (looking-at "\\[")
9670 (forward-char 1)
9671 (js2-forward-sws)
9672 (if (looking-at "[[{]")
9673 (let (forward-sexp-function) ; use Lisp version
9674 (forward-sexp) ; skip destructuring form
9675 (js2-forward-sws)
9676 (if (and (/= (char-after) ?,) ; regular array
9677 (looking-at "for"))
9678 (match-beginning 0)))
9679 ;; to skip arbitrary expressions we need the parser,
9680 ;; so we'll just guess at it.
9681 (if (and (> end (point)) ; not empty literal
9682 (re-search-forward "[^,]]* \\(for\\) " end t)
9683 ;; not inside comment or string literal
9684 (let ((state (parse-partial-sexp bracket (point))))
9685 (not (or (nth 3 state) (nth 4 state)))))
9686 (match-beginning 1))))))))
9687
9688 (defun js2-array-comp-indentation (parse-status for-kwd)
9689 (if (js2-same-line for-kwd)
9690 ;; first continuation line
9691 (save-excursion
9692 (goto-char (nth 1 parse-status))
9693 (forward-char 1)
9694 (skip-chars-forward " \t")
9695 (current-column))
9696 (save-excursion
9697 (goto-char for-kwd)
9698 (current-column))))
9699
9700 (defun js2-proper-indentation (parse-status)
9701 "Return the proper indentation for the current line."
9702 (save-excursion
9703 (back-to-indentation)
9704 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9705 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9706 (continued-expr-p (js2-continued-expression-p))
9707 (declaration-indent (and js2-pretty-multiline-declarations
9708 (js2-multiline-decl-indentation)))
9709 (bracket (nth 1 parse-status))
9710 beg)
9711 (cond
9712 ;; indent array comprehension continuation lines specially
9713 ((and bracket
9714 (>= js2-language-version 170)
9715 (not (js2-same-line bracket))
9716 (setq beg (js2-indent-in-array-comp parse-status))
9717 (>= (point) (save-excursion
9718 (goto-char beg)
9719 (point-at-bol)))) ; at or after first loop?
9720 (js2-array-comp-indentation parse-status beg))
9721
9722 (ctrl-stmt-indent)
9723
9724 ((and declaration-indent continued-expr-p)
9725 (+ declaration-indent js2-basic-offset))
9726
9727 (declaration-indent)
9728
9729 (bracket
9730 (goto-char bracket)
9731 (cond
9732 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9733 (when (save-excursion (skip-chars-backward " \t)")
9734 (looking-at ")"))
9735 (backward-list))
9736 (back-to-indentation)
9737 (and (eq js2-pretty-multiline-declarations 'all)
9738 (looking-at js2-declaration-keyword-re)
9739 (goto-char (1+ (match-end 0))))
9740 (cond (same-indent-p
9741 (current-column))
9742 (continued-expr-p
9743 (+ (current-column) (* 2 js2-basic-offset)))
9744 (t
9745 (+ (current-column) js2-basic-offset))))
9746 (t
9747 (unless same-indent-p
9748 (forward-char)
9749 (skip-chars-forward " \t"))
9750 (current-column))))
9751
9752 (continued-expr-p js2-basic-offset)
9753
9754 (t 0)))))
9755
9756 (defun js2-lineup-comment (parse-status)
9757 "Indent a multi-line block comment continuation line."
9758 (let* ((beg (nth 8 parse-status))
9759 (first-line (js2-same-line beg))
9760 (offset (save-excursion
9761 (goto-char beg)
9762 (if (looking-at "/\\*")
9763 (+ 1 (current-column))
9764 0))))
9765 (unless first-line
9766 (indent-line-to offset))))
9767
9768 (defun js2-backward-sws ()
9769 "Move backward through whitespace and comments."
9770 (interactive)
9771 (while (forward-comment -1)))
9772
9773 (defun js2-forward-sws ()
9774 "Move forward through whitespace and comments."
9775 (interactive)
9776 (while (forward-comment 1)))
9777
9778 (defun js2-current-indent (&optional pos)
9779 "Return column of indentation on current line.
9780 If POS is non-nil, go to that point and return indentation for that line."
9781 (save-excursion
9782 (if pos
9783 (goto-char pos))
9784 (back-to-indentation)
9785 (current-column)))
9786
9787 (defun js2-arglist-close ()
9788 "Return non-nil if we're on a line beginning with a close-paren/brace."
9789 (save-excursion
9790 (goto-char (point-at-bol))
9791 (js2-forward-sws)
9792 (looking-at "[])}]")))
9793
9794 (defun js2-indent-looks-like-label-p ()
9795 (goto-char (point-at-bol))
9796 (js2-forward-sws)
9797 (looking-at (concat js2-mode-identifier-re ":")))
9798
9799 (defun js2-indent-in-objlit-p (parse-status)
9800 "Return non-nil if this looks like an object-literal entry."
9801 (let ((start (nth 1 parse-status)))
9802 (and
9803 start
9804 (save-excursion
9805 (and (zerop (forward-line -1))
9806 (not (< (point) start)) ; crossed a {} boundary
9807 (js2-indent-looks-like-label-p)))
9808 (save-excursion
9809 (js2-indent-looks-like-label-p)))))
9810
9811 ;; If prev line looks like foobar({ then we're passing an object
9812 ;; literal to a function call, and people pretty much always want to
9813 ;; de-dent back to the previous line, so move the 'basic-offset'
9814 ;; position to the front.
9815 (defun js2-indent-objlit-arg-p (parse-status)
9816 (save-excursion
9817 (back-to-indentation)
9818 (js2-backward-sws)
9819 (and (eq (1- (point)) (nth 1 parse-status))
9820 (eq (char-before) ?{)
9821 (progn
9822 (forward-char -1)
9823 (skip-chars-backward " \t")
9824 (eq (char-before) ?\()))))
9825
9826 (defun js2-indent-case-block-p ()
9827 (save-excursion
9828 (back-to-indentation)
9829 (js2-backward-sws)
9830 (goto-char (point-at-bol))
9831 (skip-chars-forward " \t")
9832 (looking-at "case\\s-.+:")))
9833
9834 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
9835 "Cycle among alternate computed indentation positions.
9836 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9837 of the buffer to the current point. NORMAL-COL is the indentation
9838 column computed by the heuristic guesser based on current paren,
9839 bracket, brace and statement nesting. If BACKWARDS, cycle positions
9840 in reverse."
9841 (let ((cur-indent (js2-current-indent))
9842 (old-buffer-undo-list buffer-undo-list)
9843 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9844 (current-line (save-excursion
9845 (forward-line 0) ; move to bol
9846 (1+ (count-lines (point-min) (point)))))
9847 positions pos main-pos anchor arglist-cont same-indent
9848 prev-line-col basic-offset computed-pos)
9849 ;; temporarily don't record undo info, if user requested this
9850 (when js2-mode-indent-inhibit-undo
9851 (setq buffer-undo-list t))
9852 (unwind-protect
9853 (progn
9854 ;; First likely point: indent from beginning of previous code line
9855 (push (setq basic-offset
9856 (+ (save-excursion
9857 (back-to-indentation)
9858 (js2-backward-sws)
9859 (back-to-indentation)
9860 (setq prev-line-col (current-column)))
9861 js2-basic-offset))
9862 positions)
9863
9864 ;; (First + epsilon) likely point: indent 2x from beginning of
9865 ;; previous code line. Google does it this way.
9866 (push (setq basic-offset
9867 (+ (save-excursion
9868 (back-to-indentation)
9869 (js2-backward-sws)
9870 (back-to-indentation)
9871 (setq prev-line-col (current-column)))
9872 (* 2 js2-basic-offset)))
9873 positions)
9874
9875 ;; Second likely point: indent from assign-expr RHS. This
9876 ;; is just a crude guess based on finding " = " on the previous
9877 ;; line containing actual code.
9878 (setq pos (save-excursion
9879 (forward-line -1)
9880 (goto-char (point-at-bol))
9881 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
9882 (point-at-eol) t)
9883 (goto-char (match-end 1))
9884 (skip-chars-forward " \t\r\n")
9885 (current-column))))
9886 (when pos
9887 (incf pos js2-basic-offset)
9888 (push pos positions))
9889
9890 ;; Third likely point: same indent as previous line of code.
9891 ;; Make it the first likely point if we're not on an
9892 ;; arglist-close line and previous line ends in a comma, or
9893 ;; both this line and prev line look like object-literal
9894 ;; elements.
9895 (setq pos (save-excursion
9896 (goto-char (point-at-bol))
9897 (js2-backward-sws)
9898 (back-to-indentation)
9899 (prog1
9900 (current-column)
9901 ;; while we're here, look for trailing comma
9902 (if (save-excursion
9903 (goto-char (point-at-eol))
9904 (js2-backward-sws)
9905 (eq (char-before) ?,))
9906 (setq arglist-cont (1- (point)))))))
9907 (when pos
9908 (if (and (or arglist-cont
9909 (js2-indent-in-objlit-p parse-status))
9910 (not (js2-arglist-close)))
9911 (setq same-indent pos))
9912 (push pos positions))
9913
9914 ;; Fourth likely point: first preceding code with less indentation.
9915 ;; than the immediately preceding code line.
9916 (setq pos (save-excursion
9917 (back-to-indentation)
9918 (js2-backward-sws)
9919 (back-to-indentation)
9920 (setq anchor (current-column))
9921 (while (and (zerop (forward-line -1))
9922 (>= (progn
9923 (back-to-indentation)
9924 (current-column))
9925 anchor)))
9926 (setq pos (current-column))))
9927 (push pos positions)
9928
9929 ;; nesting-heuristic position, main by default
9930 (push (setq main-pos normal-col) positions)
9931
9932 ;; delete duplicates and sort positions list
9933 (setq positions (sort (delete-dups positions) '<))
9934
9935 ;; comma-list continuation lines: prev line indent takes precedence
9936 (if same-indent
9937 (setq main-pos same-indent))
9938
9939 ;; common special cases where we want to indent in from previous line
9940 (if (or (js2-indent-case-block-p)
9941 (js2-indent-objlit-arg-p parse-status))
9942 (setq main-pos basic-offset))
9943
9944 ;; if bouncing backwards, reverse positions list
9945 (if backwards
9946 (setq positions (reverse positions)))
9947
9948 ;; record whether we're already sitting on one of the alternatives
9949 (setq pos (member cur-indent positions))
9950
9951 (cond
9952 ;; case 0: we're one one of the alternatives and this is the
9953 ;; first time they've pressed TAB on this line (best-guess).
9954 ((and js2-mode-indent-ignore-first-tab
9955 pos
9956 ;; first time pressing TAB on this line?
9957 (not (eq js2-mode-last-indented-line current-line)))
9958 ;; do nothing
9959 (setq computed-pos nil))
9960 ;; case 1: only one computed position => use it
9961 ((null (cdr positions))
9962 (setq computed-pos 0))
9963 ;; case 2: not on any of the computed spots => use main spot
9964 ((not pos)
9965 (setq computed-pos (js2-position main-pos positions)))
9966 ;; case 3: on last position: cycle to first position
9967 ((null (cdr pos))
9968 (setq computed-pos 0))
9969 ;; case 4: on intermediate position: cycle to next position
9970 (t
9971 (setq computed-pos (js2-position (second pos) positions))))
9972
9973 ;; see if any hooks want to indent; otherwise we do it
9974 (loop with result = nil
9975 for hook in js2-indent-hook
9976 while (null result)
9977 do
9978 (setq result (funcall hook positions computed-pos))
9979 finally do
9980 (unless (or result (null computed-pos))
9981 (indent-line-to (nth computed-pos positions)))))
9982
9983 ;; finally
9984 (if js2-mode-indent-inhibit-undo
9985 (setq buffer-undo-list old-buffer-undo-list))
9986 ;; see commentary for `js2-mode-last-indented-line'
9987 (setq js2-mode-last-indented-line current-line))))
9988
9989 (defun js2-indent-bounce-backwards ()
9990 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
9991 cycles between the computed indentation positions in reverse order."
9992 (interactive)
9993 (js2-indent-line t))
9994
9995 (defun js2-1-line-comment-continuation-p ()
9996 "Return t if we're in a 1-line comment continuation.
9997 If so, we don't ever want to use bounce-indent."
9998 (save-excursion
9999 (and (progn
10000 (forward-line 0)
10001 (looking-at "\\s-*//"))
10002 (progn
10003 (forward-line -1)
10004 (forward-line 0)
10005 (when (looking-at "\\s-*$")
10006 (js2-backward-sws)
10007 (forward-line 0))
10008 (looking-at "\\s-*//")))))
10009
10010 (defun js2-indent-line (&optional bounce-backwards)
10011 "Indent the current line as JavaScript source text."
10012 (interactive)
10013 (let (parse-status current-indent offset indent-col moved
10014 ;; Don't whine about errors/warnings when we're indenting.
10015 ;; This has to be set before calling parse-partial-sexp below.
10016 (inhibit-point-motion-hooks t))
10017 (setq parse-status (save-excursion
10018 (syntax-ppss (point-at-bol)))
10019 offset (- (point) (save-excursion
10020 (back-to-indentation)
10021 (point))))
10022 (js2-with-underscore-as-word-syntax
10023 (if (nth 4 parse-status)
10024 (js2-lineup-comment parse-status)
10025 (setq indent-col (js2-proper-indentation parse-status))
10026 ;; See comments below about `js2-mode-last-indented-line'.
10027 (cond
10028 ;; bounce-indenting is disabled during electric-key indent.
10029 ;; It doesn't work well on first line of buffer.
10030 ((and js2-bounce-indent-p
10031 (not (js2-same-line (point-min)))
10032 (not (js2-1-line-comment-continuation-p)))
10033 (js2-bounce-indent indent-col parse-status bounce-backwards))
10034 ;; just indent to the guesser's likely spot
10035 (t (indent-line-to indent-col))))
10036 (when (plusp offset)
10037 (forward-char offset)))))
10038
10039 (defun js2-indent-region (start end)
10040 "Indent the region, but don't use bounce indenting."
10041 (let ((js2-bounce-indent-p nil)
10042 (indent-region-function nil)
10043 (after-change-functions (remq 'js2-mode-edit
10044 after-change-functions)))
10045 (indent-region start end nil) ; nil for byte-compiler
10046 (js2-mode-edit start end (- end start))))
10047
10048 (defvar js2-minor-mode-map
10049 (let ((map (make-sparse-keymap)))
10050 (define-key map (kbd "C-c C-`") #'js2-next-error)
10051 (define-key map [mouse-1] #'js2-mode-show-node)
10052 map)
10053 "Keymap used when `js2-minor-mode' is active.")
10054
10055 ;;;###autoload
10056 (define-minor-mode js2-minor-mode
10057 "Minor mode for running js2 as a background linter.
10058 This allows you to use a different major mode for JavaScript editing,
10059 such as `espresso-mode', while retaining the asynchronous error/warning
10060 highlighting features of `js2-mode'."
10061 :group 'js2-mode
10062 :lighter " js-lint"
10063 (if js2-minor-mode
10064 (js2-minor-mode-enter)
10065 (js2-minor-mode-exit)))
10066
10067 (defun js2-minor-mode-enter ()
10068 "Initialization for `js2-minor-mode'."
10069 (set (make-local-variable 'max-lisp-eval-depth)
10070 (max max-lisp-eval-depth 3000))
10071 (setq next-error-function #'js2-next-error)
10072 (js2-set-default-externs)
10073 ;; Experiment: make reparse-delay longer for longer files.
10074 (if (plusp js2-dynamic-idle-timer-adjust)
10075 (setq js2-idle-timer-delay
10076 (* js2-idle-timer-delay
10077 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10078 (setq js2-mode-buffer-dirty-p t
10079 js2-mode-parsing nil)
10080 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10081 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10082 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10083 (js2-reparse))
10084
10085 (defun js2-minor-mode-exit ()
10086 "Turn off `js2-minor-mode'."
10087 (setq next-error-function nil)
10088 (remove-hook 'after-change-functions #'js2-mode-edit t)
10089 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10090 (when js2-mode-node-overlay
10091 (delete-overlay js2-mode-node-overlay)
10092 (setq js2-mode-node-overlay nil))
10093 (js2-remove-overlays)
10094 (setq js2-mode-ast nil))
10095
10096 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10097 (make-variable-buffer-local 'js2-source-buffer)
10098
10099 (defun* js2-display-error-list ()
10100 "Display a navigable buffer listing parse errors/warnings."
10101 (interactive)
10102 (unless (js2-have-errors-p)
10103 (message "No errors")
10104 (return-from js2-display-error-list))
10105 (labels ((annotate-list
10106 (lst type)
10107 "Add diagnostic TYPE and line number to errs list"
10108 (mapcar (lambda (err)
10109 (list err type (line-number-at-pos (nth 1 err))))
10110 lst)))
10111 (let* ((srcbuf (current-buffer))
10112 (errbuf (get-buffer-create "*js-lint*"))
10113 (errors (annotate-list
10114 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10115 'js2-error)) ; must be a valid face name
10116 (warnings (annotate-list
10117 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10118 'js2-warning)) ; must be a valid face name
10119 (all-errs (sort (append errors warnings)
10120 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10121 (with-current-buffer errbuf
10122 (let ((inhibit-read-only t))
10123 (erase-buffer)
10124 (dolist (err all-errs)
10125 (destructuring-bind ((msg-key beg end &rest) type line) err
10126 (insert-text-button
10127 (format "line %d: %s" line (js2-get-msg msg-key))
10128 'face type
10129 'follow-link "\C-m"
10130 'action 'js2-error-buffer-jump
10131 'js2-msg (js2-get-msg msg-key)
10132 'js2-pos beg)
10133 (insert "\n"))))
10134 (js2-error-buffer-mode)
10135 (setq js2-source-buffer srcbuf)
10136 (pop-to-buffer errbuf)
10137 (goto-char (point-min))
10138 (unless (eobp)
10139 (js2-error-buffer-view))))))
10140
10141 (defvar js2-error-buffer-mode-map
10142 (let ((map (make-sparse-keymap)))
10143 (define-key map "n" #'js2-error-buffer-next)
10144 (define-key map "p" #'js2-error-buffer-prev)
10145 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10146 (define-key map "o" #'js2-error-buffer-view)
10147 (define-key map "q" #'js2-error-buffer-quit)
10148 map)
10149 "Keymap used for js2 diagnostics buffers.")
10150
10151 (defun js2-error-buffer-mode ()
10152 "Major mode for js2 diagnostics buffers.
10153 Selecting an error will jump it to the corresponding source-buffer error.
10154 \\{js2-error-buffer-mode-map}"
10155 (interactive)
10156 (setq major-mode 'js2-error-buffer-mode
10157 mode-name "JS Lint Diagnostics")
10158 (use-local-map js2-error-buffer-mode-map)
10159 (setq truncate-lines t)
10160 (set-buffer-modified-p nil)
10161 (setq buffer-read-only t)
10162 (run-hooks 'js2-error-buffer-mode-hook))
10163
10164 (defun js2-error-buffer-next ()
10165 "Move to next error and view it."
10166 (interactive)
10167 (when (zerop (forward-line 1))
10168 (js2-error-buffer-view)))
10169
10170 (defun js2-error-buffer-prev ()
10171 "Move to previous error and view it."
10172 (interactive)
10173 (when (zerop (forward-line -1))
10174 (js2-error-buffer-view)))
10175
10176 (defun js2-error-buffer-quit ()
10177 "Kill the current buffer."
10178 (interactive)
10179 (kill-buffer))
10180
10181 (defun js2-error-buffer-jump (&rest ignored)
10182 "Jump cursor to current error in source buffer."
10183 (interactive)
10184 (when (js2-error-buffer-view)
10185 (pop-to-buffer js2-source-buffer)))
10186
10187 (defun js2-error-buffer-view ()
10188 "Scroll source buffer to show error at current line."
10189 (interactive)
10190 (cond
10191 ((not (eq major-mode 'js2-error-buffer-mode))
10192 (message "Not in a js2 errors buffer"))
10193 ((not (buffer-live-p js2-source-buffer))
10194 (message "Source buffer has been killed"))
10195 ((not (wholenump (get-text-property (point) 'js2-pos)))
10196 (message "There does not seem to be an error here"))
10197 (t
10198 (let ((pos (get-text-property (point) 'js2-pos))
10199 (msg (get-text-property (point) 'js2-msg)))
10200 (save-selected-window
10201 (pop-to-buffer js2-source-buffer)
10202 (goto-char pos)
10203 (message msg))))))
10204
10205 ;;;###autoload
10206 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10207 ;; FIXME: Should derive from js-mode.
10208 "Major mode for editing JavaScript code."
10209 (setq comment-start "//" ; used by comment-region; don't change it
10210 comment-end "")
10211 (set (make-local-variable 'max-lisp-eval-depth)
10212 (max max-lisp-eval-depth 3000))
10213 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10214 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10215 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10216 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10217 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10218 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10219 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10220 ;; for characters inside regexp literals.
10221 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10222 ;; this is necessary to make `show-paren-function' work properly
10223 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10224 ;; needed for M-x rgrep, among other things
10225 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10226
10227 (set (make-local-variable 'electric-indent-chars)
10228 (append '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
10229 electric-indent-chars))
10230 (set (make-local-variable 'electric-layout-rules)
10231 '((?\; . after) (?\{ . after) (?\} . before)))
10232
10233 ;; some variables needed by cc-engine for paragraph-fill, etc.
10234 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10235 c-comment-start-regexp "/[*/]\\|\\s|"
10236 c-line-comment-starter "//"
10237 c-paragraph-start js2-paragraph-start
10238 c-paragraph-separate "$"
10239 comment-start-skip js2-comment-start-skip
10240 c-syntactic-ws-start js2-syntactic-ws-start
10241 c-syntactic-ws-end js2-syntactic-ws-end
10242 c-syntactic-eol js2-syntactic-eol)
10243
10244 (let ((c-buffer-is-cc-mode t))
10245 ;; Copied from `js-mode'. Also see Bug#6071.
10246 (make-local-variable 'paragraph-start)
10247 (make-local-variable 'paragraph-separate)
10248 (make-local-variable 'paragraph-ignore-fill-prefix)
10249 (make-local-variable 'adaptive-fill-mode)
10250 (make-local-variable 'adaptive-fill-regexp)
10251 (c-setup-paragraph-variables))
10252
10253 (setq font-lock-defaults '(nil t))
10254
10255 ;; Experiment: make reparse-delay longer for longer files.
10256 (when (plusp js2-dynamic-idle-timer-adjust)
10257 (setq js2-idle-timer-delay
10258 (* js2-idle-timer-delay
10259 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10260
10261 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10262 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10263 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10264 (setq next-error-function #'js2-next-error)
10265 (imenu-add-to-menubar (concat "IM-" mode-name))
10266 (add-to-invisibility-spec '(js2-outline . t))
10267 (set (make-local-variable 'line-move-ignore-invisible) t)
10268 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10269
10270 (setq js2-mode-functions-hidden nil
10271 js2-mode-comments-hidden nil
10272 js2-mode-buffer-dirty-p t
10273 js2-mode-parsing nil)
10274 (js2-set-default-externs)
10275 (js2-reparse))
10276
10277 (defun js2-mode-exit ()
10278 "Exit `js2-mode' and clean up."
10279 (interactive)
10280 (when js2-mode-node-overlay
10281 (delete-overlay js2-mode-node-overlay)
10282 (setq js2-mode-node-overlay nil))
10283 (js2-remove-overlays)
10284 (setq js2-mode-ast nil)
10285 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10286 (remove-from-invisibility-spec '(js2-outline . t))
10287 (js2-mode-show-all)
10288 (with-silent-modifications
10289 (js2-clear-face (point-min) (point-max))))
10290
10291 (defun js2-mode-reset-timer ()
10292 "Cancel any existing parse timer and schedule a new one."
10293 (if js2-mode-parse-timer
10294 (cancel-timer js2-mode-parse-timer))
10295 (setq js2-mode-parsing nil)
10296 (let ((timer (timer-create)))
10297 (setq js2-mode-parse-timer timer)
10298 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10299 (timer-set-idle-time timer js2-idle-timer-delay)
10300 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10301 (timer-activate-when-idle timer nil)))
10302
10303 (defun js2-mode-idle-reparse (buffer)
10304 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10305 it to be reparsed when the buffer is selected."
10306 (if (eq buffer (current-buffer))
10307 (js2-reparse)
10308 ;; reparse when the buffer is selected again
10309 (with-current-buffer buffer
10310 (add-hook 'window-configuration-change-hook
10311 #'js2-mode-idle-reparse-inner
10312 nil t))))
10313
10314 (defun js2-mode-idle-reparse-inner ()
10315 (remove-hook 'window-configuration-change-hook
10316 #'js2-mode-idle-reparse-inner
10317 t)
10318 (js2-reparse))
10319
10320 (defun js2-mode-edit (beg end len)
10321 "Schedule a new parse after buffer is edited.
10322 Buffer edit spans from BEG to END and is of length LEN."
10323 (setq js2-mode-buffer-dirty-p t)
10324 (js2-mode-hide-overlay)
10325 (js2-mode-reset-timer))
10326
10327 (defun js2-minor-mode-edit (beg end len)
10328 "Callback for buffer edits in `js2-mode'.
10329 Schedules a new parse after buffer is edited.
10330 Buffer edit spans from BEG to END and is of length LEN."
10331 (setq js2-mode-buffer-dirty-p t)
10332 (js2-mode-hide-overlay)
10333 (js2-mode-reset-timer))
10334
10335 (defun js2-reparse (&optional force)
10336 "Re-parse current buffer after user finishes some data entry.
10337 If we get any user input while parsing, including cursor motion,
10338 we discard the parse and reschedule it. If FORCE is nil, then the
10339 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10340 (let (time
10341 interrupted-p
10342 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10343 (unless js2-mode-parsing
10344 (setq js2-mode-parsing t)
10345 (unwind-protect
10346 (when (or js2-mode-buffer-dirty-p force)
10347 (js2-remove-overlays)
10348 (with-silent-modifications
10349 (setq js2-mode-buffer-dirty-p nil
10350 js2-mode-fontifications nil
10351 js2-mode-deferred-properties nil)
10352 (if js2-mode-verbose-parse-p
10353 (message "parsing..."))
10354 (setq time
10355 (js2-time
10356 (setq interrupted-p
10357 (catch 'interrupted
10358 (js2-parse)
10359 ;; if parsing is interrupted, comments and regex
10360 ;; literals stay ignored by `parse-partial-sexp'
10361 (remove-text-properties (point-min) (point-max)
10362 '(syntax-table))
10363 (js2-mode-apply-deferred-properties)
10364 (js2-mode-remove-suppressed-warnings)
10365 (js2-mode-show-warnings)
10366 (js2-mode-show-errors)
10367 (if (>= js2-highlight-level 1)
10368 (js2-highlight-jsdoc js2-mode-ast))
10369 nil))))
10370 (if interrupted-p
10371 (progn
10372 ;; unfinished parse => try again
10373 (setq js2-mode-buffer-dirty-p t)
10374 (js2-mode-reset-timer))
10375 (if js2-mode-verbose-parse-p
10376 (message "Parse time: %s" time)))))
10377 (setq js2-mode-parsing nil)
10378 (unless interrupted-p
10379 (setq js2-mode-parse-timer nil))))))
10380
10381 (defun js2-mode-show-node (event)
10382 "Debugging aid: highlight selected AST node on mouse click."
10383 (interactive "e")
10384 (mouse-set-point event)
10385 (setq deactivate-mark t)
10386 (when js2-mode-show-overlay
10387 (let ((node (js2-node-at-point))
10388 beg end)
10389 (if (null node)
10390 (message "No node found at location %s" (point))
10391 (setq beg (js2-node-abs-pos node)
10392 end (+ beg (js2-node-len node)))
10393 (if js2-mode-node-overlay
10394 (move-overlay js2-mode-node-overlay beg end)
10395 (setq js2-mode-node-overlay (make-overlay beg end))
10396 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10397 (with-silent-modifications
10398 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10399 (message "%s, parent: %s"
10400 (js2-node-short-name node)
10401 (if (js2-node-parent node)
10402 (js2-node-short-name (js2-node-parent node))
10403 "nil"))))))
10404
10405 (defun js2-mode-hide-overlay (&optional p1 p2)
10406 "Remove the debugging overlay when the point moves.
10407 P1 and P2 are the old and new values of point, respectively."
10408 (when js2-mode-node-overlay
10409 (let ((beg (overlay-start js2-mode-node-overlay))
10410 (end (overlay-end js2-mode-node-overlay)))
10411 ;; Sometimes we're called spuriously.
10412 (unless (and p2
10413 (>= p2 beg)
10414 (<= p2 end))
10415 (with-silent-modifications
10416 (remove-text-properties beg end '(point-left nil)))
10417 (delete-overlay js2-mode-node-overlay)
10418 (setq js2-mode-node-overlay nil)))))
10419
10420 (defun js2-mode-reset ()
10421 "Debugging helper: reset everything."
10422 (interactive)
10423 (js2-mode-exit)
10424 (js2-mode))
10425
10426 (defun js2-mode-show-warn-or-err (e face)
10427 "Highlight a warning or error E with FACE.
10428 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10429 The last element is optional. When present, use instead of FACE."
10430 (let* ((key (first e))
10431 (beg (second e))
10432 (end (+ beg (third e)))
10433 ;; Don't inadvertently go out of bounds.
10434 (beg (max (point-min) (min beg (point-max))))
10435 (end (max (point-min) (min end (point-max))))
10436 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10437 (ovl (make-overlay beg end)))
10438 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10439 (overlay-put ovl 'js2-error t)
10440 (put-text-property beg end 'help-echo (js2-get-msg key))
10441 (put-text-property beg end 'point-entered #'js2-echo-error)))
10442
10443 (defun js2-remove-overlays ()
10444 "Remove overlays from buffer that have a `js2-error' property."
10445 (let ((beg (point-min))
10446 (end (point-max)))
10447 (save-excursion
10448 (dolist (o (overlays-in beg end))
10449 (when (overlay-get o 'js2-error)
10450 (delete-overlay o))))))
10451
10452 (defun js2-error-at-point (&optional pos)
10453 "Return non-nil if there's an error overlay at POS.
10454 Defaults to point."
10455 (loop with pos = (or pos (point))
10456 for o in (overlays-at pos)
10457 thereis (overlay-get o 'js2-error)))
10458
10459 (defun js2-mode-apply-deferred-properties ()
10460 "Apply fontifications and other text properties recorded during parsing."
10461 (when (plusp js2-highlight-level)
10462 ;; We defer clearing faces as long as possible to eliminate flashing.
10463 (js2-clear-face (point-min) (point-max))
10464 ;; Have to reverse the recorded fontifications list so that errors
10465 ;; and warnings overwrite the normal fontifications.
10466 (dolist (f (nreverse js2-mode-fontifications))
10467 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10468 (setq js2-mode-fontifications nil))
10469 (dolist (p js2-mode-deferred-properties)
10470 (apply #'put-text-property p))
10471 (setq js2-mode-deferred-properties nil))
10472
10473 (defun js2-mode-show-errors ()
10474 "Highlight syntax errors."
10475 (when js2-mode-show-parse-errors
10476 (dolist (e (js2-ast-root-errors js2-mode-ast))
10477 (js2-mode-show-warn-or-err e 'js2-error))))
10478
10479 (defun js2-mode-remove-suppressed-warnings ()
10480 "Take suppressed warnings out of the AST warnings list.
10481 This ensures that the counts and `next-error' are correct."
10482 (setf (js2-ast-root-warnings js2-mode-ast)
10483 (js2-delete-if
10484 (lambda (e)
10485 (let ((key (caar e)))
10486 (or
10487 (and (not js2-strict-trailing-comma-warning)
10488 (string-match "trailing\\.comma" key))
10489 (and (not js2-strict-cond-assign-warning)
10490 (string= key "msg.equal.as.assign"))
10491 (and js2-missing-semi-one-line-override
10492 (string= key "msg.missing.semi")
10493 (let* ((beg (second e))
10494 (node (js2-node-at-point beg))
10495 (fn (js2-mode-find-parent-fn node))
10496 (body (and fn (js2-function-node-body fn)))
10497 (lc (and body (js2-node-abs-pos body)))
10498 (rc (and lc (+ lc (js2-node-len body)))))
10499 (and fn
10500 (or (null body)
10501 (save-excursion
10502 (goto-char beg)
10503 (and (js2-same-line lc)
10504 (js2-same-line rc))))))))))
10505 (js2-ast-root-warnings js2-mode-ast))))
10506
10507 (defun js2-mode-show-warnings ()
10508 "Highlight strict-mode warnings."
10509 (when js2-mode-show-strict-warnings
10510 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10511 (js2-mode-show-warn-or-err e 'js2-warning))))
10512
10513 (defun js2-echo-error (old-point new-point)
10514 "Called by point-motion hooks."
10515 (let ((msg (get-text-property new-point 'help-echo)))
10516 (when (and (stringp msg) (or (not (current-message))
10517 (string= (current-message) "Quit")))
10518 (message msg))))
10519
10520 (defalias #'js2-echo-help #'js2-echo-error)
10521
10522 (defun js2-line-break (&optional soft)
10523 "Break line at point and indent, continuing comment if within one.
10524 If inside a string, and `js2-concat-multiline-strings' is not
10525 nil, turn it into concatenation."
10526 (interactive)
10527 (let ((parse-status (syntax-ppss)))
10528 (cond
10529 ;; Check if we're inside a string.
10530 ((nth 3 parse-status)
10531 (if js2-concat-multiline-strings
10532 (js2-mode-split-string parse-status)
10533 (insert "\n")))
10534 ;; Check if inside a block comment.
10535 ((nth 4 parse-status)
10536 (js2-mode-extend-comment (nth 8 parse-status)))
10537 (t
10538 (newline-and-indent)))))
10539
10540 (defun js2-mode-split-string (parse-status)
10541 "Turn a newline in mid-string into a string concatenation.
10542 PARSE-STATUS is as documented in `parse-partial-sexp'."
10543 (let* ((col (current-column))
10544 (quote-char (nth 3 parse-status))
10545 (string-beg (nth 8 parse-status))
10546 (at-eol (eq js2-concat-multiline-strings 'eol)))
10547 (insert quote-char)
10548 (if at-eol
10549 (insert " +\n")
10550 (insert "\n"))
10551 (unless at-eol
10552 (insert "+ "))
10553 (js2-indent-line)
10554 (insert quote-char)
10555 (when (eolp)
10556 (insert quote-char)
10557 (backward-char 1))))
10558
10559 (defun js2-mode-extend-comment (start-pos)
10560 "Indent the line and, when inside a comment block, add comment prefix."
10561 (let (star single col first-line needs-close)
10562 (save-excursion
10563 (back-to-indentation)
10564 (when (< (point) start-pos)
10565 (goto-char start-pos))
10566 (cond
10567 ((looking-at "\\*[^/]")
10568 (setq star t
10569 col (current-column)))
10570 ((looking-at "/\\*")
10571 (setq star t
10572 first-line t
10573 col (1+ (current-column))))
10574 ((looking-at "//")
10575 (setq single t
10576 col (current-column)))))
10577 ;; Heuristic for whether we need to close the comment:
10578 ;; if we've got a parse error here, assume it's an unterminated
10579 ;; comment.
10580 (setq needs-close
10581 (or
10582 (eq (get-text-property (1- (point)) 'point-entered)
10583 'js2-echo-error)
10584 ;; The heuristic above doesn't work well when we're
10585 ;; creating a comment and there's another one downstream,
10586 ;; as our parser thinks this one ends at the end of the
10587 ;; next one. (You can have a /* inside a js block comment.)
10588 ;; So just close it if the next non-ws char isn't a *.
10589 (and first-line
10590 (eolp)
10591 (save-excursion
10592 (skip-chars-forward " \t\r\n")
10593 (not (eq (char-after) ?*))))))
10594 (delete-horizontal-space)
10595 (insert "\n")
10596 (cond
10597 (star
10598 (indent-to col)
10599 (insert "* ")
10600 (if (and first-line needs-close)
10601 (save-excursion
10602 (insert "\n")
10603 (indent-to col)
10604 (insert "*/"))))
10605 ((and single
10606 (save-excursion
10607 (and (zerop (forward-line 1))
10608 (looking-at "\\s-*//"))))
10609 (indent-to col)
10610 (insert "// ")))
10611 ;; Don't need to extend the comment after all.
10612 (js2-indent-line)))
10613
10614 (defun js2-beginning-of-line ()
10615 "Toggle point between bol and first non-whitespace char in line.
10616 Also moves past comment delimiters when inside comments."
10617 (interactive)
10618 (let (node beg)
10619 (cond
10620 ((bolp)
10621 (back-to-indentation))
10622 ((looking-at "//")
10623 (skip-chars-forward "/ \t"))
10624 ((and (eq (char-after) ?*)
10625 (setq node (js2-comment-at-point))
10626 (memq (js2-comment-node-format node) '(jsdoc block))
10627 (save-excursion
10628 (skip-chars-backward " \t")
10629 (bolp)))
10630 (skip-chars-forward "\* \t"))
10631 (t
10632 (goto-char (point-at-bol))))))
10633
10634 (defun js2-end-of-line ()
10635 "Toggle point between eol and last non-whitespace char in line."
10636 (interactive)
10637 (if (eolp)
10638 (skip-chars-backward " \t")
10639 (goto-char (point-at-eol))))
10640
10641 (defun js2-mode-wait-for-parse (callback)
10642 "Invoke CALLBACK when parsing is finished.
10643 If parsing is already finished, calls CALLBACK immediately."
10644 (if (not js2-mode-buffer-dirty-p)
10645 (funcall callback)
10646 (push callback js2-mode-pending-parse-callbacks)
10647 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10648
10649 (defun js2-mode-parse-finished ()
10650 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10651 ;; We can't let errors propagate up, since it prevents the
10652 ;; `js2-parse' method from completing normally and returning
10653 ;; the ast, which makes things mysteriously not work right.
10654 (unwind-protect
10655 (dolist (cb js2-mode-pending-parse-callbacks)
10656 (condition-case err
10657 (funcall cb)
10658 (error (message "%s" err))))
10659 (setq js2-mode-pending-parse-callbacks nil)))
10660
10661 (defun js2-mode-flag-region (from to flag)
10662 "Hide or show text from FROM to TO, according to FLAG.
10663 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10664 Returns the created overlay if FLAG is non-nil."
10665 (remove-overlays from to 'invisible 'js2-outline)
10666 (when flag
10667 (let ((o (make-overlay from to)))
10668 (overlay-put o 'invisible 'js2-outline)
10669 (overlay-put o 'isearch-open-invisible
10670 'js2-isearch-open-invisible)
10671 o)))
10672
10673 ;; Function to be set as an outline-isearch-open-invisible' property
10674 ;; to the overlay that makes the outline invisible (see
10675 ;; `js2-mode-flag-region').
10676 (defun js2-isearch-open-invisible (overlay)
10677 ;; We rely on the fact that isearch places point on the matched text.
10678 (js2-mode-show-element))
10679
10680 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10681 "Return cons cell of bounds of folding overlay at POS.
10682 Returns nil if not found."
10683 (let ((overlays (overlays-at (or pos (point))))
10684 o)
10685 (while (and overlays
10686 (not o))
10687 (if (overlay-get (car overlays) 'invisible)
10688 (setq o (car overlays))
10689 (setq overlays (cdr overlays))))
10690 (if o
10691 (cons (overlay-start o) (overlay-end o)))))
10692
10693 (defun js2-mode-function-at-point (&optional pos)
10694 "Return the innermost function node enclosing current point.
10695 Returns nil if point is not in a function."
10696 (let ((node (js2-node-at-point pos)))
10697 (while (and node (not (js2-function-node-p node)))
10698 (setq node (js2-node-parent node)))
10699 (if (js2-function-node-p node)
10700 node)))
10701
10702 (defun js2-mode-toggle-element ()
10703 "Hide or show the foldable element at the point."
10704 (interactive)
10705 (let (comment fn pos)
10706 (save-excursion
10707 (cond
10708 ;; /* ... */ comment?
10709 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10710 (if (js2-mode-invisible-overlay-bounds
10711 (setq pos (+ 3 (js2-node-abs-pos comment))))
10712 (progn
10713 (goto-char pos)
10714 (js2-mode-show-element))
10715 (js2-mode-hide-element)))
10716 ;; //-comment?
10717 ((save-excursion
10718 (back-to-indentation)
10719 (looking-at js2-mode-//-comment-re))
10720 (js2-mode-toggle-//-comment))
10721 ;; function?
10722 ((setq fn (js2-mode-function-at-point))
10723 (setq pos (and (js2-function-node-body fn)
10724 (js2-node-abs-pos (js2-function-node-body fn))))
10725 (goto-char (1+ pos))
10726 (if (js2-mode-invisible-overlay-bounds)
10727 (js2-mode-show-element)
10728 (js2-mode-hide-element)))
10729 (t
10730 (message "Nothing at point to hide or show"))))))
10731
10732 (defun js2-mode-hide-element ()
10733 "Fold/hide contents of a block, showing ellipses.
10734 Show the hidden text with \\[js2-mode-show-element]."
10735 (interactive)
10736 (if js2-mode-buffer-dirty-p
10737 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10738 (let (node body beg end)
10739 (cond
10740 ((js2-mode-invisible-overlay-bounds)
10741 (message "already hidden"))
10742 (t
10743 (setq node (js2-node-at-point))
10744 (cond
10745 ((js2-block-comment-p node)
10746 (js2-mode-hide-comment node))
10747 (t
10748 (while (and node (not (js2-function-node-p node)))
10749 (setq node (js2-node-parent node)))
10750 (if (and node
10751 (setq body (js2-function-node-body node)))
10752 (progn
10753 (setq beg (js2-node-abs-pos body)
10754 end (+ beg (js2-node-len body)))
10755 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10756 (message "No collapsable element found at point"))))))))
10757
10758 (defun js2-mode-show-element ()
10759 "Show the hidden element at current point."
10760 (interactive)
10761 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10762 (if bounds
10763 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
10764 (message "Nothing to un-hide"))))
10765
10766 (defun js2-mode-show-all ()
10767 "Show all of the text in the buffer."
10768 (interactive)
10769 (js2-mode-flag-region (point-min) (point-max) nil))
10770
10771 (defun js2-mode-toggle-hide-functions ()
10772 (interactive)
10773 (if js2-mode-functions-hidden
10774 (js2-mode-show-functions)
10775 (js2-mode-hide-functions)))
10776
10777 (defun js2-mode-hide-functions ()
10778 "Hides all non-nested function bodies in the buffer.
10779 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10780 to open an individual entry."
10781 (interactive)
10782 (if js2-mode-buffer-dirty-p
10783 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
10784 (if (null js2-mode-ast)
10785 (message "Oops - parsing failed")
10786 (setq js2-mode-functions-hidden t)
10787 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
10788
10789 (defun js2-mode-function-hider (n endp)
10790 (when (not endp)
10791 (let ((tt (js2-node-type n))
10792 body beg end)
10793 (cond
10794 ((and (= tt js2-FUNCTION)
10795 (setq body (js2-function-node-body n)))
10796 (setq beg (js2-node-abs-pos body)
10797 end (+ beg (js2-node-len body)))
10798 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
10799 nil) ; don't process children of function
10800 (t
10801 t))))) ; keep processing other AST nodes
10802
10803 (defun js2-mode-show-functions ()
10804 "Un-hide any folded function bodies in the buffer."
10805 (interactive)
10806 (setq js2-mode-functions-hidden nil)
10807 (save-excursion
10808 (goto-char (point-min))
10809 (while (/= (goto-char (next-overlay-change (point)))
10810 (point-max))
10811 (dolist (o (overlays-at (point)))
10812 (when (and (overlay-get o 'invisible)
10813 (not (overlay-get o 'comment)))
10814 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10815
10816 (defun js2-mode-hide-comment (n)
10817 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
10818 3 ; /**
10819 2)) ; /*
10820 (beg (+ (js2-node-abs-pos n) head))
10821 (end (- (+ beg (js2-node-len n)) head 2))
10822 (o (js2-mode-flag-region beg end 'hide)))
10823 (overlay-put o 'comment t)))
10824
10825 (defun js2-mode-toggle-hide-comments ()
10826 "Folds all block comments in the buffer.
10827 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10828 to open an individual entry."
10829 (interactive)
10830 (if js2-mode-comments-hidden
10831 (js2-mode-show-comments)
10832 (js2-mode-hide-comments)))
10833
10834 (defun js2-mode-hide-comments ()
10835 (interactive)
10836 (if js2-mode-buffer-dirty-p
10837 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
10838 (if (null js2-mode-ast)
10839 (message "Oops - parsing failed")
10840 (setq js2-mode-comments-hidden t)
10841 (dolist (n (js2-ast-root-comments js2-mode-ast))
10842 (let ((format (js2-comment-node-format n)))
10843 (when (js2-block-comment-p n)
10844 (js2-mode-hide-comment n))))
10845 (js2-mode-hide-//-comments)))
10846
10847 (defun js2-mode-extend-//-comment (direction)
10848 "Find start or end of a block of similar //-comment lines.
10849 DIRECTION is -1 to look back, 1 to look forward.
10850 INDENT is the indentation level to match.
10851 Returns the end-of-line position of the furthest adjacent
10852 //-comment line with the same indentation as the current line.
10853 If there is no such matching line, returns current end of line."
10854 (let ((pos (point-at-eol))
10855 (indent (current-indentation)))
10856 (save-excursion
10857 (while (and (zerop (forward-line direction))
10858 (looking-at js2-mode-//-comment-re)
10859 (eq indent (length (match-string 1))))
10860 (setq pos (point-at-eol))
10861 pos))))
10862
10863 (defun js2-mode-hide-//-comments ()
10864 "Fold adjacent 1-line comments, showing only snippet of first one."
10865 (let (beg end)
10866 (save-excursion
10867 (goto-char (point-min))
10868 (while (re-search-forward js2-mode-//-comment-re nil t)
10869 (setq beg (point)
10870 end (js2-mode-extend-//-comment 1))
10871 (unless (eq beg end)
10872 (overlay-put (js2-mode-flag-region beg end 'hide)
10873 'comment t))
10874 (goto-char end)
10875 (forward-char 1)))))
10876
10877 (defun js2-mode-toggle-//-comment ()
10878 "Fold or un-fold any multi-line //-comment at point.
10879 Caller should have determined that this line starts with a //-comment."
10880 (let* ((beg (point-at-eol))
10881 (end beg))
10882 (save-excursion
10883 (goto-char end)
10884 (if (js2-mode-invisible-overlay-bounds)
10885 (js2-mode-show-element)
10886 ;; else hide the comment
10887 (setq beg (js2-mode-extend-//-comment -1)
10888 end (js2-mode-extend-//-comment 1))
10889 (unless (eq beg end)
10890 (overlay-put (js2-mode-flag-region beg end 'hide)
10891 'comment t))))))
10892
10893 (defun js2-mode-show-comments ()
10894 "Un-hide any hidden comments, leaving other hidden elements alone."
10895 (interactive)
10896 (setq js2-mode-comments-hidden nil)
10897 (save-excursion
10898 (goto-char (point-min))
10899 (while (/= (goto-char (next-overlay-change (point)))
10900 (point-max))
10901 (dolist (o (overlays-at (point)))
10902 (when (overlay-get o 'comment)
10903 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10904
10905 (defun js2-mode-display-warnings-and-errors ()
10906 "Turn on display of warnings and errors."
10907 (interactive)
10908 (setq js2-mode-show-parse-errors t
10909 js2-mode-show-strict-warnings t)
10910 (js2-reparse 'force))
10911
10912 (defun js2-mode-hide-warnings-and-errors ()
10913 "Turn off display of warnings and errors."
10914 (interactive)
10915 (setq js2-mode-show-parse-errors nil
10916 js2-mode-show-strict-warnings nil)
10917 (js2-reparse 'force))
10918
10919 (defun js2-mode-toggle-warnings-and-errors ()
10920 "Toggle the display of warnings and errors.
10921 Some users don't like having warnings/errors reported while they type."
10922 (interactive)
10923 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
10924 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
10925 (if (called-interactively-p 'any)
10926 (message "warnings and errors %s"
10927 (if js2-mode-show-parse-errors
10928 "enabled"
10929 "disabled")))
10930 (js2-reparse 'force))
10931
10932 (defun js2-mode-customize ()
10933 (interactive)
10934 (customize-group 'js2-mode))
10935
10936 (defun js2-mode-forward-sexp (&optional arg)
10937 "Move forward across one statement or balanced expression.
10938 With ARG, do it that many times. Negative arg -N means
10939 move backward across N balanced expressions."
10940 (interactive "p")
10941 (setq arg (or arg 1))
10942 (save-restriction
10943 (widen) ;; `blink-matching-open' calls `narrow-to-region'
10944 (js2-reparse))
10945 (let (forward-sexp-function
10946 node (start (point)) pos lp rp child)
10947 (cond
10948 ;; backward-sexp
10949 ;; could probably make this better for some cases:
10950 ;; - if in statement block (e.g. function body), go to parent
10951 ;; - infix exprs like (foo in bar) - maybe go to beginning
10952 ;; of infix expr if in the right-side expression?
10953 ((and arg (minusp arg))
10954 (dotimes (i (- arg))
10955 (js2-backward-sws)
10956 (forward-char -1) ; Enter the node we backed up to.
10957 (when (setq node (js2-node-at-point (point) t))
10958 (setq pos (js2-node-abs-pos node))
10959 (let ((parens (js2-mode-forward-sexp-parens node pos)))
10960 (setq lp (car parens)
10961 rp (cdr parens)))
10962 (when (and lp (> start lp))
10963 (if (and rp (<= start rp))
10964 ;; Between parens, check if there's a child node we can jump.
10965 (when (setq child (js2-node-closest-child node (point) lp t))
10966 (setq pos (js2-node-abs-pos child)))
10967 ;; Before both parens.
10968 (setq pos lp)))
10969 (let ((state (parse-partial-sexp start pos)))
10970 (goto-char (if (not (zerop (car state)))
10971 ;; Stumble at the unbalanced paren if < 0, or
10972 ;; jump a bit further if > 0.
10973 (scan-sexps start -1)
10974 pos))))
10975 (unless pos (goto-char (point-min)))))
10976 (t
10977 ;; forward-sexp
10978 (dotimes (i arg)
10979 (js2-forward-sws)
10980 (when (setq node (js2-node-at-point (point) t))
10981 (setq pos (js2-node-abs-pos node))
10982 (let ((parens (js2-mode-forward-sexp-parens node pos)))
10983 (setq lp (car parens)
10984 rp (cdr parens)))
10985 (or
10986 (when (and rp (<= start rp))
10987 (if (> start lp)
10988 (when (setq child (js2-node-closest-child node (point) rp))
10989 (setq pos (js2-node-abs-end child)))
10990 (setq pos (1+ rp))))
10991 ;; No parens or child nodes, looks for the end of the curren node.
10992 (incf pos (js2-node-len
10993 (if (js2-expr-stmt-node-p (js2-node-parent node))
10994 ;; Stop after the semicolon.
10995 (js2-node-parent node)
10996 node))))
10997 (let ((state (save-excursion (parse-partial-sexp start pos))))
10998 (goto-char (if (not (zerop (car state)))
10999 (scan-sexps start 1)
11000 pos))))
11001 (unless pos (goto-char (point-max))))))))
11002
11003 (defun js2-mode-forward-sexp-parens (node abs-pos)
11004 "Return a cons cell with positions of main parens in NODE."
11005 (cond
11006 ((or (js2-array-node-p node)
11007 (js2-object-node-p node)
11008 (js2-array-comp-node-p node)
11009 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11010 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11011 ((js2-paren-expr-node-p node)
11012 (let ((lp (js2-node-lp node))
11013 (rp (js2-node-rp node)))
11014 (cons (when lp (+ abs-pos lp))
11015 (when rp (+ abs-pos rp)))))))
11016
11017 (defun js2-node-closest-child (parent point limit &optional before)
11018 (let* ((parent-pos (js2-node-abs-pos parent))
11019 (rpoint (- point parent-pos))
11020 (rlimit (- limit parent-pos))
11021 (min (min rpoint rlimit))
11022 (max (max rpoint rlimit))
11023 found)
11024 (catch 'done
11025 (js2-visit-ast
11026 parent
11027 (lambda (node end-p)
11028 (if (eq node parent)
11029 t
11030 (let ((pos (js2-node-pos node)) ;; Both relative values.
11031 (end (+ (js2-node-pos node) (js2-node-len node))))
11032 (when (and (>= pos min) (<= end max)
11033 (if before (< pos rpoint) (> end rpoint)))
11034 (setq found node))
11035 (when (> end rpoint)
11036 (throw 'done nil)))
11037 nil))))
11038 found))
11039
11040 (defun js2-errors ()
11041 "Return a list of errors found."
11042 (and js2-mode-ast
11043 (js2-ast-root-errors js2-mode-ast)))
11044
11045 (defun js2-warnings ()
11046 "Return a list of warnings found."
11047 (and js2-mode-ast
11048 (js2-ast-root-warnings js2-mode-ast)))
11049
11050 (defun js2-have-errors-p ()
11051 "Return non-nil if any parse errors or warnings were found."
11052 (or (js2-errors) (js2-warnings)))
11053
11054 (defun js2-errors-and-warnings ()
11055 "Return a copy of the concatenated errors and warnings lists.
11056 They are appended: first the errors, then the warnings.
11057 Entries are of the form (MSG BEG END)."
11058 (when js2-mode-ast
11059 (append (js2-ast-root-errors js2-mode-ast)
11060 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11061
11062 (defun js2-next-error (&optional arg reset)
11063 "Move to next parse error.
11064 Typically invoked via \\[next-error].
11065 ARG is the number of errors, forward or backward, to move.
11066 RESET means start over from the beginning."
11067 (interactive "p")
11068 (if (not (or (js2-errors) (js2-warnings)))
11069 (message "No errors")
11070 (when reset
11071 (goto-char (point-min)))
11072 (let* ((errs (js2-errors-and-warnings))
11073 (continue t)
11074 (start (point))
11075 (count (or arg 1))
11076 (backward (minusp count))
11077 (sorter (if backward '> '<))
11078 (stopper (if backward '< '>))
11079 (count (abs count))
11080 all-errs err)
11081 ;; Sort by start position.
11082 (setq errs (sort errs (lambda (e1 e2)
11083 (funcall sorter (second e1) (second e2))))
11084 all-errs errs)
11085 ;; Find nth error with pos > start.
11086 (while (and errs continue)
11087 (when (funcall stopper (cadar errs) start)
11088 (setq err (car errs))
11089 (if (zerop (decf count))
11090 (setq continue nil)))
11091 (setq errs (cdr errs)))
11092 (if err
11093 (goto-char (second err))
11094 ;; Wrap around to first error.
11095 (goto-char (second (car all-errs)))
11096 ;; If we were already on it, echo msg again.
11097 (if (= (point) start)
11098 (js2-echo-error (point) (point)))))))
11099
11100 (defun js2-down-mouse-3 ()
11101 "Make right-click move the point to the click location.
11102 This makes right-click context menu operations a bit more intuitive.
11103 The point will not move if the region is active, however, to avoid
11104 destroying the region selection."
11105 (interactive)
11106 (when (and js2-move-point-on-right-click
11107 (not mark-active))
11108 (let ((e last-input-event))
11109 (ignore-errors
11110 (goto-char (cadadr e))))))
11111
11112 (defun js2-mode-create-imenu-index ()
11113 "Return an alist for `imenu--index-alist'."
11114 ;; This is built up in `js2-parse-record-imenu' during parsing.
11115 (when js2-mode-ast
11116 ;; if we have an ast but no recorder, they're requesting a rescan
11117 (unless js2-imenu-recorder
11118 (js2-reparse 'force))
11119 (prog1
11120 (js2-build-imenu-index)
11121 (setq js2-imenu-recorder nil
11122 js2-imenu-function-map nil))))
11123
11124 (defun js2-mode-find-tag ()
11125 "Replacement for `find-tag-default'.
11126 `find-tag-default' returns a ridiculous answer inside comments."
11127 (let (beg end)
11128 (js2-with-underscore-as-word-syntax
11129 (save-excursion
11130 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11131 (looking-back "[A-Za-z0-9_$]"))
11132 (setq beg (progn (forward-word -1) (point))
11133 end (progn (forward-word 1) (point)))
11134 (setq beg (progn (forward-word 1) (point))
11135 end (progn (forward-word -1) (point))))
11136 (replace-regexp-in-string
11137 "[\"']" ""
11138 (buffer-substring-no-properties beg end))))))
11139
11140 (defun js2-mode-forward-sibling ()
11141 "Move to the end of the sibling following point in parent.
11142 Returns non-nil if successful, or nil if there was no following sibling."
11143 (let* ((node (js2-node-at-point))
11144 (parent (js2-mode-find-enclosing-fn node))
11145 sib)
11146 (when (setq sib (js2-node-find-child-after (point) parent))
11147 (goto-char (+ (js2-node-abs-pos sib)
11148 (js2-node-len sib))))))
11149
11150 (defun js2-mode-backward-sibling ()
11151 "Move to the beginning of the sibling node preceding point in parent.
11152 Parent is defined as the enclosing script or function."
11153 (let* ((node (js2-node-at-point))
11154 (parent (js2-mode-find-enclosing-fn node))
11155 sib)
11156 (when (setq sib (js2-node-find-child-before (point) parent))
11157 (goto-char (js2-node-abs-pos sib)))))
11158
11159 (defun js2-beginning-of-defun (&optional arg)
11160 "Go to line on which current function starts, and return t on success.
11161 If we're not in a function or already at the beginning of one, go
11162 to beginning of previous script-level element.
11163 With ARG N, do that N times. If N is negative, move forward."
11164 (setq arg (or arg 1))
11165 (if (plusp arg)
11166 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11167 (when (cond
11168 ((js2-function-node-p parent)
11169 (goto-char (js2-node-abs-pos parent)))
11170 (t
11171 (js2-mode-backward-sibling)))
11172 (if (> arg 1)
11173 (js2-beginning-of-defun (1- arg))
11174 t)))
11175 (when (js2-end-of-defun)
11176 (if (>= arg -1)
11177 (js2-beginning-of-defun 1)
11178 (js2-beginning-of-defun (1+ arg))))))
11179
11180 (defun js2-end-of-defun ()
11181 "Go to the char after the last position of the current function
11182 or script-level element."
11183 (let* ((node (js2-node-at-point))
11184 (parent (or (and (js2-function-node-p node) node)
11185 (js2-node-parent-script-or-fn node)))
11186 script)
11187 (unless (js2-function-node-p parent)
11188 ;; Use current script-level node, or, if none, the next one.
11189 (setq script (or parent node)
11190 parent (js2-node-find-child-before (point) script))
11191 (when (or (null parent)
11192 (>= (point) (+ (js2-node-abs-pos parent)
11193 (js2-node-len parent))))
11194 (setq parent (js2-node-find-child-after (point) script))))
11195 (when parent
11196 (goto-char (+ (js2-node-abs-pos parent)
11197 (js2-node-len parent))))))
11198
11199 (defun js2-mark-defun (&optional allow-extend)
11200 "Put mark at end of this function, point at beginning.
11201 The function marked is the one that contains point.
11202
11203 Interactively, if this command is repeated,
11204 or (in Transient Mark mode) if the mark is active,
11205 it marks the next defun after the ones already marked."
11206 (interactive "p")
11207 (let (extended)
11208 (when (and allow-extend
11209 (or (and (eq last-command this-command) (mark t))
11210 (and transient-mark-mode mark-active)))
11211 (let ((sib (save-excursion
11212 (goto-char (mark))
11213 (if (js2-mode-forward-sibling)
11214 (point))))
11215 node)
11216 (if sib
11217 (progn
11218 (set-mark sib)
11219 (setq extended t))
11220 ;; no more siblings - try extending to enclosing node
11221 (goto-char (mark t)))))
11222 (when (not extended)
11223 (let ((node (js2-node-at-point (point) t)) ; skip comments
11224 ast fn stmt parent beg end)
11225 (when (js2-ast-root-p node)
11226 (setq ast node
11227 node (or (js2-node-find-child-after (point) node)
11228 (js2-node-find-child-before (point) node))))
11229 ;; only mark whole buffer if we can't find any children
11230 (if (null node)
11231 (setq node ast))
11232 (if (js2-function-node-p node)
11233 (setq parent node)
11234 (setq fn (js2-mode-find-enclosing-fn node)
11235 stmt (if (or (null fn)
11236 (js2-ast-root-p fn))
11237 (js2-mode-find-first-stmt node))
11238 parent (or stmt fn)))
11239 (setq beg (js2-node-abs-pos parent)
11240 end (+ beg (js2-node-len parent)))
11241 (push-mark beg)
11242 (goto-char end)
11243 (exchange-point-and-mark)))))
11244
11245 (defun js2-narrow-to-defun ()
11246 "Narrow to the function enclosing point."
11247 (interactive)
11248 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11249 (fn (if (js2-script-node-p node)
11250 node
11251 (js2-mode-find-enclosing-fn node)))
11252 (beg (js2-node-abs-pos fn)))
11253 (unless (js2-ast-root-p fn)
11254 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11255
11256 (provide 'js2-mode)
11257
11258 ;;; js2-mode.el ends here