]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Add console Object to browser externs.
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2013 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
10 ;; Version: 20130307
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternately, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; To customize how it works:
60 ;; M-x customize-group RET js2-mode RET
61
62 ;; Notes:
63
64 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
65 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
66 ;; `js2-mode' current as the EcmaScript language standard evolves.
67
68 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
69 ;; customizable. It is a surprising amount of work to support customizable
70 ;; indentation. The current compromise is that the tab key lets you cycle among
71 ;; various likely indentation points, similar to the behavior of python-mode.
72
73 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
74 ;; and `mumamo', although it could be made to do so with some effort.
75 ;; This means that `js2-mode' is currently only useful for editing JavaScript
76 ;; files, and not for editing JavaScript within <script> tags or templates.
77
78 ;; The project page on GitHub is used for development and issue tracking.
79 ;; The original homepage at Google Code is mentioned here for posterity, it has
80 ;; outdated information and is mostly unmaintained.
81
82 ;;; Code:
83
84 (eval-when-compile
85 (require 'cl))
86
87 (require 'imenu)
88 (require 'cc-cmds) ; for `c-fill-paragraph'
89
90 (eval-and-compile
91 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
92 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
93
94 (defvar electric-layout-rules)
95
96 ;;; Externs (variables presumed to be defined by the host system)
97
98 (defvar js2-ecma-262-externs
99 (mapcar 'symbol-name
100 '(Array Boolean Date Error EvalError Function Infinity JSON
101 Math NaN Number Object RangeError ReferenceError RegExp
102 String SyntaxError TypeError URIError arguments
103 decodeURI decodeURIComponent encodeURI
104 encodeURIComponent escape eval isFinite isNaN
105 parseFloat parseInt undefined unescape))
106 "Ecma-262 externs. Included in `js2-externs' by default.")
107
108 (defvar js2-browser-externs
109 (mapcar 'symbol-name
110 '(;; DOM level 1
111 Attr CDATASection CharacterData Comment DOMException
112 DOMImplementation Document DocumentFragment
113 DocumentType Element Entity EntityReference
114 ExceptionCode NamedNodeMap Node NodeList Notation
115 ProcessingInstruction Text
116
117 ;; DOM level 2
118 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
119 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
120 HTMLBodyElement HTMLButtonElement HTMLCollection
121 HTMLDListElement HTMLDirectoryElement HTMLDivElement
122 HTMLDocument HTMLElement HTMLFieldSetElement
123 HTMLFontElement HTMLFormElement HTMLFrameElement
124 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
125 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
126 HTMLImageElement HTMLInputElement HTMLIsIndexElement
127 HTMLLIElement HTMLLabelElement HTMLLegendElement
128 HTMLLinkElement HTMLMapElement HTMLMenuElement
129 HTMLMetaElement HTMLModElement HTMLOListElement
130 HTMLObjectElement HTMLOptGroupElement
131 HTMLOptionElement HTMLOptionsCollection
132 HTMLParagraphElement HTMLParamElement HTMLPreElement
133 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
134 HTMLStyleElement HTMLTableCaptionElement
135 HTMLTableCellElement HTMLTableColElement
136 HTMLTableElement HTMLTableRowElement
137 HTMLTableSectionElement HTMLTextAreaElement
138 HTMLTitleElement HTMLUListElement
139
140 ;; DOM level 3
141 DOMConfiguration DOMError DOMException
142 DOMImplementationList DOMImplementationSource
143 DOMLocator DOMStringList NameList TypeInfo
144 UserDataHandler
145
146 ;; Window
147 window alert confirm document java navigator prompt screen
148 self top
149
150 ;; W3C CSS
151 CSSCharsetRule CSSFontFace CSSFontFaceRule
152 CSSImportRule CSSMediaRule CSSPageRule
153 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
154 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
155 CSSValue CSSValueList Counter DOMImplementationCSS
156 DocumentCSS DocumentStyle ElementCSSInlineStyle
157 LinkStyle MediaList RGBColor Rect StyleSheet
158 StyleSheetList ViewCSS
159
160 ;; W3C Event
161 EventListener EventTarget Event DocumentEvent UIEvent
162 MouseEvent MutationEvent KeyboardEvent
163
164 ;; W3C Range
165 DocumentRange Range RangeException
166
167 ;; W3C XML
168 XPathResult XMLHttpRequest
169
170 ;; Khronos Typed Array Specification
171 ArrayBuffer ArrayBufferView TypedArray Uint8ClampedArray DataView
172 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
173 Float32Array Float64Array
174
175 ;; console object. Provided by at least Chrome and Firefox.
176 console))
177 "Browser externs.
178 You can cause these to be included or excluded with the custom
179 variable `js2-include-browser-externs'.")
180
181 (defvar js2-rhino-externs
182 (mapcar 'symbol-name
183 '(Packages importClass importPackage com org java
184 ;; Global object (shell) externs.
185 defineClass deserialize doctest gc help load
186 loadClass print quit readFile readUrl runCommand seal
187 serialize spawn sync toint32 version))
188 "Mozilla Rhino externs.
189 Set `js2-include-rhino-externs' to t to include them.")
190
191 (defvar js2-node-externs
192 (mapcar 'symbol-name
193 '(__dirname __filename Buffer clearInterval clearTimeout require
194 console exports global module process setInterval setTimeout))
195 "Node.js externs.
196 Set `js2-include-node-externs' to t to include them.")
197
198 ;;; Variables
199
200 (defun js2-mark-safe-local (name pred)
201 "Make the variable NAME buffer-local and mark it as safe file-local
202 variable with predicate PRED."
203 (make-variable-buffer-local name)
204 (put name 'safe-local-variable pred))
205
206 (defcustom js2-highlight-level 2
207 "Amount of syntax highlighting to perform.
208 0 or a negative value means none.
209 1 adds basic syntax highlighting.
210 2 adds highlighting of some Ecma built-in properties.
211 3 adds highlighting of many Ecma built-in functions."
212 :group 'js2-mode
213 :type '(choice (const :tag "None" 0)
214 (const :tag "Basic" 1)
215 (const :tag "Include Properties" 2)
216 (const :tag "Include Functions" 3)))
217
218 (defvar js2-mode-dev-mode-p nil
219 "Non-nil if running in development mode. Normally nil.")
220
221 (defgroup js2-mode nil
222 "An improved JavaScript mode."
223 :group 'languages)
224
225 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
226 (numberp c-basic-offset))
227 c-basic-offset
228 4)
229 "Number of spaces to indent nested statements.
230 Similar to `c-basic-offset'."
231 :group 'js2-mode
232 :type 'integer)
233 (js2-mark-safe-local 'js2-basic-offset 'integerp)
234
235 (defcustom js2-bounce-indent-p nil
236 "Non-nil to have indent-line function choose among alternatives.
237 If nil, the indent-line function will indent to a predetermined column
238 based on heuristic guessing. If non-nil, then if the current line is
239 already indented to that predetermined column, indenting will choose
240 another likely column and indent to that spot. Repeated invocation of
241 the indent-line function will cycle among the computed alternatives.
242 See the function `js2-bounce-indent' for details. When it is non-nil,
243 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
244 :type 'boolean
245 :group 'js2-mode)
246
247 (defcustom js2-pretty-multiline-declarations t
248 "Non-nil to line up multiline declarations vertically:
249
250 var a = 10,
251 b = 20,
252 c = 30;
253
254 If the value is not `all', and the first assigned value in
255 declaration is a function/array/object literal spanning several
256 lines, it won't be indented additionally:
257
258 var o = { var bar = 2,
259 foo: 3 vs. o = {
260 }, foo: 3
261 bar = 2; };"
262 :group 'js2-mode
263 :type 'symbol)
264 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
265
266 (defcustom js2-idle-timer-delay 0.2
267 "Delay in secs before re-parsing after user makes changes.
268 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
269 :type 'number
270 :group 'js2-mode)
271 (make-variable-buffer-local 'js2-idle-timer-delay)
272
273 (defcustom js2-dynamic-idle-timer-adjust 0
274 "Positive to adjust `js2-idle-timer-delay' based on file size.
275 The idea is that for short files, parsing is faster so we can be
276 more responsive to user edits without interfering with editing.
277 The buffer length in characters (typically bytes) is divided by
278 this value and used to multiply `js2-idle-timer-delay' for the
279 buffer. For example, a 21k file and 10k adjust yields 21k/10k
280 == 2, so js2-idle-timer-delay is multiplied by 2.
281 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
282 `js2-idle-timer-delay' is not dependent on the file size."
283 :type 'number
284 :group 'js2-mode)
285
286 (defcustom js2-concat-multiline-strings t
287 "Non-nil to automatically turn a newline in mid-string into a
288 string concatenation. When `eol', the '+' will be inserted at the
289 end of the line, otherwise, at the beginning of the next line."
290 :type '(choice (const t) (const eol) (const nil))
291 :group 'js2-mode)
292
293 (defcustom js2-mode-show-parse-errors t
294 "True to highlight parse errors."
295 :type 'boolean
296 :group 'js2-mode)
297
298 (defcustom js2-mode-show-strict-warnings t
299 "Non-nil to emit Ecma strict-mode warnings.
300 Some of the warnings can be individually disabled by other flags,
301 even if this flag is non-nil."
302 :type 'boolean
303 :group 'js2-mode)
304
305 (defcustom js2-strict-trailing-comma-warning t
306 "Non-nil to warn about trailing commas in array literals.
307 Ecma-262-5.1 allows them, but older versions of IE raise an error."
308 :type 'boolean
309 :group 'js2-mode)
310
311 (defcustom js2-strict-missing-semi-warning t
312 "Non-nil to warn about semicolon auto-insertion after statement.
313 Technically this is legal per Ecma-262, but some style guides disallow
314 depending on it."
315 :type 'boolean
316 :group 'js2-mode)
317
318 (defcustom js2-missing-semi-one-line-override nil
319 "Non-nil to permit missing semicolons in one-line functions.
320 In one-liner functions such as `function identity(x) {return x}'
321 people often omit the semicolon for a cleaner look. If you are
322 such a person, you can suppress the missing-semicolon warning
323 by setting this variable to t."
324 :type 'boolean
325 :group 'js2-mode)
326
327 (defcustom js2-strict-inconsistent-return-warning t
328 "Non-nil to warn about mixing returns with value-returns.
329 It's perfectly legal to have a `return' and a `return foo' in the
330 same function, but it's often an indicator of a bug, and it also
331 interferes with type inference (in systems that support it.)"
332 :type 'boolean
333 :group 'js2-mode)
334
335 (defcustom js2-strict-cond-assign-warning t
336 "Non-nil to warn about expressions like if (a = b).
337 This often should have been '==' instead of '='. If the warning
338 is enabled, you can suppress it on a per-expression basis by
339 parenthesizing the expression, e.g. if ((a = b)) ..."
340 :type 'boolean
341 :group 'js2-mode)
342
343 (defcustom js2-strict-var-redeclaration-warning t
344 "Non-nil to warn about redeclaring variables in a script or function."
345 :type 'boolean
346 :group 'js2-mode)
347
348 (defcustom js2-strict-var-hides-function-arg-warning t
349 "Non-nil to warn about a var decl hiding a function argument."
350 :type 'boolean
351 :group 'js2-mode)
352
353 (defcustom js2-skip-preprocessor-directives nil
354 "Non-nil to treat lines beginning with # as comments.
355 Useful for viewing Mozilla JavaScript source code."
356 :type 'boolean
357 :group 'js2-mode)
358
359 (defcustom js2-language-version 200
360 "Configures what JavaScript language version to recognize.
361 Currently versions 150, 160, 170, 180 and 200 are supported,
362 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
363 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
364 yield, and Array comprehensions, and 1.8 adds function closures."
365 :type 'integer
366 :group 'js2-mode)
367
368 (defcustom js2-allow-keywords-as-property-names t
369 "If non-nil, you can use JavaScript keywords as object property names.
370 Examples:
371
372 var foo = {int: 5, while: 6, continue: 7};
373 foo.return = 8;
374
375 Ecma-262 5.1 allows this syntax, but some engines still don't."
376 :type 'boolean
377 :group 'js2-mode)
378
379 (defcustom js2-instanceof-has-side-effects nil
380 "If non-nil, treats the instanceof operator as having side effects.
381 This is useful for xulrunner apps."
382 :type 'boolean
383 :group 'js2-mode)
384
385 (defcustom js2-move-point-on-right-click t
386 "Non-nil to move insertion point when you right-click.
387 This makes right-click context menu behavior a bit more intuitive,
388 since menu operations generally apply to the point. The exception
389 is if there is a region selection, in which case the point does -not-
390 move, so cut/copy/paste can work properly.
391
392 Note that IntelliJ moves the point, and Eclipse leaves it alone,
393 so this behavior is customizable."
394 :group 'js2-mode
395 :type 'boolean)
396
397 (defcustom js2-allow-rhino-new-expr-initializer t
398 "Non-nil to support a Rhino's experimental syntactic construct.
399
400 Rhino supports the ability to follow a `new' expression with an object
401 literal, which is used to set additional properties on the new object
402 after calling its constructor. Syntax:
403
404 new <expr> [ ( arglist ) ] [initializer]
405
406 Hence, this expression:
407
408 new Object {a: 1, b: 2}
409
410 results in an Object with properties a=1 and b=2. This syntax is
411 apparently not configurable in Rhino - it's currently always enabled,
412 as of Rhino version 1.7R2."
413 :type 'boolean
414 :group 'js2-mode)
415
416 (defcustom js2-allow-member-expr-as-function-name nil
417 "Non-nil to support experimental Rhino syntax for function names.
418
419 Rhino supports an experimental syntax configured via the Rhino Context
420 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
421
422 function <member-expr> ( [ arg-list ] ) { <body> }
423
424 Where member-expr is a non-parenthesized 'member expression', which
425 is anything at the grammar level of a new-expression or lower, meaning
426 any expression that does not involve infix or unary operators.
427
428 When <member-expr> is not a simple identifier, then it is syntactic
429 sugar for assigning the anonymous function to the <member-expr>. Hence,
430 this code:
431
432 function a.b().c[2] (x, y) { ... }
433
434 is rewritten as:
435
436 a.b().c[2] = function(x, y) {...}
437
438 which doesn't seem particularly useful, but Rhino permits it."
439 :type 'boolean
440 :group 'js2-mode)
441
442 ;; scanner variables
443
444 (defmacro js2-deflocal (name value &optional comment)
445 "Define a buffer-local variable NAME with VALUE and COMMENT."
446 `(progn
447 (defvar ,name ,value ,comment)
448 (make-variable-buffer-local ',name)))
449
450 ;; We record the start and end position of each token.
451 (js2-deflocal js2-token-beg 1)
452 (js2-deflocal js2-token-end -1)
453
454 (defvar js2-EOF_CHAR -1
455 "Represents end of stream. Distinct from js2-EOF token type.")
456
457 ;; I originally used symbols to represent tokens, but Rhino uses
458 ;; ints and then sets various flag bits in them, so ints it is.
459 ;; The upshot is that we need a `js2-' prefix in front of each name.
460 (defvar js2-ERROR -1)
461 (defvar js2-EOF 0)
462 (defvar js2-EOL 1)
463 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
464 (defvar js2-LEAVEWITH 3)
465 (defvar js2-RETURN 4)
466 (defvar js2-GOTO 5)
467 (defvar js2-IFEQ 6)
468 (defvar js2-IFNE 7)
469 (defvar js2-SETNAME 8)
470 (defvar js2-BITOR 9)
471 (defvar js2-BITXOR 10)
472 (defvar js2-BITAND 11)
473 (defvar js2-EQ 12)
474 (defvar js2-NE 13)
475 (defvar js2-LT 14)
476 (defvar js2-LE 15)
477 (defvar js2-GT 16)
478 (defvar js2-GE 17)
479 (defvar js2-LSH 18)
480 (defvar js2-RSH 19)
481 (defvar js2-URSH 20)
482 (defvar js2-ADD 21) ; infix plus
483 (defvar js2-SUB 22) ; infix minus
484 (defvar js2-MUL 23)
485 (defvar js2-DIV 24)
486 (defvar js2-MOD 25)
487 (defvar js2-NOT 26)
488 (defvar js2-BITNOT 27)
489 (defvar js2-POS 28) ; unary plus
490 (defvar js2-NEG 29) ; unary minus
491 (defvar js2-NEW 30)
492 (defvar js2-DELPROP 31)
493 (defvar js2-TYPEOF 32)
494 (defvar js2-GETPROP 33)
495 (defvar js2-GETPROPNOWARN 34)
496 (defvar js2-SETPROP 35)
497 (defvar js2-GETELEM 36)
498 (defvar js2-SETELEM 37)
499 (defvar js2-CALL 38)
500 (defvar js2-NAME 39) ; an identifier
501 (defvar js2-NUMBER 40)
502 (defvar js2-STRING 41)
503 (defvar js2-NULL 42)
504 (defvar js2-THIS 43)
505 (defvar js2-FALSE 44)
506 (defvar js2-TRUE 45)
507 (defvar js2-SHEQ 46) ; shallow equality (===)
508 (defvar js2-SHNE 47) ; shallow inequality (!==)
509 (defvar js2-REGEXP 48)
510 (defvar js2-BINDNAME 49)
511 (defvar js2-THROW 50)
512 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
513 (defvar js2-IN 52)
514 (defvar js2-INSTANCEOF 53)
515 (defvar js2-LOCAL_LOAD 54)
516 (defvar js2-GETVAR 55)
517 (defvar js2-SETVAR 56)
518 (defvar js2-CATCH_SCOPE 57)
519 (defvar js2-ENUM_INIT_KEYS 58)
520 (defvar js2-ENUM_INIT_VALUES 59)
521 (defvar js2-ENUM_INIT_ARRAY 60)
522 (defvar js2-ENUM_NEXT 61)
523 (defvar js2-ENUM_ID 62)
524 (defvar js2-THISFN 63)
525 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
526 (defvar js2-ARRAYLIT 65) ; array literal
527 (defvar js2-OBJECTLIT 66) ; object literal
528 (defvar js2-GET_REF 67) ; *reference
529 (defvar js2-SET_REF 68) ; *reference = something
530 (defvar js2-DEL_REF 69) ; delete reference
531 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
532 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
533 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
534
535 ;; XML support
536 (defvar js2-DEFAULTNAMESPACE 73)
537 (defvar js2-ESCXMLATTR 74)
538 (defvar js2-ESCXMLTEXT 75)
539 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
540 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
541 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
542 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
543
544 (defvar js2-first-bytecode js2-ENTERWITH)
545 (defvar js2-last-bytecode js2-REF_NS_NAME)
546
547 (defvar js2-TRY 80)
548 (defvar js2-SEMI 81) ; semicolon
549 (defvar js2-LB 82) ; left and right brackets
550 (defvar js2-RB 83)
551 (defvar js2-LC 84) ; left and right curly-braces
552 (defvar js2-RC 85)
553 (defvar js2-LP 86) ; left and right parens
554 (defvar js2-RP 87)
555 (defvar js2-COMMA 88) ; comma operator
556
557 (defvar js2-ASSIGN 89) ; simple assignment (=)
558 (defvar js2-ASSIGN_BITOR 90) ; |=
559 (defvar js2-ASSIGN_BITXOR 91) ; ^=
560 (defvar js2-ASSIGN_BITAND 92) ; &=
561 (defvar js2-ASSIGN_LSH 93) ; <<=
562 (defvar js2-ASSIGN_RSH 94) ; >>=
563 (defvar js2-ASSIGN_URSH 95) ; >>>=
564 (defvar js2-ASSIGN_ADD 96) ; +=
565 (defvar js2-ASSIGN_SUB 97) ; -=
566 (defvar js2-ASSIGN_MUL 98) ; *=
567 (defvar js2-ASSIGN_DIV 99) ; /=
568 (defvar js2-ASSIGN_MOD 100) ; %=
569
570 (defvar js2-first-assign js2-ASSIGN)
571 (defvar js2-last-assign js2-ASSIGN_MOD)
572
573 (defvar js2-HOOK 101) ; conditional (?:)
574 (defvar js2-COLON 102)
575 (defvar js2-OR 103) ; logical or (||)
576 (defvar js2-AND 104) ; logical and (&&)
577 (defvar js2-INC 105) ; increment/decrement (++ --)
578 (defvar js2-DEC 106)
579 (defvar js2-DOT 107) ; member operator (.)
580 (defvar js2-FUNCTION 108) ; function keyword
581 (defvar js2-EXPORT 109) ; export keyword
582 (defvar js2-IMPORT 110) ; import keyword
583 (defvar js2-IF 111) ; if keyword
584 (defvar js2-ELSE 112) ; else keyword
585 (defvar js2-SWITCH 113) ; switch keyword
586 (defvar js2-CASE 114) ; case keyword
587 (defvar js2-DEFAULT 115) ; default keyword
588 (defvar js2-WHILE 116) ; while keyword
589 (defvar js2-DO 117) ; do keyword
590 (defvar js2-FOR 118) ; for keyword
591 (defvar js2-BREAK 119) ; break keyword
592 (defvar js2-CONTINUE 120) ; continue keyword
593 (defvar js2-VAR 121) ; var keyword
594 (defvar js2-WITH 122) ; with keyword
595 (defvar js2-CATCH 123) ; catch keyword
596 (defvar js2-FINALLY 124) ; finally keyword
597 (defvar js2-VOID 125) ; void keyword
598 (defvar js2-RESERVED 126) ; reserved keywords
599
600 (defvar js2-EMPTY 127)
601
602 ;; Types used for the parse tree - never returned by scanner.
603
604 (defvar js2-BLOCK 128) ; statement block
605 (defvar js2-LABEL 129) ; label
606 (defvar js2-TARGET 130)
607 (defvar js2-LOOP 131)
608 (defvar js2-EXPR_VOID 132) ; expression statement in functions
609 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
610 (defvar js2-JSR 134)
611 (defvar js2-SCRIPT 135) ; top-level node for entire script
612 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
613 (defvar js2-USE_STACK 137)
614 (defvar js2-SETPROP_OP 138) ; x.y op= something
615 (defvar js2-SETELEM_OP 139) ; x[y] op= something
616 (defvar js2-LOCAL_BLOCK 140)
617 (defvar js2-SET_REF_OP 141) ; *reference op= something
618
619 ;; For XML support:
620 (defvar js2-DOTDOT 142) ; member operator (..)
621 (defvar js2-COLONCOLON 143) ; namespace::name
622 (defvar js2-XML 144) ; XML type
623 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
624 (defvar js2-XMLATTR 146) ; @
625 (defvar js2-XMLEND 147)
626
627 ;; Optimizer-only tokens
628 (defvar js2-TO_OBJECT 148)
629 (defvar js2-TO_DOUBLE 149)
630
631 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
632 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
633 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
634 (defvar js2-CONST 153)
635 (defvar js2-SETCONST 154)
636 (defvar js2-SETCONSTVAR 155)
637 (defvar js2-ARRAYCOMP 156)
638 (defvar js2-LETEXPR 157)
639 (defvar js2-WITHEXPR 158)
640 (defvar js2-DEBUGGER 159)
641
642 (defvar js2-COMMENT 160)
643 (defvar js2-ENUM 161) ; for "enum" reserved word
644 (defvar js2-TRIPLEDOT 162) ; for rest parameter
645
646 (defconst js2-num-tokens (1+ js2-TRIPLEDOT))
647
648 (defconst js2-debug-print-trees nil)
649
650 ;; Rhino accepts any string or stream as input. Emacs character
651 ;; processing works best in buffers, so we'll assume the input is a
652 ;; buffer. JavaScript strings can be copied into temp buffers before
653 ;; scanning them.
654
655 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
656 ;; They're the Emacs equivalent of instance variables, more or less.
657
658 (js2-deflocal js2-ts-dirty-line nil
659 "Token stream buffer-local variable.
660 Indicates stuff other than whitespace since start of line.")
661
662 (js2-deflocal js2-ts-regexp-flags nil
663 "Token stream buffer-local variable.")
664
665 (js2-deflocal js2-ts-string ""
666 "Token stream buffer-local variable.
667 Last string scanned.")
668
669 (js2-deflocal js2-ts-number nil
670 "Token stream buffer-local variable.
671 Last literal number scanned.")
672
673 (js2-deflocal js2-ts-hit-eof nil
674 "Token stream buffer-local variable.")
675
676 (js2-deflocal js2-ts-line-start 0
677 "Token stream buffer-local variable.")
678
679 (js2-deflocal js2-ts-lineno 1
680 "Token stream buffer-local variable.")
681
682 (js2-deflocal js2-ts-line-end-char -1
683 "Token stream buffer-local variable.")
684
685 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
686 "Token stream buffer-local variable.
687 Current scan position.")
688
689 (js2-deflocal js2-ts-is-xml-attribute nil
690 "Token stream buffer-local variable.")
691
692 (js2-deflocal js2-ts-xml-is-tag-content nil
693 "Token stream buffer-local variable.")
694
695 (js2-deflocal js2-ts-xml-open-tags-count 0
696 "Token stream buffer-local variable.")
697
698 (js2-deflocal js2-ts-string-buffer nil
699 "Token stream buffer-local variable.
700 List of chars built up while scanning various tokens.")
701
702 (js2-deflocal js2-ts-comment-type nil
703 "Token stream buffer-local variable.")
704
705 ;;; Parser variables
706
707 (js2-deflocal js2-parsed-errors nil
708 "List of errors produced during scanning/parsing.")
709
710 (js2-deflocal js2-parsed-warnings nil
711 "List of warnings produced during scanning/parsing.")
712
713 (js2-deflocal js2-recover-from-parse-errors t
714 "Non-nil to continue parsing after a syntax error.
715
716 In recovery mode, the AST will be built in full, and any error
717 nodes will be flagged with appropriate error information. If
718 this flag is nil, a syntax error will result in an error being
719 signaled.
720
721 The variable is automatically buffer-local, because different
722 modes that use the parser will need different settings.")
723
724 (js2-deflocal js2-parse-hook nil
725 "List of callbacks for receiving parsing progress.")
726
727 (defvar js2-parse-finished-hook nil
728 "List of callbacks to notify when parsing finishes.
729 Not called if parsing was interrupted.")
730
731 (js2-deflocal js2-is-eval-code nil
732 "True if we're evaluating code in a string.
733 If non-nil, the tokenizer will record the token text, and the AST nodes
734 will record their source text. Off by default for IDE modes, since the
735 text is available in the buffer.")
736
737 (defvar js2-parse-ide-mode t
738 "Non-nil if the parser is being used for `js2-mode'.
739 If non-nil, the parser will set text properties for fontification
740 and the syntax table. The value should be nil when using the
741 parser as a frontend to an interpreter or byte compiler.")
742
743 ;;; Parser instance variables (buffer-local vars for js2-parse)
744
745 (defconst js2-clear-ti-mask #xFFFF
746 "Mask to clear token information bits.")
747
748 (defconst js2-ti-after-eol (lsh 1 16)
749 "Flag: first token of the source line.")
750
751 (defconst js2-ti-check-label (lsh 1 17)
752 "Flag: indicates to check for label.")
753
754 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
755
756 (js2-deflocal js2-compiler-generate-debug-info t)
757 (js2-deflocal js2-compiler-use-dynamic-scope nil)
758 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
759 (js2-deflocal js2-compiler-xml-available t)
760 (js2-deflocal js2-compiler-optimization-level 0)
761 (js2-deflocal js2-compiler-generating-source t)
762 (js2-deflocal js2-compiler-strict-mode nil)
763 (js2-deflocal js2-compiler-report-warning-as-error nil)
764 (js2-deflocal js2-compiler-generate-observer-count nil)
765 (js2-deflocal js2-compiler-activation-names nil)
766
767 ;; SKIP: sourceURI
768
769 ;; There's a compileFunction method in Context.java - may need it.
770 (js2-deflocal js2-called-by-compile-function nil
771 "True if `js2-parse' was called by `js2-compile-function'.
772 Will only be used when we finish implementing the interpreter.")
773
774 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
775
776 (js2-deflocal js2-current-flagged-token js2-EOF)
777 (js2-deflocal js2-current-token js2-EOF)
778
779 ;; SKIP: node factory - we're going to just call functions directly,
780 ;; and eventually go to a unified AST format.
781
782 (js2-deflocal js2-nesting-of-function 0)
783
784 (js2-deflocal js2-recorded-identifiers nil
785 "Tracks identifiers found during parsing.")
786
787 (js2-deflocal js2-is-in-destructuring nil
788 "True while parsing destructuring expression.")
789
790 (defcustom js2-global-externs nil
791 "A list of any extern names you'd like to consider always declared.
792 This list is global and is used by all `js2-mode' files.
793 You can create buffer-local externs list using `js2-additional-externs'.
794
795 There is also a buffer-local variable `js2-default-externs',
796 which is initialized by default to include the Ecma-262 externs
797 and the standard browser externs. The three lists are all
798 checked during highlighting."
799 :type 'list
800 :group 'js2-mode)
801
802 (js2-deflocal js2-default-externs nil
803 "Default external declarations.
804
805 These are currently only used for highlighting undeclared variables,
806 which only worries about top-level (unqualified) references.
807 As js2-mode's processing improves, we will flesh out this list.
808
809 The initial value is set to `js2-ecma-262-externs', unless some
810 of the `js2-include-?-externs' variables are set to t, in which
811 case the browser, Rhino and/or Node.js externs are also included.
812
813 See `js2-additional-externs' for more information.")
814
815 (defcustom js2-include-browser-externs t
816 "Non-nil to include browser externs in the master externs list.
817 If you work on JavaScript files that are not intended for browsers,
818 such as Mozilla Rhino server-side JavaScript, set this to nil.
819 See `js2-additional-externs' for more information about externs."
820 :type 'boolean
821 :group 'js2-mode)
822
823 (defcustom js2-include-rhino-externs nil
824 "Non-nil to include Mozilla Rhino externs in the master externs list.
825 See `js2-additional-externs' for more information about externs."
826 :type 'boolean
827 :group 'js2-mode)
828
829 (defcustom js2-include-node-externs nil
830 "Non-nil to include Node.js externs in the master externs list.
831 See `js2-additional-externs' for more information about externs."
832 :type 'boolean
833 :group 'js2-mode)
834
835 (js2-deflocal js2-additional-externs nil
836 "A buffer-local list of additional external declarations.
837 It is used to decide whether variables are considered undeclared
838 for purposes of highlighting.
839
840 Each entry is a Lisp string. The string should be the fully qualified
841 name of an external entity. All externs should be added to this list,
842 so that as js2-mode's processing improves it can take advantage of them.
843
844 You may want to declare your externs in three ways.
845 First, you can add externs that are valid for all your JavaScript files.
846 You should probably do this by adding them to `js2-global-externs', which
847 is a global list used for all js2-mode files.
848
849 Next, you can add a function to `js2-mode-hook' that adds additional
850 externs appropriate for the specific file, perhaps based on its path.
851 These should go in `js2-additional-externs', which is buffer-local.
852
853 Finally, you can add a function to `js2-post-parse-callbacks',
854 which is called after parsing completes, and `js2-mode-ast' is bound to
855 the root of the parse tree. At this stage you can set up an AST
856 node visitor using `js2-visit-ast' and examine the parse tree
857 for specific import patterns that may imply the existence of
858 other externs, possibly tied to your build system. These should also
859 be added to `js2-additional-externs'.
860
861 Your post-parse callback may of course also use the simpler and
862 faster (but perhaps less robust) approach of simply scanning the
863 buffer text for your imports, using regular expressions.")
864
865 ;; SKIP: decompiler
866 ;; SKIP: encoded-source
867
868 ;;; The following variables are per-function and should be saved/restored
869 ;;; during function parsing...
870
871 (js2-deflocal js2-current-script-or-fn nil)
872 (js2-deflocal js2-current-scope nil)
873 (js2-deflocal js2-nesting-of-with 0)
874 (js2-deflocal js2-label-set nil
875 "An alist mapping label names to nodes.")
876
877 (js2-deflocal js2-loop-set nil)
878 (js2-deflocal js2-loop-and-switch-set nil)
879 (js2-deflocal js2-has-return-value nil)
880 (js2-deflocal js2-end-flags 0)
881
882 ;;; ...end of per function variables
883
884 ;; Without 2-token lookahead, labels are a problem.
885 ;; These vars store the token info of the last matched name,
886 ;; iff it wasn't the last matched token. Only valid in some contexts.
887 (defvar js2-prev-name-token-start nil)
888 (defvar js2-prev-name-token-string nil)
889
890 (defsubst js2-save-name-token-data (pos name)
891 (setq js2-prev-name-token-start pos
892 js2-prev-name-token-string name))
893
894 ;; These flags enumerate the possible ways a statement/function can
895 ;; terminate. These flags are used by endCheck() and by the Parser to
896 ;; detect inconsistent return usage.
897 ;;
898 ;; END_UNREACHED is reserved for code paths that are assumed to always be
899 ;; able to execute (example: throw, continue)
900 ;;
901 ;; END_DROPS_OFF indicates if the statement can transfer control to the
902 ;; next one. Statement such as return dont. A compound statement may have
903 ;; some branch that drops off control to the next statement.
904 ;;
905 ;; END_RETURNS indicates that the statement can return (without arguments)
906 ;; END_RETURNS_VALUE indicates that the statement can return a value.
907 ;;
908 ;; A compound statement such as
909 ;; if (condition) {
910 ;; return value;
911 ;; }
912 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
913
914 (defconst js2-end-unreached #x0)
915 (defconst js2-end-drops-off #x1)
916 (defconst js2-end-returns #x2)
917 (defconst js2-end-returns-value #x4)
918 (defconst js2-end-yields #x8)
919
920 ;; Rhino awkwardly passes a statementLabel parameter to the
921 ;; statementHelper() function, the main statement parser, which
922 ;; is then used by quite a few of the sub-parsers. We just make
923 ;; it a buffer-local variable and make sure it's cleaned up properly.
924 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
925
926 ;; Similarly, Rhino passes an inForInit boolean through about half
927 ;; the expression parsers. We use a dynamically-scoped variable,
928 ;; which makes it easier to funcall the parsers individually without
929 ;; worrying about whether they take the parameter or not.
930 (js2-deflocal js2-in-for-init nil)
931 (js2-deflocal js2-temp-name-counter 0)
932 (js2-deflocal js2-parse-stmt-count 0)
933
934 (defsubst js2-get-next-temp-name ()
935 (format "$%d" (incf js2-temp-name-counter)))
936
937 (defvar js2-parse-interruptable-p t
938 "Set this to nil to force parse to continue until finished.
939 This will mostly be useful for interpreters.")
940
941 (defvar js2-statements-per-pause 50
942 "Pause after this many statements to check for user input.
943 If user input is pending, stop the parse and discard the tree.
944 This makes for a smoother user experience for large files.
945 You may have to wait a second or two before the highlighting
946 and error-reporting appear, but you can always type ahead if
947 you wish. This appears to be more or less how Eclipse, IntelliJ
948 and other editors work.")
949
950 (js2-deflocal js2-record-comments t
951 "Instructs the scanner to record comments in `js2-scanned-comments'.")
952
953 (js2-deflocal js2-scanned-comments nil
954 "List of all comments from the current parse.")
955
956 (defcustom js2-mode-indent-inhibit-undo nil
957 "Non-nil to disable collection of Undo information when indenting lines.
958 Some users have requested this behavior. It's nil by default because
959 other Emacs modes don't work this way."
960 :type 'boolean
961 :group 'js2-mode)
962
963 (defcustom js2-mode-indent-ignore-first-tab nil
964 "If non-nil, ignore first TAB keypress if we look indented properly.
965 It's fairly common for users to navigate to an already-indented line
966 and press TAB for reassurance that it's been indented. For this class
967 of users, we want the first TAB press on a line to be ignored if the
968 line is already indented to one of the precomputed alternatives.
969
970 This behavior is only partly implemented. If you TAB-indent a line,
971 navigate to another line, and then navigate back, it fails to clear
972 the last-indented variable, so it thinks you've already hit TAB once,
973 and performs the indent. A full solution would involve getting on the
974 point-motion hooks for the entire buffer. If we come across another
975 use cases that requires watching point motion, I'll consider doing it.
976
977 If you set this variable to nil, then the TAB key will always change
978 the indentation of the current line, if more than one alternative
979 indentation spot exists."
980 :type 'boolean
981 :group 'js2-mode)
982
983 (defvar js2-indent-hook nil
984 "A hook for user-defined indentation rules.
985
986 Functions on this hook should expect two arguments: (LIST INDEX)
987 The LIST argument is the list of computed indentation points for
988 the current line. INDEX is the list index of the indentation point
989 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
990 indent function is not going to change the current line indentation.
991
992 If a hook function on this list returns a non-nil value, then
993 `js2-bounce-indent' assumes the hook function has performed its own
994 indentation, and will do nothing. If all hook functions on the list
995 return nil, then `js2-bounce-indent' will use its computed indentation
996 and reindent the line.
997
998 When hook functions on this hook list are called, the variable
999 `js2-mode-ast' may or may not be set, depending on whether the
1000 parse tree is available. If the variable is nil, you can pass a
1001 callback to `js2-mode-wait-for-parse', and your callback will be
1002 called after the new parse tree is built. This can take some time
1003 in large files.")
1004
1005 (defface js2-warning
1006 `((((class color) (background light))
1007 (:underline "orange"))
1008 (((class color) (background dark))
1009 (:underline "orange"))
1010 (t (:underline t)))
1011 "Face for JavaScript warnings."
1012 :group 'js2-mode)
1013
1014 (defface js2-error
1015 `((((class color) (background light))
1016 (:foreground "red"))
1017 (((class color) (background dark))
1018 (:foreground "red"))
1019 (t (:foreground "red")))
1020 "Face for JavaScript errors."
1021 :group 'js2-mode)
1022
1023 (defface js2-jsdoc-tag
1024 '((t :foreground "SlateGray"))
1025 "Face used to highlight @whatever tags in jsdoc comments."
1026 :group 'js2-mode)
1027
1028 (defface js2-jsdoc-type
1029 '((t :foreground "SteelBlue"))
1030 "Face used to highlight {FooBar} types in jsdoc comments."
1031 :group 'js2-mode)
1032
1033 (defface js2-jsdoc-value
1034 '((t :foreground "PeachPuff3"))
1035 "Face used to highlight tag values in jsdoc comments."
1036 :group 'js2-mode)
1037
1038 (defface js2-function-param
1039 '((t :foreground "SeaGreen"))
1040 "Face used to highlight function parameters in javascript."
1041 :group 'js2-mode)
1042
1043 (defface js2-instance-member
1044 '((t :foreground "DarkOrchid"))
1045 "Face used to highlight instance variables in javascript.
1046 Not currently used."
1047 :group 'js2-mode)
1048
1049 (defface js2-private-member
1050 '((t :foreground "PeachPuff3"))
1051 "Face used to highlight calls to private methods in javascript.
1052 Not currently used."
1053 :group 'js2-mode)
1054
1055 (defface js2-private-function-call
1056 '((t :foreground "goldenrod"))
1057 "Face used to highlight calls to private functions in javascript.
1058 Not currently used."
1059 :group 'js2-mode)
1060
1061 (defface js2-jsdoc-html-tag-name
1062 '((((class color) (min-colors 88) (background light))
1063 (:foreground "rosybrown"))
1064 (((class color) (min-colors 8) (background dark))
1065 (:foreground "yellow"))
1066 (((class color) (min-colors 8) (background light))
1067 (:foreground "magenta")))
1068 "Face used to highlight jsdoc html tag names"
1069 :group 'js2-mode)
1070
1071 (defface js2-jsdoc-html-tag-delimiter
1072 '((((class color) (min-colors 88) (background light))
1073 (:foreground "dark khaki"))
1074 (((class color) (min-colors 8) (background dark))
1075 (:foreground "green"))
1076 (((class color) (min-colors 8) (background light))
1077 (:foreground "green")))
1078 "Face used to highlight brackets in jsdoc html tags."
1079 :group 'js2-mode)
1080
1081 (defface js2-external-variable
1082 '((t :foreground "orange"))
1083 "Face used to highlight undeclared variable identifiers.")
1084
1085 (defcustom js2-post-parse-callbacks nil
1086 "A list of callback functions invoked after parsing finishes.
1087 Currently, the main use for this function is to add synthetic
1088 declarations to `js2-recorded-identifiers', which see."
1089 :type 'list
1090 :group 'js2-mode)
1091
1092 (defcustom js2-highlight-external-variables t
1093 "Non-nil to highlight undeclared variable identifiers.
1094 An undeclared variable is any variable not declared with var or let
1095 in the current scope or any lexically enclosing scope. If you use
1096 such a variable, then you are either expecting it to originate from
1097 another file, or you've got a potential bug."
1098 :type 'boolean
1099 :group 'js2-mode)
1100
1101 (defcustom js2-auto-insert-catch-block t
1102 "Non-nil to insert matching catch block on open-curly after `try'."
1103 :type 'boolean
1104 :group 'js2-mode)
1105
1106 (defvar js2-mode-map
1107 (let ((map (make-sparse-keymap))
1108 keys)
1109 (define-key map [mouse-1] #'js2-mode-show-node)
1110 (define-key map (kbd "M-j") #'js2-line-break)
1111 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1112 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1113 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1114 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1115 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1116 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1117 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1118 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1119 (when js2-bounce-indent-p
1120 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1121
1122 (define-key map [menu-bar javascript]
1123 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1124
1125 (define-key map [menu-bar javascript customize-js2-mode]
1126 '(menu-item "Customize js2-mode" js2-mode-customize
1127 :help "Customize the behavior of this mode"))
1128
1129 (define-key map [menu-bar javascript js2-force-refresh]
1130 '(menu-item "Force buffer refresh" js2-mode-reset
1131 :help "Re-parse the buffer from scratch"))
1132
1133 (define-key map [menu-bar javascript separator-2]
1134 '("--"))
1135
1136 (define-key map [menu-bar javascript next-error]
1137 '(menu-item "Next warning or error" next-error
1138 :enabled (and js2-mode-ast
1139 (or (js2-ast-root-errors js2-mode-ast)
1140 (js2-ast-root-warnings js2-mode-ast)))
1141 :help "Move to next warning or error"))
1142
1143 (define-key map [menu-bar javascript display-errors]
1144 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1145 :visible (not js2-mode-show-parse-errors)
1146 :help "Turn on display of warnings and errors"))
1147
1148 (define-key map [menu-bar javascript hide-errors]
1149 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1150 :visible js2-mode-show-parse-errors
1151 :help "Turn off display of warnings and errors"))
1152
1153 (define-key map [menu-bar javascript separator-1]
1154 '("--"))
1155
1156 (define-key map [menu-bar javascript js2-toggle-function]
1157 '(menu-item "Show/collapse element" js2-mode-toggle-element
1158 :help "Hide or show function body or comment"))
1159
1160 (define-key map [menu-bar javascript show-comments]
1161 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1162 :visible js2-mode-comments-hidden
1163 :help "Expand all hidden block comments"))
1164
1165 (define-key map [menu-bar javascript hide-comments]
1166 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1167 :visible (not js2-mode-comments-hidden)
1168 :help "Show block comments as /*...*/"))
1169
1170 (define-key map [menu-bar javascript show-all-functions]
1171 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1172 :visible js2-mode-functions-hidden
1173 :help "Expand all hidden function bodies"))
1174
1175 (define-key map [menu-bar javascript hide-all-functions]
1176 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1177 :visible (not js2-mode-functions-hidden)
1178 :help "Show {...} for all top-level function bodies"))
1179
1180 map)
1181 "Keymap used in `js2-mode' buffers.")
1182
1183 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1184
1185 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1186 "Matches a //-comment line. Must be first non-whitespace on line.
1187 First match-group is the leading whitespace.")
1188
1189 (defvar js2-mode-hook nil)
1190
1191 (js2-deflocal js2-mode-ast nil "Private variable.")
1192 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1193 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1194 (js2-deflocal js2-mode-parsing nil "Private variable.")
1195 (js2-deflocal js2-mode-node-overlay nil)
1196
1197 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1198 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1199
1200 (js2-deflocal js2-mode-fontifications nil "Private variable")
1201 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1202 (js2-deflocal js2-imenu-recorder nil "Private variable")
1203 (js2-deflocal js2-imenu-function-map nil "Private variable")
1204
1205 (defvar js2-paragraph-start
1206 "\\(@[a-zA-Z]+\\>\\|$\\)")
1207
1208 ;; Note that we also set a 'c-in-sws text property in html comments,
1209 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1210 (defvar js2-syntactic-ws-start
1211 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1212
1213 (defvar js2-syntactic-ws-end
1214 "\\s \\|[\n\r/]\\|\\s!")
1215
1216 (defvar js2-syntactic-eol
1217 (concat "\\s *\\(/\\*[^*\n\r]*"
1218 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1219 "\\*+/\\s *\\)*"
1220 "\\(//\\|/\\*[^*\n\r]*"
1221 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1222 "\\|\\\\$\\|$\\)")
1223 "Copied from `java-mode'. Needed for some cc-engine functions.")
1224
1225 (defvar js2-comment-prefix-regexp
1226 "//+\\|\\**")
1227
1228 (defvar js2-comment-start-skip
1229 "\\(//+\\|/\\*+\\)\\s *")
1230
1231 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1232 "Non-nil to emit status messages during parsing.")
1233
1234 (defvar js2-mode-functions-hidden nil "Private variable.")
1235 (defvar js2-mode-comments-hidden nil "Private variable.")
1236
1237 (defvar js2-mode-syntax-table
1238 (let ((table (make-syntax-table)))
1239 (c-populate-syntax-table table)
1240 table)
1241 "Syntax table used in `js2-mode' buffers.")
1242
1243 (defvar js2-mode-abbrev-table nil
1244 "Abbrev table in use in `js2-mode' buffers.")
1245 (define-abbrev-table 'js2-mode-abbrev-table ())
1246
1247 (defvar js2-mode-pending-parse-callbacks nil
1248 "List of functions waiting to be notified that parse is finished.")
1249
1250 (defvar js2-mode-last-indented-line -1)
1251
1252 ;;; Localizable error and warning messages
1253
1254 ;; Messages are copied from Rhino's Messages.properties.
1255 ;; Many of the Java-specific messages have been elided.
1256 ;; Add any js2-specific ones at the end, so we can keep
1257 ;; this file synced with changes to Rhino's.
1258
1259 (defvar js2-message-table
1260 (make-hash-table :test 'equal :size 250)
1261 "Contains localized messages for `js2-mode'.")
1262
1263 ;; TODO(stevey): construct this table at compile-time.
1264 (defmacro js2-msg (key &rest strings)
1265 `(puthash ,key (concat ,@strings)
1266 js2-message-table))
1267
1268 (defun js2-get-msg (msg-key)
1269 "Look up a localized message.
1270 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1271 the correct number of ARGS must be provided."
1272 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1273 (args (if (listp msg-key) (cdr msg-key)))
1274 (msg (gethash key js2-message-table)))
1275 (if msg
1276 (apply #'format msg args)
1277 key))) ; default to showing the key
1278
1279 (js2-msg "msg.dup.parms"
1280 "Duplicate parameter name '%s'.")
1281
1282 (js2-msg "msg.too.big.jump"
1283 "Program too complex: jump offset too big.")
1284
1285 (js2-msg "msg.too.big.index"
1286 "Program too complex: internal index exceeds 64K limit.")
1287
1288 (js2-msg "msg.while.compiling.fn"
1289 "Encountered code generation error while compiling function '%s': %s")
1290
1291 (js2-msg "msg.while.compiling.script"
1292 "Encountered code generation error while compiling script: %s")
1293
1294 ;; Context
1295 (js2-msg "msg.ctor.not.found"
1296 "Constructor for '%s' not found.")
1297
1298 (js2-msg "msg.not.ctor"
1299 "'%s' is not a constructor.")
1300
1301 ;; FunctionObject
1302 (js2-msg "msg.varargs.ctor"
1303 "Method or constructor '%s' must be static "
1304 "with the signature (Context cx, Object[] args, "
1305 "Function ctorObj, boolean inNewExpr) "
1306 "to define a variable arguments constructor.")
1307
1308 (js2-msg "msg.varargs.fun"
1309 "Method '%s' must be static with the signature "
1310 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1311 "to define a variable arguments function.")
1312
1313 (js2-msg "msg.incompat.call"
1314 "Method '%s' called on incompatible object.")
1315
1316 (js2-msg "msg.bad.parms"
1317 "Unsupported parameter type '%s' in method '%s'.")
1318
1319 (js2-msg "msg.bad.method.return"
1320 "Unsupported return type '%s' in method '%s'.")
1321
1322 (js2-msg "msg.bad.ctor.return"
1323 "Construction of objects of type '%s' is not supported.")
1324
1325 (js2-msg "msg.no.overload"
1326 "Method '%s' occurs multiple times in class '%s'.")
1327
1328 (js2-msg "msg.method.not.found"
1329 "Method '%s' not found in '%s'.")
1330
1331 ;; IRFactory
1332
1333 (js2-msg "msg.bad.for.in.lhs"
1334 "Invalid left-hand side of for..in loop.")
1335
1336 (js2-msg "msg.mult.index"
1337 "Only one variable allowed in for..in loop.")
1338
1339 (js2-msg "msg.bad.for.in.destruct"
1340 "Left hand side of for..in loop must be an array of "
1341 "length 2 to accept key/value pair.")
1342
1343 (js2-msg "msg.cant.convert"
1344 "Can't convert to type '%s'.")
1345
1346 (js2-msg "msg.bad.assign.left"
1347 "Invalid assignment left-hand side.")
1348
1349 (js2-msg "msg.bad.decr"
1350 "Invalid decerement operand.")
1351
1352 (js2-msg "msg.bad.incr"
1353 "Invalid increment operand.")
1354
1355 (js2-msg "msg.bad.yield"
1356 "yield must be in a function.")
1357
1358 (js2-msg "msg.yield.parenthesized"
1359 "yield expression must be parenthesized.")
1360
1361 ;; NativeGlobal
1362 (js2-msg "msg.cant.call.indirect"
1363 "Function '%s' must be called directly, and not by way of a "
1364 "function of another name.")
1365
1366 (js2-msg "msg.eval.nonstring"
1367 "Calling eval() with anything other than a primitive "
1368 "string value will simply return the value. "
1369 "Is this what you intended?")
1370
1371 (js2-msg "msg.eval.nonstring.strict"
1372 "Calling eval() with anything other than a primitive "
1373 "string value is not allowed in strict mode.")
1374
1375 (js2-msg "msg.bad.destruct.op"
1376 "Invalid destructuring assignment operator")
1377
1378 ;; NativeCall
1379 (js2-msg "msg.only.from.new"
1380 "'%s' may only be invoked from a `new' expression.")
1381
1382 (js2-msg "msg.deprec.ctor"
1383 "The '%s' constructor is deprecated.")
1384
1385 ;; NativeFunction
1386 (js2-msg "msg.no.function.ref.found"
1387 "no source found to decompile function reference %s")
1388
1389 (js2-msg "msg.arg.isnt.array"
1390 "second argument to Function.prototype.apply must be an array")
1391
1392 ;; NativeGlobal
1393 (js2-msg "msg.bad.esc.mask"
1394 "invalid string escape mask")
1395
1396 ;; NativeRegExp
1397 (js2-msg "msg.bad.quant"
1398 "Invalid quantifier %s")
1399
1400 (js2-msg "msg.overlarge.backref"
1401 "Overly large back reference %s")
1402
1403 (js2-msg "msg.overlarge.min"
1404 "Overly large minimum %s")
1405
1406 (js2-msg "msg.overlarge.max"
1407 "Overly large maximum %s")
1408
1409 (js2-msg "msg.zero.quant"
1410 "Zero quantifier %s")
1411
1412 (js2-msg "msg.max.lt.min"
1413 "Maximum %s less than minimum")
1414
1415 (js2-msg "msg.unterm.quant"
1416 "Unterminated quantifier %s")
1417
1418 (js2-msg "msg.unterm.paren"
1419 "Unterminated parenthetical %s")
1420
1421 (js2-msg "msg.unterm.class"
1422 "Unterminated character class %s")
1423
1424 (js2-msg "msg.bad.range"
1425 "Invalid range in character class.")
1426
1427 (js2-msg "msg.trail.backslash"
1428 "Trailing \\ in regular expression.")
1429
1430 (js2-msg "msg.re.unmatched.right.paren"
1431 "unmatched ) in regular expression.")
1432
1433 (js2-msg "msg.no.regexp"
1434 "Regular expressions are not available.")
1435
1436 (js2-msg "msg.bad.backref"
1437 "back-reference exceeds number of capturing parentheses.")
1438
1439 (js2-msg "msg.bad.regexp.compile"
1440 "Only one argument may be specified if the first "
1441 "argument to RegExp.prototype.compile is a RegExp object.")
1442
1443 ;; Parser
1444 (js2-msg "msg.got.syntax.errors"
1445 "Compilation produced %s syntax errors.")
1446
1447 (js2-msg "msg.var.redecl"
1448 "TypeError: redeclaration of var %s.")
1449
1450 (js2-msg "msg.const.redecl"
1451 "TypeError: redeclaration of const %s.")
1452
1453 (js2-msg "msg.let.redecl"
1454 "TypeError: redeclaration of variable %s.")
1455
1456 (js2-msg "msg.parm.redecl"
1457 "TypeError: redeclaration of formal parameter %s.")
1458
1459 (js2-msg "msg.fn.redecl"
1460 "TypeError: redeclaration of function %s.")
1461
1462 (js2-msg "msg.let.decl.not.in.block"
1463 "SyntaxError: let declaration not directly within block")
1464
1465 ;; NodeTransformer
1466 (js2-msg "msg.dup.label"
1467 "duplicated label")
1468
1469 (js2-msg "msg.undef.label"
1470 "undefined label")
1471
1472 (js2-msg "msg.bad.break"
1473 "unlabelled break must be inside loop or switch")
1474
1475 (js2-msg "msg.continue.outside"
1476 "continue must be inside loop")
1477
1478 (js2-msg "msg.continue.nonloop"
1479 "continue can only use labels of iteration statements")
1480
1481 (js2-msg "msg.bad.throw.eol"
1482 "Line terminator is not allowed between the throw "
1483 "keyword and throw expression.")
1484
1485 (js2-msg "msg.no.paren.parms"
1486 "missing ( before function parameters.")
1487
1488 (js2-msg "msg.no.parm"
1489 "missing formal parameter")
1490
1491 (js2-msg "msg.no.paren.after.parms"
1492 "missing ) after formal parameters")
1493
1494 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1495 "parameter without default follows parameter with default")
1496
1497 (js2-msg "msg.param.after.rest" ; added by js2-mode
1498 "parameter after rest parameter")
1499
1500 (js2-msg "msg.no.brace.body"
1501 "missing '{' before function body")
1502
1503 (js2-msg "msg.no.brace.after.body"
1504 "missing } after function body")
1505
1506 (js2-msg "msg.no.paren.cond"
1507 "missing ( before condition")
1508
1509 (js2-msg "msg.no.paren.after.cond"
1510 "missing ) after condition")
1511
1512 (js2-msg "msg.no.semi.stmt"
1513 "missing ; before statement")
1514
1515 (js2-msg "msg.missing.semi"
1516 "missing ; after statement")
1517
1518 (js2-msg "msg.no.name.after.dot"
1519 "missing name after . operator")
1520
1521 (js2-msg "msg.no.name.after.coloncolon"
1522 "missing name after :: operator")
1523
1524 (js2-msg "msg.no.name.after.dotdot"
1525 "missing name after .. operator")
1526
1527 (js2-msg "msg.no.name.after.xmlAttr"
1528 "missing name after .@")
1529
1530 (js2-msg "msg.no.bracket.index"
1531 "missing ] in index expression")
1532
1533 (js2-msg "msg.no.paren.switch"
1534 "missing ( before switch expression")
1535
1536 (js2-msg "msg.no.paren.after.switch"
1537 "missing ) after switch expression")
1538
1539 (js2-msg "msg.no.brace.switch"
1540 "missing '{' before switch body")
1541
1542 (js2-msg "msg.bad.switch"
1543 "invalid switch statement")
1544
1545 (js2-msg "msg.no.colon.case"
1546 "missing : after case expression")
1547
1548 (js2-msg "msg.double.switch.default"
1549 "double default label in the switch statement")
1550
1551 (js2-msg "msg.no.while.do"
1552 "missing while after do-loop body")
1553
1554 (js2-msg "msg.no.paren.for"
1555 "missing ( after for")
1556
1557 (js2-msg "msg.no.semi.for"
1558 "missing ; after for-loop initializer")
1559
1560 (js2-msg "msg.no.semi.for.cond"
1561 "missing ; after for-loop condition")
1562
1563 (js2-msg "msg.in.after.for.name"
1564 "missing in or of after for")
1565
1566 (js2-msg "msg.no.paren.for.ctrl"
1567 "missing ) after for-loop control")
1568
1569 (js2-msg "msg.no.paren.with"
1570 "missing ( before with-statement object")
1571
1572 (js2-msg "msg.no.paren.after.with"
1573 "missing ) after with-statement object")
1574
1575 (js2-msg "msg.no.paren.after.let"
1576 "missing ( after let")
1577
1578 (js2-msg "msg.no.paren.let"
1579 "missing ) after variable list")
1580
1581 (js2-msg "msg.no.curly.let"
1582 "missing } after let statement")
1583
1584 (js2-msg "msg.bad.return"
1585 "invalid return")
1586
1587 (js2-msg "msg.no.brace.block"
1588 "missing } in compound statement")
1589
1590 (js2-msg "msg.bad.label"
1591 "invalid label")
1592
1593 (js2-msg "msg.bad.var"
1594 "missing variable name")
1595
1596 (js2-msg "msg.bad.var.init"
1597 "invalid variable initialization")
1598
1599 (js2-msg "msg.no.colon.cond"
1600 "missing : in conditional expression")
1601
1602 (js2-msg "msg.no.paren.arg"
1603 "missing ) after argument list")
1604
1605 (js2-msg "msg.no.bracket.arg"
1606 "missing ] after element list")
1607
1608 (js2-msg "msg.bad.prop"
1609 "invalid property id")
1610
1611 (js2-msg "msg.no.colon.prop"
1612 "missing : after property id")
1613
1614 (js2-msg "msg.no.brace.prop"
1615 "missing } after property list")
1616
1617 (js2-msg "msg.no.paren"
1618 "missing ) in parenthetical")
1619
1620 (js2-msg "msg.reserved.id"
1621 "identifier is a reserved word")
1622
1623 (js2-msg "msg.no.paren.catch"
1624 "missing ( before catch-block condition")
1625
1626 (js2-msg "msg.bad.catchcond"
1627 "invalid catch block condition")
1628
1629 (js2-msg "msg.catch.unreachable"
1630 "any catch clauses following an unqualified catch are unreachable")
1631
1632 (js2-msg "msg.no.brace.try"
1633 "missing '{' before try block")
1634
1635 (js2-msg "msg.no.brace.catchblock"
1636 "missing '{' before catch-block body")
1637
1638 (js2-msg "msg.try.no.catchfinally"
1639 "'try' without 'catch' or 'finally'")
1640
1641 (js2-msg "msg.no.return.value"
1642 "function %s does not always return a value")
1643
1644 (js2-msg "msg.anon.no.return.value"
1645 "anonymous function does not always return a value")
1646
1647 (js2-msg "msg.return.inconsistent"
1648 "return statement is inconsistent with previous usage")
1649
1650 (js2-msg "msg.generator.returns"
1651 "TypeError: generator function '%s' returns a value")
1652
1653 (js2-msg "msg.anon.generator.returns"
1654 "TypeError: anonymous generator function returns a value")
1655
1656 (js2-msg "msg.syntax"
1657 "syntax error")
1658
1659 (js2-msg "msg.unexpected.eof"
1660 "Unexpected end of file")
1661
1662 (js2-msg "msg.XML.bad.form"
1663 "illegally formed XML syntax")
1664
1665 (js2-msg "msg.XML.not.available"
1666 "XML runtime not available")
1667
1668 (js2-msg "msg.too.deep.parser.recursion"
1669 "Too deep recursion while parsing")
1670
1671 (js2-msg "msg.no.side.effects"
1672 "Code has no side effects")
1673
1674 (js2-msg "msg.extra.trailing.comma"
1675 "Trailing comma is not supported in some browsers")
1676
1677 (js2-msg "msg.array.trailing.comma"
1678 "Trailing comma yields different behavior across browsers")
1679
1680 (js2-msg "msg.equal.as.assign"
1681 (concat "Test for equality (==) mistyped as assignment (=)?"
1682 " (parenthesize to suppress warning)"))
1683
1684 (js2-msg "msg.var.hides.arg"
1685 "Variable %s hides argument")
1686
1687 (js2-msg "msg.destruct.assign.no.init"
1688 "Missing = in destructuring declaration")
1689
1690 ;; ScriptRuntime
1691 (js2-msg "msg.no.properties"
1692 "%s has no properties.")
1693
1694 (js2-msg "msg.invalid.iterator"
1695 "Invalid iterator value")
1696
1697 (js2-msg "msg.iterator.primitive"
1698 "__iterator__ returned a primitive value")
1699
1700 (js2-msg "msg.assn.create.strict"
1701 "Assignment to undeclared variable %s")
1702
1703 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1704 "Undeclared variable or function '%s'")
1705
1706 (js2-msg "msg.ref.undefined.prop"
1707 "Reference to undefined property '%s'")
1708
1709 (js2-msg "msg.prop.not.found"
1710 "Property %s not found.")
1711
1712 (js2-msg "msg.invalid.type"
1713 "Invalid JavaScript value of type %s")
1714
1715 (js2-msg "msg.primitive.expected"
1716 "Primitive type expected (had %s instead)")
1717
1718 (js2-msg "msg.namespace.expected"
1719 "Namespace object expected to left of :: (found %s instead)")
1720
1721 (js2-msg "msg.null.to.object"
1722 "Cannot convert null to an object.")
1723
1724 (js2-msg "msg.undef.to.object"
1725 "Cannot convert undefined to an object.")
1726
1727 (js2-msg "msg.cyclic.value"
1728 "Cyclic %s value not allowed.")
1729
1730 (js2-msg "msg.is.not.defined"
1731 "'%s' is not defined.")
1732
1733 (js2-msg "msg.undef.prop.read"
1734 "Cannot read property '%s' from %s")
1735
1736 (js2-msg "msg.undef.prop.write"
1737 "Cannot set property '%s' of %s to '%s'")
1738
1739 (js2-msg "msg.undef.prop.delete"
1740 "Cannot delete property '%s' of %s")
1741
1742 (js2-msg "msg.undef.method.call"
1743 "Cannot call method '%s' of %s")
1744
1745 (js2-msg "msg.undef.with"
1746 "Cannot apply 'with' to %s")
1747
1748 (js2-msg "msg.isnt.function"
1749 "%s is not a function, it is %s.")
1750
1751 (js2-msg "msg.isnt.function.in"
1752 "Cannot call property %s in object %s. "
1753 "It is not a function, it is '%s'.")
1754
1755 (js2-msg "msg.function.not.found"
1756 "Cannot find function %s.")
1757
1758 (js2-msg "msg.function.not.found.in"
1759 "Cannot find function %s in object %s.")
1760
1761 (js2-msg "msg.isnt.xml.object"
1762 "%s is not an xml object.")
1763
1764 (js2-msg "msg.no.ref.to.get"
1765 "%s is not a reference to read reference value.")
1766
1767 (js2-msg "msg.no.ref.to.set"
1768 "%s is not a reference to set reference value to %s.")
1769
1770 (js2-msg "msg.no.ref.from.function"
1771 "Function %s can not be used as the left-hand "
1772 "side of assignment or as an operand of ++ or -- operator.")
1773
1774 (js2-msg "msg.bad.default.value"
1775 "Object's getDefaultValue() method returned an object.")
1776
1777 (js2-msg "msg.instanceof.not.object"
1778 "Can't use instanceof on a non-object.")
1779
1780 (js2-msg "msg.instanceof.bad.prototype"
1781 "'prototype' property of %s is not an object.")
1782
1783 (js2-msg "msg.bad.radix"
1784 "illegal radix %s.")
1785
1786 ;; ScriptableObject
1787 (js2-msg "msg.default.value"
1788 "Cannot find default value for object.")
1789
1790 (js2-msg "msg.zero.arg.ctor"
1791 "Cannot load class '%s' which has no zero-parameter constructor.")
1792
1793 (js2-msg "msg.ctor.multiple.parms"
1794 "Can't define constructor or class %s since more than "
1795 "one constructor has multiple parameters.")
1796
1797 (js2-msg "msg.extend.scriptable"
1798 "%s must extend ScriptableObject in order to define property %s.")
1799
1800 (js2-msg "msg.bad.getter.parms"
1801 "In order to define a property, getter %s must have zero "
1802 "parameters or a single ScriptableObject parameter.")
1803
1804 (js2-msg "msg.obj.getter.parms"
1805 "Expected static or delegated getter %s to take "
1806 "a ScriptableObject parameter.")
1807
1808 (js2-msg "msg.getter.static"
1809 "Getter and setter must both be static or neither be static.")
1810
1811 (js2-msg "msg.setter.return"
1812 "Setter must have void return type: %s")
1813
1814 (js2-msg "msg.setter2.parms"
1815 "Two-parameter setter must take a ScriptableObject as "
1816 "its first parameter.")
1817
1818 (js2-msg "msg.setter1.parms"
1819 "Expected single parameter setter for %s")
1820
1821 (js2-msg "msg.setter2.expected"
1822 "Expected static or delegated setter %s to take two parameters.")
1823
1824 (js2-msg "msg.setter.parms"
1825 "Expected either one or two parameters for setter.")
1826
1827 (js2-msg "msg.setter.bad.type"
1828 "Unsupported parameter type '%s' in setter '%s'.")
1829
1830 (js2-msg "msg.add.sealed"
1831 "Cannot add a property to a sealed object: %s.")
1832
1833 (js2-msg "msg.remove.sealed"
1834 "Cannot remove a property from a sealed object: %s.")
1835
1836 (js2-msg "msg.modify.sealed"
1837 "Cannot modify a property of a sealed object: %s.")
1838
1839 (js2-msg "msg.modify.readonly"
1840 "Cannot modify readonly property: %s.")
1841
1842 ;; TokenStream
1843 (js2-msg "msg.missing.exponent"
1844 "missing exponent")
1845
1846 (js2-msg "msg.caught.nfe"
1847 "number format error")
1848
1849 (js2-msg "msg.unterminated.string.lit"
1850 "unterminated string literal")
1851
1852 (js2-msg "msg.unterminated.comment"
1853 "unterminated comment")
1854
1855 (js2-msg "msg.unterminated.re.lit"
1856 "unterminated regular expression literal")
1857
1858 (js2-msg "msg.invalid.re.flag"
1859 "invalid flag after regular expression")
1860
1861 (js2-msg "msg.no.re.input.for"
1862 "no input for %s")
1863
1864 (js2-msg "msg.illegal.character"
1865 "illegal character")
1866
1867 (js2-msg "msg.invalid.escape"
1868 "invalid Unicode escape sequence")
1869
1870 (js2-msg "msg.bad.namespace"
1871 "not a valid default namespace statement. "
1872 "Syntax is: default xml namespace = EXPRESSION;")
1873
1874 ;; TokensStream warnings
1875 (js2-msg "msg.bad.octal.literal"
1876 "illegal octal literal digit %s; "
1877 "interpreting it as a decimal digit")
1878
1879 (js2-msg "msg.reserved.keyword"
1880 "illegal usage of future reserved keyword %s; "
1881 "interpreting it as ordinary identifier")
1882
1883 (js2-msg "msg.script.is.not.constructor"
1884 "Script objects are not constructors.")
1885
1886 ;; Arrays
1887 (js2-msg "msg.arraylength.bad"
1888 "Inappropriate array length.")
1889
1890 ;; Arrays
1891 (js2-msg "msg.arraylength.too.big"
1892 "Array length %s exceeds supported capacity limit.")
1893
1894 ;; URI
1895 (js2-msg "msg.bad.uri"
1896 "Malformed URI sequence.")
1897
1898 ;; Number
1899 (js2-msg "msg.bad.precision"
1900 "Precision %s out of range.")
1901
1902 ;; NativeGenerator
1903 (js2-msg "msg.send.newborn"
1904 "Attempt to send value to newborn generator")
1905
1906 (js2-msg "msg.already.exec.gen"
1907 "Already executing generator")
1908
1909 (js2-msg "msg.StopIteration.invalid"
1910 "StopIteration may not be changed to an arbitrary object.")
1911
1912 ;; Interpreter
1913 (js2-msg "msg.yield.closing"
1914 "Yield from closing generator")
1915
1916 ;;; Utilities
1917
1918 (defun js2-delete-if (predicate list)
1919 "Remove all items satisfying PREDICATE in LIST."
1920 (loop for item in list
1921 if (not (funcall predicate item))
1922 collect item))
1923
1924 (defun js2-position (element list)
1925 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1926 Returns nil if element is not found in the list."
1927 (let ((count 0)
1928 found)
1929 (while (and list (not found))
1930 (if (eq element (car list))
1931 (setq found t)
1932 (setq count (1+ count)
1933 list (cdr list))))
1934 (if found count)))
1935
1936 (defun js2-find-if (predicate list)
1937 "Find first item satisfying PREDICATE in LIST."
1938 (let (result)
1939 (while (and list (not result))
1940 (if (funcall predicate (car list))
1941 (setq result (car list)))
1942 (setq list (cdr list)))
1943 result))
1944
1945 (defmacro js2-time (form)
1946 "Evaluate FORM, discard result, and return elapsed time in sec."
1947 (declare (debug t))
1948 (let ((beg (make-symbol "--js2-time-beg--"))
1949 (delta (make-symbol "--js2-time-end--")))
1950 `(let ((,beg (current-time))
1951 ,delta)
1952 ,form
1953 (/ (truncate (* (- (float-time (current-time))
1954 (float-time ,beg))
1955 10000))
1956 10000.0))))
1957
1958 (defsubst js2-same-line (pos)
1959 "Return t if POS is on the same line as current point."
1960 (and (>= pos (point-at-bol))
1961 (<= pos (point-at-eol))))
1962
1963 (defun js2-code-bug ()
1964 "Signal an error when we encounter an unexpected code path."
1965 (error "failed assertion"))
1966
1967 (defsubst js2-record-text-property (beg end prop value)
1968 "Record a text property to set when parsing finishes."
1969 (push (list beg end prop value) js2-mode-deferred-properties))
1970
1971 ;; I'd like to associate errors with nodes, but for now the
1972 ;; easiest thing to do is get the context info from the last token.
1973 (defun js2-record-parse-error (msg &optional arg pos len)
1974 (push (list (list msg arg)
1975 (or pos js2-token-beg)
1976 (or len (- js2-token-end js2-token-beg)))
1977 js2-parsed-errors))
1978
1979 (defun js2-report-error (msg &optional msg-arg pos len)
1980 "Signal a syntax error or record a parse error."
1981 (if js2-recover-from-parse-errors
1982 (js2-record-parse-error msg msg-arg pos len)
1983 (signal 'js2-syntax-error
1984 (list msg
1985 js2-ts-lineno
1986 (save-excursion
1987 (goto-char js2-ts-cursor)
1988 (current-column))
1989 js2-ts-hit-eof))))
1990
1991 (defun js2-report-warning (msg &optional msg-arg pos len face)
1992 (if js2-compiler-report-warning-as-error
1993 (js2-report-error msg msg-arg pos len)
1994 (push (list (list msg msg-arg)
1995 (or pos js2-token-beg)
1996 (or len (- js2-token-end js2-token-beg))
1997 face)
1998 js2-parsed-warnings)))
1999
2000 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2001 (if js2-compiler-strict-mode
2002 (js2-report-warning msg-id msg-arg beg
2003 (and beg end (- end beg)))))
2004
2005 (put 'js2-syntax-error 'error-conditions
2006 '(error syntax-error js2-syntax-error))
2007 (put 'js2-syntax-error 'error-message "Syntax error")
2008
2009 (put 'js2-parse-error 'error-conditions
2010 '(error parse-error js2-parse-error))
2011 (put 'js2-parse-error 'error-message "Parse error")
2012
2013 (defmacro js2-clear-flag (flags flag)
2014 `(setq ,flags (logand ,flags (lognot ,flag))))
2015
2016 (defmacro js2-set-flag (flags flag)
2017 "Logical-or FLAG into FLAGS."
2018 `(setq ,flags (logior ,flags ,flag)))
2019
2020 (defsubst js2-flag-set-p (flags flag)
2021 (/= 0 (logand flags flag)))
2022
2023 (defsubst js2-flag-not-set-p (flags flag)
2024 (zerop (logand flags flag)))
2025
2026 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2027 "Evaluate BODY with the _ character set to be word-syntax."
2028 (declare (indent 0) (debug t))
2029 (let ((old-syntax (make-symbol "old-syntax")))
2030 `(let ((,old-syntax (string (char-syntax ?_))))
2031 (unwind-protect
2032 (progn
2033 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2034 ,@body)
2035 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2036
2037 (defsubst js2-char-uppercase-p (c)
2038 "Return t if C is an uppercase character.
2039 Handles unicode and latin chars properly."
2040 (/= c (downcase c)))
2041
2042 (defsubst js2-char-lowercase-p (c)
2043 "Return t if C is an uppercase character.
2044 Handles unicode and latin chars properly."
2045 (/= c (upcase c)))
2046
2047 ;;; AST struct and function definitions
2048
2049 ;; flags for ast node property 'member-type (used for e4x operators)
2050 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2051 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2052 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2053
2054 (defsubst js2-relpos (pos anchor)
2055 "Convert POS to be relative to ANCHOR.
2056 If POS is nil, returns nil."
2057 (and pos (- pos anchor)))
2058
2059 (defun js2-make-pad (indent)
2060 (if (zerop indent)
2061 ""
2062 (make-string (* indent js2-basic-offset) ? )))
2063
2064 (defun js2-visit-ast (node callback)
2065 "Visit every node in ast NODE with visitor CALLBACK.
2066
2067 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2068 called twice: once to visit the node, and again after all the node's
2069 children have been processed. The END-P argument is nil on the first
2070 call and non-nil on the second call. The return value of the callback
2071 affects the traversal: if non-nil, the children of NODE are processed.
2072 If the callback returns nil, or if the node has no children, then the
2073 callback is called immediately with a non-nil END-P argument.
2074
2075 The node traversal is approximately lexical-order, although there
2076 are currently no guarantees around this."
2077 (when node
2078 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2079 ;; visit the node
2080 (when (funcall callback node nil)
2081 ;; visit the kids
2082 (cond
2083 ((eq vfunc 'js2-visit-none)
2084 nil) ; don't even bother calling it
2085 ;; Each AST node type has to define a `js2-visitor' function
2086 ;; that takes a node and a callback, and calls `js2-visit-ast'
2087 ;; on each child of the node.
2088 (vfunc
2089 (funcall vfunc node callback))
2090 (t
2091 (error "%s does not define a visitor-traversal function"
2092 (aref node 0)))))
2093 ;; call the end-visit
2094 (funcall callback node t))))
2095
2096 (defstruct (js2-node
2097 (:constructor nil)) ; abstract
2098 "Base AST node type."
2099 (type -1) ; token type
2100 (pos -1) ; start position of this AST node in parsed input
2101 (len 1) ; num characters spanned by the node
2102 props ; optional node property list (an alist)
2103 parent) ; link to parent node; null for root
2104
2105 (defsubst js2-node-get-prop (node prop &optional default)
2106 (or (cadr (assoc prop (js2-node-props node))) default))
2107
2108 (defsubst js2-node-set-prop (node prop value)
2109 (setf (js2-node-props node)
2110 (cons (list prop value) (js2-node-props node))))
2111
2112 (defun js2-fixup-starts (n nodes)
2113 "Adjust the start positions of NODES to be relative to N.
2114 Any node in the list may be nil, for convenience."
2115 (dolist (node nodes)
2116 (when node
2117 (setf (js2-node-pos node) (- (js2-node-pos node)
2118 (js2-node-pos n))))))
2119
2120 (defun js2-node-add-children (parent &rest nodes)
2121 "Set parent node of NODES to PARENT, and return PARENT.
2122 Does nothing if we're not recording parent links.
2123 If any given node in NODES is nil, doesn't record that link."
2124 (js2-fixup-starts parent nodes)
2125 (dolist (node nodes)
2126 (and node
2127 (setf (js2-node-parent node) parent))))
2128
2129 ;; Non-recursive since it's called a frightening number of times.
2130 (defun js2-node-abs-pos (n)
2131 (let ((pos (js2-node-pos n)))
2132 (while (setq n (js2-node-parent n))
2133 (setq pos (+ pos (js2-node-pos n))))
2134 pos))
2135
2136 (defsubst js2-node-abs-end (n)
2137 "Return absolute buffer position of end of N."
2138 (+ (js2-node-abs-pos n) (js2-node-len n)))
2139
2140 ;; It's important to make sure block nodes have a Lisp list for the
2141 ;; child nodes, to limit printing recursion depth in an AST that
2142 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2143 ;; a sufficiently large vector tree.
2144
2145 (defstruct (js2-block-node
2146 (:include js2-node)
2147 (:constructor nil)
2148 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2149 (pos js2-token-beg)
2150 len
2151 props
2152 kids)))
2153 "A block of statements."
2154 kids) ; a Lisp list of the child statement nodes
2155
2156 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2157 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2158
2159 (defun js2-visit-block (ast callback)
2160 "Visit the `js2-block-node' children of AST."
2161 (dolist (kid (js2-block-node-kids ast))
2162 (js2-visit-ast kid callback)))
2163
2164 (defun js2-print-block (n i)
2165 (let ((pad (js2-make-pad i)))
2166 (insert pad "{\n")
2167 (dolist (kid (js2-block-node-kids n))
2168 (js2-print-ast kid (1+ i)))
2169 (insert pad "}")))
2170
2171 (defstruct (js2-scope
2172 (:include js2-block-node)
2173 (:constructor nil)
2174 (:constructor make-js2-scope (&key (type js2-BLOCK)
2175 (pos js2-token-beg)
2176 len
2177 kids)))
2178 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2179 ;; I don't have one of those handy, so I'll use an alist for now.
2180 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2181 ;; and is much lighter-weight to construct (both CPU and mem).
2182 ;; The keys are interned strings (symbols) for faster lookup.
2183 ;; Should switch to hybrid alist/hashtable eventually.
2184 symbol-table ; an alist of (symbol . js2-symbol)
2185 parent-scope ; a `js2-scope'
2186 top) ; top-level `js2-scope' (script/function)
2187
2188 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2189 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2190
2191 (defun js2-node-get-enclosing-scope (node)
2192 "Return the innermost `js2-scope' node surrounding NODE.
2193 Returns nil if there is no enclosing scope node."
2194 (let ((parent (js2-node-parent node)))
2195 (while (not (js2-scope-p parent))
2196 (setq parent (js2-node-parent parent)))
2197 parent))
2198
2199 (defun js2-get-defining-scope (scope name)
2200 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2201 Returns `js2-scope' in which NAME is defined, or nil if not found."
2202 (let ((sym (if (symbolp name)
2203 name
2204 (intern name)))
2205 table
2206 result
2207 (continue t))
2208 (while (and scope continue)
2209 (if (and (setq table (js2-scope-symbol-table scope))
2210 (assq sym table))
2211 (setq continue nil
2212 result scope)
2213 (setq scope (js2-scope-parent-scope scope))))
2214 result))
2215
2216 (defun js2-scope-get-symbol (scope name)
2217 "Return symbol table entry for NAME in SCOPE.
2218 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2219 (and (js2-scope-symbol-table scope)
2220 (cdr (assq (if (symbolp name)
2221 name
2222 (intern name))
2223 (js2-scope-symbol-table scope)))))
2224
2225 (defun js2-scope-put-symbol (scope name symbol)
2226 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2227 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2228 (let* ((table (js2-scope-symbol-table scope))
2229 (sym (if (symbolp name) name (intern name)))
2230 (entry (assq sym table)))
2231 (if entry
2232 (setcdr entry symbol)
2233 (push (cons sym symbol)
2234 (js2-scope-symbol-table scope)))))
2235
2236 (defstruct (js2-symbol
2237 (:constructor nil)
2238 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2239 "A symbol table entry."
2240 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2241 ;; js2-LET, or js2-CONST
2242 decl-type
2243 name ; string
2244 ast-node) ; a `js2-node'
2245
2246 (defstruct (js2-error-node
2247 (:include js2-node)
2248 (:constructor nil) ; silence emacs21 byte-compiler
2249 (:constructor make-js2-error-node (&key (type js2-ERROR)
2250 (pos js2-token-beg)
2251 len)))
2252 "AST node representing a parse error.")
2253
2254 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2255 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2256
2257 (defstruct (js2-script-node
2258 (:include js2-scope)
2259 (:constructor nil)
2260 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2261 (pos js2-token-beg)
2262 len
2263 var-decls
2264 fun-decls)))
2265 functions ; Lisp list of nested functions
2266 regexps ; Lisp list of (string . flags)
2267 symbols ; alist (every symbol gets unique index)
2268 (param-count 0)
2269 var-names ; vector of string names
2270 consts ; bool-vector matching var-decls
2271 (temp-number 0)) ; for generating temp variables
2272
2273 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2274 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2275
2276 (defun js2-print-script (node indent)
2277 (dolist (kid (js2-block-node-kids node))
2278 (js2-print-ast kid indent)))
2279
2280 (defstruct (js2-ast-root
2281 (:include js2-script-node)
2282 (:constructor nil)
2283 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2284 (pos js2-token-beg)
2285 len
2286 buffer)))
2287 "The root node of a js2 AST."
2288 buffer ; the source buffer from which the code was parsed
2289 comments ; a Lisp list of comments, ordered by start position
2290 errors ; a Lisp list of errors found during parsing
2291 warnings ; a Lisp list of warnings found during parsing
2292 node-count) ; number of nodes in the tree, including the root
2293
2294 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2295 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2296
2297 (defun js2-visit-ast-root (ast callback)
2298 (dolist (kid (js2-ast-root-kids ast))
2299 (js2-visit-ast kid callback))
2300 (dolist (comment (js2-ast-root-comments ast))
2301 (js2-visit-ast comment callback)))
2302
2303 (defstruct (js2-comment-node
2304 (:include js2-node)
2305 (:constructor nil)
2306 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2307 (pos js2-token-beg)
2308 len
2309 (format js2-ts-comment-type))))
2310 format) ; 'line, 'block, 'jsdoc or 'html
2311
2312 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2313 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2314
2315 (defun js2-print-comment (n i)
2316 ;; We really ought to link end-of-line comments to their nodes.
2317 ;; Or maybe we could add a new comment type, 'endline.
2318 (insert (js2-make-pad i)
2319 (js2-node-string n)))
2320
2321 (defstruct (js2-expr-stmt-node
2322 (:include js2-node)
2323 (:constructor nil)
2324 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2325 (pos js2-ts-cursor)
2326 len
2327 expr)))
2328 "An expression statement."
2329 expr)
2330
2331 (defsubst js2-expr-stmt-node-set-has-result (node)
2332 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2333 (setf (js2-node-type node) js2-EXPR_RESULT))
2334
2335 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2336 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2337
2338 (defun js2-visit-expr-stmt-node (n v)
2339 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2340
2341 (defun js2-print-expr-stmt-node (n indent)
2342 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2343 (insert ";\n"))
2344
2345 (defstruct (js2-loop-node
2346 (:include js2-scope)
2347 (:constructor nil))
2348 "Abstract supertype of loop nodes."
2349 body ; a `js2-block-node'
2350 lp ; position of left-paren, nil if omitted
2351 rp) ; position of right-paren, nil if omitted
2352
2353 (defstruct (js2-do-node
2354 (:include js2-loop-node)
2355 (:constructor nil)
2356 (:constructor make-js2-do-node (&key (type js2-DO)
2357 (pos js2-token-beg)
2358 len
2359 body
2360 condition
2361 while-pos
2362 lp
2363 rp)))
2364 "AST node for do-loop."
2365 condition ; while (expression)
2366 while-pos) ; buffer position of 'while' keyword
2367
2368 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2369 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2370
2371 (defun js2-visit-do-node (n v)
2372 (js2-visit-ast (js2-do-node-body n) v)
2373 (js2-visit-ast (js2-do-node-condition n) v))
2374
2375 (defun js2-print-do-node (n i)
2376 (let ((pad (js2-make-pad i)))
2377 (insert pad "do {\n")
2378 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2379 (js2-print-ast kid (1+ i)))
2380 (insert pad "} while (")
2381 (js2-print-ast (js2-do-node-condition n) 0)
2382 (insert ");\n")))
2383
2384 (defstruct (js2-while-node
2385 (:include js2-loop-node)
2386 (:constructor nil)
2387 (:constructor make-js2-while-node (&key (type js2-WHILE)
2388 (pos js2-token-beg)
2389 len body
2390 condition lp
2391 rp)))
2392 "AST node for while-loop."
2393 condition) ; while-condition
2394
2395 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2396 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2397
2398 (defun js2-visit-while-node (n v)
2399 (js2-visit-ast (js2-while-node-condition n) v)
2400 (js2-visit-ast (js2-while-node-body n) v))
2401
2402 (defun js2-print-while-node (n i)
2403 (let ((pad (js2-make-pad i)))
2404 (insert pad "while (")
2405 (js2-print-ast (js2-while-node-condition n) 0)
2406 (insert ") {\n")
2407 (js2-print-body (js2-while-node-body n) (1+ i))
2408 (insert pad "}\n")))
2409
2410 (defstruct (js2-for-node
2411 (:include js2-loop-node)
2412 (:constructor nil)
2413 (:constructor make-js2-for-node (&key (type js2-FOR)
2414 (pos js2-ts-cursor)
2415 len body init
2416 condition
2417 update lp rp)))
2418 "AST node for a C-style for-loop."
2419 init ; initialization expression
2420 condition ; loop condition
2421 update) ; update clause
2422
2423 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2424 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2425
2426 (defun js2-visit-for-node (n v)
2427 (js2-visit-ast (js2-for-node-init n) v)
2428 (js2-visit-ast (js2-for-node-condition n) v)
2429 (js2-visit-ast (js2-for-node-update n) v)
2430 (js2-visit-ast (js2-for-node-body n) v))
2431
2432 (defun js2-print-for-node (n i)
2433 (let ((pad (js2-make-pad i)))
2434 (insert pad "for (")
2435 (js2-print-ast (js2-for-node-init n) 0)
2436 (insert "; ")
2437 (js2-print-ast (js2-for-node-condition n) 0)
2438 (insert "; ")
2439 (js2-print-ast (js2-for-node-update n) 0)
2440 (insert ") {\n")
2441 (js2-print-body (js2-for-node-body n) (1+ i))
2442 (insert pad "}\n")))
2443
2444 (defstruct (js2-for-in-node
2445 (:include js2-loop-node)
2446 (:constructor nil)
2447 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2448 (pos js2-ts-cursor)
2449 len body
2450 iterator
2451 object
2452 in-pos
2453 each-pos
2454 foreach-p forof-p
2455 lp rp)))
2456 "AST node for a for..in loop."
2457 iterator ; [var] foo in ...
2458 object ; object over which we're iterating
2459 in-pos ; buffer position of 'in' keyword
2460 each-pos ; buffer position of 'each' keyword, if foreach-p
2461 foreach-p ; t if it's a for-each loop
2462 forof-p) ; t if it's a for-of loop
2463
2464 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2465 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2466
2467 (defun js2-visit-for-in-node (n v)
2468 (js2-visit-ast (js2-for-in-node-iterator n) v)
2469 (js2-visit-ast (js2-for-in-node-object n) v)
2470 (js2-visit-ast (js2-for-in-node-body n) v))
2471
2472 (defun js2-print-for-in-node (n i)
2473 (let ((pad (js2-make-pad i))
2474 (foreach (js2-for-in-node-foreach-p n))
2475 (forof (js2-for-in-node-forof-p n)))
2476 (insert pad "for ")
2477 (if foreach
2478 (insert "each "))
2479 (insert "(")
2480 (js2-print-ast (js2-for-in-node-iterator n) 0)
2481 (if forof
2482 (insert " of ")
2483 (insert " in "))
2484 (js2-print-ast (js2-for-in-node-object n) 0)
2485 (insert ") {\n")
2486 (js2-print-body (js2-for-in-node-body n) (1+ i))
2487 (insert pad "}\n")))
2488
2489 (defstruct (js2-return-node
2490 (:include js2-node)
2491 (:constructor nil)
2492 (:constructor make-js2-return-node (&key (type js2-RETURN)
2493 (pos js2-ts-cursor)
2494 len
2495 retval)))
2496 "AST node for a return statement."
2497 retval) ; expression to return, or 'undefined
2498
2499 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2500 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2501
2502 (defun js2-visit-return-node (n v)
2503 (js2-visit-ast (js2-return-node-retval n) v))
2504
2505 (defun js2-print-return-node (n i)
2506 (insert (js2-make-pad i) "return")
2507 (when (js2-return-node-retval n)
2508 (insert " ")
2509 (js2-print-ast (js2-return-node-retval n) 0))
2510 (insert ";\n"))
2511
2512 (defstruct (js2-if-node
2513 (:include js2-node)
2514 (:constructor nil)
2515 (:constructor make-js2-if-node (&key (type js2-IF)
2516 (pos js2-ts-cursor)
2517 len condition
2518 then-part
2519 else-pos
2520 else-part lp
2521 rp)))
2522 "AST node for an if-statement."
2523 condition ; expression
2524 then-part ; statement or block
2525 else-pos ; optional buffer position of 'else' keyword
2526 else-part ; optional statement or block
2527 lp ; position of left-paren, nil if omitted
2528 rp) ; position of right-paren, nil if omitted
2529
2530 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2531 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2532
2533 (defun js2-visit-if-node (n v)
2534 (js2-visit-ast (js2-if-node-condition n) v)
2535 (js2-visit-ast (js2-if-node-then-part n) v)
2536 (js2-visit-ast (js2-if-node-else-part n) v))
2537
2538 (defun js2-print-if-node (n i)
2539 (let ((pad (js2-make-pad i))
2540 (then-part (js2-if-node-then-part n))
2541 (else-part (js2-if-node-else-part n)))
2542 (insert pad "if (")
2543 (js2-print-ast (js2-if-node-condition n) 0)
2544 (insert ") {\n")
2545 (js2-print-body then-part (1+ i))
2546 (insert pad "}")
2547 (cond
2548 ((not else-part)
2549 (insert "\n"))
2550 ((js2-if-node-p else-part)
2551 (insert " else ")
2552 (js2-print-body else-part i))
2553 (t
2554 (insert " else {\n")
2555 (js2-print-body else-part (1+ i))
2556 (insert pad "}\n")))))
2557
2558 (defstruct (js2-try-node
2559 (:include js2-node)
2560 (:constructor nil)
2561 (:constructor make-js2-try-node (&key (type js2-TRY)
2562 (pos js2-ts-cursor)
2563 len
2564 try-block
2565 catch-clauses
2566 finally-block)))
2567 "AST node for a try-statement."
2568 try-block
2569 catch-clauses ; a Lisp list of `js2-catch-node'
2570 finally-block) ; a `js2-finally-node'
2571
2572 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2573 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2574
2575 (defun js2-visit-try-node (n v)
2576 (js2-visit-ast (js2-try-node-try-block n) v)
2577 (dolist (clause (js2-try-node-catch-clauses n))
2578 (js2-visit-ast clause v))
2579 (js2-visit-ast (js2-try-node-finally-block n) v))
2580
2581 (defun js2-print-try-node (n i)
2582 (let ((pad (js2-make-pad i))
2583 (catches (js2-try-node-catch-clauses n))
2584 (finally (js2-try-node-finally-block n)))
2585 (insert pad "try {\n")
2586 (js2-print-body (js2-try-node-try-block n) (1+ i))
2587 (insert pad "}")
2588 (when catches
2589 (dolist (catch catches)
2590 (js2-print-ast catch i)))
2591 (if finally
2592 (js2-print-ast finally i)
2593 (insert "\n"))))
2594
2595 (defstruct (js2-catch-node
2596 (:include js2-node)
2597 (:constructor nil)
2598 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2599 (pos js2-ts-cursor)
2600 len
2601 param
2602 guard-kwd
2603 guard-expr
2604 block lp
2605 rp)))
2606 "AST node for a catch clause."
2607 param ; destructuring form or simple name node
2608 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2609 guard-expr ; catch condition, a `js2-node'
2610 block ; statements, a `js2-block-node'
2611 lp ; buffer position of left-paren, nil if omitted
2612 rp) ; buffer position of right-paren, nil if omitted
2613
2614 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2615 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2616
2617 (defun js2-visit-catch-node (n v)
2618 (js2-visit-ast (js2-catch-node-param n) v)
2619 (when (js2-catch-node-guard-kwd n)
2620 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2621 (js2-visit-ast (js2-catch-node-block n) v))
2622
2623 (defun js2-print-catch-node (n i)
2624 (let ((pad (js2-make-pad i))
2625 (guard-kwd (js2-catch-node-guard-kwd n))
2626 (guard-expr (js2-catch-node-guard-expr n)))
2627 (insert " catch (")
2628 (js2-print-ast (js2-catch-node-param n) 0)
2629 (when guard-kwd
2630 (insert " if ")
2631 (js2-print-ast guard-expr 0))
2632 (insert ") {\n")
2633 (js2-print-body (js2-catch-node-block n) (1+ i))
2634 (insert pad "}")))
2635
2636 (defstruct (js2-finally-node
2637 (:include js2-node)
2638 (:constructor nil)
2639 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2640 (pos js2-ts-cursor)
2641 len body)))
2642 "AST node for a finally clause."
2643 body) ; a `js2-node', often but not always a block node
2644
2645 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2646 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2647
2648 (defun js2-visit-finally-node (n v)
2649 (js2-visit-ast (js2-finally-node-body n) v))
2650
2651 (defun js2-print-finally-node (n i)
2652 (let ((pad (js2-make-pad i)))
2653 (insert " finally {\n")
2654 (js2-print-body (js2-finally-node-body n) (1+ i))
2655 (insert pad "}\n")))
2656
2657 (defstruct (js2-switch-node
2658 (:include js2-node)
2659 (:constructor nil)
2660 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2661 (pos js2-ts-cursor)
2662 len
2663 discriminant
2664 cases lp
2665 rp)))
2666 "AST node for a switch statement."
2667 discriminant ; a `js2-node' (switch expression)
2668 cases ; a Lisp list of `js2-case-node'
2669 lp ; position of open-paren for discriminant, nil if omitted
2670 rp) ; position of close-paren for discriminant, nil if omitted
2671
2672 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2673 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2674
2675 (defun js2-visit-switch-node (n v)
2676 (js2-visit-ast (js2-switch-node-discriminant n) v)
2677 (dolist (c (js2-switch-node-cases n))
2678 (js2-visit-ast c v)))
2679
2680 (defun js2-print-switch-node (n i)
2681 (let ((pad (js2-make-pad i))
2682 (cases (js2-switch-node-cases n)))
2683 (insert pad "switch (")
2684 (js2-print-ast (js2-switch-node-discriminant n) 0)
2685 (insert ") {\n")
2686 (dolist (case cases)
2687 (js2-print-ast case i))
2688 (insert pad "}\n")))
2689
2690 (defstruct (js2-case-node
2691 (:include js2-block-node)
2692 (:constructor nil)
2693 (:constructor make-js2-case-node (&key (type js2-CASE)
2694 (pos js2-ts-cursor)
2695 len kids expr)))
2696 "AST node for a case clause of a switch statement."
2697 expr) ; the case expression (nil for default)
2698
2699 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2700 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2701
2702 (defun js2-visit-case-node (n v)
2703 (js2-visit-ast (js2-case-node-expr n) v)
2704 (js2-visit-block n v))
2705
2706 (defun js2-print-case-node (n i)
2707 (let ((pad (js2-make-pad i))
2708 (expr (js2-case-node-expr n)))
2709 (insert pad)
2710 (if (null expr)
2711 (insert "default:\n")
2712 (insert "case ")
2713 (js2-print-ast expr 0)
2714 (insert ":\n"))
2715 (dolist (kid (js2-case-node-kids n))
2716 (js2-print-ast kid (1+ i)))))
2717
2718 (defstruct (js2-throw-node
2719 (:include js2-node)
2720 (:constructor nil)
2721 (:constructor make-js2-throw-node (&key (type js2-THROW)
2722 (pos js2-ts-cursor)
2723 len expr)))
2724 "AST node for a throw statement."
2725 expr) ; the expression to throw
2726
2727 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2728 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2729
2730 (defun js2-visit-throw-node (n v)
2731 (js2-visit-ast (js2-throw-node-expr n) v))
2732
2733 (defun js2-print-throw-node (n i)
2734 (insert (js2-make-pad i) "throw ")
2735 (js2-print-ast (js2-throw-node-expr n) 0)
2736 (insert ";\n"))
2737
2738 (defstruct (js2-with-node
2739 (:include js2-node)
2740 (:constructor nil)
2741 (:constructor make-js2-with-node (&key (type js2-WITH)
2742 (pos js2-ts-cursor)
2743 len object
2744 body lp rp)))
2745 "AST node for a with-statement."
2746 object
2747 body
2748 lp ; buffer position of left-paren around object, nil if omitted
2749 rp) ; buffer position of right-paren around object, nil if omitted
2750
2751 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2752 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2753
2754 (defun js2-visit-with-node (n v)
2755 (js2-visit-ast (js2-with-node-object n) v)
2756 (js2-visit-ast (js2-with-node-body n) v))
2757
2758 (defun js2-print-with-node (n i)
2759 (let ((pad (js2-make-pad i)))
2760 (insert pad "with (")
2761 (js2-print-ast (js2-with-node-object n) 0)
2762 (insert ") {\n")
2763 (js2-print-body (js2-with-node-body n) (1+ i))
2764 (insert pad "}\n")))
2765
2766 (defstruct (js2-label-node
2767 (:include js2-node)
2768 (:constructor nil)
2769 (:constructor make-js2-label-node (&key (type js2-LABEL)
2770 (pos js2-ts-cursor)
2771 len name)))
2772 "AST node for a statement label or case label."
2773 name ; a string
2774 loop) ; for validating and code-generating continue-to-label
2775
2776 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2777 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2778
2779 (defun js2-print-label (n i)
2780 (insert (js2-make-pad i)
2781 (js2-label-node-name n)
2782 ":\n"))
2783
2784 (defstruct (js2-labeled-stmt-node
2785 (:include js2-node)
2786 (:constructor nil)
2787 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2788 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2789 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2790 (pos js2-ts-cursor)
2791 len labels stmt)))
2792 "AST node for a statement with one or more labels.
2793 Multiple labels for a statement are collapsed into the labels field."
2794 labels ; Lisp list of `js2-label-node'
2795 stmt) ; the statement these labels are for
2796
2797 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2798 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2799
2800 (defun js2-get-label-by-name (lbl-stmt name)
2801 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2802 Returns nil if no such label is in the list."
2803 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2804 result)
2805 (while (and label-list (not result))
2806 (if (string= (js2-label-node-name (car label-list)) name)
2807 (setq result (car label-list))
2808 (setq label-list (cdr label-list))))
2809 result))
2810
2811 (defun js2-visit-labeled-stmt (n v)
2812 (dolist (label (js2-labeled-stmt-node-labels n))
2813 (js2-visit-ast label v))
2814 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2815
2816 (defun js2-print-labeled-stmt (n i)
2817 (dolist (label (js2-labeled-stmt-node-labels n))
2818 (js2-print-ast label i))
2819 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2820
2821 (defun js2-labeled-stmt-node-contains (node label)
2822 "Return t if NODE contains LABEL in its label set.
2823 NODE is a `js2-labels-node'. LABEL is an identifier."
2824 (loop for nl in (js2-labeled-stmt-node-labels node)
2825 if (string= label (js2-label-node-name nl))
2826 return t
2827 finally return nil))
2828
2829 (defsubst js2-labeled-stmt-node-add-label (node label)
2830 "Add a `js2-label-node' to the label set for this statement."
2831 (setf (js2-labeled-stmt-node-labels node)
2832 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2833
2834 (defstruct (js2-jump-node
2835 (:include js2-node)
2836 (:constructor nil))
2837 "Abstract supertype of break and continue nodes."
2838 label ; `js2-name-node' for location of label identifier, if present
2839 target) ; target js2-labels-node or loop/switch statement
2840
2841 (defun js2-visit-jump-node (n v)
2842 ;; We don't visit the target, since it's a back-link.
2843 (js2-visit-ast (js2-jump-node-label n) v))
2844
2845 (defstruct (js2-break-node
2846 (:include js2-jump-node)
2847 (:constructor nil)
2848 (:constructor make-js2-break-node (&key (type js2-BREAK)
2849 (pos js2-ts-cursor)
2850 len label target)))
2851 "AST node for a break statement.
2852 The label field is a `js2-name-node', possibly nil, for the named label
2853 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2854 is the target of the break - a label node or enclosing loop/switch statement.")
2855
2856 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2857 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2858
2859 (defun js2-print-break-node (n i)
2860 (insert (js2-make-pad i) "break")
2861 (when (js2-break-node-label n)
2862 (insert " ")
2863 (js2-print-ast (js2-break-node-label n) 0))
2864 (insert ";\n"))
2865
2866 (defstruct (js2-continue-node
2867 (:include js2-jump-node)
2868 (:constructor nil)
2869 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2870 (pos js2-ts-cursor)
2871 len label target)))
2872 "AST node for a continue statement.
2873 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2874 It is nil if continue specifies no label. The target field is the jump target:
2875 a `js2-label-node' or the innermost enclosing loop.")
2876
2877 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2878 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2879
2880 (defun js2-print-continue-node (n i)
2881 (insert (js2-make-pad i) "continue")
2882 (when (js2-continue-node-label n)
2883 (insert " ")
2884 (js2-print-ast (js2-continue-node-label n) 0))
2885 (insert ";\n"))
2886
2887 (defstruct (js2-function-node
2888 (:include js2-script-node)
2889 (:constructor nil)
2890 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2891 (pos js2-ts-cursor)
2892 len
2893 (ftype 'FUNCTION)
2894 (form 'FUNCTION_STATEMENT)
2895 (name "")
2896 params rest-p
2897 body
2898 lp rp)))
2899 "AST node for a function declaration.
2900 The `params' field is a Lisp list of nodes. Each node is either a simple
2901 `js2-name-node', or if it's a destructuring-assignment parameter, a
2902 `js2-array-node' or `js2-object-node'."
2903 ftype ; FUNCTION, GETTER or SETTER
2904 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
2905 name ; function name (a `js2-name-node', or nil if anonymous)
2906 params ; a Lisp list of destructuring forms or simple name nodes
2907 rest-p ; if t, the last parameter is rest parameter
2908 body ; a `js2-block-node' or expression node (1.8 only)
2909 lp ; position of arg-list open-paren, or nil if omitted
2910 rp ; position of arg-list close-paren, or nil if omitted
2911 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2912 needs-activation ; t if we need an activation object for this frame
2913 is-generator ; t if this function contains a yield
2914 member-expr) ; nonstandard Ecma extension from Rhino
2915
2916 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2917 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2918
2919 (defun js2-visit-function-node (n v)
2920 (js2-visit-ast (js2-function-node-name n) v)
2921 (dolist (p (js2-function-node-params n))
2922 (js2-visit-ast p v))
2923 (js2-visit-ast (js2-function-node-body n) v))
2924
2925 (defun js2-print-function-node (n i)
2926 (let ((pad (js2-make-pad i))
2927 (getter (js2-node-get-prop n 'GETTER_SETTER))
2928 (name (js2-function-node-name n))
2929 (params (js2-function-node-params n))
2930 (rest-p (js2-function-node-rest-p n))
2931 (body (js2-function-node-body n))
2932 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
2933 (unless getter
2934 (insert pad "function"))
2935 (when name
2936 (insert " ")
2937 (js2-print-ast name 0))
2938 (insert "(")
2939 (loop with len = (length params)
2940 for param in params
2941 for count from 1
2942 do
2943 (when (and rest-p (= count len))
2944 (insert "..."))
2945 (js2-print-ast param 0)
2946 (when (< count len)
2947 (insert ", ")))
2948 (insert ") {")
2949 (unless expr
2950 (insert "\n"))
2951 ;; TODO: fix this to be smarter about indenting, etc.
2952 (js2-print-body body (1+ i))
2953 (insert pad "}")
2954 (unless expr
2955 (insert "\n"))))
2956
2957 (defun js2-function-name (node)
2958 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
2959 (and (js2-function-node-name node)
2960 (js2-name-node-name (js2-function-node-name node))))
2961
2962 ;; Having this be an expression node makes it more flexible.
2963 ;; There are IDE contexts, such as indentation in a for-loop initializer,
2964 ;; that work better if you assume it's an expression. Whenever we have
2965 ;; a standalone var/const declaration, we just wrap with an expr stmt.
2966 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
2967 (defstruct (js2-var-decl-node
2968 (:include js2-node)
2969 (:constructor nil)
2970 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
2971 (pos js2-token-beg)
2972 len kids
2973 decl-type)))
2974 "AST node for a variable declaration list (VAR, CONST or LET).
2975 The node bounds differ depending on the declaration type. For VAR or
2976 CONST declarations, the bounds include the var/const keyword. For LET
2977 declarations, the node begins at the position of the first child."
2978 kids ; a Lisp list of `js2-var-init-node' structs.
2979 decl-type) ; js2-VAR, js2-CONST or js2-LET
2980
2981 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
2982 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
2983
2984 (defun js2-visit-var-decl (n v)
2985 (dolist (kid (js2-var-decl-node-kids n))
2986 (js2-visit-ast kid v)))
2987
2988 (defun js2-print-var-decl (n i)
2989 (let ((pad (js2-make-pad i))
2990 (tt (js2-var-decl-node-decl-type n)))
2991 (insert pad)
2992 (insert (cond
2993 ((= tt js2-VAR) "var ")
2994 ((= tt js2-LET) "let ")
2995 ((= tt js2-CONST) "const ")
2996 (t
2997 (error "malformed var-decl node"))))
2998 (loop with kids = (js2-var-decl-node-kids n)
2999 with len = (length kids)
3000 for kid in kids
3001 for count from 1
3002 do
3003 (js2-print-ast kid 0)
3004 (if (< count len)
3005 (insert ", ")))))
3006
3007 (defstruct (js2-var-init-node
3008 (:include js2-node)
3009 (:constructor nil)
3010 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3011 (pos js2-ts-cursor)
3012 len target
3013 initializer)))
3014 "AST node for a variable declaration.
3015 The type field will be js2-CONST for a const decl."
3016 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3017 initializer) ; initializer expression, a `js2-node'
3018
3019 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3020 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3021
3022 (defun js2-visit-var-init-node (n v)
3023 (js2-visit-ast (js2-var-init-node-target n) v)
3024 (js2-visit-ast (js2-var-init-node-initializer n) v))
3025
3026 (defun js2-print-var-init-node (n i)
3027 (let ((pad (js2-make-pad i))
3028 (name (js2-var-init-node-target n))
3029 (init (js2-var-init-node-initializer n)))
3030 (insert pad)
3031 (js2-print-ast name 0)
3032 (when init
3033 (insert " = ")
3034 (js2-print-ast init 0))))
3035
3036 (defstruct (js2-cond-node
3037 (:include js2-node)
3038 (:constructor nil)
3039 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3040 (pos js2-ts-cursor)
3041 len
3042 test-expr
3043 true-expr
3044 false-expr
3045 q-pos c-pos)))
3046 "AST node for the ternary operator"
3047 test-expr
3048 true-expr
3049 false-expr
3050 q-pos ; buffer position of ?
3051 c-pos) ; buffer position of :
3052
3053 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3054 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3055
3056 (defun js2-visit-cond-node (n v)
3057 (js2-visit-ast (js2-cond-node-test-expr n) v)
3058 (js2-visit-ast (js2-cond-node-true-expr n) v)
3059 (js2-visit-ast (js2-cond-node-false-expr n) v))
3060
3061 (defun js2-print-cond-node (n i)
3062 (let ((pad (js2-make-pad i)))
3063 (insert pad)
3064 (js2-print-ast (js2-cond-node-test-expr n) 0)
3065 (insert " ? ")
3066 (js2-print-ast (js2-cond-node-true-expr n) 0)
3067 (insert " : ")
3068 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3069
3070 (defstruct (js2-infix-node
3071 (:include js2-node)
3072 (:constructor nil)
3073 (:constructor make-js2-infix-node (&key type
3074 (pos js2-ts-cursor)
3075 len op-pos
3076 left right)))
3077 "Represents infix expressions.
3078 Includes assignment ops like `|=', and the comma operator.
3079 The type field inherited from `js2-node' holds the operator."
3080 op-pos ; buffer position where operator begins
3081 left ; any `js2-node'
3082 right) ; any `js2-node'
3083
3084 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3085 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3086
3087 (defun js2-visit-infix-node (n v)
3088 (js2-visit-ast (js2-infix-node-left n) v)
3089 (js2-visit-ast (js2-infix-node-right n) v))
3090
3091 (defconst js2-operator-tokens
3092 (let ((table (make-hash-table :test 'eq))
3093 (tokens
3094 (list (cons js2-IN "in")
3095 (cons js2-TYPEOF "typeof")
3096 (cons js2-INSTANCEOF "instanceof")
3097 (cons js2-DELPROP "delete")
3098 (cons js2-COMMA ",")
3099 (cons js2-COLON ":")
3100 (cons js2-OR "||")
3101 (cons js2-AND "&&")
3102 (cons js2-INC "++")
3103 (cons js2-DEC "--")
3104 (cons js2-BITOR "|")
3105 (cons js2-BITXOR "^")
3106 (cons js2-BITAND "&")
3107 (cons js2-EQ "==")
3108 (cons js2-NE "!=")
3109 (cons js2-LT "<")
3110 (cons js2-LE "<=")
3111 (cons js2-GT ">")
3112 (cons js2-GE ">=")
3113 (cons js2-LSH "<<")
3114 (cons js2-RSH ">>")
3115 (cons js2-URSH ">>>")
3116 (cons js2-ADD "+") ; infix plus
3117 (cons js2-SUB "-") ; infix minus
3118 (cons js2-MUL "*")
3119 (cons js2-DIV "/")
3120 (cons js2-MOD "%")
3121 (cons js2-NOT "!")
3122 (cons js2-BITNOT "~")
3123 (cons js2-POS "+") ; unary plus
3124 (cons js2-NEG "-") ; unary minus
3125 (cons js2-SHEQ "===") ; shallow equality
3126 (cons js2-SHNE "!==") ; shallow inequality
3127 (cons js2-ASSIGN "=")
3128 (cons js2-ASSIGN_BITOR "|=")
3129 (cons js2-ASSIGN_BITXOR "^=")
3130 (cons js2-ASSIGN_BITAND "&=")
3131 (cons js2-ASSIGN_LSH "<<=")
3132 (cons js2-ASSIGN_RSH ">>=")
3133 (cons js2-ASSIGN_URSH ">>>=")
3134 (cons js2-ASSIGN_ADD "+=")
3135 (cons js2-ASSIGN_SUB "-=")
3136 (cons js2-ASSIGN_MUL "*=")
3137 (cons js2-ASSIGN_DIV "/=")
3138 (cons js2-ASSIGN_MOD "%="))))
3139 (loop for (k . v) in tokens do
3140 (puthash k v table))
3141 table))
3142
3143 (defun js2-print-infix-node (n i)
3144 (let* ((tt (js2-node-type n))
3145 (op (gethash tt js2-operator-tokens)))
3146 (unless op
3147 (error "unrecognized infix operator %s" (js2-node-type n)))
3148 (insert (js2-make-pad i))
3149 (js2-print-ast (js2-infix-node-left n) 0)
3150 (unless (= tt js2-COMMA)
3151 (insert " "))
3152 (insert op)
3153 (insert " ")
3154 (js2-print-ast (js2-infix-node-right n) 0)))
3155
3156 (defstruct (js2-assign-node
3157 (:include js2-infix-node)
3158 (:constructor nil)
3159 (:constructor make-js2-assign-node (&key type
3160 (pos js2-ts-cursor)
3161 len op-pos
3162 left right)))
3163 "Represents any assignment.
3164 The type field holds the actual assignment operator.")
3165
3166 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3167 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3168
3169 (defstruct (js2-unary-node
3170 (:include js2-node)
3171 (:constructor nil)
3172 (:constructor make-js2-unary-node (&key type ; required
3173 (pos js2-ts-cursor)
3174 len operand)))
3175 "AST node type for unary operator nodes.
3176 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3177 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3178 property is added if the operator follows the operand."
3179 operand) ; a `js2-node' expression
3180
3181 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3182 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3183
3184 (defun js2-visit-unary-node (n v)
3185 (js2-visit-ast (js2-unary-node-operand n) v))
3186
3187 (defun js2-print-unary-node (n i)
3188 (let* ((tt (js2-node-type n))
3189 (op (gethash tt js2-operator-tokens))
3190 (postfix (js2-node-get-prop n 'postfix)))
3191 (unless op
3192 (error "unrecognized unary operator %s" tt))
3193 (insert (js2-make-pad i))
3194 (unless postfix
3195 (insert op))
3196 (if (or (= tt js2-TYPEOF)
3197 (= tt js2-DELPROP))
3198 (insert " "))
3199 (js2-print-ast (js2-unary-node-operand n) 0)
3200 (when postfix
3201 (insert op))))
3202
3203 (defstruct (js2-let-node
3204 (:include js2-scope)
3205 (:constructor nil)
3206 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3207 (pos js2-token-beg)
3208 len vars body
3209 lp rp)))
3210 "AST node for a let expression or a let statement.
3211 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3212 vars ; a `js2-var-decl-node'
3213 body ; a `js2-node' representing the expression or body block
3214 lp
3215 rp)
3216
3217 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3218 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3219
3220 (defun js2-visit-let-node (n v)
3221 (js2-visit-ast (js2-let-node-vars n) v)
3222 (js2-visit-ast (js2-let-node-body n) v))
3223
3224 (defun js2-print-let-node (n i)
3225 (insert (js2-make-pad i) "let (")
3226 (js2-print-ast (js2-let-node-vars n) 0)
3227 (insert ") ")
3228 (js2-print-ast (js2-let-node-body n) i))
3229
3230 (defstruct (js2-keyword-node
3231 (:include js2-node)
3232 (:constructor nil)
3233 (:constructor make-js2-keyword-node (&key type
3234 (pos js2-token-beg)
3235 (len (- js2-ts-cursor pos)))))
3236 "AST node representing a literal keyword such as `null'.
3237 Used for `null', `this', `true', `false' and `debugger'.
3238 The node type is set to js2-NULL, js2-THIS, etc.")
3239
3240 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3241 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3242
3243 (defun js2-print-keyword-node (n i)
3244 (insert (js2-make-pad i)
3245 (let ((tt (js2-node-type n)))
3246 (cond
3247 ((= tt js2-THIS) "this")
3248 ((= tt js2-NULL) "null")
3249 ((= tt js2-TRUE) "true")
3250 ((= tt js2-FALSE) "false")
3251 ((= tt js2-DEBUGGER) "debugger")
3252 (t (error "Invalid keyword literal type: %d" tt))))))
3253
3254 (defsubst js2-this-node-p (node)
3255 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3256 (eq (js2-node-type node) js2-THIS))
3257
3258 (defstruct (js2-new-node
3259 (:include js2-node)
3260 (:constructor nil)
3261 (:constructor make-js2-new-node (&key (type js2-NEW)
3262 (pos js2-token-beg)
3263 len target
3264 args initializer
3265 lp rp)))
3266 "AST node for new-expression such as new Foo()."
3267 target ; an identifier or reference
3268 args ; a Lisp list of argument nodes
3269 lp ; position of left-paren, nil if omitted
3270 rp ; position of right-paren, nil if omitted
3271 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3272
3273 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3274 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3275
3276 (defun js2-visit-new-node (n v)
3277 (js2-visit-ast (js2-new-node-target n) v)
3278 (dolist (arg (js2-new-node-args n))
3279 (js2-visit-ast arg v))
3280 (js2-visit-ast (js2-new-node-initializer n) v))
3281
3282 (defun js2-print-new-node (n i)
3283 (insert (js2-make-pad i) "new ")
3284 (js2-print-ast (js2-new-node-target n))
3285 (insert "(")
3286 (js2-print-list (js2-new-node-args n))
3287 (insert ")")
3288 (when (js2-new-node-initializer n)
3289 (insert " ")
3290 (js2-print-ast (js2-new-node-initializer n))))
3291
3292 (defstruct (js2-name-node
3293 (:include js2-node)
3294 (:constructor nil)
3295 (:constructor make-js2-name-node (&key (type js2-NAME)
3296 (pos js2-token-beg)
3297 (len (- js2-ts-cursor
3298 js2-token-beg))
3299 (name js2-ts-string))))
3300 "AST node for a JavaScript identifier"
3301 name ; a string
3302 scope) ; a `js2-scope' (optional, used for codegen)
3303
3304 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3305 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3306
3307 (defun js2-print-name-node (n i)
3308 (insert (js2-make-pad i)
3309 (js2-name-node-name n)))
3310
3311 (defsubst js2-name-node-length (node)
3312 "Return identifier length of NODE, a `js2-name-node'.
3313 Returns 0 if NODE is nil or its identifier field is nil."
3314 (if node
3315 (length (js2-name-node-name node))
3316 0))
3317
3318 (defstruct (js2-number-node
3319 (:include js2-node)
3320 (:constructor nil)
3321 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3322 (pos js2-token-beg)
3323 (len (- js2-ts-cursor
3324 js2-token-beg))
3325 (value js2-ts-string)
3326 (num-value js2-ts-number))))
3327 "AST node for a number literal."
3328 value ; the original string, e.g. "6.02e23"
3329 num-value) ; the parsed number value
3330
3331 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3332 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3333
3334 (defun js2-print-number-node (n i)
3335 (insert (js2-make-pad i)
3336 (number-to-string (js2-number-node-num-value n))))
3337
3338 (defstruct (js2-regexp-node
3339 (:include js2-node)
3340 (:constructor nil)
3341 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3342 (pos js2-token-beg)
3343 (len (- js2-ts-cursor
3344 js2-token-beg))
3345 value flags)))
3346 "AST node for a regular expression literal."
3347 value ; the regexp string, without // delimiters
3348 flags) ; a string of flags, e.g. `mi'.
3349
3350 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3351 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3352
3353 (defun js2-print-regexp (n i)
3354 (insert (js2-make-pad i)
3355 "/"
3356 (js2-regexp-node-value n)
3357 "/")
3358 (if (js2-regexp-node-flags n)
3359 (insert (js2-regexp-node-flags n))))
3360
3361 (defstruct (js2-string-node
3362 (:include js2-node)
3363 (:constructor nil)
3364 (:constructor make-js2-string-node (&key (type js2-STRING)
3365 (pos js2-token-beg)
3366 (len (- js2-ts-cursor
3367 js2-token-beg))
3368 (value js2-ts-string))))
3369 "String literal.
3370 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3371 You can tell the quote type by looking at the first character."
3372 value) ; the characters of the string, including the quotes
3373
3374 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3375 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3376
3377 (defun js2-print-string-node (n i)
3378 (insert (js2-make-pad i)
3379 (js2-node-string n)))
3380
3381 (defstruct (js2-array-node
3382 (:include js2-node)
3383 (:constructor nil)
3384 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3385 (pos js2-ts-cursor)
3386 len elems)))
3387 "AST node for an array literal."
3388 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3389
3390 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3391 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3392
3393 (defun js2-visit-array-node (n v)
3394 (dolist (e (js2-array-node-elems n))
3395 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3396
3397 (defun js2-print-array-node (n i)
3398 (insert (js2-make-pad i) "[")
3399 (js2-print-list (js2-array-node-elems n))
3400 (insert "]"))
3401
3402 (defstruct (js2-object-node
3403 (:include js2-node)
3404 (:constructor nil)
3405 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3406 (pos js2-ts-cursor)
3407 len
3408 elems)))
3409 "AST node for an object literal expression.
3410 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3411 The latter represents abbreviation in destructuring expressions."
3412 elems)
3413
3414 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3415 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3416
3417 (defun js2-visit-object-node (n v)
3418 (dolist (e (js2-object-node-elems n))
3419 (js2-visit-ast e v)))
3420
3421 (defun js2-print-object-node (n i)
3422 (insert (js2-make-pad i) "{")
3423 (js2-print-list (js2-object-node-elems n))
3424 (insert "}"))
3425
3426 (defstruct (js2-object-prop-node
3427 (:include js2-infix-node)
3428 (:constructor nil)
3429 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3430 (pos js2-ts-cursor)
3431 len left
3432 right op-pos)))
3433 "AST node for an object literal prop:value entry.
3434 The `left' field is the property: a name node, string node or number node.
3435 The `right' field is a `js2-node' representing the initializer value.")
3436
3437 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3438 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3439
3440 (defun js2-print-object-prop-node (n i)
3441 (insert (js2-make-pad i))
3442 (js2-print-ast (js2-object-prop-node-left n) 0)
3443 (insert ": ")
3444 (js2-print-ast (js2-object-prop-node-right n) 0))
3445
3446 (defstruct (js2-getter-setter-node
3447 (:include js2-infix-node)
3448 (:constructor nil)
3449 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3450 (pos js2-ts-cursor)
3451 len left right)))
3452 "AST node for a getter/setter property in an object literal.
3453 The `left' field is the `js2-name-node' naming the getter/setter prop.
3454 The `right' field is always an anonymous `js2-function-node' with a node
3455 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3456
3457 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3458 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3459
3460 (defun js2-print-getter-setter (n i)
3461 (let ((pad (js2-make-pad i))
3462 (left (js2-getter-setter-node-left n))
3463 (right (js2-getter-setter-node-right n)))
3464 (insert pad)
3465 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3466 (js2-print-ast left 0)
3467 (js2-print-ast right 0)))
3468
3469 (defstruct (js2-prop-get-node
3470 (:include js2-infix-node)
3471 (:constructor nil)
3472 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3473 (pos js2-ts-cursor)
3474 len left right)))
3475 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3476
3477 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3478 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3479
3480 (defun js2-visit-prop-get-node (n v)
3481 (js2-visit-ast (js2-prop-get-node-left n) v)
3482 (js2-visit-ast (js2-prop-get-node-right n) v))
3483
3484 (defun js2-print-prop-get-node (n i)
3485 (insert (js2-make-pad i))
3486 (js2-print-ast (js2-prop-get-node-left n) 0)
3487 (insert ".")
3488 (js2-print-ast (js2-prop-get-node-right n) 0))
3489
3490 (defstruct (js2-elem-get-node
3491 (:include js2-node)
3492 (:constructor nil)
3493 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3494 (pos js2-ts-cursor)
3495 len target element
3496 lb rb)))
3497 "AST node for an array index expression such as foo[bar]."
3498 target ; a `js2-node' - the expression preceding the "."
3499 element ; a `js2-node' - the expression in brackets
3500 lb ; position of left-bracket, nil if omitted
3501 rb) ; position of right-bracket, nil if omitted
3502
3503 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3504 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3505
3506 (defun js2-visit-elem-get-node (n v)
3507 (js2-visit-ast (js2-elem-get-node-target n) v)
3508 (js2-visit-ast (js2-elem-get-node-element n) v))
3509
3510 (defun js2-print-elem-get-node (n i)
3511 (insert (js2-make-pad i))
3512 (js2-print-ast (js2-elem-get-node-target n) 0)
3513 (insert "[")
3514 (js2-print-ast (js2-elem-get-node-element n) 0)
3515 (insert "]"))
3516
3517 (defstruct (js2-call-node
3518 (:include js2-node)
3519 (:constructor nil)
3520 (:constructor make-js2-call-node (&key (type js2-CALL)
3521 (pos js2-ts-cursor)
3522 len target args
3523 lp rp)))
3524 "AST node for a JavaScript function call."
3525 target ; a `js2-node' evaluating to the function to call
3526 args ; a Lisp list of `js2-node' arguments
3527 lp ; position of open-paren, or nil if missing
3528 rp) ; position of close-paren, or nil if missing
3529
3530 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3531 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3532
3533 (defun js2-visit-call-node (n v)
3534 (js2-visit-ast (js2-call-node-target n) v)
3535 (dolist (arg (js2-call-node-args n))
3536 (js2-visit-ast arg v)))
3537
3538 (defun js2-print-call-node (n i)
3539 (insert (js2-make-pad i))
3540 (js2-print-ast (js2-call-node-target n) 0)
3541 (insert "(")
3542 (js2-print-list (js2-call-node-args n))
3543 (insert ")"))
3544
3545 (defstruct (js2-yield-node
3546 (:include js2-node)
3547 (:constructor nil)
3548 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3549 (pos js2-ts-cursor)
3550 len value)))
3551 "AST node for yield statement or expression."
3552 value) ; optional: value to be yielded
3553
3554 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3555 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3556
3557 (defun js2-visit-yield-node (n v)
3558 (js2-visit-ast (js2-yield-node-value n) v))
3559
3560 (defun js2-print-yield-node (n i)
3561 (insert (js2-make-pad i))
3562 (insert "yield")
3563 (when (js2-yield-node-value n)
3564 (insert " ")
3565 (js2-print-ast (js2-yield-node-value n) 0)))
3566
3567 (defstruct (js2-paren-node
3568 (:include js2-node)
3569 (:constructor nil)
3570 (:constructor make-js2-paren-node (&key (type js2-LP)
3571 (pos js2-ts-cursor)
3572 len expr)))
3573 "AST node for a parenthesized expression.
3574 In particular, used when the parens are syntactically optional,
3575 as opposed to required parens such as those enclosing an if-conditional."
3576 expr) ; `js2-node'
3577
3578 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3579 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3580
3581 (defun js2-visit-paren-node (n v)
3582 (js2-visit-ast (js2-paren-node-expr n) v))
3583
3584 (defun js2-print-paren-node (n i)
3585 (insert (js2-make-pad i))
3586 (insert "(")
3587 (js2-print-ast (js2-paren-node-expr n) 0)
3588 (insert ")"))
3589
3590 (defstruct (js2-array-comp-node
3591 (:include js2-scope)
3592 (:constructor nil)
3593 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3594 (pos js2-ts-cursor)
3595 len result
3596 loops filter
3597 if-pos lp rp)))
3598 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3599 result ; result expression (just after left-bracket)
3600 loops ; a Lisp list of `js2-array-comp-loop-node'
3601 filter ; guard/filter expression
3602 if-pos ; buffer pos of 'if' keyword, if present, else nil
3603 lp ; buffer position of if-guard left-paren, or nil if not present
3604 rp) ; buffer position of if-guard right-paren, or nil if not present
3605
3606 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3607 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3608
3609 (defun js2-visit-array-comp-node (n v)
3610 (js2-visit-ast (js2-array-comp-node-result n) v)
3611 (dolist (l (js2-array-comp-node-loops n))
3612 (js2-visit-ast l v))
3613 (js2-visit-ast (js2-array-comp-node-filter n) v))
3614
3615 (defun js2-print-array-comp-node (n i)
3616 (let ((pad (js2-make-pad i))
3617 (result (js2-array-comp-node-result n))
3618 (loops (js2-array-comp-node-loops n))
3619 (filter (js2-array-comp-node-filter n)))
3620 (insert pad "[")
3621 (js2-print-ast result 0)
3622 (dolist (l loops)
3623 (insert " ")
3624 (js2-print-ast l 0))
3625 (when filter
3626 (insert " if (")
3627 (js2-print-ast filter 0)
3628 (insert ")"))
3629 (insert "]")))
3630
3631 (defstruct (js2-array-comp-loop-node
3632 (:include js2-for-in-node)
3633 (:constructor nil)
3634 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3635 (pos js2-ts-cursor)
3636 len iterator
3637 object in-pos
3638 foreach-p
3639 each-pos
3640 forof-p
3641 lp rp)))
3642 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3643
3644 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3645 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3646
3647 (defun js2-visit-array-comp-loop (n v)
3648 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3649 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3650
3651 (defun js2-print-array-comp-loop (n i)
3652 (insert "for ")
3653 (when (js2-array-comp-loop-node-foreach-p n) (insert "each "))
3654 (insert "(")
3655 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3656 (if (js2-array-comp-loop-node-forof-p n)
3657 (insert " of ")
3658 (insert " in "))
3659 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3660 (insert ")"))
3661
3662 (defstruct (js2-empty-expr-node
3663 (:include js2-node)
3664 (:constructor nil)
3665 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3666 (pos js2-token-beg)
3667 len)))
3668 "AST node for an empty expression.")
3669
3670 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3671 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3672
3673 (defstruct (js2-xml-node
3674 (:include js2-block-node)
3675 (:constructor nil)
3676 (:constructor make-js2-xml-node (&key (type js2-XML)
3677 (pos js2-token-beg)
3678 len kids)))
3679 "AST node for initial parse of E4X literals.
3680 The kids field is a list of XML fragments, each a `js2-string-node' or
3681 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3682
3683 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3684 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3685
3686 (defun js2-print-xml-node (n i)
3687 (dolist (kid (js2-xml-node-kids n))
3688 (js2-print-ast kid i)))
3689
3690 (defstruct (js2-xml-js-expr-node
3691 (:include js2-xml-node)
3692 (:constructor nil)
3693 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3694 (pos js2-ts-cursor)
3695 len expr)))
3696 "AST node for an embedded JavaScript {expression} in an E4X literal.
3697 The start and end fields correspond to the curly-braces."
3698 expr) ; a `js2-expr-node' of some sort
3699
3700 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3701 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3702
3703 (defun js2-visit-xml-js-expr (n v)
3704 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3705
3706 (defun js2-print-xml-js-expr (n i)
3707 (insert (js2-make-pad i))
3708 (insert "{")
3709 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3710 (insert "}"))
3711
3712 (defstruct (js2-xml-dot-query-node
3713 (:include js2-infix-node)
3714 (:constructor nil)
3715 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3716 (pos js2-ts-cursor)
3717 op-pos len left
3718 right rp)))
3719 "AST node for an E4X foo.(bar) filter expression.
3720 Note that the left-paren is automatically the character immediately
3721 following the dot (.) in the operator. No whitespace is permitted
3722 between the dot and the lp by the scanner."
3723 rp)
3724
3725 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3726 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3727
3728 (defun js2-print-xml-dot-query (n i)
3729 (insert (js2-make-pad i))
3730 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3731 (insert ".(")
3732 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3733 (insert ")"))
3734
3735 (defstruct (js2-xml-ref-node
3736 (:include js2-node)
3737 (:constructor nil)) ; abstract
3738 "Base type for E4X XML attribute-access or property-get expressions.
3739 Such expressions can take a variety of forms. The general syntax has
3740 three parts:
3741
3742 - (optional) an @ (specifying an attribute access)
3743 - (optional) a namespace (a `js2-name-node') and double-colon
3744 - (required) either a `js2-name-node' or a bracketed [expression]
3745
3746 The property-name expressions (examples: ns::name, @name) are
3747 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3748 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3749
3750 This node type (or more specifically, its subclasses) will sometimes
3751 be the right-hand child of a `js2-prop-get-node' or a
3752 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3753 The `js2-xml-ref-node' may also be a standalone primary expression with
3754 no explicit target, which is valid in certain expression contexts such as
3755
3756 company..employee.(@id < 100)
3757
3758 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3759 expression whose parent is a `js2-xml-dot-query-node'."
3760 namespace
3761 at-pos
3762 colon-pos)
3763
3764 (defsubst js2-xml-ref-node-attr-access-p (node)
3765 "Return non-nil if this expression began with an @-token."
3766 (and (numberp (js2-xml-ref-node-at-pos node))
3767 (plusp (js2-xml-ref-node-at-pos node))))
3768
3769 (defstruct (js2-xml-prop-ref-node
3770 (:include js2-xml-ref-node)
3771 (:constructor nil)
3772 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3773 (pos js2-token-beg)
3774 len propname
3775 namespace at-pos
3776 colon-pos)))
3777 "AST node for an E4X XML [expr] property-ref expression.
3778 The JavaScript syntax is an optional @, an optional ns::, and a name.
3779
3780 [ '@' ] [ name '::' ] name
3781
3782 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3783 @ns::*, @*::attr, @*::*, and @*.
3784
3785 The node starts at the @ token, if present. Otherwise it starts at the
3786 namespace name. The node bounds extend through the closing right-bracket,
3787 or if it is missing due to a syntax error, through the end of the index
3788 expression."
3789 propname)
3790
3791 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3792 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3793
3794 (defun js2-visit-xml-prop-ref-node (n v)
3795 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3796 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3797
3798 (defun js2-print-xml-prop-ref-node (n i)
3799 (insert (js2-make-pad i))
3800 (if (js2-xml-ref-node-attr-access-p n)
3801 (insert "@"))
3802 (when (js2-xml-prop-ref-node-namespace n)
3803 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3804 (insert "::"))
3805 (if (js2-xml-prop-ref-node-propname n)
3806 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3807
3808 (defstruct (js2-xml-elem-ref-node
3809 (:include js2-xml-ref-node)
3810 (:constructor nil)
3811 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3812 (pos js2-token-beg)
3813 len expr lb rb
3814 namespace at-pos
3815 colon-pos)))
3816 "AST node for an E4X XML [expr] member-ref expression.
3817 Syntax:
3818
3819 [ '@' ] [ name '::' ] '[' expr ']'
3820
3821 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3822
3823 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3824 is not a legal E4X XML element-ref expression, since it's already used
3825 for standard JavaScript element-get array indexing. Hence, a
3826 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3827 non-nil namespace node, or both.
3828
3829 The node starts at the @ token, if present. Otherwise it starts
3830 at the namespace name. The node bounds extend through the closing
3831 right-bracket, or if it is missing due to a syntax error, through the
3832 end of the index expression."
3833 expr ; the bracketed index expression
3834 lb
3835 rb)
3836
3837 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3838 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3839
3840 (defun js2-visit-xml-elem-ref-node (n v)
3841 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3842 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3843
3844 (defun js2-print-xml-elem-ref-node (n i)
3845 (insert (js2-make-pad i))
3846 (if (js2-xml-ref-node-attr-access-p n)
3847 (insert "@"))
3848 (when (js2-xml-elem-ref-node-namespace n)
3849 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3850 (insert "::"))
3851 (insert "[")
3852 (if (js2-xml-elem-ref-node-expr n)
3853 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3854 (insert "]"))
3855
3856 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3857
3858 (defstruct (js2-xml-start-tag-node
3859 (:include js2-xml-node)
3860 (:constructor nil)
3861 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3862 (pos js2-ts-cursor)
3863 len name attrs kids
3864 empty-p)))
3865 "AST node for an XML start-tag. Not currently used.
3866 The `kids' field is a Lisp list of child content nodes."
3867 name ; a `js2-xml-name-node'
3868 attrs ; a Lisp list of `js2-xml-attr-node'
3869 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3870
3871 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3872 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3873
3874 (defun js2-visit-xml-start-tag (n v)
3875 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3876 (dolist (attr (js2-xml-start-tag-node-attrs n))
3877 (js2-visit-ast attr v))
3878 (js2-visit-block n v))
3879
3880 (defun js2-print-xml-start-tag (n i)
3881 (insert (js2-make-pad i) "<")
3882 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3883 (when (js2-xml-start-tag-node-attrs n)
3884 (insert " ")
3885 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3886 (insert ">"))
3887
3888 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3889 ;; and add the end-tag to the kids list of the parent as well.
3890 (defstruct (js2-xml-end-tag-node
3891 (:include js2-xml-node)
3892 (:constructor nil)
3893 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
3894 (pos js2-ts-cursor)
3895 len name)))
3896 "AST node for an XML end-tag. Not currently used."
3897 name) ; a `js2-xml-name-node'
3898
3899 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
3900 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
3901
3902 (defun js2-visit-xml-end-tag (n v)
3903 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
3904
3905 (defun js2-print-xml-end-tag (n i)
3906 (insert (js2-make-pad i))
3907 (insert "</")
3908 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
3909 (insert ">"))
3910
3911 (defstruct (js2-xml-name-node
3912 (:include js2-xml-node)
3913 (:constructor nil)
3914 (:constructor make-js2-xml-name-node (&key (type js2-XML)
3915 (pos js2-ts-cursor)
3916 len namespace kids)))
3917 "AST node for an E4X XML name. Not currently used.
3918 Any XML name can be qualified with a namespace, hence the namespace field.
3919 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
3920 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
3921 For a simple name, the kids list has exactly one node, a `js2-name-node'."
3922 namespace) ; a `js2-string-node'
3923
3924 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
3925 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
3926
3927 (defun js2-visit-xml-name-node (n v)
3928 (js2-visit-ast (js2-xml-name-node-namespace n) v))
3929
3930 (defun js2-print-xml-name-node (n i)
3931 (insert (js2-make-pad i))
3932 (when (js2-xml-name-node-namespace n)
3933 (js2-print-ast (js2-xml-name-node-namespace n) 0)
3934 (insert "::"))
3935 (dolist (kid (js2-xml-name-node-kids n))
3936 (js2-print-ast kid 0)))
3937
3938 (defstruct (js2-xml-pi-node
3939 (:include js2-xml-node)
3940 (:constructor nil)
3941 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
3942 (pos js2-ts-cursor)
3943 len name attrs)))
3944 "AST node for an E4X XML processing instruction. Not currently used."
3945 name ; a `js2-xml-name-node'
3946 attrs) ; a list of `js2-xml-attr-node'
3947
3948 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
3949 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
3950
3951 (defun js2-visit-xml-pi-node (n v)
3952 (js2-visit-ast (js2-xml-pi-node-name n) v)
3953 (dolist (attr (js2-xml-pi-node-attrs n))
3954 (js2-visit-ast attr v)))
3955
3956 (defun js2-print-xml-pi-node (n i)
3957 (insert (js2-make-pad i) "<?")
3958 (js2-print-ast (js2-xml-pi-node-name n))
3959 (when (js2-xml-pi-node-attrs n)
3960 (insert " ")
3961 (js2-print-list (js2-xml-pi-node-attrs n)))
3962 (insert "?>"))
3963
3964 (defstruct (js2-xml-cdata-node
3965 (:include js2-xml-node)
3966 (:constructor nil)
3967 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
3968 (pos js2-ts-cursor)
3969 len content)))
3970 "AST node for a CDATA escape section. Not currently used."
3971 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
3972
3973 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
3974 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
3975
3976 (defun js2-visit-xml-cdata-node (n v)
3977 (js2-visit-ast (js2-xml-cdata-node-content n) v))
3978
3979 (defun js2-print-xml-cdata-node (n i)
3980 (insert (js2-make-pad i))
3981 (js2-print-ast (js2-xml-cdata-node-content n)))
3982
3983 (defstruct (js2-xml-attr-node
3984 (:include js2-xml-node)
3985 (:constructor nil)
3986 (:constructor make-js2-attr-node (&key (type js2-XML)
3987 (pos js2-ts-cursor)
3988 len name value
3989 eq-pos quote-type)))
3990 "AST node representing a foo='bar' XML attribute value. Not yet used."
3991 name ; a `js2-xml-name-node'
3992 value ; a `js2-xml-name-node'
3993 eq-pos ; buffer position of "=" sign
3994 quote-type) ; 'single or 'double
3995
3996 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
3997 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
3998
3999 (defun js2-visit-xml-attr-node (n v)
4000 (js2-visit-ast (js2-xml-attr-node-name n) v)
4001 (js2-visit-ast (js2-xml-attr-node-value n) v))
4002
4003 (defun js2-print-xml-attr-node (n i)
4004 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4005 "'"
4006 "\"")))
4007 (insert (js2-make-pad i))
4008 (js2-print-ast (js2-xml-attr-node-name n) 0)
4009 (insert "=" quote)
4010 (js2-print-ast (js2-xml-attr-node-value n) 0)
4011 (insert quote)))
4012
4013 (defstruct (js2-xml-text-node
4014 (:include js2-xml-node)
4015 (:constructor nil)
4016 (:constructor make-js2-text-node (&key (type js2-XML)
4017 (pos js2-ts-cursor)
4018 len content)))
4019 "AST node for an E4X XML text node. Not currently used."
4020 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4021
4022 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4023 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4024
4025 (defun js2-visit-xml-text-node (n v)
4026 (js2-visit-ast (js2-xml-text-node-content n) v))
4027
4028 (defun js2-print-xml-text-node (n i)
4029 (insert (js2-make-pad i))
4030 (dolist (kid (js2-xml-text-node-content n))
4031 (js2-print-ast kid)))
4032
4033 (defstruct (js2-xml-comment-node
4034 (:include js2-xml-node)
4035 (:constructor nil)
4036 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4037 (pos js2-ts-cursor)
4038 len)))
4039 "AST node for E4X XML comment. Not currently used.")
4040
4041 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4042 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4043
4044 (defun js2-print-xml-comment (n i)
4045 (insert (js2-make-pad i)
4046 (js2-node-string n)))
4047
4048 ;;; Node utilities
4049
4050 (defsubst js2-node-line (n)
4051 "Fetch the source line number at the start of node N.
4052 This is O(n) in the length of the source buffer; use prudently."
4053 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4054
4055 (defsubst js2-block-node-kid (n i)
4056 "Return child I of node N, or nil if there aren't that many."
4057 (nth i (js2-block-node-kids n)))
4058
4059 (defsubst js2-block-node-first (n)
4060 "Return first child of block node N, or nil if there is none."
4061 (first (js2-block-node-kids n)))
4062
4063 (defun js2-node-root (n)
4064 "Return the root of the AST containing N.
4065 If N has no parent pointer, returns N."
4066 (let ((parent (js2-node-parent n)))
4067 (if parent
4068 (js2-node-root parent)
4069 n)))
4070
4071 (defsubst js2-node-short-name (n)
4072 "Return the short name of node N as a string, e.g. `js2-if-node'."
4073 (substring (symbol-name (aref n 0))
4074 (length "cl-struct-")))
4075
4076 (defun js2-node-child-list (node)
4077 "Return the child list for NODE, a Lisp list of nodes.
4078 Works for block nodes, array nodes, obj literals, funarg lists,
4079 var decls and try nodes (for catch clauses). Note that you should call
4080 `js2-block-node-kids' on the function body for the body statements.
4081 Returns nil for zero-length child lists or unsupported nodes."
4082 (cond
4083 ((js2-function-node-p node)
4084 (js2-function-node-params node))
4085 ((js2-block-node-p node)
4086 (js2-block-node-kids node))
4087 ((js2-try-node-p node)
4088 (js2-try-node-catch-clauses node))
4089 ((js2-array-node-p node)
4090 (js2-array-node-elems node))
4091 ((js2-object-node-p node)
4092 (js2-object-node-elems node))
4093 ((js2-call-node-p node)
4094 (js2-call-node-args node))
4095 ((js2-new-node-p node)
4096 (js2-new-node-args node))
4097 ((js2-var-decl-node-p node)
4098 (js2-var-decl-node-kids node))
4099 (t
4100 nil)))
4101
4102 (defun js2-node-set-child-list (node kids)
4103 "Set the child list for NODE to KIDS."
4104 (cond
4105 ((js2-function-node-p node)
4106 (setf (js2-function-node-params node) kids))
4107 ((js2-block-node-p node)
4108 (setf (js2-block-node-kids node) kids))
4109 ((js2-try-node-p node)
4110 (setf (js2-try-node-catch-clauses node) kids))
4111 ((js2-array-node-p node)
4112 (setf (js2-array-node-elems node) kids))
4113 ((js2-object-node-p node)
4114 (setf (js2-object-node-elems node) kids))
4115 ((js2-call-node-p node)
4116 (setf (js2-call-node-args node) kids))
4117 ((js2-new-node-p node)
4118 (setf (js2-new-node-args node) kids))
4119 ((js2-var-decl-node-p node)
4120 (setf (js2-var-decl-node-kids node) kids))
4121 (t
4122 (error "Unsupported node type: %s" (js2-node-short-name node))))
4123 kids)
4124
4125 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4126 (defconst js2-paren-expr-nodes
4127 '(cl-struct-js2-array-comp-loop-node
4128 cl-struct-js2-array-comp-node
4129 cl-struct-js2-call-node
4130 cl-struct-js2-catch-node
4131 cl-struct-js2-do-node
4132 cl-struct-js2-elem-get-node
4133 cl-struct-js2-for-in-node
4134 cl-struct-js2-for-node
4135 cl-struct-js2-function-node
4136 cl-struct-js2-if-node
4137 cl-struct-js2-let-node
4138 cl-struct-js2-new-node
4139 cl-struct-js2-paren-node
4140 cl-struct-js2-switch-node
4141 cl-struct-js2-while-node
4142 cl-struct-js2-with-node
4143 cl-struct-js2-xml-dot-query-node)
4144 "Node types that can have a parenthesized child expression.
4145 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4146
4147 (defsubst js2-paren-expr-node-p (node)
4148 "Return t for nodes that typically have a parenthesized child expression.
4149 Useful for computing the indentation anchors for arg-lists and conditions.
4150 Note that it may return a false positive, for instance when NODE is
4151 a `js2-new-node' and there are no arguments or parentheses."
4152 (memq (aref node 0) js2-paren-expr-nodes))
4153
4154 ;; Fake polymorphism... yech.
4155 (defun js2-node-lp (node)
4156 "Return relative left-paren position for NODE, if applicable.
4157 For `js2-elem-get-node' structs, returns left-bracket position.
4158 Note that the position may be nil in the case of a parse error."
4159 (cond
4160 ((js2-elem-get-node-p node)
4161 (js2-elem-get-node-lb node))
4162 ((js2-loop-node-p node)
4163 (js2-loop-node-lp node))
4164 ((js2-function-node-p node)
4165 (js2-function-node-lp node))
4166 ((js2-if-node-p node)
4167 (js2-if-node-lp node))
4168 ((js2-new-node-p node)
4169 (js2-new-node-lp node))
4170 ((js2-call-node-p node)
4171 (js2-call-node-lp node))
4172 ((js2-paren-node-p node)
4173 0)
4174 ((js2-switch-node-p node)
4175 (js2-switch-node-lp node))
4176 ((js2-catch-node-p node)
4177 (js2-catch-node-lp node))
4178 ((js2-let-node-p node)
4179 (js2-let-node-lp node))
4180 ((js2-array-comp-node-p node)
4181 (js2-array-comp-node-lp node))
4182 ((js2-with-node-p node)
4183 (js2-with-node-lp node))
4184 ((js2-xml-dot-query-node-p node)
4185 (1+ (js2-infix-node-op-pos node)))
4186 (t
4187 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4188
4189 ;; Fake polymorphism... blech.
4190 (defun js2-node-rp (node)
4191 "Return relative right-paren position for NODE, if applicable.
4192 For `js2-elem-get-node' structs, returns right-bracket position.
4193 Note that the position may be nil in the case of a parse error."
4194 (cond
4195 ((js2-elem-get-node-p node)
4196 (js2-elem-get-node-rb node))
4197 ((js2-loop-node-p node)
4198 (js2-loop-node-rp node))
4199 ((js2-function-node-p node)
4200 (js2-function-node-rp node))
4201 ((js2-if-node-p node)
4202 (js2-if-node-rp node))
4203 ((js2-new-node-p node)
4204 (js2-new-node-rp node))
4205 ((js2-call-node-p node)
4206 (js2-call-node-rp node))
4207 ((js2-paren-node-p node)
4208 (1- (js2-node-len node)))
4209 ((js2-switch-node-p node)
4210 (js2-switch-node-rp node))
4211 ((js2-catch-node-p node)
4212 (js2-catch-node-rp node))
4213 ((js2-let-node-p node)
4214 (js2-let-node-rp node))
4215 ((js2-array-comp-node-p node)
4216 (js2-array-comp-node-rp node))
4217 ((js2-with-node-p node)
4218 (js2-with-node-rp node))
4219 ((js2-xml-dot-query-node-p node)
4220 (1+ (js2-xml-dot-query-node-rp node)))
4221 (t
4222 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4223
4224 (defsubst js2-node-first-child (node)
4225 "Return the first element of `js2-node-child-list' for NODE."
4226 (car (js2-node-child-list node)))
4227
4228 (defsubst js2-node-last-child (node)
4229 "Return the last element of `js2-node-last-child' for NODE."
4230 (car (last (js2-node-child-list node))))
4231
4232 (defun js2-node-prev-sibling (node)
4233 "Return the previous statement in parent.
4234 Works for parents supported by `js2-node-child-list'.
4235 Returns nil if NODE is not in the parent, or PARENT is
4236 not a supported node, or if NODE is the first child."
4237 (let* ((p (js2-node-parent node))
4238 (kids (js2-node-child-list p))
4239 (sib (car kids)))
4240 (while (and kids
4241 (not (eq node (cadr kids))))
4242 (setq kids (cdr kids)
4243 sib (car kids)))
4244 sib))
4245
4246 (defun js2-node-next-sibling (node)
4247 "Return the next statement in parent block.
4248 Returns nil if NODE is not in the block, or PARENT is not
4249 a block node, or if NODE is the last statement."
4250 (let* ((p (js2-node-parent node))
4251 (kids (js2-node-child-list p)))
4252 (while (and kids
4253 (not (eq node (car kids))))
4254 (setq kids (cdr kids)))
4255 (cadr kids)))
4256
4257 (defun js2-node-find-child-before (pos parent &optional after)
4258 "Find the last child that starts before POS in parent.
4259 If AFTER is non-nil, returns first child starting after POS.
4260 POS is an absolute buffer position. PARENT is any node
4261 supported by `js2-node-child-list'.
4262 Returns nil if no applicable child is found."
4263 (let ((kids (if (js2-function-node-p parent)
4264 (js2-block-node-kids (js2-function-node-body parent))
4265 (js2-node-child-list parent)))
4266 (beg (if (js2-function-node-p parent)
4267 (js2-node-abs-pos (js2-function-node-body parent))
4268 (js2-node-abs-pos parent)))
4269 kid result fn
4270 (continue t))
4271 (setq fn (if after '>= '<))
4272 (while (and kids continue)
4273 (setq kid (car kids))
4274 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4275 (setq result kid
4276 continue (if after nil t))
4277 (setq continue (if after t nil)))
4278 (setq kids (cdr kids)))
4279 result))
4280
4281 (defun js2-node-find-child-after (pos parent)
4282 "Find first child that starts after POS in parent.
4283 POS is an absolute buffer position. PARENT is any node
4284 supported by `js2-node-child-list'.
4285 Returns nil if no applicable child is found."
4286 (js2-node-find-child-before pos parent 'after))
4287
4288 (defun js2-node-replace-child (pos parent new-node)
4289 "Replace node at index POS in PARENT with NEW-NODE.
4290 Only works for parents supported by `js2-node-child-list'."
4291 (let ((kids (js2-node-child-list parent))
4292 (i 0))
4293 (while (< i pos)
4294 (setq kids (cdr kids)
4295 i (1+ i)))
4296 (setcar kids new-node)
4297 (js2-node-add-children parent new-node)))
4298
4299 (defun js2-node-buffer (n)
4300 "Return the buffer associated with AST N.
4301 Returns nil if the buffer is not set as a property on the root
4302 node, or if parent links were not recorded during parsing."
4303 (let ((root (js2-node-root n)))
4304 (and root
4305 (js2-ast-root-p root)
4306 (js2-ast-root-buffer root))))
4307
4308 (defun js2-block-node-push (n kid)
4309 "Push js2-node KID onto the end of js2-block-node N's child list.
4310 KID is always added to the -end- of the kids list.
4311 Function also calls `js2-node-add-children' to add the parent link."
4312 (let ((kids (js2-node-child-list n)))
4313 (if kids
4314 (setcdr kids (nconc (cdr kids) (list kid)))
4315 (js2-node-set-child-list n (list kid)))
4316 (js2-node-add-children n kid)))
4317
4318 (defun js2-node-string (node)
4319 (with-current-buffer (or (js2-node-buffer node)
4320 (error "No buffer available for node %s" node))
4321 (let ((pos (js2-node-abs-pos node)))
4322 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4323
4324 ;; Container for storing the node we're looking for in a traversal.
4325 (js2-deflocal js2-discovered-node nil)
4326
4327 ;; Keep track of absolute node position during traversals.
4328 (js2-deflocal js2-visitor-offset nil)
4329
4330 (js2-deflocal js2-node-search-point nil)
4331
4332 (when js2-mode-dev-mode-p
4333 (defun js2-find-node-at-point ()
4334 (interactive)
4335 (let ((node (js2-node-at-point)))
4336 (message "%s" (or node "No node found at point"))))
4337 (defun js2-node-name-at-point ()
4338 (interactive)
4339 (let ((node (js2-node-at-point)))
4340 (message "%s" (if node
4341 (js2-node-short-name node)
4342 "No node found at point.")))))
4343
4344 (defun js2-node-at-point (&optional pos skip-comments)
4345 "Return AST node at POS, a buffer position, defaulting to current point.
4346 The `js2-mode-ast' variable must be set to the current parse tree.
4347 Signals an error if the AST (`js2-mode-ast') is nil.
4348 Always returns a node - if it can't find one, it returns the root.
4349 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4350 (let ((ast js2-mode-ast)
4351 result)
4352 (unless ast
4353 (error "No JavaScript AST available"))
4354 ;; Look through comments first, since they may be inside nodes that
4355 ;; would otherwise report a match.
4356 (setq pos (or pos (point))
4357 result (if (> pos (js2-node-abs-end ast))
4358 ast
4359 (if (not skip-comments)
4360 (js2-comment-at-point pos))))
4361 (unless result
4362 (setq js2-discovered-node nil
4363 js2-visitor-offset 0
4364 js2-node-search-point pos)
4365 (unwind-protect
4366 (catch 'js2-visit-done
4367 (js2-visit-ast ast #'js2-node-at-point-visitor))
4368 (setq js2-visitor-offset nil
4369 js2-node-search-point nil))
4370 (setq result js2-discovered-node))
4371 ;; may have found a comment beyond end of last child node,
4372 ;; since visiting the ast-root looks at the comment-list last.
4373 (if (and skip-comments
4374 (js2-comment-node-p result))
4375 (setq result nil))
4376 (or result js2-mode-ast)))
4377
4378 (defun js2-node-at-point-visitor (node end-p)
4379 (let ((rel-pos (js2-node-pos node))
4380 abs-pos
4381 abs-end
4382 (point js2-node-search-point))
4383 (cond
4384 (end-p
4385 ;; this evaluates to a non-nil return value, even if it's zero
4386 (decf js2-visitor-offset rel-pos))
4387 ;; we already looked for comments before visiting, and don't want them now
4388 ((js2-comment-node-p node)
4389 nil)
4390 (t
4391 (setq abs-pos (incf js2-visitor-offset rel-pos)
4392 ;; we only want to use the node if the point is before
4393 ;; the last character position in the node, so we decrement
4394 ;; the absolute end by 1.
4395 abs-end (+ abs-pos (js2-node-len node) -1))
4396 (cond
4397 ;; If this node starts after search-point, stop the search.
4398 ((> abs-pos point)
4399 (throw 'js2-visit-done nil))
4400 ;; If this node ends before the search-point, don't check kids.
4401 ((> point abs-end)
4402 nil)
4403 (t
4404 ;; Otherwise point is within this node, possibly in a child.
4405 (setq js2-discovered-node node)
4406 t)))))) ; keep processing kids to look for more specific match
4407
4408 (defsubst js2-block-comment-p (node)
4409 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4410 (and (js2-comment-node-p node)
4411 (memq (js2-comment-node-format node) '(jsdoc block))))
4412
4413 ;; TODO: put the comments in a vector and binary-search them instead
4414 (defun js2-comment-at-point (&optional pos)
4415 "Look through scanned comment nodes for one containing POS.
4416 POS is a buffer position that defaults to current point.
4417 Function returns nil if POS was not in any comment node."
4418 (let ((ast js2-mode-ast)
4419 (x (or pos (point)))
4420 beg end)
4421 (unless ast
4422 (error "No JavaScript AST available"))
4423 (catch 'done
4424 ;; Comments are stored in lexical order.
4425 (dolist (comment (js2-ast-root-comments ast) nil)
4426 (setq beg (js2-node-abs-pos comment)
4427 end (+ beg (js2-node-len comment)))
4428 (if (and (>= x beg)
4429 (<= x end))
4430 (throw 'done comment))))))
4431
4432 (defun js2-mode-find-parent-fn (node)
4433 "Find function enclosing NODE.
4434 Returns nil if NODE is not inside a function."
4435 (setq node (js2-node-parent node))
4436 (while (and node (not (js2-function-node-p node)))
4437 (setq node (js2-node-parent node)))
4438 (and (js2-function-node-p node) node))
4439
4440 (defun js2-mode-find-enclosing-fn (node)
4441 "Find function or root enclosing NODE."
4442 (if (js2-ast-root-p node)
4443 node
4444 (setq node (js2-node-parent node))
4445 (while (not (or (js2-ast-root-p node)
4446 (js2-function-node-p node)))
4447 (setq node (js2-node-parent node)))
4448 node))
4449
4450 (defun js2-mode-find-enclosing-node (beg end)
4451 "Find script or function fully enclosing BEG and END."
4452 (let ((node (js2-node-at-point beg))
4453 pos
4454 (continue t))
4455 (while continue
4456 (if (or (js2-ast-root-p node)
4457 (and (js2-function-node-p node)
4458 (<= (setq pos (js2-node-abs-pos node)) beg)
4459 (>= (+ pos (js2-node-len node)) end)))
4460 (setq continue nil)
4461 (setq node (js2-node-parent node))))
4462 node))
4463
4464 (defun js2-node-parent-script-or-fn (node)
4465 "Find script or function immediately enclosing NODE.
4466 If NODE is the ast-root, returns nil."
4467 (if (js2-ast-root-p node)
4468 nil
4469 (setq node (js2-node-parent node))
4470 (while (and node (not (or (js2-function-node-p node)
4471 (js2-script-node-p node))))
4472 (setq node (js2-node-parent node)))
4473 node))
4474
4475 (defun js2-node-is-descendant (node ancestor)
4476 "Return t if NODE is a descendant of ANCESTOR."
4477 (while (and node
4478 (not (eq node ancestor)))
4479 (setq node (js2-node-parent node)))
4480 node)
4481
4482 ;;; visitor infrastructure
4483
4484 (defun js2-visit-none (node callback)
4485 "Visitor for AST node that have no node children."
4486 nil)
4487
4488 (defun js2-print-none (node indent)
4489 "Visitor for AST node with no printed representation.")
4490
4491 (defun js2-print-body (node indent)
4492 "Print a statement, or a block without braces."
4493 (if (js2-block-node-p node)
4494 (dolist (kid (js2-block-node-kids node))
4495 (js2-print-ast kid indent))
4496 (js2-print-ast node indent)))
4497
4498 (defun js2-print-list (args &optional delimiter)
4499 (loop with len = (length args)
4500 for arg in args
4501 for count from 1
4502 do
4503 (when arg (js2-print-ast arg 0))
4504 (if (< count len)
4505 (insert (or delimiter ", ")))))
4506
4507 (defun js2-print-tree (ast)
4508 "Prints an AST to the current buffer.
4509 Makes `js2-ast-parent-nodes' available to the printer functions."
4510 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4511 (js2-print-ast ast)))
4512
4513 (defun js2-print-ast (node &optional indent)
4514 "Helper function for printing AST nodes.
4515 Requires `js2-ast-parent-nodes' to be non-nil.
4516 You should use `js2-print-tree' instead of this function."
4517 (let ((printer (get (aref node 0) 'js2-printer))
4518 (i (or indent 0))
4519 (pos (js2-node-abs-pos node)))
4520 ;; TODO: wedge comments in here somewhere
4521 (if printer
4522 (funcall printer node i))))
4523
4524 (defconst js2-side-effecting-tokens
4525 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4526 (dolist (tt (list js2-ASSIGN
4527 js2-ASSIGN_ADD
4528 js2-ASSIGN_BITAND
4529 js2-ASSIGN_BITOR
4530 js2-ASSIGN_BITXOR
4531 js2-ASSIGN_DIV
4532 js2-ASSIGN_LSH
4533 js2-ASSIGN_MOD
4534 js2-ASSIGN_MUL
4535 js2-ASSIGN_RSH
4536 js2-ASSIGN_SUB
4537 js2-ASSIGN_URSH
4538 js2-BLOCK
4539 js2-BREAK
4540 js2-CALL
4541 js2-CATCH
4542 js2-CATCH_SCOPE
4543 js2-CONST
4544 js2-CONTINUE
4545 js2-DEBUGGER
4546 js2-DEC
4547 js2-DELPROP
4548 js2-DEL_REF
4549 js2-DO
4550 js2-ELSE
4551 js2-EMPTY
4552 js2-ENTERWITH
4553 js2-EXPORT
4554 js2-EXPR_RESULT
4555 js2-FINALLY
4556 js2-FOR
4557 js2-FUNCTION
4558 js2-GOTO
4559 js2-IF
4560 js2-IFEQ
4561 js2-IFNE
4562 js2-IMPORT
4563 js2-INC
4564 js2-JSR
4565 js2-LABEL
4566 js2-LEAVEWITH
4567 js2-LET
4568 js2-LETEXPR
4569 js2-LOCAL_BLOCK
4570 js2-LOOP
4571 js2-NEW
4572 js2-REF_CALL
4573 js2-RETHROW
4574 js2-RETURN
4575 js2-RETURN_RESULT
4576 js2-SEMI
4577 js2-SETELEM
4578 js2-SETELEM_OP
4579 js2-SETNAME
4580 js2-SETPROP
4581 js2-SETPROP_OP
4582 js2-SETVAR
4583 js2-SET_REF
4584 js2-SET_REF_OP
4585 js2-SWITCH
4586 js2-TARGET
4587 js2-THROW
4588 js2-TRY
4589 js2-VAR
4590 js2-WHILE
4591 js2-WITH
4592 js2-WITHEXPR
4593 js2-YIELD))
4594 (aset tokens tt t))
4595 (if js2-instanceof-has-side-effects
4596 (aset tokens js2-INSTANCEOF t))
4597 tokens))
4598
4599 (defun js2-node-has-side-effects (node)
4600 "Return t if NODE has side effects."
4601 (when node ; makes it easier to handle malformed expressions
4602 (let ((tt (js2-node-type node)))
4603 (cond
4604 ;; This doubtless needs some work, since EXPR_VOID is used
4605 ;; in several ways in Rhino and I may not have caught them all.
4606 ;; I'll wait for people to notice incorrect warnings.
4607 ((and (= tt js2-EXPR_VOID)
4608 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4609 (let ((expr (js2-expr-stmt-node-expr node)))
4610 (or (js2-node-has-side-effects expr)
4611 (when (js2-string-node-p expr)
4612 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4613 ((= tt js2-COMMA)
4614 (js2-node-has-side-effects (js2-infix-node-right node)))
4615 ((or (= tt js2-AND)
4616 (= tt js2-OR))
4617 (or (js2-node-has-side-effects (js2-infix-node-right node))
4618 (js2-node-has-side-effects (js2-infix-node-left node))))
4619 ((= tt js2-HOOK)
4620 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4621 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4622 ((js2-paren-node-p node)
4623 (js2-node-has-side-effects (js2-paren-node-expr node)))
4624 ((= tt js2-ERROR) ; avoid cascaded error messages
4625 nil)
4626 (t
4627 (aref js2-side-effecting-tokens tt))))))
4628
4629 (defconst js2-stmt-node-types
4630 (list js2-BLOCK
4631 js2-BREAK
4632 js2-CONTINUE
4633 js2-DEFAULT ; e4x "default xml namespace" statement
4634 js2-DO
4635 js2-EXPR_RESULT
4636 js2-EXPR_VOID
4637 js2-FOR
4638 js2-IF
4639 js2-RETURN
4640 js2-SWITCH
4641 js2-THROW
4642 js2-TRY
4643 js2-WHILE
4644 js2-WITH)
4645 "Node types that only appear in statement contexts.
4646 The list does not include nodes that always appear as the child
4647 of another specific statement type, such as switch-cases,
4648 catch and finally blocks, and else-clauses. The list also excludes
4649 nodes like yield, let and var, which may appear in either expression
4650 or statement context, and in the latter context always have a
4651 `js2-expr-stmt-node' parent. Finally, the list does not include
4652 functions or scripts, which are treated separately from statements
4653 by the JavaScript parser and runtime.")
4654
4655 (defun js2-stmt-node-p (node)
4656 "Heuristic for figuring out if NODE is a statement.
4657 Some node types can appear in either an expression context or a
4658 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4659 For these node types in a statement context, the parent will be a
4660 `js2-expr-stmt-node'.
4661 Functions aren't included in the check."
4662 (memq (js2-node-type node) js2-stmt-node-types))
4663
4664 (defun js2-mode-find-first-stmt (node)
4665 "Search upward starting from NODE looking for a statement.
4666 For purposes of this function, a `js2-function-node' counts."
4667 (while (not (or (js2-stmt-node-p node)
4668 (js2-function-node-p node)))
4669 (setq node (js2-node-parent node)))
4670 node)
4671
4672 (defun js2-node-parent-stmt (node)
4673 "Return the node's first ancestor that is a statement.
4674 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4675 appearing in a statement context will have a parent that is a
4676 `js2-expr-stmt-node' that will be returned by this function."
4677 (let ((parent (js2-node-parent node)))
4678 (if (or (null parent)
4679 (js2-stmt-node-p parent)
4680 (and (js2-function-node-p parent)
4681 (not (eq (js2-function-node-form parent)
4682 'FUNCTION_EXPRESSION))))
4683 parent
4684 (js2-node-parent-stmt parent))))
4685
4686 ;; In the Mozilla Rhino sources, Roshan James writes:
4687 ;; Does consistent-return analysis on the function body when strict mode is
4688 ;; enabled.
4689 ;;
4690 ;; function (x) { return (x+1) }
4691 ;;
4692 ;; is ok, but
4693 ;;
4694 ;; function (x) { if (x < 0) return (x+1); }
4695 ;;
4696 ;; is not because the function can potentially return a value when the
4697 ;; condition is satisfied and if not, the function does not explicitly
4698 ;; return a value.
4699 ;;
4700 ;; This extends to checking mismatches such as "return" and "return <value>"
4701 ;; used in the same function. Warnings are not emitted if inconsistent
4702 ;; returns exist in code that can be statically shown to be unreachable.
4703 ;; Ex.
4704 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4705 ;;
4706 ;; emits no warning. However if the loop had a break statement, then a
4707 ;; warning would be emitted.
4708 ;;
4709 ;; The consistency analysis looks at control structures such as loops, ifs,
4710 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4711 ;; warns the user about an inconsistent set of termination possibilities.
4712 ;;
4713 ;; These flags enumerate the possible ways a statement/function can
4714 ;; terminate. These flags are used by endCheck() and by the Parser to
4715 ;; detect inconsistent return usage.
4716 ;;
4717 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4718 ;; able to execute (example: throw, continue)
4719 ;;
4720 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4721 ;; next one. Statement such as return dont. A compound statement may have
4722 ;; some branch that drops off control to the next statement.
4723 ;;
4724 ;; END_RETURNS indicates that the statement can return with no value.
4725 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4726 ;;
4727 ;; A compound statement such as
4728 ;; if (condition) {
4729 ;; return value;
4730 ;; }
4731 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4732
4733 (defconst js2-END_UNREACHED 0)
4734 (defconst js2-END_DROPS_OFF 1)
4735 (defconst js2-END_RETURNS 2)
4736 (defconst js2-END_RETURNS_VALUE 4)
4737 (defconst js2-END_YIELDS 8)
4738
4739 (defun js2-has-consistent-return-usage (node)
4740 "Check that every return usage in a function body is consistent.
4741 Returns t if the function satisfies strict mode requirement."
4742 (let ((n (js2-end-check node)))
4743 ;; either it doesn't return a value in any branch...
4744 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4745 ;; or it returns a value (or is unreached) at every branch
4746 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4747 js2-END_RETURNS
4748 js2-END_YIELDS)))))
4749
4750 (defun js2-end-check-if (node)
4751 "Ensure that return usage in then/else blocks is consistent.
4752 If there is no else block, then the return statement can fall through.
4753 Returns logical OR of END_* flags"
4754 (let ((th (js2-if-node-then-part node))
4755 (el (js2-if-node-else-part node)))
4756 (if (null th)
4757 js2-END_UNREACHED
4758 (logior (js2-end-check th) (if el
4759 (js2-end-check el)
4760 js2-END_DROPS_OFF)))))
4761
4762 (defun js2-end-check-switch (node)
4763 "Consistency of return statements is checked between the case statements.
4764 If there is no default, then the switch can fall through. If there is a
4765 default, we check to see if all code paths in the default return or if
4766 there is a code path that can fall through.
4767 Returns logical OR of END_* flags."
4768 (let ((rv js2-END_UNREACHED)
4769 default-case)
4770 ;; examine the cases
4771 (catch 'break
4772 (dolist (c (js2-switch-node-cases node))
4773 (if (js2-case-node-expr c)
4774 (js2-set-flag rv (js2-end-check-block c))
4775 (setq default-case c)
4776 (throw 'break nil))))
4777 ;; we don't care how the cases drop into each other
4778 (js2-clear-flag rv js2-END_DROPS_OFF)
4779 ;; examine the default
4780 (js2-set-flag rv (if default-case
4781 (js2-end-check default-case)
4782 js2-END_DROPS_OFF))
4783 rv))
4784
4785 (defun js2-end-check-try (node)
4786 "If the block has a finally, return consistency is checked in the
4787 finally block. If all code paths in the finally return, then the
4788 returns in the try-catch blocks don't matter. If there is a code path
4789 that does not return or if there is no finally block, the returns
4790 of the try and catch blocks are checked for mismatch.
4791 Returns logical OR of END_* flags."
4792 (let ((finally (js2-try-node-finally-block node))
4793 rv)
4794 ;; check the finally if it exists
4795 (setq rv (if finally
4796 (js2-end-check (js2-finally-node-body finally))
4797 js2-END_DROPS_OFF))
4798 ;; If the finally block always returns, then none of the returns
4799 ;; in the try or catch blocks matter.
4800 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4801 (js2-clear-flag rv js2-END_DROPS_OFF)
4802 ;; examine the try block
4803 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4804 ;; check each catch block
4805 (dolist (cb (js2-try-node-catch-clauses node))
4806 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4807 rv))
4808
4809 (defun js2-end-check-loop (node)
4810 "Return statement in the loop body must be consistent.
4811 The default assumption for any kind of a loop is that it will eventually
4812 terminate. The only exception is a loop with a constant true condition.
4813 Code that follows such a loop is examined only if one can determine
4814 statically that there is a break out of the loop.
4815
4816 for(... ; ... ; ...) {}
4817 for(... in ... ) {}
4818 while(...) { }
4819 do { } while(...)
4820
4821 Returns logical OR of END_* flags."
4822 (let ((rv (js2-end-check (js2-loop-node-body node)))
4823 (condition (cond
4824 ((js2-while-node-p node)
4825 (js2-while-node-condition node))
4826 ((js2-do-node-p node)
4827 (js2-do-node-condition node))
4828 ((js2-for-node-p node)
4829 (js2-for-node-condition node)))))
4830
4831 ;; check to see if the loop condition is always true
4832 (if (and condition
4833 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4834 (js2-clear-flag rv js2-END_DROPS_OFF))
4835
4836 ;; look for effect of breaks
4837 (js2-set-flag rv (js2-node-get-prop node
4838 'CONTROL_BLOCK_PROP
4839 js2-END_UNREACHED))
4840 rv))
4841
4842 (defun js2-end-check-block (node)
4843 "A general block of code is examined statement by statement.
4844 If any statement (even a compound one) returns in all branches, then
4845 subsequent statements are not examined.
4846 Returns logical OR of END_* flags."
4847 (let* ((rv js2-END_DROPS_OFF)
4848 (kids (js2-block-node-kids node))
4849 (n (car kids)))
4850 ;; Check each statment. If the statement can continue onto the next
4851 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4852 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4853 (js2-clear-flag rv js2-END_DROPS_OFF)
4854 (js2-set-flag rv (js2-end-check n))
4855 (setq kids (cdr kids)
4856 n (car kids)))
4857 rv))
4858
4859 (defun js2-end-check-label (node)
4860 "A labeled statement implies that there may be a break to the label.
4861 The function processes the labeled statement and then checks the
4862 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4863 particular label.
4864 Returns logical OR of END_* flags."
4865 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4866 (logior rv (js2-node-get-prop node
4867 'CONTROL_BLOCK_PROP
4868 js2-END_UNREACHED))))
4869
4870 (defun js2-end-check-break (node)
4871 "When a break is encountered annotate the statement being broken
4872 out of by setting its CONTROL_BLOCK_PROP property.
4873 Returns logical OR of END_* flags."
4874 (and (js2-break-node-target node)
4875 (js2-node-set-prop (js2-break-node-target node)
4876 'CONTROL_BLOCK_PROP
4877 js2-END_DROPS_OFF))
4878 js2-END_UNREACHED)
4879
4880 (defun js2-end-check (node)
4881 "Examine the body of a function, doing a basic reachability analysis.
4882 Returns a combination of flags END_* flags that indicate
4883 how the function execution can terminate. These constitute only the
4884 pessimistic set of termination conditions. It is possible that at
4885 runtime certain code paths will never be actually taken. Hence this
4886 analysis will flag errors in cases where there may not be errors.
4887 Returns logical OR of END_* flags"
4888 (let (kid)
4889 (cond
4890 ((js2-break-node-p node)
4891 (js2-end-check-break node))
4892 ((js2-expr-stmt-node-p node)
4893 (if (setq kid (js2-expr-stmt-node-expr node))
4894 (js2-end-check kid)
4895 js2-END_DROPS_OFF))
4896 ((or (js2-continue-node-p node)
4897 (js2-throw-node-p node))
4898 js2-END_UNREACHED)
4899 ((js2-return-node-p node)
4900 (if (setq kid (js2-return-node-retval node))
4901 js2-END_RETURNS_VALUE
4902 js2-END_RETURNS))
4903 ((js2-loop-node-p node)
4904 (js2-end-check-loop node))
4905 ((js2-switch-node-p node)
4906 (js2-end-check-switch node))
4907 ((js2-labeled-stmt-node-p node)
4908 (js2-end-check-label node))
4909 ((js2-if-node-p node)
4910 (js2-end-check-if node))
4911 ((js2-try-node-p node)
4912 (js2-end-check-try node))
4913 ((js2-block-node-p node)
4914 (if (null (js2-block-node-kids node))
4915 js2-END_DROPS_OFF
4916 (js2-end-check-block node)))
4917 ((js2-yield-node-p node)
4918 js2-END_YIELDS)
4919 (t
4920 js2-END_DROPS_OFF))))
4921
4922 (defun js2-always-defined-boolean-p (node)
4923 "Check if NODE always evaluates to true or false in boolean context.
4924 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
4925 nor always false."
4926 (let ((tt (js2-node-type node))
4927 num)
4928 (cond
4929 ((or (= tt js2-FALSE) (= tt js2-NULL))
4930 'ALWAYS_FALSE)
4931 ((= tt js2-TRUE)
4932 'ALWAYS_TRUE)
4933 ((= tt js2-NUMBER)
4934 (setq num (js2-number-node-num-value node))
4935 (if (and (not (eq num 0.0e+NaN))
4936 (not (zerop num)))
4937 'ALWAYS_TRUE
4938 'ALWAYS_FALSE))
4939 (t
4940 nil))))
4941
4942 ;;; Scanner -- a port of Mozilla Rhino's lexer.
4943 ;; Corresponds to Rhino files Token.java and TokenStream.java.
4944
4945 (defvar js2-tokens nil
4946 "List of all defined token names.") ; initialized in `js2-token-names'
4947
4948 (defconst js2-token-names
4949 (let* ((names (make-vector js2-num-tokens -1))
4950 (case-fold-search nil) ; only match js2-UPPER_CASE
4951 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
4952 (loop for sym in syms
4953 for i from 0
4954 do
4955 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
4956 (not (boundp sym)))
4957 (aset names (symbol-value sym) ; code, e.g. 152
4958 (downcase
4959 (substring (symbol-name sym) 4))) ; name, e.g. "let"
4960 (push sym js2-tokens)))
4961 names)
4962 "Vector mapping int values to token string names, sans `js2-' prefix.")
4963
4964 (defun js2-token-name (tok)
4965 "Return a string name for TOK, a token symbol or code.
4966 Signals an error if it's not a recognized token."
4967 (let ((code tok))
4968 (if (symbolp tok)
4969 (setq code (symbol-value tok)))
4970 (if (eq code -1)
4971 "ERROR"
4972 (if (and (numberp code)
4973 (not (minusp code))
4974 (< code js2-num-tokens))
4975 (aref js2-token-names code)
4976 (error "Invalid token: %s" code)))))
4977
4978 (defsubst js2-token-sym (tok)
4979 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
4980 (intern (js2-token-name tok)))
4981
4982 (defconst js2-token-codes
4983 (let ((table (make-hash-table :test 'eq :size 256)))
4984 (loop for name across js2-token-names
4985 for sym = (intern (concat "js2-" (upcase name)))
4986 do
4987 (puthash sym (symbol-value sym) table))
4988 ;; clean up a few that are "wrong" in Rhino's token codes
4989 (puthash 'js2-DELETE js2-DELPROP table)
4990 table)
4991 "Hashtable mapping token symbols to their bytecodes.")
4992
4993 (defsubst js2-token-code (sym)
4994 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
4995 (or (gethash sym js2-token-codes)
4996 (error "Invalid token symbol: %s " sym))) ; signal code bug
4997
4998 (defun js2-report-scan-error (msg &optional no-throw beg len)
4999 (setq js2-token-end js2-ts-cursor)
5000 (js2-report-error msg nil
5001 (or beg js2-token-beg)
5002 (or len (- js2-token-end js2-token-beg)))
5003 (unless no-throw
5004 (throw 'return js2-ERROR)))
5005
5006 (defun js2-get-string-from-buffer ()
5007 "Reverse the char accumulator and return it as a string."
5008 (setq js2-token-end js2-ts-cursor)
5009 (if js2-ts-string-buffer
5010 (apply #'string (nreverse js2-ts-string-buffer))
5011 ""))
5012
5013 ;; TODO: could potentially avoid a lot of consing by allocating a
5014 ;; char buffer the way Rhino does.
5015 (defsubst js2-add-to-string (c)
5016 (push c js2-ts-string-buffer))
5017
5018 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5019 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5020 ;; any other character: when it's not part of the current token, we
5021 ;; unget it, allowing it to be read again by the following call.
5022 (defsubst js2-unget-char ()
5023 (decf js2-ts-cursor))
5024
5025 ;; Rhino distinguishes \r and \n line endings. We don't need to
5026 ;; because we only scan from Emacs buffers, which always use \n.
5027 (defun js2-get-char ()
5028 "Read and return the next character from the input buffer.
5029 Increments `js2-ts-lineno' if the return value is a newline char.
5030 Updates `js2-ts-cursor' to the point after the returned char.
5031 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5032 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5033 (let (c)
5034 ;; check for end of buffer
5035 (if (>= js2-ts-cursor (point-max))
5036 (setq js2-ts-hit-eof t
5037 js2-ts-cursor (1+ js2-ts-cursor)
5038 c js2-EOF_CHAR) ; return value
5039 ;; otherwise read next char
5040 (setq c (char-before (incf js2-ts-cursor)))
5041 ;; if we read a newline, update counters
5042 (if (= c ?\n)
5043 (setq js2-ts-line-start js2-ts-cursor
5044 js2-ts-lineno (1+ js2-ts-lineno)))
5045 ;; TODO: skip over format characters
5046 c)))
5047
5048 (defun js2-read-unicode-escape ()
5049 "Read a \\uNNNN sequence from the input.
5050 Assumes the ?\ and ?u have already been read.
5051 Returns the unicode character, or nil if it wasn't a valid character.
5052 Doesn't change the values of any scanner variables."
5053 ;; I really wish I knew a better way to do this, but I can't
5054 ;; find the Emacs function that takes a 16-bit int and converts
5055 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5056 ;; Have to first check that it's 4 hex characters or it may stop
5057 ;; the read early.
5058 (ignore-errors
5059 (let ((s (buffer-substring-no-properties js2-ts-cursor
5060 (+ 4 js2-ts-cursor))))
5061 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5062 (read (concat "?\\u" s))))))
5063
5064 (defun js2-match-char (test)
5065 "Consume and return next character if it matches TEST, a character.
5066 Returns nil and consumes nothing if TEST is not the next character."
5067 (let ((c (js2-get-char)))
5068 (if (eq c test)
5069 t
5070 (js2-unget-char)
5071 nil)))
5072
5073 (defun js2-peek-char ()
5074 (prog1
5075 (js2-get-char)
5076 (js2-unget-char)))
5077
5078 (defun js2-java-identifier-start-p (c)
5079 (or
5080 (memq c '(?$ ?_))
5081 (js2-char-uppercase-p c)
5082 (js2-char-lowercase-p c)))
5083
5084 (defun js2-java-identifier-part-p (c)
5085 "Implementation of java.lang.Character.isJavaIdentifierPart()."
5086 ;; TODO: make me Unicode-friendly. See comments above.
5087 (or
5088 (memq c '(?$ ?_))
5089 (js2-char-uppercase-p c)
5090 (js2-char-lowercase-p c)
5091 (and (>= c ?0) (<= c ?9))))
5092
5093 (defun js2-alpha-p (c)
5094 (cond ((and (<= ?A c) (<= c ?Z)) t)
5095 ((and (<= ?a c) (<= c ?z)) t)
5096 (t nil)))
5097
5098 (defsubst js2-digit-p (c)
5099 (and (<= ?0 c) (<= c ?9)))
5100
5101 (defun js2-js-space-p (c)
5102 (if (<= c 127)
5103 (memq c '(#x20 #x9 #xB #xC #xD))
5104 (or
5105 (eq c #xA0)
5106 ;; TODO: change this nil to check for Unicode space character
5107 nil)))
5108
5109 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5110
5111 (defun js2-skip-line ()
5112 "Skip to end of line."
5113 (let (c)
5114 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5115 (js2-unget-char)
5116 (setq js2-token-end js2-ts-cursor)))
5117
5118 (defun js2-init-scanner (&optional buf line)
5119 "Create token stream for BUF starting on LINE.
5120 BUF defaults to `current-buffer' and LINE defaults to 1.
5121
5122 A buffer can only have one scanner active at a time, which yields
5123 dramatically simpler code than using a defstruct. If you need to
5124 have simultaneous scanners in a buffer, copy the regions to scan
5125 into temp buffers."
5126 (with-current-buffer (or buf (current-buffer))
5127 (setq js2-ts-dirty-line nil
5128 js2-ts-regexp-flags nil
5129 js2-ts-string ""
5130 js2-ts-number nil
5131 js2-ts-hit-eof nil
5132 js2-ts-line-start 0
5133 js2-ts-lineno (or line 1)
5134 js2-ts-line-end-char -1
5135 js2-ts-cursor (point-min)
5136 js2-ts-is-xml-attribute nil
5137 js2-ts-xml-is-tag-content nil
5138 js2-ts-xml-open-tags-count 0
5139 js2-ts-string-buffer nil)))
5140
5141 ;; This function uses the cached op, string and number fields in
5142 ;; TokenStream; if getToken has been called since the passed token
5143 ;; was scanned, the op or string printed may be incorrect.
5144 (defun js2-token-to-string (token)
5145 ;; Not sure where this function is used in Rhino. Not tested.
5146 (if (not js2-debug-print-trees)
5147 ""
5148 (let ((name (js2-token-name token)))
5149 (cond
5150 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5151 (concat name " `" js2-ts-string "'"))
5152 ((eq token js2-NUMBER)
5153 (format "NUMBER %g" js2-ts-number))
5154 (t
5155 name)))))
5156
5157 (defconst js2-keywords
5158 '(break
5159 case catch const continue
5160 debugger default delete do
5161 else enum
5162 false finally for function
5163 if in instanceof import
5164 let
5165 new null
5166 return
5167 switch
5168 this throw true try typeof
5169 var void
5170 while with
5171 yield))
5172
5173 ;; Token names aren't exactly the same as the keywords, unfortunately.
5174 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5175 (defconst js2-kwd-tokens
5176 (let ((table (make-vector js2-num-tokens nil))
5177 (tokens
5178 (list js2-BREAK
5179 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5180 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5181 js2-ELSE
5182 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5183 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5184 js2-LET
5185 js2-NEW js2-NULL
5186 js2-RETURN
5187 js2-SWITCH
5188 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5189 js2-VAR
5190 js2-WHILE js2-WITH
5191 js2-YIELD)))
5192 (dolist (i tokens)
5193 (aset table i 'font-lock-keyword-face))
5194 (aset table js2-STRING 'font-lock-string-face)
5195 (aset table js2-REGEXP 'font-lock-string-face)
5196 (aset table js2-COMMENT 'font-lock-comment-face)
5197 (aset table js2-THIS 'font-lock-builtin-face)
5198 (aset table js2-VOID 'font-lock-constant-face)
5199 (aset table js2-NULL 'font-lock-constant-face)
5200 (aset table js2-TRUE 'font-lock-constant-face)
5201 (aset table js2-FALSE 'font-lock-constant-face)
5202 table)
5203 "Vector whose values are non-nil for tokens that are keywords.
5204 The values are default faces to use for highlighting the keywords.")
5205
5206 (defconst js2-reserved-words
5207 '(abstract
5208 boolean byte
5209 char class
5210 double
5211 enum export extends
5212 final float
5213 goto
5214 implements import int interface
5215 long
5216 native
5217 package private protected public
5218 short static super synchronized
5219 throws transient
5220 volatile))
5221
5222 (defconst js2-keyword-names
5223 (let ((table (make-hash-table :test 'equal)))
5224 (loop for k in js2-keywords
5225 do (puthash
5226 (symbol-name k) ; instanceof
5227 (intern (concat "js2-"
5228 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5229 table))
5230 table)
5231 "JavaScript keywords by name, mapped to their symbols.")
5232
5233 (defconst js2-reserved-word-names
5234 (let ((table (make-hash-table :test 'equal)))
5235 (loop for k in js2-reserved-words
5236 do
5237 (puthash (symbol-name k) 'js2-RESERVED table))
5238 table)
5239 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5240
5241 (defun js2-collect-string (buf)
5242 "Convert BUF, a list of chars, to a string.
5243 Reverses BUF before converting."
5244 (cond
5245 ((stringp buf)
5246 buf)
5247 ((null buf) ; for emacs21 compat
5248 "")
5249 (t
5250 (if buf
5251 (apply #'string (nreverse buf))
5252 ""))))
5253
5254 (defun js2-string-to-keyword (s)
5255 "Return token for S, a string, if S is a keyword or reserved word.
5256 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5257 (or (gethash s js2-keyword-names)
5258 (gethash s js2-reserved-word-names)))
5259
5260 (defsubst js2-ts-set-char-token-bounds ()
5261 "Used when next token is one character."
5262 (setq js2-token-beg (1- js2-ts-cursor)
5263 js2-token-end js2-ts-cursor))
5264
5265 (defsubst js2-ts-return (token)
5266 "Return an N-character TOKEN from `js2-get-token'.
5267 Updates `js2-token-end' accordingly."
5268 (setq js2-token-end js2-ts-cursor)
5269 (throw 'return token))
5270
5271 (defun js2-x-digit-to-int (c accumulator)
5272 "Build up a hex number.
5273 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5274 corresponding number. Otherwise return -1."
5275 (catch 'return
5276 (catch 'check
5277 ;; Use 0..9 < A..Z < a..z
5278 (cond
5279 ((<= c ?9)
5280 (decf c ?0)
5281 (if (<= 0 c)
5282 (throw 'check nil)))
5283 ((<= c ?F)
5284 (when (<= ?A c)
5285 (decf c (- ?A 10))
5286 (throw 'check nil)))
5287 ((<= c ?f)
5288 (when (<= ?a c)
5289 (decf c (- ?a 10))
5290 (throw 'check nil))))
5291 (throw 'return -1))
5292 (logior c (lsh accumulator 4))))
5293
5294 (defun js2-get-token ()
5295 "Return next JavaScript token, an int such as js2-RETURN."
5296 (let (c c1 identifier-start is-unicode-escape-start
5297 contains-escape escape-val escape-start str result base
5298 is-integer quote-char val look-for-slash continue)
5299 (catch 'return
5300 (while t
5301 ;; Eat whitespace, possibly sensitive to newlines.
5302 (setq continue t)
5303 (while continue
5304 (setq c (js2-get-char))
5305 (cond
5306 ((eq c js2-EOF_CHAR)
5307 (js2-ts-set-char-token-bounds)
5308 (throw 'return js2-EOF))
5309 ((eq c ?\n)
5310 (js2-ts-set-char-token-bounds)
5311 (setq js2-ts-dirty-line nil)
5312 (throw 'return js2-EOL))
5313 ((not (js2-js-space-p c))
5314 (if (/= c ?-) ; in case end of HTML comment
5315 (setq js2-ts-dirty-line t))
5316 (setq continue nil))))
5317 ;; Assume the token will be 1 char - fixed up below.
5318 (js2-ts-set-char-token-bounds)
5319 (when (eq c ?@)
5320 (throw 'return js2-XMLATTR))
5321 ;; identifier/keyword/instanceof?
5322 ;; watch out for starting with a <backslash>
5323 (cond
5324 ((eq c ?\\)
5325 (setq c (js2-get-char))
5326 (if (eq c ?u)
5327 (setq identifier-start t
5328 is-unicode-escape-start t
5329 js2-ts-string-buffer nil)
5330 (setq identifier-start nil)
5331 (js2-unget-char)
5332 (setq c ?\\)))
5333 (t
5334 (when (setq identifier-start (js2-java-identifier-start-p c))
5335 (setq js2-ts-string-buffer nil)
5336 (js2-add-to-string c))))
5337 (when identifier-start
5338 (setq contains-escape is-unicode-escape-start)
5339 (catch 'break
5340 (while t
5341 (if is-unicode-escape-start
5342 ;; strictly speaking we should probably push-back
5343 ;; all the bad characters if the <backslash>uXXXX
5344 ;; sequence is malformed. But since there isn't a
5345 ;; correct context(is there?) for a bad Unicode
5346 ;; escape sequence in an identifier, we can report
5347 ;; an error here.
5348 (progn
5349 (setq escape-val 0)
5350 (dotimes (i 4)
5351 (setq c (js2-get-char)
5352 escape-val (js2-x-digit-to-int c escape-val))
5353 ;; Next check takes care of c < 0 and bad escape
5354 (if (minusp escape-val)
5355 (throw 'break nil)))
5356 (if (minusp escape-val)
5357 (js2-report-scan-error "msg.invalid.escape" t))
5358 (js2-add-to-string escape-val)
5359 (setq is-unicode-escape-start nil))
5360 (setq c (js2-get-char))
5361 (cond
5362 ((eq c ?\\)
5363 (setq c (js2-get-char))
5364 (if (eq c ?u)
5365 (setq is-unicode-escape-start t
5366 contains-escape t)
5367 (js2-report-scan-error "msg.illegal.character" t)))
5368 (t
5369 (if (or (eq c js2-EOF_CHAR)
5370 (not (js2-java-identifier-part-p c)))
5371 (throw 'break nil))
5372 (js2-add-to-string c))))))
5373 (js2-unget-char)
5374 (setq str (js2-get-string-from-buffer))
5375 (unless contains-escape
5376 ;; OPT we shouldn't have to make a string (object!) to
5377 ;; check if it's a keyword.
5378 ;; Return the corresponding token if it's a keyword
5379 (when (setq result (js2-string-to-keyword str))
5380 (if (and (< js2-language-version 170)
5381 (memq result '(js2-LET js2-YIELD)))
5382 ;; LET and YIELD are tokens only in 1.7 and later
5383 (setq result 'js2-NAME))
5384 (if (not (eq result 'js2-RESERVED))
5385 (throw 'return (js2-token-code result)))
5386 (js2-report-warning "msg.reserved.keyword" str)))
5387 ;; If we want to intern these as Rhino does, just use (intern str)
5388 (setq js2-ts-string str)
5389 (throw 'return js2-NAME)) ; end identifier/kwd check
5390 ;; is it a number?
5391 (when (or (js2-digit-p c)
5392 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5393 (setq js2-ts-string-buffer nil
5394 base 10)
5395 (when (eq c ?0)
5396 (setq c (js2-get-char))
5397 (cond
5398 ((or (eq c ?x) (eq c ?X))
5399 (setq base 16)
5400 (setq c (js2-get-char)))
5401 ((js2-digit-p c)
5402 (setq base 8))
5403 (t
5404 (js2-add-to-string ?0))))
5405 (if (eq base 16)
5406 (while (<= 0 (js2-x-digit-to-int c 0))
5407 (js2-add-to-string c)
5408 (setq c (js2-get-char)))
5409 (while (and (<= ?0 c) (<= c ?9))
5410 ;; We permit 08 and 09 as decimal numbers, which
5411 ;; makes our behavior a superset of the ECMA
5412 ;; numeric grammar. We might not always be so
5413 ;; permissive, so we warn about it.
5414 (when (and (eq base 8) (>= c ?8))
5415 (js2-report-warning "msg.bad.octal.literal"
5416 (if (eq c ?8) "8" "9"))
5417 (setq base 10))
5418 (js2-add-to-string c)
5419 (setq c (js2-get-char))))
5420 (setq is-integer t)
5421 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5422 (setq is-integer nil)
5423 (when (eq c ?.)
5424 (loop do
5425 (js2-add-to-string c)
5426 (setq c (js2-get-char))
5427 while (js2-digit-p c)))
5428 (when (memq c '(?e ?E))
5429 (js2-add-to-string c)
5430 (setq c (js2-get-char))
5431 (when (memq c '(?+ ?-))
5432 (js2-add-to-string c)
5433 (setq c (js2-get-char)))
5434 (unless (js2-digit-p c)
5435 (js2-report-scan-error "msg.missing.exponent" t))
5436 (loop do
5437 (js2-add-to-string c)
5438 (setq c (js2-get-char))
5439 while (js2-digit-p c))))
5440 (js2-unget-char)
5441 (setq js2-ts-string (js2-get-string-from-buffer)
5442 js2-ts-number
5443 (if (and (eq base 10) (not is-integer))
5444 (string-to-number js2-ts-string)
5445 ;; TODO: call runtime number-parser. Some of it is in
5446 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5447 (string-to-number js2-ts-string)))
5448 (throw 'return js2-NUMBER))
5449 ;; is it a string?
5450 (when (memq c '(?\" ?\'))
5451 ;; We attempt to accumulate a string the fast way, by
5452 ;; building it directly out of the reader. But if there
5453 ;; are any escaped characters in the string, we revert to
5454 ;; building it out of a string buffer.
5455 (setq quote-char c
5456 js2-ts-string-buffer nil
5457 c (js2-get-char))
5458 (catch 'break
5459 (while (/= c quote-char)
5460 (catch 'continue
5461 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5462 (js2-unget-char)
5463 (setq js2-token-end js2-ts-cursor)
5464 (js2-report-error "msg.unterminated.string.lit")
5465 (throw 'return js2-STRING))
5466 (when (eq c ?\\)
5467 ;; We've hit an escaped character
5468 (setq c (js2-get-char))
5469 (case c
5470 (?b (setq c ?\b))
5471 (?f (setq c ?\f))
5472 (?n (setq c ?\n))
5473 (?r (setq c ?\r))
5474 (?t (setq c ?\t))
5475 (?v (setq c ?\v))
5476 (?u
5477 (setq c1 (js2-read-unicode-escape))
5478 (if js2-parse-ide-mode
5479 (if c1
5480 (progn
5481 ;; just copy the string in IDE-mode
5482 (js2-add-to-string ?\\)
5483 (js2-add-to-string ?u)
5484 (dotimes (i 3)
5485 (js2-add-to-string (js2-get-char)))
5486 (setq c (js2-get-char))) ; added at end of loop
5487 ;; flag it as an invalid escape
5488 (js2-report-warning "msg.invalid.escape"
5489 nil (- js2-ts-cursor 2) 6))
5490 ;; Get 4 hex digits; if the u escape is not
5491 ;; followed by 4 hex digits, use 'u' + the
5492 ;; literal character sequence that follows.
5493 (js2-add-to-string ?u)
5494 (setq escape-val 0)
5495 (dotimes (i 4)
5496 (setq c (js2-get-char)
5497 escape-val (js2-x-digit-to-int c escape-val))
5498 (if (minusp escape-val)
5499 (throw 'continue nil))
5500 (js2-add-to-string c))
5501 ;; prepare for replace of stored 'u' sequence by escape value
5502 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5503 c escape-val)))
5504 (?x
5505 ;; Get 2 hex digits, defaulting to 'x'+literal
5506 ;; sequence, as above.
5507 (setq c (js2-get-char)
5508 escape-val (js2-x-digit-to-int c 0))
5509 (if (minusp escape-val)
5510 (progn
5511 (js2-add-to-string ?x)
5512 (throw 'continue nil))
5513 (setq c1 c
5514 c (js2-get-char)
5515 escape-val (js2-x-digit-to-int c escape-val))
5516 (if (minusp escape-val)
5517 (progn
5518 (js2-add-to-string ?x)
5519 (js2-add-to-string c1)
5520 (throw 'continue nil))
5521 ;; got 2 hex digits
5522 (setq c escape-val))))
5523 (?\n
5524 ;; Remove line terminator after escape to follow
5525 ;; SpiderMonkey and C/C++
5526 (setq c (js2-get-char))
5527 (throw 'continue nil))
5528 (t
5529 (when (and (<= ?0 c) (< c ?8))
5530 (setq val (- c ?0)
5531 c (js2-get-char))
5532 (when (and (<= ?0 c) (< c ?8))
5533 (setq val (- (+ (* 8 val) c) ?0)
5534 c (js2-get-char))
5535 (when (and (<= ?0 c)
5536 (< c ?8)
5537 (< val #o37))
5538 ;; c is 3rd char of octal sequence only
5539 ;; if the resulting val <= 0377
5540 (setq val (- (+ (* 8 val) c) ?0)
5541 c (js2-get-char))))
5542 (js2-unget-char)
5543 (setq c val)))))
5544 (js2-add-to-string c)
5545 (setq c (js2-get-char)))))
5546 (setq js2-ts-string (js2-get-string-from-buffer))
5547 (throw 'return js2-STRING))
5548 (case c
5549 (?\;
5550 (throw 'return js2-SEMI))
5551 (?\[
5552 (throw 'return js2-LB))
5553 (?\]
5554 (throw 'return js2-RB))
5555 (?{
5556 (throw 'return js2-LC))
5557 (?}
5558 (throw 'return js2-RC))
5559 (?\(
5560 (throw 'return js2-LP))
5561 (?\)
5562 (throw 'return js2-RP))
5563 (?,
5564 (throw 'return js2-COMMA))
5565 (??
5566 (throw 'return js2-HOOK))
5567 (?:
5568 (if (js2-match-char ?:)
5569 (js2-ts-return js2-COLONCOLON)
5570 (throw 'return js2-COLON)))
5571 (?.
5572 (if (js2-match-char ?.)
5573 (if (js2-match-char ?.)
5574 (js2-ts-return js2-TRIPLEDOT)
5575 (js2-ts-return js2-DOTDOT))
5576 (if (js2-match-char ?\()
5577 (js2-ts-return js2-DOTQUERY)
5578 (throw 'return js2-DOT))))
5579 (?|
5580 (if (js2-match-char ?|)
5581 (throw 'return js2-OR)
5582 (if (js2-match-char ?=)
5583 (js2-ts-return js2-ASSIGN_BITOR)
5584 (throw 'return js2-BITOR))))
5585 (?^
5586 (if (js2-match-char ?=)
5587 (js2-ts-return js2-ASSIGN_BITOR)
5588 (throw 'return js2-BITXOR)))
5589 (?&
5590 (if (js2-match-char ?&)
5591 (throw 'return js2-AND)
5592 (if (js2-match-char ?=)
5593 (js2-ts-return js2-ASSIGN_BITAND)
5594 (throw 'return js2-BITAND))))
5595 (?=
5596 (if (js2-match-char ?=)
5597 (if (js2-match-char ?=)
5598 (js2-ts-return js2-SHEQ)
5599 (throw 'return js2-EQ))
5600 (throw 'return js2-ASSIGN)))
5601 (?!
5602 (if (js2-match-char ?=)
5603 (if (js2-match-char ?=)
5604 (js2-ts-return js2-SHNE)
5605 (js2-ts-return js2-NE))
5606 (throw 'return js2-NOT)))
5607 (?<
5608 ;; NB:treat HTML begin-comment as comment-till-eol
5609 (when (js2-match-char ?!)
5610 (when (js2-match-char ?-)
5611 (when (js2-match-char ?-)
5612 (js2-skip-line)
5613 (setq js2-ts-comment-type 'html)
5614 (throw 'return js2-COMMENT)))
5615 (js2-unget-char))
5616 (if (js2-match-char ?<)
5617 (if (js2-match-char ?=)
5618 (js2-ts-return js2-ASSIGN_LSH)
5619 (js2-ts-return js2-LSH))
5620 (if (js2-match-char ?=)
5621 (js2-ts-return js2-LE)
5622 (throw 'return js2-LT))))
5623 (?>
5624 (if (js2-match-char ?>)
5625 (if (js2-match-char ?>)
5626 (if (js2-match-char ?=)
5627 (js2-ts-return js2-ASSIGN_URSH)
5628 (js2-ts-return js2-URSH))
5629 (if (js2-match-char ?=)
5630 (js2-ts-return js2-ASSIGN_RSH)
5631 (js2-ts-return js2-RSH)))
5632 (if (js2-match-char ?=)
5633 (js2-ts-return js2-GE)
5634 (throw 'return js2-GT))))
5635 (?*
5636 (if (js2-match-char ?=)
5637 (js2-ts-return js2-ASSIGN_MUL)
5638 (throw 'return js2-MUL)))
5639 (?/
5640 ;; is it a // comment?
5641 (when (js2-match-char ?/)
5642 (setq js2-token-beg (- js2-ts-cursor 2))
5643 (js2-skip-line)
5644 (setq js2-ts-comment-type 'line)
5645 ;; include newline so highlighting goes to end of window
5646 (incf js2-token-end)
5647 (throw 'return js2-COMMENT))
5648 ;; is it a /* comment?
5649 (when (js2-match-char ?*)
5650 (setq look-for-slash nil
5651 js2-token-beg (- js2-ts-cursor 2)
5652 js2-ts-comment-type
5653 (if (js2-match-char ?*)
5654 (progn
5655 (setq look-for-slash t)
5656 'jsdoc)
5657 'block))
5658 (while t
5659 (setq c (js2-get-char))
5660 (cond
5661 ((eq c js2-EOF_CHAR)
5662 (setq js2-token-end (1- js2-ts-cursor))
5663 (js2-report-error "msg.unterminated.comment")
5664 (throw 'return js2-COMMENT))
5665 ((eq c ?*)
5666 (setq look-for-slash t))
5667 ((eq c ?/)
5668 (if look-for-slash
5669 (js2-ts-return js2-COMMENT)))
5670 (t
5671 (setq look-for-slash nil
5672 js2-token-end js2-ts-cursor)))))
5673 (if (js2-match-char ?=)
5674 (js2-ts-return js2-ASSIGN_DIV)
5675 (throw 'return js2-DIV)))
5676 (?#
5677 (when js2-skip-preprocessor-directives
5678 (js2-skip-line)
5679 (setq js2-ts-comment-type 'preprocessor
5680 js2-token-end js2-ts-cursor)
5681 (throw 'return js2-COMMENT))
5682 (throw 'return js2-ERROR))
5683 (?%
5684 (if (js2-match-char ?=)
5685 (js2-ts-return js2-ASSIGN_MOD)
5686 (throw 'return js2-MOD)))
5687 (?~
5688 (throw 'return js2-BITNOT))
5689 (?+
5690 (if (js2-match-char ?=)
5691 (js2-ts-return js2-ASSIGN_ADD)
5692 (if (js2-match-char ?+)
5693 (js2-ts-return js2-INC)
5694 (throw 'return js2-ADD))))
5695 (?-
5696 (cond
5697 ((js2-match-char ?=)
5698 (setq c js2-ASSIGN_SUB))
5699 ((js2-match-char ?-)
5700 (unless js2-ts-dirty-line
5701 ;; treat HTML end-comment after possible whitespace
5702 ;; after line start as comment-until-eol
5703 (when (js2-match-char ?>)
5704 (js2-skip-line)
5705 (setq js2-ts-comment-type 'html)
5706 (throw 'return js2-COMMENT)))
5707 (setq c js2-DEC))
5708 (t
5709 (setq c js2-SUB)))
5710 (setq js2-ts-dirty-line t)
5711 (js2-ts-return c))
5712 (otherwise
5713 (js2-report-scan-error "msg.illegal.character")))))))
5714
5715 (defun js2-read-regexp (start-token)
5716 "Called by parser when it gets / or /= in literal context."
5717 (let (c err
5718 in-class ; inside a '[' .. ']' character-class
5719 flags
5720 (continue t))
5721 (setq js2-token-beg js2-ts-cursor
5722 js2-ts-string-buffer nil
5723 js2-ts-regexp-flags nil)
5724 (if (eq start-token js2-ASSIGN_DIV)
5725 ;; mis-scanned /=
5726 (js2-add-to-string ?=)
5727 (if (not (eq start-token js2-DIV))
5728 (error "failed assertion")))
5729 (while (and (not err)
5730 (or (/= (setq c (js2-get-char)) ?/)
5731 in-class))
5732 (cond
5733 ((or (= c ?\n)
5734 (= c js2-EOF_CHAR))
5735 (setq js2-token-end (1- js2-ts-cursor)
5736 err t
5737 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5738 (js2-report-error "msg.unterminated.re.lit"))
5739 (t (cond
5740 ((= c ?\\)
5741 (js2-add-to-string c)
5742 (setq c (js2-get-char)))
5743 ((= c ?\[)
5744 (setq in-class t))
5745 ((= c ?\])
5746 (setq in-class nil)))
5747 (js2-add-to-string c))))
5748 (unless err
5749 (while continue
5750 (cond
5751 ((js2-match-char ?g)
5752 (push ?g flags))
5753 ((js2-match-char ?i)
5754 (push ?i flags))
5755 ((js2-match-char ?m)
5756 (push ?m flags))
5757 (t
5758 (setq continue nil))))
5759 (if (js2-alpha-p (js2-peek-char))
5760 (js2-report-scan-error "msg.invalid.re.flag" t
5761 js2-ts-cursor 1))
5762 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5763 js2-ts-regexp-flags (js2-collect-string flags)
5764 js2-token-end js2-ts-cursor)
5765 ;; tell `parse-partial-sexp' to ignore this range of chars
5766 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
5767
5768 (defun js2-get-first-xml-token ()
5769 (setq js2-ts-xml-open-tags-count 0
5770 js2-ts-is-xml-attribute nil
5771 js2-ts-xml-is-tag-content nil)
5772 (js2-unget-char)
5773 (js2-get-next-xml-token))
5774
5775 (defun js2-xml-discard-string ()
5776 "Throw away the string in progress and flag an XML parse error."
5777 (setq js2-ts-string-buffer nil
5778 js2-ts-string nil)
5779 (js2-report-scan-error "msg.XML.bad.form" t))
5780
5781 (defun js2-get-next-xml-token ()
5782 (setq js2-ts-string-buffer nil ; for recording the XML
5783 js2-token-beg js2-ts-cursor)
5784 (let (c result)
5785 (setq result
5786 (catch 'return
5787 (while t
5788 (setq c (js2-get-char))
5789 (cond
5790 ((= c js2-EOF_CHAR)
5791 (throw 'return js2-ERROR))
5792 (js2-ts-xml-is-tag-content
5793 (case c
5794 (?>
5795 (js2-add-to-string c)
5796 (setq js2-ts-xml-is-tag-content nil
5797 js2-ts-is-xml-attribute nil))
5798 (?/
5799 (js2-add-to-string c)
5800 (when (eq ?> (js2-peek-char))
5801 (setq c (js2-get-char))
5802 (js2-add-to-string c)
5803 (setq js2-ts-xml-is-tag-content nil)
5804 (decf js2-ts-xml-open-tags-count)))
5805 (?{
5806 (js2-unget-char)
5807 (setq js2-ts-string (js2-get-string-from-buffer))
5808 (throw 'return js2-XML))
5809 ((?\' ?\")
5810 (js2-add-to-string c)
5811 (unless (js2-read-quoted-string c)
5812 (throw 'return js2-ERROR)))
5813 (?=
5814 (js2-add-to-string c)
5815 (setq js2-ts-is-xml-attribute t))
5816 ((? ?\t ?\r ?\n)
5817 (js2-add-to-string c))
5818 (t
5819 (js2-add-to-string c)
5820 (setq js2-ts-is-xml-attribute nil)))
5821 (when (and (not js2-ts-xml-is-tag-content)
5822 (zerop js2-ts-xml-open-tags-count))
5823 (setq js2-ts-string (js2-get-string-from-buffer))
5824 (throw 'return js2-XMLEND)))
5825 (t
5826 ;; else not tag content
5827 (case c
5828 (?<
5829 (js2-add-to-string c)
5830 (setq c (js2-peek-char))
5831 (case c
5832 (?!
5833 (setq c (js2-get-char)) ;; skip !
5834 (js2-add-to-string c)
5835 (setq c (js2-peek-char))
5836 (case c
5837 (?-
5838 (setq c (js2-get-char)) ;; skip -
5839 (js2-add-to-string c)
5840 (if (eq c ?-)
5841 (progn
5842 (js2-add-to-string c)
5843 (unless (js2-read-xml-comment)
5844 (throw 'return js2-ERROR)))
5845 (js2-xml-discard-string)
5846 (throw 'return js2-ERROR)))
5847 (?\[
5848 (setq c (js2-get-char)) ;; skip [
5849 (js2-add-to-string c)
5850 (if (and (= (js2-get-char) ?C)
5851 (= (js2-get-char) ?D)
5852 (= (js2-get-char) ?A)
5853 (= (js2-get-char) ?T)
5854 (= (js2-get-char) ?A)
5855 (= (js2-get-char) ?\[))
5856 (progn
5857 (js2-add-to-string ?C)
5858 (js2-add-to-string ?D)
5859 (js2-add-to-string ?A)
5860 (js2-add-to-string ?T)
5861 (js2-add-to-string ?A)
5862 (js2-add-to-string ?\[)
5863 (unless (js2-read-cdata)
5864 (throw 'return js2-ERROR)))
5865 (js2-xml-discard-string)
5866 (throw 'return js2-ERROR)))
5867 (t
5868 (unless (js2-read-entity)
5869 (throw 'return js2-ERROR))))
5870 ;; Allow bare CDATA section, e.g.:
5871 ;; let xml = <![CDATA[ foo bar baz ]]>;
5872 (when (zerop js2-ts-xml-open-tags-count)
5873 (throw 'return js2-XMLEND)))
5874 (??
5875 (setq c (js2-get-char)) ;; skip ?
5876 (js2-add-to-string c)
5877 (unless (js2-read-PI)
5878 (throw 'return js2-ERROR)))
5879 (?/
5880 ;; end tag
5881 (setq c (js2-get-char)) ;; skip /
5882 (js2-add-to-string c)
5883 (when (zerop js2-ts-xml-open-tags-count)
5884 (js2-xml-discard-string)
5885 (throw 'return js2-ERROR))
5886 (setq js2-ts-xml-is-tag-content t)
5887 (decf js2-ts-xml-open-tags-count))
5888 (t
5889 ;; start tag
5890 (setq js2-ts-xml-is-tag-content t)
5891 (incf js2-ts-xml-open-tags-count))))
5892 (?{
5893 (js2-unget-char)
5894 (setq js2-ts-string (js2-get-string-from-buffer))
5895 (throw 'return js2-XML))
5896 (t
5897 (js2-add-to-string c))))))))
5898 (setq js2-token-end js2-ts-cursor)
5899 result))
5900
5901 (defun js2-read-quoted-string (quote)
5902 (let (c)
5903 (catch 'return
5904 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
5905 (js2-add-to-string c)
5906 (if (eq c quote)
5907 (throw 'return t)))
5908 (js2-xml-discard-string) ;; throw away string in progress
5909 nil)))
5910
5911 (defun js2-read-xml-comment ()
5912 (let ((c (js2-get-char)))
5913 (catch 'return
5914 (while (/= c js2-EOF_CHAR)
5915 (catch 'continue
5916 (js2-add-to-string c)
5917 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
5918 (setq c (js2-get-char))
5919 (js2-add-to-string c)
5920 (if (eq (js2-peek-char) ?>)
5921 (progn
5922 (setq c (js2-get-char)) ;; skip >
5923 (js2-add-to-string c)
5924 (throw 'return t))
5925 (throw 'continue nil)))
5926 (setq c (js2-get-char))))
5927 (js2-xml-discard-string)
5928 nil)))
5929
5930 (defun js2-read-cdata ()
5931 (let ((c (js2-get-char)))
5932 (catch 'return
5933 (while (/= c js2-EOF_CHAR)
5934 (catch 'continue
5935 (js2-add-to-string c)
5936 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
5937 (setq c (js2-get-char))
5938 (js2-add-to-string c)
5939 (if (eq (js2-peek-char) ?>)
5940 (progn
5941 (setq c (js2-get-char)) ;; Skip >
5942 (js2-add-to-string c)
5943 (throw 'return t))
5944 (throw 'continue nil)))
5945 (setq c (js2-get-char))))
5946 (js2-xml-discard-string)
5947 nil)))
5948
5949 (defun js2-read-entity ()
5950 (let ((decl-tags 1)
5951 c)
5952 (catch 'return
5953 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
5954 (js2-add-to-string c)
5955 (case c
5956 (?<
5957 (incf decl-tags))
5958 (?>
5959 (decf decl-tags)
5960 (if (zerop decl-tags)
5961 (throw 'return t)))))
5962 (js2-xml-discard-string)
5963 nil)))
5964
5965 (defun js2-read-PI ()
5966 "Scan an XML processing instruction."
5967 (let (c)
5968 (catch 'return
5969 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
5970 (js2-add-to-string c)
5971 (when (and (eq c ??) (eq (js2-peek-char) ?>))
5972 (setq c (js2-get-char)) ;; Skip >
5973 (js2-add-to-string c)
5974 (throw 'return t)))
5975 (js2-xml-discard-string)
5976 nil)))
5977
5978 ;;; Highlighting
5979
5980 (defun js2-set-face (beg end face &optional record)
5981 "Fontify a region. If RECORD is non-nil, record for later."
5982 (when (plusp js2-highlight-level)
5983 (setq beg (min (point-max) beg)
5984 beg (max (point-min) beg)
5985 end (min (point-max) end)
5986 end (max (point-min) end))
5987 (if record
5988 (push (list beg end face) js2-mode-fontifications)
5989 (put-text-property beg end 'font-lock-face face))))
5990
5991 (defsubst js2-clear-face (beg end)
5992 (remove-text-properties beg end '(font-lock-face nil
5993 help-echo nil
5994 point-entered nil
5995 c-in-sws nil)))
5996
5997 (defconst js2-ecma-global-props
5998 (concat "^"
5999 (regexp-opt
6000 '("Infinity" "NaN" "undefined" "arguments") t)
6001 "$")
6002 "Value properties of the Ecma-262 Global Object.
6003 Shown at or above `js2-highlight-level' 2.")
6004
6005 ;; might want to add the name "arguments" to this list?
6006 (defconst js2-ecma-object-props
6007 (concat "^"
6008 (regexp-opt
6009 '("prototype" "__proto__" "__parent__") t)
6010 "$")
6011 "Value properties of the Ecma-262 Object constructor.
6012 Shown at or above `js2-highlight-level' 2.")
6013
6014 (defconst js2-ecma-global-funcs
6015 (concat
6016 "^"
6017 (regexp-opt
6018 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6019 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6020 "$")
6021 "Function properties of the Ecma-262 Global object.
6022 Shown at or above `js2-highlight-level' 2.")
6023
6024 (defconst js2-ecma-number-props
6025 (concat "^"
6026 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6027 "NEGATIVE_INFINITY"
6028 "POSITIVE_INFINITY") t)
6029 "$")
6030 "Properties of the Ecma-262 Number constructor.
6031 Shown at or above `js2-highlight-level' 2.")
6032
6033 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6034 "Properties of the Ecma-262 Date constructor.
6035 Shown at or above `js2-highlight-level' 2.")
6036
6037 (defconst js2-ecma-math-props
6038 (concat "^"
6039 (regexp-opt
6040 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6041 t)
6042 "$")
6043 "Properties of the Ecma-262 Math object.
6044 Shown at or above `js2-highlight-level' 2.")
6045
6046 (defconst js2-ecma-math-funcs
6047 (concat "^"
6048 (regexp-opt
6049 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6050 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6051 "$")
6052 "Function properties of the Ecma-262 Math object.
6053 Shown at or above `js2-highlight-level' 2.")
6054
6055 (defconst js2-ecma-function-props
6056 (concat
6057 "^"
6058 (regexp-opt
6059 '(;; properties of the Object prototype object
6060 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6061 "toLocaleString" "toString" "valueOf"
6062 ;; properties of the Function prototype object
6063 "apply" "call"
6064 ;; properties of the Array prototype object
6065 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6066 "splice" "unshift"
6067 ;; properties of the String prototype object
6068 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6069 "localeCompare" "match" "replace" "search" "split" "substring"
6070 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6071 "toUpperCase"
6072 ;; properties of the Number prototype object
6073 "toExponential" "toFixed" "toPrecision"
6074 ;; properties of the Date prototype object
6075 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6076 "getMinutes" "getMonth" "getSeconds" "getTime"
6077 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6078 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6079 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6080 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6081 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6082 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6083 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6084 "toTimeString" "toUTCString"
6085 ;; properties of the RegExp prototype object
6086 "exec" "test"
6087 ;; properties of the JSON prototype object
6088 "parse" "stringify"
6089 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6090 "toSource" "__defineGetter__" "__defineSetter__"
6091 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6092 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6093 t)
6094 "$")
6095 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6096 Shown at or above `js2-highlight-level' 3.")
6097
6098 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6099 (let ((target-name (and target
6100 (js2-name-node-p target)
6101 (js2-name-node-name target)))
6102 (prop-name (if prop (js2-name-node-name prop)))
6103 (level1 (>= js2-highlight-level 1))
6104 (level2 (>= js2-highlight-level 2))
6105 (level3 (>= js2-highlight-level 3))
6106 pos face)
6107 (when level2
6108 (if call-p
6109 (cond
6110 ((and target prop)
6111 (cond
6112 ((and level3 (string-match js2-ecma-function-props prop-name))
6113 (setq face 'font-lock-builtin-face))
6114 ((and target-name prop)
6115 (cond
6116 ((string= target-name "Date")
6117 (if (string-match js2-ecma-date-props prop-name)
6118 (setq face 'font-lock-builtin-face)))
6119 ((string= target-name "Math")
6120 (if (string-match js2-ecma-math-funcs prop-name)
6121 (setq face 'font-lock-builtin-face)))))))
6122 (prop
6123 (if (string-match js2-ecma-global-funcs prop-name)
6124 (setq face 'font-lock-builtin-face))))
6125 (cond
6126 ((and target prop)
6127 (cond
6128 ((string= target-name "Number")
6129 (if (string-match js2-ecma-number-props prop-name)
6130 (setq face 'font-lock-constant-face)))
6131 ((string= target-name "Math")
6132 (if (string-match js2-ecma-math-props prop-name)
6133 (setq face 'font-lock-constant-face)))))
6134 (prop
6135 (if (string-match js2-ecma-object-props prop-name)
6136 (setq face 'font-lock-constant-face)))))
6137 (when face
6138 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6139 (js2-node-pos prop))) ; relative
6140 (+ pos (js2-node-len prop))
6141 face 'record)))))
6142
6143 (defun js2-parse-highlight-member-expr-node (node)
6144 "Perform syntax highlighting of EcmaScript built-in properties.
6145 The variable `js2-highlight-level' governs this highighting."
6146 (let (face target prop name pos end parent call-p callee)
6147 (cond
6148 ;; case 1: simple name, e.g. foo
6149 ((js2-name-node-p node)
6150 (setq name (js2-name-node-name node))
6151 ;; possible for name to be nil in rare cases - saw it when
6152 ;; running js2-mode on an elisp buffer. Might as well try to
6153 ;; make it so js2-mode never barfs.
6154 (when name
6155 (setq face (if (string-match js2-ecma-global-props name)
6156 'font-lock-constant-face))
6157 (when face
6158 (setq pos (js2-node-pos node)
6159 end (+ pos (js2-node-len node)))
6160 (js2-set-face pos end face 'record))))
6161 ;; case 2: property access or function call
6162 ((or (js2-prop-get-node-p node)
6163 ;; highlight function call if expr is a prop-get node
6164 ;; or a plain name (i.e. unqualified function call)
6165 (and (setq call-p (js2-call-node-p node))
6166 (setq callee (js2-call-node-target node)) ; separate setq!
6167 (or (js2-prop-get-node-p callee)
6168 (js2-name-node-p callee))))
6169 (setq parent node
6170 node (if call-p callee node))
6171 (if (and call-p (js2-name-node-p callee))
6172 (setq prop callee)
6173 (setq target (js2-prop-get-node-left node)
6174 prop (js2-prop-get-node-right node)))
6175 (cond
6176 ((js2-name-node-p target)
6177 (if (js2-name-node-p prop)
6178 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6179 (js2-parse-highlight-prop-get parent target prop call-p)
6180 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6181 (js2-parse-highlight-prop-get parent target nil call-p)))
6182 ((js2-name-node-p prop)
6183 ;; case 2c: complex target, simple name, e.g. x[y].bar
6184 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6185
6186 (defun js2-parse-highlight-member-expr-fn-name (expr)
6187 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6188 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6189 We currently only handle the case where the last component is a prop-get
6190 of a simple name. Called before EXPR has a parent node."
6191 (let (pos
6192 (name (and (js2-prop-get-node-p expr)
6193 (js2-prop-get-node-right expr))))
6194 (when (js2-name-node-p name)
6195 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6196 (js2-node-pos name)))
6197 (+ pos (js2-node-len name))
6198 'font-lock-function-name-face
6199 'record))))
6200
6201 ;; source: http://jsdoc.sourceforge.net/
6202 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6203 ;; allows type specifications, and needs work before entering the wild.
6204
6205 (defconst js2-jsdoc-param-tag-regexp
6206 (concat "^\\s-*\\*+\\s-*\\(@"
6207 "\\(?:param\\|argument\\)"
6208 "\\)"
6209 "\\s-*\\({[^}]+}\\)?" ; optional type
6210 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6211 "\\>")
6212 "Matches jsdoc tags with optional type and optional param name.")
6213
6214 (defconst js2-jsdoc-typed-tag-regexp
6215 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6216 (regexp-opt
6217 '("enum"
6218 "extends"
6219 "field"
6220 "id"
6221 "implements"
6222 "lends"
6223 "mods"
6224 "requires"
6225 "return"
6226 "returns"
6227 "throw"
6228 "throws"))
6229 "\\)\\)\\s-*\\({[^}]+}\\)?")
6230 "Matches jsdoc tags with optional type.")
6231
6232 (defconst js2-jsdoc-arg-tag-regexp
6233 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6234 (regexp-opt
6235 '("alias"
6236 "augments"
6237 "borrows"
6238 "bug"
6239 "base"
6240 "config"
6241 "default"
6242 "define"
6243 "exception"
6244 "function"
6245 "member"
6246 "memberOf"
6247 "name"
6248 "namespace"
6249 "property"
6250 "since"
6251 "suppress"
6252 "this"
6253 "throws"
6254 "type"
6255 "version"))
6256 "\\)\\)\\s-+\\([^ \t]+\\)")
6257 "Matches jsdoc tags with a single argument.")
6258
6259 (defconst js2-jsdoc-empty-tag-regexp
6260 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6261 (regexp-opt
6262 '("addon"
6263 "author"
6264 "class"
6265 "const"
6266 "constant"
6267 "constructor"
6268 "constructs"
6269 "deprecated"
6270 "desc"
6271 "description"
6272 "event"
6273 "example"
6274 "exec"
6275 "export"
6276 "fileoverview"
6277 "final"
6278 "function"
6279 "hidden"
6280 "ignore"
6281 "implicitCast"
6282 "inheritDoc"
6283 "inner"
6284 "interface"
6285 "license"
6286 "noalias"
6287 "noshadow"
6288 "notypecheck"
6289 "override"
6290 "owner"
6291 "preserve"
6292 "preserveTry"
6293 "private"
6294 "protected"
6295 "public"
6296 "static"
6297 "supported"
6298 ))
6299 "\\)\\)\\s-*")
6300 "Matches empty jsdoc tags.")
6301
6302 (defconst js2-jsdoc-link-tag-regexp
6303 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6304 "Matches a jsdoc link or code tag.")
6305
6306 (defconst js2-jsdoc-see-tag-regexp
6307 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6308 "Matches a jsdoc @see tag.")
6309
6310 (defconst js2-jsdoc-html-tag-regexp
6311 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6312 "Matches a simple (no attributes) html start- or end-tag.")
6313
6314 (defun js2-jsdoc-highlight-helper ()
6315 (js2-set-face (match-beginning 1)
6316 (match-end 1)
6317 'js2-jsdoc-tag)
6318 (if (match-beginning 2)
6319 (if (save-excursion
6320 (goto-char (match-beginning 2))
6321 (= (char-after) ?{))
6322 (js2-set-face (1+ (match-beginning 2))
6323 (1- (match-end 2))
6324 'js2-jsdoc-type)
6325 (js2-set-face (match-beginning 2)
6326 (match-end 2)
6327 'js2-jsdoc-value)))
6328 (if (match-beginning 3)
6329 (js2-set-face (match-beginning 3)
6330 (match-end 3)
6331 'js2-jsdoc-value)))
6332
6333 (defun js2-highlight-jsdoc (ast)
6334 "Highlight doc comment tags."
6335 (let ((comments (js2-ast-root-comments ast))
6336 beg end)
6337 (save-excursion
6338 (dolist (node comments)
6339 (when (eq (js2-comment-node-format node) 'jsdoc)
6340 (setq beg (js2-node-abs-pos node)
6341 end (+ beg (js2-node-len node)))
6342 (save-restriction
6343 (narrow-to-region beg end)
6344 (dolist (re (list js2-jsdoc-param-tag-regexp
6345 js2-jsdoc-typed-tag-regexp
6346 js2-jsdoc-arg-tag-regexp
6347 js2-jsdoc-link-tag-regexp
6348 js2-jsdoc-see-tag-regexp
6349 js2-jsdoc-empty-tag-regexp))
6350 (goto-char beg)
6351 (while (re-search-forward re nil t)
6352 (js2-jsdoc-highlight-helper)))
6353 ;; simple highlighting for html tags
6354 (goto-char beg)
6355 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6356 (js2-set-face (match-beginning 1)
6357 (match-end 1)
6358 'js2-jsdoc-html-tag-delimiter)
6359 (js2-set-face (match-beginning 2)
6360 (match-end 2)
6361 'js2-jsdoc-html-tag-name)
6362 (js2-set-face (match-beginning 3)
6363 (match-end 3)
6364 'js2-jsdoc-html-tag-delimiter))))))))
6365
6366 (defun js2-highlight-assign-targets (node left right)
6367 "Highlight function properties and external variables."
6368 (let (leftpos end name)
6369 ;; highlight vars and props assigned function values
6370 (when (js2-function-node-p right)
6371 (cond
6372 ;; var foo = function() {...}
6373 ((js2-name-node-p left)
6374 (setq name left))
6375 ;; foo.bar.baz = function() {...}
6376 ((and (js2-prop-get-node-p left)
6377 (js2-name-node-p (js2-prop-get-node-right left)))
6378 (setq name (js2-prop-get-node-right left))))
6379 (when name
6380 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6381 (+ leftpos (js2-node-len name))
6382 'font-lock-function-name-face
6383 'record)))))
6384
6385 (defun js2-record-name-node (node)
6386 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6387 later. NODE must be a name node."
6388 (let (leftpos end)
6389 (push (list node js2-current-scope
6390 (setq leftpos (js2-node-abs-pos node))
6391 (setq end (+ leftpos (js2-node-len node))))
6392 js2-recorded-identifiers)))
6393
6394 (defun js2-highlight-undeclared-vars ()
6395 "After entire parse is finished, look for undeclared variable references.
6396 We have to wait until entire buffer is parsed, since JavaScript permits var
6397 decls to occur after they're used.
6398
6399 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6400 it is considered declared."
6401 (let (name)
6402 (dolist (entry js2-recorded-identifiers)
6403 (destructuring-bind (name-node scope pos end) entry
6404 (setq name (js2-name-node-name name-node))
6405 (unless (or (member name js2-global-externs)
6406 (member name js2-default-externs)
6407 (member name js2-additional-externs)
6408 (js2-get-defining-scope scope name))
6409 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6410 'js2-external-variable))))
6411 (setq js2-recorded-identifiers nil)))
6412
6413 ;;; IMenu support
6414
6415 ;; We currently only support imenu, but eventually should support speedbar and
6416 ;; possibly other browsing mechanisms.
6417
6418 ;; The basic strategy is to identify function assignment targets of the form
6419 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6420 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6421 ;; for imenu after parsing is finished.
6422
6423 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6424 ;; JavaScript, and the general problem is undecidable. However, several forms
6425 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6426 ;; include:
6427
6428 ;; function foo() -- function declaration
6429 ;; foo = function() -- function expression assigned to variable
6430 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6431 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6432 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6433 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6434 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6435 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6436 ;; function foo() {function bar() {...}} -- nested function
6437 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6438
6439 ;; This list boils down to a few forms that can be combined recursively.
6440 ;; Top-level named function declarations include both the left-hand (name)
6441 ;; and the right-hand (function value) expressions needed to produce an imenu
6442 ;; entry. The other "right-hand" forms we need to look for are:
6443 ;; - functions declared as props/getters/setters in object literals
6444 ;; - nested named function declarations
6445 ;; The "left-hand" expressions that functions can be assigned to include:
6446 ;; - local/global variables
6447 ;; - nested property-get expressions like a.b.c.d
6448 ;; - element gets like foo[10] or foo['bar'] where the index
6449 ;; expression can be trivially converted to a property name. They
6450 ;; effectively then become property gets.
6451
6452 ;; All the different definition types are canonicalized into the form
6453 ;; foo.bar.baz = position-of-function-keyword
6454
6455 ;; We need to build a trie-like structure for imenu. As an example,
6456 ;; consider the following JavaScript code:
6457
6458 ;; a = function() {...} // function at position 5
6459 ;; b = function() {...} // function at position 25
6460 ;; foo = function() {...} // function at position 100
6461 ;; foo.bar = function() {...} // function at position 200
6462 ;; foo.bar.baz = function() {...} // function at position 300
6463 ;; foo.bar.zab = function() {...} // function at position 400
6464
6465 ;; During parsing we accumulate an entry for each definition in
6466 ;; the variable `js2-imenu-recorder', like so:
6467
6468 ;; '((fn a 5)
6469 ;; (fn b 25)
6470 ;; (fn foo 100)
6471 ;; (fn foo bar 200)
6472 ;; (fn foo bar baz 300)
6473 ;; (fn foo bar zab 400))
6474
6475 ;; Where 'fn' is the respective function node.
6476 ;; After parsing these entries are merged into this alist-trie:
6477
6478 ;; '((a . 1)
6479 ;; (b . 2)
6480 ;; (foo (<definition> . 3)
6481 ;; (bar (<definition> . 6)
6482 ;; (baz . 100)
6483 ;; (zab . 200))))
6484
6485 ;; Note the wacky need for a <definition> name. The token can be anything
6486 ;; that isn't a valid JavaScript identifier, because you might make foo
6487 ;; a function and then start setting properties on it that are also functions.
6488
6489 (defun js2-prop-node-name (node)
6490 "Return the name of a node that may be a property-get/property-name.
6491 If NODE is not a valid name-node, string-node or integral number-node,
6492 returns nil. Otherwise returns the string name/value of the node."
6493 (cond
6494 ((js2-name-node-p node)
6495 (js2-name-node-name node))
6496 ((js2-string-node-p node)
6497 (js2-string-node-value node))
6498 ((and (js2-number-node-p node)
6499 (string-match "^[0-9]+$" (js2-number-node-value node)))
6500 (js2-number-node-value node))
6501 ((js2-this-node-p node)
6502 "this")))
6503
6504 (defun js2-node-qname-component (node)
6505 "Return the name of this node, if it contributes to a qname.
6506 Returns nil if the node doesn't contribute."
6507 (copy-sequence
6508 (or (js2-prop-node-name node)
6509 (if (and (js2-function-node-p node)
6510 (js2-function-node-name node))
6511 (js2-name-node-name (js2-function-node-name node))))))
6512
6513 (defun js2-record-imenu-entry (fn-node qname pos)
6514 "Add an entry to `js2-imenu-recorder'.
6515 FN-NODE should be the current item's function node.
6516
6517 Associate FN-NODE with its QNAME for later lookup.
6518 This is used in postprocessing the chain list. For each chain, we find
6519 the parent function, look up its qname, then prepend a copy of it to the chain."
6520 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6521 (unless js2-imenu-function-map
6522 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6523 (puthash fn-node qname js2-imenu-function-map))
6524
6525 (defun js2-record-imenu-functions (node &optional var)
6526 "Record function definitions for imenu.
6527 NODE is a function node or an object literal.
6528 VAR, if non-nil, is the expression that NODE is being assigned to.
6529 When passed arguments of wrong type, does nothing."
6530 (when js2-parse-ide-mode
6531 (let ((fun-p (js2-function-node-p node))
6532 qname left fname-node pos)
6533 (cond
6534 ;; non-anonymous function declaration?
6535 ((and fun-p
6536 (not var)
6537 (setq fname-node (js2-function-node-name node)))
6538 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6539 ;; for remaining forms, compute left-side tree branch first
6540 ((and var (setq qname (js2-compute-nested-prop-get var)))
6541 (cond
6542 ;; foo.bar.baz = function
6543 (fun-p
6544 (js2-record-imenu-entry node qname (js2-node-pos node)))
6545 ;; foo.bar.baz = object-literal
6546 ;; look for nested functions: {a: {b: function() {...} }}
6547 ((js2-object-node-p node)
6548 ;; Node position here is still absolute, since the parser
6549 ;; passes the assignment target and value expressions
6550 ;; to us before they are added as children of the assignment node.
6551 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6552
6553 (defun js2-compute-nested-prop-get (node)
6554 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6555 component nodes as a list. Otherwise return nil. Element-gets are treated
6556 as property-gets if the index expression is a string, or a positive integer."
6557 (let (left right head)
6558 (cond
6559 ((or (js2-name-node-p node)
6560 (js2-this-node-p node))
6561 (list node))
6562 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6563 ((js2-prop-get-node-p node) ; foo.bar
6564 (setq left (js2-prop-get-node-left node)
6565 right (js2-prop-get-node-right node))
6566 (if (setq head (js2-compute-nested-prop-get left))
6567 (nconc head (list right))))
6568 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6569 (setq left (js2-elem-get-node-target node)
6570 right (js2-elem-get-node-element node))
6571 (if (or (js2-string-node-p right) ; ['bar']
6572 (and (js2-number-node-p right) ; [10]
6573 (string-match "^[0-9]+$"
6574 (js2-number-node-value right))))
6575 (if (setq head (js2-compute-nested-prop-get left))
6576 (nconc head (list right))))))))
6577
6578 (defun js2-record-object-literal (node qname pos)
6579 "Recursively process an object literal looking for functions.
6580 NODE is an object literal that is the right-hand child of an assignment
6581 expression. QNAME is a list of nodes representing the assignment target,
6582 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6583 POS is the absolute position of the node.
6584 We do a depth-first traversal of NODE. For any functions we find,
6585 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6586 (let (left right prop-qname)
6587 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6588 (let ((left (js2-infix-node-left e))
6589 ;; Element positions are relative to the parent position.
6590 (pos (+ pos (js2-node-pos e))))
6591 (cond
6592 ;; foo: function() {...}
6593 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6594 (when (js2-prop-node-name left)
6595 ;; As a policy decision, we record the position of the property,
6596 ;; not the position of the `function' keyword, since the property
6597 ;; is effectively the name of the function.
6598 (js2-record-imenu-entry right (append qname (list left)) pos)))
6599 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6600 ((js2-object-node-p right)
6601 (js2-record-object-literal right
6602 (append qname (list (js2-infix-node-left e)))
6603 (+ pos (js2-node-pos right)))))))))
6604
6605 (defun js2-node-top-level-decl-p (node)
6606 "Return t if NODE's name is defined in the top-level scope.
6607 Also returns t if NODE's name is not defined in any scope, since it implies
6608 that it's an external variable, which must also be in the top-level scope."
6609 (let* ((name (js2-prop-node-name node))
6610 (this-scope (js2-node-get-enclosing-scope node))
6611 defining-scope)
6612 (cond
6613 ((js2-this-node-p node)
6614 nil)
6615 ((null this-scope)
6616 t)
6617 ((setq defining-scope (js2-get-defining-scope this-scope name))
6618 (js2-ast-root-p defining-scope))
6619 (t t))))
6620
6621 (defun js2-wrapper-function-p (node)
6622 "Return t if NODE is a function expression that's immediately invoked.
6623 NODE must be `js2-function-node'."
6624 (let ((parent (js2-node-parent node)))
6625 (or
6626 ;; function(){...}();
6627 (js2-call-node-p parent)
6628 (and (js2-paren-node-p parent)
6629 ;; (function(){...})();
6630 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6631 ;; (function(){...}).call(this);
6632 (and (js2-prop-get-node-p parent)
6633 (member (js2-name-node-name (js2-prop-get-node-right parent))
6634 '("call" "apply"))
6635 (js2-call-node-p (js2-node-parent parent))))))))
6636
6637 (defun js2-browse-postprocess-chains (entries)
6638 "Modify function-declaration name chains after parsing finishes.
6639 Some of the information is only available after the parse tree is complete.
6640 For instance, processing a nested scope requires a parent function node."
6641 (let (result head fn current-fn parent-qname qname p elem)
6642 (dolist (entry entries)
6643 ;; function node goes first
6644 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6645 ;; Examine head's defining scope:
6646 ;; Pre-processed chain, or top-level/external, keep as-is.
6647 (if (or (stringp head) (js2-node-top-level-decl-p head))
6648 (push chain result)
6649 (when (js2-this-node-p head)
6650 (setq chain (cdr chain))) ; discard this-node
6651 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6652 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6653 (when (eq parent-qname 'not-found)
6654 ;; anonymous function expressions are not recorded
6655 ;; during the parse, so we need to handle this case here
6656 (setq parent-qname
6657 (if (js2-wrapper-function-p fn)
6658 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6659 (if (js2-ast-root-p grandparent)
6660 nil
6661 (gethash grandparent js2-imenu-function-map 'skip)))
6662 'skip))
6663 (puthash fn parent-qname js2-imenu-function-map))
6664 (unless (eq parent-qname 'skip)
6665 ;; prefix parent fn qname to this chain.
6666 (let ((qname (append parent-qname chain)))
6667 (puthash current-fn (butlast qname) js2-imenu-function-map)
6668 (push qname result)))))))
6669 ;; finally replace each node in each chain with its name.
6670 (dolist (chain result)
6671 (setq p chain)
6672 (while p
6673 (if (js2-node-p (setq elem (car p)))
6674 (setcar p (js2-node-qname-component elem)))
6675 (setq p (cdr p))))
6676 result))
6677
6678 ;; Merge name chains into a trie-like tree structure of nested lists.
6679 ;; To simplify construction of the trie, we first build it out using the rule
6680 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6681 ;; [key, num-or-list]. The second element can be a number; if so, this key
6682 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6683 ;; associated with the key at this level.) Otherwise the second element is
6684 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6685 ;; a simple recursive formulation.
6686 ;;
6687 ;; js2-mode is building the data structure for imenu. The imenu documentation
6688 ;; claims that it's the structure above, but in practice it wants the children
6689 ;; at the same list level as the key for that level, which is how I've drawn
6690 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6691 ;; list wrapper around the children at each level.
6692 ;;
6693 ;; A completed nested imenu-alist entry looks like this:
6694 ;; '(("foo"
6695 ;; ("<definition>" . 7)
6696 ;; ("bar"
6697 ;; ("a" . 40)
6698 ;; ("b" . 60))))
6699 ;;
6700 ;; In particular, the documentation for `imenu--index-alist' says that
6701 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6702 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6703
6704 (defun js2-treeify (lst)
6705 "Convert (a b c d) to (a ((b ((c d)))))."
6706 (if (null (cddr lst)) ; list length <= 2
6707 lst
6708 (list (car lst) (list (js2-treeify (cdr lst))))))
6709
6710 (defun js2-build-alist-trie (chains trie)
6711 "Merge declaration name chains into a trie-like alist structure for imenu.
6712 CHAINS is the qname chain list produced during parsing. TRIE is a
6713 list of elements built up so far."
6714 (let (head tail pos branch kids)
6715 (dolist (chain chains)
6716 (setq head (car chain)
6717 tail (cdr chain)
6718 pos (if (numberp (car tail)) (car tail))
6719 branch (js2-find-if (lambda (n)
6720 (string= (car n) head))
6721 trie)
6722 kids (second branch))
6723 (cond
6724 ;; case 1: this key isn't in the trie yet
6725 ((null branch)
6726 (if trie
6727 (setcdr (last trie) (list (js2-treeify chain)))
6728 (setq trie (list (js2-treeify chain)))))
6729 ;; case 2: key is present with a single number entry: replace w/ list
6730 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6731 ;; ("<definition>" 20)))
6732 ((numberp kids)
6733 (setcar (cdr branch)
6734 (list (list "<definition-1>" kids)
6735 (if pos
6736 (list "<definition-2>" pos)
6737 (js2-treeify tail)))))
6738 ;; case 3: key is there (with kids), and we're a number entry
6739 (pos
6740 (setcdr (last kids)
6741 (list
6742 (list (format "<definition-%d>"
6743 (1+ (loop for kid in kids
6744 count (eq ?< (aref (car kid) 0)))))
6745 pos))))
6746 ;; case 4: key is there with kids, need to merge in our chain
6747 (t
6748 (js2-build-alist-trie (list tail) kids))))
6749 trie))
6750
6751 (defun js2-flatten-trie (trie)
6752 "Convert TRIE to imenu-format.
6753 Recurses through nodes, and for each one whose second element is a list,
6754 appends the list's flattened elements to the current element. Also
6755 changes the tails into conses. For instance, this pre-flattened trie
6756
6757 '(a ((b 20)
6758 (c ((d 30)
6759 (e 40)))))
6760
6761 becomes
6762
6763 '(a (b . 20)
6764 (c (d . 30)
6765 (e . 40)))
6766
6767 Note that the root of the trie has no key, just a list of chains.
6768 This is also true for the value of any key with multiple children,
6769 e.g. key 'c' in the example above."
6770 (cond
6771 ((listp (car trie))
6772 (mapcar #'js2-flatten-trie trie))
6773 (t
6774 (if (numberp (second trie))
6775 (cons (car trie) (second trie))
6776 ;; else pop list and append its kids
6777 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6778
6779 (defun js2-build-imenu-index ()
6780 "Turn `js2-imenu-recorder' into an imenu data structure."
6781 (unless (eq js2-imenu-recorder 'empty)
6782 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
6783 (result (js2-build-alist-trie chains nil)))
6784 (js2-flatten-trie result))))
6785
6786 (defun js2-test-print-chains (chains)
6787 "Print a list of qname chains.
6788 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
6789 i.e. one or more nodes, and an integer position as the list tail."
6790 (mapconcat (lambda (chain)
6791 (concat "("
6792 (mapconcat (lambda (elem)
6793 (if (js2-node-p elem)
6794 (or (js2-node-qname-component elem)
6795 "nil")
6796 (number-to-string elem)))
6797 chain
6798 " ")
6799 ")"))
6800 chains
6801 "\n"))
6802
6803 ;;; Parser
6804
6805 (defconst js2-version "1.8.5"
6806 "Version of JavaScript supported.")
6807
6808 (defmacro js2-record-face (face)
6809 "Record a style run of FACE for the current token."
6810 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
6811
6812 (defsubst js2-node-end (n)
6813 "Computes the absolute end of node N.
6814 Use with caution! Assumes `js2-node-pos' is -absolute-, which
6815 is only true until the node is added to its parent; i.e., while parsing."
6816 (+ (js2-node-pos n)
6817 (js2-node-len n)))
6818
6819 (defun js2-record-comment ()
6820 "Record a comment in `js2-scanned-comments'."
6821 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
6822 :format js2-ts-comment-type)
6823 js2-scanned-comments)
6824 (when js2-parse-ide-mode
6825 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
6826 'font-lock-doc-face
6827 'font-lock-comment-face))
6828 (when (memq js2-ts-comment-type '(html preprocessor))
6829 ;; Tell cc-engine the bounds of the comment.
6830 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
6831
6832 ;; This function is called depressingly often, so it should be fast.
6833 ;; Most of the time it's looking at the same token it peeked before.
6834 (defun js2-peek-token ()
6835 "Return the next token without consuming it.
6836 If previous token was consumed, calls scanner to get new token.
6837 If previous token was -not- consumed, returns it (idempotent).
6838
6839 This function will not return a newline (js2-EOL) - instead, it
6840 gobbles newlines until it finds a non-newline token, and flags
6841 that token as appearing just after a newline.
6842
6843 This function will also not return a js2-COMMENT. Instead, it
6844 records comments found in `js2-scanned-comments'. If the token
6845 returned by this function immediately follows a jsdoc comment,
6846 the token is flagged as such.
6847
6848 Note that this function always returned the un-flagged token!
6849 The flags, if any, are saved in `js2-current-flagged-token'."
6850 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
6851 js2-current-token ; most common case - return already-peeked token
6852 (let ((tt (js2-get-token)) ; call scanner
6853 saw-eol
6854 face)
6855 ;; process comments and whitespace
6856 (while (or (= tt js2-EOL)
6857 (= tt js2-COMMENT))
6858 (if (= tt js2-EOL)
6859 (setq saw-eol t)
6860 (setq saw-eol nil)
6861 (if js2-record-comments
6862 (js2-record-comment)))
6863 (setq tt (js2-get-token))) ; call scanner
6864 (setq js2-current-token tt
6865 js2-current-flagged-token (if saw-eol
6866 (logior tt js2-ti-after-eol)
6867 tt))
6868 ;; perform lexical fontification as soon as token is scanned
6869 (when js2-parse-ide-mode
6870 (cond
6871 ((minusp tt)
6872 (js2-record-face 'js2-error))
6873 ((setq face (aref js2-kwd-tokens tt))
6874 (js2-record-face face))
6875 ((and (= tt js2-NAME)
6876 (equal js2-ts-string "undefined"))
6877 (js2-record-face 'font-lock-constant-face))))
6878 tt))) ; return unflagged token
6879
6880 (defun js2-peek-flagged-token ()
6881 "Return the current token along with any flags set for it."
6882 (js2-peek-token)
6883 js2-current-flagged-token)
6884
6885 (defsubst js2-consume-token ()
6886 (setq js2-current-flagged-token js2-EOF))
6887
6888 (defun js2-next-token ()
6889 (prog1
6890 (js2-peek-token)
6891 (js2-consume-token)))
6892
6893 (defun js2-next-flagged-token ()
6894 (js2-peek-token)
6895 (prog1 js2-current-flagged-token
6896 (js2-consume-token)))
6897
6898 (defun js2-match-token (match)
6899 "Consume and return t if next token matches MATCH, a bytecode.
6900 Returns nil and consumes nothing if MATCH is not the next token."
6901 (if (/= (js2-peek-token) match)
6902 nil
6903 (js2-consume-token)
6904 t))
6905
6906 (defun js2-match-contextual-kwd (name)
6907 "Consume and return t if next token is `js2-NAME', and its
6908 string is NAME. Returns nil and does nothing otherwise."
6909 (if (or (/= (js2-peek-token) js2-NAME)
6910 (not (string= js2-ts-string name)))
6911 nil
6912 (js2-consume-token)
6913 (js2-record-face 'font-lock-keyword-face)
6914 t))
6915
6916 (defun js2-valid-prop-name-token (tt)
6917 (or (= tt js2-NAME)
6918 (when (and js2-allow-keywords-as-property-names
6919 (plusp tt)
6920 (aref js2-kwd-tokens tt))
6921 (js2-save-name-token-data js2-token-beg (js2-token-name tt))
6922 t)))
6923
6924 (defun js2-match-prop-name ()
6925 "Consume token and return t if next token is a valid property name.
6926 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
6927 is non-nil and it's a keyword token."
6928 (if (js2-valid-prop-name-token (js2-peek-token))
6929 (progn
6930 (js2-consume-token)
6931 t)
6932 nil))
6933
6934 (defun js2-must-match-prop-name (msg-id &optional pos len)
6935 (if (js2-match-prop-name)
6936 t
6937 (js2-report-error msg-id nil pos len)
6938 nil))
6939
6940 (defun js2-peek-token-or-eol ()
6941 "Return js2-EOL if the current token immediately follows a newline.
6942 Else returns the current token. Used in situations where we don't
6943 consider certain token types valid if they are preceded by a newline.
6944 One example is the postfix ++ or -- operator, which has to be on the
6945 same line as its operand."
6946 (let ((tt (js2-peek-token)))
6947 ;; Check for last peeked token flags
6948 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
6949 js2-EOL
6950 tt)))
6951
6952 (defun js2-set-check-for-label ()
6953 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
6954 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
6955
6956 (defun js2-must-match (token msg-id &optional pos len)
6957 "Match next token to token code TOKEN, or record a syntax error.
6958 MSG-ID is the error message to report if the match fails.
6959 Returns t on match, nil if no match."
6960 (if (js2-match-token token)
6961 t
6962 (js2-report-error msg-id nil pos len)
6963 nil))
6964
6965 (defsubst js2-inside-function ()
6966 (plusp js2-nesting-of-function))
6967
6968 (defun js2-set-requires-activation ()
6969 (if (js2-function-node-p js2-current-script-or-fn)
6970 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
6971
6972 (defun js2-check-activation-name (name token)
6973 (when (js2-inside-function)
6974 ;; skip language-version 1.2 check from Rhino
6975 (if (or (string= "arguments" name)
6976 (and js2-compiler-activation-names ; only used in codegen
6977 (gethash name js2-compiler-activation-names)))
6978 (js2-set-requires-activation))))
6979
6980 (defun js2-set-is-generator ()
6981 (if (js2-function-node-p js2-current-script-or-fn)
6982 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
6983
6984 (defun js2-must-have-xml ()
6985 (unless js2-compiler-xml-available
6986 (js2-report-error "msg.XML.not.available")))
6987
6988 (defun js2-push-scope (scope)
6989 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
6990 (assert (js2-scope-p scope))
6991 (assert (null (js2-scope-parent-scope scope)))
6992 (assert (not (eq js2-current-scope scope)))
6993 (setf (js2-scope-parent-scope scope) js2-current-scope
6994 js2-current-scope scope))
6995
6996 (defsubst js2-pop-scope ()
6997 (setq js2-current-scope
6998 (js2-scope-parent-scope js2-current-scope)))
6999
7000 (defun js2-enter-loop (loop-node)
7001 (push loop-node js2-loop-set)
7002 (push loop-node js2-loop-and-switch-set)
7003 (js2-push-scope loop-node)
7004 ;; Tell the current labeled statement (if any) its statement,
7005 ;; and set the jump target of the first label to the loop.
7006 ;; These are used in `js2-parse-continue' to verify that the
7007 ;; continue target is an actual labeled loop. (And for codegen.)
7008 (when js2-labeled-stmt
7009 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7010 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7011 js2-labeled-stmt))) loop-node)))
7012
7013 (defun js2-exit-loop ()
7014 (pop js2-loop-set)
7015 (pop js2-loop-and-switch-set)
7016 (js2-pop-scope))
7017
7018 (defsubst js2-enter-switch (switch-node)
7019 (push switch-node js2-loop-and-switch-set))
7020
7021 (defsubst js2-exit-switch ()
7022 (pop js2-loop-and-switch-set))
7023
7024 (defun js2-parse (&optional buf cb)
7025 "Tell the js2 parser to parse a region of JavaScript.
7026
7027 BUF is a buffer or buffer name containing the code to parse.
7028 Call `narrow-to-region' first to parse only part of the buffer.
7029
7030 The returned AST root node is given some additional properties:
7031 `node-count' - total number of nodes in the AST
7032 `buffer' - BUF. The buffer it refers to may change or be killed,
7033 so the value is not necessarily reliable.
7034
7035 An optional callback CB can be specified to report parsing
7036 progress. If `(functionp CB)' returns t, it will be called with
7037 the current line number once before parsing begins, then again
7038 each time the lexer reaches a new line number.
7039
7040 CB can also be a list of the form `(symbol cb ...)' to specify
7041 multiple callbacks with different criteria. Each symbol is a
7042 criterion keyword, and the following element is the callback to
7043 call
7044
7045 :line - called whenever the line number changes
7046 :token - called for each new token consumed
7047
7048 The list of criteria could be extended to include entering or
7049 leaving a statement, an expression, or a function definition."
7050 (if (and cb (not (functionp cb)))
7051 (error "criteria callbacks not yet implemented"))
7052 (let ((inhibit-point-motion-hooks t)
7053 (js2-compiler-xml-available (>= js2-language-version 160))
7054 ;; This is a recursive-descent parser, so give it a big stack.
7055 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7056 (max-specpdl-size (max max-specpdl-size 3000))
7057 (case-fold-search nil)
7058 ast)
7059 (message nil) ; clear any error message from previous parse
7060 (with-current-buffer (or buf (current-buffer))
7061 (setq js2-scanned-comments nil
7062 js2-parsed-errors nil
7063 js2-parsed-warnings nil
7064 js2-imenu-recorder nil
7065 js2-imenu-function-map nil
7066 js2-label-set nil)
7067 (js2-init-scanner)
7068 (setq ast (with-silent-modifications
7069 (js2-do-parse)))
7070 (unless js2-ts-hit-eof
7071 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7072 (setf (js2-ast-root-errors ast) js2-parsed-errors
7073 (js2-ast-root-warnings ast) js2-parsed-warnings)
7074 ;; if we didn't find any declarations, put a dummy in this list so we
7075 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7076 (unless js2-imenu-recorder
7077 (setq js2-imenu-recorder 'empty))
7078 (run-hooks 'js2-parse-finished-hook)
7079 ast)))
7080
7081 ;; Corresponds to Rhino's Parser.parse() method.
7082 (defun js2-do-parse ()
7083 "Parse current buffer starting from current point.
7084 Scanner should be initialized."
7085 (let ((pos js2-ts-cursor)
7086 (end js2-ts-cursor) ; in case file is empty
7087 root n tt)
7088 ;; initialize buffer-local parsing vars
7089 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7090 js2-current-script-or-fn root
7091 js2-current-scope root
7092 js2-current-flagged-token js2-EOF
7093 js2-nesting-of-function 0
7094 js2-labeled-stmt nil
7095 js2-recorded-identifiers nil) ; for js2-highlight
7096 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7097 (if (= tt js2-FUNCTION)
7098 (progn
7099 (js2-consume-token)
7100 (setq n (js2-parse-function (if js2-called-by-compile-function
7101 'FUNCTION_EXPRESSION
7102 'FUNCTION_STATEMENT))))
7103 ;; not a function - parse a statement
7104 (setq n (js2-parse-statement)))
7105 ;; add function or statement to script
7106 (setq end (js2-node-end n))
7107 (js2-block-node-push root n))
7108 ;; add comments to root in lexical order
7109 (when js2-scanned-comments
7110 ;; if we find a comment beyond end of normal kids, use its end
7111 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7112 (dolist (comment js2-scanned-comments)
7113 (push comment (js2-ast-root-comments root))
7114 (js2-node-add-children root comment)))
7115 (setf (js2-node-len root) (- end pos))
7116 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7117 ;; Give extensions a chance to muck with things before highlighting starts.
7118 (let ((js2-additional-externs js2-additional-externs))
7119 (save-excursion
7120 (dolist (callback js2-post-parse-callbacks)
7121 (funcall callback)))
7122 (js2-highlight-undeclared-vars))
7123 root))
7124
7125 (defun js2-function-parser ()
7126 (js2-consume-token)
7127 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7128
7129 (defun js2-parse-function-closure-body (fn-node)
7130 "Parse a JavaScript 1.8 function closure body."
7131 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7132 (if js2-ts-hit-eof
7133 (js2-report-error "msg.no.brace.body" nil
7134 (js2-node-pos fn-node)
7135 (- js2-ts-cursor (js2-node-pos fn-node)))
7136 (js2-node-add-children fn-node
7137 (setf (js2-function-node-body fn-node)
7138 (js2-parse-expr t))))))
7139
7140 (defun js2-parse-function-body (fn-node)
7141 (js2-must-match js2-LC "msg.no.brace.body"
7142 (js2-node-pos fn-node)
7143 (- js2-ts-cursor (js2-node-pos fn-node)))
7144 (let ((pos js2-token-beg) ; LC position
7145 (pn (make-js2-block-node)) ; starts at LC position
7146 tt
7147 end)
7148 (incf js2-nesting-of-function)
7149 (unwind-protect
7150 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7151 (= tt js2-EOF)
7152 (= tt js2-RC)))
7153 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7154 (js2-parse-statement)
7155 (js2-consume-token)
7156 (js2-parse-function 'FUNCTION_STATEMENT))))
7157 (decf js2-nesting-of-function))
7158 (setq end js2-token-end) ; assume no curly and leave at current token
7159 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7160 (setq end js2-token-end))
7161 (setf (js2-node-pos pn) pos
7162 (js2-node-len pn) (- end pos))
7163 (setf (js2-function-node-body fn-node) pn)
7164 (js2-node-add-children fn-node pn)
7165 pn))
7166
7167 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7168 "Declare and fontify destructuring parameters inside NODE.
7169 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7170 (cond
7171 ((js2-name-node-p node)
7172 (let (leftpos)
7173 (js2-define-symbol decl-type (js2-name-node-name node)
7174 node ignore-not-in-block)
7175 (when face
7176 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7177 (+ leftpos (js2-node-len node))
7178 face 'record))))
7179 ((js2-object-node-p node)
7180 (dolist (elem (js2-object-node-elems node))
7181 (js2-define-destruct-symbols
7182 (if (js2-object-prop-node-p elem)
7183 (js2-object-prop-node-right elem)
7184 ;; abbreviated destructuring {a, b}
7185 elem)
7186 decl-type face ignore-not-in-block)))
7187 ((js2-array-node-p node)
7188 (dolist (elem (js2-array-node-elems node))
7189 (when elem
7190 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7191 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7192 (js2-node-len node)))))
7193
7194 (defun js2-parse-function-params (fn-node pos)
7195 (if (js2-match-token js2-RP)
7196 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7197 (let (params len param default-found rest-param-at)
7198 (loop for tt = (js2-peek-token)
7199 do
7200 (cond
7201 ;; destructuring param
7202 ((or (= tt js2-LB) (= tt js2-LC))
7203 (when default-found
7204 (js2-report-error "msg.no.default.after.default.param"))
7205 (setq param (js2-parse-destruct-primary-expr))
7206 (js2-define-destruct-symbols param
7207 js2-LP
7208 'js2-function-param)
7209 (push param params))
7210 ;; variable name
7211 (t
7212 (when (and (>= js2-language-version 200)
7213 (js2-match-token js2-TRIPLEDOT)
7214 (not rest-param-at))
7215 ;; to report errors if there are more parameters
7216 (setq rest-param-at (length params)))
7217 (js2-must-match js2-NAME "msg.no.parm")
7218 (js2-record-face 'js2-function-param)
7219 (setq param (js2-create-name-node))
7220 (js2-define-symbol js2-LP js2-ts-string param)
7221 ;; default parameter value
7222 (when (or (and default-found
7223 (not rest-param-at)
7224 (js2-must-match js2-ASSIGN
7225 "msg.no.default.after.default.param"
7226 (js2-node-pos param)
7227 (js2-node-len param)))
7228 (and (>= js2-language-version 200)
7229 (js2-match-token js2-ASSIGN)))
7230 (let* ((pos (js2-node-pos param))
7231 (tt js2-current-token)
7232 (op-pos (- js2-token-beg pos))
7233 (left param)
7234 (right (js2-parse-assign-expr))
7235 (len (- (js2-node-end right) pos)))
7236 (setq param (make-js2-assign-node
7237 :type tt :pos pos :len len :op-pos op-pos
7238 :left left :right right)
7239 default-found t)
7240 (js2-node-add-children param left right)))
7241 (push param params)))
7242 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7243 (js2-report-error "msg.param.after.rest" nil
7244 (js2-node-pos param) (js2-node-len param)))
7245 while
7246 (js2-match-token js2-COMMA))
7247 (when (js2-must-match js2-RP "msg.no.paren.after.parms")
7248 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7249 (when rest-param-at
7250 (setf (js2-function-node-rest-p fn-node) t))
7251 (dolist (p params)
7252 (js2-node-add-children fn-node p)
7253 (push p (js2-function-node-params fn-node))))))
7254
7255 (defun js2-check-inconsistent-return-warning (fn-node name)
7256 "Possibly show inconsistent-return warning.
7257 Last token scanned is the close-curly for the function body."
7258 (when (and js2-mode-show-strict-warnings
7259 js2-strict-inconsistent-return-warning
7260 (not (js2-has-consistent-return-usage
7261 (js2-function-node-body fn-node))))
7262 ;; Have it extend from close-curly to bol or beginning of block.
7263 (let ((pos (save-excursion
7264 (goto-char js2-token-end)
7265 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7266 (point-at-bol))))
7267 (end js2-token-end))
7268 (if (plusp (js2-name-node-length name))
7269 (js2-add-strict-warning "msg.no.return.value"
7270 (js2-name-node-name name) pos end)
7271 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7272
7273 (defun js2-parse-function (function-type)
7274 "Function parser. FUNCTION-TYPE is a symbol."
7275 (let ((pos js2-token-beg) ; start of 'function' keyword
7276 name name-beg name-end fn-node lp
7277 (synthetic-type function-type)
7278 member-expr-node)
7279 ;; parse function name, expression, or non-name (anonymous)
7280 (cond
7281 ;; function foo(...)
7282 ((js2-match-token js2-NAME)
7283 (setq name (js2-create-name-node t)
7284 name-beg js2-token-beg
7285 name-end js2-token-end)
7286 (unless (js2-match-token js2-LP)
7287 (when js2-allow-member-expr-as-function-name
7288 ;; function foo.bar(...)
7289 (setq member-expr-node name
7290 name nil
7291 member-expr-node (js2-parse-member-expr-tail
7292 nil member-expr-node)))
7293 (js2-must-match js2-LP "msg.no.paren.parms")))
7294 ((js2-match-token js2-LP)
7295 nil) ; anonymous function: leave name as null
7296 (t
7297 ;; function random-member-expr(...)
7298 (when js2-allow-member-expr-as-function-name
7299 ;; Note that memberExpr can not start with '(' like
7300 ;; in function (1+2).toString(), because 'function (' already
7301 ;; processed as anonymous function
7302 (setq member-expr-node (js2-parse-member-expr)))
7303 (js2-must-match js2-LP "msg.no.paren.parms")))
7304 (if (= js2-current-token js2-LP) ; eventually matched LP?
7305 (setq lp js2-token-beg))
7306 (if member-expr-node
7307 (progn
7308 (setq synthetic-type 'FUNCTION_EXPRESSION)
7309 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7310 (if name
7311 (js2-set-face name-beg name-end
7312 'font-lock-function-name-face 'record)))
7313 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7314 (plusp (js2-name-node-length name)))
7315 ;; Function statements define a symbol in the enclosing scope
7316 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7317 (setf fn-node (make-js2-function-node :pos pos
7318 :name name
7319 :form function-type
7320 :lp (if lp (- lp pos))))
7321 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7322 ;; 1. Nested functions are not affected by the dynamic scope flag
7323 ;; as dynamic scope is already a parent of their scope.
7324 ;; 2. Functions defined under the with statement also immune to
7325 ;; this setup, in which case dynamic scope is ignored in favor
7326 ;; of the with object.
7327 (setf (js2-function-node-ignore-dynamic fn-node) t))
7328 ;; dynamically bind all the per-function variables
7329 (let ((js2-current-script-or-fn fn-node)
7330 (js2-current-scope fn-node)
7331 (js2-nesting-of-with 0)
7332 (js2-end-flags 0)
7333 js2-label-set
7334 js2-loop-set
7335 js2-loop-and-switch-set)
7336 (js2-parse-function-params fn-node pos)
7337 (if (and (>= js2-language-version 180)
7338 (/= (js2-peek-token) js2-LC))
7339 (js2-parse-function-closure-body fn-node)
7340 (js2-parse-function-body fn-node))
7341 (if name
7342 (js2-node-add-children fn-node name))
7343 (js2-check-inconsistent-return-warning fn-node name)
7344 ;; Function expressions define a name only in the body of the
7345 ;; function, and only if not hidden by a parameter name
7346 (if (and name
7347 (eq synthetic-type 'FUNCTION_EXPRESSION)
7348 (null (js2-scope-get-symbol js2-current-scope
7349 (js2-name-node-name name))))
7350 (js2-define-symbol js2-FUNCTION
7351 (js2-name-node-name name)
7352 fn-node))
7353 (if (and name
7354 (not (eq function-type 'FUNCTION_EXPRESSION)))
7355 (js2-record-imenu-functions fn-node)))
7356 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7357 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7358 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7359 ;; We wait until after parsing the function to set its parent scope,
7360 ;; since `js2-define-symbol' needs the defining-scope check to stop
7361 ;; at the function boundary when checking for redeclarations.
7362 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7363 fn-node))
7364
7365 (defun js2-parse-statements (&optional parent)
7366 "Parse a statement list. Last token consumed must be js2-LC.
7367
7368 PARENT can be a `js2-block-node', in which case the statements are
7369 appended to PARENT. Otherwise a new `js2-block-node' is created
7370 and returned.
7371
7372 This function does not match the closing js2-RC: the caller
7373 matches the RC so it can provide a suitable error message if not
7374 matched. This means it's up to the caller to set the length of
7375 the node to include the closing RC. The node start pos is set to
7376 the absolute buffer start position, and the caller should fix it
7377 up to be relative to the parent node. All children of this block
7378 node are given relative start positions and correct lengths."
7379 (let ((pn (or parent (make-js2-block-node)))
7380 tt)
7381 (setf (js2-node-pos pn) js2-token-beg)
7382 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7383 (/= tt js2-RC))
7384 (js2-block-node-push pn (js2-parse-statement)))
7385 pn))
7386
7387 (defun js2-parse-statement ()
7388 (let (tt pn beg end)
7389 ;; coarse-grained user-interrupt check - needs work
7390 (and js2-parse-interruptable-p
7391 (zerop (% (incf js2-parse-stmt-count)
7392 js2-statements-per-pause))
7393 (input-pending-p)
7394 (throw 'interrupted t))
7395 (setq pn (js2-statement-helper))
7396 ;; no-side-effects warning check
7397 (unless (js2-node-has-side-effects pn)
7398 (setq end (js2-node-end pn))
7399 (save-excursion
7400 (goto-char end)
7401 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7402 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7403 pn))
7404
7405 ;; These correspond to the switch cases in Parser.statementHelper
7406 (defconst js2-parsers
7407 (let ((parsers (make-vector js2-num-tokens
7408 #'js2-parse-expr-stmt)))
7409 (aset parsers js2-BREAK #'js2-parse-break)
7410 (aset parsers js2-CONST #'js2-parse-const-var)
7411 (aset parsers js2-CONTINUE #'js2-parse-continue)
7412 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7413 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7414 (aset parsers js2-DO #'js2-parse-do)
7415 (aset parsers js2-FOR #'js2-parse-for)
7416 (aset parsers js2-FUNCTION #'js2-function-parser)
7417 (aset parsers js2-IF #'js2-parse-if)
7418 (aset parsers js2-LC #'js2-parse-block)
7419 (aset parsers js2-LET #'js2-parse-let-stmt)
7420 (aset parsers js2-NAME #'js2-parse-name-or-label)
7421 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7422 (aset parsers js2-SEMI #'js2-parse-semi)
7423 (aset parsers js2-SWITCH #'js2-parse-switch)
7424 (aset parsers js2-THROW #'js2-parse-throw)
7425 (aset parsers js2-TRY #'js2-parse-try)
7426 (aset parsers js2-VAR #'js2-parse-const-var)
7427 (aset parsers js2-WHILE #'js2-parse-while)
7428 (aset parsers js2-WITH #'js2-parse-with)
7429 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7430 parsers)
7431 "A vector mapping token types to parser functions.")
7432
7433 (defun js2-parse-warn-missing-semi (beg end)
7434 (and js2-mode-show-strict-warnings
7435 js2-strict-missing-semi-warning
7436 (js2-add-strict-warning
7437 "msg.missing.semi" nil
7438 ;; back up to beginning of statement or line
7439 (max beg (save-excursion
7440 (goto-char end)
7441 (point-at-bol)))
7442 end)))
7443
7444 (defconst js2-no-semi-insertion
7445 (list js2-IF
7446 js2-SWITCH
7447 js2-WHILE
7448 js2-DO
7449 js2-FOR
7450 js2-TRY
7451 js2-WITH
7452 js2-LC
7453 js2-ERROR
7454 js2-SEMI
7455 js2-FUNCTION)
7456 "List of tokens that don't do automatic semicolon insertion.")
7457
7458 (defconst js2-autoinsert-semi-and-warn
7459 (list js2-ERROR js2-EOF js2-RC))
7460
7461 (defun js2-statement-helper ()
7462 (let* ((tt (js2-peek-token))
7463 (first-tt tt)
7464 (beg js2-token-beg)
7465 (parser (if (= tt js2-ERROR)
7466 #'js2-parse-semi
7467 (aref js2-parsers tt)))
7468 pn
7469 tt-flagged)
7470 ;; If the statement is set, then it's been told its label by now.
7471 (and js2-labeled-stmt
7472 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7473 (setq js2-labeled-stmt nil))
7474 (setq pn (funcall parser))
7475 ;; Don't do auto semi insertion for certain statement types.
7476 (unless (or (memq first-tt js2-no-semi-insertion)
7477 (js2-labeled-stmt-node-p pn))
7478 (js2-auto-insert-semicolon pn))
7479 pn))
7480
7481 (defun js2-auto-insert-semicolon (pn)
7482 (let* ((tt-flagged (js2-peek-flagged-token))
7483 (tt (logand tt-flagged js2-clear-ti-mask))
7484 (pos (js2-node-pos pn)))
7485 (cond
7486 ((= tt js2-SEMI)
7487 ;; Consume ';' as a part of expression
7488 (js2-consume-token)
7489 ;; extend the node bounds to include the semicolon.
7490 (setf (js2-node-len pn) (- js2-token-end pos)))
7491 ((memq tt js2-autoinsert-semi-and-warn)
7492 ;; Autoinsert ;
7493 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7494 (t
7495 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7496 ;; Report error if no EOL or autoinsert ';' otherwise
7497 (js2-report-error "msg.no.semi.stmt")
7498 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7499
7500 (defun js2-parse-condition ()
7501 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7502 The parens are discarded and the expression node is returned.
7503 The `pos' field of the return value is set to an absolute position
7504 that must be fixed up by the caller.
7505 Return value is a list (EXPR LP RP), with absolute paren positions."
7506 (let (pn lp rp)
7507 (if (js2-must-match js2-LP "msg.no.paren.cond")
7508 (setq lp js2-token-beg))
7509 (setq pn (js2-parse-expr))
7510 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7511 (setq rp js2-token-beg))
7512 ;; Report strict warning on code like "if (a = 7) ..."
7513 (if (and js2-strict-cond-assign-warning
7514 (js2-assign-node-p pn))
7515 (js2-add-strict-warning "msg.equal.as.assign" nil
7516 (js2-node-pos pn)
7517 (+ (js2-node-pos pn)
7518 (js2-node-len pn))))
7519 (list pn lp rp)))
7520
7521 (defun js2-parse-if ()
7522 "Parser for if-statement. Last matched token must be js2-IF."
7523 (let ((pos js2-token-beg)
7524 cond if-true if-false else-pos end pn)
7525 (js2-consume-token)
7526 (setq cond (js2-parse-condition)
7527 if-true (js2-parse-statement)
7528 if-false (if (js2-match-token js2-ELSE)
7529 (progn
7530 (setq else-pos (- js2-token-beg pos))
7531 (js2-parse-statement)))
7532 end (js2-node-end (or if-false if-true))
7533 pn (make-js2-if-node :pos pos
7534 :len (- end pos)
7535 :condition (car cond)
7536 :then-part if-true
7537 :else-part if-false
7538 :else-pos else-pos
7539 :lp (js2-relpos (second cond) pos)
7540 :rp (js2-relpos (third cond) pos)))
7541 (js2-node-add-children pn (car cond) if-true if-false)
7542 pn))
7543
7544 (defun js2-parse-switch ()
7545 "Parser for if-statement. Last matched token must be js2-SWITCH."
7546 (let ((pos js2-token-beg)
7547 tt pn discriminant has-default case-expr case-node
7548 case-pos cases stmt lp rp)
7549 (js2-consume-token)
7550 (if (js2-must-match js2-LP "msg.no.paren.switch")
7551 (setq lp js2-token-beg))
7552 (setq discriminant (js2-parse-expr)
7553 pn (make-js2-switch-node :discriminant discriminant
7554 :pos pos
7555 :lp (js2-relpos lp pos)))
7556 (js2-node-add-children pn discriminant)
7557 (js2-enter-switch pn)
7558 (unwind-protect
7559 (progn
7560 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7561 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7562 (js2-must-match js2-LC "msg.no.brace.switch")
7563 (catch 'break
7564 (while t
7565 (setq tt (js2-next-token)
7566 case-pos js2-token-beg)
7567 (cond
7568 ((= tt js2-RC)
7569 (setf (js2-node-len pn) (- js2-token-end pos))
7570 (throw 'break nil)) ; done
7571 ((= tt js2-CASE)
7572 (setq case-expr (js2-parse-expr))
7573 (js2-must-match js2-COLON "msg.no.colon.case"))
7574 ((= tt js2-DEFAULT)
7575 (if has-default
7576 (js2-report-error "msg.double.switch.default"))
7577 (setq has-default t
7578 case-expr nil)
7579 (js2-must-match js2-COLON "msg.no.colon.case"))
7580 (t
7581 (js2-report-error "msg.bad.switch")
7582 (throw 'break nil)))
7583 (setq case-node (make-js2-case-node :pos case-pos
7584 :len (- js2-token-end case-pos)
7585 :expr case-expr))
7586 (js2-node-add-children case-node case-expr)
7587 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7588 (/= tt js2-CASE)
7589 (/= tt js2-DEFAULT)
7590 (/= tt js2-EOF))
7591 (setf stmt (js2-parse-statement)
7592 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7593 (js2-block-node-push case-node stmt))
7594 (push case-node cases)))
7595 ;; add cases last, as pushing reverses the order to be correct
7596 (dolist (kid cases)
7597 (js2-node-add-children pn kid)
7598 (push kid (js2-switch-node-cases pn)))
7599 pn) ; return value
7600 (js2-exit-switch))))
7601
7602 (defun js2-parse-while ()
7603 "Parser for while-statement. Last matched token must be js2-WHILE."
7604 (let ((pos js2-token-beg)
7605 (pn (make-js2-while-node))
7606 cond body)
7607 (js2-consume-token)
7608 (js2-enter-loop pn)
7609 (unwind-protect
7610 (progn
7611 (setf cond (js2-parse-condition)
7612 (js2-while-node-condition pn) (car cond)
7613 body (js2-parse-statement)
7614 (js2-while-node-body pn) body
7615 (js2-node-len pn) (- (js2-node-end body) pos)
7616 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7617 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7618 (js2-node-add-children pn body (car cond)))
7619 (js2-exit-loop))
7620 pn))
7621
7622 (defun js2-parse-do ()
7623 "Parser for do-statement. Last matched token must be js2-DO."
7624 (let ((pos js2-token-beg)
7625 (pn (make-js2-do-node))
7626 cond body end)
7627 (js2-consume-token)
7628 (js2-enter-loop pn)
7629 (unwind-protect
7630 (progn
7631 (setq body (js2-parse-statement))
7632 (js2-must-match js2-WHILE "msg.no.while.do")
7633 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7634 cond (js2-parse-condition)
7635 (js2-do-node-condition pn) (car cond)
7636 (js2-do-node-body pn) body
7637 end js2-ts-cursor
7638 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7639 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7640 (js2-node-add-children pn (car cond) body))
7641 (js2-exit-loop))
7642 ;; Always auto-insert semicolon to follow SpiderMonkey:
7643 ;; It is required by ECMAScript but is ignored by the rest of
7644 ;; world; see bug 238945
7645 (if (js2-match-token js2-SEMI)
7646 (setq end js2-ts-cursor))
7647 (setf (js2-node-len pn) (- end pos))
7648 pn))
7649
7650 (defun js2-parse-for ()
7651 "Parser for for-statement. Last matched token must be js2-FOR.
7652 Parses for, for-in, and for each-in statements."
7653 (let ((for-pos js2-token-beg)
7654 pn is-for-each is-for-in-or-of is-for-of
7655 in-pos each-pos tmp-pos
7656 init ; Node init is also foo in 'foo in object'
7657 cond ; Node cond is also object in 'foo in object'
7658 incr ; 3rd section of for-loop initializer
7659 body tt lp rp)
7660 (js2-consume-token)
7661 ;; See if this is a for each () instead of just a for ()
7662 (when (js2-match-token js2-NAME)
7663 (if (string= "each" js2-ts-string)
7664 (progn
7665 (setq is-for-each t
7666 each-pos (- js2-token-beg for-pos)) ; relative
7667 (js2-record-face 'font-lock-keyword-face))
7668 (js2-report-error "msg.no.paren.for")))
7669 (if (js2-must-match js2-LP "msg.no.paren.for")
7670 (setq lp (- js2-token-beg for-pos)))
7671 (setq tt (js2-peek-token))
7672 ;; 'for' makes local scope
7673 (js2-push-scope (make-js2-scope))
7674 (unwind-protect
7675 ;; parse init clause
7676 (let ((js2-in-for-init t)) ; set as dynamic variable
7677 (cond
7678 ((= tt js2-SEMI)
7679 (setq init (make-js2-empty-expr-node)))
7680 ((or (= tt js2-VAR) (= tt js2-LET))
7681 (js2-consume-token)
7682 (setq init (js2-parse-variables tt js2-token-beg)))
7683 (t
7684 (setq init (js2-parse-expr)))))
7685 (if (or (js2-match-token js2-IN)
7686 (and (>= js2-language-version 200)
7687 (js2-match-contextual-kwd "of")
7688 (setq is-for-of t)))
7689 (setq is-for-in-or-of t
7690 in-pos (- js2-token-beg for-pos)
7691 ;; scope of iteration target object is not the scope we've created above.
7692 ;; stash current scope temporary.
7693 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7694 (js2-parse-expr))) ; object over which we're iterating
7695 ;; else ordinary for loop - parse cond and incr
7696 (js2-must-match js2-SEMI "msg.no.semi.for")
7697 (setq cond (if (= (js2-peek-token) js2-SEMI)
7698 (make-js2-empty-expr-node) ; no loop condition
7699 (js2-parse-expr)))
7700 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7701 (setq tmp-pos js2-token-end
7702 incr (if (= (js2-peek-token) js2-RP)
7703 (make-js2-empty-expr-node :pos tmp-pos)
7704 (js2-parse-expr))))
7705 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7706 (setq rp (- js2-token-beg for-pos)))
7707 (if (not is-for-in-or-of)
7708 (setq pn (make-js2-for-node :init init
7709 :condition cond
7710 :update incr
7711 :lp lp
7712 :rp rp))
7713 ;; cond could be null if 'in obj' got eaten by the init node.
7714 (if (js2-infix-node-p init)
7715 ;; it was (foo in bar) instead of (var foo in bar)
7716 (setq cond (js2-infix-node-right init)
7717 init (js2-infix-node-left init))
7718 (if (and (js2-var-decl-node-p init)
7719 (> (length (js2-var-decl-node-kids init)) 1))
7720 (js2-report-error "msg.mult.index")))
7721 (setq pn (make-js2-for-in-node :iterator init
7722 :object cond
7723 :in-pos in-pos
7724 :foreach-p is-for-each
7725 :each-pos each-pos
7726 :forof-p is-for-of
7727 :lp lp
7728 :rp rp)))
7729 (unwind-protect
7730 (progn
7731 (js2-enter-loop pn)
7732 ;; We have to parse the body -after- creating the loop node,
7733 ;; so that the loop node appears in the js2-loop-set, allowing
7734 ;; break/continue statements to find the enclosing loop.
7735 (setf body (js2-parse-statement)
7736 (js2-loop-node-body pn) body
7737 (js2-node-pos pn) for-pos
7738 (js2-node-len pn) (- (js2-node-end body) for-pos))
7739 (js2-node-add-children pn init cond incr body))
7740 ;; finally
7741 (js2-exit-loop))
7742 (js2-pop-scope))
7743 pn))
7744
7745 (defun js2-parse-try ()
7746 "Parser for try-statement. Last matched token must be js2-TRY."
7747 (let ((try-pos js2-token-beg)
7748 try-end
7749 try-block
7750 catch-blocks
7751 finally-block
7752 saw-default-catch
7753 peek
7754 param
7755 catch-cond
7756 catch-node
7757 guard-kwd
7758 catch-pos
7759 finally-pos
7760 pn
7761 block
7762 lp
7763 rp)
7764 (js2-consume-token)
7765 (if (/= (js2-peek-token) js2-LC)
7766 (js2-report-error "msg.no.brace.try"))
7767 (setq try-block (js2-parse-statement)
7768 try-end (js2-node-end try-block)
7769 peek (js2-peek-token))
7770 (cond
7771 ((= peek js2-CATCH)
7772 (while (js2-match-token js2-CATCH)
7773 (setq catch-pos js2-token-beg
7774 guard-kwd nil
7775 catch-cond nil
7776 lp nil
7777 rp nil)
7778 (if saw-default-catch
7779 (js2-report-error "msg.catch.unreachable"))
7780 (if (js2-must-match js2-LP "msg.no.paren.catch")
7781 (setq lp (- js2-token-beg catch-pos)))
7782 (js2-push-scope (make-js2-scope))
7783 (let ((tt (js2-peek-token)))
7784 (cond
7785 ;; destructuring pattern
7786 ;; catch ({ message, file }) { ... }
7787 ((or (= tt js2-LB) (= tt js2-LC))
7788 (setq param (js2-parse-destruct-primary-expr))
7789 (js2-define-destruct-symbols param js2-LET nil))
7790 ;; simple name
7791 (t
7792 (js2-must-match js2-NAME "msg.bad.catchcond")
7793 (setq param (js2-create-name-node))
7794 (js2-define-symbol js2-LET js2-ts-string param))))
7795 ;; pattern guard
7796 (if (js2-match-token js2-IF)
7797 (setq guard-kwd (- js2-token-beg catch-pos)
7798 catch-cond (js2-parse-expr))
7799 (setq saw-default-catch t))
7800 (if (js2-must-match js2-RP "msg.bad.catchcond")
7801 (setq rp (- js2-token-beg catch-pos)))
7802 (js2-must-match js2-LC "msg.no.brace.catchblock")
7803 (setq block (js2-parse-statements)
7804 try-end (js2-node-end block)
7805 catch-node (make-js2-catch-node :pos catch-pos
7806 :param param
7807 :guard-expr catch-cond
7808 :guard-kwd guard-kwd
7809 :block block
7810 :lp lp
7811 :rp rp))
7812 (js2-pop-scope)
7813 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7814 (setq try-end js2-token-beg))
7815 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7816 (js2-node-len catch-node) (- try-end catch-pos))
7817 (js2-node-add-children catch-node param catch-cond block)
7818 (push catch-node catch-blocks)))
7819 ((/= peek js2-FINALLY)
7820 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7821 (js2-node-pos try-block)
7822 (- (setq try-end (js2-node-end try-block))
7823 (js2-node-pos try-block)))))
7824 (when (js2-match-token js2-FINALLY)
7825 (setq finally-pos js2-token-beg
7826 block (js2-parse-statement)
7827 try-end (js2-node-end block)
7828 finally-block (make-js2-finally-node :pos finally-pos
7829 :len (- try-end finally-pos)
7830 :body block))
7831 (js2-node-add-children finally-block block))
7832 (setq pn (make-js2-try-node :pos try-pos
7833 :len (- try-end try-pos)
7834 :try-block try-block
7835 :finally-block finally-block))
7836 (js2-node-add-children pn try-block finally-block)
7837 ;; push them onto the try-node, which reverses and corrects their order
7838 (dolist (cb catch-blocks)
7839 (js2-node-add-children pn cb)
7840 (push cb (js2-try-node-catch-clauses pn)))
7841 pn))
7842
7843 (defun js2-parse-throw ()
7844 "Parser for throw-statement. Last matched token must be js2-THROW."
7845 (let ((pos js2-token-beg)
7846 expr pn)
7847 (js2-consume-token)
7848 (if (= (js2-peek-token-or-eol) js2-EOL)
7849 ;; ECMAScript does not allow new lines before throw expression,
7850 ;; see bug 256617
7851 (js2-report-error "msg.bad.throw.eol"))
7852 (setq expr (js2-parse-expr)
7853 pn (make-js2-throw-node :pos pos
7854 :len (- (js2-node-end expr) pos)
7855 :expr expr))
7856 (js2-node-add-children pn expr)
7857 pn))
7858
7859 (defun js2-match-jump-label-name (label-name)
7860 "If break/continue specified a label, return that label's labeled stmt.
7861 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
7862 does not match an existing label, reports an error and returns nil."
7863 (let ((bundle (cdr (assoc label-name js2-label-set))))
7864 (if (null bundle)
7865 (js2-report-error "msg.undef.label"))
7866 bundle))
7867
7868 (defun js2-parse-break ()
7869 "Parser for break-statement. Last matched token must be js2-BREAK."
7870 (let ((pos js2-token-beg)
7871 (end js2-token-end)
7872 break-target ; statement to break from
7873 break-label ; in "break foo", name-node representing the foo
7874 labels ; matching labeled statement to break to
7875 pn)
7876 (js2-consume-token) ; `break'
7877 (when (eq (js2-peek-token-or-eol) js2-NAME)
7878 (js2-consume-token)
7879 (setq break-label (js2-create-name-node)
7880 end (js2-node-end break-label)
7881 ;; matchJumpLabelName only matches if there is one
7882 labels (js2-match-jump-label-name js2-ts-string)
7883 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
7884 (unless (or break-target break-label)
7885 ;; no break target specified - try for innermost enclosing loop/switch
7886 (if (null js2-loop-and-switch-set)
7887 (unless break-label
7888 (js2-report-error "msg.bad.break" nil pos (length "break")))
7889 (setq break-target (car js2-loop-and-switch-set))))
7890 (setq pn (make-js2-break-node :pos pos
7891 :len (- end pos)
7892 :label break-label
7893 :target break-target))
7894 (js2-node-add-children pn break-label) ; but not break-target
7895 pn))
7896
7897 (defun js2-parse-continue ()
7898 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
7899 (let ((pos js2-token-beg)
7900 (end js2-token-end)
7901 label ; optional user-specified label, a `js2-name-node'
7902 labels ; current matching labeled stmt, if any
7903 target ; the `js2-loop-node' target of this continue stmt
7904 pn)
7905 (js2-consume-token) ; `continue'
7906 (when (= (js2-peek-token-or-eol) js2-NAME)
7907 (js2-consume-token)
7908 (setq label (js2-create-name-node)
7909 end (js2-node-end label)
7910 ;; matchJumpLabelName only matches if there is one
7911 labels (js2-match-jump-label-name js2-ts-string)))
7912 (cond
7913 ((null labels) ; no current label to go to
7914 (if (null js2-loop-set) ; no loop to continue to
7915 (js2-report-error "msg.continue.outside" nil pos
7916 (length "continue"))
7917 (setq target (car js2-loop-set)))) ; innermost enclosing loop
7918 (t
7919 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
7920 (setq target (js2-labeled-stmt-node-stmt labels))
7921 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
7922 (setq pn (make-js2-continue-node :pos pos
7923 :len (- end pos)
7924 :label label
7925 :target target))
7926 (js2-node-add-children pn label) ; but not target - it's not our child
7927 pn))
7928
7929 (defun js2-parse-with ()
7930 "Parser for with-statement. Last matched token must be js2-WITH."
7931 (js2-consume-token)
7932 (let ((pos js2-token-beg)
7933 obj body pn lp rp)
7934 (if (js2-must-match js2-LP "msg.no.paren.with")
7935 (setq lp js2-token-beg))
7936 (setq obj (js2-parse-expr))
7937 (if (js2-must-match js2-RP "msg.no.paren.after.with")
7938 (setq rp js2-token-beg))
7939 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
7940 (setq body (js2-parse-statement)))
7941 (setq pn (make-js2-with-node :pos pos
7942 :len (- (js2-node-end body) pos)
7943 :object obj
7944 :body body
7945 :lp (js2-relpos lp pos)
7946 :rp (js2-relpos rp pos)))
7947 (js2-node-add-children pn obj body)
7948 pn))
7949
7950 (defun js2-parse-const-var ()
7951 "Parser for var- or const-statement.
7952 Last matched token must be js2-CONST or js2-VAR."
7953 (let ((tt (js2-peek-token))
7954 (pos js2-token-beg)
7955 expr pn)
7956 (js2-consume-token)
7957 (setq expr (js2-parse-variables tt js2-token-beg)
7958 pn (make-js2-expr-stmt-node :pos pos
7959 :len (- (js2-node-end expr) pos)
7960 :expr expr))
7961 (js2-node-add-children pn expr)
7962 pn))
7963
7964 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
7965 (let ((pn (make-js2-expr-stmt-node :pos pos
7966 :len (js2-node-len expr)
7967 :type (if (js2-inside-function)
7968 js2-EXPR_VOID
7969 js2-EXPR_RESULT)
7970 :expr expr)))
7971 (if add-child
7972 (js2-node-add-children pn expr))
7973 pn))
7974
7975 (defun js2-parse-let-stmt ()
7976 "Parser for let-statement. Last matched token must be js2-LET."
7977 (js2-consume-token)
7978 (let ((pos js2-token-beg)
7979 expr pn)
7980 (if (= (js2-peek-token) js2-LP)
7981 ;; let expression in statement context
7982 (setq expr (js2-parse-let pos 'statement)
7983 pn (js2-wrap-with-expr-stmt pos expr t))
7984 ;; else we're looking at a statement like let x=6, y=7;
7985 (setf expr (js2-parse-variables js2-LET pos)
7986 pn (js2-wrap-with-expr-stmt pos expr t)
7987 (js2-node-type pn) js2-EXPR_RESULT))
7988 pn))
7989
7990 (defun js2-parse-ret-yield ()
7991 (js2-parse-return-or-yield (js2-peek-token) nil))
7992
7993 (defconst js2-parse-return-stmt-enders
7994 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
7995
7996 (defsubst js2-now-all-set (before after mask)
7997 "Return whether or not the bits in the mask have changed to all set.
7998 BEFORE is bits before change, AFTER is bits after change, and MASK is
7999 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8000 but not BEFORE."
8001 (and (/= (logand before mask) mask)
8002 (= (logand after mask) mask)))
8003
8004 (defun js2-parse-return-or-yield (tt expr-context)
8005 (let ((pos js2-token-beg)
8006 (end js2-token-end)
8007 (before js2-end-flags)
8008 (inside-function (js2-inside-function))
8009 e ret name)
8010 (unless inside-function
8011 (js2-report-error (if (eq tt js2-RETURN)
8012 "msg.bad.return"
8013 "msg.bad.yield")))
8014 (js2-consume-token)
8015 ;; This is ugly, but we don't want to require a semicolon.
8016 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8017 (setq e (js2-parse-expr)
8018 end (js2-node-end e)))
8019 (cond
8020 ((eq tt js2-RETURN)
8021 (js2-set-flag js2-end-flags (if (null e)
8022 js2-end-returns
8023 js2-end-returns-value))
8024 (setq ret (make-js2-return-node :pos pos
8025 :len (- end pos)
8026 :retval e))
8027 (js2-node-add-children ret e)
8028 ;; See if we need a strict mode warning.
8029 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8030 ;; more thorough and accurate than this before/after flag check.
8031 ;; E.g. if there's a finally-block that always returns, we shouldn't
8032 ;; show a warning generated by inconsistent returns in the catch blocks.
8033 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8034 ;; so we know which returns/yields to highlight, and we should get rid of
8035 ;; all the checking in `js2-parse-return-or-yield'.
8036 (if (and js2-strict-inconsistent-return-warning
8037 (js2-now-all-set before js2-end-flags
8038 (logior js2-end-returns js2-end-returns-value)))
8039 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8040 (t
8041 (unless (js2-inside-function)
8042 (js2-report-error "msg.bad.yield"))
8043 (js2-set-flag js2-end-flags js2-end-yields)
8044 (setq ret (make-js2-yield-node :pos pos
8045 :len (- end pos)
8046 :value e))
8047 (js2-node-add-children ret e)
8048 (unless expr-context
8049 (setq e ret
8050 ret (js2-wrap-with-expr-stmt pos e t))
8051 (js2-set-requires-activation)
8052 (js2-set-is-generator))))
8053 ;; see if we are mixing yields and value returns.
8054 (when (and inside-function
8055 (js2-now-all-set before js2-end-flags
8056 (logior js2-end-yields js2-end-returns-value)))
8057 (setq name (js2-function-name js2-current-script-or-fn))
8058 (if (zerop (length name))
8059 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8060 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8061 ret))
8062
8063 (defun js2-parse-debugger ()
8064 (js2-consume-token)
8065 (make-js2-keyword-node :type js2-DEBUGGER))
8066
8067 (defun js2-parse-block ()
8068 "Parser for a curly-delimited statement block.
8069 Last token matched must be `js2-LC'."
8070 (let ((pos js2-token-beg)
8071 (pn (make-js2-scope)))
8072 (js2-consume-token)
8073 (js2-push-scope pn)
8074 (unwind-protect
8075 (progn
8076 (js2-parse-statements pn)
8077 (js2-must-match js2-RC "msg.no.brace.block")
8078 (setf (js2-node-len pn) (- js2-token-end pos)))
8079 (js2-pop-scope))
8080 pn))
8081
8082 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8083 (defun js2-parse-semi ()
8084 "Parse a statement or handle an error.
8085 Last matched token is `js2-SEMI' or `js2-ERROR'."
8086 (let ((tt (js2-peek-token)) pos len)
8087 (js2-consume-token)
8088 (if (eq tt js2-SEMI)
8089 (make-js2-empty-expr-node :len 1)
8090 (setq pos js2-token-beg
8091 len (- js2-token-beg pos))
8092 (js2-report-error "msg.syntax" nil pos len)
8093 (make-js2-error-node :pos pos :len len))))
8094
8095 (defun js2-parse-default-xml-namespace ()
8096 "Parse a `default xml namespace = <expr>' e4x statement."
8097 (let ((pos js2-token-beg)
8098 end len expr unary es)
8099 (js2-consume-token)
8100 (js2-must-have-xml)
8101 (js2-set-requires-activation)
8102 (setq len (- js2-ts-cursor pos))
8103 (unless (and (js2-match-token js2-NAME)
8104 (string= js2-ts-string "xml"))
8105 (js2-report-error "msg.bad.namespace" nil pos len))
8106 (unless (and (js2-match-token js2-NAME)
8107 (string= js2-ts-string "namespace"))
8108 (js2-report-error "msg.bad.namespace" nil pos len))
8109 (unless (js2-match-token js2-ASSIGN)
8110 (js2-report-error "msg.bad.namespace" nil pos len))
8111 (setq expr (js2-parse-expr)
8112 end (js2-node-end expr)
8113 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8114 :pos pos
8115 :len (- end pos)
8116 :operand expr))
8117 (js2-node-add-children unary expr)
8118 (make-js2-expr-stmt-node :pos pos
8119 :len (- end pos)
8120 :expr unary)))
8121
8122 (defun js2-record-label (label bundle)
8123 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8124 (js2-consume-token)
8125 (let ((name (js2-label-node-name label))
8126 labeled-stmt
8127 dup)
8128 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8129 ;; flag both labels if possible when used in editing mode
8130 (if (and js2-parse-ide-mode
8131 (setq dup (js2-get-label-by-name labeled-stmt name)))
8132 (js2-report-error "msg.dup.label" nil
8133 (js2-node-abs-pos dup) (js2-node-len dup)))
8134 (js2-report-error "msg.dup.label" nil
8135 (js2-node-pos label) (js2-node-len label)))
8136 (js2-labeled-stmt-node-add-label bundle label)
8137 (js2-node-add-children bundle label)
8138 ;; Add one reference to the bundle per label in `js2-label-set'
8139 (push (cons name bundle) js2-label-set)))
8140
8141 (defun js2-parse-name-or-label ()
8142 "Parser for identifier or label. Last token matched must be js2-NAME.
8143 Called when we found a name in a statement context. If it's a label, we gather
8144 up any following labels and the next non-label statement into a
8145 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8146 expression and return it wrapped in a `js2-expr-stmt-node'."
8147 (let ((pos js2-token-beg)
8148 (end js2-token-end)
8149 expr stmt pn bundle
8150 (continue t))
8151 ;; set check for label and call down to `js2-parse-primary-expr'
8152 (js2-set-check-for-label)
8153 (setq expr (js2-parse-expr))
8154 (if (/= (js2-node-type expr) js2-LABEL)
8155 ;; Parsed non-label expression - wrap with expression stmt.
8156 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8157 ;; else parsed a label
8158 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8159 (js2-record-label expr bundle)
8160 ;; look for more labels
8161 (while (and continue (= (js2-peek-token) js2-NAME))
8162 (js2-set-check-for-label)
8163 (setq expr (js2-parse-expr))
8164 (if (/= (js2-node-type expr) js2-LABEL)
8165 (progn
8166 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8167 continue nil)
8168 (js2-auto-insert-semicolon stmt))
8169 (js2-record-label expr bundle)))
8170 ;; no more labels; now parse the labeled statement
8171 (unwind-protect
8172 (unless stmt
8173 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8174 (setq stmt (js2-statement-helper))))
8175 ;; remove the labels for this statement from the global set
8176 (dolist (label (js2-labeled-stmt-node-labels bundle))
8177 (setq js2-label-set (remove label js2-label-set))))
8178 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8179 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8180 (js2-node-add-children bundle stmt)
8181 bundle)))
8182
8183 (defun js2-parse-expr-stmt ()
8184 "Default parser in statement context, if no recognized statement found."
8185 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8186
8187 (defun js2-parse-variables (decl-type pos)
8188 "Parse a comma-separated list of variable declarations.
8189 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8190
8191 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8192 For 'var' or 'const', the keyword should be the token last scanned.
8193
8194 POS is the position where the node should start. It's sometimes the
8195 var/const/let keyword, and other times the beginning of the first token
8196 in the first variable declaration.
8197
8198 Returns the parsed `js2-var-decl-node' expression node."
8199 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8200 :pos pos))
8201 destructuring kid-pos tt init name end nbeg nend vi
8202 (continue t))
8203 ;; Example:
8204 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8205 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8206 ;; var {a, b} = baz;
8207 (while continue
8208 (setq destructuring nil
8209 name nil
8210 tt (js2-peek-token)
8211 kid-pos js2-token-beg
8212 end js2-token-end
8213 init nil)
8214 (if (or (= tt js2-LB) (= tt js2-LC))
8215 ;; Destructuring assignment, e.g., var [a, b] = ...
8216 (setq destructuring (js2-parse-destruct-primary-expr)
8217 end (js2-node-end destructuring))
8218 ;; Simple variable name
8219 (when (js2-must-match js2-NAME "msg.bad.var")
8220 (setq name (js2-create-name-node)
8221 nbeg js2-token-beg
8222 nend js2-token-end
8223 end nend)
8224 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8225 (when (js2-match-token js2-ASSIGN)
8226 (setq init (js2-parse-assign-expr)
8227 end (js2-node-end init))
8228 (js2-record-imenu-functions init name))
8229 (when name
8230 (js2-set-face nbeg nend (if (js2-function-node-p init)
8231 'font-lock-function-name-face
8232 'font-lock-variable-name-face)
8233 'record))
8234 (setq vi (make-js2-var-init-node :pos kid-pos
8235 :len (- end kid-pos)
8236 :type decl-type))
8237 (if destructuring
8238 (progn
8239 (if (and (null init) (not js2-in-for-init))
8240 (js2-report-error "msg.destruct.assign.no.init"))
8241 (js2-define-destruct-symbols destructuring
8242 decl-type
8243 'font-lock-variable-name-face)
8244 (setf (js2-var-init-node-target vi) destructuring))
8245 (setf (js2-var-init-node-target vi) name))
8246 (setf (js2-var-init-node-initializer vi) init)
8247 (js2-node-add-children vi name destructuring init)
8248 (js2-block-node-push result vi)
8249 (unless (js2-match-token js2-COMMA)
8250 (setq continue nil)))
8251 (setf (js2-node-len result) (- end pos))
8252 result))
8253
8254 (defun js2-parse-let (pos &optional stmt-p)
8255 "Parse a let expression or statement.
8256 A let-expression is of the form `let (vars) expr'.
8257 A let-statment is of the form `let (vars) {statements}'.
8258 The third form of let is a variable declaration list, handled
8259 by `js2-parse-variables'."
8260 (let ((pn (make-js2-let-node :pos pos))
8261 beg vars body)
8262 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8263 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8264 (js2-push-scope pn)
8265 (unwind-protect
8266 (progn
8267 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8268 (if (js2-must-match js2-RP "msg.no.paren.let")
8269 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8270 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8271 ;; let statement
8272 (progn
8273 (js2-consume-token)
8274 (setf beg js2-token-beg ; position stmt at LC
8275 body (js2-parse-statements))
8276 (js2-must-match js2-RC "msg.no.curly.let")
8277 (setf (js2-node-len body) (- js2-token-end beg)
8278 (js2-node-len pn) (- js2-token-end pos)
8279 (js2-let-node-body pn) body
8280 (js2-node-type pn) js2-LET))
8281 ;; let expression
8282 (setf body (js2-parse-expr)
8283 (js2-node-len pn) (- (js2-node-end body) pos)
8284 (js2-let-node-body pn) body))
8285 (js2-node-add-children pn vars body))
8286 (js2-pop-scope))
8287 pn))
8288
8289 (defun js2-define-new-symbol (decl-type name node &optional scope)
8290 (js2-scope-put-symbol (or scope js2-current-scope)
8291 name
8292 (make-js2-symbol decl-type name node)))
8293
8294 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8295 "Define a symbol in the current scope.
8296 If NODE is non-nil, it is the AST node associated with the symbol."
8297 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8298 (symbol (if defining-scope
8299 (js2-scope-get-symbol defining-scope name)))
8300 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8301 (cond
8302 ((and symbol ; already defined
8303 (or (= sdt js2-CONST) ; old version is const
8304 (= decl-type js2-CONST) ; new version is const
8305 ;; two let-bound vars in this block have same name
8306 (and (= sdt js2-LET)
8307 (eq defining-scope js2-current-scope))))
8308 (js2-report-error
8309 (cond
8310 ((= sdt js2-CONST) "msg.const.redecl")
8311 ((= sdt js2-LET) "msg.let.redecl")
8312 ((= sdt js2-VAR) "msg.var.redecl")
8313 ((= sdt js2-FUNCTION) "msg.function.redecl")
8314 (t "msg.parm.redecl"))
8315 name))
8316 ((= decl-type js2-LET)
8317 (if (and (not ignore-not-in-block)
8318 (or (= (js2-node-type js2-current-scope) js2-IF)
8319 (js2-loop-node-p js2-current-scope)))
8320 (js2-report-error "msg.let.decl.not.in.block")
8321 (js2-define-new-symbol decl-type name node)))
8322 ((or (= decl-type js2-VAR)
8323 (= decl-type js2-CONST)
8324 (= decl-type js2-FUNCTION))
8325 (if symbol
8326 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8327 (js2-add-strict-warning "msg.var.redecl" name)
8328 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8329 (js2-add-strict-warning "msg.var.hides.arg" name)))
8330 (js2-define-new-symbol decl-type name node
8331 js2-current-script-or-fn)))
8332 ((= decl-type js2-LP)
8333 (if symbol
8334 ;; must be duplicate parameter. Second parameter hides the
8335 ;; first, so go ahead and add the second pararameter
8336 (js2-report-warning "msg.dup.parms" name))
8337 (js2-define-new-symbol decl-type name node))
8338 (t (js2-code-bug)))))
8339
8340 (defun js2-parse-expr (&optional oneshot)
8341 (let* ((pn (js2-parse-assign-expr))
8342 (pos (js2-node-pos pn))
8343 left
8344 right
8345 op-pos)
8346 (while (and (not oneshot)
8347 (js2-match-token js2-COMMA))
8348 (setq op-pos (- js2-token-beg pos)) ; relative
8349 (if (= (js2-peek-token) js2-YIELD)
8350 (js2-report-error "msg.yield.parenthesized"))
8351 (setq right (js2-parse-assign-expr)
8352 left pn
8353 pn (make-js2-infix-node :type js2-COMMA
8354 :pos pos
8355 :len (- js2-ts-cursor pos)
8356 :op-pos op-pos
8357 :left left
8358 :right right))
8359 (js2-node-add-children pn left right))
8360 pn))
8361
8362 (defun js2-parse-assign-expr ()
8363 (let ((tt (js2-peek-token))
8364 (pos js2-token-beg)
8365 pn left right op-pos)
8366 (if (= tt js2-YIELD)
8367 (js2-parse-return-or-yield tt t)
8368 ;; not yield - parse assignment expression
8369 (setq pn (js2-parse-cond-expr)
8370 tt (js2-peek-token))
8371 (when (and (<= js2-first-assign tt)
8372 (<= tt js2-last-assign))
8373 ;; tt express assignment (=, |=, ^=, ..., %=)
8374 (js2-consume-token)
8375 (setq op-pos (- js2-token-beg pos) ; relative
8376 left pn
8377 right (js2-parse-assign-expr)
8378 pn (make-js2-assign-node :type tt
8379 :pos pos
8380 :len (- (js2-node-end right) pos)
8381 :op-pos op-pos
8382 :left left
8383 :right right))
8384 (when js2-parse-ide-mode
8385 (js2-highlight-assign-targets pn left right)
8386 (js2-record-imenu-functions right left))
8387 ;; do this last so ide checks above can use absolute positions
8388 (js2-node-add-children pn left right))
8389 pn)))
8390
8391 (defun js2-parse-cond-expr ()
8392 (let ((pos js2-token-beg)
8393 (pn (js2-parse-or-expr))
8394 test-expr
8395 if-true
8396 if-false
8397 q-pos
8398 c-pos)
8399 (when (js2-match-token js2-HOOK)
8400 (setq q-pos (- js2-token-beg pos)
8401 if-true (js2-parse-assign-expr))
8402 (js2-must-match js2-COLON "msg.no.colon.cond")
8403 (setq c-pos (- js2-token-beg pos)
8404 if-false (js2-parse-assign-expr)
8405 test-expr pn
8406 pn (make-js2-cond-node :pos pos
8407 :len (- (js2-node-end if-false) pos)
8408 :test-expr test-expr
8409 :true-expr if-true
8410 :false-expr if-false
8411 :q-pos q-pos
8412 :c-pos c-pos))
8413 (js2-node-add-children pn test-expr if-true if-false))
8414 pn))
8415
8416 (defun js2-make-binary (type left parser)
8417 "Helper for constructing a binary-operator AST node.
8418 LEFT is the left-side-expression, already parsed, and the
8419 binary operator should have just been matched.
8420 PARSER is a function to call to parse the right operand,
8421 or a `js2-node' struct if it has already been parsed."
8422 (let* ((pos (js2-node-pos left))
8423 (op-pos (- js2-token-beg pos))
8424 (right (if (js2-node-p parser)
8425 parser
8426 (funcall parser)))
8427 (pn (make-js2-infix-node :type type
8428 :pos pos
8429 :len (- (js2-node-end right) pos)
8430 :op-pos op-pos
8431 :left left
8432 :right right)))
8433 (js2-node-add-children pn left right)
8434 pn))
8435
8436 (defun js2-parse-or-expr ()
8437 (let ((pn (js2-parse-and-expr)))
8438 (when (js2-match-token js2-OR)
8439 (setq pn (js2-make-binary js2-OR
8440 pn
8441 'js2-parse-or-expr)))
8442 pn))
8443
8444 (defun js2-parse-and-expr ()
8445 (let ((pn (js2-parse-bit-or-expr)))
8446 (when (js2-match-token js2-AND)
8447 (setq pn (js2-make-binary js2-AND
8448 pn
8449 'js2-parse-and-expr)))
8450 pn))
8451
8452 (defun js2-parse-bit-or-expr ()
8453 (let ((pn (js2-parse-bit-xor-expr)))
8454 (while (js2-match-token js2-BITOR)
8455 (setq pn (js2-make-binary js2-BITOR
8456 pn
8457 'js2-parse-bit-xor-expr)))
8458 pn))
8459
8460 (defun js2-parse-bit-xor-expr ()
8461 (let ((pn (js2-parse-bit-and-expr)))
8462 (while (js2-match-token js2-BITXOR)
8463 (setq pn (js2-make-binary js2-BITXOR
8464 pn
8465 'js2-parse-bit-and-expr)))
8466 pn))
8467
8468 (defun js2-parse-bit-and-expr ()
8469 (let ((pn (js2-parse-eq-expr)))
8470 (while (js2-match-token js2-BITAND)
8471 (setq pn (js2-make-binary js2-BITAND
8472 pn
8473 'js2-parse-eq-expr)))
8474 pn))
8475
8476 (defconst js2-parse-eq-ops
8477 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8478
8479 (defun js2-parse-eq-expr ()
8480 (let ((pn (js2-parse-rel-expr))
8481 tt)
8482 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8483 (js2-consume-token)
8484 (setq pn (js2-make-binary tt
8485 pn
8486 'js2-parse-rel-expr)))
8487 pn))
8488
8489 (defconst js2-parse-rel-ops
8490 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8491
8492 (defun js2-parse-rel-expr ()
8493 (let ((pn (js2-parse-shift-expr))
8494 (continue t)
8495 tt)
8496 (while continue
8497 (setq tt (js2-peek-token))
8498 (cond
8499 ((and js2-in-for-init (= tt js2-IN))
8500 (setq continue nil))
8501 ((memq tt js2-parse-rel-ops)
8502 (js2-consume-token)
8503 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8504 (t
8505 (setq continue nil))))
8506 pn))
8507
8508 (defconst js2-parse-shift-ops
8509 (list js2-LSH js2-URSH js2-RSH))
8510
8511 (defun js2-parse-shift-expr ()
8512 (let ((pn (js2-parse-add-expr))
8513 tt
8514 (continue t))
8515 (while continue
8516 (setq tt (js2-peek-token))
8517 (if (memq tt js2-parse-shift-ops)
8518 (progn
8519 (js2-consume-token)
8520 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8521 (setq continue nil)))
8522 pn))
8523
8524 (defun js2-parse-add-expr ()
8525 (let ((pn (js2-parse-mul-expr))
8526 tt
8527 (continue t))
8528 (while continue
8529 (setq tt (js2-peek-token))
8530 (if (or (= tt js2-ADD) (= tt js2-SUB))
8531 (progn
8532 (js2-consume-token)
8533 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8534 (setq continue nil)))
8535 pn))
8536
8537 (defconst js2-parse-mul-ops
8538 (list js2-MUL js2-DIV js2-MOD))
8539
8540 (defun js2-parse-mul-expr ()
8541 (let ((pn (js2-parse-unary-expr))
8542 tt
8543 (continue t))
8544 (while continue
8545 (setq tt (js2-peek-token))
8546 (if (memq tt js2-parse-mul-ops)
8547 (progn
8548 (js2-consume-token)
8549 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8550 (setq continue nil)))
8551 pn))
8552
8553 (defun js2-make-unary (type parser &rest args)
8554 "Make a unary node of type TYPE.
8555 PARSER is either a node (for postfix operators) or a function to call
8556 to parse the operand (for prefix operators)."
8557 (let* ((pos js2-token-beg)
8558 (postfix (js2-node-p parser))
8559 (expr (if postfix
8560 parser
8561 (apply parser args)))
8562 end
8563 pn)
8564 (if postfix ; e.g. i++
8565 (setq pos (js2-node-pos expr)
8566 end js2-token-end)
8567 (setq end (js2-node-end expr)))
8568 (setq pn (make-js2-unary-node :type type
8569 :pos pos
8570 :len (- end pos)
8571 :operand expr))
8572 (js2-node-add-children pn expr)
8573 pn))
8574
8575 (defconst js2-incrementable-node-types
8576 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8577 "Node types that can be the operand of a ++ or -- operator.")
8578
8579 (defun js2-check-bad-inc-dec (tt beg end unary)
8580 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8581 js2-incrementable-node-types)
8582 (js2-report-error (if (= tt js2-INC)
8583 "msg.bad.incr"
8584 "msg.bad.decr")
8585 nil beg (- end beg))))
8586
8587 (defun js2-parse-unary-expr ()
8588 (let ((tt (js2-peek-token))
8589 pn expr beg end)
8590 (cond
8591 ((or (= tt js2-VOID)
8592 (= tt js2-NOT)
8593 (= tt js2-BITNOT)
8594 (= tt js2-TYPEOF))
8595 (js2-consume-token)
8596 (js2-make-unary tt 'js2-parse-unary-expr))
8597 ((= tt js2-ADD)
8598 (js2-consume-token)
8599 ;; Convert to special POS token in decompiler and parse tree
8600 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8601 ((= tt js2-SUB)
8602 (js2-consume-token)
8603 ;; Convert to special NEG token in decompiler and parse tree
8604 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8605 ((or (= tt js2-INC)
8606 (= tt js2-DEC))
8607 (js2-consume-token)
8608 (prog1
8609 (setq beg js2-token-beg
8610 end js2-token-end
8611 expr (js2-make-unary tt 'js2-parse-member-expr t))
8612 (js2-check-bad-inc-dec tt beg end expr)))
8613 ((= tt js2-DELPROP)
8614 (js2-consume-token)
8615 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8616 ((= tt js2-ERROR)
8617 (js2-consume-token)
8618 (make-js2-error-node)) ; try to continue
8619 ((and (= tt js2-LT)
8620 js2-compiler-xml-available)
8621 ;; XML stream encountered in expression.
8622 (js2-consume-token)
8623 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8624 (t
8625 (setq pn (js2-parse-member-expr t)
8626 ;; Don't look across a newline boundary for a postfix incop.
8627 tt (js2-peek-token-or-eol))
8628 (when (or (= tt js2-INC) (= tt js2-DEC))
8629 (js2-consume-token)
8630 (setf expr pn
8631 pn (js2-make-unary tt expr))
8632 (js2-node-set-prop pn 'postfix t)
8633 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8634 pn))))
8635
8636 (defun js2-parse-xml-initializer ()
8637 "Parse an E4X XML initializer.
8638 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8639 Then I'll postprocess the result, depending on whether we're in IDE
8640 mode or codegen mode, and generate the appropriate rewritten AST.
8641 IDE mode uses a rich AST that models the XML structure. Codegen mode
8642 just concatenates everything and makes a new XML or XMLList out of it."
8643 (let ((tt (js2-get-first-xml-token))
8644 pn-xml pn expr kids expr-pos
8645 (continue t)
8646 (first-token t))
8647 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8648 (js2-report-error "msg.syntax"))
8649 (setq pn-xml (make-js2-xml-node))
8650 (while continue
8651 (if first-token
8652 (setq first-token nil)
8653 (setq tt (js2-get-next-xml-token)))
8654 (cond
8655 ;; js2-XML means we found a {expr} in the XML stream.
8656 ;; The js2-ts-string is the XML up to the left-curly.
8657 ((= tt js2-XML)
8658 (push (make-js2-string-node :pos js2-token-beg
8659 :len (- js2-ts-cursor js2-token-beg))
8660 kids)
8661 (js2-must-match js2-LC "msg.syntax")
8662 (setq expr-pos js2-ts-cursor
8663 expr (if (eq (js2-peek-token) js2-RC)
8664 (make-js2-empty-expr-node :pos expr-pos)
8665 (js2-parse-expr)))
8666 (js2-must-match js2-RC "msg.syntax")
8667 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8668 :len (js2-node-len expr)
8669 :expr expr))
8670 (js2-node-add-children pn expr)
8671 (push pn kids))
8672 ;; a js2-XMLEND token means we hit the final close-tag.
8673 ((= tt js2-XMLEND)
8674 (push (make-js2-string-node :pos js2-token-beg
8675 :len (- js2-ts-cursor js2-token-beg))
8676 kids)
8677 (dolist (kid (nreverse kids))
8678 (js2-block-node-push pn-xml kid))
8679 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8680 (js2-node-pos pn-xml))
8681 continue nil))
8682 (t
8683 (js2-report-error "msg.syntax")
8684 (setq continue nil))))
8685 pn-xml))
8686
8687
8688 (defun js2-parse-argument-list ()
8689 "Parse an argument list and return it as a Lisp list of nodes.
8690 Returns the list in reverse order. Consumes the right-paren token."
8691 (let (result)
8692 (unless (js2-match-token js2-RP)
8693 (loop do
8694 (if (= (js2-peek-token) js2-YIELD)
8695 (js2-report-error "msg.yield.parenthesized"))
8696 (push (js2-parse-assign-expr) result)
8697 while
8698 (js2-match-token js2-COMMA))
8699 (js2-must-match js2-RP "msg.no.paren.arg")
8700 result)))
8701
8702 (defun js2-parse-member-expr (&optional allow-call-syntax)
8703 (let ((tt (js2-peek-token))
8704 pn pos target args beg end init tail)
8705 (if (/= tt js2-NEW)
8706 (setq pn (js2-parse-primary-expr))
8707 ;; parse a 'new' expression
8708 (js2-consume-token)
8709 (setq pos js2-token-beg
8710 beg pos
8711 target (js2-parse-member-expr)
8712 end (js2-node-end target)
8713 pn (make-js2-new-node :pos pos
8714 :target target
8715 :len (- end pos)))
8716 (js2-node-add-children pn target)
8717 (when (js2-match-token js2-LP)
8718 ;; Add the arguments to pn, if any are supplied.
8719 (setf beg pos ; start of "new" keyword
8720 pos js2-token-beg
8721 args (nreverse (js2-parse-argument-list))
8722 (js2-new-node-args pn) args
8723 end js2-token-end
8724 (js2-new-node-lp pn) (- pos beg)
8725 (js2-new-node-rp pn) (- end 1 beg))
8726 (apply #'js2-node-add-children pn args))
8727 (when (and js2-allow-rhino-new-expr-initializer
8728 (js2-match-token js2-LC))
8729 (setf init (js2-parse-object-literal)
8730 end (js2-node-end init)
8731 (js2-new-node-initializer pn) init)
8732 (js2-node-add-children pn init))
8733 (setf (js2-node-len pn) (- end beg))) ; end outer if
8734 (js2-parse-member-expr-tail allow-call-syntax pn)))
8735
8736 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8737 "Parse a chain of property/array accesses or function calls.
8738 Includes parsing for E4X operators like `..' and `.@'.
8739 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8740 Returns an expression tree that includes PN, the parent node."
8741 (let ((beg (js2-node-pos pn))
8742 tt
8743 (continue t))
8744 (while continue
8745 (setq tt (js2-peek-token))
8746 (cond
8747 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8748 (setq pn (js2-parse-property-access tt pn)))
8749 ((= tt js2-DOTQUERY)
8750 (setq pn (js2-parse-dot-query pn)))
8751 ((= tt js2-LB)
8752 (setq pn (js2-parse-element-get pn)))
8753 ((= tt js2-LP)
8754 (if allow-call-syntax
8755 (setq pn (js2-parse-function-call pn))
8756 (setq continue nil)))
8757 (t
8758 (setq continue nil))))
8759 (if (>= js2-highlight-level 2)
8760 (js2-parse-highlight-member-expr-node pn))
8761 pn))
8762
8763 (defun js2-parse-dot-query (pn)
8764 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8765 Last token parsed must be `js2-DOTQUERY'."
8766 (let ((pos (js2-node-pos pn))
8767 op-pos expr end)
8768 (js2-consume-token)
8769 (js2-must-have-xml)
8770 (js2-set-requires-activation)
8771 (setq op-pos js2-token-beg
8772 expr (js2-parse-expr)
8773 end (js2-node-end expr)
8774 pn (make-js2-xml-dot-query-node :left pn
8775 :pos pos
8776 :op-pos op-pos
8777 :right expr))
8778 (js2-node-add-children pn
8779 (js2-xml-dot-query-node-left pn)
8780 (js2-xml-dot-query-node-right pn))
8781 (if (js2-must-match js2-RP "msg.no.paren")
8782 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
8783 end js2-token-end))
8784 (setf (js2-node-len pn) (- end pos))
8785 pn))
8786
8787 (defun js2-parse-element-get (pn)
8788 "Parse an element-get expression, e.g. foo[bar].
8789 Last token parsed must be `js2-RB'."
8790 (let ((lb js2-token-beg)
8791 (pos (js2-node-pos pn))
8792 rb expr)
8793 (js2-consume-token)
8794 (setq expr (js2-parse-expr))
8795 (if (js2-must-match js2-RB "msg.no.bracket.index")
8796 (setq rb js2-token-beg))
8797 (setq pn (make-js2-elem-get-node :target pn
8798 :pos pos
8799 :element expr
8800 :lb (js2-relpos lb pos)
8801 :rb (js2-relpos rb pos)
8802 :len (- js2-token-end pos)))
8803 (js2-node-add-children pn
8804 (js2-elem-get-node-target pn)
8805 (js2-elem-get-node-element pn))
8806 pn))
8807
8808 (defun js2-parse-function-call (pn)
8809 (let (args
8810 (pos (js2-node-pos pn)))
8811 (js2-consume-token)
8812 (setq pn (make-js2-call-node :pos pos
8813 :target pn
8814 :lp (- js2-token-beg pos)))
8815 (js2-node-add-children pn (js2-call-node-target pn))
8816 ;; Add the arguments to pn, if any are supplied.
8817 (setf args (nreverse (js2-parse-argument-list))
8818 (js2-call-node-rp pn) (- js2-token-beg pos)
8819 (js2-call-node-args pn) args)
8820 (apply #'js2-node-add-children pn args)
8821 (setf (js2-node-len pn) (- js2-ts-cursor pos))
8822 pn))
8823
8824 (defun js2-parse-property-access (tt pn)
8825 "Parse a property access, XML descendants access, or XML attr access."
8826 (let ((member-type-flags 0)
8827 (dot-pos js2-token-beg)
8828 (dot-len (if (= tt js2-DOTDOT) 2 1))
8829 name
8830 ref ; right side of . or .. operator
8831 result)
8832 (js2-consume-token)
8833 (when (= tt js2-DOTDOT)
8834 (js2-must-have-xml)
8835 (setq member-type-flags js2-descendants-flag))
8836 (if (not js2-compiler-xml-available)
8837 (progn
8838 (js2-must-match-prop-name "msg.no.name.after.dot")
8839 (setq name (js2-create-name-node t js2-GETPROP)
8840 result (make-js2-prop-get-node :left pn
8841 :pos js2-token-beg
8842 :right name
8843 :len (- js2-token-end
8844 js2-token-beg)))
8845 (js2-node-add-children result pn name)
8846 result)
8847 ;; otherwise look for XML operators
8848 (setf result (if (= tt js2-DOT)
8849 (make-js2-prop-get-node)
8850 (make-js2-infix-node :type js2-DOTDOT))
8851 (js2-node-pos result) (js2-node-pos pn)
8852 (js2-infix-node-op-pos result) dot-pos
8853 (js2-infix-node-left result) pn ; do this after setting position
8854 tt (js2-next-token))
8855 (cond
8856 ;; needed for generator.throw()
8857 ((= tt js2-THROW)
8858 (js2-save-name-token-data js2-token-beg "throw")
8859 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
8860 ;; handles: name, ns::name, ns::*, ns::[expr]
8861 ((js2-valid-prop-name-token tt)
8862 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
8863 ;; handles: *, *::name, *::*, *::[expr]
8864 ((= tt js2-MUL)
8865 (js2-save-name-token-data js2-token-beg "*")
8866 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
8867 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
8868 ((= tt js2-XMLATTR)
8869 (setq result (js2-parse-attribute-access)))
8870 (t
8871 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
8872 (if ref
8873 (setf (js2-node-len result) (- (js2-node-end ref)
8874 (js2-node-pos result))
8875 (js2-infix-node-right result) ref))
8876 (if (js2-infix-node-p result)
8877 (js2-node-add-children result
8878 (js2-infix-node-left result)
8879 (js2-infix-node-right result)))
8880 result)))
8881
8882 (defun js2-parse-attribute-access ()
8883 "Parse an E4X XML attribute expression.
8884 This includes expressions of the forms:
8885
8886 @attr @ns::attr @ns::*
8887 @* @*::attr @*::*
8888 @[expr] @*::[expr] @ns::[expr]
8889
8890 Called if we peeked an '@' token."
8891 (let ((tt (js2-next-token))
8892 (at-pos js2-token-beg))
8893 (cond
8894 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
8895 ((js2-valid-prop-name-token tt)
8896 (js2-parse-property-name at-pos js2-ts-string 0))
8897 ;; handles: @*, @*::name, @*::*, @*::[expr]
8898 ((= tt js2-MUL)
8899 (js2-save-name-token-data js2-token-beg "*")
8900 (js2-parse-property-name js2-token-beg "*" 0))
8901 ;; handles @[expr]
8902 ((= tt js2-LB)
8903 (js2-parse-xml-elem-ref at-pos))
8904 (t
8905 (js2-report-error "msg.no.name.after.xmlAttr")
8906 ;; Avoid cascaded errors that happen if we make an error node here.
8907 (js2-save-name-token-data js2-token-beg "")
8908 (js2-parse-property-name js2-token-beg "" 0)))))
8909
8910 (defun js2-parse-property-name (at-pos s member-type-flags)
8911 "Check if :: follows name in which case it becomes qualified name.
8912
8913 AT-POS is a natural number if we just read an '@' token, else nil.
8914 S is the name or string that was matched: an identifier, 'throw' or '*'.
8915 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
8916
8917 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
8918 operator, or the name is followed by ::. For a plain name, returns a
8919 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
8920 (let ((pos (or at-pos js2-token-beg))
8921 colon-pos
8922 (name (js2-create-name-node t js2-current-token))
8923 ns tt ref pn)
8924 (catch 'return
8925 (when (js2-match-token js2-COLONCOLON)
8926 (setq ns name
8927 colon-pos js2-token-beg
8928 tt (js2-next-token))
8929 (cond
8930 ;; handles name::name
8931 ((js2-valid-prop-name-token tt)
8932 (setq name (js2-create-name-node)))
8933 ;; handles name::*
8934 ((= tt js2-MUL)
8935 (js2-save-name-token-data js2-token-beg "*")
8936 (setq name (js2-create-name-node)))
8937 ;; handles name::[expr]
8938 ((= tt js2-LB)
8939 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
8940 (t
8941 (js2-report-error "msg.no.name.after.coloncolon"))))
8942 (if (and (null ns) (zerop member-type-flags))
8943 name
8944 (prog1
8945 (setq pn
8946 (make-js2-xml-prop-ref-node :pos pos
8947 :len (- (js2-node-end name) pos)
8948 :at-pos at-pos
8949 :colon-pos colon-pos
8950 :propname name))
8951 (js2-node-add-children pn name))))))
8952
8953 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
8954 "Parse the [expr] portion of an xml element reference.
8955 For instance, @[expr], @*::[expr], or ns::[expr]."
8956 (let* ((lb js2-token-beg)
8957 (pos (or at-pos lb))
8958 rb
8959 (expr (js2-parse-expr))
8960 (end (js2-node-end expr))
8961 pn)
8962 (if (js2-must-match js2-RB "msg.no.bracket.index")
8963 (setq rb js2-token-beg
8964 end js2-token-end))
8965 (prog1
8966 (setq pn
8967 (make-js2-xml-elem-ref-node :pos pos
8968 :len (- end pos)
8969 :namespace namespace
8970 :colon-pos colon-pos
8971 :at-pos at-pos
8972 :expr expr
8973 :lb (js2-relpos lb pos)
8974 :rb (js2-relpos rb pos)))
8975 (js2-node-add-children pn namespace expr))))
8976
8977 (defun js2-parse-destruct-primary-expr ()
8978 (let ((js2-is-in-destructuring t))
8979 (js2-parse-primary-expr)))
8980
8981 (defun js2-parse-primary-expr ()
8982 "Parse a literal (leaf) expression of some sort.
8983 Includes complex literals such as functions, object-literals,
8984 array-literals, array comprehensions and regular expressions."
8985 (let ((tt-flagged (js2-next-flagged-token))
8986 pn ; parent node (usually return value)
8987 tt
8988 px-pos ; paren-expr pos
8989 len
8990 flags ; regexp flags
8991 expr)
8992 (setq tt js2-current-token)
8993 (cond
8994 ((= tt js2-FUNCTION)
8995 (js2-parse-function 'FUNCTION_EXPRESSION))
8996 ((= tt js2-LB)
8997 (js2-parse-array-literal))
8998 ((= tt js2-LC)
8999 (js2-parse-object-literal))
9000 ((= tt js2-LET)
9001 (js2-parse-let js2-token-beg))
9002 ((= tt js2-LP)
9003 (setq px-pos js2-token-beg
9004 expr (js2-parse-expr))
9005 (js2-must-match js2-RP "msg.no.paren")
9006 (setq pn (make-js2-paren-node :pos px-pos
9007 :expr expr
9008 :len (- js2-token-end px-pos)))
9009 (js2-node-add-children pn (js2-paren-node-expr pn))
9010 pn)
9011 ((= tt js2-XMLATTR)
9012 (js2-must-have-xml)
9013 (js2-parse-attribute-access))
9014 ((= tt js2-NAME)
9015 (js2-parse-name tt-flagged tt))
9016 ((= tt js2-NUMBER)
9017 (make-js2-number-node))
9018 ((= tt js2-STRING)
9019 (prog1
9020 (make-js2-string-node)
9021 (js2-record-face 'font-lock-string-face)))
9022 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9023 ;; Got / or /= which in this context means a regexp literal
9024 (setq px-pos js2-token-beg)
9025 (js2-read-regexp tt)
9026 (setq flags js2-ts-regexp-flags
9027 js2-ts-regexp-flags nil)
9028 (prog1
9029 (make-js2-regexp-node :pos px-pos
9030 :len (- js2-ts-cursor px-pos)
9031 :value js2-ts-string
9032 :flags flags)
9033 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9034 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9035 ((or (= tt js2-NULL)
9036 (= tt js2-THIS)
9037 (= tt js2-FALSE)
9038 (= tt js2-TRUE))
9039 (make-js2-keyword-node :type tt))
9040 ((= tt js2-RESERVED)
9041 (js2-report-error "msg.reserved.id")
9042 (make-js2-name-node))
9043 ((= tt js2-ERROR)
9044 ;; the scanner or one of its subroutines reported the error.
9045 (make-js2-error-node))
9046 ((= tt js2-EOF)
9047 (setq px-pos (point-at-bol)
9048 len (- js2-ts-cursor px-pos))
9049 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9050 (make-js2-error-node :pos px-pos :len len))
9051 (t
9052 (js2-report-error "msg.syntax")
9053 (make-js2-error-node)))))
9054
9055 (defun js2-parse-name (tt-flagged tt)
9056 (let ((name js2-ts-string)
9057 (name-pos js2-token-beg)
9058 node)
9059 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9060 (= (js2-peek-token) js2-COLON))
9061 (prog1
9062 ;; Do not consume colon, it is used as unwind indicator
9063 ;; to return to statementHelper.
9064 (make-js2-label-node :pos name-pos
9065 :len (- js2-token-end name-pos)
9066 :name name)
9067 (js2-set-face name-pos
9068 js2-token-end
9069 'font-lock-variable-name-face 'record))
9070 ;; Otherwise not a label, just a name. Unfortunately peeking
9071 ;; the next token to check for a colon has biffed js2-token-beg
9072 ;; and js2-token-end. We store the name's bounds in buffer vars
9073 ;; and `js2-create-name-node' uses them.
9074 (js2-save-name-token-data name-pos name)
9075 (setq node (if js2-compiler-xml-available
9076 (js2-parse-property-name nil name 0)
9077 (js2-create-name-node 'check-activation)))
9078 (if js2-highlight-external-variables
9079 (js2-record-name-node node))
9080 node)))
9081
9082 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9083 (js2-add-strict-warning
9084 msg nil
9085 ;; back up from comma to beginning of line or array/objlit
9086 (max (if elems
9087 (js2-node-pos (car elems))
9088 pos)
9089 (save-excursion
9090 (goto-char comma-pos)
9091 (back-to-indentation)
9092 (point)))
9093 comma-pos))
9094
9095 (defun js2-parse-array-literal ()
9096 (let ((pos js2-token-beg)
9097 (end js2-token-end)
9098 (after-lb-or-comma t)
9099 after-comma tt elems pn
9100 (continue t))
9101 (unless js2-is-in-destructuring
9102 (js2-push-scope (make-js2-scope))) ; for array comp
9103 (while continue
9104 (setq tt (js2-peek-token))
9105 (cond
9106 ;; comma
9107 ((= tt js2-COMMA)
9108 (js2-consume-token)
9109 (setq after-comma js2-token-end)
9110 (if (not after-lb-or-comma)
9111 (setq after-lb-or-comma t)
9112 (push nil elems)))
9113 ;; end of array
9114 ((or (= tt js2-RB)
9115 (= tt js2-EOF)) ; prevent infinite loop
9116 (if (= tt js2-EOF)
9117 (js2-report-error "msg.no.bracket.arg" nil pos)
9118 (js2-consume-token))
9119 (setq continue nil
9120 end js2-token-end
9121 pn (make-js2-array-node :pos pos
9122 :len (- js2-ts-cursor pos)
9123 :elems (nreverse elems)))
9124 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9125 (when (and after-comma (not js2-is-in-destructuring))
9126 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9127 pos elems after-comma)))
9128 ;; destructuring binding
9129 (js2-is-in-destructuring
9130 (push (if (or (= tt js2-LC)
9131 (= tt js2-LB)
9132 (= tt js2-NAME))
9133 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9134 (js2-parse-destruct-primary-expr)
9135 ;; invalid pattern
9136 (js2-consume-token)
9137 (js2-report-error "msg.bad.var")
9138 (make-js2-error-node))
9139 elems)
9140 (setq after-lb-or-comma nil
9141 after-comma nil))
9142 ;; array comp
9143 ((and (>= js2-language-version 170)
9144 (= tt js2-FOR) ; check for array comprehension
9145 (not after-lb-or-comma) ; "for" can't follow a comma
9146 elems ; must have at least 1 element
9147 (not (cdr elems))) ; but no 2nd element
9148 (setf continue nil
9149 pn (js2-parse-array-comprehension (car elems) pos)))
9150
9151 ;; another element
9152 (t
9153 (unless after-lb-or-comma
9154 (js2-report-error "msg.no.bracket.arg"))
9155 (push (js2-parse-assign-expr) elems)
9156 (setq after-lb-or-comma nil
9157 after-comma nil))))
9158 (unless js2-is-in-destructuring
9159 (js2-pop-scope))
9160 pn))
9161
9162 (defun js2-parse-array-comprehension (expr pos)
9163 "Parse a JavaScript 1.7 Array Comprehension.
9164 EXPR is the first expression after the opening left-bracket.
9165 POS is the beginning of the LB token preceding EXPR.
9166 We should have just parsed the 'for' keyword before calling this function."
9167 (let (loops loop first prev filter if-pos result)
9168 (while (= (js2-peek-token) js2-FOR)
9169 (let ((prev (car loops))) ; rearrange scope chain
9170 (push (setq loop (js2-parse-array-comp-loop)) loops)
9171 (if prev ; each loop is parent scope to the next one
9172 (setf (js2-scope-parent-scope loop) prev)
9173 ; first loop takes expr scope's parent
9174 (setf (js2-scope-parent-scope (setq first loop))
9175 (js2-scope-parent-scope js2-current-scope)))))
9176 ;; set expr scope's parent to the last loop
9177 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9178 (when (= (js2-peek-token) js2-IF)
9179 (js2-consume-token)
9180 (setq if-pos (- js2-token-beg pos) ; relative
9181 filter (js2-parse-condition)))
9182 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9183 (setq result (make-js2-array-comp-node :pos pos
9184 :len (- js2-ts-cursor pos)
9185 :result expr
9186 :loops (nreverse loops)
9187 :filter (car filter)
9188 :lp (js2-relpos (second filter) pos)
9189 :rp (js2-relpos (third filter) pos)
9190 :if-pos if-pos))
9191 (apply #'js2-node-add-children result expr (car filter)
9192 (js2-array-comp-node-loops result))
9193 (setq js2-current-scope first) ; pop to the first loop
9194 result))
9195
9196 (defun js2-parse-array-comp-loop ()
9197 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9198 Last token peeked should be the initial FOR."
9199 (let ((pos js2-token-beg)
9200 (pn (make-js2-array-comp-loop-node))
9201 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9202 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9203 (js2-push-scope pn)
9204 (unwind-protect
9205 (progn
9206 (when (js2-match-token js2-NAME)
9207 (if (string= js2-ts-string "each")
9208 (progn
9209 (setq foreach-p t
9210 each-pos (- js2-token-beg pos)) ; relative
9211 (js2-record-face 'font-lock-keyword-face))
9212 (js2-report-error "msg.no.paren.for")))
9213 (if (js2-must-match js2-LP "msg.no.paren.for")
9214 (setq lp (- js2-token-beg pos)))
9215 (setq tt (js2-peek-token))
9216 (cond
9217 ((or (= tt js2-LB)
9218 (= tt js2-LC))
9219 (setq iter (js2-parse-destruct-primary-expr))
9220 (js2-define-destruct-symbols iter js2-LET
9221 'font-lock-variable-name-face t))
9222 ((js2-match-token js2-NAME)
9223 (setq iter (js2-create-name-node)))
9224 (t
9225 (js2-report-error "msg.bad.var")))
9226 ;; Define as a let since we want the scope of the variable to
9227 ;; be restricted to the array comprehension
9228 (if (js2-name-node-p iter)
9229 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9230 (if (or (js2-match-token js2-IN)
9231 (and (>= js2-language-version 200)
9232 (js2-match-contextual-kwd "of")
9233 (setq forof-p t)))
9234 (setq in-pos (- js2-token-beg pos))
9235 (js2-report-error "msg.in.after.for.name"))
9236 (setq obj (js2-parse-expr))
9237 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9238 (setq rp (- js2-token-beg pos)))
9239 (setf (js2-node-pos pn) pos
9240 (js2-node-len pn) (- js2-ts-cursor pos)
9241 (js2-array-comp-loop-node-iterator pn) iter
9242 (js2-array-comp-loop-node-object pn) obj
9243 (js2-array-comp-loop-node-in-pos pn) in-pos
9244 (js2-array-comp-loop-node-each-pos pn) each-pos
9245 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9246 (js2-array-comp-loop-node-forof-p pn) forof-p
9247 (js2-array-comp-loop-node-lp pn) lp
9248 (js2-array-comp-loop-node-rp pn) rp)
9249 (js2-node-add-children pn iter obj))
9250 (js2-pop-scope))
9251 pn))
9252
9253 (defun js2-parse-object-literal ()
9254 (let ((pos js2-token-beg)
9255 tt elems result after-comma
9256 (continue t))
9257 (while continue
9258 (setq tt (js2-peek-token))
9259 (cond
9260 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9261 ;; {get foo() {...}}, or {set foo(x) {...}}
9262 ((or (js2-valid-prop-name-token tt)
9263 (= tt js2-STRING))
9264 (setq after-comma nil
9265 result (js2-parse-named-prop tt))
9266 (if (and (null result)
9267 (not js2-recover-from-parse-errors))
9268 (setq continue nil)
9269 (push result elems)))
9270 ;; {12: x} or {10.7: x}
9271 ((= tt js2-NUMBER)
9272 (js2-consume-token)
9273 (setq after-comma nil)
9274 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9275 ;; trailing comma
9276 ((= tt js2-RC)
9277 (setq continue nil)
9278 (if after-comma
9279 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9280 pos elems after-comma)))
9281 (t
9282 (js2-report-error "msg.bad.prop")
9283 (unless js2-recover-from-parse-errors
9284 (setq continue nil)))) ; end switch
9285 (if (js2-match-token js2-COMMA)
9286 (setq after-comma js2-token-end)
9287 (setq continue nil))) ; end loop
9288 (js2-must-match js2-RC "msg.no.brace.prop")
9289 (setq result (make-js2-object-node :pos pos
9290 :len (- js2-ts-cursor pos)
9291 :elems (nreverse elems)))
9292 (apply #'js2-node-add-children result (js2-object-node-elems result))
9293 result))
9294
9295 (defun js2-parse-named-prop (tt)
9296 "Parse a name, string, or getter/setter object property.
9297 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9298 (js2-consume-token)
9299 (let ((string-prop (and (= tt js2-STRING)
9300 (make-js2-string-node)))
9301 expr
9302 (ppos js2-token-beg)
9303 (pend js2-token-end)
9304 (name (js2-create-name-node))
9305 (prop js2-ts-string))
9306 (cond
9307 ;; getter/setter prop
9308 ((and (= tt js2-NAME)
9309 (= (js2-peek-token) js2-NAME)
9310 (or (string= prop "get")
9311 (string= prop "set")))
9312 (js2-consume-token)
9313 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9314 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9315 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9316 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9317 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9318 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9319 ;; when patterns are used in variable declarations, function parameters,
9320 ;; catch-clause, and iterators.
9321 ;; We have to set `js2-is-in-destructuring' to t when the current
9322 ;; expressions are on the left side of any assignment, but it's difficult
9323 ;; because it requires looking ahead of expression.
9324 ((and js2-is-in-destructuring
9325 (= tt js2-NAME)
9326 (let ((ctk (js2-peek-token)))
9327 (or (= ctk js2-COMMA)
9328 (= ctk js2-RC)
9329 (js2-valid-prop-name-token ctk))))
9330 name)
9331 ;; regular prop
9332 (t
9333 (prog1
9334 (setq expr (js2-parse-plain-property (or string-prop name)))
9335 (js2-set-face ppos pend
9336 (if (js2-function-node-p
9337 (js2-object-prop-node-right expr))
9338 'font-lock-function-name-face
9339 'font-lock-variable-name-face)
9340 'record))))))
9341
9342 (defun js2-parse-plain-property (prop)
9343 "Parse a non-getter/setter property in an object literal.
9344 PROP is the node representing the property: a number, name or string."
9345 (js2-must-match js2-COLON "msg.no.colon.prop")
9346 (let* ((pos (js2-node-pos prop))
9347 (colon (- js2-token-beg pos))
9348 (expr (js2-parse-assign-expr))
9349 (result (make-js2-object-prop-node
9350 :pos pos
9351 ;; don't include last consumed token in length
9352 :len (- (+ (js2-node-pos expr)
9353 (js2-node-len expr))
9354 pos)
9355 :left prop
9356 :right expr
9357 :op-pos colon)))
9358 (js2-node-add-children result prop expr)
9359 result))
9360
9361 (defun js2-parse-getter-setter-prop (pos prop get-p)
9362 "Parse getter or setter property in an object literal.
9363 JavaScript syntax is:
9364
9365 { get foo() {...}, set foo(x) {...} }
9366
9367 and expression closure style is also supported
9368
9369 { get foo() x, set foo(x) _x = x }
9370
9371 POS is the start position of the `get' or `set' keyword.
9372 PROP is the `js2-name-node' representing the property name.
9373 GET-P is non-nil if the keyword was `get'."
9374 (let ((type (if get-p js2-GET js2-SET))
9375 result end
9376 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9377 ;; it has to be an anonymous function, as we already parsed the name
9378 (if (/= (js2-node-type fn) js2-FUNCTION)
9379 (js2-report-error "msg.bad.prop")
9380 (if (plusp (length (js2-function-name fn)))
9381 (js2-report-error "msg.bad.prop")))
9382 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9383 (setq end (js2-node-end fn)
9384 result (make-js2-getter-setter-node :type type
9385 :pos pos
9386 :len (- end pos)
9387 :left prop
9388 :right fn))
9389 (js2-node-add-children result prop fn)
9390 result))
9391
9392 (defun js2-create-name-node (&optional check-activation-p token)
9393 "Create a name node using the token info from last scanned name.
9394 In some cases we need to either synthesize a name node, or we lost
9395 the name token information by peeking. If the TOKEN parameter is
9396 not `js2-NAME', then we use the token info saved in instance vars."
9397 (let ((beg js2-token-beg)
9398 (s js2-ts-string)
9399 name)
9400 (when (/= js2-current-token js2-NAME)
9401 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9402 s js2-prev-name-token-string
9403 js2-prev-name-token-start nil
9404 js2-prev-name-token-string nil))
9405 (setq name (make-js2-name-node :pos beg
9406 :name s
9407 :len (length s)))
9408 (if check-activation-p
9409 (js2-check-activation-name s (or token js2-NAME)))
9410 name))
9411
9412 ;;; Indentation support
9413
9414 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9415 ;; Karl cleverly deduces that the desired indentation level is often a
9416 ;; function of paren/bracket/brace nesting depth, which can be determined
9417 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9418 ;; then does some equally clever checks to see if we're in the context of a
9419 ;; substatement of a possibly braceless statement keyword such as if, while,
9420 ;; or finally. This approach yields pretty good results.
9421
9422 ;; The indenter is often "wrong", however, and needs to be overridden.
9423 ;; The right long-term solution is probably to emulate (or integrate
9424 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9425 ;; parse tree from `js2-parse' is present, which is not true at the
9426 ;; moment the user is typing, computing indentation is still thousands
9427 ;; of lines of code to handle every possible syntactic edge case.
9428
9429 ;; In the meantime, the compromise solution is that we offer a "bounce
9430 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9431 ;; current line indent among various likely guess points. This approach
9432 ;; is far from perfect, but should at least make it slightly easier to
9433 ;; move the line towards its desired indentation when manually
9434 ;; overriding Karl's heuristic nesting guesser.
9435
9436 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9437 ;; extensions such as `let' and Array comprehensions. Major kudos to
9438 ;; Karl for coming up with the initial approach, which packs a lot of
9439 ;; punch for so little code.
9440
9441 (defconst js2-possibly-braceless-keywords-re
9442 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9443 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9444 "try" "while" "with" "let")))
9445 "Regular expression matching keywords that are optionally
9446 followed by an opening brace.")
9447
9448 (defconst js2-indent-operator-re
9449 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9450 (regexp-opt '("in" "instanceof") 'words))
9451 "Regular expression matching operators that affect indentation
9452 of continued expressions.")
9453
9454 (defconst js2-declaration-keyword-re
9455 (regexp-opt '("var" "let" "const") 'words)
9456 "Regular expression matching variable declaration keywords.")
9457
9458 (defun js2-re-search-forward-inner (regexp &optional bound count)
9459 "Auxiliary function for `js2-re-search-forward'."
9460 (let (parse saved-point)
9461 (while (> count 0)
9462 (re-search-forward regexp bound)
9463 (setq parse (if saved-point
9464 (parse-partial-sexp saved-point (point))
9465 (syntax-ppss (point))))
9466 (cond ((nth 3 parse)
9467 (re-search-forward
9468 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9469 (save-excursion (end-of-line) (point)) t))
9470 ((nth 7 parse)
9471 (forward-line))
9472 ((or (nth 4 parse)
9473 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9474 (re-search-forward "\\*/"))
9475 (t
9476 (setq count (1- count))))
9477 (setq saved-point (point))))
9478 (point))
9479
9480 (defun js2-re-search-forward (regexp &optional bound noerror count)
9481 "Search forward but ignore strings and comments.
9482 Invokes `re-search-forward' but treats the buffer as if strings
9483 and comments have been removed."
9484 (let ((saved-point (point))
9485 (search-expr
9486 (cond ((null count)
9487 '(js2-re-search-forward-inner regexp bound 1))
9488 ((< count 0)
9489 '(js2-re-search-backward-inner regexp bound (- count)))
9490 ((> count 0)
9491 '(js2-re-search-forward-inner regexp bound count)))))
9492 (condition-case err
9493 (eval search-expr)
9494 (search-failed
9495 (goto-char saved-point)
9496 (unless noerror
9497 (error (error-message-string err)))))))
9498
9499 (defun js2-re-search-backward-inner (regexp &optional bound count)
9500 "Auxiliary function for `js2-re-search-backward'."
9501 (let (parse)
9502 (while (> count 0)
9503 (re-search-backward regexp bound)
9504 (setq parse (syntax-ppss (point)))
9505 (cond ((nth 3 parse)
9506 (re-search-backward
9507 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9508 (line-beginning-position) t))
9509 ((nth 7 parse)
9510 (goto-char (nth 8 parse)))
9511 ((or (nth 4 parse)
9512 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9513 (re-search-backward "/\\*"))
9514 (t
9515 (setq count (1- count))))))
9516 (point))
9517
9518 (defun js2-re-search-backward (regexp &optional bound noerror count)
9519 "Search backward but ignore strings and comments.
9520 Invokes `re-search-backward' but treats the buffer as if strings
9521 and comments have been removed."
9522 (let ((saved-point (point))
9523 (search-expr
9524 (cond ((null count)
9525 '(js2-re-search-backward-inner regexp bound 1))
9526 ((< count 0)
9527 '(js2-re-search-forward-inner regexp bound (- count)))
9528 ((> count 0)
9529 '(js2-re-search-backward-inner regexp bound count)))))
9530 (condition-case err
9531 (eval search-expr)
9532 (search-failed
9533 (goto-char saved-point)
9534 (unless noerror
9535 (error (error-message-string err)))))))
9536
9537 (defun js2-looking-at-operator-p ()
9538 "Return non-nil if text after point is a non-comma operator."
9539 (and (looking-at js2-indent-operator-re)
9540 (or (not (looking-at ":"))
9541 (save-excursion
9542 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9543 (looking-at "?"))))))
9544
9545 (defun js2-continued-expression-p ()
9546 "Return non-nil if the current line continues an expression."
9547 (save-excursion
9548 (back-to-indentation)
9549 (or (js2-looking-at-operator-p)
9550 (when (catch 'found
9551 (while (and (re-search-backward "\n" nil t)
9552 (let ((state (syntax-ppss)))
9553 (when (nth 4 state)
9554 (goto-char (nth 8 state))) ;; skip comments
9555 (skip-chars-backward " \t")
9556 (if (bolp)
9557 t
9558 (throw 'found t))))))
9559 (backward-char)
9560 (when (js2-looking-at-operator-p)
9561 (backward-char)
9562 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))
9563
9564 (defun js2-end-of-do-while-loop-p ()
9565 "Return non-nil if word after point is `while' of a do-while
9566 statement, else returns nil. A braceless do-while statement
9567 spanning several lines requires that the start of the loop is
9568 indented to the same column as the current line."
9569 (interactive)
9570 (save-excursion
9571 (when (looking-at "\\s-*\\<while\\>")
9572 (if (save-excursion
9573 (skip-chars-backward "[ \t\n]*}")
9574 (looking-at "[ \t\n]*}"))
9575 (save-excursion
9576 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9577 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9578 (or (looking-at "\\<do\\>")
9579 (let ((saved-indent (current-indentation)))
9580 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9581 (/= (current-indentation) saved-indent)))
9582 (and (looking-at "[ \t]*\\<do\\>")
9583 (not (js2-re-search-forward
9584 "\\<while\\>" (point-at-eol) t))
9585 (= (current-indentation) saved-indent))))))))
9586
9587 (defun js2-multiline-decl-indentation ()
9588 "Return the declaration indentation column if the current line belongs
9589 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9590 (let (forward-sexp-function ; use Lisp version
9591 at-opening-bracket)
9592 (save-excursion
9593 (back-to-indentation)
9594 (when (not (looking-at js2-declaration-keyword-re))
9595 (when (looking-at js2-indent-operator-re)
9596 (goto-char (match-end 0))) ; continued expressions are ok
9597 (while (and (not at-opening-bracket)
9598 (not (bobp))
9599 (let ((pos (point)))
9600 (save-excursion
9601 (js2-backward-sws)
9602 (or (eq (char-before) ?,)
9603 (and (not (eq (char-before) ?\;))
9604 (prog2 (skip-syntax-backward ".")
9605 (looking-at js2-indent-operator-re)
9606 (js2-backward-sws))
9607 (not (eq (char-before) ?\;)))
9608 (js2-same-line pos)))))
9609 (condition-case err
9610 (backward-sexp)
9611 (scan-error (setq at-opening-bracket t))))
9612 (when (looking-at js2-declaration-keyword-re)
9613 (goto-char (match-end 0))
9614 (1+ (current-column)))))))
9615
9616 (defun js2-ctrl-statement-indentation ()
9617 "Return the proper indentation of current line if it is a control statement.
9618 Returns an indentation if this line starts the body of a control
9619 statement without braces, else returns nil."
9620 (let (forward-sexp-function)
9621 (save-excursion
9622 (back-to-indentation)
9623 (when (and (not (js2-same-line (point-min)))
9624 (not (looking-at "{"))
9625 (js2-re-search-backward "[[:graph:]]" nil t)
9626 (not (looking-at "[{([]"))
9627 (progn
9628 (forward-char)
9629 (when (= (char-before) ?\))
9630 ;; scan-sexps sometimes throws an error
9631 (ignore-errors (backward-sexp))
9632 (skip-chars-backward " \t" (point-at-bol)))
9633 (let ((pt (point)))
9634 (back-to-indentation)
9635 (when (looking-at "}[ \t]*")
9636 (goto-char (match-end 0)))
9637 (and (looking-at js2-possibly-braceless-keywords-re)
9638 (= (match-end 0) pt)
9639 (not (js2-end-of-do-while-loop-p))))))
9640 (+ (current-indentation) js2-basic-offset)))))
9641
9642 (defun js2-indent-in-array-comp (parse-status)
9643 "Return non-nil if we think we're in an array comprehension.
9644 In particular, return the buffer position of the first `for' kwd."
9645 (let ((bracket (nth 1 parse-status))
9646 (end (point)))
9647 (when bracket
9648 (save-excursion
9649 (goto-char bracket)
9650 (when (looking-at "\\[")
9651 (forward-char 1)
9652 (js2-forward-sws)
9653 (if (looking-at "[[{]")
9654 (let (forward-sexp-function) ; use Lisp version
9655 (forward-sexp) ; skip destructuring form
9656 (js2-forward-sws)
9657 (if (and (/= (char-after) ?,) ; regular array
9658 (looking-at "for"))
9659 (match-beginning 0)))
9660 ;; to skip arbitrary expressions we need the parser,
9661 ;; so we'll just guess at it.
9662 (if (and (> end (point)) ; not empty literal
9663 (re-search-forward "[^,]]* \\(for\\) " end t)
9664 ;; not inside comment or string literal
9665 (let ((state (parse-partial-sexp bracket (point))))
9666 (not (or (nth 3 state) (nth 4 state)))))
9667 (match-beginning 1))))))))
9668
9669 (defun js2-array-comp-indentation (parse-status for-kwd)
9670 (if (js2-same-line for-kwd)
9671 ;; first continuation line
9672 (save-excursion
9673 (goto-char (nth 1 parse-status))
9674 (forward-char 1)
9675 (skip-chars-forward " \t")
9676 (current-column))
9677 (save-excursion
9678 (goto-char for-kwd)
9679 (current-column))))
9680
9681 (defun js2-proper-indentation (parse-status)
9682 "Return the proper indentation for the current line."
9683 (save-excursion
9684 (back-to-indentation)
9685 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9686 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9687 (continued-expr-p (js2-continued-expression-p))
9688 (declaration-indent (and js2-pretty-multiline-declarations
9689 (js2-multiline-decl-indentation)))
9690 (bracket (nth 1 parse-status))
9691 beg)
9692 (cond
9693 ;; indent array comprehension continuation lines specially
9694 ((and bracket
9695 (>= js2-language-version 170)
9696 (not (js2-same-line bracket))
9697 (setq beg (js2-indent-in-array-comp parse-status))
9698 (>= (point) (save-excursion
9699 (goto-char beg)
9700 (point-at-bol)))) ; at or after first loop?
9701 (js2-array-comp-indentation parse-status beg))
9702
9703 (ctrl-stmt-indent)
9704
9705 ((and declaration-indent continued-expr-p)
9706 (+ declaration-indent js2-basic-offset))
9707
9708 (declaration-indent)
9709
9710 (bracket
9711 (goto-char bracket)
9712 (cond
9713 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9714 (when (save-excursion (skip-chars-backward " \t)")
9715 (looking-at ")"))
9716 (backward-list))
9717 (back-to-indentation)
9718 (and (eq js2-pretty-multiline-declarations 'all)
9719 (looking-at js2-declaration-keyword-re)
9720 (goto-char (1+ (match-end 0))))
9721 (cond (same-indent-p
9722 (current-column))
9723 (continued-expr-p
9724 (+ (current-column) (* 2 js2-basic-offset)))
9725 (t
9726 (+ (current-column) js2-basic-offset))))
9727 (t
9728 (unless same-indent-p
9729 (forward-char)
9730 (skip-chars-forward " \t"))
9731 (current-column))))
9732
9733 (continued-expr-p js2-basic-offset)
9734
9735 (t 0)))))
9736
9737 (defun js2-lineup-comment (parse-status)
9738 "Indent a multi-line block comment continuation line."
9739 (let* ((beg (nth 8 parse-status))
9740 (first-line (js2-same-line beg))
9741 (offset (save-excursion
9742 (goto-char beg)
9743 (if (looking-at "/\\*")
9744 (+ 1 (current-column))
9745 0))))
9746 (unless first-line
9747 (indent-line-to offset))))
9748
9749 (defun js2-backward-sws ()
9750 "Move backward through whitespace and comments."
9751 (interactive)
9752 (while (forward-comment -1)))
9753
9754 (defun js2-forward-sws ()
9755 "Move forward through whitespace and comments."
9756 (interactive)
9757 (while (forward-comment 1)))
9758
9759 (defun js2-current-indent (&optional pos)
9760 "Return column of indentation on current line.
9761 If POS is non-nil, go to that point and return indentation for that line."
9762 (save-excursion
9763 (if pos
9764 (goto-char pos))
9765 (back-to-indentation)
9766 (current-column)))
9767
9768 (defun js2-arglist-close ()
9769 "Return non-nil if we're on a line beginning with a close-paren/brace."
9770 (save-excursion
9771 (goto-char (point-at-bol))
9772 (js2-forward-sws)
9773 (looking-at "[])}]")))
9774
9775 (defun js2-indent-looks-like-label-p ()
9776 (goto-char (point-at-bol))
9777 (js2-forward-sws)
9778 (looking-at (concat js2-mode-identifier-re ":")))
9779
9780 (defun js2-indent-in-objlit-p (parse-status)
9781 "Return non-nil if this looks like an object-literal entry."
9782 (let ((start (nth 1 parse-status)))
9783 (and
9784 start
9785 (save-excursion
9786 (and (zerop (forward-line -1))
9787 (not (< (point) start)) ; crossed a {} boundary
9788 (js2-indent-looks-like-label-p)))
9789 (save-excursion
9790 (js2-indent-looks-like-label-p)))))
9791
9792 ;; If prev line looks like foobar({ then we're passing an object
9793 ;; literal to a function call, and people pretty much always want to
9794 ;; de-dent back to the previous line, so move the 'basic-offset'
9795 ;; position to the front.
9796 (defun js2-indent-objlit-arg-p (parse-status)
9797 (save-excursion
9798 (back-to-indentation)
9799 (js2-backward-sws)
9800 (and (eq (1- (point)) (nth 1 parse-status))
9801 (eq (char-before) ?{)
9802 (progn
9803 (forward-char -1)
9804 (skip-chars-backward " \t")
9805 (eq (char-before) ?\()))))
9806
9807 (defun js2-indent-case-block-p ()
9808 (save-excursion
9809 (back-to-indentation)
9810 (js2-backward-sws)
9811 (goto-char (point-at-bol))
9812 (skip-chars-forward " \t")
9813 (looking-at "case\\s-.+:")))
9814
9815 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
9816 "Cycle among alternate computed indentation positions.
9817 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9818 of the buffer to the current point. NORMAL-COL is the indentation
9819 column computed by the heuristic guesser based on current paren,
9820 bracket, brace and statement nesting. If BACKWARDS, cycle positions
9821 in reverse."
9822 (let ((cur-indent (js2-current-indent))
9823 (old-buffer-undo-list buffer-undo-list)
9824 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9825 (current-line (save-excursion
9826 (forward-line 0) ; move to bol
9827 (1+ (count-lines (point-min) (point)))))
9828 positions pos main-pos anchor arglist-cont same-indent
9829 prev-line-col basic-offset computed-pos)
9830 ;; temporarily don't record undo info, if user requested this
9831 (when js2-mode-indent-inhibit-undo
9832 (setq buffer-undo-list t))
9833 (unwind-protect
9834 (progn
9835 ;; First likely point: indent from beginning of previous code line
9836 (push (setq basic-offset
9837 (+ (save-excursion
9838 (back-to-indentation)
9839 (js2-backward-sws)
9840 (back-to-indentation)
9841 (setq prev-line-col (current-column)))
9842 js2-basic-offset))
9843 positions)
9844
9845 ;; (First + epsilon) likely point: indent 2x from beginning of
9846 ;; previous code line. Google does it this way.
9847 (push (setq basic-offset
9848 (+ (save-excursion
9849 (back-to-indentation)
9850 (js2-backward-sws)
9851 (back-to-indentation)
9852 (setq prev-line-col (current-column)))
9853 (* 2 js2-basic-offset)))
9854 positions)
9855
9856 ;; Second likely point: indent from assign-expr RHS. This
9857 ;; is just a crude guess based on finding " = " on the previous
9858 ;; line containing actual code.
9859 (setq pos (save-excursion
9860 (forward-line -1)
9861 (goto-char (point-at-bol))
9862 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
9863 (point-at-eol) t)
9864 (goto-char (match-end 1))
9865 (skip-chars-forward " \t\r\n")
9866 (current-column))))
9867 (when pos
9868 (incf pos js2-basic-offset)
9869 (push pos positions))
9870
9871 ;; Third likely point: same indent as previous line of code.
9872 ;; Make it the first likely point if we're not on an
9873 ;; arglist-close line and previous line ends in a comma, or
9874 ;; both this line and prev line look like object-literal
9875 ;; elements.
9876 (setq pos (save-excursion
9877 (goto-char (point-at-bol))
9878 (js2-backward-sws)
9879 (back-to-indentation)
9880 (prog1
9881 (current-column)
9882 ;; while we're here, look for trailing comma
9883 (if (save-excursion
9884 (goto-char (point-at-eol))
9885 (js2-backward-sws)
9886 (eq (char-before) ?,))
9887 (setq arglist-cont (1- (point)))))))
9888 (when pos
9889 (if (and (or arglist-cont
9890 (js2-indent-in-objlit-p parse-status))
9891 (not (js2-arglist-close)))
9892 (setq same-indent pos))
9893 (push pos positions))
9894
9895 ;; Fourth likely point: first preceding code with less indentation.
9896 ;; than the immediately preceding code line.
9897 (setq pos (save-excursion
9898 (back-to-indentation)
9899 (js2-backward-sws)
9900 (back-to-indentation)
9901 (setq anchor (current-column))
9902 (while (and (zerop (forward-line -1))
9903 (>= (progn
9904 (back-to-indentation)
9905 (current-column))
9906 anchor)))
9907 (setq pos (current-column))))
9908 (push pos positions)
9909
9910 ;; nesting-heuristic position, main by default
9911 (push (setq main-pos normal-col) positions)
9912
9913 ;; delete duplicates and sort positions list
9914 (setq positions (sort (delete-dups positions) '<))
9915
9916 ;; comma-list continuation lines: prev line indent takes precedence
9917 (if same-indent
9918 (setq main-pos same-indent))
9919
9920 ;; common special cases where we want to indent in from previous line
9921 (if (or (js2-indent-case-block-p)
9922 (js2-indent-objlit-arg-p parse-status))
9923 (setq main-pos basic-offset))
9924
9925 ;; if bouncing backwards, reverse positions list
9926 (if backwards
9927 (setq positions (reverse positions)))
9928
9929 ;; record whether we're already sitting on one of the alternatives
9930 (setq pos (member cur-indent positions))
9931
9932 (cond
9933 ;; case 0: we're one one of the alternatives and this is the
9934 ;; first time they've pressed TAB on this line (best-guess).
9935 ((and js2-mode-indent-ignore-first-tab
9936 pos
9937 ;; first time pressing TAB on this line?
9938 (not (eq js2-mode-last-indented-line current-line)))
9939 ;; do nothing
9940 (setq computed-pos nil))
9941 ;; case 1: only one computed position => use it
9942 ((null (cdr positions))
9943 (setq computed-pos 0))
9944 ;; case 2: not on any of the computed spots => use main spot
9945 ((not pos)
9946 (setq computed-pos (js2-position main-pos positions)))
9947 ;; case 3: on last position: cycle to first position
9948 ((null (cdr pos))
9949 (setq computed-pos 0))
9950 ;; case 4: on intermediate position: cycle to next position
9951 (t
9952 (setq computed-pos (js2-position (second pos) positions))))
9953
9954 ;; see if any hooks want to indent; otherwise we do it
9955 (loop with result = nil
9956 for hook in js2-indent-hook
9957 while (null result)
9958 do
9959 (setq result (funcall hook positions computed-pos))
9960 finally do
9961 (unless (or result (null computed-pos))
9962 (indent-line-to (nth computed-pos positions)))))
9963
9964 ;; finally
9965 (if js2-mode-indent-inhibit-undo
9966 (setq buffer-undo-list old-buffer-undo-list))
9967 ;; see commentary for `js2-mode-last-indented-line'
9968 (setq js2-mode-last-indented-line current-line))))
9969
9970 (defun js2-indent-bounce-backwards ()
9971 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
9972 cycles between the computed indentation positions in reverse order."
9973 (interactive)
9974 (js2-indent-line t))
9975
9976 (defun js2-1-line-comment-continuation-p ()
9977 "Return t if we're in a 1-line comment continuation.
9978 If so, we don't ever want to use bounce-indent."
9979 (save-excursion
9980 (and (progn
9981 (forward-line 0)
9982 (looking-at "\\s-*//"))
9983 (progn
9984 (forward-line -1)
9985 (forward-line 0)
9986 (when (looking-at "\\s-*$")
9987 (js2-backward-sws)
9988 (forward-line 0))
9989 (looking-at "\\s-*//")))))
9990
9991 (defun js2-indent-line (&optional bounce-backwards)
9992 "Indent the current line as JavaScript source text."
9993 (interactive)
9994 (let (parse-status current-indent offset indent-col moved
9995 ;; Don't whine about errors/warnings when we're indenting.
9996 ;; This has to be set before calling parse-partial-sexp below.
9997 (inhibit-point-motion-hooks t))
9998 (setq parse-status (save-excursion
9999 (syntax-ppss (point-at-bol)))
10000 offset (- (point) (save-excursion
10001 (back-to-indentation)
10002 (point))))
10003 (js2-with-underscore-as-word-syntax
10004 (if (nth 4 parse-status)
10005 (js2-lineup-comment parse-status)
10006 (setq indent-col (js2-proper-indentation parse-status))
10007 ;; See comments below about `js2-mode-last-indented-line'.
10008 (cond
10009 ;; bounce-indenting is disabled during electric-key indent.
10010 ;; It doesn't work well on first line of buffer.
10011 ((and js2-bounce-indent-p
10012 (not (js2-same-line (point-min)))
10013 (not (js2-1-line-comment-continuation-p)))
10014 (js2-bounce-indent indent-col parse-status bounce-backwards))
10015 ;; just indent to the guesser's likely spot
10016 (t (indent-line-to indent-col))))
10017 (when (plusp offset)
10018 (forward-char offset)))))
10019
10020 (defun js2-indent-region (start end)
10021 "Indent the region, but don't use bounce indenting."
10022 (let ((js2-bounce-indent-p nil)
10023 (indent-region-function nil)
10024 (after-change-functions (remq 'js2-mode-edit
10025 after-change-functions)))
10026 (indent-region start end nil) ; nil for byte-compiler
10027 (js2-mode-edit start end (- end start))))
10028
10029 (defvar js2-minor-mode-map
10030 (let ((map (make-sparse-keymap)))
10031 (define-key map (kbd "C-c C-`") #'js2-next-error)
10032 (define-key map [mouse-1] #'js2-mode-show-node)
10033 map)
10034 "Keymap used when `js2-minor-mode' is active.")
10035
10036 ;;;###autoload
10037 (define-minor-mode js2-minor-mode
10038 "Minor mode for running js2 as a background linter.
10039 This allows you to use a different major mode for JavaScript editing,
10040 such as `espresso-mode', while retaining the asynchronous error/warning
10041 highlighting features of `js2-mode'."
10042 :group 'js2-mode
10043 :lighter " js-lint"
10044 (if js2-minor-mode
10045 (js2-minor-mode-enter)
10046 (js2-minor-mode-exit)))
10047
10048 (defun js2-minor-mode-enter ()
10049 "Initialization for `js2-minor-mode'."
10050 (set (make-local-variable 'max-lisp-eval-depth)
10051 (max max-lisp-eval-depth 3000))
10052 (setq next-error-function #'js2-next-error)
10053 (setq js2-default-externs
10054 (append js2-ecma-262-externs
10055 (if js2-include-browser-externs js2-browser-externs)
10056 (if js2-include-rhino-externs js2-rhino-externs)
10057 (if js2-include-node-externs js2-node-externs)))
10058 ;; Experiment: make reparse-delay longer for longer files.
10059 (if (plusp js2-dynamic-idle-timer-adjust)
10060 (setq js2-idle-timer-delay
10061 (* js2-idle-timer-delay
10062 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10063 (setq js2-mode-buffer-dirty-p t
10064 js2-mode-parsing nil)
10065 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10066 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10067 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10068 (js2-reparse))
10069
10070 (defun js2-minor-mode-exit ()
10071 "Turn off `js2-minor-mode'."
10072 (setq next-error-function nil)
10073 (remove-hook 'after-change-functions #'js2-mode-edit t)
10074 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10075 (when js2-mode-node-overlay
10076 (delete-overlay js2-mode-node-overlay)
10077 (setq js2-mode-node-overlay nil))
10078 (js2-remove-overlays)
10079 (setq js2-mode-ast nil))
10080
10081 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10082 (make-variable-buffer-local 'js2-source-buffer)
10083
10084 (defun* js2-display-error-list ()
10085 "Display a navigable buffer listing parse errors/warnings."
10086 (interactive)
10087 (unless (js2-have-errors-p)
10088 (message "No errors")
10089 (return-from js2-display-error-list))
10090 (labels ((annotate-list
10091 (lst type)
10092 "Add diagnostic TYPE and line number to errs list"
10093 (mapcar (lambda (err)
10094 (list err type (line-number-at-pos (nth 1 err))))
10095 lst)))
10096 (let* ((srcbuf (current-buffer))
10097 (errbuf (get-buffer-create "*js-lint*"))
10098 (errors (annotate-list
10099 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10100 'js2-error)) ; must be a valid face name
10101 (warnings (annotate-list
10102 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10103 'js2-warning)) ; must be a valid face name
10104 (all-errs (sort (append errors warnings)
10105 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10106 (with-current-buffer errbuf
10107 (let ((inhibit-read-only t))
10108 (erase-buffer)
10109 (dolist (err all-errs)
10110 (destructuring-bind ((msg-key beg end &rest) type line) err
10111 (insert-text-button
10112 (format "line %d: %s" line (js2-get-msg msg-key))
10113 'face type
10114 'follow-link "\C-m"
10115 'action 'js2-error-buffer-jump
10116 'js2-msg (js2-get-msg msg-key)
10117 'js2-pos beg)
10118 (insert "\n"))))
10119 (js2-error-buffer-mode)
10120 (setq js2-source-buffer srcbuf)
10121 (pop-to-buffer errbuf)
10122 (goto-char (point-min))
10123 (unless (eobp)
10124 (js2-error-buffer-view))))))
10125
10126 (defvar js2-error-buffer-mode-map
10127 (let ((map (make-sparse-keymap)))
10128 (define-key map "n" #'js2-error-buffer-next)
10129 (define-key map "p" #'js2-error-buffer-prev)
10130 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10131 (define-key map "o" #'js2-error-buffer-view)
10132 (define-key map "q" #'js2-error-buffer-quit)
10133 map)
10134 "Keymap used for js2 diagnostics buffers.")
10135
10136 (defun js2-error-buffer-mode ()
10137 "Major mode for js2 diagnostics buffers.
10138 Selecting an error will jump it to the corresponding source-buffer error.
10139 \\{js2-error-buffer-mode-map}"
10140 (interactive)
10141 (setq major-mode 'js2-error-buffer-mode
10142 mode-name "JS Lint Diagnostics")
10143 (use-local-map js2-error-buffer-mode-map)
10144 (setq truncate-lines t)
10145 (set-buffer-modified-p nil)
10146 (setq buffer-read-only t)
10147 (run-hooks 'js2-error-buffer-mode-hook))
10148
10149 (defun js2-error-buffer-next ()
10150 "Move to next error and view it."
10151 (interactive)
10152 (when (zerop (forward-line 1))
10153 (js2-error-buffer-view)))
10154
10155 (defun js2-error-buffer-prev ()
10156 "Move to previous error and view it."
10157 (interactive)
10158 (when (zerop (forward-line -1))
10159 (js2-error-buffer-view)))
10160
10161 (defun js2-error-buffer-quit ()
10162 "Kill the current buffer."
10163 (interactive)
10164 (kill-buffer))
10165
10166 (defun js2-error-buffer-jump (&rest ignored)
10167 "Jump cursor to current error in source buffer."
10168 (interactive)
10169 (when (js2-error-buffer-view)
10170 (pop-to-buffer js2-source-buffer)))
10171
10172 (defun js2-error-buffer-view ()
10173 "Scroll source buffer to show error at current line."
10174 (interactive)
10175 (cond
10176 ((not (eq major-mode 'js2-error-buffer-mode))
10177 (message "Not in a js2 errors buffer"))
10178 ((not (buffer-live-p js2-source-buffer))
10179 (message "Source buffer has been killed"))
10180 ((not (wholenump (get-text-property (point) 'js2-pos)))
10181 (message "There does not seem to be an error here"))
10182 (t
10183 (let ((pos (get-text-property (point) 'js2-pos))
10184 (msg (get-text-property (point) 'js2-msg)))
10185 (save-selected-window
10186 (pop-to-buffer js2-source-buffer)
10187 (goto-char pos)
10188 (message msg))))))
10189
10190 ;;;###autoload
10191 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10192 ;; FIXME: Should derive from js-mode.
10193 "Major mode for editing JavaScript code."
10194 (setq comment-start "//" ; used by comment-region; don't change it
10195 comment-end "")
10196 (set (make-local-variable 'max-lisp-eval-depth)
10197 (max max-lisp-eval-depth 3000))
10198 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10199 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10200 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10201 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10202 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10203 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10204 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10205 ;; for characters inside regexp literals.
10206 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10207 ;; this is necessary to make `show-paren-function' work properly
10208 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10209 ;; needed for M-x rgrep, among other things
10210 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10211
10212 (set (make-local-variable 'electric-indent-chars)
10213 (append '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
10214 electric-indent-chars))
10215 (set (make-local-variable 'electric-layout-rules)
10216 '((?\; . after) (?\{ . after) (?\} . before)))
10217
10218 ;; some variables needed by cc-engine for paragraph-fill, etc.
10219 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10220 c-comment-start-regexp "/[*/]\\|\\s|"
10221 c-line-comment-starter "//"
10222 c-paragraph-start js2-paragraph-start
10223 c-paragraph-separate "$"
10224 comment-start-skip js2-comment-start-skip
10225 c-syntactic-ws-start js2-syntactic-ws-start
10226 c-syntactic-ws-end js2-syntactic-ws-end
10227 c-syntactic-eol js2-syntactic-eol)
10228
10229 (let ((c-buffer-is-cc-mode t))
10230 ;; Copied from `js-mode'. Also see Bug#6071.
10231 (make-local-variable 'paragraph-start)
10232 (make-local-variable 'paragraph-separate)
10233 (make-local-variable 'paragraph-ignore-fill-prefix)
10234 (make-local-variable 'adaptive-fill-mode)
10235 (make-local-variable 'adaptive-fill-regexp)
10236 (c-setup-paragraph-variables))
10237
10238 (setq js2-default-externs
10239 (append js2-ecma-262-externs
10240 (if js2-include-browser-externs js2-browser-externs)
10241 (if js2-include-rhino-externs js2-rhino-externs)
10242 (if js2-include-node-externs js2-node-externs)))
10243
10244 (setq font-lock-defaults '(nil t))
10245
10246 ;; Experiment: make reparse-delay longer for longer files.
10247 (when (plusp js2-dynamic-idle-timer-adjust)
10248 (setq js2-idle-timer-delay
10249 (* js2-idle-timer-delay
10250 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10251
10252 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10253 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10254 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10255 (setq next-error-function #'js2-next-error)
10256 (imenu-add-to-menubar (concat "IM-" mode-name))
10257 (add-to-invisibility-spec '(js2-outline . t))
10258 (set (make-local-variable 'line-move-ignore-invisible) t)
10259 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10260
10261 (setq js2-mode-functions-hidden nil
10262 js2-mode-comments-hidden nil
10263 js2-mode-buffer-dirty-p t
10264 js2-mode-parsing nil)
10265 (js2-reparse))
10266
10267 (defun js2-mode-exit ()
10268 "Exit `js2-mode' and clean up."
10269 (interactive)
10270 (when js2-mode-node-overlay
10271 (delete-overlay js2-mode-node-overlay)
10272 (setq js2-mode-node-overlay nil))
10273 (js2-remove-overlays)
10274 (setq js2-mode-ast nil)
10275 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10276 (remove-from-invisibility-spec '(js2-outline . t))
10277 (js2-mode-show-all)
10278 (with-silent-modifications
10279 (js2-clear-face (point-min) (point-max))))
10280
10281 (defun js2-mode-reset-timer ()
10282 "Cancel any existing parse timer and schedule a new one."
10283 (if js2-mode-parse-timer
10284 (cancel-timer js2-mode-parse-timer))
10285 (setq js2-mode-parsing nil)
10286 (let ((timer (timer-create)))
10287 (setq js2-mode-parse-timer timer)
10288 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10289 (timer-set-idle-time timer js2-idle-timer-delay)
10290 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10291 (timer-activate-when-idle timer nil)))
10292
10293 (defun js2-mode-idle-reparse (buffer)
10294 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10295 it to be reparsed when the buffer is selected."
10296 (if (eq buffer (current-buffer))
10297 (js2-reparse)
10298 ;; reparse when the buffer is selected again
10299 (with-current-buffer buffer
10300 (add-hook 'window-configuration-change-hook
10301 #'js2-mode-idle-reparse-inner
10302 nil t))))
10303
10304 (defun js2-mode-idle-reparse-inner ()
10305 (remove-hook 'window-configuration-change-hook
10306 #'js2-mode-idle-reparse-inner
10307 t)
10308 (js2-reparse))
10309
10310 (defun js2-mode-edit (beg end len)
10311 "Schedule a new parse after buffer is edited.
10312 Buffer edit spans from BEG to END and is of length LEN."
10313 (setq js2-mode-buffer-dirty-p t)
10314 (js2-mode-hide-overlay)
10315 (js2-mode-reset-timer))
10316
10317 (defun js2-minor-mode-edit (beg end len)
10318 "Callback for buffer edits in `js2-mode'.
10319 Schedules a new parse after buffer is edited.
10320 Buffer edit spans from BEG to END and is of length LEN."
10321 (setq js2-mode-buffer-dirty-p t)
10322 (js2-mode-hide-overlay)
10323 (js2-mode-reset-timer))
10324
10325 (defun js2-reparse (&optional force)
10326 "Re-parse current buffer after user finishes some data entry.
10327 If we get any user input while parsing, including cursor motion,
10328 we discard the parse and reschedule it. If FORCE is nil, then the
10329 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10330 (let (time
10331 interrupted-p
10332 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10333 (unless js2-mode-parsing
10334 (setq js2-mode-parsing t)
10335 (unwind-protect
10336 (when (or js2-mode-buffer-dirty-p force)
10337 (js2-remove-overlays)
10338 (with-silent-modifications
10339 (setq js2-mode-buffer-dirty-p nil
10340 js2-mode-fontifications nil
10341 js2-mode-deferred-properties nil)
10342 (if js2-mode-verbose-parse-p
10343 (message "parsing..."))
10344 (setq time
10345 (js2-time
10346 (setq interrupted-p
10347 (catch 'interrupted
10348 (js2-parse)
10349 ;; if parsing is interrupted, comments and regex
10350 ;; literals stay ignored by `parse-partial-sexp'
10351 (remove-text-properties (point-min) (point-max)
10352 '(syntax-table))
10353 (js2-mode-apply-deferred-properties)
10354 (js2-mode-remove-suppressed-warnings)
10355 (js2-mode-show-warnings)
10356 (js2-mode-show-errors)
10357 (if (>= js2-highlight-level 1)
10358 (js2-highlight-jsdoc js2-mode-ast))
10359 nil))))
10360 (if interrupted-p
10361 (progn
10362 ;; unfinished parse => try again
10363 (setq js2-mode-buffer-dirty-p t)
10364 (js2-mode-reset-timer))
10365 (if js2-mode-verbose-parse-p
10366 (message "Parse time: %s" time)))))
10367 (setq js2-mode-parsing nil)
10368 (unless interrupted-p
10369 (setq js2-mode-parse-timer nil))))))
10370
10371 (defun js2-mode-show-node (event)
10372 "Debugging aid: highlight selected AST node on mouse click."
10373 (interactive "e")
10374 (mouse-set-point event)
10375 (setq deactivate-mark t)
10376 (when js2-mode-show-overlay
10377 (let ((node (js2-node-at-point))
10378 beg end)
10379 (if (null node)
10380 (message "No node found at location %s" (point))
10381 (setq beg (js2-node-abs-pos node)
10382 end (+ beg (js2-node-len node)))
10383 (if js2-mode-node-overlay
10384 (move-overlay js2-mode-node-overlay beg end)
10385 (setq js2-mode-node-overlay (make-overlay beg end))
10386 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10387 (with-silent-modifications
10388 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10389 (message "%s, parent: %s"
10390 (js2-node-short-name node)
10391 (if (js2-node-parent node)
10392 (js2-node-short-name (js2-node-parent node))
10393 "nil"))))))
10394
10395 (defun js2-mode-hide-overlay (&optional p1 p2)
10396 "Remove the debugging overlay when the point moves.
10397 P1 and P2 are the old and new values of point, respectively."
10398 (when js2-mode-node-overlay
10399 (let ((beg (overlay-start js2-mode-node-overlay))
10400 (end (overlay-end js2-mode-node-overlay)))
10401 ;; Sometimes we're called spuriously.
10402 (unless (and p2
10403 (>= p2 beg)
10404 (<= p2 end))
10405 (with-silent-modifications
10406 (remove-text-properties beg end '(point-left nil)))
10407 (delete-overlay js2-mode-node-overlay)
10408 (setq js2-mode-node-overlay nil)))))
10409
10410 (defun js2-mode-reset ()
10411 "Debugging helper: reset everything."
10412 (interactive)
10413 (js2-mode-exit)
10414 (js2-mode))
10415
10416 (defun js2-mode-show-warn-or-err (e face)
10417 "Highlight a warning or error E with FACE.
10418 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10419 The last element is optional. When present, use instead of FACE."
10420 (let* ((key (first e))
10421 (beg (second e))
10422 (end (+ beg (third e)))
10423 ;; Don't inadvertently go out of bounds.
10424 (beg (max (point-min) (min beg (point-max))))
10425 (end (max (point-min) (min end (point-max))))
10426 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10427 (ovl (make-overlay beg end)))
10428 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10429 (overlay-put ovl 'js2-error t)
10430 (put-text-property beg end 'help-echo (js2-get-msg key))
10431 (put-text-property beg end 'point-entered #'js2-echo-error)))
10432
10433 (defun js2-remove-overlays ()
10434 "Remove overlays from buffer that have a `js2-error' property."
10435 (let ((beg (point-min))
10436 (end (point-max)))
10437 (save-excursion
10438 (dolist (o (overlays-in beg end))
10439 (when (overlay-get o 'js2-error)
10440 (delete-overlay o))))))
10441
10442 (defun js2-error-at-point (&optional pos)
10443 "Return non-nil if there's an error overlay at POS.
10444 Defaults to point."
10445 (loop with pos = (or pos (point))
10446 for o in (overlays-at pos)
10447 thereis (overlay-get o 'js2-error)))
10448
10449 (defun js2-mode-apply-deferred-properties ()
10450 "Apply fontifications and other text properties recorded during parsing."
10451 (when (plusp js2-highlight-level)
10452 ;; We defer clearing faces as long as possible to eliminate flashing.
10453 (js2-clear-face (point-min) (point-max))
10454 ;; Have to reverse the recorded fontifications list so that errors
10455 ;; and warnings overwrite the normal fontifications.
10456 (dolist (f (nreverse js2-mode-fontifications))
10457 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10458 (setq js2-mode-fontifications nil))
10459 (dolist (p js2-mode-deferred-properties)
10460 (apply #'put-text-property p))
10461 (setq js2-mode-deferred-properties nil))
10462
10463 (defun js2-mode-show-errors ()
10464 "Highlight syntax errors."
10465 (when js2-mode-show-parse-errors
10466 (dolist (e (js2-ast-root-errors js2-mode-ast))
10467 (js2-mode-show-warn-or-err e 'js2-error))))
10468
10469 (defun js2-mode-remove-suppressed-warnings ()
10470 "Take suppressed warnings out of the AST warnings list.
10471 This ensures that the counts and `next-error' are correct."
10472 (setf (js2-ast-root-warnings js2-mode-ast)
10473 (js2-delete-if
10474 (lambda (e)
10475 (let ((key (caar e)))
10476 (or
10477 (and (not js2-strict-trailing-comma-warning)
10478 (string-match "trailing\\.comma" key))
10479 (and (not js2-strict-cond-assign-warning)
10480 (string= key "msg.equal.as.assign"))
10481 (and js2-missing-semi-one-line-override
10482 (string= key "msg.missing.semi")
10483 (let* ((beg (second e))
10484 (node (js2-node-at-point beg))
10485 (fn (js2-mode-find-parent-fn node))
10486 (body (and fn (js2-function-node-body fn)))
10487 (lc (and body (js2-node-abs-pos body)))
10488 (rc (and lc (+ lc (js2-node-len body)))))
10489 (and fn
10490 (or (null body)
10491 (save-excursion
10492 (goto-char beg)
10493 (and (js2-same-line lc)
10494 (js2-same-line rc))))))))))
10495 (js2-ast-root-warnings js2-mode-ast))))
10496
10497 (defun js2-mode-show-warnings ()
10498 "Highlight strict-mode warnings."
10499 (when js2-mode-show-strict-warnings
10500 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10501 (js2-mode-show-warn-or-err e 'js2-warning))))
10502
10503 (defun js2-echo-error (old-point new-point)
10504 "Called by point-motion hooks."
10505 (let ((msg (get-text-property new-point 'help-echo)))
10506 (when (and (stringp msg) (or (not (current-message))
10507 (string= (current-message) "Quit")))
10508 (message msg))))
10509
10510 (defalias #'js2-echo-help #'js2-echo-error)
10511
10512 (defun js2-line-break (&optional soft)
10513 "Break line at point and indent, continuing comment if within one.
10514 If inside a string, and `js2-concat-multiline-strings' is not
10515 nil, turn it into concatenation."
10516 (interactive)
10517 (let ((parse-status (syntax-ppss)))
10518 (cond
10519 ;; Check if we're inside a string.
10520 ((nth 3 parse-status)
10521 (if js2-concat-multiline-strings
10522 (js2-mode-split-string parse-status)
10523 (insert "\n")))
10524 ;; Check if inside a block comment.
10525 ((nth 4 parse-status)
10526 (js2-mode-extend-comment (nth 8 parse-status)))
10527 (t
10528 (newline-and-indent)))))
10529
10530 (defun js2-mode-split-string (parse-status)
10531 "Turn a newline in mid-string into a string concatenation.
10532 PARSE-STATUS is as documented in `parse-partial-sexp'."
10533 (let* ((col (current-column))
10534 (quote-char (nth 3 parse-status))
10535 (string-beg (nth 8 parse-status))
10536 (at-eol (eq js2-concat-multiline-strings 'eol)))
10537 (insert quote-char)
10538 (if at-eol
10539 (insert " +\n")
10540 (insert "\n"))
10541 (unless at-eol
10542 (insert "+ "))
10543 (js2-indent-line)
10544 (insert quote-char)
10545 (when (eolp)
10546 (insert quote-char)
10547 (backward-char 1))))
10548
10549 (defun js2-mode-extend-comment (start-pos)
10550 "Indent the line and, when inside a comment block, add comment prefix."
10551 (let (star single col first-line needs-close)
10552 (save-excursion
10553 (back-to-indentation)
10554 (when (< (point) start-pos)
10555 (goto-char start-pos))
10556 (cond
10557 ((looking-at "\\*[^/]")
10558 (setq star t
10559 col (current-column)))
10560 ((looking-at "/\\*")
10561 (setq star t
10562 first-line t
10563 col (1+ (current-column))))
10564 ((looking-at "//")
10565 (setq single t
10566 col (current-column)))))
10567 ;; Heuristic for whether we need to close the comment:
10568 ;; if we've got a parse error here, assume it's an unterminated
10569 ;; comment.
10570 (setq needs-close
10571 (or
10572 (eq (get-text-property (1- (point)) 'point-entered)
10573 'js2-echo-error)
10574 ;; The heuristic above doesn't work well when we're
10575 ;; creating a comment and there's another one downstream,
10576 ;; as our parser thinks this one ends at the end of the
10577 ;; next one. (You can have a /* inside a js block comment.)
10578 ;; So just close it if the next non-ws char isn't a *.
10579 (and first-line
10580 (eolp)
10581 (save-excursion
10582 (skip-chars-forward " \t\r\n")
10583 (not (eq (char-after) ?*))))))
10584 (delete-horizontal-space)
10585 (insert "\n")
10586 (cond
10587 (star
10588 (indent-to col)
10589 (insert "* ")
10590 (if (and first-line needs-close)
10591 (save-excursion
10592 (insert "\n")
10593 (indent-to col)
10594 (insert "*/"))))
10595 ((and single
10596 (save-excursion
10597 (and (zerop (forward-line 1))
10598 (looking-at "\\s-*//"))))
10599 (indent-to col)
10600 (insert "// ")))
10601 ;; Don't need to extend the comment after all.
10602 (js2-indent-line)))
10603
10604 (defun js2-beginning-of-line ()
10605 "Toggle point between bol and first non-whitespace char in line.
10606 Also moves past comment delimiters when inside comments."
10607 (interactive)
10608 (let (node beg)
10609 (cond
10610 ((bolp)
10611 (back-to-indentation))
10612 ((looking-at "//")
10613 (skip-chars-forward "/ \t"))
10614 ((and (eq (char-after) ?*)
10615 (setq node (js2-comment-at-point))
10616 (memq (js2-comment-node-format node) '(jsdoc block))
10617 (save-excursion
10618 (skip-chars-backward " \t")
10619 (bolp)))
10620 (skip-chars-forward "\* \t"))
10621 (t
10622 (goto-char (point-at-bol))))))
10623
10624 (defun js2-end-of-line ()
10625 "Toggle point between eol and last non-whitespace char in line."
10626 (interactive)
10627 (if (eolp)
10628 (skip-chars-backward " \t")
10629 (goto-char (point-at-eol))))
10630
10631 (defun js2-mode-wait-for-parse (callback)
10632 "Invoke CALLBACK when parsing is finished.
10633 If parsing is already finished, calls CALLBACK immediately."
10634 (if (not js2-mode-buffer-dirty-p)
10635 (funcall callback)
10636 (push callback js2-mode-pending-parse-callbacks)
10637 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10638
10639 (defun js2-mode-parse-finished ()
10640 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10641 ;; We can't let errors propagate up, since it prevents the
10642 ;; `js2-parse' method from completing normally and returning
10643 ;; the ast, which makes things mysteriously not work right.
10644 (unwind-protect
10645 (dolist (cb js2-mode-pending-parse-callbacks)
10646 (condition-case err
10647 (funcall cb)
10648 (error (message "%s" err))))
10649 (setq js2-mode-pending-parse-callbacks nil)))
10650
10651 (defun js2-mode-flag-region (from to flag)
10652 "Hide or show text from FROM to TO, according to FLAG.
10653 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10654 Returns the created overlay if FLAG is non-nil."
10655 (remove-overlays from to 'invisible 'js2-outline)
10656 (when flag
10657 (let ((o (make-overlay from to)))
10658 (overlay-put o 'invisible 'js2-outline)
10659 (overlay-put o 'isearch-open-invisible
10660 'js2-isearch-open-invisible)
10661 o)))
10662
10663 ;; Function to be set as an outline-isearch-open-invisible' property
10664 ;; to the overlay that makes the outline invisible (see
10665 ;; `js2-mode-flag-region').
10666 (defun js2-isearch-open-invisible (overlay)
10667 ;; We rely on the fact that isearch places point on the matched text.
10668 (js2-mode-show-element))
10669
10670 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10671 "Return cons cell of bounds of folding overlay at POS.
10672 Returns nil if not found."
10673 (let ((overlays (overlays-at (or pos (point))))
10674 o)
10675 (while (and overlays
10676 (not o))
10677 (if (overlay-get (car overlays) 'invisible)
10678 (setq o (car overlays))
10679 (setq overlays (cdr overlays))))
10680 (if o
10681 (cons (overlay-start o) (overlay-end o)))))
10682
10683 (defun js2-mode-function-at-point (&optional pos)
10684 "Return the innermost function node enclosing current point.
10685 Returns nil if point is not in a function."
10686 (let ((node (js2-node-at-point pos)))
10687 (while (and node (not (js2-function-node-p node)))
10688 (setq node (js2-node-parent node)))
10689 (if (js2-function-node-p node)
10690 node)))
10691
10692 (defun js2-mode-toggle-element ()
10693 "Hide or show the foldable element at the point."
10694 (interactive)
10695 (let (comment fn pos)
10696 (save-excursion
10697 (cond
10698 ;; /* ... */ comment?
10699 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10700 (if (js2-mode-invisible-overlay-bounds
10701 (setq pos (+ 3 (js2-node-abs-pos comment))))
10702 (progn
10703 (goto-char pos)
10704 (js2-mode-show-element))
10705 (js2-mode-hide-element)))
10706 ;; //-comment?
10707 ((save-excursion
10708 (back-to-indentation)
10709 (looking-at js2-mode-//-comment-re))
10710 (js2-mode-toggle-//-comment))
10711 ;; function?
10712 ((setq fn (js2-mode-function-at-point))
10713 (setq pos (and (js2-function-node-body fn)
10714 (js2-node-abs-pos (js2-function-node-body fn))))
10715 (goto-char (1+ pos))
10716 (if (js2-mode-invisible-overlay-bounds)
10717 (js2-mode-show-element)
10718 (js2-mode-hide-element)))
10719 (t
10720 (message "Nothing at point to hide or show"))))))
10721
10722 (defun js2-mode-hide-element ()
10723 "Fold/hide contents of a block, showing ellipses.
10724 Show the hidden text with \\[js2-mode-show-element]."
10725 (interactive)
10726 (if js2-mode-buffer-dirty-p
10727 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10728 (let (node body beg end)
10729 (cond
10730 ((js2-mode-invisible-overlay-bounds)
10731 (message "already hidden"))
10732 (t
10733 (setq node (js2-node-at-point))
10734 (cond
10735 ((js2-block-comment-p node)
10736 (js2-mode-hide-comment node))
10737 (t
10738 (while (and node (not (js2-function-node-p node)))
10739 (setq node (js2-node-parent node)))
10740 (if (and node
10741 (setq body (js2-function-node-body node)))
10742 (progn
10743 (setq beg (js2-node-abs-pos body)
10744 end (+ beg (js2-node-len body)))
10745 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10746 (message "No collapsable element found at point"))))))))
10747
10748 (defun js2-mode-show-element ()
10749 "Show the hidden element at current point."
10750 (interactive)
10751 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10752 (if bounds
10753 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
10754 (message "Nothing to un-hide"))))
10755
10756 (defun js2-mode-show-all ()
10757 "Show all of the text in the buffer."
10758 (interactive)
10759 (js2-mode-flag-region (point-min) (point-max) nil))
10760
10761 (defun js2-mode-toggle-hide-functions ()
10762 (interactive)
10763 (if js2-mode-functions-hidden
10764 (js2-mode-show-functions)
10765 (js2-mode-hide-functions)))
10766
10767 (defun js2-mode-hide-functions ()
10768 "Hides all non-nested function bodies in the buffer.
10769 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10770 to open an individual entry."
10771 (interactive)
10772 (if js2-mode-buffer-dirty-p
10773 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
10774 (if (null js2-mode-ast)
10775 (message "Oops - parsing failed")
10776 (setq js2-mode-functions-hidden t)
10777 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
10778
10779 (defun js2-mode-function-hider (n endp)
10780 (when (not endp)
10781 (let ((tt (js2-node-type n))
10782 body beg end)
10783 (cond
10784 ((and (= tt js2-FUNCTION)
10785 (setq body (js2-function-node-body n)))
10786 (setq beg (js2-node-abs-pos body)
10787 end (+ beg (js2-node-len body)))
10788 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
10789 nil) ; don't process children of function
10790 (t
10791 t))))) ; keep processing other AST nodes
10792
10793 (defun js2-mode-show-functions ()
10794 "Un-hide any folded function bodies in the buffer."
10795 (interactive)
10796 (setq js2-mode-functions-hidden nil)
10797 (save-excursion
10798 (goto-char (point-min))
10799 (while (/= (goto-char (next-overlay-change (point)))
10800 (point-max))
10801 (dolist (o (overlays-at (point)))
10802 (when (and (overlay-get o 'invisible)
10803 (not (overlay-get o 'comment)))
10804 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10805
10806 (defun js2-mode-hide-comment (n)
10807 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
10808 3 ; /**
10809 2)) ; /*
10810 (beg (+ (js2-node-abs-pos n) head))
10811 (end (- (+ beg (js2-node-len n)) head 2))
10812 (o (js2-mode-flag-region beg end 'hide)))
10813 (overlay-put o 'comment t)))
10814
10815 (defun js2-mode-toggle-hide-comments ()
10816 "Folds all block comments in the buffer.
10817 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10818 to open an individual entry."
10819 (interactive)
10820 (if js2-mode-comments-hidden
10821 (js2-mode-show-comments)
10822 (js2-mode-hide-comments)))
10823
10824 (defun js2-mode-hide-comments ()
10825 (interactive)
10826 (if js2-mode-buffer-dirty-p
10827 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
10828 (if (null js2-mode-ast)
10829 (message "Oops - parsing failed")
10830 (setq js2-mode-comments-hidden t)
10831 (dolist (n (js2-ast-root-comments js2-mode-ast))
10832 (let ((format (js2-comment-node-format n)))
10833 (when (js2-block-comment-p n)
10834 (js2-mode-hide-comment n))))
10835 (js2-mode-hide-//-comments)))
10836
10837 (defun js2-mode-extend-//-comment (direction)
10838 "Find start or end of a block of similar //-comment lines.
10839 DIRECTION is -1 to look back, 1 to look forward.
10840 INDENT is the indentation level to match.
10841 Returns the end-of-line position of the furthest adjacent
10842 //-comment line with the same indentation as the current line.
10843 If there is no such matching line, returns current end of line."
10844 (let ((pos (point-at-eol))
10845 (indent (current-indentation)))
10846 (save-excursion
10847 (while (and (zerop (forward-line direction))
10848 (looking-at js2-mode-//-comment-re)
10849 (eq indent (length (match-string 1))))
10850 (setq pos (point-at-eol))
10851 pos))))
10852
10853 (defun js2-mode-hide-//-comments ()
10854 "Fold adjacent 1-line comments, showing only snippet of first one."
10855 (let (beg end)
10856 (save-excursion
10857 (goto-char (point-min))
10858 (while (re-search-forward js2-mode-//-comment-re nil t)
10859 (setq beg (point)
10860 end (js2-mode-extend-//-comment 1))
10861 (unless (eq beg end)
10862 (overlay-put (js2-mode-flag-region beg end 'hide)
10863 'comment t))
10864 (goto-char end)
10865 (forward-char 1)))))
10866
10867 (defun js2-mode-toggle-//-comment ()
10868 "Fold or un-fold any multi-line //-comment at point.
10869 Caller should have determined that this line starts with a //-comment."
10870 (let* ((beg (point-at-eol))
10871 (end beg))
10872 (save-excursion
10873 (goto-char end)
10874 (if (js2-mode-invisible-overlay-bounds)
10875 (js2-mode-show-element)
10876 ;; else hide the comment
10877 (setq beg (js2-mode-extend-//-comment -1)
10878 end (js2-mode-extend-//-comment 1))
10879 (unless (eq beg end)
10880 (overlay-put (js2-mode-flag-region beg end 'hide)
10881 'comment t))))))
10882
10883 (defun js2-mode-show-comments ()
10884 "Un-hide any hidden comments, leaving other hidden elements alone."
10885 (interactive)
10886 (setq js2-mode-comments-hidden nil)
10887 (save-excursion
10888 (goto-char (point-min))
10889 (while (/= (goto-char (next-overlay-change (point)))
10890 (point-max))
10891 (dolist (o (overlays-at (point)))
10892 (when (overlay-get o 'comment)
10893 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10894
10895 (defun js2-mode-display-warnings-and-errors ()
10896 "Turn on display of warnings and errors."
10897 (interactive)
10898 (setq js2-mode-show-parse-errors t
10899 js2-mode-show-strict-warnings t)
10900 (js2-reparse 'force))
10901
10902 (defun js2-mode-hide-warnings-and-errors ()
10903 "Turn off display of warnings and errors."
10904 (interactive)
10905 (setq js2-mode-show-parse-errors nil
10906 js2-mode-show-strict-warnings nil)
10907 (js2-reparse 'force))
10908
10909 (defun js2-mode-toggle-warnings-and-errors ()
10910 "Toggle the display of warnings and errors.
10911 Some users don't like having warnings/errors reported while they type."
10912 (interactive)
10913 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
10914 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
10915 (if (called-interactively-p 'any)
10916 (message "warnings and errors %s"
10917 (if js2-mode-show-parse-errors
10918 "enabled"
10919 "disabled")))
10920 (js2-reparse 'force))
10921
10922 (defun js2-mode-customize ()
10923 (interactive)
10924 (customize-group 'js2-mode))
10925
10926 (defun js2-mode-forward-sexp (&optional arg)
10927 "Move forward across one statement or balanced expression.
10928 With ARG, do it that many times. Negative arg -N means
10929 move backward across N balanced expressions."
10930 (interactive "p")
10931 (setq arg (or arg 1))
10932 (save-restriction
10933 (widen) ;; `blink-matching-open' calls `narrow-to-region'
10934 (js2-reparse))
10935 (let (forward-sexp-function
10936 node (start (point)) pos lp rp child)
10937 (cond
10938 ;; backward-sexp
10939 ;; could probably make this better for some cases:
10940 ;; - if in statement block (e.g. function body), go to parent
10941 ;; - infix exprs like (foo in bar) - maybe go to beginning
10942 ;; of infix expr if in the right-side expression?
10943 ((and arg (minusp arg))
10944 (dotimes (i (- arg))
10945 (js2-backward-sws)
10946 (forward-char -1) ; Enter the node we backed up to.
10947 (when (setq node (js2-node-at-point (point) t))
10948 (setq pos (js2-node-abs-pos node))
10949 (let ((parens (js2-mode-forward-sexp-parens node pos)))
10950 (setq lp (car parens)
10951 rp (cdr parens)))
10952 (when (and lp (> start lp))
10953 (if (and rp (<= start rp))
10954 ;; Between parens, check if there's a child node we can jump.
10955 (when (setq child (js2-node-closest-child node (point) lp t))
10956 (setq pos (js2-node-abs-pos child)))
10957 ;; Before both parens.
10958 (setq pos lp)))
10959 (let ((state (parse-partial-sexp start pos)))
10960 (goto-char (if (not (zerop (car state)))
10961 ;; Stumble at the unbalanced paren if < 0, or
10962 ;; jump a bit further if > 0.
10963 (scan-sexps start -1)
10964 pos))))
10965 (unless pos (goto-char (point-min)))))
10966 (t
10967 ;; forward-sexp
10968 (dotimes (i arg)
10969 (js2-forward-sws)
10970 (when (setq node (js2-node-at-point (point) t))
10971 (setq pos (js2-node-abs-pos node))
10972 (let ((parens (js2-mode-forward-sexp-parens node pos)))
10973 (setq lp (car parens)
10974 rp (cdr parens)))
10975 (or
10976 (when (and rp (<= start rp))
10977 (if (> start lp)
10978 (when (setq child (js2-node-closest-child node (point) rp))
10979 (setq pos (js2-node-abs-end child)))
10980 (setq pos (1+ rp))))
10981 ;; No parens or child nodes, looks for the end of the curren node.
10982 (incf pos (js2-node-len
10983 (if (js2-expr-stmt-node-p (js2-node-parent node))
10984 ;; Stop after the semicolon.
10985 (js2-node-parent node)
10986 node))))
10987 (let ((state (save-excursion (parse-partial-sexp start pos))))
10988 (goto-char (if (not (zerop (car state)))
10989 (scan-sexps start 1)
10990 pos))))
10991 (unless pos (goto-char (point-max))))))))
10992
10993 (defun js2-mode-forward-sexp-parens (node abs-pos)
10994 "Return a cons cell with positions of main parens in NODE."
10995 (cond
10996 ((or (js2-array-node-p node)
10997 (js2-object-node-p node)
10998 (js2-array-comp-node-p node)
10999 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11000 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11001 ((js2-paren-expr-node-p node)
11002 (let ((lp (js2-node-lp node))
11003 (rp (js2-node-rp node)))
11004 (cons (when lp (+ abs-pos lp))
11005 (when rp (+ abs-pos rp)))))))
11006
11007 (defun js2-node-closest-child (parent point limit &optional before)
11008 (let* ((parent-pos (js2-node-abs-pos parent))
11009 (rpoint (- point parent-pos))
11010 (rlimit (- limit parent-pos))
11011 (min (min rpoint rlimit))
11012 (max (max rpoint rlimit))
11013 found)
11014 (catch 'done
11015 (js2-visit-ast
11016 parent
11017 (lambda (node end-p)
11018 (if (eq node parent)
11019 t
11020 (let ((pos (js2-node-pos node)) ;; Both relative values.
11021 (end (+ (js2-node-pos node) (js2-node-len node))))
11022 (when (and (>= pos min) (<= end max)
11023 (if before (< pos rpoint) (> end rpoint)))
11024 (setq found node))
11025 (when (> end rpoint)
11026 (throw 'done nil)))
11027 nil))))
11028 found))
11029
11030 (defun js2-errors ()
11031 "Return a list of errors found."
11032 (and js2-mode-ast
11033 (js2-ast-root-errors js2-mode-ast)))
11034
11035 (defun js2-warnings ()
11036 "Return a list of warnings found."
11037 (and js2-mode-ast
11038 (js2-ast-root-warnings js2-mode-ast)))
11039
11040 (defun js2-have-errors-p ()
11041 "Return non-nil if any parse errors or warnings were found."
11042 (or (js2-errors) (js2-warnings)))
11043
11044 (defun js2-errors-and-warnings ()
11045 "Return a copy of the concatenated errors and warnings lists.
11046 They are appended: first the errors, then the warnings.
11047 Entries are of the form (MSG BEG END)."
11048 (when js2-mode-ast
11049 (append (js2-ast-root-errors js2-mode-ast)
11050 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11051
11052 (defun js2-next-error (&optional arg reset)
11053 "Move to next parse error.
11054 Typically invoked via \\[next-error].
11055 ARG is the number of errors, forward or backward, to move.
11056 RESET means start over from the beginning."
11057 (interactive "p")
11058 (if (not (or (js2-errors) (js2-warnings)))
11059 (message "No errors")
11060 (when reset
11061 (goto-char (point-min)))
11062 (let* ((errs (js2-errors-and-warnings))
11063 (continue t)
11064 (start (point))
11065 (count (or arg 1))
11066 (backward (minusp count))
11067 (sorter (if backward '> '<))
11068 (stopper (if backward '< '>))
11069 (count (abs count))
11070 all-errs err)
11071 ;; Sort by start position.
11072 (setq errs (sort errs (lambda (e1 e2)
11073 (funcall sorter (second e1) (second e2))))
11074 all-errs errs)
11075 ;; Find nth error with pos > start.
11076 (while (and errs continue)
11077 (when (funcall stopper (cadar errs) start)
11078 (setq err (car errs))
11079 (if (zerop (decf count))
11080 (setq continue nil)))
11081 (setq errs (cdr errs)))
11082 (if err
11083 (goto-char (second err))
11084 ;; Wrap around to first error.
11085 (goto-char (second (car all-errs)))
11086 ;; If we were already on it, echo msg again.
11087 (if (= (point) start)
11088 (js2-echo-error (point) (point)))))))
11089
11090 (defun js2-down-mouse-3 ()
11091 "Make right-click move the point to the click location.
11092 This makes right-click context menu operations a bit more intuitive.
11093 The point will not move if the region is active, however, to avoid
11094 destroying the region selection."
11095 (interactive)
11096 (when (and js2-move-point-on-right-click
11097 (not mark-active))
11098 (let ((e last-input-event))
11099 (ignore-errors
11100 (goto-char (cadadr e))))))
11101
11102 (defun js2-mode-create-imenu-index ()
11103 "Return an alist for `imenu--index-alist'."
11104 ;; This is built up in `js2-parse-record-imenu' during parsing.
11105 (when js2-mode-ast
11106 ;; if we have an ast but no recorder, they're requesting a rescan
11107 (unless js2-imenu-recorder
11108 (js2-reparse 'force))
11109 (prog1
11110 (js2-build-imenu-index)
11111 (setq js2-imenu-recorder nil
11112 js2-imenu-function-map nil))))
11113
11114 (defun js2-mode-find-tag ()
11115 "Replacement for `find-tag-default'.
11116 `find-tag-default' returns a ridiculous answer inside comments."
11117 (let (beg end)
11118 (js2-with-underscore-as-word-syntax
11119 (save-excursion
11120 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11121 (looking-back "[A-Za-z0-9_$]"))
11122 (setq beg (progn (forward-word -1) (point))
11123 end (progn (forward-word 1) (point)))
11124 (setq beg (progn (forward-word 1) (point))
11125 end (progn (forward-word -1) (point))))
11126 (replace-regexp-in-string
11127 "[\"']" ""
11128 (buffer-substring-no-properties beg end))))))
11129
11130 (defun js2-mode-forward-sibling ()
11131 "Move to the end of the sibling following point in parent.
11132 Returns non-nil if successful, or nil if there was no following sibling."
11133 (let* ((node (js2-node-at-point))
11134 (parent (js2-mode-find-enclosing-fn node))
11135 sib)
11136 (when (setq sib (js2-node-find-child-after (point) parent))
11137 (goto-char (+ (js2-node-abs-pos sib)
11138 (js2-node-len sib))))))
11139
11140 (defun js2-mode-backward-sibling ()
11141 "Move to the beginning of the sibling node preceding point in parent.
11142 Parent is defined as the enclosing script or function."
11143 (let* ((node (js2-node-at-point))
11144 (parent (js2-mode-find-enclosing-fn node))
11145 sib)
11146 (when (setq sib (js2-node-find-child-before (point) parent))
11147 (goto-char (js2-node-abs-pos sib)))))
11148
11149 (defun js2-beginning-of-defun (&optional arg)
11150 "Go to line on which current function starts, and return t on success.
11151 If we're not in a function or already at the beginning of one, go
11152 to beginning of previous script-level element.
11153 With ARG N, do that N times. If N is negative, move forward."
11154 (setq arg (or arg 1))
11155 (if (plusp arg)
11156 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11157 (when (cond
11158 ((js2-function-node-p parent)
11159 (goto-char (js2-node-abs-pos parent)))
11160 (t
11161 (js2-mode-backward-sibling)))
11162 (if (> arg 1)
11163 (js2-beginning-of-defun (1- arg))
11164 t)))
11165 (when (js2-end-of-defun)
11166 (if (>= arg -1)
11167 (js2-beginning-of-defun 1)
11168 (js2-beginning-of-defun (1+ arg))))))
11169
11170 (defun js2-end-of-defun ()
11171 "Go to the char after the last position of the current function
11172 or script-level element."
11173 (let* ((node (js2-node-at-point))
11174 (parent (or (and (js2-function-node-p node) node)
11175 (js2-node-parent-script-or-fn node)))
11176 script)
11177 (unless (js2-function-node-p parent)
11178 ;; Use current script-level node, or, if none, the next one.
11179 (setq script (or parent node)
11180 parent (js2-node-find-child-before (point) script))
11181 (when (or (null parent)
11182 (>= (point) (+ (js2-node-abs-pos parent)
11183 (js2-node-len parent))))
11184 (setq parent (js2-node-find-child-after (point) script))))
11185 (when parent
11186 (goto-char (+ (js2-node-abs-pos parent)
11187 (js2-node-len parent))))))
11188
11189 (defun js2-mark-defun (&optional allow-extend)
11190 "Put mark at end of this function, point at beginning.
11191 The function marked is the one that contains point.
11192
11193 Interactively, if this command is repeated,
11194 or (in Transient Mark mode) if the mark is active,
11195 it marks the next defun after the ones already marked."
11196 (interactive "p")
11197 (let (extended)
11198 (when (and allow-extend
11199 (or (and (eq last-command this-command) (mark t))
11200 (and transient-mark-mode mark-active)))
11201 (let ((sib (save-excursion
11202 (goto-char (mark))
11203 (if (js2-mode-forward-sibling)
11204 (point))))
11205 node)
11206 (if sib
11207 (progn
11208 (set-mark sib)
11209 (setq extended t))
11210 ;; no more siblings - try extending to enclosing node
11211 (goto-char (mark t)))))
11212 (when (not extended)
11213 (let ((node (js2-node-at-point (point) t)) ; skip comments
11214 ast fn stmt parent beg end)
11215 (when (js2-ast-root-p node)
11216 (setq ast node
11217 node (or (js2-node-find-child-after (point) node)
11218 (js2-node-find-child-before (point) node))))
11219 ;; only mark whole buffer if we can't find any children
11220 (if (null node)
11221 (setq node ast))
11222 (if (js2-function-node-p node)
11223 (setq parent node)
11224 (setq fn (js2-mode-find-enclosing-fn node)
11225 stmt (if (or (null fn)
11226 (js2-ast-root-p fn))
11227 (js2-mode-find-first-stmt node))
11228 parent (or stmt fn)))
11229 (setq beg (js2-node-abs-pos parent)
11230 end (+ beg (js2-node-len parent)))
11231 (push-mark beg)
11232 (goto-char end)
11233 (exchange-point-and-mark)))))
11234
11235 (defun js2-narrow-to-defun ()
11236 "Narrow to the function enclosing point."
11237 (interactive)
11238 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11239 (fn (if (js2-script-node-p node)
11240 node
11241 (js2-mode-find-enclosing-fn node)))
11242 (beg (js2-node-abs-pos fn)))
11243 (unless (js2-ast-root-p fn)
11244 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11245
11246 (provide 'js2-mode)
11247
11248 ;;; js2-mode.el ends here