]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Show keybindings in the mode description
[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-TRIPLEDOT 162) ; for rest parameter
679
680 (defconst js2-num-tokens (1+ js2-TRIPLEDOT))
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 (js2-deflocal js2-is-in-destructuring nil
822 "True while parsing destructuring expression.")
823
824 (defcustom js2-global-externs nil
825 "A list of any extern names you'd like to consider always declared.
826 This list is global and is used by all js2-mode files.
827 You can create buffer-local externs list using `js2-additional-externs'.
828
829 There is also a buffer-local variable `js2-default-externs',
830 which is initialized by default to include the Ecma-262 externs
831 and the standard browser externs. The three lists are all
832 checked during highlighting."
833 :type 'list
834 :group 'js2-mode)
835
836 (js2-deflocal js2-default-externs nil
837 "Default external declarations.
838
839 These are currently only used for highlighting undeclared variables,
840 which only worries about top-level (unqualified) references.
841 As js2-mode's processing improves, we will flesh out this list.
842
843 The initial value is set to `js2-ecma-262-externs', unless you
844 have set `js2-include-browser-externs', in which case the browser
845 externs are also included.
846
847 See `js2-additional-externs' for more information.")
848
849 (defcustom js2-include-browser-externs t
850 "Non-nil to include browser externs in the master externs list.
851 If you work on JavaScript files that are not intended for browsers,
852 such as Mozilla Rhino server-side JavaScript, set this to nil.
853 You can always include them on a per-file basis by calling
854 `js2-add-browser-externs' from a function on `js2-mode-hook'.
855
856 See `js2-additional-externs' for more information about externs."
857 :type 'boolean
858 :group 'js2-mode)
859
860 (defcustom js2-include-rhino-externs t
861 "Non-nil to include Mozilla Rhino externs in the master externs list.
862 See `js2-additional-externs' for more information about externs."
863 :type 'boolean
864 :group 'js2-mode)
865
866 (defcustom js2-include-gears-externs t
867 "Non-nil to include Google Gears externs in the master externs list.
868 See `js2-additional-externs' for more information about externs."
869 :type 'boolean
870 :group 'js2-mode)
871
872 (js2-deflocal js2-additional-externs nil
873 "A buffer-local list of additional external declarations.
874 It is used to decide whether variables are considered undeclared
875 for purposes of highlighting.
876
877 Each entry is a lisp string. The string should be the fully qualified
878 name of an external entity. All externs should be added to this list,
879 so that as js2-mode's processing improves it can take advantage of them.
880
881 You may want to declare your externs in three ways.
882 First, you can add externs that are valid for all your JavaScript files.
883 You should probably do this by adding them to `js2-global-externs', which
884 is a global list used for all js2-mode files.
885
886 Next, you can add a function to `js2-mode-hook' that adds additional
887 externs appropriate for the specific file, perhaps based on its path.
888 These should go in `js2-additional-externs', which is buffer-local.
889
890 Finally, you can add a function to `js2-post-parse-callbacks',
891 which is called after parsing completes, and `root' is bound to
892 the root of the parse tree. At this stage you can set up an AST
893 node visitor using `js2-visit-ast' and examine the parse tree
894 for specific import patterns that may imply the existence of
895 other externs, possibly tied to your build system. These should also
896 be added to `js2-additional-externs'.
897
898 Your post-parse callback may of course also use the simpler and
899 faster (but perhaps less robust) approach of simply scanning the
900 buffer text for your imports, using regular expressions.")
901
902 ;; SKIP: decompiler
903 ;; SKIP: encoded-source
904
905 ;;; The following variables are per-function and should be saved/restored
906 ;;; during function parsing...
907
908 (js2-deflocal js2-current-script-or-fn nil)
909 (js2-deflocal js2-current-scope nil)
910 (js2-deflocal js2-nesting-of-with 0)
911 (js2-deflocal js2-label-set nil
912 "An alist mapping label names to nodes.")
913
914 (js2-deflocal js2-loop-set nil)
915 (js2-deflocal js2-loop-and-switch-set nil)
916 (js2-deflocal js2-has-return-value nil)
917 (js2-deflocal js2-end-flags 0)
918
919 ;;; ...end of per function variables
920
921 ;; Without 2-token lookahead, labels are a problem.
922 ;; These vars store the token info of the last matched name,
923 ;; iff it wasn't the last matched token. Only valid in some contexts.
924 (defvar js2-prev-name-token-start nil)
925 (defvar js2-prev-name-token-string nil)
926
927 (defsubst js2-save-name-token-data (pos name)
928 (setq js2-prev-name-token-start pos
929 js2-prev-name-token-string name))
930
931 ;; These flags enumerate the possible ways a statement/function can
932 ;; terminate. These flags are used by endCheck() and by the Parser to
933 ;; detect inconsistent return usage.
934 ;;
935 ;; END_UNREACHED is reserved for code paths that are assumed to always be
936 ;; able to execute (example: throw, continue)
937 ;;
938 ;; END_DROPS_OFF indicates if the statement can transfer control to the
939 ;; next one. Statement such as return dont. A compound statement may have
940 ;; some branch that drops off control to the next statement.
941 ;;
942 ;; END_RETURNS indicates that the statement can return (without arguments)
943 ;; END_RETURNS_VALUE indicates that the statement can return a value.
944 ;;
945 ;; A compound statement such as
946 ;; if (condition) {
947 ;; return value;
948 ;; }
949 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
950
951 (defconst js2-end-unreached #x0)
952 (defconst js2-end-drops-off #x1)
953 (defconst js2-end-returns #x2)
954 (defconst js2-end-returns-value #x4)
955 (defconst js2-end-yields #x8)
956
957 ;; Rhino awkwardly passes a statementLabel parameter to the
958 ;; statementHelper() function, the main statement parser, which
959 ;; is then used by quite a few of the sub-parsers. We just make
960 ;; it a buffer-local variable and make sure it's cleaned up properly.
961 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
962
963 ;; Similarly, Rhino passes an inForInit boolean through about half
964 ;; the expression parsers. We use a dynamically-scoped variable,
965 ;; which makes it easier to funcall the parsers individually without
966 ;; worrying about whether they take the parameter or not.
967 (js2-deflocal js2-in-for-init nil)
968 (js2-deflocal js2-temp-name-counter 0)
969 (js2-deflocal js2-parse-stmt-count 0)
970
971 (defsubst js2-get-next-temp-name ()
972 (format "$%d" (incf js2-temp-name-counter)))
973
974 (defvar js2-parse-interruptable-p t
975 "Set this to nil to force parse to continue until finished.
976 This will mostly be useful for interpreters.")
977
978 (defvar js2-statements-per-pause 50
979 "Pause after this many statements to check for user input.
980 If user input is pending, stop the parse and discard the tree.
981 This makes for a smoother user experience for large files.
982 You may have to wait a second or two before the highlighting
983 and error-reporting appear, but you can always type ahead if
984 you wish. This appears to be more or less how Eclipse, IntelliJ
985 and other editors work.")
986
987 (js2-deflocal js2-record-comments t
988 "Instructs the scanner to record comments in `js2-scanned-comments'.")
989
990 (js2-deflocal js2-scanned-comments nil
991 "List of all comments from the current parse.")
992
993 (defcustom js2-mode-indent-inhibit-undo nil
994 "Non-nil to disable collection of Undo information when indenting lines.
995 Some users have requested this behavior. It's nil by default because
996 other Emacs modes don't work this way."
997 :type 'boolean
998 :group 'js2-mode)
999
1000 (defcustom js2-mode-indent-ignore-first-tab nil
1001 "If non-nil, ignore first TAB keypress if we look indented properly.
1002 It's fairly common for users to navigate to an already-indented line
1003 and press TAB for reassurance that it's been indented. For this class
1004 of users, we want the first TAB press on a line to be ignored if the
1005 line is already indented to one of the precomputed alternatives.
1006
1007 This behavior is only partly implemented. If you TAB-indent a line,
1008 navigate to another line, and then navigate back, it fails to clear
1009 the last-indented variable, so it thinks you've already hit TAB once,
1010 and performs the indent. A full solution would involve getting on the
1011 point-motion hooks for the entire buffer. If we come across another
1012 use cases that requires watching point motion, I'll consider doing it.
1013
1014 If you set this variable to nil, then the TAB key will always change
1015 the indentation of the current line, if more than one alternative
1016 indentation spot exists."
1017 :type 'boolean
1018 :group 'js2-mode)
1019
1020 (defvar js2-indent-hook nil
1021 "A hook for user-defined indentation rules.
1022
1023 Functions on this hook should expect two arguments: (LIST INDEX)
1024 The LIST argument is the list of computed indentation points for
1025 the current line. INDEX is the list index of the indentation point
1026 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1027 indent function is not going to change the current line indentation.
1028
1029 If a hook function on this list returns a non-nil value, then
1030 `js2-bounce-indent' assumes the hook function has performed its own
1031 indentation, and will do nothing. If all hook functions on the list
1032 return nil, then `js2-bounce-indent' will use its computed indentation
1033 and reindent the line.
1034
1035 When hook functions on this hook list are called, the variable
1036 `js2-mode-ast' may or may not be set, depending on whether the
1037 parse tree is available. If the variable is nil, you can pass a
1038 callback to `js2-mode-wait-for-parse', and your callback will be
1039 called after the new parse tree is built. This can take some time
1040 in large files.")
1041
1042 (defface js2-warning-face
1043 `((((class color) (background light))
1044 (:underline "orange"))
1045 (((class color) (background dark))
1046 (:underline "orange"))
1047 (t (:underline t)))
1048 "Face for JavaScript warnings."
1049 :group 'js2-mode)
1050
1051 (defface js2-error-face
1052 `((((class color) (background light))
1053 (:foreground "red"))
1054 (((class color) (background dark))
1055 (:foreground "red"))
1056 (t (:foreground "red")))
1057 "Face for JavaScript errors."
1058 :group 'js2-mode)
1059
1060 (defface js2-jsdoc-tag-face
1061 '((t :foreground "SlateGray"))
1062 "Face used to highlight @whatever tags in jsdoc comments."
1063 :group 'js2-mode)
1064
1065 (defface js2-jsdoc-type-face
1066 '((t :foreground "SteelBlue"))
1067 "Face used to highlight {FooBar} types in jsdoc comments."
1068 :group 'js2-mode)
1069
1070 (defface js2-jsdoc-value-face
1071 '((t :foreground "PeachPuff3"))
1072 "Face used to highlight tag values in jsdoc comments."
1073 :group 'js2-mode)
1074
1075 (defface js2-function-param-face
1076 '((t :foreground "SeaGreen"))
1077 "Face used to highlight function parameters in javascript."
1078 :group 'js2-mode)
1079
1080 (defface js2-instance-member-face
1081 '((t :foreground "DarkOrchid"))
1082 "Face used to highlight instance variables in javascript.
1083 Not currently used."
1084 :group 'js2-mode)
1085
1086 (defface js2-private-member-face
1087 '((t :foreground "PeachPuff3"))
1088 "Face used to highlight calls to private methods in javascript.
1089 Not currently used."
1090 :group 'js2-mode)
1091
1092 (defface js2-private-function-call-face
1093 '((t :foreground "goldenrod"))
1094 "Face used to highlight calls to private functions in javascript.
1095 Not currently used."
1096 :group 'js2-mode)
1097
1098 (defface js2-jsdoc-html-tag-name-face
1099 (if js2-emacs22
1100 '((((class color) (min-colors 88) (background light))
1101 (:foreground "rosybrown"))
1102 (((class color) (min-colors 8) (background dark))
1103 (:foreground "yellow"))
1104 (((class color) (min-colors 8) (background light))
1105 (:foreground "magenta")))
1106 '((((type tty pc) (class color) (background light))
1107 (:foreground "magenta"))
1108 (((type tty pc) (class color) (background dark))
1109 (:foreground "yellow"))
1110 (t (:foreground "RosyBrown"))))
1111 "Face used to highlight jsdoc html tag names"
1112 :group 'js2-mode)
1113
1114 (defface js2-jsdoc-html-tag-delimiter-face
1115 (if js2-emacs22
1116 '((((class color) (min-colors 88) (background light))
1117 (:foreground "dark khaki"))
1118 (((class color) (min-colors 8) (background dark))
1119 (:foreground "green"))
1120 (((class color) (min-colors 8) (background light))
1121 (:foreground "green")))
1122 '((((type tty pc) (class color) (background light))
1123 (:foreground "green"))
1124 (((type tty pc) (class color) (background dark))
1125 (:foreground "green"))
1126 (t (:foreground "dark khaki"))))
1127 "Face used to highlight brackets in jsdoc html tags."
1128 :group 'js2-mode)
1129
1130 (defface js2-magic-paren-face
1131 '((t :underline t))
1132 "Face used to color parens that will be auto-overwritten."
1133 :group 'js2-mode)
1134
1135 (defcustom js2-post-parse-callbacks nil
1136 "A list of callback functions invoked after parsing finishes.
1137 Currently, the main use for this function is to add synthetic
1138 declarations to `js2-recorded-identifiers', which see."
1139 :type 'list
1140 :group 'js2-mode)
1141
1142 (defface js2-external-variable-face
1143 '((t :foreground "orange"))
1144 "Face used to highlight undeclared variable identifiers.
1145 An undeclared variable is any variable not declared with var or let
1146 in the current scope or any lexically enclosing scope. If you use
1147 such a variable, then you are either expecting it to originate from
1148 another file, or you've got a potential bug."
1149 :group 'js2-mode)
1150
1151 (defcustom js2-highlight-external-variables t
1152 "Non-nil to highlight undeclared variable identifiers."
1153 :type 'boolean
1154 :group 'js2-mode)
1155
1156 (defcustom js2-auto-insert-catch-block t
1157 "Non-nil to insert matching catch block on open-curly after `try'."
1158 :type 'boolean
1159 :group 'js2-mode)
1160
1161 (defvar js2-mode-map
1162 (let ((map (make-sparse-keymap))
1163 keys)
1164 (define-key map [mouse-1] #'js2-mode-show-node)
1165 (define-key map (kbd "C-m") #'js2-enter-key)
1166 (when js2-rebind-eol-bol-keys
1167 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1168 (define-key map (kbd "C-e") #'js2-end-of-line))
1169 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1170 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1171 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1172 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1173 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1174 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1175 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1176 (define-key map (kbd "C-c C-`") #'js2-next-error)
1177 ;; also define user's preference for next-error, if available
1178 (if (setq keys (where-is-internal #'next-error))
1179 (define-key map (car keys) #'js2-next-error))
1180 (define-key map (or (car (where-is-internal #'mark-defun))
1181 (kbd "M-C-h"))
1182 #'js2-mark-defun)
1183 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1184 (kbd "C-x nd"))
1185 #'js2-narrow-to-defun)
1186 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1187 (when js2-auto-indent-p
1188 (mapc (lambda (key)
1189 (define-key map key #'js2-insert-and-indent))
1190 js2-electric-keys))
1191 (when js2-bounce-indent-p
1192 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1193
1194 (define-key map [menu-bar javascript]
1195 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1196
1197 (define-key map [menu-bar javascript customize-js2-mode]
1198 '(menu-item "Customize js2-mode" js2-mode-customize
1199 :help "Customize the behavior of this mode"))
1200
1201 (define-key map [menu-bar javascript js2-force-refresh]
1202 '(menu-item "Force buffer refresh" js2-mode-reset
1203 :help "Re-parse the buffer from scratch"))
1204
1205 (define-key map [menu-bar javascript separator-2]
1206 '("--"))
1207
1208 (define-key map [menu-bar javascript next-error]
1209 '(menu-item "Next warning or error" js2-next-error
1210 :enabled (and js2-mode-ast
1211 (or (js2-ast-root-errors js2-mode-ast)
1212 (js2-ast-root-warnings js2-mode-ast)))
1213 :help "Move to next warning or error"))
1214
1215 (define-key map [menu-bar javascript display-errors]
1216 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1217 :visible (not js2-mode-show-parse-errors)
1218 :help "Turn on display of warnings and errors"))
1219
1220 (define-key map [menu-bar javascript hide-errors]
1221 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1222 :visible js2-mode-show-parse-errors
1223 :help "Turn off display of warnings and errors"))
1224
1225 (define-key map [menu-bar javascript separator-1]
1226 '("--"))
1227
1228 (define-key map [menu-bar javascript js2-toggle-function]
1229 '(menu-item "Show/collapse element" js2-mode-toggle-element
1230 :help "Hide or show function body or comment"))
1231
1232 (define-key map [menu-bar javascript show-comments]
1233 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1234 :visible js2-mode-comments-hidden
1235 :help "Expand all hidden block comments"))
1236
1237 (define-key map [menu-bar javascript hide-comments]
1238 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1239 :visible (not js2-mode-comments-hidden)
1240 :help "Show block comments as /*...*/"))
1241
1242 (define-key map [menu-bar javascript show-all-functions]
1243 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1244 :visible js2-mode-functions-hidden
1245 :help "Expand all hidden function bodies"))
1246
1247 (define-key map [menu-bar javascript hide-all-functions]
1248 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1249 :visible (not js2-mode-functions-hidden)
1250 :help "Show {...} for all top-level function bodies"))
1251
1252 map)
1253 "Keymap used in `js2-mode' buffers.")
1254
1255 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1256
1257 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1258 "Matches a //-comment line. Must be first non-whitespace on line.
1259 First match-group is the leading whitespace.")
1260
1261 (defvar js2-mode-hook nil)
1262
1263 (js2-deflocal js2-mode-ast nil "Private variable.")
1264 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1265 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1266 (js2-deflocal js2-mode-parsing nil "Private variable.")
1267 (js2-deflocal js2-mode-node-overlay nil)
1268
1269 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1270 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1271
1272 (js2-deflocal js2-mode-fontifications nil "Private variable")
1273 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1274 (js2-deflocal js2-imenu-recorder nil "Private variable")
1275 (js2-deflocal js2-imenu-function-map nil "Private variable")
1276
1277 (defvar js2-paragraph-start
1278 "\\(@[a-zA-Z]+\\>\\|$\\)")
1279
1280 ;; Note that we also set a 'c-in-sws text property in html comments,
1281 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1282 (defvar js2-syntactic-ws-start
1283 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1284
1285 (defvar js2-syntactic-ws-end
1286 "\\s \\|[\n\r/]\\|\\s!")
1287
1288 (defvar js2-syntactic-eol
1289 (concat "\\s *\\(/\\*[^*\n\r]*"
1290 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1291 "\\*+/\\s *\\)*"
1292 "\\(//\\|/\\*[^*\n\r]*"
1293 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1294 "\\|\\\\$\\|$\\)")
1295 "Copied from `java-mode'. Needed for some cc-engine functions.")
1296
1297 (defvar js2-comment-prefix-regexp
1298 "//+\\|\\**")
1299
1300 (defvar js2-comment-start-skip
1301 "\\(//+\\|/\\*+\\)\\s *")
1302
1303 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1304 "Non-nil to emit status messages during parsing.")
1305
1306 (defvar js2-mode-functions-hidden nil "private variable")
1307 (defvar js2-mode-comments-hidden nil "private variable")
1308
1309 (defvar js2-mode-syntax-table
1310 (let ((table (make-syntax-table)))
1311 (c-populate-syntax-table table)
1312 table)
1313 "Syntax table used in js2-mode buffers.")
1314
1315 (defvar js2-mode-abbrev-table nil
1316 "Abbrev table in use in `js2-mode' buffers.")
1317 (define-abbrev-table 'js2-mode-abbrev-table ())
1318
1319 (defvar js2-mode-pending-parse-callbacks nil
1320 "List of functions waiting to be notified that parse is finished.")
1321
1322 (defvar js2-mode-last-indented-line -1)
1323
1324 ;;; Localizable error and warning messages
1325
1326 ;; Messages are copied from Rhino's Messages.properties.
1327 ;; Many of the Java-specific messages have been elided.
1328 ;; Add any js2-specific ones at the end, so we can keep
1329 ;; this file synced with changes to Rhino's.
1330
1331 (defvar js2-message-table
1332 (make-hash-table :test 'equal :size 250)
1333 "Contains localized messages for js2-mode.")
1334
1335 ;; TODO(stevey): construct this table at compile-time.
1336 (defmacro js2-msg (key &rest strings)
1337 `(puthash ,key (funcall #'concat ,@strings)
1338 js2-message-table))
1339
1340 (defun js2-get-msg (msg-key)
1341 "Look up a localized message.
1342 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1343 the correct number of ARGS must be provided."
1344 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1345 (args (if (listp msg-key) (cdr msg-key)))
1346 (msg (gethash key js2-message-table)))
1347 (if msg
1348 (apply #'format msg args)
1349 key))) ; default to showing the key
1350
1351 (js2-msg "msg.dup.parms"
1352 "Duplicate parameter name '%s'.")
1353
1354 (js2-msg "msg.too.big.jump"
1355 "Program too complex: jump offset too big.")
1356
1357 (js2-msg "msg.too.big.index"
1358 "Program too complex: internal index exceeds 64K limit.")
1359
1360 (js2-msg "msg.while.compiling.fn"
1361 "Encountered code generation error while compiling function '%s': %s")
1362
1363 (js2-msg "msg.while.compiling.script"
1364 "Encountered code generation error while compiling script: %s")
1365
1366 ;; Context
1367 (js2-msg "msg.ctor.not.found"
1368 "Constructor for '%s' not found.")
1369
1370 (js2-msg "msg.not.ctor"
1371 "'%s' is not a constructor.")
1372
1373 ;; FunctionObject
1374 (js2-msg "msg.varargs.ctor"
1375 "Method or constructor '%s' must be static "
1376 "with the signature (Context cx, Object[] args, "
1377 "Function ctorObj, boolean inNewExpr) "
1378 "to define a variable arguments constructor.")
1379
1380 (js2-msg "msg.varargs.fun"
1381 "Method '%s' must be static with the signature "
1382 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1383 "to define a variable arguments function.")
1384
1385 (js2-msg "msg.incompat.call"
1386 "Method '%s' called on incompatible object.")
1387
1388 (js2-msg "msg.bad.parms"
1389 "Unsupported parameter type '%s' in method '%s'.")
1390
1391 (js2-msg "msg.bad.method.return"
1392 "Unsupported return type '%s' in method '%s'.")
1393
1394 (js2-msg "msg.bad.ctor.return"
1395 "Construction of objects of type '%s' is not supported.")
1396
1397 (js2-msg "msg.no.overload"
1398 "Method '%s' occurs multiple times in class '%s'.")
1399
1400 (js2-msg "msg.method.not.found"
1401 "Method '%s' not found in '%s'.")
1402
1403 ;; IRFactory
1404
1405 (js2-msg "msg.bad.for.in.lhs"
1406 "Invalid left-hand side of for..in loop.")
1407
1408 (js2-msg "msg.mult.index"
1409 "Only one variable allowed in for..in loop.")
1410
1411 (js2-msg "msg.bad.for.in.destruct"
1412 "Left hand side of for..in loop must be an array of "
1413 "length 2 to accept key/value pair.")
1414
1415 (js2-msg "msg.cant.convert"
1416 "Can't convert to type '%s'.")
1417
1418 (js2-msg "msg.bad.assign.left"
1419 "Invalid assignment left-hand side.")
1420
1421 (js2-msg "msg.bad.decr"
1422 "Invalid decerement operand.")
1423
1424 (js2-msg "msg.bad.incr"
1425 "Invalid increment operand.")
1426
1427 (js2-msg "msg.bad.yield"
1428 "yield must be in a function.")
1429
1430 (js2-msg "msg.yield.parenthesized"
1431 "yield expression must be parenthesized.")
1432
1433 ;; NativeGlobal
1434 (js2-msg "msg.cant.call.indirect"
1435 "Function '%s' must be called directly, and not by way of a "
1436 "function of another name.")
1437
1438 (js2-msg "msg.eval.nonstring"
1439 "Calling eval() with anything other than a primitive "
1440 "string value will simply return the value. "
1441 "Is this what you intended?")
1442
1443 (js2-msg "msg.eval.nonstring.strict"
1444 "Calling eval() with anything other than a primitive "
1445 "string value is not allowed in strict mode.")
1446
1447 (js2-msg "msg.bad.destruct.op"
1448 "Invalid destructuring assignment operator")
1449
1450 ;; NativeCall
1451 (js2-msg "msg.only.from.new"
1452 "'%s' may only be invoked from a `new' expression.")
1453
1454 (js2-msg "msg.deprec.ctor"
1455 "The '%s' constructor is deprecated.")
1456
1457 ;; NativeFunction
1458 (js2-msg "msg.no.function.ref.found"
1459 "no source found to decompile function reference %s")
1460
1461 (js2-msg "msg.arg.isnt.array"
1462 "second argument to Function.prototype.apply must be an array")
1463
1464 ;; NativeGlobal
1465 (js2-msg "msg.bad.esc.mask"
1466 "invalid string escape mask")
1467
1468 ;; NativeRegExp
1469 (js2-msg "msg.bad.quant"
1470 "Invalid quantifier %s")
1471
1472 (js2-msg "msg.overlarge.backref"
1473 "Overly large back reference %s")
1474
1475 (js2-msg "msg.overlarge.min"
1476 "Overly large minimum %s")
1477
1478 (js2-msg "msg.overlarge.max"
1479 "Overly large maximum %s")
1480
1481 (js2-msg "msg.zero.quant"
1482 "Zero quantifier %s")
1483
1484 (js2-msg "msg.max.lt.min"
1485 "Maximum %s less than minimum")
1486
1487 (js2-msg "msg.unterm.quant"
1488 "Unterminated quantifier %s")
1489
1490 (js2-msg "msg.unterm.paren"
1491 "Unterminated parenthetical %s")
1492
1493 (js2-msg "msg.unterm.class"
1494 "Unterminated character class %s")
1495
1496 (js2-msg "msg.bad.range"
1497 "Invalid range in character class.")
1498
1499 (js2-msg "msg.trail.backslash"
1500 "Trailing \\ in regular expression.")
1501
1502 (js2-msg "msg.re.unmatched.right.paren"
1503 "unmatched ) in regular expression.")
1504
1505 (js2-msg "msg.no.regexp"
1506 "Regular expressions are not available.")
1507
1508 (js2-msg "msg.bad.backref"
1509 "back-reference exceeds number of capturing parentheses.")
1510
1511 (js2-msg "msg.bad.regexp.compile"
1512 "Only one argument may be specified if the first "
1513 "argument to RegExp.prototype.compile is a RegExp object.")
1514
1515 ;; Parser
1516 (js2-msg "msg.got.syntax.errors"
1517 "Compilation produced %s syntax errors.")
1518
1519 (js2-msg "msg.var.redecl"
1520 "TypeError: redeclaration of var %s.")
1521
1522 (js2-msg "msg.const.redecl"
1523 "TypeError: redeclaration of const %s.")
1524
1525 (js2-msg "msg.let.redecl"
1526 "TypeError: redeclaration of variable %s.")
1527
1528 (js2-msg "msg.parm.redecl"
1529 "TypeError: redeclaration of formal parameter %s.")
1530
1531 (js2-msg "msg.fn.redecl"
1532 "TypeError: redeclaration of function %s.")
1533
1534 (js2-msg "msg.let.decl.not.in.block"
1535 "SyntaxError: let declaration not directly within block")
1536
1537 ;; NodeTransformer
1538 (js2-msg "msg.dup.label"
1539 "duplicated label")
1540
1541 (js2-msg "msg.undef.label"
1542 "undefined label")
1543
1544 (js2-msg "msg.bad.break"
1545 "unlabelled break must be inside loop or switch")
1546
1547 (js2-msg "msg.continue.outside"
1548 "continue must be inside loop")
1549
1550 (js2-msg "msg.continue.nonloop"
1551 "continue can only use labels of iteration statements")
1552
1553 (js2-msg "msg.bad.throw.eol"
1554 "Line terminator is not allowed between the throw "
1555 "keyword and throw expression.")
1556
1557 (js2-msg "msg.no.paren.parms"
1558 "missing ( before function parameters.")
1559
1560 (js2-msg "msg.no.parm"
1561 "missing formal parameter")
1562
1563 (js2-msg "msg.no.paren.after.parms"
1564 "missing ) after formal parameters")
1565
1566 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1567 "parameter without default follows parameter with default")
1568
1569 (js2-msg "msg.param.after.rest" ; added by js2-mode
1570 "parameter after rest parameter")
1571
1572 (js2-msg "msg.no.brace.body"
1573 "missing '{' before function body")
1574
1575 (js2-msg "msg.no.brace.after.body"
1576 "missing } after function body")
1577
1578 (js2-msg "msg.no.paren.cond"
1579 "missing ( before condition")
1580
1581 (js2-msg "msg.no.paren.after.cond"
1582 "missing ) after condition")
1583
1584 (js2-msg "msg.no.semi.stmt"
1585 "missing ; before statement")
1586
1587 (js2-msg "msg.missing.semi"
1588 "missing ; after statement")
1589
1590 (js2-msg "msg.no.name.after.dot"
1591 "missing name after . operator")
1592
1593 (js2-msg "msg.no.name.after.coloncolon"
1594 "missing name after :: operator")
1595
1596 (js2-msg "msg.no.name.after.dotdot"
1597 "missing name after .. operator")
1598
1599 (js2-msg "msg.no.name.after.xmlAttr"
1600 "missing name after .@")
1601
1602 (js2-msg "msg.no.bracket.index"
1603 "missing ] in index expression")
1604
1605 (js2-msg "msg.no.paren.switch"
1606 "missing ( before switch expression")
1607
1608 (js2-msg "msg.no.paren.after.switch"
1609 "missing ) after switch expression")
1610
1611 (js2-msg "msg.no.brace.switch"
1612 "missing '{' before switch body")
1613
1614 (js2-msg "msg.bad.switch"
1615 "invalid switch statement")
1616
1617 (js2-msg "msg.no.colon.case"
1618 "missing : after case expression")
1619
1620 (js2-msg "msg.double.switch.default"
1621 "double default label in the switch statement")
1622
1623 (js2-msg "msg.no.while.do"
1624 "missing while after do-loop body")
1625
1626 (js2-msg "msg.no.paren.for"
1627 "missing ( after for")
1628
1629 (js2-msg "msg.no.semi.for"
1630 "missing ; after for-loop initializer")
1631
1632 (js2-msg "msg.no.semi.for.cond"
1633 "missing ; after for-loop condition")
1634
1635 (js2-msg "msg.in.after.for.name"
1636 "missing in or of after for")
1637
1638 (js2-msg "msg.no.paren.for.ctrl"
1639 "missing ) after for-loop control")
1640
1641 (js2-msg "msg.no.paren.with"
1642 "missing ( before with-statement object")
1643
1644 (js2-msg "msg.no.paren.after.with"
1645 "missing ) after with-statement object")
1646
1647 (js2-msg "msg.no.paren.after.let"
1648 "missing ( after let")
1649
1650 (js2-msg "msg.no.paren.let"
1651 "missing ) after variable list")
1652
1653 (js2-msg "msg.no.curly.let"
1654 "missing } after let statement")
1655
1656 (js2-msg "msg.bad.return"
1657 "invalid return")
1658
1659 (js2-msg "msg.no.brace.block"
1660 "missing } in compound statement")
1661
1662 (js2-msg "msg.bad.label"
1663 "invalid label")
1664
1665 (js2-msg "msg.bad.var"
1666 "missing variable name")
1667
1668 (js2-msg "msg.bad.var.init"
1669 "invalid variable initialization")
1670
1671 (js2-msg "msg.no.colon.cond"
1672 "missing : in conditional expression")
1673
1674 (js2-msg "msg.no.paren.arg"
1675 "missing ) after argument list")
1676
1677 (js2-msg "msg.no.bracket.arg"
1678 "missing ] after element list")
1679
1680 (js2-msg "msg.bad.prop"
1681 "invalid property id")
1682
1683 (js2-msg "msg.no.colon.prop"
1684 "missing : after property id")
1685
1686 (js2-msg "msg.no.brace.prop"
1687 "missing } after property list")
1688
1689 (js2-msg "msg.no.paren"
1690 "missing ) in parenthetical")
1691
1692 (js2-msg "msg.reserved.id"
1693 "identifier is a reserved word")
1694
1695 (js2-msg "msg.no.paren.catch"
1696 "missing ( before catch-block condition")
1697
1698 (js2-msg "msg.bad.catchcond"
1699 "invalid catch block condition")
1700
1701 (js2-msg "msg.catch.unreachable"
1702 "any catch clauses following an unqualified catch are unreachable")
1703
1704 (js2-msg "msg.no.brace.try"
1705 "missing '{' before try block")
1706
1707 (js2-msg "msg.no.brace.catchblock"
1708 "missing '{' before catch-block body")
1709
1710 (js2-msg "msg.try.no.catchfinally"
1711 "'try' without 'catch' or 'finally'")
1712
1713 (js2-msg "msg.no.return.value"
1714 "function %s does not always return a value")
1715
1716 (js2-msg "msg.anon.no.return.value"
1717 "anonymous function does not always return a value")
1718
1719 (js2-msg "msg.return.inconsistent"
1720 "return statement is inconsistent with previous usage")
1721
1722 (js2-msg "msg.generator.returns"
1723 "TypeError: generator function '%s' returns a value")
1724
1725 (js2-msg "msg.anon.generator.returns"
1726 "TypeError: anonymous generator function returns a value")
1727
1728 (js2-msg "msg.syntax"
1729 "syntax error")
1730
1731 (js2-msg "msg.unexpected.eof"
1732 "Unexpected end of file")
1733
1734 (js2-msg "msg.XML.bad.form"
1735 "illegally formed XML syntax")
1736
1737 (js2-msg "msg.XML.not.available"
1738 "XML runtime not available")
1739
1740 (js2-msg "msg.too.deep.parser.recursion"
1741 "Too deep recursion while parsing")
1742
1743 (js2-msg "msg.no.side.effects"
1744 "Code has no side effects")
1745
1746 (js2-msg "msg.extra.trailing.comma"
1747 "Trailing comma is not legal in an ECMA-262 object initializer")
1748
1749 (js2-msg "msg.array.trailing.comma"
1750 "Trailing comma yields different behavior across browsers")
1751
1752 (js2-msg "msg.equal.as.assign"
1753 (concat "Test for equality (==) mistyped as assignment (=)?"
1754 " (parenthesize to suppress warning)"))
1755
1756 (js2-msg "msg.var.hides.arg"
1757 "Variable %s hides argument")
1758
1759 (js2-msg "msg.destruct.assign.no.init"
1760 "Missing = in destructuring declaration")
1761
1762 ;; ScriptRuntime
1763 (js2-msg "msg.no.properties"
1764 "%s has no properties.")
1765
1766 (js2-msg "msg.invalid.iterator"
1767 "Invalid iterator value")
1768
1769 (js2-msg "msg.iterator.primitive"
1770 "__iterator__ returned a primitive value")
1771
1772 (js2-msg "msg.assn.create.strict"
1773 "Assignment to undeclared variable %s")
1774
1775 (js2-msg "msg.ref.undefined.prop"
1776 "Reference to undefined property '%s'")
1777
1778 (js2-msg "msg.prop.not.found"
1779 "Property %s not found.")
1780
1781 (js2-msg "msg.invalid.type"
1782 "Invalid JavaScript value of type %s")
1783
1784 (js2-msg "msg.primitive.expected"
1785 "Primitive type expected (had %s instead)")
1786
1787 (js2-msg "msg.namespace.expected"
1788 "Namespace object expected to left of :: (found %s instead)")
1789
1790 (js2-msg "msg.null.to.object"
1791 "Cannot convert null to an object.")
1792
1793 (js2-msg "msg.undef.to.object"
1794 "Cannot convert undefined to an object.")
1795
1796 (js2-msg "msg.cyclic.value"
1797 "Cyclic %s value not allowed.")
1798
1799 (js2-msg "msg.is.not.defined"
1800 "'%s' is not defined.")
1801
1802 (js2-msg "msg.undef.prop.read"
1803 "Cannot read property '%s' from %s")
1804
1805 (js2-msg "msg.undef.prop.write"
1806 "Cannot set property '%s' of %s to '%s'")
1807
1808 (js2-msg "msg.undef.prop.delete"
1809 "Cannot delete property '%s' of %s")
1810
1811 (js2-msg "msg.undef.method.call"
1812 "Cannot call method '%s' of %s")
1813
1814 (js2-msg "msg.undef.with"
1815 "Cannot apply 'with' to %s")
1816
1817 (js2-msg "msg.isnt.function"
1818 "%s is not a function, it is %s.")
1819
1820 (js2-msg "msg.isnt.function.in"
1821 "Cannot call property %s in object %s. "
1822 "It is not a function, it is '%s'.")
1823
1824 (js2-msg "msg.function.not.found"
1825 "Cannot find function %s.")
1826
1827 (js2-msg "msg.function.not.found.in"
1828 "Cannot find function %s in object %s.")
1829
1830 (js2-msg "msg.isnt.xml.object"
1831 "%s is not an xml object.")
1832
1833 (js2-msg "msg.no.ref.to.get"
1834 "%s is not a reference to read reference value.")
1835
1836 (js2-msg "msg.no.ref.to.set"
1837 "%s is not a reference to set reference value to %s.")
1838
1839 (js2-msg "msg.no.ref.from.function"
1840 "Function %s can not be used as the left-hand "
1841 "side of assignment or as an operand of ++ or -- operator.")
1842
1843 (js2-msg "msg.bad.default.value"
1844 "Object's getDefaultValue() method returned an object.")
1845
1846 (js2-msg "msg.instanceof.not.object"
1847 "Can't use instanceof on a non-object.")
1848
1849 (js2-msg "msg.instanceof.bad.prototype"
1850 "'prototype' property of %s is not an object.")
1851
1852 (js2-msg "msg.bad.radix"
1853 "illegal radix %s.")
1854
1855 ;; ScriptableObject
1856 (js2-msg "msg.default.value"
1857 "Cannot find default value for object.")
1858
1859 (js2-msg "msg.zero.arg.ctor"
1860 "Cannot load class '%s' which has no zero-parameter constructor.")
1861
1862 (js2-msg "msg.ctor.multiple.parms"
1863 "Can't define constructor or class %s since more than "
1864 "one constructor has multiple parameters.")
1865
1866 (js2-msg "msg.extend.scriptable"
1867 "%s must extend ScriptableObject in order to define property %s.")
1868
1869 (js2-msg "msg.bad.getter.parms"
1870 "In order to define a property, getter %s must have zero "
1871 "parameters or a single ScriptableObject parameter.")
1872
1873 (js2-msg "msg.obj.getter.parms"
1874 "Expected static or delegated getter %s to take "
1875 "a ScriptableObject parameter.")
1876
1877 (js2-msg "msg.getter.static"
1878 "Getter and setter must both be static or neither be static.")
1879
1880 (js2-msg "msg.setter.return"
1881 "Setter must have void return type: %s")
1882
1883 (js2-msg "msg.setter2.parms"
1884 "Two-parameter setter must take a ScriptableObject as "
1885 "its first parameter.")
1886
1887 (js2-msg "msg.setter1.parms"
1888 "Expected single parameter setter for %s")
1889
1890 (js2-msg "msg.setter2.expected"
1891 "Expected static or delegated setter %s to take two parameters.")
1892
1893 (js2-msg "msg.setter.parms"
1894 "Expected either one or two parameters for setter.")
1895
1896 (js2-msg "msg.setter.bad.type"
1897 "Unsupported parameter type '%s' in setter '%s'.")
1898
1899 (js2-msg "msg.add.sealed"
1900 "Cannot add a property to a sealed object: %s.")
1901
1902 (js2-msg "msg.remove.sealed"
1903 "Cannot remove a property from a sealed object: %s.")
1904
1905 (js2-msg "msg.modify.sealed"
1906 "Cannot modify a property of a sealed object: %s.")
1907
1908 (js2-msg "msg.modify.readonly"
1909 "Cannot modify readonly property: %s.")
1910
1911 ;; TokenStream
1912 (js2-msg "msg.missing.exponent"
1913 "missing exponent")
1914
1915 (js2-msg "msg.caught.nfe"
1916 "number format error")
1917
1918 (js2-msg "msg.unterminated.string.lit"
1919 "unterminated string literal")
1920
1921 (js2-msg "msg.unterminated.comment"
1922 "unterminated comment")
1923
1924 (js2-msg "msg.unterminated.re.lit"
1925 "unterminated regular expression literal")
1926
1927 (js2-msg "msg.invalid.re.flag"
1928 "invalid flag after regular expression")
1929
1930 (js2-msg "msg.no.re.input.for"
1931 "no input for %s")
1932
1933 (js2-msg "msg.illegal.character"
1934 "illegal character")
1935
1936 (js2-msg "msg.invalid.escape"
1937 "invalid Unicode escape sequence")
1938
1939 (js2-msg "msg.bad.namespace"
1940 "not a valid default namespace statement. "
1941 "Syntax is: default xml namespace = EXPRESSION;")
1942
1943 ;; TokensStream warnings
1944 (js2-msg "msg.bad.octal.literal"
1945 "illegal octal literal digit %s; "
1946 "interpreting it as a decimal digit")
1947
1948 (js2-msg "msg.reserved.keyword"
1949 "illegal usage of future reserved keyword %s; "
1950 "interpreting it as ordinary identifier")
1951
1952 (js2-msg "msg.script.is.not.constructor"
1953 "Script objects are not constructors.")
1954
1955 ;; Arrays
1956 (js2-msg "msg.arraylength.bad"
1957 "Inappropriate array length.")
1958
1959 ;; Arrays
1960 (js2-msg "msg.arraylength.too.big"
1961 "Array length %s exceeds supported capacity limit.")
1962
1963 ;; URI
1964 (js2-msg "msg.bad.uri"
1965 "Malformed URI sequence.")
1966
1967 ;; Number
1968 (js2-msg "msg.bad.precision"
1969 "Precision %s out of range.")
1970
1971 ;; NativeGenerator
1972 (js2-msg "msg.send.newborn"
1973 "Attempt to send value to newborn generator")
1974
1975 (js2-msg "msg.already.exec.gen"
1976 "Already executing generator")
1977
1978 (js2-msg "msg.StopIteration.invalid"
1979 "StopIteration may not be changed to an arbitrary object.")
1980
1981 ;; Interpreter
1982 (js2-msg "msg.yield.closing"
1983 "Yield from closing generator")
1984
1985 ;;; Utilities
1986
1987 (defun js2-delete-if (predicate list)
1988 "Remove all items satisfying PREDICATE in LIST."
1989 (loop for item in list
1990 if (not (funcall predicate item))
1991 collect item))
1992
1993 (defun js2-position (element list)
1994 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1995 Returns nil if element is not found in the list."
1996 (let ((count 0)
1997 found)
1998 (while (and list (not found))
1999 (if (eq element (car list))
2000 (setq found t)
2001 (setq count (1+ count)
2002 list (cdr list))))
2003 (if found count)))
2004
2005 (defun js2-find-if (predicate list)
2006 "Find first item satisfying PREDICATE in LIST."
2007 (let (result)
2008 (while (and list (not result))
2009 (if (funcall predicate (car list))
2010 (setq result (car list)))
2011 (setq list (cdr list)))
2012 result))
2013
2014 (defmacro js2-time (form)
2015 "Evaluate FORM, discard result, and return elapsed time in sec"
2016 (declare (debug t))
2017 (let ((beg (make-symbol "--js2-time-beg--"))
2018 (delta (make-symbol "--js2-time-end--")))
2019 `(let ((,beg (current-time))
2020 ,delta)
2021 ,form
2022 (/ (truncate (* (- (float-time (current-time))
2023 (float-time ,beg))
2024 10000))
2025 10000.0))))
2026
2027 (defsubst js2-same-line (pos)
2028 "Return t if POS is on the same line as current point."
2029 (and (>= pos (point-at-bol))
2030 (<= pos (point-at-eol))))
2031
2032 (defsubst js2-same-line-2 (p1 p2)
2033 "Return t if p1 is on the same line as p2."
2034 (save-excursion
2035 (goto-char p1)
2036 (js2-same-line p2)))
2037
2038 (defun js2-code-bug ()
2039 "Signal an error when we encounter an unexpected code path."
2040 (error "failed assertion"))
2041
2042 (defsubst js2-record-text-property (beg end prop value)
2043 "Record a text property to set when parsing finishes."
2044 (push (list beg end prop value) js2-mode-deferred-properties))
2045
2046 ;; I'd like to associate errors with nodes, but for now the
2047 ;; easiest thing to do is get the context info from the last token.
2048 (defsubst js2-record-parse-error (msg &optional arg pos len)
2049 (push (list (list msg arg)
2050 (or pos js2-token-beg)
2051 (or len (- js2-token-end js2-token-beg)))
2052 js2-parsed-errors))
2053
2054 (defsubst js2-report-error (msg &optional msg-arg pos len)
2055 "Signal a syntax error or record a parse error."
2056 (if js2-recover-from-parse-errors
2057 (js2-record-parse-error msg msg-arg pos len)
2058 (signal 'js2-syntax-error
2059 (list msg
2060 js2-ts-lineno
2061 (save-excursion
2062 (goto-char js2-ts-cursor)
2063 (current-column))
2064 js2-ts-hit-eof))))
2065
2066 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2067 (if js2-compiler-report-warning-as-error
2068 (js2-report-error msg msg-arg pos len)
2069 (push (list (list msg msg-arg)
2070 (or pos js2-token-beg)
2071 (or len (- js2-token-end js2-token-beg)))
2072 js2-parsed-warnings)))
2073
2074 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2075 (if js2-compiler-strict-mode
2076 (js2-report-warning msg-id msg-arg beg
2077 (and beg end (- end beg)))))
2078
2079 (put 'js2-syntax-error 'error-conditions
2080 '(error syntax-error js2-syntax-error))
2081 (put 'js2-syntax-error 'error-message "Syntax error")
2082
2083 (put 'js2-parse-error 'error-conditions
2084 '(error parse-error js2-parse-error))
2085 (put 'js2-parse-error 'error-message "Parse error")
2086
2087 (defmacro js2-clear-flag (flags flag)
2088 `(setq ,flags (logand ,flags (lognot ,flag))))
2089
2090 (defmacro js2-set-flag (flags flag)
2091 "Logical-or FLAG into FLAGS."
2092 `(setq ,flags (logior ,flags ,flag)))
2093
2094 (defsubst js2-flag-set-p (flags flag)
2095 (/= 0 (logand flags flag)))
2096
2097 (defsubst js2-flag-not-set-p (flags flag)
2098 (zerop (logand flags flag)))
2099
2100 ;; Stolen shamelessly from James Clark's nxml-mode.
2101 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2102 "Evaluate BODY without any text property changes modifying the buffer.
2103 Any text properties changes happen as usual but the changes are not treated as
2104 modifications to the buffer."
2105 (declare (indent 0) (debug t))
2106 (let ((modified (make-symbol "modified")))
2107 `(let ((,modified (buffer-modified-p))
2108 (inhibit-read-only t)
2109 (inhibit-modification-hooks t)
2110 (buffer-undo-list t)
2111 (deactivate-mark nil)
2112 ;; Apparently these avoid file locking problems.
2113 (buffer-file-name nil)
2114 (buffer-file-truename nil))
2115 (unwind-protect
2116 (progn ,@body)
2117 (unless ,modified
2118 (restore-buffer-modified-p nil))))))
2119
2120 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2121 "Evaluate BODY with the _ character set to be word-syntax."
2122 (declare (indent 0) (debug t))
2123 (let ((old-syntax (make-symbol "old-syntax")))
2124 `(let ((,old-syntax (string (char-syntax ?_))))
2125 (unwind-protect
2126 (progn
2127 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2128 ,@body)
2129 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2130
2131 (defsubst js2-char-uppercase-p (c)
2132 "Return t if C is an uppercase character.
2133 Handles unicode and latin chars properly."
2134 (/= c (downcase c)))
2135
2136 (defsubst js2-char-lowercase-p (c)
2137 "Return t if C is an uppercase character.
2138 Handles unicode and latin chars properly."
2139 (/= c (upcase c)))
2140
2141 ;;; AST struct and function definitions
2142
2143 ;; flags for ast node property 'member-type (used for e4x operators)
2144 (defvar js2-property-flag #x1 "property access: element is valid name")
2145 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2146 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2147
2148 (defsubst js2-relpos (pos anchor)
2149 "Convert POS to be relative to ANCHOR.
2150 If POS is nil, returns nil."
2151 (and pos (- pos anchor)))
2152
2153 (defsubst js2-make-pad (indent)
2154 (if (zerop indent)
2155 ""
2156 (make-string (* indent js2-basic-offset) ? )))
2157
2158 (defsubst js2-visit-ast (node callback)
2159 "Visit every node in ast NODE with visitor CALLBACK.
2160
2161 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2162 called twice: once to visit the node, and again after all the node's
2163 children have been processed. The END-P argument is nil on the first
2164 call and non-nil on the second call. The return value of the callback
2165 affects the traversal: if non-nil, the children of NODE are processed.
2166 If the callback returns nil, or if the node has no children, then the
2167 callback is called immediately with a non-nil END-P argument.
2168
2169 The node traversal is approximately lexical-order, although there
2170 are currently no guarantees around this."
2171 (if node
2172 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2173 ;; visit the node
2174 (when (funcall callback node nil)
2175 ;; visit the kids
2176 (cond
2177 ((eq vfunc 'js2-visit-none)
2178 nil) ; don't even bother calling it
2179 ;; Each AST node type has to define a `js2-visitor' function
2180 ;; that takes a node and a callback, and calls `js2-visit-ast'
2181 ;; on each child of the node.
2182 (vfunc
2183 (funcall vfunc node callback))
2184 (t
2185 (error "%s does not define a visitor-traversal function"
2186 (aref node 0)))))
2187 ;; call the end-visit
2188 (funcall callback node t))))
2189
2190 (defstruct (js2-node
2191 (:constructor nil)) ; abstract
2192 "Base AST node type."
2193 (type -1) ; token type
2194 (pos -1) ; start position of this AST node in parsed input
2195 (len 1) ; num characters spanned by the node
2196 props ; optional node property list (an alist)
2197 parent) ; link to parent node; null for root
2198
2199 (defsubst js2-node-get-prop (node prop &optional default)
2200 (or (cadr (assoc prop (js2-node-props node))) default))
2201
2202 (defsubst js2-node-set-prop (node prop value)
2203 (setf (js2-node-props node)
2204 (cons (list prop value) (js2-node-props node))))
2205
2206 (defsubst js2-fixup-starts (n nodes)
2207 "Adjust the start positions of NODES to be relative to N.
2208 Any node in the list may be nil, for convenience."
2209 (dolist (node nodes)
2210 (when node
2211 (setf (js2-node-pos node) (- (js2-node-pos node)
2212 (js2-node-pos n))))))
2213
2214 (defsubst js2-node-add-children (parent &rest nodes)
2215 "Set parent node of NODES to PARENT, and return PARENT.
2216 Does nothing if we're not recording parent links.
2217 If any given node in NODES is nil, doesn't record that link."
2218 (js2-fixup-starts parent nodes)
2219 (dolist (node nodes)
2220 (and node
2221 (setf (js2-node-parent node) parent))))
2222
2223 ;; Non-recursive since it's called a frightening number of times.
2224 (defsubst js2-node-abs-pos (n)
2225 (let ((pos (js2-node-pos n)))
2226 (while (setq n (js2-node-parent n))
2227 (setq pos (+ pos (js2-node-pos n))))
2228 pos))
2229
2230 (defsubst js2-node-abs-end (n)
2231 "Return absolute buffer position of end of N."
2232 (+ (js2-node-abs-pos n) (js2-node-len n)))
2233
2234 ;; It's important to make sure block nodes have a lisp list for the
2235 ;; child nodes, to limit printing recursion depth in an AST that
2236 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2237 ;; a sufficiently large vector tree.
2238
2239 (defstruct (js2-block-node
2240 (:include js2-node)
2241 (:constructor nil)
2242 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2243 (pos js2-token-beg)
2244 len
2245 props
2246 kids)))
2247 "A block of statements."
2248 kids) ; a lisp list of the child statement nodes
2249
2250 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2251 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2252
2253 (defsubst js2-visit-block (ast callback)
2254 "Visit the `js2-block-node' children of AST."
2255 (dolist (kid (js2-block-node-kids ast))
2256 (js2-visit-ast kid callback)))
2257
2258 (defun js2-print-block (n i)
2259 (let ((pad (js2-make-pad i)))
2260 (insert pad "{\n")
2261 (dolist (kid (js2-block-node-kids n))
2262 (js2-print-ast kid (1+ i)))
2263 (insert pad "}")))
2264
2265 (defstruct (js2-scope
2266 (:include js2-block-node)
2267 (:constructor nil)
2268 (:constructor make-js2-scope (&key (type js2-BLOCK)
2269 (pos js2-token-beg)
2270 len
2271 kids)))
2272 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2273 ;; I don't have one of those handy, so I'll use an alist for now.
2274 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2275 ;; and is much lighter-weight to construct (both CPU and mem).
2276 ;; The keys are interned strings (symbols) for faster lookup.
2277 ;; Should switch to hybrid alist/hashtable eventually.
2278 symbol-table ; an alist of (symbol . js2-symbol)
2279 parent-scope ; a `js2-scope'
2280 top) ; top-level `js2-scope' (script/function)
2281
2282 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2283 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2284
2285 (defun js2-scope-set-parent-scope (scope parent)
2286 (setf (js2-scope-parent-scope scope) parent
2287 (js2-scope-top scope) (if (null parent)
2288 scope
2289 (js2-scope-top parent))))
2290
2291 (defun js2-node-get-enclosing-scope (node)
2292 "Return the innermost `js2-scope' node surrounding NODE.
2293 Returns nil if there is no enclosing scope node."
2294 (let ((parent (js2-node-parent node)))
2295 (while (not (js2-scope-p parent))
2296 (setq parent (js2-node-parent parent)))
2297 parent))
2298
2299 (defun js2-get-defining-scope (scope name)
2300 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2301 Returns `js2-scope' in which NAME is defined, or nil if not found."
2302 (let ((sym (if (symbolp name)
2303 name
2304 (intern name)))
2305 table
2306 result
2307 (continue t))
2308 (while (and scope continue)
2309 (if (and (setq table (js2-scope-symbol-table scope))
2310 (assq sym table))
2311 (setq continue nil
2312 result scope)
2313 (setq scope (js2-scope-parent-scope scope))))
2314 result))
2315
2316 (defsubst js2-scope-get-symbol (scope name)
2317 "Return symbol table entry for NAME in SCOPE.
2318 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2319 (and (js2-scope-symbol-table scope)
2320 (cdr (assq (if (symbolp name)
2321 name
2322 (intern name))
2323 (js2-scope-symbol-table scope)))))
2324
2325 (defsubst js2-scope-put-symbol (scope name symbol)
2326 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2327 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2328 (let* ((table (js2-scope-symbol-table scope))
2329 (sym (if (symbolp name) name (intern name)))
2330 (entry (assq sym table)))
2331 (if entry
2332 (setcdr entry symbol)
2333 (push (cons sym symbol)
2334 (js2-scope-symbol-table scope)))))
2335
2336 (defstruct (js2-symbol
2337 (:constructor nil)
2338 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2339 "A symbol table entry."
2340 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2341 ;; js2-LET, or js2-CONST
2342 decl-type
2343 name ; string
2344 ast-node) ; a `js2-node'
2345
2346 (defstruct (js2-error-node
2347 (:include js2-node)
2348 (:constructor nil) ; silence emacs21 byte-compiler
2349 (:constructor make-js2-error-node (&key (type js2-ERROR)
2350 (pos js2-token-beg)
2351 len)))
2352 "AST node representing a parse error.")
2353
2354 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2355 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2356
2357 (defstruct (js2-script-node
2358 (:include js2-scope)
2359 (:constructor nil)
2360 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2361 (pos js2-token-beg)
2362 len
2363 var-decls
2364 fun-decls)))
2365 functions ; lisp list of nested functions
2366 regexps ; lisp list of (string . flags)
2367 symbols ; alist (every symbol gets unique index)
2368 (param-count 0)
2369 var-names ; vector of string names
2370 consts ; bool-vector matching var-decls
2371 (temp-number 0)) ; for generating temp variables
2372
2373 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2374 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2375
2376 (defun js2-print-script (node indent)
2377 (dolist (kid (js2-block-node-kids node))
2378 (js2-print-ast kid indent)))
2379
2380 (defstruct (js2-ast-root
2381 (:include js2-script-node)
2382 (:constructor nil)
2383 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2384 (pos js2-token-beg)
2385 len
2386 buffer)))
2387 "The root node of a js2 AST."
2388 buffer ; the source buffer from which the code was parsed
2389 comments ; a lisp list of comments, ordered by start position
2390 errors ; a lisp list of errors found during parsing
2391 warnings ; a lisp list of warnings found during parsing
2392 node-count) ; number of nodes in the tree, including the root
2393
2394 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2395 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2396
2397 (defun js2-visit-ast-root (ast callback)
2398 (dolist (kid (js2-ast-root-kids ast))
2399 (js2-visit-ast kid callback))
2400 (dolist (comment (js2-ast-root-comments ast))
2401 (js2-visit-ast comment callback)))
2402
2403 (defstruct (js2-comment-node
2404 (:include js2-node)
2405 (:constructor nil)
2406 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2407 (pos js2-token-beg)
2408 len
2409 (format js2-ts-comment-type))))
2410 format) ; 'line, 'block, 'jsdoc or 'html
2411
2412 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2413 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2414
2415 (defun js2-print-comment (n i)
2416 ;; We really ought to link end-of-line comments to their nodes.
2417 ;; Or maybe we could add a new comment type, 'endline.
2418 (insert (js2-make-pad i)
2419 (js2-node-string n)))
2420
2421 (defstruct (js2-expr-stmt-node
2422 (:include js2-node)
2423 (:constructor nil)
2424 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2425 (pos js2-ts-cursor)
2426 len
2427 expr)))
2428 "An expression statement."
2429 expr)
2430
2431 (defsubst js2-expr-stmt-node-set-has-result (node)
2432 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2433 (setf (js2-node-type node) js2-EXPR_RESULT))
2434
2435 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2436 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2437
2438 (defun js2-visit-expr-stmt-node (n v)
2439 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2440
2441 (defun js2-print-expr-stmt-node (n indent)
2442 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2443 (insert ";\n"))
2444
2445 (defstruct (js2-loop-node
2446 (:include js2-scope)
2447 (:constructor nil))
2448 "Abstract supertype of loop nodes."
2449 body ; a `js2-block-node'
2450 lp ; position of left-paren, nil if omitted
2451 rp) ; position of right-paren, nil if omitted
2452
2453 (defstruct (js2-do-node
2454 (:include js2-loop-node)
2455 (:constructor nil)
2456 (:constructor make-js2-do-node (&key (type js2-DO)
2457 (pos js2-token-beg)
2458 len
2459 body
2460 condition
2461 while-pos
2462 lp
2463 rp)))
2464 "AST node for do-loop."
2465 condition ; while (expression)
2466 while-pos) ; buffer position of 'while' keyword
2467
2468 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2469 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2470
2471 (defun js2-visit-do-node (n v)
2472 (js2-visit-ast (js2-do-node-body n) v)
2473 (js2-visit-ast (js2-do-node-condition n) v))
2474
2475 (defun js2-print-do-node (n i)
2476 (let ((pad (js2-make-pad i)))
2477 (insert pad "do {\n")
2478 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2479 (js2-print-ast kid (1+ i)))
2480 (insert pad "} while (")
2481 (js2-print-ast (js2-do-node-condition n) 0)
2482 (insert ");\n")))
2483
2484 (defstruct (js2-while-node
2485 (:include js2-loop-node)
2486 (:constructor nil)
2487 (:constructor make-js2-while-node (&key (type js2-WHILE)
2488 (pos js2-token-beg)
2489 len
2490 body
2491 condition
2492 lp
2493 rp)))
2494 "AST node for while-loop."
2495 condition) ; while-condition
2496
2497 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2498 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2499
2500 (defun js2-visit-while-node (n v)
2501 (js2-visit-ast (js2-while-node-condition n) v)
2502 (js2-visit-ast (js2-while-node-body n) v))
2503
2504 (defun js2-print-while-node (n i)
2505 (let ((pad (js2-make-pad i)))
2506 (insert pad "while (")
2507 (js2-print-ast (js2-while-node-condition n) 0)
2508 (insert ") {\n")
2509 (js2-print-body (js2-while-node-body n) (1+ i))
2510 (insert pad "}\n")))
2511
2512 (defstruct (js2-for-node
2513 (:include js2-loop-node)
2514 (:constructor nil)
2515 (:constructor make-js2-for-node (&key (type js2-FOR)
2516 (pos js2-ts-cursor)
2517 len
2518 body
2519 init
2520 condition
2521 update
2522 lp
2523 rp)))
2524 "AST node for a C-style for-loop."
2525 init ; initialization expression
2526 condition ; loop condition
2527 update) ; update clause
2528
2529 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2530 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2531
2532 (defun js2-visit-for-node (n v)
2533 (js2-visit-ast (js2-for-node-init n) v)
2534 (js2-visit-ast (js2-for-node-condition n) v)
2535 (js2-visit-ast (js2-for-node-update n) v)
2536 (js2-visit-ast (js2-for-node-body n) v))
2537
2538 (defun js2-print-for-node (n i)
2539 (let ((pad (js2-make-pad i)))
2540 (insert pad "for (")
2541 (js2-print-ast (js2-for-node-init n) 0)
2542 (insert "; ")
2543 (js2-print-ast (js2-for-node-condition n) 0)
2544 (insert "; ")
2545 (js2-print-ast (js2-for-node-update n) 0)
2546 (insert ") {\n")
2547 (js2-print-body (js2-for-node-body n) (1+ i))
2548 (insert pad "}\n")))
2549
2550 (defstruct (js2-for-in-node
2551 (:include js2-loop-node)
2552 (:constructor nil)
2553 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2554 (pos js2-ts-cursor)
2555 len
2556 body
2557 iterator
2558 object
2559 in-pos
2560 each-pos
2561 foreach-p forof-p
2562 lp rp)))
2563 "AST node for a for..in loop."
2564 iterator ; [var] foo in ...
2565 object ; object over which we're iterating
2566 in-pos ; buffer position of 'in' keyword
2567 each-pos ; buffer position of 'each' keyword, if foreach-p
2568 foreach-p ; t if it's a for-each loop
2569 forof-p) ; t if it's a for-of loop
2570
2571 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2572 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2573
2574 (defun js2-visit-for-in-node (n v)
2575 (js2-visit-ast (js2-for-in-node-iterator n) v)
2576 (js2-visit-ast (js2-for-in-node-object n) v)
2577 (js2-visit-ast (js2-for-in-node-body n) v))
2578
2579 (defun js2-print-for-in-node (n i)
2580 (let ((pad (js2-make-pad i))
2581 (foreach (js2-for-in-node-foreach-p n))
2582 (forof (js2-for-in-node-forof-p n)))
2583 (insert pad "for ")
2584 (if foreach
2585 (insert "each "))
2586 (insert "(")
2587 (js2-print-ast (js2-for-in-node-iterator n) 0)
2588 (if forof
2589 (insert " of ")
2590 (insert " in "))
2591 (js2-print-ast (js2-for-in-node-object n) 0)
2592 (insert ") {\n")
2593 (js2-print-body (js2-for-in-node-body n) (1+ i))
2594 (insert pad "}\n")))
2595
2596 (defstruct (js2-return-node
2597 (:include js2-node)
2598 (:constructor nil)
2599 (:constructor make-js2-return-node (&key (type js2-RETURN)
2600 (pos js2-ts-cursor)
2601 len
2602 retval)))
2603 "AST node for a return statement."
2604 retval) ; expression to return, or 'undefined
2605
2606 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2607 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2608
2609 (defun js2-visit-return-node (n v)
2610 (js2-visit-ast (js2-return-node-retval n) v))
2611
2612 (defun js2-print-return-node (n i)
2613 (insert (js2-make-pad i) "return")
2614 (when (js2-return-node-retval n)
2615 (insert " ")
2616 (js2-print-ast (js2-return-node-retval n) 0))
2617 (insert ";\n"))
2618
2619 (defstruct (js2-if-node
2620 (:include js2-node)
2621 (:constructor nil)
2622 (:constructor make-js2-if-node (&key (type js2-IF)
2623 (pos js2-ts-cursor)
2624 len
2625 condition
2626 then-part
2627 else-pos
2628 else-part
2629 lp
2630 rp)))
2631 "AST node for an if-statement."
2632 condition ; expression
2633 then-part ; statement or block
2634 else-pos ; optional buffer position of 'else' keyword
2635 else-part ; optional statement or block
2636 lp ; position of left-paren, nil if omitted
2637 rp) ; position of right-paren, nil if omitted
2638
2639 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2640 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2641
2642 (defun js2-visit-if-node (n v)
2643 (js2-visit-ast (js2-if-node-condition n) v)
2644 (js2-visit-ast (js2-if-node-then-part n) v)
2645 (js2-visit-ast (js2-if-node-else-part n) v))
2646
2647 (defun js2-print-if-node (n i)
2648 (let ((pad (js2-make-pad i))
2649 (then-part (js2-if-node-then-part n))
2650 (else-part (js2-if-node-else-part n)))
2651 (insert pad "if (")
2652 (js2-print-ast (js2-if-node-condition n) 0)
2653 (insert ") {\n")
2654 (js2-print-body then-part (1+ i))
2655 (insert pad "}")
2656 (cond
2657 ((not else-part)
2658 (insert "\n"))
2659 ((js2-if-node-p else-part)
2660 (insert " else ")
2661 (js2-print-body else-part i))
2662 (t
2663 (insert " else {\n")
2664 (js2-print-body else-part (1+ i))
2665 (insert pad "}\n")))))
2666
2667 (defstruct (js2-try-node
2668 (:include js2-node)
2669 (:constructor nil)
2670 (:constructor make-js2-try-node (&key (type js2-TRY)
2671 (pos js2-ts-cursor)
2672 len
2673 try-block
2674 catch-clauses
2675 finally-block)))
2676 "AST node for a try-statement."
2677 try-block
2678 catch-clauses ; a lisp list of `js2-catch-node'
2679 finally-block) ; a `js2-finally-node'
2680
2681 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2682 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2683
2684 (defun js2-visit-try-node (n v)
2685 (js2-visit-ast (js2-try-node-try-block n) v)
2686 (dolist (clause (js2-try-node-catch-clauses n))
2687 (js2-visit-ast clause v))
2688 (js2-visit-ast (js2-try-node-finally-block n) v))
2689
2690 (defun js2-print-try-node (n i)
2691 (let ((pad (js2-make-pad i))
2692 (catches (js2-try-node-catch-clauses n))
2693 (finally (js2-try-node-finally-block n)))
2694 (insert pad "try {\n")
2695 (js2-print-body (js2-try-node-try-block n) (1+ i))
2696 (insert pad "}")
2697 (when catches
2698 (dolist (catch catches)
2699 (js2-print-ast catch i)))
2700 (if finally
2701 (js2-print-ast finally i)
2702 (insert "\n"))))
2703
2704 (defstruct (js2-catch-node
2705 (:include js2-node)
2706 (:constructor nil)
2707 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2708 (pos js2-ts-cursor)
2709 len
2710 param
2711 guard-kwd
2712 guard-expr
2713 block
2714 lp
2715 rp)))
2716 "AST node for a catch clause."
2717 param ; destructuring form or simple name node
2718 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2719 guard-expr ; catch condition, a `js2-node'
2720 block ; statements, a `js2-block-node'
2721 lp ; buffer position of left-paren, nil if omitted
2722 rp) ; buffer position of right-paren, nil if omitted
2723
2724 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2725 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2726
2727 (defun js2-visit-catch-node (n v)
2728 (js2-visit-ast (js2-catch-node-param n) v)
2729 (when (js2-catch-node-guard-kwd n)
2730 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2731 (js2-visit-ast (js2-catch-node-block n) v))
2732
2733 (defun js2-print-catch-node (n i)
2734 (let ((pad (js2-make-pad i))
2735 (guard-kwd (js2-catch-node-guard-kwd n))
2736 (guard-expr (js2-catch-node-guard-expr n)))
2737 (insert " catch (")
2738 (js2-print-ast (js2-catch-node-param n) 0)
2739 (when guard-kwd
2740 (insert " if ")
2741 (js2-print-ast guard-expr 0))
2742 (insert ") {\n")
2743 (js2-print-body (js2-catch-node-block n) (1+ i))
2744 (insert pad "}")))
2745
2746 (defstruct (js2-finally-node
2747 (:include js2-node)
2748 (:constructor nil)
2749 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2750 (pos js2-ts-cursor)
2751 len
2752 body)))
2753 "AST node for a finally clause."
2754 body) ; a `js2-node', often but not always a block node
2755
2756 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2757 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2758
2759 (defun js2-visit-finally-node (n v)
2760 (js2-visit-ast (js2-finally-node-body n) v))
2761
2762 (defun js2-print-finally-node (n i)
2763 (let ((pad (js2-make-pad i)))
2764 (insert " finally {\n")
2765 (js2-print-body (js2-finally-node-body n) (1+ i))
2766 (insert pad "}\n")))
2767
2768 (defstruct (js2-switch-node
2769 (:include js2-node)
2770 (:constructor nil)
2771 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2772 (pos js2-ts-cursor)
2773 len
2774 discriminant
2775 cases
2776 lp
2777 rp)))
2778 "AST node for a switch statement."
2779 discriminant ; a `js2-node' (switch expression)
2780 cases ; a lisp list of `js2-case-node'
2781 lp ; position of open-paren for discriminant, nil if omitted
2782 rp) ; position of close-paren for discriminant, nil if omitted
2783
2784 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2785 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2786
2787 (defun js2-visit-switch-node (n v)
2788 (js2-visit-ast (js2-switch-node-discriminant n) v)
2789 (dolist (c (js2-switch-node-cases n))
2790 (js2-visit-ast c v)))
2791
2792 (defun js2-print-switch-node (n i)
2793 (let ((pad (js2-make-pad i))
2794 (cases (js2-switch-node-cases n)))
2795 (insert pad "switch (")
2796 (js2-print-ast (js2-switch-node-discriminant n) 0)
2797 (insert ") {\n")
2798 (dolist (case cases)
2799 (js2-print-ast case i))
2800 (insert pad "}\n")))
2801
2802 (defstruct (js2-case-node
2803 (:include js2-block-node)
2804 (:constructor nil)
2805 (:constructor make-js2-case-node (&key (type js2-CASE)
2806 (pos js2-ts-cursor)
2807 len
2808 kids
2809 expr)))
2810 "AST node for a case clause of a switch statement."
2811 expr) ; the case expression (nil for default)
2812
2813 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2814 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2815
2816 (defun js2-visit-case-node (n v)
2817 (js2-visit-ast (js2-case-node-expr n) v)
2818 (js2-visit-block n v))
2819
2820 (defun js2-print-case-node (n i)
2821 (let ((pad (js2-make-pad i))
2822 (expr (js2-case-node-expr n)))
2823 (insert pad)
2824 (if (null expr)
2825 (insert "default:\n")
2826 (insert "case ")
2827 (js2-print-ast expr 0)
2828 (insert ":\n"))
2829 (dolist (kid (js2-case-node-kids n))
2830 (js2-print-ast kid (1+ i)))))
2831
2832 (defstruct (js2-throw-node
2833 (:include js2-node)
2834 (:constructor nil)
2835 (:constructor make-js2-throw-node (&key (type js2-THROW)
2836 (pos js2-ts-cursor)
2837 len
2838 expr)))
2839 "AST node for a throw statement."
2840 expr) ; the expression to throw
2841
2842 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2843 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2844
2845 (defun js2-visit-throw-node (n v)
2846 (js2-visit-ast (js2-throw-node-expr n) v))
2847
2848 (defun js2-print-throw-node (n i)
2849 (insert (js2-make-pad i) "throw ")
2850 (js2-print-ast (js2-throw-node-expr n) 0)
2851 (insert ";\n"))
2852
2853 (defstruct (js2-with-node
2854 (:include js2-node)
2855 (:constructor nil)
2856 (:constructor make-js2-with-node (&key (type js2-WITH)
2857 (pos js2-ts-cursor)
2858 len
2859 object
2860 body
2861 lp
2862 rp)))
2863 "AST node for a with-statement."
2864 object
2865 body
2866 lp ; buffer position of left-paren around object, nil if omitted
2867 rp) ; buffer position of right-paren around object, nil if omitted
2868
2869 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2870 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2871
2872 (defun js2-visit-with-node (n v)
2873 (js2-visit-ast (js2-with-node-object n) v)
2874 (js2-visit-ast (js2-with-node-body n) v))
2875
2876 (defun js2-print-with-node (n i)
2877 (let ((pad (js2-make-pad i)))
2878 (insert pad "with (")
2879 (js2-print-ast (js2-with-node-object n) 0)
2880 (insert ") {\n")
2881 (js2-print-body (js2-with-node-body n) (1+ i))
2882 (insert pad "}\n")))
2883
2884 (defstruct (js2-label-node
2885 (:include js2-node)
2886 (:constructor nil)
2887 (:constructor make-js2-label-node (&key (type js2-LABEL)
2888 (pos js2-ts-cursor)
2889 len
2890 name)))
2891 "AST node for a statement label or case label."
2892 name ; a string
2893 loop) ; for validating and code-generating continue-to-label
2894
2895 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2896 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2897
2898 (defun js2-print-label (n i)
2899 (insert (js2-make-pad i)
2900 (js2-label-node-name n)
2901 ":\n"))
2902
2903 (defstruct (js2-labeled-stmt-node
2904 (:include js2-node)
2905 (:constructor nil)
2906 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2907 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2908 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2909 (pos js2-ts-cursor)
2910 len
2911 labels
2912 stmt)))
2913 "AST node for a statement with one or more labels.
2914 Multiple labels for a statement are collapsed into the labels field."
2915 labels ; lisp list of `js2-label-node'
2916 stmt) ; the statement these labels are for
2917
2918 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2919 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2920
2921 (defun js2-get-label-by-name (lbl-stmt name)
2922 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2923 Returns nil if no such label is in the list."
2924 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2925 result)
2926 (while (and label-list (not result))
2927 (if (string= (js2-label-node-name (car label-list)) name)
2928 (setq result (car label-list))
2929 (setq label-list (cdr label-list))))
2930 result))
2931
2932 (defun js2-visit-labeled-stmt (n v)
2933 (dolist (label (js2-labeled-stmt-node-labels n))
2934 (js2-visit-ast label v))
2935 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2936
2937 (defun js2-print-labeled-stmt (n i)
2938 (dolist (label (js2-labeled-stmt-node-labels n))
2939 (js2-print-ast label i))
2940 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2941
2942 (defun js2-labeled-stmt-node-contains (node label)
2943 "Return t if NODE contains LABEL in its label set.
2944 NODE is a `js2-labels-node'. LABEL is an identifier."
2945 (loop for nl in (js2-labeled-stmt-node-labels node)
2946 if (string= label (js2-label-node-name nl))
2947 return t
2948 finally return nil))
2949
2950 (defsubst js2-labeled-stmt-node-add-label (node label)
2951 "Add a `js2-label-node' to the label set for this statement."
2952 (setf (js2-labeled-stmt-node-labels node)
2953 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2954
2955 (defstruct (js2-jump-node
2956 (:include js2-node)
2957 (:constructor nil))
2958 "Abstract supertype of break and continue nodes."
2959 label ; `js2-name-node' for location of label identifier, if present
2960 target) ; target js2-labels-node or loop/switch statement
2961
2962 (defun js2-visit-jump-node (n v)
2963 (js2-visit-ast (js2-jump-node-label n) v))
2964
2965 (defstruct (js2-break-node
2966 (:include js2-jump-node)
2967 (:constructor nil)
2968 (:constructor make-js2-break-node (&key (type js2-BREAK)
2969 (pos js2-ts-cursor)
2970 len
2971 label
2972 target)))
2973 "AST node for a break statement.
2974 The label field is a `js2-name-node', possibly nil, for the named label
2975 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2976 is the target of the break - a label node or enclosing loop/switch statement.")
2977
2978 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2979 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2980
2981 (defun js2-print-break-node (n i)
2982 (insert (js2-make-pad i) "break")
2983 (when (js2-break-node-label n)
2984 (insert " ")
2985 (js2-print-ast (js2-break-node-label n) 0))
2986 (insert ";\n"))
2987
2988 (defstruct (js2-continue-node
2989 (:include js2-jump-node)
2990 (:constructor nil)
2991 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2992 (pos js2-ts-cursor)
2993 len
2994 label
2995 target)))
2996 "AST node for a continue statement.
2997 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2998 It is nil if continue specifies no label. The target field is the jump target:
2999 a `js2-label-node' or the innermost enclosing loop.")
3000
3001 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3002 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3003
3004 (defun js2-print-continue-node (n i)
3005 (insert (js2-make-pad i) "continue")
3006 (when (js2-continue-node-label n)
3007 (insert " ")
3008 (js2-print-ast (js2-continue-node-label n) 0))
3009 (insert ";\n"))
3010
3011 (defstruct (js2-function-node
3012 (:include js2-script-node)
3013 (:constructor nil)
3014 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3015 (pos js2-ts-cursor)
3016 len
3017 (ftype 'FUNCTION)
3018 (form 'FUNCTION_STATEMENT)
3019 (name "")
3020 params rest-p
3021 body
3022 lp rp)))
3023 "AST node for a function declaration.
3024 The `params' field is a lisp list of nodes. Each node is either a simple
3025 `js2-name-node', or if it's a destructuring-assignment parameter, a
3026 `js2-array-node' or `js2-object-node'."
3027 ftype ; FUNCTION, GETTER or SETTER
3028 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3029 name ; function name (a `js2-name-node', or nil if anonymous)
3030 params ; a lisp list of destructuring forms or simple name nodes
3031 rest-p ; if t, the last parameter is rest parameter
3032 body ; a `js2-block-node' or expression node (1.8 only)
3033 lp ; position of arg-list open-paren, or nil if omitted
3034 rp ; position of arg-list close-paren, or nil if omitted
3035 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3036 needs-activation ; t if we need an activation object for this frame
3037 is-generator ; t if this function contains a yield
3038 member-expr) ; nonstandard Ecma extension from Rhino
3039
3040 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3041 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3042
3043 (defun js2-visit-function-node (n v)
3044 (js2-visit-ast (js2-function-node-name n) v)
3045 (dolist (p (js2-function-node-params n))
3046 (js2-visit-ast p v))
3047 (js2-visit-ast (js2-function-node-body n) v))
3048
3049 (defun js2-print-function-node (n i)
3050 (let ((pad (js2-make-pad i))
3051 (getter (js2-node-get-prop n 'GETTER_SETTER))
3052 (name (js2-function-node-name n))
3053 (params (js2-function-node-params n))
3054 (rest-p (js2-function-node-rest-p n))
3055 (body (js2-function-node-body n))
3056 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3057 (unless getter
3058 (insert pad "function"))
3059 (when name
3060 (insert " ")
3061 (js2-print-ast name 0))
3062 (insert "(")
3063 (loop with len = (length params)
3064 for param in params
3065 for count from 1
3066 do
3067 (when (and rest-p (= count len))
3068 (insert "..."))
3069 (js2-print-ast param 0)
3070 (when (< count len)
3071 (insert ", ")))
3072 (insert ") {")
3073 (unless expr
3074 (insert "\n"))
3075 ;; TODO: fix this to be smarter about indenting, etc.
3076 (js2-print-body body (1+ i))
3077 (insert pad "}")
3078 (unless expr
3079 (insert "\n"))))
3080
3081 (defsubst js2-function-name (node)
3082 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3083 (and (js2-function-node-name node)
3084 (js2-name-node-name (js2-function-node-name node))))
3085
3086 ;; Having this be an expression node makes it more flexible.
3087 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3088 ;; that work better if you assume it's an expression. Whenever we have
3089 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3090 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3091 (defstruct (js2-var-decl-node
3092 (:include js2-node)
3093 (:constructor nil)
3094 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3095 (pos js2-token-beg)
3096 len
3097 kids
3098 decl-type)))
3099 "AST node for a variable declaration list (VAR, CONST or LET).
3100 The node bounds differ depending on the declaration type. For VAR or
3101 CONST declarations, the bounds include the var/const keyword. For LET
3102 declarations, the node begins at the position of the first child."
3103 kids ; a lisp list of `js2-var-init-node' structs.
3104 decl-type) ; js2-VAR, js2-CONST or js2-LET
3105
3106 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3107 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3108
3109 (defun js2-visit-var-decl (n v)
3110 (dolist (kid (js2-var-decl-node-kids n))
3111 (js2-visit-ast kid v)))
3112
3113 (defun js2-print-var-decl (n i)
3114 (let ((pad (js2-make-pad i))
3115 (tt (js2-var-decl-node-decl-type n)))
3116 (insert pad)
3117 (insert (cond
3118 ((= tt js2-VAR) "var ")
3119 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3120 ((= tt js2-CONST) "const ")
3121 (t
3122 (error "malformed var-decl node"))))
3123 (loop with kids = (js2-var-decl-node-kids n)
3124 with len = (length kids)
3125 for kid in kids
3126 for count from 1
3127 do
3128 (js2-print-ast kid 0)
3129 (if (< count len)
3130 (insert ", ")))))
3131
3132 (defstruct (js2-var-init-node
3133 (:include js2-node)
3134 (:constructor nil)
3135 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3136 (pos js2-ts-cursor)
3137 len
3138 target
3139 initializer)))
3140 "AST node for a variable declaration.
3141 The type field will be js2-CONST for a const decl."
3142 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3143 initializer) ; initializer expression, a `js2-node'
3144
3145 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3146 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3147
3148 (defun js2-visit-var-init-node (n v)
3149 (js2-visit-ast (js2-var-init-node-target n) v)
3150 (js2-visit-ast (js2-var-init-node-initializer n) v))
3151
3152 (defun js2-print-var-init-node (n i)
3153 (let ((pad (js2-make-pad i))
3154 (name (js2-var-init-node-target n))
3155 (init (js2-var-init-node-initializer n)))
3156 (insert pad)
3157 (js2-print-ast name 0)
3158 (when init
3159 (insert " = ")
3160 (js2-print-ast init 0))))
3161
3162 (defstruct (js2-cond-node
3163 (:include js2-node)
3164 (:constructor nil)
3165 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3166 (pos js2-ts-cursor)
3167 len
3168 test-expr
3169 true-expr
3170 false-expr
3171 q-pos
3172 c-pos)))
3173 "AST node for the ternary operator"
3174 test-expr
3175 true-expr
3176 false-expr
3177 q-pos ; buffer position of ?
3178 c-pos) ; buffer position of :
3179
3180 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3181 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3182
3183 (defun js2-visit-cond-node (n v)
3184 (js2-visit-ast (js2-cond-node-test-expr n) v)
3185 (js2-visit-ast (js2-cond-node-true-expr n) v)
3186 (js2-visit-ast (js2-cond-node-false-expr n) v))
3187
3188 (defun js2-print-cond-node (n i)
3189 (let ((pad (js2-make-pad i)))
3190 (insert pad)
3191 (js2-print-ast (js2-cond-node-test-expr n) 0)
3192 (insert " ? ")
3193 (js2-print-ast (js2-cond-node-true-expr n) 0)
3194 (insert " : ")
3195 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3196
3197 (defstruct (js2-infix-node
3198 (:include js2-node)
3199 (:constructor nil)
3200 (:constructor make-js2-infix-node (&key type
3201 (pos js2-ts-cursor)
3202 len
3203 op-pos
3204 left
3205 right)))
3206 "Represents infix expressions.
3207 Includes assignment ops like `|=', and the comma operator.
3208 The type field inherited from `js2-node' holds the operator."
3209 op-pos ; buffer position where operator begins
3210 left ; any `js2-node'
3211 right) ; any `js2-node'
3212
3213 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3214 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3215
3216 (defun js2-visit-infix-node (n v)
3217 (js2-visit-ast (js2-infix-node-left n) v)
3218 (js2-visit-ast (js2-infix-node-right n) v))
3219
3220 (defconst js2-operator-tokens
3221 (let ((table (make-hash-table :test 'eq))
3222 (tokens
3223 (list (cons js2-IN "in")
3224 (cons js2-TYPEOF "typeof")
3225 (cons js2-INSTANCEOF "instanceof")
3226 (cons js2-DELPROP "delete")
3227 (cons js2-COMMA ",")
3228 (cons js2-COLON ":")
3229 (cons js2-OR "||")
3230 (cons js2-AND "&&")
3231 (cons js2-INC "++")
3232 (cons js2-DEC "--")
3233 (cons js2-BITOR "|")
3234 (cons js2-BITXOR "^")
3235 (cons js2-BITAND "&")
3236 (cons js2-EQ "==")
3237 (cons js2-NE "!=")
3238 (cons js2-LT "<")
3239 (cons js2-LE "<=")
3240 (cons js2-GT ">")
3241 (cons js2-GE ">=")
3242 (cons js2-LSH "<<")
3243 (cons js2-RSH ">>")
3244 (cons js2-URSH ">>>")
3245 (cons js2-ADD "+") ; infix plus
3246 (cons js2-SUB "-") ; infix minus
3247 (cons js2-MUL "*")
3248 (cons js2-DIV "/")
3249 (cons js2-MOD "%")
3250 (cons js2-NOT "!")
3251 (cons js2-BITNOT "~")
3252 (cons js2-POS "+") ; unary plus
3253 (cons js2-NEG "-") ; unary minus
3254 (cons js2-SHEQ "===") ; shallow equality
3255 (cons js2-SHNE "!==") ; shallow inequality
3256 (cons js2-ASSIGN "=")
3257 (cons js2-ASSIGN_BITOR "|=")
3258 (cons js2-ASSIGN_BITXOR "^=")
3259 (cons js2-ASSIGN_BITAND "&=")
3260 (cons js2-ASSIGN_LSH "<<=")
3261 (cons js2-ASSIGN_RSH ">>=")
3262 (cons js2-ASSIGN_URSH ">>>=")
3263 (cons js2-ASSIGN_ADD "+=")
3264 (cons js2-ASSIGN_SUB "-=")
3265 (cons js2-ASSIGN_MUL "*=")
3266 (cons js2-ASSIGN_DIV "/=")
3267 (cons js2-ASSIGN_MOD "%="))))
3268 (loop for (k . v) in tokens do
3269 (puthash k v table))
3270 table))
3271
3272 (defun js2-print-infix-node (n i)
3273 (let* ((tt (js2-node-type n))
3274 (op (gethash tt js2-operator-tokens)))
3275 (unless op
3276 (error "unrecognized infix operator %s" (js2-node-type n)))
3277 (insert (js2-make-pad i))
3278 (js2-print-ast (js2-infix-node-left n) 0)
3279 (unless (= tt js2-COMMA)
3280 (insert " "))
3281 (insert op)
3282 (insert " ")
3283 (js2-print-ast (js2-infix-node-right n) 0)))
3284
3285 (defstruct (js2-assign-node
3286 (:include js2-infix-node)
3287 (:constructor nil)
3288 (:constructor make-js2-assign-node (&key type
3289 (pos js2-ts-cursor)
3290 len
3291 op-pos
3292 left
3293 right)))
3294 "Represents any assignment.
3295 The type field holds the actual assignment operator.")
3296
3297 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3298 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3299
3300 (defstruct (js2-unary-node
3301 (:include js2-node)
3302 (:constructor nil)
3303 (:constructor make-js2-unary-node (&key type ; required
3304 (pos js2-ts-cursor)
3305 len
3306 operand)))
3307 "AST node type for unary operator nodes.
3308 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3309 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3310 property is added if the operator follows the operand."
3311 operand) ; a `js2-node' expression
3312
3313 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3314 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3315
3316 (defun js2-visit-unary-node (n v)
3317 (js2-visit-ast (js2-unary-node-operand n) v))
3318
3319 (defun js2-print-unary-node (n i)
3320 (let* ((tt (js2-node-type n))
3321 (op (gethash tt js2-operator-tokens))
3322 (postfix (js2-node-get-prop n 'postfix)))
3323 (unless op
3324 (error "unrecognized unary operator %s" tt))
3325 (insert (js2-make-pad i))
3326 (unless postfix
3327 (insert op))
3328 (if (or (= tt js2-TYPEOF)
3329 (= tt js2-DELPROP))
3330 (insert " "))
3331 (js2-print-ast (js2-unary-node-operand n) 0)
3332 (when postfix
3333 (insert op))))
3334
3335 (defstruct (js2-let-node
3336 (:include js2-scope)
3337 (:constructor nil)
3338 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3339 (pos js2-token-beg)
3340 len
3341 vars
3342 body
3343 lp
3344 rp)))
3345 "AST node for a let expression or a let statement.
3346 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3347 vars ; a `js2-var-decl-node'
3348 body ; a `js2-node' representing the expression or body block
3349 lp
3350 rp)
3351
3352 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3353 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3354
3355 (defun js2-visit-let-node (n v)
3356 (js2-visit-ast (js2-let-node-vars n) v)
3357 (js2-visit-ast (js2-let-node-body n) v))
3358
3359 (defun js2-print-let-node (n i)
3360 (insert (js2-make-pad i) "let (")
3361 (js2-print-ast (js2-let-node-vars n) 0)
3362 (insert ") ")
3363 (js2-print-ast (js2-let-node-body n) i))
3364
3365 (defstruct (js2-keyword-node
3366 (:include js2-node)
3367 (:constructor nil)
3368 (:constructor make-js2-keyword-node (&key type
3369 (pos js2-token-beg)
3370 (len (- js2-ts-cursor pos)))))
3371 "AST node representing a literal keyword such as `null'.
3372 Used for `null', `this', `true', `false' and `debugger'.
3373 The node type is set to js2-NULL, js2-THIS, etc.")
3374
3375 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3376 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3377
3378 (defun js2-print-keyword-node (n i)
3379 (insert (js2-make-pad i)
3380 (let ((tt (js2-node-type n)))
3381 (cond
3382 ((= tt js2-THIS) "this")
3383 ((= tt js2-NULL) "null")
3384 ((= tt js2-TRUE) "true")
3385 ((= tt js2-FALSE) "false")
3386 ((= tt js2-DEBUGGER) "debugger")
3387 (t (error "Invalid keyword literal type: %d" tt))))))
3388
3389 (defsubst js2-this-node-p (node)
3390 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3391 (eq (js2-node-type node) js2-THIS))
3392
3393 (defstruct (js2-new-node
3394 (:include js2-node)
3395 (:constructor nil)
3396 (:constructor make-js2-new-node (&key (type js2-NEW)
3397 (pos js2-token-beg)
3398 len
3399 target
3400 args
3401 initializer
3402 lp
3403 rp)))
3404 "AST node for new-expression such as new Foo()."
3405 target ; an identifier or reference
3406 args ; a lisp list of argument nodes
3407 lp ; position of left-paren, nil if omitted
3408 rp ; position of right-paren, nil if omitted
3409 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3410
3411 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3412 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3413
3414 (defun js2-visit-new-node (n v)
3415 (js2-visit-ast (js2-new-node-target n) v)
3416 (dolist (arg (js2-new-node-args n))
3417 (js2-visit-ast arg v))
3418 (js2-visit-ast (js2-new-node-initializer n) v))
3419
3420 (defun js2-print-new-node (n i)
3421 (insert (js2-make-pad i) "new ")
3422 (js2-print-ast (js2-new-node-target n))
3423 (insert "(")
3424 (js2-print-list (js2-new-node-args n))
3425 (insert ")")
3426 (when (js2-new-node-initializer n)
3427 (insert " ")
3428 (js2-print-ast (js2-new-node-initializer n))))
3429
3430 (defstruct (js2-name-node
3431 (:include js2-node)
3432 (:constructor nil)
3433 (:constructor make-js2-name-node (&key (type js2-NAME)
3434 (pos js2-token-beg)
3435 (len (- js2-ts-cursor
3436 js2-token-beg))
3437 (name js2-ts-string))))
3438 "AST node for a JavaScript identifier"
3439 name ; a string
3440 scope) ; a `js2-scope' (optional, used for codegen)
3441
3442 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3443 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3444
3445 (defun js2-print-name-node (n i)
3446 (insert (js2-make-pad i)
3447 (js2-name-node-name n)))
3448
3449 (defsubst js2-name-node-length (node)
3450 "Return identifier length of NODE, a `js2-name-node'.
3451 Returns 0 if NODE is nil or its identifier field is nil."
3452 (if node
3453 (length (js2-name-node-name node))
3454 0))
3455
3456 (defstruct (js2-number-node
3457 (:include js2-node)
3458 (:constructor nil)
3459 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3460 (pos js2-token-beg)
3461 (len (- js2-ts-cursor
3462 js2-token-beg))
3463 (value js2-ts-string)
3464 (num-value js2-ts-number))))
3465 "AST node for a number literal."
3466 value ; the original string, e.g. "6.02e23"
3467 num-value) ; the parsed number value
3468
3469 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3470 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3471
3472 (defun js2-print-number-node (n i)
3473 (insert (js2-make-pad i)
3474 (number-to-string (js2-number-node-num-value n))))
3475
3476 (defstruct (js2-regexp-node
3477 (:include js2-node)
3478 (:constructor nil)
3479 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3480 (pos js2-token-beg)
3481 (len (- js2-ts-cursor
3482 js2-token-beg))
3483 value
3484 flags)))
3485 "AST node for a regular expression literal."
3486 value ; the regexp string, without // delimiters
3487 flags) ; a string of flags, e.g. `mi'.
3488
3489 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3490 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3491
3492 (defun js2-print-regexp (n i)
3493 (insert (js2-make-pad i)
3494 "/"
3495 (js2-regexp-node-value n)
3496 "/")
3497 (if (js2-regexp-node-flags n)
3498 (insert (js2-regexp-node-flags n))))
3499
3500 (defstruct (js2-string-node
3501 (:include js2-node)
3502 (:constructor nil)
3503 (:constructor make-js2-string-node (&key (type js2-STRING)
3504 (pos js2-token-beg)
3505 (len (- js2-ts-cursor
3506 js2-token-beg))
3507 (value js2-ts-string))))
3508 "String literal.
3509 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3510 You can tell the quote type by looking at the first character."
3511 value) ; the characters of the string, including the quotes
3512
3513 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3514 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3515
3516 (defun js2-print-string-node (n i)
3517 (insert (js2-make-pad i)
3518 (js2-node-string n)))
3519
3520 (defstruct (js2-array-node
3521 (:include js2-node)
3522 (:constructor nil)
3523 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3524 (pos js2-ts-cursor)
3525 len
3526 elems)))
3527 "AST node for an array literal."
3528 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3529
3530 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3531 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3532
3533 (defun js2-visit-array-node (n v)
3534 (dolist (e (js2-array-node-elems n))
3535 (js2-visit-ast e v)))
3536
3537 (defun js2-print-array-node (n i)
3538 (insert (js2-make-pad i) "[")
3539 (js2-print-list (js2-array-node-elems n))
3540 (insert "]"))
3541
3542 (defstruct (js2-object-node
3543 (:include js2-node)
3544 (:constructor nil)
3545 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3546 (pos js2-ts-cursor)
3547 len
3548 elems)))
3549 "AST node for an object literal expression.
3550 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3551 the latter represents abbreviation in destructuring expressions."
3552 elems)
3553
3554 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3555 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3556
3557 (defun js2-visit-object-node (n v)
3558 (dolist (e (js2-object-node-elems n))
3559 (js2-visit-ast e v)))
3560
3561 (defun js2-print-object-node (n i)
3562 (insert (js2-make-pad i) "{")
3563 (js2-print-list (js2-object-node-elems n))
3564 (insert "}"))
3565
3566 (defstruct (js2-object-prop-node
3567 (:include js2-infix-node)
3568 (:constructor nil)
3569 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3570 (pos js2-ts-cursor)
3571 len
3572 left
3573 right
3574 op-pos)))
3575 "AST node for an object literal prop:value entry.
3576 The `left' field is the property: a name node, string node or number node.
3577 The `right' field is a `js2-node' representing the initializer value.")
3578
3579 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3580 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3581
3582 (defun js2-print-object-prop-node (n i)
3583 (insert (js2-make-pad i))
3584 (js2-print-ast (js2-object-prop-node-left n) 0)
3585 (insert ": ")
3586 (js2-print-ast (js2-object-prop-node-right n) 0))
3587
3588 (defstruct (js2-getter-setter-node
3589 (:include js2-infix-node)
3590 (:constructor nil)
3591 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3592 (pos js2-ts-cursor)
3593 len
3594 left
3595 right)))
3596 "AST node for a getter/setter property in an object literal.
3597 The `left' field is the `js2-name-node' naming the getter/setter prop.
3598 The `right' field is always an anonymous `js2-function-node' with a node
3599 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3600
3601 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3602 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3603
3604 (defun js2-print-getter-setter (n i)
3605 (let ((pad (js2-make-pad i))
3606 (left (js2-getter-setter-node-left n))
3607 (right (js2-getter-setter-node-right n)))
3608 (insert pad)
3609 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3610 (js2-print-ast left 0)
3611 (js2-print-ast right 0)))
3612
3613 (defstruct (js2-prop-get-node
3614 (:include js2-infix-node)
3615 (:constructor nil)
3616 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3617 (pos js2-ts-cursor)
3618 len
3619 left
3620 right)))
3621 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3622
3623 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3624 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3625
3626 (defun js2-visit-prop-get-node (n v)
3627 (js2-visit-ast (js2-prop-get-node-left n) v)
3628 (js2-visit-ast (js2-prop-get-node-right n) v))
3629
3630 (defun js2-print-prop-get-node (n i)
3631 (insert (js2-make-pad i))
3632 (js2-print-ast (js2-prop-get-node-left n) 0)
3633 (insert ".")
3634 (js2-print-ast (js2-prop-get-node-right n) 0))
3635
3636 (defstruct (js2-elem-get-node
3637 (:include js2-node)
3638 (:constructor nil)
3639 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3640 (pos js2-ts-cursor)
3641 len
3642 target
3643 element
3644 lb
3645 rb)))
3646 "AST node for an array index expression such as foo[bar]."
3647 target ; a `js2-node' - the expression preceding the "."
3648 element ; a `js2-node' - the expression in brackets
3649 lb ; position of left-bracket, nil if omitted
3650 rb) ; position of right-bracket, nil if omitted
3651
3652 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3653 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3654
3655 (defun js2-visit-elem-get-node (n v)
3656 (js2-visit-ast (js2-elem-get-node-target n) v)
3657 (js2-visit-ast (js2-elem-get-node-element n) v))
3658
3659 (defun js2-print-elem-get-node (n i)
3660 (insert (js2-make-pad i))
3661 (js2-print-ast (js2-elem-get-node-target n) 0)
3662 (insert "[")
3663 (js2-print-ast (js2-elem-get-node-element n) 0)
3664 (insert "]"))
3665
3666 (defstruct (js2-call-node
3667 (:include js2-node)
3668 (:constructor nil)
3669 (:constructor make-js2-call-node (&key (type js2-CALL)
3670 (pos js2-ts-cursor)
3671 len
3672 target
3673 args
3674 lp
3675 rp)))
3676 "AST node for a JavaScript function call."
3677 target ; a `js2-node' evaluating to the function to call
3678 args ; a lisp list of `js2-node' arguments
3679 lp ; position of open-paren, or nil if missing
3680 rp) ; position of close-paren, or nil if missing
3681
3682 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3683 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3684
3685 (defun js2-visit-call-node (n v)
3686 (js2-visit-ast (js2-call-node-target n) v)
3687 (dolist (arg (js2-call-node-args n))
3688 (js2-visit-ast arg v)))
3689
3690 (defun js2-print-call-node (n i)
3691 (insert (js2-make-pad i))
3692 (js2-print-ast (js2-call-node-target n) 0)
3693 (insert "(")
3694 (js2-print-list (js2-call-node-args n))
3695 (insert ")"))
3696
3697 (defstruct (js2-yield-node
3698 (:include js2-node)
3699 (:constructor nil)
3700 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3701 (pos js2-ts-cursor)
3702 len
3703 value)))
3704 "AST node for yield statement or expression."
3705 value) ; optional: value to be yielded
3706
3707 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3708 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3709
3710 (defun js2-visit-yield-node (n v)
3711 (js2-visit-ast (js2-yield-node-value n) v))
3712
3713 (defun js2-print-yield-node (n i)
3714 (insert (js2-make-pad i))
3715 (insert "yield")
3716 (when (js2-yield-node-value n)
3717 (insert " ")
3718 (js2-print-ast (js2-yield-node-value n) 0)))
3719
3720 (defstruct (js2-paren-node
3721 (:include js2-node)
3722 (:constructor nil)
3723 (:constructor make-js2-paren-node (&key (type js2-LP)
3724 (pos js2-ts-cursor)
3725 len
3726 expr)))
3727 "AST node for a parenthesized expression.
3728 In particular, used when the parens are syntactically optional,
3729 as opposed to required parens such as those enclosing an if-conditional."
3730 expr) ; `js2-node'
3731
3732 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3733 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3734
3735 (defun js2-visit-paren-node (n v)
3736 (js2-visit-ast (js2-paren-node-expr n) v))
3737
3738 (defun js2-print-paren-node (n i)
3739 (insert (js2-make-pad i))
3740 (insert "(")
3741 (js2-print-ast (js2-paren-node-expr n) 0)
3742 (insert ")"))
3743
3744 (defstruct (js2-array-comp-node
3745 (:include js2-scope)
3746 (:constructor nil)
3747 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3748 (pos js2-ts-cursor)
3749 len
3750 result
3751 loops
3752 filter
3753 if-pos
3754 lp
3755 rp)))
3756 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3757 result ; result expression (just after left-bracket)
3758 loops ; a lisp list of `js2-array-comp-loop-node'
3759 filter ; guard/filter expression
3760 if-pos ; buffer pos of 'if' keyword, if present, else nil
3761 lp ; buffer position of if-guard left-paren, or nil if not present
3762 rp) ; buffer position of if-guard right-paren, or nil if not present
3763
3764 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3765 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3766
3767 (defun js2-visit-array-comp-node (n v)
3768 (js2-visit-ast (js2-array-comp-node-result n) v)
3769 (dolist (l (js2-array-comp-node-loops n))
3770 (js2-visit-ast l v))
3771 (js2-visit-ast (js2-array-comp-node-filter n) v))
3772
3773 (defun js2-print-array-comp-node (n i)
3774 (let ((pad (js2-make-pad i))
3775 (result (js2-array-comp-node-result n))
3776 (loops (js2-array-comp-node-loops n))
3777 (filter (js2-array-comp-node-filter n)))
3778 (insert pad "[")
3779 (js2-print-ast result 0)
3780 (dolist (l loops)
3781 (insert " ")
3782 (js2-print-ast l 0))
3783 (when filter
3784 (insert " if (")
3785 (js2-print-ast filter 0)
3786 (insert ")"))
3787 (insert "]")))
3788
3789 (defstruct (js2-array-comp-loop-node
3790 (:include js2-for-in-node)
3791 (:constructor nil)
3792 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3793 (pos js2-ts-cursor)
3794 len
3795 iterator
3796 object
3797 in-pos
3798 foreach-p
3799 each-pos
3800 forof-p
3801 lp rp)))
3802 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3803
3804 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3805 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3806
3807 (defun js2-visit-array-comp-loop (n v)
3808 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3809 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3810
3811 (defun js2-print-array-comp-loop (n i)
3812 (insert "for (")
3813 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3814 (if (js2-array-comp-loop-node-forof-p n)
3815 (insert " of ")
3816 (insert " in "))
3817 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3818 (insert ")"))
3819
3820 (defstruct (js2-empty-expr-node
3821 (:include js2-node)
3822 (:constructor nil)
3823 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3824 (pos js2-token-beg)
3825 len)))
3826 "AST node for an empty expression.")
3827
3828 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3829 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3830
3831 (defstruct (js2-xml-node
3832 (:include js2-block-node)
3833 (:constructor nil)
3834 (:constructor make-js2-xml-node (&key (type js2-XML)
3835 (pos js2-token-beg)
3836 len
3837 kids)))
3838 "AST node for initial parse of E4X literals.
3839 The kids field is a list of XML fragments, each a `js2-string-node' or
3840 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3841
3842 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3843 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3844
3845 (defun js2-print-xml-node (n i)
3846 (dolist (kid (js2-xml-node-kids n))
3847 (js2-print-ast kid i)))
3848
3849 (defstruct (js2-xml-js-expr-node
3850 (:include js2-xml-node)
3851 (:constructor nil)
3852 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3853 (pos js2-ts-cursor)
3854 len
3855 expr)))
3856 "AST node for an embedded JavaScript {expression} in an E4X literal.
3857 The start and end fields correspond to the curly-braces."
3858 expr) ; a `js2-expr-node' of some sort
3859
3860 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3861 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3862
3863 (defun js2-visit-xml-js-expr (n v)
3864 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3865
3866 (defun js2-print-xml-js-expr (n i)
3867 (insert (js2-make-pad i))
3868 (insert "{")
3869 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3870 (insert "}"))
3871
3872 (defstruct (js2-xml-dot-query-node
3873 (:include js2-infix-node)
3874 (:constructor nil)
3875 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3876 (pos js2-ts-cursor)
3877 op-pos
3878 len
3879 left
3880 right
3881 rp)))
3882 "AST node for an E4X foo.(bar) filter expression.
3883 Note that the left-paren is automatically the character immediately
3884 following the dot (.) in the operator. No whitespace is permitted
3885 between the dot and the lp by the scanner."
3886 rp)
3887
3888 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3889 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3890
3891 (defun js2-print-xml-dot-query (n i)
3892 (insert (js2-make-pad i))
3893 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3894 (insert ".(")
3895 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3896 (insert ")"))
3897
3898 (defstruct (js2-xml-ref-node
3899 (:include js2-node)
3900 (:constructor nil)) ; abstract
3901 "Base type for E4X XML attribute-access or property-get expressions.
3902 Such expressions can take a variety of forms. The general syntax has
3903 three parts:
3904
3905 - (optional) an @ (specifying an attribute access)
3906 - (optional) a namespace (a `js2-name-node') and double-colon
3907 - (required) either a `js2-name-node' or a bracketed [expression]
3908
3909 The property-name expressions (examples: ns::name, @name) are
3910 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3911 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3912
3913 This node type (or more specifically, its subclasses) will sometimes
3914 be the right-hand child of a `js2-prop-get-node' or a
3915 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3916 The `js2-xml-ref-node' may also be a standalone primary expression with
3917 no explicit target, which is valid in certain expression contexts such as
3918
3919 company..employee.(@id < 100)
3920
3921 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3922 expression whose parent is a `js2-xml-dot-query-node'."
3923 namespace
3924 at-pos
3925 colon-pos)
3926
3927 (defsubst js2-xml-ref-node-attr-access-p (node)
3928 "Return non-nil if this expression began with an @-token."
3929 (and (numberp (js2-xml-ref-node-at-pos node))
3930 (plusp (js2-xml-ref-node-at-pos node))))
3931
3932 (defstruct (js2-xml-prop-ref-node
3933 (:include js2-xml-ref-node)
3934 (:constructor nil)
3935 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3936 (pos js2-token-beg)
3937 len
3938 propname
3939 namespace
3940 at-pos
3941 colon-pos)))
3942 "AST node for an E4X XML [expr] property-ref expression.
3943 The JavaScript syntax is an optional @, an optional ns::, and a name.
3944
3945 [ '@' ] [ name '::' ] name
3946
3947 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3948 @ns::*, @*::attr, @*::*, and @*.
3949
3950 The node starts at the @ token, if present. Otherwise it starts at the
3951 namespace name. The node bounds extend through the closing right-bracket,
3952 or if it is missing due to a syntax error, through the end of the index
3953 expression."
3954 propname)
3955
3956 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3957 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3958
3959 (defun js2-visit-xml-prop-ref-node (n v)
3960 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3961 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3962
3963 (defun js2-print-xml-prop-ref-node (n i)
3964 (insert (js2-make-pad i))
3965 (if (js2-xml-ref-node-attr-access-p n)
3966 (insert "@"))
3967 (when (js2-xml-prop-ref-node-namespace n)
3968 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3969 (insert "::"))
3970 (if (js2-xml-prop-ref-node-propname n)
3971 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3972
3973 (defstruct (js2-xml-elem-ref-node
3974 (:include js2-xml-ref-node)
3975 (:constructor nil)
3976 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3977 (pos js2-token-beg)
3978 len
3979 expr
3980 lb
3981 rb
3982 namespace
3983 at-pos
3984 colon-pos)))
3985 "AST node for an E4X XML [expr] member-ref expression.
3986 Syntax:
3987
3988 [ '@' ] [ name '::' ] '[' expr ']'
3989
3990 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3991
3992 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3993 is not a legal E4X XML element-ref expression, since it's already used
3994 for standard JavaScript element-get array indexing. Hence, a
3995 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3996 non-nil namespace node, or both.
3997
3998 The node starts at the @ token, if present. Otherwise it starts
3999 at the namespace name. The node bounds extend through the closing
4000 right-bracket, or if it is missing due to a syntax error, through the
4001 end of the index expression."
4002 expr ; the bracketed index expression
4003 lb
4004 rb)
4005
4006 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4007 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4008
4009 (defun js2-visit-xml-elem-ref-node (n v)
4010 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4011 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4012
4013 (defun js2-print-xml-elem-ref-node (n i)
4014 (insert (js2-make-pad i))
4015 (if (js2-xml-ref-node-attr-access-p n)
4016 (insert "@"))
4017 (when (js2-xml-elem-ref-node-namespace n)
4018 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4019 (insert "::"))
4020 (insert "[")
4021 (if (js2-xml-elem-ref-node-expr n)
4022 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4023 (insert "]"))
4024
4025 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4026
4027 (defstruct (js2-xml-start-tag-node
4028 (:include js2-xml-node)
4029 (:constructor nil)
4030 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4031 (pos js2-ts-cursor)
4032 len
4033 name
4034 attrs
4035 kids
4036 empty-p)))
4037 "AST node for an XML start-tag. Not currently used.
4038 The `kids' field is a lisp list of child content nodes."
4039 name ; a `js2-xml-name-node'
4040 attrs ; a lisp list of `js2-xml-attr-node'
4041 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4042
4043 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4044 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4045
4046 (defun js2-visit-xml-start-tag (n v)
4047 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4048 (dolist (attr (js2-xml-start-tag-node-attrs n))
4049 (js2-visit-ast attr v))
4050 (js2-visit-block n v))
4051
4052 (defun js2-print-xml-start-tag (n i)
4053 (insert (js2-make-pad i) "<")
4054 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4055 (when (js2-xml-start-tag-node-attrs n)
4056 (insert " ")
4057 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4058 (insert ">"))
4059
4060 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4061 ;; and add the end-tag to the kids list of the parent as well.
4062 (defstruct (js2-xml-end-tag-node
4063 (:include js2-xml-node)
4064 (:constructor nil)
4065 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4066 (pos js2-ts-cursor)
4067 len
4068 name)))
4069 "AST node for an XML end-tag. Not currently used."
4070 name) ; a `js2-xml-name-node'
4071
4072 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4073 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4074
4075 (defun js2-visit-xml-end-tag (n v)
4076 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4077
4078 (defun js2-print-xml-end-tag (n i)
4079 (insert (js2-make-pad i))
4080 (insert "</")
4081 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4082 (insert ">"))
4083
4084 (defstruct (js2-xml-name-node
4085 (:include js2-xml-node)
4086 (:constructor nil)
4087 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4088 (pos js2-ts-cursor)
4089 len
4090 namespace
4091 kids)))
4092 "AST node for an E4X XML name. Not currently used.
4093 Any XML name can be qualified with a namespace, hence the namespace field.
4094 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4095 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4096 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4097 namespace) ; a `js2-string-node'
4098
4099 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4100 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4101
4102 (defun js2-visit-xml-name-node (n v)
4103 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4104
4105 (defun js2-print-xml-name-node (n i)
4106 (insert (js2-make-pad i))
4107 (when (js2-xml-name-node-namespace n)
4108 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4109 (insert "::"))
4110 (dolist (kid (js2-xml-name-node-kids n))
4111 (js2-print-ast kid 0)))
4112
4113 (defstruct (js2-xml-pi-node
4114 (:include js2-xml-node)
4115 (:constructor nil)
4116 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4117 (pos js2-ts-cursor)
4118 len
4119 name
4120 attrs)))
4121 "AST node for an E4X XML processing instruction. Not currently used."
4122 name ; a `js2-xml-name-node'
4123 attrs) ; a list of `js2-xml-attr-node'
4124
4125 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4126 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4127
4128 (defun js2-visit-xml-pi-node (n v)
4129 (js2-visit-ast (js2-xml-pi-node-name n) v)
4130 (dolist (attr (js2-xml-pi-node-attrs n))
4131 (js2-visit-ast attr v)))
4132
4133 (defun js2-print-xml-pi-node (n i)
4134 (insert (js2-make-pad i) "<?")
4135 (js2-print-ast (js2-xml-pi-node-name n))
4136 (when (js2-xml-pi-node-attrs n)
4137 (insert " ")
4138 (js2-print-list (js2-xml-pi-node-attrs n)))
4139 (insert "?>"))
4140
4141 (defstruct (js2-xml-cdata-node
4142 (:include js2-xml-node)
4143 (:constructor nil)
4144 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4145 (pos js2-ts-cursor)
4146 len
4147 content)))
4148 "AST node for a CDATA escape section. Not currently used."
4149 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4150
4151 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4152 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4153
4154 (defun js2-visit-xml-cdata-node (n v)
4155 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4156
4157 (defun js2-print-xml-cdata-node (n i)
4158 (insert (js2-make-pad i))
4159 (js2-print-ast (js2-xml-cdata-node-content n)))
4160
4161 (defstruct (js2-xml-attr-node
4162 (:include js2-xml-node)
4163 (:constructor nil)
4164 (:constructor make-js2-attr-node (&key (type js2-XML)
4165 (pos js2-ts-cursor)
4166 len
4167 name
4168 value
4169 eq-pos
4170 quote-type)))
4171 "AST node representing a foo='bar' XML attribute value. Not yet used."
4172 name ; a `js2-xml-name-node'
4173 value ; a `js2-xml-name-node'
4174 eq-pos ; buffer position of "=" sign
4175 quote-type) ; 'single or 'double
4176
4177 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4178 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4179
4180 (defun js2-visit-xml-attr-node (n v)
4181 (js2-visit-ast (js2-xml-attr-node-name n) v)
4182 (js2-visit-ast (js2-xml-attr-node-value n) v))
4183
4184 (defun js2-print-xml-attr-node (n i)
4185 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4186 "'"
4187 "\"")))
4188 (insert (js2-make-pad i))
4189 (js2-print-ast (js2-xml-attr-node-name n) 0)
4190 (insert "=" quote)
4191 (js2-print-ast (js2-xml-attr-node-value n) 0)
4192 (insert quote)))
4193
4194 (defstruct (js2-xml-text-node
4195 (:include js2-xml-node)
4196 (:constructor nil)
4197 (:constructor make-js2-text-node (&key (type js2-XML)
4198 (pos js2-ts-cursor)
4199 len
4200 content)))
4201 "AST node for an E4X XML text node. Not currently used."
4202 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4203
4204 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4205 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4206
4207 (defun js2-visit-xml-text-node (n v)
4208 (js2-visit-ast (js2-xml-text-node-content n) v))
4209
4210 (defun js2-print-xml-text-node (n i)
4211 (insert (js2-make-pad i))
4212 (dolist (kid (js2-xml-text-node-content n))
4213 (js2-print-ast kid)))
4214
4215 (defstruct (js2-xml-comment-node
4216 (:include js2-xml-node)
4217 (:constructor nil)
4218 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4219 (pos js2-ts-cursor)
4220 len)))
4221 "AST node for E4X XML comment. Not currently used.")
4222
4223 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4224 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4225
4226 (defun js2-print-xml-comment (n i)
4227 (insert (js2-make-pad i)
4228 (js2-node-string n)))
4229
4230 ;;; Node utilities
4231
4232 (defsubst js2-node-line (n)
4233 "Fetch the source line number at the start of node N.
4234 This is O(n) in the length of the source buffer; use prudently."
4235 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4236
4237 (defsubst js2-block-node-kid (n i)
4238 "Return child I of node N, or nil if there aren't that many."
4239 (nth i (js2-block-node-kids n)))
4240
4241 (defsubst js2-block-node-first (n)
4242 "Return first child of block node N, or nil if there is none."
4243 (first (js2-block-node-kids n)))
4244
4245 (defun js2-node-root (n)
4246 "Return the root of the AST containing N.
4247 If N has no parent pointer, returns N."
4248 (let ((parent (js2-node-parent n)))
4249 (if parent
4250 (js2-node-root parent)
4251 n)))
4252
4253 (defun js2-node-position-in-parent (node &optional parent)
4254 "Return the position of NODE in parent's block-kids list.
4255 PARENT can be supplied if known. Positioned returned is zero-indexed.
4256 Returns 0 if NODE is not a child of a block statement, or if NODE
4257 is not a statement node."
4258 (let ((p (or parent (js2-node-parent node)))
4259 (i 0))
4260 (if (not (js2-block-node-p p))
4261 i
4262 (or (js2-position node (js2-block-node-kids p))
4263 0))))
4264
4265 (defsubst js2-node-short-name (n)
4266 "Return the short name of node N as a string, e.g. `js2-if-node'."
4267 (substring (symbol-name (aref n 0))
4268 (length "cl-struct-")))
4269
4270 (defsubst js2-node-child-list (node)
4271 "Return the child list for NODE, a lisp list of nodes.
4272 Works for block nodes, array nodes, obj literals, funarg lists,
4273 var decls and try nodes (for catch clauses). Note that you should call
4274 `js2-block-node-kids' on the function body for the body statements.
4275 Returns nil for zero-length child lists or unsupported nodes."
4276 (cond
4277 ((js2-function-node-p node)
4278 (js2-function-node-params node))
4279 ((js2-block-node-p node)
4280 (js2-block-node-kids node))
4281 ((js2-try-node-p node)
4282 (js2-try-node-catch-clauses node))
4283 ((js2-array-node-p node)
4284 (js2-array-node-elems node))
4285 ((js2-object-node-p node)
4286 (js2-object-node-elems node))
4287 ((js2-call-node-p node)
4288 (js2-call-node-args node))
4289 ((js2-new-node-p node)
4290 (js2-new-node-args node))
4291 ((js2-var-decl-node-p node)
4292 (js2-var-decl-node-kids node))
4293 (t
4294 nil)))
4295
4296 (defsubst js2-node-set-child-list (node kids)
4297 "Set the child list for NODE to KIDS."
4298 (cond
4299 ((js2-function-node-p node)
4300 (setf (js2-function-node-params node) kids))
4301 ((js2-block-node-p node)
4302 (setf (js2-block-node-kids node) kids))
4303 ((js2-try-node-p node)
4304 (setf (js2-try-node-catch-clauses node) kids))
4305 ((js2-array-node-p node)
4306 (setf (js2-array-node-elems node) kids))
4307 ((js2-object-node-p node)
4308 (setf (js2-object-node-elems node) kids))
4309 ((js2-call-node-p node)
4310 (setf (js2-call-node-args node) kids))
4311 ((js2-new-node-p node)
4312 (setf (js2-new-node-args node) kids))
4313 ((js2-var-decl-node-p node)
4314 (setf (js2-var-decl-node-kids node) kids))
4315 (t
4316 (error "Unsupported node type: %s" (js2-node-short-name node))))
4317 kids)
4318
4319 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4320 (defconst js2-paren-expr-nodes
4321 '(cl-struct-js2-array-comp-loop-node
4322 cl-struct-js2-array-comp-node
4323 cl-struct-js2-call-node
4324 cl-struct-js2-catch-node
4325 cl-struct-js2-do-node
4326 cl-struct-js2-elem-get-node
4327 cl-struct-js2-for-in-node
4328 cl-struct-js2-for-node
4329 cl-struct-js2-function-node
4330 cl-struct-js2-if-node
4331 cl-struct-js2-let-node
4332 cl-struct-js2-new-node
4333 cl-struct-js2-paren-node
4334 cl-struct-js2-switch-node
4335 cl-struct-js2-while-node
4336 cl-struct-js2-with-node
4337 cl-struct-js2-xml-dot-query-node)
4338 "Node types that can have a parenthesized child expression.
4339 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4340
4341 (defsubst js2-paren-expr-node-p (node)
4342 "Return t for nodes that typically have a parenthesized child expression.
4343 Useful for computing the indentation anchors for arg-lists and conditions.
4344 Note that it may return a false positive, for instance when NODE is
4345 a `js2-new-node' and there are no arguments or parentheses."
4346 (memq (aref node 0) js2-paren-expr-nodes))
4347
4348 ;; Fake polymorphism... yech.
4349 (defsubst js2-node-lp (node)
4350 "Return relative left-paren position for NODE, if applicable.
4351 For `js2-elem-get-node' structs, returns left-bracket position.
4352 Note that the position may be nil in the case of a parse error."
4353 (cond
4354 ((js2-elem-get-node-p node)
4355 (js2-elem-get-node-lb node))
4356 ((js2-loop-node-p node)
4357 (js2-loop-node-lp node))
4358 ((js2-function-node-p node)
4359 (js2-function-node-lp node))
4360 ((js2-if-node-p node)
4361 (js2-if-node-lp node))
4362 ((js2-new-node-p node)
4363 (js2-new-node-lp node))
4364 ((js2-call-node-p node)
4365 (js2-call-node-lp node))
4366 ((js2-paren-node-p node)
4367 (js2-node-pos node))
4368 ((js2-switch-node-p node)
4369 (js2-switch-node-lp node))
4370 ((js2-catch-node-p node)
4371 (js2-catch-node-lp node))
4372 ((js2-let-node-p node)
4373 (js2-let-node-lp node))
4374 ((js2-array-comp-node-p node)
4375 (js2-array-comp-node-lp node))
4376 ((js2-with-node-p node)
4377 (js2-with-node-lp node))
4378 ((js2-xml-dot-query-node-p node)
4379 (1+ (js2-infix-node-op-pos node)))
4380 (t
4381 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4382
4383 ;; Fake polymorphism... blech.
4384 (defsubst js2-node-rp (node)
4385 "Return relative right-paren position for NODE, if applicable.
4386 For `js2-elem-get-node' structs, returns right-bracket position.
4387 Note that the position may be nil in the case of a parse error."
4388 (cond
4389 ((js2-elem-get-node-p node)
4390 (js2-elem-get-node-rb node))
4391 ((js2-loop-node-p node)
4392 (js2-loop-node-rp node))
4393 ((js2-function-node-p node)
4394 (js2-function-node-rp node))
4395 ((js2-if-node-p node)
4396 (js2-if-node-rp node))
4397 ((js2-new-node-p node)
4398 (js2-new-node-rp node))
4399 ((js2-call-node-p node)
4400 (js2-call-node-rp node))
4401 ((js2-paren-node-p node)
4402 (+ (js2-node-pos node) (js2-node-len node)))
4403 ((js2-switch-node-p node)
4404 (js2-switch-node-rp node))
4405 ((js2-catch-node-p node)
4406 (js2-catch-node-rp node))
4407 ((js2-let-node-p node)
4408 (js2-let-node-rp node))
4409 ((js2-array-comp-node-p node)
4410 (js2-array-comp-node-rp node))
4411 ((js2-with-node-p node)
4412 (js2-with-node-rp node))
4413 ((js2-xml-dot-query-node-p node)
4414 (1+ (js2-xml-dot-query-node-rp node)))
4415 (t
4416 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4417
4418 (defsubst js2-node-first-child (node)
4419 "Returns the first element of `js2-node-child-list' for NODE."
4420 (car (js2-node-child-list node)))
4421
4422 (defsubst js2-node-last-child (node)
4423 "Returns the last element of `js2-node-last-child' for NODE."
4424 (car (last (js2-node-child-list node))))
4425
4426 (defun js2-node-prev-sibling (node)
4427 "Return the previous statement in parent.
4428 Works for parents supported by `js2-node-child-list'.
4429 Returns nil if NODE is not in the parent, or PARENT is
4430 not a supported node, or if NODE is the first child."
4431 (let* ((p (js2-node-parent node))
4432 (kids (js2-node-child-list p))
4433 (sib (car kids)))
4434 (while (and kids
4435 (not (eq node (cadr kids))))
4436 (setq kids (cdr kids)
4437 sib (car kids)))
4438 sib))
4439
4440 (defun js2-node-next-sibling (node)
4441 "Return the next statement in parent block.
4442 Returns nil if NODE is not in the block, or PARENT is not
4443 a block node, or if NODE is the last statement."
4444 (let* ((p (js2-node-parent node))
4445 (kids (js2-node-child-list p)))
4446 (while (and kids
4447 (not (eq node (car kids))))
4448 (setq kids (cdr kids)))
4449 (cadr kids)))
4450
4451 (defun js2-node-find-child-before (pos parent &optional after)
4452 "Find the last child that starts before POS in parent.
4453 If AFTER is non-nil, returns first child starting after POS.
4454 POS is an absolute buffer position. PARENT is any node
4455 supported by `js2-node-child-list'.
4456 Returns nil if no applicable child is found."
4457 (let ((kids (if (js2-function-node-p parent)
4458 (js2-block-node-kids (js2-function-node-body parent))
4459 (js2-node-child-list parent)))
4460 (beg (if (js2-function-node-p parent)
4461 (js2-node-abs-pos (js2-function-node-body parent))
4462 (js2-node-abs-pos parent)))
4463 kid
4464 result
4465 fn
4466 (continue t))
4467 (setq fn (if after '>= '<))
4468 (while (and kids continue)
4469 (setq kid (car kids))
4470 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4471 (setq result kid
4472 continue (if after nil t))
4473 (setq continue (if after t nil)))
4474 (setq kids (cdr kids)))
4475 result))
4476
4477 (defun js2-node-find-child-after (pos parent)
4478 "Find first child that starts after POS in parent.
4479 POS is an absolute buffer position. PARENT is any node
4480 supported by `js2-node-child-list'.
4481 Returns nil if no applicable child is found."
4482 (js2-node-find-child-before pos parent 'after))
4483
4484 (defun js2-node-replace-child (pos parent new-node)
4485 "Replace node at index POS in PARENT with NEW-NODE.
4486 Only works for parents supported by `js2-node-child-list'."
4487 (let ((kids (js2-node-child-list parent))
4488 (i 0))
4489 (while (< i pos)
4490 (setq kids (cdr kids)
4491 i (1+ i)))
4492 (setcar kids new-node)
4493 (js2-node-add-children parent new-node)))
4494
4495 (defun js2-node-buffer (n)
4496 "Return the buffer associated with AST N.
4497 Returns nil if the buffer is not set as a property on the root
4498 node, or if parent links were not recorded during parsing."
4499 (let ((root (js2-node-root n)))
4500 (and root
4501 (js2-ast-root-p root)
4502 (js2-ast-root-buffer root))))
4503
4504 (defsubst js2-block-node-push (n kid)
4505 "Push js2-node KID onto the end of js2-block-node N's child list.
4506 KID is always added to the -end- of the kids list.
4507 Function also calls `js2-node-add-children' to add the parent link."
4508 (let ((kids (js2-node-child-list n)))
4509 (if kids
4510 (setcdr kids (nconc (cdr kids) (list kid)))
4511 (js2-node-set-child-list n (list kid)))
4512 (js2-node-add-children n kid)))
4513
4514 (defun js2-node-string (node)
4515 (let ((buf (js2-node-buffer node))
4516 pos)
4517 (unless buf
4518 (error "No buffer available for node %s" node))
4519 (with-current-buffer buf
4520 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4521 (+ pos (js2-node-len node))))))
4522
4523 ;; Container for storing the node we're looking for in a traversal.
4524 (js2-deflocal js2-discovered-node nil)
4525
4526 ;; Keep track of absolute node position during traversals.
4527 (js2-deflocal js2-visitor-offset nil)
4528
4529 (js2-deflocal js2-node-search-point nil)
4530
4531 (when js2-mode-dev-mode-p
4532 (defun js2-find-node-at-point ()
4533 (interactive)
4534 (let ((node (js2-node-at-point)))
4535 (message "%s" (or node "No node found at point"))))
4536 (defun js2-node-name-at-point ()
4537 (interactive)
4538 (let ((node (js2-node-at-point)))
4539 (message "%s" (if node
4540 (js2-node-short-name node)
4541 "No node found at point.")))))
4542
4543 (defun js2-node-at-point (&optional pos skip-comments)
4544 "Return AST node at POS, a buffer position, defaulting to current point.
4545 The `js2-mode-ast' variable must be set to the current parse tree.
4546 Signals an error if the AST (`js2-mode-ast') is nil.
4547 Always returns a node - if it can't find one, it returns the root.
4548 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4549 (let ((ast js2-mode-ast)
4550 result)
4551 (unless ast
4552 (error "No JavaScript AST available"))
4553 ;; Look through comments first, since they may be inside nodes that
4554 ;; would otherwise report a match.
4555 (setq pos (or pos (point))
4556 result (if (> pos (js2-node-abs-end ast))
4557 ast
4558 (if (not skip-comments)
4559 (js2-comment-at-point pos))))
4560 (unless result
4561 (setq js2-discovered-node nil
4562 js2-visitor-offset 0
4563 js2-node-search-point pos)
4564 (unwind-protect
4565 (catch 'js2-visit-done
4566 (js2-visit-ast ast #'js2-node-at-point-visitor))
4567 (setq js2-visitor-offset nil
4568 js2-node-search-point nil))
4569 (setq result js2-discovered-node))
4570 ;; may have found a comment beyond end of last child node,
4571 ;; since visiting the ast-root looks at the comment-list last.
4572 (if (and skip-comments
4573 (js2-comment-node-p result))
4574 (setq result nil))
4575 (or result js2-mode-ast)))
4576
4577 (defun js2-node-at-point-visitor (node end-p)
4578 (let ((rel-pos (js2-node-pos node))
4579 abs-pos
4580 abs-end
4581 (point js2-node-search-point))
4582 (cond
4583 (end-p
4584 ;; this evaluates to a non-nil return value, even if it's zero
4585 (decf js2-visitor-offset rel-pos))
4586 ;; we already looked for comments before visiting, and don't want them now
4587 ((js2-comment-node-p node)
4588 nil)
4589 (t
4590 (setq abs-pos (incf js2-visitor-offset rel-pos)
4591 ;; we only want to use the node if the point is before
4592 ;; the last character position in the node, so we decrement
4593 ;; the absolute end by 1.
4594 abs-end (+ abs-pos (js2-node-len node) -1))
4595 (cond
4596 ;; If this node starts after search-point, stop the search.
4597 ((> abs-pos point)
4598 (throw 'js2-visit-done nil))
4599 ;; If this node ends before the search-point, don't check kids.
4600 ((> point abs-end)
4601 nil)
4602 (t
4603 ;; Otherwise point is within this node, possibly in a child.
4604 (setq js2-discovered-node node)
4605 t)))))) ; keep processing kids to look for more specific match
4606
4607 (defsubst js2-block-comment-p (node)
4608 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4609 (and (js2-comment-node-p node)
4610 (memq (js2-comment-node-format node) '(jsdoc block))))
4611
4612 ;; TODO: put the comments in a vector and binary-search them instead
4613 (defun js2-comment-at-point (&optional pos)
4614 "Look through scanned comment nodes for one containing POS.
4615 POS is a buffer position that defaults to current point.
4616 Function returns nil if POS was not in any comment node."
4617 (let ((ast js2-mode-ast)
4618 (x (or pos (point)))
4619 beg
4620 end)
4621 (unless ast
4622 (error "No JavaScript AST available"))
4623 (catch 'done
4624 ;; Comments are stored in lexical order.
4625 (dolist (comment (js2-ast-root-comments ast) nil)
4626 (setq beg (js2-node-abs-pos comment)
4627 end (+ beg (js2-node-len comment)))
4628 (if (and (>= x beg)
4629 (<= x end))
4630 (throw 'done comment))))))
4631
4632 (defun js2-mode-find-parent-fn (node)
4633 "Find function enclosing NODE.
4634 Returns nil if NODE is not inside a function."
4635 (setq node (js2-node-parent node))
4636 (while (and node (not (js2-function-node-p node)))
4637 (setq node (js2-node-parent node)))
4638 (and (js2-function-node-p node) node))
4639
4640 (defun js2-mode-find-enclosing-fn (node)
4641 "Find function or root enclosing NODE."
4642 (if (js2-ast-root-p node)
4643 node
4644 (setq node (js2-node-parent node))
4645 (while (not (or (js2-ast-root-p node)
4646 (js2-function-node-p node)))
4647 (setq node (js2-node-parent node)))
4648 node))
4649
4650 (defun js2-mode-find-enclosing-node (beg end)
4651 "Find script or function fully enclosing BEG and END."
4652 (let ((node (js2-node-at-point beg))
4653 pos
4654 (continue t))
4655 (while continue
4656 (if (or (js2-ast-root-p node)
4657 (and (js2-function-node-p node)
4658 (<= (setq pos (js2-node-abs-pos node)) beg)
4659 (>= (+ pos (js2-node-len node)) end)))
4660 (setq continue nil)
4661 (setq node (js2-node-parent node))))
4662 node))
4663
4664 (defun js2-node-parent-script-or-fn (node)
4665 "Find script or function immediately enclosing NODE.
4666 If NODE is the ast-root, returns nil."
4667 (if (js2-ast-root-p node)
4668 nil
4669 (setq node (js2-node-parent node))
4670 (while (and node (not (or (js2-function-node-p node)
4671 (js2-script-node-p node))))
4672 (setq node (js2-node-parent node)))
4673 node))
4674
4675 (defsubst js2-nested-function-p (node)
4676 "Return t if NODE is a nested function, or is inside a nested function."
4677 (unless (js2-ast-root-p node)
4678 (js2-function-node-p (if (js2-function-node-p node)
4679 (js2-node-parent-script-or-fn node)
4680 (js2-node-parent-script-or-fn
4681 (js2-node-parent-script-or-fn node))))))
4682
4683 (defsubst js2-function-param-node-p (node)
4684 "Return non-nil if NODE is a param node of a `js2-function-node'."
4685 (let ((parent (js2-node-parent node)))
4686 (and parent
4687 (js2-function-node-p parent)
4688 (memq node (js2-function-node-params parent)))))
4689
4690 (defsubst js2-mode-shift-kids (kids start offset)
4691 (dolist (kid kids)
4692 (if (> (js2-node-pos kid) start)
4693 (incf (js2-node-pos kid) offset))))
4694
4695 (defsubst js2-mode-shift-children (parent start offset)
4696 "Update start-positions of all children of PARENT beyond START."
4697 (let ((root (js2-node-root parent)))
4698 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4699 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4700
4701 (defsubst js2-node-is-descendant (node ancestor)
4702 "Return t if NODE is a descendant of ANCESTOR."
4703 (while (and node
4704 (not (eq node ancestor)))
4705 (setq node (js2-node-parent node)))
4706 node)
4707
4708 ;;; visitor infrastructure
4709
4710 (defun js2-visit-none (node callback)
4711 "Visitor for AST node that have no node children."
4712 nil)
4713
4714 (defun js2-print-none (node indent)
4715 "Visitor for AST node with no printed representation.")
4716
4717 (defun js2-print-body (node indent)
4718 "Print a statement, or a block without braces."
4719 (if (js2-block-node-p node)
4720 (dolist (kid (js2-block-node-kids node))
4721 (js2-print-ast kid indent))
4722 (js2-print-ast node indent)))
4723
4724 (defun js2-print-list (args &optional delimiter)
4725 (loop with len = (length args)
4726 for arg in args
4727 for count from 1
4728 do
4729 (js2-print-ast arg 0)
4730 (if (< count len)
4731 (insert (or delimiter ", ")))))
4732
4733 (defun js2-print-tree (ast)
4734 "Prints an AST to the current buffer.
4735 Makes `js2-ast-parent-nodes' available to the printer functions."
4736 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4737 (js2-print-ast ast)))
4738
4739 (defun js2-print-ast (node &optional indent)
4740 "Helper function for printing AST nodes.
4741 Requires `js2-ast-parent-nodes' to be non-nil.
4742 You should use `js2-print-tree' instead of this function."
4743 (let ((printer (get (aref node 0) 'js2-printer))
4744 (i (or indent 0))
4745 (pos (js2-node-abs-pos node)))
4746 ;; TODO: wedge comments in here somewhere
4747 (if printer
4748 (funcall printer node i))))
4749
4750 (defconst js2-side-effecting-tokens
4751 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4752 (dolist (tt (list js2-ASSIGN
4753 js2-ASSIGN_ADD
4754 js2-ASSIGN_BITAND
4755 js2-ASSIGN_BITOR
4756 js2-ASSIGN_BITXOR
4757 js2-ASSIGN_DIV
4758 js2-ASSIGN_LSH
4759 js2-ASSIGN_MOD
4760 js2-ASSIGN_MUL
4761 js2-ASSIGN_RSH
4762 js2-ASSIGN_SUB
4763 js2-ASSIGN_URSH
4764 js2-BLOCK
4765 js2-BREAK
4766 js2-CALL
4767 js2-CATCH
4768 js2-CATCH_SCOPE
4769 js2-CONST
4770 js2-CONTINUE
4771 js2-DEBUGGER
4772 js2-DEC
4773 js2-DELPROP
4774 js2-DEL_REF
4775 js2-DO
4776 js2-ELSE
4777 js2-EMPTY
4778 js2-ENTERWITH
4779 js2-EXPORT
4780 js2-EXPR_RESULT
4781 js2-FINALLY
4782 js2-FOR
4783 js2-FUNCTION
4784 js2-GOTO
4785 js2-IF
4786 js2-IFEQ
4787 js2-IFNE
4788 js2-IMPORT
4789 js2-INC
4790 js2-JSR
4791 js2-LABEL
4792 js2-LEAVEWITH
4793 js2-LET
4794 js2-LETEXPR
4795 js2-LOCAL_BLOCK
4796 js2-LOOP
4797 js2-NEW
4798 js2-REF_CALL
4799 js2-RETHROW
4800 js2-RETURN
4801 js2-RETURN_RESULT
4802 js2-SEMI
4803 js2-SETELEM
4804 js2-SETELEM_OP
4805 js2-SETNAME
4806 js2-SETPROP
4807 js2-SETPROP_OP
4808 js2-SETVAR
4809 js2-SET_REF
4810 js2-SET_REF_OP
4811 js2-SWITCH
4812 js2-TARGET
4813 js2-THROW
4814 js2-TRY
4815 js2-VAR
4816 js2-WHILE
4817 js2-WITH
4818 js2-WITHEXPR
4819 js2-YIELD))
4820 (aset tokens tt t))
4821 (if js2-instanceof-has-side-effects
4822 (aset tokens js2-INSTANCEOF t))
4823 tokens))
4824
4825 (defun js2-node-has-side-effects (node)
4826 "Return t if NODE has side effects."
4827 (when node ; makes it easier to handle malformed expressions
4828 (let ((tt (js2-node-type node)))
4829 (cond
4830 ;; This doubtless needs some work, since EXPR_VOID is used
4831 ;; in several ways in Rhino, and I may not have caught them all.
4832 ;; I'll wait for people to notice incorrect warnings.
4833 ((and (= tt js2-EXPR_VOID)
4834 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4835 (let ((expr (js2-expr-stmt-node-expr node)))
4836 (or (js2-node-has-side-effects expr)
4837 (when (js2-string-node-p expr)
4838 (string= "use strict" (js2-string-node-value expr))))))
4839 ((= tt js2-COMMA)
4840 (js2-node-has-side-effects (js2-infix-node-right node)))
4841 ((or (= tt js2-AND)
4842 (= tt js2-OR))
4843 (or (js2-node-has-side-effects (js2-infix-node-right node))
4844 (js2-node-has-side-effects (js2-infix-node-left node))))
4845 ((= tt js2-HOOK)
4846 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4847 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4848 ((js2-paren-node-p node)
4849 (js2-node-has-side-effects (js2-paren-node-expr node)))
4850 ((= tt js2-ERROR) ; avoid cascaded error messages
4851 nil)
4852 (t
4853 (aref js2-side-effecting-tokens tt))))))
4854
4855 (defun js2-member-expr-leftmost-name (node)
4856 "For an expr such as foo.bar.baz, return leftmost node foo.
4857 NODE is any `js2-node' object. If it represents a member expression,
4858 which is any sequence of property gets, element-gets, function calls,
4859 or xml descendants/filter operators, then we look at the lexically
4860 leftmost (first) node in the chain. If it is a name-node we return it.
4861 Note that NODE can be a raw name-node and it will be returned as well.
4862 If NODE is not a name-node or member expression, or if it is a member
4863 expression whose leftmost target is not a name node, returns nil."
4864 (let ((continue t)
4865 result)
4866 (while (and continue (not result))
4867 (cond
4868 ((js2-name-node-p node)
4869 (setq result node))
4870 ((js2-prop-get-node-p node)
4871 (setq node (js2-prop-get-node-left node)))
4872 ;; TODO: handle call-nodes, xml-nodes, others?
4873 (t
4874 (setq continue nil))))
4875 result))
4876
4877 (defconst js2-stmt-node-types
4878 (list js2-BLOCK
4879 js2-BREAK
4880 js2-CONTINUE
4881 js2-DEFAULT ; e4x "default xml namespace" statement
4882 js2-DO
4883 js2-EXPR_RESULT
4884 js2-EXPR_VOID
4885 js2-FOR
4886 js2-IF
4887 js2-RETURN
4888 js2-SWITCH
4889 js2-THROW
4890 js2-TRY
4891 js2-WHILE
4892 js2-WITH)
4893 "Node types that only appear in statement contexts.
4894 The list does not include nodes that always appear as the child
4895 of another specific statement type, such as switch-cases,
4896 catch and finally blocks, and else-clauses. The list also excludes
4897 nodes like yield, let and var, which may appear in either expression
4898 or statement context, and in the latter context always have a
4899 `js2-expr-stmt-node' parent. Finally, the list does not include
4900 functions or scripts, which are treated separately from statements
4901 by the JavaScript parser and runtime.")
4902
4903 (defun js2-stmt-node-p (node)
4904 "Heuristic for figuring out if NODE is a statement.
4905 Some node types can appear in either an expression context or a
4906 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4907 For these node types in a statement context, the parent will be a
4908 `js2-expr-stmt-node'.
4909 Functions aren't included in the check."
4910 (memq (js2-node-type node) js2-stmt-node-types))
4911
4912 (defsubst js2-mode-find-first-stmt (node)
4913 "Search upward starting from NODE looking for a statement.
4914 For purposes of this function, a `js2-function-node' counts."
4915 (while (not (or (js2-stmt-node-p node)
4916 (js2-function-node-p node)))
4917 (setq node (js2-node-parent node)))
4918 node)
4919
4920 (defun js2-node-parent-stmt (node)
4921 "Return the node's first ancestor that is a statement.
4922 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4923 appearing in a statement context will have a parent that is a
4924 `js2-expr-stmt-node' that will be returned by this function."
4925 (let ((parent (js2-node-parent node)))
4926 (if (or (null parent)
4927 (js2-stmt-node-p parent)
4928 (and (js2-function-node-p parent)
4929 (not (eq (js2-function-node-form parent)
4930 'FUNCTION_EXPRESSION))))
4931 parent
4932 (js2-node-parent-stmt parent))))
4933
4934 ;; In the Mozilla Rhino sources, Roshan James writes:
4935 ;; Does consistent-return analysis on the function body when strict mode is
4936 ;; enabled.
4937 ;;
4938 ;; function (x) { return (x+1) }
4939 ;;
4940 ;; is ok, but
4941 ;;
4942 ;; function (x) { if (x < 0) return (x+1); }
4943 ;;
4944 ;; is not because the function can potentially return a value when the
4945 ;; condition is satisfied and if not, the function does not explicitly
4946 ;; return a value.
4947 ;;
4948 ;; This extends to checking mismatches such as "return" and "return <value>"
4949 ;; used in the same function. Warnings are not emitted if inconsistent
4950 ;; returns exist in code that can be statically shown to be unreachable.
4951 ;; Ex.
4952 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4953 ;;
4954 ;; emits no warning. However if the loop had a break statement, then a
4955 ;; warning would be emitted.
4956 ;;
4957 ;; The consistency analysis looks at control structures such as loops, ifs,
4958 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4959 ;; warns the user about an inconsistent set of termination possibilities.
4960 ;;
4961 ;; These flags enumerate the possible ways a statement/function can
4962 ;; terminate. These flags are used by endCheck() and by the Parser to
4963 ;; detect inconsistent return usage.
4964 ;;
4965 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4966 ;; able to execute (example: throw, continue)
4967 ;;
4968 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4969 ;; next one. Statement such as return dont. A compound statement may have
4970 ;; some branch that drops off control to the next statement.
4971 ;;
4972 ;; END_RETURNS indicates that the statement can return with no value.
4973 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4974 ;;
4975 ;; A compound statement such as
4976 ;; if (condition) {
4977 ;; return value;
4978 ;; }
4979 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4980
4981 (defconst js2-END_UNREACHED 0)
4982 (defconst js2-END_DROPS_OFF 1)
4983 (defconst js2-END_RETURNS 2)
4984 (defconst js2-END_RETURNS_VALUE 4)
4985 (defconst js2-END_YIELDS 8)
4986
4987 (defun js2-has-consistent-return-usage (node)
4988 "Check that every return usage in a function body is consistent.
4989 Returns t if the function satisfies strict mode requirement."
4990 (let ((n (js2-end-check node)))
4991 ;; either it doesn't return a value in any branch...
4992 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4993 ;; or it returns a value (or is unreached) at every branch
4994 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4995 js2-END_RETURNS
4996 js2-END_YIELDS)))))
4997
4998 (defun js2-end-check-if (node)
4999 "Returns in the then and else blocks must be consistent with each other.
5000 If there is no else block, then the return statement can fall through.
5001 Returns logical OR of END_* flags"
5002 (let ((th (js2-if-node-then-part node))
5003 (el (js2-if-node-else-part node)))
5004 (if (null th)
5005 js2-END_UNREACHED
5006 (logior (js2-end-check th) (if el
5007 (js2-end-check el)
5008 js2-END_DROPS_OFF)))))
5009
5010 (defun js2-end-check-switch (node)
5011 "Consistency of return statements is checked between the case statements.
5012 If there is no default, then the switch can fall through. If there is a
5013 default, we check to see if all code paths in the default return or if
5014 there is a code path that can fall through.
5015 Returns logical OR of END_* flags."
5016 (let ((rv js2-END_UNREACHED)
5017 default-case)
5018 ;; examine the cases
5019 (catch 'break
5020 (dolist (c (js2-switch-node-cases node))
5021 (if (js2-case-node-expr c)
5022 (js2-set-flag rv (js2-end-check-block c))
5023 (setq default-case c)
5024 (throw 'break nil))))
5025 ;; we don't care how the cases drop into each other
5026 (js2-clear-flag rv js2-END_DROPS_OFF)
5027 ;; examine the default
5028 (js2-set-flag rv (if default-case
5029 (js2-end-check default-case)
5030 js2-END_DROPS_OFF))
5031 rv))
5032
5033 (defun js2-end-check-try (node)
5034 "If the block has a finally, return consistency is checked in the
5035 finally block. If all code paths in the finally return, then the
5036 returns in the try-catch blocks don't matter. If there is a code path
5037 that does not return or if there is no finally block, the returns
5038 of the try and catch blocks are checked for mismatch.
5039 Returns logical OR of END_* flags."
5040 (let ((finally (js2-try-node-finally-block node))
5041 rv)
5042 ;; check the finally if it exists
5043 (setq rv (if finally
5044 (js2-end-check (js2-finally-node-body finally))
5045 js2-END_DROPS_OFF))
5046 ;; If the finally block always returns, then none of the returns
5047 ;; in the try or catch blocks matter.
5048 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5049 (js2-clear-flag rv js2-END_DROPS_OFF)
5050 ;; examine the try block
5051 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5052 ;; check each catch block
5053 (dolist (cb (js2-try-node-catch-clauses node))
5054 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5055 rv))
5056
5057 (defun js2-end-check-loop (node)
5058 "Return statement in the loop body must be consistent. The default
5059 assumption for any kind of a loop is that it will eventually terminate.
5060 The only exception is a loop with a constant true condition. Code that
5061 follows such a loop is examined only if one can statically determine
5062 that there is a break out of the loop.
5063
5064 for(... ; ... ; ...) {}
5065 for(... in ... ) {}
5066 while(...) { }
5067 do { } while(...)
5068
5069 Returns logical OR of END_* flags."
5070 (let ((rv (js2-end-check (js2-loop-node-body node)))
5071 (condition (cond
5072 ((js2-while-node-p node)
5073 (js2-while-node-condition node))
5074 ((js2-do-node-p node)
5075 (js2-do-node-condition node))
5076 ((js2-for-node-p node)
5077 (js2-for-node-condition node)))))
5078
5079 ;; check to see if the loop condition is always true
5080 (if (and condition
5081 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5082 (js2-clear-flag rv js2-END_DROPS_OFF))
5083
5084 ;; look for effect of breaks
5085 (js2-set-flag rv (js2-node-get-prop node
5086 'CONTROL_BLOCK_PROP
5087 js2-END_UNREACHED))
5088 rv))
5089
5090 (defun js2-end-check-block (node)
5091 "A general block of code is examined statement by statement.
5092 If any statement (even a compound one) returns in all branches, then
5093 subsequent statements are not examined.
5094 Returns logical OR of END_* flags."
5095 (let* ((rv js2-END_DROPS_OFF)
5096 (kids (js2-block-node-kids node))
5097 (n (car kids)))
5098 ;; Check each statment. If the statement can continue onto the next
5099 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5100 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5101 (js2-clear-flag rv js2-END_DROPS_OFF)
5102 (js2-set-flag rv (js2-end-check n))
5103 (setq kids (cdr kids)
5104 n (car kids)))
5105 rv))
5106
5107 (defun js2-end-check-label (node)
5108 "A labeled statement implies that there may be a break to the label.
5109 The function processes the labeled statement and then checks the
5110 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5111 particular label.
5112 Returns logical OR of END_* flags."
5113 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5114 (logior rv (js2-node-get-prop node
5115 'CONTROL_BLOCK_PROP
5116 js2-END_UNREACHED))))
5117
5118 (defun js2-end-check-break (node)
5119 "When a break is encountered annotate the statement being broken
5120 out of by setting its CONTROL_BLOCK_PROP property.
5121 Returns logical OR of END_* flags."
5122 (and (js2-break-node-target node)
5123 (js2-node-set-prop (js2-break-node-target node)
5124 'CONTROL_BLOCK_PROP
5125 js2-END_DROPS_OFF))
5126 js2-END_UNREACHED)
5127
5128 (defun js2-end-check (node)
5129 "Examine the body of a function, doing a basic reachability analysis.
5130 Returns a combination of flags END_* flags that indicate
5131 how the function execution can terminate. These constitute only the
5132 pessimistic set of termination conditions. It is possible that at
5133 runtime certain code paths will never be actually taken. Hence this
5134 analysis will flag errors in cases where there may not be errors.
5135 Returns logical OR of END_* flags"
5136 (let (kid)
5137 (cond
5138 ((js2-break-node-p node)
5139 (js2-end-check-break node))
5140 ((js2-expr-stmt-node-p node)
5141 (if (setq kid (js2-expr-stmt-node-expr node))
5142 (js2-end-check kid)
5143 js2-END_DROPS_OFF))
5144 ((or (js2-continue-node-p node)
5145 (js2-throw-node-p node))
5146 js2-END_UNREACHED)
5147 ((js2-return-node-p node)
5148 (if (setq kid (js2-return-node-retval node))
5149 js2-END_RETURNS_VALUE
5150 js2-END_RETURNS))
5151 ((js2-loop-node-p node)
5152 (js2-end-check-loop node))
5153 ((js2-switch-node-p node)
5154 (js2-end-check-switch node))
5155 ((js2-labeled-stmt-node-p node)
5156 (js2-end-check-label node))
5157 ((js2-if-node-p node)
5158 (js2-end-check-if node))
5159 ((js2-try-node-p node)
5160 (js2-end-check-try node))
5161 ((js2-block-node-p node)
5162 (if (null (js2-block-node-kids node))
5163 js2-END_DROPS_OFF
5164 (js2-end-check-block node)))
5165 ((js2-yield-node-p node)
5166 js2-END_YIELDS)
5167 (t
5168 js2-END_DROPS_OFF))))
5169
5170 (defun js2-always-defined-boolean-p (node)
5171 "Check if NODE always evaluates to true or false in boolean context.
5172 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5173 nor always false."
5174 (let ((tt (js2-node-type node))
5175 num)
5176 (cond
5177 ((or (= tt js2-FALSE) (= tt js2-NULL))
5178 'ALWAYS_FALSE)
5179 ((= tt js2-TRUE)
5180 'ALWAYS_TRUE)
5181 ((= tt js2-NUMBER)
5182 (setq num (js2-number-node-num-value node))
5183 (if (and (not (eq num 0.0e+NaN))
5184 (not (zerop num)))
5185 'ALWAYS_TRUE
5186 'ALWAYS_FALSE))
5187 (t
5188 nil))))
5189
5190 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5191 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5192
5193 (defvar js2-tokens nil
5194 "List of all defined token names.") ; initialized in `js2-token-names'
5195
5196 (defconst js2-token-names
5197 (let* ((names (make-vector js2-num-tokens -1))
5198 (case-fold-search nil) ; only match js2-UPPER_CASE
5199 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5200 (loop for sym in syms
5201 for i from 0
5202 do
5203 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5204 (not (boundp sym)))
5205 (aset names (symbol-value sym) ; code, e.g. 152
5206 (downcase
5207 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5208 (push sym js2-tokens)))
5209 names)
5210 "Vector mapping int values to token string names, sans `js2-' prefix.")
5211
5212 (defun js2-token-name (tok)
5213 "Return a string name for TOK, a token symbol or code.
5214 Signals an error if it's not a recognized token."
5215 (let ((code tok))
5216 (if (symbolp tok)
5217 (setq code (symbol-value tok)))
5218 (if (eq code -1)
5219 "ERROR"
5220 (if (and (numberp code)
5221 (not (minusp code))
5222 (< code js2-num-tokens))
5223 (aref js2-token-names code)
5224 (error "Invalid token: %s" code)))))
5225
5226 (defsubst js2-token-sym (tok)
5227 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5228 (intern (js2-token-name tok)))
5229
5230 (defconst js2-token-codes
5231 (let ((table (make-hash-table :test 'eq :size 256)))
5232 (loop for name across js2-token-names
5233 for sym = (intern (concat "js2-" (upcase name)))
5234 do
5235 (puthash sym (symbol-value sym) table))
5236 ;; clean up a few that are "wrong" in Rhino's token codes
5237 (puthash 'js2-DELETE js2-DELPROP table)
5238 table)
5239 "Hashtable mapping token symbols to their bytecodes.")
5240
5241 (defsubst js2-token-code (sym)
5242 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5243 (or (gethash sym js2-token-codes)
5244 (error "Invalid token symbol: %s " sym))) ; signal code bug
5245
5246 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5247 (setq js2-token-end js2-ts-cursor)
5248 (js2-report-error msg nil
5249 (or beg js2-token-beg)
5250 (or len (- js2-token-end js2-token-beg)))
5251 (unless no-throw
5252 (throw 'return js2-ERROR)))
5253
5254 (defsubst js2-get-string-from-buffer ()
5255 "Reverse the char accumulator and return it as a string."
5256 (setq js2-token-end js2-ts-cursor)
5257 (if js2-ts-string-buffer
5258 (apply #'string (nreverse js2-ts-string-buffer))
5259 ""))
5260
5261 ;; TODO: could potentially avoid a lot of consing by allocating a
5262 ;; char buffer the way Rhino does.
5263 (defsubst js2-add-to-string (c)
5264 (push c js2-ts-string-buffer))
5265
5266 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5267 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5268 ;; any other character: when it's not part of the current token, we
5269 ;; unget it, allowing it to be read again by the following call.
5270 (defsubst js2-unget-char ()
5271 (decf js2-ts-cursor))
5272
5273 ;; Rhino distinguishes \r and \n line endings. We don't need to
5274 ;; because we only scan from Emacs buffers, which always use \n.
5275 (defsubst js2-get-char ()
5276 "Read and return the next character from the input buffer.
5277 Increments `js2-ts-lineno' if the return value is a newline char.
5278 Updates `js2-ts-cursor' to the point after the returned char.
5279 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5280 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5281 (let (c)
5282 ;; check for end of buffer
5283 (if (>= js2-ts-cursor (point-max))
5284 (setq js2-ts-hit-eof t
5285 js2-ts-cursor (1+ js2-ts-cursor)
5286 c js2-EOF_CHAR) ; return value
5287 ;; otherwise read next char
5288 (setq c (char-before (incf js2-ts-cursor)))
5289 ;; if we read a newline, update counters
5290 (if (= c ?\n)
5291 (setq js2-ts-line-start js2-ts-cursor
5292 js2-ts-lineno (1+ js2-ts-lineno)))
5293 ;; TODO: skip over format characters
5294 c)))
5295
5296 (defsubst js2-read-unicode-escape ()
5297 "Read a \\uNNNN sequence from the input.
5298 Assumes the ?\ and ?u have already been read.
5299 Returns the unicode character, or nil if it wasn't a valid character.
5300 Doesn't change the values of any scanner variables."
5301 ;; I really wish I knew a better way to do this, but I can't
5302 ;; find the Emacs function that takes a 16-bit int and converts
5303 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5304 ;; Have to first check that it's 4 hex characters or it may stop
5305 ;; the read early.
5306 (ignore-errors
5307 (let ((s (buffer-substring-no-properties js2-ts-cursor
5308 (+ 4 js2-ts-cursor))))
5309 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5310 (read (concat "?\\u" s))))))
5311
5312 (defsubst js2-match-char (test)
5313 "Consume and return next character if it matches TEST, a character.
5314 Returns nil and consumes nothing if TEST is not the next character."
5315 (let ((c (js2-get-char)))
5316 (if (eq c test)
5317 t
5318 (js2-unget-char)
5319 nil)))
5320
5321 (defsubst js2-peek-char ()
5322 (prog1
5323 (js2-get-char)
5324 (js2-unget-char)))
5325
5326 (defsubst js2-java-identifier-start-p (c)
5327 (or
5328 (memq c '(?$ ?_))
5329 (js2-char-uppercase-p c)
5330 (js2-char-lowercase-p c)))
5331
5332 (defsubst js2-java-identifier-part-p (c)
5333 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5334 ;; TODO: make me Unicode-friendly. See comments above.
5335 (or
5336 (memq c '(?$ ?_))
5337 (js2-char-uppercase-p c)
5338 (js2-char-lowercase-p c)
5339 (and (>= c ?0) (<= c ?9))))
5340
5341 (defsubst js2-alpha-p (c)
5342 (cond ((and (<= ?A c) (<= c ?Z)) t)
5343 ((and (<= ?a c) (<= c ?z)) t)
5344 (t nil)))
5345
5346 (defsubst js2-digit-p (c)
5347 (and (<= ?0 c) (<= c ?9)))
5348
5349 (defsubst js2-js-space-p (c)
5350 (if (<= c 127)
5351 (memq c '(#x20 #x9 #xB #xC #xD))
5352 (or
5353 (eq c #xA0)
5354 ;; TODO: change this nil to check for Unicode space character
5355 nil)))
5356
5357 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5358
5359 (defsubst js2-skip-line ()
5360 "Skip to end of line"
5361 (let (c)
5362 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5363 (js2-unget-char)
5364 (setq js2-token-end js2-ts-cursor)))
5365
5366 (defun js2-init-scanner (&optional buf line)
5367 "Create token stream for BUF starting on LINE.
5368 BUF defaults to current-buffer and line defaults to 1.
5369
5370 A buffer can only have one scanner active at a time, which yields
5371 dramatically simpler code than using a defstruct. If you need to
5372 have simultaneous scanners in a buffer, copy the regions to scan
5373 into temp buffers."
5374 (save-excursion
5375 (when buf
5376 (set-buffer buf))
5377 (setq js2-ts-dirty-line nil
5378 js2-ts-regexp-flags nil
5379 js2-ts-string ""
5380 js2-ts-number nil
5381 js2-ts-hit-eof nil
5382 js2-ts-line-start 0
5383 js2-ts-lineno (or line 1)
5384 js2-ts-line-end-char -1
5385 js2-ts-cursor (point-min)
5386 js2-ts-is-xml-attribute nil
5387 js2-ts-xml-is-tag-content nil
5388 js2-ts-xml-open-tags-count 0
5389 js2-ts-string-buffer nil)))
5390
5391 ;; This function uses the cached op, string and number fields in
5392 ;; TokenStream; if getToken has been called since the passed token
5393 ;; was scanned, the op or string printed may be incorrect.
5394 (defun js2-token-to-string (token)
5395 ;; Not sure where this function is used in Rhino. Not tested.
5396 (if (not js2-debug-print-trees)
5397 ""
5398 (let ((name (js2-token-name token)))
5399 (cond
5400 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5401 (concat name " `" js2-ts-string "'"))
5402 ((eq token js2-NUMBER)
5403 (format "NUMBER %g" js2-ts-number))
5404 (t
5405 name)))))
5406
5407 (defconst js2-keywords
5408 '(break
5409 case catch const continue
5410 debugger default delete do
5411 else enum
5412 false finally for function
5413 if in instanceof import
5414 let
5415 new null
5416 return
5417 switch
5418 this throw true try typeof
5419 var void
5420 while with
5421 yield))
5422
5423 ;; Token names aren't exactly the same as the keywords, unfortunately.
5424 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5425 (defconst js2-kwd-tokens
5426 (let ((table (make-vector js2-num-tokens nil))
5427 (tokens
5428 (list js2-BREAK
5429 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5430 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5431 js2-ELSE
5432 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5433 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5434 js2-LET
5435 js2-NEW js2-NULL
5436 js2-RETURN
5437 js2-SWITCH
5438 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5439 js2-VAR
5440 js2-WHILE js2-WITH
5441 js2-YIELD)))
5442 (dolist (i tokens)
5443 (aset table i 'font-lock-keyword-face))
5444 (aset table js2-STRING 'font-lock-string-face)
5445 (aset table js2-REGEXP 'font-lock-string-face)
5446 (aset table js2-COMMENT 'font-lock-comment-face)
5447 (aset table js2-THIS 'font-lock-builtin-face)
5448 (aset table js2-VOID 'font-lock-constant-face)
5449 (aset table js2-NULL 'font-lock-constant-face)
5450 (aset table js2-TRUE 'font-lock-constant-face)
5451 (aset table js2-FALSE 'font-lock-constant-face)
5452 table)
5453 "Vector whose values are non-nil for tokens that are keywords.
5454 The values are default faces to use for highlighting the keywords.")
5455
5456 (defconst js2-reserved-words
5457 '(abstract
5458 boolean byte
5459 char class
5460 double
5461 enum export extends
5462 final float
5463 goto
5464 implements import int interface
5465 long
5466 native
5467 package private protected public
5468 short static super synchronized
5469 throws transient
5470 volatile))
5471
5472 (defconst js2-keyword-names
5473 (let ((table (make-hash-table :test 'equal)))
5474 (loop for k in js2-keywords
5475 do (puthash
5476 (symbol-name k) ; instanceof
5477 (intern (concat "js2-"
5478 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5479 table))
5480 table)
5481 "JavaScript keywords by name, mapped to their symbols.")
5482
5483 (defconst js2-reserved-word-names
5484 (let ((table (make-hash-table :test 'equal)))
5485 (loop for k in js2-reserved-words
5486 do
5487 (puthash (symbol-name k) 'js2-RESERVED table))
5488 table)
5489 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5490
5491 (defsubst js2-collect-string (buf)
5492 "Convert BUF, a list of chars, to a string.
5493 Reverses BUF before converting."
5494 (cond
5495 ((stringp buf)
5496 buf)
5497 ((null buf) ; for emacs21 compat
5498 "")
5499 (t
5500 (if buf
5501 (apply #'string (nreverse buf))
5502 ""))))
5503
5504 (defun js2-string-to-keyword (s)
5505 "Return token for S, a string, if S is a keyword or reserved word.
5506 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5507 (or (gethash s js2-keyword-names)
5508 (gethash s js2-reserved-word-names)))
5509
5510 (defsubst js2-ts-set-char-token-bounds ()
5511 "Used when next token is one character."
5512 (setq js2-token-beg (1- js2-ts-cursor)
5513 js2-token-end js2-ts-cursor))
5514
5515 (defsubst js2-ts-return (token)
5516 "Return an N-character TOKEN from `js2-get-token'.
5517 Updates `js2-token-end' accordingly."
5518 (setq js2-token-end js2-ts-cursor)
5519 (throw 'return token))
5520
5521 (defsubst js2-x-digit-to-int (c accumulator)
5522 "Build up a hex number.
5523 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5524 corresponding number. Otherwise return -1."
5525 (catch 'return
5526 (catch 'check
5527 ;; Use 0..9 < A..Z < a..z
5528 (cond
5529 ((<= c ?9)
5530 (decf c ?0)
5531 (if (<= 0 c)
5532 (throw 'check nil)))
5533 ((<= c ?F)
5534 (when (<= ?A c)
5535 (decf c (- ?A 10))
5536 (throw 'check nil)))
5537 ((<= c ?f)
5538 (when (<= ?a c)
5539 (decf c (- ?a 10))
5540 (throw 'check nil))))
5541 (throw 'return -1))
5542 (logior c (lsh accumulator 4))))
5543
5544 (defun js2-get-token ()
5545 "Return next JavaScript token, an int such as js2-RETURN."
5546 (let (c
5547 c1
5548 identifier-start
5549 is-unicode-escape-start
5550 contains-escape
5551 escape-val
5552 escape-start
5553 str
5554 result
5555 base
5556 is-integer
5557 quote-char
5558 val
5559 look-for-slash
5560 continue)
5561 (catch 'return
5562 (while t
5563 ;; Eat whitespace, possibly sensitive to newlines.
5564 (setq continue t)
5565 (while continue
5566 (setq c (js2-get-char))
5567 (cond
5568 ((eq c js2-EOF_CHAR)
5569 (js2-ts-set-char-token-bounds)
5570 (throw 'return js2-EOF))
5571 ((eq c ?\n)
5572 (js2-ts-set-char-token-bounds)
5573 (setq js2-ts-dirty-line nil)
5574 (throw 'return js2-EOL))
5575 ((not (js2-js-space-p c))
5576 (if (/= c ?-) ; in case end of HTML comment
5577 (setq js2-ts-dirty-line t))
5578 (setq continue nil))))
5579 ;; Assume the token will be 1 char - fixed up below.
5580 (js2-ts-set-char-token-bounds)
5581 (when (eq c ?@)
5582 (throw 'return js2-XMLATTR))
5583 ;; identifier/keyword/instanceof?
5584 ;; watch out for starting with a <backslash>
5585 (cond
5586 ((eq c ?\\)
5587 (setq c (js2-get-char))
5588 (if (eq c ?u)
5589 (setq identifier-start t
5590 is-unicode-escape-start t
5591 js2-ts-string-buffer nil)
5592 (setq identifier-start nil)
5593 (js2-unget-char)
5594 (setq c ?\\)))
5595 (t
5596 (when (setq identifier-start (js2-java-identifier-start-p c))
5597 (setq js2-ts-string-buffer nil)
5598 (js2-add-to-string c))))
5599 (when identifier-start
5600 (setq contains-escape is-unicode-escape-start)
5601 (catch 'break
5602 (while t
5603 (if is-unicode-escape-start
5604 ;; strictly speaking we should probably push-back
5605 ;; all the bad characters if the <backslash>uXXXX
5606 ;; sequence is malformed. But since there isn't a
5607 ;; correct context(is there?) for a bad Unicode
5608 ;; escape sequence in an identifier, we can report
5609 ;; an error here.
5610 (progn
5611 (setq escape-val 0)
5612 (dotimes (i 4)
5613 (setq c (js2-get-char)
5614 escape-val (js2-x-digit-to-int c escape-val))
5615 ;; Next check takes care of c < 0 and bad escape
5616 (if (minusp escape-val)
5617 (throw 'break nil)))
5618 (if (minusp escape-val)
5619 (js2-report-scan-error "msg.invalid.escape" t))
5620 (js2-add-to-string escape-val)
5621 (setq is-unicode-escape-start nil))
5622 (setq c (js2-get-char))
5623 (cond
5624 ((eq c ?\\)
5625 (setq c (js2-get-char))
5626 (if (eq c ?u)
5627 (setq is-unicode-escape-start t
5628 contains-escape t)
5629 (js2-report-scan-error "msg.illegal.character" t)))
5630 (t
5631 (if (or (eq c js2-EOF_CHAR)
5632 (not (js2-java-identifier-part-p c)))
5633 (throw 'break nil))
5634 (js2-add-to-string c))))))
5635 (js2-unget-char)
5636 (setq str (js2-get-string-from-buffer))
5637 (unless contains-escape
5638 ;; OPT we shouldn't have to make a string (object!) to
5639 ;; check if it's a keyword.
5640 ;; Return the corresponding token if it's a keyword
5641 (when (setq result (js2-string-to-keyword str))
5642 (if (and (< js2-language-version 170)
5643 (memq result '(js2-LET js2-YIELD)))
5644 ;; LET and YIELD are tokens only in 1.7 and later
5645 (setq result 'js2-NAME))
5646 (if (not (eq result 'js2-RESERVED))
5647 (throw 'return (js2-token-code result)))
5648 (js2-report-warning "msg.reserved.keyword" str)))
5649 ;; If we want to intern these as Rhino does, just use (intern str)
5650 (setq js2-ts-string str)
5651 (throw 'return js2-NAME)) ; end identifier/kwd check
5652 ;; is it a number?
5653 (when (or (js2-digit-p c)
5654 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5655 (setq js2-ts-string-buffer nil
5656 base 10)
5657 (when (eq c ?0)
5658 (setq c (js2-get-char))
5659 (cond
5660 ((or (eq c ?x) (eq c ?X))
5661 (setq base 16)
5662 (setq c (js2-get-char)))
5663 ((js2-digit-p c)
5664 (setq base 8))
5665 (t
5666 (js2-add-to-string ?0))))
5667 (if (eq base 16)
5668 (while (<= 0 (js2-x-digit-to-int c 0))
5669 (js2-add-to-string c)
5670 (setq c (js2-get-char)))
5671 (while (and (<= ?0 c) (<= c ?9))
5672 ;; We permit 08 and 09 as decimal numbers, which
5673 ;; makes our behavior a superset of the ECMA
5674 ;; numeric grammar. We might not always be so
5675 ;; permissive, so we warn about it.
5676 (when (and (eq base 8) (>= c ?8))
5677 (js2-report-warning "msg.bad.octal.literal"
5678 (if (eq c ?8) "8" "9"))
5679 (setq base 10))
5680 (js2-add-to-string c)
5681 (setq c (js2-get-char))))
5682 (setq is-integer t)
5683 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5684 (setq is-integer nil)
5685 (when (eq c ?.)
5686 (loop do
5687 (js2-add-to-string c)
5688 (setq c (js2-get-char))
5689 while (js2-digit-p c)))
5690 (when (memq c '(?e ?E))
5691 (js2-add-to-string c)
5692 (setq c (js2-get-char))
5693 (when (memq c '(?+ ?-))
5694 (js2-add-to-string c)
5695 (setq c (js2-get-char)))
5696 (unless (js2-digit-p c)
5697 (js2-report-scan-error "msg.missing.exponent" t))
5698 (loop do
5699 (js2-add-to-string c)
5700 (setq c (js2-get-char))
5701 while (js2-digit-p c))))
5702 (js2-unget-char)
5703 (setq js2-ts-string (js2-get-string-from-buffer)
5704 js2-ts-number
5705 (if (and (eq base 10) (not is-integer))
5706 (string-to-number js2-ts-string)
5707 ;; TODO: call runtime number-parser. Some of it is in
5708 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5709 (string-to-number js2-ts-string)))
5710 (throw 'return js2-NUMBER))
5711 ;; is it a string?
5712 (when (memq c '(?\" ?\'))
5713 ;; We attempt to accumulate a string the fast way, by
5714 ;; building it directly out of the reader. But if there
5715 ;; are any escaped characters in the string, we revert to
5716 ;; building it out of a string buffer.
5717 (setq quote-char c
5718 js2-ts-string-buffer nil
5719 c (js2-get-char))
5720 (catch 'break
5721 (while (/= c quote-char)
5722 (catch 'continue
5723 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5724 (js2-unget-char)
5725 (setq js2-token-end js2-ts-cursor)
5726 (js2-report-error "msg.unterminated.string.lit")
5727 (throw 'return js2-STRING))
5728 (when (eq c ?\\)
5729 ;; We've hit an escaped character
5730 (setq c (js2-get-char))
5731 (case c
5732 (?b (setq c ?\b))
5733 (?f (setq c ?\f))
5734 (?n (setq c ?\n))
5735 (?r (setq c ?\r))
5736 (?t (setq c ?\t))
5737 (?v (setq c ?\v))
5738 (?u
5739 (setq c1 (js2-read-unicode-escape))
5740 (if js2-parse-ide-mode
5741 (if c1
5742 (progn
5743 ;; just copy the string in IDE-mode
5744 (js2-add-to-string ?\\)
5745 (js2-add-to-string ?u)
5746 (dotimes (i 3)
5747 (js2-add-to-string (js2-get-char)))
5748 (setq c (js2-get-char))) ; added at end of loop
5749 ;; flag it as an invalid escape
5750 (js2-report-warning "msg.invalid.escape"
5751 nil (- js2-ts-cursor 2) 6))
5752 ;; Get 4 hex digits; if the u escape is not
5753 ;; followed by 4 hex digits, use 'u' + the
5754 ;; literal character sequence that follows.
5755 (js2-add-to-string ?u)
5756 (setq escape-val 0)
5757 (dotimes (i 4)
5758 (setq c (js2-get-char)
5759 escape-val (js2-x-digit-to-int c escape-val))
5760 (if (minusp escape-val)
5761 (throw 'continue nil))
5762 (js2-add-to-string c))
5763 ;; prepare for replace of stored 'u' sequence by escape value
5764 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5765 c escape-val)))
5766 (?x
5767 ;; Get 2 hex digits, defaulting to 'x'+literal
5768 ;; sequence, as above.
5769 (setq c (js2-get-char)
5770 escape-val (js2-x-digit-to-int c 0))
5771 (if (minusp escape-val)
5772 (progn
5773 (js2-add-to-string ?x)
5774 (throw 'continue nil))
5775 (setq c1 c
5776 c (js2-get-char)
5777 escape-val (js2-x-digit-to-int c escape-val))
5778 (if (minusp escape-val)
5779 (progn
5780 (js2-add-to-string ?x)
5781 (js2-add-to-string c1)
5782 (throw 'continue nil))
5783 ;; got 2 hex digits
5784 (setq c escape-val))))
5785 (?\n
5786 ;; Remove line terminator after escape to follow
5787 ;; SpiderMonkey and C/C++
5788 (setq c (js2-get-char))
5789 (throw 'continue nil))
5790 (t
5791 (when (and (<= ?0 c) (< c ?8))
5792 (setq val (- c ?0)
5793 c (js2-get-char))
5794 (when (and (<= ?0 c) (< c ?8))
5795 (setq val (- (+ (* 8 val) c) ?0)
5796 c (js2-get-char))
5797 (when (and (<= ?0 c)
5798 (< c ?8)
5799 (< val #o37))
5800 ;; c is 3rd char of octal sequence only
5801 ;; if the resulting val <= 0377
5802 (setq val (- (+ (* 8 val) c) ?0)
5803 c (js2-get-char))))
5804 (js2-unget-char)
5805 (setq c val)))))
5806 (js2-add-to-string c)
5807 (setq c (js2-get-char)))))
5808 (setq js2-ts-string (js2-get-string-from-buffer))
5809 (throw 'return js2-STRING))
5810 (case c
5811 (?\;
5812 (throw 'return js2-SEMI))
5813 (?\[
5814 (throw 'return js2-LB))
5815 (?\]
5816 (throw 'return js2-RB))
5817 (?{
5818 (throw 'return js2-LC))
5819 (?}
5820 (throw 'return js2-RC))
5821 (?\(
5822 (throw 'return js2-LP))
5823 (?\)
5824 (throw 'return js2-RP))
5825 (?,
5826 (throw 'return js2-COMMA))
5827 (??
5828 (throw 'return js2-HOOK))
5829 (?:
5830 (if (js2-match-char ?:)
5831 (js2-ts-return js2-COLONCOLON)
5832 (throw 'return js2-COLON)))
5833 (?.
5834 (if (js2-match-char ?.)
5835 (if (js2-match-char ?.)
5836 (js2-ts-return js2-TRIPLEDOT)
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 (defun js2-match-contextual-kwd (name)
7189 "Consume and return t if next token is `js2-NAME', and its
7190 string is NAME. Returns nil and does nothing otherwise."
7191 (if (or (/= (js2-peek-token) js2-NAME)
7192 (not (string= js2-ts-string name)))
7193 nil
7194 (js2-consume-token)
7195 (js2-record-face 'font-lock-keyword-face)
7196 t))
7197
7198 (defsubst js2-valid-prop-name-token (tt)
7199 (or (= tt js2-NAME)
7200 (when (and js2-allow-keywords-as-property-names
7201 (plusp tt)
7202 (aref js2-kwd-tokens tt))
7203 (js2-save-name-token-data js2-token-beg (js2-token-name tt))
7204 t)))
7205
7206 (defsubst js2-match-prop-name ()
7207 "Consume token and return t if next token is a valid property name.
7208 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7209 is non-nil and it's a keyword token."
7210 (if (js2-valid-prop-name-token (js2-peek-token))
7211 (progn
7212 (js2-consume-token)
7213 t)
7214 nil))
7215
7216 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7217 (if (js2-match-prop-name)
7218 t
7219 (js2-report-error msg-id nil pos len)
7220 nil))
7221
7222 (defsubst js2-peek-token-or-eol ()
7223 "Return js2-EOL if the current token immediately follows a newline.
7224 Else returns the current token. Used in situations where we don't
7225 consider certain token types valid if they are preceded by a newline.
7226 One example is the postfix ++ or -- operator, which has to be on the
7227 same line as its operand."
7228 (let ((tt (js2-peek-token)))
7229 ;; Check for last peeked token flags
7230 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7231 js2-EOL
7232 tt)))
7233
7234 (defsubst js2-set-check-for-label ()
7235 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7236 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7237
7238 (defsubst js2-must-match (token msg-id &optional pos len)
7239 "Match next token to token code TOKEN, or record a syntax error.
7240 MSG-ID is the error message to report if the match fails.
7241 Returns t on match, nil if no match."
7242 (if (js2-match-token token)
7243 t
7244 (js2-report-error msg-id nil pos len)
7245 nil))
7246
7247 (defsubst js2-inside-function ()
7248 (plusp js2-nesting-of-function))
7249
7250 (defsubst js2-set-requires-activation ()
7251 (if (js2-function-node-p js2-current-script-or-fn)
7252 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7253
7254 (defsubst js2-check-activation-name (name token)
7255 (when (js2-inside-function)
7256 ;; skip language-version 1.2 check from Rhino
7257 (if (or (string= "arguments" name)
7258 (and js2-compiler-activation-names ; only used in codegen
7259 (gethash name js2-compiler-activation-names)))
7260 (js2-set-requires-activation))))
7261
7262 (defsubst js2-set-is-generator ()
7263 (if (js2-function-node-p js2-current-script-or-fn)
7264 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7265
7266 (defsubst js2-must-have-xml ()
7267 (unless js2-compiler-xml-available
7268 (js2-report-error "msg.XML.not.available")))
7269
7270 (defsubst js2-push-scope (scope)
7271 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7272 (assert (js2-scope-p scope))
7273 (assert (null (js2-scope-parent-scope scope)))
7274 (assert (not (eq js2-current-scope scope)))
7275 (setf (js2-scope-parent-scope scope) js2-current-scope
7276 js2-current-scope scope))
7277
7278 (defsubst js2-pop-scope ()
7279 (setq js2-current-scope
7280 (js2-scope-parent-scope js2-current-scope)))
7281
7282 (defsubst js2-enter-loop (loop-node)
7283 (push loop-node js2-loop-set)
7284 (push loop-node js2-loop-and-switch-set)
7285 (js2-push-scope loop-node)
7286 ;; Tell the current labeled statement (if any) its statement,
7287 ;; and set the jump target of the first label to the loop.
7288 ;; These are used in `js2-parse-continue' to verify that the
7289 ;; continue target is an actual labeled loop. (And for codegen.)
7290 (when js2-labeled-stmt
7291 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7292 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7293 js2-labeled-stmt))) loop-node)))
7294
7295 (defsubst js2-exit-loop ()
7296 (pop js2-loop-set)
7297 (pop js2-loop-and-switch-set)
7298 (js2-pop-scope))
7299
7300 (defsubst js2-enter-switch (switch-node)
7301 (push switch-node js2-loop-and-switch-set))
7302
7303 (defsubst js2-exit-switch ()
7304 (pop js2-loop-and-switch-set))
7305
7306 (defun js2-parse (&optional buf cb)
7307 "Tells the js2 parser to parse a region of JavaScript.
7308
7309 BUF is a buffer or buffer name containing the code to parse.
7310 Call `narrow-to-region' first to parse only part of the buffer.
7311
7312 The returned AST root node is given some additional properties:
7313 `node-count' - total number of nodes in the AST
7314 `buffer' - BUF. The buffer it refers to may change or be killed,
7315 so the value is not necessarily reliable.
7316
7317 An optional callback CB can be specified to report parsing
7318 progress. If `(functionp CB)' returns t, it will be called with
7319 the current line number once before parsing begins, then again
7320 each time the lexer reaches a new line number.
7321
7322 CB can also be a list of the form `(symbol cb ...)' to specify
7323 multiple callbacks with different criteria. Each symbol is a
7324 criterion keyword, and the following element is the callback to
7325 call
7326
7327 :line - called whenever the line number changes
7328 :token - called for each new token consumed
7329
7330 The list of criteria could be extended to include entering or
7331 leaving a statement, an expression, or a function definition."
7332 (if (and cb (not (functionp cb)))
7333 (error "criteria callbacks not yet implemented"))
7334 (let ((inhibit-point-motion-hooks t)
7335 (js2-compiler-xml-available (>= js2-language-version 160))
7336 ;; This is a recursive-descent parser, so give it a big stack.
7337 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7338 (max-specpdl-size (max max-specpdl-size 3000))
7339 (case-fold-search nil)
7340 ast)
7341 (message nil) ; clear any error message from previous parse
7342 (save-excursion
7343 (when buf (set-buffer buf))
7344 (setq js2-scanned-comments nil
7345 js2-parsed-errors nil
7346 js2-parsed-warnings nil
7347 js2-imenu-recorder nil
7348 js2-imenu-function-map nil
7349 js2-label-set nil)
7350 (js2-init-scanner)
7351 (setq ast (js2-with-unmodifying-text-property-changes
7352 (js2-do-parse)))
7353 (unless js2-ts-hit-eof
7354 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7355 (setf (js2-ast-root-errors ast) js2-parsed-errors
7356 (js2-ast-root-warnings ast) js2-parsed-warnings)
7357 ;; if we didn't find any declarations, put a dummy in this list so we
7358 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7359 (unless js2-imenu-recorder
7360 (setq js2-imenu-recorder 'empty))
7361 (run-hooks 'js2-parse-finished-hook)
7362 ast)))
7363
7364 ;; Corresponds to Rhino's Parser.parse() method.
7365 (defun js2-do-parse ()
7366 "Parse current buffer starting from current point.
7367 Scanner should be initialized."
7368 (let ((pos js2-ts-cursor)
7369 (end js2-ts-cursor) ; in case file is empty
7370 root n tt)
7371 ;; initialize buffer-local parsing vars
7372 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7373 js2-current-script-or-fn root
7374 js2-current-scope root
7375 js2-current-flagged-token js2-EOF
7376 js2-nesting-of-function 0
7377 js2-labeled-stmt nil
7378 js2-recorded-identifiers nil) ; for js2-highlight
7379 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7380 (if (= tt js2-FUNCTION)
7381 (progn
7382 (js2-consume-token)
7383 (setq n (js2-parse-function (if js2-called-by-compile-function
7384 'FUNCTION_EXPRESSION
7385 'FUNCTION_STATEMENT))))
7386 ;; not a function - parse a statement
7387 (setq n (js2-parse-statement)))
7388 ;; add function or statement to script
7389 (setq end (js2-node-end n))
7390 (js2-block-node-push root n))
7391 ;; add comments to root in lexical order
7392 (when js2-scanned-comments
7393 ;; if we find a comment beyond end of normal kids, use its end
7394 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7395 (dolist (comment js2-scanned-comments)
7396 (push comment (js2-ast-root-comments root))
7397 (js2-node-add-children root comment)))
7398 (setf (js2-node-len root) (- end pos))
7399 ;; Give extensions a chance to muck with things before highlighting starts.
7400 (let ((js2-additional-externs js2-additional-externs))
7401 (dolist (callback js2-post-parse-callbacks)
7402 (funcall callback))
7403 (js2-highlight-undeclared-vars))
7404 root))
7405
7406 (defun js2-function-parser ()
7407 (js2-consume-token)
7408 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7409
7410 (defun js2-parse-function-closure-body (fn-node)
7411 "Parse a JavaScript 1.8 function closure body."
7412 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7413 (if js2-ts-hit-eof
7414 (js2-report-error "msg.no.brace.body" nil
7415 (js2-node-pos fn-node)
7416 (- js2-ts-cursor (js2-node-pos fn-node)))
7417 (js2-node-add-children fn-node
7418 (setf (js2-function-node-body fn-node)
7419 (js2-parse-expr t))))))
7420
7421 (defun js2-parse-function-body (fn-node)
7422 (js2-must-match js2-LC "msg.no.brace.body"
7423 (js2-node-pos fn-node)
7424 (- js2-ts-cursor (js2-node-pos fn-node)))
7425 (let ((pos js2-token-beg) ; LC position
7426 (pn (make-js2-block-node)) ; starts at LC position
7427 tt
7428 end)
7429 (incf js2-nesting-of-function)
7430 (unwind-protect
7431 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7432 (= tt js2-EOF)
7433 (= tt js2-RC)))
7434 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7435 (js2-parse-statement)
7436 (js2-consume-token)
7437 (js2-parse-function 'FUNCTION_STATEMENT))))
7438 (decf js2-nesting-of-function))
7439 (setq end js2-token-end) ; assume no curly and leave at current token
7440 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7441 (setq end js2-token-end))
7442 (setf (js2-node-pos pn) pos
7443 (js2-node-len pn) (- end pos))
7444 (setf (js2-function-node-body fn-node) pn)
7445 (js2-node-add-children fn-node pn)
7446 pn))
7447
7448 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7449 "Declare and fontify destructuring parameters inside NODE.
7450 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7451 (cond
7452 ((js2-name-node-p node)
7453 (let (leftpos)
7454 (js2-define-symbol decl-type (js2-name-node-name node)
7455 node ignore-not-in-block)
7456 (when face
7457 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7458 (+ leftpos (js2-node-len node))
7459 face 'record))))
7460 ((js2-object-node-p node)
7461 (dolist (elem (js2-object-node-elems node))
7462 (js2-define-destruct-symbols
7463 (if (js2-object-prop-node-p elem)
7464 (js2-object-prop-node-right elem)
7465 ;; abbreviated destructuring {a, b}
7466 elem)
7467 decl-type face ignore-not-in-block)))
7468 ((js2-array-node-p node)
7469 (dolist (elem (js2-array-node-elems node))
7470 (when elem
7471 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7472 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7473 (js2-node-len node)))))
7474
7475 (defun js2-parse-function-params (fn-node pos)
7476 (if (js2-match-token js2-RP)
7477 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7478 (let (params len param default-found rest-param-at)
7479 (loop for tt = (js2-peek-token)
7480 do
7481 (cond
7482 ;; destructuring param
7483 ((or (= tt js2-LB) (= tt js2-LC))
7484 (when default-found
7485 (js2-report-error "msg.no.default.after.default.param"))
7486 (setq param (js2-parse-destruct-primary-expr))
7487 (js2-define-destruct-symbols param
7488 js2-LP
7489 'js2-function-param-face)
7490 (push param params))
7491 ;; variable name
7492 (t
7493 (when (and (>= js2-language-version 200)
7494 (js2-match-token js2-TRIPLEDOT)
7495 (not rest-param-at))
7496 ;; to report errors if there are more parameters
7497 (setq rest-param-at (length params)))
7498 (js2-must-match js2-NAME "msg.no.parm")
7499 (js2-record-face 'js2-function-param-face)
7500 (setq param (js2-create-name-node))
7501 (js2-define-symbol js2-LP js2-ts-string param)
7502 ;; default parameter value
7503 (when (or (and default-found
7504 (not rest-param-at)
7505 (js2-must-match js2-ASSIGN
7506 "msg.no.default.after.default.param"
7507 (js2-node-pos param)
7508 (js2-node-len param)))
7509 (and (>= js2-language-version 200)
7510 (js2-match-token js2-ASSIGN)))
7511 (let* ((pos (js2-node-pos param))
7512 (tt js2-current-token)
7513 (op-pos (- js2-token-beg pos))
7514 (left param)
7515 (right (js2-parse-assign-expr))
7516 (len (- (js2-node-end right) pos)))
7517 (setq param (make-js2-assign-node
7518 :type tt :pos pos :len len :op-pos op-pos
7519 :left left :right right)
7520 default-found t)
7521 (js2-node-add-children param left right)))
7522 (push param params)))
7523 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7524 (js2-report-error "msg.param.after.rest" nil
7525 (js2-node-pos param) (js2-node-len param)))
7526 while
7527 (js2-match-token js2-COMMA))
7528 (when (js2-must-match js2-RP "msg.no.paren.after.parms")
7529 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7530 (when rest-param-at
7531 (setf (js2-function-node-rest-p fn-node) t))
7532 (dolist (p params)
7533 (js2-node-add-children fn-node p)
7534 (push p (js2-function-node-params fn-node))))))
7535
7536 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7537 "Possibly show inconsistent-return warning.
7538 Last token scanned is the close-curly for the function body."
7539 (when (and js2-mode-show-strict-warnings
7540 js2-strict-inconsistent-return-warning
7541 (not (js2-has-consistent-return-usage
7542 (js2-function-node-body fn-node))))
7543 ;; Have it extend from close-curly to bol or beginning of block.
7544 (let ((pos (save-excursion
7545 (goto-char js2-token-end)
7546 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7547 (point-at-bol))))
7548 (end js2-token-end))
7549 (if (plusp (js2-name-node-length name))
7550 (js2-add-strict-warning "msg.no.return.value"
7551 (js2-name-node-name name) pos end)
7552 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7553
7554 (defun js2-parse-function (function-type)
7555 "Function parser. FUNCTION-TYPE is a symbol."
7556 (let ((pos js2-token-beg) ; start of 'function' keyword
7557 name
7558 name-beg
7559 name-end
7560 fn-node
7561 lp
7562 (synthetic-type function-type)
7563 member-expr-node)
7564 ;; parse function name, expression, or non-name (anonymous)
7565 (cond
7566 ;; function foo(...)
7567 ((js2-match-token js2-NAME)
7568 (setq name (js2-create-name-node t)
7569 name-beg js2-token-beg
7570 name-end js2-token-end)
7571 (unless (js2-match-token js2-LP)
7572 (when js2-allow-member-expr-as-function-name
7573 ;; function foo.bar(...)
7574 (setq member-expr-node name
7575 name nil
7576 member-expr-node (js2-parse-member-expr-tail
7577 nil member-expr-node)))
7578 (js2-must-match js2-LP "msg.no.paren.parms")))
7579 ((js2-match-token js2-LP)
7580 nil) ; anonymous function: leave name as null
7581 (t
7582 ;; function random-member-expr(...)
7583 (when js2-allow-member-expr-as-function-name
7584 ;; Note that memberExpr can not start with '(' like
7585 ;; in function (1+2).toString(), because 'function (' already
7586 ;; processed as anonymous function
7587 (setq member-expr-node (js2-parse-member-expr)))
7588 (js2-must-match js2-LP "msg.no.paren.parms")))
7589 (if (= js2-current-token js2-LP) ; eventually matched LP?
7590 (setq lp js2-token-beg))
7591 (if member-expr-node
7592 (progn
7593 (setq synthetic-type 'FUNCTION_EXPRESSION)
7594 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7595 (if name
7596 (js2-set-face name-beg name-end
7597 'font-lock-function-name-face 'record)))
7598 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7599 (plusp (js2-name-node-length name)))
7600 ;; Function statements define a symbol in the enclosing scope
7601 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7602 (setf fn-node (make-js2-function-node :pos pos
7603 :name name
7604 :form function-type
7605 :lp (if lp (- lp pos))))
7606 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7607 ;; 1. Nested functions are not affected by the dynamic scope flag
7608 ;; as dynamic scope is already a parent of their scope.
7609 ;; 2. Functions defined under the with statement also immune to
7610 ;; this setup, in which case dynamic scope is ignored in favor
7611 ;; of the with object.
7612 (setf (js2-function-node-ignore-dynamic fn-node) t))
7613 ;; dynamically bind all the per-function variables
7614 (let ((js2-current-script-or-fn fn-node)
7615 (js2-current-scope fn-node)
7616 (js2-nesting-of-with 0)
7617 (js2-end-flags 0)
7618 js2-label-set
7619 js2-loop-set
7620 js2-loop-and-switch-set)
7621 (js2-parse-function-params fn-node pos)
7622 (if (and (>= js2-language-version 180)
7623 (/= (js2-peek-token) js2-LC))
7624 (js2-parse-function-closure-body fn-node)
7625 (js2-parse-function-body fn-node))
7626 (if name
7627 (js2-node-add-children fn-node name))
7628 (js2-check-inconsistent-return-warning fn-node name)
7629 ;; Function expressions define a name only in the body of the
7630 ;; function, and only if not hidden by a parameter name
7631 (if (and name
7632 (eq synthetic-type 'FUNCTION_EXPRESSION)
7633 (null (js2-scope-get-symbol js2-current-scope
7634 (js2-name-node-name name))))
7635 (js2-define-symbol js2-FUNCTION
7636 (js2-name-node-name name)
7637 fn-node))
7638 (if (and name
7639 (not (eq function-type 'FUNCTION_EXPRESSION)))
7640 (js2-record-imenu-functions fn-node)))
7641 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7642 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7643 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7644 ;; We wait until after parsing the function to set its parent scope,
7645 ;; since `js2-define-symbol' needs the defining-scope check to stop
7646 ;; at the function boundary when checking for redeclarations.
7647 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7648 fn-node))
7649
7650 (defun js2-parse-statements (&optional parent)
7651 "Parse a statement list. Last token consumed must be js2-LC.
7652
7653 PARENT can be a `js2-block-node', in which case the statements are
7654 appended to PARENT. Otherwise a new `js2-block-node' is created
7655 and returned.
7656
7657 This function does not match the closing js2-RC: the caller
7658 matches the RC so it can provide a suitable error message if not
7659 matched. This means it's up to the caller to set the length of
7660 the node to include the closing RC. The node start pos is set to
7661 the absolute buffer start position, and the caller should fix it
7662 up to be relative to the parent node. All children of this block
7663 node are given relative start positions and correct lengths."
7664 (let ((pn (or parent (make-js2-block-node)))
7665 tt)
7666 (setf (js2-node-pos pn) js2-token-beg)
7667 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7668 (/= tt js2-RC))
7669 (js2-block-node-push pn (js2-parse-statement)))
7670 pn))
7671
7672 (defun js2-parse-statement ()
7673 (let (tt pn beg end)
7674 ;; coarse-grained user-interrupt check - needs work
7675 (and js2-parse-interruptable-p
7676 (zerop (% (incf js2-parse-stmt-count)
7677 js2-statements-per-pause))
7678 (input-pending-p)
7679 (throw 'interrupted t))
7680 (setq pn (js2-statement-helper))
7681 ;; no-side-effects warning check
7682 (unless (js2-node-has-side-effects pn)
7683 (setq end (js2-node-end pn))
7684 (save-excursion
7685 (goto-char end)
7686 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7687 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7688 pn))
7689
7690 ;; These correspond to the switch cases in Parser.statementHelper
7691 (defconst js2-parsers
7692 (let ((parsers (make-vector js2-num-tokens
7693 #'js2-parse-expr-stmt)))
7694 (aset parsers js2-BREAK #'js2-parse-break)
7695 (aset parsers js2-CONST #'js2-parse-const-var)
7696 (aset parsers js2-CONTINUE #'js2-parse-continue)
7697 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7698 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7699 (aset parsers js2-DO #'js2-parse-do)
7700 (aset parsers js2-FOR #'js2-parse-for)
7701 (aset parsers js2-FUNCTION #'js2-function-parser)
7702 (aset parsers js2-IF #'js2-parse-if)
7703 (aset parsers js2-LC #'js2-parse-block)
7704 (aset parsers js2-LET #'js2-parse-let-stmt)
7705 (aset parsers js2-NAME #'js2-parse-name-or-label)
7706 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7707 (aset parsers js2-SEMI #'js2-parse-semi)
7708 (aset parsers js2-SWITCH #'js2-parse-switch)
7709 (aset parsers js2-THROW #'js2-parse-throw)
7710 (aset parsers js2-TRY #'js2-parse-try)
7711 (aset parsers js2-VAR #'js2-parse-const-var)
7712 (aset parsers js2-WHILE #'js2-parse-while)
7713 (aset parsers js2-WITH #'js2-parse-with)
7714 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7715 parsers)
7716 "A vector mapping token types to parser functions.")
7717
7718 (defsubst js2-parse-warn-missing-semi (beg end)
7719 (and js2-mode-show-strict-warnings
7720 js2-strict-missing-semi-warning
7721 (js2-add-strict-warning
7722 "msg.missing.semi" nil
7723 ;; back up to beginning of statement or line
7724 (max beg (save-excursion
7725 (goto-char end)
7726 (point-at-bol)))
7727 end)))
7728
7729 (defconst js2-no-semi-insertion
7730 (list js2-IF
7731 js2-SWITCH
7732 js2-WHILE
7733 js2-DO
7734 js2-FOR
7735 js2-TRY
7736 js2-WITH
7737 js2-LC
7738 js2-ERROR
7739 js2-SEMI
7740 js2-FUNCTION)
7741 "List of tokens that don't do automatic semicolon insertion.")
7742
7743 (defconst js2-autoinsert-semi-and-warn
7744 (list js2-ERROR js2-EOF js2-RC))
7745
7746 (defun js2-statement-helper ()
7747 (let* ((tt (js2-peek-token))
7748 (first-tt tt)
7749 (beg js2-token-beg)
7750 (parser (if (= tt js2-ERROR)
7751 #'js2-parse-semi
7752 (aref js2-parsers tt)))
7753 pn
7754 tt-flagged)
7755 ;; If the statement is set, then it's been told its label by now.
7756 (and js2-labeled-stmt
7757 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7758 (setq js2-labeled-stmt nil))
7759 (setq pn (funcall parser))
7760 ;; Don't do auto semi insertion for certain statement types.
7761 (unless (or (memq first-tt js2-no-semi-insertion)
7762 (js2-labeled-stmt-node-p pn))
7763 (js2-auto-insert-semicolon pn))
7764 pn))
7765
7766 (defun js2-auto-insert-semicolon (pn)
7767 (let* ((tt-flagged (js2-peek-flagged-token))
7768 (tt (logand tt-flagged js2-clear-ti-mask))
7769 (pos (js2-node-pos pn)))
7770 (cond
7771 ((= tt js2-SEMI)
7772 ;; Consume ';' as a part of expression
7773 (js2-consume-token)
7774 ;; extend the node bounds to include the semicolon.
7775 (setf (js2-node-len pn) (- js2-token-end pos)))
7776 ((memq tt js2-autoinsert-semi-and-warn)
7777 ;; Autoinsert ;
7778 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7779 (t
7780 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7781 ;; Report error if no EOL or autoinsert ';' otherwise
7782 (js2-report-error "msg.no.semi.stmt")
7783 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7784
7785 (defun js2-parse-condition ()
7786 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7787 The parens are discarded and the expression node is returned.
7788 The `pos' field of the return value is set to an absolute position
7789 that must be fixed up by the caller.
7790 Return value is a list (EXPR LP RP), with absolute paren positions."
7791 (let (pn lp rp)
7792 (if (js2-must-match js2-LP "msg.no.paren.cond")
7793 (setq lp js2-token-beg))
7794 (setq pn (js2-parse-expr))
7795 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7796 (setq rp js2-token-beg))
7797 ;; Report strict warning on code like "if (a = 7) ..."
7798 (if (and js2-strict-cond-assign-warning
7799 (js2-assign-node-p pn))
7800 (js2-add-strict-warning "msg.equal.as.assign" nil
7801 (js2-node-pos pn)
7802 (+ (js2-node-pos pn)
7803 (js2-node-len pn))))
7804 (list pn lp rp)))
7805
7806 (defun js2-parse-if ()
7807 "Parser for if-statement. Last matched token must be js2-IF."
7808 (let ((pos js2-token-beg)
7809 cond
7810 if-true
7811 if-false
7812 else-pos
7813 end
7814 pn)
7815 (js2-consume-token)
7816 (setq cond (js2-parse-condition)
7817 if-true (js2-parse-statement)
7818 if-false (if (js2-match-token js2-ELSE)
7819 (progn
7820 (setq else-pos (- js2-token-beg pos))
7821 (js2-parse-statement)))
7822 end (js2-node-end (or if-false if-true))
7823 pn (make-js2-if-node :pos pos
7824 :len (- end pos)
7825 :condition (car cond)
7826 :then-part if-true
7827 :else-part if-false
7828 :else-pos else-pos
7829 :lp (js2-relpos (second cond) pos)
7830 :rp (js2-relpos (third cond) pos)))
7831 (js2-node-add-children pn (car cond) if-true if-false)
7832 pn))
7833
7834 (defun js2-parse-switch ()
7835 "Parser for if-statement. Last matched token must be js2-SWITCH."
7836 (let ((pos js2-token-beg)
7837 tt
7838 pn
7839 discriminant
7840 has-default
7841 case-expr
7842 case-node
7843 case-pos
7844 cases
7845 stmt
7846 lp
7847 rp)
7848 (js2-consume-token)
7849 (if (js2-must-match js2-LP "msg.no.paren.switch")
7850 (setq lp js2-token-beg))
7851 (setq discriminant (js2-parse-expr)
7852 pn (make-js2-switch-node :discriminant discriminant
7853 :pos pos
7854 :lp (js2-relpos lp pos)))
7855 (js2-node-add-children pn discriminant)
7856 (js2-enter-switch pn)
7857 (unwind-protect
7858 (progn
7859 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7860 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7861 (js2-must-match js2-LC "msg.no.brace.switch")
7862 (catch 'break
7863 (while t
7864 (setq tt (js2-next-token)
7865 case-pos js2-token-beg)
7866 (cond
7867 ((= tt js2-RC)
7868 (setf (js2-node-len pn) (- js2-token-end pos))
7869 (throw 'break nil)) ; done
7870 ((= tt js2-CASE)
7871 (setq case-expr (js2-parse-expr))
7872 (js2-must-match js2-COLON "msg.no.colon.case"))
7873 ((= tt js2-DEFAULT)
7874 (if has-default
7875 (js2-report-error "msg.double.switch.default"))
7876 (setq has-default t
7877 case-expr nil)
7878 (js2-must-match js2-COLON "msg.no.colon.case"))
7879 (t
7880 (js2-report-error "msg.bad.switch")
7881 (throw 'break nil)))
7882 (setq case-node (make-js2-case-node :pos case-pos
7883 :len (- js2-token-end case-pos)
7884 :expr case-expr))
7885 (js2-node-add-children case-node case-expr)
7886 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7887 (/= tt js2-CASE)
7888 (/= tt js2-DEFAULT)
7889 (/= tt js2-EOF))
7890 (setf stmt (js2-parse-statement)
7891 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7892 (js2-block-node-push case-node stmt))
7893 (push case-node cases)))
7894 ;; add cases last, as pushing reverses the order to be correct
7895 (dolist (kid cases)
7896 (js2-node-add-children pn kid)
7897 (push kid (js2-switch-node-cases pn)))
7898 pn) ; return value
7899 (js2-exit-switch))))
7900
7901 (defun js2-parse-while ()
7902 "Parser for while-statement. Last matched token must be js2-WHILE."
7903 (let ((pos js2-token-beg)
7904 (pn (make-js2-while-node))
7905 cond
7906 body)
7907 (js2-consume-token)
7908 (js2-enter-loop pn)
7909 (unwind-protect
7910 (progn
7911 (setf cond (js2-parse-condition)
7912 (js2-while-node-condition pn) (car cond)
7913 body (js2-parse-statement)
7914 (js2-while-node-body pn) body
7915 (js2-node-len pn) (- (js2-node-end body) pos)
7916 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7917 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7918 (js2-node-add-children pn body (car cond)))
7919 (js2-exit-loop))
7920 pn))
7921
7922 (defun js2-parse-do ()
7923 "Parser for do-statement. Last matched token must be js2-DO."
7924 (let ((pos js2-token-beg)
7925 (pn (make-js2-do-node))
7926 cond
7927 body
7928 end)
7929 (js2-consume-token)
7930 (js2-enter-loop pn)
7931 (unwind-protect
7932 (progn
7933 (setq body (js2-parse-statement))
7934 (js2-must-match js2-WHILE "msg.no.while.do")
7935 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7936 cond (js2-parse-condition)
7937 (js2-do-node-condition pn) (car cond)
7938 (js2-do-node-body pn) body
7939 end js2-ts-cursor
7940 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7941 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7942 (js2-node-add-children pn (car cond) body))
7943 (js2-exit-loop))
7944 ;; Always auto-insert semicolon to follow SpiderMonkey:
7945 ;; It is required by ECMAScript but is ignored by the rest of
7946 ;; world; see bug 238945
7947 (if (js2-match-token js2-SEMI)
7948 (setq end js2-ts-cursor))
7949 (setf (js2-node-len pn) (- end pos))
7950 pn))
7951
7952 (defun js2-parse-for ()
7953 "Parser for for-statement. Last matched token must be js2-FOR.
7954 Parses for, for-in, and for each-in statements."
7955 (let ((for-pos js2-token-beg)
7956 pn is-for-each is-for-in-or-of is-for-of
7957 in-pos each-pos tmp-pos
7958 init ; Node init is also foo in 'foo in object'
7959 cond ; Node cond is also object in 'foo in object'
7960 incr ; 3rd section of for-loop initializer
7961 body tt lp rp)
7962 (js2-consume-token)
7963 ;; See if this is a for each () instead of just a for ()
7964 (when (js2-match-token js2-NAME)
7965 (if (string= "each" js2-ts-string)
7966 (progn
7967 (setq is-for-each t
7968 each-pos (- js2-token-beg for-pos)) ; relative
7969 (js2-record-face 'font-lock-keyword-face))
7970 (js2-report-error "msg.no.paren.for")))
7971 (if (js2-must-match js2-LP "msg.no.paren.for")
7972 (setq lp (- js2-token-beg for-pos)))
7973 (setq tt (js2-peek-token))
7974 ;; 'for' makes local scope
7975 (js2-push-scope (make-js2-scope))
7976 (unwind-protect
7977 ;; parse init clause
7978 (let ((js2-in-for-init t)) ; set as dynamic variable
7979 (cond
7980 ((= tt js2-SEMI)
7981 (setq init (make-js2-empty-expr-node)))
7982 ((or (= tt js2-VAR) (= tt js2-LET))
7983 (js2-consume-token)
7984 (setq init (js2-parse-variables tt js2-token-beg)))
7985 (t
7986 (setq init (js2-parse-expr)))))
7987 (if (or (js2-match-token js2-IN)
7988 (and (>= js2-language-version 200)
7989 (js2-match-contextual-kwd "of")
7990 (setq is-for-of t)))
7991 (setq is-for-in-or-of t
7992 in-pos (- js2-token-beg for-pos)
7993 ;; scope of iteration target object is not the scope we've created above.
7994 ;; stash current scope temporary.
7995 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7996 (js2-parse-expr))) ; object over which we're iterating
7997 ;; else ordinary for loop - parse cond and incr
7998 (js2-must-match js2-SEMI "msg.no.semi.for")
7999 (setq cond (if (= (js2-peek-token) js2-SEMI)
8000 (make-js2-empty-expr-node) ; no loop condition
8001 (js2-parse-expr)))
8002 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8003 (setq tmp-pos js2-token-end
8004 incr (if (= (js2-peek-token) js2-RP)
8005 (make-js2-empty-expr-node :pos tmp-pos)
8006 (js2-parse-expr))))
8007 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8008 (setq rp (- js2-token-beg for-pos)))
8009 (if (not is-for-in-or-of)
8010 (setq pn (make-js2-for-node :init init
8011 :condition cond
8012 :update incr
8013 :lp lp
8014 :rp rp))
8015 ;; cond could be null if 'in obj' got eaten by the init node.
8016 (if (js2-infix-node-p init)
8017 ;; it was (foo in bar) instead of (var foo in bar)
8018 (setq cond (js2-infix-node-right init)
8019 init (js2-infix-node-left init))
8020 (if (and (js2-var-decl-node-p init)
8021 (> (length (js2-var-decl-node-kids init)) 1))
8022 (js2-report-error "msg.mult.index")))
8023 (setq pn (make-js2-for-in-node :iterator init
8024 :object cond
8025 :in-pos in-pos
8026 :foreach-p is-for-each
8027 :each-pos each-pos
8028 :forof-p is-for-of
8029 :lp lp
8030 :rp rp)))
8031 (unwind-protect
8032 (progn
8033 (js2-enter-loop pn)
8034 ;; We have to parse the body -after- creating the loop node,
8035 ;; so that the loop node appears in the js2-loop-set, allowing
8036 ;; break/continue statements to find the enclosing loop.
8037 (setf body (js2-parse-statement)
8038 (js2-loop-node-body pn) body
8039 (js2-node-pos pn) for-pos
8040 (js2-node-len pn) (- (js2-node-end body) for-pos))
8041 (js2-node-add-children pn init cond incr body))
8042 ;; finally
8043 (js2-exit-loop))
8044 (js2-pop-scope))
8045 pn))
8046
8047 (defun js2-parse-try ()
8048 "Parser for try-statement. Last matched token must be js2-TRY."
8049 (let ((try-pos js2-token-beg)
8050 try-end
8051 try-block
8052 catch-blocks
8053 finally-block
8054 saw-default-catch
8055 peek
8056 param
8057 catch-cond
8058 catch-node
8059 guard-kwd
8060 catch-pos
8061 finally-pos
8062 pn
8063 block
8064 lp
8065 rp)
8066 (js2-consume-token)
8067 (if (/= (js2-peek-token) js2-LC)
8068 (js2-report-error "msg.no.brace.try"))
8069 (setq try-block (js2-parse-statement)
8070 try-end (js2-node-end try-block)
8071 peek (js2-peek-token))
8072 (cond
8073 ((= peek js2-CATCH)
8074 (while (js2-match-token js2-CATCH)
8075 (setq catch-pos js2-token-beg
8076 guard-kwd nil
8077 catch-cond nil
8078 lp nil
8079 rp nil)
8080 (if saw-default-catch
8081 (js2-report-error "msg.catch.unreachable"))
8082 (if (js2-must-match js2-LP "msg.no.paren.catch")
8083 (setq lp (- js2-token-beg catch-pos)))
8084 (js2-push-scope (make-js2-scope))
8085 (let ((tt (js2-peek-token)))
8086 (cond
8087 ;; destructuring pattern
8088 ;; catch ({ message, file }) { ... }
8089 ((or (= tt js2-LB) (= tt js2-LC))
8090 (setq param (js2-parse-destruct-primary-expr))
8091 (js2-define-destruct-symbols param js2-LET nil))
8092 ;; simple name
8093 (t
8094 (js2-must-match js2-NAME "msg.bad.catchcond")
8095 (setq param (js2-create-name-node))
8096 (js2-define-symbol js2-LET js2-ts-string param))))
8097 ;; pattern guard
8098 (if (js2-match-token js2-IF)
8099 (setq guard-kwd (- js2-token-beg catch-pos)
8100 catch-cond (js2-parse-expr))
8101 (setq saw-default-catch t))
8102 (if (js2-must-match js2-RP "msg.bad.catchcond")
8103 (setq rp (- js2-token-beg catch-pos)))
8104 (js2-must-match js2-LC "msg.no.brace.catchblock")
8105 (setq block (js2-parse-statements)
8106 try-end (js2-node-end block)
8107 catch-node (make-js2-catch-node :pos catch-pos
8108 :param param
8109 :guard-expr catch-cond
8110 :guard-kwd guard-kwd
8111 :block block
8112 :lp lp
8113 :rp rp))
8114 (js2-pop-scope)
8115 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8116 (setq try-end js2-token-beg))
8117 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8118 (js2-node-len catch-node) (- try-end catch-pos))
8119 (js2-node-add-children catch-node param catch-cond block)
8120 (push catch-node catch-blocks)))
8121 ((/= peek js2-FINALLY)
8122 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8123 (js2-node-pos try-block)
8124 (- (setq try-end (js2-node-end try-block))
8125 (js2-node-pos try-block)))))
8126 (when (js2-match-token js2-FINALLY)
8127 (setq finally-pos js2-token-beg
8128 block (js2-parse-statement)
8129 try-end (js2-node-end block)
8130 finally-block (make-js2-finally-node :pos finally-pos
8131 :len (- try-end finally-pos)
8132 :body block))
8133 (js2-node-add-children finally-block block))
8134 (setq pn (make-js2-try-node :pos try-pos
8135 :len (- try-end try-pos)
8136 :try-block try-block
8137 :finally-block finally-block))
8138 (js2-node-add-children pn try-block finally-block)
8139 ;; push them onto the try-node, which reverses and corrects their order
8140 (dolist (cb catch-blocks)
8141 (js2-node-add-children pn cb)
8142 (push cb (js2-try-node-catch-clauses pn)))
8143 pn))
8144
8145 (defun js2-parse-throw ()
8146 "Parser for throw-statement. Last matched token must be js2-THROW."
8147 (let ((pos js2-token-beg)
8148 expr
8149 pn)
8150 (js2-consume-token)
8151 (if (= (js2-peek-token-or-eol) js2-EOL)
8152 ;; ECMAScript does not allow new lines before throw expression,
8153 ;; see bug 256617
8154 (js2-report-error "msg.bad.throw.eol"))
8155 (setq expr (js2-parse-expr)
8156 pn (make-js2-throw-node :pos pos
8157 :len (- (js2-node-end expr) pos)
8158 :expr expr))
8159 (js2-node-add-children pn expr)
8160 pn))
8161
8162 (defsubst js2-match-jump-label-name (label-name)
8163 "If break/continue specified a label, return that label's labeled stmt.
8164 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8165 does not match an existing label, reports an error and returns nil."
8166 (let ((bundle (cdr (assoc label-name js2-label-set))))
8167 (if (null bundle)
8168 (js2-report-error "msg.undef.label"))
8169 bundle))
8170
8171 (defun js2-parse-break ()
8172 "Parser for break-statement. Last matched token must be js2-BREAK."
8173 (let ((pos js2-token-beg)
8174 (end js2-token-end)
8175 break-target ; statement to break from
8176 break-label ; in "break foo", name-node representing the foo
8177 labels ; matching labeled statement to break to
8178 pn)
8179 (js2-consume-token) ; `break'
8180 (when (eq (js2-peek-token-or-eol) js2-NAME)
8181 (js2-consume-token)
8182 (setq break-label (js2-create-name-node)
8183 end (js2-node-end break-label)
8184 ;; matchJumpLabelName only matches if there is one
8185 labels (js2-match-jump-label-name js2-ts-string)
8186 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8187 (unless (or break-target break-label)
8188 ;; no break target specified - try for innermost enclosing loop/switch
8189 (if (null js2-loop-and-switch-set)
8190 (unless break-label
8191 (js2-report-error "msg.bad.break" nil pos (length "break")))
8192 (setq break-target (car js2-loop-and-switch-set))))
8193 (setq pn (make-js2-break-node :pos pos
8194 :len (- end pos)
8195 :label break-label
8196 :target break-target))
8197 (js2-node-add-children pn break-label) ; but not break-target
8198 pn))
8199
8200 (defun js2-parse-continue ()
8201 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8202 (let ((pos js2-token-beg)
8203 (end js2-token-end)
8204 label ; optional user-specified label, a `js2-name-node'
8205 labels ; current matching labeled stmt, if any
8206 target ; the `js2-loop-node' target of this continue stmt
8207 pn)
8208 (js2-consume-token) ; `continue'
8209 (when (= (js2-peek-token-or-eol) js2-NAME)
8210 (js2-consume-token)
8211 (setq label (js2-create-name-node)
8212 end (js2-node-end label)
8213 ;; matchJumpLabelName only matches if there is one
8214 labels (js2-match-jump-label-name js2-ts-string)))
8215 (cond
8216 ((null labels) ; no current label to go to
8217 (if (null js2-loop-set) ; no loop to continue to
8218 (js2-report-error "msg.continue.outside" nil pos
8219 (length "continue"))
8220 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8221 (t
8222 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8223 (setq target (js2-labeled-stmt-node-stmt labels))
8224 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8225 (setq pn (make-js2-continue-node :pos pos
8226 :len (- end pos)
8227 :label label
8228 :target target))
8229 (js2-node-add-children pn label) ; but not target - it's not our child
8230 pn))
8231
8232 (defun js2-parse-with ()
8233 "Parser for with-statement. Last matched token must be js2-WITH."
8234 (js2-consume-token)
8235 (let ((pos js2-token-beg)
8236 obj body pn lp rp)
8237 (if (js2-must-match js2-LP "msg.no.paren.with")
8238 (setq lp js2-token-beg))
8239 (setq obj (js2-parse-expr))
8240 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8241 (setq rp js2-token-beg))
8242 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8243 (setq body (js2-parse-statement)))
8244 (setq pn (make-js2-with-node :pos pos
8245 :len (- (js2-node-end body) pos)
8246 :object obj
8247 :body body
8248 :lp (js2-relpos lp pos)
8249 :rp (js2-relpos rp pos)))
8250 (js2-node-add-children pn obj body)
8251 pn))
8252
8253 (defun js2-parse-const-var ()
8254 "Parser for var- or const-statement.
8255 Last matched token must be js2-CONST or js2-VAR."
8256 (let ((tt (js2-peek-token))
8257 (pos js2-token-beg)
8258 expr
8259 pn)
8260 (js2-consume-token)
8261 (setq expr (js2-parse-variables tt js2-token-beg)
8262 pn (make-js2-expr-stmt-node :pos pos
8263 :len (- (js2-node-end expr) pos)
8264 :expr expr))
8265 (js2-node-add-children pn expr)
8266 pn))
8267
8268 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8269 (let ((pn (make-js2-expr-stmt-node :pos pos
8270 :len (js2-node-len expr)
8271 :type (if (js2-inside-function)
8272 js2-EXPR_VOID
8273 js2-EXPR_RESULT)
8274 :expr expr)))
8275 (if add-child
8276 (js2-node-add-children pn expr))
8277 pn))
8278
8279 (defun js2-parse-let-stmt ()
8280 "Parser for let-statement. Last matched token must be js2-LET."
8281 (js2-consume-token)
8282 (let ((pos js2-token-beg)
8283 expr
8284 pn)
8285 (if (= (js2-peek-token) js2-LP)
8286 ;; let expression in statement context
8287 (setq expr (js2-parse-let pos 'statement)
8288 pn (js2-wrap-with-expr-stmt pos expr t))
8289 ;; else we're looking at a statement like let x=6, y=7;
8290 (setf expr (js2-parse-variables js2-LET pos)
8291 pn (js2-wrap-with-expr-stmt pos expr t)
8292 (js2-node-type pn) js2-EXPR_RESULT))
8293 pn))
8294
8295 (defun js2-parse-ret-yield ()
8296 (js2-parse-return-or-yield (js2-peek-token) nil))
8297
8298 (defconst js2-parse-return-stmt-enders
8299 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8300
8301 (defsubst js2-now-all-set (before after mask)
8302 "Return whether or not the bits in the mask have changed to all set.
8303 BEFORE is bits before change, AFTER is bits after change, and MASK is
8304 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8305 but not BEFORE."
8306 (and (/= (logand before mask) mask)
8307 (= (logand after mask) mask)))
8308
8309 (defun js2-parse-return-or-yield (tt expr-context)
8310 (let ((pos js2-token-beg)
8311 (end js2-token-end)
8312 (before js2-end-flags)
8313 (inside-function (js2-inside-function))
8314 e
8315 ret
8316 name)
8317 (unless inside-function
8318 (js2-report-error (if (eq tt js2-RETURN)
8319 "msg.bad.return"
8320 "msg.bad.yield")))
8321 (js2-consume-token)
8322 ;; This is ugly, but we don't want to require a semicolon.
8323 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8324 (setq e (js2-parse-expr)
8325 end (js2-node-end e)))
8326 (cond
8327 ((eq tt js2-RETURN)
8328 (js2-set-flag js2-end-flags (if (null e)
8329 js2-end-returns
8330 js2-end-returns-value))
8331 (setq ret (make-js2-return-node :pos pos
8332 :len (- end pos)
8333 :retval e))
8334 (js2-node-add-children ret e)
8335 ;; See if we need a strict mode warning.
8336 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8337 ;; more thorough and accurate than this before/after flag check.
8338 ;; E.g. if there's a finally-block that always returns, we shouldn't
8339 ;; show a warning generated by inconsistent returns in the catch blocks.
8340 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8341 ;; so we know which returns/yields to highlight, and we should get rid of
8342 ;; all the checking in `js2-parse-return-or-yield'.
8343 (if (and js2-strict-inconsistent-return-warning
8344 (js2-now-all-set before js2-end-flags
8345 (logior js2-end-returns js2-end-returns-value)))
8346 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8347 (t
8348 (unless (js2-inside-function)
8349 (js2-report-error "msg.bad.yield"))
8350 (js2-set-flag js2-end-flags js2-end-yields)
8351 (setq ret (make-js2-yield-node :pos pos
8352 :len (- end pos)
8353 :value e))
8354 (js2-node-add-children ret e)
8355 (unless expr-context
8356 (setq e ret
8357 ret (js2-wrap-with-expr-stmt pos e t))
8358 (js2-set-requires-activation)
8359 (js2-set-is-generator))))
8360 ;; see if we are mixing yields and value returns.
8361 (when (and inside-function
8362 (js2-now-all-set before js2-end-flags
8363 (logior js2-end-yields js2-end-returns-value)))
8364 (setq name (js2-function-name js2-current-script-or-fn))
8365 (if (zerop (length name))
8366 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8367 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8368 ret))
8369
8370 (defun js2-parse-debugger ()
8371 (js2-consume-token)
8372 (make-js2-keyword-node :type js2-DEBUGGER))
8373
8374 (defun js2-parse-block ()
8375 "Parser for a curly-delimited statement block.
8376 Last token matched must be js2-LC."
8377 (let ((pos js2-token-beg)
8378 (pn (make-js2-scope)))
8379 (js2-consume-token)
8380 (js2-push-scope pn)
8381 (unwind-protect
8382 (progn
8383 (js2-parse-statements pn)
8384 (js2-must-match js2-RC "msg.no.brace.block")
8385 (setf (js2-node-len pn) (- js2-token-end pos)))
8386 (js2-pop-scope))
8387 pn))
8388
8389 ;; for js2-ERROR too, to have a node for error recovery to work on
8390 (defun js2-parse-semi ()
8391 "Parse a statement or handle an error.
8392 Last matched token is js2-SEMI or js2-ERROR."
8393 (let ((tt (js2-peek-token)) pos len)
8394 (js2-consume-token)
8395 (if (eq tt js2-SEMI)
8396 (make-js2-empty-expr-node :len 1)
8397 (setq pos js2-token-beg
8398 len (- js2-token-beg pos))
8399 (js2-report-error "msg.syntax" nil pos len)
8400 (make-js2-error-node :pos pos :len len))))
8401
8402 (defun js2-parse-default-xml-namespace ()
8403 "Parse a `default xml namespace = <expr>' e4x statement."
8404 (let ((pos js2-token-beg)
8405 end len expr unary es)
8406 (js2-consume-token)
8407 (js2-must-have-xml)
8408 (js2-set-requires-activation)
8409 (setq len (- js2-ts-cursor pos))
8410 (unless (and (js2-match-token js2-NAME)
8411 (string= js2-ts-string "xml"))
8412 (js2-report-error "msg.bad.namespace" nil pos len))
8413 (unless (and (js2-match-token js2-NAME)
8414 (string= js2-ts-string "namespace"))
8415 (js2-report-error "msg.bad.namespace" nil pos len))
8416 (unless (js2-match-token js2-ASSIGN)
8417 (js2-report-error "msg.bad.namespace" nil pos len))
8418 (setq expr (js2-parse-expr)
8419 end (js2-node-end expr)
8420 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8421 :pos pos
8422 :len (- end pos)
8423 :operand expr))
8424 (js2-node-add-children unary expr)
8425 (make-js2-expr-stmt-node :pos pos
8426 :len (- end pos)
8427 :expr unary)))
8428
8429 (defun js2-record-label (label bundle)
8430 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8431 (js2-consume-token)
8432 (let ((name (js2-label-node-name label))
8433 labeled-stmt
8434 dup)
8435 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8436 ;; flag both labels if possible when used in editing mode
8437 (if (and js2-parse-ide-mode
8438 (setq dup (js2-get-label-by-name labeled-stmt name)))
8439 (js2-report-error "msg.dup.label" nil
8440 (js2-node-abs-pos dup) (js2-node-len dup)))
8441 (js2-report-error "msg.dup.label" nil
8442 (js2-node-pos label) (js2-node-len label)))
8443 (js2-labeled-stmt-node-add-label bundle label)
8444 (js2-node-add-children bundle label)
8445 ;; Add one reference to the bundle per label in `js2-label-set'
8446 (push (cons name bundle) js2-label-set)))
8447
8448 (defun js2-parse-name-or-label ()
8449 "Parser for identifier or label. Last token matched must be js2-NAME.
8450 Called when we found a name in a statement context. If it's a label, we gather
8451 up any following labels and the next non-label statement into a
8452 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8453 expression and return it wrapped in a `js2-expr-stmt-node'."
8454 (let ((pos js2-token-beg)
8455 (end js2-token-end)
8456 expr
8457 stmt
8458 pn
8459 bundle
8460 (continue t))
8461 ;; set check for label and call down to `js2-parse-primary-expr'
8462 (js2-set-check-for-label)
8463 (setq expr (js2-parse-expr))
8464 (if (/= (js2-node-type expr) js2-LABEL)
8465 ;; Parsed non-label expression - wrap with expression stmt.
8466 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8467 ;; else parsed a label
8468 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8469 (js2-record-label expr bundle)
8470 ;; look for more labels
8471 (while (and continue (= (js2-peek-token) js2-NAME))
8472 (js2-set-check-for-label)
8473 (setq expr (js2-parse-expr))
8474 (if (/= (js2-node-type expr) js2-LABEL)
8475 (progn
8476 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8477 continue nil)
8478 (js2-auto-insert-semicolon stmt))
8479 (js2-record-label expr bundle)))
8480 ;; no more labels; now parse the labeled statement
8481 (unwind-protect
8482 (unless stmt
8483 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8484 (setq stmt (js2-statement-helper))))
8485 ;; remove the labels for this statement from the global set
8486 (dolist (label (js2-labeled-stmt-node-labels bundle))
8487 (setq js2-label-set (remove label js2-label-set))))
8488 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8489 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8490 (js2-node-add-children bundle stmt)
8491 bundle)))
8492
8493 (defun js2-parse-expr-stmt ()
8494 "Default parser in statement context, if no recognized statement found."
8495 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8496
8497 (defun js2-parse-variables (decl-type pos)
8498 "Parse a comma-separated list of variable declarations.
8499 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8500
8501 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8502 For 'var' or 'const', the keyword should be the token last scanned.
8503
8504 POS is the position where the node should start. It's sometimes the
8505 var/const/let keyword, and other times the beginning of the first token
8506 in the first variable declaration.
8507
8508 Returns the parsed `js2-var-decl-node' expression node."
8509 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8510 :pos pos))
8511 destructuring
8512 kid-pos
8513 tt
8514 init
8515 name
8516 end
8517 nbeg nend
8518 vi
8519 (continue t))
8520 ;; Example:
8521 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8522 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8523 ;; var {a, b} = baz;
8524 (while continue
8525 (setq destructuring nil
8526 name nil
8527 tt (js2-peek-token)
8528 kid-pos js2-token-beg
8529 end js2-token-end
8530 init nil)
8531 (if (or (= tt js2-LB) (= tt js2-LC))
8532 ;; Destructuring assignment, e.g., var [a, b] = ...
8533 (setq destructuring (js2-parse-destruct-primary-expr)
8534 end (js2-node-end destructuring))
8535 ;; Simple variable name
8536 (when (js2-must-match js2-NAME "msg.bad.var")
8537 (setq name (js2-create-name-node)
8538 nbeg js2-token-beg
8539 nend js2-token-end
8540 end nend)
8541 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8542 (when (js2-match-token js2-ASSIGN)
8543 (setq init (js2-parse-assign-expr)
8544 end (js2-node-end init))
8545 (js2-record-imenu-functions init name))
8546 (when name
8547 (js2-set-face nbeg nend (if (js2-function-node-p init)
8548 'font-lock-function-name-face
8549 'font-lock-variable-name-face)
8550 'record))
8551 (setq vi (make-js2-var-init-node :pos kid-pos
8552 :len (- end kid-pos)
8553 :type decl-type))
8554 (if destructuring
8555 (progn
8556 (if (and (null init) (not js2-in-for-init))
8557 (js2-report-error "msg.destruct.assign.no.init"))
8558 (js2-define-destruct-symbols destructuring
8559 decl-type
8560 'font-lock-variable-name-face)
8561 (setf (js2-var-init-node-target vi) destructuring))
8562 (setf (js2-var-init-node-target vi) name))
8563 (setf (js2-var-init-node-initializer vi) init)
8564 (js2-node-add-children vi name destructuring init)
8565 (js2-block-node-push result vi)
8566 (unless (js2-match-token js2-COMMA)
8567 (setq continue nil)))
8568 (setf (js2-node-len result) (- end pos))
8569 result))
8570
8571 (defun js2-parse-let (pos &optional stmt-p)
8572 "Parse a let expression or statement.
8573 A let-expression is of the form `let (vars) expr'.
8574 A let-statment is of the form `let (vars) {statements}'.
8575 The third form of let is a variable declaration list, handled
8576 by `js2-parse-variables'."
8577 (let ((pn (make-js2-let-node :pos pos))
8578 beg vars body)
8579 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8580 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8581 (js2-push-scope pn)
8582 (unwind-protect
8583 (progn
8584 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8585 (if (js2-must-match js2-RP "msg.no.paren.let")
8586 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8587 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8588 ;; let statement
8589 (progn
8590 (js2-consume-token)
8591 (setf beg js2-token-beg ; position stmt at LC
8592 body (js2-parse-statements))
8593 (js2-must-match js2-RC "msg.no.curly.let")
8594 (setf (js2-node-len body) (- js2-token-end beg)
8595 (js2-node-len pn) (- js2-token-end pos)
8596 (js2-let-node-body pn) body
8597 (js2-node-type pn) js2-LET))
8598 ;; let expression
8599 (setf body (js2-parse-expr)
8600 (js2-node-len pn) (- (js2-node-end body) pos)
8601 (js2-let-node-body pn) body))
8602 (js2-node-add-children pn vars body))
8603 (js2-pop-scope))
8604 pn))
8605
8606 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8607 (js2-scope-put-symbol (or scope js2-current-scope)
8608 name
8609 (make-js2-symbol decl-type name node)))
8610
8611 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8612 "Define a symbol in the current scope.
8613 If NODE is non-nil, it is the AST node associated with the symbol."
8614 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8615 (symbol (if defining-scope
8616 (js2-scope-get-symbol defining-scope name)))
8617 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8618 (cond
8619 ((and symbol ; already defined
8620 (or (= sdt js2-CONST) ; old version is const
8621 (= decl-type js2-CONST) ; new version is const
8622 ;; two let-bound vars in this block have same name
8623 (and (= sdt js2-LET)
8624 (eq defining-scope js2-current-scope))))
8625 (js2-report-error
8626 (cond
8627 ((= sdt js2-CONST) "msg.const.redecl")
8628 ((= sdt js2-LET) "msg.let.redecl")
8629 ((= sdt js2-VAR) "msg.var.redecl")
8630 ((= sdt js2-FUNCTION) "msg.function.redecl")
8631 (t "msg.parm.redecl"))
8632 name))
8633 ((= decl-type js2-LET)
8634 (if (and (not ignore-not-in-block)
8635 (or (= (js2-node-type js2-current-scope) js2-IF)
8636 (js2-loop-node-p js2-current-scope)))
8637 (js2-report-error "msg.let.decl.not.in.block")
8638 (js2-define-new-symbol decl-type name node)))
8639 ((or (= decl-type js2-VAR)
8640 (= decl-type js2-CONST)
8641 (= decl-type js2-FUNCTION))
8642 (if symbol
8643 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8644 (js2-add-strict-warning "msg.var.redecl" name)
8645 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8646 (js2-add-strict-warning "msg.var.hides.arg" name)))
8647 (js2-define-new-symbol decl-type name node
8648 js2-current-script-or-fn)))
8649 ((= decl-type js2-LP)
8650 (if symbol
8651 ;; must be duplicate parameter. Second parameter hides the
8652 ;; first, so go ahead and add the second pararameter
8653 (js2-report-warning "msg.dup.parms" name))
8654 (js2-define-new-symbol decl-type name node))
8655 (t (js2-code-bug)))))
8656
8657 (defun js2-parse-expr (&optional oneshot)
8658 (let* ((pn (js2-parse-assign-expr))
8659 (pos (js2-node-pos pn))
8660 left
8661 right
8662 op-pos)
8663 (while (and (not oneshot)
8664 (js2-match-token js2-COMMA))
8665 (setq op-pos (- js2-token-beg pos)) ; relative
8666 (if (= (js2-peek-token) js2-YIELD)
8667 (js2-report-error "msg.yield.parenthesized"))
8668 (setq right (js2-parse-assign-expr)
8669 left pn
8670 pn (make-js2-infix-node :type js2-COMMA
8671 :pos pos
8672 :len (- js2-ts-cursor pos)
8673 :op-pos op-pos
8674 :left left
8675 :right right))
8676 (js2-node-add-children pn left right))
8677 pn))
8678
8679 (defun js2-parse-assign-expr ()
8680 (let ((tt (js2-peek-token))
8681 (pos js2-token-beg)
8682 pn
8683 left
8684 right
8685 op-pos)
8686 (if (= tt js2-YIELD)
8687 (js2-parse-return-or-yield tt t)
8688 ;; not yield - parse assignment expression
8689 (setq pn (js2-parse-cond-expr)
8690 tt (js2-peek-token))
8691 (when (and (<= js2-first-assign tt)
8692 (<= tt js2-last-assign))
8693 ;; tt express assignment (=, |=, ^=, ..., %=)
8694 (js2-consume-token)
8695 (setq op-pos (- js2-token-beg pos) ; relative
8696 left pn
8697 right (js2-parse-assign-expr)
8698 pn (make-js2-assign-node :type tt
8699 :pos pos
8700 :len (- (js2-node-end right) pos)
8701 :op-pos op-pos
8702 :left left
8703 :right right))
8704 (when js2-parse-ide-mode
8705 (js2-highlight-assign-targets pn left right)
8706 (js2-record-imenu-functions right left))
8707 ;; do this last so ide checks above can use absolute positions
8708 (js2-node-add-children pn left right))
8709 pn)))
8710
8711 (defun js2-parse-cond-expr ()
8712 (let ((pos js2-token-beg)
8713 (pn (js2-parse-or-expr))
8714 test-expr
8715 if-true
8716 if-false
8717 q-pos
8718 c-pos)
8719 (when (js2-match-token js2-HOOK)
8720 (setq q-pos (- js2-token-beg pos)
8721 if-true (js2-parse-assign-expr))
8722 (js2-must-match js2-COLON "msg.no.colon.cond")
8723 (setq c-pos (- js2-token-beg pos)
8724 if-false (js2-parse-assign-expr)
8725 test-expr pn
8726 pn (make-js2-cond-node :pos pos
8727 :len (- (js2-node-end if-false) pos)
8728 :test-expr test-expr
8729 :true-expr if-true
8730 :false-expr if-false
8731 :q-pos q-pos
8732 :c-pos c-pos))
8733 (js2-node-add-children pn test-expr if-true if-false))
8734 pn))
8735
8736 (defun js2-make-binary (type left parser)
8737 "Helper for constructing a binary-operator AST node.
8738 LEFT is the left-side-expression, already parsed, and the
8739 binary operator should have just been matched.
8740 PARSER is a function to call to parse the right operand,
8741 or a `js2-node' struct if it has already been parsed."
8742 (let* ((pos (js2-node-pos left))
8743 (op-pos (- js2-token-beg pos))
8744 (right (if (js2-node-p parser)
8745 parser
8746 (funcall parser)))
8747 (pn (make-js2-infix-node :type type
8748 :pos pos
8749 :len (- (js2-node-end right) pos)
8750 :op-pos op-pos
8751 :left left
8752 :right right)))
8753 (js2-node-add-children pn left right)
8754 pn))
8755
8756 (defun js2-parse-or-expr ()
8757 (let ((pn (js2-parse-and-expr)))
8758 (when (js2-match-token js2-OR)
8759 (setq pn (js2-make-binary js2-OR
8760 pn
8761 'js2-parse-or-expr)))
8762 pn))
8763
8764 (defun js2-parse-and-expr ()
8765 (let ((pn (js2-parse-bit-or-expr)))
8766 (when (js2-match-token js2-AND)
8767 (setq pn (js2-make-binary js2-AND
8768 pn
8769 'js2-parse-and-expr)))
8770 pn))
8771
8772 (defun js2-parse-bit-or-expr ()
8773 (let ((pn (js2-parse-bit-xor-expr)))
8774 (while (js2-match-token js2-BITOR)
8775 (setq pn (js2-make-binary js2-BITOR
8776 pn
8777 'js2-parse-bit-xor-expr)))
8778 pn))
8779
8780 (defun js2-parse-bit-xor-expr ()
8781 (let ((pn (js2-parse-bit-and-expr)))
8782 (while (js2-match-token js2-BITXOR)
8783 (setq pn (js2-make-binary js2-BITXOR
8784 pn
8785 'js2-parse-bit-and-expr)))
8786 pn))
8787
8788 (defun js2-parse-bit-and-expr ()
8789 (let ((pn (js2-parse-eq-expr)))
8790 (while (js2-match-token js2-BITAND)
8791 (setq pn (js2-make-binary js2-BITAND
8792 pn
8793 'js2-parse-eq-expr)))
8794 pn))
8795
8796 (defconst js2-parse-eq-ops
8797 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8798
8799 (defun js2-parse-eq-expr ()
8800 (let ((pn (js2-parse-rel-expr))
8801 tt)
8802 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8803 (js2-consume-token)
8804 (setq pn (js2-make-binary tt
8805 pn
8806 'js2-parse-rel-expr)))
8807 pn))
8808
8809 (defconst js2-parse-rel-ops
8810 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8811
8812 (defun js2-parse-rel-expr ()
8813 (let ((pn (js2-parse-shift-expr))
8814 (continue t)
8815 tt)
8816 (while continue
8817 (setq tt (js2-peek-token))
8818 (cond
8819 ((and js2-in-for-init (= tt js2-IN))
8820 (setq continue nil))
8821 ((memq tt js2-parse-rel-ops)
8822 (js2-consume-token)
8823 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8824 (t
8825 (setq continue nil))))
8826 pn))
8827
8828 (defconst js2-parse-shift-ops
8829 (list js2-LSH js2-URSH js2-RSH))
8830
8831 (defun js2-parse-shift-expr ()
8832 (let ((pn (js2-parse-add-expr))
8833 tt
8834 (continue t))
8835 (while continue
8836 (setq tt (js2-peek-token))
8837 (if (memq tt js2-parse-shift-ops)
8838 (progn
8839 (js2-consume-token)
8840 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8841 (setq continue nil)))
8842 pn))
8843
8844 (defun js2-parse-add-expr ()
8845 (let ((pn (js2-parse-mul-expr))
8846 tt
8847 (continue t))
8848 (while continue
8849 (setq tt (js2-peek-token))
8850 (if (or (= tt js2-ADD) (= tt js2-SUB))
8851 (progn
8852 (js2-consume-token)
8853 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8854 (setq continue nil)))
8855 pn))
8856
8857 (defconst js2-parse-mul-ops
8858 (list js2-MUL js2-DIV js2-MOD))
8859
8860 (defun js2-parse-mul-expr ()
8861 (let ((pn (js2-parse-unary-expr))
8862 tt
8863 (continue t))
8864 (while continue
8865 (setq tt (js2-peek-token))
8866 (if (memq tt js2-parse-mul-ops)
8867 (progn
8868 (js2-consume-token)
8869 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8870 (setq continue nil)))
8871 pn))
8872
8873 (defsubst js2-make-unary (type parser &rest args)
8874 "Make a unary node of type TYPE.
8875 PARSER is either a node (for postfix operators) or a function to call
8876 to parse the operand (for prefix operators)."
8877 (let* ((pos js2-token-beg)
8878 (postfix (js2-node-p parser))
8879 (expr (if postfix
8880 parser
8881 (apply parser args)))
8882 end
8883 pn)
8884 (if postfix ; e.g. i++
8885 (setq pos (js2-node-pos expr)
8886 end js2-token-end)
8887 (setq end (js2-node-end expr)))
8888 (setq pn (make-js2-unary-node :type type
8889 :pos pos
8890 :len (- end pos)
8891 :operand expr))
8892 (js2-node-add-children pn expr)
8893 pn))
8894
8895 (defconst js2-incrementable-node-types
8896 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8897 "Node types that can be the operand of a ++ or -- operator.")
8898
8899 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8900 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8901 js2-incrementable-node-types)
8902 (js2-report-error (if (= tt js2-INC)
8903 "msg.bad.incr"
8904 "msg.bad.decr")
8905 nil beg (- end beg))))
8906
8907 (defun js2-parse-unary-expr ()
8908 (let ((tt (js2-peek-token))
8909 pn expr beg end)
8910 (cond
8911 ((or (= tt js2-VOID)
8912 (= tt js2-NOT)
8913 (= tt js2-BITNOT)
8914 (= tt js2-TYPEOF))
8915 (js2-consume-token)
8916 (js2-make-unary tt 'js2-parse-unary-expr))
8917 ((= tt js2-ADD)
8918 (js2-consume-token)
8919 ;; Convert to special POS token in decompiler and parse tree
8920 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8921 ((= tt js2-SUB)
8922 (js2-consume-token)
8923 ;; Convert to special NEG token in decompiler and parse tree
8924 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8925 ((or (= tt js2-INC)
8926 (= tt js2-DEC))
8927 (js2-consume-token)
8928 (prog1
8929 (setq beg js2-token-beg
8930 end js2-token-end
8931 expr (js2-make-unary tt 'js2-parse-member-expr t))
8932 (js2-check-bad-inc-dec tt beg end expr)))
8933 ((= tt js2-DELPROP)
8934 (js2-consume-token)
8935 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8936 ((= tt js2-ERROR)
8937 (js2-consume-token)
8938 (make-js2-error-node)) ; try to continue
8939 ((and (= tt js2-LT)
8940 js2-compiler-xml-available)
8941 ;; XML stream encountered in expression.
8942 (js2-consume-token)
8943 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8944 (t
8945 (setq pn (js2-parse-member-expr t)
8946 ;; Don't look across a newline boundary for a postfix incop.
8947 tt (js2-peek-token-or-eol))
8948 (when (or (= tt js2-INC) (= tt js2-DEC))
8949 (js2-consume-token)
8950 (setf expr pn
8951 pn (js2-make-unary tt expr))
8952 (js2-node-set-prop pn 'postfix t)
8953 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8954 pn))))
8955
8956 (defun js2-parse-xml-initializer ()
8957 "Parse an E4X XML initializer.
8958 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8959 Then I'll postprocess the result, depending on whether we're in IDE
8960 mode or codegen mode, and generate the appropriate rewritten AST.
8961 IDE mode uses a rich AST that models the XML structure. Codegen mode
8962 just concatenates everything and makes a new XML or XMLList out of it."
8963 (let ((tt (js2-get-first-xml-token))
8964 pn-xml
8965 pn
8966 expr
8967 kids
8968 expr-pos
8969 (continue t)
8970 (first-token t))
8971 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8972 (js2-report-error "msg.syntax"))
8973 (setq pn-xml (make-js2-xml-node))
8974 (while continue
8975 (if first-token
8976 (setq first-token nil)
8977 (setq tt (js2-get-next-xml-token)))
8978 (cond
8979 ;; js2-XML means we found a {expr} in the XML stream.
8980 ;; The js2-ts-string is the XML up to the left-curly.
8981 ((= tt js2-XML)
8982 (push (make-js2-string-node :pos js2-token-beg
8983 :len (- js2-ts-cursor js2-token-beg))
8984 kids)
8985 (js2-must-match js2-LC "msg.syntax")
8986 (setq expr-pos js2-ts-cursor
8987 expr (if (eq (js2-peek-token) js2-RC)
8988 (make-js2-empty-expr-node :pos expr-pos)
8989 (js2-parse-expr)))
8990 (js2-must-match js2-RC "msg.syntax")
8991 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8992 :len (js2-node-len expr)
8993 :expr expr))
8994 (js2-node-add-children pn expr)
8995 (push pn kids))
8996 ;; a js2-XMLEND token means we hit the final close-tag.
8997 ((= tt js2-XMLEND)
8998 (push (make-js2-string-node :pos js2-token-beg
8999 :len (- js2-ts-cursor js2-token-beg))
9000 kids)
9001 (dolist (kid (nreverse kids))
9002 (js2-block-node-push pn-xml kid))
9003 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9004 (js2-node-pos pn-xml))
9005 continue nil))
9006 (t
9007 (js2-report-error "msg.syntax")
9008 (setq continue nil))))
9009 pn-xml))
9010
9011
9012 (defun js2-parse-argument-list ()
9013 "Parse an argument list and return it as a lisp list of nodes.
9014 Returns the list in reverse order. Consumes the right-paren token."
9015 (let (result)
9016 (unless (js2-match-token js2-RP)
9017 (loop do
9018 (if (= (js2-peek-token) js2-YIELD)
9019 (js2-report-error "msg.yield.parenthesized"))
9020 (push (js2-parse-assign-expr) result)
9021 while
9022 (js2-match-token js2-COMMA))
9023 (js2-must-match js2-RP "msg.no.paren.arg")
9024 result)))
9025
9026 (defun js2-parse-member-expr (&optional allow-call-syntax)
9027 (let ((tt (js2-peek-token))
9028 pn
9029 pos
9030 target
9031 args
9032 beg
9033 end
9034 init
9035 tail)
9036 (if (/= tt js2-NEW)
9037 (setq pn (js2-parse-primary-expr))
9038 ;; parse a 'new' expression
9039 (js2-consume-token)
9040 (setq pos js2-token-beg
9041 beg pos
9042 target (js2-parse-member-expr)
9043 end (js2-node-end target)
9044 pn (make-js2-new-node :pos pos
9045 :target target
9046 :len (- end pos)))
9047 (js2-node-add-children pn target)
9048 (when (js2-match-token js2-LP)
9049 ;; Add the arguments to pn, if any are supplied.
9050 (setf beg pos ; start of "new" keyword
9051 pos js2-token-beg
9052 args (nreverse (js2-parse-argument-list))
9053 (js2-new-node-args pn) args
9054 end js2-token-end
9055 (js2-new-node-lp pn) (- pos beg)
9056 (js2-new-node-rp pn) (- end 1 beg))
9057 (apply #'js2-node-add-children pn args))
9058 (when (and js2-allow-rhino-new-expr-initializer
9059 (js2-match-token js2-LC))
9060 (setf init (js2-parse-object-literal)
9061 end (js2-node-end init)
9062 (js2-new-node-initializer pn) init)
9063 (js2-node-add-children pn init))
9064 (setf (js2-node-len pn) (- end beg))) ; end outer if
9065 (js2-parse-member-expr-tail allow-call-syntax pn)))
9066
9067 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9068 "Parse a chain of property/array accesses or function calls.
9069 Includes parsing for E4X operators like `..' and `.@'.
9070 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9071 Returns an expression tree that includes PN, the parent node."
9072 (let ((beg (js2-node-pos pn))
9073 tt
9074 (continue t))
9075 (while continue
9076 (setq tt (js2-peek-token))
9077 (cond
9078 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9079 (setq pn (js2-parse-property-access tt pn)))
9080 ((= tt js2-DOTQUERY)
9081 (setq pn (js2-parse-dot-query pn)))
9082 ((= tt js2-LB)
9083 (setq pn (js2-parse-element-get pn)))
9084 ((= tt js2-LP)
9085 (if allow-call-syntax
9086 (setq pn (js2-parse-function-call pn))
9087 (setq continue nil)))
9088 (t
9089 (setq continue nil))))
9090 (if (>= js2-highlight-level 2)
9091 (js2-parse-highlight-member-expr-node pn))
9092 pn))
9093
9094 (defun js2-parse-dot-query (pn)
9095 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9096 Last token parsed must be `js2-DOTQUERY'."
9097 (let ((pos (js2-node-pos pn))
9098 op-pos
9099 expr
9100 end)
9101 (js2-consume-token)
9102 (js2-must-have-xml)
9103 (js2-set-requires-activation)
9104 (setq op-pos js2-token-beg
9105 expr (js2-parse-expr)
9106 end (js2-node-end expr)
9107 pn (make-js2-xml-dot-query-node :left pn
9108 :pos pos
9109 :op-pos op-pos
9110 :right expr))
9111 (js2-node-add-children pn
9112 (js2-xml-dot-query-node-left pn)
9113 (js2-xml-dot-query-node-right pn))
9114 (if (js2-must-match js2-RP "msg.no.paren")
9115 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9116 end js2-token-end))
9117 (setf (js2-node-len pn) (- end pos))
9118 pn))
9119
9120 (defun js2-parse-element-get (pn)
9121 "Parse an element-get expression, e.g. foo[bar].
9122 Last token parsed must be `js2-RB'."
9123 (let ((lb js2-token-beg)
9124 (pos (js2-node-pos pn))
9125 rb
9126 expr)
9127 (js2-consume-token)
9128 (setq expr (js2-parse-expr))
9129 (if (js2-must-match js2-RB "msg.no.bracket.index")
9130 (setq rb js2-token-beg))
9131 (setq pn (make-js2-elem-get-node :target pn
9132 :pos pos
9133 :element expr
9134 :lb (js2-relpos lb pos)
9135 :rb (js2-relpos rb pos)
9136 :len (- js2-token-end pos)))
9137 (js2-node-add-children pn
9138 (js2-elem-get-node-target pn)
9139 (js2-elem-get-node-element pn))
9140 pn))
9141
9142 (defun js2-parse-function-call (pn)
9143 (let (args
9144 (pos (js2-node-pos pn)))
9145 (js2-consume-token)
9146 (setq pn (make-js2-call-node :pos pos
9147 :target pn
9148 :lp (- js2-token-beg pos)))
9149 (js2-node-add-children pn (js2-call-node-target pn))
9150 ;; Add the arguments to pn, if any are supplied.
9151 (setf args (nreverse (js2-parse-argument-list))
9152 (js2-call-node-rp pn) (- js2-token-beg pos)
9153 (js2-call-node-args pn) args)
9154 (apply #'js2-node-add-children pn args)
9155 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9156 pn))
9157
9158 (defun js2-parse-property-access (tt pn)
9159 "Parse a property access, XML descendants access, or XML attr access."
9160 (let ((member-type-flags 0)
9161 (dot-pos js2-token-beg)
9162 (dot-len (if (= tt js2-DOTDOT) 2 1))
9163 name
9164 ref ; right side of . or .. operator
9165 result)
9166 (js2-consume-token)
9167 (when (= tt js2-DOTDOT)
9168 (js2-must-have-xml)
9169 (setq member-type-flags js2-descendants-flag))
9170 (if (not js2-compiler-xml-available)
9171 (progn
9172 (js2-must-match-prop-name "msg.no.name.after.dot")
9173 (setq name (js2-create-name-node t js2-GETPROP)
9174 result (make-js2-prop-get-node :left pn
9175 :pos js2-token-beg
9176 :right name
9177 :len (- js2-token-end
9178 js2-token-beg)))
9179 (js2-node-add-children result pn name)
9180 result)
9181 ;; otherwise look for XML operators
9182 (setf result (if (= tt js2-DOT)
9183 (make-js2-prop-get-node)
9184 (make-js2-infix-node :type js2-DOTDOT))
9185 (js2-node-pos result) (js2-node-pos pn)
9186 (js2-infix-node-op-pos result) dot-pos
9187 (js2-infix-node-left result) pn ; do this after setting position
9188 tt (js2-next-token))
9189 (cond
9190 ;; needed for generator.throw()
9191 ((= tt js2-THROW)
9192 (js2-save-name-token-data js2-token-beg "throw")
9193 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9194 ;; handles: name, ns::name, ns::*, ns::[expr]
9195 ((js2-valid-prop-name-token tt)
9196 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9197 ;; handles: *, *::name, *::*, *::[expr]
9198 ((= tt js2-MUL)
9199 (js2-save-name-token-data js2-token-beg "*")
9200 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9201 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9202 ((= tt js2-XMLATTR)
9203 (setq result (js2-parse-attribute-access)))
9204 (t
9205 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9206 (if ref
9207 (setf (js2-node-len result) (- (js2-node-end ref)
9208 (js2-node-pos result))
9209 (js2-infix-node-right result) ref))
9210 (if (js2-infix-node-p result)
9211 (js2-node-add-children result
9212 (js2-infix-node-left result)
9213 (js2-infix-node-right result)))
9214 result)))
9215
9216 (defun js2-parse-attribute-access ()
9217 "Parse an E4X XML attribute expression.
9218 This includes expressions of the forms:
9219
9220 @attr @ns::attr @ns::*
9221 @* @*::attr @*::*
9222 @[expr] @*::[expr] @ns::[expr]
9223
9224 Called if we peeked an '@' token."
9225 (let ((tt (js2-next-token))
9226 (at-pos js2-token-beg))
9227 (cond
9228 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9229 ((js2-valid-prop-name-token tt)
9230 (js2-parse-property-name at-pos js2-ts-string 0))
9231 ;; handles: @*, @*::name, @*::*, @*::[expr]
9232 ((= tt js2-MUL)
9233 (js2-save-name-token-data js2-token-beg "*")
9234 (js2-parse-property-name js2-token-beg "*" 0))
9235 ;; handles @[expr]
9236 ((= tt js2-LB)
9237 (js2-parse-xml-elem-ref at-pos))
9238 (t
9239 (js2-report-error "msg.no.name.after.xmlAttr")
9240 ;; Avoid cascaded errors that happen if we make an error node here.
9241 (js2-save-name-token-data js2-token-beg "")
9242 (js2-parse-property-name js2-token-beg "" 0)))))
9243
9244 (defun js2-parse-property-name (at-pos s member-type-flags)
9245 "Check if :: follows name in which case it becomes qualified name.
9246
9247 AT-POS is a natural number if we just read an '@' token, else nil.
9248 S is the name or string that was matched: an identifier, 'throw' or '*'.
9249 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9250
9251 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9252 operator, or the name is followed by ::. For a plain name, returns a
9253 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9254 (let ((pos (or at-pos js2-token-beg))
9255 colon-pos
9256 (name (js2-create-name-node t js2-current-token))
9257 ns
9258 tt
9259 ref
9260 pn)
9261 (catch 'return
9262 (when (js2-match-token js2-COLONCOLON)
9263 (setq ns name
9264 colon-pos js2-token-beg
9265 tt (js2-next-token))
9266 (cond
9267 ;; handles name::name
9268 ((js2-valid-prop-name-token tt)
9269 (setq name (js2-create-name-node)))
9270 ;; handles name::*
9271 ((= tt js2-MUL)
9272 (js2-save-name-token-data js2-token-beg "*")
9273 (setq name (js2-create-name-node)))
9274 ;; handles name::[expr]
9275 ((= tt js2-LB)
9276 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9277 (t
9278 (js2-report-error "msg.no.name.after.coloncolon"))))
9279 (if (and (null ns) (zerop member-type-flags))
9280 name
9281 (prog1
9282 (setq pn
9283 (make-js2-xml-prop-ref-node :pos pos
9284 :len (- (js2-node-end name) pos)
9285 :at-pos at-pos
9286 :colon-pos colon-pos
9287 :propname name))
9288 (js2-node-add-children pn name))))))
9289
9290 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9291 "Parse the [expr] portion of an xml element reference.
9292 For instance, @[expr], @*::[expr], or ns::[expr]."
9293 (let* ((lb js2-token-beg)
9294 (pos (or at-pos lb))
9295 rb
9296 (expr (js2-parse-expr))
9297 (end (js2-node-end expr))
9298 pn)
9299 (if (js2-must-match js2-RB "msg.no.bracket.index")
9300 (setq rb js2-token-beg
9301 end js2-token-end))
9302 (prog1
9303 (setq pn
9304 (make-js2-xml-elem-ref-node :pos pos
9305 :len (- end pos)
9306 :namespace namespace
9307 :colon-pos colon-pos
9308 :at-pos at-pos
9309 :expr expr
9310 :lb (js2-relpos lb pos)
9311 :rb (js2-relpos rb pos)))
9312 (js2-node-add-children pn namespace expr))))
9313
9314 (defun js2-parse-destruct-primary-expr ()
9315 (let ((js2-is-in-destructuring t))
9316 (js2-parse-primary-expr)))
9317
9318 (defun js2-parse-primary-expr ()
9319 "Parses a literal (leaf) expression of some sort.
9320 Includes complex literals such as functions, object-literals,
9321 array-literals, array comprehensions and regular expressions."
9322 (let ((tt-flagged (js2-next-flagged-token))
9323 pn ; parent node (usually return value)
9324 tt
9325 px-pos ; paren-expr pos
9326 len
9327 flags ; regexp flags
9328 expr)
9329 (setq tt js2-current-token)
9330 (cond
9331 ((= tt js2-FUNCTION)
9332 (js2-parse-function 'FUNCTION_EXPRESSION))
9333 ((= tt js2-LB)
9334 (js2-parse-array-literal))
9335 ((= tt js2-LC)
9336 (js2-parse-object-literal))
9337 ((= tt js2-LET)
9338 (js2-parse-let js2-token-beg))
9339 ((= tt js2-LP)
9340 (setq px-pos js2-token-beg
9341 expr (js2-parse-expr))
9342 (js2-must-match js2-RP "msg.no.paren")
9343 (setq pn (make-js2-paren-node :pos px-pos
9344 :expr expr
9345 :len (- js2-token-end px-pos)))
9346 (js2-node-add-children pn (js2-paren-node-expr pn))
9347 pn)
9348 ((= tt js2-XMLATTR)
9349 (js2-must-have-xml)
9350 (js2-parse-attribute-access))
9351 ((= tt js2-NAME)
9352 (js2-parse-name tt-flagged tt))
9353 ((= tt js2-NUMBER)
9354 (make-js2-number-node))
9355 ((= tt js2-STRING)
9356 (prog1
9357 (make-js2-string-node)
9358 (js2-record-face 'font-lock-string-face)))
9359 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9360 ;; Got / or /= which in this context means a regexp literal
9361 (setq px-pos js2-token-beg)
9362 (js2-read-regexp tt)
9363 (setq flags js2-ts-regexp-flags
9364 js2-ts-regexp-flags nil)
9365 (prog1
9366 (make-js2-regexp-node :pos px-pos
9367 :len (- js2-ts-cursor px-pos)
9368 :value js2-ts-string
9369 :flags flags)
9370 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9371 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9372 ((or (= tt js2-NULL)
9373 (= tt js2-THIS)
9374 (= tt js2-FALSE)
9375 (= tt js2-TRUE))
9376 (make-js2-keyword-node :type tt))
9377 ((= tt js2-RESERVED)
9378 (js2-report-error "msg.reserved.id")
9379 (make-js2-name-node))
9380 ((= tt js2-ERROR)
9381 ;; the scanner or one of its subroutines reported the error.
9382 (make-js2-error-node))
9383 ((= tt js2-EOF)
9384 (setq px-pos (point-at-bol)
9385 len (- js2-ts-cursor px-pos))
9386 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9387 (make-js2-error-node :pos px-pos :len len))
9388 (t
9389 (js2-report-error "msg.syntax")
9390 (make-js2-error-node)))))
9391
9392 (defun js2-parse-name (tt-flagged tt)
9393 (let ((name js2-ts-string)
9394 (name-pos js2-token-beg)
9395 node)
9396 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9397 (= (js2-peek-token) js2-COLON))
9398 (prog1
9399 ;; Do not consume colon, it is used as unwind indicator
9400 ;; to return to statementHelper.
9401 (make-js2-label-node :pos name-pos
9402 :len (- js2-token-end name-pos)
9403 :name name)
9404 (js2-set-face name-pos
9405 js2-token-end
9406 'font-lock-variable-name-face 'record))
9407 ;; Otherwise not a label, just a name. Unfortunately peeking
9408 ;; the next token to check for a colon has biffed js2-token-beg
9409 ;; and js2-token-end. We store the name's bounds in buffer vars
9410 ;; and `js2-create-name-node' uses them.
9411 (js2-save-name-token-data name-pos name)
9412 (setq node (if js2-compiler-xml-available
9413 (js2-parse-property-name nil name 0)
9414 (js2-create-name-node 'check-activation)))
9415 (if js2-highlight-external-variables
9416 (js2-record-name-node node))
9417 node)))
9418
9419 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9420 (js2-add-strict-warning
9421 msg nil
9422 ;; back up from comma to beginning of line or array/objlit
9423 (max (if elems
9424 (js2-node-pos (car elems))
9425 pos)
9426 (save-excursion
9427 (goto-char comma-pos)
9428 (back-to-indentation)
9429 (point)))
9430 comma-pos))
9431
9432 (defun js2-parse-array-literal ()
9433 (let ((pos js2-token-beg)
9434 (end js2-token-end)
9435 (after-lb-or-comma t)
9436 after-comma
9437 tt
9438 elems
9439 pn
9440 (continue t))
9441 (unless js2-is-in-destructuring
9442 (js2-push-scope (make-js2-scope))) ; for array comp
9443 (while continue
9444 (setq tt (js2-peek-token))
9445 (cond
9446 ;; comma
9447 ((= tt js2-COMMA)
9448 (js2-consume-token)
9449 (setq after-comma js2-token-end)
9450 (if (not after-lb-or-comma)
9451 (setq after-lb-or-comma t)
9452 (push nil elems)))
9453 ;; end of array
9454 ((or (= tt js2-RB)
9455 (= tt js2-EOF)) ; prevent infinite loop
9456 (if (= tt js2-EOF)
9457 (js2-report-error "msg.no.bracket.arg" nil pos)
9458 (js2-consume-token))
9459 (setq continue nil
9460 end js2-token-end
9461 pn (make-js2-array-node :pos pos
9462 :len (- js2-ts-cursor pos)
9463 :elems (nreverse elems)))
9464 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9465 (when (and after-comma (not js2-is-in-destructuring))
9466 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9467 pos elems after-comma)))
9468 ;; destructuring binding
9469 (js2-is-in-destructuring
9470 (push (if (or (= tt js2-LC)
9471 (= tt js2-LB)
9472 (= tt js2-NAME))
9473 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9474 (js2-parse-destruct-primary-expr)
9475 ;; invalid pattern
9476 (js2-consume-token)
9477 (js2-report-error "msg.bad.var")
9478 (make-js2-error-node))
9479 elems)
9480 (setq after-lb-or-comma nil
9481 after-comma nil))
9482 ;; array comp
9483 ((and (>= js2-language-version 170)
9484 (= tt js2-FOR) ; check for array comprehension
9485 (not after-lb-or-comma) ; "for" can't follow a comma
9486 elems ; must have at least 1 element
9487 (not (cdr elems))) ; but no 2nd element
9488 (setf continue nil
9489 pn (js2-parse-array-comprehension (car elems) pos)))
9490
9491 ;; another element
9492 (t
9493 (unless after-lb-or-comma
9494 (js2-report-error "msg.no.bracket.arg"))
9495 (push (js2-parse-assign-expr) elems)
9496 (setq after-lb-or-comma nil
9497 after-comma nil))))
9498 (unless js2-is-in-destructuring
9499 (js2-pop-scope))
9500 pn))
9501
9502 (defun js2-parse-array-comprehension (expr pos)
9503 "Parse a JavaScript 1.7 Array Comprehension.
9504 EXPR is the first expression after the opening left-bracket.
9505 POS is the beginning of the LB token preceding EXPR.
9506 We should have just parsed the 'for' keyword before calling this function."
9507 (let (loops
9508 loop
9509 first
9510 prev
9511 filter
9512 if-pos
9513 result)
9514 (while (= (js2-peek-token) js2-FOR)
9515 (let ((prev (car loops))) ; rearrange scope chain
9516 (push (setq loop (js2-parse-array-comp-loop)) loops)
9517 (if prev ; each loop is parent scope to the next one
9518 (setf (js2-scope-parent-scope loop) prev)
9519 ; first loop takes expr scope's parent
9520 (setf (js2-scope-parent-scope (setq first loop))
9521 (js2-scope-parent-scope js2-current-scope)))))
9522 ;; set expr scope's parent to the last loop
9523 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9524 (when (= (js2-peek-token) js2-IF)
9525 (js2-consume-token)
9526 (setq if-pos (- js2-token-beg pos) ; relative
9527 filter (js2-parse-condition)))
9528 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9529 (setq result (make-js2-array-comp-node :pos pos
9530 :len (- js2-ts-cursor pos)
9531 :result expr
9532 :loops (nreverse loops)
9533 :filter (car filter)
9534 :lp (js2-relpos (second filter) pos)
9535 :rp (js2-relpos (third filter) pos)
9536 :if-pos if-pos))
9537 (apply #'js2-node-add-children result expr (car filter)
9538 (js2-array-comp-node-loops result))
9539 (setq js2-current-scope first) ; pop to the first loop
9540 result))
9541
9542 (defun js2-parse-array-comp-loop ()
9543 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9544 Last token peeked should be the initial FOR."
9545 (let ((pos js2-token-beg)
9546 (pn (make-js2-array-comp-loop-node))
9547 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9548 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9549 (js2-push-scope pn)
9550 (unwind-protect
9551 (progn
9552 (when (js2-match-token js2-NAME)
9553 (if (string= js2-ts-string "each")
9554 (progn
9555 (setq foreach-p t
9556 each-pos (- js2-token-beg pos)) ; relative
9557 (js2-record-face 'font-lock-keyword-face))
9558 (js2-report-error "msg.no.paren.for")))
9559 (if (js2-must-match js2-LP "msg.no.paren.for")
9560 (setq lp (- js2-token-beg pos)))
9561 (setq tt (js2-peek-token))
9562 (cond
9563 ((or (= tt js2-LB)
9564 (= tt js2-LC))
9565 (setq iter (js2-parse-destruct-primary-expr))
9566 (js2-define-destruct-symbols iter js2-LET
9567 'font-lock-variable-name-face t))
9568 ((js2-match-token js2-NAME)
9569 (setq iter (js2-create-name-node)))
9570 (t
9571 (js2-report-error "msg.bad.var")))
9572 ;; Define as a let since we want the scope of the variable to
9573 ;; be restricted to the array comprehension
9574 (if (js2-name-node-p iter)
9575 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9576 (if (or (js2-match-token js2-IN)
9577 (and (>= js2-language-version 200)
9578 (js2-match-contextual-kwd "of")
9579 (setq forof-p t)))
9580 (setq in-pos (- js2-token-beg pos))
9581 (js2-report-error "msg.in.after.for.name"))
9582 (setq obj (js2-parse-expr))
9583 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9584 (setq rp (- js2-token-beg pos)))
9585 (setf (js2-node-pos pn) pos
9586 (js2-node-len pn) (- js2-ts-cursor pos)
9587 (js2-array-comp-loop-node-iterator pn) iter
9588 (js2-array-comp-loop-node-object pn) obj
9589 (js2-array-comp-loop-node-in-pos pn) in-pos
9590 (js2-array-comp-loop-node-each-pos pn) each-pos
9591 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9592 (js2-array-comp-loop-node-forof-p pn) forof-p
9593 (js2-array-comp-loop-node-lp pn) lp
9594 (js2-array-comp-loop-node-rp pn) rp)
9595 (js2-node-add-children pn iter obj))
9596 (js2-pop-scope))
9597 pn))
9598
9599 (defun js2-parse-object-literal ()
9600 (let ((pos js2-token-beg)
9601 tt
9602 elems
9603 result
9604 after-comma
9605 (continue t))
9606 (while continue
9607 (setq tt (js2-peek-token))
9608 (cond
9609 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9610 ((or (js2-valid-prop-name-token tt)
9611 (= tt js2-STRING))
9612 (setq after-comma nil
9613 result (js2-parse-named-prop tt))
9614 (if (and (null result)
9615 (not js2-recover-from-parse-errors))
9616 (setq continue nil)
9617 (push result elems)))
9618 ;; {12: x} or {10.7: x}
9619 ((= tt js2-NUMBER)
9620 (js2-consume-token)
9621 (setq after-comma nil)
9622 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9623 ;; trailing comma
9624 ((= tt js2-RC)
9625 (setq continue nil)
9626 (if after-comma
9627 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9628 pos elems after-comma)))
9629 (t
9630 (js2-report-error "msg.bad.prop")
9631 (unless js2-recover-from-parse-errors
9632 (setq continue nil)))) ; end switch
9633 (if (js2-match-token js2-COMMA)
9634 (setq after-comma js2-token-end)
9635 (setq continue nil))) ; end loop
9636 (js2-must-match js2-RC "msg.no.brace.prop")
9637 (setq result (make-js2-object-node :pos pos
9638 :len (- js2-ts-cursor pos)
9639 :elems (nreverse elems)))
9640 (apply #'js2-node-add-children result (js2-object-node-elems result))
9641 result))
9642
9643 (defun js2-parse-named-prop (tt)
9644 "Parse a name, string, or getter/setter object property.
9645 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9646 (js2-consume-token)
9647 (let ((string-prop (and (= tt js2-STRING)
9648 (make-js2-string-node)))
9649 expr
9650 (ppos js2-token-beg)
9651 (pend js2-token-end)
9652 (name (js2-create-name-node))
9653 (prop js2-ts-string))
9654 (cond
9655 ;; getter/setter prop
9656 ((and (= tt js2-NAME)
9657 (= (js2-peek-token) js2-NAME)
9658 (or (string= prop "get")
9659 (string= prop "set")))
9660 (js2-consume-token)
9661 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9662 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9663 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9664 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9665 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9666 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9667 ;; when patterns are used in variable declarations, function parameters,
9668 ;; catch-clause, and iterators.
9669 ;; We have to set `js2-is-in-destructuring' to t when the current
9670 ;; expressions are on the left side of any assignment, but it's difficult
9671 ;; because it requires looking ahead of expression.
9672 ((and js2-is-in-destructuring
9673 (= tt js2-NAME)
9674 (let ((ctk (js2-peek-token)))
9675 (or (= ctk js2-COMMA)
9676 (= ctk js2-RC)
9677 (js2-valid-prop-name-token ctk))))
9678 name)
9679 ;; regular prop
9680 (t
9681 (prog1
9682 (setq expr (js2-parse-plain-property (or string-prop name)))
9683 (js2-set-face ppos pend
9684 (if (js2-function-node-p
9685 (js2-object-prop-node-right expr))
9686 'font-lock-function-name-face
9687 'font-lock-variable-name-face)
9688 'record))))))
9689
9690 (defun js2-parse-plain-property (prop)
9691 "Parse a non-getter/setter property in an object literal.
9692 PROP is the node representing the property: a number, name or string."
9693 (js2-must-match js2-COLON "msg.no.colon.prop")
9694 (let* ((pos (js2-node-pos prop))
9695 (colon (- js2-token-beg pos))
9696 (expr (js2-parse-assign-expr))
9697 (result (make-js2-object-prop-node
9698 :pos pos
9699 ;; don't include last consumed token in length
9700 :len (- (+ (js2-node-pos expr)
9701 (js2-node-len expr))
9702 pos)
9703 :left prop
9704 :right expr
9705 :op-pos colon)))
9706 (js2-node-add-children result prop expr)
9707 result))
9708
9709 (defun js2-parse-getter-setter-prop (pos prop get-p)
9710 "Parse getter or setter property in an object literal.
9711 JavaScript syntax is:
9712
9713 { get foo() {...}, set foo(x) {...} }
9714
9715 and expression closure style is also supported
9716
9717 { get foo() x, set foo(x) _x = x }
9718
9719 POS is the start position of the `get' or `set' keyword.
9720 PROP is the `js2-name-node' representing the property name.
9721 GET-P is non-nil if the keyword was `get'."
9722 (let ((type (if get-p js2-GET js2-SET))
9723 result
9724 end
9725 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9726 ;; it has to be an anonymous function, as we already parsed the name
9727 (if (/= (js2-node-type fn) js2-FUNCTION)
9728 (js2-report-error "msg.bad.prop")
9729 (if (plusp (length (js2-function-name fn)))
9730 (js2-report-error "msg.bad.prop")))
9731 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9732 (setq end (js2-node-end fn)
9733 result (make-js2-getter-setter-node :type type
9734 :pos pos
9735 :len (- end pos)
9736 :left prop
9737 :right fn))
9738 (js2-node-add-children result prop fn)
9739 result))
9740
9741 (defun js2-create-name-node (&optional check-activation-p token)
9742 "Create a name node using the token info from last scanned name.
9743 In some cases we need to either synthesize a name node, or we lost
9744 the name token information by peeking. If the TOKEN parameter is
9745 not `js2-NAME', then we use the token info saved in instance vars."
9746 (let ((beg js2-token-beg)
9747 (s js2-ts-string)
9748 name)
9749 (when (/= js2-current-token js2-NAME)
9750 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9751 s js2-prev-name-token-string
9752 js2-prev-name-token-start nil
9753 js2-prev-name-token-string nil))
9754 (setq name (make-js2-name-node :pos beg
9755 :name s
9756 :len (length s)))
9757 (if check-activation-p
9758 (js2-check-activation-name s (or token js2-NAME)))
9759 name))
9760
9761 ;;; Indentation support
9762
9763 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9764 ;; Karl cleverly deduces that the desired indentation level is often a
9765 ;; function of paren/bracket/brace nesting depth, which can be determined
9766 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9767 ;; then does some equally clever checks to see if we're in the context of a
9768 ;; substatement of a possibly braceless statement keyword such as if, while,
9769 ;; or finally. This approach yields pretty good results.
9770
9771 ;; The indenter is often "wrong", however, and needs to be overridden.
9772 ;; The right long-term solution is probably to emulate (or integrate
9773 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9774 ;; parse tree from `js2-parse' is present, which is not true at the
9775 ;; moment the user is typing, computing indentation is still thousands
9776 ;; of lines of code to handle every possible syntactic edge case.
9777
9778 ;; In the meantime, the compromise solution is that we offer a "bounce
9779 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9780 ;; current line indent among various likely guess points. This approach
9781 ;; is far from perfect, but should at least make it slightly easier to
9782 ;; move the line towards its desired indentation when manually
9783 ;; overriding Karl's heuristic nesting guesser.
9784
9785 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9786 ;; extensions such as `let' and Array comprehensions. Major kudos to
9787 ;; Karl for coming up with the initial approach, which packs a lot of
9788 ;; punch for so little code.
9789
9790 (defconst js2-possibly-braceless-keywords-re
9791 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9792 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9793 "try" "while" "with" "let")))
9794 "Regular expression matching keywords that are optionally
9795 followed by an opening brace.")
9796
9797 (defconst js2-indent-operator-re
9798 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9799 (regexp-opt '("in" "instanceof") 'words))
9800 "Regular expression matching operators that affect indentation
9801 of continued expressions.")
9802
9803 (defconst js2-declaration-keyword-re
9804 (regexp-opt '("var" "let" "const") 'words)
9805 "Regular expression matching variable declaration keywords.")
9806
9807 ;; This function has horrible results if you're typing an array
9808 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9809 ;; in conjunction with electric-indent, so just disabling it.
9810 (defsubst js2-code-at-bol-p ()
9811 "Return t if the first character on line is non-whitespace."
9812 nil)
9813
9814 (defun js2-insert-and-indent (key)
9815 "Run command bound to key and indent current line. Runs the command
9816 bound to KEY in the global keymap and indents the current line."
9817 (interactive (list (this-command-keys)))
9818 (let ((cmd (lookup-key (current-global-map) key)))
9819 (if (commandp cmd)
9820 (call-interactively cmd)))
9821 ;; don't do the electric keys inside comments or strings,
9822 ;; and don't do bounce-indent with them.
9823 (let ((parse-state (syntax-ppss (point)))
9824 (js2-bounce-indent-p (js2-code-at-bol-p)))
9825 (unless (or (nth 3 parse-state)
9826 (nth 4 parse-state))
9827 (indent-according-to-mode))))
9828
9829 (defun js2-re-search-forward-inner (regexp &optional bound count)
9830 "Auxiliary function for `js2-re-search-forward'."
9831 (let (parse saved-point)
9832 (while (> count 0)
9833 (re-search-forward regexp bound)
9834 (setq parse (if saved-point
9835 (parse-partial-sexp saved-point (point))
9836 (syntax-ppss (point))))
9837 (cond ((nth 3 parse)
9838 (re-search-forward
9839 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9840 (save-excursion (end-of-line) (point)) t))
9841 ((nth 7 parse)
9842 (forward-line))
9843 ((or (nth 4 parse)
9844 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9845 (re-search-forward "\\*/"))
9846 (t
9847 (setq count (1- count))))
9848 (setq saved-point (point))))
9849 (point))
9850
9851 (defun js2-re-search-forward (regexp &optional bound noerror count)
9852 "Search forward but ignore strings and comments. Invokes
9853 `re-search-forward' but treats the buffer as if strings and
9854 comments have been removed."
9855 (let ((saved-point (point))
9856 (search-expr
9857 (cond ((null count)
9858 '(js2-re-search-forward-inner regexp bound 1))
9859 ((< count 0)
9860 '(js2-re-search-backward-inner regexp bound (- count)))
9861 ((> count 0)
9862 '(js2-re-search-forward-inner regexp bound count)))))
9863 (condition-case err
9864 (eval search-expr)
9865 (search-failed
9866 (goto-char saved-point)
9867 (unless noerror
9868 (error (error-message-string err)))))))
9869
9870 (defun js2-re-search-backward-inner (regexp &optional bound count)
9871 "Auxiliary function for `js2-re-search-backward'."
9872 (let (parse saved-point)
9873 (while (> count 0)
9874 (re-search-backward regexp bound)
9875 (setq parse (if saved-point
9876 (parse-partial-sexp saved-point (point))
9877 (syntax-ppss (point))))
9878 (cond ((nth 3 parse)
9879 (re-search-backward
9880 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9881 (save-excursion (beginning-of-line) (point)) t))
9882 ((nth 7 parse)
9883 (goto-char (nth 8 parse)))
9884 ((or (nth 4 parse)
9885 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9886 (re-search-backward "/\\*"))
9887 (t
9888 (setq count (1- count))))))
9889 (point))
9890
9891 (defun js2-re-search-backward (regexp &optional bound noerror count)
9892 "Search backward but ignore strings and comments. Invokes
9893 `re-search-backward' but treats the buffer as if strings and
9894 comments have been removed."
9895 (let ((saved-point (point))
9896 (search-expr
9897 (cond ((null count)
9898 '(js2-re-search-backward-inner regexp bound 1))
9899 ((< count 0)
9900 '(js2-re-search-forward-inner regexp bound (- count)))
9901 ((> count 0)
9902 '(js2-re-search-backward-inner regexp bound count)))))
9903 (condition-case err
9904 (eval search-expr)
9905 (search-failed
9906 (goto-char saved-point)
9907 (unless noerror
9908 (error (error-message-string err)))))))
9909
9910 (defun js2-looking-at-operator-p ()
9911 "Return non-nil if text after point is an operator (that is not
9912 a comma)."
9913 (save-match-data
9914 (and (looking-at js2-indent-operator-re)
9915 (or (not (looking-at ":"))
9916 (save-excursion
9917 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9918 (looking-at "?")))))))
9919
9920 (defun js2-continued-expression-p ()
9921 "Returns non-nil if the current line continues an expression."
9922 (save-excursion
9923 (back-to-indentation)
9924 (or (js2-looking-at-operator-p)
9925 (when (catch 'found
9926 (while (and (re-search-backward "\n" nil t)
9927 (let ((state (syntax-ppss)))
9928 (when (nth 4 state)
9929 (goto-char (nth 8 state))) ;; skip comments
9930 (skip-chars-backward " \t")
9931 (if (bolp)
9932 t
9933 (throw 'found t))))))
9934 (backward-char)
9935 (when (js2-looking-at-operator-p)
9936 (backward-char)
9937 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))
9938
9939 (defun js2-end-of-do-while-loop-p ()
9940 "Returns non-nil if word after point is `while' of a do-while
9941 statement, else returns nil. A braceless do-while statement
9942 spanning several lines requires that the start of the loop is
9943 indented to the same column as the current line."
9944 (interactive)
9945 (save-excursion
9946 (save-match-data
9947 (when (looking-at "\\s-*\\<while\\>")
9948 (if (save-excursion
9949 (skip-chars-backward "[ \t\n]*}")
9950 (looking-at "[ \t\n]*}"))
9951 (save-excursion
9952 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9953 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9954 (or (looking-at "\\<do\\>")
9955 (let ((saved-indent (current-indentation)))
9956 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9957 (/= (current-indentation) saved-indent)))
9958 (and (looking-at "[ \t]*\\<do\\>")
9959 (not (js2-re-search-forward
9960 "\\<while\\>" (point-at-eol) t))
9961 (= (current-indentation) saved-indent)))))))))
9962
9963 (defun js2-multiline-decl-indentation ()
9964 "Returns the declaration indentation column if the current line belongs
9965 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9966 (let (forward-sexp-function ; use Lisp version
9967 at-opening-bracket)
9968 (save-excursion
9969 (back-to-indentation)
9970 (when (not (looking-at js2-declaration-keyword-re))
9971 (when (looking-at js2-indent-operator-re)
9972 (goto-char (match-end 0))) ; continued expressions are ok
9973 (while (and (not at-opening-bracket)
9974 (not (bobp))
9975 (let ((pos (point)))
9976 (save-excursion
9977 (js2-backward-sws)
9978 (or (eq (char-before) ?,)
9979 (and (not (eq (char-before) ?\;))
9980 (and
9981 (prog2 (skip-chars-backward "[[:punct:]]")
9982 (looking-at js2-indent-operator-re)
9983 (js2-backward-sws))
9984 (not (eq (char-before) ?\;))))
9985 (js2-same-line pos)))))
9986 (condition-case err
9987 (backward-sexp)
9988 (scan-error (setq at-opening-bracket t))))
9989 (when (looking-at js2-declaration-keyword-re)
9990 (goto-char (match-end 0))
9991 (1+ (current-column)))))))
9992
9993 (defun js2-ctrl-statement-indentation ()
9994 "Returns the proper indentation of the current line if it
9995 starts the body of a control statement without braces, else
9996 returns nil."
9997 (let (forward-sexp-function) ; temporarily unbind it
9998 (save-excursion
9999 (back-to-indentation)
10000 (when (and (not (js2-same-line (point-min)))
10001 (not (looking-at "{"))
10002 (js2-re-search-backward "[[:graph:]]" nil t)
10003 (not (looking-at "[{([]"))
10004 (progn
10005 (forward-char)
10006 (when (= (char-before) ?\))
10007 ;; scan-sexps sometimes throws an error
10008 (ignore-errors (backward-sexp))
10009 (skip-chars-backward " \t" (point-at-bol)))
10010 (let ((pt (point)))
10011 (back-to-indentation)
10012 (and (looking-at js2-possibly-braceless-keywords-re)
10013 (= (match-end 0) pt)
10014 (not (js2-end-of-do-while-loop-p))))))
10015 (+ (current-indentation) js2-basic-offset)))))
10016
10017 (defun js2-indent-in-array-comp (parse-status)
10018 "Return non-nil if we think we're in an array comprehension.
10019 In particular, return the buffer position of the first `for' kwd."
10020 (let ((bracket (nth 1 parse-status))
10021 (end (point)))
10022 (when bracket
10023 (save-excursion
10024 (goto-char bracket)
10025 (when (looking-at "\\[")
10026 (forward-char 1)
10027 (js2-forward-sws)
10028 (if (looking-at "[[{]")
10029 (let (forward-sexp-function) ; use lisp version
10030 (forward-sexp) ; skip destructuring form
10031 (js2-forward-sws)
10032 (if (and (/= (char-after) ?,) ; regular array
10033 (looking-at "for"))
10034 (match-beginning 0)))
10035 ;; to skip arbitrary expressions we need the parser,
10036 ;; so we'll just guess at it.
10037 (if (and (> end (point)) ; not empty literal
10038 (re-search-forward "[^,]]* \\(for\\) " end t)
10039 ;; not inside comment or string literal
10040 (let ((state (parse-partial-sexp bracket (point))))
10041 (not (or (nth 3 state) (nth 4 state)))))
10042 (match-beginning 1))))))))
10043
10044 (defun js2-array-comp-indentation (parse-status for-kwd)
10045 (if (js2-same-line for-kwd)
10046 ;; first continuation line
10047 (save-excursion
10048 (goto-char (nth 1 parse-status))
10049 (forward-char 1)
10050 (skip-chars-forward " \t")
10051 (current-column))
10052 (save-excursion
10053 (goto-char for-kwd)
10054 (current-column))))
10055
10056 (defun js2-proper-indentation (parse-status)
10057 "Return the proper indentation for the current line."
10058 (save-excursion
10059 (back-to-indentation)
10060 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10061 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
10062 (continued-expr-p (js2-continued-expression-p))
10063 (declaration-indent (and js2-pretty-multiline-declarations
10064 (js2-multiline-decl-indentation)))
10065 (bracket (nth 1 parse-status))
10066 beg)
10067 (cond
10068 ;; indent array comprehension continuation lines specially
10069 ((and bracket
10070 (>= js2-language-version 170)
10071 (not (js2-same-line bracket))
10072 (setq beg (js2-indent-in-array-comp parse-status))
10073 (>= (point) (save-excursion
10074 (goto-char beg)
10075 (point-at-bol)))) ; at or after first loop?
10076 (js2-array-comp-indentation parse-status beg))
10077
10078 (ctrl-stmt-indent)
10079
10080 ((and declaration-indent continued-expr-p)
10081 (+ declaration-indent js2-basic-offset))
10082
10083 (declaration-indent)
10084
10085 (bracket
10086 (goto-char bracket)
10087 (cond
10088 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10089 (when (save-excursion (skip-chars-backward " \t)")
10090 (looking-at ")"))
10091 (backward-list))
10092 (back-to-indentation)
10093 (and (eq js2-pretty-multiline-declarations 'all)
10094 (looking-at js2-declaration-keyword-re)
10095 (goto-char (1+ (match-end 0))))
10096 (cond (same-indent-p
10097 (current-column))
10098 (continued-expr-p
10099 (+ (current-column) (* 2 js2-basic-offset)))
10100 (t
10101 (+ (current-column) js2-basic-offset))))
10102 (t
10103 (unless same-indent-p
10104 (forward-char)
10105 (skip-chars-forward " \t"))
10106 (current-column))))
10107
10108 (continued-expr-p js2-basic-offset)
10109
10110 (t 0)))))
10111
10112 (defun js2-lineup-comment (parse-status)
10113 "Indent a multi-line block comment continuation line."
10114 (let* ((beg (nth 8 parse-status))
10115 (first-line (js2-same-line beg))
10116 (offset (save-excursion
10117 (goto-char beg)
10118 (if (looking-at "/\\*")
10119 (+ 1 (current-column))
10120 0))))
10121 (unless first-line
10122 (indent-line-to offset))))
10123
10124 (defun js2-backward-sws ()
10125 "Move backward through whitespace and comments."
10126 (interactive)
10127 (while (forward-comment -1)))
10128
10129 (defun js2-forward-sws ()
10130 "Move forward through whitespace and comments."
10131 (interactive)
10132 (while (forward-comment 1)))
10133
10134 (defsubst js2-current-indent (&optional pos)
10135 "Return column of indentation on current line.
10136 If POS is non-nil, go to that point and return indentation for that line."
10137 (save-excursion
10138 (if pos
10139 (goto-char pos))
10140 (back-to-indentation)
10141 (current-column)))
10142
10143 (defsubst js2-arglist-close ()
10144 "Return non-nil if we're on a line beginning with a close-paren/brace."
10145 (save-match-data
10146 (save-excursion
10147 (goto-char (point-at-bol))
10148 (js2-forward-sws)
10149 (looking-at "[])}]"))))
10150
10151 (defsubst js2-indent-looks-like-label-p ()
10152 (goto-char (point-at-bol))
10153 (js2-forward-sws)
10154 (looking-at (concat js2-mode-identifier-re ":")))
10155
10156 (defun js2-indent-in-objlit-p (parse-status)
10157 "Return non-nil if this looks like an object-literal entry."
10158 (let ((start (nth 1 parse-status)))
10159 (and
10160 start
10161 (save-excursion
10162 (and (zerop (forward-line -1))
10163 (not (< (point) start)) ; crossed a {} boundary
10164 (js2-indent-looks-like-label-p)))
10165 (save-excursion
10166 (js2-indent-looks-like-label-p)))))
10167
10168 ;; if prev line looks like foobar({ then we're passing an object
10169 ;; literal to a function call, and people pretty much always want to
10170 ;; de-dent back to the previous line, so move the 'basic-offset'
10171 ;; position to the front.
10172 (defsubst js2-indent-objlit-arg-p (parse-status)
10173 (save-excursion
10174 (back-to-indentation)
10175 (js2-backward-sws)
10176 (and (eq (1- (point)) (nth 1 parse-status))
10177 (eq (char-before) ?{)
10178 (progn
10179 (forward-char -1)
10180 (skip-chars-backward " \t")
10181 (eq (char-before) ?\()))))
10182
10183 (defsubst js2-indent-case-block-p ()
10184 (save-excursion
10185 (back-to-indentation)
10186 (js2-backward-sws)
10187 (goto-char (point-at-bol))
10188 (skip-chars-forward " \t")
10189 (save-match-data
10190 (looking-at "case\\s-.+:"))))
10191
10192 (defsubst js2-syntax-bol ()
10193 "Return the point at the first non-whitespace char on the line.
10194 Returns `point-at-bol' if the line is empty."
10195 (save-excursion
10196 (beginning-of-line)
10197 (skip-chars-forward " \t")
10198 (point)))
10199
10200 (defun js2-bounce-indent (normal-col parse-status backwards)
10201 "Cycle among alternate computed indentation positions.
10202 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10203 of the buffer to the current point. NORMAL-COL is the indentation
10204 column computed by the heuristic guesser based on current paren,
10205 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10206 in reverse."
10207 (let ((cur-indent (js2-current-indent))
10208 (old-buffer-undo-list buffer-undo-list)
10209 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10210 (current-line (save-excursion
10211 (forward-line 0) ; move to bol
10212 (1+ (count-lines (point-min) (point)))))
10213 positions
10214 pos
10215 main-pos
10216 anchor
10217 arglist-cont
10218 same-indent
10219 prev-line-col
10220 basic-offset
10221 computed-pos)
10222 ;; temporarily don't record undo info, if user requested this
10223 (if js2-mode-indent-inhibit-undo
10224 (setq buffer-undo-list t))
10225 (unwind-protect
10226 (progn
10227 ;; first likely point: indent from beginning of previous code line
10228 (push (setq basic-offset
10229 (+ (save-excursion
10230 (back-to-indentation)
10231 (js2-backward-sws)
10232 (back-to-indentation)
10233 (setq prev-line-col (current-column)))
10234 js2-basic-offset))
10235 positions)
10236
10237 ;; (first + epsilon) likely point: indent 2x from beginning of
10238 ;; previous code line. Some companies like this approach. Ahem.
10239 ;; Seriously, though -- 4-space indent for expression continuation
10240 ;; lines isn't a bad idea. We should eventually implement it
10241 ;; that way.
10242 (push (setq basic-offset
10243 (+ (save-excursion
10244 (back-to-indentation)
10245 (js2-backward-sws)
10246 (back-to-indentation)
10247 (setq prev-line-col (current-column)))
10248 (* 2 js2-basic-offset)))
10249 positions)
10250
10251 ;; second likely point: indent from assign-expr RHS. This
10252 ;; is just a crude guess based on finding " = " on the previous
10253 ;; line containing actual code.
10254 (setq pos (save-excursion
10255 (save-match-data
10256 (forward-line -1)
10257 (goto-char (point-at-bol))
10258 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10259 (point-at-eol) t)
10260 (goto-char (match-end 1))
10261 (skip-chars-forward " \t\r\n")
10262 (current-column)))))
10263 (when pos
10264 (incf pos js2-basic-offset)
10265 (push pos positions))
10266
10267 ;; third likely point: same indent as previous line of code.
10268 ;; Make it the first likely point if we're not on an
10269 ;; arglist-close line and previous line ends in a comma, or
10270 ;; both this line and prev line look like object-literal
10271 ;; elements.
10272 (setq pos (save-excursion
10273 (goto-char (point-at-bol))
10274 (js2-backward-sws)
10275 (back-to-indentation)
10276 (prog1
10277 (current-column)
10278 ;; while we're here, look for trailing comma
10279 (if (save-excursion
10280 (goto-char (point-at-eol))
10281 (js2-backward-sws)
10282 (eq (char-before) ?,))
10283 (setq arglist-cont (1- (point)))))))
10284 (when pos
10285 (if (and (or arglist-cont
10286 (js2-indent-in-objlit-p parse-status))
10287 (not (js2-arglist-close)))
10288 (setq same-indent pos))
10289 (push pos positions))
10290
10291 ;; fourth likely point: first preceding code with less indentation
10292 ;; than the immediately preceding code line.
10293 (setq pos (save-excursion
10294 (back-to-indentation)
10295 (js2-backward-sws)
10296 (back-to-indentation)
10297 (setq anchor (current-column))
10298 (while (and (zerop (forward-line -1))
10299 (>= (progn
10300 (back-to-indentation)
10301 (current-column))
10302 anchor)))
10303 (setq pos (current-column))))
10304 (push pos positions)
10305
10306 ;; nesting-heuristic position, main by default
10307 (push (setq main-pos normal-col) positions)
10308
10309 ;; delete duplicates and sort positions list
10310 (setq positions (sort (delete-dups positions) '<))
10311
10312 ;; comma-list continuation lines: prev line indent takes precedence
10313 (if same-indent
10314 (setq main-pos same-indent))
10315
10316 ;; common special cases where we want to indent in from previous line
10317 (if (or (js2-indent-case-block-p)
10318 (js2-indent-objlit-arg-p parse-status))
10319 (setq main-pos basic-offset))
10320
10321 ;; if bouncing backwards, reverse positions list
10322 (if backwards
10323 (setq positions (reverse positions)))
10324
10325 ;; record whether we're already sitting on one of the alternatives
10326 (setq pos (member cur-indent positions))
10327
10328 (cond
10329 ;; case 0: we're one one of the alternatives and this is the
10330 ;; first time they've pressed TAB on this line (best-guess).
10331 ((and js2-mode-indent-ignore-first-tab
10332 pos
10333 ;; first time pressing TAB on this line?
10334 (not (eq js2-mode-last-indented-line current-line)))
10335 ;; do nothing
10336 (setq computed-pos nil))
10337 ;; case 1: only one computed position => use it
10338 ((null (cdr positions))
10339 (setq computed-pos 0))
10340 ;; case 2: not on any of the computed spots => use main spot
10341 ((not pos)
10342 (setq computed-pos (js2-position main-pos positions)))
10343 ;; case 3: on last position: cycle to first position
10344 ((null (cdr pos))
10345 (setq computed-pos 0))
10346 ;; case 4: on intermediate position: cycle to next position
10347 (t
10348 (setq computed-pos (js2-position (second pos) positions))))
10349
10350 ;; see if any hooks want to indent; otherwise we do it
10351 (loop with result = nil
10352 for hook in js2-indent-hook
10353 while (null result)
10354 do
10355 (setq result (funcall hook positions computed-pos))
10356 finally do
10357 (unless (or result (null computed-pos))
10358 (indent-line-to (nth computed-pos positions)))))
10359
10360 ;; finally
10361 (if js2-mode-indent-inhibit-undo
10362 (setq buffer-undo-list old-buffer-undo-list))
10363 ;; see commentary for `js2-mode-last-indented-line'
10364 (setq js2-mode-last-indented-line current-line))))
10365
10366 (defun js2-indent-bounce-backwards ()
10367 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10368 cycles between the computed indentation positions in reverse order."
10369 (interactive)
10370 (js2-indent-line t))
10371
10372 (defsubst js2-1-line-comment-continuation-p ()
10373 "Return t if we're in a 1-line comment continuation.
10374 If so, we don't ever want to use bounce-indent."
10375 (save-excursion
10376 (save-match-data
10377 (and (progn
10378 (forward-line 0)
10379 (looking-at "\\s-*//"))
10380 (progn
10381 (forward-line -1)
10382 (forward-line 0)
10383 (when (looking-at "\\s-*$")
10384 (js2-backward-sws)
10385 (forward-line 0))
10386 (looking-at "\\s-*//"))))))
10387
10388 (defun js2-indent-line (&optional bounce-backwards)
10389 "Indent the current line as JavaScript source text."
10390 (interactive)
10391 (let (parse-status
10392 offset
10393 indent-col
10394 moved
10395 ;; don't whine about errors/warnings when we're indenting.
10396 ;; This has to be set before calling parse-partial-sexp below.
10397 (inhibit-point-motion-hooks t))
10398 (setq parse-status (save-excursion
10399 (syntax-ppss (point-at-bol)))
10400 offset (- (point) (save-excursion
10401 (back-to-indentation)
10402 (point))))
10403 (js2-with-underscore-as-word-syntax
10404 (if (nth 4 parse-status)
10405 (js2-lineup-comment parse-status)
10406 (setq indent-col (js2-proper-indentation parse-status))
10407 ;; see comments below about js2-mode-last-indented-line
10408 (cond
10409 ;; bounce-indenting is disabled during electric-key indent.
10410 ;; It doesn't work well on first line of buffer.
10411 ((and js2-bounce-indent-p
10412 (not (js2-same-line (point-min)))
10413 (not (js2-1-line-comment-continuation-p)))
10414 (js2-bounce-indent indent-col parse-status bounce-backwards))
10415 ;; just indent to the guesser's likely spot
10416 (t (indent-line-to indent-col))))
10417 (when (plusp offset)
10418 (forward-char offset)))))
10419
10420 (defun js2-indent-region (start end)
10421 "Indent the region, but don't use bounce indenting."
10422 (let ((js2-bounce-indent-p nil)
10423 (indent-region-function nil)
10424 (after-change-functions (remq 'js2-mode-edit
10425 after-change-functions)))
10426 (indent-region start end nil) ; nil for byte-compiler
10427 (js2-mode-edit start end (- end start))))
10428
10429 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10430
10431 ;;;###autoload
10432 (defun js2-mode ()
10433 "Major mode for editing JavaScript code.
10434
10435 \\{js2-mode-map}"
10436 (interactive)
10437 (kill-all-local-variables)
10438 (set-syntax-table js2-mode-syntax-table)
10439 (use-local-map js2-mode-map)
10440 (make-local-variable 'comment-start)
10441 (make-local-variable 'comment-end)
10442 (make-local-variable 'comment-start-skip)
10443 (setq major-mode 'js2-mode
10444 mode-name "JavaScript-IDE"
10445 comment-start "//" ; used by comment-region; don't change it
10446 comment-end "")
10447 (setq local-abbrev-table js2-mode-abbrev-table)
10448 (set (make-local-variable 'max-lisp-eval-depth)
10449 (max max-lisp-eval-depth 3000))
10450 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10451 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10452
10453 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10454 ;; on most platforms other than the one I originally wrote it on.
10455 ;; So it's back to `c-fill-paragraph'.
10456 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10457
10458 (add-hook 'before-save-hook #'js2-before-save nil t)
10459 (set (make-local-variable 'next-error-function) #'js2-next-error)
10460 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10461 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10462 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10463 ;; for characters inside regexp literals.
10464 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10465 ;; this is necessary to make `show-paren-function' work properly
10466 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10467 ;; needed for M-x rgrep, among other things
10468 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10469
10470 ;; some variables needed by cc-engine for paragraph-fill, etc.
10471 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10472 c-comment-start-regexp "/[*/]\\|\\s|"
10473 c-line-comment-starter "//"
10474 c-paragraph-start js2-paragraph-start
10475 c-paragraph-separate "$"
10476 comment-start-skip js2-comment-start-skip
10477 c-syntactic-ws-start js2-syntactic-ws-start
10478 c-syntactic-ws-end js2-syntactic-ws-end
10479 c-syntactic-eol js2-syntactic-eol)
10480
10481 (let ((c-buffer-is-cc-mode t))
10482 ;; Copied from `js-mode'. Also see Bug#6071.
10483 (make-local-variable 'paragraph-start)
10484 (make-local-variable 'paragraph-separate)
10485 (make-local-variable 'paragraph-ignore-fill-prefix)
10486 (make-local-variable 'adaptive-fill-mode)
10487 (make-local-variable 'adaptive-fill-regexp)
10488 (c-setup-paragraph-variables))
10489
10490 (setq js2-default-externs
10491 (append js2-ecma-262-externs
10492 (if js2-include-browser-externs
10493 js2-browser-externs)
10494 (if js2-include-gears-externs
10495 js2-gears-externs)
10496 (if js2-include-rhino-externs
10497 js2-rhino-externs)))
10498
10499 ;; We do our own syntax highlighting based on the parse tree.
10500 ;; However, we want minor modes that add keywords to highlight properly
10501 ;; (examples: doxymacs, column-marker).
10502 ;; To customize highlighted keywords, use `font-lock-add-keywords'.
10503 (setq font-lock-defaults '(nil t))
10504
10505 ;; Experiment: make reparse-delay longer for longer files.
10506 (if (plusp js2-dynamic-idle-timer-adjust)
10507 (setq js2-idle-timer-delay
10508 (* js2-idle-timer-delay
10509 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10510
10511 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10512 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10513 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10514 (imenu-add-to-menubar (concat "IM-" mode-name))
10515 (when js2-mirror-mode
10516 (js2-enter-mirror-mode))
10517 (add-to-invisibility-spec '(js2-outline . t))
10518 (set (make-local-variable 'line-move-ignore-invisible) t)
10519 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10520
10521 (if (fboundp 'run-mode-hooks)
10522 (run-mode-hooks 'js2-mode-hook)
10523 (run-hooks 'js2-mode-hook))
10524
10525 (setq js2-mode-functions-hidden nil
10526 js2-mode-comments-hidden nil
10527 js2-mode-buffer-dirty-p t
10528 js2-mode-parsing nil)
10529 (js2-reparse))
10530
10531 (defun js2-mode-exit ()
10532 "Exit `js2-mode' and clean up."
10533 (interactive)
10534 (when js2-mode-node-overlay
10535 (delete-overlay js2-mode-node-overlay)
10536 (setq js2-mode-node-overlay nil))
10537 (js2-remove-overlays)
10538 (setq js2-mode-ast nil)
10539 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10540 (remove-from-invisibility-spec '(js2-outline . t))
10541 (js2-mode-show-all)
10542 (js2-with-unmodifying-text-property-changes
10543 (js2-clear-face (point-min) (point-max))))
10544
10545 (defun js2-before-save ()
10546 "Clean up whitespace before saving file.
10547 You can disable this by customizing `js2-cleanup-whitespace'."
10548 (when js2-cleanup-whitespace
10549 (let ((col (current-column)))
10550 (delete-trailing-whitespace)
10551 ;; don't change trailing whitespace on current line
10552 (unless (eq (current-column) col)
10553 (indent-to col)))))
10554
10555 (defsubst js2-mode-reset-timer ()
10556 "Cancel any existing parse timer and schedule a new one."
10557 (if js2-mode-parse-timer
10558 (cancel-timer js2-mode-parse-timer))
10559 (setq js2-mode-parsing nil)
10560 (let ((timer (timer-create)))
10561 (setq js2-mode-parse-timer timer)
10562 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10563 (timer-set-idle-time timer js2-idle-timer-delay)
10564 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10565 (timer-activate-when-idle timer nil)))
10566
10567 (defun js2-mode-idle-reparse (buffer)
10568 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10569 it to be reparsed when the buffer is selected."
10570 (if (eq buffer (current-buffer))
10571 (js2-reparse)
10572 ;; reparse when the buffer is selected again
10573 (with-current-buffer buffer
10574 (add-hook 'window-configuration-change-hook
10575 #'js2-mode-idle-reparse-inner
10576 nil t))))
10577
10578 (defun js2-mode-idle-reparse-inner ()
10579 (remove-hook 'window-configuration-change-hook
10580 #'js2-mode-idle-reparse-inner
10581 t)
10582 (js2-reparse))
10583
10584 (defun js2-mode-edit (beg end len)
10585 "Schedule a new parse after buffer is edited.
10586 Buffer edit spans from BEG to END and is of length LEN.
10587 Also clears the `js2-magic' bit on autoinserted parens/brackets
10588 if the edit occurred on a line different from the magic paren."
10589 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10590 (line (if magic-pos (line-number-at-pos magic-pos))))
10591 (and line
10592 (or (/= (line-number-at-pos beg) line)
10593 (and (> 0 len)
10594 (/= (line-number-at-pos end) line)))
10595 (js2-mode-mundanify-parens)))
10596 (setq js2-mode-buffer-dirty-p t)
10597 (js2-mode-hide-overlay)
10598 (js2-mode-reset-timer))
10599
10600 (defun js2-reparse (&optional force)
10601 "Re-parse current buffer after user finishes some data entry.
10602 If we get any user input while parsing, including cursor motion,
10603 we discard the parse and reschedule it. If FORCE is nil, then the
10604 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10605 (let (time
10606 interrupted-p
10607 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10608 (unless js2-mode-parsing
10609 (setq js2-mode-parsing t)
10610 (unwind-protect
10611 (when (or js2-mode-buffer-dirty-p force)
10612 (js2-remove-overlays)
10613 (js2-with-unmodifying-text-property-changes
10614 (setq js2-mode-buffer-dirty-p nil
10615 js2-mode-fontifications nil
10616 js2-mode-deferred-properties nil)
10617 (if js2-mode-verbose-parse-p
10618 (message "parsing..."))
10619 (setq time
10620 (js2-time
10621 (setq interrupted-p
10622 (catch 'interrupted
10623 (setq js2-mode-ast (js2-parse))
10624 ;; if parsing is interrupted, comments and regex
10625 ;; literals stay ignored by `parse-partial-sexp'
10626 (remove-text-properties (point-min) (point-max)
10627 '(syntax-table))
10628 (js2-mode-apply-deferred-properties)
10629 (js2-mode-remove-suppressed-warnings)
10630 (js2-mode-show-warnings)
10631 (js2-mode-show-errors)
10632 (js2-mode-highlight-magic-parens)
10633 (if (>= js2-highlight-level 1)
10634 (js2-highlight-jsdoc js2-mode-ast))
10635 nil))))
10636 (if interrupted-p
10637 (progn
10638 ;; unfinished parse => try again
10639 (setq js2-mode-buffer-dirty-p t)
10640 (js2-mode-reset-timer))
10641 (if js2-mode-verbose-parse-p
10642 (message "Parse time: %s" time)))))
10643 (setq js2-mode-parsing nil)
10644 (unless interrupted-p
10645 (setq js2-mode-parse-timer nil))))))
10646
10647 (defun js2-mode-show-node (event)
10648 "Debugging aid: highlight selected AST node on mouse click."
10649 (interactive "e")
10650 (mouse-set-point event)
10651 (let ((node (js2-node-at-point))
10652 beg
10653 end)
10654 (when js2-mode-show-overlay
10655 (if (null node)
10656 (message "No node found at location %s" (point))
10657 (setq beg (js2-node-abs-pos node)
10658 end (+ beg (js2-node-len node)))
10659 (if js2-mode-node-overlay
10660 (move-overlay js2-mode-node-overlay beg end)
10661 (setq js2-mode-node-overlay (make-overlay beg end))
10662 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10663 (js2-with-unmodifying-text-property-changes
10664 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10665 (message "%s, parent: %s"
10666 (js2-node-short-name node)
10667 (if (js2-node-parent node)
10668 (js2-node-short-name (js2-node-parent node))
10669 "nil"))))))
10670
10671 (put 'js2-mode-show-node 'CUA 'move)
10672
10673 (defun js2-mode-hide-overlay (&optional p1 p2)
10674 "Remove the debugging overlay when the point moves.
10675 P1 and P2 are the old and new values of point, respectively."
10676 (when js2-mode-node-overlay
10677 (let ((beg (overlay-start js2-mode-node-overlay))
10678 (end (overlay-end js2-mode-node-overlay)))
10679 ;; Sometimes we're called spuriously.
10680 (unless (and p2
10681 (>= p2 beg)
10682 (<= p2 end))
10683 (js2-with-unmodifying-text-property-changes
10684 (remove-text-properties beg end '(point-left nil)))
10685 (delete-overlay js2-mode-node-overlay)
10686 (setq js2-mode-node-overlay nil)))))
10687
10688 (defun js2-mode-reset ()
10689 "Debugging helper: reset everything."
10690 (interactive)
10691 (js2-mode-exit)
10692 (js2-mode))
10693
10694 (defsubst js2-mode-show-warn-or-err (e face)
10695 "Highlight a warning or error E with FACE.
10696 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10697 (let* ((key (first e))
10698 (beg (second e))
10699 (end (+ beg (third e)))
10700 ;; Don't inadvertently go out of bounds.
10701 (beg (max (point-min) (min beg (point-max))))
10702 (end (max (point-min) (min end (point-max))))
10703 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10704 (ovl (make-overlay beg end)))
10705 (overlay-put ovl 'font-lock-face face)
10706 (overlay-put ovl 'js2-error t)
10707 (put-text-property beg end 'help-echo (js2-get-msg key))
10708 (put-text-property beg end 'point-entered #'js2-echo-error)))
10709
10710 (defun js2-remove-overlays ()
10711 "Remove overlays from buffer that have a `js2-error' property."
10712 (let ((beg (point-min))
10713 (end (point-max)))
10714 (save-excursion
10715 (dolist (o (overlays-in beg end))
10716 (when (overlay-get o 'js2-error)
10717 (delete-overlay o))))))
10718
10719 (defun js2-error-at-point (&optional pos)
10720 "Return non-nil if there's an error overlay at POS.
10721 Defaults to point."
10722 (loop with pos = (or pos (point))
10723 for o in (overlays-at pos)
10724 thereis (overlay-get o 'js2-error)))
10725
10726 (defun js2-mode-apply-deferred-properties ()
10727 "Apply fontifications and other text properties recorded during parsing."
10728 (when (plusp js2-highlight-level)
10729 ;; We defer clearing faces as long as possible to eliminate flashing.
10730 (js2-clear-face (point-min) (point-max))
10731 ;; Have to reverse the recorded fontifications list so that errors
10732 ;; and warnings overwrite the normal fontifications.
10733 (dolist (f (nreverse js2-mode-fontifications))
10734 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10735 (setq js2-mode-fontifications nil))
10736 (dolist (p js2-mode-deferred-properties)
10737 (apply #'put-text-property p))
10738 (setq js2-mode-deferred-properties nil))
10739
10740 (defun js2-mode-show-errors ()
10741 "Highlight syntax errors."
10742 (when js2-mode-show-parse-errors
10743 (dolist (e (js2-ast-root-errors js2-mode-ast))
10744 (js2-mode-show-warn-or-err e 'js2-error-face))))
10745
10746 (defun js2-mode-remove-suppressed-warnings ()
10747 "Take suppressed warnings out of the AST warnings list.
10748 This ensures that the counts and `next-error' are correct."
10749 (setf (js2-ast-root-warnings js2-mode-ast)
10750 (js2-delete-if
10751 (lambda (e)
10752 (let ((key (caar e)))
10753 (or
10754 (and (not js2-strict-trailing-comma-warning)
10755 (string-match "trailing\\.comma" key))
10756 (and (not js2-strict-cond-assign-warning)
10757 (string= key "msg.equal.as.assign"))
10758 (and js2-missing-semi-one-line-override
10759 (string= key "msg.missing.semi")
10760 (let* ((beg (second e))
10761 (node (js2-node-at-point beg))
10762 (fn (js2-mode-find-parent-fn node))
10763 (body (and fn (js2-function-node-body fn)))
10764 (lc (and body (js2-node-abs-pos body)))
10765 (rc (and lc (+ lc (js2-node-len body)))))
10766 (and fn
10767 (or (null body)
10768 (save-excursion
10769 (goto-char beg)
10770 (and (js2-same-line lc)
10771 (js2-same-line rc))))))))))
10772 (js2-ast-root-warnings js2-mode-ast))))
10773
10774 (defun js2-mode-show-warnings ()
10775 "Highlight strict-mode warnings."
10776 (when js2-mode-show-strict-warnings
10777 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10778 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10779
10780 (defun js2-echo-error (old-point new-point)
10781 "Called by point-motion hooks."
10782 (let ((msg (get-text-property new-point 'help-echo)))
10783 (if (and msg (or (not (current-message))
10784 (string= (current-message) "Quit")))
10785 (message msg))))
10786
10787 (defalias #'js2-echo-help #'js2-echo-error)
10788
10789 (defun js2-enter-key ()
10790 "Handle user pressing the Enter key."
10791 (interactive)
10792 (let ((parse-status (save-excursion
10793 (syntax-ppss (point))))
10794 (js2-bounce-indent-p nil))
10795 (cond
10796 ;; check if we're inside a string
10797 ((nth 3 parse-status)
10798 (if js2-concat-multiline-strings
10799 (js2-mode-split-string parse-status)
10800 (insert "\n")))
10801 ;; check if inside a block comment
10802 ((nth 4 parse-status)
10803 (js2-mode-extend-comment))
10804 (t
10805 ;; should probably figure out what the mode-map says we should do
10806 (if js2-indent-on-enter-key
10807 (js2-indent-line))
10808 (insert "\n")
10809 (if js2-enter-indents-newline
10810 (js2-indent-line))))))
10811
10812 (defun js2-mode-split-string (parse-status)
10813 "Turn a newline in mid-string into a string concatenation.
10814 PARSE-STATUS is as documented in `parse-partial-sexp'."
10815 (let* ((col (current-column))
10816 (quote-char (nth 3 parse-status))
10817 (quote-string (string quote-char))
10818 (string-beg (nth 8 parse-status))
10819 (at-eol (eq js2-concat-multiline-strings 'eol))
10820 (indent (save-match-data
10821 (or
10822 (save-excursion
10823 (back-to-indentation)
10824 (if (looking-at "\\+")
10825 (current-column)))
10826 (save-excursion
10827 (goto-char string-beg)
10828 (if (looking-back "\\+\\s-+")
10829 (goto-char (match-beginning 0)))
10830 (current-column))))))
10831 (insert quote-char)
10832 (if at-eol
10833 (insert " +\n")
10834 (insert "\n"))
10835 ;; FIXME: This does not match the behavior of `js2-indent-line'.
10836 (indent-to indent)
10837 (unless at-eol
10838 (insert "+ "))
10839 (insert quote-string)
10840 (when (eolp)
10841 (insert quote-string)
10842 (backward-char 1))))
10843
10844 (defun js2-mode-extend-comment ()
10845 "Indent the line and, when inside a comment block, add comment prefix."
10846 (let (star single col first-line needs-close)
10847 (save-excursion
10848 (back-to-indentation)
10849 (cond
10850 ((looking-at "\\*[^/]")
10851 (setq star t
10852 col (current-column)))
10853 ((looking-at "/\\*")
10854 (setq star t
10855 first-line t
10856 col (1+ (current-column))))
10857 ((looking-at "//")
10858 (setq single t
10859 col (current-column)))))
10860 ;; Heuristic for whether we need to close the comment:
10861 ;; if we've got a parse error here, assume it's an unterminated
10862 ;; comment.
10863 (setq needs-close
10864 (or
10865 (eq (get-text-property (1- (point)) 'point-entered)
10866 'js2-echo-error)
10867 ;; The heuristic above doesn't work well when we're
10868 ;; creating a comment and there's another one downstream,
10869 ;; as our parser thinks this one ends at the end of the
10870 ;; next one. (You can have a /* inside a js block comment.)
10871 ;; So just close it if the next non-ws char isn't a *.
10872 (and first-line
10873 (eolp)
10874 (save-excursion
10875 (skip-chars-forward " \t\r\n")
10876 (not (eq (char-after) ?*))))))
10877 (insert "\n")
10878 (cond
10879 (star
10880 (indent-to col)
10881 (insert "* ")
10882 (if (and first-line needs-close)
10883 (save-excursion
10884 (insert "\n")
10885 (indent-to col)
10886 (insert "*/"))))
10887 ((and single
10888 (save-excursion
10889 (and (zerop (forward-line 1))
10890 (looking-at "\\s-*//"))))
10891 (indent-to col)
10892 (insert "// "))
10893 ;; don't need to extend the comment after all
10894 (js2-enter-indents-newline
10895 (js2-indent-line)))))
10896
10897 (defun js2-beginning-of-line ()
10898 "Toggles point between bol and first non-whitespace char in line.
10899 Also moves past comment delimiters when inside comments."
10900 (interactive)
10901 (let (node beg)
10902 (cond
10903 ((bolp)
10904 (back-to-indentation))
10905 ((looking-at "//")
10906 (skip-chars-forward "/ \t"))
10907 ((and (eq (char-after) ?*)
10908 (setq node (js2-comment-at-point))
10909 (memq (js2-comment-node-format node) '(jsdoc block))
10910 (save-excursion
10911 (skip-chars-backward " \t")
10912 (bolp)))
10913 (skip-chars-forward "\* \t"))
10914 (t
10915 (goto-char (point-at-bol))))))
10916
10917 (defun js2-end-of-line ()
10918 "Toggles point between eol and last non-whitespace char in line."
10919 (interactive)
10920 (if (eolp)
10921 (skip-chars-backward " \t")
10922 (goto-char (point-at-eol))))
10923
10924 (defun js2-enter-mirror-mode()
10925 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10926 on insertion."
10927 (interactive)
10928 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10929 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10930 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10931 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10932 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10933 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10934 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10935 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10936
10937 (defun js2-leave-mirror-mode()
10938 "Turns off mirror mode."
10939 (interactive)
10940 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10941 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10942
10943 (defsubst js2-mode-inside-string ()
10944 "Return non-nil if inside a string.
10945 Actually returns the quote character that begins the string."
10946 (let ((parse-state (save-excursion
10947 (syntax-ppss (point)))))
10948 (nth 3 parse-state)))
10949
10950 (defsubst js2-mode-inside-comment-or-string ()
10951 "Return non-nil if inside a comment or string."
10952 (or
10953 (let ((comment-start
10954 (save-excursion
10955 (goto-char (point-at-bol))
10956 (if (re-search-forward "//" (point-at-eol) t)
10957 (match-beginning 0)))))
10958 (and comment-start
10959 (<= comment-start (point))))
10960 (let ((parse-state (save-excursion
10961 (syntax-ppss (point)))))
10962 (or (nth 3 parse-state)
10963 (nth 4 parse-state)))))
10964
10965 (defsubst js2-make-magic-delimiter (delim &optional pos)
10966 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10967 Sets value of `js2-magic' text property to line number at POS."
10968 (propertize delim
10969 'js2-magic (line-number-at-pos pos)
10970 'font-lock-face 'js2-magic-paren-face))
10971
10972 (defun js2-mode-match-delimiter (open close)
10973 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10974 The rule we use, which as far as we can tell is how Eclipse works,
10975 is that we insert the match if we're not in a comment or string,
10976 and the next non-whitespace character is either punctuation or
10977 occurs on another line."
10978 (insert open)
10979 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10980 (not (js2-mode-inside-comment-or-string)))
10981 (save-excursion
10982 (insert (js2-make-magic-delimiter close)))
10983 (when js2-auto-indent-p
10984 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10985 (js2-indent-line)))))
10986
10987 (defun js2-mode-match-bracket ()
10988 "Insert matching bracket."
10989 (interactive)
10990 (js2-mode-match-delimiter "[" "]"))
10991
10992 (defun js2-mode-match-paren ()
10993 "Insert matching paren unless already inserted."
10994 (interactive)
10995 (js2-mode-match-delimiter "(" ")"))
10996
10997 (defun js2-mode-match-curly (arg)
10998 "Insert matching curly-brace.
10999 With prefix arg, no formatting or indentation will occur -- the close-brace
11000 is simply inserted directly at the point."
11001 (interactive "p")
11002 (let (try-pos)
11003 (cond
11004 (current-prefix-arg
11005 (js2-mode-match-delimiter "{" "}"))
11006 ((and js2-auto-insert-catch-block
11007 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
11008 (point-at-bol))
11009 (match-beginning 1))))
11010 (js2-insert-catch-skel try-pos))
11011 (t
11012 ;; Otherwise try to do something smarter.
11013 (insert "{")
11014 (unless (or (not (looking-at "\\s-*$"))
11015 (save-excursion
11016 (skip-chars-forward " \t\r\n")
11017 (and (looking-at "}")
11018 (js2-error-at-point)))
11019 (js2-mode-inside-comment-or-string))
11020 (undo-boundary)
11021 ;; absolutely mystifying bug: when inserting the next "\n",
11022 ;; the buffer-undo-list is given two new entries: the inserted range,
11023 ;; and the incorrect position of the point. It's recorded incorrectly
11024 ;; as being before the opening "{", not after it. But it's recorded
11025 ;; as the correct value if you're debugging `js2-mode-match-curly'
11026 ;; in edebug. I have no idea why it's doing this, but incrementing
11027 ;; the inserted position fixes the problem, so that the undo takes us
11028 ;; back to just after the user-inserted "{".
11029 (insert "\n")
11030 (ignore-errors
11031 (incf (cadr buffer-undo-list)))
11032 (js2-indent-line)
11033 (save-excursion
11034 (insert "\n}")
11035 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
11036 (js2-indent-line))))))))
11037
11038 (defun js2-insert-catch-skel (try-pos)
11039 "Complete a try/catch block after inserting a { following a try keyword.
11040 Rationale is that a try always needs a catch or a finally, and the catch is
11041 the more likely of the two.
11042
11043 TRY-POS is the buffer position of the try keyword. The open-curly should
11044 already have been inserted."
11045 (insert "{")
11046 (let ((try-col (save-excursion
11047 (goto-char try-pos)
11048 (current-column))))
11049 (insert "\n")
11050 (undo-boundary)
11051 (js2-indent-line) ;; indent the blank line where cursor will end up
11052 (save-excursion
11053 (insert "\n")
11054 (indent-to try-col)
11055 (insert "} catch (x) {\n\n")
11056 (indent-to try-col)
11057 (insert "}"))))
11058
11059 (defun js2-mode-highlight-magic-parens ()
11060 "Re-highlight magic parens after parsing nukes the 'face prop."
11061 (let ((beg (point-min))
11062 end)
11063 (while (setq beg (next-single-property-change beg 'js2-magic))
11064 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11065 (if (get-text-property beg 'js2-magic)
11066 (js2-with-unmodifying-text-property-changes
11067 (put-text-property beg (or end (1+ beg))
11068 'font-lock-face 'js2-magic-paren-face))))))
11069
11070 (defun js2-mode-mundanify-parens ()
11071 "Clear all magic parens and brackets."
11072 (let ((beg (point-min))
11073 end)
11074 (while (setq beg (next-single-property-change beg 'js2-magic))
11075 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11076 (remove-text-properties beg (or end (1+ beg))
11077 '(js2-magic face)))))
11078
11079 (defsubst js2-match-quote (quote-string)
11080 (let ((start-quote (js2-mode-inside-string)))
11081 (cond
11082 ;; inside a comment - don't do quote-matching, since we can't
11083 ;; reliably figure out if we're in a string inside the comment
11084 ((js2-comment-at-point)
11085 (insert quote-string))
11086 ((not start-quote)
11087 ;; not in string => insert matched quotes
11088 (insert quote-string)
11089 ;; exception: if we're just before a word, don't double it.
11090 (unless (looking-at "[^ \t\r\n]")
11091 (save-excursion
11092 (insert quote-string))))
11093 ((looking-at quote-string)
11094 (if (looking-back "[^\\]\\\\")
11095 (insert quote-string)
11096 (forward-char 1)))
11097 ((and js2-mode-escape-quotes
11098 (save-excursion
11099 (save-match-data
11100 (re-search-forward quote-string (point-at-eol) t))))
11101 ;; inside terminated string, escape quote (unless already escaped)
11102 (insert (if (looking-back "[^\\]\\\\")
11103 quote-string
11104 (concat "\\" quote-string))))
11105 (t
11106 (insert quote-string))))) ; else terminate the string
11107
11108 (defun js2-mode-match-single-quote ()
11109 "Insert matching single-quote."
11110 (interactive)
11111 (let ((parse-status (syntax-ppss (point))))
11112 ;; don't match inside comments, since apostrophe is more common
11113 (if (nth 4 parse-status)
11114 (insert "'")
11115 (js2-match-quote "'"))))
11116
11117 (defun js2-mode-match-double-quote ()
11118 "Insert matching double-quote."
11119 (interactive)
11120 (js2-match-quote "\""))
11121
11122 ;; Eclipse works as follows:
11123 ;; * type an open-paren and it auto-inserts close-paren
11124 ;; - auto-inserted paren gets a green bracket
11125 ;; - green bracket means typing close-paren there will skip it
11126 ;; * if you insert any text on a different line, it turns off
11127 (defun js2-mode-magic-close-paren ()
11128 "Skip over close-paren rather than inserting, where appropriate."
11129 (interactive)
11130 (let* ((here (point))
11131 (parse-status (syntax-ppss here))
11132 (open-pos (nth 1 parse-status))
11133 (close last-input-event)
11134 (open (cond
11135 ((eq close ?\))
11136 ?\()
11137 ((eq close ?\])
11138 ?\[)
11139 ((eq close ?})
11140 ?{)
11141 (t nil))))
11142 (if (and (eq (char-after) close)
11143 (eq open (char-after open-pos))
11144 (js2-same-line open-pos)
11145 (get-text-property here 'js2-magic))
11146 (progn
11147 (remove-text-properties here (1+ here) '(js2-magic face))
11148 (forward-char 1))
11149 (insert-char close 1))
11150 (blink-matching-open)))
11151
11152 (defun js2-mode-wait-for-parse (callback)
11153 "Invoke CALLBACK when parsing is finished.
11154 If parsing is already finished, calls CALLBACK immediately."
11155 (if (not js2-mode-buffer-dirty-p)
11156 (funcall callback)
11157 (push callback js2-mode-pending-parse-callbacks)
11158 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11159
11160 (defun js2-mode-parse-finished ()
11161 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11162 ;; We can't let errors propagate up, since it prevents the
11163 ;; `js2-parse' method from completing normally and returning
11164 ;; the ast, which makes things mysteriously not work right.
11165 (unwind-protect
11166 (dolist (cb js2-mode-pending-parse-callbacks)
11167 (condition-case err
11168 (funcall cb)
11169 (error (message "%s" err))))
11170 (setq js2-mode-pending-parse-callbacks nil)))
11171
11172 (defun js2-mode-flag-region (from to flag)
11173 "Hide or show text from FROM to TO, according to FLAG.
11174 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11175 Returns the created overlay if FLAG is non-nil."
11176 (remove-overlays from to 'invisible 'js2-outline)
11177 (when flag
11178 (let ((o (make-overlay from to)))
11179 (overlay-put o 'invisible 'js2-outline)
11180 (overlay-put o 'isearch-open-invisible
11181 'js2-isearch-open-invisible)
11182 o)))
11183
11184 ;; Function to be set as an outline-isearch-open-invisible' property
11185 ;; to the overlay that makes the outline invisible (see
11186 ;; `js2-mode-flag-region').
11187 (defun js2-isearch-open-invisible (overlay)
11188 ;; We rely on the fact that isearch places point on the matched text.
11189 (js2-mode-show-element))
11190
11191 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11192 "Return cons cell of bounds of folding overlay at POS.
11193 Returns nil if not found."
11194 (let ((overlays (overlays-at (or pos (point))))
11195 o)
11196 (while (and overlays
11197 (not o))
11198 (if (overlay-get (car overlays) 'invisible)
11199 (setq o (car overlays))
11200 (setq overlays (cdr overlays))))
11201 (if o
11202 (cons (overlay-start o) (overlay-end o)))))
11203
11204 (defun js2-mode-function-at-point (&optional pos)
11205 "Return the innermost function node enclosing current point.
11206 Returns nil if point is not in a function."
11207 (let ((node (js2-node-at-point pos)))
11208 (while (and node (not (js2-function-node-p node)))
11209 (setq node (js2-node-parent node)))
11210 (if (js2-function-node-p node)
11211 node)))
11212
11213 (defun js2-mode-toggle-element ()
11214 "Hide or show the foldable element at the point."
11215 (interactive)
11216 (let (comment fn pos)
11217 (save-excursion
11218 (save-match-data
11219 (cond
11220 ;; /* ... */ comment?
11221 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11222 (if (js2-mode-invisible-overlay-bounds
11223 (setq pos (+ 3 (js2-node-abs-pos comment))))
11224 (progn
11225 (goto-char pos)
11226 (js2-mode-show-element))
11227 (js2-mode-hide-element)))
11228 ;; //-comment?
11229 ((save-excursion
11230 (back-to-indentation)
11231 (looking-at js2-mode-//-comment-re))
11232 (js2-mode-toggle-//-comment))
11233 ;; function?
11234 ((setq fn (js2-mode-function-at-point))
11235 (setq pos (and (js2-function-node-body fn)
11236 (js2-node-abs-pos (js2-function-node-body fn))))
11237 (goto-char (1+ pos))
11238 (if (js2-mode-invisible-overlay-bounds)
11239 (js2-mode-show-element)
11240 (js2-mode-hide-element)))
11241 (t
11242 (message "Nothing at point to hide or show")))))))
11243
11244 (defun js2-mode-hide-element ()
11245 "Fold/hide contents of a block, showing ellipses.
11246 Show the hidden text with \\[js2-mode-show-element]."
11247 (interactive)
11248 (if js2-mode-buffer-dirty-p
11249 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11250 (let (node body beg end)
11251 (cond
11252 ((js2-mode-invisible-overlay-bounds)
11253 (message "already hidden"))
11254 (t
11255 (setq node (js2-node-at-point))
11256 (cond
11257 ((js2-block-comment-p node)
11258 (js2-mode-hide-comment node))
11259 (t
11260 (while (and node (not (js2-function-node-p node)))
11261 (setq node (js2-node-parent node)))
11262 (if (and node
11263 (setq body (js2-function-node-body node)))
11264 (progn
11265 (setq beg (js2-node-abs-pos body)
11266 end (+ beg (js2-node-len body)))
11267 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11268 (message "No collapsable element found at point"))))))))
11269
11270 (defun js2-mode-show-element ()
11271 "Show the hidden element at current point."
11272 (interactive)
11273 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11274 (if bounds
11275 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11276 (message "Nothing to un-hide"))))
11277
11278 (defun js2-mode-show-all ()
11279 "Show all of the text in the buffer."
11280 (interactive)
11281 (js2-mode-flag-region (point-min) (point-max) nil))
11282
11283 (defun js2-mode-toggle-hide-functions ()
11284 (interactive)
11285 (if js2-mode-functions-hidden
11286 (js2-mode-show-functions)
11287 (js2-mode-hide-functions)))
11288
11289 (defun js2-mode-hide-functions ()
11290 "Hides all non-nested function bodies in the buffer.
11291 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11292 to open an individual entry."
11293 (interactive)
11294 (if js2-mode-buffer-dirty-p
11295 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11296 (if (null js2-mode-ast)
11297 (message "Oops - parsing failed")
11298 (setq js2-mode-functions-hidden t)
11299 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11300
11301 (defun js2-mode-function-hider (n endp)
11302 (when (not endp)
11303 (let ((tt (js2-node-type n))
11304 body beg end)
11305 (cond
11306 ((and (= tt js2-FUNCTION)
11307 (setq body (js2-function-node-body n)))
11308 (setq beg (js2-node-abs-pos body)
11309 end (+ beg (js2-node-len body)))
11310 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11311 nil) ; don't process children of function
11312 (t
11313 t))))) ; keep processing other AST nodes
11314
11315 (defun js2-mode-show-functions ()
11316 "Un-hide any folded function bodies in the buffer."
11317 (interactive)
11318 (setq js2-mode-functions-hidden nil)
11319 (save-excursion
11320 (goto-char (point-min))
11321 (while (/= (goto-char (next-overlay-change (point)))
11322 (point-max))
11323 (dolist (o (overlays-at (point)))
11324 (when (and (overlay-get o 'invisible)
11325 (not (overlay-get o 'comment)))
11326 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11327
11328 (defun js2-mode-hide-comment (n)
11329 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11330 3 ; /**
11331 2)) ; /*
11332 (beg (+ (js2-node-abs-pos n) head))
11333 (end (- (+ beg (js2-node-len n)) head 2))
11334 (o (js2-mode-flag-region beg end 'hide)))
11335 (overlay-put o 'comment t)))
11336
11337 (defun js2-mode-toggle-hide-comments ()
11338 "Folds all block comments in the buffer.
11339 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11340 to open an individual entry."
11341 (interactive)
11342 (if js2-mode-comments-hidden
11343 (js2-mode-show-comments)
11344 (js2-mode-hide-comments)))
11345
11346 (defun js2-mode-hide-comments ()
11347 (interactive)
11348 (if js2-mode-buffer-dirty-p
11349 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11350 (if (null js2-mode-ast)
11351 (message "Oops - parsing failed")
11352 (setq js2-mode-comments-hidden t)
11353 (dolist (n (js2-ast-root-comments js2-mode-ast))
11354 (let ((format (js2-comment-node-format n)))
11355 (when (js2-block-comment-p n)
11356 (js2-mode-hide-comment n))))
11357 (js2-mode-hide-//-comments)))
11358
11359 (defsubst js2-mode-extend-//-comment (direction)
11360 "Find start or end of a block of similar //-comment lines.
11361 DIRECTION is -1 to look back, 1 to look forward.
11362 INDENT is the indentation level to match.
11363 Returns the end-of-line position of the furthest adjacent
11364 //-comment line with the same indentation as the current line.
11365 If there is no such matching line, returns current end of line."
11366 (let ((pos (point-at-eol))
11367 (indent (current-indentation)))
11368 (save-excursion
11369 (save-match-data
11370 (while (and (zerop (forward-line direction))
11371 (looking-at js2-mode-//-comment-re)
11372 (eq indent (length (match-string 1))))
11373 (setq pos (point-at-eol)))
11374 pos))))
11375
11376 (defun js2-mode-hide-//-comments ()
11377 "Fold adjacent 1-line comments, showing only snippet of first one."
11378 (let (beg end)
11379 (save-excursion
11380 (save-match-data
11381 (goto-char (point-min))
11382 (while (re-search-forward js2-mode-//-comment-re nil t)
11383 (setq beg (point)
11384 end (js2-mode-extend-//-comment 1))
11385 (unless (eq beg end)
11386 (overlay-put (js2-mode-flag-region beg end 'hide)
11387 'comment t))
11388 (goto-char end)
11389 (forward-char 1))))))
11390
11391 (defun js2-mode-toggle-//-comment ()
11392 "Fold or un-fold any multi-line //-comment at point.
11393 Caller should have determined that this line starts with a //-comment."
11394 (let* ((beg (point-at-eol))
11395 (end beg))
11396 (save-excursion
11397 (goto-char end)
11398 (if (js2-mode-invisible-overlay-bounds)
11399 (js2-mode-show-element)
11400 ;; else hide the comment
11401 (setq beg (js2-mode-extend-//-comment -1)
11402 end (js2-mode-extend-//-comment 1))
11403 (unless (eq beg end)
11404 (overlay-put (js2-mode-flag-region beg end 'hide)
11405 'comment t))))))
11406
11407 (defun js2-mode-show-comments ()
11408 "Un-hide any hidden comments, leaving other hidden elements alone."
11409 (interactive)
11410 (setq js2-mode-comments-hidden nil)
11411 (save-excursion
11412 (goto-char (point-min))
11413 (while (/= (goto-char (next-overlay-change (point)))
11414 (point-max))
11415 (dolist (o (overlays-at (point)))
11416 (when (overlay-get o 'comment)
11417 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11418
11419 (defun js2-mode-display-warnings-and-errors ()
11420 "Turn on display of warnings and errors."
11421 (interactive)
11422 (setq js2-mode-show-parse-errors t
11423 js2-mode-show-strict-warnings t)
11424 (js2-reparse 'force))
11425
11426 (defun js2-mode-hide-warnings-and-errors ()
11427 "Turn off display of warnings and errors."
11428 (interactive)
11429 (setq js2-mode-show-parse-errors nil
11430 js2-mode-show-strict-warnings nil)
11431 (js2-reparse 'force))
11432
11433 (defun js2-mode-toggle-warnings-and-errors ()
11434 "Toggle the display of warnings and errors.
11435 Some users don't like having warnings/errors reported while they type."
11436 (interactive)
11437 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11438 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11439 (if (interactive-p)
11440 (message "warnings and errors %s"
11441 (if js2-mode-show-parse-errors
11442 "enabled"
11443 "disabled")))
11444 (js2-reparse 'force))
11445
11446 (defun js2-mode-customize ()
11447 (interactive)
11448 (customize-group 'js2-mode))
11449
11450 (defun js2-mode-forward-sexp (&optional arg)
11451 "Move forward across one statement or balanced expression.
11452 With ARG, do it that many times. Negative arg -N means
11453 move backward across N balanced expressions."
11454 (interactive "p")
11455 (setq arg (or arg 1))
11456 (save-restriction
11457 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11458 (js2-reparse))
11459 (let ((scan-msg "Containing expression ends prematurely")
11460 node (start (point)) pos lp rp child)
11461 (cond
11462 ;; backward-sexp
11463 ;; could probably make this better for some cases:
11464 ;; - if in statement block (e.g. function body), go to parent
11465 ;; - infix exprs like (foo in bar) - maybe go to beginning
11466 ;; of infix expr if in the right-side expression?
11467 ((and arg (minusp arg))
11468 (dotimes (i (- arg))
11469 (js2-backward-sws)
11470 (forward-char -1) ; enter the node we backed up to
11471 (when (setq node (js2-node-at-point (point) t))
11472 (setq pos (js2-node-abs-pos node))
11473 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11474 (setq lp (car parens)
11475 rp (cdr parens))))
11476 (goto-char
11477 (or (when (and lp (> start lp))
11478 (if (and rp (<= start rp))
11479 (if (setq child (js2-node-closest-child node (point) lp t))
11480 (js2-node-abs-pos child)
11481 (goto-char start)
11482 (signal 'scan-error (list scan-msg lp lp)))
11483 lp))
11484 pos
11485 (point-min)))))
11486 (t
11487 ;; forward-sexp
11488 (js2-forward-sws)
11489 (dotimes (i arg)
11490 (js2-forward-sws)
11491 (when (setq node (js2-node-at-point (point) t))
11492 (setq pos (js2-node-abs-pos node))
11493 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11494 (setq lp (car parens)
11495 rp (cdr parens))))
11496 (goto-char
11497 (or (when (and rp (<= start rp))
11498 (if (> start lp)
11499 (if (setq child (js2-node-closest-child node (point) rp))
11500 (js2-node-abs-end child)
11501 (goto-char start)
11502 (signal 'scan-error (list scan-msg rp (1+ rp))))
11503 (1+ rp)))
11504 (and pos
11505 (+ pos
11506 (js2-node-len
11507 (if (js2-expr-stmt-node-p (js2-node-parent node))
11508 ;; stop after the semicolon
11509 (js2-node-parent node)
11510 node))))
11511 (point-max))))))))
11512
11513 (defun js2-mode-forward-sexp-parens (node abs-pos)
11514 (cond
11515 ((or (js2-array-node-p node)
11516 (js2-object-node-p node)
11517 (js2-array-comp-node-p node)
11518 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11519 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11520 ((js2-paren-expr-node-p node)
11521 (let ((lp (js2-node-lp node))
11522 (rp (js2-node-rp node)))
11523 (cons (when lp (+ abs-pos lp))
11524 (when rp (+ abs-pos rp)))))))
11525
11526 (defun js2-node-closest-child (parent point limit &optional before)
11527 (let* ((parent-pos (js2-node-abs-pos parent))
11528 (rpoint (- point parent-pos))
11529 (rlimit (- limit parent-pos))
11530 (min (min rpoint rlimit))
11531 (max (max rpoint rlimit))
11532 found)
11533 (catch 'done
11534 (js2-visit-ast
11535 parent
11536 (lambda (node end-p)
11537 (if (eq node parent)
11538 t
11539 (let ((pos (js2-node-pos node)) ;; Both relative values.
11540 (end (+ (js2-node-pos node) (js2-node-len node))))
11541 (when (and (>= pos min) (<= end max)
11542 (if before (< pos rpoint) (> end rpoint)))
11543 (setq found node))
11544 (when (> end rpoint)
11545 (throw 'done nil)))
11546 nil))))
11547 found))
11548
11549 (defun js2-next-error (&optional arg reset)
11550 "Move to next parse error.
11551 Typically invoked via \\[next-error].
11552 ARG is the number of errors, forward or backward, to move.
11553 RESET means start over from the beginning."
11554 (interactive "p")
11555 (if (or (null js2-mode-ast)
11556 (and (null (js2-ast-root-errors js2-mode-ast))
11557 (null (js2-ast-root-warnings js2-mode-ast))))
11558 (message "No errors")
11559 (when reset
11560 (goto-char (point-min)))
11561 (let* ((errs (copy-sequence
11562 (append (js2-ast-root-errors js2-mode-ast)
11563 (js2-ast-root-warnings js2-mode-ast))))
11564 (continue t)
11565 (start (point))
11566 (count (or arg 1))
11567 (backward (minusp count))
11568 (sorter (if backward '> '<))
11569 (stopper (if backward '< '>))
11570 (count (abs count))
11571 all-errs
11572 err)
11573 ;; sort by start position
11574 (setq errs (sort errs (lambda (e1 e2)
11575 (funcall sorter (second e1) (second e2))))
11576 all-errs errs)
11577 ;; find nth error with pos > start
11578 (while (and errs continue)
11579 (when (funcall stopper (cadar errs) start)
11580 (setq err (car errs))
11581 (if (zerop (decf count))
11582 (setq continue nil)))
11583 (setq errs (cdr errs)))
11584 (if err
11585 (goto-char (second err))
11586 ;; wrap around to first error
11587 (goto-char (second (car all-errs)))
11588 ;; if we were already on it, echo msg again
11589 (if (= (point) start)
11590 (js2-echo-error (point) (point)))))))
11591
11592 (defun js2-down-mouse-3 ()
11593 "Make right-click move the point to the click location.
11594 This makes right-click context menu operations a bit more intuitive.
11595 The point will not move if the region is active, however, to avoid
11596 destroying the region selection."
11597 (interactive)
11598 (when (and js2-move-point-on-right-click
11599 (not mark-active))
11600 (let ((e last-input-event))
11601 (ignore-errors
11602 (goto-char (cadadr e))))))
11603
11604 (defun js2-mode-create-imenu-index ()
11605 "Return an alist for `imenu--index-alist'."
11606 ;; This is built up in `js2-parse-record-imenu' during parsing.
11607 (when js2-mode-ast
11608 ;; if we have an ast but no recorder, they're requesting a rescan
11609 (unless js2-imenu-recorder
11610 (js2-reparse 'force))
11611 (prog1
11612 (js2-build-imenu-index)
11613 (setq js2-imenu-recorder nil
11614 js2-imenu-function-map nil))))
11615
11616 (defun js2-mode-find-tag ()
11617 "Replacement for `find-tag-default'.
11618 `find-tag-default' returns a ridiculous answer inside comments."
11619 (let (beg end)
11620 (js2-with-underscore-as-word-syntax
11621 (save-excursion
11622 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11623 (looking-back "[A-Za-z0-9_$]"))
11624 (setq beg (progn (forward-word -1) (point))
11625 end (progn (forward-word 1) (point)))
11626 (setq beg (progn (forward-word 1) (point))
11627 end (progn (forward-word -1) (point))))
11628 (replace-regexp-in-string
11629 "[\"']" ""
11630 (buffer-substring-no-properties beg end))))))
11631
11632 (defun js2-mode-forward-sibling ()
11633 "Move to the end of the sibling following point in parent.
11634 Returns non-nil if successful, or nil if there was no following sibling."
11635 (let* ((node (js2-node-at-point))
11636 (parent (js2-mode-find-enclosing-fn node))
11637 sib)
11638 (when (setq sib (js2-node-find-child-after (point) parent))
11639 (goto-char (+ (js2-node-abs-pos sib)
11640 (js2-node-len sib))))))
11641
11642 (defun js2-mode-backward-sibling ()
11643 "Move to the beginning of the sibling node preceding point in parent.
11644 Parent is defined as the enclosing script or function."
11645 (let* ((node (js2-node-at-point))
11646 (parent (js2-mode-find-enclosing-fn node))
11647 sib)
11648 (when (setq sib (js2-node-find-child-before (point) parent))
11649 (goto-char (js2-node-abs-pos sib)))))
11650
11651 (defun js2-beginning-of-defun (&optional arg)
11652 "Go to line on which current function starts, and return t on success.
11653 If we're not in a function or already at the beginning of one, go
11654 to beginning of previous script-level element.
11655 With ARG N, do that N times. If N is negative, move forward."
11656 (setq arg (or arg 1))
11657 (if (plusp arg)
11658 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11659 (when (cond
11660 ((js2-function-node-p parent)
11661 (goto-char (js2-node-abs-pos parent)))
11662 (t
11663 (js2-mode-backward-sibling)))
11664 (if (> arg 1)
11665 (js2-beginning-of-defun (1- arg))
11666 t)))
11667 (when (js2-end-of-defun)
11668 (if (>= arg -1)
11669 (js2-beginning-of-defun 1)
11670 (js2-beginning-of-defun (1+ arg))))))
11671
11672 (defun js2-end-of-defun ()
11673 "Go to the char after the last position of the current function
11674 or script-level element."
11675 (let* ((node (js2-node-at-point))
11676 (parent (or (and (js2-function-node-p node) node)
11677 (js2-node-parent-script-or-fn node)))
11678 script)
11679 (unless (js2-function-node-p parent)
11680 ;; use current script-level node, or, if none, the next one
11681 (setq script (or parent node))
11682 (setq parent (js2-node-find-child-before (point) script))
11683 (when (or (null parent)
11684 (>= (point) (+ (js2-node-abs-pos parent)
11685 (js2-node-len parent))))
11686 (setq parent (js2-node-find-child-after (point) script))))
11687 (when parent
11688 (goto-char (+ (js2-node-abs-pos parent)
11689 (js2-node-len parent))))))
11690
11691 (defun js2-mark-defun (&optional allow-extend)
11692 "Put mark at end of this function, point at beginning.
11693 The function marked is the one that contains point.
11694
11695 Interactively, if this command is repeated,
11696 or (in Transient Mark mode) if the mark is active,
11697 it marks the next defun after the ones already marked."
11698 (interactive "p")
11699 (let (extended)
11700 (when (and allow-extend
11701 (or (and (eq last-command this-command) (mark t))
11702 (and transient-mark-mode mark-active)))
11703 (let ((sib (save-excursion
11704 (goto-char (mark))
11705 (if (js2-mode-forward-sibling)
11706 (point))))
11707 node)
11708 (if sib
11709 (progn
11710 (set-mark sib)
11711 (setq extended t))
11712 ;; no more siblings - try extending to enclosing node
11713 (goto-char (mark t)))))
11714 (when (not extended)
11715 (let ((node (js2-node-at-point (point) t)) ; skip comments
11716 ast fn stmt parent beg end)
11717 (when (js2-ast-root-p node)
11718 (setq ast node
11719 node (or (js2-node-find-child-after (point) node)
11720 (js2-node-find-child-before (point) node))))
11721 ;; only mark whole buffer if we can't find any children
11722 (if (null node)
11723 (setq node ast))
11724 (if (js2-function-node-p node)
11725 (setq parent node)
11726 (setq fn (js2-mode-find-enclosing-fn node)
11727 stmt (if (or (null fn)
11728 (js2-ast-root-p fn))
11729 (js2-mode-find-first-stmt node))
11730 parent (or stmt fn)))
11731 (setq beg (js2-node-abs-pos parent)
11732 end (+ beg (js2-node-len parent)))
11733 (push-mark beg)
11734 (goto-char end)
11735 (exchange-point-and-mark)))))
11736
11737 (defun js2-narrow-to-defun ()
11738 "Narrow to the function enclosing point."
11739 (interactive)
11740 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11741 (fn (if (js2-script-node-p node)
11742 node
11743 (js2-mode-find-enclosing-fn node)))
11744 (beg (js2-node-abs-pos fn)))
11745 (unless (js2-ast-root-p fn)
11746 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11747
11748 (provide 'js2-mode)
11749
11750 ;;; js2-mode.el ends here