]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Support for..of in loops and array comprehensions
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- an improved JavaScript editing mode
2
3 ;; Copyright (C) 2009 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 ;; To customize how it works:
47 ;; M-x customize-group RET js2-mode RET
48
49 ;; Notes:
50
51 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
52 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
53 ;; `js2-mode' current as the EcmaScript language standard evolves.
54
55 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
56 ;; customizable. It is a surprising amount of work to support customizable
57 ;; indentation. The current compromise is that the tab key lets you cycle among
58 ;; various likely indentation points, similar to the behavior of python-mode.
59
60 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
61 ;; and `mumamo', although it could be made to do so with some effort.
62 ;; This means that `js2-mode' is currently only useful for editing JavaScript
63 ;; files, and not for editing JavaScript within <script> tags or templates.
64
65 ;;; Code:
66
67 (eval-when-compile
68 (require 'cl))
69
70 (require 'imenu)
71 (require 'cc-cmds) ; for `c-fill-paragraph'
72
73 (eval-and-compile
74 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
75 (require 'cc-langs) ; it's here in Emacs 21...
76 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
77
78 ;;; Externs (variables presumed to be defined by the host system)
79
80 (defvar js2-ecma-262-externs
81 (mapcar 'symbol-name
82 '(Array Boolean Date Error EvalError Function Infinity JSON
83 Math NaN Number Object RangeError ReferenceError RegExp
84 String SyntaxError TypeError URIError arguments
85 decodeURI decodeURIComponent encodeURI
86 encodeURIComponent escape eval isFinite isNaN
87 parseFloat parseInt undefined unescape))
88 "Ecma-262 externs. Included in `js2-externs' by default.")
89
90 (defvar js2-browser-externs
91 (mapcar 'symbol-name
92 '(;; DOM level 1
93 Attr CDATASection CharacterData Comment DOMException
94 DOMImplementation Document DocumentFragment
95 DocumentType Element Entity EntityReference
96 ExceptionCode NamedNodeMap Node NodeList Notation
97 ProcessingInstruction Text
98
99 ;; DOM level 2
100 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
101 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
102 HTMLBodyElement HTMLButtonElement HTMLCollection
103 HTMLDListElement HTMLDirectoryElement HTMLDivElement
104 HTMLDocument HTMLElement HTMLFieldSetElement
105 HTMLFontElement HTMLFormElement HTMLFrameElement
106 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
107 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
108 HTMLImageElement HTMLInputElement HTMLIsIndexElement
109 HTMLLIElement HTMLLabelElement HTMLLegendElement
110 HTMLLinkElement HTMLMapElement HTMLMenuElement
111 HTMLMetaElement HTMLModElement HTMLOListElement
112 HTMLObjectElement HTMLOptGroupElement
113 HTMLOptionElement HTMLOptionsCollection
114 HTMLParagraphElement HTMLParamElement HTMLPreElement
115 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
116 HTMLStyleElement HTMLTableCaptionElement
117 HTMLTableCellElement HTMLTableColElement
118 HTMLTableElement HTMLTableRowElement
119 HTMLTableSectionElement HTMLTextAreaElement
120 HTMLTitleElement HTMLUListElement
121
122 ;; DOM level 3
123 DOMConfiguration DOMError DOMException
124 DOMImplementationList DOMImplementationSource
125 DOMLocator DOMStringList NameList TypeInfo
126 UserDataHandler
127
128 ;; Window
129 window alert confirm document java navigator prompt screen
130 self top
131
132 ;; W3C CSS
133 CSSCharsetRule CSSFontFace CSSFontFaceRule
134 CSSImportRule CSSMediaRule CSSPageRule
135 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
136 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
137 CSSValue CSSValueList Counter DOMImplementationCSS
138 DocumentCSS DocumentStyle ElementCSSInlineStyle
139 LinkStyle MediaList RGBColor Rect StyleSheet
140 StyleSheetList ViewCSS
141
142 ;; W3C Event
143 EventListener EventTarget Event DocumentEvent UIEvent
144 MouseEvent MutationEvent KeyboardEvent
145
146 ;; W3C Range
147 DocumentRange Range RangeException
148
149 ;; W3C XML
150 XPathResult XMLHttpRequest))
151 "Browser externs.
152 You can cause these to be included or excluded with the custom
153 variable `js2-include-browser-externs'.")
154
155 (defvar js2-rhino-externs
156 (mapcar 'symbol-name
157 '(Packages importClass importPackage com org java
158 ;; Global object (shell) externs
159 defineClass deserialize doctest gc help load
160 loadClass print quit readFile readUrl runCommand seal
161 serialize spawn sync toint32 version))
162 "Mozilla Rhino externs.
163 Set `js2-include-rhino-externs' to t to include them.")
164
165 (defvar js2-gears-externs
166 (mapcar 'symbol-name
167 '(
168 ;; TODO(stevey): add these
169 ))
170 "Google Gears externs.
171 Set `js2-include-gears-externs' to t to include them.")
172
173 ;;; Variables
174
175 (defun js2-mark-safe-local (name pred)
176 "Make the variable NAME buffer-local and mark it as safe file-local
177 variable with predicate PRED."
178 (make-variable-buffer-local name)
179 (put name 'safe-local-variable pred))
180
181 (defvar js2-emacs22 (>= emacs-major-version 22))
182
183 (defcustom js2-highlight-level 2
184 "Amount of syntax highlighting to perform.
185 0 or a negative value means do no highlighting.
186 1 adds basic syntax highlighting.
187 2 adds highlighting of some Ecma built-in properties.
188 3 adds highlighting of many Ecma built-in functions."
189 :group 'js2-mode
190 :type '(choice (const :tag "None" 0)
191 (const :tag "Basic" 1)
192 (const :tag "Include Properties" 2)
193 (const :tag "Include Functions" 3)))
194
195 (defvar js2-mode-dev-mode-p nil
196 "Non-nil if running in development mode. Normally nil.")
197
198 (defgroup js2-mode nil
199 "An improved JavaScript mode."
200 :group 'languages)
201
202 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
203 (numberp c-basic-offset))
204 c-basic-offset
205 4)
206 "Number of spaces to indent nested statements.
207 Similar to `c-basic-offset'."
208 :group 'js2-mode
209 :type 'integer)
210 (js2-mark-safe-local 'js2-basic-offset 'integerp)
211
212 ;; TODO(stevey): move this code into a separate minor mode.
213 (defcustom js2-mirror-mode nil
214 "Non-nil to insert closing brackets, parens, etc. automatically."
215 :group 'js2-mode
216 :type 'boolean)
217
218 (defcustom js2-auto-indent-p nil
219 "Automatic indentation with punctuation characters.
220 If non-nil, the current line is indented when certain punctuations
221 are inserted."
222 :group 'js2-mode
223 :type 'boolean)
224
225 (defcustom js2-bounce-indent-p nil
226 "Non-nil to have indent-line function choose among alternatives.
227 If nil, the indent-line function will indent to a predetermined column
228 based on heuristic guessing. If non-nil, then if the current line is
229 already indented to that predetermined column, indenting will choose
230 another likely column and indent to that spot. Repeated invocation of
231 the indent-line function will cycle among the computed alternatives.
232 See the function `js2-bounce-indent' for details. When it is non-nil,
233 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
234 :type 'boolean
235 :group 'js2-mode)
236
237 (defcustom js2-pretty-multiline-declarations t
238 "Non-nil to line up multiline declarations vertically:
239
240 var a = 10,
241 b = 20,
242 c = 30;
243
244 If the value is not `all', and the first assigned value in
245 declaration is a function/array/object literal spanning several
246 lines, it won't be indented additionally:
247
248 var o = { var bar = 2,
249 foo: 3 vs. o = {
250 }, foo: 3
251 bar = 2; };"
252 :group 'js2-mode
253 :type 'symbol)
254 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
255
256 (defcustom js2-indent-on-enter-key nil
257 "Non-nil to have Enter/Return key indent the line.
258 This is unusual for Emacs modes but common in IDEs like Eclipse."
259 :type 'boolean
260 :group 'js2-mode)
261
262 (defcustom js2-enter-indents-newline nil
263 "Non-nil to have Enter/Return key indent the newly-inserted line.
264 This is unusual for Emacs modes but common in IDEs like Eclipse."
265 :type 'boolean
266 :group 'js2-mode)
267
268 (defcustom js2-rebind-eol-bol-keys t
269 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
270 If non-nil, bounce between bol/eol and first/last non-whitespace char."
271 :group 'js2-mode
272 :type 'boolean)
273
274 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
275 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
276 Each value in the list is passed to `define-key'."
277 :type 'list
278 :group 'js2-mode)
279
280 (defcustom js2-idle-timer-delay 0.2
281 "Delay in secs before re-parsing after user makes changes.
282 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
283 :type 'number
284 :group 'js2-mode)
285 (make-variable-buffer-local 'js2-idle-timer-delay)
286
287 (defcustom js2-dynamic-idle-timer-adjust 0
288 "Positive to adjust `js2-idle-timer-delay' based on file size.
289 The idea is that for short files, parsing is faster so we can be
290 more responsive to user edits without interfering with editing.
291 The buffer length in characters (typically bytes) is divided by
292 this value and used to multiply `js2-idle-timer-delay' for the
293 buffer. For example, a 21k file and 10k adjust yields 21k/10k
294 == 2, so js2-idle-timer-delay is multiplied by 2.
295 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
296 `js2-idle-timer-delay' is not dependent on the file size."
297 :type 'number
298 :group 'js2-mode)
299
300 (defcustom js2-mode-escape-quotes t
301 "Non-nil to disable automatic quote-escaping inside strings."
302 :type 'boolean
303 :group 'js2-mode)
304
305 (defcustom js2-concat-multiline-strings t
306 "Non-nil to automatically turn a newline in mid-string into a
307 string concatenation. When `eol', the '+' will be inserted at the
308 end of the line, otherwise, at the beginning of the next line."
309 :type '(choice (const t) (const eol) (const nil))
310 :group 'js2-mode)
311
312 (defcustom js2-mode-squeeze-spaces t
313 "Non-nil to normalize whitespace when filling in comments.
314 Multiple runs of spaces are converted to a single space."
315 :type 'boolean
316 :group 'js2-mode)
317
318 (defcustom js2-mode-show-parse-errors t
319 "True to highlight parse errors."
320 :type 'boolean
321 :group 'js2-mode)
322
323 (defcustom js2-mode-show-strict-warnings t
324 "Non-nil to emit Ecma strict-mode warnings.
325 Some of the warnings can be individually disabled by other flags,
326 even if this flag is non-nil."
327 :type 'boolean
328 :group 'js2-mode)
329
330 (defcustom js2-strict-trailing-comma-warning t
331 "Non-nil to warn about trailing commas in array literals.
332 Ecma-262 forbids them, but many browsers permit them. IE is the
333 big exception, and can produce bugs if you have trailing commas."
334 :type 'boolean
335 :group 'js2-mode)
336
337 (defcustom js2-strict-missing-semi-warning t
338 "Non-nil to warn about semicolon auto-insertion after statement.
339 Technically this is legal per Ecma-262, but some style guides disallow
340 depending on it."
341 :type 'boolean
342 :group 'js2-mode)
343
344 (defcustom js2-missing-semi-one-line-override nil
345 "Non-nil to permit missing semicolons in one-line functions.
346 In one-liner functions such as `function identity(x) {return x}'
347 people often omit the semicolon for a cleaner look. If you are
348 such a person, you can suppress the missing-semicolon warning
349 by setting this variable to t."
350 :type 'boolean
351 :group 'js2-mode)
352
353 (defcustom js2-strict-inconsistent-return-warning t
354 "Non-nil to warn about mixing returns with value-returns.
355 It's perfectly legal to have a `return' and a `return foo' in the
356 same function, but it's often an indicator of a bug, and it also
357 interferes with type inference (in systems that support it.)"
358 :type 'boolean
359 :group 'js2-mode)
360
361 (defcustom js2-strict-cond-assign-warning t
362 "Non-nil to warn about expressions like if (a = b).
363 This often should have been '==' instead of '='. If the warning
364 is enabled, you can suppress it on a per-expression basis by
365 parenthesizing the expression, e.g. if ((a = b)) ..."
366 :type 'boolean
367 :group 'js2-mode)
368
369 (defcustom js2-strict-var-redeclaration-warning t
370 "Non-nil to warn about redeclaring variables in a script or function."
371 :type 'boolean
372 :group 'js2-mode)
373
374 (defcustom js2-strict-var-hides-function-arg-warning t
375 "Non-nil to warn about a var decl hiding a function argument."
376 :type 'boolean
377 :group 'js2-mode)
378
379 (defcustom js2-skip-preprocessor-directives nil
380 "Non-nil to treat lines beginning with # as comments.
381 Useful for viewing Mozilla JavaScript source code."
382 :type 'boolean
383 :group 'js2-mode)
384
385 (defcustom js2-language-version 200
386 "Configures what JavaScript language version to recognize.
387 Currently versions 150, 160, 170, 180 and 200 are supported,
388 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
389 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
390 yield, and Array comprehensions, and 1.8 adds function closures."
391 :type 'integer
392 :group 'js2-mode)
393
394 (defcustom js2-allow-keywords-as-property-names t
395 "If non-nil, you can use JavaScript keywords as object property names.
396 Examples:
397
398 var foo = {int: 5, while: 6, continue: 7};
399 foo.return = 8;
400
401 Ecma-262 forbids this syntax, but many browsers support it."
402 :type 'boolean
403 :group 'js2-mode)
404
405 (defcustom js2-instanceof-has-side-effects nil
406 "If non-nil, treats the instanceof operator as having side effects.
407 This is useful for xulrunner apps."
408 :type 'boolean
409 :group 'js2-mode)
410
411 (defcustom js2-cleanup-whitespace nil
412 "Non-nil to invoke `delete-trailing-whitespace' before saves."
413 :type 'boolean
414 :group 'js2-mode)
415
416 (defcustom js2-move-point-on-right-click t
417 "Non-nil to move insertion point when you right-click.
418 This makes right-click context menu behavior a bit more intuitive,
419 since menu operations generally apply to the point. The exception
420 is if there is a region selection, in which case the point does -not-
421 move, so cut/copy/paste etc. can work properly.
422
423 Note that IntelliJ moves the point, and Eclipse leaves it alone,
424 so this behavior is customizable."
425 :group 'js2-mode
426 :type 'boolean)
427
428 (defcustom js2-allow-rhino-new-expr-initializer t
429 "Non-nil to support a Rhino's experimental syntactic construct.
430
431 Rhino supports the ability to follow a `new' expression with an object
432 literal, which is used to set additional properties on the new object
433 after calling its constructor. Syntax:
434
435 new <expr> [ ( arglist ) ] [initializer]
436
437 Hence, this expression:
438
439 new Object {a: 1, b: 2}
440
441 results in an Object with properties a=1 and b=2. This syntax is
442 apparently not configurable in Rhino - it's currently always enabled,
443 as of Rhino version 1.7R2."
444 :type 'boolean
445 :group 'js2-mode)
446
447 (defcustom js2-allow-member-expr-as-function-name nil
448 "Non-nil to support experimental Rhino syntax for function names.
449
450 Rhino supports an experimental syntax configured via the Rhino Context
451 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
452
453 function <member-expr> ( [ arg-list ] ) { <body> }
454
455 Where member-expr is a non-parenthesized 'member expression', which
456 is anything at the grammar level of a new-expression or lower, meaning
457 any expression that does not involve infix or unary operators.
458
459 When <member-expr> is not a simple identifier, then it is syntactic
460 sugar for assigning the anonymous function to the <member-expr>. Hence,
461 this code:
462
463 function a.b().c[2] (x, y) { ... }
464
465 is rewritten as:
466
467 a.b().c[2] = function(x, y) {...}
468
469 which doesn't seem particularly useful, but Rhino permits it."
470 :type 'boolean
471 :group 'js2-mode)
472
473 (defvar js2-mode-version 20101228
474 "Release number for `js2-mode'.")
475
476 ;; scanner variables
477
478 (defmacro js2-deflocal (name value &optional comment)
479 "Define a buffer-local variable NAME with VALUE and COMMENT."
480 `(progn
481 (defvar ,name ,value ,comment)
482 (make-variable-buffer-local ',name)))
483
484 ;; We record the start and end position of each token.
485 (js2-deflocal js2-token-beg 1)
486 (js2-deflocal js2-token-end -1)
487
488 (defvar js2-EOF_CHAR -1
489 "Represents end of stream. Distinct from js2-EOF token type.")
490
491 ;; I originally used symbols to represent tokens, but Rhino uses
492 ;; ints and then sets various flag bits in them, so ints it is.
493 ;; The upshot is that we need a `js2-' prefix in front of each name.
494 (defvar js2-ERROR -1)
495 (defvar js2-EOF 0)
496 (defvar js2-EOL 1)
497 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
498 (defvar js2-LEAVEWITH 3)
499 (defvar js2-RETURN 4)
500 (defvar js2-GOTO 5)
501 (defvar js2-IFEQ 6)
502 (defvar js2-IFNE 7)
503 (defvar js2-SETNAME 8)
504 (defvar js2-BITOR 9)
505 (defvar js2-BITXOR 10)
506 (defvar js2-BITAND 11)
507 (defvar js2-EQ 12)
508 (defvar js2-NE 13)
509 (defvar js2-LT 14)
510 (defvar js2-LE 15)
511 (defvar js2-GT 16)
512 (defvar js2-GE 17)
513 (defvar js2-LSH 18)
514 (defvar js2-RSH 19)
515 (defvar js2-URSH 20)
516 (defvar js2-ADD 21) ; infix plus
517 (defvar js2-SUB 22) ; infix minus
518 (defvar js2-MUL 23)
519 (defvar js2-DIV 24)
520 (defvar js2-MOD 25)
521 (defvar js2-NOT 26)
522 (defvar js2-BITNOT 27)
523 (defvar js2-POS 28) ; unary plus
524 (defvar js2-NEG 29) ; unary minus
525 (defvar js2-NEW 30)
526 (defvar js2-DELPROP 31)
527 (defvar js2-TYPEOF 32)
528 (defvar js2-GETPROP 33)
529 (defvar js2-GETPROPNOWARN 34)
530 (defvar js2-SETPROP 35)
531 (defvar js2-GETELEM 36)
532 (defvar js2-SETELEM 37)
533 (defvar js2-CALL 38)
534 (defvar js2-NAME 39) ; an identifier
535 (defvar js2-NUMBER 40)
536 (defvar js2-STRING 41)
537 (defvar js2-NULL 42)
538 (defvar js2-THIS 43)
539 (defvar js2-FALSE 44)
540 (defvar js2-TRUE 45)
541 (defvar js2-SHEQ 46) ; shallow equality (===)
542 (defvar js2-SHNE 47) ; shallow inequality (!==)
543 (defvar js2-REGEXP 48)
544 (defvar js2-BINDNAME 49)
545 (defvar js2-THROW 50)
546 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
547 (defvar js2-IN 52)
548 (defvar js2-INSTANCEOF 53)
549 (defvar js2-LOCAL_LOAD 54)
550 (defvar js2-GETVAR 55)
551 (defvar js2-SETVAR 56)
552 (defvar js2-CATCH_SCOPE 57)
553 (defvar js2-ENUM_INIT_KEYS 58)
554 (defvar js2-ENUM_INIT_VALUES 59)
555 (defvar js2-ENUM_INIT_ARRAY 60)
556 (defvar js2-ENUM_NEXT 61)
557 (defvar js2-ENUM_ID 62)
558 (defvar js2-THISFN 63)
559 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
560 (defvar js2-ARRAYLIT 65) ; array literal
561 (defvar js2-OBJECTLIT 66) ; object literal
562 (defvar js2-GET_REF 67) ; *reference
563 (defvar js2-SET_REF 68) ; *reference = something
564 (defvar js2-DEL_REF 69) ; delete reference
565 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
566 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
567 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
568
569 ;; XML support
570 (defvar js2-DEFAULTNAMESPACE 73)
571 (defvar js2-ESCXMLATTR 74)
572 (defvar js2-ESCXMLTEXT 75)
573 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
574 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
575 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
576 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
577
578 (defvar js2-first-bytecode js2-ENTERWITH)
579 (defvar js2-last-bytecode js2-REF_NS_NAME)
580
581 (defvar js2-TRY 80)
582 (defvar js2-SEMI 81) ; semicolon
583 (defvar js2-LB 82) ; left and right brackets
584 (defvar js2-RB 83)
585 (defvar js2-LC 84) ; left and right curly-braces
586 (defvar js2-RC 85)
587 (defvar js2-LP 86) ; left and right parens
588 (defvar js2-RP 87)
589 (defvar js2-COMMA 88) ; comma operator
590
591 (defvar js2-ASSIGN 89) ; simple assignment (=)
592 (defvar js2-ASSIGN_BITOR 90) ; |=
593 (defvar js2-ASSIGN_BITXOR 91) ; ^=
594 (defvar js2-ASSIGN_BITAND 92) ; &=
595 (defvar js2-ASSIGN_LSH 93) ; <<=
596 (defvar js2-ASSIGN_RSH 94) ; >>=
597 (defvar js2-ASSIGN_URSH 95) ; >>>=
598 (defvar js2-ASSIGN_ADD 96) ; +=
599 (defvar js2-ASSIGN_SUB 97) ; -=
600 (defvar js2-ASSIGN_MUL 98) ; *=
601 (defvar js2-ASSIGN_DIV 99) ; /=
602 (defvar js2-ASSIGN_MOD 100) ; %=
603
604 (defvar js2-first-assign js2-ASSIGN)
605 (defvar js2-last-assign js2-ASSIGN_MOD)
606
607 (defvar js2-HOOK 101) ; conditional (?:)
608 (defvar js2-COLON 102)
609 (defvar js2-OR 103) ; logical or (||)
610 (defvar js2-AND 104) ; logical and (&&)
611 (defvar js2-INC 105) ; increment/decrement (++ --)
612 (defvar js2-DEC 106)
613 (defvar js2-DOT 107) ; member operator (.)
614 (defvar js2-FUNCTION 108) ; function keyword
615 (defvar js2-EXPORT 109) ; export keyword
616 (defvar js2-IMPORT 110) ; import keyword
617 (defvar js2-IF 111) ; if keyword
618 (defvar js2-ELSE 112) ; else keyword
619 (defvar js2-SWITCH 113) ; switch keyword
620 (defvar js2-CASE 114) ; case keyword
621 (defvar js2-DEFAULT 115) ; default keyword
622 (defvar js2-WHILE 116) ; while keyword
623 (defvar js2-DO 117) ; do keyword
624 (defvar js2-FOR 118) ; for keyword
625 (defvar js2-BREAK 119) ; break keyword
626 (defvar js2-CONTINUE 120) ; continue keyword
627 (defvar js2-VAR 121) ; var keyword
628 (defvar js2-WITH 122) ; with keyword
629 (defvar js2-CATCH 123) ; catch keyword
630 (defvar js2-FINALLY 124) ; finally keyword
631 (defvar js2-VOID 125) ; void keyword
632 (defvar js2-RESERVED 126) ; reserved keywords
633
634 (defvar js2-EMPTY 127)
635
636 ;; Types used for the parse tree - never returned by scanner.
637
638 (defvar js2-BLOCK 128) ; statement block
639 (defvar js2-LABEL 129) ; label
640 (defvar js2-TARGET 130)
641 (defvar js2-LOOP 131)
642 (defvar js2-EXPR_VOID 132) ; expression statement in functions
643 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
644 (defvar js2-JSR 134)
645 (defvar js2-SCRIPT 135) ; top-level node for entire script
646 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
647 (defvar js2-USE_STACK 137)
648 (defvar js2-SETPROP_OP 138) ; x.y op= something
649 (defvar js2-SETELEM_OP 139) ; x[y] op= something
650 (defvar js2-LOCAL_BLOCK 140)
651 (defvar js2-SET_REF_OP 141) ; *reference op= something
652
653 ;; For XML support:
654 (defvar js2-DOTDOT 142) ; member operator (..)
655 (defvar js2-COLONCOLON 143) ; namespace::name
656 (defvar js2-XML 144) ; XML type
657 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
658 (defvar js2-XMLATTR 146) ; @
659 (defvar js2-XMLEND 147)
660
661 ;; Optimizer-only tokens
662 (defvar js2-TO_OBJECT 148)
663 (defvar js2-TO_DOUBLE 149)
664
665 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
666 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
667 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
668 (defvar js2-CONST 153)
669 (defvar js2-SETCONST 154)
670 (defvar js2-SETCONSTVAR 155)
671 (defvar js2-ARRAYCOMP 156)
672 (defvar js2-LETEXPR 157)
673 (defvar js2-WITHEXPR 158)
674 (defvar js2-DEBUGGER 159)
675
676 (defvar js2-COMMENT 160)
677 (defvar js2-ENUM 161) ; for "enum" reserved word
678 (defvar js2-OF 162) ; for "for of" iterators
679
680 (defconst js2-num-tokens (1+ js2-OF))
681
682 (defconst js2-debug-print-trees nil)
683
684 ;; Rhino accepts any string or stream as input. Emacs character
685 ;; processing works best in buffers, so we'll assume the input is a
686 ;; buffer. JavaScript strings can be copied into temp buffers before
687 ;; scanning them.
688
689 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
690 ;; They're the Emacs equivalent of instance variables, more or less.
691
692 (js2-deflocal js2-ts-dirty-line nil
693 "Token stream buffer-local variable.
694 Indicates stuff other than whitespace since start of line.")
695
696 (js2-deflocal js2-ts-regexp-flags nil
697 "Token stream buffer-local variable.")
698
699 (js2-deflocal js2-ts-string ""
700 "Token stream buffer-local variable.
701 Last string scanned.")
702
703 (js2-deflocal js2-ts-number nil
704 "Token stream buffer-local variable.
705 Last literal number scanned.")
706
707 (js2-deflocal js2-ts-hit-eof nil
708 "Token stream buffer-local variable.")
709
710 (js2-deflocal js2-ts-line-start 0
711 "Token stream buffer-local variable.")
712
713 (js2-deflocal js2-ts-lineno 1
714 "Token stream buffer-local variable.")
715
716 (js2-deflocal js2-ts-line-end-char -1
717 "Token stream buffer-local variable.")
718
719 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
720 "Token stream buffer-local variable.
721 Current scan position.")
722
723 (js2-deflocal js2-ts-is-xml-attribute nil
724 "Token stream buffer-local variable.")
725
726 (js2-deflocal js2-ts-xml-is-tag-content nil
727 "Token stream buffer-local variable.")
728
729 (js2-deflocal js2-ts-xml-open-tags-count 0
730 "Token stream buffer-local variable.")
731
732 (js2-deflocal js2-ts-string-buffer nil
733 "Token stream buffer-local variable.
734 List of chars built up while scanning various tokens.")
735
736 (js2-deflocal js2-ts-comment-type nil
737 "Token stream buffer-local variable.")
738
739 ;;; Parser variables
740
741 (js2-deflocal js2-parsed-errors nil
742 "List of errors produced during scanning/parsing.")
743
744 (js2-deflocal js2-parsed-warnings nil
745 "List of warnings produced during scanning/parsing.")
746
747 (js2-deflocal js2-recover-from-parse-errors t
748 "Non-nil to continue parsing after a syntax error.
749
750 In recovery mode, the AST will be built in full, and any error
751 nodes will be flagged with appropriate error information. If
752 this flag is nil, a syntax error will result in an error being
753 signaled.
754
755 The variable is automatically buffer-local, because different
756 modes that use the parser will need different settings.")
757
758 (js2-deflocal js2-parse-hook nil
759 "List of callbacks for receiving parsing progress.")
760
761 (defvar js2-parse-finished-hook nil
762 "List of callbacks to notify when parsing finishes.
763 Not called if parsing was interrupted.")
764
765 (js2-deflocal js2-is-eval-code nil
766 "True if we're evaluating code in a string.
767 If non-nil, the tokenizer will record the token text, and the AST nodes
768 will record their source text. Off by default for IDE modes, since the
769 text is available in the buffer.")
770
771 (defvar js2-parse-ide-mode t
772 "Non-nil if the parser is being used for `js2-mode'.
773 If non-nil, the parser will set text properties for fontification
774 and the syntax table. The value should be nil when using the
775 parser as a frontend to an interpreter or byte compiler.")
776
777 ;;; Parser instance variables (buffer-local vars for js2-parse)
778
779 (defconst js2-clear-ti-mask #xFFFF
780 "Mask to clear token information bits.")
781
782 (defconst js2-ti-after-eol (lsh 1 16)
783 "Flag: first token of the source line.")
784
785 (defconst js2-ti-check-label (lsh 1 17)
786 "Flag: indicates to check for label.")
787
788 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
789
790 (js2-deflocal js2-compiler-generate-debug-info t)
791 (js2-deflocal js2-compiler-use-dynamic-scope nil)
792 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
793 (js2-deflocal js2-compiler-xml-available t)
794 (js2-deflocal js2-compiler-optimization-level 0)
795 (js2-deflocal js2-compiler-generating-source t)
796 (js2-deflocal js2-compiler-strict-mode nil)
797 (js2-deflocal js2-compiler-report-warning-as-error nil)
798 (js2-deflocal js2-compiler-generate-observer-count nil)
799 (js2-deflocal js2-compiler-activation-names nil)
800
801 ;; SKIP: sourceURI
802
803 ;; There's a compileFunction method in Context.java - may need it.
804 (js2-deflocal js2-called-by-compile-function nil
805 "True if `js2-parse' was called by `js2-compile-function'.
806 Will only be used when we finish implementing the interpreter.")
807
808 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
809
810 (js2-deflocal js2-current-flagged-token js2-EOF)
811 (js2-deflocal js2-current-token js2-EOF)
812
813 ;; SKIP: node factory - we're going to just call functions directly,
814 ;; and eventually go to a unified AST format.
815
816 (js2-deflocal js2-nesting-of-function 0)
817
818 (js2-deflocal js2-recorded-identifiers nil
819 "Tracks identifiers found during parsing.")
820
821 (defmacro js2-in-lhs (body)
822 `(let ((js2-is-in-lhs t))
823 ,body))
824
825 (defmacro js2-in-rhs (body)
826 `(let ((js2-is-in-lhs nil))
827 ,body))
828
829 (js2-deflocal js2-is-in-lhs nil
830 "True while parsing lhs statement")
831
832 (defcustom js2-global-externs nil
833 "A list of any extern names you'd like to consider always declared.
834 This list is global and is used by all js2-mode files.
835 You can create buffer-local externs list using `js2-additional-externs'.
836
837 There is also a buffer-local variable `js2-default-externs',
838 which is initialized by default to include the Ecma-262 externs
839 and the standard browser externs. The three lists are all
840 checked during highlighting."
841 :type 'list
842 :group 'js2-mode)
843
844 (js2-deflocal js2-default-externs nil
845 "Default external declarations.
846
847 These are currently only used for highlighting undeclared variables,
848 which only worries about top-level (unqualified) references.
849 As js2-mode's processing improves, we will flesh out this list.
850
851 The initial value is set to `js2-ecma-262-externs', unless you
852 have set `js2-include-browser-externs', in which case the browser
853 externs are also included.
854
855 See `js2-additional-externs' for more information.")
856
857 (defcustom js2-include-browser-externs t
858 "Non-nil to include browser externs in the master externs list.
859 If you work on JavaScript files that are not intended for browsers,
860 such as Mozilla Rhino server-side JavaScript, set this to nil.
861 You can always include them on a per-file basis by calling
862 `js2-add-browser-externs' from a function on `js2-mode-hook'.
863
864 See `js2-additional-externs' for more information about externs."
865 :type 'boolean
866 :group 'js2-mode)
867
868 (defcustom js2-include-rhino-externs t
869 "Non-nil to include Mozilla Rhino externs in the master externs list.
870 See `js2-additional-externs' for more information about externs."
871 :type 'boolean
872 :group 'js2-mode)
873
874 (defcustom js2-include-gears-externs t
875 "Non-nil to include Google Gears externs in the master externs list.
876 See `js2-additional-externs' for more information about externs."
877 :type 'boolean
878 :group 'js2-mode)
879
880 (js2-deflocal js2-additional-externs nil
881 "A buffer-local list of additional external declarations.
882 It is used to decide whether variables are considered undeclared
883 for purposes of highlighting.
884
885 Each entry is a lisp string. The string should be the fully qualified
886 name of an external entity. All externs should be added to this list,
887 so that as js2-mode's processing improves it can take advantage of them.
888
889 You may want to declare your externs in three ways.
890 First, you can add externs that are valid for all your JavaScript files.
891 You should probably do this by adding them to `js2-global-externs', which
892 is a global list used for all js2-mode files.
893
894 Next, you can add a function to `js2-mode-hook' that adds additional
895 externs appropriate for the specific file, perhaps based on its path.
896 These should go in `js2-additional-externs', which is buffer-local.
897
898 Finally, you can add a function to `js2-post-parse-callbacks',
899 which is called after parsing completes, and `root' is bound to
900 the root of the parse tree. At this stage you can set up an AST
901 node visitor using `js2-visit-ast' and examine the parse tree
902 for specific import patterns that may imply the existence of
903 other externs, possibly tied to your build system. These should also
904 be added to `js2-additional-externs'.
905
906 Your post-parse callback may of course also use the simpler and
907 faster (but perhaps less robust) approach of simply scanning the
908 buffer text for your imports, using regular expressions.")
909
910 ;; SKIP: decompiler
911 ;; SKIP: encoded-source
912
913 ;;; The following variables are per-function and should be saved/restored
914 ;;; during function parsing...
915
916 (js2-deflocal js2-current-script-or-fn nil)
917 (js2-deflocal js2-current-scope nil)
918 (js2-deflocal js2-nesting-of-with 0)
919 (js2-deflocal js2-label-set nil
920 "An alist mapping label names to nodes.")
921
922 (js2-deflocal js2-loop-set nil)
923 (js2-deflocal js2-loop-and-switch-set nil)
924 (js2-deflocal js2-has-return-value nil)
925 (js2-deflocal js2-end-flags 0)
926
927 ;;; ...end of per function variables
928
929 ;; Without 2-token lookahead, labels are a problem.
930 ;; These vars store the token info of the last matched name,
931 ;; iff it wasn't the last matched token. Only valid in some contexts.
932 (defvar js2-prev-name-token-start nil)
933 (defvar js2-prev-name-token-string nil)
934
935 (defsubst js2-save-name-token-data (pos name)
936 (setq js2-prev-name-token-start pos
937 js2-prev-name-token-string name))
938
939 ;; These flags enumerate the possible ways a statement/function can
940 ;; terminate. These flags are used by endCheck() and by the Parser to
941 ;; detect inconsistent return usage.
942 ;;
943 ;; END_UNREACHED is reserved for code paths that are assumed to always be
944 ;; able to execute (example: throw, continue)
945 ;;
946 ;; END_DROPS_OFF indicates if the statement can transfer control to the
947 ;; next one. Statement such as return dont. A compound statement may have
948 ;; some branch that drops off control to the next statement.
949 ;;
950 ;; END_RETURNS indicates that the statement can return (without arguments)
951 ;; END_RETURNS_VALUE indicates that the statement can return a value.
952 ;;
953 ;; A compound statement such as
954 ;; if (condition) {
955 ;; return value;
956 ;; }
957 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
958
959 (defconst js2-end-unreached #x0)
960 (defconst js2-end-drops-off #x1)
961 (defconst js2-end-returns #x2)
962 (defconst js2-end-returns-value #x4)
963 (defconst js2-end-yields #x8)
964
965 ;; Rhino awkwardly passes a statementLabel parameter to the
966 ;; statementHelper() function, the main statement parser, which
967 ;; is then used by quite a few of the sub-parsers. We just make
968 ;; it a buffer-local variable and make sure it's cleaned up properly.
969 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
970
971 ;; Similarly, Rhino passes an inForInit boolean through about half
972 ;; the expression parsers. We use a dynamically-scoped variable,
973 ;; which makes it easier to funcall the parsers individually without
974 ;; worrying about whether they take the parameter or not.
975 (js2-deflocal js2-in-for-init nil)
976 (js2-deflocal js2-temp-name-counter 0)
977 (js2-deflocal js2-parse-stmt-count 0)
978
979 (defsubst js2-get-next-temp-name ()
980 (format "$%d" (incf js2-temp-name-counter)))
981
982 (defvar js2-parse-interruptable-p t
983 "Set this to nil to force parse to continue until finished.
984 This will mostly be useful for interpreters.")
985
986 (defvar js2-statements-per-pause 50
987 "Pause after this many statements to check for user input.
988 If user input is pending, stop the parse and discard the tree.
989 This makes for a smoother user experience for large files.
990 You may have to wait a second or two before the highlighting
991 and error-reporting appear, but you can always type ahead if
992 you wish. This appears to be more or less how Eclipse, IntelliJ
993 and other editors work.")
994
995 (js2-deflocal js2-record-comments t
996 "Instructs the scanner to record comments in `js2-scanned-comments'.")
997
998 (js2-deflocal js2-scanned-comments nil
999 "List of all comments from the current parse.")
1000
1001 (defcustom js2-mode-indent-inhibit-undo nil
1002 "Non-nil to disable collection of Undo information when indenting lines.
1003 Some users have requested this behavior. It's nil by default because
1004 other Emacs modes don't work this way."
1005 :type 'boolean
1006 :group 'js2-mode)
1007
1008 (defcustom js2-mode-indent-ignore-first-tab nil
1009 "If non-nil, ignore first TAB keypress if we look indented properly.
1010 It's fairly common for users to navigate to an already-indented line
1011 and press TAB for reassurance that it's been indented. For this class
1012 of users, we want the first TAB press on a line to be ignored if the
1013 line is already indented to one of the precomputed alternatives.
1014
1015 This behavior is only partly implemented. If you TAB-indent a line,
1016 navigate to another line, and then navigate back, it fails to clear
1017 the last-indented variable, so it thinks you've already hit TAB once,
1018 and performs the indent. A full solution would involve getting on the
1019 point-motion hooks for the entire buffer. If we come across another
1020 use cases that requires watching point motion, I'll consider doing it.
1021
1022 If you set this variable to nil, then the TAB key will always change
1023 the indentation of the current line, if more than one alternative
1024 indentation spot exists."
1025 :type 'boolean
1026 :group 'js2-mode)
1027
1028 (defvar js2-indent-hook nil
1029 "A hook for user-defined indentation rules.
1030
1031 Functions on this hook should expect two arguments: (LIST INDEX)
1032 The LIST argument is the list of computed indentation points for
1033 the current line. INDEX is the list index of the indentation point
1034 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1035 indent function is not going to change the current line indentation.
1036
1037 If a hook function on this list returns a non-nil value, then
1038 `js2-bounce-indent' assumes the hook function has performed its own
1039 indentation, and will do nothing. If all hook functions on the list
1040 return nil, then `js2-bounce-indent' will use its computed indentation
1041 and reindent the line.
1042
1043 When hook functions on this hook list are called, the variable
1044 `js2-mode-ast' may or may not be set, depending on whether the
1045 parse tree is available. If the variable is nil, you can pass a
1046 callback to `js2-mode-wait-for-parse', and your callback will be
1047 called after the new parse tree is built. This can take some time
1048 in large files.")
1049
1050 (defface js2-warning-face
1051 `((((class color) (background light))
1052 (:underline "orange"))
1053 (((class color) (background dark))
1054 (:underline "orange"))
1055 (t (:underline t)))
1056 "Face for JavaScript warnings."
1057 :group 'js2-mode)
1058
1059 (defface js2-error-face
1060 `((((class color) (background light))
1061 (:foreground "red"))
1062 (((class color) (background dark))
1063 (:foreground "red"))
1064 (t (:foreground "red")))
1065 "Face for JavaScript errors."
1066 :group 'js2-mode)
1067
1068 (defface js2-jsdoc-tag-face
1069 '((t :foreground "SlateGray"))
1070 "Face used to highlight @whatever tags in jsdoc comments."
1071 :group 'js2-mode)
1072
1073 (defface js2-jsdoc-type-face
1074 '((t :foreground "SteelBlue"))
1075 "Face used to highlight {FooBar} types in jsdoc comments."
1076 :group 'js2-mode)
1077
1078 (defface js2-jsdoc-value-face
1079 '((t :foreground "PeachPuff3"))
1080 "Face used to highlight tag values in jsdoc comments."
1081 :group 'js2-mode)
1082
1083 (defface js2-function-param-face
1084 '((t :foreground "SeaGreen"))
1085 "Face used to highlight function parameters in javascript."
1086 :group 'js2-mode)
1087
1088 (defface js2-instance-member-face
1089 '((t :foreground "DarkOrchid"))
1090 "Face used to highlight instance variables in javascript.
1091 Not currently used."
1092 :group 'js2-mode)
1093
1094 (defface js2-private-member-face
1095 '((t :foreground "PeachPuff3"))
1096 "Face used to highlight calls to private methods in javascript.
1097 Not currently used."
1098 :group 'js2-mode)
1099
1100 (defface js2-private-function-call-face
1101 '((t :foreground "goldenrod"))
1102 "Face used to highlight calls to private functions in javascript.
1103 Not currently used."
1104 :group 'js2-mode)
1105
1106 (defface js2-jsdoc-html-tag-name-face
1107 (if js2-emacs22
1108 '((((class color) (min-colors 88) (background light))
1109 (:foreground "rosybrown"))
1110 (((class color) (min-colors 8) (background dark))
1111 (:foreground "yellow"))
1112 (((class color) (min-colors 8) (background light))
1113 (:foreground "magenta")))
1114 '((((type tty pc) (class color) (background light))
1115 (:foreground "magenta"))
1116 (((type tty pc) (class color) (background dark))
1117 (:foreground "yellow"))
1118 (t (:foreground "RosyBrown"))))
1119 "Face used to highlight jsdoc html tag names"
1120 :group 'js2-mode)
1121
1122 (defface js2-jsdoc-html-tag-delimiter-face
1123 (if js2-emacs22
1124 '((((class color) (min-colors 88) (background light))
1125 (:foreground "dark khaki"))
1126 (((class color) (min-colors 8) (background dark))
1127 (:foreground "green"))
1128 (((class color) (min-colors 8) (background light))
1129 (:foreground "green")))
1130 '((((type tty pc) (class color) (background light))
1131 (:foreground "green"))
1132 (((type tty pc) (class color) (background dark))
1133 (:foreground "green"))
1134 (t (:foreground "dark khaki"))))
1135 "Face used to highlight brackets in jsdoc html tags."
1136 :group 'js2-mode)
1137
1138 (defface js2-magic-paren-face
1139 '((t :underline t))
1140 "Face used to color parens that will be auto-overwritten."
1141 :group 'js2-mode)
1142
1143 (defcustom js2-post-parse-callbacks nil
1144 "A list of callback functions invoked after parsing finishes.
1145 Currently, the main use for this function is to add synthetic
1146 declarations to `js2-recorded-identifiers', which see."
1147 :type 'list
1148 :group 'js2-mode)
1149
1150 (defface js2-external-variable-face
1151 '((t :foreground "orange"))
1152 "Face used to highlight undeclared variable identifiers.
1153 An undeclared variable is any variable not declared with var or let
1154 in the current scope or any lexically enclosing scope. If you use
1155 such a variable, then you are either expecting it to originate from
1156 another file, or you've got a potential bug."
1157 :group 'js2-mode)
1158
1159 (defcustom js2-highlight-external-variables t
1160 "Non-nil to highlight undeclared variable identifiers."
1161 :type 'boolean
1162 :group 'js2-mode)
1163
1164 (defcustom js2-auto-insert-catch-block t
1165 "Non-nil to insert matching catch block on open-curly after `try'."
1166 :type 'boolean
1167 :group 'js2-mode)
1168
1169 (defvar js2-mode-map
1170 (let ((map (make-sparse-keymap))
1171 keys)
1172 (define-key map [mouse-1] #'js2-mode-show-node)
1173 (define-key map (kbd "C-m") #'js2-enter-key)
1174 (when js2-rebind-eol-bol-keys
1175 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1176 (define-key map (kbd "C-e") #'js2-end-of-line))
1177 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1178 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1179 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1180 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1181 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1182 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1183 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1184 (define-key map (kbd "C-c C-`") #'js2-next-error)
1185 ;; also define user's preference for next-error, if available
1186 (if (setq keys (where-is-internal #'next-error))
1187 (define-key map (car keys) #'js2-next-error))
1188 (define-key map (or (car (where-is-internal #'mark-defun))
1189 (kbd "M-C-h"))
1190 #'js2-mark-defun)
1191 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1192 (kbd "C-x nd"))
1193 #'js2-narrow-to-defun)
1194 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1195 (when js2-auto-indent-p
1196 (mapc (lambda (key)
1197 (define-key map key #'js2-insert-and-indent))
1198 js2-electric-keys))
1199 (when js2-bounce-indent-p
1200 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1201
1202 (define-key map [menu-bar javascript]
1203 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1204
1205 (define-key map [menu-bar javascript customize-js2-mode]
1206 '(menu-item "Customize js2-mode" js2-mode-customize
1207 :help "Customize the behavior of this mode"))
1208
1209 (define-key map [menu-bar javascript js2-force-refresh]
1210 '(menu-item "Force buffer refresh" js2-mode-reset
1211 :help "Re-parse the buffer from scratch"))
1212
1213 (define-key map [menu-bar javascript separator-2]
1214 '("--"))
1215
1216 (define-key map [menu-bar javascript next-error]
1217 '(menu-item "Next warning or error" js2-next-error
1218 :enabled (and js2-mode-ast
1219 (or (js2-ast-root-errors js2-mode-ast)
1220 (js2-ast-root-warnings js2-mode-ast)))
1221 :help "Move to next warning or error"))
1222
1223 (define-key map [menu-bar javascript display-errors]
1224 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1225 :visible (not js2-mode-show-parse-errors)
1226 :help "Turn on display of warnings and errors"))
1227
1228 (define-key map [menu-bar javascript hide-errors]
1229 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1230 :visible js2-mode-show-parse-errors
1231 :help "Turn off display of warnings and errors"))
1232
1233 (define-key map [menu-bar javascript separator-1]
1234 '("--"))
1235
1236 (define-key map [menu-bar javascript js2-toggle-function]
1237 '(menu-item "Show/collapse element" js2-mode-toggle-element
1238 :help "Hide or show function body or comment"))
1239
1240 (define-key map [menu-bar javascript show-comments]
1241 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1242 :visible js2-mode-comments-hidden
1243 :help "Expand all hidden block comments"))
1244
1245 (define-key map [menu-bar javascript hide-comments]
1246 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1247 :visible (not js2-mode-comments-hidden)
1248 :help "Show block comments as /*...*/"))
1249
1250 (define-key map [menu-bar javascript show-all-functions]
1251 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1252 :visible js2-mode-functions-hidden
1253 :help "Expand all hidden function bodies"))
1254
1255 (define-key map [menu-bar javascript hide-all-functions]
1256 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1257 :visible (not js2-mode-functions-hidden)
1258 :help "Show {...} for all top-level function bodies"))
1259
1260 map)
1261 "Keymap used in `js2-mode' buffers.")
1262
1263 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1264
1265 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1266 "Matches a //-comment line. Must be first non-whitespace on line.
1267 First match-group is the leading whitespace.")
1268
1269 (defvar js2-mode-hook nil)
1270
1271 (js2-deflocal js2-mode-ast nil "Private variable.")
1272 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1273 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1274 (js2-deflocal js2-mode-parsing nil "Private variable.")
1275 (js2-deflocal js2-mode-node-overlay nil)
1276
1277 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1278 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1279
1280 (js2-deflocal js2-mode-fontifications nil "Private variable")
1281 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1282 (js2-deflocal js2-imenu-recorder nil "Private variable")
1283 (js2-deflocal js2-imenu-function-map nil "Private variable")
1284
1285 (defvar js2-paragraph-start
1286 "\\(@[a-zA-Z]+\\>\\|$\\)")
1287
1288 ;; Note that we also set a 'c-in-sws text property in html comments,
1289 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1290 (defvar js2-syntactic-ws-start
1291 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1292
1293 (defvar js2-syntactic-ws-end
1294 "\\s \\|[\n\r/]\\|\\s!")
1295
1296 (defvar js2-syntactic-eol
1297 (concat "\\s *\\(/\\*[^*\n\r]*"
1298 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1299 "\\*+/\\s *\\)*"
1300 "\\(//\\|/\\*[^*\n\r]*"
1301 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1302 "\\|\\\\$\\|$\\)")
1303 "Copied from `java-mode'. Needed for some cc-engine functions.")
1304
1305 (defvar js2-comment-prefix-regexp
1306 "//+\\|\\**")
1307
1308 (defvar js2-comment-start-skip
1309 "\\(//+\\|/\\*+\\)\\s *")
1310
1311 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1312 "Non-nil to emit status messages during parsing.")
1313
1314 (defvar js2-mode-functions-hidden nil "private variable")
1315 (defvar js2-mode-comments-hidden nil "private variable")
1316
1317 (defvar js2-mode-syntax-table
1318 (let ((table (make-syntax-table)))
1319 (c-populate-syntax-table table)
1320 table)
1321 "Syntax table used in js2-mode buffers.")
1322
1323 (defvar js2-mode-abbrev-table nil
1324 "Abbrev table in use in `js2-mode' buffers.")
1325 (define-abbrev-table 'js2-mode-abbrev-table ())
1326
1327 (defvar js2-mode-pending-parse-callbacks nil
1328 "List of functions waiting to be notified that parse is finished.")
1329
1330 (defvar js2-mode-last-indented-line -1)
1331
1332 ;;; Localizable error and warning messages
1333
1334 ;; Messages are copied from Rhino's Messages.properties.
1335 ;; Many of the Java-specific messages have been elided.
1336 ;; Add any js2-specific ones at the end, so we can keep
1337 ;; this file synced with changes to Rhino's.
1338
1339 (defvar js2-message-table
1340 (make-hash-table :test 'equal :size 250)
1341 "Contains localized messages for js2-mode.")
1342
1343 ;; TODO(stevey): construct this table at compile-time.
1344 (defmacro js2-msg (key &rest strings)
1345 `(puthash ,key (funcall #'concat ,@strings)
1346 js2-message-table))
1347
1348 (defun js2-get-msg (msg-key)
1349 "Look up a localized message.
1350 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1351 the correct number of ARGS must be provided."
1352 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1353 (args (if (listp msg-key) (cdr msg-key)))
1354 (msg (gethash key js2-message-table)))
1355 (if msg
1356 (apply #'format msg args)
1357 key))) ; default to showing the key
1358
1359 (js2-msg "msg.dup.parms"
1360 "Duplicate parameter name '%s'.")
1361
1362 (js2-msg "msg.too.big.jump"
1363 "Program too complex: jump offset too big.")
1364
1365 (js2-msg "msg.too.big.index"
1366 "Program too complex: internal index exceeds 64K limit.")
1367
1368 (js2-msg "msg.while.compiling.fn"
1369 "Encountered code generation error while compiling function '%s': %s")
1370
1371 (js2-msg "msg.while.compiling.script"
1372 "Encountered code generation error while compiling script: %s")
1373
1374 ;; Context
1375 (js2-msg "msg.ctor.not.found"
1376 "Constructor for '%s' not found.")
1377
1378 (js2-msg "msg.not.ctor"
1379 "'%s' is not a constructor.")
1380
1381 ;; FunctionObject
1382 (js2-msg "msg.varargs.ctor"
1383 "Method or constructor '%s' must be static "
1384 "with the signature (Context cx, Object[] args, "
1385 "Function ctorObj, boolean inNewExpr) "
1386 "to define a variable arguments constructor.")
1387
1388 (js2-msg "msg.varargs.fun"
1389 "Method '%s' must be static with the signature "
1390 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1391 "to define a variable arguments function.")
1392
1393 (js2-msg "msg.incompat.call"
1394 "Method '%s' called on incompatible object.")
1395
1396 (js2-msg "msg.bad.parms"
1397 "Unsupported parameter type '%s' in method '%s'.")
1398
1399 (js2-msg "msg.bad.method.return"
1400 "Unsupported return type '%s' in method '%s'.")
1401
1402 (js2-msg "msg.bad.ctor.return"
1403 "Construction of objects of type '%s' is not supported.")
1404
1405 (js2-msg "msg.no.overload"
1406 "Method '%s' occurs multiple times in class '%s'.")
1407
1408 (js2-msg "msg.method.not.found"
1409 "Method '%s' not found in '%s'.")
1410
1411 ;; IRFactory
1412
1413 (js2-msg "msg.bad.for.in.lhs"
1414 "Invalid left-hand side of for..in loop.")
1415
1416 (js2-msg "msg.mult.index"
1417 "Only one variable allowed in for..in loop.")
1418
1419 (js2-msg "msg.bad.for.in.destruct"
1420 "Left hand side of for..in loop must be an array of "
1421 "length 2 to accept key/value pair.")
1422
1423 (js2-msg "msg.cant.convert"
1424 "Can't convert to type '%s'.")
1425
1426 (js2-msg "msg.bad.assign.left"
1427 "Invalid assignment left-hand side.")
1428
1429 (js2-msg "msg.bad.decr"
1430 "Invalid decerement operand.")
1431
1432 (js2-msg "msg.bad.incr"
1433 "Invalid increment operand.")
1434
1435 (js2-msg "msg.bad.yield"
1436 "yield must be in a function.")
1437
1438 (js2-msg "msg.yield.parenthesized"
1439 "yield expression must be parenthesized.")
1440
1441 ;; NativeGlobal
1442 (js2-msg "msg.cant.call.indirect"
1443 "Function '%s' must be called directly, and not by way of a "
1444 "function of another name.")
1445
1446 (js2-msg "msg.eval.nonstring"
1447 "Calling eval() with anything other than a primitive "
1448 "string value will simply return the value. "
1449 "Is this what you intended?")
1450
1451 (js2-msg "msg.eval.nonstring.strict"
1452 "Calling eval() with anything other than a primitive "
1453 "string value is not allowed in strict mode.")
1454
1455 (js2-msg "msg.bad.destruct.op"
1456 "Invalid destructuring assignment operator")
1457
1458 ;; NativeCall
1459 (js2-msg "msg.only.from.new"
1460 "'%s' may only be invoked from a `new' expression.")
1461
1462 (js2-msg "msg.deprec.ctor"
1463 "The '%s' constructor is deprecated.")
1464
1465 ;; NativeFunction
1466 (js2-msg "msg.no.function.ref.found"
1467 "no source found to decompile function reference %s")
1468
1469 (js2-msg "msg.arg.isnt.array"
1470 "second argument to Function.prototype.apply must be an array")
1471
1472 ;; NativeGlobal
1473 (js2-msg "msg.bad.esc.mask"
1474 "invalid string escape mask")
1475
1476 ;; NativeRegExp
1477 (js2-msg "msg.bad.quant"
1478 "Invalid quantifier %s")
1479
1480 (js2-msg "msg.overlarge.backref"
1481 "Overly large back reference %s")
1482
1483 (js2-msg "msg.overlarge.min"
1484 "Overly large minimum %s")
1485
1486 (js2-msg "msg.overlarge.max"
1487 "Overly large maximum %s")
1488
1489 (js2-msg "msg.zero.quant"
1490 "Zero quantifier %s")
1491
1492 (js2-msg "msg.max.lt.min"
1493 "Maximum %s less than minimum")
1494
1495 (js2-msg "msg.unterm.quant"
1496 "Unterminated quantifier %s")
1497
1498 (js2-msg "msg.unterm.paren"
1499 "Unterminated parenthetical %s")
1500
1501 (js2-msg "msg.unterm.class"
1502 "Unterminated character class %s")
1503
1504 (js2-msg "msg.bad.range"
1505 "Invalid range in character class.")
1506
1507 (js2-msg "msg.trail.backslash"
1508 "Trailing \\ in regular expression.")
1509
1510 (js2-msg "msg.re.unmatched.right.paren"
1511 "unmatched ) in regular expression.")
1512
1513 (js2-msg "msg.no.regexp"
1514 "Regular expressions are not available.")
1515
1516 (js2-msg "msg.bad.backref"
1517 "back-reference exceeds number of capturing parentheses.")
1518
1519 (js2-msg "msg.bad.regexp.compile"
1520 "Only one argument may be specified if the first "
1521 "argument to RegExp.prototype.compile is a RegExp object.")
1522
1523 ;; Parser
1524 (js2-msg "msg.got.syntax.errors"
1525 "Compilation produced %s syntax errors.")
1526
1527 (js2-msg "msg.var.redecl"
1528 "TypeError: redeclaration of var %s.")
1529
1530 (js2-msg "msg.const.redecl"
1531 "TypeError: redeclaration of const %s.")
1532
1533 (js2-msg "msg.let.redecl"
1534 "TypeError: redeclaration of variable %s.")
1535
1536 (js2-msg "msg.parm.redecl"
1537 "TypeError: redeclaration of formal parameter %s.")
1538
1539 (js2-msg "msg.fn.redecl"
1540 "TypeError: redeclaration of function %s.")
1541
1542 (js2-msg "msg.let.decl.not.in.block"
1543 "SyntaxError: let declaration not directly within block")
1544
1545 ;; NodeTransformer
1546 (js2-msg "msg.dup.label"
1547 "duplicated label")
1548
1549 (js2-msg "msg.undef.label"
1550 "undefined label")
1551
1552 (js2-msg "msg.bad.break"
1553 "unlabelled break must be inside loop or switch")
1554
1555 (js2-msg "msg.continue.outside"
1556 "continue must be inside loop")
1557
1558 (js2-msg "msg.continue.nonloop"
1559 "continue can only use labels of iteration statements")
1560
1561 (js2-msg "msg.bad.throw.eol"
1562 "Line terminator is not allowed between the throw "
1563 "keyword and throw expression.")
1564
1565 (js2-msg "msg.no.paren.parms"
1566 "missing ( before function parameters.")
1567
1568 (js2-msg "msg.no.parm"
1569 "missing formal parameter")
1570
1571 (js2-msg "msg.no.paren.after.parms"
1572 "missing ) after formal parameters")
1573
1574 (js2-msg "msg.no.brace.body"
1575 "missing '{' before function body")
1576
1577 (js2-msg "msg.no.brace.after.body"
1578 "missing } after function body")
1579
1580 (js2-msg "msg.no.paren.cond"
1581 "missing ( before condition")
1582
1583 (js2-msg "msg.no.paren.after.cond"
1584 "missing ) after condition")
1585
1586 (js2-msg "msg.no.semi.stmt"
1587 "missing ; before statement")
1588
1589 (js2-msg "msg.missing.semi"
1590 "missing ; after statement")
1591
1592 (js2-msg "msg.no.name.after.dot"
1593 "missing name after . operator")
1594
1595 (js2-msg "msg.no.name.after.coloncolon"
1596 "missing name after :: operator")
1597
1598 (js2-msg "msg.no.name.after.dotdot"
1599 "missing name after .. operator")
1600
1601 (js2-msg "msg.no.name.after.xmlAttr"
1602 "missing name after .@")
1603
1604 (js2-msg "msg.no.bracket.index"
1605 "missing ] in index expression")
1606
1607 (js2-msg "msg.no.paren.switch"
1608 "missing ( before switch expression")
1609
1610 (js2-msg "msg.no.paren.after.switch"
1611 "missing ) after switch expression")
1612
1613 (js2-msg "msg.no.brace.switch"
1614 "missing '{' before switch body")
1615
1616 (js2-msg "msg.bad.switch"
1617 "invalid switch statement")
1618
1619 (js2-msg "msg.no.colon.case"
1620 "missing : after case expression")
1621
1622 (js2-msg "msg.double.switch.default"
1623 "double default label in the switch statement")
1624
1625 (js2-msg "msg.no.while.do"
1626 "missing while after do-loop body")
1627
1628 (js2-msg "msg.no.paren.for"
1629 "missing ( after for")
1630
1631 (js2-msg "msg.no.semi.for"
1632 "missing ; after for-loop initializer")
1633
1634 (js2-msg "msg.no.semi.for.cond"
1635 "missing ; after for-loop condition")
1636
1637 (js2-msg "msg.in.after.for.name"
1638 "missing in or of after for")
1639
1640 (js2-msg "msg.no.paren.for.ctrl"
1641 "missing ) after for-loop control")
1642
1643 (js2-msg "msg.no.paren.with"
1644 "missing ( before with-statement object")
1645
1646 (js2-msg "msg.no.paren.after.with"
1647 "missing ) after with-statement object")
1648
1649 (js2-msg "msg.no.paren.after.let"
1650 "missing ( after let")
1651
1652 (js2-msg "msg.no.paren.let"
1653 "missing ) after variable list")
1654
1655 (js2-msg "msg.no.curly.let"
1656 "missing } after let statement")
1657
1658 (js2-msg "msg.bad.return"
1659 "invalid return")
1660
1661 (js2-msg "msg.no.brace.block"
1662 "missing } in compound statement")
1663
1664 (js2-msg "msg.bad.label"
1665 "invalid label")
1666
1667 (js2-msg "msg.bad.var"
1668 "missing variable name")
1669
1670 (js2-msg "msg.bad.var.init"
1671 "invalid variable initialization")
1672
1673 (js2-msg "msg.no.colon.cond"
1674 "missing : in conditional expression")
1675
1676 (js2-msg "msg.no.paren.arg"
1677 "missing ) after argument list")
1678
1679 (js2-msg "msg.no.bracket.arg"
1680 "missing ] after element list")
1681
1682 (js2-msg "msg.bad.prop"
1683 "invalid property id")
1684
1685 (js2-msg "msg.no.colon.prop"
1686 "missing : after property id")
1687
1688 (js2-msg "msg.no.brace.prop"
1689 "missing } after property list")
1690
1691 (js2-msg "msg.no.paren"
1692 "missing ) in parenthetical")
1693
1694 (js2-msg "msg.reserved.id"
1695 "identifier is a reserved word")
1696
1697 (js2-msg "msg.no.paren.catch"
1698 "missing ( before catch-block condition")
1699
1700 (js2-msg "msg.bad.catchcond"
1701 "invalid catch block condition")
1702
1703 (js2-msg "msg.catch.unreachable"
1704 "any catch clauses following an unqualified catch are unreachable")
1705
1706 (js2-msg "msg.no.brace.try"
1707 "missing '{' before try block")
1708
1709 (js2-msg "msg.no.brace.catchblock"
1710 "missing '{' before catch-block body")
1711
1712 (js2-msg "msg.try.no.catchfinally"
1713 "'try' without 'catch' or 'finally'")
1714
1715 (js2-msg "msg.no.return.value"
1716 "function %s does not always return a value")
1717
1718 (js2-msg "msg.anon.no.return.value"
1719 "anonymous function does not always return a value")
1720
1721 (js2-msg "msg.return.inconsistent"
1722 "return statement is inconsistent with previous usage")
1723
1724 (js2-msg "msg.generator.returns"
1725 "TypeError: generator function '%s' returns a value")
1726
1727 (js2-msg "msg.anon.generator.returns"
1728 "TypeError: anonymous generator function returns a value")
1729
1730 (js2-msg "msg.syntax"
1731 "syntax error")
1732
1733 (js2-msg "msg.unexpected.eof"
1734 "Unexpected end of file")
1735
1736 (js2-msg "msg.XML.bad.form"
1737 "illegally formed XML syntax")
1738
1739 (js2-msg "msg.XML.not.available"
1740 "XML runtime not available")
1741
1742 (js2-msg "msg.too.deep.parser.recursion"
1743 "Too deep recursion while parsing")
1744
1745 (js2-msg "msg.no.side.effects"
1746 "Code has no side effects")
1747
1748 (js2-msg "msg.extra.trailing.comma"
1749 "Trailing comma is not legal in an ECMA-262 object initializer")
1750
1751 (js2-msg "msg.array.trailing.comma"
1752 "Trailing comma yields different behavior across browsers")
1753
1754 (js2-msg "msg.equal.as.assign"
1755 (concat "Test for equality (==) mistyped as assignment (=)?"
1756 " (parenthesize to suppress warning)"))
1757
1758 (js2-msg "msg.var.hides.arg"
1759 "Variable %s hides argument")
1760
1761 (js2-msg "msg.destruct.assign.no.init"
1762 "Missing = in destructuring declaration")
1763
1764 ;; ScriptRuntime
1765 (js2-msg "msg.no.properties"
1766 "%s has no properties.")
1767
1768 (js2-msg "msg.invalid.iterator"
1769 "Invalid iterator value")
1770
1771 (js2-msg "msg.iterator.primitive"
1772 "__iterator__ returned a primitive value")
1773
1774 (js2-msg "msg.assn.create.strict"
1775 "Assignment to undeclared variable %s")
1776
1777 (js2-msg "msg.ref.undefined.prop"
1778 "Reference to undefined property '%s'")
1779
1780 (js2-msg "msg.prop.not.found"
1781 "Property %s not found.")
1782
1783 (js2-msg "msg.invalid.type"
1784 "Invalid JavaScript value of type %s")
1785
1786 (js2-msg "msg.primitive.expected"
1787 "Primitive type expected (had %s instead)")
1788
1789 (js2-msg "msg.namespace.expected"
1790 "Namespace object expected to left of :: (found %s instead)")
1791
1792 (js2-msg "msg.null.to.object"
1793 "Cannot convert null to an object.")
1794
1795 (js2-msg "msg.undef.to.object"
1796 "Cannot convert undefined to an object.")
1797
1798 (js2-msg "msg.cyclic.value"
1799 "Cyclic %s value not allowed.")
1800
1801 (js2-msg "msg.is.not.defined"
1802 "'%s' is not defined.")
1803
1804 (js2-msg "msg.undef.prop.read"
1805 "Cannot read property '%s' from %s")
1806
1807 (js2-msg "msg.undef.prop.write"
1808 "Cannot set property '%s' of %s to '%s'")
1809
1810 (js2-msg "msg.undef.prop.delete"
1811 "Cannot delete property '%s' of %s")
1812
1813 (js2-msg "msg.undef.method.call"
1814 "Cannot call method '%s' of %s")
1815
1816 (js2-msg "msg.undef.with"
1817 "Cannot apply 'with' to %s")
1818
1819 (js2-msg "msg.isnt.function"
1820 "%s is not a function, it is %s.")
1821
1822 (js2-msg "msg.isnt.function.in"
1823 "Cannot call property %s in object %s. "
1824 "It is not a function, it is '%s'.")
1825
1826 (js2-msg "msg.function.not.found"
1827 "Cannot find function %s.")
1828
1829 (js2-msg "msg.function.not.found.in"
1830 "Cannot find function %s in object %s.")
1831
1832 (js2-msg "msg.isnt.xml.object"
1833 "%s is not an xml object.")
1834
1835 (js2-msg "msg.no.ref.to.get"
1836 "%s is not a reference to read reference value.")
1837
1838 (js2-msg "msg.no.ref.to.set"
1839 "%s is not a reference to set reference value to %s.")
1840
1841 (js2-msg "msg.no.ref.from.function"
1842 "Function %s can not be used as the left-hand "
1843 "side of assignment or as an operand of ++ or -- operator.")
1844
1845 (js2-msg "msg.bad.default.value"
1846 "Object's getDefaultValue() method returned an object.")
1847
1848 (js2-msg "msg.instanceof.not.object"
1849 "Can't use instanceof on a non-object.")
1850
1851 (js2-msg "msg.instanceof.bad.prototype"
1852 "'prototype' property of %s is not an object.")
1853
1854 (js2-msg "msg.bad.radix"
1855 "illegal radix %s.")
1856
1857 ;; ScriptableObject
1858 (js2-msg "msg.default.value"
1859 "Cannot find default value for object.")
1860
1861 (js2-msg "msg.zero.arg.ctor"
1862 "Cannot load class '%s' which has no zero-parameter constructor.")
1863
1864 (js2-msg "msg.ctor.multiple.parms"
1865 "Can't define constructor or class %s since more than "
1866 "one constructor has multiple parameters.")
1867
1868 (js2-msg "msg.extend.scriptable"
1869 "%s must extend ScriptableObject in order to define property %s.")
1870
1871 (js2-msg "msg.bad.getter.parms"
1872 "In order to define a property, getter %s must have zero "
1873 "parameters or a single ScriptableObject parameter.")
1874
1875 (js2-msg "msg.obj.getter.parms"
1876 "Expected static or delegated getter %s to take "
1877 "a ScriptableObject parameter.")
1878
1879 (js2-msg "msg.getter.static"
1880 "Getter and setter must both be static or neither be static.")
1881
1882 (js2-msg "msg.setter.return"
1883 "Setter must have void return type: %s")
1884
1885 (js2-msg "msg.setter2.parms"
1886 "Two-parameter setter must take a ScriptableObject as "
1887 "its first parameter.")
1888
1889 (js2-msg "msg.setter1.parms"
1890 "Expected single parameter setter for %s")
1891
1892 (js2-msg "msg.setter2.expected"
1893 "Expected static or delegated setter %s to take two parameters.")
1894
1895 (js2-msg "msg.setter.parms"
1896 "Expected either one or two parameters for setter.")
1897
1898 (js2-msg "msg.setter.bad.type"
1899 "Unsupported parameter type '%s' in setter '%s'.")
1900
1901 (js2-msg "msg.add.sealed"
1902 "Cannot add a property to a sealed object: %s.")
1903
1904 (js2-msg "msg.remove.sealed"
1905 "Cannot remove a property from a sealed object: %s.")
1906
1907 (js2-msg "msg.modify.sealed"
1908 "Cannot modify a property of a sealed object: %s.")
1909
1910 (js2-msg "msg.modify.readonly"
1911 "Cannot modify readonly property: %s.")
1912
1913 ;; TokenStream
1914 (js2-msg "msg.missing.exponent"
1915 "missing exponent")
1916
1917 (js2-msg "msg.caught.nfe"
1918 "number format error")
1919
1920 (js2-msg "msg.unterminated.string.lit"
1921 "unterminated string literal")
1922
1923 (js2-msg "msg.unterminated.comment"
1924 "unterminated comment")
1925
1926 (js2-msg "msg.unterminated.re.lit"
1927 "unterminated regular expression literal")
1928
1929 (js2-msg "msg.invalid.re.flag"
1930 "invalid flag after regular expression")
1931
1932 (js2-msg "msg.no.re.input.for"
1933 "no input for %s")
1934
1935 (js2-msg "msg.illegal.character"
1936 "illegal character")
1937
1938 (js2-msg "msg.invalid.escape"
1939 "invalid Unicode escape sequence")
1940
1941 (js2-msg "msg.bad.namespace"
1942 "not a valid default namespace statement. "
1943 "Syntax is: default xml namespace = EXPRESSION;")
1944
1945 ;; TokensStream warnings
1946 (js2-msg "msg.bad.octal.literal"
1947 "illegal octal literal digit %s; "
1948 "interpreting it as a decimal digit")
1949
1950 (js2-msg "msg.reserved.keyword"
1951 "illegal usage of future reserved keyword %s; "
1952 "interpreting it as ordinary identifier")
1953
1954 (js2-msg "msg.script.is.not.constructor"
1955 "Script objects are not constructors.")
1956
1957 ;; Arrays
1958 (js2-msg "msg.arraylength.bad"
1959 "Inappropriate array length.")
1960
1961 ;; Arrays
1962 (js2-msg "msg.arraylength.too.big"
1963 "Array length %s exceeds supported capacity limit.")
1964
1965 ;; URI
1966 (js2-msg "msg.bad.uri"
1967 "Malformed URI sequence.")
1968
1969 ;; Number
1970 (js2-msg "msg.bad.precision"
1971 "Precision %s out of range.")
1972
1973 ;; NativeGenerator
1974 (js2-msg "msg.send.newborn"
1975 "Attempt to send value to newborn generator")
1976
1977 (js2-msg "msg.already.exec.gen"
1978 "Already executing generator")
1979
1980 (js2-msg "msg.StopIteration.invalid"
1981 "StopIteration may not be changed to an arbitrary object.")
1982
1983 ;; Interpreter
1984 (js2-msg "msg.yield.closing"
1985 "Yield from closing generator")
1986
1987 ;;; Utilities
1988
1989 (defun js2-delete-if (predicate list)
1990 "Remove all items satisfying PREDICATE in LIST."
1991 (loop for item in list
1992 if (not (funcall predicate item))
1993 collect item))
1994
1995 (defun js2-position (element list)
1996 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1997 Returns nil if element is not found in the list."
1998 (let ((count 0)
1999 found)
2000 (while (and list (not found))
2001 (if (eq element (car list))
2002 (setq found t)
2003 (setq count (1+ count)
2004 list (cdr list))))
2005 (if found count)))
2006
2007 (defun js2-find-if (predicate list)
2008 "Find first item satisfying PREDICATE in LIST."
2009 (let (result)
2010 (while (and list (not result))
2011 (if (funcall predicate (car list))
2012 (setq result (car list)))
2013 (setq list (cdr list)))
2014 result))
2015
2016 (defmacro js2-time (form)
2017 "Evaluate FORM, discard result, and return elapsed time in sec"
2018 (declare (debug t))
2019 (let ((beg (make-symbol "--js2-time-beg--"))
2020 (delta (make-symbol "--js2-time-end--")))
2021 `(let ((,beg (current-time))
2022 ,delta)
2023 ,form
2024 (/ (truncate (* (- (float-time (current-time))
2025 (float-time ,beg))
2026 10000))
2027 10000.0))))
2028
2029 (defsubst js2-same-line (pos)
2030 "Return t if POS is on the same line as current point."
2031 (and (>= pos (point-at-bol))
2032 (<= pos (point-at-eol))))
2033
2034 (defsubst js2-same-line-2 (p1 p2)
2035 "Return t if p1 is on the same line as p2."
2036 (save-excursion
2037 (goto-char p1)
2038 (js2-same-line p2)))
2039
2040 (defun js2-code-bug ()
2041 "Signal an error when we encounter an unexpected code path."
2042 (error "failed assertion"))
2043
2044 (defsubst js2-record-text-property (beg end prop value)
2045 "Record a text property to set when parsing finishes."
2046 (push (list beg end prop value) js2-mode-deferred-properties))
2047
2048 ;; I'd like to associate errors with nodes, but for now the
2049 ;; easiest thing to do is get the context info from the last token.
2050 (defsubst js2-record-parse-error (msg &optional arg pos len)
2051 (push (list (list msg arg)
2052 (or pos js2-token-beg)
2053 (or len (- js2-token-end js2-token-beg)))
2054 js2-parsed-errors))
2055
2056 (defsubst js2-report-error (msg &optional msg-arg pos len)
2057 "Signal a syntax error or record a parse error."
2058 (if js2-recover-from-parse-errors
2059 (js2-record-parse-error msg msg-arg pos len)
2060 (signal 'js2-syntax-error
2061 (list msg
2062 js2-ts-lineno
2063 (save-excursion
2064 (goto-char js2-ts-cursor)
2065 (current-column))
2066 js2-ts-hit-eof))))
2067
2068 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2069 (if js2-compiler-report-warning-as-error
2070 (js2-report-error msg msg-arg pos len)
2071 (push (list (list msg msg-arg)
2072 (or pos js2-token-beg)
2073 (or len (- js2-token-end js2-token-beg)))
2074 js2-parsed-warnings)))
2075
2076 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2077 (if js2-compiler-strict-mode
2078 (js2-report-warning msg-id msg-arg beg
2079 (and beg end (- end beg)))))
2080
2081 (put 'js2-syntax-error 'error-conditions
2082 '(error syntax-error js2-syntax-error))
2083 (put 'js2-syntax-error 'error-message "Syntax error")
2084
2085 (put 'js2-parse-error 'error-conditions
2086 '(error parse-error js2-parse-error))
2087 (put 'js2-parse-error 'error-message "Parse error")
2088
2089 (defmacro js2-clear-flag (flags flag)
2090 `(setq ,flags (logand ,flags (lognot ,flag))))
2091
2092 (defmacro js2-set-flag (flags flag)
2093 "Logical-or FLAG into FLAGS."
2094 `(setq ,flags (logior ,flags ,flag)))
2095
2096 (defsubst js2-flag-set-p (flags flag)
2097 (/= 0 (logand flags flag)))
2098
2099 (defsubst js2-flag-not-set-p (flags flag)
2100 (zerop (logand flags flag)))
2101
2102 ;; Stolen shamelessly from James Clark's nxml-mode.
2103 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2104 "Evaluate BODY without any text property changes modifying the buffer.
2105 Any text properties changes happen as usual but the changes are not treated as
2106 modifications to the buffer."
2107 (declare (indent 0) (debug t))
2108 (let ((modified (make-symbol "modified")))
2109 `(let ((,modified (buffer-modified-p))
2110 (inhibit-read-only t)
2111 (inhibit-modification-hooks t)
2112 (buffer-undo-list t)
2113 (deactivate-mark nil)
2114 ;; Apparently these avoid file locking problems.
2115 (buffer-file-name nil)
2116 (buffer-file-truename nil))
2117 (unwind-protect
2118 (progn ,@body)
2119 (unless ,modified
2120 (restore-buffer-modified-p nil))))))
2121
2122 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2123 "Evaluate BODY with the _ character set to be word-syntax."
2124 (declare (indent 0) (debug t))
2125 (let ((old-syntax (make-symbol "old-syntax")))
2126 `(let ((,old-syntax (string (char-syntax ?_))))
2127 (unwind-protect
2128 (progn
2129 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2130 ,@body)
2131 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2132
2133 (defsubst js2-char-uppercase-p (c)
2134 "Return t if C is an uppercase character.
2135 Handles unicode and latin chars properly."
2136 (/= c (downcase c)))
2137
2138 (defsubst js2-char-lowercase-p (c)
2139 "Return t if C is an uppercase character.
2140 Handles unicode and latin chars properly."
2141 (/= c (upcase c)))
2142
2143 ;;; AST struct and function definitions
2144
2145 ;; flags for ast node property 'member-type (used for e4x operators)
2146 (defvar js2-property-flag #x1 "property access: element is valid name")
2147 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2148 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2149
2150 (defsubst js2-relpos (pos anchor)
2151 "Convert POS to be relative to ANCHOR.
2152 If POS is nil, returns nil."
2153 (and pos (- pos anchor)))
2154
2155 (defsubst js2-make-pad (indent)
2156 (if (zerop indent)
2157 ""
2158 (make-string (* indent js2-basic-offset) ? )))
2159
2160 (defsubst js2-visit-ast (node callback)
2161 "Visit every node in ast NODE with visitor CALLBACK.
2162
2163 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2164 called twice: once to visit the node, and again after all the node's
2165 children have been processed. The END-P argument is nil on the first
2166 call and non-nil on the second call. The return value of the callback
2167 affects the traversal: if non-nil, the children of NODE are processed.
2168 If the callback returns nil, or if the node has no children, then the
2169 callback is called immediately with a non-nil END-P argument.
2170
2171 The node traversal is approximately lexical-order, although there
2172 are currently no guarantees around this."
2173 (if node
2174 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2175 ;; visit the node
2176 (when (funcall callback node nil)
2177 ;; visit the kids
2178 (cond
2179 ((eq vfunc 'js2-visit-none)
2180 nil) ; don't even bother calling it
2181 ;; Each AST node type has to define a `js2-visitor' function
2182 ;; that takes a node and a callback, and calls `js2-visit-ast'
2183 ;; on each child of the node.
2184 (vfunc
2185 (funcall vfunc node callback))
2186 (t
2187 (error "%s does not define a visitor-traversal function"
2188 (aref node 0)))))
2189 ;; call the end-visit
2190 (funcall callback node t))))
2191
2192 (defstruct (js2-node
2193 (:constructor nil)) ; abstract
2194 "Base AST node type."
2195 (type -1) ; token type
2196 (pos -1) ; start position of this AST node in parsed input
2197 (len 1) ; num characters spanned by the node
2198 props ; optional node property list (an alist)
2199 parent) ; link to parent node; null for root
2200
2201 (defsubst js2-node-get-prop (node prop &optional default)
2202 (or (cadr (assoc prop (js2-node-props node))) default))
2203
2204 (defsubst js2-node-set-prop (node prop value)
2205 (setf (js2-node-props node)
2206 (cons (list prop value) (js2-node-props node))))
2207
2208 (defsubst js2-fixup-starts (n nodes)
2209 "Adjust the start positions of NODES to be relative to N.
2210 Any node in the list may be nil, for convenience."
2211 (dolist (node nodes)
2212 (when node
2213 (setf (js2-node-pos node) (- (js2-node-pos node)
2214 (js2-node-pos n))))))
2215
2216 (defsubst js2-node-add-children (parent &rest nodes)
2217 "Set parent node of NODES to PARENT, and return PARENT.
2218 Does nothing if we're not recording parent links.
2219 If any given node in NODES is nil, doesn't record that link."
2220 (js2-fixup-starts parent nodes)
2221 (dolist (node nodes)
2222 (and node
2223 (setf (js2-node-parent node) parent))))
2224
2225 ;; Non-recursive since it's called a frightening number of times.
2226 (defsubst js2-node-abs-pos (n)
2227 (let ((pos (js2-node-pos n)))
2228 (while (setq n (js2-node-parent n))
2229 (setq pos (+ pos (js2-node-pos n))))
2230 pos))
2231
2232 (defsubst js2-node-abs-end (n)
2233 "Return absolute buffer position of end of N."
2234 (+ (js2-node-abs-pos n) (js2-node-len n)))
2235
2236 ;; It's important to make sure block nodes have a lisp list for the
2237 ;; child nodes, to limit printing recursion depth in an AST that
2238 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2239 ;; a sufficiently large vector tree.
2240
2241 (defstruct (js2-block-node
2242 (:include js2-node)
2243 (:constructor nil)
2244 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2245 (pos js2-token-beg)
2246 len
2247 props
2248 kids)))
2249 "A block of statements."
2250 kids) ; a lisp list of the child statement nodes
2251
2252 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2253 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2254
2255 (defsubst js2-visit-block (ast callback)
2256 "Visit the `js2-block-node' children of AST."
2257 (dolist (kid (js2-block-node-kids ast))
2258 (js2-visit-ast kid callback)))
2259
2260 (defun js2-print-block (n i)
2261 (let ((pad (js2-make-pad i)))
2262 (insert pad "{\n")
2263 (dolist (kid (js2-block-node-kids n))
2264 (js2-print-ast kid (1+ i)))
2265 (insert pad "}")))
2266
2267 (defstruct (js2-scope
2268 (:include js2-block-node)
2269 (:constructor nil)
2270 (:constructor make-js2-scope (&key (type js2-BLOCK)
2271 (pos js2-token-beg)
2272 len
2273 kids)))
2274 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2275 ;; I don't have one of those handy, so I'll use an alist for now.
2276 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2277 ;; and is much lighter-weight to construct (both CPU and mem).
2278 ;; The keys are interned strings (symbols) for faster lookup.
2279 ;; Should switch to hybrid alist/hashtable eventually.
2280 symbol-table ; an alist of (symbol . js2-symbol)
2281 parent-scope ; a `js2-scope'
2282 top) ; top-level `js2-scope' (script/function)
2283
2284 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2285 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2286
2287 (defun js2-scope-set-parent-scope (scope parent)
2288 (setf (js2-scope-parent-scope scope) parent
2289 (js2-scope-top scope) (if (null parent)
2290 scope
2291 (js2-scope-top parent))))
2292
2293 (defun js2-node-get-enclosing-scope (node)
2294 "Return the innermost `js2-scope' node surrounding NODE.
2295 Returns nil if there is no enclosing scope node."
2296 (let ((parent (js2-node-parent node)))
2297 (while (not (js2-scope-p parent))
2298 (setq parent (js2-node-parent parent)))
2299 parent))
2300
2301 (defun js2-get-defining-scope (scope name)
2302 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2303 Returns `js2-scope' in which NAME is defined, or nil if not found."
2304 (let ((sym (if (symbolp name)
2305 name
2306 (intern name)))
2307 table
2308 result
2309 (continue t))
2310 (while (and scope continue)
2311 (if (and (setq table (js2-scope-symbol-table scope))
2312 (assq sym table))
2313 (setq continue nil
2314 result scope)
2315 (setq scope (js2-scope-parent-scope scope))))
2316 result))
2317
2318 (defsubst js2-scope-get-symbol (scope name)
2319 "Return symbol table entry for NAME in SCOPE.
2320 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2321 (and (js2-scope-symbol-table scope)
2322 (cdr (assq (if (symbolp name)
2323 name
2324 (intern name))
2325 (js2-scope-symbol-table scope)))))
2326
2327 (defsubst js2-scope-put-symbol (scope name symbol)
2328 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2329 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2330 (let* ((table (js2-scope-symbol-table scope))
2331 (sym (if (symbolp name) name (intern name)))
2332 (entry (assq sym table)))
2333 (if entry
2334 (setcdr entry symbol)
2335 (push (cons sym symbol)
2336 (js2-scope-symbol-table scope)))))
2337
2338 (defstruct (js2-symbol
2339 (:constructor nil)
2340 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2341 "A symbol table entry."
2342 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2343 ;; js2-LET, or js2-CONST
2344 decl-type
2345 name ; string
2346 ast-node) ; a `js2-node'
2347
2348 (defstruct (js2-error-node
2349 (:include js2-node)
2350 (:constructor nil) ; silence emacs21 byte-compiler
2351 (:constructor make-js2-error-node (&key (type js2-ERROR)
2352 (pos js2-token-beg)
2353 len)))
2354 "AST node representing a parse error.")
2355
2356 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2357 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2358
2359 (defstruct (js2-script-node
2360 (:include js2-scope)
2361 (:constructor nil)
2362 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2363 (pos js2-token-beg)
2364 len
2365 var-decls
2366 fun-decls)))
2367 functions ; lisp list of nested functions
2368 regexps ; lisp list of (string . flags)
2369 symbols ; alist (every symbol gets unique index)
2370 (param-count 0)
2371 var-names ; vector of string names
2372 consts ; bool-vector matching var-decls
2373 (temp-number 0)) ; for generating temp variables
2374
2375 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2376 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2377
2378 (defun js2-print-script (node indent)
2379 (dolist (kid (js2-block-node-kids node))
2380 (js2-print-ast kid indent)))
2381
2382 (defstruct (js2-ast-root
2383 (:include js2-script-node)
2384 (:constructor nil)
2385 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2386 (pos js2-token-beg)
2387 len
2388 buffer)))
2389 "The root node of a js2 AST."
2390 buffer ; the source buffer from which the code was parsed
2391 comments ; a lisp list of comments, ordered by start position
2392 errors ; a lisp list of errors found during parsing
2393 warnings ; a lisp list of warnings found during parsing
2394 node-count) ; number of nodes in the tree, including the root
2395
2396 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2397 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2398
2399 (defun js2-visit-ast-root (ast callback)
2400 (dolist (kid (js2-ast-root-kids ast))
2401 (js2-visit-ast kid callback))
2402 (dolist (comment (js2-ast-root-comments ast))
2403 (js2-visit-ast comment callback)))
2404
2405 (defstruct (js2-comment-node
2406 (:include js2-node)
2407 (:constructor nil)
2408 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2409 (pos js2-token-beg)
2410 len
2411 (format js2-ts-comment-type))))
2412 format) ; 'line, 'block, 'jsdoc or 'html
2413
2414 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2415 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2416
2417 (defun js2-print-comment (n i)
2418 ;; We really ought to link end-of-line comments to their nodes.
2419 ;; Or maybe we could add a new comment type, 'endline.
2420 (insert (js2-make-pad i)
2421 (js2-node-string n)))
2422
2423 (defstruct (js2-expr-stmt-node
2424 (:include js2-node)
2425 (:constructor nil)
2426 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2427 (pos js2-ts-cursor)
2428 len
2429 expr)))
2430 "An expression statement."
2431 expr)
2432
2433 (defsubst js2-expr-stmt-node-set-has-result (node)
2434 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2435 (setf (js2-node-type node) js2-EXPR_RESULT))
2436
2437 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2438 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2439
2440 (defun js2-visit-expr-stmt-node (n v)
2441 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2442
2443 (defun js2-print-expr-stmt-node (n indent)
2444 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2445 (insert ";\n"))
2446
2447 (defstruct (js2-loop-node
2448 (:include js2-scope)
2449 (:constructor nil))
2450 "Abstract supertype of loop nodes."
2451 body ; a `js2-block-node'
2452 lp ; position of left-paren, nil if omitted
2453 rp) ; position of right-paren, nil if omitted
2454
2455 (defstruct (js2-do-node
2456 (:include js2-loop-node)
2457 (:constructor nil)
2458 (:constructor make-js2-do-node (&key (type js2-DO)
2459 (pos js2-token-beg)
2460 len
2461 body
2462 condition
2463 while-pos
2464 lp
2465 rp)))
2466 "AST node for do-loop."
2467 condition ; while (expression)
2468 while-pos) ; buffer position of 'while' keyword
2469
2470 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2471 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2472
2473 (defun js2-visit-do-node (n v)
2474 (js2-visit-ast (js2-do-node-body n) v)
2475 (js2-visit-ast (js2-do-node-condition n) v))
2476
2477 (defun js2-print-do-node (n i)
2478 (let ((pad (js2-make-pad i)))
2479 (insert pad "do {\n")
2480 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2481 (js2-print-ast kid (1+ i)))
2482 (insert pad "} while (")
2483 (js2-print-ast (js2-do-node-condition n) 0)
2484 (insert ");\n")))
2485
2486 (defstruct (js2-while-node
2487 (:include js2-loop-node)
2488 (:constructor nil)
2489 (:constructor make-js2-while-node (&key (type js2-WHILE)
2490 (pos js2-token-beg)
2491 len
2492 body
2493 condition
2494 lp
2495 rp)))
2496 "AST node for while-loop."
2497 condition) ; while-condition
2498
2499 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2500 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2501
2502 (defun js2-visit-while-node (n v)
2503 (js2-visit-ast (js2-while-node-condition n) v)
2504 (js2-visit-ast (js2-while-node-body n) v))
2505
2506 (defun js2-print-while-node (n i)
2507 (let ((pad (js2-make-pad i)))
2508 (insert pad "while (")
2509 (js2-print-ast (js2-while-node-condition n) 0)
2510 (insert ") {\n")
2511 (js2-print-body (js2-while-node-body n) (1+ i))
2512 (insert pad "}\n")))
2513
2514 (defstruct (js2-for-node
2515 (:include js2-loop-node)
2516 (:constructor nil)
2517 (:constructor make-js2-for-node (&key (type js2-FOR)
2518 (pos js2-ts-cursor)
2519 len
2520 body
2521 init
2522 condition
2523 update
2524 lp
2525 rp)))
2526 "AST node for a C-style for-loop."
2527 init ; initialization expression
2528 condition ; loop condition
2529 update) ; update clause
2530
2531 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2532 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2533
2534 (defun js2-visit-for-node (n v)
2535 (js2-visit-ast (js2-for-node-init n) v)
2536 (js2-visit-ast (js2-for-node-condition n) v)
2537 (js2-visit-ast (js2-for-node-update n) v)
2538 (js2-visit-ast (js2-for-node-body n) v))
2539
2540 (defun js2-print-for-node (n i)
2541 (let ((pad (js2-make-pad i)))
2542 (insert pad "for (")
2543 (js2-print-ast (js2-for-node-init n) 0)
2544 (insert "; ")
2545 (js2-print-ast (js2-for-node-condition n) 0)
2546 (insert "; ")
2547 (js2-print-ast (js2-for-node-update n) 0)
2548 (insert ") {\n")
2549 (js2-print-body (js2-for-node-body n) (1+ i))
2550 (insert pad "}\n")))
2551
2552 (defstruct (js2-for-in-node
2553 (:include js2-loop-node)
2554 (:constructor nil)
2555 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2556 (pos js2-ts-cursor)
2557 len
2558 body
2559 iterator
2560 object
2561 in-pos
2562 each-pos
2563 foreach-p
2564 forof-p
2565 lp
2566 rp)))
2567 "AST node for a for..in loop."
2568 iterator ; [var] foo in ...
2569 object ; object over which we're iterating
2570 in-pos ; buffer position of 'in' keyword
2571 each-pos ; buffer position of 'each' keyword, if foreach-p
2572 foreach-p ; t if it's a for-each loop
2573 forof-p) ; t if it's a for-of loop
2574
2575 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2576 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2577
2578 (defun js2-visit-for-in-node (n v)
2579 (js2-visit-ast (js2-for-in-node-iterator n) v)
2580 (js2-visit-ast (js2-for-in-node-object n) v)
2581 (js2-visit-ast (js2-for-in-node-body n) v))
2582
2583 (defun js2-print-for-in-node (n i)
2584 (let ((pad (js2-make-pad i))
2585 (foreach (js2-for-in-node-foreach-p n))
2586 (forof (js2-for-in-node-forof-p n)))
2587 (insert pad "for ")
2588 (if foreach
2589 (insert "each "))
2590 (insert "(")
2591 (js2-print-ast (js2-for-in-node-iterator n) 0)
2592 (if forof
2593 (insert " of ")
2594 (insert " in "))
2595 (js2-print-ast (js2-for-in-node-object n) 0)
2596 (insert ") {\n")
2597 (js2-print-body (js2-for-in-node-body n) (1+ i))
2598 (insert pad "}\n")))
2599
2600 (defstruct (js2-return-node
2601 (:include js2-node)
2602 (:constructor nil)
2603 (:constructor make-js2-return-node (&key (type js2-RETURN)
2604 (pos js2-ts-cursor)
2605 len
2606 retval)))
2607 "AST node for a return statement."
2608 retval) ; expression to return, or 'undefined
2609
2610 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2611 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2612
2613 (defun js2-visit-return-node (n v)
2614 (js2-visit-ast (js2-return-node-retval n) v))
2615
2616 (defun js2-print-return-node (n i)
2617 (insert (js2-make-pad i) "return")
2618 (when (js2-return-node-retval n)
2619 (insert " ")
2620 (js2-print-ast (js2-return-node-retval n) 0))
2621 (insert ";\n"))
2622
2623 (defstruct (js2-if-node
2624 (:include js2-node)
2625 (:constructor nil)
2626 (:constructor make-js2-if-node (&key (type js2-IF)
2627 (pos js2-ts-cursor)
2628 len
2629 condition
2630 then-part
2631 else-pos
2632 else-part
2633 lp
2634 rp)))
2635 "AST node for an if-statement."
2636 condition ; expression
2637 then-part ; statement or block
2638 else-pos ; optional buffer position of 'else' keyword
2639 else-part ; optional statement or block
2640 lp ; position of left-paren, nil if omitted
2641 rp) ; position of right-paren, nil if omitted
2642
2643 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2644 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2645
2646 (defun js2-visit-if-node (n v)
2647 (js2-visit-ast (js2-if-node-condition n) v)
2648 (js2-visit-ast (js2-if-node-then-part n) v)
2649 (js2-visit-ast (js2-if-node-else-part n) v))
2650
2651 (defun js2-print-if-node (n i)
2652 (let ((pad (js2-make-pad i))
2653 (then-part (js2-if-node-then-part n))
2654 (else-part (js2-if-node-else-part n)))
2655 (insert pad "if (")
2656 (js2-print-ast (js2-if-node-condition n) 0)
2657 (insert ") {\n")
2658 (js2-print-body then-part (1+ i))
2659 (insert pad "}")
2660 (cond
2661 ((not else-part)
2662 (insert "\n"))
2663 ((js2-if-node-p else-part)
2664 (insert " else ")
2665 (js2-print-body else-part i))
2666 (t
2667 (insert " else {\n")
2668 (js2-print-body else-part (1+ i))
2669 (insert pad "}\n")))))
2670
2671 (defstruct (js2-try-node
2672 (:include js2-node)
2673 (:constructor nil)
2674 (:constructor make-js2-try-node (&key (type js2-TRY)
2675 (pos js2-ts-cursor)
2676 len
2677 try-block
2678 catch-clauses
2679 finally-block)))
2680 "AST node for a try-statement."
2681 try-block
2682 catch-clauses ; a lisp list of `js2-catch-node'
2683 finally-block) ; a `js2-finally-node'
2684
2685 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2686 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2687
2688 (defun js2-visit-try-node (n v)
2689 (js2-visit-ast (js2-try-node-try-block n) v)
2690 (dolist (clause (js2-try-node-catch-clauses n))
2691 (js2-visit-ast clause v))
2692 (js2-visit-ast (js2-try-node-finally-block n) v))
2693
2694 (defun js2-print-try-node (n i)
2695 (let ((pad (js2-make-pad i))
2696 (catches (js2-try-node-catch-clauses n))
2697 (finally (js2-try-node-finally-block n)))
2698 (insert pad "try {\n")
2699 (js2-print-body (js2-try-node-try-block n) (1+ i))
2700 (insert pad "}")
2701 (when catches
2702 (dolist (catch catches)
2703 (js2-print-ast catch i)))
2704 (if finally
2705 (js2-print-ast finally i)
2706 (insert "\n"))))
2707
2708 (defstruct (js2-catch-node
2709 (:include js2-node)
2710 (:constructor nil)
2711 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2712 (pos js2-ts-cursor)
2713 len
2714 param
2715 guard-kwd
2716 guard-expr
2717 block
2718 lp
2719 rp)))
2720 "AST node for a catch clause."
2721 param ; destructuring form or simple name node
2722 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2723 guard-expr ; catch condition, a `js2-node'
2724 block ; statements, a `js2-block-node'
2725 lp ; buffer position of left-paren, nil if omitted
2726 rp) ; buffer position of right-paren, nil if omitted
2727
2728 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2729 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2730
2731 (defun js2-visit-catch-node (n v)
2732 (js2-visit-ast (js2-catch-node-param n) v)
2733 (when (js2-catch-node-guard-kwd n)
2734 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2735 (js2-visit-ast (js2-catch-node-block n) v))
2736
2737 (defun js2-print-catch-node (n i)
2738 (let ((pad (js2-make-pad i))
2739 (guard-kwd (js2-catch-node-guard-kwd n))
2740 (guard-expr (js2-catch-node-guard-expr n)))
2741 (insert " catch (")
2742 (js2-print-ast (js2-catch-node-param n) 0)
2743 (when guard-kwd
2744 (insert " if ")
2745 (js2-print-ast guard-expr 0))
2746 (insert ") {\n")
2747 (js2-print-body (js2-catch-node-block n) (1+ i))
2748 (insert pad "}")))
2749
2750 (defstruct (js2-finally-node
2751 (:include js2-node)
2752 (:constructor nil)
2753 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2754 (pos js2-ts-cursor)
2755 len
2756 body)))
2757 "AST node for a finally clause."
2758 body) ; a `js2-node', often but not always a block node
2759
2760 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2761 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2762
2763 (defun js2-visit-finally-node (n v)
2764 (js2-visit-ast (js2-finally-node-body n) v))
2765
2766 (defun js2-print-finally-node (n i)
2767 (let ((pad (js2-make-pad i)))
2768 (insert " finally {\n")
2769 (js2-print-body (js2-finally-node-body n) (1+ i))
2770 (insert pad "}\n")))
2771
2772 (defstruct (js2-switch-node
2773 (:include js2-node)
2774 (:constructor nil)
2775 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2776 (pos js2-ts-cursor)
2777 len
2778 discriminant
2779 cases
2780 lp
2781 rp)))
2782 "AST node for a switch statement."
2783 discriminant ; a `js2-node' (switch expression)
2784 cases ; a lisp list of `js2-case-node'
2785 lp ; position of open-paren for discriminant, nil if omitted
2786 rp) ; position of close-paren for discriminant, nil if omitted
2787
2788 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2789 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2790
2791 (defun js2-visit-switch-node (n v)
2792 (js2-visit-ast (js2-switch-node-discriminant n) v)
2793 (dolist (c (js2-switch-node-cases n))
2794 (js2-visit-ast c v)))
2795
2796 (defun js2-print-switch-node (n i)
2797 (let ((pad (js2-make-pad i))
2798 (cases (js2-switch-node-cases n)))
2799 (insert pad "switch (")
2800 (js2-print-ast (js2-switch-node-discriminant n) 0)
2801 (insert ") {\n")
2802 (dolist (case cases)
2803 (js2-print-ast case i))
2804 (insert pad "}\n")))
2805
2806 (defstruct (js2-case-node
2807 (:include js2-block-node)
2808 (:constructor nil)
2809 (:constructor make-js2-case-node (&key (type js2-CASE)
2810 (pos js2-ts-cursor)
2811 len
2812 kids
2813 expr)))
2814 "AST node for a case clause of a switch statement."
2815 expr) ; the case expression (nil for default)
2816
2817 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2818 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2819
2820 (defun js2-visit-case-node (n v)
2821 (js2-visit-ast (js2-case-node-expr n) v)
2822 (js2-visit-block n v))
2823
2824 (defun js2-print-case-node (n i)
2825 (let ((pad (js2-make-pad i))
2826 (expr (js2-case-node-expr n)))
2827 (insert pad)
2828 (if (null expr)
2829 (insert "default:\n")
2830 (insert "case ")
2831 (js2-print-ast expr 0)
2832 (insert ":\n"))
2833 (dolist (kid (js2-case-node-kids n))
2834 (js2-print-ast kid (1+ i)))))
2835
2836 (defstruct (js2-throw-node
2837 (:include js2-node)
2838 (:constructor nil)
2839 (:constructor make-js2-throw-node (&key (type js2-THROW)
2840 (pos js2-ts-cursor)
2841 len
2842 expr)))
2843 "AST node for a throw statement."
2844 expr) ; the expression to throw
2845
2846 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2847 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2848
2849 (defun js2-visit-throw-node (n v)
2850 (js2-visit-ast (js2-throw-node-expr n) v))
2851
2852 (defun js2-print-throw-node (n i)
2853 (insert (js2-make-pad i) "throw ")
2854 (js2-print-ast (js2-throw-node-expr n) 0)
2855 (insert ";\n"))
2856
2857 (defstruct (js2-with-node
2858 (:include js2-node)
2859 (:constructor nil)
2860 (:constructor make-js2-with-node (&key (type js2-WITH)
2861 (pos js2-ts-cursor)
2862 len
2863 object
2864 body
2865 lp
2866 rp)))
2867 "AST node for a with-statement."
2868 object
2869 body
2870 lp ; buffer position of left-paren around object, nil if omitted
2871 rp) ; buffer position of right-paren around object, nil if omitted
2872
2873 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2874 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2875
2876 (defun js2-visit-with-node (n v)
2877 (js2-visit-ast (js2-with-node-object n) v)
2878 (js2-visit-ast (js2-with-node-body n) v))
2879
2880 (defun js2-print-with-node (n i)
2881 (let ((pad (js2-make-pad i)))
2882 (insert pad "with (")
2883 (js2-print-ast (js2-with-node-object n) 0)
2884 (insert ") {\n")
2885 (js2-print-body (js2-with-node-body n) (1+ i))
2886 (insert pad "}\n")))
2887
2888 (defstruct (js2-label-node
2889 (:include js2-node)
2890 (:constructor nil)
2891 (:constructor make-js2-label-node (&key (type js2-LABEL)
2892 (pos js2-ts-cursor)
2893 len
2894 name)))
2895 "AST node for a statement label or case label."
2896 name ; a string
2897 loop) ; for validating and code-generating continue-to-label
2898
2899 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2900 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2901
2902 (defun js2-print-label (n i)
2903 (insert (js2-make-pad i)
2904 (js2-label-node-name n)
2905 ":\n"))
2906
2907 (defstruct (js2-labeled-stmt-node
2908 (:include js2-node)
2909 (:constructor nil)
2910 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2911 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2912 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2913 (pos js2-ts-cursor)
2914 len
2915 labels
2916 stmt)))
2917 "AST node for a statement with one or more labels.
2918 Multiple labels for a statement are collapsed into the labels field."
2919 labels ; lisp list of `js2-label-node'
2920 stmt) ; the statement these labels are for
2921
2922 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2923 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2924
2925 (defun js2-get-label-by-name (lbl-stmt name)
2926 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2927 Returns nil if no such label is in the list."
2928 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2929 result)
2930 (while (and label-list (not result))
2931 (if (string= (js2-label-node-name (car label-list)) name)
2932 (setq result (car label-list))
2933 (setq label-list (cdr label-list))))
2934 result))
2935
2936 (defun js2-visit-labeled-stmt (n v)
2937 (dolist (label (js2-labeled-stmt-node-labels n))
2938 (js2-visit-ast label v))
2939 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2940
2941 (defun js2-print-labeled-stmt (n i)
2942 (dolist (label (js2-labeled-stmt-node-labels n))
2943 (js2-print-ast label i))
2944 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2945
2946 (defun js2-labeled-stmt-node-contains (node label)
2947 "Return t if NODE contains LABEL in its label set.
2948 NODE is a `js2-labels-node'. LABEL is an identifier."
2949 (loop for nl in (js2-labeled-stmt-node-labels node)
2950 if (string= label (js2-label-node-name nl))
2951 return t
2952 finally return nil))
2953
2954 (defsubst js2-labeled-stmt-node-add-label (node label)
2955 "Add a `js2-label-node' to the label set for this statement."
2956 (setf (js2-labeled-stmt-node-labels node)
2957 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2958
2959 (defstruct (js2-jump-node
2960 (:include js2-node)
2961 (:constructor nil))
2962 "Abstract supertype of break and continue nodes."
2963 label ; `js2-name-node' for location of label identifier, if present
2964 target) ; target js2-labels-node or loop/switch statement
2965
2966 (defun js2-visit-jump-node (n v)
2967 (js2-visit-ast (js2-jump-node-label n) v))
2968
2969 (defstruct (js2-break-node
2970 (:include js2-jump-node)
2971 (:constructor nil)
2972 (:constructor make-js2-break-node (&key (type js2-BREAK)
2973 (pos js2-ts-cursor)
2974 len
2975 label
2976 target)))
2977 "AST node for a break statement.
2978 The label field is a `js2-name-node', possibly nil, for the named label
2979 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2980 is the target of the break - a label node or enclosing loop/switch statement.")
2981
2982 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2983 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2984
2985 (defun js2-print-break-node (n i)
2986 (insert (js2-make-pad i) "break")
2987 (when (js2-break-node-label n)
2988 (insert " ")
2989 (js2-print-ast (js2-break-node-label n) 0))
2990 (insert ";\n"))
2991
2992 (defstruct (js2-continue-node
2993 (:include js2-jump-node)
2994 (:constructor nil)
2995 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2996 (pos js2-ts-cursor)
2997 len
2998 label
2999 target)))
3000 "AST node for a continue statement.
3001 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3002 It is nil if continue specifies no label. The target field is the jump target:
3003 a `js2-label-node' or the innermost enclosing loop.")
3004
3005 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3006 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3007
3008 (defun js2-print-continue-node (n i)
3009 (insert (js2-make-pad i) "continue")
3010 (when (js2-continue-node-label n)
3011 (insert " ")
3012 (js2-print-ast (js2-continue-node-label n) 0))
3013 (insert ";\n"))
3014
3015 (defstruct (js2-function-node
3016 (:include js2-script-node)
3017 (:constructor nil)
3018 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3019 (pos js2-ts-cursor)
3020 len
3021 (ftype 'FUNCTION)
3022 (form 'FUNCTION_STATEMENT)
3023 (name "")
3024 params
3025 body
3026 lp
3027 rp)))
3028 "AST node for a function declaration.
3029 The `params' field is a lisp list of nodes. Each node is either a simple
3030 `js2-name-node', or if it's a destructuring-assignment parameter, a
3031 `js2-array-node' or `js2-object-node'."
3032 ftype ; FUNCTION, GETTER or SETTER
3033 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3034 name ; function name (a `js2-name-node', or nil if anonymous)
3035 params ; a lisp list of destructuring forms or simple name nodes
3036 body ; a `js2-block-node' or expression node (1.8 only)
3037 lp ; position of arg-list open-paren, or nil if omitted
3038 rp ; position of arg-list close-paren, or nil if omitted
3039 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3040 needs-activation ; t if we need an activation object for this frame
3041 is-generator ; t if this function contains a yield
3042 member-expr) ; nonstandard Ecma extension from Rhino
3043
3044 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3045 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3046
3047 (defun js2-visit-function-node (n v)
3048 (js2-visit-ast (js2-function-node-name n) v)
3049 (dolist (p (js2-function-node-params n))
3050 (js2-visit-ast p v))
3051 (js2-visit-ast (js2-function-node-body n) v))
3052
3053 (defun js2-print-function-node (n i)
3054 (let ((pad (js2-make-pad i))
3055 (getter (js2-node-get-prop n 'GETTER_SETTER))
3056 (name (js2-function-node-name n))
3057 (params (js2-function-node-params n))
3058 (body (js2-function-node-body n))
3059 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3060 (unless getter
3061 (insert pad "function"))
3062 (when name
3063 (insert " ")
3064 (js2-print-ast name 0))
3065 (insert "(")
3066 (loop with len = (length params)
3067 for param in params
3068 for count from 1
3069 do
3070 (js2-print-ast param 0)
3071 (if (< count len)
3072 (insert ", ")))
3073 (insert ") {")
3074 (unless expr
3075 (insert "\n"))
3076 ;; TODO: fix this to be smarter about indenting, etc.
3077 (js2-print-body body (1+ i))
3078 (insert pad "}")
3079 (unless expr
3080 (insert "\n"))))
3081
3082 (defsubst js2-function-name (node)
3083 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3084 (and (js2-function-node-name node)
3085 (js2-name-node-name (js2-function-node-name node))))
3086
3087 ;; Having this be an expression node makes it more flexible.
3088 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3089 ;; that work better if you assume it's an expression. Whenever we have
3090 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3091 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3092 (defstruct (js2-var-decl-node
3093 (:include js2-node)
3094 (:constructor nil)
3095 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3096 (pos js2-token-beg)
3097 len
3098 kids
3099 decl-type)))
3100 "AST node for a variable declaration list (VAR, CONST or LET).
3101 The node bounds differ depending on the declaration type. For VAR or
3102 CONST declarations, the bounds include the var/const keyword. For LET
3103 declarations, the node begins at the position of the first child."
3104 kids ; a lisp list of `js2-var-init-node' structs.
3105 decl-type) ; js2-VAR, js2-CONST or js2-LET
3106
3107 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3108 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3109
3110 (defun js2-visit-var-decl (n v)
3111 (dolist (kid (js2-var-decl-node-kids n))
3112 (js2-visit-ast kid v)))
3113
3114 (defun js2-print-var-decl (n i)
3115 (let ((pad (js2-make-pad i))
3116 (tt (js2-var-decl-node-decl-type n)))
3117 (insert pad)
3118 (insert (cond
3119 ((= tt js2-VAR) "var ")
3120 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3121 ((= tt js2-CONST) "const ")
3122 (t
3123 (error "malformed var-decl node"))))
3124 (loop with kids = (js2-var-decl-node-kids n)
3125 with len = (length kids)
3126 for kid in kids
3127 for count from 1
3128 do
3129 (js2-print-ast kid 0)
3130 (if (< count len)
3131 (insert ", ")))))
3132
3133 (defstruct (js2-var-init-node
3134 (:include js2-node)
3135 (:constructor nil)
3136 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3137 (pos js2-ts-cursor)
3138 len
3139 target
3140 initializer)))
3141 "AST node for a variable declaration.
3142 The type field will be js2-CONST for a const decl."
3143 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3144 initializer) ; initializer expression, a `js2-node'
3145
3146 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3147 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3148
3149 (defun js2-visit-var-init-node (n v)
3150 (js2-visit-ast (js2-var-init-node-target n) v)
3151 (js2-visit-ast (js2-var-init-node-initializer n) v))
3152
3153 (defun js2-print-var-init-node (n i)
3154 (let ((pad (js2-make-pad i))
3155 (name (js2-var-init-node-target n))
3156 (init (js2-var-init-node-initializer n)))
3157 (insert pad)
3158 (js2-print-ast name 0)
3159 (when init
3160 (insert " = ")
3161 (js2-print-ast init 0))))
3162
3163 (defstruct (js2-cond-node
3164 (:include js2-node)
3165 (:constructor nil)
3166 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3167 (pos js2-ts-cursor)
3168 len
3169 test-expr
3170 true-expr
3171 false-expr
3172 q-pos
3173 c-pos)))
3174 "AST node for the ternary operator"
3175 test-expr
3176 true-expr
3177 false-expr
3178 q-pos ; buffer position of ?
3179 c-pos) ; buffer position of :
3180
3181 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3182 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3183
3184 (defun js2-visit-cond-node (n v)
3185 (js2-visit-ast (js2-cond-node-test-expr n) v)
3186 (js2-visit-ast (js2-cond-node-true-expr n) v)
3187 (js2-visit-ast (js2-cond-node-false-expr n) v))
3188
3189 (defun js2-print-cond-node (n i)
3190 (let ((pad (js2-make-pad i)))
3191 (insert pad)
3192 (js2-print-ast (js2-cond-node-test-expr n) 0)
3193 (insert " ? ")
3194 (js2-print-ast (js2-cond-node-true-expr n) 0)
3195 (insert " : ")
3196 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3197
3198 (defstruct (js2-infix-node
3199 (:include js2-node)
3200 (:constructor nil)
3201 (:constructor make-js2-infix-node (&key type
3202 (pos js2-ts-cursor)
3203 len
3204 op-pos
3205 left
3206 right)))
3207 "Represents infix expressions.
3208 Includes assignment ops like `|=', and the comma operator.
3209 The type field inherited from `js2-node' holds the operator."
3210 op-pos ; buffer position where operator begins
3211 left ; any `js2-node'
3212 right) ; any `js2-node'
3213
3214 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3215 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3216
3217 (defun js2-visit-infix-node (n v)
3218 (js2-visit-ast (js2-infix-node-left n) v)
3219 (js2-visit-ast (js2-infix-node-right n) v))
3220
3221 (defconst js2-operator-tokens
3222 (let ((table (make-hash-table :test 'eq))
3223 (tokens
3224 (list (cons js2-IN "in")
3225 (cons js2-TYPEOF "typeof")
3226 (cons js2-INSTANCEOF "instanceof")
3227 (cons js2-DELPROP "delete")
3228 (cons js2-COMMA ",")
3229 (cons js2-COLON ":")
3230 (cons js2-OR "||")
3231 (cons js2-AND "&&")
3232 (cons js2-INC "++")
3233 (cons js2-DEC "--")
3234 (cons js2-BITOR "|")
3235 (cons js2-BITXOR "^")
3236 (cons js2-BITAND "&")
3237 (cons js2-EQ "==")
3238 (cons js2-NE "!=")
3239 (cons js2-LT "<")
3240 (cons js2-LE "<=")
3241 (cons js2-GT ">")
3242 (cons js2-GE ">=")
3243 (cons js2-LSH "<<")
3244 (cons js2-RSH ">>")
3245 (cons js2-URSH ">>>")
3246 (cons js2-ADD "+") ; infix plus
3247 (cons js2-SUB "-") ; infix minus
3248 (cons js2-MUL "*")
3249 (cons js2-DIV "/")
3250 (cons js2-MOD "%")
3251 (cons js2-NOT "!")
3252 (cons js2-BITNOT "~")
3253 (cons js2-POS "+") ; unary plus
3254 (cons js2-NEG "-") ; unary minus
3255 (cons js2-SHEQ "===") ; shallow equality
3256 (cons js2-SHNE "!==") ; shallow inequality
3257 (cons js2-ASSIGN "=")
3258 (cons js2-ASSIGN_BITOR "|=")
3259 (cons js2-ASSIGN_BITXOR "^=")
3260 (cons js2-ASSIGN_BITAND "&=")
3261 (cons js2-ASSIGN_LSH "<<=")
3262 (cons js2-ASSIGN_RSH ">>=")
3263 (cons js2-ASSIGN_URSH ">>>=")
3264 (cons js2-ASSIGN_ADD "+=")
3265 (cons js2-ASSIGN_SUB "-=")
3266 (cons js2-ASSIGN_MUL "*=")
3267 (cons js2-ASSIGN_DIV "/=")
3268 (cons js2-ASSIGN_MOD "%="))))
3269 (loop for (k . v) in tokens do
3270 (puthash k v table))
3271 table))
3272
3273 (defun js2-print-infix-node (n i)
3274 (let* ((tt (js2-node-type n))
3275 (op (gethash tt js2-operator-tokens)))
3276 (unless op
3277 (error "unrecognized infix operator %s" (js2-node-type n)))
3278 (insert (js2-make-pad i))
3279 (js2-print-ast (js2-infix-node-left n) 0)
3280 (unless (= tt js2-COMMA)
3281 (insert " "))
3282 (insert op)
3283 (insert " ")
3284 (js2-print-ast (js2-infix-node-right n) 0)))
3285
3286 (defstruct (js2-assign-node
3287 (:include js2-infix-node)
3288 (:constructor nil)
3289 (:constructor make-js2-assign-node (&key type
3290 (pos js2-ts-cursor)
3291 len
3292 op-pos
3293 left
3294 right)))
3295 "Represents any assignment.
3296 The type field holds the actual assignment operator.")
3297
3298 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3299 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3300
3301 (defstruct (js2-unary-node
3302 (:include js2-node)
3303 (:constructor nil)
3304 (:constructor make-js2-unary-node (&key type ; required
3305 (pos js2-ts-cursor)
3306 len
3307 operand)))
3308 "AST node type for unary operator nodes.
3309 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3310 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3311 property is added if the operator follows the operand."
3312 operand) ; a `js2-node' expression
3313
3314 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3315 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3316
3317 (defun js2-visit-unary-node (n v)
3318 (js2-visit-ast (js2-unary-node-operand n) v))
3319
3320 (defun js2-print-unary-node (n i)
3321 (let* ((tt (js2-node-type n))
3322 (op (gethash tt js2-operator-tokens))
3323 (postfix (js2-node-get-prop n 'postfix)))
3324 (unless op
3325 (error "unrecognized unary operator %s" tt))
3326 (insert (js2-make-pad i))
3327 (unless postfix
3328 (insert op))
3329 (if (or (= tt js2-TYPEOF)
3330 (= tt js2-DELPROP))
3331 (insert " "))
3332 (js2-print-ast (js2-unary-node-operand n) 0)
3333 (when postfix
3334 (insert op))))
3335
3336 (defstruct (js2-let-node
3337 (:include js2-scope)
3338 (:constructor nil)
3339 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3340 (pos js2-token-beg)
3341 len
3342 vars
3343 body
3344 lp
3345 rp)))
3346 "AST node for a let expression or a let statement.
3347 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3348 vars ; a `js2-var-decl-node'
3349 body ; a `js2-node' representing the expression or body block
3350 lp
3351 rp)
3352
3353 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3354 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3355
3356 (defun js2-visit-let-node (n v)
3357 (js2-visit-ast (js2-let-node-vars n) v)
3358 (js2-visit-ast (js2-let-node-body n) v))
3359
3360 (defun js2-print-let-node (n i)
3361 (insert (js2-make-pad i) "let (")
3362 (js2-print-ast (js2-let-node-vars n) 0)
3363 (insert ") ")
3364 (js2-print-ast (js2-let-node-body n) i))
3365
3366 (defstruct (js2-keyword-node
3367 (:include js2-node)
3368 (:constructor nil)
3369 (:constructor make-js2-keyword-node (&key type
3370 (pos js2-token-beg)
3371 (len (- js2-ts-cursor pos)))))
3372 "AST node representing a literal keyword such as `null'.
3373 Used for `null', `this', `true', `false' and `debugger'.
3374 The node type is set to js2-NULL, js2-THIS, etc.")
3375
3376 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3377 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3378
3379 (defun js2-print-keyword-node (n i)
3380 (insert (js2-make-pad i)
3381 (let ((tt (js2-node-type n)))
3382 (cond
3383 ((= tt js2-THIS) "this")
3384 ((= tt js2-NULL) "null")
3385 ((= tt js2-TRUE) "true")
3386 ((= tt js2-FALSE) "false")
3387 ((= tt js2-DEBUGGER) "debugger")
3388 (t (error "Invalid keyword literal type: %d" tt))))))
3389
3390 (defsubst js2-this-node-p (node)
3391 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3392 (eq (js2-node-type node) js2-THIS))
3393
3394 (defstruct (js2-new-node
3395 (:include js2-node)
3396 (:constructor nil)
3397 (:constructor make-js2-new-node (&key (type js2-NEW)
3398 (pos js2-token-beg)
3399 len
3400 target
3401 args
3402 initializer
3403 lp
3404 rp)))
3405 "AST node for new-expression such as new Foo()."
3406 target ; an identifier or reference
3407 args ; a lisp list of argument nodes
3408 lp ; position of left-paren, nil if omitted
3409 rp ; position of right-paren, nil if omitted
3410 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3411
3412 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3413 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3414
3415 (defun js2-visit-new-node (n v)
3416 (js2-visit-ast (js2-new-node-target n) v)
3417 (dolist (arg (js2-new-node-args n))
3418 (js2-visit-ast arg v))
3419 (js2-visit-ast (js2-new-node-initializer n) v))
3420
3421 (defun js2-print-new-node (n i)
3422 (insert (js2-make-pad i) "new ")
3423 (js2-print-ast (js2-new-node-target n))
3424 (insert "(")
3425 (js2-print-list (js2-new-node-args n))
3426 (insert ")")
3427 (when (js2-new-node-initializer n)
3428 (insert " ")
3429 (js2-print-ast (js2-new-node-initializer n))))
3430
3431 (defstruct (js2-name-node
3432 (:include js2-node)
3433 (:constructor nil)
3434 (:constructor make-js2-name-node (&key (type js2-NAME)
3435 (pos js2-token-beg)
3436 (len (- js2-ts-cursor
3437 js2-token-beg))
3438 (name js2-ts-string))))
3439 "AST node for a JavaScript identifier"
3440 name ; a string
3441 scope) ; a `js2-scope' (optional, used for codegen)
3442
3443 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3444 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3445
3446 (defun js2-print-name-node (n i)
3447 (insert (js2-make-pad i)
3448 (js2-name-node-name n)))
3449
3450 (defsubst js2-name-node-length (node)
3451 "Return identifier length of NODE, a `js2-name-node'.
3452 Returns 0 if NODE is nil or its identifier field is nil."
3453 (if node
3454 (length (js2-name-node-name node))
3455 0))
3456
3457 (defstruct (js2-number-node
3458 (:include js2-node)
3459 (:constructor nil)
3460 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3461 (pos js2-token-beg)
3462 (len (- js2-ts-cursor
3463 js2-token-beg))
3464 (value js2-ts-string)
3465 (num-value js2-ts-number))))
3466 "AST node for a number literal."
3467 value ; the original string, e.g. "6.02e23"
3468 num-value) ; the parsed number value
3469
3470 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3471 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3472
3473 (defun js2-print-number-node (n i)
3474 (insert (js2-make-pad i)
3475 (number-to-string (js2-number-node-num-value n))))
3476
3477 (defstruct (js2-regexp-node
3478 (:include js2-node)
3479 (:constructor nil)
3480 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3481 (pos js2-token-beg)
3482 (len (- js2-ts-cursor
3483 js2-token-beg))
3484 value
3485 flags)))
3486 "AST node for a regular expression literal."
3487 value ; the regexp string, without // delimiters
3488 flags) ; a string of flags, e.g. `mi'.
3489
3490 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3491 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3492
3493 (defun js2-print-regexp (n i)
3494 (insert (js2-make-pad i)
3495 "/"
3496 (js2-regexp-node-value n)
3497 "/")
3498 (if (js2-regexp-node-flags n)
3499 (insert (js2-regexp-node-flags n))))
3500
3501 (defstruct (js2-string-node
3502 (:include js2-node)
3503 (:constructor nil)
3504 (:constructor make-js2-string-node (&key (type js2-STRING)
3505 (pos js2-token-beg)
3506 (len (- js2-ts-cursor
3507 js2-token-beg))
3508 (value js2-ts-string))))
3509 "String literal.
3510 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3511 You can tell the quote type by looking at the first character."
3512 value) ; the characters of the string, including the quotes
3513
3514 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3515 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3516
3517 (defun js2-print-string-node (n i)
3518 (insert (js2-make-pad i)
3519 (js2-node-string n)))
3520
3521 (defstruct (js2-array-node
3522 (:include js2-node)
3523 (:constructor nil)
3524 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3525 (pos js2-ts-cursor)
3526 len
3527 elems)))
3528 "AST node for an array literal."
3529 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3530
3531 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3532 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3533
3534 (defun js2-visit-array-node (n v)
3535 (dolist (e (js2-array-node-elems n))
3536 (js2-visit-ast e v)))
3537
3538 (defun js2-print-array-node (n i)
3539 (insert (js2-make-pad i) "[")
3540 (js2-print-list (js2-array-node-elems n))
3541 (insert "]"))
3542
3543 (defstruct (js2-object-node
3544 (:include js2-node)
3545 (:constructor nil)
3546 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3547 (pos js2-ts-cursor)
3548 len
3549 elems)))
3550 "AST node for an object literal expression.
3551 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3552 the latter represents abbreviation in destructuring expressions."
3553 elems)
3554
3555 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3556 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3557
3558 (defun js2-visit-object-node (n v)
3559 (dolist (e (js2-object-node-elems n))
3560 (js2-visit-ast e v)))
3561
3562 (defun js2-print-object-node (n i)
3563 (insert (js2-make-pad i) "{")
3564 (js2-print-list (js2-object-node-elems n))
3565 (insert "}"))
3566
3567 (defstruct (js2-object-prop-node
3568 (:include js2-infix-node)
3569 (:constructor nil)
3570 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3571 (pos js2-ts-cursor)
3572 len
3573 left
3574 right
3575 op-pos)))
3576 "AST node for an object literal prop:value entry.
3577 The `left' field is the property: a name node, string node or number node.
3578 The `right' field is a `js2-node' representing the initializer value.")
3579
3580 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3581 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3582
3583 (defun js2-print-object-prop-node (n i)
3584 (insert (js2-make-pad i))
3585 (js2-print-ast (js2-object-prop-node-left n) 0)
3586 (insert ":")
3587 (js2-print-ast (js2-object-prop-node-right n) 0))
3588
3589 (defstruct (js2-getter-setter-node
3590 (:include js2-infix-node)
3591 (:constructor nil)
3592 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3593 (pos js2-ts-cursor)
3594 len
3595 left
3596 right)))
3597 "AST node for a getter/setter property in an object literal.
3598 The `left' field is the `js2-name-node' naming the getter/setter prop.
3599 The `right' field is always an anonymous `js2-function-node' with a node
3600 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3601
3602 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3603 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3604
3605 (defun js2-print-getter-setter (n i)
3606 (let ((pad (js2-make-pad i))
3607 (left (js2-getter-setter-node-left n))
3608 (right (js2-getter-setter-node-right n)))
3609 (insert pad)
3610 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3611 (js2-print-ast left 0)
3612 (js2-print-ast right 0)))
3613
3614 (defstruct (js2-prop-get-node
3615 (:include js2-infix-node)
3616 (:constructor nil)
3617 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3618 (pos js2-ts-cursor)
3619 len
3620 left
3621 right)))
3622 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3623
3624 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3625 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3626
3627 (defun js2-visit-prop-get-node (n v)
3628 (js2-visit-ast (js2-prop-get-node-left n) v)
3629 (js2-visit-ast (js2-prop-get-node-right n) v))
3630
3631 (defun js2-print-prop-get-node (n i)
3632 (insert (js2-make-pad i))
3633 (js2-print-ast (js2-prop-get-node-left n) 0)
3634 (insert ".")
3635 (js2-print-ast (js2-prop-get-node-right n) 0))
3636
3637 (defstruct (js2-elem-get-node
3638 (:include js2-node)
3639 (:constructor nil)
3640 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3641 (pos js2-ts-cursor)
3642 len
3643 target
3644 element
3645 lb
3646 rb)))
3647 "AST node for an array index expression such as foo[bar]."
3648 target ; a `js2-node' - the expression preceding the "."
3649 element ; a `js2-node' - the expression in brackets
3650 lb ; position of left-bracket, nil if omitted
3651 rb) ; position of right-bracket, nil if omitted
3652
3653 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3654 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3655
3656 (defun js2-visit-elem-get-node (n v)
3657 (js2-visit-ast (js2-elem-get-node-target n) v)
3658 (js2-visit-ast (js2-elem-get-node-element n) v))
3659
3660 (defun js2-print-elem-get-node (n i)
3661 (insert (js2-make-pad i))
3662 (js2-print-ast (js2-elem-get-node-target n) 0)
3663 (insert "[")
3664 (js2-print-ast (js2-elem-get-node-element n) 0)
3665 (insert "]"))
3666
3667 (defstruct (js2-call-node
3668 (:include js2-node)
3669 (:constructor nil)
3670 (:constructor make-js2-call-node (&key (type js2-CALL)
3671 (pos js2-ts-cursor)
3672 len
3673 target
3674 args
3675 lp
3676 rp)))
3677 "AST node for a JavaScript function call."
3678 target ; a `js2-node' evaluating to the function to call
3679 args ; a lisp list of `js2-node' arguments
3680 lp ; position of open-paren, or nil if missing
3681 rp) ; position of close-paren, or nil if missing
3682
3683 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3684 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3685
3686 (defun js2-visit-call-node (n v)
3687 (js2-visit-ast (js2-call-node-target n) v)
3688 (dolist (arg (js2-call-node-args n))
3689 (js2-visit-ast arg v)))
3690
3691 (defun js2-print-call-node (n i)
3692 (insert (js2-make-pad i))
3693 (js2-print-ast (js2-call-node-target n) 0)
3694 (insert "(")
3695 (js2-print-list (js2-call-node-args n))
3696 (insert ")"))
3697
3698 (defstruct (js2-yield-node
3699 (:include js2-node)
3700 (:constructor nil)
3701 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3702 (pos js2-ts-cursor)
3703 len
3704 value)))
3705 "AST node for yield statement or expression."
3706 value) ; optional: value to be yielded
3707
3708 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3709 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3710
3711 (defun js2-visit-yield-node (n v)
3712 (js2-visit-ast (js2-yield-node-value n) v))
3713
3714 (defun js2-print-yield-node (n i)
3715 (insert (js2-make-pad i))
3716 (insert "yield")
3717 (when (js2-yield-node-value n)
3718 (insert " ")
3719 (js2-print-ast (js2-yield-node-value n) 0)))
3720
3721 (defstruct (js2-paren-node
3722 (:include js2-node)
3723 (:constructor nil)
3724 (:constructor make-js2-paren-node (&key (type js2-LP)
3725 (pos js2-ts-cursor)
3726 len
3727 expr)))
3728 "AST node for a parenthesized expression.
3729 In particular, used when the parens are syntactically optional,
3730 as opposed to required parens such as those enclosing an if-conditional."
3731 expr) ; `js2-node'
3732
3733 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3734 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3735
3736 (defun js2-visit-paren-node (n v)
3737 (js2-visit-ast (js2-paren-node-expr n) v))
3738
3739 (defun js2-print-paren-node (n i)
3740 (insert (js2-make-pad i))
3741 (insert "(")
3742 (js2-print-ast (js2-paren-node-expr n) 0)
3743 (insert ")"))
3744
3745 (defstruct (js2-array-comp-node
3746 (:include js2-scope)
3747 (:constructor nil)
3748 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3749 (pos js2-ts-cursor)
3750 len
3751 result
3752 loops
3753 filter
3754 if-pos
3755 lp
3756 rp)))
3757 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3758 result ; result expression (just after left-bracket)
3759 loops ; a lisp list of `js2-array-comp-loop-node'
3760 filter ; guard/filter expression
3761 if-pos ; buffer pos of 'if' keyword, if present, else nil
3762 lp ; buffer position of if-guard left-paren, or nil if not present
3763 rp) ; buffer position of if-guard right-paren, or nil if not present
3764
3765 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3766 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3767
3768 (defun js2-visit-array-comp-node (n v)
3769 (js2-visit-ast (js2-array-comp-node-result n) v)
3770 (dolist (l (js2-array-comp-node-loops n))
3771 (js2-visit-ast l v))
3772 (js2-visit-ast (js2-array-comp-node-filter n) v))
3773
3774 (defun js2-print-array-comp-node (n i)
3775 (let ((pad (js2-make-pad i))
3776 (result (js2-array-comp-node-result n))
3777 (loops (js2-array-comp-node-loops n))
3778 (filter (js2-array-comp-node-filter n)))
3779 (insert pad "[")
3780 (js2-print-ast result 0)
3781 (dolist (l loops)
3782 (insert " ")
3783 (js2-print-ast l 0))
3784 (when filter
3785 (insert " if (")
3786 (js2-print-ast filter 0)
3787 (insert ")"))
3788 (insert "]")))
3789
3790 (defstruct (js2-array-comp-loop-node
3791 (:include js2-for-in-node)
3792 (:constructor nil)
3793 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3794 (pos js2-ts-cursor)
3795 len
3796 iterator
3797 object
3798 in-pos
3799 foreach-p
3800 each-pos
3801 forof-p
3802 lp
3803 rp)))
3804 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3805
3806 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3807 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3808
3809 (defun js2-visit-array-comp-loop (n v)
3810 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3811 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3812
3813 (defun js2-print-array-comp-loop (n i)
3814 (insert "for (")
3815 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3816 (if (js2-array-comp-loop-node-forof-p n)
3817 (insert " of ")
3818 (insert " in "))
3819 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3820 (insert ")"))
3821
3822 (defstruct (js2-empty-expr-node
3823 (:include js2-node)
3824 (:constructor nil)
3825 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3826 (pos js2-token-beg)
3827 len)))
3828 "AST node for an empty expression.")
3829
3830 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3831 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3832
3833 (defstruct (js2-xml-node
3834 (:include js2-block-node)
3835 (:constructor nil)
3836 (:constructor make-js2-xml-node (&key (type js2-XML)
3837 (pos js2-token-beg)
3838 len
3839 kids)))
3840 "AST node for initial parse of E4X literals.
3841 The kids field is a list of XML fragments, each a `js2-string-node' or
3842 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3843
3844 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3845 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3846
3847 (defun js2-print-xml-node (n i)
3848 (dolist (kid (js2-xml-node-kids n))
3849 (js2-print-ast kid i)))
3850
3851 (defstruct (js2-xml-js-expr-node
3852 (:include js2-xml-node)
3853 (:constructor nil)
3854 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3855 (pos js2-ts-cursor)
3856 len
3857 expr)))
3858 "AST node for an embedded JavaScript {expression} in an E4X literal.
3859 The start and end fields correspond to the curly-braces."
3860 expr) ; a `js2-expr-node' of some sort
3861
3862 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3863 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3864
3865 (defun js2-visit-xml-js-expr (n v)
3866 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3867
3868 (defun js2-print-xml-js-expr (n i)
3869 (insert (js2-make-pad i))
3870 (insert "{")
3871 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3872 (insert "}"))
3873
3874 (defstruct (js2-xml-dot-query-node
3875 (:include js2-infix-node)
3876 (:constructor nil)
3877 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3878 (pos js2-ts-cursor)
3879 op-pos
3880 len
3881 left
3882 right
3883 rp)))
3884 "AST node for an E4X foo.(bar) filter expression.
3885 Note that the left-paren is automatically the character immediately
3886 following the dot (.) in the operator. No whitespace is permitted
3887 between the dot and the lp by the scanner."
3888 rp)
3889
3890 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3891 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3892
3893 (defun js2-print-xml-dot-query (n i)
3894 (insert (js2-make-pad i))
3895 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3896 (insert ".(")
3897 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3898 (insert ")"))
3899
3900 (defstruct (js2-xml-ref-node
3901 (:include js2-node)
3902 (:constructor nil)) ; abstract
3903 "Base type for E4X XML attribute-access or property-get expressions.
3904 Such expressions can take a variety of forms. The general syntax has
3905 three parts:
3906
3907 - (optional) an @ (specifying an attribute access)
3908 - (optional) a namespace (a `js2-name-node') and double-colon
3909 - (required) either a `js2-name-node' or a bracketed [expression]
3910
3911 The property-name expressions (examples: ns::name, @name) are
3912 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3913 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3914
3915 This node type (or more specifically, its subclasses) will sometimes
3916 be the right-hand child of a `js2-prop-get-node' or a
3917 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3918 The `js2-xml-ref-node' may also be a standalone primary expression with
3919 no explicit target, which is valid in certain expression contexts such as
3920
3921 company..employee.(@id < 100)
3922
3923 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3924 expression whose parent is a `js2-xml-dot-query-node'."
3925 namespace
3926 at-pos
3927 colon-pos)
3928
3929 (defsubst js2-xml-ref-node-attr-access-p (node)
3930 "Return non-nil if this expression began with an @-token."
3931 (and (numberp (js2-xml-ref-node-at-pos node))
3932 (plusp (js2-xml-ref-node-at-pos node))))
3933
3934 (defstruct (js2-xml-prop-ref-node
3935 (:include js2-xml-ref-node)
3936 (:constructor nil)
3937 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3938 (pos js2-token-beg)
3939 len
3940 propname
3941 namespace
3942 at-pos
3943 colon-pos)))
3944 "AST node for an E4X XML [expr] property-ref expression.
3945 The JavaScript syntax is an optional @, an optional ns::, and a name.
3946
3947 [ '@' ] [ name '::' ] name
3948
3949 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3950 @ns::*, @*::attr, @*::*, and @*.
3951
3952 The node starts at the @ token, if present. Otherwise it starts at the
3953 namespace name. The node bounds extend through the closing right-bracket,
3954 or if it is missing due to a syntax error, through the end of the index
3955 expression."
3956 propname)
3957
3958 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3959 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3960
3961 (defun js2-visit-xml-prop-ref-node (n v)
3962 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3963 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3964
3965 (defun js2-print-xml-prop-ref-node (n i)
3966 (insert (js2-make-pad i))
3967 (if (js2-xml-ref-node-attr-access-p n)
3968 (insert "@"))
3969 (when (js2-xml-prop-ref-node-namespace n)
3970 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3971 (insert "::"))
3972 (if (js2-xml-prop-ref-node-propname n)
3973 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3974
3975 (defstruct (js2-xml-elem-ref-node
3976 (:include js2-xml-ref-node)
3977 (:constructor nil)
3978 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3979 (pos js2-token-beg)
3980 len
3981 expr
3982 lb
3983 rb
3984 namespace
3985 at-pos
3986 colon-pos)))
3987 "AST node for an E4X XML [expr] member-ref expression.
3988 Syntax:
3989
3990 [ '@' ] [ name '::' ] '[' expr ']'
3991
3992 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3993
3994 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3995 is not a legal E4X XML element-ref expression, since it's already used
3996 for standard JavaScript element-get array indexing. Hence, a
3997 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3998 non-nil namespace node, or both.
3999
4000 The node starts at the @ token, if present. Otherwise it starts
4001 at the namespace name. The node bounds extend through the closing
4002 right-bracket, or if it is missing due to a syntax error, through the
4003 end of the index expression."
4004 expr ; the bracketed index expression
4005 lb
4006 rb)
4007
4008 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4009 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4010
4011 (defun js2-visit-xml-elem-ref-node (n v)
4012 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4013 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4014
4015 (defun js2-print-xml-elem-ref-node (n i)
4016 (insert (js2-make-pad i))
4017 (if (js2-xml-ref-node-attr-access-p n)
4018 (insert "@"))
4019 (when (js2-xml-elem-ref-node-namespace n)
4020 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4021 (insert "::"))
4022 (insert "[")
4023 (if (js2-xml-elem-ref-node-expr n)
4024 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4025 (insert "]"))
4026
4027 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4028
4029 (defstruct (js2-xml-start-tag-node
4030 (:include js2-xml-node)
4031 (:constructor nil)
4032 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4033 (pos js2-ts-cursor)
4034 len
4035 name
4036 attrs
4037 kids
4038 empty-p)))
4039 "AST node for an XML start-tag. Not currently used.
4040 The `kids' field is a lisp list of child content nodes."
4041 name ; a `js2-xml-name-node'
4042 attrs ; a lisp list of `js2-xml-attr-node'
4043 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4044
4045 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4046 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4047
4048 (defun js2-visit-xml-start-tag (n v)
4049 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4050 (dolist (attr (js2-xml-start-tag-node-attrs n))
4051 (js2-visit-ast attr v))
4052 (js2-visit-block n v))
4053
4054 (defun js2-print-xml-start-tag (n i)
4055 (insert (js2-make-pad i) "<")
4056 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4057 (when (js2-xml-start-tag-node-attrs n)
4058 (insert " ")
4059 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4060 (insert ">"))
4061
4062 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4063 ;; and add the end-tag to the kids list of the parent as well.
4064 (defstruct (js2-xml-end-tag-node
4065 (:include js2-xml-node)
4066 (:constructor nil)
4067 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4068 (pos js2-ts-cursor)
4069 len
4070 name)))
4071 "AST node for an XML end-tag. Not currently used."
4072 name) ; a `js2-xml-name-node'
4073
4074 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4075 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4076
4077 (defun js2-visit-xml-end-tag (n v)
4078 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4079
4080 (defun js2-print-xml-end-tag (n i)
4081 (insert (js2-make-pad i))
4082 (insert "</")
4083 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4084 (insert ">"))
4085
4086 (defstruct (js2-xml-name-node
4087 (:include js2-xml-node)
4088 (:constructor nil)
4089 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4090 (pos js2-ts-cursor)
4091 len
4092 namespace
4093 kids)))
4094 "AST node for an E4X XML name. Not currently used.
4095 Any XML name can be qualified with a namespace, hence the namespace field.
4096 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4097 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4098 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4099 namespace) ; a `js2-string-node'
4100
4101 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4102 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4103
4104 (defun js2-visit-xml-name-node (n v)
4105 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4106
4107 (defun js2-print-xml-name-node (n i)
4108 (insert (js2-make-pad i))
4109 (when (js2-xml-name-node-namespace n)
4110 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4111 (insert "::"))
4112 (dolist (kid (js2-xml-name-node-kids n))
4113 (js2-print-ast kid 0)))
4114
4115 (defstruct (js2-xml-pi-node
4116 (:include js2-xml-node)
4117 (:constructor nil)
4118 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4119 (pos js2-ts-cursor)
4120 len
4121 name
4122 attrs)))
4123 "AST node for an E4X XML processing instruction. Not currently used."
4124 name ; a `js2-xml-name-node'
4125 attrs) ; a list of `js2-xml-attr-node'
4126
4127 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4128 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4129
4130 (defun js2-visit-xml-pi-node (n v)
4131 (js2-visit-ast (js2-xml-pi-node-name n) v)
4132 (dolist (attr (js2-xml-pi-node-attrs n))
4133 (js2-visit-ast attr v)))
4134
4135 (defun js2-print-xml-pi-node (n i)
4136 (insert (js2-make-pad i) "<?")
4137 (js2-print-ast (js2-xml-pi-node-name n))
4138 (when (js2-xml-pi-node-attrs n)
4139 (insert " ")
4140 (js2-print-list (js2-xml-pi-node-attrs n)))
4141 (insert "?>"))
4142
4143 (defstruct (js2-xml-cdata-node
4144 (:include js2-xml-node)
4145 (:constructor nil)
4146 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4147 (pos js2-ts-cursor)
4148 len
4149 content)))
4150 "AST node for a CDATA escape section. Not currently used."
4151 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4152
4153 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4154 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4155
4156 (defun js2-visit-xml-cdata-node (n v)
4157 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4158
4159 (defun js2-print-xml-cdata-node (n i)
4160 (insert (js2-make-pad i))
4161 (js2-print-ast (js2-xml-cdata-node-content n)))
4162
4163 (defstruct (js2-xml-attr-node
4164 (:include js2-xml-node)
4165 (:constructor nil)
4166 (:constructor make-js2-attr-node (&key (type js2-XML)
4167 (pos js2-ts-cursor)
4168 len
4169 name
4170 value
4171 eq-pos
4172 quote-type)))
4173 "AST node representing a foo='bar' XML attribute value. Not yet used."
4174 name ; a `js2-xml-name-node'
4175 value ; a `js2-xml-name-node'
4176 eq-pos ; buffer position of "=" sign
4177 quote-type) ; 'single or 'double
4178
4179 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4180 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4181
4182 (defun js2-visit-xml-attr-node (n v)
4183 (js2-visit-ast (js2-xml-attr-node-name n) v)
4184 (js2-visit-ast (js2-xml-attr-node-value n) v))
4185
4186 (defun js2-print-xml-attr-node (n i)
4187 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4188 "'"
4189 "\"")))
4190 (insert (js2-make-pad i))
4191 (js2-print-ast (js2-xml-attr-node-name n) 0)
4192 (insert "=" quote)
4193 (js2-print-ast (js2-xml-attr-node-value n) 0)
4194 (insert quote)))
4195
4196 (defstruct (js2-xml-text-node
4197 (:include js2-xml-node)
4198 (:constructor nil)
4199 (:constructor make-js2-text-node (&key (type js2-XML)
4200 (pos js2-ts-cursor)
4201 len
4202 content)))
4203 "AST node for an E4X XML text node. Not currently used."
4204 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4205
4206 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4207 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4208
4209 (defun js2-visit-xml-text-node (n v)
4210 (js2-visit-ast (js2-xml-text-node-content n) v))
4211
4212 (defun js2-print-xml-text-node (n i)
4213 (insert (js2-make-pad i))
4214 (dolist (kid (js2-xml-text-node-content n))
4215 (js2-print-ast kid)))
4216
4217 (defstruct (js2-xml-comment-node
4218 (:include js2-xml-node)
4219 (:constructor nil)
4220 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4221 (pos js2-ts-cursor)
4222 len)))
4223 "AST node for E4X XML comment. Not currently used.")
4224
4225 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4226 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4227
4228 (defun js2-print-xml-comment (n i)
4229 (insert (js2-make-pad i)
4230 (js2-node-string n)))
4231
4232 ;;; Node utilities
4233
4234 (defsubst js2-node-line (n)
4235 "Fetch the source line number at the start of node N.
4236 This is O(n) in the length of the source buffer; use prudently."
4237 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4238
4239 (defsubst js2-block-node-kid (n i)
4240 "Return child I of node N, or nil if there aren't that many."
4241 (nth i (js2-block-node-kids n)))
4242
4243 (defsubst js2-block-node-first (n)
4244 "Return first child of block node N, or nil if there is none."
4245 (first (js2-block-node-kids n)))
4246
4247 (defun js2-node-root (n)
4248 "Return the root of the AST containing N.
4249 If N has no parent pointer, returns N."
4250 (let ((parent (js2-node-parent n)))
4251 (if parent
4252 (js2-node-root parent)
4253 n)))
4254
4255 (defun js2-node-position-in-parent (node &optional parent)
4256 "Return the position of NODE in parent's block-kids list.
4257 PARENT can be supplied if known. Positioned returned is zero-indexed.
4258 Returns 0 if NODE is not a child of a block statement, or if NODE
4259 is not a statement node."
4260 (let ((p (or parent (js2-node-parent node)))
4261 (i 0))
4262 (if (not (js2-block-node-p p))
4263 i
4264 (or (js2-position node (js2-block-node-kids p))
4265 0))))
4266
4267 (defsubst js2-node-short-name (n)
4268 "Return the short name of node N as a string, e.g. `js2-if-node'."
4269 (substring (symbol-name (aref n 0))
4270 (length "cl-struct-")))
4271
4272 (defsubst js2-node-child-list (node)
4273 "Return the child list for NODE, a lisp list of nodes.
4274 Works for block nodes, array nodes, obj literals, funarg lists,
4275 var decls and try nodes (for catch clauses). Note that you should call
4276 `js2-block-node-kids' on the function body for the body statements.
4277 Returns nil for zero-length child lists or unsupported nodes."
4278 (cond
4279 ((js2-function-node-p node)
4280 (js2-function-node-params node))
4281 ((js2-block-node-p node)
4282 (js2-block-node-kids node))
4283 ((js2-try-node-p node)
4284 (js2-try-node-catch-clauses node))
4285 ((js2-array-node-p node)
4286 (js2-array-node-elems node))
4287 ((js2-object-node-p node)
4288 (js2-object-node-elems node))
4289 ((js2-call-node-p node)
4290 (js2-call-node-args node))
4291 ((js2-new-node-p node)
4292 (js2-new-node-args node))
4293 ((js2-var-decl-node-p node)
4294 (js2-var-decl-node-kids node))
4295 (t
4296 nil)))
4297
4298 (defsubst js2-node-set-child-list (node kids)
4299 "Set the child list for NODE to KIDS."
4300 (cond
4301 ((js2-function-node-p node)
4302 (setf (js2-function-node-params node) kids))
4303 ((js2-block-node-p node)
4304 (setf (js2-block-node-kids node) kids))
4305 ((js2-try-node-p node)
4306 (setf (js2-try-node-catch-clauses node) kids))
4307 ((js2-array-node-p node)
4308 (setf (js2-array-node-elems node) kids))
4309 ((js2-object-node-p node)
4310 (setf (js2-object-node-elems node) kids))
4311 ((js2-call-node-p node)
4312 (setf (js2-call-node-args node) kids))
4313 ((js2-new-node-p node)
4314 (setf (js2-new-node-args node) kids))
4315 ((js2-var-decl-node-p node)
4316 (setf (js2-var-decl-node-kids node) kids))
4317 (t
4318 (error "Unsupported node type: %s" (js2-node-short-name node))))
4319 kids)
4320
4321 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4322 (defconst js2-paren-expr-nodes
4323 '(cl-struct-js2-array-comp-loop-node
4324 cl-struct-js2-array-comp-node
4325 cl-struct-js2-call-node
4326 cl-struct-js2-catch-node
4327 cl-struct-js2-do-node
4328 cl-struct-js2-elem-get-node
4329 cl-struct-js2-for-in-node
4330 cl-struct-js2-for-node
4331 cl-struct-js2-function-node
4332 cl-struct-js2-if-node
4333 cl-struct-js2-let-node
4334 cl-struct-js2-new-node
4335 cl-struct-js2-paren-node
4336 cl-struct-js2-switch-node
4337 cl-struct-js2-while-node
4338 cl-struct-js2-with-node
4339 cl-struct-js2-xml-dot-query-node)
4340 "Node types that can have a parenthesized child expression.
4341 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4342
4343 (defsubst js2-paren-expr-node-p (node)
4344 "Return t for nodes that typically have a parenthesized child expression.
4345 Useful for computing the indentation anchors for arg-lists and conditions.
4346 Note that it may return a false positive, for instance when NODE is
4347 a `js2-new-node' and there are no arguments or parentheses."
4348 (memq (aref node 0) js2-paren-expr-nodes))
4349
4350 ;; Fake polymorphism... yech.
4351 (defsubst js2-node-lp (node)
4352 "Return relative left-paren position for NODE, if applicable.
4353 For `js2-elem-get-node' structs, returns left-bracket position.
4354 Note that the position may be nil in the case of a parse error."
4355 (cond
4356 ((js2-elem-get-node-p node)
4357 (js2-elem-get-node-lb node))
4358 ((js2-loop-node-p node)
4359 (js2-loop-node-lp node))
4360 ((js2-function-node-p node)
4361 (js2-function-node-lp node))
4362 ((js2-if-node-p node)
4363 (js2-if-node-lp node))
4364 ((js2-new-node-p node)
4365 (js2-new-node-lp node))
4366 ((js2-call-node-p node)
4367 (js2-call-node-lp node))
4368 ((js2-paren-node-p node)
4369 (js2-node-pos node))
4370 ((js2-switch-node-p node)
4371 (js2-switch-node-lp node))
4372 ((js2-catch-node-p node)
4373 (js2-catch-node-lp node))
4374 ((js2-let-node-p node)
4375 (js2-let-node-lp node))
4376 ((js2-array-comp-node-p node)
4377 (js2-array-comp-node-lp node))
4378 ((js2-with-node-p node)
4379 (js2-with-node-lp node))
4380 ((js2-xml-dot-query-node-p node)
4381 (1+ (js2-infix-node-op-pos node)))
4382 (t
4383 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4384
4385 ;; Fake polymorphism... blech.
4386 (defsubst js2-node-rp (node)
4387 "Return relative right-paren position for NODE, if applicable.
4388 For `js2-elem-get-node' structs, returns right-bracket position.
4389 Note that the position may be nil in the case of a parse error."
4390 (cond
4391 ((js2-elem-get-node-p node)
4392 (js2-elem-get-node-lb node))
4393 ((js2-loop-node-p node)
4394 (js2-loop-node-rp node))
4395 ((js2-function-node-p node)
4396 (js2-function-node-rp node))
4397 ((js2-if-node-p node)
4398 (js2-if-node-rp node))
4399 ((js2-new-node-p node)
4400 (js2-new-node-rp node))
4401 ((js2-call-node-p node)
4402 (js2-call-node-rp node))
4403 ((js2-paren-node-p node)
4404 (+ (js2-node-pos node) (js2-node-len node)))
4405 ((js2-switch-node-p node)
4406 (js2-switch-node-rp node))
4407 ((js2-catch-node-p node)
4408 (js2-catch-node-rp node))
4409 ((js2-let-node-p node)
4410 (js2-let-node-rp node))
4411 ((js2-array-comp-node-p node)
4412 (js2-array-comp-node-rp node))
4413 ((js2-with-node-p node)
4414 (js2-with-node-rp node))
4415 ((js2-xml-dot-query-node-p node)
4416 (1+ (js2-xml-dot-query-node-rp node)))
4417 (t
4418 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4419
4420 (defsubst js2-node-first-child (node)
4421 "Returns the first element of `js2-node-child-list' for NODE."
4422 (car (js2-node-child-list node)))
4423
4424 (defsubst js2-node-last-child (node)
4425 "Returns the last element of `js2-node-last-child' for NODE."
4426 (car (last (js2-node-child-list node))))
4427
4428 (defun js2-node-prev-sibling (node)
4429 "Return the previous statement in parent.
4430 Works for parents supported by `js2-node-child-list'.
4431 Returns nil if NODE is not in the parent, or PARENT is
4432 not a supported node, or if NODE is the first child."
4433 (let* ((p (js2-node-parent node))
4434 (kids (js2-node-child-list p))
4435 (sib (car kids)))
4436 (while (and kids
4437 (not (eq node (cadr kids))))
4438 (setq kids (cdr kids)
4439 sib (car kids)))
4440 sib))
4441
4442 (defun js2-node-next-sibling (node)
4443 "Return the next statement in parent block.
4444 Returns nil if NODE is not in the block, or PARENT is not
4445 a block node, or if NODE is the last statement."
4446 (let* ((p (js2-node-parent node))
4447 (kids (js2-node-child-list p)))
4448 (while (and kids
4449 (not (eq node (car kids))))
4450 (setq kids (cdr kids)))
4451 (cadr kids)))
4452
4453 (defun js2-node-find-child-before (pos parent &optional after)
4454 "Find the last child that starts before POS in parent.
4455 If AFTER is non-nil, returns first child starting after POS.
4456 POS is an absolute buffer position. PARENT is any node
4457 supported by `js2-node-child-list'.
4458 Returns nil if no applicable child is found."
4459 (let ((kids (if (js2-function-node-p parent)
4460 (js2-block-node-kids (js2-function-node-body parent))
4461 (js2-node-child-list parent)))
4462 (beg (if (js2-function-node-p parent)
4463 (js2-node-abs-pos (js2-function-node-body parent))
4464 (js2-node-abs-pos parent)))
4465 kid
4466 result
4467 fn
4468 (continue t))
4469 (setq fn (if after '>= '<))
4470 (while (and kids continue)
4471 (setq kid (car kids))
4472 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4473 (setq result kid
4474 continue (if after nil t))
4475 (setq continue (if after t nil)))
4476 (setq kids (cdr kids)))
4477 result))
4478
4479 (defun js2-node-find-child-after (pos parent)
4480 "Find first child that starts after POS in parent.
4481 POS is an absolute buffer position. PARENT is any node
4482 supported by `js2-node-child-list'.
4483 Returns nil if no applicable child is found."
4484 (js2-node-find-child-before pos parent 'after))
4485
4486 (defun js2-node-replace-child (pos parent new-node)
4487 "Replace node at index POS in PARENT with NEW-NODE.
4488 Only works for parents supported by `js2-node-child-list'."
4489 (let ((kids (js2-node-child-list parent))
4490 (i 0))
4491 (while (< i pos)
4492 (setq kids (cdr kids)
4493 i (1+ i)))
4494 (setcar kids new-node)
4495 (js2-node-add-children parent new-node)))
4496
4497 (defun js2-node-buffer (n)
4498 "Return the buffer associated with AST N.
4499 Returns nil if the buffer is not set as a property on the root
4500 node, or if parent links were not recorded during parsing."
4501 (let ((root (js2-node-root n)))
4502 (and root
4503 (js2-ast-root-p root)
4504 (js2-ast-root-buffer root))))
4505
4506 (defsubst js2-block-node-push (n kid)
4507 "Push js2-node KID onto the end of js2-block-node N's child list.
4508 KID is always added to the -end- of the kids list.
4509 Function also calls `js2-node-add-children' to add the parent link."
4510 (let ((kids (js2-node-child-list n)))
4511 (if kids
4512 (setcdr kids (nconc (cdr kids) (list kid)))
4513 (js2-node-set-child-list n (list kid)))
4514 (js2-node-add-children n kid)))
4515
4516 (defun js2-node-string (node)
4517 (let ((buf (js2-node-buffer node))
4518 pos)
4519 (unless buf
4520 (error "No buffer available for node %s" node))
4521 (with-current-buffer buf
4522 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4523 (+ pos (js2-node-len node))))))
4524
4525 ;; Container for storing the node we're looking for in a traversal.
4526 (js2-deflocal js2-discovered-node nil)
4527
4528 ;; Keep track of absolute node position during traversals.
4529 (js2-deflocal js2-visitor-offset nil)
4530
4531 (js2-deflocal js2-node-search-point nil)
4532
4533 (when js2-mode-dev-mode-p
4534 (defun js2-find-node-at-point ()
4535 (interactive)
4536 (let ((node (js2-node-at-point)))
4537 (message "%s" (or node "No node found at point"))))
4538 (defun js2-node-name-at-point ()
4539 (interactive)
4540 (let ((node (js2-node-at-point)))
4541 (message "%s" (if node
4542 (js2-node-short-name node)
4543 "No node found at point.")))))
4544
4545 (defun js2-node-at-point (&optional pos skip-comments)
4546 "Return AST node at POS, a buffer position, defaulting to current point.
4547 The `js2-mode-ast' variable must be set to the current parse tree.
4548 Signals an error if the AST (`js2-mode-ast') is nil.
4549 Always returns a node - if it can't find one, it returns the root.
4550 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4551 (let ((ast js2-mode-ast)
4552 result)
4553 (unless ast
4554 (error "No JavaScript AST available"))
4555 ;; Look through comments first, since they may be inside nodes that
4556 ;; would otherwise report a match.
4557 (setq pos (or pos (point))
4558 result (if (> pos (js2-node-abs-end ast))
4559 ast
4560 (if (not skip-comments)
4561 (js2-comment-at-point pos))))
4562 (unless result
4563 (setq js2-discovered-node nil
4564 js2-visitor-offset 0
4565 js2-node-search-point pos)
4566 (unwind-protect
4567 (catch 'js2-visit-done
4568 (js2-visit-ast ast #'js2-node-at-point-visitor))
4569 (setq js2-visitor-offset nil
4570 js2-node-search-point nil))
4571 (setq result js2-discovered-node))
4572 ;; may have found a comment beyond end of last child node,
4573 ;; since visiting the ast-root looks at the comment-list last.
4574 (if (and skip-comments
4575 (js2-comment-node-p result))
4576 (setq result nil))
4577 (or result js2-mode-ast)))
4578
4579 (defun js2-node-at-point-visitor (node end-p)
4580 (let ((rel-pos (js2-node-pos node))
4581 abs-pos
4582 abs-end
4583 (point js2-node-search-point))
4584 (cond
4585 (end-p
4586 ;; this evaluates to a non-nil return value, even if it's zero
4587 (decf js2-visitor-offset rel-pos))
4588 ;; we already looked for comments before visiting, and don't want them now
4589 ((js2-comment-node-p node)
4590 nil)
4591 (t
4592 (setq abs-pos (incf js2-visitor-offset rel-pos)
4593 ;; we only want to use the node if the point is before
4594 ;; the last character position in the node, so we decrement
4595 ;; the absolute end by 1.
4596 abs-end (+ abs-pos (js2-node-len node) -1))
4597 (cond
4598 ;; If this node starts after search-point, stop the search.
4599 ((> abs-pos point)
4600 (throw 'js2-visit-done nil))
4601 ;; If this node ends before the search-point, don't check kids.
4602 ((> point abs-end)
4603 nil)
4604 (t
4605 ;; Otherwise point is within this node, possibly in a child.
4606 (setq js2-discovered-node node)
4607 t)))))) ; keep processing kids to look for more specific match
4608
4609 (defsubst js2-block-comment-p (node)
4610 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4611 (and (js2-comment-node-p node)
4612 (memq (js2-comment-node-format node) '(jsdoc block))))
4613
4614 ;; TODO: put the comments in a vector and binary-search them instead
4615 (defun js2-comment-at-point (&optional pos)
4616 "Look through scanned comment nodes for one containing POS.
4617 POS is a buffer position that defaults to current point.
4618 Function returns nil if POS was not in any comment node."
4619 (let ((ast js2-mode-ast)
4620 (x (or pos (point)))
4621 beg
4622 end)
4623 (unless ast
4624 (error "No JavaScript AST available"))
4625 (catch 'done
4626 ;; Comments are stored in lexical order.
4627 (dolist (comment (js2-ast-root-comments ast) nil)
4628 (setq beg (js2-node-abs-pos comment)
4629 end (+ beg (js2-node-len comment)))
4630 (if (and (>= x beg)
4631 (<= x end))
4632 (throw 'done comment))))))
4633
4634 (defun js2-mode-find-parent-fn (node)
4635 "Find function enclosing NODE.
4636 Returns nil if NODE is not inside a function."
4637 (setq node (js2-node-parent node))
4638 (while (and node (not (js2-function-node-p node)))
4639 (setq node (js2-node-parent node)))
4640 (and (js2-function-node-p node) node))
4641
4642 (defun js2-mode-find-enclosing-fn (node)
4643 "Find function or root enclosing NODE."
4644 (if (js2-ast-root-p node)
4645 node
4646 (setq node (js2-node-parent node))
4647 (while (not (or (js2-ast-root-p node)
4648 (js2-function-node-p node)))
4649 (setq node (js2-node-parent node)))
4650 node))
4651
4652 (defun js2-mode-find-enclosing-node (beg end)
4653 "Find script or function fully enclosing BEG and END."
4654 (let ((node (js2-node-at-point beg))
4655 pos
4656 (continue t))
4657 (while continue
4658 (if (or (js2-ast-root-p node)
4659 (and (js2-function-node-p node)
4660 (<= (setq pos (js2-node-abs-pos node)) beg)
4661 (>= (+ pos (js2-node-len node)) end)))
4662 (setq continue nil)
4663 (setq node (js2-node-parent node))))
4664 node))
4665
4666 (defun js2-node-parent-script-or-fn (node)
4667 "Find script or function immediately enclosing NODE.
4668 If NODE is the ast-root, returns nil."
4669 (if (js2-ast-root-p node)
4670 nil
4671 (setq node (js2-node-parent node))
4672 (while (and node (not (or (js2-function-node-p node)
4673 (js2-script-node-p node))))
4674 (setq node (js2-node-parent node)))
4675 node))
4676
4677 (defsubst js2-nested-function-p (node)
4678 "Return t if NODE is a nested function, or is inside a nested function."
4679 (unless (js2-ast-root-p node)
4680 (js2-function-node-p (if (js2-function-node-p node)
4681 (js2-node-parent-script-or-fn node)
4682 (js2-node-parent-script-or-fn
4683 (js2-node-parent-script-or-fn node))))))
4684
4685 (defsubst js2-function-param-node-p (node)
4686 "Return non-nil if NODE is a param node of a `js2-function-node'."
4687 (let ((parent (js2-node-parent node)))
4688 (and parent
4689 (js2-function-node-p parent)
4690 (memq node (js2-function-node-params parent)))))
4691
4692 (defsubst js2-mode-shift-kids (kids start offset)
4693 (dolist (kid kids)
4694 (if (> (js2-node-pos kid) start)
4695 (incf (js2-node-pos kid) offset))))
4696
4697 (defsubst js2-mode-shift-children (parent start offset)
4698 "Update start-positions of all children of PARENT beyond START."
4699 (let ((root (js2-node-root parent)))
4700 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4701 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4702
4703 (defsubst js2-node-is-descendant (node ancestor)
4704 "Return t if NODE is a descendant of ANCESTOR."
4705 (while (and node
4706 (not (eq node ancestor)))
4707 (setq node (js2-node-parent node)))
4708 node)
4709
4710 ;;; visitor infrastructure
4711
4712 (defun js2-visit-none (node callback)
4713 "Visitor for AST node that have no node children."
4714 nil)
4715
4716 (defun js2-print-none (node indent)
4717 "Visitor for AST node with no printed representation.")
4718
4719 (defun js2-print-body (node indent)
4720 "Print a statement, or a block without braces."
4721 (if (js2-block-node-p node)
4722 (dolist (kid (js2-block-node-kids node))
4723 (js2-print-ast kid indent))
4724 (js2-print-ast node indent)))
4725
4726 (defun js2-print-list (args &optional delimiter)
4727 (loop with len = (length args)
4728 for arg in args
4729 for count from 1
4730 do
4731 (js2-print-ast arg 0)
4732 (if (< count len)
4733 (insert (or delimiter ", ")))))
4734
4735 (defun js2-print-tree (ast)
4736 "Prints an AST to the current buffer.
4737 Makes `js2-ast-parent-nodes' available to the printer functions."
4738 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4739 (js2-print-ast ast)))
4740
4741 (defun js2-print-ast (node &optional indent)
4742 "Helper function for printing AST nodes.
4743 Requires `js2-ast-parent-nodes' to be non-nil.
4744 You should use `js2-print-tree' instead of this function."
4745 (let ((printer (get (aref node 0) 'js2-printer))
4746 (i (or indent 0))
4747 (pos (js2-node-abs-pos node)))
4748 ;; TODO: wedge comments in here somewhere
4749 (if printer
4750 (funcall printer node i))))
4751
4752 (defconst js2-side-effecting-tokens
4753 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4754 (dolist (tt (list js2-ASSIGN
4755 js2-ASSIGN_ADD
4756 js2-ASSIGN_BITAND
4757 js2-ASSIGN_BITOR
4758 js2-ASSIGN_BITXOR
4759 js2-ASSIGN_DIV
4760 js2-ASSIGN_LSH
4761 js2-ASSIGN_MOD
4762 js2-ASSIGN_MUL
4763 js2-ASSIGN_RSH
4764 js2-ASSIGN_SUB
4765 js2-ASSIGN_URSH
4766 js2-BLOCK
4767 js2-BREAK
4768 js2-CALL
4769 js2-CATCH
4770 js2-CATCH_SCOPE
4771 js2-CONST
4772 js2-CONTINUE
4773 js2-DEBUGGER
4774 js2-DEC
4775 js2-DELPROP
4776 js2-DEL_REF
4777 js2-DO
4778 js2-ELSE
4779 js2-EMPTY
4780 js2-ENTERWITH
4781 js2-EXPORT
4782 js2-EXPR_RESULT
4783 js2-FINALLY
4784 js2-FOR
4785 js2-FUNCTION
4786 js2-GOTO
4787 js2-IF
4788 js2-IFEQ
4789 js2-IFNE
4790 js2-IMPORT
4791 js2-INC
4792 js2-JSR
4793 js2-LABEL
4794 js2-LEAVEWITH
4795 js2-LET
4796 js2-LETEXPR
4797 js2-LOCAL_BLOCK
4798 js2-LOOP
4799 js2-NEW
4800 js2-REF_CALL
4801 js2-RETHROW
4802 js2-RETURN
4803 js2-RETURN_RESULT
4804 js2-SEMI
4805 js2-SETELEM
4806 js2-SETELEM_OP
4807 js2-SETNAME
4808 js2-SETPROP
4809 js2-SETPROP_OP
4810 js2-SETVAR
4811 js2-SET_REF
4812 js2-SET_REF_OP
4813 js2-SWITCH
4814 js2-TARGET
4815 js2-THROW
4816 js2-TRY
4817 js2-VAR
4818 js2-WHILE
4819 js2-WITH
4820 js2-WITHEXPR
4821 js2-YIELD))
4822 (aset tokens tt t))
4823 (if js2-instanceof-has-side-effects
4824 (aset tokens js2-INSTANCEOF t))
4825 tokens))
4826
4827 (defun js2-node-has-side-effects (node)
4828 "Return t if NODE has side effects."
4829 (when node ; makes it easier to handle malformed expressions
4830 (let ((tt (js2-node-type node)))
4831 (cond
4832 ;; This doubtless needs some work, since EXPR_VOID is used
4833 ;; in several ways in Rhino, and I may not have caught them all.
4834 ;; I'll wait for people to notice incorrect warnings.
4835 ((and (= tt js2-EXPR_VOID)
4836 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4837 (let ((expr (js2-expr-stmt-node-expr node)))
4838 (or (js2-node-has-side-effects expr)
4839 (when (js2-string-node-p expr)
4840 (string= "use strict" (js2-string-node-value expr))))))
4841 ((= tt js2-COMMA)
4842 (js2-node-has-side-effects (js2-infix-node-right node)))
4843 ((or (= tt js2-AND)
4844 (= tt js2-OR))
4845 (or (js2-node-has-side-effects (js2-infix-node-right node))
4846 (js2-node-has-side-effects (js2-infix-node-left node))))
4847 ((= tt js2-HOOK)
4848 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4849 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4850 ((js2-paren-node-p node)
4851 (js2-node-has-side-effects (js2-paren-node-expr node)))
4852 ((= tt js2-ERROR) ; avoid cascaded error messages
4853 nil)
4854 (t
4855 (aref js2-side-effecting-tokens tt))))))
4856
4857 (defun js2-member-expr-leftmost-name (node)
4858 "For an expr such as foo.bar.baz, return leftmost node foo.
4859 NODE is any `js2-node' object. If it represents a member expression,
4860 which is any sequence of property gets, element-gets, function calls,
4861 or xml descendants/filter operators, then we look at the lexically
4862 leftmost (first) node in the chain. If it is a name-node we return it.
4863 Note that NODE can be a raw name-node and it will be returned as well.
4864 If NODE is not a name-node or member expression, or if it is a member
4865 expression whose leftmost target is not a name node, returns nil."
4866 (let ((continue t)
4867 result)
4868 (while (and continue (not result))
4869 (cond
4870 ((js2-name-node-p node)
4871 (setq result node))
4872 ((js2-prop-get-node-p node)
4873 (setq node (js2-prop-get-node-left node)))
4874 ;; TODO: handle call-nodes, xml-nodes, others?
4875 (t
4876 (setq continue nil))))
4877 result))
4878
4879 (defconst js2-stmt-node-types
4880 (list js2-BLOCK
4881 js2-BREAK
4882 js2-CONTINUE
4883 js2-DEFAULT ; e4x "default xml namespace" statement
4884 js2-DO
4885 js2-EXPR_RESULT
4886 js2-EXPR_VOID
4887 js2-FOR
4888 js2-IF
4889 js2-RETURN
4890 js2-SWITCH
4891 js2-THROW
4892 js2-TRY
4893 js2-WHILE
4894 js2-WITH)
4895 "Node types that only appear in statement contexts.
4896 The list does not include nodes that always appear as the child
4897 of another specific statement type, such as switch-cases,
4898 catch and finally blocks, and else-clauses. The list also excludes
4899 nodes like yield, let and var, which may appear in either expression
4900 or statement context, and in the latter context always have a
4901 `js2-expr-stmt-node' parent. Finally, the list does not include
4902 functions or scripts, which are treated separately from statements
4903 by the JavaScript parser and runtime.")
4904
4905 (defun js2-stmt-node-p (node)
4906 "Heuristic for figuring out if NODE is a statement.
4907 Some node types can appear in either an expression context or a
4908 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4909 For these node types in a statement context, the parent will be a
4910 `js2-expr-stmt-node'.
4911 Functions aren't included in the check."
4912 (memq (js2-node-type node) js2-stmt-node-types))
4913
4914 (defsubst js2-mode-find-first-stmt (node)
4915 "Search upward starting from NODE looking for a statement.
4916 For purposes of this function, a `js2-function-node' counts."
4917 (while (not (or (js2-stmt-node-p node)
4918 (js2-function-node-p node)))
4919 (setq node (js2-node-parent node)))
4920 node)
4921
4922 (defun js2-node-parent-stmt (node)
4923 "Return the node's first ancestor that is a statement.
4924 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4925 appearing in a statement context will have a parent that is a
4926 `js2-expr-stmt-node' that will be returned by this function."
4927 (let ((parent (js2-node-parent node)))
4928 (if (or (null parent)
4929 (js2-stmt-node-p parent)
4930 (and (js2-function-node-p parent)
4931 (not (eq (js2-function-node-form parent)
4932 'FUNCTION_EXPRESSION))))
4933 parent
4934 (js2-node-parent-stmt parent))))
4935
4936 ;; In the Mozilla Rhino sources, Roshan James writes:
4937 ;; Does consistent-return analysis on the function body when strict mode is
4938 ;; enabled.
4939 ;;
4940 ;; function (x) { return (x+1) }
4941 ;;
4942 ;; is ok, but
4943 ;;
4944 ;; function (x) { if (x < 0) return (x+1); }
4945 ;;
4946 ;; is not because the function can potentially return a value when the
4947 ;; condition is satisfied and if not, the function does not explicitly
4948 ;; return a value.
4949 ;;
4950 ;; This extends to checking mismatches such as "return" and "return <value>"
4951 ;; used in the same function. Warnings are not emitted if inconsistent
4952 ;; returns exist in code that can be statically shown to be unreachable.
4953 ;; Ex.
4954 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4955 ;;
4956 ;; emits no warning. However if the loop had a break statement, then a
4957 ;; warning would be emitted.
4958 ;;
4959 ;; The consistency analysis looks at control structures such as loops, ifs,
4960 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4961 ;; warns the user about an inconsistent set of termination possibilities.
4962 ;;
4963 ;; These flags enumerate the possible ways a statement/function can
4964 ;; terminate. These flags are used by endCheck() and by the Parser to
4965 ;; detect inconsistent return usage.
4966 ;;
4967 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4968 ;; able to execute (example: throw, continue)
4969 ;;
4970 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4971 ;; next one. Statement such as return dont. A compound statement may have
4972 ;; some branch that drops off control to the next statement.
4973 ;;
4974 ;; END_RETURNS indicates that the statement can return with no value.
4975 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4976 ;;
4977 ;; A compound statement such as
4978 ;; if (condition) {
4979 ;; return value;
4980 ;; }
4981 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4982
4983 (defconst js2-END_UNREACHED 0)
4984 (defconst js2-END_DROPS_OFF 1)
4985 (defconst js2-END_RETURNS 2)
4986 (defconst js2-END_RETURNS_VALUE 4)
4987 (defconst js2-END_YIELDS 8)
4988
4989 (defun js2-has-consistent-return-usage (node)
4990 "Check that every return usage in a function body is consistent.
4991 Returns t if the function satisfies strict mode requirement."
4992 (let ((n (js2-end-check node)))
4993 ;; either it doesn't return a value in any branch...
4994 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4995 ;; or it returns a value (or is unreached) at every branch
4996 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4997 js2-END_RETURNS
4998 js2-END_YIELDS)))))
4999
5000 (defun js2-end-check-if (node)
5001 "Returns in the then and else blocks must be consistent with each other.
5002 If there is no else block, then the return statement can fall through.
5003 Returns logical OR of END_* flags"
5004 (let ((th (js2-if-node-then-part node))
5005 (el (js2-if-node-else-part node)))
5006 (if (null th)
5007 js2-END_UNREACHED
5008 (logior (js2-end-check th) (if el
5009 (js2-end-check el)
5010 js2-END_DROPS_OFF)))))
5011
5012 (defun js2-end-check-switch (node)
5013 "Consistency of return statements is checked between the case statements.
5014 If there is no default, then the switch can fall through. If there is a
5015 default, we check to see if all code paths in the default return or if
5016 there is a code path that can fall through.
5017 Returns logical OR of END_* flags."
5018 (let ((rv js2-END_UNREACHED)
5019 default-case)
5020 ;; examine the cases
5021 (catch 'break
5022 (dolist (c (js2-switch-node-cases node))
5023 (if (js2-case-node-expr c)
5024 (js2-set-flag rv (js2-end-check-block c))
5025 (setq default-case c)
5026 (throw 'break nil))))
5027 ;; we don't care how the cases drop into each other
5028 (js2-clear-flag rv js2-END_DROPS_OFF)
5029 ;; examine the default
5030 (js2-set-flag rv (if default-case
5031 (js2-end-check default-case)
5032 js2-END_DROPS_OFF))
5033 rv))
5034
5035 (defun js2-end-check-try (node)
5036 "If the block has a finally, return consistency is checked in the
5037 finally block. If all code paths in the finally return, then the
5038 returns in the try-catch blocks don't matter. If there is a code path
5039 that does not return or if there is no finally block, the returns
5040 of the try and catch blocks are checked for mismatch.
5041 Returns logical OR of END_* flags."
5042 (let ((finally (js2-try-node-finally-block node))
5043 rv)
5044 ;; check the finally if it exists
5045 (setq rv (if finally
5046 (js2-end-check (js2-finally-node-body finally))
5047 js2-END_DROPS_OFF))
5048 ;; If the finally block always returns, then none of the returns
5049 ;; in the try or catch blocks matter.
5050 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5051 (js2-clear-flag rv js2-END_DROPS_OFF)
5052 ;; examine the try block
5053 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5054 ;; check each catch block
5055 (dolist (cb (js2-try-node-catch-clauses node))
5056 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5057 rv))
5058
5059 (defun js2-end-check-loop (node)
5060 "Return statement in the loop body must be consistent. The default
5061 assumption for any kind of a loop is that it will eventually terminate.
5062 The only exception is a loop with a constant true condition. Code that
5063 follows such a loop is examined only if one can statically determine
5064 that there is a break out of the loop.
5065
5066 for(... ; ... ; ...) {}
5067 for(... in ... ) {}
5068 while(...) { }
5069 do { } while(...)
5070
5071 Returns logical OR of END_* flags."
5072 (let ((rv (js2-end-check (js2-loop-node-body node)))
5073 (condition (cond
5074 ((js2-while-node-p node)
5075 (js2-while-node-condition node))
5076 ((js2-do-node-p node)
5077 (js2-do-node-condition node))
5078 ((js2-for-node-p node)
5079 (js2-for-node-condition node)))))
5080
5081 ;; check to see if the loop condition is always true
5082 (if (and condition
5083 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5084 (js2-clear-flag rv js2-END_DROPS_OFF))
5085
5086 ;; look for effect of breaks
5087 (js2-set-flag rv (js2-node-get-prop node
5088 'CONTROL_BLOCK_PROP
5089 js2-END_UNREACHED))
5090 rv))
5091
5092 (defun js2-end-check-block (node)
5093 "A general block of code is examined statement by statement.
5094 If any statement (even a compound one) returns in all branches, then
5095 subsequent statements are not examined.
5096 Returns logical OR of END_* flags."
5097 (let* ((rv js2-END_DROPS_OFF)
5098 (kids (js2-block-node-kids node))
5099 (n (car kids)))
5100 ;; Check each statment. If the statement can continue onto the next
5101 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5102 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5103 (js2-clear-flag rv js2-END_DROPS_OFF)
5104 (js2-set-flag rv (js2-end-check n))
5105 (setq kids (cdr kids)
5106 n (car kids)))
5107 rv))
5108
5109 (defun js2-end-check-label (node)
5110 "A labeled statement implies that there may be a break to the label.
5111 The function processes the labeled statement and then checks the
5112 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5113 particular label.
5114 Returns logical OR of END_* flags."
5115 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5116 (logior rv (js2-node-get-prop node
5117 'CONTROL_BLOCK_PROP
5118 js2-END_UNREACHED))))
5119
5120 (defun js2-end-check-break (node)
5121 "When a break is encountered annotate the statement being broken
5122 out of by setting its CONTROL_BLOCK_PROP property.
5123 Returns logical OR of END_* flags."
5124 (and (js2-break-node-target node)
5125 (js2-node-set-prop (js2-break-node-target node)
5126 'CONTROL_BLOCK_PROP
5127 js2-END_DROPS_OFF))
5128 js2-END_UNREACHED)
5129
5130 (defun js2-end-check (node)
5131 "Examine the body of a function, doing a basic reachability analysis.
5132 Returns a combination of flags END_* flags that indicate
5133 how the function execution can terminate. These constitute only the
5134 pessimistic set of termination conditions. It is possible that at
5135 runtime certain code paths will never be actually taken. Hence this
5136 analysis will flag errors in cases where there may not be errors.
5137 Returns logical OR of END_* flags"
5138 (let (kid)
5139 (cond
5140 ((js2-break-node-p node)
5141 (js2-end-check-break node))
5142 ((js2-expr-stmt-node-p node)
5143 (if (setq kid (js2-expr-stmt-node-expr node))
5144 (js2-end-check kid)
5145 js2-END_DROPS_OFF))
5146 ((or (js2-continue-node-p node)
5147 (js2-throw-node-p node))
5148 js2-END_UNREACHED)
5149 ((js2-return-node-p node)
5150 (if (setq kid (js2-return-node-retval node))
5151 js2-END_RETURNS_VALUE
5152 js2-END_RETURNS))
5153 ((js2-loop-node-p node)
5154 (js2-end-check-loop node))
5155 ((js2-switch-node-p node)
5156 (js2-end-check-switch node))
5157 ((js2-labeled-stmt-node-p node)
5158 (js2-end-check-label node))
5159 ((js2-if-node-p node)
5160 (js2-end-check-if node))
5161 ((js2-try-node-p node)
5162 (js2-end-check-try node))
5163 ((js2-block-node-p node)
5164 (if (null (js2-block-node-kids node))
5165 js2-END_DROPS_OFF
5166 (js2-end-check-block node)))
5167 ((js2-yield-node-p node)
5168 js2-END_YIELDS)
5169 (t
5170 js2-END_DROPS_OFF))))
5171
5172 (defun js2-always-defined-boolean-p (node)
5173 "Check if NODE always evaluates to true or false in boolean context.
5174 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5175 nor always false."
5176 (let ((tt (js2-node-type node))
5177 num)
5178 (cond
5179 ((or (= tt js2-FALSE) (= tt js2-NULL))
5180 'ALWAYS_FALSE)
5181 ((= tt js2-TRUE)
5182 'ALWAYS_TRUE)
5183 ((= tt js2-NUMBER)
5184 (setq num (js2-number-node-num-value node))
5185 (if (and (not (eq num 0.0e+NaN))
5186 (not (zerop num)))
5187 'ALWAYS_TRUE
5188 'ALWAYS_FALSE))
5189 (t
5190 nil))))
5191
5192 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5193 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5194
5195 (defvar js2-tokens nil
5196 "List of all defined token names.") ; initialized in `js2-token-names'
5197
5198 (defconst js2-token-names
5199 (let* ((names (make-vector js2-num-tokens -1))
5200 (case-fold-search nil) ; only match js2-UPPER_CASE
5201 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5202 (loop for sym in syms
5203 for i from 0
5204 do
5205 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5206 (not (boundp sym)))
5207 (aset names (symbol-value sym) ; code, e.g. 152
5208 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5209 (push sym js2-tokens)))
5210 names)
5211 "Vector mapping int values to token string names, sans `js2-' prefix.")
5212
5213 (defun js2-token-name (tok)
5214 "Return a string name for TOK, a token symbol or code.
5215 Signals an error if it's not a recognized token."
5216 (let ((code tok))
5217 (if (symbolp tok)
5218 (setq code (symbol-value tok)))
5219 (if (eq code -1)
5220 "ERROR"
5221 (if (and (numberp code)
5222 (not (minusp code))
5223 (< code js2-num-tokens))
5224 (aref js2-token-names code)
5225 (error "Invalid token: %s" code)))))
5226
5227 (defsubst js2-token-sym (tok)
5228 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5229 (intern (js2-token-name tok)))
5230
5231 (defconst js2-token-codes
5232 (let ((table (make-hash-table :test 'eq :size 256)))
5233 (loop for name across js2-token-names
5234 for sym = (intern (concat "js2-" name))
5235 do
5236 (puthash sym (symbol-value sym) table))
5237 ;; clean up a few that are "wrong" in Rhino's token codes
5238 (puthash 'js2-DELETE js2-DELPROP table)
5239 table)
5240 "Hashtable mapping token symbols to their bytecodes.")
5241
5242 (defsubst js2-token-code (sym)
5243 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5244 (or (gethash sym js2-token-codes)
5245 (error "Invalid token symbol: %s " sym))) ; signal code bug
5246
5247 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5248 (setq js2-token-end js2-ts-cursor)
5249 (js2-report-error msg nil
5250 (or beg js2-token-beg)
5251 (or len (- js2-token-end js2-token-beg)))
5252 (unless no-throw
5253 (throw 'return js2-ERROR)))
5254
5255 (defsubst js2-get-string-from-buffer ()
5256 "Reverse the char accumulator and return it as a string."
5257 (setq js2-token-end js2-ts-cursor)
5258 (if js2-ts-string-buffer
5259 (apply #'string (nreverse js2-ts-string-buffer))
5260 ""))
5261
5262 ;; TODO: could potentially avoid a lot of consing by allocating a
5263 ;; char buffer the way Rhino does.
5264 (defsubst js2-add-to-string (c)
5265 (push c js2-ts-string-buffer))
5266
5267 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5268 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5269 ;; any other character: when it's not part of the current token, we
5270 ;; unget it, allowing it to be read again by the following call.
5271 (defsubst js2-unget-char ()
5272 (decf js2-ts-cursor))
5273
5274 ;; Rhino distinguishes \r and \n line endings. We don't need to
5275 ;; because we only scan from Emacs buffers, which always use \n.
5276 (defsubst js2-get-char ()
5277 "Read and return the next character from the input buffer.
5278 Increments `js2-ts-lineno' if the return value is a newline char.
5279 Updates `js2-ts-cursor' to the point after the returned char.
5280 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5281 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5282 (let (c)
5283 ;; check for end of buffer
5284 (if (>= js2-ts-cursor (point-max))
5285 (setq js2-ts-hit-eof t
5286 js2-ts-cursor (1+ js2-ts-cursor)
5287 c js2-EOF_CHAR) ; return value
5288 ;; otherwise read next char
5289 (setq c (char-before (incf js2-ts-cursor)))
5290 ;; if we read a newline, update counters
5291 (if (= c ?\n)
5292 (setq js2-ts-line-start js2-ts-cursor
5293 js2-ts-lineno (1+ js2-ts-lineno)))
5294 ;; TODO: skip over format characters
5295 c)))
5296
5297 (defsubst js2-read-unicode-escape ()
5298 "Read a \\uNNNN sequence from the input.
5299 Assumes the ?\ and ?u have already been read.
5300 Returns the unicode character, or nil if it wasn't a valid character.
5301 Doesn't change the values of any scanner variables."
5302 ;; I really wish I knew a better way to do this, but I can't
5303 ;; find the Emacs function that takes a 16-bit int and converts
5304 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5305 ;; Have to first check that it's 4 hex characters or it may stop
5306 ;; the read early.
5307 (ignore-errors
5308 (let ((s (buffer-substring-no-properties js2-ts-cursor
5309 (+ 4 js2-ts-cursor))))
5310 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5311 (read (concat "?\\u" s))))))
5312
5313 (defsubst js2-match-char (test)
5314 "Consume and return next character if it matches TEST, a character.
5315 Returns nil and consumes nothing if TEST is not the next character."
5316 (let ((c (js2-get-char)))
5317 (if (eq c test)
5318 t
5319 (js2-unget-char)
5320 nil)))
5321
5322 (defsubst js2-peek-char ()
5323 (prog1
5324 (js2-get-char)
5325 (js2-unget-char)))
5326
5327 (defsubst js2-java-identifier-start-p (c)
5328 (or
5329 (memq c '(?$ ?_))
5330 (js2-char-uppercase-p c)
5331 (js2-char-lowercase-p c)))
5332
5333 (defsubst js2-java-identifier-part-p (c)
5334 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5335 ;; TODO: make me Unicode-friendly. See comments above.
5336 (or
5337 (memq c '(?$ ?_))
5338 (js2-char-uppercase-p c)
5339 (js2-char-lowercase-p c)
5340 (and (>= c ?0) (<= c ?9))))
5341
5342 (defsubst js2-alpha-p (c)
5343 (cond ((and (<= ?A c) (<= c ?Z)) t)
5344 ((and (<= ?a c) (<= c ?z)) t)
5345 (t nil)))
5346
5347 (defsubst js2-digit-p (c)
5348 (and (<= ?0 c) (<= c ?9)))
5349
5350 (defsubst js2-js-space-p (c)
5351 (if (<= c 127)
5352 (memq c '(#x20 #x9 #xB #xC #xD))
5353 (or
5354 (eq c #xA0)
5355 ;; TODO: change this nil to check for Unicode space character
5356 nil)))
5357
5358 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5359
5360 (defsubst js2-skip-line ()
5361 "Skip to end of line"
5362 (let (c)
5363 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5364 (js2-unget-char)
5365 (setq js2-token-end js2-ts-cursor)))
5366
5367 (defun js2-init-scanner (&optional buf line)
5368 "Create token stream for BUF starting on LINE.
5369 BUF defaults to current-buffer and line defaults to 1.
5370
5371 A buffer can only have one scanner active at a time, which yields
5372 dramatically simpler code than using a defstruct. If you need to
5373 have simultaneous scanners in a buffer, copy the regions to scan
5374 into temp buffers."
5375 (save-excursion
5376 (when buf
5377 (set-buffer buf))
5378 (setq js2-ts-dirty-line nil
5379 js2-ts-regexp-flags nil
5380 js2-ts-string ""
5381 js2-ts-number nil
5382 js2-ts-hit-eof nil
5383 js2-ts-line-start 0
5384 js2-ts-lineno (or line 1)
5385 js2-ts-line-end-char -1
5386 js2-ts-cursor (point-min)
5387 js2-ts-is-xml-attribute nil
5388 js2-ts-xml-is-tag-content nil
5389 js2-ts-xml-open-tags-count 0
5390 js2-ts-string-buffer nil)))
5391
5392 ;; This function uses the cached op, string and number fields in
5393 ;; TokenStream; if getToken has been called since the passed token
5394 ;; was scanned, the op or string printed may be incorrect.
5395 (defun js2-token-to-string (token)
5396 ;; Not sure where this function is used in Rhino. Not tested.
5397 (if (not js2-debug-print-trees)
5398 ""
5399 (let ((name (js2-token-name token)))
5400 (cond
5401 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5402 (concat name " `" js2-ts-string "'"))
5403 ((eq token js2-NUMBER)
5404 (format "NUMBER %g" js2-ts-number))
5405 (t
5406 name)))))
5407
5408 (defconst js2-keywords
5409 '(break
5410 case catch const continue
5411 debugger default delete do
5412 else enum
5413 false finally for function
5414 if in of instanceof import
5415 let
5416 new null
5417 return
5418 switch
5419 this throw true try typeof
5420 var void
5421 while with
5422 yield))
5423
5424 ;; Token names aren't exactly the same as the keywords, unfortunately.
5425 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5426 (defconst js2-kwd-tokens
5427 (let ((table (make-vector js2-num-tokens nil))
5428 (tokens
5429 (list js2-BREAK
5430 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5431 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5432 js2-ELSE
5433 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5434 js2-IF js2-IN js2-OF js2-INSTANCEOF js2-IMPORT
5435 js2-LET
5436 js2-NEW js2-NULL
5437 js2-RETURN
5438 js2-SWITCH
5439 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5440 js2-VAR
5441 js2-WHILE js2-WITH
5442 js2-YIELD)))
5443 (dolist (i tokens)
5444 (aset table i 'font-lock-keyword-face))
5445 (aset table js2-STRING 'font-lock-string-face)
5446 (aset table js2-REGEXP 'font-lock-string-face)
5447 (aset table js2-COMMENT 'font-lock-comment-face)
5448 (aset table js2-THIS 'font-lock-builtin-face)
5449 (aset table js2-VOID 'font-lock-constant-face)
5450 (aset table js2-NULL 'font-lock-constant-face)
5451 (aset table js2-TRUE 'font-lock-constant-face)
5452 (aset table js2-FALSE 'font-lock-constant-face)
5453 table)
5454 "Vector whose values are non-nil for tokens that are keywords.
5455 The values are default faces to use for highlighting the keywords.")
5456
5457 (defconst js2-reserved-words
5458 '(abstract
5459 boolean byte
5460 char class
5461 double
5462 enum export extends
5463 final float
5464 goto
5465 implements import int interface
5466 long
5467 native
5468 package private protected public
5469 short static super synchronized
5470 throws transient
5471 volatile))
5472
5473 (defconst js2-keyword-names
5474 (let ((table (make-hash-table :test 'equal)))
5475 (loop for k in js2-keywords
5476 do (puthash
5477 (symbol-name k) ; instanceof
5478 (intern (concat "js2-"
5479 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5480 table))
5481 table)
5482 "JavaScript keywords by name, mapped to their symbols.")
5483
5484 (defconst js2-reserved-word-names
5485 (let ((table (make-hash-table :test 'equal)))
5486 (loop for k in js2-reserved-words
5487 do
5488 (puthash (symbol-name k) 'js2-RESERVED table))
5489 table)
5490 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5491
5492 (defsubst js2-collect-string (buf)
5493 "Convert BUF, a list of chars, to a string.
5494 Reverses BUF before converting."
5495 (cond
5496 ((stringp buf)
5497 buf)
5498 ((null buf) ; for emacs21 compat
5499 "")
5500 (t
5501 (if buf
5502 (apply #'string (nreverse buf))
5503 ""))))
5504
5505 (defun js2-string-to-keyword (s)
5506 "Return token for S, a string, if S is a keyword or reserved word.
5507 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5508 (or (gethash s js2-keyword-names)
5509 (gethash s js2-reserved-word-names)))
5510
5511 (defsubst js2-ts-set-char-token-bounds ()
5512 "Used when next token is one character."
5513 (setq js2-token-beg (1- js2-ts-cursor)
5514 js2-token-end js2-ts-cursor))
5515
5516 (defsubst js2-ts-return (token)
5517 "Return an N-character TOKEN from `js2-get-token'.
5518 Updates `js2-token-end' accordingly."
5519 (setq js2-token-end js2-ts-cursor)
5520 (throw 'return token))
5521
5522 (defsubst js2-x-digit-to-int (c accumulator)
5523 "Build up a hex number.
5524 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5525 corresponding number. Otherwise return -1."
5526 (catch 'return
5527 (catch 'check
5528 ;; Use 0..9 < A..Z < a..z
5529 (cond
5530 ((<= c ?9)
5531 (decf c ?0)
5532 (if (<= 0 c)
5533 (throw 'check nil)))
5534 ((<= c ?F)
5535 (when (<= ?A c)
5536 (decf c (- ?A 10))
5537 (throw 'check nil)))
5538 ((<= c ?f)
5539 (when (<= ?a c)
5540 (decf c (- ?a 10))
5541 (throw 'check nil))))
5542 (throw 'return -1))
5543 (logior c (lsh accumulator 4))))
5544
5545 (defun js2-get-token ()
5546 "Return next JavaScript token, an int such as js2-RETURN."
5547 (let (c
5548 c1
5549 identifier-start
5550 is-unicode-escape-start
5551 contains-escape
5552 escape-val
5553 escape-start
5554 str
5555 result
5556 base
5557 is-integer
5558 quote-char
5559 val
5560 look-for-slash
5561 continue)
5562 (catch 'return
5563 (while t
5564 ;; Eat whitespace, possibly sensitive to newlines.
5565 (setq continue t)
5566 (while continue
5567 (setq c (js2-get-char))
5568 (cond
5569 ((eq c js2-EOF_CHAR)
5570 (js2-ts-set-char-token-bounds)
5571 (throw 'return js2-EOF))
5572 ((eq c ?\n)
5573 (js2-ts-set-char-token-bounds)
5574 (setq js2-ts-dirty-line nil)
5575 (throw 'return js2-EOL))
5576 ((not (js2-js-space-p c))
5577 (if (/= c ?-) ; in case end of HTML comment
5578 (setq js2-ts-dirty-line t))
5579 (setq continue nil))))
5580 ;; Assume the token will be 1 char - fixed up below.
5581 (js2-ts-set-char-token-bounds)
5582 (when (eq c ?@)
5583 (throw 'return js2-XMLATTR))
5584 ;; identifier/keyword/instanceof?
5585 ;; watch out for starting with a <backslash>
5586 (cond
5587 ((eq c ?\\)
5588 (setq c (js2-get-char))
5589 (if (eq c ?u)
5590 (setq identifier-start t
5591 is-unicode-escape-start t
5592 js2-ts-string-buffer nil)
5593 (setq identifier-start nil)
5594 (js2-unget-char)
5595 (setq c ?\\)))
5596 (t
5597 (when (setq identifier-start (js2-java-identifier-start-p c))
5598 (setq js2-ts-string-buffer nil)
5599 (js2-add-to-string c))))
5600 (when identifier-start
5601 (setq contains-escape is-unicode-escape-start)
5602 (catch 'break
5603 (while t
5604 (if is-unicode-escape-start
5605 ;; strictly speaking we should probably push-back
5606 ;; all the bad characters if the <backslash>uXXXX
5607 ;; sequence is malformed. But since there isn't a
5608 ;; correct context(is there?) for a bad Unicode
5609 ;; escape sequence in an identifier, we can report
5610 ;; an error here.
5611 (progn
5612 (setq escape-val 0)
5613 (dotimes (i 4)
5614 (setq c (js2-get-char)
5615 escape-val (js2-x-digit-to-int c escape-val))
5616 ;; Next check takes care of c < 0 and bad escape
5617 (if (minusp escape-val)
5618 (throw 'break nil)))
5619 (if (minusp escape-val)
5620 (js2-report-scan-error "msg.invalid.escape" t))
5621 (js2-add-to-string escape-val)
5622 (setq is-unicode-escape-start nil))
5623 (setq c (js2-get-char))
5624 (cond
5625 ((eq c ?\\)
5626 (setq c (js2-get-char))
5627 (if (eq c ?u)
5628 (setq is-unicode-escape-start t
5629 contains-escape t)
5630 (js2-report-scan-error "msg.illegal.character" t)))
5631 (t
5632 (if (or (eq c js2-EOF_CHAR)
5633 (not (js2-java-identifier-part-p c)))
5634 (throw 'break nil))
5635 (js2-add-to-string c))))))
5636 (js2-unget-char)
5637 (setq str (js2-get-string-from-buffer))
5638 (unless contains-escape
5639 ;; OPT we shouldn't have to make a string (object!) to
5640 ;; check if it's a keyword.
5641 ;; Return the corresponding token if it's a keyword
5642 (when (setq result (js2-string-to-keyword str))
5643 (if (and (< js2-language-version 170)
5644 (memq result '(js2-LET js2-YIELD)))
5645 ;; LET and YIELD are tokens only in 1.7 and later
5646 (setq result 'js2-NAME))
5647 (if (not (eq result 'js2-RESERVED))
5648 (throw 'return (js2-token-code result)))
5649 (js2-report-warning "msg.reserved.keyword" str)))
5650 ;; If we want to intern these as Rhino does, just use (intern str)
5651 (setq js2-ts-string str)
5652 (throw 'return js2-NAME)) ; end identifier/kwd check
5653 ;; is it a number?
5654 (when (or (js2-digit-p c)
5655 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5656 (setq js2-ts-string-buffer nil
5657 base 10)
5658 (when (eq c ?0)
5659 (setq c (js2-get-char))
5660 (cond
5661 ((or (eq c ?x) (eq c ?X))
5662 (setq base 16)
5663 (setq c (js2-get-char)))
5664 ((js2-digit-p c)
5665 (setq base 8))
5666 (t
5667 (js2-add-to-string ?0))))
5668 (if (eq base 16)
5669 (while (<= 0 (js2-x-digit-to-int c 0))
5670 (js2-add-to-string c)
5671 (setq c (js2-get-char)))
5672 (while (and (<= ?0 c) (<= c ?9))
5673 ;; We permit 08 and 09 as decimal numbers, which
5674 ;; makes our behavior a superset of the ECMA
5675 ;; numeric grammar. We might not always be so
5676 ;; permissive, so we warn about it.
5677 (when (and (eq base 8) (>= c ?8))
5678 (js2-report-warning "msg.bad.octal.literal"
5679 (if (eq c ?8) "8" "9"))
5680 (setq base 10))
5681 (js2-add-to-string c)
5682 (setq c (js2-get-char))))
5683 (setq is-integer t)
5684 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5685 (setq is-integer nil)
5686 (when (eq c ?.)
5687 (loop do
5688 (js2-add-to-string c)
5689 (setq c (js2-get-char))
5690 while (js2-digit-p c)))
5691 (when (memq c '(?e ?E))
5692 (js2-add-to-string c)
5693 (setq c (js2-get-char))
5694 (when (memq c '(?+ ?-))
5695 (js2-add-to-string c)
5696 (setq c (js2-get-char)))
5697 (unless (js2-digit-p c)
5698 (js2-report-scan-error "msg.missing.exponent" t))
5699 (loop do
5700 (js2-add-to-string c)
5701 (setq c (js2-get-char))
5702 while (js2-digit-p c))))
5703 (js2-unget-char)
5704 (setq js2-ts-string (js2-get-string-from-buffer)
5705 js2-ts-number
5706 (if (and (eq base 10) (not is-integer))
5707 (string-to-number js2-ts-string)
5708 ;; TODO: call runtime number-parser. Some of it is in
5709 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5710 (string-to-number js2-ts-string)))
5711 (throw 'return js2-NUMBER))
5712 ;; is it a string?
5713 (when (memq c '(?\" ?\'))
5714 ;; We attempt to accumulate a string the fast way, by
5715 ;; building it directly out of the reader. But if there
5716 ;; are any escaped characters in the string, we revert to
5717 ;; building it out of a string buffer.
5718 (setq quote-char c
5719 js2-ts-string-buffer nil
5720 c (js2-get-char))
5721 (catch 'break
5722 (while (/= c quote-char)
5723 (catch 'continue
5724 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5725 (js2-unget-char)
5726 (setq js2-token-end js2-ts-cursor)
5727 (js2-report-error "msg.unterminated.string.lit")
5728 (throw 'return js2-STRING))
5729 (when (eq c ?\\)
5730 ;; We've hit an escaped character
5731 (setq c (js2-get-char))
5732 (case c
5733 (?b (setq c ?\b))
5734 (?f (setq c ?\f))
5735 (?n (setq c ?\n))
5736 (?r (setq c ?\r))
5737 (?t (setq c ?\t))
5738 (?v (setq c ?\v))
5739 (?u
5740 (setq c1 (js2-read-unicode-escape))
5741 (if js2-parse-ide-mode
5742 (if c1
5743 (progn
5744 ;; just copy the string in IDE-mode
5745 (js2-add-to-string ?\\)
5746 (js2-add-to-string ?u)
5747 (dotimes (i 3)
5748 (js2-add-to-string (js2-get-char)))
5749 (setq c (js2-get-char))) ; added at end of loop
5750 ;; flag it as an invalid escape
5751 (js2-report-warning "msg.invalid.escape"
5752 nil (- js2-ts-cursor 2) 6))
5753 ;; Get 4 hex digits; if the u escape is not
5754 ;; followed by 4 hex digits, use 'u' + the
5755 ;; literal character sequence that follows.
5756 (js2-add-to-string ?u)
5757 (setq escape-val 0)
5758 (dotimes (i 4)
5759 (setq c (js2-get-char)
5760 escape-val (js2-x-digit-to-int c escape-val))
5761 (if (minusp escape-val)
5762 (throw 'continue nil))
5763 (js2-add-to-string c))
5764 ;; prepare for replace of stored 'u' sequence by escape value
5765 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5766 c escape-val)))
5767 (?x
5768 ;; Get 2 hex digits, defaulting to 'x'+literal
5769 ;; sequence, as above.
5770 (setq c (js2-get-char)
5771 escape-val (js2-x-digit-to-int c 0))
5772 (if (minusp escape-val)
5773 (progn
5774 (js2-add-to-string ?x)
5775 (throw 'continue nil))
5776 (setq c1 c
5777 c (js2-get-char)
5778 escape-val (js2-x-digit-to-int c escape-val))
5779 (if (minusp escape-val)
5780 (progn
5781 (js2-add-to-string ?x)
5782 (js2-add-to-string c1)
5783 (throw 'continue nil))
5784 ;; got 2 hex digits
5785 (setq c escape-val))))
5786 (?\n
5787 ;; Remove line terminator after escape to follow
5788 ;; SpiderMonkey and C/C++
5789 (setq c (js2-get-char))
5790 (throw 'continue nil))
5791 (t
5792 (when (and (<= ?0 c) (< c ?8))
5793 (setq val (- c ?0)
5794 c (js2-get-char))
5795 (when (and (<= ?0 c) (< c ?8))
5796 (setq val (- (+ (* 8 val) c) ?0)
5797 c (js2-get-char))
5798 (when (and (<= ?0 c)
5799 (< c ?8)
5800 (< val #o37))
5801 ;; c is 3rd char of octal sequence only
5802 ;; if the resulting val <= 0377
5803 (setq val (- (+ (* 8 val) c) ?0)
5804 c (js2-get-char))))
5805 (js2-unget-char)
5806 (setq c val)))))
5807 (js2-add-to-string c)
5808 (setq c (js2-get-char)))))
5809 (setq js2-ts-string (js2-get-string-from-buffer))
5810 (throw 'return js2-STRING))
5811 (case c
5812 (?\;
5813 (throw 'return js2-SEMI))
5814 (?\[
5815 (throw 'return js2-LB))
5816 (?\]
5817 (throw 'return js2-RB))
5818 (?{
5819 (throw 'return js2-LC))
5820 (?}
5821 (throw 'return js2-RC))
5822 (?\(
5823 (throw 'return js2-LP))
5824 (?\)
5825 (throw 'return js2-RP))
5826 (?,
5827 (throw 'return js2-COMMA))
5828 (??
5829 (throw 'return js2-HOOK))
5830 (?:
5831 (if (js2-match-char ?:)
5832 (js2-ts-return js2-COLONCOLON)
5833 (throw 'return js2-COLON)))
5834 (?.
5835 (if (js2-match-char ?.)
5836 (js2-ts-return js2-DOTDOT)
5837 (if (js2-match-char ?\()
5838 (js2-ts-return js2-DOTQUERY)
5839 (throw 'return js2-DOT))))
5840 (?|
5841 (if (js2-match-char ?|)
5842 (throw 'return js2-OR)
5843 (if (js2-match-char ?=)
5844 (js2-ts-return js2-ASSIGN_BITOR)
5845 (throw 'return js2-BITOR))))
5846 (?^
5847 (if (js2-match-char ?=)
5848 (js2-ts-return js2-ASSIGN_BITOR)
5849 (throw 'return js2-BITXOR)))
5850 (?&
5851 (if (js2-match-char ?&)
5852 (throw 'return js2-AND)
5853 (if (js2-match-char ?=)
5854 (js2-ts-return js2-ASSIGN_BITAND)
5855 (throw 'return js2-BITAND))))
5856 (?=
5857 (if (js2-match-char ?=)
5858 (if (js2-match-char ?=)
5859 (js2-ts-return js2-SHEQ)
5860 (throw 'return js2-EQ))
5861 (throw 'return js2-ASSIGN)))
5862 (?!
5863 (if (js2-match-char ?=)
5864 (if (js2-match-char ?=)
5865 (js2-ts-return js2-SHNE)
5866 (js2-ts-return js2-NE))
5867 (throw 'return js2-NOT)))
5868 (?<
5869 ;; NB:treat HTML begin-comment as comment-till-eol
5870 (when (js2-match-char ?!)
5871 (when (js2-match-char ?-)
5872 (when (js2-match-char ?-)
5873 (js2-skip-line)
5874 (setq js2-ts-comment-type 'html)
5875 (throw 'return js2-COMMENT)))
5876 (js2-unget-char))
5877 (if (js2-match-char ?<)
5878 (if (js2-match-char ?=)
5879 (js2-ts-return js2-ASSIGN_LSH)
5880 (js2-ts-return js2-LSH))
5881 (if (js2-match-char ?=)
5882 (js2-ts-return js2-LE)
5883 (throw 'return js2-LT))))
5884 (?>
5885 (if (js2-match-char ?>)
5886 (if (js2-match-char ?>)
5887 (if (js2-match-char ?=)
5888 (js2-ts-return js2-ASSIGN_URSH)
5889 (js2-ts-return js2-URSH))
5890 (if (js2-match-char ?=)
5891 (js2-ts-return js2-ASSIGN_RSH)
5892 (js2-ts-return js2-RSH)))
5893 (if (js2-match-char ?=)
5894 (js2-ts-return js2-GE)
5895 (throw 'return js2-GT))))
5896 (?*
5897 (if (js2-match-char ?=)
5898 (js2-ts-return js2-ASSIGN_MUL)
5899 (throw 'return js2-MUL)))
5900 (?/
5901 ;; is it a // comment?
5902 (when (js2-match-char ?/)
5903 (setq js2-token-beg (- js2-ts-cursor 2))
5904 (js2-skip-line)
5905 (setq js2-ts-comment-type 'line)
5906 ;; include newline so highlighting goes to end of window
5907 (incf js2-token-end)
5908 (throw 'return js2-COMMENT))
5909 ;; is it a /* comment?
5910 (when (js2-match-char ?*)
5911 (setq look-for-slash nil
5912 js2-token-beg (- js2-ts-cursor 2)
5913 js2-ts-comment-type
5914 (if (js2-match-char ?*)
5915 (progn
5916 (setq look-for-slash t)
5917 'jsdoc)
5918 'block))
5919 (while t
5920 (setq c (js2-get-char))
5921 (cond
5922 ((eq c js2-EOF_CHAR)
5923 (setq js2-token-end (1- js2-ts-cursor))
5924 (js2-report-error "msg.unterminated.comment")
5925 (throw 'return js2-COMMENT))
5926 ((eq c ?*)
5927 (setq look-for-slash t))
5928 ((eq c ?/)
5929 (if look-for-slash
5930 (js2-ts-return js2-COMMENT)))
5931 (t
5932 (setq look-for-slash nil
5933 js2-token-end js2-ts-cursor)))))
5934 (if (js2-match-char ?=)
5935 (js2-ts-return js2-ASSIGN_DIV)
5936 (throw 'return js2-DIV)))
5937 (?#
5938 (when js2-skip-preprocessor-directives
5939 (js2-skip-line)
5940 (setq js2-ts-comment-type 'preprocessor
5941 js2-token-end js2-ts-cursor)
5942 (throw 'return js2-COMMENT))
5943 (throw 'return js2-ERROR))
5944 (?%
5945 (if (js2-match-char ?=)
5946 (js2-ts-return js2-ASSIGN_MOD)
5947 (throw 'return js2-MOD)))
5948 (?~
5949 (throw 'return js2-BITNOT))
5950 (?+
5951 (if (js2-match-char ?=)
5952 (js2-ts-return js2-ASSIGN_ADD)
5953 (if (js2-match-char ?+)
5954 (js2-ts-return js2-INC)
5955 (throw 'return js2-ADD))))
5956 (?-
5957 (cond
5958 ((js2-match-char ?=)
5959 (setq c js2-ASSIGN_SUB))
5960 ((js2-match-char ?-)
5961 (unless js2-ts-dirty-line
5962 ;; treat HTML end-comment after possible whitespace
5963 ;; after line start as comment-until-eol
5964 (when (js2-match-char ?>)
5965 (js2-skip-line)
5966 (setq js2-ts-comment-type 'html)
5967 (throw 'return js2-COMMENT)))
5968 (setq c js2-DEC))
5969 (t
5970 (setq c js2-SUB)))
5971 (setq js2-ts-dirty-line t)
5972 (js2-ts-return c))
5973 (otherwise
5974 (js2-report-scan-error "msg.illegal.character")))))))
5975
5976 (defun js2-read-regexp (start-token)
5977 "Called by parser when it gets / or /= in literal context."
5978 (let (c
5979 err
5980 in-class ; inside a '[' .. ']' character-class
5981 flags
5982 (continue t))
5983 (setq js2-token-beg js2-ts-cursor
5984 js2-ts-string-buffer nil
5985 js2-ts-regexp-flags nil)
5986 (if (eq start-token js2-ASSIGN_DIV)
5987 ;; mis-scanned /=
5988 (js2-add-to-string ?=)
5989 (if (not (eq start-token js2-DIV))
5990 (error "failed assertion")))
5991 (while (and (not err)
5992 (or (/= (setq c (js2-get-char)) ?/)
5993 in-class))
5994 (cond
5995 ((or (= c ?\n)
5996 (= c js2-EOF_CHAR))
5997 (setq js2-token-end (1- js2-ts-cursor)
5998 err t
5999 js2-ts-string (js2-collect-string js2-ts-string-buffer))
6000 (js2-report-error "msg.unterminated.re.lit"))
6001 (t (cond
6002 ((= c ?\\)
6003 (js2-add-to-string c)
6004 (setq c (js2-get-char)))
6005 ((= c ?\[)
6006 (setq in-class t))
6007 ((= c ?\])
6008 (setq in-class nil)))
6009 (js2-add-to-string c))))
6010 (unless err
6011 (while continue
6012 (cond
6013 ((js2-match-char ?g)
6014 (push ?g flags))
6015 ((js2-match-char ?i)
6016 (push ?i flags))
6017 ((js2-match-char ?m)
6018 (push ?m flags))
6019 (t
6020 (setq continue nil))))
6021 (if (js2-alpha-p (js2-peek-char))
6022 (js2-report-scan-error "msg.invalid.re.flag" t
6023 js2-ts-cursor 1))
6024 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6025 js2-ts-regexp-flags (js2-collect-string flags)
6026 js2-token-end js2-ts-cursor)
6027 ;; tell `parse-partial-sexp' to ignore this range of chars
6028 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6029
6030 (defun js2-get-first-xml-token ()
6031 (setq js2-ts-xml-open-tags-count 0
6032 js2-ts-is-xml-attribute nil
6033 js2-ts-xml-is-tag-content nil)
6034 (js2-unget-char)
6035 (js2-get-next-xml-token))
6036
6037 (defsubst js2-xml-discard-string ()
6038 "Throw away the string in progress and flag an XML parse error."
6039 (setq js2-ts-string-buffer nil
6040 js2-ts-string nil)
6041 (js2-report-scan-error "msg.XML.bad.form" t))
6042
6043 (defun js2-get-next-xml-token ()
6044 (setq js2-ts-string-buffer nil ; for recording the XML
6045 js2-token-beg js2-ts-cursor)
6046 (let (c result)
6047 (setq result
6048 (catch 'return
6049 (while t
6050 (setq c (js2-get-char))
6051 (cond
6052 ((= c js2-EOF_CHAR)
6053 (throw 'return js2-ERROR))
6054 (js2-ts-xml-is-tag-content
6055 (case c
6056 (?>
6057 (js2-add-to-string c)
6058 (setq js2-ts-xml-is-tag-content nil
6059 js2-ts-is-xml-attribute nil))
6060 (?/
6061 (js2-add-to-string c)
6062 (when (eq ?> (js2-peek-char))
6063 (setq c (js2-get-char))
6064 (js2-add-to-string c)
6065 (setq js2-ts-xml-is-tag-content nil)
6066 (decf js2-ts-xml-open-tags-count)))
6067 (?{
6068 (js2-unget-char)
6069 (setq js2-ts-string (js2-get-string-from-buffer))
6070 (throw 'return js2-XML))
6071 ((?\' ?\")
6072 (js2-add-to-string c)
6073 (unless (js2-read-quoted-string c)
6074 (throw 'return js2-ERROR)))
6075 (?=
6076 (js2-add-to-string c)
6077 (setq js2-ts-is-xml-attribute t))
6078 ((? ?\t ?\r ?\n)
6079 (js2-add-to-string c))
6080 (t
6081 (js2-add-to-string c)
6082 (setq js2-ts-is-xml-attribute nil)))
6083 (when (and (not js2-ts-xml-is-tag-content)
6084 (zerop js2-ts-xml-open-tags-count))
6085 (setq js2-ts-string (js2-get-string-from-buffer))
6086 (throw 'return js2-XMLEND)))
6087 (t
6088 ;; else not tag content
6089 (case c
6090 (?<
6091 (js2-add-to-string c)
6092 (setq c (js2-peek-char))
6093 (case c
6094 (?!
6095 (setq c (js2-get-char)) ;; skip !
6096 (js2-add-to-string c)
6097 (setq c (js2-peek-char))
6098 (case c
6099 (?-
6100 (setq c (js2-get-char)) ;; skip -
6101 (js2-add-to-string c)
6102 (if (eq c ?-)
6103 (progn
6104 (js2-add-to-string c)
6105 (unless (js2-read-xml-comment)
6106 (throw 'return js2-ERROR)))
6107 (js2-xml-discard-string)
6108 (throw 'return js2-ERROR)))
6109 (?\[
6110 (setq c (js2-get-char)) ;; skip [
6111 (js2-add-to-string c)
6112 (if (and (= (js2-get-char) ?C)
6113 (= (js2-get-char) ?D)
6114 (= (js2-get-char) ?A)
6115 (= (js2-get-char) ?T)
6116 (= (js2-get-char) ?A)
6117 (= (js2-get-char) ?\[))
6118 (progn
6119 (js2-add-to-string ?C)
6120 (js2-add-to-string ?D)
6121 (js2-add-to-string ?A)
6122 (js2-add-to-string ?T)
6123 (js2-add-to-string ?A)
6124 (js2-add-to-string ?\[)
6125 (unless (js2-read-cdata)
6126 (throw 'return js2-ERROR)))
6127 (js2-xml-discard-string)
6128 (throw 'return js2-ERROR)))
6129 (t
6130 (unless (js2-read-entity)
6131 (throw 'return js2-ERROR))))
6132 ;; allow bare CDATA section
6133 ;; ex) let xml = <![CDATA[ foo bar baz ]]>;
6134 (when (zerop js2-ts-xml-open-tags-count)
6135 (throw 'return js2-XMLEND)))
6136 (??
6137 (setq c (js2-get-char)) ;; skip ?
6138 (js2-add-to-string c)
6139 (unless (js2-read-PI)
6140 (throw 'return js2-ERROR)))
6141 (?/
6142 ;; end tag
6143 (setq c (js2-get-char)) ;; skip /
6144 (js2-add-to-string c)
6145 (when (zerop js2-ts-xml-open-tags-count)
6146 (js2-xml-discard-string)
6147 (throw 'return js2-ERROR))
6148 (setq js2-ts-xml-is-tag-content t)
6149 (decf js2-ts-xml-open-tags-count))
6150 (t
6151 ;; start tag
6152 (setq js2-ts-xml-is-tag-content t)
6153 (incf js2-ts-xml-open-tags-count))))
6154 (?{
6155 (js2-unget-char)
6156 (setq js2-ts-string (js2-get-string-from-buffer))
6157 (throw 'return js2-XML))
6158 (t
6159 (js2-add-to-string c))))))))
6160 (setq js2-token-end js2-ts-cursor)
6161 result))
6162
6163 (defun js2-read-quoted-string (quote)
6164 (let (c)
6165 (catch 'return
6166 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6167 (js2-add-to-string c)
6168 (if (eq c quote)
6169 (throw 'return t)))
6170 (js2-xml-discard-string) ;; throw away string in progress
6171 nil)))
6172
6173 (defun js2-read-xml-comment ()
6174 (let ((c (js2-get-char)))
6175 (catch 'return
6176 (while (/= c js2-EOF_CHAR)
6177 (catch 'continue
6178 (js2-add-to-string c)
6179 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6180 (setq c (js2-get-char))
6181 (js2-add-to-string c)
6182 (if (eq (js2-peek-char) ?>)
6183 (progn
6184 (setq c (js2-get-char)) ;; skip >
6185 (js2-add-to-string c)
6186 (throw 'return t))
6187 (throw 'continue nil)))
6188 (setq c (js2-get-char))))
6189 (js2-xml-discard-string)
6190 nil)))
6191
6192 (defun js2-read-cdata ()
6193 (let ((c (js2-get-char)))
6194 (catch 'return
6195 (while (/= c js2-EOF_CHAR)
6196 (catch 'continue
6197 (js2-add-to-string c)
6198 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6199 (setq c (js2-get-char))
6200 (js2-add-to-string c)
6201 (if (eq (js2-peek-char) ?>)
6202 (progn
6203 (setq c (js2-get-char)) ;; Skip >
6204 (js2-add-to-string c)
6205 (throw 'return t))
6206 (throw 'continue nil)))
6207 (setq c (js2-get-char))))
6208 (js2-xml-discard-string)
6209 nil)))
6210
6211 (defun js2-read-entity ()
6212 (let ((decl-tags 1)
6213 c)
6214 (catch 'return
6215 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6216 (js2-add-to-string c)
6217 (case c
6218 (?<
6219 (incf decl-tags))
6220 (?>
6221 (decf decl-tags)
6222 (if (zerop decl-tags)
6223 (throw 'return t)))))
6224 (js2-xml-discard-string)
6225 nil)))
6226
6227 (defun js2-read-PI ()
6228 "Scan an XML processing instruction."
6229 (let (c)
6230 (catch 'return
6231 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6232 (js2-add-to-string c)
6233 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6234 (setq c (js2-get-char)) ;; Skip >
6235 (js2-add-to-string c)
6236 (throw 'return t)))
6237 (js2-xml-discard-string)
6238 nil)))
6239
6240 (defun js2-scanner-get-line ()
6241 "Return the text of the current scan line."
6242 (buffer-substring (point-at-bol) (point-at-eol)))
6243
6244 ;;; Highlighting
6245
6246 (defsubst js2-set-face (beg end face &optional record)
6247 "Fontify a region. If RECORD is non-nil, record for later."
6248 (when (plusp js2-highlight-level)
6249 (setq beg (min (point-max) beg)
6250 beg (max (point-min) beg)
6251 end (min (point-max) end)
6252 end (max (point-min) end))
6253 (if record
6254 (push (list beg end face) js2-mode-fontifications)
6255 (put-text-property beg end 'font-lock-face face))))
6256
6257 (defsubst js2-set-kid-face (pos kid len face)
6258 "Set-face on a child node.
6259 POS is absolute buffer position of parent.
6260 KID is the child node.
6261 LEN is the length to fontify.
6262 FACE is the face to fontify with."
6263 (js2-set-face (+ pos (js2-node-pos kid))
6264 (+ pos (js2-node-pos kid) (js2-node-len kid))
6265 face))
6266
6267 (defsubst js2-fontify-kwd (start length)
6268 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6269
6270 (defsubst js2-clear-face (beg end)
6271 (remove-text-properties beg end '(font-lock-face nil
6272 help-echo nil
6273 point-entered nil
6274 c-in-sws nil)))
6275
6276 (defconst js2-ecma-global-props
6277 (concat "^"
6278 (regexp-opt
6279 '("Infinity" "NaN" "undefined" "arguments") t)
6280 "$")
6281 "Value properties of the Ecma-262 Global Object.
6282 Shown at or above `js2-highlight-level' 2.")
6283
6284 ;; might want to add the name "arguments" to this list?
6285 (defconst js2-ecma-object-props
6286 (concat "^"
6287 (regexp-opt
6288 '("prototype" "__proto__" "__parent__") t)
6289 "$")
6290 "Value properties of the Ecma-262 Object constructor.
6291 Shown at or above `js2-highlight-level' 2.")
6292
6293 (defconst js2-ecma-global-funcs
6294 (concat
6295 "^"
6296 (regexp-opt
6297 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6298 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6299 "$")
6300 "Function properties of the Ecma-262 Global object.
6301 Shown at or above `js2-highlight-level' 2.")
6302
6303 (defconst js2-ecma-number-props
6304 (concat "^"
6305 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6306 "NEGATIVE_INFINITY"
6307 "POSITIVE_INFINITY") t)
6308 "$")
6309 "Properties of the Ecma-262 Number constructor.
6310 Shown at or above `js2-highlight-level' 2.")
6311
6312 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6313 "Properties of the Ecma-262 Date constructor.
6314 Shown at or above `js2-highlight-level' 2.")
6315
6316 (defconst js2-ecma-math-props
6317 (concat "^"
6318 (regexp-opt
6319 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6320 t)
6321 "$")
6322 "Properties of the Ecma-262 Math object.
6323 Shown at or above `js2-highlight-level' 2.")
6324
6325 (defconst js2-ecma-math-funcs
6326 (concat "^"
6327 (regexp-opt
6328 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6329 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6330 "$")
6331 "Function properties of the Ecma-262 Math object.
6332 Shown at or above `js2-highlight-level' 2.")
6333
6334 (defconst js2-ecma-function-props
6335 (concat
6336 "^"
6337 (regexp-opt
6338 '(;; properties of the Object prototype object
6339 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6340 "toLocaleString" "toString" "valueOf"
6341 ;; properties of the Function prototype object
6342 "apply" "call"
6343 ;; properties of the Array prototype object
6344 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6345 "splice" "unshift"
6346 ;; properties of the String prototype object
6347 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6348 "localeCompare" "match" "replace" "search" "split" "substring"
6349 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6350 "toUpperCase"
6351 ;; properties of the Number prototype object
6352 "toExponential" "toFixed" "toPrecision"
6353 ;; properties of the Date prototype object
6354 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6355 "getMinutes" "getMonth" "getSeconds" "getTime"
6356 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6357 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6358 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6359 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6360 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6361 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6362 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6363 "toTimeString" "toUTCString"
6364 ;; properties of the RegExp prototype object
6365 "exec" "test"
6366 ;; properties of the JSON prototype object
6367 "parse" "stringify"
6368 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6369 "toSource" "__defineGetter__" "__defineSetter__"
6370 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6371 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6372 t)
6373 "$")
6374 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6375 Shown at or above `js2-highlight-level' 3.")
6376
6377 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6378 (let ((target-name (and target
6379 (js2-name-node-p target)
6380 (js2-name-node-name target)))
6381 (prop-name (if prop (js2-name-node-name prop)))
6382 (level1 (>= js2-highlight-level 1))
6383 (level2 (>= js2-highlight-level 2))
6384 (level3 (>= js2-highlight-level 3))
6385 pos
6386 face)
6387 (when level2
6388 (if call-p
6389 (cond
6390 ((and target prop)
6391 (cond
6392 ((and level3 (string-match js2-ecma-function-props prop-name))
6393 (setq face 'font-lock-builtin-face))
6394 ((and target-name prop)
6395 (cond
6396 ((string= target-name "Date")
6397 (if (string-match js2-ecma-date-props prop-name)
6398 (setq face 'font-lock-builtin-face)))
6399 ((string= target-name "Math")
6400 (if (string-match js2-ecma-math-funcs prop-name)
6401 (setq face 'font-lock-builtin-face)))))))
6402 (prop
6403 (if (string-match js2-ecma-global-funcs prop-name)
6404 (setq face 'font-lock-builtin-face))))
6405 (cond
6406 ((and target prop)
6407 (cond
6408 ((string= target-name "Number")
6409 (if (string-match js2-ecma-number-props prop-name)
6410 (setq face 'font-lock-constant-face)))
6411 ((string= target-name "Math")
6412 (if (string-match js2-ecma-math-props prop-name)
6413 (setq face 'font-lock-constant-face)))))
6414 (prop
6415 (if (string-match js2-ecma-object-props prop-name)
6416 (setq face 'font-lock-constant-face)))))
6417 (when face
6418 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6419 (js2-node-pos prop))) ; relative
6420 (+ pos (js2-node-len prop))
6421 face 'record)))))
6422
6423 (defun js2-parse-highlight-member-expr-node (node)
6424 "Perform syntax highlighting of EcmaScript built-in properties.
6425 The variable `js2-highlight-level' governs this highighting."
6426 (let (face target prop name pos end parent call-p callee)
6427 (cond
6428 ;; case 1: simple name, e.g. foo
6429 ((js2-name-node-p node)
6430 (setq name (js2-name-node-name node))
6431 ;; possible for name to be nil in rare cases - saw it when
6432 ;; running js2-mode on an elisp buffer. Might as well try to
6433 ;; make it so js2-mode never barfs.
6434 (when name
6435 (setq face (if (string-match js2-ecma-global-props name)
6436 'font-lock-constant-face))
6437 (when face
6438 (setq pos (js2-node-pos node)
6439 end (+ pos (js2-node-len node)))
6440 (js2-set-face pos end face 'record))))
6441 ;; case 2: property access or function call
6442 ((or (js2-prop-get-node-p node)
6443 ;; highlight function call if expr is a prop-get node
6444 ;; or a plain name (i.e. unqualified function call)
6445 (and (setq call-p (js2-call-node-p node))
6446 (setq callee (js2-call-node-target node)) ; separate setq!
6447 (or (js2-prop-get-node-p callee)
6448 (js2-name-node-p callee))))
6449 (setq parent node
6450 node (if call-p callee node))
6451 (if (and call-p (js2-name-node-p callee))
6452 (setq prop callee)
6453 (setq target (js2-prop-get-node-left node)
6454 prop (js2-prop-get-node-right node)))
6455 (cond
6456 ((js2-name-node-p target)
6457 (if (js2-name-node-p prop)
6458 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6459 (js2-parse-highlight-prop-get parent target prop call-p)
6460 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6461 (js2-parse-highlight-prop-get parent target nil call-p)))
6462 ((js2-name-node-p prop)
6463 ;; case 2c: complex target, simple name, e.g. x[y].bar
6464 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6465
6466 (defun js2-parse-highlight-member-expr-fn-name (expr)
6467 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6468 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6469 We currently only handle the case where the last component is a prop-get
6470 of a simple name. Called before EXPR has a parent node."
6471 (let (pos
6472 (name (and (js2-prop-get-node-p expr)
6473 (js2-prop-get-node-right expr))))
6474 (when (js2-name-node-p name)
6475 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6476 (js2-node-pos name)))
6477 (+ pos (js2-node-len name))
6478 'font-lock-function-name-face
6479 'record))))
6480
6481 ;; source: http://jsdoc.sourceforge.net/
6482 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6483 ;; allows type specifications, and needs work before entering the wild.
6484
6485 (defconst js2-jsdoc-param-tag-regexp
6486 (concat "^\\s-*\\*+\\s-*\\(@"
6487 "\\(?:param\\|argument\\)"
6488 "\\)"
6489 "\\s-*\\({[^}]+}\\)?" ; optional type
6490 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6491 "\\>")
6492 "Matches jsdoc tags with optional type and optional param name.")
6493
6494 (defconst js2-jsdoc-typed-tag-regexp
6495 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6496 (regexp-opt
6497 '("enum"
6498 "extends"
6499 "field"
6500 "id"
6501 "implements"
6502 "lends"
6503 "mods"
6504 "requires"
6505 "return"
6506 "returns"
6507 "throw"
6508 "throws"))
6509 "\\)\\)\\s-*\\({[^}]+}\\)?")
6510 "Matches jsdoc tags with optional type.")
6511
6512 (defconst js2-jsdoc-arg-tag-regexp
6513 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6514 (regexp-opt
6515 '("alias"
6516 "augments"
6517 "borrows"
6518 "bug"
6519 "base"
6520 "config"
6521 "default"
6522 "define"
6523 "exception"
6524 "function"
6525 "member"
6526 "memberOf"
6527 "name"
6528 "namespace"
6529 "property"
6530 "since"
6531 "suppress"
6532 "this"
6533 "throws"
6534 "type"
6535 "version"))
6536 "\\)\\)\\s-+\\([^ \t]+\\)")
6537 "Matches jsdoc tags with a single argument.")
6538
6539 (defconst js2-jsdoc-empty-tag-regexp
6540 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6541 (regexp-opt
6542 '("addon"
6543 "author"
6544 "class"
6545 "const"
6546 "constant"
6547 "constructor"
6548 "constructs"
6549 "deprecated"
6550 "desc"
6551 "description"
6552 "event"
6553 "example"
6554 "exec"
6555 "export"
6556 "fileoverview"
6557 "final"
6558 "function"
6559 "hidden"
6560 "ignore"
6561 "implicitCast"
6562 "inheritDoc"
6563 "inner"
6564 "interface"
6565 "license"
6566 "noalias"
6567 "noshadow"
6568 "notypecheck"
6569 "override"
6570 "owner"
6571 "preserve"
6572 "preserveTry"
6573 "private"
6574 "protected"
6575 "public"
6576 "static"
6577 "supported"
6578 ))
6579 "\\)\\)\\s-*")
6580 "Matches empty jsdoc tags.")
6581
6582 (defconst js2-jsdoc-link-tag-regexp
6583 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6584 "Matches a jsdoc link or code tag.")
6585
6586 (defconst js2-jsdoc-see-tag-regexp
6587 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6588 "Matches a jsdoc @see tag.")
6589
6590 (defconst js2-jsdoc-html-tag-regexp
6591 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6592 "Matches a simple (no attributes) html start- or end-tag.")
6593
6594 (defsubst js2-jsdoc-highlight-helper ()
6595 (js2-set-face (match-beginning 1)
6596 (match-end 1)
6597 'js2-jsdoc-tag-face)
6598 (if (match-beginning 2)
6599 (if (save-excursion
6600 (goto-char (match-beginning 2))
6601 (= (char-after) ?{))
6602 (js2-set-face (1+ (match-beginning 2))
6603 (1- (match-end 2))
6604 'js2-jsdoc-type-face)
6605 (js2-set-face (match-beginning 2)
6606 (match-end 2)
6607 'js2-jsdoc-value-face)))
6608 (if (match-beginning 3)
6609 (js2-set-face (match-beginning 3)
6610 (match-end 3)
6611 'js2-jsdoc-value-face)))
6612
6613 (defun js2-highlight-jsdoc (ast)
6614 "Highlight doc comment tags."
6615 (let ((comments (js2-ast-root-comments ast))
6616 beg end)
6617 (save-excursion
6618 (dolist (node comments)
6619 (when (eq (js2-comment-node-format node) 'jsdoc)
6620 (setq beg (js2-node-abs-pos node)
6621 end (+ beg (js2-node-len node)))
6622 (save-restriction
6623 (narrow-to-region beg end)
6624 (dolist (re (list js2-jsdoc-param-tag-regexp
6625 js2-jsdoc-typed-tag-regexp
6626 js2-jsdoc-arg-tag-regexp
6627 js2-jsdoc-link-tag-regexp
6628 js2-jsdoc-see-tag-regexp
6629 js2-jsdoc-empty-tag-regexp))
6630 (goto-char beg)
6631 (while (re-search-forward re nil t)
6632 (js2-jsdoc-highlight-helper)))
6633 ;; simple highlighting for html tags
6634 (goto-char beg)
6635 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6636 (js2-set-face (match-beginning 1)
6637 (match-end 1)
6638 'js2-jsdoc-html-tag-delimiter-face)
6639 (js2-set-face (match-beginning 2)
6640 (match-end 2)
6641 'js2-jsdoc-html-tag-name-face)
6642 (js2-set-face (match-beginning 3)
6643 (match-end 3)
6644 'js2-jsdoc-html-tag-delimiter-face))))))))
6645
6646 (defun js2-highlight-assign-targets (node left right)
6647 "Highlight function properties and external variables."
6648 (let (leftpos end name)
6649 ;; highlight vars and props assigned function values
6650 (when (js2-function-node-p right)
6651 (cond
6652 ;; var foo = function() {...}
6653 ((js2-name-node-p left)
6654 (setq name left))
6655 ;; foo.bar.baz = function() {...}
6656 ((and (js2-prop-get-node-p left)
6657 (js2-name-node-p (js2-prop-get-node-right left)))
6658 (setq name (js2-prop-get-node-right left))))
6659 (when name
6660 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6661 (+ leftpos (js2-node-len name))
6662 'font-lock-function-name-face
6663 'record)))))
6664
6665 (defun js2-record-name-node (node)
6666 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6667 later. NODE must be a name node."
6668 (let (leftpos end)
6669 (push (list node js2-current-scope
6670 (setq leftpos (js2-node-abs-pos node))
6671 (setq end (+ leftpos (js2-node-len node))))
6672 js2-recorded-identifiers)))
6673
6674 (defun js2-highlight-undeclared-vars ()
6675 "After entire parse is finished, look for undeclared variable references.
6676 We have to wait until entire buffer is parsed, since JavaScript permits var
6677 decls to occur after they're used.
6678
6679 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6680 it is considered declared."
6681 (let (name)
6682 (dolist (entry js2-recorded-identifiers)
6683 (destructuring-bind (name-node scope pos end) entry
6684 (setq name (js2-name-node-name name-node))
6685 (unless (or (member name js2-global-externs)
6686 (member name js2-default-externs)
6687 (member name js2-additional-externs)
6688 (js2-get-defining-scope scope name))
6689 (js2-set-face pos end 'js2-external-variable-face 'record)
6690 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6691 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6692 (setq js2-recorded-identifiers nil)))
6693
6694 ;;; IMenu support
6695
6696 ;; We currently only support imenu, but eventually should support speedbar and
6697 ;; possibly other browsing mechanisms.
6698
6699 ;; The basic strategy is to identify function assignment targets of the form
6700 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6701 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6702 ;; for imenu after parsing is finished.
6703
6704 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6705 ;; JavaScript, and the general problem is undecidable. However, several forms
6706 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6707 ;; include:
6708
6709 ;; function foo() -- function declaration
6710 ;; foo = function() -- function expression assigned to variable
6711 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6712 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6713 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6714 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6715 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6716 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6717 ;; function foo() {function bar() {...}} -- nested function
6718 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6719
6720 ;; This list boils down to a few forms that can be combined recursively.
6721 ;; Top-level named function declarations include both the left-hand (name)
6722 ;; and the right-hand (function value) expressions needed to produce an imenu
6723 ;; entry. The other "right-hand" forms we need to look for are:
6724 ;; - functions declared as props/getters/setters in object literals
6725 ;; - nested named function declarations
6726 ;; The "left-hand" expressions that functions can be assigned to include:
6727 ;; - local/global variables
6728 ;; - nested property-get expressions like a.b.c.d
6729 ;; - element gets like foo[10] or foo['bar'] where the index
6730 ;; expression can be trivially converted to a property name. They
6731 ;; effectively then become property gets.
6732
6733 ;; All the different definition types are canonicalized into the form
6734 ;; foo.bar.baz = position-of-function-keyword
6735
6736 ;; We need to build a trie-like structure for imenu. As an example,
6737 ;; consider the following JavaScript code:
6738
6739 ;; a = function() {...} // function at position 5
6740 ;; b = function() {...} // function at position 25
6741 ;; foo = function() {...} // function at position 100
6742 ;; foo.bar = function() {...} // function at position 200
6743 ;; foo.bar.baz = function() {...} // function at position 300
6744 ;; foo.bar.zab = function() {...} // function at position 400
6745
6746 ;; During parsing we accumulate an entry for each definition in
6747 ;; the variable `js2-imenu-recorder', like so:
6748
6749 ;; '((fn a 5)
6750 ;; (fn b 25)
6751 ;; (fn foo 100)
6752 ;; (fn foo bar 200)
6753 ;; (fn foo bar baz 300)
6754 ;; (fn foo bar zab 400))
6755
6756 ;; Where 'fn' is the respective function node.
6757 ;; After parsing these entries are merged into this alist-trie:
6758
6759 ;; '((a . 1)
6760 ;; (b . 2)
6761 ;; (foo (<definition> . 3)
6762 ;; (bar (<definition> . 6)
6763 ;; (baz . 100)
6764 ;; (zab . 200))))
6765
6766 ;; Note the wacky need for a <definition> name. The token can be anything
6767 ;; that isn't a valid JavaScript identifier, because you might make foo
6768 ;; a function and then start setting properties on it that are also functions.
6769
6770 (defsubst js2-prop-node-name (node)
6771 "Return the name of a node that may be a property-get/property-name.
6772 If NODE is not a valid name-node, string-node or integral number-node,
6773 returns nil. Otherwise returns the string name/value of the node."
6774 (cond
6775 ((js2-name-node-p node)
6776 (js2-name-node-name node))
6777 ((js2-string-node-p node)
6778 (js2-string-node-value node))
6779 ((and (js2-number-node-p node)
6780 (string-match "^[0-9]+$" (js2-number-node-value node)))
6781 (js2-number-node-value node))
6782 ((js2-this-node-p node)
6783 "this")))
6784
6785 (defsubst js2-node-qname-component (node)
6786 "Return the name of this node, if it contributes to a qname.
6787 Returns nil if the node doesn't contribute."
6788 (copy-sequence
6789 (or (js2-prop-node-name node)
6790 (if (and (js2-function-node-p node)
6791 (js2-function-node-name node))
6792 (js2-name-node-name (js2-function-node-name node))))))
6793
6794 (defsubst js2-record-imenu-entry (fn-node qname pos)
6795 "Add an entry to `js2-imenu-recorder'.
6796 FN-NODE should be the current item's function node.
6797
6798 Associate FN-NODE with its QNAME for later lookup.
6799 This is used in postprocessing the chain list. For each chain, we find
6800 the parent function, look up its qname, then prepend a copy of it to the chain."
6801 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6802 (unless js2-imenu-function-map
6803 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6804 (puthash fn-node qname js2-imenu-function-map))
6805
6806 (defun js2-record-imenu-functions (node &optional var)
6807 "Record function definitions for imenu.
6808 NODE is a function node or an object literal.
6809 VAR, if non-nil, is the expression that NODE is being assigned to.
6810 When passed arguments of wrong type, does nothing."
6811 (when js2-parse-ide-mode
6812 (let ((fun-p (js2-function-node-p node))
6813 qname left fname-node pos)
6814 (cond
6815 ;; non-anonymous function declaration?
6816 ((and fun-p
6817 (not var)
6818 (setq fname-node (js2-function-node-name node)))
6819 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6820 ;; for remaining forms, compute left-side tree branch first
6821 ((and var (setq qname (js2-compute-nested-prop-get var)))
6822 (cond
6823 ;; foo.bar.baz = function
6824 (fun-p
6825 (js2-record-imenu-entry node qname (js2-node-pos node)))
6826 ;; foo.bar.baz = object-literal
6827 ;; look for nested functions: {a: {b: function() {...} }}
6828 ((js2-object-node-p node)
6829 ;; Node position here is still absolute, since the parser
6830 ;; passes the assignment target and value expressions
6831 ;; to us before they are added as children of the assignment node.
6832 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6833
6834 (defun js2-compute-nested-prop-get (node)
6835 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6836 component nodes as a list. Otherwise return nil. Element-gets are treated
6837 as property-gets if the index expression is a string, or a positive integer."
6838 (let (left right head)
6839 (cond
6840 ((or (js2-name-node-p node)
6841 (js2-this-node-p node))
6842 (list node))
6843 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6844 ((js2-prop-get-node-p node) ; foo.bar
6845 (setq left (js2-prop-get-node-left node)
6846 right (js2-prop-get-node-right node))
6847 (if (setq head (js2-compute-nested-prop-get left))
6848 (nconc head (list right))))
6849 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6850 (setq left (js2-elem-get-node-target node)
6851 right (js2-elem-get-node-element node))
6852 (if (or (js2-string-node-p right) ; ['bar']
6853 (and (js2-number-node-p right) ; [10]
6854 (string-match "^[0-9]+$"
6855 (js2-number-node-value right))))
6856 (if (setq head (js2-compute-nested-prop-get left))
6857 (nconc head (list right))))))))
6858
6859 (defun js2-record-object-literal (node qname pos)
6860 "Recursively process an object literal looking for functions.
6861 NODE is an object literal that is the right-hand child of an assignment
6862 expression. QNAME is a list of nodes representing the assignment target,
6863 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6864 POS is the absolute position of the node.
6865 We do a depth-first traversal of NODE. For any functions we find,
6866 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6867 (let (left right prop-qname)
6868 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6869 (let ((left (js2-infix-node-left e))
6870 ;; Element positions are relative to the parent position.
6871 (pos (+ pos (js2-node-pos e))))
6872 (cond
6873 ;; foo: function() {...}
6874 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6875 (when (js2-prop-node-name left)
6876 ;; As a policy decision, we record the position of the property,
6877 ;; not the position of the `function' keyword, since the property
6878 ;; is effectively the name of the function.
6879 (js2-record-imenu-entry right (append qname (list left)) pos)))
6880 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6881 ((js2-object-node-p right)
6882 (js2-record-object-literal right
6883 (append qname (list (js2-infix-node-left e)))
6884 (+ pos (js2-node-pos right)))))))))
6885
6886 (defsubst js2-node-top-level-decl-p (node)
6887 "Return t if NODE's name is defined in the top-level scope.
6888 Also returns t if NODE's name is not defined in any scope, since it implies
6889 that it's an external variable, which must also be in the top-level scope."
6890 (let* ((name (js2-prop-node-name node))
6891 (this-scope (js2-node-get-enclosing-scope node))
6892 defining-scope)
6893 (cond
6894 ((js2-this-node-p node)
6895 nil)
6896 ((null this-scope)
6897 t)
6898 ((setq defining-scope (js2-get-defining-scope this-scope name))
6899 (js2-ast-root-p defining-scope))
6900 (t t))))
6901
6902 (defsubst js2-wrapper-function-p (node)
6903 "Returns t if NODE is a function expression that's immediately invoked.
6904 NODE must be `js2-function-node'."
6905 (let ((parent (js2-node-parent node)))
6906 (or
6907 ;; function(){...}();
6908 (js2-call-node-p parent)
6909 (and (js2-paren-node-p parent)
6910 ;; (function(){...})();
6911 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6912 ;; (function(){...}).call(this);
6913 (and (js2-prop-get-node-p parent)
6914 (member (js2-name-node-name (js2-prop-get-node-right parent))
6915 '("call" "apply"))
6916 (js2-call-node-p (js2-node-parent parent))))))))
6917
6918 (defun js2-browse-postprocess-chains (entries)
6919 "Modify function-declaration name chains after parsing finishes.
6920 Some of the information is only available after the parse tree is complete.
6921 For instance, processing a nested scope requires a parent function node."
6922 (let (result head fn current-fn parent-qname qname p elem)
6923 (dolist (entry entries)
6924 ;; function node goes first
6925 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6926 ;; Examine head's defining scope:
6927 ;; Pre-processed chain, or top-level/external, keep as-is.
6928 (if (or (stringp head) (js2-node-top-level-decl-p head))
6929 (push chain result)
6930 (when (js2-this-node-p head)
6931 (setq chain (cdr chain))) ; discard this-node
6932 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6933 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6934 (when (eq parent-qname 'not-found)
6935 ;; anonymous function expressions are not recorded
6936 ;; during the parse, so we need to handle this case here
6937 (setq parent-qname
6938 (if (js2-wrapper-function-p fn)
6939 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6940 (if (js2-ast-root-p grandparent)
6941 nil
6942 (gethash grandparent js2-imenu-function-map 'skip)))
6943 'skip))
6944 (puthash fn parent-qname js2-imenu-function-map))
6945 (unless (eq parent-qname 'skip)
6946 ;; prefix parent fn qname to this chain.
6947 (let ((qname (append parent-qname chain)))
6948 (puthash current-fn (butlast qname) js2-imenu-function-map)
6949 (push qname result)))))))
6950 ;; finally replace each node in each chain with its name.
6951 (dolist (chain result)
6952 (setq p chain)
6953 (while p
6954 (if (js2-node-p (setq elem (car p)))
6955 (setcar p (js2-node-qname-component elem)))
6956 (setq p (cdr p))))
6957 result))
6958
6959 ;; Merge name chains into a trie-like tree structure of nested lists.
6960 ;; To simplify construction of the trie, we first build it out using the rule
6961 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6962 ;; [key, num-or-list]. The second element can be a number; if so, this key
6963 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6964 ;; associated with the key at this level.) Otherwise the second element is
6965 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6966 ;; a simple recursive formulation.
6967 ;;
6968 ;; js2-mode is building the data structure for imenu. The imenu documentation
6969 ;; claims that it's the structure above, but in practice it wants the children
6970 ;; at the same list level as the key for that level, which is how I've drawn
6971 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6972 ;; list wrapper around the children at each level.
6973 ;;
6974 ;; A completed nested imenu-alist entry looks like this:
6975 ;; '(("foo"
6976 ;; ("<definition>" . 7)
6977 ;; ("bar"
6978 ;; ("a" . 40)
6979 ;; ("b" . 60))))
6980 ;;
6981 ;; In particular, the documentation for `imenu--index-alist' says that
6982 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6983 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6984
6985 (defun js2-treeify (lst)
6986 "Convert (a b c d) to (a ((b ((c d)))))"
6987 (if (null (cddr lst)) ; list length <= 2
6988 lst
6989 (list (car lst) (list (js2-treeify (cdr lst))))))
6990
6991 (defun js2-build-alist-trie (chains trie)
6992 "Merge declaration name chains into a trie-like alist structure for imenu.
6993 CHAINS is the qname chain list produced during parsing. TRIE is a
6994 list of elements built up so far."
6995 (let (head tail pos branch kids)
6996 (dolist (chain chains)
6997 (setq head (car chain)
6998 tail (cdr chain)
6999 pos (if (numberp (car tail)) (car tail))
7000 branch (js2-find-if (lambda (n)
7001 (string= (car n) head))
7002 trie)
7003 kids (second branch))
7004 (cond
7005 ;; case 1: this key isn't in the trie yet
7006 ((null branch)
7007 (if trie
7008 (setcdr (last trie) (list (js2-treeify chain)))
7009 (setq trie (list (js2-treeify chain)))))
7010 ;; case 2: key is present with a single number entry: replace w/ list
7011 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7012 ;; ("<definition>" 20)))
7013 ((numberp kids)
7014 (setcar (cdr branch)
7015 (list (list "<definition-1>" kids)
7016 (if pos
7017 (list "<definition-2>" pos)
7018 (js2-treeify tail)))))
7019 ;; case 3: key is there (with kids), and we're a number entry
7020 (pos
7021 (setcdr (last kids)
7022 (list
7023 (list (format "<definition-%d>"
7024 (1+ (loop for kid in kids
7025 count (eq ?< (aref (car kid) 0)))))
7026 pos))))
7027 ;; case 4: key is there with kids, need to merge in our chain
7028 (t
7029 (js2-build-alist-trie (list tail) kids))))
7030 trie))
7031
7032 (defun js2-flatten-trie (trie)
7033 "Convert TRIE to imenu-format.
7034 Recurses through nodes, and for each one whose second element is a list,
7035 appends the list's flattened elements to the current element. Also
7036 changes the tails into conses. For instance, this pre-flattened trie
7037
7038 '(a ((b 20)
7039 (c ((d 30)
7040 (e 40)))))
7041
7042 becomes
7043
7044 '(a (b . 20)
7045 (c (d . 30)
7046 (e . 40)))
7047
7048 Note that the root of the trie has no key, just a list of chains.
7049 This is also true for the value of any key with multiple children,
7050 e.g. key 'c' in the example above."
7051 (cond
7052 ((listp (car trie))
7053 (mapcar #'js2-flatten-trie trie))
7054 (t
7055 (if (numberp (second trie))
7056 (cons (car trie) (second trie))
7057 ;; else pop list and append its kids
7058 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7059
7060 (defun js2-build-imenu-index ()
7061 "Turn `js2-imenu-recorder' into an imenu data structure."
7062 (unless (eq js2-imenu-recorder 'empty)
7063 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7064 (result (js2-build-alist-trie chains nil)))
7065 (js2-flatten-trie result))))
7066
7067 (defun js2-test-print-chains (chains)
7068 "Print a list of qname chains.
7069 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7070 i.e. one or more nodes, and an integer position as the list tail."
7071 (mapconcat (lambda (chain)
7072 (concat "("
7073 (mapconcat (lambda (elem)
7074 (if (js2-node-p elem)
7075 (or (js2-node-qname-component elem)
7076 "nil")
7077 (number-to-string elem)))
7078 chain
7079 " ")
7080 ")"))
7081 chains
7082 "\n"))
7083
7084 ;;; Parser
7085
7086 (defconst js2-version "1.8.0"
7087 "Version of JavaScript supported, plus minor js2 version.")
7088
7089 (defmacro js2-record-face (face)
7090 "Record a style run of FACE for the current token."
7091 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7092
7093 (defsubst js2-node-end (n)
7094 "Computes the absolute end of node N.
7095 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7096 is only true until the node is added to its parent; i.e., while parsing."
7097 (+ (js2-node-pos n)
7098 (js2-node-len n)))
7099
7100 (defsubst js2-record-comment ()
7101 "Record a comment in `js2-scanned-comments'."
7102 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7103 :format js2-ts-comment-type)
7104 js2-scanned-comments)
7105 (when js2-parse-ide-mode
7106 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7107 'font-lock-doc-face
7108 'font-lock-comment-face))
7109 (when (memq js2-ts-comment-type '(html preprocessor))
7110 ;; Tell cc-engine the bounds of the comment.
7111 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7112
7113 ;; This function is called depressingly often, so it should be fast.
7114 ;; Most of the time it's looking at the same token it peeked before.
7115 (defsubst js2-peek-token ()
7116 "Returns the next token without consuming it.
7117 If previous token was consumed, calls scanner to get new token.
7118 If previous token was -not- consumed, returns it (idempotent).
7119
7120 This function will not return a newline (js2-EOL) - instead, it
7121 gobbles newlines until it finds a non-newline token, and flags
7122 that token as appearing just after a newline.
7123
7124 This function will also not return a js2-COMMENT. Instead, it
7125 records comments found in `js2-scanned-comments'. If the token
7126 returned by this function immediately follows a jsdoc comment,
7127 the token is flagged as such.
7128
7129 Note that this function always returned the un-flagged token!
7130 The flags, if any, are saved in `js2-current-flagged-token'."
7131 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7132 js2-current-token ; most common case - return already-peeked token
7133 (let ((tt (js2-get-token)) ; call scanner
7134 saw-eol
7135 face)
7136 ;; process comments and whitespace
7137 (while (or (= tt js2-EOL)
7138 (= tt js2-COMMENT))
7139 (if (= tt js2-EOL)
7140 (setq saw-eol t)
7141 (setq saw-eol nil)
7142 (if js2-record-comments
7143 (js2-record-comment)))
7144 (setq tt (js2-get-token))) ; call scanner
7145 (setq js2-current-token tt
7146 js2-current-flagged-token (if saw-eol
7147 (logior tt js2-ti-after-eol)
7148 tt))
7149 ;; perform lexical fontification as soon as token is scanned
7150 (when js2-parse-ide-mode
7151 (cond
7152 ((minusp tt)
7153 (js2-record-face 'js2-error-face))
7154 ((setq face (aref js2-kwd-tokens tt))
7155 (js2-record-face face))
7156 ((and (= tt js2-NAME)
7157 (equal js2-ts-string "undefined"))
7158 (js2-record-face 'font-lock-constant-face))))
7159 tt))) ; return unflagged token
7160
7161 (defsubst js2-peek-flagged-token ()
7162 "Returns the current token along with any flags set for it."
7163 (js2-peek-token)
7164 js2-current-flagged-token)
7165
7166 (defsubst js2-consume-token ()
7167 (setq js2-current-flagged-token js2-EOF))
7168
7169 (defsubst js2-next-token ()
7170 (prog1
7171 (js2-peek-token)
7172 (js2-consume-token)))
7173
7174 (defsubst js2-next-flagged-token ()
7175 (js2-peek-token)
7176 (prog1 js2-current-flagged-token
7177 (js2-consume-token)))
7178
7179 (defsubst js2-match-token (match)
7180 "Consume and return t if next token matches MATCH, a bytecode.
7181 Returns nil and consumes nothing if MATCH is not the next token."
7182 (if (/= (js2-peek-token) match)
7183 nil
7184 (js2-consume-token)
7185 t))
7186
7187 (defsubst js2-valid-prop-name-token (tt)
7188 (or (= tt js2-NAME)
7189 (and js2-allow-keywords-as-property-names
7190 (plusp tt)
7191 (aref js2-kwd-tokens tt))))
7192
7193 (defsubst js2-match-prop-name ()
7194 "Consume token and return t if next token is a valid property name.
7195 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7196 is non-nil and it's a keyword token."
7197 (if (js2-valid-prop-name-token (js2-peek-token))
7198 (progn
7199 (js2-consume-token)
7200 t)
7201 nil))
7202
7203 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7204 (if (js2-match-prop-name)
7205 t
7206 (js2-report-error msg-id nil pos len)
7207 nil))
7208
7209 (defsubst js2-peek-token-or-eol ()
7210 "Return js2-EOL if the current token immediately follows a newline.
7211 Else returns the current token. Used in situations where we don't
7212 consider certain token types valid if they are preceded by a newline.
7213 One example is the postfix ++ or -- operator, which has to be on the
7214 same line as its operand."
7215 (let ((tt (js2-peek-token)))
7216 ;; Check for last peeked token flags
7217 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7218 js2-EOL
7219 tt)))
7220
7221 (defsubst js2-set-check-for-label ()
7222 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7223 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7224
7225 (defsubst js2-must-match (token msg-id &optional pos len)
7226 "Match next token to token code TOKEN, or record a syntax error.
7227 MSG-ID is the error message to report if the match fails.
7228 Returns t on match, nil if no match."
7229 (if (js2-match-token token)
7230 t
7231 (js2-report-error msg-id nil pos len)
7232 nil))
7233
7234 (defsubst js2-inside-function ()
7235 (plusp js2-nesting-of-function))
7236
7237 (defsubst js2-set-requires-activation ()
7238 (if (js2-function-node-p js2-current-script-or-fn)
7239 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7240
7241 (defsubst js2-check-activation-name (name token)
7242 (when (js2-inside-function)
7243 ;; skip language-version 1.2 check from Rhino
7244 (if (or (string= "arguments" name)
7245 (and js2-compiler-activation-names ; only used in codegen
7246 (gethash name js2-compiler-activation-names)))
7247 (js2-set-requires-activation))))
7248
7249 (defsubst js2-set-is-generator ()
7250 (if (js2-function-node-p js2-current-script-or-fn)
7251 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7252
7253 (defsubst js2-must-have-xml ()
7254 (unless js2-compiler-xml-available
7255 (js2-report-error "msg.XML.not.available")))
7256
7257 (defsubst js2-push-scope (scope)
7258 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7259 (assert (js2-scope-p scope))
7260 (assert (null (js2-scope-parent-scope scope)))
7261 (assert (not (eq js2-current-scope scope)))
7262 (setf (js2-scope-parent-scope scope) js2-current-scope
7263 js2-current-scope scope))
7264
7265 (defsubst js2-pop-scope ()
7266 (setq js2-current-scope
7267 (js2-scope-parent-scope js2-current-scope)))
7268
7269 (defsubst js2-enter-loop (loop-node)
7270 (push loop-node js2-loop-set)
7271 (push loop-node js2-loop-and-switch-set)
7272 (js2-push-scope loop-node)
7273 ;; Tell the current labeled statement (if any) its statement,
7274 ;; and set the jump target of the first label to the loop.
7275 ;; These are used in `js2-parse-continue' to verify that the
7276 ;; continue target is an actual labeled loop. (And for codegen.)
7277 (when js2-labeled-stmt
7278 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7279 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7280 js2-labeled-stmt))) loop-node)))
7281
7282 (defsubst js2-exit-loop ()
7283 (pop js2-loop-set)
7284 (pop js2-loop-and-switch-set)
7285 (js2-pop-scope))
7286
7287 (defsubst js2-enter-switch (switch-node)
7288 (push switch-node js2-loop-and-switch-set))
7289
7290 (defsubst js2-exit-switch ()
7291 (pop js2-loop-and-switch-set))
7292
7293 (defun js2-parse (&optional buf cb)
7294 "Tells the js2 parser to parse a region of JavaScript.
7295
7296 BUF is a buffer or buffer name containing the code to parse.
7297 Call `narrow-to-region' first to parse only part of the buffer.
7298
7299 The returned AST root node is given some additional properties:
7300 `node-count' - total number of nodes in the AST
7301 `buffer' - BUF. The buffer it refers to may change or be killed,
7302 so the value is not necessarily reliable.
7303
7304 An optional callback CB can be specified to report parsing
7305 progress. If `(functionp CB)' returns t, it will be called with
7306 the current line number once before parsing begins, then again
7307 each time the lexer reaches a new line number.
7308
7309 CB can also be a list of the form `(symbol cb ...)' to specify
7310 multiple callbacks with different criteria. Each symbol is a
7311 criterion keyword, and the following element is the callback to
7312 call
7313
7314 :line - called whenever the line number changes
7315 :token - called for each new token consumed
7316
7317 The list of criteria could be extended to include entering or
7318 leaving a statement, an expression, or a function definition."
7319 (if (and cb (not (functionp cb)))
7320 (error "criteria callbacks not yet implemented"))
7321 (let ((inhibit-point-motion-hooks t)
7322 (js2-compiler-xml-available (>= js2-language-version 160))
7323 ;; This is a recursive-descent parser, so give it a big stack.
7324 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7325 (max-specpdl-size (max max-specpdl-size 3000))
7326 (case-fold-search nil)
7327 ast)
7328 (message nil) ; clear any error message from previous parse
7329 (save-excursion
7330 (when buf (set-buffer buf))
7331 (setq js2-scanned-comments nil
7332 js2-parsed-errors nil
7333 js2-parsed-warnings nil
7334 js2-imenu-recorder nil
7335 js2-imenu-function-map nil
7336 js2-label-set nil)
7337 (js2-init-scanner)
7338 (setq ast (js2-with-unmodifying-text-property-changes
7339 (js2-do-parse)))
7340 (unless js2-ts-hit-eof
7341 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7342 (setf (js2-ast-root-errors ast) js2-parsed-errors
7343 (js2-ast-root-warnings ast) js2-parsed-warnings)
7344 ;; if we didn't find any declarations, put a dummy in this list so we
7345 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7346 (unless js2-imenu-recorder
7347 (setq js2-imenu-recorder 'empty))
7348 (run-hooks 'js2-parse-finished-hook)
7349 ast)))
7350
7351 ;; Corresponds to Rhino's Parser.parse() method.
7352 (defun js2-do-parse ()
7353 "Parse current buffer starting from current point.
7354 Scanner should be initialized."
7355 (let ((pos js2-ts-cursor)
7356 (end js2-ts-cursor) ; in case file is empty
7357 root n tt)
7358 ;; initialize buffer-local parsing vars
7359 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7360 js2-current-script-or-fn root
7361 js2-current-scope root
7362 js2-current-flagged-token js2-EOF
7363 js2-nesting-of-function 0
7364 js2-labeled-stmt nil
7365 js2-recorded-identifiers nil) ; for js2-highlight
7366 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7367 (if (= tt js2-FUNCTION)
7368 (progn
7369 (js2-consume-token)
7370 (setq n (js2-parse-function (if js2-called-by-compile-function
7371 'FUNCTION_EXPRESSION
7372 'FUNCTION_STATEMENT))))
7373 ;; not a function - parse a statement
7374 (setq n (js2-parse-statement)))
7375 ;; add function or statement to script
7376 (setq end (js2-node-end n))
7377 (js2-block-node-push root n))
7378 ;; add comments to root in lexical order
7379 (when js2-scanned-comments
7380 ;; if we find a comment beyond end of normal kids, use its end
7381 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7382 (dolist (comment js2-scanned-comments)
7383 (push comment (js2-ast-root-comments root))
7384 (js2-node-add-children root comment)))
7385 (setf (js2-node-len root) (- end pos))
7386 ;; Give extensions a chance to muck with things before highlighting starts.
7387 (let ((js2-additional-externs js2-additional-externs))
7388 (dolist (callback js2-post-parse-callbacks)
7389 (funcall callback))
7390 (js2-highlight-undeclared-vars))
7391 root))
7392
7393 (defun js2-function-parser ()
7394 (js2-consume-token)
7395 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7396
7397 (defun js2-parse-function-closure-body (fn-node)
7398 "Parse a JavaScript 1.8 function closure body."
7399 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7400 (if js2-ts-hit-eof
7401 (js2-report-error "msg.no.brace.body" nil
7402 (js2-node-pos fn-node)
7403 (- js2-ts-cursor (js2-node-pos fn-node)))
7404 (js2-node-add-children fn-node
7405 (setf (js2-function-node-body fn-node)
7406 (js2-parse-expr t))))))
7407
7408 (defun js2-parse-function-body (fn-node)
7409 (js2-must-match js2-LC "msg.no.brace.body"
7410 (js2-node-pos fn-node)
7411 (- js2-ts-cursor (js2-node-pos fn-node)))
7412 (let ((pos js2-token-beg) ; LC position
7413 (pn (make-js2-block-node)) ; starts at LC position
7414 tt
7415 end)
7416 (incf js2-nesting-of-function)
7417 (unwind-protect
7418 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7419 (= tt js2-EOF)
7420 (= tt js2-RC)))
7421 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7422 (js2-parse-statement)
7423 (js2-consume-token)
7424 (js2-parse-function 'FUNCTION_STATEMENT))))
7425 (decf js2-nesting-of-function))
7426 (setq end js2-token-end) ; assume no curly and leave at current token
7427 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7428 (setq end js2-token-end))
7429 (setf (js2-node-pos pn) pos
7430 (js2-node-len pn) (- end pos))
7431 (setf (js2-function-node-body fn-node) pn)
7432 (js2-node-add-children fn-node pn)
7433 pn))
7434
7435 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7436 "Declare and fontify destructuring parameters inside NODE.
7437 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7438 (cond
7439 ((js2-name-node-p node)
7440 (let (leftpos)
7441 (js2-define-symbol decl-type (js2-name-node-name node)
7442 node ignore-not-in-block)
7443 (when face
7444 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7445 (+ leftpos (js2-node-len node))
7446 face 'record))))
7447 ((js2-object-node-p node)
7448 (dolist (elem (js2-object-node-elems node))
7449 (js2-define-destruct-symbols
7450 (if (js2-object-prop-node-p elem)
7451 (js2-object-prop-node-right elem)
7452 ;; abbreviated destructuring {a, b}
7453 elem)
7454 decl-type face ignore-not-in-block)))
7455 ((js2-array-node-p node)
7456 (dolist (elem (js2-array-node-elems node))
7457 (when elem
7458 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7459 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7460 (js2-node-len node)))))
7461
7462 (defun js2-parse-function-params (fn-node pos)
7463 (if (js2-match-token js2-RP)
7464 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7465 (let (params len param)
7466 (loop for tt = (js2-peek-token)
7467 do
7468 (cond
7469 ;; destructuring param
7470 ((or (= tt js2-LB) (= tt js2-LC))
7471 (setq param (js2-parse-primary-expr-lhs))
7472 (js2-define-destruct-symbols param
7473 js2-LP
7474 'js2-function-param-face)
7475 (push param params))
7476 ;; simple name
7477 (t
7478 (js2-must-match js2-NAME "msg.no.parm")
7479 (js2-record-face 'js2-function-param-face)
7480 (setq param (js2-create-name-node))
7481 (js2-define-symbol js2-LP js2-ts-string param)
7482 (push param params)))
7483 while
7484 (js2-match-token js2-COMMA))
7485 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7486 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7487 (dolist (p params)
7488 (js2-node-add-children fn-node p)
7489 (push p (js2-function-node-params fn-node))))))
7490
7491 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7492 "Possibly show inconsistent-return warning.
7493 Last token scanned is the close-curly for the function body."
7494 (when (and js2-mode-show-strict-warnings
7495 js2-strict-inconsistent-return-warning
7496 (not (js2-has-consistent-return-usage
7497 (js2-function-node-body fn-node))))
7498 ;; Have it extend from close-curly to bol or beginning of block.
7499 (let ((pos (save-excursion
7500 (goto-char js2-token-end)
7501 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7502 (point-at-bol))))
7503 (end js2-token-end))
7504 (if (plusp (js2-name-node-length name))
7505 (js2-add-strict-warning "msg.no.return.value"
7506 (js2-name-node-name name) pos end)
7507 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7508
7509 (defun js2-parse-function (function-type)
7510 "Function parser. FUNCTION-TYPE is a symbol."
7511 (let ((pos js2-token-beg) ; start of 'function' keyword
7512 name
7513 name-beg
7514 name-end
7515 fn-node
7516 lp
7517 (synthetic-type function-type)
7518 member-expr-node)
7519 ;; parse function name, expression, or non-name (anonymous)
7520 (cond
7521 ;; function foo(...)
7522 ((js2-match-token js2-NAME)
7523 (setq name (js2-create-name-node t)
7524 name-beg js2-token-beg
7525 name-end js2-token-end)
7526 (unless (js2-match-token js2-LP)
7527 (when js2-allow-member-expr-as-function-name
7528 ;; function foo.bar(...)
7529 (setq member-expr-node name
7530 name nil
7531 member-expr-node (js2-parse-member-expr-tail
7532 nil member-expr-node)))
7533 (js2-must-match js2-LP "msg.no.paren.parms")))
7534 ((js2-match-token js2-LP)
7535 nil) ; anonymous function: leave name as null
7536 (t
7537 ;; function random-member-expr(...)
7538 (when js2-allow-member-expr-as-function-name
7539 ;; Note that memberExpr can not start with '(' like
7540 ;; in function (1+2).toString(), because 'function (' already
7541 ;; processed as anonymous function
7542 (setq member-expr-node (js2-parse-member-expr)))
7543 (js2-must-match js2-LP "msg.no.paren.parms")))
7544 (if (= js2-current-token js2-LP) ; eventually matched LP?
7545 (setq lp js2-token-beg))
7546 (if member-expr-node
7547 (progn
7548 (setq synthetic-type 'FUNCTION_EXPRESSION)
7549 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7550 (if name
7551 (js2-set-face name-beg name-end
7552 'font-lock-function-name-face 'record)))
7553 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7554 (plusp (js2-name-node-length name)))
7555 ;; Function statements define a symbol in the enclosing scope
7556 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7557 (setf fn-node (make-js2-function-node :pos pos
7558 :name name
7559 :form function-type
7560 :lp (if lp (- lp pos))))
7561 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7562 ;; 1. Nested functions are not affected by the dynamic scope flag
7563 ;; as dynamic scope is already a parent of their scope.
7564 ;; 2. Functions defined under the with statement also immune to
7565 ;; this setup, in which case dynamic scope is ignored in favor
7566 ;; of the with object.
7567 (setf (js2-function-node-ignore-dynamic fn-node) t))
7568 ;; dynamically bind all the per-function variables
7569 (let ((js2-current-script-or-fn fn-node)
7570 (js2-current-scope fn-node)
7571 (js2-nesting-of-with 0)
7572 (js2-end-flags 0)
7573 js2-label-set
7574 js2-loop-set
7575 js2-loop-and-switch-set)
7576 (js2-parse-function-params fn-node pos)
7577 (if (and (>= js2-language-version 180)
7578 (/= (js2-peek-token) js2-LC))
7579 (js2-parse-function-closure-body fn-node)
7580 (js2-parse-function-body fn-node))
7581 (if name
7582 (js2-node-add-children fn-node name))
7583 (js2-check-inconsistent-return-warning fn-node name)
7584 ;; Function expressions define a name only in the body of the
7585 ;; function, and only if not hidden by a parameter name
7586 (if (and name
7587 (eq synthetic-type 'FUNCTION_EXPRESSION)
7588 (null (js2-scope-get-symbol js2-current-scope
7589 (js2-name-node-name name))))
7590 (js2-define-symbol js2-FUNCTION
7591 (js2-name-node-name name)
7592 fn-node))
7593 (if (and name
7594 (not (eq function-type 'FUNCTION_EXPRESSION)))
7595 (js2-record-imenu-functions fn-node)))
7596 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7597 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7598 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7599 ;; We wait until after parsing the function to set its parent scope,
7600 ;; since `js2-define-symbol' needs the defining-scope check to stop
7601 ;; at the function boundary when checking for redeclarations.
7602 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7603 fn-node))
7604
7605 (defun js2-parse-statements (&optional parent)
7606 "Parse a statement list. Last token consumed must be js2-LC.
7607
7608 PARENT can be a `js2-block-node', in which case the statements are
7609 appended to PARENT. Otherwise a new `js2-block-node' is created
7610 and returned.
7611
7612 This function does not match the closing js2-RC: the caller
7613 matches the RC so it can provide a suitable error message if not
7614 matched. This means it's up to the caller to set the length of
7615 the node to include the closing RC. The node start pos is set to
7616 the absolute buffer start position, and the caller should fix it
7617 up to be relative to the parent node. All children of this block
7618 node are given relative start positions and correct lengths."
7619 (let ((pn (or parent (make-js2-block-node)))
7620 tt)
7621 (setf (js2-node-pos pn) js2-token-beg)
7622 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7623 (/= tt js2-RC))
7624 (js2-block-node-push pn (js2-parse-statement)))
7625 pn))
7626
7627 (defun js2-parse-statement ()
7628 (let (tt pn beg end)
7629 ;; coarse-grained user-interrupt check - needs work
7630 (and js2-parse-interruptable-p
7631 (zerop (% (incf js2-parse-stmt-count)
7632 js2-statements-per-pause))
7633 (input-pending-p)
7634 (throw 'interrupted t))
7635 (setq pn (js2-statement-helper))
7636 ;; no-side-effects warning check
7637 (unless (js2-node-has-side-effects pn)
7638 (setq end (js2-node-end pn))
7639 (save-excursion
7640 (goto-char end)
7641 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7642 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7643 pn))
7644
7645 ;; These correspond to the switch cases in Parser.statementHelper
7646 (defconst js2-parsers
7647 (let ((parsers (make-vector js2-num-tokens
7648 #'js2-parse-expr-stmt)))
7649 (aset parsers js2-BREAK #'js2-parse-break)
7650 (aset parsers js2-CONST #'js2-parse-const-var)
7651 (aset parsers js2-CONTINUE #'js2-parse-continue)
7652 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7653 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7654 (aset parsers js2-DO #'js2-parse-do)
7655 (aset parsers js2-FOR #'js2-parse-for)
7656 (aset parsers js2-FUNCTION #'js2-function-parser)
7657 (aset parsers js2-IF #'js2-parse-if)
7658 (aset parsers js2-LC #'js2-parse-block)
7659 (aset parsers js2-LET #'js2-parse-let-stmt)
7660 (aset parsers js2-NAME #'js2-parse-name-or-label)
7661 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7662 (aset parsers js2-SEMI #'js2-parse-semi)
7663 (aset parsers js2-SWITCH #'js2-parse-switch)
7664 (aset parsers js2-THROW #'js2-parse-throw)
7665 (aset parsers js2-TRY #'js2-parse-try)
7666 (aset parsers js2-VAR #'js2-parse-const-var)
7667 (aset parsers js2-WHILE #'js2-parse-while)
7668 (aset parsers js2-WITH #'js2-parse-with)
7669 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7670 parsers)
7671 "A vector mapping token types to parser functions.")
7672
7673 (defsubst js2-parse-warn-missing-semi (beg end)
7674 (and js2-mode-show-strict-warnings
7675 js2-strict-missing-semi-warning
7676 (js2-add-strict-warning
7677 "msg.missing.semi" nil
7678 ;; back up to beginning of statement or line
7679 (max beg (save-excursion
7680 (goto-char end)
7681 (point-at-bol)))
7682 end)))
7683
7684 (defconst js2-no-semi-insertion
7685 (list js2-IF
7686 js2-SWITCH
7687 js2-WHILE
7688 js2-DO
7689 js2-FOR
7690 js2-TRY
7691 js2-WITH
7692 js2-LC
7693 js2-ERROR
7694 js2-SEMI
7695 js2-FUNCTION)
7696 "List of tokens that don't do automatic semicolon insertion.")
7697
7698 (defconst js2-autoinsert-semi-and-warn
7699 (list js2-ERROR js2-EOF js2-RC))
7700
7701 (defun js2-statement-helper ()
7702 (let* ((tt (js2-peek-token))
7703 (first-tt tt)
7704 (beg js2-token-beg)
7705 (parser (if (= tt js2-ERROR)
7706 #'js2-parse-semi
7707 (aref js2-parsers tt)))
7708 pn
7709 tt-flagged)
7710 ;; If the statement is set, then it's been told its label by now.
7711 (and js2-labeled-stmt
7712 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7713 (setq js2-labeled-stmt nil))
7714 (setq pn (funcall parser))
7715 ;; Don't do auto semi insertion for certain statement types.
7716 (unless (or (memq first-tt js2-no-semi-insertion)
7717 (js2-labeled-stmt-node-p pn))
7718 (js2-auto-insert-semicolon pn))
7719 pn))
7720
7721 (defun js2-auto-insert-semicolon (pn)
7722 (let* ((tt-flagged (js2-peek-flagged-token))
7723 (tt (logand tt-flagged js2-clear-ti-mask))
7724 (pos (js2-node-pos pn)))
7725 (cond
7726 ((= tt js2-SEMI)
7727 ;; Consume ';' as a part of expression
7728 (js2-consume-token)
7729 ;; extend the node bounds to include the semicolon.
7730 (setf (js2-node-len pn) (- js2-token-end pos)))
7731 ((memq tt js2-autoinsert-semi-and-warn)
7732 ;; Autoinsert ;
7733 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7734 (t
7735 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7736 ;; Report error if no EOL or autoinsert ';' otherwise
7737 (js2-report-error "msg.no.semi.stmt")
7738 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7739
7740 (defun js2-parse-condition ()
7741 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7742 The parens are discarded and the expression node is returned.
7743 The `pos' field of the return value is set to an absolute position
7744 that must be fixed up by the caller.
7745 Return value is a list (EXPR LP RP), with absolute paren positions."
7746 (let (pn lp rp)
7747 (if (js2-must-match js2-LP "msg.no.paren.cond")
7748 (setq lp js2-token-beg))
7749 (setq pn (js2-parse-expr))
7750 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7751 (setq rp js2-token-beg))
7752 ;; Report strict warning on code like "if (a = 7) ..."
7753 (if (and js2-strict-cond-assign-warning
7754 (js2-assign-node-p pn))
7755 (js2-add-strict-warning "msg.equal.as.assign" nil
7756 (js2-node-pos pn)
7757 (+ (js2-node-pos pn)
7758 (js2-node-len pn))))
7759 (list pn lp rp)))
7760
7761 (defun js2-parse-if ()
7762 "Parser for if-statement. Last matched token must be js2-IF."
7763 (let ((pos js2-token-beg)
7764 cond
7765 if-true
7766 if-false
7767 else-pos
7768 end
7769 pn)
7770 (js2-consume-token)
7771 (setq cond (js2-parse-condition)
7772 if-true (js2-parse-statement)
7773 if-false (if (js2-match-token js2-ELSE)
7774 (progn
7775 (setq else-pos (- js2-token-beg pos))
7776 (js2-parse-statement)))
7777 end (js2-node-end (or if-false if-true))
7778 pn (make-js2-if-node :pos pos
7779 :len (- end pos)
7780 :condition (car cond)
7781 :then-part if-true
7782 :else-part if-false
7783 :else-pos else-pos
7784 :lp (js2-relpos (second cond) pos)
7785 :rp (js2-relpos (third cond) pos)))
7786 (js2-node-add-children pn (car cond) if-true if-false)
7787 pn))
7788
7789 (defun js2-parse-switch ()
7790 "Parser for if-statement. Last matched token must be js2-SWITCH."
7791 (let ((pos js2-token-beg)
7792 tt
7793 pn
7794 discriminant
7795 has-default
7796 case-expr
7797 case-node
7798 case-pos
7799 cases
7800 stmt
7801 lp
7802 rp)
7803 (js2-consume-token)
7804 (if (js2-must-match js2-LP "msg.no.paren.switch")
7805 (setq lp js2-token-beg))
7806 (setq discriminant (js2-parse-expr)
7807 pn (make-js2-switch-node :discriminant discriminant
7808 :pos pos
7809 :lp (js2-relpos lp pos)))
7810 (js2-node-add-children pn discriminant)
7811 (js2-enter-switch pn)
7812 (unwind-protect
7813 (progn
7814 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7815 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7816 (js2-must-match js2-LC "msg.no.brace.switch")
7817 (catch 'break
7818 (while t
7819 (setq tt (js2-next-token)
7820 case-pos js2-token-beg)
7821 (cond
7822 ((= tt js2-RC)
7823 (setf (js2-node-len pn) (- js2-token-end pos))
7824 (throw 'break nil)) ; done
7825 ((= tt js2-CASE)
7826 (setq case-expr (js2-parse-expr))
7827 (js2-must-match js2-COLON "msg.no.colon.case"))
7828 ((= tt js2-DEFAULT)
7829 (if has-default
7830 (js2-report-error "msg.double.switch.default"))
7831 (setq has-default t
7832 case-expr nil)
7833 (js2-must-match js2-COLON "msg.no.colon.case"))
7834 (t
7835 (js2-report-error "msg.bad.switch")
7836 (throw 'break nil)))
7837 (setq case-node (make-js2-case-node :pos case-pos
7838 :len (- js2-token-end case-pos)
7839 :expr case-expr))
7840 (js2-node-add-children case-node case-expr)
7841 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7842 (/= tt js2-CASE)
7843 (/= tt js2-DEFAULT)
7844 (/= tt js2-EOF))
7845 (setf stmt (js2-parse-statement)
7846 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7847 (js2-block-node-push case-node stmt))
7848 (push case-node cases)))
7849 ;; add cases last, as pushing reverses the order to be correct
7850 (dolist (kid cases)
7851 (js2-node-add-children pn kid)
7852 (push kid (js2-switch-node-cases pn)))
7853 pn) ; return value
7854 (js2-exit-switch))))
7855
7856 (defun js2-parse-while ()
7857 "Parser for while-statement. Last matched token must be js2-WHILE."
7858 (let ((pos js2-token-beg)
7859 (pn (make-js2-while-node))
7860 cond
7861 body)
7862 (js2-consume-token)
7863 (js2-enter-loop pn)
7864 (unwind-protect
7865 (progn
7866 (setf cond (js2-parse-condition)
7867 (js2-while-node-condition pn) (car cond)
7868 body (js2-parse-statement)
7869 (js2-while-node-body pn) body
7870 (js2-node-len pn) (- (js2-node-end body) pos)
7871 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7872 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7873 (js2-node-add-children pn body (car cond)))
7874 (js2-exit-loop))
7875 pn))
7876
7877 (defun js2-parse-do ()
7878 "Parser for do-statement. Last matched token must be js2-DO."
7879 (let ((pos js2-token-beg)
7880 (pn (make-js2-do-node))
7881 cond
7882 body
7883 end)
7884 (js2-consume-token)
7885 (js2-enter-loop pn)
7886 (unwind-protect
7887 (progn
7888 (setq body (js2-parse-statement))
7889 (js2-must-match js2-WHILE "msg.no.while.do")
7890 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7891 cond (js2-parse-condition)
7892 (js2-do-node-condition pn) (car cond)
7893 (js2-do-node-body pn) body
7894 end js2-ts-cursor
7895 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7896 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7897 (js2-node-add-children pn (car cond) body))
7898 (js2-exit-loop))
7899 ;; Always auto-insert semicolon to follow SpiderMonkey:
7900 ;; It is required by ECMAScript but is ignored by the rest of
7901 ;; world; see bug 238945
7902 (if (js2-match-token js2-SEMI)
7903 (setq end js2-ts-cursor))
7904 (setf (js2-node-len pn) (- end pos))
7905 pn))
7906
7907 (defun js2-parse-for ()
7908 "Parser for for-statement. Last matched token must be js2-FOR.
7909 Parses for, for-in, and for each-in statements."
7910 (let ((for-pos js2-token-beg)
7911 pn
7912 is-for-each
7913 is-for-in-or-of
7914 is-for-of
7915 in-pos
7916 each-pos
7917 tmp-pos
7918 init ; Node init is also foo in 'foo in object'
7919 cond ; Node cond is also object in 'foo in object'
7920 incr ; 3rd section of for-loop initializer
7921 body
7922 tt
7923 lp
7924 rp)
7925 (js2-consume-token)
7926 ;; See if this is a for each () instead of just a for ()
7927 (when (js2-match-token js2-NAME)
7928 (if (string= "each" js2-ts-string)
7929 (progn
7930 (setq is-for-each t
7931 each-pos (- js2-token-beg for-pos)) ; relative
7932 (js2-record-face 'font-lock-keyword-face))
7933 (js2-report-error "msg.no.paren.for")))
7934 (if (js2-must-match js2-LP "msg.no.paren.for")
7935 (setq lp (- js2-token-beg for-pos)))
7936 (setq tt (js2-peek-token))
7937 ;; 'for' makes local scope
7938 (js2-push-scope (make-js2-scope))
7939 (unwind-protect
7940 ;; parse init clause
7941 (let ((js2-in-for-init t)) ; set as dynamic variable
7942 (cond
7943 ((= tt js2-SEMI)
7944 (setq init (make-js2-empty-expr-node)))
7945 ((or (= tt js2-VAR) (= tt js2-LET))
7946 (js2-consume-token)
7947 (setq init (js2-parse-variables tt js2-token-beg)))
7948 (t
7949 (setq init (js2-parse-expr)))))
7950 (if (or (js2-match-token js2-IN)
7951 (and (>= js2-language-version 200)
7952 (js2-match-token js2-OF)
7953 (setq is-for-of t)))
7954 (setq is-for-in-or-of t
7955 in-pos (- js2-token-beg for-pos)
7956 ;; scope of iteration target object is not the scope we've created above.
7957 ;; stash current scope temporary.
7958 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7959 (js2-parse-expr))) ; object over which we're iterating
7960 ;; else ordinary for loop - parse cond and incr
7961 (js2-must-match js2-SEMI "msg.no.semi.for")
7962 (setq cond (if (= (js2-peek-token) js2-SEMI)
7963 (make-js2-empty-expr-node) ; no loop condition
7964 (js2-parse-expr)))
7965 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7966 (setq tmp-pos js2-token-end
7967 incr (if (= (js2-peek-token) js2-RP)
7968 (make-js2-empty-expr-node :pos tmp-pos)
7969 (js2-parse-expr))))
7970 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7971 (setq rp (- js2-token-beg for-pos)))
7972 (if (not is-for-in-or-of)
7973 (setq pn (make-js2-for-node :init init
7974 :condition cond
7975 :update incr
7976 :lp lp
7977 :rp rp))
7978 ;; cond could be null if 'in obj' got eaten by the init node.
7979 (if (js2-infix-node-p init)
7980 ;; it was (foo in bar) instead of (var foo in bar)
7981 (setq cond (js2-infix-node-right init)
7982 init (js2-infix-node-left init))
7983 (if (and (js2-var-decl-node-p init)
7984 (> (length (js2-var-decl-node-kids init)) 1))
7985 (js2-report-error "msg.mult.index")))
7986 (setq pn (make-js2-for-in-node :iterator init
7987 :object cond
7988 :in-pos in-pos
7989 :foreach-p is-for-each
7990 :each-pos each-pos
7991 :forof-p is-for-of
7992 :lp lp
7993 :rp rp)))
7994 (unwind-protect
7995 (progn
7996 (js2-enter-loop pn)
7997 ;; We have to parse the body -after- creating the loop node,
7998 ;; so that the loop node appears in the js2-loop-set, allowing
7999 ;; break/continue statements to find the enclosing loop.
8000 (setf body (js2-parse-statement)
8001 (js2-loop-node-body pn) body
8002 (js2-node-pos pn) for-pos
8003 (js2-node-len pn) (- (js2-node-end body) for-pos))
8004 (js2-node-add-children pn init cond incr body))
8005 ;; finally
8006 (js2-exit-loop))
8007 (js2-pop-scope))
8008 pn))
8009
8010 (defun js2-parse-try ()
8011 "Parser for try-statement. Last matched token must be js2-TRY."
8012 (let ((try-pos js2-token-beg)
8013 try-end
8014 try-block
8015 catch-blocks
8016 finally-block
8017 saw-default-catch
8018 peek
8019 param
8020 catch-cond
8021 catch-node
8022 guard-kwd
8023 catch-pos
8024 finally-pos
8025 pn
8026 block
8027 lp
8028 rp)
8029 (js2-consume-token)
8030 (if (/= (js2-peek-token) js2-LC)
8031 (js2-report-error "msg.no.brace.try"))
8032 (setq try-block (js2-parse-statement)
8033 try-end (js2-node-end try-block)
8034 peek (js2-peek-token))
8035 (cond
8036 ((= peek js2-CATCH)
8037 (while (js2-match-token js2-CATCH)
8038 (setq catch-pos js2-token-beg
8039 guard-kwd nil
8040 catch-cond nil
8041 lp nil
8042 rp nil)
8043 (if saw-default-catch
8044 (js2-report-error "msg.catch.unreachable"))
8045 (if (js2-must-match js2-LP "msg.no.paren.catch")
8046 (setq lp (- js2-token-beg catch-pos)))
8047 (js2-push-scope (make-js2-scope))
8048 (let ((tt (js2-peek-token)))
8049 (cond
8050 ;; destructuring pattern
8051 ;; catch ({ message, file }) { ... }
8052 ((or (= tt js2-LB) (= tt js2-LC))
8053 (setq param
8054 (js2-define-destruct-symbols (js2-parse-primary-expr-lhs)
8055 js2-LET nil)))
8056 ;; simple name
8057 (t
8058 (js2-must-match js2-NAME "msg.bad.catchcond")
8059 (setq param (js2-create-name-node))
8060 (js2-define-symbol js2-LET js2-ts-string param))))
8061 ;; pattern guard
8062 (if (js2-match-token js2-IF)
8063 (setq guard-kwd (- js2-token-beg catch-pos)
8064 catch-cond (js2-parse-expr))
8065 (setq saw-default-catch t))
8066 (if (js2-must-match js2-RP "msg.bad.catchcond")
8067 (setq rp (- js2-token-beg catch-pos)))
8068 (js2-must-match js2-LC "msg.no.brace.catchblock")
8069 (setq block (js2-parse-statements)
8070 try-end (js2-node-end block)
8071 catch-node (make-js2-catch-node :pos catch-pos
8072 :param param
8073 :guard-expr catch-cond
8074 :guard-kwd guard-kwd
8075 :block block
8076 :lp lp
8077 :rp rp))
8078 (js2-pop-scope)
8079 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8080 (setq try-end js2-token-beg))
8081 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8082 (js2-node-len catch-node) (- try-end catch-pos))
8083 (js2-node-add-children catch-node param catch-cond block)
8084 (push catch-node catch-blocks)))
8085 ((/= peek js2-FINALLY)
8086 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8087 (js2-node-pos try-block)
8088 (- (setq try-end (js2-node-end try-block))
8089 (js2-node-pos try-block)))))
8090 (when (js2-match-token js2-FINALLY)
8091 (setq finally-pos js2-token-beg
8092 block (js2-parse-statement)
8093 try-end (js2-node-end block)
8094 finally-block (make-js2-finally-node :pos finally-pos
8095 :len (- try-end finally-pos)
8096 :body block))
8097 (js2-node-add-children finally-block block))
8098 (setq pn (make-js2-try-node :pos try-pos
8099 :len (- try-end try-pos)
8100 :try-block try-block
8101 :finally-block finally-block))
8102 (js2-node-add-children pn try-block finally-block)
8103 ;; push them onto the try-node, which reverses and corrects their order
8104 (dolist (cb catch-blocks)
8105 (js2-node-add-children pn cb)
8106 (push cb (js2-try-node-catch-clauses pn)))
8107 pn))
8108
8109 (defun js2-parse-throw ()
8110 "Parser for throw-statement. Last matched token must be js2-THROW."
8111 (let ((pos js2-token-beg)
8112 expr
8113 pn)
8114 (js2-consume-token)
8115 (if (= (js2-peek-token-or-eol) js2-EOL)
8116 ;; ECMAScript does not allow new lines before throw expression,
8117 ;; see bug 256617
8118 (js2-report-error "msg.bad.throw.eol"))
8119 (setq expr (js2-parse-expr)
8120 pn (make-js2-throw-node :pos pos
8121 :len (- (js2-node-end expr) pos)
8122 :expr expr))
8123 (js2-node-add-children pn expr)
8124 pn))
8125
8126 (defsubst js2-match-jump-label-name (label-name)
8127 "If break/continue specified a label, return that label's labeled stmt.
8128 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8129 does not match an existing label, reports an error and returns nil."
8130 (let ((bundle (cdr (assoc label-name js2-label-set))))
8131 (if (null bundle)
8132 (js2-report-error "msg.undef.label"))
8133 bundle))
8134
8135 (defun js2-parse-break ()
8136 "Parser for break-statement. Last matched token must be js2-BREAK."
8137 (let ((pos js2-token-beg)
8138 (end js2-token-end)
8139 break-target ; statement to break from
8140 break-label ; in "break foo", name-node representing the foo
8141 labels ; matching labeled statement to break to
8142 pn)
8143 (js2-consume-token) ; `break'
8144 (when (eq (js2-peek-token-or-eol) js2-NAME)
8145 (js2-consume-token)
8146 (setq break-label (js2-create-name-node)
8147 end (js2-node-end break-label)
8148 ;; matchJumpLabelName only matches if there is one
8149 labels (js2-match-jump-label-name js2-ts-string)
8150 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8151 (unless (or break-target break-label)
8152 ;; no break target specified - try for innermost enclosing loop/switch
8153 (if (null js2-loop-and-switch-set)
8154 (unless break-label
8155 (js2-report-error "msg.bad.break" nil pos (length "break")))
8156 (setq break-target (car js2-loop-and-switch-set))))
8157 (setq pn (make-js2-break-node :pos pos
8158 :len (- end pos)
8159 :label break-label
8160 :target break-target))
8161 (js2-node-add-children pn break-label) ; but not break-target
8162 pn))
8163
8164 (defun js2-parse-continue ()
8165 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8166 (let ((pos js2-token-beg)
8167 (end js2-token-end)
8168 label ; optional user-specified label, a `js2-name-node'
8169 labels ; current matching labeled stmt, if any
8170 target ; the `js2-loop-node' target of this continue stmt
8171 pn)
8172 (js2-consume-token) ; `continue'
8173 (when (= (js2-peek-token-or-eol) js2-NAME)
8174 (js2-consume-token)
8175 (setq label (js2-create-name-node)
8176 end (js2-node-end label)
8177 ;; matchJumpLabelName only matches if there is one
8178 labels (js2-match-jump-label-name js2-ts-string)))
8179 (cond
8180 ((null labels) ; no current label to go to
8181 (if (null js2-loop-set) ; no loop to continue to
8182 (js2-report-error "msg.continue.outside" nil pos
8183 (length "continue"))
8184 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8185 (t
8186 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8187 (setq target (js2-labeled-stmt-node-stmt labels))
8188 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8189 (setq pn (make-js2-continue-node :pos pos
8190 :len (- end pos)
8191 :label label
8192 :target target))
8193 (js2-node-add-children pn label) ; but not target - it's not our child
8194 pn))
8195
8196 (defun js2-parse-with ()
8197 "Parser for with-statement. Last matched token must be js2-WITH."
8198 (js2-consume-token)
8199 (let ((pos js2-token-beg)
8200 obj body pn lp rp)
8201 (if (js2-must-match js2-LP "msg.no.paren.with")
8202 (setq lp js2-token-beg))
8203 (setq obj (js2-parse-expr))
8204 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8205 (setq rp js2-token-beg))
8206 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8207 (setq body (js2-parse-statement)))
8208 (setq pn (make-js2-with-node :pos pos
8209 :len (- (js2-node-end body) pos)
8210 :object obj
8211 :body body
8212 :lp (js2-relpos lp pos)
8213 :rp (js2-relpos rp pos)))
8214 (js2-node-add-children pn obj body)
8215 pn))
8216
8217 (defun js2-parse-const-var ()
8218 "Parser for var- or const-statement.
8219 Last matched token must be js2-CONST or js2-VAR."
8220 (let ((tt (js2-peek-token))
8221 (pos js2-token-beg)
8222 expr
8223 pn)
8224 (js2-consume-token)
8225 (setq expr (js2-parse-variables tt js2-token-beg)
8226 pn (make-js2-expr-stmt-node :pos pos
8227 :len (- (js2-node-end expr) pos)
8228 :expr expr))
8229 (js2-node-add-children pn expr)
8230 pn))
8231
8232 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8233 (let ((pn (make-js2-expr-stmt-node :pos pos
8234 :len (js2-node-len expr)
8235 :type (if (js2-inside-function)
8236 js2-EXPR_VOID
8237 js2-EXPR_RESULT)
8238 :expr expr)))
8239 (if add-child
8240 (js2-node-add-children pn expr))
8241 pn))
8242
8243 (defun js2-parse-let-stmt ()
8244 "Parser for let-statement. Last matched token must be js2-LET."
8245 (js2-consume-token)
8246 (let ((pos js2-token-beg)
8247 expr
8248 pn)
8249 (if (= (js2-peek-token) js2-LP)
8250 ;; let expression in statement context
8251 (setq expr (js2-parse-let pos 'statement)
8252 pn (js2-wrap-with-expr-stmt pos expr t))
8253 ;; else we're looking at a statement like let x=6, y=7;
8254 (setf expr (js2-parse-variables js2-LET pos)
8255 pn (js2-wrap-with-expr-stmt pos expr t)
8256 (js2-node-type pn) js2-EXPR_RESULT))
8257 pn))
8258
8259 (defun js2-parse-ret-yield ()
8260 (js2-parse-return-or-yield (js2-peek-token) nil))
8261
8262 (defconst js2-parse-return-stmt-enders
8263 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8264
8265 (defsubst js2-now-all-set (before after mask)
8266 "Return whether or not the bits in the mask have changed to all set.
8267 BEFORE is bits before change, AFTER is bits after change, and MASK is
8268 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8269 but not BEFORE."
8270 (and (/= (logand before mask) mask)
8271 (= (logand after mask) mask)))
8272
8273 (defun js2-parse-return-or-yield (tt expr-context)
8274 (let ((pos js2-token-beg)
8275 (end js2-token-end)
8276 (before js2-end-flags)
8277 (inside-function (js2-inside-function))
8278 e
8279 ret
8280 name)
8281 (unless inside-function
8282 (js2-report-error (if (eq tt js2-RETURN)
8283 "msg.bad.return"
8284 "msg.bad.yield")))
8285 (js2-consume-token)
8286 ;; This is ugly, but we don't want to require a semicolon.
8287 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8288 (setq e (js2-parse-expr)
8289 end (js2-node-end e)))
8290 (cond
8291 ((eq tt js2-RETURN)
8292 (js2-set-flag js2-end-flags (if (null e)
8293 js2-end-returns
8294 js2-end-returns-value))
8295 (setq ret (make-js2-return-node :pos pos
8296 :len (- end pos)
8297 :retval e))
8298 (js2-node-add-children ret e)
8299 ;; See if we need a strict mode warning.
8300 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8301 ;; more thorough and accurate than this before/after flag check.
8302 ;; E.g. if there's a finally-block that always returns, we shouldn't
8303 ;; show a warning generated by inconsistent returns in the catch blocks.
8304 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8305 ;; so we know which returns/yields to highlight, and we should get rid of
8306 ;; all the checking in `js2-parse-return-or-yield'.
8307 (if (and js2-strict-inconsistent-return-warning
8308 (js2-now-all-set before js2-end-flags
8309 (logior js2-end-returns js2-end-returns-value)))
8310 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8311 (t
8312 (unless (js2-inside-function)
8313 (js2-report-error "msg.bad.yield"))
8314 (js2-set-flag js2-end-flags js2-end-yields)
8315 (setq ret (make-js2-yield-node :pos pos
8316 :len (- end pos)
8317 :value e))
8318 (js2-node-add-children ret e)
8319 (unless expr-context
8320 (setq e ret
8321 ret (js2-wrap-with-expr-stmt pos e t))
8322 (js2-set-requires-activation)
8323 (js2-set-is-generator))))
8324 ;; see if we are mixing yields and value returns.
8325 (when (and inside-function
8326 (js2-now-all-set before js2-end-flags
8327 (logior js2-end-yields js2-end-returns-value)))
8328 (setq name (js2-function-name js2-current-script-or-fn))
8329 (if (zerop (length name))
8330 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8331 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8332 ret))
8333
8334 (defun js2-parse-debugger ()
8335 (js2-consume-token)
8336 (make-js2-keyword-node :type js2-DEBUGGER))
8337
8338 (defun js2-parse-block ()
8339 "Parser for a curly-delimited statement block.
8340 Last token matched must be js2-LC."
8341 (let ((pos js2-token-beg)
8342 (pn (make-js2-scope)))
8343 (js2-consume-token)
8344 (js2-push-scope pn)
8345 (unwind-protect
8346 (progn
8347 (js2-parse-statements pn)
8348 (js2-must-match js2-RC "msg.no.brace.block")
8349 (setf (js2-node-len pn) (- js2-token-end pos)))
8350 (js2-pop-scope))
8351 pn))
8352
8353 ;; for js2-ERROR too, to have a node for error recovery to work on
8354 (defun js2-parse-semi ()
8355 "Parse a statement or handle an error.
8356 Last matched token is js2-SEMI or js2-ERROR."
8357 (let ((tt (js2-peek-token)) pos len)
8358 (js2-consume-token)
8359 (if (eq tt js2-SEMI)
8360 (make-js2-empty-expr-node :len 1)
8361 (setq pos js2-token-beg
8362 len (- js2-token-beg pos))
8363 (js2-report-error "msg.syntax" nil pos len)
8364 (make-js2-error-node :pos pos :len len))))
8365
8366 (defun js2-parse-default-xml-namespace ()
8367 "Parse a `default xml namespace = <expr>' e4x statement."
8368 (let ((pos js2-token-beg)
8369 end len expr unary es)
8370 (js2-consume-token)
8371 (js2-must-have-xml)
8372 (js2-set-requires-activation)
8373 (setq len (- js2-ts-cursor pos))
8374 (unless (and (js2-match-token js2-NAME)
8375 (string= js2-ts-string "xml"))
8376 (js2-report-error "msg.bad.namespace" nil pos len))
8377 (unless (and (js2-match-token js2-NAME)
8378 (string= js2-ts-string "namespace"))
8379 (js2-report-error "msg.bad.namespace" nil pos len))
8380 (unless (js2-match-token js2-ASSIGN)
8381 (js2-report-error "msg.bad.namespace" nil pos len))
8382 (setq expr (js2-parse-expr)
8383 end (js2-node-end expr)
8384 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8385 :pos pos
8386 :len (- end pos)
8387 :operand expr))
8388 (js2-node-add-children unary expr)
8389 (make-js2-expr-stmt-node :pos pos
8390 :len (- end pos)
8391 :expr unary)))
8392
8393 (defun js2-record-label (label bundle)
8394 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8395 (js2-consume-token)
8396 (let ((name (js2-label-node-name label))
8397 labeled-stmt
8398 dup)
8399 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8400 ;; flag both labels if possible when used in editing mode
8401 (if (and js2-parse-ide-mode
8402 (setq dup (js2-get-label-by-name labeled-stmt name)))
8403 (js2-report-error "msg.dup.label" nil
8404 (js2-node-abs-pos dup) (js2-node-len dup)))
8405 (js2-report-error "msg.dup.label" nil
8406 (js2-node-pos label) (js2-node-len label)))
8407 (js2-labeled-stmt-node-add-label bundle label)
8408 (js2-node-add-children bundle label)
8409 ;; Add one reference to the bundle per label in `js2-label-set'
8410 (push (cons name bundle) js2-label-set)))
8411
8412 (defun js2-parse-name-or-label ()
8413 "Parser for identifier or label. Last token matched must be js2-NAME.
8414 Called when we found a name in a statement context. If it's a label, we gather
8415 up any following labels and the next non-label statement into a
8416 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8417 expression and return it wrapped in a `js2-expr-stmt-node'."
8418 (let ((pos js2-token-beg)
8419 (end js2-token-end)
8420 expr
8421 stmt
8422 pn
8423 bundle
8424 (continue t))
8425 ;; set check for label and call down to `js2-parse-primary-expr'
8426 (js2-set-check-for-label)
8427 (setq expr (js2-parse-expr))
8428 (if (/= (js2-node-type expr) js2-LABEL)
8429 ;; Parsed non-label expression - wrap with expression stmt.
8430 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8431 ;; else parsed a label
8432 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8433 (js2-record-label expr bundle)
8434 ;; look for more labels
8435 (while (and continue (= (js2-peek-token) js2-NAME))
8436 (js2-set-check-for-label)
8437 (setq expr (js2-parse-expr))
8438 (if (/= (js2-node-type expr) js2-LABEL)
8439 (progn
8440 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8441 continue nil)
8442 (js2-auto-insert-semicolon stmt))
8443 (js2-record-label expr bundle)))
8444 ;; no more labels; now parse the labeled statement
8445 (unwind-protect
8446 (unless stmt
8447 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8448 (setq stmt (js2-statement-helper))))
8449 ;; remove the labels for this statement from the global set
8450 (dolist (label (js2-labeled-stmt-node-labels bundle))
8451 (setq js2-label-set (remove label js2-label-set))))
8452 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8453 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8454 (js2-node-add-children bundle stmt)
8455 bundle)))
8456
8457 (defun js2-parse-expr-stmt ()
8458 "Default parser in statement context, if no recognized statement found."
8459 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8460
8461 (defun js2-parse-variables (decl-type pos)
8462 "Parse a comma-separated list of variable declarations.
8463 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8464
8465 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8466 For 'var' or 'const', the keyword should be the token last scanned.
8467
8468 POS is the position where the node should start. It's sometimes the
8469 var/const/let keyword, and other times the beginning of the first token
8470 in the first variable declaration.
8471
8472 Returns the parsed `js2-var-decl-node' expression node."
8473 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8474 :pos pos))
8475 destructuring
8476 kid-pos
8477 tt
8478 init
8479 name
8480 end
8481 nbeg nend
8482 vi
8483 (continue t))
8484 ;; Example:
8485 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8486 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8487 ;; var {a, b} = baz;
8488 (while continue
8489 (setq destructuring nil
8490 name nil
8491 tt (js2-peek-token)
8492 kid-pos js2-token-beg
8493 end js2-token-end
8494 init nil)
8495 (if (or (= tt js2-LB) (= tt js2-LC))
8496 ;; Destructuring assignment, e.g., var [a, b] = ...
8497 (setq destructuring (js2-parse-primary-expr-lhs)
8498 end (js2-node-end destructuring))
8499 ;; Simple variable name
8500 (when (js2-must-match js2-NAME "msg.bad.var")
8501 (setq name (js2-create-name-node)
8502 nbeg js2-token-beg
8503 nend js2-token-end
8504 end nend)
8505 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8506 (when (js2-match-token js2-ASSIGN)
8507 (setq init (js2-parse-assign-expr)
8508 end (js2-node-end init))
8509 (js2-record-imenu-functions init name))
8510 (when name
8511 (js2-set-face nbeg nend (if (js2-function-node-p init)
8512 'font-lock-function-name-face
8513 'font-lock-variable-name-face)
8514 'record))
8515 (setq vi (make-js2-var-init-node :pos kid-pos
8516 :len (- end kid-pos)
8517 :type decl-type))
8518 (if destructuring
8519 (progn
8520 (if (and (null init) (not js2-in-for-init))
8521 (js2-report-error "msg.destruct.assign.no.init"))
8522 (js2-define-destruct-symbols destructuring
8523 decl-type
8524 'font-lock-variable-name-face)
8525 (setf (js2-var-init-node-target vi) destructuring))
8526 (setf (js2-var-init-node-target vi) name))
8527 (setf (js2-var-init-node-initializer vi) init)
8528 (js2-node-add-children vi name destructuring init)
8529 (js2-block-node-push result vi)
8530 (unless (js2-match-token js2-COMMA)
8531 (setq continue nil)))
8532 (setf (js2-node-len result) (- end pos))
8533 result))
8534
8535 (defun js2-parse-let (pos &optional stmt-p)
8536 "Parse a let expression or statement.
8537 A let-expression is of the form `let (vars) expr'.
8538 A let-statment is of the form `let (vars) {statements}'.
8539 The third form of let is a variable declaration list, handled
8540 by `js2-parse-variables'."
8541 (let ((pn (make-js2-let-node :pos pos))
8542 beg vars body)
8543 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8544 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8545 (js2-push-scope pn)
8546 (unwind-protect
8547 (progn
8548 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8549 (if (js2-must-match js2-RP "msg.no.paren.let")
8550 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8551 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8552 ;; let statement
8553 (progn
8554 (js2-consume-token)
8555 (setf beg js2-token-beg ; position stmt at LC
8556 body (js2-parse-statements))
8557 (js2-must-match js2-RC "msg.no.curly.let")
8558 (setf (js2-node-len body) (- js2-token-end beg)
8559 (js2-node-len pn) (- js2-token-end pos)
8560 (js2-let-node-body pn) body
8561 (js2-node-type pn) js2-LET))
8562 ;; let expression
8563 (setf body (js2-parse-expr)
8564 (js2-node-len pn) (- (js2-node-end body) pos)
8565 (js2-let-node-body pn) body))
8566 (js2-node-add-children pn vars body))
8567 (js2-pop-scope))
8568 pn))
8569
8570 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8571 (js2-scope-put-symbol (or scope js2-current-scope)
8572 name
8573 (make-js2-symbol decl-type name node)))
8574
8575 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8576 "Define a symbol in the current scope.
8577 If NODE is non-nil, it is the AST node associated with the symbol."
8578 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8579 (symbol (if defining-scope
8580 (js2-scope-get-symbol defining-scope name)))
8581 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8582 (cond
8583 ((and symbol ; already defined
8584 (or (= sdt js2-CONST) ; old version is const
8585 (= decl-type js2-CONST) ; new version is const
8586 ;; two let-bound vars in this block have same name
8587 (and (= sdt js2-LET)
8588 (eq defining-scope js2-current-scope))))
8589 (js2-report-error
8590 (cond
8591 ((= sdt js2-CONST) "msg.const.redecl")
8592 ((= sdt js2-LET) "msg.let.redecl")
8593 ((= sdt js2-VAR) "msg.var.redecl")
8594 ((= sdt js2-FUNCTION) "msg.function.redecl")
8595 (t "msg.parm.redecl"))
8596 name))
8597 ((= decl-type js2-LET)
8598 (if (and (not ignore-not-in-block)
8599 (or (= (js2-node-type js2-current-scope) js2-IF)
8600 (js2-loop-node-p js2-current-scope)))
8601 (js2-report-error "msg.let.decl.not.in.block")
8602 (js2-define-new-symbol decl-type name node)))
8603 ((or (= decl-type js2-VAR)
8604 (= decl-type js2-CONST)
8605 (= decl-type js2-FUNCTION))
8606 (if symbol
8607 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8608 (js2-add-strict-warning "msg.var.redecl" name)
8609 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8610 (js2-add-strict-warning "msg.var.hides.arg" name)))
8611 (js2-define-new-symbol decl-type name node
8612 js2-current-script-or-fn)))
8613 ((= decl-type js2-LP)
8614 (if symbol
8615 ;; must be duplicate parameter. Second parameter hides the
8616 ;; first, so go ahead and add the second pararameter
8617 (js2-report-warning "msg.dup.parms" name))
8618 (js2-define-new-symbol decl-type name node))
8619 (t (js2-code-bug)))))
8620
8621 (defun js2-parse-expr (&optional oneshot)
8622 (let* ((pn (js2-parse-assign-expr))
8623 (pos (js2-node-pos pn))
8624 left
8625 right
8626 op-pos)
8627 (while (and (not oneshot)
8628 (js2-match-token js2-COMMA))
8629 (setq op-pos (- js2-token-beg pos)) ; relative
8630 (if (= (js2-peek-token) js2-YIELD)
8631 (js2-report-error "msg.yield.parenthesized"))
8632 (setq right (js2-parse-assign-expr)
8633 left pn
8634 pn (make-js2-infix-node :type js2-COMMA
8635 :pos pos
8636 :len (- js2-ts-cursor pos)
8637 :op-pos op-pos
8638 :left left
8639 :right right))
8640 (js2-node-add-children pn left right))
8641 pn))
8642
8643 (defun js2-parse-assign-expr ()
8644 (let ((tt (js2-peek-token))
8645 (pos js2-token-beg)
8646 pn
8647 left
8648 right
8649 op-pos)
8650 (if (= tt js2-YIELD)
8651 (js2-parse-return-or-yield tt t)
8652 ;; not yield - parse assignment expression
8653 (setq pn (js2-parse-cond-expr)
8654 tt (js2-peek-token))
8655 (when (and (<= js2-first-assign tt)
8656 (<= tt js2-last-assign))
8657 ;; tt express assignment (=, |=, ^=, ..., %=)
8658 (js2-consume-token)
8659 (setq op-pos (- js2-token-beg pos) ; relative
8660 left pn
8661 right (js2-parse-assign-expr)
8662 pn (make-js2-assign-node :type tt
8663 :pos pos
8664 :len (- (js2-node-end right) pos)
8665 :op-pos op-pos
8666 :left left
8667 :right right))
8668 (when js2-parse-ide-mode
8669 (js2-highlight-assign-targets pn left right)
8670 (js2-record-imenu-functions right left))
8671 ;; do this last so ide checks above can use absolute positions
8672 (js2-node-add-children pn left right))
8673 pn)))
8674
8675 (defun js2-parse-cond-expr ()
8676 (let ((pos js2-token-beg)
8677 (pn (js2-parse-or-expr))
8678 test-expr
8679 if-true
8680 if-false
8681 q-pos
8682 c-pos)
8683 (when (js2-match-token js2-HOOK)
8684 (setq q-pos (- js2-token-beg pos)
8685 if-true (js2-parse-assign-expr))
8686 (js2-must-match js2-COLON "msg.no.colon.cond")
8687 (setq c-pos (- js2-token-beg pos)
8688 if-false (js2-parse-assign-expr)
8689 test-expr pn
8690 pn (make-js2-cond-node :pos pos
8691 :len (- (js2-node-end if-false) pos)
8692 :test-expr test-expr
8693 :true-expr if-true
8694 :false-expr if-false
8695 :q-pos q-pos
8696 :c-pos c-pos))
8697 (js2-node-add-children pn test-expr if-true if-false))
8698 pn))
8699
8700 (defun js2-make-binary (type left parser)
8701 "Helper for constructing a binary-operator AST node.
8702 LEFT is the left-side-expression, already parsed, and the
8703 binary operator should have just been matched.
8704 PARSER is a function to call to parse the right operand,
8705 or a `js2-node' struct if it has already been parsed."
8706 (let* ((pos (js2-node-pos left))
8707 (op-pos (- js2-token-beg pos))
8708 (right (if (js2-node-p parser)
8709 parser
8710 (funcall parser)))
8711 (pn (make-js2-infix-node :type type
8712 :pos pos
8713 :len (- (js2-node-end right) pos)
8714 :op-pos op-pos
8715 :left left
8716 :right right)))
8717 (js2-node-add-children pn left right)
8718 pn))
8719
8720 (defun js2-parse-or-expr ()
8721 (let ((pn (js2-parse-and-expr)))
8722 (when (js2-match-token js2-OR)
8723 (setq pn (js2-make-binary js2-OR
8724 pn
8725 'js2-parse-or-expr)))
8726 pn))
8727
8728 (defun js2-parse-and-expr ()
8729 (let ((pn (js2-parse-bit-or-expr)))
8730 (when (js2-match-token js2-AND)
8731 (setq pn (js2-make-binary js2-AND
8732 pn
8733 'js2-parse-and-expr)))
8734 pn))
8735
8736 (defun js2-parse-bit-or-expr ()
8737 (let ((pn (js2-parse-bit-xor-expr)))
8738 (while (js2-match-token js2-BITOR)
8739 (setq pn (js2-make-binary js2-BITOR
8740 pn
8741 'js2-parse-bit-xor-expr)))
8742 pn))
8743
8744 (defun js2-parse-bit-xor-expr ()
8745 (let ((pn (js2-parse-bit-and-expr)))
8746 (while (js2-match-token js2-BITXOR)
8747 (setq pn (js2-make-binary js2-BITXOR
8748 pn
8749 'js2-parse-bit-and-expr)))
8750 pn))
8751
8752 (defun js2-parse-bit-and-expr ()
8753 (let ((pn (js2-parse-eq-expr)))
8754 (while (js2-match-token js2-BITAND)
8755 (setq pn (js2-make-binary js2-BITAND
8756 pn
8757 'js2-parse-eq-expr)))
8758 pn))
8759
8760 (defconst js2-parse-eq-ops
8761 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8762
8763 (defun js2-parse-eq-expr ()
8764 (let ((pn (js2-parse-rel-expr))
8765 tt)
8766 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8767 (js2-consume-token)
8768 (setq pn (js2-make-binary tt
8769 pn
8770 'js2-parse-rel-expr)))
8771 pn))
8772
8773 (defconst js2-parse-rel-ops
8774 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8775
8776 (defun js2-parse-rel-expr ()
8777 (let ((pn (js2-parse-shift-expr))
8778 (continue t)
8779 tt)
8780 (while continue
8781 (setq tt (js2-peek-token))
8782 (cond
8783 ((and js2-in-for-init (= tt js2-IN))
8784 (setq continue nil))
8785 ((memq tt js2-parse-rel-ops)
8786 (js2-consume-token)
8787 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8788 (t
8789 (setq continue nil))))
8790 pn))
8791
8792 (defconst js2-parse-shift-ops
8793 (list js2-LSH js2-URSH js2-RSH))
8794
8795 (defun js2-parse-shift-expr ()
8796 (let ((pn (js2-parse-add-expr))
8797 tt
8798 (continue t))
8799 (while continue
8800 (setq tt (js2-peek-token))
8801 (if (memq tt js2-parse-shift-ops)
8802 (progn
8803 (js2-consume-token)
8804 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8805 (setq continue nil)))
8806 pn))
8807
8808 (defun js2-parse-add-expr ()
8809 (let ((pn (js2-parse-mul-expr))
8810 tt
8811 (continue t))
8812 (while continue
8813 (setq tt (js2-peek-token))
8814 (if (or (= tt js2-ADD) (= tt js2-SUB))
8815 (progn
8816 (js2-consume-token)
8817 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8818 (setq continue nil)))
8819 pn))
8820
8821 (defconst js2-parse-mul-ops
8822 (list js2-MUL js2-DIV js2-MOD))
8823
8824 (defun js2-parse-mul-expr ()
8825 (let ((pn (js2-parse-unary-expr))
8826 tt
8827 (continue t))
8828 (while continue
8829 (setq tt (js2-peek-token))
8830 (if (memq tt js2-parse-mul-ops)
8831 (progn
8832 (js2-consume-token)
8833 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8834 (setq continue nil)))
8835 pn))
8836
8837 (defsubst js2-make-unary (type parser &rest args)
8838 "Make a unary node of type TYPE.
8839 PARSER is either a node (for postfix operators) or a function to call
8840 to parse the operand (for prefix operators)."
8841 (let* ((pos js2-token-beg)
8842 (postfix (js2-node-p parser))
8843 (expr (if postfix
8844 parser
8845 (apply parser args)))
8846 end
8847 pn)
8848 (if postfix ; e.g. i++
8849 (setq pos (js2-node-pos expr)
8850 end js2-token-end)
8851 (setq end (js2-node-end expr)))
8852 (setq pn (make-js2-unary-node :type type
8853 :pos pos
8854 :len (- end pos)
8855 :operand expr))
8856 (js2-node-add-children pn expr)
8857 pn))
8858
8859 (defconst js2-incrementable-node-types
8860 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8861 "Node types that can be the operand of a ++ or -- operator.")
8862
8863 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8864 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8865 js2-incrementable-node-types)
8866 (js2-report-error (if (= tt js2-INC)
8867 "msg.bad.incr"
8868 "msg.bad.decr")
8869 nil beg (- end beg))))
8870
8871 (defun js2-parse-unary-expr ()
8872 (let ((tt (js2-peek-token))
8873 pn expr beg end)
8874 (cond
8875 ((or (= tt js2-VOID)
8876 (= tt js2-NOT)
8877 (= tt js2-BITNOT)
8878 (= tt js2-TYPEOF))
8879 (js2-consume-token)
8880 (js2-make-unary tt 'js2-parse-unary-expr))
8881 ((= tt js2-ADD)
8882 (js2-consume-token)
8883 ;; Convert to special POS token in decompiler and parse tree
8884 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8885 ((= tt js2-SUB)
8886 (js2-consume-token)
8887 ;; Convert to special NEG token in decompiler and parse tree
8888 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8889 ((or (= tt js2-INC)
8890 (= tt js2-DEC))
8891 (js2-consume-token)
8892 (prog1
8893 (setq beg js2-token-beg
8894 end js2-token-end
8895 expr (js2-make-unary tt 'js2-parse-member-expr t))
8896 (js2-check-bad-inc-dec tt beg end expr)))
8897 ((= tt js2-DELPROP)
8898 (js2-consume-token)
8899 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8900 ((= tt js2-ERROR)
8901 (js2-consume-token)
8902 (make-js2-error-node)) ; try to continue
8903 ((and (= tt js2-LT)
8904 js2-compiler-xml-available)
8905 ;; XML stream encountered in expression.
8906 (js2-consume-token)
8907 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8908 (t
8909 (setq pn (js2-parse-member-expr t)
8910 ;; Don't look across a newline boundary for a postfix incop.
8911 tt (js2-peek-token-or-eol))
8912 (when (or (= tt js2-INC) (= tt js2-DEC))
8913 (js2-consume-token)
8914 (setf expr pn
8915 pn (js2-make-unary tt expr))
8916 (js2-node-set-prop pn 'postfix t)
8917 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8918 pn))))
8919
8920 (defun js2-parse-xml-initializer ()
8921 "Parse an E4X XML initializer.
8922 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8923 Then I'll postprocess the result, depending on whether we're in IDE
8924 mode or codegen mode, and generate the appropriate rewritten AST.
8925 IDE mode uses a rich AST that models the XML structure. Codegen mode
8926 just concatenates everything and makes a new XML or XMLList out of it."
8927 (let ((tt (js2-get-first-xml-token))
8928 pn-xml
8929 pn
8930 expr
8931 kids
8932 expr-pos
8933 (continue t)
8934 (first-token t))
8935 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8936 (js2-report-error "msg.syntax"))
8937 (setq pn-xml (make-js2-xml-node))
8938 (while continue
8939 (if first-token
8940 (setq first-token nil)
8941 (setq tt (js2-get-next-xml-token)))
8942 (cond
8943 ;; js2-XML means we found a {expr} in the XML stream.
8944 ;; The js2-ts-string is the XML up to the left-curly.
8945 ((= tt js2-XML)
8946 (push (make-js2-string-node :pos js2-token-beg
8947 :len (- js2-ts-cursor js2-token-beg))
8948 kids)
8949 (js2-must-match js2-LC "msg.syntax")
8950 (setq expr-pos js2-ts-cursor
8951 expr (if (eq (js2-peek-token) js2-RC)
8952 (make-js2-empty-expr-node :pos expr-pos)
8953 (js2-parse-expr)))
8954 (js2-must-match js2-RC "msg.syntax")
8955 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8956 :len (js2-node-len expr)
8957 :expr expr))
8958 (js2-node-add-children pn expr)
8959 (push pn kids))
8960 ;; a js2-XMLEND token means we hit the final close-tag.
8961 ((= tt js2-XMLEND)
8962 (push (make-js2-string-node :pos js2-token-beg
8963 :len (- js2-ts-cursor js2-token-beg))
8964 kids)
8965 (dolist (kid (nreverse kids))
8966 (js2-block-node-push pn-xml kid))
8967 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8968 (js2-node-pos pn-xml))
8969 continue nil))
8970 (t
8971 (js2-report-error "msg.syntax")
8972 (setq continue nil))))
8973 pn-xml))
8974
8975
8976 (defun js2-parse-argument-list ()
8977 "Parse an argument list and return it as a lisp list of nodes.
8978 Returns the list in reverse order. Consumes the right-paren token."
8979 (let (result)
8980 (unless (js2-match-token js2-RP)
8981 (loop do
8982 (if (= (js2-peek-token) js2-YIELD)
8983 (js2-report-error "msg.yield.parenthesized"))
8984 (push (js2-parse-assign-expr) result)
8985 while
8986 (js2-match-token js2-COMMA))
8987 (js2-must-match js2-RP "msg.no.paren.arg")
8988 result)))
8989
8990 (defun js2-parse-member-expr (&optional allow-call-syntax)
8991 (let ((tt (js2-peek-token))
8992 pn
8993 pos
8994 target
8995 args
8996 beg
8997 end
8998 init
8999 tail)
9000 (if (/= tt js2-NEW)
9001 (setq pn (js2-parse-primary-expr))
9002 ;; parse a 'new' expression
9003 (js2-consume-token)
9004 (setq pos js2-token-beg
9005 beg pos
9006 target (js2-parse-member-expr)
9007 end (js2-node-end target)
9008 pn (make-js2-new-node :pos pos
9009 :target target
9010 :len (- end pos)))
9011 (js2-node-add-children pn target)
9012 (when (js2-match-token js2-LP)
9013 ;; Add the arguments to pn, if any are supplied.
9014 (setf beg pos ; start of "new" keyword
9015 pos js2-token-beg
9016 args (nreverse (js2-parse-argument-list))
9017 (js2-new-node-args pn) args
9018 end js2-token-end
9019 (js2-new-node-lp pn) (- pos beg)
9020 (js2-new-node-rp pn) (- end 1 beg))
9021 (apply #'js2-node-add-children pn args))
9022 (when (and js2-allow-rhino-new-expr-initializer
9023 (js2-match-token js2-LC))
9024 (setf init (js2-parse-object-literal)
9025 end (js2-node-end init)
9026 (js2-new-node-initializer pn) init)
9027 (js2-node-add-children pn init))
9028 (setf (js2-node-len pn) (- end beg))) ; end outer if
9029 (js2-parse-member-expr-tail allow-call-syntax pn)))
9030
9031 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9032 "Parse a chain of property/array accesses or function calls.
9033 Includes parsing for E4X operators like `..' and `.@'.
9034 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9035 Returns an expression tree that includes PN, the parent node."
9036 (let ((beg (js2-node-pos pn))
9037 tt
9038 (continue t))
9039 (while continue
9040 (setq tt (js2-peek-token))
9041 (cond
9042 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9043 (setq pn (js2-parse-property-access tt pn)))
9044 ((= tt js2-DOTQUERY)
9045 (setq pn (js2-parse-dot-query pn)))
9046 ((= tt js2-LB)
9047 (setq pn (js2-parse-element-get pn)))
9048 ((= tt js2-LP)
9049 (if allow-call-syntax
9050 (setq pn (js2-parse-function-call pn))
9051 (setq continue nil)))
9052 (t
9053 (setq continue nil))))
9054 (if (>= js2-highlight-level 2)
9055 (js2-parse-highlight-member-expr-node pn))
9056 pn))
9057
9058 (defun js2-parse-dot-query (pn)
9059 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9060 Last token parsed must be `js2-DOTQUERY'."
9061 (let ((pos (js2-node-pos pn))
9062 op-pos
9063 expr
9064 end)
9065 (js2-consume-token)
9066 (js2-must-have-xml)
9067 (js2-set-requires-activation)
9068 (setq op-pos js2-token-beg
9069 expr (js2-parse-expr)
9070 end (js2-node-end expr)
9071 pn (make-js2-xml-dot-query-node :left pn
9072 :pos pos
9073 :op-pos op-pos
9074 :right expr))
9075 (js2-node-add-children pn
9076 (js2-xml-dot-query-node-left pn)
9077 (js2-xml-dot-query-node-right pn))
9078 (if (js2-must-match js2-RP "msg.no.paren")
9079 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9080 end js2-token-end))
9081 (setf (js2-node-len pn) (- end pos))
9082 pn))
9083
9084 (defun js2-parse-element-get (pn)
9085 "Parse an element-get expression, e.g. foo[bar].
9086 Last token parsed must be `js2-RB'."
9087 (let ((lb js2-token-beg)
9088 (pos (js2-node-pos pn))
9089 rb
9090 expr)
9091 (js2-consume-token)
9092 (setq expr (js2-parse-expr))
9093 (if (js2-must-match js2-RB "msg.no.bracket.index")
9094 (setq rb js2-token-beg))
9095 (setq pn (make-js2-elem-get-node :target pn
9096 :pos pos
9097 :element expr
9098 :lb (js2-relpos lb pos)
9099 :rb (js2-relpos rb pos)
9100 :len (- js2-token-end pos)))
9101 (js2-node-add-children pn
9102 (js2-elem-get-node-target pn)
9103 (js2-elem-get-node-element pn))
9104 pn))
9105
9106 (defun js2-parse-function-call (pn)
9107 (let (args
9108 (pos (js2-node-pos pn)))
9109 (js2-consume-token)
9110 (setq pn (make-js2-call-node :pos pos
9111 :target pn
9112 :lp (- js2-token-beg pos)))
9113 (js2-node-add-children pn (js2-call-node-target pn))
9114 ;; Add the arguments to pn, if any are supplied.
9115 (setf args (nreverse (js2-parse-argument-list))
9116 (js2-call-node-rp pn) (- js2-token-beg pos)
9117 (js2-call-node-args pn) args)
9118 (apply #'js2-node-add-children pn args)
9119 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9120 pn))
9121
9122 (defun js2-parse-property-access (tt pn)
9123 "Parse a property access, XML descendants access, or XML attr access."
9124 (let ((member-type-flags 0)
9125 (dot-pos js2-token-beg)
9126 (dot-len (if (= tt js2-DOTDOT) 2 1))
9127 name
9128 ref ; right side of . or .. operator
9129 result)
9130 (js2-consume-token)
9131 (when (= tt js2-DOTDOT)
9132 (js2-must-have-xml)
9133 (setq member-type-flags js2-descendants-flag))
9134 (if (not js2-compiler-xml-available)
9135 (progn
9136 (js2-must-match-prop-name "msg.no.name.after.dot")
9137 (setq name (js2-create-name-node t js2-GETPROP)
9138 result (make-js2-prop-get-node :left pn
9139 :pos js2-token-beg
9140 :right name
9141 :len (- js2-token-end
9142 js2-token-beg)))
9143 (js2-node-add-children result pn name)
9144 result)
9145 ;; otherwise look for XML operators
9146 (setf result (if (= tt js2-DOT)
9147 (make-js2-prop-get-node)
9148 (make-js2-infix-node :type js2-DOTDOT))
9149 (js2-node-pos result) (js2-node-pos pn)
9150 (js2-infix-node-op-pos result) dot-pos
9151 (js2-infix-node-left result) pn ; do this after setting position
9152 tt (js2-next-token))
9153 (cond
9154 ;; needed for generator.throw()
9155 ((= tt js2-THROW)
9156 (js2-save-name-token-data js2-token-beg "throw")
9157 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9158 ;; handles: name, ns::name, ns::*, ns::[expr]
9159 ((js2-valid-prop-name-token tt)
9160 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9161 ;; handles: *, *::name, *::*, *::[expr]
9162 ((= tt js2-MUL)
9163 (js2-save-name-token-data js2-token-beg "*")
9164 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9165 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9166 ((= tt js2-XMLATTR)
9167 (setq result (js2-parse-attribute-access)))
9168 (t
9169 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9170 (if ref
9171 (setf (js2-node-len result) (- (js2-node-end ref)
9172 (js2-node-pos result))
9173 (js2-infix-node-right result) ref))
9174 (if (js2-infix-node-p result)
9175 (js2-node-add-children result
9176 (js2-infix-node-left result)
9177 (js2-infix-node-right result)))
9178 result)))
9179
9180 (defun js2-parse-attribute-access ()
9181 "Parse an E4X XML attribute expression.
9182 This includes expressions of the forms:
9183
9184 @attr @ns::attr @ns::*
9185 @* @*::attr @*::*
9186 @[expr] @*::[expr] @ns::[expr]
9187
9188 Called if we peeked an '@' token."
9189 (let ((tt (js2-next-token))
9190 (at-pos js2-token-beg))
9191 (cond
9192 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9193 ((js2-valid-prop-name-token tt)
9194 (js2-parse-property-name at-pos js2-ts-string 0))
9195 ;; handles: @*, @*::name, @*::*, @*::[expr]
9196 ((= tt js2-MUL)
9197 (js2-save-name-token-data js2-token-beg "*")
9198 (js2-parse-property-name js2-token-beg "*" 0))
9199 ;; handles @[expr]
9200 ((= tt js2-LB)
9201 (js2-parse-xml-elem-ref at-pos))
9202 (t
9203 (js2-report-error "msg.no.name.after.xmlAttr")
9204 ;; Avoid cascaded errors that happen if we make an error node here.
9205 (js2-save-name-token-data js2-token-beg "")
9206 (js2-parse-property-name js2-token-beg "" 0)))))
9207
9208 (defun js2-parse-property-name (at-pos s member-type-flags)
9209 "Check if :: follows name in which case it becomes qualified name.
9210
9211 AT-POS is a natural number if we just read an '@' token, else nil.
9212 S is the name or string that was matched: an identifier, 'throw' or '*'.
9213 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9214
9215 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9216 operator, or the name is followed by ::. For a plain name, returns a
9217 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9218 (let ((pos (or at-pos js2-token-beg))
9219 colon-pos
9220 (name (js2-create-name-node t js2-current-token))
9221 ns
9222 tt
9223 ref
9224 pn)
9225 (catch 'return
9226 (when (js2-match-token js2-COLONCOLON)
9227 (setq ns name
9228 colon-pos js2-token-beg
9229 tt (js2-next-token))
9230 (cond
9231 ;; handles name::name
9232 ((js2-valid-prop-name-token tt)
9233 (setq name (js2-create-name-node)))
9234 ;; handles name::*
9235 ((= tt js2-MUL)
9236 (js2-save-name-token-data js2-token-beg "*")
9237 (setq name (js2-create-name-node)))
9238 ;; handles name::[expr]
9239 ((= tt js2-LB)
9240 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9241 (t
9242 (js2-report-error "msg.no.name.after.coloncolon"))))
9243 (if (and (null ns) (zerop member-type-flags))
9244 name
9245 (prog1
9246 (setq pn
9247 (make-js2-xml-prop-ref-node :pos pos
9248 :len (- (js2-node-end name) pos)
9249 :at-pos at-pos
9250 :colon-pos colon-pos
9251 :propname name))
9252 (js2-node-add-children pn name))))))
9253
9254 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9255 "Parse the [expr] portion of an xml element reference.
9256 For instance, @[expr], @*::[expr], or ns::[expr]."
9257 (let* ((lb js2-token-beg)
9258 (pos (or at-pos lb))
9259 rb
9260 (expr (js2-parse-expr))
9261 (end (js2-node-end expr))
9262 pn)
9263 (if (js2-must-match js2-RB "msg.no.bracket.index")
9264 (setq rb js2-token-beg
9265 end js2-token-end))
9266 (prog1
9267 (setq pn
9268 (make-js2-xml-elem-ref-node :pos pos
9269 :len (- end pos)
9270 :namespace namespace
9271 :colon-pos colon-pos
9272 :at-pos at-pos
9273 :expr expr
9274 :lb (js2-relpos lb pos)
9275 :rb (js2-relpos rb pos)))
9276 (js2-node-add-children pn namespace expr))))
9277
9278 (defun js2-parse-primary-expr-lhs ()
9279 (let ((js2-is-in-lhs t))
9280 (js2-parse-primary-expr)))
9281
9282 (defun js2-parse-primary-expr ()
9283 "Parses a literal (leaf) expression of some sort.
9284 Includes complex literals such as functions, object-literals,
9285 array-literals, array comprehensions and regular expressions."
9286 (let ((tt-flagged (js2-next-flagged-token))
9287 pn ; parent node (usually return value)
9288 tt
9289 px-pos ; paren-expr pos
9290 len
9291 flags ; regexp flags
9292 expr)
9293 (setq tt js2-current-token)
9294 (cond
9295 ((= tt js2-FUNCTION)
9296 (js2-parse-function 'FUNCTION_EXPRESSION))
9297 ((= tt js2-LB)
9298 (js2-parse-array-literal))
9299 ((= tt js2-LC)
9300 (js2-parse-object-literal))
9301 ((= tt js2-LET)
9302 (js2-parse-let js2-token-beg))
9303 ((= tt js2-LP)
9304 (setq px-pos js2-token-beg
9305 expr (js2-parse-expr))
9306 (js2-must-match js2-RP "msg.no.paren")
9307 (setq pn (make-js2-paren-node :pos px-pos
9308 :expr expr
9309 :len (- js2-token-end px-pos)))
9310 (js2-node-add-children pn (js2-paren-node-expr pn))
9311 pn)
9312 ((= tt js2-XMLATTR)
9313 (js2-must-have-xml)
9314 (js2-parse-attribute-access))
9315 ((= tt js2-NAME)
9316 (js2-parse-name tt-flagged tt))
9317 ((= tt js2-NUMBER)
9318 (make-js2-number-node))
9319 ((= tt js2-STRING)
9320 (prog1
9321 (make-js2-string-node)
9322 (js2-record-face 'font-lock-string-face)))
9323 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9324 ;; Got / or /= which in this context means a regexp literal
9325 (setq px-pos js2-token-beg)
9326 (js2-read-regexp tt)
9327 (setq flags js2-ts-regexp-flags
9328 js2-ts-regexp-flags nil)
9329 (prog1
9330 (make-js2-regexp-node :pos px-pos
9331 :len (- js2-ts-cursor px-pos)
9332 :value js2-ts-string
9333 :flags flags)
9334 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9335 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9336 ((or (= tt js2-NULL)
9337 (= tt js2-THIS)
9338 (= tt js2-FALSE)
9339 (= tt js2-TRUE))
9340 (make-js2-keyword-node :type tt))
9341 ((= tt js2-RESERVED)
9342 (js2-report-error "msg.reserved.id")
9343 (make-js2-name-node))
9344 ((= tt js2-ERROR)
9345 ;; the scanner or one of its subroutines reported the error.
9346 (make-js2-error-node))
9347 ((= tt js2-EOF)
9348 (setq px-pos (point-at-bol)
9349 len (- js2-ts-cursor px-pos))
9350 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9351 (make-js2-error-node :pos px-pos :len len))
9352 (t
9353 (js2-report-error "msg.syntax")
9354 (make-js2-error-node)))))
9355
9356 (defun js2-parse-name (tt-flagged tt)
9357 (let ((name js2-ts-string)
9358 (name-pos js2-token-beg)
9359 node)
9360 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9361 (= (js2-peek-token) js2-COLON))
9362 (prog1
9363 ;; Do not consume colon, it is used as unwind indicator
9364 ;; to return to statementHelper.
9365 (make-js2-label-node :pos name-pos
9366 :len (- js2-token-end name-pos)
9367 :name name)
9368 (js2-set-face name-pos
9369 js2-token-end
9370 'font-lock-variable-name-face 'record))
9371 ;; Otherwise not a label, just a name. Unfortunately peeking
9372 ;; the next token to check for a colon has biffed js2-token-beg
9373 ;; and js2-token-end. We store the name's bounds in buffer vars
9374 ;; and `js2-create-name-node' uses them.
9375 (js2-save-name-token-data name-pos name)
9376 (setq node (if js2-compiler-xml-available
9377 (js2-parse-property-name nil name 0)
9378 (js2-create-name-node 'check-activation)))
9379 (if js2-highlight-external-variables
9380 (js2-record-name-node node))
9381 node)))
9382
9383 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9384 (js2-add-strict-warning
9385 msg nil
9386 ;; back up from comma to beginning of line or array/objlit
9387 (max (if elems
9388 (js2-node-pos (car elems))
9389 pos)
9390 (save-excursion
9391 (goto-char comma-pos)
9392 (back-to-indentation)
9393 (point)))
9394 comma-pos))
9395
9396 (defun js2-parse-array-literal ()
9397 (let ((pos js2-token-beg)
9398 (end js2-token-end)
9399 (after-lb-or-comma t)
9400 after-comma
9401 tt
9402 elems
9403 pn
9404 (continue t))
9405 (unless js2-is-in-lhs
9406 (js2-push-scope (make-js2-scope))) ; for array comp
9407 (while continue
9408 (setq tt (js2-peek-token))
9409 (cond
9410 ;; comma
9411 ((= tt js2-COMMA)
9412 (js2-consume-token)
9413 (setq after-comma js2-token-end)
9414 (if (not after-lb-or-comma)
9415 (setq after-lb-or-comma t)
9416 (push nil elems)))
9417 ;; end of array
9418 ((or (= tt js2-RB)
9419 (= tt js2-EOF)) ; prevent infinite loop
9420 (if (= tt js2-EOF)
9421 (js2-report-error "msg.no.bracket.arg" nil pos)
9422 (js2-consume-token))
9423 (setq continue nil
9424 end js2-token-end
9425 pn (make-js2-array-node :pos pos
9426 :len (- js2-ts-cursor pos)
9427 :elems (nreverse elems)))
9428 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9429 (when (and after-comma (not js2-is-in-lhs))
9430 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9431 pos elems after-comma)))
9432 ;; destructuring binding
9433 (js2-is-in-lhs
9434 (push (if (or (= tt js2-LC)
9435 (= tt js2-LB)
9436 (= tt js2-NAME))
9437 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9438 (js2-parse-primary-expr-lhs)
9439 ;; invalid pattern
9440 (js2-consume-token)
9441 (js2-report-error "msg.bad.var")
9442 (make-js2-error-node))
9443 elems)
9444 (setq after-lb-or-comma nil
9445 after-comma nil))
9446 ;; array comp
9447 ((and (>= js2-language-version 170)
9448 (= tt js2-FOR) ; check for array comprehension
9449 (not after-lb-or-comma) ; "for" can't follow a comma
9450 elems ; must have at least 1 element
9451 (not (cdr elems))) ; but no 2nd element
9452 (setf continue nil
9453 pn (js2-parse-array-comprehension (car elems) pos)))
9454
9455 ;; another element
9456 (t
9457 (unless after-lb-or-comma
9458 (js2-report-error "msg.no.bracket.arg"))
9459 (push (js2-parse-assign-expr) elems)
9460 (setq after-lb-or-comma nil
9461 after-comma nil))))
9462 (unless js2-is-in-lhs
9463 (js2-pop-scope))
9464 pn))
9465
9466 (defun js2-parse-array-comprehension (expr pos)
9467 "Parse a JavaScript 1.7 Array Comprehension.
9468 EXPR is the first expression after the opening left-bracket.
9469 POS is the beginning of the LB token preceding EXPR.
9470 We should have just parsed the 'for' keyword before calling this function."
9471 (let (loops
9472 loop
9473 first
9474 prev
9475 filter
9476 if-pos
9477 result)
9478 (while (= (js2-peek-token) js2-FOR)
9479 (let ((prev (car loops))) ; rearrange scope chain
9480 (push (setq loop (js2-parse-array-comp-loop)) loops)
9481 (if prev ; each loop is parent scope to the next one
9482 (setf (js2-scope-parent-scope loop) prev)
9483 ; first loop takes expr scope's parent
9484 (setf (js2-scope-parent-scope (setq first loop))
9485 (js2-scope-parent-scope js2-current-scope)))))
9486 ;; set expr scope's parent to the last loop
9487 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9488 (when (= (js2-peek-token) js2-IF)
9489 (js2-consume-token)
9490 (setq if-pos (- js2-token-beg pos) ; relative
9491 filter (js2-parse-condition)))
9492 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9493 (setq result (make-js2-array-comp-node :pos pos
9494 :len (- js2-ts-cursor pos)
9495 :result expr
9496 :loops (nreverse loops)
9497 :filter (car filter)
9498 :lp (js2-relpos (second filter) pos)
9499 :rp (js2-relpos (third filter) pos)
9500 :if-pos if-pos))
9501 (apply #'js2-node-add-children result expr (car filter)
9502 (js2-array-comp-node-loops result))
9503 (setq js2-current-scope first) ; pop to the first loop
9504 result))
9505
9506 (defun js2-parse-array-comp-loop ()
9507 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9508 Last token peeked should be the initial FOR."
9509 (let ((pos js2-token-beg)
9510 (pn (make-js2-array-comp-loop-node))
9511 tt
9512 iter
9513 obj
9514 foreach-p
9515 forof-p
9516 in-pos
9517 each-pos
9518 lp
9519 rp)
9520 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9521 (js2-push-scope pn)
9522 (unwind-protect
9523 (progn
9524 (when (js2-match-token js2-NAME)
9525 (if (string= js2-ts-string "each")
9526 (progn
9527 (setq foreach-p t
9528 each-pos (- js2-token-beg pos)) ; relative
9529 (js2-record-face 'font-lock-keyword-face))
9530 (js2-report-error "msg.no.paren.for")))
9531 (if (js2-must-match js2-LP "msg.no.paren.for")
9532 (setq lp (- js2-token-beg pos)))
9533 (setq tt (js2-peek-token))
9534 (cond
9535 ((or (= tt js2-LB)
9536 (= tt js2-LC))
9537 ;; handle destructuring assignment
9538 (setq iter (js2-parse-primary-expr-lhs))
9539 (js2-define-destruct-symbols iter js2-LET
9540 'font-lock-variable-name-face t))
9541 ((js2-valid-prop-name-token tt)
9542 (js2-consume-token)
9543 (setq iter (js2-create-name-node)))
9544 (t
9545 (js2-report-error "msg.bad.var")))
9546 ;; Define as a let since we want the scope of the variable to
9547 ;; be restricted to the array comprehension
9548 (if (js2-name-node-p iter)
9549 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9550 (if (or (js2-match-token js2-IN)
9551 (and (>= js2-language-version 200)
9552 (js2-match-token js2-OF)
9553 (setq forof-p t)))
9554 (setq in-pos (- js2-token-beg pos))
9555 (js2-report-error "msg.in.after.for.name"))
9556 (setq obj (js2-parse-expr))
9557 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9558 (setq rp (- js2-token-beg pos)))
9559 (setf (js2-node-pos pn) pos
9560 (js2-node-len pn) (- js2-ts-cursor pos)
9561 (js2-array-comp-loop-node-iterator pn) iter
9562 (js2-array-comp-loop-node-object pn) obj
9563 (js2-array-comp-loop-node-in-pos pn) in-pos
9564 (js2-array-comp-loop-node-each-pos pn) each-pos
9565 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9566 (js2-array-comp-loop-node-forof-p pn) forof-p
9567 (js2-array-comp-loop-node-lp pn) lp
9568 (js2-array-comp-loop-node-rp pn) rp)
9569 (js2-node-add-children pn iter obj))
9570 (js2-pop-scope))
9571 pn))
9572
9573 (defun js2-parse-object-literal ()
9574 (let ((pos js2-token-beg)
9575 tt
9576 elems
9577 result
9578 after-comma
9579 (continue t))
9580 (while continue
9581 (setq tt (js2-peek-token))
9582 (cond
9583 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9584 ((or (js2-valid-prop-name-token tt)
9585 (= tt js2-STRING))
9586 (setq after-comma nil
9587 result (js2-parse-named-prop tt))
9588 (if (and (null result)
9589 (not js2-recover-from-parse-errors))
9590 (setq continue nil)
9591 (push result elems)))
9592 ;; {12: x} or {10.7: x}
9593 ((= tt js2-NUMBER)
9594 (js2-consume-token)
9595 (setq after-comma nil)
9596 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9597 ;; trailing comma
9598 ((= tt js2-RC)
9599 (setq continue nil)
9600 (if after-comma
9601 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9602 pos elems after-comma)))
9603 (t
9604 (js2-report-error "msg.bad.prop")
9605 (unless js2-recover-from-parse-errors
9606 (setq continue nil)))) ; end switch
9607 (if (js2-match-token js2-COMMA)
9608 (setq after-comma js2-token-end)
9609 (setq continue nil))) ; end loop
9610 (js2-must-match js2-RC "msg.no.brace.prop")
9611 (setq result (make-js2-object-node :pos pos
9612 :len (- js2-ts-cursor pos)
9613 :elems (nreverse elems)))
9614 (apply #'js2-node-add-children result (js2-object-node-elems result))
9615 result))
9616
9617 (defun js2-parse-named-prop (tt)
9618 "Parse a name, string, or getter/setter object property.
9619 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9620 (js2-consume-token)
9621 (let ((string-prop (and (= tt js2-STRING)
9622 (make-js2-string-node)))
9623 expr
9624 (ppos js2-token-beg)
9625 (pend js2-token-end)
9626 (name (js2-create-name-node))
9627 (prop js2-ts-string))
9628 (cond
9629 ;; getter/setter prop
9630 ((and (= tt js2-NAME)
9631 (= (js2-peek-token) js2-NAME)
9632 (or (string= prop "get")
9633 (string= prop "set")))
9634 (js2-consume-token)
9635 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9636 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9637 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9638 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9639 ;; abbreviated destructuring bind e.g., {a, b} = c;
9640 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9641 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9642 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9643 ;; assignment but it's difficult because it requires looking ahead of expression.
9644 ((and js2-is-in-lhs
9645 (= tt js2-NAME)
9646 (let ((ctk (js2-peek-token)))
9647 (or (= ctk js2-COMMA)
9648 (= ctk js2-RC)
9649 (js2-valid-prop-name-token ctk))))
9650 name)
9651 ;; regular prop
9652 (t
9653 (prog1
9654 (setq expr (js2-parse-plain-property (or string-prop name)))
9655 (js2-set-face ppos pend
9656 (if (js2-function-node-p
9657 (js2-object-prop-node-right expr))
9658 'font-lock-function-name-face
9659 'font-lock-variable-name-face)
9660 'record))))))
9661
9662 (defun js2-parse-plain-property (prop)
9663 "Parse a non-getter/setter property in an object literal.
9664 PROP is the node representing the property: a number, name or string."
9665 (js2-must-match js2-COLON "msg.no.colon.prop")
9666 (let* ((pos (js2-node-pos prop))
9667 (colon (- js2-token-beg pos))
9668 (expr (js2-parse-assign-expr))
9669 (result (make-js2-object-prop-node
9670 :pos pos
9671 ;; don't include last consumed token in length
9672 :len (- (+ (js2-node-pos expr)
9673 (js2-node-len expr))
9674 pos)
9675 :left prop
9676 :right expr
9677 :op-pos colon)))
9678 (js2-node-add-children result prop expr)
9679 result))
9680
9681 (defun js2-parse-getter-setter-prop (pos prop get-p)
9682 "Parse getter or setter property in an object literal.
9683 JavaScript syntax is:
9684
9685 { get foo() {...}, set foo(x) {...} }
9686
9687 and expression closure style is also supported
9688
9689 { get foo() x, set foo(x) _x = x }
9690
9691 POS is the start position of the `get' or `set' keyword.
9692 PROP is the `js2-name-node' representing the property name.
9693 GET-P is non-nil if the keyword was `get'."
9694 (let ((type (if get-p js2-GET js2-SET))
9695 result
9696 end
9697 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9698 ;; it has to be an anonymous function, as we already parsed the name
9699 (if (/= (js2-node-type fn) js2-FUNCTION)
9700 (js2-report-error "msg.bad.prop")
9701 (if (plusp (length (js2-function-name fn)))
9702 (js2-report-error "msg.bad.prop")))
9703 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9704 (setq end (js2-node-end fn)
9705 result (make-js2-getter-setter-node :type type
9706 :pos pos
9707 :len (- end pos)
9708 :left prop
9709 :right fn))
9710 (js2-node-add-children result prop fn)
9711 result))
9712
9713 (defun js2-create-name-node (&optional check-activation-p token)
9714 "Create a name node using the token info from last scanned name.
9715 In some cases we need to either synthesize a name node, or we lost
9716 the name token information by peeking. If the TOKEN parameter is
9717 not `js2-NAME', then we use the token info saved in instance vars."
9718 (let ((beg js2-token-beg)
9719 (s js2-ts-string)
9720 name)
9721 (when (/= js2-current-token js2-NAME)
9722 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9723 s js2-prev-name-token-string
9724 js2-prev-name-token-start nil
9725 js2-prev-name-token-string nil))
9726 (setq name (make-js2-name-node :pos beg
9727 :name s
9728 :len (length s)))
9729 (if check-activation-p
9730 (js2-check-activation-name s (or token js2-NAME)))
9731 name))
9732
9733 ;;; Indentation support
9734
9735 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9736 ;; Karl cleverly deduces that the desired indentation level is often a
9737 ;; function of paren/bracket/brace nesting depth, which can be determined
9738 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9739 ;; then does some equally clever checks to see if we're in the context of a
9740 ;; substatement of a possibly braceless statement keyword such as if, while,
9741 ;; or finally. This approach yields pretty good results.
9742
9743 ;; The indenter is often "wrong", however, and needs to be overridden.
9744 ;; The right long-term solution is probably to emulate (or integrate
9745 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9746 ;; parse tree from `js2-parse' is present, which is not true at the
9747 ;; moment the user is typing, computing indentation is still thousands
9748 ;; of lines of code to handle every possible syntactic edge case.
9749
9750 ;; In the meantime, the compromise solution is that we offer a "bounce
9751 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9752 ;; current line indent among various likely guess points. This approach
9753 ;; is far from perfect, but should at least make it slightly easier to
9754 ;; move the line towards its desired indentation when manually
9755 ;; overriding Karl's heuristic nesting guesser.
9756
9757 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9758 ;; extensions such as `let' and Array comprehensions. Major kudos to
9759 ;; Karl for coming up with the initial approach, which packs a lot of
9760 ;; punch for so little code.
9761
9762 (defconst js2-possibly-braceless-keywords-re
9763 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9764 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9765 "try" "while" "with" "let")))
9766 "Regular expression matching keywords that are optionally
9767 followed by an opening brace.")
9768
9769 (defconst js2-indent-operator-re
9770 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9771 (regexp-opt '("in" "instanceof") 'words))
9772 "Regular expression matching operators that affect indentation
9773 of continued expressions.")
9774
9775 (defconst js2-declaration-keyword-re
9776 (regexp-opt '("var" "let" "const") 'words)
9777 "Regular expression matching variable declaration keywords.")
9778
9779 ;; This function has horrible results if you're typing an array
9780 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9781 ;; in conjunction with electric-indent, so just disabling it.
9782 (defsubst js2-code-at-bol-p ()
9783 "Return t if the first character on line is non-whitespace."
9784 nil)
9785
9786 (defun js2-insert-and-indent (key)
9787 "Run command bound to key and indent current line. Runs the command
9788 bound to KEY in the global keymap and indents the current line."
9789 (interactive (list (this-command-keys)))
9790 (let ((cmd (lookup-key (current-global-map) key)))
9791 (if (commandp cmd)
9792 (call-interactively cmd)))
9793 ;; don't do the electric keys inside comments or strings,
9794 ;; and don't do bounce-indent with them.
9795 (let ((parse-state (syntax-ppss (point)))
9796 (js2-bounce-indent-p (js2-code-at-bol-p)))
9797 (unless (or (nth 3 parse-state)
9798 (nth 4 parse-state))
9799 (indent-according-to-mode))))
9800
9801 (defun js2-re-search-forward-inner (regexp &optional bound count)
9802 "Auxiliary function for `js2-re-search-forward'."
9803 (let (parse saved-point)
9804 (while (> count 0)
9805 (re-search-forward regexp bound)
9806 (setq parse (if saved-point
9807 (parse-partial-sexp saved-point (point))
9808 (syntax-ppss (point))))
9809 (cond ((nth 3 parse)
9810 (re-search-forward
9811 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9812 (save-excursion (end-of-line) (point)) t))
9813 ((nth 7 parse)
9814 (forward-line))
9815 ((or (nth 4 parse)
9816 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9817 (re-search-forward "\\*/"))
9818 (t
9819 (setq count (1- count))))
9820 (setq saved-point (point))))
9821 (point))
9822
9823 (defun js2-re-search-forward (regexp &optional bound noerror count)
9824 "Search forward but ignore strings and comments. Invokes
9825 `re-search-forward' but treats the buffer as if strings and
9826 comments have been removed."
9827 (let ((saved-point (point))
9828 (search-expr
9829 (cond ((null count)
9830 '(js2-re-search-forward-inner regexp bound 1))
9831 ((< count 0)
9832 '(js2-re-search-backward-inner regexp bound (- count)))
9833 ((> count 0)
9834 '(js2-re-search-forward-inner regexp bound count)))))
9835 (condition-case err
9836 (eval search-expr)
9837 (search-failed
9838 (goto-char saved-point)
9839 (unless noerror
9840 (error (error-message-string err)))))))
9841
9842 (defun js2-re-search-backward-inner (regexp &optional bound count)
9843 "Auxiliary function for `js2-re-search-backward'."
9844 (let (parse saved-point)
9845 (while (> count 0)
9846 (re-search-backward regexp bound)
9847 (setq parse (if saved-point
9848 (parse-partial-sexp saved-point (point))
9849 (syntax-ppss (point))))
9850 (cond ((nth 3 parse)
9851 (re-search-backward
9852 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9853 (save-excursion (beginning-of-line) (point)) t))
9854 ((nth 7 parse)
9855 (goto-char (nth 8 parse)))
9856 ((or (nth 4 parse)
9857 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9858 (re-search-backward "/\\*"))
9859 (t
9860 (setq count (1- count))))))
9861 (point))
9862
9863 (defun js2-re-search-backward (regexp &optional bound noerror count)
9864 "Search backward but ignore strings and comments. Invokes
9865 `re-search-backward' but treats the buffer as if strings and
9866 comments have been removed."
9867 (let ((saved-point (point))
9868 (search-expr
9869 (cond ((null count)
9870 '(js2-re-search-backward-inner regexp bound 1))
9871 ((< count 0)
9872 '(js2-re-search-forward-inner regexp bound (- count)))
9873 ((> count 0)
9874 '(js2-re-search-backward-inner regexp bound count)))))
9875 (condition-case err
9876 (eval search-expr)
9877 (search-failed
9878 (goto-char saved-point)
9879 (unless noerror
9880 (error (error-message-string err)))))))
9881
9882 (defun js2-looking-at-operator-p ()
9883 "Return non-nil if text after point is an operator (that is not
9884 a comma)."
9885 (save-match-data
9886 (and (looking-at js2-indent-operator-re)
9887 (or (not (looking-at ":"))
9888 (save-excursion
9889 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9890 (looking-at "?")))))))
9891
9892 (defun js2-continued-expression-p ()
9893 "Returns non-nil if the current line continues an expression."
9894 (save-excursion
9895 (back-to-indentation)
9896 (or (js2-looking-at-operator-p)
9897 ;; comment
9898 (and (js2-re-search-backward "\n" nil t)
9899 (progn
9900 (skip-chars-backward " \t")
9901 (unless (bolp)
9902 (backward-char)
9903 (and (js2-looking-at-operator-p)
9904 (and (progn
9905 (backward-char)
9906 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))))))
9907
9908 (defun js2-end-of-do-while-loop-p ()
9909 "Returns non-nil if word after point is `while' of a do-while
9910 statement, else returns nil. A braceless do-while statement
9911 spanning several lines requires that the start of the loop is
9912 indented to the same column as the current line."
9913 (interactive)
9914 (save-excursion
9915 (save-match-data
9916 (when (looking-at "\\s-*\\<while\\>")
9917 (if (save-excursion
9918 (skip-chars-backward "[ \t\n]*}")
9919 (looking-at "[ \t\n]*}"))
9920 (save-excursion
9921 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9922 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9923 (or (looking-at "\\<do\\>")
9924 (let ((saved-indent (current-indentation)))
9925 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9926 (/= (current-indentation) saved-indent)))
9927 (and (looking-at "[ \t]*\\<do\\>")
9928 (not (js2-re-search-forward
9929 "\\<while\\>" (point-at-eol) t))
9930 (= (current-indentation) saved-indent)))))))))
9931
9932 (defun js2-multiline-decl-indentation ()
9933 "Returns the declaration indentation column if the current line belongs
9934 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9935 (let (forward-sexp-function ; use Lisp version
9936 at-opening-bracket)
9937 (save-excursion
9938 (back-to-indentation)
9939 (when (not (looking-at js2-declaration-keyword-re))
9940 (when (looking-at js2-indent-operator-re)
9941 (goto-char (match-end 0))) ; continued expressions are ok
9942 (while (and (not at-opening-bracket)
9943 (not (bobp))
9944 (let ((pos (point)))
9945 (save-excursion
9946 (js2-backward-sws)
9947 (or (eq (char-before) ?,)
9948 (and (not (eq (char-before) ?\;))
9949 (and
9950 (prog2 (skip-chars-backward "[[:punct:]]")
9951 (looking-at js2-indent-operator-re)
9952 (js2-backward-sws))
9953 (not (eq (char-before) ?\;))))
9954 (js2-same-line pos)))))
9955 (condition-case err
9956 (backward-sexp)
9957 (scan-error (setq at-opening-bracket t))))
9958 (when (looking-at js2-declaration-keyword-re)
9959 (- (1+ (match-end 0)) (point-at-bol)))))))
9960
9961 (defun js2-ctrl-statement-indentation ()
9962 "Returns the proper indentation of the current line if it
9963 starts the body of a control statement without braces, else
9964 returns nil."
9965 (let (forward-sexp-function) ; temporarily unbind it
9966 (save-excursion
9967 (back-to-indentation)
9968 (when (and (not (js2-same-line (point-min)))
9969 (not (looking-at "{"))
9970 (js2-re-search-backward "[[:graph:]]" nil t)
9971 (not (looking-at "[{([]"))
9972 (progn
9973 (forward-char)
9974 (when (= (char-before) ?\))
9975 ;; scan-sexps sometimes throws an error
9976 (ignore-errors (backward-sexp))
9977 (skip-chars-backward " \t" (point-at-bol)))
9978 (let ((pt (point)))
9979 (back-to-indentation)
9980 (and (looking-at js2-possibly-braceless-keywords-re)
9981 (= (match-end 0) pt)
9982 (not (js2-end-of-do-while-loop-p))))))
9983 (+ (current-indentation) js2-basic-offset)))))
9984
9985 (defun js2-indent-in-array-comp (parse-status)
9986 "Return non-nil if we think we're in an array comprehension.
9987 In particular, return the buffer position of the first `for' kwd."
9988 (let ((bracket (nth 1 parse-status))
9989 (end (point)))
9990 (when bracket
9991 (save-excursion
9992 (goto-char bracket)
9993 (when (looking-at "\\[")
9994 (forward-char 1)
9995 (js2-forward-sws)
9996 (if (looking-at "[[{]")
9997 (let (forward-sexp-function) ; use lisp version
9998 (forward-sexp) ; skip destructuring form
9999 (js2-forward-sws)
10000 (if (and (/= (char-after) ?,) ; regular array
10001 (looking-at "for"))
10002 (match-beginning 0)))
10003 ;; to skip arbitrary expressions we need the parser,
10004 ;; so we'll just guess at it.
10005 (if (and (> end (point)) ; not empty literal
10006 (re-search-forward "[^,]]* \\(for\\) " end t)
10007 ;; not inside comment or string literal
10008 (let ((state (parse-partial-sexp bracket (point))))
10009 (not (or (nth 3 state) (nth 4 state)))))
10010 (match-beginning 1))))))))
10011
10012 (defun js2-array-comp-indentation (parse-status for-kwd)
10013 (if (js2-same-line for-kwd)
10014 ;; first continuation line
10015 (save-excursion
10016 (goto-char (nth 1 parse-status))
10017 (forward-char 1)
10018 (skip-chars-forward " \t")
10019 (current-column))
10020 (save-excursion
10021 (goto-char for-kwd)
10022 (current-column))))
10023
10024 (defun js2-proper-indentation (parse-status)
10025 "Return the proper indentation for the current line."
10026 (save-excursion
10027 (back-to-indentation)
10028 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10029 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
10030 (continued-expr-p (js2-continued-expression-p))
10031 (declaration-indent (and js2-pretty-multiline-declarations
10032 (js2-multiline-decl-indentation)))
10033 (bracket (nth 1 parse-status))
10034 beg)
10035 (cond
10036 ;; indent array comprehension continuation lines specially
10037 ((and bracket
10038 (>= js2-language-version 170)
10039 (not (js2-same-line bracket))
10040 (setq beg (js2-indent-in-array-comp parse-status))
10041 (>= (point) (save-excursion
10042 (goto-char beg)
10043 (point-at-bol)))) ; at or after first loop?
10044 (js2-array-comp-indentation parse-status beg))
10045
10046 (ctrl-stmt-indent)
10047
10048 ((and declaration-indent continued-expr-p)
10049 (+ declaration-indent js2-basic-offset))
10050
10051 (declaration-indent)
10052
10053 (bracket
10054 (goto-char bracket)
10055 (cond
10056 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10057 (when (save-excursion (skip-chars-backward " \t)")
10058 (looking-at ")"))
10059 (backward-list))
10060 (back-to-indentation)
10061 (and (eq js2-pretty-multiline-declarations 'all)
10062 (looking-at js2-declaration-keyword-re)
10063 (goto-char (1+ (match-end 0))))
10064 (cond (same-indent-p
10065 (current-column))
10066 (continued-expr-p
10067 (+ (current-column) (* 2 js2-basic-offset)))
10068 (t
10069 (+ (current-column) js2-basic-offset))))
10070 (t
10071 (unless same-indent-p
10072 (forward-char)
10073 (skip-chars-forward " \t"))
10074 (current-column))))
10075
10076 (continued-expr-p js2-basic-offset)
10077
10078 (t 0)))))
10079
10080 (defun js2-lineup-comment (parse-status)
10081 "Indent a multi-line block comment continuation line."
10082 (let* ((beg (nth 8 parse-status))
10083 (first-line (js2-same-line beg))
10084 (offset (save-excursion
10085 (goto-char beg)
10086 (if (looking-at "/\\*")
10087 (+ 1 (current-column))
10088 0))))
10089 (unless first-line
10090 (indent-line-to offset))))
10091
10092 (defun js2-backward-sws ()
10093 "Move backward through whitespace and comments."
10094 (interactive)
10095 (while (forward-comment -1)))
10096
10097 (defun js2-forward-sws ()
10098 "Move forward through whitespace and comments."
10099 (interactive)
10100 (while (forward-comment 1)))
10101
10102 (defsubst js2-current-indent (&optional pos)
10103 "Return column of indentation on current line.
10104 If POS is non-nil, go to that point and return indentation for that line."
10105 (save-excursion
10106 (if pos
10107 (goto-char pos))
10108 (back-to-indentation)
10109 (current-column)))
10110
10111 (defsubst js2-arglist-close ()
10112 "Return non-nil if we're on a line beginning with a close-paren/brace."
10113 (save-match-data
10114 (save-excursion
10115 (goto-char (point-at-bol))
10116 (js2-forward-sws)
10117 (looking-at "[])}]"))))
10118
10119 (defsubst js2-indent-looks-like-label-p ()
10120 (goto-char (point-at-bol))
10121 (js2-forward-sws)
10122 (looking-at (concat js2-mode-identifier-re ":")))
10123
10124 (defun js2-indent-in-objlit-p (parse-status)
10125 "Return non-nil if this looks like an object-literal entry."
10126 (let ((start (nth 1 parse-status)))
10127 (and
10128 start
10129 (save-excursion
10130 (and (zerop (forward-line -1))
10131 (not (< (point) start)) ; crossed a {} boundary
10132 (js2-indent-looks-like-label-p)))
10133 (save-excursion
10134 (js2-indent-looks-like-label-p)))))
10135
10136 ;; if prev line looks like foobar({ then we're passing an object
10137 ;; literal to a function call, and people pretty much always want to
10138 ;; de-dent back to the previous line, so move the 'basic-offset'
10139 ;; position to the front.
10140 (defsubst js2-indent-objlit-arg-p (parse-status)
10141 (save-excursion
10142 (back-to-indentation)
10143 (js2-backward-sws)
10144 (and (eq (1- (point)) (nth 1 parse-status))
10145 (eq (char-before) ?{)
10146 (progn
10147 (forward-char -1)
10148 (skip-chars-backward " \t")
10149 (eq (char-before) ?\()))))
10150
10151 (defsubst js2-indent-case-block-p ()
10152 (save-excursion
10153 (back-to-indentation)
10154 (js2-backward-sws)
10155 (goto-char (point-at-bol))
10156 (skip-chars-forward " \t")
10157 (save-match-data
10158 (looking-at "case\\s-.+:"))))
10159
10160 (defsubst js2-syntax-bol ()
10161 "Return the point at the first non-whitespace char on the line.
10162 Returns `point-at-bol' if the line is empty."
10163 (save-excursion
10164 (beginning-of-line)
10165 (skip-chars-forward " \t")
10166 (point)))
10167
10168 (defun js2-bounce-indent (normal-col parse-status backwards)
10169 "Cycle among alternate computed indentation positions.
10170 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10171 of the buffer to the current point. NORMAL-COL is the indentation
10172 column computed by the heuristic guesser based on current paren,
10173 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10174 in reverse."
10175 (let ((cur-indent (js2-current-indent))
10176 (old-buffer-undo-list buffer-undo-list)
10177 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10178 (current-line (save-excursion
10179 (forward-line 0) ; move to bol
10180 (1+ (count-lines (point-min) (point)))))
10181 positions
10182 pos
10183 main-pos
10184 anchor
10185 arglist-cont
10186 same-indent
10187 prev-line-col
10188 basic-offset
10189 computed-pos)
10190 ;; temporarily don't record undo info, if user requested this
10191 (if js2-mode-indent-inhibit-undo
10192 (setq buffer-undo-list t))
10193 (unwind-protect
10194 (progn
10195 ;; first likely point: indent from beginning of previous code line
10196 (push (setq basic-offset
10197 (+ (save-excursion
10198 (back-to-indentation)
10199 (js2-backward-sws)
10200 (back-to-indentation)
10201 (setq prev-line-col (current-column)))
10202 js2-basic-offset))
10203 positions)
10204
10205 ;; (first + epsilon) likely point: indent 2x from beginning of
10206 ;; previous code line. Some companies like this approach. Ahem.
10207 ;; Seriously, though -- 4-space indent for expression continuation
10208 ;; lines isn't a bad idea. We should eventually implement it
10209 ;; that way.
10210 (push (setq basic-offset
10211 (+ (save-excursion
10212 (back-to-indentation)
10213 (js2-backward-sws)
10214 (back-to-indentation)
10215 (setq prev-line-col (current-column)))
10216 (* 2 js2-basic-offset)))
10217 positions)
10218
10219 ;; second likely point: indent from assign-expr RHS. This
10220 ;; is just a crude guess based on finding " = " on the previous
10221 ;; line containing actual code.
10222 (setq pos (save-excursion
10223 (save-match-data
10224 (forward-line -1)
10225 (goto-char (point-at-bol))
10226 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10227 (point-at-eol) t)
10228 (goto-char (match-end 1))
10229 (skip-chars-forward " \t\r\n")
10230 (current-column)))))
10231 (when pos
10232 (incf pos js2-basic-offset)
10233 (push pos positions))
10234
10235 ;; third likely point: same indent as previous line of code.
10236 ;; Make it the first likely point if we're not on an
10237 ;; arglist-close line and previous line ends in a comma, or
10238 ;; both this line and prev line look like object-literal
10239 ;; elements.
10240 (setq pos (save-excursion
10241 (goto-char (point-at-bol))
10242 (js2-backward-sws)
10243 (back-to-indentation)
10244 (prog1
10245 (current-column)
10246 ;; while we're here, look for trailing comma
10247 (if (save-excursion
10248 (goto-char (point-at-eol))
10249 (js2-backward-sws)
10250 (eq (char-before) ?,))
10251 (setq arglist-cont (1- (point)))))))
10252 (when pos
10253 (if (and (or arglist-cont
10254 (js2-indent-in-objlit-p parse-status))
10255 (not (js2-arglist-close)))
10256 (setq same-indent pos))
10257 (push pos positions))
10258
10259 ;; fourth likely point: first preceding code with less indentation
10260 ;; than the immediately preceding code line.
10261 (setq pos (save-excursion
10262 (back-to-indentation)
10263 (js2-backward-sws)
10264 (back-to-indentation)
10265 (setq anchor (current-column))
10266 (while (and (zerop (forward-line -1))
10267 (>= (progn
10268 (back-to-indentation)
10269 (current-column))
10270 anchor)))
10271 (setq pos (current-column))))
10272 (push pos positions)
10273
10274 ;; nesting-heuristic position, main by default
10275 (push (setq main-pos normal-col) positions)
10276
10277 ;; delete duplicates and sort positions list
10278 (setq positions (sort (delete-dups positions) '<))
10279
10280 ;; comma-list continuation lines: prev line indent takes precedence
10281 (if same-indent
10282 (setq main-pos same-indent))
10283
10284 ;; common special cases where we want to indent in from previous line
10285 (if (or (js2-indent-case-block-p)
10286 (js2-indent-objlit-arg-p parse-status))
10287 (setq main-pos basic-offset))
10288
10289 ;; if bouncing backwards, reverse positions list
10290 (if backwards
10291 (setq positions (reverse positions)))
10292
10293 ;; record whether we're already sitting on one of the alternatives
10294 (setq pos (member cur-indent positions))
10295
10296 (cond
10297 ;; case 0: we're one one of the alternatives and this is the
10298 ;; first time they've pressed TAB on this line (best-guess).
10299 ((and js2-mode-indent-ignore-first-tab
10300 pos
10301 ;; first time pressing TAB on this line?
10302 (not (eq js2-mode-last-indented-line current-line)))
10303 ;; do nothing
10304 (setq computed-pos nil))
10305 ;; case 1: only one computed position => use it
10306 ((null (cdr positions))
10307 (setq computed-pos 0))
10308 ;; case 2: not on any of the computed spots => use main spot
10309 ((not pos)
10310 (setq computed-pos (js2-position main-pos positions)))
10311 ;; case 3: on last position: cycle to first position
10312 ((null (cdr pos))
10313 (setq computed-pos 0))
10314 ;; case 4: on intermediate position: cycle to next position
10315 (t
10316 (setq computed-pos (js2-position (second pos) positions))))
10317
10318 ;; see if any hooks want to indent; otherwise we do it
10319 (loop with result = nil
10320 for hook in js2-indent-hook
10321 while (null result)
10322 do
10323 (setq result (funcall hook positions computed-pos))
10324 finally do
10325 (unless (or result (null computed-pos))
10326 (indent-line-to (nth computed-pos positions)))))
10327
10328 ;; finally
10329 (if js2-mode-indent-inhibit-undo
10330 (setq buffer-undo-list old-buffer-undo-list))
10331 ;; see commentary for `js2-mode-last-indented-line'
10332 (setq js2-mode-last-indented-line current-line))))
10333
10334 (defun js2-indent-bounce-backwards ()
10335 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10336 cycles between the computed indentation positions in reverse order."
10337 (interactive)
10338 (js2-indent-line t))
10339
10340 (defsubst js2-1-line-comment-continuation-p ()
10341 "Return t if we're in a 1-line comment continuation.
10342 If so, we don't ever want to use bounce-indent."
10343 (save-excursion
10344 (save-match-data
10345 (and (progn
10346 (forward-line 0)
10347 (looking-at "\\s-*//"))
10348 (progn
10349 (forward-line -1)
10350 (forward-line 0)
10351 (when (looking-at "\\s-*$")
10352 (js2-backward-sws)
10353 (forward-line 0))
10354 (looking-at "\\s-*//"))))))
10355
10356 (defun js2-indent-line (&optional bounce-backwards)
10357 "Indent the current line as JavaScript source text."
10358 (interactive)
10359 (let (parse-status
10360 offset
10361 indent-col
10362 moved
10363 ;; don't whine about errors/warnings when we're indenting.
10364 ;; This has to be set before calling parse-partial-sexp below.
10365 (inhibit-point-motion-hooks t))
10366 (setq parse-status (save-excursion
10367 (syntax-ppss (point-at-bol)))
10368 offset (- (point) (save-excursion
10369 (back-to-indentation)
10370 (point))))
10371 (js2-with-underscore-as-word-syntax
10372 (if (nth 4 parse-status)
10373 (js2-lineup-comment parse-status)
10374 (setq indent-col (js2-proper-indentation parse-status))
10375 ;; see comments below about js2-mode-last-indented-line
10376 (cond
10377 ;; bounce-indenting is disabled during electric-key indent.
10378 ;; It doesn't work well on first line of buffer.
10379 ((and js2-bounce-indent-p
10380 (not (js2-same-line (point-min)))
10381 (not (js2-1-line-comment-continuation-p)))
10382 (js2-bounce-indent indent-col parse-status bounce-backwards))
10383 ;; just indent to the guesser's likely spot
10384 (t (indent-line-to indent-col)))
10385 (when (plusp offset)
10386 (forward-char offset))))))
10387
10388 (defun js2-indent-region (start end)
10389 "Indent the region, but don't use bounce indenting."
10390 (let ((js2-bounce-indent-p nil)
10391 (indent-region-function nil)
10392 (after-change-functions (remq 'js2-mode-edit
10393 after-change-functions)))
10394 (indent-region start end nil) ; nil for byte-compiler
10395 (js2-mode-edit start end (- end start))))
10396
10397 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10398
10399 ;;;###autoload
10400 (defun js2-mode ()
10401 "Major mode for editing JavaScript code."
10402 (interactive)
10403 (kill-all-local-variables)
10404 (set-syntax-table js2-mode-syntax-table)
10405 (use-local-map js2-mode-map)
10406 (make-local-variable 'comment-start)
10407 (make-local-variable 'comment-end)
10408 (make-local-variable 'comment-start-skip)
10409 (setq major-mode 'js2-mode
10410 mode-name "JavaScript-IDE"
10411 comment-start "//" ; used by comment-region; don't change it
10412 comment-end "")
10413 (setq local-abbrev-table js2-mode-abbrev-table)
10414 (set (make-local-variable 'max-lisp-eval-depth)
10415 (max max-lisp-eval-depth 3000))
10416 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10417 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10418
10419 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10420 ;; on most platforms other than the one I originally wrote it on.
10421 ;; So it's back to `c-fill-paragraph'.
10422 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10423
10424 (add-hook 'before-save-hook #'js2-before-save nil t)
10425 (set (make-local-variable 'next-error-function) #'js2-next-error)
10426 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10427 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10428 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10429 ;; for characters inside regexp literals.
10430 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10431 ;; this is necessary to make `show-paren-function' work properly
10432 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10433 ;; needed for M-x rgrep, among other things
10434 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10435
10436 ;; some variables needed by cc-engine for paragraph-fill, etc.
10437 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10438 c-comment-start-regexp "/[*/]\\|\\s|"
10439 c-line-comment-starter "//"
10440 c-paragraph-start js2-paragraph-start
10441 c-paragraph-separate "$"
10442 comment-start-skip js2-comment-start-skip
10443 c-syntactic-ws-start js2-syntactic-ws-start
10444 c-syntactic-ws-end js2-syntactic-ws-end
10445 c-syntactic-eol js2-syntactic-eol)
10446
10447 (let ((c-buffer-is-cc-mode t))
10448 ;; Copied from `js-mode'. Also see Bug#6071.
10449 (make-local-variable 'paragraph-start)
10450 (make-local-variable 'paragraph-separate)
10451 (make-local-variable 'paragraph-ignore-fill-prefix)
10452 (make-local-variable 'adaptive-fill-mode)
10453 (make-local-variable 'adaptive-fill-regexp)
10454 (c-setup-paragraph-variables))
10455
10456 (setq js2-default-externs
10457 (append js2-ecma-262-externs
10458 (if js2-include-browser-externs
10459 js2-browser-externs)
10460 (if js2-include-gears-externs
10461 js2-gears-externs)
10462 (if js2-include-rhino-externs
10463 js2-rhino-externs)))
10464
10465 ;; We do our own syntax highlighting based on the parse tree.
10466 ;; However, we want minor modes that add keywords to highlight properly
10467 ;; (examples: doxymacs, column-marker).
10468 ;; To customize highlighted keywords, use `font-lock-add-keywords'.
10469 (setq font-lock-defaults '(nil t))
10470
10471 ;; Experiment: make reparse-delay longer for longer files.
10472 (if (plusp js2-dynamic-idle-timer-adjust)
10473 (setq js2-idle-timer-delay
10474 (* js2-idle-timer-delay
10475 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10476
10477 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10478 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10479 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10480 (imenu-add-to-menubar (concat "IM-" mode-name))
10481 (when js2-mirror-mode
10482 (js2-enter-mirror-mode))
10483 (add-to-invisibility-spec '(js2-outline . t))
10484 (set (make-local-variable 'line-move-ignore-invisible) t)
10485 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10486
10487 (if (fboundp 'run-mode-hooks)
10488 (run-mode-hooks 'js2-mode-hook)
10489 (run-hooks 'js2-mode-hook))
10490
10491 (setq js2-mode-functions-hidden nil
10492 js2-mode-comments-hidden nil
10493 js2-mode-buffer-dirty-p t
10494 js2-mode-parsing nil)
10495 (js2-reparse))
10496
10497 (defun js2-mode-exit ()
10498 "Exit `js2-mode' and clean up."
10499 (interactive)
10500 (when js2-mode-node-overlay
10501 (delete-overlay js2-mode-node-overlay)
10502 (setq js2-mode-node-overlay nil))
10503 (js2-remove-overlays)
10504 (setq js2-mode-ast nil)
10505 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10506 (remove-from-invisibility-spec '(js2-outline . t))
10507 (js2-mode-show-all)
10508 (js2-with-unmodifying-text-property-changes
10509 (js2-clear-face (point-min) (point-max))))
10510
10511 (defun js2-before-save ()
10512 "Clean up whitespace before saving file.
10513 You can disable this by customizing `js2-cleanup-whitespace'."
10514 (when js2-cleanup-whitespace
10515 (let ((col (current-column)))
10516 (delete-trailing-whitespace)
10517 ;; don't change trailing whitespace on current line
10518 (unless (eq (current-column) col)
10519 (indent-to col)))))
10520
10521 (defsubst js2-mode-reset-timer ()
10522 "Cancel any existing parse timer and schedule a new one."
10523 (if js2-mode-parse-timer
10524 (cancel-timer js2-mode-parse-timer))
10525 (setq js2-mode-parsing nil)
10526 (setq js2-mode-parse-timer
10527 (run-with-idle-timer js2-idle-timer-delay nil
10528 #'js2-mode-idle-reparse (current-buffer))))
10529
10530 (defun js2-mode-idle-reparse (buffer)
10531 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10532 it to be reparsed when the buffer is selected."
10533 (if (eq buffer (current-buffer))
10534 (js2-reparse)
10535 ;; reparse when the buffer is selected again
10536 (with-current-buffer buffer
10537 (add-hook 'window-configuration-change-hook
10538 #'js2-mode-idle-reparse-inner
10539 nil t))))
10540
10541 (defun js2-mode-idle-reparse-inner ()
10542 (remove-hook 'window-configuration-change-hook
10543 #'js2-mode-idle-reparse-inner
10544 t)
10545 (js2-reparse))
10546
10547 (defun js2-mode-edit (beg end len)
10548 "Schedule a new parse after buffer is edited.
10549 Buffer edit spans from BEG to END and is of length LEN.
10550 Also clears the `js2-magic' bit on autoinserted parens/brackets
10551 if the edit occurred on a line different from the magic paren."
10552 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10553 (line (if magic-pos (line-number-at-pos magic-pos))))
10554 (and line
10555 (or (/= (line-number-at-pos beg) line)
10556 (and (> 0 len)
10557 (/= (line-number-at-pos end) line)))
10558 (js2-mode-mundanify-parens)))
10559 (setq js2-mode-buffer-dirty-p t)
10560 (js2-mode-hide-overlay)
10561 (js2-mode-reset-timer))
10562
10563 (defun js2-reparse (&optional force)
10564 "Re-parse current buffer after user finishes some data entry.
10565 If we get any user input while parsing, including cursor motion,
10566 we discard the parse and reschedule it. If FORCE is nil, then the
10567 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10568 (let (time
10569 interrupted-p
10570 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10571 (unless js2-mode-parsing
10572 (setq js2-mode-parsing t)
10573 (unwind-protect
10574 (when (or js2-mode-buffer-dirty-p force)
10575 (js2-remove-overlays)
10576 (js2-with-unmodifying-text-property-changes
10577 (setq js2-mode-buffer-dirty-p nil
10578 js2-mode-fontifications nil
10579 js2-mode-deferred-properties nil)
10580 (if js2-mode-verbose-parse-p
10581 (message "parsing..."))
10582 (setq time
10583 (js2-time
10584 (setq interrupted-p
10585 (catch 'interrupted
10586 (setq js2-mode-ast (js2-parse))
10587 ;; if parsing is interrupted, comments and regex
10588 ;; literals stay ignored by `parse-partial-sexp'
10589 (remove-text-properties (point-min) (point-max)
10590 '(syntax-table))
10591 (js2-mode-apply-deferred-properties)
10592 (js2-mode-remove-suppressed-warnings)
10593 (js2-mode-show-warnings)
10594 (js2-mode-show-errors)
10595 (js2-mode-highlight-magic-parens)
10596 (if (>= js2-highlight-level 1)
10597 (js2-highlight-jsdoc js2-mode-ast))
10598 nil))))
10599 (if interrupted-p
10600 (progn
10601 ;; unfinished parse => try again
10602 (setq js2-mode-buffer-dirty-p t)
10603 (js2-mode-reset-timer))
10604 (if js2-mode-verbose-parse-p
10605 (message "Parse time: %s" time)))))
10606 (setq js2-mode-parsing nil)
10607 (unless interrupted-p
10608 (setq js2-mode-parse-timer nil))))))
10609
10610 (defun js2-mode-show-node ()
10611 "Debugging aid: highlight selected AST node on mouse click."
10612 (interactive)
10613 (let ((node (js2-node-at-point))
10614 beg
10615 end)
10616 (when js2-mode-show-overlay
10617 (if (null node)
10618 (message "No node found at location %s" (point))
10619 (setq beg (js2-node-abs-pos node)
10620 end (+ beg (js2-node-len node)))
10621 (if js2-mode-node-overlay
10622 (move-overlay js2-mode-node-overlay beg end)
10623 (setq js2-mode-node-overlay (make-overlay beg end))
10624 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10625 (js2-with-unmodifying-text-property-changes
10626 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10627 (message "%s, parent: %s"
10628 (js2-node-short-name node)
10629 (if (js2-node-parent node)
10630 (js2-node-short-name (js2-node-parent node))
10631 "nil"))))))
10632
10633 (defun js2-mode-hide-overlay (&optional p1 p2)
10634 "Remove the debugging overlay when the point moves.
10635 P1 and P2 are the old and new values of point, respectively."
10636 (when js2-mode-node-overlay
10637 (let ((beg (overlay-start js2-mode-node-overlay))
10638 (end (overlay-end js2-mode-node-overlay)))
10639 ;; Sometimes we're called spuriously.
10640 (unless (and p2
10641 (>= p2 beg)
10642 (<= p2 end))
10643 (js2-with-unmodifying-text-property-changes
10644 (remove-text-properties beg end '(point-left nil)))
10645 (delete-overlay js2-mode-node-overlay)
10646 (setq js2-mode-node-overlay nil)))))
10647
10648 (defun js2-mode-reset ()
10649 "Debugging helper: reset everything."
10650 (interactive)
10651 (js2-mode-exit)
10652 (js2-mode))
10653
10654 (defsubst js2-mode-show-warn-or-err (e face)
10655 "Highlight a warning or error E with FACE.
10656 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10657 (let* ((key (first e))
10658 (beg (second e))
10659 (end (+ beg (third e)))
10660 ;; Don't inadvertently go out of bounds.
10661 (beg (max (point-min) (min beg (point-max))))
10662 (end (max (point-min) (min end (point-max))))
10663 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10664 (ovl (make-overlay beg end)))
10665 (overlay-put ovl 'font-lock-face face)
10666 (overlay-put ovl 'js2-error t)
10667 (put-text-property beg end 'help-echo (js2-get-msg key))
10668 (put-text-property beg end 'point-entered #'js2-echo-error)))
10669
10670 (defun js2-remove-overlays ()
10671 "Remove overlays from buffer that have a `js2-error' property."
10672 (let ((beg (point-min))
10673 (end (point-max)))
10674 (save-excursion
10675 (dolist (o (overlays-in beg end))
10676 (when (overlay-get o 'js2-error)
10677 (delete-overlay o))))))
10678
10679 (defun js2-error-at-point (&optional pos)
10680 "Return non-nil if there's an error overlay at POS.
10681 Defaults to point."
10682 (loop with pos = (or pos (point))
10683 for o in (overlays-at pos)
10684 thereis (overlay-get o 'js2-error)))
10685
10686 (defun js2-mode-apply-deferred-properties ()
10687 "Apply fontifications and other text properties recorded during parsing."
10688 (when (plusp js2-highlight-level)
10689 ;; We defer clearing faces as long as possible to eliminate flashing.
10690 (js2-clear-face (point-min) (point-max))
10691 ;; Have to reverse the recorded fontifications list so that errors
10692 ;; and warnings overwrite the normal fontifications.
10693 (dolist (f (nreverse js2-mode-fontifications))
10694 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10695 (setq js2-mode-fontifications nil))
10696 (dolist (p js2-mode-deferred-properties)
10697 (apply #'put-text-property p))
10698 (setq js2-mode-deferred-properties nil))
10699
10700 (defun js2-mode-show-errors ()
10701 "Highlight syntax errors."
10702 (when js2-mode-show-parse-errors
10703 (dolist (e (js2-ast-root-errors js2-mode-ast))
10704 (js2-mode-show-warn-or-err e 'js2-error-face))))
10705
10706 (defun js2-mode-remove-suppressed-warnings ()
10707 "Take suppressed warnings out of the AST warnings list.
10708 This ensures that the counts and `next-error' are correct."
10709 (setf (js2-ast-root-warnings js2-mode-ast)
10710 (js2-delete-if
10711 (lambda (e)
10712 (let ((key (caar e)))
10713 (or
10714 (and (not js2-strict-trailing-comma-warning)
10715 (string-match "trailing\\.comma" key))
10716 (and (not js2-strict-cond-assign-warning)
10717 (string= key "msg.equal.as.assign"))
10718 (and js2-missing-semi-one-line-override
10719 (string= key "msg.missing.semi")
10720 (let* ((beg (second e))
10721 (node (js2-node-at-point beg))
10722 (fn (js2-mode-find-parent-fn node))
10723 (body (and fn (js2-function-node-body fn)))
10724 (lc (and body (js2-node-abs-pos body)))
10725 (rc (and lc (+ lc (js2-node-len body)))))
10726 (and fn
10727 (or (null body)
10728 (save-excursion
10729 (goto-char beg)
10730 (and (js2-same-line lc)
10731 (js2-same-line rc))))))))))
10732 (js2-ast-root-warnings js2-mode-ast))))
10733
10734 (defun js2-mode-show-warnings ()
10735 "Highlight strict-mode warnings."
10736 (when js2-mode-show-strict-warnings
10737 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10738 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10739
10740 (defun js2-echo-error (old-point new-point)
10741 "Called by point-motion hooks."
10742 (let ((msg (get-text-property new-point 'help-echo)))
10743 (if (and msg (or (not (current-message))
10744 (string= (current-message) "Quit")))
10745 (message msg))))
10746
10747 (defalias #'js2-echo-help #'js2-echo-error)
10748
10749 (defun js2-enter-key ()
10750 "Handle user pressing the Enter key."
10751 (interactive)
10752 (let ((parse-status (save-excursion
10753 (syntax-ppss (point))))
10754 (js2-bounce-indent-p nil))
10755 (cond
10756 ;; check if we're inside a string
10757 ((nth 3 parse-status)
10758 (if js2-concat-multiline-strings
10759 (js2-mode-split-string parse-status)
10760 (insert "\n")))
10761 ;; check if inside a block comment
10762 ((nth 4 parse-status)
10763 (js2-mode-extend-comment))
10764 (t
10765 ;; should probably figure out what the mode-map says we should do
10766 (if js2-indent-on-enter-key
10767 (js2-indent-line))
10768 (insert "\n")
10769 (if js2-enter-indents-newline
10770 (js2-indent-line))))))
10771
10772 (defun js2-mode-split-string (parse-status)
10773 "Turn a newline in mid-string into a string concatenation.
10774 PARSE-STATUS is as documented in `parse-partial-sexp'."
10775 (let* ((col (current-column))
10776 (quote-char (nth 3 parse-status))
10777 (quote-string (string quote-char))
10778 (string-beg (nth 8 parse-status))
10779 (at-eol (eq js2-concat-multiline-strings 'eol))
10780 (indent (save-match-data
10781 (or
10782 (save-excursion
10783 (back-to-indentation)
10784 (if (looking-at "\\+")
10785 (current-column)))
10786 (save-excursion
10787 (goto-char string-beg)
10788 (if (looking-back "\\+\\s-+")
10789 (goto-char (match-beginning 0)))
10790 (current-column))))))
10791 (insert quote-char)
10792 (if at-eol
10793 (insert " +\n")
10794 (insert "\n"))
10795 ;; FIXME: This does not match the behavior of `js2-indent-line'.
10796 (indent-to indent)
10797 (unless at-eol
10798 (insert "+ "))
10799 (insert quote-string)
10800 (when (eolp)
10801 (insert quote-string)
10802 (backward-char 1))))
10803
10804 (defun js2-mode-extend-comment ()
10805 "Indent the line and, when inside a comment block, add comment prefix."
10806 (let (star single col first-line needs-close)
10807 (save-excursion
10808 (back-to-indentation)
10809 (cond
10810 ((looking-at "\\*[^/]")
10811 (setq star t
10812 col (current-column)))
10813 ((looking-at "/\\*")
10814 (setq star t
10815 first-line t
10816 col (1+ (current-column))))
10817 ((looking-at "//")
10818 (setq single t
10819 col (current-column)))))
10820 ;; Heuristic for whether we need to close the comment:
10821 ;; if we've got a parse error here, assume it's an unterminated
10822 ;; comment.
10823 (setq needs-close
10824 (or
10825 (eq (get-text-property (1- (point)) 'point-entered)
10826 'js2-echo-error)
10827 ;; The heuristic above doesn't work well when we're
10828 ;; creating a comment and there's another one downstream,
10829 ;; as our parser thinks this one ends at the end of the
10830 ;; next one. (You can have a /* inside a js block comment.)
10831 ;; So just close it if the next non-ws char isn't a *.
10832 (and first-line
10833 (eolp)
10834 (save-excursion
10835 (skip-chars-forward " \t\r\n")
10836 (not (eq (char-after) ?*))))))
10837 (insert "\n")
10838 (cond
10839 (star
10840 (indent-to col)
10841 (insert "* ")
10842 (if (and first-line needs-close)
10843 (save-excursion
10844 (insert "\n")
10845 (indent-to col)
10846 (insert "*/"))))
10847 ((and single
10848 (save-excursion
10849 (and (zerop (forward-line 1))
10850 (looking-at "\\s-*//"))))
10851 (indent-to col)
10852 (insert "// "))
10853 ;; don't need to extend the comment after all
10854 (js2-enter-indents-newline
10855 (js2-indent-line)))))
10856
10857 (defun js2-beginning-of-line ()
10858 "Toggles point between bol and first non-whitespace char in line.
10859 Also moves past comment delimiters when inside comments."
10860 (interactive)
10861 (let (node beg)
10862 (cond
10863 ((bolp)
10864 (back-to-indentation))
10865 ((looking-at "//")
10866 (skip-chars-forward "/ \t"))
10867 ((and (eq (char-after) ?*)
10868 (setq node (js2-comment-at-point))
10869 (memq (js2-comment-node-format node) '(jsdoc block))
10870 (save-excursion
10871 (skip-chars-backward " \t")
10872 (bolp)))
10873 (skip-chars-forward "\* \t"))
10874 (t
10875 (goto-char (point-at-bol))))))
10876
10877 (defun js2-end-of-line ()
10878 "Toggles point between eol and last non-whitespace char in line."
10879 (interactive)
10880 (if (eolp)
10881 (skip-chars-backward " \t")
10882 (goto-char (point-at-eol))))
10883
10884 (defun js2-enter-mirror-mode()
10885 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10886 on insertion."
10887 (interactive)
10888 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10889 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10890 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10891 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10892 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10893 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10894 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10895 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10896
10897 (defun js2-leave-mirror-mode()
10898 "Turns off mirror mode."
10899 (interactive)
10900 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10901 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10902
10903 (defsubst js2-mode-inside-string ()
10904 "Return non-nil if inside a string.
10905 Actually returns the quote character that begins the string."
10906 (let ((parse-state (save-excursion
10907 (syntax-ppss (point)))))
10908 (nth 3 parse-state)))
10909
10910 (defsubst js2-mode-inside-comment-or-string ()
10911 "Return non-nil if inside a comment or string."
10912 (or
10913 (let ((comment-start
10914 (save-excursion
10915 (goto-char (point-at-bol))
10916 (if (re-search-forward "//" (point-at-eol) t)
10917 (match-beginning 0)))))
10918 (and comment-start
10919 (<= comment-start (point))))
10920 (let ((parse-state (save-excursion
10921 (syntax-ppss (point)))))
10922 (or (nth 3 parse-state)
10923 (nth 4 parse-state)))))
10924
10925 (defsubst js2-make-magic-delimiter (delim &optional pos)
10926 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10927 Sets value of `js2-magic' text property to line number at POS."
10928 (propertize delim
10929 'js2-magic (line-number-at-pos pos)
10930 'font-lock-face 'js2-magic-paren-face))
10931
10932 (defun js2-mode-match-delimiter (open close)
10933 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10934 The rule we use, which as far as we can tell is how Eclipse works,
10935 is that we insert the match if we're not in a comment or string,
10936 and the next non-whitespace character is either punctuation or
10937 occurs on another line."
10938 (insert open)
10939 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10940 (not (js2-mode-inside-comment-or-string)))
10941 (save-excursion
10942 (insert (js2-make-magic-delimiter close)))
10943 (when js2-auto-indent-p
10944 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10945 (js2-indent-line)))))
10946
10947 (defun js2-mode-match-bracket ()
10948 "Insert matching bracket."
10949 (interactive)
10950 (js2-mode-match-delimiter "[" "]"))
10951
10952 (defun js2-mode-match-paren ()
10953 "Insert matching paren unless already inserted."
10954 (interactive)
10955 (js2-mode-match-delimiter "(" ")"))
10956
10957 (defun js2-mode-match-curly (arg)
10958 "Insert matching curly-brace.
10959 With prefix arg, no formatting or indentation will occur -- the close-brace
10960 is simply inserted directly at the point."
10961 (interactive "p")
10962 (let (try-pos)
10963 (cond
10964 (current-prefix-arg
10965 (js2-mode-match-delimiter "{" "}"))
10966 ((and js2-auto-insert-catch-block
10967 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10968 (point-at-bol))
10969 (match-beginning 1))))
10970 (js2-insert-catch-skel try-pos))
10971 (t
10972 ;; Otherwise try to do something smarter.
10973 (insert "{")
10974 (unless (or (not (looking-at "\\s-*$"))
10975 (save-excursion
10976 (skip-chars-forward " \t\r\n")
10977 (and (looking-at "}")
10978 (js2-error-at-point)))
10979 (js2-mode-inside-comment-or-string))
10980 (undo-boundary)
10981 ;; absolutely mystifying bug: when inserting the next "\n",
10982 ;; the buffer-undo-list is given two new entries: the inserted range,
10983 ;; and the incorrect position of the point. It's recorded incorrectly
10984 ;; as being before the opening "{", not after it. But it's recorded
10985 ;; as the correct value if you're debugging `js2-mode-match-curly'
10986 ;; in edebug. I have no idea why it's doing this, but incrementing
10987 ;; the inserted position fixes the problem, so that the undo takes us
10988 ;; back to just after the user-inserted "{".
10989 (insert "\n")
10990 (ignore-errors
10991 (incf (cadr buffer-undo-list)))
10992 (js2-indent-line)
10993 (save-excursion
10994 (insert "\n}")
10995 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10996 (js2-indent-line))))))))
10997
10998 (defun js2-insert-catch-skel (try-pos)
10999 "Complete a try/catch block after inserting a { following a try keyword.
11000 Rationale is that a try always needs a catch or a finally, and the catch is
11001 the more likely of the two.
11002
11003 TRY-POS is the buffer position of the try keyword. The open-curly should
11004 already have been inserted."
11005 (insert "{")
11006 (let ((try-col (save-excursion
11007 (goto-char try-pos)
11008 (current-column))))
11009 (insert "\n")
11010 (undo-boundary)
11011 (js2-indent-line) ;; indent the blank line where cursor will end up
11012 (save-excursion
11013 (insert "\n")
11014 (indent-to try-col)
11015 (insert "} catch (x) {\n\n")
11016 (indent-to try-col)
11017 (insert "}"))))
11018
11019 (defun js2-mode-highlight-magic-parens ()
11020 "Re-highlight magic parens after parsing nukes the 'face prop."
11021 (let ((beg (point-min))
11022 end)
11023 (while (setq beg (next-single-property-change beg 'js2-magic))
11024 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11025 (if (get-text-property beg 'js2-magic)
11026 (js2-with-unmodifying-text-property-changes
11027 (put-text-property beg (or end (1+ beg))
11028 'font-lock-face 'js2-magic-paren-face))))))
11029
11030 (defun js2-mode-mundanify-parens ()
11031 "Clear all magic parens and brackets."
11032 (let ((beg (point-min))
11033 end)
11034 (while (setq beg (next-single-property-change beg 'js2-magic))
11035 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11036 (remove-text-properties beg (or end (1+ beg))
11037 '(js2-magic face)))))
11038
11039 (defsubst js2-match-quote (quote-string)
11040 (let ((start-quote (js2-mode-inside-string)))
11041 (cond
11042 ;; inside a comment - don't do quote-matching, since we can't
11043 ;; reliably figure out if we're in a string inside the comment
11044 ((js2-comment-at-point)
11045 (insert quote-string))
11046 ((not start-quote)
11047 ;; not in string => insert matched quotes
11048 (insert quote-string)
11049 ;; exception: if we're just before a word, don't double it.
11050 (unless (looking-at "[^ \t\r\n]")
11051 (save-excursion
11052 (insert quote-string))))
11053 ((looking-at quote-string)
11054 (if (looking-back "[^\\]\\\\")
11055 (insert quote-string)
11056 (forward-char 1)))
11057 ((and js2-mode-escape-quotes
11058 (save-excursion
11059 (save-match-data
11060 (re-search-forward quote-string (point-at-eol) t))))
11061 ;; inside terminated string, escape quote (unless already escaped)
11062 (insert (if (looking-back "[^\\]\\\\")
11063 quote-string
11064 (concat "\\" quote-string))))
11065 (t
11066 (insert quote-string))))) ; else terminate the string
11067
11068 (defun js2-mode-match-single-quote ()
11069 "Insert matching single-quote."
11070 (interactive)
11071 (let ((parse-status (syntax-ppss (point))))
11072 ;; don't match inside comments, since apostrophe is more common
11073 (if (nth 4 parse-status)
11074 (insert "'")
11075 (js2-match-quote "'"))))
11076
11077 (defun js2-mode-match-double-quote ()
11078 "Insert matching double-quote."
11079 (interactive)
11080 (js2-match-quote "\""))
11081
11082 ;; Eclipse works as follows:
11083 ;; * type an open-paren and it auto-inserts close-paren
11084 ;; - auto-inserted paren gets a green bracket
11085 ;; - green bracket means typing close-paren there will skip it
11086 ;; * if you insert any text on a different line, it turns off
11087 (defun js2-mode-magic-close-paren ()
11088 "Skip over close-paren rather than inserting, where appropriate."
11089 (interactive)
11090 (let* ((here (point))
11091 (parse-status (syntax-ppss here))
11092 (open-pos (nth 1 parse-status))
11093 (close last-input-event)
11094 (open (cond
11095 ((eq close ?\))
11096 ?\()
11097 ((eq close ?\])
11098 ?\[)
11099 ((eq close ?})
11100 ?{)
11101 (t nil))))
11102 (if (and (eq (char-after) close)
11103 (eq open (char-after open-pos))
11104 (js2-same-line open-pos)
11105 (get-text-property here 'js2-magic))
11106 (progn
11107 (remove-text-properties here (1+ here) '(js2-magic face))
11108 (forward-char 1))
11109 (insert-char close 1))
11110 (blink-matching-open)))
11111
11112 (defun js2-mode-wait-for-parse (callback)
11113 "Invoke CALLBACK when parsing is finished.
11114 If parsing is already finished, calls CALLBACK immediately."
11115 (if (not js2-mode-buffer-dirty-p)
11116 (funcall callback)
11117 (push callback js2-mode-pending-parse-callbacks)
11118 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11119
11120 (defun js2-mode-parse-finished ()
11121 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11122 ;; We can't let errors propagate up, since it prevents the
11123 ;; `js2-parse' method from completing normally and returning
11124 ;; the ast, which makes things mysteriously not work right.
11125 (unwind-protect
11126 (dolist (cb js2-mode-pending-parse-callbacks)
11127 (condition-case err
11128 (funcall cb)
11129 (error (message "%s" err))))
11130 (setq js2-mode-pending-parse-callbacks nil)))
11131
11132 (defun js2-mode-flag-region (from to flag)
11133 "Hide or show text from FROM to TO, according to FLAG.
11134 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11135 Returns the created overlay if FLAG is non-nil."
11136 (remove-overlays from to 'invisible 'js2-outline)
11137 (when flag
11138 (let ((o (make-overlay from to)))
11139 (overlay-put o 'invisible 'js2-outline)
11140 (overlay-put o 'isearch-open-invisible
11141 'js2-isearch-open-invisible)
11142 o)))
11143
11144 ;; Function to be set as an outline-isearch-open-invisible' property
11145 ;; to the overlay that makes the outline invisible (see
11146 ;; `js2-mode-flag-region').
11147 (defun js2-isearch-open-invisible (overlay)
11148 ;; We rely on the fact that isearch places point on the matched text.
11149 (js2-mode-show-element))
11150
11151 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11152 "Return cons cell of bounds of folding overlay at POS.
11153 Returns nil if not found."
11154 (let ((overlays (overlays-at (or pos (point))))
11155 o)
11156 (while (and overlays
11157 (not o))
11158 (if (overlay-get (car overlays) 'invisible)
11159 (setq o (car overlays))
11160 (setq overlays (cdr overlays))))
11161 (if o
11162 (cons (overlay-start o) (overlay-end o)))))
11163
11164 (defun js2-mode-function-at-point (&optional pos)
11165 "Return the innermost function node enclosing current point.
11166 Returns nil if point is not in a function."
11167 (let ((node (js2-node-at-point pos)))
11168 (while (and node (not (js2-function-node-p node)))
11169 (setq node (js2-node-parent node)))
11170 (if (js2-function-node-p node)
11171 node)))
11172
11173 (defun js2-mode-toggle-element ()
11174 "Hide or show the foldable element at the point."
11175 (interactive)
11176 (let (comment fn pos)
11177 (save-excursion
11178 (save-match-data
11179 (cond
11180 ;; /* ... */ comment?
11181 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11182 (if (js2-mode-invisible-overlay-bounds
11183 (setq pos (+ 3 (js2-node-abs-pos comment))))
11184 (progn
11185 (goto-char pos)
11186 (js2-mode-show-element))
11187 (js2-mode-hide-element)))
11188 ;; //-comment?
11189 ((save-excursion
11190 (back-to-indentation)
11191 (looking-at js2-mode-//-comment-re))
11192 (js2-mode-toggle-//-comment))
11193 ;; function?
11194 ((setq fn (js2-mode-function-at-point))
11195 (setq pos (and (js2-function-node-body fn)
11196 (js2-node-abs-pos (js2-function-node-body fn))))
11197 (goto-char (1+ pos))
11198 (if (js2-mode-invisible-overlay-bounds)
11199 (js2-mode-show-element)
11200 (js2-mode-hide-element)))
11201 (t
11202 (message "Nothing at point to hide or show")))))))
11203
11204 (defun js2-mode-hide-element ()
11205 "Fold/hide contents of a block, showing ellipses.
11206 Show the hidden text with \\[js2-mode-show-element]."
11207 (interactive)
11208 (if js2-mode-buffer-dirty-p
11209 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11210 (let (node body beg end)
11211 (cond
11212 ((js2-mode-invisible-overlay-bounds)
11213 (message "already hidden"))
11214 (t
11215 (setq node (js2-node-at-point))
11216 (cond
11217 ((js2-block-comment-p node)
11218 (js2-mode-hide-comment node))
11219 (t
11220 (while (and node (not (js2-function-node-p node)))
11221 (setq node (js2-node-parent node)))
11222 (if (and node
11223 (setq body (js2-function-node-body node)))
11224 (progn
11225 (setq beg (js2-node-abs-pos body)
11226 end (+ beg (js2-node-len body)))
11227 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11228 (message "No collapsable element found at point"))))))))
11229
11230 (defun js2-mode-show-element ()
11231 "Show the hidden element at current point."
11232 (interactive)
11233 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11234 (if bounds
11235 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11236 (message "Nothing to un-hide"))))
11237
11238 (defun js2-mode-show-all ()
11239 "Show all of the text in the buffer."
11240 (interactive)
11241 (js2-mode-flag-region (point-min) (point-max) nil))
11242
11243 (defun js2-mode-toggle-hide-functions ()
11244 (interactive)
11245 (if js2-mode-functions-hidden
11246 (js2-mode-show-functions)
11247 (js2-mode-hide-functions)))
11248
11249 (defun js2-mode-hide-functions ()
11250 "Hides all non-nested function bodies in the buffer.
11251 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11252 to open an individual entry."
11253 (interactive)
11254 (if js2-mode-buffer-dirty-p
11255 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11256 (if (null js2-mode-ast)
11257 (message "Oops - parsing failed")
11258 (setq js2-mode-functions-hidden t)
11259 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11260
11261 (defun js2-mode-function-hider (n endp)
11262 (when (not endp)
11263 (let ((tt (js2-node-type n))
11264 body beg end)
11265 (cond
11266 ((and (= tt js2-FUNCTION)
11267 (setq body (js2-function-node-body n)))
11268 (setq beg (js2-node-abs-pos body)
11269 end (+ beg (js2-node-len body)))
11270 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11271 nil) ; don't process children of function
11272 (t
11273 t))))) ; keep processing other AST nodes
11274
11275 (defun js2-mode-show-functions ()
11276 "Un-hide any folded function bodies in the buffer."
11277 (interactive)
11278 (setq js2-mode-functions-hidden nil)
11279 (save-excursion
11280 (goto-char (point-min))
11281 (while (/= (goto-char (next-overlay-change (point)))
11282 (point-max))
11283 (dolist (o (overlays-at (point)))
11284 (when (and (overlay-get o 'invisible)
11285 (not (overlay-get o 'comment)))
11286 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11287
11288 (defun js2-mode-hide-comment (n)
11289 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11290 3 ; /**
11291 2)) ; /*
11292 (beg (+ (js2-node-abs-pos n) head))
11293 (end (- (+ beg (js2-node-len n)) head 2))
11294 (o (js2-mode-flag-region beg end 'hide)))
11295 (overlay-put o 'comment t)))
11296
11297 (defun js2-mode-toggle-hide-comments ()
11298 "Folds all block comments in the buffer.
11299 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11300 to open an individual entry."
11301 (interactive)
11302 (if js2-mode-comments-hidden
11303 (js2-mode-show-comments)
11304 (js2-mode-hide-comments)))
11305
11306 (defun js2-mode-hide-comments ()
11307 (interactive)
11308 (if js2-mode-buffer-dirty-p
11309 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11310 (if (null js2-mode-ast)
11311 (message "Oops - parsing failed")
11312 (setq js2-mode-comments-hidden t)
11313 (dolist (n (js2-ast-root-comments js2-mode-ast))
11314 (let ((format (js2-comment-node-format n)))
11315 (when (js2-block-comment-p n)
11316 (js2-mode-hide-comment n))))
11317 (js2-mode-hide-//-comments)))
11318
11319 (defsubst js2-mode-extend-//-comment (direction)
11320 "Find start or end of a block of similar //-comment lines.
11321 DIRECTION is -1 to look back, 1 to look forward.
11322 INDENT is the indentation level to match.
11323 Returns the end-of-line position of the furthest adjacent
11324 //-comment line with the same indentation as the current line.
11325 If there is no such matching line, returns current end of line."
11326 (let ((pos (point-at-eol))
11327 (indent (current-indentation)))
11328 (save-excursion
11329 (save-match-data
11330 (while (and (zerop (forward-line direction))
11331 (looking-at js2-mode-//-comment-re)
11332 (eq indent (length (match-string 1))))
11333 (setq pos (point-at-eol)))
11334 pos))))
11335
11336 (defun js2-mode-hide-//-comments ()
11337 "Fold adjacent 1-line comments, showing only snippet of first one."
11338 (let (beg end)
11339 (save-excursion
11340 (save-match-data
11341 (goto-char (point-min))
11342 (while (re-search-forward js2-mode-//-comment-re nil t)
11343 (setq beg (point)
11344 end (js2-mode-extend-//-comment 1))
11345 (unless (eq beg end)
11346 (overlay-put (js2-mode-flag-region beg end 'hide)
11347 'comment t))
11348 (goto-char end)
11349 (forward-char 1))))))
11350
11351 (defun js2-mode-toggle-//-comment ()
11352 "Fold or un-fold any multi-line //-comment at point.
11353 Caller should have determined that this line starts with a //-comment."
11354 (let* ((beg (point-at-eol))
11355 (end beg))
11356 (save-excursion
11357 (goto-char end)
11358 (if (js2-mode-invisible-overlay-bounds)
11359 (js2-mode-show-element)
11360 ;; else hide the comment
11361 (setq beg (js2-mode-extend-//-comment -1)
11362 end (js2-mode-extend-//-comment 1))
11363 (unless (eq beg end)
11364 (overlay-put (js2-mode-flag-region beg end 'hide)
11365 'comment t))))))
11366
11367 (defun js2-mode-show-comments ()
11368 "Un-hide any hidden comments, leaving other hidden elements alone."
11369 (interactive)
11370 (setq js2-mode-comments-hidden nil)
11371 (save-excursion
11372 (goto-char (point-min))
11373 (while (/= (goto-char (next-overlay-change (point)))
11374 (point-max))
11375 (dolist (o (overlays-at (point)))
11376 (when (overlay-get o 'comment)
11377 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11378
11379 (defun js2-mode-display-warnings-and-errors ()
11380 "Turn on display of warnings and errors."
11381 (interactive)
11382 (setq js2-mode-show-parse-errors t
11383 js2-mode-show-strict-warnings t)
11384 (js2-reparse 'force))
11385
11386 (defun js2-mode-hide-warnings-and-errors ()
11387 "Turn off display of warnings and errors."
11388 (interactive)
11389 (setq js2-mode-show-parse-errors nil
11390 js2-mode-show-strict-warnings nil)
11391 (js2-reparse 'force))
11392
11393 (defun js2-mode-toggle-warnings-and-errors ()
11394 "Toggle the display of warnings and errors.
11395 Some users don't like having warnings/errors reported while they type."
11396 (interactive)
11397 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11398 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11399 (if (interactive-p)
11400 (message "warnings and errors %s"
11401 (if js2-mode-show-parse-errors
11402 "enabled"
11403 "disabled")))
11404 (js2-reparse 'force))
11405
11406 (defun js2-mode-customize ()
11407 (interactive)
11408 (customize-group 'js2-mode))
11409
11410 (defun js2-mode-forward-sexp (&optional arg)
11411 "Move forward across one statement or balanced expression.
11412 With ARG, do it that many times. Negative arg -N means
11413 move backward across N balanced expressions."
11414 (interactive "p")
11415 (setq arg (or arg 1))
11416 (if js2-mode-buffer-dirty-p
11417 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11418 (let (node end (start (point)))
11419 (cond
11420 ;; backward-sexp
11421 ;; could probably make this better for some cases:
11422 ;; - if in statement block (e.g. function body), go to parent
11423 ;; - infix exprs like (foo in bar) - maybe go to beginning
11424 ;; of infix expr if in the right-side expression?
11425 ((and arg (minusp arg))
11426 (dotimes (i (- arg))
11427 (js2-backward-sws)
11428 (forward-char -1) ; enter the node we backed up to
11429 (setq node (js2-node-at-point (point) t))
11430 (goto-char (if node
11431 (js2-node-abs-pos node)
11432 (point-min)))))
11433 (t
11434 ;; forward-sexp
11435 (js2-forward-sws)
11436 (dotimes (i arg)
11437 (js2-forward-sws)
11438 (setq node (js2-node-at-point (point) t)
11439 end (if node (+ (js2-node-abs-pos node)
11440 (js2-node-len node))))
11441 (goto-char (or end (point-max))))))))
11442
11443 (defun js2-next-error (&optional arg reset)
11444 "Move to next parse error.
11445 Typically invoked via \\[next-error].
11446 ARG is the number of errors, forward or backward, to move.
11447 RESET means start over from the beginning."
11448 (interactive "p")
11449 (if (or (null js2-mode-ast)
11450 (and (null (js2-ast-root-errors js2-mode-ast))
11451 (null (js2-ast-root-warnings js2-mode-ast))))
11452 (message "No errors")
11453 (when reset
11454 (goto-char (point-min)))
11455 (let* ((errs (copy-sequence
11456 (append (js2-ast-root-errors js2-mode-ast)
11457 (js2-ast-root-warnings js2-mode-ast))))
11458 (continue t)
11459 (start (point))
11460 (count (or arg 1))
11461 (backward (minusp count))
11462 (sorter (if backward '> '<))
11463 (stopper (if backward '< '>))
11464 (count (abs count))
11465 all-errs
11466 err)
11467 ;; sort by start position
11468 (setq errs (sort errs (lambda (e1 e2)
11469 (funcall sorter (second e1) (second e2))))
11470 all-errs errs)
11471 ;; find nth error with pos > start
11472 (while (and errs continue)
11473 (when (funcall stopper (cadar errs) start)
11474 (setq err (car errs))
11475 (if (zerop (decf count))
11476 (setq continue nil)))
11477 (setq errs (cdr errs)))
11478 (if err
11479 (goto-char (second err))
11480 ;; wrap around to first error
11481 (goto-char (second (car all-errs)))
11482 ;; if we were already on it, echo msg again
11483 (if (= (point) start)
11484 (js2-echo-error (point) (point)))))))
11485
11486 (defun js2-down-mouse-3 ()
11487 "Make right-click move the point to the click location.
11488 This makes right-click context menu operations a bit more intuitive.
11489 The point will not move if the region is active, however, to avoid
11490 destroying the region selection."
11491 (interactive)
11492 (when (and js2-move-point-on-right-click
11493 (not mark-active))
11494 (let ((e last-input-event))
11495 (ignore-errors
11496 (goto-char (cadadr e))))))
11497
11498 (defun js2-mode-create-imenu-index ()
11499 "Return an alist for `imenu--index-alist'."
11500 ;; This is built up in `js2-parse-record-imenu' during parsing.
11501 (when js2-mode-ast
11502 ;; if we have an ast but no recorder, they're requesting a rescan
11503 (unless js2-imenu-recorder
11504 (js2-reparse 'force))
11505 (prog1
11506 (js2-build-imenu-index)
11507 (setq js2-imenu-recorder nil
11508 js2-imenu-function-map nil))))
11509
11510 (defun js2-mode-find-tag ()
11511 "Replacement for `find-tag-default'.
11512 `find-tag-default' returns a ridiculous answer inside comments."
11513 (let (beg end)
11514 (js2-with-underscore-as-word-syntax
11515 (save-excursion
11516 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11517 (looking-back "[A-Za-z0-9_$]"))
11518 (setq beg (progn (forward-word -1) (point))
11519 end (progn (forward-word 1) (point)))
11520 (setq beg (progn (forward-word 1) (point))
11521 end (progn (forward-word -1) (point))))
11522 (replace-regexp-in-string
11523 "[\"']" ""
11524 (buffer-substring-no-properties beg end))))))
11525
11526 (defun js2-mode-forward-sibling ()
11527 "Move to the end of the sibling following point in parent.
11528 Returns non-nil if successful, or nil if there was no following sibling."
11529 (let* ((node (js2-node-at-point))
11530 (parent (js2-mode-find-enclosing-fn node))
11531 sib)
11532 (when (setq sib (js2-node-find-child-after (point) parent))
11533 (goto-char (+ (js2-node-abs-pos sib)
11534 (js2-node-len sib))))))
11535
11536 (defun js2-mode-backward-sibling ()
11537 "Move to the beginning of the sibling node preceding point in parent.
11538 Parent is defined as the enclosing script or function."
11539 (let* ((node (js2-node-at-point))
11540 (parent (js2-mode-find-enclosing-fn node))
11541 sib)
11542 (when (setq sib (js2-node-find-child-before (point) parent))
11543 (goto-char (js2-node-abs-pos sib)))))
11544
11545 (defun js2-beginning-of-defun (&optional arg)
11546 "Go to line on which current function starts, and return t on success.
11547 If we're not in a function or already at the beginning of one, go
11548 to beginning of previous script-level element.
11549 With ARG N, do that N times. If N is negative, move forward."
11550 (setq arg (or arg 1))
11551 (if (plusp arg)
11552 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11553 (when (cond
11554 ((js2-function-node-p parent)
11555 (goto-char (js2-node-abs-pos parent)))
11556 (t
11557 (js2-mode-backward-sibling)))
11558 (if (> arg 1)
11559 (js2-beginning-of-defun (1- arg))
11560 t)))
11561 (when (js2-end-of-defun)
11562 (if (>= arg -1)
11563 (js2-beginning-of-defun 1)
11564 (js2-beginning-of-defun (1+ arg))))))
11565
11566 (defun js2-end-of-defun ()
11567 "Go to the char after the last position of the current function
11568 or script-level element."
11569 (let* ((node (js2-node-at-point))
11570 (parent (or (and (js2-function-node-p node) node)
11571 (js2-node-parent-script-or-fn node)))
11572 script)
11573 (unless (js2-function-node-p parent)
11574 ;; use current script-level node, or, if none, the next one
11575 (setq script (or parent node))
11576 (setq parent (js2-node-find-child-before (point) script))
11577 (when (or (null parent)
11578 (>= (point) (+ (js2-node-abs-pos parent)
11579 (js2-node-len parent))))
11580 (setq parent (js2-node-find-child-after (point) script))))
11581 (when parent
11582 (goto-char (+ (js2-node-abs-pos parent)
11583 (js2-node-len parent))))))
11584
11585 (defun js2-mark-defun (&optional allow-extend)
11586 "Put mark at end of this function, point at beginning.
11587 The function marked is the one that contains point.
11588
11589 Interactively, if this command is repeated,
11590 or (in Transient Mark mode) if the mark is active,
11591 it marks the next defun after the ones already marked."
11592 (interactive "p")
11593 (let (extended)
11594 (when (and allow-extend
11595 (or (and (eq last-command this-command) (mark t))
11596 (and transient-mark-mode mark-active)))
11597 (let ((sib (save-excursion
11598 (goto-char (mark))
11599 (if (js2-mode-forward-sibling)
11600 (point))))
11601 node)
11602 (if sib
11603 (progn
11604 (set-mark sib)
11605 (setq extended t))
11606 ;; no more siblings - try extending to enclosing node
11607 (goto-char (mark t)))))
11608 (when (not extended)
11609 (let ((node (js2-node-at-point (point) t)) ; skip comments
11610 ast fn stmt parent beg end)
11611 (when (js2-ast-root-p node)
11612 (setq ast node
11613 node (or (js2-node-find-child-after (point) node)
11614 (js2-node-find-child-before (point) node))))
11615 ;; only mark whole buffer if we can't find any children
11616 (if (null node)
11617 (setq node ast))
11618 (if (js2-function-node-p node)
11619 (setq parent node)
11620 (setq fn (js2-mode-find-enclosing-fn node)
11621 stmt (if (or (null fn)
11622 (js2-ast-root-p fn))
11623 (js2-mode-find-first-stmt node))
11624 parent (or stmt fn)))
11625 (setq beg (js2-node-abs-pos parent)
11626 end (+ beg (js2-node-len parent)))
11627 (push-mark beg)
11628 (goto-char end)
11629 (exchange-point-and-mark)))))
11630
11631 (defun js2-narrow-to-defun ()
11632 "Narrow to the function enclosing point."
11633 (interactive)
11634 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11635 (fn (if (js2-script-node-p node)
11636 node
11637 (js2-mode-find-enclosing-fn node)))
11638 (beg (js2-node-abs-pos fn)))
11639 (unless (js2-ast-root-p fn)
11640 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11641
11642 (provide 'js2-mode)
11643
11644 ;;; js2-mode.el ends here