]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Parse default parameters
[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
679 (defconst js2-num-tokens (1+ js2-ENUM))
680
681 (defconst js2-debug-print-trees nil)
682
683 ;; Rhino accepts any string or stream as input. Emacs character
684 ;; processing works best in buffers, so we'll assume the input is a
685 ;; buffer. JavaScript strings can be copied into temp buffers before
686 ;; scanning them.
687
688 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
689 ;; They're the Emacs equivalent of instance variables, more or less.
690
691 (js2-deflocal js2-ts-dirty-line nil
692 "Token stream buffer-local variable.
693 Indicates stuff other than whitespace since start of line.")
694
695 (js2-deflocal js2-ts-regexp-flags nil
696 "Token stream buffer-local variable.")
697
698 (js2-deflocal js2-ts-string ""
699 "Token stream buffer-local variable.
700 Last string scanned.")
701
702 (js2-deflocal js2-ts-number nil
703 "Token stream buffer-local variable.
704 Last literal number scanned.")
705
706 (js2-deflocal js2-ts-hit-eof nil
707 "Token stream buffer-local variable.")
708
709 (js2-deflocal js2-ts-line-start 0
710 "Token stream buffer-local variable.")
711
712 (js2-deflocal js2-ts-lineno 1
713 "Token stream buffer-local variable.")
714
715 (js2-deflocal js2-ts-line-end-char -1
716 "Token stream buffer-local variable.")
717
718 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
719 "Token stream buffer-local variable.
720 Current scan position.")
721
722 (js2-deflocal js2-ts-is-xml-attribute nil
723 "Token stream buffer-local variable.")
724
725 (js2-deflocal js2-ts-xml-is-tag-content nil
726 "Token stream buffer-local variable.")
727
728 (js2-deflocal js2-ts-xml-open-tags-count 0
729 "Token stream buffer-local variable.")
730
731 (js2-deflocal js2-ts-string-buffer nil
732 "Token stream buffer-local variable.
733 List of chars built up while scanning various tokens.")
734
735 (js2-deflocal js2-ts-comment-type nil
736 "Token stream buffer-local variable.")
737
738 ;;; Parser variables
739
740 (js2-deflocal js2-parsed-errors nil
741 "List of errors produced during scanning/parsing.")
742
743 (js2-deflocal js2-parsed-warnings nil
744 "List of warnings produced during scanning/parsing.")
745
746 (js2-deflocal js2-recover-from-parse-errors t
747 "Non-nil to continue parsing after a syntax error.
748
749 In recovery mode, the AST will be built in full, and any error
750 nodes will be flagged with appropriate error information. If
751 this flag is nil, a syntax error will result in an error being
752 signaled.
753
754 The variable is automatically buffer-local, because different
755 modes that use the parser will need different settings.")
756
757 (js2-deflocal js2-parse-hook nil
758 "List of callbacks for receiving parsing progress.")
759
760 (defvar js2-parse-finished-hook nil
761 "List of callbacks to notify when parsing finishes.
762 Not called if parsing was interrupted.")
763
764 (js2-deflocal js2-is-eval-code nil
765 "True if we're evaluating code in a string.
766 If non-nil, the tokenizer will record the token text, and the AST nodes
767 will record their source text. Off by default for IDE modes, since the
768 text is available in the buffer.")
769
770 (defvar js2-parse-ide-mode t
771 "Non-nil if the parser is being used for `js2-mode'.
772 If non-nil, the parser will set text properties for fontification
773 and the syntax table. The value should be nil when using the
774 parser as a frontend to an interpreter or byte compiler.")
775
776 ;;; Parser instance variables (buffer-local vars for js2-parse)
777
778 (defconst js2-clear-ti-mask #xFFFF
779 "Mask to clear token information bits.")
780
781 (defconst js2-ti-after-eol (lsh 1 16)
782 "Flag: first token of the source line.")
783
784 (defconst js2-ti-check-label (lsh 1 17)
785 "Flag: indicates to check for label.")
786
787 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
788
789 (js2-deflocal js2-compiler-generate-debug-info t)
790 (js2-deflocal js2-compiler-use-dynamic-scope nil)
791 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
792 (js2-deflocal js2-compiler-xml-available t)
793 (js2-deflocal js2-compiler-optimization-level 0)
794 (js2-deflocal js2-compiler-generating-source t)
795 (js2-deflocal js2-compiler-strict-mode nil)
796 (js2-deflocal js2-compiler-report-warning-as-error nil)
797 (js2-deflocal js2-compiler-generate-observer-count nil)
798 (js2-deflocal js2-compiler-activation-names nil)
799
800 ;; SKIP: sourceURI
801
802 ;; There's a compileFunction method in Context.java - may need it.
803 (js2-deflocal js2-called-by-compile-function nil
804 "True if `js2-parse' was called by `js2-compile-function'.
805 Will only be used when we finish implementing the interpreter.")
806
807 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
808
809 (js2-deflocal js2-current-flagged-token js2-EOF)
810 (js2-deflocal js2-current-token js2-EOF)
811
812 ;; SKIP: node factory - we're going to just call functions directly,
813 ;; and eventually go to a unified AST format.
814
815 (js2-deflocal js2-nesting-of-function 0)
816
817 (js2-deflocal js2-recorded-identifiers nil
818 "Tracks identifiers found during parsing.")
819
820 (js2-deflocal js2-is-in-destructuring nil
821 "True while parsing destructuring expression.")
822
823 (defcustom js2-global-externs nil
824 "A list of any extern names you'd like to consider always declared.
825 This list is global and is used by all js2-mode files.
826 You can create buffer-local externs list using `js2-additional-externs'.
827
828 There is also a buffer-local variable `js2-default-externs',
829 which is initialized by default to include the Ecma-262 externs
830 and the standard browser externs. The three lists are all
831 checked during highlighting."
832 :type 'list
833 :group 'js2-mode)
834
835 (js2-deflocal js2-default-externs nil
836 "Default external declarations.
837
838 These are currently only used for highlighting undeclared variables,
839 which only worries about top-level (unqualified) references.
840 As js2-mode's processing improves, we will flesh out this list.
841
842 The initial value is set to `js2-ecma-262-externs', unless you
843 have set `js2-include-browser-externs', in which case the browser
844 externs are also included.
845
846 See `js2-additional-externs' for more information.")
847
848 (defcustom js2-include-browser-externs t
849 "Non-nil to include browser externs in the master externs list.
850 If you work on JavaScript files that are not intended for browsers,
851 such as Mozilla Rhino server-side JavaScript, set this to nil.
852 You can always include them on a per-file basis by calling
853 `js2-add-browser-externs' from a function on `js2-mode-hook'.
854
855 See `js2-additional-externs' for more information about externs."
856 :type 'boolean
857 :group 'js2-mode)
858
859 (defcustom js2-include-rhino-externs t
860 "Non-nil to include Mozilla Rhino externs in the master externs list.
861 See `js2-additional-externs' for more information about externs."
862 :type 'boolean
863 :group 'js2-mode)
864
865 (defcustom js2-include-gears-externs t
866 "Non-nil to include Google Gears externs in the master externs list.
867 See `js2-additional-externs' for more information about externs."
868 :type 'boolean
869 :group 'js2-mode)
870
871 (js2-deflocal js2-additional-externs nil
872 "A buffer-local list of additional external declarations.
873 It is used to decide whether variables are considered undeclared
874 for purposes of highlighting.
875
876 Each entry is a lisp string. The string should be the fully qualified
877 name of an external entity. All externs should be added to this list,
878 so that as js2-mode's processing improves it can take advantage of them.
879
880 You may want to declare your externs in three ways.
881 First, you can add externs that are valid for all your JavaScript files.
882 You should probably do this by adding them to `js2-global-externs', which
883 is a global list used for all js2-mode files.
884
885 Next, you can add a function to `js2-mode-hook' that adds additional
886 externs appropriate for the specific file, perhaps based on its path.
887 These should go in `js2-additional-externs', which is buffer-local.
888
889 Finally, you can add a function to `js2-post-parse-callbacks',
890 which is called after parsing completes, and `root' is bound to
891 the root of the parse tree. At this stage you can set up an AST
892 node visitor using `js2-visit-ast' and examine the parse tree
893 for specific import patterns that may imply the existence of
894 other externs, possibly tied to your build system. These should also
895 be added to `js2-additional-externs'.
896
897 Your post-parse callback may of course also use the simpler and
898 faster (but perhaps less robust) approach of simply scanning the
899 buffer text for your imports, using regular expressions.")
900
901 ;; SKIP: decompiler
902 ;; SKIP: encoded-source
903
904 ;;; The following variables are per-function and should be saved/restored
905 ;;; during function parsing...
906
907 (js2-deflocal js2-current-script-or-fn nil)
908 (js2-deflocal js2-current-scope nil)
909 (js2-deflocal js2-nesting-of-with 0)
910 (js2-deflocal js2-label-set nil
911 "An alist mapping label names to nodes.")
912
913 (js2-deflocal js2-loop-set nil)
914 (js2-deflocal js2-loop-and-switch-set nil)
915 (js2-deflocal js2-has-return-value nil)
916 (js2-deflocal js2-end-flags 0)
917
918 ;;; ...end of per function variables
919
920 ;; Without 2-token lookahead, labels are a problem.
921 ;; These vars store the token info of the last matched name,
922 ;; iff it wasn't the last matched token. Only valid in some contexts.
923 (defvar js2-prev-name-token-start nil)
924 (defvar js2-prev-name-token-string nil)
925
926 (defsubst js2-save-name-token-data (pos name)
927 (setq js2-prev-name-token-start pos
928 js2-prev-name-token-string name))
929
930 ;; These flags enumerate the possible ways a statement/function can
931 ;; terminate. These flags are used by endCheck() and by the Parser to
932 ;; detect inconsistent return usage.
933 ;;
934 ;; END_UNREACHED is reserved for code paths that are assumed to always be
935 ;; able to execute (example: throw, continue)
936 ;;
937 ;; END_DROPS_OFF indicates if the statement can transfer control to the
938 ;; next one. Statement such as return dont. A compound statement may have
939 ;; some branch that drops off control to the next statement.
940 ;;
941 ;; END_RETURNS indicates that the statement can return (without arguments)
942 ;; END_RETURNS_VALUE indicates that the statement can return a value.
943 ;;
944 ;; A compound statement such as
945 ;; if (condition) {
946 ;; return value;
947 ;; }
948 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
949
950 (defconst js2-end-unreached #x0)
951 (defconst js2-end-drops-off #x1)
952 (defconst js2-end-returns #x2)
953 (defconst js2-end-returns-value #x4)
954 (defconst js2-end-yields #x8)
955
956 ;; Rhino awkwardly passes a statementLabel parameter to the
957 ;; statementHelper() function, the main statement parser, which
958 ;; is then used by quite a few of the sub-parsers. We just make
959 ;; it a buffer-local variable and make sure it's cleaned up properly.
960 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
961
962 ;; Similarly, Rhino passes an inForInit boolean through about half
963 ;; the expression parsers. We use a dynamically-scoped variable,
964 ;; which makes it easier to funcall the parsers individually without
965 ;; worrying about whether they take the parameter or not.
966 (js2-deflocal js2-in-for-init nil)
967 (js2-deflocal js2-temp-name-counter 0)
968 (js2-deflocal js2-parse-stmt-count 0)
969
970 (defsubst js2-get-next-temp-name ()
971 (format "$%d" (incf js2-temp-name-counter)))
972
973 (defvar js2-parse-interruptable-p t
974 "Set this to nil to force parse to continue until finished.
975 This will mostly be useful for interpreters.")
976
977 (defvar js2-statements-per-pause 50
978 "Pause after this many statements to check for user input.
979 If user input is pending, stop the parse and discard the tree.
980 This makes for a smoother user experience for large files.
981 You may have to wait a second or two before the highlighting
982 and error-reporting appear, but you can always type ahead if
983 you wish. This appears to be more or less how Eclipse, IntelliJ
984 and other editors work.")
985
986 (js2-deflocal js2-record-comments t
987 "Instructs the scanner to record comments in `js2-scanned-comments'.")
988
989 (js2-deflocal js2-scanned-comments nil
990 "List of all comments from the current parse.")
991
992 (defcustom js2-mode-indent-inhibit-undo nil
993 "Non-nil to disable collection of Undo information when indenting lines.
994 Some users have requested this behavior. It's nil by default because
995 other Emacs modes don't work this way."
996 :type 'boolean
997 :group 'js2-mode)
998
999 (defcustom js2-mode-indent-ignore-first-tab nil
1000 "If non-nil, ignore first TAB keypress if we look indented properly.
1001 It's fairly common for users to navigate to an already-indented line
1002 and press TAB for reassurance that it's been indented. For this class
1003 of users, we want the first TAB press on a line to be ignored if the
1004 line is already indented to one of the precomputed alternatives.
1005
1006 This behavior is only partly implemented. If you TAB-indent a line,
1007 navigate to another line, and then navigate back, it fails to clear
1008 the last-indented variable, so it thinks you've already hit TAB once,
1009 and performs the indent. A full solution would involve getting on the
1010 point-motion hooks for the entire buffer. If we come across another
1011 use cases that requires watching point motion, I'll consider doing it.
1012
1013 If you set this variable to nil, then the TAB key will always change
1014 the indentation of the current line, if more than one alternative
1015 indentation spot exists."
1016 :type 'boolean
1017 :group 'js2-mode)
1018
1019 (defvar js2-indent-hook nil
1020 "A hook for user-defined indentation rules.
1021
1022 Functions on this hook should expect two arguments: (LIST INDEX)
1023 The LIST argument is the list of computed indentation points for
1024 the current line. INDEX is the list index of the indentation point
1025 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1026 indent function is not going to change the current line indentation.
1027
1028 If a hook function on this list returns a non-nil value, then
1029 `js2-bounce-indent' assumes the hook function has performed its own
1030 indentation, and will do nothing. If all hook functions on the list
1031 return nil, then `js2-bounce-indent' will use its computed indentation
1032 and reindent the line.
1033
1034 When hook functions on this hook list are called, the variable
1035 `js2-mode-ast' may or may not be set, depending on whether the
1036 parse tree is available. If the variable is nil, you can pass a
1037 callback to `js2-mode-wait-for-parse', and your callback will be
1038 called after the new parse tree is built. This can take some time
1039 in large files.")
1040
1041 (defface js2-warning-face
1042 `((((class color) (background light))
1043 (:underline "orange"))
1044 (((class color) (background dark))
1045 (:underline "orange"))
1046 (t (:underline t)))
1047 "Face for JavaScript warnings."
1048 :group 'js2-mode)
1049
1050 (defface js2-error-face
1051 `((((class color) (background light))
1052 (:foreground "red"))
1053 (((class color) (background dark))
1054 (:foreground "red"))
1055 (t (:foreground "red")))
1056 "Face for JavaScript errors."
1057 :group 'js2-mode)
1058
1059 (defface js2-jsdoc-tag-face
1060 '((t :foreground "SlateGray"))
1061 "Face used to highlight @whatever tags in jsdoc comments."
1062 :group 'js2-mode)
1063
1064 (defface js2-jsdoc-type-face
1065 '((t :foreground "SteelBlue"))
1066 "Face used to highlight {FooBar} types in jsdoc comments."
1067 :group 'js2-mode)
1068
1069 (defface js2-jsdoc-value-face
1070 '((t :foreground "PeachPuff3"))
1071 "Face used to highlight tag values in jsdoc comments."
1072 :group 'js2-mode)
1073
1074 (defface js2-function-param-face
1075 '((t :foreground "SeaGreen"))
1076 "Face used to highlight function parameters in javascript."
1077 :group 'js2-mode)
1078
1079 (defface js2-instance-member-face
1080 '((t :foreground "DarkOrchid"))
1081 "Face used to highlight instance variables in javascript.
1082 Not currently used."
1083 :group 'js2-mode)
1084
1085 (defface js2-private-member-face
1086 '((t :foreground "PeachPuff3"))
1087 "Face used to highlight calls to private methods in javascript.
1088 Not currently used."
1089 :group 'js2-mode)
1090
1091 (defface js2-private-function-call-face
1092 '((t :foreground "goldenrod"))
1093 "Face used to highlight calls to private functions in javascript.
1094 Not currently used."
1095 :group 'js2-mode)
1096
1097 (defface js2-jsdoc-html-tag-name-face
1098 (if js2-emacs22
1099 '((((class color) (min-colors 88) (background light))
1100 (:foreground "rosybrown"))
1101 (((class color) (min-colors 8) (background dark))
1102 (:foreground "yellow"))
1103 (((class color) (min-colors 8) (background light))
1104 (:foreground "magenta")))
1105 '((((type tty pc) (class color) (background light))
1106 (:foreground "magenta"))
1107 (((type tty pc) (class color) (background dark))
1108 (:foreground "yellow"))
1109 (t (:foreground "RosyBrown"))))
1110 "Face used to highlight jsdoc html tag names"
1111 :group 'js2-mode)
1112
1113 (defface js2-jsdoc-html-tag-delimiter-face
1114 (if js2-emacs22
1115 '((((class color) (min-colors 88) (background light))
1116 (:foreground "dark khaki"))
1117 (((class color) (min-colors 8) (background dark))
1118 (:foreground "green"))
1119 (((class color) (min-colors 8) (background light))
1120 (:foreground "green")))
1121 '((((type tty pc) (class color) (background light))
1122 (:foreground "green"))
1123 (((type tty pc) (class color) (background dark))
1124 (:foreground "green"))
1125 (t (:foreground "dark khaki"))))
1126 "Face used to highlight brackets in jsdoc html tags."
1127 :group 'js2-mode)
1128
1129 (defface js2-magic-paren-face
1130 '((t :underline t))
1131 "Face used to color parens that will be auto-overwritten."
1132 :group 'js2-mode)
1133
1134 (defcustom js2-post-parse-callbacks nil
1135 "A list of callback functions invoked after parsing finishes.
1136 Currently, the main use for this function is to add synthetic
1137 declarations to `js2-recorded-identifiers', which see."
1138 :type 'list
1139 :group 'js2-mode)
1140
1141 (defface js2-external-variable-face
1142 '((t :foreground "orange"))
1143 "Face used to highlight undeclared variable identifiers.
1144 An undeclared variable is any variable not declared with var or let
1145 in the current scope or any lexically enclosing scope. If you use
1146 such a variable, then you are either expecting it to originate from
1147 another file, or you've got a potential bug."
1148 :group 'js2-mode)
1149
1150 (defcustom js2-highlight-external-variables t
1151 "Non-nil to highlight undeclared variable identifiers."
1152 :type 'boolean
1153 :group 'js2-mode)
1154
1155 (defcustom js2-auto-insert-catch-block t
1156 "Non-nil to insert matching catch block on open-curly after `try'."
1157 :type 'boolean
1158 :group 'js2-mode)
1159
1160 (defvar js2-mode-map
1161 (let ((map (make-sparse-keymap))
1162 keys)
1163 (define-key map [mouse-1] #'js2-mode-show-node)
1164 (define-key map (kbd "C-m") #'js2-enter-key)
1165 (when js2-rebind-eol-bol-keys
1166 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1167 (define-key map (kbd "C-e") #'js2-end-of-line))
1168 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1169 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1170 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1171 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1172 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1173 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1174 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1175 (define-key map (kbd "C-c C-`") #'js2-next-error)
1176 ;; also define user's preference for next-error, if available
1177 (if (setq keys (where-is-internal #'next-error))
1178 (define-key map (car keys) #'js2-next-error))
1179 (define-key map (or (car (where-is-internal #'mark-defun))
1180 (kbd "M-C-h"))
1181 #'js2-mark-defun)
1182 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1183 (kbd "C-x nd"))
1184 #'js2-narrow-to-defun)
1185 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1186 (when js2-auto-indent-p
1187 (mapc (lambda (key)
1188 (define-key map key #'js2-insert-and-indent))
1189 js2-electric-keys))
1190 (when js2-bounce-indent-p
1191 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1192
1193 (define-key map [menu-bar javascript]
1194 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1195
1196 (define-key map [menu-bar javascript customize-js2-mode]
1197 '(menu-item "Customize js2-mode" js2-mode-customize
1198 :help "Customize the behavior of this mode"))
1199
1200 (define-key map [menu-bar javascript js2-force-refresh]
1201 '(menu-item "Force buffer refresh" js2-mode-reset
1202 :help "Re-parse the buffer from scratch"))
1203
1204 (define-key map [menu-bar javascript separator-2]
1205 '("--"))
1206
1207 (define-key map [menu-bar javascript next-error]
1208 '(menu-item "Next warning or error" js2-next-error
1209 :enabled (and js2-mode-ast
1210 (or (js2-ast-root-errors js2-mode-ast)
1211 (js2-ast-root-warnings js2-mode-ast)))
1212 :help "Move to next warning or error"))
1213
1214 (define-key map [menu-bar javascript display-errors]
1215 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1216 :visible (not js2-mode-show-parse-errors)
1217 :help "Turn on display of warnings and errors"))
1218
1219 (define-key map [menu-bar javascript hide-errors]
1220 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1221 :visible js2-mode-show-parse-errors
1222 :help "Turn off display of warnings and errors"))
1223
1224 (define-key map [menu-bar javascript separator-1]
1225 '("--"))
1226
1227 (define-key map [menu-bar javascript js2-toggle-function]
1228 '(menu-item "Show/collapse element" js2-mode-toggle-element
1229 :help "Hide or show function body or comment"))
1230
1231 (define-key map [menu-bar javascript show-comments]
1232 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1233 :visible js2-mode-comments-hidden
1234 :help "Expand all hidden block comments"))
1235
1236 (define-key map [menu-bar javascript hide-comments]
1237 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1238 :visible (not js2-mode-comments-hidden)
1239 :help "Show block comments as /*...*/"))
1240
1241 (define-key map [menu-bar javascript show-all-functions]
1242 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1243 :visible js2-mode-functions-hidden
1244 :help "Expand all hidden function bodies"))
1245
1246 (define-key map [menu-bar javascript hide-all-functions]
1247 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1248 :visible (not js2-mode-functions-hidden)
1249 :help "Show {...} for all top-level function bodies"))
1250
1251 map)
1252 "Keymap used in `js2-mode' buffers.")
1253
1254 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1255
1256 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1257 "Matches a //-comment line. Must be first non-whitespace on line.
1258 First match-group is the leading whitespace.")
1259
1260 (defvar js2-mode-hook nil)
1261
1262 (js2-deflocal js2-mode-ast nil "Private variable.")
1263 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1264 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1265 (js2-deflocal js2-mode-parsing nil "Private variable.")
1266 (js2-deflocal js2-mode-node-overlay nil)
1267
1268 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1269 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1270
1271 (js2-deflocal js2-mode-fontifications nil "Private variable")
1272 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1273 (js2-deflocal js2-imenu-recorder nil "Private variable")
1274 (js2-deflocal js2-imenu-function-map nil "Private variable")
1275
1276 (defvar js2-paragraph-start
1277 "\\(@[a-zA-Z]+\\>\\|$\\)")
1278
1279 ;; Note that we also set a 'c-in-sws text property in html comments,
1280 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1281 (defvar js2-syntactic-ws-start
1282 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1283
1284 (defvar js2-syntactic-ws-end
1285 "\\s \\|[\n\r/]\\|\\s!")
1286
1287 (defvar js2-syntactic-eol
1288 (concat "\\s *\\(/\\*[^*\n\r]*"
1289 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1290 "\\*+/\\s *\\)*"
1291 "\\(//\\|/\\*[^*\n\r]*"
1292 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1293 "\\|\\\\$\\|$\\)")
1294 "Copied from `java-mode'. Needed for some cc-engine functions.")
1295
1296 (defvar js2-comment-prefix-regexp
1297 "//+\\|\\**")
1298
1299 (defvar js2-comment-start-skip
1300 "\\(//+\\|/\\*+\\)\\s *")
1301
1302 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1303 "Non-nil to emit status messages during parsing.")
1304
1305 (defvar js2-mode-functions-hidden nil "private variable")
1306 (defvar js2-mode-comments-hidden nil "private variable")
1307
1308 (defvar js2-mode-syntax-table
1309 (let ((table (make-syntax-table)))
1310 (c-populate-syntax-table table)
1311 table)
1312 "Syntax table used in js2-mode buffers.")
1313
1314 (defvar js2-mode-abbrev-table nil
1315 "Abbrev table in use in `js2-mode' buffers.")
1316 (define-abbrev-table 'js2-mode-abbrev-table ())
1317
1318 (defvar js2-mode-pending-parse-callbacks nil
1319 "List of functions waiting to be notified that parse is finished.")
1320
1321 (defvar js2-mode-last-indented-line -1)
1322
1323 ;;; Localizable error and warning messages
1324
1325 ;; Messages are copied from Rhino's Messages.properties.
1326 ;; Many of the Java-specific messages have been elided.
1327 ;; Add any js2-specific ones at the end, so we can keep
1328 ;; this file synced with changes to Rhino's.
1329
1330 (defvar js2-message-table
1331 (make-hash-table :test 'equal :size 250)
1332 "Contains localized messages for js2-mode.")
1333
1334 ;; TODO(stevey): construct this table at compile-time.
1335 (defmacro js2-msg (key &rest strings)
1336 `(puthash ,key (funcall #'concat ,@strings)
1337 js2-message-table))
1338
1339 (defun js2-get-msg (msg-key)
1340 "Look up a localized message.
1341 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1342 the correct number of ARGS must be provided."
1343 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1344 (args (if (listp msg-key) (cdr msg-key)))
1345 (msg (gethash key js2-message-table)))
1346 (if msg
1347 (apply #'format msg args)
1348 key))) ; default to showing the key
1349
1350 (js2-msg "msg.dup.parms"
1351 "Duplicate parameter name '%s'.")
1352
1353 (js2-msg "msg.too.big.jump"
1354 "Program too complex: jump offset too big.")
1355
1356 (js2-msg "msg.too.big.index"
1357 "Program too complex: internal index exceeds 64K limit.")
1358
1359 (js2-msg "msg.while.compiling.fn"
1360 "Encountered code generation error while compiling function '%s': %s")
1361
1362 (js2-msg "msg.while.compiling.script"
1363 "Encountered code generation error while compiling script: %s")
1364
1365 ;; Context
1366 (js2-msg "msg.ctor.not.found"
1367 "Constructor for '%s' not found.")
1368
1369 (js2-msg "msg.not.ctor"
1370 "'%s' is not a constructor.")
1371
1372 ;; FunctionObject
1373 (js2-msg "msg.varargs.ctor"
1374 "Method or constructor '%s' must be static "
1375 "with the signature (Context cx, Object[] args, "
1376 "Function ctorObj, boolean inNewExpr) "
1377 "to define a variable arguments constructor.")
1378
1379 (js2-msg "msg.varargs.fun"
1380 "Method '%s' must be static with the signature "
1381 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1382 "to define a variable arguments function.")
1383
1384 (js2-msg "msg.incompat.call"
1385 "Method '%s' called on incompatible object.")
1386
1387 (js2-msg "msg.bad.parms"
1388 "Unsupported parameter type '%s' in method '%s'.")
1389
1390 (js2-msg "msg.bad.method.return"
1391 "Unsupported return type '%s' in method '%s'.")
1392
1393 (js2-msg "msg.bad.ctor.return"
1394 "Construction of objects of type '%s' is not supported.")
1395
1396 (js2-msg "msg.no.overload"
1397 "Method '%s' occurs multiple times in class '%s'.")
1398
1399 (js2-msg "msg.method.not.found"
1400 "Method '%s' not found in '%s'.")
1401
1402 ;; IRFactory
1403
1404 (js2-msg "msg.bad.for.in.lhs"
1405 "Invalid left-hand side of for..in loop.")
1406
1407 (js2-msg "msg.mult.index"
1408 "Only one variable allowed in for..in loop.")
1409
1410 (js2-msg "msg.bad.for.in.destruct"
1411 "Left hand side of for..in loop must be an array of "
1412 "length 2 to accept key/value pair.")
1413
1414 (js2-msg "msg.cant.convert"
1415 "Can't convert to type '%s'.")
1416
1417 (js2-msg "msg.bad.assign.left"
1418 "Invalid assignment left-hand side.")
1419
1420 (js2-msg "msg.bad.decr"
1421 "Invalid decerement operand.")
1422
1423 (js2-msg "msg.bad.incr"
1424 "Invalid increment operand.")
1425
1426 (js2-msg "msg.bad.yield"
1427 "yield must be in a function.")
1428
1429 (js2-msg "msg.yield.parenthesized"
1430 "yield expression must be parenthesized.")
1431
1432 ;; NativeGlobal
1433 (js2-msg "msg.cant.call.indirect"
1434 "Function '%s' must be called directly, and not by way of a "
1435 "function of another name.")
1436
1437 (js2-msg "msg.eval.nonstring"
1438 "Calling eval() with anything other than a primitive "
1439 "string value will simply return the value. "
1440 "Is this what you intended?")
1441
1442 (js2-msg "msg.eval.nonstring.strict"
1443 "Calling eval() with anything other than a primitive "
1444 "string value is not allowed in strict mode.")
1445
1446 (js2-msg "msg.bad.destruct.op"
1447 "Invalid destructuring assignment operator")
1448
1449 ;; NativeCall
1450 (js2-msg "msg.only.from.new"
1451 "'%s' may only be invoked from a `new' expression.")
1452
1453 (js2-msg "msg.deprec.ctor"
1454 "The '%s' constructor is deprecated.")
1455
1456 ;; NativeFunction
1457 (js2-msg "msg.no.function.ref.found"
1458 "no source found to decompile function reference %s")
1459
1460 (js2-msg "msg.arg.isnt.array"
1461 "second argument to Function.prototype.apply must be an array")
1462
1463 ;; NativeGlobal
1464 (js2-msg "msg.bad.esc.mask"
1465 "invalid string escape mask")
1466
1467 ;; NativeRegExp
1468 (js2-msg "msg.bad.quant"
1469 "Invalid quantifier %s")
1470
1471 (js2-msg "msg.overlarge.backref"
1472 "Overly large back reference %s")
1473
1474 (js2-msg "msg.overlarge.min"
1475 "Overly large minimum %s")
1476
1477 (js2-msg "msg.overlarge.max"
1478 "Overly large maximum %s")
1479
1480 (js2-msg "msg.zero.quant"
1481 "Zero quantifier %s")
1482
1483 (js2-msg "msg.max.lt.min"
1484 "Maximum %s less than minimum")
1485
1486 (js2-msg "msg.unterm.quant"
1487 "Unterminated quantifier %s")
1488
1489 (js2-msg "msg.unterm.paren"
1490 "Unterminated parenthetical %s")
1491
1492 (js2-msg "msg.unterm.class"
1493 "Unterminated character class %s")
1494
1495 (js2-msg "msg.bad.range"
1496 "Invalid range in character class.")
1497
1498 (js2-msg "msg.trail.backslash"
1499 "Trailing \\ in regular expression.")
1500
1501 (js2-msg "msg.re.unmatched.right.paren"
1502 "unmatched ) in regular expression.")
1503
1504 (js2-msg "msg.no.regexp"
1505 "Regular expressions are not available.")
1506
1507 (js2-msg "msg.bad.backref"
1508 "back-reference exceeds number of capturing parentheses.")
1509
1510 (js2-msg "msg.bad.regexp.compile"
1511 "Only one argument may be specified if the first "
1512 "argument to RegExp.prototype.compile is a RegExp object.")
1513
1514 ;; Parser
1515 (js2-msg "msg.got.syntax.errors"
1516 "Compilation produced %s syntax errors.")
1517
1518 (js2-msg "msg.var.redecl"
1519 "TypeError: redeclaration of var %s.")
1520
1521 (js2-msg "msg.const.redecl"
1522 "TypeError: redeclaration of const %s.")
1523
1524 (js2-msg "msg.let.redecl"
1525 "TypeError: redeclaration of variable %s.")
1526
1527 (js2-msg "msg.parm.redecl"
1528 "TypeError: redeclaration of formal parameter %s.")
1529
1530 (js2-msg "msg.fn.redecl"
1531 "TypeError: redeclaration of function %s.")
1532
1533 (js2-msg "msg.let.decl.not.in.block"
1534 "SyntaxError: let declaration not directly within block")
1535
1536 ;; NodeTransformer
1537 (js2-msg "msg.dup.label"
1538 "duplicated label")
1539
1540 (js2-msg "msg.undef.label"
1541 "undefined label")
1542
1543 (js2-msg "msg.bad.break"
1544 "unlabelled break must be inside loop or switch")
1545
1546 (js2-msg "msg.continue.outside"
1547 "continue must be inside loop")
1548
1549 (js2-msg "msg.continue.nonloop"
1550 "continue can only use labels of iteration statements")
1551
1552 (js2-msg "msg.bad.throw.eol"
1553 "Line terminator is not allowed between the throw "
1554 "keyword and throw expression.")
1555
1556 (js2-msg "msg.no.paren.parms"
1557 "missing ( before function parameters.")
1558
1559 (js2-msg "msg.no.parm"
1560 "missing formal parameter")
1561
1562 (js2-msg "msg.no.paren.after.parms"
1563 "missing ) after formal parameters")
1564
1565 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1566 "parameter without default follows parameter with default")
1567
1568 (js2-msg "msg.no.brace.body"
1569 "missing '{' before function body")
1570
1571 (js2-msg "msg.no.brace.after.body"
1572 "missing } after function body")
1573
1574 (js2-msg "msg.no.paren.cond"
1575 "missing ( before condition")
1576
1577 (js2-msg "msg.no.paren.after.cond"
1578 "missing ) after condition")
1579
1580 (js2-msg "msg.no.semi.stmt"
1581 "missing ; before statement")
1582
1583 (js2-msg "msg.missing.semi"
1584 "missing ; after statement")
1585
1586 (js2-msg "msg.no.name.after.dot"
1587 "missing name after . operator")
1588
1589 (js2-msg "msg.no.name.after.coloncolon"
1590 "missing name after :: operator")
1591
1592 (js2-msg "msg.no.name.after.dotdot"
1593 "missing name after .. operator")
1594
1595 (js2-msg "msg.no.name.after.xmlAttr"
1596 "missing name after .@")
1597
1598 (js2-msg "msg.no.bracket.index"
1599 "missing ] in index expression")
1600
1601 (js2-msg "msg.no.paren.switch"
1602 "missing ( before switch expression")
1603
1604 (js2-msg "msg.no.paren.after.switch"
1605 "missing ) after switch expression")
1606
1607 (js2-msg "msg.no.brace.switch"
1608 "missing '{' before switch body")
1609
1610 (js2-msg "msg.bad.switch"
1611 "invalid switch statement")
1612
1613 (js2-msg "msg.no.colon.case"
1614 "missing : after case expression")
1615
1616 (js2-msg "msg.double.switch.default"
1617 "double default label in the switch statement")
1618
1619 (js2-msg "msg.no.while.do"
1620 "missing while after do-loop body")
1621
1622 (js2-msg "msg.no.paren.for"
1623 "missing ( after for")
1624
1625 (js2-msg "msg.no.semi.for"
1626 "missing ; after for-loop initializer")
1627
1628 (js2-msg "msg.no.semi.for.cond"
1629 "missing ; after for-loop condition")
1630
1631 (js2-msg "msg.in.after.for.name"
1632 "missing in or of after for")
1633
1634 (js2-msg "msg.no.paren.for.ctrl"
1635 "missing ) after for-loop control")
1636
1637 (js2-msg "msg.no.paren.with"
1638 "missing ( before with-statement object")
1639
1640 (js2-msg "msg.no.paren.after.with"
1641 "missing ) after with-statement object")
1642
1643 (js2-msg "msg.no.paren.after.let"
1644 "missing ( after let")
1645
1646 (js2-msg "msg.no.paren.let"
1647 "missing ) after variable list")
1648
1649 (js2-msg "msg.no.curly.let"
1650 "missing } after let statement")
1651
1652 (js2-msg "msg.bad.return"
1653 "invalid return")
1654
1655 (js2-msg "msg.no.brace.block"
1656 "missing } in compound statement")
1657
1658 (js2-msg "msg.bad.label"
1659 "invalid label")
1660
1661 (js2-msg "msg.bad.var"
1662 "missing variable name")
1663
1664 (js2-msg "msg.bad.var.init"
1665 "invalid variable initialization")
1666
1667 (js2-msg "msg.no.colon.cond"
1668 "missing : in conditional expression")
1669
1670 (js2-msg "msg.no.paren.arg"
1671 "missing ) after argument list")
1672
1673 (js2-msg "msg.no.bracket.arg"
1674 "missing ] after element list")
1675
1676 (js2-msg "msg.bad.prop"
1677 "invalid property id")
1678
1679 (js2-msg "msg.no.colon.prop"
1680 "missing : after property id")
1681
1682 (js2-msg "msg.no.brace.prop"
1683 "missing } after property list")
1684
1685 (js2-msg "msg.no.paren"
1686 "missing ) in parenthetical")
1687
1688 (js2-msg "msg.reserved.id"
1689 "identifier is a reserved word")
1690
1691 (js2-msg "msg.no.paren.catch"
1692 "missing ( before catch-block condition")
1693
1694 (js2-msg "msg.bad.catchcond"
1695 "invalid catch block condition")
1696
1697 (js2-msg "msg.catch.unreachable"
1698 "any catch clauses following an unqualified catch are unreachable")
1699
1700 (js2-msg "msg.no.brace.try"
1701 "missing '{' before try block")
1702
1703 (js2-msg "msg.no.brace.catchblock"
1704 "missing '{' before catch-block body")
1705
1706 (js2-msg "msg.try.no.catchfinally"
1707 "'try' without 'catch' or 'finally'")
1708
1709 (js2-msg "msg.no.return.value"
1710 "function %s does not always return a value")
1711
1712 (js2-msg "msg.anon.no.return.value"
1713 "anonymous function does not always return a value")
1714
1715 (js2-msg "msg.return.inconsistent"
1716 "return statement is inconsistent with previous usage")
1717
1718 (js2-msg "msg.generator.returns"
1719 "TypeError: generator function '%s' returns a value")
1720
1721 (js2-msg "msg.anon.generator.returns"
1722 "TypeError: anonymous generator function returns a value")
1723
1724 (js2-msg "msg.syntax"
1725 "syntax error")
1726
1727 (js2-msg "msg.unexpected.eof"
1728 "Unexpected end of file")
1729
1730 (js2-msg "msg.XML.bad.form"
1731 "illegally formed XML syntax")
1732
1733 (js2-msg "msg.XML.not.available"
1734 "XML runtime not available")
1735
1736 (js2-msg "msg.too.deep.parser.recursion"
1737 "Too deep recursion while parsing")
1738
1739 (js2-msg "msg.no.side.effects"
1740 "Code has no side effects")
1741
1742 (js2-msg "msg.extra.trailing.comma"
1743 "Trailing comma is not legal in an ECMA-262 object initializer")
1744
1745 (js2-msg "msg.array.trailing.comma"
1746 "Trailing comma yields different behavior across browsers")
1747
1748 (js2-msg "msg.equal.as.assign"
1749 (concat "Test for equality (==) mistyped as assignment (=)?"
1750 " (parenthesize to suppress warning)"))
1751
1752 (js2-msg "msg.var.hides.arg"
1753 "Variable %s hides argument")
1754
1755 (js2-msg "msg.destruct.assign.no.init"
1756 "Missing = in destructuring declaration")
1757
1758 ;; ScriptRuntime
1759 (js2-msg "msg.no.properties"
1760 "%s has no properties.")
1761
1762 (js2-msg "msg.invalid.iterator"
1763 "Invalid iterator value")
1764
1765 (js2-msg "msg.iterator.primitive"
1766 "__iterator__ returned a primitive value")
1767
1768 (js2-msg "msg.assn.create.strict"
1769 "Assignment to undeclared variable %s")
1770
1771 (js2-msg "msg.ref.undefined.prop"
1772 "Reference to undefined property '%s'")
1773
1774 (js2-msg "msg.prop.not.found"
1775 "Property %s not found.")
1776
1777 (js2-msg "msg.invalid.type"
1778 "Invalid JavaScript value of type %s")
1779
1780 (js2-msg "msg.primitive.expected"
1781 "Primitive type expected (had %s instead)")
1782
1783 (js2-msg "msg.namespace.expected"
1784 "Namespace object expected to left of :: (found %s instead)")
1785
1786 (js2-msg "msg.null.to.object"
1787 "Cannot convert null to an object.")
1788
1789 (js2-msg "msg.undef.to.object"
1790 "Cannot convert undefined to an object.")
1791
1792 (js2-msg "msg.cyclic.value"
1793 "Cyclic %s value not allowed.")
1794
1795 (js2-msg "msg.is.not.defined"
1796 "'%s' is not defined.")
1797
1798 (js2-msg "msg.undef.prop.read"
1799 "Cannot read property '%s' from %s")
1800
1801 (js2-msg "msg.undef.prop.write"
1802 "Cannot set property '%s' of %s to '%s'")
1803
1804 (js2-msg "msg.undef.prop.delete"
1805 "Cannot delete property '%s' of %s")
1806
1807 (js2-msg "msg.undef.method.call"
1808 "Cannot call method '%s' of %s")
1809
1810 (js2-msg "msg.undef.with"
1811 "Cannot apply 'with' to %s")
1812
1813 (js2-msg "msg.isnt.function"
1814 "%s is not a function, it is %s.")
1815
1816 (js2-msg "msg.isnt.function.in"
1817 "Cannot call property %s in object %s. "
1818 "It is not a function, it is '%s'.")
1819
1820 (js2-msg "msg.function.not.found"
1821 "Cannot find function %s.")
1822
1823 (js2-msg "msg.function.not.found.in"
1824 "Cannot find function %s in object %s.")
1825
1826 (js2-msg "msg.isnt.xml.object"
1827 "%s is not an xml object.")
1828
1829 (js2-msg "msg.no.ref.to.get"
1830 "%s is not a reference to read reference value.")
1831
1832 (js2-msg "msg.no.ref.to.set"
1833 "%s is not a reference to set reference value to %s.")
1834
1835 (js2-msg "msg.no.ref.from.function"
1836 "Function %s can not be used as the left-hand "
1837 "side of assignment or as an operand of ++ or -- operator.")
1838
1839 (js2-msg "msg.bad.default.value"
1840 "Object's getDefaultValue() method returned an object.")
1841
1842 (js2-msg "msg.instanceof.not.object"
1843 "Can't use instanceof on a non-object.")
1844
1845 (js2-msg "msg.instanceof.bad.prototype"
1846 "'prototype' property of %s is not an object.")
1847
1848 (js2-msg "msg.bad.radix"
1849 "illegal radix %s.")
1850
1851 ;; ScriptableObject
1852 (js2-msg "msg.default.value"
1853 "Cannot find default value for object.")
1854
1855 (js2-msg "msg.zero.arg.ctor"
1856 "Cannot load class '%s' which has no zero-parameter constructor.")
1857
1858 (js2-msg "msg.ctor.multiple.parms"
1859 "Can't define constructor or class %s since more than "
1860 "one constructor has multiple parameters.")
1861
1862 (js2-msg "msg.extend.scriptable"
1863 "%s must extend ScriptableObject in order to define property %s.")
1864
1865 (js2-msg "msg.bad.getter.parms"
1866 "In order to define a property, getter %s must have zero "
1867 "parameters or a single ScriptableObject parameter.")
1868
1869 (js2-msg "msg.obj.getter.parms"
1870 "Expected static or delegated getter %s to take "
1871 "a ScriptableObject parameter.")
1872
1873 (js2-msg "msg.getter.static"
1874 "Getter and setter must both be static or neither be static.")
1875
1876 (js2-msg "msg.setter.return"
1877 "Setter must have void return type: %s")
1878
1879 (js2-msg "msg.setter2.parms"
1880 "Two-parameter setter must take a ScriptableObject as "
1881 "its first parameter.")
1882
1883 (js2-msg "msg.setter1.parms"
1884 "Expected single parameter setter for %s")
1885
1886 (js2-msg "msg.setter2.expected"
1887 "Expected static or delegated setter %s to take two parameters.")
1888
1889 (js2-msg "msg.setter.parms"
1890 "Expected either one or two parameters for setter.")
1891
1892 (js2-msg "msg.setter.bad.type"
1893 "Unsupported parameter type '%s' in setter '%s'.")
1894
1895 (js2-msg "msg.add.sealed"
1896 "Cannot add a property to a sealed object: %s.")
1897
1898 (js2-msg "msg.remove.sealed"
1899 "Cannot remove a property from a sealed object: %s.")
1900
1901 (js2-msg "msg.modify.sealed"
1902 "Cannot modify a property of a sealed object: %s.")
1903
1904 (js2-msg "msg.modify.readonly"
1905 "Cannot modify readonly property: %s.")
1906
1907 ;; TokenStream
1908 (js2-msg "msg.missing.exponent"
1909 "missing exponent")
1910
1911 (js2-msg "msg.caught.nfe"
1912 "number format error")
1913
1914 (js2-msg "msg.unterminated.string.lit"
1915 "unterminated string literal")
1916
1917 (js2-msg "msg.unterminated.comment"
1918 "unterminated comment")
1919
1920 (js2-msg "msg.unterminated.re.lit"
1921 "unterminated regular expression literal")
1922
1923 (js2-msg "msg.invalid.re.flag"
1924 "invalid flag after regular expression")
1925
1926 (js2-msg "msg.no.re.input.for"
1927 "no input for %s")
1928
1929 (js2-msg "msg.illegal.character"
1930 "illegal character")
1931
1932 (js2-msg "msg.invalid.escape"
1933 "invalid Unicode escape sequence")
1934
1935 (js2-msg "msg.bad.namespace"
1936 "not a valid default namespace statement. "
1937 "Syntax is: default xml namespace = EXPRESSION;")
1938
1939 ;; TokensStream warnings
1940 (js2-msg "msg.bad.octal.literal"
1941 "illegal octal literal digit %s; "
1942 "interpreting it as a decimal digit")
1943
1944 (js2-msg "msg.reserved.keyword"
1945 "illegal usage of future reserved keyword %s; "
1946 "interpreting it as ordinary identifier")
1947
1948 (js2-msg "msg.script.is.not.constructor"
1949 "Script objects are not constructors.")
1950
1951 ;; Arrays
1952 (js2-msg "msg.arraylength.bad"
1953 "Inappropriate array length.")
1954
1955 ;; Arrays
1956 (js2-msg "msg.arraylength.too.big"
1957 "Array length %s exceeds supported capacity limit.")
1958
1959 ;; URI
1960 (js2-msg "msg.bad.uri"
1961 "Malformed URI sequence.")
1962
1963 ;; Number
1964 (js2-msg "msg.bad.precision"
1965 "Precision %s out of range.")
1966
1967 ;; NativeGenerator
1968 (js2-msg "msg.send.newborn"
1969 "Attempt to send value to newborn generator")
1970
1971 (js2-msg "msg.already.exec.gen"
1972 "Already executing generator")
1973
1974 (js2-msg "msg.StopIteration.invalid"
1975 "StopIteration may not be changed to an arbitrary object.")
1976
1977 ;; Interpreter
1978 (js2-msg "msg.yield.closing"
1979 "Yield from closing generator")
1980
1981 ;;; Utilities
1982
1983 (defun js2-delete-if (predicate list)
1984 "Remove all items satisfying PREDICATE in LIST."
1985 (loop for item in list
1986 if (not (funcall predicate item))
1987 collect item))
1988
1989 (defun js2-position (element list)
1990 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1991 Returns nil if element is not found in the list."
1992 (let ((count 0)
1993 found)
1994 (while (and list (not found))
1995 (if (eq element (car list))
1996 (setq found t)
1997 (setq count (1+ count)
1998 list (cdr list))))
1999 (if found count)))
2000
2001 (defun js2-find-if (predicate list)
2002 "Find first item satisfying PREDICATE in LIST."
2003 (let (result)
2004 (while (and list (not result))
2005 (if (funcall predicate (car list))
2006 (setq result (car list)))
2007 (setq list (cdr list)))
2008 result))
2009
2010 (defmacro js2-time (form)
2011 "Evaluate FORM, discard result, and return elapsed time in sec"
2012 (declare (debug t))
2013 (let ((beg (make-symbol "--js2-time-beg--"))
2014 (delta (make-symbol "--js2-time-end--")))
2015 `(let ((,beg (current-time))
2016 ,delta)
2017 ,form
2018 (/ (truncate (* (- (float-time (current-time))
2019 (float-time ,beg))
2020 10000))
2021 10000.0))))
2022
2023 (defsubst js2-same-line (pos)
2024 "Return t if POS is on the same line as current point."
2025 (and (>= pos (point-at-bol))
2026 (<= pos (point-at-eol))))
2027
2028 (defsubst js2-same-line-2 (p1 p2)
2029 "Return t if p1 is on the same line as p2."
2030 (save-excursion
2031 (goto-char p1)
2032 (js2-same-line p2)))
2033
2034 (defun js2-code-bug ()
2035 "Signal an error when we encounter an unexpected code path."
2036 (error "failed assertion"))
2037
2038 (defsubst js2-record-text-property (beg end prop value)
2039 "Record a text property to set when parsing finishes."
2040 (push (list beg end prop value) js2-mode-deferred-properties))
2041
2042 ;; I'd like to associate errors with nodes, but for now the
2043 ;; easiest thing to do is get the context info from the last token.
2044 (defsubst js2-record-parse-error (msg &optional arg pos len)
2045 (push (list (list msg arg)
2046 (or pos js2-token-beg)
2047 (or len (- js2-token-end js2-token-beg)))
2048 js2-parsed-errors))
2049
2050 (defsubst js2-report-error (msg &optional msg-arg pos len)
2051 "Signal a syntax error or record a parse error."
2052 (if js2-recover-from-parse-errors
2053 (js2-record-parse-error msg msg-arg pos len)
2054 (signal 'js2-syntax-error
2055 (list msg
2056 js2-ts-lineno
2057 (save-excursion
2058 (goto-char js2-ts-cursor)
2059 (current-column))
2060 js2-ts-hit-eof))))
2061
2062 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2063 (if js2-compiler-report-warning-as-error
2064 (js2-report-error msg msg-arg pos len)
2065 (push (list (list msg msg-arg)
2066 (or pos js2-token-beg)
2067 (or len (- js2-token-end js2-token-beg)))
2068 js2-parsed-warnings)))
2069
2070 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2071 (if js2-compiler-strict-mode
2072 (js2-report-warning msg-id msg-arg beg
2073 (and beg end (- end beg)))))
2074
2075 (put 'js2-syntax-error 'error-conditions
2076 '(error syntax-error js2-syntax-error))
2077 (put 'js2-syntax-error 'error-message "Syntax error")
2078
2079 (put 'js2-parse-error 'error-conditions
2080 '(error parse-error js2-parse-error))
2081 (put 'js2-parse-error 'error-message "Parse error")
2082
2083 (defmacro js2-clear-flag (flags flag)
2084 `(setq ,flags (logand ,flags (lognot ,flag))))
2085
2086 (defmacro js2-set-flag (flags flag)
2087 "Logical-or FLAG into FLAGS."
2088 `(setq ,flags (logior ,flags ,flag)))
2089
2090 (defsubst js2-flag-set-p (flags flag)
2091 (/= 0 (logand flags flag)))
2092
2093 (defsubst js2-flag-not-set-p (flags flag)
2094 (zerop (logand flags flag)))
2095
2096 ;; Stolen shamelessly from James Clark's nxml-mode.
2097 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2098 "Evaluate BODY without any text property changes modifying the buffer.
2099 Any text properties changes happen as usual but the changes are not treated as
2100 modifications to the buffer."
2101 (declare (indent 0) (debug t))
2102 (let ((modified (make-symbol "modified")))
2103 `(let ((,modified (buffer-modified-p))
2104 (inhibit-read-only t)
2105 (inhibit-modification-hooks t)
2106 (buffer-undo-list t)
2107 (deactivate-mark nil)
2108 ;; Apparently these avoid file locking problems.
2109 (buffer-file-name nil)
2110 (buffer-file-truename nil))
2111 (unwind-protect
2112 (progn ,@body)
2113 (unless ,modified
2114 (restore-buffer-modified-p nil))))))
2115
2116 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2117 "Evaluate BODY with the _ character set to be word-syntax."
2118 (declare (indent 0) (debug t))
2119 (let ((old-syntax (make-symbol "old-syntax")))
2120 `(let ((,old-syntax (string (char-syntax ?_))))
2121 (unwind-protect
2122 (progn
2123 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2124 ,@body)
2125 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2126
2127 (defsubst js2-char-uppercase-p (c)
2128 "Return t if C is an uppercase character.
2129 Handles unicode and latin chars properly."
2130 (/= c (downcase c)))
2131
2132 (defsubst js2-char-lowercase-p (c)
2133 "Return t if C is an uppercase character.
2134 Handles unicode and latin chars properly."
2135 (/= c (upcase c)))
2136
2137 ;;; AST struct and function definitions
2138
2139 ;; flags for ast node property 'member-type (used for e4x operators)
2140 (defvar js2-property-flag #x1 "property access: element is valid name")
2141 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2142 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2143
2144 (defsubst js2-relpos (pos anchor)
2145 "Convert POS to be relative to ANCHOR.
2146 If POS is nil, returns nil."
2147 (and pos (- pos anchor)))
2148
2149 (defsubst js2-make-pad (indent)
2150 (if (zerop indent)
2151 ""
2152 (make-string (* indent js2-basic-offset) ? )))
2153
2154 (defsubst js2-visit-ast (node callback)
2155 "Visit every node in ast NODE with visitor CALLBACK.
2156
2157 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2158 called twice: once to visit the node, and again after all the node's
2159 children have been processed. The END-P argument is nil on the first
2160 call and non-nil on the second call. The return value of the callback
2161 affects the traversal: if non-nil, the children of NODE are processed.
2162 If the callback returns nil, or if the node has no children, then the
2163 callback is called immediately with a non-nil END-P argument.
2164
2165 The node traversal is approximately lexical-order, although there
2166 are currently no guarantees around this."
2167 (if node
2168 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2169 ;; visit the node
2170 (when (funcall callback node nil)
2171 ;; visit the kids
2172 (cond
2173 ((eq vfunc 'js2-visit-none)
2174 nil) ; don't even bother calling it
2175 ;; Each AST node type has to define a `js2-visitor' function
2176 ;; that takes a node and a callback, and calls `js2-visit-ast'
2177 ;; on each child of the node.
2178 (vfunc
2179 (funcall vfunc node callback))
2180 (t
2181 (error "%s does not define a visitor-traversal function"
2182 (aref node 0)))))
2183 ;; call the end-visit
2184 (funcall callback node t))))
2185
2186 (defstruct (js2-node
2187 (:constructor nil)) ; abstract
2188 "Base AST node type."
2189 (type -1) ; token type
2190 (pos -1) ; start position of this AST node in parsed input
2191 (len 1) ; num characters spanned by the node
2192 props ; optional node property list (an alist)
2193 parent) ; link to parent node; null for root
2194
2195 (defsubst js2-node-get-prop (node prop &optional default)
2196 (or (cadr (assoc prop (js2-node-props node))) default))
2197
2198 (defsubst js2-node-set-prop (node prop value)
2199 (setf (js2-node-props node)
2200 (cons (list prop value) (js2-node-props node))))
2201
2202 (defsubst js2-fixup-starts (n nodes)
2203 "Adjust the start positions of NODES to be relative to N.
2204 Any node in the list may be nil, for convenience."
2205 (dolist (node nodes)
2206 (when node
2207 (setf (js2-node-pos node) (- (js2-node-pos node)
2208 (js2-node-pos n))))))
2209
2210 (defsubst js2-node-add-children (parent &rest nodes)
2211 "Set parent node of NODES to PARENT, and return PARENT.
2212 Does nothing if we're not recording parent links.
2213 If any given node in NODES is nil, doesn't record that link."
2214 (js2-fixup-starts parent nodes)
2215 (dolist (node nodes)
2216 (and node
2217 (setf (js2-node-parent node) parent))))
2218
2219 ;; Non-recursive since it's called a frightening number of times.
2220 (defsubst js2-node-abs-pos (n)
2221 (let ((pos (js2-node-pos n)))
2222 (while (setq n (js2-node-parent n))
2223 (setq pos (+ pos (js2-node-pos n))))
2224 pos))
2225
2226 (defsubst js2-node-abs-end (n)
2227 "Return absolute buffer position of end of N."
2228 (+ (js2-node-abs-pos n) (js2-node-len n)))
2229
2230 ;; It's important to make sure block nodes have a lisp list for the
2231 ;; child nodes, to limit printing recursion depth in an AST that
2232 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2233 ;; a sufficiently large vector tree.
2234
2235 (defstruct (js2-block-node
2236 (:include js2-node)
2237 (:constructor nil)
2238 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2239 (pos js2-token-beg)
2240 len
2241 props
2242 kids)))
2243 "A block of statements."
2244 kids) ; a lisp list of the child statement nodes
2245
2246 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2247 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2248
2249 (defsubst js2-visit-block (ast callback)
2250 "Visit the `js2-block-node' children of AST."
2251 (dolist (kid (js2-block-node-kids ast))
2252 (js2-visit-ast kid callback)))
2253
2254 (defun js2-print-block (n i)
2255 (let ((pad (js2-make-pad i)))
2256 (insert pad "{\n")
2257 (dolist (kid (js2-block-node-kids n))
2258 (js2-print-ast kid (1+ i)))
2259 (insert pad "}")))
2260
2261 (defstruct (js2-scope
2262 (:include js2-block-node)
2263 (:constructor nil)
2264 (:constructor make-js2-scope (&key (type js2-BLOCK)
2265 (pos js2-token-beg)
2266 len
2267 kids)))
2268 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2269 ;; I don't have one of those handy, so I'll use an alist for now.
2270 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2271 ;; and is much lighter-weight to construct (both CPU and mem).
2272 ;; The keys are interned strings (symbols) for faster lookup.
2273 ;; Should switch to hybrid alist/hashtable eventually.
2274 symbol-table ; an alist of (symbol . js2-symbol)
2275 parent-scope ; a `js2-scope'
2276 top) ; top-level `js2-scope' (script/function)
2277
2278 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2279 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2280
2281 (defun js2-scope-set-parent-scope (scope parent)
2282 (setf (js2-scope-parent-scope scope) parent
2283 (js2-scope-top scope) (if (null parent)
2284 scope
2285 (js2-scope-top parent))))
2286
2287 (defun js2-node-get-enclosing-scope (node)
2288 "Return the innermost `js2-scope' node surrounding NODE.
2289 Returns nil if there is no enclosing scope node."
2290 (let ((parent (js2-node-parent node)))
2291 (while (not (js2-scope-p parent))
2292 (setq parent (js2-node-parent parent)))
2293 parent))
2294
2295 (defun js2-get-defining-scope (scope name)
2296 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2297 Returns `js2-scope' in which NAME is defined, or nil if not found."
2298 (let ((sym (if (symbolp name)
2299 name
2300 (intern name)))
2301 table
2302 result
2303 (continue t))
2304 (while (and scope continue)
2305 (if (and (setq table (js2-scope-symbol-table scope))
2306 (assq sym table))
2307 (setq continue nil
2308 result scope)
2309 (setq scope (js2-scope-parent-scope scope))))
2310 result))
2311
2312 (defsubst js2-scope-get-symbol (scope name)
2313 "Return symbol table entry for NAME in SCOPE.
2314 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2315 (and (js2-scope-symbol-table scope)
2316 (cdr (assq (if (symbolp name)
2317 name
2318 (intern name))
2319 (js2-scope-symbol-table scope)))))
2320
2321 (defsubst js2-scope-put-symbol (scope name symbol)
2322 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2323 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2324 (let* ((table (js2-scope-symbol-table scope))
2325 (sym (if (symbolp name) name (intern name)))
2326 (entry (assq sym table)))
2327 (if entry
2328 (setcdr entry symbol)
2329 (push (cons sym symbol)
2330 (js2-scope-symbol-table scope)))))
2331
2332 (defstruct (js2-symbol
2333 (:constructor nil)
2334 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2335 "A symbol table entry."
2336 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2337 ;; js2-LET, or js2-CONST
2338 decl-type
2339 name ; string
2340 ast-node) ; a `js2-node'
2341
2342 (defstruct (js2-error-node
2343 (:include js2-node)
2344 (:constructor nil) ; silence emacs21 byte-compiler
2345 (:constructor make-js2-error-node (&key (type js2-ERROR)
2346 (pos js2-token-beg)
2347 len)))
2348 "AST node representing a parse error.")
2349
2350 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2351 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2352
2353 (defstruct (js2-script-node
2354 (:include js2-scope)
2355 (:constructor nil)
2356 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2357 (pos js2-token-beg)
2358 len
2359 var-decls
2360 fun-decls)))
2361 functions ; lisp list of nested functions
2362 regexps ; lisp list of (string . flags)
2363 symbols ; alist (every symbol gets unique index)
2364 (param-count 0)
2365 var-names ; vector of string names
2366 consts ; bool-vector matching var-decls
2367 (temp-number 0)) ; for generating temp variables
2368
2369 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2370 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2371
2372 (defun js2-print-script (node indent)
2373 (dolist (kid (js2-block-node-kids node))
2374 (js2-print-ast kid indent)))
2375
2376 (defstruct (js2-ast-root
2377 (:include js2-script-node)
2378 (:constructor nil)
2379 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2380 (pos js2-token-beg)
2381 len
2382 buffer)))
2383 "The root node of a js2 AST."
2384 buffer ; the source buffer from which the code was parsed
2385 comments ; a lisp list of comments, ordered by start position
2386 errors ; a lisp list of errors found during parsing
2387 warnings ; a lisp list of warnings found during parsing
2388 node-count) ; number of nodes in the tree, including the root
2389
2390 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2391 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2392
2393 (defun js2-visit-ast-root (ast callback)
2394 (dolist (kid (js2-ast-root-kids ast))
2395 (js2-visit-ast kid callback))
2396 (dolist (comment (js2-ast-root-comments ast))
2397 (js2-visit-ast comment callback)))
2398
2399 (defstruct (js2-comment-node
2400 (:include js2-node)
2401 (:constructor nil)
2402 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2403 (pos js2-token-beg)
2404 len
2405 (format js2-ts-comment-type))))
2406 format) ; 'line, 'block, 'jsdoc or 'html
2407
2408 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2409 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2410
2411 (defun js2-print-comment (n i)
2412 ;; We really ought to link end-of-line comments to their nodes.
2413 ;; Or maybe we could add a new comment type, 'endline.
2414 (insert (js2-make-pad i)
2415 (js2-node-string n)))
2416
2417 (defstruct (js2-expr-stmt-node
2418 (:include js2-node)
2419 (:constructor nil)
2420 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2421 (pos js2-ts-cursor)
2422 len
2423 expr)))
2424 "An expression statement."
2425 expr)
2426
2427 (defsubst js2-expr-stmt-node-set-has-result (node)
2428 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2429 (setf (js2-node-type node) js2-EXPR_RESULT))
2430
2431 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2432 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2433
2434 (defun js2-visit-expr-stmt-node (n v)
2435 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2436
2437 (defun js2-print-expr-stmt-node (n indent)
2438 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2439 (insert ";\n"))
2440
2441 (defstruct (js2-loop-node
2442 (:include js2-scope)
2443 (:constructor nil))
2444 "Abstract supertype of loop nodes."
2445 body ; a `js2-block-node'
2446 lp ; position of left-paren, nil if omitted
2447 rp) ; position of right-paren, nil if omitted
2448
2449 (defstruct (js2-do-node
2450 (:include js2-loop-node)
2451 (:constructor nil)
2452 (:constructor make-js2-do-node (&key (type js2-DO)
2453 (pos js2-token-beg)
2454 len
2455 body
2456 condition
2457 while-pos
2458 lp
2459 rp)))
2460 "AST node for do-loop."
2461 condition ; while (expression)
2462 while-pos) ; buffer position of 'while' keyword
2463
2464 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2465 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2466
2467 (defun js2-visit-do-node (n v)
2468 (js2-visit-ast (js2-do-node-body n) v)
2469 (js2-visit-ast (js2-do-node-condition n) v))
2470
2471 (defun js2-print-do-node (n i)
2472 (let ((pad (js2-make-pad i)))
2473 (insert pad "do {\n")
2474 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2475 (js2-print-ast kid (1+ i)))
2476 (insert pad "} while (")
2477 (js2-print-ast (js2-do-node-condition n) 0)
2478 (insert ");\n")))
2479
2480 (defstruct (js2-while-node
2481 (:include js2-loop-node)
2482 (:constructor nil)
2483 (:constructor make-js2-while-node (&key (type js2-WHILE)
2484 (pos js2-token-beg)
2485 len
2486 body
2487 condition
2488 lp
2489 rp)))
2490 "AST node for while-loop."
2491 condition) ; while-condition
2492
2493 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2494 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2495
2496 (defun js2-visit-while-node (n v)
2497 (js2-visit-ast (js2-while-node-condition n) v)
2498 (js2-visit-ast (js2-while-node-body n) v))
2499
2500 (defun js2-print-while-node (n i)
2501 (let ((pad (js2-make-pad i)))
2502 (insert pad "while (")
2503 (js2-print-ast (js2-while-node-condition n) 0)
2504 (insert ") {\n")
2505 (js2-print-body (js2-while-node-body n) (1+ i))
2506 (insert pad "}\n")))
2507
2508 (defstruct (js2-for-node
2509 (:include js2-loop-node)
2510 (:constructor nil)
2511 (:constructor make-js2-for-node (&key (type js2-FOR)
2512 (pos js2-ts-cursor)
2513 len
2514 body
2515 init
2516 condition
2517 update
2518 lp
2519 rp)))
2520 "AST node for a C-style for-loop."
2521 init ; initialization expression
2522 condition ; loop condition
2523 update) ; update clause
2524
2525 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2526 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2527
2528 (defun js2-visit-for-node (n v)
2529 (js2-visit-ast (js2-for-node-init n) v)
2530 (js2-visit-ast (js2-for-node-condition n) v)
2531 (js2-visit-ast (js2-for-node-update n) v)
2532 (js2-visit-ast (js2-for-node-body n) v))
2533
2534 (defun js2-print-for-node (n i)
2535 (let ((pad (js2-make-pad i)))
2536 (insert pad "for (")
2537 (js2-print-ast (js2-for-node-init n) 0)
2538 (insert "; ")
2539 (js2-print-ast (js2-for-node-condition n) 0)
2540 (insert "; ")
2541 (js2-print-ast (js2-for-node-update n) 0)
2542 (insert ") {\n")
2543 (js2-print-body (js2-for-node-body n) (1+ i))
2544 (insert pad "}\n")))
2545
2546 (defstruct (js2-for-in-node
2547 (:include js2-loop-node)
2548 (:constructor nil)
2549 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2550 (pos js2-ts-cursor)
2551 len
2552 body
2553 iterator
2554 object
2555 in-pos
2556 each-pos
2557 foreach-p
2558 forof-p
2559 lp
2560 rp)))
2561 "AST node for a for..in loop."
2562 iterator ; [var] foo in ...
2563 object ; object over which we're iterating
2564 in-pos ; buffer position of 'in' keyword
2565 each-pos ; buffer position of 'each' keyword, if foreach-p
2566 foreach-p ; t if it's a for-each loop
2567 forof-p) ; t if it's a for-of loop
2568
2569 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2570 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2571
2572 (defun js2-visit-for-in-node (n v)
2573 (js2-visit-ast (js2-for-in-node-iterator n) v)
2574 (js2-visit-ast (js2-for-in-node-object n) v)
2575 (js2-visit-ast (js2-for-in-node-body n) v))
2576
2577 (defun js2-print-for-in-node (n i)
2578 (let ((pad (js2-make-pad i))
2579 (foreach (js2-for-in-node-foreach-p n))
2580 (forof (js2-for-in-node-forof-p n)))
2581 (insert pad "for ")
2582 (if foreach
2583 (insert "each "))
2584 (insert "(")
2585 (js2-print-ast (js2-for-in-node-iterator n) 0)
2586 (if forof
2587 (insert " of ")
2588 (insert " in "))
2589 (js2-print-ast (js2-for-in-node-object n) 0)
2590 (insert ") {\n")
2591 (js2-print-body (js2-for-in-node-body n) (1+ i))
2592 (insert pad "}\n")))
2593
2594 (defstruct (js2-return-node
2595 (:include js2-node)
2596 (:constructor nil)
2597 (:constructor make-js2-return-node (&key (type js2-RETURN)
2598 (pos js2-ts-cursor)
2599 len
2600 retval)))
2601 "AST node for a return statement."
2602 retval) ; expression to return, or 'undefined
2603
2604 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2605 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2606
2607 (defun js2-visit-return-node (n v)
2608 (js2-visit-ast (js2-return-node-retval n) v))
2609
2610 (defun js2-print-return-node (n i)
2611 (insert (js2-make-pad i) "return")
2612 (when (js2-return-node-retval n)
2613 (insert " ")
2614 (js2-print-ast (js2-return-node-retval n) 0))
2615 (insert ";\n"))
2616
2617 (defstruct (js2-if-node
2618 (:include js2-node)
2619 (:constructor nil)
2620 (:constructor make-js2-if-node (&key (type js2-IF)
2621 (pos js2-ts-cursor)
2622 len
2623 condition
2624 then-part
2625 else-pos
2626 else-part
2627 lp
2628 rp)))
2629 "AST node for an if-statement."
2630 condition ; expression
2631 then-part ; statement or block
2632 else-pos ; optional buffer position of 'else' keyword
2633 else-part ; optional statement or block
2634 lp ; position of left-paren, nil if omitted
2635 rp) ; position of right-paren, nil if omitted
2636
2637 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2638 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2639
2640 (defun js2-visit-if-node (n v)
2641 (js2-visit-ast (js2-if-node-condition n) v)
2642 (js2-visit-ast (js2-if-node-then-part n) v)
2643 (js2-visit-ast (js2-if-node-else-part n) v))
2644
2645 (defun js2-print-if-node (n i)
2646 (let ((pad (js2-make-pad i))
2647 (then-part (js2-if-node-then-part n))
2648 (else-part (js2-if-node-else-part n)))
2649 (insert pad "if (")
2650 (js2-print-ast (js2-if-node-condition n) 0)
2651 (insert ") {\n")
2652 (js2-print-body then-part (1+ i))
2653 (insert pad "}")
2654 (cond
2655 ((not else-part)
2656 (insert "\n"))
2657 ((js2-if-node-p else-part)
2658 (insert " else ")
2659 (js2-print-body else-part i))
2660 (t
2661 (insert " else {\n")
2662 (js2-print-body else-part (1+ i))
2663 (insert pad "}\n")))))
2664
2665 (defstruct (js2-try-node
2666 (:include js2-node)
2667 (:constructor nil)
2668 (:constructor make-js2-try-node (&key (type js2-TRY)
2669 (pos js2-ts-cursor)
2670 len
2671 try-block
2672 catch-clauses
2673 finally-block)))
2674 "AST node for a try-statement."
2675 try-block
2676 catch-clauses ; a lisp list of `js2-catch-node'
2677 finally-block) ; a `js2-finally-node'
2678
2679 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2680 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2681
2682 (defun js2-visit-try-node (n v)
2683 (js2-visit-ast (js2-try-node-try-block n) v)
2684 (dolist (clause (js2-try-node-catch-clauses n))
2685 (js2-visit-ast clause v))
2686 (js2-visit-ast (js2-try-node-finally-block n) v))
2687
2688 (defun js2-print-try-node (n i)
2689 (let ((pad (js2-make-pad i))
2690 (catches (js2-try-node-catch-clauses n))
2691 (finally (js2-try-node-finally-block n)))
2692 (insert pad "try {\n")
2693 (js2-print-body (js2-try-node-try-block n) (1+ i))
2694 (insert pad "}")
2695 (when catches
2696 (dolist (catch catches)
2697 (js2-print-ast catch i)))
2698 (if finally
2699 (js2-print-ast finally i)
2700 (insert "\n"))))
2701
2702 (defstruct (js2-catch-node
2703 (:include js2-node)
2704 (:constructor nil)
2705 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2706 (pos js2-ts-cursor)
2707 len
2708 param
2709 guard-kwd
2710 guard-expr
2711 block
2712 lp
2713 rp)))
2714 "AST node for a catch clause."
2715 param ; destructuring form or simple name node
2716 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2717 guard-expr ; catch condition, a `js2-node'
2718 block ; statements, a `js2-block-node'
2719 lp ; buffer position of left-paren, nil if omitted
2720 rp) ; buffer position of right-paren, nil if omitted
2721
2722 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2723 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2724
2725 (defun js2-visit-catch-node (n v)
2726 (js2-visit-ast (js2-catch-node-param n) v)
2727 (when (js2-catch-node-guard-kwd n)
2728 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2729 (js2-visit-ast (js2-catch-node-block n) v))
2730
2731 (defun js2-print-catch-node (n i)
2732 (let ((pad (js2-make-pad i))
2733 (guard-kwd (js2-catch-node-guard-kwd n))
2734 (guard-expr (js2-catch-node-guard-expr n)))
2735 (insert " catch (")
2736 (js2-print-ast (js2-catch-node-param n) 0)
2737 (when guard-kwd
2738 (insert " if ")
2739 (js2-print-ast guard-expr 0))
2740 (insert ") {\n")
2741 (js2-print-body (js2-catch-node-block n) (1+ i))
2742 (insert pad "}")))
2743
2744 (defstruct (js2-finally-node
2745 (:include js2-node)
2746 (:constructor nil)
2747 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2748 (pos js2-ts-cursor)
2749 len
2750 body)))
2751 "AST node for a finally clause."
2752 body) ; a `js2-node', often but not always a block node
2753
2754 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2755 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2756
2757 (defun js2-visit-finally-node (n v)
2758 (js2-visit-ast (js2-finally-node-body n) v))
2759
2760 (defun js2-print-finally-node (n i)
2761 (let ((pad (js2-make-pad i)))
2762 (insert " finally {\n")
2763 (js2-print-body (js2-finally-node-body n) (1+ i))
2764 (insert pad "}\n")))
2765
2766 (defstruct (js2-switch-node
2767 (:include js2-node)
2768 (:constructor nil)
2769 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2770 (pos js2-ts-cursor)
2771 len
2772 discriminant
2773 cases
2774 lp
2775 rp)))
2776 "AST node for a switch statement."
2777 discriminant ; a `js2-node' (switch expression)
2778 cases ; a lisp list of `js2-case-node'
2779 lp ; position of open-paren for discriminant, nil if omitted
2780 rp) ; position of close-paren for discriminant, nil if omitted
2781
2782 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2783 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2784
2785 (defun js2-visit-switch-node (n v)
2786 (js2-visit-ast (js2-switch-node-discriminant n) v)
2787 (dolist (c (js2-switch-node-cases n))
2788 (js2-visit-ast c v)))
2789
2790 (defun js2-print-switch-node (n i)
2791 (let ((pad (js2-make-pad i))
2792 (cases (js2-switch-node-cases n)))
2793 (insert pad "switch (")
2794 (js2-print-ast (js2-switch-node-discriminant n) 0)
2795 (insert ") {\n")
2796 (dolist (case cases)
2797 (js2-print-ast case i))
2798 (insert pad "}\n")))
2799
2800 (defstruct (js2-case-node
2801 (:include js2-block-node)
2802 (:constructor nil)
2803 (:constructor make-js2-case-node (&key (type js2-CASE)
2804 (pos js2-ts-cursor)
2805 len
2806 kids
2807 expr)))
2808 "AST node for a case clause of a switch statement."
2809 expr) ; the case expression (nil for default)
2810
2811 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2812 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2813
2814 (defun js2-visit-case-node (n v)
2815 (js2-visit-ast (js2-case-node-expr n) v)
2816 (js2-visit-block n v))
2817
2818 (defun js2-print-case-node (n i)
2819 (let ((pad (js2-make-pad i))
2820 (expr (js2-case-node-expr n)))
2821 (insert pad)
2822 (if (null expr)
2823 (insert "default:\n")
2824 (insert "case ")
2825 (js2-print-ast expr 0)
2826 (insert ":\n"))
2827 (dolist (kid (js2-case-node-kids n))
2828 (js2-print-ast kid (1+ i)))))
2829
2830 (defstruct (js2-throw-node
2831 (:include js2-node)
2832 (:constructor nil)
2833 (:constructor make-js2-throw-node (&key (type js2-THROW)
2834 (pos js2-ts-cursor)
2835 len
2836 expr)))
2837 "AST node for a throw statement."
2838 expr) ; the expression to throw
2839
2840 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2841 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2842
2843 (defun js2-visit-throw-node (n v)
2844 (js2-visit-ast (js2-throw-node-expr n) v))
2845
2846 (defun js2-print-throw-node (n i)
2847 (insert (js2-make-pad i) "throw ")
2848 (js2-print-ast (js2-throw-node-expr n) 0)
2849 (insert ";\n"))
2850
2851 (defstruct (js2-with-node
2852 (:include js2-node)
2853 (:constructor nil)
2854 (:constructor make-js2-with-node (&key (type js2-WITH)
2855 (pos js2-ts-cursor)
2856 len
2857 object
2858 body
2859 lp
2860 rp)))
2861 "AST node for a with-statement."
2862 object
2863 body
2864 lp ; buffer position of left-paren around object, nil if omitted
2865 rp) ; buffer position of right-paren around object, nil if omitted
2866
2867 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2868 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2869
2870 (defun js2-visit-with-node (n v)
2871 (js2-visit-ast (js2-with-node-object n) v)
2872 (js2-visit-ast (js2-with-node-body n) v))
2873
2874 (defun js2-print-with-node (n i)
2875 (let ((pad (js2-make-pad i)))
2876 (insert pad "with (")
2877 (js2-print-ast (js2-with-node-object n) 0)
2878 (insert ") {\n")
2879 (js2-print-body (js2-with-node-body n) (1+ i))
2880 (insert pad "}\n")))
2881
2882 (defstruct (js2-label-node
2883 (:include js2-node)
2884 (:constructor nil)
2885 (:constructor make-js2-label-node (&key (type js2-LABEL)
2886 (pos js2-ts-cursor)
2887 len
2888 name)))
2889 "AST node for a statement label or case label."
2890 name ; a string
2891 loop) ; for validating and code-generating continue-to-label
2892
2893 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2894 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2895
2896 (defun js2-print-label (n i)
2897 (insert (js2-make-pad i)
2898 (js2-label-node-name n)
2899 ":\n"))
2900
2901 (defstruct (js2-labeled-stmt-node
2902 (:include js2-node)
2903 (:constructor nil)
2904 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2905 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2906 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2907 (pos js2-ts-cursor)
2908 len
2909 labels
2910 stmt)))
2911 "AST node for a statement with one or more labels.
2912 Multiple labels for a statement are collapsed into the labels field."
2913 labels ; lisp list of `js2-label-node'
2914 stmt) ; the statement these labels are for
2915
2916 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2917 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2918
2919 (defun js2-get-label-by-name (lbl-stmt name)
2920 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2921 Returns nil if no such label is in the list."
2922 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2923 result)
2924 (while (and label-list (not result))
2925 (if (string= (js2-label-node-name (car label-list)) name)
2926 (setq result (car label-list))
2927 (setq label-list (cdr label-list))))
2928 result))
2929
2930 (defun js2-visit-labeled-stmt (n v)
2931 (dolist (label (js2-labeled-stmt-node-labels n))
2932 (js2-visit-ast label v))
2933 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2934
2935 (defun js2-print-labeled-stmt (n i)
2936 (dolist (label (js2-labeled-stmt-node-labels n))
2937 (js2-print-ast label i))
2938 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2939
2940 (defun js2-labeled-stmt-node-contains (node label)
2941 "Return t if NODE contains LABEL in its label set.
2942 NODE is a `js2-labels-node'. LABEL is an identifier."
2943 (loop for nl in (js2-labeled-stmt-node-labels node)
2944 if (string= label (js2-label-node-name nl))
2945 return t
2946 finally return nil))
2947
2948 (defsubst js2-labeled-stmt-node-add-label (node label)
2949 "Add a `js2-label-node' to the label set for this statement."
2950 (setf (js2-labeled-stmt-node-labels node)
2951 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2952
2953 (defstruct (js2-jump-node
2954 (:include js2-node)
2955 (:constructor nil))
2956 "Abstract supertype of break and continue nodes."
2957 label ; `js2-name-node' for location of label identifier, if present
2958 target) ; target js2-labels-node or loop/switch statement
2959
2960 (defun js2-visit-jump-node (n v)
2961 (js2-visit-ast (js2-jump-node-label n) v))
2962
2963 (defstruct (js2-break-node
2964 (:include js2-jump-node)
2965 (:constructor nil)
2966 (:constructor make-js2-break-node (&key (type js2-BREAK)
2967 (pos js2-ts-cursor)
2968 len
2969 label
2970 target)))
2971 "AST node for a break statement.
2972 The label field is a `js2-name-node', possibly nil, for the named label
2973 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2974 is the target of the break - a label node or enclosing loop/switch statement.")
2975
2976 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2977 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2978
2979 (defun js2-print-break-node (n i)
2980 (insert (js2-make-pad i) "break")
2981 (when (js2-break-node-label n)
2982 (insert " ")
2983 (js2-print-ast (js2-break-node-label n) 0))
2984 (insert ";\n"))
2985
2986 (defstruct (js2-continue-node
2987 (:include js2-jump-node)
2988 (:constructor nil)
2989 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2990 (pos js2-ts-cursor)
2991 len
2992 label
2993 target)))
2994 "AST node for a continue statement.
2995 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2996 It is nil if continue specifies no label. The target field is the jump target:
2997 a `js2-label-node' or the innermost enclosing loop.")
2998
2999 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3000 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3001
3002 (defun js2-print-continue-node (n i)
3003 (insert (js2-make-pad i) "continue")
3004 (when (js2-continue-node-label n)
3005 (insert " ")
3006 (js2-print-ast (js2-continue-node-label n) 0))
3007 (insert ";\n"))
3008
3009 (defstruct (js2-function-node
3010 (:include js2-script-node)
3011 (:constructor nil)
3012 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3013 (pos js2-ts-cursor)
3014 len
3015 (ftype 'FUNCTION)
3016 (form 'FUNCTION_STATEMENT)
3017 (name "")
3018 params
3019 body
3020 lp
3021 rp)))
3022 "AST node for a function declaration.
3023 The `params' field is a lisp list of nodes. Each node is either a simple
3024 `js2-name-node', or if it's a destructuring-assignment parameter, a
3025 `js2-array-node' or `js2-object-node'."
3026 ftype ; FUNCTION, GETTER or SETTER
3027 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3028 name ; function name (a `js2-name-node', or nil if anonymous)
3029 params ; a lisp list of destructuring forms or simple name nodes
3030 body ; a `js2-block-node' or expression node (1.8 only)
3031 lp ; position of arg-list open-paren, or nil if omitted
3032 rp ; position of arg-list close-paren, or nil if omitted
3033 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3034 needs-activation ; t if we need an activation object for this frame
3035 is-generator ; t if this function contains a yield
3036 member-expr) ; nonstandard Ecma extension from Rhino
3037
3038 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3039 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3040
3041 (defun js2-visit-function-node (n v)
3042 (js2-visit-ast (js2-function-node-name n) v)
3043 (dolist (p (js2-function-node-params n))
3044 (js2-visit-ast p v))
3045 (js2-visit-ast (js2-function-node-body n) v))
3046
3047 (defun js2-print-function-node (n i)
3048 (let ((pad (js2-make-pad i))
3049 (getter (js2-node-get-prop n 'GETTER_SETTER))
3050 (name (js2-function-node-name n))
3051 (params (js2-function-node-params n))
3052 (body (js2-function-node-body n))
3053 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3054 (unless getter
3055 (insert pad "function"))
3056 (when name
3057 (insert " ")
3058 (js2-print-ast name 0))
3059 (insert "(")
3060 (loop with len = (length params)
3061 for param in params
3062 for count from 1
3063 do
3064 (js2-print-ast param 0)
3065 (if (< count len)
3066 (insert ", ")))
3067 (insert ") {")
3068 (unless expr
3069 (insert "\n"))
3070 ;; TODO: fix this to be smarter about indenting, etc.
3071 (js2-print-body body (1+ i))
3072 (insert pad "}")
3073 (unless expr
3074 (insert "\n"))))
3075
3076 (defsubst js2-function-name (node)
3077 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3078 (and (js2-function-node-name node)
3079 (js2-name-node-name (js2-function-node-name node))))
3080
3081 ;; Having this be an expression node makes it more flexible.
3082 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3083 ;; that work better if you assume it's an expression. Whenever we have
3084 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3085 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3086 (defstruct (js2-var-decl-node
3087 (:include js2-node)
3088 (:constructor nil)
3089 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3090 (pos js2-token-beg)
3091 len
3092 kids
3093 decl-type)))
3094 "AST node for a variable declaration list (VAR, CONST or LET).
3095 The node bounds differ depending on the declaration type. For VAR or
3096 CONST declarations, the bounds include the var/const keyword. For LET
3097 declarations, the node begins at the position of the first child."
3098 kids ; a lisp list of `js2-var-init-node' structs.
3099 decl-type) ; js2-VAR, js2-CONST or js2-LET
3100
3101 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3102 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3103
3104 (defun js2-visit-var-decl (n v)
3105 (dolist (kid (js2-var-decl-node-kids n))
3106 (js2-visit-ast kid v)))
3107
3108 (defun js2-print-var-decl (n i)
3109 (let ((pad (js2-make-pad i))
3110 (tt (js2-var-decl-node-decl-type n)))
3111 (insert pad)
3112 (insert (cond
3113 ((= tt js2-VAR) "var ")
3114 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3115 ((= tt js2-CONST) "const ")
3116 (t
3117 (error "malformed var-decl node"))))
3118 (loop with kids = (js2-var-decl-node-kids n)
3119 with len = (length kids)
3120 for kid in kids
3121 for count from 1
3122 do
3123 (js2-print-ast kid 0)
3124 (if (< count len)
3125 (insert ", ")))))
3126
3127 (defstruct (js2-var-init-node
3128 (:include js2-node)
3129 (:constructor nil)
3130 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3131 (pos js2-ts-cursor)
3132 len
3133 target
3134 initializer)))
3135 "AST node for a variable declaration.
3136 The type field will be js2-CONST for a const decl."
3137 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3138 initializer) ; initializer expression, a `js2-node'
3139
3140 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3141 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3142
3143 (defun js2-visit-var-init-node (n v)
3144 (js2-visit-ast (js2-var-init-node-target n) v)
3145 (js2-visit-ast (js2-var-init-node-initializer n) v))
3146
3147 (defun js2-print-var-init-node (n i)
3148 (let ((pad (js2-make-pad i))
3149 (name (js2-var-init-node-target n))
3150 (init (js2-var-init-node-initializer n)))
3151 (insert pad)
3152 (js2-print-ast name 0)
3153 (when init
3154 (insert " = ")
3155 (js2-print-ast init 0))))
3156
3157 (defstruct (js2-cond-node
3158 (:include js2-node)
3159 (:constructor nil)
3160 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3161 (pos js2-ts-cursor)
3162 len
3163 test-expr
3164 true-expr
3165 false-expr
3166 q-pos
3167 c-pos)))
3168 "AST node for the ternary operator"
3169 test-expr
3170 true-expr
3171 false-expr
3172 q-pos ; buffer position of ?
3173 c-pos) ; buffer position of :
3174
3175 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3176 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3177
3178 (defun js2-visit-cond-node (n v)
3179 (js2-visit-ast (js2-cond-node-test-expr n) v)
3180 (js2-visit-ast (js2-cond-node-true-expr n) v)
3181 (js2-visit-ast (js2-cond-node-false-expr n) v))
3182
3183 (defun js2-print-cond-node (n i)
3184 (let ((pad (js2-make-pad i)))
3185 (insert pad)
3186 (js2-print-ast (js2-cond-node-test-expr n) 0)
3187 (insert " ? ")
3188 (js2-print-ast (js2-cond-node-true-expr n) 0)
3189 (insert " : ")
3190 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3191
3192 (defstruct (js2-infix-node
3193 (:include js2-node)
3194 (:constructor nil)
3195 (:constructor make-js2-infix-node (&key type
3196 (pos js2-ts-cursor)
3197 len
3198 op-pos
3199 left
3200 right)))
3201 "Represents infix expressions.
3202 Includes assignment ops like `|=', and the comma operator.
3203 The type field inherited from `js2-node' holds the operator."
3204 op-pos ; buffer position where operator begins
3205 left ; any `js2-node'
3206 right) ; any `js2-node'
3207
3208 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3209 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3210
3211 (defun js2-visit-infix-node (n v)
3212 (js2-visit-ast (js2-infix-node-left n) v)
3213 (js2-visit-ast (js2-infix-node-right n) v))
3214
3215 (defconst js2-operator-tokens
3216 (let ((table (make-hash-table :test 'eq))
3217 (tokens
3218 (list (cons js2-IN "in")
3219 (cons js2-TYPEOF "typeof")
3220 (cons js2-INSTANCEOF "instanceof")
3221 (cons js2-DELPROP "delete")
3222 (cons js2-COMMA ",")
3223 (cons js2-COLON ":")
3224 (cons js2-OR "||")
3225 (cons js2-AND "&&")
3226 (cons js2-INC "++")
3227 (cons js2-DEC "--")
3228 (cons js2-BITOR "|")
3229 (cons js2-BITXOR "^")
3230 (cons js2-BITAND "&")
3231 (cons js2-EQ "==")
3232 (cons js2-NE "!=")
3233 (cons js2-LT "<")
3234 (cons js2-LE "<=")
3235 (cons js2-GT ">")
3236 (cons js2-GE ">=")
3237 (cons js2-LSH "<<")
3238 (cons js2-RSH ">>")
3239 (cons js2-URSH ">>>")
3240 (cons js2-ADD "+") ; infix plus
3241 (cons js2-SUB "-") ; infix minus
3242 (cons js2-MUL "*")
3243 (cons js2-DIV "/")
3244 (cons js2-MOD "%")
3245 (cons js2-NOT "!")
3246 (cons js2-BITNOT "~")
3247 (cons js2-POS "+") ; unary plus
3248 (cons js2-NEG "-") ; unary minus
3249 (cons js2-SHEQ "===") ; shallow equality
3250 (cons js2-SHNE "!==") ; shallow inequality
3251 (cons js2-ASSIGN "=")
3252 (cons js2-ASSIGN_BITOR "|=")
3253 (cons js2-ASSIGN_BITXOR "^=")
3254 (cons js2-ASSIGN_BITAND "&=")
3255 (cons js2-ASSIGN_LSH "<<=")
3256 (cons js2-ASSIGN_RSH ">>=")
3257 (cons js2-ASSIGN_URSH ">>>=")
3258 (cons js2-ASSIGN_ADD "+=")
3259 (cons js2-ASSIGN_SUB "-=")
3260 (cons js2-ASSIGN_MUL "*=")
3261 (cons js2-ASSIGN_DIV "/=")
3262 (cons js2-ASSIGN_MOD "%="))))
3263 (loop for (k . v) in tokens do
3264 (puthash k v table))
3265 table))
3266
3267 (defun js2-print-infix-node (n i)
3268 (let* ((tt (js2-node-type n))
3269 (op (gethash tt js2-operator-tokens)))
3270 (unless op
3271 (error "unrecognized infix operator %s" (js2-node-type n)))
3272 (insert (js2-make-pad i))
3273 (js2-print-ast (js2-infix-node-left n) 0)
3274 (unless (= tt js2-COMMA)
3275 (insert " "))
3276 (insert op)
3277 (insert " ")
3278 (js2-print-ast (js2-infix-node-right n) 0)))
3279
3280 (defstruct (js2-assign-node
3281 (:include js2-infix-node)
3282 (:constructor nil)
3283 (:constructor make-js2-assign-node (&key type
3284 (pos js2-ts-cursor)
3285 len
3286 op-pos
3287 left
3288 right)))
3289 "Represents any assignment.
3290 The type field holds the actual assignment operator.")
3291
3292 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3293 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3294
3295 (defstruct (js2-unary-node
3296 (:include js2-node)
3297 (:constructor nil)
3298 (:constructor make-js2-unary-node (&key type ; required
3299 (pos js2-ts-cursor)
3300 len
3301 operand)))
3302 "AST node type for unary operator nodes.
3303 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3304 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3305 property is added if the operator follows the operand."
3306 operand) ; a `js2-node' expression
3307
3308 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3309 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3310
3311 (defun js2-visit-unary-node (n v)
3312 (js2-visit-ast (js2-unary-node-operand n) v))
3313
3314 (defun js2-print-unary-node (n i)
3315 (let* ((tt (js2-node-type n))
3316 (op (gethash tt js2-operator-tokens))
3317 (postfix (js2-node-get-prop n 'postfix)))
3318 (unless op
3319 (error "unrecognized unary operator %s" tt))
3320 (insert (js2-make-pad i))
3321 (unless postfix
3322 (insert op))
3323 (if (or (= tt js2-TYPEOF)
3324 (= tt js2-DELPROP))
3325 (insert " "))
3326 (js2-print-ast (js2-unary-node-operand n) 0)
3327 (when postfix
3328 (insert op))))
3329
3330 (defstruct (js2-let-node
3331 (:include js2-scope)
3332 (:constructor nil)
3333 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3334 (pos js2-token-beg)
3335 len
3336 vars
3337 body
3338 lp
3339 rp)))
3340 "AST node for a let expression or a let statement.
3341 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3342 vars ; a `js2-var-decl-node'
3343 body ; a `js2-node' representing the expression or body block
3344 lp
3345 rp)
3346
3347 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3348 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3349
3350 (defun js2-visit-let-node (n v)
3351 (js2-visit-ast (js2-let-node-vars n) v)
3352 (js2-visit-ast (js2-let-node-body n) v))
3353
3354 (defun js2-print-let-node (n i)
3355 (insert (js2-make-pad i) "let (")
3356 (js2-print-ast (js2-let-node-vars n) 0)
3357 (insert ") ")
3358 (js2-print-ast (js2-let-node-body n) i))
3359
3360 (defstruct (js2-keyword-node
3361 (:include js2-node)
3362 (:constructor nil)
3363 (:constructor make-js2-keyword-node (&key type
3364 (pos js2-token-beg)
3365 (len (- js2-ts-cursor pos)))))
3366 "AST node representing a literal keyword such as `null'.
3367 Used for `null', `this', `true', `false' and `debugger'.
3368 The node type is set to js2-NULL, js2-THIS, etc.")
3369
3370 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3371 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3372
3373 (defun js2-print-keyword-node (n i)
3374 (insert (js2-make-pad i)
3375 (let ((tt (js2-node-type n)))
3376 (cond
3377 ((= tt js2-THIS) "this")
3378 ((= tt js2-NULL) "null")
3379 ((= tt js2-TRUE) "true")
3380 ((= tt js2-FALSE) "false")
3381 ((= tt js2-DEBUGGER) "debugger")
3382 (t (error "Invalid keyword literal type: %d" tt))))))
3383
3384 (defsubst js2-this-node-p (node)
3385 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3386 (eq (js2-node-type node) js2-THIS))
3387
3388 (defstruct (js2-new-node
3389 (:include js2-node)
3390 (:constructor nil)
3391 (:constructor make-js2-new-node (&key (type js2-NEW)
3392 (pos js2-token-beg)
3393 len
3394 target
3395 args
3396 initializer
3397 lp
3398 rp)))
3399 "AST node for new-expression such as new Foo()."
3400 target ; an identifier or reference
3401 args ; a lisp list of argument nodes
3402 lp ; position of left-paren, nil if omitted
3403 rp ; position of right-paren, nil if omitted
3404 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3405
3406 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3407 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3408
3409 (defun js2-visit-new-node (n v)
3410 (js2-visit-ast (js2-new-node-target n) v)
3411 (dolist (arg (js2-new-node-args n))
3412 (js2-visit-ast arg v))
3413 (js2-visit-ast (js2-new-node-initializer n) v))
3414
3415 (defun js2-print-new-node (n i)
3416 (insert (js2-make-pad i) "new ")
3417 (js2-print-ast (js2-new-node-target n))
3418 (insert "(")
3419 (js2-print-list (js2-new-node-args n))
3420 (insert ")")
3421 (when (js2-new-node-initializer n)
3422 (insert " ")
3423 (js2-print-ast (js2-new-node-initializer n))))
3424
3425 (defstruct (js2-name-node
3426 (:include js2-node)
3427 (:constructor nil)
3428 (:constructor make-js2-name-node (&key (type js2-NAME)
3429 (pos js2-token-beg)
3430 (len (- js2-ts-cursor
3431 js2-token-beg))
3432 (name js2-ts-string))))
3433 "AST node for a JavaScript identifier"
3434 name ; a string
3435 scope) ; a `js2-scope' (optional, used for codegen)
3436
3437 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3438 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3439
3440 (defun js2-print-name-node (n i)
3441 (insert (js2-make-pad i)
3442 (js2-name-node-name n)))
3443
3444 (defsubst js2-name-node-length (node)
3445 "Return identifier length of NODE, a `js2-name-node'.
3446 Returns 0 if NODE is nil or its identifier field is nil."
3447 (if node
3448 (length (js2-name-node-name node))
3449 0))
3450
3451 (defstruct (js2-number-node
3452 (:include js2-node)
3453 (:constructor nil)
3454 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3455 (pos js2-token-beg)
3456 (len (- js2-ts-cursor
3457 js2-token-beg))
3458 (value js2-ts-string)
3459 (num-value js2-ts-number))))
3460 "AST node for a number literal."
3461 value ; the original string, e.g. "6.02e23"
3462 num-value) ; the parsed number value
3463
3464 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3465 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3466
3467 (defun js2-print-number-node (n i)
3468 (insert (js2-make-pad i)
3469 (number-to-string (js2-number-node-num-value n))))
3470
3471 (defstruct (js2-regexp-node
3472 (:include js2-node)
3473 (:constructor nil)
3474 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3475 (pos js2-token-beg)
3476 (len (- js2-ts-cursor
3477 js2-token-beg))
3478 value
3479 flags)))
3480 "AST node for a regular expression literal."
3481 value ; the regexp string, without // delimiters
3482 flags) ; a string of flags, e.g. `mi'.
3483
3484 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3485 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3486
3487 (defun js2-print-regexp (n i)
3488 (insert (js2-make-pad i)
3489 "/"
3490 (js2-regexp-node-value n)
3491 "/")
3492 (if (js2-regexp-node-flags n)
3493 (insert (js2-regexp-node-flags n))))
3494
3495 (defstruct (js2-string-node
3496 (:include js2-node)
3497 (:constructor nil)
3498 (:constructor make-js2-string-node (&key (type js2-STRING)
3499 (pos js2-token-beg)
3500 (len (- js2-ts-cursor
3501 js2-token-beg))
3502 (value js2-ts-string))))
3503 "String literal.
3504 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3505 You can tell the quote type by looking at the first character."
3506 value) ; the characters of the string, including the quotes
3507
3508 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3509 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3510
3511 (defun js2-print-string-node (n i)
3512 (insert (js2-make-pad i)
3513 (js2-node-string n)))
3514
3515 (defstruct (js2-array-node
3516 (:include js2-node)
3517 (:constructor nil)
3518 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3519 (pos js2-ts-cursor)
3520 len
3521 elems)))
3522 "AST node for an array literal."
3523 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3524
3525 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3526 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3527
3528 (defun js2-visit-array-node (n v)
3529 (dolist (e (js2-array-node-elems n))
3530 (js2-visit-ast e v)))
3531
3532 (defun js2-print-array-node (n i)
3533 (insert (js2-make-pad i) "[")
3534 (js2-print-list (js2-array-node-elems n))
3535 (insert "]"))
3536
3537 (defstruct (js2-object-node
3538 (:include js2-node)
3539 (:constructor nil)
3540 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3541 (pos js2-ts-cursor)
3542 len
3543 elems)))
3544 "AST node for an object literal expression.
3545 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3546 the latter represents abbreviation in destructuring expressions."
3547 elems)
3548
3549 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3550 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3551
3552 (defun js2-visit-object-node (n v)
3553 (dolist (e (js2-object-node-elems n))
3554 (js2-visit-ast e v)))
3555
3556 (defun js2-print-object-node (n i)
3557 (insert (js2-make-pad i) "{")
3558 (js2-print-list (js2-object-node-elems n))
3559 (insert "}"))
3560
3561 (defstruct (js2-object-prop-node
3562 (:include js2-infix-node)
3563 (:constructor nil)
3564 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3565 (pos js2-ts-cursor)
3566 len
3567 left
3568 right
3569 op-pos)))
3570 "AST node for an object literal prop:value entry.
3571 The `left' field is the property: a name node, string node or number node.
3572 The `right' field is a `js2-node' representing the initializer value.")
3573
3574 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3575 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3576
3577 (defun js2-print-object-prop-node (n i)
3578 (insert (js2-make-pad i))
3579 (js2-print-ast (js2-object-prop-node-left n) 0)
3580 (insert ": ")
3581 (js2-print-ast (js2-object-prop-node-right n) 0))
3582
3583 (defstruct (js2-getter-setter-node
3584 (:include js2-infix-node)
3585 (:constructor nil)
3586 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3587 (pos js2-ts-cursor)
3588 len
3589 left
3590 right)))
3591 "AST node for a getter/setter property in an object literal.
3592 The `left' field is the `js2-name-node' naming the getter/setter prop.
3593 The `right' field is always an anonymous `js2-function-node' with a node
3594 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3595
3596 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3597 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3598
3599 (defun js2-print-getter-setter (n i)
3600 (let ((pad (js2-make-pad i))
3601 (left (js2-getter-setter-node-left n))
3602 (right (js2-getter-setter-node-right n)))
3603 (insert pad)
3604 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3605 (js2-print-ast left 0)
3606 (js2-print-ast right 0)))
3607
3608 (defstruct (js2-prop-get-node
3609 (:include js2-infix-node)
3610 (:constructor nil)
3611 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3612 (pos js2-ts-cursor)
3613 len
3614 left
3615 right)))
3616 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3617
3618 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3619 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3620
3621 (defun js2-visit-prop-get-node (n v)
3622 (js2-visit-ast (js2-prop-get-node-left n) v)
3623 (js2-visit-ast (js2-prop-get-node-right n) v))
3624
3625 (defun js2-print-prop-get-node (n i)
3626 (insert (js2-make-pad i))
3627 (js2-print-ast (js2-prop-get-node-left n) 0)
3628 (insert ".")
3629 (js2-print-ast (js2-prop-get-node-right n) 0))
3630
3631 (defstruct (js2-elem-get-node
3632 (:include js2-node)
3633 (:constructor nil)
3634 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3635 (pos js2-ts-cursor)
3636 len
3637 target
3638 element
3639 lb
3640 rb)))
3641 "AST node for an array index expression such as foo[bar]."
3642 target ; a `js2-node' - the expression preceding the "."
3643 element ; a `js2-node' - the expression in brackets
3644 lb ; position of left-bracket, nil if omitted
3645 rb) ; position of right-bracket, nil if omitted
3646
3647 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3648 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3649
3650 (defun js2-visit-elem-get-node (n v)
3651 (js2-visit-ast (js2-elem-get-node-target n) v)
3652 (js2-visit-ast (js2-elem-get-node-element n) v))
3653
3654 (defun js2-print-elem-get-node (n i)
3655 (insert (js2-make-pad i))
3656 (js2-print-ast (js2-elem-get-node-target n) 0)
3657 (insert "[")
3658 (js2-print-ast (js2-elem-get-node-element n) 0)
3659 (insert "]"))
3660
3661 (defstruct (js2-call-node
3662 (:include js2-node)
3663 (:constructor nil)
3664 (:constructor make-js2-call-node (&key (type js2-CALL)
3665 (pos js2-ts-cursor)
3666 len
3667 target
3668 args
3669 lp
3670 rp)))
3671 "AST node for a JavaScript function call."
3672 target ; a `js2-node' evaluating to the function to call
3673 args ; a lisp list of `js2-node' arguments
3674 lp ; position of open-paren, or nil if missing
3675 rp) ; position of close-paren, or nil if missing
3676
3677 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3678 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3679
3680 (defun js2-visit-call-node (n v)
3681 (js2-visit-ast (js2-call-node-target n) v)
3682 (dolist (arg (js2-call-node-args n))
3683 (js2-visit-ast arg v)))
3684
3685 (defun js2-print-call-node (n i)
3686 (insert (js2-make-pad i))
3687 (js2-print-ast (js2-call-node-target n) 0)
3688 (insert "(")
3689 (js2-print-list (js2-call-node-args n))
3690 (insert ")"))
3691
3692 (defstruct (js2-yield-node
3693 (:include js2-node)
3694 (:constructor nil)
3695 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3696 (pos js2-ts-cursor)
3697 len
3698 value)))
3699 "AST node for yield statement or expression."
3700 value) ; optional: value to be yielded
3701
3702 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3703 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3704
3705 (defun js2-visit-yield-node (n v)
3706 (js2-visit-ast (js2-yield-node-value n) v))
3707
3708 (defun js2-print-yield-node (n i)
3709 (insert (js2-make-pad i))
3710 (insert "yield")
3711 (when (js2-yield-node-value n)
3712 (insert " ")
3713 (js2-print-ast (js2-yield-node-value n) 0)))
3714
3715 (defstruct (js2-paren-node
3716 (:include js2-node)
3717 (:constructor nil)
3718 (:constructor make-js2-paren-node (&key (type js2-LP)
3719 (pos js2-ts-cursor)
3720 len
3721 expr)))
3722 "AST node for a parenthesized expression.
3723 In particular, used when the parens are syntactically optional,
3724 as opposed to required parens such as those enclosing an if-conditional."
3725 expr) ; `js2-node'
3726
3727 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3728 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3729
3730 (defun js2-visit-paren-node (n v)
3731 (js2-visit-ast (js2-paren-node-expr n) v))
3732
3733 (defun js2-print-paren-node (n i)
3734 (insert (js2-make-pad i))
3735 (insert "(")
3736 (js2-print-ast (js2-paren-node-expr n) 0)
3737 (insert ")"))
3738
3739 (defstruct (js2-array-comp-node
3740 (:include js2-scope)
3741 (:constructor nil)
3742 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3743 (pos js2-ts-cursor)
3744 len
3745 result
3746 loops
3747 filter
3748 if-pos
3749 lp
3750 rp)))
3751 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3752 result ; result expression (just after left-bracket)
3753 loops ; a lisp list of `js2-array-comp-loop-node'
3754 filter ; guard/filter expression
3755 if-pos ; buffer pos of 'if' keyword, if present, else nil
3756 lp ; buffer position of if-guard left-paren, or nil if not present
3757 rp) ; buffer position of if-guard right-paren, or nil if not present
3758
3759 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3760 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3761
3762 (defun js2-visit-array-comp-node (n v)
3763 (js2-visit-ast (js2-array-comp-node-result n) v)
3764 (dolist (l (js2-array-comp-node-loops n))
3765 (js2-visit-ast l v))
3766 (js2-visit-ast (js2-array-comp-node-filter n) v))
3767
3768 (defun js2-print-array-comp-node (n i)
3769 (let ((pad (js2-make-pad i))
3770 (result (js2-array-comp-node-result n))
3771 (loops (js2-array-comp-node-loops n))
3772 (filter (js2-array-comp-node-filter n)))
3773 (insert pad "[")
3774 (js2-print-ast result 0)
3775 (dolist (l loops)
3776 (insert " ")
3777 (js2-print-ast l 0))
3778 (when filter
3779 (insert " if (")
3780 (js2-print-ast filter 0)
3781 (insert ")"))
3782 (insert "]")))
3783
3784 (defstruct (js2-array-comp-loop-node
3785 (:include js2-for-in-node)
3786 (:constructor nil)
3787 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3788 (pos js2-ts-cursor)
3789 len
3790 iterator
3791 object
3792 in-pos
3793 foreach-p
3794 each-pos
3795 forof-p
3796 lp
3797 rp)))
3798 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3799
3800 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3801 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3802
3803 (defun js2-visit-array-comp-loop (n v)
3804 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3805 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3806
3807 (defun js2-print-array-comp-loop (n i)
3808 (insert "for (")
3809 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3810 (if (js2-array-comp-loop-node-forof-p n)
3811 (insert " of ")
3812 (insert " in "))
3813 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3814 (insert ")"))
3815
3816 (defstruct (js2-empty-expr-node
3817 (:include js2-node)
3818 (:constructor nil)
3819 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3820 (pos js2-token-beg)
3821 len)))
3822 "AST node for an empty expression.")
3823
3824 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3825 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3826
3827 (defstruct (js2-xml-node
3828 (:include js2-block-node)
3829 (:constructor nil)
3830 (:constructor make-js2-xml-node (&key (type js2-XML)
3831 (pos js2-token-beg)
3832 len
3833 kids)))
3834 "AST node for initial parse of E4X literals.
3835 The kids field is a list of XML fragments, each a `js2-string-node' or
3836 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3837
3838 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3839 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3840
3841 (defun js2-print-xml-node (n i)
3842 (dolist (kid (js2-xml-node-kids n))
3843 (js2-print-ast kid i)))
3844
3845 (defstruct (js2-xml-js-expr-node
3846 (:include js2-xml-node)
3847 (:constructor nil)
3848 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3849 (pos js2-ts-cursor)
3850 len
3851 expr)))
3852 "AST node for an embedded JavaScript {expression} in an E4X literal.
3853 The start and end fields correspond to the curly-braces."
3854 expr) ; a `js2-expr-node' of some sort
3855
3856 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3857 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3858
3859 (defun js2-visit-xml-js-expr (n v)
3860 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3861
3862 (defun js2-print-xml-js-expr (n i)
3863 (insert (js2-make-pad i))
3864 (insert "{")
3865 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3866 (insert "}"))
3867
3868 (defstruct (js2-xml-dot-query-node
3869 (:include js2-infix-node)
3870 (:constructor nil)
3871 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3872 (pos js2-ts-cursor)
3873 op-pos
3874 len
3875 left
3876 right
3877 rp)))
3878 "AST node for an E4X foo.(bar) filter expression.
3879 Note that the left-paren is automatically the character immediately
3880 following the dot (.) in the operator. No whitespace is permitted
3881 between the dot and the lp by the scanner."
3882 rp)
3883
3884 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3885 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3886
3887 (defun js2-print-xml-dot-query (n i)
3888 (insert (js2-make-pad i))
3889 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3890 (insert ".(")
3891 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3892 (insert ")"))
3893
3894 (defstruct (js2-xml-ref-node
3895 (:include js2-node)
3896 (:constructor nil)) ; abstract
3897 "Base type for E4X XML attribute-access or property-get expressions.
3898 Such expressions can take a variety of forms. The general syntax has
3899 three parts:
3900
3901 - (optional) an @ (specifying an attribute access)
3902 - (optional) a namespace (a `js2-name-node') and double-colon
3903 - (required) either a `js2-name-node' or a bracketed [expression]
3904
3905 The property-name expressions (examples: ns::name, @name) are
3906 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3907 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3908
3909 This node type (or more specifically, its subclasses) will sometimes
3910 be the right-hand child of a `js2-prop-get-node' or a
3911 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3912 The `js2-xml-ref-node' may also be a standalone primary expression with
3913 no explicit target, which is valid in certain expression contexts such as
3914
3915 company..employee.(@id < 100)
3916
3917 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3918 expression whose parent is a `js2-xml-dot-query-node'."
3919 namespace
3920 at-pos
3921 colon-pos)
3922
3923 (defsubst js2-xml-ref-node-attr-access-p (node)
3924 "Return non-nil if this expression began with an @-token."
3925 (and (numberp (js2-xml-ref-node-at-pos node))
3926 (plusp (js2-xml-ref-node-at-pos node))))
3927
3928 (defstruct (js2-xml-prop-ref-node
3929 (:include js2-xml-ref-node)
3930 (:constructor nil)
3931 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3932 (pos js2-token-beg)
3933 len
3934 propname
3935 namespace
3936 at-pos
3937 colon-pos)))
3938 "AST node for an E4X XML [expr] property-ref expression.
3939 The JavaScript syntax is an optional @, an optional ns::, and a name.
3940
3941 [ '@' ] [ name '::' ] name
3942
3943 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3944 @ns::*, @*::attr, @*::*, and @*.
3945
3946 The node starts at the @ token, if present. Otherwise it starts at the
3947 namespace name. The node bounds extend through the closing right-bracket,
3948 or if it is missing due to a syntax error, through the end of the index
3949 expression."
3950 propname)
3951
3952 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3953 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3954
3955 (defun js2-visit-xml-prop-ref-node (n v)
3956 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3957 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3958
3959 (defun js2-print-xml-prop-ref-node (n i)
3960 (insert (js2-make-pad i))
3961 (if (js2-xml-ref-node-attr-access-p n)
3962 (insert "@"))
3963 (when (js2-xml-prop-ref-node-namespace n)
3964 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3965 (insert "::"))
3966 (if (js2-xml-prop-ref-node-propname n)
3967 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3968
3969 (defstruct (js2-xml-elem-ref-node
3970 (:include js2-xml-ref-node)
3971 (:constructor nil)
3972 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3973 (pos js2-token-beg)
3974 len
3975 expr
3976 lb
3977 rb
3978 namespace
3979 at-pos
3980 colon-pos)))
3981 "AST node for an E4X XML [expr] member-ref expression.
3982 Syntax:
3983
3984 [ '@' ] [ name '::' ] '[' expr ']'
3985
3986 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3987
3988 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3989 is not a legal E4X XML element-ref expression, since it's already used
3990 for standard JavaScript element-get array indexing. Hence, a
3991 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3992 non-nil namespace node, or both.
3993
3994 The node starts at the @ token, if present. Otherwise it starts
3995 at the namespace name. The node bounds extend through the closing
3996 right-bracket, or if it is missing due to a syntax error, through the
3997 end of the index expression."
3998 expr ; the bracketed index expression
3999 lb
4000 rb)
4001
4002 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4003 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4004
4005 (defun js2-visit-xml-elem-ref-node (n v)
4006 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4007 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4008
4009 (defun js2-print-xml-elem-ref-node (n i)
4010 (insert (js2-make-pad i))
4011 (if (js2-xml-ref-node-attr-access-p n)
4012 (insert "@"))
4013 (when (js2-xml-elem-ref-node-namespace n)
4014 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4015 (insert "::"))
4016 (insert "[")
4017 (if (js2-xml-elem-ref-node-expr n)
4018 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4019 (insert "]"))
4020
4021 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4022
4023 (defstruct (js2-xml-start-tag-node
4024 (:include js2-xml-node)
4025 (:constructor nil)
4026 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4027 (pos js2-ts-cursor)
4028 len
4029 name
4030 attrs
4031 kids
4032 empty-p)))
4033 "AST node for an XML start-tag. Not currently used.
4034 The `kids' field is a lisp list of child content nodes."
4035 name ; a `js2-xml-name-node'
4036 attrs ; a lisp list of `js2-xml-attr-node'
4037 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4038
4039 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4040 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4041
4042 (defun js2-visit-xml-start-tag (n v)
4043 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4044 (dolist (attr (js2-xml-start-tag-node-attrs n))
4045 (js2-visit-ast attr v))
4046 (js2-visit-block n v))
4047
4048 (defun js2-print-xml-start-tag (n i)
4049 (insert (js2-make-pad i) "<")
4050 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4051 (when (js2-xml-start-tag-node-attrs n)
4052 (insert " ")
4053 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4054 (insert ">"))
4055
4056 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4057 ;; and add the end-tag to the kids list of the parent as well.
4058 (defstruct (js2-xml-end-tag-node
4059 (:include js2-xml-node)
4060 (:constructor nil)
4061 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4062 (pos js2-ts-cursor)
4063 len
4064 name)))
4065 "AST node for an XML end-tag. Not currently used."
4066 name) ; a `js2-xml-name-node'
4067
4068 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4069 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4070
4071 (defun js2-visit-xml-end-tag (n v)
4072 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4073
4074 (defun js2-print-xml-end-tag (n i)
4075 (insert (js2-make-pad i))
4076 (insert "</")
4077 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4078 (insert ">"))
4079
4080 (defstruct (js2-xml-name-node
4081 (:include js2-xml-node)
4082 (:constructor nil)
4083 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4084 (pos js2-ts-cursor)
4085 len
4086 namespace
4087 kids)))
4088 "AST node for an E4X XML name. Not currently used.
4089 Any XML name can be qualified with a namespace, hence the namespace field.
4090 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4091 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4092 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4093 namespace) ; a `js2-string-node'
4094
4095 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4096 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4097
4098 (defun js2-visit-xml-name-node (n v)
4099 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4100
4101 (defun js2-print-xml-name-node (n i)
4102 (insert (js2-make-pad i))
4103 (when (js2-xml-name-node-namespace n)
4104 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4105 (insert "::"))
4106 (dolist (kid (js2-xml-name-node-kids n))
4107 (js2-print-ast kid 0)))
4108
4109 (defstruct (js2-xml-pi-node
4110 (:include js2-xml-node)
4111 (:constructor nil)
4112 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4113 (pos js2-ts-cursor)
4114 len
4115 name
4116 attrs)))
4117 "AST node for an E4X XML processing instruction. Not currently used."
4118 name ; a `js2-xml-name-node'
4119 attrs) ; a list of `js2-xml-attr-node'
4120
4121 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4122 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4123
4124 (defun js2-visit-xml-pi-node (n v)
4125 (js2-visit-ast (js2-xml-pi-node-name n) v)
4126 (dolist (attr (js2-xml-pi-node-attrs n))
4127 (js2-visit-ast attr v)))
4128
4129 (defun js2-print-xml-pi-node (n i)
4130 (insert (js2-make-pad i) "<?")
4131 (js2-print-ast (js2-xml-pi-node-name n))
4132 (when (js2-xml-pi-node-attrs n)
4133 (insert " ")
4134 (js2-print-list (js2-xml-pi-node-attrs n)))
4135 (insert "?>"))
4136
4137 (defstruct (js2-xml-cdata-node
4138 (:include js2-xml-node)
4139 (:constructor nil)
4140 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4141 (pos js2-ts-cursor)
4142 len
4143 content)))
4144 "AST node for a CDATA escape section. Not currently used."
4145 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4146
4147 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4148 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4149
4150 (defun js2-visit-xml-cdata-node (n v)
4151 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4152
4153 (defun js2-print-xml-cdata-node (n i)
4154 (insert (js2-make-pad i))
4155 (js2-print-ast (js2-xml-cdata-node-content n)))
4156
4157 (defstruct (js2-xml-attr-node
4158 (:include js2-xml-node)
4159 (:constructor nil)
4160 (:constructor make-js2-attr-node (&key (type js2-XML)
4161 (pos js2-ts-cursor)
4162 len
4163 name
4164 value
4165 eq-pos
4166 quote-type)))
4167 "AST node representing a foo='bar' XML attribute value. Not yet used."
4168 name ; a `js2-xml-name-node'
4169 value ; a `js2-xml-name-node'
4170 eq-pos ; buffer position of "=" sign
4171 quote-type) ; 'single or 'double
4172
4173 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4174 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4175
4176 (defun js2-visit-xml-attr-node (n v)
4177 (js2-visit-ast (js2-xml-attr-node-name n) v)
4178 (js2-visit-ast (js2-xml-attr-node-value n) v))
4179
4180 (defun js2-print-xml-attr-node (n i)
4181 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4182 "'"
4183 "\"")))
4184 (insert (js2-make-pad i))
4185 (js2-print-ast (js2-xml-attr-node-name n) 0)
4186 (insert "=" quote)
4187 (js2-print-ast (js2-xml-attr-node-value n) 0)
4188 (insert quote)))
4189
4190 (defstruct (js2-xml-text-node
4191 (:include js2-xml-node)
4192 (:constructor nil)
4193 (:constructor make-js2-text-node (&key (type js2-XML)
4194 (pos js2-ts-cursor)
4195 len
4196 content)))
4197 "AST node for an E4X XML text node. Not currently used."
4198 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4199
4200 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4201 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4202
4203 (defun js2-visit-xml-text-node (n v)
4204 (js2-visit-ast (js2-xml-text-node-content n) v))
4205
4206 (defun js2-print-xml-text-node (n i)
4207 (insert (js2-make-pad i))
4208 (dolist (kid (js2-xml-text-node-content n))
4209 (js2-print-ast kid)))
4210
4211 (defstruct (js2-xml-comment-node
4212 (:include js2-xml-node)
4213 (:constructor nil)
4214 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4215 (pos js2-ts-cursor)
4216 len)))
4217 "AST node for E4X XML comment. Not currently used.")
4218
4219 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4220 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4221
4222 (defun js2-print-xml-comment (n i)
4223 (insert (js2-make-pad i)
4224 (js2-node-string n)))
4225
4226 ;;; Node utilities
4227
4228 (defsubst js2-node-line (n)
4229 "Fetch the source line number at the start of node N.
4230 This is O(n) in the length of the source buffer; use prudently."
4231 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4232
4233 (defsubst js2-block-node-kid (n i)
4234 "Return child I of node N, or nil if there aren't that many."
4235 (nth i (js2-block-node-kids n)))
4236
4237 (defsubst js2-block-node-first (n)
4238 "Return first child of block node N, or nil if there is none."
4239 (first (js2-block-node-kids n)))
4240
4241 (defun js2-node-root (n)
4242 "Return the root of the AST containing N.
4243 If N has no parent pointer, returns N."
4244 (let ((parent (js2-node-parent n)))
4245 (if parent
4246 (js2-node-root parent)
4247 n)))
4248
4249 (defun js2-node-position-in-parent (node &optional parent)
4250 "Return the position of NODE in parent's block-kids list.
4251 PARENT can be supplied if known. Positioned returned is zero-indexed.
4252 Returns 0 if NODE is not a child of a block statement, or if NODE
4253 is not a statement node."
4254 (let ((p (or parent (js2-node-parent node)))
4255 (i 0))
4256 (if (not (js2-block-node-p p))
4257 i
4258 (or (js2-position node (js2-block-node-kids p))
4259 0))))
4260
4261 (defsubst js2-node-short-name (n)
4262 "Return the short name of node N as a string, e.g. `js2-if-node'."
4263 (substring (symbol-name (aref n 0))
4264 (length "cl-struct-")))
4265
4266 (defsubst js2-node-child-list (node)
4267 "Return the child list for NODE, a lisp list of nodes.
4268 Works for block nodes, array nodes, obj literals, funarg lists,
4269 var decls and try nodes (for catch clauses). Note that you should call
4270 `js2-block-node-kids' on the function body for the body statements.
4271 Returns nil for zero-length child lists or unsupported nodes."
4272 (cond
4273 ((js2-function-node-p node)
4274 (js2-function-node-params node))
4275 ((js2-block-node-p node)
4276 (js2-block-node-kids node))
4277 ((js2-try-node-p node)
4278 (js2-try-node-catch-clauses node))
4279 ((js2-array-node-p node)
4280 (js2-array-node-elems node))
4281 ((js2-object-node-p node)
4282 (js2-object-node-elems node))
4283 ((js2-call-node-p node)
4284 (js2-call-node-args node))
4285 ((js2-new-node-p node)
4286 (js2-new-node-args node))
4287 ((js2-var-decl-node-p node)
4288 (js2-var-decl-node-kids node))
4289 (t
4290 nil)))
4291
4292 (defsubst js2-node-set-child-list (node kids)
4293 "Set the child list for NODE to KIDS."
4294 (cond
4295 ((js2-function-node-p node)
4296 (setf (js2-function-node-params node) kids))
4297 ((js2-block-node-p node)
4298 (setf (js2-block-node-kids node) kids))
4299 ((js2-try-node-p node)
4300 (setf (js2-try-node-catch-clauses node) kids))
4301 ((js2-array-node-p node)
4302 (setf (js2-array-node-elems node) kids))
4303 ((js2-object-node-p node)
4304 (setf (js2-object-node-elems node) kids))
4305 ((js2-call-node-p node)
4306 (setf (js2-call-node-args node) kids))
4307 ((js2-new-node-p node)
4308 (setf (js2-new-node-args node) kids))
4309 ((js2-var-decl-node-p node)
4310 (setf (js2-var-decl-node-kids node) kids))
4311 (t
4312 (error "Unsupported node type: %s" (js2-node-short-name node))))
4313 kids)
4314
4315 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4316 (defconst js2-paren-expr-nodes
4317 '(cl-struct-js2-array-comp-loop-node
4318 cl-struct-js2-array-comp-node
4319 cl-struct-js2-call-node
4320 cl-struct-js2-catch-node
4321 cl-struct-js2-do-node
4322 cl-struct-js2-elem-get-node
4323 cl-struct-js2-for-in-node
4324 cl-struct-js2-for-node
4325 cl-struct-js2-function-node
4326 cl-struct-js2-if-node
4327 cl-struct-js2-let-node
4328 cl-struct-js2-new-node
4329 cl-struct-js2-paren-node
4330 cl-struct-js2-switch-node
4331 cl-struct-js2-while-node
4332 cl-struct-js2-with-node
4333 cl-struct-js2-xml-dot-query-node)
4334 "Node types that can have a parenthesized child expression.
4335 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4336
4337 (defsubst js2-paren-expr-node-p (node)
4338 "Return t for nodes that typically have a parenthesized child expression.
4339 Useful for computing the indentation anchors for arg-lists and conditions.
4340 Note that it may return a false positive, for instance when NODE is
4341 a `js2-new-node' and there are no arguments or parentheses."
4342 (memq (aref node 0) js2-paren-expr-nodes))
4343
4344 ;; Fake polymorphism... yech.
4345 (defsubst js2-node-lp (node)
4346 "Return relative left-paren position for NODE, if applicable.
4347 For `js2-elem-get-node' structs, returns left-bracket position.
4348 Note that the position may be nil in the case of a parse error."
4349 (cond
4350 ((js2-elem-get-node-p node)
4351 (js2-elem-get-node-lb node))
4352 ((js2-loop-node-p node)
4353 (js2-loop-node-lp node))
4354 ((js2-function-node-p node)
4355 (js2-function-node-lp node))
4356 ((js2-if-node-p node)
4357 (js2-if-node-lp node))
4358 ((js2-new-node-p node)
4359 (js2-new-node-lp node))
4360 ((js2-call-node-p node)
4361 (js2-call-node-lp node))
4362 ((js2-paren-node-p node)
4363 (js2-node-pos node))
4364 ((js2-switch-node-p node)
4365 (js2-switch-node-lp node))
4366 ((js2-catch-node-p node)
4367 (js2-catch-node-lp node))
4368 ((js2-let-node-p node)
4369 (js2-let-node-lp node))
4370 ((js2-array-comp-node-p node)
4371 (js2-array-comp-node-lp node))
4372 ((js2-with-node-p node)
4373 (js2-with-node-lp node))
4374 ((js2-xml-dot-query-node-p node)
4375 (1+ (js2-infix-node-op-pos node)))
4376 (t
4377 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4378
4379 ;; Fake polymorphism... blech.
4380 (defsubst js2-node-rp (node)
4381 "Return relative right-paren position for NODE, if applicable.
4382 For `js2-elem-get-node' structs, returns right-bracket position.
4383 Note that the position may be nil in the case of a parse error."
4384 (cond
4385 ((js2-elem-get-node-p node)
4386 (js2-elem-get-node-lb node))
4387 ((js2-loop-node-p node)
4388 (js2-loop-node-rp node))
4389 ((js2-function-node-p node)
4390 (js2-function-node-rp node))
4391 ((js2-if-node-p node)
4392 (js2-if-node-rp node))
4393 ((js2-new-node-p node)
4394 (js2-new-node-rp node))
4395 ((js2-call-node-p node)
4396 (js2-call-node-rp node))
4397 ((js2-paren-node-p node)
4398 (+ (js2-node-pos node) (js2-node-len node)))
4399 ((js2-switch-node-p node)
4400 (js2-switch-node-rp node))
4401 ((js2-catch-node-p node)
4402 (js2-catch-node-rp node))
4403 ((js2-let-node-p node)
4404 (js2-let-node-rp node))
4405 ((js2-array-comp-node-p node)
4406 (js2-array-comp-node-rp node))
4407 ((js2-with-node-p node)
4408 (js2-with-node-rp node))
4409 ((js2-xml-dot-query-node-p node)
4410 (1+ (js2-xml-dot-query-node-rp node)))
4411 (t
4412 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4413
4414 (defsubst js2-node-first-child (node)
4415 "Returns the first element of `js2-node-child-list' for NODE."
4416 (car (js2-node-child-list node)))
4417
4418 (defsubst js2-node-last-child (node)
4419 "Returns the last element of `js2-node-last-child' for NODE."
4420 (car (last (js2-node-child-list node))))
4421
4422 (defun js2-node-prev-sibling (node)
4423 "Return the previous statement in parent.
4424 Works for parents supported by `js2-node-child-list'.
4425 Returns nil if NODE is not in the parent, or PARENT is
4426 not a supported node, or if NODE is the first child."
4427 (let* ((p (js2-node-parent node))
4428 (kids (js2-node-child-list p))
4429 (sib (car kids)))
4430 (while (and kids
4431 (not (eq node (cadr kids))))
4432 (setq kids (cdr kids)
4433 sib (car kids)))
4434 sib))
4435
4436 (defun js2-node-next-sibling (node)
4437 "Return the next statement in parent block.
4438 Returns nil if NODE is not in the block, or PARENT is not
4439 a block node, or if NODE is the last statement."
4440 (let* ((p (js2-node-parent node))
4441 (kids (js2-node-child-list p)))
4442 (while (and kids
4443 (not (eq node (car kids))))
4444 (setq kids (cdr kids)))
4445 (cadr kids)))
4446
4447 (defun js2-node-find-child-before (pos parent &optional after)
4448 "Find the last child that starts before POS in parent.
4449 If AFTER is non-nil, returns first child starting after POS.
4450 POS is an absolute buffer position. PARENT is any node
4451 supported by `js2-node-child-list'.
4452 Returns nil if no applicable child is found."
4453 (let ((kids (if (js2-function-node-p parent)
4454 (js2-block-node-kids (js2-function-node-body parent))
4455 (js2-node-child-list parent)))
4456 (beg (if (js2-function-node-p parent)
4457 (js2-node-abs-pos (js2-function-node-body parent))
4458 (js2-node-abs-pos parent)))
4459 kid
4460 result
4461 fn
4462 (continue t))
4463 (setq fn (if after '>= '<))
4464 (while (and kids continue)
4465 (setq kid (car kids))
4466 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4467 (setq result kid
4468 continue (if after nil t))
4469 (setq continue (if after t nil)))
4470 (setq kids (cdr kids)))
4471 result))
4472
4473 (defun js2-node-find-child-after (pos parent)
4474 "Find first child that starts after POS in parent.
4475 POS is an absolute buffer position. PARENT is any node
4476 supported by `js2-node-child-list'.
4477 Returns nil if no applicable child is found."
4478 (js2-node-find-child-before pos parent 'after))
4479
4480 (defun js2-node-replace-child (pos parent new-node)
4481 "Replace node at index POS in PARENT with NEW-NODE.
4482 Only works for parents supported by `js2-node-child-list'."
4483 (let ((kids (js2-node-child-list parent))
4484 (i 0))
4485 (while (< i pos)
4486 (setq kids (cdr kids)
4487 i (1+ i)))
4488 (setcar kids new-node)
4489 (js2-node-add-children parent new-node)))
4490
4491 (defun js2-node-buffer (n)
4492 "Return the buffer associated with AST N.
4493 Returns nil if the buffer is not set as a property on the root
4494 node, or if parent links were not recorded during parsing."
4495 (let ((root (js2-node-root n)))
4496 (and root
4497 (js2-ast-root-p root)
4498 (js2-ast-root-buffer root))))
4499
4500 (defsubst js2-block-node-push (n kid)
4501 "Push js2-node KID onto the end of js2-block-node N's child list.
4502 KID is always added to the -end- of the kids list.
4503 Function also calls `js2-node-add-children' to add the parent link."
4504 (let ((kids (js2-node-child-list n)))
4505 (if kids
4506 (setcdr kids (nconc (cdr kids) (list kid)))
4507 (js2-node-set-child-list n (list kid)))
4508 (js2-node-add-children n kid)))
4509
4510 (defun js2-node-string (node)
4511 (let ((buf (js2-node-buffer node))
4512 pos)
4513 (unless buf
4514 (error "No buffer available for node %s" node))
4515 (with-current-buffer buf
4516 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4517 (+ pos (js2-node-len node))))))
4518
4519 ;; Container for storing the node we're looking for in a traversal.
4520 (js2-deflocal js2-discovered-node nil)
4521
4522 ;; Keep track of absolute node position during traversals.
4523 (js2-deflocal js2-visitor-offset nil)
4524
4525 (js2-deflocal js2-node-search-point nil)
4526
4527 (when js2-mode-dev-mode-p
4528 (defun js2-find-node-at-point ()
4529 (interactive)
4530 (let ((node (js2-node-at-point)))
4531 (message "%s" (or node "No node found at point"))))
4532 (defun js2-node-name-at-point ()
4533 (interactive)
4534 (let ((node (js2-node-at-point)))
4535 (message "%s" (if node
4536 (js2-node-short-name node)
4537 "No node found at point.")))))
4538
4539 (defun js2-node-at-point (&optional pos skip-comments)
4540 "Return AST node at POS, a buffer position, defaulting to current point.
4541 The `js2-mode-ast' variable must be set to the current parse tree.
4542 Signals an error if the AST (`js2-mode-ast') is nil.
4543 Always returns a node - if it can't find one, it returns the root.
4544 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4545 (let ((ast js2-mode-ast)
4546 result)
4547 (unless ast
4548 (error "No JavaScript AST available"))
4549 ;; Look through comments first, since they may be inside nodes that
4550 ;; would otherwise report a match.
4551 (setq pos (or pos (point))
4552 result (if (> pos (js2-node-abs-end ast))
4553 ast
4554 (if (not skip-comments)
4555 (js2-comment-at-point pos))))
4556 (unless result
4557 (setq js2-discovered-node nil
4558 js2-visitor-offset 0
4559 js2-node-search-point pos)
4560 (unwind-protect
4561 (catch 'js2-visit-done
4562 (js2-visit-ast ast #'js2-node-at-point-visitor))
4563 (setq js2-visitor-offset nil
4564 js2-node-search-point nil))
4565 (setq result js2-discovered-node))
4566 ;; may have found a comment beyond end of last child node,
4567 ;; since visiting the ast-root looks at the comment-list last.
4568 (if (and skip-comments
4569 (js2-comment-node-p result))
4570 (setq result nil))
4571 (or result js2-mode-ast)))
4572
4573 (defun js2-node-at-point-visitor (node end-p)
4574 (let ((rel-pos (js2-node-pos node))
4575 abs-pos
4576 abs-end
4577 (point js2-node-search-point))
4578 (cond
4579 (end-p
4580 ;; this evaluates to a non-nil return value, even if it's zero
4581 (decf js2-visitor-offset rel-pos))
4582 ;; we already looked for comments before visiting, and don't want them now
4583 ((js2-comment-node-p node)
4584 nil)
4585 (t
4586 (setq abs-pos (incf js2-visitor-offset rel-pos)
4587 ;; we only want to use the node if the point is before
4588 ;; the last character position in the node, so we decrement
4589 ;; the absolute end by 1.
4590 abs-end (+ abs-pos (js2-node-len node) -1))
4591 (cond
4592 ;; If this node starts after search-point, stop the search.
4593 ((> abs-pos point)
4594 (throw 'js2-visit-done nil))
4595 ;; If this node ends before the search-point, don't check kids.
4596 ((> point abs-end)
4597 nil)
4598 (t
4599 ;; Otherwise point is within this node, possibly in a child.
4600 (setq js2-discovered-node node)
4601 t)))))) ; keep processing kids to look for more specific match
4602
4603 (defsubst js2-block-comment-p (node)
4604 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4605 (and (js2-comment-node-p node)
4606 (memq (js2-comment-node-format node) '(jsdoc block))))
4607
4608 ;; TODO: put the comments in a vector and binary-search them instead
4609 (defun js2-comment-at-point (&optional pos)
4610 "Look through scanned comment nodes for one containing POS.
4611 POS is a buffer position that defaults to current point.
4612 Function returns nil if POS was not in any comment node."
4613 (let ((ast js2-mode-ast)
4614 (x (or pos (point)))
4615 beg
4616 end)
4617 (unless ast
4618 (error "No JavaScript AST available"))
4619 (catch 'done
4620 ;; Comments are stored in lexical order.
4621 (dolist (comment (js2-ast-root-comments ast) nil)
4622 (setq beg (js2-node-abs-pos comment)
4623 end (+ beg (js2-node-len comment)))
4624 (if (and (>= x beg)
4625 (<= x end))
4626 (throw 'done comment))))))
4627
4628 (defun js2-mode-find-parent-fn (node)
4629 "Find function enclosing NODE.
4630 Returns nil if NODE is not inside a function."
4631 (setq node (js2-node-parent node))
4632 (while (and node (not (js2-function-node-p node)))
4633 (setq node (js2-node-parent node)))
4634 (and (js2-function-node-p node) node))
4635
4636 (defun js2-mode-find-enclosing-fn (node)
4637 "Find function or root enclosing NODE."
4638 (if (js2-ast-root-p node)
4639 node
4640 (setq node (js2-node-parent node))
4641 (while (not (or (js2-ast-root-p node)
4642 (js2-function-node-p node)))
4643 (setq node (js2-node-parent node)))
4644 node))
4645
4646 (defun js2-mode-find-enclosing-node (beg end)
4647 "Find script or function fully enclosing BEG and END."
4648 (let ((node (js2-node-at-point beg))
4649 pos
4650 (continue t))
4651 (while continue
4652 (if (or (js2-ast-root-p node)
4653 (and (js2-function-node-p node)
4654 (<= (setq pos (js2-node-abs-pos node)) beg)
4655 (>= (+ pos (js2-node-len node)) end)))
4656 (setq continue nil)
4657 (setq node (js2-node-parent node))))
4658 node))
4659
4660 (defun js2-node-parent-script-or-fn (node)
4661 "Find script or function immediately enclosing NODE.
4662 If NODE is the ast-root, returns nil."
4663 (if (js2-ast-root-p node)
4664 nil
4665 (setq node (js2-node-parent node))
4666 (while (and node (not (or (js2-function-node-p node)
4667 (js2-script-node-p node))))
4668 (setq node (js2-node-parent node)))
4669 node))
4670
4671 (defsubst js2-nested-function-p (node)
4672 "Return t if NODE is a nested function, or is inside a nested function."
4673 (unless (js2-ast-root-p node)
4674 (js2-function-node-p (if (js2-function-node-p node)
4675 (js2-node-parent-script-or-fn node)
4676 (js2-node-parent-script-or-fn
4677 (js2-node-parent-script-or-fn node))))))
4678
4679 (defsubst js2-function-param-node-p (node)
4680 "Return non-nil if NODE is a param node of a `js2-function-node'."
4681 (let ((parent (js2-node-parent node)))
4682 (and parent
4683 (js2-function-node-p parent)
4684 (memq node (js2-function-node-params parent)))))
4685
4686 (defsubst js2-mode-shift-kids (kids start offset)
4687 (dolist (kid kids)
4688 (if (> (js2-node-pos kid) start)
4689 (incf (js2-node-pos kid) offset))))
4690
4691 (defsubst js2-mode-shift-children (parent start offset)
4692 "Update start-positions of all children of PARENT beyond START."
4693 (let ((root (js2-node-root parent)))
4694 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4695 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4696
4697 (defsubst js2-node-is-descendant (node ancestor)
4698 "Return t if NODE is a descendant of ANCESTOR."
4699 (while (and node
4700 (not (eq node ancestor)))
4701 (setq node (js2-node-parent node)))
4702 node)
4703
4704 ;;; visitor infrastructure
4705
4706 (defun js2-visit-none (node callback)
4707 "Visitor for AST node that have no node children."
4708 nil)
4709
4710 (defun js2-print-none (node indent)
4711 "Visitor for AST node with no printed representation.")
4712
4713 (defun js2-print-body (node indent)
4714 "Print a statement, or a block without braces."
4715 (if (js2-block-node-p node)
4716 (dolist (kid (js2-block-node-kids node))
4717 (js2-print-ast kid indent))
4718 (js2-print-ast node indent)))
4719
4720 (defun js2-print-list (args &optional delimiter)
4721 (loop with len = (length args)
4722 for arg in args
4723 for count from 1
4724 do
4725 (js2-print-ast arg 0)
4726 (if (< count len)
4727 (insert (or delimiter ", ")))))
4728
4729 (defun js2-print-tree (ast)
4730 "Prints an AST to the current buffer.
4731 Makes `js2-ast-parent-nodes' available to the printer functions."
4732 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4733 (js2-print-ast ast)))
4734
4735 (defun js2-print-ast (node &optional indent)
4736 "Helper function for printing AST nodes.
4737 Requires `js2-ast-parent-nodes' to be non-nil.
4738 You should use `js2-print-tree' instead of this function."
4739 (let ((printer (get (aref node 0) 'js2-printer))
4740 (i (or indent 0))
4741 (pos (js2-node-abs-pos node)))
4742 ;; TODO: wedge comments in here somewhere
4743 (if printer
4744 (funcall printer node i))))
4745
4746 (defconst js2-side-effecting-tokens
4747 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4748 (dolist (tt (list js2-ASSIGN
4749 js2-ASSIGN_ADD
4750 js2-ASSIGN_BITAND
4751 js2-ASSIGN_BITOR
4752 js2-ASSIGN_BITXOR
4753 js2-ASSIGN_DIV
4754 js2-ASSIGN_LSH
4755 js2-ASSIGN_MOD
4756 js2-ASSIGN_MUL
4757 js2-ASSIGN_RSH
4758 js2-ASSIGN_SUB
4759 js2-ASSIGN_URSH
4760 js2-BLOCK
4761 js2-BREAK
4762 js2-CALL
4763 js2-CATCH
4764 js2-CATCH_SCOPE
4765 js2-CONST
4766 js2-CONTINUE
4767 js2-DEBUGGER
4768 js2-DEC
4769 js2-DELPROP
4770 js2-DEL_REF
4771 js2-DO
4772 js2-ELSE
4773 js2-EMPTY
4774 js2-ENTERWITH
4775 js2-EXPORT
4776 js2-EXPR_RESULT
4777 js2-FINALLY
4778 js2-FOR
4779 js2-FUNCTION
4780 js2-GOTO
4781 js2-IF
4782 js2-IFEQ
4783 js2-IFNE
4784 js2-IMPORT
4785 js2-INC
4786 js2-JSR
4787 js2-LABEL
4788 js2-LEAVEWITH
4789 js2-LET
4790 js2-LETEXPR
4791 js2-LOCAL_BLOCK
4792 js2-LOOP
4793 js2-NEW
4794 js2-REF_CALL
4795 js2-RETHROW
4796 js2-RETURN
4797 js2-RETURN_RESULT
4798 js2-SEMI
4799 js2-SETELEM
4800 js2-SETELEM_OP
4801 js2-SETNAME
4802 js2-SETPROP
4803 js2-SETPROP_OP
4804 js2-SETVAR
4805 js2-SET_REF
4806 js2-SET_REF_OP
4807 js2-SWITCH
4808 js2-TARGET
4809 js2-THROW
4810 js2-TRY
4811 js2-VAR
4812 js2-WHILE
4813 js2-WITH
4814 js2-WITHEXPR
4815 js2-YIELD))
4816 (aset tokens tt t))
4817 (if js2-instanceof-has-side-effects
4818 (aset tokens js2-INSTANCEOF t))
4819 tokens))
4820
4821 (defun js2-node-has-side-effects (node)
4822 "Return t if NODE has side effects."
4823 (when node ; makes it easier to handle malformed expressions
4824 (let ((tt (js2-node-type node)))
4825 (cond
4826 ;; This doubtless needs some work, since EXPR_VOID is used
4827 ;; in several ways in Rhino, and I may not have caught them all.
4828 ;; I'll wait for people to notice incorrect warnings.
4829 ((and (= tt js2-EXPR_VOID)
4830 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4831 (let ((expr (js2-expr-stmt-node-expr node)))
4832 (or (js2-node-has-side-effects expr)
4833 (when (js2-string-node-p expr)
4834 (string= "use strict" (js2-string-node-value expr))))))
4835 ((= tt js2-COMMA)
4836 (js2-node-has-side-effects (js2-infix-node-right node)))
4837 ((or (= tt js2-AND)
4838 (= tt js2-OR))
4839 (or (js2-node-has-side-effects (js2-infix-node-right node))
4840 (js2-node-has-side-effects (js2-infix-node-left node))))
4841 ((= tt js2-HOOK)
4842 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4843 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4844 ((js2-paren-node-p node)
4845 (js2-node-has-side-effects (js2-paren-node-expr node)))
4846 ((= tt js2-ERROR) ; avoid cascaded error messages
4847 nil)
4848 (t
4849 (aref js2-side-effecting-tokens tt))))))
4850
4851 (defun js2-member-expr-leftmost-name (node)
4852 "For an expr such as foo.bar.baz, return leftmost node foo.
4853 NODE is any `js2-node' object. If it represents a member expression,
4854 which is any sequence of property gets, element-gets, function calls,
4855 or xml descendants/filter operators, then we look at the lexically
4856 leftmost (first) node in the chain. If it is a name-node we return it.
4857 Note that NODE can be a raw name-node and it will be returned as well.
4858 If NODE is not a name-node or member expression, or if it is a member
4859 expression whose leftmost target is not a name node, returns nil."
4860 (let ((continue t)
4861 result)
4862 (while (and continue (not result))
4863 (cond
4864 ((js2-name-node-p node)
4865 (setq result node))
4866 ((js2-prop-get-node-p node)
4867 (setq node (js2-prop-get-node-left node)))
4868 ;; TODO: handle call-nodes, xml-nodes, others?
4869 (t
4870 (setq continue nil))))
4871 result))
4872
4873 (defconst js2-stmt-node-types
4874 (list js2-BLOCK
4875 js2-BREAK
4876 js2-CONTINUE
4877 js2-DEFAULT ; e4x "default xml namespace" statement
4878 js2-DO
4879 js2-EXPR_RESULT
4880 js2-EXPR_VOID
4881 js2-FOR
4882 js2-IF
4883 js2-RETURN
4884 js2-SWITCH
4885 js2-THROW
4886 js2-TRY
4887 js2-WHILE
4888 js2-WITH)
4889 "Node types that only appear in statement contexts.
4890 The list does not include nodes that always appear as the child
4891 of another specific statement type, such as switch-cases,
4892 catch and finally blocks, and else-clauses. The list also excludes
4893 nodes like yield, let and var, which may appear in either expression
4894 or statement context, and in the latter context always have a
4895 `js2-expr-stmt-node' parent. Finally, the list does not include
4896 functions or scripts, which are treated separately from statements
4897 by the JavaScript parser and runtime.")
4898
4899 (defun js2-stmt-node-p (node)
4900 "Heuristic for figuring out if NODE is a statement.
4901 Some node types can appear in either an expression context or a
4902 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4903 For these node types in a statement context, the parent will be a
4904 `js2-expr-stmt-node'.
4905 Functions aren't included in the check."
4906 (memq (js2-node-type node) js2-stmt-node-types))
4907
4908 (defsubst js2-mode-find-first-stmt (node)
4909 "Search upward starting from NODE looking for a statement.
4910 For purposes of this function, a `js2-function-node' counts."
4911 (while (not (or (js2-stmt-node-p node)
4912 (js2-function-node-p node)))
4913 (setq node (js2-node-parent node)))
4914 node)
4915
4916 (defun js2-node-parent-stmt (node)
4917 "Return the node's first ancestor that is a statement.
4918 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4919 appearing in a statement context will have a parent that is a
4920 `js2-expr-stmt-node' that will be returned by this function."
4921 (let ((parent (js2-node-parent node)))
4922 (if (or (null parent)
4923 (js2-stmt-node-p parent)
4924 (and (js2-function-node-p parent)
4925 (not (eq (js2-function-node-form parent)
4926 'FUNCTION_EXPRESSION))))
4927 parent
4928 (js2-node-parent-stmt parent))))
4929
4930 ;; In the Mozilla Rhino sources, Roshan James writes:
4931 ;; Does consistent-return analysis on the function body when strict mode is
4932 ;; enabled.
4933 ;;
4934 ;; function (x) { return (x+1) }
4935 ;;
4936 ;; is ok, but
4937 ;;
4938 ;; function (x) { if (x < 0) return (x+1); }
4939 ;;
4940 ;; is not because the function can potentially return a value when the
4941 ;; condition is satisfied and if not, the function does not explicitly
4942 ;; return a value.
4943 ;;
4944 ;; This extends to checking mismatches such as "return" and "return <value>"
4945 ;; used in the same function. Warnings are not emitted if inconsistent
4946 ;; returns exist in code that can be statically shown to be unreachable.
4947 ;; Ex.
4948 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4949 ;;
4950 ;; emits no warning. However if the loop had a break statement, then a
4951 ;; warning would be emitted.
4952 ;;
4953 ;; The consistency analysis looks at control structures such as loops, ifs,
4954 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4955 ;; warns the user about an inconsistent set of termination possibilities.
4956 ;;
4957 ;; These flags enumerate the possible ways a statement/function can
4958 ;; terminate. These flags are used by endCheck() and by the Parser to
4959 ;; detect inconsistent return usage.
4960 ;;
4961 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4962 ;; able to execute (example: throw, continue)
4963 ;;
4964 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4965 ;; next one. Statement such as return dont. A compound statement may have
4966 ;; some branch that drops off control to the next statement.
4967 ;;
4968 ;; END_RETURNS indicates that the statement can return with no value.
4969 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4970 ;;
4971 ;; A compound statement such as
4972 ;; if (condition) {
4973 ;; return value;
4974 ;; }
4975 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4976
4977 (defconst js2-END_UNREACHED 0)
4978 (defconst js2-END_DROPS_OFF 1)
4979 (defconst js2-END_RETURNS 2)
4980 (defconst js2-END_RETURNS_VALUE 4)
4981 (defconst js2-END_YIELDS 8)
4982
4983 (defun js2-has-consistent-return-usage (node)
4984 "Check that every return usage in a function body is consistent.
4985 Returns t if the function satisfies strict mode requirement."
4986 (let ((n (js2-end-check node)))
4987 ;; either it doesn't return a value in any branch...
4988 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4989 ;; or it returns a value (or is unreached) at every branch
4990 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4991 js2-END_RETURNS
4992 js2-END_YIELDS)))))
4993
4994 (defun js2-end-check-if (node)
4995 "Returns in the then and else blocks must be consistent with each other.
4996 If there is no else block, then the return statement can fall through.
4997 Returns logical OR of END_* flags"
4998 (let ((th (js2-if-node-then-part node))
4999 (el (js2-if-node-else-part node)))
5000 (if (null th)
5001 js2-END_UNREACHED
5002 (logior (js2-end-check th) (if el
5003 (js2-end-check el)
5004 js2-END_DROPS_OFF)))))
5005
5006 (defun js2-end-check-switch (node)
5007 "Consistency of return statements is checked between the case statements.
5008 If there is no default, then the switch can fall through. If there is a
5009 default, we check to see if all code paths in the default return or if
5010 there is a code path that can fall through.
5011 Returns logical OR of END_* flags."
5012 (let ((rv js2-END_UNREACHED)
5013 default-case)
5014 ;; examine the cases
5015 (catch 'break
5016 (dolist (c (js2-switch-node-cases node))
5017 (if (js2-case-node-expr c)
5018 (js2-set-flag rv (js2-end-check-block c))
5019 (setq default-case c)
5020 (throw 'break nil))))
5021 ;; we don't care how the cases drop into each other
5022 (js2-clear-flag rv js2-END_DROPS_OFF)
5023 ;; examine the default
5024 (js2-set-flag rv (if default-case
5025 (js2-end-check default-case)
5026 js2-END_DROPS_OFF))
5027 rv))
5028
5029 (defun js2-end-check-try (node)
5030 "If the block has a finally, return consistency is checked in the
5031 finally block. If all code paths in the finally return, then the
5032 returns in the try-catch blocks don't matter. If there is a code path
5033 that does not return or if there is no finally block, the returns
5034 of the try and catch blocks are checked for mismatch.
5035 Returns logical OR of END_* flags."
5036 (let ((finally (js2-try-node-finally-block node))
5037 rv)
5038 ;; check the finally if it exists
5039 (setq rv (if finally
5040 (js2-end-check (js2-finally-node-body finally))
5041 js2-END_DROPS_OFF))
5042 ;; If the finally block always returns, then none of the returns
5043 ;; in the try or catch blocks matter.
5044 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5045 (js2-clear-flag rv js2-END_DROPS_OFF)
5046 ;; examine the try block
5047 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5048 ;; check each catch block
5049 (dolist (cb (js2-try-node-catch-clauses node))
5050 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5051 rv))
5052
5053 (defun js2-end-check-loop (node)
5054 "Return statement in the loop body must be consistent. The default
5055 assumption for any kind of a loop is that it will eventually terminate.
5056 The only exception is a loop with a constant true condition. Code that
5057 follows such a loop is examined only if one can statically determine
5058 that there is a break out of the loop.
5059
5060 for(... ; ... ; ...) {}
5061 for(... in ... ) {}
5062 while(...) { }
5063 do { } while(...)
5064
5065 Returns logical OR of END_* flags."
5066 (let ((rv (js2-end-check (js2-loop-node-body node)))
5067 (condition (cond
5068 ((js2-while-node-p node)
5069 (js2-while-node-condition node))
5070 ((js2-do-node-p node)
5071 (js2-do-node-condition node))
5072 ((js2-for-node-p node)
5073 (js2-for-node-condition node)))))
5074
5075 ;; check to see if the loop condition is always true
5076 (if (and condition
5077 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5078 (js2-clear-flag rv js2-END_DROPS_OFF))
5079
5080 ;; look for effect of breaks
5081 (js2-set-flag rv (js2-node-get-prop node
5082 'CONTROL_BLOCK_PROP
5083 js2-END_UNREACHED))
5084 rv))
5085
5086 (defun js2-end-check-block (node)
5087 "A general block of code is examined statement by statement.
5088 If any statement (even a compound one) returns in all branches, then
5089 subsequent statements are not examined.
5090 Returns logical OR of END_* flags."
5091 (let* ((rv js2-END_DROPS_OFF)
5092 (kids (js2-block-node-kids node))
5093 (n (car kids)))
5094 ;; Check each statment. If the statement can continue onto the next
5095 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5096 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5097 (js2-clear-flag rv js2-END_DROPS_OFF)
5098 (js2-set-flag rv (js2-end-check n))
5099 (setq kids (cdr kids)
5100 n (car kids)))
5101 rv))
5102
5103 (defun js2-end-check-label (node)
5104 "A labeled statement implies that there may be a break to the label.
5105 The function processes the labeled statement and then checks the
5106 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5107 particular label.
5108 Returns logical OR of END_* flags."
5109 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5110 (logior rv (js2-node-get-prop node
5111 'CONTROL_BLOCK_PROP
5112 js2-END_UNREACHED))))
5113
5114 (defun js2-end-check-break (node)
5115 "When a break is encountered annotate the statement being broken
5116 out of by setting its CONTROL_BLOCK_PROP property.
5117 Returns logical OR of END_* flags."
5118 (and (js2-break-node-target node)
5119 (js2-node-set-prop (js2-break-node-target node)
5120 'CONTROL_BLOCK_PROP
5121 js2-END_DROPS_OFF))
5122 js2-END_UNREACHED)
5123
5124 (defun js2-end-check (node)
5125 "Examine the body of a function, doing a basic reachability analysis.
5126 Returns a combination of flags END_* flags that indicate
5127 how the function execution can terminate. These constitute only the
5128 pessimistic set of termination conditions. It is possible that at
5129 runtime certain code paths will never be actually taken. Hence this
5130 analysis will flag errors in cases where there may not be errors.
5131 Returns logical OR of END_* flags"
5132 (let (kid)
5133 (cond
5134 ((js2-break-node-p node)
5135 (js2-end-check-break node))
5136 ((js2-expr-stmt-node-p node)
5137 (if (setq kid (js2-expr-stmt-node-expr node))
5138 (js2-end-check kid)
5139 js2-END_DROPS_OFF))
5140 ((or (js2-continue-node-p node)
5141 (js2-throw-node-p node))
5142 js2-END_UNREACHED)
5143 ((js2-return-node-p node)
5144 (if (setq kid (js2-return-node-retval node))
5145 js2-END_RETURNS_VALUE
5146 js2-END_RETURNS))
5147 ((js2-loop-node-p node)
5148 (js2-end-check-loop node))
5149 ((js2-switch-node-p node)
5150 (js2-end-check-switch node))
5151 ((js2-labeled-stmt-node-p node)
5152 (js2-end-check-label node))
5153 ((js2-if-node-p node)
5154 (js2-end-check-if node))
5155 ((js2-try-node-p node)
5156 (js2-end-check-try node))
5157 ((js2-block-node-p node)
5158 (if (null (js2-block-node-kids node))
5159 js2-END_DROPS_OFF
5160 (js2-end-check-block node)))
5161 ((js2-yield-node-p node)
5162 js2-END_YIELDS)
5163 (t
5164 js2-END_DROPS_OFF))))
5165
5166 (defun js2-always-defined-boolean-p (node)
5167 "Check if NODE always evaluates to true or false in boolean context.
5168 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5169 nor always false."
5170 (let ((tt (js2-node-type node))
5171 num)
5172 (cond
5173 ((or (= tt js2-FALSE) (= tt js2-NULL))
5174 'ALWAYS_FALSE)
5175 ((= tt js2-TRUE)
5176 'ALWAYS_TRUE)
5177 ((= tt js2-NUMBER)
5178 (setq num (js2-number-node-num-value node))
5179 (if (and (not (eq num 0.0e+NaN))
5180 (not (zerop num)))
5181 'ALWAYS_TRUE
5182 'ALWAYS_FALSE))
5183 (t
5184 nil))))
5185
5186 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5187 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5188
5189 (defvar js2-tokens nil
5190 "List of all defined token names.") ; initialized in `js2-token-names'
5191
5192 (defconst js2-token-names
5193 (let* ((names (make-vector js2-num-tokens -1))
5194 (case-fold-search nil) ; only match js2-UPPER_CASE
5195 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5196 (loop for sym in syms
5197 for i from 0
5198 do
5199 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5200 (not (boundp sym)))
5201 (aset names (symbol-value sym) ; code, e.g. 152
5202 (downcase
5203 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5204 (push sym js2-tokens)))
5205 names)
5206 "Vector mapping int values to token string names, sans `js2-' prefix.")
5207
5208 (defun js2-token-name (tok)
5209 "Return a string name for TOK, a token symbol or code.
5210 Signals an error if it's not a recognized token."
5211 (let ((code tok))
5212 (if (symbolp tok)
5213 (setq code (symbol-value tok)))
5214 (if (eq code -1)
5215 "ERROR"
5216 (if (and (numberp code)
5217 (not (minusp code))
5218 (< code js2-num-tokens))
5219 (aref js2-token-names code)
5220 (error "Invalid token: %s" code)))))
5221
5222 (defsubst js2-token-sym (tok)
5223 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5224 (intern (js2-token-name tok)))
5225
5226 (defconst js2-token-codes
5227 (let ((table (make-hash-table :test 'eq :size 256)))
5228 (loop for name across js2-token-names
5229 for sym = (intern (concat "js2-" (upcase name)))
5230 do
5231 (puthash sym (symbol-value sym) table))
5232 ;; clean up a few that are "wrong" in Rhino's token codes
5233 (puthash 'js2-DELETE js2-DELPROP table)
5234 table)
5235 "Hashtable mapping token symbols to their bytecodes.")
5236
5237 (defsubst js2-token-code (sym)
5238 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5239 (or (gethash sym js2-token-codes)
5240 (error "Invalid token symbol: %s " sym))) ; signal code bug
5241
5242 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5243 (setq js2-token-end js2-ts-cursor)
5244 (js2-report-error msg nil
5245 (or beg js2-token-beg)
5246 (or len (- js2-token-end js2-token-beg)))
5247 (unless no-throw
5248 (throw 'return js2-ERROR)))
5249
5250 (defsubst js2-get-string-from-buffer ()
5251 "Reverse the char accumulator and return it as a string."
5252 (setq js2-token-end js2-ts-cursor)
5253 (if js2-ts-string-buffer
5254 (apply #'string (nreverse js2-ts-string-buffer))
5255 ""))
5256
5257 ;; TODO: could potentially avoid a lot of consing by allocating a
5258 ;; char buffer the way Rhino does.
5259 (defsubst js2-add-to-string (c)
5260 (push c js2-ts-string-buffer))
5261
5262 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5263 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5264 ;; any other character: when it's not part of the current token, we
5265 ;; unget it, allowing it to be read again by the following call.
5266 (defsubst js2-unget-char ()
5267 (decf js2-ts-cursor))
5268
5269 ;; Rhino distinguishes \r and \n line endings. We don't need to
5270 ;; because we only scan from Emacs buffers, which always use \n.
5271 (defsubst js2-get-char ()
5272 "Read and return the next character from the input buffer.
5273 Increments `js2-ts-lineno' if the return value is a newline char.
5274 Updates `js2-ts-cursor' to the point after the returned char.
5275 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5276 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5277 (let (c)
5278 ;; check for end of buffer
5279 (if (>= js2-ts-cursor (point-max))
5280 (setq js2-ts-hit-eof t
5281 js2-ts-cursor (1+ js2-ts-cursor)
5282 c js2-EOF_CHAR) ; return value
5283 ;; otherwise read next char
5284 (setq c (char-before (incf js2-ts-cursor)))
5285 ;; if we read a newline, update counters
5286 (if (= c ?\n)
5287 (setq js2-ts-line-start js2-ts-cursor
5288 js2-ts-lineno (1+ js2-ts-lineno)))
5289 ;; TODO: skip over format characters
5290 c)))
5291
5292 (defsubst js2-read-unicode-escape ()
5293 "Read a \\uNNNN sequence from the input.
5294 Assumes the ?\ and ?u have already been read.
5295 Returns the unicode character, or nil if it wasn't a valid character.
5296 Doesn't change the values of any scanner variables."
5297 ;; I really wish I knew a better way to do this, but I can't
5298 ;; find the Emacs function that takes a 16-bit int and converts
5299 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5300 ;; Have to first check that it's 4 hex characters or it may stop
5301 ;; the read early.
5302 (ignore-errors
5303 (let ((s (buffer-substring-no-properties js2-ts-cursor
5304 (+ 4 js2-ts-cursor))))
5305 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5306 (read (concat "?\\u" s))))))
5307
5308 (defsubst js2-match-char (test)
5309 "Consume and return next character if it matches TEST, a character.
5310 Returns nil and consumes nothing if TEST is not the next character."
5311 (let ((c (js2-get-char)))
5312 (if (eq c test)
5313 t
5314 (js2-unget-char)
5315 nil)))
5316
5317 (defsubst js2-peek-char ()
5318 (prog1
5319 (js2-get-char)
5320 (js2-unget-char)))
5321
5322 (defsubst js2-java-identifier-start-p (c)
5323 (or
5324 (memq c '(?$ ?_))
5325 (js2-char-uppercase-p c)
5326 (js2-char-lowercase-p c)))
5327
5328 (defsubst js2-java-identifier-part-p (c)
5329 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5330 ;; TODO: make me Unicode-friendly. See comments above.
5331 (or
5332 (memq c '(?$ ?_))
5333 (js2-char-uppercase-p c)
5334 (js2-char-lowercase-p c)
5335 (and (>= c ?0) (<= c ?9))))
5336
5337 (defsubst js2-alpha-p (c)
5338 (cond ((and (<= ?A c) (<= c ?Z)) t)
5339 ((and (<= ?a c) (<= c ?z)) t)
5340 (t nil)))
5341
5342 (defsubst js2-digit-p (c)
5343 (and (<= ?0 c) (<= c ?9)))
5344
5345 (defsubst js2-js-space-p (c)
5346 (if (<= c 127)
5347 (memq c '(#x20 #x9 #xB #xC #xD))
5348 (or
5349 (eq c #xA0)
5350 ;; TODO: change this nil to check for Unicode space character
5351 nil)))
5352
5353 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5354
5355 (defsubst js2-skip-line ()
5356 "Skip to end of line"
5357 (let (c)
5358 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5359 (js2-unget-char)
5360 (setq js2-token-end js2-ts-cursor)))
5361
5362 (defun js2-init-scanner (&optional buf line)
5363 "Create token stream for BUF starting on LINE.
5364 BUF defaults to current-buffer and line defaults to 1.
5365
5366 A buffer can only have one scanner active at a time, which yields
5367 dramatically simpler code than using a defstruct. If you need to
5368 have simultaneous scanners in a buffer, copy the regions to scan
5369 into temp buffers."
5370 (save-excursion
5371 (when buf
5372 (set-buffer buf))
5373 (setq js2-ts-dirty-line nil
5374 js2-ts-regexp-flags nil
5375 js2-ts-string ""
5376 js2-ts-number nil
5377 js2-ts-hit-eof nil
5378 js2-ts-line-start 0
5379 js2-ts-lineno (or line 1)
5380 js2-ts-line-end-char -1
5381 js2-ts-cursor (point-min)
5382 js2-ts-is-xml-attribute nil
5383 js2-ts-xml-is-tag-content nil
5384 js2-ts-xml-open-tags-count 0
5385 js2-ts-string-buffer nil)))
5386
5387 ;; This function uses the cached op, string and number fields in
5388 ;; TokenStream; if getToken has been called since the passed token
5389 ;; was scanned, the op or string printed may be incorrect.
5390 (defun js2-token-to-string (token)
5391 ;; Not sure where this function is used in Rhino. Not tested.
5392 (if (not js2-debug-print-trees)
5393 ""
5394 (let ((name (js2-token-name token)))
5395 (cond
5396 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5397 (concat name " `" js2-ts-string "'"))
5398 ((eq token js2-NUMBER)
5399 (format "NUMBER %g" js2-ts-number))
5400 (t
5401 name)))))
5402
5403 (defconst js2-keywords
5404 '(break
5405 case catch const continue
5406 debugger default delete do
5407 else enum
5408 false finally for function
5409 if in instanceof import
5410 let
5411 new null
5412 return
5413 switch
5414 this throw true try typeof
5415 var void
5416 while with
5417 yield))
5418
5419 ;; Token names aren't exactly the same as the keywords, unfortunately.
5420 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5421 (defconst js2-kwd-tokens
5422 (let ((table (make-vector js2-num-tokens nil))
5423 (tokens
5424 (list js2-BREAK
5425 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5426 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5427 js2-ELSE
5428 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5429 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5430 js2-LET
5431 js2-NEW js2-NULL
5432 js2-RETURN
5433 js2-SWITCH
5434 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5435 js2-VAR
5436 js2-WHILE js2-WITH
5437 js2-YIELD)))
5438 (dolist (i tokens)
5439 (aset table i 'font-lock-keyword-face))
5440 (aset table js2-STRING 'font-lock-string-face)
5441 (aset table js2-REGEXP 'font-lock-string-face)
5442 (aset table js2-COMMENT 'font-lock-comment-face)
5443 (aset table js2-THIS 'font-lock-builtin-face)
5444 (aset table js2-VOID 'font-lock-constant-face)
5445 (aset table js2-NULL 'font-lock-constant-face)
5446 (aset table js2-TRUE 'font-lock-constant-face)
5447 (aset table js2-FALSE 'font-lock-constant-face)
5448 table)
5449 "Vector whose values are non-nil for tokens that are keywords.
5450 The values are default faces to use for highlighting the keywords.")
5451
5452 (defconst js2-reserved-words
5453 '(abstract
5454 boolean byte
5455 char class
5456 double
5457 enum export extends
5458 final float
5459 goto
5460 implements import int interface
5461 long
5462 native
5463 package private protected public
5464 short static super synchronized
5465 throws transient
5466 volatile))
5467
5468 (defconst js2-keyword-names
5469 (let ((table (make-hash-table :test 'equal)))
5470 (loop for k in js2-keywords
5471 do (puthash
5472 (symbol-name k) ; instanceof
5473 (intern (concat "js2-"
5474 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5475 table))
5476 table)
5477 "JavaScript keywords by name, mapped to their symbols.")
5478
5479 (defconst js2-reserved-word-names
5480 (let ((table (make-hash-table :test 'equal)))
5481 (loop for k in js2-reserved-words
5482 do
5483 (puthash (symbol-name k) 'js2-RESERVED table))
5484 table)
5485 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5486
5487 (defsubst js2-collect-string (buf)
5488 "Convert BUF, a list of chars, to a string.
5489 Reverses BUF before converting."
5490 (cond
5491 ((stringp buf)
5492 buf)
5493 ((null buf) ; for emacs21 compat
5494 "")
5495 (t
5496 (if buf
5497 (apply #'string (nreverse buf))
5498 ""))))
5499
5500 (defun js2-string-to-keyword (s)
5501 "Return token for S, a string, if S is a keyword or reserved word.
5502 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5503 (or (gethash s js2-keyword-names)
5504 (gethash s js2-reserved-word-names)))
5505
5506 (defsubst js2-ts-set-char-token-bounds ()
5507 "Used when next token is one character."
5508 (setq js2-token-beg (1- js2-ts-cursor)
5509 js2-token-end js2-ts-cursor))
5510
5511 (defsubst js2-ts-return (token)
5512 "Return an N-character TOKEN from `js2-get-token'.
5513 Updates `js2-token-end' accordingly."
5514 (setq js2-token-end js2-ts-cursor)
5515 (throw 'return token))
5516
5517 (defsubst js2-x-digit-to-int (c accumulator)
5518 "Build up a hex number.
5519 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5520 corresponding number. Otherwise return -1."
5521 (catch 'return
5522 (catch 'check
5523 ;; Use 0..9 < A..Z < a..z
5524 (cond
5525 ((<= c ?9)
5526 (decf c ?0)
5527 (if (<= 0 c)
5528 (throw 'check nil)))
5529 ((<= c ?F)
5530 (when (<= ?A c)
5531 (decf c (- ?A 10))
5532 (throw 'check nil)))
5533 ((<= c ?f)
5534 (when (<= ?a c)
5535 (decf c (- ?a 10))
5536 (throw 'check nil))))
5537 (throw 'return -1))
5538 (logior c (lsh accumulator 4))))
5539
5540 (defun js2-get-token ()
5541 "Return next JavaScript token, an int such as js2-RETURN."
5542 (let (c
5543 c1
5544 identifier-start
5545 is-unicode-escape-start
5546 contains-escape
5547 escape-val
5548 escape-start
5549 str
5550 result
5551 base
5552 is-integer
5553 quote-char
5554 val
5555 look-for-slash
5556 continue)
5557 (catch 'return
5558 (while t
5559 ;; Eat whitespace, possibly sensitive to newlines.
5560 (setq continue t)
5561 (while continue
5562 (setq c (js2-get-char))
5563 (cond
5564 ((eq c js2-EOF_CHAR)
5565 (js2-ts-set-char-token-bounds)
5566 (throw 'return js2-EOF))
5567 ((eq c ?\n)
5568 (js2-ts-set-char-token-bounds)
5569 (setq js2-ts-dirty-line nil)
5570 (throw 'return js2-EOL))
5571 ((not (js2-js-space-p c))
5572 (if (/= c ?-) ; in case end of HTML comment
5573 (setq js2-ts-dirty-line t))
5574 (setq continue nil))))
5575 ;; Assume the token will be 1 char - fixed up below.
5576 (js2-ts-set-char-token-bounds)
5577 (when (eq c ?@)
5578 (throw 'return js2-XMLATTR))
5579 ;; identifier/keyword/instanceof?
5580 ;; watch out for starting with a <backslash>
5581 (cond
5582 ((eq c ?\\)
5583 (setq c (js2-get-char))
5584 (if (eq c ?u)
5585 (setq identifier-start t
5586 is-unicode-escape-start t
5587 js2-ts-string-buffer nil)
5588 (setq identifier-start nil)
5589 (js2-unget-char)
5590 (setq c ?\\)))
5591 (t
5592 (when (setq identifier-start (js2-java-identifier-start-p c))
5593 (setq js2-ts-string-buffer nil)
5594 (js2-add-to-string c))))
5595 (when identifier-start
5596 (setq contains-escape is-unicode-escape-start)
5597 (catch 'break
5598 (while t
5599 (if is-unicode-escape-start
5600 ;; strictly speaking we should probably push-back
5601 ;; all the bad characters if the <backslash>uXXXX
5602 ;; sequence is malformed. But since there isn't a
5603 ;; correct context(is there?) for a bad Unicode
5604 ;; escape sequence in an identifier, we can report
5605 ;; an error here.
5606 (progn
5607 (setq escape-val 0)
5608 (dotimes (i 4)
5609 (setq c (js2-get-char)
5610 escape-val (js2-x-digit-to-int c escape-val))
5611 ;; Next check takes care of c < 0 and bad escape
5612 (if (minusp escape-val)
5613 (throw 'break nil)))
5614 (if (minusp escape-val)
5615 (js2-report-scan-error "msg.invalid.escape" t))
5616 (js2-add-to-string escape-val)
5617 (setq is-unicode-escape-start nil))
5618 (setq c (js2-get-char))
5619 (cond
5620 ((eq c ?\\)
5621 (setq c (js2-get-char))
5622 (if (eq c ?u)
5623 (setq is-unicode-escape-start t
5624 contains-escape t)
5625 (js2-report-scan-error "msg.illegal.character" t)))
5626 (t
5627 (if (or (eq c js2-EOF_CHAR)
5628 (not (js2-java-identifier-part-p c)))
5629 (throw 'break nil))
5630 (js2-add-to-string c))))))
5631 (js2-unget-char)
5632 (setq str (js2-get-string-from-buffer))
5633 (unless contains-escape
5634 ;; OPT we shouldn't have to make a string (object!) to
5635 ;; check if it's a keyword.
5636 ;; Return the corresponding token if it's a keyword
5637 (when (setq result (js2-string-to-keyword str))
5638 (if (and (< js2-language-version 170)
5639 (memq result '(js2-LET js2-YIELD)))
5640 ;; LET and YIELD are tokens only in 1.7 and later
5641 (setq result 'js2-NAME))
5642 (if (not (eq result 'js2-RESERVED))
5643 (throw 'return (js2-token-code result)))
5644 (js2-report-warning "msg.reserved.keyword" str)))
5645 ;; If we want to intern these as Rhino does, just use (intern str)
5646 (setq js2-ts-string str)
5647 (throw 'return js2-NAME)) ; end identifier/kwd check
5648 ;; is it a number?
5649 (when (or (js2-digit-p c)
5650 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5651 (setq js2-ts-string-buffer nil
5652 base 10)
5653 (when (eq c ?0)
5654 (setq c (js2-get-char))
5655 (cond
5656 ((or (eq c ?x) (eq c ?X))
5657 (setq base 16)
5658 (setq c (js2-get-char)))
5659 ((js2-digit-p c)
5660 (setq base 8))
5661 (t
5662 (js2-add-to-string ?0))))
5663 (if (eq base 16)
5664 (while (<= 0 (js2-x-digit-to-int c 0))
5665 (js2-add-to-string c)
5666 (setq c (js2-get-char)))
5667 (while (and (<= ?0 c) (<= c ?9))
5668 ;; We permit 08 and 09 as decimal numbers, which
5669 ;; makes our behavior a superset of the ECMA
5670 ;; numeric grammar. We might not always be so
5671 ;; permissive, so we warn about it.
5672 (when (and (eq base 8) (>= c ?8))
5673 (js2-report-warning "msg.bad.octal.literal"
5674 (if (eq c ?8) "8" "9"))
5675 (setq base 10))
5676 (js2-add-to-string c)
5677 (setq c (js2-get-char))))
5678 (setq is-integer t)
5679 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5680 (setq is-integer nil)
5681 (when (eq c ?.)
5682 (loop do
5683 (js2-add-to-string c)
5684 (setq c (js2-get-char))
5685 while (js2-digit-p c)))
5686 (when (memq c '(?e ?E))
5687 (js2-add-to-string c)
5688 (setq c (js2-get-char))
5689 (when (memq c '(?+ ?-))
5690 (js2-add-to-string c)
5691 (setq c (js2-get-char)))
5692 (unless (js2-digit-p c)
5693 (js2-report-scan-error "msg.missing.exponent" t))
5694 (loop do
5695 (js2-add-to-string c)
5696 (setq c (js2-get-char))
5697 while (js2-digit-p c))))
5698 (js2-unget-char)
5699 (setq js2-ts-string (js2-get-string-from-buffer)
5700 js2-ts-number
5701 (if (and (eq base 10) (not is-integer))
5702 (string-to-number js2-ts-string)
5703 ;; TODO: call runtime number-parser. Some of it is in
5704 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5705 (string-to-number js2-ts-string)))
5706 (throw 'return js2-NUMBER))
5707 ;; is it a string?
5708 (when (memq c '(?\" ?\'))
5709 ;; We attempt to accumulate a string the fast way, by
5710 ;; building it directly out of the reader. But if there
5711 ;; are any escaped characters in the string, we revert to
5712 ;; building it out of a string buffer.
5713 (setq quote-char c
5714 js2-ts-string-buffer nil
5715 c (js2-get-char))
5716 (catch 'break
5717 (while (/= c quote-char)
5718 (catch 'continue
5719 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5720 (js2-unget-char)
5721 (setq js2-token-end js2-ts-cursor)
5722 (js2-report-error "msg.unterminated.string.lit")
5723 (throw 'return js2-STRING))
5724 (when (eq c ?\\)
5725 ;; We've hit an escaped character
5726 (setq c (js2-get-char))
5727 (case c
5728 (?b (setq c ?\b))
5729 (?f (setq c ?\f))
5730 (?n (setq c ?\n))
5731 (?r (setq c ?\r))
5732 (?t (setq c ?\t))
5733 (?v (setq c ?\v))
5734 (?u
5735 (setq c1 (js2-read-unicode-escape))
5736 (if js2-parse-ide-mode
5737 (if c1
5738 (progn
5739 ;; just copy the string in IDE-mode
5740 (js2-add-to-string ?\\)
5741 (js2-add-to-string ?u)
5742 (dotimes (i 3)
5743 (js2-add-to-string (js2-get-char)))
5744 (setq c (js2-get-char))) ; added at end of loop
5745 ;; flag it as an invalid escape
5746 (js2-report-warning "msg.invalid.escape"
5747 nil (- js2-ts-cursor 2) 6))
5748 ;; Get 4 hex digits; if the u escape is not
5749 ;; followed by 4 hex digits, use 'u' + the
5750 ;; literal character sequence that follows.
5751 (js2-add-to-string ?u)
5752 (setq escape-val 0)
5753 (dotimes (i 4)
5754 (setq c (js2-get-char)
5755 escape-val (js2-x-digit-to-int c escape-val))
5756 (if (minusp escape-val)
5757 (throw 'continue nil))
5758 (js2-add-to-string c))
5759 ;; prepare for replace of stored 'u' sequence by escape value
5760 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5761 c escape-val)))
5762 (?x
5763 ;; Get 2 hex digits, defaulting to 'x'+literal
5764 ;; sequence, as above.
5765 (setq c (js2-get-char)
5766 escape-val (js2-x-digit-to-int c 0))
5767 (if (minusp escape-val)
5768 (progn
5769 (js2-add-to-string ?x)
5770 (throw 'continue nil))
5771 (setq c1 c
5772 c (js2-get-char)
5773 escape-val (js2-x-digit-to-int c escape-val))
5774 (if (minusp escape-val)
5775 (progn
5776 (js2-add-to-string ?x)
5777 (js2-add-to-string c1)
5778 (throw 'continue nil))
5779 ;; got 2 hex digits
5780 (setq c escape-val))))
5781 (?\n
5782 ;; Remove line terminator after escape to follow
5783 ;; SpiderMonkey and C/C++
5784 (setq c (js2-get-char))
5785 (throw 'continue nil))
5786 (t
5787 (when (and (<= ?0 c) (< c ?8))
5788 (setq val (- c ?0)
5789 c (js2-get-char))
5790 (when (and (<= ?0 c) (< c ?8))
5791 (setq val (- (+ (* 8 val) c) ?0)
5792 c (js2-get-char))
5793 (when (and (<= ?0 c)
5794 (< c ?8)
5795 (< val #o37))
5796 ;; c is 3rd char of octal sequence only
5797 ;; if the resulting val <= 0377
5798 (setq val (- (+ (* 8 val) c) ?0)
5799 c (js2-get-char))))
5800 (js2-unget-char)
5801 (setq c val)))))
5802 (js2-add-to-string c)
5803 (setq c (js2-get-char)))))
5804 (setq js2-ts-string (js2-get-string-from-buffer))
5805 (throw 'return js2-STRING))
5806 (case c
5807 (?\;
5808 (throw 'return js2-SEMI))
5809 (?\[
5810 (throw 'return js2-LB))
5811 (?\]
5812 (throw 'return js2-RB))
5813 (?{
5814 (throw 'return js2-LC))
5815 (?}
5816 (throw 'return js2-RC))
5817 (?\(
5818 (throw 'return js2-LP))
5819 (?\)
5820 (throw 'return js2-RP))
5821 (?,
5822 (throw 'return js2-COMMA))
5823 (??
5824 (throw 'return js2-HOOK))
5825 (?:
5826 (if (js2-match-char ?:)
5827 (js2-ts-return js2-COLONCOLON)
5828 (throw 'return js2-COLON)))
5829 (?.
5830 (if (js2-match-char ?.)
5831 (js2-ts-return js2-DOTDOT)
5832 (if (js2-match-char ?\()
5833 (js2-ts-return js2-DOTQUERY)
5834 (throw 'return js2-DOT))))
5835 (?|
5836 (if (js2-match-char ?|)
5837 (throw 'return js2-OR)
5838 (if (js2-match-char ?=)
5839 (js2-ts-return js2-ASSIGN_BITOR)
5840 (throw 'return js2-BITOR))))
5841 (?^
5842 (if (js2-match-char ?=)
5843 (js2-ts-return js2-ASSIGN_BITOR)
5844 (throw 'return js2-BITXOR)))
5845 (?&
5846 (if (js2-match-char ?&)
5847 (throw 'return js2-AND)
5848 (if (js2-match-char ?=)
5849 (js2-ts-return js2-ASSIGN_BITAND)
5850 (throw 'return js2-BITAND))))
5851 (?=
5852 (if (js2-match-char ?=)
5853 (if (js2-match-char ?=)
5854 (js2-ts-return js2-SHEQ)
5855 (throw 'return js2-EQ))
5856 (throw 'return js2-ASSIGN)))
5857 (?!
5858 (if (js2-match-char ?=)
5859 (if (js2-match-char ?=)
5860 (js2-ts-return js2-SHNE)
5861 (js2-ts-return js2-NE))
5862 (throw 'return js2-NOT)))
5863 (?<
5864 ;; NB:treat HTML begin-comment as comment-till-eol
5865 (when (js2-match-char ?!)
5866 (when (js2-match-char ?-)
5867 (when (js2-match-char ?-)
5868 (js2-skip-line)
5869 (setq js2-ts-comment-type 'html)
5870 (throw 'return js2-COMMENT)))
5871 (js2-unget-char))
5872 (if (js2-match-char ?<)
5873 (if (js2-match-char ?=)
5874 (js2-ts-return js2-ASSIGN_LSH)
5875 (js2-ts-return js2-LSH))
5876 (if (js2-match-char ?=)
5877 (js2-ts-return js2-LE)
5878 (throw 'return js2-LT))))
5879 (?>
5880 (if (js2-match-char ?>)
5881 (if (js2-match-char ?>)
5882 (if (js2-match-char ?=)
5883 (js2-ts-return js2-ASSIGN_URSH)
5884 (js2-ts-return js2-URSH))
5885 (if (js2-match-char ?=)
5886 (js2-ts-return js2-ASSIGN_RSH)
5887 (js2-ts-return js2-RSH)))
5888 (if (js2-match-char ?=)
5889 (js2-ts-return js2-GE)
5890 (throw 'return js2-GT))))
5891 (?*
5892 (if (js2-match-char ?=)
5893 (js2-ts-return js2-ASSIGN_MUL)
5894 (throw 'return js2-MUL)))
5895 (?/
5896 ;; is it a // comment?
5897 (when (js2-match-char ?/)
5898 (setq js2-token-beg (- js2-ts-cursor 2))
5899 (js2-skip-line)
5900 (setq js2-ts-comment-type 'line)
5901 ;; include newline so highlighting goes to end of window
5902 (incf js2-token-end)
5903 (throw 'return js2-COMMENT))
5904 ;; is it a /* comment?
5905 (when (js2-match-char ?*)
5906 (setq look-for-slash nil
5907 js2-token-beg (- js2-ts-cursor 2)
5908 js2-ts-comment-type
5909 (if (js2-match-char ?*)
5910 (progn
5911 (setq look-for-slash t)
5912 'jsdoc)
5913 'block))
5914 (while t
5915 (setq c (js2-get-char))
5916 (cond
5917 ((eq c js2-EOF_CHAR)
5918 (setq js2-token-end (1- js2-ts-cursor))
5919 (js2-report-error "msg.unterminated.comment")
5920 (throw 'return js2-COMMENT))
5921 ((eq c ?*)
5922 (setq look-for-slash t))
5923 ((eq c ?/)
5924 (if look-for-slash
5925 (js2-ts-return js2-COMMENT)))
5926 (t
5927 (setq look-for-slash nil
5928 js2-token-end js2-ts-cursor)))))
5929 (if (js2-match-char ?=)
5930 (js2-ts-return js2-ASSIGN_DIV)
5931 (throw 'return js2-DIV)))
5932 (?#
5933 (when js2-skip-preprocessor-directives
5934 (js2-skip-line)
5935 (setq js2-ts-comment-type 'preprocessor
5936 js2-token-end js2-ts-cursor)
5937 (throw 'return js2-COMMENT))
5938 (throw 'return js2-ERROR))
5939 (?%
5940 (if (js2-match-char ?=)
5941 (js2-ts-return js2-ASSIGN_MOD)
5942 (throw 'return js2-MOD)))
5943 (?~
5944 (throw 'return js2-BITNOT))
5945 (?+
5946 (if (js2-match-char ?=)
5947 (js2-ts-return js2-ASSIGN_ADD)
5948 (if (js2-match-char ?+)
5949 (js2-ts-return js2-INC)
5950 (throw 'return js2-ADD))))
5951 (?-
5952 (cond
5953 ((js2-match-char ?=)
5954 (setq c js2-ASSIGN_SUB))
5955 ((js2-match-char ?-)
5956 (unless js2-ts-dirty-line
5957 ;; treat HTML end-comment after possible whitespace
5958 ;; after line start as comment-until-eol
5959 (when (js2-match-char ?>)
5960 (js2-skip-line)
5961 (setq js2-ts-comment-type 'html)
5962 (throw 'return js2-COMMENT)))
5963 (setq c js2-DEC))
5964 (t
5965 (setq c js2-SUB)))
5966 (setq js2-ts-dirty-line t)
5967 (js2-ts-return c))
5968 (otherwise
5969 (js2-report-scan-error "msg.illegal.character")))))))
5970
5971 (defun js2-read-regexp (start-token)
5972 "Called by parser when it gets / or /= in literal context."
5973 (let (c
5974 err
5975 in-class ; inside a '[' .. ']' character-class
5976 flags
5977 (continue t))
5978 (setq js2-token-beg js2-ts-cursor
5979 js2-ts-string-buffer nil
5980 js2-ts-regexp-flags nil)
5981 (if (eq start-token js2-ASSIGN_DIV)
5982 ;; mis-scanned /=
5983 (js2-add-to-string ?=)
5984 (if (not (eq start-token js2-DIV))
5985 (error "failed assertion")))
5986 (while (and (not err)
5987 (or (/= (setq c (js2-get-char)) ?/)
5988 in-class))
5989 (cond
5990 ((or (= c ?\n)
5991 (= c js2-EOF_CHAR))
5992 (setq js2-token-end (1- js2-ts-cursor)
5993 err t
5994 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5995 (js2-report-error "msg.unterminated.re.lit"))
5996 (t (cond
5997 ((= c ?\\)
5998 (js2-add-to-string c)
5999 (setq c (js2-get-char)))
6000 ((= c ?\[)
6001 (setq in-class t))
6002 ((= c ?\])
6003 (setq in-class nil)))
6004 (js2-add-to-string c))))
6005 (unless err
6006 (while continue
6007 (cond
6008 ((js2-match-char ?g)
6009 (push ?g flags))
6010 ((js2-match-char ?i)
6011 (push ?i flags))
6012 ((js2-match-char ?m)
6013 (push ?m flags))
6014 (t
6015 (setq continue nil))))
6016 (if (js2-alpha-p (js2-peek-char))
6017 (js2-report-scan-error "msg.invalid.re.flag" t
6018 js2-ts-cursor 1))
6019 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6020 js2-ts-regexp-flags (js2-collect-string flags)
6021 js2-token-end js2-ts-cursor)
6022 ;; tell `parse-partial-sexp' to ignore this range of chars
6023 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6024
6025 (defun js2-get-first-xml-token ()
6026 (setq js2-ts-xml-open-tags-count 0
6027 js2-ts-is-xml-attribute nil
6028 js2-ts-xml-is-tag-content nil)
6029 (js2-unget-char)
6030 (js2-get-next-xml-token))
6031
6032 (defsubst js2-xml-discard-string ()
6033 "Throw away the string in progress and flag an XML parse error."
6034 (setq js2-ts-string-buffer nil
6035 js2-ts-string nil)
6036 (js2-report-scan-error "msg.XML.bad.form" t))
6037
6038 (defun js2-get-next-xml-token ()
6039 (setq js2-ts-string-buffer nil ; for recording the XML
6040 js2-token-beg js2-ts-cursor)
6041 (let (c result)
6042 (setq result
6043 (catch 'return
6044 (while t
6045 (setq c (js2-get-char))
6046 (cond
6047 ((= c js2-EOF_CHAR)
6048 (throw 'return js2-ERROR))
6049 (js2-ts-xml-is-tag-content
6050 (case c
6051 (?>
6052 (js2-add-to-string c)
6053 (setq js2-ts-xml-is-tag-content nil
6054 js2-ts-is-xml-attribute nil))
6055 (?/
6056 (js2-add-to-string c)
6057 (when (eq ?> (js2-peek-char))
6058 (setq c (js2-get-char))
6059 (js2-add-to-string c)
6060 (setq js2-ts-xml-is-tag-content nil)
6061 (decf js2-ts-xml-open-tags-count)))
6062 (?{
6063 (js2-unget-char)
6064 (setq js2-ts-string (js2-get-string-from-buffer))
6065 (throw 'return js2-XML))
6066 ((?\' ?\")
6067 (js2-add-to-string c)
6068 (unless (js2-read-quoted-string c)
6069 (throw 'return js2-ERROR)))
6070 (?=
6071 (js2-add-to-string c)
6072 (setq js2-ts-is-xml-attribute t))
6073 ((? ?\t ?\r ?\n)
6074 (js2-add-to-string c))
6075 (t
6076 (js2-add-to-string c)
6077 (setq js2-ts-is-xml-attribute nil)))
6078 (when (and (not js2-ts-xml-is-tag-content)
6079 (zerop js2-ts-xml-open-tags-count))
6080 (setq js2-ts-string (js2-get-string-from-buffer))
6081 (throw 'return js2-XMLEND)))
6082 (t
6083 ;; else not tag content
6084 (case c
6085 (?<
6086 (js2-add-to-string c)
6087 (setq c (js2-peek-char))
6088 (case c
6089 (?!
6090 (setq c (js2-get-char)) ;; skip !
6091 (js2-add-to-string c)
6092 (setq c (js2-peek-char))
6093 (case c
6094 (?-
6095 (setq c (js2-get-char)) ;; skip -
6096 (js2-add-to-string c)
6097 (if (eq c ?-)
6098 (progn
6099 (js2-add-to-string c)
6100 (unless (js2-read-xml-comment)
6101 (throw 'return js2-ERROR)))
6102 (js2-xml-discard-string)
6103 (throw 'return js2-ERROR)))
6104 (?\[
6105 (setq c (js2-get-char)) ;; skip [
6106 (js2-add-to-string c)
6107 (if (and (= (js2-get-char) ?C)
6108 (= (js2-get-char) ?D)
6109 (= (js2-get-char) ?A)
6110 (= (js2-get-char) ?T)
6111 (= (js2-get-char) ?A)
6112 (= (js2-get-char) ?\[))
6113 (progn
6114 (js2-add-to-string ?C)
6115 (js2-add-to-string ?D)
6116 (js2-add-to-string ?A)
6117 (js2-add-to-string ?T)
6118 (js2-add-to-string ?A)
6119 (js2-add-to-string ?\[)
6120 (unless (js2-read-cdata)
6121 (throw 'return js2-ERROR)))
6122 (js2-xml-discard-string)
6123 (throw 'return js2-ERROR)))
6124 (t
6125 (unless (js2-read-entity)
6126 (throw 'return js2-ERROR))))
6127 ;; allow bare CDATA section
6128 ;; ex) let xml = <![CDATA[ foo bar baz ]]>;
6129 (when (zerop js2-ts-xml-open-tags-count)
6130 (throw 'return js2-XMLEND)))
6131 (??
6132 (setq c (js2-get-char)) ;; skip ?
6133 (js2-add-to-string c)
6134 (unless (js2-read-PI)
6135 (throw 'return js2-ERROR)))
6136 (?/
6137 ;; end tag
6138 (setq c (js2-get-char)) ;; skip /
6139 (js2-add-to-string c)
6140 (when (zerop js2-ts-xml-open-tags-count)
6141 (js2-xml-discard-string)
6142 (throw 'return js2-ERROR))
6143 (setq js2-ts-xml-is-tag-content t)
6144 (decf js2-ts-xml-open-tags-count))
6145 (t
6146 ;; start tag
6147 (setq js2-ts-xml-is-tag-content t)
6148 (incf js2-ts-xml-open-tags-count))))
6149 (?{
6150 (js2-unget-char)
6151 (setq js2-ts-string (js2-get-string-from-buffer))
6152 (throw 'return js2-XML))
6153 (t
6154 (js2-add-to-string c))))))))
6155 (setq js2-token-end js2-ts-cursor)
6156 result))
6157
6158 (defun js2-read-quoted-string (quote)
6159 (let (c)
6160 (catch 'return
6161 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6162 (js2-add-to-string c)
6163 (if (eq c quote)
6164 (throw 'return t)))
6165 (js2-xml-discard-string) ;; throw away string in progress
6166 nil)))
6167
6168 (defun js2-read-xml-comment ()
6169 (let ((c (js2-get-char)))
6170 (catch 'return
6171 (while (/= c js2-EOF_CHAR)
6172 (catch 'continue
6173 (js2-add-to-string c)
6174 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6175 (setq c (js2-get-char))
6176 (js2-add-to-string c)
6177 (if (eq (js2-peek-char) ?>)
6178 (progn
6179 (setq c (js2-get-char)) ;; skip >
6180 (js2-add-to-string c)
6181 (throw 'return t))
6182 (throw 'continue nil)))
6183 (setq c (js2-get-char))))
6184 (js2-xml-discard-string)
6185 nil)))
6186
6187 (defun js2-read-cdata ()
6188 (let ((c (js2-get-char)))
6189 (catch 'return
6190 (while (/= c js2-EOF_CHAR)
6191 (catch 'continue
6192 (js2-add-to-string c)
6193 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6194 (setq c (js2-get-char))
6195 (js2-add-to-string c)
6196 (if (eq (js2-peek-char) ?>)
6197 (progn
6198 (setq c (js2-get-char)) ;; Skip >
6199 (js2-add-to-string c)
6200 (throw 'return t))
6201 (throw 'continue nil)))
6202 (setq c (js2-get-char))))
6203 (js2-xml-discard-string)
6204 nil)))
6205
6206 (defun js2-read-entity ()
6207 (let ((decl-tags 1)
6208 c)
6209 (catch 'return
6210 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6211 (js2-add-to-string c)
6212 (case c
6213 (?<
6214 (incf decl-tags))
6215 (?>
6216 (decf decl-tags)
6217 (if (zerop decl-tags)
6218 (throw 'return t)))))
6219 (js2-xml-discard-string)
6220 nil)))
6221
6222 (defun js2-read-PI ()
6223 "Scan an XML processing instruction."
6224 (let (c)
6225 (catch 'return
6226 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6227 (js2-add-to-string c)
6228 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6229 (setq c (js2-get-char)) ;; Skip >
6230 (js2-add-to-string c)
6231 (throw 'return t)))
6232 (js2-xml-discard-string)
6233 nil)))
6234
6235 (defun js2-scanner-get-line ()
6236 "Return the text of the current scan line."
6237 (buffer-substring (point-at-bol) (point-at-eol)))
6238
6239 ;;; Highlighting
6240
6241 (defsubst js2-set-face (beg end face &optional record)
6242 "Fontify a region. If RECORD is non-nil, record for later."
6243 (when (plusp js2-highlight-level)
6244 (setq beg (min (point-max) beg)
6245 beg (max (point-min) beg)
6246 end (min (point-max) end)
6247 end (max (point-min) end))
6248 (if record
6249 (push (list beg end face) js2-mode-fontifications)
6250 (put-text-property beg end 'font-lock-face face))))
6251
6252 (defsubst js2-set-kid-face (pos kid len face)
6253 "Set-face on a child node.
6254 POS is absolute buffer position of parent.
6255 KID is the child node.
6256 LEN is the length to fontify.
6257 FACE is the face to fontify with."
6258 (js2-set-face (+ pos (js2-node-pos kid))
6259 (+ pos (js2-node-pos kid) (js2-node-len kid))
6260 face))
6261
6262 (defsubst js2-fontify-kwd (start length)
6263 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6264
6265 (defsubst js2-clear-face (beg end)
6266 (remove-text-properties beg end '(font-lock-face nil
6267 help-echo nil
6268 point-entered nil
6269 c-in-sws nil)))
6270
6271 (defconst js2-ecma-global-props
6272 (concat "^"
6273 (regexp-opt
6274 '("Infinity" "NaN" "undefined" "arguments") t)
6275 "$")
6276 "Value properties of the Ecma-262 Global Object.
6277 Shown at or above `js2-highlight-level' 2.")
6278
6279 ;; might want to add the name "arguments" to this list?
6280 (defconst js2-ecma-object-props
6281 (concat "^"
6282 (regexp-opt
6283 '("prototype" "__proto__" "__parent__") t)
6284 "$")
6285 "Value properties of the Ecma-262 Object constructor.
6286 Shown at or above `js2-highlight-level' 2.")
6287
6288 (defconst js2-ecma-global-funcs
6289 (concat
6290 "^"
6291 (regexp-opt
6292 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6293 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6294 "$")
6295 "Function properties of the Ecma-262 Global object.
6296 Shown at or above `js2-highlight-level' 2.")
6297
6298 (defconst js2-ecma-number-props
6299 (concat "^"
6300 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6301 "NEGATIVE_INFINITY"
6302 "POSITIVE_INFINITY") t)
6303 "$")
6304 "Properties of the Ecma-262 Number constructor.
6305 Shown at or above `js2-highlight-level' 2.")
6306
6307 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6308 "Properties of the Ecma-262 Date constructor.
6309 Shown at or above `js2-highlight-level' 2.")
6310
6311 (defconst js2-ecma-math-props
6312 (concat "^"
6313 (regexp-opt
6314 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6315 t)
6316 "$")
6317 "Properties of the Ecma-262 Math object.
6318 Shown at or above `js2-highlight-level' 2.")
6319
6320 (defconst js2-ecma-math-funcs
6321 (concat "^"
6322 (regexp-opt
6323 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6324 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6325 "$")
6326 "Function properties of the Ecma-262 Math object.
6327 Shown at or above `js2-highlight-level' 2.")
6328
6329 (defconst js2-ecma-function-props
6330 (concat
6331 "^"
6332 (regexp-opt
6333 '(;; properties of the Object prototype object
6334 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6335 "toLocaleString" "toString" "valueOf"
6336 ;; properties of the Function prototype object
6337 "apply" "call"
6338 ;; properties of the Array prototype object
6339 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6340 "splice" "unshift"
6341 ;; properties of the String prototype object
6342 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6343 "localeCompare" "match" "replace" "search" "split" "substring"
6344 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6345 "toUpperCase"
6346 ;; properties of the Number prototype object
6347 "toExponential" "toFixed" "toPrecision"
6348 ;; properties of the Date prototype object
6349 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6350 "getMinutes" "getMonth" "getSeconds" "getTime"
6351 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6352 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6353 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6354 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6355 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6356 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6357 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6358 "toTimeString" "toUTCString"
6359 ;; properties of the RegExp prototype object
6360 "exec" "test"
6361 ;; properties of the JSON prototype object
6362 "parse" "stringify"
6363 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6364 "toSource" "__defineGetter__" "__defineSetter__"
6365 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6366 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6367 t)
6368 "$")
6369 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6370 Shown at or above `js2-highlight-level' 3.")
6371
6372 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6373 (let ((target-name (and target
6374 (js2-name-node-p target)
6375 (js2-name-node-name target)))
6376 (prop-name (if prop (js2-name-node-name prop)))
6377 (level1 (>= js2-highlight-level 1))
6378 (level2 (>= js2-highlight-level 2))
6379 (level3 (>= js2-highlight-level 3))
6380 pos
6381 face)
6382 (when level2
6383 (if call-p
6384 (cond
6385 ((and target prop)
6386 (cond
6387 ((and level3 (string-match js2-ecma-function-props prop-name))
6388 (setq face 'font-lock-builtin-face))
6389 ((and target-name prop)
6390 (cond
6391 ((string= target-name "Date")
6392 (if (string-match js2-ecma-date-props prop-name)
6393 (setq face 'font-lock-builtin-face)))
6394 ((string= target-name "Math")
6395 (if (string-match js2-ecma-math-funcs prop-name)
6396 (setq face 'font-lock-builtin-face)))))))
6397 (prop
6398 (if (string-match js2-ecma-global-funcs prop-name)
6399 (setq face 'font-lock-builtin-face))))
6400 (cond
6401 ((and target prop)
6402 (cond
6403 ((string= target-name "Number")
6404 (if (string-match js2-ecma-number-props prop-name)
6405 (setq face 'font-lock-constant-face)))
6406 ((string= target-name "Math")
6407 (if (string-match js2-ecma-math-props prop-name)
6408 (setq face 'font-lock-constant-face)))))
6409 (prop
6410 (if (string-match js2-ecma-object-props prop-name)
6411 (setq face 'font-lock-constant-face)))))
6412 (when face
6413 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6414 (js2-node-pos prop))) ; relative
6415 (+ pos (js2-node-len prop))
6416 face 'record)))))
6417
6418 (defun js2-parse-highlight-member-expr-node (node)
6419 "Perform syntax highlighting of EcmaScript built-in properties.
6420 The variable `js2-highlight-level' governs this highighting."
6421 (let (face target prop name pos end parent call-p callee)
6422 (cond
6423 ;; case 1: simple name, e.g. foo
6424 ((js2-name-node-p node)
6425 (setq name (js2-name-node-name node))
6426 ;; possible for name to be nil in rare cases - saw it when
6427 ;; running js2-mode on an elisp buffer. Might as well try to
6428 ;; make it so js2-mode never barfs.
6429 (when name
6430 (setq face (if (string-match js2-ecma-global-props name)
6431 'font-lock-constant-face))
6432 (when face
6433 (setq pos (js2-node-pos node)
6434 end (+ pos (js2-node-len node)))
6435 (js2-set-face pos end face 'record))))
6436 ;; case 2: property access or function call
6437 ((or (js2-prop-get-node-p node)
6438 ;; highlight function call if expr is a prop-get node
6439 ;; or a plain name (i.e. unqualified function call)
6440 (and (setq call-p (js2-call-node-p node))
6441 (setq callee (js2-call-node-target node)) ; separate setq!
6442 (or (js2-prop-get-node-p callee)
6443 (js2-name-node-p callee))))
6444 (setq parent node
6445 node (if call-p callee node))
6446 (if (and call-p (js2-name-node-p callee))
6447 (setq prop callee)
6448 (setq target (js2-prop-get-node-left node)
6449 prop (js2-prop-get-node-right node)))
6450 (cond
6451 ((js2-name-node-p target)
6452 (if (js2-name-node-p prop)
6453 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6454 (js2-parse-highlight-prop-get parent target prop call-p)
6455 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6456 (js2-parse-highlight-prop-get parent target nil call-p)))
6457 ((js2-name-node-p prop)
6458 ;; case 2c: complex target, simple name, e.g. x[y].bar
6459 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6460
6461 (defun js2-parse-highlight-member-expr-fn-name (expr)
6462 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6463 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6464 We currently only handle the case where the last component is a prop-get
6465 of a simple name. Called before EXPR has a parent node."
6466 (let (pos
6467 (name (and (js2-prop-get-node-p expr)
6468 (js2-prop-get-node-right expr))))
6469 (when (js2-name-node-p name)
6470 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6471 (js2-node-pos name)))
6472 (+ pos (js2-node-len name))
6473 'font-lock-function-name-face
6474 'record))))
6475
6476 ;; source: http://jsdoc.sourceforge.net/
6477 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6478 ;; allows type specifications, and needs work before entering the wild.
6479
6480 (defconst js2-jsdoc-param-tag-regexp
6481 (concat "^\\s-*\\*+\\s-*\\(@"
6482 "\\(?:param\\|argument\\)"
6483 "\\)"
6484 "\\s-*\\({[^}]+}\\)?" ; optional type
6485 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6486 "\\>")
6487 "Matches jsdoc tags with optional type and optional param name.")
6488
6489 (defconst js2-jsdoc-typed-tag-regexp
6490 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6491 (regexp-opt
6492 '("enum"
6493 "extends"
6494 "field"
6495 "id"
6496 "implements"
6497 "lends"
6498 "mods"
6499 "requires"
6500 "return"
6501 "returns"
6502 "throw"
6503 "throws"))
6504 "\\)\\)\\s-*\\({[^}]+}\\)?")
6505 "Matches jsdoc tags with optional type.")
6506
6507 (defconst js2-jsdoc-arg-tag-regexp
6508 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6509 (regexp-opt
6510 '("alias"
6511 "augments"
6512 "borrows"
6513 "bug"
6514 "base"
6515 "config"
6516 "default"
6517 "define"
6518 "exception"
6519 "function"
6520 "member"
6521 "memberOf"
6522 "name"
6523 "namespace"
6524 "property"
6525 "since"
6526 "suppress"
6527 "this"
6528 "throws"
6529 "type"
6530 "version"))
6531 "\\)\\)\\s-+\\([^ \t]+\\)")
6532 "Matches jsdoc tags with a single argument.")
6533
6534 (defconst js2-jsdoc-empty-tag-regexp
6535 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6536 (regexp-opt
6537 '("addon"
6538 "author"
6539 "class"
6540 "const"
6541 "constant"
6542 "constructor"
6543 "constructs"
6544 "deprecated"
6545 "desc"
6546 "description"
6547 "event"
6548 "example"
6549 "exec"
6550 "export"
6551 "fileoverview"
6552 "final"
6553 "function"
6554 "hidden"
6555 "ignore"
6556 "implicitCast"
6557 "inheritDoc"
6558 "inner"
6559 "interface"
6560 "license"
6561 "noalias"
6562 "noshadow"
6563 "notypecheck"
6564 "override"
6565 "owner"
6566 "preserve"
6567 "preserveTry"
6568 "private"
6569 "protected"
6570 "public"
6571 "static"
6572 "supported"
6573 ))
6574 "\\)\\)\\s-*")
6575 "Matches empty jsdoc tags.")
6576
6577 (defconst js2-jsdoc-link-tag-regexp
6578 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6579 "Matches a jsdoc link or code tag.")
6580
6581 (defconst js2-jsdoc-see-tag-regexp
6582 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6583 "Matches a jsdoc @see tag.")
6584
6585 (defconst js2-jsdoc-html-tag-regexp
6586 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6587 "Matches a simple (no attributes) html start- or end-tag.")
6588
6589 (defsubst js2-jsdoc-highlight-helper ()
6590 (js2-set-face (match-beginning 1)
6591 (match-end 1)
6592 'js2-jsdoc-tag-face)
6593 (if (match-beginning 2)
6594 (if (save-excursion
6595 (goto-char (match-beginning 2))
6596 (= (char-after) ?{))
6597 (js2-set-face (1+ (match-beginning 2))
6598 (1- (match-end 2))
6599 'js2-jsdoc-type-face)
6600 (js2-set-face (match-beginning 2)
6601 (match-end 2)
6602 'js2-jsdoc-value-face)))
6603 (if (match-beginning 3)
6604 (js2-set-face (match-beginning 3)
6605 (match-end 3)
6606 'js2-jsdoc-value-face)))
6607
6608 (defun js2-highlight-jsdoc (ast)
6609 "Highlight doc comment tags."
6610 (let ((comments (js2-ast-root-comments ast))
6611 beg end)
6612 (save-excursion
6613 (dolist (node comments)
6614 (when (eq (js2-comment-node-format node) 'jsdoc)
6615 (setq beg (js2-node-abs-pos node)
6616 end (+ beg (js2-node-len node)))
6617 (save-restriction
6618 (narrow-to-region beg end)
6619 (dolist (re (list js2-jsdoc-param-tag-regexp
6620 js2-jsdoc-typed-tag-regexp
6621 js2-jsdoc-arg-tag-regexp
6622 js2-jsdoc-link-tag-regexp
6623 js2-jsdoc-see-tag-regexp
6624 js2-jsdoc-empty-tag-regexp))
6625 (goto-char beg)
6626 (while (re-search-forward re nil t)
6627 (js2-jsdoc-highlight-helper)))
6628 ;; simple highlighting for html tags
6629 (goto-char beg)
6630 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6631 (js2-set-face (match-beginning 1)
6632 (match-end 1)
6633 'js2-jsdoc-html-tag-delimiter-face)
6634 (js2-set-face (match-beginning 2)
6635 (match-end 2)
6636 'js2-jsdoc-html-tag-name-face)
6637 (js2-set-face (match-beginning 3)
6638 (match-end 3)
6639 'js2-jsdoc-html-tag-delimiter-face))))))))
6640
6641 (defun js2-highlight-assign-targets (node left right)
6642 "Highlight function properties and external variables."
6643 (let (leftpos end name)
6644 ;; highlight vars and props assigned function values
6645 (when (js2-function-node-p right)
6646 (cond
6647 ;; var foo = function() {...}
6648 ((js2-name-node-p left)
6649 (setq name left))
6650 ;; foo.bar.baz = function() {...}
6651 ((and (js2-prop-get-node-p left)
6652 (js2-name-node-p (js2-prop-get-node-right left)))
6653 (setq name (js2-prop-get-node-right left))))
6654 (when name
6655 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6656 (+ leftpos (js2-node-len name))
6657 'font-lock-function-name-face
6658 'record)))))
6659
6660 (defun js2-record-name-node (node)
6661 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6662 later. NODE must be a name node."
6663 (let (leftpos end)
6664 (push (list node js2-current-scope
6665 (setq leftpos (js2-node-abs-pos node))
6666 (setq end (+ leftpos (js2-node-len node))))
6667 js2-recorded-identifiers)))
6668
6669 (defun js2-highlight-undeclared-vars ()
6670 "After entire parse is finished, look for undeclared variable references.
6671 We have to wait until entire buffer is parsed, since JavaScript permits var
6672 decls to occur after they're used.
6673
6674 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6675 it is considered declared."
6676 (let (name)
6677 (dolist (entry js2-recorded-identifiers)
6678 (destructuring-bind (name-node scope pos end) entry
6679 (setq name (js2-name-node-name name-node))
6680 (unless (or (member name js2-global-externs)
6681 (member name js2-default-externs)
6682 (member name js2-additional-externs)
6683 (js2-get-defining-scope scope name))
6684 (js2-set-face pos end 'js2-external-variable-face 'record)
6685 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6686 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6687 (setq js2-recorded-identifiers nil)))
6688
6689 ;;; IMenu support
6690
6691 ;; We currently only support imenu, but eventually should support speedbar and
6692 ;; possibly other browsing mechanisms.
6693
6694 ;; The basic strategy is to identify function assignment targets of the form
6695 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6696 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6697 ;; for imenu after parsing is finished.
6698
6699 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6700 ;; JavaScript, and the general problem is undecidable. However, several forms
6701 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6702 ;; include:
6703
6704 ;; function foo() -- function declaration
6705 ;; foo = function() -- function expression assigned to variable
6706 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6707 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6708 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6709 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6710 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6711 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6712 ;; function foo() {function bar() {...}} -- nested function
6713 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6714
6715 ;; This list boils down to a few forms that can be combined recursively.
6716 ;; Top-level named function declarations include both the left-hand (name)
6717 ;; and the right-hand (function value) expressions needed to produce an imenu
6718 ;; entry. The other "right-hand" forms we need to look for are:
6719 ;; - functions declared as props/getters/setters in object literals
6720 ;; - nested named function declarations
6721 ;; The "left-hand" expressions that functions can be assigned to include:
6722 ;; - local/global variables
6723 ;; - nested property-get expressions like a.b.c.d
6724 ;; - element gets like foo[10] or foo['bar'] where the index
6725 ;; expression can be trivially converted to a property name. They
6726 ;; effectively then become property gets.
6727
6728 ;; All the different definition types are canonicalized into the form
6729 ;; foo.bar.baz = position-of-function-keyword
6730
6731 ;; We need to build a trie-like structure for imenu. As an example,
6732 ;; consider the following JavaScript code:
6733
6734 ;; a = function() {...} // function at position 5
6735 ;; b = function() {...} // function at position 25
6736 ;; foo = function() {...} // function at position 100
6737 ;; foo.bar = function() {...} // function at position 200
6738 ;; foo.bar.baz = function() {...} // function at position 300
6739 ;; foo.bar.zab = function() {...} // function at position 400
6740
6741 ;; During parsing we accumulate an entry for each definition in
6742 ;; the variable `js2-imenu-recorder', like so:
6743
6744 ;; '((fn a 5)
6745 ;; (fn b 25)
6746 ;; (fn foo 100)
6747 ;; (fn foo bar 200)
6748 ;; (fn foo bar baz 300)
6749 ;; (fn foo bar zab 400))
6750
6751 ;; Where 'fn' is the respective function node.
6752 ;; After parsing these entries are merged into this alist-trie:
6753
6754 ;; '((a . 1)
6755 ;; (b . 2)
6756 ;; (foo (<definition> . 3)
6757 ;; (bar (<definition> . 6)
6758 ;; (baz . 100)
6759 ;; (zab . 200))))
6760
6761 ;; Note the wacky need for a <definition> name. The token can be anything
6762 ;; that isn't a valid JavaScript identifier, because you might make foo
6763 ;; a function and then start setting properties on it that are also functions.
6764
6765 (defsubst js2-prop-node-name (node)
6766 "Return the name of a node that may be a property-get/property-name.
6767 If NODE is not a valid name-node, string-node or integral number-node,
6768 returns nil. Otherwise returns the string name/value of the node."
6769 (cond
6770 ((js2-name-node-p node)
6771 (js2-name-node-name node))
6772 ((js2-string-node-p node)
6773 (js2-string-node-value node))
6774 ((and (js2-number-node-p node)
6775 (string-match "^[0-9]+$" (js2-number-node-value node)))
6776 (js2-number-node-value node))
6777 ((js2-this-node-p node)
6778 "this")))
6779
6780 (defsubst js2-node-qname-component (node)
6781 "Return the name of this node, if it contributes to a qname.
6782 Returns nil if the node doesn't contribute."
6783 (copy-sequence
6784 (or (js2-prop-node-name node)
6785 (if (and (js2-function-node-p node)
6786 (js2-function-node-name node))
6787 (js2-name-node-name (js2-function-node-name node))))))
6788
6789 (defsubst js2-record-imenu-entry (fn-node qname pos)
6790 "Add an entry to `js2-imenu-recorder'.
6791 FN-NODE should be the current item's function node.
6792
6793 Associate FN-NODE with its QNAME for later lookup.
6794 This is used in postprocessing the chain list. For each chain, we find
6795 the parent function, look up its qname, then prepend a copy of it to the chain."
6796 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6797 (unless js2-imenu-function-map
6798 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6799 (puthash fn-node qname js2-imenu-function-map))
6800
6801 (defun js2-record-imenu-functions (node &optional var)
6802 "Record function definitions for imenu.
6803 NODE is a function node or an object literal.
6804 VAR, if non-nil, is the expression that NODE is being assigned to.
6805 When passed arguments of wrong type, does nothing."
6806 (when js2-parse-ide-mode
6807 (let ((fun-p (js2-function-node-p node))
6808 qname left fname-node pos)
6809 (cond
6810 ;; non-anonymous function declaration?
6811 ((and fun-p
6812 (not var)
6813 (setq fname-node (js2-function-node-name node)))
6814 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6815 ;; for remaining forms, compute left-side tree branch first
6816 ((and var (setq qname (js2-compute-nested-prop-get var)))
6817 (cond
6818 ;; foo.bar.baz = function
6819 (fun-p
6820 (js2-record-imenu-entry node qname (js2-node-pos node)))
6821 ;; foo.bar.baz = object-literal
6822 ;; look for nested functions: {a: {b: function() {...} }}
6823 ((js2-object-node-p node)
6824 ;; Node position here is still absolute, since the parser
6825 ;; passes the assignment target and value expressions
6826 ;; to us before they are added as children of the assignment node.
6827 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6828
6829 (defun js2-compute-nested-prop-get (node)
6830 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6831 component nodes as a list. Otherwise return nil. Element-gets are treated
6832 as property-gets if the index expression is a string, or a positive integer."
6833 (let (left right head)
6834 (cond
6835 ((or (js2-name-node-p node)
6836 (js2-this-node-p node))
6837 (list node))
6838 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6839 ((js2-prop-get-node-p node) ; foo.bar
6840 (setq left (js2-prop-get-node-left node)
6841 right (js2-prop-get-node-right node))
6842 (if (setq head (js2-compute-nested-prop-get left))
6843 (nconc head (list right))))
6844 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6845 (setq left (js2-elem-get-node-target node)
6846 right (js2-elem-get-node-element node))
6847 (if (or (js2-string-node-p right) ; ['bar']
6848 (and (js2-number-node-p right) ; [10]
6849 (string-match "^[0-9]+$"
6850 (js2-number-node-value right))))
6851 (if (setq head (js2-compute-nested-prop-get left))
6852 (nconc head (list right))))))))
6853
6854 (defun js2-record-object-literal (node qname pos)
6855 "Recursively process an object literal looking for functions.
6856 NODE is an object literal that is the right-hand child of an assignment
6857 expression. QNAME is a list of nodes representing the assignment target,
6858 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6859 POS is the absolute position of the node.
6860 We do a depth-first traversal of NODE. For any functions we find,
6861 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6862 (let (left right prop-qname)
6863 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6864 (let ((left (js2-infix-node-left e))
6865 ;; Element positions are relative to the parent position.
6866 (pos (+ pos (js2-node-pos e))))
6867 (cond
6868 ;; foo: function() {...}
6869 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6870 (when (js2-prop-node-name left)
6871 ;; As a policy decision, we record the position of the property,
6872 ;; not the position of the `function' keyword, since the property
6873 ;; is effectively the name of the function.
6874 (js2-record-imenu-entry right (append qname (list left)) pos)))
6875 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6876 ((js2-object-node-p right)
6877 (js2-record-object-literal right
6878 (append qname (list (js2-infix-node-left e)))
6879 (+ pos (js2-node-pos right)))))))))
6880
6881 (defsubst js2-node-top-level-decl-p (node)
6882 "Return t if NODE's name is defined in the top-level scope.
6883 Also returns t if NODE's name is not defined in any scope, since it implies
6884 that it's an external variable, which must also be in the top-level scope."
6885 (let* ((name (js2-prop-node-name node))
6886 (this-scope (js2-node-get-enclosing-scope node))
6887 defining-scope)
6888 (cond
6889 ((js2-this-node-p node)
6890 nil)
6891 ((null this-scope)
6892 t)
6893 ((setq defining-scope (js2-get-defining-scope this-scope name))
6894 (js2-ast-root-p defining-scope))
6895 (t t))))
6896
6897 (defsubst js2-wrapper-function-p (node)
6898 "Returns t if NODE is a function expression that's immediately invoked.
6899 NODE must be `js2-function-node'."
6900 (let ((parent (js2-node-parent node)))
6901 (or
6902 ;; function(){...}();
6903 (js2-call-node-p parent)
6904 (and (js2-paren-node-p parent)
6905 ;; (function(){...})();
6906 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6907 ;; (function(){...}).call(this);
6908 (and (js2-prop-get-node-p parent)
6909 (member (js2-name-node-name (js2-prop-get-node-right parent))
6910 '("call" "apply"))
6911 (js2-call-node-p (js2-node-parent parent))))))))
6912
6913 (defun js2-browse-postprocess-chains (entries)
6914 "Modify function-declaration name chains after parsing finishes.
6915 Some of the information is only available after the parse tree is complete.
6916 For instance, processing a nested scope requires a parent function node."
6917 (let (result head fn current-fn parent-qname qname p elem)
6918 (dolist (entry entries)
6919 ;; function node goes first
6920 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6921 ;; Examine head's defining scope:
6922 ;; Pre-processed chain, or top-level/external, keep as-is.
6923 (if (or (stringp head) (js2-node-top-level-decl-p head))
6924 (push chain result)
6925 (when (js2-this-node-p head)
6926 (setq chain (cdr chain))) ; discard this-node
6927 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6928 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6929 (when (eq parent-qname 'not-found)
6930 ;; anonymous function expressions are not recorded
6931 ;; during the parse, so we need to handle this case here
6932 (setq parent-qname
6933 (if (js2-wrapper-function-p fn)
6934 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6935 (if (js2-ast-root-p grandparent)
6936 nil
6937 (gethash grandparent js2-imenu-function-map 'skip)))
6938 'skip))
6939 (puthash fn parent-qname js2-imenu-function-map))
6940 (unless (eq parent-qname 'skip)
6941 ;; prefix parent fn qname to this chain.
6942 (let ((qname (append parent-qname chain)))
6943 (puthash current-fn (butlast qname) js2-imenu-function-map)
6944 (push qname result)))))))
6945 ;; finally replace each node in each chain with its name.
6946 (dolist (chain result)
6947 (setq p chain)
6948 (while p
6949 (if (js2-node-p (setq elem (car p)))
6950 (setcar p (js2-node-qname-component elem)))
6951 (setq p (cdr p))))
6952 result))
6953
6954 ;; Merge name chains into a trie-like tree structure of nested lists.
6955 ;; To simplify construction of the trie, we first build it out using the rule
6956 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6957 ;; [key, num-or-list]. The second element can be a number; if so, this key
6958 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6959 ;; associated with the key at this level.) Otherwise the second element is
6960 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6961 ;; a simple recursive formulation.
6962 ;;
6963 ;; js2-mode is building the data structure for imenu. The imenu documentation
6964 ;; claims that it's the structure above, but in practice it wants the children
6965 ;; at the same list level as the key for that level, which is how I've drawn
6966 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6967 ;; list wrapper around the children at each level.
6968 ;;
6969 ;; A completed nested imenu-alist entry looks like this:
6970 ;; '(("foo"
6971 ;; ("<definition>" . 7)
6972 ;; ("bar"
6973 ;; ("a" . 40)
6974 ;; ("b" . 60))))
6975 ;;
6976 ;; In particular, the documentation for `imenu--index-alist' says that
6977 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6978 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6979
6980 (defun js2-treeify (lst)
6981 "Convert (a b c d) to (a ((b ((c d)))))"
6982 (if (null (cddr lst)) ; list length <= 2
6983 lst
6984 (list (car lst) (list (js2-treeify (cdr lst))))))
6985
6986 (defun js2-build-alist-trie (chains trie)
6987 "Merge declaration name chains into a trie-like alist structure for imenu.
6988 CHAINS is the qname chain list produced during parsing. TRIE is a
6989 list of elements built up so far."
6990 (let (head tail pos branch kids)
6991 (dolist (chain chains)
6992 (setq head (car chain)
6993 tail (cdr chain)
6994 pos (if (numberp (car tail)) (car tail))
6995 branch (js2-find-if (lambda (n)
6996 (string= (car n) head))
6997 trie)
6998 kids (second branch))
6999 (cond
7000 ;; case 1: this key isn't in the trie yet
7001 ((null branch)
7002 (if trie
7003 (setcdr (last trie) (list (js2-treeify chain)))
7004 (setq trie (list (js2-treeify chain)))))
7005 ;; case 2: key is present with a single number entry: replace w/ list
7006 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7007 ;; ("<definition>" 20)))
7008 ((numberp kids)
7009 (setcar (cdr branch)
7010 (list (list "<definition-1>" kids)
7011 (if pos
7012 (list "<definition-2>" pos)
7013 (js2-treeify tail)))))
7014 ;; case 3: key is there (with kids), and we're a number entry
7015 (pos
7016 (setcdr (last kids)
7017 (list
7018 (list (format "<definition-%d>"
7019 (1+ (loop for kid in kids
7020 count (eq ?< (aref (car kid) 0)))))
7021 pos))))
7022 ;; case 4: key is there with kids, need to merge in our chain
7023 (t
7024 (js2-build-alist-trie (list tail) kids))))
7025 trie))
7026
7027 (defun js2-flatten-trie (trie)
7028 "Convert TRIE to imenu-format.
7029 Recurses through nodes, and for each one whose second element is a list,
7030 appends the list's flattened elements to the current element. Also
7031 changes the tails into conses. For instance, this pre-flattened trie
7032
7033 '(a ((b 20)
7034 (c ((d 30)
7035 (e 40)))))
7036
7037 becomes
7038
7039 '(a (b . 20)
7040 (c (d . 30)
7041 (e . 40)))
7042
7043 Note that the root of the trie has no key, just a list of chains.
7044 This is also true for the value of any key with multiple children,
7045 e.g. key 'c' in the example above."
7046 (cond
7047 ((listp (car trie))
7048 (mapcar #'js2-flatten-trie trie))
7049 (t
7050 (if (numberp (second trie))
7051 (cons (car trie) (second trie))
7052 ;; else pop list and append its kids
7053 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7054
7055 (defun js2-build-imenu-index ()
7056 "Turn `js2-imenu-recorder' into an imenu data structure."
7057 (unless (eq js2-imenu-recorder 'empty)
7058 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7059 (result (js2-build-alist-trie chains nil)))
7060 (js2-flatten-trie result))))
7061
7062 (defun js2-test-print-chains (chains)
7063 "Print a list of qname chains.
7064 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7065 i.e. one or more nodes, and an integer position as the list tail."
7066 (mapconcat (lambda (chain)
7067 (concat "("
7068 (mapconcat (lambda (elem)
7069 (if (js2-node-p elem)
7070 (or (js2-node-qname-component elem)
7071 "nil")
7072 (number-to-string elem)))
7073 chain
7074 " ")
7075 ")"))
7076 chains
7077 "\n"))
7078
7079 ;;; Parser
7080
7081 (defconst js2-version "1.8.0"
7082 "Version of JavaScript supported, plus minor js2 version.")
7083
7084 (defmacro js2-record-face (face)
7085 "Record a style run of FACE for the current token."
7086 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7087
7088 (defsubst js2-node-end (n)
7089 "Computes the absolute end of node N.
7090 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7091 is only true until the node is added to its parent; i.e., while parsing."
7092 (+ (js2-node-pos n)
7093 (js2-node-len n)))
7094
7095 (defsubst js2-record-comment ()
7096 "Record a comment in `js2-scanned-comments'."
7097 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7098 :format js2-ts-comment-type)
7099 js2-scanned-comments)
7100 (when js2-parse-ide-mode
7101 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7102 'font-lock-doc-face
7103 'font-lock-comment-face))
7104 (when (memq js2-ts-comment-type '(html preprocessor))
7105 ;; Tell cc-engine the bounds of the comment.
7106 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7107
7108 ;; This function is called depressingly often, so it should be fast.
7109 ;; Most of the time it's looking at the same token it peeked before.
7110 (defsubst js2-peek-token ()
7111 "Returns the next token without consuming it.
7112 If previous token was consumed, calls scanner to get new token.
7113 If previous token was -not- consumed, returns it (idempotent).
7114
7115 This function will not return a newline (js2-EOL) - instead, it
7116 gobbles newlines until it finds a non-newline token, and flags
7117 that token as appearing just after a newline.
7118
7119 This function will also not return a js2-COMMENT. Instead, it
7120 records comments found in `js2-scanned-comments'. If the token
7121 returned by this function immediately follows a jsdoc comment,
7122 the token is flagged as such.
7123
7124 Note that this function always returned the un-flagged token!
7125 The flags, if any, are saved in `js2-current-flagged-token'."
7126 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7127 js2-current-token ; most common case - return already-peeked token
7128 (let ((tt (js2-get-token)) ; call scanner
7129 saw-eol
7130 face)
7131 ;; process comments and whitespace
7132 (while (or (= tt js2-EOL)
7133 (= tt js2-COMMENT))
7134 (if (= tt js2-EOL)
7135 (setq saw-eol t)
7136 (setq saw-eol nil)
7137 (if js2-record-comments
7138 (js2-record-comment)))
7139 (setq tt (js2-get-token))) ; call scanner
7140 (setq js2-current-token tt
7141 js2-current-flagged-token (if saw-eol
7142 (logior tt js2-ti-after-eol)
7143 tt))
7144 ;; perform lexical fontification as soon as token is scanned
7145 (when js2-parse-ide-mode
7146 (cond
7147 ((minusp tt)
7148 (js2-record-face 'js2-error-face))
7149 ((setq face (aref js2-kwd-tokens tt))
7150 (js2-record-face face))
7151 ((and (= tt js2-NAME)
7152 (equal js2-ts-string "undefined"))
7153 (js2-record-face 'font-lock-constant-face))))
7154 tt))) ; return unflagged token
7155
7156 (defsubst js2-peek-flagged-token ()
7157 "Returns the current token along with any flags set for it."
7158 (js2-peek-token)
7159 js2-current-flagged-token)
7160
7161 (defsubst js2-consume-token ()
7162 (setq js2-current-flagged-token js2-EOF))
7163
7164 (defsubst js2-next-token ()
7165 (prog1
7166 (js2-peek-token)
7167 (js2-consume-token)))
7168
7169 (defsubst js2-next-flagged-token ()
7170 (js2-peek-token)
7171 (prog1 js2-current-flagged-token
7172 (js2-consume-token)))
7173
7174 (defsubst js2-match-token (match)
7175 "Consume and return t if next token matches MATCH, a bytecode.
7176 Returns nil and consumes nothing if MATCH is not the next token."
7177 (if (/= (js2-peek-token) match)
7178 nil
7179 (js2-consume-token)
7180 t))
7181
7182 (defun js2-match-contextual-kwd (name)
7183 "Consume and return t if next token is `js2-NAME', and its
7184 string is NAME. Returns nil and does nothing otherwise."
7185 (if (or (/= (js2-peek-token) js2-NAME)
7186 (not (string= js2-ts-string name)))
7187 nil
7188 (js2-consume-token)
7189 (js2-record-face 'font-lock-keyword-face)
7190 t))
7191
7192 (defsubst js2-valid-prop-name-token (tt)
7193 (or (= tt js2-NAME)
7194 (when (and js2-allow-keywords-as-property-names
7195 (plusp tt)
7196 (aref js2-kwd-tokens tt))
7197 (js2-save-name-token-data js2-token-beg (js2-token-name tt))
7198 t)))
7199
7200 (defsubst js2-match-prop-name ()
7201 "Consume token and return t if next token is a valid property name.
7202 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7203 is non-nil and it's a keyword token."
7204 (if (js2-valid-prop-name-token (js2-peek-token))
7205 (progn
7206 (js2-consume-token)
7207 t)
7208 nil))
7209
7210 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7211 (if (js2-match-prop-name)
7212 t
7213 (js2-report-error msg-id nil pos len)
7214 nil))
7215
7216 (defsubst js2-peek-token-or-eol ()
7217 "Return js2-EOL if the current token immediately follows a newline.
7218 Else returns the current token. Used in situations where we don't
7219 consider certain token types valid if they are preceded by a newline.
7220 One example is the postfix ++ or -- operator, which has to be on the
7221 same line as its operand."
7222 (let ((tt (js2-peek-token)))
7223 ;; Check for last peeked token flags
7224 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7225 js2-EOL
7226 tt)))
7227
7228 (defsubst js2-set-check-for-label ()
7229 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7230 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7231
7232 (defsubst js2-must-match (token msg-id &optional pos len)
7233 "Match next token to token code TOKEN, or record a syntax error.
7234 MSG-ID is the error message to report if the match fails.
7235 Returns t on match, nil if no match."
7236 (if (js2-match-token token)
7237 t
7238 (js2-report-error msg-id nil pos len)
7239 nil))
7240
7241 (defsubst js2-inside-function ()
7242 (plusp js2-nesting-of-function))
7243
7244 (defsubst js2-set-requires-activation ()
7245 (if (js2-function-node-p js2-current-script-or-fn)
7246 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7247
7248 (defsubst js2-check-activation-name (name token)
7249 (when (js2-inside-function)
7250 ;; skip language-version 1.2 check from Rhino
7251 (if (or (string= "arguments" name)
7252 (and js2-compiler-activation-names ; only used in codegen
7253 (gethash name js2-compiler-activation-names)))
7254 (js2-set-requires-activation))))
7255
7256 (defsubst js2-set-is-generator ()
7257 (if (js2-function-node-p js2-current-script-or-fn)
7258 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7259
7260 (defsubst js2-must-have-xml ()
7261 (unless js2-compiler-xml-available
7262 (js2-report-error "msg.XML.not.available")))
7263
7264 (defsubst js2-push-scope (scope)
7265 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7266 (assert (js2-scope-p scope))
7267 (assert (null (js2-scope-parent-scope scope)))
7268 (assert (not (eq js2-current-scope scope)))
7269 (setf (js2-scope-parent-scope scope) js2-current-scope
7270 js2-current-scope scope))
7271
7272 (defsubst js2-pop-scope ()
7273 (setq js2-current-scope
7274 (js2-scope-parent-scope js2-current-scope)))
7275
7276 (defsubst js2-enter-loop (loop-node)
7277 (push loop-node js2-loop-set)
7278 (push loop-node js2-loop-and-switch-set)
7279 (js2-push-scope loop-node)
7280 ;; Tell the current labeled statement (if any) its statement,
7281 ;; and set the jump target of the first label to the loop.
7282 ;; These are used in `js2-parse-continue' to verify that the
7283 ;; continue target is an actual labeled loop. (And for codegen.)
7284 (when js2-labeled-stmt
7285 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7286 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7287 js2-labeled-stmt))) loop-node)))
7288
7289 (defsubst js2-exit-loop ()
7290 (pop js2-loop-set)
7291 (pop js2-loop-and-switch-set)
7292 (js2-pop-scope))
7293
7294 (defsubst js2-enter-switch (switch-node)
7295 (push switch-node js2-loop-and-switch-set))
7296
7297 (defsubst js2-exit-switch ()
7298 (pop js2-loop-and-switch-set))
7299
7300 (defun js2-parse (&optional buf cb)
7301 "Tells the js2 parser to parse a region of JavaScript.
7302
7303 BUF is a buffer or buffer name containing the code to parse.
7304 Call `narrow-to-region' first to parse only part of the buffer.
7305
7306 The returned AST root node is given some additional properties:
7307 `node-count' - total number of nodes in the AST
7308 `buffer' - BUF. The buffer it refers to may change or be killed,
7309 so the value is not necessarily reliable.
7310
7311 An optional callback CB can be specified to report parsing
7312 progress. If `(functionp CB)' returns t, it will be called with
7313 the current line number once before parsing begins, then again
7314 each time the lexer reaches a new line number.
7315
7316 CB can also be a list of the form `(symbol cb ...)' to specify
7317 multiple callbacks with different criteria. Each symbol is a
7318 criterion keyword, and the following element is the callback to
7319 call
7320
7321 :line - called whenever the line number changes
7322 :token - called for each new token consumed
7323
7324 The list of criteria could be extended to include entering or
7325 leaving a statement, an expression, or a function definition."
7326 (if (and cb (not (functionp cb)))
7327 (error "criteria callbacks not yet implemented"))
7328 (let ((inhibit-point-motion-hooks t)
7329 (js2-compiler-xml-available (>= js2-language-version 160))
7330 ;; This is a recursive-descent parser, so give it a big stack.
7331 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7332 (max-specpdl-size (max max-specpdl-size 3000))
7333 (case-fold-search nil)
7334 ast)
7335 (message nil) ; clear any error message from previous parse
7336 (save-excursion
7337 (when buf (set-buffer buf))
7338 (setq js2-scanned-comments nil
7339 js2-parsed-errors nil
7340 js2-parsed-warnings nil
7341 js2-imenu-recorder nil
7342 js2-imenu-function-map nil
7343 js2-label-set nil)
7344 (js2-init-scanner)
7345 (setq ast (js2-with-unmodifying-text-property-changes
7346 (js2-do-parse)))
7347 (unless js2-ts-hit-eof
7348 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7349 (setf (js2-ast-root-errors ast) js2-parsed-errors
7350 (js2-ast-root-warnings ast) js2-parsed-warnings)
7351 ;; if we didn't find any declarations, put a dummy in this list so we
7352 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7353 (unless js2-imenu-recorder
7354 (setq js2-imenu-recorder 'empty))
7355 (run-hooks 'js2-parse-finished-hook)
7356 ast)))
7357
7358 ;; Corresponds to Rhino's Parser.parse() method.
7359 (defun js2-do-parse ()
7360 "Parse current buffer starting from current point.
7361 Scanner should be initialized."
7362 (let ((pos js2-ts-cursor)
7363 (end js2-ts-cursor) ; in case file is empty
7364 root n tt)
7365 ;; initialize buffer-local parsing vars
7366 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7367 js2-current-script-or-fn root
7368 js2-current-scope root
7369 js2-current-flagged-token js2-EOF
7370 js2-nesting-of-function 0
7371 js2-labeled-stmt nil
7372 js2-recorded-identifiers nil) ; for js2-highlight
7373 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7374 (if (= tt js2-FUNCTION)
7375 (progn
7376 (js2-consume-token)
7377 (setq n (js2-parse-function (if js2-called-by-compile-function
7378 'FUNCTION_EXPRESSION
7379 'FUNCTION_STATEMENT))))
7380 ;; not a function - parse a statement
7381 (setq n (js2-parse-statement)))
7382 ;; add function or statement to script
7383 (setq end (js2-node-end n))
7384 (js2-block-node-push root n))
7385 ;; add comments to root in lexical order
7386 (when js2-scanned-comments
7387 ;; if we find a comment beyond end of normal kids, use its end
7388 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7389 (dolist (comment js2-scanned-comments)
7390 (push comment (js2-ast-root-comments root))
7391 (js2-node-add-children root comment)))
7392 (setf (js2-node-len root) (- end pos))
7393 ;; Give extensions a chance to muck with things before highlighting starts.
7394 (let ((js2-additional-externs js2-additional-externs))
7395 (dolist (callback js2-post-parse-callbacks)
7396 (funcall callback))
7397 (js2-highlight-undeclared-vars))
7398 root))
7399
7400 (defun js2-function-parser ()
7401 (js2-consume-token)
7402 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7403
7404 (defun js2-parse-function-closure-body (fn-node)
7405 "Parse a JavaScript 1.8 function closure body."
7406 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7407 (if js2-ts-hit-eof
7408 (js2-report-error "msg.no.brace.body" nil
7409 (js2-node-pos fn-node)
7410 (- js2-ts-cursor (js2-node-pos fn-node)))
7411 (js2-node-add-children fn-node
7412 (setf (js2-function-node-body fn-node)
7413 (js2-parse-expr t))))))
7414
7415 (defun js2-parse-function-body (fn-node)
7416 (js2-must-match js2-LC "msg.no.brace.body"
7417 (js2-node-pos fn-node)
7418 (- js2-ts-cursor (js2-node-pos fn-node)))
7419 (let ((pos js2-token-beg) ; LC position
7420 (pn (make-js2-block-node)) ; starts at LC position
7421 tt
7422 end)
7423 (incf js2-nesting-of-function)
7424 (unwind-protect
7425 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7426 (= tt js2-EOF)
7427 (= tt js2-RC)))
7428 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7429 (js2-parse-statement)
7430 (js2-consume-token)
7431 (js2-parse-function 'FUNCTION_STATEMENT))))
7432 (decf js2-nesting-of-function))
7433 (setq end js2-token-end) ; assume no curly and leave at current token
7434 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7435 (setq end js2-token-end))
7436 (setf (js2-node-pos pn) pos
7437 (js2-node-len pn) (- end pos))
7438 (setf (js2-function-node-body fn-node) pn)
7439 (js2-node-add-children fn-node pn)
7440 pn))
7441
7442 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7443 "Declare and fontify destructuring parameters inside NODE.
7444 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7445 (cond
7446 ((js2-name-node-p node)
7447 (let (leftpos)
7448 (js2-define-symbol decl-type (js2-name-node-name node)
7449 node ignore-not-in-block)
7450 (when face
7451 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7452 (+ leftpos (js2-node-len node))
7453 face 'record))))
7454 ((js2-object-node-p node)
7455 (dolist (elem (js2-object-node-elems node))
7456 (js2-define-destruct-symbols
7457 (if (js2-object-prop-node-p elem)
7458 (js2-object-prop-node-right elem)
7459 ;; abbreviated destructuring {a, b}
7460 elem)
7461 decl-type face ignore-not-in-block)))
7462 ((js2-array-node-p node)
7463 (dolist (elem (js2-array-node-elems node))
7464 (when elem
7465 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7466 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7467 (js2-node-len node)))))
7468
7469 (defun js2-parse-function-params (fn-node pos)
7470 (if (js2-match-token js2-RP)
7471 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7472 (let (params len param default-found)
7473 (loop for tt = (js2-peek-token)
7474 do
7475 (cond
7476 ;; destructuring param
7477 ((or (= tt js2-LB) (= tt js2-LC))
7478 (when default-found
7479 (js2-report-error "msg.no.default.after.default.param"))
7480 (setq param (js2-parse-destruct-primary-expr))
7481 (js2-define-destruct-symbols param
7482 js2-LP
7483 'js2-function-param-face)
7484 (push param params))
7485 ;; variable name
7486 (t
7487 (js2-must-match js2-NAME "msg.no.parm")
7488 (js2-record-face 'js2-function-param-face)
7489 (setq param (js2-create-name-node))
7490 (js2-define-symbol js2-LP js2-ts-string param)
7491 ;; default parameter value
7492 (when (or (and default-found
7493 (js2-must-match js2-ASSIGN
7494 "msg.no.default.after.default.param"
7495 (js2-node-pos param)
7496 (js2-node-len param)))
7497 (and (>= js2-language-version 200)
7498 (js2-match-token js2-ASSIGN)))
7499 (let* ((pos (js2-node-pos param))
7500 (tt js2-current-token)
7501 (op-pos (- js2-token-beg pos))
7502 (left param)
7503 (right (js2-parse-assign-expr))
7504 (len (- (js2-node-end right) pos)))
7505 (setq param (make-js2-assign-node
7506 :type tt :pos pos :len len :op-pos op-pos
7507 :left left :right right)
7508 default-found t)
7509 (js2-node-add-children param left right)))
7510 (push param params)))
7511 while
7512 (js2-match-token js2-COMMA))
7513 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7514 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7515 (dolist (p params)
7516 (js2-node-add-children fn-node p)
7517 (push p (js2-function-node-params fn-node))))))
7518
7519 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7520 "Possibly show inconsistent-return warning.
7521 Last token scanned is the close-curly for the function body."
7522 (when (and js2-mode-show-strict-warnings
7523 js2-strict-inconsistent-return-warning
7524 (not (js2-has-consistent-return-usage
7525 (js2-function-node-body fn-node))))
7526 ;; Have it extend from close-curly to bol or beginning of block.
7527 (let ((pos (save-excursion
7528 (goto-char js2-token-end)
7529 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7530 (point-at-bol))))
7531 (end js2-token-end))
7532 (if (plusp (js2-name-node-length name))
7533 (js2-add-strict-warning "msg.no.return.value"
7534 (js2-name-node-name name) pos end)
7535 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7536
7537 (defun js2-parse-function (function-type)
7538 "Function parser. FUNCTION-TYPE is a symbol."
7539 (let ((pos js2-token-beg) ; start of 'function' keyword
7540 name
7541 name-beg
7542 name-end
7543 fn-node
7544 lp
7545 (synthetic-type function-type)
7546 member-expr-node)
7547 ;; parse function name, expression, or non-name (anonymous)
7548 (cond
7549 ;; function foo(...)
7550 ((js2-match-token js2-NAME)
7551 (setq name (js2-create-name-node t)
7552 name-beg js2-token-beg
7553 name-end js2-token-end)
7554 (unless (js2-match-token js2-LP)
7555 (when js2-allow-member-expr-as-function-name
7556 ;; function foo.bar(...)
7557 (setq member-expr-node name
7558 name nil
7559 member-expr-node (js2-parse-member-expr-tail
7560 nil member-expr-node)))
7561 (js2-must-match js2-LP "msg.no.paren.parms")))
7562 ((js2-match-token js2-LP)
7563 nil) ; anonymous function: leave name as null
7564 (t
7565 ;; function random-member-expr(...)
7566 (when js2-allow-member-expr-as-function-name
7567 ;; Note that memberExpr can not start with '(' like
7568 ;; in function (1+2).toString(), because 'function (' already
7569 ;; processed as anonymous function
7570 (setq member-expr-node (js2-parse-member-expr)))
7571 (js2-must-match js2-LP "msg.no.paren.parms")))
7572 (if (= js2-current-token js2-LP) ; eventually matched LP?
7573 (setq lp js2-token-beg))
7574 (if member-expr-node
7575 (progn
7576 (setq synthetic-type 'FUNCTION_EXPRESSION)
7577 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7578 (if name
7579 (js2-set-face name-beg name-end
7580 'font-lock-function-name-face 'record)))
7581 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7582 (plusp (js2-name-node-length name)))
7583 ;; Function statements define a symbol in the enclosing scope
7584 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7585 (setf fn-node (make-js2-function-node :pos pos
7586 :name name
7587 :form function-type
7588 :lp (if lp (- lp pos))))
7589 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7590 ;; 1. Nested functions are not affected by the dynamic scope flag
7591 ;; as dynamic scope is already a parent of their scope.
7592 ;; 2. Functions defined under the with statement also immune to
7593 ;; this setup, in which case dynamic scope is ignored in favor
7594 ;; of the with object.
7595 (setf (js2-function-node-ignore-dynamic fn-node) t))
7596 ;; dynamically bind all the per-function variables
7597 (let ((js2-current-script-or-fn fn-node)
7598 (js2-current-scope fn-node)
7599 (js2-nesting-of-with 0)
7600 (js2-end-flags 0)
7601 js2-label-set
7602 js2-loop-set
7603 js2-loop-and-switch-set)
7604 (js2-parse-function-params fn-node pos)
7605 (if (and (>= js2-language-version 180)
7606 (/= (js2-peek-token) js2-LC))
7607 (js2-parse-function-closure-body fn-node)
7608 (js2-parse-function-body fn-node))
7609 (if name
7610 (js2-node-add-children fn-node name))
7611 (js2-check-inconsistent-return-warning fn-node name)
7612 ;; Function expressions define a name only in the body of the
7613 ;; function, and only if not hidden by a parameter name
7614 (if (and name
7615 (eq synthetic-type 'FUNCTION_EXPRESSION)
7616 (null (js2-scope-get-symbol js2-current-scope
7617 (js2-name-node-name name))))
7618 (js2-define-symbol js2-FUNCTION
7619 (js2-name-node-name name)
7620 fn-node))
7621 (if (and name
7622 (not (eq function-type 'FUNCTION_EXPRESSION)))
7623 (js2-record-imenu-functions fn-node)))
7624 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7625 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7626 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7627 ;; We wait until after parsing the function to set its parent scope,
7628 ;; since `js2-define-symbol' needs the defining-scope check to stop
7629 ;; at the function boundary when checking for redeclarations.
7630 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7631 fn-node))
7632
7633 (defun js2-parse-statements (&optional parent)
7634 "Parse a statement list. Last token consumed must be js2-LC.
7635
7636 PARENT can be a `js2-block-node', in which case the statements are
7637 appended to PARENT. Otherwise a new `js2-block-node' is created
7638 and returned.
7639
7640 This function does not match the closing js2-RC: the caller
7641 matches the RC so it can provide a suitable error message if not
7642 matched. This means it's up to the caller to set the length of
7643 the node to include the closing RC. The node start pos is set to
7644 the absolute buffer start position, and the caller should fix it
7645 up to be relative to the parent node. All children of this block
7646 node are given relative start positions and correct lengths."
7647 (let ((pn (or parent (make-js2-block-node)))
7648 tt)
7649 (setf (js2-node-pos pn) js2-token-beg)
7650 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7651 (/= tt js2-RC))
7652 (js2-block-node-push pn (js2-parse-statement)))
7653 pn))
7654
7655 (defun js2-parse-statement ()
7656 (let (tt pn beg end)
7657 ;; coarse-grained user-interrupt check - needs work
7658 (and js2-parse-interruptable-p
7659 (zerop (% (incf js2-parse-stmt-count)
7660 js2-statements-per-pause))
7661 (input-pending-p)
7662 (throw 'interrupted t))
7663 (setq pn (js2-statement-helper))
7664 ;; no-side-effects warning check
7665 (unless (js2-node-has-side-effects pn)
7666 (setq end (js2-node-end pn))
7667 (save-excursion
7668 (goto-char end)
7669 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7670 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7671 pn))
7672
7673 ;; These correspond to the switch cases in Parser.statementHelper
7674 (defconst js2-parsers
7675 (let ((parsers (make-vector js2-num-tokens
7676 #'js2-parse-expr-stmt)))
7677 (aset parsers js2-BREAK #'js2-parse-break)
7678 (aset parsers js2-CONST #'js2-parse-const-var)
7679 (aset parsers js2-CONTINUE #'js2-parse-continue)
7680 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7681 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7682 (aset parsers js2-DO #'js2-parse-do)
7683 (aset parsers js2-FOR #'js2-parse-for)
7684 (aset parsers js2-FUNCTION #'js2-function-parser)
7685 (aset parsers js2-IF #'js2-parse-if)
7686 (aset parsers js2-LC #'js2-parse-block)
7687 (aset parsers js2-LET #'js2-parse-let-stmt)
7688 (aset parsers js2-NAME #'js2-parse-name-or-label)
7689 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7690 (aset parsers js2-SEMI #'js2-parse-semi)
7691 (aset parsers js2-SWITCH #'js2-parse-switch)
7692 (aset parsers js2-THROW #'js2-parse-throw)
7693 (aset parsers js2-TRY #'js2-parse-try)
7694 (aset parsers js2-VAR #'js2-parse-const-var)
7695 (aset parsers js2-WHILE #'js2-parse-while)
7696 (aset parsers js2-WITH #'js2-parse-with)
7697 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7698 parsers)
7699 "A vector mapping token types to parser functions.")
7700
7701 (defsubst js2-parse-warn-missing-semi (beg end)
7702 (and js2-mode-show-strict-warnings
7703 js2-strict-missing-semi-warning
7704 (js2-add-strict-warning
7705 "msg.missing.semi" nil
7706 ;; back up to beginning of statement or line
7707 (max beg (save-excursion
7708 (goto-char end)
7709 (point-at-bol)))
7710 end)))
7711
7712 (defconst js2-no-semi-insertion
7713 (list js2-IF
7714 js2-SWITCH
7715 js2-WHILE
7716 js2-DO
7717 js2-FOR
7718 js2-TRY
7719 js2-WITH
7720 js2-LC
7721 js2-ERROR
7722 js2-SEMI
7723 js2-FUNCTION)
7724 "List of tokens that don't do automatic semicolon insertion.")
7725
7726 (defconst js2-autoinsert-semi-and-warn
7727 (list js2-ERROR js2-EOF js2-RC))
7728
7729 (defun js2-statement-helper ()
7730 (let* ((tt (js2-peek-token))
7731 (first-tt tt)
7732 (beg js2-token-beg)
7733 (parser (if (= tt js2-ERROR)
7734 #'js2-parse-semi
7735 (aref js2-parsers tt)))
7736 pn
7737 tt-flagged)
7738 ;; If the statement is set, then it's been told its label by now.
7739 (and js2-labeled-stmt
7740 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7741 (setq js2-labeled-stmt nil))
7742 (setq pn (funcall parser))
7743 ;; Don't do auto semi insertion for certain statement types.
7744 (unless (or (memq first-tt js2-no-semi-insertion)
7745 (js2-labeled-stmt-node-p pn))
7746 (js2-auto-insert-semicolon pn))
7747 pn))
7748
7749 (defun js2-auto-insert-semicolon (pn)
7750 (let* ((tt-flagged (js2-peek-flagged-token))
7751 (tt (logand tt-flagged js2-clear-ti-mask))
7752 (pos (js2-node-pos pn)))
7753 (cond
7754 ((= tt js2-SEMI)
7755 ;; Consume ';' as a part of expression
7756 (js2-consume-token)
7757 ;; extend the node bounds to include the semicolon.
7758 (setf (js2-node-len pn) (- js2-token-end pos)))
7759 ((memq tt js2-autoinsert-semi-and-warn)
7760 ;; Autoinsert ;
7761 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7762 (t
7763 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7764 ;; Report error if no EOL or autoinsert ';' otherwise
7765 (js2-report-error "msg.no.semi.stmt")
7766 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7767
7768 (defun js2-parse-condition ()
7769 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7770 The parens are discarded and the expression node is returned.
7771 The `pos' field of the return value is set to an absolute position
7772 that must be fixed up by the caller.
7773 Return value is a list (EXPR LP RP), with absolute paren positions."
7774 (let (pn lp rp)
7775 (if (js2-must-match js2-LP "msg.no.paren.cond")
7776 (setq lp js2-token-beg))
7777 (setq pn (js2-parse-expr))
7778 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7779 (setq rp js2-token-beg))
7780 ;; Report strict warning on code like "if (a = 7) ..."
7781 (if (and js2-strict-cond-assign-warning
7782 (js2-assign-node-p pn))
7783 (js2-add-strict-warning "msg.equal.as.assign" nil
7784 (js2-node-pos pn)
7785 (+ (js2-node-pos pn)
7786 (js2-node-len pn))))
7787 (list pn lp rp)))
7788
7789 (defun js2-parse-if ()
7790 "Parser for if-statement. Last matched token must be js2-IF."
7791 (let ((pos js2-token-beg)
7792 cond
7793 if-true
7794 if-false
7795 else-pos
7796 end
7797 pn)
7798 (js2-consume-token)
7799 (setq cond (js2-parse-condition)
7800 if-true (js2-parse-statement)
7801 if-false (if (js2-match-token js2-ELSE)
7802 (progn
7803 (setq else-pos (- js2-token-beg pos))
7804 (js2-parse-statement)))
7805 end (js2-node-end (or if-false if-true))
7806 pn (make-js2-if-node :pos pos
7807 :len (- end pos)
7808 :condition (car cond)
7809 :then-part if-true
7810 :else-part if-false
7811 :else-pos else-pos
7812 :lp (js2-relpos (second cond) pos)
7813 :rp (js2-relpos (third cond) pos)))
7814 (js2-node-add-children pn (car cond) if-true if-false)
7815 pn))
7816
7817 (defun js2-parse-switch ()
7818 "Parser for if-statement. Last matched token must be js2-SWITCH."
7819 (let ((pos js2-token-beg)
7820 tt
7821 pn
7822 discriminant
7823 has-default
7824 case-expr
7825 case-node
7826 case-pos
7827 cases
7828 stmt
7829 lp
7830 rp)
7831 (js2-consume-token)
7832 (if (js2-must-match js2-LP "msg.no.paren.switch")
7833 (setq lp js2-token-beg))
7834 (setq discriminant (js2-parse-expr)
7835 pn (make-js2-switch-node :discriminant discriminant
7836 :pos pos
7837 :lp (js2-relpos lp pos)))
7838 (js2-node-add-children pn discriminant)
7839 (js2-enter-switch pn)
7840 (unwind-protect
7841 (progn
7842 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7843 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7844 (js2-must-match js2-LC "msg.no.brace.switch")
7845 (catch 'break
7846 (while t
7847 (setq tt (js2-next-token)
7848 case-pos js2-token-beg)
7849 (cond
7850 ((= tt js2-RC)
7851 (setf (js2-node-len pn) (- js2-token-end pos))
7852 (throw 'break nil)) ; done
7853 ((= tt js2-CASE)
7854 (setq case-expr (js2-parse-expr))
7855 (js2-must-match js2-COLON "msg.no.colon.case"))
7856 ((= tt js2-DEFAULT)
7857 (if has-default
7858 (js2-report-error "msg.double.switch.default"))
7859 (setq has-default t
7860 case-expr nil)
7861 (js2-must-match js2-COLON "msg.no.colon.case"))
7862 (t
7863 (js2-report-error "msg.bad.switch")
7864 (throw 'break nil)))
7865 (setq case-node (make-js2-case-node :pos case-pos
7866 :len (- js2-token-end case-pos)
7867 :expr case-expr))
7868 (js2-node-add-children case-node case-expr)
7869 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7870 (/= tt js2-CASE)
7871 (/= tt js2-DEFAULT)
7872 (/= tt js2-EOF))
7873 (setf stmt (js2-parse-statement)
7874 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7875 (js2-block-node-push case-node stmt))
7876 (push case-node cases)))
7877 ;; add cases last, as pushing reverses the order to be correct
7878 (dolist (kid cases)
7879 (js2-node-add-children pn kid)
7880 (push kid (js2-switch-node-cases pn)))
7881 pn) ; return value
7882 (js2-exit-switch))))
7883
7884 (defun js2-parse-while ()
7885 "Parser for while-statement. Last matched token must be js2-WHILE."
7886 (let ((pos js2-token-beg)
7887 (pn (make-js2-while-node))
7888 cond
7889 body)
7890 (js2-consume-token)
7891 (js2-enter-loop pn)
7892 (unwind-protect
7893 (progn
7894 (setf cond (js2-parse-condition)
7895 (js2-while-node-condition pn) (car cond)
7896 body (js2-parse-statement)
7897 (js2-while-node-body pn) body
7898 (js2-node-len pn) (- (js2-node-end body) pos)
7899 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7900 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7901 (js2-node-add-children pn body (car cond)))
7902 (js2-exit-loop))
7903 pn))
7904
7905 (defun js2-parse-do ()
7906 "Parser for do-statement. Last matched token must be js2-DO."
7907 (let ((pos js2-token-beg)
7908 (pn (make-js2-do-node))
7909 cond
7910 body
7911 end)
7912 (js2-consume-token)
7913 (js2-enter-loop pn)
7914 (unwind-protect
7915 (progn
7916 (setq body (js2-parse-statement))
7917 (js2-must-match js2-WHILE "msg.no.while.do")
7918 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7919 cond (js2-parse-condition)
7920 (js2-do-node-condition pn) (car cond)
7921 (js2-do-node-body pn) body
7922 end js2-ts-cursor
7923 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7924 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7925 (js2-node-add-children pn (car cond) body))
7926 (js2-exit-loop))
7927 ;; Always auto-insert semicolon to follow SpiderMonkey:
7928 ;; It is required by ECMAScript but is ignored by the rest of
7929 ;; world; see bug 238945
7930 (if (js2-match-token js2-SEMI)
7931 (setq end js2-ts-cursor))
7932 (setf (js2-node-len pn) (- end pos))
7933 pn))
7934
7935 (defun js2-parse-for ()
7936 "Parser for for-statement. Last matched token must be js2-FOR.
7937 Parses for, for-in, and for each-in statements."
7938 (let ((for-pos js2-token-beg)
7939 pn
7940 is-for-each
7941 is-for-in-or-of
7942 is-for-of
7943 in-pos
7944 each-pos
7945 tmp-pos
7946 init ; Node init is also foo in 'foo in object'
7947 cond ; Node cond is also object in 'foo in object'
7948 incr ; 3rd section of for-loop initializer
7949 body
7950 tt
7951 lp
7952 rp)
7953 (js2-consume-token)
7954 ;; See if this is a for each () instead of just a for ()
7955 (when (js2-match-token js2-NAME)
7956 (if (string= "each" js2-ts-string)
7957 (progn
7958 (setq is-for-each t
7959 each-pos (- js2-token-beg for-pos)) ; relative
7960 (js2-record-face 'font-lock-keyword-face))
7961 (js2-report-error "msg.no.paren.for")))
7962 (if (js2-must-match js2-LP "msg.no.paren.for")
7963 (setq lp (- js2-token-beg for-pos)))
7964 (setq tt (js2-peek-token))
7965 ;; 'for' makes local scope
7966 (js2-push-scope (make-js2-scope))
7967 (unwind-protect
7968 ;; parse init clause
7969 (let ((js2-in-for-init t)) ; set as dynamic variable
7970 (cond
7971 ((= tt js2-SEMI)
7972 (setq init (make-js2-empty-expr-node)))
7973 ((or (= tt js2-VAR) (= tt js2-LET))
7974 (js2-consume-token)
7975 (setq init (js2-parse-variables tt js2-token-beg)))
7976 (t
7977 (setq init (js2-parse-expr)))))
7978 (if (or (js2-match-token js2-IN)
7979 (and (>= js2-language-version 200)
7980 (js2-match-contextual-kwd "of")
7981 (setq is-for-of t)))
7982 (setq is-for-in-or-of t
7983 in-pos (- js2-token-beg for-pos)
7984 ;; scope of iteration target object is not the scope we've created above.
7985 ;; stash current scope temporary.
7986 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7987 (js2-parse-expr))) ; object over which we're iterating
7988 ;; else ordinary for loop - parse cond and incr
7989 (js2-must-match js2-SEMI "msg.no.semi.for")
7990 (setq cond (if (= (js2-peek-token) js2-SEMI)
7991 (make-js2-empty-expr-node) ; no loop condition
7992 (js2-parse-expr)))
7993 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7994 (setq tmp-pos js2-token-end
7995 incr (if (= (js2-peek-token) js2-RP)
7996 (make-js2-empty-expr-node :pos tmp-pos)
7997 (js2-parse-expr))))
7998 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7999 (setq rp (- js2-token-beg for-pos)))
8000 (if (not is-for-in-or-of)
8001 (setq pn (make-js2-for-node :init init
8002 :condition cond
8003 :update incr
8004 :lp lp
8005 :rp rp))
8006 ;; cond could be null if 'in obj' got eaten by the init node.
8007 (if (js2-infix-node-p init)
8008 ;; it was (foo in bar) instead of (var foo in bar)
8009 (setq cond (js2-infix-node-right init)
8010 init (js2-infix-node-left init))
8011 (if (and (js2-var-decl-node-p init)
8012 (> (length (js2-var-decl-node-kids init)) 1))
8013 (js2-report-error "msg.mult.index")))
8014 (setq pn (make-js2-for-in-node :iterator init
8015 :object cond
8016 :in-pos in-pos
8017 :foreach-p is-for-each
8018 :each-pos each-pos
8019 :forof-p is-for-of
8020 :lp lp
8021 :rp rp)))
8022 (unwind-protect
8023 (progn
8024 (js2-enter-loop pn)
8025 ;; We have to parse the body -after- creating the loop node,
8026 ;; so that the loop node appears in the js2-loop-set, allowing
8027 ;; break/continue statements to find the enclosing loop.
8028 (setf body (js2-parse-statement)
8029 (js2-loop-node-body pn) body
8030 (js2-node-pos pn) for-pos
8031 (js2-node-len pn) (- (js2-node-end body) for-pos))
8032 (js2-node-add-children pn init cond incr body))
8033 ;; finally
8034 (js2-exit-loop))
8035 (js2-pop-scope))
8036 pn))
8037
8038 (defun js2-parse-try ()
8039 "Parser for try-statement. Last matched token must be js2-TRY."
8040 (let ((try-pos js2-token-beg)
8041 try-end
8042 try-block
8043 catch-blocks
8044 finally-block
8045 saw-default-catch
8046 peek
8047 param
8048 catch-cond
8049 catch-node
8050 guard-kwd
8051 catch-pos
8052 finally-pos
8053 pn
8054 block
8055 lp
8056 rp)
8057 (js2-consume-token)
8058 (if (/= (js2-peek-token) js2-LC)
8059 (js2-report-error "msg.no.brace.try"))
8060 (setq try-block (js2-parse-statement)
8061 try-end (js2-node-end try-block)
8062 peek (js2-peek-token))
8063 (cond
8064 ((= peek js2-CATCH)
8065 (while (js2-match-token js2-CATCH)
8066 (setq catch-pos js2-token-beg
8067 guard-kwd nil
8068 catch-cond nil
8069 lp nil
8070 rp nil)
8071 (if saw-default-catch
8072 (js2-report-error "msg.catch.unreachable"))
8073 (if (js2-must-match js2-LP "msg.no.paren.catch")
8074 (setq lp (- js2-token-beg catch-pos)))
8075 (js2-push-scope (make-js2-scope))
8076 (let ((tt (js2-peek-token)))
8077 (cond
8078 ;; destructuring pattern
8079 ;; catch ({ message, file }) { ... }
8080 ((or (= tt js2-LB) (= tt js2-LC))
8081 (setq param (js2-parse-destruct-primary-expr))
8082 (js2-define-destruct-symbols param js2-LET nil))
8083 ;; simple name
8084 (t
8085 (js2-must-match js2-NAME "msg.bad.catchcond")
8086 (setq param (js2-create-name-node))
8087 (js2-define-symbol js2-LET js2-ts-string param))))
8088 ;; pattern guard
8089 (if (js2-match-token js2-IF)
8090 (setq guard-kwd (- js2-token-beg catch-pos)
8091 catch-cond (js2-parse-expr))
8092 (setq saw-default-catch t))
8093 (if (js2-must-match js2-RP "msg.bad.catchcond")
8094 (setq rp (- js2-token-beg catch-pos)))
8095 (js2-must-match js2-LC "msg.no.brace.catchblock")
8096 (setq block (js2-parse-statements)
8097 try-end (js2-node-end block)
8098 catch-node (make-js2-catch-node :pos catch-pos
8099 :param param
8100 :guard-expr catch-cond
8101 :guard-kwd guard-kwd
8102 :block block
8103 :lp lp
8104 :rp rp))
8105 (js2-pop-scope)
8106 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8107 (setq try-end js2-token-beg))
8108 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8109 (js2-node-len catch-node) (- try-end catch-pos))
8110 (js2-node-add-children catch-node param catch-cond block)
8111 (push catch-node catch-blocks)))
8112 ((/= peek js2-FINALLY)
8113 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8114 (js2-node-pos try-block)
8115 (- (setq try-end (js2-node-end try-block))
8116 (js2-node-pos try-block)))))
8117 (when (js2-match-token js2-FINALLY)
8118 (setq finally-pos js2-token-beg
8119 block (js2-parse-statement)
8120 try-end (js2-node-end block)
8121 finally-block (make-js2-finally-node :pos finally-pos
8122 :len (- try-end finally-pos)
8123 :body block))
8124 (js2-node-add-children finally-block block))
8125 (setq pn (make-js2-try-node :pos try-pos
8126 :len (- try-end try-pos)
8127 :try-block try-block
8128 :finally-block finally-block))
8129 (js2-node-add-children pn try-block finally-block)
8130 ;; push them onto the try-node, which reverses and corrects their order
8131 (dolist (cb catch-blocks)
8132 (js2-node-add-children pn cb)
8133 (push cb (js2-try-node-catch-clauses pn)))
8134 pn))
8135
8136 (defun js2-parse-throw ()
8137 "Parser for throw-statement. Last matched token must be js2-THROW."
8138 (let ((pos js2-token-beg)
8139 expr
8140 pn)
8141 (js2-consume-token)
8142 (if (= (js2-peek-token-or-eol) js2-EOL)
8143 ;; ECMAScript does not allow new lines before throw expression,
8144 ;; see bug 256617
8145 (js2-report-error "msg.bad.throw.eol"))
8146 (setq expr (js2-parse-expr)
8147 pn (make-js2-throw-node :pos pos
8148 :len (- (js2-node-end expr) pos)
8149 :expr expr))
8150 (js2-node-add-children pn expr)
8151 pn))
8152
8153 (defsubst js2-match-jump-label-name (label-name)
8154 "If break/continue specified a label, return that label's labeled stmt.
8155 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8156 does not match an existing label, reports an error and returns nil."
8157 (let ((bundle (cdr (assoc label-name js2-label-set))))
8158 (if (null bundle)
8159 (js2-report-error "msg.undef.label"))
8160 bundle))
8161
8162 (defun js2-parse-break ()
8163 "Parser for break-statement. Last matched token must be js2-BREAK."
8164 (let ((pos js2-token-beg)
8165 (end js2-token-end)
8166 break-target ; statement to break from
8167 break-label ; in "break foo", name-node representing the foo
8168 labels ; matching labeled statement to break to
8169 pn)
8170 (js2-consume-token) ; `break'
8171 (when (eq (js2-peek-token-or-eol) js2-NAME)
8172 (js2-consume-token)
8173 (setq break-label (js2-create-name-node)
8174 end (js2-node-end break-label)
8175 ;; matchJumpLabelName only matches if there is one
8176 labels (js2-match-jump-label-name js2-ts-string)
8177 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8178 (unless (or break-target break-label)
8179 ;; no break target specified - try for innermost enclosing loop/switch
8180 (if (null js2-loop-and-switch-set)
8181 (unless break-label
8182 (js2-report-error "msg.bad.break" nil pos (length "break")))
8183 (setq break-target (car js2-loop-and-switch-set))))
8184 (setq pn (make-js2-break-node :pos pos
8185 :len (- end pos)
8186 :label break-label
8187 :target break-target))
8188 (js2-node-add-children pn break-label) ; but not break-target
8189 pn))
8190
8191 (defun js2-parse-continue ()
8192 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8193 (let ((pos js2-token-beg)
8194 (end js2-token-end)
8195 label ; optional user-specified label, a `js2-name-node'
8196 labels ; current matching labeled stmt, if any
8197 target ; the `js2-loop-node' target of this continue stmt
8198 pn)
8199 (js2-consume-token) ; `continue'
8200 (when (= (js2-peek-token-or-eol) js2-NAME)
8201 (js2-consume-token)
8202 (setq label (js2-create-name-node)
8203 end (js2-node-end label)
8204 ;; matchJumpLabelName only matches if there is one
8205 labels (js2-match-jump-label-name js2-ts-string)))
8206 (cond
8207 ((null labels) ; no current label to go to
8208 (if (null js2-loop-set) ; no loop to continue to
8209 (js2-report-error "msg.continue.outside" nil pos
8210 (length "continue"))
8211 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8212 (t
8213 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8214 (setq target (js2-labeled-stmt-node-stmt labels))
8215 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8216 (setq pn (make-js2-continue-node :pos pos
8217 :len (- end pos)
8218 :label label
8219 :target target))
8220 (js2-node-add-children pn label) ; but not target - it's not our child
8221 pn))
8222
8223 (defun js2-parse-with ()
8224 "Parser for with-statement. Last matched token must be js2-WITH."
8225 (js2-consume-token)
8226 (let ((pos js2-token-beg)
8227 obj body pn lp rp)
8228 (if (js2-must-match js2-LP "msg.no.paren.with")
8229 (setq lp js2-token-beg))
8230 (setq obj (js2-parse-expr))
8231 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8232 (setq rp js2-token-beg))
8233 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8234 (setq body (js2-parse-statement)))
8235 (setq pn (make-js2-with-node :pos pos
8236 :len (- (js2-node-end body) pos)
8237 :object obj
8238 :body body
8239 :lp (js2-relpos lp pos)
8240 :rp (js2-relpos rp pos)))
8241 (js2-node-add-children pn obj body)
8242 pn))
8243
8244 (defun js2-parse-const-var ()
8245 "Parser for var- or const-statement.
8246 Last matched token must be js2-CONST or js2-VAR."
8247 (let ((tt (js2-peek-token))
8248 (pos js2-token-beg)
8249 expr
8250 pn)
8251 (js2-consume-token)
8252 (setq expr (js2-parse-variables tt js2-token-beg)
8253 pn (make-js2-expr-stmt-node :pos pos
8254 :len (- (js2-node-end expr) pos)
8255 :expr expr))
8256 (js2-node-add-children pn expr)
8257 pn))
8258
8259 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8260 (let ((pn (make-js2-expr-stmt-node :pos pos
8261 :len (js2-node-len expr)
8262 :type (if (js2-inside-function)
8263 js2-EXPR_VOID
8264 js2-EXPR_RESULT)
8265 :expr expr)))
8266 (if add-child
8267 (js2-node-add-children pn expr))
8268 pn))
8269
8270 (defun js2-parse-let-stmt ()
8271 "Parser for let-statement. Last matched token must be js2-LET."
8272 (js2-consume-token)
8273 (let ((pos js2-token-beg)
8274 expr
8275 pn)
8276 (if (= (js2-peek-token) js2-LP)
8277 ;; let expression in statement context
8278 (setq expr (js2-parse-let pos 'statement)
8279 pn (js2-wrap-with-expr-stmt pos expr t))
8280 ;; else we're looking at a statement like let x=6, y=7;
8281 (setf expr (js2-parse-variables js2-LET pos)
8282 pn (js2-wrap-with-expr-stmt pos expr t)
8283 (js2-node-type pn) js2-EXPR_RESULT))
8284 pn))
8285
8286 (defun js2-parse-ret-yield ()
8287 (js2-parse-return-or-yield (js2-peek-token) nil))
8288
8289 (defconst js2-parse-return-stmt-enders
8290 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8291
8292 (defsubst js2-now-all-set (before after mask)
8293 "Return whether or not the bits in the mask have changed to all set.
8294 BEFORE is bits before change, AFTER is bits after change, and MASK is
8295 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8296 but not BEFORE."
8297 (and (/= (logand before mask) mask)
8298 (= (logand after mask) mask)))
8299
8300 (defun js2-parse-return-or-yield (tt expr-context)
8301 (let ((pos js2-token-beg)
8302 (end js2-token-end)
8303 (before js2-end-flags)
8304 (inside-function (js2-inside-function))
8305 e
8306 ret
8307 name)
8308 (unless inside-function
8309 (js2-report-error (if (eq tt js2-RETURN)
8310 "msg.bad.return"
8311 "msg.bad.yield")))
8312 (js2-consume-token)
8313 ;; This is ugly, but we don't want to require a semicolon.
8314 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8315 (setq e (js2-parse-expr)
8316 end (js2-node-end e)))
8317 (cond
8318 ((eq tt js2-RETURN)
8319 (js2-set-flag js2-end-flags (if (null e)
8320 js2-end-returns
8321 js2-end-returns-value))
8322 (setq ret (make-js2-return-node :pos pos
8323 :len (- end pos)
8324 :retval e))
8325 (js2-node-add-children ret e)
8326 ;; See if we need a strict mode warning.
8327 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8328 ;; more thorough and accurate than this before/after flag check.
8329 ;; E.g. if there's a finally-block that always returns, we shouldn't
8330 ;; show a warning generated by inconsistent returns in the catch blocks.
8331 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8332 ;; so we know which returns/yields to highlight, and we should get rid of
8333 ;; all the checking in `js2-parse-return-or-yield'.
8334 (if (and js2-strict-inconsistent-return-warning
8335 (js2-now-all-set before js2-end-flags
8336 (logior js2-end-returns js2-end-returns-value)))
8337 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8338 (t
8339 (unless (js2-inside-function)
8340 (js2-report-error "msg.bad.yield"))
8341 (js2-set-flag js2-end-flags js2-end-yields)
8342 (setq ret (make-js2-yield-node :pos pos
8343 :len (- end pos)
8344 :value e))
8345 (js2-node-add-children ret e)
8346 (unless expr-context
8347 (setq e ret
8348 ret (js2-wrap-with-expr-stmt pos e t))
8349 (js2-set-requires-activation)
8350 (js2-set-is-generator))))
8351 ;; see if we are mixing yields and value returns.
8352 (when (and inside-function
8353 (js2-now-all-set before js2-end-flags
8354 (logior js2-end-yields js2-end-returns-value)))
8355 (setq name (js2-function-name js2-current-script-or-fn))
8356 (if (zerop (length name))
8357 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8358 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8359 ret))
8360
8361 (defun js2-parse-debugger ()
8362 (js2-consume-token)
8363 (make-js2-keyword-node :type js2-DEBUGGER))
8364
8365 (defun js2-parse-block ()
8366 "Parser for a curly-delimited statement block.
8367 Last token matched must be js2-LC."
8368 (let ((pos js2-token-beg)
8369 (pn (make-js2-scope)))
8370 (js2-consume-token)
8371 (js2-push-scope pn)
8372 (unwind-protect
8373 (progn
8374 (js2-parse-statements pn)
8375 (js2-must-match js2-RC "msg.no.brace.block")
8376 (setf (js2-node-len pn) (- js2-token-end pos)))
8377 (js2-pop-scope))
8378 pn))
8379
8380 ;; for js2-ERROR too, to have a node for error recovery to work on
8381 (defun js2-parse-semi ()
8382 "Parse a statement or handle an error.
8383 Last matched token is js2-SEMI or js2-ERROR."
8384 (let ((tt (js2-peek-token)) pos len)
8385 (js2-consume-token)
8386 (if (eq tt js2-SEMI)
8387 (make-js2-empty-expr-node :len 1)
8388 (setq pos js2-token-beg
8389 len (- js2-token-beg pos))
8390 (js2-report-error "msg.syntax" nil pos len)
8391 (make-js2-error-node :pos pos :len len))))
8392
8393 (defun js2-parse-default-xml-namespace ()
8394 "Parse a `default xml namespace = <expr>' e4x statement."
8395 (let ((pos js2-token-beg)
8396 end len expr unary es)
8397 (js2-consume-token)
8398 (js2-must-have-xml)
8399 (js2-set-requires-activation)
8400 (setq len (- js2-ts-cursor pos))
8401 (unless (and (js2-match-token js2-NAME)
8402 (string= js2-ts-string "xml"))
8403 (js2-report-error "msg.bad.namespace" nil pos len))
8404 (unless (and (js2-match-token js2-NAME)
8405 (string= js2-ts-string "namespace"))
8406 (js2-report-error "msg.bad.namespace" nil pos len))
8407 (unless (js2-match-token js2-ASSIGN)
8408 (js2-report-error "msg.bad.namespace" nil pos len))
8409 (setq expr (js2-parse-expr)
8410 end (js2-node-end expr)
8411 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8412 :pos pos
8413 :len (- end pos)
8414 :operand expr))
8415 (js2-node-add-children unary expr)
8416 (make-js2-expr-stmt-node :pos pos
8417 :len (- end pos)
8418 :expr unary)))
8419
8420 (defun js2-record-label (label bundle)
8421 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8422 (js2-consume-token)
8423 (let ((name (js2-label-node-name label))
8424 labeled-stmt
8425 dup)
8426 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8427 ;; flag both labels if possible when used in editing mode
8428 (if (and js2-parse-ide-mode
8429 (setq dup (js2-get-label-by-name labeled-stmt name)))
8430 (js2-report-error "msg.dup.label" nil
8431 (js2-node-abs-pos dup) (js2-node-len dup)))
8432 (js2-report-error "msg.dup.label" nil
8433 (js2-node-pos label) (js2-node-len label)))
8434 (js2-labeled-stmt-node-add-label bundle label)
8435 (js2-node-add-children bundle label)
8436 ;; Add one reference to the bundle per label in `js2-label-set'
8437 (push (cons name bundle) js2-label-set)))
8438
8439 (defun js2-parse-name-or-label ()
8440 "Parser for identifier or label. Last token matched must be js2-NAME.
8441 Called when we found a name in a statement context. If it's a label, we gather
8442 up any following labels and the next non-label statement into a
8443 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8444 expression and return it wrapped in a `js2-expr-stmt-node'."
8445 (let ((pos js2-token-beg)
8446 (end js2-token-end)
8447 expr
8448 stmt
8449 pn
8450 bundle
8451 (continue t))
8452 ;; set check for label and call down to `js2-parse-primary-expr'
8453 (js2-set-check-for-label)
8454 (setq expr (js2-parse-expr))
8455 (if (/= (js2-node-type expr) js2-LABEL)
8456 ;; Parsed non-label expression - wrap with expression stmt.
8457 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8458 ;; else parsed a label
8459 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8460 (js2-record-label expr bundle)
8461 ;; look for more labels
8462 (while (and continue (= (js2-peek-token) js2-NAME))
8463 (js2-set-check-for-label)
8464 (setq expr (js2-parse-expr))
8465 (if (/= (js2-node-type expr) js2-LABEL)
8466 (progn
8467 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8468 continue nil)
8469 (js2-auto-insert-semicolon stmt))
8470 (js2-record-label expr bundle)))
8471 ;; no more labels; now parse the labeled statement
8472 (unwind-protect
8473 (unless stmt
8474 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8475 (setq stmt (js2-statement-helper))))
8476 ;; remove the labels for this statement from the global set
8477 (dolist (label (js2-labeled-stmt-node-labels bundle))
8478 (setq js2-label-set (remove label js2-label-set))))
8479 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8480 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8481 (js2-node-add-children bundle stmt)
8482 bundle)))
8483
8484 (defun js2-parse-expr-stmt ()
8485 "Default parser in statement context, if no recognized statement found."
8486 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8487
8488 (defun js2-parse-variables (decl-type pos)
8489 "Parse a comma-separated list of variable declarations.
8490 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8491
8492 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8493 For 'var' or 'const', the keyword should be the token last scanned.
8494
8495 POS is the position where the node should start. It's sometimes the
8496 var/const/let keyword, and other times the beginning of the first token
8497 in the first variable declaration.
8498
8499 Returns the parsed `js2-var-decl-node' expression node."
8500 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8501 :pos pos))
8502 destructuring
8503 kid-pos
8504 tt
8505 init
8506 name
8507 end
8508 nbeg nend
8509 vi
8510 (continue t))
8511 ;; Example:
8512 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8513 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8514 ;; var {a, b} = baz;
8515 (while continue
8516 (setq destructuring nil
8517 name nil
8518 tt (js2-peek-token)
8519 kid-pos js2-token-beg
8520 end js2-token-end
8521 init nil)
8522 (if (or (= tt js2-LB) (= tt js2-LC))
8523 ;; Destructuring assignment, e.g., var [a, b] = ...
8524 (setq destructuring (js2-parse-destruct-primary-expr)
8525 end (js2-node-end destructuring))
8526 ;; Simple variable name
8527 (when (js2-must-match js2-NAME "msg.bad.var")
8528 (setq name (js2-create-name-node)
8529 nbeg js2-token-beg
8530 nend js2-token-end
8531 end nend)
8532 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8533 (when (js2-match-token js2-ASSIGN)
8534 (setq init (js2-parse-assign-expr)
8535 end (js2-node-end init))
8536 (js2-record-imenu-functions init name))
8537 (when name
8538 (js2-set-face nbeg nend (if (js2-function-node-p init)
8539 'font-lock-function-name-face
8540 'font-lock-variable-name-face)
8541 'record))
8542 (setq vi (make-js2-var-init-node :pos kid-pos
8543 :len (- end kid-pos)
8544 :type decl-type))
8545 (if destructuring
8546 (progn
8547 (if (and (null init) (not js2-in-for-init))
8548 (js2-report-error "msg.destruct.assign.no.init"))
8549 (js2-define-destruct-symbols destructuring
8550 decl-type
8551 'font-lock-variable-name-face)
8552 (setf (js2-var-init-node-target vi) destructuring))
8553 (setf (js2-var-init-node-target vi) name))
8554 (setf (js2-var-init-node-initializer vi) init)
8555 (js2-node-add-children vi name destructuring init)
8556 (js2-block-node-push result vi)
8557 (unless (js2-match-token js2-COMMA)
8558 (setq continue nil)))
8559 (setf (js2-node-len result) (- end pos))
8560 result))
8561
8562 (defun js2-parse-let (pos &optional stmt-p)
8563 "Parse a let expression or statement.
8564 A let-expression is of the form `let (vars) expr'.
8565 A let-statment is of the form `let (vars) {statements}'.
8566 The third form of let is a variable declaration list, handled
8567 by `js2-parse-variables'."
8568 (let ((pn (make-js2-let-node :pos pos))
8569 beg vars body)
8570 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8571 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8572 (js2-push-scope pn)
8573 (unwind-protect
8574 (progn
8575 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8576 (if (js2-must-match js2-RP "msg.no.paren.let")
8577 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8578 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8579 ;; let statement
8580 (progn
8581 (js2-consume-token)
8582 (setf beg js2-token-beg ; position stmt at LC
8583 body (js2-parse-statements))
8584 (js2-must-match js2-RC "msg.no.curly.let")
8585 (setf (js2-node-len body) (- js2-token-end beg)
8586 (js2-node-len pn) (- js2-token-end pos)
8587 (js2-let-node-body pn) body
8588 (js2-node-type pn) js2-LET))
8589 ;; let expression
8590 (setf body (js2-parse-expr)
8591 (js2-node-len pn) (- (js2-node-end body) pos)
8592 (js2-let-node-body pn) body))
8593 (js2-node-add-children pn vars body))
8594 (js2-pop-scope))
8595 pn))
8596
8597 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8598 (js2-scope-put-symbol (or scope js2-current-scope)
8599 name
8600 (make-js2-symbol decl-type name node)))
8601
8602 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8603 "Define a symbol in the current scope.
8604 If NODE is non-nil, it is the AST node associated with the symbol."
8605 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8606 (symbol (if defining-scope
8607 (js2-scope-get-symbol defining-scope name)))
8608 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8609 (cond
8610 ((and symbol ; already defined
8611 (or (= sdt js2-CONST) ; old version is const
8612 (= decl-type js2-CONST) ; new version is const
8613 ;; two let-bound vars in this block have same name
8614 (and (= sdt js2-LET)
8615 (eq defining-scope js2-current-scope))))
8616 (js2-report-error
8617 (cond
8618 ((= sdt js2-CONST) "msg.const.redecl")
8619 ((= sdt js2-LET) "msg.let.redecl")
8620 ((= sdt js2-VAR) "msg.var.redecl")
8621 ((= sdt js2-FUNCTION) "msg.function.redecl")
8622 (t "msg.parm.redecl"))
8623 name))
8624 ((= decl-type js2-LET)
8625 (if (and (not ignore-not-in-block)
8626 (or (= (js2-node-type js2-current-scope) js2-IF)
8627 (js2-loop-node-p js2-current-scope)))
8628 (js2-report-error "msg.let.decl.not.in.block")
8629 (js2-define-new-symbol decl-type name node)))
8630 ((or (= decl-type js2-VAR)
8631 (= decl-type js2-CONST)
8632 (= decl-type js2-FUNCTION))
8633 (if symbol
8634 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8635 (js2-add-strict-warning "msg.var.redecl" name)
8636 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8637 (js2-add-strict-warning "msg.var.hides.arg" name)))
8638 (js2-define-new-symbol decl-type name node
8639 js2-current-script-or-fn)))
8640 ((= decl-type js2-LP)
8641 (if symbol
8642 ;; must be duplicate parameter. Second parameter hides the
8643 ;; first, so go ahead and add the second pararameter
8644 (js2-report-warning "msg.dup.parms" name))
8645 (js2-define-new-symbol decl-type name node))
8646 (t (js2-code-bug)))))
8647
8648 (defun js2-parse-expr (&optional oneshot)
8649 (let* ((pn (js2-parse-assign-expr))
8650 (pos (js2-node-pos pn))
8651 left
8652 right
8653 op-pos)
8654 (while (and (not oneshot)
8655 (js2-match-token js2-COMMA))
8656 (setq op-pos (- js2-token-beg pos)) ; relative
8657 (if (= (js2-peek-token) js2-YIELD)
8658 (js2-report-error "msg.yield.parenthesized"))
8659 (setq right (js2-parse-assign-expr)
8660 left pn
8661 pn (make-js2-infix-node :type js2-COMMA
8662 :pos pos
8663 :len (- js2-ts-cursor pos)
8664 :op-pos op-pos
8665 :left left
8666 :right right))
8667 (js2-node-add-children pn left right))
8668 pn))
8669
8670 (defun js2-parse-assign-expr ()
8671 (let ((tt (js2-peek-token))
8672 (pos js2-token-beg)
8673 pn
8674 left
8675 right
8676 op-pos)
8677 (if (= tt js2-YIELD)
8678 (js2-parse-return-or-yield tt t)
8679 ;; not yield - parse assignment expression
8680 (setq pn (js2-parse-cond-expr)
8681 tt (js2-peek-token))
8682 (when (and (<= js2-first-assign tt)
8683 (<= tt js2-last-assign))
8684 ;; tt express assignment (=, |=, ^=, ..., %=)
8685 (js2-consume-token)
8686 (setq op-pos (- js2-token-beg pos) ; relative
8687 left pn
8688 right (js2-parse-assign-expr)
8689 pn (make-js2-assign-node :type tt
8690 :pos pos
8691 :len (- (js2-node-end right) pos)
8692 :op-pos op-pos
8693 :left left
8694 :right right))
8695 (when js2-parse-ide-mode
8696 (js2-highlight-assign-targets pn left right)
8697 (js2-record-imenu-functions right left))
8698 ;; do this last so ide checks above can use absolute positions
8699 (js2-node-add-children pn left right))
8700 pn)))
8701
8702 (defun js2-parse-cond-expr ()
8703 (let ((pos js2-token-beg)
8704 (pn (js2-parse-or-expr))
8705 test-expr
8706 if-true
8707 if-false
8708 q-pos
8709 c-pos)
8710 (when (js2-match-token js2-HOOK)
8711 (setq q-pos (- js2-token-beg pos)
8712 if-true (js2-parse-assign-expr))
8713 (js2-must-match js2-COLON "msg.no.colon.cond")
8714 (setq c-pos (- js2-token-beg pos)
8715 if-false (js2-parse-assign-expr)
8716 test-expr pn
8717 pn (make-js2-cond-node :pos pos
8718 :len (- (js2-node-end if-false) pos)
8719 :test-expr test-expr
8720 :true-expr if-true
8721 :false-expr if-false
8722 :q-pos q-pos
8723 :c-pos c-pos))
8724 (js2-node-add-children pn test-expr if-true if-false))
8725 pn))
8726
8727 (defun js2-make-binary (type left parser)
8728 "Helper for constructing a binary-operator AST node.
8729 LEFT is the left-side-expression, already parsed, and the
8730 binary operator should have just been matched.
8731 PARSER is a function to call to parse the right operand,
8732 or a `js2-node' struct if it has already been parsed."
8733 (let* ((pos (js2-node-pos left))
8734 (op-pos (- js2-token-beg pos))
8735 (right (if (js2-node-p parser)
8736 parser
8737 (funcall parser)))
8738 (pn (make-js2-infix-node :type type
8739 :pos pos
8740 :len (- (js2-node-end right) pos)
8741 :op-pos op-pos
8742 :left left
8743 :right right)))
8744 (js2-node-add-children pn left right)
8745 pn))
8746
8747 (defun js2-parse-or-expr ()
8748 (let ((pn (js2-parse-and-expr)))
8749 (when (js2-match-token js2-OR)
8750 (setq pn (js2-make-binary js2-OR
8751 pn
8752 'js2-parse-or-expr)))
8753 pn))
8754
8755 (defun js2-parse-and-expr ()
8756 (let ((pn (js2-parse-bit-or-expr)))
8757 (when (js2-match-token js2-AND)
8758 (setq pn (js2-make-binary js2-AND
8759 pn
8760 'js2-parse-and-expr)))
8761 pn))
8762
8763 (defun js2-parse-bit-or-expr ()
8764 (let ((pn (js2-parse-bit-xor-expr)))
8765 (while (js2-match-token js2-BITOR)
8766 (setq pn (js2-make-binary js2-BITOR
8767 pn
8768 'js2-parse-bit-xor-expr)))
8769 pn))
8770
8771 (defun js2-parse-bit-xor-expr ()
8772 (let ((pn (js2-parse-bit-and-expr)))
8773 (while (js2-match-token js2-BITXOR)
8774 (setq pn (js2-make-binary js2-BITXOR
8775 pn
8776 'js2-parse-bit-and-expr)))
8777 pn))
8778
8779 (defun js2-parse-bit-and-expr ()
8780 (let ((pn (js2-parse-eq-expr)))
8781 (while (js2-match-token js2-BITAND)
8782 (setq pn (js2-make-binary js2-BITAND
8783 pn
8784 'js2-parse-eq-expr)))
8785 pn))
8786
8787 (defconst js2-parse-eq-ops
8788 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8789
8790 (defun js2-parse-eq-expr ()
8791 (let ((pn (js2-parse-rel-expr))
8792 tt)
8793 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8794 (js2-consume-token)
8795 (setq pn (js2-make-binary tt
8796 pn
8797 'js2-parse-rel-expr)))
8798 pn))
8799
8800 (defconst js2-parse-rel-ops
8801 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8802
8803 (defun js2-parse-rel-expr ()
8804 (let ((pn (js2-parse-shift-expr))
8805 (continue t)
8806 tt)
8807 (while continue
8808 (setq tt (js2-peek-token))
8809 (cond
8810 ((and js2-in-for-init (= tt js2-IN))
8811 (setq continue nil))
8812 ((memq tt js2-parse-rel-ops)
8813 (js2-consume-token)
8814 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8815 (t
8816 (setq continue nil))))
8817 pn))
8818
8819 (defconst js2-parse-shift-ops
8820 (list js2-LSH js2-URSH js2-RSH))
8821
8822 (defun js2-parse-shift-expr ()
8823 (let ((pn (js2-parse-add-expr))
8824 tt
8825 (continue t))
8826 (while continue
8827 (setq tt (js2-peek-token))
8828 (if (memq tt js2-parse-shift-ops)
8829 (progn
8830 (js2-consume-token)
8831 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8832 (setq continue nil)))
8833 pn))
8834
8835 (defun js2-parse-add-expr ()
8836 (let ((pn (js2-parse-mul-expr))
8837 tt
8838 (continue t))
8839 (while continue
8840 (setq tt (js2-peek-token))
8841 (if (or (= tt js2-ADD) (= tt js2-SUB))
8842 (progn
8843 (js2-consume-token)
8844 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8845 (setq continue nil)))
8846 pn))
8847
8848 (defconst js2-parse-mul-ops
8849 (list js2-MUL js2-DIV js2-MOD))
8850
8851 (defun js2-parse-mul-expr ()
8852 (let ((pn (js2-parse-unary-expr))
8853 tt
8854 (continue t))
8855 (while continue
8856 (setq tt (js2-peek-token))
8857 (if (memq tt js2-parse-mul-ops)
8858 (progn
8859 (js2-consume-token)
8860 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8861 (setq continue nil)))
8862 pn))
8863
8864 (defsubst js2-make-unary (type parser &rest args)
8865 "Make a unary node of type TYPE.
8866 PARSER is either a node (for postfix operators) or a function to call
8867 to parse the operand (for prefix operators)."
8868 (let* ((pos js2-token-beg)
8869 (postfix (js2-node-p parser))
8870 (expr (if postfix
8871 parser
8872 (apply parser args)))
8873 end
8874 pn)
8875 (if postfix ; e.g. i++
8876 (setq pos (js2-node-pos expr)
8877 end js2-token-end)
8878 (setq end (js2-node-end expr)))
8879 (setq pn (make-js2-unary-node :type type
8880 :pos pos
8881 :len (- end pos)
8882 :operand expr))
8883 (js2-node-add-children pn expr)
8884 pn))
8885
8886 (defconst js2-incrementable-node-types
8887 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8888 "Node types that can be the operand of a ++ or -- operator.")
8889
8890 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8891 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8892 js2-incrementable-node-types)
8893 (js2-report-error (if (= tt js2-INC)
8894 "msg.bad.incr"
8895 "msg.bad.decr")
8896 nil beg (- end beg))))
8897
8898 (defun js2-parse-unary-expr ()
8899 (let ((tt (js2-peek-token))
8900 pn expr beg end)
8901 (cond
8902 ((or (= tt js2-VOID)
8903 (= tt js2-NOT)
8904 (= tt js2-BITNOT)
8905 (= tt js2-TYPEOF))
8906 (js2-consume-token)
8907 (js2-make-unary tt 'js2-parse-unary-expr))
8908 ((= tt js2-ADD)
8909 (js2-consume-token)
8910 ;; Convert to special POS token in decompiler and parse tree
8911 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8912 ((= tt js2-SUB)
8913 (js2-consume-token)
8914 ;; Convert to special NEG token in decompiler and parse tree
8915 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8916 ((or (= tt js2-INC)
8917 (= tt js2-DEC))
8918 (js2-consume-token)
8919 (prog1
8920 (setq beg js2-token-beg
8921 end js2-token-end
8922 expr (js2-make-unary tt 'js2-parse-member-expr t))
8923 (js2-check-bad-inc-dec tt beg end expr)))
8924 ((= tt js2-DELPROP)
8925 (js2-consume-token)
8926 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8927 ((= tt js2-ERROR)
8928 (js2-consume-token)
8929 (make-js2-error-node)) ; try to continue
8930 ((and (= tt js2-LT)
8931 js2-compiler-xml-available)
8932 ;; XML stream encountered in expression.
8933 (js2-consume-token)
8934 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8935 (t
8936 (setq pn (js2-parse-member-expr t)
8937 ;; Don't look across a newline boundary for a postfix incop.
8938 tt (js2-peek-token-or-eol))
8939 (when (or (= tt js2-INC) (= tt js2-DEC))
8940 (js2-consume-token)
8941 (setf expr pn
8942 pn (js2-make-unary tt expr))
8943 (js2-node-set-prop pn 'postfix t)
8944 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8945 pn))))
8946
8947 (defun js2-parse-xml-initializer ()
8948 "Parse an E4X XML initializer.
8949 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8950 Then I'll postprocess the result, depending on whether we're in IDE
8951 mode or codegen mode, and generate the appropriate rewritten AST.
8952 IDE mode uses a rich AST that models the XML structure. Codegen mode
8953 just concatenates everything and makes a new XML or XMLList out of it."
8954 (let ((tt (js2-get-first-xml-token))
8955 pn-xml
8956 pn
8957 expr
8958 kids
8959 expr-pos
8960 (continue t)
8961 (first-token t))
8962 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8963 (js2-report-error "msg.syntax"))
8964 (setq pn-xml (make-js2-xml-node))
8965 (while continue
8966 (if first-token
8967 (setq first-token nil)
8968 (setq tt (js2-get-next-xml-token)))
8969 (cond
8970 ;; js2-XML means we found a {expr} in the XML stream.
8971 ;; The js2-ts-string is the XML up to the left-curly.
8972 ((= tt js2-XML)
8973 (push (make-js2-string-node :pos js2-token-beg
8974 :len (- js2-ts-cursor js2-token-beg))
8975 kids)
8976 (js2-must-match js2-LC "msg.syntax")
8977 (setq expr-pos js2-ts-cursor
8978 expr (if (eq (js2-peek-token) js2-RC)
8979 (make-js2-empty-expr-node :pos expr-pos)
8980 (js2-parse-expr)))
8981 (js2-must-match js2-RC "msg.syntax")
8982 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8983 :len (js2-node-len expr)
8984 :expr expr))
8985 (js2-node-add-children pn expr)
8986 (push pn kids))
8987 ;; a js2-XMLEND token means we hit the final close-tag.
8988 ((= tt js2-XMLEND)
8989 (push (make-js2-string-node :pos js2-token-beg
8990 :len (- js2-ts-cursor js2-token-beg))
8991 kids)
8992 (dolist (kid (nreverse kids))
8993 (js2-block-node-push pn-xml kid))
8994 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8995 (js2-node-pos pn-xml))
8996 continue nil))
8997 (t
8998 (js2-report-error "msg.syntax")
8999 (setq continue nil))))
9000 pn-xml))
9001
9002
9003 (defun js2-parse-argument-list ()
9004 "Parse an argument list and return it as a lisp list of nodes.
9005 Returns the list in reverse order. Consumes the right-paren token."
9006 (let (result)
9007 (unless (js2-match-token js2-RP)
9008 (loop do
9009 (if (= (js2-peek-token) js2-YIELD)
9010 (js2-report-error "msg.yield.parenthesized"))
9011 (push (js2-parse-assign-expr) result)
9012 while
9013 (js2-match-token js2-COMMA))
9014 (js2-must-match js2-RP "msg.no.paren.arg")
9015 result)))
9016
9017 (defun js2-parse-member-expr (&optional allow-call-syntax)
9018 (let ((tt (js2-peek-token))
9019 pn
9020 pos
9021 target
9022 args
9023 beg
9024 end
9025 init
9026 tail)
9027 (if (/= tt js2-NEW)
9028 (setq pn (js2-parse-primary-expr))
9029 ;; parse a 'new' expression
9030 (js2-consume-token)
9031 (setq pos js2-token-beg
9032 beg pos
9033 target (js2-parse-member-expr)
9034 end (js2-node-end target)
9035 pn (make-js2-new-node :pos pos
9036 :target target
9037 :len (- end pos)))
9038 (js2-node-add-children pn target)
9039 (when (js2-match-token js2-LP)
9040 ;; Add the arguments to pn, if any are supplied.
9041 (setf beg pos ; start of "new" keyword
9042 pos js2-token-beg
9043 args (nreverse (js2-parse-argument-list))
9044 (js2-new-node-args pn) args
9045 end js2-token-end
9046 (js2-new-node-lp pn) (- pos beg)
9047 (js2-new-node-rp pn) (- end 1 beg))
9048 (apply #'js2-node-add-children pn args))
9049 (when (and js2-allow-rhino-new-expr-initializer
9050 (js2-match-token js2-LC))
9051 (setf init (js2-parse-object-literal)
9052 end (js2-node-end init)
9053 (js2-new-node-initializer pn) init)
9054 (js2-node-add-children pn init))
9055 (setf (js2-node-len pn) (- end beg))) ; end outer if
9056 (js2-parse-member-expr-tail allow-call-syntax pn)))
9057
9058 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9059 "Parse a chain of property/array accesses or function calls.
9060 Includes parsing for E4X operators like `..' and `.@'.
9061 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9062 Returns an expression tree that includes PN, the parent node."
9063 (let ((beg (js2-node-pos pn))
9064 tt
9065 (continue t))
9066 (while continue
9067 (setq tt (js2-peek-token))
9068 (cond
9069 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9070 (setq pn (js2-parse-property-access tt pn)))
9071 ((= tt js2-DOTQUERY)
9072 (setq pn (js2-parse-dot-query pn)))
9073 ((= tt js2-LB)
9074 (setq pn (js2-parse-element-get pn)))
9075 ((= tt js2-LP)
9076 (if allow-call-syntax
9077 (setq pn (js2-parse-function-call pn))
9078 (setq continue nil)))
9079 (t
9080 (setq continue nil))))
9081 (if (>= js2-highlight-level 2)
9082 (js2-parse-highlight-member-expr-node pn))
9083 pn))
9084
9085 (defun js2-parse-dot-query (pn)
9086 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9087 Last token parsed must be `js2-DOTQUERY'."
9088 (let ((pos (js2-node-pos pn))
9089 op-pos
9090 expr
9091 end)
9092 (js2-consume-token)
9093 (js2-must-have-xml)
9094 (js2-set-requires-activation)
9095 (setq op-pos js2-token-beg
9096 expr (js2-parse-expr)
9097 end (js2-node-end expr)
9098 pn (make-js2-xml-dot-query-node :left pn
9099 :pos pos
9100 :op-pos op-pos
9101 :right expr))
9102 (js2-node-add-children pn
9103 (js2-xml-dot-query-node-left pn)
9104 (js2-xml-dot-query-node-right pn))
9105 (if (js2-must-match js2-RP "msg.no.paren")
9106 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9107 end js2-token-end))
9108 (setf (js2-node-len pn) (- end pos))
9109 pn))
9110
9111 (defun js2-parse-element-get (pn)
9112 "Parse an element-get expression, e.g. foo[bar].
9113 Last token parsed must be `js2-RB'."
9114 (let ((lb js2-token-beg)
9115 (pos (js2-node-pos pn))
9116 rb
9117 expr)
9118 (js2-consume-token)
9119 (setq expr (js2-parse-expr))
9120 (if (js2-must-match js2-RB "msg.no.bracket.index")
9121 (setq rb js2-token-beg))
9122 (setq pn (make-js2-elem-get-node :target pn
9123 :pos pos
9124 :element expr
9125 :lb (js2-relpos lb pos)
9126 :rb (js2-relpos rb pos)
9127 :len (- js2-token-end pos)))
9128 (js2-node-add-children pn
9129 (js2-elem-get-node-target pn)
9130 (js2-elem-get-node-element pn))
9131 pn))
9132
9133 (defun js2-parse-function-call (pn)
9134 (let (args
9135 (pos (js2-node-pos pn)))
9136 (js2-consume-token)
9137 (setq pn (make-js2-call-node :pos pos
9138 :target pn
9139 :lp (- js2-token-beg pos)))
9140 (js2-node-add-children pn (js2-call-node-target pn))
9141 ;; Add the arguments to pn, if any are supplied.
9142 (setf args (nreverse (js2-parse-argument-list))
9143 (js2-call-node-rp pn) (- js2-token-beg pos)
9144 (js2-call-node-args pn) args)
9145 (apply #'js2-node-add-children pn args)
9146 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9147 pn))
9148
9149 (defun js2-parse-property-access (tt pn)
9150 "Parse a property access, XML descendants access, or XML attr access."
9151 (let ((member-type-flags 0)
9152 (dot-pos js2-token-beg)
9153 (dot-len (if (= tt js2-DOTDOT) 2 1))
9154 name
9155 ref ; right side of . or .. operator
9156 result)
9157 (js2-consume-token)
9158 (when (= tt js2-DOTDOT)
9159 (js2-must-have-xml)
9160 (setq member-type-flags js2-descendants-flag))
9161 (if (not js2-compiler-xml-available)
9162 (progn
9163 (js2-must-match-prop-name "msg.no.name.after.dot")
9164 (setq name (js2-create-name-node t js2-GETPROP)
9165 result (make-js2-prop-get-node :left pn
9166 :pos js2-token-beg
9167 :right name
9168 :len (- js2-token-end
9169 js2-token-beg)))
9170 (js2-node-add-children result pn name)
9171 result)
9172 ;; otherwise look for XML operators
9173 (setf result (if (= tt js2-DOT)
9174 (make-js2-prop-get-node)
9175 (make-js2-infix-node :type js2-DOTDOT))
9176 (js2-node-pos result) (js2-node-pos pn)
9177 (js2-infix-node-op-pos result) dot-pos
9178 (js2-infix-node-left result) pn ; do this after setting position
9179 tt (js2-next-token))
9180 (cond
9181 ;; needed for generator.throw()
9182 ((= tt js2-THROW)
9183 (js2-save-name-token-data js2-token-beg "throw")
9184 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9185 ;; handles: name, ns::name, ns::*, ns::[expr]
9186 ((js2-valid-prop-name-token tt)
9187 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9188 ;; handles: *, *::name, *::*, *::[expr]
9189 ((= tt js2-MUL)
9190 (js2-save-name-token-data js2-token-beg "*")
9191 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9192 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9193 ((= tt js2-XMLATTR)
9194 (setq result (js2-parse-attribute-access)))
9195 (t
9196 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9197 (if ref
9198 (setf (js2-node-len result) (- (js2-node-end ref)
9199 (js2-node-pos result))
9200 (js2-infix-node-right result) ref))
9201 (if (js2-infix-node-p result)
9202 (js2-node-add-children result
9203 (js2-infix-node-left result)
9204 (js2-infix-node-right result)))
9205 result)))
9206
9207 (defun js2-parse-attribute-access ()
9208 "Parse an E4X XML attribute expression.
9209 This includes expressions of the forms:
9210
9211 @attr @ns::attr @ns::*
9212 @* @*::attr @*::*
9213 @[expr] @*::[expr] @ns::[expr]
9214
9215 Called if we peeked an '@' token."
9216 (let ((tt (js2-next-token))
9217 (at-pos js2-token-beg))
9218 (cond
9219 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9220 ((js2-valid-prop-name-token tt)
9221 (js2-parse-property-name at-pos js2-ts-string 0))
9222 ;; handles: @*, @*::name, @*::*, @*::[expr]
9223 ((= tt js2-MUL)
9224 (js2-save-name-token-data js2-token-beg "*")
9225 (js2-parse-property-name js2-token-beg "*" 0))
9226 ;; handles @[expr]
9227 ((= tt js2-LB)
9228 (js2-parse-xml-elem-ref at-pos))
9229 (t
9230 (js2-report-error "msg.no.name.after.xmlAttr")
9231 ;; Avoid cascaded errors that happen if we make an error node here.
9232 (js2-save-name-token-data js2-token-beg "")
9233 (js2-parse-property-name js2-token-beg "" 0)))))
9234
9235 (defun js2-parse-property-name (at-pos s member-type-flags)
9236 "Check if :: follows name in which case it becomes qualified name.
9237
9238 AT-POS is a natural number if we just read an '@' token, else nil.
9239 S is the name or string that was matched: an identifier, 'throw' or '*'.
9240 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9241
9242 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9243 operator, or the name is followed by ::. For a plain name, returns a
9244 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9245 (let ((pos (or at-pos js2-token-beg))
9246 colon-pos
9247 (name (js2-create-name-node t js2-current-token))
9248 ns
9249 tt
9250 ref
9251 pn)
9252 (catch 'return
9253 (when (js2-match-token js2-COLONCOLON)
9254 (setq ns name
9255 colon-pos js2-token-beg
9256 tt (js2-next-token))
9257 (cond
9258 ;; handles name::name
9259 ((js2-valid-prop-name-token tt)
9260 (setq name (js2-create-name-node)))
9261 ;; handles name::*
9262 ((= tt js2-MUL)
9263 (js2-save-name-token-data js2-token-beg "*")
9264 (setq name (js2-create-name-node)))
9265 ;; handles name::[expr]
9266 ((= tt js2-LB)
9267 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9268 (t
9269 (js2-report-error "msg.no.name.after.coloncolon"))))
9270 (if (and (null ns) (zerop member-type-flags))
9271 name
9272 (prog1
9273 (setq pn
9274 (make-js2-xml-prop-ref-node :pos pos
9275 :len (- (js2-node-end name) pos)
9276 :at-pos at-pos
9277 :colon-pos colon-pos
9278 :propname name))
9279 (js2-node-add-children pn name))))))
9280
9281 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9282 "Parse the [expr] portion of an xml element reference.
9283 For instance, @[expr], @*::[expr], or ns::[expr]."
9284 (let* ((lb js2-token-beg)
9285 (pos (or at-pos lb))
9286 rb
9287 (expr (js2-parse-expr))
9288 (end (js2-node-end expr))
9289 pn)
9290 (if (js2-must-match js2-RB "msg.no.bracket.index")
9291 (setq rb js2-token-beg
9292 end js2-token-end))
9293 (prog1
9294 (setq pn
9295 (make-js2-xml-elem-ref-node :pos pos
9296 :len (- end pos)
9297 :namespace namespace
9298 :colon-pos colon-pos
9299 :at-pos at-pos
9300 :expr expr
9301 :lb (js2-relpos lb pos)
9302 :rb (js2-relpos rb pos)))
9303 (js2-node-add-children pn namespace expr))))
9304
9305 (defun js2-parse-destruct-primary-expr ()
9306 (let ((js2-is-in-destructuring t))
9307 (js2-parse-primary-expr)))
9308
9309 (defun js2-parse-primary-expr ()
9310 "Parses a literal (leaf) expression of some sort.
9311 Includes complex literals such as functions, object-literals,
9312 array-literals, array comprehensions and regular expressions."
9313 (let ((tt-flagged (js2-next-flagged-token))
9314 pn ; parent node (usually return value)
9315 tt
9316 px-pos ; paren-expr pos
9317 len
9318 flags ; regexp flags
9319 expr)
9320 (setq tt js2-current-token)
9321 (cond
9322 ((= tt js2-FUNCTION)
9323 (js2-parse-function 'FUNCTION_EXPRESSION))
9324 ((= tt js2-LB)
9325 (js2-parse-array-literal))
9326 ((= tt js2-LC)
9327 (js2-parse-object-literal))
9328 ((= tt js2-LET)
9329 (js2-parse-let js2-token-beg))
9330 ((= tt js2-LP)
9331 (setq px-pos js2-token-beg
9332 expr (js2-parse-expr))
9333 (js2-must-match js2-RP "msg.no.paren")
9334 (setq pn (make-js2-paren-node :pos px-pos
9335 :expr expr
9336 :len (- js2-token-end px-pos)))
9337 (js2-node-add-children pn (js2-paren-node-expr pn))
9338 pn)
9339 ((= tt js2-XMLATTR)
9340 (js2-must-have-xml)
9341 (js2-parse-attribute-access))
9342 ((= tt js2-NAME)
9343 (js2-parse-name tt-flagged tt))
9344 ((= tt js2-NUMBER)
9345 (make-js2-number-node))
9346 ((= tt js2-STRING)
9347 (prog1
9348 (make-js2-string-node)
9349 (js2-record-face 'font-lock-string-face)))
9350 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9351 ;; Got / or /= which in this context means a regexp literal
9352 (setq px-pos js2-token-beg)
9353 (js2-read-regexp tt)
9354 (setq flags js2-ts-regexp-flags
9355 js2-ts-regexp-flags nil)
9356 (prog1
9357 (make-js2-regexp-node :pos px-pos
9358 :len (- js2-ts-cursor px-pos)
9359 :value js2-ts-string
9360 :flags flags)
9361 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9362 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9363 ((or (= tt js2-NULL)
9364 (= tt js2-THIS)
9365 (= tt js2-FALSE)
9366 (= tt js2-TRUE))
9367 (make-js2-keyword-node :type tt))
9368 ((= tt js2-RESERVED)
9369 (js2-report-error "msg.reserved.id")
9370 (make-js2-name-node))
9371 ((= tt js2-ERROR)
9372 ;; the scanner or one of its subroutines reported the error.
9373 (make-js2-error-node))
9374 ((= tt js2-EOF)
9375 (setq px-pos (point-at-bol)
9376 len (- js2-ts-cursor px-pos))
9377 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9378 (make-js2-error-node :pos px-pos :len len))
9379 (t
9380 (js2-report-error "msg.syntax")
9381 (make-js2-error-node)))))
9382
9383 (defun js2-parse-name (tt-flagged tt)
9384 (let ((name js2-ts-string)
9385 (name-pos js2-token-beg)
9386 node)
9387 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9388 (= (js2-peek-token) js2-COLON))
9389 (prog1
9390 ;; Do not consume colon, it is used as unwind indicator
9391 ;; to return to statementHelper.
9392 (make-js2-label-node :pos name-pos
9393 :len (- js2-token-end name-pos)
9394 :name name)
9395 (js2-set-face name-pos
9396 js2-token-end
9397 'font-lock-variable-name-face 'record))
9398 ;; Otherwise not a label, just a name. Unfortunately peeking
9399 ;; the next token to check for a colon has biffed js2-token-beg
9400 ;; and js2-token-end. We store the name's bounds in buffer vars
9401 ;; and `js2-create-name-node' uses them.
9402 (js2-save-name-token-data name-pos name)
9403 (setq node (if js2-compiler-xml-available
9404 (js2-parse-property-name nil name 0)
9405 (js2-create-name-node 'check-activation)))
9406 (if js2-highlight-external-variables
9407 (js2-record-name-node node))
9408 node)))
9409
9410 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9411 (js2-add-strict-warning
9412 msg nil
9413 ;; back up from comma to beginning of line or array/objlit
9414 (max (if elems
9415 (js2-node-pos (car elems))
9416 pos)
9417 (save-excursion
9418 (goto-char comma-pos)
9419 (back-to-indentation)
9420 (point)))
9421 comma-pos))
9422
9423 (defun js2-parse-array-literal ()
9424 (let ((pos js2-token-beg)
9425 (end js2-token-end)
9426 (after-lb-or-comma t)
9427 after-comma
9428 tt
9429 elems
9430 pn
9431 (continue t))
9432 (unless js2-is-in-destructuring
9433 (js2-push-scope (make-js2-scope))) ; for array comp
9434 (while continue
9435 (setq tt (js2-peek-token))
9436 (cond
9437 ;; comma
9438 ((= tt js2-COMMA)
9439 (js2-consume-token)
9440 (setq after-comma js2-token-end)
9441 (if (not after-lb-or-comma)
9442 (setq after-lb-or-comma t)
9443 (push nil elems)))
9444 ;; end of array
9445 ((or (= tt js2-RB)
9446 (= tt js2-EOF)) ; prevent infinite loop
9447 (if (= tt js2-EOF)
9448 (js2-report-error "msg.no.bracket.arg" nil pos)
9449 (js2-consume-token))
9450 (setq continue nil
9451 end js2-token-end
9452 pn (make-js2-array-node :pos pos
9453 :len (- js2-ts-cursor pos)
9454 :elems (nreverse elems)))
9455 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9456 (when (and after-comma (not js2-is-in-destructuring))
9457 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9458 pos elems after-comma)))
9459 ;; destructuring binding
9460 (js2-is-in-destructuring
9461 (push (if (or (= tt js2-LC)
9462 (= tt js2-LB)
9463 (= tt js2-NAME))
9464 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9465 (js2-parse-destruct-primary-expr)
9466 ;; invalid pattern
9467 (js2-consume-token)
9468 (js2-report-error "msg.bad.var")
9469 (make-js2-error-node))
9470 elems)
9471 (setq after-lb-or-comma nil
9472 after-comma nil))
9473 ;; array comp
9474 ((and (>= js2-language-version 170)
9475 (= tt js2-FOR) ; check for array comprehension
9476 (not after-lb-or-comma) ; "for" can't follow a comma
9477 elems ; must have at least 1 element
9478 (not (cdr elems))) ; but no 2nd element
9479 (setf continue nil
9480 pn (js2-parse-array-comprehension (car elems) pos)))
9481
9482 ;; another element
9483 (t
9484 (unless after-lb-or-comma
9485 (js2-report-error "msg.no.bracket.arg"))
9486 (push (js2-parse-assign-expr) elems)
9487 (setq after-lb-or-comma nil
9488 after-comma nil))))
9489 (unless js2-is-in-destructuring
9490 (js2-pop-scope))
9491 pn))
9492
9493 (defun js2-parse-array-comprehension (expr pos)
9494 "Parse a JavaScript 1.7 Array Comprehension.
9495 EXPR is the first expression after the opening left-bracket.
9496 POS is the beginning of the LB token preceding EXPR.
9497 We should have just parsed the 'for' keyword before calling this function."
9498 (let (loops
9499 loop
9500 first
9501 prev
9502 filter
9503 if-pos
9504 result)
9505 (while (= (js2-peek-token) js2-FOR)
9506 (let ((prev (car loops))) ; rearrange scope chain
9507 (push (setq loop (js2-parse-array-comp-loop)) loops)
9508 (if prev ; each loop is parent scope to the next one
9509 (setf (js2-scope-parent-scope loop) prev)
9510 ; first loop takes expr scope's parent
9511 (setf (js2-scope-parent-scope (setq first loop))
9512 (js2-scope-parent-scope js2-current-scope)))))
9513 ;; set expr scope's parent to the last loop
9514 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9515 (when (= (js2-peek-token) js2-IF)
9516 (js2-consume-token)
9517 (setq if-pos (- js2-token-beg pos) ; relative
9518 filter (js2-parse-condition)))
9519 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9520 (setq result (make-js2-array-comp-node :pos pos
9521 :len (- js2-ts-cursor pos)
9522 :result expr
9523 :loops (nreverse loops)
9524 :filter (car filter)
9525 :lp (js2-relpos (second filter) pos)
9526 :rp (js2-relpos (third filter) pos)
9527 :if-pos if-pos))
9528 (apply #'js2-node-add-children result expr (car filter)
9529 (js2-array-comp-node-loops result))
9530 (setq js2-current-scope first) ; pop to the first loop
9531 result))
9532
9533 (defun js2-parse-array-comp-loop ()
9534 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9535 Last token peeked should be the initial FOR."
9536 (let ((pos js2-token-beg)
9537 (pn (make-js2-array-comp-loop-node))
9538 tt
9539 iter
9540 obj
9541 foreach-p
9542 forof-p
9543 in-pos
9544 each-pos
9545 lp
9546 rp)
9547 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9548 (js2-push-scope pn)
9549 (unwind-protect
9550 (progn
9551 (when (js2-match-token js2-NAME)
9552 (if (string= js2-ts-string "each")
9553 (progn
9554 (setq foreach-p t
9555 each-pos (- js2-token-beg pos)) ; relative
9556 (js2-record-face 'font-lock-keyword-face))
9557 (js2-report-error "msg.no.paren.for")))
9558 (if (js2-must-match js2-LP "msg.no.paren.for")
9559 (setq lp (- js2-token-beg pos)))
9560 (setq tt (js2-peek-token))
9561 (cond
9562 ((or (= tt js2-LB)
9563 (= tt js2-LC))
9564 (setq iter (js2-parse-destruct-primary-expr))
9565 (js2-define-destruct-symbols iter js2-LET
9566 'font-lock-variable-name-face t))
9567 ((js2-match-token js2-NAME)
9568 (setq iter (js2-create-name-node)))
9569 (t
9570 (js2-report-error "msg.bad.var")))
9571 ;; Define as a let since we want the scope of the variable to
9572 ;; be restricted to the array comprehension
9573 (if (js2-name-node-p iter)
9574 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9575 (if (or (js2-match-token js2-IN)
9576 (and (>= js2-language-version 200)
9577 (js2-match-contextual-kwd "of")
9578 (setq forof-p t)))
9579 (setq in-pos (- js2-token-beg pos))
9580 (js2-report-error "msg.in.after.for.name"))
9581 (setq obj (js2-parse-expr))
9582 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9583 (setq rp (- js2-token-beg pos)))
9584 (setf (js2-node-pos pn) pos
9585 (js2-node-len pn) (- js2-ts-cursor pos)
9586 (js2-array-comp-loop-node-iterator pn) iter
9587 (js2-array-comp-loop-node-object pn) obj
9588 (js2-array-comp-loop-node-in-pos pn) in-pos
9589 (js2-array-comp-loop-node-each-pos pn) each-pos
9590 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9591 (js2-array-comp-loop-node-forof-p pn) forof-p
9592 (js2-array-comp-loop-node-lp pn) lp
9593 (js2-array-comp-loop-node-rp pn) rp)
9594 (js2-node-add-children pn iter obj))
9595 (js2-pop-scope))
9596 pn))
9597
9598 (defun js2-parse-object-literal ()
9599 (let ((pos js2-token-beg)
9600 tt
9601 elems
9602 result
9603 after-comma
9604 (continue t))
9605 (while continue
9606 (setq tt (js2-peek-token))
9607 (cond
9608 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9609 ((or (js2-valid-prop-name-token tt)
9610 (= tt js2-STRING))
9611 (setq after-comma nil
9612 result (js2-parse-named-prop tt))
9613 (if (and (null result)
9614 (not js2-recover-from-parse-errors))
9615 (setq continue nil)
9616 (push result elems)))
9617 ;; {12: x} or {10.7: x}
9618 ((= tt js2-NUMBER)
9619 (js2-consume-token)
9620 (setq after-comma nil)
9621 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9622 ;; trailing comma
9623 ((= tt js2-RC)
9624 (setq continue nil)
9625 (if after-comma
9626 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9627 pos elems after-comma)))
9628 (t
9629 (js2-report-error "msg.bad.prop")
9630 (unless js2-recover-from-parse-errors
9631 (setq continue nil)))) ; end switch
9632 (if (js2-match-token js2-COMMA)
9633 (setq after-comma js2-token-end)
9634 (setq continue nil))) ; end loop
9635 (js2-must-match js2-RC "msg.no.brace.prop")
9636 (setq result (make-js2-object-node :pos pos
9637 :len (- js2-ts-cursor pos)
9638 :elems (nreverse elems)))
9639 (apply #'js2-node-add-children result (js2-object-node-elems result))
9640 result))
9641
9642 (defun js2-parse-named-prop (tt)
9643 "Parse a name, string, or getter/setter object property.
9644 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9645 (js2-consume-token)
9646 (let ((string-prop (and (= tt js2-STRING)
9647 (make-js2-string-node)))
9648 expr
9649 (ppos js2-token-beg)
9650 (pend js2-token-end)
9651 (name (js2-create-name-node))
9652 (prop js2-ts-string))
9653 (cond
9654 ;; getter/setter prop
9655 ((and (= tt js2-NAME)
9656 (= (js2-peek-token) js2-NAME)
9657 (or (string= prop "get")
9658 (string= prop "set")))
9659 (js2-consume-token)
9660 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9661 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9662 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9663 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9664 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9665 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9666 ;; when patterns are used in variable declarations, function parameters,
9667 ;; catch-clause, and iterators.
9668 ;; We have to set `js2-is-in-destructuring' to t when the current
9669 ;; expressions are on the left side of any assignment, but it's difficult
9670 ;; because it requires looking ahead of expression.
9671 ((and js2-is-in-destructuring
9672 (= tt js2-NAME)
9673 (let ((ctk (js2-peek-token)))
9674 (or (= ctk js2-COMMA)
9675 (= ctk js2-RC)
9676 (js2-valid-prop-name-token ctk))))
9677 name)
9678 ;; regular prop
9679 (t
9680 (prog1
9681 (setq expr (js2-parse-plain-property (or string-prop name)))
9682 (js2-set-face ppos pend
9683 (if (js2-function-node-p
9684 (js2-object-prop-node-right expr))
9685 'font-lock-function-name-face
9686 'font-lock-variable-name-face)
9687 'record))))))
9688
9689 (defun js2-parse-plain-property (prop)
9690 "Parse a non-getter/setter property in an object literal.
9691 PROP is the node representing the property: a number, name or string."
9692 (js2-must-match js2-COLON "msg.no.colon.prop")
9693 (let* ((pos (js2-node-pos prop))
9694 (colon (- js2-token-beg pos))
9695 (expr (js2-parse-assign-expr))
9696 (result (make-js2-object-prop-node
9697 :pos pos
9698 ;; don't include last consumed token in length
9699 :len (- (+ (js2-node-pos expr)
9700 (js2-node-len expr))
9701 pos)
9702 :left prop
9703 :right expr
9704 :op-pos colon)))
9705 (js2-node-add-children result prop expr)
9706 result))
9707
9708 (defun js2-parse-getter-setter-prop (pos prop get-p)
9709 "Parse getter or setter property in an object literal.
9710 JavaScript syntax is:
9711
9712 { get foo() {...}, set foo(x) {...} }
9713
9714 and expression closure style is also supported
9715
9716 { get foo() x, set foo(x) _x = x }
9717
9718 POS is the start position of the `get' or `set' keyword.
9719 PROP is the `js2-name-node' representing the property name.
9720 GET-P is non-nil if the keyword was `get'."
9721 (let ((type (if get-p js2-GET js2-SET))
9722 result
9723 end
9724 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9725 ;; it has to be an anonymous function, as we already parsed the name
9726 (if (/= (js2-node-type fn) js2-FUNCTION)
9727 (js2-report-error "msg.bad.prop")
9728 (if (plusp (length (js2-function-name fn)))
9729 (js2-report-error "msg.bad.prop")))
9730 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9731 (setq end (js2-node-end fn)
9732 result (make-js2-getter-setter-node :type type
9733 :pos pos
9734 :len (- end pos)
9735 :left prop
9736 :right fn))
9737 (js2-node-add-children result prop fn)
9738 result))
9739
9740 (defun js2-create-name-node (&optional check-activation-p token)
9741 "Create a name node using the token info from last scanned name.
9742 In some cases we need to either synthesize a name node, or we lost
9743 the name token information by peeking. If the TOKEN parameter is
9744 not `js2-NAME', then we use the token info saved in instance vars."
9745 (let ((beg js2-token-beg)
9746 (s js2-ts-string)
9747 name)
9748 (when (/= js2-current-token js2-NAME)
9749 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9750 s js2-prev-name-token-string
9751 js2-prev-name-token-start nil
9752 js2-prev-name-token-string nil))
9753 (setq name (make-js2-name-node :pos beg
9754 :name s
9755 :len (length s)))
9756 (if check-activation-p
9757 (js2-check-activation-name s (or token js2-NAME)))
9758 name))
9759
9760 ;;; Indentation support
9761
9762 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9763 ;; Karl cleverly deduces that the desired indentation level is often a
9764 ;; function of paren/bracket/brace nesting depth, which can be determined
9765 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9766 ;; then does some equally clever checks to see if we're in the context of a
9767 ;; substatement of a possibly braceless statement keyword such as if, while,
9768 ;; or finally. This approach yields pretty good results.
9769
9770 ;; The indenter is often "wrong", however, and needs to be overridden.
9771 ;; The right long-term solution is probably to emulate (or integrate
9772 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9773 ;; parse tree from `js2-parse' is present, which is not true at the
9774 ;; moment the user is typing, computing indentation is still thousands
9775 ;; of lines of code to handle every possible syntactic edge case.
9776
9777 ;; In the meantime, the compromise solution is that we offer a "bounce
9778 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9779 ;; current line indent among various likely guess points. This approach
9780 ;; is far from perfect, but should at least make it slightly easier to
9781 ;; move the line towards its desired indentation when manually
9782 ;; overriding Karl's heuristic nesting guesser.
9783
9784 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9785 ;; extensions such as `let' and Array comprehensions. Major kudos to
9786 ;; Karl for coming up with the initial approach, which packs a lot of
9787 ;; punch for so little code.
9788
9789 (defconst js2-possibly-braceless-keywords-re
9790 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9791 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9792 "try" "while" "with" "let")))
9793 "Regular expression matching keywords that are optionally
9794 followed by an opening brace.")
9795
9796 (defconst js2-indent-operator-re
9797 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9798 (regexp-opt '("in" "instanceof") 'words))
9799 "Regular expression matching operators that affect indentation
9800 of continued expressions.")
9801
9802 (defconst js2-declaration-keyword-re
9803 (regexp-opt '("var" "let" "const") 'words)
9804 "Regular expression matching variable declaration keywords.")
9805
9806 ;; This function has horrible results if you're typing an array
9807 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9808 ;; in conjunction with electric-indent, so just disabling it.
9809 (defsubst js2-code-at-bol-p ()
9810 "Return t if the first character on line is non-whitespace."
9811 nil)
9812
9813 (defun js2-insert-and-indent (key)
9814 "Run command bound to key and indent current line. Runs the command
9815 bound to KEY in the global keymap and indents the current line."
9816 (interactive (list (this-command-keys)))
9817 (let ((cmd (lookup-key (current-global-map) key)))
9818 (if (commandp cmd)
9819 (call-interactively cmd)))
9820 ;; don't do the electric keys inside comments or strings,
9821 ;; and don't do bounce-indent with them.
9822 (let ((parse-state (syntax-ppss (point)))
9823 (js2-bounce-indent-p (js2-code-at-bol-p)))
9824 (unless (or (nth 3 parse-state)
9825 (nth 4 parse-state))
9826 (indent-according-to-mode))))
9827
9828 (defun js2-re-search-forward-inner (regexp &optional bound count)
9829 "Auxiliary function for `js2-re-search-forward'."
9830 (let (parse saved-point)
9831 (while (> count 0)
9832 (re-search-forward regexp bound)
9833 (setq parse (if saved-point
9834 (parse-partial-sexp saved-point (point))
9835 (syntax-ppss (point))))
9836 (cond ((nth 3 parse)
9837 (re-search-forward
9838 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9839 (save-excursion (end-of-line) (point)) t))
9840 ((nth 7 parse)
9841 (forward-line))
9842 ((or (nth 4 parse)
9843 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9844 (re-search-forward "\\*/"))
9845 (t
9846 (setq count (1- count))))
9847 (setq saved-point (point))))
9848 (point))
9849
9850 (defun js2-re-search-forward (regexp &optional bound noerror count)
9851 "Search forward but ignore strings and comments. Invokes
9852 `re-search-forward' but treats the buffer as if strings and
9853 comments have been removed."
9854 (let ((saved-point (point))
9855 (search-expr
9856 (cond ((null count)
9857 '(js2-re-search-forward-inner regexp bound 1))
9858 ((< count 0)
9859 '(js2-re-search-backward-inner regexp bound (- count)))
9860 ((> count 0)
9861 '(js2-re-search-forward-inner regexp bound count)))))
9862 (condition-case err
9863 (eval search-expr)
9864 (search-failed
9865 (goto-char saved-point)
9866 (unless noerror
9867 (error (error-message-string err)))))))
9868
9869 (defun js2-re-search-backward-inner (regexp &optional bound count)
9870 "Auxiliary function for `js2-re-search-backward'."
9871 (let (parse saved-point)
9872 (while (> count 0)
9873 (re-search-backward regexp bound)
9874 (setq parse (if saved-point
9875 (parse-partial-sexp saved-point (point))
9876 (syntax-ppss (point))))
9877 (cond ((nth 3 parse)
9878 (re-search-backward
9879 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9880 (save-excursion (beginning-of-line) (point)) t))
9881 ((nth 7 parse)
9882 (goto-char (nth 8 parse)))
9883 ((or (nth 4 parse)
9884 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9885 (re-search-backward "/\\*"))
9886 (t
9887 (setq count (1- count))))))
9888 (point))
9889
9890 (defun js2-re-search-backward (regexp &optional bound noerror count)
9891 "Search backward but ignore strings and comments. Invokes
9892 `re-search-backward' but treats the buffer as if strings and
9893 comments have been removed."
9894 (let ((saved-point (point))
9895 (search-expr
9896 (cond ((null count)
9897 '(js2-re-search-backward-inner regexp bound 1))
9898 ((< count 0)
9899 '(js2-re-search-forward-inner regexp bound (- count)))
9900 ((> count 0)
9901 '(js2-re-search-backward-inner regexp bound count)))))
9902 (condition-case err
9903 (eval search-expr)
9904 (search-failed
9905 (goto-char saved-point)
9906 (unless noerror
9907 (error (error-message-string err)))))))
9908
9909 (defun js2-looking-at-operator-p ()
9910 "Return non-nil if text after point is an operator (that is not
9911 a comma)."
9912 (save-match-data
9913 (and (looking-at js2-indent-operator-re)
9914 (or (not (looking-at ":"))
9915 (save-excursion
9916 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9917 (looking-at "?")))))))
9918
9919 (defun js2-continued-expression-p ()
9920 "Returns non-nil if the current line continues an expression."
9921 (save-excursion
9922 (back-to-indentation)
9923 (or (js2-looking-at-operator-p)
9924 ;; comment
9925 (and (js2-re-search-backward "\n" nil t)
9926 (progn
9927 (skip-chars-backward " \t")
9928 (unless (bolp)
9929 (backward-char)
9930 (and (js2-looking-at-operator-p)
9931 (and (progn
9932 (backward-char)
9933 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))))))
9934
9935 (defun js2-end-of-do-while-loop-p ()
9936 "Returns non-nil if word after point is `while' of a do-while
9937 statement, else returns nil. A braceless do-while statement
9938 spanning several lines requires that the start of the loop is
9939 indented to the same column as the current line."
9940 (interactive)
9941 (save-excursion
9942 (save-match-data
9943 (when (looking-at "\\s-*\\<while\\>")
9944 (if (save-excursion
9945 (skip-chars-backward "[ \t\n]*}")
9946 (looking-at "[ \t\n]*}"))
9947 (save-excursion
9948 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9949 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9950 (or (looking-at "\\<do\\>")
9951 (let ((saved-indent (current-indentation)))
9952 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9953 (/= (current-indentation) saved-indent)))
9954 (and (looking-at "[ \t]*\\<do\\>")
9955 (not (js2-re-search-forward
9956 "\\<while\\>" (point-at-eol) t))
9957 (= (current-indentation) saved-indent)))))))))
9958
9959 (defun js2-multiline-decl-indentation ()
9960 "Returns the declaration indentation column if the current line belongs
9961 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9962 (let (forward-sexp-function ; use Lisp version
9963 at-opening-bracket)
9964 (save-excursion
9965 (back-to-indentation)
9966 (when (not (looking-at js2-declaration-keyword-re))
9967 (when (looking-at js2-indent-operator-re)
9968 (goto-char (match-end 0))) ; continued expressions are ok
9969 (while (and (not at-opening-bracket)
9970 (not (bobp))
9971 (let ((pos (point)))
9972 (save-excursion
9973 (js2-backward-sws)
9974 (or (eq (char-before) ?,)
9975 (and (not (eq (char-before) ?\;))
9976 (and
9977 (prog2 (skip-chars-backward "[[:punct:]]")
9978 (looking-at js2-indent-operator-re)
9979 (js2-backward-sws))
9980 (not (eq (char-before) ?\;))))
9981 (js2-same-line pos)))))
9982 (condition-case err
9983 (backward-sexp)
9984 (scan-error (setq at-opening-bracket t))))
9985 (when (looking-at js2-declaration-keyword-re)
9986 (- (1+ (match-end 0)) (point-at-bol)))))))
9987
9988 (defun js2-ctrl-statement-indentation ()
9989 "Returns the proper indentation of the current line if it
9990 starts the body of a control statement without braces, else
9991 returns nil."
9992 (let (forward-sexp-function) ; temporarily unbind it
9993 (save-excursion
9994 (back-to-indentation)
9995 (when (and (not (js2-same-line (point-min)))
9996 (not (looking-at "{"))
9997 (js2-re-search-backward "[[:graph:]]" nil t)
9998 (not (looking-at "[{([]"))
9999 (progn
10000 (forward-char)
10001 (when (= (char-before) ?\))
10002 ;; scan-sexps sometimes throws an error
10003 (ignore-errors (backward-sexp))
10004 (skip-chars-backward " \t" (point-at-bol)))
10005 (let ((pt (point)))
10006 (back-to-indentation)
10007 (and (looking-at js2-possibly-braceless-keywords-re)
10008 (= (match-end 0) pt)
10009 (not (js2-end-of-do-while-loop-p))))))
10010 (+ (current-indentation) js2-basic-offset)))))
10011
10012 (defun js2-indent-in-array-comp (parse-status)
10013 "Return non-nil if we think we're in an array comprehension.
10014 In particular, return the buffer position of the first `for' kwd."
10015 (let ((bracket (nth 1 parse-status))
10016 (end (point)))
10017 (when bracket
10018 (save-excursion
10019 (goto-char bracket)
10020 (when (looking-at "\\[")
10021 (forward-char 1)
10022 (js2-forward-sws)
10023 (if (looking-at "[[{]")
10024 (let (forward-sexp-function) ; use lisp version
10025 (forward-sexp) ; skip destructuring form
10026 (js2-forward-sws)
10027 (if (and (/= (char-after) ?,) ; regular array
10028 (looking-at "for"))
10029 (match-beginning 0)))
10030 ;; to skip arbitrary expressions we need the parser,
10031 ;; so we'll just guess at it.
10032 (if (and (> end (point)) ; not empty literal
10033 (re-search-forward "[^,]]* \\(for\\) " end t)
10034 ;; not inside comment or string literal
10035 (let ((state (parse-partial-sexp bracket (point))))
10036 (not (or (nth 3 state) (nth 4 state)))))
10037 (match-beginning 1))))))))
10038
10039 (defun js2-array-comp-indentation (parse-status for-kwd)
10040 (if (js2-same-line for-kwd)
10041 ;; first continuation line
10042 (save-excursion
10043 (goto-char (nth 1 parse-status))
10044 (forward-char 1)
10045 (skip-chars-forward " \t")
10046 (current-column))
10047 (save-excursion
10048 (goto-char for-kwd)
10049 (current-column))))
10050
10051 (defun js2-proper-indentation (parse-status)
10052 "Return the proper indentation for the current line."
10053 (save-excursion
10054 (back-to-indentation)
10055 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10056 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
10057 (continued-expr-p (js2-continued-expression-p))
10058 (declaration-indent (and js2-pretty-multiline-declarations
10059 (js2-multiline-decl-indentation)))
10060 (bracket (nth 1 parse-status))
10061 beg)
10062 (cond
10063 ;; indent array comprehension continuation lines specially
10064 ((and bracket
10065 (>= js2-language-version 170)
10066 (not (js2-same-line bracket))
10067 (setq beg (js2-indent-in-array-comp parse-status))
10068 (>= (point) (save-excursion
10069 (goto-char beg)
10070 (point-at-bol)))) ; at or after first loop?
10071 (js2-array-comp-indentation parse-status beg))
10072
10073 (ctrl-stmt-indent)
10074
10075 ((and declaration-indent continued-expr-p)
10076 (+ declaration-indent js2-basic-offset))
10077
10078 (declaration-indent)
10079
10080 (bracket
10081 (goto-char bracket)
10082 (cond
10083 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10084 (when (save-excursion (skip-chars-backward " \t)")
10085 (looking-at ")"))
10086 (backward-list))
10087 (back-to-indentation)
10088 (and (eq js2-pretty-multiline-declarations 'all)
10089 (looking-at js2-declaration-keyword-re)
10090 (goto-char (1+ (match-end 0))))
10091 (cond (same-indent-p
10092 (current-column))
10093 (continued-expr-p
10094 (+ (current-column) (* 2 js2-basic-offset)))
10095 (t
10096 (+ (current-column) js2-basic-offset))))
10097 (t
10098 (unless same-indent-p
10099 (forward-char)
10100 (skip-chars-forward " \t"))
10101 (current-column))))
10102
10103 (continued-expr-p js2-basic-offset)
10104
10105 (t 0)))))
10106
10107 (defun js2-lineup-comment (parse-status)
10108 "Indent a multi-line block comment continuation line."
10109 (let* ((beg (nth 8 parse-status))
10110 (first-line (js2-same-line beg))
10111 (offset (save-excursion
10112 (goto-char beg)
10113 (if (looking-at "/\\*")
10114 (+ 1 (current-column))
10115 0))))
10116 (unless first-line
10117 (indent-line-to offset))))
10118
10119 (defun js2-backward-sws ()
10120 "Move backward through whitespace and comments."
10121 (interactive)
10122 (while (forward-comment -1)))
10123
10124 (defun js2-forward-sws ()
10125 "Move forward through whitespace and comments."
10126 (interactive)
10127 (while (forward-comment 1)))
10128
10129 (defsubst js2-current-indent (&optional pos)
10130 "Return column of indentation on current line.
10131 If POS is non-nil, go to that point and return indentation for that line."
10132 (save-excursion
10133 (if pos
10134 (goto-char pos))
10135 (back-to-indentation)
10136 (current-column)))
10137
10138 (defsubst js2-arglist-close ()
10139 "Return non-nil if we're on a line beginning with a close-paren/brace."
10140 (save-match-data
10141 (save-excursion
10142 (goto-char (point-at-bol))
10143 (js2-forward-sws)
10144 (looking-at "[])}]"))))
10145
10146 (defsubst js2-indent-looks-like-label-p ()
10147 (goto-char (point-at-bol))
10148 (js2-forward-sws)
10149 (looking-at (concat js2-mode-identifier-re ":")))
10150
10151 (defun js2-indent-in-objlit-p (parse-status)
10152 "Return non-nil if this looks like an object-literal entry."
10153 (let ((start (nth 1 parse-status)))
10154 (and
10155 start
10156 (save-excursion
10157 (and (zerop (forward-line -1))
10158 (not (< (point) start)) ; crossed a {} boundary
10159 (js2-indent-looks-like-label-p)))
10160 (save-excursion
10161 (js2-indent-looks-like-label-p)))))
10162
10163 ;; if prev line looks like foobar({ then we're passing an object
10164 ;; literal to a function call, and people pretty much always want to
10165 ;; de-dent back to the previous line, so move the 'basic-offset'
10166 ;; position to the front.
10167 (defsubst js2-indent-objlit-arg-p (parse-status)
10168 (save-excursion
10169 (back-to-indentation)
10170 (js2-backward-sws)
10171 (and (eq (1- (point)) (nth 1 parse-status))
10172 (eq (char-before) ?{)
10173 (progn
10174 (forward-char -1)
10175 (skip-chars-backward " \t")
10176 (eq (char-before) ?\()))))
10177
10178 (defsubst js2-indent-case-block-p ()
10179 (save-excursion
10180 (back-to-indentation)
10181 (js2-backward-sws)
10182 (goto-char (point-at-bol))
10183 (skip-chars-forward " \t")
10184 (save-match-data
10185 (looking-at "case\\s-.+:"))))
10186
10187 (defsubst js2-syntax-bol ()
10188 "Return the point at the first non-whitespace char on the line.
10189 Returns `point-at-bol' if the line is empty."
10190 (save-excursion
10191 (beginning-of-line)
10192 (skip-chars-forward " \t")
10193 (point)))
10194
10195 (defun js2-bounce-indent (normal-col parse-status backwards)
10196 "Cycle among alternate computed indentation positions.
10197 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10198 of the buffer to the current point. NORMAL-COL is the indentation
10199 column computed by the heuristic guesser based on current paren,
10200 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10201 in reverse."
10202 (let ((cur-indent (js2-current-indent))
10203 (old-buffer-undo-list buffer-undo-list)
10204 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10205 (current-line (save-excursion
10206 (forward-line 0) ; move to bol
10207 (1+ (count-lines (point-min) (point)))))
10208 positions
10209 pos
10210 main-pos
10211 anchor
10212 arglist-cont
10213 same-indent
10214 prev-line-col
10215 basic-offset
10216 computed-pos)
10217 ;; temporarily don't record undo info, if user requested this
10218 (if js2-mode-indent-inhibit-undo
10219 (setq buffer-undo-list t))
10220 (unwind-protect
10221 (progn
10222 ;; first likely point: indent from beginning of previous code line
10223 (push (setq basic-offset
10224 (+ (save-excursion
10225 (back-to-indentation)
10226 (js2-backward-sws)
10227 (back-to-indentation)
10228 (setq prev-line-col (current-column)))
10229 js2-basic-offset))
10230 positions)
10231
10232 ;; (first + epsilon) likely point: indent 2x from beginning of
10233 ;; previous code line. Some companies like this approach. Ahem.
10234 ;; Seriously, though -- 4-space indent for expression continuation
10235 ;; lines isn't a bad idea. We should eventually implement it
10236 ;; that way.
10237 (push (setq basic-offset
10238 (+ (save-excursion
10239 (back-to-indentation)
10240 (js2-backward-sws)
10241 (back-to-indentation)
10242 (setq prev-line-col (current-column)))
10243 (* 2 js2-basic-offset)))
10244 positions)
10245
10246 ;; second likely point: indent from assign-expr RHS. This
10247 ;; is just a crude guess based on finding " = " on the previous
10248 ;; line containing actual code.
10249 (setq pos (save-excursion
10250 (save-match-data
10251 (forward-line -1)
10252 (goto-char (point-at-bol))
10253 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10254 (point-at-eol) t)
10255 (goto-char (match-end 1))
10256 (skip-chars-forward " \t\r\n")
10257 (current-column)))))
10258 (when pos
10259 (incf pos js2-basic-offset)
10260 (push pos positions))
10261
10262 ;; third likely point: same indent as previous line of code.
10263 ;; Make it the first likely point if we're not on an
10264 ;; arglist-close line and previous line ends in a comma, or
10265 ;; both this line and prev line look like object-literal
10266 ;; elements.
10267 (setq pos (save-excursion
10268 (goto-char (point-at-bol))
10269 (js2-backward-sws)
10270 (back-to-indentation)
10271 (prog1
10272 (current-column)
10273 ;; while we're here, look for trailing comma
10274 (if (save-excursion
10275 (goto-char (point-at-eol))
10276 (js2-backward-sws)
10277 (eq (char-before) ?,))
10278 (setq arglist-cont (1- (point)))))))
10279 (when pos
10280 (if (and (or arglist-cont
10281 (js2-indent-in-objlit-p parse-status))
10282 (not (js2-arglist-close)))
10283 (setq same-indent pos))
10284 (push pos positions))
10285
10286 ;; fourth likely point: first preceding code with less indentation
10287 ;; than the immediately preceding code line.
10288 (setq pos (save-excursion
10289 (back-to-indentation)
10290 (js2-backward-sws)
10291 (back-to-indentation)
10292 (setq anchor (current-column))
10293 (while (and (zerop (forward-line -1))
10294 (>= (progn
10295 (back-to-indentation)
10296 (current-column))
10297 anchor)))
10298 (setq pos (current-column))))
10299 (push pos positions)
10300
10301 ;; nesting-heuristic position, main by default
10302 (push (setq main-pos normal-col) positions)
10303
10304 ;; delete duplicates and sort positions list
10305 (setq positions (sort (delete-dups positions) '<))
10306
10307 ;; comma-list continuation lines: prev line indent takes precedence
10308 (if same-indent
10309 (setq main-pos same-indent))
10310
10311 ;; common special cases where we want to indent in from previous line
10312 (if (or (js2-indent-case-block-p)
10313 (js2-indent-objlit-arg-p parse-status))
10314 (setq main-pos basic-offset))
10315
10316 ;; if bouncing backwards, reverse positions list
10317 (if backwards
10318 (setq positions (reverse positions)))
10319
10320 ;; record whether we're already sitting on one of the alternatives
10321 (setq pos (member cur-indent positions))
10322
10323 (cond
10324 ;; case 0: we're one one of the alternatives and this is the
10325 ;; first time they've pressed TAB on this line (best-guess).
10326 ((and js2-mode-indent-ignore-first-tab
10327 pos
10328 ;; first time pressing TAB on this line?
10329 (not (eq js2-mode-last-indented-line current-line)))
10330 ;; do nothing
10331 (setq computed-pos nil))
10332 ;; case 1: only one computed position => use it
10333 ((null (cdr positions))
10334 (setq computed-pos 0))
10335 ;; case 2: not on any of the computed spots => use main spot
10336 ((not pos)
10337 (setq computed-pos (js2-position main-pos positions)))
10338 ;; case 3: on last position: cycle to first position
10339 ((null (cdr pos))
10340 (setq computed-pos 0))
10341 ;; case 4: on intermediate position: cycle to next position
10342 (t
10343 (setq computed-pos (js2-position (second pos) positions))))
10344
10345 ;; see if any hooks want to indent; otherwise we do it
10346 (loop with result = nil
10347 for hook in js2-indent-hook
10348 while (null result)
10349 do
10350 (setq result (funcall hook positions computed-pos))
10351 finally do
10352 (unless (or result (null computed-pos))
10353 (indent-line-to (nth computed-pos positions)))))
10354
10355 ;; finally
10356 (if js2-mode-indent-inhibit-undo
10357 (setq buffer-undo-list old-buffer-undo-list))
10358 ;; see commentary for `js2-mode-last-indented-line'
10359 (setq js2-mode-last-indented-line current-line))))
10360
10361 (defun js2-indent-bounce-backwards ()
10362 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10363 cycles between the computed indentation positions in reverse order."
10364 (interactive)
10365 (js2-indent-line t))
10366
10367 (defsubst js2-1-line-comment-continuation-p ()
10368 "Return t if we're in a 1-line comment continuation.
10369 If so, we don't ever want to use bounce-indent."
10370 (save-excursion
10371 (save-match-data
10372 (and (progn
10373 (forward-line 0)
10374 (looking-at "\\s-*//"))
10375 (progn
10376 (forward-line -1)
10377 (forward-line 0)
10378 (when (looking-at "\\s-*$")
10379 (js2-backward-sws)
10380 (forward-line 0))
10381 (looking-at "\\s-*//"))))))
10382
10383 (defun js2-indent-line (&optional bounce-backwards)
10384 "Indent the current line as JavaScript source text."
10385 (interactive)
10386 (let (parse-status
10387 offset
10388 indent-col
10389 moved
10390 ;; don't whine about errors/warnings when we're indenting.
10391 ;; This has to be set before calling parse-partial-sexp below.
10392 (inhibit-point-motion-hooks t))
10393 (setq parse-status (save-excursion
10394 (syntax-ppss (point-at-bol)))
10395 offset (- (point) (save-excursion
10396 (back-to-indentation)
10397 (point))))
10398 (js2-with-underscore-as-word-syntax
10399 (if (nth 4 parse-status)
10400 (js2-lineup-comment parse-status)
10401 (setq indent-col (js2-proper-indentation parse-status))
10402 ;; see comments below about js2-mode-last-indented-line
10403 (cond
10404 ;; bounce-indenting is disabled during electric-key indent.
10405 ;; It doesn't work well on first line of buffer.
10406 ((and js2-bounce-indent-p
10407 (not (js2-same-line (point-min)))
10408 (not (js2-1-line-comment-continuation-p)))
10409 (js2-bounce-indent indent-col parse-status bounce-backwards))
10410 ;; just indent to the guesser's likely spot
10411 (t (indent-line-to indent-col)))
10412 (when (plusp offset)
10413 (forward-char offset))))))
10414
10415 (defun js2-indent-region (start end)
10416 "Indent the region, but don't use bounce indenting."
10417 (let ((js2-bounce-indent-p nil)
10418 (indent-region-function nil)
10419 (after-change-functions (remq 'js2-mode-edit
10420 after-change-functions)))
10421 (indent-region start end nil) ; nil for byte-compiler
10422 (js2-mode-edit start end (- end start))))
10423
10424 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10425
10426 ;;;###autoload
10427 (defun js2-mode ()
10428 "Major mode for editing JavaScript code."
10429 (interactive)
10430 (kill-all-local-variables)
10431 (set-syntax-table js2-mode-syntax-table)
10432 (use-local-map js2-mode-map)
10433 (make-local-variable 'comment-start)
10434 (make-local-variable 'comment-end)
10435 (make-local-variable 'comment-start-skip)
10436 (setq major-mode 'js2-mode
10437 mode-name "JavaScript-IDE"
10438 comment-start "//" ; used by comment-region; don't change it
10439 comment-end "")
10440 (setq local-abbrev-table js2-mode-abbrev-table)
10441 (set (make-local-variable 'max-lisp-eval-depth)
10442 (max max-lisp-eval-depth 3000))
10443 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10444 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10445
10446 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10447 ;; on most platforms other than the one I originally wrote it on.
10448 ;; So it's back to `c-fill-paragraph'.
10449 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10450
10451 (add-hook 'before-save-hook #'js2-before-save nil t)
10452 (set (make-local-variable 'next-error-function) #'js2-next-error)
10453 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10454 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10455 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10456 ;; for characters inside regexp literals.
10457 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10458 ;; this is necessary to make `show-paren-function' work properly
10459 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10460 ;; needed for M-x rgrep, among other things
10461 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10462
10463 ;; some variables needed by cc-engine for paragraph-fill, etc.
10464 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10465 c-comment-start-regexp "/[*/]\\|\\s|"
10466 c-line-comment-starter "//"
10467 c-paragraph-start js2-paragraph-start
10468 c-paragraph-separate "$"
10469 comment-start-skip js2-comment-start-skip
10470 c-syntactic-ws-start js2-syntactic-ws-start
10471 c-syntactic-ws-end js2-syntactic-ws-end
10472 c-syntactic-eol js2-syntactic-eol)
10473
10474 (let ((c-buffer-is-cc-mode t))
10475 ;; Copied from `js-mode'. Also see Bug#6071.
10476 (make-local-variable 'paragraph-start)
10477 (make-local-variable 'paragraph-separate)
10478 (make-local-variable 'paragraph-ignore-fill-prefix)
10479 (make-local-variable 'adaptive-fill-mode)
10480 (make-local-variable 'adaptive-fill-regexp)
10481 (c-setup-paragraph-variables))
10482
10483 (setq js2-default-externs
10484 (append js2-ecma-262-externs
10485 (if js2-include-browser-externs
10486 js2-browser-externs)
10487 (if js2-include-gears-externs
10488 js2-gears-externs)
10489 (if js2-include-rhino-externs
10490 js2-rhino-externs)))
10491
10492 ;; We do our own syntax highlighting based on the parse tree.
10493 ;; However, we want minor modes that add keywords to highlight properly
10494 ;; (examples: doxymacs, column-marker).
10495 ;; To customize highlighted keywords, use `font-lock-add-keywords'.
10496 (setq font-lock-defaults '(nil t))
10497
10498 ;; Experiment: make reparse-delay longer for longer files.
10499 (if (plusp js2-dynamic-idle-timer-adjust)
10500 (setq js2-idle-timer-delay
10501 (* js2-idle-timer-delay
10502 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10503
10504 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10505 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10506 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10507 (imenu-add-to-menubar (concat "IM-" mode-name))
10508 (when js2-mirror-mode
10509 (js2-enter-mirror-mode))
10510 (add-to-invisibility-spec '(js2-outline . t))
10511 (set (make-local-variable 'line-move-ignore-invisible) t)
10512 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10513
10514 (if (fboundp 'run-mode-hooks)
10515 (run-mode-hooks 'js2-mode-hook)
10516 (run-hooks 'js2-mode-hook))
10517
10518 (setq js2-mode-functions-hidden nil
10519 js2-mode-comments-hidden nil
10520 js2-mode-buffer-dirty-p t
10521 js2-mode-parsing nil)
10522 (js2-reparse))
10523
10524 (defun js2-mode-exit ()
10525 "Exit `js2-mode' and clean up."
10526 (interactive)
10527 (when js2-mode-node-overlay
10528 (delete-overlay js2-mode-node-overlay)
10529 (setq js2-mode-node-overlay nil))
10530 (js2-remove-overlays)
10531 (setq js2-mode-ast nil)
10532 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10533 (remove-from-invisibility-spec '(js2-outline . t))
10534 (js2-mode-show-all)
10535 (js2-with-unmodifying-text-property-changes
10536 (js2-clear-face (point-min) (point-max))))
10537
10538 (defun js2-before-save ()
10539 "Clean up whitespace before saving file.
10540 You can disable this by customizing `js2-cleanup-whitespace'."
10541 (when js2-cleanup-whitespace
10542 (let ((col (current-column)))
10543 (delete-trailing-whitespace)
10544 ;; don't change trailing whitespace on current line
10545 (unless (eq (current-column) col)
10546 (indent-to col)))))
10547
10548 (defsubst js2-mode-reset-timer ()
10549 "Cancel any existing parse timer and schedule a new one."
10550 (if js2-mode-parse-timer
10551 (cancel-timer js2-mode-parse-timer))
10552 (setq js2-mode-parsing nil)
10553 (setq js2-mode-parse-timer
10554 (run-with-idle-timer js2-idle-timer-delay nil
10555 #'js2-mode-idle-reparse (current-buffer))))
10556
10557 (defun js2-mode-idle-reparse (buffer)
10558 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10559 it to be reparsed when the buffer is selected."
10560 (if (eq buffer (current-buffer))
10561 (js2-reparse)
10562 ;; reparse when the buffer is selected again
10563 (with-current-buffer buffer
10564 (add-hook 'window-configuration-change-hook
10565 #'js2-mode-idle-reparse-inner
10566 nil t))))
10567
10568 (defun js2-mode-idle-reparse-inner ()
10569 (remove-hook 'window-configuration-change-hook
10570 #'js2-mode-idle-reparse-inner
10571 t)
10572 (js2-reparse))
10573
10574 (defun js2-mode-edit (beg end len)
10575 "Schedule a new parse after buffer is edited.
10576 Buffer edit spans from BEG to END and is of length LEN.
10577 Also clears the `js2-magic' bit on autoinserted parens/brackets
10578 if the edit occurred on a line different from the magic paren."
10579 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10580 (line (if magic-pos (line-number-at-pos magic-pos))))
10581 (and line
10582 (or (/= (line-number-at-pos beg) line)
10583 (and (> 0 len)
10584 (/= (line-number-at-pos end) line)))
10585 (js2-mode-mundanify-parens)))
10586 (setq js2-mode-buffer-dirty-p t)
10587 (js2-mode-hide-overlay)
10588 (js2-mode-reset-timer))
10589
10590 (defun js2-reparse (&optional force)
10591 "Re-parse current buffer after user finishes some data entry.
10592 If we get any user input while parsing, including cursor motion,
10593 we discard the parse and reschedule it. If FORCE is nil, then the
10594 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10595 (let (time
10596 interrupted-p
10597 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10598 (unless js2-mode-parsing
10599 (setq js2-mode-parsing t)
10600 (unwind-protect
10601 (when (or js2-mode-buffer-dirty-p force)
10602 (js2-remove-overlays)
10603 (js2-with-unmodifying-text-property-changes
10604 (setq js2-mode-buffer-dirty-p nil
10605 js2-mode-fontifications nil
10606 js2-mode-deferred-properties nil)
10607 (if js2-mode-verbose-parse-p
10608 (message "parsing..."))
10609 (setq time
10610 (js2-time
10611 (setq interrupted-p
10612 (catch 'interrupted
10613 (setq js2-mode-ast (js2-parse))
10614 ;; if parsing is interrupted, comments and regex
10615 ;; literals stay ignored by `parse-partial-sexp'
10616 (remove-text-properties (point-min) (point-max)
10617 '(syntax-table))
10618 (js2-mode-apply-deferred-properties)
10619 (js2-mode-remove-suppressed-warnings)
10620 (js2-mode-show-warnings)
10621 (js2-mode-show-errors)
10622 (js2-mode-highlight-magic-parens)
10623 (if (>= js2-highlight-level 1)
10624 (js2-highlight-jsdoc js2-mode-ast))
10625 nil))))
10626 (if interrupted-p
10627 (progn
10628 ;; unfinished parse => try again
10629 (setq js2-mode-buffer-dirty-p t)
10630 (js2-mode-reset-timer))
10631 (if js2-mode-verbose-parse-p
10632 (message "Parse time: %s" time)))))
10633 (setq js2-mode-parsing nil)
10634 (unless interrupted-p
10635 (setq js2-mode-parse-timer nil))))))
10636
10637 (defun js2-mode-show-node ()
10638 "Debugging aid: highlight selected AST node on mouse click."
10639 (interactive)
10640 (let ((node (js2-node-at-point))
10641 beg
10642 end)
10643 (when js2-mode-show-overlay
10644 (if (null node)
10645 (message "No node found at location %s" (point))
10646 (setq beg (js2-node-abs-pos node)
10647 end (+ beg (js2-node-len node)))
10648 (if js2-mode-node-overlay
10649 (move-overlay js2-mode-node-overlay beg end)
10650 (setq js2-mode-node-overlay (make-overlay beg end))
10651 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10652 (js2-with-unmodifying-text-property-changes
10653 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10654 (message "%s, parent: %s"
10655 (js2-node-short-name node)
10656 (if (js2-node-parent node)
10657 (js2-node-short-name (js2-node-parent node))
10658 "nil"))))))
10659
10660 (defun js2-mode-hide-overlay (&optional p1 p2)
10661 "Remove the debugging overlay when the point moves.
10662 P1 and P2 are the old and new values of point, respectively."
10663 (when js2-mode-node-overlay
10664 (let ((beg (overlay-start js2-mode-node-overlay))
10665 (end (overlay-end js2-mode-node-overlay)))
10666 ;; Sometimes we're called spuriously.
10667 (unless (and p2
10668 (>= p2 beg)
10669 (<= p2 end))
10670 (js2-with-unmodifying-text-property-changes
10671 (remove-text-properties beg end '(point-left nil)))
10672 (delete-overlay js2-mode-node-overlay)
10673 (setq js2-mode-node-overlay nil)))))
10674
10675 (defun js2-mode-reset ()
10676 "Debugging helper: reset everything."
10677 (interactive)
10678 (js2-mode-exit)
10679 (js2-mode))
10680
10681 (defsubst js2-mode-show-warn-or-err (e face)
10682 "Highlight a warning or error E with FACE.
10683 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10684 (let* ((key (first e))
10685 (beg (second e))
10686 (end (+ beg (third e)))
10687 ;; Don't inadvertently go out of bounds.
10688 (beg (max (point-min) (min beg (point-max))))
10689 (end (max (point-min) (min end (point-max))))
10690 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10691 (ovl (make-overlay beg end)))
10692 (overlay-put ovl 'font-lock-face face)
10693 (overlay-put ovl 'js2-error t)
10694 (put-text-property beg end 'help-echo (js2-get-msg key))
10695 (put-text-property beg end 'point-entered #'js2-echo-error)))
10696
10697 (defun js2-remove-overlays ()
10698 "Remove overlays from buffer that have a `js2-error' property."
10699 (let ((beg (point-min))
10700 (end (point-max)))
10701 (save-excursion
10702 (dolist (o (overlays-in beg end))
10703 (when (overlay-get o 'js2-error)
10704 (delete-overlay o))))))
10705
10706 (defun js2-error-at-point (&optional pos)
10707 "Return non-nil if there's an error overlay at POS.
10708 Defaults to point."
10709 (loop with pos = (or pos (point))
10710 for o in (overlays-at pos)
10711 thereis (overlay-get o 'js2-error)))
10712
10713 (defun js2-mode-apply-deferred-properties ()
10714 "Apply fontifications and other text properties recorded during parsing."
10715 (when (plusp js2-highlight-level)
10716 ;; We defer clearing faces as long as possible to eliminate flashing.
10717 (js2-clear-face (point-min) (point-max))
10718 ;; Have to reverse the recorded fontifications list so that errors
10719 ;; and warnings overwrite the normal fontifications.
10720 (dolist (f (nreverse js2-mode-fontifications))
10721 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10722 (setq js2-mode-fontifications nil))
10723 (dolist (p js2-mode-deferred-properties)
10724 (apply #'put-text-property p))
10725 (setq js2-mode-deferred-properties nil))
10726
10727 (defun js2-mode-show-errors ()
10728 "Highlight syntax errors."
10729 (when js2-mode-show-parse-errors
10730 (dolist (e (js2-ast-root-errors js2-mode-ast))
10731 (js2-mode-show-warn-or-err e 'js2-error-face))))
10732
10733 (defun js2-mode-remove-suppressed-warnings ()
10734 "Take suppressed warnings out of the AST warnings list.
10735 This ensures that the counts and `next-error' are correct."
10736 (setf (js2-ast-root-warnings js2-mode-ast)
10737 (js2-delete-if
10738 (lambda (e)
10739 (let ((key (caar e)))
10740 (or
10741 (and (not js2-strict-trailing-comma-warning)
10742 (string-match "trailing\\.comma" key))
10743 (and (not js2-strict-cond-assign-warning)
10744 (string= key "msg.equal.as.assign"))
10745 (and js2-missing-semi-one-line-override
10746 (string= key "msg.missing.semi")
10747 (let* ((beg (second e))
10748 (node (js2-node-at-point beg))
10749 (fn (js2-mode-find-parent-fn node))
10750 (body (and fn (js2-function-node-body fn)))
10751 (lc (and body (js2-node-abs-pos body)))
10752 (rc (and lc (+ lc (js2-node-len body)))))
10753 (and fn
10754 (or (null body)
10755 (save-excursion
10756 (goto-char beg)
10757 (and (js2-same-line lc)
10758 (js2-same-line rc))))))))))
10759 (js2-ast-root-warnings js2-mode-ast))))
10760
10761 (defun js2-mode-show-warnings ()
10762 "Highlight strict-mode warnings."
10763 (when js2-mode-show-strict-warnings
10764 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10765 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10766
10767 (defun js2-echo-error (old-point new-point)
10768 "Called by point-motion hooks."
10769 (let ((msg (get-text-property new-point 'help-echo)))
10770 (if (and msg (or (not (current-message))
10771 (string= (current-message) "Quit")))
10772 (message msg))))
10773
10774 (defalias #'js2-echo-help #'js2-echo-error)
10775
10776 (defun js2-enter-key ()
10777 "Handle user pressing the Enter key."
10778 (interactive)
10779 (let ((parse-status (save-excursion
10780 (syntax-ppss (point))))
10781 (js2-bounce-indent-p nil))
10782 (cond
10783 ;; check if we're inside a string
10784 ((nth 3 parse-status)
10785 (if js2-concat-multiline-strings
10786 (js2-mode-split-string parse-status)
10787 (insert "\n")))
10788 ;; check if inside a block comment
10789 ((nth 4 parse-status)
10790 (js2-mode-extend-comment))
10791 (t
10792 ;; should probably figure out what the mode-map says we should do
10793 (if js2-indent-on-enter-key
10794 (js2-indent-line))
10795 (insert "\n")
10796 (if js2-enter-indents-newline
10797 (js2-indent-line))))))
10798
10799 (defun js2-mode-split-string (parse-status)
10800 "Turn a newline in mid-string into a string concatenation.
10801 PARSE-STATUS is as documented in `parse-partial-sexp'."
10802 (let* ((col (current-column))
10803 (quote-char (nth 3 parse-status))
10804 (quote-string (string quote-char))
10805 (string-beg (nth 8 parse-status))
10806 (at-eol (eq js2-concat-multiline-strings 'eol))
10807 (indent (save-match-data
10808 (or
10809 (save-excursion
10810 (back-to-indentation)
10811 (if (looking-at "\\+")
10812 (current-column)))
10813 (save-excursion
10814 (goto-char string-beg)
10815 (if (looking-back "\\+\\s-+")
10816 (goto-char (match-beginning 0)))
10817 (current-column))))))
10818 (insert quote-char)
10819 (if at-eol
10820 (insert " +\n")
10821 (insert "\n"))
10822 ;; FIXME: This does not match the behavior of `js2-indent-line'.
10823 (indent-to indent)
10824 (unless at-eol
10825 (insert "+ "))
10826 (insert quote-string)
10827 (when (eolp)
10828 (insert quote-string)
10829 (backward-char 1))))
10830
10831 (defun js2-mode-extend-comment ()
10832 "Indent the line and, when inside a comment block, add comment prefix."
10833 (let (star single col first-line needs-close)
10834 (save-excursion
10835 (back-to-indentation)
10836 (cond
10837 ((looking-at "\\*[^/]")
10838 (setq star t
10839 col (current-column)))
10840 ((looking-at "/\\*")
10841 (setq star t
10842 first-line t
10843 col (1+ (current-column))))
10844 ((looking-at "//")
10845 (setq single t
10846 col (current-column)))))
10847 ;; Heuristic for whether we need to close the comment:
10848 ;; if we've got a parse error here, assume it's an unterminated
10849 ;; comment.
10850 (setq needs-close
10851 (or
10852 (eq (get-text-property (1- (point)) 'point-entered)
10853 'js2-echo-error)
10854 ;; The heuristic above doesn't work well when we're
10855 ;; creating a comment and there's another one downstream,
10856 ;; as our parser thinks this one ends at the end of the
10857 ;; next one. (You can have a /* inside a js block comment.)
10858 ;; So just close it if the next non-ws char isn't a *.
10859 (and first-line
10860 (eolp)
10861 (save-excursion
10862 (skip-chars-forward " \t\r\n")
10863 (not (eq (char-after) ?*))))))
10864 (insert "\n")
10865 (cond
10866 (star
10867 (indent-to col)
10868 (insert "* ")
10869 (if (and first-line needs-close)
10870 (save-excursion
10871 (insert "\n")
10872 (indent-to col)
10873 (insert "*/"))))
10874 ((and single
10875 (save-excursion
10876 (and (zerop (forward-line 1))
10877 (looking-at "\\s-*//"))))
10878 (indent-to col)
10879 (insert "// "))
10880 ;; don't need to extend the comment after all
10881 (js2-enter-indents-newline
10882 (js2-indent-line)))))
10883
10884 (defun js2-beginning-of-line ()
10885 "Toggles point between bol and first non-whitespace char in line.
10886 Also moves past comment delimiters when inside comments."
10887 (interactive)
10888 (let (node beg)
10889 (cond
10890 ((bolp)
10891 (back-to-indentation))
10892 ((looking-at "//")
10893 (skip-chars-forward "/ \t"))
10894 ((and (eq (char-after) ?*)
10895 (setq node (js2-comment-at-point))
10896 (memq (js2-comment-node-format node) '(jsdoc block))
10897 (save-excursion
10898 (skip-chars-backward " \t")
10899 (bolp)))
10900 (skip-chars-forward "\* \t"))
10901 (t
10902 (goto-char (point-at-bol))))))
10903
10904 (defun js2-end-of-line ()
10905 "Toggles point between eol and last non-whitespace char in line."
10906 (interactive)
10907 (if (eolp)
10908 (skip-chars-backward " \t")
10909 (goto-char (point-at-eol))))
10910
10911 (defun js2-enter-mirror-mode()
10912 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10913 on insertion."
10914 (interactive)
10915 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10916 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10917 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10918 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10919 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10920 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10921 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10922 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10923
10924 (defun js2-leave-mirror-mode()
10925 "Turns off mirror mode."
10926 (interactive)
10927 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10928 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10929
10930 (defsubst js2-mode-inside-string ()
10931 "Return non-nil if inside a string.
10932 Actually returns the quote character that begins the string."
10933 (let ((parse-state (save-excursion
10934 (syntax-ppss (point)))))
10935 (nth 3 parse-state)))
10936
10937 (defsubst js2-mode-inside-comment-or-string ()
10938 "Return non-nil if inside a comment or string."
10939 (or
10940 (let ((comment-start
10941 (save-excursion
10942 (goto-char (point-at-bol))
10943 (if (re-search-forward "//" (point-at-eol) t)
10944 (match-beginning 0)))))
10945 (and comment-start
10946 (<= comment-start (point))))
10947 (let ((parse-state (save-excursion
10948 (syntax-ppss (point)))))
10949 (or (nth 3 parse-state)
10950 (nth 4 parse-state)))))
10951
10952 (defsubst js2-make-magic-delimiter (delim &optional pos)
10953 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10954 Sets value of `js2-magic' text property to line number at POS."
10955 (propertize delim
10956 'js2-magic (line-number-at-pos pos)
10957 'font-lock-face 'js2-magic-paren-face))
10958
10959 (defun js2-mode-match-delimiter (open close)
10960 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10961 The rule we use, which as far as we can tell is how Eclipse works,
10962 is that we insert the match if we're not in a comment or string,
10963 and the next non-whitespace character is either punctuation or
10964 occurs on another line."
10965 (insert open)
10966 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10967 (not (js2-mode-inside-comment-or-string)))
10968 (save-excursion
10969 (insert (js2-make-magic-delimiter close)))
10970 (when js2-auto-indent-p
10971 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10972 (js2-indent-line)))))
10973
10974 (defun js2-mode-match-bracket ()
10975 "Insert matching bracket."
10976 (interactive)
10977 (js2-mode-match-delimiter "[" "]"))
10978
10979 (defun js2-mode-match-paren ()
10980 "Insert matching paren unless already inserted."
10981 (interactive)
10982 (js2-mode-match-delimiter "(" ")"))
10983
10984 (defun js2-mode-match-curly (arg)
10985 "Insert matching curly-brace.
10986 With prefix arg, no formatting or indentation will occur -- the close-brace
10987 is simply inserted directly at the point."
10988 (interactive "p")
10989 (let (try-pos)
10990 (cond
10991 (current-prefix-arg
10992 (js2-mode-match-delimiter "{" "}"))
10993 ((and js2-auto-insert-catch-block
10994 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10995 (point-at-bol))
10996 (match-beginning 1))))
10997 (js2-insert-catch-skel try-pos))
10998 (t
10999 ;; Otherwise try to do something smarter.
11000 (insert "{")
11001 (unless (or (not (looking-at "\\s-*$"))
11002 (save-excursion
11003 (skip-chars-forward " \t\r\n")
11004 (and (looking-at "}")
11005 (js2-error-at-point)))
11006 (js2-mode-inside-comment-or-string))
11007 (undo-boundary)
11008 ;; absolutely mystifying bug: when inserting the next "\n",
11009 ;; the buffer-undo-list is given two new entries: the inserted range,
11010 ;; and the incorrect position of the point. It's recorded incorrectly
11011 ;; as being before the opening "{", not after it. But it's recorded
11012 ;; as the correct value if you're debugging `js2-mode-match-curly'
11013 ;; in edebug. I have no idea why it's doing this, but incrementing
11014 ;; the inserted position fixes the problem, so that the undo takes us
11015 ;; back to just after the user-inserted "{".
11016 (insert "\n")
11017 (ignore-errors
11018 (incf (cadr buffer-undo-list)))
11019 (js2-indent-line)
11020 (save-excursion
11021 (insert "\n}")
11022 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
11023 (js2-indent-line))))))))
11024
11025 (defun js2-insert-catch-skel (try-pos)
11026 "Complete a try/catch block after inserting a { following a try keyword.
11027 Rationale is that a try always needs a catch or a finally, and the catch is
11028 the more likely of the two.
11029
11030 TRY-POS is the buffer position of the try keyword. The open-curly should
11031 already have been inserted."
11032 (insert "{")
11033 (let ((try-col (save-excursion
11034 (goto-char try-pos)
11035 (current-column))))
11036 (insert "\n")
11037 (undo-boundary)
11038 (js2-indent-line) ;; indent the blank line where cursor will end up
11039 (save-excursion
11040 (insert "\n")
11041 (indent-to try-col)
11042 (insert "} catch (x) {\n\n")
11043 (indent-to try-col)
11044 (insert "}"))))
11045
11046 (defun js2-mode-highlight-magic-parens ()
11047 "Re-highlight magic parens after parsing nukes the 'face prop."
11048 (let ((beg (point-min))
11049 end)
11050 (while (setq beg (next-single-property-change beg 'js2-magic))
11051 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11052 (if (get-text-property beg 'js2-magic)
11053 (js2-with-unmodifying-text-property-changes
11054 (put-text-property beg (or end (1+ beg))
11055 'font-lock-face 'js2-magic-paren-face))))))
11056
11057 (defun js2-mode-mundanify-parens ()
11058 "Clear all magic parens and brackets."
11059 (let ((beg (point-min))
11060 end)
11061 (while (setq beg (next-single-property-change beg 'js2-magic))
11062 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11063 (remove-text-properties beg (or end (1+ beg))
11064 '(js2-magic face)))))
11065
11066 (defsubst js2-match-quote (quote-string)
11067 (let ((start-quote (js2-mode-inside-string)))
11068 (cond
11069 ;; inside a comment - don't do quote-matching, since we can't
11070 ;; reliably figure out if we're in a string inside the comment
11071 ((js2-comment-at-point)
11072 (insert quote-string))
11073 ((not start-quote)
11074 ;; not in string => insert matched quotes
11075 (insert quote-string)
11076 ;; exception: if we're just before a word, don't double it.
11077 (unless (looking-at "[^ \t\r\n]")
11078 (save-excursion
11079 (insert quote-string))))
11080 ((looking-at quote-string)
11081 (if (looking-back "[^\\]\\\\")
11082 (insert quote-string)
11083 (forward-char 1)))
11084 ((and js2-mode-escape-quotes
11085 (save-excursion
11086 (save-match-data
11087 (re-search-forward quote-string (point-at-eol) t))))
11088 ;; inside terminated string, escape quote (unless already escaped)
11089 (insert (if (looking-back "[^\\]\\\\")
11090 quote-string
11091 (concat "\\" quote-string))))
11092 (t
11093 (insert quote-string))))) ; else terminate the string
11094
11095 (defun js2-mode-match-single-quote ()
11096 "Insert matching single-quote."
11097 (interactive)
11098 (let ((parse-status (syntax-ppss (point))))
11099 ;; don't match inside comments, since apostrophe is more common
11100 (if (nth 4 parse-status)
11101 (insert "'")
11102 (js2-match-quote "'"))))
11103
11104 (defun js2-mode-match-double-quote ()
11105 "Insert matching double-quote."
11106 (interactive)
11107 (js2-match-quote "\""))
11108
11109 ;; Eclipse works as follows:
11110 ;; * type an open-paren and it auto-inserts close-paren
11111 ;; - auto-inserted paren gets a green bracket
11112 ;; - green bracket means typing close-paren there will skip it
11113 ;; * if you insert any text on a different line, it turns off
11114 (defun js2-mode-magic-close-paren ()
11115 "Skip over close-paren rather than inserting, where appropriate."
11116 (interactive)
11117 (let* ((here (point))
11118 (parse-status (syntax-ppss here))
11119 (open-pos (nth 1 parse-status))
11120 (close last-input-event)
11121 (open (cond
11122 ((eq close ?\))
11123 ?\()
11124 ((eq close ?\])
11125 ?\[)
11126 ((eq close ?})
11127 ?{)
11128 (t nil))))
11129 (if (and (eq (char-after) close)
11130 (eq open (char-after open-pos))
11131 (js2-same-line open-pos)
11132 (get-text-property here 'js2-magic))
11133 (progn
11134 (remove-text-properties here (1+ here) '(js2-magic face))
11135 (forward-char 1))
11136 (insert-char close 1))
11137 (blink-matching-open)))
11138
11139 (defun js2-mode-wait-for-parse (callback)
11140 "Invoke CALLBACK when parsing is finished.
11141 If parsing is already finished, calls CALLBACK immediately."
11142 (if (not js2-mode-buffer-dirty-p)
11143 (funcall callback)
11144 (push callback js2-mode-pending-parse-callbacks)
11145 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11146
11147 (defun js2-mode-parse-finished ()
11148 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11149 ;; We can't let errors propagate up, since it prevents the
11150 ;; `js2-parse' method from completing normally and returning
11151 ;; the ast, which makes things mysteriously not work right.
11152 (unwind-protect
11153 (dolist (cb js2-mode-pending-parse-callbacks)
11154 (condition-case err
11155 (funcall cb)
11156 (error (message "%s" err))))
11157 (setq js2-mode-pending-parse-callbacks nil)))
11158
11159 (defun js2-mode-flag-region (from to flag)
11160 "Hide or show text from FROM to TO, according to FLAG.
11161 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11162 Returns the created overlay if FLAG is non-nil."
11163 (remove-overlays from to 'invisible 'js2-outline)
11164 (when flag
11165 (let ((o (make-overlay from to)))
11166 (overlay-put o 'invisible 'js2-outline)
11167 (overlay-put o 'isearch-open-invisible
11168 'js2-isearch-open-invisible)
11169 o)))
11170
11171 ;; Function to be set as an outline-isearch-open-invisible' property
11172 ;; to the overlay that makes the outline invisible (see
11173 ;; `js2-mode-flag-region').
11174 (defun js2-isearch-open-invisible (overlay)
11175 ;; We rely on the fact that isearch places point on the matched text.
11176 (js2-mode-show-element))
11177
11178 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11179 "Return cons cell of bounds of folding overlay at POS.
11180 Returns nil if not found."
11181 (let ((overlays (overlays-at (or pos (point))))
11182 o)
11183 (while (and overlays
11184 (not o))
11185 (if (overlay-get (car overlays) 'invisible)
11186 (setq o (car overlays))
11187 (setq overlays (cdr overlays))))
11188 (if o
11189 (cons (overlay-start o) (overlay-end o)))))
11190
11191 (defun js2-mode-function-at-point (&optional pos)
11192 "Return the innermost function node enclosing current point.
11193 Returns nil if point is not in a function."
11194 (let ((node (js2-node-at-point pos)))
11195 (while (and node (not (js2-function-node-p node)))
11196 (setq node (js2-node-parent node)))
11197 (if (js2-function-node-p node)
11198 node)))
11199
11200 (defun js2-mode-toggle-element ()
11201 "Hide or show the foldable element at the point."
11202 (interactive)
11203 (let (comment fn pos)
11204 (save-excursion
11205 (save-match-data
11206 (cond
11207 ;; /* ... */ comment?
11208 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11209 (if (js2-mode-invisible-overlay-bounds
11210 (setq pos (+ 3 (js2-node-abs-pos comment))))
11211 (progn
11212 (goto-char pos)
11213 (js2-mode-show-element))
11214 (js2-mode-hide-element)))
11215 ;; //-comment?
11216 ((save-excursion
11217 (back-to-indentation)
11218 (looking-at js2-mode-//-comment-re))
11219 (js2-mode-toggle-//-comment))
11220 ;; function?
11221 ((setq fn (js2-mode-function-at-point))
11222 (setq pos (and (js2-function-node-body fn)
11223 (js2-node-abs-pos (js2-function-node-body fn))))
11224 (goto-char (1+ pos))
11225 (if (js2-mode-invisible-overlay-bounds)
11226 (js2-mode-show-element)
11227 (js2-mode-hide-element)))
11228 (t
11229 (message "Nothing at point to hide or show")))))))
11230
11231 (defun js2-mode-hide-element ()
11232 "Fold/hide contents of a block, showing ellipses.
11233 Show the hidden text with \\[js2-mode-show-element]."
11234 (interactive)
11235 (if js2-mode-buffer-dirty-p
11236 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11237 (let (node body beg end)
11238 (cond
11239 ((js2-mode-invisible-overlay-bounds)
11240 (message "already hidden"))
11241 (t
11242 (setq node (js2-node-at-point))
11243 (cond
11244 ((js2-block-comment-p node)
11245 (js2-mode-hide-comment node))
11246 (t
11247 (while (and node (not (js2-function-node-p node)))
11248 (setq node (js2-node-parent node)))
11249 (if (and node
11250 (setq body (js2-function-node-body node)))
11251 (progn
11252 (setq beg (js2-node-abs-pos body)
11253 end (+ beg (js2-node-len body)))
11254 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11255 (message "No collapsable element found at point"))))))))
11256
11257 (defun js2-mode-show-element ()
11258 "Show the hidden element at current point."
11259 (interactive)
11260 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11261 (if bounds
11262 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11263 (message "Nothing to un-hide"))))
11264
11265 (defun js2-mode-show-all ()
11266 "Show all of the text in the buffer."
11267 (interactive)
11268 (js2-mode-flag-region (point-min) (point-max) nil))
11269
11270 (defun js2-mode-toggle-hide-functions ()
11271 (interactive)
11272 (if js2-mode-functions-hidden
11273 (js2-mode-show-functions)
11274 (js2-mode-hide-functions)))
11275
11276 (defun js2-mode-hide-functions ()
11277 "Hides all non-nested function bodies in the buffer.
11278 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11279 to open an individual entry."
11280 (interactive)
11281 (if js2-mode-buffer-dirty-p
11282 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11283 (if (null js2-mode-ast)
11284 (message "Oops - parsing failed")
11285 (setq js2-mode-functions-hidden t)
11286 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11287
11288 (defun js2-mode-function-hider (n endp)
11289 (when (not endp)
11290 (let ((tt (js2-node-type n))
11291 body beg end)
11292 (cond
11293 ((and (= tt js2-FUNCTION)
11294 (setq body (js2-function-node-body n)))
11295 (setq beg (js2-node-abs-pos body)
11296 end (+ beg (js2-node-len body)))
11297 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11298 nil) ; don't process children of function
11299 (t
11300 t))))) ; keep processing other AST nodes
11301
11302 (defun js2-mode-show-functions ()
11303 "Un-hide any folded function bodies in the buffer."
11304 (interactive)
11305 (setq js2-mode-functions-hidden nil)
11306 (save-excursion
11307 (goto-char (point-min))
11308 (while (/= (goto-char (next-overlay-change (point)))
11309 (point-max))
11310 (dolist (o (overlays-at (point)))
11311 (when (and (overlay-get o 'invisible)
11312 (not (overlay-get o 'comment)))
11313 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11314
11315 (defun js2-mode-hide-comment (n)
11316 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11317 3 ; /**
11318 2)) ; /*
11319 (beg (+ (js2-node-abs-pos n) head))
11320 (end (- (+ beg (js2-node-len n)) head 2))
11321 (o (js2-mode-flag-region beg end 'hide)))
11322 (overlay-put o 'comment t)))
11323
11324 (defun js2-mode-toggle-hide-comments ()
11325 "Folds all block comments in the buffer.
11326 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11327 to open an individual entry."
11328 (interactive)
11329 (if js2-mode-comments-hidden
11330 (js2-mode-show-comments)
11331 (js2-mode-hide-comments)))
11332
11333 (defun js2-mode-hide-comments ()
11334 (interactive)
11335 (if js2-mode-buffer-dirty-p
11336 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11337 (if (null js2-mode-ast)
11338 (message "Oops - parsing failed")
11339 (setq js2-mode-comments-hidden t)
11340 (dolist (n (js2-ast-root-comments js2-mode-ast))
11341 (let ((format (js2-comment-node-format n)))
11342 (when (js2-block-comment-p n)
11343 (js2-mode-hide-comment n))))
11344 (js2-mode-hide-//-comments)))
11345
11346 (defsubst js2-mode-extend-//-comment (direction)
11347 "Find start or end of a block of similar //-comment lines.
11348 DIRECTION is -1 to look back, 1 to look forward.
11349 INDENT is the indentation level to match.
11350 Returns the end-of-line position of the furthest adjacent
11351 //-comment line with the same indentation as the current line.
11352 If there is no such matching line, returns current end of line."
11353 (let ((pos (point-at-eol))
11354 (indent (current-indentation)))
11355 (save-excursion
11356 (save-match-data
11357 (while (and (zerop (forward-line direction))
11358 (looking-at js2-mode-//-comment-re)
11359 (eq indent (length (match-string 1))))
11360 (setq pos (point-at-eol)))
11361 pos))))
11362
11363 (defun js2-mode-hide-//-comments ()
11364 "Fold adjacent 1-line comments, showing only snippet of first one."
11365 (let (beg end)
11366 (save-excursion
11367 (save-match-data
11368 (goto-char (point-min))
11369 (while (re-search-forward js2-mode-//-comment-re nil t)
11370 (setq beg (point)
11371 end (js2-mode-extend-//-comment 1))
11372 (unless (eq beg end)
11373 (overlay-put (js2-mode-flag-region beg end 'hide)
11374 'comment t))
11375 (goto-char end)
11376 (forward-char 1))))))
11377
11378 (defun js2-mode-toggle-//-comment ()
11379 "Fold or un-fold any multi-line //-comment at point.
11380 Caller should have determined that this line starts with a //-comment."
11381 (let* ((beg (point-at-eol))
11382 (end beg))
11383 (save-excursion
11384 (goto-char end)
11385 (if (js2-mode-invisible-overlay-bounds)
11386 (js2-mode-show-element)
11387 ;; else hide the comment
11388 (setq beg (js2-mode-extend-//-comment -1)
11389 end (js2-mode-extend-//-comment 1))
11390 (unless (eq beg end)
11391 (overlay-put (js2-mode-flag-region beg end 'hide)
11392 'comment t))))))
11393
11394 (defun js2-mode-show-comments ()
11395 "Un-hide any hidden comments, leaving other hidden elements alone."
11396 (interactive)
11397 (setq js2-mode-comments-hidden nil)
11398 (save-excursion
11399 (goto-char (point-min))
11400 (while (/= (goto-char (next-overlay-change (point)))
11401 (point-max))
11402 (dolist (o (overlays-at (point)))
11403 (when (overlay-get o 'comment)
11404 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11405
11406 (defun js2-mode-display-warnings-and-errors ()
11407 "Turn on display of warnings and errors."
11408 (interactive)
11409 (setq js2-mode-show-parse-errors t
11410 js2-mode-show-strict-warnings t)
11411 (js2-reparse 'force))
11412
11413 (defun js2-mode-hide-warnings-and-errors ()
11414 "Turn off display of warnings and errors."
11415 (interactive)
11416 (setq js2-mode-show-parse-errors nil
11417 js2-mode-show-strict-warnings nil)
11418 (js2-reparse 'force))
11419
11420 (defun js2-mode-toggle-warnings-and-errors ()
11421 "Toggle the display of warnings and errors.
11422 Some users don't like having warnings/errors reported while they type."
11423 (interactive)
11424 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11425 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11426 (if (interactive-p)
11427 (message "warnings and errors %s"
11428 (if js2-mode-show-parse-errors
11429 "enabled"
11430 "disabled")))
11431 (js2-reparse 'force))
11432
11433 (defun js2-mode-customize ()
11434 (interactive)
11435 (customize-group 'js2-mode))
11436
11437 (defun js2-mode-forward-sexp (&optional arg)
11438 "Move forward across one statement or balanced expression.
11439 With ARG, do it that many times. Negative arg -N means
11440 move backward across N balanced expressions."
11441 (interactive "p")
11442 (setq arg (or arg 1))
11443 (if js2-mode-buffer-dirty-p
11444 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11445 (let (node end (start (point)))
11446 (cond
11447 ;; backward-sexp
11448 ;; could probably make this better for some cases:
11449 ;; - if in statement block (e.g. function body), go to parent
11450 ;; - infix exprs like (foo in bar) - maybe go to beginning
11451 ;; of infix expr if in the right-side expression?
11452 ((and arg (minusp arg))
11453 (dotimes (i (- arg))
11454 (js2-backward-sws)
11455 (forward-char -1) ; enter the node we backed up to
11456 (setq node (js2-node-at-point (point) t))
11457 (goto-char (if node
11458 (js2-node-abs-pos node)
11459 (point-min)))))
11460 (t
11461 ;; forward-sexp
11462 (js2-forward-sws)
11463 (dotimes (i arg)
11464 (js2-forward-sws)
11465 (setq node (js2-node-at-point (point) t)
11466 end (if node (+ (js2-node-abs-pos node)
11467 (js2-node-len node))))
11468 (goto-char (or end (point-max))))))))
11469
11470 (defun js2-next-error (&optional arg reset)
11471 "Move to next parse error.
11472 Typically invoked via \\[next-error].
11473 ARG is the number of errors, forward or backward, to move.
11474 RESET means start over from the beginning."
11475 (interactive "p")
11476 (if (or (null js2-mode-ast)
11477 (and (null (js2-ast-root-errors js2-mode-ast))
11478 (null (js2-ast-root-warnings js2-mode-ast))))
11479 (message "No errors")
11480 (when reset
11481 (goto-char (point-min)))
11482 (let* ((errs (copy-sequence
11483 (append (js2-ast-root-errors js2-mode-ast)
11484 (js2-ast-root-warnings js2-mode-ast))))
11485 (continue t)
11486 (start (point))
11487 (count (or arg 1))
11488 (backward (minusp count))
11489 (sorter (if backward '> '<))
11490 (stopper (if backward '< '>))
11491 (count (abs count))
11492 all-errs
11493 err)
11494 ;; sort by start position
11495 (setq errs (sort errs (lambda (e1 e2)
11496 (funcall sorter (second e1) (second e2))))
11497 all-errs errs)
11498 ;; find nth error with pos > start
11499 (while (and errs continue)
11500 (when (funcall stopper (cadar errs) start)
11501 (setq err (car errs))
11502 (if (zerop (decf count))
11503 (setq continue nil)))
11504 (setq errs (cdr errs)))
11505 (if err
11506 (goto-char (second err))
11507 ;; wrap around to first error
11508 (goto-char (second (car all-errs)))
11509 ;; if we were already on it, echo msg again
11510 (if (= (point) start)
11511 (js2-echo-error (point) (point)))))))
11512
11513 (defun js2-down-mouse-3 ()
11514 "Make right-click move the point to the click location.
11515 This makes right-click context menu operations a bit more intuitive.
11516 The point will not move if the region is active, however, to avoid
11517 destroying the region selection."
11518 (interactive)
11519 (when (and js2-move-point-on-right-click
11520 (not mark-active))
11521 (let ((e last-input-event))
11522 (ignore-errors
11523 (goto-char (cadadr e))))))
11524
11525 (defun js2-mode-create-imenu-index ()
11526 "Return an alist for `imenu--index-alist'."
11527 ;; This is built up in `js2-parse-record-imenu' during parsing.
11528 (when js2-mode-ast
11529 ;; if we have an ast but no recorder, they're requesting a rescan
11530 (unless js2-imenu-recorder
11531 (js2-reparse 'force))
11532 (prog1
11533 (js2-build-imenu-index)
11534 (setq js2-imenu-recorder nil
11535 js2-imenu-function-map nil))))
11536
11537 (defun js2-mode-find-tag ()
11538 "Replacement for `find-tag-default'.
11539 `find-tag-default' returns a ridiculous answer inside comments."
11540 (let (beg end)
11541 (js2-with-underscore-as-word-syntax
11542 (save-excursion
11543 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11544 (looking-back "[A-Za-z0-9_$]"))
11545 (setq beg (progn (forward-word -1) (point))
11546 end (progn (forward-word 1) (point)))
11547 (setq beg (progn (forward-word 1) (point))
11548 end (progn (forward-word -1) (point))))
11549 (replace-regexp-in-string
11550 "[\"']" ""
11551 (buffer-substring-no-properties beg end))))))
11552
11553 (defun js2-mode-forward-sibling ()
11554 "Move to the end of the sibling following point in parent.
11555 Returns non-nil if successful, or nil if there was no following sibling."
11556 (let* ((node (js2-node-at-point))
11557 (parent (js2-mode-find-enclosing-fn node))
11558 sib)
11559 (when (setq sib (js2-node-find-child-after (point) parent))
11560 (goto-char (+ (js2-node-abs-pos sib)
11561 (js2-node-len sib))))))
11562
11563 (defun js2-mode-backward-sibling ()
11564 "Move to the beginning of the sibling node preceding point in parent.
11565 Parent is defined as the enclosing script or function."
11566 (let* ((node (js2-node-at-point))
11567 (parent (js2-mode-find-enclosing-fn node))
11568 sib)
11569 (when (setq sib (js2-node-find-child-before (point) parent))
11570 (goto-char (js2-node-abs-pos sib)))))
11571
11572 (defun js2-beginning-of-defun (&optional arg)
11573 "Go to line on which current function starts, and return t on success.
11574 If we're not in a function or already at the beginning of one, go
11575 to beginning of previous script-level element.
11576 With ARG N, do that N times. If N is negative, move forward."
11577 (setq arg (or arg 1))
11578 (if (plusp arg)
11579 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11580 (when (cond
11581 ((js2-function-node-p parent)
11582 (goto-char (js2-node-abs-pos parent)))
11583 (t
11584 (js2-mode-backward-sibling)))
11585 (if (> arg 1)
11586 (js2-beginning-of-defun (1- arg))
11587 t)))
11588 (when (js2-end-of-defun)
11589 (if (>= arg -1)
11590 (js2-beginning-of-defun 1)
11591 (js2-beginning-of-defun (1+ arg))))))
11592
11593 (defun js2-end-of-defun ()
11594 "Go to the char after the last position of the current function
11595 or script-level element."
11596 (let* ((node (js2-node-at-point))
11597 (parent (or (and (js2-function-node-p node) node)
11598 (js2-node-parent-script-or-fn node)))
11599 script)
11600 (unless (js2-function-node-p parent)
11601 ;; use current script-level node, or, if none, the next one
11602 (setq script (or parent node))
11603 (setq parent (js2-node-find-child-before (point) script))
11604 (when (or (null parent)
11605 (>= (point) (+ (js2-node-abs-pos parent)
11606 (js2-node-len parent))))
11607 (setq parent (js2-node-find-child-after (point) script))))
11608 (when parent
11609 (goto-char (+ (js2-node-abs-pos parent)
11610 (js2-node-len parent))))))
11611
11612 (defun js2-mark-defun (&optional allow-extend)
11613 "Put mark at end of this function, point at beginning.
11614 The function marked is the one that contains point.
11615
11616 Interactively, if this command is repeated,
11617 or (in Transient Mark mode) if the mark is active,
11618 it marks the next defun after the ones already marked."
11619 (interactive "p")
11620 (let (extended)
11621 (when (and allow-extend
11622 (or (and (eq last-command this-command) (mark t))
11623 (and transient-mark-mode mark-active)))
11624 (let ((sib (save-excursion
11625 (goto-char (mark))
11626 (if (js2-mode-forward-sibling)
11627 (point))))
11628 node)
11629 (if sib
11630 (progn
11631 (set-mark sib)
11632 (setq extended t))
11633 ;; no more siblings - try extending to enclosing node
11634 (goto-char (mark t)))))
11635 (when (not extended)
11636 (let ((node (js2-node-at-point (point) t)) ; skip comments
11637 ast fn stmt parent beg end)
11638 (when (js2-ast-root-p node)
11639 (setq ast node
11640 node (or (js2-node-find-child-after (point) node)
11641 (js2-node-find-child-before (point) node))))
11642 ;; only mark whole buffer if we can't find any children
11643 (if (null node)
11644 (setq node ast))
11645 (if (js2-function-node-p node)
11646 (setq parent node)
11647 (setq fn (js2-mode-find-enclosing-fn node)
11648 stmt (if (or (null fn)
11649 (js2-ast-root-p fn))
11650 (js2-mode-find-first-stmt node))
11651 parent (or stmt fn)))
11652 (setq beg (js2-node-abs-pos parent)
11653 end (+ beg (js2-node-len parent)))
11654 (push-mark beg)
11655 (goto-char end)
11656 (exchange-point-and-mark)))))
11657
11658 (defun js2-narrow-to-defun ()
11659 "Narrow to the function enclosing point."
11660 (interactive)
11661 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11662 (fn (if (js2-script-node-p node)
11663 node
11664 (js2-mode-find-enclosing-fn node)))
11665 (beg (js2-node-abs-pos fn)))
11666 (unless (js2-ast-root-p fn)
11667 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11668
11669 (provide 'js2-mode)
11670
11671 ;;; js2-mode.el ends here