]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
cfbbdc22b8e93fb8c74dceeb800bbfc1a7563f7b
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2012 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; Contributors: mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; Version: See `js2-mode-version'
9 ;; Keywords: languages, javascript
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27
28 ;; This JavaScript editing mode supports:
29
30 ;; - strict recognition of the Ecma-262 language standard
31 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 to 1.8
32 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
33 ;; - accurate syntax highlighting using a recursive-descent parser
34 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
35 ;; - undeclared-variable warnings using a configurable externs framework
36 ;; - "bouncing" line indentation to choose among alternate indentation points
37 ;; - smart line-wrapping within comments and strings
38 ;; - code folding:
39 ;; - show some or all function bodies as {...}
40 ;; - show some or all block comments as /*...*/
41 ;; - context-sensitive menu bar and popup menus
42 ;; - code browsing using the `imenu' package
43 ;; - typing helpers such as automatic insertion of matching braces/parens
44 ;; - many customization options
45
46 ;; Installation:
47 ;;
48 ;; To install it as your major mode for JavaScript editing:
49
50 ;; (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
51
52 ;; Alternately, to install it as a minor mode just for JavaScript linting,
53 ;; you must add it to the appropriate major-mode hook. Normally this would be:
54
55 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
56
57 ;; To customize how it works:
58 ;; M-x customize-group RET js2-mode RET
59
60 ;; Notes:
61
62 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
63 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
64 ;; `js2-mode' current as the EcmaScript language standard evolves.
65
66 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
67 ;; customizable. It is a surprising amount of work to support customizable
68 ;; indentation. The current compromise is that the tab key lets you cycle among
69 ;; various likely indentation points, similar to the behavior of python-mode.
70
71 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
72 ;; and `mumamo', although it could be made to do so with some effort.
73 ;; This means that `js2-mode' is currently only useful for editing JavaScript
74 ;; files, and not for editing JavaScript within <script> tags or templates.
75
76 ;;; Code:
77
78 (eval-when-compile
79 (require 'cl))
80
81 (require 'imenu)
82 (require 'cc-cmds) ; for `c-fill-paragraph'
83
84 (eval-and-compile
85 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
86 (require 'cc-langs) ; it's here in Emacs 21...
87 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
88
89 (defvar electric-layout-rules)
90
91 ;;; Externs (variables presumed to be defined by the host system)
92
93 (defvar js2-ecma-262-externs
94 (mapcar 'symbol-name
95 '(Array Boolean Date Error EvalError Function Infinity JSON
96 Math NaN Number Object RangeError ReferenceError RegExp
97 String SyntaxError TypeError URIError arguments
98 decodeURI decodeURIComponent encodeURI
99 encodeURIComponent escape eval isFinite isNaN
100 parseFloat parseInt undefined unescape))
101 "Ecma-262 externs. Included in `js2-externs' by default.")
102
103 (defvar js2-browser-externs
104 (mapcar 'symbol-name
105 '(;; DOM level 1
106 Attr CDATASection CharacterData Comment DOMException
107 DOMImplementation Document DocumentFragment
108 DocumentType Element Entity EntityReference
109 ExceptionCode NamedNodeMap Node NodeList Notation
110 ProcessingInstruction Text
111
112 ;; DOM level 2
113 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
114 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
115 HTMLBodyElement HTMLButtonElement HTMLCollection
116 HTMLDListElement HTMLDirectoryElement HTMLDivElement
117 HTMLDocument HTMLElement HTMLFieldSetElement
118 HTMLFontElement HTMLFormElement HTMLFrameElement
119 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
120 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
121 HTMLImageElement HTMLInputElement HTMLIsIndexElement
122 HTMLLIElement HTMLLabelElement HTMLLegendElement
123 HTMLLinkElement HTMLMapElement HTMLMenuElement
124 HTMLMetaElement HTMLModElement HTMLOListElement
125 HTMLObjectElement HTMLOptGroupElement
126 HTMLOptionElement HTMLOptionsCollection
127 HTMLParagraphElement HTMLParamElement HTMLPreElement
128 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
129 HTMLStyleElement HTMLTableCaptionElement
130 HTMLTableCellElement HTMLTableColElement
131 HTMLTableElement HTMLTableRowElement
132 HTMLTableSectionElement HTMLTextAreaElement
133 HTMLTitleElement HTMLUListElement
134
135 ;; DOM level 3
136 DOMConfiguration DOMError DOMException
137 DOMImplementationList DOMImplementationSource
138 DOMLocator DOMStringList NameList TypeInfo
139 UserDataHandler
140
141 ;; Window
142 window alert confirm document java navigator prompt screen
143 self top
144
145 ;; W3C CSS
146 CSSCharsetRule CSSFontFace CSSFontFaceRule
147 CSSImportRule CSSMediaRule CSSPageRule
148 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
149 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
150 CSSValue CSSValueList Counter DOMImplementationCSS
151 DocumentCSS DocumentStyle ElementCSSInlineStyle
152 LinkStyle MediaList RGBColor Rect StyleSheet
153 StyleSheetList ViewCSS
154
155 ;; W3C Event
156 EventListener EventTarget Event DocumentEvent UIEvent
157 MouseEvent MutationEvent KeyboardEvent
158
159 ;; W3C Range
160 DocumentRange Range RangeException
161
162 ;; W3C XML
163 XPathResult XMLHttpRequest))
164 "Browser externs.
165 You can cause these to be included or excluded with the custom
166 variable `js2-include-browser-externs'.")
167
168 (defvar js2-rhino-externs
169 (mapcar 'symbol-name
170 '(Packages importClass importPackage com org java
171 ;; Global object (shell) externs.
172 defineClass deserialize doctest gc help load
173 loadClass print quit readFile readUrl runCommand seal
174 serialize spawn sync toint32 version))
175 "Mozilla Rhino externs.
176 Set `js2-include-rhino-externs' to t to include them.")
177
178 (defvar js2-gears-externs
179 (mapcar 'symbol-name
180 '(
181 ;; TODO(stevey): add these
182 ))
183 "Google Gears externs.
184 Set `js2-include-gears-externs' to t to include them.")
185
186 ;;; Variables
187
188 (defun js2-mark-safe-local (name pred)
189 "Make the variable NAME buffer-local and mark it as safe file-local
190 variable with predicate PRED."
191 (make-variable-buffer-local name)
192 (put name 'safe-local-variable pred))
193
194 (defcustom js2-highlight-level 2
195 "Amount of syntax highlighting to perform.
196 0 or a negative value means none.
197 1 adds basic syntax highlighting.
198 2 adds highlighting of some Ecma built-in properties.
199 3 adds highlighting of many Ecma built-in functions."
200 :group 'js2-mode
201 :type '(choice (const :tag "None" 0)
202 (const :tag "Basic" 1)
203 (const :tag "Include Properties" 2)
204 (const :tag "Include Functions" 3)))
205
206 (defvar js2-mode-dev-mode-p nil
207 "Non-nil if running in development mode. Normally nil.")
208
209 (defgroup js2-mode nil
210 "An improved JavaScript mode."
211 :group 'languages)
212
213 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
214 (numberp c-basic-offset))
215 c-basic-offset
216 4)
217 "Number of spaces to indent nested statements.
218 Similar to `c-basic-offset'."
219 :group 'js2-mode
220 :type 'integer)
221 (js2-mark-safe-local 'js2-basic-offset 'integerp)
222
223
224 (defcustom js2-bounce-indent-p nil
225 "Non-nil to have indent-line function choose among alternatives.
226 If nil, the indent-line function will indent to a predetermined column
227 based on heuristic guessing. If non-nil, then if the current line is
228 already indented to that predetermined column, indenting will choose
229 another likely column and indent to that spot. Repeated invocation of
230 the indent-line function will cycle among the computed alternatives.
231 See the function `js2-bounce-indent' for details. When it is non-nil,
232 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
233 :type 'boolean
234 :group 'js2-mode)
235
236 (defcustom js2-pretty-multiline-declarations t
237 "Non-nil to line up multiline declarations vertically:
238
239 var a = 10,
240 b = 20,
241 c = 30;
242
243 If the value is not `all', and the first assigned value in
244 declaration is a function/array/object literal spanning several
245 lines, it won't be indented additionally:
246
247 var o = { var bar = 2,
248 foo: 3 vs. o = {
249 }, foo: 3
250 bar = 2; };"
251 :group 'js2-mode
252 :type 'symbol)
253 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
254
255 (defcustom js2-indent-on-enter-key nil
256 "Non-nil to have Enter/Return key indent the line.
257 This is unusual for Emacs modes but common in IDEs like Eclipse."
258 :type 'boolean
259 :group 'js2-mode)
260
261 (defcustom js2-enter-indents-newline nil
262 "Non-nil to have Enter/Return key indent the newly-inserted line.
263 This is unusual for Emacs modes but common in IDEs like Eclipse."
264 :type 'boolean
265 :group 'js2-mode)
266
267 (defcustom js2-idle-timer-delay 0.2
268 "Delay in secs before re-parsing after user makes changes.
269 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
270 :type 'number
271 :group 'js2-mode)
272 (make-variable-buffer-local 'js2-idle-timer-delay)
273
274 (defcustom js2-dynamic-idle-timer-adjust 0
275 "Positive to adjust `js2-idle-timer-delay' based on file size.
276 The idea is that for short files, parsing is faster so we can be
277 more responsive to user edits without interfering with editing.
278 The buffer length in characters (typically bytes) is divided by
279 this value and used to multiply `js2-idle-timer-delay' for the
280 buffer. For example, a 21k file and 10k adjust yields 21k/10k
281 == 2, so js2-idle-timer-delay is multiplied by 2.
282 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
283 `js2-idle-timer-delay' is not dependent on the file size."
284 :type 'number
285 :group 'js2-mode)
286
287 (defcustom js2-mode-escape-quotes t
288 "Non-nil to disable automatic quote-escaping inside strings."
289 :type 'boolean
290 :group 'js2-mode)
291
292 (defcustom js2-concat-multiline-strings t
293 "Non-nil to automatically turn a newline in mid-string into a
294 string concatenation. When `eol', the '+' will be inserted at the
295 end of the line, otherwise, at the beginning of the next line."
296 :type '(choice (const t) (const eol) (const nil))
297 :group 'js2-mode)
298
299 (defcustom js2-mode-squeeze-spaces t
300 "Non-nil to normalize whitespace when filling in comments.
301 Multiple runs of spaces are converted to a single space."
302 :type 'boolean
303 :group 'js2-mode)
304
305 (defcustom js2-mode-show-parse-errors t
306 "True to highlight parse errors."
307 :type 'boolean
308 :group 'js2-mode)
309
310 (defcustom js2-mode-show-strict-warnings t
311 "Non-nil to emit Ecma strict-mode warnings.
312 Some of the warnings can be individually disabled by other flags,
313 even if this flag is non-nil."
314 :type 'boolean
315 :group 'js2-mode)
316
317 (defcustom js2-strict-trailing-comma-warning t
318 "Non-nil to warn about trailing commas in array literals.
319 Ecma-262 forbids them, but many browsers permit them. IE is the
320 big exception, and can produce bugs if you have trailing commas."
321 :type 'boolean
322 :group 'js2-mode)
323
324 (defcustom js2-strict-missing-semi-warning t
325 "Non-nil to warn about semicolon auto-insertion after statement.
326 Technically this is legal per Ecma-262, but some style guides disallow
327 depending on it."
328 :type 'boolean
329 :group 'js2-mode)
330
331 (defcustom js2-missing-semi-one-line-override nil
332 "Non-nil to permit missing semicolons in one-line functions.
333 In one-liner functions such as `function identity(x) {return x}'
334 people often omit the semicolon for a cleaner look. If you are
335 such a person, you can suppress the missing-semicolon warning
336 by setting this variable to t."
337 :type 'boolean
338 :group 'js2-mode)
339
340 (defcustom js2-strict-inconsistent-return-warning t
341 "Non-nil to warn about mixing returns with value-returns.
342 It's perfectly legal to have a `return' and a `return foo' in the
343 same function, but it's often an indicator of a bug, and it also
344 interferes with type inference (in systems that support it.)"
345 :type 'boolean
346 :group 'js2-mode)
347
348 (defcustom js2-strict-cond-assign-warning t
349 "Non-nil to warn about expressions like if (a = b).
350 This often should have been '==' instead of '='. If the warning
351 is enabled, you can suppress it on a per-expression basis by
352 parenthesizing the expression, e.g. if ((a = b)) ..."
353 :type 'boolean
354 :group 'js2-mode)
355
356 (defcustom js2-strict-var-redeclaration-warning t
357 "Non-nil to warn about redeclaring variables in a script or function."
358 :type 'boolean
359 :group 'js2-mode)
360
361 (defcustom js2-strict-var-hides-function-arg-warning t
362 "Non-nil to warn about a var decl hiding a function argument."
363 :type 'boolean
364 :group 'js2-mode)
365
366 (defcustom js2-skip-preprocessor-directives nil
367 "Non-nil to treat lines beginning with # as comments.
368 Useful for viewing Mozilla JavaScript source code."
369 :type 'boolean
370 :group 'js2-mode)
371
372 (defcustom js2-language-version 200
373 "Configures what JavaScript language version to recognize.
374 Currently versions 150, 160, 170, 180 and 200 are supported,
375 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
376 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
377 yield, and Array comprehensions, and 1.8 adds function closures."
378 :type 'integer
379 :group 'js2-mode)
380
381 (defcustom js2-allow-keywords-as-property-names t
382 "If non-nil, you can use JavaScript keywords as object property names.
383 Examples:
384
385 var foo = {int: 5, while: 6, continue: 7};
386 foo.return = 8;
387
388 Ecma-262 forbids this syntax, but many browsers support it."
389 :type 'boolean
390 :group 'js2-mode)
391
392 (defcustom js2-instanceof-has-side-effects nil
393 "If non-nil, treats the instanceof operator as having side effects.
394 This is useful for xulrunner apps."
395 :type 'boolean
396 :group 'js2-mode)
397
398 (defcustom js2-move-point-on-right-click t
399 "Non-nil to move insertion point when you right-click.
400 This makes right-click context menu behavior a bit more intuitive,
401 since menu operations generally apply to the point. The exception
402 is if there is a region selection, in which case the point does -not-
403 move, so cut/copy/paste can work properly.
404
405 Note that IntelliJ moves the point, and Eclipse leaves it alone,
406 so this behavior is customizable."
407 :group 'js2-mode
408 :type 'boolean)
409
410 (defcustom js2-allow-rhino-new-expr-initializer t
411 "Non-nil to support a Rhino's experimental syntactic construct.
412
413 Rhino supports the ability to follow a `new' expression with an object
414 literal, which is used to set additional properties on the new object
415 after calling its constructor. Syntax:
416
417 new <expr> [ ( arglist ) ] [initializer]
418
419 Hence, this expression:
420
421 new Object {a: 1, b: 2}
422
423 results in an Object with properties a=1 and b=2. This syntax is
424 apparently not configurable in Rhino - it's currently always enabled,
425 as of Rhino version 1.7R2."
426 :type 'boolean
427 :group 'js2-mode)
428
429 (defcustom js2-allow-member-expr-as-function-name nil
430 "Non-nil to support experimental Rhino syntax for function names.
431
432 Rhino supports an experimental syntax configured via the Rhino Context
433 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
434
435 function <member-expr> ( [ arg-list ] ) { <body> }
436
437 Where member-expr is a non-parenthesized 'member expression', which
438 is anything at the grammar level of a new-expression or lower, meaning
439 any expression that does not involve infix or unary operators.
440
441 When <member-expr> is not a simple identifier, then it is syntactic
442 sugar for assigning the anonymous function to the <member-expr>. Hence,
443 this code:
444
445 function a.b().c[2] (x, y) { ... }
446
447 is rewritten as:
448
449 a.b().c[2] = function(x, y) {...}
450
451 which doesn't seem particularly useful, but Rhino permits it."
452 :type 'boolean
453 :group 'js2-mode)
454
455 (defvar js2-mode-version 20120416
456 "Release number for `js2-mode'.")
457
458 ;; scanner variables
459
460 (defmacro js2-deflocal (name value &optional comment)
461 "Define a buffer-local variable NAME with VALUE and COMMENT."
462 `(progn
463 (defvar ,name ,value ,comment)
464 (make-variable-buffer-local ',name)))
465
466 ;; We record the start and end position of each token.
467 (js2-deflocal js2-token-beg 1)
468 (js2-deflocal js2-token-end -1)
469
470 (defvar js2-EOF_CHAR -1
471 "Represents end of stream. Distinct from js2-EOF token type.")
472
473 ;; I originally used symbols to represent tokens, but Rhino uses
474 ;; ints and then sets various flag bits in them, so ints it is.
475 ;; The upshot is that we need a `js2-' prefix in front of each name.
476 (defvar js2-ERROR -1)
477 (defvar js2-EOF 0)
478 (defvar js2-EOL 1)
479 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
480 (defvar js2-LEAVEWITH 3)
481 (defvar js2-RETURN 4)
482 (defvar js2-GOTO 5)
483 (defvar js2-IFEQ 6)
484 (defvar js2-IFNE 7)
485 (defvar js2-SETNAME 8)
486 (defvar js2-BITOR 9)
487 (defvar js2-BITXOR 10)
488 (defvar js2-BITAND 11)
489 (defvar js2-EQ 12)
490 (defvar js2-NE 13)
491 (defvar js2-LT 14)
492 (defvar js2-LE 15)
493 (defvar js2-GT 16)
494 (defvar js2-GE 17)
495 (defvar js2-LSH 18)
496 (defvar js2-RSH 19)
497 (defvar js2-URSH 20)
498 (defvar js2-ADD 21) ; infix plus
499 (defvar js2-SUB 22) ; infix minus
500 (defvar js2-MUL 23)
501 (defvar js2-DIV 24)
502 (defvar js2-MOD 25)
503 (defvar js2-NOT 26)
504 (defvar js2-BITNOT 27)
505 (defvar js2-POS 28) ; unary plus
506 (defvar js2-NEG 29) ; unary minus
507 (defvar js2-NEW 30)
508 (defvar js2-DELPROP 31)
509 (defvar js2-TYPEOF 32)
510 (defvar js2-GETPROP 33)
511 (defvar js2-GETPROPNOWARN 34)
512 (defvar js2-SETPROP 35)
513 (defvar js2-GETELEM 36)
514 (defvar js2-SETELEM 37)
515 (defvar js2-CALL 38)
516 (defvar js2-NAME 39) ; an identifier
517 (defvar js2-NUMBER 40)
518 (defvar js2-STRING 41)
519 (defvar js2-NULL 42)
520 (defvar js2-THIS 43)
521 (defvar js2-FALSE 44)
522 (defvar js2-TRUE 45)
523 (defvar js2-SHEQ 46) ; shallow equality (===)
524 (defvar js2-SHNE 47) ; shallow inequality (!==)
525 (defvar js2-REGEXP 48)
526 (defvar js2-BINDNAME 49)
527 (defvar js2-THROW 50)
528 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
529 (defvar js2-IN 52)
530 (defvar js2-INSTANCEOF 53)
531 (defvar js2-LOCAL_LOAD 54)
532 (defvar js2-GETVAR 55)
533 (defvar js2-SETVAR 56)
534 (defvar js2-CATCH_SCOPE 57)
535 (defvar js2-ENUM_INIT_KEYS 58)
536 (defvar js2-ENUM_INIT_VALUES 59)
537 (defvar js2-ENUM_INIT_ARRAY 60)
538 (defvar js2-ENUM_NEXT 61)
539 (defvar js2-ENUM_ID 62)
540 (defvar js2-THISFN 63)
541 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
542 (defvar js2-ARRAYLIT 65) ; array literal
543 (defvar js2-OBJECTLIT 66) ; object literal
544 (defvar js2-GET_REF 67) ; *reference
545 (defvar js2-SET_REF 68) ; *reference = something
546 (defvar js2-DEL_REF 69) ; delete reference
547 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
548 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
549 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
550
551 ;; XML support
552 (defvar js2-DEFAULTNAMESPACE 73)
553 (defvar js2-ESCXMLATTR 74)
554 (defvar js2-ESCXMLTEXT 75)
555 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
556 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
557 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
558 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
559
560 (defvar js2-first-bytecode js2-ENTERWITH)
561 (defvar js2-last-bytecode js2-REF_NS_NAME)
562
563 (defvar js2-TRY 80)
564 (defvar js2-SEMI 81) ; semicolon
565 (defvar js2-LB 82) ; left and right brackets
566 (defvar js2-RB 83)
567 (defvar js2-LC 84) ; left and right curly-braces
568 (defvar js2-RC 85)
569 (defvar js2-LP 86) ; left and right parens
570 (defvar js2-RP 87)
571 (defvar js2-COMMA 88) ; comma operator
572
573 (defvar js2-ASSIGN 89) ; simple assignment (=)
574 (defvar js2-ASSIGN_BITOR 90) ; |=
575 (defvar js2-ASSIGN_BITXOR 91) ; ^=
576 (defvar js2-ASSIGN_BITAND 92) ; &=
577 (defvar js2-ASSIGN_LSH 93) ; <<=
578 (defvar js2-ASSIGN_RSH 94) ; >>=
579 (defvar js2-ASSIGN_URSH 95) ; >>>=
580 (defvar js2-ASSIGN_ADD 96) ; +=
581 (defvar js2-ASSIGN_SUB 97) ; -=
582 (defvar js2-ASSIGN_MUL 98) ; *=
583 (defvar js2-ASSIGN_DIV 99) ; /=
584 (defvar js2-ASSIGN_MOD 100) ; %=
585
586 (defvar js2-first-assign js2-ASSIGN)
587 (defvar js2-last-assign js2-ASSIGN_MOD)
588
589 (defvar js2-HOOK 101) ; conditional (?:)
590 (defvar js2-COLON 102)
591 (defvar js2-OR 103) ; logical or (||)
592 (defvar js2-AND 104) ; logical and (&&)
593 (defvar js2-INC 105) ; increment/decrement (++ --)
594 (defvar js2-DEC 106)
595 (defvar js2-DOT 107) ; member operator (.)
596 (defvar js2-FUNCTION 108) ; function keyword
597 (defvar js2-EXPORT 109) ; export keyword
598 (defvar js2-IMPORT 110) ; import keyword
599 (defvar js2-IF 111) ; if keyword
600 (defvar js2-ELSE 112) ; else keyword
601 (defvar js2-SWITCH 113) ; switch keyword
602 (defvar js2-CASE 114) ; case keyword
603 (defvar js2-DEFAULT 115) ; default keyword
604 (defvar js2-WHILE 116) ; while keyword
605 (defvar js2-DO 117) ; do keyword
606 (defvar js2-FOR 118) ; for keyword
607 (defvar js2-BREAK 119) ; break keyword
608 (defvar js2-CONTINUE 120) ; continue keyword
609 (defvar js2-VAR 121) ; var keyword
610 (defvar js2-WITH 122) ; with keyword
611 (defvar js2-CATCH 123) ; catch keyword
612 (defvar js2-FINALLY 124) ; finally keyword
613 (defvar js2-VOID 125) ; void keyword
614 (defvar js2-RESERVED 126) ; reserved keywords
615
616 (defvar js2-EMPTY 127)
617
618 ;; Types used for the parse tree - never returned by scanner.
619
620 (defvar js2-BLOCK 128) ; statement block
621 (defvar js2-LABEL 129) ; label
622 (defvar js2-TARGET 130)
623 (defvar js2-LOOP 131)
624 (defvar js2-EXPR_VOID 132) ; expression statement in functions
625 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
626 (defvar js2-JSR 134)
627 (defvar js2-SCRIPT 135) ; top-level node for entire script
628 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
629 (defvar js2-USE_STACK 137)
630 (defvar js2-SETPROP_OP 138) ; x.y op= something
631 (defvar js2-SETELEM_OP 139) ; x[y] op= something
632 (defvar js2-LOCAL_BLOCK 140)
633 (defvar js2-SET_REF_OP 141) ; *reference op= something
634
635 ;; For XML support:
636 (defvar js2-DOTDOT 142) ; member operator (..)
637 (defvar js2-COLONCOLON 143) ; namespace::name
638 (defvar js2-XML 144) ; XML type
639 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
640 (defvar js2-XMLATTR 146) ; @
641 (defvar js2-XMLEND 147)
642
643 ;; Optimizer-only tokens
644 (defvar js2-TO_OBJECT 148)
645 (defvar js2-TO_DOUBLE 149)
646
647 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
648 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
649 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
650 (defvar js2-CONST 153)
651 (defvar js2-SETCONST 154)
652 (defvar js2-SETCONSTVAR 155)
653 (defvar js2-ARRAYCOMP 156)
654 (defvar js2-LETEXPR 157)
655 (defvar js2-WITHEXPR 158)
656 (defvar js2-DEBUGGER 159)
657
658 (defvar js2-COMMENT 160)
659 (defvar js2-ENUM 161) ; for "enum" reserved word
660 (defvar js2-TRIPLEDOT 162) ; for rest parameter
661
662 (defconst js2-num-tokens (1+ js2-TRIPLEDOT))
663
664 (defconst js2-debug-print-trees nil)
665
666 ;; Rhino accepts any string or stream as input. Emacs character
667 ;; processing works best in buffers, so we'll assume the input is a
668 ;; buffer. JavaScript strings can be copied into temp buffers before
669 ;; scanning them.
670
671 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
672 ;; They're the Emacs equivalent of instance variables, more or less.
673
674 (js2-deflocal js2-ts-dirty-line nil
675 "Token stream buffer-local variable.
676 Indicates stuff other than whitespace since start of line.")
677
678 (js2-deflocal js2-ts-regexp-flags nil
679 "Token stream buffer-local variable.")
680
681 (js2-deflocal js2-ts-string ""
682 "Token stream buffer-local variable.
683 Last string scanned.")
684
685 (js2-deflocal js2-ts-number nil
686 "Token stream buffer-local variable.
687 Last literal number scanned.")
688
689 (js2-deflocal js2-ts-hit-eof nil
690 "Token stream buffer-local variable.")
691
692 (js2-deflocal js2-ts-line-start 0
693 "Token stream buffer-local variable.")
694
695 (js2-deflocal js2-ts-lineno 1
696 "Token stream buffer-local variable.")
697
698 (js2-deflocal js2-ts-line-end-char -1
699 "Token stream buffer-local variable.")
700
701 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
702 "Token stream buffer-local variable.
703 Current scan position.")
704
705 (js2-deflocal js2-ts-is-xml-attribute nil
706 "Token stream buffer-local variable.")
707
708 (js2-deflocal js2-ts-xml-is-tag-content nil
709 "Token stream buffer-local variable.")
710
711 (js2-deflocal js2-ts-xml-open-tags-count 0
712 "Token stream buffer-local variable.")
713
714 (js2-deflocal js2-ts-string-buffer nil
715 "Token stream buffer-local variable.
716 List of chars built up while scanning various tokens.")
717
718 (js2-deflocal js2-ts-comment-type nil
719 "Token stream buffer-local variable.")
720
721 ;;; Parser variables
722
723 (js2-deflocal js2-parsed-errors nil
724 "List of errors produced during scanning/parsing.")
725
726 (js2-deflocal js2-parsed-warnings nil
727 "List of warnings produced during scanning/parsing.")
728
729 (js2-deflocal js2-recover-from-parse-errors t
730 "Non-nil to continue parsing after a syntax error.
731
732 In recovery mode, the AST will be built in full, and any error
733 nodes will be flagged with appropriate error information. If
734 this flag is nil, a syntax error will result in an error being
735 signaled.
736
737 The variable is automatically buffer-local, because different
738 modes that use the parser will need different settings.")
739
740 (js2-deflocal js2-parse-hook nil
741 "List of callbacks for receiving parsing progress.")
742
743 (defvar js2-parse-finished-hook nil
744 "List of callbacks to notify when parsing finishes.
745 Not called if parsing was interrupted.")
746
747 (js2-deflocal js2-is-eval-code nil
748 "True if we're evaluating code in a string.
749 If non-nil, the tokenizer will record the token text, and the AST nodes
750 will record their source text. Off by default for IDE modes, since the
751 text is available in the buffer.")
752
753 (defvar js2-parse-ide-mode t
754 "Non-nil if the parser is being used for `js2-mode'.
755 If non-nil, the parser will set text properties for fontification
756 and the syntax table. The value should be nil when using the
757 parser as a frontend to an interpreter or byte compiler.")
758
759 ;;; Parser instance variables (buffer-local vars for js2-parse)
760
761 (defconst js2-clear-ti-mask #xFFFF
762 "Mask to clear token information bits.")
763
764 (defconst js2-ti-after-eol (lsh 1 16)
765 "Flag: first token of the source line.")
766
767 (defconst js2-ti-check-label (lsh 1 17)
768 "Flag: indicates to check for label.")
769
770 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
771
772 (js2-deflocal js2-compiler-generate-debug-info t)
773 (js2-deflocal js2-compiler-use-dynamic-scope nil)
774 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
775 (js2-deflocal js2-compiler-xml-available t)
776 (js2-deflocal js2-compiler-optimization-level 0)
777 (js2-deflocal js2-compiler-generating-source t)
778 (js2-deflocal js2-compiler-strict-mode nil)
779 (js2-deflocal js2-compiler-report-warning-as-error nil)
780 (js2-deflocal js2-compiler-generate-observer-count nil)
781 (js2-deflocal js2-compiler-activation-names nil)
782
783 ;; SKIP: sourceURI
784
785 ;; There's a compileFunction method in Context.java - may need it.
786 (js2-deflocal js2-called-by-compile-function nil
787 "True if `js2-parse' was called by `js2-compile-function'.
788 Will only be used when we finish implementing the interpreter.")
789
790 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
791
792 (js2-deflocal js2-current-flagged-token js2-EOF)
793 (js2-deflocal js2-current-token js2-EOF)
794
795 ;; SKIP: node factory - we're going to just call functions directly,
796 ;; and eventually go to a unified AST format.
797
798 (js2-deflocal js2-nesting-of-function 0)
799
800 (js2-deflocal js2-recorded-identifiers nil
801 "Tracks identifiers found during parsing.")
802
803 (js2-deflocal js2-is-in-destructuring nil
804 "True while parsing destructuring expression.")
805
806 (defcustom js2-global-externs nil
807 "A list of any extern names you'd like to consider always declared.
808 This list is global and is used by all `js2-mode' files.
809 You can create buffer-local externs list using `js2-additional-externs'.
810
811 There is also a buffer-local variable `js2-default-externs',
812 which is initialized by default to include the Ecma-262 externs
813 and the standard browser externs. The three lists are all
814 checked during highlighting."
815 :type 'list
816 :group 'js2-mode)
817
818 (js2-deflocal js2-default-externs nil
819 "Default external declarations.
820
821 These are currently only used for highlighting undeclared variables,
822 which only worries about top-level (unqualified) references.
823 As js2-mode's processing improves, we will flesh out this list.
824
825 The initial value is set to `js2-ecma-262-externs', unless you
826 have set `js2-include-browser-externs', in which case the browser
827 externs are also included.
828
829 See `js2-additional-externs' for more information.")
830
831 (defcustom js2-include-browser-externs t
832 "Non-nil to include browser externs in the master externs list.
833 If you work on JavaScript files that are not intended for browsers,
834 such as Mozilla Rhino server-side JavaScript, set this to nil.
835 You can always include them on a per-file basis by calling
836 `js2-add-browser-externs' from a function on `js2-mode-hook'.
837
838 See `js2-additional-externs' for more information about externs."
839 :type 'boolean
840 :group 'js2-mode)
841
842 (defcustom js2-include-rhino-externs t
843 "Non-nil to include Mozilla Rhino externs in the master externs list.
844 See `js2-additional-externs' for more information about externs."
845 :type 'boolean
846 :group 'js2-mode)
847
848 (defcustom js2-include-gears-externs t
849 "Non-nil to include Google Gears externs in the master externs list.
850 See `js2-additional-externs' for more information about externs."
851 :type 'boolean
852 :group 'js2-mode)
853
854 (js2-deflocal js2-additional-externs nil
855 "A buffer-local list of additional external declarations.
856 It is used to decide whether variables are considered undeclared
857 for purposes of highlighting.
858
859 Each entry is a Lisp string. The string should be the fully qualified
860 name of an external entity. All externs should be added to this list,
861 so that as js2-mode's processing improves it can take advantage of them.
862
863 You may want to declare your externs in three ways.
864 First, you can add externs that are valid for all your JavaScript files.
865 You should probably do this by adding them to `js2-global-externs', which
866 is a global list used for all js2-mode files.
867
868 Next, you can add a function to `js2-mode-hook' that adds additional
869 externs appropriate for the specific file, perhaps based on its path.
870 These should go in `js2-additional-externs', which is buffer-local.
871
872 Finally, you can add a function to `js2-post-parse-callbacks',
873 which is called after parsing completes, and `root' is bound to
874 the root of the parse tree. At this stage you can set up an AST
875 node visitor using `js2-visit-ast' and examine the parse tree
876 for specific import patterns that may imply the existence of
877 other externs, possibly tied to your build system. These should also
878 be added to `js2-additional-externs'.
879
880 Your post-parse callback may of course also use the simpler and
881 faster (but perhaps less robust) approach of simply scanning the
882 buffer text for your imports, using regular expressions.")
883
884 ;; SKIP: decompiler
885 ;; SKIP: encoded-source
886
887 ;;; The following variables are per-function and should be saved/restored
888 ;;; during function parsing...
889
890 (js2-deflocal js2-current-script-or-fn nil)
891 (js2-deflocal js2-current-scope nil)
892 (js2-deflocal js2-nesting-of-with 0)
893 (js2-deflocal js2-label-set nil
894 "An alist mapping label names to nodes.")
895
896 (js2-deflocal js2-loop-set nil)
897 (js2-deflocal js2-loop-and-switch-set nil)
898 (js2-deflocal js2-has-return-value nil)
899 (js2-deflocal js2-end-flags 0)
900
901 ;;; ...end of per function variables
902
903 ;; Without 2-token lookahead, labels are a problem.
904 ;; These vars store the token info of the last matched name,
905 ;; iff it wasn't the last matched token. Only valid in some contexts.
906 (defvar js2-prev-name-token-start nil)
907 (defvar js2-prev-name-token-string nil)
908
909 (defsubst js2-save-name-token-data (pos name)
910 (setq js2-prev-name-token-start pos
911 js2-prev-name-token-string name))
912
913 ;; These flags enumerate the possible ways a statement/function can
914 ;; terminate. These flags are used by endCheck() and by the Parser to
915 ;; detect inconsistent return usage.
916 ;;
917 ;; END_UNREACHED is reserved for code paths that are assumed to always be
918 ;; able to execute (example: throw, continue)
919 ;;
920 ;; END_DROPS_OFF indicates if the statement can transfer control to the
921 ;; next one. Statement such as return dont. A compound statement may have
922 ;; some branch that drops off control to the next statement.
923 ;;
924 ;; END_RETURNS indicates that the statement can return (without arguments)
925 ;; END_RETURNS_VALUE indicates that the statement can return a value.
926 ;;
927 ;; A compound statement such as
928 ;; if (condition) {
929 ;; return value;
930 ;; }
931 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
932
933 (defconst js2-end-unreached #x0)
934 (defconst js2-end-drops-off #x1)
935 (defconst js2-end-returns #x2)
936 (defconst js2-end-returns-value #x4)
937 (defconst js2-end-yields #x8)
938
939 ;; Rhino awkwardly passes a statementLabel parameter to the
940 ;; statementHelper() function, the main statement parser, which
941 ;; is then used by quite a few of the sub-parsers. We just make
942 ;; it a buffer-local variable and make sure it's cleaned up properly.
943 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
944
945 ;; Similarly, Rhino passes an inForInit boolean through about half
946 ;; the expression parsers. We use a dynamically-scoped variable,
947 ;; which makes it easier to funcall the parsers individually without
948 ;; worrying about whether they take the parameter or not.
949 (js2-deflocal js2-in-for-init nil)
950 (js2-deflocal js2-temp-name-counter 0)
951 (js2-deflocal js2-parse-stmt-count 0)
952
953 (defsubst js2-get-next-temp-name ()
954 (format "$%d" (incf js2-temp-name-counter)))
955
956 (defvar js2-parse-interruptable-p t
957 "Set this to nil to force parse to continue until finished.
958 This will mostly be useful for interpreters.")
959
960 (defvar js2-statements-per-pause 50
961 "Pause after this many statements to check for user input.
962 If user input is pending, stop the parse and discard the tree.
963 This makes for a smoother user experience for large files.
964 You may have to wait a second or two before the highlighting
965 and error-reporting appear, but you can always type ahead if
966 you wish. This appears to be more or less how Eclipse, IntelliJ
967 and other editors work.")
968
969 (js2-deflocal js2-record-comments t
970 "Instructs the scanner to record comments in `js2-scanned-comments'.")
971
972 (js2-deflocal js2-scanned-comments nil
973 "List of all comments from the current parse.")
974
975 (defcustom js2-mode-indent-inhibit-undo nil
976 "Non-nil to disable collection of Undo information when indenting lines.
977 Some users have requested this behavior. It's nil by default because
978 other Emacs modes don't work this way."
979 :type 'boolean
980 :group 'js2-mode)
981
982 (defcustom js2-mode-indent-ignore-first-tab nil
983 "If non-nil, ignore first TAB keypress if we look indented properly.
984 It's fairly common for users to navigate to an already-indented line
985 and press TAB for reassurance that it's been indented. For this class
986 of users, we want the first TAB press on a line to be ignored if the
987 line is already indented to one of the precomputed alternatives.
988
989 This behavior is only partly implemented. If you TAB-indent a line,
990 navigate to another line, and then navigate back, it fails to clear
991 the last-indented variable, so it thinks you've already hit TAB once,
992 and performs the indent. A full solution would involve getting on the
993 point-motion hooks for the entire buffer. If we come across another
994 use cases that requires watching point motion, I'll consider doing it.
995
996 If you set this variable to nil, then the TAB key will always change
997 the indentation of the current line, if more than one alternative
998 indentation spot exists."
999 :type 'boolean
1000 :group 'js2-mode)
1001
1002 (defvar js2-indent-hook nil
1003 "A hook for user-defined indentation rules.
1004
1005 Functions on this hook should expect two arguments: (LIST INDEX)
1006 The LIST argument is the list of computed indentation points for
1007 the current line. INDEX is the list index of the indentation point
1008 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1009 indent function is not going to change the current line indentation.
1010
1011 If a hook function on this list returns a non-nil value, then
1012 `js2-bounce-indent' assumes the hook function has performed its own
1013 indentation, and will do nothing. If all hook functions on the list
1014 return nil, then `js2-bounce-indent' will use its computed indentation
1015 and reindent the line.
1016
1017 When hook functions on this hook list are called, the variable
1018 `js2-mode-ast' may or may not be set, depending on whether the
1019 parse tree is available. If the variable is nil, you can pass a
1020 callback to `js2-mode-wait-for-parse', and your callback will be
1021 called after the new parse tree is built. This can take some time
1022 in large files.")
1023
1024 (defface js2-warning
1025 `((((class color) (background light))
1026 (:underline "orange"))
1027 (((class color) (background dark))
1028 (:underline "orange"))
1029 (t (:underline t)))
1030 "Face for JavaScript warnings."
1031 :group 'js2-mode)
1032
1033 (defface js2-error
1034 `((((class color) (background light))
1035 (:foreground "red"))
1036 (((class color) (background dark))
1037 (:foreground "red"))
1038 (t (:foreground "red")))
1039 "Face for JavaScript errors."
1040 :group 'js2-mode)
1041
1042 (defface js2-jsdoc-tag
1043 '((t :foreground "SlateGray"))
1044 "Face used to highlight @whatever tags in jsdoc comments."
1045 :group 'js2-mode)
1046
1047 (defface js2-jsdoc-type
1048 '((t :foreground "SteelBlue"))
1049 "Face used to highlight {FooBar} types in jsdoc comments."
1050 :group 'js2-mode)
1051
1052 (defface js2-jsdoc-value
1053 '((t :foreground "PeachPuff3"))
1054 "Face used to highlight tag values in jsdoc comments."
1055 :group 'js2-mode)
1056
1057 (defface js2-function-param
1058 '((t :foreground "SeaGreen"))
1059 "Face used to highlight function parameters in javascript."
1060 :group 'js2-mode)
1061
1062 (defface js2-instance-member
1063 '((t :foreground "DarkOrchid"))
1064 "Face used to highlight instance variables in javascript.
1065 Not currently used."
1066 :group 'js2-mode)
1067
1068 (defface js2-private-member
1069 '((t :foreground "PeachPuff3"))
1070 "Face used to highlight calls to private methods in javascript.
1071 Not currently used."
1072 :group 'js2-mode)
1073
1074 (defface js2-private-function-call
1075 '((t :foreground "goldenrod"))
1076 "Face used to highlight calls to private functions in javascript.
1077 Not currently used."
1078 :group 'js2-mode)
1079
1080 (defface js2-jsdoc-html-tag-name
1081 '((((class color) (min-colors 88) (background light))
1082 (:foreground "rosybrown"))
1083 (((class color) (min-colors 8) (background dark))
1084 (:foreground "yellow"))
1085 (((class color) (min-colors 8) (background light))
1086 (:foreground "magenta")))
1087 "Face used to highlight jsdoc html tag names"
1088 :group 'js2-mode)
1089
1090 (defface js2-jsdoc-html-tag-delimiter
1091 '((((class color) (min-colors 88) (background light))
1092 (:foreground "dark khaki"))
1093 (((class color) (min-colors 8) (background dark))
1094 (:foreground "green"))
1095 (((class color) (min-colors 8) (background light))
1096 (:foreground "green")))
1097 "Face used to highlight brackets in jsdoc html tags."
1098 :group 'js2-mode)
1099
1100 (defface js2-external-variable
1101 '((t :foreground "orange"))
1102 "Face used to highlight undeclared variable identifiers.")
1103
1104 (defcustom js2-post-parse-callbacks nil
1105 "A list of callback functions invoked after parsing finishes.
1106 Currently, the main use for this function is to add synthetic
1107 declarations to `js2-recorded-identifiers', which see."
1108 :type 'list
1109 :group 'js2-mode)
1110
1111 (defcustom js2-highlight-external-variables t
1112 "Non-nil to highlight undeclared variable identifiers.
1113 An undeclared variable is any variable not declared with var or let
1114 in the current scope or any lexically enclosing scope. If you use
1115 such a variable, then you are either expecting it to originate from
1116 another file, or you've got a potential bug."
1117 :type 'boolean
1118 :group 'js2-mode)
1119
1120 (defcustom js2-auto-insert-catch-block t
1121 "Non-nil to insert matching catch block on open-curly after `try'."
1122 :type 'boolean
1123 :group 'js2-mode)
1124
1125 (defvar js2-mode-map
1126 (let ((map (make-sparse-keymap))
1127 keys)
1128 (define-key map [mouse-1] #'js2-mode-show-node)
1129 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1130 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1131 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1132 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1133 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1134 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1135 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1136 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1137 (when js2-bounce-indent-p
1138 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1139
1140 (define-key map [menu-bar javascript]
1141 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1142
1143 (define-key map [menu-bar javascript customize-js2-mode]
1144 '(menu-item "Customize js2-mode" js2-mode-customize
1145 :help "Customize the behavior of this mode"))
1146
1147 (define-key map [menu-bar javascript js2-force-refresh]
1148 '(menu-item "Force buffer refresh" js2-mode-reset
1149 :help "Re-parse the buffer from scratch"))
1150
1151 (define-key map [menu-bar javascript separator-2]
1152 '("--"))
1153
1154 (define-key map [menu-bar javascript next-error]
1155 '(menu-item "Next warning or error" next-error
1156 :enabled (and js2-mode-ast
1157 (or (js2-ast-root-errors js2-mode-ast)
1158 (js2-ast-root-warnings js2-mode-ast)))
1159 :help "Move to next warning or error"))
1160
1161 (define-key map [menu-bar javascript display-errors]
1162 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1163 :visible (not js2-mode-show-parse-errors)
1164 :help "Turn on display of warnings and errors"))
1165
1166 (define-key map [menu-bar javascript hide-errors]
1167 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1168 :visible js2-mode-show-parse-errors
1169 :help "Turn off display of warnings and errors"))
1170
1171 (define-key map [menu-bar javascript separator-1]
1172 '("--"))
1173
1174 (define-key map [menu-bar javascript js2-toggle-function]
1175 '(menu-item "Show/collapse element" js2-mode-toggle-element
1176 :help "Hide or show function body or comment"))
1177
1178 (define-key map [menu-bar javascript show-comments]
1179 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1180 :visible js2-mode-comments-hidden
1181 :help "Expand all hidden block comments"))
1182
1183 (define-key map [menu-bar javascript hide-comments]
1184 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1185 :visible (not js2-mode-comments-hidden)
1186 :help "Show block comments as /*...*/"))
1187
1188 (define-key map [menu-bar javascript show-all-functions]
1189 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1190 :visible js2-mode-functions-hidden
1191 :help "Expand all hidden function bodies"))
1192
1193 (define-key map [menu-bar javascript hide-all-functions]
1194 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1195 :visible (not js2-mode-functions-hidden)
1196 :help "Show {...} for all top-level function bodies"))
1197
1198 map)
1199 "Keymap used in `js2-mode' buffers.")
1200
1201 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1202
1203 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1204 "Matches a //-comment line. Must be first non-whitespace on line.
1205 First match-group is the leading whitespace.")
1206
1207 (defvar js2-mode-hook nil)
1208
1209 (js2-deflocal js2-mode-ast nil "Private variable.")
1210 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1211 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1212 (js2-deflocal js2-mode-parsing nil "Private variable.")
1213 (js2-deflocal js2-mode-node-overlay nil)
1214
1215 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1216 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1217
1218 (js2-deflocal js2-mode-fontifications nil "Private variable")
1219 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1220 (js2-deflocal js2-imenu-recorder nil "Private variable")
1221 (js2-deflocal js2-imenu-function-map nil "Private variable")
1222
1223 (defvar js2-paragraph-start
1224 "\\(@[a-zA-Z]+\\>\\|$\\)")
1225
1226 ;; Note that we also set a 'c-in-sws text property in html comments,
1227 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1228 (defvar js2-syntactic-ws-start
1229 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1230
1231 (defvar js2-syntactic-ws-end
1232 "\\s \\|[\n\r/]\\|\\s!")
1233
1234 (defvar js2-syntactic-eol
1235 (concat "\\s *\\(/\\*[^*\n\r]*"
1236 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1237 "\\*+/\\s *\\)*"
1238 "\\(//\\|/\\*[^*\n\r]*"
1239 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1240 "\\|\\\\$\\|$\\)")
1241 "Copied from `java-mode'. Needed for some cc-engine functions.")
1242
1243 (defvar js2-comment-prefix-regexp
1244 "//+\\|\\**")
1245
1246 (defvar js2-comment-start-skip
1247 "\\(//+\\|/\\*+\\)\\s *")
1248
1249 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1250 "Non-nil to emit status messages during parsing.")
1251
1252 (defvar js2-mode-functions-hidden nil "Private variable.")
1253 (defvar js2-mode-comments-hidden nil "Private variable.")
1254
1255 (defvar js2-mode-syntax-table
1256 (let ((table (make-syntax-table)))
1257 (c-populate-syntax-table table)
1258 table)
1259 "Syntax table used in `js2-mode' buffers.")
1260
1261 (defvar js2-mode-abbrev-table nil
1262 "Abbrev table in use in `js2-mode' buffers.")
1263 (define-abbrev-table 'js2-mode-abbrev-table ())
1264
1265 (defvar js2-mode-pending-parse-callbacks nil
1266 "List of functions waiting to be notified that parse is finished.")
1267
1268 (defvar js2-mode-last-indented-line -1)
1269
1270 ;;; Localizable error and warning messages
1271
1272 ;; Messages are copied from Rhino's Messages.properties.
1273 ;; Many of the Java-specific messages have been elided.
1274 ;; Add any js2-specific ones at the end, so we can keep
1275 ;; this file synced with changes to Rhino's.
1276
1277 (defvar js2-message-table
1278 (make-hash-table :test 'equal :size 250)
1279 "Contains localized messages for `js2-mode'.")
1280
1281 ;; TODO(stevey): construct this table at compile-time.
1282 (defmacro js2-msg (key &rest strings)
1283 `(puthash ,key (funcall #'concat ,@strings)
1284 js2-message-table))
1285
1286 (defun js2-get-msg (msg-key)
1287 "Look up a localized message.
1288 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1289 the correct number of ARGS must be provided."
1290 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1291 (args (if (listp msg-key) (cdr msg-key)))
1292 (msg (gethash key js2-message-table)))
1293 (if msg
1294 (apply #'format msg args)
1295 key))) ; default to showing the key
1296
1297 (js2-msg "msg.dup.parms"
1298 "Duplicate parameter name '%s'.")
1299
1300 (js2-msg "msg.too.big.jump"
1301 "Program too complex: jump offset too big.")
1302
1303 (js2-msg "msg.too.big.index"
1304 "Program too complex: internal index exceeds 64K limit.")
1305
1306 (js2-msg "msg.while.compiling.fn"
1307 "Encountered code generation error while compiling function '%s': %s")
1308
1309 (js2-msg "msg.while.compiling.script"
1310 "Encountered code generation error while compiling script: %s")
1311
1312 ;; Context
1313 (js2-msg "msg.ctor.not.found"
1314 "Constructor for '%s' not found.")
1315
1316 (js2-msg "msg.not.ctor"
1317 "'%s' is not a constructor.")
1318
1319 ;; FunctionObject
1320 (js2-msg "msg.varargs.ctor"
1321 "Method or constructor '%s' must be static "
1322 "with the signature (Context cx, Object[] args, "
1323 "Function ctorObj, boolean inNewExpr) "
1324 "to define a variable arguments constructor.")
1325
1326 (js2-msg "msg.varargs.fun"
1327 "Method '%s' must be static with the signature "
1328 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1329 "to define a variable arguments function.")
1330
1331 (js2-msg "msg.incompat.call"
1332 "Method '%s' called on incompatible object.")
1333
1334 (js2-msg "msg.bad.parms"
1335 "Unsupported parameter type '%s' in method '%s'.")
1336
1337 (js2-msg "msg.bad.method.return"
1338 "Unsupported return type '%s' in method '%s'.")
1339
1340 (js2-msg "msg.bad.ctor.return"
1341 "Construction of objects of type '%s' is not supported.")
1342
1343 (js2-msg "msg.no.overload"
1344 "Method '%s' occurs multiple times in class '%s'.")
1345
1346 (js2-msg "msg.method.not.found"
1347 "Method '%s' not found in '%s'.")
1348
1349 ;; IRFactory
1350
1351 (js2-msg "msg.bad.for.in.lhs"
1352 "Invalid left-hand side of for..in loop.")
1353
1354 (js2-msg "msg.mult.index"
1355 "Only one variable allowed in for..in loop.")
1356
1357 (js2-msg "msg.bad.for.in.destruct"
1358 "Left hand side of for..in loop must be an array of "
1359 "length 2 to accept key/value pair.")
1360
1361 (js2-msg "msg.cant.convert"
1362 "Can't convert to type '%s'.")
1363
1364 (js2-msg "msg.bad.assign.left"
1365 "Invalid assignment left-hand side.")
1366
1367 (js2-msg "msg.bad.decr"
1368 "Invalid decerement operand.")
1369
1370 (js2-msg "msg.bad.incr"
1371 "Invalid increment operand.")
1372
1373 (js2-msg "msg.bad.yield"
1374 "yield must be in a function.")
1375
1376 (js2-msg "msg.yield.parenthesized"
1377 "yield expression must be parenthesized.")
1378
1379 ;; NativeGlobal
1380 (js2-msg "msg.cant.call.indirect"
1381 "Function '%s' must be called directly, and not by way of a "
1382 "function of another name.")
1383
1384 (js2-msg "msg.eval.nonstring"
1385 "Calling eval() with anything other than a primitive "
1386 "string value will simply return the value. "
1387 "Is this what you intended?")
1388
1389 (js2-msg "msg.eval.nonstring.strict"
1390 "Calling eval() with anything other than a primitive "
1391 "string value is not allowed in strict mode.")
1392
1393 (js2-msg "msg.bad.destruct.op"
1394 "Invalid destructuring assignment operator")
1395
1396 ;; NativeCall
1397 (js2-msg "msg.only.from.new"
1398 "'%s' may only be invoked from a `new' expression.")
1399
1400 (js2-msg "msg.deprec.ctor"
1401 "The '%s' constructor is deprecated.")
1402
1403 ;; NativeFunction
1404 (js2-msg "msg.no.function.ref.found"
1405 "no source found to decompile function reference %s")
1406
1407 (js2-msg "msg.arg.isnt.array"
1408 "second argument to Function.prototype.apply must be an array")
1409
1410 ;; NativeGlobal
1411 (js2-msg "msg.bad.esc.mask"
1412 "invalid string escape mask")
1413
1414 ;; NativeRegExp
1415 (js2-msg "msg.bad.quant"
1416 "Invalid quantifier %s")
1417
1418 (js2-msg "msg.overlarge.backref"
1419 "Overly large back reference %s")
1420
1421 (js2-msg "msg.overlarge.min"
1422 "Overly large minimum %s")
1423
1424 (js2-msg "msg.overlarge.max"
1425 "Overly large maximum %s")
1426
1427 (js2-msg "msg.zero.quant"
1428 "Zero quantifier %s")
1429
1430 (js2-msg "msg.max.lt.min"
1431 "Maximum %s less than minimum")
1432
1433 (js2-msg "msg.unterm.quant"
1434 "Unterminated quantifier %s")
1435
1436 (js2-msg "msg.unterm.paren"
1437 "Unterminated parenthetical %s")
1438
1439 (js2-msg "msg.unterm.class"
1440 "Unterminated character class %s")
1441
1442 (js2-msg "msg.bad.range"
1443 "Invalid range in character class.")
1444
1445 (js2-msg "msg.trail.backslash"
1446 "Trailing \\ in regular expression.")
1447
1448 (js2-msg "msg.re.unmatched.right.paren"
1449 "unmatched ) in regular expression.")
1450
1451 (js2-msg "msg.no.regexp"
1452 "Regular expressions are not available.")
1453
1454 (js2-msg "msg.bad.backref"
1455 "back-reference exceeds number of capturing parentheses.")
1456
1457 (js2-msg "msg.bad.regexp.compile"
1458 "Only one argument may be specified if the first "
1459 "argument to RegExp.prototype.compile is a RegExp object.")
1460
1461 ;; Parser
1462 (js2-msg "msg.got.syntax.errors"
1463 "Compilation produced %s syntax errors.")
1464
1465 (js2-msg "msg.var.redecl"
1466 "TypeError: redeclaration of var %s.")
1467
1468 (js2-msg "msg.const.redecl"
1469 "TypeError: redeclaration of const %s.")
1470
1471 (js2-msg "msg.let.redecl"
1472 "TypeError: redeclaration of variable %s.")
1473
1474 (js2-msg "msg.parm.redecl"
1475 "TypeError: redeclaration of formal parameter %s.")
1476
1477 (js2-msg "msg.fn.redecl"
1478 "TypeError: redeclaration of function %s.")
1479
1480 (js2-msg "msg.let.decl.not.in.block"
1481 "SyntaxError: let declaration not directly within block")
1482
1483 ;; NodeTransformer
1484 (js2-msg "msg.dup.label"
1485 "duplicated label")
1486
1487 (js2-msg "msg.undef.label"
1488 "undefined label")
1489
1490 (js2-msg "msg.bad.break"
1491 "unlabelled break must be inside loop or switch")
1492
1493 (js2-msg "msg.continue.outside"
1494 "continue must be inside loop")
1495
1496 (js2-msg "msg.continue.nonloop"
1497 "continue can only use labels of iteration statements")
1498
1499 (js2-msg "msg.bad.throw.eol"
1500 "Line terminator is not allowed between the throw "
1501 "keyword and throw expression.")
1502
1503 (js2-msg "msg.no.paren.parms"
1504 "missing ( before function parameters.")
1505
1506 (js2-msg "msg.no.parm"
1507 "missing formal parameter")
1508
1509 (js2-msg "msg.no.paren.after.parms"
1510 "missing ) after formal parameters")
1511
1512 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1513 "parameter without default follows parameter with default")
1514
1515 (js2-msg "msg.param.after.rest" ; added by js2-mode
1516 "parameter after rest parameter")
1517
1518 (js2-msg "msg.no.brace.body"
1519 "missing '{' before function body")
1520
1521 (js2-msg "msg.no.brace.after.body"
1522 "missing } after function body")
1523
1524 (js2-msg "msg.no.paren.cond"
1525 "missing ( before condition")
1526
1527 (js2-msg "msg.no.paren.after.cond"
1528 "missing ) after condition")
1529
1530 (js2-msg "msg.no.semi.stmt"
1531 "missing ; before statement")
1532
1533 (js2-msg "msg.missing.semi"
1534 "missing ; after statement")
1535
1536 (js2-msg "msg.no.name.after.dot"
1537 "missing name after . operator")
1538
1539 (js2-msg "msg.no.name.after.coloncolon"
1540 "missing name after :: operator")
1541
1542 (js2-msg "msg.no.name.after.dotdot"
1543 "missing name after .. operator")
1544
1545 (js2-msg "msg.no.name.after.xmlAttr"
1546 "missing name after .@")
1547
1548 (js2-msg "msg.no.bracket.index"
1549 "missing ] in index expression")
1550
1551 (js2-msg "msg.no.paren.switch"
1552 "missing ( before switch expression")
1553
1554 (js2-msg "msg.no.paren.after.switch"
1555 "missing ) after switch expression")
1556
1557 (js2-msg "msg.no.brace.switch"
1558 "missing '{' before switch body")
1559
1560 (js2-msg "msg.bad.switch"
1561 "invalid switch statement")
1562
1563 (js2-msg "msg.no.colon.case"
1564 "missing : after case expression")
1565
1566 (js2-msg "msg.double.switch.default"
1567 "double default label in the switch statement")
1568
1569 (js2-msg "msg.no.while.do"
1570 "missing while after do-loop body")
1571
1572 (js2-msg "msg.no.paren.for"
1573 "missing ( after for")
1574
1575 (js2-msg "msg.no.semi.for"
1576 "missing ; after for-loop initializer")
1577
1578 (js2-msg "msg.no.semi.for.cond"
1579 "missing ; after for-loop condition")
1580
1581 (js2-msg "msg.in.after.for.name"
1582 "missing in or of after for")
1583
1584 (js2-msg "msg.no.paren.for.ctrl"
1585 "missing ) after for-loop control")
1586
1587 (js2-msg "msg.no.paren.with"
1588 "missing ( before with-statement object")
1589
1590 (js2-msg "msg.no.paren.after.with"
1591 "missing ) after with-statement object")
1592
1593 (js2-msg "msg.no.paren.after.let"
1594 "missing ( after let")
1595
1596 (js2-msg "msg.no.paren.let"
1597 "missing ) after variable list")
1598
1599 (js2-msg "msg.no.curly.let"
1600 "missing } after let statement")
1601
1602 (js2-msg "msg.bad.return"
1603 "invalid return")
1604
1605 (js2-msg "msg.no.brace.block"
1606 "missing } in compound statement")
1607
1608 (js2-msg "msg.bad.label"
1609 "invalid label")
1610
1611 (js2-msg "msg.bad.var"
1612 "missing variable name")
1613
1614 (js2-msg "msg.bad.var.init"
1615 "invalid variable initialization")
1616
1617 (js2-msg "msg.no.colon.cond"
1618 "missing : in conditional expression")
1619
1620 (js2-msg "msg.no.paren.arg"
1621 "missing ) after argument list")
1622
1623 (js2-msg "msg.no.bracket.arg"
1624 "missing ] after element list")
1625
1626 (js2-msg "msg.bad.prop"
1627 "invalid property id")
1628
1629 (js2-msg "msg.no.colon.prop"
1630 "missing : after property id")
1631
1632 (js2-msg "msg.no.brace.prop"
1633 "missing } after property list")
1634
1635 (js2-msg "msg.no.paren"
1636 "missing ) in parenthetical")
1637
1638 (js2-msg "msg.reserved.id"
1639 "identifier is a reserved word")
1640
1641 (js2-msg "msg.no.paren.catch"
1642 "missing ( before catch-block condition")
1643
1644 (js2-msg "msg.bad.catchcond"
1645 "invalid catch block condition")
1646
1647 (js2-msg "msg.catch.unreachable"
1648 "any catch clauses following an unqualified catch are unreachable")
1649
1650 (js2-msg "msg.no.brace.try"
1651 "missing '{' before try block")
1652
1653 (js2-msg "msg.no.brace.catchblock"
1654 "missing '{' before catch-block body")
1655
1656 (js2-msg "msg.try.no.catchfinally"
1657 "'try' without 'catch' or 'finally'")
1658
1659 (js2-msg "msg.no.return.value"
1660 "function %s does not always return a value")
1661
1662 (js2-msg "msg.anon.no.return.value"
1663 "anonymous function does not always return a value")
1664
1665 (js2-msg "msg.return.inconsistent"
1666 "return statement is inconsistent with previous usage")
1667
1668 (js2-msg "msg.generator.returns"
1669 "TypeError: generator function '%s' returns a value")
1670
1671 (js2-msg "msg.anon.generator.returns"
1672 "TypeError: anonymous generator function returns a value")
1673
1674 (js2-msg "msg.syntax"
1675 "syntax error")
1676
1677 (js2-msg "msg.unexpected.eof"
1678 "Unexpected end of file")
1679
1680 (js2-msg "msg.XML.bad.form"
1681 "illegally formed XML syntax")
1682
1683 (js2-msg "msg.XML.not.available"
1684 "XML runtime not available")
1685
1686 (js2-msg "msg.too.deep.parser.recursion"
1687 "Too deep recursion while parsing")
1688
1689 (js2-msg "msg.no.side.effects"
1690 "Code has no side effects")
1691
1692 (js2-msg "msg.extra.trailing.comma"
1693 "Trailing comma is not legal in an ECMA-262 object initializer")
1694
1695 (js2-msg "msg.array.trailing.comma"
1696 "Trailing comma yields different behavior across browsers")
1697
1698 (js2-msg "msg.equal.as.assign"
1699 (concat "Test for equality (==) mistyped as assignment (=)?"
1700 " (parenthesize to suppress warning)"))
1701
1702 (js2-msg "msg.var.hides.arg"
1703 "Variable %s hides argument")
1704
1705 (js2-msg "msg.destruct.assign.no.init"
1706 "Missing = in destructuring declaration")
1707
1708 ;; ScriptRuntime
1709 (js2-msg "msg.no.properties"
1710 "%s has no properties.")
1711
1712 (js2-msg "msg.invalid.iterator"
1713 "Invalid iterator value")
1714
1715 (js2-msg "msg.iterator.primitive"
1716 "__iterator__ returned a primitive value")
1717
1718 (js2-msg "msg.assn.create.strict"
1719 "Assignment to undeclared variable %s")
1720
1721 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1722 "Undeclared variable or function '%s'")
1723
1724 (js2-msg "msg.ref.undefined.prop"
1725 "Reference to undefined property '%s'")
1726
1727 (js2-msg "msg.prop.not.found"
1728 "Property %s not found.")
1729
1730 (js2-msg "msg.invalid.type"
1731 "Invalid JavaScript value of type %s")
1732
1733 (js2-msg "msg.primitive.expected"
1734 "Primitive type expected (had %s instead)")
1735
1736 (js2-msg "msg.namespace.expected"
1737 "Namespace object expected to left of :: (found %s instead)")
1738
1739 (js2-msg "msg.null.to.object"
1740 "Cannot convert null to an object.")
1741
1742 (js2-msg "msg.undef.to.object"
1743 "Cannot convert undefined to an object.")
1744
1745 (js2-msg "msg.cyclic.value"
1746 "Cyclic %s value not allowed.")
1747
1748 (js2-msg "msg.is.not.defined"
1749 "'%s' is not defined.")
1750
1751 (js2-msg "msg.undef.prop.read"
1752 "Cannot read property '%s' from %s")
1753
1754 (js2-msg "msg.undef.prop.write"
1755 "Cannot set property '%s' of %s to '%s'")
1756
1757 (js2-msg "msg.undef.prop.delete"
1758 "Cannot delete property '%s' of %s")
1759
1760 (js2-msg "msg.undef.method.call"
1761 "Cannot call method '%s' of %s")
1762
1763 (js2-msg "msg.undef.with"
1764 "Cannot apply 'with' to %s")
1765
1766 (js2-msg "msg.isnt.function"
1767 "%s is not a function, it is %s.")
1768
1769 (js2-msg "msg.isnt.function.in"
1770 "Cannot call property %s in object %s. "
1771 "It is not a function, it is '%s'.")
1772
1773 (js2-msg "msg.function.not.found"
1774 "Cannot find function %s.")
1775
1776 (js2-msg "msg.function.not.found.in"
1777 "Cannot find function %s in object %s.")
1778
1779 (js2-msg "msg.isnt.xml.object"
1780 "%s is not an xml object.")
1781
1782 (js2-msg "msg.no.ref.to.get"
1783 "%s is not a reference to read reference value.")
1784
1785 (js2-msg "msg.no.ref.to.set"
1786 "%s is not a reference to set reference value to %s.")
1787
1788 (js2-msg "msg.no.ref.from.function"
1789 "Function %s can not be used as the left-hand "
1790 "side of assignment or as an operand of ++ or -- operator.")
1791
1792 (js2-msg "msg.bad.default.value"
1793 "Object's getDefaultValue() method returned an object.")
1794
1795 (js2-msg "msg.instanceof.not.object"
1796 "Can't use instanceof on a non-object.")
1797
1798 (js2-msg "msg.instanceof.bad.prototype"
1799 "'prototype' property of %s is not an object.")
1800
1801 (js2-msg "msg.bad.radix"
1802 "illegal radix %s.")
1803
1804 ;; ScriptableObject
1805 (js2-msg "msg.default.value"
1806 "Cannot find default value for object.")
1807
1808 (js2-msg "msg.zero.arg.ctor"
1809 "Cannot load class '%s' which has no zero-parameter constructor.")
1810
1811 (js2-msg "msg.ctor.multiple.parms"
1812 "Can't define constructor or class %s since more than "
1813 "one constructor has multiple parameters.")
1814
1815 (js2-msg "msg.extend.scriptable"
1816 "%s must extend ScriptableObject in order to define property %s.")
1817
1818 (js2-msg "msg.bad.getter.parms"
1819 "In order to define a property, getter %s must have zero "
1820 "parameters or a single ScriptableObject parameter.")
1821
1822 (js2-msg "msg.obj.getter.parms"
1823 "Expected static or delegated getter %s to take "
1824 "a ScriptableObject parameter.")
1825
1826 (js2-msg "msg.getter.static"
1827 "Getter and setter must both be static or neither be static.")
1828
1829 (js2-msg "msg.setter.return"
1830 "Setter must have void return type: %s")
1831
1832 (js2-msg "msg.setter2.parms"
1833 "Two-parameter setter must take a ScriptableObject as "
1834 "its first parameter.")
1835
1836 (js2-msg "msg.setter1.parms"
1837 "Expected single parameter setter for %s")
1838
1839 (js2-msg "msg.setter2.expected"
1840 "Expected static or delegated setter %s to take two parameters.")
1841
1842 (js2-msg "msg.setter.parms"
1843 "Expected either one or two parameters for setter.")
1844
1845 (js2-msg "msg.setter.bad.type"
1846 "Unsupported parameter type '%s' in setter '%s'.")
1847
1848 (js2-msg "msg.add.sealed"
1849 "Cannot add a property to a sealed object: %s.")
1850
1851 (js2-msg "msg.remove.sealed"
1852 "Cannot remove a property from a sealed object: %s.")
1853
1854 (js2-msg "msg.modify.sealed"
1855 "Cannot modify a property of a sealed object: %s.")
1856
1857 (js2-msg "msg.modify.readonly"
1858 "Cannot modify readonly property: %s.")
1859
1860 ;; TokenStream
1861 (js2-msg "msg.missing.exponent"
1862 "missing exponent")
1863
1864 (js2-msg "msg.caught.nfe"
1865 "number format error")
1866
1867 (js2-msg "msg.unterminated.string.lit"
1868 "unterminated string literal")
1869
1870 (js2-msg "msg.unterminated.comment"
1871 "unterminated comment")
1872
1873 (js2-msg "msg.unterminated.re.lit"
1874 "unterminated regular expression literal")
1875
1876 (js2-msg "msg.invalid.re.flag"
1877 "invalid flag after regular expression")
1878
1879 (js2-msg "msg.no.re.input.for"
1880 "no input for %s")
1881
1882 (js2-msg "msg.illegal.character"
1883 "illegal character")
1884
1885 (js2-msg "msg.invalid.escape"
1886 "invalid Unicode escape sequence")
1887
1888 (js2-msg "msg.bad.namespace"
1889 "not a valid default namespace statement. "
1890 "Syntax is: default xml namespace = EXPRESSION;")
1891
1892 ;; TokensStream warnings
1893 (js2-msg "msg.bad.octal.literal"
1894 "illegal octal literal digit %s; "
1895 "interpreting it as a decimal digit")
1896
1897 (js2-msg "msg.reserved.keyword"
1898 "illegal usage of future reserved keyword %s; "
1899 "interpreting it as ordinary identifier")
1900
1901 (js2-msg "msg.script.is.not.constructor"
1902 "Script objects are not constructors.")
1903
1904 ;; Arrays
1905 (js2-msg "msg.arraylength.bad"
1906 "Inappropriate array length.")
1907
1908 ;; Arrays
1909 (js2-msg "msg.arraylength.too.big"
1910 "Array length %s exceeds supported capacity limit.")
1911
1912 ;; URI
1913 (js2-msg "msg.bad.uri"
1914 "Malformed URI sequence.")
1915
1916 ;; Number
1917 (js2-msg "msg.bad.precision"
1918 "Precision %s out of range.")
1919
1920 ;; NativeGenerator
1921 (js2-msg "msg.send.newborn"
1922 "Attempt to send value to newborn generator")
1923
1924 (js2-msg "msg.already.exec.gen"
1925 "Already executing generator")
1926
1927 (js2-msg "msg.StopIteration.invalid"
1928 "StopIteration may not be changed to an arbitrary object.")
1929
1930 ;; Interpreter
1931 (js2-msg "msg.yield.closing"
1932 "Yield from closing generator")
1933
1934 ;;; Utilities
1935
1936 (defun js2-delete-if (predicate list)
1937 "Remove all items satisfying PREDICATE in LIST."
1938 (loop for item in list
1939 if (not (funcall predicate item))
1940 collect item))
1941
1942 (defun js2-position (element list)
1943 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1944 Returns nil if element is not found in the list."
1945 (let ((count 0)
1946 found)
1947 (while (and list (not found))
1948 (if (eq element (car list))
1949 (setq found t)
1950 (setq count (1+ count)
1951 list (cdr list))))
1952 (if found count)))
1953
1954 (defun js2-find-if (predicate list)
1955 "Find first item satisfying PREDICATE in LIST."
1956 (let (result)
1957 (while (and list (not result))
1958 (if (funcall predicate (car list))
1959 (setq result (car list)))
1960 (setq list (cdr list)))
1961 result))
1962
1963 (defmacro js2-time (form)
1964 "Evaluate FORM, discard result, and return elapsed time in sec."
1965 (declare (debug t))
1966 (let ((beg (make-symbol "--js2-time-beg--"))
1967 (delta (make-symbol "--js2-time-end--")))
1968 `(let ((,beg (current-time))
1969 ,delta)
1970 ,form
1971 (/ (truncate (* (- (float-time (current-time))
1972 (float-time ,beg))
1973 10000))
1974 10000.0))))
1975
1976 (defsubst js2-same-line (pos)
1977 "Return t if POS is on the same line as current point."
1978 (and (>= pos (point-at-bol))
1979 (<= pos (point-at-eol))))
1980
1981 (defun js2-same-line-2 (p1 p2)
1982 "Return t if P1 is on the same line as P2."
1983 (save-excursion
1984 (goto-char p1)
1985 (js2-same-line p2)))
1986
1987 (defun js2-code-bug ()
1988 "Signal an error when we encounter an unexpected code path."
1989 (error "failed assertion"))
1990
1991 (defsubst js2-record-text-property (beg end prop value)
1992 "Record a text property to set when parsing finishes."
1993 (push (list beg end prop value) js2-mode-deferred-properties))
1994
1995 ;; I'd like to associate errors with nodes, but for now the
1996 ;; easiest thing to do is get the context info from the last token.
1997 (defun js2-record-parse-error (msg &optional arg pos len)
1998 (push (list (list msg arg)
1999 (or pos js2-token-beg)
2000 (or len (- js2-token-end js2-token-beg)))
2001 js2-parsed-errors))
2002
2003 (defun js2-report-error (msg &optional msg-arg pos len)
2004 "Signal a syntax error or record a parse error."
2005 (if js2-recover-from-parse-errors
2006 (js2-record-parse-error msg msg-arg pos len)
2007 (signal 'js2-syntax-error
2008 (list msg
2009 js2-ts-lineno
2010 (save-excursion
2011 (goto-char js2-ts-cursor)
2012 (current-column))
2013 js2-ts-hit-eof))))
2014
2015 (defun js2-report-warning (msg &optional msg-arg pos len face)
2016 (if js2-compiler-report-warning-as-error
2017 (js2-report-error msg msg-arg pos len)
2018 (push (list (list msg msg-arg)
2019 (or pos js2-token-beg)
2020 (or len (- js2-token-end js2-token-beg))
2021 face)
2022 js2-parsed-warnings)))
2023
2024 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2025 (if js2-compiler-strict-mode
2026 (js2-report-warning msg-id msg-arg beg
2027 (and beg end (- end beg)))))
2028
2029 (put 'js2-syntax-error 'error-conditions
2030 '(error syntax-error js2-syntax-error))
2031 (put 'js2-syntax-error 'error-message "Syntax error")
2032
2033 (put 'js2-parse-error 'error-conditions
2034 '(error parse-error js2-parse-error))
2035 (put 'js2-parse-error 'error-message "Parse error")
2036
2037 (defmacro js2-clear-flag (flags flag)
2038 `(setq ,flags (logand ,flags (lognot ,flag))))
2039
2040 (defmacro js2-set-flag (flags flag)
2041 "Logical-or FLAG into FLAGS."
2042 `(setq ,flags (logior ,flags ,flag)))
2043
2044 (defsubst js2-flag-set-p (flags flag)
2045 (/= 0 (logand flags flag)))
2046
2047 (defsubst js2-flag-not-set-p (flags flag)
2048 (zerop (logand flags flag)))
2049
2050 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2051 "Evaluate BODY with the _ character set to be word-syntax."
2052 (declare (indent 0) (debug t))
2053 (let ((old-syntax (make-symbol "old-syntax")))
2054 `(let ((,old-syntax (string (char-syntax ?_))))
2055 (unwind-protect
2056 (progn
2057 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2058 ,@body)
2059 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2060
2061 (defsubst js2-char-uppercase-p (c)
2062 "Return t if C is an uppercase character.
2063 Handles unicode and latin chars properly."
2064 (/= c (downcase c)))
2065
2066 (defsubst js2-char-lowercase-p (c)
2067 "Return t if C is an uppercase character.
2068 Handles unicode and latin chars properly."
2069 (/= c (upcase c)))
2070
2071 ;;; AST struct and function definitions
2072
2073 ;; flags for ast node property 'member-type (used for e4x operators)
2074 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2075 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2076 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2077
2078 (defsubst js2-relpos (pos anchor)
2079 "Convert POS to be relative to ANCHOR.
2080 If POS is nil, returns nil."
2081 (and pos (- pos anchor)))
2082
2083 (defun js2-make-pad (indent)
2084 (if (zerop indent)
2085 ""
2086 (make-string (* indent js2-basic-offset) ? )))
2087
2088 (defun js2-visit-ast (node callback)
2089 "Visit every node in ast NODE with visitor CALLBACK.
2090
2091 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2092 called twice: once to visit the node, and again after all the node's
2093 children have been processed. The END-P argument is nil on the first
2094 call and non-nil on the second call. The return value of the callback
2095 affects the traversal: if non-nil, the children of NODE are processed.
2096 If the callback returns nil, or if the node has no children, then the
2097 callback is called immediately with a non-nil END-P argument.
2098
2099 The node traversal is approximately lexical-order, although there
2100 are currently no guarantees around this."
2101 (when node
2102 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2103 ;; visit the node
2104 (when (funcall callback node nil)
2105 ;; visit the kids
2106 (cond
2107 ((eq vfunc 'js2-visit-none)
2108 nil) ; don't even bother calling it
2109 ;; Each AST node type has to define a `js2-visitor' function
2110 ;; that takes a node and a callback, and calls `js2-visit-ast'
2111 ;; on each child of the node.
2112 (vfunc
2113 (funcall vfunc node callback))
2114 (t
2115 (error "%s does not define a visitor-traversal function"
2116 (aref node 0)))))
2117 ;; call the end-visit
2118 (funcall callback node t))))
2119
2120 (defstruct (js2-node
2121 (:constructor nil)) ; abstract
2122 "Base AST node type."
2123 (type -1) ; token type
2124 (pos -1) ; start position of this AST node in parsed input
2125 (len 1) ; num characters spanned by the node
2126 props ; optional node property list (an alist)
2127 parent) ; link to parent node; null for root
2128
2129 (defsubst js2-node-get-prop (node prop &optional default)
2130 (or (cadr (assoc prop (js2-node-props node))) default))
2131
2132 (defsubst js2-node-set-prop (node prop value)
2133 (setf (js2-node-props node)
2134 (cons (list prop value) (js2-node-props node))))
2135
2136 (defun js2-fixup-starts (n nodes)
2137 "Adjust the start positions of NODES to be relative to N.
2138 Any node in the list may be nil, for convenience."
2139 (dolist (node nodes)
2140 (when node
2141 (setf (js2-node-pos node) (- (js2-node-pos node)
2142 (js2-node-pos n))))))
2143
2144 (defun js2-node-add-children (parent &rest nodes)
2145 "Set parent node of NODES to PARENT, and return PARENT.
2146 Does nothing if we're not recording parent links.
2147 If any given node in NODES is nil, doesn't record that link."
2148 (js2-fixup-starts parent nodes)
2149 (dolist (node nodes)
2150 (and node
2151 (setf (js2-node-parent node) parent))))
2152
2153 ;; Non-recursive since it's called a frightening number of times.
2154 (defun js2-node-abs-pos (n)
2155 (let ((pos (js2-node-pos n)))
2156 (while (setq n (js2-node-parent n))
2157 (setq pos (+ pos (js2-node-pos n))))
2158 pos))
2159
2160 (defsubst js2-node-abs-end (n)
2161 "Return absolute buffer position of end of N."
2162 (+ (js2-node-abs-pos n) (js2-node-len n)))
2163
2164 ;; It's important to make sure block nodes have a Lisp list for the
2165 ;; child nodes, to limit printing recursion depth in an AST that
2166 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2167 ;; a sufficiently large vector tree.
2168
2169 (defstruct (js2-block-node
2170 (:include js2-node)
2171 (:constructor nil)
2172 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2173 (pos js2-token-beg)
2174 len
2175 props
2176 kids)))
2177 "A block of statements."
2178 kids) ; a Lisp list of the child statement nodes
2179
2180 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2181 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2182
2183 (defun js2-visit-block (ast callback)
2184 "Visit the `js2-block-node' children of AST."
2185 (dolist (kid (js2-block-node-kids ast))
2186 (js2-visit-ast kid callback)))
2187
2188 (defun js2-print-block (n i)
2189 (let ((pad (js2-make-pad i)))
2190 (insert pad "{\n")
2191 (dolist (kid (js2-block-node-kids n))
2192 (js2-print-ast kid (1+ i)))
2193 (insert pad "}")))
2194
2195 (defstruct (js2-scope
2196 (:include js2-block-node)
2197 (:constructor nil)
2198 (:constructor make-js2-scope (&key (type js2-BLOCK)
2199 (pos js2-token-beg)
2200 len
2201 kids)))
2202 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2203 ;; I don't have one of those handy, so I'll use an alist for now.
2204 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2205 ;; and is much lighter-weight to construct (both CPU and mem).
2206 ;; The keys are interned strings (symbols) for faster lookup.
2207 ;; Should switch to hybrid alist/hashtable eventually.
2208 symbol-table ; an alist of (symbol . js2-symbol)
2209 parent-scope ; a `js2-scope'
2210 top) ; top-level `js2-scope' (script/function)
2211
2212 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2213 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2214
2215 (defun js2-scope-set-parent-scope (scope parent)
2216 (setf (js2-scope-parent-scope scope) parent
2217 (js2-scope-top scope) (if (null parent)
2218 scope
2219 (js2-scope-top parent))))
2220
2221 (defun js2-node-get-enclosing-scope (node)
2222 "Return the innermost `js2-scope' node surrounding NODE.
2223 Returns nil if there is no enclosing scope node."
2224 (let ((parent (js2-node-parent node)))
2225 (while (not (js2-scope-p parent))
2226 (setq parent (js2-node-parent parent)))
2227 parent))
2228
2229 (defun js2-get-defining-scope (scope name)
2230 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2231 Returns `js2-scope' in which NAME is defined, or nil if not found."
2232 (let ((sym (if (symbolp name)
2233 name
2234 (intern name)))
2235 table
2236 result
2237 (continue t))
2238 (while (and scope continue)
2239 (if (and (setq table (js2-scope-symbol-table scope))
2240 (assq sym table))
2241 (setq continue nil
2242 result scope)
2243 (setq scope (js2-scope-parent-scope scope))))
2244 result))
2245
2246 (defun js2-scope-get-symbol (scope name)
2247 "Return symbol table entry for NAME in SCOPE.
2248 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2249 (and (js2-scope-symbol-table scope)
2250 (cdr (assq (if (symbolp name)
2251 name
2252 (intern name))
2253 (js2-scope-symbol-table scope)))))
2254
2255 (defun js2-scope-put-symbol (scope name symbol)
2256 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2257 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2258 (let* ((table (js2-scope-symbol-table scope))
2259 (sym (if (symbolp name) name (intern name)))
2260 (entry (assq sym table)))
2261 (if entry
2262 (setcdr entry symbol)
2263 (push (cons sym symbol)
2264 (js2-scope-symbol-table scope)))))
2265
2266 (defstruct (js2-symbol
2267 (:constructor nil)
2268 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2269 "A symbol table entry."
2270 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2271 ;; js2-LET, or js2-CONST
2272 decl-type
2273 name ; string
2274 ast-node) ; a `js2-node'
2275
2276 (defstruct (js2-error-node
2277 (:include js2-node)
2278 (:constructor nil) ; silence emacs21 byte-compiler
2279 (:constructor make-js2-error-node (&key (type js2-ERROR)
2280 (pos js2-token-beg)
2281 len)))
2282 "AST node representing a parse error.")
2283
2284 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2285 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2286
2287 (defstruct (js2-script-node
2288 (:include js2-scope)
2289 (:constructor nil)
2290 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2291 (pos js2-token-beg)
2292 len
2293 var-decls
2294 fun-decls)))
2295 functions ; Lisp list of nested functions
2296 regexps ; Lisp list of (string . flags)
2297 symbols ; alist (every symbol gets unique index)
2298 (param-count 0)
2299 var-names ; vector of string names
2300 consts ; bool-vector matching var-decls
2301 (temp-number 0)) ; for generating temp variables
2302
2303 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2304 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2305
2306 (defun js2-print-script (node indent)
2307 (dolist (kid (js2-block-node-kids node))
2308 (js2-print-ast kid indent)))
2309
2310 (defstruct (js2-ast-root
2311 (:include js2-script-node)
2312 (:constructor nil)
2313 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2314 (pos js2-token-beg)
2315 len
2316 buffer)))
2317 "The root node of a js2 AST."
2318 buffer ; the source buffer from which the code was parsed
2319 comments ; a Lisp list of comments, ordered by start position
2320 errors ; a Lisp list of errors found during parsing
2321 warnings ; a Lisp list of warnings found during parsing
2322 node-count) ; number of nodes in the tree, including the root
2323
2324 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2325 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2326
2327 (defun js2-visit-ast-root (ast callback)
2328 (dolist (kid (js2-ast-root-kids ast))
2329 (js2-visit-ast kid callback))
2330 (dolist (comment (js2-ast-root-comments ast))
2331 (js2-visit-ast comment callback)))
2332
2333 (defstruct (js2-comment-node
2334 (:include js2-node)
2335 (:constructor nil)
2336 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2337 (pos js2-token-beg)
2338 len
2339 (format js2-ts-comment-type))))
2340 format) ; 'line, 'block, 'jsdoc or 'html
2341
2342 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2343 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2344
2345 (defun js2-print-comment (n i)
2346 ;; We really ought to link end-of-line comments to their nodes.
2347 ;; Or maybe we could add a new comment type, 'endline.
2348 (insert (js2-make-pad i)
2349 (js2-node-string n)))
2350
2351 (defstruct (js2-expr-stmt-node
2352 (:include js2-node)
2353 (:constructor nil)
2354 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2355 (pos js2-ts-cursor)
2356 len
2357 expr)))
2358 "An expression statement."
2359 expr)
2360
2361 (defsubst js2-expr-stmt-node-set-has-result (node)
2362 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2363 (setf (js2-node-type node) js2-EXPR_RESULT))
2364
2365 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2366 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2367
2368 (defun js2-visit-expr-stmt-node (n v)
2369 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2370
2371 (defun js2-print-expr-stmt-node (n indent)
2372 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2373 (insert ";\n"))
2374
2375 (defstruct (js2-loop-node
2376 (:include js2-scope)
2377 (:constructor nil))
2378 "Abstract supertype of loop nodes."
2379 body ; a `js2-block-node'
2380 lp ; position of left-paren, nil if omitted
2381 rp) ; position of right-paren, nil if omitted
2382
2383 (defstruct (js2-do-node
2384 (:include js2-loop-node)
2385 (:constructor nil)
2386 (:constructor make-js2-do-node (&key (type js2-DO)
2387 (pos js2-token-beg)
2388 len
2389 body
2390 condition
2391 while-pos
2392 lp
2393 rp)))
2394 "AST node for do-loop."
2395 condition ; while (expression)
2396 while-pos) ; buffer position of 'while' keyword
2397
2398 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2399 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2400
2401 (defun js2-visit-do-node (n v)
2402 (js2-visit-ast (js2-do-node-body n) v)
2403 (js2-visit-ast (js2-do-node-condition n) v))
2404
2405 (defun js2-print-do-node (n i)
2406 (let ((pad (js2-make-pad i)))
2407 (insert pad "do {\n")
2408 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2409 (js2-print-ast kid (1+ i)))
2410 (insert pad "} while (")
2411 (js2-print-ast (js2-do-node-condition n) 0)
2412 (insert ");\n")))
2413
2414 (defstruct (js2-while-node
2415 (:include js2-loop-node)
2416 (:constructor nil)
2417 (:constructor make-js2-while-node (&key (type js2-WHILE)
2418 (pos js2-token-beg)
2419 len body
2420 condition lp
2421 rp)))
2422 "AST node for while-loop."
2423 condition) ; while-condition
2424
2425 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2426 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2427
2428 (defun js2-visit-while-node (n v)
2429 (js2-visit-ast (js2-while-node-condition n) v)
2430 (js2-visit-ast (js2-while-node-body n) v))
2431
2432 (defun js2-print-while-node (n i)
2433 (let ((pad (js2-make-pad i)))
2434 (insert pad "while (")
2435 (js2-print-ast (js2-while-node-condition n) 0)
2436 (insert ") {\n")
2437 (js2-print-body (js2-while-node-body n) (1+ i))
2438 (insert pad "}\n")))
2439
2440 (defstruct (js2-for-node
2441 (:include js2-loop-node)
2442 (:constructor nil)
2443 (:constructor make-js2-for-node (&key (type js2-FOR)
2444 (pos js2-ts-cursor)
2445 len body init
2446 condition
2447 update lp rp)))
2448 "AST node for a C-style for-loop."
2449 init ; initialization expression
2450 condition ; loop condition
2451 update) ; update clause
2452
2453 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2454 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2455
2456 (defun js2-visit-for-node (n v)
2457 (js2-visit-ast (js2-for-node-init n) v)
2458 (js2-visit-ast (js2-for-node-condition n) v)
2459 (js2-visit-ast (js2-for-node-update n) v)
2460 (js2-visit-ast (js2-for-node-body n) v))
2461
2462 (defun js2-print-for-node (n i)
2463 (let ((pad (js2-make-pad i)))
2464 (insert pad "for (")
2465 (js2-print-ast (js2-for-node-init n) 0)
2466 (insert "; ")
2467 (js2-print-ast (js2-for-node-condition n) 0)
2468 (insert "; ")
2469 (js2-print-ast (js2-for-node-update n) 0)
2470 (insert ") {\n")
2471 (js2-print-body (js2-for-node-body n) (1+ i))
2472 (insert pad "}\n")))
2473
2474 (defstruct (js2-for-in-node
2475 (:include js2-loop-node)
2476 (:constructor nil)
2477 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2478 (pos js2-ts-cursor)
2479 len body
2480 iterator
2481 object
2482 in-pos
2483 each-pos
2484 foreach-p forof-p
2485 lp rp)))
2486 "AST node for a for..in loop."
2487 iterator ; [var] foo in ...
2488 object ; object over which we're iterating
2489 in-pos ; buffer position of 'in' keyword
2490 each-pos ; buffer position of 'each' keyword, if foreach-p
2491 foreach-p ; t if it's a for-each loop
2492 forof-p) ; t if it's a for-of loop
2493
2494 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2495 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2496
2497 (defun js2-visit-for-in-node (n v)
2498 (js2-visit-ast (js2-for-in-node-iterator n) v)
2499 (js2-visit-ast (js2-for-in-node-object n) v)
2500 (js2-visit-ast (js2-for-in-node-body n) v))
2501
2502 (defun js2-print-for-in-node (n i)
2503 (let ((pad (js2-make-pad i))
2504 (foreach (js2-for-in-node-foreach-p n))
2505 (forof (js2-for-in-node-forof-p n)))
2506 (insert pad "for ")
2507 (if foreach
2508 (insert "each "))
2509 (insert "(")
2510 (js2-print-ast (js2-for-in-node-iterator n) 0)
2511 (if forof
2512 (insert " of ")
2513 (insert " in "))
2514 (js2-print-ast (js2-for-in-node-object n) 0)
2515 (insert ") {\n")
2516 (js2-print-body (js2-for-in-node-body n) (1+ i))
2517 (insert pad "}\n")))
2518
2519 (defstruct (js2-return-node
2520 (:include js2-node)
2521 (:constructor nil)
2522 (:constructor make-js2-return-node (&key (type js2-RETURN)
2523 (pos js2-ts-cursor)
2524 len
2525 retval)))
2526 "AST node for a return statement."
2527 retval) ; expression to return, or 'undefined
2528
2529 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2530 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2531
2532 (defun js2-visit-return-node (n v)
2533 (js2-visit-ast (js2-return-node-retval n) v))
2534
2535 (defun js2-print-return-node (n i)
2536 (insert (js2-make-pad i) "return")
2537 (when (js2-return-node-retval n)
2538 (insert " ")
2539 (js2-print-ast (js2-return-node-retval n) 0))
2540 (insert ";\n"))
2541
2542 (defstruct (js2-if-node
2543 (:include js2-node)
2544 (:constructor nil)
2545 (:constructor make-js2-if-node (&key (type js2-IF)
2546 (pos js2-ts-cursor)
2547 len condition
2548 then-part
2549 else-pos
2550 else-part lp
2551 rp)))
2552 "AST node for an if-statement."
2553 condition ; expression
2554 then-part ; statement or block
2555 else-pos ; optional buffer position of 'else' keyword
2556 else-part ; optional statement or block
2557 lp ; position of left-paren, nil if omitted
2558 rp) ; position of right-paren, nil if omitted
2559
2560 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2561 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2562
2563 (defun js2-visit-if-node (n v)
2564 (js2-visit-ast (js2-if-node-condition n) v)
2565 (js2-visit-ast (js2-if-node-then-part n) v)
2566 (js2-visit-ast (js2-if-node-else-part n) v))
2567
2568 (defun js2-print-if-node (n i)
2569 (let ((pad (js2-make-pad i))
2570 (then-part (js2-if-node-then-part n))
2571 (else-part (js2-if-node-else-part n)))
2572 (insert pad "if (")
2573 (js2-print-ast (js2-if-node-condition n) 0)
2574 (insert ") {\n")
2575 (js2-print-body then-part (1+ i))
2576 (insert pad "}")
2577 (cond
2578 ((not else-part)
2579 (insert "\n"))
2580 ((js2-if-node-p else-part)
2581 (insert " else ")
2582 (js2-print-body else-part i))
2583 (t
2584 (insert " else {\n")
2585 (js2-print-body else-part (1+ i))
2586 (insert pad "}\n")))))
2587
2588 (defstruct (js2-try-node
2589 (:include js2-node)
2590 (:constructor nil)
2591 (:constructor make-js2-try-node (&key (type js2-TRY)
2592 (pos js2-ts-cursor)
2593 len
2594 try-block
2595 catch-clauses
2596 finally-block)))
2597 "AST node for a try-statement."
2598 try-block
2599 catch-clauses ; a Lisp list of `js2-catch-node'
2600 finally-block) ; a `js2-finally-node'
2601
2602 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2603 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2604
2605 (defun js2-visit-try-node (n v)
2606 (js2-visit-ast (js2-try-node-try-block n) v)
2607 (dolist (clause (js2-try-node-catch-clauses n))
2608 (js2-visit-ast clause v))
2609 (js2-visit-ast (js2-try-node-finally-block n) v))
2610
2611 (defun js2-print-try-node (n i)
2612 (let ((pad (js2-make-pad i))
2613 (catches (js2-try-node-catch-clauses n))
2614 (finally (js2-try-node-finally-block n)))
2615 (insert pad "try {\n")
2616 (js2-print-body (js2-try-node-try-block n) (1+ i))
2617 (insert pad "}")
2618 (when catches
2619 (dolist (catch catches)
2620 (js2-print-ast catch i)))
2621 (if finally
2622 (js2-print-ast finally i)
2623 (insert "\n"))))
2624
2625 (defstruct (js2-catch-node
2626 (:include js2-node)
2627 (:constructor nil)
2628 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2629 (pos js2-ts-cursor)
2630 len
2631 param
2632 guard-kwd
2633 guard-expr
2634 block lp
2635 rp)))
2636 "AST node for a catch clause."
2637 param ; destructuring form or simple name node
2638 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2639 guard-expr ; catch condition, a `js2-node'
2640 block ; statements, a `js2-block-node'
2641 lp ; buffer position of left-paren, nil if omitted
2642 rp) ; buffer position of right-paren, nil if omitted
2643
2644 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2645 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2646
2647 (defun js2-visit-catch-node (n v)
2648 (js2-visit-ast (js2-catch-node-param n) v)
2649 (when (js2-catch-node-guard-kwd n)
2650 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2651 (js2-visit-ast (js2-catch-node-block n) v))
2652
2653 (defun js2-print-catch-node (n i)
2654 (let ((pad (js2-make-pad i))
2655 (guard-kwd (js2-catch-node-guard-kwd n))
2656 (guard-expr (js2-catch-node-guard-expr n)))
2657 (insert " catch (")
2658 (js2-print-ast (js2-catch-node-param n) 0)
2659 (when guard-kwd
2660 (insert " if ")
2661 (js2-print-ast guard-expr 0))
2662 (insert ") {\n")
2663 (js2-print-body (js2-catch-node-block n) (1+ i))
2664 (insert pad "}")))
2665
2666 (defstruct (js2-finally-node
2667 (:include js2-node)
2668 (:constructor nil)
2669 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2670 (pos js2-ts-cursor)
2671 len body)))
2672 "AST node for a finally clause."
2673 body) ; a `js2-node', often but not always a block node
2674
2675 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2676 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2677
2678 (defun js2-visit-finally-node (n v)
2679 (js2-visit-ast (js2-finally-node-body n) v))
2680
2681 (defun js2-print-finally-node (n i)
2682 (let ((pad (js2-make-pad i)))
2683 (insert " finally {\n")
2684 (js2-print-body (js2-finally-node-body n) (1+ i))
2685 (insert pad "}\n")))
2686
2687 (defstruct (js2-switch-node
2688 (:include js2-node)
2689 (:constructor nil)
2690 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2691 (pos js2-ts-cursor)
2692 len
2693 discriminant
2694 cases lp
2695 rp)))
2696 "AST node for a switch statement."
2697 discriminant ; a `js2-node' (switch expression)
2698 cases ; a Lisp list of `js2-case-node'
2699 lp ; position of open-paren for discriminant, nil if omitted
2700 rp) ; position of close-paren for discriminant, nil if omitted
2701
2702 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2703 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2704
2705 (defun js2-visit-switch-node (n v)
2706 (js2-visit-ast (js2-switch-node-discriminant n) v)
2707 (dolist (c (js2-switch-node-cases n))
2708 (js2-visit-ast c v)))
2709
2710 (defun js2-print-switch-node (n i)
2711 (let ((pad (js2-make-pad i))
2712 (cases (js2-switch-node-cases n)))
2713 (insert pad "switch (")
2714 (js2-print-ast (js2-switch-node-discriminant n) 0)
2715 (insert ") {\n")
2716 (dolist (case cases)
2717 (js2-print-ast case i))
2718 (insert pad "}\n")))
2719
2720 (defstruct (js2-case-node
2721 (:include js2-block-node)
2722 (:constructor nil)
2723 (:constructor make-js2-case-node (&key (type js2-CASE)
2724 (pos js2-ts-cursor)
2725 len kids expr)))
2726 "AST node for a case clause of a switch statement."
2727 expr) ; the case expression (nil for default)
2728
2729 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2730 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2731
2732 (defun js2-visit-case-node (n v)
2733 (js2-visit-ast (js2-case-node-expr n) v)
2734 (js2-visit-block n v))
2735
2736 (defun js2-print-case-node (n i)
2737 (let ((pad (js2-make-pad i))
2738 (expr (js2-case-node-expr n)))
2739 (insert pad)
2740 (if (null expr)
2741 (insert "default:\n")
2742 (insert "case ")
2743 (js2-print-ast expr 0)
2744 (insert ":\n"))
2745 (dolist (kid (js2-case-node-kids n))
2746 (js2-print-ast kid (1+ i)))))
2747
2748 (defstruct (js2-throw-node
2749 (:include js2-node)
2750 (:constructor nil)
2751 (:constructor make-js2-throw-node (&key (type js2-THROW)
2752 (pos js2-ts-cursor)
2753 len expr)))
2754 "AST node for a throw statement."
2755 expr) ; the expression to throw
2756
2757 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2758 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2759
2760 (defun js2-visit-throw-node (n v)
2761 (js2-visit-ast (js2-throw-node-expr n) v))
2762
2763 (defun js2-print-throw-node (n i)
2764 (insert (js2-make-pad i) "throw ")
2765 (js2-print-ast (js2-throw-node-expr n) 0)
2766 (insert ";\n"))
2767
2768 (defstruct (js2-with-node
2769 (:include js2-node)
2770 (:constructor nil)
2771 (:constructor make-js2-with-node (&key (type js2-WITH)
2772 (pos js2-ts-cursor)
2773 len object
2774 body lp rp)))
2775 "AST node for a with-statement."
2776 object
2777 body
2778 lp ; buffer position of left-paren around object, nil if omitted
2779 rp) ; buffer position of right-paren around object, nil if omitted
2780
2781 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2782 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2783
2784 (defun js2-visit-with-node (n v)
2785 (js2-visit-ast (js2-with-node-object n) v)
2786 (js2-visit-ast (js2-with-node-body n) v))
2787
2788 (defun js2-print-with-node (n i)
2789 (let ((pad (js2-make-pad i)))
2790 (insert pad "with (")
2791 (js2-print-ast (js2-with-node-object n) 0)
2792 (insert ") {\n")
2793 (js2-print-body (js2-with-node-body n) (1+ i))
2794 (insert pad "}\n")))
2795
2796 (defstruct (js2-label-node
2797 (:include js2-node)
2798 (:constructor nil)
2799 (:constructor make-js2-label-node (&key (type js2-LABEL)
2800 (pos js2-ts-cursor)
2801 len name)))
2802 "AST node for a statement label or case label."
2803 name ; a string
2804 loop) ; for validating and code-generating continue-to-label
2805
2806 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2807 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2808
2809 (defun js2-print-label (n i)
2810 (insert (js2-make-pad i)
2811 (js2-label-node-name n)
2812 ":\n"))
2813
2814 (defstruct (js2-labeled-stmt-node
2815 (:include js2-node)
2816 (:constructor nil)
2817 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2818 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2819 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2820 (pos js2-ts-cursor)
2821 len labels stmt)))
2822 "AST node for a statement with one or more labels.
2823 Multiple labels for a statement are collapsed into the labels field."
2824 labels ; Lisp list of `js2-label-node'
2825 stmt) ; the statement these labels are for
2826
2827 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2828 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2829
2830 (defun js2-get-label-by-name (lbl-stmt name)
2831 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2832 Returns nil if no such label is in the list."
2833 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2834 result)
2835 (while (and label-list (not result))
2836 (if (string= (js2-label-node-name (car label-list)) name)
2837 (setq result (car label-list))
2838 (setq label-list (cdr label-list))))
2839 result))
2840
2841 (defun js2-visit-labeled-stmt (n v)
2842 (dolist (label (js2-labeled-stmt-node-labels n))
2843 (js2-visit-ast label v))
2844 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2845
2846 (defun js2-print-labeled-stmt (n i)
2847 (dolist (label (js2-labeled-stmt-node-labels n))
2848 (js2-print-ast label i))
2849 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2850
2851 (defun js2-labeled-stmt-node-contains (node label)
2852 "Return t if NODE contains LABEL in its label set.
2853 NODE is a `js2-labels-node'. LABEL is an identifier."
2854 (loop for nl in (js2-labeled-stmt-node-labels node)
2855 if (string= label (js2-label-node-name nl))
2856 return t
2857 finally return nil))
2858
2859 (defsubst js2-labeled-stmt-node-add-label (node label)
2860 "Add a `js2-label-node' to the label set for this statement."
2861 (setf (js2-labeled-stmt-node-labels node)
2862 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2863
2864 (defstruct (js2-jump-node
2865 (:include js2-node)
2866 (:constructor nil))
2867 "Abstract supertype of break and continue nodes."
2868 label ; `js2-name-node' for location of label identifier, if present
2869 target) ; target js2-labels-node or loop/switch statement
2870
2871 (defun js2-visit-jump-node (n v)
2872 ;; We don't visit the target, since it's a back-link.
2873 (js2-visit-ast (js2-jump-node-label n) v))
2874
2875 (defstruct (js2-break-node
2876 (:include js2-jump-node)
2877 (:constructor nil)
2878 (:constructor make-js2-break-node (&key (type js2-BREAK)
2879 (pos js2-ts-cursor)
2880 len label target)))
2881 "AST node for a break statement.
2882 The label field is a `js2-name-node', possibly nil, for the named label
2883 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2884 is the target of the break - a label node or enclosing loop/switch statement.")
2885
2886 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2887 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2888
2889 (defun js2-print-break-node (n i)
2890 (insert (js2-make-pad i) "break")
2891 (when (js2-break-node-label n)
2892 (insert " ")
2893 (js2-print-ast (js2-break-node-label n) 0))
2894 (insert ";\n"))
2895
2896 (defstruct (js2-continue-node
2897 (:include js2-jump-node)
2898 (:constructor nil)
2899 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2900 (pos js2-ts-cursor)
2901 len label target)))
2902 "AST node for a continue statement.
2903 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2904 It is nil if continue specifies no label. The target field is the jump target:
2905 a `js2-label-node' or the innermost enclosing loop.")
2906
2907 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2908 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2909
2910 (defun js2-print-continue-node (n i)
2911 (insert (js2-make-pad i) "continue")
2912 (when (js2-continue-node-label n)
2913 (insert " ")
2914 (js2-print-ast (js2-continue-node-label n) 0))
2915 (insert ";\n"))
2916
2917 (defstruct (js2-function-node
2918 (:include js2-script-node)
2919 (:constructor nil)
2920 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2921 (pos js2-ts-cursor)
2922 len
2923 (ftype 'FUNCTION)
2924 (form 'FUNCTION_STATEMENT)
2925 (name "")
2926 params rest-p
2927 body
2928 lp rp)))
2929 "AST node for a function declaration.
2930 The `params' field is a Lisp list of nodes. Each node is either a simple
2931 `js2-name-node', or if it's a destructuring-assignment parameter, a
2932 `js2-array-node' or `js2-object-node'."
2933 ftype ; FUNCTION, GETTER or SETTER
2934 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
2935 name ; function name (a `js2-name-node', or nil if anonymous)
2936 params ; a Lisp list of destructuring forms or simple name nodes
2937 rest-p ; if t, the last parameter is rest parameter
2938 body ; a `js2-block-node' or expression node (1.8 only)
2939 lp ; position of arg-list open-paren, or nil if omitted
2940 rp ; position of arg-list close-paren, or nil if omitted
2941 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2942 needs-activation ; t if we need an activation object for this frame
2943 is-generator ; t if this function contains a yield
2944 member-expr) ; nonstandard Ecma extension from Rhino
2945
2946 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2947 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2948
2949 (defun js2-visit-function-node (n v)
2950 (js2-visit-ast (js2-function-node-name n) v)
2951 (dolist (p (js2-function-node-params n))
2952 (js2-visit-ast p v))
2953 (js2-visit-ast (js2-function-node-body n) v))
2954
2955 (defun js2-print-function-node (n i)
2956 (let ((pad (js2-make-pad i))
2957 (getter (js2-node-get-prop n 'GETTER_SETTER))
2958 (name (js2-function-node-name n))
2959 (params (js2-function-node-params n))
2960 (rest-p (js2-function-node-rest-p n))
2961 (body (js2-function-node-body n))
2962 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
2963 (unless getter
2964 (insert pad "function"))
2965 (when name
2966 (insert " ")
2967 (js2-print-ast name 0))
2968 (insert "(")
2969 (loop with len = (length params)
2970 for param in params
2971 for count from 1
2972 do
2973 (when (and rest-p (= count len))
2974 (insert "..."))
2975 (js2-print-ast param 0)
2976 (when (< count len)
2977 (insert ", ")))
2978 (insert ") {")
2979 (unless expr
2980 (insert "\n"))
2981 ;; TODO: fix this to be smarter about indenting, etc.
2982 (js2-print-body body (1+ i))
2983 (insert pad "}")
2984 (unless expr
2985 (insert "\n"))))
2986
2987 (defun js2-function-name (node)
2988 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
2989 (and (js2-function-node-name node)
2990 (js2-name-node-name (js2-function-node-name node))))
2991
2992 ;; Having this be an expression node makes it more flexible.
2993 ;; There are IDE contexts, such as indentation in a for-loop initializer,
2994 ;; that work better if you assume it's an expression. Whenever we have
2995 ;; a standalone var/const declaration, we just wrap with an expr stmt.
2996 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
2997 (defstruct (js2-var-decl-node
2998 (:include js2-node)
2999 (:constructor nil)
3000 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3001 (pos js2-token-beg)
3002 len kids
3003 decl-type)))
3004 "AST node for a variable declaration list (VAR, CONST or LET).
3005 The node bounds differ depending on the declaration type. For VAR or
3006 CONST declarations, the bounds include the var/const keyword. For LET
3007 declarations, the node begins at the position of the first child."
3008 kids ; a Lisp list of `js2-var-init-node' structs.
3009 decl-type) ; js2-VAR, js2-CONST or js2-LET
3010
3011 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3012 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3013
3014 (defun js2-visit-var-decl (n v)
3015 (dolist (kid (js2-var-decl-node-kids n))
3016 (js2-visit-ast kid v)))
3017
3018 (defun js2-print-var-decl (n i)
3019 (let ((pad (js2-make-pad i))
3020 (tt (js2-var-decl-node-decl-type n)))
3021 (insert pad)
3022 (insert (cond
3023 ((= tt js2-VAR) "var ")
3024 ((= tt js2-LET) "let ")
3025 ((= tt js2-CONST) "const ")
3026 (t
3027 (error "malformed var-decl node"))))
3028 (loop with kids = (js2-var-decl-node-kids n)
3029 with len = (length kids)
3030 for kid in kids
3031 for count from 1
3032 do
3033 (js2-print-ast kid 0)
3034 (if (< count len)
3035 (insert ", ")))))
3036
3037 (defstruct (js2-var-init-node
3038 (:include js2-node)
3039 (:constructor nil)
3040 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3041 (pos js2-ts-cursor)
3042 len target
3043 initializer)))
3044 "AST node for a variable declaration.
3045 The type field will be js2-CONST for a const decl."
3046 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3047 initializer) ; initializer expression, a `js2-node'
3048
3049 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3050 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3051
3052 (defun js2-visit-var-init-node (n v)
3053 (js2-visit-ast (js2-var-init-node-target n) v)
3054 (js2-visit-ast (js2-var-init-node-initializer n) v))
3055
3056 (defun js2-print-var-init-node (n i)
3057 (let ((pad (js2-make-pad i))
3058 (name (js2-var-init-node-target n))
3059 (init (js2-var-init-node-initializer n)))
3060 (insert pad)
3061 (js2-print-ast name 0)
3062 (when init
3063 (insert " = ")
3064 (js2-print-ast init 0))))
3065
3066 (defstruct (js2-cond-node
3067 (:include js2-node)
3068 (:constructor nil)
3069 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3070 (pos js2-ts-cursor)
3071 len
3072 test-expr
3073 true-expr
3074 false-expr
3075 q-pos c-pos)))
3076 "AST node for the ternary operator"
3077 test-expr
3078 true-expr
3079 false-expr
3080 q-pos ; buffer position of ?
3081 c-pos) ; buffer position of :
3082
3083 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3084 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3085
3086 (defun js2-visit-cond-node (n v)
3087 (js2-visit-ast (js2-cond-node-test-expr n) v)
3088 (js2-visit-ast (js2-cond-node-true-expr n) v)
3089 (js2-visit-ast (js2-cond-node-false-expr n) v))
3090
3091 (defun js2-print-cond-node (n i)
3092 (let ((pad (js2-make-pad i)))
3093 (insert pad)
3094 (js2-print-ast (js2-cond-node-test-expr n) 0)
3095 (insert " ? ")
3096 (js2-print-ast (js2-cond-node-true-expr n) 0)
3097 (insert " : ")
3098 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3099
3100 (defstruct (js2-infix-node
3101 (:include js2-node)
3102 (:constructor nil)
3103 (:constructor make-js2-infix-node (&key type
3104 (pos js2-ts-cursor)
3105 len op-pos
3106 left right)))
3107 "Represents infix expressions.
3108 Includes assignment ops like `|=', and the comma operator.
3109 The type field inherited from `js2-node' holds the operator."
3110 op-pos ; buffer position where operator begins
3111 left ; any `js2-node'
3112 right) ; any `js2-node'
3113
3114 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3115 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3116
3117 (defun js2-visit-infix-node (n v)
3118 (js2-visit-ast (js2-infix-node-left n) v)
3119 (js2-visit-ast (js2-infix-node-right n) v))
3120
3121 (defconst js2-operator-tokens
3122 (let ((table (make-hash-table :test 'eq))
3123 (tokens
3124 (list (cons js2-IN "in")
3125 (cons js2-TYPEOF "typeof")
3126 (cons js2-INSTANCEOF "instanceof")
3127 (cons js2-DELPROP "delete")
3128 (cons js2-COMMA ",")
3129 (cons js2-COLON ":")
3130 (cons js2-OR "||")
3131 (cons js2-AND "&&")
3132 (cons js2-INC "++")
3133 (cons js2-DEC "--")
3134 (cons js2-BITOR "|")
3135 (cons js2-BITXOR "^")
3136 (cons js2-BITAND "&")
3137 (cons js2-EQ "==")
3138 (cons js2-NE "!=")
3139 (cons js2-LT "<")
3140 (cons js2-LE "<=")
3141 (cons js2-GT ">")
3142 (cons js2-GE ">=")
3143 (cons js2-LSH "<<")
3144 (cons js2-RSH ">>")
3145 (cons js2-URSH ">>>")
3146 (cons js2-ADD "+") ; infix plus
3147 (cons js2-SUB "-") ; infix minus
3148 (cons js2-MUL "*")
3149 (cons js2-DIV "/")
3150 (cons js2-MOD "%")
3151 (cons js2-NOT "!")
3152 (cons js2-BITNOT "~")
3153 (cons js2-POS "+") ; unary plus
3154 (cons js2-NEG "-") ; unary minus
3155 (cons js2-SHEQ "===") ; shallow equality
3156 (cons js2-SHNE "!==") ; shallow inequality
3157 (cons js2-ASSIGN "=")
3158 (cons js2-ASSIGN_BITOR "|=")
3159 (cons js2-ASSIGN_BITXOR "^=")
3160 (cons js2-ASSIGN_BITAND "&=")
3161 (cons js2-ASSIGN_LSH "<<=")
3162 (cons js2-ASSIGN_RSH ">>=")
3163 (cons js2-ASSIGN_URSH ">>>=")
3164 (cons js2-ASSIGN_ADD "+=")
3165 (cons js2-ASSIGN_SUB "-=")
3166 (cons js2-ASSIGN_MUL "*=")
3167 (cons js2-ASSIGN_DIV "/=")
3168 (cons js2-ASSIGN_MOD "%="))))
3169 (loop for (k . v) in tokens do
3170 (puthash k v table))
3171 table))
3172
3173 (defun js2-print-infix-node (n i)
3174 (let* ((tt (js2-node-type n))
3175 (op (gethash tt js2-operator-tokens)))
3176 (unless op
3177 (error "unrecognized infix operator %s" (js2-node-type n)))
3178 (insert (js2-make-pad i))
3179 (js2-print-ast (js2-infix-node-left n) 0)
3180 (unless (= tt js2-COMMA)
3181 (insert " "))
3182 (insert op)
3183 (insert " ")
3184 (js2-print-ast (js2-infix-node-right n) 0)))
3185
3186 (defstruct (js2-assign-node
3187 (:include js2-infix-node)
3188 (:constructor nil)
3189 (:constructor make-js2-assign-node (&key type
3190 (pos js2-ts-cursor)
3191 len op-pos
3192 left right)))
3193 "Represents any assignment.
3194 The type field holds the actual assignment operator.")
3195
3196 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3197 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3198
3199 (defstruct (js2-unary-node
3200 (:include js2-node)
3201 (:constructor nil)
3202 (:constructor make-js2-unary-node (&key type ; required
3203 (pos js2-ts-cursor)
3204 len operand)))
3205 "AST node type for unary operator nodes.
3206 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3207 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3208 property is added if the operator follows the operand."
3209 operand) ; a `js2-node' expression
3210
3211 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3212 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3213
3214 (defun js2-visit-unary-node (n v)
3215 (js2-visit-ast (js2-unary-node-operand n) v))
3216
3217 (defun js2-print-unary-node (n i)
3218 (let* ((tt (js2-node-type n))
3219 (op (gethash tt js2-operator-tokens))
3220 (postfix (js2-node-get-prop n 'postfix)))
3221 (unless op
3222 (error "unrecognized unary operator %s" tt))
3223 (insert (js2-make-pad i))
3224 (unless postfix
3225 (insert op))
3226 (if (or (= tt js2-TYPEOF)
3227 (= tt js2-DELPROP))
3228 (insert " "))
3229 (js2-print-ast (js2-unary-node-operand n) 0)
3230 (when postfix
3231 (insert op))))
3232
3233 (defstruct (js2-let-node
3234 (:include js2-scope)
3235 (:constructor nil)
3236 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3237 (pos js2-token-beg)
3238 len vars body
3239 lp rp)))
3240 "AST node for a let expression or a let statement.
3241 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3242 vars ; a `js2-var-decl-node'
3243 body ; a `js2-node' representing the expression or body block
3244 lp
3245 rp)
3246
3247 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3248 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3249
3250 (defun js2-visit-let-node (n v)
3251 (js2-visit-ast (js2-let-node-vars n) v)
3252 (js2-visit-ast (js2-let-node-body n) v))
3253
3254 (defun js2-print-let-node (n i)
3255 (insert (js2-make-pad i) "let (")
3256 (js2-print-ast (js2-let-node-vars n) 0)
3257 (insert ") ")
3258 (js2-print-ast (js2-let-node-body n) i))
3259
3260 (defstruct (js2-keyword-node
3261 (:include js2-node)
3262 (:constructor nil)
3263 (:constructor make-js2-keyword-node (&key type
3264 (pos js2-token-beg)
3265 (len (- js2-ts-cursor pos)))))
3266 "AST node representing a literal keyword such as `null'.
3267 Used for `null', `this', `true', `false' and `debugger'.
3268 The node type is set to js2-NULL, js2-THIS, etc.")
3269
3270 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3271 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3272
3273 (defun js2-print-keyword-node (n i)
3274 (insert (js2-make-pad i)
3275 (let ((tt (js2-node-type n)))
3276 (cond
3277 ((= tt js2-THIS) "this")
3278 ((= tt js2-NULL) "null")
3279 ((= tt js2-TRUE) "true")
3280 ((= tt js2-FALSE) "false")
3281 ((= tt js2-DEBUGGER) "debugger")
3282 (t (error "Invalid keyword literal type: %d" tt))))))
3283
3284 (defsubst js2-this-node-p (node)
3285 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3286 (eq (js2-node-type node) js2-THIS))
3287
3288 (defstruct (js2-new-node
3289 (:include js2-node)
3290 (:constructor nil)
3291 (:constructor make-js2-new-node (&key (type js2-NEW)
3292 (pos js2-token-beg)
3293 len target
3294 args initializer
3295 lp rp)))
3296 "AST node for new-expression such as new Foo()."
3297 target ; an identifier or reference
3298 args ; a Lisp list of argument nodes
3299 lp ; position of left-paren, nil if omitted
3300 rp ; position of right-paren, nil if omitted
3301 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3302
3303 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3304 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3305
3306 (defun js2-visit-new-node (n v)
3307 (js2-visit-ast (js2-new-node-target n) v)
3308 (dolist (arg (js2-new-node-args n))
3309 (js2-visit-ast arg v))
3310 (js2-visit-ast (js2-new-node-initializer n) v))
3311
3312 (defun js2-print-new-node (n i)
3313 (insert (js2-make-pad i) "new ")
3314 (js2-print-ast (js2-new-node-target n))
3315 (insert "(")
3316 (js2-print-list (js2-new-node-args n))
3317 (insert ")")
3318 (when (js2-new-node-initializer n)
3319 (insert " ")
3320 (js2-print-ast (js2-new-node-initializer n))))
3321
3322 (defstruct (js2-name-node
3323 (:include js2-node)
3324 (:constructor nil)
3325 (:constructor make-js2-name-node (&key (type js2-NAME)
3326 (pos js2-token-beg)
3327 (len (- js2-ts-cursor
3328 js2-token-beg))
3329 (name js2-ts-string))))
3330 "AST node for a JavaScript identifier"
3331 name ; a string
3332 scope) ; a `js2-scope' (optional, used for codegen)
3333
3334 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3335 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3336
3337 (defun js2-print-name-node (n i)
3338 (insert (js2-make-pad i)
3339 (js2-name-node-name n)))
3340
3341 (defsubst js2-name-node-length (node)
3342 "Return identifier length of NODE, a `js2-name-node'.
3343 Returns 0 if NODE is nil or its identifier field is nil."
3344 (if node
3345 (length (js2-name-node-name node))
3346 0))
3347
3348 (defstruct (js2-number-node
3349 (:include js2-node)
3350 (:constructor nil)
3351 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3352 (pos js2-token-beg)
3353 (len (- js2-ts-cursor
3354 js2-token-beg))
3355 (value js2-ts-string)
3356 (num-value js2-ts-number))))
3357 "AST node for a number literal."
3358 value ; the original string, e.g. "6.02e23"
3359 num-value) ; the parsed number value
3360
3361 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3362 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3363
3364 (defun js2-print-number-node (n i)
3365 (insert (js2-make-pad i)
3366 (number-to-string (js2-number-node-num-value n))))
3367
3368 (defstruct (js2-regexp-node
3369 (:include js2-node)
3370 (:constructor nil)
3371 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3372 (pos js2-token-beg)
3373 (len (- js2-ts-cursor
3374 js2-token-beg))
3375 value flags)))
3376 "AST node for a regular expression literal."
3377 value ; the regexp string, without // delimiters
3378 flags) ; a string of flags, e.g. `mi'.
3379
3380 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3381 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3382
3383 (defun js2-print-regexp (n i)
3384 (insert (js2-make-pad i)
3385 "/"
3386 (js2-regexp-node-value n)
3387 "/")
3388 (if (js2-regexp-node-flags n)
3389 (insert (js2-regexp-node-flags n))))
3390
3391 (defstruct (js2-string-node
3392 (:include js2-node)
3393 (:constructor nil)
3394 (:constructor make-js2-string-node (&key (type js2-STRING)
3395 (pos js2-token-beg)
3396 (len (- js2-ts-cursor
3397 js2-token-beg))
3398 (value js2-ts-string))))
3399 "String literal.
3400 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3401 You can tell the quote type by looking at the first character."
3402 value) ; the characters of the string, including the quotes
3403
3404 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3405 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3406
3407 (defun js2-print-string-node (n i)
3408 (insert (js2-make-pad i)
3409 (js2-node-string n)))
3410
3411 (defstruct (js2-array-node
3412 (:include js2-node)
3413 (:constructor nil)
3414 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3415 (pos js2-ts-cursor)
3416 len elems)))
3417 "AST node for an array literal."
3418 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3419
3420 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3421 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3422
3423 (defun js2-visit-array-node (n v)
3424 (dolist (e (js2-array-node-elems n))
3425 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3426
3427 (defun js2-print-array-node (n i)
3428 (insert (js2-make-pad i) "[")
3429 (js2-print-list (js2-array-node-elems n))
3430 (insert "]"))
3431
3432 (defstruct (js2-object-node
3433 (:include js2-node)
3434 (:constructor nil)
3435 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3436 (pos js2-ts-cursor)
3437 len
3438 elems)))
3439 "AST node for an object literal expression.
3440 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3441 The latter represents abbreviation in destructuring expressions."
3442 elems)
3443
3444 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3445 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3446
3447 (defun js2-visit-object-node (n v)
3448 (dolist (e (js2-object-node-elems n))
3449 (js2-visit-ast e v)))
3450
3451 (defun js2-print-object-node (n i)
3452 (insert (js2-make-pad i) "{")
3453 (js2-print-list (js2-object-node-elems n))
3454 (insert "}"))
3455
3456 (defstruct (js2-object-prop-node
3457 (:include js2-infix-node)
3458 (:constructor nil)
3459 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3460 (pos js2-ts-cursor)
3461 len left
3462 right op-pos)))
3463 "AST node for an object literal prop:value entry.
3464 The `left' field is the property: a name node, string node or number node.
3465 The `right' field is a `js2-node' representing the initializer value.")
3466
3467 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3468 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3469
3470 (defun js2-print-object-prop-node (n i)
3471 (insert (js2-make-pad i))
3472 (js2-print-ast (js2-object-prop-node-left n) 0)
3473 (insert ": ")
3474 (js2-print-ast (js2-object-prop-node-right n) 0))
3475
3476 (defstruct (js2-getter-setter-node
3477 (:include js2-infix-node)
3478 (:constructor nil)
3479 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3480 (pos js2-ts-cursor)
3481 len left right)))
3482 "AST node for a getter/setter property in an object literal.
3483 The `left' field is the `js2-name-node' naming the getter/setter prop.
3484 The `right' field is always an anonymous `js2-function-node' with a node
3485 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3486
3487 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3488 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3489
3490 (defun js2-print-getter-setter (n i)
3491 (let ((pad (js2-make-pad i))
3492 (left (js2-getter-setter-node-left n))
3493 (right (js2-getter-setter-node-right n)))
3494 (insert pad)
3495 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3496 (js2-print-ast left 0)
3497 (js2-print-ast right 0)))
3498
3499 (defstruct (js2-prop-get-node
3500 (:include js2-infix-node)
3501 (:constructor nil)
3502 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3503 (pos js2-ts-cursor)
3504 len left right)))
3505 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3506
3507 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3508 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3509
3510 (defun js2-visit-prop-get-node (n v)
3511 (js2-visit-ast (js2-prop-get-node-left n) v)
3512 (js2-visit-ast (js2-prop-get-node-right n) v))
3513
3514 (defun js2-print-prop-get-node (n i)
3515 (insert (js2-make-pad i))
3516 (js2-print-ast (js2-prop-get-node-left n) 0)
3517 (insert ".")
3518 (js2-print-ast (js2-prop-get-node-right n) 0))
3519
3520 (defstruct (js2-elem-get-node
3521 (:include js2-node)
3522 (:constructor nil)
3523 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3524 (pos js2-ts-cursor)
3525 len target element
3526 lb rb)))
3527 "AST node for an array index expression such as foo[bar]."
3528 target ; a `js2-node' - the expression preceding the "."
3529 element ; a `js2-node' - the expression in brackets
3530 lb ; position of left-bracket, nil if omitted
3531 rb) ; position of right-bracket, nil if omitted
3532
3533 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3534 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3535
3536 (defun js2-visit-elem-get-node (n v)
3537 (js2-visit-ast (js2-elem-get-node-target n) v)
3538 (js2-visit-ast (js2-elem-get-node-element n) v))
3539
3540 (defun js2-print-elem-get-node (n i)
3541 (insert (js2-make-pad i))
3542 (js2-print-ast (js2-elem-get-node-target n) 0)
3543 (insert "[")
3544 (js2-print-ast (js2-elem-get-node-element n) 0)
3545 (insert "]"))
3546
3547 (defstruct (js2-call-node
3548 (:include js2-node)
3549 (:constructor nil)
3550 (:constructor make-js2-call-node (&key (type js2-CALL)
3551 (pos js2-ts-cursor)
3552 len target args
3553 lp rp)))
3554 "AST node for a JavaScript function call."
3555 target ; a `js2-node' evaluating to the function to call
3556 args ; a Lisp list of `js2-node' arguments
3557 lp ; position of open-paren, or nil if missing
3558 rp) ; position of close-paren, or nil if missing
3559
3560 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3561 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3562
3563 (defun js2-visit-call-node (n v)
3564 (js2-visit-ast (js2-call-node-target n) v)
3565 (dolist (arg (js2-call-node-args n))
3566 (js2-visit-ast arg v)))
3567
3568 (defun js2-print-call-node (n i)
3569 (insert (js2-make-pad i))
3570 (js2-print-ast (js2-call-node-target n) 0)
3571 (insert "(")
3572 (js2-print-list (js2-call-node-args n))
3573 (insert ")"))
3574
3575 (defstruct (js2-yield-node
3576 (:include js2-node)
3577 (:constructor nil)
3578 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3579 (pos js2-ts-cursor)
3580 len value)))
3581 "AST node for yield statement or expression."
3582 value) ; optional: value to be yielded
3583
3584 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3585 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3586
3587 (defun js2-visit-yield-node (n v)
3588 (js2-visit-ast (js2-yield-node-value n) v))
3589
3590 (defun js2-print-yield-node (n i)
3591 (insert (js2-make-pad i))
3592 (insert "yield")
3593 (when (js2-yield-node-value n)
3594 (insert " ")
3595 (js2-print-ast (js2-yield-node-value n) 0)))
3596
3597 (defstruct (js2-paren-node
3598 (:include js2-node)
3599 (:constructor nil)
3600 (:constructor make-js2-paren-node (&key (type js2-LP)
3601 (pos js2-ts-cursor)
3602 len expr)))
3603 "AST node for a parenthesized expression.
3604 In particular, used when the parens are syntactically optional,
3605 as opposed to required parens such as those enclosing an if-conditional."
3606 expr) ; `js2-node'
3607
3608 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3609 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3610
3611 (defun js2-visit-paren-node (n v)
3612 (js2-visit-ast (js2-paren-node-expr n) v))
3613
3614 (defun js2-print-paren-node (n i)
3615 (insert (js2-make-pad i))
3616 (insert "(")
3617 (js2-print-ast (js2-paren-node-expr n) 0)
3618 (insert ")"))
3619
3620 (defstruct (js2-array-comp-node
3621 (:include js2-scope)
3622 (:constructor nil)
3623 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3624 (pos js2-ts-cursor)
3625 len result
3626 loops filter
3627 if-pos lp rp)))
3628 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3629 result ; result expression (just after left-bracket)
3630 loops ; a Lisp list of `js2-array-comp-loop-node'
3631 filter ; guard/filter expression
3632 if-pos ; buffer pos of 'if' keyword, if present, else nil
3633 lp ; buffer position of if-guard left-paren, or nil if not present
3634 rp) ; buffer position of if-guard right-paren, or nil if not present
3635
3636 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3637 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3638
3639 (defun js2-visit-array-comp-node (n v)
3640 (js2-visit-ast (js2-array-comp-node-result n) v)
3641 (dolist (l (js2-array-comp-node-loops n))
3642 (js2-visit-ast l v))
3643 (js2-visit-ast (js2-array-comp-node-filter n) v))
3644
3645 (defun js2-print-array-comp-node (n i)
3646 (let ((pad (js2-make-pad i))
3647 (result (js2-array-comp-node-result n))
3648 (loops (js2-array-comp-node-loops n))
3649 (filter (js2-array-comp-node-filter n)))
3650 (insert pad "[")
3651 (js2-print-ast result 0)
3652 (dolist (l loops)
3653 (insert " ")
3654 (js2-print-ast l 0))
3655 (when filter
3656 (insert " if (")
3657 (js2-print-ast filter 0)
3658 (insert ")"))
3659 (insert "]")))
3660
3661 (defstruct (js2-array-comp-loop-node
3662 (:include js2-for-in-node)
3663 (:constructor nil)
3664 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3665 (pos js2-ts-cursor)
3666 len iterator
3667 object in-pos
3668 foreach-p
3669 each-pos
3670 forof-p
3671 lp rp)))
3672 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3673
3674 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3675 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3676
3677 (defun js2-visit-array-comp-loop (n v)
3678 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3679 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3680
3681 (defun js2-print-array-comp-loop (n i)
3682 (insert "for ")
3683 (when (js2-array-comp-loop-node-foreach-p n) (insert "each "))
3684 (insert "(")
3685 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3686 (if (js2-array-comp-loop-node-forof-p n)
3687 (insert " of ")
3688 (insert " in "))
3689 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3690 (insert ")"))
3691
3692 (defstruct (js2-empty-expr-node
3693 (:include js2-node)
3694 (:constructor nil)
3695 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3696 (pos js2-token-beg)
3697 len)))
3698 "AST node for an empty expression.")
3699
3700 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3701 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3702
3703 (defstruct (js2-xml-node
3704 (:include js2-block-node)
3705 (:constructor nil)
3706 (:constructor make-js2-xml-node (&key (type js2-XML)
3707 (pos js2-token-beg)
3708 len kids)))
3709 "AST node for initial parse of E4X literals.
3710 The kids field is a list of XML fragments, each a `js2-string-node' or
3711 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3712
3713 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3714 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3715
3716 (defun js2-print-xml-node (n i)
3717 (dolist (kid (js2-xml-node-kids n))
3718 (js2-print-ast kid i)))
3719
3720 (defstruct (js2-xml-js-expr-node
3721 (:include js2-xml-node)
3722 (:constructor nil)
3723 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3724 (pos js2-ts-cursor)
3725 len expr)))
3726 "AST node for an embedded JavaScript {expression} in an E4X literal.
3727 The start and end fields correspond to the curly-braces."
3728 expr) ; a `js2-expr-node' of some sort
3729
3730 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3731 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3732
3733 (defun js2-visit-xml-js-expr (n v)
3734 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3735
3736 (defun js2-print-xml-js-expr (n i)
3737 (insert (js2-make-pad i))
3738 (insert "{")
3739 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3740 (insert "}"))
3741
3742 (defstruct (js2-xml-dot-query-node
3743 (:include js2-infix-node)
3744 (:constructor nil)
3745 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3746 (pos js2-ts-cursor)
3747 op-pos len left
3748 right rp)))
3749 "AST node for an E4X foo.(bar) filter expression.
3750 Note that the left-paren is automatically the character immediately
3751 following the dot (.) in the operator. No whitespace is permitted
3752 between the dot and the lp by the scanner."
3753 rp)
3754
3755 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3756 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3757
3758 (defun js2-print-xml-dot-query (n i)
3759 (insert (js2-make-pad i))
3760 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3761 (insert ".(")
3762 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3763 (insert ")"))
3764
3765 (defstruct (js2-xml-ref-node
3766 (:include js2-node)
3767 (:constructor nil)) ; abstract
3768 "Base type for E4X XML attribute-access or property-get expressions.
3769 Such expressions can take a variety of forms. The general syntax has
3770 three parts:
3771
3772 - (optional) an @ (specifying an attribute access)
3773 - (optional) a namespace (a `js2-name-node') and double-colon
3774 - (required) either a `js2-name-node' or a bracketed [expression]
3775
3776 The property-name expressions (examples: ns::name, @name) are
3777 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3778 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3779
3780 This node type (or more specifically, its subclasses) will sometimes
3781 be the right-hand child of a `js2-prop-get-node' or a
3782 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3783 The `js2-xml-ref-node' may also be a standalone primary expression with
3784 no explicit target, which is valid in certain expression contexts such as
3785
3786 company..employee.(@id < 100)
3787
3788 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3789 expression whose parent is a `js2-xml-dot-query-node'."
3790 namespace
3791 at-pos
3792 colon-pos)
3793
3794 (defsubst js2-xml-ref-node-attr-access-p (node)
3795 "Return non-nil if this expression began with an @-token."
3796 (and (numberp (js2-xml-ref-node-at-pos node))
3797 (plusp (js2-xml-ref-node-at-pos node))))
3798
3799 (defstruct (js2-xml-prop-ref-node
3800 (:include js2-xml-ref-node)
3801 (:constructor nil)
3802 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3803 (pos js2-token-beg)
3804 len propname
3805 namespace at-pos
3806 colon-pos)))
3807 "AST node for an E4X XML [expr] property-ref expression.
3808 The JavaScript syntax is an optional @, an optional ns::, and a name.
3809
3810 [ '@' ] [ name '::' ] name
3811
3812 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3813 @ns::*, @*::attr, @*::*, and @*.
3814
3815 The node starts at the @ token, if present. Otherwise it starts at the
3816 namespace name. The node bounds extend through the closing right-bracket,
3817 or if it is missing due to a syntax error, through the end of the index
3818 expression."
3819 propname)
3820
3821 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3822 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3823
3824 (defun js2-visit-xml-prop-ref-node (n v)
3825 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3826 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3827
3828 (defun js2-print-xml-prop-ref-node (n i)
3829 (insert (js2-make-pad i))
3830 (if (js2-xml-ref-node-attr-access-p n)
3831 (insert "@"))
3832 (when (js2-xml-prop-ref-node-namespace n)
3833 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3834 (insert "::"))
3835 (if (js2-xml-prop-ref-node-propname n)
3836 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3837
3838 (defstruct (js2-xml-elem-ref-node
3839 (:include js2-xml-ref-node)
3840 (:constructor nil)
3841 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3842 (pos js2-token-beg)
3843 len expr lb rb
3844 namespace at-pos
3845 colon-pos)))
3846 "AST node for an E4X XML [expr] member-ref expression.
3847 Syntax:
3848
3849 [ '@' ] [ name '::' ] '[' expr ']'
3850
3851 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3852
3853 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3854 is not a legal E4X XML element-ref expression, since it's already used
3855 for standard JavaScript element-get array indexing. Hence, a
3856 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3857 non-nil namespace node, or both.
3858
3859 The node starts at the @ token, if present. Otherwise it starts
3860 at the namespace name. The node bounds extend through the closing
3861 right-bracket, or if it is missing due to a syntax error, through the
3862 end of the index expression."
3863 expr ; the bracketed index expression
3864 lb
3865 rb)
3866
3867 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3868 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3869
3870 (defun js2-visit-xml-elem-ref-node (n v)
3871 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3872 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3873
3874 (defun js2-print-xml-elem-ref-node (n i)
3875 (insert (js2-make-pad i))
3876 (if (js2-xml-ref-node-attr-access-p n)
3877 (insert "@"))
3878 (when (js2-xml-elem-ref-node-namespace n)
3879 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3880 (insert "::"))
3881 (insert "[")
3882 (if (js2-xml-elem-ref-node-expr n)
3883 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3884 (insert "]"))
3885
3886 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3887
3888 (defstruct (js2-xml-start-tag-node
3889 (:include js2-xml-node)
3890 (:constructor nil)
3891 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3892 (pos js2-ts-cursor)
3893 len name attrs kids
3894 empty-p)))
3895 "AST node for an XML start-tag. Not currently used.
3896 The `kids' field is a Lisp list of child content nodes."
3897 name ; a `js2-xml-name-node'
3898 attrs ; a Lisp list of `js2-xml-attr-node'
3899 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3900
3901 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3902 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3903
3904 (defun js2-visit-xml-start-tag (n v)
3905 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3906 (dolist (attr (js2-xml-start-tag-node-attrs n))
3907 (js2-visit-ast attr v))
3908 (js2-visit-block n v))
3909
3910 (defun js2-print-xml-start-tag (n i)
3911 (insert (js2-make-pad i) "<")
3912 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3913 (when (js2-xml-start-tag-node-attrs n)
3914 (insert " ")
3915 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3916 (insert ">"))
3917
3918 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3919 ;; and add the end-tag to the kids list of the parent as well.
3920 (defstruct (js2-xml-end-tag-node
3921 (:include js2-xml-node)
3922 (:constructor nil)
3923 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
3924 (pos js2-ts-cursor)
3925 len name)))
3926 "AST node for an XML end-tag. Not currently used."
3927 name) ; a `js2-xml-name-node'
3928
3929 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
3930 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
3931
3932 (defun js2-visit-xml-end-tag (n v)
3933 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
3934
3935 (defun js2-print-xml-end-tag (n i)
3936 (insert (js2-make-pad i))
3937 (insert "</")
3938 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
3939 (insert ">"))
3940
3941 (defstruct (js2-xml-name-node
3942 (:include js2-xml-node)
3943 (:constructor nil)
3944 (:constructor make-js2-xml-name-node (&key (type js2-XML)
3945 (pos js2-ts-cursor)
3946 len namespace kids)))
3947 "AST node for an E4X XML name. Not currently used.
3948 Any XML name can be qualified with a namespace, hence the namespace field.
3949 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
3950 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
3951 For a simple name, the kids list has exactly one node, a `js2-name-node'."
3952 namespace) ; a `js2-string-node'
3953
3954 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
3955 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
3956
3957 (defun js2-visit-xml-name-node (n v)
3958 (js2-visit-ast (js2-xml-name-node-namespace n) v))
3959
3960 (defun js2-print-xml-name-node (n i)
3961 (insert (js2-make-pad i))
3962 (when (js2-xml-name-node-namespace n)
3963 (js2-print-ast (js2-xml-name-node-namespace n) 0)
3964 (insert "::"))
3965 (dolist (kid (js2-xml-name-node-kids n))
3966 (js2-print-ast kid 0)))
3967
3968 (defstruct (js2-xml-pi-node
3969 (:include js2-xml-node)
3970 (:constructor nil)
3971 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
3972 (pos js2-ts-cursor)
3973 len name attrs)))
3974 "AST node for an E4X XML processing instruction. Not currently used."
3975 name ; a `js2-xml-name-node'
3976 attrs) ; a list of `js2-xml-attr-node'
3977
3978 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
3979 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
3980
3981 (defun js2-visit-xml-pi-node (n v)
3982 (js2-visit-ast (js2-xml-pi-node-name n) v)
3983 (dolist (attr (js2-xml-pi-node-attrs n))
3984 (js2-visit-ast attr v)))
3985
3986 (defun js2-print-xml-pi-node (n i)
3987 (insert (js2-make-pad i) "<?")
3988 (js2-print-ast (js2-xml-pi-node-name n))
3989 (when (js2-xml-pi-node-attrs n)
3990 (insert " ")
3991 (js2-print-list (js2-xml-pi-node-attrs n)))
3992 (insert "?>"))
3993
3994 (defstruct (js2-xml-cdata-node
3995 (:include js2-xml-node)
3996 (:constructor nil)
3997 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
3998 (pos js2-ts-cursor)
3999 len content)))
4000 "AST node for a CDATA escape section. Not currently used."
4001 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4002
4003 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4004 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4005
4006 (defun js2-visit-xml-cdata-node (n v)
4007 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4008
4009 (defun js2-print-xml-cdata-node (n i)
4010 (insert (js2-make-pad i))
4011 (js2-print-ast (js2-xml-cdata-node-content n)))
4012
4013 (defstruct (js2-xml-attr-node
4014 (:include js2-xml-node)
4015 (:constructor nil)
4016 (:constructor make-js2-attr-node (&key (type js2-XML)
4017 (pos js2-ts-cursor)
4018 len name value
4019 eq-pos quote-type)))
4020 "AST node representing a foo='bar' XML attribute value. Not yet used."
4021 name ; a `js2-xml-name-node'
4022 value ; a `js2-xml-name-node'
4023 eq-pos ; buffer position of "=" sign
4024 quote-type) ; 'single or 'double
4025
4026 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4027 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4028
4029 (defun js2-visit-xml-attr-node (n v)
4030 (js2-visit-ast (js2-xml-attr-node-name n) v)
4031 (js2-visit-ast (js2-xml-attr-node-value n) v))
4032
4033 (defun js2-print-xml-attr-node (n i)
4034 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4035 "'"
4036 "\"")))
4037 (insert (js2-make-pad i))
4038 (js2-print-ast (js2-xml-attr-node-name n) 0)
4039 (insert "=" quote)
4040 (js2-print-ast (js2-xml-attr-node-value n) 0)
4041 (insert quote)))
4042
4043 (defstruct (js2-xml-text-node
4044 (:include js2-xml-node)
4045 (:constructor nil)
4046 (:constructor make-js2-text-node (&key (type js2-XML)
4047 (pos js2-ts-cursor)
4048 len content)))
4049 "AST node for an E4X XML text node. Not currently used."
4050 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4051
4052 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4053 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4054
4055 (defun js2-visit-xml-text-node (n v)
4056 (js2-visit-ast (js2-xml-text-node-content n) v))
4057
4058 (defun js2-print-xml-text-node (n i)
4059 (insert (js2-make-pad i))
4060 (dolist (kid (js2-xml-text-node-content n))
4061 (js2-print-ast kid)))
4062
4063 (defstruct (js2-xml-comment-node
4064 (:include js2-xml-node)
4065 (:constructor nil)
4066 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4067 (pos js2-ts-cursor)
4068 len)))
4069 "AST node for E4X XML comment. Not currently used.")
4070
4071 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4072 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4073
4074 (defun js2-print-xml-comment (n i)
4075 (insert (js2-make-pad i)
4076 (js2-node-string n)))
4077
4078 ;;; Node utilities
4079
4080 (defsubst js2-node-line (n)
4081 "Fetch the source line number at the start of node N.
4082 This is O(n) in the length of the source buffer; use prudently."
4083 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4084
4085 (defsubst js2-block-node-kid (n i)
4086 "Return child I of node N, or nil if there aren't that many."
4087 (nth i (js2-block-node-kids n)))
4088
4089 (defsubst js2-block-node-first (n)
4090 "Return first child of block node N, or nil if there is none."
4091 (first (js2-block-node-kids n)))
4092
4093 (defun js2-node-root (n)
4094 "Return the root of the AST containing N.
4095 If N has no parent pointer, returns N."
4096 (let ((parent (js2-node-parent n)))
4097 (if parent
4098 (js2-node-root parent)
4099 n)))
4100
4101 (defun js2-node-position-in-parent (node &optional parent)
4102 "Return the position of NODE in parent's block-kids list.
4103 PARENT can be supplied if known. Positioned returned is zero-indexed.
4104 Returns 0 if NODE is not a child of a block statement, or if NODE
4105 is not a statement node."
4106 (let ((p (or parent (js2-node-parent node)))
4107 (i 0))
4108 (if (not (js2-block-node-p p))
4109 i
4110 (or (js2-position node (js2-block-node-kids p))
4111 0))))
4112
4113 (defsubst js2-node-short-name (n)
4114 "Return the short name of node N as a string, e.g. `js2-if-node'."
4115 (substring (symbol-name (aref n 0))
4116 (length "cl-struct-")))
4117
4118 (defun js2-node-child-list (node)
4119 "Return the child list for NODE, a Lisp list of nodes.
4120 Works for block nodes, array nodes, obj literals, funarg lists,
4121 var decls and try nodes (for catch clauses). Note that you should call
4122 `js2-block-node-kids' on the function body for the body statements.
4123 Returns nil for zero-length child lists or unsupported nodes."
4124 (cond
4125 ((js2-function-node-p node)
4126 (js2-function-node-params node))
4127 ((js2-block-node-p node)
4128 (js2-block-node-kids node))
4129 ((js2-try-node-p node)
4130 (js2-try-node-catch-clauses node))
4131 ((js2-array-node-p node)
4132 (js2-array-node-elems node))
4133 ((js2-object-node-p node)
4134 (js2-object-node-elems node))
4135 ((js2-call-node-p node)
4136 (js2-call-node-args node))
4137 ((js2-new-node-p node)
4138 (js2-new-node-args node))
4139 ((js2-var-decl-node-p node)
4140 (js2-var-decl-node-kids node))
4141 (t
4142 nil)))
4143
4144 (defun js2-node-set-child-list (node kids)
4145 "Set the child list for NODE to KIDS."
4146 (cond
4147 ((js2-function-node-p node)
4148 (setf (js2-function-node-params node) kids))
4149 ((js2-block-node-p node)
4150 (setf (js2-block-node-kids node) kids))
4151 ((js2-try-node-p node)
4152 (setf (js2-try-node-catch-clauses node) kids))
4153 ((js2-array-node-p node)
4154 (setf (js2-array-node-elems node) kids))
4155 ((js2-object-node-p node)
4156 (setf (js2-object-node-elems node) kids))
4157 ((js2-call-node-p node)
4158 (setf (js2-call-node-args node) kids))
4159 ((js2-new-node-p node)
4160 (setf (js2-new-node-args node) kids))
4161 ((js2-var-decl-node-p node)
4162 (setf (js2-var-decl-node-kids node) kids))
4163 (t
4164 (error "Unsupported node type: %s" (js2-node-short-name node))))
4165 kids)
4166
4167 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4168 (defconst js2-paren-expr-nodes
4169 '(cl-struct-js2-array-comp-loop-node
4170 cl-struct-js2-array-comp-node
4171 cl-struct-js2-call-node
4172 cl-struct-js2-catch-node
4173 cl-struct-js2-do-node
4174 cl-struct-js2-elem-get-node
4175 cl-struct-js2-for-in-node
4176 cl-struct-js2-for-node
4177 cl-struct-js2-function-node
4178 cl-struct-js2-if-node
4179 cl-struct-js2-let-node
4180 cl-struct-js2-new-node
4181 cl-struct-js2-paren-node
4182 cl-struct-js2-switch-node
4183 cl-struct-js2-while-node
4184 cl-struct-js2-with-node
4185 cl-struct-js2-xml-dot-query-node)
4186 "Node types that can have a parenthesized child expression.
4187 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4188
4189 (defsubst js2-paren-expr-node-p (node)
4190 "Return t for nodes that typically have a parenthesized child expression.
4191 Useful for computing the indentation anchors for arg-lists and conditions.
4192 Note that it may return a false positive, for instance when NODE is
4193 a `js2-new-node' and there are no arguments or parentheses."
4194 (memq (aref node 0) js2-paren-expr-nodes))
4195
4196 ;; Fake polymorphism... yech.
4197 (defun js2-node-lp (node)
4198 "Return relative left-paren position for NODE, if applicable.
4199 For `js2-elem-get-node' structs, returns left-bracket position.
4200 Note that the position may be nil in the case of a parse error."
4201 (cond
4202 ((js2-elem-get-node-p node)
4203 (js2-elem-get-node-lb node))
4204 ((js2-loop-node-p node)
4205 (js2-loop-node-lp node))
4206 ((js2-function-node-p node)
4207 (js2-function-node-lp node))
4208 ((js2-if-node-p node)
4209 (js2-if-node-lp node))
4210 ((js2-new-node-p node)
4211 (js2-new-node-lp node))
4212 ((js2-call-node-p node)
4213 (js2-call-node-lp node))
4214 ((js2-paren-node-p node)
4215 (js2-node-pos node))
4216 ((js2-switch-node-p node)
4217 (js2-switch-node-lp node))
4218 ((js2-catch-node-p node)
4219 (js2-catch-node-lp node))
4220 ((js2-let-node-p node)
4221 (js2-let-node-lp node))
4222 ((js2-array-comp-node-p node)
4223 (js2-array-comp-node-lp node))
4224 ((js2-with-node-p node)
4225 (js2-with-node-lp node))
4226 ((js2-xml-dot-query-node-p node)
4227 (1+ (js2-infix-node-op-pos node)))
4228 (t
4229 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4230
4231 ;; Fake polymorphism... blech.
4232 (defun js2-node-rp (node)
4233 "Return relative right-paren position for NODE, if applicable.
4234 For `js2-elem-get-node' structs, returns right-bracket position.
4235 Note that the position may be nil in the case of a parse error."
4236 (cond
4237 ((js2-elem-get-node-p node)
4238 (js2-elem-get-node-rb node))
4239 ((js2-loop-node-p node)
4240 (js2-loop-node-rp node))
4241 ((js2-function-node-p node)
4242 (js2-function-node-rp node))
4243 ((js2-if-node-p node)
4244 (js2-if-node-rp node))
4245 ((js2-new-node-p node)
4246 (js2-new-node-rp node))
4247 ((js2-call-node-p node)
4248 (js2-call-node-rp node))
4249 ((js2-paren-node-p node)
4250 (+ (js2-node-pos node) (js2-node-len node)))
4251 ((js2-switch-node-p node)
4252 (js2-switch-node-rp node))
4253 ((js2-catch-node-p node)
4254 (js2-catch-node-rp node))
4255 ((js2-let-node-p node)
4256 (js2-let-node-rp node))
4257 ((js2-array-comp-node-p node)
4258 (js2-array-comp-node-rp node))
4259 ((js2-with-node-p node)
4260 (js2-with-node-rp node))
4261 ((js2-xml-dot-query-node-p node)
4262 (1+ (js2-xml-dot-query-node-rp node)))
4263 (t
4264 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4265
4266 (defsubst js2-node-first-child (node)
4267 "Return the first element of `js2-node-child-list' for NODE."
4268 (car (js2-node-child-list node)))
4269
4270 (defsubst js2-node-last-child (node)
4271 "Return the last element of `js2-node-last-child' for NODE."
4272 (car (last (js2-node-child-list node))))
4273
4274 (defun js2-node-prev-sibling (node)
4275 "Return the previous statement in parent.
4276 Works for parents supported by `js2-node-child-list'.
4277 Returns nil if NODE is not in the parent, or PARENT is
4278 not a supported node, or if NODE is the first child."
4279 (let* ((p (js2-node-parent node))
4280 (kids (js2-node-child-list p))
4281 (sib (car kids)))
4282 (while (and kids
4283 (not (eq node (cadr kids))))
4284 (setq kids (cdr kids)
4285 sib (car kids)))
4286 sib))
4287
4288 (defun js2-node-next-sibling (node)
4289 "Return the next statement in parent block.
4290 Returns nil if NODE is not in the block, or PARENT is not
4291 a block node, or if NODE is the last statement."
4292 (let* ((p (js2-node-parent node))
4293 (kids (js2-node-child-list p)))
4294 (while (and kids
4295 (not (eq node (car kids))))
4296 (setq kids (cdr kids)))
4297 (cadr kids)))
4298
4299 (defun js2-node-find-child-before (pos parent &optional after)
4300 "Find the last child that starts before POS in parent.
4301 If AFTER is non-nil, returns first child starting after POS.
4302 POS is an absolute buffer position. PARENT is any node
4303 supported by `js2-node-child-list'.
4304 Returns nil if no applicable child is found."
4305 (let ((kids (if (js2-function-node-p parent)
4306 (js2-block-node-kids (js2-function-node-body parent))
4307 (js2-node-child-list parent)))
4308 (beg (if (js2-function-node-p parent)
4309 (js2-node-abs-pos (js2-function-node-body parent))
4310 (js2-node-abs-pos parent)))
4311 kid result fn
4312 (continue t))
4313 (setq fn (if after '>= '<))
4314 (while (and kids continue)
4315 (setq kid (car kids))
4316 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4317 (setq result kid
4318 continue (if after nil t))
4319 (setq continue (if after t nil)))
4320 (setq kids (cdr kids)))
4321 result))
4322
4323 (defun js2-node-find-child-after (pos parent)
4324 "Find first child that starts after POS in parent.
4325 POS is an absolute buffer position. PARENT is any node
4326 supported by `js2-node-child-list'.
4327 Returns nil if no applicable child is found."
4328 (js2-node-find-child-before pos parent 'after))
4329
4330 (defun js2-node-replace-child (pos parent new-node)
4331 "Replace node at index POS in PARENT with NEW-NODE.
4332 Only works for parents supported by `js2-node-child-list'."
4333 (let ((kids (js2-node-child-list parent))
4334 (i 0))
4335 (while (< i pos)
4336 (setq kids (cdr kids)
4337 i (1+ i)))
4338 (setcar kids new-node)
4339 (js2-node-add-children parent new-node)))
4340
4341 (defun js2-node-buffer (n)
4342 "Return the buffer associated with AST N.
4343 Returns nil if the buffer is not set as a property on the root
4344 node, or if parent links were not recorded during parsing."
4345 (let ((root (js2-node-root n)))
4346 (and root
4347 (js2-ast-root-p root)
4348 (js2-ast-root-buffer root))))
4349
4350 (defun js2-block-node-push (n kid)
4351 "Push js2-node KID onto the end of js2-block-node N's child list.
4352 KID is always added to the -end- of the kids list.
4353 Function also calls `js2-node-add-children' to add the parent link."
4354 (let ((kids (js2-node-child-list n)))
4355 (if kids
4356 (setcdr kids (nconc (cdr kids) (list kid)))
4357 (js2-node-set-child-list n (list kid)))
4358 (js2-node-add-children n kid)))
4359
4360 (defun js2-node-string (node)
4361 (with-current-buffer (or (js2-node-buffer node)
4362 (error "No buffer available for node %s" node))
4363 (let ((pos (js2-node-abs-pos node)))
4364 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4365
4366 ;; Container for storing the node we're looking for in a traversal.
4367 (js2-deflocal js2-discovered-node nil)
4368
4369 ;; Keep track of absolute node position during traversals.
4370 (js2-deflocal js2-visitor-offset nil)
4371
4372 (js2-deflocal js2-node-search-point nil)
4373
4374 (when js2-mode-dev-mode-p
4375 (defun js2-find-node-at-point ()
4376 (interactive)
4377 (let ((node (js2-node-at-point)))
4378 (message "%s" (or node "No node found at point"))))
4379 (defun js2-node-name-at-point ()
4380 (interactive)
4381 (let ((node (js2-node-at-point)))
4382 (message "%s" (if node
4383 (js2-node-short-name node)
4384 "No node found at point.")))))
4385
4386 (defun js2-node-at-point (&optional pos skip-comments)
4387 "Return AST node at POS, a buffer position, defaulting to current point.
4388 The `js2-mode-ast' variable must be set to the current parse tree.
4389 Signals an error if the AST (`js2-mode-ast') is nil.
4390 Always returns a node - if it can't find one, it returns the root.
4391 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4392 (let ((ast js2-mode-ast)
4393 result)
4394 (unless ast
4395 (error "No JavaScript AST available"))
4396 ;; Look through comments first, since they may be inside nodes that
4397 ;; would otherwise report a match.
4398 (setq pos (or pos (point))
4399 result (if (> pos (js2-node-abs-end ast))
4400 ast
4401 (if (not skip-comments)
4402 (js2-comment-at-point pos))))
4403 (unless result
4404 (setq js2-discovered-node nil
4405 js2-visitor-offset 0
4406 js2-node-search-point pos)
4407 (unwind-protect
4408 (catch 'js2-visit-done
4409 (js2-visit-ast ast #'js2-node-at-point-visitor))
4410 (setq js2-visitor-offset nil
4411 js2-node-search-point nil))
4412 (setq result js2-discovered-node))
4413 ;; may have found a comment beyond end of last child node,
4414 ;; since visiting the ast-root looks at the comment-list last.
4415 (if (and skip-comments
4416 (js2-comment-node-p result))
4417 (setq result nil))
4418 (or result js2-mode-ast)))
4419
4420 (defun js2-node-at-point-visitor (node end-p)
4421 (let ((rel-pos (js2-node-pos node))
4422 abs-pos
4423 abs-end
4424 (point js2-node-search-point))
4425 (cond
4426 (end-p
4427 ;; this evaluates to a non-nil return value, even if it's zero
4428 (decf js2-visitor-offset rel-pos))
4429 ;; we already looked for comments before visiting, and don't want them now
4430 ((js2-comment-node-p node)
4431 nil)
4432 (t
4433 (setq abs-pos (incf js2-visitor-offset rel-pos)
4434 ;; we only want to use the node if the point is before
4435 ;; the last character position in the node, so we decrement
4436 ;; the absolute end by 1.
4437 abs-end (+ abs-pos (js2-node-len node) -1))
4438 (cond
4439 ;; If this node starts after search-point, stop the search.
4440 ((> abs-pos point)
4441 (throw 'js2-visit-done nil))
4442 ;; If this node ends before the search-point, don't check kids.
4443 ((> point abs-end)
4444 nil)
4445 (t
4446 ;; Otherwise point is within this node, possibly in a child.
4447 (setq js2-discovered-node node)
4448 t)))))) ; keep processing kids to look for more specific match
4449
4450 (defsubst js2-block-comment-p (node)
4451 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4452 (and (js2-comment-node-p node)
4453 (memq (js2-comment-node-format node) '(jsdoc block))))
4454
4455 ;; TODO: put the comments in a vector and binary-search them instead
4456 (defun js2-comment-at-point (&optional pos)
4457 "Look through scanned comment nodes for one containing POS.
4458 POS is a buffer position that defaults to current point.
4459 Function returns nil if POS was not in any comment node."
4460 (let ((ast js2-mode-ast)
4461 (x (or pos (point)))
4462 beg end)
4463 (unless ast
4464 (error "No JavaScript AST available"))
4465 (catch 'done
4466 ;; Comments are stored in lexical order.
4467 (dolist (comment (js2-ast-root-comments ast) nil)
4468 (setq beg (js2-node-abs-pos comment)
4469 end (+ beg (js2-node-len comment)))
4470 (if (and (>= x beg)
4471 (<= x end))
4472 (throw 'done comment))))))
4473
4474 (defun js2-mode-find-parent-fn (node)
4475 "Find function enclosing NODE.
4476 Returns nil if NODE is not inside a function."
4477 (setq node (js2-node-parent node))
4478 (while (and node (not (js2-function-node-p node)))
4479 (setq node (js2-node-parent node)))
4480 (and (js2-function-node-p node) node))
4481
4482 (defun js2-mode-find-enclosing-fn (node)
4483 "Find function or root enclosing NODE."
4484 (if (js2-ast-root-p node)
4485 node
4486 (setq node (js2-node-parent node))
4487 (while (not (or (js2-ast-root-p node)
4488 (js2-function-node-p node)))
4489 (setq node (js2-node-parent node)))
4490 node))
4491
4492 (defun js2-mode-find-enclosing-node (beg end)
4493 "Find script or function fully enclosing BEG and END."
4494 (let ((node (js2-node-at-point beg))
4495 pos
4496 (continue t))
4497 (while continue
4498 (if (or (js2-ast-root-p node)
4499 (and (js2-function-node-p node)
4500 (<= (setq pos (js2-node-abs-pos node)) beg)
4501 (>= (+ pos (js2-node-len node)) end)))
4502 (setq continue nil)
4503 (setq node (js2-node-parent node))))
4504 node))
4505
4506 (defun js2-node-parent-script-or-fn (node)
4507 "Find script or function immediately enclosing NODE.
4508 If NODE is the ast-root, returns nil."
4509 (if (js2-ast-root-p node)
4510 nil
4511 (setq node (js2-node-parent node))
4512 (while (and node (not (or (js2-function-node-p node)
4513 (js2-script-node-p node))))
4514 (setq node (js2-node-parent node)))
4515 node))
4516
4517 (defun js2-nested-function-p (node)
4518 "Return t if NODE is a nested function, or is inside a nested function."
4519 (unless (js2-ast-root-p node)
4520 (js2-function-node-p (if (js2-function-node-p node)
4521 (js2-node-parent-script-or-fn node)
4522 (js2-node-parent-script-or-fn
4523 (js2-node-parent-script-or-fn node))))))
4524
4525 (defun js2-mode-shift-kids (kids start offset)
4526 (dolist (kid kids)
4527 (if (> (js2-node-pos kid) start)
4528 (incf (js2-node-pos kid) offset))))
4529
4530 (defun js2-mode-shift-children (parent start offset)
4531 "Update start-positions of all children of PARENT beyond START."
4532 (let ((root (js2-node-root parent)))
4533 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4534 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4535
4536 (defun js2-node-is-descendant (node ancestor)
4537 "Return t if NODE is a descendant of ANCESTOR."
4538 (while (and node
4539 (not (eq node ancestor)))
4540 (setq node (js2-node-parent node)))
4541 node)
4542
4543 ;;; visitor infrastructure
4544
4545 (defun js2-visit-none (node callback)
4546 "Visitor for AST node that have no node children."
4547 nil)
4548
4549 (defun js2-print-none (node indent)
4550 "Visitor for AST node with no printed representation.")
4551
4552 (defun js2-print-body (node indent)
4553 "Print a statement, or a block without braces."
4554 (if (js2-block-node-p node)
4555 (dolist (kid (js2-block-node-kids node))
4556 (js2-print-ast kid indent))
4557 (js2-print-ast node indent)))
4558
4559 (defun js2-print-list (args &optional delimiter)
4560 (loop with len = (length args)
4561 for arg in args
4562 for count from 1
4563 do
4564 (when arg (js2-print-ast arg 0))
4565 (if (< count len)
4566 (insert (or delimiter ", ")))))
4567
4568 (defun js2-print-tree (ast)
4569 "Prints an AST to the current buffer.
4570 Makes `js2-ast-parent-nodes' available to the printer functions."
4571 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4572 (js2-print-ast ast)))
4573
4574 (defun js2-print-ast (node &optional indent)
4575 "Helper function for printing AST nodes.
4576 Requires `js2-ast-parent-nodes' to be non-nil.
4577 You should use `js2-print-tree' instead of this function."
4578 (let ((printer (get (aref node 0) 'js2-printer))
4579 (i (or indent 0))
4580 (pos (js2-node-abs-pos node)))
4581 ;; TODO: wedge comments in here somewhere
4582 (if printer
4583 (funcall printer node i))))
4584
4585 (defconst js2-side-effecting-tokens
4586 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4587 (dolist (tt (list js2-ASSIGN
4588 js2-ASSIGN_ADD
4589 js2-ASSIGN_BITAND
4590 js2-ASSIGN_BITOR
4591 js2-ASSIGN_BITXOR
4592 js2-ASSIGN_DIV
4593 js2-ASSIGN_LSH
4594 js2-ASSIGN_MOD
4595 js2-ASSIGN_MUL
4596 js2-ASSIGN_RSH
4597 js2-ASSIGN_SUB
4598 js2-ASSIGN_URSH
4599 js2-BLOCK
4600 js2-BREAK
4601 js2-CALL
4602 js2-CATCH
4603 js2-CATCH_SCOPE
4604 js2-CONST
4605 js2-CONTINUE
4606 js2-DEBUGGER
4607 js2-DEC
4608 js2-DELPROP
4609 js2-DEL_REF
4610 js2-DO
4611 js2-ELSE
4612 js2-EMPTY
4613 js2-ENTERWITH
4614 js2-EXPORT
4615 js2-EXPR_RESULT
4616 js2-FINALLY
4617 js2-FOR
4618 js2-FUNCTION
4619 js2-GOTO
4620 js2-IF
4621 js2-IFEQ
4622 js2-IFNE
4623 js2-IMPORT
4624 js2-INC
4625 js2-JSR
4626 js2-LABEL
4627 js2-LEAVEWITH
4628 js2-LET
4629 js2-LETEXPR
4630 js2-LOCAL_BLOCK
4631 js2-LOOP
4632 js2-NEW
4633 js2-REF_CALL
4634 js2-RETHROW
4635 js2-RETURN
4636 js2-RETURN_RESULT
4637 js2-SEMI
4638 js2-SETELEM
4639 js2-SETELEM_OP
4640 js2-SETNAME
4641 js2-SETPROP
4642 js2-SETPROP_OP
4643 js2-SETVAR
4644 js2-SET_REF
4645 js2-SET_REF_OP
4646 js2-SWITCH
4647 js2-TARGET
4648 js2-THROW
4649 js2-TRY
4650 js2-VAR
4651 js2-WHILE
4652 js2-WITH
4653 js2-WITHEXPR
4654 js2-YIELD))
4655 (aset tokens tt t))
4656 (if js2-instanceof-has-side-effects
4657 (aset tokens js2-INSTANCEOF t))
4658 tokens))
4659
4660 (defun js2-node-has-side-effects (node)
4661 "Return t if NODE has side effects."
4662 (when node ; makes it easier to handle malformed expressions
4663 (let ((tt (js2-node-type node)))
4664 (cond
4665 ;; This doubtless needs some work, since EXPR_VOID is used
4666 ;; in several ways in Rhino and I may not have caught them all.
4667 ;; I'll wait for people to notice incorrect warnings.
4668 ((and (= tt js2-EXPR_VOID)
4669 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4670 (let ((expr (js2-expr-stmt-node-expr node)))
4671 (or (js2-node-has-side-effects expr)
4672 (when (js2-string-node-p expr)
4673 (string= "use strict" (js2-string-node-value expr))))))
4674 ((= tt js2-COMMA)
4675 (js2-node-has-side-effects (js2-infix-node-right node)))
4676 ((or (= tt js2-AND)
4677 (= tt js2-OR))
4678 (or (js2-node-has-side-effects (js2-infix-node-right node))
4679 (js2-node-has-side-effects (js2-infix-node-left node))))
4680 ((= tt js2-HOOK)
4681 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4682 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4683 ((js2-paren-node-p node)
4684 (js2-node-has-side-effects (js2-paren-node-expr node)))
4685 ((= tt js2-ERROR) ; avoid cascaded error messages
4686 nil)
4687 (t
4688 (aref js2-side-effecting-tokens tt))))))
4689
4690 (defun js2-member-expr-leftmost-name (node)
4691 "For an expr such as foo.bar.baz, return leftmost node foo.
4692 NODE is any `js2-node' object. If it represents a member expression,
4693 which is any sequence of property gets, element-gets, function calls,
4694 or xml descendants/filter operators, then we look at the lexically
4695 leftmost (first) node in the chain. If it is a name-node we return it.
4696 Note that NODE can be a raw name-node and it will be returned as well.
4697 If NODE is not a name-node or member expression, or if it is a member
4698 expression whose leftmost target is not a name node, returns nil."
4699 (let ((continue t)
4700 result)
4701 (while (and continue (not result))
4702 (cond
4703 ((js2-name-node-p node)
4704 (setq result node))
4705 ((js2-prop-get-node-p node)
4706 (setq node (js2-prop-get-node-left node)))
4707 ;; TODO: handle call-nodes, xml-nodes, others?
4708 (t
4709 (setq continue nil))))
4710 result))
4711
4712 (defconst js2-stmt-node-types
4713 (list js2-BLOCK
4714 js2-BREAK
4715 js2-CONTINUE
4716 js2-DEFAULT ; e4x "default xml namespace" statement
4717 js2-DO
4718 js2-EXPR_RESULT
4719 js2-EXPR_VOID
4720 js2-FOR
4721 js2-IF
4722 js2-RETURN
4723 js2-SWITCH
4724 js2-THROW
4725 js2-TRY
4726 js2-WHILE
4727 js2-WITH)
4728 "Node types that only appear in statement contexts.
4729 The list does not include nodes that always appear as the child
4730 of another specific statement type, such as switch-cases,
4731 catch and finally blocks, and else-clauses. The list also excludes
4732 nodes like yield, let and var, which may appear in either expression
4733 or statement context, and in the latter context always have a
4734 `js2-expr-stmt-node' parent. Finally, the list does not include
4735 functions or scripts, which are treated separately from statements
4736 by the JavaScript parser and runtime.")
4737
4738 (defun js2-stmt-node-p (node)
4739 "Heuristic for figuring out if NODE is a statement.
4740 Some node types can appear in either an expression context or a
4741 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4742 For these node types in a statement context, the parent will be a
4743 `js2-expr-stmt-node'.
4744 Functions aren't included in the check."
4745 (memq (js2-node-type node) js2-stmt-node-types))
4746
4747 (defun js2-mode-find-first-stmt (node)
4748 "Search upward starting from NODE looking for a statement.
4749 For purposes of this function, a `js2-function-node' counts."
4750 (while (not (or (js2-stmt-node-p node)
4751 (js2-function-node-p node)))
4752 (setq node (js2-node-parent node)))
4753 node)
4754
4755 (defun js2-node-parent-stmt (node)
4756 "Return the node's first ancestor that is a statement.
4757 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4758 appearing in a statement context will have a parent that is a
4759 `js2-expr-stmt-node' that will be returned by this function."
4760 (let ((parent (js2-node-parent node)))
4761 (if (or (null parent)
4762 (js2-stmt-node-p parent)
4763 (and (js2-function-node-p parent)
4764 (not (eq (js2-function-node-form parent)
4765 'FUNCTION_EXPRESSION))))
4766 parent
4767 (js2-node-parent-stmt parent))))
4768
4769 ;; In the Mozilla Rhino sources, Roshan James writes:
4770 ;; Does consistent-return analysis on the function body when strict mode is
4771 ;; enabled.
4772 ;;
4773 ;; function (x) { return (x+1) }
4774 ;;
4775 ;; is ok, but
4776 ;;
4777 ;; function (x) { if (x < 0) return (x+1); }
4778 ;;
4779 ;; is not because the function can potentially return a value when the
4780 ;; condition is satisfied and if not, the function does not explicitly
4781 ;; return a value.
4782 ;;
4783 ;; This extends to checking mismatches such as "return" and "return <value>"
4784 ;; used in the same function. Warnings are not emitted if inconsistent
4785 ;; returns exist in code that can be statically shown to be unreachable.
4786 ;; Ex.
4787 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4788 ;;
4789 ;; emits no warning. However if the loop had a break statement, then a
4790 ;; warning would be emitted.
4791 ;;
4792 ;; The consistency analysis looks at control structures such as loops, ifs,
4793 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4794 ;; warns the user about an inconsistent set of termination possibilities.
4795 ;;
4796 ;; These flags enumerate the possible ways a statement/function can
4797 ;; terminate. These flags are used by endCheck() and by the Parser to
4798 ;; detect inconsistent return usage.
4799 ;;
4800 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4801 ;; able to execute (example: throw, continue)
4802 ;;
4803 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4804 ;; next one. Statement such as return dont. A compound statement may have
4805 ;; some branch that drops off control to the next statement.
4806 ;;
4807 ;; END_RETURNS indicates that the statement can return with no value.
4808 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4809 ;;
4810 ;; A compound statement such as
4811 ;; if (condition) {
4812 ;; return value;
4813 ;; }
4814 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4815
4816 (defconst js2-END_UNREACHED 0)
4817 (defconst js2-END_DROPS_OFF 1)
4818 (defconst js2-END_RETURNS 2)
4819 (defconst js2-END_RETURNS_VALUE 4)
4820 (defconst js2-END_YIELDS 8)
4821
4822 (defun js2-has-consistent-return-usage (node)
4823 "Check that every return usage in a function body is consistent.
4824 Returns t if the function satisfies strict mode requirement."
4825 (let ((n (js2-end-check node)))
4826 ;; either it doesn't return a value in any branch...
4827 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4828 ;; or it returns a value (or is unreached) at every branch
4829 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4830 js2-END_RETURNS
4831 js2-END_YIELDS)))))
4832
4833 (defun js2-end-check-if (node)
4834 "Ensure that return usage in then/else blocks is consistent.
4835 If there is no else block, then the return statement can fall through.
4836 Returns logical OR of END_* flags"
4837 (let ((th (js2-if-node-then-part node))
4838 (el (js2-if-node-else-part node)))
4839 (if (null th)
4840 js2-END_UNREACHED
4841 (logior (js2-end-check th) (if el
4842 (js2-end-check el)
4843 js2-END_DROPS_OFF)))))
4844
4845 (defun js2-end-check-switch (node)
4846 "Consistency of return statements is checked between the case statements.
4847 If there is no default, then the switch can fall through. If there is a
4848 default, we check to see if all code paths in the default return or if
4849 there is a code path that can fall through.
4850 Returns logical OR of END_* flags."
4851 (let ((rv js2-END_UNREACHED)
4852 default-case)
4853 ;; examine the cases
4854 (catch 'break
4855 (dolist (c (js2-switch-node-cases node))
4856 (if (js2-case-node-expr c)
4857 (js2-set-flag rv (js2-end-check-block c))
4858 (setq default-case c)
4859 (throw 'break nil))))
4860 ;; we don't care how the cases drop into each other
4861 (js2-clear-flag rv js2-END_DROPS_OFF)
4862 ;; examine the default
4863 (js2-set-flag rv (if default-case
4864 (js2-end-check default-case)
4865 js2-END_DROPS_OFF))
4866 rv))
4867
4868 (defun js2-end-check-try (node)
4869 "If the block has a finally, return consistency is checked in the
4870 finally block. If all code paths in the finally return, then the
4871 returns in the try-catch blocks don't matter. If there is a code path
4872 that does not return or if there is no finally block, the returns
4873 of the try and catch blocks are checked for mismatch.
4874 Returns logical OR of END_* flags."
4875 (let ((finally (js2-try-node-finally-block node))
4876 rv)
4877 ;; check the finally if it exists
4878 (setq rv (if finally
4879 (js2-end-check (js2-finally-node-body finally))
4880 js2-END_DROPS_OFF))
4881 ;; If the finally block always returns, then none of the returns
4882 ;; in the try or catch blocks matter.
4883 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4884 (js2-clear-flag rv js2-END_DROPS_OFF)
4885 ;; examine the try block
4886 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4887 ;; check each catch block
4888 (dolist (cb (js2-try-node-catch-clauses node))
4889 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4890 rv))
4891
4892 (defun js2-end-check-loop (node)
4893 "Return statement in the loop body must be consistent.
4894 The default assumption for any kind of a loop is that it will eventually
4895 terminate. The only exception is a loop with a constant true condition.
4896 Code that follows such a loop is examined only if one can determine
4897 statically that there is a break out of the loop.
4898
4899 for(... ; ... ; ...) {}
4900 for(... in ... ) {}
4901 while(...) { }
4902 do { } while(...)
4903
4904 Returns logical OR of END_* flags."
4905 (let ((rv (js2-end-check (js2-loop-node-body node)))
4906 (condition (cond
4907 ((js2-while-node-p node)
4908 (js2-while-node-condition node))
4909 ((js2-do-node-p node)
4910 (js2-do-node-condition node))
4911 ((js2-for-node-p node)
4912 (js2-for-node-condition node)))))
4913
4914 ;; check to see if the loop condition is always true
4915 (if (and condition
4916 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4917 (js2-clear-flag rv js2-END_DROPS_OFF))
4918
4919 ;; look for effect of breaks
4920 (js2-set-flag rv (js2-node-get-prop node
4921 'CONTROL_BLOCK_PROP
4922 js2-END_UNREACHED))
4923 rv))
4924
4925 (defun js2-end-check-block (node)
4926 "A general block of code is examined statement by statement.
4927 If any statement (even a compound one) returns in all branches, then
4928 subsequent statements are not examined.
4929 Returns logical OR of END_* flags."
4930 (let* ((rv js2-END_DROPS_OFF)
4931 (kids (js2-block-node-kids node))
4932 (n (car kids)))
4933 ;; Check each statment. If the statement can continue onto the next
4934 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4935 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4936 (js2-clear-flag rv js2-END_DROPS_OFF)
4937 (js2-set-flag rv (js2-end-check n))
4938 (setq kids (cdr kids)
4939 n (car kids)))
4940 rv))
4941
4942 (defun js2-end-check-label (node)
4943 "A labeled statement implies that there may be a break to the label.
4944 The function processes the labeled statement and then checks the
4945 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4946 particular label.
4947 Returns logical OR of END_* flags."
4948 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4949 (logior rv (js2-node-get-prop node
4950 'CONTROL_BLOCK_PROP
4951 js2-END_UNREACHED))))
4952
4953 (defun js2-end-check-break (node)
4954 "When a break is encountered annotate the statement being broken
4955 out of by setting its CONTROL_BLOCK_PROP property.
4956 Returns logical OR of END_* flags."
4957 (and (js2-break-node-target node)
4958 (js2-node-set-prop (js2-break-node-target node)
4959 'CONTROL_BLOCK_PROP
4960 js2-END_DROPS_OFF))
4961 js2-END_UNREACHED)
4962
4963 (defun js2-end-check (node)
4964 "Examine the body of a function, doing a basic reachability analysis.
4965 Returns a combination of flags END_* flags that indicate
4966 how the function execution can terminate. These constitute only the
4967 pessimistic set of termination conditions. It is possible that at
4968 runtime certain code paths will never be actually taken. Hence this
4969 analysis will flag errors in cases where there may not be errors.
4970 Returns logical OR of END_* flags"
4971 (let (kid)
4972 (cond
4973 ((js2-break-node-p node)
4974 (js2-end-check-break node))
4975 ((js2-expr-stmt-node-p node)
4976 (if (setq kid (js2-expr-stmt-node-expr node))
4977 (js2-end-check kid)
4978 js2-END_DROPS_OFF))
4979 ((or (js2-continue-node-p node)
4980 (js2-throw-node-p node))
4981 js2-END_UNREACHED)
4982 ((js2-return-node-p node)
4983 (if (setq kid (js2-return-node-retval node))
4984 js2-END_RETURNS_VALUE
4985 js2-END_RETURNS))
4986 ((js2-loop-node-p node)
4987 (js2-end-check-loop node))
4988 ((js2-switch-node-p node)
4989 (js2-end-check-switch node))
4990 ((js2-labeled-stmt-node-p node)
4991 (js2-end-check-label node))
4992 ((js2-if-node-p node)
4993 (js2-end-check-if node))
4994 ((js2-try-node-p node)
4995 (js2-end-check-try node))
4996 ((js2-block-node-p node)
4997 (if (null (js2-block-node-kids node))
4998 js2-END_DROPS_OFF
4999 (js2-end-check-block node)))
5000 ((js2-yield-node-p node)
5001 js2-END_YIELDS)
5002 (t
5003 js2-END_DROPS_OFF))))
5004
5005 (defun js2-always-defined-boolean-p (node)
5006 "Check if NODE always evaluates to true or false in boolean context.
5007 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5008 nor always false."
5009 (let ((tt (js2-node-type node))
5010 num)
5011 (cond
5012 ((or (= tt js2-FALSE) (= tt js2-NULL))
5013 'ALWAYS_FALSE)
5014 ((= tt js2-TRUE)
5015 'ALWAYS_TRUE)
5016 ((= tt js2-NUMBER)
5017 (setq num (js2-number-node-num-value node))
5018 (if (and (not (eq num 0.0e+NaN))
5019 (not (zerop num)))
5020 'ALWAYS_TRUE
5021 'ALWAYS_FALSE))
5022 (t
5023 nil))))
5024
5025 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5026 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5027
5028 (defvar js2-tokens nil
5029 "List of all defined token names.") ; initialized in `js2-token-names'
5030
5031 (defconst js2-token-names
5032 (let* ((names (make-vector js2-num-tokens -1))
5033 (case-fold-search nil) ; only match js2-UPPER_CASE
5034 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5035 (loop for sym in syms
5036 for i from 0
5037 do
5038 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5039 (not (boundp sym)))
5040 (aset names (symbol-value sym) ; code, e.g. 152
5041 (downcase
5042 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5043 (push sym js2-tokens)))
5044 names)
5045 "Vector mapping int values to token string names, sans `js2-' prefix.")
5046
5047 (defun js2-token-name (tok)
5048 "Return a string name for TOK, a token symbol or code.
5049 Signals an error if it's not a recognized token."
5050 (let ((code tok))
5051 (if (symbolp tok)
5052 (setq code (symbol-value tok)))
5053 (if (eq code -1)
5054 "ERROR"
5055 (if (and (numberp code)
5056 (not (minusp code))
5057 (< code js2-num-tokens))
5058 (aref js2-token-names code)
5059 (error "Invalid token: %s" code)))))
5060
5061 (defsubst js2-token-sym (tok)
5062 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5063 (intern (js2-token-name tok)))
5064
5065 (defconst js2-token-codes
5066 (let ((table (make-hash-table :test 'eq :size 256)))
5067 (loop for name across js2-token-names
5068 for sym = (intern (concat "js2-" (upcase name)))
5069 do
5070 (puthash sym (symbol-value sym) table))
5071 ;; clean up a few that are "wrong" in Rhino's token codes
5072 (puthash 'js2-DELETE js2-DELPROP table)
5073 table)
5074 "Hashtable mapping token symbols to their bytecodes.")
5075
5076 (defsubst js2-token-code (sym)
5077 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5078 (or (gethash sym js2-token-codes)
5079 (error "Invalid token symbol: %s " sym))) ; signal code bug
5080
5081 (defun js2-report-scan-error (msg &optional no-throw beg len)
5082 (setq js2-token-end js2-ts-cursor)
5083 (js2-report-error msg nil
5084 (or beg js2-token-beg)
5085 (or len (- js2-token-end js2-token-beg)))
5086 (unless no-throw
5087 (throw 'return js2-ERROR)))
5088
5089 (defun js2-get-string-from-buffer ()
5090 "Reverse the char accumulator and return it as a string."
5091 (setq js2-token-end js2-ts-cursor)
5092 (if js2-ts-string-buffer
5093 (apply #'string (nreverse js2-ts-string-buffer))
5094 ""))
5095
5096 ;; TODO: could potentially avoid a lot of consing by allocating a
5097 ;; char buffer the way Rhino does.
5098 (defsubst js2-add-to-string (c)
5099 (push c js2-ts-string-buffer))
5100
5101 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5102 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5103 ;; any other character: when it's not part of the current token, we
5104 ;; unget it, allowing it to be read again by the following call.
5105 (defsubst js2-unget-char ()
5106 (decf js2-ts-cursor))
5107
5108 ;; Rhino distinguishes \r and \n line endings. We don't need to
5109 ;; because we only scan from Emacs buffers, which always use \n.
5110 (defun js2-get-char ()
5111 "Read and return the next character from the input buffer.
5112 Increments `js2-ts-lineno' if the return value is a newline char.
5113 Updates `js2-ts-cursor' to the point after the returned char.
5114 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5115 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5116 (let (c)
5117 ;; check for end of buffer
5118 (if (>= js2-ts-cursor (point-max))
5119 (setq js2-ts-hit-eof t
5120 js2-ts-cursor (1+ js2-ts-cursor)
5121 c js2-EOF_CHAR) ; return value
5122 ;; otherwise read next char
5123 (setq c (char-before (incf js2-ts-cursor)))
5124 ;; if we read a newline, update counters
5125 (if (= c ?\n)
5126 (setq js2-ts-line-start js2-ts-cursor
5127 js2-ts-lineno (1+ js2-ts-lineno)))
5128 ;; TODO: skip over format characters
5129 c)))
5130
5131 (defun js2-read-unicode-escape ()
5132 "Read a \\uNNNN sequence from the input.
5133 Assumes the ?\ and ?u have already been read.
5134 Returns the unicode character, or nil if it wasn't a valid character.
5135 Doesn't change the values of any scanner variables."
5136 ;; I really wish I knew a better way to do this, but I can't
5137 ;; find the Emacs function that takes a 16-bit int and converts
5138 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5139 ;; Have to first check that it's 4 hex characters or it may stop
5140 ;; the read early.
5141 (ignore-errors
5142 (let ((s (buffer-substring-no-properties js2-ts-cursor
5143 (+ 4 js2-ts-cursor))))
5144 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5145 (read (concat "?\\u" s))))))
5146
5147 (defun js2-match-char (test)
5148 "Consume and return next character if it matches TEST, a character.
5149 Returns nil and consumes nothing if TEST is not the next character."
5150 (let ((c (js2-get-char)))
5151 (if (eq c test)
5152 t
5153 (js2-unget-char)
5154 nil)))
5155
5156 (defun js2-peek-char ()
5157 (prog1
5158 (js2-get-char)
5159 (js2-unget-char)))
5160
5161 (defun js2-java-identifier-start-p (c)
5162 (or
5163 (memq c '(?$ ?_))
5164 (js2-char-uppercase-p c)
5165 (js2-char-lowercase-p c)))
5166
5167 (defun js2-java-identifier-part-p (c)
5168 "Implementation of java.lang.Character.isJavaIdentifierPart()."
5169 ;; TODO: make me Unicode-friendly. See comments above.
5170 (or
5171 (memq c '(?$ ?_))
5172 (js2-char-uppercase-p c)
5173 (js2-char-lowercase-p c)
5174 (and (>= c ?0) (<= c ?9))))
5175
5176 (defun js2-alpha-p (c)
5177 (cond ((and (<= ?A c) (<= c ?Z)) t)
5178 ((and (<= ?a c) (<= c ?z)) t)
5179 (t nil)))
5180
5181 (defsubst js2-digit-p (c)
5182 (and (<= ?0 c) (<= c ?9)))
5183
5184 (defun js2-js-space-p (c)
5185 (if (<= c 127)
5186 (memq c '(#x20 #x9 #xB #xC #xD))
5187 (or
5188 (eq c #xA0)
5189 ;; TODO: change this nil to check for Unicode space character
5190 nil)))
5191
5192 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5193
5194 (defun js2-skip-line ()
5195 "Skip to end of line."
5196 (let (c)
5197 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5198 (js2-unget-char)
5199 (setq js2-token-end js2-ts-cursor)))
5200
5201 (defun js2-init-scanner (&optional buf line)
5202 "Create token stream for BUF starting on LINE.
5203 BUF defaults to `current-buffer' and LINE defaults to 1.
5204
5205 A buffer can only have one scanner active at a time, which yields
5206 dramatically simpler code than using a defstruct. If you need to
5207 have simultaneous scanners in a buffer, copy the regions to scan
5208 into temp buffers."
5209 (with-current-buffer (or buf (current-buffer))
5210 (setq js2-ts-dirty-line nil
5211 js2-ts-regexp-flags nil
5212 js2-ts-string ""
5213 js2-ts-number nil
5214 js2-ts-hit-eof nil
5215 js2-ts-line-start 0
5216 js2-ts-lineno (or line 1)
5217 js2-ts-line-end-char -1
5218 js2-ts-cursor (point-min)
5219 js2-ts-is-xml-attribute nil
5220 js2-ts-xml-is-tag-content nil
5221 js2-ts-xml-open-tags-count 0
5222 js2-ts-string-buffer nil)))
5223
5224 ;; This function uses the cached op, string and number fields in
5225 ;; TokenStream; if getToken has been called since the passed token
5226 ;; was scanned, the op or string printed may be incorrect.
5227 (defun js2-token-to-string (token)
5228 ;; Not sure where this function is used in Rhino. Not tested.
5229 (if (not js2-debug-print-trees)
5230 ""
5231 (let ((name (js2-token-name token)))
5232 (cond
5233 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5234 (concat name " `" js2-ts-string "'"))
5235 ((eq token js2-NUMBER)
5236 (format "NUMBER %g" js2-ts-number))
5237 (t
5238 name)))))
5239
5240 (defconst js2-keywords
5241 '(break
5242 case catch const continue
5243 debugger default delete do
5244 else enum
5245 false finally for function
5246 if in instanceof import
5247 let
5248 new null
5249 return
5250 switch
5251 this throw true try typeof
5252 var void
5253 while with
5254 yield))
5255
5256 ;; Token names aren't exactly the same as the keywords, unfortunately.
5257 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5258 (defconst js2-kwd-tokens
5259 (let ((table (make-vector js2-num-tokens nil))
5260 (tokens
5261 (list js2-BREAK
5262 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5263 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5264 js2-ELSE
5265 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5266 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5267 js2-LET
5268 js2-NEW js2-NULL
5269 js2-RETURN
5270 js2-SWITCH
5271 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5272 js2-VAR
5273 js2-WHILE js2-WITH
5274 js2-YIELD)))
5275 (dolist (i tokens)
5276 (aset table i 'font-lock-keyword-face))
5277 (aset table js2-STRING 'font-lock-string-face)
5278 (aset table js2-REGEXP 'font-lock-string-face)
5279 (aset table js2-COMMENT 'font-lock-comment-face)
5280 (aset table js2-THIS 'font-lock-builtin-face)
5281 (aset table js2-VOID 'font-lock-constant-face)
5282 (aset table js2-NULL 'font-lock-constant-face)
5283 (aset table js2-TRUE 'font-lock-constant-face)
5284 (aset table js2-FALSE 'font-lock-constant-face)
5285 table)
5286 "Vector whose values are non-nil for tokens that are keywords.
5287 The values are default faces to use for highlighting the keywords.")
5288
5289 (defconst js2-reserved-words
5290 '(abstract
5291 boolean byte
5292 char class
5293 double
5294 enum export extends
5295 final float
5296 goto
5297 implements import int interface
5298 long
5299 native
5300 package private protected public
5301 short static super synchronized
5302 throws transient
5303 volatile))
5304
5305 (defconst js2-keyword-names
5306 (let ((table (make-hash-table :test 'equal)))
5307 (loop for k in js2-keywords
5308 do (puthash
5309 (symbol-name k) ; instanceof
5310 (intern (concat "js2-"
5311 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5312 table))
5313 table)
5314 "JavaScript keywords by name, mapped to their symbols.")
5315
5316 (defconst js2-reserved-word-names
5317 (let ((table (make-hash-table :test 'equal)))
5318 (loop for k in js2-reserved-words
5319 do
5320 (puthash (symbol-name k) 'js2-RESERVED table))
5321 table)
5322 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5323
5324 (defun js2-collect-string (buf)
5325 "Convert BUF, a list of chars, to a string.
5326 Reverses BUF before converting."
5327 (cond
5328 ((stringp buf)
5329 buf)
5330 ((null buf) ; for emacs21 compat
5331 "")
5332 (t
5333 (if buf
5334 (apply #'string (nreverse buf))
5335 ""))))
5336
5337 (defun js2-string-to-keyword (s)
5338 "Return token for S, a string, if S is a keyword or reserved word.
5339 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5340 (or (gethash s js2-keyword-names)
5341 (gethash s js2-reserved-word-names)))
5342
5343 (defsubst js2-ts-set-char-token-bounds ()
5344 "Used when next token is one character."
5345 (setq js2-token-beg (1- js2-ts-cursor)
5346 js2-token-end js2-ts-cursor))
5347
5348 (defsubst js2-ts-return (token)
5349 "Return an N-character TOKEN from `js2-get-token'.
5350 Updates `js2-token-end' accordingly."
5351 (setq js2-token-end js2-ts-cursor)
5352 (throw 'return token))
5353
5354 (defun js2-x-digit-to-int (c accumulator)
5355 "Build up a hex number.
5356 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5357 corresponding number. Otherwise return -1."
5358 (catch 'return
5359 (catch 'check
5360 ;; Use 0..9 < A..Z < a..z
5361 (cond
5362 ((<= c ?9)
5363 (decf c ?0)
5364 (if (<= 0 c)
5365 (throw 'check nil)))
5366 ((<= c ?F)
5367 (when (<= ?A c)
5368 (decf c (- ?A 10))
5369 (throw 'check nil)))
5370 ((<= c ?f)
5371 (when (<= ?a c)
5372 (decf c (- ?a 10))
5373 (throw 'check nil))))
5374 (throw 'return -1))
5375 (logior c (lsh accumulator 4))))
5376
5377 (defun js2-get-token ()
5378 "Return next JavaScript token, an int such as js2-RETURN."
5379 (let (c c1 identifier-start is-unicode-escape-start
5380 contains-escape escape-val escape-start str result base
5381 is-integer quote-char val look-for-slash continue)
5382 (catch 'return
5383 (while t
5384 ;; Eat whitespace, possibly sensitive to newlines.
5385 (setq continue t)
5386 (while continue
5387 (setq c (js2-get-char))
5388 (cond
5389 ((eq c js2-EOF_CHAR)
5390 (js2-ts-set-char-token-bounds)
5391 (throw 'return js2-EOF))
5392 ((eq c ?\n)
5393 (js2-ts-set-char-token-bounds)
5394 (setq js2-ts-dirty-line nil)
5395 (throw 'return js2-EOL))
5396 ((not (js2-js-space-p c))
5397 (if (/= c ?-) ; in case end of HTML comment
5398 (setq js2-ts-dirty-line t))
5399 (setq continue nil))))
5400 ;; Assume the token will be 1 char - fixed up below.
5401 (js2-ts-set-char-token-bounds)
5402 (when (eq c ?@)
5403 (throw 'return js2-XMLATTR))
5404 ;; identifier/keyword/instanceof?
5405 ;; watch out for starting with a <backslash>
5406 (cond
5407 ((eq c ?\\)
5408 (setq c (js2-get-char))
5409 (if (eq c ?u)
5410 (setq identifier-start t
5411 is-unicode-escape-start t
5412 js2-ts-string-buffer nil)
5413 (setq identifier-start nil)
5414 (js2-unget-char)
5415 (setq c ?\\)))
5416 (t
5417 (when (setq identifier-start (js2-java-identifier-start-p c))
5418 (setq js2-ts-string-buffer nil)
5419 (js2-add-to-string c))))
5420 (when identifier-start
5421 (setq contains-escape is-unicode-escape-start)
5422 (catch 'break
5423 (while t
5424 (if is-unicode-escape-start
5425 ;; strictly speaking we should probably push-back
5426 ;; all the bad characters if the <backslash>uXXXX
5427 ;; sequence is malformed. But since there isn't a
5428 ;; correct context(is there?) for a bad Unicode
5429 ;; escape sequence in an identifier, we can report
5430 ;; an error here.
5431 (progn
5432 (setq escape-val 0)
5433 (dotimes (i 4)
5434 (setq c (js2-get-char)
5435 escape-val (js2-x-digit-to-int c escape-val))
5436 ;; Next check takes care of c < 0 and bad escape
5437 (if (minusp escape-val)
5438 (throw 'break nil)))
5439 (if (minusp escape-val)
5440 (js2-report-scan-error "msg.invalid.escape" t))
5441 (js2-add-to-string escape-val)
5442 (setq is-unicode-escape-start nil))
5443 (setq c (js2-get-char))
5444 (cond
5445 ((eq c ?\\)
5446 (setq c (js2-get-char))
5447 (if (eq c ?u)
5448 (setq is-unicode-escape-start t
5449 contains-escape t)
5450 (js2-report-scan-error "msg.illegal.character" t)))
5451 (t
5452 (if (or (eq c js2-EOF_CHAR)
5453 (not (js2-java-identifier-part-p c)))
5454 (throw 'break nil))
5455 (js2-add-to-string c))))))
5456 (js2-unget-char)
5457 (setq str (js2-get-string-from-buffer))
5458 (unless contains-escape
5459 ;; OPT we shouldn't have to make a string (object!) to
5460 ;; check if it's a keyword.
5461 ;; Return the corresponding token if it's a keyword
5462 (when (setq result (js2-string-to-keyword str))
5463 (if (and (< js2-language-version 170)
5464 (memq result '(js2-LET js2-YIELD)))
5465 ;; LET and YIELD are tokens only in 1.7 and later
5466 (setq result 'js2-NAME))
5467 (if (not (eq result 'js2-RESERVED))
5468 (throw 'return (js2-token-code result)))
5469 (js2-report-warning "msg.reserved.keyword" str)))
5470 ;; If we want to intern these as Rhino does, just use (intern str)
5471 (setq js2-ts-string str)
5472 (throw 'return js2-NAME)) ; end identifier/kwd check
5473 ;; is it a number?
5474 (when (or (js2-digit-p c)
5475 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5476 (setq js2-ts-string-buffer nil
5477 base 10)
5478 (when (eq c ?0)
5479 (setq c (js2-get-char))
5480 (cond
5481 ((or (eq c ?x) (eq c ?X))
5482 (setq base 16)
5483 (setq c (js2-get-char)))
5484 ((js2-digit-p c)
5485 (setq base 8))
5486 (t
5487 (js2-add-to-string ?0))))
5488 (if (eq base 16)
5489 (while (<= 0 (js2-x-digit-to-int c 0))
5490 (js2-add-to-string c)
5491 (setq c (js2-get-char)))
5492 (while (and (<= ?0 c) (<= c ?9))
5493 ;; We permit 08 and 09 as decimal numbers, which
5494 ;; makes our behavior a superset of the ECMA
5495 ;; numeric grammar. We might not always be so
5496 ;; permissive, so we warn about it.
5497 (when (and (eq base 8) (>= c ?8))
5498 (js2-report-warning "msg.bad.octal.literal"
5499 (if (eq c ?8) "8" "9"))
5500 (setq base 10))
5501 (js2-add-to-string c)
5502 (setq c (js2-get-char))))
5503 (setq is-integer t)
5504 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5505 (setq is-integer nil)
5506 (when (eq c ?.)
5507 (loop do
5508 (js2-add-to-string c)
5509 (setq c (js2-get-char))
5510 while (js2-digit-p c)))
5511 (when (memq c '(?e ?E))
5512 (js2-add-to-string c)
5513 (setq c (js2-get-char))
5514 (when (memq c '(?+ ?-))
5515 (js2-add-to-string c)
5516 (setq c (js2-get-char)))
5517 (unless (js2-digit-p c)
5518 (js2-report-scan-error "msg.missing.exponent" t))
5519 (loop do
5520 (js2-add-to-string c)
5521 (setq c (js2-get-char))
5522 while (js2-digit-p c))))
5523 (js2-unget-char)
5524 (setq js2-ts-string (js2-get-string-from-buffer)
5525 js2-ts-number
5526 (if (and (eq base 10) (not is-integer))
5527 (string-to-number js2-ts-string)
5528 ;; TODO: call runtime number-parser. Some of it is in
5529 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5530 (string-to-number js2-ts-string)))
5531 (throw 'return js2-NUMBER))
5532 ;; is it a string?
5533 (when (memq c '(?\" ?\'))
5534 ;; We attempt to accumulate a string the fast way, by
5535 ;; building it directly out of the reader. But if there
5536 ;; are any escaped characters in the string, we revert to
5537 ;; building it out of a string buffer.
5538 (setq quote-char c
5539 js2-ts-string-buffer nil
5540 c (js2-get-char))
5541 (catch 'break
5542 (while (/= c quote-char)
5543 (catch 'continue
5544 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5545 (js2-unget-char)
5546 (setq js2-token-end js2-ts-cursor)
5547 (js2-report-error "msg.unterminated.string.lit")
5548 (throw 'return js2-STRING))
5549 (when (eq c ?\\)
5550 ;; We've hit an escaped character
5551 (setq c (js2-get-char))
5552 (case c
5553 (?b (setq c ?\b))
5554 (?f (setq c ?\f))
5555 (?n (setq c ?\n))
5556 (?r (setq c ?\r))
5557 (?t (setq c ?\t))
5558 (?v (setq c ?\v))
5559 (?u
5560 (setq c1 (js2-read-unicode-escape))
5561 (if js2-parse-ide-mode
5562 (if c1
5563 (progn
5564 ;; just copy the string in IDE-mode
5565 (js2-add-to-string ?\\)
5566 (js2-add-to-string ?u)
5567 (dotimes (i 3)
5568 (js2-add-to-string (js2-get-char)))
5569 (setq c (js2-get-char))) ; added at end of loop
5570 ;; flag it as an invalid escape
5571 (js2-report-warning "msg.invalid.escape"
5572 nil (- js2-ts-cursor 2) 6))
5573 ;; Get 4 hex digits; if the u escape is not
5574 ;; followed by 4 hex digits, use 'u' + the
5575 ;; literal character sequence that follows.
5576 (js2-add-to-string ?u)
5577 (setq escape-val 0)
5578 (dotimes (i 4)
5579 (setq c (js2-get-char)
5580 escape-val (js2-x-digit-to-int c escape-val))
5581 (if (minusp escape-val)
5582 (throw 'continue nil))
5583 (js2-add-to-string c))
5584 ;; prepare for replace of stored 'u' sequence by escape value
5585 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5586 c escape-val)))
5587 (?x
5588 ;; Get 2 hex digits, defaulting to 'x'+literal
5589 ;; sequence, as above.
5590 (setq c (js2-get-char)
5591 escape-val (js2-x-digit-to-int c 0))
5592 (if (minusp escape-val)
5593 (progn
5594 (js2-add-to-string ?x)
5595 (throw 'continue nil))
5596 (setq c1 c
5597 c (js2-get-char)
5598 escape-val (js2-x-digit-to-int c escape-val))
5599 (if (minusp escape-val)
5600 (progn
5601 (js2-add-to-string ?x)
5602 (js2-add-to-string c1)
5603 (throw 'continue nil))
5604 ;; got 2 hex digits
5605 (setq c escape-val))))
5606 (?\n
5607 ;; Remove line terminator after escape to follow
5608 ;; SpiderMonkey and C/C++
5609 (setq c (js2-get-char))
5610 (throw 'continue nil))
5611 (t
5612 (when (and (<= ?0 c) (< c ?8))
5613 (setq val (- c ?0)
5614 c (js2-get-char))
5615 (when (and (<= ?0 c) (< c ?8))
5616 (setq val (- (+ (* 8 val) c) ?0)
5617 c (js2-get-char))
5618 (when (and (<= ?0 c)
5619 (< c ?8)
5620 (< val #o37))
5621 ;; c is 3rd char of octal sequence only
5622 ;; if the resulting val <= 0377
5623 (setq val (- (+ (* 8 val) c) ?0)
5624 c (js2-get-char))))
5625 (js2-unget-char)
5626 (setq c val)))))
5627 (js2-add-to-string c)
5628 (setq c (js2-get-char)))))
5629 (setq js2-ts-string (js2-get-string-from-buffer))
5630 (throw 'return js2-STRING))
5631 (case c
5632 (?\;
5633 (throw 'return js2-SEMI))
5634 (?\[
5635 (throw 'return js2-LB))
5636 (?\]
5637 (throw 'return js2-RB))
5638 (?{
5639 (throw 'return js2-LC))
5640 (?}
5641 (throw 'return js2-RC))
5642 (?\(
5643 (throw 'return js2-LP))
5644 (?\)
5645 (throw 'return js2-RP))
5646 (?,
5647 (throw 'return js2-COMMA))
5648 (??
5649 (throw 'return js2-HOOK))
5650 (?:
5651 (if (js2-match-char ?:)
5652 (js2-ts-return js2-COLONCOLON)
5653 (throw 'return js2-COLON)))
5654 (?.
5655 (if (js2-match-char ?.)
5656 (if (js2-match-char ?.)
5657 (js2-ts-return js2-TRIPLEDOT)
5658 (js2-ts-return js2-DOTDOT))
5659 (if (js2-match-char ?\()
5660 (js2-ts-return js2-DOTQUERY)
5661 (throw 'return js2-DOT))))
5662 (?|
5663 (if (js2-match-char ?|)
5664 (throw 'return js2-OR)
5665 (if (js2-match-char ?=)
5666 (js2-ts-return js2-ASSIGN_BITOR)
5667 (throw 'return js2-BITOR))))
5668 (?^
5669 (if (js2-match-char ?=)
5670 (js2-ts-return js2-ASSIGN_BITOR)
5671 (throw 'return js2-BITXOR)))
5672 (?&
5673 (if (js2-match-char ?&)
5674 (throw 'return js2-AND)
5675 (if (js2-match-char ?=)
5676 (js2-ts-return js2-ASSIGN_BITAND)
5677 (throw 'return js2-BITAND))))
5678 (?=
5679 (if (js2-match-char ?=)
5680 (if (js2-match-char ?=)
5681 (js2-ts-return js2-SHEQ)
5682 (throw 'return js2-EQ))
5683 (throw 'return js2-ASSIGN)))
5684 (?!
5685 (if (js2-match-char ?=)
5686 (if (js2-match-char ?=)
5687 (js2-ts-return js2-SHNE)
5688 (js2-ts-return js2-NE))
5689 (throw 'return js2-NOT)))
5690 (?<
5691 ;; NB:treat HTML begin-comment as comment-till-eol
5692 (when (js2-match-char ?!)
5693 (when (js2-match-char ?-)
5694 (when (js2-match-char ?-)
5695 (js2-skip-line)
5696 (setq js2-ts-comment-type 'html)
5697 (throw 'return js2-COMMENT)))
5698 (js2-unget-char))
5699 (if (js2-match-char ?<)
5700 (if (js2-match-char ?=)
5701 (js2-ts-return js2-ASSIGN_LSH)
5702 (js2-ts-return js2-LSH))
5703 (if (js2-match-char ?=)
5704 (js2-ts-return js2-LE)
5705 (throw 'return js2-LT))))
5706 (?>
5707 (if (js2-match-char ?>)
5708 (if (js2-match-char ?>)
5709 (if (js2-match-char ?=)
5710 (js2-ts-return js2-ASSIGN_URSH)
5711 (js2-ts-return js2-URSH))
5712 (if (js2-match-char ?=)
5713 (js2-ts-return js2-ASSIGN_RSH)
5714 (js2-ts-return js2-RSH)))
5715 (if (js2-match-char ?=)
5716 (js2-ts-return js2-GE)
5717 (throw 'return js2-GT))))
5718 (?*
5719 (if (js2-match-char ?=)
5720 (js2-ts-return js2-ASSIGN_MUL)
5721 (throw 'return js2-MUL)))
5722 (?/
5723 ;; is it a // comment?
5724 (when (js2-match-char ?/)
5725 (setq js2-token-beg (- js2-ts-cursor 2))
5726 (js2-skip-line)
5727 (setq js2-ts-comment-type 'line)
5728 ;; include newline so highlighting goes to end of window
5729 (incf js2-token-end)
5730 (throw 'return js2-COMMENT))
5731 ;; is it a /* comment?
5732 (when (js2-match-char ?*)
5733 (setq look-for-slash nil
5734 js2-token-beg (- js2-ts-cursor 2)
5735 js2-ts-comment-type
5736 (if (js2-match-char ?*)
5737 (progn
5738 (setq look-for-slash t)
5739 'jsdoc)
5740 'block))
5741 (while t
5742 (setq c (js2-get-char))
5743 (cond
5744 ((eq c js2-EOF_CHAR)
5745 (setq js2-token-end (1- js2-ts-cursor))
5746 (js2-report-error "msg.unterminated.comment")
5747 (throw 'return js2-COMMENT))
5748 ((eq c ?*)
5749 (setq look-for-slash t))
5750 ((eq c ?/)
5751 (if look-for-slash
5752 (js2-ts-return js2-COMMENT)))
5753 (t
5754 (setq look-for-slash nil
5755 js2-token-end js2-ts-cursor)))))
5756 (if (js2-match-char ?=)
5757 (js2-ts-return js2-ASSIGN_DIV)
5758 (throw 'return js2-DIV)))
5759 (?#
5760 (when js2-skip-preprocessor-directives
5761 (js2-skip-line)
5762 (setq js2-ts-comment-type 'preprocessor
5763 js2-token-end js2-ts-cursor)
5764 (throw 'return js2-COMMENT))
5765 (throw 'return js2-ERROR))
5766 (?%
5767 (if (js2-match-char ?=)
5768 (js2-ts-return js2-ASSIGN_MOD)
5769 (throw 'return js2-MOD)))
5770 (?~
5771 (throw 'return js2-BITNOT))
5772 (?+
5773 (if (js2-match-char ?=)
5774 (js2-ts-return js2-ASSIGN_ADD)
5775 (if (js2-match-char ?+)
5776 (js2-ts-return js2-INC)
5777 (throw 'return js2-ADD))))
5778 (?-
5779 (cond
5780 ((js2-match-char ?=)
5781 (setq c js2-ASSIGN_SUB))
5782 ((js2-match-char ?-)
5783 (unless js2-ts-dirty-line
5784 ;; treat HTML end-comment after possible whitespace
5785 ;; after line start as comment-until-eol
5786 (when (js2-match-char ?>)
5787 (js2-skip-line)
5788 (setq js2-ts-comment-type 'html)
5789 (throw 'return js2-COMMENT)))
5790 (setq c js2-DEC))
5791 (t
5792 (setq c js2-SUB)))
5793 (setq js2-ts-dirty-line t)
5794 (js2-ts-return c))
5795 (otherwise
5796 (js2-report-scan-error "msg.illegal.character")))))))
5797
5798 (defun js2-read-regexp (start-token)
5799 "Called by parser when it gets / or /= in literal context."
5800 (let (c err
5801 in-class ; inside a '[' .. ']' character-class
5802 flags
5803 (continue t))
5804 (setq js2-token-beg js2-ts-cursor
5805 js2-ts-string-buffer nil
5806 js2-ts-regexp-flags nil)
5807 (if (eq start-token js2-ASSIGN_DIV)
5808 ;; mis-scanned /=
5809 (js2-add-to-string ?=)
5810 (if (not (eq start-token js2-DIV))
5811 (error "failed assertion")))
5812 (while (and (not err)
5813 (or (/= (setq c (js2-get-char)) ?/)
5814 in-class))
5815 (cond
5816 ((or (= c ?\n)
5817 (= c js2-EOF_CHAR))
5818 (setq js2-token-end (1- js2-ts-cursor)
5819 err t
5820 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5821 (js2-report-error "msg.unterminated.re.lit"))
5822 (t (cond
5823 ((= c ?\\)
5824 (js2-add-to-string c)
5825 (setq c (js2-get-char)))
5826 ((= c ?\[)
5827 (setq in-class t))
5828 ((= c ?\])
5829 (setq in-class nil)))
5830 (js2-add-to-string c))))
5831 (unless err
5832 (while continue
5833 (cond
5834 ((js2-match-char ?g)
5835 (push ?g flags))
5836 ((js2-match-char ?i)
5837 (push ?i flags))
5838 ((js2-match-char ?m)
5839 (push ?m flags))
5840 (t
5841 (setq continue nil))))
5842 (if (js2-alpha-p (js2-peek-char))
5843 (js2-report-scan-error "msg.invalid.re.flag" t
5844 js2-ts-cursor 1))
5845 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5846 js2-ts-regexp-flags (js2-collect-string flags)
5847 js2-token-end js2-ts-cursor)
5848 ;; tell `parse-partial-sexp' to ignore this range of chars
5849 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
5850
5851 (defun js2-get-first-xml-token ()
5852 (setq js2-ts-xml-open-tags-count 0
5853 js2-ts-is-xml-attribute nil
5854 js2-ts-xml-is-tag-content nil)
5855 (js2-unget-char)
5856 (js2-get-next-xml-token))
5857
5858 (defun js2-xml-discard-string ()
5859 "Throw away the string in progress and flag an XML parse error."
5860 (setq js2-ts-string-buffer nil
5861 js2-ts-string nil)
5862 (js2-report-scan-error "msg.XML.bad.form" t))
5863
5864 (defun js2-get-next-xml-token ()
5865 (setq js2-ts-string-buffer nil ; for recording the XML
5866 js2-token-beg js2-ts-cursor)
5867 (let (c result)
5868 (setq result
5869 (catch 'return
5870 (while t
5871 (setq c (js2-get-char))
5872 (cond
5873 ((= c js2-EOF_CHAR)
5874 (throw 'return js2-ERROR))
5875 (js2-ts-xml-is-tag-content
5876 (case c
5877 (?>
5878 (js2-add-to-string c)
5879 (setq js2-ts-xml-is-tag-content nil
5880 js2-ts-is-xml-attribute nil))
5881 (?/
5882 (js2-add-to-string c)
5883 (when (eq ?> (js2-peek-char))
5884 (setq c (js2-get-char))
5885 (js2-add-to-string c)
5886 (setq js2-ts-xml-is-tag-content nil)
5887 (decf js2-ts-xml-open-tags-count)))
5888 (?{
5889 (js2-unget-char)
5890 (setq js2-ts-string (js2-get-string-from-buffer))
5891 (throw 'return js2-XML))
5892 ((?\' ?\")
5893 (js2-add-to-string c)
5894 (unless (js2-read-quoted-string c)
5895 (throw 'return js2-ERROR)))
5896 (?=
5897 (js2-add-to-string c)
5898 (setq js2-ts-is-xml-attribute t))
5899 ((? ?\t ?\r ?\n)
5900 (js2-add-to-string c))
5901 (t
5902 (js2-add-to-string c)
5903 (setq js2-ts-is-xml-attribute nil)))
5904 (when (and (not js2-ts-xml-is-tag-content)
5905 (zerop js2-ts-xml-open-tags-count))
5906 (setq js2-ts-string (js2-get-string-from-buffer))
5907 (throw 'return js2-XMLEND)))
5908 (t
5909 ;; else not tag content
5910 (case c
5911 (?<
5912 (js2-add-to-string c)
5913 (setq c (js2-peek-char))
5914 (case c
5915 (?!
5916 (setq c (js2-get-char)) ;; skip !
5917 (js2-add-to-string c)
5918 (setq c (js2-peek-char))
5919 (case c
5920 (?-
5921 (setq c (js2-get-char)) ;; skip -
5922 (js2-add-to-string c)
5923 (if (eq c ?-)
5924 (progn
5925 (js2-add-to-string c)
5926 (unless (js2-read-xml-comment)
5927 (throw 'return js2-ERROR)))
5928 (js2-xml-discard-string)
5929 (throw 'return js2-ERROR)))
5930 (?\[
5931 (setq c (js2-get-char)) ;; skip [
5932 (js2-add-to-string c)
5933 (if (and (= (js2-get-char) ?C)
5934 (= (js2-get-char) ?D)
5935 (= (js2-get-char) ?A)
5936 (= (js2-get-char) ?T)
5937 (= (js2-get-char) ?A)
5938 (= (js2-get-char) ?\[))
5939 (progn
5940 (js2-add-to-string ?C)
5941 (js2-add-to-string ?D)
5942 (js2-add-to-string ?A)
5943 (js2-add-to-string ?T)
5944 (js2-add-to-string ?A)
5945 (js2-add-to-string ?\[)
5946 (unless (js2-read-cdata)
5947 (throw 'return js2-ERROR)))
5948 (js2-xml-discard-string)
5949 (throw 'return js2-ERROR)))
5950 (t
5951 (unless (js2-read-entity)
5952 (throw 'return js2-ERROR))))
5953 ;; Allow bare CDATA section, e.g.:
5954 ;; let xml = <![CDATA[ foo bar baz ]]>;
5955 (when (zerop js2-ts-xml-open-tags-count)
5956 (throw 'return js2-XMLEND)))
5957 (??
5958 (setq c (js2-get-char)) ;; skip ?
5959 (js2-add-to-string c)
5960 (unless (js2-read-PI)
5961 (throw 'return js2-ERROR)))
5962 (?/
5963 ;; end tag
5964 (setq c (js2-get-char)) ;; skip /
5965 (js2-add-to-string c)
5966 (when (zerop js2-ts-xml-open-tags-count)
5967 (js2-xml-discard-string)
5968 (throw 'return js2-ERROR))
5969 (setq js2-ts-xml-is-tag-content t)
5970 (decf js2-ts-xml-open-tags-count))
5971 (t
5972 ;; start tag
5973 (setq js2-ts-xml-is-tag-content t)
5974 (incf js2-ts-xml-open-tags-count))))
5975 (?{
5976 (js2-unget-char)
5977 (setq js2-ts-string (js2-get-string-from-buffer))
5978 (throw 'return js2-XML))
5979 (t
5980 (js2-add-to-string c))))))))
5981 (setq js2-token-end js2-ts-cursor)
5982 result))
5983
5984 (defun js2-read-quoted-string (quote)
5985 (let (c)
5986 (catch 'return
5987 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
5988 (js2-add-to-string c)
5989 (if (eq c quote)
5990 (throw 'return t)))
5991 (js2-xml-discard-string) ;; throw away string in progress
5992 nil)))
5993
5994 (defun js2-read-xml-comment ()
5995 (let ((c (js2-get-char)))
5996 (catch 'return
5997 (while (/= c js2-EOF_CHAR)
5998 (catch 'continue
5999 (js2-add-to-string c)
6000 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6001 (setq c (js2-get-char))
6002 (js2-add-to-string c)
6003 (if (eq (js2-peek-char) ?>)
6004 (progn
6005 (setq c (js2-get-char)) ;; skip >
6006 (js2-add-to-string c)
6007 (throw 'return t))
6008 (throw 'continue nil)))
6009 (setq c (js2-get-char))))
6010 (js2-xml-discard-string)
6011 nil)))
6012
6013 (defun js2-read-cdata ()
6014 (let ((c (js2-get-char)))
6015 (catch 'return
6016 (while (/= c js2-EOF_CHAR)
6017 (catch 'continue
6018 (js2-add-to-string c)
6019 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6020 (setq c (js2-get-char))
6021 (js2-add-to-string c)
6022 (if (eq (js2-peek-char) ?>)
6023 (progn
6024 (setq c (js2-get-char)) ;; Skip >
6025 (js2-add-to-string c)
6026 (throw 'return t))
6027 (throw 'continue nil)))
6028 (setq c (js2-get-char))))
6029 (js2-xml-discard-string)
6030 nil)))
6031
6032 (defun js2-read-entity ()
6033 (let ((decl-tags 1)
6034 c)
6035 (catch 'return
6036 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6037 (js2-add-to-string c)
6038 (case c
6039 (?<
6040 (incf decl-tags))
6041 (?>
6042 (decf decl-tags)
6043 (if (zerop decl-tags)
6044 (throw 'return t)))))
6045 (js2-xml-discard-string)
6046 nil)))
6047
6048 (defun js2-read-PI ()
6049 "Scan an XML processing instruction."
6050 (let (c)
6051 (catch 'return
6052 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6053 (js2-add-to-string c)
6054 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6055 (setq c (js2-get-char)) ;; Skip >
6056 (js2-add-to-string c)
6057 (throw 'return t)))
6058 (js2-xml-discard-string)
6059 nil)))
6060
6061 (defun js2-scanner-get-line ()
6062 "Return the text of the current scan line."
6063 (buffer-substring (point-at-bol) (point-at-eol)))
6064
6065 ;;; Highlighting
6066
6067 (defun js2-set-face (beg end face &optional record)
6068 "Fontify a region. If RECORD is non-nil, record for later."
6069 (when (plusp js2-highlight-level)
6070 (setq beg (min (point-max) beg)
6071 beg (max (point-min) beg)
6072 end (min (point-max) end)
6073 end (max (point-min) end))
6074 (if record
6075 (push (list beg end face) js2-mode-fontifications)
6076 (put-text-property beg end 'font-lock-face face))))
6077
6078 (defun js2-set-kid-face (pos kid len face)
6079 "Set-face on a child node.
6080 POS is absolute buffer position of parent.
6081 KID is the child node.
6082 LEN is the length to fontify.
6083 FACE is the face to fontify with."
6084 (js2-set-face (+ pos (js2-node-pos kid))
6085 (+ pos (js2-node-pos kid) (js2-node-len kid))
6086 face))
6087
6088 (defsubst js2-fontify-kwd (start length)
6089 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6090
6091 (defsubst js2-clear-face (beg end)
6092 (remove-text-properties beg end '(font-lock-face nil
6093 help-echo nil
6094 point-entered nil
6095 c-in-sws nil)))
6096
6097 (defconst js2-ecma-global-props
6098 (concat "^"
6099 (regexp-opt
6100 '("Infinity" "NaN" "undefined" "arguments") t)
6101 "$")
6102 "Value properties of the Ecma-262 Global Object.
6103 Shown at or above `js2-highlight-level' 2.")
6104
6105 ;; might want to add the name "arguments" to this list?
6106 (defconst js2-ecma-object-props
6107 (concat "^"
6108 (regexp-opt
6109 '("prototype" "__proto__" "__parent__") t)
6110 "$")
6111 "Value properties of the Ecma-262 Object constructor.
6112 Shown at or above `js2-highlight-level' 2.")
6113
6114 (defconst js2-ecma-global-funcs
6115 (concat
6116 "^"
6117 (regexp-opt
6118 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6119 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6120 "$")
6121 "Function properties of the Ecma-262 Global object.
6122 Shown at or above `js2-highlight-level' 2.")
6123
6124 (defconst js2-ecma-number-props
6125 (concat "^"
6126 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6127 "NEGATIVE_INFINITY"
6128 "POSITIVE_INFINITY") t)
6129 "$")
6130 "Properties of the Ecma-262 Number constructor.
6131 Shown at or above `js2-highlight-level' 2.")
6132
6133 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6134 "Properties of the Ecma-262 Date constructor.
6135 Shown at or above `js2-highlight-level' 2.")
6136
6137 (defconst js2-ecma-math-props
6138 (concat "^"
6139 (regexp-opt
6140 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6141 t)
6142 "$")
6143 "Properties of the Ecma-262 Math object.
6144 Shown at or above `js2-highlight-level' 2.")
6145
6146 (defconst js2-ecma-math-funcs
6147 (concat "^"
6148 (regexp-opt
6149 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6150 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6151 "$")
6152 "Function properties of the Ecma-262 Math object.
6153 Shown at or above `js2-highlight-level' 2.")
6154
6155 (defconst js2-ecma-function-props
6156 (concat
6157 "^"
6158 (regexp-opt
6159 '(;; properties of the Object prototype object
6160 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6161 "toLocaleString" "toString" "valueOf"
6162 ;; properties of the Function prototype object
6163 "apply" "call"
6164 ;; properties of the Array prototype object
6165 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6166 "splice" "unshift"
6167 ;; properties of the String prototype object
6168 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6169 "localeCompare" "match" "replace" "search" "split" "substring"
6170 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6171 "toUpperCase"
6172 ;; properties of the Number prototype object
6173 "toExponential" "toFixed" "toPrecision"
6174 ;; properties of the Date prototype object
6175 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6176 "getMinutes" "getMonth" "getSeconds" "getTime"
6177 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6178 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6179 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6180 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6181 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6182 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6183 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6184 "toTimeString" "toUTCString"
6185 ;; properties of the RegExp prototype object
6186 "exec" "test"
6187 ;; properties of the JSON prototype object
6188 "parse" "stringify"
6189 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6190 "toSource" "__defineGetter__" "__defineSetter__"
6191 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6192 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6193 t)
6194 "$")
6195 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6196 Shown at or above `js2-highlight-level' 3.")
6197
6198 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6199 (let ((target-name (and target
6200 (js2-name-node-p target)
6201 (js2-name-node-name target)))
6202 (prop-name (if prop (js2-name-node-name prop)))
6203 (level1 (>= js2-highlight-level 1))
6204 (level2 (>= js2-highlight-level 2))
6205 (level3 (>= js2-highlight-level 3))
6206 pos face)
6207 (when level2
6208 (if call-p
6209 (cond
6210 ((and target prop)
6211 (cond
6212 ((and level3 (string-match js2-ecma-function-props prop-name))
6213 (setq face 'font-lock-builtin-face))
6214 ((and target-name prop)
6215 (cond
6216 ((string= target-name "Date")
6217 (if (string-match js2-ecma-date-props prop-name)
6218 (setq face 'font-lock-builtin-face)))
6219 ((string= target-name "Math")
6220 (if (string-match js2-ecma-math-funcs prop-name)
6221 (setq face 'font-lock-builtin-face)))))))
6222 (prop
6223 (if (string-match js2-ecma-global-funcs prop-name)
6224 (setq face 'font-lock-builtin-face))))
6225 (cond
6226 ((and target prop)
6227 (cond
6228 ((string= target-name "Number")
6229 (if (string-match js2-ecma-number-props prop-name)
6230 (setq face 'font-lock-constant-face)))
6231 ((string= target-name "Math")
6232 (if (string-match js2-ecma-math-props prop-name)
6233 (setq face 'font-lock-constant-face)))))
6234 (prop
6235 (if (string-match js2-ecma-object-props prop-name)
6236 (setq face 'font-lock-constant-face)))))
6237 (when face
6238 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6239 (js2-node-pos prop))) ; relative
6240 (+ pos (js2-node-len prop))
6241 face 'record)))))
6242
6243 (defun js2-parse-highlight-member-expr-node (node)
6244 "Perform syntax highlighting of EcmaScript built-in properties.
6245 The variable `js2-highlight-level' governs this highighting."
6246 (let (face target prop name pos end parent call-p callee)
6247 (cond
6248 ;; case 1: simple name, e.g. foo
6249 ((js2-name-node-p node)
6250 (setq name (js2-name-node-name node))
6251 ;; possible for name to be nil in rare cases - saw it when
6252 ;; running js2-mode on an elisp buffer. Might as well try to
6253 ;; make it so js2-mode never barfs.
6254 (when name
6255 (setq face (if (string-match js2-ecma-global-props name)
6256 'font-lock-constant-face))
6257 (when face
6258 (setq pos (js2-node-pos node)
6259 end (+ pos (js2-node-len node)))
6260 (js2-set-face pos end face 'record))))
6261 ;; case 2: property access or function call
6262 ((or (js2-prop-get-node-p node)
6263 ;; highlight function call if expr is a prop-get node
6264 ;; or a plain name (i.e. unqualified function call)
6265 (and (setq call-p (js2-call-node-p node))
6266 (setq callee (js2-call-node-target node)) ; separate setq!
6267 (or (js2-prop-get-node-p callee)
6268 (js2-name-node-p callee))))
6269 (setq parent node
6270 node (if call-p callee node))
6271 (if (and call-p (js2-name-node-p callee))
6272 (setq prop callee)
6273 (setq target (js2-prop-get-node-left node)
6274 prop (js2-prop-get-node-right node)))
6275 (cond
6276 ((js2-name-node-p target)
6277 (if (js2-name-node-p prop)
6278 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6279 (js2-parse-highlight-prop-get parent target prop call-p)
6280 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6281 (js2-parse-highlight-prop-get parent target nil call-p)))
6282 ((js2-name-node-p prop)
6283 ;; case 2c: complex target, simple name, e.g. x[y].bar
6284 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6285
6286 (defun js2-parse-highlight-member-expr-fn-name (expr)
6287 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6288 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6289 We currently only handle the case where the last component is a prop-get
6290 of a simple name. Called before EXPR has a parent node."
6291 (let (pos
6292 (name (and (js2-prop-get-node-p expr)
6293 (js2-prop-get-node-right expr))))
6294 (when (js2-name-node-p name)
6295 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6296 (js2-node-pos name)))
6297 (+ pos (js2-node-len name))
6298 'font-lock-function-name-face
6299 'record))))
6300
6301 ;; source: http://jsdoc.sourceforge.net/
6302 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6303 ;; allows type specifications, and needs work before entering the wild.
6304
6305 (defconst js2-jsdoc-param-tag-regexp
6306 (concat "^\\s-*\\*+\\s-*\\(@"
6307 "\\(?:param\\|argument\\)"
6308 "\\)"
6309 "\\s-*\\({[^}]+}\\)?" ; optional type
6310 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6311 "\\>")
6312 "Matches jsdoc tags with optional type and optional param name.")
6313
6314 (defconst js2-jsdoc-typed-tag-regexp
6315 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6316 (regexp-opt
6317 '("enum"
6318 "extends"
6319 "field"
6320 "id"
6321 "implements"
6322 "lends"
6323 "mods"
6324 "requires"
6325 "return"
6326 "returns"
6327 "throw"
6328 "throws"))
6329 "\\)\\)\\s-*\\({[^}]+}\\)?")
6330 "Matches jsdoc tags with optional type.")
6331
6332 (defconst js2-jsdoc-arg-tag-regexp
6333 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6334 (regexp-opt
6335 '("alias"
6336 "augments"
6337 "borrows"
6338 "bug"
6339 "base"
6340 "config"
6341 "default"
6342 "define"
6343 "exception"
6344 "function"
6345 "member"
6346 "memberOf"
6347 "name"
6348 "namespace"
6349 "property"
6350 "since"
6351 "suppress"
6352 "this"
6353 "throws"
6354 "type"
6355 "version"))
6356 "\\)\\)\\s-+\\([^ \t]+\\)")
6357 "Matches jsdoc tags with a single argument.")
6358
6359 (defconst js2-jsdoc-empty-tag-regexp
6360 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6361 (regexp-opt
6362 '("addon"
6363 "author"
6364 "class"
6365 "const"
6366 "constant"
6367 "constructor"
6368 "constructs"
6369 "deprecated"
6370 "desc"
6371 "description"
6372 "event"
6373 "example"
6374 "exec"
6375 "export"
6376 "fileoverview"
6377 "final"
6378 "function"
6379 "hidden"
6380 "ignore"
6381 "implicitCast"
6382 "inheritDoc"
6383 "inner"
6384 "interface"
6385 "license"
6386 "noalias"
6387 "noshadow"
6388 "notypecheck"
6389 "override"
6390 "owner"
6391 "preserve"
6392 "preserveTry"
6393 "private"
6394 "protected"
6395 "public"
6396 "static"
6397 "supported"
6398 ))
6399 "\\)\\)\\s-*")
6400 "Matches empty jsdoc tags.")
6401
6402 (defconst js2-jsdoc-link-tag-regexp
6403 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6404 "Matches a jsdoc link or code tag.")
6405
6406 (defconst js2-jsdoc-see-tag-regexp
6407 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6408 "Matches a jsdoc @see tag.")
6409
6410 (defconst js2-jsdoc-html-tag-regexp
6411 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6412 "Matches a simple (no attributes) html start- or end-tag.")
6413
6414 (defun js2-jsdoc-highlight-helper ()
6415 (js2-set-face (match-beginning 1)
6416 (match-end 1)
6417 'js2-jsdoc-tag)
6418 (if (match-beginning 2)
6419 (if (save-excursion
6420 (goto-char (match-beginning 2))
6421 (= (char-after) ?{))
6422 (js2-set-face (1+ (match-beginning 2))
6423 (1- (match-end 2))
6424 'js2-jsdoc-type)
6425 (js2-set-face (match-beginning 2)
6426 (match-end 2)
6427 'js2-jsdoc-value)))
6428 (if (match-beginning 3)
6429 (js2-set-face (match-beginning 3)
6430 (match-end 3)
6431 'js2-jsdoc-value)))
6432
6433 (defun js2-highlight-jsdoc (ast)
6434 "Highlight doc comment tags."
6435 (let ((comments (js2-ast-root-comments ast))
6436 beg end)
6437 (save-excursion
6438 (dolist (node comments)
6439 (when (eq (js2-comment-node-format node) 'jsdoc)
6440 (setq beg (js2-node-abs-pos node)
6441 end (+ beg (js2-node-len node)))
6442 (save-restriction
6443 (narrow-to-region beg end)
6444 (dolist (re (list js2-jsdoc-param-tag-regexp
6445 js2-jsdoc-typed-tag-regexp
6446 js2-jsdoc-arg-tag-regexp
6447 js2-jsdoc-link-tag-regexp
6448 js2-jsdoc-see-tag-regexp
6449 js2-jsdoc-empty-tag-regexp))
6450 (goto-char beg)
6451 (while (re-search-forward re nil t)
6452 (js2-jsdoc-highlight-helper)))
6453 ;; simple highlighting for html tags
6454 (goto-char beg)
6455 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6456 (js2-set-face (match-beginning 1)
6457 (match-end 1)
6458 'js2-jsdoc-html-tag-delimiter)
6459 (js2-set-face (match-beginning 2)
6460 (match-end 2)
6461 'js2-jsdoc-html-tag-name)
6462 (js2-set-face (match-beginning 3)
6463 (match-end 3)
6464 'js2-jsdoc-html-tag-delimiter))))))))
6465
6466 (defun js2-highlight-assign-targets (node left right)
6467 "Highlight function properties and external variables."
6468 (let (leftpos end name)
6469 ;; highlight vars and props assigned function values
6470 (when (js2-function-node-p right)
6471 (cond
6472 ;; var foo = function() {...}
6473 ((js2-name-node-p left)
6474 (setq name left))
6475 ;; foo.bar.baz = function() {...}
6476 ((and (js2-prop-get-node-p left)
6477 (js2-name-node-p (js2-prop-get-node-right left)))
6478 (setq name (js2-prop-get-node-right left))))
6479 (when name
6480 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6481 (+ leftpos (js2-node-len name))
6482 'font-lock-function-name-face
6483 'record)))))
6484
6485 (defun js2-record-name-node (node)
6486 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6487 later. NODE must be a name node."
6488 (let (leftpos end)
6489 (push (list node js2-current-scope
6490 (setq leftpos (js2-node-abs-pos node))
6491 (setq end (+ leftpos (js2-node-len node))))
6492 js2-recorded-identifiers)))
6493
6494 (defun js2-highlight-undeclared-vars ()
6495 "After entire parse is finished, look for undeclared variable references.
6496 We have to wait until entire buffer is parsed, since JavaScript permits var
6497 decls to occur after they're used.
6498
6499 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6500 it is considered declared."
6501 (let (name)
6502 (dolist (entry js2-recorded-identifiers)
6503 (destructuring-bind (name-node scope pos end) entry
6504 (setq name (js2-name-node-name name-node))
6505 (unless (or (member name js2-global-externs)
6506 (member name js2-default-externs)
6507 (member name js2-additional-externs)
6508 (js2-get-defining-scope scope name))
6509 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6510 'js2-external-variable))))
6511 (setq js2-recorded-identifiers nil)))
6512
6513 ;;; IMenu support
6514
6515 ;; We currently only support imenu, but eventually should support speedbar and
6516 ;; possibly other browsing mechanisms.
6517
6518 ;; The basic strategy is to identify function assignment targets of the form
6519 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6520 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6521 ;; for imenu after parsing is finished.
6522
6523 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6524 ;; JavaScript, and the general problem is undecidable. However, several forms
6525 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6526 ;; include:
6527
6528 ;; function foo() -- function declaration
6529 ;; foo = function() -- function expression assigned to variable
6530 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6531 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6532 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6533 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6534 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6535 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6536 ;; function foo() {function bar() {...}} -- nested function
6537 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6538
6539 ;; This list boils down to a few forms that can be combined recursively.
6540 ;; Top-level named function declarations include both the left-hand (name)
6541 ;; and the right-hand (function value) expressions needed to produce an imenu
6542 ;; entry. The other "right-hand" forms we need to look for are:
6543 ;; - functions declared as props/getters/setters in object literals
6544 ;; - nested named function declarations
6545 ;; The "left-hand" expressions that functions can be assigned to include:
6546 ;; - local/global variables
6547 ;; - nested property-get expressions like a.b.c.d
6548 ;; - element gets like foo[10] or foo['bar'] where the index
6549 ;; expression can be trivially converted to a property name. They
6550 ;; effectively then become property gets.
6551
6552 ;; All the different definition types are canonicalized into the form
6553 ;; foo.bar.baz = position-of-function-keyword
6554
6555 ;; We need to build a trie-like structure for imenu. As an example,
6556 ;; consider the following JavaScript code:
6557
6558 ;; a = function() {...} // function at position 5
6559 ;; b = function() {...} // function at position 25
6560 ;; foo = function() {...} // function at position 100
6561 ;; foo.bar = function() {...} // function at position 200
6562 ;; foo.bar.baz = function() {...} // function at position 300
6563 ;; foo.bar.zab = function() {...} // function at position 400
6564
6565 ;; During parsing we accumulate an entry for each definition in
6566 ;; the variable `js2-imenu-recorder', like so:
6567
6568 ;; '((fn a 5)
6569 ;; (fn b 25)
6570 ;; (fn foo 100)
6571 ;; (fn foo bar 200)
6572 ;; (fn foo bar baz 300)
6573 ;; (fn foo bar zab 400))
6574
6575 ;; Where 'fn' is the respective function node.
6576 ;; After parsing these entries are merged into this alist-trie:
6577
6578 ;; '((a . 1)
6579 ;; (b . 2)
6580 ;; (foo (<definition> . 3)
6581 ;; (bar (<definition> . 6)
6582 ;; (baz . 100)
6583 ;; (zab . 200))))
6584
6585 ;; Note the wacky need for a <definition> name. The token can be anything
6586 ;; that isn't a valid JavaScript identifier, because you might make foo
6587 ;; a function and then start setting properties on it that are also functions.
6588
6589 (defun js2-prop-node-name (node)
6590 "Return the name of a node that may be a property-get/property-name.
6591 If NODE is not a valid name-node, string-node or integral number-node,
6592 returns nil. Otherwise returns the string name/value of the node."
6593 (cond
6594 ((js2-name-node-p node)
6595 (js2-name-node-name node))
6596 ((js2-string-node-p node)
6597 (js2-string-node-value node))
6598 ((and (js2-number-node-p node)
6599 (string-match "^[0-9]+$" (js2-number-node-value node)))
6600 (js2-number-node-value node))
6601 ((js2-this-node-p node)
6602 "this")))
6603
6604 (defun js2-node-qname-component (node)
6605 "Return the name of this node, if it contributes to a qname.
6606 Returns nil if the node doesn't contribute."
6607 (copy-sequence
6608 (or (js2-prop-node-name node)
6609 (if (and (js2-function-node-p node)
6610 (js2-function-node-name node))
6611 (js2-name-node-name (js2-function-node-name node))))))
6612
6613 (defun js2-record-imenu-entry (fn-node qname pos)
6614 "Add an entry to `js2-imenu-recorder'.
6615 FN-NODE should be the current item's function node.
6616
6617 Associate FN-NODE with its QNAME for later lookup.
6618 This is used in postprocessing the chain list. For each chain, we find
6619 the parent function, look up its qname, then prepend a copy of it to the chain."
6620 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6621 (unless js2-imenu-function-map
6622 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6623 (puthash fn-node qname js2-imenu-function-map))
6624
6625 (defun js2-record-imenu-functions (node &optional var)
6626 "Record function definitions for imenu.
6627 NODE is a function node or an object literal.
6628 VAR, if non-nil, is the expression that NODE is being assigned to.
6629 When passed arguments of wrong type, does nothing."
6630 (when js2-parse-ide-mode
6631 (let ((fun-p (js2-function-node-p node))
6632 qname left fname-node pos)
6633 (cond
6634 ;; non-anonymous function declaration?
6635 ((and fun-p
6636 (not var)
6637 (setq fname-node (js2-function-node-name node)))
6638 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6639 ;; for remaining forms, compute left-side tree branch first
6640 ((and var (setq qname (js2-compute-nested-prop-get var)))
6641 (cond
6642 ;; foo.bar.baz = function
6643 (fun-p
6644 (js2-record-imenu-entry node qname (js2-node-pos node)))
6645 ;; foo.bar.baz = object-literal
6646 ;; look for nested functions: {a: {b: function() {...} }}
6647 ((js2-object-node-p node)
6648 ;; Node position here is still absolute, since the parser
6649 ;; passes the assignment target and value expressions
6650 ;; to us before they are added as children of the assignment node.
6651 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6652
6653 (defun js2-compute-nested-prop-get (node)
6654 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6655 component nodes as a list. Otherwise return nil. Element-gets are treated
6656 as property-gets if the index expression is a string, or a positive integer."
6657 (let (left right head)
6658 (cond
6659 ((or (js2-name-node-p node)
6660 (js2-this-node-p node))
6661 (list node))
6662 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6663 ((js2-prop-get-node-p node) ; foo.bar
6664 (setq left (js2-prop-get-node-left node)
6665 right (js2-prop-get-node-right node))
6666 (if (setq head (js2-compute-nested-prop-get left))
6667 (nconc head (list right))))
6668 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6669 (setq left (js2-elem-get-node-target node)
6670 right (js2-elem-get-node-element node))
6671 (if (or (js2-string-node-p right) ; ['bar']
6672 (and (js2-number-node-p right) ; [10]
6673 (string-match "^[0-9]+$"
6674 (js2-number-node-value right))))
6675 (if (setq head (js2-compute-nested-prop-get left))
6676 (nconc head (list right))))))))
6677
6678 (defun js2-record-object-literal (node qname pos)
6679 "Recursively process an object literal looking for functions.
6680 NODE is an object literal that is the right-hand child of an assignment
6681 expression. QNAME is a list of nodes representing the assignment target,
6682 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6683 POS is the absolute position of the node.
6684 We do a depth-first traversal of NODE. For any functions we find,
6685 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6686 (let (left right prop-qname)
6687 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6688 (let ((left (js2-infix-node-left e))
6689 ;; Element positions are relative to the parent position.
6690 (pos (+ pos (js2-node-pos e))))
6691 (cond
6692 ;; foo: function() {...}
6693 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6694 (when (js2-prop-node-name left)
6695 ;; As a policy decision, we record the position of the property,
6696 ;; not the position of the `function' keyword, since the property
6697 ;; is effectively the name of the function.
6698 (js2-record-imenu-entry right (append qname (list left)) pos)))
6699 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6700 ((js2-object-node-p right)
6701 (js2-record-object-literal right
6702 (append qname (list (js2-infix-node-left e)))
6703 (+ pos (js2-node-pos right)))))))))
6704
6705 (defun js2-node-top-level-decl-p (node)
6706 "Return t if NODE's name is defined in the top-level scope.
6707 Also returns t if NODE's name is not defined in any scope, since it implies
6708 that it's an external variable, which must also be in the top-level scope."
6709 (let* ((name (js2-prop-node-name node))
6710 (this-scope (js2-node-get-enclosing-scope node))
6711 defining-scope)
6712 (cond
6713 ((js2-this-node-p node)
6714 nil)
6715 ((null this-scope)
6716 t)
6717 ((setq defining-scope (js2-get-defining-scope this-scope name))
6718 (js2-ast-root-p defining-scope))
6719 (t t))))
6720
6721 (defun js2-wrapper-function-p (node)
6722 "Returns t if NODE is a function expression that's immediately invoked.
6723 NODE must be `js2-function-node'."
6724 (let ((parent (js2-node-parent node)))
6725 (or
6726 ;; function(){...}();
6727 (js2-call-node-p parent)
6728 (and (js2-paren-node-p parent)
6729 ;; (function(){...})();
6730 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6731 ;; (function(){...}).call(this);
6732 (and (js2-prop-get-node-p parent)
6733 (member (js2-name-node-name (js2-prop-get-node-right parent))
6734 '("call" "apply"))
6735 (js2-call-node-p (js2-node-parent parent))))))))
6736
6737 (defun js2-browse-postprocess-chains (entries)
6738 "Modify function-declaration name chains after parsing finishes.
6739 Some of the information is only available after the parse tree is complete.
6740 For instance, processing a nested scope requires a parent function node."
6741 (let (result head fn current-fn parent-qname qname p elem)
6742 (dolist (entry entries)
6743 ;; function node goes first
6744 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6745 ;; Examine head's defining scope:
6746 ;; Pre-processed chain, or top-level/external, keep as-is.
6747 (if (or (stringp head) (js2-node-top-level-decl-p head))
6748 (push chain result)
6749 (when (js2-this-node-p head)
6750 (setq chain (cdr chain))) ; discard this-node
6751 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6752 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6753 (when (eq parent-qname 'not-found)
6754 ;; anonymous function expressions are not recorded
6755 ;; during the parse, so we need to handle this case here
6756 (setq parent-qname
6757 (if (js2-wrapper-function-p fn)
6758 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6759 (if (js2-ast-root-p grandparent)
6760 nil
6761 (gethash grandparent js2-imenu-function-map 'skip)))
6762 'skip))
6763 (puthash fn parent-qname js2-imenu-function-map))
6764 (unless (eq parent-qname 'skip)
6765 ;; prefix parent fn qname to this chain.
6766 (let ((qname (append parent-qname chain)))
6767 (puthash current-fn (butlast qname) js2-imenu-function-map)
6768 (push qname result)))))))
6769 ;; finally replace each node in each chain with its name.
6770 (dolist (chain result)
6771 (setq p chain)
6772 (while p
6773 (if (js2-node-p (setq elem (car p)))
6774 (setcar p (js2-node-qname-component elem)))
6775 (setq p (cdr p))))
6776 result))
6777
6778 ;; Merge name chains into a trie-like tree structure of nested lists.
6779 ;; To simplify construction of the trie, we first build it out using the rule
6780 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6781 ;; [key, num-or-list]. The second element can be a number; if so, this key
6782 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6783 ;; associated with the key at this level.) Otherwise the second element is
6784 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6785 ;; a simple recursive formulation.
6786 ;;
6787 ;; js2-mode is building the data structure for imenu. The imenu documentation
6788 ;; claims that it's the structure above, but in practice it wants the children
6789 ;; at the same list level as the key for that level, which is how I've drawn
6790 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6791 ;; list wrapper around the children at each level.
6792 ;;
6793 ;; A completed nested imenu-alist entry looks like this:
6794 ;; '(("foo"
6795 ;; ("<definition>" . 7)
6796 ;; ("bar"
6797 ;; ("a" . 40)
6798 ;; ("b" . 60))))
6799 ;;
6800 ;; In particular, the documentation for `imenu--index-alist' says that
6801 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6802 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6803
6804 (defun js2-treeify (lst)
6805 "Convert (a b c d) to (a ((b ((c d)))))."
6806 (if (null (cddr lst)) ; list length <= 2
6807 lst
6808 (list (car lst) (list (js2-treeify (cdr lst))))))
6809
6810 (defun js2-build-alist-trie (chains trie)
6811 "Merge declaration name chains into a trie-like alist structure for imenu.
6812 CHAINS is the qname chain list produced during parsing. TRIE is a
6813 list of elements built up so far."
6814 (let (head tail pos branch kids)
6815 (dolist (chain chains)
6816 (setq head (car chain)
6817 tail (cdr chain)
6818 pos (if (numberp (car tail)) (car tail))
6819 branch (js2-find-if (lambda (n)
6820 (string= (car n) head))
6821 trie)
6822 kids (second branch))
6823 (cond
6824 ;; case 1: this key isn't in the trie yet
6825 ((null branch)
6826 (if trie
6827 (setcdr (last trie) (list (js2-treeify chain)))
6828 (setq trie (list (js2-treeify chain)))))
6829 ;; case 2: key is present with a single number entry: replace w/ list
6830 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6831 ;; ("<definition>" 20)))
6832 ((numberp kids)
6833 (setcar (cdr branch)
6834 (list (list "<definition-1>" kids)
6835 (if pos
6836 (list "<definition-2>" pos)
6837 (js2-treeify tail)))))
6838 ;; case 3: key is there (with kids), and we're a number entry
6839 (pos
6840 (setcdr (last kids)
6841 (list
6842 (list (format "<definition-%d>"
6843 (1+ (loop for kid in kids
6844 count (eq ?< (aref (car kid) 0)))))
6845 pos))))
6846 ;; case 4: key is there with kids, need to merge in our chain
6847 (t
6848 (js2-build-alist-trie (list tail) kids))))
6849 trie))
6850
6851 (defun js2-flatten-trie (trie)
6852 "Convert TRIE to imenu-format.
6853 Recurses through nodes, and for each one whose second element is a list,
6854 appends the list's flattened elements to the current element. Also
6855 changes the tails into conses. For instance, this pre-flattened trie
6856
6857 '(a ((b 20)
6858 (c ((d 30)
6859 (e 40)))))
6860
6861 becomes
6862
6863 '(a (b . 20)
6864 (c (d . 30)
6865 (e . 40)))
6866
6867 Note that the root of the trie has no key, just a list of chains.
6868 This is also true for the value of any key with multiple children,
6869 e.g. key 'c' in the example above."
6870 (cond
6871 ((listp (car trie))
6872 (mapcar #'js2-flatten-trie trie))
6873 (t
6874 (if (numberp (second trie))
6875 (cons (car trie) (second trie))
6876 ;; else pop list and append its kids
6877 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6878
6879 (defun js2-build-imenu-index ()
6880 "Turn `js2-imenu-recorder' into an imenu data structure."
6881 (unless (eq js2-imenu-recorder 'empty)
6882 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
6883 (result (js2-build-alist-trie chains nil)))
6884 (js2-flatten-trie result))))
6885
6886 (defun js2-test-print-chains (chains)
6887 "Print a list of qname chains.
6888 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
6889 i.e. one or more nodes, and an integer position as the list tail."
6890 (mapconcat (lambda (chain)
6891 (concat "("
6892 (mapconcat (lambda (elem)
6893 (if (js2-node-p elem)
6894 (or (js2-node-qname-component elem)
6895 "nil")
6896 (number-to-string elem)))
6897 chain
6898 " ")
6899 ")"))
6900 chains
6901 "\n"))
6902
6903 ;;; Parser
6904
6905 (defconst js2-version "1.8.0"
6906 "Version of JavaScript supported, plus minor js2 version.")
6907
6908 (defmacro js2-record-face (face)
6909 "Record a style run of FACE for the current token."
6910 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
6911
6912 (defsubst js2-node-end (n)
6913 "Computes the absolute end of node N.
6914 Use with caution! Assumes `js2-node-pos' is -absolute-, which
6915 is only true until the node is added to its parent; i.e., while parsing."
6916 (+ (js2-node-pos n)
6917 (js2-node-len n)))
6918
6919 (defun js2-record-comment ()
6920 "Record a comment in `js2-scanned-comments'."
6921 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
6922 :format js2-ts-comment-type)
6923 js2-scanned-comments)
6924 (when js2-parse-ide-mode
6925 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
6926 'font-lock-doc-face
6927 'font-lock-comment-face))
6928 (when (memq js2-ts-comment-type '(html preprocessor))
6929 ;; Tell cc-engine the bounds of the comment.
6930 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
6931
6932 ;; This function is called depressingly often, so it should be fast.
6933 ;; Most of the time it's looking at the same token it peeked before.
6934 (defun js2-peek-token ()
6935 "Return the next token without consuming it.
6936 If previous token was consumed, calls scanner to get new token.
6937 If previous token was -not- consumed, returns it (idempotent).
6938
6939 This function will not return a newline (js2-EOL) - instead, it
6940 gobbles newlines until it finds a non-newline token, and flags
6941 that token as appearing just after a newline.
6942
6943 This function will also not return a js2-COMMENT. Instead, it
6944 records comments found in `js2-scanned-comments'. If the token
6945 returned by this function immediately follows a jsdoc comment,
6946 the token is flagged as such.
6947
6948 Note that this function always returned the un-flagged token!
6949 The flags, if any, are saved in `js2-current-flagged-token'."
6950 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
6951 js2-current-token ; most common case - return already-peeked token
6952 (let ((tt (js2-get-token)) ; call scanner
6953 saw-eol
6954 face)
6955 ;; process comments and whitespace
6956 (while (or (= tt js2-EOL)
6957 (= tt js2-COMMENT))
6958 (if (= tt js2-EOL)
6959 (setq saw-eol t)
6960 (setq saw-eol nil)
6961 (if js2-record-comments
6962 (js2-record-comment)))
6963 (setq tt (js2-get-token))) ; call scanner
6964 (setq js2-current-token tt
6965 js2-current-flagged-token (if saw-eol
6966 (logior tt js2-ti-after-eol)
6967 tt))
6968 ;; perform lexical fontification as soon as token is scanned
6969 (when js2-parse-ide-mode
6970 (cond
6971 ((minusp tt)
6972 (js2-record-face 'js2-error))
6973 ((setq face (aref js2-kwd-tokens tt))
6974 (js2-record-face face))
6975 ((and (= tt js2-NAME)
6976 (equal js2-ts-string "undefined"))
6977 (js2-record-face 'font-lock-constant-face))))
6978 tt))) ; return unflagged token
6979
6980 (defun js2-peek-flagged-token ()
6981 "Returns the current token along with any flags set for it."
6982 (js2-peek-token)
6983 js2-current-flagged-token)
6984
6985 (defsubst js2-consume-token ()
6986 (setq js2-current-flagged-token js2-EOF))
6987
6988 (defun js2-next-token ()
6989 (prog1
6990 (js2-peek-token)
6991 (js2-consume-token)))
6992
6993 (defun js2-next-flagged-token ()
6994 (js2-peek-token)
6995 (prog1 js2-current-flagged-token
6996 (js2-consume-token)))
6997
6998 (defun js2-match-token (match)
6999 "Consume and return t if next token matches MATCH, a bytecode.
7000 Returns nil and consumes nothing if MATCH is not the next token."
7001 (if (/= (js2-peek-token) match)
7002 nil
7003 (js2-consume-token)
7004 t))
7005
7006 (defun js2-match-contextual-kwd (name)
7007 "Consume and return t if next token is `js2-NAME', and its
7008 string is NAME. Returns nil and does nothing otherwise."
7009 (if (or (/= (js2-peek-token) js2-NAME)
7010 (not (string= js2-ts-string name)))
7011 nil
7012 (js2-consume-token)
7013 (js2-record-face 'font-lock-keyword-face)
7014 t))
7015
7016 (defun js2-valid-prop-name-token (tt)
7017 (or (= tt js2-NAME)
7018 (when (and js2-allow-keywords-as-property-names
7019 (plusp tt)
7020 (aref js2-kwd-tokens tt))
7021 (js2-save-name-token-data js2-token-beg (js2-token-name tt))
7022 t)))
7023
7024 (defun js2-match-prop-name ()
7025 "Consume token and return t if next token is a valid property name.
7026 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7027 is non-nil and it's a keyword token."
7028 (if (js2-valid-prop-name-token (js2-peek-token))
7029 (progn
7030 (js2-consume-token)
7031 t)
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 current token immediately follows a newline.
7042 Else returns the current 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-peek-token)))
7047 ;; Check for last peeked token flags
7048 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7049 js2-EOL
7050 tt)))
7051
7052 (defun js2-set-check-for-label ()
7053 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7054 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7055
7056 (defun js2-must-match (token msg-id &optional pos len)
7057 "Match next token to token code TOKEN, or record a syntax error.
7058 MSG-ID is the error message to report if the match fails.
7059 Returns t on match, nil if no match."
7060 (if (js2-match-token token)
7061 t
7062 (js2-report-error msg-id nil pos len)
7063 nil))
7064
7065 (defsubst js2-inside-function ()
7066 (plusp js2-nesting-of-function))
7067
7068 (defun js2-set-requires-activation ()
7069 (if (js2-function-node-p js2-current-script-or-fn)
7070 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7071
7072 (defun js2-check-activation-name (name token)
7073 (when (js2-inside-function)
7074 ;; skip language-version 1.2 check from Rhino
7075 (if (or (string= "arguments" name)
7076 (and js2-compiler-activation-names ; only used in codegen
7077 (gethash name js2-compiler-activation-names)))
7078 (js2-set-requires-activation))))
7079
7080 (defun js2-set-is-generator ()
7081 (if (js2-function-node-p js2-current-script-or-fn)
7082 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7083
7084 (defun js2-must-have-xml ()
7085 (unless js2-compiler-xml-available
7086 (js2-report-error "msg.XML.not.available")))
7087
7088 (defun js2-push-scope (scope)
7089 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7090 (assert (js2-scope-p scope))
7091 (assert (null (js2-scope-parent-scope scope)))
7092 (assert (not (eq js2-current-scope scope)))
7093 (setf (js2-scope-parent-scope scope) js2-current-scope
7094 js2-current-scope scope))
7095
7096 (defsubst js2-pop-scope ()
7097 (setq js2-current-scope
7098 (js2-scope-parent-scope js2-current-scope)))
7099
7100 (defun js2-enter-loop (loop-node)
7101 (push loop-node js2-loop-set)
7102 (push loop-node js2-loop-and-switch-set)
7103 (js2-push-scope loop-node)
7104 ;; Tell the current labeled statement (if any) its statement,
7105 ;; and set the jump target of the first label to the loop.
7106 ;; These are used in `js2-parse-continue' to verify that the
7107 ;; continue target is an actual labeled loop. (And for codegen.)
7108 (when js2-labeled-stmt
7109 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7110 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7111 js2-labeled-stmt))) loop-node)))
7112
7113 (defun js2-exit-loop ()
7114 (pop js2-loop-set)
7115 (pop js2-loop-and-switch-set)
7116 (js2-pop-scope))
7117
7118 (defsubst js2-enter-switch (switch-node)
7119 (push switch-node js2-loop-and-switch-set))
7120
7121 (defsubst js2-exit-switch ()
7122 (pop js2-loop-and-switch-set))
7123
7124 (defun js2-parse (&optional buf cb)
7125 "Tell the js2 parser to parse a region of JavaScript.
7126
7127 BUF is a buffer or buffer name containing the code to parse.
7128 Call `narrow-to-region' first to parse only part of the buffer.
7129
7130 The returned AST root node is given some additional properties:
7131 `node-count' - total number of nodes in the AST
7132 `buffer' - BUF. The buffer it refers to may change or be killed,
7133 so the value is not necessarily reliable.
7134
7135 An optional callback CB can be specified to report parsing
7136 progress. If `(functionp CB)' returns t, it will be called with
7137 the current line number once before parsing begins, then again
7138 each time the lexer reaches a new line number.
7139
7140 CB can also be a list of the form `(symbol cb ...)' to specify
7141 multiple callbacks with different criteria. Each symbol is a
7142 criterion keyword, and the following element is the callback to
7143 call
7144
7145 :line - called whenever the line number changes
7146 :token - called for each new token consumed
7147
7148 The list of criteria could be extended to include entering or
7149 leaving a statement, an expression, or a function definition."
7150 (if (and cb (not (functionp cb)))
7151 (error "criteria callbacks not yet implemented"))
7152 (let ((inhibit-point-motion-hooks t)
7153 (js2-compiler-xml-available (>= js2-language-version 160))
7154 ;; This is a recursive-descent parser, so give it a big stack.
7155 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7156 (max-specpdl-size (max max-specpdl-size 3000))
7157 (case-fold-search nil)
7158 ast)
7159 (message nil) ; clear any error message from previous parse
7160 (with-current-buffer (or buf (current-buffer))
7161 (setq js2-scanned-comments nil
7162 js2-parsed-errors nil
7163 js2-parsed-warnings nil
7164 js2-imenu-recorder nil
7165 js2-imenu-function-map nil
7166 js2-label-set nil)
7167 (js2-init-scanner)
7168 (setq ast (with-silent-modifications
7169 (js2-do-parse)))
7170 (unless js2-ts-hit-eof
7171 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7172 (setf (js2-ast-root-errors ast) js2-parsed-errors
7173 (js2-ast-root-warnings ast) js2-parsed-warnings)
7174 ;; if we didn't find any declarations, put a dummy in this list so we
7175 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7176 (unless js2-imenu-recorder
7177 (setq js2-imenu-recorder 'empty))
7178 (run-hooks 'js2-parse-finished-hook)
7179 ast)))
7180
7181 ;; Corresponds to Rhino's Parser.parse() method.
7182 (defun js2-do-parse ()
7183 "Parse current buffer starting from current point.
7184 Scanner should be initialized."
7185 (let ((pos js2-ts-cursor)
7186 (end js2-ts-cursor) ; in case file is empty
7187 root n tt)
7188 ;; initialize buffer-local parsing vars
7189 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7190 js2-current-script-or-fn root
7191 js2-current-scope root
7192 js2-current-flagged-token js2-EOF
7193 js2-nesting-of-function 0
7194 js2-labeled-stmt nil
7195 js2-recorded-identifiers nil) ; for js2-highlight
7196 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7197 (if (= tt js2-FUNCTION)
7198 (progn
7199 (js2-consume-token)
7200 (setq n (js2-parse-function (if js2-called-by-compile-function
7201 'FUNCTION_EXPRESSION
7202 'FUNCTION_STATEMENT))))
7203 ;; not a function - parse a statement
7204 (setq n (js2-parse-statement)))
7205 ;; add function or statement to script
7206 (setq end (js2-node-end n))
7207 (js2-block-node-push root n))
7208 ;; add comments to root in lexical order
7209 (when js2-scanned-comments
7210 ;; if we find a comment beyond end of normal kids, use its end
7211 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7212 (dolist (comment js2-scanned-comments)
7213 (push comment (js2-ast-root-comments root))
7214 (js2-node-add-children root comment)))
7215 (setf (js2-node-len root) (- end pos))
7216 ;; Give extensions a chance to muck with things before highlighting starts.
7217 (let ((js2-additional-externs js2-additional-externs))
7218 (save-excursion
7219 (dolist (callback js2-post-parse-callbacks)
7220 (funcall callback)))
7221 (js2-highlight-undeclared-vars))
7222 root))
7223
7224 (defun js2-function-parser ()
7225 (js2-consume-token)
7226 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7227
7228 (defun js2-parse-function-closure-body (fn-node)
7229 "Parse a JavaScript 1.8 function closure body."
7230 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7231 (if js2-ts-hit-eof
7232 (js2-report-error "msg.no.brace.body" nil
7233 (js2-node-pos fn-node)
7234 (- js2-ts-cursor (js2-node-pos fn-node)))
7235 (js2-node-add-children fn-node
7236 (setf (js2-function-node-body fn-node)
7237 (js2-parse-expr t))))))
7238
7239 (defun js2-parse-function-body (fn-node)
7240 (js2-must-match js2-LC "msg.no.brace.body"
7241 (js2-node-pos fn-node)
7242 (- js2-ts-cursor (js2-node-pos fn-node)))
7243 (let ((pos js2-token-beg) ; LC position
7244 (pn (make-js2-block-node)) ; starts at LC position
7245 tt
7246 end)
7247 (incf js2-nesting-of-function)
7248 (unwind-protect
7249 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7250 (= tt js2-EOF)
7251 (= tt js2-RC)))
7252 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7253 (js2-parse-statement)
7254 (js2-consume-token)
7255 (js2-parse-function 'FUNCTION_STATEMENT))))
7256 (decf js2-nesting-of-function))
7257 (setq end js2-token-end) ; assume no curly and leave at current token
7258 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7259 (setq end js2-token-end))
7260 (setf (js2-node-pos pn) pos
7261 (js2-node-len pn) (- end pos))
7262 (setf (js2-function-node-body fn-node) pn)
7263 (js2-node-add-children fn-node pn)
7264 pn))
7265
7266 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7267 "Declare and fontify destructuring parameters inside NODE.
7268 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7269 (cond
7270 ((js2-name-node-p node)
7271 (let (leftpos)
7272 (js2-define-symbol decl-type (js2-name-node-name node)
7273 node ignore-not-in-block)
7274 (when face
7275 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7276 (+ leftpos (js2-node-len node))
7277 face 'record))))
7278 ((js2-object-node-p node)
7279 (dolist (elem (js2-object-node-elems node))
7280 (js2-define-destruct-symbols
7281 (if (js2-object-prop-node-p elem)
7282 (js2-object-prop-node-right elem)
7283 ;; abbreviated destructuring {a, b}
7284 elem)
7285 decl-type face ignore-not-in-block)))
7286 ((js2-array-node-p node)
7287 (dolist (elem (js2-array-node-elems node))
7288 (when elem
7289 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7290 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7291 (js2-node-len node)))))
7292
7293 (defun js2-parse-function-params (fn-node pos)
7294 (if (js2-match-token js2-RP)
7295 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7296 (let (params len param default-found rest-param-at)
7297 (loop for tt = (js2-peek-token)
7298 do
7299 (cond
7300 ;; destructuring param
7301 ((or (= tt js2-LB) (= tt js2-LC))
7302 (when default-found
7303 (js2-report-error "msg.no.default.after.default.param"))
7304 (setq param (js2-parse-destruct-primary-expr))
7305 (js2-define-destruct-symbols param
7306 js2-LP
7307 'js2-function-param)
7308 (push param params))
7309 ;; variable name
7310 (t
7311 (when (and (>= js2-language-version 200)
7312 (js2-match-token js2-TRIPLEDOT)
7313 (not rest-param-at))
7314 ;; to report errors if there are more parameters
7315 (setq rest-param-at (length params)))
7316 (js2-must-match js2-NAME "msg.no.parm")
7317 (js2-record-face 'js2-function-param)
7318 (setq param (js2-create-name-node))
7319 (js2-define-symbol js2-LP js2-ts-string param)
7320 ;; default parameter value
7321 (when (or (and default-found
7322 (not rest-param-at)
7323 (js2-must-match js2-ASSIGN
7324 "msg.no.default.after.default.param"
7325 (js2-node-pos param)
7326 (js2-node-len param)))
7327 (and (>= js2-language-version 200)
7328 (js2-match-token js2-ASSIGN)))
7329 (let* ((pos (js2-node-pos param))
7330 (tt js2-current-token)
7331 (op-pos (- js2-token-beg pos))
7332 (left param)
7333 (right (js2-parse-assign-expr))
7334 (len (- (js2-node-end right) pos)))
7335 (setq param (make-js2-assign-node
7336 :type tt :pos pos :len len :op-pos op-pos
7337 :left left :right right)
7338 default-found t)
7339 (js2-node-add-children param left right)))
7340 (push param params)))
7341 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7342 (js2-report-error "msg.param.after.rest" nil
7343 (js2-node-pos param) (js2-node-len param)))
7344 while
7345 (js2-match-token js2-COMMA))
7346 (when (js2-must-match js2-RP "msg.no.paren.after.parms")
7347 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7348 (when rest-param-at
7349 (setf (js2-function-node-rest-p fn-node) t))
7350 (dolist (p params)
7351 (js2-node-add-children fn-node p)
7352 (push p (js2-function-node-params fn-node))))))
7353
7354 (defun js2-check-inconsistent-return-warning (fn-node name)
7355 "Possibly show inconsistent-return warning.
7356 Last token scanned is the close-curly for the function body."
7357 (when (and js2-mode-show-strict-warnings
7358 js2-strict-inconsistent-return-warning
7359 (not (js2-has-consistent-return-usage
7360 (js2-function-node-body fn-node))))
7361 ;; Have it extend from close-curly to bol or beginning of block.
7362 (let ((pos (save-excursion
7363 (goto-char js2-token-end)
7364 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7365 (point-at-bol))))
7366 (end js2-token-end))
7367 (if (plusp (js2-name-node-length name))
7368 (js2-add-strict-warning "msg.no.return.value"
7369 (js2-name-node-name name) pos end)
7370 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7371
7372 (defun js2-parse-function (function-type)
7373 "Function parser. FUNCTION-TYPE is a symbol."
7374 (let ((pos js2-token-beg) ; start of 'function' keyword
7375 name name-beg name-end fn-node lp
7376 (synthetic-type function-type)
7377 member-expr-node)
7378 ;; parse function name, expression, or non-name (anonymous)
7379 (cond
7380 ;; function foo(...)
7381 ((js2-match-token js2-NAME)
7382 (setq name (js2-create-name-node t)
7383 name-beg js2-token-beg
7384 name-end js2-token-end)
7385 (unless (js2-match-token js2-LP)
7386 (when js2-allow-member-expr-as-function-name
7387 ;; function foo.bar(...)
7388 (setq member-expr-node name
7389 name nil
7390 member-expr-node (js2-parse-member-expr-tail
7391 nil member-expr-node)))
7392 (js2-must-match js2-LP "msg.no.paren.parms")))
7393 ((js2-match-token js2-LP)
7394 nil) ; anonymous function: leave name as null
7395 (t
7396 ;; function random-member-expr(...)
7397 (when js2-allow-member-expr-as-function-name
7398 ;; Note that memberExpr can not start with '(' like
7399 ;; in function (1+2).toString(), because 'function (' already
7400 ;; processed as anonymous function
7401 (setq member-expr-node (js2-parse-member-expr)))
7402 (js2-must-match js2-LP "msg.no.paren.parms")))
7403 (if (= js2-current-token js2-LP) ; eventually matched LP?
7404 (setq lp js2-token-beg))
7405 (if member-expr-node
7406 (progn
7407 (setq synthetic-type 'FUNCTION_EXPRESSION)
7408 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7409 (if name
7410 (js2-set-face name-beg name-end
7411 'font-lock-function-name-face 'record)))
7412 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7413 (plusp (js2-name-node-length name)))
7414 ;; Function statements define a symbol in the enclosing scope
7415 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7416 (setf fn-node (make-js2-function-node :pos pos
7417 :name name
7418 :form function-type
7419 :lp (if lp (- lp pos))))
7420 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7421 ;; 1. Nested functions are not affected by the dynamic scope flag
7422 ;; as dynamic scope is already a parent of their scope.
7423 ;; 2. Functions defined under the with statement also immune to
7424 ;; this setup, in which case dynamic scope is ignored in favor
7425 ;; of the with object.
7426 (setf (js2-function-node-ignore-dynamic fn-node) t))
7427 ;; dynamically bind all the per-function variables
7428 (let ((js2-current-script-or-fn fn-node)
7429 (js2-current-scope fn-node)
7430 (js2-nesting-of-with 0)
7431 (js2-end-flags 0)
7432 js2-label-set
7433 js2-loop-set
7434 js2-loop-and-switch-set)
7435 (js2-parse-function-params fn-node pos)
7436 (if (and (>= js2-language-version 180)
7437 (/= (js2-peek-token) js2-LC))
7438 (js2-parse-function-closure-body fn-node)
7439 (js2-parse-function-body fn-node))
7440 (if name
7441 (js2-node-add-children fn-node name))
7442 (js2-check-inconsistent-return-warning fn-node name)
7443 ;; Function expressions define a name only in the body of the
7444 ;; function, and only if not hidden by a parameter name
7445 (if (and name
7446 (eq synthetic-type 'FUNCTION_EXPRESSION)
7447 (null (js2-scope-get-symbol js2-current-scope
7448 (js2-name-node-name name))))
7449 (js2-define-symbol js2-FUNCTION
7450 (js2-name-node-name name)
7451 fn-node))
7452 (if (and name
7453 (not (eq function-type 'FUNCTION_EXPRESSION)))
7454 (js2-record-imenu-functions fn-node)))
7455 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7456 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7457 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7458 ;; We wait until after parsing the function to set its parent scope,
7459 ;; since `js2-define-symbol' needs the defining-scope check to stop
7460 ;; at the function boundary when checking for redeclarations.
7461 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7462 fn-node))
7463
7464 (defun js2-parse-statements (&optional parent)
7465 "Parse a statement list. Last token consumed must be js2-LC.
7466
7467 PARENT can be a `js2-block-node', in which case the statements are
7468 appended to PARENT. Otherwise a new `js2-block-node' is created
7469 and returned.
7470
7471 This function does not match the closing js2-RC: the caller
7472 matches the RC so it can provide a suitable error message if not
7473 matched. This means it's up to the caller to set the length of
7474 the node to include the closing RC. The node start pos is set to
7475 the absolute buffer start position, and the caller should fix it
7476 up to be relative to the parent node. All children of this block
7477 node are given relative start positions and correct lengths."
7478 (let ((pn (or parent (make-js2-block-node)))
7479 tt)
7480 (setf (js2-node-pos pn) js2-token-beg)
7481 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7482 (/= tt js2-RC))
7483 (js2-block-node-push pn (js2-parse-statement)))
7484 pn))
7485
7486 (defun js2-parse-statement ()
7487 (let (tt pn beg end)
7488 ;; coarse-grained user-interrupt check - needs work
7489 (and js2-parse-interruptable-p
7490 (zerop (% (incf js2-parse-stmt-count)
7491 js2-statements-per-pause))
7492 (input-pending-p)
7493 (throw 'interrupted t))
7494 (setq pn (js2-statement-helper))
7495 ;; no-side-effects warning check
7496 (unless (js2-node-has-side-effects pn)
7497 (setq end (js2-node-end pn))
7498 (save-excursion
7499 (goto-char end)
7500 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7501 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7502 pn))
7503
7504 ;; These correspond to the switch cases in Parser.statementHelper
7505 (defconst js2-parsers
7506 (let ((parsers (make-vector js2-num-tokens
7507 #'js2-parse-expr-stmt)))
7508 (aset parsers js2-BREAK #'js2-parse-break)
7509 (aset parsers js2-CONST #'js2-parse-const-var)
7510 (aset parsers js2-CONTINUE #'js2-parse-continue)
7511 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7512 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7513 (aset parsers js2-DO #'js2-parse-do)
7514 (aset parsers js2-FOR #'js2-parse-for)
7515 (aset parsers js2-FUNCTION #'js2-function-parser)
7516 (aset parsers js2-IF #'js2-parse-if)
7517 (aset parsers js2-LC #'js2-parse-block)
7518 (aset parsers js2-LET #'js2-parse-let-stmt)
7519 (aset parsers js2-NAME #'js2-parse-name-or-label)
7520 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7521 (aset parsers js2-SEMI #'js2-parse-semi)
7522 (aset parsers js2-SWITCH #'js2-parse-switch)
7523 (aset parsers js2-THROW #'js2-parse-throw)
7524 (aset parsers js2-TRY #'js2-parse-try)
7525 (aset parsers js2-VAR #'js2-parse-const-var)
7526 (aset parsers js2-WHILE #'js2-parse-while)
7527 (aset parsers js2-WITH #'js2-parse-with)
7528 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7529 parsers)
7530 "A vector mapping token types to parser functions.")
7531
7532 (defun js2-parse-warn-missing-semi (beg end)
7533 (and js2-mode-show-strict-warnings
7534 js2-strict-missing-semi-warning
7535 (js2-add-strict-warning
7536 "msg.missing.semi" nil
7537 ;; back up to beginning of statement or line
7538 (max beg (save-excursion
7539 (goto-char end)
7540 (point-at-bol)))
7541 end)))
7542
7543 (defconst js2-no-semi-insertion
7544 (list js2-IF
7545 js2-SWITCH
7546 js2-WHILE
7547 js2-DO
7548 js2-FOR
7549 js2-TRY
7550 js2-WITH
7551 js2-LC
7552 js2-ERROR
7553 js2-SEMI
7554 js2-FUNCTION)
7555 "List of tokens that don't do automatic semicolon insertion.")
7556
7557 (defconst js2-autoinsert-semi-and-warn
7558 (list js2-ERROR js2-EOF js2-RC))
7559
7560 (defun js2-statement-helper ()
7561 (let* ((tt (js2-peek-token))
7562 (first-tt tt)
7563 (beg js2-token-beg)
7564 (parser (if (= tt js2-ERROR)
7565 #'js2-parse-semi
7566 (aref js2-parsers tt)))
7567 pn
7568 tt-flagged)
7569 ;; If the statement is set, then it's been told its label by now.
7570 (and js2-labeled-stmt
7571 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7572 (setq js2-labeled-stmt nil))
7573 (setq pn (funcall parser))
7574 ;; Don't do auto semi insertion for certain statement types.
7575 (unless (or (memq first-tt js2-no-semi-insertion)
7576 (js2-labeled-stmt-node-p pn))
7577 (js2-auto-insert-semicolon pn))
7578 pn))
7579
7580 (defun js2-auto-insert-semicolon (pn)
7581 (let* ((tt-flagged (js2-peek-flagged-token))
7582 (tt (logand tt-flagged js2-clear-ti-mask))
7583 (pos (js2-node-pos pn)))
7584 (cond
7585 ((= tt js2-SEMI)
7586 ;; Consume ';' as a part of expression
7587 (js2-consume-token)
7588 ;; extend the node bounds to include the semicolon.
7589 (setf (js2-node-len pn) (- js2-token-end pos)))
7590 ((memq tt js2-autoinsert-semi-and-warn)
7591 ;; Autoinsert ;
7592 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7593 (t
7594 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7595 ;; Report error if no EOL or autoinsert ';' otherwise
7596 (js2-report-error "msg.no.semi.stmt")
7597 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7598
7599 (defun js2-parse-condition ()
7600 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7601 The parens are discarded and the expression node is returned.
7602 The `pos' field of the return value is set to an absolute position
7603 that must be fixed up by the caller.
7604 Return value is a list (EXPR LP RP), with absolute paren positions."
7605 (let (pn lp rp)
7606 (if (js2-must-match js2-LP "msg.no.paren.cond")
7607 (setq lp js2-token-beg))
7608 (setq pn (js2-parse-expr))
7609 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7610 (setq rp js2-token-beg))
7611 ;; Report strict warning on code like "if (a = 7) ..."
7612 (if (and js2-strict-cond-assign-warning
7613 (js2-assign-node-p pn))
7614 (js2-add-strict-warning "msg.equal.as.assign" nil
7615 (js2-node-pos pn)
7616 (+ (js2-node-pos pn)
7617 (js2-node-len pn))))
7618 (list pn lp rp)))
7619
7620 (defun js2-parse-if ()
7621 "Parser for if-statement. Last matched token must be js2-IF."
7622 (let ((pos js2-token-beg)
7623 cond if-true if-false else-pos end pn)
7624 (js2-consume-token)
7625 (setq cond (js2-parse-condition)
7626 if-true (js2-parse-statement)
7627 if-false (if (js2-match-token js2-ELSE)
7628 (progn
7629 (setq else-pos (- js2-token-beg pos))
7630 (js2-parse-statement)))
7631 end (js2-node-end (or if-false if-true))
7632 pn (make-js2-if-node :pos pos
7633 :len (- end pos)
7634 :condition (car cond)
7635 :then-part if-true
7636 :else-part if-false
7637 :else-pos else-pos
7638 :lp (js2-relpos (second cond) pos)
7639 :rp (js2-relpos (third cond) pos)))
7640 (js2-node-add-children pn (car cond) if-true if-false)
7641 pn))
7642
7643 (defun js2-parse-switch ()
7644 "Parser for if-statement. Last matched token must be js2-SWITCH."
7645 (let ((pos js2-token-beg)
7646 tt pn discriminant has-default case-expr case-node
7647 case-pos cases stmt lp rp)
7648 (js2-consume-token)
7649 (if (js2-must-match js2-LP "msg.no.paren.switch")
7650 (setq lp js2-token-beg))
7651 (setq discriminant (js2-parse-expr)
7652 pn (make-js2-switch-node :discriminant discriminant
7653 :pos pos
7654 :lp (js2-relpos lp pos)))
7655 (js2-node-add-children pn discriminant)
7656 (js2-enter-switch pn)
7657 (unwind-protect
7658 (progn
7659 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7660 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7661 (js2-must-match js2-LC "msg.no.brace.switch")
7662 (catch 'break
7663 (while t
7664 (setq tt (js2-next-token)
7665 case-pos js2-token-beg)
7666 (cond
7667 ((= tt js2-RC)
7668 (setf (js2-node-len pn) (- js2-token-end pos))
7669 (throw 'break nil)) ; done
7670 ((= tt js2-CASE)
7671 (setq case-expr (js2-parse-expr))
7672 (js2-must-match js2-COLON "msg.no.colon.case"))
7673 ((= tt js2-DEFAULT)
7674 (if has-default
7675 (js2-report-error "msg.double.switch.default"))
7676 (setq has-default t
7677 case-expr nil)
7678 (js2-must-match js2-COLON "msg.no.colon.case"))
7679 (t
7680 (js2-report-error "msg.bad.switch")
7681 (throw 'break nil)))
7682 (setq case-node (make-js2-case-node :pos case-pos
7683 :len (- js2-token-end case-pos)
7684 :expr case-expr))
7685 (js2-node-add-children case-node case-expr)
7686 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7687 (/= tt js2-CASE)
7688 (/= tt js2-DEFAULT)
7689 (/= tt js2-EOF))
7690 (setf stmt (js2-parse-statement)
7691 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7692 (js2-block-node-push case-node stmt))
7693 (push case-node cases)))
7694 ;; add cases last, as pushing reverses the order to be correct
7695 (dolist (kid cases)
7696 (js2-node-add-children pn kid)
7697 (push kid (js2-switch-node-cases pn)))
7698 pn) ; return value
7699 (js2-exit-switch))))
7700
7701 (defun js2-parse-while ()
7702 "Parser for while-statement. Last matched token must be js2-WHILE."
7703 (let ((pos js2-token-beg)
7704 (pn (make-js2-while-node))
7705 cond body)
7706 (js2-consume-token)
7707 (js2-enter-loop pn)
7708 (unwind-protect
7709 (progn
7710 (setf cond (js2-parse-condition)
7711 (js2-while-node-condition pn) (car cond)
7712 body (js2-parse-statement)
7713 (js2-while-node-body pn) body
7714 (js2-node-len pn) (- (js2-node-end body) pos)
7715 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7716 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7717 (js2-node-add-children pn body (car cond)))
7718 (js2-exit-loop))
7719 pn))
7720
7721 (defun js2-parse-do ()
7722 "Parser for do-statement. Last matched token must be js2-DO."
7723 (let ((pos js2-token-beg)
7724 (pn (make-js2-do-node))
7725 cond body end)
7726 (js2-consume-token)
7727 (js2-enter-loop pn)
7728 (unwind-protect
7729 (progn
7730 (setq body (js2-parse-statement))
7731 (js2-must-match js2-WHILE "msg.no.while.do")
7732 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7733 cond (js2-parse-condition)
7734 (js2-do-node-condition pn) (car cond)
7735 (js2-do-node-body pn) body
7736 end js2-ts-cursor
7737 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7738 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7739 (js2-node-add-children pn (car cond) body))
7740 (js2-exit-loop))
7741 ;; Always auto-insert semicolon to follow SpiderMonkey:
7742 ;; It is required by ECMAScript but is ignored by the rest of
7743 ;; world; see bug 238945
7744 (if (js2-match-token js2-SEMI)
7745 (setq end js2-ts-cursor))
7746 (setf (js2-node-len pn) (- end pos))
7747 pn))
7748
7749 (defun js2-parse-for ()
7750 "Parser for for-statement. Last matched token must be js2-FOR.
7751 Parses for, for-in, and for each-in statements."
7752 (let ((for-pos js2-token-beg)
7753 pn is-for-each is-for-in-or-of is-for-of
7754 in-pos each-pos tmp-pos
7755 init ; Node init is also foo in 'foo in object'
7756 cond ; Node cond is also object in 'foo in object'
7757 incr ; 3rd section of for-loop initializer
7758 body tt lp rp)
7759 (js2-consume-token)
7760 ;; See if this is a for each () instead of just a for ()
7761 (when (js2-match-token js2-NAME)
7762 (if (string= "each" js2-ts-string)
7763 (progn
7764 (setq is-for-each t
7765 each-pos (- js2-token-beg for-pos)) ; relative
7766 (js2-record-face 'font-lock-keyword-face))
7767 (js2-report-error "msg.no.paren.for")))
7768 (if (js2-must-match js2-LP "msg.no.paren.for")
7769 (setq lp (- js2-token-beg for-pos)))
7770 (setq tt (js2-peek-token))
7771 ;; 'for' makes local scope
7772 (js2-push-scope (make-js2-scope))
7773 (unwind-protect
7774 ;; parse init clause
7775 (let ((js2-in-for-init t)) ; set as dynamic variable
7776 (cond
7777 ((= tt js2-SEMI)
7778 (setq init (make-js2-empty-expr-node)))
7779 ((or (= tt js2-VAR) (= tt js2-LET))
7780 (js2-consume-token)
7781 (setq init (js2-parse-variables tt js2-token-beg)))
7782 (t
7783 (setq init (js2-parse-expr)))))
7784 (if (or (js2-match-token js2-IN)
7785 (and (>= js2-language-version 200)
7786 (js2-match-contextual-kwd "of")
7787 (setq is-for-of t)))
7788 (setq is-for-in-or-of t
7789 in-pos (- js2-token-beg for-pos)
7790 ;; scope of iteration target object is not the scope we've created above.
7791 ;; stash current scope temporary.
7792 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7793 (js2-parse-expr))) ; object over which we're iterating
7794 ;; else ordinary for loop - parse cond and incr
7795 (js2-must-match js2-SEMI "msg.no.semi.for")
7796 (setq cond (if (= (js2-peek-token) js2-SEMI)
7797 (make-js2-empty-expr-node) ; no loop condition
7798 (js2-parse-expr)))
7799 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7800 (setq tmp-pos js2-token-end
7801 incr (if (= (js2-peek-token) js2-RP)
7802 (make-js2-empty-expr-node :pos tmp-pos)
7803 (js2-parse-expr))))
7804 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7805 (setq rp (- js2-token-beg for-pos)))
7806 (if (not is-for-in-or-of)
7807 (setq pn (make-js2-for-node :init init
7808 :condition cond
7809 :update incr
7810 :lp lp
7811 :rp rp))
7812 ;; cond could be null if 'in obj' got eaten by the init node.
7813 (if (js2-infix-node-p init)
7814 ;; it was (foo in bar) instead of (var foo in bar)
7815 (setq cond (js2-infix-node-right init)
7816 init (js2-infix-node-left init))
7817 (if (and (js2-var-decl-node-p init)
7818 (> (length (js2-var-decl-node-kids init)) 1))
7819 (js2-report-error "msg.mult.index")))
7820 (setq pn (make-js2-for-in-node :iterator init
7821 :object cond
7822 :in-pos in-pos
7823 :foreach-p is-for-each
7824 :each-pos each-pos
7825 :forof-p is-for-of
7826 :lp lp
7827 :rp rp)))
7828 (unwind-protect
7829 (progn
7830 (js2-enter-loop pn)
7831 ;; We have to parse the body -after- creating the loop node,
7832 ;; so that the loop node appears in the js2-loop-set, allowing
7833 ;; break/continue statements to find the enclosing loop.
7834 (setf body (js2-parse-statement)
7835 (js2-loop-node-body pn) body
7836 (js2-node-pos pn) for-pos
7837 (js2-node-len pn) (- (js2-node-end body) for-pos))
7838 (js2-node-add-children pn init cond incr body))
7839 ;; finally
7840 (js2-exit-loop))
7841 (js2-pop-scope))
7842 pn))
7843
7844 (defun js2-parse-try ()
7845 "Parser for try-statement. Last matched token must be js2-TRY."
7846 (let ((try-pos js2-token-beg)
7847 try-end
7848 try-block
7849 catch-blocks
7850 finally-block
7851 saw-default-catch
7852 peek
7853 param
7854 catch-cond
7855 catch-node
7856 guard-kwd
7857 catch-pos
7858 finally-pos
7859 pn
7860 block
7861 lp
7862 rp)
7863 (js2-consume-token)
7864 (if (/= (js2-peek-token) js2-LC)
7865 (js2-report-error "msg.no.brace.try"))
7866 (setq try-block (js2-parse-statement)
7867 try-end (js2-node-end try-block)
7868 peek (js2-peek-token))
7869 (cond
7870 ((= peek js2-CATCH)
7871 (while (js2-match-token js2-CATCH)
7872 (setq catch-pos js2-token-beg
7873 guard-kwd nil
7874 catch-cond nil
7875 lp nil
7876 rp nil)
7877 (if saw-default-catch
7878 (js2-report-error "msg.catch.unreachable"))
7879 (if (js2-must-match js2-LP "msg.no.paren.catch")
7880 (setq lp (- js2-token-beg catch-pos)))
7881 (js2-push-scope (make-js2-scope))
7882 (let ((tt (js2-peek-token)))
7883 (cond
7884 ;; destructuring pattern
7885 ;; catch ({ message, file }) { ... }
7886 ((or (= tt js2-LB) (= tt js2-LC))
7887 (setq param (js2-parse-destruct-primary-expr))
7888 (js2-define-destruct-symbols param js2-LET nil))
7889 ;; simple name
7890 (t
7891 (js2-must-match js2-NAME "msg.bad.catchcond")
7892 (setq param (js2-create-name-node))
7893 (js2-define-symbol js2-LET js2-ts-string param))))
7894 ;; pattern guard
7895 (if (js2-match-token js2-IF)
7896 (setq guard-kwd (- js2-token-beg catch-pos)
7897 catch-cond (js2-parse-expr))
7898 (setq saw-default-catch t))
7899 (if (js2-must-match js2-RP "msg.bad.catchcond")
7900 (setq rp (- js2-token-beg catch-pos)))
7901 (js2-must-match js2-LC "msg.no.brace.catchblock")
7902 (setq block (js2-parse-statements)
7903 try-end (js2-node-end block)
7904 catch-node (make-js2-catch-node :pos catch-pos
7905 :param param
7906 :guard-expr catch-cond
7907 :guard-kwd guard-kwd
7908 :block block
7909 :lp lp
7910 :rp rp))
7911 (js2-pop-scope)
7912 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7913 (setq try-end js2-token-beg))
7914 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7915 (js2-node-len catch-node) (- try-end catch-pos))
7916 (js2-node-add-children catch-node param catch-cond block)
7917 (push catch-node catch-blocks)))
7918 ((/= peek js2-FINALLY)
7919 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7920 (js2-node-pos try-block)
7921 (- (setq try-end (js2-node-end try-block))
7922 (js2-node-pos try-block)))))
7923 (when (js2-match-token js2-FINALLY)
7924 (setq finally-pos js2-token-beg
7925 block (js2-parse-statement)
7926 try-end (js2-node-end block)
7927 finally-block (make-js2-finally-node :pos finally-pos
7928 :len (- try-end finally-pos)
7929 :body block))
7930 (js2-node-add-children finally-block block))
7931 (setq pn (make-js2-try-node :pos try-pos
7932 :len (- try-end try-pos)
7933 :try-block try-block
7934 :finally-block finally-block))
7935 (js2-node-add-children pn try-block finally-block)
7936 ;; push them onto the try-node, which reverses and corrects their order
7937 (dolist (cb catch-blocks)
7938 (js2-node-add-children pn cb)
7939 (push cb (js2-try-node-catch-clauses pn)))
7940 pn))
7941
7942 (defun js2-parse-throw ()
7943 "Parser for throw-statement. Last matched token must be js2-THROW."
7944 (let ((pos js2-token-beg)
7945 expr pn)
7946 (js2-consume-token)
7947 (if (= (js2-peek-token-or-eol) js2-EOL)
7948 ;; ECMAScript does not allow new lines before throw expression,
7949 ;; see bug 256617
7950 (js2-report-error "msg.bad.throw.eol"))
7951 (setq expr (js2-parse-expr)
7952 pn (make-js2-throw-node :pos pos
7953 :len (- (js2-node-end expr) pos)
7954 :expr expr))
7955 (js2-node-add-children pn expr)
7956 pn))
7957
7958 (defun js2-match-jump-label-name (label-name)
7959 "If break/continue specified a label, return that label's labeled stmt.
7960 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
7961 does not match an existing label, reports an error and returns nil."
7962 (let ((bundle (cdr (assoc label-name js2-label-set))))
7963 (if (null bundle)
7964 (js2-report-error "msg.undef.label"))
7965 bundle))
7966
7967 (defun js2-parse-break ()
7968 "Parser for break-statement. Last matched token must be js2-BREAK."
7969 (let ((pos js2-token-beg)
7970 (end js2-token-end)
7971 break-target ; statement to break from
7972 break-label ; in "break foo", name-node representing the foo
7973 labels ; matching labeled statement to break to
7974 pn)
7975 (js2-consume-token) ; `break'
7976 (when (eq (js2-peek-token-or-eol) js2-NAME)
7977 (js2-consume-token)
7978 (setq break-label (js2-create-name-node)
7979 end (js2-node-end break-label)
7980 ;; matchJumpLabelName only matches if there is one
7981 labels (js2-match-jump-label-name js2-ts-string)
7982 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
7983 (unless (or break-target break-label)
7984 ;; no break target specified - try for innermost enclosing loop/switch
7985 (if (null js2-loop-and-switch-set)
7986 (unless break-label
7987 (js2-report-error "msg.bad.break" nil pos (length "break")))
7988 (setq break-target (car js2-loop-and-switch-set))))
7989 (setq pn (make-js2-break-node :pos pos
7990 :len (- end pos)
7991 :label break-label
7992 :target break-target))
7993 (js2-node-add-children pn break-label) ; but not break-target
7994 pn))
7995
7996 (defun js2-parse-continue ()
7997 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
7998 (let ((pos js2-token-beg)
7999 (end js2-token-end)
8000 label ; optional user-specified label, a `js2-name-node'
8001 labels ; current matching labeled stmt, if any
8002 target ; the `js2-loop-node' target of this continue stmt
8003 pn)
8004 (js2-consume-token) ; `continue'
8005 (when (= (js2-peek-token-or-eol) js2-NAME)
8006 (js2-consume-token)
8007 (setq label (js2-create-name-node)
8008 end (js2-node-end label)
8009 ;; matchJumpLabelName only matches if there is one
8010 labels (js2-match-jump-label-name js2-ts-string)))
8011 (cond
8012 ((null labels) ; no current label to go to
8013 (if (null js2-loop-set) ; no loop to continue to
8014 (js2-report-error "msg.continue.outside" nil pos
8015 (length "continue"))
8016 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8017 (t
8018 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8019 (setq target (js2-labeled-stmt-node-stmt labels))
8020 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8021 (setq pn (make-js2-continue-node :pos pos
8022 :len (- end pos)
8023 :label label
8024 :target target))
8025 (js2-node-add-children pn label) ; but not target - it's not our child
8026 pn))
8027
8028 (defun js2-parse-with ()
8029 "Parser for with-statement. Last matched token must be js2-WITH."
8030 (js2-consume-token)
8031 (let ((pos js2-token-beg)
8032 obj body pn lp rp)
8033 (if (js2-must-match js2-LP "msg.no.paren.with")
8034 (setq lp js2-token-beg))
8035 (setq obj (js2-parse-expr))
8036 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8037 (setq rp js2-token-beg))
8038 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8039 (setq body (js2-parse-statement)))
8040 (setq pn (make-js2-with-node :pos pos
8041 :len (- (js2-node-end body) pos)
8042 :object obj
8043 :body body
8044 :lp (js2-relpos lp pos)
8045 :rp (js2-relpos rp pos)))
8046 (js2-node-add-children pn obj body)
8047 pn))
8048
8049 (defun js2-parse-const-var ()
8050 "Parser for var- or const-statement.
8051 Last matched token must be js2-CONST or js2-VAR."
8052 (let ((tt (js2-peek-token))
8053 (pos js2-token-beg)
8054 expr pn)
8055 (js2-consume-token)
8056 (setq expr (js2-parse-variables tt js2-token-beg)
8057 pn (make-js2-expr-stmt-node :pos pos
8058 :len (- (js2-node-end expr) pos)
8059 :expr expr))
8060 (js2-node-add-children pn expr)
8061 pn))
8062
8063 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8064 (let ((pn (make-js2-expr-stmt-node :pos pos
8065 :len (js2-node-len expr)
8066 :type (if (js2-inside-function)
8067 js2-EXPR_VOID
8068 js2-EXPR_RESULT)
8069 :expr expr)))
8070 (if add-child
8071 (js2-node-add-children pn expr))
8072 pn))
8073
8074 (defun js2-parse-let-stmt ()
8075 "Parser for let-statement. Last matched token must be js2-LET."
8076 (js2-consume-token)
8077 (let ((pos js2-token-beg)
8078 expr pn)
8079 (if (= (js2-peek-token) js2-LP)
8080 ;; let expression in statement context
8081 (setq expr (js2-parse-let pos 'statement)
8082 pn (js2-wrap-with-expr-stmt pos expr t))
8083 ;; else we're looking at a statement like let x=6, y=7;
8084 (setf expr (js2-parse-variables js2-LET pos)
8085 pn (js2-wrap-with-expr-stmt pos expr t)
8086 (js2-node-type pn) js2-EXPR_RESULT))
8087 pn))
8088
8089 (defun js2-parse-ret-yield ()
8090 (js2-parse-return-or-yield (js2-peek-token) nil))
8091
8092 (defconst js2-parse-return-stmt-enders
8093 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8094
8095 (defsubst js2-now-all-set (before after mask)
8096 "Return whether or not the bits in the mask have changed to all set.
8097 BEFORE is bits before change, AFTER is bits after change, and MASK is
8098 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8099 but not BEFORE."
8100 (and (/= (logand before mask) mask)
8101 (= (logand after mask) mask)))
8102
8103 (defun js2-parse-return-or-yield (tt expr-context)
8104 (let ((pos js2-token-beg)
8105 (end js2-token-end)
8106 (before js2-end-flags)
8107 (inside-function (js2-inside-function))
8108 e ret name)
8109 (unless inside-function
8110 (js2-report-error (if (eq tt js2-RETURN)
8111 "msg.bad.return"
8112 "msg.bad.yield")))
8113 (js2-consume-token)
8114 ;; This is ugly, but we don't want to require a semicolon.
8115 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8116 (setq e (js2-parse-expr)
8117 end (js2-node-end e)))
8118 (cond
8119 ((eq tt js2-RETURN)
8120 (js2-set-flag js2-end-flags (if (null e)
8121 js2-end-returns
8122 js2-end-returns-value))
8123 (setq ret (make-js2-return-node :pos pos
8124 :len (- end pos)
8125 :retval e))
8126 (js2-node-add-children ret e)
8127 ;; See if we need a strict mode warning.
8128 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8129 ;; more thorough and accurate than this before/after flag check.
8130 ;; E.g. if there's a finally-block that always returns, we shouldn't
8131 ;; show a warning generated by inconsistent returns in the catch blocks.
8132 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8133 ;; so we know which returns/yields to highlight, and we should get rid of
8134 ;; all the checking in `js2-parse-return-or-yield'.
8135 (if (and js2-strict-inconsistent-return-warning
8136 (js2-now-all-set before js2-end-flags
8137 (logior js2-end-returns js2-end-returns-value)))
8138 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8139 (t
8140 (unless (js2-inside-function)
8141 (js2-report-error "msg.bad.yield"))
8142 (js2-set-flag js2-end-flags js2-end-yields)
8143 (setq ret (make-js2-yield-node :pos pos
8144 :len (- end pos)
8145 :value e))
8146 (js2-node-add-children ret e)
8147 (unless expr-context
8148 (setq e ret
8149 ret (js2-wrap-with-expr-stmt pos e t))
8150 (js2-set-requires-activation)
8151 (js2-set-is-generator))))
8152 ;; see if we are mixing yields and value returns.
8153 (when (and inside-function
8154 (js2-now-all-set before js2-end-flags
8155 (logior js2-end-yields js2-end-returns-value)))
8156 (setq name (js2-function-name js2-current-script-or-fn))
8157 (if (zerop (length name))
8158 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8159 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8160 ret))
8161
8162 (defun js2-parse-debugger ()
8163 (js2-consume-token)
8164 (make-js2-keyword-node :type js2-DEBUGGER))
8165
8166 (defun js2-parse-block ()
8167 "Parser for a curly-delimited statement block.
8168 Last token matched must be `js2-LC'."
8169 (let ((pos js2-token-beg)
8170 (pn (make-js2-scope)))
8171 (js2-consume-token)
8172 (js2-push-scope pn)
8173 (unwind-protect
8174 (progn
8175 (js2-parse-statements pn)
8176 (js2-must-match js2-RC "msg.no.brace.block")
8177 (setf (js2-node-len pn) (- js2-token-end pos)))
8178 (js2-pop-scope))
8179 pn))
8180
8181 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8182 (defun js2-parse-semi ()
8183 "Parse a statement or handle an error.
8184 Last matched token is `js2-SEMI' or `js2-ERROR'."
8185 (let ((tt (js2-peek-token)) pos len)
8186 (js2-consume-token)
8187 (if (eq tt js2-SEMI)
8188 (make-js2-empty-expr-node :len 1)
8189 (setq pos js2-token-beg
8190 len (- js2-token-beg pos))
8191 (js2-report-error "msg.syntax" nil pos len)
8192 (make-js2-error-node :pos pos :len len))))
8193
8194 (defun js2-parse-default-xml-namespace ()
8195 "Parse a `default xml namespace = <expr>' e4x statement."
8196 (let ((pos js2-token-beg)
8197 end len expr unary es)
8198 (js2-consume-token)
8199 (js2-must-have-xml)
8200 (js2-set-requires-activation)
8201 (setq len (- js2-ts-cursor pos))
8202 (unless (and (js2-match-token js2-NAME)
8203 (string= js2-ts-string "xml"))
8204 (js2-report-error "msg.bad.namespace" nil pos len))
8205 (unless (and (js2-match-token js2-NAME)
8206 (string= js2-ts-string "namespace"))
8207 (js2-report-error "msg.bad.namespace" nil pos len))
8208 (unless (js2-match-token js2-ASSIGN)
8209 (js2-report-error "msg.bad.namespace" nil pos len))
8210 (setq expr (js2-parse-expr)
8211 end (js2-node-end expr)
8212 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8213 :pos pos
8214 :len (- end pos)
8215 :operand expr))
8216 (js2-node-add-children unary expr)
8217 (make-js2-expr-stmt-node :pos pos
8218 :len (- end pos)
8219 :expr unary)))
8220
8221 (defun js2-record-label (label bundle)
8222 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8223 (js2-consume-token)
8224 (let ((name (js2-label-node-name label))
8225 labeled-stmt
8226 dup)
8227 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8228 ;; flag both labels if possible when used in editing mode
8229 (if (and js2-parse-ide-mode
8230 (setq dup (js2-get-label-by-name labeled-stmt name)))
8231 (js2-report-error "msg.dup.label" nil
8232 (js2-node-abs-pos dup) (js2-node-len dup)))
8233 (js2-report-error "msg.dup.label" nil
8234 (js2-node-pos label) (js2-node-len label)))
8235 (js2-labeled-stmt-node-add-label bundle label)
8236 (js2-node-add-children bundle label)
8237 ;; Add one reference to the bundle per label in `js2-label-set'
8238 (push (cons name bundle) js2-label-set)))
8239
8240 (defun js2-parse-name-or-label ()
8241 "Parser for identifier or label. Last token matched must be js2-NAME.
8242 Called when we found a name in a statement context. If it's a label, we gather
8243 up any following labels and the next non-label statement into a
8244 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8245 expression and return it wrapped in a `js2-expr-stmt-node'."
8246 (let ((pos js2-token-beg)
8247 (end js2-token-end)
8248 expr stmt pn bundle
8249 (continue t))
8250 ;; set check for label and call down to `js2-parse-primary-expr'
8251 (js2-set-check-for-label)
8252 (setq expr (js2-parse-expr))
8253 (if (/= (js2-node-type expr) js2-LABEL)
8254 ;; Parsed non-label expression - wrap with expression stmt.
8255 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8256 ;; else parsed a label
8257 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8258 (js2-record-label expr bundle)
8259 ;; look for more labels
8260 (while (and continue (= (js2-peek-token) js2-NAME))
8261 (js2-set-check-for-label)
8262 (setq expr (js2-parse-expr))
8263 (if (/= (js2-node-type expr) js2-LABEL)
8264 (progn
8265 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8266 continue nil)
8267 (js2-auto-insert-semicolon stmt))
8268 (js2-record-label expr bundle)))
8269 ;; no more labels; now parse the labeled statement
8270 (unwind-protect
8271 (unless stmt
8272 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8273 (setq stmt (js2-statement-helper))))
8274 ;; remove the labels for this statement from the global set
8275 (dolist (label (js2-labeled-stmt-node-labels bundle))
8276 (setq js2-label-set (remove label js2-label-set))))
8277 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8278 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8279 (js2-node-add-children bundle stmt)
8280 bundle)))
8281
8282 (defun js2-parse-expr-stmt ()
8283 "Default parser in statement context, if no recognized statement found."
8284 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8285
8286 (defun js2-parse-variables (decl-type pos)
8287 "Parse a comma-separated list of variable declarations.
8288 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8289
8290 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8291 For 'var' or 'const', the keyword should be the token last scanned.
8292
8293 POS is the position where the node should start. It's sometimes the
8294 var/const/let keyword, and other times the beginning of the first token
8295 in the first variable declaration.
8296
8297 Returns the parsed `js2-var-decl-node' expression node."
8298 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8299 :pos pos))
8300 destructuring kid-pos tt init name end nbeg nend vi
8301 (continue t))
8302 ;; Example:
8303 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8304 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8305 ;; var {a, b} = baz;
8306 (while continue
8307 (setq destructuring nil
8308 name nil
8309 tt (js2-peek-token)
8310 kid-pos js2-token-beg
8311 end js2-token-end
8312 init nil)
8313 (if (or (= tt js2-LB) (= tt js2-LC))
8314 ;; Destructuring assignment, e.g., var [a, b] = ...
8315 (setq destructuring (js2-parse-destruct-primary-expr)
8316 end (js2-node-end destructuring))
8317 ;; Simple variable name
8318 (when (js2-must-match js2-NAME "msg.bad.var")
8319 (setq name (js2-create-name-node)
8320 nbeg js2-token-beg
8321 nend js2-token-end
8322 end nend)
8323 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8324 (when (js2-match-token js2-ASSIGN)
8325 (setq init (js2-parse-assign-expr)
8326 end (js2-node-end init))
8327 (js2-record-imenu-functions init name))
8328 (when name
8329 (js2-set-face nbeg nend (if (js2-function-node-p init)
8330 'font-lock-function-name-face
8331 'font-lock-variable-name-face)
8332 'record))
8333 (setq vi (make-js2-var-init-node :pos kid-pos
8334 :len (- end kid-pos)
8335 :type decl-type))
8336 (if destructuring
8337 (progn
8338 (if (and (null init) (not js2-in-for-init))
8339 (js2-report-error "msg.destruct.assign.no.init"))
8340 (js2-define-destruct-symbols destructuring
8341 decl-type
8342 'font-lock-variable-name-face)
8343 (setf (js2-var-init-node-target vi) destructuring))
8344 (setf (js2-var-init-node-target vi) name))
8345 (setf (js2-var-init-node-initializer vi) init)
8346 (js2-node-add-children vi name destructuring init)
8347 (js2-block-node-push result vi)
8348 (unless (js2-match-token js2-COMMA)
8349 (setq continue nil)))
8350 (setf (js2-node-len result) (- end pos))
8351 result))
8352
8353 (defun js2-parse-let (pos &optional stmt-p)
8354 "Parse a let expression or statement.
8355 A let-expression is of the form `let (vars) expr'.
8356 A let-statment is of the form `let (vars) {statements}'.
8357 The third form of let is a variable declaration list, handled
8358 by `js2-parse-variables'."
8359 (let ((pn (make-js2-let-node :pos pos))
8360 beg vars body)
8361 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8362 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8363 (js2-push-scope pn)
8364 (unwind-protect
8365 (progn
8366 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8367 (if (js2-must-match js2-RP "msg.no.paren.let")
8368 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8369 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8370 ;; let statement
8371 (progn
8372 (js2-consume-token)
8373 (setf beg js2-token-beg ; position stmt at LC
8374 body (js2-parse-statements))
8375 (js2-must-match js2-RC "msg.no.curly.let")
8376 (setf (js2-node-len body) (- js2-token-end beg)
8377 (js2-node-len pn) (- js2-token-end pos)
8378 (js2-let-node-body pn) body
8379 (js2-node-type pn) js2-LET))
8380 ;; let expression
8381 (setf body (js2-parse-expr)
8382 (js2-node-len pn) (- (js2-node-end body) pos)
8383 (js2-let-node-body pn) body))
8384 (js2-node-add-children pn vars body))
8385 (js2-pop-scope))
8386 pn))
8387
8388 (defun js2-define-new-symbol (decl-type name node &optional scope)
8389 (js2-scope-put-symbol (or scope js2-current-scope)
8390 name
8391 (make-js2-symbol decl-type name node)))
8392
8393 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8394 "Define a symbol in the current scope.
8395 If NODE is non-nil, it is the AST node associated with the symbol."
8396 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8397 (symbol (if defining-scope
8398 (js2-scope-get-symbol defining-scope name)))
8399 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8400 (cond
8401 ((and symbol ; already defined
8402 (or (= sdt js2-CONST) ; old version is const
8403 (= decl-type js2-CONST) ; new version is const
8404 ;; two let-bound vars in this block have same name
8405 (and (= sdt js2-LET)
8406 (eq defining-scope js2-current-scope))))
8407 (js2-report-error
8408 (cond
8409 ((= sdt js2-CONST) "msg.const.redecl")
8410 ((= sdt js2-LET) "msg.let.redecl")
8411 ((= sdt js2-VAR) "msg.var.redecl")
8412 ((= sdt js2-FUNCTION) "msg.function.redecl")
8413 (t "msg.parm.redecl"))
8414 name))
8415 ((= decl-type js2-LET)
8416 (if (and (not ignore-not-in-block)
8417 (or (= (js2-node-type js2-current-scope) js2-IF)
8418 (js2-loop-node-p js2-current-scope)))
8419 (js2-report-error "msg.let.decl.not.in.block")
8420 (js2-define-new-symbol decl-type name node)))
8421 ((or (= decl-type js2-VAR)
8422 (= decl-type js2-CONST)
8423 (= decl-type js2-FUNCTION))
8424 (if symbol
8425 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8426 (js2-add-strict-warning "msg.var.redecl" name)
8427 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8428 (js2-add-strict-warning "msg.var.hides.arg" name)))
8429 (js2-define-new-symbol decl-type name node
8430 js2-current-script-or-fn)))
8431 ((= decl-type js2-LP)
8432 (if symbol
8433 ;; must be duplicate parameter. Second parameter hides the
8434 ;; first, so go ahead and add the second pararameter
8435 (js2-report-warning "msg.dup.parms" name))
8436 (js2-define-new-symbol decl-type name node))
8437 (t (js2-code-bug)))))
8438
8439 (defun js2-parse-expr (&optional oneshot)
8440 (let* ((pn (js2-parse-assign-expr))
8441 (pos (js2-node-pos pn))
8442 left
8443 right
8444 op-pos)
8445 (while (and (not oneshot)
8446 (js2-match-token js2-COMMA))
8447 (setq op-pos (- js2-token-beg pos)) ; relative
8448 (if (= (js2-peek-token) js2-YIELD)
8449 (js2-report-error "msg.yield.parenthesized"))
8450 (setq right (js2-parse-assign-expr)
8451 left pn
8452 pn (make-js2-infix-node :type js2-COMMA
8453 :pos pos
8454 :len (- js2-ts-cursor pos)
8455 :op-pos op-pos
8456 :left left
8457 :right right))
8458 (js2-node-add-children pn left right))
8459 pn))
8460
8461 (defun js2-parse-assign-expr ()
8462 (let ((tt (js2-peek-token))
8463 (pos js2-token-beg)
8464 pn left right op-pos)
8465 (if (= tt js2-YIELD)
8466 (js2-parse-return-or-yield tt t)
8467 ;; not yield - parse assignment expression
8468 (setq pn (js2-parse-cond-expr)
8469 tt (js2-peek-token))
8470 (when (and (<= js2-first-assign tt)
8471 (<= tt js2-last-assign))
8472 ;; tt express assignment (=, |=, ^=, ..., %=)
8473 (js2-consume-token)
8474 (setq op-pos (- js2-token-beg pos) ; relative
8475 left pn
8476 right (js2-parse-assign-expr)
8477 pn (make-js2-assign-node :type tt
8478 :pos pos
8479 :len (- (js2-node-end right) pos)
8480 :op-pos op-pos
8481 :left left
8482 :right right))
8483 (when js2-parse-ide-mode
8484 (js2-highlight-assign-targets pn left right)
8485 (js2-record-imenu-functions right left))
8486 ;; do this last so ide checks above can use absolute positions
8487 (js2-node-add-children pn left right))
8488 pn)))
8489
8490 (defun js2-parse-cond-expr ()
8491 (let ((pos js2-token-beg)
8492 (pn (js2-parse-or-expr))
8493 test-expr
8494 if-true
8495 if-false
8496 q-pos
8497 c-pos)
8498 (when (js2-match-token js2-HOOK)
8499 (setq q-pos (- js2-token-beg pos)
8500 if-true (js2-parse-assign-expr))
8501 (js2-must-match js2-COLON "msg.no.colon.cond")
8502 (setq c-pos (- js2-token-beg pos)
8503 if-false (js2-parse-assign-expr)
8504 test-expr pn
8505 pn (make-js2-cond-node :pos pos
8506 :len (- (js2-node-end if-false) pos)
8507 :test-expr test-expr
8508 :true-expr if-true
8509 :false-expr if-false
8510 :q-pos q-pos
8511 :c-pos c-pos))
8512 (js2-node-add-children pn test-expr if-true if-false))
8513 pn))
8514
8515 (defun js2-make-binary (type left parser)
8516 "Helper for constructing a binary-operator AST node.
8517 LEFT is the left-side-expression, already parsed, and the
8518 binary operator should have just been matched.
8519 PARSER is a function to call to parse the right operand,
8520 or a `js2-node' struct if it has already been parsed."
8521 (let* ((pos (js2-node-pos left))
8522 (op-pos (- js2-token-beg pos))
8523 (right (if (js2-node-p parser)
8524 parser
8525 (funcall parser)))
8526 (pn (make-js2-infix-node :type type
8527 :pos pos
8528 :len (- (js2-node-end right) pos)
8529 :op-pos op-pos
8530 :left left
8531 :right right)))
8532 (js2-node-add-children pn left right)
8533 pn))
8534
8535 (defun js2-parse-or-expr ()
8536 (let ((pn (js2-parse-and-expr)))
8537 (when (js2-match-token js2-OR)
8538 (setq pn (js2-make-binary js2-OR
8539 pn
8540 'js2-parse-or-expr)))
8541 pn))
8542
8543 (defun js2-parse-and-expr ()
8544 (let ((pn (js2-parse-bit-or-expr)))
8545 (when (js2-match-token js2-AND)
8546 (setq pn (js2-make-binary js2-AND
8547 pn
8548 'js2-parse-and-expr)))
8549 pn))
8550
8551 (defun js2-parse-bit-or-expr ()
8552 (let ((pn (js2-parse-bit-xor-expr)))
8553 (while (js2-match-token js2-BITOR)
8554 (setq pn (js2-make-binary js2-BITOR
8555 pn
8556 'js2-parse-bit-xor-expr)))
8557 pn))
8558
8559 (defun js2-parse-bit-xor-expr ()
8560 (let ((pn (js2-parse-bit-and-expr)))
8561 (while (js2-match-token js2-BITXOR)
8562 (setq pn (js2-make-binary js2-BITXOR
8563 pn
8564 'js2-parse-bit-and-expr)))
8565 pn))
8566
8567 (defun js2-parse-bit-and-expr ()
8568 (let ((pn (js2-parse-eq-expr)))
8569 (while (js2-match-token js2-BITAND)
8570 (setq pn (js2-make-binary js2-BITAND
8571 pn
8572 'js2-parse-eq-expr)))
8573 pn))
8574
8575 (defconst js2-parse-eq-ops
8576 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8577
8578 (defun js2-parse-eq-expr ()
8579 (let ((pn (js2-parse-rel-expr))
8580 tt)
8581 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8582 (js2-consume-token)
8583 (setq pn (js2-make-binary tt
8584 pn
8585 'js2-parse-rel-expr)))
8586 pn))
8587
8588 (defconst js2-parse-rel-ops
8589 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8590
8591 (defun js2-parse-rel-expr ()
8592 (let ((pn (js2-parse-shift-expr))
8593 (continue t)
8594 tt)
8595 (while continue
8596 (setq tt (js2-peek-token))
8597 (cond
8598 ((and js2-in-for-init (= tt js2-IN))
8599 (setq continue nil))
8600 ((memq tt js2-parse-rel-ops)
8601 (js2-consume-token)
8602 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8603 (t
8604 (setq continue nil))))
8605 pn))
8606
8607 (defconst js2-parse-shift-ops
8608 (list js2-LSH js2-URSH js2-RSH))
8609
8610 (defun js2-parse-shift-expr ()
8611 (let ((pn (js2-parse-add-expr))
8612 tt
8613 (continue t))
8614 (while continue
8615 (setq tt (js2-peek-token))
8616 (if (memq tt js2-parse-shift-ops)
8617 (progn
8618 (js2-consume-token)
8619 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8620 (setq continue nil)))
8621 pn))
8622
8623 (defun js2-parse-add-expr ()
8624 (let ((pn (js2-parse-mul-expr))
8625 tt
8626 (continue t))
8627 (while continue
8628 (setq tt (js2-peek-token))
8629 (if (or (= tt js2-ADD) (= tt js2-SUB))
8630 (progn
8631 (js2-consume-token)
8632 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8633 (setq continue nil)))
8634 pn))
8635
8636 (defconst js2-parse-mul-ops
8637 (list js2-MUL js2-DIV js2-MOD))
8638
8639 (defun js2-parse-mul-expr ()
8640 (let ((pn (js2-parse-unary-expr))
8641 tt
8642 (continue t))
8643 (while continue
8644 (setq tt (js2-peek-token))
8645 (if (memq tt js2-parse-mul-ops)
8646 (progn
8647 (js2-consume-token)
8648 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8649 (setq continue nil)))
8650 pn))
8651
8652 (defun js2-make-unary (type parser &rest args)
8653 "Make a unary node of type TYPE.
8654 PARSER is either a node (for postfix operators) or a function to call
8655 to parse the operand (for prefix operators)."
8656 (let* ((pos js2-token-beg)
8657 (postfix (js2-node-p parser))
8658 (expr (if postfix
8659 parser
8660 (apply parser args)))
8661 end
8662 pn)
8663 (if postfix ; e.g. i++
8664 (setq pos (js2-node-pos expr)
8665 end js2-token-end)
8666 (setq end (js2-node-end expr)))
8667 (setq pn (make-js2-unary-node :type type
8668 :pos pos
8669 :len (- end pos)
8670 :operand expr))
8671 (js2-node-add-children pn expr)
8672 pn))
8673
8674 (defconst js2-incrementable-node-types
8675 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8676 "Node types that can be the operand of a ++ or -- operator.")
8677
8678 (defun js2-check-bad-inc-dec (tt beg end unary)
8679 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8680 js2-incrementable-node-types)
8681 (js2-report-error (if (= tt js2-INC)
8682 "msg.bad.incr"
8683 "msg.bad.decr")
8684 nil beg (- end beg))))
8685
8686 (defun js2-parse-unary-expr ()
8687 (let ((tt (js2-peek-token))
8688 pn expr beg end)
8689 (cond
8690 ((or (= tt js2-VOID)
8691 (= tt js2-NOT)
8692 (= tt js2-BITNOT)
8693 (= tt js2-TYPEOF))
8694 (js2-consume-token)
8695 (js2-make-unary tt 'js2-parse-unary-expr))
8696 ((= tt js2-ADD)
8697 (js2-consume-token)
8698 ;; Convert to special POS token in decompiler and parse tree
8699 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8700 ((= tt js2-SUB)
8701 (js2-consume-token)
8702 ;; Convert to special NEG token in decompiler and parse tree
8703 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8704 ((or (= tt js2-INC)
8705 (= tt js2-DEC))
8706 (js2-consume-token)
8707 (prog1
8708 (setq beg js2-token-beg
8709 end js2-token-end
8710 expr (js2-make-unary tt 'js2-parse-member-expr t))
8711 (js2-check-bad-inc-dec tt beg end expr)))
8712 ((= tt js2-DELPROP)
8713 (js2-consume-token)
8714 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8715 ((= tt js2-ERROR)
8716 (js2-consume-token)
8717 (make-js2-error-node)) ; try to continue
8718 ((and (= tt js2-LT)
8719 js2-compiler-xml-available)
8720 ;; XML stream encountered in expression.
8721 (js2-consume-token)
8722 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8723 (t
8724 (setq pn (js2-parse-member-expr t)
8725 ;; Don't look across a newline boundary for a postfix incop.
8726 tt (js2-peek-token-or-eol))
8727 (when (or (= tt js2-INC) (= tt js2-DEC))
8728 (js2-consume-token)
8729 (setf expr pn
8730 pn (js2-make-unary tt expr))
8731 (js2-node-set-prop pn 'postfix t)
8732 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8733 pn))))
8734
8735 (defun js2-parse-xml-initializer ()
8736 "Parse an E4X XML initializer.
8737 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8738 Then I'll postprocess the result, depending on whether we're in IDE
8739 mode or codegen mode, and generate the appropriate rewritten AST.
8740 IDE mode uses a rich AST that models the XML structure. Codegen mode
8741 just concatenates everything and makes a new XML or XMLList out of it."
8742 (let ((tt (js2-get-first-xml-token))
8743 pn-xml pn expr kids expr-pos
8744 (continue t)
8745 (first-token t))
8746 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8747 (js2-report-error "msg.syntax"))
8748 (setq pn-xml (make-js2-xml-node))
8749 (while continue
8750 (if first-token
8751 (setq first-token nil)
8752 (setq tt (js2-get-next-xml-token)))
8753 (cond
8754 ;; js2-XML means we found a {expr} in the XML stream.
8755 ;; The js2-ts-string is the XML up to the left-curly.
8756 ((= tt js2-XML)
8757 (push (make-js2-string-node :pos js2-token-beg
8758 :len (- js2-ts-cursor js2-token-beg))
8759 kids)
8760 (js2-must-match js2-LC "msg.syntax")
8761 (setq expr-pos js2-ts-cursor
8762 expr (if (eq (js2-peek-token) js2-RC)
8763 (make-js2-empty-expr-node :pos expr-pos)
8764 (js2-parse-expr)))
8765 (js2-must-match js2-RC "msg.syntax")
8766 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8767 :len (js2-node-len expr)
8768 :expr expr))
8769 (js2-node-add-children pn expr)
8770 (push pn kids))
8771 ;; a js2-XMLEND token means we hit the final close-tag.
8772 ((= tt js2-XMLEND)
8773 (push (make-js2-string-node :pos js2-token-beg
8774 :len (- js2-ts-cursor js2-token-beg))
8775 kids)
8776 (dolist (kid (nreverse kids))
8777 (js2-block-node-push pn-xml kid))
8778 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8779 (js2-node-pos pn-xml))
8780 continue nil))
8781 (t
8782 (js2-report-error "msg.syntax")
8783 (setq continue nil))))
8784 pn-xml))
8785
8786
8787 (defun js2-parse-argument-list ()
8788 "Parse an argument list and return it as a Lisp list of nodes.
8789 Returns the list in reverse order. Consumes the right-paren token."
8790 (let (result)
8791 (unless (js2-match-token js2-RP)
8792 (loop do
8793 (if (= (js2-peek-token) js2-YIELD)
8794 (js2-report-error "msg.yield.parenthesized"))
8795 (push (js2-parse-assign-expr) result)
8796 while
8797 (js2-match-token js2-COMMA))
8798 (js2-must-match js2-RP "msg.no.paren.arg")
8799 result)))
8800
8801 (defun js2-parse-member-expr (&optional allow-call-syntax)
8802 (let ((tt (js2-peek-token))
8803 pn pos target args beg end init tail)
8804 (if (/= tt js2-NEW)
8805 (setq pn (js2-parse-primary-expr))
8806 ;; parse a 'new' expression
8807 (js2-consume-token)
8808 (setq pos js2-token-beg
8809 beg pos
8810 target (js2-parse-member-expr)
8811 end (js2-node-end target)
8812 pn (make-js2-new-node :pos pos
8813 :target target
8814 :len (- end pos)))
8815 (js2-node-add-children pn target)
8816 (when (js2-match-token js2-LP)
8817 ;; Add the arguments to pn, if any are supplied.
8818 (setf beg pos ; start of "new" keyword
8819 pos js2-token-beg
8820 args (nreverse (js2-parse-argument-list))
8821 (js2-new-node-args pn) args
8822 end js2-token-end
8823 (js2-new-node-lp pn) (- pos beg)
8824 (js2-new-node-rp pn) (- end 1 beg))
8825 (apply #'js2-node-add-children pn args))
8826 (when (and js2-allow-rhino-new-expr-initializer
8827 (js2-match-token js2-LC))
8828 (setf init (js2-parse-object-literal)
8829 end (js2-node-end init)
8830 (js2-new-node-initializer pn) init)
8831 (js2-node-add-children pn init))
8832 (setf (js2-node-len pn) (- end beg))) ; end outer if
8833 (js2-parse-member-expr-tail allow-call-syntax pn)))
8834
8835 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8836 "Parse a chain of property/array accesses or function calls.
8837 Includes parsing for E4X operators like `..' and `.@'.
8838 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8839 Returns an expression tree that includes PN, the parent node."
8840 (let ((beg (js2-node-pos pn))
8841 tt
8842 (continue t))
8843 (while continue
8844 (setq tt (js2-peek-token))
8845 (cond
8846 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8847 (setq pn (js2-parse-property-access tt pn)))
8848 ((= tt js2-DOTQUERY)
8849 (setq pn (js2-parse-dot-query pn)))
8850 ((= tt js2-LB)
8851 (setq pn (js2-parse-element-get pn)))
8852 ((= tt js2-LP)
8853 (if allow-call-syntax
8854 (setq pn (js2-parse-function-call pn))
8855 (setq continue nil)))
8856 (t
8857 (setq continue nil))))
8858 (if (>= js2-highlight-level 2)
8859 (js2-parse-highlight-member-expr-node pn))
8860 pn))
8861
8862 (defun js2-parse-dot-query (pn)
8863 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8864 Last token parsed must be `js2-DOTQUERY'."
8865 (let ((pos (js2-node-pos pn))
8866 op-pos expr end)
8867 (js2-consume-token)
8868 (js2-must-have-xml)
8869 (js2-set-requires-activation)
8870 (setq op-pos js2-token-beg
8871 expr (js2-parse-expr)
8872 end (js2-node-end expr)
8873 pn (make-js2-xml-dot-query-node :left pn
8874 :pos pos
8875 :op-pos op-pos
8876 :right expr))
8877 (js2-node-add-children pn
8878 (js2-xml-dot-query-node-left pn)
8879 (js2-xml-dot-query-node-right pn))
8880 (if (js2-must-match js2-RP "msg.no.paren")
8881 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
8882 end js2-token-end))
8883 (setf (js2-node-len pn) (- end pos))
8884 pn))
8885
8886 (defun js2-parse-element-get (pn)
8887 "Parse an element-get expression, e.g. foo[bar].
8888 Last token parsed must be `js2-RB'."
8889 (let ((lb js2-token-beg)
8890 (pos (js2-node-pos pn))
8891 rb expr)
8892 (js2-consume-token)
8893 (setq expr (js2-parse-expr))
8894 (if (js2-must-match js2-RB "msg.no.bracket.index")
8895 (setq rb js2-token-beg))
8896 (setq pn (make-js2-elem-get-node :target pn
8897 :pos pos
8898 :element expr
8899 :lb (js2-relpos lb pos)
8900 :rb (js2-relpos rb pos)
8901 :len (- js2-token-end pos)))
8902 (js2-node-add-children pn
8903 (js2-elem-get-node-target pn)
8904 (js2-elem-get-node-element pn))
8905 pn))
8906
8907 (defun js2-parse-function-call (pn)
8908 (let (args
8909 (pos (js2-node-pos pn)))
8910 (js2-consume-token)
8911 (setq pn (make-js2-call-node :pos pos
8912 :target pn
8913 :lp (- js2-token-beg pos)))
8914 (js2-node-add-children pn (js2-call-node-target pn))
8915 ;; Add the arguments to pn, if any are supplied.
8916 (setf args (nreverse (js2-parse-argument-list))
8917 (js2-call-node-rp pn) (- js2-token-beg pos)
8918 (js2-call-node-args pn) args)
8919 (apply #'js2-node-add-children pn args)
8920 (setf (js2-node-len pn) (- js2-ts-cursor pos))
8921 pn))
8922
8923 (defun js2-parse-property-access (tt pn)
8924 "Parse a property access, XML descendants access, or XML attr access."
8925 (let ((member-type-flags 0)
8926 (dot-pos js2-token-beg)
8927 (dot-len (if (= tt js2-DOTDOT) 2 1))
8928 name
8929 ref ; right side of . or .. operator
8930 result)
8931 (js2-consume-token)
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-token-beg
8941 :right name
8942 :len (- js2-token-end
8943 js2-token-beg)))
8944 (js2-node-add-children result pn name)
8945 result)
8946 ;; otherwise look for XML operators
8947 (setf result (if (= tt js2-DOT)
8948 (make-js2-prop-get-node)
8949 (make-js2-infix-node :type js2-DOTDOT))
8950 (js2-node-pos result) (js2-node-pos pn)
8951 (js2-infix-node-op-pos result) dot-pos
8952 (js2-infix-node-left result) pn ; do this after setting position
8953 tt (js2-next-token))
8954 (cond
8955 ;; needed for generator.throw()
8956 ((= tt js2-THROW)
8957 (js2-save-name-token-data js2-token-beg "throw")
8958 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
8959 ;; handles: name, ns::name, ns::*, ns::[expr]
8960 ((js2-valid-prop-name-token tt)
8961 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
8962 ;; handles: *, *::name, *::*, *::[expr]
8963 ((= tt js2-MUL)
8964 (js2-save-name-token-data js2-token-beg "*")
8965 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
8966 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
8967 ((= tt js2-XMLATTR)
8968 (setq result (js2-parse-attribute-access)))
8969 (t
8970 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
8971 (if ref
8972 (setf (js2-node-len result) (- (js2-node-end ref)
8973 (js2-node-pos result))
8974 (js2-infix-node-right result) ref))
8975 (if (js2-infix-node-p result)
8976 (js2-node-add-children result
8977 (js2-infix-node-left result)
8978 (js2-infix-node-right result)))
8979 result)))
8980
8981 (defun js2-parse-attribute-access ()
8982 "Parse an E4X XML attribute expression.
8983 This includes expressions of the forms:
8984
8985 @attr @ns::attr @ns::*
8986 @* @*::attr @*::*
8987 @[expr] @*::[expr] @ns::[expr]
8988
8989 Called if we peeked an '@' token."
8990 (let ((tt (js2-next-token))
8991 (at-pos js2-token-beg))
8992 (cond
8993 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
8994 ((js2-valid-prop-name-token tt)
8995 (js2-parse-property-name at-pos js2-ts-string 0))
8996 ;; handles: @*, @*::name, @*::*, @*::[expr]
8997 ((= tt js2-MUL)
8998 (js2-save-name-token-data js2-token-beg "*")
8999 (js2-parse-property-name js2-token-beg "*" 0))
9000 ;; handles @[expr]
9001 ((= tt js2-LB)
9002 (js2-parse-xml-elem-ref at-pos))
9003 (t
9004 (js2-report-error "msg.no.name.after.xmlAttr")
9005 ;; Avoid cascaded errors that happen if we make an error node here.
9006 (js2-save-name-token-data js2-token-beg "")
9007 (js2-parse-property-name js2-token-beg "" 0)))))
9008
9009 (defun js2-parse-property-name (at-pos s member-type-flags)
9010 "Check if :: follows name in which case it becomes qualified name.
9011
9012 AT-POS is a natural number if we just read an '@' token, else nil.
9013 S is the name or string that was matched: an identifier, 'throw' or '*'.
9014 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9015
9016 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9017 operator, or the name is followed by ::. For a plain name, returns a
9018 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9019 (let ((pos (or at-pos js2-token-beg))
9020 colon-pos
9021 (name (js2-create-name-node t js2-current-token))
9022 ns tt ref pn)
9023 (catch 'return
9024 (when (js2-match-token js2-COLONCOLON)
9025 (setq ns name
9026 colon-pos js2-token-beg
9027 tt (js2-next-token))
9028 (cond
9029 ;; handles name::name
9030 ((js2-valid-prop-name-token tt)
9031 (setq name (js2-create-name-node)))
9032 ;; handles name::*
9033 ((= tt js2-MUL)
9034 (js2-save-name-token-data js2-token-beg "*")
9035 (setq name (js2-create-name-node)))
9036 ;; handles name::[expr]
9037 ((= tt js2-LB)
9038 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9039 (t
9040 (js2-report-error "msg.no.name.after.coloncolon"))))
9041 (if (and (null ns) (zerop member-type-flags))
9042 name
9043 (prog1
9044 (setq pn
9045 (make-js2-xml-prop-ref-node :pos pos
9046 :len (- (js2-node-end name) pos)
9047 :at-pos at-pos
9048 :colon-pos colon-pos
9049 :propname name))
9050 (js2-node-add-children pn name))))))
9051
9052 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9053 "Parse the [expr] portion of an xml element reference.
9054 For instance, @[expr], @*::[expr], or ns::[expr]."
9055 (let* ((lb js2-token-beg)
9056 (pos (or at-pos lb))
9057 rb
9058 (expr (js2-parse-expr))
9059 (end (js2-node-end expr))
9060 pn)
9061 (if (js2-must-match js2-RB "msg.no.bracket.index")
9062 (setq rb js2-token-beg
9063 end js2-token-end))
9064 (prog1
9065 (setq pn
9066 (make-js2-xml-elem-ref-node :pos pos
9067 :len (- end pos)
9068 :namespace namespace
9069 :colon-pos colon-pos
9070 :at-pos at-pos
9071 :expr expr
9072 :lb (js2-relpos lb pos)
9073 :rb (js2-relpos rb pos)))
9074 (js2-node-add-children pn namespace expr))))
9075
9076 (defun js2-parse-destruct-primary-expr ()
9077 (let ((js2-is-in-destructuring t))
9078 (js2-parse-primary-expr)))
9079
9080 (defun js2-parse-primary-expr ()
9081 "Parse a literal (leaf) expression of some sort.
9082 Includes complex literals such as functions, object-literals,
9083 array-literals, array comprehensions and regular expressions."
9084 (let ((tt-flagged (js2-next-flagged-token))
9085 pn ; parent node (usually return value)
9086 tt
9087 px-pos ; paren-expr pos
9088 len
9089 flags ; regexp flags
9090 expr)
9091 (setq tt js2-current-token)
9092 (cond
9093 ((= tt js2-FUNCTION)
9094 (js2-parse-function 'FUNCTION_EXPRESSION))
9095 ((= tt js2-LB)
9096 (js2-parse-array-literal))
9097 ((= tt js2-LC)
9098 (js2-parse-object-literal))
9099 ((= tt js2-LET)
9100 (js2-parse-let js2-token-beg))
9101 ((= tt js2-LP)
9102 (setq px-pos js2-token-beg
9103 expr (js2-parse-expr))
9104 (js2-must-match js2-RP "msg.no.paren")
9105 (setq pn (make-js2-paren-node :pos px-pos
9106 :expr expr
9107 :len (- js2-token-end px-pos)))
9108 (js2-node-add-children pn (js2-paren-node-expr pn))
9109 pn)
9110 ((= tt js2-XMLATTR)
9111 (js2-must-have-xml)
9112 (js2-parse-attribute-access))
9113 ((= tt js2-NAME)
9114 (js2-parse-name tt-flagged tt))
9115 ((= tt js2-NUMBER)
9116 (make-js2-number-node))
9117 ((= tt js2-STRING)
9118 (prog1
9119 (make-js2-string-node)
9120 (js2-record-face 'font-lock-string-face)))
9121 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9122 ;; Got / or /= which in this context means a regexp literal
9123 (setq px-pos js2-token-beg)
9124 (js2-read-regexp tt)
9125 (setq flags js2-ts-regexp-flags
9126 js2-ts-regexp-flags nil)
9127 (prog1
9128 (make-js2-regexp-node :pos px-pos
9129 :len (- js2-ts-cursor px-pos)
9130 :value js2-ts-string
9131 :flags flags)
9132 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9133 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9134 ((or (= tt js2-NULL)
9135 (= tt js2-THIS)
9136 (= tt js2-FALSE)
9137 (= tt js2-TRUE))
9138 (make-js2-keyword-node :type tt))
9139 ((= tt js2-RESERVED)
9140 (js2-report-error "msg.reserved.id")
9141 (make-js2-name-node))
9142 ((= tt js2-ERROR)
9143 ;; the scanner or one of its subroutines reported the error.
9144 (make-js2-error-node))
9145 ((= tt js2-EOF)
9146 (setq px-pos (point-at-bol)
9147 len (- js2-ts-cursor px-pos))
9148 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9149 (make-js2-error-node :pos px-pos :len len))
9150 (t
9151 (js2-report-error "msg.syntax")
9152 (make-js2-error-node)))))
9153
9154 (defun js2-parse-name (tt-flagged tt)
9155 (let ((name js2-ts-string)
9156 (name-pos js2-token-beg)
9157 node)
9158 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9159 (= (js2-peek-token) js2-COLON))
9160 (prog1
9161 ;; Do not consume colon, it is used as unwind indicator
9162 ;; to return to statementHelper.
9163 (make-js2-label-node :pos name-pos
9164 :len (- js2-token-end name-pos)
9165 :name name)
9166 (js2-set-face name-pos
9167 js2-token-end
9168 'font-lock-variable-name-face 'record))
9169 ;; Otherwise not a label, just a name. Unfortunately peeking
9170 ;; the next token to check for a colon has biffed js2-token-beg
9171 ;; and js2-token-end. We store the name's bounds in buffer vars
9172 ;; and `js2-create-name-node' uses them.
9173 (js2-save-name-token-data name-pos name)
9174 (setq node (if js2-compiler-xml-available
9175 (js2-parse-property-name nil name 0)
9176 (js2-create-name-node 'check-activation)))
9177 (if js2-highlight-external-variables
9178 (js2-record-name-node node))
9179 node)))
9180
9181 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9182 (js2-add-strict-warning
9183 msg nil
9184 ;; back up from comma to beginning of line or array/objlit
9185 (max (if elems
9186 (js2-node-pos (car elems))
9187 pos)
9188 (save-excursion
9189 (goto-char comma-pos)
9190 (back-to-indentation)
9191 (point)))
9192 comma-pos))
9193
9194 (defun js2-parse-array-literal ()
9195 (let ((pos js2-token-beg)
9196 (end js2-token-end)
9197 (after-lb-or-comma t)
9198 after-comma tt elems pn
9199 (continue t))
9200 (unless js2-is-in-destructuring
9201 (js2-push-scope (make-js2-scope))) ; for array comp
9202 (while continue
9203 (setq tt (js2-peek-token))
9204 (cond
9205 ;; comma
9206 ((= tt js2-COMMA)
9207 (js2-consume-token)
9208 (setq after-comma js2-token-end)
9209 (if (not after-lb-or-comma)
9210 (setq after-lb-or-comma t)
9211 (push nil elems)))
9212 ;; end of array
9213 ((or (= tt js2-RB)
9214 (= tt js2-EOF)) ; prevent infinite loop
9215 (if (= tt js2-EOF)
9216 (js2-report-error "msg.no.bracket.arg" nil pos)
9217 (js2-consume-token))
9218 (setq continue nil
9219 end js2-token-end
9220 pn (make-js2-array-node :pos pos
9221 :len (- js2-ts-cursor pos)
9222 :elems (nreverse elems)))
9223 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9224 (when (and after-comma (not js2-is-in-destructuring))
9225 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9226 pos elems after-comma)))
9227 ;; destructuring binding
9228 (js2-is-in-destructuring
9229 (push (if (or (= tt js2-LC)
9230 (= tt js2-LB)
9231 (= tt js2-NAME))
9232 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9233 (js2-parse-destruct-primary-expr)
9234 ;; invalid pattern
9235 (js2-consume-token)
9236 (js2-report-error "msg.bad.var")
9237 (make-js2-error-node))
9238 elems)
9239 (setq after-lb-or-comma nil
9240 after-comma nil))
9241 ;; array comp
9242 ((and (>= js2-language-version 170)
9243 (= tt js2-FOR) ; check for array comprehension
9244 (not after-lb-or-comma) ; "for" can't follow a comma
9245 elems ; must have at least 1 element
9246 (not (cdr elems))) ; but no 2nd element
9247 (setf continue nil
9248 pn (js2-parse-array-comprehension (car elems) pos)))
9249
9250 ;; another element
9251 (t
9252 (unless after-lb-or-comma
9253 (js2-report-error "msg.no.bracket.arg"))
9254 (push (js2-parse-assign-expr) elems)
9255 (setq after-lb-or-comma nil
9256 after-comma nil))))
9257 (unless js2-is-in-destructuring
9258 (js2-pop-scope))
9259 pn))
9260
9261 (defun js2-parse-array-comprehension (expr pos)
9262 "Parse a JavaScript 1.7 Array Comprehension.
9263 EXPR is the first expression after the opening left-bracket.
9264 POS is the beginning of the LB token preceding EXPR.
9265 We should have just parsed the 'for' keyword before calling this function."
9266 (let (loops loop first prev filter if-pos result)
9267 (while (= (js2-peek-token) js2-FOR)
9268 (let ((prev (car loops))) ; rearrange scope chain
9269 (push (setq loop (js2-parse-array-comp-loop)) loops)
9270 (if prev ; each loop is parent scope to the next one
9271 (setf (js2-scope-parent-scope loop) prev)
9272 ; first loop takes expr scope's parent
9273 (setf (js2-scope-parent-scope (setq first loop))
9274 (js2-scope-parent-scope js2-current-scope)))))
9275 ;; set expr scope's parent to the last loop
9276 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9277 (when (= (js2-peek-token) js2-IF)
9278 (js2-consume-token)
9279 (setq if-pos (- js2-token-beg pos) ; relative
9280 filter (js2-parse-condition)))
9281 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9282 (setq result (make-js2-array-comp-node :pos pos
9283 :len (- js2-ts-cursor pos)
9284 :result expr
9285 :loops (nreverse loops)
9286 :filter (car filter)
9287 :lp (js2-relpos (second filter) pos)
9288 :rp (js2-relpos (third filter) pos)
9289 :if-pos if-pos))
9290 (apply #'js2-node-add-children result expr (car filter)
9291 (js2-array-comp-node-loops result))
9292 (setq js2-current-scope first) ; pop to the first loop
9293 result))
9294
9295 (defun js2-parse-array-comp-loop ()
9296 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9297 Last token peeked should be the initial FOR."
9298 (let ((pos js2-token-beg)
9299 (pn (make-js2-array-comp-loop-node))
9300 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9301 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9302 (js2-push-scope pn)
9303 (unwind-protect
9304 (progn
9305 (when (js2-match-token js2-NAME)
9306 (if (string= js2-ts-string "each")
9307 (progn
9308 (setq foreach-p t
9309 each-pos (- js2-token-beg pos)) ; relative
9310 (js2-record-face 'font-lock-keyword-face))
9311 (js2-report-error "msg.no.paren.for")))
9312 (if (js2-must-match js2-LP "msg.no.paren.for")
9313 (setq lp (- js2-token-beg pos)))
9314 (setq tt (js2-peek-token))
9315 (cond
9316 ((or (= tt js2-LB)
9317 (= tt js2-LC))
9318 (setq iter (js2-parse-destruct-primary-expr))
9319 (js2-define-destruct-symbols iter js2-LET
9320 'font-lock-variable-name-face t))
9321 ((js2-match-token js2-NAME)
9322 (setq iter (js2-create-name-node)))
9323 (t
9324 (js2-report-error "msg.bad.var")))
9325 ;; Define as a let since we want the scope of the variable to
9326 ;; be restricted to the array comprehension
9327 (if (js2-name-node-p iter)
9328 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9329 (if (or (js2-match-token js2-IN)
9330 (and (>= js2-language-version 200)
9331 (js2-match-contextual-kwd "of")
9332 (setq forof-p t)))
9333 (setq in-pos (- js2-token-beg pos))
9334 (js2-report-error "msg.in.after.for.name"))
9335 (setq obj (js2-parse-expr))
9336 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9337 (setq rp (- js2-token-beg pos)))
9338 (setf (js2-node-pos pn) pos
9339 (js2-node-len pn) (- js2-ts-cursor pos)
9340 (js2-array-comp-loop-node-iterator pn) iter
9341 (js2-array-comp-loop-node-object pn) obj
9342 (js2-array-comp-loop-node-in-pos pn) in-pos
9343 (js2-array-comp-loop-node-each-pos pn) each-pos
9344 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9345 (js2-array-comp-loop-node-forof-p pn) forof-p
9346 (js2-array-comp-loop-node-lp pn) lp
9347 (js2-array-comp-loop-node-rp pn) rp)
9348 (js2-node-add-children pn iter obj))
9349 (js2-pop-scope))
9350 pn))
9351
9352 (defun js2-parse-object-literal ()
9353 (let ((pos js2-token-beg)
9354 tt elems result after-comma
9355 (continue t))
9356 (while continue
9357 (setq tt (js2-peek-token))
9358 (cond
9359 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9360 ;; {get foo() {...}}, or {set foo(x) {...}}
9361 ((or (js2-valid-prop-name-token tt)
9362 (= tt js2-STRING))
9363 (setq after-comma nil
9364 result (js2-parse-named-prop tt))
9365 (if (and (null result)
9366 (not js2-recover-from-parse-errors))
9367 (setq continue nil)
9368 (push result elems)))
9369 ;; {12: x} or {10.7: x}
9370 ((= tt js2-NUMBER)
9371 (js2-consume-token)
9372 (setq after-comma nil)
9373 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9374 ;; trailing comma
9375 ((= tt js2-RC)
9376 (setq continue nil)
9377 (if after-comma
9378 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9379 pos elems after-comma)))
9380 (t
9381 (js2-report-error "msg.bad.prop")
9382 (unless js2-recover-from-parse-errors
9383 (setq continue nil)))) ; end switch
9384 (if (js2-match-token js2-COMMA)
9385 (setq after-comma js2-token-end)
9386 (setq continue nil))) ; end loop
9387 (js2-must-match js2-RC "msg.no.brace.prop")
9388 (setq result (make-js2-object-node :pos pos
9389 :len (- js2-ts-cursor pos)
9390 :elems (nreverse elems)))
9391 (apply #'js2-node-add-children result (js2-object-node-elems result))
9392 result))
9393
9394 (defun js2-parse-named-prop (tt)
9395 "Parse a name, string, or getter/setter object property.
9396 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9397 (js2-consume-token)
9398 (let ((string-prop (and (= tt js2-STRING)
9399 (make-js2-string-node)))
9400 expr
9401 (ppos js2-token-beg)
9402 (pend js2-token-end)
9403 (name (js2-create-name-node))
9404 (prop js2-ts-string))
9405 (cond
9406 ;; getter/setter prop
9407 ((and (= tt js2-NAME)
9408 (= (js2-peek-token) js2-NAME)
9409 (or (string= prop "get")
9410 (string= prop "set")))
9411 (js2-consume-token)
9412 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9413 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9414 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9415 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9416 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9417 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9418 ;; when patterns are used in variable declarations, function parameters,
9419 ;; catch-clause, and iterators.
9420 ;; We have to set `js2-is-in-destructuring' to t when the current
9421 ;; expressions are on the left side of any assignment, but it's difficult
9422 ;; because it requires looking ahead of expression.
9423 ((and js2-is-in-destructuring
9424 (= tt js2-NAME)
9425 (let ((ctk (js2-peek-token)))
9426 (or (= ctk js2-COMMA)
9427 (= ctk js2-RC)
9428 (js2-valid-prop-name-token ctk))))
9429 name)
9430 ;; regular prop
9431 (t
9432 (prog1
9433 (setq expr (js2-parse-plain-property (or string-prop name)))
9434 (js2-set-face ppos pend
9435 (if (js2-function-node-p
9436 (js2-object-prop-node-right expr))
9437 'font-lock-function-name-face
9438 'font-lock-variable-name-face)
9439 'record))))))
9440
9441 (defun js2-parse-plain-property (prop)
9442 "Parse a non-getter/setter property in an object literal.
9443 PROP is the node representing the property: a number, name or string."
9444 (js2-must-match js2-COLON "msg.no.colon.prop")
9445 (let* ((pos (js2-node-pos prop))
9446 (colon (- js2-token-beg pos))
9447 (expr (js2-parse-assign-expr))
9448 (result (make-js2-object-prop-node
9449 :pos pos
9450 ;; don't include last consumed token in length
9451 :len (- (+ (js2-node-pos expr)
9452 (js2-node-len expr))
9453 pos)
9454 :left prop
9455 :right expr
9456 :op-pos colon)))
9457 (js2-node-add-children result prop expr)
9458 result))
9459
9460 (defun js2-parse-getter-setter-prop (pos prop get-p)
9461 "Parse getter or setter property in an object literal.
9462 JavaScript syntax is:
9463
9464 { get foo() {...}, set foo(x) {...} }
9465
9466 and expression closure style is also supported
9467
9468 { get foo() x, set foo(x) _x = x }
9469
9470 POS is the start position of the `get' or `set' keyword.
9471 PROP is the `js2-name-node' representing the property name.
9472 GET-P is non-nil if the keyword was `get'."
9473 (let ((type (if get-p js2-GET js2-SET))
9474 result end
9475 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9476 ;; it has to be an anonymous function, as we already parsed the name
9477 (if (/= (js2-node-type fn) js2-FUNCTION)
9478 (js2-report-error "msg.bad.prop")
9479 (if (plusp (length (js2-function-name fn)))
9480 (js2-report-error "msg.bad.prop")))
9481 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9482 (setq end (js2-node-end fn)
9483 result (make-js2-getter-setter-node :type type
9484 :pos pos
9485 :len (- end pos)
9486 :left prop
9487 :right fn))
9488 (js2-node-add-children result prop fn)
9489 result))
9490
9491 (defun js2-create-name-node (&optional check-activation-p token)
9492 "Create a name node using the token info from last scanned name.
9493 In some cases we need to either synthesize a name node, or we lost
9494 the name token information by peeking. If the TOKEN parameter is
9495 not `js2-NAME', then we use the token info saved in instance vars."
9496 (let ((beg js2-token-beg)
9497 (s js2-ts-string)
9498 name)
9499 (when (/= js2-current-token js2-NAME)
9500 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9501 s js2-prev-name-token-string
9502 js2-prev-name-token-start nil
9503 js2-prev-name-token-string nil))
9504 (setq name (make-js2-name-node :pos beg
9505 :name s
9506 :len (length s)))
9507 (if check-activation-p
9508 (js2-check-activation-name s (or token js2-NAME)))
9509 name))
9510
9511 ;;; Indentation support
9512
9513 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9514 ;; Karl cleverly deduces that the desired indentation level is often a
9515 ;; function of paren/bracket/brace nesting depth, which can be determined
9516 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9517 ;; then does some equally clever checks to see if we're in the context of a
9518 ;; substatement of a possibly braceless statement keyword such as if, while,
9519 ;; or finally. This approach yields pretty good results.
9520
9521 ;; The indenter is often "wrong", however, and needs to be overridden.
9522 ;; The right long-term solution is probably to emulate (or integrate
9523 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9524 ;; parse tree from `js2-parse' is present, which is not true at the
9525 ;; moment the user is typing, computing indentation is still thousands
9526 ;; of lines of code to handle every possible syntactic edge case.
9527
9528 ;; In the meantime, the compromise solution is that we offer a "bounce
9529 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9530 ;; current line indent among various likely guess points. This approach
9531 ;; is far from perfect, but should at least make it slightly easier to
9532 ;; move the line towards its desired indentation when manually
9533 ;; overriding Karl's heuristic nesting guesser.
9534
9535 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9536 ;; extensions such as `let' and Array comprehensions. Major kudos to
9537 ;; Karl for coming up with the initial approach, which packs a lot of
9538 ;; punch for so little code.
9539
9540 (defconst js2-possibly-braceless-keywords-re
9541 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9542 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9543 "try" "while" "with" "let")))
9544 "Regular expression matching keywords that are optionally
9545 followed by an opening brace.")
9546
9547 (defconst js2-indent-operator-re
9548 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9549 (regexp-opt '("in" "instanceof") 'words))
9550 "Regular expression matching operators that affect indentation
9551 of continued expressions.")
9552
9553 (defconst js2-declaration-keyword-re
9554 (regexp-opt '("var" "let" "const") 'words)
9555 "Regular expression matching variable declaration keywords.")
9556
9557 ;; This function has horrible results if you're typing an array
9558 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9559 ;; in conjunction with electric-indent, so just disabling it.
9560 (defsubst js2-code-at-bol-p ()
9561 "Return t if the first character on line is non-whitespace."
9562 nil)
9563
9564 (defun js2-insert-and-indent (key)
9565 "Run command bound to KEY and indent current line.
9566 Runs the command bound to KEY in the global keymap and indents
9567 the current line."
9568 (interactive (list (this-command-keys)))
9569 (let ((cmd (lookup-key (current-global-map) key)))
9570 (if (commandp cmd)
9571 (call-interactively cmd)))
9572 ;; don't do the electric keys inside comments or strings,
9573 ;; and don't do bounce-indent with them.
9574 (let ((parse-state (syntax-ppss (point)))
9575 (js2-bounce-indent-p (js2-code-at-bol-p)))
9576 (unless (or (nth 3 parse-state)
9577 (nth 4 parse-state))
9578 (indent-according-to-mode))))
9579
9580 (defun js2-re-search-forward-inner (regexp &optional bound count)
9581 "Auxiliary function for `js2-re-search-forward'."
9582 (let (parse saved-point)
9583 (while (> count 0)
9584 (re-search-forward regexp bound)
9585 (setq parse (if saved-point
9586 (parse-partial-sexp saved-point (point))
9587 (syntax-ppss (point))))
9588 (cond ((nth 3 parse)
9589 (re-search-forward
9590 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9591 (save-excursion (end-of-line) (point)) t))
9592 ((nth 7 parse)
9593 (forward-line))
9594 ((or (nth 4 parse)
9595 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9596 (re-search-forward "\\*/"))
9597 (t
9598 (setq count (1- count))))
9599 (setq saved-point (point))))
9600 (point))
9601
9602 (defun js2-re-search-forward (regexp &optional bound noerror count)
9603 "Search forward but ignore strings and comments.
9604 Invokes `re-search-forward' but treats the buffer as if strings
9605 and comments have been removed."
9606 (let ((saved-point (point))
9607 (search-expr
9608 (cond ((null count)
9609 '(js2-re-search-forward-inner regexp bound 1))
9610 ((< count 0)
9611 '(js2-re-search-backward-inner regexp bound (- count)))
9612 ((> count 0)
9613 '(js2-re-search-forward-inner regexp bound count)))))
9614 (condition-case err
9615 (eval search-expr)
9616 (search-failed
9617 (goto-char saved-point)
9618 (unless noerror
9619 (error (error-message-string err)))))))
9620
9621 (defun js2-re-search-backward-inner (regexp &optional bound count)
9622 "Auxiliary function for `js2-re-search-backward'."
9623 (let (parse)
9624 (while (> count 0)
9625 (re-search-backward regexp bound)
9626 (setq parse (syntax-ppss (point)))
9627 (cond ((nth 3 parse)
9628 (re-search-backward
9629 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9630 (line-beginning-position) t))
9631 ((nth 7 parse)
9632 (goto-char (nth 8 parse)))
9633 ((or (nth 4 parse)
9634 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9635 (re-search-backward "/\\*"))
9636 (t
9637 (setq count (1- count))))))
9638 (point))
9639
9640 (defun js2-re-search-backward (regexp &optional bound noerror count)
9641 "Search backward but ignore strings and comments.
9642 Invokes `re-search-backward' but treats the buffer as if strings
9643 and comments have been removed."
9644 (let ((saved-point (point))
9645 (search-expr
9646 (cond ((null count)
9647 '(js2-re-search-backward-inner regexp bound 1))
9648 ((< count 0)
9649 '(js2-re-search-forward-inner regexp bound (- count)))
9650 ((> count 0)
9651 '(js2-re-search-backward-inner regexp bound count)))))
9652 (condition-case err
9653 (eval search-expr)
9654 (search-failed
9655 (goto-char saved-point)
9656 (unless noerror
9657 (error (error-message-string err)))))))
9658
9659 (defun js2-looking-at-operator-p ()
9660 "Return non-nil if text after point is a non-comma operator."
9661 (and (looking-at js2-indent-operator-re)
9662 (or (not (looking-at ":"))
9663 (save-excursion
9664 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9665 (looking-at "?"))))))
9666
9667 (defun js2-continued-expression-p ()
9668 "Return non-nil if the current line continues an expression."
9669 (save-excursion
9670 (back-to-indentation)
9671 (or (js2-looking-at-operator-p)
9672 (when (js2-re-search-backward "\n" nil t) ;; skip comments
9673 (skip-chars-backward " \t")
9674 (unless (bolp) ;; previous line is empty
9675 (backward-char)
9676 (when (js2-looking-at-operator-p)
9677 (backward-char)
9678 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))
9679
9680 (defun js2-end-of-do-while-loop-p ()
9681 "Return non-nil if word after point is `while' of a do-while
9682 statement, else returns nil. A braceless do-while statement
9683 spanning several lines requires that the start of the loop is
9684 indented to the same column as the current line."
9685 (interactive)
9686 (save-excursion
9687 (when (looking-at "\\s-*\\<while\\>")
9688 (if (save-excursion
9689 (skip-chars-backward "[ \t\n]*}")
9690 (looking-at "[ \t\n]*}"))
9691 (save-excursion
9692 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9693 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9694 (or (looking-at "\\<do\\>")
9695 (let ((saved-indent (current-indentation)))
9696 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9697 (/= (current-indentation) saved-indent)))
9698 (and (looking-at "[ \t]*\\<do\\>")
9699 (not (js2-re-search-forward
9700 "\\<while\\>" (point-at-eol) t))
9701 (= (current-indentation) saved-indent))))))))
9702
9703 (defun js2-multiline-decl-indentation ()
9704 "Returns the declaration indentation column if the current line belongs
9705 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9706 (let (forward-sexp-function ; use Lisp version
9707 at-opening-bracket)
9708 (save-excursion
9709 (back-to-indentation)
9710 (when (not (looking-at js2-declaration-keyword-re))
9711 (when (looking-at js2-indent-operator-re)
9712 (goto-char (match-end 0))) ; continued expressions are ok
9713 (while (and (not at-opening-bracket)
9714 (not (bobp))
9715 (let ((pos (point)))
9716 (save-excursion
9717 (js2-backward-sws)
9718 (or (eq (char-before) ?,)
9719 (and (not (eq (char-before) ?\;))
9720 (and
9721 (prog2 (skip-chars-backward "[[:punct:]]")
9722 (looking-at js2-indent-operator-re)
9723 (js2-backward-sws))
9724 (not (eq (char-before) ?\;))))
9725 (js2-same-line pos)))))
9726 (condition-case err
9727 (backward-sexp)
9728 (scan-error (setq at-opening-bracket t))))
9729 (when (looking-at js2-declaration-keyword-re)
9730 (goto-char (match-end 0))
9731 (1+ (current-column)))))))
9732
9733 (defun js2-ctrl-statement-indentation ()
9734 "Return the proper indentation of current line if it is a control statement.
9735 Returns an indentation if this line starts the body of a control
9736 statement without braces, else returns nil."
9737 (let (forward-sexp-function)
9738 (save-excursion
9739 (back-to-indentation)
9740 (when (and (not (js2-same-line (point-min)))
9741 (not (looking-at "{"))
9742 (js2-re-search-backward "[[:graph:]]" nil t)
9743 (not (looking-at "[{([]"))
9744 (progn
9745 (forward-char)
9746 (when (= (char-before) ?\))
9747 ;; scan-sexps sometimes throws an error
9748 (ignore-errors (backward-sexp))
9749 (skip-chars-backward " \t" (point-at-bol)))
9750 (let ((pt (point)))
9751 (back-to-indentation)
9752 (and (looking-at js2-possibly-braceless-keywords-re)
9753 (= (match-end 0) pt)
9754 (not (js2-end-of-do-while-loop-p))))))
9755 (+ (current-indentation) js2-basic-offset)))))
9756
9757 (defun js2-indent-in-array-comp (parse-status)
9758 "Return non-nil if we think we're in an array comprehension.
9759 In particular, return the buffer position of the first `for' kwd."
9760 (let ((bracket (nth 1 parse-status))
9761 (end (point)))
9762 (when bracket
9763 (save-excursion
9764 (goto-char bracket)
9765 (when (looking-at "\\[")
9766 (forward-char 1)
9767 (js2-forward-sws)
9768 (if (looking-at "[[{]")
9769 (let (forward-sexp-function) ; use Lisp version
9770 (forward-sexp) ; skip destructuring form
9771 (js2-forward-sws)
9772 (if (and (/= (char-after) ?,) ; regular array
9773 (looking-at "for"))
9774 (match-beginning 0)))
9775 ;; to skip arbitrary expressions we need the parser,
9776 ;; so we'll just guess at it.
9777 (if (and (> end (point)) ; not empty literal
9778 (re-search-forward "[^,]]* \\(for\\) " end t)
9779 ;; not inside comment or string literal
9780 (let ((state (parse-partial-sexp bracket (point))))
9781 (not (or (nth 3 state) (nth 4 state)))))
9782 (match-beginning 1))))))))
9783
9784 (defun js2-array-comp-indentation (parse-status for-kwd)
9785 (if (js2-same-line for-kwd)
9786 ;; first continuation line
9787 (save-excursion
9788 (goto-char (nth 1 parse-status))
9789 (forward-char 1)
9790 (skip-chars-forward " \t")
9791 (current-column))
9792 (save-excursion
9793 (goto-char for-kwd)
9794 (current-column))))
9795
9796 (defun js2-proper-indentation (parse-status)
9797 "Return the proper indentation for the current line."
9798 (save-excursion
9799 (back-to-indentation)
9800 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9801 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9802 (continued-expr-p (js2-continued-expression-p))
9803 (declaration-indent (and js2-pretty-multiline-declarations
9804 (js2-multiline-decl-indentation)))
9805 (bracket (nth 1 parse-status))
9806 beg)
9807 (cond
9808 ;; indent array comprehension continuation lines specially
9809 ((and bracket
9810 (>= js2-language-version 170)
9811 (not (js2-same-line bracket))
9812 (setq beg (js2-indent-in-array-comp parse-status))
9813 (>= (point) (save-excursion
9814 (goto-char beg)
9815 (point-at-bol)))) ; at or after first loop?
9816 (js2-array-comp-indentation parse-status beg))
9817
9818 (ctrl-stmt-indent)
9819
9820 ((and declaration-indent continued-expr-p)
9821 (+ declaration-indent js2-basic-offset))
9822
9823 (declaration-indent)
9824
9825 (bracket
9826 (goto-char bracket)
9827 (cond
9828 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9829 (when (save-excursion (skip-chars-backward " \t)")
9830 (looking-at ")"))
9831 (backward-list))
9832 (back-to-indentation)
9833 (and (eq js2-pretty-multiline-declarations 'all)
9834 (looking-at js2-declaration-keyword-re)
9835 (goto-char (1+ (match-end 0))))
9836 (cond (same-indent-p
9837 (current-column))
9838 (continued-expr-p
9839 (+ (current-column) (* 2 js2-basic-offset)))
9840 (t
9841 (+ (current-column) js2-basic-offset))))
9842 (t
9843 (unless same-indent-p
9844 (forward-char)
9845 (skip-chars-forward " \t"))
9846 (current-column))))
9847
9848 (continued-expr-p js2-basic-offset)
9849
9850 (t 0)))))
9851
9852 (defun js2-lineup-comment (parse-status)
9853 "Indent a multi-line block comment continuation line."
9854 (let* ((beg (nth 8 parse-status))
9855 (first-line (js2-same-line beg))
9856 (offset (save-excursion
9857 (goto-char beg)
9858 (if (looking-at "/\\*")
9859 (+ 1 (current-column))
9860 0))))
9861 (unless first-line
9862 (indent-line-to offset))))
9863
9864 (defun js2-backward-sws ()
9865 "Move backward through whitespace and comments."
9866 (interactive)
9867 (while (forward-comment -1)))
9868
9869 (defun js2-forward-sws ()
9870 "Move forward through whitespace and comments."
9871 (interactive)
9872 (while (forward-comment 1)))
9873
9874 (defun js2-current-indent (&optional pos)
9875 "Return column of indentation on current line.
9876 If POS is non-nil, go to that point and return indentation for that line."
9877 (save-excursion
9878 (if pos
9879 (goto-char pos))
9880 (back-to-indentation)
9881 (current-column)))
9882
9883 (defun js2-arglist-close ()
9884 "Return non-nil if we're on a line beginning with a close-paren/brace."
9885 (save-excursion
9886 (goto-char (point-at-bol))
9887 (js2-forward-sws)
9888 (looking-at "[])}]")))
9889
9890 (defun js2-indent-looks-like-label-p ()
9891 (goto-char (point-at-bol))
9892 (js2-forward-sws)
9893 (looking-at (concat js2-mode-identifier-re ":")))
9894
9895 (defun js2-indent-in-objlit-p (parse-status)
9896 "Return non-nil if this looks like an object-literal entry."
9897 (let ((start (nth 1 parse-status)))
9898 (and
9899 start
9900 (save-excursion
9901 (and (zerop (forward-line -1))
9902 (not (< (point) start)) ; crossed a {} boundary
9903 (js2-indent-looks-like-label-p)))
9904 (save-excursion
9905 (js2-indent-looks-like-label-p)))))
9906
9907 ;; If prev line looks like foobar({ then we're passing an object
9908 ;; literal to a function call, and people pretty much always want to
9909 ;; de-dent back to the previous line, so move the 'basic-offset'
9910 ;; position to the front.
9911 (defun js2-indent-objlit-arg-p (parse-status)
9912 (save-excursion
9913 (back-to-indentation)
9914 (js2-backward-sws)
9915 (and (eq (1- (point)) (nth 1 parse-status))
9916 (eq (char-before) ?{)
9917 (progn
9918 (forward-char -1)
9919 (skip-chars-backward " \t")
9920 (eq (char-before) ?\()))))
9921
9922 (defun js2-indent-case-block-p ()
9923 (save-excursion
9924 (back-to-indentation)
9925 (js2-backward-sws)
9926 (goto-char (point-at-bol))
9927 (skip-chars-forward " \t")
9928 (looking-at "case\\s-.+:")))
9929
9930 (defun js2-syntax-bol ()
9931 "Return the point at the first non-whitespace char on the line.
9932 Returns `point-at-bol' if the line is empty."
9933 (save-excursion
9934 (beginning-of-line)
9935 (skip-chars-forward " \t")
9936 (point)))
9937
9938 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
9939 "Cycle among alternate computed indentation positions.
9940 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9941 of the buffer to the current point. NORMAL-COL is the indentation
9942 column computed by the heuristic guesser based on current paren,
9943 bracket, brace and statement nesting. If BACKWARDS, cycle positions
9944 in reverse."
9945 (let ((cur-indent (js2-current-indent))
9946 (old-buffer-undo-list buffer-undo-list)
9947 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9948 (current-line (save-excursion
9949 (forward-line 0) ; move to bol
9950 (1+ (count-lines (point-min) (point)))))
9951 positions pos main-pos anchor arglist-cont same-indent
9952 prev-line-col basic-offset computed-pos)
9953 ;; temporarily don't record undo info, if user requested this
9954 (when js2-mode-indent-inhibit-undo
9955 (setq buffer-undo-list t))
9956 (unwind-protect
9957 (progn
9958 ;; First likely point: indent from beginning of previous code line
9959 (push (setq basic-offset
9960 (+ (save-excursion
9961 (back-to-indentation)
9962 (js2-backward-sws)
9963 (back-to-indentation)
9964 (setq prev-line-col (current-column)))
9965 js2-basic-offset))
9966 positions)
9967
9968 ;; (First + epsilon) likely point: indent 2x from beginning of
9969 ;; previous code line. Google does it this way.
9970 (push (setq basic-offset
9971 (+ (save-excursion
9972 (back-to-indentation)
9973 (js2-backward-sws)
9974 (back-to-indentation)
9975 (setq prev-line-col (current-column)))
9976 (* 2 js2-basic-offset)))
9977 positions)
9978
9979 ;; Second likely point: indent from assign-expr RHS. This
9980 ;; is just a crude guess based on finding " = " on the previous
9981 ;; line containing actual code.
9982 (setq pos (save-excursion
9983 (forward-line -1)
9984 (goto-char (point-at-bol))
9985 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
9986 (point-at-eol) t)
9987 (goto-char (match-end 1))
9988 (skip-chars-forward " \t\r\n")
9989 (current-column))))
9990 (when pos
9991 (incf pos js2-basic-offset)
9992 (push pos positions))
9993
9994 ;; Third likely point: same indent as previous line of code.
9995 ;; Make it the first likely point if we're not on an
9996 ;; arglist-close line and previous line ends in a comma, or
9997 ;; both this line and prev line look like object-literal
9998 ;; elements.
9999 (setq pos (save-excursion
10000 (goto-char (point-at-bol))
10001 (js2-backward-sws)
10002 (back-to-indentation)
10003 (prog1
10004 (current-column)
10005 ;; while we're here, look for trailing comma
10006 (if (save-excursion
10007 (goto-char (point-at-eol))
10008 (js2-backward-sws)
10009 (eq (char-before) ?,))
10010 (setq arglist-cont (1- (point)))))))
10011 (when pos
10012 (if (and (or arglist-cont
10013 (js2-indent-in-objlit-p parse-status))
10014 (not (js2-arglist-close)))
10015 (setq same-indent pos))
10016 (push pos positions))
10017
10018 ;; Fourth likely point: first preceding code with less indentation.
10019 ;; than the immediately preceding code line.
10020 (setq pos (save-excursion
10021 (back-to-indentation)
10022 (js2-backward-sws)
10023 (back-to-indentation)
10024 (setq anchor (current-column))
10025 (while (and (zerop (forward-line -1))
10026 (>= (progn
10027 (back-to-indentation)
10028 (current-column))
10029 anchor)))
10030 (setq pos (current-column))))
10031 (push pos positions)
10032
10033 ;; nesting-heuristic position, main by default
10034 (push (setq main-pos normal-col) positions)
10035
10036 ;; delete duplicates and sort positions list
10037 (setq positions (sort (delete-dups positions) '<))
10038
10039 ;; comma-list continuation lines: prev line indent takes precedence
10040 (if same-indent
10041 (setq main-pos same-indent))
10042
10043 ;; common special cases where we want to indent in from previous line
10044 (if (or (js2-indent-case-block-p)
10045 (js2-indent-objlit-arg-p parse-status))
10046 (setq main-pos basic-offset))
10047
10048 ;; if bouncing backwards, reverse positions list
10049 (if backwards
10050 (setq positions (reverse positions)))
10051
10052 ;; record whether we're already sitting on one of the alternatives
10053 (setq pos (member cur-indent positions))
10054
10055 (cond
10056 ;; case 0: we're one one of the alternatives and this is the
10057 ;; first time they've pressed TAB on this line (best-guess).
10058 ((and js2-mode-indent-ignore-first-tab
10059 pos
10060 ;; first time pressing TAB on this line?
10061 (not (eq js2-mode-last-indented-line current-line)))
10062 ;; do nothing
10063 (setq computed-pos nil))
10064 ;; case 1: only one computed position => use it
10065 ((null (cdr positions))
10066 (setq computed-pos 0))
10067 ;; case 2: not on any of the computed spots => use main spot
10068 ((not pos)
10069 (setq computed-pos (js2-position main-pos positions)))
10070 ;; case 3: on last position: cycle to first position
10071 ((null (cdr pos))
10072 (setq computed-pos 0))
10073 ;; case 4: on intermediate position: cycle to next position
10074 (t
10075 (setq computed-pos (js2-position (second pos) positions))))
10076
10077 ;; see if any hooks want to indent; otherwise we do it
10078 (loop with result = nil
10079 for hook in js2-indent-hook
10080 while (null result)
10081 do
10082 (setq result (funcall hook positions computed-pos))
10083 finally do
10084 (unless (or result (null computed-pos))
10085 (indent-line-to (nth computed-pos positions)))))
10086
10087 ;; finally
10088 (if js2-mode-indent-inhibit-undo
10089 (setq buffer-undo-list old-buffer-undo-list))
10090 ;; see commentary for `js2-mode-last-indented-line'
10091 (setq js2-mode-last-indented-line current-line))))
10092
10093 (defun js2-indent-bounce-backwards ()
10094 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10095 cycles between the computed indentation positions in reverse order."
10096 (interactive)
10097 (js2-indent-line t))
10098
10099 (defun js2-1-line-comment-continuation-p ()
10100 "Return t if we're in a 1-line comment continuation.
10101 If so, we don't ever want to use bounce-indent."
10102 (save-excursion
10103 (and (progn
10104 (forward-line 0)
10105 (looking-at "\\s-*//"))
10106 (progn
10107 (forward-line -1)
10108 (forward-line 0)
10109 (when (looking-at "\\s-*$")
10110 (js2-backward-sws)
10111 (forward-line 0))
10112 (looking-at "\\s-*//")))))
10113
10114 (defun js2-indent-line (&optional bounce-backwards)
10115 "Indent the current line as JavaScript source text."
10116 (interactive)
10117 (let (parse-status current-indent offset indent-col moved
10118 ;; Don't whine about errors/warnings when we're indenting.
10119 ;; This has to be set before calling parse-partial-sexp below.
10120 (inhibit-point-motion-hooks t))
10121 (setq parse-status (save-excursion
10122 (syntax-ppss (point-at-bol)))
10123 offset (- (point) (save-excursion
10124 (back-to-indentation)
10125 (point))))
10126 (js2-with-underscore-as-word-syntax
10127 (if (nth 4 parse-status)
10128 (js2-lineup-comment parse-status)
10129 (setq indent-col (js2-proper-indentation parse-status))
10130 ;; See comments below about `js2-mode-last-indented-line'.
10131 (cond
10132 ;; bounce-indenting is disabled during electric-key indent.
10133 ;; It doesn't work well on first line of buffer.
10134 ((and js2-bounce-indent-p
10135 (not (js2-same-line (point-min)))
10136 (not (js2-1-line-comment-continuation-p)))
10137 (js2-bounce-indent indent-col parse-status bounce-backwards))
10138 ;; just indent to the guesser's likely spot
10139 (t (indent-line-to indent-col))))
10140 (when (plusp offset)
10141 (forward-char offset)))))
10142
10143 (defun js2-indent-region (start end)
10144 "Indent the region, but don't use bounce indenting."
10145 (let ((js2-bounce-indent-p nil)
10146 (indent-region-function nil)
10147 (after-change-functions (remq 'js2-mode-edit
10148 after-change-functions)))
10149 (indent-region start end nil) ; nil for byte-compiler
10150 (js2-mode-edit start end (- end start))))
10151
10152 (defvar js2-minor-mode-map
10153 (let ((map (make-sparse-keymap)))
10154 (define-key map (kbd "C-c C-`") #'js2-next-error)
10155 (define-key map [mouse-1] #'js2-mode-show-node)
10156 map)
10157 "Keymap used when `js2-minor-mode' is active.")
10158
10159 ;;;###autoload
10160 (define-minor-mode js2-minor-mode
10161 "Minor mode for running js2 as a background linter.
10162 This allows you to use a different major mode for JavaScript editing,
10163 such as `espresso-mode', while retaining the asynchronous error/warning
10164 highlighting features of `js2-mode'."
10165 :group 'js2-mode
10166 :lighter " js-lint"
10167 (if js2-minor-mode
10168 (js2-minor-mode-enter)
10169 (js2-minor-mode-exit)))
10170
10171 (defun js2-minor-mode-enter ()
10172 "Initialization for `js2-minor-mode'."
10173 (set (make-local-variable 'max-lisp-eval-depth)
10174 (max max-lisp-eval-depth 3000))
10175 (setq next-error-function #'js2-next-error)
10176 (setq js2-default-externs
10177 (append js2-ecma-262-externs
10178 (if js2-include-browser-externs js2-browser-externs)
10179 (if js2-include-gears-externs js2-gears-externs)
10180 (if js2-include-rhino-externs js2-rhino-externs)))
10181 ;; Experiment: make reparse-delay longer for longer files.
10182 (if (plusp js2-dynamic-idle-timer-adjust)
10183 (setq js2-idle-timer-delay
10184 (* js2-idle-timer-delay
10185 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10186 (setq js2-mode-buffer-dirty-p t
10187 js2-mode-parsing nil)
10188 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10189 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10190 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10191 (js2-reparse))
10192
10193 (defun js2-minor-mode-exit ()
10194 "Turn off `js2-minor-mode'."
10195 (setq next-error-function nil)
10196 (remove-hook 'after-change-functions #'js2-mode-edit t)
10197 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10198 (when js2-mode-node-overlay
10199 (delete-overlay js2-mode-node-overlay)
10200 (setq js2-mode-node-overlay nil))
10201 (js2-remove-overlays)
10202 (setq js2-mode-ast nil))
10203
10204 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10205 (make-variable-buffer-local 'js2-source-buffer)
10206
10207 (defun* js2-display-error-list ()
10208 "Display a navigable buffer listing parse errors/warnings."
10209 (interactive)
10210 (unless (js2-have-errors-p)
10211 (message "No errors")
10212 (return-from js2-display-error-list))
10213 (labels ((annotate-list
10214 (lst type)
10215 "Add diagnostic TYPE and line number to errs list"
10216 (mapcar (lambda (err)
10217 (append err (list type
10218 (line-number-at-pos (nth 1 err)))))
10219 lst)))
10220 (let* ((srcbuf (current-buffer))
10221 (errbuf (get-buffer-create "*js-lint*"))
10222 (errors (annotate-list
10223 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10224 'js2-error)) ; must be a valid face name
10225 (warnings (annotate-list
10226 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10227 'js2-warning)) ; must be a valid face name
10228 (all-errs (sort (append errors warnings)
10229 (lambda (e1 e2)
10230 (funcall '< (nth 1 e1) (nth 1 e2))))))
10231 (with-current-buffer errbuf
10232 (let ((inhibit-read-only t))
10233 (erase-buffer)
10234 (dolist (err all-errs)
10235 (destructuring-bind (msg-key beg end type line) err
10236 (insert-text-button
10237 (format "line %d: %s" line (js2-get-msg msg-key))
10238 'face type
10239 'follow-link "\C-m"
10240 'action 'js2-error-buffer-jump
10241 'js2-msg (js2-get-msg msg-key)
10242 'js2-pos beg)
10243 (insert "\n"))))
10244 (js2-error-buffer-mode)
10245 (setq js2-source-buffer srcbuf)
10246 (pop-to-buffer errbuf)
10247 (goto-char (point-min))
10248 (unless (eobp)
10249 (js2-error-buffer-view))))))
10250
10251 (defvar js2-error-buffer-mode-map
10252 (let ((map (make-sparse-keymap)))
10253 (define-key map "n" #'js2-error-buffer-next)
10254 (define-key map "p" #'js2-error-buffer-prev)
10255 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10256 (define-key map "o" #'js2-error-buffer-view)
10257 (define-key map "q" #'js2-error-buffer-quit)
10258 map)
10259 "Keymap used for js2 diagnostics buffers.")
10260
10261 (defun js2-error-buffer-mode ()
10262 "Major mode for js2 diagnostics buffers.
10263 Selecting an error will jump it to the corresponding source-buffer error.
10264 \\{js2-error-buffer-mode-map}"
10265 (interactive)
10266 (setq major-mode 'js2-error-buffer-mode
10267 mode-name "JS Lint Diagnostics")
10268 (use-local-map js2-error-buffer-mode-map)
10269 (setq truncate-lines t)
10270 (set-buffer-modified-p nil)
10271 (setq buffer-read-only t)
10272 (run-hooks 'js2-error-buffer-mode-hook))
10273
10274 (defun js2-error-buffer-next ()
10275 "Move to next error and view it."
10276 (interactive)
10277 (when (zerop (forward-line 1))
10278 (js2-error-buffer-view)))
10279
10280 (defun js2-error-buffer-prev ()
10281 "Move to previous error and view it."
10282 (interactive)
10283 (when (zerop (forward-line -1))
10284 (js2-error-buffer-view)))
10285
10286 (defun js2-error-buffer-quit ()
10287 "Kill the current buffer."
10288 (interactive)
10289 (kill-buffer))
10290
10291 (defun js2-error-buffer-jump (&rest ignored)
10292 "Jump cursor to current error in source buffer."
10293 (interactive)
10294 (when (js2-error-buffer-view)
10295 (pop-to-buffer js2-source-buffer)))
10296
10297 (defun js2-error-buffer-view ()
10298 "Scroll source buffer to show error at current line."
10299 (interactive)
10300 (cond
10301 ((not (eq major-mode 'js2-error-buffer-mode))
10302 (message "Not in a js2 errors buffer"))
10303 ((not (buffer-live-p js2-source-buffer))
10304 (message "Source buffer has been killed"))
10305 ((not (wholenump (get-text-property (point) 'js2-pos)))
10306 (message "There does not seem to be an error here"))
10307 (t
10308 (let ((pos (get-text-property (point) 'js2-pos))
10309 (msg (get-text-property (point) 'js2-msg)))
10310 (save-selected-window
10311 (pop-to-buffer js2-source-buffer)
10312 (goto-char pos)
10313 (message msg))))))
10314
10315 ;;;###autoload
10316 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10317 ;; FIXME: Should derive from js-mode.
10318 "Major mode for editing JavaScript code."
10319 (setq comment-start "//" ; used by comment-region; don't change it
10320 comment-end "")
10321 (set (make-local-variable 'max-lisp-eval-depth)
10322 (max max-lisp-eval-depth 3000))
10323 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10324 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10325 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10326 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10327 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10328 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10329 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10330 ;; for characters inside regexp literals.
10331 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10332 ;; this is necessary to make `show-paren-function' work properly
10333 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10334 ;; needed for M-x rgrep, among other things
10335 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10336
10337 (set (make-local-variable 'electric-indent-chars)
10338 (append '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
10339 electric-indent-chars))
10340 (set (make-local-variable 'electric-layout-rules)
10341 '((?\; . after) (?\{ . after) (?\} . before)))
10342
10343 ;; some variables needed by cc-engine for paragraph-fill, etc.
10344 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10345 c-comment-start-regexp "/[*/]\\|\\s|"
10346 c-line-comment-starter "//"
10347 c-paragraph-start js2-paragraph-start
10348 c-paragraph-separate "$"
10349 comment-start-skip js2-comment-start-skip
10350 c-syntactic-ws-start js2-syntactic-ws-start
10351 c-syntactic-ws-end js2-syntactic-ws-end
10352 c-syntactic-eol js2-syntactic-eol)
10353
10354 (let ((c-buffer-is-cc-mode t))
10355 ;; Copied from `js-mode'. Also see Bug#6071.
10356 (make-local-variable 'paragraph-start)
10357 (make-local-variable 'paragraph-separate)
10358 (make-local-variable 'paragraph-ignore-fill-prefix)
10359 (make-local-variable 'adaptive-fill-mode)
10360 (make-local-variable 'adaptive-fill-regexp)
10361 (c-setup-paragraph-variables))
10362
10363 (setq js2-default-externs
10364 (append js2-ecma-262-externs
10365 (if js2-include-browser-externs js2-browser-externs)
10366 (if js2-include-gears-externs js2-gears-externs)
10367 (if js2-include-rhino-externs js2-rhino-externs)))
10368
10369 (setq font-lock-defaults '(nil t))
10370
10371 ;; Experiment: make reparse-delay longer for longer files.
10372 (when (plusp js2-dynamic-idle-timer-adjust)
10373 (setq js2-idle-timer-delay
10374 (* js2-idle-timer-delay
10375 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10376
10377 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10378 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10379 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10380 (setq next-error-function #'js2-next-error)
10381 (imenu-add-to-menubar (concat "IM-" mode-name))
10382 (add-to-invisibility-spec '(js2-outline . t))
10383 (set (make-local-variable 'line-move-ignore-invisible) t)
10384 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10385
10386 (if (fboundp 'run-mode-hooks)
10387 (run-mode-hooks 'js2-mode-hook)
10388 (run-hooks 'js2-mode-hook))
10389
10390 (setq js2-mode-functions-hidden nil
10391 js2-mode-comments-hidden nil
10392 js2-mode-buffer-dirty-p t
10393 js2-mode-parsing nil)
10394 (js2-reparse))
10395
10396 (defun js2-mode-exit ()
10397 "Exit `js2-mode' and clean up."
10398 (interactive)
10399 (when js2-mode-node-overlay
10400 (delete-overlay js2-mode-node-overlay)
10401 (setq js2-mode-node-overlay nil))
10402 (js2-remove-overlays)
10403 (setq js2-mode-ast nil)
10404 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10405 (remove-from-invisibility-spec '(js2-outline . t))
10406 (js2-mode-show-all)
10407 (with-silent-modifications
10408 (js2-clear-face (point-min) (point-max))))
10409
10410 (defun js2-mode-reset-timer ()
10411 "Cancel any existing parse timer and schedule a new one."
10412 (if js2-mode-parse-timer
10413 (cancel-timer js2-mode-parse-timer))
10414 (setq js2-mode-parsing nil)
10415 (let ((timer (timer-create)))
10416 (setq js2-mode-parse-timer timer)
10417 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10418 (timer-set-idle-time timer js2-idle-timer-delay)
10419 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10420 (timer-activate-when-idle timer nil)))
10421
10422 (defun js2-mode-idle-reparse (buffer)
10423 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10424 it to be reparsed when the buffer is selected."
10425 (if (eq buffer (current-buffer))
10426 (js2-reparse)
10427 ;; reparse when the buffer is selected again
10428 (with-current-buffer buffer
10429 (add-hook 'window-configuration-change-hook
10430 #'js2-mode-idle-reparse-inner
10431 nil t))))
10432
10433 (defun js2-mode-idle-reparse-inner ()
10434 (remove-hook 'window-configuration-change-hook
10435 #'js2-mode-idle-reparse-inner
10436 t)
10437 (js2-reparse))
10438
10439 (defun js2-mode-edit (beg end len)
10440 "Schedule a new parse after buffer is edited.
10441 Buffer edit spans from BEG to END and is of length LEN."
10442 (setq js2-mode-buffer-dirty-p t)
10443 (js2-mode-hide-overlay)
10444 (js2-mode-reset-timer))
10445
10446 (defun js2-minor-mode-edit (beg end len)
10447 "Callback for buffer edits in `js2-mode'.
10448 Schedules a new parse after buffer is edited.
10449 Buffer edit spans from BEG to END and is of length LEN."
10450 (setq js2-mode-buffer-dirty-p t)
10451 (js2-mode-hide-overlay)
10452 (js2-mode-reset-timer))
10453
10454 (defun js2-reparse (&optional force)
10455 "Re-parse current buffer after user finishes some data entry.
10456 If we get any user input while parsing, including cursor motion,
10457 we discard the parse and reschedule it. If FORCE is nil, then the
10458 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10459 (let (time
10460 interrupted-p
10461 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10462 (unless js2-mode-parsing
10463 (setq js2-mode-parsing t)
10464 (unwind-protect
10465 (when (or js2-mode-buffer-dirty-p force)
10466 (js2-remove-overlays)
10467 (with-silent-modifications
10468 (setq js2-mode-buffer-dirty-p nil
10469 js2-mode-fontifications nil
10470 js2-mode-deferred-properties nil)
10471 (if js2-mode-verbose-parse-p
10472 (message "parsing..."))
10473 (setq time
10474 (js2-time
10475 (setq interrupted-p
10476 (catch 'interrupted
10477 (setq js2-mode-ast (js2-parse))
10478 ;; if parsing is interrupted, comments and regex
10479 ;; literals stay ignored by `parse-partial-sexp'
10480 (remove-text-properties (point-min) (point-max)
10481 '(syntax-table))
10482 (js2-mode-apply-deferred-properties)
10483 (js2-mode-remove-suppressed-warnings)
10484 (js2-mode-show-warnings)
10485 (js2-mode-show-errors)
10486 (if (>= js2-highlight-level 1)
10487 (js2-highlight-jsdoc js2-mode-ast))
10488 nil))))
10489 (if interrupted-p
10490 (progn
10491 ;; unfinished parse => try again
10492 (setq js2-mode-buffer-dirty-p t)
10493 (js2-mode-reset-timer))
10494 (if js2-mode-verbose-parse-p
10495 (message "Parse time: %s" time)))))
10496 (setq js2-mode-parsing nil)
10497 (unless interrupted-p
10498 (setq js2-mode-parse-timer nil))))))
10499
10500 (defun js2-mode-show-node (event)
10501 "Debugging aid: highlight selected AST node on mouse click."
10502 (interactive "e")
10503 (mouse-set-point event)
10504 (let ((node (js2-node-at-point))
10505 beg end)
10506 (when js2-mode-show-overlay
10507 (if (null node)
10508 (message "No node found at location %s" (point))
10509 (setq beg (js2-node-abs-pos node)
10510 end (+ beg (js2-node-len node)))
10511 (if js2-mode-node-overlay
10512 (move-overlay js2-mode-node-overlay beg end)
10513 (setq js2-mode-node-overlay (make-overlay beg end))
10514 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10515 (with-silent-modifications
10516 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10517 (message "%s, parent: %s"
10518 (js2-node-short-name node)
10519 (if (js2-node-parent node)
10520 (js2-node-short-name (js2-node-parent node))
10521 "nil"))))))
10522
10523 (put 'js2-mode-show-node 'CUA 'move)
10524
10525 (defun js2-mode-hide-overlay (&optional p1 p2)
10526 "Remove the debugging overlay when the point moves.
10527 P1 and P2 are the old and new values of point, respectively."
10528 (when js2-mode-node-overlay
10529 (let ((beg (overlay-start js2-mode-node-overlay))
10530 (end (overlay-end js2-mode-node-overlay)))
10531 ;; Sometimes we're called spuriously.
10532 (unless (and p2
10533 (>= p2 beg)
10534 (<= p2 end))
10535 (with-silent-modifications
10536 (remove-text-properties beg end '(point-left nil)))
10537 (delete-overlay js2-mode-node-overlay)
10538 (setq js2-mode-node-overlay nil)))))
10539
10540 (defun js2-mode-reset ()
10541 "Debugging helper: reset everything."
10542 (interactive)
10543 (js2-mode-exit)
10544 (js2-mode))
10545
10546 (defun js2-mode-show-warn-or-err (e face)
10547 "Highlight a warning or error E with FACE.
10548 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10549 The last element is optional. When present, use instead of FACE."
10550 (let* ((key (first e))
10551 (beg (second e))
10552 (end (+ beg (third e)))
10553 ;; Don't inadvertently go out of bounds.
10554 (beg (max (point-min) (min beg (point-max))))
10555 (end (max (point-min) (min end (point-max))))
10556 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10557 (ovl (make-overlay beg end)))
10558 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10559 (overlay-put ovl 'js2-error t)
10560 (put-text-property beg end 'help-echo (js2-get-msg key))
10561 (put-text-property beg end 'point-entered #'js2-echo-error)))
10562
10563 (defun js2-remove-overlays ()
10564 "Remove overlays from buffer that have a `js2-error' property."
10565 (let ((beg (point-min))
10566 (end (point-max)))
10567 (save-excursion
10568 (dolist (o (overlays-in beg end))
10569 (when (overlay-get o 'js2-error)
10570 (delete-overlay o))))))
10571
10572 (defun js2-error-at-point (&optional pos)
10573 "Return non-nil if there's an error overlay at POS.
10574 Defaults to point."
10575 (loop with pos = (or pos (point))
10576 for o in (overlays-at pos)
10577 thereis (overlay-get o 'js2-error)))
10578
10579 (defun js2-mode-apply-deferred-properties ()
10580 "Apply fontifications and other text properties recorded during parsing."
10581 (when (plusp js2-highlight-level)
10582 ;; We defer clearing faces as long as possible to eliminate flashing.
10583 (js2-clear-face (point-min) (point-max))
10584 ;; Have to reverse the recorded fontifications list so that errors
10585 ;; and warnings overwrite the normal fontifications.
10586 (dolist (f (nreverse js2-mode-fontifications))
10587 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10588 (setq js2-mode-fontifications nil))
10589 (dolist (p js2-mode-deferred-properties)
10590 (apply #'put-text-property p))
10591 (setq js2-mode-deferred-properties nil))
10592
10593 (defun js2-mode-show-errors ()
10594 "Highlight syntax errors."
10595 (when js2-mode-show-parse-errors
10596 (dolist (e (js2-ast-root-errors js2-mode-ast))
10597 (js2-mode-show-warn-or-err e 'js2-error))))
10598
10599 (defun js2-mode-remove-suppressed-warnings ()
10600 "Take suppressed warnings out of the AST warnings list.
10601 This ensures that the counts and `next-error' are correct."
10602 (setf (js2-ast-root-warnings js2-mode-ast)
10603 (js2-delete-if
10604 (lambda (e)
10605 (let ((key (caar e)))
10606 (or
10607 (and (not js2-strict-trailing-comma-warning)
10608 (string-match "trailing\\.comma" key))
10609 (and (not js2-strict-cond-assign-warning)
10610 (string= key "msg.equal.as.assign"))
10611 (and js2-missing-semi-one-line-override
10612 (string= key "msg.missing.semi")
10613 (let* ((beg (second e))
10614 (node (js2-node-at-point beg))
10615 (fn (js2-mode-find-parent-fn node))
10616 (body (and fn (js2-function-node-body fn)))
10617 (lc (and body (js2-node-abs-pos body)))
10618 (rc (and lc (+ lc (js2-node-len body)))))
10619 (and fn
10620 (or (null body)
10621 (save-excursion
10622 (goto-char beg)
10623 (and (js2-same-line lc)
10624 (js2-same-line rc))))))))))
10625 (js2-ast-root-warnings js2-mode-ast))))
10626
10627 (defun js2-mode-show-warnings ()
10628 "Highlight strict-mode warnings."
10629 (when js2-mode-show-strict-warnings
10630 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10631 (js2-mode-show-warn-or-err e 'js2-warning))))
10632
10633 (defun js2-echo-error (old-point new-point)
10634 "Called by point-motion hooks."
10635 (let ((msg (get-text-property new-point 'help-echo)))
10636 (when (and (stringp msg) (or (not (current-message))
10637 (string= (current-message) "Quit")))
10638 (message msg))))
10639
10640 (defalias #'js2-echo-help #'js2-echo-error)
10641
10642 (defun js2-line-break (&optional soft)
10643 "Break line at point."
10644 (let ((parse-status (syntax-ppss)))
10645 (cond
10646 ;; Check if we're inside a string.
10647 ((nth 3 parse-status)
10648 (if js2-concat-multiline-strings
10649 (js2-mode-split-string parse-status)
10650 (insert "\n")))
10651 ;; Check if inside a block comment.
10652 ((nth 4 parse-status)
10653 (js2-mode-extend-comment))
10654 (t
10655 (newline)))))
10656
10657 (defun js2-mode-split-string (parse-status)
10658 "Turn a newline in mid-string into a string concatenation.
10659 PARSE-STATUS is as documented in `parse-partial-sexp'."
10660 (let* ((col (current-column))
10661 (quote-char (nth 3 parse-status))
10662 (quote-string (string quote-char))
10663 (string-beg (nth 8 parse-status))
10664 (at-eol (eq js2-concat-multiline-strings 'eol))
10665 (indent (or
10666 (save-excursion
10667 (back-to-indentation)
10668 (if (looking-at "\\+")
10669 (current-column)))
10670 (save-excursion
10671 (goto-char string-beg)
10672 (if (looking-back "\\+\\s-+")
10673 (goto-char (match-beginning 0)))
10674 (current-column)))))
10675 (insert quote-char)
10676 (if at-eol
10677 (insert " +\n")
10678 (insert "\n"))
10679 ;; FIXME: This does not match the behavior of `js2-indent-line'.
10680 (indent-to indent)
10681 (unless at-eol
10682 (insert "+ "))
10683 (insert quote-string)
10684 (when (eolp)
10685 (insert quote-string)
10686 (backward-char 1))))
10687
10688 (defun js2-mode-extend-comment ()
10689 "Indent the line and, when inside a comment block, add comment prefix."
10690 (let (star single col first-line needs-close)
10691 (save-excursion
10692 (back-to-indentation)
10693 (cond
10694 ((looking-at "\\*[^/]")
10695 (setq star t
10696 col (current-column)))
10697 ((looking-at "/\\*")
10698 (setq star t
10699 first-line t
10700 col (1+ (current-column))))
10701 ((looking-at "//")
10702 (setq single t
10703 col (current-column)))))
10704 ;; Heuristic for whether we need to close the comment:
10705 ;; if we've got a parse error here, assume it's an unterminated
10706 ;; comment.
10707 (setq needs-close
10708 (or
10709 (eq (get-text-property (1- (point)) 'point-entered)
10710 'js2-echo-error)
10711 ;; The heuristic above doesn't work well when we're
10712 ;; creating a comment and there's another one downstream,
10713 ;; as our parser thinks this one ends at the end of the
10714 ;; next one. (You can have a /* inside a js block comment.)
10715 ;; So just close it if the next non-ws char isn't a *.
10716 (and first-line
10717 (eolp)
10718 (save-excursion
10719 (skip-chars-forward " \t\r\n")
10720 (not (eq (char-after) ?*))))))
10721 (insert "\n")
10722 (cond
10723 (star
10724 (indent-to col)
10725 (insert "* ")
10726 (if (and first-line needs-close)
10727 (save-excursion
10728 (insert "\n")
10729 (indent-to col)
10730 (insert "*/"))))
10731 ((and single
10732 (save-excursion
10733 (and (zerop (forward-line 1))
10734 (looking-at "\\s-*//"))))
10735 (indent-to col)
10736 (insert "// "))
10737 ;; don't need to extend the comment after all
10738 (js2-enter-indents-newline
10739 (js2-indent-line)))))
10740
10741 (defun js2-beginning-of-line ()
10742 "Toggles point between bol and first non-whitespace char in line.
10743 Also moves past comment delimiters when inside comments."
10744 (interactive)
10745 (let (node beg)
10746 (cond
10747 ((bolp)
10748 (back-to-indentation))
10749 ((looking-at "//")
10750 (skip-chars-forward "/ \t"))
10751 ((and (eq (char-after) ?*)
10752 (setq node (js2-comment-at-point))
10753 (memq (js2-comment-node-format node) '(jsdoc block))
10754 (save-excursion
10755 (skip-chars-backward " \t")
10756 (bolp)))
10757 (skip-chars-forward "\* \t"))
10758 (t
10759 (goto-char (point-at-bol))))))
10760
10761 (defun js2-end-of-line ()
10762 "Toggles point between eol and last non-whitespace char in line."
10763 (interactive)
10764 (if (eolp)
10765 (skip-chars-backward " \t")
10766 (goto-char (point-at-eol))))
10767
10768 (defsubst js2-mode-inside-string ()
10769 "Return non-nil if inside a string.
10770 Actually returns the quote character that begins the string."
10771 (nth 3 (syntax-ppss)))
10772
10773 (defun js2-mode-inside-comment-or-string ()
10774 "Return non-nil if inside a comment or string."
10775 (or
10776 (let ((comment-start
10777 (save-excursion
10778 (goto-char (point-at-bol))
10779 (if (re-search-forward "//" (point-at-eol) t)
10780 (match-beginning 0)))))
10781 (and comment-start
10782 (<= comment-start (point))))
10783 (let ((parse-state (syntax-ppss)))
10784 (or (nth 3 parse-state)
10785 (nth 4 parse-state)))))
10786
10787
10788 (defun js2-insert-catch-skel (try-pos)
10789 "Complete a try/catch block after inserting a { following a try keyword.
10790 Rationale is that a try always needs a catch or a finally, and the catch is
10791 the more likely of the two.
10792
10793 TRY-POS is the buffer position of the try keyword. The open-curly should
10794 already have been inserted."
10795 (insert "{")
10796 (let ((try-col (save-excursion
10797 (goto-char try-pos)
10798 (current-column))))
10799 (insert "\n")
10800 (undo-boundary)
10801 (js2-indent-line) ;; indent the blank line where cursor will end up
10802 (save-excursion
10803 (insert "\n")
10804 (indent-to try-col)
10805 (insert "} catch (x) {\n\n")
10806 (indent-to try-col)
10807 (insert "}"))))
10808
10809
10810 (defun js2-mode-wait-for-parse (callback)
10811 "Invoke CALLBACK when parsing is finished.
10812 If parsing is already finished, calls CALLBACK immediately."
10813 (if (not js2-mode-buffer-dirty-p)
10814 (funcall callback)
10815 (push callback js2-mode-pending-parse-callbacks)
10816 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10817
10818 (defun js2-mode-parse-finished ()
10819 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10820 ;; We can't let errors propagate up, since it prevents the
10821 ;; `js2-parse' method from completing normally and returning
10822 ;; the ast, which makes things mysteriously not work right.
10823 (unwind-protect
10824 (dolist (cb js2-mode-pending-parse-callbacks)
10825 (condition-case err
10826 (funcall cb)
10827 (error (message "%s" err))))
10828 (setq js2-mode-pending-parse-callbacks nil)))
10829
10830 (defun js2-mode-flag-region (from to flag)
10831 "Hide or show text from FROM to TO, according to FLAG.
10832 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10833 Returns the created overlay if FLAG is non-nil."
10834 (remove-overlays from to 'invisible 'js2-outline)
10835 (when flag
10836 (let ((o (make-overlay from to)))
10837 (overlay-put o 'invisible 'js2-outline)
10838 (overlay-put o 'isearch-open-invisible
10839 'js2-isearch-open-invisible)
10840 o)))
10841
10842 ;; Function to be set as an outline-isearch-open-invisible' property
10843 ;; to the overlay that makes the outline invisible (see
10844 ;; `js2-mode-flag-region').
10845 (defun js2-isearch-open-invisible (overlay)
10846 ;; We rely on the fact that isearch places point on the matched text.
10847 (js2-mode-show-element))
10848
10849 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10850 "Return cons cell of bounds of folding overlay at POS.
10851 Returns nil if not found."
10852 (let ((overlays (overlays-at (or pos (point))))
10853 o)
10854 (while (and overlays
10855 (not o))
10856 (if (overlay-get (car overlays) 'invisible)
10857 (setq o (car overlays))
10858 (setq overlays (cdr overlays))))
10859 (if o
10860 (cons (overlay-start o) (overlay-end o)))))
10861
10862 (defun js2-mode-function-at-point (&optional pos)
10863 "Return the innermost function node enclosing current point.
10864 Returns nil if point is not in a function."
10865 (let ((node (js2-node-at-point pos)))
10866 (while (and node (not (js2-function-node-p node)))
10867 (setq node (js2-node-parent node)))
10868 (if (js2-function-node-p node)
10869 node)))
10870
10871 (defun js2-mode-toggle-element ()
10872 "Hide or show the foldable element at the point."
10873 (interactive)
10874 (let (comment fn pos)
10875 (save-excursion
10876 (cond
10877 ;; /* ... */ comment?
10878 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10879 (if (js2-mode-invisible-overlay-bounds
10880 (setq pos (+ 3 (js2-node-abs-pos comment))))
10881 (progn
10882 (goto-char pos)
10883 (js2-mode-show-element))
10884 (js2-mode-hide-element)))
10885 ;; //-comment?
10886 ((save-excursion
10887 (back-to-indentation)
10888 (looking-at js2-mode-//-comment-re))
10889 (js2-mode-toggle-//-comment))
10890 ;; function?
10891 ((setq fn (js2-mode-function-at-point))
10892 (setq pos (and (js2-function-node-body fn)
10893 (js2-node-abs-pos (js2-function-node-body fn))))
10894 (goto-char (1+ pos))
10895 (if (js2-mode-invisible-overlay-bounds)
10896 (js2-mode-show-element)
10897 (js2-mode-hide-element)))
10898 (t
10899 (message "Nothing at point to hide or show"))))))
10900
10901 (defun js2-mode-hide-element ()
10902 "Fold/hide contents of a block, showing ellipses.
10903 Show the hidden text with \\[js2-mode-show-element]."
10904 (interactive)
10905 (if js2-mode-buffer-dirty-p
10906 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10907 (let (node body beg end)
10908 (cond
10909 ((js2-mode-invisible-overlay-bounds)
10910 (message "already hidden"))
10911 (t
10912 (setq node (js2-node-at-point))
10913 (cond
10914 ((js2-block-comment-p node)
10915 (js2-mode-hide-comment node))
10916 (t
10917 (while (and node (not (js2-function-node-p node)))
10918 (setq node (js2-node-parent node)))
10919 (if (and node
10920 (setq body (js2-function-node-body node)))
10921 (progn
10922 (setq beg (js2-node-abs-pos body)
10923 end (+ beg (js2-node-len body)))
10924 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10925 (message "No collapsable element found at point"))))))))
10926
10927 (defun js2-mode-show-element ()
10928 "Show the hidden element at current point."
10929 (interactive)
10930 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10931 (if bounds
10932 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
10933 (message "Nothing to un-hide"))))
10934
10935 (defun js2-mode-show-all ()
10936 "Show all of the text in the buffer."
10937 (interactive)
10938 (js2-mode-flag-region (point-min) (point-max) nil))
10939
10940 (defun js2-mode-toggle-hide-functions ()
10941 (interactive)
10942 (if js2-mode-functions-hidden
10943 (js2-mode-show-functions)
10944 (js2-mode-hide-functions)))
10945
10946 (defun js2-mode-hide-functions ()
10947 "Hides all non-nested function bodies in the buffer.
10948 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10949 to open an individual entry."
10950 (interactive)
10951 (if js2-mode-buffer-dirty-p
10952 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
10953 (if (null js2-mode-ast)
10954 (message "Oops - parsing failed")
10955 (setq js2-mode-functions-hidden t)
10956 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
10957
10958 (defun js2-mode-function-hider (n endp)
10959 (when (not endp)
10960 (let ((tt (js2-node-type n))
10961 body beg end)
10962 (cond
10963 ((and (= tt js2-FUNCTION)
10964 (setq body (js2-function-node-body n)))
10965 (setq beg (js2-node-abs-pos body)
10966 end (+ beg (js2-node-len body)))
10967 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
10968 nil) ; don't process children of function
10969 (t
10970 t))))) ; keep processing other AST nodes
10971
10972 (defun js2-mode-show-functions ()
10973 "Un-hide any folded function bodies in the buffer."
10974 (interactive)
10975 (setq js2-mode-functions-hidden nil)
10976 (save-excursion
10977 (goto-char (point-min))
10978 (while (/= (goto-char (next-overlay-change (point)))
10979 (point-max))
10980 (dolist (o (overlays-at (point)))
10981 (when (and (overlay-get o 'invisible)
10982 (not (overlay-get o 'comment)))
10983 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10984
10985 (defun js2-mode-hide-comment (n)
10986 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
10987 3 ; /**
10988 2)) ; /*
10989 (beg (+ (js2-node-abs-pos n) head))
10990 (end (- (+ beg (js2-node-len n)) head 2))
10991 (o (js2-mode-flag-region beg end 'hide)))
10992 (overlay-put o 'comment t)))
10993
10994 (defun js2-mode-toggle-hide-comments ()
10995 "Folds all block comments in the buffer.
10996 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10997 to open an individual entry."
10998 (interactive)
10999 (if js2-mode-comments-hidden
11000 (js2-mode-show-comments)
11001 (js2-mode-hide-comments)))
11002
11003 (defun js2-mode-hide-comments ()
11004 (interactive)
11005 (if js2-mode-buffer-dirty-p
11006 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11007 (if (null js2-mode-ast)
11008 (message "Oops - parsing failed")
11009 (setq js2-mode-comments-hidden t)
11010 (dolist (n (js2-ast-root-comments js2-mode-ast))
11011 (let ((format (js2-comment-node-format n)))
11012 (when (js2-block-comment-p n)
11013 (js2-mode-hide-comment n))))
11014 (js2-mode-hide-//-comments)))
11015
11016 (defun js2-mode-extend-//-comment (direction)
11017 "Find start or end of a block of similar //-comment lines.
11018 DIRECTION is -1 to look back, 1 to look forward.
11019 INDENT is the indentation level to match.
11020 Returns the end-of-line position of the furthest adjacent
11021 //-comment line with the same indentation as the current line.
11022 If there is no such matching line, returns current end of line."
11023 (let ((pos (point-at-eol))
11024 (indent (current-indentation)))
11025 (save-excursion
11026 (while (and (zerop (forward-line direction))
11027 (looking-at js2-mode-//-comment-re)
11028 (eq indent (length (match-string 1))))
11029 (setq pos (point-at-eol))
11030 pos))))
11031
11032 (defun js2-mode-hide-//-comments ()
11033 "Fold adjacent 1-line comments, showing only snippet of first one."
11034 (let (beg end)
11035 (save-excursion
11036 (goto-char (point-min))
11037 (while (re-search-forward js2-mode-//-comment-re nil t)
11038 (setq beg (point)
11039 end (js2-mode-extend-//-comment 1))
11040 (unless (eq beg end)
11041 (overlay-put (js2-mode-flag-region beg end 'hide)
11042 'comment t))
11043 (goto-char end)
11044 (forward-char 1)))))
11045
11046 (defun js2-mode-toggle-//-comment ()
11047 "Fold or un-fold any multi-line //-comment at point.
11048 Caller should have determined that this line starts with a //-comment."
11049 (let* ((beg (point-at-eol))
11050 (end beg))
11051 (save-excursion
11052 (goto-char end)
11053 (if (js2-mode-invisible-overlay-bounds)
11054 (js2-mode-show-element)
11055 ;; else hide the comment
11056 (setq beg (js2-mode-extend-//-comment -1)
11057 end (js2-mode-extend-//-comment 1))
11058 (unless (eq beg end)
11059 (overlay-put (js2-mode-flag-region beg end 'hide)
11060 'comment t))))))
11061
11062 (defun js2-mode-show-comments ()
11063 "Un-hide any hidden comments, leaving other hidden elements alone."
11064 (interactive)
11065 (setq js2-mode-comments-hidden nil)
11066 (save-excursion
11067 (goto-char (point-min))
11068 (while (/= (goto-char (next-overlay-change (point)))
11069 (point-max))
11070 (dolist (o (overlays-at (point)))
11071 (when (overlay-get o 'comment)
11072 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11073
11074 (defun js2-mode-display-warnings-and-errors ()
11075 "Turn on display of warnings and errors."
11076 (interactive)
11077 (setq js2-mode-show-parse-errors t
11078 js2-mode-show-strict-warnings t)
11079 (js2-reparse 'force))
11080
11081 (defun js2-mode-hide-warnings-and-errors ()
11082 "Turn off display of warnings and errors."
11083 (interactive)
11084 (setq js2-mode-show-parse-errors nil
11085 js2-mode-show-strict-warnings nil)
11086 (js2-reparse 'force))
11087
11088 (defun js2-mode-toggle-warnings-and-errors ()
11089 "Toggle the display of warnings and errors.
11090 Some users don't like having warnings/errors reported while they type."
11091 (interactive)
11092 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11093 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11094 (if (called-interactively-p 'any)
11095 (message "warnings and errors %s"
11096 (if js2-mode-show-parse-errors
11097 "enabled"
11098 "disabled")))
11099 (js2-reparse 'force))
11100
11101 (defun js2-mode-customize ()
11102 (interactive)
11103 (customize-group 'js2-mode))
11104
11105 (defun js2-mode-forward-sexp (&optional arg)
11106 "Move forward across one statement or balanced expression.
11107 With ARG, do it that many times. Negative arg -N means
11108 move backward across N balanced expressions."
11109 (interactive "p")
11110 (setq arg (or arg 1))
11111 (save-restriction
11112 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11113 (js2-reparse))
11114 (let ((scan-msg "Containing expression ends prematurely")
11115 node (start (point)) pos lp rp child)
11116 (cond
11117 ;; backward-sexp
11118 ;; could probably make this better for some cases:
11119 ;; - if in statement block (e.g. function body), go to parent
11120 ;; - infix exprs like (foo in bar) - maybe go to beginning
11121 ;; of infix expr if in the right-side expression?
11122 ((and arg (minusp arg))
11123 (dotimes (i (- arg))
11124 (js2-backward-sws)
11125 (forward-char -1) ; enter the node we backed up to
11126 (when (setq node (js2-node-at-point (point) t))
11127 (setq pos (js2-node-abs-pos node))
11128 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11129 (setq lp (car parens)
11130 rp (cdr parens))))
11131 (goto-char
11132 (or (when (and lp (> start lp))
11133 (if (and rp (<= start rp))
11134 (if (setq child (js2-node-closest-child node (point) lp t))
11135 (js2-node-abs-pos child)
11136 (goto-char start)
11137 (signal 'scan-error (list scan-msg lp lp)))
11138 lp))
11139 pos
11140 (point-min)))))
11141 (t
11142 ;; forward-sexp
11143 (js2-forward-sws)
11144 (dotimes (i arg)
11145 (js2-forward-sws)
11146 (when (setq node (js2-node-at-point (point) t))
11147 (setq pos (js2-node-abs-pos node))
11148 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11149 (setq lp (car parens)
11150 rp (cdr parens))))
11151 (goto-char
11152 (or (when (and rp (<= start rp))
11153 (if (> start lp)
11154 (if (setq child (js2-node-closest-child node (point) rp))
11155 (js2-node-abs-end child)
11156 (goto-char start)
11157 (signal 'scan-error (list scan-msg rp (1+ rp))))
11158 (1+ rp)))
11159 (and pos
11160 (+ pos
11161 (js2-node-len
11162 (if (js2-expr-stmt-node-p (js2-node-parent node))
11163 ;; stop after the semicolon
11164 (js2-node-parent node)
11165 node))))
11166 (point-max))))))))
11167
11168 (defun js2-mode-forward-sexp-parens (node abs-pos)
11169 (cond
11170 ((or (js2-array-node-p node)
11171 (js2-object-node-p node)
11172 (js2-array-comp-node-p node)
11173 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11174 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11175 ((js2-paren-expr-node-p node)
11176 (let ((lp (js2-node-lp node))
11177 (rp (js2-node-rp node)))
11178 (cons (when lp (+ abs-pos lp))
11179 (when rp (+ abs-pos rp)))))))
11180
11181 (defun js2-node-closest-child (parent point limit &optional before)
11182 (let* ((parent-pos (js2-node-abs-pos parent))
11183 (rpoint (- point parent-pos))
11184 (rlimit (- limit parent-pos))
11185 (min (min rpoint rlimit))
11186 (max (max rpoint rlimit))
11187 found)
11188 (catch 'done
11189 (js2-visit-ast
11190 parent
11191 (lambda (node end-p)
11192 (if (eq node parent)
11193 t
11194 (let ((pos (js2-node-pos node)) ;; Both relative values.
11195 (end (+ (js2-node-pos node) (js2-node-len node))))
11196 (when (and (>= pos min) (<= end max)
11197 (if before (< pos rpoint) (> end rpoint)))
11198 (setq found node))
11199 (when (> end rpoint)
11200 (throw 'done nil)))
11201 nil))))
11202 found))
11203
11204 (defun js2-errors ()
11205 "Return a list of errors found."
11206 (and js2-mode-ast
11207 (js2-ast-root-errors js2-mode-ast)))
11208
11209 (defun js2-warnings ()
11210 "Return a list of warnings found."
11211 (and js2-mode-ast
11212 (js2-ast-root-warnings js2-mode-ast)))
11213
11214 (defun js2-have-errors-p ()
11215 "Return non-nil if any parse errors or warnings were found."
11216 (or (js2-errors) (js2-warnings)))
11217
11218 (defun js2-errors-and-warnings ()
11219 "Return a copy of the concatenated errors and warnings lists.
11220 They are appended: first the errors, then the warnings.
11221 Entries are of the form (MSG BEG END)."
11222 (when js2-mode-ast
11223 (append (js2-ast-root-errors js2-mode-ast)
11224 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11225
11226 (defun js2-next-error (&optional arg reset)
11227 "Move to next parse error.
11228 Typically invoked via \\[next-error].
11229 ARG is the number of errors, forward or backward, to move.
11230 RESET means start over from the beginning."
11231 (interactive "p")
11232 (if (not (or (js2-errors) (js2-warnings)))
11233 (message "No errors")
11234 (when reset
11235 (goto-char (point-min)))
11236 (let* ((errs (js2-errors-and-warnings))
11237 (continue t)
11238 (start (point))
11239 (count (or arg 1))
11240 (backward (minusp count))
11241 (sorter (if backward '> '<))
11242 (stopper (if backward '< '>))
11243 (count (abs count))
11244 all-errs err)
11245 ;; Sort by start position.
11246 (setq errs (sort errs (lambda (e1 e2)
11247 (funcall sorter (second e1) (second e2))))
11248 all-errs errs)
11249 ;; Find nth error with pos > start.
11250 (while (and errs continue)
11251 (when (funcall stopper (cadar errs) start)
11252 (setq err (car errs))
11253 (if (zerop (decf count))
11254 (setq continue nil)))
11255 (setq errs (cdr errs)))
11256 (if err
11257 (goto-char (second err))
11258 ;; Wrap around to first error.
11259 (goto-char (second (car all-errs)))
11260 ;; If we were already on it, echo msg again.
11261 (if (= (point) start)
11262 (js2-echo-error (point) (point)))))))
11263
11264 (defun js2-down-mouse-3 ()
11265 "Make right-click move the point to the click location.
11266 This makes right-click context menu operations a bit more intuitive.
11267 The point will not move if the region is active, however, to avoid
11268 destroying the region selection."
11269 (interactive)
11270 (when (and js2-move-point-on-right-click
11271 (not mark-active))
11272 (let ((e last-input-event))
11273 (ignore-errors
11274 (goto-char (cadadr e))))))
11275
11276 (defun js2-mode-create-imenu-index ()
11277 "Return an alist for `imenu--index-alist'."
11278 ;; This is built up in `js2-parse-record-imenu' during parsing.
11279 (when js2-mode-ast
11280 ;; if we have an ast but no recorder, they're requesting a rescan
11281 (unless js2-imenu-recorder
11282 (js2-reparse 'force))
11283 (prog1
11284 (js2-build-imenu-index)
11285 (setq js2-imenu-recorder nil
11286 js2-imenu-function-map nil))))
11287
11288 (defun js2-mode-find-tag ()
11289 "Replacement for `find-tag-default'.
11290 `find-tag-default' returns a ridiculous answer inside comments."
11291 (let (beg end)
11292 (js2-with-underscore-as-word-syntax
11293 (save-excursion
11294 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11295 (looking-back "[A-Za-z0-9_$]"))
11296 (setq beg (progn (forward-word -1) (point))
11297 end (progn (forward-word 1) (point)))
11298 (setq beg (progn (forward-word 1) (point))
11299 end (progn (forward-word -1) (point))))
11300 (replace-regexp-in-string
11301 "[\"']" ""
11302 (buffer-substring-no-properties beg end))))))
11303
11304 (defun js2-mode-forward-sibling ()
11305 "Move to the end of the sibling following point in parent.
11306 Returns non-nil if successful, or nil if there was no following sibling."
11307 (let* ((node (js2-node-at-point))
11308 (parent (js2-mode-find-enclosing-fn node))
11309 sib)
11310 (when (setq sib (js2-node-find-child-after (point) parent))
11311 (goto-char (+ (js2-node-abs-pos sib)
11312 (js2-node-len sib))))))
11313
11314 (defun js2-mode-backward-sibling ()
11315 "Move to the beginning of the sibling node preceding point in parent.
11316 Parent is defined as the enclosing script or function."
11317 (let* ((node (js2-node-at-point))
11318 (parent (js2-mode-find-enclosing-fn node))
11319 sib)
11320 (when (setq sib (js2-node-find-child-before (point) parent))
11321 (goto-char (js2-node-abs-pos sib)))))
11322
11323 (defun js2-beginning-of-defun (&optional arg)
11324 "Go to line on which current function starts, and return t on success.
11325 If we're not in a function or already at the beginning of one, go
11326 to beginning of previous script-level element.
11327 With ARG N, do that N times. If N is negative, move forward."
11328 (setq arg (or arg 1))
11329 (if (plusp arg)
11330 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11331 (when (cond
11332 ((js2-function-node-p parent)
11333 (goto-char (js2-node-abs-pos parent)))
11334 (t
11335 (js2-mode-backward-sibling)))
11336 (if (> arg 1)
11337 (js2-beginning-of-defun (1- arg))
11338 t)))
11339 (when (js2-end-of-defun)
11340 (if (>= arg -1)
11341 (js2-beginning-of-defun 1)
11342 (js2-beginning-of-defun (1+ arg))))))
11343
11344 (defun js2-end-of-defun ()
11345 "Go to the char after the last position of the current function
11346 or script-level element."
11347 (let* ((node (js2-node-at-point))
11348 (parent (or (and (js2-function-node-p node) node)
11349 (js2-node-parent-script-or-fn node)))
11350 script)
11351 (unless (js2-function-node-p parent)
11352 ;; Use current script-level node, or, if none, the next one.
11353 (setq script (or parent node)
11354 parent (js2-node-find-child-before (point) script))
11355 (when (or (null parent)
11356 (>= (point) (+ (js2-node-abs-pos parent)
11357 (js2-node-len parent))))
11358 (setq parent (js2-node-find-child-after (point) script))))
11359 (when parent
11360 (goto-char (+ (js2-node-abs-pos parent)
11361 (js2-node-len parent))))))
11362
11363 (defun js2-mark-defun (&optional allow-extend)
11364 "Put mark at end of this function, point at beginning.
11365 The function marked is the one that contains point.
11366
11367 Interactively, if this command is repeated,
11368 or (in Transient Mark mode) if the mark is active,
11369 it marks the next defun after the ones already marked."
11370 (interactive "p")
11371 (let (extended)
11372 (when (and allow-extend
11373 (or (and (eq last-command this-command) (mark t))
11374 (and transient-mark-mode mark-active)))
11375 (let ((sib (save-excursion
11376 (goto-char (mark))
11377 (if (js2-mode-forward-sibling)
11378 (point))))
11379 node)
11380 (if sib
11381 (progn
11382 (set-mark sib)
11383 (setq extended t))
11384 ;; no more siblings - try extending to enclosing node
11385 (goto-char (mark t)))))
11386 (when (not extended)
11387 (let ((node (js2-node-at-point (point) t)) ; skip comments
11388 ast fn stmt parent beg end)
11389 (when (js2-ast-root-p node)
11390 (setq ast node
11391 node (or (js2-node-find-child-after (point) node)
11392 (js2-node-find-child-before (point) node))))
11393 ;; only mark whole buffer if we can't find any children
11394 (if (null node)
11395 (setq node ast))
11396 (if (js2-function-node-p node)
11397 (setq parent node)
11398 (setq fn (js2-mode-find-enclosing-fn node)
11399 stmt (if (or (null fn)
11400 (js2-ast-root-p fn))
11401 (js2-mode-find-first-stmt node))
11402 parent (or stmt fn)))
11403 (setq beg (js2-node-abs-pos parent)
11404 end (+ beg (js2-node-len parent)))
11405 (push-mark beg)
11406 (goto-char end)
11407 (exchange-point-and-mark)))))
11408
11409 (defun js2-narrow-to-defun ()
11410 "Narrow to the function enclosing point."
11411 (interactive)
11412 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11413 (fn (if (js2-script-node-p node)
11414 node
11415 (js2-mode-find-enclosing-fn node)))
11416 (beg (js2-node-abs-pos fn)))
11417 (unless (js2-ast-root-p fn)
11418 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11419
11420 (provide 'js2-mode)
11421
11422 ;;; js2-mode.el ends here