]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Make comment vars buffer-local
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2013 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
10 ;; Version: 20130619
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
65
66 ;; Notes:
67
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
71
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
76
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
81
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code 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 "When non-nil, `js2-line-break' in mid-string will make it 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-init-hook' that adds additional
858 externs appropriate for the specific file, perhaps based on its path.
859 These should go in `js2-additional-externs', which is buffer-local.
860
861 Third, you can use JSLint's global declaration, as long as
862 `js2-include-jslint-globals' is non-nil, which see.
863
864 Finally, you can add a function to `js2-post-parse-callbacks',
865 which is called after parsing completes, and `js2-mode-ast' is bound to
866 the root of the parse tree. At this stage you can set up an AST
867 node visitor using `js2-visit-ast' and examine the parse tree
868 for specific import patterns that may imply the existence of
869 other externs, possibly tied to your build system. These should also
870 be added to `js2-additional-externs'.
871
872 Your post-parse callback may of course also use the simpler and
873 faster (but perhaps less robust) approach of simply scanning the
874 buffer text for your imports, using regular expressions.")
875
876 ;; SKIP: decompiler
877 ;; SKIP: encoded-source
878
879 ;;; The following variables are per-function and should be saved/restored
880 ;;; during function parsing...
881
882 (js2-deflocal js2-current-script-or-fn nil)
883 (js2-deflocal js2-current-scope nil)
884 (js2-deflocal js2-nesting-of-with 0)
885 (js2-deflocal js2-label-set nil
886 "An alist mapping label names to nodes.")
887
888 (js2-deflocal js2-loop-set nil)
889 (js2-deflocal js2-loop-and-switch-set nil)
890 (js2-deflocal js2-has-return-value nil)
891 (js2-deflocal js2-end-flags 0)
892
893 ;;; ...end of per function variables
894
895 ;; Without 2-token lookahead, labels are a problem.
896 ;; These vars store the token info of the last matched name,
897 ;; iff it wasn't the last matched token. Only valid in some contexts.
898 (defvar js2-prev-name-token-start nil)
899 (defvar js2-prev-name-token-string nil)
900
901 (defsubst js2-save-name-token-data (pos name)
902 (setq js2-prev-name-token-start pos
903 js2-prev-name-token-string name))
904
905 ;; These flags enumerate the possible ways a statement/function can
906 ;; terminate. These flags are used by endCheck() and by the Parser to
907 ;; detect inconsistent return usage.
908 ;;
909 ;; END_UNREACHED is reserved for code paths that are assumed to always be
910 ;; able to execute (example: throw, continue)
911 ;;
912 ;; END_DROPS_OFF indicates if the statement can transfer control to the
913 ;; next one. Statement such as return dont. A compound statement may have
914 ;; some branch that drops off control to the next statement.
915 ;;
916 ;; END_RETURNS indicates that the statement can return (without arguments)
917 ;; END_RETURNS_VALUE indicates that the statement can return a value.
918 ;;
919 ;; A compound statement such as
920 ;; if (condition) {
921 ;; return value;
922 ;; }
923 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
924
925 (defconst js2-end-unreached #x0)
926 (defconst js2-end-drops-off #x1)
927 (defconst js2-end-returns #x2)
928 (defconst js2-end-returns-value #x4)
929 (defconst js2-end-yields #x8)
930
931 ;; Rhino awkwardly passes a statementLabel parameter to the
932 ;; statementHelper() function, the main statement parser, which
933 ;; is then used by quite a few of the sub-parsers. We just make
934 ;; it a buffer-local variable and make sure it's cleaned up properly.
935 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
936
937 ;; Similarly, Rhino passes an inForInit boolean through about half
938 ;; the expression parsers. We use a dynamically-scoped variable,
939 ;; which makes it easier to funcall the parsers individually without
940 ;; worrying about whether they take the parameter or not.
941 (js2-deflocal js2-in-for-init nil)
942 (js2-deflocal js2-temp-name-counter 0)
943 (js2-deflocal js2-parse-stmt-count 0)
944
945 (defsubst js2-get-next-temp-name ()
946 (format "$%d" (incf js2-temp-name-counter)))
947
948 (defvar js2-parse-interruptable-p t
949 "Set this to nil to force parse to continue until finished.
950 This will mostly be useful for interpreters.")
951
952 (defvar js2-statements-per-pause 50
953 "Pause after this many statements to check for user input.
954 If user input is pending, stop the parse and discard the tree.
955 This makes for a smoother user experience for large files.
956 You may have to wait a second or two before the highlighting
957 and error-reporting appear, but you can always type ahead if
958 you wish. This appears to be more or less how Eclipse, IntelliJ
959 and other editors work.")
960
961 (js2-deflocal js2-record-comments t
962 "Instructs the scanner to record comments in `js2-scanned-comments'.")
963
964 (js2-deflocal js2-scanned-comments nil
965 "List of all comments from the current parse.")
966
967 (defcustom js2-mode-indent-inhibit-undo nil
968 "Non-nil to disable collection of Undo information when indenting lines.
969 Some users have requested this behavior. It's nil by default because
970 other Emacs modes don't work this way."
971 :type 'boolean
972 :group 'js2-mode)
973
974 (defcustom js2-mode-indent-ignore-first-tab nil
975 "If non-nil, ignore first TAB keypress if we look indented properly.
976 It's fairly common for users to navigate to an already-indented line
977 and press TAB for reassurance that it's been indented. For this class
978 of users, we want the first TAB press on a line to be ignored if the
979 line is already indented to one of the precomputed alternatives.
980
981 This behavior is only partly implemented. If you TAB-indent a line,
982 navigate to another line, and then navigate back, it fails to clear
983 the last-indented variable, so it thinks you've already hit TAB once,
984 and performs the indent. A full solution would involve getting on the
985 point-motion hooks for the entire buffer. If we come across another
986 use cases that requires watching point motion, I'll consider doing it.
987
988 If you set this variable to nil, then the TAB key will always change
989 the indentation of the current line, if more than one alternative
990 indentation spot exists."
991 :type 'boolean
992 :group 'js2-mode)
993
994 (defvar js2-indent-hook nil
995 "A hook for user-defined indentation rules.
996
997 Functions on this hook should expect two arguments: (LIST INDEX)
998 The LIST argument is the list of computed indentation points for
999 the current line. INDEX is the list index of the indentation point
1000 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1001 indent function is not going to change the current line indentation.
1002
1003 If a hook function on this list returns a non-nil value, then
1004 `js2-bounce-indent' assumes the hook function has performed its own
1005 indentation, and will do nothing. If all hook functions on the list
1006 return nil, then `js2-bounce-indent' will use its computed indentation
1007 and reindent the line.
1008
1009 When hook functions on this hook list are called, the variable
1010 `js2-mode-ast' may or may not be set, depending on whether the
1011 parse tree is available. If the variable is nil, you can pass a
1012 callback to `js2-mode-wait-for-parse', and your callback will be
1013 called after the new parse tree is built. This can take some time
1014 in large files.")
1015
1016 (defface js2-warning
1017 `((((class color) (background light))
1018 (:underline "orange"))
1019 (((class color) (background dark))
1020 (:underline "orange"))
1021 (t (:underline t)))
1022 "Face for JavaScript warnings."
1023 :group 'js2-mode)
1024
1025 (defface js2-error
1026 `((((class color) (background light))
1027 (:foreground "red"))
1028 (((class color) (background dark))
1029 (:foreground "red"))
1030 (t (:foreground "red")))
1031 "Face for JavaScript errors."
1032 :group 'js2-mode)
1033
1034 (defface js2-jsdoc-tag
1035 '((t :foreground "SlateGray"))
1036 "Face used to highlight @whatever tags in jsdoc comments."
1037 :group 'js2-mode)
1038
1039 (defface js2-jsdoc-type
1040 '((t :foreground "SteelBlue"))
1041 "Face used to highlight {FooBar} types in jsdoc comments."
1042 :group 'js2-mode)
1043
1044 (defface js2-jsdoc-value
1045 '((t :foreground "PeachPuff3"))
1046 "Face used to highlight tag values in jsdoc comments."
1047 :group 'js2-mode)
1048
1049 (defface js2-function-param
1050 '((t :foreground "SeaGreen"))
1051 "Face used to highlight function parameters in javascript."
1052 :group 'js2-mode)
1053
1054 (defface js2-instance-member
1055 '((t :foreground "DarkOrchid"))
1056 "Face used to highlight instance variables in javascript.
1057 Not currently used."
1058 :group 'js2-mode)
1059
1060 (defface js2-private-member
1061 '((t :foreground "PeachPuff3"))
1062 "Face used to highlight calls to private methods in javascript.
1063 Not currently used."
1064 :group 'js2-mode)
1065
1066 (defface js2-private-function-call
1067 '((t :foreground "goldenrod"))
1068 "Face used to highlight calls to private functions in javascript.
1069 Not currently used."
1070 :group 'js2-mode)
1071
1072 (defface js2-jsdoc-html-tag-name
1073 '((((class color) (min-colors 88) (background light))
1074 (:foreground "rosybrown"))
1075 (((class color) (min-colors 8) (background dark))
1076 (:foreground "yellow"))
1077 (((class color) (min-colors 8) (background light))
1078 (:foreground "magenta")))
1079 "Face used to highlight jsdoc html tag names"
1080 :group 'js2-mode)
1081
1082 (defface js2-jsdoc-html-tag-delimiter
1083 '((((class color) (min-colors 88) (background light))
1084 (:foreground "dark khaki"))
1085 (((class color) (min-colors 8) (background dark))
1086 (:foreground "green"))
1087 (((class color) (min-colors 8) (background light))
1088 (:foreground "green")))
1089 "Face used to highlight brackets in jsdoc html tags."
1090 :group 'js2-mode)
1091
1092 (defface js2-external-variable
1093 '((t :foreground "orange"))
1094 "Face used to highlight undeclared variable identifiers.")
1095
1096 (defcustom js2-init-hook nil
1097 "List of functions to be called after `js2-mode' or
1098 `js2-minor-mode' has initialized all variables, before parsing
1099 the buffer for the first time."
1100 :type 'hook
1101 :group 'js2-mode
1102 :version "20130608")
1103
1104 (defcustom js2-post-parse-callbacks nil
1105 "List of callback functions invoked after parsing finishes.
1106 Currently, the main use for this function is to add synthetic
1107 declarations to `js2-recorded-identifiers', which see."
1108 :type 'hook
1109 :group 'js2-mode)
1110
1111 (defcustom js2-highlight-external-variables t
1112 "Non-nil to highlight undeclared variable identifiers.
1113 An undeclared variable is any variable not declared with var or let
1114 in the current scope or any lexically enclosing scope. If you use
1115 such a variable, then you are either expecting it to originate from
1116 another file, or you've got a potential bug."
1117 :type 'boolean
1118 :group 'js2-mode)
1119
1120 (defcustom js2-include-jslint-globals t
1121 "Non-nil to include the identifiers from JSLint global
1122 declaration (see http://www.jslint.com/lint.html#global) in the
1123 buffer-local externs list. See `js2-additional-externs' for more
1124 information."
1125 :type 'boolean
1126 :group 'js2-mode)
1127
1128 (defvar js2-mode-map
1129 (let ((map (make-sparse-keymap))
1130 keys)
1131 (define-key map [mouse-1] #'js2-mode-show-node)
1132 (define-key map (kbd "M-j") #'js2-line-break)
1133 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1134 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1135 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1136 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1137 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1138 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1139 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1140 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1141 (when js2-bounce-indent-p
1142 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1143
1144 (define-key map [menu-bar javascript]
1145 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1146
1147 (define-key map [menu-bar javascript customize-js2-mode]
1148 '(menu-item "Customize js2-mode" js2-mode-customize
1149 :help "Customize the behavior of this mode"))
1150
1151 (define-key map [menu-bar javascript js2-force-refresh]
1152 '(menu-item "Force buffer refresh" js2-mode-reset
1153 :help "Re-parse the buffer from scratch"))
1154
1155 (define-key map [menu-bar javascript separator-2]
1156 '("--"))
1157
1158 (define-key map [menu-bar javascript next-error]
1159 '(menu-item "Next warning or error" next-error
1160 :enabled (and js2-mode-ast
1161 (or (js2-ast-root-errors js2-mode-ast)
1162 (js2-ast-root-warnings js2-mode-ast)))
1163 :help "Move to next warning or error"))
1164
1165 (define-key map [menu-bar javascript display-errors]
1166 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1167 :visible (not js2-mode-show-parse-errors)
1168 :help "Turn on display of warnings and errors"))
1169
1170 (define-key map [menu-bar javascript hide-errors]
1171 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1172 :visible js2-mode-show-parse-errors
1173 :help "Turn off display of warnings and errors"))
1174
1175 (define-key map [menu-bar javascript separator-1]
1176 '("--"))
1177
1178 (define-key map [menu-bar javascript js2-toggle-function]
1179 '(menu-item "Show/collapse element" js2-mode-toggle-element
1180 :help "Hide or show function body or comment"))
1181
1182 (define-key map [menu-bar javascript show-comments]
1183 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1184 :visible js2-mode-comments-hidden
1185 :help "Expand all hidden block comments"))
1186
1187 (define-key map [menu-bar javascript hide-comments]
1188 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1189 :visible (not js2-mode-comments-hidden)
1190 :help "Show block comments as /*...*/"))
1191
1192 (define-key map [menu-bar javascript show-all-functions]
1193 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1194 :visible js2-mode-functions-hidden
1195 :help "Expand all hidden function bodies"))
1196
1197 (define-key map [menu-bar javascript hide-all-functions]
1198 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1199 :visible (not js2-mode-functions-hidden)
1200 :help "Show {...} for all top-level function bodies"))
1201
1202 map)
1203 "Keymap used in `js2-mode' buffers.")
1204
1205 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1206
1207 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1208 "Matches a //-comment line. Must be first non-whitespace on line.
1209 First match-group is the leading whitespace.")
1210
1211 (defvar js2-mode-hook nil)
1212
1213 (js2-deflocal js2-mode-ast nil "Private variable.")
1214 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1215 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1216 (js2-deflocal js2-mode-parsing nil "Private variable.")
1217 (js2-deflocal js2-mode-node-overlay nil)
1218
1219 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1220 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1221
1222 (js2-deflocal js2-mode-fontifications nil "Private variable")
1223 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1224 (js2-deflocal js2-imenu-recorder nil "Private variable")
1225 (js2-deflocal js2-imenu-function-map nil "Private variable")
1226
1227 (defvar js2-paragraph-start
1228 "\\(@[a-zA-Z]+\\>\\|$\\)")
1229
1230 ;; Note that we also set a 'c-in-sws text property in html comments,
1231 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1232 (defvar js2-syntactic-ws-start
1233 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1234
1235 (defvar js2-syntactic-ws-end
1236 "\\s \\|[\n\r/]\\|\\s!")
1237
1238 (defvar js2-syntactic-eol
1239 (concat "\\s *\\(/\\*[^*\n\r]*"
1240 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1241 "\\*+/\\s *\\)*"
1242 "\\(//\\|/\\*[^*\n\r]*"
1243 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1244 "\\|\\\\$\\|$\\)")
1245 "Copied from `java-mode'. Needed for some cc-engine functions.")
1246
1247 (defvar js2-comment-prefix-regexp
1248 "//+\\|\\**")
1249
1250 (defvar js2-comment-start-skip
1251 "\\(//+\\|/\\*+\\)\\s *")
1252
1253 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1254 "Non-nil to emit status messages during parsing.")
1255
1256 (defvar js2-mode-functions-hidden nil "Private variable.")
1257 (defvar js2-mode-comments-hidden nil "Private variable.")
1258
1259 (defvar js2-mode-syntax-table
1260 (let ((table (make-syntax-table)))
1261 (c-populate-syntax-table table)
1262 table)
1263 "Syntax table used in `js2-mode' buffers.")
1264
1265 (defvar js2-mode-abbrev-table nil
1266 "Abbrev table in use in `js2-mode' buffers.")
1267 (define-abbrev-table 'js2-mode-abbrev-table ())
1268
1269 (defvar js2-mode-pending-parse-callbacks nil
1270 "List of functions waiting to be notified that parse is finished.")
1271
1272 (defvar js2-mode-last-indented-line -1)
1273
1274 ;;; Localizable error and warning messages
1275
1276 ;; Messages are copied from Rhino's Messages.properties.
1277 ;; Many of the Java-specific messages have been elided.
1278 ;; Add any js2-specific ones at the end, so we can keep
1279 ;; this file synced with changes to Rhino's.
1280
1281 (defvar js2-message-table
1282 (make-hash-table :test 'equal :size 250)
1283 "Contains localized messages for `js2-mode'.")
1284
1285 ;; TODO(stevey): construct this table at compile-time.
1286 (defmacro js2-msg (key &rest strings)
1287 `(puthash ,key (concat ,@strings)
1288 js2-message-table))
1289
1290 (defun js2-get-msg (msg-key)
1291 "Look up a localized message.
1292 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1293 the correct number of ARGS must be provided."
1294 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1295 (args (if (listp msg-key) (cdr msg-key)))
1296 (msg (gethash key js2-message-table)))
1297 (if msg
1298 (apply #'format msg args)
1299 key))) ; default to showing the key
1300
1301 (js2-msg "msg.dup.parms"
1302 "Duplicate parameter name '%s'.")
1303
1304 (js2-msg "msg.too.big.jump"
1305 "Program too complex: jump offset too big.")
1306
1307 (js2-msg "msg.too.big.index"
1308 "Program too complex: internal index exceeds 64K limit.")
1309
1310 (js2-msg "msg.while.compiling.fn"
1311 "Encountered code generation error while compiling function '%s': %s")
1312
1313 (js2-msg "msg.while.compiling.script"
1314 "Encountered code generation error while compiling script: %s")
1315
1316 ;; Context
1317 (js2-msg "msg.ctor.not.found"
1318 "Constructor for '%s' not found.")
1319
1320 (js2-msg "msg.not.ctor"
1321 "'%s' is not a constructor.")
1322
1323 ;; FunctionObject
1324 (js2-msg "msg.varargs.ctor"
1325 "Method or constructor '%s' must be static "
1326 "with the signature (Context cx, Object[] args, "
1327 "Function ctorObj, boolean inNewExpr) "
1328 "to define a variable arguments constructor.")
1329
1330 (js2-msg "msg.varargs.fun"
1331 "Method '%s' must be static with the signature "
1332 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1333 "to define a variable arguments function.")
1334
1335 (js2-msg "msg.incompat.call"
1336 "Method '%s' called on incompatible object.")
1337
1338 (js2-msg "msg.bad.parms"
1339 "Unsupported parameter type '%s' in method '%s'.")
1340
1341 (js2-msg "msg.bad.method.return"
1342 "Unsupported return type '%s' in method '%s'.")
1343
1344 (js2-msg "msg.bad.ctor.return"
1345 "Construction of objects of type '%s' is not supported.")
1346
1347 (js2-msg "msg.no.overload"
1348 "Method '%s' occurs multiple times in class '%s'.")
1349
1350 (js2-msg "msg.method.not.found"
1351 "Method '%s' not found in '%s'.")
1352
1353 ;; IRFactory
1354
1355 (js2-msg "msg.bad.for.in.lhs"
1356 "Invalid left-hand side of for..in loop.")
1357
1358 (js2-msg "msg.mult.index"
1359 "Only one variable allowed in for..in loop.")
1360
1361 (js2-msg "msg.bad.for.in.destruct"
1362 "Left hand side of for..in loop must be an array of "
1363 "length 2 to accept key/value pair.")
1364
1365 (js2-msg "msg.cant.convert"
1366 "Can't convert to type '%s'.")
1367
1368 (js2-msg "msg.bad.assign.left"
1369 "Invalid assignment left-hand side.")
1370
1371 (js2-msg "msg.bad.decr"
1372 "Invalid decerement operand.")
1373
1374 (js2-msg "msg.bad.incr"
1375 "Invalid increment operand.")
1376
1377 (js2-msg "msg.bad.yield"
1378 "yield must be in a function.")
1379
1380 (js2-msg "msg.yield.parenthesized"
1381 "yield expression must be parenthesized.")
1382
1383 ;; NativeGlobal
1384 (js2-msg "msg.cant.call.indirect"
1385 "Function '%s' must be called directly, and not by way of a "
1386 "function of another name.")
1387
1388 (js2-msg "msg.eval.nonstring"
1389 "Calling eval() with anything other than a primitive "
1390 "string value will simply return the value. "
1391 "Is this what you intended?")
1392
1393 (js2-msg "msg.eval.nonstring.strict"
1394 "Calling eval() with anything other than a primitive "
1395 "string value is not allowed in strict mode.")
1396
1397 (js2-msg "msg.bad.destruct.op"
1398 "Invalid destructuring assignment operator")
1399
1400 ;; NativeCall
1401 (js2-msg "msg.only.from.new"
1402 "'%s' may only be invoked from a `new' expression.")
1403
1404 (js2-msg "msg.deprec.ctor"
1405 "The '%s' constructor is deprecated.")
1406
1407 ;; NativeFunction
1408 (js2-msg "msg.no.function.ref.found"
1409 "no source found to decompile function reference %s")
1410
1411 (js2-msg "msg.arg.isnt.array"
1412 "second argument to Function.prototype.apply must be an array")
1413
1414 ;; NativeGlobal
1415 (js2-msg "msg.bad.esc.mask"
1416 "invalid string escape mask")
1417
1418 ;; NativeRegExp
1419 (js2-msg "msg.bad.quant"
1420 "Invalid quantifier %s")
1421
1422 (js2-msg "msg.overlarge.backref"
1423 "Overly large back reference %s")
1424
1425 (js2-msg "msg.overlarge.min"
1426 "Overly large minimum %s")
1427
1428 (js2-msg "msg.overlarge.max"
1429 "Overly large maximum %s")
1430
1431 (js2-msg "msg.zero.quant"
1432 "Zero quantifier %s")
1433
1434 (js2-msg "msg.max.lt.min"
1435 "Maximum %s less than minimum")
1436
1437 (js2-msg "msg.unterm.quant"
1438 "Unterminated quantifier %s")
1439
1440 (js2-msg "msg.unterm.paren"
1441 "Unterminated parenthetical %s")
1442
1443 (js2-msg "msg.unterm.class"
1444 "Unterminated character class %s")
1445
1446 (js2-msg "msg.bad.range"
1447 "Invalid range in character class.")
1448
1449 (js2-msg "msg.trail.backslash"
1450 "Trailing \\ in regular expression.")
1451
1452 (js2-msg "msg.re.unmatched.right.paren"
1453 "unmatched ) in regular expression.")
1454
1455 (js2-msg "msg.no.regexp"
1456 "Regular expressions are not available.")
1457
1458 (js2-msg "msg.bad.backref"
1459 "back-reference exceeds number of capturing parentheses.")
1460
1461 (js2-msg "msg.bad.regexp.compile"
1462 "Only one argument may be specified if the first "
1463 "argument to RegExp.prototype.compile is a RegExp object.")
1464
1465 ;; Parser
1466 (js2-msg "msg.got.syntax.errors"
1467 "Compilation produced %s syntax errors.")
1468
1469 (js2-msg "msg.var.redecl"
1470 "TypeError: redeclaration of var %s.")
1471
1472 (js2-msg "msg.const.redecl"
1473 "TypeError: redeclaration of const %s.")
1474
1475 (js2-msg "msg.let.redecl"
1476 "TypeError: redeclaration of variable %s.")
1477
1478 (js2-msg "msg.parm.redecl"
1479 "TypeError: redeclaration of formal parameter %s.")
1480
1481 (js2-msg "msg.fn.redecl"
1482 "TypeError: redeclaration of function %s.")
1483
1484 (js2-msg "msg.let.decl.not.in.block"
1485 "SyntaxError: let declaration not directly within block")
1486
1487 ;; NodeTransformer
1488 (js2-msg "msg.dup.label"
1489 "duplicated label")
1490
1491 (js2-msg "msg.undef.label"
1492 "undefined label")
1493
1494 (js2-msg "msg.bad.break"
1495 "unlabelled break must be inside loop or switch")
1496
1497 (js2-msg "msg.continue.outside"
1498 "continue must be inside loop")
1499
1500 (js2-msg "msg.continue.nonloop"
1501 "continue can only use labels of iteration statements")
1502
1503 (js2-msg "msg.bad.throw.eol"
1504 "Line terminator is not allowed between the throw "
1505 "keyword and throw expression.")
1506
1507 (js2-msg "msg.no.paren.parms"
1508 "missing ( before function parameters.")
1509
1510 (js2-msg "msg.no.parm"
1511 "missing formal parameter")
1512
1513 (js2-msg "msg.no.paren.after.parms"
1514 "missing ) after formal parameters")
1515
1516 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1517 "parameter without default follows parameter with default")
1518
1519 (js2-msg "msg.param.after.rest" ; added by js2-mode
1520 "parameter after rest parameter")
1521
1522 (js2-msg "msg.no.brace.body"
1523 "missing '{' before function body")
1524
1525 (js2-msg "msg.no.brace.after.body"
1526 "missing } after function body")
1527
1528 (js2-msg "msg.no.paren.cond"
1529 "missing ( before condition")
1530
1531 (js2-msg "msg.no.paren.after.cond"
1532 "missing ) after condition")
1533
1534 (js2-msg "msg.no.semi.stmt"
1535 "missing ; before statement")
1536
1537 (js2-msg "msg.missing.semi"
1538 "missing ; after statement")
1539
1540 (js2-msg "msg.no.name.after.dot"
1541 "missing name after . operator")
1542
1543 (js2-msg "msg.no.name.after.coloncolon"
1544 "missing name after :: operator")
1545
1546 (js2-msg "msg.no.name.after.dotdot"
1547 "missing name after .. operator")
1548
1549 (js2-msg "msg.no.name.after.xmlAttr"
1550 "missing name after .@")
1551
1552 (js2-msg "msg.no.bracket.index"
1553 "missing ] in index expression")
1554
1555 (js2-msg "msg.no.paren.switch"
1556 "missing ( before switch expression")
1557
1558 (js2-msg "msg.no.paren.after.switch"
1559 "missing ) after switch expression")
1560
1561 (js2-msg "msg.no.brace.switch"
1562 "missing '{' before switch body")
1563
1564 (js2-msg "msg.bad.switch"
1565 "invalid switch statement")
1566
1567 (js2-msg "msg.no.colon.case"
1568 "missing : after case expression")
1569
1570 (js2-msg "msg.double.switch.default"
1571 "double default label in the switch statement")
1572
1573 (js2-msg "msg.no.while.do"
1574 "missing while after do-loop body")
1575
1576 (js2-msg "msg.no.paren.for"
1577 "missing ( after for")
1578
1579 (js2-msg "msg.no.semi.for"
1580 "missing ; after for-loop initializer")
1581
1582 (js2-msg "msg.no.semi.for.cond"
1583 "missing ; after for-loop condition")
1584
1585 (js2-msg "msg.in.after.for.name"
1586 "missing in or of after for")
1587
1588 (js2-msg "msg.no.paren.for.ctrl"
1589 "missing ) after for-loop control")
1590
1591 (js2-msg "msg.no.paren.with"
1592 "missing ( before with-statement object")
1593
1594 (js2-msg "msg.no.paren.after.with"
1595 "missing ) after with-statement object")
1596
1597 (js2-msg "msg.no.paren.after.let"
1598 "missing ( after let")
1599
1600 (js2-msg "msg.no.paren.let"
1601 "missing ) after variable list")
1602
1603 (js2-msg "msg.no.curly.let"
1604 "missing } after let statement")
1605
1606 (js2-msg "msg.bad.return"
1607 "invalid return")
1608
1609 (js2-msg "msg.no.brace.block"
1610 "missing } in compound statement")
1611
1612 (js2-msg "msg.bad.label"
1613 "invalid label")
1614
1615 (js2-msg "msg.bad.var"
1616 "missing variable name")
1617
1618 (js2-msg "msg.bad.var.init"
1619 "invalid variable initialization")
1620
1621 (js2-msg "msg.no.colon.cond"
1622 "missing : in conditional expression")
1623
1624 (js2-msg "msg.no.paren.arg"
1625 "missing ) after argument list")
1626
1627 (js2-msg "msg.no.bracket.arg"
1628 "missing ] after element list")
1629
1630 (js2-msg "msg.bad.prop"
1631 "invalid property id")
1632
1633 (js2-msg "msg.no.colon.prop"
1634 "missing : after property id")
1635
1636 (js2-msg "msg.no.brace.prop"
1637 "missing } after property list")
1638
1639 (js2-msg "msg.no.paren"
1640 "missing ) in parenthetical")
1641
1642 (js2-msg "msg.reserved.id"
1643 "identifier is a reserved word")
1644
1645 (js2-msg "msg.no.paren.catch"
1646 "missing ( before catch-block condition")
1647
1648 (js2-msg "msg.bad.catchcond"
1649 "invalid catch block condition")
1650
1651 (js2-msg "msg.catch.unreachable"
1652 "any catch clauses following an unqualified catch are unreachable")
1653
1654 (js2-msg "msg.no.brace.try"
1655 "missing '{' before try block")
1656
1657 (js2-msg "msg.no.brace.catchblock"
1658 "missing '{' before catch-block body")
1659
1660 (js2-msg "msg.try.no.catchfinally"
1661 "'try' without 'catch' or 'finally'")
1662
1663 (js2-msg "msg.no.return.value"
1664 "function %s does not always return a value")
1665
1666 (js2-msg "msg.anon.no.return.value"
1667 "anonymous function does not always return a value")
1668
1669 (js2-msg "msg.return.inconsistent"
1670 "return statement is inconsistent with previous usage")
1671
1672 (js2-msg "msg.generator.returns"
1673 "TypeError: generator function '%s' returns a value")
1674
1675 (js2-msg "msg.anon.generator.returns"
1676 "TypeError: anonymous generator function returns a value")
1677
1678 (js2-msg "msg.syntax"
1679 "syntax error")
1680
1681 (js2-msg "msg.unexpected.eof"
1682 "Unexpected end of file")
1683
1684 (js2-msg "msg.XML.bad.form"
1685 "illegally formed XML syntax")
1686
1687 (js2-msg "msg.XML.not.available"
1688 "XML runtime not available")
1689
1690 (js2-msg "msg.too.deep.parser.recursion"
1691 "Too deep recursion while parsing")
1692
1693 (js2-msg "msg.no.side.effects"
1694 "Code has no side effects")
1695
1696 (js2-msg "msg.extra.trailing.comma"
1697 "Trailing comma is not supported in some browsers")
1698
1699 (js2-msg "msg.array.trailing.comma"
1700 "Trailing comma yields different behavior across browsers")
1701
1702 (js2-msg "msg.equal.as.assign"
1703 (concat "Test for equality (==) mistyped as assignment (=)?"
1704 " (parenthesize to suppress warning)"))
1705
1706 (js2-msg "msg.var.hides.arg"
1707 "Variable %s hides argument")
1708
1709 (js2-msg "msg.destruct.assign.no.init"
1710 "Missing = in destructuring declaration")
1711
1712 ;; ScriptRuntime
1713 (js2-msg "msg.no.properties"
1714 "%s has no properties.")
1715
1716 (js2-msg "msg.invalid.iterator"
1717 "Invalid iterator value")
1718
1719 (js2-msg "msg.iterator.primitive"
1720 "__iterator__ returned a primitive value")
1721
1722 (js2-msg "msg.assn.create.strict"
1723 "Assignment to undeclared variable %s")
1724
1725 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1726 "Undeclared variable or function '%s'")
1727
1728 (js2-msg "msg.ref.undefined.prop"
1729 "Reference to undefined property '%s'")
1730
1731 (js2-msg "msg.prop.not.found"
1732 "Property %s not found.")
1733
1734 (js2-msg "msg.invalid.type"
1735 "Invalid JavaScript value of type %s")
1736
1737 (js2-msg "msg.primitive.expected"
1738 "Primitive type expected (had %s instead)")
1739
1740 (js2-msg "msg.namespace.expected"
1741 "Namespace object expected to left of :: (found %s instead)")
1742
1743 (js2-msg "msg.null.to.object"
1744 "Cannot convert null to an object.")
1745
1746 (js2-msg "msg.undef.to.object"
1747 "Cannot convert undefined to an object.")
1748
1749 (js2-msg "msg.cyclic.value"
1750 "Cyclic %s value not allowed.")
1751
1752 (js2-msg "msg.is.not.defined"
1753 "'%s' is not defined.")
1754
1755 (js2-msg "msg.undef.prop.read"
1756 "Cannot read property '%s' from %s")
1757
1758 (js2-msg "msg.undef.prop.write"
1759 "Cannot set property '%s' of %s to '%s'")
1760
1761 (js2-msg "msg.undef.prop.delete"
1762 "Cannot delete property '%s' of %s")
1763
1764 (js2-msg "msg.undef.method.call"
1765 "Cannot call method '%s' of %s")
1766
1767 (js2-msg "msg.undef.with"
1768 "Cannot apply 'with' to %s")
1769
1770 (js2-msg "msg.isnt.function"
1771 "%s is not a function, it is %s.")
1772
1773 (js2-msg "msg.isnt.function.in"
1774 "Cannot call property %s in object %s. "
1775 "It is not a function, it is '%s'.")
1776
1777 (js2-msg "msg.function.not.found"
1778 "Cannot find function %s.")
1779
1780 (js2-msg "msg.function.not.found.in"
1781 "Cannot find function %s in object %s.")
1782
1783 (js2-msg "msg.isnt.xml.object"
1784 "%s is not an xml object.")
1785
1786 (js2-msg "msg.no.ref.to.get"
1787 "%s is not a reference to read reference value.")
1788
1789 (js2-msg "msg.no.ref.to.set"
1790 "%s is not a reference to set reference value to %s.")
1791
1792 (js2-msg "msg.no.ref.from.function"
1793 "Function %s can not be used as the left-hand "
1794 "side of assignment or as an operand of ++ or -- operator.")
1795
1796 (js2-msg "msg.bad.default.value"
1797 "Object's getDefaultValue() method returned an object.")
1798
1799 (js2-msg "msg.instanceof.not.object"
1800 "Can't use instanceof on a non-object.")
1801
1802 (js2-msg "msg.instanceof.bad.prototype"
1803 "'prototype' property of %s is not an object.")
1804
1805 (js2-msg "msg.bad.radix"
1806 "illegal radix %s.")
1807
1808 ;; ScriptableObject
1809 (js2-msg "msg.default.value"
1810 "Cannot find default value for object.")
1811
1812 (js2-msg "msg.zero.arg.ctor"
1813 "Cannot load class '%s' which has no zero-parameter constructor.")
1814
1815 (js2-msg "msg.ctor.multiple.parms"
1816 "Can't define constructor or class %s since more than "
1817 "one constructor has multiple parameters.")
1818
1819 (js2-msg "msg.extend.scriptable"
1820 "%s must extend ScriptableObject in order to define property %s.")
1821
1822 (js2-msg "msg.bad.getter.parms"
1823 "In order to define a property, getter %s must have zero "
1824 "parameters or a single ScriptableObject parameter.")
1825
1826 (js2-msg "msg.obj.getter.parms"
1827 "Expected static or delegated getter %s to take "
1828 "a ScriptableObject parameter.")
1829
1830 (js2-msg "msg.getter.static"
1831 "Getter and setter must both be static or neither be static.")
1832
1833 (js2-msg "msg.setter.return"
1834 "Setter must have void return type: %s")
1835
1836 (js2-msg "msg.setter2.parms"
1837 "Two-parameter setter must take a ScriptableObject as "
1838 "its first parameter.")
1839
1840 (js2-msg "msg.setter1.parms"
1841 "Expected single parameter setter for %s")
1842
1843 (js2-msg "msg.setter2.expected"
1844 "Expected static or delegated setter %s to take two parameters.")
1845
1846 (js2-msg "msg.setter.parms"
1847 "Expected either one or two parameters for setter.")
1848
1849 (js2-msg "msg.setter.bad.type"
1850 "Unsupported parameter type '%s' in setter '%s'.")
1851
1852 (js2-msg "msg.add.sealed"
1853 "Cannot add a property to a sealed object: %s.")
1854
1855 (js2-msg "msg.remove.sealed"
1856 "Cannot remove a property from a sealed object: %s.")
1857
1858 (js2-msg "msg.modify.sealed"
1859 "Cannot modify a property of a sealed object: %s.")
1860
1861 (js2-msg "msg.modify.readonly"
1862 "Cannot modify readonly property: %s.")
1863
1864 ;; TokenStream
1865 (js2-msg "msg.missing.exponent"
1866 "missing exponent")
1867
1868 (js2-msg "msg.caught.nfe"
1869 "number format error")
1870
1871 (js2-msg "msg.unterminated.string.lit"
1872 "unterminated string literal")
1873
1874 (js2-msg "msg.unterminated.comment"
1875 "unterminated comment")
1876
1877 (js2-msg "msg.unterminated.re.lit"
1878 "unterminated regular expression literal")
1879
1880 (js2-msg "msg.invalid.re.flag"
1881 "invalid flag after regular expression")
1882
1883 (js2-msg "msg.no.re.input.for"
1884 "no input for %s")
1885
1886 (js2-msg "msg.illegal.character"
1887 "illegal character")
1888
1889 (js2-msg "msg.invalid.escape"
1890 "invalid Unicode escape sequence")
1891
1892 (js2-msg "msg.bad.namespace"
1893 "not a valid default namespace statement. "
1894 "Syntax is: default xml namespace = EXPRESSION;")
1895
1896 ;; TokensStream warnings
1897 (js2-msg "msg.bad.octal.literal"
1898 "illegal octal literal digit %s; "
1899 "interpreting it as a decimal digit")
1900
1901 (js2-msg "msg.reserved.keyword"
1902 "illegal usage of future reserved keyword %s; "
1903 "interpreting it as ordinary identifier")
1904
1905 (js2-msg "msg.script.is.not.constructor"
1906 "Script objects are not constructors.")
1907
1908 ;; Arrays
1909 (js2-msg "msg.arraylength.bad"
1910 "Inappropriate array length.")
1911
1912 ;; Arrays
1913 (js2-msg "msg.arraylength.too.big"
1914 "Array length %s exceeds supported capacity limit.")
1915
1916 ;; URI
1917 (js2-msg "msg.bad.uri"
1918 "Malformed URI sequence.")
1919
1920 ;; Number
1921 (js2-msg "msg.bad.precision"
1922 "Precision %s out of range.")
1923
1924 ;; NativeGenerator
1925 (js2-msg "msg.send.newborn"
1926 "Attempt to send value to newborn generator")
1927
1928 (js2-msg "msg.already.exec.gen"
1929 "Already executing generator")
1930
1931 (js2-msg "msg.StopIteration.invalid"
1932 "StopIteration may not be changed to an arbitrary object.")
1933
1934 ;; Interpreter
1935 (js2-msg "msg.yield.closing"
1936 "Yield from closing generator")
1937
1938 ;;; Utilities
1939
1940 (defun js2-delete-if (predicate list)
1941 "Remove all items satisfying PREDICATE in LIST."
1942 (loop for item in list
1943 if (not (funcall predicate item))
1944 collect item))
1945
1946 (defun js2-position (element list)
1947 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1948 Returns nil if element is not found in the list."
1949 (let ((count 0)
1950 found)
1951 (while (and list (not found))
1952 (if (eq element (car list))
1953 (setq found t)
1954 (setq count (1+ count)
1955 list (cdr list))))
1956 (if found count)))
1957
1958 (defun js2-find-if (predicate list)
1959 "Find first item satisfying PREDICATE in LIST."
1960 (let (result)
1961 (while (and list (not result))
1962 (if (funcall predicate (car list))
1963 (setq result (car list)))
1964 (setq list (cdr list)))
1965 result))
1966
1967 (defmacro js2-time (form)
1968 "Evaluate FORM, discard result, and return elapsed time in sec."
1969 (declare (debug t))
1970 (let ((beg (make-symbol "--js2-time-beg--"))
1971 (delta (make-symbol "--js2-time-end--")))
1972 `(let ((,beg (current-time))
1973 ,delta)
1974 ,form
1975 (/ (truncate (* (- (float-time (current-time))
1976 (float-time ,beg))
1977 10000))
1978 10000.0))))
1979
1980 (defsubst js2-same-line (pos)
1981 "Return t if POS is on the same line as current point."
1982 (and (>= pos (point-at-bol))
1983 (<= pos (point-at-eol))))
1984
1985 (defun js2-code-bug ()
1986 "Signal an error when we encounter an unexpected code path."
1987 (error "failed assertion"))
1988
1989 (defsubst js2-record-text-property (beg end prop value)
1990 "Record a text property to set when parsing finishes."
1991 (push (list beg end prop value) js2-mode-deferred-properties))
1992
1993 ;; I'd like to associate errors with nodes, but for now the
1994 ;; easiest thing to do is get the context info from the last token.
1995 (defun js2-record-parse-error (msg &optional arg pos len)
1996 (push (list (list msg arg)
1997 (or pos js2-token-beg)
1998 (or len (- js2-token-end js2-token-beg)))
1999 js2-parsed-errors))
2000
2001 (defun js2-report-error (msg &optional msg-arg pos len)
2002 "Signal a syntax error or record a parse error."
2003 (if js2-recover-from-parse-errors
2004 (js2-record-parse-error msg msg-arg pos len)
2005 (signal 'js2-syntax-error
2006 (list msg
2007 js2-ts-lineno
2008 (save-excursion
2009 (goto-char js2-ts-cursor)
2010 (current-column))
2011 js2-ts-hit-eof))))
2012
2013 (defun js2-report-warning (msg &optional msg-arg pos len face)
2014 (if js2-compiler-report-warning-as-error
2015 (js2-report-error msg msg-arg pos len)
2016 (push (list (list msg msg-arg)
2017 (or pos js2-token-beg)
2018 (or len (- js2-token-end js2-token-beg))
2019 face)
2020 js2-parsed-warnings)))
2021
2022 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2023 (if js2-compiler-strict-mode
2024 (js2-report-warning msg-id msg-arg beg
2025 (and beg end (- end beg)))))
2026
2027 (put 'js2-syntax-error 'error-conditions
2028 '(error syntax-error js2-syntax-error))
2029 (put 'js2-syntax-error 'error-message "Syntax error")
2030
2031 (put 'js2-parse-error 'error-conditions
2032 '(error parse-error js2-parse-error))
2033 (put 'js2-parse-error 'error-message "Parse error")
2034
2035 (defmacro js2-clear-flag (flags flag)
2036 `(setq ,flags (logand ,flags (lognot ,flag))))
2037
2038 (defmacro js2-set-flag (flags flag)
2039 "Logical-or FLAG into FLAGS."
2040 `(setq ,flags (logior ,flags ,flag)))
2041
2042 (defsubst js2-flag-set-p (flags flag)
2043 (/= 0 (logand flags flag)))
2044
2045 (defsubst js2-flag-not-set-p (flags flag)
2046 (zerop (logand flags flag)))
2047
2048 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2049 "Evaluate BODY with the _ character set to be word-syntax."
2050 (declare (indent 0) (debug t))
2051 (let ((old-syntax (make-symbol "old-syntax")))
2052 `(let ((,old-syntax (string (char-syntax ?_))))
2053 (unwind-protect
2054 (progn
2055 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2056 ,@body)
2057 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2058
2059 (defsubst js2-char-uppercase-p (c)
2060 "Return t if C is an uppercase character.
2061 Handles unicode and latin chars properly."
2062 (/= c (downcase c)))
2063
2064 (defsubst js2-char-lowercase-p (c)
2065 "Return t if C is an uppercase character.
2066 Handles unicode and latin chars properly."
2067 (/= c (upcase c)))
2068
2069 ;;; AST struct and function definitions
2070
2071 ;; flags for ast node property 'member-type (used for e4x operators)
2072 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2073 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2074 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2075
2076 (defsubst js2-relpos (pos anchor)
2077 "Convert POS to be relative to ANCHOR.
2078 If POS is nil, returns nil."
2079 (and pos (- pos anchor)))
2080
2081 (defun js2-make-pad (indent)
2082 (if (zerop indent)
2083 ""
2084 (make-string (* indent js2-basic-offset) ? )))
2085
2086 (defun js2-visit-ast (node callback)
2087 "Visit every node in ast NODE with visitor CALLBACK.
2088
2089 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2090 called twice: once to visit the node, and again after all the node's
2091 children have been processed. The END-P argument is nil on the first
2092 call and non-nil on the second call. The return value of the callback
2093 affects the traversal: if non-nil, the children of NODE are processed.
2094 If the callback returns nil, or if the node has no children, then the
2095 callback is called immediately with a non-nil END-P argument.
2096
2097 The node traversal is approximately lexical-order, although there
2098 are currently no guarantees around this."
2099 (when node
2100 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2101 ;; visit the node
2102 (when (funcall callback node nil)
2103 ;; visit the kids
2104 (cond
2105 ((eq vfunc 'js2-visit-none)
2106 nil) ; don't even bother calling it
2107 ;; Each AST node type has to define a `js2-visitor' function
2108 ;; that takes a node and a callback, and calls `js2-visit-ast'
2109 ;; on each child of the node.
2110 (vfunc
2111 (funcall vfunc node callback))
2112 (t
2113 (error "%s does not define a visitor-traversal function"
2114 (aref node 0)))))
2115 ;; call the end-visit
2116 (funcall callback node t))))
2117
2118 (defstruct (js2-node
2119 (:constructor nil)) ; abstract
2120 "Base AST node type."
2121 (type -1) ; token type
2122 (pos -1) ; start position of this AST node in parsed input
2123 (len 1) ; num characters spanned by the node
2124 props ; optional node property list (an alist)
2125 parent) ; link to parent node; null for root
2126
2127 (defsubst js2-node-get-prop (node prop &optional default)
2128 (or (cadr (assoc prop (js2-node-props node))) default))
2129
2130 (defsubst js2-node-set-prop (node prop value)
2131 (setf (js2-node-props node)
2132 (cons (list prop value) (js2-node-props node))))
2133
2134 (defun js2-fixup-starts (n nodes)
2135 "Adjust the start positions of NODES to be relative to N.
2136 Any node in the list may be nil, for convenience."
2137 (dolist (node nodes)
2138 (when node
2139 (setf (js2-node-pos node) (- (js2-node-pos node)
2140 (js2-node-pos n))))))
2141
2142 (defun js2-node-add-children (parent &rest nodes)
2143 "Set parent node of NODES to PARENT, and return PARENT.
2144 Does nothing if we're not recording parent links.
2145 If any given node in NODES is nil, doesn't record that link."
2146 (js2-fixup-starts parent nodes)
2147 (dolist (node nodes)
2148 (and node
2149 (setf (js2-node-parent node) parent))))
2150
2151 ;; Non-recursive since it's called a frightening number of times.
2152 (defun js2-node-abs-pos (n)
2153 (let ((pos (js2-node-pos n)))
2154 (while (setq n (js2-node-parent n))
2155 (setq pos (+ pos (js2-node-pos n))))
2156 pos))
2157
2158 (defsubst js2-node-abs-end (n)
2159 "Return absolute buffer position of end of N."
2160 (+ (js2-node-abs-pos n) (js2-node-len n)))
2161
2162 ;; It's important to make sure block nodes have a Lisp list for the
2163 ;; child nodes, to limit printing recursion depth in an AST that
2164 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2165 ;; a sufficiently large vector tree.
2166
2167 (defstruct (js2-block-node
2168 (:include js2-node)
2169 (:constructor nil)
2170 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2171 (pos js2-token-beg)
2172 len
2173 props
2174 kids)))
2175 "A block of statements."
2176 kids) ; a Lisp list of the child statement nodes
2177
2178 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2179 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2180
2181 (defun js2-visit-block (ast callback)
2182 "Visit the `js2-block-node' children of AST."
2183 (dolist (kid (js2-block-node-kids ast))
2184 (js2-visit-ast kid callback)))
2185
2186 (defun js2-print-block (n i)
2187 (let ((pad (js2-make-pad i)))
2188 (insert pad "{\n")
2189 (dolist (kid (js2-block-node-kids n))
2190 (js2-print-ast kid (1+ i)))
2191 (insert pad "}")))
2192
2193 (defstruct (js2-scope
2194 (:include js2-block-node)
2195 (:constructor nil)
2196 (:constructor make-js2-scope (&key (type js2-BLOCK)
2197 (pos js2-token-beg)
2198 len
2199 kids)))
2200 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2201 ;; I don't have one of those handy, so I'll use an alist for now.
2202 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2203 ;; and is much lighter-weight to construct (both CPU and mem).
2204 ;; The keys are interned strings (symbols) for faster lookup.
2205 ;; Should switch to hybrid alist/hashtable eventually.
2206 symbol-table ; an alist of (symbol . js2-symbol)
2207 parent-scope ; a `js2-scope'
2208 top) ; top-level `js2-scope' (script/function)
2209
2210 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2211 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2212
2213 (defun js2-node-get-enclosing-scope (node)
2214 "Return the innermost `js2-scope' node surrounding NODE.
2215 Returns nil if there is no enclosing scope node."
2216 (let ((parent (js2-node-parent node)))
2217 (while (not (js2-scope-p parent))
2218 (setq parent (js2-node-parent parent)))
2219 parent))
2220
2221 (defun js2-get-defining-scope (scope name)
2222 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2223 Returns `js2-scope' in which NAME is defined, or nil if not found."
2224 (let ((sym (if (symbolp name)
2225 name
2226 (intern name)))
2227 table
2228 result
2229 (continue t))
2230 (while (and scope continue)
2231 (if (and (setq table (js2-scope-symbol-table scope))
2232 (assq sym table))
2233 (setq continue nil
2234 result scope)
2235 (setq scope (js2-scope-parent-scope scope))))
2236 result))
2237
2238 (defun js2-scope-get-symbol (scope name)
2239 "Return symbol table entry for NAME in SCOPE.
2240 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2241 (and (js2-scope-symbol-table scope)
2242 (cdr (assq (if (symbolp name)
2243 name
2244 (intern name))
2245 (js2-scope-symbol-table scope)))))
2246
2247 (defun js2-scope-put-symbol (scope name symbol)
2248 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2249 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2250 (let* ((table (js2-scope-symbol-table scope))
2251 (sym (if (symbolp name) name (intern name)))
2252 (entry (assq sym table)))
2253 (if entry
2254 (setcdr entry symbol)
2255 (push (cons sym symbol)
2256 (js2-scope-symbol-table scope)))))
2257
2258 (defstruct (js2-symbol
2259 (:constructor nil)
2260 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2261 "A symbol table entry."
2262 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2263 ;; js2-LET, or js2-CONST
2264 decl-type
2265 name ; string
2266 ast-node) ; a `js2-node'
2267
2268 (defstruct (js2-error-node
2269 (:include js2-node)
2270 (:constructor nil) ; silence emacs21 byte-compiler
2271 (:constructor make-js2-error-node (&key (type js2-ERROR)
2272 (pos js2-token-beg)
2273 len)))
2274 "AST node representing a parse error.")
2275
2276 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2277 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2278
2279 (defstruct (js2-script-node
2280 (:include js2-scope)
2281 (:constructor nil)
2282 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2283 (pos js2-token-beg)
2284 len
2285 var-decls
2286 fun-decls)))
2287 functions ; Lisp list of nested functions
2288 regexps ; Lisp list of (string . flags)
2289 symbols ; alist (every symbol gets unique index)
2290 (param-count 0)
2291 var-names ; vector of string names
2292 consts ; bool-vector matching var-decls
2293 (temp-number 0)) ; for generating temp variables
2294
2295 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2296 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2297
2298 (defun js2-print-script (node indent)
2299 (dolist (kid (js2-block-node-kids node))
2300 (js2-print-ast kid indent)))
2301
2302 (defstruct (js2-ast-root
2303 (:include js2-script-node)
2304 (:constructor nil)
2305 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2306 (pos js2-token-beg)
2307 len
2308 buffer)))
2309 "The root node of a js2 AST."
2310 buffer ; the source buffer from which the code was parsed
2311 comments ; a Lisp list of comments, ordered by start position
2312 errors ; a Lisp list of errors found during parsing
2313 warnings ; a Lisp list of warnings found during parsing
2314 node-count) ; number of nodes in the tree, including the root
2315
2316 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2317 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2318
2319 (defun js2-visit-ast-root (ast callback)
2320 (dolist (kid (js2-ast-root-kids ast))
2321 (js2-visit-ast kid callback))
2322 (dolist (comment (js2-ast-root-comments ast))
2323 (js2-visit-ast comment callback)))
2324
2325 (defstruct (js2-comment-node
2326 (:include js2-node)
2327 (:constructor nil)
2328 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2329 (pos js2-token-beg)
2330 len
2331 (format js2-ts-comment-type))))
2332 format) ; 'line, 'block, 'jsdoc or 'html
2333
2334 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2335 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2336
2337 (defun js2-print-comment (n i)
2338 ;; We really ought to link end-of-line comments to their nodes.
2339 ;; Or maybe we could add a new comment type, 'endline.
2340 (insert (js2-make-pad i)
2341 (js2-node-string n)))
2342
2343 (defstruct (js2-expr-stmt-node
2344 (:include js2-node)
2345 (:constructor nil)
2346 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2347 (pos js2-ts-cursor)
2348 len
2349 expr)))
2350 "An expression statement."
2351 expr)
2352
2353 (defsubst js2-expr-stmt-node-set-has-result (node)
2354 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2355 (setf (js2-node-type node) js2-EXPR_RESULT))
2356
2357 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2358 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2359
2360 (defun js2-visit-expr-stmt-node (n v)
2361 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2362
2363 (defun js2-print-expr-stmt-node (n indent)
2364 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2365 (insert ";\n"))
2366
2367 (defstruct (js2-loop-node
2368 (:include js2-scope)
2369 (:constructor nil))
2370 "Abstract supertype of loop nodes."
2371 body ; a `js2-block-node'
2372 lp ; position of left-paren, nil if omitted
2373 rp) ; position of right-paren, nil if omitted
2374
2375 (defstruct (js2-do-node
2376 (:include js2-loop-node)
2377 (:constructor nil)
2378 (:constructor make-js2-do-node (&key (type js2-DO)
2379 (pos js2-token-beg)
2380 len
2381 body
2382 condition
2383 while-pos
2384 lp
2385 rp)))
2386 "AST node for do-loop."
2387 condition ; while (expression)
2388 while-pos) ; buffer position of 'while' keyword
2389
2390 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2391 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2392
2393 (defun js2-visit-do-node (n v)
2394 (js2-visit-ast (js2-do-node-body n) v)
2395 (js2-visit-ast (js2-do-node-condition n) v))
2396
2397 (defun js2-print-do-node (n i)
2398 (let ((pad (js2-make-pad i)))
2399 (insert pad "do {\n")
2400 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2401 (js2-print-ast kid (1+ i)))
2402 (insert pad "} while (")
2403 (js2-print-ast (js2-do-node-condition n) 0)
2404 (insert ");\n")))
2405
2406 (defstruct (js2-while-node
2407 (:include js2-loop-node)
2408 (:constructor nil)
2409 (:constructor make-js2-while-node (&key (type js2-WHILE)
2410 (pos js2-token-beg)
2411 len body
2412 condition lp
2413 rp)))
2414 "AST node for while-loop."
2415 condition) ; while-condition
2416
2417 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2418 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2419
2420 (defun js2-visit-while-node (n v)
2421 (js2-visit-ast (js2-while-node-condition n) v)
2422 (js2-visit-ast (js2-while-node-body n) v))
2423
2424 (defun js2-print-while-node (n i)
2425 (let ((pad (js2-make-pad i)))
2426 (insert pad "while (")
2427 (js2-print-ast (js2-while-node-condition n) 0)
2428 (insert ") {\n")
2429 (js2-print-body (js2-while-node-body n) (1+ i))
2430 (insert pad "}\n")))
2431
2432 (defstruct (js2-for-node
2433 (:include js2-loop-node)
2434 (:constructor nil)
2435 (:constructor make-js2-for-node (&key (type js2-FOR)
2436 (pos js2-ts-cursor)
2437 len body init
2438 condition
2439 update lp rp)))
2440 "AST node for a C-style for-loop."
2441 init ; initialization expression
2442 condition ; loop condition
2443 update) ; update clause
2444
2445 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2446 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2447
2448 (defun js2-visit-for-node (n v)
2449 (js2-visit-ast (js2-for-node-init n) v)
2450 (js2-visit-ast (js2-for-node-condition n) v)
2451 (js2-visit-ast (js2-for-node-update n) v)
2452 (js2-visit-ast (js2-for-node-body n) v))
2453
2454 (defun js2-print-for-node (n i)
2455 (let ((pad (js2-make-pad i)))
2456 (insert pad "for (")
2457 (js2-print-ast (js2-for-node-init n) 0)
2458 (insert "; ")
2459 (js2-print-ast (js2-for-node-condition n) 0)
2460 (insert "; ")
2461 (js2-print-ast (js2-for-node-update n) 0)
2462 (insert ") {\n")
2463 (js2-print-body (js2-for-node-body n) (1+ i))
2464 (insert pad "}\n")))
2465
2466 (defstruct (js2-for-in-node
2467 (:include js2-loop-node)
2468 (:constructor nil)
2469 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2470 (pos js2-ts-cursor)
2471 len body
2472 iterator
2473 object
2474 in-pos
2475 each-pos
2476 foreach-p forof-p
2477 lp rp)))
2478 "AST node for a for..in loop."
2479 iterator ; [var] foo in ...
2480 object ; object over which we're iterating
2481 in-pos ; buffer position of 'in' keyword
2482 each-pos ; buffer position of 'each' keyword, if foreach-p
2483 foreach-p ; t if it's a for-each loop
2484 forof-p) ; t if it's a for-of loop
2485
2486 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2487 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2488
2489 (defun js2-visit-for-in-node (n v)
2490 (js2-visit-ast (js2-for-in-node-iterator n) v)
2491 (js2-visit-ast (js2-for-in-node-object n) v)
2492 (js2-visit-ast (js2-for-in-node-body n) v))
2493
2494 (defun js2-print-for-in-node (n i)
2495 (let ((pad (js2-make-pad i))
2496 (foreach (js2-for-in-node-foreach-p n))
2497 (forof (js2-for-in-node-forof-p n)))
2498 (insert pad "for ")
2499 (if foreach
2500 (insert "each "))
2501 (insert "(")
2502 (js2-print-ast (js2-for-in-node-iterator n) 0)
2503 (if forof
2504 (insert " of ")
2505 (insert " in "))
2506 (js2-print-ast (js2-for-in-node-object n) 0)
2507 (insert ") {\n")
2508 (js2-print-body (js2-for-in-node-body n) (1+ i))
2509 (insert pad "}\n")))
2510
2511 (defstruct (js2-return-node
2512 (:include js2-node)
2513 (:constructor nil)
2514 (:constructor make-js2-return-node (&key (type js2-RETURN)
2515 (pos js2-ts-cursor)
2516 len
2517 retval)))
2518 "AST node for a return statement."
2519 retval) ; expression to return, or 'undefined
2520
2521 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2522 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2523
2524 (defun js2-visit-return-node (n v)
2525 (js2-visit-ast (js2-return-node-retval n) v))
2526
2527 (defun js2-print-return-node (n i)
2528 (insert (js2-make-pad i) "return")
2529 (when (js2-return-node-retval n)
2530 (insert " ")
2531 (js2-print-ast (js2-return-node-retval n) 0))
2532 (insert ";\n"))
2533
2534 (defstruct (js2-if-node
2535 (:include js2-node)
2536 (:constructor nil)
2537 (:constructor make-js2-if-node (&key (type js2-IF)
2538 (pos js2-ts-cursor)
2539 len condition
2540 then-part
2541 else-pos
2542 else-part lp
2543 rp)))
2544 "AST node for an if-statement."
2545 condition ; expression
2546 then-part ; statement or block
2547 else-pos ; optional buffer position of 'else' keyword
2548 else-part ; optional statement or block
2549 lp ; position of left-paren, nil if omitted
2550 rp) ; position of right-paren, nil if omitted
2551
2552 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2553 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2554
2555 (defun js2-visit-if-node (n v)
2556 (js2-visit-ast (js2-if-node-condition n) v)
2557 (js2-visit-ast (js2-if-node-then-part n) v)
2558 (js2-visit-ast (js2-if-node-else-part n) v))
2559
2560 (defun js2-print-if-node (n i)
2561 (let ((pad (js2-make-pad i))
2562 (then-part (js2-if-node-then-part n))
2563 (else-part (js2-if-node-else-part n)))
2564 (insert pad "if (")
2565 (js2-print-ast (js2-if-node-condition n) 0)
2566 (insert ") {\n")
2567 (js2-print-body then-part (1+ i))
2568 (insert pad "}")
2569 (cond
2570 ((not else-part)
2571 (insert "\n"))
2572 ((js2-if-node-p else-part)
2573 (insert " else ")
2574 (js2-print-body else-part i))
2575 (t
2576 (insert " else {\n")
2577 (js2-print-body else-part (1+ i))
2578 (insert pad "}\n")))))
2579
2580 (defstruct (js2-try-node
2581 (:include js2-node)
2582 (:constructor nil)
2583 (:constructor make-js2-try-node (&key (type js2-TRY)
2584 (pos js2-ts-cursor)
2585 len
2586 try-block
2587 catch-clauses
2588 finally-block)))
2589 "AST node for a try-statement."
2590 try-block
2591 catch-clauses ; a Lisp list of `js2-catch-node'
2592 finally-block) ; a `js2-finally-node'
2593
2594 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2595 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2596
2597 (defun js2-visit-try-node (n v)
2598 (js2-visit-ast (js2-try-node-try-block n) v)
2599 (dolist (clause (js2-try-node-catch-clauses n))
2600 (js2-visit-ast clause v))
2601 (js2-visit-ast (js2-try-node-finally-block n) v))
2602
2603 (defun js2-print-try-node (n i)
2604 (let ((pad (js2-make-pad i))
2605 (catches (js2-try-node-catch-clauses n))
2606 (finally (js2-try-node-finally-block n)))
2607 (insert pad "try {\n")
2608 (js2-print-body (js2-try-node-try-block n) (1+ i))
2609 (insert pad "}")
2610 (when catches
2611 (dolist (catch catches)
2612 (js2-print-ast catch i)))
2613 (if finally
2614 (js2-print-ast finally i)
2615 (insert "\n"))))
2616
2617 (defstruct (js2-catch-node
2618 (:include js2-node)
2619 (:constructor nil)
2620 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2621 (pos js2-ts-cursor)
2622 len
2623 param
2624 guard-kwd
2625 guard-expr
2626 block lp
2627 rp)))
2628 "AST node for a catch clause."
2629 param ; destructuring form or simple name node
2630 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2631 guard-expr ; catch condition, a `js2-node'
2632 block ; statements, a `js2-block-node'
2633 lp ; buffer position of left-paren, nil if omitted
2634 rp) ; buffer position of right-paren, nil if omitted
2635
2636 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2637 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2638
2639 (defun js2-visit-catch-node (n v)
2640 (js2-visit-ast (js2-catch-node-param n) v)
2641 (when (js2-catch-node-guard-kwd n)
2642 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2643 (js2-visit-ast (js2-catch-node-block n) v))
2644
2645 (defun js2-print-catch-node (n i)
2646 (let ((pad (js2-make-pad i))
2647 (guard-kwd (js2-catch-node-guard-kwd n))
2648 (guard-expr (js2-catch-node-guard-expr n)))
2649 (insert " catch (")
2650 (js2-print-ast (js2-catch-node-param n) 0)
2651 (when guard-kwd
2652 (insert " if ")
2653 (js2-print-ast guard-expr 0))
2654 (insert ") {\n")
2655 (js2-print-body (js2-catch-node-block n) (1+ i))
2656 (insert pad "}")))
2657
2658 (defstruct (js2-finally-node
2659 (:include js2-node)
2660 (:constructor nil)
2661 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2662 (pos js2-ts-cursor)
2663 len body)))
2664 "AST node for a finally clause."
2665 body) ; a `js2-node', often but not always a block node
2666
2667 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2668 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2669
2670 (defun js2-visit-finally-node (n v)
2671 (js2-visit-ast (js2-finally-node-body n) v))
2672
2673 (defun js2-print-finally-node (n i)
2674 (let ((pad (js2-make-pad i)))
2675 (insert " finally {\n")
2676 (js2-print-body (js2-finally-node-body n) (1+ i))
2677 (insert pad "}\n")))
2678
2679 (defstruct (js2-switch-node
2680 (:include js2-node)
2681 (:constructor nil)
2682 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2683 (pos js2-ts-cursor)
2684 len
2685 discriminant
2686 cases lp
2687 rp)))
2688 "AST node for a switch statement."
2689 discriminant ; a `js2-node' (switch expression)
2690 cases ; a Lisp list of `js2-case-node'
2691 lp ; position of open-paren for discriminant, nil if omitted
2692 rp) ; position of close-paren for discriminant, nil if omitted
2693
2694 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2695 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2696
2697 (defun js2-visit-switch-node (n v)
2698 (js2-visit-ast (js2-switch-node-discriminant n) v)
2699 (dolist (c (js2-switch-node-cases n))
2700 (js2-visit-ast c v)))
2701
2702 (defun js2-print-switch-node (n i)
2703 (let ((pad (js2-make-pad i))
2704 (cases (js2-switch-node-cases n)))
2705 (insert pad "switch (")
2706 (js2-print-ast (js2-switch-node-discriminant n) 0)
2707 (insert ") {\n")
2708 (dolist (case cases)
2709 (js2-print-ast case i))
2710 (insert pad "}\n")))
2711
2712 (defstruct (js2-case-node
2713 (:include js2-block-node)
2714 (:constructor nil)
2715 (:constructor make-js2-case-node (&key (type js2-CASE)
2716 (pos js2-ts-cursor)
2717 len kids expr)))
2718 "AST node for a case clause of a switch statement."
2719 expr) ; the case expression (nil for default)
2720
2721 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2722 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2723
2724 (defun js2-visit-case-node (n v)
2725 (js2-visit-ast (js2-case-node-expr n) v)
2726 (js2-visit-block n v))
2727
2728 (defun js2-print-case-node (n i)
2729 (let ((pad (js2-make-pad i))
2730 (expr (js2-case-node-expr n)))
2731 (insert pad)
2732 (if (null expr)
2733 (insert "default:\n")
2734 (insert "case ")
2735 (js2-print-ast expr 0)
2736 (insert ":\n"))
2737 (dolist (kid (js2-case-node-kids n))
2738 (js2-print-ast kid (1+ i)))))
2739
2740 (defstruct (js2-throw-node
2741 (:include js2-node)
2742 (:constructor nil)
2743 (:constructor make-js2-throw-node (&key (type js2-THROW)
2744 (pos js2-ts-cursor)
2745 len expr)))
2746 "AST node for a throw statement."
2747 expr) ; the expression to throw
2748
2749 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2750 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2751
2752 (defun js2-visit-throw-node (n v)
2753 (js2-visit-ast (js2-throw-node-expr n) v))
2754
2755 (defun js2-print-throw-node (n i)
2756 (insert (js2-make-pad i) "throw ")
2757 (js2-print-ast (js2-throw-node-expr n) 0)
2758 (insert ";\n"))
2759
2760 (defstruct (js2-with-node
2761 (:include js2-node)
2762 (:constructor nil)
2763 (:constructor make-js2-with-node (&key (type js2-WITH)
2764 (pos js2-ts-cursor)
2765 len object
2766 body lp rp)))
2767 "AST node for a with-statement."
2768 object
2769 body
2770 lp ; buffer position of left-paren around object, nil if omitted
2771 rp) ; buffer position of right-paren around object, nil if omitted
2772
2773 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2774 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2775
2776 (defun js2-visit-with-node (n v)
2777 (js2-visit-ast (js2-with-node-object n) v)
2778 (js2-visit-ast (js2-with-node-body n) v))
2779
2780 (defun js2-print-with-node (n i)
2781 (let ((pad (js2-make-pad i)))
2782 (insert pad "with (")
2783 (js2-print-ast (js2-with-node-object n) 0)
2784 (insert ") {\n")
2785 (js2-print-body (js2-with-node-body n) (1+ i))
2786 (insert pad "}\n")))
2787
2788 (defstruct (js2-label-node
2789 (:include js2-node)
2790 (:constructor nil)
2791 (:constructor make-js2-label-node (&key (type js2-LABEL)
2792 (pos js2-ts-cursor)
2793 len name)))
2794 "AST node for a statement label or case label."
2795 name ; a string
2796 loop) ; for validating and code-generating continue-to-label
2797
2798 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2799 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2800
2801 (defun js2-print-label (n i)
2802 (insert (js2-make-pad i)
2803 (js2-label-node-name n)
2804 ":\n"))
2805
2806 (defstruct (js2-labeled-stmt-node
2807 (:include js2-node)
2808 (:constructor nil)
2809 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2810 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2811 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2812 (pos js2-ts-cursor)
2813 len labels stmt)))
2814 "AST node for a statement with one or more labels.
2815 Multiple labels for a statement are collapsed into the labels field."
2816 labels ; Lisp list of `js2-label-node'
2817 stmt) ; the statement these labels are for
2818
2819 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2820 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2821
2822 (defun js2-get-label-by-name (lbl-stmt name)
2823 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2824 Returns nil if no such label is in the list."
2825 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2826 result)
2827 (while (and label-list (not result))
2828 (if (string= (js2-label-node-name (car label-list)) name)
2829 (setq result (car label-list))
2830 (setq label-list (cdr label-list))))
2831 result))
2832
2833 (defun js2-visit-labeled-stmt (n v)
2834 (dolist (label (js2-labeled-stmt-node-labels n))
2835 (js2-visit-ast label v))
2836 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2837
2838 (defun js2-print-labeled-stmt (n i)
2839 (dolist (label (js2-labeled-stmt-node-labels n))
2840 (js2-print-ast label i))
2841 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2842
2843 (defun js2-labeled-stmt-node-contains (node label)
2844 "Return t if NODE contains LABEL in its label set.
2845 NODE is a `js2-labels-node'. LABEL is an identifier."
2846 (loop for nl in (js2-labeled-stmt-node-labels node)
2847 if (string= label (js2-label-node-name nl))
2848 return t
2849 finally return nil))
2850
2851 (defsubst js2-labeled-stmt-node-add-label (node label)
2852 "Add a `js2-label-node' to the label set for this statement."
2853 (setf (js2-labeled-stmt-node-labels node)
2854 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2855
2856 (defstruct (js2-jump-node
2857 (:include js2-node)
2858 (:constructor nil))
2859 "Abstract supertype of break and continue nodes."
2860 label ; `js2-name-node' for location of label identifier, if present
2861 target) ; target js2-labels-node or loop/switch statement
2862
2863 (defun js2-visit-jump-node (n v)
2864 ;; We don't visit the target, since it's a back-link.
2865 (js2-visit-ast (js2-jump-node-label n) v))
2866
2867 (defstruct (js2-break-node
2868 (:include js2-jump-node)
2869 (:constructor nil)
2870 (:constructor make-js2-break-node (&key (type js2-BREAK)
2871 (pos js2-ts-cursor)
2872 len label target)))
2873 "AST node for a break statement.
2874 The label field is a `js2-name-node', possibly nil, for the named label
2875 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2876 is the target of the break - a label node or enclosing loop/switch statement.")
2877
2878 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2879 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2880
2881 (defun js2-print-break-node (n i)
2882 (insert (js2-make-pad i) "break")
2883 (when (js2-break-node-label n)
2884 (insert " ")
2885 (js2-print-ast (js2-break-node-label n) 0))
2886 (insert ";\n"))
2887
2888 (defstruct (js2-continue-node
2889 (:include js2-jump-node)
2890 (:constructor nil)
2891 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2892 (pos js2-ts-cursor)
2893 len label target)))
2894 "AST node for a continue statement.
2895 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2896 It is nil if continue specifies no label. The target field is the jump target:
2897 a `js2-label-node' or the innermost enclosing loop.")
2898
2899 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2900 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2901
2902 (defun js2-print-continue-node (n i)
2903 (insert (js2-make-pad i) "continue")
2904 (when (js2-continue-node-label n)
2905 (insert " ")
2906 (js2-print-ast (js2-continue-node-label n) 0))
2907 (insert ";\n"))
2908
2909 (defstruct (js2-function-node
2910 (:include js2-script-node)
2911 (:constructor nil)
2912 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2913 (pos js2-ts-cursor)
2914 len
2915 (ftype 'FUNCTION)
2916 (form 'FUNCTION_STATEMENT)
2917 (name "")
2918 params rest-p
2919 body
2920 lp rp)))
2921 "AST node for a function declaration.
2922 The `params' field is a Lisp list of nodes. Each node is either a simple
2923 `js2-name-node', or if it's a destructuring-assignment parameter, a
2924 `js2-array-node' or `js2-object-node'."
2925 ftype ; FUNCTION, GETTER or SETTER
2926 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
2927 name ; function name (a `js2-name-node', or nil if anonymous)
2928 params ; a Lisp list of destructuring forms or simple name nodes
2929 rest-p ; if t, the last parameter is rest parameter
2930 body ; a `js2-block-node' or expression node (1.8 only)
2931 lp ; position of arg-list open-paren, or nil if omitted
2932 rp ; position of arg-list close-paren, or nil if omitted
2933 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2934 needs-activation ; t if we need an activation object for this frame
2935 is-generator ; t if this function contains a yield
2936 member-expr) ; nonstandard Ecma extension from Rhino
2937
2938 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2939 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2940
2941 (defun js2-visit-function-node (n v)
2942 (js2-visit-ast (js2-function-node-name n) v)
2943 (dolist (p (js2-function-node-params n))
2944 (js2-visit-ast p v))
2945 (js2-visit-ast (js2-function-node-body n) v))
2946
2947 (defun js2-print-function-node (n i)
2948 (let ((pad (js2-make-pad i))
2949 (getter (js2-node-get-prop n 'GETTER_SETTER))
2950 (name (js2-function-node-name n))
2951 (params (js2-function-node-params n))
2952 (rest-p (js2-function-node-rest-p n))
2953 (body (js2-function-node-body n))
2954 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
2955 (unless getter
2956 (insert pad "function"))
2957 (when name
2958 (insert " ")
2959 (js2-print-ast name 0))
2960 (insert "(")
2961 (loop with len = (length params)
2962 for param in params
2963 for count from 1
2964 do
2965 (when (and rest-p (= count len))
2966 (insert "..."))
2967 (js2-print-ast param 0)
2968 (when (< count len)
2969 (insert ", ")))
2970 (insert ") {")
2971 (unless expr
2972 (insert "\n"))
2973 ;; TODO: fix this to be smarter about indenting, etc.
2974 (js2-print-body body (1+ i))
2975 (insert pad "}")
2976 (unless expr
2977 (insert "\n"))))
2978
2979 (defun js2-function-name (node)
2980 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
2981 (and (js2-function-node-name node)
2982 (js2-name-node-name (js2-function-node-name node))))
2983
2984 ;; Having this be an expression node makes it more flexible.
2985 ;; There are IDE contexts, such as indentation in a for-loop initializer,
2986 ;; that work better if you assume it's an expression. Whenever we have
2987 ;; a standalone var/const declaration, we just wrap with an expr stmt.
2988 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
2989 (defstruct (js2-var-decl-node
2990 (:include js2-node)
2991 (:constructor nil)
2992 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
2993 (pos js2-token-beg)
2994 len kids
2995 decl-type)))
2996 "AST node for a variable declaration list (VAR, CONST or LET).
2997 The node bounds differ depending on the declaration type. For VAR or
2998 CONST declarations, the bounds include the var/const keyword. For LET
2999 declarations, the node begins at the position of the first child."
3000 kids ; a Lisp list of `js2-var-init-node' structs.
3001 decl-type) ; js2-VAR, js2-CONST or js2-LET
3002
3003 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3004 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3005
3006 (defun js2-visit-var-decl (n v)
3007 (dolist (kid (js2-var-decl-node-kids n))
3008 (js2-visit-ast kid v)))
3009
3010 (defun js2-print-var-decl (n i)
3011 (let ((pad (js2-make-pad i))
3012 (tt (js2-var-decl-node-decl-type n)))
3013 (insert pad)
3014 (insert (cond
3015 ((= tt js2-VAR) "var ")
3016 ((= tt js2-LET) "let ")
3017 ((= tt js2-CONST) "const ")
3018 (t
3019 (error "malformed var-decl node"))))
3020 (loop with kids = (js2-var-decl-node-kids n)
3021 with len = (length kids)
3022 for kid in kids
3023 for count from 1
3024 do
3025 (js2-print-ast kid 0)
3026 (if (< count len)
3027 (insert ", ")))))
3028
3029 (defstruct (js2-var-init-node
3030 (:include js2-node)
3031 (:constructor nil)
3032 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3033 (pos js2-ts-cursor)
3034 len target
3035 initializer)))
3036 "AST node for a variable declaration.
3037 The type field will be js2-CONST for a const decl."
3038 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3039 initializer) ; initializer expression, a `js2-node'
3040
3041 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3042 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3043
3044 (defun js2-visit-var-init-node (n v)
3045 (js2-visit-ast (js2-var-init-node-target n) v)
3046 (js2-visit-ast (js2-var-init-node-initializer n) v))
3047
3048 (defun js2-print-var-init-node (n i)
3049 (let ((pad (js2-make-pad i))
3050 (name (js2-var-init-node-target n))
3051 (init (js2-var-init-node-initializer n)))
3052 (insert pad)
3053 (js2-print-ast name 0)
3054 (when init
3055 (insert " = ")
3056 (js2-print-ast init 0))))
3057
3058 (defstruct (js2-cond-node
3059 (:include js2-node)
3060 (:constructor nil)
3061 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3062 (pos js2-ts-cursor)
3063 len
3064 test-expr
3065 true-expr
3066 false-expr
3067 q-pos c-pos)))
3068 "AST node for the ternary operator"
3069 test-expr
3070 true-expr
3071 false-expr
3072 q-pos ; buffer position of ?
3073 c-pos) ; buffer position of :
3074
3075 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3076 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3077
3078 (defun js2-visit-cond-node (n v)
3079 (js2-visit-ast (js2-cond-node-test-expr n) v)
3080 (js2-visit-ast (js2-cond-node-true-expr n) v)
3081 (js2-visit-ast (js2-cond-node-false-expr n) v))
3082
3083 (defun js2-print-cond-node (n i)
3084 (let ((pad (js2-make-pad i)))
3085 (insert pad)
3086 (js2-print-ast (js2-cond-node-test-expr n) 0)
3087 (insert " ? ")
3088 (js2-print-ast (js2-cond-node-true-expr n) 0)
3089 (insert " : ")
3090 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3091
3092 (defstruct (js2-infix-node
3093 (:include js2-node)
3094 (:constructor nil)
3095 (:constructor make-js2-infix-node (&key type
3096 (pos js2-ts-cursor)
3097 len op-pos
3098 left right)))
3099 "Represents infix expressions.
3100 Includes assignment ops like `|=', and the comma operator.
3101 The type field inherited from `js2-node' holds the operator."
3102 op-pos ; buffer position where operator begins
3103 left ; any `js2-node'
3104 right) ; any `js2-node'
3105
3106 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3107 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3108
3109 (defun js2-visit-infix-node (n v)
3110 (js2-visit-ast (js2-infix-node-left n) v)
3111 (js2-visit-ast (js2-infix-node-right n) v))
3112
3113 (defconst js2-operator-tokens
3114 (let ((table (make-hash-table :test 'eq))
3115 (tokens
3116 (list (cons js2-IN "in")
3117 (cons js2-TYPEOF "typeof")
3118 (cons js2-INSTANCEOF "instanceof")
3119 (cons js2-DELPROP "delete")
3120 (cons js2-COMMA ",")
3121 (cons js2-COLON ":")
3122 (cons js2-OR "||")
3123 (cons js2-AND "&&")
3124 (cons js2-INC "++")
3125 (cons js2-DEC "--")
3126 (cons js2-BITOR "|")
3127 (cons js2-BITXOR "^")
3128 (cons js2-BITAND "&")
3129 (cons js2-EQ "==")
3130 (cons js2-NE "!=")
3131 (cons js2-LT "<")
3132 (cons js2-LE "<=")
3133 (cons js2-GT ">")
3134 (cons js2-GE ">=")
3135 (cons js2-LSH "<<")
3136 (cons js2-RSH ">>")
3137 (cons js2-URSH ">>>")
3138 (cons js2-ADD "+") ; infix plus
3139 (cons js2-SUB "-") ; infix minus
3140 (cons js2-MUL "*")
3141 (cons js2-DIV "/")
3142 (cons js2-MOD "%")
3143 (cons js2-NOT "!")
3144 (cons js2-BITNOT "~")
3145 (cons js2-POS "+") ; unary plus
3146 (cons js2-NEG "-") ; unary minus
3147 (cons js2-SHEQ "===") ; shallow equality
3148 (cons js2-SHNE "!==") ; shallow inequality
3149 (cons js2-ASSIGN "=")
3150 (cons js2-ASSIGN_BITOR "|=")
3151 (cons js2-ASSIGN_BITXOR "^=")
3152 (cons js2-ASSIGN_BITAND "&=")
3153 (cons js2-ASSIGN_LSH "<<=")
3154 (cons js2-ASSIGN_RSH ">>=")
3155 (cons js2-ASSIGN_URSH ">>>=")
3156 (cons js2-ASSIGN_ADD "+=")
3157 (cons js2-ASSIGN_SUB "-=")
3158 (cons js2-ASSIGN_MUL "*=")
3159 (cons js2-ASSIGN_DIV "/=")
3160 (cons js2-ASSIGN_MOD "%="))))
3161 (loop for (k . v) in tokens do
3162 (puthash k v table))
3163 table))
3164
3165 (defun js2-print-infix-node (n i)
3166 (let* ((tt (js2-node-type n))
3167 (op (gethash tt js2-operator-tokens)))
3168 (unless op
3169 (error "unrecognized infix operator %s" (js2-node-type n)))
3170 (insert (js2-make-pad i))
3171 (js2-print-ast (js2-infix-node-left n) 0)
3172 (unless (= tt js2-COMMA)
3173 (insert " "))
3174 (insert op)
3175 (insert " ")
3176 (js2-print-ast (js2-infix-node-right n) 0)))
3177
3178 (defstruct (js2-assign-node
3179 (:include js2-infix-node)
3180 (:constructor nil)
3181 (:constructor make-js2-assign-node (&key type
3182 (pos js2-ts-cursor)
3183 len op-pos
3184 left right)))
3185 "Represents any assignment.
3186 The type field holds the actual assignment operator.")
3187
3188 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3189 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3190
3191 (defstruct (js2-unary-node
3192 (:include js2-node)
3193 (:constructor nil)
3194 (:constructor make-js2-unary-node (&key type ; required
3195 (pos js2-ts-cursor)
3196 len operand)))
3197 "AST node type for unary operator nodes.
3198 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3199 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3200 property is added if the operator follows the operand."
3201 operand) ; a `js2-node' expression
3202
3203 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3204 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3205
3206 (defun js2-visit-unary-node (n v)
3207 (js2-visit-ast (js2-unary-node-operand n) v))
3208
3209 (defun js2-print-unary-node (n i)
3210 (let* ((tt (js2-node-type n))
3211 (op (gethash tt js2-operator-tokens))
3212 (postfix (js2-node-get-prop n 'postfix)))
3213 (unless op
3214 (error "unrecognized unary operator %s" tt))
3215 (insert (js2-make-pad i))
3216 (unless postfix
3217 (insert op))
3218 (if (or (= tt js2-TYPEOF)
3219 (= tt js2-DELPROP))
3220 (insert " "))
3221 (js2-print-ast (js2-unary-node-operand n) 0)
3222 (when postfix
3223 (insert op))))
3224
3225 (defstruct (js2-let-node
3226 (:include js2-scope)
3227 (:constructor nil)
3228 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3229 (pos js2-token-beg)
3230 len vars body
3231 lp rp)))
3232 "AST node for a let expression or a let statement.
3233 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3234 vars ; a `js2-var-decl-node'
3235 body ; a `js2-node' representing the expression or body block
3236 lp
3237 rp)
3238
3239 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3240 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3241
3242 (defun js2-visit-let-node (n v)
3243 (js2-visit-ast (js2-let-node-vars n) v)
3244 (js2-visit-ast (js2-let-node-body n) v))
3245
3246 (defun js2-print-let-node (n i)
3247 (insert (js2-make-pad i) "let (")
3248 (js2-print-ast (js2-let-node-vars n) 0)
3249 (insert ") ")
3250 (js2-print-ast (js2-let-node-body n) i))
3251
3252 (defstruct (js2-keyword-node
3253 (:include js2-node)
3254 (:constructor nil)
3255 (:constructor make-js2-keyword-node (&key type
3256 (pos js2-token-beg)
3257 (len (- js2-ts-cursor pos)))))
3258 "AST node representing a literal keyword such as `null'.
3259 Used for `null', `this', `true', `false' and `debugger'.
3260 The node type is set to js2-NULL, js2-THIS, etc.")
3261
3262 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3263 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3264
3265 (defun js2-print-keyword-node (n i)
3266 (insert (js2-make-pad i)
3267 (let ((tt (js2-node-type n)))
3268 (cond
3269 ((= tt js2-THIS) "this")
3270 ((= tt js2-NULL) "null")
3271 ((= tt js2-TRUE) "true")
3272 ((= tt js2-FALSE) "false")
3273 ((= tt js2-DEBUGGER) "debugger")
3274 (t (error "Invalid keyword literal type: %d" tt))))))
3275
3276 (defsubst js2-this-node-p (node)
3277 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3278 (eq (js2-node-type node) js2-THIS))
3279
3280 (defstruct (js2-new-node
3281 (:include js2-node)
3282 (:constructor nil)
3283 (:constructor make-js2-new-node (&key (type js2-NEW)
3284 (pos js2-token-beg)
3285 len target
3286 args initializer
3287 lp rp)))
3288 "AST node for new-expression such as new Foo()."
3289 target ; an identifier or reference
3290 args ; a Lisp list of argument nodes
3291 lp ; position of left-paren, nil if omitted
3292 rp ; position of right-paren, nil if omitted
3293 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3294
3295 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3296 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3297
3298 (defun js2-visit-new-node (n v)
3299 (js2-visit-ast (js2-new-node-target n) v)
3300 (dolist (arg (js2-new-node-args n))
3301 (js2-visit-ast arg v))
3302 (js2-visit-ast (js2-new-node-initializer n) v))
3303
3304 (defun js2-print-new-node (n i)
3305 (insert (js2-make-pad i) "new ")
3306 (js2-print-ast (js2-new-node-target n))
3307 (insert "(")
3308 (js2-print-list (js2-new-node-args n))
3309 (insert ")")
3310 (when (js2-new-node-initializer n)
3311 (insert " ")
3312 (js2-print-ast (js2-new-node-initializer n))))
3313
3314 (defstruct (js2-name-node
3315 (:include js2-node)
3316 (:constructor nil)
3317 (:constructor make-js2-name-node (&key (type js2-NAME)
3318 (pos js2-token-beg)
3319 (len (- js2-ts-cursor
3320 js2-token-beg))
3321 (name js2-ts-string))))
3322 "AST node for a JavaScript identifier"
3323 name ; a string
3324 scope) ; a `js2-scope' (optional, used for codegen)
3325
3326 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3327 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3328
3329 (defun js2-print-name-node (n i)
3330 (insert (js2-make-pad i)
3331 (js2-name-node-name n)))
3332
3333 (defsubst js2-name-node-length (node)
3334 "Return identifier length of NODE, a `js2-name-node'.
3335 Returns 0 if NODE is nil or its identifier field is nil."
3336 (if node
3337 (length (js2-name-node-name node))
3338 0))
3339
3340 (defstruct (js2-number-node
3341 (:include js2-node)
3342 (:constructor nil)
3343 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3344 (pos js2-token-beg)
3345 (len (- js2-ts-cursor
3346 js2-token-beg))
3347 (value js2-ts-string)
3348 (num-value js2-ts-number))))
3349 "AST node for a number literal."
3350 value ; the original string, e.g. "6.02e23"
3351 num-value) ; the parsed number value
3352
3353 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3354 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3355
3356 (defun js2-print-number-node (n i)
3357 (insert (js2-make-pad i)
3358 (number-to-string (js2-number-node-num-value n))))
3359
3360 (defstruct (js2-regexp-node
3361 (:include js2-node)
3362 (:constructor nil)
3363 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3364 (pos js2-token-beg)
3365 (len (- js2-ts-cursor
3366 js2-token-beg))
3367 value flags)))
3368 "AST node for a regular expression literal."
3369 value ; the regexp string, without // delimiters
3370 flags) ; a string of flags, e.g. `mi'.
3371
3372 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3373 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3374
3375 (defun js2-print-regexp (n i)
3376 (insert (js2-make-pad i)
3377 "/"
3378 (js2-regexp-node-value n)
3379 "/")
3380 (if (js2-regexp-node-flags n)
3381 (insert (js2-regexp-node-flags n))))
3382
3383 (defstruct (js2-string-node
3384 (:include js2-node)
3385 (:constructor nil)
3386 (:constructor make-js2-string-node (&key (type js2-STRING)
3387 (pos js2-token-beg)
3388 (len (- js2-ts-cursor
3389 js2-token-beg))
3390 (value js2-ts-string))))
3391 "String literal.
3392 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3393 You can tell the quote type by looking at the first character."
3394 value) ; the characters of the string, including the quotes
3395
3396 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3397 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3398
3399 (defun js2-print-string-node (n i)
3400 (insert (js2-make-pad i)
3401 (js2-node-string n)))
3402
3403 (defstruct (js2-array-node
3404 (:include js2-node)
3405 (:constructor nil)
3406 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3407 (pos js2-ts-cursor)
3408 len elems)))
3409 "AST node for an array literal."
3410 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3411
3412 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3413 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3414
3415 (defun js2-visit-array-node (n v)
3416 (dolist (e (js2-array-node-elems n))
3417 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3418
3419 (defun js2-print-array-node (n i)
3420 (insert (js2-make-pad i) "[")
3421 (js2-print-list (js2-array-node-elems n))
3422 (insert "]"))
3423
3424 (defstruct (js2-object-node
3425 (:include js2-node)
3426 (:constructor nil)
3427 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3428 (pos js2-ts-cursor)
3429 len
3430 elems)))
3431 "AST node for an object literal expression.
3432 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3433 The latter represents abbreviation in destructuring expressions."
3434 elems)
3435
3436 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3437 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3438
3439 (defun js2-visit-object-node (n v)
3440 (dolist (e (js2-object-node-elems n))
3441 (js2-visit-ast e v)))
3442
3443 (defun js2-print-object-node (n i)
3444 (insert (js2-make-pad i) "{")
3445 (js2-print-list (js2-object-node-elems n))
3446 (insert "}"))
3447
3448 (defstruct (js2-object-prop-node
3449 (:include js2-infix-node)
3450 (:constructor nil)
3451 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3452 (pos js2-ts-cursor)
3453 len left
3454 right op-pos)))
3455 "AST node for an object literal prop:value entry.
3456 The `left' field is the property: a name node, string node or number node.
3457 The `right' field is a `js2-node' representing the initializer value.")
3458
3459 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3460 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3461
3462 (defun js2-print-object-prop-node (n i)
3463 (insert (js2-make-pad i))
3464 (js2-print-ast (js2-object-prop-node-left n) 0)
3465 (insert ": ")
3466 (js2-print-ast (js2-object-prop-node-right n) 0))
3467
3468 (defstruct (js2-getter-setter-node
3469 (:include js2-infix-node)
3470 (:constructor nil)
3471 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3472 (pos js2-ts-cursor)
3473 len left right)))
3474 "AST node for a getter/setter property in an object literal.
3475 The `left' field is the `js2-name-node' naming the getter/setter prop.
3476 The `right' field is always an anonymous `js2-function-node' with a node
3477 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3478
3479 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3480 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3481
3482 (defun js2-print-getter-setter (n i)
3483 (let ((pad (js2-make-pad i))
3484 (left (js2-getter-setter-node-left n))
3485 (right (js2-getter-setter-node-right n)))
3486 (insert pad)
3487 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3488 (js2-print-ast left 0)
3489 (js2-print-ast right 0)))
3490
3491 (defstruct (js2-prop-get-node
3492 (:include js2-infix-node)
3493 (:constructor nil)
3494 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3495 (pos js2-ts-cursor)
3496 len left right)))
3497 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3498
3499 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3500 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3501
3502 (defun js2-visit-prop-get-node (n v)
3503 (js2-visit-ast (js2-prop-get-node-left n) v)
3504 (js2-visit-ast (js2-prop-get-node-right n) v))
3505
3506 (defun js2-print-prop-get-node (n i)
3507 (insert (js2-make-pad i))
3508 (js2-print-ast (js2-prop-get-node-left n) 0)
3509 (insert ".")
3510 (js2-print-ast (js2-prop-get-node-right n) 0))
3511
3512 (defstruct (js2-elem-get-node
3513 (:include js2-node)
3514 (:constructor nil)
3515 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3516 (pos js2-ts-cursor)
3517 len target element
3518 lb rb)))
3519 "AST node for an array index expression such as foo[bar]."
3520 target ; a `js2-node' - the expression preceding the "."
3521 element ; a `js2-node' - the expression in brackets
3522 lb ; position of left-bracket, nil if omitted
3523 rb) ; position of right-bracket, nil if omitted
3524
3525 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3526 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3527
3528 (defun js2-visit-elem-get-node (n v)
3529 (js2-visit-ast (js2-elem-get-node-target n) v)
3530 (js2-visit-ast (js2-elem-get-node-element n) v))
3531
3532 (defun js2-print-elem-get-node (n i)
3533 (insert (js2-make-pad i))
3534 (js2-print-ast (js2-elem-get-node-target n) 0)
3535 (insert "[")
3536 (js2-print-ast (js2-elem-get-node-element n) 0)
3537 (insert "]"))
3538
3539 (defstruct (js2-call-node
3540 (:include js2-node)
3541 (:constructor nil)
3542 (:constructor make-js2-call-node (&key (type js2-CALL)
3543 (pos js2-ts-cursor)
3544 len target args
3545 lp rp)))
3546 "AST node for a JavaScript function call."
3547 target ; a `js2-node' evaluating to the function to call
3548 args ; a Lisp list of `js2-node' arguments
3549 lp ; position of open-paren, or nil if missing
3550 rp) ; position of close-paren, or nil if missing
3551
3552 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3553 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3554
3555 (defun js2-visit-call-node (n v)
3556 (js2-visit-ast (js2-call-node-target n) v)
3557 (dolist (arg (js2-call-node-args n))
3558 (js2-visit-ast arg v)))
3559
3560 (defun js2-print-call-node (n i)
3561 (insert (js2-make-pad i))
3562 (js2-print-ast (js2-call-node-target n) 0)
3563 (insert "(")
3564 (js2-print-list (js2-call-node-args n))
3565 (insert ")"))
3566
3567 (defstruct (js2-yield-node
3568 (:include js2-node)
3569 (:constructor nil)
3570 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3571 (pos js2-ts-cursor)
3572 len value)))
3573 "AST node for yield statement or expression."
3574 value) ; optional: value to be yielded
3575
3576 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3577 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3578
3579 (defun js2-visit-yield-node (n v)
3580 (js2-visit-ast (js2-yield-node-value n) v))
3581
3582 (defun js2-print-yield-node (n i)
3583 (insert (js2-make-pad i))
3584 (insert "yield")
3585 (when (js2-yield-node-value n)
3586 (insert " ")
3587 (js2-print-ast (js2-yield-node-value n) 0)))
3588
3589 (defstruct (js2-paren-node
3590 (:include js2-node)
3591 (:constructor nil)
3592 (:constructor make-js2-paren-node (&key (type js2-LP)
3593 (pos js2-ts-cursor)
3594 len expr)))
3595 "AST node for a parenthesized expression.
3596 In particular, used when the parens are syntactically optional,
3597 as opposed to required parens such as those enclosing an if-conditional."
3598 expr) ; `js2-node'
3599
3600 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3601 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3602
3603 (defun js2-visit-paren-node (n v)
3604 (js2-visit-ast (js2-paren-node-expr n) v))
3605
3606 (defun js2-print-paren-node (n i)
3607 (insert (js2-make-pad i))
3608 (insert "(")
3609 (js2-print-ast (js2-paren-node-expr n) 0)
3610 (insert ")"))
3611
3612 (defstruct (js2-array-comp-node
3613 (:include js2-scope)
3614 (:constructor nil)
3615 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3616 (pos js2-ts-cursor)
3617 len result
3618 loops filter
3619 if-pos lp rp)))
3620 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3621 result ; result expression (just after left-bracket)
3622 loops ; a Lisp list of `js2-array-comp-loop-node'
3623 filter ; guard/filter expression
3624 if-pos ; buffer pos of 'if' keyword, if present, else nil
3625 lp ; buffer position of if-guard left-paren, or nil if not present
3626 rp) ; buffer position of if-guard right-paren, or nil if not present
3627
3628 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3629 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3630
3631 (defun js2-visit-array-comp-node (n v)
3632 (js2-visit-ast (js2-array-comp-node-result n) v)
3633 (dolist (l (js2-array-comp-node-loops n))
3634 (js2-visit-ast l v))
3635 (js2-visit-ast (js2-array-comp-node-filter n) v))
3636
3637 (defun js2-print-array-comp-node (n i)
3638 (let ((pad (js2-make-pad i))
3639 (result (js2-array-comp-node-result n))
3640 (loops (js2-array-comp-node-loops n))
3641 (filter (js2-array-comp-node-filter n)))
3642 (insert pad "[")
3643 (js2-print-ast result 0)
3644 (dolist (l loops)
3645 (insert " ")
3646 (js2-print-ast l 0))
3647 (when filter
3648 (insert " if (")
3649 (js2-print-ast filter 0)
3650 (insert ")"))
3651 (insert "]")))
3652
3653 (defstruct (js2-array-comp-loop-node
3654 (:include js2-for-in-node)
3655 (:constructor nil)
3656 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3657 (pos js2-ts-cursor)
3658 len iterator
3659 object in-pos
3660 foreach-p
3661 each-pos
3662 forof-p
3663 lp rp)))
3664 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3665
3666 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3667 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3668
3669 (defun js2-visit-array-comp-loop (n v)
3670 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3671 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3672
3673 (defun js2-print-array-comp-loop (n i)
3674 (insert "for ")
3675 (when (js2-array-comp-loop-node-foreach-p n) (insert "each "))
3676 (insert "(")
3677 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3678 (if (js2-array-comp-loop-node-forof-p n)
3679 (insert " of ")
3680 (insert " in "))
3681 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3682 (insert ")"))
3683
3684 (defstruct (js2-empty-expr-node
3685 (:include js2-node)
3686 (:constructor nil)
3687 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3688 (pos js2-token-beg)
3689 len)))
3690 "AST node for an empty expression.")
3691
3692 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3693 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3694
3695 (defstruct (js2-xml-node
3696 (:include js2-block-node)
3697 (:constructor nil)
3698 (:constructor make-js2-xml-node (&key (type js2-XML)
3699 (pos js2-token-beg)
3700 len kids)))
3701 "AST node for initial parse of E4X literals.
3702 The kids field is a list of XML fragments, each a `js2-string-node' or
3703 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3704
3705 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3706 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3707
3708 (defun js2-print-xml-node (n i)
3709 (dolist (kid (js2-xml-node-kids n))
3710 (js2-print-ast kid i)))
3711
3712 (defstruct (js2-xml-js-expr-node
3713 (:include js2-xml-node)
3714 (:constructor nil)
3715 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3716 (pos js2-ts-cursor)
3717 len expr)))
3718 "AST node for an embedded JavaScript {expression} in an E4X literal.
3719 The start and end fields correspond to the curly-braces."
3720 expr) ; a `js2-expr-node' of some sort
3721
3722 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3723 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3724
3725 (defun js2-visit-xml-js-expr (n v)
3726 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3727
3728 (defun js2-print-xml-js-expr (n i)
3729 (insert (js2-make-pad i))
3730 (insert "{")
3731 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3732 (insert "}"))
3733
3734 (defstruct (js2-xml-dot-query-node
3735 (:include js2-infix-node)
3736 (:constructor nil)
3737 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3738 (pos js2-ts-cursor)
3739 op-pos len left
3740 right rp)))
3741 "AST node for an E4X foo.(bar) filter expression.
3742 Note that the left-paren is automatically the character immediately
3743 following the dot (.) in the operator. No whitespace is permitted
3744 between the dot and the lp by the scanner."
3745 rp)
3746
3747 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3748 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3749
3750 (defun js2-print-xml-dot-query (n i)
3751 (insert (js2-make-pad i))
3752 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3753 (insert ".(")
3754 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3755 (insert ")"))
3756
3757 (defstruct (js2-xml-ref-node
3758 (:include js2-node)
3759 (:constructor nil)) ; abstract
3760 "Base type for E4X XML attribute-access or property-get expressions.
3761 Such expressions can take a variety of forms. The general syntax has
3762 three parts:
3763
3764 - (optional) an @ (specifying an attribute access)
3765 - (optional) a namespace (a `js2-name-node') and double-colon
3766 - (required) either a `js2-name-node' or a bracketed [expression]
3767
3768 The property-name expressions (examples: ns::name, @name) are
3769 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3770 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3771
3772 This node type (or more specifically, its subclasses) will sometimes
3773 be the right-hand child of a `js2-prop-get-node' or a
3774 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3775 The `js2-xml-ref-node' may also be a standalone primary expression with
3776 no explicit target, which is valid in certain expression contexts such as
3777
3778 company..employee.(@id < 100)
3779
3780 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3781 expression whose parent is a `js2-xml-dot-query-node'."
3782 namespace
3783 at-pos
3784 colon-pos)
3785
3786 (defsubst js2-xml-ref-node-attr-access-p (node)
3787 "Return non-nil if this expression began with an @-token."
3788 (and (numberp (js2-xml-ref-node-at-pos node))
3789 (plusp (js2-xml-ref-node-at-pos node))))
3790
3791 (defstruct (js2-xml-prop-ref-node
3792 (:include js2-xml-ref-node)
3793 (:constructor nil)
3794 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3795 (pos js2-token-beg)
3796 len propname
3797 namespace at-pos
3798 colon-pos)))
3799 "AST node for an E4X XML [expr] property-ref expression.
3800 The JavaScript syntax is an optional @, an optional ns::, and a name.
3801
3802 [ '@' ] [ name '::' ] name
3803
3804 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3805 @ns::*, @*::attr, @*::*, and @*.
3806
3807 The node starts at the @ token, if present. Otherwise it starts at the
3808 namespace name. The node bounds extend through the closing right-bracket,
3809 or if it is missing due to a syntax error, through the end of the index
3810 expression."
3811 propname)
3812
3813 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3814 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3815
3816 (defun js2-visit-xml-prop-ref-node (n v)
3817 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3818 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3819
3820 (defun js2-print-xml-prop-ref-node (n i)
3821 (insert (js2-make-pad i))
3822 (if (js2-xml-ref-node-attr-access-p n)
3823 (insert "@"))
3824 (when (js2-xml-prop-ref-node-namespace n)
3825 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3826 (insert "::"))
3827 (if (js2-xml-prop-ref-node-propname n)
3828 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3829
3830 (defstruct (js2-xml-elem-ref-node
3831 (:include js2-xml-ref-node)
3832 (:constructor nil)
3833 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3834 (pos js2-token-beg)
3835 len expr lb rb
3836 namespace at-pos
3837 colon-pos)))
3838 "AST node for an E4X XML [expr] member-ref expression.
3839 Syntax:
3840
3841 [ '@' ] [ name '::' ] '[' expr ']'
3842
3843 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3844
3845 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3846 is not a legal E4X XML element-ref expression, since it's already used
3847 for standard JavaScript element-get array indexing. Hence, a
3848 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3849 non-nil namespace node, or both.
3850
3851 The node starts at the @ token, if present. Otherwise it starts
3852 at the namespace name. The node bounds extend through the closing
3853 right-bracket, or if it is missing due to a syntax error, through the
3854 end of the index expression."
3855 expr ; the bracketed index expression
3856 lb
3857 rb)
3858
3859 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3860 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3861
3862 (defun js2-visit-xml-elem-ref-node (n v)
3863 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3864 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3865
3866 (defun js2-print-xml-elem-ref-node (n i)
3867 (insert (js2-make-pad i))
3868 (if (js2-xml-ref-node-attr-access-p n)
3869 (insert "@"))
3870 (when (js2-xml-elem-ref-node-namespace n)
3871 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3872 (insert "::"))
3873 (insert "[")
3874 (if (js2-xml-elem-ref-node-expr n)
3875 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3876 (insert "]"))
3877
3878 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3879
3880 (defstruct (js2-xml-start-tag-node
3881 (:include js2-xml-node)
3882 (:constructor nil)
3883 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3884 (pos js2-ts-cursor)
3885 len name attrs kids
3886 empty-p)))
3887 "AST node for an XML start-tag. Not currently used.
3888 The `kids' field is a Lisp list of child content nodes."
3889 name ; a `js2-xml-name-node'
3890 attrs ; a Lisp list of `js2-xml-attr-node'
3891 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3892
3893 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3894 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3895
3896 (defun js2-visit-xml-start-tag (n v)
3897 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3898 (dolist (attr (js2-xml-start-tag-node-attrs n))
3899 (js2-visit-ast attr v))
3900 (js2-visit-block n v))
3901
3902 (defun js2-print-xml-start-tag (n i)
3903 (insert (js2-make-pad i) "<")
3904 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3905 (when (js2-xml-start-tag-node-attrs n)
3906 (insert " ")
3907 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3908 (insert ">"))
3909
3910 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3911 ;; and add the end-tag to the kids list of the parent as well.
3912 (defstruct (js2-xml-end-tag-node
3913 (:include js2-xml-node)
3914 (:constructor nil)
3915 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
3916 (pos js2-ts-cursor)
3917 len name)))
3918 "AST node for an XML end-tag. Not currently used."
3919 name) ; a `js2-xml-name-node'
3920
3921 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
3922 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
3923
3924 (defun js2-visit-xml-end-tag (n v)
3925 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
3926
3927 (defun js2-print-xml-end-tag (n i)
3928 (insert (js2-make-pad i))
3929 (insert "</")
3930 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
3931 (insert ">"))
3932
3933 (defstruct (js2-xml-name-node
3934 (:include js2-xml-node)
3935 (:constructor nil)
3936 (:constructor make-js2-xml-name-node (&key (type js2-XML)
3937 (pos js2-ts-cursor)
3938 len namespace kids)))
3939 "AST node for an E4X XML name. Not currently used.
3940 Any XML name can be qualified with a namespace, hence the namespace field.
3941 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
3942 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
3943 For a simple name, the kids list has exactly one node, a `js2-name-node'."
3944 namespace) ; a `js2-string-node'
3945
3946 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
3947 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
3948
3949 (defun js2-visit-xml-name-node (n v)
3950 (js2-visit-ast (js2-xml-name-node-namespace n) v))
3951
3952 (defun js2-print-xml-name-node (n i)
3953 (insert (js2-make-pad i))
3954 (when (js2-xml-name-node-namespace n)
3955 (js2-print-ast (js2-xml-name-node-namespace n) 0)
3956 (insert "::"))
3957 (dolist (kid (js2-xml-name-node-kids n))
3958 (js2-print-ast kid 0)))
3959
3960 (defstruct (js2-xml-pi-node
3961 (:include js2-xml-node)
3962 (:constructor nil)
3963 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
3964 (pos js2-ts-cursor)
3965 len name attrs)))
3966 "AST node for an E4X XML processing instruction. Not currently used."
3967 name ; a `js2-xml-name-node'
3968 attrs) ; a list of `js2-xml-attr-node'
3969
3970 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
3971 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
3972
3973 (defun js2-visit-xml-pi-node (n v)
3974 (js2-visit-ast (js2-xml-pi-node-name n) v)
3975 (dolist (attr (js2-xml-pi-node-attrs n))
3976 (js2-visit-ast attr v)))
3977
3978 (defun js2-print-xml-pi-node (n i)
3979 (insert (js2-make-pad i) "<?")
3980 (js2-print-ast (js2-xml-pi-node-name n))
3981 (when (js2-xml-pi-node-attrs n)
3982 (insert " ")
3983 (js2-print-list (js2-xml-pi-node-attrs n)))
3984 (insert "?>"))
3985
3986 (defstruct (js2-xml-cdata-node
3987 (:include js2-xml-node)
3988 (:constructor nil)
3989 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
3990 (pos js2-ts-cursor)
3991 len content)))
3992 "AST node for a CDATA escape section. Not currently used."
3993 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
3994
3995 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
3996 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
3997
3998 (defun js2-visit-xml-cdata-node (n v)
3999 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4000
4001 (defun js2-print-xml-cdata-node (n i)
4002 (insert (js2-make-pad i))
4003 (js2-print-ast (js2-xml-cdata-node-content n)))
4004
4005 (defstruct (js2-xml-attr-node
4006 (:include js2-xml-node)
4007 (:constructor nil)
4008 (:constructor make-js2-attr-node (&key (type js2-XML)
4009 (pos js2-ts-cursor)
4010 len name value
4011 eq-pos quote-type)))
4012 "AST node representing a foo='bar' XML attribute value. Not yet used."
4013 name ; a `js2-xml-name-node'
4014 value ; a `js2-xml-name-node'
4015 eq-pos ; buffer position of "=" sign
4016 quote-type) ; 'single or 'double
4017
4018 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4019 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4020
4021 (defun js2-visit-xml-attr-node (n v)
4022 (js2-visit-ast (js2-xml-attr-node-name n) v)
4023 (js2-visit-ast (js2-xml-attr-node-value n) v))
4024
4025 (defun js2-print-xml-attr-node (n i)
4026 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4027 "'"
4028 "\"")))
4029 (insert (js2-make-pad i))
4030 (js2-print-ast (js2-xml-attr-node-name n) 0)
4031 (insert "=" quote)
4032 (js2-print-ast (js2-xml-attr-node-value n) 0)
4033 (insert quote)))
4034
4035 (defstruct (js2-xml-text-node
4036 (:include js2-xml-node)
4037 (:constructor nil)
4038 (:constructor make-js2-text-node (&key (type js2-XML)
4039 (pos js2-ts-cursor)
4040 len content)))
4041 "AST node for an E4X XML text node. Not currently used."
4042 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4043
4044 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4045 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4046
4047 (defun js2-visit-xml-text-node (n v)
4048 (js2-visit-ast (js2-xml-text-node-content n) v))
4049
4050 (defun js2-print-xml-text-node (n i)
4051 (insert (js2-make-pad i))
4052 (dolist (kid (js2-xml-text-node-content n))
4053 (js2-print-ast kid)))
4054
4055 (defstruct (js2-xml-comment-node
4056 (:include js2-xml-node)
4057 (:constructor nil)
4058 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4059 (pos js2-ts-cursor)
4060 len)))
4061 "AST node for E4X XML comment. Not currently used.")
4062
4063 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4064 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4065
4066 (defun js2-print-xml-comment (n i)
4067 (insert (js2-make-pad i)
4068 (js2-node-string n)))
4069
4070 ;;; Node utilities
4071
4072 (defsubst js2-node-line (n)
4073 "Fetch the source line number at the start of node N.
4074 This is O(n) in the length of the source buffer; use prudently."
4075 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4076
4077 (defsubst js2-block-node-kid (n i)
4078 "Return child I of node N, or nil if there aren't that many."
4079 (nth i (js2-block-node-kids n)))
4080
4081 (defsubst js2-block-node-first (n)
4082 "Return first child of block node N, or nil if there is none."
4083 (first (js2-block-node-kids n)))
4084
4085 (defun js2-node-root (n)
4086 "Return the root of the AST containing N.
4087 If N has no parent pointer, returns N."
4088 (let ((parent (js2-node-parent n)))
4089 (if parent
4090 (js2-node-root parent)
4091 n)))
4092
4093 (defsubst js2-node-short-name (n)
4094 "Return the short name of node N as a string, e.g. `js2-if-node'."
4095 (substring (symbol-name (aref n 0))
4096 (length "cl-struct-")))
4097
4098 (defun js2-node-child-list (node)
4099 "Return the child list for NODE, a Lisp list of nodes.
4100 Works for block nodes, array nodes, obj literals, funarg lists,
4101 var decls and try nodes (for catch clauses). Note that you should call
4102 `js2-block-node-kids' on the function body for the body statements.
4103 Returns nil for zero-length child lists or unsupported nodes."
4104 (cond
4105 ((js2-function-node-p node)
4106 (js2-function-node-params node))
4107 ((js2-block-node-p node)
4108 (js2-block-node-kids node))
4109 ((js2-try-node-p node)
4110 (js2-try-node-catch-clauses node))
4111 ((js2-array-node-p node)
4112 (js2-array-node-elems node))
4113 ((js2-object-node-p node)
4114 (js2-object-node-elems node))
4115 ((js2-call-node-p node)
4116 (js2-call-node-args node))
4117 ((js2-new-node-p node)
4118 (js2-new-node-args node))
4119 ((js2-var-decl-node-p node)
4120 (js2-var-decl-node-kids node))
4121 (t
4122 nil)))
4123
4124 (defun js2-node-set-child-list (node kids)
4125 "Set the child list for NODE to KIDS."
4126 (cond
4127 ((js2-function-node-p node)
4128 (setf (js2-function-node-params node) kids))
4129 ((js2-block-node-p node)
4130 (setf (js2-block-node-kids node) kids))
4131 ((js2-try-node-p node)
4132 (setf (js2-try-node-catch-clauses node) kids))
4133 ((js2-array-node-p node)
4134 (setf (js2-array-node-elems node) kids))
4135 ((js2-object-node-p node)
4136 (setf (js2-object-node-elems node) kids))
4137 ((js2-call-node-p node)
4138 (setf (js2-call-node-args node) kids))
4139 ((js2-new-node-p node)
4140 (setf (js2-new-node-args node) kids))
4141 ((js2-var-decl-node-p node)
4142 (setf (js2-var-decl-node-kids node) kids))
4143 (t
4144 (error "Unsupported node type: %s" (js2-node-short-name node))))
4145 kids)
4146
4147 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4148 (defconst js2-paren-expr-nodes
4149 '(cl-struct-js2-array-comp-loop-node
4150 cl-struct-js2-array-comp-node
4151 cl-struct-js2-call-node
4152 cl-struct-js2-catch-node
4153 cl-struct-js2-do-node
4154 cl-struct-js2-elem-get-node
4155 cl-struct-js2-for-in-node
4156 cl-struct-js2-for-node
4157 cl-struct-js2-function-node
4158 cl-struct-js2-if-node
4159 cl-struct-js2-let-node
4160 cl-struct-js2-new-node
4161 cl-struct-js2-paren-node
4162 cl-struct-js2-switch-node
4163 cl-struct-js2-while-node
4164 cl-struct-js2-with-node
4165 cl-struct-js2-xml-dot-query-node)
4166 "Node types that can have a parenthesized child expression.
4167 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4168
4169 (defsubst js2-paren-expr-node-p (node)
4170 "Return t for nodes that typically have a parenthesized child expression.
4171 Useful for computing the indentation anchors for arg-lists and conditions.
4172 Note that it may return a false positive, for instance when NODE is
4173 a `js2-new-node' and there are no arguments or parentheses."
4174 (memq (aref node 0) js2-paren-expr-nodes))
4175
4176 ;; Fake polymorphism... yech.
4177 (defun js2-node-lp (node)
4178 "Return relative left-paren position for NODE, if applicable.
4179 For `js2-elem-get-node' structs, returns left-bracket position.
4180 Note that the position may be nil in the case of a parse error."
4181 (cond
4182 ((js2-elem-get-node-p node)
4183 (js2-elem-get-node-lb node))
4184 ((js2-loop-node-p node)
4185 (js2-loop-node-lp node))
4186 ((js2-function-node-p node)
4187 (js2-function-node-lp node))
4188 ((js2-if-node-p node)
4189 (js2-if-node-lp node))
4190 ((js2-new-node-p node)
4191 (js2-new-node-lp node))
4192 ((js2-call-node-p node)
4193 (js2-call-node-lp node))
4194 ((js2-paren-node-p node)
4195 0)
4196 ((js2-switch-node-p node)
4197 (js2-switch-node-lp node))
4198 ((js2-catch-node-p node)
4199 (js2-catch-node-lp node))
4200 ((js2-let-node-p node)
4201 (js2-let-node-lp node))
4202 ((js2-array-comp-node-p node)
4203 (js2-array-comp-node-lp node))
4204 ((js2-with-node-p node)
4205 (js2-with-node-lp node))
4206 ((js2-xml-dot-query-node-p node)
4207 (1+ (js2-infix-node-op-pos node)))
4208 (t
4209 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4210
4211 ;; Fake polymorphism... blech.
4212 (defun js2-node-rp (node)
4213 "Return relative right-paren position for NODE, if applicable.
4214 For `js2-elem-get-node' structs, returns right-bracket position.
4215 Note that the position may be nil in the case of a parse error."
4216 (cond
4217 ((js2-elem-get-node-p node)
4218 (js2-elem-get-node-rb node))
4219 ((js2-loop-node-p node)
4220 (js2-loop-node-rp node))
4221 ((js2-function-node-p node)
4222 (js2-function-node-rp node))
4223 ((js2-if-node-p node)
4224 (js2-if-node-rp node))
4225 ((js2-new-node-p node)
4226 (js2-new-node-rp node))
4227 ((js2-call-node-p node)
4228 (js2-call-node-rp node))
4229 ((js2-paren-node-p node)
4230 (1- (js2-node-len node)))
4231 ((js2-switch-node-p node)
4232 (js2-switch-node-rp node))
4233 ((js2-catch-node-p node)
4234 (js2-catch-node-rp node))
4235 ((js2-let-node-p node)
4236 (js2-let-node-rp node))
4237 ((js2-array-comp-node-p node)
4238 (js2-array-comp-node-rp node))
4239 ((js2-with-node-p node)
4240 (js2-with-node-rp node))
4241 ((js2-xml-dot-query-node-p node)
4242 (1+ (js2-xml-dot-query-node-rp node)))
4243 (t
4244 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4245
4246 (defsubst js2-node-first-child (node)
4247 "Return the first element of `js2-node-child-list' for NODE."
4248 (car (js2-node-child-list node)))
4249
4250 (defsubst js2-node-last-child (node)
4251 "Return the last element of `js2-node-last-child' for NODE."
4252 (car (last (js2-node-child-list node))))
4253
4254 (defun js2-node-prev-sibling (node)
4255 "Return the previous statement in parent.
4256 Works for parents supported by `js2-node-child-list'.
4257 Returns nil if NODE is not in the parent, or PARENT is
4258 not a supported node, or if NODE is the first child."
4259 (let* ((p (js2-node-parent node))
4260 (kids (js2-node-child-list p))
4261 (sib (car kids)))
4262 (while (and kids
4263 (not (eq node (cadr kids))))
4264 (setq kids (cdr kids)
4265 sib (car kids)))
4266 sib))
4267
4268 (defun js2-node-next-sibling (node)
4269 "Return the next statement in parent block.
4270 Returns nil if NODE is not in the block, or PARENT is not
4271 a block node, or if NODE is the last statement."
4272 (let* ((p (js2-node-parent node))
4273 (kids (js2-node-child-list p)))
4274 (while (and kids
4275 (not (eq node (car kids))))
4276 (setq kids (cdr kids)))
4277 (cadr kids)))
4278
4279 (defun js2-node-find-child-before (pos parent &optional after)
4280 "Find the last child that starts before POS in parent.
4281 If AFTER is non-nil, returns first child starting after POS.
4282 POS is an absolute buffer position. PARENT is any node
4283 supported by `js2-node-child-list'.
4284 Returns nil if no applicable child is found."
4285 (let ((kids (if (js2-function-node-p parent)
4286 (js2-block-node-kids (js2-function-node-body parent))
4287 (js2-node-child-list parent)))
4288 (beg (if (js2-function-node-p parent)
4289 (js2-node-abs-pos (js2-function-node-body parent))
4290 (js2-node-abs-pos parent)))
4291 kid result fn
4292 (continue t))
4293 (setq fn (if after '>= '<))
4294 (while (and kids continue)
4295 (setq kid (car kids))
4296 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4297 (setq result kid
4298 continue (if after nil t))
4299 (setq continue (if after t nil)))
4300 (setq kids (cdr kids)))
4301 result))
4302
4303 (defun js2-node-find-child-after (pos parent)
4304 "Find first child that starts after POS in parent.
4305 POS is an absolute buffer position. PARENT is any node
4306 supported by `js2-node-child-list'.
4307 Returns nil if no applicable child is found."
4308 (js2-node-find-child-before pos parent 'after))
4309
4310 (defun js2-node-replace-child (pos parent new-node)
4311 "Replace node at index POS in PARENT with NEW-NODE.
4312 Only works for parents supported by `js2-node-child-list'."
4313 (let ((kids (js2-node-child-list parent))
4314 (i 0))
4315 (while (< i pos)
4316 (setq kids (cdr kids)
4317 i (1+ i)))
4318 (setcar kids new-node)
4319 (js2-node-add-children parent new-node)))
4320
4321 (defun js2-node-buffer (n)
4322 "Return the buffer associated with AST N.
4323 Returns nil if the buffer is not set as a property on the root
4324 node, or if parent links were not recorded during parsing."
4325 (let ((root (js2-node-root n)))
4326 (and root
4327 (js2-ast-root-p root)
4328 (js2-ast-root-buffer root))))
4329
4330 (defun js2-block-node-push (n kid)
4331 "Push js2-node KID onto the end of js2-block-node N's child list.
4332 KID is always added to the -end- of the kids list.
4333 Function also calls `js2-node-add-children' to add the parent link."
4334 (let ((kids (js2-node-child-list n)))
4335 (if kids
4336 (setcdr kids (nconc (cdr kids) (list kid)))
4337 (js2-node-set-child-list n (list kid)))
4338 (js2-node-add-children n kid)))
4339
4340 (defun js2-node-string (node)
4341 (with-current-buffer (or (js2-node-buffer node)
4342 (error "No buffer available for node %s" node))
4343 (let ((pos (js2-node-abs-pos node)))
4344 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4345
4346 ;; Container for storing the node we're looking for in a traversal.
4347 (js2-deflocal js2-discovered-node nil)
4348
4349 ;; Keep track of absolute node position during traversals.
4350 (js2-deflocal js2-visitor-offset nil)
4351
4352 (js2-deflocal js2-node-search-point nil)
4353
4354 (when js2-mode-dev-mode-p
4355 (defun js2-find-node-at-point ()
4356 (interactive)
4357 (let ((node (js2-node-at-point)))
4358 (message "%s" (or node "No node found at point"))))
4359 (defun js2-node-name-at-point ()
4360 (interactive)
4361 (let ((node (js2-node-at-point)))
4362 (message "%s" (if node
4363 (js2-node-short-name node)
4364 "No node found at point.")))))
4365
4366 (defun js2-node-at-point (&optional pos skip-comments)
4367 "Return AST node at POS, a buffer position, defaulting to current point.
4368 The `js2-mode-ast' variable must be set to the current parse tree.
4369 Signals an error if the AST (`js2-mode-ast') is nil.
4370 Always returns a node - if it can't find one, it returns the root.
4371 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4372 (let ((ast js2-mode-ast)
4373 result)
4374 (unless ast
4375 (error "No JavaScript AST available"))
4376 ;; Look through comments first, since they may be inside nodes that
4377 ;; would otherwise report a match.
4378 (setq pos (or pos (point))
4379 result (if (> pos (js2-node-abs-end ast))
4380 ast
4381 (if (not skip-comments)
4382 (js2-comment-at-point pos))))
4383 (unless result
4384 (setq js2-discovered-node nil
4385 js2-visitor-offset 0
4386 js2-node-search-point pos)
4387 (unwind-protect
4388 (catch 'js2-visit-done
4389 (js2-visit-ast ast #'js2-node-at-point-visitor))
4390 (setq js2-visitor-offset nil
4391 js2-node-search-point nil))
4392 (setq result js2-discovered-node))
4393 ;; may have found a comment beyond end of last child node,
4394 ;; since visiting the ast-root looks at the comment-list last.
4395 (if (and skip-comments
4396 (js2-comment-node-p result))
4397 (setq result nil))
4398 (or result js2-mode-ast)))
4399
4400 (defun js2-node-at-point-visitor (node end-p)
4401 (let ((rel-pos (js2-node-pos node))
4402 abs-pos
4403 abs-end
4404 (point js2-node-search-point))
4405 (cond
4406 (end-p
4407 ;; this evaluates to a non-nil return value, even if it's zero
4408 (decf js2-visitor-offset rel-pos))
4409 ;; we already looked for comments before visiting, and don't want them now
4410 ((js2-comment-node-p node)
4411 nil)
4412 (t
4413 (setq abs-pos (incf js2-visitor-offset rel-pos)
4414 ;; we only want to use the node if the point is before
4415 ;; the last character position in the node, so we decrement
4416 ;; the absolute end by 1.
4417 abs-end (+ abs-pos (js2-node-len node) -1))
4418 (cond
4419 ;; If this node starts after search-point, stop the search.
4420 ((> abs-pos point)
4421 (throw 'js2-visit-done nil))
4422 ;; If this node ends before the search-point, don't check kids.
4423 ((> point abs-end)
4424 nil)
4425 (t
4426 ;; Otherwise point is within this node, possibly in a child.
4427 (setq js2-discovered-node node)
4428 t)))))) ; keep processing kids to look for more specific match
4429
4430 (defsubst js2-block-comment-p (node)
4431 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4432 (and (js2-comment-node-p node)
4433 (memq (js2-comment-node-format node) '(jsdoc block))))
4434
4435 ;; TODO: put the comments in a vector and binary-search them instead
4436 (defun js2-comment-at-point (&optional pos)
4437 "Look through scanned comment nodes for one containing POS.
4438 POS is a buffer position that defaults to current point.
4439 Function returns nil if POS was not in any comment node."
4440 (let ((ast js2-mode-ast)
4441 (x (or pos (point)))
4442 beg end)
4443 (unless ast
4444 (error "No JavaScript AST available"))
4445 (catch 'done
4446 ;; Comments are stored in lexical order.
4447 (dolist (comment (js2-ast-root-comments ast) nil)
4448 (setq beg (js2-node-abs-pos comment)
4449 end (+ beg (js2-node-len comment)))
4450 (if (and (>= x beg)
4451 (<= x end))
4452 (throw 'done comment))))))
4453
4454 (defun js2-mode-find-parent-fn (node)
4455 "Find function enclosing NODE.
4456 Returns nil if NODE is not inside a function."
4457 (setq node (js2-node-parent node))
4458 (while (and node (not (js2-function-node-p node)))
4459 (setq node (js2-node-parent node)))
4460 (and (js2-function-node-p node) node))
4461
4462 (defun js2-mode-find-enclosing-fn (node)
4463 "Find function or root enclosing NODE."
4464 (if (js2-ast-root-p node)
4465 node
4466 (setq node (js2-node-parent node))
4467 (while (not (or (js2-ast-root-p node)
4468 (js2-function-node-p node)))
4469 (setq node (js2-node-parent node)))
4470 node))
4471
4472 (defun js2-mode-find-enclosing-node (beg end)
4473 "Find script or function fully enclosing BEG and END."
4474 (let ((node (js2-node-at-point beg))
4475 pos
4476 (continue t))
4477 (while continue
4478 (if (or (js2-ast-root-p node)
4479 (and (js2-function-node-p node)
4480 (<= (setq pos (js2-node-abs-pos node)) beg)
4481 (>= (+ pos (js2-node-len node)) end)))
4482 (setq continue nil)
4483 (setq node (js2-node-parent node))))
4484 node))
4485
4486 (defun js2-node-parent-script-or-fn (node)
4487 "Find script or function immediately enclosing NODE.
4488 If NODE is the ast-root, returns nil."
4489 (if (js2-ast-root-p node)
4490 nil
4491 (setq node (js2-node-parent node))
4492 (while (and node (not (or (js2-function-node-p node)
4493 (js2-script-node-p node))))
4494 (setq node (js2-node-parent node)))
4495 node))
4496
4497 (defun js2-node-is-descendant (node ancestor)
4498 "Return t if NODE is a descendant of ANCESTOR."
4499 (while (and node
4500 (not (eq node ancestor)))
4501 (setq node (js2-node-parent node)))
4502 node)
4503
4504 ;;; visitor infrastructure
4505
4506 (defun js2-visit-none (node callback)
4507 "Visitor for AST node that have no node children."
4508 nil)
4509
4510 (defun js2-print-none (node indent)
4511 "Visitor for AST node with no printed representation.")
4512
4513 (defun js2-print-body (node indent)
4514 "Print a statement, or a block without braces."
4515 (if (js2-block-node-p node)
4516 (dolist (kid (js2-block-node-kids node))
4517 (js2-print-ast kid indent))
4518 (js2-print-ast node indent)))
4519
4520 (defun js2-print-list (args &optional delimiter)
4521 (loop with len = (length args)
4522 for arg in args
4523 for count from 1
4524 do
4525 (when arg (js2-print-ast arg 0))
4526 (if (< count len)
4527 (insert (or delimiter ", ")))))
4528
4529 (defun js2-print-tree (ast)
4530 "Prints an AST to the current buffer.
4531 Makes `js2-ast-parent-nodes' available to the printer functions."
4532 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4533 (js2-print-ast ast)))
4534
4535 (defun js2-print-ast (node &optional indent)
4536 "Helper function for printing AST nodes.
4537 Requires `js2-ast-parent-nodes' to be non-nil.
4538 You should use `js2-print-tree' instead of this function."
4539 (let ((printer (get (aref node 0) 'js2-printer))
4540 (i (or indent 0))
4541 (pos (js2-node-abs-pos node)))
4542 ;; TODO: wedge comments in here somewhere
4543 (if printer
4544 (funcall printer node i))))
4545
4546 (defconst js2-side-effecting-tokens
4547 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4548 (dolist (tt (list js2-ASSIGN
4549 js2-ASSIGN_ADD
4550 js2-ASSIGN_BITAND
4551 js2-ASSIGN_BITOR
4552 js2-ASSIGN_BITXOR
4553 js2-ASSIGN_DIV
4554 js2-ASSIGN_LSH
4555 js2-ASSIGN_MOD
4556 js2-ASSIGN_MUL
4557 js2-ASSIGN_RSH
4558 js2-ASSIGN_SUB
4559 js2-ASSIGN_URSH
4560 js2-BLOCK
4561 js2-BREAK
4562 js2-CALL
4563 js2-CATCH
4564 js2-CATCH_SCOPE
4565 js2-CONST
4566 js2-CONTINUE
4567 js2-DEBUGGER
4568 js2-DEC
4569 js2-DELPROP
4570 js2-DEL_REF
4571 js2-DO
4572 js2-ELSE
4573 js2-EMPTY
4574 js2-ENTERWITH
4575 js2-EXPORT
4576 js2-EXPR_RESULT
4577 js2-FINALLY
4578 js2-FOR
4579 js2-FUNCTION
4580 js2-GOTO
4581 js2-IF
4582 js2-IFEQ
4583 js2-IFNE
4584 js2-IMPORT
4585 js2-INC
4586 js2-JSR
4587 js2-LABEL
4588 js2-LEAVEWITH
4589 js2-LET
4590 js2-LETEXPR
4591 js2-LOCAL_BLOCK
4592 js2-LOOP
4593 js2-NEW
4594 js2-REF_CALL
4595 js2-RETHROW
4596 js2-RETURN
4597 js2-RETURN_RESULT
4598 js2-SEMI
4599 js2-SETELEM
4600 js2-SETELEM_OP
4601 js2-SETNAME
4602 js2-SETPROP
4603 js2-SETPROP_OP
4604 js2-SETVAR
4605 js2-SET_REF
4606 js2-SET_REF_OP
4607 js2-SWITCH
4608 js2-TARGET
4609 js2-THROW
4610 js2-TRY
4611 js2-VAR
4612 js2-WHILE
4613 js2-WITH
4614 js2-WITHEXPR
4615 js2-YIELD))
4616 (aset tokens tt t))
4617 (if js2-instanceof-has-side-effects
4618 (aset tokens js2-INSTANCEOF t))
4619 tokens))
4620
4621 (defun js2-node-has-side-effects (node)
4622 "Return t if NODE has side effects."
4623 (when node ; makes it easier to handle malformed expressions
4624 (let ((tt (js2-node-type node)))
4625 (cond
4626 ;; This doubtless needs some work, since EXPR_VOID is used
4627 ;; in several ways in Rhino and I may not have caught them all.
4628 ;; I'll wait for people to notice incorrect warnings.
4629 ((and (= tt js2-EXPR_VOID)
4630 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4631 (let ((expr (js2-expr-stmt-node-expr node)))
4632 (or (js2-node-has-side-effects expr)
4633 (when (js2-string-node-p expr)
4634 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4635 ((= tt js2-COMMA)
4636 (js2-node-has-side-effects (js2-infix-node-right node)))
4637 ((or (= tt js2-AND)
4638 (= tt js2-OR))
4639 (or (js2-node-has-side-effects (js2-infix-node-right node))
4640 (js2-node-has-side-effects (js2-infix-node-left node))))
4641 ((= tt js2-HOOK)
4642 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4643 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4644 ((js2-paren-node-p node)
4645 (js2-node-has-side-effects (js2-paren-node-expr node)))
4646 ((= tt js2-ERROR) ; avoid cascaded error messages
4647 nil)
4648 (t
4649 (aref js2-side-effecting-tokens tt))))))
4650
4651 (defconst js2-stmt-node-types
4652 (list js2-BLOCK
4653 js2-BREAK
4654 js2-CONTINUE
4655 js2-DEFAULT ; e4x "default xml namespace" statement
4656 js2-DO
4657 js2-EXPR_RESULT
4658 js2-EXPR_VOID
4659 js2-FOR
4660 js2-IF
4661 js2-RETURN
4662 js2-SWITCH
4663 js2-THROW
4664 js2-TRY
4665 js2-WHILE
4666 js2-WITH)
4667 "Node types that only appear in statement contexts.
4668 The list does not include nodes that always appear as the child
4669 of another specific statement type, such as switch-cases,
4670 catch and finally blocks, and else-clauses. The list also excludes
4671 nodes like yield, let and var, which may appear in either expression
4672 or statement context, and in the latter context always have a
4673 `js2-expr-stmt-node' parent. Finally, the list does not include
4674 functions or scripts, which are treated separately from statements
4675 by the JavaScript parser and runtime.")
4676
4677 (defun js2-stmt-node-p (node)
4678 "Heuristic for figuring out if NODE is a statement.
4679 Some node types can appear in either an expression context or a
4680 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4681 For these node types in a statement context, the parent will be a
4682 `js2-expr-stmt-node'.
4683 Functions aren't included in the check."
4684 (memq (js2-node-type node) js2-stmt-node-types))
4685
4686 (defun js2-mode-find-first-stmt (node)
4687 "Search upward starting from NODE looking for a statement.
4688 For purposes of this function, a `js2-function-node' counts."
4689 (while (not (or (js2-stmt-node-p node)
4690 (js2-function-node-p node)))
4691 (setq node (js2-node-parent node)))
4692 node)
4693
4694 (defun js2-node-parent-stmt (node)
4695 "Return the node's first ancestor that is a statement.
4696 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4697 appearing in a statement context will have a parent that is a
4698 `js2-expr-stmt-node' that will be returned by this function."
4699 (let ((parent (js2-node-parent node)))
4700 (if (or (null parent)
4701 (js2-stmt-node-p parent)
4702 (and (js2-function-node-p parent)
4703 (not (eq (js2-function-node-form parent)
4704 'FUNCTION_EXPRESSION))))
4705 parent
4706 (js2-node-parent-stmt parent))))
4707
4708 ;; In the Mozilla Rhino sources, Roshan James writes:
4709 ;; Does consistent-return analysis on the function body when strict mode is
4710 ;; enabled.
4711 ;;
4712 ;; function (x) { return (x+1) }
4713 ;;
4714 ;; is ok, but
4715 ;;
4716 ;; function (x) { if (x < 0) return (x+1); }
4717 ;;
4718 ;; is not because the function can potentially return a value when the
4719 ;; condition is satisfied and if not, the function does not explicitly
4720 ;; return a value.
4721 ;;
4722 ;; This extends to checking mismatches such as "return" and "return <value>"
4723 ;; used in the same function. Warnings are not emitted if inconsistent
4724 ;; returns exist in code that can be statically shown to be unreachable.
4725 ;; Ex.
4726 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4727 ;;
4728 ;; emits no warning. However if the loop had a break statement, then a
4729 ;; warning would be emitted.
4730 ;;
4731 ;; The consistency analysis looks at control structures such as loops, ifs,
4732 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4733 ;; warns the user about an inconsistent set of termination possibilities.
4734 ;;
4735 ;; These flags enumerate the possible ways a statement/function can
4736 ;; terminate. These flags are used by endCheck() and by the Parser to
4737 ;; detect inconsistent return usage.
4738 ;;
4739 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4740 ;; able to execute (example: throw, continue)
4741 ;;
4742 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4743 ;; next one. Statement such as return dont. A compound statement may have
4744 ;; some branch that drops off control to the next statement.
4745 ;;
4746 ;; END_RETURNS indicates that the statement can return with no value.
4747 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4748 ;;
4749 ;; A compound statement such as
4750 ;; if (condition) {
4751 ;; return value;
4752 ;; }
4753 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4754
4755 (defconst js2-END_UNREACHED 0)
4756 (defconst js2-END_DROPS_OFF 1)
4757 (defconst js2-END_RETURNS 2)
4758 (defconst js2-END_RETURNS_VALUE 4)
4759 (defconst js2-END_YIELDS 8)
4760
4761 (defun js2-has-consistent-return-usage (node)
4762 "Check that every return usage in a function body is consistent.
4763 Returns t if the function satisfies strict mode requirement."
4764 (let ((n (js2-end-check node)))
4765 ;; either it doesn't return a value in any branch...
4766 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4767 ;; or it returns a value (or is unreached) at every branch
4768 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4769 js2-END_RETURNS
4770 js2-END_YIELDS)))))
4771
4772 (defun js2-end-check-if (node)
4773 "Ensure that return usage in then/else blocks is consistent.
4774 If there is no else block, then the return statement can fall through.
4775 Returns logical OR of END_* flags"
4776 (let ((th (js2-if-node-then-part node))
4777 (el (js2-if-node-else-part node)))
4778 (if (null th)
4779 js2-END_UNREACHED
4780 (logior (js2-end-check th) (if el
4781 (js2-end-check el)
4782 js2-END_DROPS_OFF)))))
4783
4784 (defun js2-end-check-switch (node)
4785 "Consistency of return statements is checked between the case statements.
4786 If there is no default, then the switch can fall through. If there is a
4787 default, we check to see if all code paths in the default return or if
4788 there is a code path that can fall through.
4789 Returns logical OR of END_* flags."
4790 (let ((rv js2-END_UNREACHED)
4791 default-case)
4792 ;; examine the cases
4793 (catch 'break
4794 (dolist (c (js2-switch-node-cases node))
4795 (if (js2-case-node-expr c)
4796 (js2-set-flag rv (js2-end-check-block c))
4797 (setq default-case c)
4798 (throw 'break nil))))
4799 ;; we don't care how the cases drop into each other
4800 (js2-clear-flag rv js2-END_DROPS_OFF)
4801 ;; examine the default
4802 (js2-set-flag rv (if default-case
4803 (js2-end-check default-case)
4804 js2-END_DROPS_OFF))
4805 rv))
4806
4807 (defun js2-end-check-try (node)
4808 "If the block has a finally, return consistency is checked in the
4809 finally block. If all code paths in the finally return, then the
4810 returns in the try-catch blocks don't matter. If there is a code path
4811 that does not return or if there is no finally block, the returns
4812 of the try and catch blocks are checked for mismatch.
4813 Returns logical OR of END_* flags."
4814 (let ((finally (js2-try-node-finally-block node))
4815 rv)
4816 ;; check the finally if it exists
4817 (setq rv (if finally
4818 (js2-end-check (js2-finally-node-body finally))
4819 js2-END_DROPS_OFF))
4820 ;; If the finally block always returns, then none of the returns
4821 ;; in the try or catch blocks matter.
4822 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4823 (js2-clear-flag rv js2-END_DROPS_OFF)
4824 ;; examine the try block
4825 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4826 ;; check each catch block
4827 (dolist (cb (js2-try-node-catch-clauses node))
4828 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4829 rv))
4830
4831 (defun js2-end-check-loop (node)
4832 "Return statement in the loop body must be consistent.
4833 The default assumption for any kind of a loop is that it will eventually
4834 terminate. The only exception is a loop with a constant true condition.
4835 Code that follows such a loop is examined only if one can determine
4836 statically that there is a break out of the loop.
4837
4838 for(... ; ... ; ...) {}
4839 for(... in ... ) {}
4840 while(...) { }
4841 do { } while(...)
4842
4843 Returns logical OR of END_* flags."
4844 (let ((rv (js2-end-check (js2-loop-node-body node)))
4845 (condition (cond
4846 ((js2-while-node-p node)
4847 (js2-while-node-condition node))
4848 ((js2-do-node-p node)
4849 (js2-do-node-condition node))
4850 ((js2-for-node-p node)
4851 (js2-for-node-condition node)))))
4852
4853 ;; check to see if the loop condition is always true
4854 (if (and condition
4855 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4856 (js2-clear-flag rv js2-END_DROPS_OFF))
4857
4858 ;; look for effect of breaks
4859 (js2-set-flag rv (js2-node-get-prop node
4860 'CONTROL_BLOCK_PROP
4861 js2-END_UNREACHED))
4862 rv))
4863
4864 (defun js2-end-check-block (node)
4865 "A general block of code is examined statement by statement.
4866 If any statement (even a compound one) returns in all branches, then
4867 subsequent statements are not examined.
4868 Returns logical OR of END_* flags."
4869 (let* ((rv js2-END_DROPS_OFF)
4870 (kids (js2-block-node-kids node))
4871 (n (car kids)))
4872 ;; Check each statment. If the statement can continue onto the next
4873 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4874 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4875 (js2-clear-flag rv js2-END_DROPS_OFF)
4876 (js2-set-flag rv (js2-end-check n))
4877 (setq kids (cdr kids)
4878 n (car kids)))
4879 rv))
4880
4881 (defun js2-end-check-label (node)
4882 "A labeled statement implies that there may be a break to the label.
4883 The function processes the labeled statement and then checks the
4884 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4885 particular label.
4886 Returns logical OR of END_* flags."
4887 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4888 (logior rv (js2-node-get-prop node
4889 'CONTROL_BLOCK_PROP
4890 js2-END_UNREACHED))))
4891
4892 (defun js2-end-check-break (node)
4893 "When a break is encountered annotate the statement being broken
4894 out of by setting its CONTROL_BLOCK_PROP property.
4895 Returns logical OR of END_* flags."
4896 (and (js2-break-node-target node)
4897 (js2-node-set-prop (js2-break-node-target node)
4898 'CONTROL_BLOCK_PROP
4899 js2-END_DROPS_OFF))
4900 js2-END_UNREACHED)
4901
4902 (defun js2-end-check (node)
4903 "Examine the body of a function, doing a basic reachability analysis.
4904 Returns a combination of flags END_* flags that indicate
4905 how the function execution can terminate. These constitute only the
4906 pessimistic set of termination conditions. It is possible that at
4907 runtime certain code paths will never be actually taken. Hence this
4908 analysis will flag errors in cases where there may not be errors.
4909 Returns logical OR of END_* flags"
4910 (let (kid)
4911 (cond
4912 ((js2-break-node-p node)
4913 (js2-end-check-break node))
4914 ((js2-expr-stmt-node-p node)
4915 (if (setq kid (js2-expr-stmt-node-expr node))
4916 (js2-end-check kid)
4917 js2-END_DROPS_OFF))
4918 ((or (js2-continue-node-p node)
4919 (js2-throw-node-p node))
4920 js2-END_UNREACHED)
4921 ((js2-return-node-p node)
4922 (if (setq kid (js2-return-node-retval node))
4923 js2-END_RETURNS_VALUE
4924 js2-END_RETURNS))
4925 ((js2-loop-node-p node)
4926 (js2-end-check-loop node))
4927 ((js2-switch-node-p node)
4928 (js2-end-check-switch node))
4929 ((js2-labeled-stmt-node-p node)
4930 (js2-end-check-label node))
4931 ((js2-if-node-p node)
4932 (js2-end-check-if node))
4933 ((js2-try-node-p node)
4934 (js2-end-check-try node))
4935 ((js2-block-node-p node)
4936 (if (null (js2-block-node-kids node))
4937 js2-END_DROPS_OFF
4938 (js2-end-check-block node)))
4939 ((js2-yield-node-p node)
4940 js2-END_YIELDS)
4941 (t
4942 js2-END_DROPS_OFF))))
4943
4944 (defun js2-always-defined-boolean-p (node)
4945 "Check if NODE always evaluates to true or false in boolean context.
4946 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
4947 nor always false."
4948 (let ((tt (js2-node-type node))
4949 num)
4950 (cond
4951 ((or (= tt js2-FALSE) (= tt js2-NULL))
4952 'ALWAYS_FALSE)
4953 ((= tt js2-TRUE)
4954 'ALWAYS_TRUE)
4955 ((= tt js2-NUMBER)
4956 (setq num (js2-number-node-num-value node))
4957 (if (and (not (eq num 0.0e+NaN))
4958 (not (zerop num)))
4959 'ALWAYS_TRUE
4960 'ALWAYS_FALSE))
4961 (t
4962 nil))))
4963
4964 ;;; Scanner -- a port of Mozilla Rhino's lexer.
4965 ;; Corresponds to Rhino files Token.java and TokenStream.java.
4966
4967 (defvar js2-tokens nil
4968 "List of all defined token names.") ; initialized in `js2-token-names'
4969
4970 (defconst js2-token-names
4971 (let* ((names (make-vector js2-num-tokens -1))
4972 (case-fold-search nil) ; only match js2-UPPER_CASE
4973 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
4974 (loop for sym in syms
4975 for i from 0
4976 do
4977 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
4978 (not (boundp sym)))
4979 (aset names (symbol-value sym) ; code, e.g. 152
4980 (downcase
4981 (substring (symbol-name sym) 4))) ; name, e.g. "let"
4982 (push sym js2-tokens)))
4983 names)
4984 "Vector mapping int values to token string names, sans `js2-' prefix.")
4985
4986 (defun js2-token-name (tok)
4987 "Return a string name for TOK, a token symbol or code.
4988 Signals an error if it's not a recognized token."
4989 (let ((code tok))
4990 (if (symbolp tok)
4991 (setq code (symbol-value tok)))
4992 (if (eq code -1)
4993 "ERROR"
4994 (if (and (numberp code)
4995 (not (minusp code))
4996 (< code js2-num-tokens))
4997 (aref js2-token-names code)
4998 (error "Invalid token: %s" code)))))
4999
5000 (defsubst js2-token-sym (tok)
5001 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5002 (intern (js2-token-name tok)))
5003
5004 (defconst js2-token-codes
5005 (let ((table (make-hash-table :test 'eq :size 256)))
5006 (loop for name across js2-token-names
5007 for sym = (intern (concat "js2-" (upcase name)))
5008 do
5009 (puthash sym (symbol-value sym) table))
5010 ;; clean up a few that are "wrong" in Rhino's token codes
5011 (puthash 'js2-DELETE js2-DELPROP table)
5012 table)
5013 "Hashtable mapping token symbols to their bytecodes.")
5014
5015 (defsubst js2-token-code (sym)
5016 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5017 (or (gethash sym js2-token-codes)
5018 (error "Invalid token symbol: %s " sym))) ; signal code bug
5019
5020 (defun js2-report-scan-error (msg &optional no-throw beg len)
5021 (setq js2-token-end js2-ts-cursor)
5022 (js2-report-error msg nil
5023 (or beg js2-token-beg)
5024 (or len (- js2-token-end js2-token-beg)))
5025 (unless no-throw
5026 (throw 'return js2-ERROR)))
5027
5028 (defun js2-get-string-from-buffer ()
5029 "Reverse the char accumulator and return it as a string."
5030 (setq js2-token-end js2-ts-cursor)
5031 (if js2-ts-string-buffer
5032 (apply #'string (nreverse js2-ts-string-buffer))
5033 ""))
5034
5035 ;; TODO: could potentially avoid a lot of consing by allocating a
5036 ;; char buffer the way Rhino does.
5037 (defsubst js2-add-to-string (c)
5038 (push c js2-ts-string-buffer))
5039
5040 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5041 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5042 ;; any other character: when it's not part of the current token, we
5043 ;; unget it, allowing it to be read again by the following call.
5044 (defsubst js2-unget-char ()
5045 (decf js2-ts-cursor))
5046
5047 ;; Rhino distinguishes \r and \n line endings. We don't need to
5048 ;; because we only scan from Emacs buffers, which always use \n.
5049 (defun js2-get-char ()
5050 "Read and return the next character from the input buffer.
5051 Increments `js2-ts-lineno' if the return value is a newline char.
5052 Updates `js2-ts-cursor' to the point after the returned char.
5053 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5054 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5055 (let (c)
5056 ;; check for end of buffer
5057 (if (>= js2-ts-cursor (point-max))
5058 (setq js2-ts-hit-eof t
5059 js2-ts-cursor (1+ js2-ts-cursor)
5060 c js2-EOF_CHAR) ; return value
5061 ;; otherwise read next char
5062 (setq c (char-before (incf js2-ts-cursor)))
5063 ;; if we read a newline, update counters
5064 (if (= c ?\n)
5065 (setq js2-ts-line-start js2-ts-cursor
5066 js2-ts-lineno (1+ js2-ts-lineno)))
5067 ;; TODO: skip over format characters
5068 c)))
5069
5070 (defun js2-read-unicode-escape ()
5071 "Read a \\uNNNN sequence from the input.
5072 Assumes the ?\ and ?u have already been read.
5073 Returns the unicode character, or nil if it wasn't a valid character.
5074 Doesn't change the values of any scanner variables."
5075 ;; I really wish I knew a better way to do this, but I can't
5076 ;; find the Emacs function that takes a 16-bit int and converts
5077 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5078 ;; Have to first check that it's 4 hex characters or it may stop
5079 ;; the read early.
5080 (ignore-errors
5081 (let ((s (buffer-substring-no-properties js2-ts-cursor
5082 (+ 4 js2-ts-cursor))))
5083 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5084 (read (concat "?\\u" s))))))
5085
5086 (defun js2-match-char (test)
5087 "Consume and return next character if it matches TEST, a character.
5088 Returns nil and consumes nothing if TEST is not the next character."
5089 (let ((c (js2-get-char)))
5090 (if (eq c test)
5091 t
5092 (js2-unget-char)
5093 nil)))
5094
5095 (defun js2-peek-char ()
5096 (prog1
5097 (js2-get-char)
5098 (js2-unget-char)))
5099
5100 (defun js2-java-identifier-start-p (c)
5101 (or
5102 (memq c '(?$ ?_))
5103 (js2-char-uppercase-p c)
5104 (js2-char-lowercase-p c)))
5105
5106 (defun js2-java-identifier-part-p (c)
5107 "Implementation of java.lang.Character.isJavaIdentifierPart()."
5108 ;; TODO: make me Unicode-friendly. See comments above.
5109 (or
5110 (memq c '(?$ ?_))
5111 (js2-char-uppercase-p c)
5112 (js2-char-lowercase-p c)
5113 (and (>= c ?0) (<= c ?9))))
5114
5115 (defun js2-alpha-p (c)
5116 (cond ((and (<= ?A c) (<= c ?Z)) t)
5117 ((and (<= ?a c) (<= c ?z)) t)
5118 (t nil)))
5119
5120 (defsubst js2-digit-p (c)
5121 (and (<= ?0 c) (<= c ?9)))
5122
5123 (defun js2-js-space-p (c)
5124 (if (<= c 127)
5125 (memq c '(#x20 #x9 #xB #xC #xD))
5126 (or
5127 (eq c #xA0)
5128 ;; TODO: change this nil to check for Unicode space character
5129 nil)))
5130
5131 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5132
5133 (defun js2-skip-line ()
5134 "Skip to end of line."
5135 (let (c)
5136 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5137 (js2-unget-char)
5138 (setq js2-token-end js2-ts-cursor)))
5139
5140 (defun js2-init-scanner (&optional buf line)
5141 "Create token stream for BUF starting on LINE.
5142 BUF defaults to `current-buffer' and LINE defaults to 1.
5143
5144 A buffer can only have one scanner active at a time, which yields
5145 dramatically simpler code than using a defstruct. If you need to
5146 have simultaneous scanners in a buffer, copy the regions to scan
5147 into temp buffers."
5148 (with-current-buffer (or buf (current-buffer))
5149 (setq js2-ts-dirty-line nil
5150 js2-ts-regexp-flags nil
5151 js2-ts-string ""
5152 js2-ts-number nil
5153 js2-ts-hit-eof nil
5154 js2-ts-line-start 0
5155 js2-ts-lineno (or line 1)
5156 js2-ts-line-end-char -1
5157 js2-ts-cursor (point-min)
5158 js2-ts-is-xml-attribute nil
5159 js2-ts-xml-is-tag-content nil
5160 js2-ts-xml-open-tags-count 0
5161 js2-ts-string-buffer nil)))
5162
5163 ;; This function uses the cached op, string and number fields in
5164 ;; TokenStream; if getToken has been called since the passed token
5165 ;; was scanned, the op or string printed may be incorrect.
5166 (defun js2-token-to-string (token)
5167 ;; Not sure where this function is used in Rhino. Not tested.
5168 (if (not js2-debug-print-trees)
5169 ""
5170 (let ((name (js2-token-name token)))
5171 (cond
5172 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5173 (concat name " `" js2-ts-string "'"))
5174 ((eq token js2-NUMBER)
5175 (format "NUMBER %g" js2-ts-number))
5176 (t
5177 name)))))
5178
5179 (defconst js2-keywords
5180 '(break
5181 case catch const continue
5182 debugger default delete do
5183 else enum
5184 false finally for function
5185 if in instanceof import
5186 let
5187 new null
5188 return
5189 switch
5190 this throw true try typeof
5191 var void
5192 while with
5193 yield))
5194
5195 ;; Token names aren't exactly the same as the keywords, unfortunately.
5196 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5197 (defconst js2-kwd-tokens
5198 (let ((table (make-vector js2-num-tokens nil))
5199 (tokens
5200 (list js2-BREAK
5201 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5202 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5203 js2-ELSE
5204 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5205 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5206 js2-LET
5207 js2-NEW js2-NULL
5208 js2-RETURN
5209 js2-SWITCH
5210 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5211 js2-VAR
5212 js2-WHILE js2-WITH
5213 js2-YIELD)))
5214 (dolist (i tokens)
5215 (aset table i 'font-lock-keyword-face))
5216 (aset table js2-STRING 'font-lock-string-face)
5217 (aset table js2-REGEXP 'font-lock-string-face)
5218 (aset table js2-COMMENT 'font-lock-comment-face)
5219 (aset table js2-THIS 'font-lock-builtin-face)
5220 (aset table js2-VOID 'font-lock-constant-face)
5221 (aset table js2-NULL 'font-lock-constant-face)
5222 (aset table js2-TRUE 'font-lock-constant-face)
5223 (aset table js2-FALSE 'font-lock-constant-face)
5224 table)
5225 "Vector whose values are non-nil for tokens that are keywords.
5226 The values are default faces to use for highlighting the keywords.")
5227
5228 (defconst js2-reserved-words
5229 '(abstract
5230 boolean byte
5231 char class
5232 double
5233 enum export extends
5234 final float
5235 goto
5236 implements import int interface
5237 long
5238 native
5239 package private protected public
5240 short static super synchronized
5241 throws transient
5242 volatile))
5243
5244 (defconst js2-keyword-names
5245 (let ((table (make-hash-table :test 'equal)))
5246 (loop for k in js2-keywords
5247 do (puthash
5248 (symbol-name k) ; instanceof
5249 (intern (concat "js2-"
5250 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5251 table))
5252 table)
5253 "JavaScript keywords by name, mapped to their symbols.")
5254
5255 (defconst js2-reserved-word-names
5256 (let ((table (make-hash-table :test 'equal)))
5257 (loop for k in js2-reserved-words
5258 do
5259 (puthash (symbol-name k) 'js2-RESERVED table))
5260 table)
5261 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5262
5263 (defun js2-collect-string (buf)
5264 "Convert BUF, a list of chars, to a string.
5265 Reverses BUF before converting."
5266 (cond
5267 ((stringp buf)
5268 buf)
5269 ((null buf) ; for emacs21 compat
5270 "")
5271 (t
5272 (if buf
5273 (apply #'string (nreverse buf))
5274 ""))))
5275
5276 (defun js2-string-to-keyword (s)
5277 "Return token for S, a string, if S is a keyword or reserved word.
5278 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5279 (or (gethash s js2-keyword-names)
5280 (gethash s js2-reserved-word-names)))
5281
5282 (defsubst js2-ts-set-char-token-bounds ()
5283 "Used when next token is one character."
5284 (setq js2-token-beg (1- js2-ts-cursor)
5285 js2-token-end js2-ts-cursor))
5286
5287 (defsubst js2-ts-return (token)
5288 "Return an N-character TOKEN from `js2-get-token'.
5289 Updates `js2-token-end' accordingly."
5290 (setq js2-token-end js2-ts-cursor)
5291 (throw 'return token))
5292
5293 (defun js2-x-digit-to-int (c accumulator)
5294 "Build up a hex number.
5295 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5296 corresponding number. Otherwise return -1."
5297 (catch 'return
5298 (catch 'check
5299 ;; Use 0..9 < A..Z < a..z
5300 (cond
5301 ((<= c ?9)
5302 (decf c ?0)
5303 (if (<= 0 c)
5304 (throw 'check nil)))
5305 ((<= c ?F)
5306 (when (<= ?A c)
5307 (decf c (- ?A 10))
5308 (throw 'check nil)))
5309 ((<= c ?f)
5310 (when (<= ?a c)
5311 (decf c (- ?a 10))
5312 (throw 'check nil))))
5313 (throw 'return -1))
5314 (logior c (lsh accumulator 4))))
5315
5316 (defun js2-get-token ()
5317 "Return next JavaScript token, an int such as js2-RETURN."
5318 (let (c c1 identifier-start is-unicode-escape-start
5319 contains-escape escape-val escape-start str result base
5320 is-integer quote-char val look-for-slash continue)
5321 (catch 'return
5322 (while t
5323 ;; Eat whitespace, possibly sensitive to newlines.
5324 (setq continue t)
5325 (while continue
5326 (setq c (js2-get-char))
5327 (cond
5328 ((eq c js2-EOF_CHAR)
5329 (js2-ts-set-char-token-bounds)
5330 (throw 'return js2-EOF))
5331 ((eq c ?\n)
5332 (js2-ts-set-char-token-bounds)
5333 (setq js2-ts-dirty-line nil)
5334 (throw 'return js2-EOL))
5335 ((not (js2-js-space-p c))
5336 (if (/= c ?-) ; in case end of HTML comment
5337 (setq js2-ts-dirty-line t))
5338 (setq continue nil))))
5339 ;; Assume the token will be 1 char - fixed up below.
5340 (js2-ts-set-char-token-bounds)
5341 (when (eq c ?@)
5342 (throw 'return js2-XMLATTR))
5343 ;; identifier/keyword/instanceof?
5344 ;; watch out for starting with a <backslash>
5345 (cond
5346 ((eq c ?\\)
5347 (setq c (js2-get-char))
5348 (if (eq c ?u)
5349 (setq identifier-start t
5350 is-unicode-escape-start t
5351 js2-ts-string-buffer nil)
5352 (setq identifier-start nil)
5353 (js2-unget-char)
5354 (setq c ?\\)))
5355 (t
5356 (when (setq identifier-start (js2-java-identifier-start-p c))
5357 (setq js2-ts-string-buffer nil)
5358 (js2-add-to-string c))))
5359 (when identifier-start
5360 (setq contains-escape is-unicode-escape-start)
5361 (catch 'break
5362 (while t
5363 (if is-unicode-escape-start
5364 ;; strictly speaking we should probably push-back
5365 ;; all the bad characters if the <backslash>uXXXX
5366 ;; sequence is malformed. But since there isn't a
5367 ;; correct context(is there?) for a bad Unicode
5368 ;; escape sequence in an identifier, we can report
5369 ;; an error here.
5370 (progn
5371 (setq escape-val 0)
5372 (dotimes (i 4)
5373 (setq c (js2-get-char)
5374 escape-val (js2-x-digit-to-int c escape-val))
5375 ;; Next check takes care of c < 0 and bad escape
5376 (if (minusp escape-val)
5377 (throw 'break nil)))
5378 (if (minusp escape-val)
5379 (js2-report-scan-error "msg.invalid.escape" t))
5380 (js2-add-to-string escape-val)
5381 (setq is-unicode-escape-start nil))
5382 (setq c (js2-get-char))
5383 (cond
5384 ((eq c ?\\)
5385 (setq c (js2-get-char))
5386 (if (eq c ?u)
5387 (setq is-unicode-escape-start t
5388 contains-escape t)
5389 (js2-report-scan-error "msg.illegal.character" t)))
5390 (t
5391 (if (or (eq c js2-EOF_CHAR)
5392 (not (js2-java-identifier-part-p c)))
5393 (throw 'break nil))
5394 (js2-add-to-string c))))))
5395 (js2-unget-char)
5396 (setq str (js2-get-string-from-buffer))
5397 (unless contains-escape
5398 ;; OPT we shouldn't have to make a string (object!) to
5399 ;; check if it's a keyword.
5400 ;; Return the corresponding token if it's a keyword
5401 (when (setq result (js2-string-to-keyword str))
5402 (if (and (< js2-language-version 170)
5403 (memq result '(js2-LET js2-YIELD)))
5404 ;; LET and YIELD are tokens only in 1.7 and later
5405 (setq result 'js2-NAME))
5406 (if (not (eq result 'js2-RESERVED))
5407 (throw 'return (js2-token-code result)))
5408 (js2-report-warning "msg.reserved.keyword" str)))
5409 ;; If we want to intern these as Rhino does, just use (intern str)
5410 (setq js2-ts-string str)
5411 (throw 'return js2-NAME)) ; end identifier/kwd check
5412 ;; is it a number?
5413 (when (or (js2-digit-p c)
5414 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5415 (setq js2-ts-string-buffer nil
5416 base 10)
5417 (when (eq c ?0)
5418 (setq c (js2-get-char))
5419 (cond
5420 ((or (eq c ?x) (eq c ?X))
5421 (setq base 16)
5422 (setq c (js2-get-char)))
5423 ((js2-digit-p c)
5424 (setq base 8))
5425 (t
5426 (js2-add-to-string ?0))))
5427 (if (eq base 16)
5428 (while (<= 0 (js2-x-digit-to-int c 0))
5429 (js2-add-to-string c)
5430 (setq c (js2-get-char)))
5431 (while (and (<= ?0 c) (<= c ?9))
5432 ;; We permit 08 and 09 as decimal numbers, which
5433 ;; makes our behavior a superset of the ECMA
5434 ;; numeric grammar. We might not always be so
5435 ;; permissive, so we warn about it.
5436 (when (and (eq base 8) (>= c ?8))
5437 (js2-report-warning "msg.bad.octal.literal"
5438 (if (eq c ?8) "8" "9"))
5439 (setq base 10))
5440 (js2-add-to-string c)
5441 (setq c (js2-get-char))))
5442 (setq is-integer t)
5443 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5444 (setq is-integer nil)
5445 (when (eq c ?.)
5446 (loop do
5447 (js2-add-to-string c)
5448 (setq c (js2-get-char))
5449 while (js2-digit-p c)))
5450 (when (memq c '(?e ?E))
5451 (js2-add-to-string c)
5452 (setq c (js2-get-char))
5453 (when (memq c '(?+ ?-))
5454 (js2-add-to-string c)
5455 (setq c (js2-get-char)))
5456 (unless (js2-digit-p c)
5457 (js2-report-scan-error "msg.missing.exponent" t))
5458 (loop do
5459 (js2-add-to-string c)
5460 (setq c (js2-get-char))
5461 while (js2-digit-p c))))
5462 (js2-unget-char)
5463 (setq js2-ts-string (js2-get-string-from-buffer)
5464 js2-ts-number
5465 (if (and (eq base 10) (not is-integer))
5466 (string-to-number js2-ts-string)
5467 ;; TODO: call runtime number-parser. Some of it is in
5468 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5469 (string-to-number js2-ts-string)))
5470 (throw 'return js2-NUMBER))
5471 ;; is it a string?
5472 (when (memq c '(?\" ?\'))
5473 ;; We attempt to accumulate a string the fast way, by
5474 ;; building it directly out of the reader. But if there
5475 ;; are any escaped characters in the string, we revert to
5476 ;; building it out of a string buffer.
5477 (setq quote-char c
5478 js2-ts-string-buffer nil
5479 c (js2-get-char))
5480 (catch 'break
5481 (while (/= c quote-char)
5482 (catch 'continue
5483 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5484 (js2-unget-char)
5485 (setq js2-token-end js2-ts-cursor)
5486 (js2-report-error "msg.unterminated.string.lit")
5487 (throw 'return js2-STRING))
5488 (when (eq c ?\\)
5489 ;; We've hit an escaped character
5490 (setq c (js2-get-char))
5491 (case c
5492 (?b (setq c ?\b))
5493 (?f (setq c ?\f))
5494 (?n (setq c ?\n))
5495 (?r (setq c ?\r))
5496 (?t (setq c ?\t))
5497 (?v (setq c ?\v))
5498 (?u
5499 (setq c1 (js2-read-unicode-escape))
5500 (if js2-parse-ide-mode
5501 (if c1
5502 (progn
5503 ;; just copy the string in IDE-mode
5504 (js2-add-to-string ?\\)
5505 (js2-add-to-string ?u)
5506 (dotimes (i 3)
5507 (js2-add-to-string (js2-get-char)))
5508 (setq c (js2-get-char))) ; added at end of loop
5509 ;; flag it as an invalid escape
5510 (js2-report-warning "msg.invalid.escape"
5511 nil (- js2-ts-cursor 2) 6))
5512 ;; Get 4 hex digits; if the u escape is not
5513 ;; followed by 4 hex digits, use 'u' + the
5514 ;; literal character sequence that follows.
5515 (js2-add-to-string ?u)
5516 (setq escape-val 0)
5517 (dotimes (i 4)
5518 (setq c (js2-get-char)
5519 escape-val (js2-x-digit-to-int c escape-val))
5520 (if (minusp escape-val)
5521 (throw 'continue nil))
5522 (js2-add-to-string c))
5523 ;; prepare for replace of stored 'u' sequence by escape value
5524 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5525 c escape-val)))
5526 (?x
5527 ;; Get 2 hex digits, defaulting to 'x'+literal
5528 ;; sequence, as above.
5529 (setq c (js2-get-char)
5530 escape-val (js2-x-digit-to-int c 0))
5531 (if (minusp escape-val)
5532 (progn
5533 (js2-add-to-string ?x)
5534 (throw 'continue nil))
5535 (setq c1 c
5536 c (js2-get-char)
5537 escape-val (js2-x-digit-to-int c escape-val))
5538 (if (minusp escape-val)
5539 (progn
5540 (js2-add-to-string ?x)
5541 (js2-add-to-string c1)
5542 (throw 'continue nil))
5543 ;; got 2 hex digits
5544 (setq c escape-val))))
5545 (?\n
5546 ;; Remove line terminator after escape to follow
5547 ;; SpiderMonkey and C/C++
5548 (setq c (js2-get-char))
5549 (throw 'continue nil))
5550 (t
5551 (when (and (<= ?0 c) (< c ?8))
5552 (setq val (- c ?0)
5553 c (js2-get-char))
5554 (when (and (<= ?0 c) (< c ?8))
5555 (setq val (- (+ (* 8 val) c) ?0)
5556 c (js2-get-char))
5557 (when (and (<= ?0 c)
5558 (< c ?8)
5559 (< val #o37))
5560 ;; c is 3rd char of octal sequence only
5561 ;; if the resulting val <= 0377
5562 (setq val (- (+ (* 8 val) c) ?0)
5563 c (js2-get-char))))
5564 (js2-unget-char)
5565 (setq c val)))))
5566 (js2-add-to-string c)
5567 (setq c (js2-get-char)))))
5568 (setq js2-ts-string (js2-get-string-from-buffer))
5569 (throw 'return js2-STRING))
5570 (case c
5571 (?\;
5572 (throw 'return js2-SEMI))
5573 (?\[
5574 (throw 'return js2-LB))
5575 (?\]
5576 (throw 'return js2-RB))
5577 (?{
5578 (throw 'return js2-LC))
5579 (?}
5580 (throw 'return js2-RC))
5581 (?\(
5582 (throw 'return js2-LP))
5583 (?\)
5584 (throw 'return js2-RP))
5585 (?,
5586 (throw 'return js2-COMMA))
5587 (??
5588 (throw 'return js2-HOOK))
5589 (?:
5590 (if (js2-match-char ?:)
5591 (js2-ts-return js2-COLONCOLON)
5592 (throw 'return js2-COLON)))
5593 (?.
5594 (if (js2-match-char ?.)
5595 (if (js2-match-char ?.)
5596 (js2-ts-return js2-TRIPLEDOT)
5597 (js2-ts-return js2-DOTDOT))
5598 (if (js2-match-char ?\()
5599 (js2-ts-return js2-DOTQUERY)
5600 (throw 'return js2-DOT))))
5601 (?|
5602 (if (js2-match-char ?|)
5603 (throw 'return js2-OR)
5604 (if (js2-match-char ?=)
5605 (js2-ts-return js2-ASSIGN_BITOR)
5606 (throw 'return js2-BITOR))))
5607 (?^
5608 (if (js2-match-char ?=)
5609 (js2-ts-return js2-ASSIGN_BITOR)
5610 (throw 'return js2-BITXOR)))
5611 (?&
5612 (if (js2-match-char ?&)
5613 (throw 'return js2-AND)
5614 (if (js2-match-char ?=)
5615 (js2-ts-return js2-ASSIGN_BITAND)
5616 (throw 'return js2-BITAND))))
5617 (?=
5618 (if (js2-match-char ?=)
5619 (if (js2-match-char ?=)
5620 (js2-ts-return js2-SHEQ)
5621 (throw 'return js2-EQ))
5622 (throw 'return js2-ASSIGN)))
5623 (?!
5624 (if (js2-match-char ?=)
5625 (if (js2-match-char ?=)
5626 (js2-ts-return js2-SHNE)
5627 (js2-ts-return js2-NE))
5628 (throw 'return js2-NOT)))
5629 (?<
5630 ;; NB:treat HTML begin-comment as comment-till-eol
5631 (when (js2-match-char ?!)
5632 (when (js2-match-char ?-)
5633 (when (js2-match-char ?-)
5634 (js2-skip-line)
5635 (setq js2-ts-comment-type 'html)
5636 (throw 'return js2-COMMENT)))
5637 (js2-unget-char))
5638 (if (js2-match-char ?<)
5639 (if (js2-match-char ?=)
5640 (js2-ts-return js2-ASSIGN_LSH)
5641 (js2-ts-return js2-LSH))
5642 (if (js2-match-char ?=)
5643 (js2-ts-return js2-LE)
5644 (throw 'return js2-LT))))
5645 (?>
5646 (if (js2-match-char ?>)
5647 (if (js2-match-char ?>)
5648 (if (js2-match-char ?=)
5649 (js2-ts-return js2-ASSIGN_URSH)
5650 (js2-ts-return js2-URSH))
5651 (if (js2-match-char ?=)
5652 (js2-ts-return js2-ASSIGN_RSH)
5653 (js2-ts-return js2-RSH)))
5654 (if (js2-match-char ?=)
5655 (js2-ts-return js2-GE)
5656 (throw 'return js2-GT))))
5657 (?*
5658 (if (js2-match-char ?=)
5659 (js2-ts-return js2-ASSIGN_MUL)
5660 (throw 'return js2-MUL)))
5661 (?/
5662 ;; is it a // comment?
5663 (when (js2-match-char ?/)
5664 (setq js2-token-beg (- js2-ts-cursor 2))
5665 (js2-skip-line)
5666 (setq js2-ts-comment-type 'line)
5667 ;; include newline so highlighting goes to end of window
5668 (incf js2-token-end)
5669 (throw 'return js2-COMMENT))
5670 ;; is it a /* comment?
5671 (when (js2-match-char ?*)
5672 (setq look-for-slash nil
5673 js2-token-beg (- js2-ts-cursor 2)
5674 js2-ts-comment-type
5675 (if (js2-match-char ?*)
5676 (progn
5677 (setq look-for-slash t)
5678 'jsdoc)
5679 'block))
5680 (while t
5681 (setq c (js2-get-char))
5682 (cond
5683 ((eq c js2-EOF_CHAR)
5684 (setq js2-token-end (1- js2-ts-cursor))
5685 (js2-report-error "msg.unterminated.comment")
5686 (throw 'return js2-COMMENT))
5687 ((eq c ?*)
5688 (setq look-for-slash t))
5689 ((eq c ?/)
5690 (if look-for-slash
5691 (js2-ts-return js2-COMMENT)))
5692 (t
5693 (setq look-for-slash nil
5694 js2-token-end js2-ts-cursor)))))
5695 (if (js2-match-char ?=)
5696 (js2-ts-return js2-ASSIGN_DIV)
5697 (throw 'return js2-DIV)))
5698 (?#
5699 (when js2-skip-preprocessor-directives
5700 (js2-skip-line)
5701 (setq js2-ts-comment-type 'preprocessor
5702 js2-token-end js2-ts-cursor)
5703 (throw 'return js2-COMMENT))
5704 (throw 'return js2-ERROR))
5705 (?%
5706 (if (js2-match-char ?=)
5707 (js2-ts-return js2-ASSIGN_MOD)
5708 (throw 'return js2-MOD)))
5709 (?~
5710 (throw 'return js2-BITNOT))
5711 (?+
5712 (if (js2-match-char ?=)
5713 (js2-ts-return js2-ASSIGN_ADD)
5714 (if (js2-match-char ?+)
5715 (js2-ts-return js2-INC)
5716 (throw 'return js2-ADD))))
5717 (?-
5718 (cond
5719 ((js2-match-char ?=)
5720 (setq c js2-ASSIGN_SUB))
5721 ((js2-match-char ?-)
5722 (unless js2-ts-dirty-line
5723 ;; treat HTML end-comment after possible whitespace
5724 ;; after line start as comment-until-eol
5725 (when (js2-match-char ?>)
5726 (js2-skip-line)
5727 (setq js2-ts-comment-type 'html)
5728 (throw 'return js2-COMMENT)))
5729 (setq c js2-DEC))
5730 (t
5731 (setq c js2-SUB)))
5732 (setq js2-ts-dirty-line t)
5733 (js2-ts-return c))
5734 (otherwise
5735 (js2-report-scan-error "msg.illegal.character")))))))
5736
5737 (defun js2-read-regexp (start-token)
5738 "Called by parser when it gets / or /= in literal context."
5739 (let (c err
5740 in-class ; inside a '[' .. ']' character-class
5741 flags
5742 (continue t))
5743 (setq js2-token-beg js2-ts-cursor
5744 js2-ts-string-buffer nil
5745 js2-ts-regexp-flags nil)
5746 (if (eq start-token js2-ASSIGN_DIV)
5747 ;; mis-scanned /=
5748 (js2-add-to-string ?=)
5749 (if (not (eq start-token js2-DIV))
5750 (error "failed assertion")))
5751 (while (and (not err)
5752 (or (/= (setq c (js2-get-char)) ?/)
5753 in-class))
5754 (cond
5755 ((or (= c ?\n)
5756 (= c js2-EOF_CHAR))
5757 (setq js2-token-end (1- js2-ts-cursor)
5758 err t
5759 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5760 (js2-report-error "msg.unterminated.re.lit"))
5761 (t (cond
5762 ((= c ?\\)
5763 (js2-add-to-string c)
5764 (setq c (js2-get-char)))
5765 ((= c ?\[)
5766 (setq in-class t))
5767 ((= c ?\])
5768 (setq in-class nil)))
5769 (js2-add-to-string c))))
5770 (unless err
5771 (while continue
5772 (cond
5773 ((js2-match-char ?g)
5774 (push ?g flags))
5775 ((js2-match-char ?i)
5776 (push ?i flags))
5777 ((js2-match-char ?m)
5778 (push ?m flags))
5779 (t
5780 (setq continue nil))))
5781 (if (js2-alpha-p (js2-peek-char))
5782 (js2-report-scan-error "msg.invalid.re.flag" t
5783 js2-ts-cursor 1))
5784 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5785 js2-ts-regexp-flags (js2-collect-string flags)
5786 js2-token-end js2-ts-cursor)
5787 ;; tell `parse-partial-sexp' to ignore this range of chars
5788 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
5789
5790 (defun js2-get-first-xml-token ()
5791 (setq js2-ts-xml-open-tags-count 0
5792 js2-ts-is-xml-attribute nil
5793 js2-ts-xml-is-tag-content nil)
5794 (js2-unget-char)
5795 (js2-get-next-xml-token))
5796
5797 (defun js2-xml-discard-string ()
5798 "Throw away the string in progress and flag an XML parse error."
5799 (setq js2-ts-string-buffer nil
5800 js2-ts-string nil)
5801 (js2-report-scan-error "msg.XML.bad.form" t))
5802
5803 (defun js2-get-next-xml-token ()
5804 (setq js2-ts-string-buffer nil ; for recording the XML
5805 js2-token-beg js2-ts-cursor)
5806 (let (c result)
5807 (setq result
5808 (catch 'return
5809 (while t
5810 (setq c (js2-get-char))
5811 (cond
5812 ((= c js2-EOF_CHAR)
5813 (throw 'return js2-ERROR))
5814 (js2-ts-xml-is-tag-content
5815 (case c
5816 (?>
5817 (js2-add-to-string c)
5818 (setq js2-ts-xml-is-tag-content nil
5819 js2-ts-is-xml-attribute nil))
5820 (?/
5821 (js2-add-to-string c)
5822 (when (eq ?> (js2-peek-char))
5823 (setq c (js2-get-char))
5824 (js2-add-to-string c)
5825 (setq js2-ts-xml-is-tag-content nil)
5826 (decf js2-ts-xml-open-tags-count)))
5827 (?{
5828 (js2-unget-char)
5829 (setq js2-ts-string (js2-get-string-from-buffer))
5830 (throw 'return js2-XML))
5831 ((?\' ?\")
5832 (js2-add-to-string c)
5833 (unless (js2-read-quoted-string c)
5834 (throw 'return js2-ERROR)))
5835 (?=
5836 (js2-add-to-string c)
5837 (setq js2-ts-is-xml-attribute t))
5838 ((? ?\t ?\r ?\n)
5839 (js2-add-to-string c))
5840 (t
5841 (js2-add-to-string c)
5842 (setq js2-ts-is-xml-attribute nil)))
5843 (when (and (not js2-ts-xml-is-tag-content)
5844 (zerop js2-ts-xml-open-tags-count))
5845 (setq js2-ts-string (js2-get-string-from-buffer))
5846 (throw 'return js2-XMLEND)))
5847 (t
5848 ;; else not tag content
5849 (case c
5850 (?<
5851 (js2-add-to-string c)
5852 (setq c (js2-peek-char))
5853 (case c
5854 (?!
5855 (setq c (js2-get-char)) ;; skip !
5856 (js2-add-to-string c)
5857 (setq c (js2-peek-char))
5858 (case c
5859 (?-
5860 (setq c (js2-get-char)) ;; skip -
5861 (js2-add-to-string c)
5862 (if (eq c ?-)
5863 (progn
5864 (js2-add-to-string c)
5865 (unless (js2-read-xml-comment)
5866 (throw 'return js2-ERROR)))
5867 (js2-xml-discard-string)
5868 (throw 'return js2-ERROR)))
5869 (?\[
5870 (setq c (js2-get-char)) ;; skip [
5871 (js2-add-to-string c)
5872 (if (and (= (js2-get-char) ?C)
5873 (= (js2-get-char) ?D)
5874 (= (js2-get-char) ?A)
5875 (= (js2-get-char) ?T)
5876 (= (js2-get-char) ?A)
5877 (= (js2-get-char) ?\[))
5878 (progn
5879 (js2-add-to-string ?C)
5880 (js2-add-to-string ?D)
5881 (js2-add-to-string ?A)
5882 (js2-add-to-string ?T)
5883 (js2-add-to-string ?A)
5884 (js2-add-to-string ?\[)
5885 (unless (js2-read-cdata)
5886 (throw 'return js2-ERROR)))
5887 (js2-xml-discard-string)
5888 (throw 'return js2-ERROR)))
5889 (t
5890 (unless (js2-read-entity)
5891 (throw 'return js2-ERROR))))
5892 ;; Allow bare CDATA section, e.g.:
5893 ;; let xml = <![CDATA[ foo bar baz ]]>;
5894 (when (zerop js2-ts-xml-open-tags-count)
5895 (throw 'return js2-XMLEND)))
5896 (??
5897 (setq c (js2-get-char)) ;; skip ?
5898 (js2-add-to-string c)
5899 (unless (js2-read-PI)
5900 (throw 'return js2-ERROR)))
5901 (?/
5902 ;; end tag
5903 (setq c (js2-get-char)) ;; skip /
5904 (js2-add-to-string c)
5905 (when (zerop js2-ts-xml-open-tags-count)
5906 (js2-xml-discard-string)
5907 (throw 'return js2-ERROR))
5908 (setq js2-ts-xml-is-tag-content t)
5909 (decf js2-ts-xml-open-tags-count))
5910 (t
5911 ;; start tag
5912 (setq js2-ts-xml-is-tag-content t)
5913 (incf js2-ts-xml-open-tags-count))))
5914 (?{
5915 (js2-unget-char)
5916 (setq js2-ts-string (js2-get-string-from-buffer))
5917 (throw 'return js2-XML))
5918 (t
5919 (js2-add-to-string c))))))))
5920 (setq js2-token-end js2-ts-cursor)
5921 result))
5922
5923 (defun js2-read-quoted-string (quote)
5924 (let (c)
5925 (catch 'return
5926 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
5927 (js2-add-to-string c)
5928 (if (eq c quote)
5929 (throw 'return t)))
5930 (js2-xml-discard-string) ;; throw away string in progress
5931 nil)))
5932
5933 (defun js2-read-xml-comment ()
5934 (let ((c (js2-get-char)))
5935 (catch 'return
5936 (while (/= c js2-EOF_CHAR)
5937 (catch 'continue
5938 (js2-add-to-string c)
5939 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
5940 (setq c (js2-get-char))
5941 (js2-add-to-string c)
5942 (if (eq (js2-peek-char) ?>)
5943 (progn
5944 (setq c (js2-get-char)) ;; skip >
5945 (js2-add-to-string c)
5946 (throw 'return t))
5947 (throw 'continue nil)))
5948 (setq c (js2-get-char))))
5949 (js2-xml-discard-string)
5950 nil)))
5951
5952 (defun js2-read-cdata ()
5953 (let ((c (js2-get-char)))
5954 (catch 'return
5955 (while (/= c js2-EOF_CHAR)
5956 (catch 'continue
5957 (js2-add-to-string c)
5958 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
5959 (setq c (js2-get-char))
5960 (js2-add-to-string c)
5961 (if (eq (js2-peek-char) ?>)
5962 (progn
5963 (setq c (js2-get-char)) ;; Skip >
5964 (js2-add-to-string c)
5965 (throw 'return t))
5966 (throw 'continue nil)))
5967 (setq c (js2-get-char))))
5968 (js2-xml-discard-string)
5969 nil)))
5970
5971 (defun js2-read-entity ()
5972 (let ((decl-tags 1)
5973 c)
5974 (catch 'return
5975 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
5976 (js2-add-to-string c)
5977 (case c
5978 (?<
5979 (incf decl-tags))
5980 (?>
5981 (decf decl-tags)
5982 (if (zerop decl-tags)
5983 (throw 'return t)))))
5984 (js2-xml-discard-string)
5985 nil)))
5986
5987 (defun js2-read-PI ()
5988 "Scan an XML processing instruction."
5989 (let (c)
5990 (catch 'return
5991 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
5992 (js2-add-to-string c)
5993 (when (and (eq c ??) (eq (js2-peek-char) ?>))
5994 (setq c (js2-get-char)) ;; Skip >
5995 (js2-add-to-string c)
5996 (throw 'return t)))
5997 (js2-xml-discard-string)
5998 nil)))
5999
6000 ;;; Highlighting
6001
6002 (defun js2-set-face (beg end face &optional record)
6003 "Fontify a region. If RECORD is non-nil, record for later."
6004 (when (plusp js2-highlight-level)
6005 (setq beg (min (point-max) beg)
6006 beg (max (point-min) beg)
6007 end (min (point-max) end)
6008 end (max (point-min) end))
6009 (if record
6010 (push (list beg end face) js2-mode-fontifications)
6011 (put-text-property beg end 'font-lock-face face))))
6012
6013 (defsubst js2-clear-face (beg end)
6014 (remove-text-properties beg end '(font-lock-face nil
6015 help-echo nil
6016 point-entered nil
6017 c-in-sws nil)))
6018
6019 (defconst js2-ecma-global-props
6020 (concat "^"
6021 (regexp-opt
6022 '("Infinity" "NaN" "undefined" "arguments") t)
6023 "$")
6024 "Value properties of the Ecma-262 Global Object.
6025 Shown at or above `js2-highlight-level' 2.")
6026
6027 ;; might want to add the name "arguments" to this list?
6028 (defconst js2-ecma-object-props
6029 (concat "^"
6030 (regexp-opt
6031 '("prototype" "__proto__" "__parent__") t)
6032 "$")
6033 "Value properties of the Ecma-262 Object constructor.
6034 Shown at or above `js2-highlight-level' 2.")
6035
6036 (defconst js2-ecma-global-funcs
6037 (concat
6038 "^"
6039 (regexp-opt
6040 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6041 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6042 "$")
6043 "Function properties of the Ecma-262 Global object.
6044 Shown at or above `js2-highlight-level' 2.")
6045
6046 (defconst js2-ecma-number-props
6047 (concat "^"
6048 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6049 "NEGATIVE_INFINITY"
6050 "POSITIVE_INFINITY") t)
6051 "$")
6052 "Properties of the Ecma-262 Number constructor.
6053 Shown at or above `js2-highlight-level' 2.")
6054
6055 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6056 "Properties of the Ecma-262 Date constructor.
6057 Shown at or above `js2-highlight-level' 2.")
6058
6059 (defconst js2-ecma-math-props
6060 (concat "^"
6061 (regexp-opt
6062 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6063 t)
6064 "$")
6065 "Properties of the Ecma-262 Math object.
6066 Shown at or above `js2-highlight-level' 2.")
6067
6068 (defconst js2-ecma-math-funcs
6069 (concat "^"
6070 (regexp-opt
6071 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6072 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6073 "$")
6074 "Function properties of the Ecma-262 Math object.
6075 Shown at or above `js2-highlight-level' 2.")
6076
6077 (defconst js2-ecma-function-props
6078 (concat
6079 "^"
6080 (regexp-opt
6081 '(;; properties of the Object prototype object
6082 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6083 "toLocaleString" "toString" "valueOf"
6084 ;; properties of the Function prototype object
6085 "apply" "call"
6086 ;; properties of the Array prototype object
6087 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6088 "splice" "unshift"
6089 ;; properties of the String prototype object
6090 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6091 "localeCompare" "match" "replace" "search" "split" "substring"
6092 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6093 "toUpperCase"
6094 ;; properties of the Number prototype object
6095 "toExponential" "toFixed" "toPrecision"
6096 ;; properties of the Date prototype object
6097 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6098 "getMinutes" "getMonth" "getSeconds" "getTime"
6099 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6100 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6101 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6102 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6103 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6104 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6105 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6106 "toTimeString" "toUTCString"
6107 ;; properties of the RegExp prototype object
6108 "exec" "test"
6109 ;; properties of the JSON prototype object
6110 "parse" "stringify"
6111 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6112 "toSource" "__defineGetter__" "__defineSetter__"
6113 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6114 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6115 t)
6116 "$")
6117 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6118 Shown at or above `js2-highlight-level' 3.")
6119
6120 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6121 (let ((target-name (and target
6122 (js2-name-node-p target)
6123 (js2-name-node-name target)))
6124 (prop-name (if prop (js2-name-node-name prop)))
6125 (level1 (>= js2-highlight-level 1))
6126 (level2 (>= js2-highlight-level 2))
6127 (level3 (>= js2-highlight-level 3))
6128 pos face)
6129 (when level2
6130 (if call-p
6131 (cond
6132 ((and target prop)
6133 (cond
6134 ((and level3 (string-match js2-ecma-function-props prop-name))
6135 (setq face 'font-lock-builtin-face))
6136 ((and target-name prop)
6137 (cond
6138 ((string= target-name "Date")
6139 (if (string-match js2-ecma-date-props prop-name)
6140 (setq face 'font-lock-builtin-face)))
6141 ((string= target-name "Math")
6142 (if (string-match js2-ecma-math-funcs prop-name)
6143 (setq face 'font-lock-builtin-face)))))))
6144 (prop
6145 (if (string-match js2-ecma-global-funcs prop-name)
6146 (setq face 'font-lock-builtin-face))))
6147 (cond
6148 ((and target prop)
6149 (cond
6150 ((string= target-name "Number")
6151 (if (string-match js2-ecma-number-props prop-name)
6152 (setq face 'font-lock-constant-face)))
6153 ((string= target-name "Math")
6154 (if (string-match js2-ecma-math-props prop-name)
6155 (setq face 'font-lock-constant-face)))))
6156 (prop
6157 (if (string-match js2-ecma-object-props prop-name)
6158 (setq face 'font-lock-constant-face)))))
6159 (when face
6160 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6161 (js2-node-pos prop))) ; relative
6162 (+ pos (js2-node-len prop))
6163 face 'record)))))
6164
6165 (defun js2-parse-highlight-member-expr-node (node)
6166 "Perform syntax highlighting of EcmaScript built-in properties.
6167 The variable `js2-highlight-level' governs this highighting."
6168 (let (face target prop name pos end parent call-p callee)
6169 (cond
6170 ;; case 1: simple name, e.g. foo
6171 ((js2-name-node-p node)
6172 (setq name (js2-name-node-name node))
6173 ;; possible for name to be nil in rare cases - saw it when
6174 ;; running js2-mode on an elisp buffer. Might as well try to
6175 ;; make it so js2-mode never barfs.
6176 (when name
6177 (setq face (if (string-match js2-ecma-global-props name)
6178 'font-lock-constant-face))
6179 (when face
6180 (setq pos (js2-node-pos node)
6181 end (+ pos (js2-node-len node)))
6182 (js2-set-face pos end face 'record))))
6183 ;; case 2: property access or function call
6184 ((or (js2-prop-get-node-p node)
6185 ;; highlight function call if expr is a prop-get node
6186 ;; or a plain name (i.e. unqualified function call)
6187 (and (setq call-p (js2-call-node-p node))
6188 (setq callee (js2-call-node-target node)) ; separate setq!
6189 (or (js2-prop-get-node-p callee)
6190 (js2-name-node-p callee))))
6191 (setq parent node
6192 node (if call-p callee node))
6193 (if (and call-p (js2-name-node-p callee))
6194 (setq prop callee)
6195 (setq target (js2-prop-get-node-left node)
6196 prop (js2-prop-get-node-right node)))
6197 (cond
6198 ((js2-name-node-p target)
6199 (if (js2-name-node-p prop)
6200 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6201 (js2-parse-highlight-prop-get parent target prop call-p)
6202 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6203 (js2-parse-highlight-prop-get parent target nil call-p)))
6204 ((js2-name-node-p prop)
6205 ;; case 2c: complex target, simple name, e.g. x[y].bar
6206 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6207
6208 (defun js2-parse-highlight-member-expr-fn-name (expr)
6209 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6210 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6211 We currently only handle the case where the last component is a prop-get
6212 of a simple name. Called before EXPR has a parent node."
6213 (let (pos
6214 (name (and (js2-prop-get-node-p expr)
6215 (js2-prop-get-node-right expr))))
6216 (when (js2-name-node-p name)
6217 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6218 (js2-node-pos name)))
6219 (+ pos (js2-node-len name))
6220 'font-lock-function-name-face
6221 'record))))
6222
6223 ;; source: http://jsdoc.sourceforge.net/
6224 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6225 ;; allows type specifications, and needs work before entering the wild.
6226
6227 (defconst js2-jsdoc-param-tag-regexp
6228 (concat "^\\s-*\\*+\\s-*\\(@"
6229 "\\(?:param\\|argument\\)"
6230 "\\)"
6231 "\\s-*\\({[^}]+}\\)?" ; optional type
6232 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6233 "\\>")
6234 "Matches jsdoc tags with optional type and optional param name.")
6235
6236 (defconst js2-jsdoc-typed-tag-regexp
6237 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6238 (regexp-opt
6239 '("enum"
6240 "extends"
6241 "field"
6242 "id"
6243 "implements"
6244 "lends"
6245 "mods"
6246 "requires"
6247 "return"
6248 "returns"
6249 "throw"
6250 "throws"))
6251 "\\)\\)\\s-*\\({[^}]+}\\)?")
6252 "Matches jsdoc tags with optional type.")
6253
6254 (defconst js2-jsdoc-arg-tag-regexp
6255 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6256 (regexp-opt
6257 '("alias"
6258 "augments"
6259 "borrows"
6260 "bug"
6261 "base"
6262 "config"
6263 "default"
6264 "define"
6265 "exception"
6266 "function"
6267 "member"
6268 "memberOf"
6269 "name"
6270 "namespace"
6271 "property"
6272 "since"
6273 "suppress"
6274 "this"
6275 "throws"
6276 "type"
6277 "version"))
6278 "\\)\\)\\s-+\\([^ \t]+\\)")
6279 "Matches jsdoc tags with a single argument.")
6280
6281 (defconst js2-jsdoc-empty-tag-regexp
6282 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6283 (regexp-opt
6284 '("addon"
6285 "author"
6286 "class"
6287 "const"
6288 "constant"
6289 "constructor"
6290 "constructs"
6291 "deprecated"
6292 "desc"
6293 "description"
6294 "event"
6295 "example"
6296 "exec"
6297 "export"
6298 "fileoverview"
6299 "final"
6300 "function"
6301 "hidden"
6302 "ignore"
6303 "implicitCast"
6304 "inheritDoc"
6305 "inner"
6306 "interface"
6307 "license"
6308 "noalias"
6309 "noshadow"
6310 "notypecheck"
6311 "override"
6312 "owner"
6313 "preserve"
6314 "preserveTry"
6315 "private"
6316 "protected"
6317 "public"
6318 "static"
6319 "supported"
6320 ))
6321 "\\)\\)\\s-*")
6322 "Matches empty jsdoc tags.")
6323
6324 (defconst js2-jsdoc-link-tag-regexp
6325 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6326 "Matches a jsdoc link or code tag.")
6327
6328 (defconst js2-jsdoc-see-tag-regexp
6329 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6330 "Matches a jsdoc @see tag.")
6331
6332 (defconst js2-jsdoc-html-tag-regexp
6333 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6334 "Matches a simple (no attributes) html start- or end-tag.")
6335
6336 (defun js2-jsdoc-highlight-helper ()
6337 (js2-set-face (match-beginning 1)
6338 (match-end 1)
6339 'js2-jsdoc-tag)
6340 (if (match-beginning 2)
6341 (if (save-excursion
6342 (goto-char (match-beginning 2))
6343 (= (char-after) ?{))
6344 (js2-set-face (1+ (match-beginning 2))
6345 (1- (match-end 2))
6346 'js2-jsdoc-type)
6347 (js2-set-face (match-beginning 2)
6348 (match-end 2)
6349 'js2-jsdoc-value)))
6350 (if (match-beginning 3)
6351 (js2-set-face (match-beginning 3)
6352 (match-end 3)
6353 'js2-jsdoc-value)))
6354
6355 (defun js2-highlight-jsdoc (ast)
6356 "Highlight doc comment tags."
6357 (let ((comments (js2-ast-root-comments ast))
6358 beg end)
6359 (save-excursion
6360 (dolist (node comments)
6361 (when (eq (js2-comment-node-format node) 'jsdoc)
6362 (setq beg (js2-node-abs-pos node)
6363 end (+ beg (js2-node-len node)))
6364 (save-restriction
6365 (narrow-to-region beg end)
6366 (dolist (re (list js2-jsdoc-param-tag-regexp
6367 js2-jsdoc-typed-tag-regexp
6368 js2-jsdoc-arg-tag-regexp
6369 js2-jsdoc-link-tag-regexp
6370 js2-jsdoc-see-tag-regexp
6371 js2-jsdoc-empty-tag-regexp))
6372 (goto-char beg)
6373 (while (re-search-forward re nil t)
6374 (js2-jsdoc-highlight-helper)))
6375 ;; simple highlighting for html tags
6376 (goto-char beg)
6377 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6378 (js2-set-face (match-beginning 1)
6379 (match-end 1)
6380 'js2-jsdoc-html-tag-delimiter)
6381 (js2-set-face (match-beginning 2)
6382 (match-end 2)
6383 'js2-jsdoc-html-tag-name)
6384 (js2-set-face (match-beginning 3)
6385 (match-end 3)
6386 'js2-jsdoc-html-tag-delimiter))))))))
6387
6388 (defun js2-highlight-assign-targets (node left right)
6389 "Highlight function properties and external variables."
6390 (let (leftpos end name)
6391 ;; highlight vars and props assigned function values
6392 (when (js2-function-node-p right)
6393 (cond
6394 ;; var foo = function() {...}
6395 ((js2-name-node-p left)
6396 (setq name left))
6397 ;; foo.bar.baz = function() {...}
6398 ((and (js2-prop-get-node-p left)
6399 (js2-name-node-p (js2-prop-get-node-right left)))
6400 (setq name (js2-prop-get-node-right left))))
6401 (when name
6402 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6403 (+ leftpos (js2-node-len name))
6404 'font-lock-function-name-face
6405 'record)))))
6406
6407 (defun js2-record-name-node (node)
6408 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6409 later. NODE must be a name node."
6410 (let (leftpos end)
6411 (push (list node js2-current-scope
6412 (setq leftpos (js2-node-abs-pos node))
6413 (setq end (+ leftpos (js2-node-len node))))
6414 js2-recorded-identifiers)))
6415
6416 (defun js2-highlight-undeclared-vars ()
6417 "After entire parse is finished, look for undeclared variable references.
6418 We have to wait until entire buffer is parsed, since JavaScript permits var
6419 decls to occur after they're used.
6420
6421 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6422 it is considered declared."
6423 (let (name)
6424 (dolist (entry js2-recorded-identifiers)
6425 (destructuring-bind (name-node scope pos end) entry
6426 (setq name (js2-name-node-name name-node))
6427 (unless (or (member name js2-global-externs)
6428 (member name js2-default-externs)
6429 (member name js2-additional-externs)
6430 (js2-get-defining-scope scope name))
6431 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6432 'js2-external-variable))))
6433 (setq js2-recorded-identifiers nil)))
6434
6435 (defun js2-set-default-externs ()
6436 "Set the value of `js2-default-externs' based on the various
6437 `js2-include-?-externs' variables."
6438 (setq js2-default-externs
6439 (append js2-ecma-262-externs
6440 (if js2-include-browser-externs js2-browser-externs)
6441 (if js2-include-rhino-externs js2-rhino-externs)
6442 (if js2-include-node-externs js2-node-externs)
6443 (if (or js2-include-browser-externs js2-include-node-externs)
6444 js2-typed-array-externs))))
6445
6446 (defun js2-apply-jslint-globals ()
6447 (setq js2-additional-externs
6448 (nconc (js2-get-jslint-globals)
6449 js2-additional-externs)))
6450
6451 (defun js2-get-jslint-globals ()
6452 (loop for node in (js2-ast-root-comments js2-mode-ast)
6453 when (and (eq 'block (js2-comment-node-format node))
6454 (save-excursion
6455 (goto-char (js2-node-abs-pos node))
6456 (looking-at "/\\*global ")))
6457 append (js2-get-jslint-globals-in
6458 (match-end 0)
6459 (js2-node-abs-end node))))
6460
6461 (defun js2-get-jslint-globals-in (beg end)
6462 (let (res)
6463 (save-excursion
6464 (goto-char beg)
6465 (while (re-search-forward js2-mode-identifier-re end t)
6466 (let ((match (match-string 0)))
6467 (unless (member match '("true" "false"))
6468 (push match res)))))
6469 (nreverse res)))
6470
6471 ;;; IMenu support
6472
6473 ;; We currently only support imenu, but eventually should support speedbar and
6474 ;; possibly other browsing mechanisms.
6475
6476 ;; The basic strategy is to identify function assignment targets of the form
6477 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6478 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6479 ;; for imenu after parsing is finished.
6480
6481 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6482 ;; JavaScript, and the general problem is undecidable. However, several forms
6483 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6484 ;; include:
6485
6486 ;; function foo() -- function declaration
6487 ;; foo = function() -- function expression assigned to variable
6488 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6489 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6490 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6491 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6492 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6493 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6494 ;; function foo() {function bar() {...}} -- nested function
6495 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6496
6497 ;; This list boils down to a few forms that can be combined recursively.
6498 ;; Top-level named function declarations include both the left-hand (name)
6499 ;; and the right-hand (function value) expressions needed to produce an imenu
6500 ;; entry. The other "right-hand" forms we need to look for are:
6501 ;; - functions declared as props/getters/setters in object literals
6502 ;; - nested named function declarations
6503 ;; The "left-hand" expressions that functions can be assigned to include:
6504 ;; - local/global variables
6505 ;; - nested property-get expressions like a.b.c.d
6506 ;; - element gets like foo[10] or foo['bar'] where the index
6507 ;; expression can be trivially converted to a property name. They
6508 ;; effectively then become property gets.
6509
6510 ;; All the different definition types are canonicalized into the form
6511 ;; foo.bar.baz = position-of-function-keyword
6512
6513 ;; We need to build a trie-like structure for imenu. As an example,
6514 ;; consider the following JavaScript code:
6515
6516 ;; a = function() {...} // function at position 5
6517 ;; b = function() {...} // function at position 25
6518 ;; foo = function() {...} // function at position 100
6519 ;; foo.bar = function() {...} // function at position 200
6520 ;; foo.bar.baz = function() {...} // function at position 300
6521 ;; foo.bar.zab = function() {...} // function at position 400
6522
6523 ;; During parsing we accumulate an entry for each definition in
6524 ;; the variable `js2-imenu-recorder', like so:
6525
6526 ;; '((fn a 5)
6527 ;; (fn b 25)
6528 ;; (fn foo 100)
6529 ;; (fn foo bar 200)
6530 ;; (fn foo bar baz 300)
6531 ;; (fn foo bar zab 400))
6532
6533 ;; Where 'fn' is the respective function node.
6534 ;; After parsing these entries are merged into this alist-trie:
6535
6536 ;; '((a . 1)
6537 ;; (b . 2)
6538 ;; (foo (<definition> . 3)
6539 ;; (bar (<definition> . 6)
6540 ;; (baz . 100)
6541 ;; (zab . 200))))
6542
6543 ;; Note the wacky need for a <definition> name. The token can be anything
6544 ;; that isn't a valid JavaScript identifier, because you might make foo
6545 ;; a function and then start setting properties on it that are also functions.
6546
6547 (defun js2-prop-node-name (node)
6548 "Return the name of a node that may be a property-get/property-name.
6549 If NODE is not a valid name-node, string-node or integral number-node,
6550 returns nil. Otherwise returns the string name/value of the node."
6551 (cond
6552 ((js2-name-node-p node)
6553 (js2-name-node-name node))
6554 ((js2-string-node-p node)
6555 (js2-string-node-value node))
6556 ((and (js2-number-node-p node)
6557 (string-match "^[0-9]+$" (js2-number-node-value node)))
6558 (js2-number-node-value node))
6559 ((js2-this-node-p node)
6560 "this")))
6561
6562 (defun js2-node-qname-component (node)
6563 "Return the name of this node, if it contributes to a qname.
6564 Returns nil if the node doesn't contribute."
6565 (copy-sequence
6566 (or (js2-prop-node-name node)
6567 (if (and (js2-function-node-p node)
6568 (js2-function-node-name node))
6569 (js2-name-node-name (js2-function-node-name node))))))
6570
6571 (defun js2-record-imenu-entry (fn-node qname pos)
6572 "Add an entry to `js2-imenu-recorder'.
6573 FN-NODE should be the current item's function node.
6574
6575 Associate FN-NODE with its QNAME for later lookup.
6576 This is used in postprocessing the chain list. For each chain, we find
6577 the parent function, look up its qname, then prepend a copy of it to the chain."
6578 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6579 (unless js2-imenu-function-map
6580 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6581 (puthash fn-node qname js2-imenu-function-map))
6582
6583 (defun js2-record-imenu-functions (node &optional var)
6584 "Record function definitions for imenu.
6585 NODE is a function node or an object literal.
6586 VAR, if non-nil, is the expression that NODE is being assigned to.
6587 When passed arguments of wrong type, does nothing."
6588 (when js2-parse-ide-mode
6589 (let ((fun-p (js2-function-node-p node))
6590 qname left fname-node pos)
6591 (cond
6592 ;; non-anonymous function declaration?
6593 ((and fun-p
6594 (not var)
6595 (setq fname-node (js2-function-node-name node)))
6596 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6597 ;; for remaining forms, compute left-side tree branch first
6598 ((and var (setq qname (js2-compute-nested-prop-get var)))
6599 (cond
6600 ;; foo.bar.baz = function
6601 (fun-p
6602 (js2-record-imenu-entry node qname (js2-node-pos node)))
6603 ;; foo.bar.baz = object-literal
6604 ;; look for nested functions: {a: {b: function() {...} }}
6605 ((js2-object-node-p node)
6606 ;; Node position here is still absolute, since the parser
6607 ;; passes the assignment target and value expressions
6608 ;; to us before they are added as children of the assignment node.
6609 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6610
6611 (defun js2-compute-nested-prop-get (node)
6612 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6613 component nodes as a list. Otherwise return nil. Element-gets are treated
6614 as property-gets if the index expression is a string, or a positive integer."
6615 (let (left right head)
6616 (cond
6617 ((or (js2-name-node-p node)
6618 (js2-this-node-p node))
6619 (list node))
6620 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6621 ((js2-prop-get-node-p node) ; foo.bar
6622 (setq left (js2-prop-get-node-left node)
6623 right (js2-prop-get-node-right node))
6624 (if (setq head (js2-compute-nested-prop-get left))
6625 (nconc head (list right))))
6626 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6627 (setq left (js2-elem-get-node-target node)
6628 right (js2-elem-get-node-element node))
6629 (if (or (js2-string-node-p right) ; ['bar']
6630 (and (js2-number-node-p right) ; [10]
6631 (string-match "^[0-9]+$"
6632 (js2-number-node-value right))))
6633 (if (setq head (js2-compute-nested-prop-get left))
6634 (nconc head (list right))))))))
6635
6636 (defun js2-record-object-literal (node qname pos)
6637 "Recursively process an object literal looking for functions.
6638 NODE is an object literal that is the right-hand child of an assignment
6639 expression. QNAME is a list of nodes representing the assignment target,
6640 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6641 POS is the absolute position of the node.
6642 We do a depth-first traversal of NODE. For any functions we find,
6643 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6644 (let (left right prop-qname)
6645 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6646 (let ((left (js2-infix-node-left e))
6647 ;; Element positions are relative to the parent position.
6648 (pos (+ pos (js2-node-pos e))))
6649 (cond
6650 ;; foo: function() {...}
6651 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6652 (when (js2-prop-node-name left)
6653 ;; As a policy decision, we record the position of the property,
6654 ;; not the position of the `function' keyword, since the property
6655 ;; is effectively the name of the function.
6656 (js2-record-imenu-entry right (append qname (list left)) pos)))
6657 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6658 ((js2-object-node-p right)
6659 (js2-record-object-literal right
6660 (append qname (list (js2-infix-node-left e)))
6661 (+ pos (js2-node-pos right)))))))))
6662
6663 (defun js2-node-top-level-decl-p (node)
6664 "Return t if NODE's name is defined in the top-level scope.
6665 Also returns t if NODE's name is not defined in any scope, since it implies
6666 that it's an external variable, which must also be in the top-level scope."
6667 (let* ((name (js2-prop-node-name node))
6668 (this-scope (js2-node-get-enclosing-scope node))
6669 defining-scope)
6670 (cond
6671 ((js2-this-node-p node)
6672 nil)
6673 ((null this-scope)
6674 t)
6675 ((setq defining-scope (js2-get-defining-scope this-scope name))
6676 (js2-ast-root-p defining-scope))
6677 (t t))))
6678
6679 (defun js2-wrapper-function-p (node)
6680 "Return t if NODE is a function expression that's immediately invoked.
6681 NODE must be `js2-function-node'."
6682 (let ((parent (js2-node-parent node)))
6683 (or
6684 ;; function(){...}();
6685 (js2-call-node-p parent)
6686 (and (js2-paren-node-p parent)
6687 ;; (function(){...})();
6688 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6689 ;; (function(){...}).call(this);
6690 (and (js2-prop-get-node-p parent)
6691 (member (js2-name-node-name (js2-prop-get-node-right parent))
6692 '("call" "apply"))
6693 (js2-call-node-p (js2-node-parent parent))))))))
6694
6695 (defun js2-browse-postprocess-chains (entries)
6696 "Modify function-declaration name chains after parsing finishes.
6697 Some of the information is only available after the parse tree is complete.
6698 For instance, processing a nested scope requires a parent function node."
6699 (let (result head fn current-fn parent-qname qname p elem)
6700 (dolist (entry entries)
6701 ;; function node goes first
6702 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6703 ;; Examine head's defining scope:
6704 ;; Pre-processed chain, or top-level/external, keep as-is.
6705 (if (or (stringp head) (js2-node-top-level-decl-p head))
6706 (push chain result)
6707 (when (js2-this-node-p head)
6708 (setq chain (cdr chain))) ; discard this-node
6709 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6710 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6711 (when (eq parent-qname 'not-found)
6712 ;; anonymous function expressions are not recorded
6713 ;; during the parse, so we need to handle this case here
6714 (setq parent-qname
6715 (if (js2-wrapper-function-p fn)
6716 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6717 (if (js2-ast-root-p grandparent)
6718 nil
6719 (gethash grandparent js2-imenu-function-map 'skip)))
6720 'skip))
6721 (puthash fn parent-qname js2-imenu-function-map))
6722 (unless (eq parent-qname 'skip)
6723 ;; prefix parent fn qname to this chain.
6724 (let ((qname (append parent-qname chain)))
6725 (puthash current-fn (butlast qname) js2-imenu-function-map)
6726 (push qname result)))))))
6727 ;; finally replace each node in each chain with its name.
6728 (dolist (chain result)
6729 (setq p chain)
6730 (while p
6731 (if (js2-node-p (setq elem (car p)))
6732 (setcar p (js2-node-qname-component elem)))
6733 (setq p (cdr p))))
6734 result))
6735
6736 ;; Merge name chains into a trie-like tree structure of nested lists.
6737 ;; To simplify construction of the trie, we first build it out using the rule
6738 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6739 ;; [key, num-or-list]. The second element can be a number; if so, this key
6740 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6741 ;; associated with the key at this level.) Otherwise the second element is
6742 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6743 ;; a simple recursive formulation.
6744 ;;
6745 ;; js2-mode is building the data structure for imenu. The imenu documentation
6746 ;; claims that it's the structure above, but in practice it wants the children
6747 ;; at the same list level as the key for that level, which is how I've drawn
6748 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6749 ;; list wrapper around the children at each level.
6750 ;;
6751 ;; A completed nested imenu-alist entry looks like this:
6752 ;; '(("foo"
6753 ;; ("<definition>" . 7)
6754 ;; ("bar"
6755 ;; ("a" . 40)
6756 ;; ("b" . 60))))
6757 ;;
6758 ;; In particular, the documentation for `imenu--index-alist' says that
6759 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6760 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6761
6762 (defun js2-treeify (lst)
6763 "Convert (a b c d) to (a ((b ((c d)))))."
6764 (if (null (cddr lst)) ; list length <= 2
6765 lst
6766 (list (car lst) (list (js2-treeify (cdr lst))))))
6767
6768 (defun js2-build-alist-trie (chains trie)
6769 "Merge declaration name chains into a trie-like alist structure for imenu.
6770 CHAINS is the qname chain list produced during parsing. TRIE is a
6771 list of elements built up so far."
6772 (let (head tail pos branch kids)
6773 (dolist (chain chains)
6774 (setq head (car chain)
6775 tail (cdr chain)
6776 pos (if (numberp (car tail)) (car tail))
6777 branch (js2-find-if (lambda (n)
6778 (string= (car n) head))
6779 trie)
6780 kids (second branch))
6781 (cond
6782 ;; case 1: this key isn't in the trie yet
6783 ((null branch)
6784 (if trie
6785 (setcdr (last trie) (list (js2-treeify chain)))
6786 (setq trie (list (js2-treeify chain)))))
6787 ;; case 2: key is present with a single number entry: replace w/ list
6788 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6789 ;; ("<definition>" 20)))
6790 ((numberp kids)
6791 (setcar (cdr branch)
6792 (list (list "<definition-1>" kids)
6793 (if pos
6794 (list "<definition-2>" pos)
6795 (js2-treeify tail)))))
6796 ;; case 3: key is there (with kids), and we're a number entry
6797 (pos
6798 (setcdr (last kids)
6799 (list
6800 (list (format "<definition-%d>"
6801 (1+ (loop for kid in kids
6802 count (eq ?< (aref (car kid) 0)))))
6803 pos))))
6804 ;; case 4: key is there with kids, need to merge in our chain
6805 (t
6806 (js2-build-alist-trie (list tail) kids))))
6807 trie))
6808
6809 (defun js2-flatten-trie (trie)
6810 "Convert TRIE to imenu-format.
6811 Recurses through nodes, and for each one whose second element is a list,
6812 appends the list's flattened elements to the current element. Also
6813 changes the tails into conses. For instance, this pre-flattened trie
6814
6815 '(a ((b 20)
6816 (c ((d 30)
6817 (e 40)))))
6818
6819 becomes
6820
6821 '(a (b . 20)
6822 (c (d . 30)
6823 (e . 40)))
6824
6825 Note that the root of the trie has no key, just a list of chains.
6826 This is also true for the value of any key with multiple children,
6827 e.g. key 'c' in the example above."
6828 (cond
6829 ((listp (car trie))
6830 (mapcar #'js2-flatten-trie trie))
6831 (t
6832 (if (numberp (second trie))
6833 (cons (car trie) (second trie))
6834 ;; else pop list and append its kids
6835 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6836
6837 (defun js2-build-imenu-index ()
6838 "Turn `js2-imenu-recorder' into an imenu data structure."
6839 (unless (eq js2-imenu-recorder 'empty)
6840 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
6841 (result (js2-build-alist-trie chains nil)))
6842 (js2-flatten-trie result))))
6843
6844 (defun js2-test-print-chains (chains)
6845 "Print a list of qname chains.
6846 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
6847 i.e. one or more nodes, and an integer position as the list tail."
6848 (mapconcat (lambda (chain)
6849 (concat "("
6850 (mapconcat (lambda (elem)
6851 (if (js2-node-p elem)
6852 (or (js2-node-qname-component elem)
6853 "nil")
6854 (number-to-string elem)))
6855 chain
6856 " ")
6857 ")"))
6858 chains
6859 "\n"))
6860
6861 ;;; Parser
6862
6863 (defconst js2-version "1.8.5"
6864 "Version of JavaScript supported.")
6865
6866 (defmacro js2-record-face (face)
6867 "Record a style run of FACE for the current token."
6868 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
6869
6870 (defsubst js2-node-end (n)
6871 "Computes the absolute end of node N.
6872 Use with caution! Assumes `js2-node-pos' is -absolute-, which
6873 is only true until the node is added to its parent; i.e., while parsing."
6874 (+ (js2-node-pos n)
6875 (js2-node-len n)))
6876
6877 (defun js2-record-comment ()
6878 "Record a comment in `js2-scanned-comments'."
6879 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
6880 :format js2-ts-comment-type)
6881 js2-scanned-comments)
6882 (when js2-parse-ide-mode
6883 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
6884 'font-lock-doc-face
6885 'font-lock-comment-face))
6886 (when (memq js2-ts-comment-type '(html preprocessor))
6887 ;; Tell cc-engine the bounds of the comment.
6888 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
6889
6890 ;; This function is called depressingly often, so it should be fast.
6891 ;; Most of the time it's looking at the same token it peeked before.
6892 (defun js2-peek-token ()
6893 "Return the next token without consuming it.
6894 If previous token was consumed, calls scanner to get new token.
6895 If previous token was -not- consumed, returns it (idempotent).
6896
6897 This function will not return a newline (js2-EOL) - instead, it
6898 gobbles newlines until it finds a non-newline token, and flags
6899 that token as appearing just after a newline.
6900
6901 This function will also not return a js2-COMMENT. Instead, it
6902 records comments found in `js2-scanned-comments'. If the token
6903 returned by this function immediately follows a jsdoc comment,
6904 the token is flagged as such.
6905
6906 Note that this function always returned the un-flagged token!
6907 The flags, if any, are saved in `js2-current-flagged-token'."
6908 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
6909 js2-current-token ; most common case - return already-peeked token
6910 (let ((tt (js2-get-token)) ; call scanner
6911 saw-eol
6912 face)
6913 ;; process comments and whitespace
6914 (while (or (= tt js2-EOL)
6915 (= tt js2-COMMENT))
6916 (if (= tt js2-EOL)
6917 (setq saw-eol t)
6918 (setq saw-eol nil)
6919 (if js2-record-comments
6920 (js2-record-comment)))
6921 (setq tt (js2-get-token))) ; call scanner
6922 (setq js2-current-token tt
6923 js2-current-flagged-token (if saw-eol
6924 (logior tt js2-ti-after-eol)
6925 tt))
6926 ;; perform lexical fontification as soon as token is scanned
6927 (when js2-parse-ide-mode
6928 (cond
6929 ((minusp tt)
6930 (js2-record-face 'js2-error))
6931 ((setq face (aref js2-kwd-tokens tt))
6932 (js2-record-face face))
6933 ((and (= tt js2-NAME)
6934 (equal js2-ts-string "undefined"))
6935 (js2-record-face 'font-lock-constant-face))))
6936 tt))) ; return unflagged token
6937
6938 (defun js2-peek-flagged-token ()
6939 "Return the current token along with any flags set for it."
6940 (js2-peek-token)
6941 js2-current-flagged-token)
6942
6943 (defsubst js2-consume-token ()
6944 (setq js2-current-flagged-token js2-EOF))
6945
6946 (defun js2-next-token ()
6947 (prog1
6948 (js2-peek-token)
6949 (js2-consume-token)))
6950
6951 (defun js2-next-flagged-token ()
6952 (js2-peek-token)
6953 (prog1 js2-current-flagged-token
6954 (js2-consume-token)))
6955
6956 (defun js2-match-token (match)
6957 "Consume and return t if next token matches MATCH, a bytecode.
6958 Returns nil and consumes nothing if MATCH is not the next token."
6959 (if (/= (js2-peek-token) match)
6960 nil
6961 (js2-consume-token)
6962 t))
6963
6964 (defun js2-match-contextual-kwd (name)
6965 "Consume and return t if next token is `js2-NAME', and its
6966 string is NAME. Returns nil and does nothing otherwise."
6967 (if (or (/= (js2-peek-token) js2-NAME)
6968 (not (string= js2-ts-string name)))
6969 nil
6970 (js2-consume-token)
6971 (js2-record-face 'font-lock-keyword-face)
6972 t))
6973
6974 (defun js2-valid-prop-name-token (tt)
6975 (or (= tt js2-NAME)
6976 (when (and js2-allow-keywords-as-property-names
6977 (plusp tt)
6978 (aref js2-kwd-tokens tt))
6979 (js2-save-name-token-data js2-token-beg (js2-token-name tt))
6980 t)))
6981
6982 (defun js2-match-prop-name ()
6983 "Consume token and return t if next token is a valid property name.
6984 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
6985 is non-nil and it's a keyword token."
6986 (if (js2-valid-prop-name-token (js2-peek-token))
6987 (progn
6988 (js2-consume-token)
6989 t)
6990 nil))
6991
6992 (defun js2-must-match-prop-name (msg-id &optional pos len)
6993 (if (js2-match-prop-name)
6994 t
6995 (js2-report-error msg-id nil pos len)
6996 nil))
6997
6998 (defun js2-peek-token-or-eol ()
6999 "Return js2-EOL if the current token immediately follows a newline.
7000 Else returns the current token. Used in situations where we don't
7001 consider certain token types valid if they are preceded by a newline.
7002 One example is the postfix ++ or -- operator, which has to be on the
7003 same line as its operand."
7004 (let ((tt (js2-peek-token)))
7005 ;; Check for last peeked token flags
7006 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7007 js2-EOL
7008 tt)))
7009
7010 (defun js2-set-check-for-label ()
7011 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7012 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7013
7014 (defun js2-must-match (token msg-id &optional pos len)
7015 "Match next token to token code TOKEN, or record a syntax error.
7016 MSG-ID is the error message to report if the match fails.
7017 Returns t on match, nil if no match."
7018 (if (js2-match-token token)
7019 t
7020 (js2-report-error msg-id nil pos len)
7021 nil))
7022
7023 (defsubst js2-inside-function ()
7024 (plusp js2-nesting-of-function))
7025
7026 (defun js2-set-requires-activation ()
7027 (if (js2-function-node-p js2-current-script-or-fn)
7028 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7029
7030 (defun js2-check-activation-name (name token)
7031 (when (js2-inside-function)
7032 ;; skip language-version 1.2 check from Rhino
7033 (if (or (string= "arguments" name)
7034 (and js2-compiler-activation-names ; only used in codegen
7035 (gethash name js2-compiler-activation-names)))
7036 (js2-set-requires-activation))))
7037
7038 (defun js2-set-is-generator ()
7039 (if (js2-function-node-p js2-current-script-or-fn)
7040 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7041
7042 (defun js2-must-have-xml ()
7043 (unless js2-compiler-xml-available
7044 (js2-report-error "msg.XML.not.available")))
7045
7046 (defun js2-push-scope (scope)
7047 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7048 (assert (js2-scope-p scope))
7049 (assert (null (js2-scope-parent-scope scope)))
7050 (assert (not (eq js2-current-scope scope)))
7051 (setf (js2-scope-parent-scope scope) js2-current-scope
7052 js2-current-scope scope))
7053
7054 (defsubst js2-pop-scope ()
7055 (setq js2-current-scope
7056 (js2-scope-parent-scope js2-current-scope)))
7057
7058 (defun js2-enter-loop (loop-node)
7059 (push loop-node js2-loop-set)
7060 (push loop-node js2-loop-and-switch-set)
7061 (js2-push-scope loop-node)
7062 ;; Tell the current labeled statement (if any) its statement,
7063 ;; and set the jump target of the first label to the loop.
7064 ;; These are used in `js2-parse-continue' to verify that the
7065 ;; continue target is an actual labeled loop. (And for codegen.)
7066 (when js2-labeled-stmt
7067 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7068 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7069 js2-labeled-stmt))) loop-node)))
7070
7071 (defun js2-exit-loop ()
7072 (pop js2-loop-set)
7073 (pop js2-loop-and-switch-set)
7074 (js2-pop-scope))
7075
7076 (defsubst js2-enter-switch (switch-node)
7077 (push switch-node js2-loop-and-switch-set))
7078
7079 (defsubst js2-exit-switch ()
7080 (pop js2-loop-and-switch-set))
7081
7082 (defun js2-parse (&optional buf cb)
7083 "Tell the js2 parser to parse a region of JavaScript.
7084
7085 BUF is a buffer or buffer name containing the code to parse.
7086 Call `narrow-to-region' first to parse only part of the buffer.
7087
7088 The returned AST root node is given some additional properties:
7089 `node-count' - total number of nodes in the AST
7090 `buffer' - BUF. The buffer it refers to may change or be killed,
7091 so the value is not necessarily reliable.
7092
7093 An optional callback CB can be specified to report parsing
7094 progress. If `(functionp CB)' returns t, it will be called with
7095 the current line number once before parsing begins, then again
7096 each time the lexer reaches a new line number.
7097
7098 CB can also be a list of the form `(symbol cb ...)' to specify
7099 multiple callbacks with different criteria. Each symbol is a
7100 criterion keyword, and the following element is the callback to
7101 call
7102
7103 :line - called whenever the line number changes
7104 :token - called for each new token consumed
7105
7106 The list of criteria could be extended to include entering or
7107 leaving a statement, an expression, or a function definition."
7108 (if (and cb (not (functionp cb)))
7109 (error "criteria callbacks not yet implemented"))
7110 (let ((inhibit-point-motion-hooks t)
7111 (js2-compiler-xml-available (>= js2-language-version 160))
7112 ;; This is a recursive-descent parser, so give it a big stack.
7113 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7114 (max-specpdl-size (max max-specpdl-size 3000))
7115 (case-fold-search nil)
7116 ast)
7117 (message nil) ; clear any error message from previous parse
7118 (with-current-buffer (or buf (current-buffer))
7119 (setq js2-scanned-comments nil
7120 js2-parsed-errors nil
7121 js2-parsed-warnings nil
7122 js2-imenu-recorder nil
7123 js2-imenu-function-map nil
7124 js2-label-set nil)
7125 (js2-init-scanner)
7126 (setq ast (with-silent-modifications
7127 (js2-do-parse)))
7128 (unless js2-ts-hit-eof
7129 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7130 (setf (js2-ast-root-errors ast) js2-parsed-errors
7131 (js2-ast-root-warnings ast) js2-parsed-warnings)
7132 ;; if we didn't find any declarations, put a dummy in this list so we
7133 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7134 (unless js2-imenu-recorder
7135 (setq js2-imenu-recorder 'empty))
7136 (run-hooks 'js2-parse-finished-hook)
7137 ast)))
7138
7139 ;; Corresponds to Rhino's Parser.parse() method.
7140 (defun js2-do-parse ()
7141 "Parse current buffer starting from current point.
7142 Scanner should be initialized."
7143 (let ((pos js2-ts-cursor)
7144 (end js2-ts-cursor) ; in case file is empty
7145 root n tt)
7146 ;; initialize buffer-local parsing vars
7147 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7148 js2-current-script-or-fn root
7149 js2-current-scope root
7150 js2-current-flagged-token js2-EOF
7151 js2-nesting-of-function 0
7152 js2-labeled-stmt nil
7153 js2-recorded-identifiers nil) ; for js2-highlight
7154 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7155 (if (= tt js2-FUNCTION)
7156 (progn
7157 (js2-consume-token)
7158 (setq n (js2-parse-function (if js2-called-by-compile-function
7159 'FUNCTION_EXPRESSION
7160 'FUNCTION_STATEMENT))))
7161 ;; not a function - parse a statement
7162 (setq n (js2-parse-statement)))
7163 ;; add function or statement to script
7164 (setq end (js2-node-end n))
7165 (js2-block-node-push root n))
7166 ;; add comments to root in lexical order
7167 (when js2-scanned-comments
7168 ;; if we find a comment beyond end of normal kids, use its end
7169 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7170 (dolist (comment js2-scanned-comments)
7171 (push comment (js2-ast-root-comments root))
7172 (js2-node-add-children root comment)))
7173 (setf (js2-node-len root) (- end pos))
7174 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7175 ;; Give extensions a chance to muck with things before highlighting starts.
7176 (let ((js2-additional-externs js2-additional-externs))
7177 (save-excursion
7178 (run-hooks 'js2-post-parse-callbacks))
7179 (js2-highlight-undeclared-vars))
7180 root))
7181
7182 (defun js2-function-parser ()
7183 (js2-consume-token)
7184 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7185
7186 (defun js2-parse-function-closure-body (fn-node)
7187 "Parse a JavaScript 1.8 function closure body."
7188 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7189 (if js2-ts-hit-eof
7190 (js2-report-error "msg.no.brace.body" nil
7191 (js2-node-pos fn-node)
7192 (- js2-ts-cursor (js2-node-pos fn-node)))
7193 (js2-node-add-children fn-node
7194 (setf (js2-function-node-body fn-node)
7195 (js2-parse-expr t))))))
7196
7197 (defun js2-parse-function-body (fn-node)
7198 (js2-must-match js2-LC "msg.no.brace.body"
7199 (js2-node-pos fn-node)
7200 (- js2-ts-cursor (js2-node-pos fn-node)))
7201 (let ((pos js2-token-beg) ; LC position
7202 (pn (make-js2-block-node)) ; starts at LC position
7203 tt
7204 end)
7205 (incf js2-nesting-of-function)
7206 (unwind-protect
7207 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7208 (= tt js2-EOF)
7209 (= tt js2-RC)))
7210 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7211 (js2-parse-statement)
7212 (js2-consume-token)
7213 (js2-parse-function 'FUNCTION_STATEMENT))))
7214 (decf js2-nesting-of-function))
7215 (setq end js2-token-end) ; assume no curly and leave at current token
7216 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7217 (setq end js2-token-end))
7218 (setf (js2-node-pos pn) pos
7219 (js2-node-len pn) (- end pos))
7220 (setf (js2-function-node-body fn-node) pn)
7221 (js2-node-add-children fn-node pn)
7222 pn))
7223
7224 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7225 "Declare and fontify destructuring parameters inside NODE.
7226 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7227 (cond
7228 ((js2-name-node-p node)
7229 (let (leftpos)
7230 (js2-define-symbol decl-type (js2-name-node-name node)
7231 node ignore-not-in-block)
7232 (when face
7233 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7234 (+ leftpos (js2-node-len node))
7235 face 'record))))
7236 ((js2-object-node-p node)
7237 (dolist (elem (js2-object-node-elems node))
7238 (js2-define-destruct-symbols
7239 (if (js2-object-prop-node-p elem)
7240 (js2-object-prop-node-right elem)
7241 ;; abbreviated destructuring {a, b}
7242 elem)
7243 decl-type face ignore-not-in-block)))
7244 ((js2-array-node-p node)
7245 (dolist (elem (js2-array-node-elems node))
7246 (when elem
7247 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7248 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7249 (js2-node-len node)))))
7250
7251 (defun js2-parse-function-params (fn-node pos)
7252 (if (js2-match-token js2-RP)
7253 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7254 (let (params len param default-found rest-param-at)
7255 (loop for tt = (js2-peek-token)
7256 do
7257 (cond
7258 ;; destructuring param
7259 ((or (= tt js2-LB) (= tt js2-LC))
7260 (when default-found
7261 (js2-report-error "msg.no.default.after.default.param"))
7262 (setq param (js2-parse-destruct-primary-expr))
7263 (js2-define-destruct-symbols param
7264 js2-LP
7265 'js2-function-param)
7266 (push param params))
7267 ;; variable name
7268 (t
7269 (when (and (>= js2-language-version 200)
7270 (js2-match-token js2-TRIPLEDOT)
7271 (not rest-param-at))
7272 ;; to report errors if there are more parameters
7273 (setq rest-param-at (length params)))
7274 (js2-must-match js2-NAME "msg.no.parm")
7275 (js2-record-face 'js2-function-param)
7276 (setq param (js2-create-name-node))
7277 (js2-define-symbol js2-LP js2-ts-string param)
7278 ;; default parameter value
7279 (when (or (and default-found
7280 (not rest-param-at)
7281 (js2-must-match js2-ASSIGN
7282 "msg.no.default.after.default.param"
7283 (js2-node-pos param)
7284 (js2-node-len param)))
7285 (and (>= js2-language-version 200)
7286 (js2-match-token js2-ASSIGN)))
7287 (let* ((pos (js2-node-pos param))
7288 (tt js2-current-token)
7289 (op-pos (- js2-token-beg pos))
7290 (left param)
7291 (right (js2-parse-assign-expr))
7292 (len (- (js2-node-end right) pos)))
7293 (setq param (make-js2-assign-node
7294 :type tt :pos pos :len len :op-pos op-pos
7295 :left left :right right)
7296 default-found t)
7297 (js2-node-add-children param left right)))
7298 (push param params)))
7299 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7300 (js2-report-error "msg.param.after.rest" nil
7301 (js2-node-pos param) (js2-node-len param)))
7302 while
7303 (js2-match-token js2-COMMA))
7304 (when (js2-must-match js2-RP "msg.no.paren.after.parms")
7305 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7306 (when rest-param-at
7307 (setf (js2-function-node-rest-p fn-node) t))
7308 (dolist (p params)
7309 (js2-node-add-children fn-node p)
7310 (push p (js2-function-node-params fn-node))))))
7311
7312 (defun js2-check-inconsistent-return-warning (fn-node name)
7313 "Possibly show inconsistent-return warning.
7314 Last token scanned is the close-curly for the function body."
7315 (when (and js2-mode-show-strict-warnings
7316 js2-strict-inconsistent-return-warning
7317 (not (js2-has-consistent-return-usage
7318 (js2-function-node-body fn-node))))
7319 ;; Have it extend from close-curly to bol or beginning of block.
7320 (let ((pos (save-excursion
7321 (goto-char js2-token-end)
7322 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7323 (point-at-bol))))
7324 (end js2-token-end))
7325 (if (plusp (js2-name-node-length name))
7326 (js2-add-strict-warning "msg.no.return.value"
7327 (js2-name-node-name name) pos end)
7328 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7329
7330 (defun js2-parse-function (function-type)
7331 "Function parser. FUNCTION-TYPE is a symbol."
7332 (let ((pos js2-token-beg) ; start of 'function' keyword
7333 name name-beg name-end fn-node lp
7334 (synthetic-type function-type)
7335 member-expr-node)
7336 ;; parse function name, expression, or non-name (anonymous)
7337 (cond
7338 ;; function foo(...)
7339 ((js2-match-token js2-NAME)
7340 (setq name (js2-create-name-node t)
7341 name-beg js2-token-beg
7342 name-end js2-token-end)
7343 (unless (js2-match-token js2-LP)
7344 (when js2-allow-member-expr-as-function-name
7345 ;; function foo.bar(...)
7346 (setq member-expr-node name
7347 name nil
7348 member-expr-node (js2-parse-member-expr-tail
7349 nil member-expr-node)))
7350 (js2-must-match js2-LP "msg.no.paren.parms")))
7351 ((js2-match-token js2-LP)
7352 nil) ; anonymous function: leave name as null
7353 (t
7354 ;; function random-member-expr(...)
7355 (when js2-allow-member-expr-as-function-name
7356 ;; Note that memberExpr can not start with '(' like
7357 ;; in function (1+2).toString(), because 'function (' already
7358 ;; processed as anonymous function
7359 (setq member-expr-node (js2-parse-member-expr)))
7360 (js2-must-match js2-LP "msg.no.paren.parms")))
7361 (if (= js2-current-token js2-LP) ; eventually matched LP?
7362 (setq lp js2-token-beg))
7363 (if member-expr-node
7364 (progn
7365 (setq synthetic-type 'FUNCTION_EXPRESSION)
7366 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7367 (if name
7368 (js2-set-face name-beg name-end
7369 'font-lock-function-name-face 'record)))
7370 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7371 (plusp (js2-name-node-length name)))
7372 ;; Function statements define a symbol in the enclosing scope
7373 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7374 (setf fn-node (make-js2-function-node :pos pos
7375 :name name
7376 :form function-type
7377 :lp (if lp (- lp pos))))
7378 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7379 ;; 1. Nested functions are not affected by the dynamic scope flag
7380 ;; as dynamic scope is already a parent of their scope.
7381 ;; 2. Functions defined under the with statement also immune to
7382 ;; this setup, in which case dynamic scope is ignored in favor
7383 ;; of the with object.
7384 (setf (js2-function-node-ignore-dynamic fn-node) t))
7385 ;; dynamically bind all the per-function variables
7386 (let ((js2-current-script-or-fn fn-node)
7387 (js2-current-scope fn-node)
7388 (js2-nesting-of-with 0)
7389 (js2-end-flags 0)
7390 js2-label-set
7391 js2-loop-set
7392 js2-loop-and-switch-set)
7393 (js2-parse-function-params fn-node pos)
7394 (if (and (>= js2-language-version 180)
7395 (/= (js2-peek-token) js2-LC))
7396 (js2-parse-function-closure-body fn-node)
7397 (js2-parse-function-body fn-node))
7398 (if name
7399 (js2-node-add-children fn-node name))
7400 (js2-check-inconsistent-return-warning fn-node name)
7401 ;; Function expressions define a name only in the body of the
7402 ;; function, and only if not hidden by a parameter name
7403 (if (and name
7404 (eq synthetic-type 'FUNCTION_EXPRESSION)
7405 (null (js2-scope-get-symbol js2-current-scope
7406 (js2-name-node-name name))))
7407 (js2-define-symbol js2-FUNCTION
7408 (js2-name-node-name name)
7409 fn-node))
7410 (if (and name
7411 (not (eq function-type 'FUNCTION_EXPRESSION)))
7412 (js2-record-imenu-functions fn-node)))
7413 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7414 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7415 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7416 ;; We wait until after parsing the function to set its parent scope,
7417 ;; since `js2-define-symbol' needs the defining-scope check to stop
7418 ;; at the function boundary when checking for redeclarations.
7419 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7420 fn-node))
7421
7422 (defun js2-parse-statements (&optional parent)
7423 "Parse a statement list. Last token consumed must be js2-LC.
7424
7425 PARENT can be a `js2-block-node', in which case the statements are
7426 appended to PARENT. Otherwise a new `js2-block-node' is created
7427 and returned.
7428
7429 This function does not match the closing js2-RC: the caller
7430 matches the RC so it can provide a suitable error message if not
7431 matched. This means it's up to the caller to set the length of
7432 the node to include the closing RC. The node start pos is set to
7433 the absolute buffer start position, and the caller should fix it
7434 up to be relative to the parent node. All children of this block
7435 node are given relative start positions and correct lengths."
7436 (let ((pn (or parent (make-js2-block-node)))
7437 tt)
7438 (setf (js2-node-pos pn) js2-token-beg)
7439 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7440 (/= tt js2-RC))
7441 (js2-block-node-push pn (js2-parse-statement)))
7442 pn))
7443
7444 (defun js2-parse-statement ()
7445 (let (tt pn beg end)
7446 ;; coarse-grained user-interrupt check - needs work
7447 (and js2-parse-interruptable-p
7448 (zerop (% (incf js2-parse-stmt-count)
7449 js2-statements-per-pause))
7450 (input-pending-p)
7451 (throw 'interrupted t))
7452 (setq pn (js2-statement-helper))
7453 ;; no-side-effects warning check
7454 (unless (js2-node-has-side-effects pn)
7455 (setq end (js2-node-end pn))
7456 (save-excursion
7457 (goto-char end)
7458 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7459 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7460 pn))
7461
7462 ;; These correspond to the switch cases in Parser.statementHelper
7463 (defconst js2-parsers
7464 (let ((parsers (make-vector js2-num-tokens
7465 #'js2-parse-expr-stmt)))
7466 (aset parsers js2-BREAK #'js2-parse-break)
7467 (aset parsers js2-CONST #'js2-parse-const-var)
7468 (aset parsers js2-CONTINUE #'js2-parse-continue)
7469 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7470 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7471 (aset parsers js2-DO #'js2-parse-do)
7472 (aset parsers js2-FOR #'js2-parse-for)
7473 (aset parsers js2-FUNCTION #'js2-function-parser)
7474 (aset parsers js2-IF #'js2-parse-if)
7475 (aset parsers js2-LC #'js2-parse-block)
7476 (aset parsers js2-LET #'js2-parse-let-stmt)
7477 (aset parsers js2-NAME #'js2-parse-name-or-label)
7478 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7479 (aset parsers js2-SEMI #'js2-parse-semi)
7480 (aset parsers js2-SWITCH #'js2-parse-switch)
7481 (aset parsers js2-THROW #'js2-parse-throw)
7482 (aset parsers js2-TRY #'js2-parse-try)
7483 (aset parsers js2-VAR #'js2-parse-const-var)
7484 (aset parsers js2-WHILE #'js2-parse-while)
7485 (aset parsers js2-WITH #'js2-parse-with)
7486 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7487 parsers)
7488 "A vector mapping token types to parser functions.")
7489
7490 (defun js2-parse-warn-missing-semi (beg end)
7491 (and js2-mode-show-strict-warnings
7492 js2-strict-missing-semi-warning
7493 (js2-add-strict-warning
7494 "msg.missing.semi" nil
7495 ;; back up to beginning of statement or line
7496 (max beg (save-excursion
7497 (goto-char end)
7498 (point-at-bol)))
7499 end)))
7500
7501 (defconst js2-no-semi-insertion
7502 (list js2-IF
7503 js2-SWITCH
7504 js2-WHILE
7505 js2-DO
7506 js2-FOR
7507 js2-TRY
7508 js2-WITH
7509 js2-LC
7510 js2-ERROR
7511 js2-SEMI
7512 js2-FUNCTION)
7513 "List of tokens that don't do automatic semicolon insertion.")
7514
7515 (defconst js2-autoinsert-semi-and-warn
7516 (list js2-ERROR js2-EOF js2-RC))
7517
7518 (defun js2-statement-helper ()
7519 (let* ((tt (js2-peek-token))
7520 (first-tt tt)
7521 (beg js2-token-beg)
7522 (parser (if (= tt js2-ERROR)
7523 #'js2-parse-semi
7524 (aref js2-parsers tt)))
7525 pn
7526 tt-flagged)
7527 ;; If the statement is set, then it's been told its label by now.
7528 (and js2-labeled-stmt
7529 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7530 (setq js2-labeled-stmt nil))
7531 (setq pn (funcall parser))
7532 ;; Don't do auto semi insertion for certain statement types.
7533 (unless (or (memq first-tt js2-no-semi-insertion)
7534 (js2-labeled-stmt-node-p pn))
7535 (js2-auto-insert-semicolon pn))
7536 pn))
7537
7538 (defun js2-auto-insert-semicolon (pn)
7539 (let* ((tt-flagged (js2-peek-flagged-token))
7540 (tt (logand tt-flagged js2-clear-ti-mask))
7541 (pos (js2-node-pos pn)))
7542 (cond
7543 ((= tt js2-SEMI)
7544 ;; Consume ';' as a part of expression
7545 (js2-consume-token)
7546 ;; extend the node bounds to include the semicolon.
7547 (setf (js2-node-len pn) (- js2-token-end pos)))
7548 ((memq tt js2-autoinsert-semi-and-warn)
7549 ;; Autoinsert ;
7550 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7551 (t
7552 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7553 ;; Report error if no EOL or autoinsert ';' otherwise
7554 (js2-report-error "msg.no.semi.stmt")
7555 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7556
7557 (defun js2-parse-condition ()
7558 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7559 The parens are discarded and the expression node is returned.
7560 The `pos' field of the return value is set to an absolute position
7561 that must be fixed up by the caller.
7562 Return value is a list (EXPR LP RP), with absolute paren positions."
7563 (let (pn lp rp)
7564 (if (js2-must-match js2-LP "msg.no.paren.cond")
7565 (setq lp js2-token-beg))
7566 (setq pn (js2-parse-expr))
7567 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7568 (setq rp js2-token-beg))
7569 ;; Report strict warning on code like "if (a = 7) ..."
7570 (if (and js2-strict-cond-assign-warning
7571 (js2-assign-node-p pn))
7572 (js2-add-strict-warning "msg.equal.as.assign" nil
7573 (js2-node-pos pn)
7574 (+ (js2-node-pos pn)
7575 (js2-node-len pn))))
7576 (list pn lp rp)))
7577
7578 (defun js2-parse-if ()
7579 "Parser for if-statement. Last matched token must be js2-IF."
7580 (let ((pos js2-token-beg)
7581 cond if-true if-false else-pos end pn)
7582 (js2-consume-token)
7583 (setq cond (js2-parse-condition)
7584 if-true (js2-parse-statement)
7585 if-false (if (js2-match-token js2-ELSE)
7586 (progn
7587 (setq else-pos (- js2-token-beg pos))
7588 (js2-parse-statement)))
7589 end (js2-node-end (or if-false if-true))
7590 pn (make-js2-if-node :pos pos
7591 :len (- end pos)
7592 :condition (car cond)
7593 :then-part if-true
7594 :else-part if-false
7595 :else-pos else-pos
7596 :lp (js2-relpos (second cond) pos)
7597 :rp (js2-relpos (third cond) pos)))
7598 (js2-node-add-children pn (car cond) if-true if-false)
7599 pn))
7600
7601 (defun js2-parse-switch ()
7602 "Parser for if-statement. Last matched token must be js2-SWITCH."
7603 (let ((pos js2-token-beg)
7604 tt pn discriminant has-default case-expr case-node
7605 case-pos cases stmt lp rp)
7606 (js2-consume-token)
7607 (if (js2-must-match js2-LP "msg.no.paren.switch")
7608 (setq lp js2-token-beg))
7609 (setq discriminant (js2-parse-expr)
7610 pn (make-js2-switch-node :discriminant discriminant
7611 :pos pos
7612 :lp (js2-relpos lp pos)))
7613 (js2-node-add-children pn discriminant)
7614 (js2-enter-switch pn)
7615 (unwind-protect
7616 (progn
7617 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7618 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7619 (js2-must-match js2-LC "msg.no.brace.switch")
7620 (catch 'break
7621 (while t
7622 (setq tt (js2-next-token)
7623 case-pos js2-token-beg)
7624 (cond
7625 ((= tt js2-RC)
7626 (setf (js2-node-len pn) (- js2-token-end pos))
7627 (throw 'break nil)) ; done
7628 ((= tt js2-CASE)
7629 (setq case-expr (js2-parse-expr))
7630 (js2-must-match js2-COLON "msg.no.colon.case"))
7631 ((= tt js2-DEFAULT)
7632 (if has-default
7633 (js2-report-error "msg.double.switch.default"))
7634 (setq has-default t
7635 case-expr nil)
7636 (js2-must-match js2-COLON "msg.no.colon.case"))
7637 (t
7638 (js2-report-error "msg.bad.switch")
7639 (throw 'break nil)))
7640 (setq case-node (make-js2-case-node :pos case-pos
7641 :len (- js2-token-end case-pos)
7642 :expr case-expr))
7643 (js2-node-add-children case-node case-expr)
7644 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7645 (/= tt js2-CASE)
7646 (/= tt js2-DEFAULT)
7647 (/= tt js2-EOF))
7648 (setf stmt (js2-parse-statement)
7649 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7650 (js2-block-node-push case-node stmt))
7651 (push case-node cases)))
7652 ;; add cases last, as pushing reverses the order to be correct
7653 (dolist (kid cases)
7654 (js2-node-add-children pn kid)
7655 (push kid (js2-switch-node-cases pn)))
7656 pn) ; return value
7657 (js2-exit-switch))))
7658
7659 (defun js2-parse-while ()
7660 "Parser for while-statement. Last matched token must be js2-WHILE."
7661 (let ((pos js2-token-beg)
7662 (pn (make-js2-while-node))
7663 cond body)
7664 (js2-consume-token)
7665 (js2-enter-loop pn)
7666 (unwind-protect
7667 (progn
7668 (setf cond (js2-parse-condition)
7669 (js2-while-node-condition pn) (car cond)
7670 body (js2-parse-statement)
7671 (js2-while-node-body pn) body
7672 (js2-node-len pn) (- (js2-node-end body) pos)
7673 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7674 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7675 (js2-node-add-children pn body (car cond)))
7676 (js2-exit-loop))
7677 pn))
7678
7679 (defun js2-parse-do ()
7680 "Parser for do-statement. Last matched token must be js2-DO."
7681 (let ((pos js2-token-beg)
7682 (pn (make-js2-do-node))
7683 cond body end)
7684 (js2-consume-token)
7685 (js2-enter-loop pn)
7686 (unwind-protect
7687 (progn
7688 (setq body (js2-parse-statement))
7689 (js2-must-match js2-WHILE "msg.no.while.do")
7690 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7691 cond (js2-parse-condition)
7692 (js2-do-node-condition pn) (car cond)
7693 (js2-do-node-body pn) body
7694 end js2-ts-cursor
7695 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7696 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7697 (js2-node-add-children pn (car cond) body))
7698 (js2-exit-loop))
7699 ;; Always auto-insert semicolon to follow SpiderMonkey:
7700 ;; It is required by ECMAScript but is ignored by the rest of
7701 ;; world; see bug 238945
7702 (if (js2-match-token js2-SEMI)
7703 (setq end js2-ts-cursor))
7704 (setf (js2-node-len pn) (- end pos))
7705 pn))
7706
7707 (defun js2-parse-for ()
7708 "Parser for for-statement. Last matched token must be js2-FOR.
7709 Parses for, for-in, and for each-in statements."
7710 (let ((for-pos js2-token-beg)
7711 pn is-for-each is-for-in-or-of is-for-of
7712 in-pos each-pos tmp-pos
7713 init ; Node init is also foo in 'foo in object'
7714 cond ; Node cond is also object in 'foo in object'
7715 incr ; 3rd section of for-loop initializer
7716 body tt lp rp)
7717 (js2-consume-token)
7718 ;; See if this is a for each () instead of just a for ()
7719 (when (js2-match-token js2-NAME)
7720 (if (string= "each" js2-ts-string)
7721 (progn
7722 (setq is-for-each t
7723 each-pos (- js2-token-beg for-pos)) ; relative
7724 (js2-record-face 'font-lock-keyword-face))
7725 (js2-report-error "msg.no.paren.for")))
7726 (if (js2-must-match js2-LP "msg.no.paren.for")
7727 (setq lp (- js2-token-beg for-pos)))
7728 (setq tt (js2-peek-token))
7729 ;; 'for' makes local scope
7730 (js2-push-scope (make-js2-scope))
7731 (unwind-protect
7732 ;; parse init clause
7733 (let ((js2-in-for-init t)) ; set as dynamic variable
7734 (cond
7735 ((= tt js2-SEMI)
7736 (setq init (make-js2-empty-expr-node)))
7737 ((or (= tt js2-VAR) (= tt js2-LET))
7738 (js2-consume-token)
7739 (setq init (js2-parse-variables tt js2-token-beg)))
7740 (t
7741 (setq init (js2-parse-expr)))))
7742 (if (or (js2-match-token js2-IN)
7743 (and (>= js2-language-version 200)
7744 (js2-match-contextual-kwd "of")
7745 (setq is-for-of t)))
7746 (setq is-for-in-or-of t
7747 in-pos (- js2-token-beg for-pos)
7748 ;; scope of iteration target object is not the scope we've created above.
7749 ;; stash current scope temporary.
7750 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7751 (js2-parse-expr))) ; object over which we're iterating
7752 ;; else ordinary for loop - parse cond and incr
7753 (js2-must-match js2-SEMI "msg.no.semi.for")
7754 (setq cond (if (= (js2-peek-token) js2-SEMI)
7755 (make-js2-empty-expr-node) ; no loop condition
7756 (js2-parse-expr)))
7757 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7758 (setq tmp-pos js2-token-end
7759 incr (if (= (js2-peek-token) js2-RP)
7760 (make-js2-empty-expr-node :pos tmp-pos)
7761 (js2-parse-expr))))
7762 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7763 (setq rp (- js2-token-beg for-pos)))
7764 (if (not is-for-in-or-of)
7765 (setq pn (make-js2-for-node :init init
7766 :condition cond
7767 :update incr
7768 :lp lp
7769 :rp rp))
7770 ;; cond could be null if 'in obj' got eaten by the init node.
7771 (if (js2-infix-node-p init)
7772 ;; it was (foo in bar) instead of (var foo in bar)
7773 (setq cond (js2-infix-node-right init)
7774 init (js2-infix-node-left init))
7775 (if (and (js2-var-decl-node-p init)
7776 (> (length (js2-var-decl-node-kids init)) 1))
7777 (js2-report-error "msg.mult.index")))
7778 (setq pn (make-js2-for-in-node :iterator init
7779 :object cond
7780 :in-pos in-pos
7781 :foreach-p is-for-each
7782 :each-pos each-pos
7783 :forof-p is-for-of
7784 :lp lp
7785 :rp rp)))
7786 (unwind-protect
7787 (progn
7788 (js2-enter-loop pn)
7789 ;; We have to parse the body -after- creating the loop node,
7790 ;; so that the loop node appears in the js2-loop-set, allowing
7791 ;; break/continue statements to find the enclosing loop.
7792 (setf body (js2-parse-statement)
7793 (js2-loop-node-body pn) body
7794 (js2-node-pos pn) for-pos
7795 (js2-node-len pn) (- (js2-node-end body) for-pos))
7796 (js2-node-add-children pn init cond incr body))
7797 ;; finally
7798 (js2-exit-loop))
7799 (js2-pop-scope))
7800 pn))
7801
7802 (defun js2-parse-try ()
7803 "Parser for try-statement. Last matched token must be js2-TRY."
7804 (let ((try-pos js2-token-beg)
7805 try-end
7806 try-block
7807 catch-blocks
7808 finally-block
7809 saw-default-catch
7810 peek
7811 param
7812 catch-cond
7813 catch-node
7814 guard-kwd
7815 catch-pos
7816 finally-pos
7817 pn
7818 block
7819 lp
7820 rp)
7821 (js2-consume-token)
7822 (if (/= (js2-peek-token) js2-LC)
7823 (js2-report-error "msg.no.brace.try"))
7824 (setq try-block (js2-parse-statement)
7825 try-end (js2-node-end try-block)
7826 peek (js2-peek-token))
7827 (cond
7828 ((= peek js2-CATCH)
7829 (while (js2-match-token js2-CATCH)
7830 (setq catch-pos js2-token-beg
7831 guard-kwd nil
7832 catch-cond nil
7833 lp nil
7834 rp nil)
7835 (if saw-default-catch
7836 (js2-report-error "msg.catch.unreachable"))
7837 (if (js2-must-match js2-LP "msg.no.paren.catch")
7838 (setq lp (- js2-token-beg catch-pos)))
7839 (js2-push-scope (make-js2-scope))
7840 (let ((tt (js2-peek-token)))
7841 (cond
7842 ;; destructuring pattern
7843 ;; catch ({ message, file }) { ... }
7844 ((or (= tt js2-LB) (= tt js2-LC))
7845 (setq param (js2-parse-destruct-primary-expr))
7846 (js2-define-destruct-symbols param js2-LET nil))
7847 ;; simple name
7848 (t
7849 (js2-must-match js2-NAME "msg.bad.catchcond")
7850 (setq param (js2-create-name-node))
7851 (js2-define-symbol js2-LET js2-ts-string param))))
7852 ;; pattern guard
7853 (if (js2-match-token js2-IF)
7854 (setq guard-kwd (- js2-token-beg catch-pos)
7855 catch-cond (js2-parse-expr))
7856 (setq saw-default-catch t))
7857 (if (js2-must-match js2-RP "msg.bad.catchcond")
7858 (setq rp (- js2-token-beg catch-pos)))
7859 (js2-must-match js2-LC "msg.no.brace.catchblock")
7860 (setq block (js2-parse-statements)
7861 try-end (js2-node-end block)
7862 catch-node (make-js2-catch-node :pos catch-pos
7863 :param param
7864 :guard-expr catch-cond
7865 :guard-kwd guard-kwd
7866 :block block
7867 :lp lp
7868 :rp rp))
7869 (js2-pop-scope)
7870 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7871 (setq try-end js2-token-beg))
7872 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7873 (js2-node-len catch-node) (- try-end catch-pos))
7874 (js2-node-add-children catch-node param catch-cond block)
7875 (push catch-node catch-blocks)))
7876 ((/= peek js2-FINALLY)
7877 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7878 (js2-node-pos try-block)
7879 (- (setq try-end (js2-node-end try-block))
7880 (js2-node-pos try-block)))))
7881 (when (js2-match-token js2-FINALLY)
7882 (setq finally-pos js2-token-beg
7883 block (js2-parse-statement)
7884 try-end (js2-node-end block)
7885 finally-block (make-js2-finally-node :pos finally-pos
7886 :len (- try-end finally-pos)
7887 :body block))
7888 (js2-node-add-children finally-block block))
7889 (setq pn (make-js2-try-node :pos try-pos
7890 :len (- try-end try-pos)
7891 :try-block try-block
7892 :finally-block finally-block))
7893 (js2-node-add-children pn try-block finally-block)
7894 ;; push them onto the try-node, which reverses and corrects their order
7895 (dolist (cb catch-blocks)
7896 (js2-node-add-children pn cb)
7897 (push cb (js2-try-node-catch-clauses pn)))
7898 pn))
7899
7900 (defun js2-parse-throw ()
7901 "Parser for throw-statement. Last matched token must be js2-THROW."
7902 (let ((pos js2-token-beg)
7903 expr pn)
7904 (js2-consume-token)
7905 (if (= (js2-peek-token-or-eol) js2-EOL)
7906 ;; ECMAScript does not allow new lines before throw expression,
7907 ;; see bug 256617
7908 (js2-report-error "msg.bad.throw.eol"))
7909 (setq expr (js2-parse-expr)
7910 pn (make-js2-throw-node :pos pos
7911 :len (- (js2-node-end expr) pos)
7912 :expr expr))
7913 (js2-node-add-children pn expr)
7914 pn))
7915
7916 (defun js2-match-jump-label-name (label-name)
7917 "If break/continue specified a label, return that label's labeled stmt.
7918 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
7919 does not match an existing label, reports an error and returns nil."
7920 (let ((bundle (cdr (assoc label-name js2-label-set))))
7921 (if (null bundle)
7922 (js2-report-error "msg.undef.label"))
7923 bundle))
7924
7925 (defun js2-parse-break ()
7926 "Parser for break-statement. Last matched token must be js2-BREAK."
7927 (let ((pos js2-token-beg)
7928 (end js2-token-end)
7929 break-target ; statement to break from
7930 break-label ; in "break foo", name-node representing the foo
7931 labels ; matching labeled statement to break to
7932 pn)
7933 (js2-consume-token) ; `break'
7934 (when (eq (js2-peek-token-or-eol) js2-NAME)
7935 (js2-consume-token)
7936 (setq break-label (js2-create-name-node)
7937 end (js2-node-end break-label)
7938 ;; matchJumpLabelName only matches if there is one
7939 labels (js2-match-jump-label-name js2-ts-string)
7940 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
7941 (unless (or break-target break-label)
7942 ;; no break target specified - try for innermost enclosing loop/switch
7943 (if (null js2-loop-and-switch-set)
7944 (unless break-label
7945 (js2-report-error "msg.bad.break" nil pos (length "break")))
7946 (setq break-target (car js2-loop-and-switch-set))))
7947 (setq pn (make-js2-break-node :pos pos
7948 :len (- end pos)
7949 :label break-label
7950 :target break-target))
7951 (js2-node-add-children pn break-label) ; but not break-target
7952 pn))
7953
7954 (defun js2-parse-continue ()
7955 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
7956 (let ((pos js2-token-beg)
7957 (end js2-token-end)
7958 label ; optional user-specified label, a `js2-name-node'
7959 labels ; current matching labeled stmt, if any
7960 target ; the `js2-loop-node' target of this continue stmt
7961 pn)
7962 (js2-consume-token) ; `continue'
7963 (when (= (js2-peek-token-or-eol) js2-NAME)
7964 (js2-consume-token)
7965 (setq label (js2-create-name-node)
7966 end (js2-node-end label)
7967 ;; matchJumpLabelName only matches if there is one
7968 labels (js2-match-jump-label-name js2-ts-string)))
7969 (cond
7970 ((null labels) ; no current label to go to
7971 (if (null js2-loop-set) ; no loop to continue to
7972 (js2-report-error "msg.continue.outside" nil pos
7973 (length "continue"))
7974 (setq target (car js2-loop-set)))) ; innermost enclosing loop
7975 (t
7976 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
7977 (setq target (js2-labeled-stmt-node-stmt labels))
7978 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
7979 (setq pn (make-js2-continue-node :pos pos
7980 :len (- end pos)
7981 :label label
7982 :target target))
7983 (js2-node-add-children pn label) ; but not target - it's not our child
7984 pn))
7985
7986 (defun js2-parse-with ()
7987 "Parser for with-statement. Last matched token must be js2-WITH."
7988 (js2-consume-token)
7989 (let ((pos js2-token-beg)
7990 obj body pn lp rp)
7991 (if (js2-must-match js2-LP "msg.no.paren.with")
7992 (setq lp js2-token-beg))
7993 (setq obj (js2-parse-expr))
7994 (if (js2-must-match js2-RP "msg.no.paren.after.with")
7995 (setq rp js2-token-beg))
7996 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
7997 (setq body (js2-parse-statement)))
7998 (setq pn (make-js2-with-node :pos pos
7999 :len (- (js2-node-end body) pos)
8000 :object obj
8001 :body body
8002 :lp (js2-relpos lp pos)
8003 :rp (js2-relpos rp pos)))
8004 (js2-node-add-children pn obj body)
8005 pn))
8006
8007 (defun js2-parse-const-var ()
8008 "Parser for var- or const-statement.
8009 Last matched token must be js2-CONST or js2-VAR."
8010 (let ((tt (js2-peek-token))
8011 (pos js2-token-beg)
8012 expr pn)
8013 (js2-consume-token)
8014 (setq expr (js2-parse-variables tt js2-token-beg)
8015 pn (make-js2-expr-stmt-node :pos pos
8016 :len (- (js2-node-end expr) pos)
8017 :expr expr))
8018 (js2-node-add-children pn expr)
8019 pn))
8020
8021 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8022 (let ((pn (make-js2-expr-stmt-node :pos pos
8023 :len (js2-node-len expr)
8024 :type (if (js2-inside-function)
8025 js2-EXPR_VOID
8026 js2-EXPR_RESULT)
8027 :expr expr)))
8028 (if add-child
8029 (js2-node-add-children pn expr))
8030 pn))
8031
8032 (defun js2-parse-let-stmt ()
8033 "Parser for let-statement. Last matched token must be js2-LET."
8034 (js2-consume-token)
8035 (let ((pos js2-token-beg)
8036 expr pn)
8037 (if (= (js2-peek-token) js2-LP)
8038 ;; let expression in statement context
8039 (setq expr (js2-parse-let pos 'statement)
8040 pn (js2-wrap-with-expr-stmt pos expr t))
8041 ;; else we're looking at a statement like let x=6, y=7;
8042 (setf expr (js2-parse-variables js2-LET pos)
8043 pn (js2-wrap-with-expr-stmt pos expr t)
8044 (js2-node-type pn) js2-EXPR_RESULT))
8045 pn))
8046
8047 (defun js2-parse-ret-yield ()
8048 (js2-parse-return-or-yield (js2-peek-token) nil))
8049
8050 (defconst js2-parse-return-stmt-enders
8051 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8052
8053 (defsubst js2-now-all-set (before after mask)
8054 "Return whether or not the bits in the mask have changed to all set.
8055 BEFORE is bits before change, AFTER is bits after change, and MASK is
8056 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8057 but not BEFORE."
8058 (and (/= (logand before mask) mask)
8059 (= (logand after mask) mask)))
8060
8061 (defun js2-parse-return-or-yield (tt expr-context)
8062 (let ((pos js2-token-beg)
8063 (end js2-token-end)
8064 (before js2-end-flags)
8065 (inside-function (js2-inside-function))
8066 e ret name)
8067 (unless inside-function
8068 (js2-report-error (if (eq tt js2-RETURN)
8069 "msg.bad.return"
8070 "msg.bad.yield")))
8071 (js2-consume-token)
8072 ;; This is ugly, but we don't want to require a semicolon.
8073 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8074 (setq e (js2-parse-expr)
8075 end (js2-node-end e)))
8076 (cond
8077 ((eq tt js2-RETURN)
8078 (js2-set-flag js2-end-flags (if (null e)
8079 js2-end-returns
8080 js2-end-returns-value))
8081 (setq ret (make-js2-return-node :pos pos
8082 :len (- end pos)
8083 :retval e))
8084 (js2-node-add-children ret e)
8085 ;; See if we need a strict mode warning.
8086 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8087 ;; more thorough and accurate than this before/after flag check.
8088 ;; E.g. if there's a finally-block that always returns, we shouldn't
8089 ;; show a warning generated by inconsistent returns in the catch blocks.
8090 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8091 ;; so we know which returns/yields to highlight, and we should get rid of
8092 ;; all the checking in `js2-parse-return-or-yield'.
8093 (if (and js2-strict-inconsistent-return-warning
8094 (js2-now-all-set before js2-end-flags
8095 (logior js2-end-returns js2-end-returns-value)))
8096 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8097 (t
8098 (unless (js2-inside-function)
8099 (js2-report-error "msg.bad.yield"))
8100 (js2-set-flag js2-end-flags js2-end-yields)
8101 (setq ret (make-js2-yield-node :pos pos
8102 :len (- end pos)
8103 :value e))
8104 (js2-node-add-children ret e)
8105 (unless expr-context
8106 (setq e ret
8107 ret (js2-wrap-with-expr-stmt pos e t))
8108 (js2-set-requires-activation)
8109 (js2-set-is-generator))))
8110 ;; see if we are mixing yields and value returns.
8111 (when (and inside-function
8112 (js2-now-all-set before js2-end-flags
8113 (logior js2-end-yields js2-end-returns-value)))
8114 (setq name (js2-function-name js2-current-script-or-fn))
8115 (if (zerop (length name))
8116 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8117 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8118 ret))
8119
8120 (defun js2-parse-debugger ()
8121 (js2-consume-token)
8122 (make-js2-keyword-node :type js2-DEBUGGER))
8123
8124 (defun js2-parse-block ()
8125 "Parser for a curly-delimited statement block.
8126 Last token matched must be `js2-LC'."
8127 (let ((pos js2-token-beg)
8128 (pn (make-js2-scope)))
8129 (js2-consume-token)
8130 (js2-push-scope pn)
8131 (unwind-protect
8132 (progn
8133 (js2-parse-statements pn)
8134 (js2-must-match js2-RC "msg.no.brace.block")
8135 (setf (js2-node-len pn) (- js2-token-end pos)))
8136 (js2-pop-scope))
8137 pn))
8138
8139 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8140 (defun js2-parse-semi ()
8141 "Parse a statement or handle an error.
8142 Last matched token is `js2-SEMI' or `js2-ERROR'."
8143 (let ((tt (js2-peek-token)) pos len)
8144 (js2-consume-token)
8145 (if (eq tt js2-SEMI)
8146 (make-js2-empty-expr-node :len 1)
8147 (setq pos js2-token-beg
8148 len (- js2-token-beg pos))
8149 (js2-report-error "msg.syntax" nil pos len)
8150 (make-js2-error-node :pos pos :len len))))
8151
8152 (defun js2-parse-default-xml-namespace ()
8153 "Parse a `default xml namespace = <expr>' e4x statement."
8154 (let ((pos js2-token-beg)
8155 end len expr unary es)
8156 (js2-consume-token)
8157 (js2-must-have-xml)
8158 (js2-set-requires-activation)
8159 (setq len (- js2-ts-cursor pos))
8160 (unless (and (js2-match-token js2-NAME)
8161 (string= js2-ts-string "xml"))
8162 (js2-report-error "msg.bad.namespace" nil pos len))
8163 (unless (and (js2-match-token js2-NAME)
8164 (string= js2-ts-string "namespace"))
8165 (js2-report-error "msg.bad.namespace" nil pos len))
8166 (unless (js2-match-token js2-ASSIGN)
8167 (js2-report-error "msg.bad.namespace" nil pos len))
8168 (setq expr (js2-parse-expr)
8169 end (js2-node-end expr)
8170 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8171 :pos pos
8172 :len (- end pos)
8173 :operand expr))
8174 (js2-node-add-children unary expr)
8175 (make-js2-expr-stmt-node :pos pos
8176 :len (- end pos)
8177 :expr unary)))
8178
8179 (defun js2-record-label (label bundle)
8180 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8181 (js2-consume-token)
8182 (let ((name (js2-label-node-name label))
8183 labeled-stmt
8184 dup)
8185 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8186 ;; flag both labels if possible when used in editing mode
8187 (if (and js2-parse-ide-mode
8188 (setq dup (js2-get-label-by-name labeled-stmt name)))
8189 (js2-report-error "msg.dup.label" nil
8190 (js2-node-abs-pos dup) (js2-node-len dup)))
8191 (js2-report-error "msg.dup.label" nil
8192 (js2-node-pos label) (js2-node-len label)))
8193 (js2-labeled-stmt-node-add-label bundle label)
8194 (js2-node-add-children bundle label)
8195 ;; Add one reference to the bundle per label in `js2-label-set'
8196 (push (cons name bundle) js2-label-set)))
8197
8198 (defun js2-parse-name-or-label ()
8199 "Parser for identifier or label. Last token matched must be js2-NAME.
8200 Called when we found a name in a statement context. If it's a label, we gather
8201 up any following labels and the next non-label statement into a
8202 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8203 expression and return it wrapped in a `js2-expr-stmt-node'."
8204 (let ((pos js2-token-beg)
8205 (end js2-token-end)
8206 expr stmt pn bundle
8207 (continue t))
8208 ;; set check for label and call down to `js2-parse-primary-expr'
8209 (js2-set-check-for-label)
8210 (setq expr (js2-parse-expr))
8211 (if (/= (js2-node-type expr) js2-LABEL)
8212 ;; Parsed non-label expression - wrap with expression stmt.
8213 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8214 ;; else parsed a label
8215 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8216 (js2-record-label expr bundle)
8217 ;; look for more labels
8218 (while (and continue (= (js2-peek-token) js2-NAME))
8219 (js2-set-check-for-label)
8220 (setq expr (js2-parse-expr))
8221 (if (/= (js2-node-type expr) js2-LABEL)
8222 (progn
8223 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8224 continue nil)
8225 (js2-auto-insert-semicolon stmt))
8226 (js2-record-label expr bundle)))
8227 ;; no more labels; now parse the labeled statement
8228 (unwind-protect
8229 (unless stmt
8230 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8231 (setq stmt (js2-statement-helper))))
8232 ;; remove the labels for this statement from the global set
8233 (dolist (label (js2-labeled-stmt-node-labels bundle))
8234 (setq js2-label-set (remove label js2-label-set))))
8235 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8236 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8237 (js2-node-add-children bundle stmt)
8238 bundle)))
8239
8240 (defun js2-parse-expr-stmt ()
8241 "Default parser in statement context, if no recognized statement found."
8242 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8243
8244 (defun js2-parse-variables (decl-type pos)
8245 "Parse a comma-separated list of variable declarations.
8246 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8247
8248 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8249 For 'var' or 'const', the keyword should be the token last scanned.
8250
8251 POS is the position where the node should start. It's sometimes the
8252 var/const/let keyword, and other times the beginning of the first token
8253 in the first variable declaration.
8254
8255 Returns the parsed `js2-var-decl-node' expression node."
8256 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8257 :pos pos))
8258 destructuring kid-pos tt init name end nbeg nend vi
8259 (continue t))
8260 ;; Example:
8261 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8262 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8263 ;; var {a, b} = baz;
8264 (while continue
8265 (setq destructuring nil
8266 name nil
8267 tt (js2-peek-token)
8268 kid-pos js2-token-beg
8269 end js2-token-end
8270 init nil)
8271 (if (or (= tt js2-LB) (= tt js2-LC))
8272 ;; Destructuring assignment, e.g., var [a, b] = ...
8273 (setq destructuring (js2-parse-destruct-primary-expr)
8274 end (js2-node-end destructuring))
8275 ;; Simple variable name
8276 (when (js2-must-match js2-NAME "msg.bad.var")
8277 (setq name (js2-create-name-node)
8278 nbeg js2-token-beg
8279 nend js2-token-end
8280 end nend)
8281 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8282 (when (js2-match-token js2-ASSIGN)
8283 (setq init (js2-parse-assign-expr)
8284 end (js2-node-end init))
8285 (js2-record-imenu-functions init name))
8286 (when name
8287 (js2-set-face nbeg nend (if (js2-function-node-p init)
8288 'font-lock-function-name-face
8289 'font-lock-variable-name-face)
8290 'record))
8291 (setq vi (make-js2-var-init-node :pos kid-pos
8292 :len (- end kid-pos)
8293 :type decl-type))
8294 (if destructuring
8295 (progn
8296 (if (and (null init) (not js2-in-for-init))
8297 (js2-report-error "msg.destruct.assign.no.init"))
8298 (js2-define-destruct-symbols destructuring
8299 decl-type
8300 'font-lock-variable-name-face)
8301 (setf (js2-var-init-node-target vi) destructuring))
8302 (setf (js2-var-init-node-target vi) name))
8303 (setf (js2-var-init-node-initializer vi) init)
8304 (js2-node-add-children vi name destructuring init)
8305 (js2-block-node-push result vi)
8306 (unless (js2-match-token js2-COMMA)
8307 (setq continue nil)))
8308 (setf (js2-node-len result) (- end pos))
8309 result))
8310
8311 (defun js2-parse-let (pos &optional stmt-p)
8312 "Parse a let expression or statement.
8313 A let-expression is of the form `let (vars) expr'.
8314 A let-statment is of the form `let (vars) {statements}'.
8315 The third form of let is a variable declaration list, handled
8316 by `js2-parse-variables'."
8317 (let ((pn (make-js2-let-node :pos pos))
8318 beg vars body)
8319 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8320 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8321 (js2-push-scope pn)
8322 (unwind-protect
8323 (progn
8324 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8325 (if (js2-must-match js2-RP "msg.no.paren.let")
8326 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8327 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8328 ;; let statement
8329 (progn
8330 (js2-consume-token)
8331 (setf beg js2-token-beg ; position stmt at LC
8332 body (js2-parse-statements))
8333 (js2-must-match js2-RC "msg.no.curly.let")
8334 (setf (js2-node-len body) (- js2-token-end beg)
8335 (js2-node-len pn) (- js2-token-end pos)
8336 (js2-let-node-body pn) body
8337 (js2-node-type pn) js2-LET))
8338 ;; let expression
8339 (setf body (js2-parse-expr)
8340 (js2-node-len pn) (- (js2-node-end body) pos)
8341 (js2-let-node-body pn) body))
8342 (js2-node-add-children pn vars body))
8343 (js2-pop-scope))
8344 pn))
8345
8346 (defun js2-define-new-symbol (decl-type name node &optional scope)
8347 (js2-scope-put-symbol (or scope js2-current-scope)
8348 name
8349 (make-js2-symbol decl-type name node)))
8350
8351 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8352 "Define a symbol in the current scope.
8353 If NODE is non-nil, it is the AST node associated with the symbol."
8354 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8355 (symbol (if defining-scope
8356 (js2-scope-get-symbol defining-scope name)))
8357 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8358 (cond
8359 ((and symbol ; already defined
8360 (or (= sdt js2-CONST) ; old version is const
8361 (= decl-type js2-CONST) ; new version is const
8362 ;; two let-bound vars in this block have same name
8363 (and (= sdt js2-LET)
8364 (eq defining-scope js2-current-scope))))
8365 (js2-report-error
8366 (cond
8367 ((= sdt js2-CONST) "msg.const.redecl")
8368 ((= sdt js2-LET) "msg.let.redecl")
8369 ((= sdt js2-VAR) "msg.var.redecl")
8370 ((= sdt js2-FUNCTION) "msg.function.redecl")
8371 (t "msg.parm.redecl"))
8372 name))
8373 ((= decl-type js2-LET)
8374 (if (and (not ignore-not-in-block)
8375 (or (= (js2-node-type js2-current-scope) js2-IF)
8376 (js2-loop-node-p js2-current-scope)))
8377 (js2-report-error "msg.let.decl.not.in.block")
8378 (js2-define-new-symbol decl-type name node)))
8379 ((or (= decl-type js2-VAR)
8380 (= decl-type js2-CONST)
8381 (= decl-type js2-FUNCTION))
8382 (if symbol
8383 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8384 (js2-add-strict-warning "msg.var.redecl" name)
8385 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8386 (js2-add-strict-warning "msg.var.hides.arg" name)))
8387 (js2-define-new-symbol decl-type name node
8388 js2-current-script-or-fn)))
8389 ((= decl-type js2-LP)
8390 (if symbol
8391 ;; must be duplicate parameter. Second parameter hides the
8392 ;; first, so go ahead and add the second pararameter
8393 (js2-report-warning "msg.dup.parms" name))
8394 (js2-define-new-symbol decl-type name node))
8395 (t (js2-code-bug)))))
8396
8397 (defun js2-parse-expr (&optional oneshot)
8398 (let* ((pn (js2-parse-assign-expr))
8399 (pos (js2-node-pos pn))
8400 left
8401 right
8402 op-pos)
8403 (while (and (not oneshot)
8404 (js2-match-token js2-COMMA))
8405 (setq op-pos (- js2-token-beg pos)) ; relative
8406 (if (= (js2-peek-token) js2-YIELD)
8407 (js2-report-error "msg.yield.parenthesized"))
8408 (setq right (js2-parse-assign-expr)
8409 left pn
8410 pn (make-js2-infix-node :type js2-COMMA
8411 :pos pos
8412 :len (- js2-ts-cursor pos)
8413 :op-pos op-pos
8414 :left left
8415 :right right))
8416 (js2-node-add-children pn left right))
8417 pn))
8418
8419 (defun js2-parse-assign-expr ()
8420 (let ((tt (js2-peek-token))
8421 (pos js2-token-beg)
8422 pn left right op-pos)
8423 (if (= tt js2-YIELD)
8424 (js2-parse-return-or-yield tt t)
8425 ;; not yield - parse assignment expression
8426 (setq pn (js2-parse-cond-expr)
8427 tt (js2-peek-token))
8428 (when (and (<= js2-first-assign tt)
8429 (<= tt js2-last-assign))
8430 ;; tt express assignment (=, |=, ^=, ..., %=)
8431 (js2-consume-token)
8432 (setq op-pos (- js2-token-beg pos) ; relative
8433 left pn
8434 right (js2-parse-assign-expr)
8435 pn (make-js2-assign-node :type tt
8436 :pos pos
8437 :len (- (js2-node-end right) pos)
8438 :op-pos op-pos
8439 :left left
8440 :right right))
8441 (when js2-parse-ide-mode
8442 (js2-highlight-assign-targets pn left right)
8443 (js2-record-imenu-functions right left))
8444 ;; do this last so ide checks above can use absolute positions
8445 (js2-node-add-children pn left right))
8446 pn)))
8447
8448 (defun js2-parse-cond-expr ()
8449 (let ((pos js2-token-beg)
8450 (pn (js2-parse-or-expr))
8451 test-expr
8452 if-true
8453 if-false
8454 q-pos
8455 c-pos)
8456 (when (js2-match-token js2-HOOK)
8457 (setq q-pos (- js2-token-beg pos)
8458 if-true (js2-parse-assign-expr))
8459 (js2-must-match js2-COLON "msg.no.colon.cond")
8460 (setq c-pos (- js2-token-beg pos)
8461 if-false (js2-parse-assign-expr)
8462 test-expr pn
8463 pn (make-js2-cond-node :pos pos
8464 :len (- (js2-node-end if-false) pos)
8465 :test-expr test-expr
8466 :true-expr if-true
8467 :false-expr if-false
8468 :q-pos q-pos
8469 :c-pos c-pos))
8470 (js2-node-add-children pn test-expr if-true if-false))
8471 pn))
8472
8473 (defun js2-make-binary (type left parser)
8474 "Helper for constructing a binary-operator AST node.
8475 LEFT is the left-side-expression, already parsed, and the
8476 binary operator should have just been matched.
8477 PARSER is a function to call to parse the right operand,
8478 or a `js2-node' struct if it has already been parsed."
8479 (let* ((pos (js2-node-pos left))
8480 (op-pos (- js2-token-beg pos))
8481 (right (if (js2-node-p parser)
8482 parser
8483 (funcall parser)))
8484 (pn (make-js2-infix-node :type type
8485 :pos pos
8486 :len (- (js2-node-end right) pos)
8487 :op-pos op-pos
8488 :left left
8489 :right right)))
8490 (js2-node-add-children pn left right)
8491 pn))
8492
8493 (defun js2-parse-or-expr ()
8494 (let ((pn (js2-parse-and-expr)))
8495 (when (js2-match-token js2-OR)
8496 (setq pn (js2-make-binary js2-OR
8497 pn
8498 'js2-parse-or-expr)))
8499 pn))
8500
8501 (defun js2-parse-and-expr ()
8502 (let ((pn (js2-parse-bit-or-expr)))
8503 (when (js2-match-token js2-AND)
8504 (setq pn (js2-make-binary js2-AND
8505 pn
8506 'js2-parse-and-expr)))
8507 pn))
8508
8509 (defun js2-parse-bit-or-expr ()
8510 (let ((pn (js2-parse-bit-xor-expr)))
8511 (while (js2-match-token js2-BITOR)
8512 (setq pn (js2-make-binary js2-BITOR
8513 pn
8514 'js2-parse-bit-xor-expr)))
8515 pn))
8516
8517 (defun js2-parse-bit-xor-expr ()
8518 (let ((pn (js2-parse-bit-and-expr)))
8519 (while (js2-match-token js2-BITXOR)
8520 (setq pn (js2-make-binary js2-BITXOR
8521 pn
8522 'js2-parse-bit-and-expr)))
8523 pn))
8524
8525 (defun js2-parse-bit-and-expr ()
8526 (let ((pn (js2-parse-eq-expr)))
8527 (while (js2-match-token js2-BITAND)
8528 (setq pn (js2-make-binary js2-BITAND
8529 pn
8530 'js2-parse-eq-expr)))
8531 pn))
8532
8533 (defconst js2-parse-eq-ops
8534 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8535
8536 (defun js2-parse-eq-expr ()
8537 (let ((pn (js2-parse-rel-expr))
8538 tt)
8539 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8540 (js2-consume-token)
8541 (setq pn (js2-make-binary tt
8542 pn
8543 'js2-parse-rel-expr)))
8544 pn))
8545
8546 (defconst js2-parse-rel-ops
8547 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8548
8549 (defun js2-parse-rel-expr ()
8550 (let ((pn (js2-parse-shift-expr))
8551 (continue t)
8552 tt)
8553 (while continue
8554 (setq tt (js2-peek-token))
8555 (cond
8556 ((and js2-in-for-init (= tt js2-IN))
8557 (setq continue nil))
8558 ((memq tt js2-parse-rel-ops)
8559 (js2-consume-token)
8560 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8561 (t
8562 (setq continue nil))))
8563 pn))
8564
8565 (defconst js2-parse-shift-ops
8566 (list js2-LSH js2-URSH js2-RSH))
8567
8568 (defun js2-parse-shift-expr ()
8569 (let ((pn (js2-parse-add-expr))
8570 tt
8571 (continue t))
8572 (while continue
8573 (setq tt (js2-peek-token))
8574 (if (memq tt js2-parse-shift-ops)
8575 (progn
8576 (js2-consume-token)
8577 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8578 (setq continue nil)))
8579 pn))
8580
8581 (defun js2-parse-add-expr ()
8582 (let ((pn (js2-parse-mul-expr))
8583 tt
8584 (continue t))
8585 (while continue
8586 (setq tt (js2-peek-token))
8587 (if (or (= tt js2-ADD) (= tt js2-SUB))
8588 (progn
8589 (js2-consume-token)
8590 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8591 (setq continue nil)))
8592 pn))
8593
8594 (defconst js2-parse-mul-ops
8595 (list js2-MUL js2-DIV js2-MOD))
8596
8597 (defun js2-parse-mul-expr ()
8598 (let ((pn (js2-parse-unary-expr))
8599 tt
8600 (continue t))
8601 (while continue
8602 (setq tt (js2-peek-token))
8603 (if (memq tt js2-parse-mul-ops)
8604 (progn
8605 (js2-consume-token)
8606 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8607 (setq continue nil)))
8608 pn))
8609
8610 (defun js2-make-unary (type parser &rest args)
8611 "Make a unary node of type TYPE.
8612 PARSER is either a node (for postfix operators) or a function to call
8613 to parse the operand (for prefix operators)."
8614 (let* ((pos js2-token-beg)
8615 (postfix (js2-node-p parser))
8616 (expr (if postfix
8617 parser
8618 (apply parser args)))
8619 end
8620 pn)
8621 (if postfix ; e.g. i++
8622 (setq pos (js2-node-pos expr)
8623 end js2-token-end)
8624 (setq end (js2-node-end expr)))
8625 (setq pn (make-js2-unary-node :type type
8626 :pos pos
8627 :len (- end pos)
8628 :operand expr))
8629 (js2-node-add-children pn expr)
8630 pn))
8631
8632 (defconst js2-incrementable-node-types
8633 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8634 "Node types that can be the operand of a ++ or -- operator.")
8635
8636 (defun js2-check-bad-inc-dec (tt beg end unary)
8637 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8638 js2-incrementable-node-types)
8639 (js2-report-error (if (= tt js2-INC)
8640 "msg.bad.incr"
8641 "msg.bad.decr")
8642 nil beg (- end beg))))
8643
8644 (defun js2-parse-unary-expr ()
8645 (let ((tt (js2-peek-token))
8646 pn expr beg end)
8647 (cond
8648 ((or (= tt js2-VOID)
8649 (= tt js2-NOT)
8650 (= tt js2-BITNOT)
8651 (= tt js2-TYPEOF))
8652 (js2-consume-token)
8653 (js2-make-unary tt 'js2-parse-unary-expr))
8654 ((= tt js2-ADD)
8655 (js2-consume-token)
8656 ;; Convert to special POS token in decompiler and parse tree
8657 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8658 ((= tt js2-SUB)
8659 (js2-consume-token)
8660 ;; Convert to special NEG token in decompiler and parse tree
8661 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8662 ((or (= tt js2-INC)
8663 (= tt js2-DEC))
8664 (js2-consume-token)
8665 (prog1
8666 (setq beg js2-token-beg
8667 end js2-token-end
8668 expr (js2-make-unary tt 'js2-parse-member-expr t))
8669 (js2-check-bad-inc-dec tt beg end expr)))
8670 ((= tt js2-DELPROP)
8671 (js2-consume-token)
8672 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8673 ((= tt js2-ERROR)
8674 (js2-consume-token)
8675 (make-js2-error-node)) ; try to continue
8676 ((and (= tt js2-LT)
8677 js2-compiler-xml-available)
8678 ;; XML stream encountered in expression.
8679 (js2-consume-token)
8680 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8681 (t
8682 (setq pn (js2-parse-member-expr t)
8683 ;; Don't look across a newline boundary for a postfix incop.
8684 tt (js2-peek-token-or-eol))
8685 (when (or (= tt js2-INC) (= tt js2-DEC))
8686 (js2-consume-token)
8687 (setf expr pn
8688 pn (js2-make-unary tt expr))
8689 (js2-node-set-prop pn 'postfix t)
8690 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8691 pn))))
8692
8693 (defun js2-parse-xml-initializer ()
8694 "Parse an E4X XML initializer.
8695 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8696 Then I'll postprocess the result, depending on whether we're in IDE
8697 mode or codegen mode, and generate the appropriate rewritten AST.
8698 IDE mode uses a rich AST that models the XML structure. Codegen mode
8699 just concatenates everything and makes a new XML or XMLList out of it."
8700 (let ((tt (js2-get-first-xml-token))
8701 pn-xml pn expr kids expr-pos
8702 (continue t)
8703 (first-token t))
8704 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8705 (js2-report-error "msg.syntax"))
8706 (setq pn-xml (make-js2-xml-node))
8707 (while continue
8708 (if first-token
8709 (setq first-token nil)
8710 (setq tt (js2-get-next-xml-token)))
8711 (cond
8712 ;; js2-XML means we found a {expr} in the XML stream.
8713 ;; The js2-ts-string is the XML up to the left-curly.
8714 ((= tt js2-XML)
8715 (push (make-js2-string-node :pos js2-token-beg
8716 :len (- js2-ts-cursor js2-token-beg))
8717 kids)
8718 (js2-must-match js2-LC "msg.syntax")
8719 (setq expr-pos js2-ts-cursor
8720 expr (if (eq (js2-peek-token) js2-RC)
8721 (make-js2-empty-expr-node :pos expr-pos)
8722 (js2-parse-expr)))
8723 (js2-must-match js2-RC "msg.syntax")
8724 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8725 :len (js2-node-len expr)
8726 :expr expr))
8727 (js2-node-add-children pn expr)
8728 (push pn kids))
8729 ;; a js2-XMLEND token means we hit the final close-tag.
8730 ((= tt js2-XMLEND)
8731 (push (make-js2-string-node :pos js2-token-beg
8732 :len (- js2-ts-cursor js2-token-beg))
8733 kids)
8734 (dolist (kid (nreverse kids))
8735 (js2-block-node-push pn-xml kid))
8736 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8737 (js2-node-pos pn-xml))
8738 continue nil))
8739 (t
8740 (js2-report-error "msg.syntax")
8741 (setq continue nil))))
8742 pn-xml))
8743
8744
8745 (defun js2-parse-argument-list ()
8746 "Parse an argument list and return it as a Lisp list of nodes.
8747 Returns the list in reverse order. Consumes the right-paren token."
8748 (let (result)
8749 (unless (js2-match-token js2-RP)
8750 (loop do
8751 (if (= (js2-peek-token) js2-YIELD)
8752 (js2-report-error "msg.yield.parenthesized"))
8753 (push (js2-parse-assign-expr) result)
8754 while
8755 (js2-match-token js2-COMMA))
8756 (js2-must-match js2-RP "msg.no.paren.arg")
8757 result)))
8758
8759 (defun js2-parse-member-expr (&optional allow-call-syntax)
8760 (let ((tt (js2-peek-token))
8761 pn pos target args beg end init tail)
8762 (if (/= tt js2-NEW)
8763 (setq pn (js2-parse-primary-expr))
8764 ;; parse a 'new' expression
8765 (js2-consume-token)
8766 (setq pos js2-token-beg
8767 beg pos
8768 target (js2-parse-member-expr)
8769 end (js2-node-end target)
8770 pn (make-js2-new-node :pos pos
8771 :target target
8772 :len (- end pos)))
8773 (js2-node-add-children pn target)
8774 (when (js2-match-token js2-LP)
8775 ;; Add the arguments to pn, if any are supplied.
8776 (setf beg pos ; start of "new" keyword
8777 pos js2-token-beg
8778 args (nreverse (js2-parse-argument-list))
8779 (js2-new-node-args pn) args
8780 end js2-token-end
8781 (js2-new-node-lp pn) (- pos beg)
8782 (js2-new-node-rp pn) (- end 1 beg))
8783 (apply #'js2-node-add-children pn args))
8784 (when (and js2-allow-rhino-new-expr-initializer
8785 (js2-match-token js2-LC))
8786 (setf init (js2-parse-object-literal)
8787 end (js2-node-end init)
8788 (js2-new-node-initializer pn) init)
8789 (js2-node-add-children pn init))
8790 (setf (js2-node-len pn) (- end beg))) ; end outer if
8791 (js2-parse-member-expr-tail allow-call-syntax pn)))
8792
8793 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8794 "Parse a chain of property/array accesses or function calls.
8795 Includes parsing for E4X operators like `..' and `.@'.
8796 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8797 Returns an expression tree that includes PN, the parent node."
8798 (let ((beg (js2-node-pos pn))
8799 tt
8800 (continue t))
8801 (while continue
8802 (setq tt (js2-peek-token))
8803 (cond
8804 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8805 (setq pn (js2-parse-property-access tt pn)))
8806 ((= tt js2-DOTQUERY)
8807 (setq pn (js2-parse-dot-query pn)))
8808 ((= tt js2-LB)
8809 (setq pn (js2-parse-element-get pn)))
8810 ((= tt js2-LP)
8811 (if allow-call-syntax
8812 (setq pn (js2-parse-function-call pn))
8813 (setq continue nil)))
8814 (t
8815 (setq continue nil))))
8816 (if (>= js2-highlight-level 2)
8817 (js2-parse-highlight-member-expr-node pn))
8818 pn))
8819
8820 (defun js2-parse-dot-query (pn)
8821 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8822 Last token parsed must be `js2-DOTQUERY'."
8823 (let ((pos (js2-node-pos pn))
8824 op-pos expr end)
8825 (js2-consume-token)
8826 (js2-must-have-xml)
8827 (js2-set-requires-activation)
8828 (setq op-pos js2-token-beg
8829 expr (js2-parse-expr)
8830 end (js2-node-end expr)
8831 pn (make-js2-xml-dot-query-node :left pn
8832 :pos pos
8833 :op-pos op-pos
8834 :right expr))
8835 (js2-node-add-children pn
8836 (js2-xml-dot-query-node-left pn)
8837 (js2-xml-dot-query-node-right pn))
8838 (if (js2-must-match js2-RP "msg.no.paren")
8839 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
8840 end js2-token-end))
8841 (setf (js2-node-len pn) (- end pos))
8842 pn))
8843
8844 (defun js2-parse-element-get (pn)
8845 "Parse an element-get expression, e.g. foo[bar].
8846 Last token parsed must be `js2-RB'."
8847 (let ((lb js2-token-beg)
8848 (pos (js2-node-pos pn))
8849 rb expr)
8850 (js2-consume-token)
8851 (setq expr (js2-parse-expr))
8852 (if (js2-must-match js2-RB "msg.no.bracket.index")
8853 (setq rb js2-token-beg))
8854 (setq pn (make-js2-elem-get-node :target pn
8855 :pos pos
8856 :element expr
8857 :lb (js2-relpos lb pos)
8858 :rb (js2-relpos rb pos)
8859 :len (- js2-token-end pos)))
8860 (js2-node-add-children pn
8861 (js2-elem-get-node-target pn)
8862 (js2-elem-get-node-element pn))
8863 pn))
8864
8865 (defun js2-parse-function-call (pn)
8866 (let (args
8867 (pos (js2-node-pos pn)))
8868 (js2-consume-token)
8869 (setq pn (make-js2-call-node :pos pos
8870 :target pn
8871 :lp (- js2-token-beg pos)))
8872 (js2-node-add-children pn (js2-call-node-target pn))
8873 ;; Add the arguments to pn, if any are supplied.
8874 (setf args (nreverse (js2-parse-argument-list))
8875 (js2-call-node-rp pn) (- js2-token-beg pos)
8876 (js2-call-node-args pn) args)
8877 (apply #'js2-node-add-children pn args)
8878 (setf (js2-node-len pn) (- js2-ts-cursor pos))
8879 pn))
8880
8881 (defun js2-parse-property-access (tt pn)
8882 "Parse a property access, XML descendants access, or XML attr access."
8883 (let ((member-type-flags 0)
8884 (dot-pos js2-token-beg)
8885 (dot-len (if (= tt js2-DOTDOT) 2 1))
8886 name
8887 ref ; right side of . or .. operator
8888 result)
8889 (js2-consume-token)
8890 (when (= tt js2-DOTDOT)
8891 (js2-must-have-xml)
8892 (setq member-type-flags js2-descendants-flag))
8893 (if (not js2-compiler-xml-available)
8894 (progn
8895 (js2-must-match-prop-name "msg.no.name.after.dot")
8896 (setq name (js2-create-name-node t js2-GETPROP)
8897 result (make-js2-prop-get-node :left pn
8898 :pos js2-token-beg
8899 :right name
8900 :len (- js2-token-end
8901 js2-token-beg)))
8902 (js2-node-add-children result pn name)
8903 result)
8904 ;; otherwise look for XML operators
8905 (setf result (if (= tt js2-DOT)
8906 (make-js2-prop-get-node)
8907 (make-js2-infix-node :type js2-DOTDOT))
8908 (js2-node-pos result) (js2-node-pos pn)
8909 (js2-infix-node-op-pos result) dot-pos
8910 (js2-infix-node-left result) pn ; do this after setting position
8911 tt (js2-next-token))
8912 (cond
8913 ;; needed for generator.throw()
8914 ((= tt js2-THROW)
8915 (js2-save-name-token-data js2-token-beg "throw")
8916 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
8917 ;; handles: name, ns::name, ns::*, ns::[expr]
8918 ((js2-valid-prop-name-token tt)
8919 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
8920 ;; handles: *, *::name, *::*, *::[expr]
8921 ((= tt js2-MUL)
8922 (js2-save-name-token-data js2-token-beg "*")
8923 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
8924 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
8925 ((= tt js2-XMLATTR)
8926 (setq result (js2-parse-attribute-access)))
8927 (t
8928 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
8929 (if ref
8930 (setf (js2-node-len result) (- (js2-node-end ref)
8931 (js2-node-pos result))
8932 (js2-infix-node-right result) ref))
8933 (if (js2-infix-node-p result)
8934 (js2-node-add-children result
8935 (js2-infix-node-left result)
8936 (js2-infix-node-right result)))
8937 result)))
8938
8939 (defun js2-parse-attribute-access ()
8940 "Parse an E4X XML attribute expression.
8941 This includes expressions of the forms:
8942
8943 @attr @ns::attr @ns::*
8944 @* @*::attr @*::*
8945 @[expr] @*::[expr] @ns::[expr]
8946
8947 Called if we peeked an '@' token."
8948 (let ((tt (js2-next-token))
8949 (at-pos js2-token-beg))
8950 (cond
8951 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
8952 ((js2-valid-prop-name-token tt)
8953 (js2-parse-property-name at-pos js2-ts-string 0))
8954 ;; handles: @*, @*::name, @*::*, @*::[expr]
8955 ((= tt js2-MUL)
8956 (js2-save-name-token-data js2-token-beg "*")
8957 (js2-parse-property-name js2-token-beg "*" 0))
8958 ;; handles @[expr]
8959 ((= tt js2-LB)
8960 (js2-parse-xml-elem-ref at-pos))
8961 (t
8962 (js2-report-error "msg.no.name.after.xmlAttr")
8963 ;; Avoid cascaded errors that happen if we make an error node here.
8964 (js2-save-name-token-data js2-token-beg "")
8965 (js2-parse-property-name js2-token-beg "" 0)))))
8966
8967 (defun js2-parse-property-name (at-pos s member-type-flags)
8968 "Check if :: follows name in which case it becomes qualified name.
8969
8970 AT-POS is a natural number if we just read an '@' token, else nil.
8971 S is the name or string that was matched: an identifier, 'throw' or '*'.
8972 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
8973
8974 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
8975 operator, or the name is followed by ::. For a plain name, returns a
8976 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
8977 (let ((pos (or at-pos js2-token-beg))
8978 colon-pos
8979 (name (js2-create-name-node t js2-current-token))
8980 ns tt ref pn)
8981 (catch 'return
8982 (when (js2-match-token js2-COLONCOLON)
8983 (setq ns name
8984 colon-pos js2-token-beg
8985 tt (js2-next-token))
8986 (cond
8987 ;; handles name::name
8988 ((js2-valid-prop-name-token tt)
8989 (setq name (js2-create-name-node)))
8990 ;; handles name::*
8991 ((= tt js2-MUL)
8992 (js2-save-name-token-data js2-token-beg "*")
8993 (setq name (js2-create-name-node)))
8994 ;; handles name::[expr]
8995 ((= tt js2-LB)
8996 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
8997 (t
8998 (js2-report-error "msg.no.name.after.coloncolon"))))
8999 (if (and (null ns) (zerop member-type-flags))
9000 name
9001 (prog1
9002 (setq pn
9003 (make-js2-xml-prop-ref-node :pos pos
9004 :len (- (js2-node-end name) pos)
9005 :at-pos at-pos
9006 :colon-pos colon-pos
9007 :propname name))
9008 (js2-node-add-children pn name))))))
9009
9010 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9011 "Parse the [expr] portion of an xml element reference.
9012 For instance, @[expr], @*::[expr], or ns::[expr]."
9013 (let* ((lb js2-token-beg)
9014 (pos (or at-pos lb))
9015 rb
9016 (expr (js2-parse-expr))
9017 (end (js2-node-end expr))
9018 pn)
9019 (if (js2-must-match js2-RB "msg.no.bracket.index")
9020 (setq rb js2-token-beg
9021 end js2-token-end))
9022 (prog1
9023 (setq pn
9024 (make-js2-xml-elem-ref-node :pos pos
9025 :len (- end pos)
9026 :namespace namespace
9027 :colon-pos colon-pos
9028 :at-pos at-pos
9029 :expr expr
9030 :lb (js2-relpos lb pos)
9031 :rb (js2-relpos rb pos)))
9032 (js2-node-add-children pn namespace expr))))
9033
9034 (defun js2-parse-destruct-primary-expr ()
9035 (let ((js2-is-in-destructuring t))
9036 (js2-parse-primary-expr)))
9037
9038 (defun js2-parse-primary-expr ()
9039 "Parse a literal (leaf) expression of some sort.
9040 Includes complex literals such as functions, object-literals,
9041 array-literals, array comprehensions and regular expressions."
9042 (let ((tt-flagged (js2-next-flagged-token))
9043 pn ; parent node (usually return value)
9044 tt
9045 px-pos ; paren-expr pos
9046 len
9047 flags ; regexp flags
9048 expr)
9049 (setq tt js2-current-token)
9050 (cond
9051 ((= tt js2-FUNCTION)
9052 (js2-parse-function 'FUNCTION_EXPRESSION))
9053 ((= tt js2-LB)
9054 (js2-parse-array-literal))
9055 ((= tt js2-LC)
9056 (js2-parse-object-literal))
9057 ((= tt js2-LET)
9058 (js2-parse-let js2-token-beg))
9059 ((= tt js2-LP)
9060 (setq px-pos js2-token-beg
9061 expr (js2-parse-expr))
9062 (js2-must-match js2-RP "msg.no.paren")
9063 (setq pn (make-js2-paren-node :pos px-pos
9064 :expr expr
9065 :len (- js2-token-end px-pos)))
9066 (js2-node-add-children pn (js2-paren-node-expr pn))
9067 pn)
9068 ((= tt js2-XMLATTR)
9069 (js2-must-have-xml)
9070 (js2-parse-attribute-access))
9071 ((= tt js2-NAME)
9072 (js2-parse-name tt-flagged tt))
9073 ((= tt js2-NUMBER)
9074 (make-js2-number-node))
9075 ((= tt js2-STRING)
9076 (prog1
9077 (make-js2-string-node)
9078 (js2-record-face 'font-lock-string-face)))
9079 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9080 ;; Got / or /= which in this context means a regexp literal
9081 (setq px-pos js2-token-beg)
9082 (js2-read-regexp tt)
9083 (setq flags js2-ts-regexp-flags
9084 js2-ts-regexp-flags nil)
9085 (prog1
9086 (make-js2-regexp-node :pos px-pos
9087 :len (- js2-ts-cursor px-pos)
9088 :value js2-ts-string
9089 :flags flags)
9090 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9091 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9092 ((or (= tt js2-NULL)
9093 (= tt js2-THIS)
9094 (= tt js2-FALSE)
9095 (= tt js2-TRUE))
9096 (make-js2-keyword-node :type tt))
9097 ((= tt js2-RESERVED)
9098 (js2-report-error "msg.reserved.id")
9099 (make-js2-name-node))
9100 ((= tt js2-ERROR)
9101 ;; the scanner or one of its subroutines reported the error.
9102 (make-js2-error-node))
9103 ((= tt js2-EOF)
9104 (setq px-pos (point-at-bol)
9105 len (- js2-ts-cursor px-pos))
9106 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9107 (make-js2-error-node :pos px-pos :len len))
9108 (t
9109 (js2-report-error "msg.syntax")
9110 (make-js2-error-node)))))
9111
9112 (defun js2-parse-name (tt-flagged tt)
9113 (let ((name js2-ts-string)
9114 (name-pos js2-token-beg)
9115 node)
9116 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9117 (= (js2-peek-token) js2-COLON))
9118 (prog1
9119 ;; Do not consume colon, it is used as unwind indicator
9120 ;; to return to statementHelper.
9121 (make-js2-label-node :pos name-pos
9122 :len (- js2-token-end name-pos)
9123 :name name)
9124 (js2-set-face name-pos
9125 js2-token-end
9126 'font-lock-variable-name-face 'record))
9127 ;; Otherwise not a label, just a name. Unfortunately peeking
9128 ;; the next token to check for a colon has biffed js2-token-beg
9129 ;; and js2-token-end. We store the name's bounds in buffer vars
9130 ;; and `js2-create-name-node' uses them.
9131 (js2-save-name-token-data name-pos name)
9132 (setq node (if js2-compiler-xml-available
9133 (js2-parse-property-name nil name 0)
9134 (js2-create-name-node 'check-activation)))
9135 (if js2-highlight-external-variables
9136 (js2-record-name-node node))
9137 node)))
9138
9139 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9140 (js2-add-strict-warning
9141 msg nil
9142 ;; back up from comma to beginning of line or array/objlit
9143 (max (if elems
9144 (js2-node-pos (car elems))
9145 pos)
9146 (save-excursion
9147 (goto-char comma-pos)
9148 (back-to-indentation)
9149 (point)))
9150 comma-pos))
9151
9152 (defun js2-parse-array-literal ()
9153 (let ((pos js2-token-beg)
9154 (end js2-token-end)
9155 (after-lb-or-comma t)
9156 after-comma tt elems pn
9157 (continue t))
9158 (unless js2-is-in-destructuring
9159 (js2-push-scope (make-js2-scope))) ; for array comp
9160 (while continue
9161 (setq tt (js2-peek-token))
9162 (cond
9163 ;; comma
9164 ((= tt js2-COMMA)
9165 (js2-consume-token)
9166 (setq after-comma js2-token-end)
9167 (if (not after-lb-or-comma)
9168 (setq after-lb-or-comma t)
9169 (push nil elems)))
9170 ;; end of array
9171 ((or (= tt js2-RB)
9172 (= tt js2-EOF)) ; prevent infinite loop
9173 (if (= tt js2-EOF)
9174 (js2-report-error "msg.no.bracket.arg" nil pos)
9175 (js2-consume-token))
9176 (setq continue nil
9177 end js2-token-end
9178 pn (make-js2-array-node :pos pos
9179 :len (- js2-ts-cursor pos)
9180 :elems (nreverse elems)))
9181 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9182 (when (and after-comma (not js2-is-in-destructuring))
9183 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9184 pos elems after-comma)))
9185 ;; destructuring binding
9186 (js2-is-in-destructuring
9187 (push (if (or (= tt js2-LC)
9188 (= tt js2-LB)
9189 (= tt js2-NAME))
9190 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9191 (js2-parse-destruct-primary-expr)
9192 ;; invalid pattern
9193 (js2-consume-token)
9194 (js2-report-error "msg.bad.var")
9195 (make-js2-error-node))
9196 elems)
9197 (setq after-lb-or-comma nil
9198 after-comma nil))
9199 ;; array comp
9200 ((and (>= js2-language-version 170)
9201 (= tt js2-FOR) ; check for array comprehension
9202 (not after-lb-or-comma) ; "for" can't follow a comma
9203 elems ; must have at least 1 element
9204 (not (cdr elems))) ; but no 2nd element
9205 (setf continue nil
9206 pn (js2-parse-array-comprehension (car elems) pos)))
9207
9208 ;; another element
9209 (t
9210 (unless after-lb-or-comma
9211 (js2-report-error "msg.no.bracket.arg"))
9212 (push (js2-parse-assign-expr) elems)
9213 (setq after-lb-or-comma nil
9214 after-comma nil))))
9215 (unless js2-is-in-destructuring
9216 (js2-pop-scope))
9217 pn))
9218
9219 (defun js2-parse-array-comprehension (expr pos)
9220 "Parse a JavaScript 1.7 Array Comprehension.
9221 EXPR is the first expression after the opening left-bracket.
9222 POS is the beginning of the LB token preceding EXPR.
9223 We should have just parsed the 'for' keyword before calling this function."
9224 (let (loops loop first prev filter if-pos result)
9225 (while (= (js2-peek-token) js2-FOR)
9226 (let ((prev (car loops))) ; rearrange scope chain
9227 (push (setq loop (js2-parse-array-comp-loop)) loops)
9228 (if prev ; each loop is parent scope to the next one
9229 (setf (js2-scope-parent-scope loop) prev)
9230 ; first loop takes expr scope's parent
9231 (setf (js2-scope-parent-scope (setq first loop))
9232 (js2-scope-parent-scope js2-current-scope)))))
9233 ;; set expr scope's parent to the last loop
9234 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9235 (when (= (js2-peek-token) js2-IF)
9236 (js2-consume-token)
9237 (setq if-pos (- js2-token-beg pos) ; relative
9238 filter (js2-parse-condition)))
9239 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9240 (setq result (make-js2-array-comp-node :pos pos
9241 :len (- js2-ts-cursor pos)
9242 :result expr
9243 :loops (nreverse loops)
9244 :filter (car filter)
9245 :lp (js2-relpos (second filter) pos)
9246 :rp (js2-relpos (third filter) pos)
9247 :if-pos if-pos))
9248 (apply #'js2-node-add-children result expr (car filter)
9249 (js2-array-comp-node-loops result))
9250 (setq js2-current-scope first) ; pop to the first loop
9251 result))
9252
9253 (defun js2-parse-array-comp-loop ()
9254 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9255 Last token peeked should be the initial FOR."
9256 (let ((pos js2-token-beg)
9257 (pn (make-js2-array-comp-loop-node))
9258 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9259 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9260 (js2-push-scope pn)
9261 (unwind-protect
9262 (progn
9263 (when (js2-match-token js2-NAME)
9264 (if (string= js2-ts-string "each")
9265 (progn
9266 (setq foreach-p t
9267 each-pos (- js2-token-beg pos)) ; relative
9268 (js2-record-face 'font-lock-keyword-face))
9269 (js2-report-error "msg.no.paren.for")))
9270 (if (js2-must-match js2-LP "msg.no.paren.for")
9271 (setq lp (- js2-token-beg pos)))
9272 (setq tt (js2-peek-token))
9273 (cond
9274 ((or (= tt js2-LB)
9275 (= tt js2-LC))
9276 (setq iter (js2-parse-destruct-primary-expr))
9277 (js2-define-destruct-symbols iter js2-LET
9278 'font-lock-variable-name-face t))
9279 ((js2-match-token js2-NAME)
9280 (setq iter (js2-create-name-node)))
9281 (t
9282 (js2-report-error "msg.bad.var")))
9283 ;; Define as a let since we want the scope of the variable to
9284 ;; be restricted to the array comprehension
9285 (if (js2-name-node-p iter)
9286 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9287 (if (or (js2-match-token js2-IN)
9288 (and (>= js2-language-version 200)
9289 (js2-match-contextual-kwd "of")
9290 (setq forof-p t)))
9291 (setq in-pos (- js2-token-beg pos))
9292 (js2-report-error "msg.in.after.for.name"))
9293 (setq obj (js2-parse-expr))
9294 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9295 (setq rp (- js2-token-beg pos)))
9296 (setf (js2-node-pos pn) pos
9297 (js2-node-len pn) (- js2-ts-cursor pos)
9298 (js2-array-comp-loop-node-iterator pn) iter
9299 (js2-array-comp-loop-node-object pn) obj
9300 (js2-array-comp-loop-node-in-pos pn) in-pos
9301 (js2-array-comp-loop-node-each-pos pn) each-pos
9302 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9303 (js2-array-comp-loop-node-forof-p pn) forof-p
9304 (js2-array-comp-loop-node-lp pn) lp
9305 (js2-array-comp-loop-node-rp pn) rp)
9306 (js2-node-add-children pn iter obj))
9307 (js2-pop-scope))
9308 pn))
9309
9310 (defun js2-parse-object-literal ()
9311 (let ((pos js2-token-beg)
9312 tt elems result after-comma
9313 (continue t))
9314 (while continue
9315 (setq tt (js2-peek-token))
9316 (cond
9317 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9318 ;; {get foo() {...}}, or {set foo(x) {...}}
9319 ((or (js2-valid-prop-name-token tt)
9320 (= tt js2-STRING))
9321 (setq after-comma nil
9322 result (js2-parse-named-prop tt))
9323 (if (and (null result)
9324 (not js2-recover-from-parse-errors))
9325 (setq continue nil)
9326 (push result elems)))
9327 ;; {12: x} or {10.7: x}
9328 ((= tt js2-NUMBER)
9329 (js2-consume-token)
9330 (setq after-comma nil)
9331 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9332 ;; trailing comma
9333 ((= tt js2-RC)
9334 (setq continue nil)
9335 (if after-comma
9336 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9337 pos elems after-comma)))
9338 (t
9339 (js2-report-error "msg.bad.prop")
9340 (unless js2-recover-from-parse-errors
9341 (setq continue nil)))) ; end switch
9342 (if (js2-match-token js2-COMMA)
9343 (setq after-comma js2-token-end)
9344 (setq continue nil))) ; end loop
9345 (js2-must-match js2-RC "msg.no.brace.prop")
9346 (setq result (make-js2-object-node :pos pos
9347 :len (- js2-ts-cursor pos)
9348 :elems (nreverse elems)))
9349 (apply #'js2-node-add-children result (js2-object-node-elems result))
9350 result))
9351
9352 (defun js2-parse-named-prop (tt)
9353 "Parse a name, string, or getter/setter object property.
9354 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9355 (js2-consume-token)
9356 (let ((string-prop (and (= tt js2-STRING)
9357 (make-js2-string-node)))
9358 expr
9359 (ppos js2-token-beg)
9360 (pend js2-token-end)
9361 (name (js2-create-name-node))
9362 (prop js2-ts-string))
9363 (cond
9364 ;; getter/setter prop
9365 ((and (= tt js2-NAME)
9366 (= (js2-peek-token) js2-NAME)
9367 (or (string= prop "get")
9368 (string= prop "set")))
9369 (js2-consume-token)
9370 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9371 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9372 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9373 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9374 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9375 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9376 ;; when patterns are used in variable declarations, function parameters,
9377 ;; catch-clause, and iterators.
9378 ;; We have to set `js2-is-in-destructuring' to t when the current
9379 ;; expressions are on the left side of any assignment, but it's difficult
9380 ;; because it requires looking ahead of expression.
9381 ((and js2-is-in-destructuring
9382 (= tt js2-NAME)
9383 (let ((ctk (js2-peek-token)))
9384 (or (= ctk js2-COMMA)
9385 (= ctk js2-RC)
9386 (js2-valid-prop-name-token ctk))))
9387 name)
9388 ;; regular prop
9389 (t
9390 (prog1
9391 (setq expr (js2-parse-plain-property (or string-prop name)))
9392 (js2-set-face ppos pend
9393 (if (js2-function-node-p
9394 (js2-object-prop-node-right expr))
9395 'font-lock-function-name-face
9396 'font-lock-variable-name-face)
9397 'record))))))
9398
9399 (defun js2-parse-plain-property (prop)
9400 "Parse a non-getter/setter property in an object literal.
9401 PROP is the node representing the property: a number, name or string."
9402 (js2-must-match js2-COLON "msg.no.colon.prop")
9403 (let* ((pos (js2-node-pos prop))
9404 (colon (- js2-token-beg pos))
9405 (expr (js2-parse-assign-expr))
9406 (result (make-js2-object-prop-node
9407 :pos pos
9408 ;; don't include last consumed token in length
9409 :len (- (+ (js2-node-pos expr)
9410 (js2-node-len expr))
9411 pos)
9412 :left prop
9413 :right expr
9414 :op-pos colon)))
9415 (js2-node-add-children result prop expr)
9416 result))
9417
9418 (defun js2-parse-getter-setter-prop (pos prop get-p)
9419 "Parse getter or setter property in an object literal.
9420 JavaScript syntax is:
9421
9422 { get foo() {...}, set foo(x) {...} }
9423
9424 and expression closure style is also supported
9425
9426 { get foo() x, set foo(x) _x = x }
9427
9428 POS is the start position of the `get' or `set' keyword.
9429 PROP is the `js2-name-node' representing the property name.
9430 GET-P is non-nil if the keyword was `get'."
9431 (let ((type (if get-p js2-GET js2-SET))
9432 result end
9433 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9434 ;; it has to be an anonymous function, as we already parsed the name
9435 (if (/= (js2-node-type fn) js2-FUNCTION)
9436 (js2-report-error "msg.bad.prop")
9437 (if (plusp (length (js2-function-name fn)))
9438 (js2-report-error "msg.bad.prop")))
9439 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9440 (setq end (js2-node-end fn)
9441 result (make-js2-getter-setter-node :type type
9442 :pos pos
9443 :len (- end pos)
9444 :left prop
9445 :right fn))
9446 (js2-node-add-children result prop fn)
9447 result))
9448
9449 (defun js2-create-name-node (&optional check-activation-p token)
9450 "Create a name node using the token info from last scanned name.
9451 In some cases we need to either synthesize a name node, or we lost
9452 the name token information by peeking. If the TOKEN parameter is
9453 not `js2-NAME', then we use the token info saved in instance vars."
9454 (let ((beg js2-token-beg)
9455 (s js2-ts-string)
9456 name)
9457 (when (/= js2-current-token js2-NAME)
9458 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9459 s js2-prev-name-token-string
9460 js2-prev-name-token-start nil
9461 js2-prev-name-token-string nil))
9462 (setq name (make-js2-name-node :pos beg
9463 :name s
9464 :len (length s)))
9465 (if check-activation-p
9466 (js2-check-activation-name s (or token js2-NAME)))
9467 name))
9468
9469 ;;; Indentation support
9470
9471 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9472 ;; Karl cleverly deduces that the desired indentation level is often a
9473 ;; function of paren/bracket/brace nesting depth, which can be determined
9474 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9475 ;; then does some equally clever checks to see if we're in the context of a
9476 ;; substatement of a possibly braceless statement keyword such as if, while,
9477 ;; or finally. This approach yields pretty good results.
9478
9479 ;; The indenter is often "wrong", however, and needs to be overridden.
9480 ;; The right long-term solution is probably to emulate (or integrate
9481 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9482 ;; parse tree from `js2-parse' is present, which is not true at the
9483 ;; moment the user is typing, computing indentation is still thousands
9484 ;; of lines of code to handle every possible syntactic edge case.
9485
9486 ;; In the meantime, the compromise solution is that we offer a "bounce
9487 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9488 ;; current line indent among various likely guess points. This approach
9489 ;; is far from perfect, but should at least make it slightly easier to
9490 ;; move the line towards its desired indentation when manually
9491 ;; overriding Karl's heuristic nesting guesser.
9492
9493 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9494 ;; extensions such as `let' and Array comprehensions. Major kudos to
9495 ;; Karl for coming up with the initial approach, which packs a lot of
9496 ;; punch for so little code.
9497
9498 (defconst js2-possibly-braceless-keywords-re
9499 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9500 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9501 "try" "while" "with" "let")))
9502 "Regular expression matching keywords that are optionally
9503 followed by an opening brace.")
9504
9505 (defconst js2-indent-operator-re
9506 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9507 (regexp-opt '("in" "instanceof") 'words))
9508 "Regular expression matching operators that affect indentation
9509 of continued expressions.")
9510
9511 (defconst js2-declaration-keyword-re
9512 (regexp-opt '("var" "let" "const") 'words)
9513 "Regular expression matching variable declaration keywords.")
9514
9515 (defun js2-re-search-forward-inner (regexp &optional bound count)
9516 "Auxiliary function for `js2-re-search-forward'."
9517 (let (parse saved-point)
9518 (while (> count 0)
9519 (re-search-forward regexp bound)
9520 (setq parse (if saved-point
9521 (parse-partial-sexp saved-point (point))
9522 (syntax-ppss (point))))
9523 (cond ((nth 3 parse)
9524 (re-search-forward
9525 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9526 (save-excursion (end-of-line) (point)) t))
9527 ((nth 7 parse)
9528 (forward-line))
9529 ((or (nth 4 parse)
9530 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9531 (re-search-forward "\\*/"))
9532 (t
9533 (setq count (1- count))))
9534 (setq saved-point (point))))
9535 (point))
9536
9537 (defun js2-re-search-forward (regexp &optional bound noerror count)
9538 "Search forward but ignore strings and comments.
9539 Invokes `re-search-forward' 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-forward-inner regexp bound 1))
9545 ((< count 0)
9546 '(js2-re-search-backward-inner regexp bound (- count)))
9547 ((> count 0)
9548 '(js2-re-search-forward-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-re-search-backward-inner (regexp &optional bound count)
9557 "Auxiliary function for `js2-re-search-backward'."
9558 (let (parse)
9559 (while (> count 0)
9560 (re-search-backward regexp bound)
9561 (setq parse (syntax-ppss (point)))
9562 (cond ((nth 3 parse)
9563 (re-search-backward
9564 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9565 (line-beginning-position) t))
9566 ((nth 7 parse)
9567 (goto-char (nth 8 parse)))
9568 ((or (nth 4 parse)
9569 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9570 (re-search-backward "/\\*"))
9571 (t
9572 (setq count (1- count))))))
9573 (point))
9574
9575 (defun js2-re-search-backward (regexp &optional bound noerror count)
9576 "Search backward but ignore strings and comments.
9577 Invokes `re-search-backward' but treats the buffer as if strings
9578 and comments have been removed."
9579 (let ((saved-point (point))
9580 (search-expr
9581 (cond ((null count)
9582 '(js2-re-search-backward-inner regexp bound 1))
9583 ((< count 0)
9584 '(js2-re-search-forward-inner regexp bound (- count)))
9585 ((> count 0)
9586 '(js2-re-search-backward-inner regexp bound count)))))
9587 (condition-case err
9588 (eval search-expr)
9589 (search-failed
9590 (goto-char saved-point)
9591 (unless noerror
9592 (error (error-message-string err)))))))
9593
9594 (defun js2-looking-at-operator-p ()
9595 "Return non-nil if text after point is a non-comma operator."
9596 (and (looking-at js2-indent-operator-re)
9597 (or (not (looking-at ":"))
9598 (save-excursion
9599 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9600 (looking-at "?"))))))
9601
9602 (defun js2-continued-expression-p ()
9603 "Return non-nil if the current line continues an expression."
9604 (save-excursion
9605 (back-to-indentation)
9606 (or (js2-looking-at-operator-p)
9607 (when (catch 'found
9608 (while (and (re-search-backward "\n" nil t)
9609 (let ((state (syntax-ppss)))
9610 (when (nth 4 state)
9611 (goto-char (nth 8 state))) ;; skip comments
9612 (skip-chars-backward " \t")
9613 (if (bolp)
9614 t
9615 (throw 'found t))))))
9616 (backward-char)
9617 (when (js2-looking-at-operator-p)
9618 (backward-char)
9619 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))
9620
9621 (defun js2-end-of-do-while-loop-p ()
9622 "Return non-nil if word after point is `while' of a do-while
9623 statement, else returns nil. A braceless do-while statement
9624 spanning several lines requires that the start of the loop is
9625 indented to the same column as the current line."
9626 (interactive)
9627 (save-excursion
9628 (when (looking-at "\\s-*\\<while\\>")
9629 (if (save-excursion
9630 (skip-chars-backward "[ \t\n]*}")
9631 (looking-at "[ \t\n]*}"))
9632 (save-excursion
9633 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9634 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9635 (or (looking-at "\\<do\\>")
9636 (let ((saved-indent (current-indentation)))
9637 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9638 (/= (current-indentation) saved-indent)))
9639 (and (looking-at "[ \t]*\\<do\\>")
9640 (not (js2-re-search-forward
9641 "\\<while\\>" (point-at-eol) t))
9642 (= (current-indentation) saved-indent))))))))
9643
9644 (defun js2-multiline-decl-indentation ()
9645 "Return the declaration indentation column if the current line belongs
9646 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9647 (let (forward-sexp-function ; use Lisp version
9648 at-opening-bracket)
9649 (save-excursion
9650 (back-to-indentation)
9651 (when (not (looking-at js2-declaration-keyword-re))
9652 (when (looking-at js2-indent-operator-re)
9653 (goto-char (match-end 0))) ; continued expressions are ok
9654 (while (and (not at-opening-bracket)
9655 (not (bobp))
9656 (let ((pos (point)))
9657 (save-excursion
9658 (js2-backward-sws)
9659 (or (eq (char-before) ?,)
9660 (and (not (eq (char-before) ?\;))
9661 (prog2 (skip-syntax-backward ".")
9662 (looking-at js2-indent-operator-re)
9663 (js2-backward-sws))
9664 (not (eq (char-before) ?\;)))
9665 (js2-same-line pos)))))
9666 (condition-case err
9667 (backward-sexp)
9668 (scan-error (setq at-opening-bracket t))))
9669 (when (looking-at js2-declaration-keyword-re)
9670 (goto-char (match-end 0))
9671 (1+ (current-column)))))))
9672
9673 (defun js2-ctrl-statement-indentation ()
9674 "Return the proper indentation of current line if it is a control statement.
9675 Returns an indentation if this line starts the body of a control
9676 statement without braces, else returns nil."
9677 (let (forward-sexp-function)
9678 (save-excursion
9679 (back-to-indentation)
9680 (when (and (not (js2-same-line (point-min)))
9681 (not (looking-at "{"))
9682 (js2-re-search-backward "[[:graph:]]" nil t)
9683 (not (looking-at "[{([]"))
9684 (progn
9685 (forward-char)
9686 (when (= (char-before) ?\))
9687 ;; scan-sexps sometimes throws an error
9688 (ignore-errors (backward-sexp))
9689 (skip-chars-backward " \t" (point-at-bol)))
9690 (let ((pt (point)))
9691 (back-to-indentation)
9692 (when (looking-at "}[ \t]*")
9693 (goto-char (match-end 0)))
9694 (and (looking-at js2-possibly-braceless-keywords-re)
9695 (= (match-end 0) pt)
9696 (not (js2-end-of-do-while-loop-p))))))
9697 (+ (current-indentation) js2-basic-offset)))))
9698
9699 (defun js2-indent-in-array-comp (parse-status)
9700 "Return non-nil if we think we're in an array comprehension.
9701 In particular, return the buffer position of the first `for' kwd."
9702 (let ((bracket (nth 1 parse-status))
9703 (end (point)))
9704 (when bracket
9705 (save-excursion
9706 (goto-char bracket)
9707 (when (looking-at "\\[")
9708 (forward-char 1)
9709 (js2-forward-sws)
9710 (if (looking-at "[[{]")
9711 (let (forward-sexp-function) ; use Lisp version
9712 (forward-sexp) ; skip destructuring form
9713 (js2-forward-sws)
9714 (if (and (/= (char-after) ?,) ; regular array
9715 (looking-at "for"))
9716 (match-beginning 0)))
9717 ;; to skip arbitrary expressions we need the parser,
9718 ;; so we'll just guess at it.
9719 (if (and (> end (point)) ; not empty literal
9720 (re-search-forward "[^,]]* \\(for\\) " end t)
9721 ;; not inside comment or string literal
9722 (let ((state (parse-partial-sexp bracket (point))))
9723 (not (or (nth 3 state) (nth 4 state)))))
9724 (match-beginning 1))))))))
9725
9726 (defun js2-array-comp-indentation (parse-status for-kwd)
9727 (if (js2-same-line for-kwd)
9728 ;; first continuation line
9729 (save-excursion
9730 (goto-char (nth 1 parse-status))
9731 (forward-char 1)
9732 (skip-chars-forward " \t")
9733 (current-column))
9734 (save-excursion
9735 (goto-char for-kwd)
9736 (current-column))))
9737
9738 (defun js2-proper-indentation (parse-status)
9739 "Return the proper indentation for the current line."
9740 (save-excursion
9741 (back-to-indentation)
9742 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9743 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9744 (continued-expr-p (js2-continued-expression-p))
9745 (declaration-indent (and js2-pretty-multiline-declarations
9746 (js2-multiline-decl-indentation)))
9747 (bracket (nth 1 parse-status))
9748 beg)
9749 (cond
9750 ;; indent array comprehension continuation lines specially
9751 ((and bracket
9752 (>= js2-language-version 170)
9753 (not (js2-same-line bracket))
9754 (setq beg (js2-indent-in-array-comp parse-status))
9755 (>= (point) (save-excursion
9756 (goto-char beg)
9757 (point-at-bol)))) ; at or after first loop?
9758 (js2-array-comp-indentation parse-status beg))
9759
9760 (ctrl-stmt-indent)
9761
9762 ((and declaration-indent continued-expr-p)
9763 (+ declaration-indent js2-basic-offset))
9764
9765 (declaration-indent)
9766
9767 (bracket
9768 (goto-char bracket)
9769 (cond
9770 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9771 (when (save-excursion (skip-chars-backward " \t)")
9772 (looking-at ")"))
9773 (backward-list))
9774 (back-to-indentation)
9775 (and (eq js2-pretty-multiline-declarations 'all)
9776 (looking-at js2-declaration-keyword-re)
9777 (goto-char (1+ (match-end 0))))
9778 (cond (same-indent-p
9779 (current-column))
9780 (continued-expr-p
9781 (+ (current-column) (* 2 js2-basic-offset)))
9782 (t
9783 (+ (current-column) js2-basic-offset))))
9784 (t
9785 (unless same-indent-p
9786 (forward-char)
9787 (skip-chars-forward " \t"))
9788 (current-column))))
9789
9790 (continued-expr-p js2-basic-offset)
9791
9792 (t 0)))))
9793
9794 (defun js2-lineup-comment (parse-status)
9795 "Indent a multi-line block comment continuation line."
9796 (let* ((beg (nth 8 parse-status))
9797 (first-line (js2-same-line beg))
9798 (offset (save-excursion
9799 (goto-char beg)
9800 (if (looking-at "/\\*")
9801 (+ 1 (current-column))
9802 0))))
9803 (unless first-line
9804 (indent-line-to offset))))
9805
9806 (defun js2-backward-sws ()
9807 "Move backward through whitespace and comments."
9808 (interactive)
9809 (while (forward-comment -1)))
9810
9811 (defun js2-forward-sws ()
9812 "Move forward through whitespace and comments."
9813 (interactive)
9814 (while (forward-comment 1)))
9815
9816 (defun js2-current-indent (&optional pos)
9817 "Return column of indentation on current line.
9818 If POS is non-nil, go to that point and return indentation for that line."
9819 (save-excursion
9820 (if pos
9821 (goto-char pos))
9822 (back-to-indentation)
9823 (current-column)))
9824
9825 (defun js2-arglist-close ()
9826 "Return non-nil if we're on a line beginning with a close-paren/brace."
9827 (save-excursion
9828 (goto-char (point-at-bol))
9829 (js2-forward-sws)
9830 (looking-at "[])}]")))
9831
9832 (defun js2-indent-looks-like-label-p ()
9833 (goto-char (point-at-bol))
9834 (js2-forward-sws)
9835 (looking-at (concat js2-mode-identifier-re ":")))
9836
9837 (defun js2-indent-in-objlit-p (parse-status)
9838 "Return non-nil if this looks like an object-literal entry."
9839 (let ((start (nth 1 parse-status)))
9840 (and
9841 start
9842 (save-excursion
9843 (and (zerop (forward-line -1))
9844 (not (< (point) start)) ; crossed a {} boundary
9845 (js2-indent-looks-like-label-p)))
9846 (save-excursion
9847 (js2-indent-looks-like-label-p)))))
9848
9849 ;; If prev line looks like foobar({ then we're passing an object
9850 ;; literal to a function call, and people pretty much always want to
9851 ;; de-dent back to the previous line, so move the 'basic-offset'
9852 ;; position to the front.
9853 (defun js2-indent-objlit-arg-p (parse-status)
9854 (save-excursion
9855 (back-to-indentation)
9856 (js2-backward-sws)
9857 (and (eq (1- (point)) (nth 1 parse-status))
9858 (eq (char-before) ?{)
9859 (progn
9860 (forward-char -1)
9861 (skip-chars-backward " \t")
9862 (eq (char-before) ?\()))))
9863
9864 (defun js2-indent-case-block-p ()
9865 (save-excursion
9866 (back-to-indentation)
9867 (js2-backward-sws)
9868 (goto-char (point-at-bol))
9869 (skip-chars-forward " \t")
9870 (looking-at "case\\s-.+:")))
9871
9872 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
9873 "Cycle among alternate computed indentation positions.
9874 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9875 of the buffer to the current point. NORMAL-COL is the indentation
9876 column computed by the heuristic guesser based on current paren,
9877 bracket, brace and statement nesting. If BACKWARDS, cycle positions
9878 in reverse."
9879 (let ((cur-indent (js2-current-indent))
9880 (old-buffer-undo-list buffer-undo-list)
9881 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9882 (current-line (save-excursion
9883 (forward-line 0) ; move to bol
9884 (1+ (count-lines (point-min) (point)))))
9885 positions pos main-pos anchor arglist-cont same-indent
9886 prev-line-col basic-offset computed-pos)
9887 ;; temporarily don't record undo info, if user requested this
9888 (when js2-mode-indent-inhibit-undo
9889 (setq buffer-undo-list t))
9890 (unwind-protect
9891 (progn
9892 ;; First likely point: indent from beginning of previous code line
9893 (push (setq basic-offset
9894 (+ (save-excursion
9895 (back-to-indentation)
9896 (js2-backward-sws)
9897 (back-to-indentation)
9898 (setq prev-line-col (current-column)))
9899 js2-basic-offset))
9900 positions)
9901
9902 ;; (First + epsilon) likely point: indent 2x from beginning of
9903 ;; previous code line. Google does it this way.
9904 (push (setq basic-offset
9905 (+ (save-excursion
9906 (back-to-indentation)
9907 (js2-backward-sws)
9908 (back-to-indentation)
9909 (setq prev-line-col (current-column)))
9910 (* 2 js2-basic-offset)))
9911 positions)
9912
9913 ;; Second likely point: indent from assign-expr RHS. This
9914 ;; is just a crude guess based on finding " = " on the previous
9915 ;; line containing actual code.
9916 (setq pos (save-excursion
9917 (forward-line -1)
9918 (goto-char (point-at-bol))
9919 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
9920 (point-at-eol) t)
9921 (goto-char (match-end 1))
9922 (skip-chars-forward " \t\r\n")
9923 (current-column))))
9924 (when pos
9925 (incf pos js2-basic-offset)
9926 (push pos positions))
9927
9928 ;; Third likely point: same indent as previous line of code.
9929 ;; Make it the first likely point if we're not on an
9930 ;; arglist-close line and previous line ends in a comma, or
9931 ;; both this line and prev line look like object-literal
9932 ;; elements.
9933 (setq pos (save-excursion
9934 (goto-char (point-at-bol))
9935 (js2-backward-sws)
9936 (back-to-indentation)
9937 (prog1
9938 (current-column)
9939 ;; while we're here, look for trailing comma
9940 (if (save-excursion
9941 (goto-char (point-at-eol))
9942 (js2-backward-sws)
9943 (eq (char-before) ?,))
9944 (setq arglist-cont (1- (point)))))))
9945 (when pos
9946 (if (and (or arglist-cont
9947 (js2-indent-in-objlit-p parse-status))
9948 (not (js2-arglist-close)))
9949 (setq same-indent pos))
9950 (push pos positions))
9951
9952 ;; Fourth likely point: first preceding code with less indentation.
9953 ;; than the immediately preceding code line.
9954 (setq pos (save-excursion
9955 (back-to-indentation)
9956 (js2-backward-sws)
9957 (back-to-indentation)
9958 (setq anchor (current-column))
9959 (while (and (zerop (forward-line -1))
9960 (>= (progn
9961 (back-to-indentation)
9962 (current-column))
9963 anchor)))
9964 (setq pos (current-column))))
9965 (push pos positions)
9966
9967 ;; nesting-heuristic position, main by default
9968 (push (setq main-pos normal-col) positions)
9969
9970 ;; delete duplicates and sort positions list
9971 (setq positions (sort (delete-dups positions) '<))
9972
9973 ;; comma-list continuation lines: prev line indent takes precedence
9974 (if same-indent
9975 (setq main-pos same-indent))
9976
9977 ;; common special cases where we want to indent in from previous line
9978 (if (or (js2-indent-case-block-p)
9979 (js2-indent-objlit-arg-p parse-status))
9980 (setq main-pos basic-offset))
9981
9982 ;; if bouncing backwards, reverse positions list
9983 (if backwards
9984 (setq positions (reverse positions)))
9985
9986 ;; record whether we're already sitting on one of the alternatives
9987 (setq pos (member cur-indent positions))
9988
9989 (cond
9990 ;; case 0: we're one one of the alternatives and this is the
9991 ;; first time they've pressed TAB on this line (best-guess).
9992 ((and js2-mode-indent-ignore-first-tab
9993 pos
9994 ;; first time pressing TAB on this line?
9995 (not (eq js2-mode-last-indented-line current-line)))
9996 ;; do nothing
9997 (setq computed-pos nil))
9998 ;; case 1: only one computed position => use it
9999 ((null (cdr positions))
10000 (setq computed-pos 0))
10001 ;; case 2: not on any of the computed spots => use main spot
10002 ((not pos)
10003 (setq computed-pos (js2-position main-pos positions)))
10004 ;; case 3: on last position: cycle to first position
10005 ((null (cdr pos))
10006 (setq computed-pos 0))
10007 ;; case 4: on intermediate position: cycle to next position
10008 (t
10009 (setq computed-pos (js2-position (second pos) positions))))
10010
10011 ;; see if any hooks want to indent; otherwise we do it
10012 (loop with result = nil
10013 for hook in js2-indent-hook
10014 while (null result)
10015 do
10016 (setq result (funcall hook positions computed-pos))
10017 finally do
10018 (unless (or result (null computed-pos))
10019 (indent-line-to (nth computed-pos positions)))))
10020
10021 ;; finally
10022 (if js2-mode-indent-inhibit-undo
10023 (setq buffer-undo-list old-buffer-undo-list))
10024 ;; see commentary for `js2-mode-last-indented-line'
10025 (setq js2-mode-last-indented-line current-line))))
10026
10027 (defun js2-indent-bounce-backwards ()
10028 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10029 cycles between the computed indentation positions in reverse order."
10030 (interactive)
10031 (js2-indent-line t))
10032
10033 (defun js2-1-line-comment-continuation-p ()
10034 "Return t if we're in a 1-line comment continuation.
10035 If so, we don't ever want to use bounce-indent."
10036 (save-excursion
10037 (and (progn
10038 (forward-line 0)
10039 (looking-at "\\s-*//"))
10040 (progn
10041 (forward-line -1)
10042 (forward-line 0)
10043 (when (looking-at "\\s-*$")
10044 (js2-backward-sws)
10045 (forward-line 0))
10046 (looking-at "\\s-*//")))))
10047
10048 (defun js2-indent-line (&optional bounce-backwards)
10049 "Indent the current line as JavaScript source text."
10050 (interactive)
10051 (let (parse-status current-indent offset indent-col moved
10052 ;; Don't whine about errors/warnings when we're indenting.
10053 ;; This has to be set before calling parse-partial-sexp below.
10054 (inhibit-point-motion-hooks t))
10055 (setq parse-status (save-excursion
10056 (syntax-ppss (point-at-bol)))
10057 offset (- (point) (save-excursion
10058 (back-to-indentation)
10059 (point))))
10060 (js2-with-underscore-as-word-syntax
10061 (if (nth 4 parse-status)
10062 (js2-lineup-comment parse-status)
10063 (setq indent-col (js2-proper-indentation parse-status))
10064 ;; See comments below about `js2-mode-last-indented-line'.
10065 (cond
10066 ;; bounce-indenting is disabled during electric-key indent.
10067 ;; It doesn't work well on first line of buffer.
10068 ((and js2-bounce-indent-p
10069 (not (js2-same-line (point-min)))
10070 (not (js2-1-line-comment-continuation-p)))
10071 (js2-bounce-indent indent-col parse-status bounce-backwards))
10072 ;; just indent to the guesser's likely spot
10073 (t (indent-line-to indent-col))))
10074 (when (plusp offset)
10075 (forward-char offset)))))
10076
10077 (defun js2-indent-region (start end)
10078 "Indent the region, but don't use bounce indenting."
10079 (let ((js2-bounce-indent-p nil)
10080 (indent-region-function nil)
10081 (after-change-functions (remq 'js2-mode-edit
10082 after-change-functions)))
10083 (indent-region start end nil) ; nil for byte-compiler
10084 (js2-mode-edit start end (- end start))))
10085
10086 (defvar js2-minor-mode-map
10087 (let ((map (make-sparse-keymap)))
10088 (define-key map (kbd "C-c C-`") #'js2-next-error)
10089 (define-key map [mouse-1] #'js2-mode-show-node)
10090 map)
10091 "Keymap used when `js2-minor-mode' is active.")
10092
10093 ;;;###autoload
10094 (define-minor-mode js2-minor-mode
10095 "Minor mode for running js2 as a background linter.
10096 This allows you to use a different major mode for JavaScript editing,
10097 such as `espresso-mode', while retaining the asynchronous error/warning
10098 highlighting features of `js2-mode'."
10099 :group 'js2-mode
10100 :lighter " js-lint"
10101 (if js2-minor-mode
10102 (js2-minor-mode-enter)
10103 (js2-minor-mode-exit)))
10104
10105 (defun js2-minor-mode-enter ()
10106 "Initialization for `js2-minor-mode'."
10107 (set (make-local-variable 'max-lisp-eval-depth)
10108 (max max-lisp-eval-depth 3000))
10109 (setq next-error-function #'js2-next-error)
10110 (js2-set-default-externs)
10111 ;; Experiment: make reparse-delay longer for longer files.
10112 (if (plusp js2-dynamic-idle-timer-adjust)
10113 (setq js2-idle-timer-delay
10114 (* js2-idle-timer-delay
10115 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10116 (setq js2-mode-buffer-dirty-p t
10117 js2-mode-parsing nil)
10118 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10119 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10120 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10121 (when js2-include-jslint-globals
10122 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10123 (run-hooks 'js2-init-hook)
10124 (js2-reparse))
10125
10126 (defun js2-minor-mode-exit ()
10127 "Turn off `js2-minor-mode'."
10128 (setq next-error-function nil)
10129 (remove-hook 'after-change-functions #'js2-mode-edit t)
10130 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10131 (when js2-mode-node-overlay
10132 (delete-overlay js2-mode-node-overlay)
10133 (setq js2-mode-node-overlay nil))
10134 (js2-remove-overlays)
10135 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
10136 (setq js2-mode-ast nil))
10137
10138 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10139 (make-variable-buffer-local 'js2-source-buffer)
10140
10141 (defun* js2-display-error-list ()
10142 "Display a navigable buffer listing parse errors/warnings."
10143 (interactive)
10144 (unless (js2-have-errors-p)
10145 (message "No errors")
10146 (return-from js2-display-error-list))
10147 (labels ((annotate-list
10148 (lst type)
10149 "Add diagnostic TYPE and line number to errs list"
10150 (mapcar (lambda (err)
10151 (list err type (line-number-at-pos (nth 1 err))))
10152 lst)))
10153 (let* ((srcbuf (current-buffer))
10154 (errbuf (get-buffer-create "*js-lint*"))
10155 (errors (annotate-list
10156 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10157 'js2-error)) ; must be a valid face name
10158 (warnings (annotate-list
10159 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10160 'js2-warning)) ; must be a valid face name
10161 (all-errs (sort (append errors warnings)
10162 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10163 (with-current-buffer errbuf
10164 (let ((inhibit-read-only t))
10165 (erase-buffer)
10166 (dolist (err all-errs)
10167 (destructuring-bind ((msg-key beg end &rest) type line) err
10168 (insert-text-button
10169 (format "line %d: %s" line (js2-get-msg msg-key))
10170 'face type
10171 'follow-link "\C-m"
10172 'action 'js2-error-buffer-jump
10173 'js2-msg (js2-get-msg msg-key)
10174 'js2-pos beg)
10175 (insert "\n"))))
10176 (js2-error-buffer-mode)
10177 (setq js2-source-buffer srcbuf)
10178 (pop-to-buffer errbuf)
10179 (goto-char (point-min))
10180 (unless (eobp)
10181 (js2-error-buffer-view))))))
10182
10183 (defvar js2-error-buffer-mode-map
10184 (let ((map (make-sparse-keymap)))
10185 (define-key map "n" #'js2-error-buffer-next)
10186 (define-key map "p" #'js2-error-buffer-prev)
10187 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10188 (define-key map "o" #'js2-error-buffer-view)
10189 (define-key map "q" #'js2-error-buffer-quit)
10190 map)
10191 "Keymap used for js2 diagnostics buffers.")
10192
10193 (defun js2-error-buffer-mode ()
10194 "Major mode for js2 diagnostics buffers.
10195 Selecting an error will jump it to the corresponding source-buffer error.
10196 \\{js2-error-buffer-mode-map}"
10197 (interactive)
10198 (setq major-mode 'js2-error-buffer-mode
10199 mode-name "JS Lint Diagnostics")
10200 (use-local-map js2-error-buffer-mode-map)
10201 (setq truncate-lines t)
10202 (set-buffer-modified-p nil)
10203 (setq buffer-read-only t)
10204 (run-hooks 'js2-error-buffer-mode-hook))
10205
10206 (defun js2-error-buffer-next ()
10207 "Move to next error and view it."
10208 (interactive)
10209 (when (zerop (forward-line 1))
10210 (js2-error-buffer-view)))
10211
10212 (defun js2-error-buffer-prev ()
10213 "Move to previous error and view it."
10214 (interactive)
10215 (when (zerop (forward-line -1))
10216 (js2-error-buffer-view)))
10217
10218 (defun js2-error-buffer-quit ()
10219 "Kill the current buffer."
10220 (interactive)
10221 (kill-buffer))
10222
10223 (defun js2-error-buffer-jump (&rest ignored)
10224 "Jump cursor to current error in source buffer."
10225 (interactive)
10226 (when (js2-error-buffer-view)
10227 (pop-to-buffer js2-source-buffer)))
10228
10229 (defun js2-error-buffer-view ()
10230 "Scroll source buffer to show error at current line."
10231 (interactive)
10232 (cond
10233 ((not (eq major-mode 'js2-error-buffer-mode))
10234 (message "Not in a js2 errors buffer"))
10235 ((not (buffer-live-p js2-source-buffer))
10236 (message "Source buffer has been killed"))
10237 ((not (wholenump (get-text-property (point) 'js2-pos)))
10238 (message "There does not seem to be an error here"))
10239 (t
10240 (let ((pos (get-text-property (point) 'js2-pos))
10241 (msg (get-text-property (point) 'js2-msg)))
10242 (save-selected-window
10243 (pop-to-buffer js2-source-buffer)
10244 (goto-char pos)
10245 (message msg))))))
10246
10247 ;;;###autoload
10248 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10249 ;; FIXME: Should derive from js-mode.
10250 "Major mode for editing JavaScript code."
10251 ;; Used by comment-region; don't change it.
10252 (set (make-local-variable 'comment-start) "//")
10253 (set (make-local-variable 'comment-end) "")
10254 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
10255 (set (make-local-variable 'max-lisp-eval-depth)
10256 (max max-lisp-eval-depth 3000))
10257 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10258 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10259 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10260 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10261 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10262 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10263 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10264 ;; for characters inside regexp literals.
10265 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10266 ;; this is necessary to make `show-paren-function' work properly
10267 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10268 ;; needed for M-x rgrep, among other things
10269 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10270
10271 (set (make-local-variable 'electric-indent-chars)
10272 (append '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
10273 electric-indent-chars))
10274 (set (make-local-variable 'electric-layout-rules)
10275 '((?\; . after) (?\{ . after) (?\} . before)))
10276
10277 ;; some variables needed by cc-engine for paragraph-fill, etc.
10278 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10279 c-comment-start-regexp "/[*/]\\|\\s|"
10280 c-line-comment-starter "//"
10281 c-paragraph-start js2-paragraph-start
10282 c-paragraph-separate "$"
10283 c-syntactic-ws-start js2-syntactic-ws-start
10284 c-syntactic-ws-end js2-syntactic-ws-end
10285 c-syntactic-eol js2-syntactic-eol)
10286
10287 (let ((c-buffer-is-cc-mode t))
10288 ;; Copied from `js-mode'. Also see Bug#6071.
10289 (make-local-variable 'paragraph-start)
10290 (make-local-variable 'paragraph-separate)
10291 (make-local-variable 'paragraph-ignore-fill-prefix)
10292 (make-local-variable 'adaptive-fill-mode)
10293 (make-local-variable 'adaptive-fill-regexp)
10294 (c-setup-paragraph-variables))
10295
10296 (setq font-lock-defaults '(nil t))
10297
10298 ;; Experiment: make reparse-delay longer for longer files.
10299 (when (plusp js2-dynamic-idle-timer-adjust)
10300 (setq js2-idle-timer-delay
10301 (* js2-idle-timer-delay
10302 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10303
10304 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10305 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10306 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10307 (setq next-error-function #'js2-next-error)
10308 (imenu-add-to-menubar (concat "IM-" mode-name))
10309 (add-to-invisibility-spec '(js2-outline . t))
10310 (set (make-local-variable 'line-move-ignore-invisible) t)
10311 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10312
10313 (setq js2-mode-functions-hidden nil
10314 js2-mode-comments-hidden nil
10315 js2-mode-buffer-dirty-p t
10316 js2-mode-parsing nil)
10317
10318 (js2-set-default-externs)
10319
10320 (when js2-include-jslint-globals
10321 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10322
10323 (run-hooks 'js2-init-hook)
10324
10325 (js2-reparse))
10326
10327 (defun js2-mode-exit ()
10328 "Exit `js2-mode' and clean up."
10329 (interactive)
10330 (when js2-mode-node-overlay
10331 (delete-overlay js2-mode-node-overlay)
10332 (setq js2-mode-node-overlay nil))
10333 (js2-remove-overlays)
10334 (setq js2-mode-ast nil)
10335 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10336 (remove-from-invisibility-spec '(js2-outline . t))
10337 (js2-mode-show-all)
10338 (with-silent-modifications
10339 (js2-clear-face (point-min) (point-max))))
10340
10341 (defun js2-mode-reset-timer ()
10342 "Cancel any existing parse timer and schedule a new one."
10343 (if js2-mode-parse-timer
10344 (cancel-timer js2-mode-parse-timer))
10345 (setq js2-mode-parsing nil)
10346 (let ((timer (timer-create)))
10347 (setq js2-mode-parse-timer timer)
10348 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10349 (timer-set-idle-time timer js2-idle-timer-delay)
10350 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10351 (timer-activate-when-idle timer nil)))
10352
10353 (defun js2-mode-idle-reparse (buffer)
10354 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10355 it to be reparsed when the buffer is selected."
10356 (if (eq buffer (current-buffer))
10357 (js2-reparse)
10358 ;; reparse when the buffer is selected again
10359 (with-current-buffer buffer
10360 (add-hook 'window-configuration-change-hook
10361 #'js2-mode-idle-reparse-inner
10362 nil t))))
10363
10364 (defun js2-mode-idle-reparse-inner ()
10365 (remove-hook 'window-configuration-change-hook
10366 #'js2-mode-idle-reparse-inner
10367 t)
10368 (js2-reparse))
10369
10370 (defun js2-mode-edit (beg end len)
10371 "Schedule a new parse after buffer is edited.
10372 Buffer edit spans from BEG to END and is of length LEN."
10373 (setq js2-mode-buffer-dirty-p t)
10374 (js2-mode-hide-overlay)
10375 (js2-mode-reset-timer))
10376
10377 (defun js2-minor-mode-edit (beg end len)
10378 "Callback for buffer edits in `js2-mode'.
10379 Schedules a new parse after buffer is edited.
10380 Buffer edit spans from BEG to END and is of length LEN."
10381 (setq js2-mode-buffer-dirty-p t)
10382 (js2-mode-hide-overlay)
10383 (js2-mode-reset-timer))
10384
10385 (defun js2-reparse (&optional force)
10386 "Re-parse current buffer after user finishes some data entry.
10387 If we get any user input while parsing, including cursor motion,
10388 we discard the parse and reschedule it. If FORCE is nil, then the
10389 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10390 (let (time
10391 interrupted-p
10392 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10393 (unless js2-mode-parsing
10394 (setq js2-mode-parsing t)
10395 (unwind-protect
10396 (when (or js2-mode-buffer-dirty-p force)
10397 (js2-remove-overlays)
10398 (with-silent-modifications
10399 (setq js2-mode-buffer-dirty-p nil
10400 js2-mode-fontifications nil
10401 js2-mode-deferred-properties nil)
10402 (if js2-mode-verbose-parse-p
10403 (message "parsing..."))
10404 (setq time
10405 (js2-time
10406 (setq interrupted-p
10407 (catch 'interrupted
10408 (js2-parse)
10409 ;; if parsing is interrupted, comments and regex
10410 ;; literals stay ignored by `parse-partial-sexp'
10411 (remove-text-properties (point-min) (point-max)
10412 '(syntax-table))
10413 (js2-mode-apply-deferred-properties)
10414 (js2-mode-remove-suppressed-warnings)
10415 (js2-mode-show-warnings)
10416 (js2-mode-show-errors)
10417 (if (>= js2-highlight-level 1)
10418 (js2-highlight-jsdoc js2-mode-ast))
10419 nil))))
10420 (if interrupted-p
10421 (progn
10422 ;; unfinished parse => try again
10423 (setq js2-mode-buffer-dirty-p t)
10424 (js2-mode-reset-timer))
10425 (if js2-mode-verbose-parse-p
10426 (message "Parse time: %s" time)))))
10427 (setq js2-mode-parsing nil)
10428 (unless interrupted-p
10429 (setq js2-mode-parse-timer nil))))))
10430
10431 (defun js2-mode-show-node (event)
10432 "Debugging aid: highlight selected AST node on mouse click."
10433 (interactive "e")
10434 (mouse-set-point event)
10435 (setq deactivate-mark t)
10436 (when js2-mode-show-overlay
10437 (let ((node (js2-node-at-point))
10438 beg end)
10439 (if (null node)
10440 (message "No node found at location %s" (point))
10441 (setq beg (js2-node-abs-pos node)
10442 end (+ beg (js2-node-len node)))
10443 (if js2-mode-node-overlay
10444 (move-overlay js2-mode-node-overlay beg end)
10445 (setq js2-mode-node-overlay (make-overlay beg end))
10446 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10447 (with-silent-modifications
10448 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10449 (message "%s, parent: %s"
10450 (js2-node-short-name node)
10451 (if (js2-node-parent node)
10452 (js2-node-short-name (js2-node-parent node))
10453 "nil"))))))
10454
10455 (defun js2-mode-hide-overlay (&optional p1 p2)
10456 "Remove the debugging overlay when the point moves.
10457 P1 and P2 are the old and new values of point, respectively."
10458 (when js2-mode-node-overlay
10459 (let ((beg (overlay-start js2-mode-node-overlay))
10460 (end (overlay-end js2-mode-node-overlay)))
10461 ;; Sometimes we're called spuriously.
10462 (unless (and p2
10463 (>= p2 beg)
10464 (<= p2 end))
10465 (with-silent-modifications
10466 (remove-text-properties beg end '(point-left nil)))
10467 (delete-overlay js2-mode-node-overlay)
10468 (setq js2-mode-node-overlay nil)))))
10469
10470 (defun js2-mode-reset ()
10471 "Debugging helper: reset everything."
10472 (interactive)
10473 (js2-mode-exit)
10474 (js2-mode))
10475
10476 (defun js2-mode-show-warn-or-err (e face)
10477 "Highlight a warning or error E with FACE.
10478 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10479 The last element is optional. When present, use instead of FACE."
10480 (let* ((key (first e))
10481 (beg (second e))
10482 (end (+ beg (third e)))
10483 ;; Don't inadvertently go out of bounds.
10484 (beg (max (point-min) (min beg (point-max))))
10485 (end (max (point-min) (min end (point-max))))
10486 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10487 (ovl (make-overlay beg end)))
10488 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10489 (overlay-put ovl 'js2-error t)
10490 (put-text-property beg end 'help-echo (js2-get-msg key))
10491 (put-text-property beg end 'point-entered #'js2-echo-error)))
10492
10493 (defun js2-remove-overlays ()
10494 "Remove overlays from buffer that have a `js2-error' property."
10495 (let ((beg (point-min))
10496 (end (point-max)))
10497 (save-excursion
10498 (dolist (o (overlays-in beg end))
10499 (when (overlay-get o 'js2-error)
10500 (delete-overlay o))))))
10501
10502 (defun js2-error-at-point (&optional pos)
10503 "Return non-nil if there's an error overlay at POS.
10504 Defaults to point."
10505 (loop with pos = (or pos (point))
10506 for o in (overlays-at pos)
10507 thereis (overlay-get o 'js2-error)))
10508
10509 (defun js2-mode-apply-deferred-properties ()
10510 "Apply fontifications and other text properties recorded during parsing."
10511 (when (plusp js2-highlight-level)
10512 ;; We defer clearing faces as long as possible to eliminate flashing.
10513 (js2-clear-face (point-min) (point-max))
10514 ;; Have to reverse the recorded fontifications list so that errors
10515 ;; and warnings overwrite the normal fontifications.
10516 (dolist (f (nreverse js2-mode-fontifications))
10517 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10518 (setq js2-mode-fontifications nil))
10519 (dolist (p js2-mode-deferred-properties)
10520 (apply #'put-text-property p))
10521 (setq js2-mode-deferred-properties nil))
10522
10523 (defun js2-mode-show-errors ()
10524 "Highlight syntax errors."
10525 (when js2-mode-show-parse-errors
10526 (dolist (e (js2-ast-root-errors js2-mode-ast))
10527 (js2-mode-show-warn-or-err e 'js2-error))))
10528
10529 (defun js2-mode-remove-suppressed-warnings ()
10530 "Take suppressed warnings out of the AST warnings list.
10531 This ensures that the counts and `next-error' are correct."
10532 (setf (js2-ast-root-warnings js2-mode-ast)
10533 (js2-delete-if
10534 (lambda (e)
10535 (let ((key (caar e)))
10536 (or
10537 (and (not js2-strict-trailing-comma-warning)
10538 (string-match "trailing\\.comma" key))
10539 (and (not js2-strict-cond-assign-warning)
10540 (string= key "msg.equal.as.assign"))
10541 (and js2-missing-semi-one-line-override
10542 (string= key "msg.missing.semi")
10543 (let* ((beg (second e))
10544 (node (js2-node-at-point beg))
10545 (fn (js2-mode-find-parent-fn node))
10546 (body (and fn (js2-function-node-body fn)))
10547 (lc (and body (js2-node-abs-pos body)))
10548 (rc (and lc (+ lc (js2-node-len body)))))
10549 (and fn
10550 (or (null body)
10551 (save-excursion
10552 (goto-char beg)
10553 (and (js2-same-line lc)
10554 (js2-same-line rc))))))))))
10555 (js2-ast-root-warnings js2-mode-ast))))
10556
10557 (defun js2-mode-show-warnings ()
10558 "Highlight strict-mode warnings."
10559 (when js2-mode-show-strict-warnings
10560 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10561 (js2-mode-show-warn-or-err e 'js2-warning))))
10562
10563 (defun js2-echo-error (old-point new-point)
10564 "Called by point-motion hooks."
10565 (let ((msg (get-text-property new-point 'help-echo)))
10566 (when (and (stringp msg)
10567 (not (active-minibuffer-window))
10568 (not (current-message)))
10569 (message msg))))
10570
10571 (defalias #'js2-echo-help #'js2-echo-error)
10572
10573 (defun js2-line-break (&optional soft)
10574 "Break line at point and indent, continuing comment if within one.
10575 If inside a string, and `js2-concat-multiline-strings' is not
10576 nil, turn it into concatenation."
10577 (interactive)
10578 (let ((parse-status (syntax-ppss)))
10579 (cond
10580 ;; Check if we're inside a string.
10581 ((nth 3 parse-status)
10582 (if js2-concat-multiline-strings
10583 (js2-mode-split-string parse-status)
10584 (insert "\n")))
10585 ;; Check if inside a block comment.
10586 ((nth 4 parse-status)
10587 (js2-mode-extend-comment (nth 8 parse-status)))
10588 (t
10589 (newline-and-indent)))))
10590
10591 (defun js2-mode-split-string (parse-status)
10592 "Turn a newline in mid-string into a string concatenation.
10593 PARSE-STATUS is as documented in `parse-partial-sexp'."
10594 (let* ((col (current-column))
10595 (quote-char (nth 3 parse-status))
10596 (string-beg (nth 8 parse-status))
10597 (at-eol (eq js2-concat-multiline-strings 'eol)))
10598 (insert quote-char)
10599 (if at-eol
10600 (insert " +\n")
10601 (insert "\n"))
10602 (unless at-eol
10603 (insert "+ "))
10604 (js2-indent-line)
10605 (insert quote-char)
10606 (when (eolp)
10607 (insert quote-char)
10608 (backward-char 1))))
10609
10610 (defun js2-mode-extend-comment (start-pos)
10611 "Indent the line and, when inside a comment block, add comment prefix."
10612 (let (star single col first-line needs-close)
10613 (save-excursion
10614 (back-to-indentation)
10615 (when (< (point) start-pos)
10616 (goto-char start-pos))
10617 (cond
10618 ((looking-at "\\*[^/]")
10619 (setq star t
10620 col (current-column)))
10621 ((looking-at "/\\*")
10622 (setq star t
10623 first-line t
10624 col (1+ (current-column))))
10625 ((looking-at "//")
10626 (setq single t
10627 col (current-column)))))
10628 ;; Heuristic for whether we need to close the comment:
10629 ;; if we've got a parse error here, assume it's an unterminated
10630 ;; comment.
10631 (setq needs-close
10632 (or
10633 (eq (get-text-property (1- (point)) 'point-entered)
10634 'js2-echo-error)
10635 ;; The heuristic above doesn't work well when we're
10636 ;; creating a comment and there's another one downstream,
10637 ;; as our parser thinks this one ends at the end of the
10638 ;; next one. (You can have a /* inside a js block comment.)
10639 ;; So just close it if the next non-ws char isn't a *.
10640 (and first-line
10641 (eolp)
10642 (save-excursion
10643 (skip-chars-forward " \t\r\n")
10644 (not (eq (char-after) ?*))))))
10645 (delete-horizontal-space)
10646 (insert "\n")
10647 (cond
10648 (star
10649 (indent-to col)
10650 (insert "* ")
10651 (if (and first-line needs-close)
10652 (save-excursion
10653 (insert "\n")
10654 (indent-to col)
10655 (insert "*/"))))
10656 ((and single
10657 (save-excursion
10658 (and (zerop (forward-line 1))
10659 (looking-at "\\s-*//"))))
10660 (indent-to col)
10661 (insert "// ")))
10662 ;; Don't need to extend the comment after all.
10663 (js2-indent-line)))
10664
10665 (defun js2-beginning-of-line ()
10666 "Toggle point between bol and first non-whitespace char in line.
10667 Also moves past comment delimiters when inside comments."
10668 (interactive)
10669 (let (node beg)
10670 (cond
10671 ((bolp)
10672 (back-to-indentation))
10673 ((looking-at "//")
10674 (skip-chars-forward "/ \t"))
10675 ((and (eq (char-after) ?*)
10676 (setq node (js2-comment-at-point))
10677 (memq (js2-comment-node-format node) '(jsdoc block))
10678 (save-excursion
10679 (skip-chars-backward " \t")
10680 (bolp)))
10681 (skip-chars-forward "\* \t"))
10682 (t
10683 (goto-char (point-at-bol))))))
10684
10685 (defun js2-end-of-line ()
10686 "Toggle point between eol and last non-whitespace char in line."
10687 (interactive)
10688 (if (eolp)
10689 (skip-chars-backward " \t")
10690 (goto-char (point-at-eol))))
10691
10692 (defun js2-mode-wait-for-parse (callback)
10693 "Invoke CALLBACK when parsing is finished.
10694 If parsing is already finished, calls CALLBACK immediately."
10695 (if (not js2-mode-buffer-dirty-p)
10696 (funcall callback)
10697 (push callback js2-mode-pending-parse-callbacks)
10698 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10699
10700 (defun js2-mode-parse-finished ()
10701 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10702 ;; We can't let errors propagate up, since it prevents the
10703 ;; `js2-parse' method from completing normally and returning
10704 ;; the ast, which makes things mysteriously not work right.
10705 (unwind-protect
10706 (dolist (cb js2-mode-pending-parse-callbacks)
10707 (condition-case err
10708 (funcall cb)
10709 (error (message "%s" err))))
10710 (setq js2-mode-pending-parse-callbacks nil)))
10711
10712 (defun js2-mode-flag-region (from to flag)
10713 "Hide or show text from FROM to TO, according to FLAG.
10714 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10715 Returns the created overlay if FLAG is non-nil."
10716 (remove-overlays from to 'invisible 'js2-outline)
10717 (when flag
10718 (let ((o (make-overlay from to)))
10719 (overlay-put o 'invisible 'js2-outline)
10720 (overlay-put o 'isearch-open-invisible
10721 'js2-isearch-open-invisible)
10722 o)))
10723
10724 ;; Function to be set as an outline-isearch-open-invisible' property
10725 ;; to the overlay that makes the outline invisible (see
10726 ;; `js2-mode-flag-region').
10727 (defun js2-isearch-open-invisible (overlay)
10728 ;; We rely on the fact that isearch places point on the matched text.
10729 (js2-mode-show-element))
10730
10731 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10732 "Return cons cell of bounds of folding overlay at POS.
10733 Returns nil if not found."
10734 (let ((overlays (overlays-at (or pos (point))))
10735 o)
10736 (while (and overlays
10737 (not o))
10738 (if (overlay-get (car overlays) 'invisible)
10739 (setq o (car overlays))
10740 (setq overlays (cdr overlays))))
10741 (if o
10742 (cons (overlay-start o) (overlay-end o)))))
10743
10744 (defun js2-mode-function-at-point (&optional pos)
10745 "Return the innermost function node enclosing current point.
10746 Returns nil if point is not in a function."
10747 (let ((node (js2-node-at-point pos)))
10748 (while (and node (not (js2-function-node-p node)))
10749 (setq node (js2-node-parent node)))
10750 (if (js2-function-node-p node)
10751 node)))
10752
10753 (defun js2-mode-toggle-element ()
10754 "Hide or show the foldable element at the point."
10755 (interactive)
10756 (let (comment fn pos)
10757 (save-excursion
10758 (cond
10759 ;; /* ... */ comment?
10760 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10761 (if (js2-mode-invisible-overlay-bounds
10762 (setq pos (+ 3 (js2-node-abs-pos comment))))
10763 (progn
10764 (goto-char pos)
10765 (js2-mode-show-element))
10766 (js2-mode-hide-element)))
10767 ;; //-comment?
10768 ((save-excursion
10769 (back-to-indentation)
10770 (looking-at js2-mode-//-comment-re))
10771 (js2-mode-toggle-//-comment))
10772 ;; function?
10773 ((setq fn (js2-mode-function-at-point))
10774 (setq pos (and (js2-function-node-body fn)
10775 (js2-node-abs-pos (js2-function-node-body fn))))
10776 (goto-char (1+ pos))
10777 (if (js2-mode-invisible-overlay-bounds)
10778 (js2-mode-show-element)
10779 (js2-mode-hide-element)))
10780 (t
10781 (message "Nothing at point to hide or show"))))))
10782
10783 (defun js2-mode-hide-element ()
10784 "Fold/hide contents of a block, showing ellipses.
10785 Show the hidden text with \\[js2-mode-show-element]."
10786 (interactive)
10787 (if js2-mode-buffer-dirty-p
10788 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10789 (let (node body beg end)
10790 (cond
10791 ((js2-mode-invisible-overlay-bounds)
10792 (message "already hidden"))
10793 (t
10794 (setq node (js2-node-at-point))
10795 (cond
10796 ((js2-block-comment-p node)
10797 (js2-mode-hide-comment node))
10798 (t
10799 (while (and node (not (js2-function-node-p node)))
10800 (setq node (js2-node-parent node)))
10801 (if (and node
10802 (setq body (js2-function-node-body node)))
10803 (progn
10804 (setq beg (js2-node-abs-pos body)
10805 end (+ beg (js2-node-len body)))
10806 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10807 (message "No collapsable element found at point"))))))))
10808
10809 (defun js2-mode-show-element ()
10810 "Show the hidden element at current point."
10811 (interactive)
10812 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10813 (if bounds
10814 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
10815 (message "Nothing to un-hide"))))
10816
10817 (defun js2-mode-show-all ()
10818 "Show all of the text in the buffer."
10819 (interactive)
10820 (js2-mode-flag-region (point-min) (point-max) nil))
10821
10822 (defun js2-mode-toggle-hide-functions ()
10823 (interactive)
10824 (if js2-mode-functions-hidden
10825 (js2-mode-show-functions)
10826 (js2-mode-hide-functions)))
10827
10828 (defun js2-mode-hide-functions ()
10829 "Hides all non-nested function bodies in the buffer.
10830 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10831 to open an individual entry."
10832 (interactive)
10833 (if js2-mode-buffer-dirty-p
10834 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
10835 (if (null js2-mode-ast)
10836 (message "Oops - parsing failed")
10837 (setq js2-mode-functions-hidden t)
10838 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
10839
10840 (defun js2-mode-function-hider (n endp)
10841 (when (not endp)
10842 (let ((tt (js2-node-type n))
10843 body beg end)
10844 (cond
10845 ((and (= tt js2-FUNCTION)
10846 (setq body (js2-function-node-body n)))
10847 (setq beg (js2-node-abs-pos body)
10848 end (+ beg (js2-node-len body)))
10849 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
10850 nil) ; don't process children of function
10851 (t
10852 t))))) ; keep processing other AST nodes
10853
10854 (defun js2-mode-show-functions ()
10855 "Un-hide any folded function bodies in the buffer."
10856 (interactive)
10857 (setq js2-mode-functions-hidden nil)
10858 (save-excursion
10859 (goto-char (point-min))
10860 (while (/= (goto-char (next-overlay-change (point)))
10861 (point-max))
10862 (dolist (o (overlays-at (point)))
10863 (when (and (overlay-get o 'invisible)
10864 (not (overlay-get o 'comment)))
10865 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10866
10867 (defun js2-mode-hide-comment (n)
10868 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
10869 3 ; /**
10870 2)) ; /*
10871 (beg (+ (js2-node-abs-pos n) head))
10872 (end (- (+ beg (js2-node-len n)) head 2))
10873 (o (js2-mode-flag-region beg end 'hide)))
10874 (overlay-put o 'comment t)))
10875
10876 (defun js2-mode-toggle-hide-comments ()
10877 "Folds all block comments in the buffer.
10878 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10879 to open an individual entry."
10880 (interactive)
10881 (if js2-mode-comments-hidden
10882 (js2-mode-show-comments)
10883 (js2-mode-hide-comments)))
10884
10885 (defun js2-mode-hide-comments ()
10886 (interactive)
10887 (if js2-mode-buffer-dirty-p
10888 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
10889 (if (null js2-mode-ast)
10890 (message "Oops - parsing failed")
10891 (setq js2-mode-comments-hidden t)
10892 (dolist (n (js2-ast-root-comments js2-mode-ast))
10893 (let ((format (js2-comment-node-format n)))
10894 (when (js2-block-comment-p n)
10895 (js2-mode-hide-comment n))))
10896 (js2-mode-hide-//-comments)))
10897
10898 (defun js2-mode-extend-//-comment (direction)
10899 "Find start or end of a block of similar //-comment lines.
10900 DIRECTION is -1 to look back, 1 to look forward.
10901 INDENT is the indentation level to match.
10902 Returns the end-of-line position of the furthest adjacent
10903 //-comment line with the same indentation as the current line.
10904 If there is no such matching line, returns current end of line."
10905 (let ((pos (point-at-eol))
10906 (indent (current-indentation)))
10907 (save-excursion
10908 (while (and (zerop (forward-line direction))
10909 (looking-at js2-mode-//-comment-re)
10910 (eq indent (length (match-string 1))))
10911 (setq pos (point-at-eol))
10912 pos))))
10913
10914 (defun js2-mode-hide-//-comments ()
10915 "Fold adjacent 1-line comments, showing only snippet of first one."
10916 (let (beg end)
10917 (save-excursion
10918 (goto-char (point-min))
10919 (while (re-search-forward js2-mode-//-comment-re nil t)
10920 (setq beg (point)
10921 end (js2-mode-extend-//-comment 1))
10922 (unless (eq beg end)
10923 (overlay-put (js2-mode-flag-region beg end 'hide)
10924 'comment t))
10925 (goto-char end)
10926 (forward-char 1)))))
10927
10928 (defun js2-mode-toggle-//-comment ()
10929 "Fold or un-fold any multi-line //-comment at point.
10930 Caller should have determined that this line starts with a //-comment."
10931 (let* ((beg (point-at-eol))
10932 (end beg))
10933 (save-excursion
10934 (goto-char end)
10935 (if (js2-mode-invisible-overlay-bounds)
10936 (js2-mode-show-element)
10937 ;; else hide the comment
10938 (setq beg (js2-mode-extend-//-comment -1)
10939 end (js2-mode-extend-//-comment 1))
10940 (unless (eq beg end)
10941 (overlay-put (js2-mode-flag-region beg end 'hide)
10942 'comment t))))))
10943
10944 (defun js2-mode-show-comments ()
10945 "Un-hide any hidden comments, leaving other hidden elements alone."
10946 (interactive)
10947 (setq js2-mode-comments-hidden nil)
10948 (save-excursion
10949 (goto-char (point-min))
10950 (while (/= (goto-char (next-overlay-change (point)))
10951 (point-max))
10952 (dolist (o (overlays-at (point)))
10953 (when (overlay-get o 'comment)
10954 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10955
10956 (defun js2-mode-display-warnings-and-errors ()
10957 "Turn on display of warnings and errors."
10958 (interactive)
10959 (setq js2-mode-show-parse-errors t
10960 js2-mode-show-strict-warnings t)
10961 (js2-reparse 'force))
10962
10963 (defun js2-mode-hide-warnings-and-errors ()
10964 "Turn off display of warnings and errors."
10965 (interactive)
10966 (setq js2-mode-show-parse-errors nil
10967 js2-mode-show-strict-warnings nil)
10968 (js2-reparse 'force))
10969
10970 (defun js2-mode-toggle-warnings-and-errors ()
10971 "Toggle the display of warnings and errors.
10972 Some users don't like having warnings/errors reported while they type."
10973 (interactive)
10974 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
10975 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
10976 (if (called-interactively-p 'any)
10977 (message "warnings and errors %s"
10978 (if js2-mode-show-parse-errors
10979 "enabled"
10980 "disabled")))
10981 (js2-reparse 'force))
10982
10983 (defun js2-mode-customize ()
10984 (interactive)
10985 (customize-group 'js2-mode))
10986
10987 (defun js2-mode-forward-sexp (&optional arg)
10988 "Move forward across one statement or balanced expression.
10989 With ARG, do it that many times. Negative arg -N means
10990 move backward across N balanced expressions."
10991 (interactive "p")
10992 (setq arg (or arg 1))
10993 (save-restriction
10994 (widen) ;; `blink-matching-open' calls `narrow-to-region'
10995 (js2-reparse))
10996 (let (forward-sexp-function
10997 node (start (point)) pos lp rp child)
10998 (cond
10999 ;; backward-sexp
11000 ;; could probably make this better for some cases:
11001 ;; - if in statement block (e.g. function body), go to parent
11002 ;; - infix exprs like (foo in bar) - maybe go to beginning
11003 ;; of infix expr if in the right-side expression?
11004 ((and arg (minusp arg))
11005 (dotimes (i (- arg))
11006 (js2-backward-sws)
11007 (forward-char -1) ; Enter the node we backed up to.
11008 (when (setq node (js2-node-at-point (point) t))
11009 (setq pos (js2-node-abs-pos node))
11010 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11011 (setq lp (car parens)
11012 rp (cdr parens)))
11013 (when (and lp (> start lp))
11014 (if (and rp (<= start rp))
11015 ;; Between parens, check if there's a child node we can jump.
11016 (when (setq child (js2-node-closest-child node (point) lp t))
11017 (setq pos (js2-node-abs-pos child)))
11018 ;; Before both parens.
11019 (setq pos lp)))
11020 (let ((state (parse-partial-sexp start pos)))
11021 (goto-char (if (not (zerop (car state)))
11022 ;; Stumble at the unbalanced paren if < 0, or
11023 ;; jump a bit further if > 0.
11024 (scan-sexps start -1)
11025 pos))))
11026 (unless pos (goto-char (point-min)))))
11027 (t
11028 ;; forward-sexp
11029 (dotimes (i arg)
11030 (js2-forward-sws)
11031 (when (setq node (js2-node-at-point (point) t))
11032 (setq pos (js2-node-abs-pos node))
11033 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11034 (setq lp (car parens)
11035 rp (cdr parens)))
11036 (or
11037 (when (and rp (<= start rp))
11038 (if (> start lp)
11039 (when (setq child (js2-node-closest-child node (point) rp))
11040 (setq pos (js2-node-abs-end child)))
11041 (setq pos (1+ rp))))
11042 ;; No parens or child nodes, looks for the end of the curren node.
11043 (incf pos (js2-node-len
11044 (if (js2-expr-stmt-node-p (js2-node-parent node))
11045 ;; Stop after the semicolon.
11046 (js2-node-parent node)
11047 node))))
11048 (let ((state (save-excursion (parse-partial-sexp start pos))))
11049 (goto-char (if (not (zerop (car state)))
11050 (scan-sexps start 1)
11051 pos))))
11052 (unless pos (goto-char (point-max))))))))
11053
11054 (defun js2-mode-forward-sexp-parens (node abs-pos)
11055 "Return a cons cell with positions of main parens in NODE."
11056 (cond
11057 ((or (js2-array-node-p node)
11058 (js2-object-node-p node)
11059 (js2-array-comp-node-p node)
11060 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11061 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11062 ((js2-paren-expr-node-p node)
11063 (let ((lp (js2-node-lp node))
11064 (rp (js2-node-rp node)))
11065 (cons (when lp (+ abs-pos lp))
11066 (when rp (+ abs-pos rp)))))))
11067
11068 (defun js2-node-closest-child (parent point limit &optional before)
11069 (let* ((parent-pos (js2-node-abs-pos parent))
11070 (rpoint (- point parent-pos))
11071 (rlimit (- limit parent-pos))
11072 (min (min rpoint rlimit))
11073 (max (max rpoint rlimit))
11074 found)
11075 (catch 'done
11076 (js2-visit-ast
11077 parent
11078 (lambda (node end-p)
11079 (if (eq node parent)
11080 t
11081 (let ((pos (js2-node-pos node)) ;; Both relative values.
11082 (end (+ (js2-node-pos node) (js2-node-len node))))
11083 (when (and (>= pos min) (<= end max)
11084 (if before (< pos rpoint) (> end rpoint)))
11085 (setq found node))
11086 (when (> end rpoint)
11087 (throw 'done nil)))
11088 nil))))
11089 found))
11090
11091 (defun js2-errors ()
11092 "Return a list of errors found."
11093 (and js2-mode-ast
11094 (js2-ast-root-errors js2-mode-ast)))
11095
11096 (defun js2-warnings ()
11097 "Return a list of warnings found."
11098 (and js2-mode-ast
11099 (js2-ast-root-warnings js2-mode-ast)))
11100
11101 (defun js2-have-errors-p ()
11102 "Return non-nil if any parse errors or warnings were found."
11103 (or (js2-errors) (js2-warnings)))
11104
11105 (defun js2-errors-and-warnings ()
11106 "Return a copy of the concatenated errors and warnings lists.
11107 They are appended: first the errors, then the warnings.
11108 Entries are of the form (MSG BEG END)."
11109 (when js2-mode-ast
11110 (append (js2-ast-root-errors js2-mode-ast)
11111 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11112
11113 (defun js2-next-error (&optional arg reset)
11114 "Move to next parse error.
11115 Typically invoked via \\[next-error].
11116 ARG is the number of errors, forward or backward, to move.
11117 RESET means start over from the beginning."
11118 (interactive "p")
11119 (if (not (or (js2-errors) (js2-warnings)))
11120 (message "No errors")
11121 (when reset
11122 (goto-char (point-min)))
11123 (let* ((errs (js2-errors-and-warnings))
11124 (continue t)
11125 (start (point))
11126 (count (or arg 1))
11127 (backward (minusp count))
11128 (sorter (if backward '> '<))
11129 (stopper (if backward '< '>))
11130 (count (abs count))
11131 all-errs err)
11132 ;; Sort by start position.
11133 (setq errs (sort errs (lambda (e1 e2)
11134 (funcall sorter (second e1) (second e2))))
11135 all-errs errs)
11136 ;; Find nth error with pos > start.
11137 (while (and errs continue)
11138 (when (funcall stopper (cadar errs) start)
11139 (setq err (car errs))
11140 (if (zerop (decf count))
11141 (setq continue nil)))
11142 (setq errs (cdr errs)))
11143 ;; Clear for `js2-echo-error'.
11144 (message nil)
11145 (if err
11146 (goto-char (second err))
11147 ;; Wrap around to first error.
11148 (goto-char (second (car all-errs)))
11149 ;; If we were already on it, echo msg again.
11150 (if (= (point) start)
11151 (js2-echo-error (point) (point)))))))
11152
11153 (defun js2-down-mouse-3 ()
11154 "Make right-click move the point to the click location.
11155 This makes right-click context menu operations a bit more intuitive.
11156 The point will not move if the region is active, however, to avoid
11157 destroying the region selection."
11158 (interactive)
11159 (when (and js2-move-point-on-right-click
11160 (not mark-active))
11161 (let ((e last-input-event))
11162 (ignore-errors
11163 (goto-char (cadadr e))))))
11164
11165 (defun js2-mode-create-imenu-index ()
11166 "Return an alist for `imenu--index-alist'."
11167 ;; This is built up in `js2-parse-record-imenu' during parsing.
11168 (when js2-mode-ast
11169 ;; if we have an ast but no recorder, they're requesting a rescan
11170 (unless js2-imenu-recorder
11171 (js2-reparse 'force))
11172 (prog1
11173 (js2-build-imenu-index)
11174 (setq js2-imenu-recorder nil
11175 js2-imenu-function-map nil))))
11176
11177 (defun js2-mode-find-tag ()
11178 "Replacement for `find-tag-default'.
11179 `find-tag-default' returns a ridiculous answer inside comments."
11180 (let (beg end)
11181 (js2-with-underscore-as-word-syntax
11182 (save-excursion
11183 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11184 (looking-back "[A-Za-z0-9_$]"))
11185 (setq beg (progn (forward-word -1) (point))
11186 end (progn (forward-word 1) (point)))
11187 (setq beg (progn (forward-word 1) (point))
11188 end (progn (forward-word -1) (point))))
11189 (replace-regexp-in-string
11190 "[\"']" ""
11191 (buffer-substring-no-properties beg end))))))
11192
11193 (defun js2-mode-forward-sibling ()
11194 "Move to the end of the sibling following point in parent.
11195 Returns non-nil if successful, or nil if there was no following sibling."
11196 (let* ((node (js2-node-at-point))
11197 (parent (js2-mode-find-enclosing-fn node))
11198 sib)
11199 (when (setq sib (js2-node-find-child-after (point) parent))
11200 (goto-char (+ (js2-node-abs-pos sib)
11201 (js2-node-len sib))))))
11202
11203 (defun js2-mode-backward-sibling ()
11204 "Move to the beginning of the sibling node preceding point in parent.
11205 Parent is defined as the enclosing script or function."
11206 (let* ((node (js2-node-at-point))
11207 (parent (js2-mode-find-enclosing-fn node))
11208 sib)
11209 (when (setq sib (js2-node-find-child-before (point) parent))
11210 (goto-char (js2-node-abs-pos sib)))))
11211
11212 (defun js2-beginning-of-defun (&optional arg)
11213 "Go to line on which current function starts, and return t on success.
11214 If we're not in a function or already at the beginning of one, go
11215 to beginning of previous script-level element.
11216 With ARG N, do that N times. If N is negative, move forward."
11217 (setq arg (or arg 1))
11218 (if (plusp arg)
11219 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11220 (when (cond
11221 ((js2-function-node-p parent)
11222 (goto-char (js2-node-abs-pos parent)))
11223 (t
11224 (js2-mode-backward-sibling)))
11225 (if (> arg 1)
11226 (js2-beginning-of-defun (1- arg))
11227 t)))
11228 (when (js2-end-of-defun)
11229 (if (>= arg -1)
11230 (js2-beginning-of-defun 1)
11231 (js2-beginning-of-defun (1+ arg))))))
11232
11233 (defun js2-end-of-defun ()
11234 "Go to the char after the last position of the current function
11235 or script-level element."
11236 (let* ((node (js2-node-at-point))
11237 (parent (or (and (js2-function-node-p node) node)
11238 (js2-node-parent-script-or-fn node)))
11239 script)
11240 (unless (js2-function-node-p parent)
11241 ;; Use current script-level node, or, if none, the next one.
11242 (setq script (or parent node)
11243 parent (js2-node-find-child-before (point) script))
11244 (when (or (null parent)
11245 (>= (point) (+ (js2-node-abs-pos parent)
11246 (js2-node-len parent))))
11247 (setq parent (js2-node-find-child-after (point) script))))
11248 (when parent
11249 (goto-char (+ (js2-node-abs-pos parent)
11250 (js2-node-len parent))))))
11251
11252 (defun js2-mark-defun (&optional allow-extend)
11253 "Put mark at end of this function, point at beginning.
11254 The function marked is the one that contains point.
11255
11256 Interactively, if this command is repeated,
11257 or (in Transient Mark mode) if the mark is active,
11258 it marks the next defun after the ones already marked."
11259 (interactive "p")
11260 (let (extended)
11261 (when (and allow-extend
11262 (or (and (eq last-command this-command) (mark t))
11263 (and transient-mark-mode mark-active)))
11264 (let ((sib (save-excursion
11265 (goto-char (mark))
11266 (if (js2-mode-forward-sibling)
11267 (point))))
11268 node)
11269 (if sib
11270 (progn
11271 (set-mark sib)
11272 (setq extended t))
11273 ;; no more siblings - try extending to enclosing node
11274 (goto-char (mark t)))))
11275 (when (not extended)
11276 (let ((node (js2-node-at-point (point) t)) ; skip comments
11277 ast fn stmt parent beg end)
11278 (when (js2-ast-root-p node)
11279 (setq ast node
11280 node (or (js2-node-find-child-after (point) node)
11281 (js2-node-find-child-before (point) node))))
11282 ;; only mark whole buffer if we can't find any children
11283 (if (null node)
11284 (setq node ast))
11285 (if (js2-function-node-p node)
11286 (setq parent node)
11287 (setq fn (js2-mode-find-enclosing-fn node)
11288 stmt (if (or (null fn)
11289 (js2-ast-root-p fn))
11290 (js2-mode-find-first-stmt node))
11291 parent (or stmt fn)))
11292 (setq beg (js2-node-abs-pos parent)
11293 end (+ beg (js2-node-len parent)))
11294 (push-mark beg)
11295 (goto-char end)
11296 (exchange-point-and-mark)))))
11297
11298 (defun js2-narrow-to-defun ()
11299 "Narrow to the function enclosing point."
11300 (interactive)
11301 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11302 (fn (if (js2-script-node-p node)
11303 node
11304 (js2-mode-find-enclosing-fn node)))
11305 (beg (js2-node-abs-pos fn)))
11306 (unless (js2-ast-root-p fn)
11307 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11308
11309 (provide 'js2-mode)
11310
11311 ;;; js2-mode.el ends here