]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
abc4dc22437a85293ac73e239fde470bcb86c58f
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2013 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
10 ;; Version: 20130619
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
65
66 ;; Notes:
67
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
71
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
76
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
81
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code is mentioned here for posterity, it has
84 ;; outdated information and is mostly unmaintained.
85
86 ;;; Code:
87
88 (eval-when-compile
89 (require 'cl))
90
91 (require 'imenu)
92 (require 'cc-cmds) ; for `c-fill-paragraph'
93
94 (eval-and-compile
95 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
96 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
97
98 (defvar electric-layout-rules)
99
100 ;;; Externs (variables presumed to be defined by the host system)
101
102 (defvar js2-ecma-262-externs
103 (mapcar 'symbol-name
104 '(Array Boolean Date Error EvalError Function Infinity JSON
105 Math NaN Number Object RangeError ReferenceError RegExp
106 String SyntaxError TypeError URIError arguments
107 decodeURI decodeURIComponent encodeURI
108 encodeURIComponent escape eval isFinite isNaN
109 parseFloat parseInt undefined unescape))
110 "Ecma-262 externs. Included in `js2-externs' by default.")
111
112 (defvar js2-browser-externs
113 (mapcar 'symbol-name
114 '(;; DOM level 1
115 Attr CDATASection CharacterData Comment DOMException
116 DOMImplementation Document DocumentFragment
117 DocumentType Element Entity EntityReference
118 ExceptionCode NamedNodeMap Node NodeList Notation
119 ProcessingInstruction Text
120
121 ;; DOM level 2
122 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
123 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
124 HTMLBodyElement HTMLButtonElement HTMLCollection
125 HTMLDListElement HTMLDirectoryElement HTMLDivElement
126 HTMLDocument HTMLElement HTMLFieldSetElement
127 HTMLFontElement HTMLFormElement HTMLFrameElement
128 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
129 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
130 HTMLImageElement HTMLInputElement HTMLIsIndexElement
131 HTMLLIElement HTMLLabelElement HTMLLegendElement
132 HTMLLinkElement HTMLMapElement HTMLMenuElement
133 HTMLMetaElement HTMLModElement HTMLOListElement
134 HTMLObjectElement HTMLOptGroupElement
135 HTMLOptionElement HTMLOptionsCollection
136 HTMLParagraphElement HTMLParamElement HTMLPreElement
137 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
138 HTMLStyleElement HTMLTableCaptionElement
139 HTMLTableCellElement HTMLTableColElement
140 HTMLTableElement HTMLTableRowElement
141 HTMLTableSectionElement HTMLTextAreaElement
142 HTMLTitleElement HTMLUListElement
143
144 ;; DOM level 3
145 DOMConfiguration DOMError DOMException
146 DOMImplementationList DOMImplementationSource
147 DOMLocator DOMStringList NameList TypeInfo
148 UserDataHandler
149
150 ;; Window
151 window alert confirm document java navigator prompt screen
152 self top
153
154 ;; W3C CSS
155 CSSCharsetRule CSSFontFace CSSFontFaceRule
156 CSSImportRule CSSMediaRule CSSPageRule
157 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
158 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
159 CSSValue CSSValueList Counter DOMImplementationCSS
160 DocumentCSS DocumentStyle ElementCSSInlineStyle
161 LinkStyle MediaList RGBColor Rect StyleSheet
162 StyleSheetList ViewCSS
163
164 ;; W3C Event
165 EventListener EventTarget Event DocumentEvent UIEvent
166 MouseEvent MutationEvent KeyboardEvent
167
168 ;; W3C Range
169 DocumentRange Range RangeException
170
171 ;; W3C XML
172 XPathResult XMLHttpRequest
173
174 ;; console object. Provided by at least Chrome and Firefox.
175 console))
176 "Browser externs.
177 You can cause these to be included or excluded with the custom
178 variable `js2-include-browser-externs'.")
179
180 (defvar js2-rhino-externs
181 (mapcar 'symbol-name
182 '(Packages importClass importPackage com org java
183 ;; Global object (shell) externs.
184 defineClass deserialize doctest gc help load
185 loadClass print quit readFile readUrl runCommand seal
186 serialize spawn sync toint32 version))
187 "Mozilla Rhino externs.
188 Set `js2-include-rhino-externs' to t to include them.")
189
190 (defvar js2-node-externs
191 (mapcar 'symbol-name
192 '(__dirname __filename Buffer clearInterval clearTimeout require
193 console exports global module process setInterval setTimeout))
194 "Node.js externs.
195 Set `js2-include-node-externs' to t to include them.")
196
197 (defvar js2-typed-array-externs
198 (mapcar 'symbol-name
199 '(ArrayBuffer Uint8ClampedArray DataView
200 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
201 Float32Array Float64Array))
202 "Khronos typed array externs. Available in most modern browsers and
203 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
204 are enabled, these will also be included.")
205
206 ;;; Variables
207
208 (defun js2-mark-safe-local (name pred)
209 "Make the variable NAME buffer-local and mark it as safe file-local
210 variable with predicate PRED."
211 (make-variable-buffer-local name)
212 (put name 'safe-local-variable pred))
213
214 (defcustom js2-highlight-level 2
215 "Amount of syntax highlighting to perform.
216 0 or a negative value means none.
217 1 adds basic syntax highlighting.
218 2 adds highlighting of some Ecma built-in properties.
219 3 adds highlighting of many Ecma built-in functions."
220 :group 'js2-mode
221 :type '(choice (const :tag "None" 0)
222 (const :tag "Basic" 1)
223 (const :tag "Include Properties" 2)
224 (const :tag "Include Functions" 3)))
225
226 (defvar js2-mode-dev-mode-p nil
227 "Non-nil if running in development mode. Normally nil.")
228
229 (defgroup js2-mode nil
230 "An improved JavaScript mode."
231 :group 'languages)
232
233 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
234 (numberp c-basic-offset))
235 c-basic-offset
236 4)
237 "Number of spaces to indent nested statements.
238 Similar to `c-basic-offset'."
239 :group 'js2-mode
240 :type 'integer)
241 (js2-mark-safe-local 'js2-basic-offset 'integerp)
242
243 (defcustom js2-bounce-indent-p nil
244 "Non-nil to have indent-line function choose among alternatives.
245 If nil, the indent-line function will indent to a predetermined column
246 based on heuristic guessing. If non-nil, then if the current line is
247 already indented to that predetermined column, indenting will choose
248 another likely column and indent to that spot. Repeated invocation of
249 the indent-line function will cycle among the computed alternatives.
250 See the function `js2-bounce-indent' for details. When it is non-nil,
251 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
252 :type 'boolean
253 :group 'js2-mode)
254
255 (defcustom js2-pretty-multiline-declarations t
256 "Non-nil to line up multiline declarations vertically:
257
258 var a = 10,
259 b = 20,
260 c = 30;
261
262 If the value is not `all', and the first assigned value in
263 declaration is a function/array/object literal spanning several
264 lines, it won't be indented additionally:
265
266 var o = { var bar = 2,
267 foo: 3 vs. o = {
268 }, foo: 3
269 bar = 2; };"
270 :group 'js2-mode
271 :type 'symbol)
272 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
273
274 (defcustom js2-idle-timer-delay 0.2
275 "Delay in secs before re-parsing after user makes changes.
276 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
277 :type 'number
278 :group 'js2-mode)
279 (make-variable-buffer-local 'js2-idle-timer-delay)
280
281 (defcustom js2-dynamic-idle-timer-adjust 0
282 "Positive to adjust `js2-idle-timer-delay' based on file size.
283 The idea is that for short files, parsing is faster so we can be
284 more responsive to user edits without interfering with editing.
285 The buffer length in characters (typically bytes) is divided by
286 this value and used to multiply `js2-idle-timer-delay' for the
287 buffer. For example, a 21k file and 10k adjust yields 21k/10k
288 == 2, so js2-idle-timer-delay is multiplied by 2.
289 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
290 `js2-idle-timer-delay' is not dependent on the file size."
291 :type 'number
292 :group 'js2-mode)
293
294 (defcustom js2-concat-multiline-strings t
295 "When non-nil, `js2-line-break' in mid-string will make it a
296 string concatenation. When `eol', the '+' will be inserted at the
297 end of the line, otherwise, at the beginning of the next line."
298 :type '(choice (const t) (const eol) (const nil))
299 :group 'js2-mode)
300
301 (defcustom js2-mode-show-parse-errors t
302 "True to highlight parse errors."
303 :type 'boolean
304 :group 'js2-mode)
305
306 (defcustom js2-mode-show-strict-warnings t
307 "Non-nil to emit Ecma strict-mode warnings.
308 Some of the warnings can be individually disabled by other flags,
309 even if this flag is non-nil."
310 :type 'boolean
311 :group 'js2-mode)
312
313 (defcustom js2-strict-trailing-comma-warning t
314 "Non-nil to warn about trailing commas in array literals.
315 Ecma-262-5.1 allows them, but older versions of IE raise an error."
316 :type 'boolean
317 :group 'js2-mode)
318
319 (defcustom js2-strict-missing-semi-warning t
320 "Non-nil to warn about semicolon auto-insertion after statement.
321 Technically this is legal per Ecma-262, but some style guides disallow
322 depending on it."
323 :type 'boolean
324 :group 'js2-mode)
325
326 (defcustom js2-missing-semi-one-line-override nil
327 "Non-nil to permit missing semicolons in one-line functions.
328 In one-liner functions such as `function identity(x) {return x}'
329 people often omit the semicolon for a cleaner look. If you are
330 such a person, you can suppress the missing-semicolon warning
331 by setting this variable to t."
332 :type 'boolean
333 :group 'js2-mode)
334
335 (defcustom js2-strict-inconsistent-return-warning t
336 "Non-nil to warn about mixing returns with value-returns.
337 It's perfectly legal to have a `return' and a `return foo' in the
338 same function, but it's often an indicator of a bug, and it also
339 interferes with type inference (in systems that support it.)"
340 :type 'boolean
341 :group 'js2-mode)
342
343 (defcustom js2-strict-cond-assign-warning t
344 "Non-nil to warn about expressions like if (a = b).
345 This often should have been '==' instead of '='. If the warning
346 is enabled, you can suppress it on a per-expression basis by
347 parenthesizing the expression, e.g. if ((a = b)) ..."
348 :type 'boolean
349 :group 'js2-mode)
350
351 (defcustom js2-strict-var-redeclaration-warning t
352 "Non-nil to warn about redeclaring variables in a script or function."
353 :type 'boolean
354 :group 'js2-mode)
355
356 (defcustom js2-strict-var-hides-function-arg-warning t
357 "Non-nil to warn about a var decl hiding a function argument."
358 :type 'boolean
359 :group 'js2-mode)
360
361 (defcustom js2-skip-preprocessor-directives nil
362 "Non-nil to treat lines beginning with # as comments.
363 Useful for viewing Mozilla JavaScript source code."
364 :type 'boolean
365 :group 'js2-mode)
366
367 (defcustom js2-language-version 200
368 "Configures what JavaScript language version to recognize.
369 Currently versions 150, 160, 170, 180 and 200 are supported,
370 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
371 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
372 yield, and Array comprehensions, and 1.8 adds function closures."
373 :type 'integer
374 :group 'js2-mode)
375
376 (defcustom js2-allow-keywords-as-property-names t
377 "If non-nil, you can use JavaScript keywords as object property names.
378 Examples:
379
380 var foo = {int: 5, while: 6, continue: 7};
381 foo.return = 8;
382
383 Ecma-262 5.1 allows this syntax, but some engines still don't."
384 :type 'boolean
385 :group 'js2-mode)
386
387 (defcustom js2-instanceof-has-side-effects nil
388 "If non-nil, treats the instanceof operator as having side effects.
389 This is useful for xulrunner apps."
390 :type 'boolean
391 :group 'js2-mode)
392
393 (defcustom js2-move-point-on-right-click t
394 "Non-nil to move insertion point when you right-click.
395 This makes right-click context menu behavior a bit more intuitive,
396 since menu operations generally apply to the point. The exception
397 is if there is a region selection, in which case the point does -not-
398 move, so cut/copy/paste can work properly.
399
400 Note that IntelliJ moves the point, and Eclipse leaves it alone,
401 so this behavior is customizable."
402 :group 'js2-mode
403 :type 'boolean)
404
405 (defcustom js2-allow-rhino-new-expr-initializer t
406 "Non-nil to support a Rhino's experimental syntactic construct.
407
408 Rhino supports the ability to follow a `new' expression with an object
409 literal, which is used to set additional properties on the new object
410 after calling its constructor. Syntax:
411
412 new <expr> [ ( arglist ) ] [initializer]
413
414 Hence, this expression:
415
416 new Object {a: 1, b: 2}
417
418 results in an Object with properties a=1 and b=2. This syntax is
419 apparently not configurable in Rhino - it's currently always enabled,
420 as of Rhino version 1.7R2."
421 :type 'boolean
422 :group 'js2-mode)
423
424 (defcustom js2-allow-member-expr-as-function-name nil
425 "Non-nil to support experimental Rhino syntax for function names.
426
427 Rhino supports an experimental syntax configured via the Rhino Context
428 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
429
430 function <member-expr> ( [ arg-list ] ) { <body> }
431
432 Where member-expr is a non-parenthesized 'member expression', which
433 is anything at the grammar level of a new-expression or lower, meaning
434 any expression that does not involve infix or unary operators.
435
436 When <member-expr> is not a simple identifier, then it is syntactic
437 sugar for assigning the anonymous function to the <member-expr>. Hence,
438 this code:
439
440 function a.b().c[2] (x, y) { ... }
441
442 is rewritten as:
443
444 a.b().c[2] = function(x, y) {...}
445
446 which doesn't seem particularly useful, but Rhino permits it."
447 :type 'boolean
448 :group 'js2-mode)
449
450 ;; scanner variables
451
452 (defmacro js2-deflocal (name value &optional comment)
453 "Define a buffer-local variable NAME with VALUE and COMMENT."
454 `(progn
455 (defvar ,name ,value ,comment)
456 (make-variable-buffer-local ',name)))
457
458 (defvar js2-EOF_CHAR -1
459 "Represents end of stream. Distinct from js2-EOF token type.")
460
461 ;; I originally used symbols to represent tokens, but Rhino uses
462 ;; ints and then sets various flag bits in them, so ints it is.
463 ;; The upshot is that we need a `js2-' prefix in front of each name.
464 (defvar js2-ERROR -1)
465 (defvar js2-EOF 0)
466 (defvar js2-EOL 1)
467 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
468 (defvar js2-LEAVEWITH 3)
469 (defvar js2-RETURN 4)
470 (defvar js2-GOTO 5)
471 (defvar js2-IFEQ 6)
472 (defvar js2-IFNE 7)
473 (defvar js2-SETNAME 8)
474 (defvar js2-BITOR 9)
475 (defvar js2-BITXOR 10)
476 (defvar js2-BITAND 11)
477 (defvar js2-EQ 12)
478 (defvar js2-NE 13)
479 (defvar js2-LT 14)
480 (defvar js2-LE 15)
481 (defvar js2-GT 16)
482 (defvar js2-GE 17)
483 (defvar js2-LSH 18)
484 (defvar js2-RSH 19)
485 (defvar js2-URSH 20)
486 (defvar js2-ADD 21) ; infix plus
487 (defvar js2-SUB 22) ; infix minus
488 (defvar js2-MUL 23)
489 (defvar js2-DIV 24)
490 (defvar js2-MOD 25)
491 (defvar js2-NOT 26)
492 (defvar js2-BITNOT 27)
493 (defvar js2-POS 28) ; unary plus
494 (defvar js2-NEG 29) ; unary minus
495 (defvar js2-NEW 30)
496 (defvar js2-DELPROP 31)
497 (defvar js2-TYPEOF 32)
498 (defvar js2-GETPROP 33)
499 (defvar js2-GETPROPNOWARN 34)
500 (defvar js2-SETPROP 35)
501 (defvar js2-GETELEM 36)
502 (defvar js2-SETELEM 37)
503 (defvar js2-CALL 38)
504 (defvar js2-NAME 39) ; an identifier
505 (defvar js2-NUMBER 40)
506 (defvar js2-STRING 41)
507 (defvar js2-NULL 42)
508 (defvar js2-THIS 43)
509 (defvar js2-FALSE 44)
510 (defvar js2-TRUE 45)
511 (defvar js2-SHEQ 46) ; shallow equality (===)
512 (defvar js2-SHNE 47) ; shallow inequality (!==)
513 (defvar js2-REGEXP 48)
514 (defvar js2-BINDNAME 49)
515 (defvar js2-THROW 50)
516 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
517 (defvar js2-IN 52)
518 (defvar js2-INSTANCEOF 53)
519 (defvar js2-LOCAL_LOAD 54)
520 (defvar js2-GETVAR 55)
521 (defvar js2-SETVAR 56)
522 (defvar js2-CATCH_SCOPE 57)
523 (defvar js2-ENUM_INIT_KEYS 58)
524 (defvar js2-ENUM_INIT_VALUES 59)
525 (defvar js2-ENUM_INIT_ARRAY 60)
526 (defvar js2-ENUM_NEXT 61)
527 (defvar js2-ENUM_ID 62)
528 (defvar js2-THISFN 63)
529 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
530 (defvar js2-ARRAYLIT 65) ; array literal
531 (defvar js2-OBJECTLIT 66) ; object literal
532 (defvar js2-GET_REF 67) ; *reference
533 (defvar js2-SET_REF 68) ; *reference = something
534 (defvar js2-DEL_REF 69) ; delete reference
535 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
536 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
537 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
538
539 ;; XML support
540 (defvar js2-DEFAULTNAMESPACE 73)
541 (defvar js2-ESCXMLATTR 74)
542 (defvar js2-ESCXMLTEXT 75)
543 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
544 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
545 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
546 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
547
548 (defvar js2-first-bytecode js2-ENTERWITH)
549 (defvar js2-last-bytecode js2-REF_NS_NAME)
550
551 (defvar js2-TRY 80)
552 (defvar js2-SEMI 81) ; semicolon
553 (defvar js2-LB 82) ; left and right brackets
554 (defvar js2-RB 83)
555 (defvar js2-LC 84) ; left and right curly-braces
556 (defvar js2-RC 85)
557 (defvar js2-LP 86) ; left and right parens
558 (defvar js2-RP 87)
559 (defvar js2-COMMA 88) ; comma operator
560
561 (defvar js2-ASSIGN 89) ; simple assignment (=)
562 (defvar js2-ASSIGN_BITOR 90) ; |=
563 (defvar js2-ASSIGN_BITXOR 91) ; ^=
564 (defvar js2-ASSIGN_BITAND 92) ; &=
565 (defvar js2-ASSIGN_LSH 93) ; <<=
566 (defvar js2-ASSIGN_RSH 94) ; >>=
567 (defvar js2-ASSIGN_URSH 95) ; >>>=
568 (defvar js2-ASSIGN_ADD 96) ; +=
569 (defvar js2-ASSIGN_SUB 97) ; -=
570 (defvar js2-ASSIGN_MUL 98) ; *=
571 (defvar js2-ASSIGN_DIV 99) ; /=
572 (defvar js2-ASSIGN_MOD 100) ; %=
573
574 (defvar js2-first-assign js2-ASSIGN)
575 (defvar js2-last-assign js2-ASSIGN_MOD)
576
577 (defvar js2-HOOK 101) ; conditional (?:)
578 (defvar js2-COLON 102)
579 (defvar js2-OR 103) ; logical or (||)
580 (defvar js2-AND 104) ; logical and (&&)
581 (defvar js2-INC 105) ; increment/decrement (++ --)
582 (defvar js2-DEC 106)
583 (defvar js2-DOT 107) ; member operator (.)
584 (defvar js2-FUNCTION 108) ; function keyword
585 (defvar js2-EXPORT 109) ; export keyword
586 (defvar js2-IMPORT 110) ; import keyword
587 (defvar js2-IF 111) ; if keyword
588 (defvar js2-ELSE 112) ; else keyword
589 (defvar js2-SWITCH 113) ; switch keyword
590 (defvar js2-CASE 114) ; case keyword
591 (defvar js2-DEFAULT 115) ; default keyword
592 (defvar js2-WHILE 116) ; while keyword
593 (defvar js2-DO 117) ; do keyword
594 (defvar js2-FOR 118) ; for keyword
595 (defvar js2-BREAK 119) ; break keyword
596 (defvar js2-CONTINUE 120) ; continue keyword
597 (defvar js2-VAR 121) ; var keyword
598 (defvar js2-WITH 122) ; with keyword
599 (defvar js2-CATCH 123) ; catch keyword
600 (defvar js2-FINALLY 124) ; finally keyword
601 (defvar js2-VOID 125) ; void keyword
602 (defvar js2-RESERVED 126) ; reserved keywords
603
604 (defvar js2-EMPTY 127)
605
606 ;; Types used for the parse tree - never returned by scanner.
607
608 (defvar js2-BLOCK 128) ; statement block
609 (defvar js2-LABEL 129) ; label
610 (defvar js2-TARGET 130)
611 (defvar js2-LOOP 131)
612 (defvar js2-EXPR_VOID 132) ; expression statement in functions
613 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
614 (defvar js2-JSR 134)
615 (defvar js2-SCRIPT 135) ; top-level node for entire script
616 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
617 (defvar js2-USE_STACK 137)
618 (defvar js2-SETPROP_OP 138) ; x.y op= something
619 (defvar js2-SETELEM_OP 139) ; x[y] op= something
620 (defvar js2-LOCAL_BLOCK 140)
621 (defvar js2-SET_REF_OP 141) ; *reference op= something
622
623 ;; For XML support:
624 (defvar js2-DOTDOT 142) ; member operator (..)
625 (defvar js2-COLONCOLON 143) ; namespace::name
626 (defvar js2-XML 144) ; XML type
627 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
628 (defvar js2-XMLATTR 146) ; @
629 (defvar js2-XMLEND 147)
630
631 ;; Optimizer-only tokens
632 (defvar js2-TO_OBJECT 148)
633 (defvar js2-TO_DOUBLE 149)
634
635 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
636 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
637 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
638 (defvar js2-CONST 153)
639 (defvar js2-SETCONST 154)
640 (defvar js2-SETCONSTVAR 155)
641 (defvar js2-ARRAYCOMP 156)
642 (defvar js2-LETEXPR 157)
643 (defvar js2-WITHEXPR 158)
644 (defvar js2-DEBUGGER 159)
645
646 (defvar js2-COMMENT 160)
647 (defvar js2-ENUM 161) ; for "enum" reserved word
648 (defvar js2-TRIPLEDOT 162) ; for rest parameter
649
650 (defconst js2-num-tokens (1+ js2-TRIPLEDOT))
651
652 (defconst js2-debug-print-trees nil)
653
654 ;; Rhino accepts any string or stream as input. Emacs character
655 ;; processing works best in buffers, so we'll assume the input is a
656 ;; buffer. JavaScript strings can be copied into temp buffers before
657 ;; scanning them.
658
659 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
660 ;; They're the Emacs equivalent of instance variables, more or less.
661
662 (js2-deflocal js2-ts-dirty-line nil
663 "Token stream buffer-local variable.
664 Indicates stuff other than whitespace since start of line.")
665
666 (js2-deflocal js2-ts-hit-eof nil
667 "Token stream buffer-local variable.")
668
669 ;; FIXME: Unused.
670 (js2-deflocal js2-ts-line-start 0
671 "Token stream buffer-local variable.")
672
673 (js2-deflocal js2-ts-lineno 1
674 "Token stream buffer-local variable.")
675
676 ;; FIXME: Unused.
677 (js2-deflocal js2-ts-line-end-char -1
678 "Token stream buffer-local variable.")
679
680 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
681 "Token stream buffer-local variable.
682 Current scan position.")
683
684 ;; FIXME: Unused.
685 (js2-deflocal js2-ts-is-xml-attribute nil
686 "Token stream buffer-local variable.")
687
688 (js2-deflocal js2-ts-xml-is-tag-content nil
689 "Token stream buffer-local variable.")
690
691 (js2-deflocal js2-ts-xml-open-tags-count 0
692 "Token stream buffer-local variable.")
693
694 (js2-deflocal js2-ts-string-buffer nil
695 "Token stream buffer-local variable.
696 List of chars built up while scanning various tokens.")
697
698 (defstruct (js2-token
699 (:constructor nil)
700 (:constructor make-js2-token (beg)))
701 "Value returned from the token stream."
702 (type js2-EOF)
703 (beg 1)
704 (end -1)
705 (string "")
706 number
707 regexp-flags
708 comment-type
709 follows-eol-p)
710
711 (defstruct (js2-ts-state
712 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
713 (cursor js2-ts-cursor)
714 (tokens js2-ti-tokens)
715 (tokens-cursor js2-ti-tokens-cursor)
716 (lookahead js2-ti-lookahead))))
717 lineno
718 cursor
719 tokens
720 tokens-cursor
721 lookahead)
722
723 ;;; Parser variables
724
725 (js2-deflocal js2-parsed-errors nil
726 "List of errors produced during scanning/parsing.")
727
728 (js2-deflocal js2-parsed-warnings nil
729 "List of warnings produced during scanning/parsing.")
730
731 (js2-deflocal js2-recover-from-parse-errors t
732 "Non-nil to continue parsing after a syntax error.
733
734 In recovery mode, the AST will be built in full, and any error
735 nodes will be flagged with appropriate error information. If
736 this flag is nil, a syntax error will result in an error being
737 signaled.
738
739 The variable is automatically buffer-local, because different
740 modes that use the parser will need different settings.")
741
742 (js2-deflocal js2-parse-hook nil
743 "List of callbacks for receiving parsing progress.")
744
745 (defvar js2-parse-finished-hook nil
746 "List of callbacks to notify when parsing finishes.
747 Not called if parsing was interrupted.")
748
749 (js2-deflocal js2-is-eval-code nil
750 "True if we're evaluating code in a string.
751 If non-nil, the tokenizer will record the token text, and the AST nodes
752 will record their source text. Off by default for IDE modes, since the
753 text is available in the buffer.")
754
755 (defvar js2-parse-ide-mode t
756 "Non-nil if the parser is being used for `js2-mode'.
757 If non-nil, the parser will set text properties for fontification
758 and the syntax table. The value should be nil when using the
759 parser as a frontend to an interpreter or byte compiler.")
760
761 ;;; Parser instance variables (buffer-local vars for js2-parse)
762
763 (defconst js2-ti-after-eol (lsh 1 16)
764 "Flag: first token of the source line.")
765
766 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
767
768 (js2-deflocal js2-compiler-generate-debug-info t)
769 (js2-deflocal js2-compiler-use-dynamic-scope nil)
770 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
771 (js2-deflocal js2-compiler-xml-available t)
772 (js2-deflocal js2-compiler-optimization-level 0)
773 (js2-deflocal js2-compiler-generating-source t)
774 (js2-deflocal js2-compiler-strict-mode nil)
775 (js2-deflocal js2-compiler-report-warning-as-error nil)
776 (js2-deflocal js2-compiler-generate-observer-count nil)
777 (js2-deflocal js2-compiler-activation-names nil)
778
779 ;; SKIP: sourceURI
780
781 ;; There's a compileFunction method in Context.java - may need it.
782 (js2-deflocal js2-called-by-compile-function nil
783 "True if `js2-parse' was called by `js2-compile-function'.
784 Will only be used when we finish implementing the interpreter.")
785
786 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
787
788 ;; SKIP: node factory - we're going to just call functions directly,
789 ;; and eventually go to a unified AST format.
790
791 (js2-deflocal js2-nesting-of-function 0)
792
793 (js2-deflocal js2-recorded-identifiers nil
794 "Tracks identifiers found during parsing.")
795
796 (js2-deflocal js2-is-in-destructuring nil
797 "True while parsing destructuring expression.")
798
799 (defcustom js2-global-externs nil
800 "A list of any extern names you'd like to consider always declared.
801 This list is global and is used by all `js2-mode' files.
802 You can create buffer-local externs list using `js2-additional-externs'.
803
804 There is also a buffer-local variable `js2-default-externs',
805 which is initialized by default to include the Ecma-262 externs
806 and the standard browser externs. The three lists are all
807 checked during highlighting."
808 :type 'list
809 :group 'js2-mode)
810
811 (js2-deflocal js2-default-externs nil
812 "Default external declarations.
813
814 These are currently only used for highlighting undeclared variables,
815 which only worries about top-level (unqualified) references.
816 As js2-mode's processing improves, we will flesh out this list.
817
818 The initial value is set to `js2-ecma-262-externs', unless some
819 of the `js2-include-?-externs' variables are set to t, in which
820 case the browser, Rhino and/or Node.js externs are also included.
821
822 See `js2-additional-externs' for more information.")
823
824 (defcustom js2-include-browser-externs t
825 "Non-nil to include browser externs in the master externs list.
826 If you work on JavaScript files that are not intended for browsers,
827 such as Mozilla Rhino server-side JavaScript, set this to nil.
828 See `js2-additional-externs' for more information about externs."
829 :type 'boolean
830 :group 'js2-mode)
831
832 (defcustom js2-include-rhino-externs nil
833 "Non-nil to include Mozilla Rhino externs in the master externs list.
834 See `js2-additional-externs' for more information about externs."
835 :type 'boolean
836 :group 'js2-mode)
837
838 (defcustom js2-include-node-externs nil
839 "Non-nil to include Node.js externs in the master externs list.
840 See `js2-additional-externs' for more information about externs."
841 :type 'boolean
842 :group 'js2-mode)
843
844 (js2-deflocal js2-additional-externs nil
845 "A buffer-local list of additional external declarations.
846 It is used to decide whether variables are considered undeclared
847 for purposes of highlighting.
848
849 Each entry is a Lisp string. The string should be the fully qualified
850 name of an external entity. All externs should be added to this list,
851 so that as js2-mode's processing improves it can take advantage of them.
852
853 You may want to declare your externs in three ways.
854 First, you can add externs that are valid for all your JavaScript files.
855 You should probably do this by adding them to `js2-global-externs', which
856 is a global list used for all js2-mode files.
857
858 Next, you can add a function to `js2-init-hook' that adds additional
859 externs appropriate for the specific file, perhaps based on its path.
860 These should go in `js2-additional-externs', which is buffer-local.
861
862 Third, you can use JSLint's global declaration, as long as
863 `js2-include-jslint-globals' is non-nil, which see.
864
865 Finally, you can add a function to `js2-post-parse-callbacks',
866 which is called after parsing completes, and `js2-mode-ast' is bound to
867 the root of the parse tree. At this stage you can set up an AST
868 node visitor using `js2-visit-ast' and examine the parse tree
869 for specific import patterns that may imply the existence of
870 other externs, possibly tied to your build system. These should also
871 be added to `js2-additional-externs'.
872
873 Your post-parse callback may of course also use the simpler and
874 faster (but perhaps less robust) approach of simply scanning the
875 buffer text for your imports, using regular expressions.")
876
877 ;; SKIP: decompiler
878 ;; SKIP: encoded-source
879
880 ;;; The following variables are per-function and should be saved/restored
881 ;;; during function parsing...
882
883 (js2-deflocal js2-current-script-or-fn nil)
884 (js2-deflocal js2-current-scope nil)
885 (js2-deflocal js2-nesting-of-with 0)
886 (js2-deflocal js2-label-set nil
887 "An alist mapping label names to nodes.")
888
889 (js2-deflocal js2-loop-set nil)
890 (js2-deflocal js2-loop-and-switch-set nil)
891 (js2-deflocal js2-has-return-value nil)
892 (js2-deflocal js2-end-flags 0)
893
894 ;;; ...end of per function variables
895
896 ;; These flags enumerate the possible ways a statement/function can
897 ;; terminate. These flags are used by endCheck() and by the Parser to
898 ;; detect inconsistent return usage.
899 ;;
900 ;; END_UNREACHED is reserved for code paths that are assumed to always be
901 ;; able to execute (example: throw, continue)
902 ;;
903 ;; END_DROPS_OFF indicates if the statement can transfer control to the
904 ;; next one. Statement such as return dont. A compound statement may have
905 ;; some branch that drops off control to the next statement.
906 ;;
907 ;; END_RETURNS indicates that the statement can return (without arguments)
908 ;; END_RETURNS_VALUE indicates that the statement can return a value.
909 ;;
910 ;; A compound statement such as
911 ;; if (condition) {
912 ;; return value;
913 ;; }
914 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
915
916 (defconst js2-end-unreached #x0)
917 (defconst js2-end-drops-off #x1)
918 (defconst js2-end-returns #x2)
919 (defconst js2-end-returns-value #x4)
920 (defconst js2-end-yields #x8)
921
922 ;; Rhino awkwardly passes a statementLabel parameter to the
923 ;; statementHelper() function, the main statement parser, which
924 ;; is then used by quite a few of the sub-parsers. We just make
925 ;; it a buffer-local variable and make sure it's cleaned up properly.
926 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
927
928 ;; Similarly, Rhino passes an inForInit boolean through about half
929 ;; the expression parsers. We use a dynamically-scoped variable,
930 ;; which makes it easier to funcall the parsers individually without
931 ;; worrying about whether they take the parameter or not.
932 (js2-deflocal js2-in-for-init nil)
933 (js2-deflocal js2-temp-name-counter 0)
934 (js2-deflocal js2-parse-stmt-count 0)
935
936 (defsubst js2-get-next-temp-name ()
937 (format "$%d" (incf js2-temp-name-counter)))
938
939 (defvar js2-parse-interruptable-p t
940 "Set this to nil to force parse to continue until finished.
941 This will mostly be useful for interpreters.")
942
943 (defvar js2-statements-per-pause 50
944 "Pause after this many statements to check for user input.
945 If user input is pending, stop the parse and discard the tree.
946 This makes for a smoother user experience for large files.
947 You may have to wait a second or two before the highlighting
948 and error-reporting appear, but you can always type ahead if
949 you wish. This appears to be more or less how Eclipse, IntelliJ
950 and other editors work.")
951
952 (js2-deflocal js2-record-comments t
953 "Instructs the scanner to record comments in `js2-scanned-comments'.")
954
955 (js2-deflocal js2-scanned-comments nil
956 "List of all comments from the current parse.")
957
958 (defcustom js2-mode-indent-inhibit-undo nil
959 "Non-nil to disable collection of Undo information when indenting lines.
960 Some users have requested this behavior. It's nil by default because
961 other Emacs modes don't work this way."
962 :type 'boolean
963 :group 'js2-mode)
964
965 (defcustom js2-mode-indent-ignore-first-tab nil
966 "If non-nil, ignore first TAB keypress if we look indented properly.
967 It's fairly common for users to navigate to an already-indented line
968 and press TAB for reassurance that it's been indented. For this class
969 of users, we want the first TAB press on a line to be ignored if the
970 line is already indented to one of the precomputed alternatives.
971
972 This behavior is only partly implemented. If you TAB-indent a line,
973 navigate to another line, and then navigate back, it fails to clear
974 the last-indented variable, so it thinks you've already hit TAB once,
975 and performs the indent. A full solution would involve getting on the
976 point-motion hooks for the entire buffer. If we come across another
977 use cases that requires watching point motion, I'll consider doing it.
978
979 If you set this variable to nil, then the TAB key will always change
980 the indentation of the current line, if more than one alternative
981 indentation spot exists."
982 :type 'boolean
983 :group 'js2-mode)
984
985 (defvar js2-indent-hook nil
986 "A hook for user-defined indentation rules.
987
988 Functions on this hook should expect two arguments: (LIST INDEX)
989 The LIST argument is the list of computed indentation points for
990 the current line. INDEX is the list index of the indentation point
991 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
992 indent function is not going to change the current line indentation.
993
994 If a hook function on this list returns a non-nil value, then
995 `js2-bounce-indent' assumes the hook function has performed its own
996 indentation, and will do nothing. If all hook functions on the list
997 return nil, then `js2-bounce-indent' will use its computed indentation
998 and reindent the line.
999
1000 When hook functions on this hook list are called, the variable
1001 `js2-mode-ast' may or may not be set, depending on whether the
1002 parse tree is available. If the variable is nil, you can pass a
1003 callback to `js2-mode-wait-for-parse', and your callback will be
1004 called after the new parse tree is built. This can take some time
1005 in large files.")
1006
1007 (defface js2-warning
1008 `((((class color) (background light))
1009 (:underline "orange"))
1010 (((class color) (background dark))
1011 (:underline "orange"))
1012 (t (:underline t)))
1013 "Face for JavaScript warnings."
1014 :group 'js2-mode)
1015
1016 (defface js2-error
1017 `((((class color) (background light))
1018 (:foreground "red"))
1019 (((class color) (background dark))
1020 (:foreground "red"))
1021 (t (:foreground "red")))
1022 "Face for JavaScript errors."
1023 :group 'js2-mode)
1024
1025 (defface js2-jsdoc-tag
1026 '((t :foreground "SlateGray"))
1027 "Face used to highlight @whatever tags in jsdoc comments."
1028 :group 'js2-mode)
1029
1030 (defface js2-jsdoc-type
1031 '((t :foreground "SteelBlue"))
1032 "Face used to highlight {FooBar} types in jsdoc comments."
1033 :group 'js2-mode)
1034
1035 (defface js2-jsdoc-value
1036 '((t :foreground "PeachPuff3"))
1037 "Face used to highlight tag values in jsdoc comments."
1038 :group 'js2-mode)
1039
1040 (defface js2-function-param
1041 '((t :foreground "SeaGreen"))
1042 "Face used to highlight function parameters in javascript."
1043 :group 'js2-mode)
1044
1045 (defface js2-instance-member
1046 '((t :foreground "DarkOrchid"))
1047 "Face used to highlight instance variables in javascript.
1048 Not currently used."
1049 :group 'js2-mode)
1050
1051 (defface js2-private-member
1052 '((t :foreground "PeachPuff3"))
1053 "Face used to highlight calls to private methods in javascript.
1054 Not currently used."
1055 :group 'js2-mode)
1056
1057 (defface js2-private-function-call
1058 '((t :foreground "goldenrod"))
1059 "Face used to highlight calls to private functions in javascript.
1060 Not currently used."
1061 :group 'js2-mode)
1062
1063 (defface js2-jsdoc-html-tag-name
1064 '((((class color) (min-colors 88) (background light))
1065 (:foreground "rosybrown"))
1066 (((class color) (min-colors 8) (background dark))
1067 (:foreground "yellow"))
1068 (((class color) (min-colors 8) (background light))
1069 (:foreground "magenta")))
1070 "Face used to highlight jsdoc html tag names"
1071 :group 'js2-mode)
1072
1073 (defface js2-jsdoc-html-tag-delimiter
1074 '((((class color) (min-colors 88) (background light))
1075 (:foreground "dark khaki"))
1076 (((class color) (min-colors 8) (background dark))
1077 (:foreground "green"))
1078 (((class color) (min-colors 8) (background light))
1079 (:foreground "green")))
1080 "Face used to highlight brackets in jsdoc html tags."
1081 :group 'js2-mode)
1082
1083 (defface js2-external-variable
1084 '((t :foreground "orange"))
1085 "Face used to highlight undeclared variable identifiers.")
1086
1087 (defcustom js2-init-hook nil
1088 "List of functions to be called after `js2-mode' or
1089 `js2-minor-mode' has initialized all variables, before parsing
1090 the buffer for the first time."
1091 :type 'hook
1092 :group 'js2-mode
1093 :version "20130608")
1094
1095 (defcustom js2-post-parse-callbacks nil
1096 "List of callback functions invoked after parsing finishes.
1097 Currently, the main use for this function is to add synthetic
1098 declarations to `js2-recorded-identifiers', which see."
1099 :type 'hook
1100 :group 'js2-mode)
1101
1102 (defcustom js2-highlight-external-variables t
1103 "Non-nil to highlight undeclared variable identifiers.
1104 An undeclared variable is any variable not declared with var or let
1105 in the current scope or any lexically enclosing scope. If you use
1106 such a variable, then you are either expecting it to originate from
1107 another file, or you've got a potential bug."
1108 :type 'boolean
1109 :group 'js2-mode)
1110
1111 (defcustom js2-include-jslint-globals t
1112 "Non-nil to include the identifiers from JSLint global
1113 declaration (see http://www.jslint.com/lint.html#global) in the
1114 buffer-local externs list. See `js2-additional-externs' for more
1115 information."
1116 :type 'boolean
1117 :group 'js2-mode)
1118
1119 (defvar js2-mode-map
1120 (let ((map (make-sparse-keymap))
1121 keys)
1122 (define-key map [mouse-1] #'js2-mode-show-node)
1123 (define-key map (kbd "M-j") #'js2-line-break)
1124 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1125 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1126 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1127 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1128 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1129 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1130 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1131 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1132 (when js2-bounce-indent-p
1133 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1134
1135 (define-key map [menu-bar javascript]
1136 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1137
1138 (define-key map [menu-bar javascript customize-js2-mode]
1139 '(menu-item "Customize js2-mode" js2-mode-customize
1140 :help "Customize the behavior of this mode"))
1141
1142 (define-key map [menu-bar javascript js2-force-refresh]
1143 '(menu-item "Force buffer refresh" js2-mode-reset
1144 :help "Re-parse the buffer from scratch"))
1145
1146 (define-key map [menu-bar javascript separator-2]
1147 '("--"))
1148
1149 (define-key map [menu-bar javascript next-error]
1150 '(menu-item "Next warning or error" next-error
1151 :enabled (and js2-mode-ast
1152 (or (js2-ast-root-errors js2-mode-ast)
1153 (js2-ast-root-warnings js2-mode-ast)))
1154 :help "Move to next warning or error"))
1155
1156 (define-key map [menu-bar javascript display-errors]
1157 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1158 :visible (not js2-mode-show-parse-errors)
1159 :help "Turn on display of warnings and errors"))
1160
1161 (define-key map [menu-bar javascript hide-errors]
1162 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1163 :visible js2-mode-show-parse-errors
1164 :help "Turn off display of warnings and errors"))
1165
1166 (define-key map [menu-bar javascript separator-1]
1167 '("--"))
1168
1169 (define-key map [menu-bar javascript js2-toggle-function]
1170 '(menu-item "Show/collapse element" js2-mode-toggle-element
1171 :help "Hide or show function body or comment"))
1172
1173 (define-key map [menu-bar javascript show-comments]
1174 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1175 :visible js2-mode-comments-hidden
1176 :help "Expand all hidden block comments"))
1177
1178 (define-key map [menu-bar javascript hide-comments]
1179 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1180 :visible (not js2-mode-comments-hidden)
1181 :help "Show block comments as /*...*/"))
1182
1183 (define-key map [menu-bar javascript show-all-functions]
1184 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1185 :visible js2-mode-functions-hidden
1186 :help "Expand all hidden function bodies"))
1187
1188 (define-key map [menu-bar javascript hide-all-functions]
1189 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1190 :visible (not js2-mode-functions-hidden)
1191 :help "Show {...} for all top-level function bodies"))
1192
1193 map)
1194 "Keymap used in `js2-mode' buffers.")
1195
1196 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1197
1198 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1199 "Matches a //-comment line. Must be first non-whitespace on line.
1200 First match-group is the leading whitespace.")
1201
1202 (defvar js2-mode-hook nil)
1203
1204 (js2-deflocal js2-mode-ast nil "Private variable.")
1205 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1206 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1207 (js2-deflocal js2-mode-parsing nil "Private variable.")
1208 (js2-deflocal js2-mode-node-overlay nil)
1209
1210 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1211 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1212
1213 (js2-deflocal js2-mode-fontifications nil "Private variable")
1214 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1215 (js2-deflocal js2-imenu-recorder nil "Private variable")
1216 (js2-deflocal js2-imenu-function-map nil "Private variable")
1217
1218 (defvar js2-paragraph-start
1219 "\\(@[a-zA-Z]+\\>\\|$\\)")
1220
1221 ;; Note that we also set a 'c-in-sws text property in html comments,
1222 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1223 (defvar js2-syntactic-ws-start
1224 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1225
1226 (defvar js2-syntactic-ws-end
1227 "\\s \\|[\n\r/]\\|\\s!")
1228
1229 (defvar js2-syntactic-eol
1230 (concat "\\s *\\(/\\*[^*\n\r]*"
1231 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1232 "\\*+/\\s *\\)*"
1233 "\\(//\\|/\\*[^*\n\r]*"
1234 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1235 "\\|\\\\$\\|$\\)")
1236 "Copied from `java-mode'. Needed for some cc-engine functions.")
1237
1238 (defvar js2-comment-prefix-regexp
1239 "//+\\|\\**")
1240
1241 (defvar js2-comment-start-skip
1242 "\\(//+\\|/\\*+\\)\\s *")
1243
1244 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1245 "Non-nil to emit status messages during parsing.")
1246
1247 (defvar js2-mode-functions-hidden nil "Private variable.")
1248 (defvar js2-mode-comments-hidden nil "Private variable.")
1249
1250 (defvar js2-mode-syntax-table
1251 (let ((table (make-syntax-table)))
1252 (c-populate-syntax-table table)
1253 table)
1254 "Syntax table used in `js2-mode' buffers.")
1255
1256 (defvar js2-mode-abbrev-table nil
1257 "Abbrev table in use in `js2-mode' buffers.")
1258 (define-abbrev-table 'js2-mode-abbrev-table ())
1259
1260 (defvar js2-mode-pending-parse-callbacks nil
1261 "List of functions waiting to be notified that parse is finished.")
1262
1263 (defvar js2-mode-last-indented-line -1)
1264
1265 ;;; Localizable error and warning messages
1266
1267 ;; Messages are copied from Rhino's Messages.properties.
1268 ;; Many of the Java-specific messages have been elided.
1269 ;; Add any js2-specific ones at the end, so we can keep
1270 ;; this file synced with changes to Rhino's.
1271
1272 (defvar js2-message-table
1273 (make-hash-table :test 'equal :size 250)
1274 "Contains localized messages for `js2-mode'.")
1275
1276 ;; TODO(stevey): construct this table at compile-time.
1277 (defmacro js2-msg (key &rest strings)
1278 `(puthash ,key (concat ,@strings)
1279 js2-message-table))
1280
1281 (defun js2-get-msg (msg-key)
1282 "Look up a localized message.
1283 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1284 the correct number of ARGS must be provided."
1285 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1286 (args (if (listp msg-key) (cdr msg-key)))
1287 (msg (gethash key js2-message-table)))
1288 (if msg
1289 (apply #'format msg args)
1290 key))) ; default to showing the key
1291
1292 (js2-msg "msg.dup.parms"
1293 "Duplicate parameter name '%s'.")
1294
1295 (js2-msg "msg.too.big.jump"
1296 "Program too complex: jump offset too big.")
1297
1298 (js2-msg "msg.too.big.index"
1299 "Program too complex: internal index exceeds 64K limit.")
1300
1301 (js2-msg "msg.while.compiling.fn"
1302 "Encountered code generation error while compiling function '%s': %s")
1303
1304 (js2-msg "msg.while.compiling.script"
1305 "Encountered code generation error while compiling script: %s")
1306
1307 ;; Context
1308 (js2-msg "msg.ctor.not.found"
1309 "Constructor for '%s' not found.")
1310
1311 (js2-msg "msg.not.ctor"
1312 "'%s' is not a constructor.")
1313
1314 ;; FunctionObject
1315 (js2-msg "msg.varargs.ctor"
1316 "Method or constructor '%s' must be static "
1317 "with the signature (Context cx, Object[] args, "
1318 "Function ctorObj, boolean inNewExpr) "
1319 "to define a variable arguments constructor.")
1320
1321 (js2-msg "msg.varargs.fun"
1322 "Method '%s' must be static with the signature "
1323 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1324 "to define a variable arguments function.")
1325
1326 (js2-msg "msg.incompat.call"
1327 "Method '%s' called on incompatible object.")
1328
1329 (js2-msg "msg.bad.parms"
1330 "Unsupported parameter type '%s' in method '%s'.")
1331
1332 (js2-msg "msg.bad.method.return"
1333 "Unsupported return type '%s' in method '%s'.")
1334
1335 (js2-msg "msg.bad.ctor.return"
1336 "Construction of objects of type '%s' is not supported.")
1337
1338 (js2-msg "msg.no.overload"
1339 "Method '%s' occurs multiple times in class '%s'.")
1340
1341 (js2-msg "msg.method.not.found"
1342 "Method '%s' not found in '%s'.")
1343
1344 ;; IRFactory
1345
1346 (js2-msg "msg.bad.for.in.lhs"
1347 "Invalid left-hand side of for..in loop.")
1348
1349 (js2-msg "msg.mult.index"
1350 "Only one variable allowed in for..in loop.")
1351
1352 (js2-msg "msg.bad.for.in.destruct"
1353 "Left hand side of for..in loop must be an array of "
1354 "length 2 to accept key/value pair.")
1355
1356 (js2-msg "msg.cant.convert"
1357 "Can't convert to type '%s'.")
1358
1359 (js2-msg "msg.bad.assign.left"
1360 "Invalid assignment left-hand side.")
1361
1362 (js2-msg "msg.bad.decr"
1363 "Invalid decerement operand.")
1364
1365 (js2-msg "msg.bad.incr"
1366 "Invalid increment operand.")
1367
1368 (js2-msg "msg.bad.yield"
1369 "yield must be in a function.")
1370
1371 (js2-msg "msg.yield.parenthesized"
1372 "yield expression must be parenthesized.")
1373
1374 ;; NativeGlobal
1375 (js2-msg "msg.cant.call.indirect"
1376 "Function '%s' must be called directly, and not by way of a "
1377 "function of another name.")
1378
1379 (js2-msg "msg.eval.nonstring"
1380 "Calling eval() with anything other than a primitive "
1381 "string value will simply return the value. "
1382 "Is this what you intended?")
1383
1384 (js2-msg "msg.eval.nonstring.strict"
1385 "Calling eval() with anything other than a primitive "
1386 "string value is not allowed in strict mode.")
1387
1388 (js2-msg "msg.bad.destruct.op"
1389 "Invalid destructuring assignment operator")
1390
1391 ;; NativeCall
1392 (js2-msg "msg.only.from.new"
1393 "'%s' may only be invoked from a `new' expression.")
1394
1395 (js2-msg "msg.deprec.ctor"
1396 "The '%s' constructor is deprecated.")
1397
1398 ;; NativeFunction
1399 (js2-msg "msg.no.function.ref.found"
1400 "no source found to decompile function reference %s")
1401
1402 (js2-msg "msg.arg.isnt.array"
1403 "second argument to Function.prototype.apply must be an array")
1404
1405 ;; NativeGlobal
1406 (js2-msg "msg.bad.esc.mask"
1407 "invalid string escape mask")
1408
1409 ;; NativeRegExp
1410 (js2-msg "msg.bad.quant"
1411 "Invalid quantifier %s")
1412
1413 (js2-msg "msg.overlarge.backref"
1414 "Overly large back reference %s")
1415
1416 (js2-msg "msg.overlarge.min"
1417 "Overly large minimum %s")
1418
1419 (js2-msg "msg.overlarge.max"
1420 "Overly large maximum %s")
1421
1422 (js2-msg "msg.zero.quant"
1423 "Zero quantifier %s")
1424
1425 (js2-msg "msg.max.lt.min"
1426 "Maximum %s less than minimum")
1427
1428 (js2-msg "msg.unterm.quant"
1429 "Unterminated quantifier %s")
1430
1431 (js2-msg "msg.unterm.paren"
1432 "Unterminated parenthetical %s")
1433
1434 (js2-msg "msg.unterm.class"
1435 "Unterminated character class %s")
1436
1437 (js2-msg "msg.bad.range"
1438 "Invalid range in character class.")
1439
1440 (js2-msg "msg.trail.backslash"
1441 "Trailing \\ in regular expression.")
1442
1443 (js2-msg "msg.re.unmatched.right.paren"
1444 "unmatched ) in regular expression.")
1445
1446 (js2-msg "msg.no.regexp"
1447 "Regular expressions are not available.")
1448
1449 (js2-msg "msg.bad.backref"
1450 "back-reference exceeds number of capturing parentheses.")
1451
1452 (js2-msg "msg.bad.regexp.compile"
1453 "Only one argument may be specified if the first "
1454 "argument to RegExp.prototype.compile is a RegExp object.")
1455
1456 ;; Parser
1457 (js2-msg "msg.got.syntax.errors"
1458 "Compilation produced %s syntax errors.")
1459
1460 (js2-msg "msg.var.redecl"
1461 "TypeError: redeclaration of var %s.")
1462
1463 (js2-msg "msg.const.redecl"
1464 "TypeError: redeclaration of const %s.")
1465
1466 (js2-msg "msg.let.redecl"
1467 "TypeError: redeclaration of variable %s.")
1468
1469 (js2-msg "msg.parm.redecl"
1470 "TypeError: redeclaration of formal parameter %s.")
1471
1472 (js2-msg "msg.fn.redecl"
1473 "TypeError: redeclaration of function %s.")
1474
1475 (js2-msg "msg.let.decl.not.in.block"
1476 "SyntaxError: let declaration not directly within block")
1477
1478 ;; NodeTransformer
1479 (js2-msg "msg.dup.label"
1480 "duplicated label")
1481
1482 (js2-msg "msg.undef.label"
1483 "undefined label")
1484
1485 (js2-msg "msg.bad.break"
1486 "unlabelled break must be inside loop or switch")
1487
1488 (js2-msg "msg.continue.outside"
1489 "continue must be inside loop")
1490
1491 (js2-msg "msg.continue.nonloop"
1492 "continue can only use labels of iteration statements")
1493
1494 (js2-msg "msg.bad.throw.eol"
1495 "Line terminator is not allowed between the throw "
1496 "keyword and throw expression.")
1497
1498 (js2-msg "msg.no.paren.parms"
1499 "missing ( before function parameters.")
1500
1501 (js2-msg "msg.no.parm"
1502 "missing formal parameter")
1503
1504 (js2-msg "msg.no.paren.after.parms"
1505 "missing ) after formal parameters")
1506
1507 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1508 "parameter without default follows parameter with default")
1509
1510 (js2-msg "msg.param.after.rest" ; added by js2-mode
1511 "parameter after rest parameter")
1512
1513 (js2-msg "msg.no.brace.body"
1514 "missing '{' before function body")
1515
1516 (js2-msg "msg.no.brace.after.body"
1517 "missing } after function body")
1518
1519 (js2-msg "msg.no.paren.cond"
1520 "missing ( before condition")
1521
1522 (js2-msg "msg.no.paren.after.cond"
1523 "missing ) after condition")
1524
1525 (js2-msg "msg.no.semi.stmt"
1526 "missing ; before statement")
1527
1528 (js2-msg "msg.missing.semi"
1529 "missing ; after statement")
1530
1531 (js2-msg "msg.no.name.after.dot"
1532 "missing name after . operator")
1533
1534 (js2-msg "msg.no.name.after.coloncolon"
1535 "missing name after :: operator")
1536
1537 (js2-msg "msg.no.name.after.dotdot"
1538 "missing name after .. operator")
1539
1540 (js2-msg "msg.no.name.after.xmlAttr"
1541 "missing name after .@")
1542
1543 (js2-msg "msg.no.bracket.index"
1544 "missing ] in index expression")
1545
1546 (js2-msg "msg.no.paren.switch"
1547 "missing ( before switch expression")
1548
1549 (js2-msg "msg.no.paren.after.switch"
1550 "missing ) after switch expression")
1551
1552 (js2-msg "msg.no.brace.switch"
1553 "missing '{' before switch body")
1554
1555 (js2-msg "msg.bad.switch"
1556 "invalid switch statement")
1557
1558 (js2-msg "msg.no.colon.case"
1559 "missing : after case expression")
1560
1561 (js2-msg "msg.double.switch.default"
1562 "double default label in the switch statement")
1563
1564 (js2-msg "msg.no.while.do"
1565 "missing while after do-loop body")
1566
1567 (js2-msg "msg.no.paren.for"
1568 "missing ( after for")
1569
1570 (js2-msg "msg.no.semi.for"
1571 "missing ; after for-loop initializer")
1572
1573 (js2-msg "msg.no.semi.for.cond"
1574 "missing ; after for-loop condition")
1575
1576 (js2-msg "msg.in.after.for.name"
1577 "missing in or of after for")
1578
1579 (js2-msg "msg.no.paren.for.ctrl"
1580 "missing ) after for-loop control")
1581
1582 (js2-msg "msg.no.paren.with"
1583 "missing ( before with-statement object")
1584
1585 (js2-msg "msg.no.paren.after.with"
1586 "missing ) after with-statement object")
1587
1588 (js2-msg "msg.no.paren.after.let"
1589 "missing ( after let")
1590
1591 (js2-msg "msg.no.paren.let"
1592 "missing ) after variable list")
1593
1594 (js2-msg "msg.no.curly.let"
1595 "missing } after let statement")
1596
1597 (js2-msg "msg.bad.return"
1598 "invalid return")
1599
1600 (js2-msg "msg.no.brace.block"
1601 "missing } in compound statement")
1602
1603 (js2-msg "msg.bad.label"
1604 "invalid label")
1605
1606 (js2-msg "msg.bad.var"
1607 "missing variable name")
1608
1609 (js2-msg "msg.bad.var.init"
1610 "invalid variable initialization")
1611
1612 (js2-msg "msg.no.colon.cond"
1613 "missing : in conditional expression")
1614
1615 (js2-msg "msg.no.paren.arg"
1616 "missing ) after argument list")
1617
1618 (js2-msg "msg.no.bracket.arg"
1619 "missing ] after element list")
1620
1621 (js2-msg "msg.bad.prop"
1622 "invalid property id")
1623
1624 (js2-msg "msg.no.colon.prop"
1625 "missing : after property id")
1626
1627 (js2-msg "msg.no.brace.prop"
1628 "missing } after property list")
1629
1630 (js2-msg "msg.no.paren"
1631 "missing ) in parenthetical")
1632
1633 (js2-msg "msg.reserved.id"
1634 "identifier is a reserved word")
1635
1636 (js2-msg "msg.no.paren.catch"
1637 "missing ( before catch-block condition")
1638
1639 (js2-msg "msg.bad.catchcond"
1640 "invalid catch block condition")
1641
1642 (js2-msg "msg.catch.unreachable"
1643 "any catch clauses following an unqualified catch are unreachable")
1644
1645 (js2-msg "msg.no.brace.try"
1646 "missing '{' before try block")
1647
1648 (js2-msg "msg.no.brace.catchblock"
1649 "missing '{' before catch-block body")
1650
1651 (js2-msg "msg.try.no.catchfinally"
1652 "'try' without 'catch' or 'finally'")
1653
1654 (js2-msg "msg.no.return.value"
1655 "function %s does not always return a value")
1656
1657 (js2-msg "msg.anon.no.return.value"
1658 "anonymous function does not always return a value")
1659
1660 (js2-msg "msg.return.inconsistent"
1661 "return statement is inconsistent with previous usage")
1662
1663 (js2-msg "msg.generator.returns"
1664 "TypeError: generator function '%s' returns a value")
1665
1666 (js2-msg "msg.anon.generator.returns"
1667 "TypeError: anonymous generator function returns a value")
1668
1669 (js2-msg "msg.syntax"
1670 "syntax error")
1671
1672 (js2-msg "msg.unexpected.eof"
1673 "Unexpected end of file")
1674
1675 (js2-msg "msg.XML.bad.form"
1676 "illegally formed XML syntax")
1677
1678 (js2-msg "msg.XML.not.available"
1679 "XML runtime not available")
1680
1681 (js2-msg "msg.too.deep.parser.recursion"
1682 "Too deep recursion while parsing")
1683
1684 (js2-msg "msg.no.side.effects"
1685 "Code has no side effects")
1686
1687 (js2-msg "msg.extra.trailing.comma"
1688 "Trailing comma is not supported in some browsers")
1689
1690 (js2-msg "msg.array.trailing.comma"
1691 "Trailing comma yields different behavior across browsers")
1692
1693 (js2-msg "msg.equal.as.assign"
1694 (concat "Test for equality (==) mistyped as assignment (=)?"
1695 " (parenthesize to suppress warning)"))
1696
1697 (js2-msg "msg.var.hides.arg"
1698 "Variable %s hides argument")
1699
1700 (js2-msg "msg.destruct.assign.no.init"
1701 "Missing = in destructuring declaration")
1702
1703 ;; ScriptRuntime
1704 (js2-msg "msg.no.properties"
1705 "%s has no properties.")
1706
1707 (js2-msg "msg.invalid.iterator"
1708 "Invalid iterator value")
1709
1710 (js2-msg "msg.iterator.primitive"
1711 "__iterator__ returned a primitive value")
1712
1713 (js2-msg "msg.assn.create.strict"
1714 "Assignment to undeclared variable %s")
1715
1716 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1717 "Undeclared variable or function '%s'")
1718
1719 (js2-msg "msg.ref.undefined.prop"
1720 "Reference to undefined property '%s'")
1721
1722 (js2-msg "msg.prop.not.found"
1723 "Property %s not found.")
1724
1725 (js2-msg "msg.invalid.type"
1726 "Invalid JavaScript value of type %s")
1727
1728 (js2-msg "msg.primitive.expected"
1729 "Primitive type expected (had %s instead)")
1730
1731 (js2-msg "msg.namespace.expected"
1732 "Namespace object expected to left of :: (found %s instead)")
1733
1734 (js2-msg "msg.null.to.object"
1735 "Cannot convert null to an object.")
1736
1737 (js2-msg "msg.undef.to.object"
1738 "Cannot convert undefined to an object.")
1739
1740 (js2-msg "msg.cyclic.value"
1741 "Cyclic %s value not allowed.")
1742
1743 (js2-msg "msg.is.not.defined"
1744 "'%s' is not defined.")
1745
1746 (js2-msg "msg.undef.prop.read"
1747 "Cannot read property '%s' from %s")
1748
1749 (js2-msg "msg.undef.prop.write"
1750 "Cannot set property '%s' of %s to '%s'")
1751
1752 (js2-msg "msg.undef.prop.delete"
1753 "Cannot delete property '%s' of %s")
1754
1755 (js2-msg "msg.undef.method.call"
1756 "Cannot call method '%s' of %s")
1757
1758 (js2-msg "msg.undef.with"
1759 "Cannot apply 'with' to %s")
1760
1761 (js2-msg "msg.isnt.function"
1762 "%s is not a function, it is %s.")
1763
1764 (js2-msg "msg.isnt.function.in"
1765 "Cannot call property %s in object %s. "
1766 "It is not a function, it is '%s'.")
1767
1768 (js2-msg "msg.function.not.found"
1769 "Cannot find function %s.")
1770
1771 (js2-msg "msg.function.not.found.in"
1772 "Cannot find function %s in object %s.")
1773
1774 (js2-msg "msg.isnt.xml.object"
1775 "%s is not an xml object.")
1776
1777 (js2-msg "msg.no.ref.to.get"
1778 "%s is not a reference to read reference value.")
1779
1780 (js2-msg "msg.no.ref.to.set"
1781 "%s is not a reference to set reference value to %s.")
1782
1783 (js2-msg "msg.no.ref.from.function"
1784 "Function %s can not be used as the left-hand "
1785 "side of assignment or as an operand of ++ or -- operator.")
1786
1787 (js2-msg "msg.bad.default.value"
1788 "Object's getDefaultValue() method returned an object.")
1789
1790 (js2-msg "msg.instanceof.not.object"
1791 "Can't use instanceof on a non-object.")
1792
1793 (js2-msg "msg.instanceof.bad.prototype"
1794 "'prototype' property of %s is not an object.")
1795
1796 (js2-msg "msg.bad.radix"
1797 "illegal radix %s.")
1798
1799 ;; ScriptableObject
1800 (js2-msg "msg.default.value"
1801 "Cannot find default value for object.")
1802
1803 (js2-msg "msg.zero.arg.ctor"
1804 "Cannot load class '%s' which has no zero-parameter constructor.")
1805
1806 (js2-msg "msg.ctor.multiple.parms"
1807 "Can't define constructor or class %s since more than "
1808 "one constructor has multiple parameters.")
1809
1810 (js2-msg "msg.extend.scriptable"
1811 "%s must extend ScriptableObject in order to define property %s.")
1812
1813 (js2-msg "msg.bad.getter.parms"
1814 "In order to define a property, getter %s must have zero "
1815 "parameters or a single ScriptableObject parameter.")
1816
1817 (js2-msg "msg.obj.getter.parms"
1818 "Expected static or delegated getter %s to take "
1819 "a ScriptableObject parameter.")
1820
1821 (js2-msg "msg.getter.static"
1822 "Getter and setter must both be static or neither be static.")
1823
1824 (js2-msg "msg.setter.return"
1825 "Setter must have void return type: %s")
1826
1827 (js2-msg "msg.setter2.parms"
1828 "Two-parameter setter must take a ScriptableObject as "
1829 "its first parameter.")
1830
1831 (js2-msg "msg.setter1.parms"
1832 "Expected single parameter setter for %s")
1833
1834 (js2-msg "msg.setter2.expected"
1835 "Expected static or delegated setter %s to take two parameters.")
1836
1837 (js2-msg "msg.setter.parms"
1838 "Expected either one or two parameters for setter.")
1839
1840 (js2-msg "msg.setter.bad.type"
1841 "Unsupported parameter type '%s' in setter '%s'.")
1842
1843 (js2-msg "msg.add.sealed"
1844 "Cannot add a property to a sealed object: %s.")
1845
1846 (js2-msg "msg.remove.sealed"
1847 "Cannot remove a property from a sealed object: %s.")
1848
1849 (js2-msg "msg.modify.sealed"
1850 "Cannot modify a property of a sealed object: %s.")
1851
1852 (js2-msg "msg.modify.readonly"
1853 "Cannot modify readonly property: %s.")
1854
1855 ;; TokenStream
1856 (js2-msg "msg.missing.exponent"
1857 "missing exponent")
1858
1859 (js2-msg "msg.caught.nfe"
1860 "number format error")
1861
1862 (js2-msg "msg.unterminated.string.lit"
1863 "unterminated string literal")
1864
1865 (js2-msg "msg.unterminated.comment"
1866 "unterminated comment")
1867
1868 (js2-msg "msg.unterminated.re.lit"
1869 "unterminated regular expression literal")
1870
1871 (js2-msg "msg.invalid.re.flag"
1872 "invalid flag after regular expression")
1873
1874 (js2-msg "msg.no.re.input.for"
1875 "no input for %s")
1876
1877 (js2-msg "msg.illegal.character"
1878 "illegal character")
1879
1880 (js2-msg "msg.invalid.escape"
1881 "invalid Unicode escape sequence")
1882
1883 (js2-msg "msg.bad.namespace"
1884 "not a valid default namespace statement. "
1885 "Syntax is: default xml namespace = EXPRESSION;")
1886
1887 ;; TokensStream warnings
1888 (js2-msg "msg.bad.octal.literal"
1889 "illegal octal literal digit %s; "
1890 "interpreting it as a decimal digit")
1891
1892 (js2-msg "msg.reserved.keyword"
1893 "illegal usage of future reserved keyword %s; "
1894 "interpreting it as ordinary identifier")
1895
1896 (js2-msg "msg.script.is.not.constructor"
1897 "Script objects are not constructors.")
1898
1899 ;; Arrays
1900 (js2-msg "msg.arraylength.bad"
1901 "Inappropriate array length.")
1902
1903 ;; Arrays
1904 (js2-msg "msg.arraylength.too.big"
1905 "Array length %s exceeds supported capacity limit.")
1906
1907 ;; URI
1908 (js2-msg "msg.bad.uri"
1909 "Malformed URI sequence.")
1910
1911 ;; Number
1912 (js2-msg "msg.bad.precision"
1913 "Precision %s out of range.")
1914
1915 ;; NativeGenerator
1916 (js2-msg "msg.send.newborn"
1917 "Attempt to send value to newborn generator")
1918
1919 (js2-msg "msg.already.exec.gen"
1920 "Already executing generator")
1921
1922 (js2-msg "msg.StopIteration.invalid"
1923 "StopIteration may not be changed to an arbitrary object.")
1924
1925 ;; Interpreter
1926 (js2-msg "msg.yield.closing"
1927 "Yield from closing generator")
1928
1929 ;;; Tokens Buffer
1930
1931 (defconst js2-ti-max-lookahead 2)
1932 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1933
1934 ;; Have to call `js2-init-scanner' to initialize the values.
1935 (js2-deflocal js2-ti-tokens nil)
1936 (js2-deflocal js2-ti-tokens-cursor nil)
1937 (js2-deflocal js2-ti-lookahead nil)
1938
1939 (defun js2-new-token (offset)
1940 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
1941 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
1942 (aset js2-ti-tokens js2-ti-tokens-cursor token)
1943 token))
1944
1945 (defsubst js2-current-token ()
1946 (aref js2-ti-tokens js2-ti-tokens-cursor))
1947
1948 (defsubst js2-current-token-string ()
1949 (js2-token-string (js2-current-token)))
1950
1951 (defsubst js2-current-token-type ()
1952 (js2-token-type (js2-current-token)))
1953
1954 (defsubst js2-current-token-beg ()
1955 (js2-token-beg (js2-current-token)))
1956
1957 (defsubst js2-current-token-end ()
1958 (js2-token-end (js2-current-token)))
1959
1960 (defun js2-current-token-len ()
1961 (let ((token (js2-current-token)))
1962 (- (js2-token-end token)
1963 (js2-token-beg token))))
1964
1965 (defun js2-ts-set-state (state)
1966 (setq js2-ts-lineno (js2-ts-state-lineno state)
1967 js2-ts-cursor (js2-ts-state-cursor state)
1968 js2-ti-tokens (js2-ts-state-tokens state)
1969 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
1970 js2-ti-lookahead (js2-ts-state-lookahead state)))
1971
1972 ;;; Utilities
1973
1974 (defun js2-delete-if (predicate list)
1975 "Remove all items satisfying PREDICATE in LIST."
1976 (loop for item in list
1977 if (not (funcall predicate item))
1978 collect item))
1979
1980 (defun js2-position (element list)
1981 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1982 Returns nil if element is not found in the list."
1983 (let ((count 0)
1984 found)
1985 (while (and list (not found))
1986 (if (eq element (car list))
1987 (setq found t)
1988 (setq count (1+ count)
1989 list (cdr list))))
1990 (if found count)))
1991
1992 (defun js2-find-if (predicate list)
1993 "Find first item satisfying PREDICATE in LIST."
1994 (let (result)
1995 (while (and list (not result))
1996 (if (funcall predicate (car list))
1997 (setq result (car list)))
1998 (setq list (cdr list)))
1999 result))
2000
2001 (defmacro js2-time (form)
2002 "Evaluate FORM, discard result, and return elapsed time in sec."
2003 (declare (debug t))
2004 (let ((beg (make-symbol "--js2-time-beg--"))
2005 (delta (make-symbol "--js2-time-end--")))
2006 `(let ((,beg (current-time))
2007 ,delta)
2008 ,form
2009 (/ (truncate (* (- (float-time (current-time))
2010 (float-time ,beg))
2011 10000))
2012 10000.0))))
2013
2014 (defsubst js2-same-line (pos)
2015 "Return t if POS is on the same line as current point."
2016 (and (>= pos (point-at-bol))
2017 (<= pos (point-at-eol))))
2018
2019 (defun js2-code-bug ()
2020 "Signal an error when we encounter an unexpected code path."
2021 (error "failed assertion"))
2022
2023 (defsubst js2-record-text-property (beg end prop value)
2024 "Record a text property to set when parsing finishes."
2025 (push (list beg end prop value) js2-mode-deferred-properties))
2026
2027 ;; I'd like to associate errors with nodes, but for now the
2028 ;; easiest thing to do is get the context info from the last token.
2029 (defun js2-record-parse-error (msg &optional arg pos len)
2030 (push (list (list msg arg)
2031 (or pos (js2-current-token-beg))
2032 (or len (js2-current-token-len)))
2033 js2-parsed-errors))
2034
2035 (defun js2-report-error (msg &optional msg-arg pos len)
2036 "Signal a syntax error or record a parse error."
2037 (if js2-recover-from-parse-errors
2038 (js2-record-parse-error msg msg-arg pos len)
2039 (signal 'js2-syntax-error
2040 (list msg
2041 js2-ts-lineno
2042 (save-excursion
2043 (goto-char js2-ts-cursor)
2044 (current-column))
2045 js2-ts-hit-eof))))
2046
2047 (defun js2-report-warning (msg &optional msg-arg pos len face)
2048 (if js2-compiler-report-warning-as-error
2049 (js2-report-error msg msg-arg pos len)
2050 (push (list (list msg msg-arg)
2051 (or pos (js2-current-token-beg))
2052 (or len (js2-current-token-len))
2053 face)
2054 js2-parsed-warnings)))
2055
2056 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2057 (if js2-compiler-strict-mode
2058 (js2-report-warning msg-id msg-arg beg
2059 (and beg end (- end beg)))))
2060
2061 (put 'js2-syntax-error 'error-conditions
2062 '(error syntax-error js2-syntax-error))
2063 (put 'js2-syntax-error 'error-message "Syntax error")
2064
2065 (put 'js2-parse-error 'error-conditions
2066 '(error parse-error js2-parse-error))
2067 (put 'js2-parse-error 'error-message "Parse error")
2068
2069 (defmacro js2-clear-flag (flags flag)
2070 `(setq ,flags (logand ,flags (lognot ,flag))))
2071
2072 (defmacro js2-set-flag (flags flag)
2073 "Logical-or FLAG into FLAGS."
2074 `(setq ,flags (logior ,flags ,flag)))
2075
2076 (defsubst js2-flag-set-p (flags flag)
2077 (/= 0 (logand flags flag)))
2078
2079 (defsubst js2-flag-not-set-p (flags flag)
2080 (zerop (logand flags flag)))
2081
2082 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2083 "Evaluate BODY with the _ character set to be word-syntax."
2084 (declare (indent 0) (debug t))
2085 (let ((old-syntax (make-symbol "old-syntax")))
2086 `(let ((,old-syntax (string (char-syntax ?_))))
2087 (unwind-protect
2088 (progn
2089 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2090 ,@body)
2091 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2092
2093 (defsubst js2-char-uppercase-p (c)
2094 "Return t if C is an uppercase character.
2095 Handles unicode and latin chars properly."
2096 (/= c (downcase c)))
2097
2098 (defsubst js2-char-lowercase-p (c)
2099 "Return t if C is an uppercase character.
2100 Handles unicode and latin chars properly."
2101 (/= c (upcase c)))
2102
2103 ;;; AST struct and function definitions
2104
2105 ;; flags for ast node property 'member-type (used for e4x operators)
2106 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2107 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2108 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2109
2110 (defsubst js2-relpos (pos anchor)
2111 "Convert POS to be relative to ANCHOR.
2112 If POS is nil, returns nil."
2113 (and pos (- pos anchor)))
2114
2115 (defun js2-make-pad (indent)
2116 (if (zerop indent)
2117 ""
2118 (make-string (* indent js2-basic-offset) ? )))
2119
2120 (defun js2-visit-ast (node callback)
2121 "Visit every node in ast NODE with visitor CALLBACK.
2122
2123 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2124 called twice: once to visit the node, and again after all the node's
2125 children have been processed. The END-P argument is nil on the first
2126 call and non-nil on the second call. The return value of the callback
2127 affects the traversal: if non-nil, the children of NODE are processed.
2128 If the callback returns nil, or if the node has no children, then the
2129 callback is called immediately with a non-nil END-P argument.
2130
2131 The node traversal is approximately lexical-order, although there
2132 are currently no guarantees around this."
2133 (when node
2134 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2135 ;; visit the node
2136 (when (funcall callback node nil)
2137 ;; visit the kids
2138 (cond
2139 ((eq vfunc 'js2-visit-none)
2140 nil) ; don't even bother calling it
2141 ;; Each AST node type has to define a `js2-visitor' function
2142 ;; that takes a node and a callback, and calls `js2-visit-ast'
2143 ;; on each child of the node.
2144 (vfunc
2145 (funcall vfunc node callback))
2146 (t
2147 (error "%s does not define a visitor-traversal function"
2148 (aref node 0)))))
2149 ;; call the end-visit
2150 (funcall callback node t))))
2151
2152 (defstruct (js2-node
2153 (:constructor nil)) ; abstract
2154 "Base AST node type."
2155 (type -1) ; token type
2156 (pos -1) ; start position of this AST node in parsed input
2157 (len 1) ; num characters spanned by the node
2158 props ; optional node property list (an alist)
2159 parent) ; link to parent node; null for root
2160
2161 (defsubst js2-node-get-prop (node prop &optional default)
2162 (or (cadr (assoc prop (js2-node-props node))) default))
2163
2164 (defsubst js2-node-set-prop (node prop value)
2165 (setf (js2-node-props node)
2166 (cons (list prop value) (js2-node-props node))))
2167
2168 (defun js2-fixup-starts (n nodes)
2169 "Adjust the start positions of NODES to be relative to N.
2170 Any node in the list may be nil, for convenience."
2171 (dolist (node nodes)
2172 (when node
2173 (setf (js2-node-pos node) (- (js2-node-pos node)
2174 (js2-node-pos n))))))
2175
2176 (defun js2-node-add-children (parent &rest nodes)
2177 "Set parent node of NODES to PARENT, and return PARENT.
2178 Does nothing if we're not recording parent links.
2179 If any given node in NODES is nil, doesn't record that link."
2180 (js2-fixup-starts parent nodes)
2181 (dolist (node nodes)
2182 (and node
2183 (setf (js2-node-parent node) parent))))
2184
2185 ;; Non-recursive since it's called a frightening number of times.
2186 (defun js2-node-abs-pos (n)
2187 (let ((pos (js2-node-pos n)))
2188 (while (setq n (js2-node-parent n))
2189 (setq pos (+ pos (js2-node-pos n))))
2190 pos))
2191
2192 (defsubst js2-node-abs-end (n)
2193 "Return absolute buffer position of end of N."
2194 (+ (js2-node-abs-pos n) (js2-node-len n)))
2195
2196 ;; It's important to make sure block nodes have a Lisp list for the
2197 ;; child nodes, to limit printing recursion depth in an AST that
2198 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2199 ;; a sufficiently large vector tree.
2200
2201 (defstruct (js2-block-node
2202 (:include js2-node)
2203 (:constructor nil)
2204 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2205 (pos (js2-current-token-beg))
2206 len
2207 props
2208 kids)))
2209 "A block of statements."
2210 kids) ; a Lisp list of the child statement nodes
2211
2212 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2213 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2214
2215 (defun js2-visit-block (ast callback)
2216 "Visit the `js2-block-node' children of AST."
2217 (dolist (kid (js2-block-node-kids ast))
2218 (js2-visit-ast kid callback)))
2219
2220 (defun js2-print-block (n i)
2221 (let ((pad (js2-make-pad i)))
2222 (insert pad "{\n")
2223 (dolist (kid (js2-block-node-kids n))
2224 (js2-print-ast kid (1+ i)))
2225 (insert pad "}")))
2226
2227 (defstruct (js2-scope
2228 (:include js2-block-node)
2229 (:constructor nil)
2230 (:constructor make-js2-scope (&key (type js2-BLOCK)
2231 (pos (js2-current-token-beg))
2232 len
2233 kids)))
2234 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2235 ;; I don't have one of those handy, so I'll use an alist for now.
2236 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2237 ;; and is much lighter-weight to construct (both CPU and mem).
2238 ;; The keys are interned strings (symbols) for faster lookup.
2239 ;; Should switch to hybrid alist/hashtable eventually.
2240 symbol-table ; an alist of (symbol . js2-symbol)
2241 parent-scope ; a `js2-scope'
2242 top) ; top-level `js2-scope' (script/function)
2243
2244 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2245 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2246
2247 (defun js2-node-get-enclosing-scope (node)
2248 "Return the innermost `js2-scope' node surrounding NODE.
2249 Returns nil if there is no enclosing scope node."
2250 (let ((parent (js2-node-parent node)))
2251 (while (not (js2-scope-p parent))
2252 (setq parent (js2-node-parent parent)))
2253 parent))
2254
2255 (defun js2-get-defining-scope (scope name)
2256 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2257 Returns `js2-scope' in which NAME is defined, or nil if not found."
2258 (let ((sym (if (symbolp name)
2259 name
2260 (intern name)))
2261 table
2262 result
2263 (continue t))
2264 (while (and scope continue)
2265 (if (and (setq table (js2-scope-symbol-table scope))
2266 (assq sym table))
2267 (setq continue nil
2268 result scope)
2269 (setq scope (js2-scope-parent-scope scope))))
2270 result))
2271
2272 (defun js2-scope-get-symbol (scope name)
2273 "Return symbol table entry for NAME in SCOPE.
2274 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2275 (and (js2-scope-symbol-table scope)
2276 (cdr (assq (if (symbolp name)
2277 name
2278 (intern name))
2279 (js2-scope-symbol-table scope)))))
2280
2281 (defun js2-scope-put-symbol (scope name symbol)
2282 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2283 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2284 (let* ((table (js2-scope-symbol-table scope))
2285 (sym (if (symbolp name) name (intern name)))
2286 (entry (assq sym table)))
2287 (if entry
2288 (setcdr entry symbol)
2289 (push (cons sym symbol)
2290 (js2-scope-symbol-table scope)))))
2291
2292 (defstruct (js2-symbol
2293 (:constructor nil)
2294 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2295 "A symbol table entry."
2296 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2297 ;; js2-LET, or js2-CONST
2298 decl-type
2299 name ; string
2300 ast-node) ; a `js2-node'
2301
2302 (defstruct (js2-error-node
2303 (:include js2-node)
2304 (:constructor nil) ; silence emacs21 byte-compiler
2305 (:constructor make-js2-error-node (&key (type js2-ERROR)
2306 (pos (js2-current-token-beg))
2307 len)))
2308 "AST node representing a parse error.")
2309
2310 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2311 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2312
2313 (defstruct (js2-script-node
2314 (:include js2-scope)
2315 (:constructor nil)
2316 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2317 (pos (js2-current-token-beg))
2318 len
2319 var-decls
2320 fun-decls)))
2321 functions ; Lisp list of nested functions
2322 regexps ; Lisp list of (string . flags)
2323 symbols ; alist (every symbol gets unique index)
2324 (param-count 0)
2325 var-names ; vector of string names
2326 consts ; bool-vector matching var-decls
2327 (temp-number 0)) ; for generating temp variables
2328
2329 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2330 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2331
2332 (defun js2-print-script (node indent)
2333 (dolist (kid (js2-block-node-kids node))
2334 (js2-print-ast kid indent)))
2335
2336 (defstruct (js2-ast-root
2337 (:include js2-script-node)
2338 (:constructor nil)
2339 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2340 (pos (js2-current-token-beg))
2341 len
2342 buffer)))
2343 "The root node of a js2 AST."
2344 buffer ; the source buffer from which the code was parsed
2345 comments ; a Lisp list of comments, ordered by start position
2346 errors ; a Lisp list of errors found during parsing
2347 warnings ; a Lisp list of warnings found during parsing
2348 node-count) ; number of nodes in the tree, including the root
2349
2350 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2351 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2352
2353 (defun js2-visit-ast-root (ast callback)
2354 (dolist (kid (js2-ast-root-kids ast))
2355 (js2-visit-ast kid callback))
2356 (dolist (comment (js2-ast-root-comments ast))
2357 (js2-visit-ast comment callback)))
2358
2359 (defstruct (js2-comment-node
2360 (:include js2-node)
2361 (:constructor nil)
2362 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2363 (pos (js2-current-token-beg))
2364 len
2365 format)))
2366 format) ; 'line, 'block, 'jsdoc or 'html
2367
2368 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2369 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2370
2371 (defun js2-print-comment (n i)
2372 ;; We really ought to link end-of-line comments to their nodes.
2373 ;; Or maybe we could add a new comment type, 'endline.
2374 (insert (js2-make-pad i)
2375 (js2-node-string n)))
2376
2377 (defstruct (js2-expr-stmt-node
2378 (:include js2-node)
2379 (:constructor nil)
2380 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2381 (pos js2-ts-cursor)
2382 len
2383 expr)))
2384 "An expression statement."
2385 expr)
2386
2387 (defsubst js2-expr-stmt-node-set-has-result (node)
2388 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2389 (setf (js2-node-type node) js2-EXPR_RESULT))
2390
2391 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2392 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2393
2394 (defun js2-visit-expr-stmt-node (n v)
2395 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2396
2397 (defun js2-print-expr-stmt-node (n indent)
2398 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2399 (insert ";\n"))
2400
2401 (defstruct (js2-loop-node
2402 (:include js2-scope)
2403 (:constructor nil))
2404 "Abstract supertype of loop nodes."
2405 body ; a `js2-block-node'
2406 lp ; position of left-paren, nil if omitted
2407 rp) ; position of right-paren, nil if omitted
2408
2409 (defstruct (js2-do-node
2410 (:include js2-loop-node)
2411 (:constructor nil)
2412 (:constructor make-js2-do-node (&key (type js2-DO)
2413 (pos (js2-current-token-beg))
2414 len
2415 body
2416 condition
2417 while-pos
2418 lp
2419 rp)))
2420 "AST node for do-loop."
2421 condition ; while (expression)
2422 while-pos) ; buffer position of 'while' keyword
2423
2424 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2425 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2426
2427 (defun js2-visit-do-node (n v)
2428 (js2-visit-ast (js2-do-node-body n) v)
2429 (js2-visit-ast (js2-do-node-condition n) v))
2430
2431 (defun js2-print-do-node (n i)
2432 (let ((pad (js2-make-pad i)))
2433 (insert pad "do {\n")
2434 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2435 (js2-print-ast kid (1+ i)))
2436 (insert pad "} while (")
2437 (js2-print-ast (js2-do-node-condition n) 0)
2438 (insert ");\n")))
2439
2440 (defstruct (js2-while-node
2441 (:include js2-loop-node)
2442 (:constructor nil)
2443 (:constructor make-js2-while-node (&key (type js2-WHILE)
2444 (pos (js2-current-token-beg))
2445 len body
2446 condition lp
2447 rp)))
2448 "AST node for while-loop."
2449 condition) ; while-condition
2450
2451 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2452 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2453
2454 (defun js2-visit-while-node (n v)
2455 (js2-visit-ast (js2-while-node-condition n) v)
2456 (js2-visit-ast (js2-while-node-body n) v))
2457
2458 (defun js2-print-while-node (n i)
2459 (let ((pad (js2-make-pad i)))
2460 (insert pad "while (")
2461 (js2-print-ast (js2-while-node-condition n) 0)
2462 (insert ") {\n")
2463 (js2-print-body (js2-while-node-body n) (1+ i))
2464 (insert pad "}\n")))
2465
2466 (defstruct (js2-for-node
2467 (:include js2-loop-node)
2468 (:constructor nil)
2469 (:constructor make-js2-for-node (&key (type js2-FOR)
2470 (pos js2-ts-cursor)
2471 len body init
2472 condition
2473 update lp rp)))
2474 "AST node for a C-style for-loop."
2475 init ; initialization expression
2476 condition ; loop condition
2477 update) ; update clause
2478
2479 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2480 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2481
2482 (defun js2-visit-for-node (n v)
2483 (js2-visit-ast (js2-for-node-init n) v)
2484 (js2-visit-ast (js2-for-node-condition n) v)
2485 (js2-visit-ast (js2-for-node-update n) v)
2486 (js2-visit-ast (js2-for-node-body n) v))
2487
2488 (defun js2-print-for-node (n i)
2489 (let ((pad (js2-make-pad i)))
2490 (insert pad "for (")
2491 (js2-print-ast (js2-for-node-init n) 0)
2492 (insert "; ")
2493 (js2-print-ast (js2-for-node-condition n) 0)
2494 (insert "; ")
2495 (js2-print-ast (js2-for-node-update n) 0)
2496 (insert ") {\n")
2497 (js2-print-body (js2-for-node-body n) (1+ i))
2498 (insert pad "}\n")))
2499
2500 (defstruct (js2-for-in-node
2501 (:include js2-loop-node)
2502 (:constructor nil)
2503 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2504 (pos js2-ts-cursor)
2505 len body
2506 iterator
2507 object
2508 in-pos
2509 each-pos
2510 foreach-p forof-p
2511 lp rp)))
2512 "AST node for a for..in loop."
2513 iterator ; [var] foo in ...
2514 object ; object over which we're iterating
2515 in-pos ; buffer position of 'in' keyword
2516 each-pos ; buffer position of 'each' keyword, if foreach-p
2517 foreach-p ; t if it's a for-each loop
2518 forof-p) ; t if it's a for-of loop
2519
2520 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2521 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2522
2523 (defun js2-visit-for-in-node (n v)
2524 (js2-visit-ast (js2-for-in-node-iterator n) v)
2525 (js2-visit-ast (js2-for-in-node-object n) v)
2526 (js2-visit-ast (js2-for-in-node-body n) v))
2527
2528 (defun js2-print-for-in-node (n i)
2529 (let ((pad (js2-make-pad i))
2530 (foreach (js2-for-in-node-foreach-p n))
2531 (forof (js2-for-in-node-forof-p n)))
2532 (insert pad "for ")
2533 (if foreach
2534 (insert "each "))
2535 (insert "(")
2536 (js2-print-ast (js2-for-in-node-iterator n) 0)
2537 (if forof
2538 (insert " of ")
2539 (insert " in "))
2540 (js2-print-ast (js2-for-in-node-object n) 0)
2541 (insert ") {\n")
2542 (js2-print-body (js2-for-in-node-body n) (1+ i))
2543 (insert pad "}\n")))
2544
2545 (defstruct (js2-return-node
2546 (:include js2-node)
2547 (:constructor nil)
2548 (:constructor make-js2-return-node (&key (type js2-RETURN)
2549 (pos js2-ts-cursor)
2550 len
2551 retval)))
2552 "AST node for a return statement."
2553 retval) ; expression to return, or 'undefined
2554
2555 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2556 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2557
2558 (defun js2-visit-return-node (n v)
2559 (js2-visit-ast (js2-return-node-retval n) v))
2560
2561 (defun js2-print-return-node (n i)
2562 (insert (js2-make-pad i) "return")
2563 (when (js2-return-node-retval n)
2564 (insert " ")
2565 (js2-print-ast (js2-return-node-retval n) 0))
2566 (insert ";\n"))
2567
2568 (defstruct (js2-if-node
2569 (:include js2-node)
2570 (:constructor nil)
2571 (:constructor make-js2-if-node (&key (type js2-IF)
2572 (pos js2-ts-cursor)
2573 len condition
2574 then-part
2575 else-pos
2576 else-part lp
2577 rp)))
2578 "AST node for an if-statement."
2579 condition ; expression
2580 then-part ; statement or block
2581 else-pos ; optional buffer position of 'else' keyword
2582 else-part ; optional statement or block
2583 lp ; position of left-paren, nil if omitted
2584 rp) ; position of right-paren, nil if omitted
2585
2586 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2587 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2588
2589 (defun js2-visit-if-node (n v)
2590 (js2-visit-ast (js2-if-node-condition n) v)
2591 (js2-visit-ast (js2-if-node-then-part n) v)
2592 (js2-visit-ast (js2-if-node-else-part n) v))
2593
2594 (defun js2-print-if-node (n i)
2595 (let ((pad (js2-make-pad i))
2596 (then-part (js2-if-node-then-part n))
2597 (else-part (js2-if-node-else-part n)))
2598 (insert pad "if (")
2599 (js2-print-ast (js2-if-node-condition n) 0)
2600 (insert ") {\n")
2601 (js2-print-body then-part (1+ i))
2602 (insert pad "}")
2603 (cond
2604 ((not else-part)
2605 (insert "\n"))
2606 ((js2-if-node-p else-part)
2607 (insert " else ")
2608 (js2-print-body else-part i))
2609 (t
2610 (insert " else {\n")
2611 (js2-print-body else-part (1+ i))
2612 (insert pad "}\n")))))
2613
2614 (defstruct (js2-try-node
2615 (:include js2-node)
2616 (:constructor nil)
2617 (:constructor make-js2-try-node (&key (type js2-TRY)
2618 (pos js2-ts-cursor)
2619 len
2620 try-block
2621 catch-clauses
2622 finally-block)))
2623 "AST node for a try-statement."
2624 try-block
2625 catch-clauses ; a Lisp list of `js2-catch-node'
2626 finally-block) ; a `js2-finally-node'
2627
2628 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2629 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2630
2631 (defun js2-visit-try-node (n v)
2632 (js2-visit-ast (js2-try-node-try-block n) v)
2633 (dolist (clause (js2-try-node-catch-clauses n))
2634 (js2-visit-ast clause v))
2635 (js2-visit-ast (js2-try-node-finally-block n) v))
2636
2637 (defun js2-print-try-node (n i)
2638 (let ((pad (js2-make-pad i))
2639 (catches (js2-try-node-catch-clauses n))
2640 (finally (js2-try-node-finally-block n)))
2641 (insert pad "try {\n")
2642 (js2-print-body (js2-try-node-try-block n) (1+ i))
2643 (insert pad "}")
2644 (when catches
2645 (dolist (catch catches)
2646 (js2-print-ast catch i)))
2647 (if finally
2648 (js2-print-ast finally i)
2649 (insert "\n"))))
2650
2651 (defstruct (js2-catch-node
2652 (:include js2-node)
2653 (:constructor nil)
2654 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2655 (pos js2-ts-cursor)
2656 len
2657 param
2658 guard-kwd
2659 guard-expr
2660 block lp
2661 rp)))
2662 "AST node for a catch clause."
2663 param ; destructuring form or simple name node
2664 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2665 guard-expr ; catch condition, a `js2-node'
2666 block ; statements, a `js2-block-node'
2667 lp ; buffer position of left-paren, nil if omitted
2668 rp) ; buffer position of right-paren, nil if omitted
2669
2670 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2671 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2672
2673 (defun js2-visit-catch-node (n v)
2674 (js2-visit-ast (js2-catch-node-param n) v)
2675 (when (js2-catch-node-guard-kwd n)
2676 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2677 (js2-visit-ast (js2-catch-node-block n) v))
2678
2679 (defun js2-print-catch-node (n i)
2680 (let ((pad (js2-make-pad i))
2681 (guard-kwd (js2-catch-node-guard-kwd n))
2682 (guard-expr (js2-catch-node-guard-expr n)))
2683 (insert " catch (")
2684 (js2-print-ast (js2-catch-node-param n) 0)
2685 (when guard-kwd
2686 (insert " if ")
2687 (js2-print-ast guard-expr 0))
2688 (insert ") {\n")
2689 (js2-print-body (js2-catch-node-block n) (1+ i))
2690 (insert pad "}")))
2691
2692 (defstruct (js2-finally-node
2693 (:include js2-node)
2694 (:constructor nil)
2695 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2696 (pos js2-ts-cursor)
2697 len body)))
2698 "AST node for a finally clause."
2699 body) ; a `js2-node', often but not always a block node
2700
2701 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2702 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2703
2704 (defun js2-visit-finally-node (n v)
2705 (js2-visit-ast (js2-finally-node-body n) v))
2706
2707 (defun js2-print-finally-node (n i)
2708 (let ((pad (js2-make-pad i)))
2709 (insert " finally {\n")
2710 (js2-print-body (js2-finally-node-body n) (1+ i))
2711 (insert pad "}\n")))
2712
2713 (defstruct (js2-switch-node
2714 (:include js2-node)
2715 (:constructor nil)
2716 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2717 (pos js2-ts-cursor)
2718 len
2719 discriminant
2720 cases lp
2721 rp)))
2722 "AST node for a switch statement."
2723 discriminant ; a `js2-node' (switch expression)
2724 cases ; a Lisp list of `js2-case-node'
2725 lp ; position of open-paren for discriminant, nil if omitted
2726 rp) ; position of close-paren for discriminant, nil if omitted
2727
2728 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2729 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2730
2731 (defun js2-visit-switch-node (n v)
2732 (js2-visit-ast (js2-switch-node-discriminant n) v)
2733 (dolist (c (js2-switch-node-cases n))
2734 (js2-visit-ast c v)))
2735
2736 (defun js2-print-switch-node (n i)
2737 (let ((pad (js2-make-pad i))
2738 (cases (js2-switch-node-cases n)))
2739 (insert pad "switch (")
2740 (js2-print-ast (js2-switch-node-discriminant n) 0)
2741 (insert ") {\n")
2742 (dolist (case cases)
2743 (js2-print-ast case i))
2744 (insert pad "}\n")))
2745
2746 (defstruct (js2-case-node
2747 (:include js2-block-node)
2748 (:constructor nil)
2749 (:constructor make-js2-case-node (&key (type js2-CASE)
2750 (pos js2-ts-cursor)
2751 len kids expr)))
2752 "AST node for a case clause of a switch statement."
2753 expr) ; the case expression (nil for default)
2754
2755 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2756 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2757
2758 (defun js2-visit-case-node (n v)
2759 (js2-visit-ast (js2-case-node-expr n) v)
2760 (js2-visit-block n v))
2761
2762 (defun js2-print-case-node (n i)
2763 (let ((pad (js2-make-pad i))
2764 (expr (js2-case-node-expr n)))
2765 (insert pad)
2766 (if (null expr)
2767 (insert "default:\n")
2768 (insert "case ")
2769 (js2-print-ast expr 0)
2770 (insert ":\n"))
2771 (dolist (kid (js2-case-node-kids n))
2772 (js2-print-ast kid (1+ i)))))
2773
2774 (defstruct (js2-throw-node
2775 (:include js2-node)
2776 (:constructor nil)
2777 (:constructor make-js2-throw-node (&key (type js2-THROW)
2778 (pos js2-ts-cursor)
2779 len expr)))
2780 "AST node for a throw statement."
2781 expr) ; the expression to throw
2782
2783 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2784 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2785
2786 (defun js2-visit-throw-node (n v)
2787 (js2-visit-ast (js2-throw-node-expr n) v))
2788
2789 (defun js2-print-throw-node (n i)
2790 (insert (js2-make-pad i) "throw ")
2791 (js2-print-ast (js2-throw-node-expr n) 0)
2792 (insert ";\n"))
2793
2794 (defstruct (js2-with-node
2795 (:include js2-node)
2796 (:constructor nil)
2797 (:constructor make-js2-with-node (&key (type js2-WITH)
2798 (pos js2-ts-cursor)
2799 len object
2800 body lp rp)))
2801 "AST node for a with-statement."
2802 object
2803 body
2804 lp ; buffer position of left-paren around object, nil if omitted
2805 rp) ; buffer position of right-paren around object, nil if omitted
2806
2807 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2808 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2809
2810 (defun js2-visit-with-node (n v)
2811 (js2-visit-ast (js2-with-node-object n) v)
2812 (js2-visit-ast (js2-with-node-body n) v))
2813
2814 (defun js2-print-with-node (n i)
2815 (let ((pad (js2-make-pad i)))
2816 (insert pad "with (")
2817 (js2-print-ast (js2-with-node-object n) 0)
2818 (insert ") {\n")
2819 (js2-print-body (js2-with-node-body n) (1+ i))
2820 (insert pad "}\n")))
2821
2822 (defstruct (js2-label-node
2823 (:include js2-node)
2824 (:constructor nil)
2825 (:constructor make-js2-label-node (&key (type js2-LABEL)
2826 (pos js2-ts-cursor)
2827 len name)))
2828 "AST node for a statement label or case label."
2829 name ; a string
2830 loop) ; for validating and code-generating continue-to-label
2831
2832 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2833 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2834
2835 (defun js2-print-label (n i)
2836 (insert (js2-make-pad i)
2837 (js2-label-node-name n)
2838 ":\n"))
2839
2840 (defstruct (js2-labeled-stmt-node
2841 (:include js2-node)
2842 (:constructor nil)
2843 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2844 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2845 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2846 (pos js2-ts-cursor)
2847 len labels stmt)))
2848 "AST node for a statement with one or more labels.
2849 Multiple labels for a statement are collapsed into the labels field."
2850 labels ; Lisp list of `js2-label-node'
2851 stmt) ; the statement these labels are for
2852
2853 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2854 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2855
2856 (defun js2-get-label-by-name (lbl-stmt name)
2857 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2858 Returns nil if no such label is in the list."
2859 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2860 result)
2861 (while (and label-list (not result))
2862 (if (string= (js2-label-node-name (car label-list)) name)
2863 (setq result (car label-list))
2864 (setq label-list (cdr label-list))))
2865 result))
2866
2867 (defun js2-visit-labeled-stmt (n v)
2868 (dolist (label (js2-labeled-stmt-node-labels n))
2869 (js2-visit-ast label v))
2870 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2871
2872 (defun js2-print-labeled-stmt (n i)
2873 (dolist (label (js2-labeled-stmt-node-labels n))
2874 (js2-print-ast label i))
2875 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2876
2877 (defun js2-labeled-stmt-node-contains (node label)
2878 "Return t if NODE contains LABEL in its label set.
2879 NODE is a `js2-labels-node'. LABEL is an identifier."
2880 (loop for nl in (js2-labeled-stmt-node-labels node)
2881 if (string= label (js2-label-node-name nl))
2882 return t
2883 finally return nil))
2884
2885 (defsubst js2-labeled-stmt-node-add-label (node label)
2886 "Add a `js2-label-node' to the label set for this statement."
2887 (setf (js2-labeled-stmt-node-labels node)
2888 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2889
2890 (defstruct (js2-jump-node
2891 (:include js2-node)
2892 (:constructor nil))
2893 "Abstract supertype of break and continue nodes."
2894 label ; `js2-name-node' for location of label identifier, if present
2895 target) ; target js2-labels-node or loop/switch statement
2896
2897 (defun js2-visit-jump-node (n v)
2898 ;; We don't visit the target, since it's a back-link.
2899 (js2-visit-ast (js2-jump-node-label n) v))
2900
2901 (defstruct (js2-break-node
2902 (:include js2-jump-node)
2903 (:constructor nil)
2904 (:constructor make-js2-break-node (&key (type js2-BREAK)
2905 (pos js2-ts-cursor)
2906 len label target)))
2907 "AST node for a break statement.
2908 The label field is a `js2-name-node', possibly nil, for the named label
2909 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2910 is the target of the break - a label node or enclosing loop/switch statement.")
2911
2912 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2913 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2914
2915 (defun js2-print-break-node (n i)
2916 (insert (js2-make-pad i) "break")
2917 (when (js2-break-node-label n)
2918 (insert " ")
2919 (js2-print-ast (js2-break-node-label n) 0))
2920 (insert ";\n"))
2921
2922 (defstruct (js2-continue-node
2923 (:include js2-jump-node)
2924 (:constructor nil)
2925 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2926 (pos js2-ts-cursor)
2927 len label target)))
2928 "AST node for a continue statement.
2929 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2930 It is nil if continue specifies no label. The target field is the jump target:
2931 a `js2-label-node' or the innermost enclosing loop.")
2932
2933 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2934 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2935
2936 (defun js2-print-continue-node (n i)
2937 (insert (js2-make-pad i) "continue")
2938 (when (js2-continue-node-label n)
2939 (insert " ")
2940 (js2-print-ast (js2-continue-node-label n) 0))
2941 (insert ";\n"))
2942
2943 (defstruct (js2-function-node
2944 (:include js2-script-node)
2945 (:constructor nil)
2946 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2947 (pos js2-ts-cursor)
2948 len
2949 (ftype 'FUNCTION)
2950 (form 'FUNCTION_STATEMENT)
2951 (name "")
2952 params rest-p
2953 body
2954 lp rp)))
2955 "AST node for a function declaration.
2956 The `params' field is a Lisp list of nodes. Each node is either a simple
2957 `js2-name-node', or if it's a destructuring-assignment parameter, a
2958 `js2-array-node' or `js2-object-node'."
2959 ftype ; FUNCTION, GETTER or SETTER
2960 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
2961 name ; function name (a `js2-name-node', or nil if anonymous)
2962 params ; a Lisp list of destructuring forms or simple name nodes
2963 rest-p ; if t, the last parameter is rest parameter
2964 body ; a `js2-block-node' or expression node (1.8 only)
2965 lp ; position of arg-list open-paren, or nil if omitted
2966 rp ; position of arg-list close-paren, or nil if omitted
2967 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2968 needs-activation ; t if we need an activation object for this frame
2969 is-generator ; t if this function contains a yield
2970 member-expr) ; nonstandard Ecma extension from Rhino
2971
2972 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2973 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2974
2975 (defun js2-visit-function-node (n v)
2976 (js2-visit-ast (js2-function-node-name n) v)
2977 (dolist (p (js2-function-node-params n))
2978 (js2-visit-ast p v))
2979 (js2-visit-ast (js2-function-node-body n) v))
2980
2981 (defun js2-print-function-node (n i)
2982 (let ((pad (js2-make-pad i))
2983 (getter (js2-node-get-prop n 'GETTER_SETTER))
2984 (name (js2-function-node-name n))
2985 (params (js2-function-node-params n))
2986 (rest-p (js2-function-node-rest-p n))
2987 (body (js2-function-node-body n))
2988 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
2989 (unless getter
2990 (insert pad "function"))
2991 (when name
2992 (insert " ")
2993 (js2-print-ast name 0))
2994 (insert "(")
2995 (loop with len = (length params)
2996 for param in params
2997 for count from 1
2998 do
2999 (when (and rest-p (= count len))
3000 (insert "..."))
3001 (js2-print-ast param 0)
3002 (when (< count len)
3003 (insert ", ")))
3004 (insert ") {")
3005 (unless expr
3006 (insert "\n"))
3007 ;; TODO: fix this to be smarter about indenting, etc.
3008 (js2-print-body body (1+ i))
3009 (insert pad "}")
3010 (unless expr
3011 (insert "\n"))))
3012
3013 (defun js2-function-name (node)
3014 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3015 (and (js2-function-node-name node)
3016 (js2-name-node-name (js2-function-node-name node))))
3017
3018 ;; Having this be an expression node makes it more flexible.
3019 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3020 ;; that work better if you assume it's an expression. Whenever we have
3021 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3022 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3023 (defstruct (js2-var-decl-node
3024 (:include js2-node)
3025 (:constructor nil)
3026 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3027 (pos (js2-current-token-beg))
3028 len kids
3029 decl-type)))
3030 "AST node for a variable declaration list (VAR, CONST or LET).
3031 The node bounds differ depending on the declaration type. For VAR or
3032 CONST declarations, the bounds include the var/const keyword. For LET
3033 declarations, the node begins at the position of the first child."
3034 kids ; a Lisp list of `js2-var-init-node' structs.
3035 decl-type) ; js2-VAR, js2-CONST or js2-LET
3036
3037 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3038 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3039
3040 (defun js2-visit-var-decl (n v)
3041 (dolist (kid (js2-var-decl-node-kids n))
3042 (js2-visit-ast kid v)))
3043
3044 (defun js2-print-var-decl (n i)
3045 (let ((pad (js2-make-pad i))
3046 (tt (js2-var-decl-node-decl-type n)))
3047 (insert pad)
3048 (insert (cond
3049 ((= tt js2-VAR) "var ")
3050 ((= tt js2-LET) "let ")
3051 ((= tt js2-CONST) "const ")
3052 (t
3053 (error "malformed var-decl node"))))
3054 (loop with kids = (js2-var-decl-node-kids n)
3055 with len = (length kids)
3056 for kid in kids
3057 for count from 1
3058 do
3059 (js2-print-ast kid 0)
3060 (if (< count len)
3061 (insert ", ")))))
3062
3063 (defstruct (js2-var-init-node
3064 (:include js2-node)
3065 (:constructor nil)
3066 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3067 (pos js2-ts-cursor)
3068 len target
3069 initializer)))
3070 "AST node for a variable declaration.
3071 The type field will be js2-CONST for a const decl."
3072 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3073 initializer) ; initializer expression, a `js2-node'
3074
3075 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3076 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3077
3078 (defun js2-visit-var-init-node (n v)
3079 (js2-visit-ast (js2-var-init-node-target n) v)
3080 (js2-visit-ast (js2-var-init-node-initializer n) v))
3081
3082 (defun js2-print-var-init-node (n i)
3083 (let ((pad (js2-make-pad i))
3084 (name (js2-var-init-node-target n))
3085 (init (js2-var-init-node-initializer n)))
3086 (insert pad)
3087 (js2-print-ast name 0)
3088 (when init
3089 (insert " = ")
3090 (js2-print-ast init 0))))
3091
3092 (defstruct (js2-cond-node
3093 (:include js2-node)
3094 (:constructor nil)
3095 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3096 (pos js2-ts-cursor)
3097 len
3098 test-expr
3099 true-expr
3100 false-expr
3101 q-pos c-pos)))
3102 "AST node for the ternary operator"
3103 test-expr
3104 true-expr
3105 false-expr
3106 q-pos ; buffer position of ?
3107 c-pos) ; buffer position of :
3108
3109 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3110 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3111
3112 (defun js2-visit-cond-node (n v)
3113 (js2-visit-ast (js2-cond-node-test-expr n) v)
3114 (js2-visit-ast (js2-cond-node-true-expr n) v)
3115 (js2-visit-ast (js2-cond-node-false-expr n) v))
3116
3117 (defun js2-print-cond-node (n i)
3118 (let ((pad (js2-make-pad i)))
3119 (insert pad)
3120 (js2-print-ast (js2-cond-node-test-expr n) 0)
3121 (insert " ? ")
3122 (js2-print-ast (js2-cond-node-true-expr n) 0)
3123 (insert " : ")
3124 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3125
3126 (defstruct (js2-infix-node
3127 (:include js2-node)
3128 (:constructor nil)
3129 (:constructor make-js2-infix-node (&key type
3130 (pos js2-ts-cursor)
3131 len op-pos
3132 left right)))
3133 "Represents infix expressions.
3134 Includes assignment ops like `|=', and the comma operator.
3135 The type field inherited from `js2-node' holds the operator."
3136 op-pos ; buffer position where operator begins
3137 left ; any `js2-node'
3138 right) ; any `js2-node'
3139
3140 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3141 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3142
3143 (defun js2-visit-infix-node (n v)
3144 (js2-visit-ast (js2-infix-node-left n) v)
3145 (js2-visit-ast (js2-infix-node-right n) v))
3146
3147 (defconst js2-operator-tokens
3148 (let ((table (make-hash-table :test 'eq))
3149 (tokens
3150 (list (cons js2-IN "in")
3151 (cons js2-TYPEOF "typeof")
3152 (cons js2-INSTANCEOF "instanceof")
3153 (cons js2-DELPROP "delete")
3154 (cons js2-COMMA ",")
3155 (cons js2-COLON ":")
3156 (cons js2-OR "||")
3157 (cons js2-AND "&&")
3158 (cons js2-INC "++")
3159 (cons js2-DEC "--")
3160 (cons js2-BITOR "|")
3161 (cons js2-BITXOR "^")
3162 (cons js2-BITAND "&")
3163 (cons js2-EQ "==")
3164 (cons js2-NE "!=")
3165 (cons js2-LT "<")
3166 (cons js2-LE "<=")
3167 (cons js2-GT ">")
3168 (cons js2-GE ">=")
3169 (cons js2-LSH "<<")
3170 (cons js2-RSH ">>")
3171 (cons js2-URSH ">>>")
3172 (cons js2-ADD "+") ; infix plus
3173 (cons js2-SUB "-") ; infix minus
3174 (cons js2-MUL "*")
3175 (cons js2-DIV "/")
3176 (cons js2-MOD "%")
3177 (cons js2-NOT "!")
3178 (cons js2-BITNOT "~")
3179 (cons js2-POS "+") ; unary plus
3180 (cons js2-NEG "-") ; unary minus
3181 (cons js2-SHEQ "===") ; shallow equality
3182 (cons js2-SHNE "!==") ; shallow inequality
3183 (cons js2-ASSIGN "=")
3184 (cons js2-ASSIGN_BITOR "|=")
3185 (cons js2-ASSIGN_BITXOR "^=")
3186 (cons js2-ASSIGN_BITAND "&=")
3187 (cons js2-ASSIGN_LSH "<<=")
3188 (cons js2-ASSIGN_RSH ">>=")
3189 (cons js2-ASSIGN_URSH ">>>=")
3190 (cons js2-ASSIGN_ADD "+=")
3191 (cons js2-ASSIGN_SUB "-=")
3192 (cons js2-ASSIGN_MUL "*=")
3193 (cons js2-ASSIGN_DIV "/=")
3194 (cons js2-ASSIGN_MOD "%="))))
3195 (loop for (k . v) in tokens do
3196 (puthash k v table))
3197 table))
3198
3199 (defun js2-print-infix-node (n i)
3200 (let* ((tt (js2-node-type n))
3201 (op (gethash tt js2-operator-tokens)))
3202 (unless op
3203 (error "unrecognized infix operator %s" (js2-node-type n)))
3204 (insert (js2-make-pad i))
3205 (js2-print-ast (js2-infix-node-left n) 0)
3206 (unless (= tt js2-COMMA)
3207 (insert " "))
3208 (insert op)
3209 (insert " ")
3210 (js2-print-ast (js2-infix-node-right n) 0)))
3211
3212 (defstruct (js2-assign-node
3213 (:include js2-infix-node)
3214 (:constructor nil)
3215 (:constructor make-js2-assign-node (&key type
3216 (pos js2-ts-cursor)
3217 len op-pos
3218 left right)))
3219 "Represents any assignment.
3220 The type field holds the actual assignment operator.")
3221
3222 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3223 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3224
3225 (defstruct (js2-unary-node
3226 (:include js2-node)
3227 (:constructor nil)
3228 (:constructor make-js2-unary-node (&key type ; required
3229 (pos js2-ts-cursor)
3230 len operand)))
3231 "AST node type for unary operator nodes.
3232 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3233 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3234 property is added if the operator follows the operand."
3235 operand) ; a `js2-node' expression
3236
3237 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3238 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3239
3240 (defun js2-visit-unary-node (n v)
3241 (js2-visit-ast (js2-unary-node-operand n) v))
3242
3243 (defun js2-print-unary-node (n i)
3244 (let* ((tt (js2-node-type n))
3245 (op (gethash tt js2-operator-tokens))
3246 (postfix (js2-node-get-prop n 'postfix)))
3247 (unless op
3248 (error "unrecognized unary operator %s" tt))
3249 (insert (js2-make-pad i))
3250 (unless postfix
3251 (insert op))
3252 (if (or (= tt js2-TYPEOF)
3253 (= tt js2-DELPROP))
3254 (insert " "))
3255 (js2-print-ast (js2-unary-node-operand n) 0)
3256 (when postfix
3257 (insert op))))
3258
3259 (defstruct (js2-let-node
3260 (:include js2-scope)
3261 (:constructor nil)
3262 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3263 (pos (js2-current-token-beg))
3264 len vars body
3265 lp rp)))
3266 "AST node for a let expression or a let statement.
3267 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3268 vars ; a `js2-var-decl-node'
3269 body ; a `js2-node' representing the expression or body block
3270 lp
3271 rp)
3272
3273 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3274 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3275
3276 (defun js2-visit-let-node (n v)
3277 (js2-visit-ast (js2-let-node-vars n) v)
3278 (js2-visit-ast (js2-let-node-body n) v))
3279
3280 (defun js2-print-let-node (n i)
3281 (insert (js2-make-pad i) "let (")
3282 (js2-print-ast (js2-let-node-vars n) 0)
3283 (insert ") ")
3284 (js2-print-ast (js2-let-node-body n) i))
3285
3286 (defstruct (js2-keyword-node
3287 (:include js2-node)
3288 (:constructor nil)
3289 (:constructor make-js2-keyword-node (&key type
3290 (pos (js2-current-token-beg))
3291 (len (- js2-ts-cursor pos)))))
3292 "AST node representing a literal keyword such as `null'.
3293 Used for `null', `this', `true', `false' and `debugger'.
3294 The node type is set to js2-NULL, js2-THIS, etc.")
3295
3296 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3297 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3298
3299 (defun js2-print-keyword-node (n i)
3300 (insert (js2-make-pad i)
3301 (let ((tt (js2-node-type n)))
3302 (cond
3303 ((= tt js2-THIS) "this")
3304 ((= tt js2-NULL) "null")
3305 ((= tt js2-TRUE) "true")
3306 ((= tt js2-FALSE) "false")
3307 ((= tt js2-DEBUGGER) "debugger")
3308 (t (error "Invalid keyword literal type: %d" tt))))))
3309
3310 (defsubst js2-this-node-p (node)
3311 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3312 (eq (js2-node-type node) js2-THIS))
3313
3314 (defstruct (js2-new-node
3315 (:include js2-node)
3316 (:constructor nil)
3317 (:constructor make-js2-new-node (&key (type js2-NEW)
3318 (pos (js2-current-token-beg))
3319 len target
3320 args initializer
3321 lp rp)))
3322 "AST node for new-expression such as new Foo()."
3323 target ; an identifier or reference
3324 args ; a Lisp list of argument nodes
3325 lp ; position of left-paren, nil if omitted
3326 rp ; position of right-paren, nil if omitted
3327 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3328
3329 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3330 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3331
3332 (defun js2-visit-new-node (n v)
3333 (js2-visit-ast (js2-new-node-target n) v)
3334 (dolist (arg (js2-new-node-args n))
3335 (js2-visit-ast arg v))
3336 (js2-visit-ast (js2-new-node-initializer n) v))
3337
3338 (defun js2-print-new-node (n i)
3339 (insert (js2-make-pad i) "new ")
3340 (js2-print-ast (js2-new-node-target n))
3341 (insert "(")
3342 (js2-print-list (js2-new-node-args n))
3343 (insert ")")
3344 (when (js2-new-node-initializer n)
3345 (insert " ")
3346 (js2-print-ast (js2-new-node-initializer n))))
3347
3348 (defstruct (js2-name-node
3349 (:include js2-node)
3350 (:constructor nil)
3351 (:constructor make-js2-name-node (&key (type js2-NAME)
3352 (pos (js2-current-token-beg))
3353 (len (- js2-ts-cursor
3354 (js2-current-token-beg)))
3355 (name (js2-current-token-string)))))
3356 "AST node for a JavaScript identifier"
3357 name ; a string
3358 scope) ; a `js2-scope' (optional, used for codegen)
3359
3360 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3361 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3362
3363 (defun js2-print-name-node (n i)
3364 (insert (js2-make-pad i)
3365 (js2-name-node-name n)))
3366
3367 (defsubst js2-name-node-length (node)
3368 "Return identifier length of NODE, a `js2-name-node'.
3369 Returns 0 if NODE is nil or its identifier field is nil."
3370 (if node
3371 (length (js2-name-node-name node))
3372 0))
3373
3374 (defstruct (js2-number-node
3375 (:include js2-node)
3376 (:constructor nil)
3377 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3378 (pos (js2-current-token-beg))
3379 (len (- js2-ts-cursor
3380 (js2-current-token-beg)))
3381 (value (js2-current-token-string))
3382 (num-value (js2-token-number
3383 (js2-current-token))))))
3384 "AST node for a number literal."
3385 value ; the original string, e.g. "6.02e23"
3386 num-value) ; the parsed number value
3387
3388 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3389 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3390
3391 (defun js2-print-number-node (n i)
3392 (insert (js2-make-pad i)
3393 (number-to-string (js2-number-node-num-value n))))
3394
3395 (defstruct (js2-regexp-node
3396 (:include js2-node)
3397 (:constructor nil)
3398 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3399 (pos (js2-current-token-beg))
3400 (len (- js2-ts-cursor
3401 (js2-current-token-beg)))
3402 value flags)))
3403 "AST node for a regular expression literal."
3404 value ; the regexp string, without // delimiters
3405 flags) ; a string of flags, e.g. `mi'.
3406
3407 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3408 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3409
3410 (defun js2-print-regexp (n i)
3411 (insert (js2-make-pad i)
3412 "/"
3413 (js2-regexp-node-value n)
3414 "/")
3415 (if (js2-regexp-node-flags n)
3416 (insert (js2-regexp-node-flags n))))
3417
3418 (defstruct (js2-string-node
3419 (:include js2-node)
3420 (:constructor nil)
3421 (:constructor make-js2-string-node (&key (type js2-STRING)
3422 (pos (js2-current-token-beg))
3423 (len (- js2-ts-cursor
3424 (js2-current-token-beg)))
3425 (value (js2-current-token-string)))))
3426 "String literal.
3427 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3428 You can tell the quote type by looking at the first character."
3429 value) ; the characters of the string, including the quotes
3430
3431 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3432 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3433
3434 (defun js2-print-string-node (n i)
3435 (insert (js2-make-pad i)
3436 (js2-node-string n)))
3437
3438 (defstruct (js2-array-node
3439 (:include js2-node)
3440 (:constructor nil)
3441 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3442 (pos js2-ts-cursor)
3443 len elems)))
3444 "AST node for an array literal."
3445 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3446
3447 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3448 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3449
3450 (defun js2-visit-array-node (n v)
3451 (dolist (e (js2-array-node-elems n))
3452 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3453
3454 (defun js2-print-array-node (n i)
3455 (insert (js2-make-pad i) "[")
3456 (js2-print-list (js2-array-node-elems n))
3457 (insert "]"))
3458
3459 (defstruct (js2-object-node
3460 (:include js2-node)
3461 (:constructor nil)
3462 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3463 (pos js2-ts-cursor)
3464 len
3465 elems)))
3466 "AST node for an object literal expression.
3467 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3468 The latter represents abbreviation in destructuring expressions."
3469 elems)
3470
3471 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3472 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3473
3474 (defun js2-visit-object-node (n v)
3475 (dolist (e (js2-object-node-elems n))
3476 (js2-visit-ast e v)))
3477
3478 (defun js2-print-object-node (n i)
3479 (insert (js2-make-pad i) "{")
3480 (js2-print-list (js2-object-node-elems n))
3481 (insert "}"))
3482
3483 (defstruct (js2-object-prop-node
3484 (:include js2-infix-node)
3485 (:constructor nil)
3486 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3487 (pos js2-ts-cursor)
3488 len left
3489 right op-pos)))
3490 "AST node for an object literal prop:value entry.
3491 The `left' field is the property: a name node, string node or number node.
3492 The `right' field is a `js2-node' representing the initializer value.")
3493
3494 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3495 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3496
3497 (defun js2-print-object-prop-node (n i)
3498 (insert (js2-make-pad i))
3499 (js2-print-ast (js2-object-prop-node-left n) 0)
3500 (insert ": ")
3501 (js2-print-ast (js2-object-prop-node-right n) 0))
3502
3503 (defstruct (js2-getter-setter-node
3504 (:include js2-infix-node)
3505 (:constructor nil)
3506 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3507 (pos js2-ts-cursor)
3508 len left right)))
3509 "AST node for a getter/setter property in an object literal.
3510 The `left' field is the `js2-name-node' naming the getter/setter prop.
3511 The `right' field is always an anonymous `js2-function-node' with a node
3512 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3513
3514 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3515 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3516
3517 (defun js2-print-getter-setter (n i)
3518 (let ((pad (js2-make-pad i))
3519 (left (js2-getter-setter-node-left n))
3520 (right (js2-getter-setter-node-right n)))
3521 (insert pad)
3522 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3523 (js2-print-ast left 0)
3524 (js2-print-ast right 0)))
3525
3526 (defstruct (js2-prop-get-node
3527 (:include js2-infix-node)
3528 (:constructor nil)
3529 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3530 (pos js2-ts-cursor)
3531 len left right)))
3532 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3533
3534 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3535 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3536
3537 (defun js2-visit-prop-get-node (n v)
3538 (js2-visit-ast (js2-prop-get-node-left n) v)
3539 (js2-visit-ast (js2-prop-get-node-right n) v))
3540
3541 (defun js2-print-prop-get-node (n i)
3542 (insert (js2-make-pad i))
3543 (js2-print-ast (js2-prop-get-node-left n) 0)
3544 (insert ".")
3545 (js2-print-ast (js2-prop-get-node-right n) 0))
3546
3547 (defstruct (js2-elem-get-node
3548 (:include js2-node)
3549 (:constructor nil)
3550 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3551 (pos js2-ts-cursor)
3552 len target element
3553 lb rb)))
3554 "AST node for an array index expression such as foo[bar]."
3555 target ; a `js2-node' - the expression preceding the "."
3556 element ; a `js2-node' - the expression in brackets
3557 lb ; position of left-bracket, nil if omitted
3558 rb) ; position of right-bracket, nil if omitted
3559
3560 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3561 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3562
3563 (defun js2-visit-elem-get-node (n v)
3564 (js2-visit-ast (js2-elem-get-node-target n) v)
3565 (js2-visit-ast (js2-elem-get-node-element n) v))
3566
3567 (defun js2-print-elem-get-node (n i)
3568 (insert (js2-make-pad i))
3569 (js2-print-ast (js2-elem-get-node-target n) 0)
3570 (insert "[")
3571 (js2-print-ast (js2-elem-get-node-element n) 0)
3572 (insert "]"))
3573
3574 (defstruct (js2-call-node
3575 (:include js2-node)
3576 (:constructor nil)
3577 (:constructor make-js2-call-node (&key (type js2-CALL)
3578 (pos js2-ts-cursor)
3579 len target args
3580 lp rp)))
3581 "AST node for a JavaScript function call."
3582 target ; a `js2-node' evaluating to the function to call
3583 args ; a Lisp list of `js2-node' arguments
3584 lp ; position of open-paren, or nil if missing
3585 rp) ; position of close-paren, or nil if missing
3586
3587 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3588 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3589
3590 (defun js2-visit-call-node (n v)
3591 (js2-visit-ast (js2-call-node-target n) v)
3592 (dolist (arg (js2-call-node-args n))
3593 (js2-visit-ast arg v)))
3594
3595 (defun js2-print-call-node (n i)
3596 (insert (js2-make-pad i))
3597 (js2-print-ast (js2-call-node-target n) 0)
3598 (insert "(")
3599 (js2-print-list (js2-call-node-args n))
3600 (insert ")"))
3601
3602 (defstruct (js2-yield-node
3603 (:include js2-node)
3604 (:constructor nil)
3605 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3606 (pos js2-ts-cursor)
3607 len value)))
3608 "AST node for yield statement or expression."
3609 value) ; optional: value to be yielded
3610
3611 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3612 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3613
3614 (defun js2-visit-yield-node (n v)
3615 (js2-visit-ast (js2-yield-node-value n) v))
3616
3617 (defun js2-print-yield-node (n i)
3618 (insert (js2-make-pad i))
3619 (insert "yield")
3620 (when (js2-yield-node-value n)
3621 (insert " ")
3622 (js2-print-ast (js2-yield-node-value n) 0)))
3623
3624 (defstruct (js2-paren-node
3625 (:include js2-node)
3626 (:constructor nil)
3627 (:constructor make-js2-paren-node (&key (type js2-LP)
3628 (pos js2-ts-cursor)
3629 len expr)))
3630 "AST node for a parenthesized expression.
3631 In particular, used when the parens are syntactically optional,
3632 as opposed to required parens such as those enclosing an if-conditional."
3633 expr) ; `js2-node'
3634
3635 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3636 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3637
3638 (defun js2-visit-paren-node (n v)
3639 (js2-visit-ast (js2-paren-node-expr n) v))
3640
3641 (defun js2-print-paren-node (n i)
3642 (insert (js2-make-pad i))
3643 (insert "(")
3644 (js2-print-ast (js2-paren-node-expr n) 0)
3645 (insert ")"))
3646
3647 (defstruct (js2-array-comp-node
3648 (:include js2-scope)
3649 (:constructor nil)
3650 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3651 (pos js2-ts-cursor)
3652 len result
3653 loops filter
3654 if-pos lp rp)))
3655 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3656 result ; result expression (just after left-bracket)
3657 loops ; a Lisp list of `js2-array-comp-loop-node'
3658 filter ; guard/filter expression
3659 if-pos ; buffer pos of 'if' keyword, if present, else nil
3660 lp ; buffer position of if-guard left-paren, or nil if not present
3661 rp) ; buffer position of if-guard right-paren, or nil if not present
3662
3663 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3664 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3665
3666 (defun js2-visit-array-comp-node (n v)
3667 (js2-visit-ast (js2-array-comp-node-result n) v)
3668 (dolist (l (js2-array-comp-node-loops n))
3669 (js2-visit-ast l v))
3670 (js2-visit-ast (js2-array-comp-node-filter n) v))
3671
3672 (defun js2-print-array-comp-node (n i)
3673 (let ((pad (js2-make-pad i))
3674 (result (js2-array-comp-node-result n))
3675 (loops (js2-array-comp-node-loops n))
3676 (filter (js2-array-comp-node-filter n)))
3677 (insert pad "[")
3678 (js2-print-ast result 0)
3679 (dolist (l loops)
3680 (insert " ")
3681 (js2-print-ast l 0))
3682 (when filter
3683 (insert " if (")
3684 (js2-print-ast filter 0)
3685 (insert ")"))
3686 (insert "]")))
3687
3688 (defstruct (js2-array-comp-loop-node
3689 (:include js2-for-in-node)
3690 (:constructor nil)
3691 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3692 (pos js2-ts-cursor)
3693 len iterator
3694 object in-pos
3695 foreach-p
3696 each-pos
3697 forof-p
3698 lp rp)))
3699 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3700
3701 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3702 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3703
3704 (defun js2-visit-array-comp-loop (n v)
3705 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3706 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3707
3708 (defun js2-print-array-comp-loop (n i)
3709 (insert "for ")
3710 (when (js2-array-comp-loop-node-foreach-p n) (insert "each "))
3711 (insert "(")
3712 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3713 (if (js2-array-comp-loop-node-forof-p n)
3714 (insert " of ")
3715 (insert " in "))
3716 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3717 (insert ")"))
3718
3719 (defstruct (js2-empty-expr-node
3720 (:include js2-node)
3721 (:constructor nil)
3722 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3723 (pos (js2-current-token-beg))
3724 len)))
3725 "AST node for an empty expression.")
3726
3727 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3728 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3729
3730 (defstruct (js2-xml-node
3731 (:include js2-block-node)
3732 (:constructor nil)
3733 (:constructor make-js2-xml-node (&key (type js2-XML)
3734 (pos (js2-current-token-beg))
3735 len kids)))
3736 "AST node for initial parse of E4X literals.
3737 The kids field is a list of XML fragments, each a `js2-string-node' or
3738 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3739
3740 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3741 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3742
3743 (defun js2-print-xml-node (n i)
3744 (dolist (kid (js2-xml-node-kids n))
3745 (js2-print-ast kid i)))
3746
3747 (defstruct (js2-xml-js-expr-node
3748 (:include js2-xml-node)
3749 (:constructor nil)
3750 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3751 (pos js2-ts-cursor)
3752 len expr)))
3753 "AST node for an embedded JavaScript {expression} in an E4X literal.
3754 The start and end fields correspond to the curly-braces."
3755 expr) ; a `js2-expr-node' of some sort
3756
3757 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3758 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3759
3760 (defun js2-visit-xml-js-expr (n v)
3761 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3762
3763 (defun js2-print-xml-js-expr (n i)
3764 (insert (js2-make-pad i))
3765 (insert "{")
3766 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3767 (insert "}"))
3768
3769 (defstruct (js2-xml-dot-query-node
3770 (:include js2-infix-node)
3771 (:constructor nil)
3772 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3773 (pos js2-ts-cursor)
3774 op-pos len left
3775 right rp)))
3776 "AST node for an E4X foo.(bar) filter expression.
3777 Note that the left-paren is automatically the character immediately
3778 following the dot (.) in the operator. No whitespace is permitted
3779 between the dot and the lp by the scanner."
3780 rp)
3781
3782 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3783 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3784
3785 (defun js2-print-xml-dot-query (n i)
3786 (insert (js2-make-pad i))
3787 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3788 (insert ".(")
3789 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3790 (insert ")"))
3791
3792 (defstruct (js2-xml-ref-node
3793 (:include js2-node)
3794 (:constructor nil)) ; abstract
3795 "Base type for E4X XML attribute-access or property-get expressions.
3796 Such expressions can take a variety of forms. The general syntax has
3797 three parts:
3798
3799 - (optional) an @ (specifying an attribute access)
3800 - (optional) a namespace (a `js2-name-node') and double-colon
3801 - (required) either a `js2-name-node' or a bracketed [expression]
3802
3803 The property-name expressions (examples: ns::name, @name) are
3804 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3805 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3806
3807 This node type (or more specifically, its subclasses) will sometimes
3808 be the right-hand child of a `js2-prop-get-node' or a
3809 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3810 The `js2-xml-ref-node' may also be a standalone primary expression with
3811 no explicit target, which is valid in certain expression contexts such as
3812
3813 company..employee.(@id < 100)
3814
3815 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3816 expression whose parent is a `js2-xml-dot-query-node'."
3817 namespace
3818 at-pos
3819 colon-pos)
3820
3821 (defsubst js2-xml-ref-node-attr-access-p (node)
3822 "Return non-nil if this expression began with an @-token."
3823 (and (numberp (js2-xml-ref-node-at-pos node))
3824 (plusp (js2-xml-ref-node-at-pos node))))
3825
3826 (defstruct (js2-xml-prop-ref-node
3827 (:include js2-xml-ref-node)
3828 (:constructor nil)
3829 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3830 (pos (js2-current-token-beg))
3831 len propname
3832 namespace at-pos
3833 colon-pos)))
3834 "AST node for an E4X XML [expr] property-ref expression.
3835 The JavaScript syntax is an optional @, an optional ns::, and a name.
3836
3837 [ '@' ] [ name '::' ] name
3838
3839 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3840 @ns::*, @*::attr, @*::*, and @*.
3841
3842 The node starts at the @ token, if present. Otherwise it starts at the
3843 namespace name. The node bounds extend through the closing right-bracket,
3844 or if it is missing due to a syntax error, through the end of the index
3845 expression."
3846 propname)
3847
3848 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3849 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3850
3851 (defun js2-visit-xml-prop-ref-node (n v)
3852 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3853 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3854
3855 (defun js2-print-xml-prop-ref-node (n i)
3856 (insert (js2-make-pad i))
3857 (if (js2-xml-ref-node-attr-access-p n)
3858 (insert "@"))
3859 (when (js2-xml-prop-ref-node-namespace n)
3860 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3861 (insert "::"))
3862 (if (js2-xml-prop-ref-node-propname n)
3863 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3864
3865 (defstruct (js2-xml-elem-ref-node
3866 (:include js2-xml-ref-node)
3867 (:constructor nil)
3868 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3869 (pos (js2-current-token-beg))
3870 len expr lb rb
3871 namespace at-pos
3872 colon-pos)))
3873 "AST node for an E4X XML [expr] member-ref expression.
3874 Syntax:
3875
3876 [ '@' ] [ name '::' ] '[' expr ']'
3877
3878 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3879
3880 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3881 is not a legal E4X XML element-ref expression, since it's already used
3882 for standard JavaScript element-get array indexing. Hence, a
3883 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3884 non-nil namespace node, or both.
3885
3886 The node starts at the @ token, if present. Otherwise it starts
3887 at the namespace name. The node bounds extend through the closing
3888 right-bracket, or if it is missing due to a syntax error, through the
3889 end of the index expression."
3890 expr ; the bracketed index expression
3891 lb
3892 rb)
3893
3894 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3895 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3896
3897 (defun js2-visit-xml-elem-ref-node (n v)
3898 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3899 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3900
3901 (defun js2-print-xml-elem-ref-node (n i)
3902 (insert (js2-make-pad i))
3903 (if (js2-xml-ref-node-attr-access-p n)
3904 (insert "@"))
3905 (when (js2-xml-elem-ref-node-namespace n)
3906 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3907 (insert "::"))
3908 (insert "[")
3909 (if (js2-xml-elem-ref-node-expr n)
3910 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3911 (insert "]"))
3912
3913 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3914
3915 (defstruct (js2-xml-start-tag-node
3916 (:include js2-xml-node)
3917 (:constructor nil)
3918 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3919 (pos js2-ts-cursor)
3920 len name attrs kids
3921 empty-p)))
3922 "AST node for an XML start-tag. Not currently used.
3923 The `kids' field is a Lisp list of child content nodes."
3924 name ; a `js2-xml-name-node'
3925 attrs ; a Lisp list of `js2-xml-attr-node'
3926 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3927
3928 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3929 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3930
3931 (defun js2-visit-xml-start-tag (n v)
3932 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3933 (dolist (attr (js2-xml-start-tag-node-attrs n))
3934 (js2-visit-ast attr v))
3935 (js2-visit-block n v))
3936
3937 (defun js2-print-xml-start-tag (n i)
3938 (insert (js2-make-pad i) "<")
3939 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3940 (when (js2-xml-start-tag-node-attrs n)
3941 (insert " ")
3942 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3943 (insert ">"))
3944
3945 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3946 ;; and add the end-tag to the kids list of the parent as well.
3947 (defstruct (js2-xml-end-tag-node
3948 (:include js2-xml-node)
3949 (:constructor nil)
3950 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
3951 (pos js2-ts-cursor)
3952 len name)))
3953 "AST node for an XML end-tag. Not currently used."
3954 name) ; a `js2-xml-name-node'
3955
3956 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
3957 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
3958
3959 (defun js2-visit-xml-end-tag (n v)
3960 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
3961
3962 (defun js2-print-xml-end-tag (n i)
3963 (insert (js2-make-pad i))
3964 (insert "</")
3965 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
3966 (insert ">"))
3967
3968 (defstruct (js2-xml-name-node
3969 (:include js2-xml-node)
3970 (:constructor nil)
3971 (:constructor make-js2-xml-name-node (&key (type js2-XML)
3972 (pos js2-ts-cursor)
3973 len namespace kids)))
3974 "AST node for an E4X XML name. Not currently used.
3975 Any XML name can be qualified with a namespace, hence the namespace field.
3976 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
3977 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
3978 For a simple name, the kids list has exactly one node, a `js2-name-node'."
3979 namespace) ; a `js2-string-node'
3980
3981 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
3982 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
3983
3984 (defun js2-visit-xml-name-node (n v)
3985 (js2-visit-ast (js2-xml-name-node-namespace n) v))
3986
3987 (defun js2-print-xml-name-node (n i)
3988 (insert (js2-make-pad i))
3989 (when (js2-xml-name-node-namespace n)
3990 (js2-print-ast (js2-xml-name-node-namespace n) 0)
3991 (insert "::"))
3992 (dolist (kid (js2-xml-name-node-kids n))
3993 (js2-print-ast kid 0)))
3994
3995 (defstruct (js2-xml-pi-node
3996 (:include js2-xml-node)
3997 (:constructor nil)
3998 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
3999 (pos js2-ts-cursor)
4000 len name attrs)))
4001 "AST node for an E4X XML processing instruction. Not currently used."
4002 name ; a `js2-xml-name-node'
4003 attrs) ; a list of `js2-xml-attr-node'
4004
4005 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4006 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4007
4008 (defun js2-visit-xml-pi-node (n v)
4009 (js2-visit-ast (js2-xml-pi-node-name n) v)
4010 (dolist (attr (js2-xml-pi-node-attrs n))
4011 (js2-visit-ast attr v)))
4012
4013 (defun js2-print-xml-pi-node (n i)
4014 (insert (js2-make-pad i) "<?")
4015 (js2-print-ast (js2-xml-pi-node-name n))
4016 (when (js2-xml-pi-node-attrs n)
4017 (insert " ")
4018 (js2-print-list (js2-xml-pi-node-attrs n)))
4019 (insert "?>"))
4020
4021 (defstruct (js2-xml-cdata-node
4022 (:include js2-xml-node)
4023 (:constructor nil)
4024 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4025 (pos js2-ts-cursor)
4026 len content)))
4027 "AST node for a CDATA escape section. Not currently used."
4028 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4029
4030 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4031 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4032
4033 (defun js2-visit-xml-cdata-node (n v)
4034 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4035
4036 (defun js2-print-xml-cdata-node (n i)
4037 (insert (js2-make-pad i))
4038 (js2-print-ast (js2-xml-cdata-node-content n)))
4039
4040 (defstruct (js2-xml-attr-node
4041 (:include js2-xml-node)
4042 (:constructor nil)
4043 (:constructor make-js2-attr-node (&key (type js2-XML)
4044 (pos js2-ts-cursor)
4045 len name value
4046 eq-pos quote-type)))
4047 "AST node representing a foo='bar' XML attribute value. Not yet used."
4048 name ; a `js2-xml-name-node'
4049 value ; a `js2-xml-name-node'
4050 eq-pos ; buffer position of "=" sign
4051 quote-type) ; 'single or 'double
4052
4053 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4054 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4055
4056 (defun js2-visit-xml-attr-node (n v)
4057 (js2-visit-ast (js2-xml-attr-node-name n) v)
4058 (js2-visit-ast (js2-xml-attr-node-value n) v))
4059
4060 (defun js2-print-xml-attr-node (n i)
4061 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4062 "'"
4063 "\"")))
4064 (insert (js2-make-pad i))
4065 (js2-print-ast (js2-xml-attr-node-name n) 0)
4066 (insert "=" quote)
4067 (js2-print-ast (js2-xml-attr-node-value n) 0)
4068 (insert quote)))
4069
4070 (defstruct (js2-xml-text-node
4071 (:include js2-xml-node)
4072 (:constructor nil)
4073 (:constructor make-js2-text-node (&key (type js2-XML)
4074 (pos js2-ts-cursor)
4075 len content)))
4076 "AST node for an E4X XML text node. Not currently used."
4077 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4078
4079 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4080 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4081
4082 (defun js2-visit-xml-text-node (n v)
4083 (js2-visit-ast (js2-xml-text-node-content n) v))
4084
4085 (defun js2-print-xml-text-node (n i)
4086 (insert (js2-make-pad i))
4087 (dolist (kid (js2-xml-text-node-content n))
4088 (js2-print-ast kid)))
4089
4090 (defstruct (js2-xml-comment-node
4091 (:include js2-xml-node)
4092 (:constructor nil)
4093 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4094 (pos js2-ts-cursor)
4095 len)))
4096 "AST node for E4X XML comment. Not currently used.")
4097
4098 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4099 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4100
4101 (defun js2-print-xml-comment (n i)
4102 (insert (js2-make-pad i)
4103 (js2-node-string n)))
4104
4105 ;;; Node utilities
4106
4107 (defsubst js2-node-line (n)
4108 "Fetch the source line number at the start of node N.
4109 This is O(n) in the length of the source buffer; use prudently."
4110 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4111
4112 (defsubst js2-block-node-kid (n i)
4113 "Return child I of node N, or nil if there aren't that many."
4114 (nth i (js2-block-node-kids n)))
4115
4116 (defsubst js2-block-node-first (n)
4117 "Return first child of block node N, or nil if there is none."
4118 (first (js2-block-node-kids n)))
4119
4120 (defun js2-node-root (n)
4121 "Return the root of the AST containing N.
4122 If N has no parent pointer, returns N."
4123 (let ((parent (js2-node-parent n)))
4124 (if parent
4125 (js2-node-root parent)
4126 n)))
4127
4128 (defsubst js2-node-short-name (n)
4129 "Return the short name of node N as a string, e.g. `js2-if-node'."
4130 (substring (symbol-name (aref n 0))
4131 (length "cl-struct-")))
4132
4133 (defun js2-node-child-list (node)
4134 "Return the child list for NODE, a Lisp list of nodes.
4135 Works for block nodes, array nodes, obj literals, funarg lists,
4136 var decls and try nodes (for catch clauses). Note that you should call
4137 `js2-block-node-kids' on the function body for the body statements.
4138 Returns nil for zero-length child lists or unsupported nodes."
4139 (cond
4140 ((js2-function-node-p node)
4141 (js2-function-node-params node))
4142 ((js2-block-node-p node)
4143 (js2-block-node-kids node))
4144 ((js2-try-node-p node)
4145 (js2-try-node-catch-clauses node))
4146 ((js2-array-node-p node)
4147 (js2-array-node-elems node))
4148 ((js2-object-node-p node)
4149 (js2-object-node-elems node))
4150 ((js2-call-node-p node)
4151 (js2-call-node-args node))
4152 ((js2-new-node-p node)
4153 (js2-new-node-args node))
4154 ((js2-var-decl-node-p node)
4155 (js2-var-decl-node-kids node))
4156 (t
4157 nil)))
4158
4159 (defun js2-node-set-child-list (node kids)
4160 "Set the child list for NODE to KIDS."
4161 (cond
4162 ((js2-function-node-p node)
4163 (setf (js2-function-node-params node) kids))
4164 ((js2-block-node-p node)
4165 (setf (js2-block-node-kids node) kids))
4166 ((js2-try-node-p node)
4167 (setf (js2-try-node-catch-clauses node) kids))
4168 ((js2-array-node-p node)
4169 (setf (js2-array-node-elems node) kids))
4170 ((js2-object-node-p node)
4171 (setf (js2-object-node-elems node) kids))
4172 ((js2-call-node-p node)
4173 (setf (js2-call-node-args node) kids))
4174 ((js2-new-node-p node)
4175 (setf (js2-new-node-args node) kids))
4176 ((js2-var-decl-node-p node)
4177 (setf (js2-var-decl-node-kids node) kids))
4178 (t
4179 (error "Unsupported node type: %s" (js2-node-short-name node))))
4180 kids)
4181
4182 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4183 (defconst js2-paren-expr-nodes
4184 '(cl-struct-js2-array-comp-loop-node
4185 cl-struct-js2-array-comp-node
4186 cl-struct-js2-call-node
4187 cl-struct-js2-catch-node
4188 cl-struct-js2-do-node
4189 cl-struct-js2-elem-get-node
4190 cl-struct-js2-for-in-node
4191 cl-struct-js2-for-node
4192 cl-struct-js2-function-node
4193 cl-struct-js2-if-node
4194 cl-struct-js2-let-node
4195 cl-struct-js2-new-node
4196 cl-struct-js2-paren-node
4197 cl-struct-js2-switch-node
4198 cl-struct-js2-while-node
4199 cl-struct-js2-with-node
4200 cl-struct-js2-xml-dot-query-node)
4201 "Node types that can have a parenthesized child expression.
4202 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4203
4204 (defsubst js2-paren-expr-node-p (node)
4205 "Return t for nodes that typically have a parenthesized child expression.
4206 Useful for computing the indentation anchors for arg-lists and conditions.
4207 Note that it may return a false positive, for instance when NODE is
4208 a `js2-new-node' and there are no arguments or parentheses."
4209 (memq (aref node 0) js2-paren-expr-nodes))
4210
4211 ;; Fake polymorphism... yech.
4212 (defun js2-node-lp (node)
4213 "Return relative left-paren position for NODE, if applicable.
4214 For `js2-elem-get-node' structs, returns left-bracket position.
4215 Note that the position may be nil in the case of a parse error."
4216 (cond
4217 ((js2-elem-get-node-p node)
4218 (js2-elem-get-node-lb node))
4219 ((js2-loop-node-p node)
4220 (js2-loop-node-lp node))
4221 ((js2-function-node-p node)
4222 (js2-function-node-lp node))
4223 ((js2-if-node-p node)
4224 (js2-if-node-lp node))
4225 ((js2-new-node-p node)
4226 (js2-new-node-lp node))
4227 ((js2-call-node-p node)
4228 (js2-call-node-lp node))
4229 ((js2-paren-node-p node)
4230 0)
4231 ((js2-switch-node-p node)
4232 (js2-switch-node-lp node))
4233 ((js2-catch-node-p node)
4234 (js2-catch-node-lp node))
4235 ((js2-let-node-p node)
4236 (js2-let-node-lp node))
4237 ((js2-array-comp-node-p node)
4238 (js2-array-comp-node-lp node))
4239 ((js2-with-node-p node)
4240 (js2-with-node-lp node))
4241 ((js2-xml-dot-query-node-p node)
4242 (1+ (js2-infix-node-op-pos node)))
4243 (t
4244 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4245
4246 ;; Fake polymorphism... blech.
4247 (defun js2-node-rp (node)
4248 "Return relative right-paren position for NODE, if applicable.
4249 For `js2-elem-get-node' structs, returns right-bracket position.
4250 Note that the position may be nil in the case of a parse error."
4251 (cond
4252 ((js2-elem-get-node-p node)
4253 (js2-elem-get-node-rb node))
4254 ((js2-loop-node-p node)
4255 (js2-loop-node-rp node))
4256 ((js2-function-node-p node)
4257 (js2-function-node-rp node))
4258 ((js2-if-node-p node)
4259 (js2-if-node-rp node))
4260 ((js2-new-node-p node)
4261 (js2-new-node-rp node))
4262 ((js2-call-node-p node)
4263 (js2-call-node-rp node))
4264 ((js2-paren-node-p node)
4265 (1- (js2-node-len node)))
4266 ((js2-switch-node-p node)
4267 (js2-switch-node-rp node))
4268 ((js2-catch-node-p node)
4269 (js2-catch-node-rp node))
4270 ((js2-let-node-p node)
4271 (js2-let-node-rp node))
4272 ((js2-array-comp-node-p node)
4273 (js2-array-comp-node-rp node))
4274 ((js2-with-node-p node)
4275 (js2-with-node-rp node))
4276 ((js2-xml-dot-query-node-p node)
4277 (1+ (js2-xml-dot-query-node-rp node)))
4278 (t
4279 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4280
4281 (defsubst js2-node-first-child (node)
4282 "Return the first element of `js2-node-child-list' for NODE."
4283 (car (js2-node-child-list node)))
4284
4285 (defsubst js2-node-last-child (node)
4286 "Return the last element of `js2-node-last-child' for NODE."
4287 (car (last (js2-node-child-list node))))
4288
4289 (defun js2-node-prev-sibling (node)
4290 "Return the previous statement in parent.
4291 Works for parents supported by `js2-node-child-list'.
4292 Returns nil if NODE is not in the parent, or PARENT is
4293 not a supported node, or if NODE is the first child."
4294 (let* ((p (js2-node-parent node))
4295 (kids (js2-node-child-list p))
4296 (sib (car kids)))
4297 (while (and kids
4298 (not (eq node (cadr kids))))
4299 (setq kids (cdr kids)
4300 sib (car kids)))
4301 sib))
4302
4303 (defun js2-node-next-sibling (node)
4304 "Return the next statement in parent block.
4305 Returns nil if NODE is not in the block, or PARENT is not
4306 a block node, or if NODE is the last statement."
4307 (let* ((p (js2-node-parent node))
4308 (kids (js2-node-child-list p)))
4309 (while (and kids
4310 (not (eq node (car kids))))
4311 (setq kids (cdr kids)))
4312 (cadr kids)))
4313
4314 (defun js2-node-find-child-before (pos parent &optional after)
4315 "Find the last child that starts before POS in parent.
4316 If AFTER is non-nil, returns first child starting after POS.
4317 POS is an absolute buffer position. PARENT is any node
4318 supported by `js2-node-child-list'.
4319 Returns nil if no applicable child is found."
4320 (let ((kids (if (js2-function-node-p parent)
4321 (js2-block-node-kids (js2-function-node-body parent))
4322 (js2-node-child-list parent)))
4323 (beg (if (js2-function-node-p parent)
4324 (js2-node-abs-pos (js2-function-node-body parent))
4325 (js2-node-abs-pos parent)))
4326 kid result fn
4327 (continue t))
4328 (setq fn (if after '>= '<))
4329 (while (and kids continue)
4330 (setq kid (car kids))
4331 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4332 (setq result kid
4333 continue (if after nil t))
4334 (setq continue (if after t nil)))
4335 (setq kids (cdr kids)))
4336 result))
4337
4338 (defun js2-node-find-child-after (pos parent)
4339 "Find first child that starts after POS in parent.
4340 POS is an absolute buffer position. PARENT is any node
4341 supported by `js2-node-child-list'.
4342 Returns nil if no applicable child is found."
4343 (js2-node-find-child-before pos parent 'after))
4344
4345 (defun js2-node-replace-child (pos parent new-node)
4346 "Replace node at index POS in PARENT with NEW-NODE.
4347 Only works for parents supported by `js2-node-child-list'."
4348 (let ((kids (js2-node-child-list parent))
4349 (i 0))
4350 (while (< i pos)
4351 (setq kids (cdr kids)
4352 i (1+ i)))
4353 (setcar kids new-node)
4354 (js2-node-add-children parent new-node)))
4355
4356 (defun js2-node-buffer (n)
4357 "Return the buffer associated with AST N.
4358 Returns nil if the buffer is not set as a property on the root
4359 node, or if parent links were not recorded during parsing."
4360 (let ((root (js2-node-root n)))
4361 (and root
4362 (js2-ast-root-p root)
4363 (js2-ast-root-buffer root))))
4364
4365 (defun js2-block-node-push (n kid)
4366 "Push js2-node KID onto the end of js2-block-node N's child list.
4367 KID is always added to the -end- of the kids list.
4368 Function also calls `js2-node-add-children' to add the parent link."
4369 (let ((kids (js2-node-child-list n)))
4370 (if kids
4371 (setcdr kids (nconc (cdr kids) (list kid)))
4372 (js2-node-set-child-list n (list kid)))
4373 (js2-node-add-children n kid)))
4374
4375 (defun js2-node-string (node)
4376 (with-current-buffer (or (js2-node-buffer node)
4377 (error "No buffer available for node %s" node))
4378 (let ((pos (js2-node-abs-pos node)))
4379 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4380
4381 ;; Container for storing the node we're looking for in a traversal.
4382 (js2-deflocal js2-discovered-node nil)
4383
4384 ;; Keep track of absolute node position during traversals.
4385 (js2-deflocal js2-visitor-offset nil)
4386
4387 (js2-deflocal js2-node-search-point nil)
4388
4389 (when js2-mode-dev-mode-p
4390 (defun js2-find-node-at-point ()
4391 (interactive)
4392 (let ((node (js2-node-at-point)))
4393 (message "%s" (or node "No node found at point"))))
4394 (defun js2-node-name-at-point ()
4395 (interactive)
4396 (let ((node (js2-node-at-point)))
4397 (message "%s" (if node
4398 (js2-node-short-name node)
4399 "No node found at point.")))))
4400
4401 (defun js2-node-at-point (&optional pos skip-comments)
4402 "Return AST node at POS, a buffer position, defaulting to current point.
4403 The `js2-mode-ast' variable must be set to the current parse tree.
4404 Signals an error if the AST (`js2-mode-ast') is nil.
4405 Always returns a node - if it can't find one, it returns the root.
4406 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4407 (let ((ast js2-mode-ast)
4408 result)
4409 (unless ast
4410 (error "No JavaScript AST available"))
4411 ;; Look through comments first, since they may be inside nodes that
4412 ;; would otherwise report a match.
4413 (setq pos (or pos (point))
4414 result (if (> pos (js2-node-abs-end ast))
4415 ast
4416 (if (not skip-comments)
4417 (js2-comment-at-point pos))))
4418 (unless result
4419 (setq js2-discovered-node nil
4420 js2-visitor-offset 0
4421 js2-node-search-point pos)
4422 (unwind-protect
4423 (catch 'js2-visit-done
4424 (js2-visit-ast ast #'js2-node-at-point-visitor))
4425 (setq js2-visitor-offset nil
4426 js2-node-search-point nil))
4427 (setq result js2-discovered-node))
4428 ;; may have found a comment beyond end of last child node,
4429 ;; since visiting the ast-root looks at the comment-list last.
4430 (if (and skip-comments
4431 (js2-comment-node-p result))
4432 (setq result nil))
4433 (or result js2-mode-ast)))
4434
4435 (defun js2-node-at-point-visitor (node end-p)
4436 (let ((rel-pos (js2-node-pos node))
4437 abs-pos
4438 abs-end
4439 (point js2-node-search-point))
4440 (cond
4441 (end-p
4442 ;; this evaluates to a non-nil return value, even if it's zero
4443 (decf js2-visitor-offset rel-pos))
4444 ;; we already looked for comments before visiting, and don't want them now
4445 ((js2-comment-node-p node)
4446 nil)
4447 (t
4448 (setq abs-pos (incf js2-visitor-offset rel-pos)
4449 ;; we only want to use the node if the point is before
4450 ;; the last character position in the node, so we decrement
4451 ;; the absolute end by 1.
4452 abs-end (+ abs-pos (js2-node-len node) -1))
4453 (cond
4454 ;; If this node starts after search-point, stop the search.
4455 ((> abs-pos point)
4456 (throw 'js2-visit-done nil))
4457 ;; If this node ends before the search-point, don't check kids.
4458 ((> point abs-end)
4459 nil)
4460 (t
4461 ;; Otherwise point is within this node, possibly in a child.
4462 (setq js2-discovered-node node)
4463 t)))))) ; keep processing kids to look for more specific match
4464
4465 (defsubst js2-block-comment-p (node)
4466 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4467 (and (js2-comment-node-p node)
4468 (memq (js2-comment-node-format node) '(jsdoc block))))
4469
4470 ;; TODO: put the comments in a vector and binary-search them instead
4471 (defun js2-comment-at-point (&optional pos)
4472 "Look through scanned comment nodes for one containing POS.
4473 POS is a buffer position that defaults to current point.
4474 Function returns nil if POS was not in any comment node."
4475 (let ((ast js2-mode-ast)
4476 (x (or pos (point)))
4477 beg end)
4478 (unless ast
4479 (error "No JavaScript AST available"))
4480 (catch 'done
4481 ;; Comments are stored in lexical order.
4482 (dolist (comment (js2-ast-root-comments ast) nil)
4483 (setq beg (js2-node-abs-pos comment)
4484 end (+ beg (js2-node-len comment)))
4485 (if (and (>= x beg)
4486 (<= x end))
4487 (throw 'done comment))))))
4488
4489 (defun js2-mode-find-parent-fn (node)
4490 "Find function enclosing NODE.
4491 Returns nil if NODE is not inside a function."
4492 (setq node (js2-node-parent node))
4493 (while (and node (not (js2-function-node-p node)))
4494 (setq node (js2-node-parent node)))
4495 (and (js2-function-node-p node) node))
4496
4497 (defun js2-mode-find-enclosing-fn (node)
4498 "Find function or root enclosing NODE."
4499 (if (js2-ast-root-p node)
4500 node
4501 (setq node (js2-node-parent node))
4502 (while (not (or (js2-ast-root-p node)
4503 (js2-function-node-p node)))
4504 (setq node (js2-node-parent node)))
4505 node))
4506
4507 (defun js2-mode-find-enclosing-node (beg end)
4508 "Find script or function fully enclosing BEG and END."
4509 (let ((node (js2-node-at-point beg))
4510 pos
4511 (continue t))
4512 (while continue
4513 (if (or (js2-ast-root-p node)
4514 (and (js2-function-node-p node)
4515 (<= (setq pos (js2-node-abs-pos node)) beg)
4516 (>= (+ pos (js2-node-len node)) end)))
4517 (setq continue nil)
4518 (setq node (js2-node-parent node))))
4519 node))
4520
4521 (defun js2-node-parent-script-or-fn (node)
4522 "Find script or function immediately enclosing NODE.
4523 If NODE is the ast-root, returns nil."
4524 (if (js2-ast-root-p node)
4525 nil
4526 (setq node (js2-node-parent node))
4527 (while (and node (not (or (js2-function-node-p node)
4528 (js2-script-node-p node))))
4529 (setq node (js2-node-parent node)))
4530 node))
4531
4532 (defun js2-node-is-descendant (node ancestor)
4533 "Return t if NODE is a descendant of ANCESTOR."
4534 (while (and node
4535 (not (eq node ancestor)))
4536 (setq node (js2-node-parent node)))
4537 node)
4538
4539 ;;; visitor infrastructure
4540
4541 (defun js2-visit-none (node callback)
4542 "Visitor for AST node that have no node children."
4543 nil)
4544
4545 (defun js2-print-none (node indent)
4546 "Visitor for AST node with no printed representation.")
4547
4548 (defun js2-print-body (node indent)
4549 "Print a statement, or a block without braces."
4550 (if (js2-block-node-p node)
4551 (dolist (kid (js2-block-node-kids node))
4552 (js2-print-ast kid indent))
4553 (js2-print-ast node indent)))
4554
4555 (defun js2-print-list (args &optional delimiter)
4556 (loop with len = (length args)
4557 for arg in args
4558 for count from 1
4559 do
4560 (when arg (js2-print-ast arg 0))
4561 (if (< count len)
4562 (insert (or delimiter ", ")))))
4563
4564 (defun js2-print-tree (ast)
4565 "Prints an AST to the current buffer.
4566 Makes `js2-ast-parent-nodes' available to the printer functions."
4567 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4568 (js2-print-ast ast)))
4569
4570 (defun js2-print-ast (node &optional indent)
4571 "Helper function for printing AST nodes.
4572 Requires `js2-ast-parent-nodes' to be non-nil.
4573 You should use `js2-print-tree' instead of this function."
4574 (let ((printer (get (aref node 0) 'js2-printer))
4575 (i (or indent 0))
4576 (pos (js2-node-abs-pos node)))
4577 ;; TODO: wedge comments in here somewhere
4578 (if printer
4579 (funcall printer node i))))
4580
4581 (defconst js2-side-effecting-tokens
4582 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4583 (dolist (tt (list js2-ASSIGN
4584 js2-ASSIGN_ADD
4585 js2-ASSIGN_BITAND
4586 js2-ASSIGN_BITOR
4587 js2-ASSIGN_BITXOR
4588 js2-ASSIGN_DIV
4589 js2-ASSIGN_LSH
4590 js2-ASSIGN_MOD
4591 js2-ASSIGN_MUL
4592 js2-ASSIGN_RSH
4593 js2-ASSIGN_SUB
4594 js2-ASSIGN_URSH
4595 js2-BLOCK
4596 js2-BREAK
4597 js2-CALL
4598 js2-CATCH
4599 js2-CATCH_SCOPE
4600 js2-CONST
4601 js2-CONTINUE
4602 js2-DEBUGGER
4603 js2-DEC
4604 js2-DELPROP
4605 js2-DEL_REF
4606 js2-DO
4607 js2-ELSE
4608 js2-EMPTY
4609 js2-ENTERWITH
4610 js2-EXPORT
4611 js2-EXPR_RESULT
4612 js2-FINALLY
4613 js2-FOR
4614 js2-FUNCTION
4615 js2-GOTO
4616 js2-IF
4617 js2-IFEQ
4618 js2-IFNE
4619 js2-IMPORT
4620 js2-INC
4621 js2-JSR
4622 js2-LABEL
4623 js2-LEAVEWITH
4624 js2-LET
4625 js2-LETEXPR
4626 js2-LOCAL_BLOCK
4627 js2-LOOP
4628 js2-NEW
4629 js2-REF_CALL
4630 js2-RETHROW
4631 js2-RETURN
4632 js2-RETURN_RESULT
4633 js2-SEMI
4634 js2-SETELEM
4635 js2-SETELEM_OP
4636 js2-SETNAME
4637 js2-SETPROP
4638 js2-SETPROP_OP
4639 js2-SETVAR
4640 js2-SET_REF
4641 js2-SET_REF_OP
4642 js2-SWITCH
4643 js2-TARGET
4644 js2-THROW
4645 js2-TRY
4646 js2-VAR
4647 js2-WHILE
4648 js2-WITH
4649 js2-WITHEXPR
4650 js2-YIELD))
4651 (aset tokens tt t))
4652 (if js2-instanceof-has-side-effects
4653 (aset tokens js2-INSTANCEOF t))
4654 tokens))
4655
4656 (defun js2-node-has-side-effects (node)
4657 "Return t if NODE has side effects."
4658 (when node ; makes it easier to handle malformed expressions
4659 (let ((tt (js2-node-type node)))
4660 (cond
4661 ;; This doubtless needs some work, since EXPR_VOID is used
4662 ;; in several ways in Rhino and I may not have caught them all.
4663 ;; I'll wait for people to notice incorrect warnings.
4664 ((and (= tt js2-EXPR_VOID)
4665 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4666 (let ((expr (js2-expr-stmt-node-expr node)))
4667 (or (js2-node-has-side-effects expr)
4668 (when (js2-string-node-p expr)
4669 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4670 ((= tt js2-COMMA)
4671 (js2-node-has-side-effects (js2-infix-node-right node)))
4672 ((or (= tt js2-AND)
4673 (= tt js2-OR))
4674 (or (js2-node-has-side-effects (js2-infix-node-right node))
4675 (js2-node-has-side-effects (js2-infix-node-left node))))
4676 ((= tt js2-HOOK)
4677 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4678 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4679 ((js2-paren-node-p node)
4680 (js2-node-has-side-effects (js2-paren-node-expr node)))
4681 ((= tt js2-ERROR) ; avoid cascaded error messages
4682 nil)
4683 (t
4684 (aref js2-side-effecting-tokens tt))))))
4685
4686 (defconst js2-stmt-node-types
4687 (list js2-BLOCK
4688 js2-BREAK
4689 js2-CONTINUE
4690 js2-DEFAULT ; e4x "default xml namespace" statement
4691 js2-DO
4692 js2-EXPR_RESULT
4693 js2-EXPR_VOID
4694 js2-FOR
4695 js2-IF
4696 js2-RETURN
4697 js2-SWITCH
4698 js2-THROW
4699 js2-TRY
4700 js2-WHILE
4701 js2-WITH)
4702 "Node types that only appear in statement contexts.
4703 The list does not include nodes that always appear as the child
4704 of another specific statement type, such as switch-cases,
4705 catch and finally blocks, and else-clauses. The list also excludes
4706 nodes like yield, let and var, which may appear in either expression
4707 or statement context, and in the latter context always have a
4708 `js2-expr-stmt-node' parent. Finally, the list does not include
4709 functions or scripts, which are treated separately from statements
4710 by the JavaScript parser and runtime.")
4711
4712 (defun js2-stmt-node-p (node)
4713 "Heuristic for figuring out if NODE is a statement.
4714 Some node types can appear in either an expression context or a
4715 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4716 For these node types in a statement context, the parent will be a
4717 `js2-expr-stmt-node'.
4718 Functions aren't included in the check."
4719 (memq (js2-node-type node) js2-stmt-node-types))
4720
4721 (defun js2-mode-find-first-stmt (node)
4722 "Search upward starting from NODE looking for a statement.
4723 For purposes of this function, a `js2-function-node' counts."
4724 (while (not (or (js2-stmt-node-p node)
4725 (js2-function-node-p node)))
4726 (setq node (js2-node-parent node)))
4727 node)
4728
4729 (defun js2-node-parent-stmt (node)
4730 "Return the node's first ancestor that is a statement.
4731 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4732 appearing in a statement context will have a parent that is a
4733 `js2-expr-stmt-node' that will be returned by this function."
4734 (let ((parent (js2-node-parent node)))
4735 (if (or (null parent)
4736 (js2-stmt-node-p parent)
4737 (and (js2-function-node-p parent)
4738 (not (eq (js2-function-node-form parent)
4739 'FUNCTION_EXPRESSION))))
4740 parent
4741 (js2-node-parent-stmt parent))))
4742
4743 ;; In the Mozilla Rhino sources, Roshan James writes:
4744 ;; Does consistent-return analysis on the function body when strict mode is
4745 ;; enabled.
4746 ;;
4747 ;; function (x) { return (x+1) }
4748 ;;
4749 ;; is ok, but
4750 ;;
4751 ;; function (x) { if (x < 0) return (x+1); }
4752 ;;
4753 ;; is not because the function can potentially return a value when the
4754 ;; condition is satisfied and if not, the function does not explicitly
4755 ;; return a value.
4756 ;;
4757 ;; This extends to checking mismatches such as "return" and "return <value>"
4758 ;; used in the same function. Warnings are not emitted if inconsistent
4759 ;; returns exist in code that can be statically shown to be unreachable.
4760 ;; Ex.
4761 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4762 ;;
4763 ;; emits no warning. However if the loop had a break statement, then a
4764 ;; warning would be emitted.
4765 ;;
4766 ;; The consistency analysis looks at control structures such as loops, ifs,
4767 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4768 ;; warns the user about an inconsistent set of termination possibilities.
4769 ;;
4770 ;; These flags enumerate the possible ways a statement/function can
4771 ;; terminate. These flags are used by endCheck() and by the Parser to
4772 ;; detect inconsistent return usage.
4773 ;;
4774 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4775 ;; able to execute (example: throw, continue)
4776 ;;
4777 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4778 ;; next one. Statement such as return dont. A compound statement may have
4779 ;; some branch that drops off control to the next statement.
4780 ;;
4781 ;; END_RETURNS indicates that the statement can return with no value.
4782 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4783 ;;
4784 ;; A compound statement such as
4785 ;; if (condition) {
4786 ;; return value;
4787 ;; }
4788 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4789
4790 (defconst js2-END_UNREACHED 0)
4791 (defconst js2-END_DROPS_OFF 1)
4792 (defconst js2-END_RETURNS 2)
4793 (defconst js2-END_RETURNS_VALUE 4)
4794 (defconst js2-END_YIELDS 8)
4795
4796 (defun js2-has-consistent-return-usage (node)
4797 "Check that every return usage in a function body is consistent.
4798 Returns t if the function satisfies strict mode requirement."
4799 (let ((n (js2-end-check node)))
4800 ;; either it doesn't return a value in any branch...
4801 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4802 ;; or it returns a value (or is unreached) at every branch
4803 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4804 js2-END_RETURNS
4805 js2-END_YIELDS)))))
4806
4807 (defun js2-end-check-if (node)
4808 "Ensure that return usage in then/else blocks is consistent.
4809 If there is no else block, then the return statement can fall through.
4810 Returns logical OR of END_* flags"
4811 (let ((th (js2-if-node-then-part node))
4812 (el (js2-if-node-else-part node)))
4813 (if (null th)
4814 js2-END_UNREACHED
4815 (logior (js2-end-check th) (if el
4816 (js2-end-check el)
4817 js2-END_DROPS_OFF)))))
4818
4819 (defun js2-end-check-switch (node)
4820 "Consistency of return statements is checked between the case statements.
4821 If there is no default, then the switch can fall through. If there is a
4822 default, we check to see if all code paths in the default return or if
4823 there is a code path that can fall through.
4824 Returns logical OR of END_* flags."
4825 (let ((rv js2-END_UNREACHED)
4826 default-case)
4827 ;; examine the cases
4828 (catch 'break
4829 (dolist (c (js2-switch-node-cases node))
4830 (if (js2-case-node-expr c)
4831 (js2-set-flag rv (js2-end-check-block c))
4832 (setq default-case c)
4833 (throw 'break nil))))
4834 ;; we don't care how the cases drop into each other
4835 (js2-clear-flag rv js2-END_DROPS_OFF)
4836 ;; examine the default
4837 (js2-set-flag rv (if default-case
4838 (js2-end-check default-case)
4839 js2-END_DROPS_OFF))
4840 rv))
4841
4842 (defun js2-end-check-try (node)
4843 "If the block has a finally, return consistency is checked in the
4844 finally block. If all code paths in the finally return, then the
4845 returns in the try-catch blocks don't matter. If there is a code path
4846 that does not return or if there is no finally block, the returns
4847 of the try and catch blocks are checked for mismatch.
4848 Returns logical OR of END_* flags."
4849 (let ((finally (js2-try-node-finally-block node))
4850 rv)
4851 ;; check the finally if it exists
4852 (setq rv (if finally
4853 (js2-end-check (js2-finally-node-body finally))
4854 js2-END_DROPS_OFF))
4855 ;; If the finally block always returns, then none of the returns
4856 ;; in the try or catch blocks matter.
4857 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4858 (js2-clear-flag rv js2-END_DROPS_OFF)
4859 ;; examine the try block
4860 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4861 ;; check each catch block
4862 (dolist (cb (js2-try-node-catch-clauses node))
4863 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4864 rv))
4865
4866 (defun js2-end-check-loop (node)
4867 "Return statement in the loop body must be consistent.
4868 The default assumption for any kind of a loop is that it will eventually
4869 terminate. The only exception is a loop with a constant true condition.
4870 Code that follows such a loop is examined only if one can determine
4871 statically that there is a break out of the loop.
4872
4873 for(... ; ... ; ...) {}
4874 for(... in ... ) {}
4875 while(...) { }
4876 do { } while(...)
4877
4878 Returns logical OR of END_* flags."
4879 (let ((rv (js2-end-check (js2-loop-node-body node)))
4880 (condition (cond
4881 ((js2-while-node-p node)
4882 (js2-while-node-condition node))
4883 ((js2-do-node-p node)
4884 (js2-do-node-condition node))
4885 ((js2-for-node-p node)
4886 (js2-for-node-condition node)))))
4887
4888 ;; check to see if the loop condition is always true
4889 (if (and condition
4890 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4891 (js2-clear-flag rv js2-END_DROPS_OFF))
4892
4893 ;; look for effect of breaks
4894 (js2-set-flag rv (js2-node-get-prop node
4895 'CONTROL_BLOCK_PROP
4896 js2-END_UNREACHED))
4897 rv))
4898
4899 (defun js2-end-check-block (node)
4900 "A general block of code is examined statement by statement.
4901 If any statement (even a compound one) returns in all branches, then
4902 subsequent statements are not examined.
4903 Returns logical OR of END_* flags."
4904 (let* ((rv js2-END_DROPS_OFF)
4905 (kids (js2-block-node-kids node))
4906 (n (car kids)))
4907 ;; Check each statment. If the statement can continue onto the next
4908 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4909 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4910 (js2-clear-flag rv js2-END_DROPS_OFF)
4911 (js2-set-flag rv (js2-end-check n))
4912 (setq kids (cdr kids)
4913 n (car kids)))
4914 rv))
4915
4916 (defun js2-end-check-label (node)
4917 "A labeled statement implies that there may be a break to the label.
4918 The function processes the labeled statement and then checks the
4919 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4920 particular label.
4921 Returns logical OR of END_* flags."
4922 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4923 (logior rv (js2-node-get-prop node
4924 'CONTROL_BLOCK_PROP
4925 js2-END_UNREACHED))))
4926
4927 (defun js2-end-check-break (node)
4928 "When a break is encountered annotate the statement being broken
4929 out of by setting its CONTROL_BLOCK_PROP property.
4930 Returns logical OR of END_* flags."
4931 (and (js2-break-node-target node)
4932 (js2-node-set-prop (js2-break-node-target node)
4933 'CONTROL_BLOCK_PROP
4934 js2-END_DROPS_OFF))
4935 js2-END_UNREACHED)
4936
4937 (defun js2-end-check (node)
4938 "Examine the body of a function, doing a basic reachability analysis.
4939 Returns a combination of flags END_* flags that indicate
4940 how the function execution can terminate. These constitute only the
4941 pessimistic set of termination conditions. It is possible that at
4942 runtime certain code paths will never be actually taken. Hence this
4943 analysis will flag errors in cases where there may not be errors.
4944 Returns logical OR of END_* flags"
4945 (let (kid)
4946 (cond
4947 ((js2-break-node-p node)
4948 (js2-end-check-break node))
4949 ((js2-expr-stmt-node-p node)
4950 (if (setq kid (js2-expr-stmt-node-expr node))
4951 (js2-end-check kid)
4952 js2-END_DROPS_OFF))
4953 ((or (js2-continue-node-p node)
4954 (js2-throw-node-p node))
4955 js2-END_UNREACHED)
4956 ((js2-return-node-p node)
4957 (if (setq kid (js2-return-node-retval node))
4958 js2-END_RETURNS_VALUE
4959 js2-END_RETURNS))
4960 ((js2-loop-node-p node)
4961 (js2-end-check-loop node))
4962 ((js2-switch-node-p node)
4963 (js2-end-check-switch node))
4964 ((js2-labeled-stmt-node-p node)
4965 (js2-end-check-label node))
4966 ((js2-if-node-p node)
4967 (js2-end-check-if node))
4968 ((js2-try-node-p node)
4969 (js2-end-check-try node))
4970 ((js2-block-node-p node)
4971 (if (null (js2-block-node-kids node))
4972 js2-END_DROPS_OFF
4973 (js2-end-check-block node)))
4974 ((js2-yield-node-p node)
4975 js2-END_YIELDS)
4976 (t
4977 js2-END_DROPS_OFF))))
4978
4979 (defun js2-always-defined-boolean-p (node)
4980 "Check if NODE always evaluates to true or false in boolean context.
4981 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
4982 nor always false."
4983 (let ((tt (js2-node-type node))
4984 num)
4985 (cond
4986 ((or (= tt js2-FALSE) (= tt js2-NULL))
4987 'ALWAYS_FALSE)
4988 ((= tt js2-TRUE)
4989 'ALWAYS_TRUE)
4990 ((= tt js2-NUMBER)
4991 (setq num (js2-number-node-num-value node))
4992 (if (and (not (eq num 0.0e+NaN))
4993 (not (zerop num)))
4994 'ALWAYS_TRUE
4995 'ALWAYS_FALSE))
4996 (t
4997 nil))))
4998
4999 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5000 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5001
5002 (defvar js2-tokens nil
5003 "List of all defined token names.") ; initialized in `js2-token-names'
5004
5005 (defconst js2-token-names
5006 (let* ((names (make-vector js2-num-tokens -1))
5007 (case-fold-search nil) ; only match js2-UPPER_CASE
5008 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5009 (loop for sym in syms
5010 for i from 0
5011 do
5012 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5013 (not (boundp sym)))
5014 (aset names (symbol-value sym) ; code, e.g. 152
5015 (downcase
5016 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5017 (push sym js2-tokens)))
5018 names)
5019 "Vector mapping int values to token string names, sans `js2-' prefix.")
5020
5021 (defun js2-tt-name (tok)
5022 "Return a string name for TOK, a token symbol or code.
5023 Signals an error if it's not a recognized token."
5024 (let ((code tok))
5025 (if (symbolp tok)
5026 (setq code (symbol-value tok)))
5027 (if (eq code -1)
5028 "ERROR"
5029 (if (and (numberp code)
5030 (not (minusp code))
5031 (< code js2-num-tokens))
5032 (aref js2-token-names code)
5033 (error "Invalid token: %s" code)))))
5034
5035 (defsubst js2-tt-sym (tok)
5036 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5037 (intern (js2-tt-name tok)))
5038
5039 (defconst js2-token-codes
5040 (let ((table (make-hash-table :test 'eq :size 256)))
5041 (loop for name across js2-token-names
5042 for sym = (intern (concat "js2-" (upcase name)))
5043 do
5044 (puthash sym (symbol-value sym) table))
5045 ;; clean up a few that are "wrong" in Rhino's token codes
5046 (puthash 'js2-DELETE js2-DELPROP table)
5047 table)
5048 "Hashtable mapping token type symbols to their bytecodes.")
5049
5050 (defsubst js2-tt-code (sym)
5051 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5052 (or (gethash sym js2-token-codes)
5053 (error "Invalid token symbol: %s " sym))) ; signal code bug
5054
5055 (defun js2-report-scan-error (msg &optional no-throw beg len)
5056 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5057 (js2-report-error msg nil
5058 (or beg (js2-current-token-beg))
5059 (or len (js2-current-token-len)))
5060 (unless no-throw
5061 (throw 'return js2-ERROR)))
5062
5063 (defun js2-set-string-from-buffer (token)
5064 "Set `string' and `end' slots for TOKEN, return the string."
5065 (setf (js2-token-end token) js2-ts-cursor
5066 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5067
5068 ;; TODO: could potentially avoid a lot of consing by allocating a
5069 ;; char buffer the way Rhino does.
5070 (defsubst js2-add-to-string (c)
5071 (push c js2-ts-string-buffer))
5072
5073 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5074 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5075 ;; any other character: when it's not part of the current token, we
5076 ;; unget it, allowing it to be read again by the following call.
5077 (defsubst js2-unget-char ()
5078 (decf js2-ts-cursor))
5079
5080 ;; Rhino distinguishes \r and \n line endings. We don't need to
5081 ;; because we only scan from Emacs buffers, which always use \n.
5082 (defun js2-get-char ()
5083 "Read and return the next character from the input buffer.
5084 Increments `js2-ts-lineno' if the return value is a newline char.
5085 Updates `js2-ts-cursor' to the point after the returned char.
5086 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5087 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5088 (let (c)
5089 ;; check for end of buffer
5090 (if (>= js2-ts-cursor (point-max))
5091 (setq js2-ts-hit-eof t
5092 js2-ts-cursor (1+ js2-ts-cursor)
5093 c js2-EOF_CHAR) ; return value
5094 ;; otherwise read next char
5095 (setq c (char-before (incf js2-ts-cursor)))
5096 ;; if we read a newline, update counters
5097 (if (= c ?\n)
5098 (setq js2-ts-line-start js2-ts-cursor
5099 js2-ts-lineno (1+ js2-ts-lineno)))
5100 ;; TODO: skip over format characters
5101 c)))
5102
5103 (defun js2-read-unicode-escape ()
5104 "Read a \\uNNNN sequence from the input.
5105 Assumes the ?\ and ?u have already been read.
5106 Returns the unicode character, or nil if it wasn't a valid character.
5107 Doesn't change the values of any scanner variables."
5108 ;; I really wish I knew a better way to do this, but I can't
5109 ;; find the Emacs function that takes a 16-bit int and converts
5110 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5111 ;; Have to first check that it's 4 hex characters or it may stop
5112 ;; the read early.
5113 (ignore-errors
5114 (let ((s (buffer-substring-no-properties js2-ts-cursor
5115 (+ 4 js2-ts-cursor))))
5116 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5117 (read (concat "?\\u" s))))))
5118
5119 (defun js2-match-char (test)
5120 "Consume and return next character if it matches TEST, a character.
5121 Returns nil and consumes nothing if TEST is not the next character."
5122 (let ((c (js2-get-char)))
5123 (if (eq c test)
5124 t
5125 (js2-unget-char)
5126 nil)))
5127
5128 (defun js2-peek-char ()
5129 (prog1
5130 (js2-get-char)
5131 (js2-unget-char)))
5132
5133 (defun js2-java-identifier-start-p (c)
5134 (or
5135 (memq c '(?$ ?_))
5136 (js2-char-uppercase-p c)
5137 (js2-char-lowercase-p c)))
5138
5139 (defun js2-java-identifier-part-p (c)
5140 "Implementation of java.lang.Character.isJavaIdentifierPart()."
5141 ;; TODO: make me Unicode-friendly. See comments above.
5142 (or
5143 (memq c '(?$ ?_))
5144 (js2-char-uppercase-p c)
5145 (js2-char-lowercase-p c)
5146 (and (>= c ?0) (<= c ?9))))
5147
5148 (defun js2-alpha-p (c)
5149 (cond ((and (<= ?A c) (<= c ?Z)) t)
5150 ((and (<= ?a c) (<= c ?z)) t)
5151 (t nil)))
5152
5153 (defsubst js2-digit-p (c)
5154 (and (<= ?0 c) (<= c ?9)))
5155
5156 (defun js2-js-space-p (c)
5157 (if (<= c 127)
5158 (memq c '(#x20 #x9 #xB #xC #xD))
5159 (or
5160 (eq c #xA0)
5161 ;; TODO: change this nil to check for Unicode space character
5162 nil)))
5163
5164 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5165
5166 (defun js2-skip-line ()
5167 "Skip to end of line."
5168 (let (c)
5169 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5170 (js2-unget-char)
5171 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)))
5172
5173 (defun js2-init-scanner (&optional buf line)
5174 "Create token stream for BUF starting on LINE.
5175 BUF defaults to `current-buffer' and LINE defaults to 1.
5176
5177 A buffer can only have one scanner active at a time, which yields
5178 dramatically simpler code than using a defstruct. If you need to
5179 have simultaneous scanners in a buffer, copy the regions to scan
5180 into temp buffers."
5181 (with-current-buffer (or buf (current-buffer))
5182 (setq js2-ts-dirty-line nil
5183 js2-ts-hit-eof nil
5184 js2-ts-line-start 0
5185 js2-ts-lineno (or line 1)
5186 js2-ts-line-end-char -1
5187 js2-ts-cursor (point-min)
5188 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5189 js2-ti-tokens-cursor 0
5190 js2-ti-lookahead 0
5191 js2-ts-is-xml-attribute nil
5192 js2-ts-xml-is-tag-content nil
5193 js2-ts-xml-open-tags-count 0
5194 js2-ts-string-buffer nil)))
5195
5196 ;; This function uses the cached op, string and number fields in
5197 ;; TokenStream; if getToken has been called since the passed token
5198 ;; was scanned, the op or string printed may be incorrect.
5199 (defun js2-token-to-string (token)
5200 ;; Not sure where this function is used in Rhino. Not tested.
5201 (if (not js2-debug-print-trees)
5202 ""
5203 (let ((name (js2-tt-name token)))
5204 (cond
5205 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5206 (concat name " `" (js2-current-token-string) "'"))
5207 ((eq token js2-NUMBER)
5208 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5209 (t
5210 name)))))
5211
5212 (defconst js2-keywords
5213 '(break
5214 case catch const continue
5215 debugger default delete do
5216 else enum
5217 false finally for function
5218 if in instanceof import
5219 let
5220 new null
5221 return
5222 switch
5223 this throw true try typeof
5224 var void
5225 while with
5226 yield))
5227
5228 ;; Token names aren't exactly the same as the keywords, unfortunately.
5229 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5230 (defconst js2-kwd-tokens
5231 (let ((table (make-vector js2-num-tokens nil))
5232 (tokens
5233 (list js2-BREAK
5234 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5235 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5236 js2-ELSE
5237 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5238 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5239 js2-LET
5240 js2-NEW js2-NULL
5241 js2-RETURN
5242 js2-SWITCH
5243 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5244 js2-VAR
5245 js2-WHILE js2-WITH
5246 js2-YIELD)))
5247 (dolist (i tokens)
5248 (aset table i 'font-lock-keyword-face))
5249 (aset table js2-STRING 'font-lock-string-face)
5250 (aset table js2-REGEXP 'font-lock-string-face)
5251 (aset table js2-COMMENT 'font-lock-comment-face)
5252 (aset table js2-THIS 'font-lock-builtin-face)
5253 (aset table js2-VOID 'font-lock-constant-face)
5254 (aset table js2-NULL 'font-lock-constant-face)
5255 (aset table js2-TRUE 'font-lock-constant-face)
5256 (aset table js2-FALSE 'font-lock-constant-face)
5257 table)
5258 "Vector whose values are non-nil for tokens that are keywords.
5259 The values are default faces to use for highlighting the keywords.")
5260
5261 (defconst js2-reserved-words
5262 '(abstract
5263 boolean byte
5264 char class
5265 double
5266 enum export extends
5267 final float
5268 goto
5269 implements import int interface
5270 long
5271 native
5272 package private protected public
5273 short static super synchronized
5274 throws transient
5275 volatile))
5276
5277 (defconst js2-keyword-names
5278 (let ((table (make-hash-table :test 'equal)))
5279 (loop for k in js2-keywords
5280 do (puthash
5281 (symbol-name k) ; instanceof
5282 (intern (concat "js2-"
5283 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5284 table))
5285 table)
5286 "JavaScript keywords by name, mapped to their symbols.")
5287
5288 (defconst js2-reserved-word-names
5289 (let ((table (make-hash-table :test 'equal)))
5290 (loop for k in js2-reserved-words
5291 do
5292 (puthash (symbol-name k) 'js2-RESERVED table))
5293 table)
5294 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5295
5296 (defun js2-collect-string (buf)
5297 "Convert BUF, a list of chars, to a string.
5298 Reverses BUF before converting."
5299 (if buf
5300 (apply #'string (nreverse buf))
5301 ""))
5302
5303 (defun js2-string-to-keyword (s)
5304 "Return token for S, a string, if S is a keyword or reserved word.
5305 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5306 (or (gethash s js2-keyword-names)
5307 (gethash s js2-reserved-word-names)))
5308
5309 (defsubst js2-ts-set-char-token-bounds (token)
5310 "Used when next token is one character."
5311 (setf (js2-token-beg token) (1- js2-ts-cursor)
5312 (js2-token-end token) js2-ts-cursor))
5313
5314 (defsubst js2-ts-return (token type)
5315 "Update the `end' and `type' slots of TOKEN,
5316 then throw `return' with value TYPE."
5317 (setf (js2-token-end token) js2-ts-cursor
5318 (js2-token-type token) type)
5319 (throw 'return type))
5320
5321 (defun js2-x-digit-to-int (c accumulator)
5322 "Build up a hex number.
5323 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5324 corresponding number. Otherwise return -1."
5325 (catch 'return
5326 (catch 'check
5327 ;; Use 0..9 < A..Z < a..z
5328 (cond
5329 ((<= c ?9)
5330 (decf c ?0)
5331 (if (<= 0 c)
5332 (throw 'check nil)))
5333 ((<= c ?F)
5334 (when (<= ?A c)
5335 (decf c (- ?A 10))
5336 (throw 'check nil)))
5337 ((<= c ?f)
5338 (when (<= ?a c)
5339 (decf c (- ?a 10))
5340 (throw 'check nil))))
5341 (throw 'return -1))
5342 (logior c (lsh accumulator 4))))
5343
5344 (defun js2-get-token ()
5345 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5346 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5347 next saved token.
5348
5349 This function will not return a newline (js2-EOL) - instead, it
5350 gobbles newlines until it finds a non-newline token. Call
5351 `js2-peek-token-or-eol' when you care about newlines.
5352
5353 This function will also not return a js2-COMMENT. Instead, it
5354 records comments found in `js2-scanned-comments'. If the token
5355 returned by this function immediately follows a jsdoc comment,
5356 the token is flagged as such."
5357 (if (zerop js2-ti-lookahead)
5358 (js2-get-token-internal)
5359 (decf js2-ti-lookahead)
5360 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5361 (let ((tt (js2-current-token-type)))
5362 (assert (not (= tt js2-EOL)))
5363 tt)))
5364
5365 (defun js2-unget-token ()
5366 (assert (< js2-ti-lookahead js2-ti-max-lookahead))
5367 (incf js2-ti-lookahead)
5368 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5369
5370 (defun js2-get-token-internal ()
5371 (let* ((token (js2-get-token-internal-1)) ; call scanner
5372 (tt (js2-token-type token))
5373 saw-eol
5374 face)
5375 ;; process comments
5376 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5377 (if (= tt js2-EOL)
5378 (setq saw-eol t)
5379 (setq saw-eol nil)
5380 (when js2-record-comments
5381 (js2-record-comment token)))
5382 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5383 (setq token (js2-get-token-internal-1) ; call scanner again
5384 tt (js2-token-type token)))
5385
5386 (when saw-eol
5387 (setf (js2-token-follows-eol-p token) t))
5388
5389 ;; perform lexical fontification as soon as token is scanned
5390 (when js2-parse-ide-mode
5391 (cond
5392 ((minusp tt)
5393 (js2-record-face 'js2-error token))
5394 ((setq face (aref js2-kwd-tokens tt))
5395 (js2-record-face face token))
5396 ((and (= tt js2-NAME)
5397 (equal (js2-token-string token) "undefined"))
5398 (js2-record-face 'font-lock-constant-face token))))
5399 tt))
5400
5401 (defun js2-get-token-internal-1 ()
5402 "Return next JavaScript token type, an int such as js2-RETURN.
5403 During operation, creates an instance of `js2-token' struct, sets
5404 its relevant fields and puts it into `js2-ti-tokens'."
5405 (let (c c1 identifier-start is-unicode-escape-start
5406 contains-escape escape-val escape-start str result base
5407 is-integer quote-char val look-for-slash continue tt
5408 (token (js2-new-token 0)))
5409 (setq
5410 tt
5411 (catch 'return
5412 (while t
5413 ;; Eat whitespace, possibly sensitive to newlines.
5414 (setq continue t)
5415 (while continue
5416 (setq c (js2-get-char))
5417 (cond
5418 ((eq c js2-EOF_CHAR)
5419 (js2-ts-set-char-token-bounds token)
5420 (throw 'return js2-EOF))
5421 ((eq c ?\n)
5422 (js2-ts-set-char-token-bounds token)
5423 (setq js2-ts-dirty-line nil)
5424 (throw 'return js2-EOL))
5425 ((not (js2-js-space-p c))
5426 (if (/= c ?-) ; in case end of HTML comment
5427 (setq js2-ts-dirty-line t))
5428 (setq continue nil))))
5429 ;; Assume the token will be 1 char - fixed up below.
5430 (js2-ts-set-char-token-bounds token)
5431 (when (eq c ?@)
5432 (throw 'return js2-XMLATTR))
5433 ;; identifier/keyword/instanceof?
5434 ;; watch out for starting with a <backslash>
5435 (cond
5436 ((eq c ?\\)
5437 (setq c (js2-get-char))
5438 (if (eq c ?u)
5439 (setq identifier-start t
5440 is-unicode-escape-start t
5441 js2-ts-string-buffer nil)
5442 (setq identifier-start nil)
5443 (js2-unget-char)
5444 (setq c ?\\)))
5445 (t
5446 (when (setq identifier-start (js2-java-identifier-start-p c))
5447 (setq js2-ts-string-buffer nil)
5448 (js2-add-to-string c))))
5449 (when identifier-start
5450 (setq contains-escape is-unicode-escape-start)
5451 (catch 'break
5452 (while t
5453 (if is-unicode-escape-start
5454 ;; strictly speaking we should probably push-back
5455 ;; all the bad characters if the <backslash>uXXXX
5456 ;; sequence is malformed. But since there isn't a
5457 ;; correct context(is there?) for a bad Unicode
5458 ;; escape sequence in an identifier, we can report
5459 ;; an error here.
5460 (progn
5461 (setq escape-val 0)
5462 (dotimes (i 4)
5463 (setq c (js2-get-char)
5464 escape-val (js2-x-digit-to-int c escape-val))
5465 ;; Next check takes care of c < 0 and bad escape
5466 (if (minusp escape-val)
5467 (throw 'break nil)))
5468 (if (minusp escape-val)
5469 (js2-report-scan-error "msg.invalid.escape" t))
5470 (js2-add-to-string escape-val)
5471 (setq is-unicode-escape-start nil))
5472 (setq c (js2-get-char))
5473 (cond
5474 ((eq c ?\\)
5475 (setq c (js2-get-char))
5476 (if (eq c ?u)
5477 (setq is-unicode-escape-start t
5478 contains-escape t)
5479 (js2-report-scan-error "msg.illegal.character" t)))
5480 (t
5481 (if (or (eq c js2-EOF_CHAR)
5482 (not (js2-java-identifier-part-p c)))
5483 (throw 'break nil))
5484 (js2-add-to-string c))))))
5485 (js2-unget-char)
5486 (setf str (js2-collect-string js2-ts-string-buffer)
5487 (js2-token-end token) js2-ts-cursor)
5488 (unless contains-escape
5489 ;; OPT we shouldn't have to make a string (object!) to
5490 ;; check if it's a keyword.
5491 ;; Return the corresponding token if it's a keyword
5492 (when (setq result (js2-string-to-keyword str))
5493 (if (and (< js2-language-version 170)
5494 (memq result '(js2-LET js2-YIELD)))
5495 ;; LET and YIELD are tokens only in 1.7 and later
5496 (setq result 'js2-NAME))
5497 (if (not (eq result 'js2-RESERVED))
5498 (throw 'return (js2-tt-code result)))
5499 (js2-report-warning "msg.reserved.keyword" str)))
5500 ;; If we want to intern these as Rhino does, just use (intern str)
5501 (setf (js2-token-string token) str)
5502 (throw 'return js2-NAME)) ; end identifier/kwd check
5503 ;; is it a number?
5504 (when (or (js2-digit-p c)
5505 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5506 (setq js2-ts-string-buffer nil
5507 base 10)
5508 (when (eq c ?0)
5509 (setq c (js2-get-char))
5510 (cond
5511 ((or (eq c ?x) (eq c ?X))
5512 (setq base 16)
5513 (setq c (js2-get-char)))
5514 ((js2-digit-p c)
5515 (setq base 8))
5516 (t
5517 (js2-add-to-string ?0))))
5518 (if (eq base 16)
5519 (while (<= 0 (js2-x-digit-to-int c 0))
5520 (js2-add-to-string c)
5521 (setq c (js2-get-char)))
5522 (while (and (<= ?0 c) (<= c ?9))
5523 ;; We permit 08 and 09 as decimal numbers, which
5524 ;; makes our behavior a superset of the ECMA
5525 ;; numeric grammar. We might not always be so
5526 ;; permissive, so we warn about it.
5527 (when (and (eq base 8) (>= c ?8))
5528 (js2-report-warning "msg.bad.octal.literal"
5529 (if (eq c ?8) "8" "9"))
5530 (setq base 10))
5531 (js2-add-to-string c)
5532 (setq c (js2-get-char))))
5533 (setq is-integer t)
5534 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5535 (setq is-integer nil)
5536 (when (eq c ?.)
5537 (loop do
5538 (js2-add-to-string c)
5539 (setq c (js2-get-char))
5540 while (js2-digit-p c)))
5541 (when (memq c '(?e ?E))
5542 (js2-add-to-string c)
5543 (setq c (js2-get-char))
5544 (when (memq c '(?+ ?-))
5545 (js2-add-to-string c)
5546 (setq c (js2-get-char)))
5547 (unless (js2-digit-p c)
5548 (js2-report-scan-error "msg.missing.exponent" t))
5549 (loop do
5550 (js2-add-to-string c)
5551 (setq c (js2-get-char))
5552 while (js2-digit-p c))))
5553 (js2-unget-char)
5554 (let ((str (js2-set-string-from-buffer token)))
5555 (setf (js2-token-number token)
5556 (if (and (eq base 10) (not is-integer))
5557 (string-to-number str)
5558 ;; TODO: call runtime number-parser. Some of it is in
5559 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5560 (string-to-number str))))
5561 (throw 'return js2-NUMBER))
5562 ;; is it a string?
5563 (when (memq c '(?\" ?\'))
5564 ;; We attempt to accumulate a string the fast way, by
5565 ;; building it directly out of the reader. But if there
5566 ;; are any escaped characters in the string, we revert to
5567 ;; building it out of a string buffer.
5568 (setq quote-char c
5569 js2-ts-string-buffer nil
5570 c (js2-get-char))
5571 (catch 'break
5572 (while (/= c quote-char)
5573 (catch 'continue
5574 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5575 (js2-unget-char)
5576 (setf (js2-token-end token) js2-ts-cursor)
5577 (js2-report-error "msg.unterminated.string.lit")
5578 (throw 'return js2-STRING))
5579 (when (eq c ?\\)
5580 ;; We've hit an escaped character
5581 (setq c (js2-get-char))
5582 (case c
5583 (?b (setq c ?\b))
5584 (?f (setq c ?\f))
5585 (?n (setq c ?\n))
5586 (?r (setq c ?\r))
5587 (?t (setq c ?\t))
5588 (?v (setq c ?\v))
5589 (?u
5590 (setq c1 (js2-read-unicode-escape))
5591 (if js2-parse-ide-mode
5592 (if c1
5593 (progn
5594 ;; just copy the string in IDE-mode
5595 (js2-add-to-string ?\\)
5596 (js2-add-to-string ?u)
5597 (dotimes (i 3)
5598 (js2-add-to-string (js2-get-char)))
5599 (setq c (js2-get-char))) ; added at end of loop
5600 ;; flag it as an invalid escape
5601 (js2-report-warning "msg.invalid.escape"
5602 nil (- js2-ts-cursor 2) 6))
5603 ;; Get 4 hex digits; if the u escape is not
5604 ;; followed by 4 hex digits, use 'u' + the
5605 ;; literal character sequence that follows.
5606 (js2-add-to-string ?u)
5607 (setq escape-val 0)
5608 (dotimes (i 4)
5609 (setq c (js2-get-char)
5610 escape-val (js2-x-digit-to-int c escape-val))
5611 (if (minusp escape-val)
5612 (throw 'continue nil))
5613 (js2-add-to-string c))
5614 ;; prepare for replace of stored 'u' sequence by escape value
5615 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5616 c escape-val)))
5617 (?x
5618 ;; Get 2 hex digits, defaulting to 'x'+literal
5619 ;; sequence, as above.
5620 (setq c (js2-get-char)
5621 escape-val (js2-x-digit-to-int c 0))
5622 (if (minusp escape-val)
5623 (progn
5624 (js2-add-to-string ?x)
5625 (throw 'continue nil))
5626 (setq c1 c
5627 c (js2-get-char)
5628 escape-val (js2-x-digit-to-int c escape-val))
5629 (if (minusp escape-val)
5630 (progn
5631 (js2-add-to-string ?x)
5632 (js2-add-to-string c1)
5633 (throw 'continue nil))
5634 ;; got 2 hex digits
5635 (setq c escape-val))))
5636 (?\n
5637 ;; Remove line terminator after escape to follow
5638 ;; SpiderMonkey and C/C++
5639 (setq c (js2-get-char))
5640 (throw 'continue nil))
5641 (t
5642 (when (and (<= ?0 c) (< c ?8))
5643 (setq val (- c ?0)
5644 c (js2-get-char))
5645 (when (and (<= ?0 c) (< c ?8))
5646 (setq val (- (+ (* 8 val) c) ?0)
5647 c (js2-get-char))
5648 (when (and (<= ?0 c)
5649 (< c ?8)
5650 (< val #o37))
5651 ;; c is 3rd char of octal sequence only
5652 ;; if the resulting val <= 0377
5653 (setq val (- (+ (* 8 val) c) ?0)
5654 c (js2-get-char))))
5655 (js2-unget-char)
5656 (setq c val)))))
5657 (js2-add-to-string c)
5658 (setq c (js2-get-char)))))
5659 (js2-set-string-from-buffer token)
5660 (throw 'return js2-STRING))
5661 (case c
5662 (?\;
5663 (throw 'return js2-SEMI))
5664 (?\[
5665 (throw 'return js2-LB))
5666 (?\]
5667 (throw 'return js2-RB))
5668 (?{
5669 (throw 'return js2-LC))
5670 (?}
5671 (throw 'return js2-RC))
5672 (?\(
5673 (throw 'return js2-LP))
5674 (?\)
5675 (throw 'return js2-RP))
5676 (?,
5677 (throw 'return js2-COMMA))
5678 (??
5679 (throw 'return js2-HOOK))
5680 (?:
5681 (if (js2-match-char ?:)
5682 (js2-ts-return token js2-COLONCOLON)
5683 (throw 'return js2-COLON)))
5684 (?.
5685 (if (js2-match-char ?.)
5686 (if (js2-match-char ?.)
5687 (js2-ts-return token js2-TRIPLEDOT)
5688 (js2-ts-return token js2-DOTDOT))
5689 (if (js2-match-char ?\()
5690 (js2-ts-return token js2-DOTQUERY)
5691 (throw 'return js2-DOT))))
5692 (?|
5693 (if (js2-match-char ?|)
5694 (throw 'return js2-OR)
5695 (if (js2-match-char ?=)
5696 (js2-ts-return token js2-ASSIGN_BITOR)
5697 (throw 'return js2-BITOR))))
5698 (?^
5699 (if (js2-match-char ?=)
5700 (js2-ts-return token js2-ASSIGN_BITOR)
5701 (throw 'return js2-BITXOR)))
5702 (?&
5703 (if (js2-match-char ?&)
5704 (throw 'return js2-AND)
5705 (if (js2-match-char ?=)
5706 (js2-ts-return token js2-ASSIGN_BITAND)
5707 (throw 'return js2-BITAND))))
5708 (?=
5709 (if (js2-match-char ?=)
5710 (if (js2-match-char ?=)
5711 (js2-ts-return token js2-SHEQ)
5712 (throw 'return js2-EQ))
5713 (throw 'return js2-ASSIGN)))
5714 (?!
5715 (if (js2-match-char ?=)
5716 (if (js2-match-char ?=)
5717 (js2-ts-return token js2-SHNE)
5718 (js2-ts-return token js2-NE))
5719 (throw 'return js2-NOT)))
5720 (?<
5721 ;; NB:treat HTML begin-comment as comment-till-eol
5722 (when (js2-match-char ?!)
5723 (when (js2-match-char ?-)
5724 (when (js2-match-char ?-)
5725 (js2-skip-line)
5726 (setf (js2-token-comment-type (js2-current-token)) 'html)
5727 (throw 'return js2-COMMENT)))
5728 (js2-unget-char))
5729 (if (js2-match-char ?<)
5730 (if (js2-match-char ?=)
5731 (js2-ts-return token js2-ASSIGN_LSH)
5732 (js2-ts-return token js2-LSH))
5733 (if (js2-match-char ?=)
5734 (js2-ts-return token js2-LE)
5735 (throw 'return js2-LT))))
5736 (?>
5737 (if (js2-match-char ?>)
5738 (if (js2-match-char ?>)
5739 (if (js2-match-char ?=)
5740 (js2-ts-return token js2-ASSIGN_URSH)
5741 (js2-ts-return token js2-URSH))
5742 (if (js2-match-char ?=)
5743 (js2-ts-return token js2-ASSIGN_RSH)
5744 (js2-ts-return token js2-RSH)))
5745 (if (js2-match-char ?=)
5746 (js2-ts-return token js2-GE)
5747 (throw 'return js2-GT))))
5748 (?*
5749 (if (js2-match-char ?=)
5750 (js2-ts-return token js2-ASSIGN_MUL)
5751 (throw 'return js2-MUL)))
5752 (?/
5753 ;; is it a // comment?
5754 (when (js2-match-char ?/)
5755 (setf (js2-token-beg token) (- js2-ts-cursor 2))
5756 (js2-skip-line)
5757 (setf (js2-token-comment-type token) 'line)
5758 ;; include newline so highlighting goes to end of window
5759 (incf (js2-token-end token))
5760 (throw 'return js2-COMMENT))
5761 ;; is it a /* comment?
5762 (when (js2-match-char ?*)
5763 (setf look-for-slash nil
5764 (js2-token-beg token) (- js2-ts-cursor 2)
5765 (js2-token-comment-type token)
5766 (if (js2-match-char ?*)
5767 (progn
5768 (setq look-for-slash t)
5769 'jsdoc)
5770 'block))
5771 (while t
5772 (setq c (js2-get-char))
5773 (cond
5774 ((eq c js2-EOF_CHAR)
5775 (setf (js2-token-end token) (1- js2-ts-cursor))
5776 (js2-report-error "msg.unterminated.comment")
5777 (throw 'return js2-COMMENT))
5778 ((eq c ?*)
5779 (setq look-for-slash t))
5780 ((eq c ?/)
5781 (if look-for-slash
5782 (js2-ts-return token js2-COMMENT)))
5783 (t
5784 (setf look-for-slash nil
5785 (js2-token-end token) js2-ts-cursor)))))
5786 (if (js2-match-char ?=)
5787 (js2-ts-return token js2-ASSIGN_DIV)
5788 (throw 'return js2-DIV)))
5789 (?#
5790 (when js2-skip-preprocessor-directives
5791 (js2-skip-line)
5792 (setf (js2-token-comment-type token) 'preprocessor
5793 (js2-token-end token) js2-ts-cursor)
5794 (throw 'return js2-COMMENT))
5795 (throw 'return js2-ERROR))
5796 (?%
5797 (if (js2-match-char ?=)
5798 (js2-ts-return token js2-ASSIGN_MOD)
5799 (throw 'return js2-MOD)))
5800 (?~
5801 (throw 'return js2-BITNOT))
5802 (?+
5803 (if (js2-match-char ?=)
5804 (js2-ts-return token js2-ASSIGN_ADD)
5805 (if (js2-match-char ?+)
5806 (js2-ts-return token js2-INC)
5807 (throw 'return js2-ADD))))
5808 (?-
5809 (cond
5810 ((js2-match-char ?=)
5811 (setq c js2-ASSIGN_SUB))
5812 ((js2-match-char ?-)
5813 (unless js2-ts-dirty-line
5814 ;; treat HTML end-comment after possible whitespace
5815 ;; after line start as comment-until-eol
5816 (when (js2-match-char ?>)
5817 (js2-skip-line)
5818 (setf (js2-token-comment-type (js2-current-token)) 'html)
5819 (throw 'return js2-COMMENT)))
5820 (setq c js2-DEC))
5821 (t
5822 (setq c js2-SUB)))
5823 (setq js2-ts-dirty-line t)
5824 (js2-ts-return token c))
5825 (otherwise
5826 (js2-report-scan-error "msg.illegal.character"))))))
5827 (setf (js2-token-type token) tt)
5828 token))
5829
5830 (defun js2-read-regexp (start-tt)
5831 "Called by parser when it gets / or /= in literal context."
5832 (let (c err
5833 in-class ; inside a '[' .. ']' character-class
5834 flags
5835 (continue t)
5836 (token (js2-new-token 0)))
5837 (setq js2-ts-string-buffer nil)
5838 (if (eq start-tt js2-ASSIGN_DIV)
5839 ;; mis-scanned /=
5840 (js2-add-to-string ?=)
5841 (if (not (eq start-tt js2-DIV))
5842 (error "failed assertion")))
5843 (while (and (not err)
5844 (or (/= (setq c (js2-get-char)) ?/)
5845 in-class))
5846 (cond
5847 ((or (= c ?\n)
5848 (= c js2-EOF_CHAR))
5849 (setf (js2-token-end token) (1- js2-ts-cursor)
5850 err t
5851 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
5852 (js2-report-error "msg.unterminated.re.lit"))
5853 (t (cond
5854 ((= c ?\\)
5855 (js2-add-to-string c)
5856 (setq c (js2-get-char)))
5857 ((= c ?\[)
5858 (setq in-class t))
5859 ((= c ?\])
5860 (setq in-class nil)))
5861 (js2-add-to-string c))))
5862 (unless err
5863 (while continue
5864 (cond
5865 ((js2-match-char ?g)
5866 (push ?g flags))
5867 ((js2-match-char ?i)
5868 (push ?i flags))
5869 ((js2-match-char ?m)
5870 (push ?m flags))
5871 (t
5872 (setq continue nil))))
5873 (if (js2-alpha-p (js2-peek-char))
5874 (js2-report-scan-error "msg.invalid.re.flag" t
5875 js2-ts-cursor 1))
5876 (js2-set-string-from-buffer token)
5877 ;; tell `parse-partial-sexp' to ignore this range of chars
5878 (js2-record-text-property (js2-current-token-beg)
5879 (js2-current-token-end) 'syntax-class '(2)))
5880 (js2-collect-string flags)))
5881
5882 (defun js2-get-first-xml-token ()
5883 (setq js2-ts-xml-open-tags-count 0
5884 js2-ts-is-xml-attribute nil
5885 js2-ts-xml-is-tag-content nil)
5886 (js2-unget-char)
5887 (js2-get-next-xml-token))
5888
5889 (defun js2-xml-discard-string (token)
5890 "Throw away the string in progress and flag an XML parse error."
5891 (setf js2-ts-string-buffer nil
5892 (js2-token-string token) nil)
5893 (js2-report-scan-error "msg.XML.bad.form" t))
5894
5895 (defun js2-get-next-xml-token ()
5896 (setq js2-ts-string-buffer nil) ; for recording the XML
5897 (let ((token (js2-new-token 0))
5898 c result)
5899 (setq result
5900 (catch 'return
5901 (while t
5902 (setq c (js2-get-char))
5903 (cond
5904 ((= c js2-EOF_CHAR)
5905 (throw 'return js2-ERROR))
5906 (js2-ts-xml-is-tag-content
5907 (case c
5908 (?>
5909 (js2-add-to-string c)
5910 (setq js2-ts-xml-is-tag-content nil
5911 js2-ts-is-xml-attribute nil))
5912 (?/
5913 (js2-add-to-string c)
5914 (when (eq ?> (js2-peek-char))
5915 (setq c (js2-get-char))
5916 (js2-add-to-string c)
5917 (setq js2-ts-xml-is-tag-content nil)
5918 (decf js2-ts-xml-open-tags-count)))
5919 (?{
5920 (js2-unget-char)
5921 (js2-set-string-from-buffer token)
5922 (throw 'return js2-XML))
5923 ((?\' ?\")
5924 (js2-add-to-string c)
5925 (unless (js2-read-quoted-string c token)
5926 (throw 'return js2-ERROR)))
5927 (?=
5928 (js2-add-to-string c)
5929 (setq js2-ts-is-xml-attribute t))
5930 ((? ?\t ?\r ?\n)
5931 (js2-add-to-string c))
5932 (t
5933 (js2-add-to-string c)
5934 (setq js2-ts-is-xml-attribute nil)))
5935 (when (and (not js2-ts-xml-is-tag-content)
5936 (zerop js2-ts-xml-open-tags-count))
5937 (js2-set-string-from-buffer token)
5938 (throw 'return js2-XMLEND)))
5939 (t
5940 ;; else not tag content
5941 (case c
5942 (?<
5943 (js2-add-to-string c)
5944 (setq c (js2-peek-char))
5945 (case c
5946 (?!
5947 (setq c (js2-get-char)) ;; skip !
5948 (js2-add-to-string c)
5949 (setq c (js2-peek-char))
5950 (case c
5951 (?-
5952 (setq c (js2-get-char)) ;; skip -
5953 (js2-add-to-string c)
5954 (if (eq c ?-)
5955 (progn
5956 (js2-add-to-string c)
5957 (unless (js2-read-xml-comment token)
5958 (throw 'return js2-ERROR)))
5959 (js2-xml-discard-string token)
5960 (throw 'return js2-ERROR)))
5961 (?\[
5962 (setq c (js2-get-char)) ;; skip [
5963 (js2-add-to-string c)
5964 (if (and (= (js2-get-char) ?C)
5965 (= (js2-get-char) ?D)
5966 (= (js2-get-char) ?A)
5967 (= (js2-get-char) ?T)
5968 (= (js2-get-char) ?A)
5969 (= (js2-get-char) ?\[))
5970 (progn
5971 (js2-add-to-string ?C)
5972 (js2-add-to-string ?D)
5973 (js2-add-to-string ?A)
5974 (js2-add-to-string ?T)
5975 (js2-add-to-string ?A)
5976 (js2-add-to-string ?\[)
5977 (unless (js2-read-cdata token)
5978 (throw 'return js2-ERROR)))
5979 (js2-xml-discard-string token)
5980 (throw 'return js2-ERROR)))
5981 (t
5982 (unless (js2-read-entity token)
5983 (throw 'return js2-ERROR))))
5984 ;; Allow bare CDATA section, e.g.:
5985 ;; let xml = <![CDATA[ foo bar baz ]]>;
5986 (when (zerop js2-ts-xml-open-tags-count)
5987 (throw 'return js2-XMLEND)))
5988 (??
5989 (setq c (js2-get-char)) ;; skip ?
5990 (js2-add-to-string c)
5991 (unless (js2-read-PI token)
5992 (throw 'return js2-ERROR)))
5993 (?/
5994 ;; end tag
5995 (setq c (js2-get-char)) ;; skip /
5996 (js2-add-to-string c)
5997 (when (zerop js2-ts-xml-open-tags-count)
5998 (js2-xml-discard-string token)
5999 (throw 'return js2-ERROR))
6000 (setq js2-ts-xml-is-tag-content t)
6001 (decf js2-ts-xml-open-tags-count))
6002 (t
6003 ;; start tag
6004 (setq js2-ts-xml-is-tag-content t)
6005 (incf js2-ts-xml-open-tags-count))))
6006 (?{
6007 (js2-unget-char)
6008 (js2-set-string-from-buffer token)
6009 (throw 'return js2-XML))
6010 (t
6011 (js2-add-to-string c))))))))
6012 (setf (js2-token-end token) js2-ts-cursor)
6013 (setf (js2-token-type token) result)
6014 result))
6015
6016 (defun js2-read-quoted-string (quote token)
6017 (let (c)
6018 (catch 'return
6019 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6020 (js2-add-to-string c)
6021 (if (eq c quote)
6022 (throw 'return t)))
6023 (js2-xml-discard-string token) ;; throw away string in progress
6024 nil)))
6025
6026 (defun js2-read-xml-comment (token)
6027 (let ((c (js2-get-char)))
6028 (catch 'return
6029 (while (/= c js2-EOF_CHAR)
6030 (catch 'continue
6031 (js2-add-to-string c)
6032 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6033 (setq c (js2-get-char))
6034 (js2-add-to-string c)
6035 (if (eq (js2-peek-char) ?>)
6036 (progn
6037 (setq c (js2-get-char)) ;; skip >
6038 (js2-add-to-string c)
6039 (throw 'return t))
6040 (throw 'continue nil)))
6041 (setq c (js2-get-char))))
6042 (js2-xml-discard-string token)
6043 nil)))
6044
6045 (defun js2-read-cdata (token)
6046 (let ((c (js2-get-char)))
6047 (catch 'return
6048 (while (/= c js2-EOF_CHAR)
6049 (catch 'continue
6050 (js2-add-to-string c)
6051 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6052 (setq c (js2-get-char))
6053 (js2-add-to-string c)
6054 (if (eq (js2-peek-char) ?>)
6055 (progn
6056 (setq c (js2-get-char)) ;; Skip >
6057 (js2-add-to-string c)
6058 (throw 'return t))
6059 (throw 'continue nil)))
6060 (setq c (js2-get-char))))
6061 (js2-xml-discard-string token)
6062 nil)))
6063
6064 (defun js2-read-entity (token)
6065 (let ((decl-tags 1)
6066 c)
6067 (catch 'return
6068 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6069 (js2-add-to-string c)
6070 (case c
6071 (?<
6072 (incf decl-tags))
6073 (?>
6074 (decf decl-tags)
6075 (if (zerop decl-tags)
6076 (throw 'return t)))))
6077 (js2-xml-discard-string token)
6078 nil)))
6079
6080 (defun js2-read-PI (token)
6081 "Scan an XML processing instruction."
6082 (let (c)
6083 (catch 'return
6084 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6085 (js2-add-to-string c)
6086 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6087 (setq c (js2-get-char)) ;; Skip >
6088 (js2-add-to-string c)
6089 (throw 'return t)))
6090 (js2-xml-discard-string token)
6091 nil)))
6092
6093 ;;; Highlighting
6094
6095 (defun js2-set-face (beg end face &optional record)
6096 "Fontify a region. If RECORD is non-nil, record for later."
6097 (when (plusp js2-highlight-level)
6098 (setq beg (min (point-max) beg)
6099 beg (max (point-min) beg)
6100 end (min (point-max) end)
6101 end (max (point-min) end))
6102 (if record
6103 (push (list beg end face) js2-mode-fontifications)
6104 (put-text-property beg end 'font-lock-face face))))
6105
6106 (defsubst js2-clear-face (beg end)
6107 (remove-text-properties beg end '(font-lock-face nil
6108 help-echo nil
6109 point-entered nil
6110 c-in-sws nil)))
6111
6112 (defconst js2-ecma-global-props
6113 (concat "^"
6114 (regexp-opt
6115 '("Infinity" "NaN" "undefined" "arguments") t)
6116 "$")
6117 "Value properties of the Ecma-262 Global Object.
6118 Shown at or above `js2-highlight-level' 2.")
6119
6120 ;; might want to add the name "arguments" to this list?
6121 (defconst js2-ecma-object-props
6122 (concat "^"
6123 (regexp-opt
6124 '("prototype" "__proto__" "__parent__") t)
6125 "$")
6126 "Value properties of the Ecma-262 Object constructor.
6127 Shown at or above `js2-highlight-level' 2.")
6128
6129 (defconst js2-ecma-global-funcs
6130 (concat
6131 "^"
6132 (regexp-opt
6133 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6134 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6135 "$")
6136 "Function properties of the Ecma-262 Global object.
6137 Shown at or above `js2-highlight-level' 2.")
6138
6139 (defconst js2-ecma-number-props
6140 (concat "^"
6141 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6142 "NEGATIVE_INFINITY"
6143 "POSITIVE_INFINITY") t)
6144 "$")
6145 "Properties of the Ecma-262 Number constructor.
6146 Shown at or above `js2-highlight-level' 2.")
6147
6148 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6149 "Properties of the Ecma-262 Date constructor.
6150 Shown at or above `js2-highlight-level' 2.")
6151
6152 (defconst js2-ecma-math-props
6153 (concat "^"
6154 (regexp-opt
6155 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6156 t)
6157 "$")
6158 "Properties of the Ecma-262 Math object.
6159 Shown at or above `js2-highlight-level' 2.")
6160
6161 (defconst js2-ecma-math-funcs
6162 (concat "^"
6163 (regexp-opt
6164 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6165 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6166 "$")
6167 "Function properties of the Ecma-262 Math object.
6168 Shown at or above `js2-highlight-level' 2.")
6169
6170 (defconst js2-ecma-function-props
6171 (concat
6172 "^"
6173 (regexp-opt
6174 '(;; properties of the Object prototype object
6175 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6176 "toLocaleString" "toString" "valueOf"
6177 ;; properties of the Function prototype object
6178 "apply" "call"
6179 ;; properties of the Array prototype object
6180 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6181 "splice" "unshift"
6182 ;; properties of the String prototype object
6183 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6184 "localeCompare" "match" "replace" "search" "split" "substring"
6185 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6186 "toUpperCase"
6187 ;; properties of the Number prototype object
6188 "toExponential" "toFixed" "toPrecision"
6189 ;; properties of the Date prototype object
6190 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6191 "getMinutes" "getMonth" "getSeconds" "getTime"
6192 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6193 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6194 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6195 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6196 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6197 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6198 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6199 "toTimeString" "toUTCString"
6200 ;; properties of the RegExp prototype object
6201 "exec" "test"
6202 ;; properties of the JSON prototype object
6203 "parse" "stringify"
6204 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6205 "toSource" "__defineGetter__" "__defineSetter__"
6206 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6207 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6208 t)
6209 "$")
6210 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6211 Shown at or above `js2-highlight-level' 3.")
6212
6213 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6214 (let ((target-name (and target
6215 (js2-name-node-p target)
6216 (js2-name-node-name target)))
6217 (prop-name (if prop (js2-name-node-name prop)))
6218 (level1 (>= js2-highlight-level 1))
6219 (level2 (>= js2-highlight-level 2))
6220 (level3 (>= js2-highlight-level 3))
6221 pos face)
6222 (when level2
6223 (if call-p
6224 (cond
6225 ((and target prop)
6226 (cond
6227 ((and level3 (string-match js2-ecma-function-props prop-name))
6228 (setq face 'font-lock-builtin-face))
6229 ((and target-name prop)
6230 (cond
6231 ((string= target-name "Date")
6232 (if (string-match js2-ecma-date-props prop-name)
6233 (setq face 'font-lock-builtin-face)))
6234 ((string= target-name "Math")
6235 (if (string-match js2-ecma-math-funcs prop-name)
6236 (setq face 'font-lock-builtin-face)))))))
6237 (prop
6238 (if (string-match js2-ecma-global-funcs prop-name)
6239 (setq face 'font-lock-builtin-face))))
6240 (cond
6241 ((and target prop)
6242 (cond
6243 ((string= target-name "Number")
6244 (if (string-match js2-ecma-number-props prop-name)
6245 (setq face 'font-lock-constant-face)))
6246 ((string= target-name "Math")
6247 (if (string-match js2-ecma-math-props prop-name)
6248 (setq face 'font-lock-constant-face)))))
6249 (prop
6250 (if (string-match js2-ecma-object-props prop-name)
6251 (setq face 'font-lock-constant-face)))))
6252 (when face
6253 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6254 (js2-node-pos prop))) ; relative
6255 (+ pos (js2-node-len prop))
6256 face 'record)))))
6257
6258 (defun js2-parse-highlight-member-expr-node (node)
6259 "Perform syntax highlighting of EcmaScript built-in properties.
6260 The variable `js2-highlight-level' governs this highighting."
6261 (let (face target prop name pos end parent call-p callee)
6262 (cond
6263 ;; case 1: simple name, e.g. foo
6264 ((js2-name-node-p node)
6265 (setq name (js2-name-node-name node))
6266 ;; possible for name to be nil in rare cases - saw it when
6267 ;; running js2-mode on an elisp buffer. Might as well try to
6268 ;; make it so js2-mode never barfs.
6269 (when name
6270 (setq face (if (string-match js2-ecma-global-props name)
6271 'font-lock-constant-face))
6272 (when face
6273 (setq pos (js2-node-pos node)
6274 end (+ pos (js2-node-len node)))
6275 (js2-set-face pos end face 'record))))
6276 ;; case 2: property access or function call
6277 ((or (js2-prop-get-node-p node)
6278 ;; highlight function call if expr is a prop-get node
6279 ;; or a plain name (i.e. unqualified function call)
6280 (and (setq call-p (js2-call-node-p node))
6281 (setq callee (js2-call-node-target node)) ; separate setq!
6282 (or (js2-prop-get-node-p callee)
6283 (js2-name-node-p callee))))
6284 (setq parent node
6285 node (if call-p callee node))
6286 (if (and call-p (js2-name-node-p callee))
6287 (setq prop callee)
6288 (setq target (js2-prop-get-node-left node)
6289 prop (js2-prop-get-node-right node)))
6290 (cond
6291 ((js2-name-node-p target)
6292 (if (js2-name-node-p prop)
6293 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6294 (js2-parse-highlight-prop-get parent target prop call-p)
6295 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6296 (js2-parse-highlight-prop-get parent target nil call-p)))
6297 ((js2-name-node-p prop)
6298 ;; case 2c: complex target, simple name, e.g. x[y].bar
6299 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6300
6301 (defun js2-parse-highlight-member-expr-fn-name (expr)
6302 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6303 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6304 We currently only handle the case where the last component is a prop-get
6305 of a simple name. Called before EXPR has a parent node."
6306 (let (pos
6307 (name (and (js2-prop-get-node-p expr)
6308 (js2-prop-get-node-right expr))))
6309 (when (js2-name-node-p name)
6310 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6311 (js2-node-pos name)))
6312 (+ pos (js2-node-len name))
6313 'font-lock-function-name-face
6314 'record))))
6315
6316 ;; source: http://jsdoc.sourceforge.net/
6317 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6318 ;; allows type specifications, and needs work before entering the wild.
6319
6320 (defconst js2-jsdoc-param-tag-regexp
6321 (concat "^\\s-*\\*+\\s-*\\(@"
6322 "\\(?:param\\|argument\\)"
6323 "\\)"
6324 "\\s-*\\({[^}]+}\\)?" ; optional type
6325 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6326 "\\>")
6327 "Matches jsdoc tags with optional type and optional param name.")
6328
6329 (defconst js2-jsdoc-typed-tag-regexp
6330 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6331 (regexp-opt
6332 '("enum"
6333 "extends"
6334 "field"
6335 "id"
6336 "implements"
6337 "lends"
6338 "mods"
6339 "requires"
6340 "return"
6341 "returns"
6342 "throw"
6343 "throws"))
6344 "\\)\\)\\s-*\\({[^}]+}\\)?")
6345 "Matches jsdoc tags with optional type.")
6346
6347 (defconst js2-jsdoc-arg-tag-regexp
6348 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6349 (regexp-opt
6350 '("alias"
6351 "augments"
6352 "borrows"
6353 "bug"
6354 "base"
6355 "config"
6356 "default"
6357 "define"
6358 "exception"
6359 "function"
6360 "member"
6361 "memberOf"
6362 "name"
6363 "namespace"
6364 "property"
6365 "since"
6366 "suppress"
6367 "this"
6368 "throws"
6369 "type"
6370 "version"))
6371 "\\)\\)\\s-+\\([^ \t]+\\)")
6372 "Matches jsdoc tags with a single argument.")
6373
6374 (defconst js2-jsdoc-empty-tag-regexp
6375 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6376 (regexp-opt
6377 '("addon"
6378 "author"
6379 "class"
6380 "const"
6381 "constant"
6382 "constructor"
6383 "constructs"
6384 "deprecated"
6385 "desc"
6386 "description"
6387 "event"
6388 "example"
6389 "exec"
6390 "export"
6391 "fileoverview"
6392 "final"
6393 "function"
6394 "hidden"
6395 "ignore"
6396 "implicitCast"
6397 "inheritDoc"
6398 "inner"
6399 "interface"
6400 "license"
6401 "noalias"
6402 "noshadow"
6403 "notypecheck"
6404 "override"
6405 "owner"
6406 "preserve"
6407 "preserveTry"
6408 "private"
6409 "protected"
6410 "public"
6411 "static"
6412 "supported"
6413 ))
6414 "\\)\\)\\s-*")
6415 "Matches empty jsdoc tags.")
6416
6417 (defconst js2-jsdoc-link-tag-regexp
6418 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6419 "Matches a jsdoc link or code tag.")
6420
6421 (defconst js2-jsdoc-see-tag-regexp
6422 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6423 "Matches a jsdoc @see tag.")
6424
6425 (defconst js2-jsdoc-html-tag-regexp
6426 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6427 "Matches a simple (no attributes) html start- or end-tag.")
6428
6429 (defun js2-jsdoc-highlight-helper ()
6430 (js2-set-face (match-beginning 1)
6431 (match-end 1)
6432 'js2-jsdoc-tag)
6433 (if (match-beginning 2)
6434 (if (save-excursion
6435 (goto-char (match-beginning 2))
6436 (= (char-after) ?{))
6437 (js2-set-face (1+ (match-beginning 2))
6438 (1- (match-end 2))
6439 'js2-jsdoc-type)
6440 (js2-set-face (match-beginning 2)
6441 (match-end 2)
6442 'js2-jsdoc-value)))
6443 (if (match-beginning 3)
6444 (js2-set-face (match-beginning 3)
6445 (match-end 3)
6446 'js2-jsdoc-value)))
6447
6448 (defun js2-highlight-jsdoc (ast)
6449 "Highlight doc comment tags."
6450 (let ((comments (js2-ast-root-comments ast))
6451 beg end)
6452 (save-excursion
6453 (dolist (node comments)
6454 (when (eq (js2-comment-node-format node) 'jsdoc)
6455 (setq beg (js2-node-abs-pos node)
6456 end (+ beg (js2-node-len node)))
6457 (save-restriction
6458 (narrow-to-region beg end)
6459 (dolist (re (list js2-jsdoc-param-tag-regexp
6460 js2-jsdoc-typed-tag-regexp
6461 js2-jsdoc-arg-tag-regexp
6462 js2-jsdoc-link-tag-regexp
6463 js2-jsdoc-see-tag-regexp
6464 js2-jsdoc-empty-tag-regexp))
6465 (goto-char beg)
6466 (while (re-search-forward re nil t)
6467 (js2-jsdoc-highlight-helper)))
6468 ;; simple highlighting for html tags
6469 (goto-char beg)
6470 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6471 (js2-set-face (match-beginning 1)
6472 (match-end 1)
6473 'js2-jsdoc-html-tag-delimiter)
6474 (js2-set-face (match-beginning 2)
6475 (match-end 2)
6476 'js2-jsdoc-html-tag-name)
6477 (js2-set-face (match-beginning 3)
6478 (match-end 3)
6479 'js2-jsdoc-html-tag-delimiter))))))))
6480
6481 (defun js2-highlight-assign-targets (node left right)
6482 "Highlight function properties and external variables."
6483 (let (leftpos end name)
6484 ;; highlight vars and props assigned function values
6485 (when (js2-function-node-p right)
6486 (cond
6487 ;; var foo = function() {...}
6488 ((js2-name-node-p left)
6489 (setq name left))
6490 ;; foo.bar.baz = function() {...}
6491 ((and (js2-prop-get-node-p left)
6492 (js2-name-node-p (js2-prop-get-node-right left)))
6493 (setq name (js2-prop-get-node-right left))))
6494 (when name
6495 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6496 (+ leftpos (js2-node-len name))
6497 'font-lock-function-name-face
6498 'record)))))
6499
6500 (defun js2-record-name-node (node)
6501 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6502 later. NODE must be a name node."
6503 (let (leftpos end)
6504 (push (list node js2-current-scope
6505 (setq leftpos (js2-node-abs-pos node))
6506 (setq end (+ leftpos (js2-node-len node))))
6507 js2-recorded-identifiers)))
6508
6509 (defun js2-highlight-undeclared-vars ()
6510 "After entire parse is finished, look for undeclared variable references.
6511 We have to wait until entire buffer is parsed, since JavaScript permits var
6512 decls to occur after they're used.
6513
6514 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6515 it is considered declared."
6516 (let (name)
6517 (dolist (entry js2-recorded-identifiers)
6518 (destructuring-bind (name-node scope pos end) entry
6519 (setq name (js2-name-node-name name-node))
6520 (unless (or (member name js2-global-externs)
6521 (member name js2-default-externs)
6522 (member name js2-additional-externs)
6523 (js2-get-defining-scope scope name))
6524 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6525 'js2-external-variable))))
6526 (setq js2-recorded-identifiers nil)))
6527
6528 (defun js2-set-default-externs ()
6529 "Set the value of `js2-default-externs' based on the various
6530 `js2-include-?-externs' variables."
6531 (setq js2-default-externs
6532 (append js2-ecma-262-externs
6533 (if js2-include-browser-externs js2-browser-externs)
6534 (if js2-include-rhino-externs js2-rhino-externs)
6535 (if js2-include-node-externs js2-node-externs)
6536 (if (or js2-include-browser-externs js2-include-node-externs)
6537 js2-typed-array-externs))))
6538
6539 (defun js2-apply-jslint-globals ()
6540 (setq js2-additional-externs
6541 (nconc (js2-get-jslint-globals)
6542 js2-additional-externs)))
6543
6544 (defun js2-get-jslint-globals ()
6545 (loop for node in (js2-ast-root-comments js2-mode-ast)
6546 when (and (eq 'block (js2-comment-node-format node))
6547 (save-excursion
6548 (goto-char (js2-node-abs-pos node))
6549 (looking-at "/\\*global ")))
6550 append (js2-get-jslint-globals-in
6551 (match-end 0)
6552 (js2-node-abs-end node))))
6553
6554 (defun js2-get-jslint-globals-in (beg end)
6555 (let (res)
6556 (save-excursion
6557 (goto-char beg)
6558 (while (re-search-forward js2-mode-identifier-re end t)
6559 (let ((match (match-string 0)))
6560 (unless (member match '("true" "false"))
6561 (push match res)))))
6562 (nreverse res)))
6563
6564 ;;; IMenu support
6565
6566 ;; We currently only support imenu, but eventually should support speedbar and
6567 ;; possibly other browsing mechanisms.
6568
6569 ;; The basic strategy is to identify function assignment targets of the form
6570 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6571 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6572 ;; for imenu after parsing is finished.
6573
6574 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6575 ;; JavaScript, and the general problem is undecidable. However, several forms
6576 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6577 ;; include:
6578
6579 ;; function foo() -- function declaration
6580 ;; foo = function() -- function expression assigned to variable
6581 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6582 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6583 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6584 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6585 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6586 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6587 ;; function foo() {function bar() {...}} -- nested function
6588 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6589
6590 ;; This list boils down to a few forms that can be combined recursively.
6591 ;; Top-level named function declarations include both the left-hand (name)
6592 ;; and the right-hand (function value) expressions needed to produce an imenu
6593 ;; entry. The other "right-hand" forms we need to look for are:
6594 ;; - functions declared as props/getters/setters in object literals
6595 ;; - nested named function declarations
6596 ;; The "left-hand" expressions that functions can be assigned to include:
6597 ;; - local/global variables
6598 ;; - nested property-get expressions like a.b.c.d
6599 ;; - element gets like foo[10] or foo['bar'] where the index
6600 ;; expression can be trivially converted to a property name. They
6601 ;; effectively then become property gets.
6602
6603 ;; All the different definition types are canonicalized into the form
6604 ;; foo.bar.baz = position-of-function-keyword
6605
6606 ;; We need to build a trie-like structure for imenu. As an example,
6607 ;; consider the following JavaScript code:
6608
6609 ;; a = function() {...} // function at position 5
6610 ;; b = function() {...} // function at position 25
6611 ;; foo = function() {...} // function at position 100
6612 ;; foo.bar = function() {...} // function at position 200
6613 ;; foo.bar.baz = function() {...} // function at position 300
6614 ;; foo.bar.zab = function() {...} // function at position 400
6615
6616 ;; During parsing we accumulate an entry for each definition in
6617 ;; the variable `js2-imenu-recorder', like so:
6618
6619 ;; '((fn a 5)
6620 ;; (fn b 25)
6621 ;; (fn foo 100)
6622 ;; (fn foo bar 200)
6623 ;; (fn foo bar baz 300)
6624 ;; (fn foo bar zab 400))
6625
6626 ;; Where 'fn' is the respective function node.
6627 ;; After parsing these entries are merged into this alist-trie:
6628
6629 ;; '((a . 1)
6630 ;; (b . 2)
6631 ;; (foo (<definition> . 3)
6632 ;; (bar (<definition> . 6)
6633 ;; (baz . 100)
6634 ;; (zab . 200))))
6635
6636 ;; Note the wacky need for a <definition> name. The token can be anything
6637 ;; that isn't a valid JavaScript identifier, because you might make foo
6638 ;; a function and then start setting properties on it that are also functions.
6639
6640 (defun js2-prop-node-name (node)
6641 "Return the name of a node that may be a property-get/property-name.
6642 If NODE is not a valid name-node, string-node or integral number-node,
6643 returns nil. Otherwise returns the string name/value of the node."
6644 (cond
6645 ((js2-name-node-p node)
6646 (js2-name-node-name node))
6647 ((js2-string-node-p node)
6648 (js2-string-node-value node))
6649 ((and (js2-number-node-p node)
6650 (string-match "^[0-9]+$" (js2-number-node-value node)))
6651 (js2-number-node-value node))
6652 ((js2-this-node-p node)
6653 "this")))
6654
6655 (defun js2-node-qname-component (node)
6656 "Return the name of this node, if it contributes to a qname.
6657 Returns nil if the node doesn't contribute."
6658 (copy-sequence
6659 (or (js2-prop-node-name node)
6660 (if (and (js2-function-node-p node)
6661 (js2-function-node-name node))
6662 (js2-name-node-name (js2-function-node-name node))))))
6663
6664 (defun js2-record-imenu-entry (fn-node qname pos)
6665 "Add an entry to `js2-imenu-recorder'.
6666 FN-NODE should be the current item's function node.
6667
6668 Associate FN-NODE with its QNAME for later lookup.
6669 This is used in postprocessing the chain list. For each chain, we find
6670 the parent function, look up its qname, then prepend a copy of it to the chain."
6671 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6672 (unless js2-imenu-function-map
6673 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6674 (puthash fn-node qname js2-imenu-function-map))
6675
6676 (defun js2-record-imenu-functions (node &optional var)
6677 "Record function definitions for imenu.
6678 NODE is a function node or an object literal.
6679 VAR, if non-nil, is the expression that NODE is being assigned to.
6680 When passed arguments of wrong type, does nothing."
6681 (when js2-parse-ide-mode
6682 (let ((fun-p (js2-function-node-p node))
6683 qname left fname-node pos)
6684 (cond
6685 ;; non-anonymous function declaration?
6686 ((and fun-p
6687 (not var)
6688 (setq fname-node (js2-function-node-name node)))
6689 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6690 ;; for remaining forms, compute left-side tree branch first
6691 ((and var (setq qname (js2-compute-nested-prop-get var)))
6692 (cond
6693 ;; foo.bar.baz = function
6694 (fun-p
6695 (js2-record-imenu-entry node qname (js2-node-pos node)))
6696 ;; foo.bar.baz = object-literal
6697 ;; look for nested functions: {a: {b: function() {...} }}
6698 ((js2-object-node-p node)
6699 ;; Node position here is still absolute, since the parser
6700 ;; passes the assignment target and value expressions
6701 ;; to us before they are added as children of the assignment node.
6702 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6703
6704 (defun js2-compute-nested-prop-get (node)
6705 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6706 component nodes as a list. Otherwise return nil. Element-gets are treated
6707 as property-gets if the index expression is a string, or a positive integer."
6708 (let (left right head)
6709 (cond
6710 ((or (js2-name-node-p node)
6711 (js2-this-node-p node))
6712 (list node))
6713 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6714 ((js2-prop-get-node-p node) ; foo.bar
6715 (setq left (js2-prop-get-node-left node)
6716 right (js2-prop-get-node-right node))
6717 (if (setq head (js2-compute-nested-prop-get left))
6718 (nconc head (list right))))
6719 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6720 (setq left (js2-elem-get-node-target node)
6721 right (js2-elem-get-node-element node))
6722 (if (or (js2-string-node-p right) ; ['bar']
6723 (and (js2-number-node-p right) ; [10]
6724 (string-match "^[0-9]+$"
6725 (js2-number-node-value right))))
6726 (if (setq head (js2-compute-nested-prop-get left))
6727 (nconc head (list right))))))))
6728
6729 (defun js2-record-object-literal (node qname pos)
6730 "Recursively process an object literal looking for functions.
6731 NODE is an object literal that is the right-hand child of an assignment
6732 expression. QNAME is a list of nodes representing the assignment target,
6733 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6734 POS is the absolute position of the node.
6735 We do a depth-first traversal of NODE. For any functions we find,
6736 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6737 (let (left right prop-qname)
6738 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6739 (let ((left (js2-infix-node-left e))
6740 ;; Element positions are relative to the parent position.
6741 (pos (+ pos (js2-node-pos e))))
6742 (cond
6743 ;; foo: function() {...}
6744 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6745 (when (js2-prop-node-name left)
6746 ;; As a policy decision, we record the position of the property,
6747 ;; not the position of the `function' keyword, since the property
6748 ;; is effectively the name of the function.
6749 (js2-record-imenu-entry right (append qname (list left)) pos)))
6750 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6751 ((js2-object-node-p right)
6752 (js2-record-object-literal right
6753 (append qname (list (js2-infix-node-left e)))
6754 (+ pos (js2-node-pos right)))))))))
6755
6756 (defun js2-node-top-level-decl-p (node)
6757 "Return t if NODE's name is defined in the top-level scope.
6758 Also returns t if NODE's name is not defined in any scope, since it implies
6759 that it's an external variable, which must also be in the top-level scope."
6760 (let* ((name (js2-prop-node-name node))
6761 (this-scope (js2-node-get-enclosing-scope node))
6762 defining-scope)
6763 (cond
6764 ((js2-this-node-p node)
6765 nil)
6766 ((null this-scope)
6767 t)
6768 ((setq defining-scope (js2-get-defining-scope this-scope name))
6769 (js2-ast-root-p defining-scope))
6770 (t t))))
6771
6772 (defun js2-wrapper-function-p (node)
6773 "Return t if NODE is a function expression that's immediately invoked.
6774 NODE must be `js2-function-node'."
6775 (let ((parent (js2-node-parent node)))
6776 (or
6777 ;; function(){...}();
6778 (js2-call-node-p parent)
6779 (and (js2-paren-node-p parent)
6780 ;; (function(){...})();
6781 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6782 ;; (function(){...}).call(this);
6783 (and (js2-prop-get-node-p parent)
6784 (member (js2-name-node-name (js2-prop-get-node-right parent))
6785 '("call" "apply"))
6786 (js2-call-node-p (js2-node-parent parent))))))))
6787
6788 (defun js2-browse-postprocess-chains (entries)
6789 "Modify function-declaration name chains after parsing finishes.
6790 Some of the information is only available after the parse tree is complete.
6791 For instance, processing a nested scope requires a parent function node."
6792 (let (result head fn current-fn parent-qname qname p elem)
6793 (dolist (entry entries)
6794 ;; function node goes first
6795 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6796 ;; Examine head's defining scope:
6797 ;; Pre-processed chain, or top-level/external, keep as-is.
6798 (if (or (stringp head) (js2-node-top-level-decl-p head))
6799 (push chain result)
6800 (when (js2-this-node-p head)
6801 (setq chain (cdr chain))) ; discard this-node
6802 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6803 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6804 (when (eq parent-qname 'not-found)
6805 ;; anonymous function expressions are not recorded
6806 ;; during the parse, so we need to handle this case here
6807 (setq parent-qname
6808 (if (js2-wrapper-function-p fn)
6809 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6810 (if (js2-ast-root-p grandparent)
6811 nil
6812 (gethash grandparent js2-imenu-function-map 'skip)))
6813 'skip))
6814 (puthash fn parent-qname js2-imenu-function-map))
6815 (unless (eq parent-qname 'skip)
6816 ;; prefix parent fn qname to this chain.
6817 (let ((qname (append parent-qname chain)))
6818 (puthash current-fn (butlast qname) js2-imenu-function-map)
6819 (push qname result)))))))
6820 ;; finally replace each node in each chain with its name.
6821 (dolist (chain result)
6822 (setq p chain)
6823 (while p
6824 (if (js2-node-p (setq elem (car p)))
6825 (setcar p (js2-node-qname-component elem)))
6826 (setq p (cdr p))))
6827 result))
6828
6829 ;; Merge name chains into a trie-like tree structure of nested lists.
6830 ;; To simplify construction of the trie, we first build it out using the rule
6831 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6832 ;; [key, num-or-list]. The second element can be a number; if so, this key
6833 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6834 ;; associated with the key at this level.) Otherwise the second element is
6835 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6836 ;; a simple recursive formulation.
6837 ;;
6838 ;; js2-mode is building the data structure for imenu. The imenu documentation
6839 ;; claims that it's the structure above, but in practice it wants the children
6840 ;; at the same list level as the key for that level, which is how I've drawn
6841 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6842 ;; list wrapper around the children at each level.
6843 ;;
6844 ;; A completed nested imenu-alist entry looks like this:
6845 ;; '(("foo"
6846 ;; ("<definition>" . 7)
6847 ;; ("bar"
6848 ;; ("a" . 40)
6849 ;; ("b" . 60))))
6850 ;;
6851 ;; In particular, the documentation for `imenu--index-alist' says that
6852 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6853 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6854
6855 (defun js2-treeify (lst)
6856 "Convert (a b c d) to (a ((b ((c d)))))."
6857 (if (null (cddr lst)) ; list length <= 2
6858 lst
6859 (list (car lst) (list (js2-treeify (cdr lst))))))
6860
6861 (defun js2-build-alist-trie (chains trie)
6862 "Merge declaration name chains into a trie-like alist structure for imenu.
6863 CHAINS is the qname chain list produced during parsing. TRIE is a
6864 list of elements built up so far."
6865 (let (head tail pos branch kids)
6866 (dolist (chain chains)
6867 (setq head (car chain)
6868 tail (cdr chain)
6869 pos (if (numberp (car tail)) (car tail))
6870 branch (js2-find-if (lambda (n)
6871 (string= (car n) head))
6872 trie)
6873 kids (second branch))
6874 (cond
6875 ;; case 1: this key isn't in the trie yet
6876 ((null branch)
6877 (if trie
6878 (setcdr (last trie) (list (js2-treeify chain)))
6879 (setq trie (list (js2-treeify chain)))))
6880 ;; case 2: key is present with a single number entry: replace w/ list
6881 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6882 ;; ("<definition>" 20)))
6883 ((numberp kids)
6884 (setcar (cdr branch)
6885 (list (list "<definition-1>" kids)
6886 (if pos
6887 (list "<definition-2>" pos)
6888 (js2-treeify tail)))))
6889 ;; case 3: key is there (with kids), and we're a number entry
6890 (pos
6891 (setcdr (last kids)
6892 (list
6893 (list (format "<definition-%d>"
6894 (1+ (loop for kid in kids
6895 count (eq ?< (aref (car kid) 0)))))
6896 pos))))
6897 ;; case 4: key is there with kids, need to merge in our chain
6898 (t
6899 (js2-build-alist-trie (list tail) kids))))
6900 trie))
6901
6902 (defun js2-flatten-trie (trie)
6903 "Convert TRIE to imenu-format.
6904 Recurses through nodes, and for each one whose second element is a list,
6905 appends the list's flattened elements to the current element. Also
6906 changes the tails into conses. For instance, this pre-flattened trie
6907
6908 '(a ((b 20)
6909 (c ((d 30)
6910 (e 40)))))
6911
6912 becomes
6913
6914 '(a (b . 20)
6915 (c (d . 30)
6916 (e . 40)))
6917
6918 Note that the root of the trie has no key, just a list of chains.
6919 This is also true for the value of any key with multiple children,
6920 e.g. key 'c' in the example above."
6921 (cond
6922 ((listp (car trie))
6923 (mapcar #'js2-flatten-trie trie))
6924 (t
6925 (if (numberp (second trie))
6926 (cons (car trie) (second trie))
6927 ;; else pop list and append its kids
6928 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6929
6930 (defun js2-build-imenu-index ()
6931 "Turn `js2-imenu-recorder' into an imenu data structure."
6932 (unless (eq js2-imenu-recorder 'empty)
6933 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
6934 (result (js2-build-alist-trie chains nil)))
6935 (js2-flatten-trie result))))
6936
6937 (defun js2-test-print-chains (chains)
6938 "Print a list of qname chains.
6939 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
6940 i.e. one or more nodes, and an integer position as the list tail."
6941 (mapconcat (lambda (chain)
6942 (concat "("
6943 (mapconcat (lambda (elem)
6944 (if (js2-node-p elem)
6945 (or (js2-node-qname-component elem)
6946 "nil")
6947 (number-to-string elem)))
6948 chain
6949 " ")
6950 ")"))
6951 chains
6952 "\n"))
6953
6954 ;;; Parser
6955
6956 (defconst js2-version "1.8.5"
6957 "Version of JavaScript supported.")
6958
6959 (defun js2-record-face (face &optional token)
6960 "Record a style run of FACE for TOKEN or the current token."
6961 (unless token (setq token (js2-current-token)))
6962 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
6963
6964 (defsubst js2-node-end (n)
6965 "Computes the absolute end of node N.
6966 Use with caution! Assumes `js2-node-pos' is -absolute-, which
6967 is only true until the node is added to its parent; i.e., while parsing."
6968 (+ (js2-node-pos n)
6969 (js2-node-len n)))
6970
6971 (defun js2-record-comment (token)
6972 "Record a comment in `js2-scanned-comments'."
6973 (let ((ct (js2-token-comment-type token))
6974 (beg (js2-token-beg token))
6975 (end (js2-token-end token)))
6976 (push (make-js2-comment-node :len (- end beg)
6977 :format ct)
6978 js2-scanned-comments)
6979 (when js2-parse-ide-mode
6980 (js2-record-face (if (eq ct 'jsdoc)
6981 'font-lock-doc-face
6982 'font-lock-comment-face)
6983 token)
6984 (when (memq ct '(html preprocessor))
6985 ;; Tell cc-engine the bounds of the comment.
6986 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
6987
6988 (defun js2-peek-token ()
6989 "Return the next token type without consuming it.
6990 If `js2-ti-lookahead' is positive, return the type of next token
6991 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
6992 (if (not (zerop js2-ti-lookahead))
6993 (js2-token-type
6994 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
6995 (let ((tt (js2-get-token-internal)))
6996 (js2-unget-token)
6997 tt)))
6998
6999 (defalias 'js2-next-token 'js2-get-token)
7000
7001 (defun js2-match-token (match)
7002 "Get next token and return t if it matches MATCH, a bytecode.
7003 Returns nil and consumes nothing if MATCH is not the next token."
7004 (if (/= (js2-get-token) match)
7005 (ignore (js2-unget-token))
7006 t))
7007
7008 (defun js2-match-contextual-kwd (name)
7009 "Consume and return t if next token is `js2-NAME', and its
7010 string is NAME. Returns nil and keeps current token otherwise."
7011 (if (or (/= (js2-get-token) js2-NAME)
7012 (not (string= (js2-current-token-string) name)))
7013 (progn
7014 (js2-unget-token)
7015 nil)
7016 (js2-record-face 'font-lock-keyword-face)
7017 t))
7018
7019 (defun js2-valid-prop-name-token (tt)
7020 (or (= tt js2-NAME)
7021 (and js2-allow-keywords-as-property-names
7022 (plusp tt)
7023 (aref js2-kwd-tokens tt))))
7024
7025 (defun js2-match-prop-name ()
7026 "Consume token and return t if next token is a valid property name.
7027 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7028 is non-nil and it's a keyword token."
7029 (if (js2-valid-prop-name-token (js2-get-token))
7030 t
7031 (js2-unget-token)
7032 nil))
7033
7034 (defun js2-must-match-prop-name (msg-id &optional pos len)
7035 (if (js2-match-prop-name)
7036 t
7037 (js2-report-error msg-id nil pos len)
7038 nil))
7039
7040 (defun js2-peek-token-or-eol ()
7041 "Return js2-EOL if the next token immediately follows a newline.
7042 Else returns the next token. Used in situations where we don't
7043 consider certain token types valid if they are preceded by a newline.
7044 One example is the postfix ++ or -- operator, which has to be on the
7045 same line as its operand."
7046 (let ((tt (js2-get-token))
7047 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7048 (js2-unget-token)
7049 (if follows-eol
7050 js2-EOL
7051 tt)))
7052
7053 (defun js2-must-match (token msg-id &optional pos len)
7054 "Match next token to token code TOKEN, or record a syntax error.
7055 MSG-ID is the error message to report if the match fails.
7056 Returns t on match, nil if no match."
7057 (if (js2-match-token token)
7058 t
7059 (js2-report-error msg-id nil pos len)
7060 nil))
7061
7062 (defsubst js2-inside-function ()
7063 (plusp js2-nesting-of-function))
7064
7065 (defun js2-set-requires-activation ()
7066 (if (js2-function-node-p js2-current-script-or-fn)
7067 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7068
7069 (defun js2-check-activation-name (name token)
7070 (when (js2-inside-function)
7071 ;; skip language-version 1.2 check from Rhino
7072 (if (or (string= "arguments" name)
7073 (and js2-compiler-activation-names ; only used in codegen
7074 (gethash name js2-compiler-activation-names)))
7075 (js2-set-requires-activation))))
7076
7077 (defun js2-set-is-generator ()
7078 (if (js2-function-node-p js2-current-script-or-fn)
7079 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7080
7081 (defun js2-must-have-xml ()
7082 (unless js2-compiler-xml-available
7083 (js2-report-error "msg.XML.not.available")))
7084
7085 (defun js2-push-scope (scope)
7086 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7087 (assert (js2-scope-p scope))
7088 (assert (null (js2-scope-parent-scope scope)))
7089 (assert (not (eq js2-current-scope scope)))
7090 (setf (js2-scope-parent-scope scope) js2-current-scope
7091 js2-current-scope scope))
7092
7093 (defsubst js2-pop-scope ()
7094 (setq js2-current-scope
7095 (js2-scope-parent-scope js2-current-scope)))
7096
7097 (defun js2-enter-loop (loop-node)
7098 (push loop-node js2-loop-set)
7099 (push loop-node js2-loop-and-switch-set)
7100 (js2-push-scope loop-node)
7101 ;; Tell the current labeled statement (if any) its statement,
7102 ;; and set the jump target of the first label to the loop.
7103 ;; These are used in `js2-parse-continue' to verify that the
7104 ;; continue target is an actual labeled loop. (And for codegen.)
7105 (when js2-labeled-stmt
7106 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7107 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7108 js2-labeled-stmt))) loop-node)))
7109
7110 (defun js2-exit-loop ()
7111 (pop js2-loop-set)
7112 (pop js2-loop-and-switch-set)
7113 (js2-pop-scope))
7114
7115 (defsubst js2-enter-switch (switch-node)
7116 (push switch-node js2-loop-and-switch-set))
7117
7118 (defsubst js2-exit-switch ()
7119 (pop js2-loop-and-switch-set))
7120
7121 (defun js2-parse (&optional buf cb)
7122 "Tell the js2 parser to parse a region of JavaScript.
7123
7124 BUF is a buffer or buffer name containing the code to parse.
7125 Call `narrow-to-region' first to parse only part of the buffer.
7126
7127 The returned AST root node is given some additional properties:
7128 `node-count' - total number of nodes in the AST
7129 `buffer' - BUF. The buffer it refers to may change or be killed,
7130 so the value is not necessarily reliable.
7131
7132 An optional callback CB can be specified to report parsing
7133 progress. If `(functionp CB)' returns t, it will be called with
7134 the current line number once before parsing begins, then again
7135 each time the lexer reaches a new line number.
7136
7137 CB can also be a list of the form `(symbol cb ...)' to specify
7138 multiple callbacks with different criteria. Each symbol is a
7139 criterion keyword, and the following element is the callback to
7140 call
7141
7142 :line - called whenever the line number changes
7143 :token - called for each new token consumed
7144
7145 The list of criteria could be extended to include entering or
7146 leaving a statement, an expression, or a function definition."
7147 (if (and cb (not (functionp cb)))
7148 (error "criteria callbacks not yet implemented"))
7149 (let ((inhibit-point-motion-hooks t)
7150 (js2-compiler-xml-available (>= js2-language-version 160))
7151 ;; This is a recursive-descent parser, so give it a big stack.
7152 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7153 (max-specpdl-size (max max-specpdl-size 3000))
7154 (case-fold-search nil)
7155 ast)
7156 (message nil) ; clear any error message from previous parse
7157 (with-current-buffer (or buf (current-buffer))
7158 (setq js2-scanned-comments nil
7159 js2-parsed-errors nil
7160 js2-parsed-warnings nil
7161 js2-imenu-recorder nil
7162 js2-imenu-function-map nil
7163 js2-label-set nil)
7164 (js2-init-scanner)
7165 (setq ast (with-silent-modifications
7166 (js2-do-parse)))
7167 (unless js2-ts-hit-eof
7168 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7169 (setf (js2-ast-root-errors ast) js2-parsed-errors
7170 (js2-ast-root-warnings ast) js2-parsed-warnings)
7171 ;; if we didn't find any declarations, put a dummy in this list so we
7172 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7173 (unless js2-imenu-recorder
7174 (setq js2-imenu-recorder 'empty))
7175 (run-hooks 'js2-parse-finished-hook)
7176 ast)))
7177
7178 ;; Corresponds to Rhino's Parser.parse() method.
7179 (defun js2-do-parse ()
7180 "Parse current buffer starting from current point.
7181 Scanner should be initialized."
7182 (let ((pos js2-ts-cursor)
7183 (end js2-ts-cursor) ; in case file is empty
7184 root n tt)
7185 ;; initialize buffer-local parsing vars
7186 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7187 js2-current-script-or-fn root
7188 js2-current-scope root
7189 js2-nesting-of-function 0
7190 js2-labeled-stmt nil
7191 js2-recorded-identifiers nil) ; for js2-highlight
7192 (while (/= (setq tt (js2-get-token)) js2-EOF)
7193 (if (= tt js2-FUNCTION)
7194 (progn
7195 (setq n (js2-parse-function (if js2-called-by-compile-function
7196 'FUNCTION_EXPRESSION
7197 'FUNCTION_STATEMENT))))
7198 ;; not a function - parse a statement
7199 (js2-unget-token)
7200 (setq n (js2-parse-statement)))
7201 ;; add function or statement to script
7202 (setq end (js2-node-end n))
7203 (js2-block-node-push root n))
7204 ;; add comments to root in lexical order
7205 (when js2-scanned-comments
7206 ;; if we find a comment beyond end of normal kids, use its end
7207 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7208 (dolist (comment js2-scanned-comments)
7209 (push comment (js2-ast-root-comments root))
7210 (js2-node-add-children root comment)))
7211 (setf (js2-node-len root) (- end pos))
7212 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7213 ;; Give extensions a chance to muck with things before highlighting starts.
7214 (let ((js2-additional-externs js2-additional-externs))
7215 (save-excursion
7216 (run-hooks 'js2-post-parse-callbacks))
7217 (js2-highlight-undeclared-vars))
7218 root))
7219
7220 (defun js2-function-parser ()
7221 (js2-get-token)
7222 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7223
7224 (defun js2-parse-function-closure-body (fn-node)
7225 "Parse a JavaScript 1.8 function closure body."
7226 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7227 (if js2-ts-hit-eof
7228 (js2-report-error "msg.no.brace.body" nil
7229 (js2-node-pos fn-node)
7230 (- js2-ts-cursor (js2-node-pos fn-node)))
7231 (js2-node-add-children fn-node
7232 (setf (js2-function-node-body fn-node)
7233 (js2-parse-expr t))))))
7234
7235 (defun js2-parse-function-body (fn-node)
7236 (js2-must-match js2-LC "msg.no.brace.body"
7237 (js2-node-pos fn-node)
7238 (- js2-ts-cursor (js2-node-pos fn-node)))
7239 (let ((pos (js2-current-token-beg)) ; LC position
7240 (pn (make-js2-block-node)) ; starts at LC position
7241 tt
7242 end)
7243 (incf js2-nesting-of-function)
7244 (unwind-protect
7245 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7246 (= tt js2-EOF)
7247 (= tt js2-RC)))
7248 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7249 (js2-parse-statement)
7250 (js2-get-token)
7251 (js2-parse-function 'FUNCTION_STATEMENT))))
7252 (decf js2-nesting-of-function))
7253 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7254 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7255 (setq end (js2-current-token-end)))
7256 (setf (js2-node-pos pn) pos
7257 (js2-node-len pn) (- end pos))
7258 (setf (js2-function-node-body fn-node) pn)
7259 (js2-node-add-children fn-node pn)
7260 pn))
7261
7262 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7263 "Declare and fontify destructuring parameters inside NODE.
7264 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7265 (cond
7266 ((js2-name-node-p node)
7267 (let (leftpos)
7268 (js2-define-symbol decl-type (js2-name-node-name node)
7269 node ignore-not-in-block)
7270 (when face
7271 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7272 (+ leftpos (js2-node-len node))
7273 face 'record))))
7274 ((js2-object-node-p node)
7275 (dolist (elem (js2-object-node-elems node))
7276 (js2-define-destruct-symbols
7277 (if (js2-object-prop-node-p elem)
7278 (js2-object-prop-node-right elem)
7279 ;; abbreviated destructuring {a, b}
7280 elem)
7281 decl-type face ignore-not-in-block)))
7282 ((js2-array-node-p node)
7283 (dolist (elem (js2-array-node-elems node))
7284 (when elem
7285 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7286 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7287 (js2-node-len node)))))
7288
7289 (defun js2-parse-function-params (fn-node pos)
7290 (if (js2-match-token js2-RP)
7291 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7292 (let (params len param default-found rest-param-at)
7293 (loop for tt = (js2-peek-token)
7294 do
7295 (cond
7296 ;; destructuring param
7297 ((or (= tt js2-LB) (= tt js2-LC))
7298 (js2-get-token)
7299 (when default-found
7300 (js2-report-error "msg.no.default.after.default.param"))
7301 (setq param (js2-parse-destruct-primary-expr))
7302 (js2-define-destruct-symbols param
7303 js2-LP
7304 'js2-function-param)
7305 (push param params))
7306 ;; variable name
7307 (t
7308 (when (and (>= js2-language-version 200)
7309 (js2-match-token js2-TRIPLEDOT)
7310 (not rest-param-at))
7311 ;; to report errors if there are more parameters
7312 (setq rest-param-at (length params)))
7313 (js2-must-match js2-NAME "msg.no.parm")
7314 (js2-record-face 'js2-function-param)
7315 (setq param (js2-create-name-node))
7316 (js2-define-symbol js2-LP (js2-current-token-string) param)
7317 ;; default parameter value
7318 (when (or (and default-found
7319 (not rest-param-at)
7320 (js2-must-match js2-ASSIGN
7321 "msg.no.default.after.default.param"
7322 (js2-node-pos param)
7323 (js2-node-len param)))
7324 (and (>= js2-language-version 200)
7325 (js2-match-token js2-ASSIGN)))
7326 (let* ((pos (js2-node-pos param))
7327 (tt (js2-current-token-type))
7328 (op-pos (- (js2-current-token-beg) pos))
7329 (left param)
7330 (right (js2-parse-assign-expr))
7331 (len (- (js2-node-end right) pos)))
7332 (setq param (make-js2-assign-node
7333 :type tt :pos pos :len len :op-pos op-pos
7334 :left left :right right)
7335 default-found t)
7336 (js2-node-add-children param left right)))
7337 (push param params)))
7338 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7339 (js2-report-error "msg.param.after.rest" nil
7340 (js2-node-pos param) (js2-node-len param)))
7341 while
7342 (js2-match-token js2-COMMA))
7343 (when (js2-must-match js2-RP "msg.no.paren.after.parms")
7344 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7345 (when rest-param-at
7346 (setf (js2-function-node-rest-p fn-node) t))
7347 (dolist (p params)
7348 (js2-node-add-children fn-node p)
7349 (push p (js2-function-node-params fn-node))))))
7350
7351 (defun js2-check-inconsistent-return-warning (fn-node name)
7352 "Possibly show inconsistent-return warning.
7353 Last token scanned is the close-curly for the function body."
7354 (when (and js2-mode-show-strict-warnings
7355 js2-strict-inconsistent-return-warning
7356 (not (js2-has-consistent-return-usage
7357 (js2-function-node-body fn-node))))
7358 ;; Have it extend from close-curly to bol or beginning of block.
7359 (let ((pos (save-excursion
7360 (goto-char (js2-current-token-end))
7361 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7362 (point-at-bol))))
7363 (end (js2-current-token-end)))
7364 (if (plusp (js2-name-node-length name))
7365 (js2-add-strict-warning "msg.no.return.value"
7366 (js2-name-node-name name) pos end)
7367 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7368
7369 (defun js2-parse-function (function-type)
7370 "Function parser. FUNCTION-TYPE is a symbol."
7371 (let ((pos (js2-current-token-beg)) ; start of 'function' keyword
7372 name name-beg name-end fn-node lp
7373 (synthetic-type function-type)
7374 member-expr-node)
7375 ;; parse function name, expression, or non-name (anonymous)
7376 (cond
7377 ;; function foo(...)
7378 ((js2-match-token js2-NAME)
7379 (setq name (js2-create-name-node t)
7380 name-beg (js2-current-token-beg)
7381 name-end (js2-current-token-end))
7382 (unless (js2-match-token js2-LP)
7383 (when js2-allow-member-expr-as-function-name
7384 ;; function foo.bar(...)
7385 (setq member-expr-node name
7386 name nil
7387 member-expr-node (js2-parse-member-expr-tail
7388 nil member-expr-node)))
7389 (js2-must-match js2-LP "msg.no.paren.parms")))
7390 ((js2-match-token js2-LP)
7391 nil) ; anonymous function: leave name as null
7392 (t
7393 ;; function random-member-expr(...)
7394 (when js2-allow-member-expr-as-function-name
7395 ;; Note that memberExpr can not start with '(' like
7396 ;; in function (1+2).toString(), because 'function (' already
7397 ;; processed as anonymous function
7398 (setq member-expr-node (js2-parse-member-expr)))
7399 (js2-must-match js2-LP "msg.no.paren.parms")))
7400 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7401 (setq lp (js2-current-token-beg)))
7402 (if member-expr-node
7403 (progn
7404 (setq synthetic-type 'FUNCTION_EXPRESSION)
7405 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7406 (if name
7407 (js2-set-face name-beg name-end
7408 'font-lock-function-name-face 'record)))
7409 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7410 (plusp (js2-name-node-length name)))
7411 ;; Function statements define a symbol in the enclosing scope
7412 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7413 (setf fn-node (make-js2-function-node :pos pos
7414 :name name
7415 :form function-type
7416 :lp (if lp (- lp pos))))
7417 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7418 ;; 1. Nested functions are not affected by the dynamic scope flag
7419 ;; as dynamic scope is already a parent of their scope.
7420 ;; 2. Functions defined under the with statement also immune to
7421 ;; this setup, in which case dynamic scope is ignored in favor
7422 ;; of the with object.
7423 (setf (js2-function-node-ignore-dynamic fn-node) t))
7424 ;; dynamically bind all the per-function variables
7425 (let ((js2-current-script-or-fn fn-node)
7426 (js2-current-scope fn-node)
7427 (js2-nesting-of-with 0)
7428 (js2-end-flags 0)
7429 js2-label-set
7430 js2-loop-set
7431 js2-loop-and-switch-set)
7432 (js2-parse-function-params fn-node pos)
7433 (if (and (>= js2-language-version 180)
7434 (/= (js2-peek-token) js2-LC))
7435 (js2-parse-function-closure-body fn-node)
7436 (js2-parse-function-body fn-node))
7437 (if name
7438 (js2-node-add-children fn-node name))
7439 (js2-check-inconsistent-return-warning fn-node name)
7440 ;; Function expressions define a name only in the body of the
7441 ;; function, and only if not hidden by a parameter name
7442 (if (and name
7443 (eq synthetic-type 'FUNCTION_EXPRESSION)
7444 (null (js2-scope-get-symbol js2-current-scope
7445 (js2-name-node-name name))))
7446 (js2-define-symbol js2-FUNCTION
7447 (js2-name-node-name name)
7448 fn-node))
7449 (if (and name
7450 (not (eq function-type 'FUNCTION_EXPRESSION)))
7451 (js2-record-imenu-functions fn-node)))
7452 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7453 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7454 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7455 ;; We wait until after parsing the function to set its parent scope,
7456 ;; since `js2-define-symbol' needs the defining-scope check to stop
7457 ;; at the function boundary when checking for redeclarations.
7458 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7459 fn-node))
7460
7461 (defun js2-parse-statements (&optional parent)
7462 "Parse a statement list. Last token consumed must be js2-LC.
7463
7464 PARENT can be a `js2-block-node', in which case the statements are
7465 appended to PARENT. Otherwise a new `js2-block-node' is created
7466 and returned.
7467
7468 This function does not match the closing js2-RC: the caller
7469 matches the RC so it can provide a suitable error message if not
7470 matched. This means it's up to the caller to set the length of
7471 the node to include the closing RC. The node start pos is set to
7472 the absolute buffer start position, and the caller should fix it
7473 up to be relative to the parent node. All children of this block
7474 node are given relative start positions and correct lengths."
7475 (let ((pn (or parent (make-js2-block-node)))
7476 tt)
7477 (setf (js2-node-pos pn) (js2-current-token-beg))
7478 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7479 (/= tt js2-RC))
7480 (js2-block-node-push pn (js2-parse-statement)))
7481 pn))
7482
7483 (defun js2-parse-statement ()
7484 (let (tt pn beg end)
7485 ;; coarse-grained user-interrupt check - needs work
7486 (and js2-parse-interruptable-p
7487 (zerop (% (incf js2-parse-stmt-count)
7488 js2-statements-per-pause))
7489 (input-pending-p)
7490 (throw 'interrupted t))
7491 (setq pn (js2-statement-helper))
7492 ;; no-side-effects warning check
7493 (unless (js2-node-has-side-effects pn)
7494 (setq end (js2-node-end pn))
7495 (save-excursion
7496 (goto-char end)
7497 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7498 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7499 pn))
7500
7501 ;; These correspond to the switch cases in Parser.statementHelper
7502 (defconst js2-parsers
7503 (let ((parsers (make-vector js2-num-tokens
7504 #'js2-parse-expr-stmt)))
7505 (aset parsers js2-BREAK #'js2-parse-break)
7506 (aset parsers js2-CONST #'js2-parse-const-var)
7507 (aset parsers js2-CONTINUE #'js2-parse-continue)
7508 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7509 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7510 (aset parsers js2-DO #'js2-parse-do)
7511 (aset parsers js2-FOR #'js2-parse-for)
7512 (aset parsers js2-FUNCTION #'js2-function-parser)
7513 (aset parsers js2-IF #'js2-parse-if)
7514 (aset parsers js2-LC #'js2-parse-block)
7515 (aset parsers js2-LET #'js2-parse-let-stmt)
7516 (aset parsers js2-NAME #'js2-parse-name-or-label)
7517 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7518 (aset parsers js2-SEMI #'js2-parse-semi)
7519 (aset parsers js2-SWITCH #'js2-parse-switch)
7520 (aset parsers js2-THROW #'js2-parse-throw)
7521 (aset parsers js2-TRY #'js2-parse-try)
7522 (aset parsers js2-VAR #'js2-parse-const-var)
7523 (aset parsers js2-WHILE #'js2-parse-while)
7524 (aset parsers js2-WITH #'js2-parse-with)
7525 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7526 parsers)
7527 "A vector mapping token types to parser functions.")
7528
7529 (defun js2-parse-warn-missing-semi (beg end)
7530 (and js2-mode-show-strict-warnings
7531 js2-strict-missing-semi-warning
7532 (js2-add-strict-warning
7533 "msg.missing.semi" nil
7534 ;; back up to beginning of statement or line
7535 (max beg (save-excursion
7536 (goto-char end)
7537 (point-at-bol)))
7538 end)))
7539
7540 (defconst js2-no-semi-insertion
7541 (list js2-IF
7542 js2-SWITCH
7543 js2-WHILE
7544 js2-DO
7545 js2-FOR
7546 js2-TRY
7547 js2-WITH
7548 js2-LC
7549 js2-ERROR
7550 js2-SEMI
7551 js2-FUNCTION)
7552 "List of tokens that don't do automatic semicolon insertion.")
7553
7554 (defconst js2-autoinsert-semi-and-warn
7555 (list js2-ERROR js2-EOF js2-RC))
7556
7557 (defun js2-statement-helper ()
7558 (let* ((tt (js2-get-token))
7559 (first-tt tt)
7560 (beg (js2-current-token-beg))
7561 (parser (if (= tt js2-ERROR)
7562 #'js2-parse-semi
7563 (aref js2-parsers tt)))
7564 pn)
7565 ;; If the statement is set, then it's been told its label by now.
7566 (and js2-labeled-stmt
7567 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7568 (setq js2-labeled-stmt nil))
7569 (setq pn (funcall parser))
7570 ;; Don't do auto semi insertion for certain statement types.
7571 (unless (or (memq first-tt js2-no-semi-insertion)
7572 (js2-labeled-stmt-node-p pn))
7573 (js2-auto-insert-semicolon pn))
7574 pn))
7575
7576 (defun js2-auto-insert-semicolon (pn)
7577 (let* ((tt (js2-get-token))
7578 (pos (js2-node-pos pn)))
7579 (cond
7580 ((= tt js2-SEMI)
7581 ;; extend the node bounds to include the semicolon.
7582 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
7583 ((memq tt js2-autoinsert-semi-and-warn)
7584 (js2-unget-token) ; Not ';', do not consume.
7585 ;; Autoinsert ;
7586 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7587 (t
7588 (if (not (js2-token-follows-eol-p (js2-current-token)))
7589 ;; Report error if no EOL or autoinsert ';' otherwise
7590 (js2-report-error "msg.no.semi.stmt")
7591 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7592 (js2-unget-token) ; Not ';', do not consume.
7593 ))))
7594
7595 (defun js2-parse-condition ()
7596 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7597 The parens are discarded and the expression node is returned.
7598 The `pos' field of the return value is set to an absolute position
7599 that must be fixed up by the caller.
7600 Return value is a list (EXPR LP RP), with absolute paren positions."
7601 (let (pn lp rp)
7602 (if (js2-must-match js2-LP "msg.no.paren.cond")
7603 (setq lp (js2-current-token-beg)))
7604 (setq pn (js2-parse-expr))
7605 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7606 (setq rp (js2-current-token-beg)))
7607 ;; Report strict warning on code like "if (a = 7) ..."
7608 (if (and js2-strict-cond-assign-warning
7609 (js2-assign-node-p pn))
7610 (js2-add-strict-warning "msg.equal.as.assign" nil
7611 (js2-node-pos pn)
7612 (+ (js2-node-pos pn)
7613 (js2-node-len pn))))
7614 (list pn lp rp)))
7615
7616 (defun js2-parse-if ()
7617 "Parser for if-statement. Last matched token must be js2-IF."
7618 (let ((pos (js2-current-token-beg))
7619 cond if-true if-false else-pos end pn)
7620 (setq cond (js2-parse-condition)
7621 if-true (js2-parse-statement)
7622 if-false (if (js2-match-token js2-ELSE)
7623 (progn
7624 (setq else-pos (- (js2-current-token-beg) pos))
7625 (js2-parse-statement)))
7626 end (js2-node-end (or if-false if-true))
7627 pn (make-js2-if-node :pos pos
7628 :len (- end pos)
7629 :condition (car cond)
7630 :then-part if-true
7631 :else-part if-false
7632 :else-pos else-pos
7633 :lp (js2-relpos (second cond) pos)
7634 :rp (js2-relpos (third cond) pos)))
7635 (js2-node-add-children pn (car cond) if-true if-false)
7636 pn))
7637
7638 (defun js2-parse-switch ()
7639 "Parser for if-statement. Last matched token must be js2-SWITCH."
7640 (let ((pos (js2-current-token-beg))
7641 tt pn discriminant has-default case-expr case-node
7642 case-pos cases stmt lp rp)
7643 (if (js2-must-match js2-LP "msg.no.paren.switch")
7644 (setq lp (js2-current-token-beg)))
7645 (setq discriminant (js2-parse-expr)
7646 pn (make-js2-switch-node :discriminant discriminant
7647 :pos pos
7648 :lp (js2-relpos lp pos)))
7649 (js2-node-add-children pn discriminant)
7650 (js2-enter-switch pn)
7651 (unwind-protect
7652 (progn
7653 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7654 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
7655 (js2-must-match js2-LC "msg.no.brace.switch")
7656 (catch 'break
7657 (while t
7658 (setq tt (js2-next-token)
7659 case-pos (js2-current-token-beg))
7660 (cond
7661 ((= tt js2-RC)
7662 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
7663 (throw 'break nil)) ; done
7664 ((= tt js2-CASE)
7665 (setq case-expr (js2-parse-expr))
7666 (js2-must-match js2-COLON "msg.no.colon.case"))
7667 ((= tt js2-DEFAULT)
7668 (if has-default
7669 (js2-report-error "msg.double.switch.default"))
7670 (setq has-default t
7671 case-expr nil)
7672 (js2-must-match js2-COLON "msg.no.colon.case"))
7673 (t
7674 (js2-report-error "msg.bad.switch")
7675 (throw 'break nil)))
7676 (setq case-node (make-js2-case-node :pos case-pos
7677 :len (- (js2-current-token-end) case-pos)
7678 :expr case-expr))
7679 (js2-node-add-children case-node case-expr)
7680 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7681 (/= tt js2-CASE)
7682 (/= tt js2-DEFAULT)
7683 (/= tt js2-EOF))
7684 (setf stmt (js2-parse-statement)
7685 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7686 (js2-block-node-push case-node stmt))
7687 (push case-node cases)))
7688 ;; add cases last, as pushing reverses the order to be correct
7689 (dolist (kid cases)
7690 (js2-node-add-children pn kid)
7691 (push kid (js2-switch-node-cases pn)))
7692 pn) ; return value
7693 (js2-exit-switch))))
7694
7695 (defun js2-parse-while ()
7696 "Parser for while-statement. Last matched token must be js2-WHILE."
7697 (let ((pos (js2-current-token-beg))
7698 (pn (make-js2-while-node))
7699 cond body)
7700 (js2-enter-loop pn)
7701 (unwind-protect
7702 (progn
7703 (setf cond (js2-parse-condition)
7704 (js2-while-node-condition pn) (car cond)
7705 body (js2-parse-statement)
7706 (js2-while-node-body pn) body
7707 (js2-node-len pn) (- (js2-node-end body) pos)
7708 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7709 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7710 (js2-node-add-children pn body (car cond)))
7711 (js2-exit-loop))
7712 pn))
7713
7714 (defun js2-parse-do ()
7715 "Parser for do-statement. Last matched token must be js2-DO."
7716 (let ((pos (js2-current-token-beg))
7717 (pn (make-js2-do-node))
7718 cond body end)
7719 (js2-enter-loop pn)
7720 (unwind-protect
7721 (progn
7722 (setq body (js2-parse-statement))
7723 (js2-must-match js2-WHILE "msg.no.while.do")
7724 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
7725 cond (js2-parse-condition)
7726 (js2-do-node-condition pn) (car cond)
7727 (js2-do-node-body pn) body
7728 end js2-ts-cursor
7729 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7730 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7731 (js2-node-add-children pn (car cond) body))
7732 (js2-exit-loop))
7733 ;; Always auto-insert semicolon to follow SpiderMonkey:
7734 ;; It is required by ECMAScript but is ignored by the rest of
7735 ;; world; see bug 238945
7736 (if (js2-match-token js2-SEMI)
7737 (setq end js2-ts-cursor))
7738 (setf (js2-node-len pn) (- end pos))
7739 pn))
7740
7741 (defun js2-parse-for ()
7742 "Parser for for-statement. Last matched token must be js2-FOR.
7743 Parses for, for-in, and for each-in statements."
7744 (let ((for-pos (js2-current-token-beg))
7745 pn is-for-each is-for-in-or-of is-for-of
7746 in-pos each-pos tmp-pos
7747 init ; Node init is also foo in 'foo in object'
7748 cond ; Node cond is also object in 'foo in object'
7749 incr ; 3rd section of for-loop initializer
7750 body tt lp rp)
7751 ;; See if this is a for each () instead of just a for ()
7752 (when (js2-match-token js2-NAME)
7753 (if (string= "each" (js2-current-token-string))
7754 (progn
7755 (setq is-for-each t
7756 each-pos (- (js2-current-token-beg) for-pos)) ; relative
7757 (js2-record-face 'font-lock-keyword-face))
7758 (js2-report-error "msg.no.paren.for")))
7759 (if (js2-must-match js2-LP "msg.no.paren.for")
7760 (setq lp (- (js2-current-token-beg) for-pos)))
7761 (setq tt (js2-get-token))
7762 ;; 'for' makes local scope
7763 (js2-push-scope (make-js2-scope))
7764 (unwind-protect
7765 ;; parse init clause
7766 (let ((js2-in-for-init t)) ; set as dynamic variable
7767 (cond
7768 ((= tt js2-SEMI)
7769 (js2-unget-token)
7770 (setq init (make-js2-empty-expr-node)))
7771 ((or (= tt js2-VAR) (= tt js2-LET))
7772 (setq init (js2-parse-variables tt (js2-current-token-beg))))
7773 (t
7774 (js2-unget-token)
7775 (setq init (js2-parse-expr)))))
7776 (if (or (js2-match-token js2-IN)
7777 (and (>= js2-language-version 200)
7778 (js2-match-contextual-kwd "of")
7779 (setq is-for-of t)))
7780 (setq is-for-in-or-of t
7781 in-pos (- (js2-current-token-beg) for-pos)
7782 ;; scope of iteration target object is not the scope we've created above.
7783 ;; stash current scope temporary.
7784 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7785 (js2-parse-expr))) ; object over which we're iterating
7786 ;; else ordinary for loop - parse cond and incr
7787 (js2-must-match js2-SEMI "msg.no.semi.for")
7788 (setq cond (if (= (js2-peek-token) js2-SEMI)
7789 (make-js2-empty-expr-node) ; no loop condition
7790 (js2-parse-expr)))
7791 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7792 (setq tmp-pos (js2-current-token-end)
7793 incr (if (= (js2-peek-token) js2-RP)
7794 (make-js2-empty-expr-node :pos tmp-pos)
7795 (js2-parse-expr))))
7796 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7797 (setq rp (- (js2-current-token-beg) for-pos)))
7798 (if (not is-for-in-or-of)
7799 (setq pn (make-js2-for-node :init init
7800 :condition cond
7801 :update incr
7802 :lp lp
7803 :rp rp))
7804 ;; cond could be null if 'in obj' got eaten by the init node.
7805 (if (js2-infix-node-p init)
7806 ;; it was (foo in bar) instead of (var foo in bar)
7807 (setq cond (js2-infix-node-right init)
7808 init (js2-infix-node-left init))
7809 (if (and (js2-var-decl-node-p init)
7810 (> (length (js2-var-decl-node-kids init)) 1))
7811 (js2-report-error "msg.mult.index")))
7812 (setq pn (make-js2-for-in-node :iterator init
7813 :object cond
7814 :in-pos in-pos
7815 :foreach-p is-for-each
7816 :each-pos each-pos
7817 :forof-p is-for-of
7818 :lp lp
7819 :rp rp)))
7820 (unwind-protect
7821 (progn
7822 (js2-enter-loop pn)
7823 ;; We have to parse the body -after- creating the loop node,
7824 ;; so that the loop node appears in the js2-loop-set, allowing
7825 ;; break/continue statements to find the enclosing loop.
7826 (setf body (js2-parse-statement)
7827 (js2-loop-node-body pn) body
7828 (js2-node-pos pn) for-pos
7829 (js2-node-len pn) (- (js2-node-end body) for-pos))
7830 (js2-node-add-children pn init cond incr body))
7831 ;; finally
7832 (js2-exit-loop))
7833 (js2-pop-scope))
7834 pn))
7835
7836 (defun js2-parse-try ()
7837 "Parser for try-statement. Last matched token must be js2-TRY."
7838 (let ((try-pos (js2-current-token-beg))
7839 try-end
7840 try-block
7841 catch-blocks
7842 finally-block
7843 saw-default-catch
7844 peek
7845 param
7846 catch-cond
7847 catch-node
7848 guard-kwd
7849 catch-pos
7850 finally-pos
7851 pn
7852 block
7853 lp
7854 rp)
7855 (if (/= (js2-peek-token) js2-LC)
7856 (js2-report-error "msg.no.brace.try"))
7857 (setq try-block (js2-parse-statement)
7858 try-end (js2-node-end try-block)
7859 peek (js2-peek-token))
7860 (cond
7861 ((= peek js2-CATCH)
7862 (while (js2-match-token js2-CATCH)
7863 (setq catch-pos (js2-current-token-beg)
7864 guard-kwd nil
7865 catch-cond nil
7866 lp nil
7867 rp nil)
7868 (if saw-default-catch
7869 (js2-report-error "msg.catch.unreachable"))
7870 (if (js2-must-match js2-LP "msg.no.paren.catch")
7871 (setq lp (- (js2-current-token-beg) catch-pos)))
7872 (js2-push-scope (make-js2-scope))
7873 (let ((tt (js2-peek-token)))
7874 (cond
7875 ;; destructuring pattern
7876 ;; catch ({ message, file }) { ... }
7877 ((or (= tt js2-LB) (= tt js2-LC))
7878 (js2-get-token)
7879 (setq param (js2-parse-destruct-primary-expr))
7880 (js2-define-destruct-symbols param js2-LET nil))
7881 ;; simple name
7882 (t
7883 (js2-must-match js2-NAME "msg.bad.catchcond")
7884 (setq param (js2-create-name-node))
7885 (js2-define-symbol js2-LET (js2-current-token-string) param))))
7886 ;; pattern guard
7887 (if (js2-match-token js2-IF)
7888 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
7889 catch-cond (js2-parse-expr))
7890 (setq saw-default-catch t))
7891 (if (js2-must-match js2-RP "msg.bad.catchcond")
7892 (setq rp (- (js2-current-token-beg) catch-pos)))
7893 (js2-must-match js2-LC "msg.no.brace.catchblock")
7894 (setq block (js2-parse-statements)
7895 try-end (js2-node-end block)
7896 catch-node (make-js2-catch-node :pos catch-pos
7897 :param param
7898 :guard-expr catch-cond
7899 :guard-kwd guard-kwd
7900 :block block
7901 :lp lp
7902 :rp rp))
7903 (js2-pop-scope)
7904 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7905 (setq try-end (js2-current-token-beg)))
7906 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7907 (js2-node-len catch-node) (- try-end catch-pos))
7908 (js2-node-add-children catch-node param catch-cond block)
7909 (push catch-node catch-blocks)))
7910 ((/= peek js2-FINALLY)
7911 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7912 (js2-node-pos try-block)
7913 (- (setq try-end (js2-node-end try-block))
7914 (js2-node-pos try-block)))))
7915 (when (js2-match-token js2-FINALLY)
7916 (setq finally-pos (js2-current-token-beg)
7917 block (js2-parse-statement)
7918 try-end (js2-node-end block)
7919 finally-block (make-js2-finally-node :pos finally-pos
7920 :len (- try-end finally-pos)
7921 :body block))
7922 (js2-node-add-children finally-block block))
7923 (setq pn (make-js2-try-node :pos try-pos
7924 :len (- try-end try-pos)
7925 :try-block try-block
7926 :finally-block finally-block))
7927 (js2-node-add-children pn try-block finally-block)
7928 ;; push them onto the try-node, which reverses and corrects their order
7929 (dolist (cb catch-blocks)
7930 (js2-node-add-children pn cb)
7931 (push cb (js2-try-node-catch-clauses pn)))
7932 pn))
7933
7934 (defun js2-parse-throw ()
7935 "Parser for throw-statement. Last matched token must be js2-THROW."
7936 (let ((pos (js2-current-token-beg))
7937 expr pn)
7938 (if (= (js2-peek-token-or-eol) js2-EOL)
7939 ;; ECMAScript does not allow new lines before throw expression,
7940 ;; see bug 256617
7941 (js2-report-error "msg.bad.throw.eol"))
7942 (setq expr (js2-parse-expr)
7943 pn (make-js2-throw-node :pos pos
7944 :len (- (js2-node-end expr) pos)
7945 :expr expr))
7946 (js2-node-add-children pn expr)
7947 pn))
7948
7949 (defun js2-match-jump-label-name (label-name)
7950 "If break/continue specified a label, return that label's labeled stmt.
7951 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
7952 does not match an existing label, reports an error and returns nil."
7953 (let ((bundle (cdr (assoc label-name js2-label-set))))
7954 (if (null bundle)
7955 (js2-report-error "msg.undef.label"))
7956 bundle))
7957
7958 (defun js2-parse-break ()
7959 "Parser for break-statement. Last matched token must be js2-BREAK."
7960 (let ((pos (js2-current-token-beg))
7961 (end (js2-current-token-end))
7962 break-target ; statement to break from
7963 break-label ; in "break foo", name-node representing the foo
7964 labels ; matching labeled statement to break to
7965 pn)
7966 (when (eq (js2-peek-token-or-eol) js2-NAME)
7967 (js2-get-token)
7968 (setq break-label (js2-create-name-node)
7969 end (js2-node-end break-label)
7970 ;; matchJumpLabelName only matches if there is one
7971 labels (js2-match-jump-label-name (js2-current-token-string))
7972 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
7973 (unless (or break-target break-label)
7974 ;; no break target specified - try for innermost enclosing loop/switch
7975 (if (null js2-loop-and-switch-set)
7976 (unless break-label
7977 (js2-report-error "msg.bad.break" nil pos (length "break")))
7978 (setq break-target (car js2-loop-and-switch-set))))
7979 (setq pn (make-js2-break-node :pos pos
7980 :len (- end pos)
7981 :label break-label
7982 :target break-target))
7983 (js2-node-add-children pn break-label) ; but not break-target
7984 pn))
7985
7986 (defun js2-parse-continue ()
7987 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
7988 (let ((pos (js2-current-token-beg))
7989 (end (js2-current-token-end))
7990 label ; optional user-specified label, a `js2-name-node'
7991 labels ; current matching labeled stmt, if any
7992 target ; the `js2-loop-node' target of this continue stmt
7993 pn)
7994 (when (= (js2-peek-token-or-eol) js2-NAME)
7995 (js2-get-token)
7996 (setq label (js2-create-name-node)
7997 end (js2-node-end label)
7998 ;; matchJumpLabelName only matches if there is one
7999 labels (js2-match-jump-label-name (js2-current-token-string))))
8000 (cond
8001 ((null labels) ; no current label to go to
8002 (if (null js2-loop-set) ; no loop to continue to
8003 (js2-report-error "msg.continue.outside" nil pos
8004 (length "continue"))
8005 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8006 (t
8007 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8008 (setq target (js2-labeled-stmt-node-stmt labels))
8009 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8010 (setq pn (make-js2-continue-node :pos pos
8011 :len (- end pos)
8012 :label label
8013 :target target))
8014 (js2-node-add-children pn label) ; but not target - it's not our child
8015 pn))
8016
8017 (defun js2-parse-with ()
8018 "Parser for with-statement. Last matched token must be js2-WITH."
8019 (let ((pos (js2-current-token-beg))
8020 obj body pn lp rp)
8021 (if (js2-must-match js2-LP "msg.no.paren.with")
8022 (setq lp (js2-current-token-beg)))
8023 (setq obj (js2-parse-expr))
8024 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8025 (setq rp (js2-current-token-beg)))
8026 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8027 (setq body (js2-parse-statement)))
8028 (setq pn (make-js2-with-node :pos pos
8029 :len (- (js2-node-end body) pos)
8030 :object obj
8031 :body body
8032 :lp (js2-relpos lp pos)
8033 :rp (js2-relpos rp pos)))
8034 (js2-node-add-children pn obj body)
8035 pn))
8036
8037 (defun js2-parse-const-var ()
8038 "Parser for var- or const-statement.
8039 Last matched token must be js2-CONST or js2-VAR."
8040 (let ((tt (js2-current-token-type))
8041 (pos (js2-current-token-beg))
8042 expr pn)
8043 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8044 pn (make-js2-expr-stmt-node :pos pos
8045 :len (- (js2-node-end expr) pos)
8046 :expr expr))
8047 (js2-node-add-children pn expr)
8048 pn))
8049
8050 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8051 (let ((pn (make-js2-expr-stmt-node :pos pos
8052 :len (js2-node-len expr)
8053 :type (if (js2-inside-function)
8054 js2-EXPR_VOID
8055 js2-EXPR_RESULT)
8056 :expr expr)))
8057 (if add-child
8058 (js2-node-add-children pn expr))
8059 pn))
8060
8061 (defun js2-parse-let-stmt ()
8062 "Parser for let-statement. Last matched token must be js2-LET."
8063 (let ((pos (js2-current-token-beg))
8064 expr pn)
8065 (if (= (js2-peek-token) js2-LP)
8066 ;; let expression in statement context
8067 (setq expr (js2-parse-let pos 'statement)
8068 pn (js2-wrap-with-expr-stmt pos expr t))
8069 ;; else we're looking at a statement like let x=6, y=7;
8070 (setf expr (js2-parse-variables js2-LET pos)
8071 pn (js2-wrap-with-expr-stmt pos expr t)
8072 (js2-node-type pn) js2-EXPR_RESULT))
8073 pn))
8074
8075 (defun js2-parse-ret-yield ()
8076 (js2-parse-return-or-yield (js2-current-token-type) nil))
8077
8078 (defconst js2-parse-return-stmt-enders
8079 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8080
8081 (defsubst js2-now-all-set (before after mask)
8082 "Return whether or not the bits in the mask have changed to all set.
8083 BEFORE is bits before change, AFTER is bits after change, and MASK is
8084 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8085 but not BEFORE."
8086 (and (/= (logand before mask) mask)
8087 (= (logand after mask) mask)))
8088
8089 (defun js2-parse-return-or-yield (tt expr-context)
8090 (let ((pos (js2-current-token-beg))
8091 (end (js2-current-token-end))
8092 (before js2-end-flags)
8093 (inside-function (js2-inside-function))
8094 e ret name)
8095 (unless inside-function
8096 (js2-report-error (if (eq tt js2-RETURN)
8097 "msg.bad.return"
8098 "msg.bad.yield")))
8099 ;; This is ugly, but we don't want to require a semicolon.
8100 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8101 (setq e (js2-parse-expr)
8102 end (js2-node-end e)))
8103 (cond
8104 ((eq tt js2-RETURN)
8105 (js2-set-flag js2-end-flags (if (null e)
8106 js2-end-returns
8107 js2-end-returns-value))
8108 (setq ret (make-js2-return-node :pos pos
8109 :len (- end pos)
8110 :retval e))
8111 (js2-node-add-children ret e)
8112 ;; See if we need a strict mode warning.
8113 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8114 ;; more thorough and accurate than this before/after flag check.
8115 ;; E.g. if there's a finally-block that always returns, we shouldn't
8116 ;; show a warning generated by inconsistent returns in the catch blocks.
8117 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8118 ;; so we know which returns/yields to highlight, and we should get rid of
8119 ;; all the checking in `js2-parse-return-or-yield'.
8120 (if (and js2-strict-inconsistent-return-warning
8121 (js2-now-all-set before js2-end-flags
8122 (logior js2-end-returns js2-end-returns-value)))
8123 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8124 (t
8125 (unless (js2-inside-function)
8126 (js2-report-error "msg.bad.yield"))
8127 (js2-set-flag js2-end-flags js2-end-yields)
8128 (setq ret (make-js2-yield-node :pos pos
8129 :len (- end pos)
8130 :value e))
8131 (js2-node-add-children ret e)
8132 (unless expr-context
8133 (setq e ret
8134 ret (js2-wrap-with-expr-stmt pos e t))
8135 (js2-set-requires-activation)
8136 (js2-set-is-generator))))
8137 ;; see if we are mixing yields and value returns.
8138 (when (and inside-function
8139 (js2-now-all-set before js2-end-flags
8140 (logior js2-end-yields js2-end-returns-value)))
8141 (setq name (js2-function-name js2-current-script-or-fn))
8142 (if (zerop (length name))
8143 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8144 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8145 ret))
8146
8147 (defun js2-parse-debugger ()
8148 (make-js2-keyword-node :type js2-DEBUGGER))
8149
8150 (defun js2-parse-block ()
8151 "Parser for a curly-delimited statement block.
8152 Last token matched must be `js2-LC'."
8153 (let ((pos (js2-current-token-beg))
8154 (pn (make-js2-scope)))
8155 (js2-push-scope pn)
8156 (unwind-protect
8157 (progn
8158 (js2-parse-statements pn)
8159 (js2-must-match js2-RC "msg.no.brace.block")
8160 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8161 (js2-pop-scope))
8162 pn))
8163
8164 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8165 (defun js2-parse-semi ()
8166 "Parse a statement or handle an error.
8167 Current token type is `js2-SEMI' or `js2-ERROR'."
8168 (let ((tt (js2-current-token-type)) pos len)
8169 (if (eq tt js2-SEMI)
8170 (make-js2-empty-expr-node :len 1)
8171 (setq pos (js2-current-token-beg)
8172 len (- (js2-current-token-beg) pos))
8173 (js2-report-error "msg.syntax" nil pos len)
8174 (make-js2-error-node :pos pos :len len))))
8175
8176 (defun js2-parse-default-xml-namespace ()
8177 "Parse a `default xml namespace = <expr>' e4x statement."
8178 (let ((pos (js2-current-token-beg))
8179 end len expr unary es)
8180 (js2-must-have-xml)
8181 (js2-set-requires-activation)
8182 (setq len (- js2-ts-cursor pos))
8183 (unless (and (js2-match-token js2-NAME)
8184 (string= (js2-current-token-string) "xml"))
8185 (js2-report-error "msg.bad.namespace" nil pos len))
8186 (unless (and (js2-match-token js2-NAME)
8187 (string= (js2-current-token-string) "namespace"))
8188 (js2-report-error "msg.bad.namespace" nil pos len))
8189 (unless (js2-match-token js2-ASSIGN)
8190 (js2-report-error "msg.bad.namespace" nil pos len))
8191 (setq expr (js2-parse-expr)
8192 end (js2-node-end expr)
8193 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8194 :pos pos
8195 :len (- end pos)
8196 :operand expr))
8197 (js2-node-add-children unary expr)
8198 (make-js2-expr-stmt-node :pos pos
8199 :len (- end pos)
8200 :expr unary)))
8201
8202 (defun js2-record-label (label bundle)
8203 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8204 (js2-get-token)
8205 (let ((name (js2-label-node-name label))
8206 labeled-stmt
8207 dup)
8208 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8209 ;; flag both labels if possible when used in editing mode
8210 (if (and js2-parse-ide-mode
8211 (setq dup (js2-get-label-by-name labeled-stmt name)))
8212 (js2-report-error "msg.dup.label" nil
8213 (js2-node-abs-pos dup) (js2-node-len dup)))
8214 (js2-report-error "msg.dup.label" nil
8215 (js2-node-pos label) (js2-node-len label)))
8216 (js2-labeled-stmt-node-add-label bundle label)
8217 (js2-node-add-children bundle label)
8218 ;; Add one reference to the bundle per label in `js2-label-set'
8219 (push (cons name bundle) js2-label-set)))
8220
8221 (defun js2-parse-name-or-label ()
8222 "Parser for identifier or label. Last token matched must be js2-NAME.
8223 Called when we found a name in a statement context. If it's a label, we gather
8224 up any following labels and the next non-label statement into a
8225 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8226 expression and return it wrapped in a `js2-expr-stmt-node'."
8227 (let ((pos (js2-current-token-beg))
8228 (end (js2-current-token-end))
8229 expr stmt pn bundle
8230 (continue t))
8231 ;; set check for label and call down to `js2-parse-primary-expr'
8232 (setq expr (js2-maybe-parse-label))
8233 (if (null expr)
8234 ;; Parse the non-label expression and wrap with expression stmt.
8235 (setq pn (js2-wrap-with-expr-stmt pos (js2-parse-expr) t))
8236 ;; else parsed a label
8237 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8238 (js2-record-label expr bundle)
8239 ;; look for more labels
8240 (while (and continue (= (js2-get-token) js2-NAME))
8241 (if (setq expr (js2-maybe-parse-label))
8242 (js2-record-label expr bundle)
8243 (setq expr (js2-parse-expr)
8244 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8245 continue nil)
8246 (js2-auto-insert-semicolon stmt)))
8247 ;; no more labels; now parse the labeled statement
8248 (unwind-protect
8249 (unless stmt
8250 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8251 (setq stmt (js2-statement-helper))))
8252 ;; remove the labels for this statement from the global set
8253 (dolist (label (js2-labeled-stmt-node-labels bundle))
8254 (setq js2-label-set (remove label js2-label-set))))
8255 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8256 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8257 (js2-node-add-children bundle stmt)
8258 bundle)))
8259
8260 (defun js2-maybe-parse-label ()
8261 (assert (= (js2-current-token-type) js2-NAME))
8262 (let (label-pos
8263 (next-tt (js2-get-token))
8264 (label-end (js2-current-token-end)))
8265 ;; Do not consume colon, it is used as unwind indicator
8266 ;; to return to statementHelper.
8267 (js2-unget-token)
8268 (if (= next-tt js2-COLON)
8269 (prog2
8270 (setq label-pos (js2-current-token-beg))
8271 (make-js2-label-node :pos label-pos
8272 :len (- label-end label-pos)
8273 :name (js2-current-token-string))
8274 (js2-set-face label-pos
8275 label-end
8276 'font-lock-variable-name-face 'record))
8277 ;; Backtrack from the name token, too.
8278 (js2-unget-token)
8279 nil)))
8280
8281 (defun js2-parse-expr-stmt ()
8282 "Default parser in statement context, if no recognized statement found."
8283 (js2-wrap-with-expr-stmt (js2-current-token-beg)
8284 (progn
8285 (js2-unget-token)
8286 (js2-parse-expr)) t))
8287
8288 (defun js2-parse-variables (decl-type pos)
8289 "Parse a comma-separated list of variable declarations.
8290 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8291
8292 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8293 For 'var' or 'const', the keyword should be the token last scanned.
8294
8295 POS is the position where the node should start. It's sometimes the
8296 var/const/let keyword, and other times the beginning of the first token
8297 in the first variable declaration.
8298
8299 Returns the parsed `js2-var-decl-node' expression node."
8300 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8301 :pos pos))
8302 destructuring kid-pos tt init name end nbeg nend vi
8303 (continue t))
8304 ;; Example:
8305 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8306 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8307 ;; var {a, b} = baz;
8308 (while continue
8309 (setq destructuring nil
8310 name nil
8311 tt (js2-get-token)
8312 kid-pos (js2-current-token-beg)
8313 end (js2-current-token-end)
8314 init nil)
8315 (if (or (= tt js2-LB) (= tt js2-LC))
8316 ;; Destructuring assignment, e.g., var [a, b] = ...
8317 (setq destructuring (js2-parse-destruct-primary-expr)
8318 end (js2-node-end destructuring))
8319 ;; Simple variable name
8320 (js2-unget-token)
8321 (when (js2-must-match js2-NAME "msg.bad.var")
8322 (setq name (js2-create-name-node)
8323 nbeg (js2-current-token-beg)
8324 nend (js2-current-token-end)
8325 end nend)
8326 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
8327 (when (js2-match-token js2-ASSIGN)
8328 (setq init (js2-parse-assign-expr)
8329 end (js2-node-end init))
8330 (js2-record-imenu-functions init name))
8331 (when name
8332 (js2-set-face nbeg nend (if (js2-function-node-p init)
8333 'font-lock-function-name-face
8334 'font-lock-variable-name-face)
8335 'record))
8336 (setq vi (make-js2-var-init-node :pos kid-pos
8337 :len (- end kid-pos)
8338 :type decl-type))
8339 (if destructuring
8340 (progn
8341 (if (and (null init) (not js2-in-for-init))
8342 (js2-report-error "msg.destruct.assign.no.init"))
8343 (js2-define-destruct-symbols destructuring
8344 decl-type
8345 'font-lock-variable-name-face)
8346 (setf (js2-var-init-node-target vi) destructuring))
8347 (setf (js2-var-init-node-target vi) name))
8348 (setf (js2-var-init-node-initializer vi) init)
8349 (js2-node-add-children vi name destructuring init)
8350 (js2-block-node-push result vi)
8351 (unless (js2-match-token js2-COMMA)
8352 (setq continue nil)))
8353 (setf (js2-node-len result) (- end pos))
8354 result))
8355
8356 (defun js2-parse-let (pos &optional stmt-p)
8357 "Parse a let expression or statement.
8358 A let-expression is of the form `let (vars) expr'.
8359 A let-statment is of the form `let (vars) {statements}'.
8360 The third form of let is a variable declaration list, handled
8361 by `js2-parse-variables'."
8362 (let ((pn (make-js2-let-node :pos pos))
8363 beg vars body)
8364 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8365 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
8366 (js2-push-scope pn)
8367 (unwind-protect
8368 (progn
8369 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
8370 (if (js2-must-match js2-RP "msg.no.paren.let")
8371 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
8372 (if (and stmt-p (eq (js2-get-token) js2-LC))
8373 ;; let statement
8374 (progn
8375 (setf beg (js2-current-token-beg) ; position stmt at LC
8376 body (js2-parse-statements))
8377 (js2-must-match js2-RC "msg.no.curly.let")
8378 (setf (js2-node-len body) (- (js2-current-token-end) beg)
8379 (js2-node-len pn) (- (js2-current-token-end) pos)
8380 (js2-let-node-body pn) body
8381 (js2-node-type pn) js2-LET))
8382 ;; let expression
8383 (js2-unget-token)
8384 (setf body (js2-parse-expr)
8385 (js2-node-len pn) (- (js2-node-end body) pos)
8386 (js2-let-node-body pn) body))
8387 (js2-node-add-children pn vars body))
8388 (js2-pop-scope))
8389 pn))
8390
8391 (defun js2-define-new-symbol (decl-type name node &optional scope)
8392 (js2-scope-put-symbol (or scope js2-current-scope)
8393 name
8394 (make-js2-symbol decl-type name node)))
8395
8396 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8397 "Define a symbol in the current scope.
8398 If NODE is non-nil, it is the AST node associated with the symbol."
8399 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8400 (symbol (if defining-scope
8401 (js2-scope-get-symbol defining-scope name)))
8402 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8403 (cond
8404 ((and symbol ; already defined
8405 (or (= sdt js2-CONST) ; old version is const
8406 (= decl-type js2-CONST) ; new version is const
8407 ;; two let-bound vars in this block have same name
8408 (and (= sdt js2-LET)
8409 (eq defining-scope js2-current-scope))))
8410 (js2-report-error
8411 (cond
8412 ((= sdt js2-CONST) "msg.const.redecl")
8413 ((= sdt js2-LET) "msg.let.redecl")
8414 ((= sdt js2-VAR) "msg.var.redecl")
8415 ((= sdt js2-FUNCTION) "msg.function.redecl")
8416 (t "msg.parm.redecl"))
8417 name))
8418 ((= decl-type js2-LET)
8419 (if (and (not ignore-not-in-block)
8420 (or (= (js2-node-type js2-current-scope) js2-IF)
8421 (js2-loop-node-p js2-current-scope)))
8422 (js2-report-error "msg.let.decl.not.in.block")
8423 (js2-define-new-symbol decl-type name node)))
8424 ((or (= decl-type js2-VAR)
8425 (= decl-type js2-CONST)
8426 (= decl-type js2-FUNCTION))
8427 (if symbol
8428 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8429 (js2-add-strict-warning "msg.var.redecl" name)
8430 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8431 (js2-add-strict-warning "msg.var.hides.arg" name)))
8432 (js2-define-new-symbol decl-type name node
8433 js2-current-script-or-fn)))
8434 ((= decl-type js2-LP)
8435 (if symbol
8436 ;; must be duplicate parameter. Second parameter hides the
8437 ;; first, so go ahead and add the second pararameter
8438 (js2-report-warning "msg.dup.parms" name))
8439 (js2-define-new-symbol decl-type name node))
8440 (t (js2-code-bug)))))
8441
8442 (defun js2-parse-expr (&optional oneshot)
8443 (let* ((pn (js2-parse-assign-expr))
8444 (pos (js2-node-pos pn))
8445 left
8446 right
8447 op-pos)
8448 (while (and (not oneshot)
8449 (js2-match-token js2-COMMA))
8450 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
8451 (if (= (js2-peek-token) js2-YIELD)
8452 (js2-report-error "msg.yield.parenthesized"))
8453 (setq right (js2-parse-assign-expr)
8454 left pn
8455 pn (make-js2-infix-node :type js2-COMMA
8456 :pos pos
8457 :len (- js2-ts-cursor pos)
8458 :op-pos op-pos
8459 :left left
8460 :right right))
8461 (js2-node-add-children pn left right))
8462 pn))
8463
8464 (defun js2-parse-assign-expr ()
8465 (let ((tt (js2-get-token))
8466 (pos (js2-current-token-beg))
8467 pn left right op-pos)
8468 (if (= tt js2-YIELD)
8469 (js2-parse-return-or-yield tt t)
8470 ;; not yield - parse assignment expression
8471 (setq pn (js2-parse-cond-expr)
8472 tt (js2-get-token))
8473 (if (not (and (<= js2-first-assign tt)
8474 (<= tt js2-last-assign)))
8475 (js2-unget-token)
8476 ;; tt express assignment (=, |=, ^=, ..., %=)
8477 (setq op-pos (- (js2-current-token-beg) pos) ; relative
8478 left pn)
8479 (setq right (js2-parse-assign-expr)
8480 pn (make-js2-assign-node :type tt
8481 :pos pos
8482 :len (- (js2-node-end right) pos)
8483 :op-pos op-pos
8484 :left left
8485 :right right))
8486 (when js2-parse-ide-mode
8487 (js2-highlight-assign-targets pn left right)
8488 (js2-record-imenu-functions right left))
8489 ;; do this last so ide checks above can use absolute positions
8490 (js2-node-add-children pn left right))
8491 pn)))
8492
8493 (defun js2-parse-cond-expr ()
8494 (let ((pos (js2-current-token-beg))
8495 (pn (js2-parse-or-expr))
8496 test-expr
8497 if-true
8498 if-false
8499 q-pos
8500 c-pos)
8501 (when (js2-match-token js2-HOOK)
8502 (setq q-pos (- (js2-current-token-beg) pos)
8503 if-true (js2-parse-assign-expr))
8504 (js2-must-match js2-COLON "msg.no.colon.cond")
8505 (setq c-pos (- (js2-current-token-beg) pos)
8506 if-false (js2-parse-assign-expr)
8507 test-expr pn
8508 pn (make-js2-cond-node :pos pos
8509 :len (- (js2-node-end if-false) pos)
8510 :test-expr test-expr
8511 :true-expr if-true
8512 :false-expr if-false
8513 :q-pos q-pos
8514 :c-pos c-pos))
8515 (js2-node-add-children pn test-expr if-true if-false))
8516 pn))
8517
8518 (defun js2-make-binary (type left parser)
8519 "Helper for constructing a binary-operator AST node.
8520 LEFT is the left-side-expression, already parsed, and the
8521 binary operator should have just been matched.
8522 PARSER is a function to call to parse the right operand,
8523 or a `js2-node' struct if it has already been parsed.
8524 FIXME: The latter option is unused?"
8525 (let* ((pos (js2-node-pos left))
8526 (op-pos (- (js2-current-token-beg) pos))
8527 (right (if (js2-node-p parser)
8528 parser
8529 (js2-get-token)
8530 (funcall parser)))
8531 (pn (make-js2-infix-node :type type
8532 :pos pos
8533 :len (- (js2-node-end right) pos)
8534 :op-pos op-pos
8535 :left left
8536 :right right)))
8537 (js2-node-add-children pn left right)
8538 pn))
8539
8540 (defun js2-parse-or-expr ()
8541 (let ((pn (js2-parse-and-expr)))
8542 (when (js2-match-token js2-OR)
8543 (setq pn (js2-make-binary js2-OR
8544 pn
8545 'js2-parse-or-expr)))
8546 pn))
8547
8548 (defun js2-parse-and-expr ()
8549 (let ((pn (js2-parse-bit-or-expr)))
8550 (when (js2-match-token js2-AND)
8551 (setq pn (js2-make-binary js2-AND
8552 pn
8553 'js2-parse-and-expr)))
8554 pn))
8555
8556 (defun js2-parse-bit-or-expr ()
8557 (let ((pn (js2-parse-bit-xor-expr)))
8558 (while (js2-match-token js2-BITOR)
8559 (setq pn (js2-make-binary js2-BITOR
8560 pn
8561 'js2-parse-bit-xor-expr)))
8562 pn))
8563
8564 (defun js2-parse-bit-xor-expr ()
8565 (let ((pn (js2-parse-bit-and-expr)))
8566 (while (js2-match-token js2-BITXOR)
8567 (setq pn (js2-make-binary js2-BITXOR
8568 pn
8569 'js2-parse-bit-and-expr)))
8570 pn))
8571
8572 (defun js2-parse-bit-and-expr ()
8573 (let ((pn (js2-parse-eq-expr)))
8574 (while (js2-match-token js2-BITAND)
8575 (setq pn (js2-make-binary js2-BITAND
8576 pn
8577 'js2-parse-eq-expr)))
8578 pn))
8579
8580 (defconst js2-parse-eq-ops
8581 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8582
8583 (defun js2-parse-eq-expr ()
8584 (let ((pn (js2-parse-rel-expr))
8585 tt)
8586 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
8587 (setq pn (js2-make-binary tt
8588 pn
8589 'js2-parse-rel-expr)))
8590 (js2-unget-token)
8591 pn))
8592
8593 (defconst js2-parse-rel-ops
8594 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8595
8596 (defun js2-parse-rel-expr ()
8597 (let ((pn (js2-parse-shift-expr))
8598 (continue t)
8599 tt)
8600 (while continue
8601 (setq tt (js2-get-token))
8602 (cond
8603 ((and js2-in-for-init (= tt js2-IN))
8604 (js2-unget-token)
8605 (setq continue nil))
8606 ((memq tt js2-parse-rel-ops)
8607 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8608 (t
8609 (js2-unget-token)
8610 (setq continue nil))))
8611 pn))
8612
8613 (defconst js2-parse-shift-ops
8614 (list js2-LSH js2-URSH js2-RSH))
8615
8616 (defun js2-parse-shift-expr ()
8617 (let ((pn (js2-parse-add-expr))
8618 tt
8619 (continue t))
8620 (while continue
8621 (setq tt (js2-get-token))
8622 (if (memq tt js2-parse-shift-ops)
8623 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
8624 (js2-unget-token)
8625 (setq continue nil)))
8626 pn))
8627
8628 (defun js2-parse-add-expr ()
8629 (let ((pn (js2-parse-mul-expr))
8630 tt
8631 (continue t))
8632 (while continue
8633 (setq tt (js2-get-token))
8634 (if (or (= tt js2-ADD) (= tt js2-SUB))
8635 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
8636 (js2-unget-token)
8637 (setq continue nil)))
8638 pn))
8639
8640 (defconst js2-parse-mul-ops
8641 (list js2-MUL js2-DIV js2-MOD))
8642
8643 (defun js2-parse-mul-expr ()
8644 (let ((pn (js2-parse-unary-expr))
8645 tt
8646 (continue t))
8647 (while continue
8648 (setq tt (js2-get-token))
8649 (if (memq tt js2-parse-mul-ops)
8650 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
8651 (js2-unget-token)
8652 (setq continue nil)))
8653 pn))
8654
8655 (defun js2-make-unary (type parser &rest args)
8656 "Make a unary node of type TYPE.
8657 PARSER is either a node (for postfix operators) or a function to call
8658 to parse the operand (for prefix operators)."
8659 (let* ((pos (js2-current-token-beg))
8660 (postfix (js2-node-p parser))
8661 (expr (if postfix
8662 parser
8663 (apply parser args)))
8664 end
8665 pn)
8666 (if postfix ; e.g. i++
8667 (setq pos (js2-node-pos expr)
8668 end (js2-current-token-end))
8669 (setq end (js2-node-end expr)))
8670 (setq pn (make-js2-unary-node :type type
8671 :pos pos
8672 :len (- end pos)
8673 :operand expr))
8674 (js2-node-add-children pn expr)
8675 pn))
8676
8677 (defconst js2-incrementable-node-types
8678 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8679 "Node types that can be the operand of a ++ or -- operator.")
8680
8681 (defun js2-check-bad-inc-dec (tt beg end unary)
8682 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8683 js2-incrementable-node-types)
8684 (js2-report-error (if (= tt js2-INC)
8685 "msg.bad.incr"
8686 "msg.bad.decr")
8687 nil beg (- end beg))))
8688
8689 (defun js2-parse-unary-expr ()
8690 (let ((tt (js2-current-token-type))
8691 pn expr beg end)
8692 (cond
8693 ((or (= tt js2-VOID)
8694 (= tt js2-NOT)
8695 (= tt js2-BITNOT)
8696 (= tt js2-TYPEOF))
8697 (js2-get-token)
8698 (js2-make-unary tt 'js2-parse-unary-expr))
8699 ((= tt js2-ADD)
8700 (js2-get-token)
8701 ;; Convert to special POS token in decompiler and parse tree
8702 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8703 ((= tt js2-SUB)
8704 (js2-get-token)
8705 ;; Convert to special NEG token in decompiler and parse tree
8706 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8707 ((or (= tt js2-INC)
8708 (= tt js2-DEC))
8709 (js2-get-token)
8710 (prog1
8711 (setq beg (js2-current-token-beg)
8712 end (js2-current-token-end)
8713 expr (js2-make-unary tt 'js2-parse-member-expr t))
8714 (js2-check-bad-inc-dec tt beg end expr)))
8715 ((= tt js2-DELPROP)
8716 (js2-get-token)
8717 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8718 ((= tt js2-ERROR)
8719 (js2-get-token)
8720 (make-js2-error-node)) ; try to continue
8721 ((and (= tt js2-LT)
8722 js2-compiler-xml-available)
8723 ;; XML stream encountered in expression.
8724 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8725 (t
8726 (setq pn (js2-parse-member-expr t)
8727 ;; Don't look across a newline boundary for a postfix incop.
8728 tt (js2-peek-token-or-eol))
8729 (when (or (= tt js2-INC) (= tt js2-DEC))
8730 (js2-get-token)
8731 (setf expr pn
8732 pn (js2-make-unary tt expr))
8733 (js2-node-set-prop pn 'postfix t)
8734 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
8735 pn))))
8736
8737 (defun js2-parse-xml-initializer ()
8738 "Parse an E4X XML initializer.
8739 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8740 Then I'll postprocess the result, depending on whether we're in IDE
8741 mode or codegen mode, and generate the appropriate rewritten AST.
8742 IDE mode uses a rich AST that models the XML structure. Codegen mode
8743 just concatenates everything and makes a new XML or XMLList out of it."
8744 (let ((tt (js2-get-first-xml-token))
8745 pn-xml pn expr kids expr-pos
8746 (continue t)
8747 (first-token t))
8748 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8749 (js2-report-error "msg.syntax"))
8750 (setq pn-xml (make-js2-xml-node))
8751 (while continue
8752 (if first-token
8753 (setq first-token nil)
8754 (setq tt (js2-get-next-xml-token)))
8755 (cond
8756 ;; js2-XML means we found a {expr} in the XML stream.
8757 ;; The token string is the XML up to the left-curly.
8758 ((= tt js2-XML)
8759 (push (make-js2-string-node :pos (js2-current-token-beg)
8760 :len (- js2-ts-cursor (js2-current-token-beg)))
8761 kids)
8762 (js2-must-match js2-LC "msg.syntax")
8763 (setq expr-pos js2-ts-cursor
8764 expr (if (eq (js2-peek-token) js2-RC)
8765 (make-js2-empty-expr-node :pos expr-pos)
8766 (js2-parse-expr)))
8767 (js2-must-match js2-RC "msg.syntax")
8768 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8769 :len (js2-node-len expr)
8770 :expr expr))
8771 (js2-node-add-children pn expr)
8772 (push pn kids))
8773 ;; a js2-XMLEND token means we hit the final close-tag.
8774 ((= tt js2-XMLEND)
8775 (push (make-js2-string-node :pos (js2-current-token-beg)
8776 :len (- js2-ts-cursor (js2-current-token-beg)))
8777 kids)
8778 (dolist (kid (nreverse kids))
8779 (js2-block-node-push pn-xml kid))
8780 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8781 (js2-node-pos pn-xml))
8782 continue nil))
8783 (t
8784 (js2-report-error "msg.syntax")
8785 (setq continue nil))))
8786 pn-xml))
8787
8788
8789 (defun js2-parse-argument-list ()
8790 "Parse an argument list and return it as a Lisp list of nodes.
8791 Returns the list in reverse order. Consumes the right-paren token."
8792 (let (result)
8793 (unless (js2-match-token js2-RP)
8794 (loop do
8795 (if (= (js2-peek-token) js2-YIELD)
8796 (js2-report-error "msg.yield.parenthesized"))
8797 (push (js2-parse-assign-expr) result)
8798 while
8799 (js2-match-token js2-COMMA))
8800 (js2-must-match js2-RP "msg.no.paren.arg")
8801 result)))
8802
8803 (defun js2-parse-member-expr (&optional allow-call-syntax)
8804 (let ((tt (js2-current-token-type))
8805 pn pos target args beg end init tail)
8806 (if (/= tt js2-NEW)
8807 (setq pn (js2-parse-primary-expr))
8808 ;; parse a 'new' expression
8809 (js2-get-token)
8810 (setq pos (js2-current-token-beg)
8811 beg pos
8812 target (js2-parse-member-expr)
8813 end (js2-node-end target)
8814 pn (make-js2-new-node :pos pos
8815 :target target
8816 :len (- end pos)))
8817 (js2-node-add-children pn target)
8818 (when (js2-match-token js2-LP)
8819 ;; Add the arguments to pn, if any are supplied.
8820 (setf beg pos ; start of "new" keyword
8821 pos (js2-current-token-beg)
8822 args (nreverse (js2-parse-argument-list))
8823 (js2-new-node-args pn) args
8824 end (js2-current-token-end)
8825 (js2-new-node-lp pn) (- pos beg)
8826 (js2-new-node-rp pn) (- end 1 beg))
8827 (apply #'js2-node-add-children pn args))
8828 (when (and js2-allow-rhino-new-expr-initializer
8829 (js2-match-token js2-LC))
8830 (setf init (js2-parse-object-literal)
8831 end (js2-node-end init)
8832 (js2-new-node-initializer pn) init)
8833 (js2-node-add-children pn init))
8834 (setf (js2-node-len pn) (- end beg))) ; end outer if
8835 (js2-parse-member-expr-tail allow-call-syntax pn)))
8836
8837 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8838 "Parse a chain of property/array accesses or function calls.
8839 Includes parsing for E4X operators like `..' and `.@'.
8840 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8841 Returns an expression tree that includes PN, the parent node."
8842 (let ((beg (js2-node-pos pn))
8843 tt
8844 (continue t))
8845 (while continue
8846 (setq tt (js2-get-token))
8847 (cond
8848 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8849 (setq pn (js2-parse-property-access tt pn)))
8850 ((= tt js2-DOTQUERY)
8851 (setq pn (js2-parse-dot-query pn)))
8852 ((= tt js2-LB)
8853 (setq pn (js2-parse-element-get pn)))
8854 ((= tt js2-LP)
8855 (if allow-call-syntax
8856 (setq pn (js2-parse-function-call pn))
8857 (js2-unget-token)
8858 (setq continue nil)))
8859 (t
8860 (js2-unget-token)
8861 (setq continue nil))))
8862 (if (>= js2-highlight-level 2)
8863 (js2-parse-highlight-member-expr-node pn))
8864 pn))
8865
8866 (defun js2-parse-dot-query (pn)
8867 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8868 Last token parsed must be `js2-DOTQUERY'."
8869 (let ((pos (js2-node-pos pn))
8870 op-pos expr end)
8871 (js2-must-have-xml)
8872 (js2-set-requires-activation)
8873 (setq op-pos (js2-current-token-beg)
8874 expr (js2-parse-expr)
8875 end (js2-node-end expr)
8876 pn (make-js2-xml-dot-query-node :left pn
8877 :pos pos
8878 :op-pos op-pos
8879 :right expr))
8880 (js2-node-add-children pn
8881 (js2-xml-dot-query-node-left pn)
8882 (js2-xml-dot-query-node-right pn))
8883 (if (js2-must-match js2-RP "msg.no.paren")
8884 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
8885 end (js2-current-token-end)))
8886 (setf (js2-node-len pn) (- end pos))
8887 pn))
8888
8889 (defun js2-parse-element-get (pn)
8890 "Parse an element-get expression, e.g. foo[bar].
8891 Last token parsed must be `js2-RB'."
8892 (let ((lb (js2-current-token-beg))
8893 (pos (js2-node-pos pn))
8894 rb expr)
8895 (setq expr (js2-parse-expr))
8896 (if (js2-must-match js2-RB "msg.no.bracket.index")
8897 (setq rb (js2-current-token-beg)))
8898 (setq pn (make-js2-elem-get-node :target pn
8899 :pos pos
8900 :element expr
8901 :lb (js2-relpos lb pos)
8902 :rb (js2-relpos rb pos)
8903 :len (- (js2-current-token-end) pos)))
8904 (js2-node-add-children pn
8905 (js2-elem-get-node-target pn)
8906 (js2-elem-get-node-element pn))
8907 pn))
8908
8909 (defun js2-parse-function-call (pn)
8910 (let (args
8911 (pos (js2-node-pos pn)))
8912 (setq pn (make-js2-call-node :pos pos
8913 :target pn
8914 :lp (- (js2-current-token-beg) pos)))
8915 (js2-node-add-children pn (js2-call-node-target pn))
8916 ;; Add the arguments to pn, if any are supplied.
8917 (setf args (nreverse (js2-parse-argument-list))
8918 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
8919 (js2-call-node-args pn) args)
8920 (apply #'js2-node-add-children pn args)
8921 (setf (js2-node-len pn) (- js2-ts-cursor pos))
8922 pn))
8923
8924 (defun js2-parse-property-access (tt pn)
8925 "Parse a property access, XML descendants access, or XML attr access."
8926 (let ((member-type-flags 0)
8927 (dot-pos (js2-current-token-beg))
8928 (dot-len (if (= tt js2-DOTDOT) 2 1))
8929 name
8930 ref ; right side of . or .. operator
8931 result)
8932 (when (= tt js2-DOTDOT)
8933 (js2-must-have-xml)
8934 (setq member-type-flags js2-descendants-flag))
8935 (if (not js2-compiler-xml-available)
8936 (progn
8937 (js2-must-match-prop-name "msg.no.name.after.dot")
8938 (setq name (js2-create-name-node t js2-GETPROP)
8939 result (make-js2-prop-get-node :left pn
8940 :pos (js2-current-token-beg)
8941 :right name
8942 :len (js2-current-token-len)))
8943 (js2-node-add-children result pn name)
8944 result)
8945 ;; otherwise look for XML operators
8946 (setf result (if (= tt js2-DOT)
8947 (make-js2-prop-get-node)
8948 (make-js2-infix-node :type js2-DOTDOT))
8949 (js2-node-pos result) (js2-node-pos pn)
8950 (js2-infix-node-op-pos result) dot-pos
8951 (js2-infix-node-left result) pn ; do this after setting position
8952 tt (js2-next-token))
8953 (cond
8954 ;; needed for generator.throw()
8955 ((= tt js2-THROW)
8956 (setq ref (js2-parse-property-name nil nil member-type-flags)))
8957 ;; handles: name, ns::name, ns::*, ns::[expr]
8958 ((js2-valid-prop-name-token tt)
8959 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
8960 ;; handles: *, *::name, *::*, *::[expr]
8961 ((= tt js2-MUL)
8962 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
8963 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
8964 ((= tt js2-XMLATTR)
8965 (setq result (js2-parse-attribute-access)))
8966 (t
8967 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
8968 (if ref
8969 (setf (js2-node-len result) (- (js2-node-end ref)
8970 (js2-node-pos result))
8971 (js2-infix-node-right result) ref))
8972 (if (js2-infix-node-p result)
8973 (js2-node-add-children result
8974 (js2-infix-node-left result)
8975 (js2-infix-node-right result)))
8976 result)))
8977
8978 (defun js2-parse-attribute-access ()
8979 "Parse an E4X XML attribute expression.
8980 This includes expressions of the forms:
8981
8982 @attr @ns::attr @ns::*
8983 @* @*::attr @*::*
8984 @[expr] @*::[expr] @ns::[expr]
8985
8986 Called if we peeked an '@' token."
8987 (let ((tt (js2-next-token))
8988 (at-pos (js2-current-token-beg)))
8989 (cond
8990 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
8991 ((js2-valid-prop-name-token tt)
8992 (js2-parse-property-name at-pos nil 0))
8993 ;; handles: @*, @*::name, @*::*, @*::[expr]
8994 ((= tt js2-MUL)
8995 (js2-parse-property-name (js2-current-token-beg) "*" 0))
8996 ;; handles @[expr]
8997 ((= tt js2-LB)
8998 (js2-parse-xml-elem-ref at-pos))
8999 (t
9000 (js2-report-error "msg.no.name.after.xmlAttr")
9001 ;; Avoid cascaded errors that happen if we make an error node here.
9002 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9003
9004 (defun js2-parse-property-name (at-pos s member-type-flags)
9005 "Check if :: follows name in which case it becomes qualified name.
9006
9007 AT-POS is a natural number if we just read an '@' token, else nil.
9008 S is the name or string that was matched: an identifier, 'throw' or '*'.
9009 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9010
9011 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9012 operator, or the name is followed by ::. For a plain name, returns a
9013 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9014 (let ((pos (or at-pos (js2-current-token-beg)))
9015 colon-pos
9016 (name (js2-create-name-node t (js2-current-token-type) s))
9017 ns tt ref pn)
9018 (catch 'return
9019 (when (js2-match-token js2-COLONCOLON)
9020 (setq ns name
9021 colon-pos (js2-current-token-beg)
9022 tt (js2-next-token))
9023 (cond
9024 ;; handles name::name
9025 ((js2-valid-prop-name-token tt)
9026 (setq name (js2-create-name-node)))
9027 ;; handles name::*
9028 ((= tt js2-MUL)
9029 (setq name (js2-create-name-node nil nil "*")))
9030 ;; handles name::[expr]
9031 ((= tt js2-LB)
9032 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9033 (t
9034 (js2-report-error "msg.no.name.after.coloncolon"))))
9035 (if (and (null ns) (zerop member-type-flags))
9036 name
9037 (prog1
9038 (setq pn
9039 (make-js2-xml-prop-ref-node :pos pos
9040 :len (- (js2-node-end name) pos)
9041 :at-pos at-pos
9042 :colon-pos colon-pos
9043 :propname name))
9044 (js2-node-add-children pn name))))))
9045
9046 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9047 "Parse the [expr] portion of an xml element reference.
9048 For instance, @[expr], @*::[expr], or ns::[expr]."
9049 (let* ((lb (js2-current-token-beg))
9050 (pos (or at-pos lb))
9051 rb
9052 (expr (js2-parse-expr))
9053 (end (js2-node-end expr))
9054 pn)
9055 (if (js2-must-match js2-RB "msg.no.bracket.index")
9056 (setq rb (js2-current-token-beg)
9057 end (js2-current-token-end)))
9058 (prog1
9059 (setq pn
9060 (make-js2-xml-elem-ref-node :pos pos
9061 :len (- end pos)
9062 :namespace namespace
9063 :colon-pos colon-pos
9064 :at-pos at-pos
9065 :expr expr
9066 :lb (js2-relpos lb pos)
9067 :rb (js2-relpos rb pos)))
9068 (js2-node-add-children pn namespace expr))))
9069
9070 (defun js2-parse-destruct-primary-expr ()
9071 (let ((js2-is-in-destructuring t))
9072 (js2-parse-primary-expr)))
9073
9074 (defun js2-parse-primary-expr ()
9075 "Parse a literal (leaf) expression of some sort.
9076 Includes complex literals such as functions, object-literals,
9077 array-literals, array comprehensions and regular expressions."
9078 (let (pn ; parent node (usually return value)
9079 tt
9080 px-pos ; paren-expr pos
9081 len
9082 flags ; regexp flags
9083 expr)
9084 (setq tt (js2-current-token-type))
9085 (cond
9086 ((= tt js2-FUNCTION)
9087 (js2-parse-function 'FUNCTION_EXPRESSION))
9088 ((= tt js2-LB)
9089 (js2-parse-array-literal))
9090 ((= tt js2-LC)
9091 (js2-parse-object-literal))
9092 ((= tt js2-LET)
9093 (js2-parse-let (js2-current-token-beg)))
9094 ((= tt js2-LP)
9095 (setq px-pos (js2-current-token-beg)
9096 expr (js2-parse-expr))
9097 (js2-must-match js2-RP "msg.no.paren")
9098 (setq pn (make-js2-paren-node :pos px-pos
9099 :expr expr
9100 :len (- (js2-current-token-end) px-pos)))
9101 (js2-node-add-children pn (js2-paren-node-expr pn))
9102 pn)
9103 ((= tt js2-XMLATTR)
9104 (js2-must-have-xml)
9105 (js2-parse-attribute-access))
9106 ((= tt js2-NAME)
9107 (js2-parse-name tt))
9108 ((= tt js2-NUMBER)
9109 (make-js2-number-node))
9110 ((= tt js2-STRING)
9111 (prog1
9112 (make-js2-string-node)
9113 (js2-record-face 'font-lock-string-face)))
9114 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9115 ;; Got / or /= which in this context means a regexp literal
9116 (setq px-pos (js2-current-token-beg))
9117 (setq flags (js2-read-regexp tt))
9118 (prog1
9119 (make-js2-regexp-node :pos px-pos
9120 :len (- js2-ts-cursor px-pos)
9121 :value (js2-current-token-string)
9122 :flags flags)
9123 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9124 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9125 ((or (= tt js2-NULL)
9126 (= tt js2-THIS)
9127 (= tt js2-FALSE)
9128 (= tt js2-TRUE))
9129 (make-js2-keyword-node :type tt))
9130 ((= tt js2-RESERVED)
9131 (js2-report-error "msg.reserved.id")
9132 (make-js2-name-node))
9133 ((= tt js2-ERROR)
9134 ;; the scanner or one of its subroutines reported the error.
9135 (make-js2-error-node))
9136 ((= tt js2-EOF)
9137 (setq px-pos (point-at-bol)
9138 len (- js2-ts-cursor px-pos))
9139 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9140 (make-js2-error-node :pos px-pos :len len))
9141 (t
9142 (js2-report-error "msg.syntax")
9143 (make-js2-error-node)))))
9144
9145 (defun js2-parse-name (tt)
9146 (let ((name (js2-current-token-string))
9147 node)
9148 (setq node (if js2-compiler-xml-available
9149 (js2-parse-property-name nil name 0)
9150 (js2-create-name-node 'check-activation nil name)))
9151 (if js2-highlight-external-variables
9152 (js2-record-name-node node))
9153 node))
9154
9155 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9156 (js2-add-strict-warning
9157 msg nil
9158 ;; back up from comma to beginning of line or array/objlit
9159 (max (if elems
9160 (js2-node-pos (car elems))
9161 pos)
9162 (save-excursion
9163 (goto-char comma-pos)
9164 (back-to-indentation)
9165 (point)))
9166 comma-pos))
9167
9168 (defun js2-parse-array-literal ()
9169 (let ((pos (js2-current-token-beg))
9170 (end (js2-current-token-end))
9171 (after-lb-or-comma t)
9172 after-comma tt elems pn
9173 (continue t))
9174 (unless js2-is-in-destructuring
9175 (js2-push-scope (make-js2-scope))) ; for array comp
9176 (while continue
9177 (setq tt (js2-get-token))
9178 (cond
9179 ;; comma
9180 ((= tt js2-COMMA)
9181 (setq after-comma (js2-current-token-end))
9182 (if (not after-lb-or-comma)
9183 (setq after-lb-or-comma t)
9184 (push nil elems)))
9185 ;; end of array
9186 ((or (= tt js2-RB)
9187 (= tt js2-EOF)) ; prevent infinite loop
9188 (if (= tt js2-EOF)
9189 (js2-report-error "msg.no.bracket.arg" nil pos))
9190 (setq continue nil
9191 end (js2-current-token-end)
9192 pn (make-js2-array-node :pos pos
9193 :len (- js2-ts-cursor pos)
9194 :elems (nreverse elems)))
9195 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9196 (when (and after-comma (not js2-is-in-destructuring))
9197 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9198 pos elems after-comma)))
9199 ;; destructuring binding
9200 (js2-is-in-destructuring
9201 (push (if (or (= tt js2-LC)
9202 (= tt js2-LB)
9203 (= tt js2-NAME))
9204 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9205 (js2-parse-destruct-primary-expr)
9206 ;; invalid pattern
9207 (js2-report-error "msg.bad.var")
9208 (make-js2-error-node))
9209 elems)
9210 (setq after-lb-or-comma nil
9211 after-comma nil))
9212 ;; array comp
9213 ((and (>= js2-language-version 170)
9214 (= tt js2-FOR) ; check for array comprehension
9215 (not after-lb-or-comma) ; "for" can't follow a comma
9216 elems ; must have at least 1 element
9217 (not (cdr elems))) ; but no 2nd element
9218 (js2-unget-token)
9219 (setf continue nil
9220 pn (js2-parse-array-comprehension (car elems) pos)))
9221
9222 ;; another element
9223 (t
9224 (unless after-lb-or-comma
9225 (js2-report-error "msg.no.bracket.arg"))
9226 (js2-unget-token)
9227 (push (js2-parse-assign-expr) elems)
9228 (setq after-lb-or-comma nil
9229 after-comma nil))))
9230 (unless js2-is-in-destructuring
9231 (js2-pop-scope))
9232 pn))
9233
9234 (defun js2-parse-array-comprehension (expr pos)
9235 "Parse a JavaScript 1.7 Array Comprehension.
9236 EXPR is the first expression after the opening left-bracket.
9237 POS is the beginning of the LB token preceding EXPR.
9238 We should have just parsed the 'for' keyword before calling this function."
9239 (let (loops loop first prev filter if-pos result)
9240 (while (= (js2-get-token) js2-FOR)
9241 (let ((prev (car loops))) ; rearrange scope chain
9242 (push (setq loop (js2-parse-array-comp-loop)) loops)
9243 (if prev ; each loop is parent scope to the next one
9244 (setf (js2-scope-parent-scope loop) prev)
9245 ; first loop takes expr scope's parent
9246 (setf (js2-scope-parent-scope (setq first loop))
9247 (js2-scope-parent-scope js2-current-scope)))))
9248 (js2-unget-token)
9249 ;; set expr scope's parent to the last loop
9250 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9251 (if (/= (js2-get-token) js2-IF)
9252 (js2-unget-token)
9253 (setq if-pos (- (js2-current-token-beg) pos) ; relative
9254 filter (js2-parse-condition)))
9255 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9256 (setq result (make-js2-array-comp-node :pos pos
9257 :len (- js2-ts-cursor pos)
9258 :result expr
9259 :loops (nreverse loops)
9260 :filter (car filter)
9261 :lp (js2-relpos (second filter) pos)
9262 :rp (js2-relpos (third filter) pos)
9263 :if-pos if-pos))
9264 (apply #'js2-node-add-children result expr (car filter)
9265 (js2-array-comp-node-loops result))
9266 (setq js2-current-scope first) ; pop to the first loop
9267 result))
9268
9269 (defun js2-parse-array-comp-loop ()
9270 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9271 Last token peeked should be the initial FOR."
9272 (let ((pos (js2-current-token-beg))
9273 (pn (make-js2-array-comp-loop-node))
9274 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9275 (assert (= (js2-current-token-type) js2-FOR))
9276 (js2-push-scope pn)
9277 (unwind-protect
9278 (progn
9279 (when (js2-match-token js2-NAME)
9280 (if (string= (js2-current-token-string) "each")
9281 (progn
9282 (setq foreach-p t
9283 each-pos (- (js2-current-token-beg) pos)) ; relative
9284 (js2-record-face 'font-lock-keyword-face))
9285 (js2-report-error "msg.no.paren.for")))
9286 (if (js2-must-match js2-LP "msg.no.paren.for")
9287 (setq lp (- (js2-current-token-beg) pos)))
9288 (setq tt (js2-peek-token))
9289 (cond
9290 ((or (= tt js2-LB)
9291 (= tt js2-LC))
9292 (js2-get-token)
9293 (setq iter (js2-parse-destruct-primary-expr))
9294 (js2-define-destruct-symbols iter js2-LET
9295 'font-lock-variable-name-face t))
9296 ((js2-match-token js2-NAME)
9297 (setq iter (js2-create-name-node)))
9298 (t
9299 (js2-report-error "msg.bad.var")))
9300 ;; Define as a let since we want the scope of the variable to
9301 ;; be restricted to the array comprehension
9302 (if (js2-name-node-p iter)
9303 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9304 (if (or (js2-match-token js2-IN)
9305 (and (>= js2-language-version 200)
9306 (js2-match-contextual-kwd "of")
9307 (setq forof-p t)))
9308 (setq in-pos (- (js2-current-token-beg) pos))
9309 (js2-report-error "msg.in.after.for.name"))
9310 (setq obj (js2-parse-expr))
9311 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9312 (setq rp (- (js2-current-token-beg) pos)))
9313 (setf (js2-node-pos pn) pos
9314 (js2-node-len pn) (- js2-ts-cursor pos)
9315 (js2-array-comp-loop-node-iterator pn) iter
9316 (js2-array-comp-loop-node-object pn) obj
9317 (js2-array-comp-loop-node-in-pos pn) in-pos
9318 (js2-array-comp-loop-node-each-pos pn) each-pos
9319 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9320 (js2-array-comp-loop-node-forof-p pn) forof-p
9321 (js2-array-comp-loop-node-lp pn) lp
9322 (js2-array-comp-loop-node-rp pn) rp)
9323 (js2-node-add-children pn iter obj))
9324 (js2-pop-scope))
9325 pn))
9326
9327 (defun js2-parse-object-literal ()
9328 (let ((pos (js2-current-token-beg))
9329 tt elems result after-comma
9330 (continue t))
9331 (while continue
9332 (setq tt (js2-get-token))
9333 (cond
9334 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9335 ;; {get foo() {...}}, or {set foo(x) {...}}
9336 ((or (js2-valid-prop-name-token tt)
9337 (= tt js2-STRING))
9338 (setq after-comma nil
9339 result (js2-parse-named-prop tt))
9340 (if (and (null result)
9341 (not js2-recover-from-parse-errors))
9342 (setq continue nil)
9343 (push result elems)))
9344 ;; {12: x} or {10.7: x}
9345 ((= tt js2-NUMBER)
9346 (setq after-comma nil)
9347 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9348 ;; trailing comma
9349 ((= tt js2-RC)
9350 (js2-unget-token)
9351 (setq continue nil)
9352 (if after-comma
9353 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9354 pos elems after-comma)))
9355 (t
9356 (js2-report-error "msg.bad.prop")
9357 (unless js2-recover-from-parse-errors
9358 (setq continue nil)))) ; end switch
9359 (if (js2-match-token js2-COMMA)
9360 (setq after-comma (js2-current-token-end))
9361 (setq continue nil))) ; end loop
9362 (js2-must-match js2-RC "msg.no.brace.prop")
9363 (setq result (make-js2-object-node :pos pos
9364 :len (- js2-ts-cursor pos)
9365 :elems (nreverse elems)))
9366 (apply #'js2-node-add-children result (js2-object-node-elems result))
9367 result))
9368
9369 (defun js2-parse-named-prop (tt)
9370 "Parse a name, string, or getter/setter object property.
9371 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9372 (let ((string-prop (and (= tt js2-STRING)
9373 (make-js2-string-node)))
9374 expr
9375 (ppos (js2-current-token-beg))
9376 (pend (js2-current-token-end))
9377 (name (js2-create-name-node))
9378 (prop (js2-current-token-string)))
9379 (cond
9380 ;; getter/setter prop
9381 ((and (= tt js2-NAME)
9382 (= (js2-peek-token) js2-NAME)
9383 (or (string= prop "get")
9384 (string= prop "set")))
9385 (js2-get-token)
9386 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9387 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9388 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9389 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9390 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9391 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9392 ;; when patterns are used in variable declarations, function parameters,
9393 ;; catch-clause, and iterators.
9394 ;; We have to set `js2-is-in-destructuring' to t when the current
9395 ;; expressions are on the left side of any assignment, but it's difficult
9396 ;; because it requires looking ahead of expression.
9397 ((and js2-is-in-destructuring
9398 (= tt js2-NAME)
9399 (let ((ctk (js2-peek-token)))
9400 (or (= ctk js2-COMMA)
9401 (= ctk js2-RC)
9402 (js2-valid-prop-name-token ctk))))
9403 name)
9404 ;; regular prop
9405 (t
9406 (prog1
9407 (setq expr (js2-parse-plain-property (or string-prop name)))
9408 (js2-set-face ppos pend
9409 (if (js2-function-node-p
9410 (js2-object-prop-node-right expr))
9411 'font-lock-function-name-face
9412 'font-lock-variable-name-face)
9413 'record))))))
9414
9415 (defun js2-parse-plain-property (prop)
9416 "Parse a non-getter/setter property in an object literal.
9417 PROP is the node representing the property: a number, name or string."
9418 (js2-must-match js2-COLON "msg.no.colon.prop")
9419 (let* ((pos (js2-node-pos prop))
9420 (colon (- (js2-current-token-beg) pos))
9421 (expr (js2-parse-assign-expr))
9422 (result (make-js2-object-prop-node
9423 :pos pos
9424 ;; don't include last consumed token in length
9425 :len (- (+ (js2-node-pos expr)
9426 (js2-node-len expr))
9427 pos)
9428 :left prop
9429 :right expr
9430 :op-pos colon)))
9431 (js2-node-add-children result prop expr)
9432 result))
9433
9434 (defun js2-parse-getter-setter-prop (pos prop get-p)
9435 "Parse getter or setter property in an object literal.
9436 JavaScript syntax is:
9437
9438 { get foo() {...}, set foo(x) {...} }
9439
9440 and expression closure style is also supported
9441
9442 { get foo() x, set foo(x) _x = x }
9443
9444 POS is the start position of the `get' or `set' keyword.
9445 PROP is the `js2-name-node' representing the property name.
9446 GET-P is non-nil if the keyword was `get'."
9447 (let ((type (if get-p js2-GET js2-SET))
9448 result end
9449 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9450 ;; it has to be an anonymous function, as we already parsed the name
9451 (if (/= (js2-node-type fn) js2-FUNCTION)
9452 (js2-report-error "msg.bad.prop")
9453 (if (plusp (length (js2-function-name fn)))
9454 (js2-report-error "msg.bad.prop")))
9455 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9456 (setq end (js2-node-end fn)
9457 result (make-js2-getter-setter-node :type type
9458 :pos pos
9459 :len (- end pos)
9460 :left prop
9461 :right fn))
9462 (js2-node-add-children result prop fn)
9463 result))
9464
9465 (defun js2-create-name-node (&optional check-activation-p token string)
9466 "Create a name node using the current token and, optionally, STRING.
9467 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
9468 (let* ((beg (js2-current-token-beg))
9469 (tt (js2-current-token-type))
9470 (s (or string
9471 (if (= js2-NAME tt)
9472 (js2-current-token-string)
9473 (js2-tt-name tt))))
9474 name)
9475 (setq name (make-js2-name-node :pos beg
9476 :name s
9477 :len (length s)))
9478 (if check-activation-p
9479 (js2-check-activation-name s (or token js2-NAME)))
9480 name))
9481
9482 ;;; Indentation support
9483
9484 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9485 ;; Karl cleverly deduces that the desired indentation level is often a
9486 ;; function of paren/bracket/brace nesting depth, which can be determined
9487 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9488 ;; then does some equally clever checks to see if we're in the context of a
9489 ;; substatement of a possibly braceless statement keyword such as if, while,
9490 ;; or finally. This approach yields pretty good results.
9491
9492 ;; The indenter is often "wrong", however, and needs to be overridden.
9493 ;; The right long-term solution is probably to emulate (or integrate
9494 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9495 ;; parse tree from `js2-parse' is present, which is not true at the
9496 ;; moment the user is typing, computing indentation is still thousands
9497 ;; of lines of code to handle every possible syntactic edge case.
9498
9499 ;; In the meantime, the compromise solution is that we offer a "bounce
9500 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9501 ;; current line indent among various likely guess points. This approach
9502 ;; is far from perfect, but should at least make it slightly easier to
9503 ;; move the line towards its desired indentation when manually
9504 ;; overriding Karl's heuristic nesting guesser.
9505
9506 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9507 ;; extensions such as `let' and Array comprehensions. Major kudos to
9508 ;; Karl for coming up with the initial approach, which packs a lot of
9509 ;; punch for so little code.
9510
9511 (defconst js2-possibly-braceless-keywords-re
9512 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9513 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9514 "try" "while" "with" "let")))
9515 "Regular expression matching keywords that are optionally
9516 followed by an opening brace.")
9517
9518 (defconst js2-indent-operator-re
9519 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9520 (regexp-opt '("in" "instanceof") 'words))
9521 "Regular expression matching operators that affect indentation
9522 of continued expressions.")
9523
9524 (defconst js2-declaration-keyword-re
9525 (regexp-opt '("var" "let" "const") 'words)
9526 "Regular expression matching variable declaration keywords.")
9527
9528 (defun js2-re-search-forward-inner (regexp &optional bound count)
9529 "Auxiliary function for `js2-re-search-forward'."
9530 (let (parse saved-point)
9531 (while (> count 0)
9532 (re-search-forward regexp bound)
9533 (setq parse (if saved-point
9534 (parse-partial-sexp saved-point (point))
9535 (syntax-ppss (point))))
9536 (cond ((nth 3 parse)
9537 (re-search-forward
9538 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9539 (save-excursion (end-of-line) (point)) t))
9540 ((nth 7 parse)
9541 (forward-line))
9542 ((or (nth 4 parse)
9543 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9544 (re-search-forward "\\*/"))
9545 (t
9546 (setq count (1- count))))
9547 (setq saved-point (point))))
9548 (point))
9549
9550 (defun js2-re-search-forward (regexp &optional bound noerror count)
9551 "Search forward but ignore strings and comments.
9552 Invokes `re-search-forward' but treats the buffer as if strings
9553 and comments have been removed."
9554 (let ((saved-point (point))
9555 (search-expr
9556 (cond ((null count)
9557 '(js2-re-search-forward-inner regexp bound 1))
9558 ((< count 0)
9559 '(js2-re-search-backward-inner regexp bound (- count)))
9560 ((> count 0)
9561 '(js2-re-search-forward-inner regexp bound count)))))
9562 (condition-case err
9563 (eval search-expr)
9564 (search-failed
9565 (goto-char saved-point)
9566 (unless noerror
9567 (error (error-message-string err)))))))
9568
9569 (defun js2-re-search-backward-inner (regexp &optional bound count)
9570 "Auxiliary function for `js2-re-search-backward'."
9571 (let (parse)
9572 (while (> count 0)
9573 (re-search-backward regexp bound)
9574 (setq parse (syntax-ppss (point)))
9575 (cond ((nth 3 parse)
9576 (re-search-backward
9577 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9578 (line-beginning-position) t))
9579 ((nth 7 parse)
9580 (goto-char (nth 8 parse)))
9581 ((or (nth 4 parse)
9582 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9583 (re-search-backward "/\\*"))
9584 (t
9585 (setq count (1- count))))))
9586 (point))
9587
9588 (defun js2-re-search-backward (regexp &optional bound noerror count)
9589 "Search backward but ignore strings and comments.
9590 Invokes `re-search-backward' but treats the buffer as if strings
9591 and comments have been removed."
9592 (let ((saved-point (point))
9593 (search-expr
9594 (cond ((null count)
9595 '(js2-re-search-backward-inner regexp bound 1))
9596 ((< count 0)
9597 '(js2-re-search-forward-inner regexp bound (- count)))
9598 ((> count 0)
9599 '(js2-re-search-backward-inner regexp bound count)))))
9600 (condition-case err
9601 (eval search-expr)
9602 (search-failed
9603 (goto-char saved-point)
9604 (unless noerror
9605 (error (error-message-string err)))))))
9606
9607 (defun js2-looking-at-operator-p ()
9608 "Return non-nil if text after point is a non-comma operator."
9609 (and (looking-at js2-indent-operator-re)
9610 (or (not (looking-at ":"))
9611 (save-excursion
9612 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9613 (looking-at "?"))))))
9614
9615 (defun js2-continued-expression-p ()
9616 "Return non-nil if the current line continues an expression."
9617 (save-excursion
9618 (back-to-indentation)
9619 (or (js2-looking-at-operator-p)
9620 (when (catch 'found
9621 (while (and (re-search-backward "\n" nil t)
9622 (let ((state (syntax-ppss)))
9623 (when (nth 4 state)
9624 (goto-char (nth 8 state))) ;; skip comments
9625 (skip-chars-backward " \t")
9626 (if (bolp)
9627 t
9628 (throw 'found t))))))
9629 (backward-char)
9630 (when (js2-looking-at-operator-p)
9631 (backward-char)
9632 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))
9633
9634 (defun js2-end-of-do-while-loop-p ()
9635 "Return non-nil if word after point is `while' of a do-while
9636 statement, else returns nil. A braceless do-while statement
9637 spanning several lines requires that the start of the loop is
9638 indented to the same column as the current line."
9639 (interactive)
9640 (save-excursion
9641 (when (looking-at "\\s-*\\<while\\>")
9642 (if (save-excursion
9643 (skip-chars-backward "[ \t\n]*}")
9644 (looking-at "[ \t\n]*}"))
9645 (save-excursion
9646 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9647 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9648 (or (looking-at "\\<do\\>")
9649 (let ((saved-indent (current-indentation)))
9650 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9651 (/= (current-indentation) saved-indent)))
9652 (and (looking-at "[ \t]*\\<do\\>")
9653 (not (js2-re-search-forward
9654 "\\<while\\>" (point-at-eol) t))
9655 (= (current-indentation) saved-indent))))))))
9656
9657 (defun js2-multiline-decl-indentation ()
9658 "Return the declaration indentation column if the current line belongs
9659 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9660 (let (forward-sexp-function ; use Lisp version
9661 at-opening-bracket)
9662 (save-excursion
9663 (back-to-indentation)
9664 (when (not (looking-at js2-declaration-keyword-re))
9665 (when (looking-at js2-indent-operator-re)
9666 (goto-char (match-end 0))) ; continued expressions are ok
9667 (while (and (not at-opening-bracket)
9668 (not (bobp))
9669 (let ((pos (point)))
9670 (save-excursion
9671 (js2-backward-sws)
9672 (or (eq (char-before) ?,)
9673 (and (not (eq (char-before) ?\;))
9674 (prog2 (skip-syntax-backward ".")
9675 (looking-at js2-indent-operator-re)
9676 (js2-backward-sws))
9677 (not (eq (char-before) ?\;)))
9678 (js2-same-line pos)))))
9679 (condition-case err
9680 (backward-sexp)
9681 (scan-error (setq at-opening-bracket t))))
9682 (when (looking-at js2-declaration-keyword-re)
9683 (goto-char (match-end 0))
9684 (1+ (current-column)))))))
9685
9686 (defun js2-ctrl-statement-indentation ()
9687 "Return the proper indentation of current line if it is a control statement.
9688 Returns an indentation if this line starts the body of a control
9689 statement without braces, else returns nil."
9690 (let (forward-sexp-function)
9691 (save-excursion
9692 (back-to-indentation)
9693 (when (and (not (js2-same-line (point-min)))
9694 (not (looking-at "{"))
9695 (js2-re-search-backward "[[:graph:]]" nil t)
9696 (not (looking-at "[{([]"))
9697 (progn
9698 (forward-char)
9699 (when (= (char-before) ?\))
9700 ;; scan-sexps sometimes throws an error
9701 (ignore-errors (backward-sexp))
9702 (skip-chars-backward " \t" (point-at-bol)))
9703 (let ((pt (point)))
9704 (back-to-indentation)
9705 (when (looking-at "}[ \t]*")
9706 (goto-char (match-end 0)))
9707 (and (looking-at js2-possibly-braceless-keywords-re)
9708 (= (match-end 0) pt)
9709 (not (js2-end-of-do-while-loop-p))))))
9710 (+ (current-indentation) js2-basic-offset)))))
9711
9712 (defun js2-indent-in-array-comp (parse-status)
9713 "Return non-nil if we think we're in an array comprehension.
9714 In particular, return the buffer position of the first `for' kwd."
9715 (let ((bracket (nth 1 parse-status))
9716 (end (point)))
9717 (when bracket
9718 (save-excursion
9719 (goto-char bracket)
9720 (when (looking-at "\\[")
9721 (forward-char 1)
9722 (js2-forward-sws)
9723 (if (looking-at "[[{]")
9724 (let (forward-sexp-function) ; use Lisp version
9725 (forward-sexp) ; skip destructuring form
9726 (js2-forward-sws)
9727 (if (and (/= (char-after) ?,) ; regular array
9728 (looking-at "for"))
9729 (match-beginning 0)))
9730 ;; to skip arbitrary expressions we need the parser,
9731 ;; so we'll just guess at it.
9732 (if (and (> end (point)) ; not empty literal
9733 (re-search-forward "[^,]]* \\(for\\) " end t)
9734 ;; not inside comment or string literal
9735 (let ((state (parse-partial-sexp bracket (point))))
9736 (not (or (nth 3 state) (nth 4 state)))))
9737 (match-beginning 1))))))))
9738
9739 (defun js2-array-comp-indentation (parse-status for-kwd)
9740 (if (js2-same-line for-kwd)
9741 ;; first continuation line
9742 (save-excursion
9743 (goto-char (nth 1 parse-status))
9744 (forward-char 1)
9745 (skip-chars-forward " \t")
9746 (current-column))
9747 (save-excursion
9748 (goto-char for-kwd)
9749 (current-column))))
9750
9751 (defun js2-proper-indentation (parse-status)
9752 "Return the proper indentation for the current line."
9753 (save-excursion
9754 (back-to-indentation)
9755 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9756 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9757 (continued-expr-p (js2-continued-expression-p))
9758 (declaration-indent (and js2-pretty-multiline-declarations
9759 (js2-multiline-decl-indentation)))
9760 (bracket (nth 1 parse-status))
9761 beg)
9762 (cond
9763 ;; indent array comprehension continuation lines specially
9764 ((and bracket
9765 (>= js2-language-version 170)
9766 (not (js2-same-line bracket))
9767 (setq beg (js2-indent-in-array-comp parse-status))
9768 (>= (point) (save-excursion
9769 (goto-char beg)
9770 (point-at-bol)))) ; at or after first loop?
9771 (js2-array-comp-indentation parse-status beg))
9772
9773 (ctrl-stmt-indent)
9774
9775 ((and declaration-indent continued-expr-p)
9776 (+ declaration-indent js2-basic-offset))
9777
9778 (declaration-indent)
9779
9780 (bracket
9781 (goto-char bracket)
9782 (cond
9783 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9784 (when (save-excursion (skip-chars-backward " \t)")
9785 (looking-at ")"))
9786 (backward-list))
9787 (back-to-indentation)
9788 (and (eq js2-pretty-multiline-declarations 'all)
9789 (looking-at js2-declaration-keyword-re)
9790 (goto-char (1+ (match-end 0))))
9791 (cond (same-indent-p
9792 (current-column))
9793 (continued-expr-p
9794 (+ (current-column) (* 2 js2-basic-offset)))
9795 (t
9796 (+ (current-column) js2-basic-offset))))
9797 (t
9798 (unless same-indent-p
9799 (forward-char)
9800 (skip-chars-forward " \t"))
9801 (current-column))))
9802
9803 (continued-expr-p js2-basic-offset)
9804
9805 (t 0)))))
9806
9807 (defun js2-lineup-comment (parse-status)
9808 "Indent a multi-line block comment continuation line."
9809 (let* ((beg (nth 8 parse-status))
9810 (first-line (js2-same-line beg))
9811 (offset (save-excursion
9812 (goto-char beg)
9813 (if (looking-at "/\\*")
9814 (+ 1 (current-column))
9815 0))))
9816 (unless first-line
9817 (indent-line-to offset))))
9818
9819 (defun js2-backward-sws ()
9820 "Move backward through whitespace and comments."
9821 (interactive)
9822 (while (forward-comment -1)))
9823
9824 (defun js2-forward-sws ()
9825 "Move forward through whitespace and comments."
9826 (interactive)
9827 (while (forward-comment 1)))
9828
9829 (defun js2-current-indent (&optional pos)
9830 "Return column of indentation on current line.
9831 If POS is non-nil, go to that point and return indentation for that line."
9832 (save-excursion
9833 (if pos
9834 (goto-char pos))
9835 (back-to-indentation)
9836 (current-column)))
9837
9838 (defun js2-arglist-close ()
9839 "Return non-nil if we're on a line beginning with a close-paren/brace."
9840 (save-excursion
9841 (goto-char (point-at-bol))
9842 (js2-forward-sws)
9843 (looking-at "[])}]")))
9844
9845 (defun js2-indent-looks-like-label-p ()
9846 (goto-char (point-at-bol))
9847 (js2-forward-sws)
9848 (looking-at (concat js2-mode-identifier-re ":")))
9849
9850 (defun js2-indent-in-objlit-p (parse-status)
9851 "Return non-nil if this looks like an object-literal entry."
9852 (let ((start (nth 1 parse-status)))
9853 (and
9854 start
9855 (save-excursion
9856 (and (zerop (forward-line -1))
9857 (not (< (point) start)) ; crossed a {} boundary
9858 (js2-indent-looks-like-label-p)))
9859 (save-excursion
9860 (js2-indent-looks-like-label-p)))))
9861
9862 ;; If prev line looks like foobar({ then we're passing an object
9863 ;; literal to a function call, and people pretty much always want to
9864 ;; de-dent back to the previous line, so move the 'basic-offset'
9865 ;; position to the front.
9866 (defun js2-indent-objlit-arg-p (parse-status)
9867 (save-excursion
9868 (back-to-indentation)
9869 (js2-backward-sws)
9870 (and (eq (1- (point)) (nth 1 parse-status))
9871 (eq (char-before) ?{)
9872 (progn
9873 (forward-char -1)
9874 (skip-chars-backward " \t")
9875 (eq (char-before) ?\()))))
9876
9877 (defun js2-indent-case-block-p ()
9878 (save-excursion
9879 (back-to-indentation)
9880 (js2-backward-sws)
9881 (goto-char (point-at-bol))
9882 (skip-chars-forward " \t")
9883 (looking-at "case\\s-.+:")))
9884
9885 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
9886 "Cycle among alternate computed indentation positions.
9887 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9888 of the buffer to the current point. NORMAL-COL is the indentation
9889 column computed by the heuristic guesser based on current paren,
9890 bracket, brace and statement nesting. If BACKWARDS, cycle positions
9891 in reverse."
9892 (let ((cur-indent (js2-current-indent))
9893 (old-buffer-undo-list buffer-undo-list)
9894 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9895 (current-line (save-excursion
9896 (forward-line 0) ; move to bol
9897 (1+ (count-lines (point-min) (point)))))
9898 positions pos main-pos anchor arglist-cont same-indent
9899 prev-line-col basic-offset computed-pos)
9900 ;; temporarily don't record undo info, if user requested this
9901 (when js2-mode-indent-inhibit-undo
9902 (setq buffer-undo-list t))
9903 (unwind-protect
9904 (progn
9905 ;; First likely point: indent from beginning of previous code line
9906 (push (setq basic-offset
9907 (+ (save-excursion
9908 (back-to-indentation)
9909 (js2-backward-sws)
9910 (back-to-indentation)
9911 (setq prev-line-col (current-column)))
9912 js2-basic-offset))
9913 positions)
9914
9915 ;; (First + epsilon) likely point: indent 2x from beginning of
9916 ;; previous code line. Google does it this way.
9917 (push (setq basic-offset
9918 (+ (save-excursion
9919 (back-to-indentation)
9920 (js2-backward-sws)
9921 (back-to-indentation)
9922 (setq prev-line-col (current-column)))
9923 (* 2 js2-basic-offset)))
9924 positions)
9925
9926 ;; Second likely point: indent from assign-expr RHS. This
9927 ;; is just a crude guess based on finding " = " on the previous
9928 ;; line containing actual code.
9929 (setq pos (save-excursion
9930 (forward-line -1)
9931 (goto-char (point-at-bol))
9932 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
9933 (point-at-eol) t)
9934 (goto-char (match-end 1))
9935 (skip-chars-forward " \t\r\n")
9936 (current-column))))
9937 (when pos
9938 (incf pos js2-basic-offset)
9939 (push pos positions))
9940
9941 ;; Third likely point: same indent as previous line of code.
9942 ;; Make it the first likely point if we're not on an
9943 ;; arglist-close line and previous line ends in a comma, or
9944 ;; both this line and prev line look like object-literal
9945 ;; elements.
9946 (setq pos (save-excursion
9947 (goto-char (point-at-bol))
9948 (js2-backward-sws)
9949 (back-to-indentation)
9950 (prog1
9951 (current-column)
9952 ;; while we're here, look for trailing comma
9953 (if (save-excursion
9954 (goto-char (point-at-eol))
9955 (js2-backward-sws)
9956 (eq (char-before) ?,))
9957 (setq arglist-cont (1- (point)))))))
9958 (when pos
9959 (if (and (or arglist-cont
9960 (js2-indent-in-objlit-p parse-status))
9961 (not (js2-arglist-close)))
9962 (setq same-indent pos))
9963 (push pos positions))
9964
9965 ;; Fourth likely point: first preceding code with less indentation.
9966 ;; than the immediately preceding code line.
9967 (setq pos (save-excursion
9968 (back-to-indentation)
9969 (js2-backward-sws)
9970 (back-to-indentation)
9971 (setq anchor (current-column))
9972 (while (and (zerop (forward-line -1))
9973 (>= (progn
9974 (back-to-indentation)
9975 (current-column))
9976 anchor)))
9977 (setq pos (current-column))))
9978 (push pos positions)
9979
9980 ;; nesting-heuristic position, main by default
9981 (push (setq main-pos normal-col) positions)
9982
9983 ;; delete duplicates and sort positions list
9984 (setq positions (sort (delete-dups positions) '<))
9985
9986 ;; comma-list continuation lines: prev line indent takes precedence
9987 (if same-indent
9988 (setq main-pos same-indent))
9989
9990 ;; common special cases where we want to indent in from previous line
9991 (if (or (js2-indent-case-block-p)
9992 (js2-indent-objlit-arg-p parse-status))
9993 (setq main-pos basic-offset))
9994
9995 ;; if bouncing backwards, reverse positions list
9996 (if backwards
9997 (setq positions (reverse positions)))
9998
9999 ;; record whether we're already sitting on one of the alternatives
10000 (setq pos (member cur-indent positions))
10001
10002 (cond
10003 ;; case 0: we're one one of the alternatives and this is the
10004 ;; first time they've pressed TAB on this line (best-guess).
10005 ((and js2-mode-indent-ignore-first-tab
10006 pos
10007 ;; first time pressing TAB on this line?
10008 (not (eq js2-mode-last-indented-line current-line)))
10009 ;; do nothing
10010 (setq computed-pos nil))
10011 ;; case 1: only one computed position => use it
10012 ((null (cdr positions))
10013 (setq computed-pos 0))
10014 ;; case 2: not on any of the computed spots => use main spot
10015 ((not pos)
10016 (setq computed-pos (js2-position main-pos positions)))
10017 ;; case 3: on last position: cycle to first position
10018 ((null (cdr pos))
10019 (setq computed-pos 0))
10020 ;; case 4: on intermediate position: cycle to next position
10021 (t
10022 (setq computed-pos (js2-position (second pos) positions))))
10023
10024 ;; see if any hooks want to indent; otherwise we do it
10025 (loop with result = nil
10026 for hook in js2-indent-hook
10027 while (null result)
10028 do
10029 (setq result (funcall hook positions computed-pos))
10030 finally do
10031 (unless (or result (null computed-pos))
10032 (indent-line-to (nth computed-pos positions)))))
10033
10034 ;; finally
10035 (if js2-mode-indent-inhibit-undo
10036 (setq buffer-undo-list old-buffer-undo-list))
10037 ;; see commentary for `js2-mode-last-indented-line'
10038 (setq js2-mode-last-indented-line current-line))))
10039
10040 (defun js2-indent-bounce-backwards ()
10041 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10042 cycles between the computed indentation positions in reverse order."
10043 (interactive)
10044 (js2-indent-line t))
10045
10046 (defun js2-1-line-comment-continuation-p ()
10047 "Return t if we're in a 1-line comment continuation.
10048 If so, we don't ever want to use bounce-indent."
10049 (save-excursion
10050 (and (progn
10051 (forward-line 0)
10052 (looking-at "\\s-*//"))
10053 (progn
10054 (forward-line -1)
10055 (forward-line 0)
10056 (when (looking-at "\\s-*$")
10057 (js2-backward-sws)
10058 (forward-line 0))
10059 (looking-at "\\s-*//")))))
10060
10061 (defun js2-indent-line (&optional bounce-backwards)
10062 "Indent the current line as JavaScript source text."
10063 (interactive)
10064 (let (parse-status current-indent offset indent-col moved
10065 ;; Don't whine about errors/warnings when we're indenting.
10066 ;; This has to be set before calling parse-partial-sexp below.
10067 (inhibit-point-motion-hooks t))
10068 (setq parse-status (save-excursion
10069 (syntax-ppss (point-at-bol)))
10070 offset (- (point) (save-excursion
10071 (back-to-indentation)
10072 (point))))
10073 (js2-with-underscore-as-word-syntax
10074 (if (nth 4 parse-status)
10075 (js2-lineup-comment parse-status)
10076 (setq indent-col (js2-proper-indentation parse-status))
10077 ;; See comments below about `js2-mode-last-indented-line'.
10078 (cond
10079 ;; bounce-indenting is disabled during electric-key indent.
10080 ;; It doesn't work well on first line of buffer.
10081 ((and js2-bounce-indent-p
10082 (not (js2-same-line (point-min)))
10083 (not (js2-1-line-comment-continuation-p)))
10084 (js2-bounce-indent indent-col parse-status bounce-backwards))
10085 ;; just indent to the guesser's likely spot
10086 (t (indent-line-to indent-col))))
10087 (when (plusp offset)
10088 (forward-char offset)))))
10089
10090 (defun js2-indent-region (start end)
10091 "Indent the region, but don't use bounce indenting."
10092 (let ((js2-bounce-indent-p nil)
10093 (indent-region-function nil)
10094 (after-change-functions (remq 'js2-mode-edit
10095 after-change-functions)))
10096 (indent-region start end nil) ; nil for byte-compiler
10097 (js2-mode-edit start end (- end start))))
10098
10099 (defvar js2-minor-mode-map
10100 (let ((map (make-sparse-keymap)))
10101 (define-key map (kbd "C-c C-`") #'js2-next-error)
10102 (define-key map [mouse-1] #'js2-mode-show-node)
10103 map)
10104 "Keymap used when `js2-minor-mode' is active.")
10105
10106 ;;;###autoload
10107 (define-minor-mode js2-minor-mode
10108 "Minor mode for running js2 as a background linter.
10109 This allows you to use a different major mode for JavaScript editing,
10110 such as `espresso-mode', while retaining the asynchronous error/warning
10111 highlighting features of `js2-mode'."
10112 :group 'js2-mode
10113 :lighter " js-lint"
10114 (if js2-minor-mode
10115 (js2-minor-mode-enter)
10116 (js2-minor-mode-exit)))
10117
10118 (defun js2-minor-mode-enter ()
10119 "Initialization for `js2-minor-mode'."
10120 (set (make-local-variable 'max-lisp-eval-depth)
10121 (max max-lisp-eval-depth 3000))
10122 (setq next-error-function #'js2-next-error)
10123 (js2-set-default-externs)
10124 ;; Experiment: make reparse-delay longer for longer files.
10125 (if (plusp js2-dynamic-idle-timer-adjust)
10126 (setq js2-idle-timer-delay
10127 (* js2-idle-timer-delay
10128 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10129 (setq js2-mode-buffer-dirty-p t
10130 js2-mode-parsing nil)
10131 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10132 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10133 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10134 (when js2-include-jslint-globals
10135 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10136 (run-hooks 'js2-init-hook)
10137 (js2-reparse))
10138
10139 (defun js2-minor-mode-exit ()
10140 "Turn off `js2-minor-mode'."
10141 (setq next-error-function nil)
10142 (remove-hook 'after-change-functions #'js2-mode-edit t)
10143 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10144 (when js2-mode-node-overlay
10145 (delete-overlay js2-mode-node-overlay)
10146 (setq js2-mode-node-overlay nil))
10147 (js2-remove-overlays)
10148 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
10149 (setq js2-mode-ast nil))
10150
10151 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10152 (make-variable-buffer-local 'js2-source-buffer)
10153
10154 (defun* js2-display-error-list ()
10155 "Display a navigable buffer listing parse errors/warnings."
10156 (interactive)
10157 (unless (js2-have-errors-p)
10158 (message "No errors")
10159 (return-from js2-display-error-list))
10160 (labels ((annotate-list
10161 (lst type)
10162 "Add diagnostic TYPE and line number to errs list"
10163 (mapcar (lambda (err)
10164 (list err type (line-number-at-pos (nth 1 err))))
10165 lst)))
10166 (let* ((srcbuf (current-buffer))
10167 (errbuf (get-buffer-create "*js-lint*"))
10168 (errors (annotate-list
10169 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10170 'js2-error)) ; must be a valid face name
10171 (warnings (annotate-list
10172 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10173 'js2-warning)) ; must be a valid face name
10174 (all-errs (sort (append errors warnings)
10175 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10176 (with-current-buffer errbuf
10177 (let ((inhibit-read-only t))
10178 (erase-buffer)
10179 (dolist (err all-errs)
10180 (destructuring-bind ((msg-key beg end &rest) type line) err
10181 (insert-text-button
10182 (format "line %d: %s" line (js2-get-msg msg-key))
10183 'face type
10184 'follow-link "\C-m"
10185 'action 'js2-error-buffer-jump
10186 'js2-msg (js2-get-msg msg-key)
10187 'js2-pos beg)
10188 (insert "\n"))))
10189 (js2-error-buffer-mode)
10190 (setq js2-source-buffer srcbuf)
10191 (pop-to-buffer errbuf)
10192 (goto-char (point-min))
10193 (unless (eobp)
10194 (js2-error-buffer-view))))))
10195
10196 (defvar js2-error-buffer-mode-map
10197 (let ((map (make-sparse-keymap)))
10198 (define-key map "n" #'js2-error-buffer-next)
10199 (define-key map "p" #'js2-error-buffer-prev)
10200 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10201 (define-key map "o" #'js2-error-buffer-view)
10202 (define-key map "q" #'js2-error-buffer-quit)
10203 map)
10204 "Keymap used for js2 diagnostics buffers.")
10205
10206 (defun js2-error-buffer-mode ()
10207 "Major mode for js2 diagnostics buffers.
10208 Selecting an error will jump it to the corresponding source-buffer error.
10209 \\{js2-error-buffer-mode-map}"
10210 (interactive)
10211 (setq major-mode 'js2-error-buffer-mode
10212 mode-name "JS Lint Diagnostics")
10213 (use-local-map js2-error-buffer-mode-map)
10214 (setq truncate-lines t)
10215 (set-buffer-modified-p nil)
10216 (setq buffer-read-only t)
10217 (run-hooks 'js2-error-buffer-mode-hook))
10218
10219 (defun js2-error-buffer-next ()
10220 "Move to next error and view it."
10221 (interactive)
10222 (when (zerop (forward-line 1))
10223 (js2-error-buffer-view)))
10224
10225 (defun js2-error-buffer-prev ()
10226 "Move to previous error and view it."
10227 (interactive)
10228 (when (zerop (forward-line -1))
10229 (js2-error-buffer-view)))
10230
10231 (defun js2-error-buffer-quit ()
10232 "Kill the current buffer."
10233 (interactive)
10234 (kill-buffer))
10235
10236 (defun js2-error-buffer-jump (&rest ignored)
10237 "Jump cursor to current error in source buffer."
10238 (interactive)
10239 (when (js2-error-buffer-view)
10240 (pop-to-buffer js2-source-buffer)))
10241
10242 (defun js2-error-buffer-view ()
10243 "Scroll source buffer to show error at current line."
10244 (interactive)
10245 (cond
10246 ((not (eq major-mode 'js2-error-buffer-mode))
10247 (message "Not in a js2 errors buffer"))
10248 ((not (buffer-live-p js2-source-buffer))
10249 (message "Source buffer has been killed"))
10250 ((not (wholenump (get-text-property (point) 'js2-pos)))
10251 (message "There does not seem to be an error here"))
10252 (t
10253 (let ((pos (get-text-property (point) 'js2-pos))
10254 (msg (get-text-property (point) 'js2-msg)))
10255 (save-selected-window
10256 (pop-to-buffer js2-source-buffer)
10257 (goto-char pos)
10258 (message msg))))))
10259
10260 ;;;###autoload
10261 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10262 ;; FIXME: Should derive from js-mode.
10263 "Major mode for editing JavaScript code."
10264 ;; Used by comment-region; don't change it.
10265 (set (make-local-variable 'comment-start) "//")
10266 (set (make-local-variable 'comment-end) "")
10267 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
10268 (set (make-local-variable 'max-lisp-eval-depth)
10269 (max max-lisp-eval-depth 3000))
10270 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10271 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10272 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10273 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10274 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10275 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10276 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10277 ;; for characters inside regexp literals.
10278 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10279 ;; this is necessary to make `show-paren-function' work properly
10280 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10281 ;; needed for M-x rgrep, among other things
10282 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10283
10284 (set (make-local-variable 'electric-indent-chars)
10285 (append '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
10286 electric-indent-chars))
10287 (set (make-local-variable 'electric-layout-rules)
10288 '((?\; . after) (?\{ . after) (?\} . before)))
10289
10290 ;; some variables needed by cc-engine for paragraph-fill, etc.
10291 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10292 c-comment-start-regexp "/[*/]\\|\\s|"
10293 c-line-comment-starter "//"
10294 c-paragraph-start js2-paragraph-start
10295 c-paragraph-separate "$"
10296 c-syntactic-ws-start js2-syntactic-ws-start
10297 c-syntactic-ws-end js2-syntactic-ws-end
10298 c-syntactic-eol js2-syntactic-eol)
10299
10300 (let ((c-buffer-is-cc-mode t))
10301 ;; Copied from `js-mode'. Also see Bug#6071.
10302 (make-local-variable 'paragraph-start)
10303 (make-local-variable 'paragraph-separate)
10304 (make-local-variable 'paragraph-ignore-fill-prefix)
10305 (make-local-variable 'adaptive-fill-mode)
10306 (make-local-variable 'adaptive-fill-regexp)
10307 (c-setup-paragraph-variables))
10308
10309 (setq font-lock-defaults '(nil t))
10310
10311 ;; Experiment: make reparse-delay longer for longer files.
10312 (when (plusp js2-dynamic-idle-timer-adjust)
10313 (setq js2-idle-timer-delay
10314 (* js2-idle-timer-delay
10315 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10316
10317 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10318 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10319 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10320 (setq next-error-function #'js2-next-error)
10321 (imenu-add-to-menubar (concat "IM-" mode-name))
10322 (add-to-invisibility-spec '(js2-outline . t))
10323 (set (make-local-variable 'line-move-ignore-invisible) t)
10324 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10325
10326 (setq js2-mode-functions-hidden nil
10327 js2-mode-comments-hidden nil
10328 js2-mode-buffer-dirty-p t
10329 js2-mode-parsing nil)
10330
10331 (js2-set-default-externs)
10332
10333 (when js2-include-jslint-globals
10334 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10335
10336 (run-hooks 'js2-init-hook)
10337
10338 (js2-reparse))
10339
10340 (defun js2-mode-exit ()
10341 "Exit `js2-mode' and clean up."
10342 (interactive)
10343 (when js2-mode-node-overlay
10344 (delete-overlay js2-mode-node-overlay)
10345 (setq js2-mode-node-overlay nil))
10346 (js2-remove-overlays)
10347 (setq js2-mode-ast nil)
10348 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10349 (remove-from-invisibility-spec '(js2-outline . t))
10350 (js2-mode-show-all)
10351 (with-silent-modifications
10352 (js2-clear-face (point-min) (point-max))))
10353
10354 (defun js2-mode-reset-timer ()
10355 "Cancel any existing parse timer and schedule a new one."
10356 (if js2-mode-parse-timer
10357 (cancel-timer js2-mode-parse-timer))
10358 (setq js2-mode-parsing nil)
10359 (let ((timer (timer-create)))
10360 (setq js2-mode-parse-timer timer)
10361 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10362 (timer-set-idle-time timer js2-idle-timer-delay)
10363 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10364 (timer-activate-when-idle timer nil)))
10365
10366 (defun js2-mode-idle-reparse (buffer)
10367 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10368 it to be reparsed when the buffer is selected."
10369 (if (eq buffer (current-buffer))
10370 (js2-reparse)
10371 ;; reparse when the buffer is selected again
10372 (with-current-buffer buffer
10373 (add-hook 'window-configuration-change-hook
10374 #'js2-mode-idle-reparse-inner
10375 nil t))))
10376
10377 (defun js2-mode-idle-reparse-inner ()
10378 (remove-hook 'window-configuration-change-hook
10379 #'js2-mode-idle-reparse-inner
10380 t)
10381 (js2-reparse))
10382
10383 (defun js2-mode-edit (beg end len)
10384 "Schedule a new parse after buffer is edited.
10385 Buffer edit spans from BEG to END and is of length LEN."
10386 (setq js2-mode-buffer-dirty-p t)
10387 (js2-mode-hide-overlay)
10388 (js2-mode-reset-timer))
10389
10390 (defun js2-minor-mode-edit (beg end len)
10391 "Callback for buffer edits in `js2-mode'.
10392 Schedules a new parse after buffer is edited.
10393 Buffer edit spans from BEG to END and is of length LEN."
10394 (setq js2-mode-buffer-dirty-p t)
10395 (js2-mode-hide-overlay)
10396 (js2-mode-reset-timer))
10397
10398 (defun js2-reparse (&optional force)
10399 "Re-parse current buffer after user finishes some data entry.
10400 If we get any user input while parsing, including cursor motion,
10401 we discard the parse and reschedule it. If FORCE is nil, then the
10402 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10403 (let (time
10404 interrupted-p
10405 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10406 (unless js2-mode-parsing
10407 (setq js2-mode-parsing t)
10408 (unwind-protect
10409 (when (or js2-mode-buffer-dirty-p force)
10410 (js2-remove-overlays)
10411 (with-silent-modifications
10412 (setq js2-mode-buffer-dirty-p nil
10413 js2-mode-fontifications nil
10414 js2-mode-deferred-properties nil)
10415 (if js2-mode-verbose-parse-p
10416 (message "parsing..."))
10417 (setq time
10418 (js2-time
10419 (setq interrupted-p
10420 (catch 'interrupted
10421 (js2-parse)
10422 ;; if parsing is interrupted, comments and regex
10423 ;; literals stay ignored by `parse-partial-sexp'
10424 (remove-text-properties (point-min) (point-max)
10425 '(syntax-table))
10426 (js2-mode-apply-deferred-properties)
10427 (js2-mode-remove-suppressed-warnings)
10428 (js2-mode-show-warnings)
10429 (js2-mode-show-errors)
10430 (if (>= js2-highlight-level 1)
10431 (js2-highlight-jsdoc js2-mode-ast))
10432 nil))))
10433 (if interrupted-p
10434 (progn
10435 ;; unfinished parse => try again
10436 (setq js2-mode-buffer-dirty-p t)
10437 (js2-mode-reset-timer))
10438 (if js2-mode-verbose-parse-p
10439 (message "Parse time: %s" time)))))
10440 (setq js2-mode-parsing nil)
10441 (unless interrupted-p
10442 (setq js2-mode-parse-timer nil))))))
10443
10444 (defun js2-mode-show-node (event)
10445 "Debugging aid: highlight selected AST node on mouse click."
10446 (interactive "e")
10447 (mouse-set-point event)
10448 (setq deactivate-mark t)
10449 (when js2-mode-show-overlay
10450 (let ((node (js2-node-at-point))
10451 beg end)
10452 (if (null node)
10453 (message "No node found at location %s" (point))
10454 (setq beg (js2-node-abs-pos node)
10455 end (+ beg (js2-node-len node)))
10456 (if js2-mode-node-overlay
10457 (move-overlay js2-mode-node-overlay beg end)
10458 (setq js2-mode-node-overlay (make-overlay beg end))
10459 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10460 (with-silent-modifications
10461 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10462 (message "%s, parent: %s"
10463 (js2-node-short-name node)
10464 (if (js2-node-parent node)
10465 (js2-node-short-name (js2-node-parent node))
10466 "nil"))))))
10467
10468 (defun js2-mode-hide-overlay (&optional p1 p2)
10469 "Remove the debugging overlay when the point moves.
10470 P1 and P2 are the old and new values of point, respectively."
10471 (when js2-mode-node-overlay
10472 (let ((beg (overlay-start js2-mode-node-overlay))
10473 (end (overlay-end js2-mode-node-overlay)))
10474 ;; Sometimes we're called spuriously.
10475 (unless (and p2
10476 (>= p2 beg)
10477 (<= p2 end))
10478 (with-silent-modifications
10479 (remove-text-properties beg end '(point-left nil)))
10480 (delete-overlay js2-mode-node-overlay)
10481 (setq js2-mode-node-overlay nil)))))
10482
10483 (defun js2-mode-reset ()
10484 "Debugging helper: reset everything."
10485 (interactive)
10486 (js2-mode-exit)
10487 (js2-mode))
10488
10489 (defun js2-mode-show-warn-or-err (e face)
10490 "Highlight a warning or error E with FACE.
10491 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10492 The last element is optional. When present, use instead of FACE."
10493 (let* ((key (first e))
10494 (beg (second e))
10495 (end (+ beg (third e)))
10496 ;; Don't inadvertently go out of bounds.
10497 (beg (max (point-min) (min beg (point-max))))
10498 (end (max (point-min) (min end (point-max))))
10499 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10500 (ovl (make-overlay beg end)))
10501 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10502 (overlay-put ovl 'js2-error t)
10503 (put-text-property beg end 'help-echo (js2-get-msg key))
10504 (put-text-property beg end 'point-entered #'js2-echo-error)))
10505
10506 (defun js2-remove-overlays ()
10507 "Remove overlays from buffer that have a `js2-error' property."
10508 (let ((beg (point-min))
10509 (end (point-max)))
10510 (save-excursion
10511 (dolist (o (overlays-in beg end))
10512 (when (overlay-get o 'js2-error)
10513 (delete-overlay o))))))
10514
10515 (defun js2-error-at-point (&optional pos)
10516 "Return non-nil if there's an error overlay at POS.
10517 Defaults to point."
10518 (loop with pos = (or pos (point))
10519 for o in (overlays-at pos)
10520 thereis (overlay-get o 'js2-error)))
10521
10522 (defun js2-mode-apply-deferred-properties ()
10523 "Apply fontifications and other text properties recorded during parsing."
10524 (when (plusp js2-highlight-level)
10525 ;; We defer clearing faces as long as possible to eliminate flashing.
10526 (js2-clear-face (point-min) (point-max))
10527 ;; Have to reverse the recorded fontifications list so that errors
10528 ;; and warnings overwrite the normal fontifications.
10529 (dolist (f (nreverse js2-mode-fontifications))
10530 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10531 (setq js2-mode-fontifications nil))
10532 (dolist (p js2-mode-deferred-properties)
10533 (apply #'put-text-property p))
10534 (setq js2-mode-deferred-properties nil))
10535
10536 (defun js2-mode-show-errors ()
10537 "Highlight syntax errors."
10538 (when js2-mode-show-parse-errors
10539 (dolist (e (js2-ast-root-errors js2-mode-ast))
10540 (js2-mode-show-warn-or-err e 'js2-error))))
10541
10542 (defun js2-mode-remove-suppressed-warnings ()
10543 "Take suppressed warnings out of the AST warnings list.
10544 This ensures that the counts and `next-error' are correct."
10545 (setf (js2-ast-root-warnings js2-mode-ast)
10546 (js2-delete-if
10547 (lambda (e)
10548 (let ((key (caar e)))
10549 (or
10550 (and (not js2-strict-trailing-comma-warning)
10551 (string-match "trailing\\.comma" key))
10552 (and (not js2-strict-cond-assign-warning)
10553 (string= key "msg.equal.as.assign"))
10554 (and js2-missing-semi-one-line-override
10555 (string= key "msg.missing.semi")
10556 (let* ((beg (second e))
10557 (node (js2-node-at-point beg))
10558 (fn (js2-mode-find-parent-fn node))
10559 (body (and fn (js2-function-node-body fn)))
10560 (lc (and body (js2-node-abs-pos body)))
10561 (rc (and lc (+ lc (js2-node-len body)))))
10562 (and fn
10563 (or (null body)
10564 (save-excursion
10565 (goto-char beg)
10566 (and (js2-same-line lc)
10567 (js2-same-line rc))))))))))
10568 (js2-ast-root-warnings js2-mode-ast))))
10569
10570 (defun js2-mode-show-warnings ()
10571 "Highlight strict-mode warnings."
10572 (when js2-mode-show-strict-warnings
10573 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10574 (js2-mode-show-warn-or-err e 'js2-warning))))
10575
10576 (defun js2-echo-error (old-point new-point)
10577 "Called by point-motion hooks."
10578 (let ((msg (get-text-property new-point 'help-echo)))
10579 (when (and (stringp msg)
10580 (not (active-minibuffer-window))
10581 (not (current-message)))
10582 (message msg))))
10583
10584 (defalias #'js2-echo-help #'js2-echo-error)
10585
10586 (defun js2-line-break (&optional soft)
10587 "Break line at point and indent, continuing comment if within one.
10588 If inside a string, and `js2-concat-multiline-strings' is not
10589 nil, turn it into concatenation."
10590 (interactive)
10591 (let ((parse-status (syntax-ppss)))
10592 (cond
10593 ;; Check if we're inside a string.
10594 ((nth 3 parse-status)
10595 (if js2-concat-multiline-strings
10596 (js2-mode-split-string parse-status)
10597 (insert "\n")))
10598 ;; Check if inside a block comment.
10599 ((nth 4 parse-status)
10600 (js2-mode-extend-comment (nth 8 parse-status)))
10601 (t
10602 (newline-and-indent)))))
10603
10604 (defun js2-mode-split-string (parse-status)
10605 "Turn a newline in mid-string into a string concatenation.
10606 PARSE-STATUS is as documented in `parse-partial-sexp'."
10607 (let* ((col (current-column))
10608 (quote-char (nth 3 parse-status))
10609 (string-beg (nth 8 parse-status))
10610 (at-eol (eq js2-concat-multiline-strings 'eol)))
10611 (insert quote-char)
10612 (if at-eol
10613 (insert " +\n")
10614 (insert "\n"))
10615 (unless at-eol
10616 (insert "+ "))
10617 (js2-indent-line)
10618 (insert quote-char)
10619 (when (eolp)
10620 (insert quote-char)
10621 (backward-char 1))))
10622
10623 (defun js2-mode-extend-comment (start-pos)
10624 "Indent the line and, when inside a comment block, add comment prefix."
10625 (let (star single col first-line needs-close)
10626 (save-excursion
10627 (back-to-indentation)
10628 (when (< (point) start-pos)
10629 (goto-char start-pos))
10630 (cond
10631 ((looking-at "\\*[^/]")
10632 (setq star t
10633 col (current-column)))
10634 ((looking-at "/\\*")
10635 (setq star t
10636 first-line t
10637 col (1+ (current-column))))
10638 ((looking-at "//")
10639 (setq single t
10640 col (current-column)))))
10641 ;; Heuristic for whether we need to close the comment:
10642 ;; if we've got a parse error here, assume it's an unterminated
10643 ;; comment.
10644 (setq needs-close
10645 (or
10646 (eq (get-text-property (1- (point)) 'point-entered)
10647 'js2-echo-error)
10648 ;; The heuristic above doesn't work well when we're
10649 ;; creating a comment and there's another one downstream,
10650 ;; as our parser thinks this one ends at the end of the
10651 ;; next one. (You can have a /* inside a js block comment.)
10652 ;; So just close it if the next non-ws char isn't a *.
10653 (and first-line
10654 (eolp)
10655 (save-excursion
10656 (skip-chars-forward " \t\r\n")
10657 (not (eq (char-after) ?*))))))
10658 (delete-horizontal-space)
10659 (insert "\n")
10660 (cond
10661 (star
10662 (indent-to col)
10663 (insert "* ")
10664 (if (and first-line needs-close)
10665 (save-excursion
10666 (insert "\n")
10667 (indent-to col)
10668 (insert "*/"))))
10669 ((and single
10670 (save-excursion
10671 (and (zerop (forward-line 1))
10672 (looking-at "\\s-*//"))))
10673 (indent-to col)
10674 (insert "// ")))
10675 ;; Don't need to extend the comment after all.
10676 (js2-indent-line)))
10677
10678 (defun js2-beginning-of-line ()
10679 "Toggle point between bol and first non-whitespace char in line.
10680 Also moves past comment delimiters when inside comments."
10681 (interactive)
10682 (let (node beg)
10683 (cond
10684 ((bolp)
10685 (back-to-indentation))
10686 ((looking-at "//")
10687 (skip-chars-forward "/ \t"))
10688 ((and (eq (char-after) ?*)
10689 (setq node (js2-comment-at-point))
10690 (memq (js2-comment-node-format node) '(jsdoc block))
10691 (save-excursion
10692 (skip-chars-backward " \t")
10693 (bolp)))
10694 (skip-chars-forward "\* \t"))
10695 (t
10696 (goto-char (point-at-bol))))))
10697
10698 (defun js2-end-of-line ()
10699 "Toggle point between eol and last non-whitespace char in line."
10700 (interactive)
10701 (if (eolp)
10702 (skip-chars-backward " \t")
10703 (goto-char (point-at-eol))))
10704
10705 (defun js2-mode-wait-for-parse (callback)
10706 "Invoke CALLBACK when parsing is finished.
10707 If parsing is already finished, calls CALLBACK immediately."
10708 (if (not js2-mode-buffer-dirty-p)
10709 (funcall callback)
10710 (push callback js2-mode-pending-parse-callbacks)
10711 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10712
10713 (defun js2-mode-parse-finished ()
10714 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10715 ;; We can't let errors propagate up, since it prevents the
10716 ;; `js2-parse' method from completing normally and returning
10717 ;; the ast, which makes things mysteriously not work right.
10718 (unwind-protect
10719 (dolist (cb js2-mode-pending-parse-callbacks)
10720 (condition-case err
10721 (funcall cb)
10722 (error (message "%s" err))))
10723 (setq js2-mode-pending-parse-callbacks nil)))
10724
10725 (defun js2-mode-flag-region (from to flag)
10726 "Hide or show text from FROM to TO, according to FLAG.
10727 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10728 Returns the created overlay if FLAG is non-nil."
10729 (remove-overlays from to 'invisible 'js2-outline)
10730 (when flag
10731 (let ((o (make-overlay from to)))
10732 (overlay-put o 'invisible 'js2-outline)
10733 (overlay-put o 'isearch-open-invisible
10734 'js2-isearch-open-invisible)
10735 o)))
10736
10737 ;; Function to be set as an outline-isearch-open-invisible' property
10738 ;; to the overlay that makes the outline invisible (see
10739 ;; `js2-mode-flag-region').
10740 (defun js2-isearch-open-invisible (overlay)
10741 ;; We rely on the fact that isearch places point on the matched text.
10742 (js2-mode-show-element))
10743
10744 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10745 "Return cons cell of bounds of folding overlay at POS.
10746 Returns nil if not found."
10747 (let ((overlays (overlays-at (or pos (point))))
10748 o)
10749 (while (and overlays
10750 (not o))
10751 (if (overlay-get (car overlays) 'invisible)
10752 (setq o (car overlays))
10753 (setq overlays (cdr overlays))))
10754 (if o
10755 (cons (overlay-start o) (overlay-end o)))))
10756
10757 (defun js2-mode-function-at-point (&optional pos)
10758 "Return the innermost function node enclosing current point.
10759 Returns nil if point is not in a function."
10760 (let ((node (js2-node-at-point pos)))
10761 (while (and node (not (js2-function-node-p node)))
10762 (setq node (js2-node-parent node)))
10763 (if (js2-function-node-p node)
10764 node)))
10765
10766 (defun js2-mode-toggle-element ()
10767 "Hide or show the foldable element at the point."
10768 (interactive)
10769 (let (comment fn pos)
10770 (save-excursion
10771 (cond
10772 ;; /* ... */ comment?
10773 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10774 (if (js2-mode-invisible-overlay-bounds
10775 (setq pos (+ 3 (js2-node-abs-pos comment))))
10776 (progn
10777 (goto-char pos)
10778 (js2-mode-show-element))
10779 (js2-mode-hide-element)))
10780 ;; //-comment?
10781 ((save-excursion
10782 (back-to-indentation)
10783 (looking-at js2-mode-//-comment-re))
10784 (js2-mode-toggle-//-comment))
10785 ;; function?
10786 ((setq fn (js2-mode-function-at-point))
10787 (setq pos (and (js2-function-node-body fn)
10788 (js2-node-abs-pos (js2-function-node-body fn))))
10789 (goto-char (1+ pos))
10790 (if (js2-mode-invisible-overlay-bounds)
10791 (js2-mode-show-element)
10792 (js2-mode-hide-element)))
10793 (t
10794 (message "Nothing at point to hide or show"))))))
10795
10796 (defun js2-mode-hide-element ()
10797 "Fold/hide contents of a block, showing ellipses.
10798 Show the hidden text with \\[js2-mode-show-element]."
10799 (interactive)
10800 (if js2-mode-buffer-dirty-p
10801 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10802 (let (node body beg end)
10803 (cond
10804 ((js2-mode-invisible-overlay-bounds)
10805 (message "already hidden"))
10806 (t
10807 (setq node (js2-node-at-point))
10808 (cond
10809 ((js2-block-comment-p node)
10810 (js2-mode-hide-comment node))
10811 (t
10812 (while (and node (not (js2-function-node-p node)))
10813 (setq node (js2-node-parent node)))
10814 (if (and node
10815 (setq body (js2-function-node-body node)))
10816 (progn
10817 (setq beg (js2-node-abs-pos body)
10818 end (+ beg (js2-node-len body)))
10819 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10820 (message "No collapsable element found at point"))))))))
10821
10822 (defun js2-mode-show-element ()
10823 "Show the hidden element at current point."
10824 (interactive)
10825 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10826 (if bounds
10827 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
10828 (message "Nothing to un-hide"))))
10829
10830 (defun js2-mode-show-all ()
10831 "Show all of the text in the buffer."
10832 (interactive)
10833 (js2-mode-flag-region (point-min) (point-max) nil))
10834
10835 (defun js2-mode-toggle-hide-functions ()
10836 (interactive)
10837 (if js2-mode-functions-hidden
10838 (js2-mode-show-functions)
10839 (js2-mode-hide-functions)))
10840
10841 (defun js2-mode-hide-functions ()
10842 "Hides all non-nested function bodies in the buffer.
10843 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10844 to open an individual entry."
10845 (interactive)
10846 (if js2-mode-buffer-dirty-p
10847 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
10848 (if (null js2-mode-ast)
10849 (message "Oops - parsing failed")
10850 (setq js2-mode-functions-hidden t)
10851 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
10852
10853 (defun js2-mode-function-hider (n endp)
10854 (when (not endp)
10855 (let ((tt (js2-node-type n))
10856 body beg end)
10857 (cond
10858 ((and (= tt js2-FUNCTION)
10859 (setq body (js2-function-node-body n)))
10860 (setq beg (js2-node-abs-pos body)
10861 end (+ beg (js2-node-len body)))
10862 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
10863 nil) ; don't process children of function
10864 (t
10865 t))))) ; keep processing other AST nodes
10866
10867 (defun js2-mode-show-functions ()
10868 "Un-hide any folded function bodies in the buffer."
10869 (interactive)
10870 (setq js2-mode-functions-hidden nil)
10871 (save-excursion
10872 (goto-char (point-min))
10873 (while (/= (goto-char (next-overlay-change (point)))
10874 (point-max))
10875 (dolist (o (overlays-at (point)))
10876 (when (and (overlay-get o 'invisible)
10877 (not (overlay-get o 'comment)))
10878 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10879
10880 (defun js2-mode-hide-comment (n)
10881 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
10882 3 ; /**
10883 2)) ; /*
10884 (beg (+ (js2-node-abs-pos n) head))
10885 (end (- (+ beg (js2-node-len n)) head 2))
10886 (o (js2-mode-flag-region beg end 'hide)))
10887 (overlay-put o 'comment t)))
10888
10889 (defun js2-mode-toggle-hide-comments ()
10890 "Folds all block comments in the buffer.
10891 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10892 to open an individual entry."
10893 (interactive)
10894 (if js2-mode-comments-hidden
10895 (js2-mode-show-comments)
10896 (js2-mode-hide-comments)))
10897
10898 (defun js2-mode-hide-comments ()
10899 (interactive)
10900 (if js2-mode-buffer-dirty-p
10901 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
10902 (if (null js2-mode-ast)
10903 (message "Oops - parsing failed")
10904 (setq js2-mode-comments-hidden t)
10905 (dolist (n (js2-ast-root-comments js2-mode-ast))
10906 (let ((format (js2-comment-node-format n)))
10907 (when (js2-block-comment-p n)
10908 (js2-mode-hide-comment n))))
10909 (js2-mode-hide-//-comments)))
10910
10911 (defun js2-mode-extend-//-comment (direction)
10912 "Find start or end of a block of similar //-comment lines.
10913 DIRECTION is -1 to look back, 1 to look forward.
10914 INDENT is the indentation level to match.
10915 Returns the end-of-line position of the furthest adjacent
10916 //-comment line with the same indentation as the current line.
10917 If there is no such matching line, returns current end of line."
10918 (let ((pos (point-at-eol))
10919 (indent (current-indentation)))
10920 (save-excursion
10921 (while (and (zerop (forward-line direction))
10922 (looking-at js2-mode-//-comment-re)
10923 (eq indent (length (match-string 1))))
10924 (setq pos (point-at-eol))
10925 pos))))
10926
10927 (defun js2-mode-hide-//-comments ()
10928 "Fold adjacent 1-line comments, showing only snippet of first one."
10929 (let (beg end)
10930 (save-excursion
10931 (goto-char (point-min))
10932 (while (re-search-forward js2-mode-//-comment-re nil t)
10933 (setq beg (point)
10934 end (js2-mode-extend-//-comment 1))
10935 (unless (eq beg end)
10936 (overlay-put (js2-mode-flag-region beg end 'hide)
10937 'comment t))
10938 (goto-char end)
10939 (forward-char 1)))))
10940
10941 (defun js2-mode-toggle-//-comment ()
10942 "Fold or un-fold any multi-line //-comment at point.
10943 Caller should have determined that this line starts with a //-comment."
10944 (let* ((beg (point-at-eol))
10945 (end beg))
10946 (save-excursion
10947 (goto-char end)
10948 (if (js2-mode-invisible-overlay-bounds)
10949 (js2-mode-show-element)
10950 ;; else hide the comment
10951 (setq beg (js2-mode-extend-//-comment -1)
10952 end (js2-mode-extend-//-comment 1))
10953 (unless (eq beg end)
10954 (overlay-put (js2-mode-flag-region beg end 'hide)
10955 'comment t))))))
10956
10957 (defun js2-mode-show-comments ()
10958 "Un-hide any hidden comments, leaving other hidden elements alone."
10959 (interactive)
10960 (setq js2-mode-comments-hidden nil)
10961 (save-excursion
10962 (goto-char (point-min))
10963 (while (/= (goto-char (next-overlay-change (point)))
10964 (point-max))
10965 (dolist (o (overlays-at (point)))
10966 (when (overlay-get o 'comment)
10967 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10968
10969 (defun js2-mode-display-warnings-and-errors ()
10970 "Turn on display of warnings and errors."
10971 (interactive)
10972 (setq js2-mode-show-parse-errors t
10973 js2-mode-show-strict-warnings t)
10974 (js2-reparse 'force))
10975
10976 (defun js2-mode-hide-warnings-and-errors ()
10977 "Turn off display of warnings and errors."
10978 (interactive)
10979 (setq js2-mode-show-parse-errors nil
10980 js2-mode-show-strict-warnings nil)
10981 (js2-reparse 'force))
10982
10983 (defun js2-mode-toggle-warnings-and-errors ()
10984 "Toggle the display of warnings and errors.
10985 Some users don't like having warnings/errors reported while they type."
10986 (interactive)
10987 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
10988 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
10989 (if (called-interactively-p 'any)
10990 (message "warnings and errors %s"
10991 (if js2-mode-show-parse-errors
10992 "enabled"
10993 "disabled")))
10994 (js2-reparse 'force))
10995
10996 (defun js2-mode-customize ()
10997 (interactive)
10998 (customize-group 'js2-mode))
10999
11000 (defun js2-mode-forward-sexp (&optional arg)
11001 "Move forward across one statement or balanced expression.
11002 With ARG, do it that many times. Negative arg -N means
11003 move backward across N balanced expressions."
11004 (interactive "p")
11005 (setq arg (or arg 1))
11006 (save-restriction
11007 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11008 (js2-reparse))
11009 (let (forward-sexp-function
11010 node (start (point)) pos lp rp child)
11011 (cond
11012 ;; backward-sexp
11013 ;; could probably make this better for some cases:
11014 ;; - if in statement block (e.g. function body), go to parent
11015 ;; - infix exprs like (foo in bar) - maybe go to beginning
11016 ;; of infix expr if in the right-side expression?
11017 ((and arg (minusp arg))
11018 (dotimes (i (- arg))
11019 (js2-backward-sws)
11020 (forward-char -1) ; Enter the node we backed up to.
11021 (when (setq node (js2-node-at-point (point) t))
11022 (setq pos (js2-node-abs-pos node))
11023 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11024 (setq lp (car parens)
11025 rp (cdr parens)))
11026 (when (and lp (> start lp))
11027 (if (and rp (<= start rp))
11028 ;; Between parens, check if there's a child node we can jump.
11029 (when (setq child (js2-node-closest-child node (point) lp t))
11030 (setq pos (js2-node-abs-pos child)))
11031 ;; Before both parens.
11032 (setq pos lp)))
11033 (let ((state (parse-partial-sexp start pos)))
11034 (goto-char (if (not (zerop (car state)))
11035 ;; Stumble at the unbalanced paren if < 0, or
11036 ;; jump a bit further if > 0.
11037 (scan-sexps start -1)
11038 pos))))
11039 (unless pos (goto-char (point-min)))))
11040 (t
11041 ;; forward-sexp
11042 (dotimes (i arg)
11043 (js2-forward-sws)
11044 (when (setq node (js2-node-at-point (point) t))
11045 (setq pos (js2-node-abs-pos node))
11046 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11047 (setq lp (car parens)
11048 rp (cdr parens)))
11049 (or
11050 (when (and rp (<= start rp))
11051 (if (> start lp)
11052 (when (setq child (js2-node-closest-child node (point) rp))
11053 (setq pos (js2-node-abs-end child)))
11054 (setq pos (1+ rp))))
11055 ;; No parens or child nodes, looks for the end of the curren node.
11056 (incf pos (js2-node-len
11057 (if (js2-expr-stmt-node-p (js2-node-parent node))
11058 ;; Stop after the semicolon.
11059 (js2-node-parent node)
11060 node))))
11061 (let ((state (save-excursion (parse-partial-sexp start pos))))
11062 (goto-char (if (not (zerop (car state)))
11063 (scan-sexps start 1)
11064 pos))))
11065 (unless pos (goto-char (point-max))))))))
11066
11067 (defun js2-mode-forward-sexp-parens (node abs-pos)
11068 "Return a cons cell with positions of main parens in NODE."
11069 (cond
11070 ((or (js2-array-node-p node)
11071 (js2-object-node-p node)
11072 (js2-array-comp-node-p node)
11073 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11074 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11075 ((js2-paren-expr-node-p node)
11076 (let ((lp (js2-node-lp node))
11077 (rp (js2-node-rp node)))
11078 (cons (when lp (+ abs-pos lp))
11079 (when rp (+ abs-pos rp)))))))
11080
11081 (defun js2-node-closest-child (parent point limit &optional before)
11082 (let* ((parent-pos (js2-node-abs-pos parent))
11083 (rpoint (- point parent-pos))
11084 (rlimit (- limit parent-pos))
11085 (min (min rpoint rlimit))
11086 (max (max rpoint rlimit))
11087 found)
11088 (catch 'done
11089 (js2-visit-ast
11090 parent
11091 (lambda (node end-p)
11092 (if (eq node parent)
11093 t
11094 (let ((pos (js2-node-pos node)) ;; Both relative values.
11095 (end (+ (js2-node-pos node) (js2-node-len node))))
11096 (when (and (>= pos min) (<= end max)
11097 (if before (< pos rpoint) (> end rpoint)))
11098 (setq found node))
11099 (when (> end rpoint)
11100 (throw 'done nil)))
11101 nil))))
11102 found))
11103
11104 (defun js2-errors ()
11105 "Return a list of errors found."
11106 (and js2-mode-ast
11107 (js2-ast-root-errors js2-mode-ast)))
11108
11109 (defun js2-warnings ()
11110 "Return a list of warnings found."
11111 (and js2-mode-ast
11112 (js2-ast-root-warnings js2-mode-ast)))
11113
11114 (defun js2-have-errors-p ()
11115 "Return non-nil if any parse errors or warnings were found."
11116 (or (js2-errors) (js2-warnings)))
11117
11118 (defun js2-errors-and-warnings ()
11119 "Return a copy of the concatenated errors and warnings lists.
11120 They are appended: first the errors, then the warnings.
11121 Entries are of the form (MSG BEG END)."
11122 (when js2-mode-ast
11123 (append (js2-ast-root-errors js2-mode-ast)
11124 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11125
11126 (defun js2-next-error (&optional arg reset)
11127 "Move to next parse error.
11128 Typically invoked via \\[next-error].
11129 ARG is the number of errors, forward or backward, to move.
11130 RESET means start over from the beginning."
11131 (interactive "p")
11132 (if (not (or (js2-errors) (js2-warnings)))
11133 (message "No errors")
11134 (when reset
11135 (goto-char (point-min)))
11136 (let* ((errs (js2-errors-and-warnings))
11137 (continue t)
11138 (start (point))
11139 (count (or arg 1))
11140 (backward (minusp count))
11141 (sorter (if backward '> '<))
11142 (stopper (if backward '< '>))
11143 (count (abs count))
11144 all-errs err)
11145 ;; Sort by start position.
11146 (setq errs (sort errs (lambda (e1 e2)
11147 (funcall sorter (second e1) (second e2))))
11148 all-errs errs)
11149 ;; Find nth error with pos > start.
11150 (while (and errs continue)
11151 (when (funcall stopper (cadar errs) start)
11152 (setq err (car errs))
11153 (if (zerop (decf count))
11154 (setq continue nil)))
11155 (setq errs (cdr errs)))
11156 ;; Clear for `js2-echo-error'.
11157 (message nil)
11158 (if err
11159 (goto-char (second err))
11160 ;; Wrap around to first error.
11161 (goto-char (second (car all-errs)))
11162 ;; If we were already on it, echo msg again.
11163 (if (= (point) start)
11164 (js2-echo-error (point) (point)))))))
11165
11166 (defun js2-down-mouse-3 ()
11167 "Make right-click move the point to the click location.
11168 This makes right-click context menu operations a bit more intuitive.
11169 The point will not move if the region is active, however, to avoid
11170 destroying the region selection."
11171 (interactive)
11172 (when (and js2-move-point-on-right-click
11173 (not mark-active))
11174 (let ((e last-input-event))
11175 (ignore-errors
11176 (goto-char (cadadr e))))))
11177
11178 (defun js2-mode-create-imenu-index ()
11179 "Return an alist for `imenu--index-alist'."
11180 ;; This is built up in `js2-parse-record-imenu' during parsing.
11181 (when js2-mode-ast
11182 ;; if we have an ast but no recorder, they're requesting a rescan
11183 (unless js2-imenu-recorder
11184 (js2-reparse 'force))
11185 (prog1
11186 (js2-build-imenu-index)
11187 (setq js2-imenu-recorder nil
11188 js2-imenu-function-map nil))))
11189
11190 (defun js2-mode-find-tag ()
11191 "Replacement for `find-tag-default'.
11192 `find-tag-default' returns a ridiculous answer inside comments."
11193 (let (beg end)
11194 (js2-with-underscore-as-word-syntax
11195 (save-excursion
11196 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11197 (looking-back "[A-Za-z0-9_$]"))
11198 (setq beg (progn (forward-word -1) (point))
11199 end (progn (forward-word 1) (point)))
11200 (setq beg (progn (forward-word 1) (point))
11201 end (progn (forward-word -1) (point))))
11202 (replace-regexp-in-string
11203 "[\"']" ""
11204 (buffer-substring-no-properties beg end))))))
11205
11206 (defun js2-mode-forward-sibling ()
11207 "Move to the end of the sibling following point in parent.
11208 Returns non-nil if successful, or nil if there was no following sibling."
11209 (let* ((node (js2-node-at-point))
11210 (parent (js2-mode-find-enclosing-fn node))
11211 sib)
11212 (when (setq sib (js2-node-find-child-after (point) parent))
11213 (goto-char (+ (js2-node-abs-pos sib)
11214 (js2-node-len sib))))))
11215
11216 (defun js2-mode-backward-sibling ()
11217 "Move to the beginning of the sibling node preceding point in parent.
11218 Parent is defined as the enclosing script or function."
11219 (let* ((node (js2-node-at-point))
11220 (parent (js2-mode-find-enclosing-fn node))
11221 sib)
11222 (when (setq sib (js2-node-find-child-before (point) parent))
11223 (goto-char (js2-node-abs-pos sib)))))
11224
11225 (defun js2-beginning-of-defun (&optional arg)
11226 "Go to line on which current function starts, and return t on success.
11227 If we're not in a function or already at the beginning of one, go
11228 to beginning of previous script-level element.
11229 With ARG N, do that N times. If N is negative, move forward."
11230 (setq arg (or arg 1))
11231 (if (plusp arg)
11232 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11233 (when (cond
11234 ((js2-function-node-p parent)
11235 (goto-char (js2-node-abs-pos parent)))
11236 (t
11237 (js2-mode-backward-sibling)))
11238 (if (> arg 1)
11239 (js2-beginning-of-defun (1- arg))
11240 t)))
11241 (when (js2-end-of-defun)
11242 (if (>= arg -1)
11243 (js2-beginning-of-defun 1)
11244 (js2-beginning-of-defun (1+ arg))))))
11245
11246 (defun js2-end-of-defun ()
11247 "Go to the char after the last position of the current function
11248 or script-level element."
11249 (let* ((node (js2-node-at-point))
11250 (parent (or (and (js2-function-node-p node) node)
11251 (js2-node-parent-script-or-fn node)))
11252 script)
11253 (unless (js2-function-node-p parent)
11254 ;; Use current script-level node, or, if none, the next one.
11255 (setq script (or parent node)
11256 parent (js2-node-find-child-before (point) script))
11257 (when (or (null parent)
11258 (>= (point) (+ (js2-node-abs-pos parent)
11259 (js2-node-len parent))))
11260 (setq parent (js2-node-find-child-after (point) script))))
11261 (when parent
11262 (goto-char (+ (js2-node-abs-pos parent)
11263 (js2-node-len parent))))))
11264
11265 (defun js2-mark-defun (&optional allow-extend)
11266 "Put mark at end of this function, point at beginning.
11267 The function marked is the one that contains point.
11268
11269 Interactively, if this command is repeated,
11270 or (in Transient Mark mode) if the mark is active,
11271 it marks the next defun after the ones already marked."
11272 (interactive "p")
11273 (let (extended)
11274 (when (and allow-extend
11275 (or (and (eq last-command this-command) (mark t))
11276 (and transient-mark-mode mark-active)))
11277 (let ((sib (save-excursion
11278 (goto-char (mark))
11279 (if (js2-mode-forward-sibling)
11280 (point))))
11281 node)
11282 (if sib
11283 (progn
11284 (set-mark sib)
11285 (setq extended t))
11286 ;; no more siblings - try extending to enclosing node
11287 (goto-char (mark t)))))
11288 (when (not extended)
11289 (let ((node (js2-node-at-point (point) t)) ; skip comments
11290 ast fn stmt parent beg end)
11291 (when (js2-ast-root-p node)
11292 (setq ast node
11293 node (or (js2-node-find-child-after (point) node)
11294 (js2-node-find-child-before (point) node))))
11295 ;; only mark whole buffer if we can't find any children
11296 (if (null node)
11297 (setq node ast))
11298 (if (js2-function-node-p node)
11299 (setq parent node)
11300 (setq fn (js2-mode-find-enclosing-fn node)
11301 stmt (if (or (null fn)
11302 (js2-ast-root-p fn))
11303 (js2-mode-find-first-stmt node))
11304 parent (or stmt fn)))
11305 (setq beg (js2-node-abs-pos parent)
11306 end (+ beg (js2-node-len parent)))
11307 (push-mark beg)
11308 (goto-char end)
11309 (exchange-point-and-mark)))))
11310
11311 (defun js2-narrow-to-defun ()
11312 "Narrow to the function enclosing point."
11313 (interactive)
11314 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11315 (fn (if (js2-script-node-p node)
11316 node
11317 (js2-mode-find-enclosing-fn node)))
11318 (beg (js2-node-abs-pos fn)))
11319 (unless (js2-ast-root-p fn)
11320 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11321
11322 (provide 'js2-mode)
11323
11324 ;;; js2-mode.el ends here