]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Fix parsing of keyword property names
[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 (downcase
5209 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5210 (push sym js2-tokens)))
5211 names)
5212 "Vector mapping int values to token string names, sans `js2-' prefix.")
5213
5214 (defun js2-token-name (tok)
5215 "Return a string name for TOK, a token symbol or code.
5216 Signals an error if it's not a recognized token."
5217 (let ((code tok))
5218 (if (symbolp tok)
5219 (setq code (symbol-value tok)))
5220 (if (eq code -1)
5221 "ERROR"
5222 (if (and (numberp code)
5223 (not (minusp code))
5224 (< code js2-num-tokens))
5225 (aref js2-token-names code)
5226 (error "Invalid token: %s" code)))))
5227
5228 (defsubst js2-token-sym (tok)
5229 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5230 (intern (js2-token-name tok)))
5231
5232 (defconst js2-token-codes
5233 (let ((table (make-hash-table :test 'eq :size 256)))
5234 (loop for name across js2-token-names
5235 for sym = (intern (concat "js2-" (upcase name)))
5236 do
5237 (puthash sym (symbol-value sym) table))
5238 ;; clean up a few that are "wrong" in Rhino's token codes
5239 (puthash 'js2-DELETE js2-DELPROP table)
5240 table)
5241 "Hashtable mapping token symbols to their bytecodes.")
5242
5243 (defsubst js2-token-code (sym)
5244 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5245 (or (gethash sym js2-token-codes)
5246 (error "Invalid token symbol: %s " sym))) ; signal code bug
5247
5248 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5249 (setq js2-token-end js2-ts-cursor)
5250 (js2-report-error msg nil
5251 (or beg js2-token-beg)
5252 (or len (- js2-token-end js2-token-beg)))
5253 (unless no-throw
5254 (throw 'return js2-ERROR)))
5255
5256 (defsubst js2-get-string-from-buffer ()
5257 "Reverse the char accumulator and return it as a string."
5258 (setq js2-token-end js2-ts-cursor)
5259 (if js2-ts-string-buffer
5260 (apply #'string (nreverse js2-ts-string-buffer))
5261 ""))
5262
5263 ;; TODO: could potentially avoid a lot of consing by allocating a
5264 ;; char buffer the way Rhino does.
5265 (defsubst js2-add-to-string (c)
5266 (push c js2-ts-string-buffer))
5267
5268 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5269 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5270 ;; any other character: when it's not part of the current token, we
5271 ;; unget it, allowing it to be read again by the following call.
5272 (defsubst js2-unget-char ()
5273 (decf js2-ts-cursor))
5274
5275 ;; Rhino distinguishes \r and \n line endings. We don't need to
5276 ;; because we only scan from Emacs buffers, which always use \n.
5277 (defsubst js2-get-char ()
5278 "Read and return the next character from the input buffer.
5279 Increments `js2-ts-lineno' if the return value is a newline char.
5280 Updates `js2-ts-cursor' to the point after the returned char.
5281 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5282 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5283 (let (c)
5284 ;; check for end of buffer
5285 (if (>= js2-ts-cursor (point-max))
5286 (setq js2-ts-hit-eof t
5287 js2-ts-cursor (1+ js2-ts-cursor)
5288 c js2-EOF_CHAR) ; return value
5289 ;; otherwise read next char
5290 (setq c (char-before (incf js2-ts-cursor)))
5291 ;; if we read a newline, update counters
5292 (if (= c ?\n)
5293 (setq js2-ts-line-start js2-ts-cursor
5294 js2-ts-lineno (1+ js2-ts-lineno)))
5295 ;; TODO: skip over format characters
5296 c)))
5297
5298 (defsubst js2-read-unicode-escape ()
5299 "Read a \\uNNNN sequence from the input.
5300 Assumes the ?\ and ?u have already been read.
5301 Returns the unicode character, or nil if it wasn't a valid character.
5302 Doesn't change the values of any scanner variables."
5303 ;; I really wish I knew a better way to do this, but I can't
5304 ;; find the Emacs function that takes a 16-bit int and converts
5305 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5306 ;; Have to first check that it's 4 hex characters or it may stop
5307 ;; the read early.
5308 (ignore-errors
5309 (let ((s (buffer-substring-no-properties js2-ts-cursor
5310 (+ 4 js2-ts-cursor))))
5311 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5312 (read (concat "?\\u" s))))))
5313
5314 (defsubst js2-match-char (test)
5315 "Consume and return next character if it matches TEST, a character.
5316 Returns nil and consumes nothing if TEST is not the next character."
5317 (let ((c (js2-get-char)))
5318 (if (eq c test)
5319 t
5320 (js2-unget-char)
5321 nil)))
5322
5323 (defsubst js2-peek-char ()
5324 (prog1
5325 (js2-get-char)
5326 (js2-unget-char)))
5327
5328 (defsubst js2-java-identifier-start-p (c)
5329 (or
5330 (memq c '(?$ ?_))
5331 (js2-char-uppercase-p c)
5332 (js2-char-lowercase-p c)))
5333
5334 (defsubst js2-java-identifier-part-p (c)
5335 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5336 ;; TODO: make me Unicode-friendly. See comments above.
5337 (or
5338 (memq c '(?$ ?_))
5339 (js2-char-uppercase-p c)
5340 (js2-char-lowercase-p c)
5341 (and (>= c ?0) (<= c ?9))))
5342
5343 (defsubst js2-alpha-p (c)
5344 (cond ((and (<= ?A c) (<= c ?Z)) t)
5345 ((and (<= ?a c) (<= c ?z)) t)
5346 (t nil)))
5347
5348 (defsubst js2-digit-p (c)
5349 (and (<= ?0 c) (<= c ?9)))
5350
5351 (defsubst js2-js-space-p (c)
5352 (if (<= c 127)
5353 (memq c '(#x20 #x9 #xB #xC #xD))
5354 (or
5355 (eq c #xA0)
5356 ;; TODO: change this nil to check for Unicode space character
5357 nil)))
5358
5359 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5360
5361 (defsubst js2-skip-line ()
5362 "Skip to end of line"
5363 (let (c)
5364 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5365 (js2-unget-char)
5366 (setq js2-token-end js2-ts-cursor)))
5367
5368 (defun js2-init-scanner (&optional buf line)
5369 "Create token stream for BUF starting on LINE.
5370 BUF defaults to current-buffer and line defaults to 1.
5371
5372 A buffer can only have one scanner active at a time, which yields
5373 dramatically simpler code than using a defstruct. If you need to
5374 have simultaneous scanners in a buffer, copy the regions to scan
5375 into temp buffers."
5376 (save-excursion
5377 (when buf
5378 (set-buffer buf))
5379 (setq js2-ts-dirty-line nil
5380 js2-ts-regexp-flags nil
5381 js2-ts-string ""
5382 js2-ts-number nil
5383 js2-ts-hit-eof nil
5384 js2-ts-line-start 0
5385 js2-ts-lineno (or line 1)
5386 js2-ts-line-end-char -1
5387 js2-ts-cursor (point-min)
5388 js2-ts-is-xml-attribute nil
5389 js2-ts-xml-is-tag-content nil
5390 js2-ts-xml-open-tags-count 0
5391 js2-ts-string-buffer nil)))
5392
5393 ;; This function uses the cached op, string and number fields in
5394 ;; TokenStream; if getToken has been called since the passed token
5395 ;; was scanned, the op or string printed may be incorrect.
5396 (defun js2-token-to-string (token)
5397 ;; Not sure where this function is used in Rhino. Not tested.
5398 (if (not js2-debug-print-trees)
5399 ""
5400 (let ((name (js2-token-name token)))
5401 (cond
5402 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5403 (concat name " `" js2-ts-string "'"))
5404 ((eq token js2-NUMBER)
5405 (format "NUMBER %g" js2-ts-number))
5406 (t
5407 name)))))
5408
5409 (defconst js2-keywords
5410 '(break
5411 case catch const continue
5412 debugger default delete do
5413 else enum
5414 false finally for function
5415 if in of instanceof import
5416 let
5417 new null
5418 return
5419 switch
5420 this throw true try typeof
5421 var void
5422 while with
5423 yield))
5424
5425 ;; Token names aren't exactly the same as the keywords, unfortunately.
5426 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5427 (defconst js2-kwd-tokens
5428 (let ((table (make-vector js2-num-tokens nil))
5429 (tokens
5430 (list js2-BREAK
5431 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5432 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5433 js2-ELSE
5434 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5435 js2-IF js2-IN js2-OF js2-INSTANCEOF js2-IMPORT
5436 js2-LET
5437 js2-NEW js2-NULL
5438 js2-RETURN
5439 js2-SWITCH
5440 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5441 js2-VAR
5442 js2-WHILE js2-WITH
5443 js2-YIELD)))
5444 (dolist (i tokens)
5445 (aset table i 'font-lock-keyword-face))
5446 (aset table js2-STRING 'font-lock-string-face)
5447 (aset table js2-REGEXP 'font-lock-string-face)
5448 (aset table js2-COMMENT 'font-lock-comment-face)
5449 (aset table js2-THIS 'font-lock-builtin-face)
5450 (aset table js2-VOID 'font-lock-constant-face)
5451 (aset table js2-NULL 'font-lock-constant-face)
5452 (aset table js2-TRUE 'font-lock-constant-face)
5453 (aset table js2-FALSE 'font-lock-constant-face)
5454 table)
5455 "Vector whose values are non-nil for tokens that are keywords.
5456 The values are default faces to use for highlighting the keywords.")
5457
5458 (defconst js2-reserved-words
5459 '(abstract
5460 boolean byte
5461 char class
5462 double
5463 enum export extends
5464 final float
5465 goto
5466 implements import int interface
5467 long
5468 native
5469 package private protected public
5470 short static super synchronized
5471 throws transient
5472 volatile))
5473
5474 (defconst js2-keyword-names
5475 (let ((table (make-hash-table :test 'equal)))
5476 (loop for k in js2-keywords
5477 do (puthash
5478 (symbol-name k) ; instanceof
5479 (intern (concat "js2-"
5480 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5481 table))
5482 table)
5483 "JavaScript keywords by name, mapped to their symbols.")
5484
5485 (defconst js2-reserved-word-names
5486 (let ((table (make-hash-table :test 'equal)))
5487 (loop for k in js2-reserved-words
5488 do
5489 (puthash (symbol-name k) 'js2-RESERVED table))
5490 table)
5491 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5492
5493 (defsubst js2-collect-string (buf)
5494 "Convert BUF, a list of chars, to a string.
5495 Reverses BUF before converting."
5496 (cond
5497 ((stringp buf)
5498 buf)
5499 ((null buf) ; for emacs21 compat
5500 "")
5501 (t
5502 (if buf
5503 (apply #'string (nreverse buf))
5504 ""))))
5505
5506 (defun js2-string-to-keyword (s)
5507 "Return token for S, a string, if S is a keyword or reserved word.
5508 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5509 (or (gethash s js2-keyword-names)
5510 (gethash s js2-reserved-word-names)))
5511
5512 (defsubst js2-ts-set-char-token-bounds ()
5513 "Used when next token is one character."
5514 (setq js2-token-beg (1- js2-ts-cursor)
5515 js2-token-end js2-ts-cursor))
5516
5517 (defsubst js2-ts-return (token)
5518 "Return an N-character TOKEN from `js2-get-token'.
5519 Updates `js2-token-end' accordingly."
5520 (setq js2-token-end js2-ts-cursor)
5521 (throw 'return token))
5522
5523 (defsubst js2-x-digit-to-int (c accumulator)
5524 "Build up a hex number.
5525 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5526 corresponding number. Otherwise return -1."
5527 (catch 'return
5528 (catch 'check
5529 ;; Use 0..9 < A..Z < a..z
5530 (cond
5531 ((<= c ?9)
5532 (decf c ?0)
5533 (if (<= 0 c)
5534 (throw 'check nil)))
5535 ((<= c ?F)
5536 (when (<= ?A c)
5537 (decf c (- ?A 10))
5538 (throw 'check nil)))
5539 ((<= c ?f)
5540 (when (<= ?a c)
5541 (decf c (- ?a 10))
5542 (throw 'check nil))))
5543 (throw 'return -1))
5544 (logior c (lsh accumulator 4))))
5545
5546 (defun js2-get-token ()
5547 "Return next JavaScript token, an int such as js2-RETURN."
5548 (let (c
5549 c1
5550 identifier-start
5551 is-unicode-escape-start
5552 contains-escape
5553 escape-val
5554 escape-start
5555 str
5556 result
5557 base
5558 is-integer
5559 quote-char
5560 val
5561 look-for-slash
5562 continue)
5563 (catch 'return
5564 (while t
5565 ;; Eat whitespace, possibly sensitive to newlines.
5566 (setq continue t)
5567 (while continue
5568 (setq c (js2-get-char))
5569 (cond
5570 ((eq c js2-EOF_CHAR)
5571 (js2-ts-set-char-token-bounds)
5572 (throw 'return js2-EOF))
5573 ((eq c ?\n)
5574 (js2-ts-set-char-token-bounds)
5575 (setq js2-ts-dirty-line nil)
5576 (throw 'return js2-EOL))
5577 ((not (js2-js-space-p c))
5578 (if (/= c ?-) ; in case end of HTML comment
5579 (setq js2-ts-dirty-line t))
5580 (setq continue nil))))
5581 ;; Assume the token will be 1 char - fixed up below.
5582 (js2-ts-set-char-token-bounds)
5583 (when (eq c ?@)
5584 (throw 'return js2-XMLATTR))
5585 ;; identifier/keyword/instanceof?
5586 ;; watch out for starting with a <backslash>
5587 (cond
5588 ((eq c ?\\)
5589 (setq c (js2-get-char))
5590 (if (eq c ?u)
5591 (setq identifier-start t
5592 is-unicode-escape-start t
5593 js2-ts-string-buffer nil)
5594 (setq identifier-start nil)
5595 (js2-unget-char)
5596 (setq c ?\\)))
5597 (t
5598 (when (setq identifier-start (js2-java-identifier-start-p c))
5599 (setq js2-ts-string-buffer nil)
5600 (js2-add-to-string c))))
5601 (when identifier-start
5602 (setq contains-escape is-unicode-escape-start)
5603 (catch 'break
5604 (while t
5605 (if is-unicode-escape-start
5606 ;; strictly speaking we should probably push-back
5607 ;; all the bad characters if the <backslash>uXXXX
5608 ;; sequence is malformed. But since there isn't a
5609 ;; correct context(is there?) for a bad Unicode
5610 ;; escape sequence in an identifier, we can report
5611 ;; an error here.
5612 (progn
5613 (setq escape-val 0)
5614 (dotimes (i 4)
5615 (setq c (js2-get-char)
5616 escape-val (js2-x-digit-to-int c escape-val))
5617 ;; Next check takes care of c < 0 and bad escape
5618 (if (minusp escape-val)
5619 (throw 'break nil)))
5620 (if (minusp escape-val)
5621 (js2-report-scan-error "msg.invalid.escape" t))
5622 (js2-add-to-string escape-val)
5623 (setq is-unicode-escape-start nil))
5624 (setq c (js2-get-char))
5625 (cond
5626 ((eq c ?\\)
5627 (setq c (js2-get-char))
5628 (if (eq c ?u)
5629 (setq is-unicode-escape-start t
5630 contains-escape t)
5631 (js2-report-scan-error "msg.illegal.character" t)))
5632 (t
5633 (if (or (eq c js2-EOF_CHAR)
5634 (not (js2-java-identifier-part-p c)))
5635 (throw 'break nil))
5636 (js2-add-to-string c))))))
5637 (js2-unget-char)
5638 (setq str (js2-get-string-from-buffer))
5639 (unless contains-escape
5640 ;; OPT we shouldn't have to make a string (object!) to
5641 ;; check if it's a keyword.
5642 ;; Return the corresponding token if it's a keyword
5643 (when (setq result (js2-string-to-keyword str))
5644 (if (and (< js2-language-version 170)
5645 (memq result '(js2-LET js2-YIELD)))
5646 ;; LET and YIELD are tokens only in 1.7 and later
5647 (setq result 'js2-NAME))
5648 (if (not (eq result 'js2-RESERVED))
5649 (throw 'return (js2-token-code result)))
5650 (js2-report-warning "msg.reserved.keyword" str)))
5651 ;; If we want to intern these as Rhino does, just use (intern str)
5652 (setq js2-ts-string str)
5653 (throw 'return js2-NAME)) ; end identifier/kwd check
5654 ;; is it a number?
5655 (when (or (js2-digit-p c)
5656 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5657 (setq js2-ts-string-buffer nil
5658 base 10)
5659 (when (eq c ?0)
5660 (setq c (js2-get-char))
5661 (cond
5662 ((or (eq c ?x) (eq c ?X))
5663 (setq base 16)
5664 (setq c (js2-get-char)))
5665 ((js2-digit-p c)
5666 (setq base 8))
5667 (t
5668 (js2-add-to-string ?0))))
5669 (if (eq base 16)
5670 (while (<= 0 (js2-x-digit-to-int c 0))
5671 (js2-add-to-string c)
5672 (setq c (js2-get-char)))
5673 (while (and (<= ?0 c) (<= c ?9))
5674 ;; We permit 08 and 09 as decimal numbers, which
5675 ;; makes our behavior a superset of the ECMA
5676 ;; numeric grammar. We might not always be so
5677 ;; permissive, so we warn about it.
5678 (when (and (eq base 8) (>= c ?8))
5679 (js2-report-warning "msg.bad.octal.literal"
5680 (if (eq c ?8) "8" "9"))
5681 (setq base 10))
5682 (js2-add-to-string c)
5683 (setq c (js2-get-char))))
5684 (setq is-integer t)
5685 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5686 (setq is-integer nil)
5687 (when (eq c ?.)
5688 (loop do
5689 (js2-add-to-string c)
5690 (setq c (js2-get-char))
5691 while (js2-digit-p c)))
5692 (when (memq c '(?e ?E))
5693 (js2-add-to-string c)
5694 (setq c (js2-get-char))
5695 (when (memq c '(?+ ?-))
5696 (js2-add-to-string c)
5697 (setq c (js2-get-char)))
5698 (unless (js2-digit-p c)
5699 (js2-report-scan-error "msg.missing.exponent" t))
5700 (loop do
5701 (js2-add-to-string c)
5702 (setq c (js2-get-char))
5703 while (js2-digit-p c))))
5704 (js2-unget-char)
5705 (setq js2-ts-string (js2-get-string-from-buffer)
5706 js2-ts-number
5707 (if (and (eq base 10) (not is-integer))
5708 (string-to-number js2-ts-string)
5709 ;; TODO: call runtime number-parser. Some of it is in
5710 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5711 (string-to-number js2-ts-string)))
5712 (throw 'return js2-NUMBER))
5713 ;; is it a string?
5714 (when (memq c '(?\" ?\'))
5715 ;; We attempt to accumulate a string the fast way, by
5716 ;; building it directly out of the reader. But if there
5717 ;; are any escaped characters in the string, we revert to
5718 ;; building it out of a string buffer.
5719 (setq quote-char c
5720 js2-ts-string-buffer nil
5721 c (js2-get-char))
5722 (catch 'break
5723 (while (/= c quote-char)
5724 (catch 'continue
5725 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5726 (js2-unget-char)
5727 (setq js2-token-end js2-ts-cursor)
5728 (js2-report-error "msg.unterminated.string.lit")
5729 (throw 'return js2-STRING))
5730 (when (eq c ?\\)
5731 ;; We've hit an escaped character
5732 (setq c (js2-get-char))
5733 (case c
5734 (?b (setq c ?\b))
5735 (?f (setq c ?\f))
5736 (?n (setq c ?\n))
5737 (?r (setq c ?\r))
5738 (?t (setq c ?\t))
5739 (?v (setq c ?\v))
5740 (?u
5741 (setq c1 (js2-read-unicode-escape))
5742 (if js2-parse-ide-mode
5743 (if c1
5744 (progn
5745 ;; just copy the string in IDE-mode
5746 (js2-add-to-string ?\\)
5747 (js2-add-to-string ?u)
5748 (dotimes (i 3)
5749 (js2-add-to-string (js2-get-char)))
5750 (setq c (js2-get-char))) ; added at end of loop
5751 ;; flag it as an invalid escape
5752 (js2-report-warning "msg.invalid.escape"
5753 nil (- js2-ts-cursor 2) 6))
5754 ;; Get 4 hex digits; if the u escape is not
5755 ;; followed by 4 hex digits, use 'u' + the
5756 ;; literal character sequence that follows.
5757 (js2-add-to-string ?u)
5758 (setq escape-val 0)
5759 (dotimes (i 4)
5760 (setq c (js2-get-char)
5761 escape-val (js2-x-digit-to-int c escape-val))
5762 (if (minusp escape-val)
5763 (throw 'continue nil))
5764 (js2-add-to-string c))
5765 ;; prepare for replace of stored 'u' sequence by escape value
5766 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5767 c escape-val)))
5768 (?x
5769 ;; Get 2 hex digits, defaulting to 'x'+literal
5770 ;; sequence, as above.
5771 (setq c (js2-get-char)
5772 escape-val (js2-x-digit-to-int c 0))
5773 (if (minusp escape-val)
5774 (progn
5775 (js2-add-to-string ?x)
5776 (throw 'continue nil))
5777 (setq c1 c
5778 c (js2-get-char)
5779 escape-val (js2-x-digit-to-int c escape-val))
5780 (if (minusp escape-val)
5781 (progn
5782 (js2-add-to-string ?x)
5783 (js2-add-to-string c1)
5784 (throw 'continue nil))
5785 ;; got 2 hex digits
5786 (setq c escape-val))))
5787 (?\n
5788 ;; Remove line terminator after escape to follow
5789 ;; SpiderMonkey and C/C++
5790 (setq c (js2-get-char))
5791 (throw 'continue nil))
5792 (t
5793 (when (and (<= ?0 c) (< c ?8))
5794 (setq val (- c ?0)
5795 c (js2-get-char))
5796 (when (and (<= ?0 c) (< c ?8))
5797 (setq val (- (+ (* 8 val) c) ?0)
5798 c (js2-get-char))
5799 (when (and (<= ?0 c)
5800 (< c ?8)
5801 (< val #o37))
5802 ;; c is 3rd char of octal sequence only
5803 ;; if the resulting val <= 0377
5804 (setq val (- (+ (* 8 val) c) ?0)
5805 c (js2-get-char))))
5806 (js2-unget-char)
5807 (setq c val)))))
5808 (js2-add-to-string c)
5809 (setq c (js2-get-char)))))
5810 (setq js2-ts-string (js2-get-string-from-buffer))
5811 (throw 'return js2-STRING))
5812 (case c
5813 (?\;
5814 (throw 'return js2-SEMI))
5815 (?\[
5816 (throw 'return js2-LB))
5817 (?\]
5818 (throw 'return js2-RB))
5819 (?{
5820 (throw 'return js2-LC))
5821 (?}
5822 (throw 'return js2-RC))
5823 (?\(
5824 (throw 'return js2-LP))
5825 (?\)
5826 (throw 'return js2-RP))
5827 (?,
5828 (throw 'return js2-COMMA))
5829 (??
5830 (throw 'return js2-HOOK))
5831 (?:
5832 (if (js2-match-char ?:)
5833 (js2-ts-return js2-COLONCOLON)
5834 (throw 'return js2-COLON)))
5835 (?.
5836 (if (js2-match-char ?.)
5837 (js2-ts-return js2-DOTDOT)
5838 (if (js2-match-char ?\()
5839 (js2-ts-return js2-DOTQUERY)
5840 (throw 'return js2-DOT))))
5841 (?|
5842 (if (js2-match-char ?|)
5843 (throw 'return js2-OR)
5844 (if (js2-match-char ?=)
5845 (js2-ts-return js2-ASSIGN_BITOR)
5846 (throw 'return js2-BITOR))))
5847 (?^
5848 (if (js2-match-char ?=)
5849 (js2-ts-return js2-ASSIGN_BITOR)
5850 (throw 'return js2-BITXOR)))
5851 (?&
5852 (if (js2-match-char ?&)
5853 (throw 'return js2-AND)
5854 (if (js2-match-char ?=)
5855 (js2-ts-return js2-ASSIGN_BITAND)
5856 (throw 'return js2-BITAND))))
5857 (?=
5858 (if (js2-match-char ?=)
5859 (if (js2-match-char ?=)
5860 (js2-ts-return js2-SHEQ)
5861 (throw 'return js2-EQ))
5862 (throw 'return js2-ASSIGN)))
5863 (?!
5864 (if (js2-match-char ?=)
5865 (if (js2-match-char ?=)
5866 (js2-ts-return js2-SHNE)
5867 (js2-ts-return js2-NE))
5868 (throw 'return js2-NOT)))
5869 (?<
5870 ;; NB:treat HTML begin-comment as comment-till-eol
5871 (when (js2-match-char ?!)
5872 (when (js2-match-char ?-)
5873 (when (js2-match-char ?-)
5874 (js2-skip-line)
5875 (setq js2-ts-comment-type 'html)
5876 (throw 'return js2-COMMENT)))
5877 (js2-unget-char))
5878 (if (js2-match-char ?<)
5879 (if (js2-match-char ?=)
5880 (js2-ts-return js2-ASSIGN_LSH)
5881 (js2-ts-return js2-LSH))
5882 (if (js2-match-char ?=)
5883 (js2-ts-return js2-LE)
5884 (throw 'return js2-LT))))
5885 (?>
5886 (if (js2-match-char ?>)
5887 (if (js2-match-char ?>)
5888 (if (js2-match-char ?=)
5889 (js2-ts-return js2-ASSIGN_URSH)
5890 (js2-ts-return js2-URSH))
5891 (if (js2-match-char ?=)
5892 (js2-ts-return js2-ASSIGN_RSH)
5893 (js2-ts-return js2-RSH)))
5894 (if (js2-match-char ?=)
5895 (js2-ts-return js2-GE)
5896 (throw 'return js2-GT))))
5897 (?*
5898 (if (js2-match-char ?=)
5899 (js2-ts-return js2-ASSIGN_MUL)
5900 (throw 'return js2-MUL)))
5901 (?/
5902 ;; is it a // comment?
5903 (when (js2-match-char ?/)
5904 (setq js2-token-beg (- js2-ts-cursor 2))
5905 (js2-skip-line)
5906 (setq js2-ts-comment-type 'line)
5907 ;; include newline so highlighting goes to end of window
5908 (incf js2-token-end)
5909 (throw 'return js2-COMMENT))
5910 ;; is it a /* comment?
5911 (when (js2-match-char ?*)
5912 (setq look-for-slash nil
5913 js2-token-beg (- js2-ts-cursor 2)
5914 js2-ts-comment-type
5915 (if (js2-match-char ?*)
5916 (progn
5917 (setq look-for-slash t)
5918 'jsdoc)
5919 'block))
5920 (while t
5921 (setq c (js2-get-char))
5922 (cond
5923 ((eq c js2-EOF_CHAR)
5924 (setq js2-token-end (1- js2-ts-cursor))
5925 (js2-report-error "msg.unterminated.comment")
5926 (throw 'return js2-COMMENT))
5927 ((eq c ?*)
5928 (setq look-for-slash t))
5929 ((eq c ?/)
5930 (if look-for-slash
5931 (js2-ts-return js2-COMMENT)))
5932 (t
5933 (setq look-for-slash nil
5934 js2-token-end js2-ts-cursor)))))
5935 (if (js2-match-char ?=)
5936 (js2-ts-return js2-ASSIGN_DIV)
5937 (throw 'return js2-DIV)))
5938 (?#
5939 (when js2-skip-preprocessor-directives
5940 (js2-skip-line)
5941 (setq js2-ts-comment-type 'preprocessor
5942 js2-token-end js2-ts-cursor)
5943 (throw 'return js2-COMMENT))
5944 (throw 'return js2-ERROR))
5945 (?%
5946 (if (js2-match-char ?=)
5947 (js2-ts-return js2-ASSIGN_MOD)
5948 (throw 'return js2-MOD)))
5949 (?~
5950 (throw 'return js2-BITNOT))
5951 (?+
5952 (if (js2-match-char ?=)
5953 (js2-ts-return js2-ASSIGN_ADD)
5954 (if (js2-match-char ?+)
5955 (js2-ts-return js2-INC)
5956 (throw 'return js2-ADD))))
5957 (?-
5958 (cond
5959 ((js2-match-char ?=)
5960 (setq c js2-ASSIGN_SUB))
5961 ((js2-match-char ?-)
5962 (unless js2-ts-dirty-line
5963 ;; treat HTML end-comment after possible whitespace
5964 ;; after line start as comment-until-eol
5965 (when (js2-match-char ?>)
5966 (js2-skip-line)
5967 (setq js2-ts-comment-type 'html)
5968 (throw 'return js2-COMMENT)))
5969 (setq c js2-DEC))
5970 (t
5971 (setq c js2-SUB)))
5972 (setq js2-ts-dirty-line t)
5973 (js2-ts-return c))
5974 (otherwise
5975 (js2-report-scan-error "msg.illegal.character")))))))
5976
5977 (defun js2-read-regexp (start-token)
5978 "Called by parser when it gets / or /= in literal context."
5979 (let (c
5980 err
5981 in-class ; inside a '[' .. ']' character-class
5982 flags
5983 (continue t))
5984 (setq js2-token-beg js2-ts-cursor
5985 js2-ts-string-buffer nil
5986 js2-ts-regexp-flags nil)
5987 (if (eq start-token js2-ASSIGN_DIV)
5988 ;; mis-scanned /=
5989 (js2-add-to-string ?=)
5990 (if (not (eq start-token js2-DIV))
5991 (error "failed assertion")))
5992 (while (and (not err)
5993 (or (/= (setq c (js2-get-char)) ?/)
5994 in-class))
5995 (cond
5996 ((or (= c ?\n)
5997 (= c js2-EOF_CHAR))
5998 (setq js2-token-end (1- js2-ts-cursor)
5999 err t
6000 js2-ts-string (js2-collect-string js2-ts-string-buffer))
6001 (js2-report-error "msg.unterminated.re.lit"))
6002 (t (cond
6003 ((= c ?\\)
6004 (js2-add-to-string c)
6005 (setq c (js2-get-char)))
6006 ((= c ?\[)
6007 (setq in-class t))
6008 ((= c ?\])
6009 (setq in-class nil)))
6010 (js2-add-to-string c))))
6011 (unless err
6012 (while continue
6013 (cond
6014 ((js2-match-char ?g)
6015 (push ?g flags))
6016 ((js2-match-char ?i)
6017 (push ?i flags))
6018 ((js2-match-char ?m)
6019 (push ?m flags))
6020 (t
6021 (setq continue nil))))
6022 (if (js2-alpha-p (js2-peek-char))
6023 (js2-report-scan-error "msg.invalid.re.flag" t
6024 js2-ts-cursor 1))
6025 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6026 js2-ts-regexp-flags (js2-collect-string flags)
6027 js2-token-end js2-ts-cursor)
6028 ;; tell `parse-partial-sexp' to ignore this range of chars
6029 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6030
6031 (defun js2-get-first-xml-token ()
6032 (setq js2-ts-xml-open-tags-count 0
6033 js2-ts-is-xml-attribute nil
6034 js2-ts-xml-is-tag-content nil)
6035 (js2-unget-char)
6036 (js2-get-next-xml-token))
6037
6038 (defsubst js2-xml-discard-string ()
6039 "Throw away the string in progress and flag an XML parse error."
6040 (setq js2-ts-string-buffer nil
6041 js2-ts-string nil)
6042 (js2-report-scan-error "msg.XML.bad.form" t))
6043
6044 (defun js2-get-next-xml-token ()
6045 (setq js2-ts-string-buffer nil ; for recording the XML
6046 js2-token-beg js2-ts-cursor)
6047 (let (c result)
6048 (setq result
6049 (catch 'return
6050 (while t
6051 (setq c (js2-get-char))
6052 (cond
6053 ((= c js2-EOF_CHAR)
6054 (throw 'return js2-ERROR))
6055 (js2-ts-xml-is-tag-content
6056 (case c
6057 (?>
6058 (js2-add-to-string c)
6059 (setq js2-ts-xml-is-tag-content nil
6060 js2-ts-is-xml-attribute nil))
6061 (?/
6062 (js2-add-to-string c)
6063 (when (eq ?> (js2-peek-char))
6064 (setq c (js2-get-char))
6065 (js2-add-to-string c)
6066 (setq js2-ts-xml-is-tag-content nil)
6067 (decf js2-ts-xml-open-tags-count)))
6068 (?{
6069 (js2-unget-char)
6070 (setq js2-ts-string (js2-get-string-from-buffer))
6071 (throw 'return js2-XML))
6072 ((?\' ?\")
6073 (js2-add-to-string c)
6074 (unless (js2-read-quoted-string c)
6075 (throw 'return js2-ERROR)))
6076 (?=
6077 (js2-add-to-string c)
6078 (setq js2-ts-is-xml-attribute t))
6079 ((? ?\t ?\r ?\n)
6080 (js2-add-to-string c))
6081 (t
6082 (js2-add-to-string c)
6083 (setq js2-ts-is-xml-attribute nil)))
6084 (when (and (not js2-ts-xml-is-tag-content)
6085 (zerop js2-ts-xml-open-tags-count))
6086 (setq js2-ts-string (js2-get-string-from-buffer))
6087 (throw 'return js2-XMLEND)))
6088 (t
6089 ;; else not tag content
6090 (case c
6091 (?<
6092 (js2-add-to-string c)
6093 (setq c (js2-peek-char))
6094 (case c
6095 (?!
6096 (setq c (js2-get-char)) ;; skip !
6097 (js2-add-to-string c)
6098 (setq c (js2-peek-char))
6099 (case c
6100 (?-
6101 (setq c (js2-get-char)) ;; skip -
6102 (js2-add-to-string c)
6103 (if (eq c ?-)
6104 (progn
6105 (js2-add-to-string c)
6106 (unless (js2-read-xml-comment)
6107 (throw 'return js2-ERROR)))
6108 (js2-xml-discard-string)
6109 (throw 'return js2-ERROR)))
6110 (?\[
6111 (setq c (js2-get-char)) ;; skip [
6112 (js2-add-to-string c)
6113 (if (and (= (js2-get-char) ?C)
6114 (= (js2-get-char) ?D)
6115 (= (js2-get-char) ?A)
6116 (= (js2-get-char) ?T)
6117 (= (js2-get-char) ?A)
6118 (= (js2-get-char) ?\[))
6119 (progn
6120 (js2-add-to-string ?C)
6121 (js2-add-to-string ?D)
6122 (js2-add-to-string ?A)
6123 (js2-add-to-string ?T)
6124 (js2-add-to-string ?A)
6125 (js2-add-to-string ?\[)
6126 (unless (js2-read-cdata)
6127 (throw 'return js2-ERROR)))
6128 (js2-xml-discard-string)
6129 (throw 'return js2-ERROR)))
6130 (t
6131 (unless (js2-read-entity)
6132 (throw 'return js2-ERROR))))
6133 ;; allow bare CDATA section
6134 ;; ex) let xml = <![CDATA[ foo bar baz ]]>;
6135 (when (zerop js2-ts-xml-open-tags-count)
6136 (throw 'return js2-XMLEND)))
6137 (??
6138 (setq c (js2-get-char)) ;; skip ?
6139 (js2-add-to-string c)
6140 (unless (js2-read-PI)
6141 (throw 'return js2-ERROR)))
6142 (?/
6143 ;; end tag
6144 (setq c (js2-get-char)) ;; skip /
6145 (js2-add-to-string c)
6146 (when (zerop js2-ts-xml-open-tags-count)
6147 (js2-xml-discard-string)
6148 (throw 'return js2-ERROR))
6149 (setq js2-ts-xml-is-tag-content t)
6150 (decf js2-ts-xml-open-tags-count))
6151 (t
6152 ;; start tag
6153 (setq js2-ts-xml-is-tag-content t)
6154 (incf js2-ts-xml-open-tags-count))))
6155 (?{
6156 (js2-unget-char)
6157 (setq js2-ts-string (js2-get-string-from-buffer))
6158 (throw 'return js2-XML))
6159 (t
6160 (js2-add-to-string c))))))))
6161 (setq js2-token-end js2-ts-cursor)
6162 result))
6163
6164 (defun js2-read-quoted-string (quote)
6165 (let (c)
6166 (catch 'return
6167 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6168 (js2-add-to-string c)
6169 (if (eq c quote)
6170 (throw 'return t)))
6171 (js2-xml-discard-string) ;; throw away string in progress
6172 nil)))
6173
6174 (defun js2-read-xml-comment ()
6175 (let ((c (js2-get-char)))
6176 (catch 'return
6177 (while (/= c js2-EOF_CHAR)
6178 (catch 'continue
6179 (js2-add-to-string c)
6180 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6181 (setq c (js2-get-char))
6182 (js2-add-to-string c)
6183 (if (eq (js2-peek-char) ?>)
6184 (progn
6185 (setq c (js2-get-char)) ;; skip >
6186 (js2-add-to-string c)
6187 (throw 'return t))
6188 (throw 'continue nil)))
6189 (setq c (js2-get-char))))
6190 (js2-xml-discard-string)
6191 nil)))
6192
6193 (defun js2-read-cdata ()
6194 (let ((c (js2-get-char)))
6195 (catch 'return
6196 (while (/= c js2-EOF_CHAR)
6197 (catch 'continue
6198 (js2-add-to-string c)
6199 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6200 (setq c (js2-get-char))
6201 (js2-add-to-string c)
6202 (if (eq (js2-peek-char) ?>)
6203 (progn
6204 (setq c (js2-get-char)) ;; Skip >
6205 (js2-add-to-string c)
6206 (throw 'return t))
6207 (throw 'continue nil)))
6208 (setq c (js2-get-char))))
6209 (js2-xml-discard-string)
6210 nil)))
6211
6212 (defun js2-read-entity ()
6213 (let ((decl-tags 1)
6214 c)
6215 (catch 'return
6216 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6217 (js2-add-to-string c)
6218 (case c
6219 (?<
6220 (incf decl-tags))
6221 (?>
6222 (decf decl-tags)
6223 (if (zerop decl-tags)
6224 (throw 'return t)))))
6225 (js2-xml-discard-string)
6226 nil)))
6227
6228 (defun js2-read-PI ()
6229 "Scan an XML processing instruction."
6230 (let (c)
6231 (catch 'return
6232 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6233 (js2-add-to-string c)
6234 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6235 (setq c (js2-get-char)) ;; Skip >
6236 (js2-add-to-string c)
6237 (throw 'return t)))
6238 (js2-xml-discard-string)
6239 nil)))
6240
6241 (defun js2-scanner-get-line ()
6242 "Return the text of the current scan line."
6243 (buffer-substring (point-at-bol) (point-at-eol)))
6244
6245 ;;; Highlighting
6246
6247 (defsubst js2-set-face (beg end face &optional record)
6248 "Fontify a region. If RECORD is non-nil, record for later."
6249 (when (plusp js2-highlight-level)
6250 (setq beg (min (point-max) beg)
6251 beg (max (point-min) beg)
6252 end (min (point-max) end)
6253 end (max (point-min) end))
6254 (if record
6255 (push (list beg end face) js2-mode-fontifications)
6256 (put-text-property beg end 'font-lock-face face))))
6257
6258 (defsubst js2-set-kid-face (pos kid len face)
6259 "Set-face on a child node.
6260 POS is absolute buffer position of parent.
6261 KID is the child node.
6262 LEN is the length to fontify.
6263 FACE is the face to fontify with."
6264 (js2-set-face (+ pos (js2-node-pos kid))
6265 (+ pos (js2-node-pos kid) (js2-node-len kid))
6266 face))
6267
6268 (defsubst js2-fontify-kwd (start length)
6269 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6270
6271 (defsubst js2-clear-face (beg end)
6272 (remove-text-properties beg end '(font-lock-face nil
6273 help-echo nil
6274 point-entered nil
6275 c-in-sws nil)))
6276
6277 (defconst js2-ecma-global-props
6278 (concat "^"
6279 (regexp-opt
6280 '("Infinity" "NaN" "undefined" "arguments") t)
6281 "$")
6282 "Value properties of the Ecma-262 Global Object.
6283 Shown at or above `js2-highlight-level' 2.")
6284
6285 ;; might want to add the name "arguments" to this list?
6286 (defconst js2-ecma-object-props
6287 (concat "^"
6288 (regexp-opt
6289 '("prototype" "__proto__" "__parent__") t)
6290 "$")
6291 "Value properties of the Ecma-262 Object constructor.
6292 Shown at or above `js2-highlight-level' 2.")
6293
6294 (defconst js2-ecma-global-funcs
6295 (concat
6296 "^"
6297 (regexp-opt
6298 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6299 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6300 "$")
6301 "Function properties of the Ecma-262 Global object.
6302 Shown at or above `js2-highlight-level' 2.")
6303
6304 (defconst js2-ecma-number-props
6305 (concat "^"
6306 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6307 "NEGATIVE_INFINITY"
6308 "POSITIVE_INFINITY") t)
6309 "$")
6310 "Properties of the Ecma-262 Number constructor.
6311 Shown at or above `js2-highlight-level' 2.")
6312
6313 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6314 "Properties of the Ecma-262 Date constructor.
6315 Shown at or above `js2-highlight-level' 2.")
6316
6317 (defconst js2-ecma-math-props
6318 (concat "^"
6319 (regexp-opt
6320 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6321 t)
6322 "$")
6323 "Properties of the Ecma-262 Math object.
6324 Shown at or above `js2-highlight-level' 2.")
6325
6326 (defconst js2-ecma-math-funcs
6327 (concat "^"
6328 (regexp-opt
6329 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6330 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6331 "$")
6332 "Function properties of the Ecma-262 Math object.
6333 Shown at or above `js2-highlight-level' 2.")
6334
6335 (defconst js2-ecma-function-props
6336 (concat
6337 "^"
6338 (regexp-opt
6339 '(;; properties of the Object prototype object
6340 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6341 "toLocaleString" "toString" "valueOf"
6342 ;; properties of the Function prototype object
6343 "apply" "call"
6344 ;; properties of the Array prototype object
6345 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6346 "splice" "unshift"
6347 ;; properties of the String prototype object
6348 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6349 "localeCompare" "match" "replace" "search" "split" "substring"
6350 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6351 "toUpperCase"
6352 ;; properties of the Number prototype object
6353 "toExponential" "toFixed" "toPrecision"
6354 ;; properties of the Date prototype object
6355 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6356 "getMinutes" "getMonth" "getSeconds" "getTime"
6357 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6358 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6359 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6360 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6361 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6362 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6363 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6364 "toTimeString" "toUTCString"
6365 ;; properties of the RegExp prototype object
6366 "exec" "test"
6367 ;; properties of the JSON prototype object
6368 "parse" "stringify"
6369 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6370 "toSource" "__defineGetter__" "__defineSetter__"
6371 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6372 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6373 t)
6374 "$")
6375 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6376 Shown at or above `js2-highlight-level' 3.")
6377
6378 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6379 (let ((target-name (and target
6380 (js2-name-node-p target)
6381 (js2-name-node-name target)))
6382 (prop-name (if prop (js2-name-node-name prop)))
6383 (level1 (>= js2-highlight-level 1))
6384 (level2 (>= js2-highlight-level 2))
6385 (level3 (>= js2-highlight-level 3))
6386 pos
6387 face)
6388 (when level2
6389 (if call-p
6390 (cond
6391 ((and target prop)
6392 (cond
6393 ((and level3 (string-match js2-ecma-function-props prop-name))
6394 (setq face 'font-lock-builtin-face))
6395 ((and target-name prop)
6396 (cond
6397 ((string= target-name "Date")
6398 (if (string-match js2-ecma-date-props prop-name)
6399 (setq face 'font-lock-builtin-face)))
6400 ((string= target-name "Math")
6401 (if (string-match js2-ecma-math-funcs prop-name)
6402 (setq face 'font-lock-builtin-face)))))))
6403 (prop
6404 (if (string-match js2-ecma-global-funcs prop-name)
6405 (setq face 'font-lock-builtin-face))))
6406 (cond
6407 ((and target prop)
6408 (cond
6409 ((string= target-name "Number")
6410 (if (string-match js2-ecma-number-props prop-name)
6411 (setq face 'font-lock-constant-face)))
6412 ((string= target-name "Math")
6413 (if (string-match js2-ecma-math-props prop-name)
6414 (setq face 'font-lock-constant-face)))))
6415 (prop
6416 (if (string-match js2-ecma-object-props prop-name)
6417 (setq face 'font-lock-constant-face)))))
6418 (when face
6419 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6420 (js2-node-pos prop))) ; relative
6421 (+ pos (js2-node-len prop))
6422 face 'record)))))
6423
6424 (defun js2-parse-highlight-member-expr-node (node)
6425 "Perform syntax highlighting of EcmaScript built-in properties.
6426 The variable `js2-highlight-level' governs this highighting."
6427 (let (face target prop name pos end parent call-p callee)
6428 (cond
6429 ;; case 1: simple name, e.g. foo
6430 ((js2-name-node-p node)
6431 (setq name (js2-name-node-name node))
6432 ;; possible for name to be nil in rare cases - saw it when
6433 ;; running js2-mode on an elisp buffer. Might as well try to
6434 ;; make it so js2-mode never barfs.
6435 (when name
6436 (setq face (if (string-match js2-ecma-global-props name)
6437 'font-lock-constant-face))
6438 (when face
6439 (setq pos (js2-node-pos node)
6440 end (+ pos (js2-node-len node)))
6441 (js2-set-face pos end face 'record))))
6442 ;; case 2: property access or function call
6443 ((or (js2-prop-get-node-p node)
6444 ;; highlight function call if expr is a prop-get node
6445 ;; or a plain name (i.e. unqualified function call)
6446 (and (setq call-p (js2-call-node-p node))
6447 (setq callee (js2-call-node-target node)) ; separate setq!
6448 (or (js2-prop-get-node-p callee)
6449 (js2-name-node-p callee))))
6450 (setq parent node
6451 node (if call-p callee node))
6452 (if (and call-p (js2-name-node-p callee))
6453 (setq prop callee)
6454 (setq target (js2-prop-get-node-left node)
6455 prop (js2-prop-get-node-right node)))
6456 (cond
6457 ((js2-name-node-p target)
6458 (if (js2-name-node-p prop)
6459 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6460 (js2-parse-highlight-prop-get parent target prop call-p)
6461 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6462 (js2-parse-highlight-prop-get parent target nil call-p)))
6463 ((js2-name-node-p prop)
6464 ;; case 2c: complex target, simple name, e.g. x[y].bar
6465 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6466
6467 (defun js2-parse-highlight-member-expr-fn-name (expr)
6468 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6469 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6470 We currently only handle the case where the last component is a prop-get
6471 of a simple name. Called before EXPR has a parent node."
6472 (let (pos
6473 (name (and (js2-prop-get-node-p expr)
6474 (js2-prop-get-node-right expr))))
6475 (when (js2-name-node-p name)
6476 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6477 (js2-node-pos name)))
6478 (+ pos (js2-node-len name))
6479 'font-lock-function-name-face
6480 'record))))
6481
6482 ;; source: http://jsdoc.sourceforge.net/
6483 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6484 ;; allows type specifications, and needs work before entering the wild.
6485
6486 (defconst js2-jsdoc-param-tag-regexp
6487 (concat "^\\s-*\\*+\\s-*\\(@"
6488 "\\(?:param\\|argument\\)"
6489 "\\)"
6490 "\\s-*\\({[^}]+}\\)?" ; optional type
6491 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6492 "\\>")
6493 "Matches jsdoc tags with optional type and optional param name.")
6494
6495 (defconst js2-jsdoc-typed-tag-regexp
6496 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6497 (regexp-opt
6498 '("enum"
6499 "extends"
6500 "field"
6501 "id"
6502 "implements"
6503 "lends"
6504 "mods"
6505 "requires"
6506 "return"
6507 "returns"
6508 "throw"
6509 "throws"))
6510 "\\)\\)\\s-*\\({[^}]+}\\)?")
6511 "Matches jsdoc tags with optional type.")
6512
6513 (defconst js2-jsdoc-arg-tag-regexp
6514 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6515 (regexp-opt
6516 '("alias"
6517 "augments"
6518 "borrows"
6519 "bug"
6520 "base"
6521 "config"
6522 "default"
6523 "define"
6524 "exception"
6525 "function"
6526 "member"
6527 "memberOf"
6528 "name"
6529 "namespace"
6530 "property"
6531 "since"
6532 "suppress"
6533 "this"
6534 "throws"
6535 "type"
6536 "version"))
6537 "\\)\\)\\s-+\\([^ \t]+\\)")
6538 "Matches jsdoc tags with a single argument.")
6539
6540 (defconst js2-jsdoc-empty-tag-regexp
6541 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6542 (regexp-opt
6543 '("addon"
6544 "author"
6545 "class"
6546 "const"
6547 "constant"
6548 "constructor"
6549 "constructs"
6550 "deprecated"
6551 "desc"
6552 "description"
6553 "event"
6554 "example"
6555 "exec"
6556 "export"
6557 "fileoverview"
6558 "final"
6559 "function"
6560 "hidden"
6561 "ignore"
6562 "implicitCast"
6563 "inheritDoc"
6564 "inner"
6565 "interface"
6566 "license"
6567 "noalias"
6568 "noshadow"
6569 "notypecheck"
6570 "override"
6571 "owner"
6572 "preserve"
6573 "preserveTry"
6574 "private"
6575 "protected"
6576 "public"
6577 "static"
6578 "supported"
6579 ))
6580 "\\)\\)\\s-*")
6581 "Matches empty jsdoc tags.")
6582
6583 (defconst js2-jsdoc-link-tag-regexp
6584 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6585 "Matches a jsdoc link or code tag.")
6586
6587 (defconst js2-jsdoc-see-tag-regexp
6588 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6589 "Matches a jsdoc @see tag.")
6590
6591 (defconst js2-jsdoc-html-tag-regexp
6592 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6593 "Matches a simple (no attributes) html start- or end-tag.")
6594
6595 (defsubst js2-jsdoc-highlight-helper ()
6596 (js2-set-face (match-beginning 1)
6597 (match-end 1)
6598 'js2-jsdoc-tag-face)
6599 (if (match-beginning 2)
6600 (if (save-excursion
6601 (goto-char (match-beginning 2))
6602 (= (char-after) ?{))
6603 (js2-set-face (1+ (match-beginning 2))
6604 (1- (match-end 2))
6605 'js2-jsdoc-type-face)
6606 (js2-set-face (match-beginning 2)
6607 (match-end 2)
6608 'js2-jsdoc-value-face)))
6609 (if (match-beginning 3)
6610 (js2-set-face (match-beginning 3)
6611 (match-end 3)
6612 'js2-jsdoc-value-face)))
6613
6614 (defun js2-highlight-jsdoc (ast)
6615 "Highlight doc comment tags."
6616 (let ((comments (js2-ast-root-comments ast))
6617 beg end)
6618 (save-excursion
6619 (dolist (node comments)
6620 (when (eq (js2-comment-node-format node) 'jsdoc)
6621 (setq beg (js2-node-abs-pos node)
6622 end (+ beg (js2-node-len node)))
6623 (save-restriction
6624 (narrow-to-region beg end)
6625 (dolist (re (list js2-jsdoc-param-tag-regexp
6626 js2-jsdoc-typed-tag-regexp
6627 js2-jsdoc-arg-tag-regexp
6628 js2-jsdoc-link-tag-regexp
6629 js2-jsdoc-see-tag-regexp
6630 js2-jsdoc-empty-tag-regexp))
6631 (goto-char beg)
6632 (while (re-search-forward re nil t)
6633 (js2-jsdoc-highlight-helper)))
6634 ;; simple highlighting for html tags
6635 (goto-char beg)
6636 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6637 (js2-set-face (match-beginning 1)
6638 (match-end 1)
6639 'js2-jsdoc-html-tag-delimiter-face)
6640 (js2-set-face (match-beginning 2)
6641 (match-end 2)
6642 'js2-jsdoc-html-tag-name-face)
6643 (js2-set-face (match-beginning 3)
6644 (match-end 3)
6645 'js2-jsdoc-html-tag-delimiter-face))))))))
6646
6647 (defun js2-highlight-assign-targets (node left right)
6648 "Highlight function properties and external variables."
6649 (let (leftpos end name)
6650 ;; highlight vars and props assigned function values
6651 (when (js2-function-node-p right)
6652 (cond
6653 ;; var foo = function() {...}
6654 ((js2-name-node-p left)
6655 (setq name left))
6656 ;; foo.bar.baz = function() {...}
6657 ((and (js2-prop-get-node-p left)
6658 (js2-name-node-p (js2-prop-get-node-right left)))
6659 (setq name (js2-prop-get-node-right left))))
6660 (when name
6661 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6662 (+ leftpos (js2-node-len name))
6663 'font-lock-function-name-face
6664 'record)))))
6665
6666 (defun js2-record-name-node (node)
6667 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6668 later. NODE must be a name node."
6669 (let (leftpos end)
6670 (push (list node js2-current-scope
6671 (setq leftpos (js2-node-abs-pos node))
6672 (setq end (+ leftpos (js2-node-len node))))
6673 js2-recorded-identifiers)))
6674
6675 (defun js2-highlight-undeclared-vars ()
6676 "After entire parse is finished, look for undeclared variable references.
6677 We have to wait until entire buffer is parsed, since JavaScript permits var
6678 decls to occur after they're used.
6679
6680 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6681 it is considered declared."
6682 (let (name)
6683 (dolist (entry js2-recorded-identifiers)
6684 (destructuring-bind (name-node scope pos end) entry
6685 (setq name (js2-name-node-name name-node))
6686 (unless (or (member name js2-global-externs)
6687 (member name js2-default-externs)
6688 (member name js2-additional-externs)
6689 (js2-get-defining-scope scope name))
6690 (js2-set-face pos end 'js2-external-variable-face 'record)
6691 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6692 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6693 (setq js2-recorded-identifiers nil)))
6694
6695 ;;; IMenu support
6696
6697 ;; We currently only support imenu, but eventually should support speedbar and
6698 ;; possibly other browsing mechanisms.
6699
6700 ;; The basic strategy is to identify function assignment targets of the form
6701 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6702 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6703 ;; for imenu after parsing is finished.
6704
6705 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6706 ;; JavaScript, and the general problem is undecidable. However, several forms
6707 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6708 ;; include:
6709
6710 ;; function foo() -- function declaration
6711 ;; foo = function() -- function expression assigned to variable
6712 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6713 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6714 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6715 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6716 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6717 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6718 ;; function foo() {function bar() {...}} -- nested function
6719 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6720
6721 ;; This list boils down to a few forms that can be combined recursively.
6722 ;; Top-level named function declarations include both the left-hand (name)
6723 ;; and the right-hand (function value) expressions needed to produce an imenu
6724 ;; entry. The other "right-hand" forms we need to look for are:
6725 ;; - functions declared as props/getters/setters in object literals
6726 ;; - nested named function declarations
6727 ;; The "left-hand" expressions that functions can be assigned to include:
6728 ;; - local/global variables
6729 ;; - nested property-get expressions like a.b.c.d
6730 ;; - element gets like foo[10] or foo['bar'] where the index
6731 ;; expression can be trivially converted to a property name. They
6732 ;; effectively then become property gets.
6733
6734 ;; All the different definition types are canonicalized into the form
6735 ;; foo.bar.baz = position-of-function-keyword
6736
6737 ;; We need to build a trie-like structure for imenu. As an example,
6738 ;; consider the following JavaScript code:
6739
6740 ;; a = function() {...} // function at position 5
6741 ;; b = function() {...} // function at position 25
6742 ;; foo = function() {...} // function at position 100
6743 ;; foo.bar = function() {...} // function at position 200
6744 ;; foo.bar.baz = function() {...} // function at position 300
6745 ;; foo.bar.zab = function() {...} // function at position 400
6746
6747 ;; During parsing we accumulate an entry for each definition in
6748 ;; the variable `js2-imenu-recorder', like so:
6749
6750 ;; '((fn a 5)
6751 ;; (fn b 25)
6752 ;; (fn foo 100)
6753 ;; (fn foo bar 200)
6754 ;; (fn foo bar baz 300)
6755 ;; (fn foo bar zab 400))
6756
6757 ;; Where 'fn' is the respective function node.
6758 ;; After parsing these entries are merged into this alist-trie:
6759
6760 ;; '((a . 1)
6761 ;; (b . 2)
6762 ;; (foo (<definition> . 3)
6763 ;; (bar (<definition> . 6)
6764 ;; (baz . 100)
6765 ;; (zab . 200))))
6766
6767 ;; Note the wacky need for a <definition> name. The token can be anything
6768 ;; that isn't a valid JavaScript identifier, because you might make foo
6769 ;; a function and then start setting properties on it that are also functions.
6770
6771 (defsubst js2-prop-node-name (node)
6772 "Return the name of a node that may be a property-get/property-name.
6773 If NODE is not a valid name-node, string-node or integral number-node,
6774 returns nil. Otherwise returns the string name/value of the node."
6775 (cond
6776 ((js2-name-node-p node)
6777 (js2-name-node-name node))
6778 ((js2-string-node-p node)
6779 (js2-string-node-value node))
6780 ((and (js2-number-node-p node)
6781 (string-match "^[0-9]+$" (js2-number-node-value node)))
6782 (js2-number-node-value node))
6783 ((js2-this-node-p node)
6784 "this")))
6785
6786 (defsubst js2-node-qname-component (node)
6787 "Return the name of this node, if it contributes to a qname.
6788 Returns nil if the node doesn't contribute."
6789 (copy-sequence
6790 (or (js2-prop-node-name node)
6791 (if (and (js2-function-node-p node)
6792 (js2-function-node-name node))
6793 (js2-name-node-name (js2-function-node-name node))))))
6794
6795 (defsubst js2-record-imenu-entry (fn-node qname pos)
6796 "Add an entry to `js2-imenu-recorder'.
6797 FN-NODE should be the current item's function node.
6798
6799 Associate FN-NODE with its QNAME for later lookup.
6800 This is used in postprocessing the chain list. For each chain, we find
6801 the parent function, look up its qname, then prepend a copy of it to the chain."
6802 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6803 (unless js2-imenu-function-map
6804 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6805 (puthash fn-node qname js2-imenu-function-map))
6806
6807 (defun js2-record-imenu-functions (node &optional var)
6808 "Record function definitions for imenu.
6809 NODE is a function node or an object literal.
6810 VAR, if non-nil, is the expression that NODE is being assigned to.
6811 When passed arguments of wrong type, does nothing."
6812 (when js2-parse-ide-mode
6813 (let ((fun-p (js2-function-node-p node))
6814 qname left fname-node pos)
6815 (cond
6816 ;; non-anonymous function declaration?
6817 ((and fun-p
6818 (not var)
6819 (setq fname-node (js2-function-node-name node)))
6820 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6821 ;; for remaining forms, compute left-side tree branch first
6822 ((and var (setq qname (js2-compute-nested-prop-get var)))
6823 (cond
6824 ;; foo.bar.baz = function
6825 (fun-p
6826 (js2-record-imenu-entry node qname (js2-node-pos node)))
6827 ;; foo.bar.baz = object-literal
6828 ;; look for nested functions: {a: {b: function() {...} }}
6829 ((js2-object-node-p node)
6830 ;; Node position here is still absolute, since the parser
6831 ;; passes the assignment target and value expressions
6832 ;; to us before they are added as children of the assignment node.
6833 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6834
6835 (defun js2-compute-nested-prop-get (node)
6836 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6837 component nodes as a list. Otherwise return nil. Element-gets are treated
6838 as property-gets if the index expression is a string, or a positive integer."
6839 (let (left right head)
6840 (cond
6841 ((or (js2-name-node-p node)
6842 (js2-this-node-p node))
6843 (list node))
6844 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6845 ((js2-prop-get-node-p node) ; foo.bar
6846 (setq left (js2-prop-get-node-left node)
6847 right (js2-prop-get-node-right node))
6848 (if (setq head (js2-compute-nested-prop-get left))
6849 (nconc head (list right))))
6850 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6851 (setq left (js2-elem-get-node-target node)
6852 right (js2-elem-get-node-element node))
6853 (if (or (js2-string-node-p right) ; ['bar']
6854 (and (js2-number-node-p right) ; [10]
6855 (string-match "^[0-9]+$"
6856 (js2-number-node-value right))))
6857 (if (setq head (js2-compute-nested-prop-get left))
6858 (nconc head (list right))))))))
6859
6860 (defun js2-record-object-literal (node qname pos)
6861 "Recursively process an object literal looking for functions.
6862 NODE is an object literal that is the right-hand child of an assignment
6863 expression. QNAME is a list of nodes representing the assignment target,
6864 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6865 POS is the absolute position of the node.
6866 We do a depth-first traversal of NODE. For any functions we find,
6867 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6868 (let (left right prop-qname)
6869 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6870 (let ((left (js2-infix-node-left e))
6871 ;; Element positions are relative to the parent position.
6872 (pos (+ pos (js2-node-pos e))))
6873 (cond
6874 ;; foo: function() {...}
6875 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6876 (when (js2-prop-node-name left)
6877 ;; As a policy decision, we record the position of the property,
6878 ;; not the position of the `function' keyword, since the property
6879 ;; is effectively the name of the function.
6880 (js2-record-imenu-entry right (append qname (list left)) pos)))
6881 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6882 ((js2-object-node-p right)
6883 (js2-record-object-literal right
6884 (append qname (list (js2-infix-node-left e)))
6885 (+ pos (js2-node-pos right)))))))))
6886
6887 (defsubst js2-node-top-level-decl-p (node)
6888 "Return t if NODE's name is defined in the top-level scope.
6889 Also returns t if NODE's name is not defined in any scope, since it implies
6890 that it's an external variable, which must also be in the top-level scope."
6891 (let* ((name (js2-prop-node-name node))
6892 (this-scope (js2-node-get-enclosing-scope node))
6893 defining-scope)
6894 (cond
6895 ((js2-this-node-p node)
6896 nil)
6897 ((null this-scope)
6898 t)
6899 ((setq defining-scope (js2-get-defining-scope this-scope name))
6900 (js2-ast-root-p defining-scope))
6901 (t t))))
6902
6903 (defsubst js2-wrapper-function-p (node)
6904 "Returns t if NODE is a function expression that's immediately invoked.
6905 NODE must be `js2-function-node'."
6906 (let ((parent (js2-node-parent node)))
6907 (or
6908 ;; function(){...}();
6909 (js2-call-node-p parent)
6910 (and (js2-paren-node-p parent)
6911 ;; (function(){...})();
6912 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6913 ;; (function(){...}).call(this);
6914 (and (js2-prop-get-node-p parent)
6915 (member (js2-name-node-name (js2-prop-get-node-right parent))
6916 '("call" "apply"))
6917 (js2-call-node-p (js2-node-parent parent))))))))
6918
6919 (defun js2-browse-postprocess-chains (entries)
6920 "Modify function-declaration name chains after parsing finishes.
6921 Some of the information is only available after the parse tree is complete.
6922 For instance, processing a nested scope requires a parent function node."
6923 (let (result head fn current-fn parent-qname qname p elem)
6924 (dolist (entry entries)
6925 ;; function node goes first
6926 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6927 ;; Examine head's defining scope:
6928 ;; Pre-processed chain, or top-level/external, keep as-is.
6929 (if (or (stringp head) (js2-node-top-level-decl-p head))
6930 (push chain result)
6931 (when (js2-this-node-p head)
6932 (setq chain (cdr chain))) ; discard this-node
6933 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6934 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6935 (when (eq parent-qname 'not-found)
6936 ;; anonymous function expressions are not recorded
6937 ;; during the parse, so we need to handle this case here
6938 (setq parent-qname
6939 (if (js2-wrapper-function-p fn)
6940 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6941 (if (js2-ast-root-p grandparent)
6942 nil
6943 (gethash grandparent js2-imenu-function-map 'skip)))
6944 'skip))
6945 (puthash fn parent-qname js2-imenu-function-map))
6946 (unless (eq parent-qname 'skip)
6947 ;; prefix parent fn qname to this chain.
6948 (let ((qname (append parent-qname chain)))
6949 (puthash current-fn (butlast qname) js2-imenu-function-map)
6950 (push qname result)))))))
6951 ;; finally replace each node in each chain with its name.
6952 (dolist (chain result)
6953 (setq p chain)
6954 (while p
6955 (if (js2-node-p (setq elem (car p)))
6956 (setcar p (js2-node-qname-component elem)))
6957 (setq p (cdr p))))
6958 result))
6959
6960 ;; Merge name chains into a trie-like tree structure of nested lists.
6961 ;; To simplify construction of the trie, we first build it out using the rule
6962 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6963 ;; [key, num-or-list]. The second element can be a number; if so, this key
6964 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6965 ;; associated with the key at this level.) Otherwise the second element is
6966 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6967 ;; a simple recursive formulation.
6968 ;;
6969 ;; js2-mode is building the data structure for imenu. The imenu documentation
6970 ;; claims that it's the structure above, but in practice it wants the children
6971 ;; at the same list level as the key for that level, which is how I've drawn
6972 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6973 ;; list wrapper around the children at each level.
6974 ;;
6975 ;; A completed nested imenu-alist entry looks like this:
6976 ;; '(("foo"
6977 ;; ("<definition>" . 7)
6978 ;; ("bar"
6979 ;; ("a" . 40)
6980 ;; ("b" . 60))))
6981 ;;
6982 ;; In particular, the documentation for `imenu--index-alist' says that
6983 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6984 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6985
6986 (defun js2-treeify (lst)
6987 "Convert (a b c d) to (a ((b ((c d)))))"
6988 (if (null (cddr lst)) ; list length <= 2
6989 lst
6990 (list (car lst) (list (js2-treeify (cdr lst))))))
6991
6992 (defun js2-build-alist-trie (chains trie)
6993 "Merge declaration name chains into a trie-like alist structure for imenu.
6994 CHAINS is the qname chain list produced during parsing. TRIE is a
6995 list of elements built up so far."
6996 (let (head tail pos branch kids)
6997 (dolist (chain chains)
6998 (setq head (car chain)
6999 tail (cdr chain)
7000 pos (if (numberp (car tail)) (car tail))
7001 branch (js2-find-if (lambda (n)
7002 (string= (car n) head))
7003 trie)
7004 kids (second branch))
7005 (cond
7006 ;; case 1: this key isn't in the trie yet
7007 ((null branch)
7008 (if trie
7009 (setcdr (last trie) (list (js2-treeify chain)))
7010 (setq trie (list (js2-treeify chain)))))
7011 ;; case 2: key is present with a single number entry: replace w/ list
7012 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7013 ;; ("<definition>" 20)))
7014 ((numberp kids)
7015 (setcar (cdr branch)
7016 (list (list "<definition-1>" kids)
7017 (if pos
7018 (list "<definition-2>" pos)
7019 (js2-treeify tail)))))
7020 ;; case 3: key is there (with kids), and we're a number entry
7021 (pos
7022 (setcdr (last kids)
7023 (list
7024 (list (format "<definition-%d>"
7025 (1+ (loop for kid in kids
7026 count (eq ?< (aref (car kid) 0)))))
7027 pos))))
7028 ;; case 4: key is there with kids, need to merge in our chain
7029 (t
7030 (js2-build-alist-trie (list tail) kids))))
7031 trie))
7032
7033 (defun js2-flatten-trie (trie)
7034 "Convert TRIE to imenu-format.
7035 Recurses through nodes, and for each one whose second element is a list,
7036 appends the list's flattened elements to the current element. Also
7037 changes the tails into conses. For instance, this pre-flattened trie
7038
7039 '(a ((b 20)
7040 (c ((d 30)
7041 (e 40)))))
7042
7043 becomes
7044
7045 '(a (b . 20)
7046 (c (d . 30)
7047 (e . 40)))
7048
7049 Note that the root of the trie has no key, just a list of chains.
7050 This is also true for the value of any key with multiple children,
7051 e.g. key 'c' in the example above."
7052 (cond
7053 ((listp (car trie))
7054 (mapcar #'js2-flatten-trie trie))
7055 (t
7056 (if (numberp (second trie))
7057 (cons (car trie) (second trie))
7058 ;; else pop list and append its kids
7059 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7060
7061 (defun js2-build-imenu-index ()
7062 "Turn `js2-imenu-recorder' into an imenu data structure."
7063 (unless (eq js2-imenu-recorder 'empty)
7064 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7065 (result (js2-build-alist-trie chains nil)))
7066 (js2-flatten-trie result))))
7067
7068 (defun js2-test-print-chains (chains)
7069 "Print a list of qname chains.
7070 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7071 i.e. one or more nodes, and an integer position as the list tail."
7072 (mapconcat (lambda (chain)
7073 (concat "("
7074 (mapconcat (lambda (elem)
7075 (if (js2-node-p elem)
7076 (or (js2-node-qname-component elem)
7077 "nil")
7078 (number-to-string elem)))
7079 chain
7080 " ")
7081 ")"))
7082 chains
7083 "\n"))
7084
7085 ;;; Parser
7086
7087 (defconst js2-version "1.8.0"
7088 "Version of JavaScript supported, plus minor js2 version.")
7089
7090 (defmacro js2-record-face (face)
7091 "Record a style run of FACE for the current token."
7092 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7093
7094 (defsubst js2-node-end (n)
7095 "Computes the absolute end of node N.
7096 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7097 is only true until the node is added to its parent; i.e., while parsing."
7098 (+ (js2-node-pos n)
7099 (js2-node-len n)))
7100
7101 (defsubst js2-record-comment ()
7102 "Record a comment in `js2-scanned-comments'."
7103 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7104 :format js2-ts-comment-type)
7105 js2-scanned-comments)
7106 (when js2-parse-ide-mode
7107 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7108 'font-lock-doc-face
7109 'font-lock-comment-face))
7110 (when (memq js2-ts-comment-type '(html preprocessor))
7111 ;; Tell cc-engine the bounds of the comment.
7112 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7113
7114 ;; This function is called depressingly often, so it should be fast.
7115 ;; Most of the time it's looking at the same token it peeked before.
7116 (defsubst js2-peek-token ()
7117 "Returns the next token without consuming it.
7118 If previous token was consumed, calls scanner to get new token.
7119 If previous token was -not- consumed, returns it (idempotent).
7120
7121 This function will not return a newline (js2-EOL) - instead, it
7122 gobbles newlines until it finds a non-newline token, and flags
7123 that token as appearing just after a newline.
7124
7125 This function will also not return a js2-COMMENT. Instead, it
7126 records comments found in `js2-scanned-comments'. If the token
7127 returned by this function immediately follows a jsdoc comment,
7128 the token is flagged as such.
7129
7130 Note that this function always returned the un-flagged token!
7131 The flags, if any, are saved in `js2-current-flagged-token'."
7132 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7133 js2-current-token ; most common case - return already-peeked token
7134 (let ((tt (js2-get-token)) ; call scanner
7135 saw-eol
7136 face)
7137 ;; process comments and whitespace
7138 (while (or (= tt js2-EOL)
7139 (= tt js2-COMMENT))
7140 (if (= tt js2-EOL)
7141 (setq saw-eol t)
7142 (setq saw-eol nil)
7143 (if js2-record-comments
7144 (js2-record-comment)))
7145 (setq tt (js2-get-token))) ; call scanner
7146 (setq js2-current-token tt
7147 js2-current-flagged-token (if saw-eol
7148 (logior tt js2-ti-after-eol)
7149 tt))
7150 ;; perform lexical fontification as soon as token is scanned
7151 (when js2-parse-ide-mode
7152 (cond
7153 ((minusp tt)
7154 (js2-record-face 'js2-error-face))
7155 ((setq face (aref js2-kwd-tokens tt))
7156 (js2-record-face face))
7157 ((and (= tt js2-NAME)
7158 (equal js2-ts-string "undefined"))
7159 (js2-record-face 'font-lock-constant-face))))
7160 tt))) ; return unflagged token
7161
7162 (defsubst js2-peek-flagged-token ()
7163 "Returns the current token along with any flags set for it."
7164 (js2-peek-token)
7165 js2-current-flagged-token)
7166
7167 (defsubst js2-consume-token ()
7168 (setq js2-current-flagged-token js2-EOF))
7169
7170 (defsubst js2-next-token ()
7171 (prog1
7172 (js2-peek-token)
7173 (js2-consume-token)))
7174
7175 (defsubst js2-next-flagged-token ()
7176 (js2-peek-token)
7177 (prog1 js2-current-flagged-token
7178 (js2-consume-token)))
7179
7180 (defsubst js2-match-token (match)
7181 "Consume and return t if next token matches MATCH, a bytecode.
7182 Returns nil and consumes nothing if MATCH is not the next token."
7183 (if (/= (js2-peek-token) match)
7184 nil
7185 (js2-consume-token)
7186 t))
7187
7188 (defsubst js2-valid-prop-name-token (tt)
7189 (or (= tt js2-NAME)
7190 (when (and js2-allow-keywords-as-property-names
7191 (plusp tt)
7192 (aref js2-kwd-tokens tt))
7193 (js2-save-name-token-data js2-token-beg (js2-token-name tt))
7194 t)))
7195
7196 (defsubst js2-match-prop-name ()
7197 "Consume token and return t if next token is a valid property name.
7198 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7199 is non-nil and it's a keyword token."
7200 (if (js2-valid-prop-name-token (js2-peek-token))
7201 (progn
7202 (js2-consume-token)
7203 t)
7204 nil))
7205
7206 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7207 (if (js2-match-prop-name)
7208 t
7209 (js2-report-error msg-id nil pos len)
7210 nil))
7211
7212 (defsubst js2-peek-token-or-eol ()
7213 "Return js2-EOL if the current token immediately follows a newline.
7214 Else returns the current token. Used in situations where we don't
7215 consider certain token types valid if they are preceded by a newline.
7216 One example is the postfix ++ or -- operator, which has to be on the
7217 same line as its operand."
7218 (let ((tt (js2-peek-token)))
7219 ;; Check for last peeked token flags
7220 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7221 js2-EOL
7222 tt)))
7223
7224 (defsubst js2-set-check-for-label ()
7225 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7226 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7227
7228 (defsubst js2-must-match (token msg-id &optional pos len)
7229 "Match next token to token code TOKEN, or record a syntax error.
7230 MSG-ID is the error message to report if the match fails.
7231 Returns t on match, nil if no match."
7232 (if (js2-match-token token)
7233 t
7234 (js2-report-error msg-id nil pos len)
7235 nil))
7236
7237 (defsubst js2-inside-function ()
7238 (plusp js2-nesting-of-function))
7239
7240 (defsubst js2-set-requires-activation ()
7241 (if (js2-function-node-p js2-current-script-or-fn)
7242 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7243
7244 (defsubst js2-check-activation-name (name token)
7245 (when (js2-inside-function)
7246 ;; skip language-version 1.2 check from Rhino
7247 (if (or (string= "arguments" name)
7248 (and js2-compiler-activation-names ; only used in codegen
7249 (gethash name js2-compiler-activation-names)))
7250 (js2-set-requires-activation))))
7251
7252 (defsubst js2-set-is-generator ()
7253 (if (js2-function-node-p js2-current-script-or-fn)
7254 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7255
7256 (defsubst js2-must-have-xml ()
7257 (unless js2-compiler-xml-available
7258 (js2-report-error "msg.XML.not.available")))
7259
7260 (defsubst js2-push-scope (scope)
7261 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7262 (assert (js2-scope-p scope))
7263 (assert (null (js2-scope-parent-scope scope)))
7264 (assert (not (eq js2-current-scope scope)))
7265 (setf (js2-scope-parent-scope scope) js2-current-scope
7266 js2-current-scope scope))
7267
7268 (defsubst js2-pop-scope ()
7269 (setq js2-current-scope
7270 (js2-scope-parent-scope js2-current-scope)))
7271
7272 (defsubst js2-enter-loop (loop-node)
7273 (push loop-node js2-loop-set)
7274 (push loop-node js2-loop-and-switch-set)
7275 (js2-push-scope loop-node)
7276 ;; Tell the current labeled statement (if any) its statement,
7277 ;; and set the jump target of the first label to the loop.
7278 ;; These are used in `js2-parse-continue' to verify that the
7279 ;; continue target is an actual labeled loop. (And for codegen.)
7280 (when js2-labeled-stmt
7281 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7282 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7283 js2-labeled-stmt))) loop-node)))
7284
7285 (defsubst js2-exit-loop ()
7286 (pop js2-loop-set)
7287 (pop js2-loop-and-switch-set)
7288 (js2-pop-scope))
7289
7290 (defsubst js2-enter-switch (switch-node)
7291 (push switch-node js2-loop-and-switch-set))
7292
7293 (defsubst js2-exit-switch ()
7294 (pop js2-loop-and-switch-set))
7295
7296 (defun js2-parse (&optional buf cb)
7297 "Tells the js2 parser to parse a region of JavaScript.
7298
7299 BUF is a buffer or buffer name containing the code to parse.
7300 Call `narrow-to-region' first to parse only part of the buffer.
7301
7302 The returned AST root node is given some additional properties:
7303 `node-count' - total number of nodes in the AST
7304 `buffer' - BUF. The buffer it refers to may change or be killed,
7305 so the value is not necessarily reliable.
7306
7307 An optional callback CB can be specified to report parsing
7308 progress. If `(functionp CB)' returns t, it will be called with
7309 the current line number once before parsing begins, then again
7310 each time the lexer reaches a new line number.
7311
7312 CB can also be a list of the form `(symbol cb ...)' to specify
7313 multiple callbacks with different criteria. Each symbol is a
7314 criterion keyword, and the following element is the callback to
7315 call
7316
7317 :line - called whenever the line number changes
7318 :token - called for each new token consumed
7319
7320 The list of criteria could be extended to include entering or
7321 leaving a statement, an expression, or a function definition."
7322 (if (and cb (not (functionp cb)))
7323 (error "criteria callbacks not yet implemented"))
7324 (let ((inhibit-point-motion-hooks t)
7325 (js2-compiler-xml-available (>= js2-language-version 160))
7326 ;; This is a recursive-descent parser, so give it a big stack.
7327 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7328 (max-specpdl-size (max max-specpdl-size 3000))
7329 (case-fold-search nil)
7330 ast)
7331 (message nil) ; clear any error message from previous parse
7332 (save-excursion
7333 (when buf (set-buffer buf))
7334 (setq js2-scanned-comments nil
7335 js2-parsed-errors nil
7336 js2-parsed-warnings nil
7337 js2-imenu-recorder nil
7338 js2-imenu-function-map nil
7339 js2-label-set nil)
7340 (js2-init-scanner)
7341 (setq ast (js2-with-unmodifying-text-property-changes
7342 (js2-do-parse)))
7343 (unless js2-ts-hit-eof
7344 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7345 (setf (js2-ast-root-errors ast) js2-parsed-errors
7346 (js2-ast-root-warnings ast) js2-parsed-warnings)
7347 ;; if we didn't find any declarations, put a dummy in this list so we
7348 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7349 (unless js2-imenu-recorder
7350 (setq js2-imenu-recorder 'empty))
7351 (run-hooks 'js2-parse-finished-hook)
7352 ast)))
7353
7354 ;; Corresponds to Rhino's Parser.parse() method.
7355 (defun js2-do-parse ()
7356 "Parse current buffer starting from current point.
7357 Scanner should be initialized."
7358 (let ((pos js2-ts-cursor)
7359 (end js2-ts-cursor) ; in case file is empty
7360 root n tt)
7361 ;; initialize buffer-local parsing vars
7362 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7363 js2-current-script-or-fn root
7364 js2-current-scope root
7365 js2-current-flagged-token js2-EOF
7366 js2-nesting-of-function 0
7367 js2-labeled-stmt nil
7368 js2-recorded-identifiers nil) ; for js2-highlight
7369 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7370 (if (= tt js2-FUNCTION)
7371 (progn
7372 (js2-consume-token)
7373 (setq n (js2-parse-function (if js2-called-by-compile-function
7374 'FUNCTION_EXPRESSION
7375 'FUNCTION_STATEMENT))))
7376 ;; not a function - parse a statement
7377 (setq n (js2-parse-statement)))
7378 ;; add function or statement to script
7379 (setq end (js2-node-end n))
7380 (js2-block-node-push root n))
7381 ;; add comments to root in lexical order
7382 (when js2-scanned-comments
7383 ;; if we find a comment beyond end of normal kids, use its end
7384 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7385 (dolist (comment js2-scanned-comments)
7386 (push comment (js2-ast-root-comments root))
7387 (js2-node-add-children root comment)))
7388 (setf (js2-node-len root) (- end pos))
7389 ;; Give extensions a chance to muck with things before highlighting starts.
7390 (let ((js2-additional-externs js2-additional-externs))
7391 (dolist (callback js2-post-parse-callbacks)
7392 (funcall callback))
7393 (js2-highlight-undeclared-vars))
7394 root))
7395
7396 (defun js2-function-parser ()
7397 (js2-consume-token)
7398 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7399
7400 (defun js2-parse-function-closure-body (fn-node)
7401 "Parse a JavaScript 1.8 function closure body."
7402 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7403 (if js2-ts-hit-eof
7404 (js2-report-error "msg.no.brace.body" nil
7405 (js2-node-pos fn-node)
7406 (- js2-ts-cursor (js2-node-pos fn-node)))
7407 (js2-node-add-children fn-node
7408 (setf (js2-function-node-body fn-node)
7409 (js2-parse-expr t))))))
7410
7411 (defun js2-parse-function-body (fn-node)
7412 (js2-must-match js2-LC "msg.no.brace.body"
7413 (js2-node-pos fn-node)
7414 (- js2-ts-cursor (js2-node-pos fn-node)))
7415 (let ((pos js2-token-beg) ; LC position
7416 (pn (make-js2-block-node)) ; starts at LC position
7417 tt
7418 end)
7419 (incf js2-nesting-of-function)
7420 (unwind-protect
7421 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7422 (= tt js2-EOF)
7423 (= tt js2-RC)))
7424 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7425 (js2-parse-statement)
7426 (js2-consume-token)
7427 (js2-parse-function 'FUNCTION_STATEMENT))))
7428 (decf js2-nesting-of-function))
7429 (setq end js2-token-end) ; assume no curly and leave at current token
7430 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7431 (setq end js2-token-end))
7432 (setf (js2-node-pos pn) pos
7433 (js2-node-len pn) (- end pos))
7434 (setf (js2-function-node-body fn-node) pn)
7435 (js2-node-add-children fn-node pn)
7436 pn))
7437
7438 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7439 "Declare and fontify destructuring parameters inside NODE.
7440 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7441 (cond
7442 ((js2-name-node-p node)
7443 (let (leftpos)
7444 (js2-define-symbol decl-type (js2-name-node-name node)
7445 node ignore-not-in-block)
7446 (when face
7447 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7448 (+ leftpos (js2-node-len node))
7449 face 'record))))
7450 ((js2-object-node-p node)
7451 (dolist (elem (js2-object-node-elems node))
7452 (js2-define-destruct-symbols
7453 (if (js2-object-prop-node-p elem)
7454 (js2-object-prop-node-right elem)
7455 ;; abbreviated destructuring {a, b}
7456 elem)
7457 decl-type face ignore-not-in-block)))
7458 ((js2-array-node-p node)
7459 (dolist (elem (js2-array-node-elems node))
7460 (when elem
7461 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7462 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7463 (js2-node-len node)))))
7464
7465 (defun js2-parse-function-params (fn-node pos)
7466 (if (js2-match-token js2-RP)
7467 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7468 (let (params len param)
7469 (loop for tt = (js2-peek-token)
7470 do
7471 (cond
7472 ;; destructuring param
7473 ((or (= tt js2-LB) (= tt js2-LC))
7474 (setq param (js2-parse-primary-expr-lhs))
7475 (js2-define-destruct-symbols param
7476 js2-LP
7477 'js2-function-param-face)
7478 (push param params))
7479 ;; simple name
7480 (t
7481 (js2-must-match js2-NAME "msg.no.parm")
7482 (js2-record-face 'js2-function-param-face)
7483 (setq param (js2-create-name-node))
7484 (js2-define-symbol js2-LP js2-ts-string param)
7485 (push param params)))
7486 while
7487 (js2-match-token js2-COMMA))
7488 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7489 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7490 (dolist (p params)
7491 (js2-node-add-children fn-node p)
7492 (push p (js2-function-node-params fn-node))))))
7493
7494 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7495 "Possibly show inconsistent-return warning.
7496 Last token scanned is the close-curly for the function body."
7497 (when (and js2-mode-show-strict-warnings
7498 js2-strict-inconsistent-return-warning
7499 (not (js2-has-consistent-return-usage
7500 (js2-function-node-body fn-node))))
7501 ;; Have it extend from close-curly to bol or beginning of block.
7502 (let ((pos (save-excursion
7503 (goto-char js2-token-end)
7504 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7505 (point-at-bol))))
7506 (end js2-token-end))
7507 (if (plusp (js2-name-node-length name))
7508 (js2-add-strict-warning "msg.no.return.value"
7509 (js2-name-node-name name) pos end)
7510 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7511
7512 (defun js2-parse-function (function-type)
7513 "Function parser. FUNCTION-TYPE is a symbol."
7514 (let ((pos js2-token-beg) ; start of 'function' keyword
7515 name
7516 name-beg
7517 name-end
7518 fn-node
7519 lp
7520 (synthetic-type function-type)
7521 member-expr-node)
7522 ;; parse function name, expression, or non-name (anonymous)
7523 (cond
7524 ;; function foo(...)
7525 ((js2-match-token js2-NAME)
7526 (setq name (js2-create-name-node t)
7527 name-beg js2-token-beg
7528 name-end js2-token-end)
7529 (unless (js2-match-token js2-LP)
7530 (when js2-allow-member-expr-as-function-name
7531 ;; function foo.bar(...)
7532 (setq member-expr-node name
7533 name nil
7534 member-expr-node (js2-parse-member-expr-tail
7535 nil member-expr-node)))
7536 (js2-must-match js2-LP "msg.no.paren.parms")))
7537 ((js2-match-token js2-LP)
7538 nil) ; anonymous function: leave name as null
7539 (t
7540 ;; function random-member-expr(...)
7541 (when js2-allow-member-expr-as-function-name
7542 ;; Note that memberExpr can not start with '(' like
7543 ;; in function (1+2).toString(), because 'function (' already
7544 ;; processed as anonymous function
7545 (setq member-expr-node (js2-parse-member-expr)))
7546 (js2-must-match js2-LP "msg.no.paren.parms")))
7547 (if (= js2-current-token js2-LP) ; eventually matched LP?
7548 (setq lp js2-token-beg))
7549 (if member-expr-node
7550 (progn
7551 (setq synthetic-type 'FUNCTION_EXPRESSION)
7552 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7553 (if name
7554 (js2-set-face name-beg name-end
7555 'font-lock-function-name-face 'record)))
7556 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7557 (plusp (js2-name-node-length name)))
7558 ;; Function statements define a symbol in the enclosing scope
7559 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7560 (setf fn-node (make-js2-function-node :pos pos
7561 :name name
7562 :form function-type
7563 :lp (if lp (- lp pos))))
7564 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7565 ;; 1. Nested functions are not affected by the dynamic scope flag
7566 ;; as dynamic scope is already a parent of their scope.
7567 ;; 2. Functions defined under the with statement also immune to
7568 ;; this setup, in which case dynamic scope is ignored in favor
7569 ;; of the with object.
7570 (setf (js2-function-node-ignore-dynamic fn-node) t))
7571 ;; dynamically bind all the per-function variables
7572 (let ((js2-current-script-or-fn fn-node)
7573 (js2-current-scope fn-node)
7574 (js2-nesting-of-with 0)
7575 (js2-end-flags 0)
7576 js2-label-set
7577 js2-loop-set
7578 js2-loop-and-switch-set)
7579 (js2-parse-function-params fn-node pos)
7580 (if (and (>= js2-language-version 180)
7581 (/= (js2-peek-token) js2-LC))
7582 (js2-parse-function-closure-body fn-node)
7583 (js2-parse-function-body fn-node))
7584 (if name
7585 (js2-node-add-children fn-node name))
7586 (js2-check-inconsistent-return-warning fn-node name)
7587 ;; Function expressions define a name only in the body of the
7588 ;; function, and only if not hidden by a parameter name
7589 (if (and name
7590 (eq synthetic-type 'FUNCTION_EXPRESSION)
7591 (null (js2-scope-get-symbol js2-current-scope
7592 (js2-name-node-name name))))
7593 (js2-define-symbol js2-FUNCTION
7594 (js2-name-node-name name)
7595 fn-node))
7596 (if (and name
7597 (not (eq function-type 'FUNCTION_EXPRESSION)))
7598 (js2-record-imenu-functions fn-node)))
7599 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7600 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7601 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7602 ;; We wait until after parsing the function to set its parent scope,
7603 ;; since `js2-define-symbol' needs the defining-scope check to stop
7604 ;; at the function boundary when checking for redeclarations.
7605 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7606 fn-node))
7607
7608 (defun js2-parse-statements (&optional parent)
7609 "Parse a statement list. Last token consumed must be js2-LC.
7610
7611 PARENT can be a `js2-block-node', in which case the statements are
7612 appended to PARENT. Otherwise a new `js2-block-node' is created
7613 and returned.
7614
7615 This function does not match the closing js2-RC: the caller
7616 matches the RC so it can provide a suitable error message if not
7617 matched. This means it's up to the caller to set the length of
7618 the node to include the closing RC. The node start pos is set to
7619 the absolute buffer start position, and the caller should fix it
7620 up to be relative to the parent node. All children of this block
7621 node are given relative start positions and correct lengths."
7622 (let ((pn (or parent (make-js2-block-node)))
7623 tt)
7624 (setf (js2-node-pos pn) js2-token-beg)
7625 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7626 (/= tt js2-RC))
7627 (js2-block-node-push pn (js2-parse-statement)))
7628 pn))
7629
7630 (defun js2-parse-statement ()
7631 (let (tt pn beg end)
7632 ;; coarse-grained user-interrupt check - needs work
7633 (and js2-parse-interruptable-p
7634 (zerop (% (incf js2-parse-stmt-count)
7635 js2-statements-per-pause))
7636 (input-pending-p)
7637 (throw 'interrupted t))
7638 (setq pn (js2-statement-helper))
7639 ;; no-side-effects warning check
7640 (unless (js2-node-has-side-effects pn)
7641 (setq end (js2-node-end pn))
7642 (save-excursion
7643 (goto-char end)
7644 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7645 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7646 pn))
7647
7648 ;; These correspond to the switch cases in Parser.statementHelper
7649 (defconst js2-parsers
7650 (let ((parsers (make-vector js2-num-tokens
7651 #'js2-parse-expr-stmt)))
7652 (aset parsers js2-BREAK #'js2-parse-break)
7653 (aset parsers js2-CONST #'js2-parse-const-var)
7654 (aset parsers js2-CONTINUE #'js2-parse-continue)
7655 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7656 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7657 (aset parsers js2-DO #'js2-parse-do)
7658 (aset parsers js2-FOR #'js2-parse-for)
7659 (aset parsers js2-FUNCTION #'js2-function-parser)
7660 (aset parsers js2-IF #'js2-parse-if)
7661 (aset parsers js2-LC #'js2-parse-block)
7662 (aset parsers js2-LET #'js2-parse-let-stmt)
7663 (aset parsers js2-NAME #'js2-parse-name-or-label)
7664 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7665 (aset parsers js2-SEMI #'js2-parse-semi)
7666 (aset parsers js2-SWITCH #'js2-parse-switch)
7667 (aset parsers js2-THROW #'js2-parse-throw)
7668 (aset parsers js2-TRY #'js2-parse-try)
7669 (aset parsers js2-VAR #'js2-parse-const-var)
7670 (aset parsers js2-WHILE #'js2-parse-while)
7671 (aset parsers js2-WITH #'js2-parse-with)
7672 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7673 parsers)
7674 "A vector mapping token types to parser functions.")
7675
7676 (defsubst js2-parse-warn-missing-semi (beg end)
7677 (and js2-mode-show-strict-warnings
7678 js2-strict-missing-semi-warning
7679 (js2-add-strict-warning
7680 "msg.missing.semi" nil
7681 ;; back up to beginning of statement or line
7682 (max beg (save-excursion
7683 (goto-char end)
7684 (point-at-bol)))
7685 end)))
7686
7687 (defconst js2-no-semi-insertion
7688 (list js2-IF
7689 js2-SWITCH
7690 js2-WHILE
7691 js2-DO
7692 js2-FOR
7693 js2-TRY
7694 js2-WITH
7695 js2-LC
7696 js2-ERROR
7697 js2-SEMI
7698 js2-FUNCTION)
7699 "List of tokens that don't do automatic semicolon insertion.")
7700
7701 (defconst js2-autoinsert-semi-and-warn
7702 (list js2-ERROR js2-EOF js2-RC))
7703
7704 (defun js2-statement-helper ()
7705 (let* ((tt (js2-peek-token))
7706 (first-tt tt)
7707 (beg js2-token-beg)
7708 (parser (if (= tt js2-ERROR)
7709 #'js2-parse-semi
7710 (aref js2-parsers tt)))
7711 pn
7712 tt-flagged)
7713 ;; If the statement is set, then it's been told its label by now.
7714 (and js2-labeled-stmt
7715 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7716 (setq js2-labeled-stmt nil))
7717 (setq pn (funcall parser))
7718 ;; Don't do auto semi insertion for certain statement types.
7719 (unless (or (memq first-tt js2-no-semi-insertion)
7720 (js2-labeled-stmt-node-p pn))
7721 (js2-auto-insert-semicolon pn))
7722 pn))
7723
7724 (defun js2-auto-insert-semicolon (pn)
7725 (let* ((tt-flagged (js2-peek-flagged-token))
7726 (tt (logand tt-flagged js2-clear-ti-mask))
7727 (pos (js2-node-pos pn)))
7728 (cond
7729 ((= tt js2-SEMI)
7730 ;; Consume ';' as a part of expression
7731 (js2-consume-token)
7732 ;; extend the node bounds to include the semicolon.
7733 (setf (js2-node-len pn) (- js2-token-end pos)))
7734 ((memq tt js2-autoinsert-semi-and-warn)
7735 ;; Autoinsert ;
7736 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7737 (t
7738 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7739 ;; Report error if no EOL or autoinsert ';' otherwise
7740 (js2-report-error "msg.no.semi.stmt")
7741 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7742
7743 (defun js2-parse-condition ()
7744 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7745 The parens are discarded and the expression node is returned.
7746 The `pos' field of the return value is set to an absolute position
7747 that must be fixed up by the caller.
7748 Return value is a list (EXPR LP RP), with absolute paren positions."
7749 (let (pn lp rp)
7750 (if (js2-must-match js2-LP "msg.no.paren.cond")
7751 (setq lp js2-token-beg))
7752 (setq pn (js2-parse-expr))
7753 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7754 (setq rp js2-token-beg))
7755 ;; Report strict warning on code like "if (a = 7) ..."
7756 (if (and js2-strict-cond-assign-warning
7757 (js2-assign-node-p pn))
7758 (js2-add-strict-warning "msg.equal.as.assign" nil
7759 (js2-node-pos pn)
7760 (+ (js2-node-pos pn)
7761 (js2-node-len pn))))
7762 (list pn lp rp)))
7763
7764 (defun js2-parse-if ()
7765 "Parser for if-statement. Last matched token must be js2-IF."
7766 (let ((pos js2-token-beg)
7767 cond
7768 if-true
7769 if-false
7770 else-pos
7771 end
7772 pn)
7773 (js2-consume-token)
7774 (setq cond (js2-parse-condition)
7775 if-true (js2-parse-statement)
7776 if-false (if (js2-match-token js2-ELSE)
7777 (progn
7778 (setq else-pos (- js2-token-beg pos))
7779 (js2-parse-statement)))
7780 end (js2-node-end (or if-false if-true))
7781 pn (make-js2-if-node :pos pos
7782 :len (- end pos)
7783 :condition (car cond)
7784 :then-part if-true
7785 :else-part if-false
7786 :else-pos else-pos
7787 :lp (js2-relpos (second cond) pos)
7788 :rp (js2-relpos (third cond) pos)))
7789 (js2-node-add-children pn (car cond) if-true if-false)
7790 pn))
7791
7792 (defun js2-parse-switch ()
7793 "Parser for if-statement. Last matched token must be js2-SWITCH."
7794 (let ((pos js2-token-beg)
7795 tt
7796 pn
7797 discriminant
7798 has-default
7799 case-expr
7800 case-node
7801 case-pos
7802 cases
7803 stmt
7804 lp
7805 rp)
7806 (js2-consume-token)
7807 (if (js2-must-match js2-LP "msg.no.paren.switch")
7808 (setq lp js2-token-beg))
7809 (setq discriminant (js2-parse-expr)
7810 pn (make-js2-switch-node :discriminant discriminant
7811 :pos pos
7812 :lp (js2-relpos lp pos)))
7813 (js2-node-add-children pn discriminant)
7814 (js2-enter-switch pn)
7815 (unwind-protect
7816 (progn
7817 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7818 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7819 (js2-must-match js2-LC "msg.no.brace.switch")
7820 (catch 'break
7821 (while t
7822 (setq tt (js2-next-token)
7823 case-pos js2-token-beg)
7824 (cond
7825 ((= tt js2-RC)
7826 (setf (js2-node-len pn) (- js2-token-end pos))
7827 (throw 'break nil)) ; done
7828 ((= tt js2-CASE)
7829 (setq case-expr (js2-parse-expr))
7830 (js2-must-match js2-COLON "msg.no.colon.case"))
7831 ((= tt js2-DEFAULT)
7832 (if has-default
7833 (js2-report-error "msg.double.switch.default"))
7834 (setq has-default t
7835 case-expr nil)
7836 (js2-must-match js2-COLON "msg.no.colon.case"))
7837 (t
7838 (js2-report-error "msg.bad.switch")
7839 (throw 'break nil)))
7840 (setq case-node (make-js2-case-node :pos case-pos
7841 :len (- js2-token-end case-pos)
7842 :expr case-expr))
7843 (js2-node-add-children case-node case-expr)
7844 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7845 (/= tt js2-CASE)
7846 (/= tt js2-DEFAULT)
7847 (/= tt js2-EOF))
7848 (setf stmt (js2-parse-statement)
7849 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7850 (js2-block-node-push case-node stmt))
7851 (push case-node cases)))
7852 ;; add cases last, as pushing reverses the order to be correct
7853 (dolist (kid cases)
7854 (js2-node-add-children pn kid)
7855 (push kid (js2-switch-node-cases pn)))
7856 pn) ; return value
7857 (js2-exit-switch))))
7858
7859 (defun js2-parse-while ()
7860 "Parser for while-statement. Last matched token must be js2-WHILE."
7861 (let ((pos js2-token-beg)
7862 (pn (make-js2-while-node))
7863 cond
7864 body)
7865 (js2-consume-token)
7866 (js2-enter-loop pn)
7867 (unwind-protect
7868 (progn
7869 (setf cond (js2-parse-condition)
7870 (js2-while-node-condition pn) (car cond)
7871 body (js2-parse-statement)
7872 (js2-while-node-body pn) body
7873 (js2-node-len pn) (- (js2-node-end body) pos)
7874 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7875 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7876 (js2-node-add-children pn body (car cond)))
7877 (js2-exit-loop))
7878 pn))
7879
7880 (defun js2-parse-do ()
7881 "Parser for do-statement. Last matched token must be js2-DO."
7882 (let ((pos js2-token-beg)
7883 (pn (make-js2-do-node))
7884 cond
7885 body
7886 end)
7887 (js2-consume-token)
7888 (js2-enter-loop pn)
7889 (unwind-protect
7890 (progn
7891 (setq body (js2-parse-statement))
7892 (js2-must-match js2-WHILE "msg.no.while.do")
7893 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7894 cond (js2-parse-condition)
7895 (js2-do-node-condition pn) (car cond)
7896 (js2-do-node-body pn) body
7897 end js2-ts-cursor
7898 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7899 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7900 (js2-node-add-children pn (car cond) body))
7901 (js2-exit-loop))
7902 ;; Always auto-insert semicolon to follow SpiderMonkey:
7903 ;; It is required by ECMAScript but is ignored by the rest of
7904 ;; world; see bug 238945
7905 (if (js2-match-token js2-SEMI)
7906 (setq end js2-ts-cursor))
7907 (setf (js2-node-len pn) (- end pos))
7908 pn))
7909
7910 (defun js2-parse-for ()
7911 "Parser for for-statement. Last matched token must be js2-FOR.
7912 Parses for, for-in, and for each-in statements."
7913 (let ((for-pos js2-token-beg)
7914 pn
7915 is-for-each
7916 is-for-in-or-of
7917 is-for-of
7918 in-pos
7919 each-pos
7920 tmp-pos
7921 init ; Node init is also foo in 'foo in object'
7922 cond ; Node cond is also object in 'foo in object'
7923 incr ; 3rd section of for-loop initializer
7924 body
7925 tt
7926 lp
7927 rp)
7928 (js2-consume-token)
7929 ;; See if this is a for each () instead of just a for ()
7930 (when (js2-match-token js2-NAME)
7931 (if (string= "each" js2-ts-string)
7932 (progn
7933 (setq is-for-each t
7934 each-pos (- js2-token-beg for-pos)) ; relative
7935 (js2-record-face 'font-lock-keyword-face))
7936 (js2-report-error "msg.no.paren.for")))
7937 (if (js2-must-match js2-LP "msg.no.paren.for")
7938 (setq lp (- js2-token-beg for-pos)))
7939 (setq tt (js2-peek-token))
7940 ;; 'for' makes local scope
7941 (js2-push-scope (make-js2-scope))
7942 (unwind-protect
7943 ;; parse init clause
7944 (let ((js2-in-for-init t)) ; set as dynamic variable
7945 (cond
7946 ((= tt js2-SEMI)
7947 (setq init (make-js2-empty-expr-node)))
7948 ((or (= tt js2-VAR) (= tt js2-LET))
7949 (js2-consume-token)
7950 (setq init (js2-parse-variables tt js2-token-beg)))
7951 (t
7952 (setq init (js2-parse-expr)))))
7953 (if (or (js2-match-token js2-IN)
7954 (and (>= js2-language-version 200)
7955 (js2-match-token js2-OF)
7956 (setq is-for-of t)))
7957 (setq is-for-in-or-of t
7958 in-pos (- js2-token-beg for-pos)
7959 ;; scope of iteration target object is not the scope we've created above.
7960 ;; stash current scope temporary.
7961 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7962 (js2-parse-expr))) ; object over which we're iterating
7963 ;; else ordinary for loop - parse cond and incr
7964 (js2-must-match js2-SEMI "msg.no.semi.for")
7965 (setq cond (if (= (js2-peek-token) js2-SEMI)
7966 (make-js2-empty-expr-node) ; no loop condition
7967 (js2-parse-expr)))
7968 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7969 (setq tmp-pos js2-token-end
7970 incr (if (= (js2-peek-token) js2-RP)
7971 (make-js2-empty-expr-node :pos tmp-pos)
7972 (js2-parse-expr))))
7973 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7974 (setq rp (- js2-token-beg for-pos)))
7975 (if (not is-for-in-or-of)
7976 (setq pn (make-js2-for-node :init init
7977 :condition cond
7978 :update incr
7979 :lp lp
7980 :rp rp))
7981 ;; cond could be null if 'in obj' got eaten by the init node.
7982 (if (js2-infix-node-p init)
7983 ;; it was (foo in bar) instead of (var foo in bar)
7984 (setq cond (js2-infix-node-right init)
7985 init (js2-infix-node-left init))
7986 (if (and (js2-var-decl-node-p init)
7987 (> (length (js2-var-decl-node-kids init)) 1))
7988 (js2-report-error "msg.mult.index")))
7989 (setq pn (make-js2-for-in-node :iterator init
7990 :object cond
7991 :in-pos in-pos
7992 :foreach-p is-for-each
7993 :each-pos each-pos
7994 :forof-p is-for-of
7995 :lp lp
7996 :rp rp)))
7997 (unwind-protect
7998 (progn
7999 (js2-enter-loop pn)
8000 ;; We have to parse the body -after- creating the loop node,
8001 ;; so that the loop node appears in the js2-loop-set, allowing
8002 ;; break/continue statements to find the enclosing loop.
8003 (setf body (js2-parse-statement)
8004 (js2-loop-node-body pn) body
8005 (js2-node-pos pn) for-pos
8006 (js2-node-len pn) (- (js2-node-end body) for-pos))
8007 (js2-node-add-children pn init cond incr body))
8008 ;; finally
8009 (js2-exit-loop))
8010 (js2-pop-scope))
8011 pn))
8012
8013 (defun js2-parse-try ()
8014 "Parser for try-statement. Last matched token must be js2-TRY."
8015 (let ((try-pos js2-token-beg)
8016 try-end
8017 try-block
8018 catch-blocks
8019 finally-block
8020 saw-default-catch
8021 peek
8022 param
8023 catch-cond
8024 catch-node
8025 guard-kwd
8026 catch-pos
8027 finally-pos
8028 pn
8029 block
8030 lp
8031 rp)
8032 (js2-consume-token)
8033 (if (/= (js2-peek-token) js2-LC)
8034 (js2-report-error "msg.no.brace.try"))
8035 (setq try-block (js2-parse-statement)
8036 try-end (js2-node-end try-block)
8037 peek (js2-peek-token))
8038 (cond
8039 ((= peek js2-CATCH)
8040 (while (js2-match-token js2-CATCH)
8041 (setq catch-pos js2-token-beg
8042 guard-kwd nil
8043 catch-cond nil
8044 lp nil
8045 rp nil)
8046 (if saw-default-catch
8047 (js2-report-error "msg.catch.unreachable"))
8048 (if (js2-must-match js2-LP "msg.no.paren.catch")
8049 (setq lp (- js2-token-beg catch-pos)))
8050 (js2-push-scope (make-js2-scope))
8051 (let ((tt (js2-peek-token)))
8052 (cond
8053 ;; destructuring pattern
8054 ;; catch ({ message, file }) { ... }
8055 ((or (= tt js2-LB) (= tt js2-LC))
8056 (setq param
8057 (js2-define-destruct-symbols (js2-parse-primary-expr-lhs)
8058 js2-LET nil)))
8059 ;; simple name
8060 (t
8061 (js2-must-match js2-NAME "msg.bad.catchcond")
8062 (setq param (js2-create-name-node))
8063 (js2-define-symbol js2-LET js2-ts-string param))))
8064 ;; pattern guard
8065 (if (js2-match-token js2-IF)
8066 (setq guard-kwd (- js2-token-beg catch-pos)
8067 catch-cond (js2-parse-expr))
8068 (setq saw-default-catch t))
8069 (if (js2-must-match js2-RP "msg.bad.catchcond")
8070 (setq rp (- js2-token-beg catch-pos)))
8071 (js2-must-match js2-LC "msg.no.brace.catchblock")
8072 (setq block (js2-parse-statements)
8073 try-end (js2-node-end block)
8074 catch-node (make-js2-catch-node :pos catch-pos
8075 :param param
8076 :guard-expr catch-cond
8077 :guard-kwd guard-kwd
8078 :block block
8079 :lp lp
8080 :rp rp))
8081 (js2-pop-scope)
8082 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8083 (setq try-end js2-token-beg))
8084 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8085 (js2-node-len catch-node) (- try-end catch-pos))
8086 (js2-node-add-children catch-node param catch-cond block)
8087 (push catch-node catch-blocks)))
8088 ((/= peek js2-FINALLY)
8089 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8090 (js2-node-pos try-block)
8091 (- (setq try-end (js2-node-end try-block))
8092 (js2-node-pos try-block)))))
8093 (when (js2-match-token js2-FINALLY)
8094 (setq finally-pos js2-token-beg
8095 block (js2-parse-statement)
8096 try-end (js2-node-end block)
8097 finally-block (make-js2-finally-node :pos finally-pos
8098 :len (- try-end finally-pos)
8099 :body block))
8100 (js2-node-add-children finally-block block))
8101 (setq pn (make-js2-try-node :pos try-pos
8102 :len (- try-end try-pos)
8103 :try-block try-block
8104 :finally-block finally-block))
8105 (js2-node-add-children pn try-block finally-block)
8106 ;; push them onto the try-node, which reverses and corrects their order
8107 (dolist (cb catch-blocks)
8108 (js2-node-add-children pn cb)
8109 (push cb (js2-try-node-catch-clauses pn)))
8110 pn))
8111
8112 (defun js2-parse-throw ()
8113 "Parser for throw-statement. Last matched token must be js2-THROW."
8114 (let ((pos js2-token-beg)
8115 expr
8116 pn)
8117 (js2-consume-token)
8118 (if (= (js2-peek-token-or-eol) js2-EOL)
8119 ;; ECMAScript does not allow new lines before throw expression,
8120 ;; see bug 256617
8121 (js2-report-error "msg.bad.throw.eol"))
8122 (setq expr (js2-parse-expr)
8123 pn (make-js2-throw-node :pos pos
8124 :len (- (js2-node-end expr) pos)
8125 :expr expr))
8126 (js2-node-add-children pn expr)
8127 pn))
8128
8129 (defsubst js2-match-jump-label-name (label-name)
8130 "If break/continue specified a label, return that label's labeled stmt.
8131 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8132 does not match an existing label, reports an error and returns nil."
8133 (let ((bundle (cdr (assoc label-name js2-label-set))))
8134 (if (null bundle)
8135 (js2-report-error "msg.undef.label"))
8136 bundle))
8137
8138 (defun js2-parse-break ()
8139 "Parser for break-statement. Last matched token must be js2-BREAK."
8140 (let ((pos js2-token-beg)
8141 (end js2-token-end)
8142 break-target ; statement to break from
8143 break-label ; in "break foo", name-node representing the foo
8144 labels ; matching labeled statement to break to
8145 pn)
8146 (js2-consume-token) ; `break'
8147 (when (eq (js2-peek-token-or-eol) js2-NAME)
8148 (js2-consume-token)
8149 (setq break-label (js2-create-name-node)
8150 end (js2-node-end break-label)
8151 ;; matchJumpLabelName only matches if there is one
8152 labels (js2-match-jump-label-name js2-ts-string)
8153 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8154 (unless (or break-target break-label)
8155 ;; no break target specified - try for innermost enclosing loop/switch
8156 (if (null js2-loop-and-switch-set)
8157 (unless break-label
8158 (js2-report-error "msg.bad.break" nil pos (length "break")))
8159 (setq break-target (car js2-loop-and-switch-set))))
8160 (setq pn (make-js2-break-node :pos pos
8161 :len (- end pos)
8162 :label break-label
8163 :target break-target))
8164 (js2-node-add-children pn break-label) ; but not break-target
8165 pn))
8166
8167 (defun js2-parse-continue ()
8168 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8169 (let ((pos js2-token-beg)
8170 (end js2-token-end)
8171 label ; optional user-specified label, a `js2-name-node'
8172 labels ; current matching labeled stmt, if any
8173 target ; the `js2-loop-node' target of this continue stmt
8174 pn)
8175 (js2-consume-token) ; `continue'
8176 (when (= (js2-peek-token-or-eol) js2-NAME)
8177 (js2-consume-token)
8178 (setq label (js2-create-name-node)
8179 end (js2-node-end label)
8180 ;; matchJumpLabelName only matches if there is one
8181 labels (js2-match-jump-label-name js2-ts-string)))
8182 (cond
8183 ((null labels) ; no current label to go to
8184 (if (null js2-loop-set) ; no loop to continue to
8185 (js2-report-error "msg.continue.outside" nil pos
8186 (length "continue"))
8187 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8188 (t
8189 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8190 (setq target (js2-labeled-stmt-node-stmt labels))
8191 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8192 (setq pn (make-js2-continue-node :pos pos
8193 :len (- end pos)
8194 :label label
8195 :target target))
8196 (js2-node-add-children pn label) ; but not target - it's not our child
8197 pn))
8198
8199 (defun js2-parse-with ()
8200 "Parser for with-statement. Last matched token must be js2-WITH."
8201 (js2-consume-token)
8202 (let ((pos js2-token-beg)
8203 obj body pn lp rp)
8204 (if (js2-must-match js2-LP "msg.no.paren.with")
8205 (setq lp js2-token-beg))
8206 (setq obj (js2-parse-expr))
8207 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8208 (setq rp js2-token-beg))
8209 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8210 (setq body (js2-parse-statement)))
8211 (setq pn (make-js2-with-node :pos pos
8212 :len (- (js2-node-end body) pos)
8213 :object obj
8214 :body body
8215 :lp (js2-relpos lp pos)
8216 :rp (js2-relpos rp pos)))
8217 (js2-node-add-children pn obj body)
8218 pn))
8219
8220 (defun js2-parse-const-var ()
8221 "Parser for var- or const-statement.
8222 Last matched token must be js2-CONST or js2-VAR."
8223 (let ((tt (js2-peek-token))
8224 (pos js2-token-beg)
8225 expr
8226 pn)
8227 (js2-consume-token)
8228 (setq expr (js2-parse-variables tt js2-token-beg)
8229 pn (make-js2-expr-stmt-node :pos pos
8230 :len (- (js2-node-end expr) pos)
8231 :expr expr))
8232 (js2-node-add-children pn expr)
8233 pn))
8234
8235 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8236 (let ((pn (make-js2-expr-stmt-node :pos pos
8237 :len (js2-node-len expr)
8238 :type (if (js2-inside-function)
8239 js2-EXPR_VOID
8240 js2-EXPR_RESULT)
8241 :expr expr)))
8242 (if add-child
8243 (js2-node-add-children pn expr))
8244 pn))
8245
8246 (defun js2-parse-let-stmt ()
8247 "Parser for let-statement. Last matched token must be js2-LET."
8248 (js2-consume-token)
8249 (let ((pos js2-token-beg)
8250 expr
8251 pn)
8252 (if (= (js2-peek-token) js2-LP)
8253 ;; let expression in statement context
8254 (setq expr (js2-parse-let pos 'statement)
8255 pn (js2-wrap-with-expr-stmt pos expr t))
8256 ;; else we're looking at a statement like let x=6, y=7;
8257 (setf expr (js2-parse-variables js2-LET pos)
8258 pn (js2-wrap-with-expr-stmt pos expr t)
8259 (js2-node-type pn) js2-EXPR_RESULT))
8260 pn))
8261
8262 (defun js2-parse-ret-yield ()
8263 (js2-parse-return-or-yield (js2-peek-token) nil))
8264
8265 (defconst js2-parse-return-stmt-enders
8266 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8267
8268 (defsubst js2-now-all-set (before after mask)
8269 "Return whether or not the bits in the mask have changed to all set.
8270 BEFORE is bits before change, AFTER is bits after change, and MASK is
8271 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8272 but not BEFORE."
8273 (and (/= (logand before mask) mask)
8274 (= (logand after mask) mask)))
8275
8276 (defun js2-parse-return-or-yield (tt expr-context)
8277 (let ((pos js2-token-beg)
8278 (end js2-token-end)
8279 (before js2-end-flags)
8280 (inside-function (js2-inside-function))
8281 e
8282 ret
8283 name)
8284 (unless inside-function
8285 (js2-report-error (if (eq tt js2-RETURN)
8286 "msg.bad.return"
8287 "msg.bad.yield")))
8288 (js2-consume-token)
8289 ;; This is ugly, but we don't want to require a semicolon.
8290 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8291 (setq e (js2-parse-expr)
8292 end (js2-node-end e)))
8293 (cond
8294 ((eq tt js2-RETURN)
8295 (js2-set-flag js2-end-flags (if (null e)
8296 js2-end-returns
8297 js2-end-returns-value))
8298 (setq ret (make-js2-return-node :pos pos
8299 :len (- end pos)
8300 :retval e))
8301 (js2-node-add-children ret e)
8302 ;; See if we need a strict mode warning.
8303 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8304 ;; more thorough and accurate than this before/after flag check.
8305 ;; E.g. if there's a finally-block that always returns, we shouldn't
8306 ;; show a warning generated by inconsistent returns in the catch blocks.
8307 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8308 ;; so we know which returns/yields to highlight, and we should get rid of
8309 ;; all the checking in `js2-parse-return-or-yield'.
8310 (if (and js2-strict-inconsistent-return-warning
8311 (js2-now-all-set before js2-end-flags
8312 (logior js2-end-returns js2-end-returns-value)))
8313 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8314 (t
8315 (unless (js2-inside-function)
8316 (js2-report-error "msg.bad.yield"))
8317 (js2-set-flag js2-end-flags js2-end-yields)
8318 (setq ret (make-js2-yield-node :pos pos
8319 :len (- end pos)
8320 :value e))
8321 (js2-node-add-children ret e)
8322 (unless expr-context
8323 (setq e ret
8324 ret (js2-wrap-with-expr-stmt pos e t))
8325 (js2-set-requires-activation)
8326 (js2-set-is-generator))))
8327 ;; see if we are mixing yields and value returns.
8328 (when (and inside-function
8329 (js2-now-all-set before js2-end-flags
8330 (logior js2-end-yields js2-end-returns-value)))
8331 (setq name (js2-function-name js2-current-script-or-fn))
8332 (if (zerop (length name))
8333 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8334 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8335 ret))
8336
8337 (defun js2-parse-debugger ()
8338 (js2-consume-token)
8339 (make-js2-keyword-node :type js2-DEBUGGER))
8340
8341 (defun js2-parse-block ()
8342 "Parser for a curly-delimited statement block.
8343 Last token matched must be js2-LC."
8344 (let ((pos js2-token-beg)
8345 (pn (make-js2-scope)))
8346 (js2-consume-token)
8347 (js2-push-scope pn)
8348 (unwind-protect
8349 (progn
8350 (js2-parse-statements pn)
8351 (js2-must-match js2-RC "msg.no.brace.block")
8352 (setf (js2-node-len pn) (- js2-token-end pos)))
8353 (js2-pop-scope))
8354 pn))
8355
8356 ;; for js2-ERROR too, to have a node for error recovery to work on
8357 (defun js2-parse-semi ()
8358 "Parse a statement or handle an error.
8359 Last matched token is js2-SEMI or js2-ERROR."
8360 (let ((tt (js2-peek-token)) pos len)
8361 (js2-consume-token)
8362 (if (eq tt js2-SEMI)
8363 (make-js2-empty-expr-node :len 1)
8364 (setq pos js2-token-beg
8365 len (- js2-token-beg pos))
8366 (js2-report-error "msg.syntax" nil pos len)
8367 (make-js2-error-node :pos pos :len len))))
8368
8369 (defun js2-parse-default-xml-namespace ()
8370 "Parse a `default xml namespace = <expr>' e4x statement."
8371 (let ((pos js2-token-beg)
8372 end len expr unary es)
8373 (js2-consume-token)
8374 (js2-must-have-xml)
8375 (js2-set-requires-activation)
8376 (setq len (- js2-ts-cursor pos))
8377 (unless (and (js2-match-token js2-NAME)
8378 (string= js2-ts-string "xml"))
8379 (js2-report-error "msg.bad.namespace" nil pos len))
8380 (unless (and (js2-match-token js2-NAME)
8381 (string= js2-ts-string "namespace"))
8382 (js2-report-error "msg.bad.namespace" nil pos len))
8383 (unless (js2-match-token js2-ASSIGN)
8384 (js2-report-error "msg.bad.namespace" nil pos len))
8385 (setq expr (js2-parse-expr)
8386 end (js2-node-end expr)
8387 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8388 :pos pos
8389 :len (- end pos)
8390 :operand expr))
8391 (js2-node-add-children unary expr)
8392 (make-js2-expr-stmt-node :pos pos
8393 :len (- end pos)
8394 :expr unary)))
8395
8396 (defun js2-record-label (label bundle)
8397 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8398 (js2-consume-token)
8399 (let ((name (js2-label-node-name label))
8400 labeled-stmt
8401 dup)
8402 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8403 ;; flag both labels if possible when used in editing mode
8404 (if (and js2-parse-ide-mode
8405 (setq dup (js2-get-label-by-name labeled-stmt name)))
8406 (js2-report-error "msg.dup.label" nil
8407 (js2-node-abs-pos dup) (js2-node-len dup)))
8408 (js2-report-error "msg.dup.label" nil
8409 (js2-node-pos label) (js2-node-len label)))
8410 (js2-labeled-stmt-node-add-label bundle label)
8411 (js2-node-add-children bundle label)
8412 ;; Add one reference to the bundle per label in `js2-label-set'
8413 (push (cons name bundle) js2-label-set)))
8414
8415 (defun js2-parse-name-or-label ()
8416 "Parser for identifier or label. Last token matched must be js2-NAME.
8417 Called when we found a name in a statement context. If it's a label, we gather
8418 up any following labels and the next non-label statement into a
8419 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8420 expression and return it wrapped in a `js2-expr-stmt-node'."
8421 (let ((pos js2-token-beg)
8422 (end js2-token-end)
8423 expr
8424 stmt
8425 pn
8426 bundle
8427 (continue t))
8428 ;; set check for label and call down to `js2-parse-primary-expr'
8429 (js2-set-check-for-label)
8430 (setq expr (js2-parse-expr))
8431 (if (/= (js2-node-type expr) js2-LABEL)
8432 ;; Parsed non-label expression - wrap with expression stmt.
8433 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8434 ;; else parsed a label
8435 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8436 (js2-record-label expr bundle)
8437 ;; look for more labels
8438 (while (and continue (= (js2-peek-token) js2-NAME))
8439 (js2-set-check-for-label)
8440 (setq expr (js2-parse-expr))
8441 (if (/= (js2-node-type expr) js2-LABEL)
8442 (progn
8443 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8444 continue nil)
8445 (js2-auto-insert-semicolon stmt))
8446 (js2-record-label expr bundle)))
8447 ;; no more labels; now parse the labeled statement
8448 (unwind-protect
8449 (unless stmt
8450 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8451 (setq stmt (js2-statement-helper))))
8452 ;; remove the labels for this statement from the global set
8453 (dolist (label (js2-labeled-stmt-node-labels bundle))
8454 (setq js2-label-set (remove label js2-label-set))))
8455 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8456 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8457 (js2-node-add-children bundle stmt)
8458 bundle)))
8459
8460 (defun js2-parse-expr-stmt ()
8461 "Default parser in statement context, if no recognized statement found."
8462 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8463
8464 (defun js2-parse-variables (decl-type pos)
8465 "Parse a comma-separated list of variable declarations.
8466 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8467
8468 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8469 For 'var' or 'const', the keyword should be the token last scanned.
8470
8471 POS is the position where the node should start. It's sometimes the
8472 var/const/let keyword, and other times the beginning of the first token
8473 in the first variable declaration.
8474
8475 Returns the parsed `js2-var-decl-node' expression node."
8476 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8477 :pos pos))
8478 destructuring
8479 kid-pos
8480 tt
8481 init
8482 name
8483 end
8484 nbeg nend
8485 vi
8486 (continue t))
8487 ;; Example:
8488 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8489 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8490 ;; var {a, b} = baz;
8491 (while continue
8492 (setq destructuring nil
8493 name nil
8494 tt (js2-peek-token)
8495 kid-pos js2-token-beg
8496 end js2-token-end
8497 init nil)
8498 (if (or (= tt js2-LB) (= tt js2-LC))
8499 ;; Destructuring assignment, e.g., var [a, b] = ...
8500 (setq destructuring (js2-parse-primary-expr-lhs)
8501 end (js2-node-end destructuring))
8502 ;; Simple variable name
8503 (when (js2-must-match js2-NAME "msg.bad.var")
8504 (setq name (js2-create-name-node)
8505 nbeg js2-token-beg
8506 nend js2-token-end
8507 end nend)
8508 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8509 (when (js2-match-token js2-ASSIGN)
8510 (setq init (js2-parse-assign-expr)
8511 end (js2-node-end init))
8512 (js2-record-imenu-functions init name))
8513 (when name
8514 (js2-set-face nbeg nend (if (js2-function-node-p init)
8515 'font-lock-function-name-face
8516 'font-lock-variable-name-face)
8517 'record))
8518 (setq vi (make-js2-var-init-node :pos kid-pos
8519 :len (- end kid-pos)
8520 :type decl-type))
8521 (if destructuring
8522 (progn
8523 (if (and (null init) (not js2-in-for-init))
8524 (js2-report-error "msg.destruct.assign.no.init"))
8525 (js2-define-destruct-symbols destructuring
8526 decl-type
8527 'font-lock-variable-name-face)
8528 (setf (js2-var-init-node-target vi) destructuring))
8529 (setf (js2-var-init-node-target vi) name))
8530 (setf (js2-var-init-node-initializer vi) init)
8531 (js2-node-add-children vi name destructuring init)
8532 (js2-block-node-push result vi)
8533 (unless (js2-match-token js2-COMMA)
8534 (setq continue nil)))
8535 (setf (js2-node-len result) (- end pos))
8536 result))
8537
8538 (defun js2-parse-let (pos &optional stmt-p)
8539 "Parse a let expression or statement.
8540 A let-expression is of the form `let (vars) expr'.
8541 A let-statment is of the form `let (vars) {statements}'.
8542 The third form of let is a variable declaration list, handled
8543 by `js2-parse-variables'."
8544 (let ((pn (make-js2-let-node :pos pos))
8545 beg vars body)
8546 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8547 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8548 (js2-push-scope pn)
8549 (unwind-protect
8550 (progn
8551 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8552 (if (js2-must-match js2-RP "msg.no.paren.let")
8553 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8554 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8555 ;; let statement
8556 (progn
8557 (js2-consume-token)
8558 (setf beg js2-token-beg ; position stmt at LC
8559 body (js2-parse-statements))
8560 (js2-must-match js2-RC "msg.no.curly.let")
8561 (setf (js2-node-len body) (- js2-token-end beg)
8562 (js2-node-len pn) (- js2-token-end pos)
8563 (js2-let-node-body pn) body
8564 (js2-node-type pn) js2-LET))
8565 ;; let expression
8566 (setf body (js2-parse-expr)
8567 (js2-node-len pn) (- (js2-node-end body) pos)
8568 (js2-let-node-body pn) body))
8569 (js2-node-add-children pn vars body))
8570 (js2-pop-scope))
8571 pn))
8572
8573 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8574 (js2-scope-put-symbol (or scope js2-current-scope)
8575 name
8576 (make-js2-symbol decl-type name node)))
8577
8578 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8579 "Define a symbol in the current scope.
8580 If NODE is non-nil, it is the AST node associated with the symbol."
8581 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8582 (symbol (if defining-scope
8583 (js2-scope-get-symbol defining-scope name)))
8584 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8585 (cond
8586 ((and symbol ; already defined
8587 (or (= sdt js2-CONST) ; old version is const
8588 (= decl-type js2-CONST) ; new version is const
8589 ;; two let-bound vars in this block have same name
8590 (and (= sdt js2-LET)
8591 (eq defining-scope js2-current-scope))))
8592 (js2-report-error
8593 (cond
8594 ((= sdt js2-CONST) "msg.const.redecl")
8595 ((= sdt js2-LET) "msg.let.redecl")
8596 ((= sdt js2-VAR) "msg.var.redecl")
8597 ((= sdt js2-FUNCTION) "msg.function.redecl")
8598 (t "msg.parm.redecl"))
8599 name))
8600 ((= decl-type js2-LET)
8601 (if (and (not ignore-not-in-block)
8602 (or (= (js2-node-type js2-current-scope) js2-IF)
8603 (js2-loop-node-p js2-current-scope)))
8604 (js2-report-error "msg.let.decl.not.in.block")
8605 (js2-define-new-symbol decl-type name node)))
8606 ((or (= decl-type js2-VAR)
8607 (= decl-type js2-CONST)
8608 (= decl-type js2-FUNCTION))
8609 (if symbol
8610 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8611 (js2-add-strict-warning "msg.var.redecl" name)
8612 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8613 (js2-add-strict-warning "msg.var.hides.arg" name)))
8614 (js2-define-new-symbol decl-type name node
8615 js2-current-script-or-fn)))
8616 ((= decl-type js2-LP)
8617 (if symbol
8618 ;; must be duplicate parameter. Second parameter hides the
8619 ;; first, so go ahead and add the second pararameter
8620 (js2-report-warning "msg.dup.parms" name))
8621 (js2-define-new-symbol decl-type name node))
8622 (t (js2-code-bug)))))
8623
8624 (defun js2-parse-expr (&optional oneshot)
8625 (let* ((pn (js2-parse-assign-expr))
8626 (pos (js2-node-pos pn))
8627 left
8628 right
8629 op-pos)
8630 (while (and (not oneshot)
8631 (js2-match-token js2-COMMA))
8632 (setq op-pos (- js2-token-beg pos)) ; relative
8633 (if (= (js2-peek-token) js2-YIELD)
8634 (js2-report-error "msg.yield.parenthesized"))
8635 (setq right (js2-parse-assign-expr)
8636 left pn
8637 pn (make-js2-infix-node :type js2-COMMA
8638 :pos pos
8639 :len (- js2-ts-cursor pos)
8640 :op-pos op-pos
8641 :left left
8642 :right right))
8643 (js2-node-add-children pn left right))
8644 pn))
8645
8646 (defun js2-parse-assign-expr ()
8647 (let ((tt (js2-peek-token))
8648 (pos js2-token-beg)
8649 pn
8650 left
8651 right
8652 op-pos)
8653 (if (= tt js2-YIELD)
8654 (js2-parse-return-or-yield tt t)
8655 ;; not yield - parse assignment expression
8656 (setq pn (js2-parse-cond-expr)
8657 tt (js2-peek-token))
8658 (when (and (<= js2-first-assign tt)
8659 (<= tt js2-last-assign))
8660 ;; tt express assignment (=, |=, ^=, ..., %=)
8661 (js2-consume-token)
8662 (setq op-pos (- js2-token-beg pos) ; relative
8663 left pn
8664 right (js2-parse-assign-expr)
8665 pn (make-js2-assign-node :type tt
8666 :pos pos
8667 :len (- (js2-node-end right) pos)
8668 :op-pos op-pos
8669 :left left
8670 :right right))
8671 (when js2-parse-ide-mode
8672 (js2-highlight-assign-targets pn left right)
8673 (js2-record-imenu-functions right left))
8674 ;; do this last so ide checks above can use absolute positions
8675 (js2-node-add-children pn left right))
8676 pn)))
8677
8678 (defun js2-parse-cond-expr ()
8679 (let ((pos js2-token-beg)
8680 (pn (js2-parse-or-expr))
8681 test-expr
8682 if-true
8683 if-false
8684 q-pos
8685 c-pos)
8686 (when (js2-match-token js2-HOOK)
8687 (setq q-pos (- js2-token-beg pos)
8688 if-true (js2-parse-assign-expr))
8689 (js2-must-match js2-COLON "msg.no.colon.cond")
8690 (setq c-pos (- js2-token-beg pos)
8691 if-false (js2-parse-assign-expr)
8692 test-expr pn
8693 pn (make-js2-cond-node :pos pos
8694 :len (- (js2-node-end if-false) pos)
8695 :test-expr test-expr
8696 :true-expr if-true
8697 :false-expr if-false
8698 :q-pos q-pos
8699 :c-pos c-pos))
8700 (js2-node-add-children pn test-expr if-true if-false))
8701 pn))
8702
8703 (defun js2-make-binary (type left parser)
8704 "Helper for constructing a binary-operator AST node.
8705 LEFT is the left-side-expression, already parsed, and the
8706 binary operator should have just been matched.
8707 PARSER is a function to call to parse the right operand,
8708 or a `js2-node' struct if it has already been parsed."
8709 (let* ((pos (js2-node-pos left))
8710 (op-pos (- js2-token-beg pos))
8711 (right (if (js2-node-p parser)
8712 parser
8713 (funcall parser)))
8714 (pn (make-js2-infix-node :type type
8715 :pos pos
8716 :len (- (js2-node-end right) pos)
8717 :op-pos op-pos
8718 :left left
8719 :right right)))
8720 (js2-node-add-children pn left right)
8721 pn))
8722
8723 (defun js2-parse-or-expr ()
8724 (let ((pn (js2-parse-and-expr)))
8725 (when (js2-match-token js2-OR)
8726 (setq pn (js2-make-binary js2-OR
8727 pn
8728 'js2-parse-or-expr)))
8729 pn))
8730
8731 (defun js2-parse-and-expr ()
8732 (let ((pn (js2-parse-bit-or-expr)))
8733 (when (js2-match-token js2-AND)
8734 (setq pn (js2-make-binary js2-AND
8735 pn
8736 'js2-parse-and-expr)))
8737 pn))
8738
8739 (defun js2-parse-bit-or-expr ()
8740 (let ((pn (js2-parse-bit-xor-expr)))
8741 (while (js2-match-token js2-BITOR)
8742 (setq pn (js2-make-binary js2-BITOR
8743 pn
8744 'js2-parse-bit-xor-expr)))
8745 pn))
8746
8747 (defun js2-parse-bit-xor-expr ()
8748 (let ((pn (js2-parse-bit-and-expr)))
8749 (while (js2-match-token js2-BITXOR)
8750 (setq pn (js2-make-binary js2-BITXOR
8751 pn
8752 'js2-parse-bit-and-expr)))
8753 pn))
8754
8755 (defun js2-parse-bit-and-expr ()
8756 (let ((pn (js2-parse-eq-expr)))
8757 (while (js2-match-token js2-BITAND)
8758 (setq pn (js2-make-binary js2-BITAND
8759 pn
8760 'js2-parse-eq-expr)))
8761 pn))
8762
8763 (defconst js2-parse-eq-ops
8764 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8765
8766 (defun js2-parse-eq-expr ()
8767 (let ((pn (js2-parse-rel-expr))
8768 tt)
8769 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8770 (js2-consume-token)
8771 (setq pn (js2-make-binary tt
8772 pn
8773 'js2-parse-rel-expr)))
8774 pn))
8775
8776 (defconst js2-parse-rel-ops
8777 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8778
8779 (defun js2-parse-rel-expr ()
8780 (let ((pn (js2-parse-shift-expr))
8781 (continue t)
8782 tt)
8783 (while continue
8784 (setq tt (js2-peek-token))
8785 (cond
8786 ((and js2-in-for-init (= tt js2-IN))
8787 (setq continue nil))
8788 ((memq tt js2-parse-rel-ops)
8789 (js2-consume-token)
8790 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8791 (t
8792 (setq continue nil))))
8793 pn))
8794
8795 (defconst js2-parse-shift-ops
8796 (list js2-LSH js2-URSH js2-RSH))
8797
8798 (defun js2-parse-shift-expr ()
8799 (let ((pn (js2-parse-add-expr))
8800 tt
8801 (continue t))
8802 (while continue
8803 (setq tt (js2-peek-token))
8804 (if (memq tt js2-parse-shift-ops)
8805 (progn
8806 (js2-consume-token)
8807 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8808 (setq continue nil)))
8809 pn))
8810
8811 (defun js2-parse-add-expr ()
8812 (let ((pn (js2-parse-mul-expr))
8813 tt
8814 (continue t))
8815 (while continue
8816 (setq tt (js2-peek-token))
8817 (if (or (= tt js2-ADD) (= tt js2-SUB))
8818 (progn
8819 (js2-consume-token)
8820 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8821 (setq continue nil)))
8822 pn))
8823
8824 (defconst js2-parse-mul-ops
8825 (list js2-MUL js2-DIV js2-MOD))
8826
8827 (defun js2-parse-mul-expr ()
8828 (let ((pn (js2-parse-unary-expr))
8829 tt
8830 (continue t))
8831 (while continue
8832 (setq tt (js2-peek-token))
8833 (if (memq tt js2-parse-mul-ops)
8834 (progn
8835 (js2-consume-token)
8836 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8837 (setq continue nil)))
8838 pn))
8839
8840 (defsubst js2-make-unary (type parser &rest args)
8841 "Make a unary node of type TYPE.
8842 PARSER is either a node (for postfix operators) or a function to call
8843 to parse the operand (for prefix operators)."
8844 (let* ((pos js2-token-beg)
8845 (postfix (js2-node-p parser))
8846 (expr (if postfix
8847 parser
8848 (apply parser args)))
8849 end
8850 pn)
8851 (if postfix ; e.g. i++
8852 (setq pos (js2-node-pos expr)
8853 end js2-token-end)
8854 (setq end (js2-node-end expr)))
8855 (setq pn (make-js2-unary-node :type type
8856 :pos pos
8857 :len (- end pos)
8858 :operand expr))
8859 (js2-node-add-children pn expr)
8860 pn))
8861
8862 (defconst js2-incrementable-node-types
8863 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8864 "Node types that can be the operand of a ++ or -- operator.")
8865
8866 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8867 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8868 js2-incrementable-node-types)
8869 (js2-report-error (if (= tt js2-INC)
8870 "msg.bad.incr"
8871 "msg.bad.decr")
8872 nil beg (- end beg))))
8873
8874 (defun js2-parse-unary-expr ()
8875 (let ((tt (js2-peek-token))
8876 pn expr beg end)
8877 (cond
8878 ((or (= tt js2-VOID)
8879 (= tt js2-NOT)
8880 (= tt js2-BITNOT)
8881 (= tt js2-TYPEOF))
8882 (js2-consume-token)
8883 (js2-make-unary tt 'js2-parse-unary-expr))
8884 ((= tt js2-ADD)
8885 (js2-consume-token)
8886 ;; Convert to special POS token in decompiler and parse tree
8887 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8888 ((= tt js2-SUB)
8889 (js2-consume-token)
8890 ;; Convert to special NEG token in decompiler and parse tree
8891 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8892 ((or (= tt js2-INC)
8893 (= tt js2-DEC))
8894 (js2-consume-token)
8895 (prog1
8896 (setq beg js2-token-beg
8897 end js2-token-end
8898 expr (js2-make-unary tt 'js2-parse-member-expr t))
8899 (js2-check-bad-inc-dec tt beg end expr)))
8900 ((= tt js2-DELPROP)
8901 (js2-consume-token)
8902 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8903 ((= tt js2-ERROR)
8904 (js2-consume-token)
8905 (make-js2-error-node)) ; try to continue
8906 ((and (= tt js2-LT)
8907 js2-compiler-xml-available)
8908 ;; XML stream encountered in expression.
8909 (js2-consume-token)
8910 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8911 (t
8912 (setq pn (js2-parse-member-expr t)
8913 ;; Don't look across a newline boundary for a postfix incop.
8914 tt (js2-peek-token-or-eol))
8915 (when (or (= tt js2-INC) (= tt js2-DEC))
8916 (js2-consume-token)
8917 (setf expr pn
8918 pn (js2-make-unary tt expr))
8919 (js2-node-set-prop pn 'postfix t)
8920 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8921 pn))))
8922
8923 (defun js2-parse-xml-initializer ()
8924 "Parse an E4X XML initializer.
8925 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8926 Then I'll postprocess the result, depending on whether we're in IDE
8927 mode or codegen mode, and generate the appropriate rewritten AST.
8928 IDE mode uses a rich AST that models the XML structure. Codegen mode
8929 just concatenates everything and makes a new XML or XMLList out of it."
8930 (let ((tt (js2-get-first-xml-token))
8931 pn-xml
8932 pn
8933 expr
8934 kids
8935 expr-pos
8936 (continue t)
8937 (first-token t))
8938 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8939 (js2-report-error "msg.syntax"))
8940 (setq pn-xml (make-js2-xml-node))
8941 (while continue
8942 (if first-token
8943 (setq first-token nil)
8944 (setq tt (js2-get-next-xml-token)))
8945 (cond
8946 ;; js2-XML means we found a {expr} in the XML stream.
8947 ;; The js2-ts-string is the XML up to the left-curly.
8948 ((= tt js2-XML)
8949 (push (make-js2-string-node :pos js2-token-beg
8950 :len (- js2-ts-cursor js2-token-beg))
8951 kids)
8952 (js2-must-match js2-LC "msg.syntax")
8953 (setq expr-pos js2-ts-cursor
8954 expr (if (eq (js2-peek-token) js2-RC)
8955 (make-js2-empty-expr-node :pos expr-pos)
8956 (js2-parse-expr)))
8957 (js2-must-match js2-RC "msg.syntax")
8958 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8959 :len (js2-node-len expr)
8960 :expr expr))
8961 (js2-node-add-children pn expr)
8962 (push pn kids))
8963 ;; a js2-XMLEND token means we hit the final close-tag.
8964 ((= tt js2-XMLEND)
8965 (push (make-js2-string-node :pos js2-token-beg
8966 :len (- js2-ts-cursor js2-token-beg))
8967 kids)
8968 (dolist (kid (nreverse kids))
8969 (js2-block-node-push pn-xml kid))
8970 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8971 (js2-node-pos pn-xml))
8972 continue nil))
8973 (t
8974 (js2-report-error "msg.syntax")
8975 (setq continue nil))))
8976 pn-xml))
8977
8978
8979 (defun js2-parse-argument-list ()
8980 "Parse an argument list and return it as a lisp list of nodes.
8981 Returns the list in reverse order. Consumes the right-paren token."
8982 (let (result)
8983 (unless (js2-match-token js2-RP)
8984 (loop do
8985 (if (= (js2-peek-token) js2-YIELD)
8986 (js2-report-error "msg.yield.parenthesized"))
8987 (push (js2-parse-assign-expr) result)
8988 while
8989 (js2-match-token js2-COMMA))
8990 (js2-must-match js2-RP "msg.no.paren.arg")
8991 result)))
8992
8993 (defun js2-parse-member-expr (&optional allow-call-syntax)
8994 (let ((tt (js2-peek-token))
8995 pn
8996 pos
8997 target
8998 args
8999 beg
9000 end
9001 init
9002 tail)
9003 (if (/= tt js2-NEW)
9004 (setq pn (js2-parse-primary-expr))
9005 ;; parse a 'new' expression
9006 (js2-consume-token)
9007 (setq pos js2-token-beg
9008 beg pos
9009 target (js2-parse-member-expr)
9010 end (js2-node-end target)
9011 pn (make-js2-new-node :pos pos
9012 :target target
9013 :len (- end pos)))
9014 (js2-node-add-children pn target)
9015 (when (js2-match-token js2-LP)
9016 ;; Add the arguments to pn, if any are supplied.
9017 (setf beg pos ; start of "new" keyword
9018 pos js2-token-beg
9019 args (nreverse (js2-parse-argument-list))
9020 (js2-new-node-args pn) args
9021 end js2-token-end
9022 (js2-new-node-lp pn) (- pos beg)
9023 (js2-new-node-rp pn) (- end 1 beg))
9024 (apply #'js2-node-add-children pn args))
9025 (when (and js2-allow-rhino-new-expr-initializer
9026 (js2-match-token js2-LC))
9027 (setf init (js2-parse-object-literal)
9028 end (js2-node-end init)
9029 (js2-new-node-initializer pn) init)
9030 (js2-node-add-children pn init))
9031 (setf (js2-node-len pn) (- end beg))) ; end outer if
9032 (js2-parse-member-expr-tail allow-call-syntax pn)))
9033
9034 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9035 "Parse a chain of property/array accesses or function calls.
9036 Includes parsing for E4X operators like `..' and `.@'.
9037 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9038 Returns an expression tree that includes PN, the parent node."
9039 (let ((beg (js2-node-pos pn))
9040 tt
9041 (continue t))
9042 (while continue
9043 (setq tt (js2-peek-token))
9044 (cond
9045 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9046 (setq pn (js2-parse-property-access tt pn)))
9047 ((= tt js2-DOTQUERY)
9048 (setq pn (js2-parse-dot-query pn)))
9049 ((= tt js2-LB)
9050 (setq pn (js2-parse-element-get pn)))
9051 ((= tt js2-LP)
9052 (if allow-call-syntax
9053 (setq pn (js2-parse-function-call pn))
9054 (setq continue nil)))
9055 (t
9056 (setq continue nil))))
9057 (if (>= js2-highlight-level 2)
9058 (js2-parse-highlight-member-expr-node pn))
9059 pn))
9060
9061 (defun js2-parse-dot-query (pn)
9062 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9063 Last token parsed must be `js2-DOTQUERY'."
9064 (let ((pos (js2-node-pos pn))
9065 op-pos
9066 expr
9067 end)
9068 (js2-consume-token)
9069 (js2-must-have-xml)
9070 (js2-set-requires-activation)
9071 (setq op-pos js2-token-beg
9072 expr (js2-parse-expr)
9073 end (js2-node-end expr)
9074 pn (make-js2-xml-dot-query-node :left pn
9075 :pos pos
9076 :op-pos op-pos
9077 :right expr))
9078 (js2-node-add-children pn
9079 (js2-xml-dot-query-node-left pn)
9080 (js2-xml-dot-query-node-right pn))
9081 (if (js2-must-match js2-RP "msg.no.paren")
9082 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9083 end js2-token-end))
9084 (setf (js2-node-len pn) (- end pos))
9085 pn))
9086
9087 (defun js2-parse-element-get (pn)
9088 "Parse an element-get expression, e.g. foo[bar].
9089 Last token parsed must be `js2-RB'."
9090 (let ((lb js2-token-beg)
9091 (pos (js2-node-pos pn))
9092 rb
9093 expr)
9094 (js2-consume-token)
9095 (setq expr (js2-parse-expr))
9096 (if (js2-must-match js2-RB "msg.no.bracket.index")
9097 (setq rb js2-token-beg))
9098 (setq pn (make-js2-elem-get-node :target pn
9099 :pos pos
9100 :element expr
9101 :lb (js2-relpos lb pos)
9102 :rb (js2-relpos rb pos)
9103 :len (- js2-token-end pos)))
9104 (js2-node-add-children pn
9105 (js2-elem-get-node-target pn)
9106 (js2-elem-get-node-element pn))
9107 pn))
9108
9109 (defun js2-parse-function-call (pn)
9110 (let (args
9111 (pos (js2-node-pos pn)))
9112 (js2-consume-token)
9113 (setq pn (make-js2-call-node :pos pos
9114 :target pn
9115 :lp (- js2-token-beg pos)))
9116 (js2-node-add-children pn (js2-call-node-target pn))
9117 ;; Add the arguments to pn, if any are supplied.
9118 (setf args (nreverse (js2-parse-argument-list))
9119 (js2-call-node-rp pn) (- js2-token-beg pos)
9120 (js2-call-node-args pn) args)
9121 (apply #'js2-node-add-children pn args)
9122 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9123 pn))
9124
9125 (defun js2-parse-property-access (tt pn)
9126 "Parse a property access, XML descendants access, or XML attr access."
9127 (let ((member-type-flags 0)
9128 (dot-pos js2-token-beg)
9129 (dot-len (if (= tt js2-DOTDOT) 2 1))
9130 name
9131 ref ; right side of . or .. operator
9132 result)
9133 (js2-consume-token)
9134 (when (= tt js2-DOTDOT)
9135 (js2-must-have-xml)
9136 (setq member-type-flags js2-descendants-flag))
9137 (if (not js2-compiler-xml-available)
9138 (progn
9139 (js2-must-match-prop-name "msg.no.name.after.dot")
9140 (setq name (js2-create-name-node t js2-GETPROP)
9141 result (make-js2-prop-get-node :left pn
9142 :pos js2-token-beg
9143 :right name
9144 :len (- js2-token-end
9145 js2-token-beg)))
9146 (js2-node-add-children result pn name)
9147 result)
9148 ;; otherwise look for XML operators
9149 (setf result (if (= tt js2-DOT)
9150 (make-js2-prop-get-node)
9151 (make-js2-infix-node :type js2-DOTDOT))
9152 (js2-node-pos result) (js2-node-pos pn)
9153 (js2-infix-node-op-pos result) dot-pos
9154 (js2-infix-node-left result) pn ; do this after setting position
9155 tt (js2-next-token))
9156 (cond
9157 ;; needed for generator.throw()
9158 ((= tt js2-THROW)
9159 (js2-save-name-token-data js2-token-beg "throw")
9160 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9161 ;; handles: name, ns::name, ns::*, ns::[expr]
9162 ((js2-valid-prop-name-token tt)
9163 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9164 ;; handles: *, *::name, *::*, *::[expr]
9165 ((= tt js2-MUL)
9166 (js2-save-name-token-data js2-token-beg "*")
9167 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9168 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9169 ((= tt js2-XMLATTR)
9170 (setq result (js2-parse-attribute-access)))
9171 (t
9172 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9173 (if ref
9174 (setf (js2-node-len result) (- (js2-node-end ref)
9175 (js2-node-pos result))
9176 (js2-infix-node-right result) ref))
9177 (if (js2-infix-node-p result)
9178 (js2-node-add-children result
9179 (js2-infix-node-left result)
9180 (js2-infix-node-right result)))
9181 result)))
9182
9183 (defun js2-parse-attribute-access ()
9184 "Parse an E4X XML attribute expression.
9185 This includes expressions of the forms:
9186
9187 @attr @ns::attr @ns::*
9188 @* @*::attr @*::*
9189 @[expr] @*::[expr] @ns::[expr]
9190
9191 Called if we peeked an '@' token."
9192 (let ((tt (js2-next-token))
9193 (at-pos js2-token-beg))
9194 (cond
9195 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9196 ((js2-valid-prop-name-token tt)
9197 (js2-parse-property-name at-pos js2-ts-string 0))
9198 ;; handles: @*, @*::name, @*::*, @*::[expr]
9199 ((= tt js2-MUL)
9200 (js2-save-name-token-data js2-token-beg "*")
9201 (js2-parse-property-name js2-token-beg "*" 0))
9202 ;; handles @[expr]
9203 ((= tt js2-LB)
9204 (js2-parse-xml-elem-ref at-pos))
9205 (t
9206 (js2-report-error "msg.no.name.after.xmlAttr")
9207 ;; Avoid cascaded errors that happen if we make an error node here.
9208 (js2-save-name-token-data js2-token-beg "")
9209 (js2-parse-property-name js2-token-beg "" 0)))))
9210
9211 (defun js2-parse-property-name (at-pos s member-type-flags)
9212 "Check if :: follows name in which case it becomes qualified name.
9213
9214 AT-POS is a natural number if we just read an '@' token, else nil.
9215 S is the name or string that was matched: an identifier, 'throw' or '*'.
9216 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9217
9218 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9219 operator, or the name is followed by ::. For a plain name, returns a
9220 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9221 (let ((pos (or at-pos js2-token-beg))
9222 colon-pos
9223 (name (js2-create-name-node t js2-current-token))
9224 ns
9225 tt
9226 ref
9227 pn)
9228 (catch 'return
9229 (when (js2-match-token js2-COLONCOLON)
9230 (setq ns name
9231 colon-pos js2-token-beg
9232 tt (js2-next-token))
9233 (cond
9234 ;; handles name::name
9235 ((js2-valid-prop-name-token tt)
9236 (setq name (js2-create-name-node)))
9237 ;; handles name::*
9238 ((= tt js2-MUL)
9239 (js2-save-name-token-data js2-token-beg "*")
9240 (setq name (js2-create-name-node)))
9241 ;; handles name::[expr]
9242 ((= tt js2-LB)
9243 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9244 (t
9245 (js2-report-error "msg.no.name.after.coloncolon"))))
9246 (if (and (null ns) (zerop member-type-flags))
9247 name
9248 (prog1
9249 (setq pn
9250 (make-js2-xml-prop-ref-node :pos pos
9251 :len (- (js2-node-end name) pos)
9252 :at-pos at-pos
9253 :colon-pos colon-pos
9254 :propname name))
9255 (js2-node-add-children pn name))))))
9256
9257 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9258 "Parse the [expr] portion of an xml element reference.
9259 For instance, @[expr], @*::[expr], or ns::[expr]."
9260 (let* ((lb js2-token-beg)
9261 (pos (or at-pos lb))
9262 rb
9263 (expr (js2-parse-expr))
9264 (end (js2-node-end expr))
9265 pn)
9266 (if (js2-must-match js2-RB "msg.no.bracket.index")
9267 (setq rb js2-token-beg
9268 end js2-token-end))
9269 (prog1
9270 (setq pn
9271 (make-js2-xml-elem-ref-node :pos pos
9272 :len (- end pos)
9273 :namespace namespace
9274 :colon-pos colon-pos
9275 :at-pos at-pos
9276 :expr expr
9277 :lb (js2-relpos lb pos)
9278 :rb (js2-relpos rb pos)))
9279 (js2-node-add-children pn namespace expr))))
9280
9281 (defun js2-parse-primary-expr-lhs ()
9282 (let ((js2-is-in-lhs t))
9283 (js2-parse-primary-expr)))
9284
9285 (defun js2-parse-primary-expr ()
9286 "Parses a literal (leaf) expression of some sort.
9287 Includes complex literals such as functions, object-literals,
9288 array-literals, array comprehensions and regular expressions."
9289 (let ((tt-flagged (js2-next-flagged-token))
9290 pn ; parent node (usually return value)
9291 tt
9292 px-pos ; paren-expr pos
9293 len
9294 flags ; regexp flags
9295 expr)
9296 (setq tt js2-current-token)
9297 (cond
9298 ((= tt js2-FUNCTION)
9299 (js2-parse-function 'FUNCTION_EXPRESSION))
9300 ((= tt js2-LB)
9301 (js2-parse-array-literal))
9302 ((= tt js2-LC)
9303 (js2-parse-object-literal))
9304 ((= tt js2-LET)
9305 (js2-parse-let js2-token-beg))
9306 ((= tt js2-LP)
9307 (setq px-pos js2-token-beg
9308 expr (js2-parse-expr))
9309 (js2-must-match js2-RP "msg.no.paren")
9310 (setq pn (make-js2-paren-node :pos px-pos
9311 :expr expr
9312 :len (- js2-token-end px-pos)))
9313 (js2-node-add-children pn (js2-paren-node-expr pn))
9314 pn)
9315 ((= tt js2-XMLATTR)
9316 (js2-must-have-xml)
9317 (js2-parse-attribute-access))
9318 ((= tt js2-NAME)
9319 (js2-parse-name tt-flagged tt))
9320 ((= tt js2-NUMBER)
9321 (make-js2-number-node))
9322 ((= tt js2-STRING)
9323 (prog1
9324 (make-js2-string-node)
9325 (js2-record-face 'font-lock-string-face)))
9326 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9327 ;; Got / or /= which in this context means a regexp literal
9328 (setq px-pos js2-token-beg)
9329 (js2-read-regexp tt)
9330 (setq flags js2-ts-regexp-flags
9331 js2-ts-regexp-flags nil)
9332 (prog1
9333 (make-js2-regexp-node :pos px-pos
9334 :len (- js2-ts-cursor px-pos)
9335 :value js2-ts-string
9336 :flags flags)
9337 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9338 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9339 ((or (= tt js2-NULL)
9340 (= tt js2-THIS)
9341 (= tt js2-FALSE)
9342 (= tt js2-TRUE))
9343 (make-js2-keyword-node :type tt))
9344 ((= tt js2-RESERVED)
9345 (js2-report-error "msg.reserved.id")
9346 (make-js2-name-node))
9347 ((= tt js2-ERROR)
9348 ;; the scanner or one of its subroutines reported the error.
9349 (make-js2-error-node))
9350 ((= tt js2-EOF)
9351 (setq px-pos (point-at-bol)
9352 len (- js2-ts-cursor px-pos))
9353 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9354 (make-js2-error-node :pos px-pos :len len))
9355 (t
9356 (js2-report-error "msg.syntax")
9357 (make-js2-error-node)))))
9358
9359 (defun js2-parse-name (tt-flagged tt)
9360 (let ((name js2-ts-string)
9361 (name-pos js2-token-beg)
9362 node)
9363 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9364 (= (js2-peek-token) js2-COLON))
9365 (prog1
9366 ;; Do not consume colon, it is used as unwind indicator
9367 ;; to return to statementHelper.
9368 (make-js2-label-node :pos name-pos
9369 :len (- js2-token-end name-pos)
9370 :name name)
9371 (js2-set-face name-pos
9372 js2-token-end
9373 'font-lock-variable-name-face 'record))
9374 ;; Otherwise not a label, just a name. Unfortunately peeking
9375 ;; the next token to check for a colon has biffed js2-token-beg
9376 ;; and js2-token-end. We store the name's bounds in buffer vars
9377 ;; and `js2-create-name-node' uses them.
9378 (js2-save-name-token-data name-pos name)
9379 (setq node (if js2-compiler-xml-available
9380 (js2-parse-property-name nil name 0)
9381 (js2-create-name-node 'check-activation)))
9382 (if js2-highlight-external-variables
9383 (js2-record-name-node node))
9384 node)))
9385
9386 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9387 (js2-add-strict-warning
9388 msg nil
9389 ;; back up from comma to beginning of line or array/objlit
9390 (max (if elems
9391 (js2-node-pos (car elems))
9392 pos)
9393 (save-excursion
9394 (goto-char comma-pos)
9395 (back-to-indentation)
9396 (point)))
9397 comma-pos))
9398
9399 (defun js2-parse-array-literal ()
9400 (let ((pos js2-token-beg)
9401 (end js2-token-end)
9402 (after-lb-or-comma t)
9403 after-comma
9404 tt
9405 elems
9406 pn
9407 (continue t))
9408 (unless js2-is-in-lhs
9409 (js2-push-scope (make-js2-scope))) ; for array comp
9410 (while continue
9411 (setq tt (js2-peek-token))
9412 (cond
9413 ;; comma
9414 ((= tt js2-COMMA)
9415 (js2-consume-token)
9416 (setq after-comma js2-token-end)
9417 (if (not after-lb-or-comma)
9418 (setq after-lb-or-comma t)
9419 (push nil elems)))
9420 ;; end of array
9421 ((or (= tt js2-RB)
9422 (= tt js2-EOF)) ; prevent infinite loop
9423 (if (= tt js2-EOF)
9424 (js2-report-error "msg.no.bracket.arg" nil pos)
9425 (js2-consume-token))
9426 (setq continue nil
9427 end js2-token-end
9428 pn (make-js2-array-node :pos pos
9429 :len (- js2-ts-cursor pos)
9430 :elems (nreverse elems)))
9431 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9432 (when (and after-comma (not js2-is-in-lhs))
9433 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9434 pos elems after-comma)))
9435 ;; destructuring binding
9436 (js2-is-in-lhs
9437 (push (if (or (= tt js2-LC)
9438 (= tt js2-LB)
9439 (= tt js2-NAME))
9440 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9441 (js2-parse-primary-expr-lhs)
9442 ;; invalid pattern
9443 (js2-consume-token)
9444 (js2-report-error "msg.bad.var")
9445 (make-js2-error-node))
9446 elems)
9447 (setq after-lb-or-comma nil
9448 after-comma nil))
9449 ;; array comp
9450 ((and (>= js2-language-version 170)
9451 (= tt js2-FOR) ; check for array comprehension
9452 (not after-lb-or-comma) ; "for" can't follow a comma
9453 elems ; must have at least 1 element
9454 (not (cdr elems))) ; but no 2nd element
9455 (setf continue nil
9456 pn (js2-parse-array-comprehension (car elems) pos)))
9457
9458 ;; another element
9459 (t
9460 (unless after-lb-or-comma
9461 (js2-report-error "msg.no.bracket.arg"))
9462 (push (js2-parse-assign-expr) elems)
9463 (setq after-lb-or-comma nil
9464 after-comma nil))))
9465 (unless js2-is-in-lhs
9466 (js2-pop-scope))
9467 pn))
9468
9469 (defun js2-parse-array-comprehension (expr pos)
9470 "Parse a JavaScript 1.7 Array Comprehension.
9471 EXPR is the first expression after the opening left-bracket.
9472 POS is the beginning of the LB token preceding EXPR.
9473 We should have just parsed the 'for' keyword before calling this function."
9474 (let (loops
9475 loop
9476 first
9477 prev
9478 filter
9479 if-pos
9480 result)
9481 (while (= (js2-peek-token) js2-FOR)
9482 (let ((prev (car loops))) ; rearrange scope chain
9483 (push (setq loop (js2-parse-array-comp-loop)) loops)
9484 (if prev ; each loop is parent scope to the next one
9485 (setf (js2-scope-parent-scope loop) prev)
9486 ; first loop takes expr scope's parent
9487 (setf (js2-scope-parent-scope (setq first loop))
9488 (js2-scope-parent-scope js2-current-scope)))))
9489 ;; set expr scope's parent to the last loop
9490 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9491 (when (= (js2-peek-token) js2-IF)
9492 (js2-consume-token)
9493 (setq if-pos (- js2-token-beg pos) ; relative
9494 filter (js2-parse-condition)))
9495 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9496 (setq result (make-js2-array-comp-node :pos pos
9497 :len (- js2-ts-cursor pos)
9498 :result expr
9499 :loops (nreverse loops)
9500 :filter (car filter)
9501 :lp (js2-relpos (second filter) pos)
9502 :rp (js2-relpos (third filter) pos)
9503 :if-pos if-pos))
9504 (apply #'js2-node-add-children result expr (car filter)
9505 (js2-array-comp-node-loops result))
9506 (setq js2-current-scope first) ; pop to the first loop
9507 result))
9508
9509 (defun js2-parse-array-comp-loop ()
9510 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9511 Last token peeked should be the initial FOR."
9512 (let ((pos js2-token-beg)
9513 (pn (make-js2-array-comp-loop-node))
9514 tt
9515 iter
9516 obj
9517 foreach-p
9518 forof-p
9519 in-pos
9520 each-pos
9521 lp
9522 rp)
9523 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9524 (js2-push-scope pn)
9525 (unwind-protect
9526 (progn
9527 (when (js2-match-token js2-NAME)
9528 (if (string= js2-ts-string "each")
9529 (progn
9530 (setq foreach-p t
9531 each-pos (- js2-token-beg pos)) ; relative
9532 (js2-record-face 'font-lock-keyword-face))
9533 (js2-report-error "msg.no.paren.for")))
9534 (if (js2-must-match js2-LP "msg.no.paren.for")
9535 (setq lp (- js2-token-beg pos)))
9536 (setq tt (js2-peek-token))
9537 (cond
9538 ((or (= tt js2-LB)
9539 (= tt js2-LC))
9540 ;; handle destructuring assignment
9541 (setq iter (js2-parse-primary-expr-lhs))
9542 (js2-define-destruct-symbols iter js2-LET
9543 'font-lock-variable-name-face t))
9544 ((js2-match-token js2-NAME)
9545 (setq iter (js2-create-name-node)))
9546 (t
9547 (js2-report-error "msg.bad.var")))
9548 ;; Define as a let since we want the scope of the variable to
9549 ;; be restricted to the array comprehension
9550 (if (js2-name-node-p iter)
9551 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9552 (if (or (js2-match-token js2-IN)
9553 (and (>= js2-language-version 200)
9554 (js2-match-token js2-OF)
9555 (setq forof-p t)))
9556 (setq in-pos (- js2-token-beg pos))
9557 (js2-report-error "msg.in.after.for.name"))
9558 (setq obj (js2-parse-expr))
9559 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9560 (setq rp (- js2-token-beg pos)))
9561 (setf (js2-node-pos pn) pos
9562 (js2-node-len pn) (- js2-ts-cursor pos)
9563 (js2-array-comp-loop-node-iterator pn) iter
9564 (js2-array-comp-loop-node-object pn) obj
9565 (js2-array-comp-loop-node-in-pos pn) in-pos
9566 (js2-array-comp-loop-node-each-pos pn) each-pos
9567 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9568 (js2-array-comp-loop-node-forof-p pn) forof-p
9569 (js2-array-comp-loop-node-lp pn) lp
9570 (js2-array-comp-loop-node-rp pn) rp)
9571 (js2-node-add-children pn iter obj))
9572 (js2-pop-scope))
9573 pn))
9574
9575 (defun js2-parse-object-literal ()
9576 (let ((pos js2-token-beg)
9577 tt
9578 elems
9579 result
9580 after-comma
9581 (continue t))
9582 (while continue
9583 (setq tt (js2-peek-token))
9584 (cond
9585 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9586 ((or (js2-valid-prop-name-token tt)
9587 (= tt js2-STRING))
9588 (setq after-comma nil
9589 result (js2-parse-named-prop tt))
9590 (if (and (null result)
9591 (not js2-recover-from-parse-errors))
9592 (setq continue nil)
9593 (push result elems)))
9594 ;; {12: x} or {10.7: x}
9595 ((= tt js2-NUMBER)
9596 (js2-consume-token)
9597 (setq after-comma nil)
9598 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9599 ;; trailing comma
9600 ((= tt js2-RC)
9601 (setq continue nil)
9602 (if after-comma
9603 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9604 pos elems after-comma)))
9605 (t
9606 (js2-report-error "msg.bad.prop")
9607 (unless js2-recover-from-parse-errors
9608 (setq continue nil)))) ; end switch
9609 (if (js2-match-token js2-COMMA)
9610 (setq after-comma js2-token-end)
9611 (setq continue nil))) ; end loop
9612 (js2-must-match js2-RC "msg.no.brace.prop")
9613 (setq result (make-js2-object-node :pos pos
9614 :len (- js2-ts-cursor pos)
9615 :elems (nreverse elems)))
9616 (apply #'js2-node-add-children result (js2-object-node-elems result))
9617 result))
9618
9619 (defun js2-parse-named-prop (tt)
9620 "Parse a name, string, or getter/setter object property.
9621 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9622 (js2-consume-token)
9623 (let ((string-prop (and (= tt js2-STRING)
9624 (make-js2-string-node)))
9625 expr
9626 (ppos js2-token-beg)
9627 (pend js2-token-end)
9628 (name (js2-create-name-node))
9629 (prop js2-ts-string))
9630 (cond
9631 ;; getter/setter prop
9632 ((and (= tt js2-NAME)
9633 (= (js2-peek-token) js2-NAME)
9634 (or (string= prop "get")
9635 (string= prop "set")))
9636 (js2-consume-token)
9637 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9638 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9639 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9640 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9641 ;; abbreviated destructuring bind e.g., {a, b} = c;
9642 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9643 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9644 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9645 ;; assignment but it's difficult because it requires looking ahead of expression.
9646 ((and js2-is-in-lhs
9647 (= tt js2-NAME)
9648 (let ((ctk (js2-peek-token)))
9649 (or (= ctk js2-COMMA)
9650 (= ctk js2-RC)
9651 (js2-valid-prop-name-token ctk))))
9652 name)
9653 ;; regular prop
9654 (t
9655 (prog1
9656 (setq expr (js2-parse-plain-property (or string-prop name)))
9657 (js2-set-face ppos pend
9658 (if (js2-function-node-p
9659 (js2-object-prop-node-right expr))
9660 'font-lock-function-name-face
9661 'font-lock-variable-name-face)
9662 'record))))))
9663
9664 (defun js2-parse-plain-property (prop)
9665 "Parse a non-getter/setter property in an object literal.
9666 PROP is the node representing the property: a number, name or string."
9667 (js2-must-match js2-COLON "msg.no.colon.prop")
9668 (let* ((pos (js2-node-pos prop))
9669 (colon (- js2-token-beg pos))
9670 (expr (js2-parse-assign-expr))
9671 (result (make-js2-object-prop-node
9672 :pos pos
9673 ;; don't include last consumed token in length
9674 :len (- (+ (js2-node-pos expr)
9675 (js2-node-len expr))
9676 pos)
9677 :left prop
9678 :right expr
9679 :op-pos colon)))
9680 (js2-node-add-children result prop expr)
9681 result))
9682
9683 (defun js2-parse-getter-setter-prop (pos prop get-p)
9684 "Parse getter or setter property in an object literal.
9685 JavaScript syntax is:
9686
9687 { get foo() {...}, set foo(x) {...} }
9688
9689 and expression closure style is also supported
9690
9691 { get foo() x, set foo(x) _x = x }
9692
9693 POS is the start position of the `get' or `set' keyword.
9694 PROP is the `js2-name-node' representing the property name.
9695 GET-P is non-nil if the keyword was `get'."
9696 (let ((type (if get-p js2-GET js2-SET))
9697 result
9698 end
9699 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9700 ;; it has to be an anonymous function, as we already parsed the name
9701 (if (/= (js2-node-type fn) js2-FUNCTION)
9702 (js2-report-error "msg.bad.prop")
9703 (if (plusp (length (js2-function-name fn)))
9704 (js2-report-error "msg.bad.prop")))
9705 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9706 (setq end (js2-node-end fn)
9707 result (make-js2-getter-setter-node :type type
9708 :pos pos
9709 :len (- end pos)
9710 :left prop
9711 :right fn))
9712 (js2-node-add-children result prop fn)
9713 result))
9714
9715 (defun js2-create-name-node (&optional check-activation-p token)
9716 "Create a name node using the token info from last scanned name.
9717 In some cases we need to either synthesize a name node, or we lost
9718 the name token information by peeking. If the TOKEN parameter is
9719 not `js2-NAME', then we use the token info saved in instance vars."
9720 (let ((beg js2-token-beg)
9721 (s js2-ts-string)
9722 name)
9723 (when (/= js2-current-token js2-NAME)
9724 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9725 s js2-prev-name-token-string
9726 js2-prev-name-token-start nil
9727 js2-prev-name-token-string nil))
9728 (setq name (make-js2-name-node :pos beg
9729 :name s
9730 :len (length s)))
9731 (if check-activation-p
9732 (js2-check-activation-name s (or token js2-NAME)))
9733 name))
9734
9735 ;;; Indentation support
9736
9737 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9738 ;; Karl cleverly deduces that the desired indentation level is often a
9739 ;; function of paren/bracket/brace nesting depth, which can be determined
9740 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9741 ;; then does some equally clever checks to see if we're in the context of a
9742 ;; substatement of a possibly braceless statement keyword such as if, while,
9743 ;; or finally. This approach yields pretty good results.
9744
9745 ;; The indenter is often "wrong", however, and needs to be overridden.
9746 ;; The right long-term solution is probably to emulate (or integrate
9747 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9748 ;; parse tree from `js2-parse' is present, which is not true at the
9749 ;; moment the user is typing, computing indentation is still thousands
9750 ;; of lines of code to handle every possible syntactic edge case.
9751
9752 ;; In the meantime, the compromise solution is that we offer a "bounce
9753 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9754 ;; current line indent among various likely guess points. This approach
9755 ;; is far from perfect, but should at least make it slightly easier to
9756 ;; move the line towards its desired indentation when manually
9757 ;; overriding Karl's heuristic nesting guesser.
9758
9759 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9760 ;; extensions such as `let' and Array comprehensions. Major kudos to
9761 ;; Karl for coming up with the initial approach, which packs a lot of
9762 ;; punch for so little code.
9763
9764 (defconst js2-possibly-braceless-keywords-re
9765 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9766 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9767 "try" "while" "with" "let")))
9768 "Regular expression matching keywords that are optionally
9769 followed by an opening brace.")
9770
9771 (defconst js2-indent-operator-re
9772 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9773 (regexp-opt '("in" "instanceof") 'words))
9774 "Regular expression matching operators that affect indentation
9775 of continued expressions.")
9776
9777 (defconst js2-declaration-keyword-re
9778 (regexp-opt '("var" "let" "const") 'words)
9779 "Regular expression matching variable declaration keywords.")
9780
9781 ;; This function has horrible results if you're typing an array
9782 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9783 ;; in conjunction with electric-indent, so just disabling it.
9784 (defsubst js2-code-at-bol-p ()
9785 "Return t if the first character on line is non-whitespace."
9786 nil)
9787
9788 (defun js2-insert-and-indent (key)
9789 "Run command bound to key and indent current line. Runs the command
9790 bound to KEY in the global keymap and indents the current line."
9791 (interactive (list (this-command-keys)))
9792 (let ((cmd (lookup-key (current-global-map) key)))
9793 (if (commandp cmd)
9794 (call-interactively cmd)))
9795 ;; don't do the electric keys inside comments or strings,
9796 ;; and don't do bounce-indent with them.
9797 (let ((parse-state (syntax-ppss (point)))
9798 (js2-bounce-indent-p (js2-code-at-bol-p)))
9799 (unless (or (nth 3 parse-state)
9800 (nth 4 parse-state))
9801 (indent-according-to-mode))))
9802
9803 (defun js2-re-search-forward-inner (regexp &optional bound count)
9804 "Auxiliary function for `js2-re-search-forward'."
9805 (let (parse saved-point)
9806 (while (> count 0)
9807 (re-search-forward regexp bound)
9808 (setq parse (if saved-point
9809 (parse-partial-sexp saved-point (point))
9810 (syntax-ppss (point))))
9811 (cond ((nth 3 parse)
9812 (re-search-forward
9813 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9814 (save-excursion (end-of-line) (point)) t))
9815 ((nth 7 parse)
9816 (forward-line))
9817 ((or (nth 4 parse)
9818 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9819 (re-search-forward "\\*/"))
9820 (t
9821 (setq count (1- count))))
9822 (setq saved-point (point))))
9823 (point))
9824
9825 (defun js2-re-search-forward (regexp &optional bound noerror count)
9826 "Search forward but ignore strings and comments. Invokes
9827 `re-search-forward' but treats the buffer as if strings and
9828 comments have been removed."
9829 (let ((saved-point (point))
9830 (search-expr
9831 (cond ((null count)
9832 '(js2-re-search-forward-inner regexp bound 1))
9833 ((< count 0)
9834 '(js2-re-search-backward-inner regexp bound (- count)))
9835 ((> count 0)
9836 '(js2-re-search-forward-inner regexp bound count)))))
9837 (condition-case err
9838 (eval search-expr)
9839 (search-failed
9840 (goto-char saved-point)
9841 (unless noerror
9842 (error (error-message-string err)))))))
9843
9844 (defun js2-re-search-backward-inner (regexp &optional bound count)
9845 "Auxiliary function for `js2-re-search-backward'."
9846 (let (parse saved-point)
9847 (while (> count 0)
9848 (re-search-backward regexp bound)
9849 (setq parse (if saved-point
9850 (parse-partial-sexp saved-point (point))
9851 (syntax-ppss (point))))
9852 (cond ((nth 3 parse)
9853 (re-search-backward
9854 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9855 (save-excursion (beginning-of-line) (point)) t))
9856 ((nth 7 parse)
9857 (goto-char (nth 8 parse)))
9858 ((or (nth 4 parse)
9859 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9860 (re-search-backward "/\\*"))
9861 (t
9862 (setq count (1- count))))))
9863 (point))
9864
9865 (defun js2-re-search-backward (regexp &optional bound noerror count)
9866 "Search backward but ignore strings and comments. Invokes
9867 `re-search-backward' but treats the buffer as if strings and
9868 comments have been removed."
9869 (let ((saved-point (point))
9870 (search-expr
9871 (cond ((null count)
9872 '(js2-re-search-backward-inner regexp bound 1))
9873 ((< count 0)
9874 '(js2-re-search-forward-inner regexp bound (- count)))
9875 ((> count 0)
9876 '(js2-re-search-backward-inner regexp bound count)))))
9877 (condition-case err
9878 (eval search-expr)
9879 (search-failed
9880 (goto-char saved-point)
9881 (unless noerror
9882 (error (error-message-string err)))))))
9883
9884 (defun js2-looking-at-operator-p ()
9885 "Return non-nil if text after point is an operator (that is not
9886 a comma)."
9887 (save-match-data
9888 (and (looking-at js2-indent-operator-re)
9889 (or (not (looking-at ":"))
9890 (save-excursion
9891 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9892 (looking-at "?")))))))
9893
9894 (defun js2-continued-expression-p ()
9895 "Returns non-nil if the current line continues an expression."
9896 (save-excursion
9897 (back-to-indentation)
9898 (or (js2-looking-at-operator-p)
9899 ;; comment
9900 (and (js2-re-search-backward "\n" nil t)
9901 (progn
9902 (skip-chars-backward " \t")
9903 (unless (bolp)
9904 (backward-char)
9905 (and (js2-looking-at-operator-p)
9906 (and (progn
9907 (backward-char)
9908 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))))))
9909
9910 (defun js2-end-of-do-while-loop-p ()
9911 "Returns non-nil if word after point is `while' of a do-while
9912 statement, else returns nil. A braceless do-while statement
9913 spanning several lines requires that the start of the loop is
9914 indented to the same column as the current line."
9915 (interactive)
9916 (save-excursion
9917 (save-match-data
9918 (when (looking-at "\\s-*\\<while\\>")
9919 (if (save-excursion
9920 (skip-chars-backward "[ \t\n]*}")
9921 (looking-at "[ \t\n]*}"))
9922 (save-excursion
9923 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9924 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9925 (or (looking-at "\\<do\\>")
9926 (let ((saved-indent (current-indentation)))
9927 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9928 (/= (current-indentation) saved-indent)))
9929 (and (looking-at "[ \t]*\\<do\\>")
9930 (not (js2-re-search-forward
9931 "\\<while\\>" (point-at-eol) t))
9932 (= (current-indentation) saved-indent)))))))))
9933
9934 (defun js2-multiline-decl-indentation ()
9935 "Returns the declaration indentation column if the current line belongs
9936 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9937 (let (forward-sexp-function ; use Lisp version
9938 at-opening-bracket)
9939 (save-excursion
9940 (back-to-indentation)
9941 (when (not (looking-at js2-declaration-keyword-re))
9942 (when (looking-at js2-indent-operator-re)
9943 (goto-char (match-end 0))) ; continued expressions are ok
9944 (while (and (not at-opening-bracket)
9945 (not (bobp))
9946 (let ((pos (point)))
9947 (save-excursion
9948 (js2-backward-sws)
9949 (or (eq (char-before) ?,)
9950 (and (not (eq (char-before) ?\;))
9951 (and
9952 (prog2 (skip-chars-backward "[[:punct:]]")
9953 (looking-at js2-indent-operator-re)
9954 (js2-backward-sws))
9955 (not (eq (char-before) ?\;))))
9956 (js2-same-line pos)))))
9957 (condition-case err
9958 (backward-sexp)
9959 (scan-error (setq at-opening-bracket t))))
9960 (when (looking-at js2-declaration-keyword-re)
9961 (- (1+ (match-end 0)) (point-at-bol)))))))
9962
9963 (defun js2-ctrl-statement-indentation ()
9964 "Returns the proper indentation of the current line if it
9965 starts the body of a control statement without braces, else
9966 returns nil."
9967 (let (forward-sexp-function) ; temporarily unbind it
9968 (save-excursion
9969 (back-to-indentation)
9970 (when (and (not (js2-same-line (point-min)))
9971 (not (looking-at "{"))
9972 (js2-re-search-backward "[[:graph:]]" nil t)
9973 (not (looking-at "[{([]"))
9974 (progn
9975 (forward-char)
9976 (when (= (char-before) ?\))
9977 ;; scan-sexps sometimes throws an error
9978 (ignore-errors (backward-sexp))
9979 (skip-chars-backward " \t" (point-at-bol)))
9980 (let ((pt (point)))
9981 (back-to-indentation)
9982 (and (looking-at js2-possibly-braceless-keywords-re)
9983 (= (match-end 0) pt)
9984 (not (js2-end-of-do-while-loop-p))))))
9985 (+ (current-indentation) js2-basic-offset)))))
9986
9987 (defun js2-indent-in-array-comp (parse-status)
9988 "Return non-nil if we think we're in an array comprehension.
9989 In particular, return the buffer position of the first `for' kwd."
9990 (let ((bracket (nth 1 parse-status))
9991 (end (point)))
9992 (when bracket
9993 (save-excursion
9994 (goto-char bracket)
9995 (when (looking-at "\\[")
9996 (forward-char 1)
9997 (js2-forward-sws)
9998 (if (looking-at "[[{]")
9999 (let (forward-sexp-function) ; use lisp version
10000 (forward-sexp) ; skip destructuring form
10001 (js2-forward-sws)
10002 (if (and (/= (char-after) ?,) ; regular array
10003 (looking-at "for"))
10004 (match-beginning 0)))
10005 ;; to skip arbitrary expressions we need the parser,
10006 ;; so we'll just guess at it.
10007 (if (and (> end (point)) ; not empty literal
10008 (re-search-forward "[^,]]* \\(for\\) " end t)
10009 ;; not inside comment or string literal
10010 (let ((state (parse-partial-sexp bracket (point))))
10011 (not (or (nth 3 state) (nth 4 state)))))
10012 (match-beginning 1))))))))
10013
10014 (defun js2-array-comp-indentation (parse-status for-kwd)
10015 (if (js2-same-line for-kwd)
10016 ;; first continuation line
10017 (save-excursion
10018 (goto-char (nth 1 parse-status))
10019 (forward-char 1)
10020 (skip-chars-forward " \t")
10021 (current-column))
10022 (save-excursion
10023 (goto-char for-kwd)
10024 (current-column))))
10025
10026 (defun js2-proper-indentation (parse-status)
10027 "Return the proper indentation for the current line."
10028 (save-excursion
10029 (back-to-indentation)
10030 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10031 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
10032 (continued-expr-p (js2-continued-expression-p))
10033 (declaration-indent (and js2-pretty-multiline-declarations
10034 (js2-multiline-decl-indentation)))
10035 (bracket (nth 1 parse-status))
10036 beg)
10037 (cond
10038 ;; indent array comprehension continuation lines specially
10039 ((and bracket
10040 (>= js2-language-version 170)
10041 (not (js2-same-line bracket))
10042 (setq beg (js2-indent-in-array-comp parse-status))
10043 (>= (point) (save-excursion
10044 (goto-char beg)
10045 (point-at-bol)))) ; at or after first loop?
10046 (js2-array-comp-indentation parse-status beg))
10047
10048 (ctrl-stmt-indent)
10049
10050 ((and declaration-indent continued-expr-p)
10051 (+ declaration-indent js2-basic-offset))
10052
10053 (declaration-indent)
10054
10055 (bracket
10056 (goto-char bracket)
10057 (cond
10058 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10059 (when (save-excursion (skip-chars-backward " \t)")
10060 (looking-at ")"))
10061 (backward-list))
10062 (back-to-indentation)
10063 (and (eq js2-pretty-multiline-declarations 'all)
10064 (looking-at js2-declaration-keyword-re)
10065 (goto-char (1+ (match-end 0))))
10066 (cond (same-indent-p
10067 (current-column))
10068 (continued-expr-p
10069 (+ (current-column) (* 2 js2-basic-offset)))
10070 (t
10071 (+ (current-column) js2-basic-offset))))
10072 (t
10073 (unless same-indent-p
10074 (forward-char)
10075 (skip-chars-forward " \t"))
10076 (current-column))))
10077
10078 (continued-expr-p js2-basic-offset)
10079
10080 (t 0)))))
10081
10082 (defun js2-lineup-comment (parse-status)
10083 "Indent a multi-line block comment continuation line."
10084 (let* ((beg (nth 8 parse-status))
10085 (first-line (js2-same-line beg))
10086 (offset (save-excursion
10087 (goto-char beg)
10088 (if (looking-at "/\\*")
10089 (+ 1 (current-column))
10090 0))))
10091 (unless first-line
10092 (indent-line-to offset))))
10093
10094 (defun js2-backward-sws ()
10095 "Move backward through whitespace and comments."
10096 (interactive)
10097 (while (forward-comment -1)))
10098
10099 (defun js2-forward-sws ()
10100 "Move forward through whitespace and comments."
10101 (interactive)
10102 (while (forward-comment 1)))
10103
10104 (defsubst js2-current-indent (&optional pos)
10105 "Return column of indentation on current line.
10106 If POS is non-nil, go to that point and return indentation for that line."
10107 (save-excursion
10108 (if pos
10109 (goto-char pos))
10110 (back-to-indentation)
10111 (current-column)))
10112
10113 (defsubst js2-arglist-close ()
10114 "Return non-nil if we're on a line beginning with a close-paren/brace."
10115 (save-match-data
10116 (save-excursion
10117 (goto-char (point-at-bol))
10118 (js2-forward-sws)
10119 (looking-at "[])}]"))))
10120
10121 (defsubst js2-indent-looks-like-label-p ()
10122 (goto-char (point-at-bol))
10123 (js2-forward-sws)
10124 (looking-at (concat js2-mode-identifier-re ":")))
10125
10126 (defun js2-indent-in-objlit-p (parse-status)
10127 "Return non-nil if this looks like an object-literal entry."
10128 (let ((start (nth 1 parse-status)))
10129 (and
10130 start
10131 (save-excursion
10132 (and (zerop (forward-line -1))
10133 (not (< (point) start)) ; crossed a {} boundary
10134 (js2-indent-looks-like-label-p)))
10135 (save-excursion
10136 (js2-indent-looks-like-label-p)))))
10137
10138 ;; if prev line looks like foobar({ then we're passing an object
10139 ;; literal to a function call, and people pretty much always want to
10140 ;; de-dent back to the previous line, so move the 'basic-offset'
10141 ;; position to the front.
10142 (defsubst js2-indent-objlit-arg-p (parse-status)
10143 (save-excursion
10144 (back-to-indentation)
10145 (js2-backward-sws)
10146 (and (eq (1- (point)) (nth 1 parse-status))
10147 (eq (char-before) ?{)
10148 (progn
10149 (forward-char -1)
10150 (skip-chars-backward " \t")
10151 (eq (char-before) ?\()))))
10152
10153 (defsubst js2-indent-case-block-p ()
10154 (save-excursion
10155 (back-to-indentation)
10156 (js2-backward-sws)
10157 (goto-char (point-at-bol))
10158 (skip-chars-forward " \t")
10159 (save-match-data
10160 (looking-at "case\\s-.+:"))))
10161
10162 (defsubst js2-syntax-bol ()
10163 "Return the point at the first non-whitespace char on the line.
10164 Returns `point-at-bol' if the line is empty."
10165 (save-excursion
10166 (beginning-of-line)
10167 (skip-chars-forward " \t")
10168 (point)))
10169
10170 (defun js2-bounce-indent (normal-col parse-status backwards)
10171 "Cycle among alternate computed indentation positions.
10172 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10173 of the buffer to the current point. NORMAL-COL is the indentation
10174 column computed by the heuristic guesser based on current paren,
10175 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10176 in reverse."
10177 (let ((cur-indent (js2-current-indent))
10178 (old-buffer-undo-list buffer-undo-list)
10179 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10180 (current-line (save-excursion
10181 (forward-line 0) ; move to bol
10182 (1+ (count-lines (point-min) (point)))))
10183 positions
10184 pos
10185 main-pos
10186 anchor
10187 arglist-cont
10188 same-indent
10189 prev-line-col
10190 basic-offset
10191 computed-pos)
10192 ;; temporarily don't record undo info, if user requested this
10193 (if js2-mode-indent-inhibit-undo
10194 (setq buffer-undo-list t))
10195 (unwind-protect
10196 (progn
10197 ;; first likely point: indent from beginning of previous code line
10198 (push (setq basic-offset
10199 (+ (save-excursion
10200 (back-to-indentation)
10201 (js2-backward-sws)
10202 (back-to-indentation)
10203 (setq prev-line-col (current-column)))
10204 js2-basic-offset))
10205 positions)
10206
10207 ;; (first + epsilon) likely point: indent 2x from beginning of
10208 ;; previous code line. Some companies like this approach. Ahem.
10209 ;; Seriously, though -- 4-space indent for expression continuation
10210 ;; lines isn't a bad idea. We should eventually implement it
10211 ;; that way.
10212 (push (setq basic-offset
10213 (+ (save-excursion
10214 (back-to-indentation)
10215 (js2-backward-sws)
10216 (back-to-indentation)
10217 (setq prev-line-col (current-column)))
10218 (* 2 js2-basic-offset)))
10219 positions)
10220
10221 ;; second likely point: indent from assign-expr RHS. This
10222 ;; is just a crude guess based on finding " = " on the previous
10223 ;; line containing actual code.
10224 (setq pos (save-excursion
10225 (save-match-data
10226 (forward-line -1)
10227 (goto-char (point-at-bol))
10228 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10229 (point-at-eol) t)
10230 (goto-char (match-end 1))
10231 (skip-chars-forward " \t\r\n")
10232 (current-column)))))
10233 (when pos
10234 (incf pos js2-basic-offset)
10235 (push pos positions))
10236
10237 ;; third likely point: same indent as previous line of code.
10238 ;; Make it the first likely point if we're not on an
10239 ;; arglist-close line and previous line ends in a comma, or
10240 ;; both this line and prev line look like object-literal
10241 ;; elements.
10242 (setq pos (save-excursion
10243 (goto-char (point-at-bol))
10244 (js2-backward-sws)
10245 (back-to-indentation)
10246 (prog1
10247 (current-column)
10248 ;; while we're here, look for trailing comma
10249 (if (save-excursion
10250 (goto-char (point-at-eol))
10251 (js2-backward-sws)
10252 (eq (char-before) ?,))
10253 (setq arglist-cont (1- (point)))))))
10254 (when pos
10255 (if (and (or arglist-cont
10256 (js2-indent-in-objlit-p parse-status))
10257 (not (js2-arglist-close)))
10258 (setq same-indent pos))
10259 (push pos positions))
10260
10261 ;; fourth likely point: first preceding code with less indentation
10262 ;; than the immediately preceding code line.
10263 (setq pos (save-excursion
10264 (back-to-indentation)
10265 (js2-backward-sws)
10266 (back-to-indentation)
10267 (setq anchor (current-column))
10268 (while (and (zerop (forward-line -1))
10269 (>= (progn
10270 (back-to-indentation)
10271 (current-column))
10272 anchor)))
10273 (setq pos (current-column))))
10274 (push pos positions)
10275
10276 ;; nesting-heuristic position, main by default
10277 (push (setq main-pos normal-col) positions)
10278
10279 ;; delete duplicates and sort positions list
10280 (setq positions (sort (delete-dups positions) '<))
10281
10282 ;; comma-list continuation lines: prev line indent takes precedence
10283 (if same-indent
10284 (setq main-pos same-indent))
10285
10286 ;; common special cases where we want to indent in from previous line
10287 (if (or (js2-indent-case-block-p)
10288 (js2-indent-objlit-arg-p parse-status))
10289 (setq main-pos basic-offset))
10290
10291 ;; if bouncing backwards, reverse positions list
10292 (if backwards
10293 (setq positions (reverse positions)))
10294
10295 ;; record whether we're already sitting on one of the alternatives
10296 (setq pos (member cur-indent positions))
10297
10298 (cond
10299 ;; case 0: we're one one of the alternatives and this is the
10300 ;; first time they've pressed TAB on this line (best-guess).
10301 ((and js2-mode-indent-ignore-first-tab
10302 pos
10303 ;; first time pressing TAB on this line?
10304 (not (eq js2-mode-last-indented-line current-line)))
10305 ;; do nothing
10306 (setq computed-pos nil))
10307 ;; case 1: only one computed position => use it
10308 ((null (cdr positions))
10309 (setq computed-pos 0))
10310 ;; case 2: not on any of the computed spots => use main spot
10311 ((not pos)
10312 (setq computed-pos (js2-position main-pos positions)))
10313 ;; case 3: on last position: cycle to first position
10314 ((null (cdr pos))
10315 (setq computed-pos 0))
10316 ;; case 4: on intermediate position: cycle to next position
10317 (t
10318 (setq computed-pos (js2-position (second pos) positions))))
10319
10320 ;; see if any hooks want to indent; otherwise we do it
10321 (loop with result = nil
10322 for hook in js2-indent-hook
10323 while (null result)
10324 do
10325 (setq result (funcall hook positions computed-pos))
10326 finally do
10327 (unless (or result (null computed-pos))
10328 (indent-line-to (nth computed-pos positions)))))
10329
10330 ;; finally
10331 (if js2-mode-indent-inhibit-undo
10332 (setq buffer-undo-list old-buffer-undo-list))
10333 ;; see commentary for `js2-mode-last-indented-line'
10334 (setq js2-mode-last-indented-line current-line))))
10335
10336 (defun js2-indent-bounce-backwards ()
10337 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10338 cycles between the computed indentation positions in reverse order."
10339 (interactive)
10340 (js2-indent-line t))
10341
10342 (defsubst js2-1-line-comment-continuation-p ()
10343 "Return t if we're in a 1-line comment continuation.
10344 If so, we don't ever want to use bounce-indent."
10345 (save-excursion
10346 (save-match-data
10347 (and (progn
10348 (forward-line 0)
10349 (looking-at "\\s-*//"))
10350 (progn
10351 (forward-line -1)
10352 (forward-line 0)
10353 (when (looking-at "\\s-*$")
10354 (js2-backward-sws)
10355 (forward-line 0))
10356 (looking-at "\\s-*//"))))))
10357
10358 (defun js2-indent-line (&optional bounce-backwards)
10359 "Indent the current line as JavaScript source text."
10360 (interactive)
10361 (let (parse-status
10362 offset
10363 indent-col
10364 moved
10365 ;; don't whine about errors/warnings when we're indenting.
10366 ;; This has to be set before calling parse-partial-sexp below.
10367 (inhibit-point-motion-hooks t))
10368 (setq parse-status (save-excursion
10369 (syntax-ppss (point-at-bol)))
10370 offset (- (point) (save-excursion
10371 (back-to-indentation)
10372 (point))))
10373 (js2-with-underscore-as-word-syntax
10374 (if (nth 4 parse-status)
10375 (js2-lineup-comment parse-status)
10376 (setq indent-col (js2-proper-indentation parse-status))
10377 ;; see comments below about js2-mode-last-indented-line
10378 (cond
10379 ;; bounce-indenting is disabled during electric-key indent.
10380 ;; It doesn't work well on first line of buffer.
10381 ((and js2-bounce-indent-p
10382 (not (js2-same-line (point-min)))
10383 (not (js2-1-line-comment-continuation-p)))
10384 (js2-bounce-indent indent-col parse-status bounce-backwards))
10385 ;; just indent to the guesser's likely spot
10386 (t (indent-line-to indent-col)))
10387 (when (plusp offset)
10388 (forward-char offset))))))
10389
10390 (defun js2-indent-region (start end)
10391 "Indent the region, but don't use bounce indenting."
10392 (let ((js2-bounce-indent-p nil)
10393 (indent-region-function nil)
10394 (after-change-functions (remq 'js2-mode-edit
10395 after-change-functions)))
10396 (indent-region start end nil) ; nil for byte-compiler
10397 (js2-mode-edit start end (- end start))))
10398
10399 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10400
10401 ;;;###autoload
10402 (defun js2-mode ()
10403 "Major mode for editing JavaScript code."
10404 (interactive)
10405 (kill-all-local-variables)
10406 (set-syntax-table js2-mode-syntax-table)
10407 (use-local-map js2-mode-map)
10408 (make-local-variable 'comment-start)
10409 (make-local-variable 'comment-end)
10410 (make-local-variable 'comment-start-skip)
10411 (setq major-mode 'js2-mode
10412 mode-name "JavaScript-IDE"
10413 comment-start "//" ; used by comment-region; don't change it
10414 comment-end "")
10415 (setq local-abbrev-table js2-mode-abbrev-table)
10416 (set (make-local-variable 'max-lisp-eval-depth)
10417 (max max-lisp-eval-depth 3000))
10418 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10419 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10420
10421 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10422 ;; on most platforms other than the one I originally wrote it on.
10423 ;; So it's back to `c-fill-paragraph'.
10424 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10425
10426 (add-hook 'before-save-hook #'js2-before-save nil t)
10427 (set (make-local-variable 'next-error-function) #'js2-next-error)
10428 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10429 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10430 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10431 ;; for characters inside regexp literals.
10432 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10433 ;; this is necessary to make `show-paren-function' work properly
10434 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10435 ;; needed for M-x rgrep, among other things
10436 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10437
10438 ;; some variables needed by cc-engine for paragraph-fill, etc.
10439 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10440 c-comment-start-regexp "/[*/]\\|\\s|"
10441 c-line-comment-starter "//"
10442 c-paragraph-start js2-paragraph-start
10443 c-paragraph-separate "$"
10444 comment-start-skip js2-comment-start-skip
10445 c-syntactic-ws-start js2-syntactic-ws-start
10446 c-syntactic-ws-end js2-syntactic-ws-end
10447 c-syntactic-eol js2-syntactic-eol)
10448
10449 (let ((c-buffer-is-cc-mode t))
10450 ;; Copied from `js-mode'. Also see Bug#6071.
10451 (make-local-variable 'paragraph-start)
10452 (make-local-variable 'paragraph-separate)
10453 (make-local-variable 'paragraph-ignore-fill-prefix)
10454 (make-local-variable 'adaptive-fill-mode)
10455 (make-local-variable 'adaptive-fill-regexp)
10456 (c-setup-paragraph-variables))
10457
10458 (setq js2-default-externs
10459 (append js2-ecma-262-externs
10460 (if js2-include-browser-externs
10461 js2-browser-externs)
10462 (if js2-include-gears-externs
10463 js2-gears-externs)
10464 (if js2-include-rhino-externs
10465 js2-rhino-externs)))
10466
10467 ;; We do our own syntax highlighting based on the parse tree.
10468 ;; However, we want minor modes that add keywords to highlight properly
10469 ;; (examples: doxymacs, column-marker).
10470 ;; To customize highlighted keywords, use `font-lock-add-keywords'.
10471 (setq font-lock-defaults '(nil t))
10472
10473 ;; Experiment: make reparse-delay longer for longer files.
10474 (if (plusp js2-dynamic-idle-timer-adjust)
10475 (setq js2-idle-timer-delay
10476 (* js2-idle-timer-delay
10477 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10478
10479 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10480 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10481 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10482 (imenu-add-to-menubar (concat "IM-" mode-name))
10483 (when js2-mirror-mode
10484 (js2-enter-mirror-mode))
10485 (add-to-invisibility-spec '(js2-outline . t))
10486 (set (make-local-variable 'line-move-ignore-invisible) t)
10487 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10488
10489 (if (fboundp 'run-mode-hooks)
10490 (run-mode-hooks 'js2-mode-hook)
10491 (run-hooks 'js2-mode-hook))
10492
10493 (setq js2-mode-functions-hidden nil
10494 js2-mode-comments-hidden nil
10495 js2-mode-buffer-dirty-p t
10496 js2-mode-parsing nil)
10497 (js2-reparse))
10498
10499 (defun js2-mode-exit ()
10500 "Exit `js2-mode' and clean up."
10501 (interactive)
10502 (when js2-mode-node-overlay
10503 (delete-overlay js2-mode-node-overlay)
10504 (setq js2-mode-node-overlay nil))
10505 (js2-remove-overlays)
10506 (setq js2-mode-ast nil)
10507 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10508 (remove-from-invisibility-spec '(js2-outline . t))
10509 (js2-mode-show-all)
10510 (js2-with-unmodifying-text-property-changes
10511 (js2-clear-face (point-min) (point-max))))
10512
10513 (defun js2-before-save ()
10514 "Clean up whitespace before saving file.
10515 You can disable this by customizing `js2-cleanup-whitespace'."
10516 (when js2-cleanup-whitespace
10517 (let ((col (current-column)))
10518 (delete-trailing-whitespace)
10519 ;; don't change trailing whitespace on current line
10520 (unless (eq (current-column) col)
10521 (indent-to col)))))
10522
10523 (defsubst js2-mode-reset-timer ()
10524 "Cancel any existing parse timer and schedule a new one."
10525 (if js2-mode-parse-timer
10526 (cancel-timer js2-mode-parse-timer))
10527 (setq js2-mode-parsing nil)
10528 (setq js2-mode-parse-timer
10529 (run-with-idle-timer js2-idle-timer-delay nil
10530 #'js2-mode-idle-reparse (current-buffer))))
10531
10532 (defun js2-mode-idle-reparse (buffer)
10533 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10534 it to be reparsed when the buffer is selected."
10535 (if (eq buffer (current-buffer))
10536 (js2-reparse)
10537 ;; reparse when the buffer is selected again
10538 (with-current-buffer buffer
10539 (add-hook 'window-configuration-change-hook
10540 #'js2-mode-idle-reparse-inner
10541 nil t))))
10542
10543 (defun js2-mode-idle-reparse-inner ()
10544 (remove-hook 'window-configuration-change-hook
10545 #'js2-mode-idle-reparse-inner
10546 t)
10547 (js2-reparse))
10548
10549 (defun js2-mode-edit (beg end len)
10550 "Schedule a new parse after buffer is edited.
10551 Buffer edit spans from BEG to END and is of length LEN.
10552 Also clears the `js2-magic' bit on autoinserted parens/brackets
10553 if the edit occurred on a line different from the magic paren."
10554 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10555 (line (if magic-pos (line-number-at-pos magic-pos))))
10556 (and line
10557 (or (/= (line-number-at-pos beg) line)
10558 (and (> 0 len)
10559 (/= (line-number-at-pos end) line)))
10560 (js2-mode-mundanify-parens)))
10561 (setq js2-mode-buffer-dirty-p t)
10562 (js2-mode-hide-overlay)
10563 (js2-mode-reset-timer))
10564
10565 (defun js2-reparse (&optional force)
10566 "Re-parse current buffer after user finishes some data entry.
10567 If we get any user input while parsing, including cursor motion,
10568 we discard the parse and reschedule it. If FORCE is nil, then the
10569 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10570 (let (time
10571 interrupted-p
10572 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10573 (unless js2-mode-parsing
10574 (setq js2-mode-parsing t)
10575 (unwind-protect
10576 (when (or js2-mode-buffer-dirty-p force)
10577 (js2-remove-overlays)
10578 (js2-with-unmodifying-text-property-changes
10579 (setq js2-mode-buffer-dirty-p nil
10580 js2-mode-fontifications nil
10581 js2-mode-deferred-properties nil)
10582 (if js2-mode-verbose-parse-p
10583 (message "parsing..."))
10584 (setq time
10585 (js2-time
10586 (setq interrupted-p
10587 (catch 'interrupted
10588 (setq js2-mode-ast (js2-parse))
10589 ;; if parsing is interrupted, comments and regex
10590 ;; literals stay ignored by `parse-partial-sexp'
10591 (remove-text-properties (point-min) (point-max)
10592 '(syntax-table))
10593 (js2-mode-apply-deferred-properties)
10594 (js2-mode-remove-suppressed-warnings)
10595 (js2-mode-show-warnings)
10596 (js2-mode-show-errors)
10597 (js2-mode-highlight-magic-parens)
10598 (if (>= js2-highlight-level 1)
10599 (js2-highlight-jsdoc js2-mode-ast))
10600 nil))))
10601 (if interrupted-p
10602 (progn
10603 ;; unfinished parse => try again
10604 (setq js2-mode-buffer-dirty-p t)
10605 (js2-mode-reset-timer))
10606 (if js2-mode-verbose-parse-p
10607 (message "Parse time: %s" time)))))
10608 (setq js2-mode-parsing nil)
10609 (unless interrupted-p
10610 (setq js2-mode-parse-timer nil))))))
10611
10612 (defun js2-mode-show-node ()
10613 "Debugging aid: highlight selected AST node on mouse click."
10614 (interactive)
10615 (let ((node (js2-node-at-point))
10616 beg
10617 end)
10618 (when js2-mode-show-overlay
10619 (if (null node)
10620 (message "No node found at location %s" (point))
10621 (setq beg (js2-node-abs-pos node)
10622 end (+ beg (js2-node-len node)))
10623 (if js2-mode-node-overlay
10624 (move-overlay js2-mode-node-overlay beg end)
10625 (setq js2-mode-node-overlay (make-overlay beg end))
10626 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10627 (js2-with-unmodifying-text-property-changes
10628 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10629 (message "%s, parent: %s"
10630 (js2-node-short-name node)
10631 (if (js2-node-parent node)
10632 (js2-node-short-name (js2-node-parent node))
10633 "nil"))))))
10634
10635 (defun js2-mode-hide-overlay (&optional p1 p2)
10636 "Remove the debugging overlay when the point moves.
10637 P1 and P2 are the old and new values of point, respectively."
10638 (when js2-mode-node-overlay
10639 (let ((beg (overlay-start js2-mode-node-overlay))
10640 (end (overlay-end js2-mode-node-overlay)))
10641 ;; Sometimes we're called spuriously.
10642 (unless (and p2
10643 (>= p2 beg)
10644 (<= p2 end))
10645 (js2-with-unmodifying-text-property-changes
10646 (remove-text-properties beg end '(point-left nil)))
10647 (delete-overlay js2-mode-node-overlay)
10648 (setq js2-mode-node-overlay nil)))))
10649
10650 (defun js2-mode-reset ()
10651 "Debugging helper: reset everything."
10652 (interactive)
10653 (js2-mode-exit)
10654 (js2-mode))
10655
10656 (defsubst js2-mode-show-warn-or-err (e face)
10657 "Highlight a warning or error E with FACE.
10658 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10659 (let* ((key (first e))
10660 (beg (second e))
10661 (end (+ beg (third e)))
10662 ;; Don't inadvertently go out of bounds.
10663 (beg (max (point-min) (min beg (point-max))))
10664 (end (max (point-min) (min end (point-max))))
10665 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10666 (ovl (make-overlay beg end)))
10667 (overlay-put ovl 'font-lock-face face)
10668 (overlay-put ovl 'js2-error t)
10669 (put-text-property beg end 'help-echo (js2-get-msg key))
10670 (put-text-property beg end 'point-entered #'js2-echo-error)))
10671
10672 (defun js2-remove-overlays ()
10673 "Remove overlays from buffer that have a `js2-error' property."
10674 (let ((beg (point-min))
10675 (end (point-max)))
10676 (save-excursion
10677 (dolist (o (overlays-in beg end))
10678 (when (overlay-get o 'js2-error)
10679 (delete-overlay o))))))
10680
10681 (defun js2-error-at-point (&optional pos)
10682 "Return non-nil if there's an error overlay at POS.
10683 Defaults to point."
10684 (loop with pos = (or pos (point))
10685 for o in (overlays-at pos)
10686 thereis (overlay-get o 'js2-error)))
10687
10688 (defun js2-mode-apply-deferred-properties ()
10689 "Apply fontifications and other text properties recorded during parsing."
10690 (when (plusp js2-highlight-level)
10691 ;; We defer clearing faces as long as possible to eliminate flashing.
10692 (js2-clear-face (point-min) (point-max))
10693 ;; Have to reverse the recorded fontifications list so that errors
10694 ;; and warnings overwrite the normal fontifications.
10695 (dolist (f (nreverse js2-mode-fontifications))
10696 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10697 (setq js2-mode-fontifications nil))
10698 (dolist (p js2-mode-deferred-properties)
10699 (apply #'put-text-property p))
10700 (setq js2-mode-deferred-properties nil))
10701
10702 (defun js2-mode-show-errors ()
10703 "Highlight syntax errors."
10704 (when js2-mode-show-parse-errors
10705 (dolist (e (js2-ast-root-errors js2-mode-ast))
10706 (js2-mode-show-warn-or-err e 'js2-error-face))))
10707
10708 (defun js2-mode-remove-suppressed-warnings ()
10709 "Take suppressed warnings out of the AST warnings list.
10710 This ensures that the counts and `next-error' are correct."
10711 (setf (js2-ast-root-warnings js2-mode-ast)
10712 (js2-delete-if
10713 (lambda (e)
10714 (let ((key (caar e)))
10715 (or
10716 (and (not js2-strict-trailing-comma-warning)
10717 (string-match "trailing\\.comma" key))
10718 (and (not js2-strict-cond-assign-warning)
10719 (string= key "msg.equal.as.assign"))
10720 (and js2-missing-semi-one-line-override
10721 (string= key "msg.missing.semi")
10722 (let* ((beg (second e))
10723 (node (js2-node-at-point beg))
10724 (fn (js2-mode-find-parent-fn node))
10725 (body (and fn (js2-function-node-body fn)))
10726 (lc (and body (js2-node-abs-pos body)))
10727 (rc (and lc (+ lc (js2-node-len body)))))
10728 (and fn
10729 (or (null body)
10730 (save-excursion
10731 (goto-char beg)
10732 (and (js2-same-line lc)
10733 (js2-same-line rc))))))))))
10734 (js2-ast-root-warnings js2-mode-ast))))
10735
10736 (defun js2-mode-show-warnings ()
10737 "Highlight strict-mode warnings."
10738 (when js2-mode-show-strict-warnings
10739 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10740 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10741
10742 (defun js2-echo-error (old-point new-point)
10743 "Called by point-motion hooks."
10744 (let ((msg (get-text-property new-point 'help-echo)))
10745 (if (and msg (or (not (current-message))
10746 (string= (current-message) "Quit")))
10747 (message msg))))
10748
10749 (defalias #'js2-echo-help #'js2-echo-error)
10750
10751 (defun js2-enter-key ()
10752 "Handle user pressing the Enter key."
10753 (interactive)
10754 (let ((parse-status (save-excursion
10755 (syntax-ppss (point))))
10756 (js2-bounce-indent-p nil))
10757 (cond
10758 ;; check if we're inside a string
10759 ((nth 3 parse-status)
10760 (if js2-concat-multiline-strings
10761 (js2-mode-split-string parse-status)
10762 (insert "\n")))
10763 ;; check if inside a block comment
10764 ((nth 4 parse-status)
10765 (js2-mode-extend-comment))
10766 (t
10767 ;; should probably figure out what the mode-map says we should do
10768 (if js2-indent-on-enter-key
10769 (js2-indent-line))
10770 (insert "\n")
10771 (if js2-enter-indents-newline
10772 (js2-indent-line))))))
10773
10774 (defun js2-mode-split-string (parse-status)
10775 "Turn a newline in mid-string into a string concatenation.
10776 PARSE-STATUS is as documented in `parse-partial-sexp'."
10777 (let* ((col (current-column))
10778 (quote-char (nth 3 parse-status))
10779 (quote-string (string quote-char))
10780 (string-beg (nth 8 parse-status))
10781 (at-eol (eq js2-concat-multiline-strings 'eol))
10782 (indent (save-match-data
10783 (or
10784 (save-excursion
10785 (back-to-indentation)
10786 (if (looking-at "\\+")
10787 (current-column)))
10788 (save-excursion
10789 (goto-char string-beg)
10790 (if (looking-back "\\+\\s-+")
10791 (goto-char (match-beginning 0)))
10792 (current-column))))))
10793 (insert quote-char)
10794 (if at-eol
10795 (insert " +\n")
10796 (insert "\n"))
10797 ;; FIXME: This does not match the behavior of `js2-indent-line'.
10798 (indent-to indent)
10799 (unless at-eol
10800 (insert "+ "))
10801 (insert quote-string)
10802 (when (eolp)
10803 (insert quote-string)
10804 (backward-char 1))))
10805
10806 (defun js2-mode-extend-comment ()
10807 "Indent the line and, when inside a comment block, add comment prefix."
10808 (let (star single col first-line needs-close)
10809 (save-excursion
10810 (back-to-indentation)
10811 (cond
10812 ((looking-at "\\*[^/]")
10813 (setq star t
10814 col (current-column)))
10815 ((looking-at "/\\*")
10816 (setq star t
10817 first-line t
10818 col (1+ (current-column))))
10819 ((looking-at "//")
10820 (setq single t
10821 col (current-column)))))
10822 ;; Heuristic for whether we need to close the comment:
10823 ;; if we've got a parse error here, assume it's an unterminated
10824 ;; comment.
10825 (setq needs-close
10826 (or
10827 (eq (get-text-property (1- (point)) 'point-entered)
10828 'js2-echo-error)
10829 ;; The heuristic above doesn't work well when we're
10830 ;; creating a comment and there's another one downstream,
10831 ;; as our parser thinks this one ends at the end of the
10832 ;; next one. (You can have a /* inside a js block comment.)
10833 ;; So just close it if the next non-ws char isn't a *.
10834 (and first-line
10835 (eolp)
10836 (save-excursion
10837 (skip-chars-forward " \t\r\n")
10838 (not (eq (char-after) ?*))))))
10839 (insert "\n")
10840 (cond
10841 (star
10842 (indent-to col)
10843 (insert "* ")
10844 (if (and first-line needs-close)
10845 (save-excursion
10846 (insert "\n")
10847 (indent-to col)
10848 (insert "*/"))))
10849 ((and single
10850 (save-excursion
10851 (and (zerop (forward-line 1))
10852 (looking-at "\\s-*//"))))
10853 (indent-to col)
10854 (insert "// "))
10855 ;; don't need to extend the comment after all
10856 (js2-enter-indents-newline
10857 (js2-indent-line)))))
10858
10859 (defun js2-beginning-of-line ()
10860 "Toggles point between bol and first non-whitespace char in line.
10861 Also moves past comment delimiters when inside comments."
10862 (interactive)
10863 (let (node beg)
10864 (cond
10865 ((bolp)
10866 (back-to-indentation))
10867 ((looking-at "//")
10868 (skip-chars-forward "/ \t"))
10869 ((and (eq (char-after) ?*)
10870 (setq node (js2-comment-at-point))
10871 (memq (js2-comment-node-format node) '(jsdoc block))
10872 (save-excursion
10873 (skip-chars-backward " \t")
10874 (bolp)))
10875 (skip-chars-forward "\* \t"))
10876 (t
10877 (goto-char (point-at-bol))))))
10878
10879 (defun js2-end-of-line ()
10880 "Toggles point between eol and last non-whitespace char in line."
10881 (interactive)
10882 (if (eolp)
10883 (skip-chars-backward " \t")
10884 (goto-char (point-at-eol))))
10885
10886 (defun js2-enter-mirror-mode()
10887 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10888 on insertion."
10889 (interactive)
10890 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10891 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10892 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10893 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10894 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10895 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10896 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10897 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10898
10899 (defun js2-leave-mirror-mode()
10900 "Turns off mirror mode."
10901 (interactive)
10902 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10903 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10904
10905 (defsubst js2-mode-inside-string ()
10906 "Return non-nil if inside a string.
10907 Actually returns the quote character that begins the string."
10908 (let ((parse-state (save-excursion
10909 (syntax-ppss (point)))))
10910 (nth 3 parse-state)))
10911
10912 (defsubst js2-mode-inside-comment-or-string ()
10913 "Return non-nil if inside a comment or string."
10914 (or
10915 (let ((comment-start
10916 (save-excursion
10917 (goto-char (point-at-bol))
10918 (if (re-search-forward "//" (point-at-eol) t)
10919 (match-beginning 0)))))
10920 (and comment-start
10921 (<= comment-start (point))))
10922 (let ((parse-state (save-excursion
10923 (syntax-ppss (point)))))
10924 (or (nth 3 parse-state)
10925 (nth 4 parse-state)))))
10926
10927 (defsubst js2-make-magic-delimiter (delim &optional pos)
10928 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10929 Sets value of `js2-magic' text property to line number at POS."
10930 (propertize delim
10931 'js2-magic (line-number-at-pos pos)
10932 'font-lock-face 'js2-magic-paren-face))
10933
10934 (defun js2-mode-match-delimiter (open close)
10935 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10936 The rule we use, which as far as we can tell is how Eclipse works,
10937 is that we insert the match if we're not in a comment or string,
10938 and the next non-whitespace character is either punctuation or
10939 occurs on another line."
10940 (insert open)
10941 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10942 (not (js2-mode-inside-comment-or-string)))
10943 (save-excursion
10944 (insert (js2-make-magic-delimiter close)))
10945 (when js2-auto-indent-p
10946 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10947 (js2-indent-line)))))
10948
10949 (defun js2-mode-match-bracket ()
10950 "Insert matching bracket."
10951 (interactive)
10952 (js2-mode-match-delimiter "[" "]"))
10953
10954 (defun js2-mode-match-paren ()
10955 "Insert matching paren unless already inserted."
10956 (interactive)
10957 (js2-mode-match-delimiter "(" ")"))
10958
10959 (defun js2-mode-match-curly (arg)
10960 "Insert matching curly-brace.
10961 With prefix arg, no formatting or indentation will occur -- the close-brace
10962 is simply inserted directly at the point."
10963 (interactive "p")
10964 (let (try-pos)
10965 (cond
10966 (current-prefix-arg
10967 (js2-mode-match-delimiter "{" "}"))
10968 ((and js2-auto-insert-catch-block
10969 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10970 (point-at-bol))
10971 (match-beginning 1))))
10972 (js2-insert-catch-skel try-pos))
10973 (t
10974 ;; Otherwise try to do something smarter.
10975 (insert "{")
10976 (unless (or (not (looking-at "\\s-*$"))
10977 (save-excursion
10978 (skip-chars-forward " \t\r\n")
10979 (and (looking-at "}")
10980 (js2-error-at-point)))
10981 (js2-mode-inside-comment-or-string))
10982 (undo-boundary)
10983 ;; absolutely mystifying bug: when inserting the next "\n",
10984 ;; the buffer-undo-list is given two new entries: the inserted range,
10985 ;; and the incorrect position of the point. It's recorded incorrectly
10986 ;; as being before the opening "{", not after it. But it's recorded
10987 ;; as the correct value if you're debugging `js2-mode-match-curly'
10988 ;; in edebug. I have no idea why it's doing this, but incrementing
10989 ;; the inserted position fixes the problem, so that the undo takes us
10990 ;; back to just after the user-inserted "{".
10991 (insert "\n")
10992 (ignore-errors
10993 (incf (cadr buffer-undo-list)))
10994 (js2-indent-line)
10995 (save-excursion
10996 (insert "\n}")
10997 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10998 (js2-indent-line))))))))
10999
11000 (defun js2-insert-catch-skel (try-pos)
11001 "Complete a try/catch block after inserting a { following a try keyword.
11002 Rationale is that a try always needs a catch or a finally, and the catch is
11003 the more likely of the two.
11004
11005 TRY-POS is the buffer position of the try keyword. The open-curly should
11006 already have been inserted."
11007 (insert "{")
11008 (let ((try-col (save-excursion
11009 (goto-char try-pos)
11010 (current-column))))
11011 (insert "\n")
11012 (undo-boundary)
11013 (js2-indent-line) ;; indent the blank line where cursor will end up
11014 (save-excursion
11015 (insert "\n")
11016 (indent-to try-col)
11017 (insert "} catch (x) {\n\n")
11018 (indent-to try-col)
11019 (insert "}"))))
11020
11021 (defun js2-mode-highlight-magic-parens ()
11022 "Re-highlight magic parens after parsing nukes the 'face prop."
11023 (let ((beg (point-min))
11024 end)
11025 (while (setq beg (next-single-property-change beg 'js2-magic))
11026 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11027 (if (get-text-property beg 'js2-magic)
11028 (js2-with-unmodifying-text-property-changes
11029 (put-text-property beg (or end (1+ beg))
11030 'font-lock-face 'js2-magic-paren-face))))))
11031
11032 (defun js2-mode-mundanify-parens ()
11033 "Clear all magic parens and brackets."
11034 (let ((beg (point-min))
11035 end)
11036 (while (setq beg (next-single-property-change beg 'js2-magic))
11037 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11038 (remove-text-properties beg (or end (1+ beg))
11039 '(js2-magic face)))))
11040
11041 (defsubst js2-match-quote (quote-string)
11042 (let ((start-quote (js2-mode-inside-string)))
11043 (cond
11044 ;; inside a comment - don't do quote-matching, since we can't
11045 ;; reliably figure out if we're in a string inside the comment
11046 ((js2-comment-at-point)
11047 (insert quote-string))
11048 ((not start-quote)
11049 ;; not in string => insert matched quotes
11050 (insert quote-string)
11051 ;; exception: if we're just before a word, don't double it.
11052 (unless (looking-at "[^ \t\r\n]")
11053 (save-excursion
11054 (insert quote-string))))
11055 ((looking-at quote-string)
11056 (if (looking-back "[^\\]\\\\")
11057 (insert quote-string)
11058 (forward-char 1)))
11059 ((and js2-mode-escape-quotes
11060 (save-excursion
11061 (save-match-data
11062 (re-search-forward quote-string (point-at-eol) t))))
11063 ;; inside terminated string, escape quote (unless already escaped)
11064 (insert (if (looking-back "[^\\]\\\\")
11065 quote-string
11066 (concat "\\" quote-string))))
11067 (t
11068 (insert quote-string))))) ; else terminate the string
11069
11070 (defun js2-mode-match-single-quote ()
11071 "Insert matching single-quote."
11072 (interactive)
11073 (let ((parse-status (syntax-ppss (point))))
11074 ;; don't match inside comments, since apostrophe is more common
11075 (if (nth 4 parse-status)
11076 (insert "'")
11077 (js2-match-quote "'"))))
11078
11079 (defun js2-mode-match-double-quote ()
11080 "Insert matching double-quote."
11081 (interactive)
11082 (js2-match-quote "\""))
11083
11084 ;; Eclipse works as follows:
11085 ;; * type an open-paren and it auto-inserts close-paren
11086 ;; - auto-inserted paren gets a green bracket
11087 ;; - green bracket means typing close-paren there will skip it
11088 ;; * if you insert any text on a different line, it turns off
11089 (defun js2-mode-magic-close-paren ()
11090 "Skip over close-paren rather than inserting, where appropriate."
11091 (interactive)
11092 (let* ((here (point))
11093 (parse-status (syntax-ppss here))
11094 (open-pos (nth 1 parse-status))
11095 (close last-input-event)
11096 (open (cond
11097 ((eq close ?\))
11098 ?\()
11099 ((eq close ?\])
11100 ?\[)
11101 ((eq close ?})
11102 ?{)
11103 (t nil))))
11104 (if (and (eq (char-after) close)
11105 (eq open (char-after open-pos))
11106 (js2-same-line open-pos)
11107 (get-text-property here 'js2-magic))
11108 (progn
11109 (remove-text-properties here (1+ here) '(js2-magic face))
11110 (forward-char 1))
11111 (insert-char close 1))
11112 (blink-matching-open)))
11113
11114 (defun js2-mode-wait-for-parse (callback)
11115 "Invoke CALLBACK when parsing is finished.
11116 If parsing is already finished, calls CALLBACK immediately."
11117 (if (not js2-mode-buffer-dirty-p)
11118 (funcall callback)
11119 (push callback js2-mode-pending-parse-callbacks)
11120 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11121
11122 (defun js2-mode-parse-finished ()
11123 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11124 ;; We can't let errors propagate up, since it prevents the
11125 ;; `js2-parse' method from completing normally and returning
11126 ;; the ast, which makes things mysteriously not work right.
11127 (unwind-protect
11128 (dolist (cb js2-mode-pending-parse-callbacks)
11129 (condition-case err
11130 (funcall cb)
11131 (error (message "%s" err))))
11132 (setq js2-mode-pending-parse-callbacks nil)))
11133
11134 (defun js2-mode-flag-region (from to flag)
11135 "Hide or show text from FROM to TO, according to FLAG.
11136 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11137 Returns the created overlay if FLAG is non-nil."
11138 (remove-overlays from to 'invisible 'js2-outline)
11139 (when flag
11140 (let ((o (make-overlay from to)))
11141 (overlay-put o 'invisible 'js2-outline)
11142 (overlay-put o 'isearch-open-invisible
11143 'js2-isearch-open-invisible)
11144 o)))
11145
11146 ;; Function to be set as an outline-isearch-open-invisible' property
11147 ;; to the overlay that makes the outline invisible (see
11148 ;; `js2-mode-flag-region').
11149 (defun js2-isearch-open-invisible (overlay)
11150 ;; We rely on the fact that isearch places point on the matched text.
11151 (js2-mode-show-element))
11152
11153 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11154 "Return cons cell of bounds of folding overlay at POS.
11155 Returns nil if not found."
11156 (let ((overlays (overlays-at (or pos (point))))
11157 o)
11158 (while (and overlays
11159 (not o))
11160 (if (overlay-get (car overlays) 'invisible)
11161 (setq o (car overlays))
11162 (setq overlays (cdr overlays))))
11163 (if o
11164 (cons (overlay-start o) (overlay-end o)))))
11165
11166 (defun js2-mode-function-at-point (&optional pos)
11167 "Return the innermost function node enclosing current point.
11168 Returns nil if point is not in a function."
11169 (let ((node (js2-node-at-point pos)))
11170 (while (and node (not (js2-function-node-p node)))
11171 (setq node (js2-node-parent node)))
11172 (if (js2-function-node-p node)
11173 node)))
11174
11175 (defun js2-mode-toggle-element ()
11176 "Hide or show the foldable element at the point."
11177 (interactive)
11178 (let (comment fn pos)
11179 (save-excursion
11180 (save-match-data
11181 (cond
11182 ;; /* ... */ comment?
11183 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11184 (if (js2-mode-invisible-overlay-bounds
11185 (setq pos (+ 3 (js2-node-abs-pos comment))))
11186 (progn
11187 (goto-char pos)
11188 (js2-mode-show-element))
11189 (js2-mode-hide-element)))
11190 ;; //-comment?
11191 ((save-excursion
11192 (back-to-indentation)
11193 (looking-at js2-mode-//-comment-re))
11194 (js2-mode-toggle-//-comment))
11195 ;; function?
11196 ((setq fn (js2-mode-function-at-point))
11197 (setq pos (and (js2-function-node-body fn)
11198 (js2-node-abs-pos (js2-function-node-body fn))))
11199 (goto-char (1+ pos))
11200 (if (js2-mode-invisible-overlay-bounds)
11201 (js2-mode-show-element)
11202 (js2-mode-hide-element)))
11203 (t
11204 (message "Nothing at point to hide or show")))))))
11205
11206 (defun js2-mode-hide-element ()
11207 "Fold/hide contents of a block, showing ellipses.
11208 Show the hidden text with \\[js2-mode-show-element]."
11209 (interactive)
11210 (if js2-mode-buffer-dirty-p
11211 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11212 (let (node body beg end)
11213 (cond
11214 ((js2-mode-invisible-overlay-bounds)
11215 (message "already hidden"))
11216 (t
11217 (setq node (js2-node-at-point))
11218 (cond
11219 ((js2-block-comment-p node)
11220 (js2-mode-hide-comment node))
11221 (t
11222 (while (and node (not (js2-function-node-p node)))
11223 (setq node (js2-node-parent node)))
11224 (if (and node
11225 (setq body (js2-function-node-body node)))
11226 (progn
11227 (setq beg (js2-node-abs-pos body)
11228 end (+ beg (js2-node-len body)))
11229 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11230 (message "No collapsable element found at point"))))))))
11231
11232 (defun js2-mode-show-element ()
11233 "Show the hidden element at current point."
11234 (interactive)
11235 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11236 (if bounds
11237 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11238 (message "Nothing to un-hide"))))
11239
11240 (defun js2-mode-show-all ()
11241 "Show all of the text in the buffer."
11242 (interactive)
11243 (js2-mode-flag-region (point-min) (point-max) nil))
11244
11245 (defun js2-mode-toggle-hide-functions ()
11246 (interactive)
11247 (if js2-mode-functions-hidden
11248 (js2-mode-show-functions)
11249 (js2-mode-hide-functions)))
11250
11251 (defun js2-mode-hide-functions ()
11252 "Hides all non-nested function bodies in the buffer.
11253 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11254 to open an individual entry."
11255 (interactive)
11256 (if js2-mode-buffer-dirty-p
11257 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11258 (if (null js2-mode-ast)
11259 (message "Oops - parsing failed")
11260 (setq js2-mode-functions-hidden t)
11261 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11262
11263 (defun js2-mode-function-hider (n endp)
11264 (when (not endp)
11265 (let ((tt (js2-node-type n))
11266 body beg end)
11267 (cond
11268 ((and (= tt js2-FUNCTION)
11269 (setq body (js2-function-node-body n)))
11270 (setq beg (js2-node-abs-pos body)
11271 end (+ beg (js2-node-len body)))
11272 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11273 nil) ; don't process children of function
11274 (t
11275 t))))) ; keep processing other AST nodes
11276
11277 (defun js2-mode-show-functions ()
11278 "Un-hide any folded function bodies in the buffer."
11279 (interactive)
11280 (setq js2-mode-functions-hidden nil)
11281 (save-excursion
11282 (goto-char (point-min))
11283 (while (/= (goto-char (next-overlay-change (point)))
11284 (point-max))
11285 (dolist (o (overlays-at (point)))
11286 (when (and (overlay-get o 'invisible)
11287 (not (overlay-get o 'comment)))
11288 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11289
11290 (defun js2-mode-hide-comment (n)
11291 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11292 3 ; /**
11293 2)) ; /*
11294 (beg (+ (js2-node-abs-pos n) head))
11295 (end (- (+ beg (js2-node-len n)) head 2))
11296 (o (js2-mode-flag-region beg end 'hide)))
11297 (overlay-put o 'comment t)))
11298
11299 (defun js2-mode-toggle-hide-comments ()
11300 "Folds all block comments in the buffer.
11301 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11302 to open an individual entry."
11303 (interactive)
11304 (if js2-mode-comments-hidden
11305 (js2-mode-show-comments)
11306 (js2-mode-hide-comments)))
11307
11308 (defun js2-mode-hide-comments ()
11309 (interactive)
11310 (if js2-mode-buffer-dirty-p
11311 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11312 (if (null js2-mode-ast)
11313 (message "Oops - parsing failed")
11314 (setq js2-mode-comments-hidden t)
11315 (dolist (n (js2-ast-root-comments js2-mode-ast))
11316 (let ((format (js2-comment-node-format n)))
11317 (when (js2-block-comment-p n)
11318 (js2-mode-hide-comment n))))
11319 (js2-mode-hide-//-comments)))
11320
11321 (defsubst js2-mode-extend-//-comment (direction)
11322 "Find start or end of a block of similar //-comment lines.
11323 DIRECTION is -1 to look back, 1 to look forward.
11324 INDENT is the indentation level to match.
11325 Returns the end-of-line position of the furthest adjacent
11326 //-comment line with the same indentation as the current line.
11327 If there is no such matching line, returns current end of line."
11328 (let ((pos (point-at-eol))
11329 (indent (current-indentation)))
11330 (save-excursion
11331 (save-match-data
11332 (while (and (zerop (forward-line direction))
11333 (looking-at js2-mode-//-comment-re)
11334 (eq indent (length (match-string 1))))
11335 (setq pos (point-at-eol)))
11336 pos))))
11337
11338 (defun js2-mode-hide-//-comments ()
11339 "Fold adjacent 1-line comments, showing only snippet of first one."
11340 (let (beg end)
11341 (save-excursion
11342 (save-match-data
11343 (goto-char (point-min))
11344 (while (re-search-forward js2-mode-//-comment-re nil t)
11345 (setq beg (point)
11346 end (js2-mode-extend-//-comment 1))
11347 (unless (eq beg end)
11348 (overlay-put (js2-mode-flag-region beg end 'hide)
11349 'comment t))
11350 (goto-char end)
11351 (forward-char 1))))))
11352
11353 (defun js2-mode-toggle-//-comment ()
11354 "Fold or un-fold any multi-line //-comment at point.
11355 Caller should have determined that this line starts with a //-comment."
11356 (let* ((beg (point-at-eol))
11357 (end beg))
11358 (save-excursion
11359 (goto-char end)
11360 (if (js2-mode-invisible-overlay-bounds)
11361 (js2-mode-show-element)
11362 ;; else hide the comment
11363 (setq beg (js2-mode-extend-//-comment -1)
11364 end (js2-mode-extend-//-comment 1))
11365 (unless (eq beg end)
11366 (overlay-put (js2-mode-flag-region beg end 'hide)
11367 'comment t))))))
11368
11369 (defun js2-mode-show-comments ()
11370 "Un-hide any hidden comments, leaving other hidden elements alone."
11371 (interactive)
11372 (setq js2-mode-comments-hidden nil)
11373 (save-excursion
11374 (goto-char (point-min))
11375 (while (/= (goto-char (next-overlay-change (point)))
11376 (point-max))
11377 (dolist (o (overlays-at (point)))
11378 (when (overlay-get o 'comment)
11379 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11380
11381 (defun js2-mode-display-warnings-and-errors ()
11382 "Turn on display of warnings and errors."
11383 (interactive)
11384 (setq js2-mode-show-parse-errors t
11385 js2-mode-show-strict-warnings t)
11386 (js2-reparse 'force))
11387
11388 (defun js2-mode-hide-warnings-and-errors ()
11389 "Turn off display of warnings and errors."
11390 (interactive)
11391 (setq js2-mode-show-parse-errors nil
11392 js2-mode-show-strict-warnings nil)
11393 (js2-reparse 'force))
11394
11395 (defun js2-mode-toggle-warnings-and-errors ()
11396 "Toggle the display of warnings and errors.
11397 Some users don't like having warnings/errors reported while they type."
11398 (interactive)
11399 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11400 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11401 (if (interactive-p)
11402 (message "warnings and errors %s"
11403 (if js2-mode-show-parse-errors
11404 "enabled"
11405 "disabled")))
11406 (js2-reparse 'force))
11407
11408 (defun js2-mode-customize ()
11409 (interactive)
11410 (customize-group 'js2-mode))
11411
11412 (defun js2-mode-forward-sexp (&optional arg)
11413 "Move forward across one statement or balanced expression.
11414 With ARG, do it that many times. Negative arg -N means
11415 move backward across N balanced expressions."
11416 (interactive "p")
11417 (setq arg (or arg 1))
11418 (if js2-mode-buffer-dirty-p
11419 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11420 (let (node end (start (point)))
11421 (cond
11422 ;; backward-sexp
11423 ;; could probably make this better for some cases:
11424 ;; - if in statement block (e.g. function body), go to parent
11425 ;; - infix exprs like (foo in bar) - maybe go to beginning
11426 ;; of infix expr if in the right-side expression?
11427 ((and arg (minusp arg))
11428 (dotimes (i (- arg))
11429 (js2-backward-sws)
11430 (forward-char -1) ; enter the node we backed up to
11431 (setq node (js2-node-at-point (point) t))
11432 (goto-char (if node
11433 (js2-node-abs-pos node)
11434 (point-min)))))
11435 (t
11436 ;; forward-sexp
11437 (js2-forward-sws)
11438 (dotimes (i arg)
11439 (js2-forward-sws)
11440 (setq node (js2-node-at-point (point) t)
11441 end (if node (+ (js2-node-abs-pos node)
11442 (js2-node-len node))))
11443 (goto-char (or end (point-max))))))))
11444
11445 (defun js2-next-error (&optional arg reset)
11446 "Move to next parse error.
11447 Typically invoked via \\[next-error].
11448 ARG is the number of errors, forward or backward, to move.
11449 RESET means start over from the beginning."
11450 (interactive "p")
11451 (if (or (null js2-mode-ast)
11452 (and (null (js2-ast-root-errors js2-mode-ast))
11453 (null (js2-ast-root-warnings js2-mode-ast))))
11454 (message "No errors")
11455 (when reset
11456 (goto-char (point-min)))
11457 (let* ((errs (copy-sequence
11458 (append (js2-ast-root-errors js2-mode-ast)
11459 (js2-ast-root-warnings js2-mode-ast))))
11460 (continue t)
11461 (start (point))
11462 (count (or arg 1))
11463 (backward (minusp count))
11464 (sorter (if backward '> '<))
11465 (stopper (if backward '< '>))
11466 (count (abs count))
11467 all-errs
11468 err)
11469 ;; sort by start position
11470 (setq errs (sort errs (lambda (e1 e2)
11471 (funcall sorter (second e1) (second e2))))
11472 all-errs errs)
11473 ;; find nth error with pos > start
11474 (while (and errs continue)
11475 (when (funcall stopper (cadar errs) start)
11476 (setq err (car errs))
11477 (if (zerop (decf count))
11478 (setq continue nil)))
11479 (setq errs (cdr errs)))
11480 (if err
11481 (goto-char (second err))
11482 ;; wrap around to first error
11483 (goto-char (second (car all-errs)))
11484 ;; if we were already on it, echo msg again
11485 (if (= (point) start)
11486 (js2-echo-error (point) (point)))))))
11487
11488 (defun js2-down-mouse-3 ()
11489 "Make right-click move the point to the click location.
11490 This makes right-click context menu operations a bit more intuitive.
11491 The point will not move if the region is active, however, to avoid
11492 destroying the region selection."
11493 (interactive)
11494 (when (and js2-move-point-on-right-click
11495 (not mark-active))
11496 (let ((e last-input-event))
11497 (ignore-errors
11498 (goto-char (cadadr e))))))
11499
11500 (defun js2-mode-create-imenu-index ()
11501 "Return an alist for `imenu--index-alist'."
11502 ;; This is built up in `js2-parse-record-imenu' during parsing.
11503 (when js2-mode-ast
11504 ;; if we have an ast but no recorder, they're requesting a rescan
11505 (unless js2-imenu-recorder
11506 (js2-reparse 'force))
11507 (prog1
11508 (js2-build-imenu-index)
11509 (setq js2-imenu-recorder nil
11510 js2-imenu-function-map nil))))
11511
11512 (defun js2-mode-find-tag ()
11513 "Replacement for `find-tag-default'.
11514 `find-tag-default' returns a ridiculous answer inside comments."
11515 (let (beg end)
11516 (js2-with-underscore-as-word-syntax
11517 (save-excursion
11518 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11519 (looking-back "[A-Za-z0-9_$]"))
11520 (setq beg (progn (forward-word -1) (point))
11521 end (progn (forward-word 1) (point)))
11522 (setq beg (progn (forward-word 1) (point))
11523 end (progn (forward-word -1) (point))))
11524 (replace-regexp-in-string
11525 "[\"']" ""
11526 (buffer-substring-no-properties beg end))))))
11527
11528 (defun js2-mode-forward-sibling ()
11529 "Move to the end of the sibling following point in parent.
11530 Returns non-nil if successful, or nil if there was no following sibling."
11531 (let* ((node (js2-node-at-point))
11532 (parent (js2-mode-find-enclosing-fn node))
11533 sib)
11534 (when (setq sib (js2-node-find-child-after (point) parent))
11535 (goto-char (+ (js2-node-abs-pos sib)
11536 (js2-node-len sib))))))
11537
11538 (defun js2-mode-backward-sibling ()
11539 "Move to the beginning of the sibling node preceding point in parent.
11540 Parent is defined as the enclosing script or function."
11541 (let* ((node (js2-node-at-point))
11542 (parent (js2-mode-find-enclosing-fn node))
11543 sib)
11544 (when (setq sib (js2-node-find-child-before (point) parent))
11545 (goto-char (js2-node-abs-pos sib)))))
11546
11547 (defun js2-beginning-of-defun (&optional arg)
11548 "Go to line on which current function starts, and return t on success.
11549 If we're not in a function or already at the beginning of one, go
11550 to beginning of previous script-level element.
11551 With ARG N, do that N times. If N is negative, move forward."
11552 (setq arg (or arg 1))
11553 (if (plusp arg)
11554 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11555 (when (cond
11556 ((js2-function-node-p parent)
11557 (goto-char (js2-node-abs-pos parent)))
11558 (t
11559 (js2-mode-backward-sibling)))
11560 (if (> arg 1)
11561 (js2-beginning-of-defun (1- arg))
11562 t)))
11563 (when (js2-end-of-defun)
11564 (if (>= arg -1)
11565 (js2-beginning-of-defun 1)
11566 (js2-beginning-of-defun (1+ arg))))))
11567
11568 (defun js2-end-of-defun ()
11569 "Go to the char after the last position of the current function
11570 or script-level element."
11571 (let* ((node (js2-node-at-point))
11572 (parent (or (and (js2-function-node-p node) node)
11573 (js2-node-parent-script-or-fn node)))
11574 script)
11575 (unless (js2-function-node-p parent)
11576 ;; use current script-level node, or, if none, the next one
11577 (setq script (or parent node))
11578 (setq parent (js2-node-find-child-before (point) script))
11579 (when (or (null parent)
11580 (>= (point) (+ (js2-node-abs-pos parent)
11581 (js2-node-len parent))))
11582 (setq parent (js2-node-find-child-after (point) script))))
11583 (when parent
11584 (goto-char (+ (js2-node-abs-pos parent)
11585 (js2-node-len parent))))))
11586
11587 (defun js2-mark-defun (&optional allow-extend)
11588 "Put mark at end of this function, point at beginning.
11589 The function marked is the one that contains point.
11590
11591 Interactively, if this command is repeated,
11592 or (in Transient Mark mode) if the mark is active,
11593 it marks the next defun after the ones already marked."
11594 (interactive "p")
11595 (let (extended)
11596 (when (and allow-extend
11597 (or (and (eq last-command this-command) (mark t))
11598 (and transient-mark-mode mark-active)))
11599 (let ((sib (save-excursion
11600 (goto-char (mark))
11601 (if (js2-mode-forward-sibling)
11602 (point))))
11603 node)
11604 (if sib
11605 (progn
11606 (set-mark sib)
11607 (setq extended t))
11608 ;; no more siblings - try extending to enclosing node
11609 (goto-char (mark t)))))
11610 (when (not extended)
11611 (let ((node (js2-node-at-point (point) t)) ; skip comments
11612 ast fn stmt parent beg end)
11613 (when (js2-ast-root-p node)
11614 (setq ast node
11615 node (or (js2-node-find-child-after (point) node)
11616 (js2-node-find-child-before (point) node))))
11617 ;; only mark whole buffer if we can't find any children
11618 (if (null node)
11619 (setq node ast))
11620 (if (js2-function-node-p node)
11621 (setq parent node)
11622 (setq fn (js2-mode-find-enclosing-fn node)
11623 stmt (if (or (null fn)
11624 (js2-ast-root-p fn))
11625 (js2-mode-find-first-stmt node))
11626 parent (or stmt fn)))
11627 (setq beg (js2-node-abs-pos parent)
11628 end (+ beg (js2-node-len parent)))
11629 (push-mark beg)
11630 (goto-char end)
11631 (exchange-point-and-mark)))))
11632
11633 (defun js2-narrow-to-defun ()
11634 "Narrow to the function enclosing point."
11635 (interactive)
11636 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11637 (fn (if (js2-script-node-p node)
11638 node
11639 (js2-mode-find-enclosing-fn node)))
11640 (beg (js2-node-abs-pos fn)))
11641 (unless (js2-ast-root-p fn)
11642 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11643
11644 (provide 'js2-mode)
11645
11646 ;;; js2-mode.el ends here