]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Fix comment
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- an improved JavaScript editing mode
2
3 ;; Copyright (C) 2009 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; Contributors: mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; Version: See `js2-mode-version'
9 ;; Keywords: languages, javascript
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27
28 ;; This JavaScript editing mode supports:
29
30 ;; - strict recognition of the Ecma-262 language standard
31 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 to 1.8
32 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
33 ;; - accurate syntax highlighting using a recursive-descent parser
34 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
35 ;; - undeclared-variable warnings using a configurable externs framework
36 ;; - "bouncing" line indentation to choose among alternate indentation points
37 ;; - smart line-wrapping within comments and strings
38 ;; - code folding:
39 ;; - show some or all function bodies as {...}
40 ;; - show some or all block comments as /*...*/
41 ;; - context-sensitive menu bar and popup menus
42 ;; - code browsing using the `imenu' package
43 ;; - typing helpers such as automatic insertion of matching braces/parens
44 ;; - many customization options
45
46 ;; To customize how it works:
47 ;; M-x customize-group RET js2-mode RET
48
49 ;; Notes:
50
51 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
52 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
53 ;; `js2-mode' current as the EcmaScript language standard evolves.
54
55 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
56 ;; customizable. It is a surprising amount of work to support customizable
57 ;; indentation. The current compromise is that the tab key lets you cycle among
58 ;; various likely indentation points, similar to the behavior of python-mode.
59
60 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
61 ;; and `mumamo', although it could be made to do so with some effort.
62 ;; This means that `js2-mode' is currently only useful for editing JavaScript
63 ;; files, and not for editing JavaScript within <script> tags or templates.
64
65 ;;; Code:
66
67 (eval-when-compile
68 (require 'cl))
69
70 (require 'imenu)
71 (require 'cc-cmds) ; for `c-fill-paragraph'
72
73 (eval-and-compile
74 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
75 (require 'cc-langs) ; it's here in Emacs 21...
76 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
77
78 ;;; Externs (variables presumed to be defined by the host system)
79
80 (defvar js2-ecma-262-externs
81 (mapcar 'symbol-name
82 '(Array Boolean Date Error EvalError Function Infinity JSON
83 Math NaN Number Object RangeError ReferenceError RegExp
84 String SyntaxError TypeError URIError arguments
85 decodeURI decodeURIComponent encodeURI
86 encodeURIComponent escape eval isFinite isNaN
87 parseFloat parseInt undefined unescape))
88 "Ecma-262 externs. Included in `js2-externs' by default.")
89
90 (defvar js2-browser-externs
91 (mapcar 'symbol-name
92 '(;; DOM level 1
93 Attr CDATASection CharacterData Comment DOMException
94 DOMImplementation Document DocumentFragment
95 DocumentType Element Entity EntityReference
96 ExceptionCode NamedNodeMap Node NodeList Notation
97 ProcessingInstruction Text
98
99 ;; DOM level 2
100 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
101 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
102 HTMLBodyElement HTMLButtonElement HTMLCollection
103 HTMLDListElement HTMLDirectoryElement HTMLDivElement
104 HTMLDocument HTMLElement HTMLFieldSetElement
105 HTMLFontElement HTMLFormElement HTMLFrameElement
106 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
107 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
108 HTMLImageElement HTMLInputElement HTMLIsIndexElement
109 HTMLLIElement HTMLLabelElement HTMLLegendElement
110 HTMLLinkElement HTMLMapElement HTMLMenuElement
111 HTMLMetaElement HTMLModElement HTMLOListElement
112 HTMLObjectElement HTMLOptGroupElement
113 HTMLOptionElement HTMLOptionsCollection
114 HTMLParagraphElement HTMLParamElement HTMLPreElement
115 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
116 HTMLStyleElement HTMLTableCaptionElement
117 HTMLTableCellElement HTMLTableColElement
118 HTMLTableElement HTMLTableRowElement
119 HTMLTableSectionElement HTMLTextAreaElement
120 HTMLTitleElement HTMLUListElement
121
122 ;; DOM level 3
123 DOMConfiguration DOMError DOMException
124 DOMImplementationList DOMImplementationSource
125 DOMLocator DOMStringList NameList TypeInfo
126 UserDataHandler
127
128 ;; Window
129 window alert confirm document java navigator prompt screen
130 self top
131
132 ;; W3C CSS
133 CSSCharsetRule CSSFontFace CSSFontFaceRule
134 CSSImportRule CSSMediaRule CSSPageRule
135 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
136 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
137 CSSValue CSSValueList Counter DOMImplementationCSS
138 DocumentCSS DocumentStyle ElementCSSInlineStyle
139 LinkStyle MediaList RGBColor Rect StyleSheet
140 StyleSheetList ViewCSS
141
142 ;; W3C Event
143 EventListener EventTarget Event DocumentEvent UIEvent
144 MouseEvent MutationEvent KeyboardEvent
145
146 ;; W3C Range
147 DocumentRange Range RangeException
148
149 ;; W3C XML
150 XPathResult XMLHttpRequest))
151 "Browser externs.
152 You can cause these to be included or excluded with the custom
153 variable `js2-include-browser-externs'.")
154
155 (defvar js2-rhino-externs
156 (mapcar 'symbol-name
157 '(Packages importClass importPackage com org java
158 ;; Global object (shell) externs
159 defineClass deserialize doctest gc help load
160 loadClass print quit readFile readUrl runCommand seal
161 serialize spawn sync toint32 version))
162 "Mozilla Rhino externs.
163 Set `js2-include-rhino-externs' to t to include them.")
164
165 (defvar js2-gears-externs
166 (mapcar 'symbol-name
167 '(
168 ;; TODO(stevey): add these
169 ))
170 "Google Gears externs.
171 Set `js2-include-gears-externs' to t to include them.")
172
173 ;;; Variables
174
175 (defun js2-mark-safe-local (name pred)
176 "Make the variable NAME buffer-local and mark it as safe file-local
177 variable with predicate PRED."
178 (make-variable-buffer-local name)
179 (put name 'safe-local-variable pred))
180
181 (defvar js2-emacs22 (>= emacs-major-version 22))
182
183 (defcustom js2-highlight-level 2
184 "Amount of syntax highlighting to perform.
185 0 or a negative value means do no highlighting.
186 1 adds basic syntax highlighting.
187 2 adds highlighting of some Ecma built-in properties.
188 3 adds highlighting of many Ecma built-in functions."
189 :group 'js2-mode
190 :type '(choice (const :tag "None" 0)
191 (const :tag "Basic" 1)
192 (const :tag "Include Properties" 2)
193 (const :tag "Include Functions" 3)))
194
195 (defvar js2-mode-dev-mode-p nil
196 "Non-nil if running in development mode. Normally nil.")
197
198 (defgroup js2-mode nil
199 "An improved JavaScript mode."
200 :group 'languages)
201
202 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
203 (numberp c-basic-offset))
204 c-basic-offset
205 4)
206 "Number of spaces to indent nested statements.
207 Similar to `c-basic-offset'."
208 :group 'js2-mode
209 :type 'integer)
210 (js2-mark-safe-local 'js2-basic-offset 'integerp)
211
212 ;; TODO(stevey): move this code into a separate minor mode.
213 (defcustom js2-mirror-mode nil
214 "Non-nil to insert closing brackets, parens, etc. automatically."
215 :group 'js2-mode
216 :type 'boolean)
217
218 (defcustom js2-auto-indent-p nil
219 "Automatic indentation with punctuation characters.
220 If non-nil, the current line is indented when certain punctuations
221 are inserted."
222 :group 'js2-mode
223 :type 'boolean)
224
225 (defcustom js2-bounce-indent-p nil
226 "Non-nil to have indent-line function choose among alternatives.
227 If nil, the indent-line function will indent to a predetermined column
228 based on heuristic guessing. If non-nil, then if the current line is
229 already indented to that predetermined column, indenting will choose
230 another likely column and indent to that spot. Repeated invocation of
231 the indent-line function will cycle among the computed alternatives.
232 See the function `js2-bounce-indent' for details. When it is non-nil,
233 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
234 :type 'boolean
235 :group 'js2-mode)
236
237 (defcustom js2-pretty-multiline-declarations t
238 "Non-nil to line up multiline declarations vertically:
239
240 var a = 10,
241 b = 20,
242 c = 30;
243
244 If the value is not `all', and the first assigned value in
245 declaration is a function/array/object literal spanning several
246 lines, it won't be indented additionally:
247
248 var o = { var bar = 2,
249 foo: 3 vs. o = {
250 }, foo: 3
251 bar = 2; };"
252 :group 'js2-mode
253 :type 'symbol)
254 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
255
256 (defcustom js2-indent-on-enter-key nil
257 "Non-nil to have Enter/Return key indent the line.
258 This is unusual for Emacs modes but common in IDEs like Eclipse."
259 :type 'boolean
260 :group 'js2-mode)
261
262 (defcustom js2-enter-indents-newline nil
263 "Non-nil to have Enter/Return key indent the newly-inserted line.
264 This is unusual for Emacs modes but common in IDEs like Eclipse."
265 :type 'boolean
266 :group 'js2-mode)
267
268 (defcustom js2-rebind-eol-bol-keys t
269 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
270 If non-nil, bounce between bol/eol and first/last non-whitespace char."
271 :group 'js2-mode
272 :type 'boolean)
273
274 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
275 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
276 Each value in the list is passed to `define-key'."
277 :type 'list
278 :group 'js2-mode)
279
280 (defcustom js2-idle-timer-delay 0.2
281 "Delay in secs before re-parsing after user makes changes.
282 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
283 :type 'number
284 :group 'js2-mode)
285 (make-variable-buffer-local 'js2-idle-timer-delay)
286
287 (defcustom js2-dynamic-idle-timer-adjust 0
288 "Positive to adjust `js2-idle-timer-delay' based on file size.
289 The idea is that for short files, parsing is faster so we can be
290 more responsive to user edits without interfering with editing.
291 The buffer length in characters (typically bytes) is divided by
292 this value and used to multiply `js2-idle-timer-delay' for the
293 buffer. For example, a 21k file and 10k adjust yields 21k/10k
294 == 2, so js2-idle-timer-delay is multiplied by 2.
295 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
296 `js2-idle-timer-delay' is not dependent on the file size."
297 :type 'number
298 :group 'js2-mode)
299
300 (defcustom js2-mode-escape-quotes t
301 "Non-nil to disable automatic quote-escaping inside strings."
302 :type 'boolean
303 :group 'js2-mode)
304
305 (defcustom js2-concat-multiline-strings t
306 "Non-nil to automatically turn a newline in mid-string into a
307 string concatenation. When `eol', the '+' will be inserted at the
308 end of the line, otherwise, at the beginning of the next line."
309 :type '(choice (const t) (const eol) (const nil))
310 :group 'js2-mode)
311
312 (defcustom js2-mode-squeeze-spaces t
313 "Non-nil to normalize whitespace when filling in comments.
314 Multiple runs of spaces are converted to a single space."
315 :type 'boolean
316 :group 'js2-mode)
317
318 (defcustom js2-mode-show-parse-errors t
319 "True to highlight parse errors."
320 :type 'boolean
321 :group 'js2-mode)
322
323 (defcustom js2-mode-show-strict-warnings t
324 "Non-nil to emit Ecma strict-mode warnings.
325 Some of the warnings can be individually disabled by other flags,
326 even if this flag is non-nil."
327 :type 'boolean
328 :group 'js2-mode)
329
330 (defcustom js2-strict-trailing-comma-warning t
331 "Non-nil to warn about trailing commas in array literals.
332 Ecma-262 forbids them, but many browsers permit them. IE is the
333 big exception, and can produce bugs if you have trailing commas."
334 :type 'boolean
335 :group 'js2-mode)
336
337 (defcustom js2-strict-missing-semi-warning t
338 "Non-nil to warn about semicolon auto-insertion after statement.
339 Technically this is legal per Ecma-262, but some style guides disallow
340 depending on it."
341 :type 'boolean
342 :group 'js2-mode)
343
344 (defcustom js2-missing-semi-one-line-override nil
345 "Non-nil to permit missing semicolons in one-line functions.
346 In one-liner functions such as `function identity(x) {return x}'
347 people often omit the semicolon for a cleaner look. If you are
348 such a person, you can suppress the missing-semicolon warning
349 by setting this variable to t."
350 :type 'boolean
351 :group 'js2-mode)
352
353 (defcustom js2-strict-inconsistent-return-warning t
354 "Non-nil to warn about mixing returns with value-returns.
355 It's perfectly legal to have a `return' and a `return foo' in the
356 same function, but it's often an indicator of a bug, and it also
357 interferes with type inference (in systems that support it.)"
358 :type 'boolean
359 :group 'js2-mode)
360
361 (defcustom js2-strict-cond-assign-warning t
362 "Non-nil to warn about expressions like if (a = b).
363 This often should have been '==' instead of '='. If the warning
364 is enabled, you can suppress it on a per-expression basis by
365 parenthesizing the expression, e.g. if ((a = b)) ..."
366 :type 'boolean
367 :group 'js2-mode)
368
369 (defcustom js2-strict-var-redeclaration-warning t
370 "Non-nil to warn about redeclaring variables in a script or function."
371 :type 'boolean
372 :group 'js2-mode)
373
374 (defcustom js2-strict-var-hides-function-arg-warning t
375 "Non-nil to warn about a var decl hiding a function argument."
376 :type 'boolean
377 :group 'js2-mode)
378
379 (defcustom js2-skip-preprocessor-directives nil
380 "Non-nil to treat lines beginning with # as comments.
381 Useful for viewing Mozilla JavaScript source code."
382 :type 'boolean
383 :group 'js2-mode)
384
385 (defcustom js2-language-version 200
386 "Configures what JavaScript language version to recognize.
387 Currently versions 150, 160, 170, 180 and 200 are supported,
388 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
389 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
390 yield, and Array comprehensions, and 1.8 adds function closures."
391 :type 'integer
392 :group 'js2-mode)
393
394 (defcustom js2-allow-keywords-as-property-names t
395 "If non-nil, you can use JavaScript keywords as object property names.
396 Examples:
397
398 var foo = {int: 5, while: 6, continue: 7};
399 foo.return = 8;
400
401 Ecma-262 forbids this syntax, but many browsers support it."
402 :type 'boolean
403 :group 'js2-mode)
404
405 (defcustom js2-instanceof-has-side-effects nil
406 "If non-nil, treats the instanceof operator as having side effects.
407 This is useful for xulrunner apps."
408 :type 'boolean
409 :group 'js2-mode)
410
411 (defcustom js2-cleanup-whitespace nil
412 "Non-nil to invoke `delete-trailing-whitespace' before saves."
413 :type 'boolean
414 :group 'js2-mode)
415
416 (defcustom js2-move-point-on-right-click t
417 "Non-nil to move insertion point when you right-click.
418 This makes right-click context menu behavior a bit more intuitive,
419 since menu operations generally apply to the point. The exception
420 is if there is a region selection, in which case the point does -not-
421 move, so cut/copy/paste etc. can work properly.
422
423 Note that IntelliJ moves the point, and Eclipse leaves it alone,
424 so this behavior is customizable."
425 :group 'js2-mode
426 :type 'boolean)
427
428 (defcustom js2-allow-rhino-new-expr-initializer t
429 "Non-nil to support a Rhino's experimental syntactic construct.
430
431 Rhino supports the ability to follow a `new' expression with an object
432 literal, which is used to set additional properties on the new object
433 after calling its constructor. Syntax:
434
435 new <expr> [ ( arglist ) ] [initializer]
436
437 Hence, this expression:
438
439 new Object {a: 1, b: 2}
440
441 results in an Object with properties a=1 and b=2. This syntax is
442 apparently not configurable in Rhino - it's currently always enabled,
443 as of Rhino version 1.7R2."
444 :type 'boolean
445 :group 'js2-mode)
446
447 (defcustom js2-allow-member-expr-as-function-name nil
448 "Non-nil to support experimental Rhino syntax for function names.
449
450 Rhino supports an experimental syntax configured via the Rhino Context
451 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
452
453 function <member-expr> ( [ arg-list ] ) { <body> }
454
455 Where member-expr is a non-parenthesized 'member expression', which
456 is anything at the grammar level of a new-expression or lower, meaning
457 any expression that does not involve infix or unary operators.
458
459 When <member-expr> is not a simple identifier, then it is syntactic
460 sugar for assigning the anonymous function to the <member-expr>. Hence,
461 this code:
462
463 function a.b().c[2] (x, y) { ... }
464
465 is rewritten as:
466
467 a.b().c[2] = function(x, y) {...}
468
469 which doesn't seem particularly useful, but Rhino permits it."
470 :type 'boolean
471 :group 'js2-mode)
472
473 (defvar js2-mode-version 20101228
474 "Release number for `js2-mode'.")
475
476 ;; scanner variables
477
478 (defmacro js2-deflocal (name value &optional comment)
479 "Define a buffer-local variable NAME with VALUE and COMMENT."
480 `(progn
481 (defvar ,name ,value ,comment)
482 (make-variable-buffer-local ',name)))
483
484 ;; We record the start and end position of each token.
485 (js2-deflocal js2-token-beg 1)
486 (js2-deflocal js2-token-end -1)
487
488 (defvar js2-EOF_CHAR -1
489 "Represents end of stream. Distinct from js2-EOF token type.")
490
491 ;; I originally used symbols to represent tokens, but Rhino uses
492 ;; ints and then sets various flag bits in them, so ints it is.
493 ;; The upshot is that we need a `js2-' prefix in front of each name.
494 (defvar js2-ERROR -1)
495 (defvar js2-EOF 0)
496 (defvar js2-EOL 1)
497 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
498 (defvar js2-LEAVEWITH 3)
499 (defvar js2-RETURN 4)
500 (defvar js2-GOTO 5)
501 (defvar js2-IFEQ 6)
502 (defvar js2-IFNE 7)
503 (defvar js2-SETNAME 8)
504 (defvar js2-BITOR 9)
505 (defvar js2-BITXOR 10)
506 (defvar js2-BITAND 11)
507 (defvar js2-EQ 12)
508 (defvar js2-NE 13)
509 (defvar js2-LT 14)
510 (defvar js2-LE 15)
511 (defvar js2-GT 16)
512 (defvar js2-GE 17)
513 (defvar js2-LSH 18)
514 (defvar js2-RSH 19)
515 (defvar js2-URSH 20)
516 (defvar js2-ADD 21) ; infix plus
517 (defvar js2-SUB 22) ; infix minus
518 (defvar js2-MUL 23)
519 (defvar js2-DIV 24)
520 (defvar js2-MOD 25)
521 (defvar js2-NOT 26)
522 (defvar js2-BITNOT 27)
523 (defvar js2-POS 28) ; unary plus
524 (defvar js2-NEG 29) ; unary minus
525 (defvar js2-NEW 30)
526 (defvar js2-DELPROP 31)
527 (defvar js2-TYPEOF 32)
528 (defvar js2-GETPROP 33)
529 (defvar js2-GETPROPNOWARN 34)
530 (defvar js2-SETPROP 35)
531 (defvar js2-GETELEM 36)
532 (defvar js2-SETELEM 37)
533 (defvar js2-CALL 38)
534 (defvar js2-NAME 39) ; an identifier
535 (defvar js2-NUMBER 40)
536 (defvar js2-STRING 41)
537 (defvar js2-NULL 42)
538 (defvar js2-THIS 43)
539 (defvar js2-FALSE 44)
540 (defvar js2-TRUE 45)
541 (defvar js2-SHEQ 46) ; shallow equality (===)
542 (defvar js2-SHNE 47) ; shallow inequality (!==)
543 (defvar js2-REGEXP 48)
544 (defvar js2-BINDNAME 49)
545 (defvar js2-THROW 50)
546 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
547 (defvar js2-IN 52)
548 (defvar js2-INSTANCEOF 53)
549 (defvar js2-LOCAL_LOAD 54)
550 (defvar js2-GETVAR 55)
551 (defvar js2-SETVAR 56)
552 (defvar js2-CATCH_SCOPE 57)
553 (defvar js2-ENUM_INIT_KEYS 58)
554 (defvar js2-ENUM_INIT_VALUES 59)
555 (defvar js2-ENUM_INIT_ARRAY 60)
556 (defvar js2-ENUM_NEXT 61)
557 (defvar js2-ENUM_ID 62)
558 (defvar js2-THISFN 63)
559 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
560 (defvar js2-ARRAYLIT 65) ; array literal
561 (defvar js2-OBJECTLIT 66) ; object literal
562 (defvar js2-GET_REF 67) ; *reference
563 (defvar js2-SET_REF 68) ; *reference = something
564 (defvar js2-DEL_REF 69) ; delete reference
565 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
566 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
567 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
568
569 ;; XML support
570 (defvar js2-DEFAULTNAMESPACE 73)
571 (defvar js2-ESCXMLATTR 74)
572 (defvar js2-ESCXMLTEXT 75)
573 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
574 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
575 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
576 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
577
578 (defvar js2-first-bytecode js2-ENTERWITH)
579 (defvar js2-last-bytecode js2-REF_NS_NAME)
580
581 (defvar js2-TRY 80)
582 (defvar js2-SEMI 81) ; semicolon
583 (defvar js2-LB 82) ; left and right brackets
584 (defvar js2-RB 83)
585 (defvar js2-LC 84) ; left and right curly-braces
586 (defvar js2-RC 85)
587 (defvar js2-LP 86) ; left and right parens
588 (defvar js2-RP 87)
589 (defvar js2-COMMA 88) ; comma operator
590
591 (defvar js2-ASSIGN 89) ; simple assignment (=)
592 (defvar js2-ASSIGN_BITOR 90) ; |=
593 (defvar js2-ASSIGN_BITXOR 91) ; ^=
594 (defvar js2-ASSIGN_BITAND 92) ; &=
595 (defvar js2-ASSIGN_LSH 93) ; <<=
596 (defvar js2-ASSIGN_RSH 94) ; >>=
597 (defvar js2-ASSIGN_URSH 95) ; >>>=
598 (defvar js2-ASSIGN_ADD 96) ; +=
599 (defvar js2-ASSIGN_SUB 97) ; -=
600 (defvar js2-ASSIGN_MUL 98) ; *=
601 (defvar js2-ASSIGN_DIV 99) ; /=
602 (defvar js2-ASSIGN_MOD 100) ; %=
603
604 (defvar js2-first-assign js2-ASSIGN)
605 (defvar js2-last-assign js2-ASSIGN_MOD)
606
607 (defvar js2-HOOK 101) ; conditional (?:)
608 (defvar js2-COLON 102)
609 (defvar js2-OR 103) ; logical or (||)
610 (defvar js2-AND 104) ; logical and (&&)
611 (defvar js2-INC 105) ; increment/decrement (++ --)
612 (defvar js2-DEC 106)
613 (defvar js2-DOT 107) ; member operator (.)
614 (defvar js2-FUNCTION 108) ; function keyword
615 (defvar js2-EXPORT 109) ; export keyword
616 (defvar js2-IMPORT 110) ; import keyword
617 (defvar js2-IF 111) ; if keyword
618 (defvar js2-ELSE 112) ; else keyword
619 (defvar js2-SWITCH 113) ; switch keyword
620 (defvar js2-CASE 114) ; case keyword
621 (defvar js2-DEFAULT 115) ; default keyword
622 (defvar js2-WHILE 116) ; while keyword
623 (defvar js2-DO 117) ; do keyword
624 (defvar js2-FOR 118) ; for keyword
625 (defvar js2-BREAK 119) ; break keyword
626 (defvar js2-CONTINUE 120) ; continue keyword
627 (defvar js2-VAR 121) ; var keyword
628 (defvar js2-WITH 122) ; with keyword
629 (defvar js2-CATCH 123) ; catch keyword
630 (defvar js2-FINALLY 124) ; finally keyword
631 (defvar js2-VOID 125) ; void keyword
632 (defvar js2-RESERVED 126) ; reserved keywords
633
634 (defvar js2-EMPTY 127)
635
636 ;; Types used for the parse tree - never returned by scanner.
637
638 (defvar js2-BLOCK 128) ; statement block
639 (defvar js2-LABEL 129) ; label
640 (defvar js2-TARGET 130)
641 (defvar js2-LOOP 131)
642 (defvar js2-EXPR_VOID 132) ; expression statement in functions
643 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
644 (defvar js2-JSR 134)
645 (defvar js2-SCRIPT 135) ; top-level node for entire script
646 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
647 (defvar js2-USE_STACK 137)
648 (defvar js2-SETPROP_OP 138) ; x.y op= something
649 (defvar js2-SETELEM_OP 139) ; x[y] op= something
650 (defvar js2-LOCAL_BLOCK 140)
651 (defvar js2-SET_REF_OP 141) ; *reference op= something
652
653 ;; For XML support:
654 (defvar js2-DOTDOT 142) ; member operator (..)
655 (defvar js2-COLONCOLON 143) ; namespace::name
656 (defvar js2-XML 144) ; XML type
657 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
658 (defvar js2-XMLATTR 146) ; @
659 (defvar js2-XMLEND 147)
660
661 ;; Optimizer-only tokens
662 (defvar js2-TO_OBJECT 148)
663 (defvar js2-TO_DOUBLE 149)
664
665 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
666 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
667 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
668 (defvar js2-CONST 153)
669 (defvar js2-SETCONST 154)
670 (defvar js2-SETCONSTVAR 155)
671 (defvar js2-ARRAYCOMP 156)
672 (defvar js2-LETEXPR 157)
673 (defvar js2-WITHEXPR 158)
674 (defvar js2-DEBUGGER 159)
675
676 (defvar js2-COMMENT 160)
677 (defvar js2-ENUM 161) ; for "enum" reserved word
678 (defvar js2-TRIPLEDOT 162) ; for rest parameter
679
680 (defconst js2-num-tokens (1+ js2-TRIPLEDOT))
681
682 (defconst js2-debug-print-trees nil)
683
684 ;; Rhino accepts any string or stream as input. Emacs character
685 ;; processing works best in buffers, so we'll assume the input is a
686 ;; buffer. JavaScript strings can be copied into temp buffers before
687 ;; scanning them.
688
689 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
690 ;; They're the Emacs equivalent of instance variables, more or less.
691
692 (js2-deflocal js2-ts-dirty-line nil
693 "Token stream buffer-local variable.
694 Indicates stuff other than whitespace since start of line.")
695
696 (js2-deflocal js2-ts-regexp-flags nil
697 "Token stream buffer-local variable.")
698
699 (js2-deflocal js2-ts-string ""
700 "Token stream buffer-local variable.
701 Last string scanned.")
702
703 (js2-deflocal js2-ts-number nil
704 "Token stream buffer-local variable.
705 Last literal number scanned.")
706
707 (js2-deflocal js2-ts-hit-eof nil
708 "Token stream buffer-local variable.")
709
710 (js2-deflocal js2-ts-line-start 0
711 "Token stream buffer-local variable.")
712
713 (js2-deflocal js2-ts-lineno 1
714 "Token stream buffer-local variable.")
715
716 (js2-deflocal js2-ts-line-end-char -1
717 "Token stream buffer-local variable.")
718
719 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
720 "Token stream buffer-local variable.
721 Current scan position.")
722
723 (js2-deflocal js2-ts-is-xml-attribute nil
724 "Token stream buffer-local variable.")
725
726 (js2-deflocal js2-ts-xml-is-tag-content nil
727 "Token stream buffer-local variable.")
728
729 (js2-deflocal js2-ts-xml-open-tags-count 0
730 "Token stream buffer-local variable.")
731
732 (js2-deflocal js2-ts-string-buffer nil
733 "Token stream buffer-local variable.
734 List of chars built up while scanning various tokens.")
735
736 (js2-deflocal js2-ts-comment-type nil
737 "Token stream buffer-local variable.")
738
739 ;;; Parser variables
740
741 (js2-deflocal js2-parsed-errors nil
742 "List of errors produced during scanning/parsing.")
743
744 (js2-deflocal js2-parsed-warnings nil
745 "List of warnings produced during scanning/parsing.")
746
747 (js2-deflocal js2-recover-from-parse-errors t
748 "Non-nil to continue parsing after a syntax error.
749
750 In recovery mode, the AST will be built in full, and any error
751 nodes will be flagged with appropriate error information. If
752 this flag is nil, a syntax error will result in an error being
753 signaled.
754
755 The variable is automatically buffer-local, because different
756 modes that use the parser will need different settings.")
757
758 (js2-deflocal js2-parse-hook nil
759 "List of callbacks for receiving parsing progress.")
760
761 (defvar js2-parse-finished-hook nil
762 "List of callbacks to notify when parsing finishes.
763 Not called if parsing was interrupted.")
764
765 (js2-deflocal js2-is-eval-code nil
766 "True if we're evaluating code in a string.
767 If non-nil, the tokenizer will record the token text, and the AST nodes
768 will record their source text. Off by default for IDE modes, since the
769 text is available in the buffer.")
770
771 (defvar js2-parse-ide-mode t
772 "Non-nil if the parser is being used for `js2-mode'.
773 If non-nil, the parser will set text properties for fontification
774 and the syntax table. The value should be nil when using the
775 parser as a frontend to an interpreter or byte compiler.")
776
777 ;;; Parser instance variables (buffer-local vars for js2-parse)
778
779 (defconst js2-clear-ti-mask #xFFFF
780 "Mask to clear token information bits.")
781
782 (defconst js2-ti-after-eol (lsh 1 16)
783 "Flag: first token of the source line.")
784
785 (defconst js2-ti-check-label (lsh 1 17)
786 "Flag: indicates to check for label.")
787
788 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
789
790 (js2-deflocal js2-compiler-generate-debug-info t)
791 (js2-deflocal js2-compiler-use-dynamic-scope nil)
792 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
793 (js2-deflocal js2-compiler-xml-available t)
794 (js2-deflocal js2-compiler-optimization-level 0)
795 (js2-deflocal js2-compiler-generating-source t)
796 (js2-deflocal js2-compiler-strict-mode nil)
797 (js2-deflocal js2-compiler-report-warning-as-error nil)
798 (js2-deflocal js2-compiler-generate-observer-count nil)
799 (js2-deflocal js2-compiler-activation-names nil)
800
801 ;; SKIP: sourceURI
802
803 ;; There's a compileFunction method in Context.java - may need it.
804 (js2-deflocal js2-called-by-compile-function nil
805 "True if `js2-parse' was called by `js2-compile-function'.
806 Will only be used when we finish implementing the interpreter.")
807
808 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
809
810 (js2-deflocal js2-current-flagged-token js2-EOF)
811 (js2-deflocal js2-current-token js2-EOF)
812
813 ;; SKIP: node factory - we're going to just call functions directly,
814 ;; and eventually go to a unified AST format.
815
816 (js2-deflocal js2-nesting-of-function 0)
817
818 (js2-deflocal js2-recorded-identifiers nil
819 "Tracks identifiers found during parsing.")
820
821 (js2-deflocal js2-is-in-destructuring nil
822 "True while parsing destructuring expression.")
823
824 (defcustom js2-global-externs nil
825 "A list of any extern names you'd like to consider always declared.
826 This list is global and is used by all js2-mode files.
827 You can create buffer-local externs list using `js2-additional-externs'.
828
829 There is also a buffer-local variable `js2-default-externs',
830 which is initialized by default to include the Ecma-262 externs
831 and the standard browser externs. The three lists are all
832 checked during highlighting."
833 :type 'list
834 :group 'js2-mode)
835
836 (js2-deflocal js2-default-externs nil
837 "Default external declarations.
838
839 These are currently only used for highlighting undeclared variables,
840 which only worries about top-level (unqualified) references.
841 As js2-mode's processing improves, we will flesh out this list.
842
843 The initial value is set to `js2-ecma-262-externs', unless you
844 have set `js2-include-browser-externs', in which case the browser
845 externs are also included.
846
847 See `js2-additional-externs' for more information.")
848
849 (defcustom js2-include-browser-externs t
850 "Non-nil to include browser externs in the master externs list.
851 If you work on JavaScript files that are not intended for browsers,
852 such as Mozilla Rhino server-side JavaScript, set this to nil.
853 You can always include them on a per-file basis by calling
854 `js2-add-browser-externs' from a function on `js2-mode-hook'.
855
856 See `js2-additional-externs' for more information about externs."
857 :type 'boolean
858 :group 'js2-mode)
859
860 (defcustom js2-include-rhino-externs t
861 "Non-nil to include Mozilla Rhino externs in the master externs list.
862 See `js2-additional-externs' for more information about externs."
863 :type 'boolean
864 :group 'js2-mode)
865
866 (defcustom js2-include-gears-externs t
867 "Non-nil to include Google Gears externs in the master externs list.
868 See `js2-additional-externs' for more information about externs."
869 :type 'boolean
870 :group 'js2-mode)
871
872 (js2-deflocal js2-additional-externs nil
873 "A buffer-local list of additional external declarations.
874 It is used to decide whether variables are considered undeclared
875 for purposes of highlighting.
876
877 Each entry is a lisp string. The string should be the fully qualified
878 name of an external entity. All externs should be added to this list,
879 so that as js2-mode's processing improves it can take advantage of them.
880
881 You may want to declare your externs in three ways.
882 First, you can add externs that are valid for all your JavaScript files.
883 You should probably do this by adding them to `js2-global-externs', which
884 is a global list used for all js2-mode files.
885
886 Next, you can add a function to `js2-mode-hook' that adds additional
887 externs appropriate for the specific file, perhaps based on its path.
888 These should go in `js2-additional-externs', which is buffer-local.
889
890 Finally, you can add a function to `js2-post-parse-callbacks',
891 which is called after parsing completes, and `root' is bound to
892 the root of the parse tree. At this stage you can set up an AST
893 node visitor using `js2-visit-ast' and examine the parse tree
894 for specific import patterns that may imply the existence of
895 other externs, possibly tied to your build system. These should also
896 be added to `js2-additional-externs'.
897
898 Your post-parse callback may of course also use the simpler and
899 faster (but perhaps less robust) approach of simply scanning the
900 buffer text for your imports, using regular expressions.")
901
902 ;; SKIP: decompiler
903 ;; SKIP: encoded-source
904
905 ;;; The following variables are per-function and should be saved/restored
906 ;;; during function parsing...
907
908 (js2-deflocal js2-current-script-or-fn nil)
909 (js2-deflocal js2-current-scope nil)
910 (js2-deflocal js2-nesting-of-with 0)
911 (js2-deflocal js2-label-set nil
912 "An alist mapping label names to nodes.")
913
914 (js2-deflocal js2-loop-set nil)
915 (js2-deflocal js2-loop-and-switch-set nil)
916 (js2-deflocal js2-has-return-value nil)
917 (js2-deflocal js2-end-flags 0)
918
919 ;;; ...end of per function variables
920
921 ;; Without 2-token lookahead, labels are a problem.
922 ;; These vars store the token info of the last matched name,
923 ;; iff it wasn't the last matched token. Only valid in some contexts.
924 (defvar js2-prev-name-token-start nil)
925 (defvar js2-prev-name-token-string nil)
926
927 (defsubst js2-save-name-token-data (pos name)
928 (setq js2-prev-name-token-start pos
929 js2-prev-name-token-string name))
930
931 ;; These flags enumerate the possible ways a statement/function can
932 ;; terminate. These flags are used by endCheck() and by the Parser to
933 ;; detect inconsistent return usage.
934 ;;
935 ;; END_UNREACHED is reserved for code paths that are assumed to always be
936 ;; able to execute (example: throw, continue)
937 ;;
938 ;; END_DROPS_OFF indicates if the statement can transfer control to the
939 ;; next one. Statement such as return dont. A compound statement may have
940 ;; some branch that drops off control to the next statement.
941 ;;
942 ;; END_RETURNS indicates that the statement can return (without arguments)
943 ;; END_RETURNS_VALUE indicates that the statement can return a value.
944 ;;
945 ;; A compound statement such as
946 ;; if (condition) {
947 ;; return value;
948 ;; }
949 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
950
951 (defconst js2-end-unreached #x0)
952 (defconst js2-end-drops-off #x1)
953 (defconst js2-end-returns #x2)
954 (defconst js2-end-returns-value #x4)
955 (defconst js2-end-yields #x8)
956
957 ;; Rhino awkwardly passes a statementLabel parameter to the
958 ;; statementHelper() function, the main statement parser, which
959 ;; is then used by quite a few of the sub-parsers. We just make
960 ;; it a buffer-local variable and make sure it's cleaned up properly.
961 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
962
963 ;; Similarly, Rhino passes an inForInit boolean through about half
964 ;; the expression parsers. We use a dynamically-scoped variable,
965 ;; which makes it easier to funcall the parsers individually without
966 ;; worrying about whether they take the parameter or not.
967 (js2-deflocal js2-in-for-init nil)
968 (js2-deflocal js2-temp-name-counter 0)
969 (js2-deflocal js2-parse-stmt-count 0)
970
971 (defsubst js2-get-next-temp-name ()
972 (format "$%d" (incf js2-temp-name-counter)))
973
974 (defvar js2-parse-interruptable-p t
975 "Set this to nil to force parse to continue until finished.
976 This will mostly be useful for interpreters.")
977
978 (defvar js2-statements-per-pause 50
979 "Pause after this many statements to check for user input.
980 If user input is pending, stop the parse and discard the tree.
981 This makes for a smoother user experience for large files.
982 You may have to wait a second or two before the highlighting
983 and error-reporting appear, but you can always type ahead if
984 you wish. This appears to be more or less how Eclipse, IntelliJ
985 and other editors work.")
986
987 (js2-deflocal js2-record-comments t
988 "Instructs the scanner to record comments in `js2-scanned-comments'.")
989
990 (js2-deflocal js2-scanned-comments nil
991 "List of all comments from the current parse.")
992
993 (defcustom js2-mode-indent-inhibit-undo nil
994 "Non-nil to disable collection of Undo information when indenting lines.
995 Some users have requested this behavior. It's nil by default because
996 other Emacs modes don't work this way."
997 :type 'boolean
998 :group 'js2-mode)
999
1000 (defcustom js2-mode-indent-ignore-first-tab nil
1001 "If non-nil, ignore first TAB keypress if we look indented properly.
1002 It's fairly common for users to navigate to an already-indented line
1003 and press TAB for reassurance that it's been indented. For this class
1004 of users, we want the first TAB press on a line to be ignored if the
1005 line is already indented to one of the precomputed alternatives.
1006
1007 This behavior is only partly implemented. If you TAB-indent a line,
1008 navigate to another line, and then navigate back, it fails to clear
1009 the last-indented variable, so it thinks you've already hit TAB once,
1010 and performs the indent. A full solution would involve getting on the
1011 point-motion hooks for the entire buffer. If we come across another
1012 use cases that requires watching point motion, I'll consider doing it.
1013
1014 If you set this variable to nil, then the TAB key will always change
1015 the indentation of the current line, if more than one alternative
1016 indentation spot exists."
1017 :type 'boolean
1018 :group 'js2-mode)
1019
1020 (defvar js2-indent-hook nil
1021 "A hook for user-defined indentation rules.
1022
1023 Functions on this hook should expect two arguments: (LIST INDEX)
1024 The LIST argument is the list of computed indentation points for
1025 the current line. INDEX is the list index of the indentation point
1026 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1027 indent function is not going to change the current line indentation.
1028
1029 If a hook function on this list returns a non-nil value, then
1030 `js2-bounce-indent' assumes the hook function has performed its own
1031 indentation, and will do nothing. If all hook functions on the list
1032 return nil, then `js2-bounce-indent' will use its computed indentation
1033 and reindent the line.
1034
1035 When hook functions on this hook list are called, the variable
1036 `js2-mode-ast' may or may not be set, depending on whether the
1037 parse tree is available. If the variable is nil, you can pass a
1038 callback to `js2-mode-wait-for-parse', and your callback will be
1039 called after the new parse tree is built. This can take some time
1040 in large files.")
1041
1042 (defface js2-warning-face
1043 `((((class color) (background light))
1044 (:underline "orange"))
1045 (((class color) (background dark))
1046 (:underline "orange"))
1047 (t (:underline t)))
1048 "Face for JavaScript warnings."
1049 :group 'js2-mode)
1050
1051 (defface js2-error-face
1052 `((((class color) (background light))
1053 (:foreground "red"))
1054 (((class color) (background dark))
1055 (:foreground "red"))
1056 (t (:foreground "red")))
1057 "Face for JavaScript errors."
1058 :group 'js2-mode)
1059
1060 (defface js2-jsdoc-tag-face
1061 '((t :foreground "SlateGray"))
1062 "Face used to highlight @whatever tags in jsdoc comments."
1063 :group 'js2-mode)
1064
1065 (defface js2-jsdoc-type-face
1066 '((t :foreground "SteelBlue"))
1067 "Face used to highlight {FooBar} types in jsdoc comments."
1068 :group 'js2-mode)
1069
1070 (defface js2-jsdoc-value-face
1071 '((t :foreground "PeachPuff3"))
1072 "Face used to highlight tag values in jsdoc comments."
1073 :group 'js2-mode)
1074
1075 (defface js2-function-param-face
1076 '((t :foreground "SeaGreen"))
1077 "Face used to highlight function parameters in javascript."
1078 :group 'js2-mode)
1079
1080 (defface js2-instance-member-face
1081 '((t :foreground "DarkOrchid"))
1082 "Face used to highlight instance variables in javascript.
1083 Not currently used."
1084 :group 'js2-mode)
1085
1086 (defface js2-private-member-face
1087 '((t :foreground "PeachPuff3"))
1088 "Face used to highlight calls to private methods in javascript.
1089 Not currently used."
1090 :group 'js2-mode)
1091
1092 (defface js2-private-function-call-face
1093 '((t :foreground "goldenrod"))
1094 "Face used to highlight calls to private functions in javascript.
1095 Not currently used."
1096 :group 'js2-mode)
1097
1098 (defface js2-jsdoc-html-tag-name-face
1099 (if js2-emacs22
1100 '((((class color) (min-colors 88) (background light))
1101 (:foreground "rosybrown"))
1102 (((class color) (min-colors 8) (background dark))
1103 (:foreground "yellow"))
1104 (((class color) (min-colors 8) (background light))
1105 (:foreground "magenta")))
1106 '((((type tty pc) (class color) (background light))
1107 (:foreground "magenta"))
1108 (((type tty pc) (class color) (background dark))
1109 (:foreground "yellow"))
1110 (t (:foreground "RosyBrown"))))
1111 "Face used to highlight jsdoc html tag names"
1112 :group 'js2-mode)
1113
1114 (defface js2-jsdoc-html-tag-delimiter-face
1115 (if js2-emacs22
1116 '((((class color) (min-colors 88) (background light))
1117 (:foreground "dark khaki"))
1118 (((class color) (min-colors 8) (background dark))
1119 (:foreground "green"))
1120 (((class color) (min-colors 8) (background light))
1121 (:foreground "green")))
1122 '((((type tty pc) (class color) (background light))
1123 (:foreground "green"))
1124 (((type tty pc) (class color) (background dark))
1125 (:foreground "green"))
1126 (t (:foreground "dark khaki"))))
1127 "Face used to highlight brackets in jsdoc html tags."
1128 :group 'js2-mode)
1129
1130 (defface js2-magic-paren-face
1131 '((t :underline t))
1132 "Face used to color parens that will be auto-overwritten."
1133 :group 'js2-mode)
1134
1135 (defcustom js2-post-parse-callbacks nil
1136 "A list of callback functions invoked after parsing finishes.
1137 Currently, the main use for this function is to add synthetic
1138 declarations to `js2-recorded-identifiers', which see."
1139 :type 'list
1140 :group 'js2-mode)
1141
1142 (defface js2-external-variable-face
1143 '((t :foreground "orange"))
1144 "Face used to highlight undeclared variable identifiers.
1145 An undeclared variable is any variable not declared with var or let
1146 in the current scope or any lexically enclosing scope. If you use
1147 such a variable, then you are either expecting it to originate from
1148 another file, or you've got a potential bug."
1149 :group 'js2-mode)
1150
1151 (defcustom js2-highlight-external-variables t
1152 "Non-nil to highlight undeclared variable identifiers."
1153 :type 'boolean
1154 :group 'js2-mode)
1155
1156 (defcustom js2-auto-insert-catch-block t
1157 "Non-nil to insert matching catch block on open-curly after `try'."
1158 :type 'boolean
1159 :group 'js2-mode)
1160
1161 (defvar js2-mode-map
1162 (let ((map (make-sparse-keymap))
1163 keys)
1164 (define-key map [mouse-1] #'js2-mode-show-node)
1165 (define-key map (kbd "C-m") #'js2-enter-key)
1166 (when js2-rebind-eol-bol-keys
1167 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1168 (define-key map (kbd "C-e") #'js2-end-of-line))
1169 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1170 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1171 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1172 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1173 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1174 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1175 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1176 (define-key map (kbd "C-c C-`") #'js2-next-error)
1177 ;; also define user's preference for next-error, if available
1178 (if (setq keys (where-is-internal #'next-error))
1179 (define-key map (car keys) #'js2-next-error))
1180 (define-key map (or (car (where-is-internal #'mark-defun))
1181 (kbd "M-C-h"))
1182 #'js2-mark-defun)
1183 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1184 (kbd "C-x nd"))
1185 #'js2-narrow-to-defun)
1186 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1187 (when js2-auto-indent-p
1188 (mapc (lambda (key)
1189 (define-key map key #'js2-insert-and-indent))
1190 js2-electric-keys))
1191 (when js2-bounce-indent-p
1192 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1193
1194 (define-key map [menu-bar javascript]
1195 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1196
1197 (define-key map [menu-bar javascript customize-js2-mode]
1198 '(menu-item "Customize js2-mode" js2-mode-customize
1199 :help "Customize the behavior of this mode"))
1200
1201 (define-key map [menu-bar javascript js2-force-refresh]
1202 '(menu-item "Force buffer refresh" js2-mode-reset
1203 :help "Re-parse the buffer from scratch"))
1204
1205 (define-key map [menu-bar javascript separator-2]
1206 '("--"))
1207
1208 (define-key map [menu-bar javascript next-error]
1209 '(menu-item "Next warning or error" js2-next-error
1210 :enabled (and js2-mode-ast
1211 (or (js2-ast-root-errors js2-mode-ast)
1212 (js2-ast-root-warnings js2-mode-ast)))
1213 :help "Move to next warning or error"))
1214
1215 (define-key map [menu-bar javascript display-errors]
1216 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1217 :visible (not js2-mode-show-parse-errors)
1218 :help "Turn on display of warnings and errors"))
1219
1220 (define-key map [menu-bar javascript hide-errors]
1221 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1222 :visible js2-mode-show-parse-errors
1223 :help "Turn off display of warnings and errors"))
1224
1225 (define-key map [menu-bar javascript separator-1]
1226 '("--"))
1227
1228 (define-key map [menu-bar javascript js2-toggle-function]
1229 '(menu-item "Show/collapse element" js2-mode-toggle-element
1230 :help "Hide or show function body or comment"))
1231
1232 (define-key map [menu-bar javascript show-comments]
1233 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1234 :visible js2-mode-comments-hidden
1235 :help "Expand all hidden block comments"))
1236
1237 (define-key map [menu-bar javascript hide-comments]
1238 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1239 :visible (not js2-mode-comments-hidden)
1240 :help "Show block comments as /*...*/"))
1241
1242 (define-key map [menu-bar javascript show-all-functions]
1243 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1244 :visible js2-mode-functions-hidden
1245 :help "Expand all hidden function bodies"))
1246
1247 (define-key map [menu-bar javascript hide-all-functions]
1248 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1249 :visible (not js2-mode-functions-hidden)
1250 :help "Show {...} for all top-level function bodies"))
1251
1252 map)
1253 "Keymap used in `js2-mode' buffers.")
1254
1255 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1256
1257 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1258 "Matches a //-comment line. Must be first non-whitespace on line.
1259 First match-group is the leading whitespace.")
1260
1261 (defvar js2-mode-hook nil)
1262
1263 (js2-deflocal js2-mode-ast nil "Private variable.")
1264 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1265 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1266 (js2-deflocal js2-mode-parsing nil "Private variable.")
1267 (js2-deflocal js2-mode-node-overlay nil)
1268
1269 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1270 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1271
1272 (js2-deflocal js2-mode-fontifications nil "Private variable")
1273 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1274 (js2-deflocal js2-imenu-recorder nil "Private variable")
1275 (js2-deflocal js2-imenu-function-map nil "Private variable")
1276
1277 (defvar js2-paragraph-start
1278 "\\(@[a-zA-Z]+\\>\\|$\\)")
1279
1280 ;; Note that we also set a 'c-in-sws text property in html comments,
1281 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1282 (defvar js2-syntactic-ws-start
1283 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1284
1285 (defvar js2-syntactic-ws-end
1286 "\\s \\|[\n\r/]\\|\\s!")
1287
1288 (defvar js2-syntactic-eol
1289 (concat "\\s *\\(/\\*[^*\n\r]*"
1290 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1291 "\\*+/\\s *\\)*"
1292 "\\(//\\|/\\*[^*\n\r]*"
1293 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1294 "\\|\\\\$\\|$\\)")
1295 "Copied from `java-mode'. Needed for some cc-engine functions.")
1296
1297 (defvar js2-comment-prefix-regexp
1298 "//+\\|\\**")
1299
1300 (defvar js2-comment-start-skip
1301 "\\(//+\\|/\\*+\\)\\s *")
1302
1303 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1304 "Non-nil to emit status messages during parsing.")
1305
1306 (defvar js2-mode-functions-hidden nil "private variable")
1307 (defvar js2-mode-comments-hidden nil "private variable")
1308
1309 (defvar js2-mode-syntax-table
1310 (let ((table (make-syntax-table)))
1311 (c-populate-syntax-table table)
1312 table)
1313 "Syntax table used in js2-mode buffers.")
1314
1315 (defvar js2-mode-abbrev-table nil
1316 "Abbrev table in use in `js2-mode' buffers.")
1317 (define-abbrev-table 'js2-mode-abbrev-table ())
1318
1319 (defvar js2-mode-pending-parse-callbacks nil
1320 "List of functions waiting to be notified that parse is finished.")
1321
1322 (defvar js2-mode-last-indented-line -1)
1323
1324 ;;; Localizable error and warning messages
1325
1326 ;; Messages are copied from Rhino's Messages.properties.
1327 ;; Many of the Java-specific messages have been elided.
1328 ;; Add any js2-specific ones at the end, so we can keep
1329 ;; this file synced with changes to Rhino's.
1330
1331 (defvar js2-message-table
1332 (make-hash-table :test 'equal :size 250)
1333 "Contains localized messages for js2-mode.")
1334
1335 ;; TODO(stevey): construct this table at compile-time.
1336 (defmacro js2-msg (key &rest strings)
1337 `(puthash ,key (funcall #'concat ,@strings)
1338 js2-message-table))
1339
1340 (defun js2-get-msg (msg-key)
1341 "Look up a localized message.
1342 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1343 the correct number of ARGS must be provided."
1344 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1345 (args (if (listp msg-key) (cdr msg-key)))
1346 (msg (gethash key js2-message-table)))
1347 (if msg
1348 (apply #'format msg args)
1349 key))) ; default to showing the key
1350
1351 (js2-msg "msg.dup.parms"
1352 "Duplicate parameter name '%s'.")
1353
1354 (js2-msg "msg.too.big.jump"
1355 "Program too complex: jump offset too big.")
1356
1357 (js2-msg "msg.too.big.index"
1358 "Program too complex: internal index exceeds 64K limit.")
1359
1360 (js2-msg "msg.while.compiling.fn"
1361 "Encountered code generation error while compiling function '%s': %s")
1362
1363 (js2-msg "msg.while.compiling.script"
1364 "Encountered code generation error while compiling script: %s")
1365
1366 ;; Context
1367 (js2-msg "msg.ctor.not.found"
1368 "Constructor for '%s' not found.")
1369
1370 (js2-msg "msg.not.ctor"
1371 "'%s' is not a constructor.")
1372
1373 ;; FunctionObject
1374 (js2-msg "msg.varargs.ctor"
1375 "Method or constructor '%s' must be static "
1376 "with the signature (Context cx, Object[] args, "
1377 "Function ctorObj, boolean inNewExpr) "
1378 "to define a variable arguments constructor.")
1379
1380 (js2-msg "msg.varargs.fun"
1381 "Method '%s' must be static with the signature "
1382 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1383 "to define a variable arguments function.")
1384
1385 (js2-msg "msg.incompat.call"
1386 "Method '%s' called on incompatible object.")
1387
1388 (js2-msg "msg.bad.parms"
1389 "Unsupported parameter type '%s' in method '%s'.")
1390
1391 (js2-msg "msg.bad.method.return"
1392 "Unsupported return type '%s' in method '%s'.")
1393
1394 (js2-msg "msg.bad.ctor.return"
1395 "Construction of objects of type '%s' is not supported.")
1396
1397 (js2-msg "msg.no.overload"
1398 "Method '%s' occurs multiple times in class '%s'.")
1399
1400 (js2-msg "msg.method.not.found"
1401 "Method '%s' not found in '%s'.")
1402
1403 ;; IRFactory
1404
1405 (js2-msg "msg.bad.for.in.lhs"
1406 "Invalid left-hand side of for..in loop.")
1407
1408 (js2-msg "msg.mult.index"
1409 "Only one variable allowed in for..in loop.")
1410
1411 (js2-msg "msg.bad.for.in.destruct"
1412 "Left hand side of for..in loop must be an array of "
1413 "length 2 to accept key/value pair.")
1414
1415 (js2-msg "msg.cant.convert"
1416 "Can't convert to type '%s'.")
1417
1418 (js2-msg "msg.bad.assign.left"
1419 "Invalid assignment left-hand side.")
1420
1421 (js2-msg "msg.bad.decr"
1422 "Invalid decerement operand.")
1423
1424 (js2-msg "msg.bad.incr"
1425 "Invalid increment operand.")
1426
1427 (js2-msg "msg.bad.yield"
1428 "yield must be in a function.")
1429
1430 (js2-msg "msg.yield.parenthesized"
1431 "yield expression must be parenthesized.")
1432
1433 ;; NativeGlobal
1434 (js2-msg "msg.cant.call.indirect"
1435 "Function '%s' must be called directly, and not by way of a "
1436 "function of another name.")
1437
1438 (js2-msg "msg.eval.nonstring"
1439 "Calling eval() with anything other than a primitive "
1440 "string value will simply return the value. "
1441 "Is this what you intended?")
1442
1443 (js2-msg "msg.eval.nonstring.strict"
1444 "Calling eval() with anything other than a primitive "
1445 "string value is not allowed in strict mode.")
1446
1447 (js2-msg "msg.bad.destruct.op"
1448 "Invalid destructuring assignment operator")
1449
1450 ;; NativeCall
1451 (js2-msg "msg.only.from.new"
1452 "'%s' may only be invoked from a `new' expression.")
1453
1454 (js2-msg "msg.deprec.ctor"
1455 "The '%s' constructor is deprecated.")
1456
1457 ;; NativeFunction
1458 (js2-msg "msg.no.function.ref.found"
1459 "no source found to decompile function reference %s")
1460
1461 (js2-msg "msg.arg.isnt.array"
1462 "second argument to Function.prototype.apply must be an array")
1463
1464 ;; NativeGlobal
1465 (js2-msg "msg.bad.esc.mask"
1466 "invalid string escape mask")
1467
1468 ;; NativeRegExp
1469 (js2-msg "msg.bad.quant"
1470 "Invalid quantifier %s")
1471
1472 (js2-msg "msg.overlarge.backref"
1473 "Overly large back reference %s")
1474
1475 (js2-msg "msg.overlarge.min"
1476 "Overly large minimum %s")
1477
1478 (js2-msg "msg.overlarge.max"
1479 "Overly large maximum %s")
1480
1481 (js2-msg "msg.zero.quant"
1482 "Zero quantifier %s")
1483
1484 (js2-msg "msg.max.lt.min"
1485 "Maximum %s less than minimum")
1486
1487 (js2-msg "msg.unterm.quant"
1488 "Unterminated quantifier %s")
1489
1490 (js2-msg "msg.unterm.paren"
1491 "Unterminated parenthetical %s")
1492
1493 (js2-msg "msg.unterm.class"
1494 "Unterminated character class %s")
1495
1496 (js2-msg "msg.bad.range"
1497 "Invalid range in character class.")
1498
1499 (js2-msg "msg.trail.backslash"
1500 "Trailing \\ in regular expression.")
1501
1502 (js2-msg "msg.re.unmatched.right.paren"
1503 "unmatched ) in regular expression.")
1504
1505 (js2-msg "msg.no.regexp"
1506 "Regular expressions are not available.")
1507
1508 (js2-msg "msg.bad.backref"
1509 "back-reference exceeds number of capturing parentheses.")
1510
1511 (js2-msg "msg.bad.regexp.compile"
1512 "Only one argument may be specified if the first "
1513 "argument to RegExp.prototype.compile is a RegExp object.")
1514
1515 ;; Parser
1516 (js2-msg "msg.got.syntax.errors"
1517 "Compilation produced %s syntax errors.")
1518
1519 (js2-msg "msg.var.redecl"
1520 "TypeError: redeclaration of var %s.")
1521
1522 (js2-msg "msg.const.redecl"
1523 "TypeError: redeclaration of const %s.")
1524
1525 (js2-msg "msg.let.redecl"
1526 "TypeError: redeclaration of variable %s.")
1527
1528 (js2-msg "msg.parm.redecl"
1529 "TypeError: redeclaration of formal parameter %s.")
1530
1531 (js2-msg "msg.fn.redecl"
1532 "TypeError: redeclaration of function %s.")
1533
1534 (js2-msg "msg.let.decl.not.in.block"
1535 "SyntaxError: let declaration not directly within block")
1536
1537 ;; NodeTransformer
1538 (js2-msg "msg.dup.label"
1539 "duplicated label")
1540
1541 (js2-msg "msg.undef.label"
1542 "undefined label")
1543
1544 (js2-msg "msg.bad.break"
1545 "unlabelled break must be inside loop or switch")
1546
1547 (js2-msg "msg.continue.outside"
1548 "continue must be inside loop")
1549
1550 (js2-msg "msg.continue.nonloop"
1551 "continue can only use labels of iteration statements")
1552
1553 (js2-msg "msg.bad.throw.eol"
1554 "Line terminator is not allowed between the throw "
1555 "keyword and throw expression.")
1556
1557 (js2-msg "msg.no.paren.parms"
1558 "missing ( before function parameters.")
1559
1560 (js2-msg "msg.no.parm"
1561 "missing formal parameter")
1562
1563 (js2-msg "msg.no.paren.after.parms"
1564 "missing ) after formal parameters")
1565
1566 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1567 "parameter without default follows parameter with default")
1568
1569 (js2-msg "msg.param.after.rest" ; added by js2-mode
1570 "parameter after rest parameter")
1571
1572 (js2-msg "msg.no.brace.body"
1573 "missing '{' before function body")
1574
1575 (js2-msg "msg.no.brace.after.body"
1576 "missing } after function body")
1577
1578 (js2-msg "msg.no.paren.cond"
1579 "missing ( before condition")
1580
1581 (js2-msg "msg.no.paren.after.cond"
1582 "missing ) after condition")
1583
1584 (js2-msg "msg.no.semi.stmt"
1585 "missing ; before statement")
1586
1587 (js2-msg "msg.missing.semi"
1588 "missing ; after statement")
1589
1590 (js2-msg "msg.no.name.after.dot"
1591 "missing name after . operator")
1592
1593 (js2-msg "msg.no.name.after.coloncolon"
1594 "missing name after :: operator")
1595
1596 (js2-msg "msg.no.name.after.dotdot"
1597 "missing name after .. operator")
1598
1599 (js2-msg "msg.no.name.after.xmlAttr"
1600 "missing name after .@")
1601
1602 (js2-msg "msg.no.bracket.index"
1603 "missing ] in index expression")
1604
1605 (js2-msg "msg.no.paren.switch"
1606 "missing ( before switch expression")
1607
1608 (js2-msg "msg.no.paren.after.switch"
1609 "missing ) after switch expression")
1610
1611 (js2-msg "msg.no.brace.switch"
1612 "missing '{' before switch body")
1613
1614 (js2-msg "msg.bad.switch"
1615 "invalid switch statement")
1616
1617 (js2-msg "msg.no.colon.case"
1618 "missing : after case expression")
1619
1620 (js2-msg "msg.double.switch.default"
1621 "double default label in the switch statement")
1622
1623 (js2-msg "msg.no.while.do"
1624 "missing while after do-loop body")
1625
1626 (js2-msg "msg.no.paren.for"
1627 "missing ( after for")
1628
1629 (js2-msg "msg.no.semi.for"
1630 "missing ; after for-loop initializer")
1631
1632 (js2-msg "msg.no.semi.for.cond"
1633 "missing ; after for-loop condition")
1634
1635 (js2-msg "msg.in.after.for.name"
1636 "missing in or of after for")
1637
1638 (js2-msg "msg.no.paren.for.ctrl"
1639 "missing ) after for-loop control")
1640
1641 (js2-msg "msg.no.paren.with"
1642 "missing ( before with-statement object")
1643
1644 (js2-msg "msg.no.paren.after.with"
1645 "missing ) after with-statement object")
1646
1647 (js2-msg "msg.no.paren.after.let"
1648 "missing ( after let")
1649
1650 (js2-msg "msg.no.paren.let"
1651 "missing ) after variable list")
1652
1653 (js2-msg "msg.no.curly.let"
1654 "missing } after let statement")
1655
1656 (js2-msg "msg.bad.return"
1657 "invalid return")
1658
1659 (js2-msg "msg.no.brace.block"
1660 "missing } in compound statement")
1661
1662 (js2-msg "msg.bad.label"
1663 "invalid label")
1664
1665 (js2-msg "msg.bad.var"
1666 "missing variable name")
1667
1668 (js2-msg "msg.bad.var.init"
1669 "invalid variable initialization")
1670
1671 (js2-msg "msg.no.colon.cond"
1672 "missing : in conditional expression")
1673
1674 (js2-msg "msg.no.paren.arg"
1675 "missing ) after argument list")
1676
1677 (js2-msg "msg.no.bracket.arg"
1678 "missing ] after element list")
1679
1680 (js2-msg "msg.bad.prop"
1681 "invalid property id")
1682
1683 (js2-msg "msg.no.colon.prop"
1684 "missing : after property id")
1685
1686 (js2-msg "msg.no.brace.prop"
1687 "missing } after property list")
1688
1689 (js2-msg "msg.no.paren"
1690 "missing ) in parenthetical")
1691
1692 (js2-msg "msg.reserved.id"
1693 "identifier is a reserved word")
1694
1695 (js2-msg "msg.no.paren.catch"
1696 "missing ( before catch-block condition")
1697
1698 (js2-msg "msg.bad.catchcond"
1699 "invalid catch block condition")
1700
1701 (js2-msg "msg.catch.unreachable"
1702 "any catch clauses following an unqualified catch are unreachable")
1703
1704 (js2-msg "msg.no.brace.try"
1705 "missing '{' before try block")
1706
1707 (js2-msg "msg.no.brace.catchblock"
1708 "missing '{' before catch-block body")
1709
1710 (js2-msg "msg.try.no.catchfinally"
1711 "'try' without 'catch' or 'finally'")
1712
1713 (js2-msg "msg.no.return.value"
1714 "function %s does not always return a value")
1715
1716 (js2-msg "msg.anon.no.return.value"
1717 "anonymous function does not always return a value")
1718
1719 (js2-msg "msg.return.inconsistent"
1720 "return statement is inconsistent with previous usage")
1721
1722 (js2-msg "msg.generator.returns"
1723 "TypeError: generator function '%s' returns a value")
1724
1725 (js2-msg "msg.anon.generator.returns"
1726 "TypeError: anonymous generator function returns a value")
1727
1728 (js2-msg "msg.syntax"
1729 "syntax error")
1730
1731 (js2-msg "msg.unexpected.eof"
1732 "Unexpected end of file")
1733
1734 (js2-msg "msg.XML.bad.form"
1735 "illegally formed XML syntax")
1736
1737 (js2-msg "msg.XML.not.available"
1738 "XML runtime not available")
1739
1740 (js2-msg "msg.too.deep.parser.recursion"
1741 "Too deep recursion while parsing")
1742
1743 (js2-msg "msg.no.side.effects"
1744 "Code has no side effects")
1745
1746 (js2-msg "msg.extra.trailing.comma"
1747 "Trailing comma is not legal in an ECMA-262 object initializer")
1748
1749 (js2-msg "msg.array.trailing.comma"
1750 "Trailing comma yields different behavior across browsers")
1751
1752 (js2-msg "msg.equal.as.assign"
1753 (concat "Test for equality (==) mistyped as assignment (=)?"
1754 " (parenthesize to suppress warning)"))
1755
1756 (js2-msg "msg.var.hides.arg"
1757 "Variable %s hides argument")
1758
1759 (js2-msg "msg.destruct.assign.no.init"
1760 "Missing = in destructuring declaration")
1761
1762 ;; ScriptRuntime
1763 (js2-msg "msg.no.properties"
1764 "%s has no properties.")
1765
1766 (js2-msg "msg.invalid.iterator"
1767 "Invalid iterator value")
1768
1769 (js2-msg "msg.iterator.primitive"
1770 "__iterator__ returned a primitive value")
1771
1772 (js2-msg "msg.assn.create.strict"
1773 "Assignment to undeclared variable %s")
1774
1775 (js2-msg "msg.ref.undefined.prop"
1776 "Reference to undefined property '%s'")
1777
1778 (js2-msg "msg.prop.not.found"
1779 "Property %s not found.")
1780
1781 (js2-msg "msg.invalid.type"
1782 "Invalid JavaScript value of type %s")
1783
1784 (js2-msg "msg.primitive.expected"
1785 "Primitive type expected (had %s instead)")
1786
1787 (js2-msg "msg.namespace.expected"
1788 "Namespace object expected to left of :: (found %s instead)")
1789
1790 (js2-msg "msg.null.to.object"
1791 "Cannot convert null to an object.")
1792
1793 (js2-msg "msg.undef.to.object"
1794 "Cannot convert undefined to an object.")
1795
1796 (js2-msg "msg.cyclic.value"
1797 "Cyclic %s value not allowed.")
1798
1799 (js2-msg "msg.is.not.defined"
1800 "'%s' is not defined.")
1801
1802 (js2-msg "msg.undef.prop.read"
1803 "Cannot read property '%s' from %s")
1804
1805 (js2-msg "msg.undef.prop.write"
1806 "Cannot set property '%s' of %s to '%s'")
1807
1808 (js2-msg "msg.undef.prop.delete"
1809 "Cannot delete property '%s' of %s")
1810
1811 (js2-msg "msg.undef.method.call"
1812 "Cannot call method '%s' of %s")
1813
1814 (js2-msg "msg.undef.with"
1815 "Cannot apply 'with' to %s")
1816
1817 (js2-msg "msg.isnt.function"
1818 "%s is not a function, it is %s.")
1819
1820 (js2-msg "msg.isnt.function.in"
1821 "Cannot call property %s in object %s. "
1822 "It is not a function, it is '%s'.")
1823
1824 (js2-msg "msg.function.not.found"
1825 "Cannot find function %s.")
1826
1827 (js2-msg "msg.function.not.found.in"
1828 "Cannot find function %s in object %s.")
1829
1830 (js2-msg "msg.isnt.xml.object"
1831 "%s is not an xml object.")
1832
1833 (js2-msg "msg.no.ref.to.get"
1834 "%s is not a reference to read reference value.")
1835
1836 (js2-msg "msg.no.ref.to.set"
1837 "%s is not a reference to set reference value to %s.")
1838
1839 (js2-msg "msg.no.ref.from.function"
1840 "Function %s can not be used as the left-hand "
1841 "side of assignment or as an operand of ++ or -- operator.")
1842
1843 (js2-msg "msg.bad.default.value"
1844 "Object's getDefaultValue() method returned an object.")
1845
1846 (js2-msg "msg.instanceof.not.object"
1847 "Can't use instanceof on a non-object.")
1848
1849 (js2-msg "msg.instanceof.bad.prototype"
1850 "'prototype' property of %s is not an object.")
1851
1852 (js2-msg "msg.bad.radix"
1853 "illegal radix %s.")
1854
1855 ;; ScriptableObject
1856 (js2-msg "msg.default.value"
1857 "Cannot find default value for object.")
1858
1859 (js2-msg "msg.zero.arg.ctor"
1860 "Cannot load class '%s' which has no zero-parameter constructor.")
1861
1862 (js2-msg "msg.ctor.multiple.parms"
1863 "Can't define constructor or class %s since more than "
1864 "one constructor has multiple parameters.")
1865
1866 (js2-msg "msg.extend.scriptable"
1867 "%s must extend ScriptableObject in order to define property %s.")
1868
1869 (js2-msg "msg.bad.getter.parms"
1870 "In order to define a property, getter %s must have zero "
1871 "parameters or a single ScriptableObject parameter.")
1872
1873 (js2-msg "msg.obj.getter.parms"
1874 "Expected static or delegated getter %s to take "
1875 "a ScriptableObject parameter.")
1876
1877 (js2-msg "msg.getter.static"
1878 "Getter and setter must both be static or neither be static.")
1879
1880 (js2-msg "msg.setter.return"
1881 "Setter must have void return type: %s")
1882
1883 (js2-msg "msg.setter2.parms"
1884 "Two-parameter setter must take a ScriptableObject as "
1885 "its first parameter.")
1886
1887 (js2-msg "msg.setter1.parms"
1888 "Expected single parameter setter for %s")
1889
1890 (js2-msg "msg.setter2.expected"
1891 "Expected static or delegated setter %s to take two parameters.")
1892
1893 (js2-msg "msg.setter.parms"
1894 "Expected either one or two parameters for setter.")
1895
1896 (js2-msg "msg.setter.bad.type"
1897 "Unsupported parameter type '%s' in setter '%s'.")
1898
1899 (js2-msg "msg.add.sealed"
1900 "Cannot add a property to a sealed object: %s.")
1901
1902 (js2-msg "msg.remove.sealed"
1903 "Cannot remove a property from a sealed object: %s.")
1904
1905 (js2-msg "msg.modify.sealed"
1906 "Cannot modify a property of a sealed object: %s.")
1907
1908 (js2-msg "msg.modify.readonly"
1909 "Cannot modify readonly property: %s.")
1910
1911 ;; TokenStream
1912 (js2-msg "msg.missing.exponent"
1913 "missing exponent")
1914
1915 (js2-msg "msg.caught.nfe"
1916 "number format error")
1917
1918 (js2-msg "msg.unterminated.string.lit"
1919 "unterminated string literal")
1920
1921 (js2-msg "msg.unterminated.comment"
1922 "unterminated comment")
1923
1924 (js2-msg "msg.unterminated.re.lit"
1925 "unterminated regular expression literal")
1926
1927 (js2-msg "msg.invalid.re.flag"
1928 "invalid flag after regular expression")
1929
1930 (js2-msg "msg.no.re.input.for"
1931 "no input for %s")
1932
1933 (js2-msg "msg.illegal.character"
1934 "illegal character")
1935
1936 (js2-msg "msg.invalid.escape"
1937 "invalid Unicode escape sequence")
1938
1939 (js2-msg "msg.bad.namespace"
1940 "not a valid default namespace statement. "
1941 "Syntax is: default xml namespace = EXPRESSION;")
1942
1943 ;; TokensStream warnings
1944 (js2-msg "msg.bad.octal.literal"
1945 "illegal octal literal digit %s; "
1946 "interpreting it as a decimal digit")
1947
1948 (js2-msg "msg.reserved.keyword"
1949 "illegal usage of future reserved keyword %s; "
1950 "interpreting it as ordinary identifier")
1951
1952 (js2-msg "msg.script.is.not.constructor"
1953 "Script objects are not constructors.")
1954
1955 ;; Arrays
1956 (js2-msg "msg.arraylength.bad"
1957 "Inappropriate array length.")
1958
1959 ;; Arrays
1960 (js2-msg "msg.arraylength.too.big"
1961 "Array length %s exceeds supported capacity limit.")
1962
1963 ;; URI
1964 (js2-msg "msg.bad.uri"
1965 "Malformed URI sequence.")
1966
1967 ;; Number
1968 (js2-msg "msg.bad.precision"
1969 "Precision %s out of range.")
1970
1971 ;; NativeGenerator
1972 (js2-msg "msg.send.newborn"
1973 "Attempt to send value to newborn generator")
1974
1975 (js2-msg "msg.already.exec.gen"
1976 "Already executing generator")
1977
1978 (js2-msg "msg.StopIteration.invalid"
1979 "StopIteration may not be changed to an arbitrary object.")
1980
1981 ;; Interpreter
1982 (js2-msg "msg.yield.closing"
1983 "Yield from closing generator")
1984
1985 ;;; Utilities
1986
1987 (defun js2-delete-if (predicate list)
1988 "Remove all items satisfying PREDICATE in LIST."
1989 (loop for item in list
1990 if (not (funcall predicate item))
1991 collect item))
1992
1993 (defun js2-position (element list)
1994 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1995 Returns nil if element is not found in the list."
1996 (let ((count 0)
1997 found)
1998 (while (and list (not found))
1999 (if (eq element (car list))
2000 (setq found t)
2001 (setq count (1+ count)
2002 list (cdr list))))
2003 (if found count)))
2004
2005 (defun js2-find-if (predicate list)
2006 "Find first item satisfying PREDICATE in LIST."
2007 (let (result)
2008 (while (and list (not result))
2009 (if (funcall predicate (car list))
2010 (setq result (car list)))
2011 (setq list (cdr list)))
2012 result))
2013
2014 (defmacro js2-time (form)
2015 "Evaluate FORM, discard result, and return elapsed time in sec"
2016 (declare (debug t))
2017 (let ((beg (make-symbol "--js2-time-beg--"))
2018 (delta (make-symbol "--js2-time-end--")))
2019 `(let ((,beg (current-time))
2020 ,delta)
2021 ,form
2022 (/ (truncate (* (- (float-time (current-time))
2023 (float-time ,beg))
2024 10000))
2025 10000.0))))
2026
2027 (defsubst js2-same-line (pos)
2028 "Return t if POS is on the same line as current point."
2029 (and (>= pos (point-at-bol))
2030 (<= pos (point-at-eol))))
2031
2032 (defsubst js2-same-line-2 (p1 p2)
2033 "Return t if p1 is on the same line as p2."
2034 (save-excursion
2035 (goto-char p1)
2036 (js2-same-line p2)))
2037
2038 (defun js2-code-bug ()
2039 "Signal an error when we encounter an unexpected code path."
2040 (error "failed assertion"))
2041
2042 (defsubst js2-record-text-property (beg end prop value)
2043 "Record a text property to set when parsing finishes."
2044 (push (list beg end prop value) js2-mode-deferred-properties))
2045
2046 ;; I'd like to associate errors with nodes, but for now the
2047 ;; easiest thing to do is get the context info from the last token.
2048 (defsubst js2-record-parse-error (msg &optional arg pos len)
2049 (push (list (list msg arg)
2050 (or pos js2-token-beg)
2051 (or len (- js2-token-end js2-token-beg)))
2052 js2-parsed-errors))
2053
2054 (defsubst js2-report-error (msg &optional msg-arg pos len)
2055 "Signal a syntax error or record a parse error."
2056 (if js2-recover-from-parse-errors
2057 (js2-record-parse-error msg msg-arg pos len)
2058 (signal 'js2-syntax-error
2059 (list msg
2060 js2-ts-lineno
2061 (save-excursion
2062 (goto-char js2-ts-cursor)
2063 (current-column))
2064 js2-ts-hit-eof))))
2065
2066 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2067 (if js2-compiler-report-warning-as-error
2068 (js2-report-error msg msg-arg pos len)
2069 (push (list (list msg msg-arg)
2070 (or pos js2-token-beg)
2071 (or len (- js2-token-end js2-token-beg)))
2072 js2-parsed-warnings)))
2073
2074 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2075 (if js2-compiler-strict-mode
2076 (js2-report-warning msg-id msg-arg beg
2077 (and beg end (- end beg)))))
2078
2079 (put 'js2-syntax-error 'error-conditions
2080 '(error syntax-error js2-syntax-error))
2081 (put 'js2-syntax-error 'error-message "Syntax error")
2082
2083 (put 'js2-parse-error 'error-conditions
2084 '(error parse-error js2-parse-error))
2085 (put 'js2-parse-error 'error-message "Parse error")
2086
2087 (defmacro js2-clear-flag (flags flag)
2088 `(setq ,flags (logand ,flags (lognot ,flag))))
2089
2090 (defmacro js2-set-flag (flags flag)
2091 "Logical-or FLAG into FLAGS."
2092 `(setq ,flags (logior ,flags ,flag)))
2093
2094 (defsubst js2-flag-set-p (flags flag)
2095 (/= 0 (logand flags flag)))
2096
2097 (defsubst js2-flag-not-set-p (flags flag)
2098 (zerop (logand flags flag)))
2099
2100 ;; Stolen shamelessly from James Clark's nxml-mode.
2101 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2102 "Evaluate BODY without any text property changes modifying the buffer.
2103 Any text properties changes happen as usual but the changes are not treated as
2104 modifications to the buffer."
2105 (declare (indent 0) (debug t))
2106 (let ((modified (make-symbol "modified")))
2107 `(let ((,modified (buffer-modified-p))
2108 (inhibit-read-only t)
2109 (inhibit-modification-hooks t)
2110 (buffer-undo-list t)
2111 (deactivate-mark nil)
2112 ;; Apparently these avoid file locking problems.
2113 (buffer-file-name nil)
2114 (buffer-file-truename nil))
2115 (unwind-protect
2116 (progn ,@body)
2117 (unless ,modified
2118 (restore-buffer-modified-p nil))))))
2119
2120 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2121 "Evaluate BODY with the _ character set to be word-syntax."
2122 (declare (indent 0) (debug t))
2123 (let ((old-syntax (make-symbol "old-syntax")))
2124 `(let ((,old-syntax (string (char-syntax ?_))))
2125 (unwind-protect
2126 (progn
2127 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2128 ,@body)
2129 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2130
2131 (defsubst js2-char-uppercase-p (c)
2132 "Return t if C is an uppercase character.
2133 Handles unicode and latin chars properly."
2134 (/= c (downcase c)))
2135
2136 (defsubst js2-char-lowercase-p (c)
2137 "Return t if C is an uppercase character.
2138 Handles unicode and latin chars properly."
2139 (/= c (upcase c)))
2140
2141 ;;; AST struct and function definitions
2142
2143 ;; flags for ast node property 'member-type (used for e4x operators)
2144 (defvar js2-property-flag #x1 "property access: element is valid name")
2145 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2146 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2147
2148 (defsubst js2-relpos (pos anchor)
2149 "Convert POS to be relative to ANCHOR.
2150 If POS is nil, returns nil."
2151 (and pos (- pos anchor)))
2152
2153 (defsubst js2-make-pad (indent)
2154 (if (zerop indent)
2155 ""
2156 (make-string (* indent js2-basic-offset) ? )))
2157
2158 (defsubst js2-visit-ast (node callback)
2159 "Visit every node in ast NODE with visitor CALLBACK.
2160
2161 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2162 called twice: once to visit the node, and again after all the node's
2163 children have been processed. The END-P argument is nil on the first
2164 call and non-nil on the second call. The return value of the callback
2165 affects the traversal: if non-nil, the children of NODE are processed.
2166 If the callback returns nil, or if the node has no children, then the
2167 callback is called immediately with a non-nil END-P argument.
2168
2169 The node traversal is approximately lexical-order, although there
2170 are currently no guarantees around this."
2171 (if node
2172 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2173 ;; visit the node
2174 (when (funcall callback node nil)
2175 ;; visit the kids
2176 (cond
2177 ((eq vfunc 'js2-visit-none)
2178 nil) ; don't even bother calling it
2179 ;; Each AST node type has to define a `js2-visitor' function
2180 ;; that takes a node and a callback, and calls `js2-visit-ast'
2181 ;; on each child of the node.
2182 (vfunc
2183 (funcall vfunc node callback))
2184 (t
2185 (error "%s does not define a visitor-traversal function"
2186 (aref node 0)))))
2187 ;; call the end-visit
2188 (funcall callback node t))))
2189
2190 (defstruct (js2-node
2191 (:constructor nil)) ; abstract
2192 "Base AST node type."
2193 (type -1) ; token type
2194 (pos -1) ; start position of this AST node in parsed input
2195 (len 1) ; num characters spanned by the node
2196 props ; optional node property list (an alist)
2197 parent) ; link to parent node; null for root
2198
2199 (defsubst js2-node-get-prop (node prop &optional default)
2200 (or (cadr (assoc prop (js2-node-props node))) default))
2201
2202 (defsubst js2-node-set-prop (node prop value)
2203 (setf (js2-node-props node)
2204 (cons (list prop value) (js2-node-props node))))
2205
2206 (defsubst js2-fixup-starts (n nodes)
2207 "Adjust the start positions of NODES to be relative to N.
2208 Any node in the list may be nil, for convenience."
2209 (dolist (node nodes)
2210 (when node
2211 (setf (js2-node-pos node) (- (js2-node-pos node)
2212 (js2-node-pos n))))))
2213
2214 (defsubst js2-node-add-children (parent &rest nodes)
2215 "Set parent node of NODES to PARENT, and return PARENT.
2216 Does nothing if we're not recording parent links.
2217 If any given node in NODES is nil, doesn't record that link."
2218 (js2-fixup-starts parent nodes)
2219 (dolist (node nodes)
2220 (and node
2221 (setf (js2-node-parent node) parent))))
2222
2223 ;; Non-recursive since it's called a frightening number of times.
2224 (defsubst js2-node-abs-pos (n)
2225 (let ((pos (js2-node-pos n)))
2226 (while (setq n (js2-node-parent n))
2227 (setq pos (+ pos (js2-node-pos n))))
2228 pos))
2229
2230 (defsubst js2-node-abs-end (n)
2231 "Return absolute buffer position of end of N."
2232 (+ (js2-node-abs-pos n) (js2-node-len n)))
2233
2234 ;; It's important to make sure block nodes have a lisp list for the
2235 ;; child nodes, to limit printing recursion depth in an AST that
2236 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2237 ;; a sufficiently large vector tree.
2238
2239 (defstruct (js2-block-node
2240 (:include js2-node)
2241 (:constructor nil)
2242 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2243 (pos js2-token-beg)
2244 len
2245 props
2246 kids)))
2247 "A block of statements."
2248 kids) ; a lisp list of the child statement nodes
2249
2250 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2251 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2252
2253 (defsubst js2-visit-block (ast callback)
2254 "Visit the `js2-block-node' children of AST."
2255 (dolist (kid (js2-block-node-kids ast))
2256 (js2-visit-ast kid callback)))
2257
2258 (defun js2-print-block (n i)
2259 (let ((pad (js2-make-pad i)))
2260 (insert pad "{\n")
2261 (dolist (kid (js2-block-node-kids n))
2262 (js2-print-ast kid (1+ i)))
2263 (insert pad "}")))
2264
2265 (defstruct (js2-scope
2266 (:include js2-block-node)
2267 (:constructor nil)
2268 (:constructor make-js2-scope (&key (type js2-BLOCK)
2269 (pos js2-token-beg)
2270 len
2271 kids)))
2272 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2273 ;; I don't have one of those handy, so I'll use an alist for now.
2274 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2275 ;; and is much lighter-weight to construct (both CPU and mem).
2276 ;; The keys are interned strings (symbols) for faster lookup.
2277 ;; Should switch to hybrid alist/hashtable eventually.
2278 symbol-table ; an alist of (symbol . js2-symbol)
2279 parent-scope ; a `js2-scope'
2280 top) ; top-level `js2-scope' (script/function)
2281
2282 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2283 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2284
2285 (defun js2-scope-set-parent-scope (scope parent)
2286 (setf (js2-scope-parent-scope scope) parent
2287 (js2-scope-top scope) (if (null parent)
2288 scope
2289 (js2-scope-top parent))))
2290
2291 (defun js2-node-get-enclosing-scope (node)
2292 "Return the innermost `js2-scope' node surrounding NODE.
2293 Returns nil if there is no enclosing scope node."
2294 (let ((parent (js2-node-parent node)))
2295 (while (not (js2-scope-p parent))
2296 (setq parent (js2-node-parent parent)))
2297 parent))
2298
2299 (defun js2-get-defining-scope (scope name)
2300 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2301 Returns `js2-scope' in which NAME is defined, or nil if not found."
2302 (let ((sym (if (symbolp name)
2303 name
2304 (intern name)))
2305 table
2306 result
2307 (continue t))
2308 (while (and scope continue)
2309 (if (and (setq table (js2-scope-symbol-table scope))
2310 (assq sym table))
2311 (setq continue nil
2312 result scope)
2313 (setq scope (js2-scope-parent-scope scope))))
2314 result))
2315
2316 (defsubst js2-scope-get-symbol (scope name)
2317 "Return symbol table entry for NAME in SCOPE.
2318 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2319 (and (js2-scope-symbol-table scope)
2320 (cdr (assq (if (symbolp name)
2321 name
2322 (intern name))
2323 (js2-scope-symbol-table scope)))))
2324
2325 (defsubst js2-scope-put-symbol (scope name symbol)
2326 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2327 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2328 (let* ((table (js2-scope-symbol-table scope))
2329 (sym (if (symbolp name) name (intern name)))
2330 (entry (assq sym table)))
2331 (if entry
2332 (setcdr entry symbol)
2333 (push (cons sym symbol)
2334 (js2-scope-symbol-table scope)))))
2335
2336 (defstruct (js2-symbol
2337 (:constructor nil)
2338 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2339 "A symbol table entry."
2340 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2341 ;; js2-LET, or js2-CONST
2342 decl-type
2343 name ; string
2344 ast-node) ; a `js2-node'
2345
2346 (defstruct (js2-error-node
2347 (:include js2-node)
2348 (:constructor nil) ; silence emacs21 byte-compiler
2349 (:constructor make-js2-error-node (&key (type js2-ERROR)
2350 (pos js2-token-beg)
2351 len)))
2352 "AST node representing a parse error.")
2353
2354 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2355 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2356
2357 (defstruct (js2-script-node
2358 (:include js2-scope)
2359 (:constructor nil)
2360 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2361 (pos js2-token-beg)
2362 len
2363 var-decls
2364 fun-decls)))
2365 functions ; lisp list of nested functions
2366 regexps ; lisp list of (string . flags)
2367 symbols ; alist (every symbol gets unique index)
2368 (param-count 0)
2369 var-names ; vector of string names
2370 consts ; bool-vector matching var-decls
2371 (temp-number 0)) ; for generating temp variables
2372
2373 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2374 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2375
2376 (defun js2-print-script (node indent)
2377 (dolist (kid (js2-block-node-kids node))
2378 (js2-print-ast kid indent)))
2379
2380 (defstruct (js2-ast-root
2381 (:include js2-script-node)
2382 (:constructor nil)
2383 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2384 (pos js2-token-beg)
2385 len
2386 buffer)))
2387 "The root node of a js2 AST."
2388 buffer ; the source buffer from which the code was parsed
2389 comments ; a lisp list of comments, ordered by start position
2390 errors ; a lisp list of errors found during parsing
2391 warnings ; a lisp list of warnings found during parsing
2392 node-count) ; number of nodes in the tree, including the root
2393
2394 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2395 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2396
2397 (defun js2-visit-ast-root (ast callback)
2398 (dolist (kid (js2-ast-root-kids ast))
2399 (js2-visit-ast kid callback))
2400 (dolist (comment (js2-ast-root-comments ast))
2401 (js2-visit-ast comment callback)))
2402
2403 (defstruct (js2-comment-node
2404 (:include js2-node)
2405 (:constructor nil)
2406 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2407 (pos js2-token-beg)
2408 len
2409 (format js2-ts-comment-type))))
2410 format) ; 'line, 'block, 'jsdoc or 'html
2411
2412 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2413 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2414
2415 (defun js2-print-comment (n i)
2416 ;; We really ought to link end-of-line comments to their nodes.
2417 ;; Or maybe we could add a new comment type, 'endline.
2418 (insert (js2-make-pad i)
2419 (js2-node-string n)))
2420
2421 (defstruct (js2-expr-stmt-node
2422 (:include js2-node)
2423 (:constructor nil)
2424 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2425 (pos js2-ts-cursor)
2426 len
2427 expr)))
2428 "An expression statement."
2429 expr)
2430
2431 (defsubst js2-expr-stmt-node-set-has-result (node)
2432 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2433 (setf (js2-node-type node) js2-EXPR_RESULT))
2434
2435 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2436 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2437
2438 (defun js2-visit-expr-stmt-node (n v)
2439 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2440
2441 (defun js2-print-expr-stmt-node (n indent)
2442 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2443 (insert ";\n"))
2444
2445 (defstruct (js2-loop-node
2446 (:include js2-scope)
2447 (:constructor nil))
2448 "Abstract supertype of loop nodes."
2449 body ; a `js2-block-node'
2450 lp ; position of left-paren, nil if omitted
2451 rp) ; position of right-paren, nil if omitted
2452
2453 (defstruct (js2-do-node
2454 (:include js2-loop-node)
2455 (:constructor nil)
2456 (:constructor make-js2-do-node (&key (type js2-DO)
2457 (pos js2-token-beg)
2458 len
2459 body
2460 condition
2461 while-pos
2462 lp
2463 rp)))
2464 "AST node for do-loop."
2465 condition ; while (expression)
2466 while-pos) ; buffer position of 'while' keyword
2467
2468 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2469 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2470
2471 (defun js2-visit-do-node (n v)
2472 (js2-visit-ast (js2-do-node-body n) v)
2473 (js2-visit-ast (js2-do-node-condition n) v))
2474
2475 (defun js2-print-do-node (n i)
2476 (let ((pad (js2-make-pad i)))
2477 (insert pad "do {\n")
2478 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2479 (js2-print-ast kid (1+ i)))
2480 (insert pad "} while (")
2481 (js2-print-ast (js2-do-node-condition n) 0)
2482 (insert ");\n")))
2483
2484 (defstruct (js2-while-node
2485 (:include js2-loop-node)
2486 (:constructor nil)
2487 (:constructor make-js2-while-node (&key (type js2-WHILE)
2488 (pos js2-token-beg)
2489 len
2490 body
2491 condition
2492 lp
2493 rp)))
2494 "AST node for while-loop."
2495 condition) ; while-condition
2496
2497 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2498 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2499
2500 (defun js2-visit-while-node (n v)
2501 (js2-visit-ast (js2-while-node-condition n) v)
2502 (js2-visit-ast (js2-while-node-body n) v))
2503
2504 (defun js2-print-while-node (n i)
2505 (let ((pad (js2-make-pad i)))
2506 (insert pad "while (")
2507 (js2-print-ast (js2-while-node-condition n) 0)
2508 (insert ") {\n")
2509 (js2-print-body (js2-while-node-body n) (1+ i))
2510 (insert pad "}\n")))
2511
2512 (defstruct (js2-for-node
2513 (:include js2-loop-node)
2514 (:constructor nil)
2515 (:constructor make-js2-for-node (&key (type js2-FOR)
2516 (pos js2-ts-cursor)
2517 len
2518 body
2519 init
2520 condition
2521 update
2522 lp
2523 rp)))
2524 "AST node for a C-style for-loop."
2525 init ; initialization expression
2526 condition ; loop condition
2527 update) ; update clause
2528
2529 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2530 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2531
2532 (defun js2-visit-for-node (n v)
2533 (js2-visit-ast (js2-for-node-init n) v)
2534 (js2-visit-ast (js2-for-node-condition n) v)
2535 (js2-visit-ast (js2-for-node-update n) v)
2536 (js2-visit-ast (js2-for-node-body n) v))
2537
2538 (defun js2-print-for-node (n i)
2539 (let ((pad (js2-make-pad i)))
2540 (insert pad "for (")
2541 (js2-print-ast (js2-for-node-init n) 0)
2542 (insert "; ")
2543 (js2-print-ast (js2-for-node-condition n) 0)
2544 (insert "; ")
2545 (js2-print-ast (js2-for-node-update n) 0)
2546 (insert ") {\n")
2547 (js2-print-body (js2-for-node-body n) (1+ i))
2548 (insert pad "}\n")))
2549
2550 (defstruct (js2-for-in-node
2551 (:include js2-loop-node)
2552 (:constructor nil)
2553 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2554 (pos js2-ts-cursor)
2555 len
2556 body
2557 iterator
2558 object
2559 in-pos
2560 each-pos
2561 foreach-p
2562 forof-p
2563 lp
2564 rp)))
2565 "AST node for a for..in loop."
2566 iterator ; [var] foo in ...
2567 object ; object over which we're iterating
2568 in-pos ; buffer position of 'in' keyword
2569 each-pos ; buffer position of 'each' keyword, if foreach-p
2570 foreach-p ; t if it's a for-each loop
2571 forof-p) ; t if it's a for-of loop
2572
2573 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2574 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2575
2576 (defun js2-visit-for-in-node (n v)
2577 (js2-visit-ast (js2-for-in-node-iterator n) v)
2578 (js2-visit-ast (js2-for-in-node-object n) v)
2579 (js2-visit-ast (js2-for-in-node-body n) v))
2580
2581 (defun js2-print-for-in-node (n i)
2582 (let ((pad (js2-make-pad i))
2583 (foreach (js2-for-in-node-foreach-p n))
2584 (forof (js2-for-in-node-forof-p n)))
2585 (insert pad "for ")
2586 (if foreach
2587 (insert "each "))
2588 (insert "(")
2589 (js2-print-ast (js2-for-in-node-iterator n) 0)
2590 (if forof
2591 (insert " of ")
2592 (insert " in "))
2593 (js2-print-ast (js2-for-in-node-object n) 0)
2594 (insert ") {\n")
2595 (js2-print-body (js2-for-in-node-body n) (1+ i))
2596 (insert pad "}\n")))
2597
2598 (defstruct (js2-return-node
2599 (:include js2-node)
2600 (:constructor nil)
2601 (:constructor make-js2-return-node (&key (type js2-RETURN)
2602 (pos js2-ts-cursor)
2603 len
2604 retval)))
2605 "AST node for a return statement."
2606 retval) ; expression to return, or 'undefined
2607
2608 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2609 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2610
2611 (defun js2-visit-return-node (n v)
2612 (js2-visit-ast (js2-return-node-retval n) v))
2613
2614 (defun js2-print-return-node (n i)
2615 (insert (js2-make-pad i) "return")
2616 (when (js2-return-node-retval n)
2617 (insert " ")
2618 (js2-print-ast (js2-return-node-retval n) 0))
2619 (insert ";\n"))
2620
2621 (defstruct (js2-if-node
2622 (:include js2-node)
2623 (:constructor nil)
2624 (:constructor make-js2-if-node (&key (type js2-IF)
2625 (pos js2-ts-cursor)
2626 len
2627 condition
2628 then-part
2629 else-pos
2630 else-part
2631 lp
2632 rp)))
2633 "AST node for an if-statement."
2634 condition ; expression
2635 then-part ; statement or block
2636 else-pos ; optional buffer position of 'else' keyword
2637 else-part ; optional statement or block
2638 lp ; position of left-paren, nil if omitted
2639 rp) ; position of right-paren, nil if omitted
2640
2641 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2642 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2643
2644 (defun js2-visit-if-node (n v)
2645 (js2-visit-ast (js2-if-node-condition n) v)
2646 (js2-visit-ast (js2-if-node-then-part n) v)
2647 (js2-visit-ast (js2-if-node-else-part n) v))
2648
2649 (defun js2-print-if-node (n i)
2650 (let ((pad (js2-make-pad i))
2651 (then-part (js2-if-node-then-part n))
2652 (else-part (js2-if-node-else-part n)))
2653 (insert pad "if (")
2654 (js2-print-ast (js2-if-node-condition n) 0)
2655 (insert ") {\n")
2656 (js2-print-body then-part (1+ i))
2657 (insert pad "}")
2658 (cond
2659 ((not else-part)
2660 (insert "\n"))
2661 ((js2-if-node-p else-part)
2662 (insert " else ")
2663 (js2-print-body else-part i))
2664 (t
2665 (insert " else {\n")
2666 (js2-print-body else-part (1+ i))
2667 (insert pad "}\n")))))
2668
2669 (defstruct (js2-try-node
2670 (:include js2-node)
2671 (:constructor nil)
2672 (:constructor make-js2-try-node (&key (type js2-TRY)
2673 (pos js2-ts-cursor)
2674 len
2675 try-block
2676 catch-clauses
2677 finally-block)))
2678 "AST node for a try-statement."
2679 try-block
2680 catch-clauses ; a lisp list of `js2-catch-node'
2681 finally-block) ; a `js2-finally-node'
2682
2683 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2684 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2685
2686 (defun js2-visit-try-node (n v)
2687 (js2-visit-ast (js2-try-node-try-block n) v)
2688 (dolist (clause (js2-try-node-catch-clauses n))
2689 (js2-visit-ast clause v))
2690 (js2-visit-ast (js2-try-node-finally-block n) v))
2691
2692 (defun js2-print-try-node (n i)
2693 (let ((pad (js2-make-pad i))
2694 (catches (js2-try-node-catch-clauses n))
2695 (finally (js2-try-node-finally-block n)))
2696 (insert pad "try {\n")
2697 (js2-print-body (js2-try-node-try-block n) (1+ i))
2698 (insert pad "}")
2699 (when catches
2700 (dolist (catch catches)
2701 (js2-print-ast catch i)))
2702 (if finally
2703 (js2-print-ast finally i)
2704 (insert "\n"))))
2705
2706 (defstruct (js2-catch-node
2707 (:include js2-node)
2708 (:constructor nil)
2709 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2710 (pos js2-ts-cursor)
2711 len
2712 param
2713 guard-kwd
2714 guard-expr
2715 block
2716 lp
2717 rp)))
2718 "AST node for a catch clause."
2719 param ; destructuring form or simple name node
2720 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2721 guard-expr ; catch condition, a `js2-node'
2722 block ; statements, a `js2-block-node'
2723 lp ; buffer position of left-paren, nil if omitted
2724 rp) ; buffer position of right-paren, nil if omitted
2725
2726 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2727 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2728
2729 (defun js2-visit-catch-node (n v)
2730 (js2-visit-ast (js2-catch-node-param n) v)
2731 (when (js2-catch-node-guard-kwd n)
2732 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2733 (js2-visit-ast (js2-catch-node-block n) v))
2734
2735 (defun js2-print-catch-node (n i)
2736 (let ((pad (js2-make-pad i))
2737 (guard-kwd (js2-catch-node-guard-kwd n))
2738 (guard-expr (js2-catch-node-guard-expr n)))
2739 (insert " catch (")
2740 (js2-print-ast (js2-catch-node-param n) 0)
2741 (when guard-kwd
2742 (insert " if ")
2743 (js2-print-ast guard-expr 0))
2744 (insert ") {\n")
2745 (js2-print-body (js2-catch-node-block n) (1+ i))
2746 (insert pad "}")))
2747
2748 (defstruct (js2-finally-node
2749 (:include js2-node)
2750 (:constructor nil)
2751 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2752 (pos js2-ts-cursor)
2753 len
2754 body)))
2755 "AST node for a finally clause."
2756 body) ; a `js2-node', often but not always a block node
2757
2758 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2759 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2760
2761 (defun js2-visit-finally-node (n v)
2762 (js2-visit-ast (js2-finally-node-body n) v))
2763
2764 (defun js2-print-finally-node (n i)
2765 (let ((pad (js2-make-pad i)))
2766 (insert " finally {\n")
2767 (js2-print-body (js2-finally-node-body n) (1+ i))
2768 (insert pad "}\n")))
2769
2770 (defstruct (js2-switch-node
2771 (:include js2-node)
2772 (:constructor nil)
2773 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2774 (pos js2-ts-cursor)
2775 len
2776 discriminant
2777 cases
2778 lp
2779 rp)))
2780 "AST node for a switch statement."
2781 discriminant ; a `js2-node' (switch expression)
2782 cases ; a lisp list of `js2-case-node'
2783 lp ; position of open-paren for discriminant, nil if omitted
2784 rp) ; position of close-paren for discriminant, nil if omitted
2785
2786 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2787 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2788
2789 (defun js2-visit-switch-node (n v)
2790 (js2-visit-ast (js2-switch-node-discriminant n) v)
2791 (dolist (c (js2-switch-node-cases n))
2792 (js2-visit-ast c v)))
2793
2794 (defun js2-print-switch-node (n i)
2795 (let ((pad (js2-make-pad i))
2796 (cases (js2-switch-node-cases n)))
2797 (insert pad "switch (")
2798 (js2-print-ast (js2-switch-node-discriminant n) 0)
2799 (insert ") {\n")
2800 (dolist (case cases)
2801 (js2-print-ast case i))
2802 (insert pad "}\n")))
2803
2804 (defstruct (js2-case-node
2805 (:include js2-block-node)
2806 (:constructor nil)
2807 (:constructor make-js2-case-node (&key (type js2-CASE)
2808 (pos js2-ts-cursor)
2809 len
2810 kids
2811 expr)))
2812 "AST node for a case clause of a switch statement."
2813 expr) ; the case expression (nil for default)
2814
2815 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2816 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2817
2818 (defun js2-visit-case-node (n v)
2819 (js2-visit-ast (js2-case-node-expr n) v)
2820 (js2-visit-block n v))
2821
2822 (defun js2-print-case-node (n i)
2823 (let ((pad (js2-make-pad i))
2824 (expr (js2-case-node-expr n)))
2825 (insert pad)
2826 (if (null expr)
2827 (insert "default:\n")
2828 (insert "case ")
2829 (js2-print-ast expr 0)
2830 (insert ":\n"))
2831 (dolist (kid (js2-case-node-kids n))
2832 (js2-print-ast kid (1+ i)))))
2833
2834 (defstruct (js2-throw-node
2835 (:include js2-node)
2836 (:constructor nil)
2837 (:constructor make-js2-throw-node (&key (type js2-THROW)
2838 (pos js2-ts-cursor)
2839 len
2840 expr)))
2841 "AST node for a throw statement."
2842 expr) ; the expression to throw
2843
2844 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2845 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2846
2847 (defun js2-visit-throw-node (n v)
2848 (js2-visit-ast (js2-throw-node-expr n) v))
2849
2850 (defun js2-print-throw-node (n i)
2851 (insert (js2-make-pad i) "throw ")
2852 (js2-print-ast (js2-throw-node-expr n) 0)
2853 (insert ";\n"))
2854
2855 (defstruct (js2-with-node
2856 (:include js2-node)
2857 (:constructor nil)
2858 (:constructor make-js2-with-node (&key (type js2-WITH)
2859 (pos js2-ts-cursor)
2860 len
2861 object
2862 body
2863 lp
2864 rp)))
2865 "AST node for a with-statement."
2866 object
2867 body
2868 lp ; buffer position of left-paren around object, nil if omitted
2869 rp) ; buffer position of right-paren around object, nil if omitted
2870
2871 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2872 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2873
2874 (defun js2-visit-with-node (n v)
2875 (js2-visit-ast (js2-with-node-object n) v)
2876 (js2-visit-ast (js2-with-node-body n) v))
2877
2878 (defun js2-print-with-node (n i)
2879 (let ((pad (js2-make-pad i)))
2880 (insert pad "with (")
2881 (js2-print-ast (js2-with-node-object n) 0)
2882 (insert ") {\n")
2883 (js2-print-body (js2-with-node-body n) (1+ i))
2884 (insert pad "}\n")))
2885
2886 (defstruct (js2-label-node
2887 (:include js2-node)
2888 (:constructor nil)
2889 (:constructor make-js2-label-node (&key (type js2-LABEL)
2890 (pos js2-ts-cursor)
2891 len
2892 name)))
2893 "AST node for a statement label or case label."
2894 name ; a string
2895 loop) ; for validating and code-generating continue-to-label
2896
2897 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2898 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2899
2900 (defun js2-print-label (n i)
2901 (insert (js2-make-pad i)
2902 (js2-label-node-name n)
2903 ":\n"))
2904
2905 (defstruct (js2-labeled-stmt-node
2906 (:include js2-node)
2907 (:constructor nil)
2908 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2909 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2910 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2911 (pos js2-ts-cursor)
2912 len
2913 labels
2914 stmt)))
2915 "AST node for a statement with one or more labels.
2916 Multiple labels for a statement are collapsed into the labels field."
2917 labels ; lisp list of `js2-label-node'
2918 stmt) ; the statement these labels are for
2919
2920 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2921 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2922
2923 (defun js2-get-label-by-name (lbl-stmt name)
2924 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2925 Returns nil if no such label is in the list."
2926 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2927 result)
2928 (while (and label-list (not result))
2929 (if (string= (js2-label-node-name (car label-list)) name)
2930 (setq result (car label-list))
2931 (setq label-list (cdr label-list))))
2932 result))
2933
2934 (defun js2-visit-labeled-stmt (n v)
2935 (dolist (label (js2-labeled-stmt-node-labels n))
2936 (js2-visit-ast label v))
2937 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2938
2939 (defun js2-print-labeled-stmt (n i)
2940 (dolist (label (js2-labeled-stmt-node-labels n))
2941 (js2-print-ast label i))
2942 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2943
2944 (defun js2-labeled-stmt-node-contains (node label)
2945 "Return t if NODE contains LABEL in its label set.
2946 NODE is a `js2-labels-node'. LABEL is an identifier."
2947 (loop for nl in (js2-labeled-stmt-node-labels node)
2948 if (string= label (js2-label-node-name nl))
2949 return t
2950 finally return nil))
2951
2952 (defsubst js2-labeled-stmt-node-add-label (node label)
2953 "Add a `js2-label-node' to the label set for this statement."
2954 (setf (js2-labeled-stmt-node-labels node)
2955 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2956
2957 (defstruct (js2-jump-node
2958 (:include js2-node)
2959 (:constructor nil))
2960 "Abstract supertype of break and continue nodes."
2961 label ; `js2-name-node' for location of label identifier, if present
2962 target) ; target js2-labels-node or loop/switch statement
2963
2964 (defun js2-visit-jump-node (n v)
2965 (js2-visit-ast (js2-jump-node-label n) v))
2966
2967 (defstruct (js2-break-node
2968 (:include js2-jump-node)
2969 (:constructor nil)
2970 (:constructor make-js2-break-node (&key (type js2-BREAK)
2971 (pos js2-ts-cursor)
2972 len
2973 label
2974 target)))
2975 "AST node for a break statement.
2976 The label field is a `js2-name-node', possibly nil, for the named label
2977 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2978 is the target of the break - a label node or enclosing loop/switch statement.")
2979
2980 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2981 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2982
2983 (defun js2-print-break-node (n i)
2984 (insert (js2-make-pad i) "break")
2985 (when (js2-break-node-label n)
2986 (insert " ")
2987 (js2-print-ast (js2-break-node-label n) 0))
2988 (insert ";\n"))
2989
2990 (defstruct (js2-continue-node
2991 (:include js2-jump-node)
2992 (:constructor nil)
2993 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2994 (pos js2-ts-cursor)
2995 len
2996 label
2997 target)))
2998 "AST node for a continue statement.
2999 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3000 It is nil if continue specifies no label. The target field is the jump target:
3001 a `js2-label-node' or the innermost enclosing loop.")
3002
3003 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3004 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3005
3006 (defun js2-print-continue-node (n i)
3007 (insert (js2-make-pad i) "continue")
3008 (when (js2-continue-node-label n)
3009 (insert " ")
3010 (js2-print-ast (js2-continue-node-label n) 0))
3011 (insert ";\n"))
3012
3013 (defstruct (js2-function-node
3014 (:include js2-script-node)
3015 (:constructor nil)
3016 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3017 (pos js2-ts-cursor)
3018 len
3019 (ftype 'FUNCTION)
3020 (form 'FUNCTION_STATEMENT)
3021 (name "")
3022 params
3023 rest-p
3024 body
3025 lp
3026 rp)))
3027 "AST node for a function declaration.
3028 The `params' field is a lisp list of nodes. Each node is either a simple
3029 `js2-name-node', or if it's a destructuring-assignment parameter, a
3030 `js2-array-node' or `js2-object-node'."
3031 ftype ; FUNCTION, GETTER or SETTER
3032 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3033 name ; function name (a `js2-name-node', or nil if anonymous)
3034 params ; a lisp list of destructuring forms or simple name nodes
3035 rest-p ; if t, the last parameter is rest parameter
3036 body ; a `js2-block-node' or expression node (1.8 only)
3037 lp ; position of arg-list open-paren, or nil if omitted
3038 rp ; position of arg-list close-paren, or nil if omitted
3039 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3040 needs-activation ; t if we need an activation object for this frame
3041 is-generator ; t if this function contains a yield
3042 member-expr) ; nonstandard Ecma extension from Rhino
3043
3044 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3045 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3046
3047 (defun js2-visit-function-node (n v)
3048 (js2-visit-ast (js2-function-node-name n) v)
3049 (dolist (p (js2-function-node-params n))
3050 (js2-visit-ast p v))
3051 (js2-visit-ast (js2-function-node-body n) v))
3052
3053 (defun js2-print-function-node (n i)
3054 (let ((pad (js2-make-pad i))
3055 (getter (js2-node-get-prop n 'GETTER_SETTER))
3056 (name (js2-function-node-name n))
3057 (params (js2-function-node-params n))
3058 (rest-p (js2-function-node-rest-p n))
3059 (body (js2-function-node-body n))
3060 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3061 (unless getter
3062 (insert pad "function"))
3063 (when name
3064 (insert " ")
3065 (js2-print-ast name 0))
3066 (insert "(")
3067 (loop with len = (length params)
3068 for param in params
3069 for count from 1
3070 do
3071 (when (and rest-p (= count len))
3072 (insert "..."))
3073 (js2-print-ast param 0)
3074 (when (< count len)
3075 (insert ", ")))
3076 (insert ") {")
3077 (unless expr
3078 (insert "\n"))
3079 ;; TODO: fix this to be smarter about indenting, etc.
3080 (js2-print-body body (1+ i))
3081 (insert pad "}")
3082 (unless expr
3083 (insert "\n"))))
3084
3085 (defsubst js2-function-name (node)
3086 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3087 (and (js2-function-node-name node)
3088 (js2-name-node-name (js2-function-node-name node))))
3089
3090 ;; Having this be an expression node makes it more flexible.
3091 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3092 ;; that work better if you assume it's an expression. Whenever we have
3093 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3094 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3095 (defstruct (js2-var-decl-node
3096 (:include js2-node)
3097 (:constructor nil)
3098 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3099 (pos js2-token-beg)
3100 len
3101 kids
3102 decl-type)))
3103 "AST node for a variable declaration list (VAR, CONST or LET).
3104 The node bounds differ depending on the declaration type. For VAR or
3105 CONST declarations, the bounds include the var/const keyword. For LET
3106 declarations, the node begins at the position of the first child."
3107 kids ; a lisp list of `js2-var-init-node' structs.
3108 decl-type) ; js2-VAR, js2-CONST or js2-LET
3109
3110 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3111 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3112
3113 (defun js2-visit-var-decl (n v)
3114 (dolist (kid (js2-var-decl-node-kids n))
3115 (js2-visit-ast kid v)))
3116
3117 (defun js2-print-var-decl (n i)
3118 (let ((pad (js2-make-pad i))
3119 (tt (js2-var-decl-node-decl-type n)))
3120 (insert pad)
3121 (insert (cond
3122 ((= tt js2-VAR) "var ")
3123 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3124 ((= tt js2-CONST) "const ")
3125 (t
3126 (error "malformed var-decl node"))))
3127 (loop with kids = (js2-var-decl-node-kids n)
3128 with len = (length kids)
3129 for kid in kids
3130 for count from 1
3131 do
3132 (js2-print-ast kid 0)
3133 (if (< count len)
3134 (insert ", ")))))
3135
3136 (defstruct (js2-var-init-node
3137 (:include js2-node)
3138 (:constructor nil)
3139 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3140 (pos js2-ts-cursor)
3141 len
3142 target
3143 initializer)))
3144 "AST node for a variable declaration.
3145 The type field will be js2-CONST for a const decl."
3146 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3147 initializer) ; initializer expression, a `js2-node'
3148
3149 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3150 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3151
3152 (defun js2-visit-var-init-node (n v)
3153 (js2-visit-ast (js2-var-init-node-target n) v)
3154 (js2-visit-ast (js2-var-init-node-initializer n) v))
3155
3156 (defun js2-print-var-init-node (n i)
3157 (let ((pad (js2-make-pad i))
3158 (name (js2-var-init-node-target n))
3159 (init (js2-var-init-node-initializer n)))
3160 (insert pad)
3161 (js2-print-ast name 0)
3162 (when init
3163 (insert " = ")
3164 (js2-print-ast init 0))))
3165
3166 (defstruct (js2-cond-node
3167 (:include js2-node)
3168 (:constructor nil)
3169 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3170 (pos js2-ts-cursor)
3171 len
3172 test-expr
3173 true-expr
3174 false-expr
3175 q-pos
3176 c-pos)))
3177 "AST node for the ternary operator"
3178 test-expr
3179 true-expr
3180 false-expr
3181 q-pos ; buffer position of ?
3182 c-pos) ; buffer position of :
3183
3184 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3185 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3186
3187 (defun js2-visit-cond-node (n v)
3188 (js2-visit-ast (js2-cond-node-test-expr n) v)
3189 (js2-visit-ast (js2-cond-node-true-expr n) v)
3190 (js2-visit-ast (js2-cond-node-false-expr n) v))
3191
3192 (defun js2-print-cond-node (n i)
3193 (let ((pad (js2-make-pad i)))
3194 (insert pad)
3195 (js2-print-ast (js2-cond-node-test-expr n) 0)
3196 (insert " ? ")
3197 (js2-print-ast (js2-cond-node-true-expr n) 0)
3198 (insert " : ")
3199 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3200
3201 (defstruct (js2-infix-node
3202 (:include js2-node)
3203 (:constructor nil)
3204 (:constructor make-js2-infix-node (&key type
3205 (pos js2-ts-cursor)
3206 len
3207 op-pos
3208 left
3209 right)))
3210 "Represents infix expressions.
3211 Includes assignment ops like `|=', and the comma operator.
3212 The type field inherited from `js2-node' holds the operator."
3213 op-pos ; buffer position where operator begins
3214 left ; any `js2-node'
3215 right) ; any `js2-node'
3216
3217 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3218 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3219
3220 (defun js2-visit-infix-node (n v)
3221 (js2-visit-ast (js2-infix-node-left n) v)
3222 (js2-visit-ast (js2-infix-node-right n) v))
3223
3224 (defconst js2-operator-tokens
3225 (let ((table (make-hash-table :test 'eq))
3226 (tokens
3227 (list (cons js2-IN "in")
3228 (cons js2-TYPEOF "typeof")
3229 (cons js2-INSTANCEOF "instanceof")
3230 (cons js2-DELPROP "delete")
3231 (cons js2-COMMA ",")
3232 (cons js2-COLON ":")
3233 (cons js2-OR "||")
3234 (cons js2-AND "&&")
3235 (cons js2-INC "++")
3236 (cons js2-DEC "--")
3237 (cons js2-BITOR "|")
3238 (cons js2-BITXOR "^")
3239 (cons js2-BITAND "&")
3240 (cons js2-EQ "==")
3241 (cons js2-NE "!=")
3242 (cons js2-LT "<")
3243 (cons js2-LE "<=")
3244 (cons js2-GT ">")
3245 (cons js2-GE ">=")
3246 (cons js2-LSH "<<")
3247 (cons js2-RSH ">>")
3248 (cons js2-URSH ">>>")
3249 (cons js2-ADD "+") ; infix plus
3250 (cons js2-SUB "-") ; infix minus
3251 (cons js2-MUL "*")
3252 (cons js2-DIV "/")
3253 (cons js2-MOD "%")
3254 (cons js2-NOT "!")
3255 (cons js2-BITNOT "~")
3256 (cons js2-POS "+") ; unary plus
3257 (cons js2-NEG "-") ; unary minus
3258 (cons js2-SHEQ "===") ; shallow equality
3259 (cons js2-SHNE "!==") ; shallow inequality
3260 (cons js2-ASSIGN "=")
3261 (cons js2-ASSIGN_BITOR "|=")
3262 (cons js2-ASSIGN_BITXOR "^=")
3263 (cons js2-ASSIGN_BITAND "&=")
3264 (cons js2-ASSIGN_LSH "<<=")
3265 (cons js2-ASSIGN_RSH ">>=")
3266 (cons js2-ASSIGN_URSH ">>>=")
3267 (cons js2-ASSIGN_ADD "+=")
3268 (cons js2-ASSIGN_SUB "-=")
3269 (cons js2-ASSIGN_MUL "*=")
3270 (cons js2-ASSIGN_DIV "/=")
3271 (cons js2-ASSIGN_MOD "%="))))
3272 (loop for (k . v) in tokens do
3273 (puthash k v table))
3274 table))
3275
3276 (defun js2-print-infix-node (n i)
3277 (let* ((tt (js2-node-type n))
3278 (op (gethash tt js2-operator-tokens)))
3279 (unless op
3280 (error "unrecognized infix operator %s" (js2-node-type n)))
3281 (insert (js2-make-pad i))
3282 (js2-print-ast (js2-infix-node-left n) 0)
3283 (unless (= tt js2-COMMA)
3284 (insert " "))
3285 (insert op)
3286 (insert " ")
3287 (js2-print-ast (js2-infix-node-right n) 0)))
3288
3289 (defstruct (js2-assign-node
3290 (:include js2-infix-node)
3291 (:constructor nil)
3292 (:constructor make-js2-assign-node (&key type
3293 (pos js2-ts-cursor)
3294 len
3295 op-pos
3296 left
3297 right)))
3298 "Represents any assignment.
3299 The type field holds the actual assignment operator.")
3300
3301 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3302 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3303
3304 (defstruct (js2-unary-node
3305 (:include js2-node)
3306 (:constructor nil)
3307 (:constructor make-js2-unary-node (&key type ; required
3308 (pos js2-ts-cursor)
3309 len
3310 operand)))
3311 "AST node type for unary operator nodes.
3312 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3313 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3314 property is added if the operator follows the operand."
3315 operand) ; a `js2-node' expression
3316
3317 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3318 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3319
3320 (defun js2-visit-unary-node (n v)
3321 (js2-visit-ast (js2-unary-node-operand n) v))
3322
3323 (defun js2-print-unary-node (n i)
3324 (let* ((tt (js2-node-type n))
3325 (op (gethash tt js2-operator-tokens))
3326 (postfix (js2-node-get-prop n 'postfix)))
3327 (unless op
3328 (error "unrecognized unary operator %s" tt))
3329 (insert (js2-make-pad i))
3330 (unless postfix
3331 (insert op))
3332 (if (or (= tt js2-TYPEOF)
3333 (= tt js2-DELPROP))
3334 (insert " "))
3335 (js2-print-ast (js2-unary-node-operand n) 0)
3336 (when postfix
3337 (insert op))))
3338
3339 (defstruct (js2-let-node
3340 (:include js2-scope)
3341 (:constructor nil)
3342 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3343 (pos js2-token-beg)
3344 len
3345 vars
3346 body
3347 lp
3348 rp)))
3349 "AST node for a let expression or a let statement.
3350 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3351 vars ; a `js2-var-decl-node'
3352 body ; a `js2-node' representing the expression or body block
3353 lp
3354 rp)
3355
3356 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3357 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3358
3359 (defun js2-visit-let-node (n v)
3360 (js2-visit-ast (js2-let-node-vars n) v)
3361 (js2-visit-ast (js2-let-node-body n) v))
3362
3363 (defun js2-print-let-node (n i)
3364 (insert (js2-make-pad i) "let (")
3365 (js2-print-ast (js2-let-node-vars n) 0)
3366 (insert ") ")
3367 (js2-print-ast (js2-let-node-body n) i))
3368
3369 (defstruct (js2-keyword-node
3370 (:include js2-node)
3371 (:constructor nil)
3372 (:constructor make-js2-keyword-node (&key type
3373 (pos js2-token-beg)
3374 (len (- js2-ts-cursor pos)))))
3375 "AST node representing a literal keyword such as `null'.
3376 Used for `null', `this', `true', `false' and `debugger'.
3377 The node type is set to js2-NULL, js2-THIS, etc.")
3378
3379 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3380 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3381
3382 (defun js2-print-keyword-node (n i)
3383 (insert (js2-make-pad i)
3384 (let ((tt (js2-node-type n)))
3385 (cond
3386 ((= tt js2-THIS) "this")
3387 ((= tt js2-NULL) "null")
3388 ((= tt js2-TRUE) "true")
3389 ((= tt js2-FALSE) "false")
3390 ((= tt js2-DEBUGGER) "debugger")
3391 (t (error "Invalid keyword literal type: %d" tt))))))
3392
3393 (defsubst js2-this-node-p (node)
3394 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3395 (eq (js2-node-type node) js2-THIS))
3396
3397 (defstruct (js2-new-node
3398 (:include js2-node)
3399 (:constructor nil)
3400 (:constructor make-js2-new-node (&key (type js2-NEW)
3401 (pos js2-token-beg)
3402 len
3403 target
3404 args
3405 initializer
3406 lp
3407 rp)))
3408 "AST node for new-expression such as new Foo()."
3409 target ; an identifier or reference
3410 args ; a lisp list of argument nodes
3411 lp ; position of left-paren, nil if omitted
3412 rp ; position of right-paren, nil if omitted
3413 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3414
3415 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3416 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3417
3418 (defun js2-visit-new-node (n v)
3419 (js2-visit-ast (js2-new-node-target n) v)
3420 (dolist (arg (js2-new-node-args n))
3421 (js2-visit-ast arg v))
3422 (js2-visit-ast (js2-new-node-initializer n) v))
3423
3424 (defun js2-print-new-node (n i)
3425 (insert (js2-make-pad i) "new ")
3426 (js2-print-ast (js2-new-node-target n))
3427 (insert "(")
3428 (js2-print-list (js2-new-node-args n))
3429 (insert ")")
3430 (when (js2-new-node-initializer n)
3431 (insert " ")
3432 (js2-print-ast (js2-new-node-initializer n))))
3433
3434 (defstruct (js2-name-node
3435 (:include js2-node)
3436 (:constructor nil)
3437 (:constructor make-js2-name-node (&key (type js2-NAME)
3438 (pos js2-token-beg)
3439 (len (- js2-ts-cursor
3440 js2-token-beg))
3441 (name js2-ts-string))))
3442 "AST node for a JavaScript identifier"
3443 name ; a string
3444 scope) ; a `js2-scope' (optional, used for codegen)
3445
3446 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3447 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3448
3449 (defun js2-print-name-node (n i)
3450 (insert (js2-make-pad i)
3451 (js2-name-node-name n)))
3452
3453 (defsubst js2-name-node-length (node)
3454 "Return identifier length of NODE, a `js2-name-node'.
3455 Returns 0 if NODE is nil or its identifier field is nil."
3456 (if node
3457 (length (js2-name-node-name node))
3458 0))
3459
3460 (defstruct (js2-number-node
3461 (:include js2-node)
3462 (:constructor nil)
3463 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3464 (pos js2-token-beg)
3465 (len (- js2-ts-cursor
3466 js2-token-beg))
3467 (value js2-ts-string)
3468 (num-value js2-ts-number))))
3469 "AST node for a number literal."
3470 value ; the original string, e.g. "6.02e23"
3471 num-value) ; the parsed number value
3472
3473 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3474 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3475
3476 (defun js2-print-number-node (n i)
3477 (insert (js2-make-pad i)
3478 (number-to-string (js2-number-node-num-value n))))
3479
3480 (defstruct (js2-regexp-node
3481 (:include js2-node)
3482 (:constructor nil)
3483 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3484 (pos js2-token-beg)
3485 (len (- js2-ts-cursor
3486 js2-token-beg))
3487 value
3488 flags)))
3489 "AST node for a regular expression literal."
3490 value ; the regexp string, without // delimiters
3491 flags) ; a string of flags, e.g. `mi'.
3492
3493 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3494 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3495
3496 (defun js2-print-regexp (n i)
3497 (insert (js2-make-pad i)
3498 "/"
3499 (js2-regexp-node-value n)
3500 "/")
3501 (if (js2-regexp-node-flags n)
3502 (insert (js2-regexp-node-flags n))))
3503
3504 (defstruct (js2-string-node
3505 (:include js2-node)
3506 (:constructor nil)
3507 (:constructor make-js2-string-node (&key (type js2-STRING)
3508 (pos js2-token-beg)
3509 (len (- js2-ts-cursor
3510 js2-token-beg))
3511 (value js2-ts-string))))
3512 "String literal.
3513 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3514 You can tell the quote type by looking at the first character."
3515 value) ; the characters of the string, including the quotes
3516
3517 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3518 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3519
3520 (defun js2-print-string-node (n i)
3521 (insert (js2-make-pad i)
3522 (js2-node-string n)))
3523
3524 (defstruct (js2-array-node
3525 (:include js2-node)
3526 (:constructor nil)
3527 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3528 (pos js2-ts-cursor)
3529 len
3530 elems)))
3531 "AST node for an array literal."
3532 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3533
3534 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3535 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3536
3537 (defun js2-visit-array-node (n v)
3538 (dolist (e (js2-array-node-elems n))
3539 (js2-visit-ast e v)))
3540
3541 (defun js2-print-array-node (n i)
3542 (insert (js2-make-pad i) "[")
3543 (js2-print-list (js2-array-node-elems n))
3544 (insert "]"))
3545
3546 (defstruct (js2-object-node
3547 (:include js2-node)
3548 (:constructor nil)
3549 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3550 (pos js2-ts-cursor)
3551 len
3552 elems)))
3553 "AST node for an object literal expression.
3554 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3555 the latter represents abbreviation in destructuring expressions."
3556 elems)
3557
3558 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3559 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3560
3561 (defun js2-visit-object-node (n v)
3562 (dolist (e (js2-object-node-elems n))
3563 (js2-visit-ast e v)))
3564
3565 (defun js2-print-object-node (n i)
3566 (insert (js2-make-pad i) "{")
3567 (js2-print-list (js2-object-node-elems n))
3568 (insert "}"))
3569
3570 (defstruct (js2-object-prop-node
3571 (:include js2-infix-node)
3572 (:constructor nil)
3573 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3574 (pos js2-ts-cursor)
3575 len
3576 left
3577 right
3578 op-pos)))
3579 "AST node for an object literal prop:value entry.
3580 The `left' field is the property: a name node, string node or number node.
3581 The `right' field is a `js2-node' representing the initializer value.")
3582
3583 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3584 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3585
3586 (defun js2-print-object-prop-node (n i)
3587 (insert (js2-make-pad i))
3588 (js2-print-ast (js2-object-prop-node-left n) 0)
3589 (insert ": ")
3590 (js2-print-ast (js2-object-prop-node-right n) 0))
3591
3592 (defstruct (js2-getter-setter-node
3593 (:include js2-infix-node)
3594 (:constructor nil)
3595 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3596 (pos js2-ts-cursor)
3597 len
3598 left
3599 right)))
3600 "AST node for a getter/setter property in an object literal.
3601 The `left' field is the `js2-name-node' naming the getter/setter prop.
3602 The `right' field is always an anonymous `js2-function-node' with a node
3603 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3604
3605 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3606 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3607
3608 (defun js2-print-getter-setter (n i)
3609 (let ((pad (js2-make-pad i))
3610 (left (js2-getter-setter-node-left n))
3611 (right (js2-getter-setter-node-right n)))
3612 (insert pad)
3613 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3614 (js2-print-ast left 0)
3615 (js2-print-ast right 0)))
3616
3617 (defstruct (js2-prop-get-node
3618 (:include js2-infix-node)
3619 (:constructor nil)
3620 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3621 (pos js2-ts-cursor)
3622 len
3623 left
3624 right)))
3625 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3626
3627 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3628 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3629
3630 (defun js2-visit-prop-get-node (n v)
3631 (js2-visit-ast (js2-prop-get-node-left n) v)
3632 (js2-visit-ast (js2-prop-get-node-right n) v))
3633
3634 (defun js2-print-prop-get-node (n i)
3635 (insert (js2-make-pad i))
3636 (js2-print-ast (js2-prop-get-node-left n) 0)
3637 (insert ".")
3638 (js2-print-ast (js2-prop-get-node-right n) 0))
3639
3640 (defstruct (js2-elem-get-node
3641 (:include js2-node)
3642 (:constructor nil)
3643 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3644 (pos js2-ts-cursor)
3645 len
3646 target
3647 element
3648 lb
3649 rb)))
3650 "AST node for an array index expression such as foo[bar]."
3651 target ; a `js2-node' - the expression preceding the "."
3652 element ; a `js2-node' - the expression in brackets
3653 lb ; position of left-bracket, nil if omitted
3654 rb) ; position of right-bracket, nil if omitted
3655
3656 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3657 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3658
3659 (defun js2-visit-elem-get-node (n v)
3660 (js2-visit-ast (js2-elem-get-node-target n) v)
3661 (js2-visit-ast (js2-elem-get-node-element n) v))
3662
3663 (defun js2-print-elem-get-node (n i)
3664 (insert (js2-make-pad i))
3665 (js2-print-ast (js2-elem-get-node-target n) 0)
3666 (insert "[")
3667 (js2-print-ast (js2-elem-get-node-element n) 0)
3668 (insert "]"))
3669
3670 (defstruct (js2-call-node
3671 (:include js2-node)
3672 (:constructor nil)
3673 (:constructor make-js2-call-node (&key (type js2-CALL)
3674 (pos js2-ts-cursor)
3675 len
3676 target
3677 args
3678 lp
3679 rp)))
3680 "AST node for a JavaScript function call."
3681 target ; a `js2-node' evaluating to the function to call
3682 args ; a lisp list of `js2-node' arguments
3683 lp ; position of open-paren, or nil if missing
3684 rp) ; position of close-paren, or nil if missing
3685
3686 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3687 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3688
3689 (defun js2-visit-call-node (n v)
3690 (js2-visit-ast (js2-call-node-target n) v)
3691 (dolist (arg (js2-call-node-args n))
3692 (js2-visit-ast arg v)))
3693
3694 (defun js2-print-call-node (n i)
3695 (insert (js2-make-pad i))
3696 (js2-print-ast (js2-call-node-target n) 0)
3697 (insert "(")
3698 (js2-print-list (js2-call-node-args n))
3699 (insert ")"))
3700
3701 (defstruct (js2-yield-node
3702 (:include js2-node)
3703 (:constructor nil)
3704 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3705 (pos js2-ts-cursor)
3706 len
3707 value)))
3708 "AST node for yield statement or expression."
3709 value) ; optional: value to be yielded
3710
3711 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3712 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3713
3714 (defun js2-visit-yield-node (n v)
3715 (js2-visit-ast (js2-yield-node-value n) v))
3716
3717 (defun js2-print-yield-node (n i)
3718 (insert (js2-make-pad i))
3719 (insert "yield")
3720 (when (js2-yield-node-value n)
3721 (insert " ")
3722 (js2-print-ast (js2-yield-node-value n) 0)))
3723
3724 (defstruct (js2-paren-node
3725 (:include js2-node)
3726 (:constructor nil)
3727 (:constructor make-js2-paren-node (&key (type js2-LP)
3728 (pos js2-ts-cursor)
3729 len
3730 expr)))
3731 "AST node for a parenthesized expression.
3732 In particular, used when the parens are syntactically optional,
3733 as opposed to required parens such as those enclosing an if-conditional."
3734 expr) ; `js2-node'
3735
3736 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3737 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3738
3739 (defun js2-visit-paren-node (n v)
3740 (js2-visit-ast (js2-paren-node-expr n) v))
3741
3742 (defun js2-print-paren-node (n i)
3743 (insert (js2-make-pad i))
3744 (insert "(")
3745 (js2-print-ast (js2-paren-node-expr n) 0)
3746 (insert ")"))
3747
3748 (defstruct (js2-array-comp-node
3749 (:include js2-scope)
3750 (:constructor nil)
3751 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3752 (pos js2-ts-cursor)
3753 len
3754 result
3755 loops
3756 filter
3757 if-pos
3758 lp
3759 rp)))
3760 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3761 result ; result expression (just after left-bracket)
3762 loops ; a lisp list of `js2-array-comp-loop-node'
3763 filter ; guard/filter expression
3764 if-pos ; buffer pos of 'if' keyword, if present, else nil
3765 lp ; buffer position of if-guard left-paren, or nil if not present
3766 rp) ; buffer position of if-guard right-paren, or nil if not present
3767
3768 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3769 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3770
3771 (defun js2-visit-array-comp-node (n v)
3772 (js2-visit-ast (js2-array-comp-node-result n) v)
3773 (dolist (l (js2-array-comp-node-loops n))
3774 (js2-visit-ast l v))
3775 (js2-visit-ast (js2-array-comp-node-filter n) v))
3776
3777 (defun js2-print-array-comp-node (n i)
3778 (let ((pad (js2-make-pad i))
3779 (result (js2-array-comp-node-result n))
3780 (loops (js2-array-comp-node-loops n))
3781 (filter (js2-array-comp-node-filter n)))
3782 (insert pad "[")
3783 (js2-print-ast result 0)
3784 (dolist (l loops)
3785 (insert " ")
3786 (js2-print-ast l 0))
3787 (when filter
3788 (insert " if (")
3789 (js2-print-ast filter 0)
3790 (insert ")"))
3791 (insert "]")))
3792
3793 (defstruct (js2-array-comp-loop-node
3794 (:include js2-for-in-node)
3795 (:constructor nil)
3796 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3797 (pos js2-ts-cursor)
3798 len
3799 iterator
3800 object
3801 in-pos
3802 foreach-p
3803 each-pos
3804 forof-p
3805 lp
3806 rp)))
3807 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3808
3809 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3810 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3811
3812 (defun js2-visit-array-comp-loop (n v)
3813 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3814 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3815
3816 (defun js2-print-array-comp-loop (n i)
3817 (insert "for (")
3818 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3819 (if (js2-array-comp-loop-node-forof-p n)
3820 (insert " of ")
3821 (insert " in "))
3822 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3823 (insert ")"))
3824
3825 (defstruct (js2-empty-expr-node
3826 (:include js2-node)
3827 (:constructor nil)
3828 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3829 (pos js2-token-beg)
3830 len)))
3831 "AST node for an empty expression.")
3832
3833 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3834 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3835
3836 (defstruct (js2-xml-node
3837 (:include js2-block-node)
3838 (:constructor nil)
3839 (:constructor make-js2-xml-node (&key (type js2-XML)
3840 (pos js2-token-beg)
3841 len
3842 kids)))
3843 "AST node for initial parse of E4X literals.
3844 The kids field is a list of XML fragments, each a `js2-string-node' or
3845 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3846
3847 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3848 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3849
3850 (defun js2-print-xml-node (n i)
3851 (dolist (kid (js2-xml-node-kids n))
3852 (js2-print-ast kid i)))
3853
3854 (defstruct (js2-xml-js-expr-node
3855 (:include js2-xml-node)
3856 (:constructor nil)
3857 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3858 (pos js2-ts-cursor)
3859 len
3860 expr)))
3861 "AST node for an embedded JavaScript {expression} in an E4X literal.
3862 The start and end fields correspond to the curly-braces."
3863 expr) ; a `js2-expr-node' of some sort
3864
3865 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3866 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3867
3868 (defun js2-visit-xml-js-expr (n v)
3869 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3870
3871 (defun js2-print-xml-js-expr (n i)
3872 (insert (js2-make-pad i))
3873 (insert "{")
3874 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3875 (insert "}"))
3876
3877 (defstruct (js2-xml-dot-query-node
3878 (:include js2-infix-node)
3879 (:constructor nil)
3880 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3881 (pos js2-ts-cursor)
3882 op-pos
3883 len
3884 left
3885 right
3886 rp)))
3887 "AST node for an E4X foo.(bar) filter expression.
3888 Note that the left-paren is automatically the character immediately
3889 following the dot (.) in the operator. No whitespace is permitted
3890 between the dot and the lp by the scanner."
3891 rp)
3892
3893 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3894 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3895
3896 (defun js2-print-xml-dot-query (n i)
3897 (insert (js2-make-pad i))
3898 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3899 (insert ".(")
3900 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3901 (insert ")"))
3902
3903 (defstruct (js2-xml-ref-node
3904 (:include js2-node)
3905 (:constructor nil)) ; abstract
3906 "Base type for E4X XML attribute-access or property-get expressions.
3907 Such expressions can take a variety of forms. The general syntax has
3908 three parts:
3909
3910 - (optional) an @ (specifying an attribute access)
3911 - (optional) a namespace (a `js2-name-node') and double-colon
3912 - (required) either a `js2-name-node' or a bracketed [expression]
3913
3914 The property-name expressions (examples: ns::name, @name) are
3915 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3916 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3917
3918 This node type (or more specifically, its subclasses) will sometimes
3919 be the right-hand child of a `js2-prop-get-node' or a
3920 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3921 The `js2-xml-ref-node' may also be a standalone primary expression with
3922 no explicit target, which is valid in certain expression contexts such as
3923
3924 company..employee.(@id < 100)
3925
3926 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3927 expression whose parent is a `js2-xml-dot-query-node'."
3928 namespace
3929 at-pos
3930 colon-pos)
3931
3932 (defsubst js2-xml-ref-node-attr-access-p (node)
3933 "Return non-nil if this expression began with an @-token."
3934 (and (numberp (js2-xml-ref-node-at-pos node))
3935 (plusp (js2-xml-ref-node-at-pos node))))
3936
3937 (defstruct (js2-xml-prop-ref-node
3938 (:include js2-xml-ref-node)
3939 (:constructor nil)
3940 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3941 (pos js2-token-beg)
3942 len
3943 propname
3944 namespace
3945 at-pos
3946 colon-pos)))
3947 "AST node for an E4X XML [expr] property-ref expression.
3948 The JavaScript syntax is an optional @, an optional ns::, and a name.
3949
3950 [ '@' ] [ name '::' ] name
3951
3952 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3953 @ns::*, @*::attr, @*::*, and @*.
3954
3955 The node starts at the @ token, if present. Otherwise it starts at the
3956 namespace name. The node bounds extend through the closing right-bracket,
3957 or if it is missing due to a syntax error, through the end of the index
3958 expression."
3959 propname)
3960
3961 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3962 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3963
3964 (defun js2-visit-xml-prop-ref-node (n v)
3965 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3966 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3967
3968 (defun js2-print-xml-prop-ref-node (n i)
3969 (insert (js2-make-pad i))
3970 (if (js2-xml-ref-node-attr-access-p n)
3971 (insert "@"))
3972 (when (js2-xml-prop-ref-node-namespace n)
3973 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3974 (insert "::"))
3975 (if (js2-xml-prop-ref-node-propname n)
3976 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3977
3978 (defstruct (js2-xml-elem-ref-node
3979 (:include js2-xml-ref-node)
3980 (:constructor nil)
3981 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3982 (pos js2-token-beg)
3983 len
3984 expr
3985 lb
3986 rb
3987 namespace
3988 at-pos
3989 colon-pos)))
3990 "AST node for an E4X XML [expr] member-ref expression.
3991 Syntax:
3992
3993 [ '@' ] [ name '::' ] '[' expr ']'
3994
3995 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3996
3997 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3998 is not a legal E4X XML element-ref expression, since it's already used
3999 for standard JavaScript element-get array indexing. Hence, a
4000 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4001 non-nil namespace node, or both.
4002
4003 The node starts at the @ token, if present. Otherwise it starts
4004 at the namespace name. The node bounds extend through the closing
4005 right-bracket, or if it is missing due to a syntax error, through the
4006 end of the index expression."
4007 expr ; the bracketed index expression
4008 lb
4009 rb)
4010
4011 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4012 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4013
4014 (defun js2-visit-xml-elem-ref-node (n v)
4015 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4016 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4017
4018 (defun js2-print-xml-elem-ref-node (n i)
4019 (insert (js2-make-pad i))
4020 (if (js2-xml-ref-node-attr-access-p n)
4021 (insert "@"))
4022 (when (js2-xml-elem-ref-node-namespace n)
4023 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4024 (insert "::"))
4025 (insert "[")
4026 (if (js2-xml-elem-ref-node-expr n)
4027 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4028 (insert "]"))
4029
4030 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4031
4032 (defstruct (js2-xml-start-tag-node
4033 (:include js2-xml-node)
4034 (:constructor nil)
4035 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4036 (pos js2-ts-cursor)
4037 len
4038 name
4039 attrs
4040 kids
4041 empty-p)))
4042 "AST node for an XML start-tag. Not currently used.
4043 The `kids' field is a lisp list of child content nodes."
4044 name ; a `js2-xml-name-node'
4045 attrs ; a lisp list of `js2-xml-attr-node'
4046 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4047
4048 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4049 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4050
4051 (defun js2-visit-xml-start-tag (n v)
4052 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4053 (dolist (attr (js2-xml-start-tag-node-attrs n))
4054 (js2-visit-ast attr v))
4055 (js2-visit-block n v))
4056
4057 (defun js2-print-xml-start-tag (n i)
4058 (insert (js2-make-pad i) "<")
4059 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4060 (when (js2-xml-start-tag-node-attrs n)
4061 (insert " ")
4062 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4063 (insert ">"))
4064
4065 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4066 ;; and add the end-tag to the kids list of the parent as well.
4067 (defstruct (js2-xml-end-tag-node
4068 (:include js2-xml-node)
4069 (:constructor nil)
4070 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4071 (pos js2-ts-cursor)
4072 len
4073 name)))
4074 "AST node for an XML end-tag. Not currently used."
4075 name) ; a `js2-xml-name-node'
4076
4077 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4078 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4079
4080 (defun js2-visit-xml-end-tag (n v)
4081 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4082
4083 (defun js2-print-xml-end-tag (n i)
4084 (insert (js2-make-pad i))
4085 (insert "</")
4086 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4087 (insert ">"))
4088
4089 (defstruct (js2-xml-name-node
4090 (:include js2-xml-node)
4091 (:constructor nil)
4092 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4093 (pos js2-ts-cursor)
4094 len
4095 namespace
4096 kids)))
4097 "AST node for an E4X XML name. Not currently used.
4098 Any XML name can be qualified with a namespace, hence the namespace field.
4099 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4100 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4101 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4102 namespace) ; a `js2-string-node'
4103
4104 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4105 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4106
4107 (defun js2-visit-xml-name-node (n v)
4108 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4109
4110 (defun js2-print-xml-name-node (n i)
4111 (insert (js2-make-pad i))
4112 (when (js2-xml-name-node-namespace n)
4113 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4114 (insert "::"))
4115 (dolist (kid (js2-xml-name-node-kids n))
4116 (js2-print-ast kid 0)))
4117
4118 (defstruct (js2-xml-pi-node
4119 (:include js2-xml-node)
4120 (:constructor nil)
4121 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4122 (pos js2-ts-cursor)
4123 len
4124 name
4125 attrs)))
4126 "AST node for an E4X XML processing instruction. Not currently used."
4127 name ; a `js2-xml-name-node'
4128 attrs) ; a list of `js2-xml-attr-node'
4129
4130 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4131 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4132
4133 (defun js2-visit-xml-pi-node (n v)
4134 (js2-visit-ast (js2-xml-pi-node-name n) v)
4135 (dolist (attr (js2-xml-pi-node-attrs n))
4136 (js2-visit-ast attr v)))
4137
4138 (defun js2-print-xml-pi-node (n i)
4139 (insert (js2-make-pad i) "<?")
4140 (js2-print-ast (js2-xml-pi-node-name n))
4141 (when (js2-xml-pi-node-attrs n)
4142 (insert " ")
4143 (js2-print-list (js2-xml-pi-node-attrs n)))
4144 (insert "?>"))
4145
4146 (defstruct (js2-xml-cdata-node
4147 (:include js2-xml-node)
4148 (:constructor nil)
4149 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4150 (pos js2-ts-cursor)
4151 len
4152 content)))
4153 "AST node for a CDATA escape section. Not currently used."
4154 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4155
4156 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4157 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4158
4159 (defun js2-visit-xml-cdata-node (n v)
4160 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4161
4162 (defun js2-print-xml-cdata-node (n i)
4163 (insert (js2-make-pad i))
4164 (js2-print-ast (js2-xml-cdata-node-content n)))
4165
4166 (defstruct (js2-xml-attr-node
4167 (:include js2-xml-node)
4168 (:constructor nil)
4169 (:constructor make-js2-attr-node (&key (type js2-XML)
4170 (pos js2-ts-cursor)
4171 len
4172 name
4173 value
4174 eq-pos
4175 quote-type)))
4176 "AST node representing a foo='bar' XML attribute value. Not yet used."
4177 name ; a `js2-xml-name-node'
4178 value ; a `js2-xml-name-node'
4179 eq-pos ; buffer position of "=" sign
4180 quote-type) ; 'single or 'double
4181
4182 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4183 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4184
4185 (defun js2-visit-xml-attr-node (n v)
4186 (js2-visit-ast (js2-xml-attr-node-name n) v)
4187 (js2-visit-ast (js2-xml-attr-node-value n) v))
4188
4189 (defun js2-print-xml-attr-node (n i)
4190 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4191 "'"
4192 "\"")))
4193 (insert (js2-make-pad i))
4194 (js2-print-ast (js2-xml-attr-node-name n) 0)
4195 (insert "=" quote)
4196 (js2-print-ast (js2-xml-attr-node-value n) 0)
4197 (insert quote)))
4198
4199 (defstruct (js2-xml-text-node
4200 (:include js2-xml-node)
4201 (:constructor nil)
4202 (:constructor make-js2-text-node (&key (type js2-XML)
4203 (pos js2-ts-cursor)
4204 len
4205 content)))
4206 "AST node for an E4X XML text node. Not currently used."
4207 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4208
4209 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4210 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4211
4212 (defun js2-visit-xml-text-node (n v)
4213 (js2-visit-ast (js2-xml-text-node-content n) v))
4214
4215 (defun js2-print-xml-text-node (n i)
4216 (insert (js2-make-pad i))
4217 (dolist (kid (js2-xml-text-node-content n))
4218 (js2-print-ast kid)))
4219
4220 (defstruct (js2-xml-comment-node
4221 (:include js2-xml-node)
4222 (:constructor nil)
4223 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4224 (pos js2-ts-cursor)
4225 len)))
4226 "AST node for E4X XML comment. Not currently used.")
4227
4228 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4229 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4230
4231 (defun js2-print-xml-comment (n i)
4232 (insert (js2-make-pad i)
4233 (js2-node-string n)))
4234
4235 ;;; Node utilities
4236
4237 (defsubst js2-node-line (n)
4238 "Fetch the source line number at the start of node N.
4239 This is O(n) in the length of the source buffer; use prudently."
4240 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4241
4242 (defsubst js2-block-node-kid (n i)
4243 "Return child I of node N, or nil if there aren't that many."
4244 (nth i (js2-block-node-kids n)))
4245
4246 (defsubst js2-block-node-first (n)
4247 "Return first child of block node N, or nil if there is none."
4248 (first (js2-block-node-kids n)))
4249
4250 (defun js2-node-root (n)
4251 "Return the root of the AST containing N.
4252 If N has no parent pointer, returns N."
4253 (let ((parent (js2-node-parent n)))
4254 (if parent
4255 (js2-node-root parent)
4256 n)))
4257
4258 (defun js2-node-position-in-parent (node &optional parent)
4259 "Return the position of NODE in parent's block-kids list.
4260 PARENT can be supplied if known. Positioned returned is zero-indexed.
4261 Returns 0 if NODE is not a child of a block statement, or if NODE
4262 is not a statement node."
4263 (let ((p (or parent (js2-node-parent node)))
4264 (i 0))
4265 (if (not (js2-block-node-p p))
4266 i
4267 (or (js2-position node (js2-block-node-kids p))
4268 0))))
4269
4270 (defsubst js2-node-short-name (n)
4271 "Return the short name of node N as a string, e.g. `js2-if-node'."
4272 (substring (symbol-name (aref n 0))
4273 (length "cl-struct-")))
4274
4275 (defsubst js2-node-child-list (node)
4276 "Return the child list for NODE, a lisp list of nodes.
4277 Works for block nodes, array nodes, obj literals, funarg lists,
4278 var decls and try nodes (for catch clauses). Note that you should call
4279 `js2-block-node-kids' on the function body for the body statements.
4280 Returns nil for zero-length child lists or unsupported nodes."
4281 (cond
4282 ((js2-function-node-p node)
4283 (js2-function-node-params node))
4284 ((js2-block-node-p node)
4285 (js2-block-node-kids node))
4286 ((js2-try-node-p node)
4287 (js2-try-node-catch-clauses node))
4288 ((js2-array-node-p node)
4289 (js2-array-node-elems node))
4290 ((js2-object-node-p node)
4291 (js2-object-node-elems node))
4292 ((js2-call-node-p node)
4293 (js2-call-node-args node))
4294 ((js2-new-node-p node)
4295 (js2-new-node-args node))
4296 ((js2-var-decl-node-p node)
4297 (js2-var-decl-node-kids node))
4298 (t
4299 nil)))
4300
4301 (defsubst js2-node-set-child-list (node kids)
4302 "Set the child list for NODE to KIDS."
4303 (cond
4304 ((js2-function-node-p node)
4305 (setf (js2-function-node-params node) kids))
4306 ((js2-block-node-p node)
4307 (setf (js2-block-node-kids node) kids))
4308 ((js2-try-node-p node)
4309 (setf (js2-try-node-catch-clauses node) kids))
4310 ((js2-array-node-p node)
4311 (setf (js2-array-node-elems node) kids))
4312 ((js2-object-node-p node)
4313 (setf (js2-object-node-elems node) kids))
4314 ((js2-call-node-p node)
4315 (setf (js2-call-node-args node) kids))
4316 ((js2-new-node-p node)
4317 (setf (js2-new-node-args node) kids))
4318 ((js2-var-decl-node-p node)
4319 (setf (js2-var-decl-node-kids node) kids))
4320 (t
4321 (error "Unsupported node type: %s" (js2-node-short-name node))))
4322 kids)
4323
4324 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4325 (defconst js2-paren-expr-nodes
4326 '(cl-struct-js2-array-comp-loop-node
4327 cl-struct-js2-array-comp-node
4328 cl-struct-js2-call-node
4329 cl-struct-js2-catch-node
4330 cl-struct-js2-do-node
4331 cl-struct-js2-elem-get-node
4332 cl-struct-js2-for-in-node
4333 cl-struct-js2-for-node
4334 cl-struct-js2-function-node
4335 cl-struct-js2-if-node
4336 cl-struct-js2-let-node
4337 cl-struct-js2-new-node
4338 cl-struct-js2-paren-node
4339 cl-struct-js2-switch-node
4340 cl-struct-js2-while-node
4341 cl-struct-js2-with-node
4342 cl-struct-js2-xml-dot-query-node)
4343 "Node types that can have a parenthesized child expression.
4344 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4345
4346 (defsubst js2-paren-expr-node-p (node)
4347 "Return t for nodes that typically have a parenthesized child expression.
4348 Useful for computing the indentation anchors for arg-lists and conditions.
4349 Note that it may return a false positive, for instance when NODE is
4350 a `js2-new-node' and there are no arguments or parentheses."
4351 (memq (aref node 0) js2-paren-expr-nodes))
4352
4353 ;; Fake polymorphism... yech.
4354 (defsubst js2-node-lp (node)
4355 "Return relative left-paren position for NODE, if applicable.
4356 For `js2-elem-get-node' structs, returns left-bracket position.
4357 Note that the position may be nil in the case of a parse error."
4358 (cond
4359 ((js2-elem-get-node-p node)
4360 (js2-elem-get-node-lb node))
4361 ((js2-loop-node-p node)
4362 (js2-loop-node-lp node))
4363 ((js2-function-node-p node)
4364 (js2-function-node-lp node))
4365 ((js2-if-node-p node)
4366 (js2-if-node-lp node))
4367 ((js2-new-node-p node)
4368 (js2-new-node-lp node))
4369 ((js2-call-node-p node)
4370 (js2-call-node-lp node))
4371 ((js2-paren-node-p node)
4372 (js2-node-pos node))
4373 ((js2-switch-node-p node)
4374 (js2-switch-node-lp node))
4375 ((js2-catch-node-p node)
4376 (js2-catch-node-lp node))
4377 ((js2-let-node-p node)
4378 (js2-let-node-lp node))
4379 ((js2-array-comp-node-p node)
4380 (js2-array-comp-node-lp node))
4381 ((js2-with-node-p node)
4382 (js2-with-node-lp node))
4383 ((js2-xml-dot-query-node-p node)
4384 (1+ (js2-infix-node-op-pos node)))
4385 (t
4386 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4387
4388 ;; Fake polymorphism... blech.
4389 (defsubst js2-node-rp (node)
4390 "Return relative right-paren position for NODE, if applicable.
4391 For `js2-elem-get-node' structs, returns right-bracket position.
4392 Note that the position may be nil in the case of a parse error."
4393 (cond
4394 ((js2-elem-get-node-p node)
4395 (js2-elem-get-node-lb node))
4396 ((js2-loop-node-p node)
4397 (js2-loop-node-rp node))
4398 ((js2-function-node-p node)
4399 (js2-function-node-rp node))
4400 ((js2-if-node-p node)
4401 (js2-if-node-rp node))
4402 ((js2-new-node-p node)
4403 (js2-new-node-rp node))
4404 ((js2-call-node-p node)
4405 (js2-call-node-rp node))
4406 ((js2-paren-node-p node)
4407 (+ (js2-node-pos node) (js2-node-len node)))
4408 ((js2-switch-node-p node)
4409 (js2-switch-node-rp node))
4410 ((js2-catch-node-p node)
4411 (js2-catch-node-rp node))
4412 ((js2-let-node-p node)
4413 (js2-let-node-rp node))
4414 ((js2-array-comp-node-p node)
4415 (js2-array-comp-node-rp node))
4416 ((js2-with-node-p node)
4417 (js2-with-node-rp node))
4418 ((js2-xml-dot-query-node-p node)
4419 (1+ (js2-xml-dot-query-node-rp node)))
4420 (t
4421 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4422
4423 (defsubst js2-node-first-child (node)
4424 "Returns the first element of `js2-node-child-list' for NODE."
4425 (car (js2-node-child-list node)))
4426
4427 (defsubst js2-node-last-child (node)
4428 "Returns the last element of `js2-node-last-child' for NODE."
4429 (car (last (js2-node-child-list node))))
4430
4431 (defun js2-node-prev-sibling (node)
4432 "Return the previous statement in parent.
4433 Works for parents supported by `js2-node-child-list'.
4434 Returns nil if NODE is not in the parent, or PARENT is
4435 not a supported node, or if NODE is the first child."
4436 (let* ((p (js2-node-parent node))
4437 (kids (js2-node-child-list p))
4438 (sib (car kids)))
4439 (while (and kids
4440 (not (eq node (cadr kids))))
4441 (setq kids (cdr kids)
4442 sib (car kids)))
4443 sib))
4444
4445 (defun js2-node-next-sibling (node)
4446 "Return the next statement in parent block.
4447 Returns nil if NODE is not in the block, or PARENT is not
4448 a block node, or if NODE is the last statement."
4449 (let* ((p (js2-node-parent node))
4450 (kids (js2-node-child-list p)))
4451 (while (and kids
4452 (not (eq node (car kids))))
4453 (setq kids (cdr kids)))
4454 (cadr kids)))
4455
4456 (defun js2-node-find-child-before (pos parent &optional after)
4457 "Find the last child that starts before POS in parent.
4458 If AFTER is non-nil, returns first child starting after POS.
4459 POS is an absolute buffer position. PARENT is any node
4460 supported by `js2-node-child-list'.
4461 Returns nil if no applicable child is found."
4462 (let ((kids (if (js2-function-node-p parent)
4463 (js2-block-node-kids (js2-function-node-body parent))
4464 (js2-node-child-list parent)))
4465 (beg (if (js2-function-node-p parent)
4466 (js2-node-abs-pos (js2-function-node-body parent))
4467 (js2-node-abs-pos parent)))
4468 kid
4469 result
4470 fn
4471 (continue t))
4472 (setq fn (if after '>= '<))
4473 (while (and kids continue)
4474 (setq kid (car kids))
4475 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4476 (setq result kid
4477 continue (if after nil t))
4478 (setq continue (if after t nil)))
4479 (setq kids (cdr kids)))
4480 result))
4481
4482 (defun js2-node-find-child-after (pos parent)
4483 "Find first child that starts after POS in parent.
4484 POS is an absolute buffer position. PARENT is any node
4485 supported by `js2-node-child-list'.
4486 Returns nil if no applicable child is found."
4487 (js2-node-find-child-before pos parent 'after))
4488
4489 (defun js2-node-replace-child (pos parent new-node)
4490 "Replace node at index POS in PARENT with NEW-NODE.
4491 Only works for parents supported by `js2-node-child-list'."
4492 (let ((kids (js2-node-child-list parent))
4493 (i 0))
4494 (while (< i pos)
4495 (setq kids (cdr kids)
4496 i (1+ i)))
4497 (setcar kids new-node)
4498 (js2-node-add-children parent new-node)))
4499
4500 (defun js2-node-buffer (n)
4501 "Return the buffer associated with AST N.
4502 Returns nil if the buffer is not set as a property on the root
4503 node, or if parent links were not recorded during parsing."
4504 (let ((root (js2-node-root n)))
4505 (and root
4506 (js2-ast-root-p root)
4507 (js2-ast-root-buffer root))))
4508
4509 (defsubst js2-block-node-push (n kid)
4510 "Push js2-node KID onto the end of js2-block-node N's child list.
4511 KID is always added to the -end- of the kids list.
4512 Function also calls `js2-node-add-children' to add the parent link."
4513 (let ((kids (js2-node-child-list n)))
4514 (if kids
4515 (setcdr kids (nconc (cdr kids) (list kid)))
4516 (js2-node-set-child-list n (list kid)))
4517 (js2-node-add-children n kid)))
4518
4519 (defun js2-node-string (node)
4520 (let ((buf (js2-node-buffer node))
4521 pos)
4522 (unless buf
4523 (error "No buffer available for node %s" node))
4524 (with-current-buffer buf
4525 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4526 (+ pos (js2-node-len node))))))
4527
4528 ;; Container for storing the node we're looking for in a traversal.
4529 (js2-deflocal js2-discovered-node nil)
4530
4531 ;; Keep track of absolute node position during traversals.
4532 (js2-deflocal js2-visitor-offset nil)
4533
4534 (js2-deflocal js2-node-search-point nil)
4535
4536 (when js2-mode-dev-mode-p
4537 (defun js2-find-node-at-point ()
4538 (interactive)
4539 (let ((node (js2-node-at-point)))
4540 (message "%s" (or node "No node found at point"))))
4541 (defun js2-node-name-at-point ()
4542 (interactive)
4543 (let ((node (js2-node-at-point)))
4544 (message "%s" (if node
4545 (js2-node-short-name node)
4546 "No node found at point.")))))
4547
4548 (defun js2-node-at-point (&optional pos skip-comments)
4549 "Return AST node at POS, a buffer position, defaulting to current point.
4550 The `js2-mode-ast' variable must be set to the current parse tree.
4551 Signals an error if the AST (`js2-mode-ast') is nil.
4552 Always returns a node - if it can't find one, it returns the root.
4553 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4554 (let ((ast js2-mode-ast)
4555 result)
4556 (unless ast
4557 (error "No JavaScript AST available"))
4558 ;; Look through comments first, since they may be inside nodes that
4559 ;; would otherwise report a match.
4560 (setq pos (or pos (point))
4561 result (if (> pos (js2-node-abs-end ast))
4562 ast
4563 (if (not skip-comments)
4564 (js2-comment-at-point pos))))
4565 (unless result
4566 (setq js2-discovered-node nil
4567 js2-visitor-offset 0
4568 js2-node-search-point pos)
4569 (unwind-protect
4570 (catch 'js2-visit-done
4571 (js2-visit-ast ast #'js2-node-at-point-visitor))
4572 (setq js2-visitor-offset nil
4573 js2-node-search-point nil))
4574 (setq result js2-discovered-node))
4575 ;; may have found a comment beyond end of last child node,
4576 ;; since visiting the ast-root looks at the comment-list last.
4577 (if (and skip-comments
4578 (js2-comment-node-p result))
4579 (setq result nil))
4580 (or result js2-mode-ast)))
4581
4582 (defun js2-node-at-point-visitor (node end-p)
4583 (let ((rel-pos (js2-node-pos node))
4584 abs-pos
4585 abs-end
4586 (point js2-node-search-point))
4587 (cond
4588 (end-p
4589 ;; this evaluates to a non-nil return value, even if it's zero
4590 (decf js2-visitor-offset rel-pos))
4591 ;; we already looked for comments before visiting, and don't want them now
4592 ((js2-comment-node-p node)
4593 nil)
4594 (t
4595 (setq abs-pos (incf js2-visitor-offset rel-pos)
4596 ;; we only want to use the node if the point is before
4597 ;; the last character position in the node, so we decrement
4598 ;; the absolute end by 1.
4599 abs-end (+ abs-pos (js2-node-len node) -1))
4600 (cond
4601 ;; If this node starts after search-point, stop the search.
4602 ((> abs-pos point)
4603 (throw 'js2-visit-done nil))
4604 ;; If this node ends before the search-point, don't check kids.
4605 ((> point abs-end)
4606 nil)
4607 (t
4608 ;; Otherwise point is within this node, possibly in a child.
4609 (setq js2-discovered-node node)
4610 t)))))) ; keep processing kids to look for more specific match
4611
4612 (defsubst js2-block-comment-p (node)
4613 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4614 (and (js2-comment-node-p node)
4615 (memq (js2-comment-node-format node) '(jsdoc block))))
4616
4617 ;; TODO: put the comments in a vector and binary-search them instead
4618 (defun js2-comment-at-point (&optional pos)
4619 "Look through scanned comment nodes for one containing POS.
4620 POS is a buffer position that defaults to current point.
4621 Function returns nil if POS was not in any comment node."
4622 (let ((ast js2-mode-ast)
4623 (x (or pos (point)))
4624 beg
4625 end)
4626 (unless ast
4627 (error "No JavaScript AST available"))
4628 (catch 'done
4629 ;; Comments are stored in lexical order.
4630 (dolist (comment (js2-ast-root-comments ast) nil)
4631 (setq beg (js2-node-abs-pos comment)
4632 end (+ beg (js2-node-len comment)))
4633 (if (and (>= x beg)
4634 (<= x end))
4635 (throw 'done comment))))))
4636
4637 (defun js2-mode-find-parent-fn (node)
4638 "Find function enclosing NODE.
4639 Returns nil if NODE is not inside a function."
4640 (setq node (js2-node-parent node))
4641 (while (and node (not (js2-function-node-p node)))
4642 (setq node (js2-node-parent node)))
4643 (and (js2-function-node-p node) node))
4644
4645 (defun js2-mode-find-enclosing-fn (node)
4646 "Find function or root enclosing NODE."
4647 (if (js2-ast-root-p node)
4648 node
4649 (setq node (js2-node-parent node))
4650 (while (not (or (js2-ast-root-p node)
4651 (js2-function-node-p node)))
4652 (setq node (js2-node-parent node)))
4653 node))
4654
4655 (defun js2-mode-find-enclosing-node (beg end)
4656 "Find script or function fully enclosing BEG and END."
4657 (let ((node (js2-node-at-point beg))
4658 pos
4659 (continue t))
4660 (while continue
4661 (if (or (js2-ast-root-p node)
4662 (and (js2-function-node-p node)
4663 (<= (setq pos (js2-node-abs-pos node)) beg)
4664 (>= (+ pos (js2-node-len node)) end)))
4665 (setq continue nil)
4666 (setq node (js2-node-parent node))))
4667 node))
4668
4669 (defun js2-node-parent-script-or-fn (node)
4670 "Find script or function immediately enclosing NODE.
4671 If NODE is the ast-root, returns nil."
4672 (if (js2-ast-root-p node)
4673 nil
4674 (setq node (js2-node-parent node))
4675 (while (and node (not (or (js2-function-node-p node)
4676 (js2-script-node-p node))))
4677 (setq node (js2-node-parent node)))
4678 node))
4679
4680 (defsubst js2-nested-function-p (node)
4681 "Return t if NODE is a nested function, or is inside a nested function."
4682 (unless (js2-ast-root-p node)
4683 (js2-function-node-p (if (js2-function-node-p node)
4684 (js2-node-parent-script-or-fn node)
4685 (js2-node-parent-script-or-fn
4686 (js2-node-parent-script-or-fn node))))))
4687
4688 (defsubst js2-function-param-node-p (node)
4689 "Return non-nil if NODE is a param node of a `js2-function-node'."
4690 (let ((parent (js2-node-parent node)))
4691 (and parent
4692 (js2-function-node-p parent)
4693 (memq node (js2-function-node-params parent)))))
4694
4695 (defsubst js2-mode-shift-kids (kids start offset)
4696 (dolist (kid kids)
4697 (if (> (js2-node-pos kid) start)
4698 (incf (js2-node-pos kid) offset))))
4699
4700 (defsubst js2-mode-shift-children (parent start offset)
4701 "Update start-positions of all children of PARENT beyond START."
4702 (let ((root (js2-node-root parent)))
4703 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4704 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4705
4706 (defsubst js2-node-is-descendant (node ancestor)
4707 "Return t if NODE is a descendant of ANCESTOR."
4708 (while (and node
4709 (not (eq node ancestor)))
4710 (setq node (js2-node-parent node)))
4711 node)
4712
4713 ;;; visitor infrastructure
4714
4715 (defun js2-visit-none (node callback)
4716 "Visitor for AST node that have no node children."
4717 nil)
4718
4719 (defun js2-print-none (node indent)
4720 "Visitor for AST node with no printed representation.")
4721
4722 (defun js2-print-body (node indent)
4723 "Print a statement, or a block without braces."
4724 (if (js2-block-node-p node)
4725 (dolist (kid (js2-block-node-kids node))
4726 (js2-print-ast kid indent))
4727 (js2-print-ast node indent)))
4728
4729 (defun js2-print-list (args &optional delimiter)
4730 (loop with len = (length args)
4731 for arg in args
4732 for count from 1
4733 do
4734 (js2-print-ast arg 0)
4735 (if (< count len)
4736 (insert (or delimiter ", ")))))
4737
4738 (defun js2-print-tree (ast)
4739 "Prints an AST to the current buffer.
4740 Makes `js2-ast-parent-nodes' available to the printer functions."
4741 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4742 (js2-print-ast ast)))
4743
4744 (defun js2-print-ast (node &optional indent)
4745 "Helper function for printing AST nodes.
4746 Requires `js2-ast-parent-nodes' to be non-nil.
4747 You should use `js2-print-tree' instead of this function."
4748 (let ((printer (get (aref node 0) 'js2-printer))
4749 (i (or indent 0))
4750 (pos (js2-node-abs-pos node)))
4751 ;; TODO: wedge comments in here somewhere
4752 (if printer
4753 (funcall printer node i))))
4754
4755 (defconst js2-side-effecting-tokens
4756 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4757 (dolist (tt (list js2-ASSIGN
4758 js2-ASSIGN_ADD
4759 js2-ASSIGN_BITAND
4760 js2-ASSIGN_BITOR
4761 js2-ASSIGN_BITXOR
4762 js2-ASSIGN_DIV
4763 js2-ASSIGN_LSH
4764 js2-ASSIGN_MOD
4765 js2-ASSIGN_MUL
4766 js2-ASSIGN_RSH
4767 js2-ASSIGN_SUB
4768 js2-ASSIGN_URSH
4769 js2-BLOCK
4770 js2-BREAK
4771 js2-CALL
4772 js2-CATCH
4773 js2-CATCH_SCOPE
4774 js2-CONST
4775 js2-CONTINUE
4776 js2-DEBUGGER
4777 js2-DEC
4778 js2-DELPROP
4779 js2-DEL_REF
4780 js2-DO
4781 js2-ELSE
4782 js2-EMPTY
4783 js2-ENTERWITH
4784 js2-EXPORT
4785 js2-EXPR_RESULT
4786 js2-FINALLY
4787 js2-FOR
4788 js2-FUNCTION
4789 js2-GOTO
4790 js2-IF
4791 js2-IFEQ
4792 js2-IFNE
4793 js2-IMPORT
4794 js2-INC
4795 js2-JSR
4796 js2-LABEL
4797 js2-LEAVEWITH
4798 js2-LET
4799 js2-LETEXPR
4800 js2-LOCAL_BLOCK
4801 js2-LOOP
4802 js2-NEW
4803 js2-REF_CALL
4804 js2-RETHROW
4805 js2-RETURN
4806 js2-RETURN_RESULT
4807 js2-SEMI
4808 js2-SETELEM
4809 js2-SETELEM_OP
4810 js2-SETNAME
4811 js2-SETPROP
4812 js2-SETPROP_OP
4813 js2-SETVAR
4814 js2-SET_REF
4815 js2-SET_REF_OP
4816 js2-SWITCH
4817 js2-TARGET
4818 js2-THROW
4819 js2-TRY
4820 js2-VAR
4821 js2-WHILE
4822 js2-WITH
4823 js2-WITHEXPR
4824 js2-YIELD))
4825 (aset tokens tt t))
4826 (if js2-instanceof-has-side-effects
4827 (aset tokens js2-INSTANCEOF t))
4828 tokens))
4829
4830 (defun js2-node-has-side-effects (node)
4831 "Return t if NODE has side effects."
4832 (when node ; makes it easier to handle malformed expressions
4833 (let ((tt (js2-node-type node)))
4834 (cond
4835 ;; This doubtless needs some work, since EXPR_VOID is used
4836 ;; in several ways in Rhino, and I may not have caught them all.
4837 ;; I'll wait for people to notice incorrect warnings.
4838 ((and (= tt js2-EXPR_VOID)
4839 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4840 (let ((expr (js2-expr-stmt-node-expr node)))
4841 (or (js2-node-has-side-effects expr)
4842 (when (js2-string-node-p expr)
4843 (string= "use strict" (js2-string-node-value expr))))))
4844 ((= tt js2-COMMA)
4845 (js2-node-has-side-effects (js2-infix-node-right node)))
4846 ((or (= tt js2-AND)
4847 (= tt js2-OR))
4848 (or (js2-node-has-side-effects (js2-infix-node-right node))
4849 (js2-node-has-side-effects (js2-infix-node-left node))))
4850 ((= tt js2-HOOK)
4851 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4852 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4853 ((js2-paren-node-p node)
4854 (js2-node-has-side-effects (js2-paren-node-expr node)))
4855 ((= tt js2-ERROR) ; avoid cascaded error messages
4856 nil)
4857 (t
4858 (aref js2-side-effecting-tokens tt))))))
4859
4860 (defun js2-member-expr-leftmost-name (node)
4861 "For an expr such as foo.bar.baz, return leftmost node foo.
4862 NODE is any `js2-node' object. If it represents a member expression,
4863 which is any sequence of property gets, element-gets, function calls,
4864 or xml descendants/filter operators, then we look at the lexically
4865 leftmost (first) node in the chain. If it is a name-node we return it.
4866 Note that NODE can be a raw name-node and it will be returned as well.
4867 If NODE is not a name-node or member expression, or if it is a member
4868 expression whose leftmost target is not a name node, returns nil."
4869 (let ((continue t)
4870 result)
4871 (while (and continue (not result))
4872 (cond
4873 ((js2-name-node-p node)
4874 (setq result node))
4875 ((js2-prop-get-node-p node)
4876 (setq node (js2-prop-get-node-left node)))
4877 ;; TODO: handle call-nodes, xml-nodes, others?
4878 (t
4879 (setq continue nil))))
4880 result))
4881
4882 (defconst js2-stmt-node-types
4883 (list js2-BLOCK
4884 js2-BREAK
4885 js2-CONTINUE
4886 js2-DEFAULT ; e4x "default xml namespace" statement
4887 js2-DO
4888 js2-EXPR_RESULT
4889 js2-EXPR_VOID
4890 js2-FOR
4891 js2-IF
4892 js2-RETURN
4893 js2-SWITCH
4894 js2-THROW
4895 js2-TRY
4896 js2-WHILE
4897 js2-WITH)
4898 "Node types that only appear in statement contexts.
4899 The list does not include nodes that always appear as the child
4900 of another specific statement type, such as switch-cases,
4901 catch and finally blocks, and else-clauses. The list also excludes
4902 nodes like yield, let and var, which may appear in either expression
4903 or statement context, and in the latter context always have a
4904 `js2-expr-stmt-node' parent. Finally, the list does not include
4905 functions or scripts, which are treated separately from statements
4906 by the JavaScript parser and runtime.")
4907
4908 (defun js2-stmt-node-p (node)
4909 "Heuristic for figuring out if NODE is a statement.
4910 Some node types can appear in either an expression context or a
4911 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4912 For these node types in a statement context, the parent will be a
4913 `js2-expr-stmt-node'.
4914 Functions aren't included in the check."
4915 (memq (js2-node-type node) js2-stmt-node-types))
4916
4917 (defsubst js2-mode-find-first-stmt (node)
4918 "Search upward starting from NODE looking for a statement.
4919 For purposes of this function, a `js2-function-node' counts."
4920 (while (not (or (js2-stmt-node-p node)
4921 (js2-function-node-p node)))
4922 (setq node (js2-node-parent node)))
4923 node)
4924
4925 (defun js2-node-parent-stmt (node)
4926 "Return the node's first ancestor that is a statement.
4927 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4928 appearing in a statement context will have a parent that is a
4929 `js2-expr-stmt-node' that will be returned by this function."
4930 (let ((parent (js2-node-parent node)))
4931 (if (or (null parent)
4932 (js2-stmt-node-p parent)
4933 (and (js2-function-node-p parent)
4934 (not (eq (js2-function-node-form parent)
4935 'FUNCTION_EXPRESSION))))
4936 parent
4937 (js2-node-parent-stmt parent))))
4938
4939 ;; In the Mozilla Rhino sources, Roshan James writes:
4940 ;; Does consistent-return analysis on the function body when strict mode is
4941 ;; enabled.
4942 ;;
4943 ;; function (x) { return (x+1) }
4944 ;;
4945 ;; is ok, but
4946 ;;
4947 ;; function (x) { if (x < 0) return (x+1); }
4948 ;;
4949 ;; is not because the function can potentially return a value when the
4950 ;; condition is satisfied and if not, the function does not explicitly
4951 ;; return a value.
4952 ;;
4953 ;; This extends to checking mismatches such as "return" and "return <value>"
4954 ;; used in the same function. Warnings are not emitted if inconsistent
4955 ;; returns exist in code that can be statically shown to be unreachable.
4956 ;; Ex.
4957 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4958 ;;
4959 ;; emits no warning. However if the loop had a break statement, then a
4960 ;; warning would be emitted.
4961 ;;
4962 ;; The consistency analysis looks at control structures such as loops, ifs,
4963 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4964 ;; warns the user about an inconsistent set of termination possibilities.
4965 ;;
4966 ;; These flags enumerate the possible ways a statement/function can
4967 ;; terminate. These flags are used by endCheck() and by the Parser to
4968 ;; detect inconsistent return usage.
4969 ;;
4970 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4971 ;; able to execute (example: throw, continue)
4972 ;;
4973 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4974 ;; next one. Statement such as return dont. A compound statement may have
4975 ;; some branch that drops off control to the next statement.
4976 ;;
4977 ;; END_RETURNS indicates that the statement can return with no value.
4978 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4979 ;;
4980 ;; A compound statement such as
4981 ;; if (condition) {
4982 ;; return value;
4983 ;; }
4984 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4985
4986 (defconst js2-END_UNREACHED 0)
4987 (defconst js2-END_DROPS_OFF 1)
4988 (defconst js2-END_RETURNS 2)
4989 (defconst js2-END_RETURNS_VALUE 4)
4990 (defconst js2-END_YIELDS 8)
4991
4992 (defun js2-has-consistent-return-usage (node)
4993 "Check that every return usage in a function body is consistent.
4994 Returns t if the function satisfies strict mode requirement."
4995 (let ((n (js2-end-check node)))
4996 ;; either it doesn't return a value in any branch...
4997 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4998 ;; or it returns a value (or is unreached) at every branch
4999 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5000 js2-END_RETURNS
5001 js2-END_YIELDS)))))
5002
5003 (defun js2-end-check-if (node)
5004 "Returns in the then and else blocks must be consistent with each other.
5005 If there is no else block, then the return statement can fall through.
5006 Returns logical OR of END_* flags"
5007 (let ((th (js2-if-node-then-part node))
5008 (el (js2-if-node-else-part node)))
5009 (if (null th)
5010 js2-END_UNREACHED
5011 (logior (js2-end-check th) (if el
5012 (js2-end-check el)
5013 js2-END_DROPS_OFF)))))
5014
5015 (defun js2-end-check-switch (node)
5016 "Consistency of return statements is checked between the case statements.
5017 If there is no default, then the switch can fall through. If there is a
5018 default, we check to see if all code paths in the default return or if
5019 there is a code path that can fall through.
5020 Returns logical OR of END_* flags."
5021 (let ((rv js2-END_UNREACHED)
5022 default-case)
5023 ;; examine the cases
5024 (catch 'break
5025 (dolist (c (js2-switch-node-cases node))
5026 (if (js2-case-node-expr c)
5027 (js2-set-flag rv (js2-end-check-block c))
5028 (setq default-case c)
5029 (throw 'break nil))))
5030 ;; we don't care how the cases drop into each other
5031 (js2-clear-flag rv js2-END_DROPS_OFF)
5032 ;; examine the default
5033 (js2-set-flag rv (if default-case
5034 (js2-end-check default-case)
5035 js2-END_DROPS_OFF))
5036 rv))
5037
5038 (defun js2-end-check-try (node)
5039 "If the block has a finally, return consistency is checked in the
5040 finally block. If all code paths in the finally return, then the
5041 returns in the try-catch blocks don't matter. If there is a code path
5042 that does not return or if there is no finally block, the returns
5043 of the try and catch blocks are checked for mismatch.
5044 Returns logical OR of END_* flags."
5045 (let ((finally (js2-try-node-finally-block node))
5046 rv)
5047 ;; check the finally if it exists
5048 (setq rv (if finally
5049 (js2-end-check (js2-finally-node-body finally))
5050 js2-END_DROPS_OFF))
5051 ;; If the finally block always returns, then none of the returns
5052 ;; in the try or catch blocks matter.
5053 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5054 (js2-clear-flag rv js2-END_DROPS_OFF)
5055 ;; examine the try block
5056 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5057 ;; check each catch block
5058 (dolist (cb (js2-try-node-catch-clauses node))
5059 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5060 rv))
5061
5062 (defun js2-end-check-loop (node)
5063 "Return statement in the loop body must be consistent. The default
5064 assumption for any kind of a loop is that it will eventually terminate.
5065 The only exception is a loop with a constant true condition. Code that
5066 follows such a loop is examined only if one can statically determine
5067 that there is a break out of the loop.
5068
5069 for(... ; ... ; ...) {}
5070 for(... in ... ) {}
5071 while(...) { }
5072 do { } while(...)
5073
5074 Returns logical OR of END_* flags."
5075 (let ((rv (js2-end-check (js2-loop-node-body node)))
5076 (condition (cond
5077 ((js2-while-node-p node)
5078 (js2-while-node-condition node))
5079 ((js2-do-node-p node)
5080 (js2-do-node-condition node))
5081 ((js2-for-node-p node)
5082 (js2-for-node-condition node)))))
5083
5084 ;; check to see if the loop condition is always true
5085 (if (and condition
5086 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5087 (js2-clear-flag rv js2-END_DROPS_OFF))
5088
5089 ;; look for effect of breaks
5090 (js2-set-flag rv (js2-node-get-prop node
5091 'CONTROL_BLOCK_PROP
5092 js2-END_UNREACHED))
5093 rv))
5094
5095 (defun js2-end-check-block (node)
5096 "A general block of code is examined statement by statement.
5097 If any statement (even a compound one) returns in all branches, then
5098 subsequent statements are not examined.
5099 Returns logical OR of END_* flags."
5100 (let* ((rv js2-END_DROPS_OFF)
5101 (kids (js2-block-node-kids node))
5102 (n (car kids)))
5103 ;; Check each statment. If the statement can continue onto the next
5104 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5105 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5106 (js2-clear-flag rv js2-END_DROPS_OFF)
5107 (js2-set-flag rv (js2-end-check n))
5108 (setq kids (cdr kids)
5109 n (car kids)))
5110 rv))
5111
5112 (defun js2-end-check-label (node)
5113 "A labeled statement implies that there may be a break to the label.
5114 The function processes the labeled statement and then checks the
5115 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5116 particular label.
5117 Returns logical OR of END_* flags."
5118 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5119 (logior rv (js2-node-get-prop node
5120 'CONTROL_BLOCK_PROP
5121 js2-END_UNREACHED))))
5122
5123 (defun js2-end-check-break (node)
5124 "When a break is encountered annotate the statement being broken
5125 out of by setting its CONTROL_BLOCK_PROP property.
5126 Returns logical OR of END_* flags."
5127 (and (js2-break-node-target node)
5128 (js2-node-set-prop (js2-break-node-target node)
5129 'CONTROL_BLOCK_PROP
5130 js2-END_DROPS_OFF))
5131 js2-END_UNREACHED)
5132
5133 (defun js2-end-check (node)
5134 "Examine the body of a function, doing a basic reachability analysis.
5135 Returns a combination of flags END_* flags that indicate
5136 how the function execution can terminate. These constitute only the
5137 pessimistic set of termination conditions. It is possible that at
5138 runtime certain code paths will never be actually taken. Hence this
5139 analysis will flag errors in cases where there may not be errors.
5140 Returns logical OR of END_* flags"
5141 (let (kid)
5142 (cond
5143 ((js2-break-node-p node)
5144 (js2-end-check-break node))
5145 ((js2-expr-stmt-node-p node)
5146 (if (setq kid (js2-expr-stmt-node-expr node))
5147 (js2-end-check kid)
5148 js2-END_DROPS_OFF))
5149 ((or (js2-continue-node-p node)
5150 (js2-throw-node-p node))
5151 js2-END_UNREACHED)
5152 ((js2-return-node-p node)
5153 (if (setq kid (js2-return-node-retval node))
5154 js2-END_RETURNS_VALUE
5155 js2-END_RETURNS))
5156 ((js2-loop-node-p node)
5157 (js2-end-check-loop node))
5158 ((js2-switch-node-p node)
5159 (js2-end-check-switch node))
5160 ((js2-labeled-stmt-node-p node)
5161 (js2-end-check-label node))
5162 ((js2-if-node-p node)
5163 (js2-end-check-if node))
5164 ((js2-try-node-p node)
5165 (js2-end-check-try node))
5166 ((js2-block-node-p node)
5167 (if (null (js2-block-node-kids node))
5168 js2-END_DROPS_OFF
5169 (js2-end-check-block node)))
5170 ((js2-yield-node-p node)
5171 js2-END_YIELDS)
5172 (t
5173 js2-END_DROPS_OFF))))
5174
5175 (defun js2-always-defined-boolean-p (node)
5176 "Check if NODE always evaluates to true or false in boolean context.
5177 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5178 nor always false."
5179 (let ((tt (js2-node-type node))
5180 num)
5181 (cond
5182 ((or (= tt js2-FALSE) (= tt js2-NULL))
5183 'ALWAYS_FALSE)
5184 ((= tt js2-TRUE)
5185 'ALWAYS_TRUE)
5186 ((= tt js2-NUMBER)
5187 (setq num (js2-number-node-num-value node))
5188 (if (and (not (eq num 0.0e+NaN))
5189 (not (zerop num)))
5190 'ALWAYS_TRUE
5191 'ALWAYS_FALSE))
5192 (t
5193 nil))))
5194
5195 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5196 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5197
5198 (defvar js2-tokens nil
5199 "List of all defined token names.") ; initialized in `js2-token-names'
5200
5201 (defconst js2-token-names
5202 (let* ((names (make-vector js2-num-tokens -1))
5203 (case-fold-search nil) ; only match js2-UPPER_CASE
5204 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5205 (loop for sym in syms
5206 for i from 0
5207 do
5208 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5209 (not (boundp sym)))
5210 (aset names (symbol-value sym) ; code, e.g. 152
5211 (downcase
5212 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5213 (push sym js2-tokens)))
5214 names)
5215 "Vector mapping int values to token string names, sans `js2-' prefix.")
5216
5217 (defun js2-token-name (tok)
5218 "Return a string name for TOK, a token symbol or code.
5219 Signals an error if it's not a recognized token."
5220 (let ((code tok))
5221 (if (symbolp tok)
5222 (setq code (symbol-value tok)))
5223 (if (eq code -1)
5224 "ERROR"
5225 (if (and (numberp code)
5226 (not (minusp code))
5227 (< code js2-num-tokens))
5228 (aref js2-token-names code)
5229 (error "Invalid token: %s" code)))))
5230
5231 (defsubst js2-token-sym (tok)
5232 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5233 (intern (js2-token-name tok)))
5234
5235 (defconst js2-token-codes
5236 (let ((table (make-hash-table :test 'eq :size 256)))
5237 (loop for name across js2-token-names
5238 for sym = (intern (concat "js2-" (upcase name)))
5239 do
5240 (puthash sym (symbol-value sym) table))
5241 ;; clean up a few that are "wrong" in Rhino's token codes
5242 (puthash 'js2-DELETE js2-DELPROP table)
5243 table)
5244 "Hashtable mapping token symbols to their bytecodes.")
5245
5246 (defsubst js2-token-code (sym)
5247 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5248 (or (gethash sym js2-token-codes)
5249 (error "Invalid token symbol: %s " sym))) ; signal code bug
5250
5251 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5252 (setq js2-token-end js2-ts-cursor)
5253 (js2-report-error msg nil
5254 (or beg js2-token-beg)
5255 (or len (- js2-token-end js2-token-beg)))
5256 (unless no-throw
5257 (throw 'return js2-ERROR)))
5258
5259 (defsubst js2-get-string-from-buffer ()
5260 "Reverse the char accumulator and return it as a string."
5261 (setq js2-token-end js2-ts-cursor)
5262 (if js2-ts-string-buffer
5263 (apply #'string (nreverse js2-ts-string-buffer))
5264 ""))
5265
5266 ;; TODO: could potentially avoid a lot of consing by allocating a
5267 ;; char buffer the way Rhino does.
5268 (defsubst js2-add-to-string (c)
5269 (push c js2-ts-string-buffer))
5270
5271 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5272 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5273 ;; any other character: when it's not part of the current token, we
5274 ;; unget it, allowing it to be read again by the following call.
5275 (defsubst js2-unget-char ()
5276 (decf js2-ts-cursor))
5277
5278 ;; Rhino distinguishes \r and \n line endings. We don't need to
5279 ;; because we only scan from Emacs buffers, which always use \n.
5280 (defsubst js2-get-char ()
5281 "Read and return the next character from the input buffer.
5282 Increments `js2-ts-lineno' if the return value is a newline char.
5283 Updates `js2-ts-cursor' to the point after the returned char.
5284 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5285 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5286 (let (c)
5287 ;; check for end of buffer
5288 (if (>= js2-ts-cursor (point-max))
5289 (setq js2-ts-hit-eof t
5290 js2-ts-cursor (1+ js2-ts-cursor)
5291 c js2-EOF_CHAR) ; return value
5292 ;; otherwise read next char
5293 (setq c (char-before (incf js2-ts-cursor)))
5294 ;; if we read a newline, update counters
5295 (if (= c ?\n)
5296 (setq js2-ts-line-start js2-ts-cursor
5297 js2-ts-lineno (1+ js2-ts-lineno)))
5298 ;; TODO: skip over format characters
5299 c)))
5300
5301 (defsubst js2-read-unicode-escape ()
5302 "Read a \\uNNNN sequence from the input.
5303 Assumes the ?\ and ?u have already been read.
5304 Returns the unicode character, or nil if it wasn't a valid character.
5305 Doesn't change the values of any scanner variables."
5306 ;; I really wish I knew a better way to do this, but I can't
5307 ;; find the Emacs function that takes a 16-bit int and converts
5308 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5309 ;; Have to first check that it's 4 hex characters or it may stop
5310 ;; the read early.
5311 (ignore-errors
5312 (let ((s (buffer-substring-no-properties js2-ts-cursor
5313 (+ 4 js2-ts-cursor))))
5314 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5315 (read (concat "?\\u" s))))))
5316
5317 (defsubst js2-match-char (test)
5318 "Consume and return next character if it matches TEST, a character.
5319 Returns nil and consumes nothing if TEST is not the next character."
5320 (let ((c (js2-get-char)))
5321 (if (eq c test)
5322 t
5323 (js2-unget-char)
5324 nil)))
5325
5326 (defsubst js2-peek-char ()
5327 (prog1
5328 (js2-get-char)
5329 (js2-unget-char)))
5330
5331 (defsubst js2-java-identifier-start-p (c)
5332 (or
5333 (memq c '(?$ ?_))
5334 (js2-char-uppercase-p c)
5335 (js2-char-lowercase-p c)))
5336
5337 (defsubst js2-java-identifier-part-p (c)
5338 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5339 ;; TODO: make me Unicode-friendly. See comments above.
5340 (or
5341 (memq c '(?$ ?_))
5342 (js2-char-uppercase-p c)
5343 (js2-char-lowercase-p c)
5344 (and (>= c ?0) (<= c ?9))))
5345
5346 (defsubst js2-alpha-p (c)
5347 (cond ((and (<= ?A c) (<= c ?Z)) t)
5348 ((and (<= ?a c) (<= c ?z)) t)
5349 (t nil)))
5350
5351 (defsubst js2-digit-p (c)
5352 (and (<= ?0 c) (<= c ?9)))
5353
5354 (defsubst js2-js-space-p (c)
5355 (if (<= c 127)
5356 (memq c '(#x20 #x9 #xB #xC #xD))
5357 (or
5358 (eq c #xA0)
5359 ;; TODO: change this nil to check for Unicode space character
5360 nil)))
5361
5362 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5363
5364 (defsubst js2-skip-line ()
5365 "Skip to end of line"
5366 (let (c)
5367 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5368 (js2-unget-char)
5369 (setq js2-token-end js2-ts-cursor)))
5370
5371 (defun js2-init-scanner (&optional buf line)
5372 "Create token stream for BUF starting on LINE.
5373 BUF defaults to current-buffer and line defaults to 1.
5374
5375 A buffer can only have one scanner active at a time, which yields
5376 dramatically simpler code than using a defstruct. If you need to
5377 have simultaneous scanners in a buffer, copy the regions to scan
5378 into temp buffers."
5379 (save-excursion
5380 (when buf
5381 (set-buffer buf))
5382 (setq js2-ts-dirty-line nil
5383 js2-ts-regexp-flags nil
5384 js2-ts-string ""
5385 js2-ts-number nil
5386 js2-ts-hit-eof nil
5387 js2-ts-line-start 0
5388 js2-ts-lineno (or line 1)
5389 js2-ts-line-end-char -1
5390 js2-ts-cursor (point-min)
5391 js2-ts-is-xml-attribute nil
5392 js2-ts-xml-is-tag-content nil
5393 js2-ts-xml-open-tags-count 0
5394 js2-ts-string-buffer nil)))
5395
5396 ;; This function uses the cached op, string and number fields in
5397 ;; TokenStream; if getToken has been called since the passed token
5398 ;; was scanned, the op or string printed may be incorrect.
5399 (defun js2-token-to-string (token)
5400 ;; Not sure where this function is used in Rhino. Not tested.
5401 (if (not js2-debug-print-trees)
5402 ""
5403 (let ((name (js2-token-name token)))
5404 (cond
5405 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5406 (concat name " `" js2-ts-string "'"))
5407 ((eq token js2-NUMBER)
5408 (format "NUMBER %g" js2-ts-number))
5409 (t
5410 name)))))
5411
5412 (defconst js2-keywords
5413 '(break
5414 case catch const continue
5415 debugger default delete do
5416 else enum
5417 false finally for function
5418 if in instanceof import
5419 let
5420 new null
5421 return
5422 switch
5423 this throw true try typeof
5424 var void
5425 while with
5426 yield))
5427
5428 ;; Token names aren't exactly the same as the keywords, unfortunately.
5429 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5430 (defconst js2-kwd-tokens
5431 (let ((table (make-vector js2-num-tokens nil))
5432 (tokens
5433 (list js2-BREAK
5434 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5435 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5436 js2-ELSE
5437 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5438 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5439 js2-LET
5440 js2-NEW js2-NULL
5441 js2-RETURN
5442 js2-SWITCH
5443 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5444 js2-VAR
5445 js2-WHILE js2-WITH
5446 js2-YIELD)))
5447 (dolist (i tokens)
5448 (aset table i 'font-lock-keyword-face))
5449 (aset table js2-STRING 'font-lock-string-face)
5450 (aset table js2-REGEXP 'font-lock-string-face)
5451 (aset table js2-COMMENT 'font-lock-comment-face)
5452 (aset table js2-THIS 'font-lock-builtin-face)
5453 (aset table js2-VOID 'font-lock-constant-face)
5454 (aset table js2-NULL 'font-lock-constant-face)
5455 (aset table js2-TRUE 'font-lock-constant-face)
5456 (aset table js2-FALSE 'font-lock-constant-face)
5457 table)
5458 "Vector whose values are non-nil for tokens that are keywords.
5459 The values are default faces to use for highlighting the keywords.")
5460
5461 (defconst js2-reserved-words
5462 '(abstract
5463 boolean byte
5464 char class
5465 double
5466 enum export extends
5467 final float
5468 goto
5469 implements import int interface
5470 long
5471 native
5472 package private protected public
5473 short static super synchronized
5474 throws transient
5475 volatile))
5476
5477 (defconst js2-keyword-names
5478 (let ((table (make-hash-table :test 'equal)))
5479 (loop for k in js2-keywords
5480 do (puthash
5481 (symbol-name k) ; instanceof
5482 (intern (concat "js2-"
5483 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5484 table))
5485 table)
5486 "JavaScript keywords by name, mapped to their symbols.")
5487
5488 (defconst js2-reserved-word-names
5489 (let ((table (make-hash-table :test 'equal)))
5490 (loop for k in js2-reserved-words
5491 do
5492 (puthash (symbol-name k) 'js2-RESERVED table))
5493 table)
5494 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5495
5496 (defsubst js2-collect-string (buf)
5497 "Convert BUF, a list of chars, to a string.
5498 Reverses BUF before converting."
5499 (cond
5500 ((stringp buf)
5501 buf)
5502 ((null buf) ; for emacs21 compat
5503 "")
5504 (t
5505 (if buf
5506 (apply #'string (nreverse buf))
5507 ""))))
5508
5509 (defun js2-string-to-keyword (s)
5510 "Return token for S, a string, if S is a keyword or reserved word.
5511 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5512 (or (gethash s js2-keyword-names)
5513 (gethash s js2-reserved-word-names)))
5514
5515 (defsubst js2-ts-set-char-token-bounds ()
5516 "Used when next token is one character."
5517 (setq js2-token-beg (1- js2-ts-cursor)
5518 js2-token-end js2-ts-cursor))
5519
5520 (defsubst js2-ts-return (token)
5521 "Return an N-character TOKEN from `js2-get-token'.
5522 Updates `js2-token-end' accordingly."
5523 (setq js2-token-end js2-ts-cursor)
5524 (throw 'return token))
5525
5526 (defsubst js2-x-digit-to-int (c accumulator)
5527 "Build up a hex number.
5528 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5529 corresponding number. Otherwise return -1."
5530 (catch 'return
5531 (catch 'check
5532 ;; Use 0..9 < A..Z < a..z
5533 (cond
5534 ((<= c ?9)
5535 (decf c ?0)
5536 (if (<= 0 c)
5537 (throw 'check nil)))
5538 ((<= c ?F)
5539 (when (<= ?A c)
5540 (decf c (- ?A 10))
5541 (throw 'check nil)))
5542 ((<= c ?f)
5543 (when (<= ?a c)
5544 (decf c (- ?a 10))
5545 (throw 'check nil))))
5546 (throw 'return -1))
5547 (logior c (lsh accumulator 4))))
5548
5549 (defun js2-get-token ()
5550 "Return next JavaScript token, an int such as js2-RETURN."
5551 (let (c
5552 c1
5553 identifier-start
5554 is-unicode-escape-start
5555 contains-escape
5556 escape-val
5557 escape-start
5558 str
5559 result
5560 base
5561 is-integer
5562 quote-char
5563 val
5564 look-for-slash
5565 continue)
5566 (catch 'return
5567 (while t
5568 ;; Eat whitespace, possibly sensitive to newlines.
5569 (setq continue t)
5570 (while continue
5571 (setq c (js2-get-char))
5572 (cond
5573 ((eq c js2-EOF_CHAR)
5574 (js2-ts-set-char-token-bounds)
5575 (throw 'return js2-EOF))
5576 ((eq c ?\n)
5577 (js2-ts-set-char-token-bounds)
5578 (setq js2-ts-dirty-line nil)
5579 (throw 'return js2-EOL))
5580 ((not (js2-js-space-p c))
5581 (if (/= c ?-) ; in case end of HTML comment
5582 (setq js2-ts-dirty-line t))
5583 (setq continue nil))))
5584 ;; Assume the token will be 1 char - fixed up below.
5585 (js2-ts-set-char-token-bounds)
5586 (when (eq c ?@)
5587 (throw 'return js2-XMLATTR))
5588 ;; identifier/keyword/instanceof?
5589 ;; watch out for starting with a <backslash>
5590 (cond
5591 ((eq c ?\\)
5592 (setq c (js2-get-char))
5593 (if (eq c ?u)
5594 (setq identifier-start t
5595 is-unicode-escape-start t
5596 js2-ts-string-buffer nil)
5597 (setq identifier-start nil)
5598 (js2-unget-char)
5599 (setq c ?\\)))
5600 (t
5601 (when (setq identifier-start (js2-java-identifier-start-p c))
5602 (setq js2-ts-string-buffer nil)
5603 (js2-add-to-string c))))
5604 (when identifier-start
5605 (setq contains-escape is-unicode-escape-start)
5606 (catch 'break
5607 (while t
5608 (if is-unicode-escape-start
5609 ;; strictly speaking we should probably push-back
5610 ;; all the bad characters if the <backslash>uXXXX
5611 ;; sequence is malformed. But since there isn't a
5612 ;; correct context(is there?) for a bad Unicode
5613 ;; escape sequence in an identifier, we can report
5614 ;; an error here.
5615 (progn
5616 (setq escape-val 0)
5617 (dotimes (i 4)
5618 (setq c (js2-get-char)
5619 escape-val (js2-x-digit-to-int c escape-val))
5620 ;; Next check takes care of c < 0 and bad escape
5621 (if (minusp escape-val)
5622 (throw 'break nil)))
5623 (if (minusp escape-val)
5624 (js2-report-scan-error "msg.invalid.escape" t))
5625 (js2-add-to-string escape-val)
5626 (setq is-unicode-escape-start nil))
5627 (setq c (js2-get-char))
5628 (cond
5629 ((eq c ?\\)
5630 (setq c (js2-get-char))
5631 (if (eq c ?u)
5632 (setq is-unicode-escape-start t
5633 contains-escape t)
5634 (js2-report-scan-error "msg.illegal.character" t)))
5635 (t
5636 (if (or (eq c js2-EOF_CHAR)
5637 (not (js2-java-identifier-part-p c)))
5638 (throw 'break nil))
5639 (js2-add-to-string c))))))
5640 (js2-unget-char)
5641 (setq str (js2-get-string-from-buffer))
5642 (unless contains-escape
5643 ;; OPT we shouldn't have to make a string (object!) to
5644 ;; check if it's a keyword.
5645 ;; Return the corresponding token if it's a keyword
5646 (when (setq result (js2-string-to-keyword str))
5647 (if (and (< js2-language-version 170)
5648 (memq result '(js2-LET js2-YIELD)))
5649 ;; LET and YIELD are tokens only in 1.7 and later
5650 (setq result 'js2-NAME))
5651 (if (not (eq result 'js2-RESERVED))
5652 (throw 'return (js2-token-code result)))
5653 (js2-report-warning "msg.reserved.keyword" str)))
5654 ;; If we want to intern these as Rhino does, just use (intern str)
5655 (setq js2-ts-string str)
5656 (throw 'return js2-NAME)) ; end identifier/kwd check
5657 ;; is it a number?
5658 (when (or (js2-digit-p c)
5659 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5660 (setq js2-ts-string-buffer nil
5661 base 10)
5662 (when (eq c ?0)
5663 (setq c (js2-get-char))
5664 (cond
5665 ((or (eq c ?x) (eq c ?X))
5666 (setq base 16)
5667 (setq c (js2-get-char)))
5668 ((js2-digit-p c)
5669 (setq base 8))
5670 (t
5671 (js2-add-to-string ?0))))
5672 (if (eq base 16)
5673 (while (<= 0 (js2-x-digit-to-int c 0))
5674 (js2-add-to-string c)
5675 (setq c (js2-get-char)))
5676 (while (and (<= ?0 c) (<= c ?9))
5677 ;; We permit 08 and 09 as decimal numbers, which
5678 ;; makes our behavior a superset of the ECMA
5679 ;; numeric grammar. We might not always be so
5680 ;; permissive, so we warn about it.
5681 (when (and (eq base 8) (>= c ?8))
5682 (js2-report-warning "msg.bad.octal.literal"
5683 (if (eq c ?8) "8" "9"))
5684 (setq base 10))
5685 (js2-add-to-string c)
5686 (setq c (js2-get-char))))
5687 (setq is-integer t)
5688 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5689 (setq is-integer nil)
5690 (when (eq c ?.)
5691 (loop do
5692 (js2-add-to-string c)
5693 (setq c (js2-get-char))
5694 while (js2-digit-p c)))
5695 (when (memq c '(?e ?E))
5696 (js2-add-to-string c)
5697 (setq c (js2-get-char))
5698 (when (memq c '(?+ ?-))
5699 (js2-add-to-string c)
5700 (setq c (js2-get-char)))
5701 (unless (js2-digit-p c)
5702 (js2-report-scan-error "msg.missing.exponent" t))
5703 (loop do
5704 (js2-add-to-string c)
5705 (setq c (js2-get-char))
5706 while (js2-digit-p c))))
5707 (js2-unget-char)
5708 (setq js2-ts-string (js2-get-string-from-buffer)
5709 js2-ts-number
5710 (if (and (eq base 10) (not is-integer))
5711 (string-to-number js2-ts-string)
5712 ;; TODO: call runtime number-parser. Some of it is in
5713 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5714 (string-to-number js2-ts-string)))
5715 (throw 'return js2-NUMBER))
5716 ;; is it a string?
5717 (when (memq c '(?\" ?\'))
5718 ;; We attempt to accumulate a string the fast way, by
5719 ;; building it directly out of the reader. But if there
5720 ;; are any escaped characters in the string, we revert to
5721 ;; building it out of a string buffer.
5722 (setq quote-char c
5723 js2-ts-string-buffer nil
5724 c (js2-get-char))
5725 (catch 'break
5726 (while (/= c quote-char)
5727 (catch 'continue
5728 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5729 (js2-unget-char)
5730 (setq js2-token-end js2-ts-cursor)
5731 (js2-report-error "msg.unterminated.string.lit")
5732 (throw 'return js2-STRING))
5733 (when (eq c ?\\)
5734 ;; We've hit an escaped character
5735 (setq c (js2-get-char))
5736 (case c
5737 (?b (setq c ?\b))
5738 (?f (setq c ?\f))
5739 (?n (setq c ?\n))
5740 (?r (setq c ?\r))
5741 (?t (setq c ?\t))
5742 (?v (setq c ?\v))
5743 (?u
5744 (setq c1 (js2-read-unicode-escape))
5745 (if js2-parse-ide-mode
5746 (if c1
5747 (progn
5748 ;; just copy the string in IDE-mode
5749 (js2-add-to-string ?\\)
5750 (js2-add-to-string ?u)
5751 (dotimes (i 3)
5752 (js2-add-to-string (js2-get-char)))
5753 (setq c (js2-get-char))) ; added at end of loop
5754 ;; flag it as an invalid escape
5755 (js2-report-warning "msg.invalid.escape"
5756 nil (- js2-ts-cursor 2) 6))
5757 ;; Get 4 hex digits; if the u escape is not
5758 ;; followed by 4 hex digits, use 'u' + the
5759 ;; literal character sequence that follows.
5760 (js2-add-to-string ?u)
5761 (setq escape-val 0)
5762 (dotimes (i 4)
5763 (setq c (js2-get-char)
5764 escape-val (js2-x-digit-to-int c escape-val))
5765 (if (minusp escape-val)
5766 (throw 'continue nil))
5767 (js2-add-to-string c))
5768 ;; prepare for replace of stored 'u' sequence by escape value
5769 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5770 c escape-val)))
5771 (?x
5772 ;; Get 2 hex digits, defaulting to 'x'+literal
5773 ;; sequence, as above.
5774 (setq c (js2-get-char)
5775 escape-val (js2-x-digit-to-int c 0))
5776 (if (minusp escape-val)
5777 (progn
5778 (js2-add-to-string ?x)
5779 (throw 'continue nil))
5780 (setq c1 c
5781 c (js2-get-char)
5782 escape-val (js2-x-digit-to-int c escape-val))
5783 (if (minusp escape-val)
5784 (progn
5785 (js2-add-to-string ?x)
5786 (js2-add-to-string c1)
5787 (throw 'continue nil))
5788 ;; got 2 hex digits
5789 (setq c escape-val))))
5790 (?\n
5791 ;; Remove line terminator after escape to follow
5792 ;; SpiderMonkey and C/C++
5793 (setq c (js2-get-char))
5794 (throw 'continue nil))
5795 (t
5796 (when (and (<= ?0 c) (< c ?8))
5797 (setq val (- c ?0)
5798 c (js2-get-char))
5799 (when (and (<= ?0 c) (< c ?8))
5800 (setq val (- (+ (* 8 val) c) ?0)
5801 c (js2-get-char))
5802 (when (and (<= ?0 c)
5803 (< c ?8)
5804 (< val #o37))
5805 ;; c is 3rd char of octal sequence only
5806 ;; if the resulting val <= 0377
5807 (setq val (- (+ (* 8 val) c) ?0)
5808 c (js2-get-char))))
5809 (js2-unget-char)
5810 (setq c val)))))
5811 (js2-add-to-string c)
5812 (setq c (js2-get-char)))))
5813 (setq js2-ts-string (js2-get-string-from-buffer))
5814 (throw 'return js2-STRING))
5815 (case c
5816 (?\;
5817 (throw 'return js2-SEMI))
5818 (?\[
5819 (throw 'return js2-LB))
5820 (?\]
5821 (throw 'return js2-RB))
5822 (?{
5823 (throw 'return js2-LC))
5824 (?}
5825 (throw 'return js2-RC))
5826 (?\(
5827 (throw 'return js2-LP))
5828 (?\)
5829 (throw 'return js2-RP))
5830 (?,
5831 (throw 'return js2-COMMA))
5832 (??
5833 (throw 'return js2-HOOK))
5834 (?:
5835 (if (js2-match-char ?:)
5836 (js2-ts-return js2-COLONCOLON)
5837 (throw 'return js2-COLON)))
5838 (?.
5839 (if (js2-match-char ?.)
5840 (if (js2-match-char ?.)
5841 (js2-ts-return js2-TRIPLEDOT)
5842 (js2-ts-return js2-DOTDOT))
5843 (if (js2-match-char ?\()
5844 (js2-ts-return js2-DOTQUERY)
5845 (throw 'return js2-DOT))))
5846 (?|
5847 (if (js2-match-char ?|)
5848 (throw 'return js2-OR)
5849 (if (js2-match-char ?=)
5850 (js2-ts-return js2-ASSIGN_BITOR)
5851 (throw 'return js2-BITOR))))
5852 (?^
5853 (if (js2-match-char ?=)
5854 (js2-ts-return js2-ASSIGN_BITOR)
5855 (throw 'return js2-BITXOR)))
5856 (?&
5857 (if (js2-match-char ?&)
5858 (throw 'return js2-AND)
5859 (if (js2-match-char ?=)
5860 (js2-ts-return js2-ASSIGN_BITAND)
5861 (throw 'return js2-BITAND))))
5862 (?=
5863 (if (js2-match-char ?=)
5864 (if (js2-match-char ?=)
5865 (js2-ts-return js2-SHEQ)
5866 (throw 'return js2-EQ))
5867 (throw 'return js2-ASSIGN)))
5868 (?!
5869 (if (js2-match-char ?=)
5870 (if (js2-match-char ?=)
5871 (js2-ts-return js2-SHNE)
5872 (js2-ts-return js2-NE))
5873 (throw 'return js2-NOT)))
5874 (?<
5875 ;; NB:treat HTML begin-comment as comment-till-eol
5876 (when (js2-match-char ?!)
5877 (when (js2-match-char ?-)
5878 (when (js2-match-char ?-)
5879 (js2-skip-line)
5880 (setq js2-ts-comment-type 'html)
5881 (throw 'return js2-COMMENT)))
5882 (js2-unget-char))
5883 (if (js2-match-char ?<)
5884 (if (js2-match-char ?=)
5885 (js2-ts-return js2-ASSIGN_LSH)
5886 (js2-ts-return js2-LSH))
5887 (if (js2-match-char ?=)
5888 (js2-ts-return js2-LE)
5889 (throw 'return js2-LT))))
5890 (?>
5891 (if (js2-match-char ?>)
5892 (if (js2-match-char ?>)
5893 (if (js2-match-char ?=)
5894 (js2-ts-return js2-ASSIGN_URSH)
5895 (js2-ts-return js2-URSH))
5896 (if (js2-match-char ?=)
5897 (js2-ts-return js2-ASSIGN_RSH)
5898 (js2-ts-return js2-RSH)))
5899 (if (js2-match-char ?=)
5900 (js2-ts-return js2-GE)
5901 (throw 'return js2-GT))))
5902 (?*
5903 (if (js2-match-char ?=)
5904 (js2-ts-return js2-ASSIGN_MUL)
5905 (throw 'return js2-MUL)))
5906 (?/
5907 ;; is it a // comment?
5908 (when (js2-match-char ?/)
5909 (setq js2-token-beg (- js2-ts-cursor 2))
5910 (js2-skip-line)
5911 (setq js2-ts-comment-type 'line)
5912 ;; include newline so highlighting goes to end of window
5913 (incf js2-token-end)
5914 (throw 'return js2-COMMENT))
5915 ;; is it a /* comment?
5916 (when (js2-match-char ?*)
5917 (setq look-for-slash nil
5918 js2-token-beg (- js2-ts-cursor 2)
5919 js2-ts-comment-type
5920 (if (js2-match-char ?*)
5921 (progn
5922 (setq look-for-slash t)
5923 'jsdoc)
5924 'block))
5925 (while t
5926 (setq c (js2-get-char))
5927 (cond
5928 ((eq c js2-EOF_CHAR)
5929 (setq js2-token-end (1- js2-ts-cursor))
5930 (js2-report-error "msg.unterminated.comment")
5931 (throw 'return js2-COMMENT))
5932 ((eq c ?*)
5933 (setq look-for-slash t))
5934 ((eq c ?/)
5935 (if look-for-slash
5936 (js2-ts-return js2-COMMENT)))
5937 (t
5938 (setq look-for-slash nil
5939 js2-token-end js2-ts-cursor)))))
5940 (if (js2-match-char ?=)
5941 (js2-ts-return js2-ASSIGN_DIV)
5942 (throw 'return js2-DIV)))
5943 (?#
5944 (when js2-skip-preprocessor-directives
5945 (js2-skip-line)
5946 (setq js2-ts-comment-type 'preprocessor
5947 js2-token-end js2-ts-cursor)
5948 (throw 'return js2-COMMENT))
5949 (throw 'return js2-ERROR))
5950 (?%
5951 (if (js2-match-char ?=)
5952 (js2-ts-return js2-ASSIGN_MOD)
5953 (throw 'return js2-MOD)))
5954 (?~
5955 (throw 'return js2-BITNOT))
5956 (?+
5957 (if (js2-match-char ?=)
5958 (js2-ts-return js2-ASSIGN_ADD)
5959 (if (js2-match-char ?+)
5960 (js2-ts-return js2-INC)
5961 (throw 'return js2-ADD))))
5962 (?-
5963 (cond
5964 ((js2-match-char ?=)
5965 (setq c js2-ASSIGN_SUB))
5966 ((js2-match-char ?-)
5967 (unless js2-ts-dirty-line
5968 ;; treat HTML end-comment after possible whitespace
5969 ;; after line start as comment-until-eol
5970 (when (js2-match-char ?>)
5971 (js2-skip-line)
5972 (setq js2-ts-comment-type 'html)
5973 (throw 'return js2-COMMENT)))
5974 (setq c js2-DEC))
5975 (t
5976 (setq c js2-SUB)))
5977 (setq js2-ts-dirty-line t)
5978 (js2-ts-return c))
5979 (otherwise
5980 (js2-report-scan-error "msg.illegal.character")))))))
5981
5982 (defun js2-read-regexp (start-token)
5983 "Called by parser when it gets / or /= in literal context."
5984 (let (c
5985 err
5986 in-class ; inside a '[' .. ']' character-class
5987 flags
5988 (continue t))
5989 (setq js2-token-beg js2-ts-cursor
5990 js2-ts-string-buffer nil
5991 js2-ts-regexp-flags nil)
5992 (if (eq start-token js2-ASSIGN_DIV)
5993 ;; mis-scanned /=
5994 (js2-add-to-string ?=)
5995 (if (not (eq start-token js2-DIV))
5996 (error "failed assertion")))
5997 (while (and (not err)
5998 (or (/= (setq c (js2-get-char)) ?/)
5999 in-class))
6000 (cond
6001 ((or (= c ?\n)
6002 (= c js2-EOF_CHAR))
6003 (setq js2-token-end (1- js2-ts-cursor)
6004 err t
6005 js2-ts-string (js2-collect-string js2-ts-string-buffer))
6006 (js2-report-error "msg.unterminated.re.lit"))
6007 (t (cond
6008 ((= c ?\\)
6009 (js2-add-to-string c)
6010 (setq c (js2-get-char)))
6011 ((= c ?\[)
6012 (setq in-class t))
6013 ((= c ?\])
6014 (setq in-class nil)))
6015 (js2-add-to-string c))))
6016 (unless err
6017 (while continue
6018 (cond
6019 ((js2-match-char ?g)
6020 (push ?g flags))
6021 ((js2-match-char ?i)
6022 (push ?i flags))
6023 ((js2-match-char ?m)
6024 (push ?m flags))
6025 (t
6026 (setq continue nil))))
6027 (if (js2-alpha-p (js2-peek-char))
6028 (js2-report-scan-error "msg.invalid.re.flag" t
6029 js2-ts-cursor 1))
6030 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6031 js2-ts-regexp-flags (js2-collect-string flags)
6032 js2-token-end js2-ts-cursor)
6033 ;; tell `parse-partial-sexp' to ignore this range of chars
6034 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6035
6036 (defun js2-get-first-xml-token ()
6037 (setq js2-ts-xml-open-tags-count 0
6038 js2-ts-is-xml-attribute nil
6039 js2-ts-xml-is-tag-content nil)
6040 (js2-unget-char)
6041 (js2-get-next-xml-token))
6042
6043 (defsubst js2-xml-discard-string ()
6044 "Throw away the string in progress and flag an XML parse error."
6045 (setq js2-ts-string-buffer nil
6046 js2-ts-string nil)
6047 (js2-report-scan-error "msg.XML.bad.form" t))
6048
6049 (defun js2-get-next-xml-token ()
6050 (setq js2-ts-string-buffer nil ; for recording the XML
6051 js2-token-beg js2-ts-cursor)
6052 (let (c result)
6053 (setq result
6054 (catch 'return
6055 (while t
6056 (setq c (js2-get-char))
6057 (cond
6058 ((= c js2-EOF_CHAR)
6059 (throw 'return js2-ERROR))
6060 (js2-ts-xml-is-tag-content
6061 (case c
6062 (?>
6063 (js2-add-to-string c)
6064 (setq js2-ts-xml-is-tag-content nil
6065 js2-ts-is-xml-attribute nil))
6066 (?/
6067 (js2-add-to-string c)
6068 (when (eq ?> (js2-peek-char))
6069 (setq c (js2-get-char))
6070 (js2-add-to-string c)
6071 (setq js2-ts-xml-is-tag-content nil)
6072 (decf js2-ts-xml-open-tags-count)))
6073 (?{
6074 (js2-unget-char)
6075 (setq js2-ts-string (js2-get-string-from-buffer))
6076 (throw 'return js2-XML))
6077 ((?\' ?\")
6078 (js2-add-to-string c)
6079 (unless (js2-read-quoted-string c)
6080 (throw 'return js2-ERROR)))
6081 (?=
6082 (js2-add-to-string c)
6083 (setq js2-ts-is-xml-attribute t))
6084 ((? ?\t ?\r ?\n)
6085 (js2-add-to-string c))
6086 (t
6087 (js2-add-to-string c)
6088 (setq js2-ts-is-xml-attribute nil)))
6089 (when (and (not js2-ts-xml-is-tag-content)
6090 (zerop js2-ts-xml-open-tags-count))
6091 (setq js2-ts-string (js2-get-string-from-buffer))
6092 (throw 'return js2-XMLEND)))
6093 (t
6094 ;; else not tag content
6095 (case c
6096 (?<
6097 (js2-add-to-string c)
6098 (setq c (js2-peek-char))
6099 (case c
6100 (?!
6101 (setq c (js2-get-char)) ;; skip !
6102 (js2-add-to-string c)
6103 (setq c (js2-peek-char))
6104 (case c
6105 (?-
6106 (setq c (js2-get-char)) ;; skip -
6107 (js2-add-to-string c)
6108 (if (eq c ?-)
6109 (progn
6110 (js2-add-to-string c)
6111 (unless (js2-read-xml-comment)
6112 (throw 'return js2-ERROR)))
6113 (js2-xml-discard-string)
6114 (throw 'return js2-ERROR)))
6115 (?\[
6116 (setq c (js2-get-char)) ;; skip [
6117 (js2-add-to-string c)
6118 (if (and (= (js2-get-char) ?C)
6119 (= (js2-get-char) ?D)
6120 (= (js2-get-char) ?A)
6121 (= (js2-get-char) ?T)
6122 (= (js2-get-char) ?A)
6123 (= (js2-get-char) ?\[))
6124 (progn
6125 (js2-add-to-string ?C)
6126 (js2-add-to-string ?D)
6127 (js2-add-to-string ?A)
6128 (js2-add-to-string ?T)
6129 (js2-add-to-string ?A)
6130 (js2-add-to-string ?\[)
6131 (unless (js2-read-cdata)
6132 (throw 'return js2-ERROR)))
6133 (js2-xml-discard-string)
6134 (throw 'return js2-ERROR)))
6135 (t
6136 (unless (js2-read-entity)
6137 (throw 'return js2-ERROR))))
6138 ;; allow bare CDATA section
6139 ;; ex) let xml = <![CDATA[ foo bar baz ]]>;
6140 (when (zerop js2-ts-xml-open-tags-count)
6141 (throw 'return js2-XMLEND)))
6142 (??
6143 (setq c (js2-get-char)) ;; skip ?
6144 (js2-add-to-string c)
6145 (unless (js2-read-PI)
6146 (throw 'return js2-ERROR)))
6147 (?/
6148 ;; end tag
6149 (setq c (js2-get-char)) ;; skip /
6150 (js2-add-to-string c)
6151 (when (zerop js2-ts-xml-open-tags-count)
6152 (js2-xml-discard-string)
6153 (throw 'return js2-ERROR))
6154 (setq js2-ts-xml-is-tag-content t)
6155 (decf js2-ts-xml-open-tags-count))
6156 (t
6157 ;; start tag
6158 (setq js2-ts-xml-is-tag-content t)
6159 (incf js2-ts-xml-open-tags-count))))
6160 (?{
6161 (js2-unget-char)
6162 (setq js2-ts-string (js2-get-string-from-buffer))
6163 (throw 'return js2-XML))
6164 (t
6165 (js2-add-to-string c))))))))
6166 (setq js2-token-end js2-ts-cursor)
6167 result))
6168
6169 (defun js2-read-quoted-string (quote)
6170 (let (c)
6171 (catch 'return
6172 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6173 (js2-add-to-string c)
6174 (if (eq c quote)
6175 (throw 'return t)))
6176 (js2-xml-discard-string) ;; throw away string in progress
6177 nil)))
6178
6179 (defun js2-read-xml-comment ()
6180 (let ((c (js2-get-char)))
6181 (catch 'return
6182 (while (/= c js2-EOF_CHAR)
6183 (catch 'continue
6184 (js2-add-to-string c)
6185 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6186 (setq c (js2-get-char))
6187 (js2-add-to-string c)
6188 (if (eq (js2-peek-char) ?>)
6189 (progn
6190 (setq c (js2-get-char)) ;; skip >
6191 (js2-add-to-string c)
6192 (throw 'return t))
6193 (throw 'continue nil)))
6194 (setq c (js2-get-char))))
6195 (js2-xml-discard-string)
6196 nil)))
6197
6198 (defun js2-read-cdata ()
6199 (let ((c (js2-get-char)))
6200 (catch 'return
6201 (while (/= c js2-EOF_CHAR)
6202 (catch 'continue
6203 (js2-add-to-string c)
6204 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6205 (setq c (js2-get-char))
6206 (js2-add-to-string c)
6207 (if (eq (js2-peek-char) ?>)
6208 (progn
6209 (setq c (js2-get-char)) ;; Skip >
6210 (js2-add-to-string c)
6211 (throw 'return t))
6212 (throw 'continue nil)))
6213 (setq c (js2-get-char))))
6214 (js2-xml-discard-string)
6215 nil)))
6216
6217 (defun js2-read-entity ()
6218 (let ((decl-tags 1)
6219 c)
6220 (catch 'return
6221 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6222 (js2-add-to-string c)
6223 (case c
6224 (?<
6225 (incf decl-tags))
6226 (?>
6227 (decf decl-tags)
6228 (if (zerop decl-tags)
6229 (throw 'return t)))))
6230 (js2-xml-discard-string)
6231 nil)))
6232
6233 (defun js2-read-PI ()
6234 "Scan an XML processing instruction."
6235 (let (c)
6236 (catch 'return
6237 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6238 (js2-add-to-string c)
6239 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6240 (setq c (js2-get-char)) ;; Skip >
6241 (js2-add-to-string c)
6242 (throw 'return t)))
6243 (js2-xml-discard-string)
6244 nil)))
6245
6246 (defun js2-scanner-get-line ()
6247 "Return the text of the current scan line."
6248 (buffer-substring (point-at-bol) (point-at-eol)))
6249
6250 ;;; Highlighting
6251
6252 (defsubst js2-set-face (beg end face &optional record)
6253 "Fontify a region. If RECORD is non-nil, record for later."
6254 (when (plusp js2-highlight-level)
6255 (setq beg (min (point-max) beg)
6256 beg (max (point-min) beg)
6257 end (min (point-max) end)
6258 end (max (point-min) end))
6259 (if record
6260 (push (list beg end face) js2-mode-fontifications)
6261 (put-text-property beg end 'font-lock-face face))))
6262
6263 (defsubst js2-set-kid-face (pos kid len face)
6264 "Set-face on a child node.
6265 POS is absolute buffer position of parent.
6266 KID is the child node.
6267 LEN is the length to fontify.
6268 FACE is the face to fontify with."
6269 (js2-set-face (+ pos (js2-node-pos kid))
6270 (+ pos (js2-node-pos kid) (js2-node-len kid))
6271 face))
6272
6273 (defsubst js2-fontify-kwd (start length)
6274 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6275
6276 (defsubst js2-clear-face (beg end)
6277 (remove-text-properties beg end '(font-lock-face nil
6278 help-echo nil
6279 point-entered nil
6280 c-in-sws nil)))
6281
6282 (defconst js2-ecma-global-props
6283 (concat "^"
6284 (regexp-opt
6285 '("Infinity" "NaN" "undefined" "arguments") t)
6286 "$")
6287 "Value properties of the Ecma-262 Global Object.
6288 Shown at or above `js2-highlight-level' 2.")
6289
6290 ;; might want to add the name "arguments" to this list?
6291 (defconst js2-ecma-object-props
6292 (concat "^"
6293 (regexp-opt
6294 '("prototype" "__proto__" "__parent__") t)
6295 "$")
6296 "Value properties of the Ecma-262 Object constructor.
6297 Shown at or above `js2-highlight-level' 2.")
6298
6299 (defconst js2-ecma-global-funcs
6300 (concat
6301 "^"
6302 (regexp-opt
6303 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6304 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6305 "$")
6306 "Function properties of the Ecma-262 Global object.
6307 Shown at or above `js2-highlight-level' 2.")
6308
6309 (defconst js2-ecma-number-props
6310 (concat "^"
6311 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6312 "NEGATIVE_INFINITY"
6313 "POSITIVE_INFINITY") t)
6314 "$")
6315 "Properties of the Ecma-262 Number constructor.
6316 Shown at or above `js2-highlight-level' 2.")
6317
6318 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6319 "Properties of the Ecma-262 Date constructor.
6320 Shown at or above `js2-highlight-level' 2.")
6321
6322 (defconst js2-ecma-math-props
6323 (concat "^"
6324 (regexp-opt
6325 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6326 t)
6327 "$")
6328 "Properties of the Ecma-262 Math object.
6329 Shown at or above `js2-highlight-level' 2.")
6330
6331 (defconst js2-ecma-math-funcs
6332 (concat "^"
6333 (regexp-opt
6334 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6335 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6336 "$")
6337 "Function properties of the Ecma-262 Math object.
6338 Shown at or above `js2-highlight-level' 2.")
6339
6340 (defconst js2-ecma-function-props
6341 (concat
6342 "^"
6343 (regexp-opt
6344 '(;; properties of the Object prototype object
6345 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6346 "toLocaleString" "toString" "valueOf"
6347 ;; properties of the Function prototype object
6348 "apply" "call"
6349 ;; properties of the Array prototype object
6350 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6351 "splice" "unshift"
6352 ;; properties of the String prototype object
6353 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6354 "localeCompare" "match" "replace" "search" "split" "substring"
6355 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6356 "toUpperCase"
6357 ;; properties of the Number prototype object
6358 "toExponential" "toFixed" "toPrecision"
6359 ;; properties of the Date prototype object
6360 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6361 "getMinutes" "getMonth" "getSeconds" "getTime"
6362 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6363 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6364 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6365 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6366 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6367 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6368 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6369 "toTimeString" "toUTCString"
6370 ;; properties of the RegExp prototype object
6371 "exec" "test"
6372 ;; properties of the JSON prototype object
6373 "parse" "stringify"
6374 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6375 "toSource" "__defineGetter__" "__defineSetter__"
6376 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6377 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6378 t)
6379 "$")
6380 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6381 Shown at or above `js2-highlight-level' 3.")
6382
6383 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6384 (let ((target-name (and target
6385 (js2-name-node-p target)
6386 (js2-name-node-name target)))
6387 (prop-name (if prop (js2-name-node-name prop)))
6388 (level1 (>= js2-highlight-level 1))
6389 (level2 (>= js2-highlight-level 2))
6390 (level3 (>= js2-highlight-level 3))
6391 pos
6392 face)
6393 (when level2
6394 (if call-p
6395 (cond
6396 ((and target prop)
6397 (cond
6398 ((and level3 (string-match js2-ecma-function-props prop-name))
6399 (setq face 'font-lock-builtin-face))
6400 ((and target-name prop)
6401 (cond
6402 ((string= target-name "Date")
6403 (if (string-match js2-ecma-date-props prop-name)
6404 (setq face 'font-lock-builtin-face)))
6405 ((string= target-name "Math")
6406 (if (string-match js2-ecma-math-funcs prop-name)
6407 (setq face 'font-lock-builtin-face)))))))
6408 (prop
6409 (if (string-match js2-ecma-global-funcs prop-name)
6410 (setq face 'font-lock-builtin-face))))
6411 (cond
6412 ((and target prop)
6413 (cond
6414 ((string= target-name "Number")
6415 (if (string-match js2-ecma-number-props prop-name)
6416 (setq face 'font-lock-constant-face)))
6417 ((string= target-name "Math")
6418 (if (string-match js2-ecma-math-props prop-name)
6419 (setq face 'font-lock-constant-face)))))
6420 (prop
6421 (if (string-match js2-ecma-object-props prop-name)
6422 (setq face 'font-lock-constant-face)))))
6423 (when face
6424 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6425 (js2-node-pos prop))) ; relative
6426 (+ pos (js2-node-len prop))
6427 face 'record)))))
6428
6429 (defun js2-parse-highlight-member-expr-node (node)
6430 "Perform syntax highlighting of EcmaScript built-in properties.
6431 The variable `js2-highlight-level' governs this highighting."
6432 (let (face target prop name pos end parent call-p callee)
6433 (cond
6434 ;; case 1: simple name, e.g. foo
6435 ((js2-name-node-p node)
6436 (setq name (js2-name-node-name node))
6437 ;; possible for name to be nil in rare cases - saw it when
6438 ;; running js2-mode on an elisp buffer. Might as well try to
6439 ;; make it so js2-mode never barfs.
6440 (when name
6441 (setq face (if (string-match js2-ecma-global-props name)
6442 'font-lock-constant-face))
6443 (when face
6444 (setq pos (js2-node-pos node)
6445 end (+ pos (js2-node-len node)))
6446 (js2-set-face pos end face 'record))))
6447 ;; case 2: property access or function call
6448 ((or (js2-prop-get-node-p node)
6449 ;; highlight function call if expr is a prop-get node
6450 ;; or a plain name (i.e. unqualified function call)
6451 (and (setq call-p (js2-call-node-p node))
6452 (setq callee (js2-call-node-target node)) ; separate setq!
6453 (or (js2-prop-get-node-p callee)
6454 (js2-name-node-p callee))))
6455 (setq parent node
6456 node (if call-p callee node))
6457 (if (and call-p (js2-name-node-p callee))
6458 (setq prop callee)
6459 (setq target (js2-prop-get-node-left node)
6460 prop (js2-prop-get-node-right node)))
6461 (cond
6462 ((js2-name-node-p target)
6463 (if (js2-name-node-p prop)
6464 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6465 (js2-parse-highlight-prop-get parent target prop call-p)
6466 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6467 (js2-parse-highlight-prop-get parent target nil call-p)))
6468 ((js2-name-node-p prop)
6469 ;; case 2c: complex target, simple name, e.g. x[y].bar
6470 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6471
6472 (defun js2-parse-highlight-member-expr-fn-name (expr)
6473 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6474 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6475 We currently only handle the case where the last component is a prop-get
6476 of a simple name. Called before EXPR has a parent node."
6477 (let (pos
6478 (name (and (js2-prop-get-node-p expr)
6479 (js2-prop-get-node-right expr))))
6480 (when (js2-name-node-p name)
6481 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6482 (js2-node-pos name)))
6483 (+ pos (js2-node-len name))
6484 'font-lock-function-name-face
6485 'record))))
6486
6487 ;; source: http://jsdoc.sourceforge.net/
6488 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6489 ;; allows type specifications, and needs work before entering the wild.
6490
6491 (defconst js2-jsdoc-param-tag-regexp
6492 (concat "^\\s-*\\*+\\s-*\\(@"
6493 "\\(?:param\\|argument\\)"
6494 "\\)"
6495 "\\s-*\\({[^}]+}\\)?" ; optional type
6496 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6497 "\\>")
6498 "Matches jsdoc tags with optional type and optional param name.")
6499
6500 (defconst js2-jsdoc-typed-tag-regexp
6501 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6502 (regexp-opt
6503 '("enum"
6504 "extends"
6505 "field"
6506 "id"
6507 "implements"
6508 "lends"
6509 "mods"
6510 "requires"
6511 "return"
6512 "returns"
6513 "throw"
6514 "throws"))
6515 "\\)\\)\\s-*\\({[^}]+}\\)?")
6516 "Matches jsdoc tags with optional type.")
6517
6518 (defconst js2-jsdoc-arg-tag-regexp
6519 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6520 (regexp-opt
6521 '("alias"
6522 "augments"
6523 "borrows"
6524 "bug"
6525 "base"
6526 "config"
6527 "default"
6528 "define"
6529 "exception"
6530 "function"
6531 "member"
6532 "memberOf"
6533 "name"
6534 "namespace"
6535 "property"
6536 "since"
6537 "suppress"
6538 "this"
6539 "throws"
6540 "type"
6541 "version"))
6542 "\\)\\)\\s-+\\([^ \t]+\\)")
6543 "Matches jsdoc tags with a single argument.")
6544
6545 (defconst js2-jsdoc-empty-tag-regexp
6546 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6547 (regexp-opt
6548 '("addon"
6549 "author"
6550 "class"
6551 "const"
6552 "constant"
6553 "constructor"
6554 "constructs"
6555 "deprecated"
6556 "desc"
6557 "description"
6558 "event"
6559 "example"
6560 "exec"
6561 "export"
6562 "fileoverview"
6563 "final"
6564 "function"
6565 "hidden"
6566 "ignore"
6567 "implicitCast"
6568 "inheritDoc"
6569 "inner"
6570 "interface"
6571 "license"
6572 "noalias"
6573 "noshadow"
6574 "notypecheck"
6575 "override"
6576 "owner"
6577 "preserve"
6578 "preserveTry"
6579 "private"
6580 "protected"
6581 "public"
6582 "static"
6583 "supported"
6584 ))
6585 "\\)\\)\\s-*")
6586 "Matches empty jsdoc tags.")
6587
6588 (defconst js2-jsdoc-link-tag-regexp
6589 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6590 "Matches a jsdoc link or code tag.")
6591
6592 (defconst js2-jsdoc-see-tag-regexp
6593 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6594 "Matches a jsdoc @see tag.")
6595
6596 (defconst js2-jsdoc-html-tag-regexp
6597 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6598 "Matches a simple (no attributes) html start- or end-tag.")
6599
6600 (defsubst js2-jsdoc-highlight-helper ()
6601 (js2-set-face (match-beginning 1)
6602 (match-end 1)
6603 'js2-jsdoc-tag-face)
6604 (if (match-beginning 2)
6605 (if (save-excursion
6606 (goto-char (match-beginning 2))
6607 (= (char-after) ?{))
6608 (js2-set-face (1+ (match-beginning 2))
6609 (1- (match-end 2))
6610 'js2-jsdoc-type-face)
6611 (js2-set-face (match-beginning 2)
6612 (match-end 2)
6613 'js2-jsdoc-value-face)))
6614 (if (match-beginning 3)
6615 (js2-set-face (match-beginning 3)
6616 (match-end 3)
6617 'js2-jsdoc-value-face)))
6618
6619 (defun js2-highlight-jsdoc (ast)
6620 "Highlight doc comment tags."
6621 (let ((comments (js2-ast-root-comments ast))
6622 beg end)
6623 (save-excursion
6624 (dolist (node comments)
6625 (when (eq (js2-comment-node-format node) 'jsdoc)
6626 (setq beg (js2-node-abs-pos node)
6627 end (+ beg (js2-node-len node)))
6628 (save-restriction
6629 (narrow-to-region beg end)
6630 (dolist (re (list js2-jsdoc-param-tag-regexp
6631 js2-jsdoc-typed-tag-regexp
6632 js2-jsdoc-arg-tag-regexp
6633 js2-jsdoc-link-tag-regexp
6634 js2-jsdoc-see-tag-regexp
6635 js2-jsdoc-empty-tag-regexp))
6636 (goto-char beg)
6637 (while (re-search-forward re nil t)
6638 (js2-jsdoc-highlight-helper)))
6639 ;; simple highlighting for html tags
6640 (goto-char beg)
6641 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6642 (js2-set-face (match-beginning 1)
6643 (match-end 1)
6644 'js2-jsdoc-html-tag-delimiter-face)
6645 (js2-set-face (match-beginning 2)
6646 (match-end 2)
6647 'js2-jsdoc-html-tag-name-face)
6648 (js2-set-face (match-beginning 3)
6649 (match-end 3)
6650 'js2-jsdoc-html-tag-delimiter-face))))))))
6651
6652 (defun js2-highlight-assign-targets (node left right)
6653 "Highlight function properties and external variables."
6654 (let (leftpos end name)
6655 ;; highlight vars and props assigned function values
6656 (when (js2-function-node-p right)
6657 (cond
6658 ;; var foo = function() {...}
6659 ((js2-name-node-p left)
6660 (setq name left))
6661 ;; foo.bar.baz = function() {...}
6662 ((and (js2-prop-get-node-p left)
6663 (js2-name-node-p (js2-prop-get-node-right left)))
6664 (setq name (js2-prop-get-node-right left))))
6665 (when name
6666 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6667 (+ leftpos (js2-node-len name))
6668 'font-lock-function-name-face
6669 'record)))))
6670
6671 (defun js2-record-name-node (node)
6672 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6673 later. NODE must be a name node."
6674 (let (leftpos end)
6675 (push (list node js2-current-scope
6676 (setq leftpos (js2-node-abs-pos node))
6677 (setq end (+ leftpos (js2-node-len node))))
6678 js2-recorded-identifiers)))
6679
6680 (defun js2-highlight-undeclared-vars ()
6681 "After entire parse is finished, look for undeclared variable references.
6682 We have to wait until entire buffer is parsed, since JavaScript permits var
6683 decls to occur after they're used.
6684
6685 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6686 it is considered declared."
6687 (let (name)
6688 (dolist (entry js2-recorded-identifiers)
6689 (destructuring-bind (name-node scope pos end) entry
6690 (setq name (js2-name-node-name name-node))
6691 (unless (or (member name js2-global-externs)
6692 (member name js2-default-externs)
6693 (member name js2-additional-externs)
6694 (js2-get-defining-scope scope name))
6695 (js2-set-face pos end 'js2-external-variable-face 'record)
6696 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6697 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6698 (setq js2-recorded-identifiers nil)))
6699
6700 ;;; IMenu support
6701
6702 ;; We currently only support imenu, but eventually should support speedbar and
6703 ;; possibly other browsing mechanisms.
6704
6705 ;; The basic strategy is to identify function assignment targets of the form
6706 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6707 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6708 ;; for imenu after parsing is finished.
6709
6710 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6711 ;; JavaScript, and the general problem is undecidable. However, several forms
6712 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6713 ;; include:
6714
6715 ;; function foo() -- function declaration
6716 ;; foo = function() -- function expression assigned to variable
6717 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6718 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6719 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6720 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6721 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6722 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6723 ;; function foo() {function bar() {...}} -- nested function
6724 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6725
6726 ;; This list boils down to a few forms that can be combined recursively.
6727 ;; Top-level named function declarations include both the left-hand (name)
6728 ;; and the right-hand (function value) expressions needed to produce an imenu
6729 ;; entry. The other "right-hand" forms we need to look for are:
6730 ;; - functions declared as props/getters/setters in object literals
6731 ;; - nested named function declarations
6732 ;; The "left-hand" expressions that functions can be assigned to include:
6733 ;; - local/global variables
6734 ;; - nested property-get expressions like a.b.c.d
6735 ;; - element gets like foo[10] or foo['bar'] where the index
6736 ;; expression can be trivially converted to a property name. They
6737 ;; effectively then become property gets.
6738
6739 ;; All the different definition types are canonicalized into the form
6740 ;; foo.bar.baz = position-of-function-keyword
6741
6742 ;; We need to build a trie-like structure for imenu. As an example,
6743 ;; consider the following JavaScript code:
6744
6745 ;; a = function() {...} // function at position 5
6746 ;; b = function() {...} // function at position 25
6747 ;; foo = function() {...} // function at position 100
6748 ;; foo.bar = function() {...} // function at position 200
6749 ;; foo.bar.baz = function() {...} // function at position 300
6750 ;; foo.bar.zab = function() {...} // function at position 400
6751
6752 ;; During parsing we accumulate an entry for each definition in
6753 ;; the variable `js2-imenu-recorder', like so:
6754
6755 ;; '((fn a 5)
6756 ;; (fn b 25)
6757 ;; (fn foo 100)
6758 ;; (fn foo bar 200)
6759 ;; (fn foo bar baz 300)
6760 ;; (fn foo bar zab 400))
6761
6762 ;; Where 'fn' is the respective function node.
6763 ;; After parsing these entries are merged into this alist-trie:
6764
6765 ;; '((a . 1)
6766 ;; (b . 2)
6767 ;; (foo (<definition> . 3)
6768 ;; (bar (<definition> . 6)
6769 ;; (baz . 100)
6770 ;; (zab . 200))))
6771
6772 ;; Note the wacky need for a <definition> name. The token can be anything
6773 ;; that isn't a valid JavaScript identifier, because you might make foo
6774 ;; a function and then start setting properties on it that are also functions.
6775
6776 (defsubst js2-prop-node-name (node)
6777 "Return the name of a node that may be a property-get/property-name.
6778 If NODE is not a valid name-node, string-node or integral number-node,
6779 returns nil. Otherwise returns the string name/value of the node."
6780 (cond
6781 ((js2-name-node-p node)
6782 (js2-name-node-name node))
6783 ((js2-string-node-p node)
6784 (js2-string-node-value node))
6785 ((and (js2-number-node-p node)
6786 (string-match "^[0-9]+$" (js2-number-node-value node)))
6787 (js2-number-node-value node))
6788 ((js2-this-node-p node)
6789 "this")))
6790
6791 (defsubst js2-node-qname-component (node)
6792 "Return the name of this node, if it contributes to a qname.
6793 Returns nil if the node doesn't contribute."
6794 (copy-sequence
6795 (or (js2-prop-node-name node)
6796 (if (and (js2-function-node-p node)
6797 (js2-function-node-name node))
6798 (js2-name-node-name (js2-function-node-name node))))))
6799
6800 (defsubst js2-record-imenu-entry (fn-node qname pos)
6801 "Add an entry to `js2-imenu-recorder'.
6802 FN-NODE should be the current item's function node.
6803
6804 Associate FN-NODE with its QNAME for later lookup.
6805 This is used in postprocessing the chain list. For each chain, we find
6806 the parent function, look up its qname, then prepend a copy of it to the chain."
6807 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6808 (unless js2-imenu-function-map
6809 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6810 (puthash fn-node qname js2-imenu-function-map))
6811
6812 (defun js2-record-imenu-functions (node &optional var)
6813 "Record function definitions for imenu.
6814 NODE is a function node or an object literal.
6815 VAR, if non-nil, is the expression that NODE is being assigned to.
6816 When passed arguments of wrong type, does nothing."
6817 (when js2-parse-ide-mode
6818 (let ((fun-p (js2-function-node-p node))
6819 qname left fname-node pos)
6820 (cond
6821 ;; non-anonymous function declaration?
6822 ((and fun-p
6823 (not var)
6824 (setq fname-node (js2-function-node-name node)))
6825 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6826 ;; for remaining forms, compute left-side tree branch first
6827 ((and var (setq qname (js2-compute-nested-prop-get var)))
6828 (cond
6829 ;; foo.bar.baz = function
6830 (fun-p
6831 (js2-record-imenu-entry node qname (js2-node-pos node)))
6832 ;; foo.bar.baz = object-literal
6833 ;; look for nested functions: {a: {b: function() {...} }}
6834 ((js2-object-node-p node)
6835 ;; Node position here is still absolute, since the parser
6836 ;; passes the assignment target and value expressions
6837 ;; to us before they are added as children of the assignment node.
6838 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6839
6840 (defun js2-compute-nested-prop-get (node)
6841 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6842 component nodes as a list. Otherwise return nil. Element-gets are treated
6843 as property-gets if the index expression is a string, or a positive integer."
6844 (let (left right head)
6845 (cond
6846 ((or (js2-name-node-p node)
6847 (js2-this-node-p node))
6848 (list node))
6849 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6850 ((js2-prop-get-node-p node) ; foo.bar
6851 (setq left (js2-prop-get-node-left node)
6852 right (js2-prop-get-node-right node))
6853 (if (setq head (js2-compute-nested-prop-get left))
6854 (nconc head (list right))))
6855 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6856 (setq left (js2-elem-get-node-target node)
6857 right (js2-elem-get-node-element node))
6858 (if (or (js2-string-node-p right) ; ['bar']
6859 (and (js2-number-node-p right) ; [10]
6860 (string-match "^[0-9]+$"
6861 (js2-number-node-value right))))
6862 (if (setq head (js2-compute-nested-prop-get left))
6863 (nconc head (list right))))))))
6864
6865 (defun js2-record-object-literal (node qname pos)
6866 "Recursively process an object literal looking for functions.
6867 NODE is an object literal that is the right-hand child of an assignment
6868 expression. QNAME is a list of nodes representing the assignment target,
6869 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6870 POS is the absolute position of the node.
6871 We do a depth-first traversal of NODE. For any functions we find,
6872 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6873 (let (left right prop-qname)
6874 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6875 (let ((left (js2-infix-node-left e))
6876 ;; Element positions are relative to the parent position.
6877 (pos (+ pos (js2-node-pos e))))
6878 (cond
6879 ;; foo: function() {...}
6880 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6881 (when (js2-prop-node-name left)
6882 ;; As a policy decision, we record the position of the property,
6883 ;; not the position of the `function' keyword, since the property
6884 ;; is effectively the name of the function.
6885 (js2-record-imenu-entry right (append qname (list left)) pos)))
6886 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6887 ((js2-object-node-p right)
6888 (js2-record-object-literal right
6889 (append qname (list (js2-infix-node-left e)))
6890 (+ pos (js2-node-pos right)))))))))
6891
6892 (defsubst js2-node-top-level-decl-p (node)
6893 "Return t if NODE's name is defined in the top-level scope.
6894 Also returns t if NODE's name is not defined in any scope, since it implies
6895 that it's an external variable, which must also be in the top-level scope."
6896 (let* ((name (js2-prop-node-name node))
6897 (this-scope (js2-node-get-enclosing-scope node))
6898 defining-scope)
6899 (cond
6900 ((js2-this-node-p node)
6901 nil)
6902 ((null this-scope)
6903 t)
6904 ((setq defining-scope (js2-get-defining-scope this-scope name))
6905 (js2-ast-root-p defining-scope))
6906 (t t))))
6907
6908 (defsubst js2-wrapper-function-p (node)
6909 "Returns t if NODE is a function expression that's immediately invoked.
6910 NODE must be `js2-function-node'."
6911 (let ((parent (js2-node-parent node)))
6912 (or
6913 ;; function(){...}();
6914 (js2-call-node-p parent)
6915 (and (js2-paren-node-p parent)
6916 ;; (function(){...})();
6917 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6918 ;; (function(){...}).call(this);
6919 (and (js2-prop-get-node-p parent)
6920 (member (js2-name-node-name (js2-prop-get-node-right parent))
6921 '("call" "apply"))
6922 (js2-call-node-p (js2-node-parent parent))))))))
6923
6924 (defun js2-browse-postprocess-chains (entries)
6925 "Modify function-declaration name chains after parsing finishes.
6926 Some of the information is only available after the parse tree is complete.
6927 For instance, processing a nested scope requires a parent function node."
6928 (let (result head fn current-fn parent-qname qname p elem)
6929 (dolist (entry entries)
6930 ;; function node goes first
6931 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6932 ;; Examine head's defining scope:
6933 ;; Pre-processed chain, or top-level/external, keep as-is.
6934 (if (or (stringp head) (js2-node-top-level-decl-p head))
6935 (push chain result)
6936 (when (js2-this-node-p head)
6937 (setq chain (cdr chain))) ; discard this-node
6938 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6939 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6940 (when (eq parent-qname 'not-found)
6941 ;; anonymous function expressions are not recorded
6942 ;; during the parse, so we need to handle this case here
6943 (setq parent-qname
6944 (if (js2-wrapper-function-p fn)
6945 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6946 (if (js2-ast-root-p grandparent)
6947 nil
6948 (gethash grandparent js2-imenu-function-map 'skip)))
6949 'skip))
6950 (puthash fn parent-qname js2-imenu-function-map))
6951 (unless (eq parent-qname 'skip)
6952 ;; prefix parent fn qname to this chain.
6953 (let ((qname (append parent-qname chain)))
6954 (puthash current-fn (butlast qname) js2-imenu-function-map)
6955 (push qname result)))))))
6956 ;; finally replace each node in each chain with its name.
6957 (dolist (chain result)
6958 (setq p chain)
6959 (while p
6960 (if (js2-node-p (setq elem (car p)))
6961 (setcar p (js2-node-qname-component elem)))
6962 (setq p (cdr p))))
6963 result))
6964
6965 ;; Merge name chains into a trie-like tree structure of nested lists.
6966 ;; To simplify construction of the trie, we first build it out using the rule
6967 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6968 ;; [key, num-or-list]. The second element can be a number; if so, this key
6969 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6970 ;; associated with the key at this level.) Otherwise the second element is
6971 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6972 ;; a simple recursive formulation.
6973 ;;
6974 ;; js2-mode is building the data structure for imenu. The imenu documentation
6975 ;; claims that it's the structure above, but in practice it wants the children
6976 ;; at the same list level as the key for that level, which is how I've drawn
6977 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6978 ;; list wrapper around the children at each level.
6979 ;;
6980 ;; A completed nested imenu-alist entry looks like this:
6981 ;; '(("foo"
6982 ;; ("<definition>" . 7)
6983 ;; ("bar"
6984 ;; ("a" . 40)
6985 ;; ("b" . 60))))
6986 ;;
6987 ;; In particular, the documentation for `imenu--index-alist' says that
6988 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6989 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6990
6991 (defun js2-treeify (lst)
6992 "Convert (a b c d) to (a ((b ((c d)))))"
6993 (if (null (cddr lst)) ; list length <= 2
6994 lst
6995 (list (car lst) (list (js2-treeify (cdr lst))))))
6996
6997 (defun js2-build-alist-trie (chains trie)
6998 "Merge declaration name chains into a trie-like alist structure for imenu.
6999 CHAINS is the qname chain list produced during parsing. TRIE is a
7000 list of elements built up so far."
7001 (let (head tail pos branch kids)
7002 (dolist (chain chains)
7003 (setq head (car chain)
7004 tail (cdr chain)
7005 pos (if (numberp (car tail)) (car tail))
7006 branch (js2-find-if (lambda (n)
7007 (string= (car n) head))
7008 trie)
7009 kids (second branch))
7010 (cond
7011 ;; case 1: this key isn't in the trie yet
7012 ((null branch)
7013 (if trie
7014 (setcdr (last trie) (list (js2-treeify chain)))
7015 (setq trie (list (js2-treeify chain)))))
7016 ;; case 2: key is present with a single number entry: replace w/ list
7017 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7018 ;; ("<definition>" 20)))
7019 ((numberp kids)
7020 (setcar (cdr branch)
7021 (list (list "<definition-1>" kids)
7022 (if pos
7023 (list "<definition-2>" pos)
7024 (js2-treeify tail)))))
7025 ;; case 3: key is there (with kids), and we're a number entry
7026 (pos
7027 (setcdr (last kids)
7028 (list
7029 (list (format "<definition-%d>"
7030 (1+ (loop for kid in kids
7031 count (eq ?< (aref (car kid) 0)))))
7032 pos))))
7033 ;; case 4: key is there with kids, need to merge in our chain
7034 (t
7035 (js2-build-alist-trie (list tail) kids))))
7036 trie))
7037
7038 (defun js2-flatten-trie (trie)
7039 "Convert TRIE to imenu-format.
7040 Recurses through nodes, and for each one whose second element is a list,
7041 appends the list's flattened elements to the current element. Also
7042 changes the tails into conses. For instance, this pre-flattened trie
7043
7044 '(a ((b 20)
7045 (c ((d 30)
7046 (e 40)))))
7047
7048 becomes
7049
7050 '(a (b . 20)
7051 (c (d . 30)
7052 (e . 40)))
7053
7054 Note that the root of the trie has no key, just a list of chains.
7055 This is also true for the value of any key with multiple children,
7056 e.g. key 'c' in the example above."
7057 (cond
7058 ((listp (car trie))
7059 (mapcar #'js2-flatten-trie trie))
7060 (t
7061 (if (numberp (second trie))
7062 (cons (car trie) (second trie))
7063 ;; else pop list and append its kids
7064 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7065
7066 (defun js2-build-imenu-index ()
7067 "Turn `js2-imenu-recorder' into an imenu data structure."
7068 (unless (eq js2-imenu-recorder 'empty)
7069 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7070 (result (js2-build-alist-trie chains nil)))
7071 (js2-flatten-trie result))))
7072
7073 (defun js2-test-print-chains (chains)
7074 "Print a list of qname chains.
7075 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7076 i.e. one or more nodes, and an integer position as the list tail."
7077 (mapconcat (lambda (chain)
7078 (concat "("
7079 (mapconcat (lambda (elem)
7080 (if (js2-node-p elem)
7081 (or (js2-node-qname-component elem)
7082 "nil")
7083 (number-to-string elem)))
7084 chain
7085 " ")
7086 ")"))
7087 chains
7088 "\n"))
7089
7090 ;;; Parser
7091
7092 (defconst js2-version "1.8.0"
7093 "Version of JavaScript supported, plus minor js2 version.")
7094
7095 (defmacro js2-record-face (face)
7096 "Record a style run of FACE for the current token."
7097 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7098
7099 (defsubst js2-node-end (n)
7100 "Computes the absolute end of node N.
7101 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7102 is only true until the node is added to its parent; i.e., while parsing."
7103 (+ (js2-node-pos n)
7104 (js2-node-len n)))
7105
7106 (defsubst js2-record-comment ()
7107 "Record a comment in `js2-scanned-comments'."
7108 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7109 :format js2-ts-comment-type)
7110 js2-scanned-comments)
7111 (when js2-parse-ide-mode
7112 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7113 'font-lock-doc-face
7114 'font-lock-comment-face))
7115 (when (memq js2-ts-comment-type '(html preprocessor))
7116 ;; Tell cc-engine the bounds of the comment.
7117 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7118
7119 ;; This function is called depressingly often, so it should be fast.
7120 ;; Most of the time it's looking at the same token it peeked before.
7121 (defsubst js2-peek-token ()
7122 "Returns the next token without consuming it.
7123 If previous token was consumed, calls scanner to get new token.
7124 If previous token was -not- consumed, returns it (idempotent).
7125
7126 This function will not return a newline (js2-EOL) - instead, it
7127 gobbles newlines until it finds a non-newline token, and flags
7128 that token as appearing just after a newline.
7129
7130 This function will also not return a js2-COMMENT. Instead, it
7131 records comments found in `js2-scanned-comments'. If the token
7132 returned by this function immediately follows a jsdoc comment,
7133 the token is flagged as such.
7134
7135 Note that this function always returned the un-flagged token!
7136 The flags, if any, are saved in `js2-current-flagged-token'."
7137 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7138 js2-current-token ; most common case - return already-peeked token
7139 (let ((tt (js2-get-token)) ; call scanner
7140 saw-eol
7141 face)
7142 ;; process comments and whitespace
7143 (while (or (= tt js2-EOL)
7144 (= tt js2-COMMENT))
7145 (if (= tt js2-EOL)
7146 (setq saw-eol t)
7147 (setq saw-eol nil)
7148 (if js2-record-comments
7149 (js2-record-comment)))
7150 (setq tt (js2-get-token))) ; call scanner
7151 (setq js2-current-token tt
7152 js2-current-flagged-token (if saw-eol
7153 (logior tt js2-ti-after-eol)
7154 tt))
7155 ;; perform lexical fontification as soon as token is scanned
7156 (when js2-parse-ide-mode
7157 (cond
7158 ((minusp tt)
7159 (js2-record-face 'js2-error-face))
7160 ((setq face (aref js2-kwd-tokens tt))
7161 (js2-record-face face))
7162 ((and (= tt js2-NAME)
7163 (equal js2-ts-string "undefined"))
7164 (js2-record-face 'font-lock-constant-face))))
7165 tt))) ; return unflagged token
7166
7167 (defsubst js2-peek-flagged-token ()
7168 "Returns the current token along with any flags set for it."
7169 (js2-peek-token)
7170 js2-current-flagged-token)
7171
7172 (defsubst js2-consume-token ()
7173 (setq js2-current-flagged-token js2-EOF))
7174
7175 (defsubst js2-next-token ()
7176 (prog1
7177 (js2-peek-token)
7178 (js2-consume-token)))
7179
7180 (defsubst js2-next-flagged-token ()
7181 (js2-peek-token)
7182 (prog1 js2-current-flagged-token
7183 (js2-consume-token)))
7184
7185 (defsubst js2-match-token (match)
7186 "Consume and return t if next token matches MATCH, a bytecode.
7187 Returns nil and consumes nothing if MATCH is not the next token."
7188 (if (/= (js2-peek-token) match)
7189 nil
7190 (js2-consume-token)
7191 t))
7192
7193 (defun js2-match-contextual-kwd (name)
7194 "Consume and return t if next token is `js2-NAME', and its
7195 string is NAME. Returns nil and does nothing otherwise."
7196 (if (or (/= (js2-peek-token) js2-NAME)
7197 (not (string= js2-ts-string name)))
7198 nil
7199 (js2-consume-token)
7200 (js2-record-face 'font-lock-keyword-face)
7201 t))
7202
7203 (defsubst js2-valid-prop-name-token (tt)
7204 (or (= tt js2-NAME)
7205 (when (and js2-allow-keywords-as-property-names
7206 (plusp tt)
7207 (aref js2-kwd-tokens tt))
7208 (js2-save-name-token-data js2-token-beg (js2-token-name tt))
7209 t)))
7210
7211 (defsubst js2-match-prop-name ()
7212 "Consume token and return t if next token is a valid property name.
7213 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7214 is non-nil and it's a keyword token."
7215 (if (js2-valid-prop-name-token (js2-peek-token))
7216 (progn
7217 (js2-consume-token)
7218 t)
7219 nil))
7220
7221 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7222 (if (js2-match-prop-name)
7223 t
7224 (js2-report-error msg-id nil pos len)
7225 nil))
7226
7227 (defsubst js2-peek-token-or-eol ()
7228 "Return js2-EOL if the current token immediately follows a newline.
7229 Else returns the current token. Used in situations where we don't
7230 consider certain token types valid if they are preceded by a newline.
7231 One example is the postfix ++ or -- operator, which has to be on the
7232 same line as its operand."
7233 (let ((tt (js2-peek-token)))
7234 ;; Check for last peeked token flags
7235 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7236 js2-EOL
7237 tt)))
7238
7239 (defsubst js2-set-check-for-label ()
7240 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7241 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7242
7243 (defsubst js2-must-match (token msg-id &optional pos len)
7244 "Match next token to token code TOKEN, or record a syntax error.
7245 MSG-ID is the error message to report if the match fails.
7246 Returns t on match, nil if no match."
7247 (if (js2-match-token token)
7248 t
7249 (js2-report-error msg-id nil pos len)
7250 nil))
7251
7252 (defsubst js2-inside-function ()
7253 (plusp js2-nesting-of-function))
7254
7255 (defsubst js2-set-requires-activation ()
7256 (if (js2-function-node-p js2-current-script-or-fn)
7257 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7258
7259 (defsubst js2-check-activation-name (name token)
7260 (when (js2-inside-function)
7261 ;; skip language-version 1.2 check from Rhino
7262 (if (or (string= "arguments" name)
7263 (and js2-compiler-activation-names ; only used in codegen
7264 (gethash name js2-compiler-activation-names)))
7265 (js2-set-requires-activation))))
7266
7267 (defsubst js2-set-is-generator ()
7268 (if (js2-function-node-p js2-current-script-or-fn)
7269 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7270
7271 (defsubst js2-must-have-xml ()
7272 (unless js2-compiler-xml-available
7273 (js2-report-error "msg.XML.not.available")))
7274
7275 (defsubst js2-push-scope (scope)
7276 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7277 (assert (js2-scope-p scope))
7278 (assert (null (js2-scope-parent-scope scope)))
7279 (assert (not (eq js2-current-scope scope)))
7280 (setf (js2-scope-parent-scope scope) js2-current-scope
7281 js2-current-scope scope))
7282
7283 (defsubst js2-pop-scope ()
7284 (setq js2-current-scope
7285 (js2-scope-parent-scope js2-current-scope)))
7286
7287 (defsubst js2-enter-loop (loop-node)
7288 (push loop-node js2-loop-set)
7289 (push loop-node js2-loop-and-switch-set)
7290 (js2-push-scope loop-node)
7291 ;; Tell the current labeled statement (if any) its statement,
7292 ;; and set the jump target of the first label to the loop.
7293 ;; These are used in `js2-parse-continue' to verify that the
7294 ;; continue target is an actual labeled loop. (And for codegen.)
7295 (when js2-labeled-stmt
7296 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7297 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7298 js2-labeled-stmt))) loop-node)))
7299
7300 (defsubst js2-exit-loop ()
7301 (pop js2-loop-set)
7302 (pop js2-loop-and-switch-set)
7303 (js2-pop-scope))
7304
7305 (defsubst js2-enter-switch (switch-node)
7306 (push switch-node js2-loop-and-switch-set))
7307
7308 (defsubst js2-exit-switch ()
7309 (pop js2-loop-and-switch-set))
7310
7311 (defun js2-parse (&optional buf cb)
7312 "Tells the js2 parser to parse a region of JavaScript.
7313
7314 BUF is a buffer or buffer name containing the code to parse.
7315 Call `narrow-to-region' first to parse only part of the buffer.
7316
7317 The returned AST root node is given some additional properties:
7318 `node-count' - total number of nodes in the AST
7319 `buffer' - BUF. The buffer it refers to may change or be killed,
7320 so the value is not necessarily reliable.
7321
7322 An optional callback CB can be specified to report parsing
7323 progress. If `(functionp CB)' returns t, it will be called with
7324 the current line number once before parsing begins, then again
7325 each time the lexer reaches a new line number.
7326
7327 CB can also be a list of the form `(symbol cb ...)' to specify
7328 multiple callbacks with different criteria. Each symbol is a
7329 criterion keyword, and the following element is the callback to
7330 call
7331
7332 :line - called whenever the line number changes
7333 :token - called for each new token consumed
7334
7335 The list of criteria could be extended to include entering or
7336 leaving a statement, an expression, or a function definition."
7337 (if (and cb (not (functionp cb)))
7338 (error "criteria callbacks not yet implemented"))
7339 (let ((inhibit-point-motion-hooks t)
7340 (js2-compiler-xml-available (>= js2-language-version 160))
7341 ;; This is a recursive-descent parser, so give it a big stack.
7342 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7343 (max-specpdl-size (max max-specpdl-size 3000))
7344 (case-fold-search nil)
7345 ast)
7346 (message nil) ; clear any error message from previous parse
7347 (save-excursion
7348 (when buf (set-buffer buf))
7349 (setq js2-scanned-comments nil
7350 js2-parsed-errors nil
7351 js2-parsed-warnings nil
7352 js2-imenu-recorder nil
7353 js2-imenu-function-map nil
7354 js2-label-set nil)
7355 (js2-init-scanner)
7356 (setq ast (js2-with-unmodifying-text-property-changes
7357 (js2-do-parse)))
7358 (unless js2-ts-hit-eof
7359 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7360 (setf (js2-ast-root-errors ast) js2-parsed-errors
7361 (js2-ast-root-warnings ast) js2-parsed-warnings)
7362 ;; if we didn't find any declarations, put a dummy in this list so we
7363 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7364 (unless js2-imenu-recorder
7365 (setq js2-imenu-recorder 'empty))
7366 (run-hooks 'js2-parse-finished-hook)
7367 ast)))
7368
7369 ;; Corresponds to Rhino's Parser.parse() method.
7370 (defun js2-do-parse ()
7371 "Parse current buffer starting from current point.
7372 Scanner should be initialized."
7373 (let ((pos js2-ts-cursor)
7374 (end js2-ts-cursor) ; in case file is empty
7375 root n tt)
7376 ;; initialize buffer-local parsing vars
7377 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7378 js2-current-script-or-fn root
7379 js2-current-scope root
7380 js2-current-flagged-token js2-EOF
7381 js2-nesting-of-function 0
7382 js2-labeled-stmt nil
7383 js2-recorded-identifiers nil) ; for js2-highlight
7384 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7385 (if (= tt js2-FUNCTION)
7386 (progn
7387 (js2-consume-token)
7388 (setq n (js2-parse-function (if js2-called-by-compile-function
7389 'FUNCTION_EXPRESSION
7390 'FUNCTION_STATEMENT))))
7391 ;; not a function - parse a statement
7392 (setq n (js2-parse-statement)))
7393 ;; add function or statement to script
7394 (setq end (js2-node-end n))
7395 (js2-block-node-push root n))
7396 ;; add comments to root in lexical order
7397 (when js2-scanned-comments
7398 ;; if we find a comment beyond end of normal kids, use its end
7399 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7400 (dolist (comment js2-scanned-comments)
7401 (push comment (js2-ast-root-comments root))
7402 (js2-node-add-children root comment)))
7403 (setf (js2-node-len root) (- end pos))
7404 ;; Give extensions a chance to muck with things before highlighting starts.
7405 (let ((js2-additional-externs js2-additional-externs))
7406 (dolist (callback js2-post-parse-callbacks)
7407 (funcall callback))
7408 (js2-highlight-undeclared-vars))
7409 root))
7410
7411 (defun js2-function-parser ()
7412 (js2-consume-token)
7413 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7414
7415 (defun js2-parse-function-closure-body (fn-node)
7416 "Parse a JavaScript 1.8 function closure body."
7417 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7418 (if js2-ts-hit-eof
7419 (js2-report-error "msg.no.brace.body" nil
7420 (js2-node-pos fn-node)
7421 (- js2-ts-cursor (js2-node-pos fn-node)))
7422 (js2-node-add-children fn-node
7423 (setf (js2-function-node-body fn-node)
7424 (js2-parse-expr t))))))
7425
7426 (defun js2-parse-function-body (fn-node)
7427 (js2-must-match js2-LC "msg.no.brace.body"
7428 (js2-node-pos fn-node)
7429 (- js2-ts-cursor (js2-node-pos fn-node)))
7430 (let ((pos js2-token-beg) ; LC position
7431 (pn (make-js2-block-node)) ; starts at LC position
7432 tt
7433 end)
7434 (incf js2-nesting-of-function)
7435 (unwind-protect
7436 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7437 (= tt js2-EOF)
7438 (= tt js2-RC)))
7439 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7440 (js2-parse-statement)
7441 (js2-consume-token)
7442 (js2-parse-function 'FUNCTION_STATEMENT))))
7443 (decf js2-nesting-of-function))
7444 (setq end js2-token-end) ; assume no curly and leave at current token
7445 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7446 (setq end js2-token-end))
7447 (setf (js2-node-pos pn) pos
7448 (js2-node-len pn) (- end pos))
7449 (setf (js2-function-node-body fn-node) pn)
7450 (js2-node-add-children fn-node pn)
7451 pn))
7452
7453 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7454 "Declare and fontify destructuring parameters inside NODE.
7455 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7456 (cond
7457 ((js2-name-node-p node)
7458 (let (leftpos)
7459 (js2-define-symbol decl-type (js2-name-node-name node)
7460 node ignore-not-in-block)
7461 (when face
7462 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7463 (+ leftpos (js2-node-len node))
7464 face 'record))))
7465 ((js2-object-node-p node)
7466 (dolist (elem (js2-object-node-elems node))
7467 (js2-define-destruct-symbols
7468 (if (js2-object-prop-node-p elem)
7469 (js2-object-prop-node-right elem)
7470 ;; abbreviated destructuring {a, b}
7471 elem)
7472 decl-type face ignore-not-in-block)))
7473 ((js2-array-node-p node)
7474 (dolist (elem (js2-array-node-elems node))
7475 (when elem
7476 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7477 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7478 (js2-node-len node)))))
7479
7480 (defun js2-parse-function-params (fn-node pos)
7481 (if (js2-match-token js2-RP)
7482 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7483 (let (params len param default-found rest-param-at)
7484 (loop for tt = (js2-peek-token)
7485 do
7486 (cond
7487 ;; destructuring param
7488 ((or (= tt js2-LB) (= tt js2-LC))
7489 (when default-found
7490 (js2-report-error "msg.no.default.after.default.param"))
7491 (setq param (js2-parse-destruct-primary-expr))
7492 (js2-define-destruct-symbols param
7493 js2-LP
7494 'js2-function-param-face)
7495 (push param params))
7496 ;; variable name
7497 (t
7498 (when (and (>= js2-language-version 200)
7499 (js2-match-token js2-TRIPLEDOT)
7500 (not rest-param-at))
7501 ;; to report errors if there are more parameters
7502 (setq rest-param-at (length params)))
7503 (js2-must-match js2-NAME "msg.no.parm")
7504 (js2-record-face 'js2-function-param-face)
7505 (setq param (js2-create-name-node))
7506 (js2-define-symbol js2-LP js2-ts-string param)
7507 ;; default parameter value
7508 (when (or (and default-found
7509 (not rest-param-at)
7510 (js2-must-match js2-ASSIGN
7511 "msg.no.default.after.default.param"
7512 (js2-node-pos param)
7513 (js2-node-len param)))
7514 (and (>= js2-language-version 200)
7515 (js2-match-token js2-ASSIGN)))
7516 (let* ((pos (js2-node-pos param))
7517 (tt js2-current-token)
7518 (op-pos (- js2-token-beg pos))
7519 (left param)
7520 (right (js2-parse-assign-expr))
7521 (len (- (js2-node-end right) pos)))
7522 (setq param (make-js2-assign-node
7523 :type tt :pos pos :len len :op-pos op-pos
7524 :left left :right right)
7525 default-found t)
7526 (js2-node-add-children param left right)))
7527 (push param params)))
7528 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7529 (js2-report-error "msg.param.after.rest" nil
7530 (js2-node-pos param) (js2-node-len param)))
7531 while
7532 (js2-match-token js2-COMMA))
7533 (when (js2-must-match js2-RP "msg.no.paren.after.parms")
7534 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7535 (when rest-param-at
7536 (setf (js2-function-node-rest-p fn-node) t))
7537 (dolist (p params)
7538 (js2-node-add-children fn-node p)
7539 (push p (js2-function-node-params fn-node))))))
7540
7541 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7542 "Possibly show inconsistent-return warning.
7543 Last token scanned is the close-curly for the function body."
7544 (when (and js2-mode-show-strict-warnings
7545 js2-strict-inconsistent-return-warning
7546 (not (js2-has-consistent-return-usage
7547 (js2-function-node-body fn-node))))
7548 ;; Have it extend from close-curly to bol or beginning of block.
7549 (let ((pos (save-excursion
7550 (goto-char js2-token-end)
7551 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7552 (point-at-bol))))
7553 (end js2-token-end))
7554 (if (plusp (js2-name-node-length name))
7555 (js2-add-strict-warning "msg.no.return.value"
7556 (js2-name-node-name name) pos end)
7557 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7558
7559 (defun js2-parse-function (function-type)
7560 "Function parser. FUNCTION-TYPE is a symbol."
7561 (let ((pos js2-token-beg) ; start of 'function' keyword
7562 name
7563 name-beg
7564 name-end
7565 fn-node
7566 lp
7567 (synthetic-type function-type)
7568 member-expr-node)
7569 ;; parse function name, expression, or non-name (anonymous)
7570 (cond
7571 ;; function foo(...)
7572 ((js2-match-token js2-NAME)
7573 (setq name (js2-create-name-node t)
7574 name-beg js2-token-beg
7575 name-end js2-token-end)
7576 (unless (js2-match-token js2-LP)
7577 (when js2-allow-member-expr-as-function-name
7578 ;; function foo.bar(...)
7579 (setq member-expr-node name
7580 name nil
7581 member-expr-node (js2-parse-member-expr-tail
7582 nil member-expr-node)))
7583 (js2-must-match js2-LP "msg.no.paren.parms")))
7584 ((js2-match-token js2-LP)
7585 nil) ; anonymous function: leave name as null
7586 (t
7587 ;; function random-member-expr(...)
7588 (when js2-allow-member-expr-as-function-name
7589 ;; Note that memberExpr can not start with '(' like
7590 ;; in function (1+2).toString(), because 'function (' already
7591 ;; processed as anonymous function
7592 (setq member-expr-node (js2-parse-member-expr)))
7593 (js2-must-match js2-LP "msg.no.paren.parms")))
7594 (if (= js2-current-token js2-LP) ; eventually matched LP?
7595 (setq lp js2-token-beg))
7596 (if member-expr-node
7597 (progn
7598 (setq synthetic-type 'FUNCTION_EXPRESSION)
7599 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7600 (if name
7601 (js2-set-face name-beg name-end
7602 'font-lock-function-name-face 'record)))
7603 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7604 (plusp (js2-name-node-length name)))
7605 ;; Function statements define a symbol in the enclosing scope
7606 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7607 (setf fn-node (make-js2-function-node :pos pos
7608 :name name
7609 :form function-type
7610 :lp (if lp (- lp pos))))
7611 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7612 ;; 1. Nested functions are not affected by the dynamic scope flag
7613 ;; as dynamic scope is already a parent of their scope.
7614 ;; 2. Functions defined under the with statement also immune to
7615 ;; this setup, in which case dynamic scope is ignored in favor
7616 ;; of the with object.
7617 (setf (js2-function-node-ignore-dynamic fn-node) t))
7618 ;; dynamically bind all the per-function variables
7619 (let ((js2-current-script-or-fn fn-node)
7620 (js2-current-scope fn-node)
7621 (js2-nesting-of-with 0)
7622 (js2-end-flags 0)
7623 js2-label-set
7624 js2-loop-set
7625 js2-loop-and-switch-set)
7626 (js2-parse-function-params fn-node pos)
7627 (if (and (>= js2-language-version 180)
7628 (/= (js2-peek-token) js2-LC))
7629 (js2-parse-function-closure-body fn-node)
7630 (js2-parse-function-body fn-node))
7631 (if name
7632 (js2-node-add-children fn-node name))
7633 (js2-check-inconsistent-return-warning fn-node name)
7634 ;; Function expressions define a name only in the body of the
7635 ;; function, and only if not hidden by a parameter name
7636 (if (and name
7637 (eq synthetic-type 'FUNCTION_EXPRESSION)
7638 (null (js2-scope-get-symbol js2-current-scope
7639 (js2-name-node-name name))))
7640 (js2-define-symbol js2-FUNCTION
7641 (js2-name-node-name name)
7642 fn-node))
7643 (if (and name
7644 (not (eq function-type 'FUNCTION_EXPRESSION)))
7645 (js2-record-imenu-functions fn-node)))
7646 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7647 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7648 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7649 ;; We wait until after parsing the function to set its parent scope,
7650 ;; since `js2-define-symbol' needs the defining-scope check to stop
7651 ;; at the function boundary when checking for redeclarations.
7652 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7653 fn-node))
7654
7655 (defun js2-parse-statements (&optional parent)
7656 "Parse a statement list. Last token consumed must be js2-LC.
7657
7658 PARENT can be a `js2-block-node', in which case the statements are
7659 appended to PARENT. Otherwise a new `js2-block-node' is created
7660 and returned.
7661
7662 This function does not match the closing js2-RC: the caller
7663 matches the RC so it can provide a suitable error message if not
7664 matched. This means it's up to the caller to set the length of
7665 the node to include the closing RC. The node start pos is set to
7666 the absolute buffer start position, and the caller should fix it
7667 up to be relative to the parent node. All children of this block
7668 node are given relative start positions and correct lengths."
7669 (let ((pn (or parent (make-js2-block-node)))
7670 tt)
7671 (setf (js2-node-pos pn) js2-token-beg)
7672 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7673 (/= tt js2-RC))
7674 (js2-block-node-push pn (js2-parse-statement)))
7675 pn))
7676
7677 (defun js2-parse-statement ()
7678 (let (tt pn beg end)
7679 ;; coarse-grained user-interrupt check - needs work
7680 (and js2-parse-interruptable-p
7681 (zerop (% (incf js2-parse-stmt-count)
7682 js2-statements-per-pause))
7683 (input-pending-p)
7684 (throw 'interrupted t))
7685 (setq pn (js2-statement-helper))
7686 ;; no-side-effects warning check
7687 (unless (js2-node-has-side-effects pn)
7688 (setq end (js2-node-end pn))
7689 (save-excursion
7690 (goto-char end)
7691 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7692 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7693 pn))
7694
7695 ;; These correspond to the switch cases in Parser.statementHelper
7696 (defconst js2-parsers
7697 (let ((parsers (make-vector js2-num-tokens
7698 #'js2-parse-expr-stmt)))
7699 (aset parsers js2-BREAK #'js2-parse-break)
7700 (aset parsers js2-CONST #'js2-parse-const-var)
7701 (aset parsers js2-CONTINUE #'js2-parse-continue)
7702 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7703 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7704 (aset parsers js2-DO #'js2-parse-do)
7705 (aset parsers js2-FOR #'js2-parse-for)
7706 (aset parsers js2-FUNCTION #'js2-function-parser)
7707 (aset parsers js2-IF #'js2-parse-if)
7708 (aset parsers js2-LC #'js2-parse-block)
7709 (aset parsers js2-LET #'js2-parse-let-stmt)
7710 (aset parsers js2-NAME #'js2-parse-name-or-label)
7711 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7712 (aset parsers js2-SEMI #'js2-parse-semi)
7713 (aset parsers js2-SWITCH #'js2-parse-switch)
7714 (aset parsers js2-THROW #'js2-parse-throw)
7715 (aset parsers js2-TRY #'js2-parse-try)
7716 (aset parsers js2-VAR #'js2-parse-const-var)
7717 (aset parsers js2-WHILE #'js2-parse-while)
7718 (aset parsers js2-WITH #'js2-parse-with)
7719 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7720 parsers)
7721 "A vector mapping token types to parser functions.")
7722
7723 (defsubst js2-parse-warn-missing-semi (beg end)
7724 (and js2-mode-show-strict-warnings
7725 js2-strict-missing-semi-warning
7726 (js2-add-strict-warning
7727 "msg.missing.semi" nil
7728 ;; back up to beginning of statement or line
7729 (max beg (save-excursion
7730 (goto-char end)
7731 (point-at-bol)))
7732 end)))
7733
7734 (defconst js2-no-semi-insertion
7735 (list js2-IF
7736 js2-SWITCH
7737 js2-WHILE
7738 js2-DO
7739 js2-FOR
7740 js2-TRY
7741 js2-WITH
7742 js2-LC
7743 js2-ERROR
7744 js2-SEMI
7745 js2-FUNCTION)
7746 "List of tokens that don't do automatic semicolon insertion.")
7747
7748 (defconst js2-autoinsert-semi-and-warn
7749 (list js2-ERROR js2-EOF js2-RC))
7750
7751 (defun js2-statement-helper ()
7752 (let* ((tt (js2-peek-token))
7753 (first-tt tt)
7754 (beg js2-token-beg)
7755 (parser (if (= tt js2-ERROR)
7756 #'js2-parse-semi
7757 (aref js2-parsers tt)))
7758 pn
7759 tt-flagged)
7760 ;; If the statement is set, then it's been told its label by now.
7761 (and js2-labeled-stmt
7762 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7763 (setq js2-labeled-stmt nil))
7764 (setq pn (funcall parser))
7765 ;; Don't do auto semi insertion for certain statement types.
7766 (unless (or (memq first-tt js2-no-semi-insertion)
7767 (js2-labeled-stmt-node-p pn))
7768 (js2-auto-insert-semicolon pn))
7769 pn))
7770
7771 (defun js2-auto-insert-semicolon (pn)
7772 (let* ((tt-flagged (js2-peek-flagged-token))
7773 (tt (logand tt-flagged js2-clear-ti-mask))
7774 (pos (js2-node-pos pn)))
7775 (cond
7776 ((= tt js2-SEMI)
7777 ;; Consume ';' as a part of expression
7778 (js2-consume-token)
7779 ;; extend the node bounds to include the semicolon.
7780 (setf (js2-node-len pn) (- js2-token-end pos)))
7781 ((memq tt js2-autoinsert-semi-and-warn)
7782 ;; Autoinsert ;
7783 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7784 (t
7785 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7786 ;; Report error if no EOL or autoinsert ';' otherwise
7787 (js2-report-error "msg.no.semi.stmt")
7788 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7789
7790 (defun js2-parse-condition ()
7791 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7792 The parens are discarded and the expression node is returned.
7793 The `pos' field of the return value is set to an absolute position
7794 that must be fixed up by the caller.
7795 Return value is a list (EXPR LP RP), with absolute paren positions."
7796 (let (pn lp rp)
7797 (if (js2-must-match js2-LP "msg.no.paren.cond")
7798 (setq lp js2-token-beg))
7799 (setq pn (js2-parse-expr))
7800 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7801 (setq rp js2-token-beg))
7802 ;; Report strict warning on code like "if (a = 7) ..."
7803 (if (and js2-strict-cond-assign-warning
7804 (js2-assign-node-p pn))
7805 (js2-add-strict-warning "msg.equal.as.assign" nil
7806 (js2-node-pos pn)
7807 (+ (js2-node-pos pn)
7808 (js2-node-len pn))))
7809 (list pn lp rp)))
7810
7811 (defun js2-parse-if ()
7812 "Parser for if-statement. Last matched token must be js2-IF."
7813 (let ((pos js2-token-beg)
7814 cond
7815 if-true
7816 if-false
7817 else-pos
7818 end
7819 pn)
7820 (js2-consume-token)
7821 (setq cond (js2-parse-condition)
7822 if-true (js2-parse-statement)
7823 if-false (if (js2-match-token js2-ELSE)
7824 (progn
7825 (setq else-pos (- js2-token-beg pos))
7826 (js2-parse-statement)))
7827 end (js2-node-end (or if-false if-true))
7828 pn (make-js2-if-node :pos pos
7829 :len (- end pos)
7830 :condition (car cond)
7831 :then-part if-true
7832 :else-part if-false
7833 :else-pos else-pos
7834 :lp (js2-relpos (second cond) pos)
7835 :rp (js2-relpos (third cond) pos)))
7836 (js2-node-add-children pn (car cond) if-true if-false)
7837 pn))
7838
7839 (defun js2-parse-switch ()
7840 "Parser for if-statement. Last matched token must be js2-SWITCH."
7841 (let ((pos js2-token-beg)
7842 tt
7843 pn
7844 discriminant
7845 has-default
7846 case-expr
7847 case-node
7848 case-pos
7849 cases
7850 stmt
7851 lp
7852 rp)
7853 (js2-consume-token)
7854 (if (js2-must-match js2-LP "msg.no.paren.switch")
7855 (setq lp js2-token-beg))
7856 (setq discriminant (js2-parse-expr)
7857 pn (make-js2-switch-node :discriminant discriminant
7858 :pos pos
7859 :lp (js2-relpos lp pos)))
7860 (js2-node-add-children pn discriminant)
7861 (js2-enter-switch pn)
7862 (unwind-protect
7863 (progn
7864 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7865 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7866 (js2-must-match js2-LC "msg.no.brace.switch")
7867 (catch 'break
7868 (while t
7869 (setq tt (js2-next-token)
7870 case-pos js2-token-beg)
7871 (cond
7872 ((= tt js2-RC)
7873 (setf (js2-node-len pn) (- js2-token-end pos))
7874 (throw 'break nil)) ; done
7875 ((= tt js2-CASE)
7876 (setq case-expr (js2-parse-expr))
7877 (js2-must-match js2-COLON "msg.no.colon.case"))
7878 ((= tt js2-DEFAULT)
7879 (if has-default
7880 (js2-report-error "msg.double.switch.default"))
7881 (setq has-default t
7882 case-expr nil)
7883 (js2-must-match js2-COLON "msg.no.colon.case"))
7884 (t
7885 (js2-report-error "msg.bad.switch")
7886 (throw 'break nil)))
7887 (setq case-node (make-js2-case-node :pos case-pos
7888 :len (- js2-token-end case-pos)
7889 :expr case-expr))
7890 (js2-node-add-children case-node case-expr)
7891 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7892 (/= tt js2-CASE)
7893 (/= tt js2-DEFAULT)
7894 (/= tt js2-EOF))
7895 (setf stmt (js2-parse-statement)
7896 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7897 (js2-block-node-push case-node stmt))
7898 (push case-node cases)))
7899 ;; add cases last, as pushing reverses the order to be correct
7900 (dolist (kid cases)
7901 (js2-node-add-children pn kid)
7902 (push kid (js2-switch-node-cases pn)))
7903 pn) ; return value
7904 (js2-exit-switch))))
7905
7906 (defun js2-parse-while ()
7907 "Parser for while-statement. Last matched token must be js2-WHILE."
7908 (let ((pos js2-token-beg)
7909 (pn (make-js2-while-node))
7910 cond
7911 body)
7912 (js2-consume-token)
7913 (js2-enter-loop pn)
7914 (unwind-protect
7915 (progn
7916 (setf cond (js2-parse-condition)
7917 (js2-while-node-condition pn) (car cond)
7918 body (js2-parse-statement)
7919 (js2-while-node-body pn) body
7920 (js2-node-len pn) (- (js2-node-end body) pos)
7921 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7922 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7923 (js2-node-add-children pn body (car cond)))
7924 (js2-exit-loop))
7925 pn))
7926
7927 (defun js2-parse-do ()
7928 "Parser for do-statement. Last matched token must be js2-DO."
7929 (let ((pos js2-token-beg)
7930 (pn (make-js2-do-node))
7931 cond
7932 body
7933 end)
7934 (js2-consume-token)
7935 (js2-enter-loop pn)
7936 (unwind-protect
7937 (progn
7938 (setq body (js2-parse-statement))
7939 (js2-must-match js2-WHILE "msg.no.while.do")
7940 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7941 cond (js2-parse-condition)
7942 (js2-do-node-condition pn) (car cond)
7943 (js2-do-node-body pn) body
7944 end js2-ts-cursor
7945 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7946 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7947 (js2-node-add-children pn (car cond) body))
7948 (js2-exit-loop))
7949 ;; Always auto-insert semicolon to follow SpiderMonkey:
7950 ;; It is required by ECMAScript but is ignored by the rest of
7951 ;; world; see bug 238945
7952 (if (js2-match-token js2-SEMI)
7953 (setq end js2-ts-cursor))
7954 (setf (js2-node-len pn) (- end pos))
7955 pn))
7956
7957 (defun js2-parse-for ()
7958 "Parser for for-statement. Last matched token must be js2-FOR.
7959 Parses for, for-in, and for each-in statements."
7960 (let ((for-pos js2-token-beg)
7961 pn
7962 is-for-each
7963 is-for-in-or-of
7964 is-for-of
7965 in-pos
7966 each-pos
7967 tmp-pos
7968 init ; Node init is also foo in 'foo in object'
7969 cond ; Node cond is also object in 'foo in object'
7970 incr ; 3rd section of for-loop initializer
7971 body
7972 tt
7973 lp
7974 rp)
7975 (js2-consume-token)
7976 ;; See if this is a for each () instead of just a for ()
7977 (when (js2-match-token js2-NAME)
7978 (if (string= "each" js2-ts-string)
7979 (progn
7980 (setq is-for-each t
7981 each-pos (- js2-token-beg for-pos)) ; relative
7982 (js2-record-face 'font-lock-keyword-face))
7983 (js2-report-error "msg.no.paren.for")))
7984 (if (js2-must-match js2-LP "msg.no.paren.for")
7985 (setq lp (- js2-token-beg for-pos)))
7986 (setq tt (js2-peek-token))
7987 ;; 'for' makes local scope
7988 (js2-push-scope (make-js2-scope))
7989 (unwind-protect
7990 ;; parse init clause
7991 (let ((js2-in-for-init t)) ; set as dynamic variable
7992 (cond
7993 ((= tt js2-SEMI)
7994 (setq init (make-js2-empty-expr-node)))
7995 ((or (= tt js2-VAR) (= tt js2-LET))
7996 (js2-consume-token)
7997 (setq init (js2-parse-variables tt js2-token-beg)))
7998 (t
7999 (setq init (js2-parse-expr)))))
8000 (if (or (js2-match-token js2-IN)
8001 (and (>= js2-language-version 200)
8002 (js2-match-contextual-kwd "of")
8003 (setq is-for-of t)))
8004 (setq is-for-in-or-of t
8005 in-pos (- js2-token-beg for-pos)
8006 ;; scope of iteration target object is not the scope we've created above.
8007 ;; stash current scope temporary.
8008 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8009 (js2-parse-expr))) ; object over which we're iterating
8010 ;; else ordinary for loop - parse cond and incr
8011 (js2-must-match js2-SEMI "msg.no.semi.for")
8012 (setq cond (if (= (js2-peek-token) js2-SEMI)
8013 (make-js2-empty-expr-node) ; no loop condition
8014 (js2-parse-expr)))
8015 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8016 (setq tmp-pos js2-token-end
8017 incr (if (= (js2-peek-token) js2-RP)
8018 (make-js2-empty-expr-node :pos tmp-pos)
8019 (js2-parse-expr))))
8020 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8021 (setq rp (- js2-token-beg for-pos)))
8022 (if (not is-for-in-or-of)
8023 (setq pn (make-js2-for-node :init init
8024 :condition cond
8025 :update incr
8026 :lp lp
8027 :rp rp))
8028 ;; cond could be null if 'in obj' got eaten by the init node.
8029 (if (js2-infix-node-p init)
8030 ;; it was (foo in bar) instead of (var foo in bar)
8031 (setq cond (js2-infix-node-right init)
8032 init (js2-infix-node-left init))
8033 (if (and (js2-var-decl-node-p init)
8034 (> (length (js2-var-decl-node-kids init)) 1))
8035 (js2-report-error "msg.mult.index")))
8036 (setq pn (make-js2-for-in-node :iterator init
8037 :object cond
8038 :in-pos in-pos
8039 :foreach-p is-for-each
8040 :each-pos each-pos
8041 :forof-p is-for-of
8042 :lp lp
8043 :rp rp)))
8044 (unwind-protect
8045 (progn
8046 (js2-enter-loop pn)
8047 ;; We have to parse the body -after- creating the loop node,
8048 ;; so that the loop node appears in the js2-loop-set, allowing
8049 ;; break/continue statements to find the enclosing loop.
8050 (setf body (js2-parse-statement)
8051 (js2-loop-node-body pn) body
8052 (js2-node-pos pn) for-pos
8053 (js2-node-len pn) (- (js2-node-end body) for-pos))
8054 (js2-node-add-children pn init cond incr body))
8055 ;; finally
8056 (js2-exit-loop))
8057 (js2-pop-scope))
8058 pn))
8059
8060 (defun js2-parse-try ()
8061 "Parser for try-statement. Last matched token must be js2-TRY."
8062 (let ((try-pos js2-token-beg)
8063 try-end
8064 try-block
8065 catch-blocks
8066 finally-block
8067 saw-default-catch
8068 peek
8069 param
8070 catch-cond
8071 catch-node
8072 guard-kwd
8073 catch-pos
8074 finally-pos
8075 pn
8076 block
8077 lp
8078 rp)
8079 (js2-consume-token)
8080 (if (/= (js2-peek-token) js2-LC)
8081 (js2-report-error "msg.no.brace.try"))
8082 (setq try-block (js2-parse-statement)
8083 try-end (js2-node-end try-block)
8084 peek (js2-peek-token))
8085 (cond
8086 ((= peek js2-CATCH)
8087 (while (js2-match-token js2-CATCH)
8088 (setq catch-pos js2-token-beg
8089 guard-kwd nil
8090 catch-cond nil
8091 lp nil
8092 rp nil)
8093 (if saw-default-catch
8094 (js2-report-error "msg.catch.unreachable"))
8095 (if (js2-must-match js2-LP "msg.no.paren.catch")
8096 (setq lp (- js2-token-beg catch-pos)))
8097 (js2-push-scope (make-js2-scope))
8098 (let ((tt (js2-peek-token)))
8099 (cond
8100 ;; destructuring pattern
8101 ;; catch ({ message, file }) { ... }
8102 ((or (= tt js2-LB) (= tt js2-LC))
8103 (setq param (js2-parse-destruct-primary-expr))
8104 (js2-define-destruct-symbols param js2-LET nil))
8105 ;; simple name
8106 (t
8107 (js2-must-match js2-NAME "msg.bad.catchcond")
8108 (setq param (js2-create-name-node))
8109 (js2-define-symbol js2-LET js2-ts-string param))))
8110 ;; pattern guard
8111 (if (js2-match-token js2-IF)
8112 (setq guard-kwd (- js2-token-beg catch-pos)
8113 catch-cond (js2-parse-expr))
8114 (setq saw-default-catch t))
8115 (if (js2-must-match js2-RP "msg.bad.catchcond")
8116 (setq rp (- js2-token-beg catch-pos)))
8117 (js2-must-match js2-LC "msg.no.brace.catchblock")
8118 (setq block (js2-parse-statements)
8119 try-end (js2-node-end block)
8120 catch-node (make-js2-catch-node :pos catch-pos
8121 :param param
8122 :guard-expr catch-cond
8123 :guard-kwd guard-kwd
8124 :block block
8125 :lp lp
8126 :rp rp))
8127 (js2-pop-scope)
8128 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8129 (setq try-end js2-token-beg))
8130 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8131 (js2-node-len catch-node) (- try-end catch-pos))
8132 (js2-node-add-children catch-node param catch-cond block)
8133 (push catch-node catch-blocks)))
8134 ((/= peek js2-FINALLY)
8135 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8136 (js2-node-pos try-block)
8137 (- (setq try-end (js2-node-end try-block))
8138 (js2-node-pos try-block)))))
8139 (when (js2-match-token js2-FINALLY)
8140 (setq finally-pos js2-token-beg
8141 block (js2-parse-statement)
8142 try-end (js2-node-end block)
8143 finally-block (make-js2-finally-node :pos finally-pos
8144 :len (- try-end finally-pos)
8145 :body block))
8146 (js2-node-add-children finally-block block))
8147 (setq pn (make-js2-try-node :pos try-pos
8148 :len (- try-end try-pos)
8149 :try-block try-block
8150 :finally-block finally-block))
8151 (js2-node-add-children pn try-block finally-block)
8152 ;; push them onto the try-node, which reverses and corrects their order
8153 (dolist (cb catch-blocks)
8154 (js2-node-add-children pn cb)
8155 (push cb (js2-try-node-catch-clauses pn)))
8156 pn))
8157
8158 (defun js2-parse-throw ()
8159 "Parser for throw-statement. Last matched token must be js2-THROW."
8160 (let ((pos js2-token-beg)
8161 expr
8162 pn)
8163 (js2-consume-token)
8164 (if (= (js2-peek-token-or-eol) js2-EOL)
8165 ;; ECMAScript does not allow new lines before throw expression,
8166 ;; see bug 256617
8167 (js2-report-error "msg.bad.throw.eol"))
8168 (setq expr (js2-parse-expr)
8169 pn (make-js2-throw-node :pos pos
8170 :len (- (js2-node-end expr) pos)
8171 :expr expr))
8172 (js2-node-add-children pn expr)
8173 pn))
8174
8175 (defsubst js2-match-jump-label-name (label-name)
8176 "If break/continue specified a label, return that label's labeled stmt.
8177 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8178 does not match an existing label, reports an error and returns nil."
8179 (let ((bundle (cdr (assoc label-name js2-label-set))))
8180 (if (null bundle)
8181 (js2-report-error "msg.undef.label"))
8182 bundle))
8183
8184 (defun js2-parse-break ()
8185 "Parser for break-statement. Last matched token must be js2-BREAK."
8186 (let ((pos js2-token-beg)
8187 (end js2-token-end)
8188 break-target ; statement to break from
8189 break-label ; in "break foo", name-node representing the foo
8190 labels ; matching labeled statement to break to
8191 pn)
8192 (js2-consume-token) ; `break'
8193 (when (eq (js2-peek-token-or-eol) js2-NAME)
8194 (js2-consume-token)
8195 (setq break-label (js2-create-name-node)
8196 end (js2-node-end break-label)
8197 ;; matchJumpLabelName only matches if there is one
8198 labels (js2-match-jump-label-name js2-ts-string)
8199 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8200 (unless (or break-target break-label)
8201 ;; no break target specified - try for innermost enclosing loop/switch
8202 (if (null js2-loop-and-switch-set)
8203 (unless break-label
8204 (js2-report-error "msg.bad.break" nil pos (length "break")))
8205 (setq break-target (car js2-loop-and-switch-set))))
8206 (setq pn (make-js2-break-node :pos pos
8207 :len (- end pos)
8208 :label break-label
8209 :target break-target))
8210 (js2-node-add-children pn break-label) ; but not break-target
8211 pn))
8212
8213 (defun js2-parse-continue ()
8214 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8215 (let ((pos js2-token-beg)
8216 (end js2-token-end)
8217 label ; optional user-specified label, a `js2-name-node'
8218 labels ; current matching labeled stmt, if any
8219 target ; the `js2-loop-node' target of this continue stmt
8220 pn)
8221 (js2-consume-token) ; `continue'
8222 (when (= (js2-peek-token-or-eol) js2-NAME)
8223 (js2-consume-token)
8224 (setq label (js2-create-name-node)
8225 end (js2-node-end label)
8226 ;; matchJumpLabelName only matches if there is one
8227 labels (js2-match-jump-label-name js2-ts-string)))
8228 (cond
8229 ((null labels) ; no current label to go to
8230 (if (null js2-loop-set) ; no loop to continue to
8231 (js2-report-error "msg.continue.outside" nil pos
8232 (length "continue"))
8233 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8234 (t
8235 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8236 (setq target (js2-labeled-stmt-node-stmt labels))
8237 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8238 (setq pn (make-js2-continue-node :pos pos
8239 :len (- end pos)
8240 :label label
8241 :target target))
8242 (js2-node-add-children pn label) ; but not target - it's not our child
8243 pn))
8244
8245 (defun js2-parse-with ()
8246 "Parser for with-statement. Last matched token must be js2-WITH."
8247 (js2-consume-token)
8248 (let ((pos js2-token-beg)
8249 obj body pn lp rp)
8250 (if (js2-must-match js2-LP "msg.no.paren.with")
8251 (setq lp js2-token-beg))
8252 (setq obj (js2-parse-expr))
8253 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8254 (setq rp js2-token-beg))
8255 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8256 (setq body (js2-parse-statement)))
8257 (setq pn (make-js2-with-node :pos pos
8258 :len (- (js2-node-end body) pos)
8259 :object obj
8260 :body body
8261 :lp (js2-relpos lp pos)
8262 :rp (js2-relpos rp pos)))
8263 (js2-node-add-children pn obj body)
8264 pn))
8265
8266 (defun js2-parse-const-var ()
8267 "Parser for var- or const-statement.
8268 Last matched token must be js2-CONST or js2-VAR."
8269 (let ((tt (js2-peek-token))
8270 (pos js2-token-beg)
8271 expr
8272 pn)
8273 (js2-consume-token)
8274 (setq expr (js2-parse-variables tt js2-token-beg)
8275 pn (make-js2-expr-stmt-node :pos pos
8276 :len (- (js2-node-end expr) pos)
8277 :expr expr))
8278 (js2-node-add-children pn expr)
8279 pn))
8280
8281 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8282 (let ((pn (make-js2-expr-stmt-node :pos pos
8283 :len (js2-node-len expr)
8284 :type (if (js2-inside-function)
8285 js2-EXPR_VOID
8286 js2-EXPR_RESULT)
8287 :expr expr)))
8288 (if add-child
8289 (js2-node-add-children pn expr))
8290 pn))
8291
8292 (defun js2-parse-let-stmt ()
8293 "Parser for let-statement. Last matched token must be js2-LET."
8294 (js2-consume-token)
8295 (let ((pos js2-token-beg)
8296 expr
8297 pn)
8298 (if (= (js2-peek-token) js2-LP)
8299 ;; let expression in statement context
8300 (setq expr (js2-parse-let pos 'statement)
8301 pn (js2-wrap-with-expr-stmt pos expr t))
8302 ;; else we're looking at a statement like let x=6, y=7;
8303 (setf expr (js2-parse-variables js2-LET pos)
8304 pn (js2-wrap-with-expr-stmt pos expr t)
8305 (js2-node-type pn) js2-EXPR_RESULT))
8306 pn))
8307
8308 (defun js2-parse-ret-yield ()
8309 (js2-parse-return-or-yield (js2-peek-token) nil))
8310
8311 (defconst js2-parse-return-stmt-enders
8312 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8313
8314 (defsubst js2-now-all-set (before after mask)
8315 "Return whether or not the bits in the mask have changed to all set.
8316 BEFORE is bits before change, AFTER is bits after change, and MASK is
8317 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8318 but not BEFORE."
8319 (and (/= (logand before mask) mask)
8320 (= (logand after mask) mask)))
8321
8322 (defun js2-parse-return-or-yield (tt expr-context)
8323 (let ((pos js2-token-beg)
8324 (end js2-token-end)
8325 (before js2-end-flags)
8326 (inside-function (js2-inside-function))
8327 e
8328 ret
8329 name)
8330 (unless inside-function
8331 (js2-report-error (if (eq tt js2-RETURN)
8332 "msg.bad.return"
8333 "msg.bad.yield")))
8334 (js2-consume-token)
8335 ;; This is ugly, but we don't want to require a semicolon.
8336 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8337 (setq e (js2-parse-expr)
8338 end (js2-node-end e)))
8339 (cond
8340 ((eq tt js2-RETURN)
8341 (js2-set-flag js2-end-flags (if (null e)
8342 js2-end-returns
8343 js2-end-returns-value))
8344 (setq ret (make-js2-return-node :pos pos
8345 :len (- end pos)
8346 :retval e))
8347 (js2-node-add-children ret e)
8348 ;; See if we need a strict mode warning.
8349 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8350 ;; more thorough and accurate than this before/after flag check.
8351 ;; E.g. if there's a finally-block that always returns, we shouldn't
8352 ;; show a warning generated by inconsistent returns in the catch blocks.
8353 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8354 ;; so we know which returns/yields to highlight, and we should get rid of
8355 ;; all the checking in `js2-parse-return-or-yield'.
8356 (if (and js2-strict-inconsistent-return-warning
8357 (js2-now-all-set before js2-end-flags
8358 (logior js2-end-returns js2-end-returns-value)))
8359 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8360 (t
8361 (unless (js2-inside-function)
8362 (js2-report-error "msg.bad.yield"))
8363 (js2-set-flag js2-end-flags js2-end-yields)
8364 (setq ret (make-js2-yield-node :pos pos
8365 :len (- end pos)
8366 :value e))
8367 (js2-node-add-children ret e)
8368 (unless expr-context
8369 (setq e ret
8370 ret (js2-wrap-with-expr-stmt pos e t))
8371 (js2-set-requires-activation)
8372 (js2-set-is-generator))))
8373 ;; see if we are mixing yields and value returns.
8374 (when (and inside-function
8375 (js2-now-all-set before js2-end-flags
8376 (logior js2-end-yields js2-end-returns-value)))
8377 (setq name (js2-function-name js2-current-script-or-fn))
8378 (if (zerop (length name))
8379 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8380 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8381 ret))
8382
8383 (defun js2-parse-debugger ()
8384 (js2-consume-token)
8385 (make-js2-keyword-node :type js2-DEBUGGER))
8386
8387 (defun js2-parse-block ()
8388 "Parser for a curly-delimited statement block.
8389 Last token matched must be js2-LC."
8390 (let ((pos js2-token-beg)
8391 (pn (make-js2-scope)))
8392 (js2-consume-token)
8393 (js2-push-scope pn)
8394 (unwind-protect
8395 (progn
8396 (js2-parse-statements pn)
8397 (js2-must-match js2-RC "msg.no.brace.block")
8398 (setf (js2-node-len pn) (- js2-token-end pos)))
8399 (js2-pop-scope))
8400 pn))
8401
8402 ;; for js2-ERROR too, to have a node for error recovery to work on
8403 (defun js2-parse-semi ()
8404 "Parse a statement or handle an error.
8405 Last matched token is js2-SEMI or js2-ERROR."
8406 (let ((tt (js2-peek-token)) pos len)
8407 (js2-consume-token)
8408 (if (eq tt js2-SEMI)
8409 (make-js2-empty-expr-node :len 1)
8410 (setq pos js2-token-beg
8411 len (- js2-token-beg pos))
8412 (js2-report-error "msg.syntax" nil pos len)
8413 (make-js2-error-node :pos pos :len len))))
8414
8415 (defun js2-parse-default-xml-namespace ()
8416 "Parse a `default xml namespace = <expr>' e4x statement."
8417 (let ((pos js2-token-beg)
8418 end len expr unary es)
8419 (js2-consume-token)
8420 (js2-must-have-xml)
8421 (js2-set-requires-activation)
8422 (setq len (- js2-ts-cursor pos))
8423 (unless (and (js2-match-token js2-NAME)
8424 (string= js2-ts-string "xml"))
8425 (js2-report-error "msg.bad.namespace" nil pos len))
8426 (unless (and (js2-match-token js2-NAME)
8427 (string= js2-ts-string "namespace"))
8428 (js2-report-error "msg.bad.namespace" nil pos len))
8429 (unless (js2-match-token js2-ASSIGN)
8430 (js2-report-error "msg.bad.namespace" nil pos len))
8431 (setq expr (js2-parse-expr)
8432 end (js2-node-end expr)
8433 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8434 :pos pos
8435 :len (- end pos)
8436 :operand expr))
8437 (js2-node-add-children unary expr)
8438 (make-js2-expr-stmt-node :pos pos
8439 :len (- end pos)
8440 :expr unary)))
8441
8442 (defun js2-record-label (label bundle)
8443 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8444 (js2-consume-token)
8445 (let ((name (js2-label-node-name label))
8446 labeled-stmt
8447 dup)
8448 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8449 ;; flag both labels if possible when used in editing mode
8450 (if (and js2-parse-ide-mode
8451 (setq dup (js2-get-label-by-name labeled-stmt name)))
8452 (js2-report-error "msg.dup.label" nil
8453 (js2-node-abs-pos dup) (js2-node-len dup)))
8454 (js2-report-error "msg.dup.label" nil
8455 (js2-node-pos label) (js2-node-len label)))
8456 (js2-labeled-stmt-node-add-label bundle label)
8457 (js2-node-add-children bundle label)
8458 ;; Add one reference to the bundle per label in `js2-label-set'
8459 (push (cons name bundle) js2-label-set)))
8460
8461 (defun js2-parse-name-or-label ()
8462 "Parser for identifier or label. Last token matched must be js2-NAME.
8463 Called when we found a name in a statement context. If it's a label, we gather
8464 up any following labels and the next non-label statement into a
8465 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8466 expression and return it wrapped in a `js2-expr-stmt-node'."
8467 (let ((pos js2-token-beg)
8468 (end js2-token-end)
8469 expr
8470 stmt
8471 pn
8472 bundle
8473 (continue t))
8474 ;; set check for label and call down to `js2-parse-primary-expr'
8475 (js2-set-check-for-label)
8476 (setq expr (js2-parse-expr))
8477 (if (/= (js2-node-type expr) js2-LABEL)
8478 ;; Parsed non-label expression - wrap with expression stmt.
8479 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8480 ;; else parsed a label
8481 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8482 (js2-record-label expr bundle)
8483 ;; look for more labels
8484 (while (and continue (= (js2-peek-token) js2-NAME))
8485 (js2-set-check-for-label)
8486 (setq expr (js2-parse-expr))
8487 (if (/= (js2-node-type expr) js2-LABEL)
8488 (progn
8489 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8490 continue nil)
8491 (js2-auto-insert-semicolon stmt))
8492 (js2-record-label expr bundle)))
8493 ;; no more labels; now parse the labeled statement
8494 (unwind-protect
8495 (unless stmt
8496 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8497 (setq stmt (js2-statement-helper))))
8498 ;; remove the labels for this statement from the global set
8499 (dolist (label (js2-labeled-stmt-node-labels bundle))
8500 (setq js2-label-set (remove label js2-label-set))))
8501 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8502 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8503 (js2-node-add-children bundle stmt)
8504 bundle)))
8505
8506 (defun js2-parse-expr-stmt ()
8507 "Default parser in statement context, if no recognized statement found."
8508 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8509
8510 (defun js2-parse-variables (decl-type pos)
8511 "Parse a comma-separated list of variable declarations.
8512 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8513
8514 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8515 For 'var' or 'const', the keyword should be the token last scanned.
8516
8517 POS is the position where the node should start. It's sometimes the
8518 var/const/let keyword, and other times the beginning of the first token
8519 in the first variable declaration.
8520
8521 Returns the parsed `js2-var-decl-node' expression node."
8522 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8523 :pos pos))
8524 destructuring
8525 kid-pos
8526 tt
8527 init
8528 name
8529 end
8530 nbeg nend
8531 vi
8532 (continue t))
8533 ;; Example:
8534 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8535 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8536 ;; var {a, b} = baz;
8537 (while continue
8538 (setq destructuring nil
8539 name nil
8540 tt (js2-peek-token)
8541 kid-pos js2-token-beg
8542 end js2-token-end
8543 init nil)
8544 (if (or (= tt js2-LB) (= tt js2-LC))
8545 ;; Destructuring assignment, e.g., var [a, b] = ...
8546 (setq destructuring (js2-parse-destruct-primary-expr)
8547 end (js2-node-end destructuring))
8548 ;; Simple variable name
8549 (when (js2-must-match js2-NAME "msg.bad.var")
8550 (setq name (js2-create-name-node)
8551 nbeg js2-token-beg
8552 nend js2-token-end
8553 end nend)
8554 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8555 (when (js2-match-token js2-ASSIGN)
8556 (setq init (js2-parse-assign-expr)
8557 end (js2-node-end init))
8558 (js2-record-imenu-functions init name))
8559 (when name
8560 (js2-set-face nbeg nend (if (js2-function-node-p init)
8561 'font-lock-function-name-face
8562 'font-lock-variable-name-face)
8563 'record))
8564 (setq vi (make-js2-var-init-node :pos kid-pos
8565 :len (- end kid-pos)
8566 :type decl-type))
8567 (if destructuring
8568 (progn
8569 (if (and (null init) (not js2-in-for-init))
8570 (js2-report-error "msg.destruct.assign.no.init"))
8571 (js2-define-destruct-symbols destructuring
8572 decl-type
8573 'font-lock-variable-name-face)
8574 (setf (js2-var-init-node-target vi) destructuring))
8575 (setf (js2-var-init-node-target vi) name))
8576 (setf (js2-var-init-node-initializer vi) init)
8577 (js2-node-add-children vi name destructuring init)
8578 (js2-block-node-push result vi)
8579 (unless (js2-match-token js2-COMMA)
8580 (setq continue nil)))
8581 (setf (js2-node-len result) (- end pos))
8582 result))
8583
8584 (defun js2-parse-let (pos &optional stmt-p)
8585 "Parse a let expression or statement.
8586 A let-expression is of the form `let (vars) expr'.
8587 A let-statment is of the form `let (vars) {statements}'.
8588 The third form of let is a variable declaration list, handled
8589 by `js2-parse-variables'."
8590 (let ((pn (make-js2-let-node :pos pos))
8591 beg vars body)
8592 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8593 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8594 (js2-push-scope pn)
8595 (unwind-protect
8596 (progn
8597 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8598 (if (js2-must-match js2-RP "msg.no.paren.let")
8599 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8600 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8601 ;; let statement
8602 (progn
8603 (js2-consume-token)
8604 (setf beg js2-token-beg ; position stmt at LC
8605 body (js2-parse-statements))
8606 (js2-must-match js2-RC "msg.no.curly.let")
8607 (setf (js2-node-len body) (- js2-token-end beg)
8608 (js2-node-len pn) (- js2-token-end pos)
8609 (js2-let-node-body pn) body
8610 (js2-node-type pn) js2-LET))
8611 ;; let expression
8612 (setf body (js2-parse-expr)
8613 (js2-node-len pn) (- (js2-node-end body) pos)
8614 (js2-let-node-body pn) body))
8615 (js2-node-add-children pn vars body))
8616 (js2-pop-scope))
8617 pn))
8618
8619 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8620 (js2-scope-put-symbol (or scope js2-current-scope)
8621 name
8622 (make-js2-symbol decl-type name node)))
8623
8624 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8625 "Define a symbol in the current scope.
8626 If NODE is non-nil, it is the AST node associated with the symbol."
8627 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8628 (symbol (if defining-scope
8629 (js2-scope-get-symbol defining-scope name)))
8630 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8631 (cond
8632 ((and symbol ; already defined
8633 (or (= sdt js2-CONST) ; old version is const
8634 (= decl-type js2-CONST) ; new version is const
8635 ;; two let-bound vars in this block have same name
8636 (and (= sdt js2-LET)
8637 (eq defining-scope js2-current-scope))))
8638 (js2-report-error
8639 (cond
8640 ((= sdt js2-CONST) "msg.const.redecl")
8641 ((= sdt js2-LET) "msg.let.redecl")
8642 ((= sdt js2-VAR) "msg.var.redecl")
8643 ((= sdt js2-FUNCTION) "msg.function.redecl")
8644 (t "msg.parm.redecl"))
8645 name))
8646 ((= decl-type js2-LET)
8647 (if (and (not ignore-not-in-block)
8648 (or (= (js2-node-type js2-current-scope) js2-IF)
8649 (js2-loop-node-p js2-current-scope)))
8650 (js2-report-error "msg.let.decl.not.in.block")
8651 (js2-define-new-symbol decl-type name node)))
8652 ((or (= decl-type js2-VAR)
8653 (= decl-type js2-CONST)
8654 (= decl-type js2-FUNCTION))
8655 (if symbol
8656 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8657 (js2-add-strict-warning "msg.var.redecl" name)
8658 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8659 (js2-add-strict-warning "msg.var.hides.arg" name)))
8660 (js2-define-new-symbol decl-type name node
8661 js2-current-script-or-fn)))
8662 ((= decl-type js2-LP)
8663 (if symbol
8664 ;; must be duplicate parameter. Second parameter hides the
8665 ;; first, so go ahead and add the second pararameter
8666 (js2-report-warning "msg.dup.parms" name))
8667 (js2-define-new-symbol decl-type name node))
8668 (t (js2-code-bug)))))
8669
8670 (defun js2-parse-expr (&optional oneshot)
8671 (let* ((pn (js2-parse-assign-expr))
8672 (pos (js2-node-pos pn))
8673 left
8674 right
8675 op-pos)
8676 (while (and (not oneshot)
8677 (js2-match-token js2-COMMA))
8678 (setq op-pos (- js2-token-beg pos)) ; relative
8679 (if (= (js2-peek-token) js2-YIELD)
8680 (js2-report-error "msg.yield.parenthesized"))
8681 (setq right (js2-parse-assign-expr)
8682 left pn
8683 pn (make-js2-infix-node :type js2-COMMA
8684 :pos pos
8685 :len (- js2-ts-cursor pos)
8686 :op-pos op-pos
8687 :left left
8688 :right right))
8689 (js2-node-add-children pn left right))
8690 pn))
8691
8692 (defun js2-parse-assign-expr ()
8693 (let ((tt (js2-peek-token))
8694 (pos js2-token-beg)
8695 pn
8696 left
8697 right
8698 op-pos)
8699 (if (= tt js2-YIELD)
8700 (js2-parse-return-or-yield tt t)
8701 ;; not yield - parse assignment expression
8702 (setq pn (js2-parse-cond-expr)
8703 tt (js2-peek-token))
8704 (when (and (<= js2-first-assign tt)
8705 (<= tt js2-last-assign))
8706 ;; tt express assignment (=, |=, ^=, ..., %=)
8707 (js2-consume-token)
8708 (setq op-pos (- js2-token-beg pos) ; relative
8709 left pn
8710 right (js2-parse-assign-expr)
8711 pn (make-js2-assign-node :type tt
8712 :pos pos
8713 :len (- (js2-node-end right) pos)
8714 :op-pos op-pos
8715 :left left
8716 :right right))
8717 (when js2-parse-ide-mode
8718 (js2-highlight-assign-targets pn left right)
8719 (js2-record-imenu-functions right left))
8720 ;; do this last so ide checks above can use absolute positions
8721 (js2-node-add-children pn left right))
8722 pn)))
8723
8724 (defun js2-parse-cond-expr ()
8725 (let ((pos js2-token-beg)
8726 (pn (js2-parse-or-expr))
8727 test-expr
8728 if-true
8729 if-false
8730 q-pos
8731 c-pos)
8732 (when (js2-match-token js2-HOOK)
8733 (setq q-pos (- js2-token-beg pos)
8734 if-true (js2-parse-assign-expr))
8735 (js2-must-match js2-COLON "msg.no.colon.cond")
8736 (setq c-pos (- js2-token-beg pos)
8737 if-false (js2-parse-assign-expr)
8738 test-expr pn
8739 pn (make-js2-cond-node :pos pos
8740 :len (- (js2-node-end if-false) pos)
8741 :test-expr test-expr
8742 :true-expr if-true
8743 :false-expr if-false
8744 :q-pos q-pos
8745 :c-pos c-pos))
8746 (js2-node-add-children pn test-expr if-true if-false))
8747 pn))
8748
8749 (defun js2-make-binary (type left parser)
8750 "Helper for constructing a binary-operator AST node.
8751 LEFT is the left-side-expression, already parsed, and the
8752 binary operator should have just been matched.
8753 PARSER is a function to call to parse the right operand,
8754 or a `js2-node' struct if it has already been parsed."
8755 (let* ((pos (js2-node-pos left))
8756 (op-pos (- js2-token-beg pos))
8757 (right (if (js2-node-p parser)
8758 parser
8759 (funcall parser)))
8760 (pn (make-js2-infix-node :type type
8761 :pos pos
8762 :len (- (js2-node-end right) pos)
8763 :op-pos op-pos
8764 :left left
8765 :right right)))
8766 (js2-node-add-children pn left right)
8767 pn))
8768
8769 (defun js2-parse-or-expr ()
8770 (let ((pn (js2-parse-and-expr)))
8771 (when (js2-match-token js2-OR)
8772 (setq pn (js2-make-binary js2-OR
8773 pn
8774 'js2-parse-or-expr)))
8775 pn))
8776
8777 (defun js2-parse-and-expr ()
8778 (let ((pn (js2-parse-bit-or-expr)))
8779 (when (js2-match-token js2-AND)
8780 (setq pn (js2-make-binary js2-AND
8781 pn
8782 'js2-parse-and-expr)))
8783 pn))
8784
8785 (defun js2-parse-bit-or-expr ()
8786 (let ((pn (js2-parse-bit-xor-expr)))
8787 (while (js2-match-token js2-BITOR)
8788 (setq pn (js2-make-binary js2-BITOR
8789 pn
8790 'js2-parse-bit-xor-expr)))
8791 pn))
8792
8793 (defun js2-parse-bit-xor-expr ()
8794 (let ((pn (js2-parse-bit-and-expr)))
8795 (while (js2-match-token js2-BITXOR)
8796 (setq pn (js2-make-binary js2-BITXOR
8797 pn
8798 'js2-parse-bit-and-expr)))
8799 pn))
8800
8801 (defun js2-parse-bit-and-expr ()
8802 (let ((pn (js2-parse-eq-expr)))
8803 (while (js2-match-token js2-BITAND)
8804 (setq pn (js2-make-binary js2-BITAND
8805 pn
8806 'js2-parse-eq-expr)))
8807 pn))
8808
8809 (defconst js2-parse-eq-ops
8810 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8811
8812 (defun js2-parse-eq-expr ()
8813 (let ((pn (js2-parse-rel-expr))
8814 tt)
8815 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8816 (js2-consume-token)
8817 (setq pn (js2-make-binary tt
8818 pn
8819 'js2-parse-rel-expr)))
8820 pn))
8821
8822 (defconst js2-parse-rel-ops
8823 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8824
8825 (defun js2-parse-rel-expr ()
8826 (let ((pn (js2-parse-shift-expr))
8827 (continue t)
8828 tt)
8829 (while continue
8830 (setq tt (js2-peek-token))
8831 (cond
8832 ((and js2-in-for-init (= tt js2-IN))
8833 (setq continue nil))
8834 ((memq tt js2-parse-rel-ops)
8835 (js2-consume-token)
8836 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8837 (t
8838 (setq continue nil))))
8839 pn))
8840
8841 (defconst js2-parse-shift-ops
8842 (list js2-LSH js2-URSH js2-RSH))
8843
8844 (defun js2-parse-shift-expr ()
8845 (let ((pn (js2-parse-add-expr))
8846 tt
8847 (continue t))
8848 (while continue
8849 (setq tt (js2-peek-token))
8850 (if (memq tt js2-parse-shift-ops)
8851 (progn
8852 (js2-consume-token)
8853 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8854 (setq continue nil)))
8855 pn))
8856
8857 (defun js2-parse-add-expr ()
8858 (let ((pn (js2-parse-mul-expr))
8859 tt
8860 (continue t))
8861 (while continue
8862 (setq tt (js2-peek-token))
8863 (if (or (= tt js2-ADD) (= tt js2-SUB))
8864 (progn
8865 (js2-consume-token)
8866 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8867 (setq continue nil)))
8868 pn))
8869
8870 (defconst js2-parse-mul-ops
8871 (list js2-MUL js2-DIV js2-MOD))
8872
8873 (defun js2-parse-mul-expr ()
8874 (let ((pn (js2-parse-unary-expr))
8875 tt
8876 (continue t))
8877 (while continue
8878 (setq tt (js2-peek-token))
8879 (if (memq tt js2-parse-mul-ops)
8880 (progn
8881 (js2-consume-token)
8882 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8883 (setq continue nil)))
8884 pn))
8885
8886 (defsubst js2-make-unary (type parser &rest args)
8887 "Make a unary node of type TYPE.
8888 PARSER is either a node (for postfix operators) or a function to call
8889 to parse the operand (for prefix operators)."
8890 (let* ((pos js2-token-beg)
8891 (postfix (js2-node-p parser))
8892 (expr (if postfix
8893 parser
8894 (apply parser args)))
8895 end
8896 pn)
8897 (if postfix ; e.g. i++
8898 (setq pos (js2-node-pos expr)
8899 end js2-token-end)
8900 (setq end (js2-node-end expr)))
8901 (setq pn (make-js2-unary-node :type type
8902 :pos pos
8903 :len (- end pos)
8904 :operand expr))
8905 (js2-node-add-children pn expr)
8906 pn))
8907
8908 (defconst js2-incrementable-node-types
8909 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8910 "Node types that can be the operand of a ++ or -- operator.")
8911
8912 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8913 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8914 js2-incrementable-node-types)
8915 (js2-report-error (if (= tt js2-INC)
8916 "msg.bad.incr"
8917 "msg.bad.decr")
8918 nil beg (- end beg))))
8919
8920 (defun js2-parse-unary-expr ()
8921 (let ((tt (js2-peek-token))
8922 pn expr beg end)
8923 (cond
8924 ((or (= tt js2-VOID)
8925 (= tt js2-NOT)
8926 (= tt js2-BITNOT)
8927 (= tt js2-TYPEOF))
8928 (js2-consume-token)
8929 (js2-make-unary tt 'js2-parse-unary-expr))
8930 ((= tt js2-ADD)
8931 (js2-consume-token)
8932 ;; Convert to special POS token in decompiler and parse tree
8933 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8934 ((= tt js2-SUB)
8935 (js2-consume-token)
8936 ;; Convert to special NEG token in decompiler and parse tree
8937 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8938 ((or (= tt js2-INC)
8939 (= tt js2-DEC))
8940 (js2-consume-token)
8941 (prog1
8942 (setq beg js2-token-beg
8943 end js2-token-end
8944 expr (js2-make-unary tt 'js2-parse-member-expr t))
8945 (js2-check-bad-inc-dec tt beg end expr)))
8946 ((= tt js2-DELPROP)
8947 (js2-consume-token)
8948 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8949 ((= tt js2-ERROR)
8950 (js2-consume-token)
8951 (make-js2-error-node)) ; try to continue
8952 ((and (= tt js2-LT)
8953 js2-compiler-xml-available)
8954 ;; XML stream encountered in expression.
8955 (js2-consume-token)
8956 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8957 (t
8958 (setq pn (js2-parse-member-expr t)
8959 ;; Don't look across a newline boundary for a postfix incop.
8960 tt (js2-peek-token-or-eol))
8961 (when (or (= tt js2-INC) (= tt js2-DEC))
8962 (js2-consume-token)
8963 (setf expr pn
8964 pn (js2-make-unary tt expr))
8965 (js2-node-set-prop pn 'postfix t)
8966 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8967 pn))))
8968
8969 (defun js2-parse-xml-initializer ()
8970 "Parse an E4X XML initializer.
8971 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8972 Then I'll postprocess the result, depending on whether we're in IDE
8973 mode or codegen mode, and generate the appropriate rewritten AST.
8974 IDE mode uses a rich AST that models the XML structure. Codegen mode
8975 just concatenates everything and makes a new XML or XMLList out of it."
8976 (let ((tt (js2-get-first-xml-token))
8977 pn-xml
8978 pn
8979 expr
8980 kids
8981 expr-pos
8982 (continue t)
8983 (first-token t))
8984 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8985 (js2-report-error "msg.syntax"))
8986 (setq pn-xml (make-js2-xml-node))
8987 (while continue
8988 (if first-token
8989 (setq first-token nil)
8990 (setq tt (js2-get-next-xml-token)))
8991 (cond
8992 ;; js2-XML means we found a {expr} in the XML stream.
8993 ;; The js2-ts-string is the XML up to the left-curly.
8994 ((= tt js2-XML)
8995 (push (make-js2-string-node :pos js2-token-beg
8996 :len (- js2-ts-cursor js2-token-beg))
8997 kids)
8998 (js2-must-match js2-LC "msg.syntax")
8999 (setq expr-pos js2-ts-cursor
9000 expr (if (eq (js2-peek-token) js2-RC)
9001 (make-js2-empty-expr-node :pos expr-pos)
9002 (js2-parse-expr)))
9003 (js2-must-match js2-RC "msg.syntax")
9004 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9005 :len (js2-node-len expr)
9006 :expr expr))
9007 (js2-node-add-children pn expr)
9008 (push pn kids))
9009 ;; a js2-XMLEND token means we hit the final close-tag.
9010 ((= tt js2-XMLEND)
9011 (push (make-js2-string-node :pos js2-token-beg
9012 :len (- js2-ts-cursor js2-token-beg))
9013 kids)
9014 (dolist (kid (nreverse kids))
9015 (js2-block-node-push pn-xml kid))
9016 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9017 (js2-node-pos pn-xml))
9018 continue nil))
9019 (t
9020 (js2-report-error "msg.syntax")
9021 (setq continue nil))))
9022 pn-xml))
9023
9024
9025 (defun js2-parse-argument-list ()
9026 "Parse an argument list and return it as a lisp list of nodes.
9027 Returns the list in reverse order. Consumes the right-paren token."
9028 (let (result)
9029 (unless (js2-match-token js2-RP)
9030 (loop do
9031 (if (= (js2-peek-token) js2-YIELD)
9032 (js2-report-error "msg.yield.parenthesized"))
9033 (push (js2-parse-assign-expr) result)
9034 while
9035 (js2-match-token js2-COMMA))
9036 (js2-must-match js2-RP "msg.no.paren.arg")
9037 result)))
9038
9039 (defun js2-parse-member-expr (&optional allow-call-syntax)
9040 (let ((tt (js2-peek-token))
9041 pn
9042 pos
9043 target
9044 args
9045 beg
9046 end
9047 init
9048 tail)
9049 (if (/= tt js2-NEW)
9050 (setq pn (js2-parse-primary-expr))
9051 ;; parse a 'new' expression
9052 (js2-consume-token)
9053 (setq pos js2-token-beg
9054 beg pos
9055 target (js2-parse-member-expr)
9056 end (js2-node-end target)
9057 pn (make-js2-new-node :pos pos
9058 :target target
9059 :len (- end pos)))
9060 (js2-node-add-children pn target)
9061 (when (js2-match-token js2-LP)
9062 ;; Add the arguments to pn, if any are supplied.
9063 (setf beg pos ; start of "new" keyword
9064 pos js2-token-beg
9065 args (nreverse (js2-parse-argument-list))
9066 (js2-new-node-args pn) args
9067 end js2-token-end
9068 (js2-new-node-lp pn) (- pos beg)
9069 (js2-new-node-rp pn) (- end 1 beg))
9070 (apply #'js2-node-add-children pn args))
9071 (when (and js2-allow-rhino-new-expr-initializer
9072 (js2-match-token js2-LC))
9073 (setf init (js2-parse-object-literal)
9074 end (js2-node-end init)
9075 (js2-new-node-initializer pn) init)
9076 (js2-node-add-children pn init))
9077 (setf (js2-node-len pn) (- end beg))) ; end outer if
9078 (js2-parse-member-expr-tail allow-call-syntax pn)))
9079
9080 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9081 "Parse a chain of property/array accesses or function calls.
9082 Includes parsing for E4X operators like `..' and `.@'.
9083 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9084 Returns an expression tree that includes PN, the parent node."
9085 (let ((beg (js2-node-pos pn))
9086 tt
9087 (continue t))
9088 (while continue
9089 (setq tt (js2-peek-token))
9090 (cond
9091 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9092 (setq pn (js2-parse-property-access tt pn)))
9093 ((= tt js2-DOTQUERY)
9094 (setq pn (js2-parse-dot-query pn)))
9095 ((= tt js2-LB)
9096 (setq pn (js2-parse-element-get pn)))
9097 ((= tt js2-LP)
9098 (if allow-call-syntax
9099 (setq pn (js2-parse-function-call pn))
9100 (setq continue nil)))
9101 (t
9102 (setq continue nil))))
9103 (if (>= js2-highlight-level 2)
9104 (js2-parse-highlight-member-expr-node pn))
9105 pn))
9106
9107 (defun js2-parse-dot-query (pn)
9108 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9109 Last token parsed must be `js2-DOTQUERY'."
9110 (let ((pos (js2-node-pos pn))
9111 op-pos
9112 expr
9113 end)
9114 (js2-consume-token)
9115 (js2-must-have-xml)
9116 (js2-set-requires-activation)
9117 (setq op-pos js2-token-beg
9118 expr (js2-parse-expr)
9119 end (js2-node-end expr)
9120 pn (make-js2-xml-dot-query-node :left pn
9121 :pos pos
9122 :op-pos op-pos
9123 :right expr))
9124 (js2-node-add-children pn
9125 (js2-xml-dot-query-node-left pn)
9126 (js2-xml-dot-query-node-right pn))
9127 (if (js2-must-match js2-RP "msg.no.paren")
9128 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9129 end js2-token-end))
9130 (setf (js2-node-len pn) (- end pos))
9131 pn))
9132
9133 (defun js2-parse-element-get (pn)
9134 "Parse an element-get expression, e.g. foo[bar].
9135 Last token parsed must be `js2-RB'."
9136 (let ((lb js2-token-beg)
9137 (pos (js2-node-pos pn))
9138 rb
9139 expr)
9140 (js2-consume-token)
9141 (setq expr (js2-parse-expr))
9142 (if (js2-must-match js2-RB "msg.no.bracket.index")
9143 (setq rb js2-token-beg))
9144 (setq pn (make-js2-elem-get-node :target pn
9145 :pos pos
9146 :element expr
9147 :lb (js2-relpos lb pos)
9148 :rb (js2-relpos rb pos)
9149 :len (- js2-token-end pos)))
9150 (js2-node-add-children pn
9151 (js2-elem-get-node-target pn)
9152 (js2-elem-get-node-element pn))
9153 pn))
9154
9155 (defun js2-parse-function-call (pn)
9156 (let (args
9157 (pos (js2-node-pos pn)))
9158 (js2-consume-token)
9159 (setq pn (make-js2-call-node :pos pos
9160 :target pn
9161 :lp (- js2-token-beg pos)))
9162 (js2-node-add-children pn (js2-call-node-target pn))
9163 ;; Add the arguments to pn, if any are supplied.
9164 (setf args (nreverse (js2-parse-argument-list))
9165 (js2-call-node-rp pn) (- js2-token-beg pos)
9166 (js2-call-node-args pn) args)
9167 (apply #'js2-node-add-children pn args)
9168 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9169 pn))
9170
9171 (defun js2-parse-property-access (tt pn)
9172 "Parse a property access, XML descendants access, or XML attr access."
9173 (let ((member-type-flags 0)
9174 (dot-pos js2-token-beg)
9175 (dot-len (if (= tt js2-DOTDOT) 2 1))
9176 name
9177 ref ; right side of . or .. operator
9178 result)
9179 (js2-consume-token)
9180 (when (= tt js2-DOTDOT)
9181 (js2-must-have-xml)
9182 (setq member-type-flags js2-descendants-flag))
9183 (if (not js2-compiler-xml-available)
9184 (progn
9185 (js2-must-match-prop-name "msg.no.name.after.dot")
9186 (setq name (js2-create-name-node t js2-GETPROP)
9187 result (make-js2-prop-get-node :left pn
9188 :pos js2-token-beg
9189 :right name
9190 :len (- js2-token-end
9191 js2-token-beg)))
9192 (js2-node-add-children result pn name)
9193 result)
9194 ;; otherwise look for XML operators
9195 (setf result (if (= tt js2-DOT)
9196 (make-js2-prop-get-node)
9197 (make-js2-infix-node :type js2-DOTDOT))
9198 (js2-node-pos result) (js2-node-pos pn)
9199 (js2-infix-node-op-pos result) dot-pos
9200 (js2-infix-node-left result) pn ; do this after setting position
9201 tt (js2-next-token))
9202 (cond
9203 ;; needed for generator.throw()
9204 ((= tt js2-THROW)
9205 (js2-save-name-token-data js2-token-beg "throw")
9206 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9207 ;; handles: name, ns::name, ns::*, ns::[expr]
9208 ((js2-valid-prop-name-token tt)
9209 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9210 ;; handles: *, *::name, *::*, *::[expr]
9211 ((= tt js2-MUL)
9212 (js2-save-name-token-data js2-token-beg "*")
9213 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9214 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9215 ((= tt js2-XMLATTR)
9216 (setq result (js2-parse-attribute-access)))
9217 (t
9218 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9219 (if ref
9220 (setf (js2-node-len result) (- (js2-node-end ref)
9221 (js2-node-pos result))
9222 (js2-infix-node-right result) ref))
9223 (if (js2-infix-node-p result)
9224 (js2-node-add-children result
9225 (js2-infix-node-left result)
9226 (js2-infix-node-right result)))
9227 result)))
9228
9229 (defun js2-parse-attribute-access ()
9230 "Parse an E4X XML attribute expression.
9231 This includes expressions of the forms:
9232
9233 @attr @ns::attr @ns::*
9234 @* @*::attr @*::*
9235 @[expr] @*::[expr] @ns::[expr]
9236
9237 Called if we peeked an '@' token."
9238 (let ((tt (js2-next-token))
9239 (at-pos js2-token-beg))
9240 (cond
9241 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9242 ((js2-valid-prop-name-token tt)
9243 (js2-parse-property-name at-pos js2-ts-string 0))
9244 ;; handles: @*, @*::name, @*::*, @*::[expr]
9245 ((= tt js2-MUL)
9246 (js2-save-name-token-data js2-token-beg "*")
9247 (js2-parse-property-name js2-token-beg "*" 0))
9248 ;; handles @[expr]
9249 ((= tt js2-LB)
9250 (js2-parse-xml-elem-ref at-pos))
9251 (t
9252 (js2-report-error "msg.no.name.after.xmlAttr")
9253 ;; Avoid cascaded errors that happen if we make an error node here.
9254 (js2-save-name-token-data js2-token-beg "")
9255 (js2-parse-property-name js2-token-beg "" 0)))))
9256
9257 (defun js2-parse-property-name (at-pos s member-type-flags)
9258 "Check if :: follows name in which case it becomes qualified name.
9259
9260 AT-POS is a natural number if we just read an '@' token, else nil.
9261 S is the name or string that was matched: an identifier, 'throw' or '*'.
9262 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9263
9264 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9265 operator, or the name is followed by ::. For a plain name, returns a
9266 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9267 (let ((pos (or at-pos js2-token-beg))
9268 colon-pos
9269 (name (js2-create-name-node t js2-current-token))
9270 ns
9271 tt
9272 ref
9273 pn)
9274 (catch 'return
9275 (when (js2-match-token js2-COLONCOLON)
9276 (setq ns name
9277 colon-pos js2-token-beg
9278 tt (js2-next-token))
9279 (cond
9280 ;; handles name::name
9281 ((js2-valid-prop-name-token tt)
9282 (setq name (js2-create-name-node)))
9283 ;; handles name::*
9284 ((= tt js2-MUL)
9285 (js2-save-name-token-data js2-token-beg "*")
9286 (setq name (js2-create-name-node)))
9287 ;; handles name::[expr]
9288 ((= tt js2-LB)
9289 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9290 (t
9291 (js2-report-error "msg.no.name.after.coloncolon"))))
9292 (if (and (null ns) (zerop member-type-flags))
9293 name
9294 (prog1
9295 (setq pn
9296 (make-js2-xml-prop-ref-node :pos pos
9297 :len (- (js2-node-end name) pos)
9298 :at-pos at-pos
9299 :colon-pos colon-pos
9300 :propname name))
9301 (js2-node-add-children pn name))))))
9302
9303 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9304 "Parse the [expr] portion of an xml element reference.
9305 For instance, @[expr], @*::[expr], or ns::[expr]."
9306 (let* ((lb js2-token-beg)
9307 (pos (or at-pos lb))
9308 rb
9309 (expr (js2-parse-expr))
9310 (end (js2-node-end expr))
9311 pn)
9312 (if (js2-must-match js2-RB "msg.no.bracket.index")
9313 (setq rb js2-token-beg
9314 end js2-token-end))
9315 (prog1
9316 (setq pn
9317 (make-js2-xml-elem-ref-node :pos pos
9318 :len (- end pos)
9319 :namespace namespace
9320 :colon-pos colon-pos
9321 :at-pos at-pos
9322 :expr expr
9323 :lb (js2-relpos lb pos)
9324 :rb (js2-relpos rb pos)))
9325 (js2-node-add-children pn namespace expr))))
9326
9327 (defun js2-parse-destruct-primary-expr ()
9328 (let ((js2-is-in-destructuring t))
9329 (js2-parse-primary-expr)))
9330
9331 (defun js2-parse-primary-expr ()
9332 "Parses a literal (leaf) expression of some sort.
9333 Includes complex literals such as functions, object-literals,
9334 array-literals, array comprehensions and regular expressions."
9335 (let ((tt-flagged (js2-next-flagged-token))
9336 pn ; parent node (usually return value)
9337 tt
9338 px-pos ; paren-expr pos
9339 len
9340 flags ; regexp flags
9341 expr)
9342 (setq tt js2-current-token)
9343 (cond
9344 ((= tt js2-FUNCTION)
9345 (js2-parse-function 'FUNCTION_EXPRESSION))
9346 ((= tt js2-LB)
9347 (js2-parse-array-literal))
9348 ((= tt js2-LC)
9349 (js2-parse-object-literal))
9350 ((= tt js2-LET)
9351 (js2-parse-let js2-token-beg))
9352 ((= tt js2-LP)
9353 (setq px-pos js2-token-beg
9354 expr (js2-parse-expr))
9355 (js2-must-match js2-RP "msg.no.paren")
9356 (setq pn (make-js2-paren-node :pos px-pos
9357 :expr expr
9358 :len (- js2-token-end px-pos)))
9359 (js2-node-add-children pn (js2-paren-node-expr pn))
9360 pn)
9361 ((= tt js2-XMLATTR)
9362 (js2-must-have-xml)
9363 (js2-parse-attribute-access))
9364 ((= tt js2-NAME)
9365 (js2-parse-name tt-flagged tt))
9366 ((= tt js2-NUMBER)
9367 (make-js2-number-node))
9368 ((= tt js2-STRING)
9369 (prog1
9370 (make-js2-string-node)
9371 (js2-record-face 'font-lock-string-face)))
9372 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9373 ;; Got / or /= which in this context means a regexp literal
9374 (setq px-pos js2-token-beg)
9375 (js2-read-regexp tt)
9376 (setq flags js2-ts-regexp-flags
9377 js2-ts-regexp-flags nil)
9378 (prog1
9379 (make-js2-regexp-node :pos px-pos
9380 :len (- js2-ts-cursor px-pos)
9381 :value js2-ts-string
9382 :flags flags)
9383 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9384 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9385 ((or (= tt js2-NULL)
9386 (= tt js2-THIS)
9387 (= tt js2-FALSE)
9388 (= tt js2-TRUE))
9389 (make-js2-keyword-node :type tt))
9390 ((= tt js2-RESERVED)
9391 (js2-report-error "msg.reserved.id")
9392 (make-js2-name-node))
9393 ((= tt js2-ERROR)
9394 ;; the scanner or one of its subroutines reported the error.
9395 (make-js2-error-node))
9396 ((= tt js2-EOF)
9397 (setq px-pos (point-at-bol)
9398 len (- js2-ts-cursor px-pos))
9399 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9400 (make-js2-error-node :pos px-pos :len len))
9401 (t
9402 (js2-report-error "msg.syntax")
9403 (make-js2-error-node)))))
9404
9405 (defun js2-parse-name (tt-flagged tt)
9406 (let ((name js2-ts-string)
9407 (name-pos js2-token-beg)
9408 node)
9409 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9410 (= (js2-peek-token) js2-COLON))
9411 (prog1
9412 ;; Do not consume colon, it is used as unwind indicator
9413 ;; to return to statementHelper.
9414 (make-js2-label-node :pos name-pos
9415 :len (- js2-token-end name-pos)
9416 :name name)
9417 (js2-set-face name-pos
9418 js2-token-end
9419 'font-lock-variable-name-face 'record))
9420 ;; Otherwise not a label, just a name. Unfortunately peeking
9421 ;; the next token to check for a colon has biffed js2-token-beg
9422 ;; and js2-token-end. We store the name's bounds in buffer vars
9423 ;; and `js2-create-name-node' uses them.
9424 (js2-save-name-token-data name-pos name)
9425 (setq node (if js2-compiler-xml-available
9426 (js2-parse-property-name nil name 0)
9427 (js2-create-name-node 'check-activation)))
9428 (if js2-highlight-external-variables
9429 (js2-record-name-node node))
9430 node)))
9431
9432 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9433 (js2-add-strict-warning
9434 msg nil
9435 ;; back up from comma to beginning of line or array/objlit
9436 (max (if elems
9437 (js2-node-pos (car elems))
9438 pos)
9439 (save-excursion
9440 (goto-char comma-pos)
9441 (back-to-indentation)
9442 (point)))
9443 comma-pos))
9444
9445 (defun js2-parse-array-literal ()
9446 (let ((pos js2-token-beg)
9447 (end js2-token-end)
9448 (after-lb-or-comma t)
9449 after-comma
9450 tt
9451 elems
9452 pn
9453 (continue t))
9454 (unless js2-is-in-destructuring
9455 (js2-push-scope (make-js2-scope))) ; for array comp
9456 (while continue
9457 (setq tt (js2-peek-token))
9458 (cond
9459 ;; comma
9460 ((= tt js2-COMMA)
9461 (js2-consume-token)
9462 (setq after-comma js2-token-end)
9463 (if (not after-lb-or-comma)
9464 (setq after-lb-or-comma t)
9465 (push nil elems)))
9466 ;; end of array
9467 ((or (= tt js2-RB)
9468 (= tt js2-EOF)) ; prevent infinite loop
9469 (if (= tt js2-EOF)
9470 (js2-report-error "msg.no.bracket.arg" nil pos)
9471 (js2-consume-token))
9472 (setq continue nil
9473 end js2-token-end
9474 pn (make-js2-array-node :pos pos
9475 :len (- js2-ts-cursor pos)
9476 :elems (nreverse elems)))
9477 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9478 (when (and after-comma (not js2-is-in-destructuring))
9479 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9480 pos elems after-comma)))
9481 ;; destructuring binding
9482 (js2-is-in-destructuring
9483 (push (if (or (= tt js2-LC)
9484 (= tt js2-LB)
9485 (= tt js2-NAME))
9486 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9487 (js2-parse-destruct-primary-expr)
9488 ;; invalid pattern
9489 (js2-consume-token)
9490 (js2-report-error "msg.bad.var")
9491 (make-js2-error-node))
9492 elems)
9493 (setq after-lb-or-comma nil
9494 after-comma nil))
9495 ;; array comp
9496 ((and (>= js2-language-version 170)
9497 (= tt js2-FOR) ; check for array comprehension
9498 (not after-lb-or-comma) ; "for" can't follow a comma
9499 elems ; must have at least 1 element
9500 (not (cdr elems))) ; but no 2nd element
9501 (setf continue nil
9502 pn (js2-parse-array-comprehension (car elems) pos)))
9503
9504 ;; another element
9505 (t
9506 (unless after-lb-or-comma
9507 (js2-report-error "msg.no.bracket.arg"))
9508 (push (js2-parse-assign-expr) elems)
9509 (setq after-lb-or-comma nil
9510 after-comma nil))))
9511 (unless js2-is-in-destructuring
9512 (js2-pop-scope))
9513 pn))
9514
9515 (defun js2-parse-array-comprehension (expr pos)
9516 "Parse a JavaScript 1.7 Array Comprehension.
9517 EXPR is the first expression after the opening left-bracket.
9518 POS is the beginning of the LB token preceding EXPR.
9519 We should have just parsed the 'for' keyword before calling this function."
9520 (let (loops
9521 loop
9522 first
9523 prev
9524 filter
9525 if-pos
9526 result)
9527 (while (= (js2-peek-token) js2-FOR)
9528 (let ((prev (car loops))) ; rearrange scope chain
9529 (push (setq loop (js2-parse-array-comp-loop)) loops)
9530 (if prev ; each loop is parent scope to the next one
9531 (setf (js2-scope-parent-scope loop) prev)
9532 ; first loop takes expr scope's parent
9533 (setf (js2-scope-parent-scope (setq first loop))
9534 (js2-scope-parent-scope js2-current-scope)))))
9535 ;; set expr scope's parent to the last loop
9536 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9537 (when (= (js2-peek-token) js2-IF)
9538 (js2-consume-token)
9539 (setq if-pos (- js2-token-beg pos) ; relative
9540 filter (js2-parse-condition)))
9541 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9542 (setq result (make-js2-array-comp-node :pos pos
9543 :len (- js2-ts-cursor pos)
9544 :result expr
9545 :loops (nreverse loops)
9546 :filter (car filter)
9547 :lp (js2-relpos (second filter) pos)
9548 :rp (js2-relpos (third filter) pos)
9549 :if-pos if-pos))
9550 (apply #'js2-node-add-children result expr (car filter)
9551 (js2-array-comp-node-loops result))
9552 (setq js2-current-scope first) ; pop to the first loop
9553 result))
9554
9555 (defun js2-parse-array-comp-loop ()
9556 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9557 Last token peeked should be the initial FOR."
9558 (let ((pos js2-token-beg)
9559 (pn (make-js2-array-comp-loop-node))
9560 tt
9561 iter
9562 obj
9563 foreach-p
9564 forof-p
9565 in-pos
9566 each-pos
9567 lp
9568 rp)
9569 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9570 (js2-push-scope pn)
9571 (unwind-protect
9572 (progn
9573 (when (js2-match-token js2-NAME)
9574 (if (string= js2-ts-string "each")
9575 (progn
9576 (setq foreach-p t
9577 each-pos (- js2-token-beg pos)) ; relative
9578 (js2-record-face 'font-lock-keyword-face))
9579 (js2-report-error "msg.no.paren.for")))
9580 (if (js2-must-match js2-LP "msg.no.paren.for")
9581 (setq lp (- js2-token-beg pos)))
9582 (setq tt (js2-peek-token))
9583 (cond
9584 ((or (= tt js2-LB)
9585 (= tt js2-LC))
9586 (setq iter (js2-parse-destruct-primary-expr))
9587 (js2-define-destruct-symbols iter js2-LET
9588 'font-lock-variable-name-face t))
9589 ((js2-match-token js2-NAME)
9590 (setq iter (js2-create-name-node)))
9591 (t
9592 (js2-report-error "msg.bad.var")))
9593 ;; Define as a let since we want the scope of the variable to
9594 ;; be restricted to the array comprehension
9595 (if (js2-name-node-p iter)
9596 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9597 (if (or (js2-match-token js2-IN)
9598 (and (>= js2-language-version 200)
9599 (js2-match-contextual-kwd "of")
9600 (setq forof-p t)))
9601 (setq in-pos (- js2-token-beg pos))
9602 (js2-report-error "msg.in.after.for.name"))
9603 (setq obj (js2-parse-expr))
9604 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9605 (setq rp (- js2-token-beg pos)))
9606 (setf (js2-node-pos pn) pos
9607 (js2-node-len pn) (- js2-ts-cursor pos)
9608 (js2-array-comp-loop-node-iterator pn) iter
9609 (js2-array-comp-loop-node-object pn) obj
9610 (js2-array-comp-loop-node-in-pos pn) in-pos
9611 (js2-array-comp-loop-node-each-pos pn) each-pos
9612 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9613 (js2-array-comp-loop-node-forof-p pn) forof-p
9614 (js2-array-comp-loop-node-lp pn) lp
9615 (js2-array-comp-loop-node-rp pn) rp)
9616 (js2-node-add-children pn iter obj))
9617 (js2-pop-scope))
9618 pn))
9619
9620 (defun js2-parse-object-literal ()
9621 (let ((pos js2-token-beg)
9622 tt
9623 elems
9624 result
9625 after-comma
9626 (continue t))
9627 (while continue
9628 (setq tt (js2-peek-token))
9629 (cond
9630 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9631 ((or (js2-valid-prop-name-token tt)
9632 (= tt js2-STRING))
9633 (setq after-comma nil
9634 result (js2-parse-named-prop tt))
9635 (if (and (null result)
9636 (not js2-recover-from-parse-errors))
9637 (setq continue nil)
9638 (push result elems)))
9639 ;; {12: x} or {10.7: x}
9640 ((= tt js2-NUMBER)
9641 (js2-consume-token)
9642 (setq after-comma nil)
9643 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9644 ;; trailing comma
9645 ((= tt js2-RC)
9646 (setq continue nil)
9647 (if after-comma
9648 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9649 pos elems after-comma)))
9650 (t
9651 (js2-report-error "msg.bad.prop")
9652 (unless js2-recover-from-parse-errors
9653 (setq continue nil)))) ; end switch
9654 (if (js2-match-token js2-COMMA)
9655 (setq after-comma js2-token-end)
9656 (setq continue nil))) ; end loop
9657 (js2-must-match js2-RC "msg.no.brace.prop")
9658 (setq result (make-js2-object-node :pos pos
9659 :len (- js2-ts-cursor pos)
9660 :elems (nreverse elems)))
9661 (apply #'js2-node-add-children result (js2-object-node-elems result))
9662 result))
9663
9664 (defun js2-parse-named-prop (tt)
9665 "Parse a name, string, or getter/setter object property.
9666 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9667 (js2-consume-token)
9668 (let ((string-prop (and (= tt js2-STRING)
9669 (make-js2-string-node)))
9670 expr
9671 (ppos js2-token-beg)
9672 (pend js2-token-end)
9673 (name (js2-create-name-node))
9674 (prop js2-ts-string))
9675 (cond
9676 ;; getter/setter prop
9677 ((and (= tt js2-NAME)
9678 (= (js2-peek-token) js2-NAME)
9679 (or (string= prop "get")
9680 (string= prop "set")))
9681 (js2-consume-token)
9682 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9683 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9684 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9685 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9686 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9687 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9688 ;; when patterns are used in variable declarations, function parameters,
9689 ;; catch-clause, and iterators.
9690 ;; We have to set `js2-is-in-destructuring' to t when the current
9691 ;; expressions are on the left side of any assignment, but it's difficult
9692 ;; because it requires looking ahead of expression.
9693 ((and js2-is-in-destructuring
9694 (= tt js2-NAME)
9695 (let ((ctk (js2-peek-token)))
9696 (or (= ctk js2-COMMA)
9697 (= ctk js2-RC)
9698 (js2-valid-prop-name-token ctk))))
9699 name)
9700 ;; regular prop
9701 (t
9702 (prog1
9703 (setq expr (js2-parse-plain-property (or string-prop name)))
9704 (js2-set-face ppos pend
9705 (if (js2-function-node-p
9706 (js2-object-prop-node-right expr))
9707 'font-lock-function-name-face
9708 'font-lock-variable-name-face)
9709 'record))))))
9710
9711 (defun js2-parse-plain-property (prop)
9712 "Parse a non-getter/setter property in an object literal.
9713 PROP is the node representing the property: a number, name or string."
9714 (js2-must-match js2-COLON "msg.no.colon.prop")
9715 (let* ((pos (js2-node-pos prop))
9716 (colon (- js2-token-beg pos))
9717 (expr (js2-parse-assign-expr))
9718 (result (make-js2-object-prop-node
9719 :pos pos
9720 ;; don't include last consumed token in length
9721 :len (- (+ (js2-node-pos expr)
9722 (js2-node-len expr))
9723 pos)
9724 :left prop
9725 :right expr
9726 :op-pos colon)))
9727 (js2-node-add-children result prop expr)
9728 result))
9729
9730 (defun js2-parse-getter-setter-prop (pos prop get-p)
9731 "Parse getter or setter property in an object literal.
9732 JavaScript syntax is:
9733
9734 { get foo() {...}, set foo(x) {...} }
9735
9736 and expression closure style is also supported
9737
9738 { get foo() x, set foo(x) _x = x }
9739
9740 POS is the start position of the `get' or `set' keyword.
9741 PROP is the `js2-name-node' representing the property name.
9742 GET-P is non-nil if the keyword was `get'."
9743 (let ((type (if get-p js2-GET js2-SET))
9744 result
9745 end
9746 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9747 ;; it has to be an anonymous function, as we already parsed the name
9748 (if (/= (js2-node-type fn) js2-FUNCTION)
9749 (js2-report-error "msg.bad.prop")
9750 (if (plusp (length (js2-function-name fn)))
9751 (js2-report-error "msg.bad.prop")))
9752 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9753 (setq end (js2-node-end fn)
9754 result (make-js2-getter-setter-node :type type
9755 :pos pos
9756 :len (- end pos)
9757 :left prop
9758 :right fn))
9759 (js2-node-add-children result prop fn)
9760 result))
9761
9762 (defun js2-create-name-node (&optional check-activation-p token)
9763 "Create a name node using the token info from last scanned name.
9764 In some cases we need to either synthesize a name node, or we lost
9765 the name token information by peeking. If the TOKEN parameter is
9766 not `js2-NAME', then we use the token info saved in instance vars."
9767 (let ((beg js2-token-beg)
9768 (s js2-ts-string)
9769 name)
9770 (when (/= js2-current-token js2-NAME)
9771 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9772 s js2-prev-name-token-string
9773 js2-prev-name-token-start nil
9774 js2-prev-name-token-string nil))
9775 (setq name (make-js2-name-node :pos beg
9776 :name s
9777 :len (length s)))
9778 (if check-activation-p
9779 (js2-check-activation-name s (or token js2-NAME)))
9780 name))
9781
9782 ;;; Indentation support
9783
9784 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9785 ;; Karl cleverly deduces that the desired indentation level is often a
9786 ;; function of paren/bracket/brace nesting depth, which can be determined
9787 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9788 ;; then does some equally clever checks to see if we're in the context of a
9789 ;; substatement of a possibly braceless statement keyword such as if, while,
9790 ;; or finally. This approach yields pretty good results.
9791
9792 ;; The indenter is often "wrong", however, and needs to be overridden.
9793 ;; The right long-term solution is probably to emulate (or integrate
9794 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9795 ;; parse tree from `js2-parse' is present, which is not true at the
9796 ;; moment the user is typing, computing indentation is still thousands
9797 ;; of lines of code to handle every possible syntactic edge case.
9798
9799 ;; In the meantime, the compromise solution is that we offer a "bounce
9800 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9801 ;; current line indent among various likely guess points. This approach
9802 ;; is far from perfect, but should at least make it slightly easier to
9803 ;; move the line towards its desired indentation when manually
9804 ;; overriding Karl's heuristic nesting guesser.
9805
9806 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9807 ;; extensions such as `let' and Array comprehensions. Major kudos to
9808 ;; Karl for coming up with the initial approach, which packs a lot of
9809 ;; punch for so little code.
9810
9811 (defconst js2-possibly-braceless-keywords-re
9812 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9813 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9814 "try" "while" "with" "let")))
9815 "Regular expression matching keywords that are optionally
9816 followed by an opening brace.")
9817
9818 (defconst js2-indent-operator-re
9819 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9820 (regexp-opt '("in" "instanceof") 'words))
9821 "Regular expression matching operators that affect indentation
9822 of continued expressions.")
9823
9824 (defconst js2-declaration-keyword-re
9825 (regexp-opt '("var" "let" "const") 'words)
9826 "Regular expression matching variable declaration keywords.")
9827
9828 ;; This function has horrible results if you're typing an array
9829 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9830 ;; in conjunction with electric-indent, so just disabling it.
9831 (defsubst js2-code-at-bol-p ()
9832 "Return t if the first character on line is non-whitespace."
9833 nil)
9834
9835 (defun js2-insert-and-indent (key)
9836 "Run command bound to key and indent current line. Runs the command
9837 bound to KEY in the global keymap and indents the current line."
9838 (interactive (list (this-command-keys)))
9839 (let ((cmd (lookup-key (current-global-map) key)))
9840 (if (commandp cmd)
9841 (call-interactively cmd)))
9842 ;; don't do the electric keys inside comments or strings,
9843 ;; and don't do bounce-indent with them.
9844 (let ((parse-state (syntax-ppss (point)))
9845 (js2-bounce-indent-p (js2-code-at-bol-p)))
9846 (unless (or (nth 3 parse-state)
9847 (nth 4 parse-state))
9848 (indent-according-to-mode))))
9849
9850 (defun js2-re-search-forward-inner (regexp &optional bound count)
9851 "Auxiliary function for `js2-re-search-forward'."
9852 (let (parse saved-point)
9853 (while (> count 0)
9854 (re-search-forward regexp bound)
9855 (setq parse (if saved-point
9856 (parse-partial-sexp saved-point (point))
9857 (syntax-ppss (point))))
9858 (cond ((nth 3 parse)
9859 (re-search-forward
9860 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9861 (save-excursion (end-of-line) (point)) t))
9862 ((nth 7 parse)
9863 (forward-line))
9864 ((or (nth 4 parse)
9865 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9866 (re-search-forward "\\*/"))
9867 (t
9868 (setq count (1- count))))
9869 (setq saved-point (point))))
9870 (point))
9871
9872 (defun js2-re-search-forward (regexp &optional bound noerror count)
9873 "Search forward but ignore strings and comments. Invokes
9874 `re-search-forward' but treats the buffer as if strings and
9875 comments have been removed."
9876 (let ((saved-point (point))
9877 (search-expr
9878 (cond ((null count)
9879 '(js2-re-search-forward-inner regexp bound 1))
9880 ((< count 0)
9881 '(js2-re-search-backward-inner regexp bound (- count)))
9882 ((> count 0)
9883 '(js2-re-search-forward-inner regexp bound count)))))
9884 (condition-case err
9885 (eval search-expr)
9886 (search-failed
9887 (goto-char saved-point)
9888 (unless noerror
9889 (error (error-message-string err)))))))
9890
9891 (defun js2-re-search-backward-inner (regexp &optional bound count)
9892 "Auxiliary function for `js2-re-search-backward'."
9893 (let (parse saved-point)
9894 (while (> count 0)
9895 (re-search-backward regexp bound)
9896 (setq parse (if saved-point
9897 (parse-partial-sexp saved-point (point))
9898 (syntax-ppss (point))))
9899 (cond ((nth 3 parse)
9900 (re-search-backward
9901 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9902 (save-excursion (beginning-of-line) (point)) t))
9903 ((nth 7 parse)
9904 (goto-char (nth 8 parse)))
9905 ((or (nth 4 parse)
9906 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9907 (re-search-backward "/\\*"))
9908 (t
9909 (setq count (1- count))))))
9910 (point))
9911
9912 (defun js2-re-search-backward (regexp &optional bound noerror count)
9913 "Search backward but ignore strings and comments. Invokes
9914 `re-search-backward' but treats the buffer as if strings and
9915 comments have been removed."
9916 (let ((saved-point (point))
9917 (search-expr
9918 (cond ((null count)
9919 '(js2-re-search-backward-inner regexp bound 1))
9920 ((< count 0)
9921 '(js2-re-search-forward-inner regexp bound (- count)))
9922 ((> count 0)
9923 '(js2-re-search-backward-inner regexp bound count)))))
9924 (condition-case err
9925 (eval search-expr)
9926 (search-failed
9927 (goto-char saved-point)
9928 (unless noerror
9929 (error (error-message-string err)))))))
9930
9931 (defun js2-looking-at-operator-p ()
9932 "Return non-nil if text after point is an operator (that is not
9933 a comma)."
9934 (save-match-data
9935 (and (looking-at js2-indent-operator-re)
9936 (or (not (looking-at ":"))
9937 (save-excursion
9938 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9939 (looking-at "?")))))))
9940
9941 (defun js2-continued-expression-p ()
9942 "Returns non-nil if the current line continues an expression."
9943 (save-excursion
9944 (back-to-indentation)
9945 (or (js2-looking-at-operator-p)
9946 ;; comment
9947 (and (js2-re-search-backward "\n" nil t)
9948 (progn
9949 (skip-chars-backward " \t")
9950 (unless (bolp)
9951 (backward-char)
9952 (and (js2-looking-at-operator-p)
9953 (and (progn
9954 (backward-char)
9955 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))))))
9956
9957 (defun js2-end-of-do-while-loop-p ()
9958 "Returns non-nil if word after point is `while' of a do-while
9959 statement, else returns nil. A braceless do-while statement
9960 spanning several lines requires that the start of the loop is
9961 indented to the same column as the current line."
9962 (interactive)
9963 (save-excursion
9964 (save-match-data
9965 (when (looking-at "\\s-*\\<while\\>")
9966 (if (save-excursion
9967 (skip-chars-backward "[ \t\n]*}")
9968 (looking-at "[ \t\n]*}"))
9969 (save-excursion
9970 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9971 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9972 (or (looking-at "\\<do\\>")
9973 (let ((saved-indent (current-indentation)))
9974 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9975 (/= (current-indentation) saved-indent)))
9976 (and (looking-at "[ \t]*\\<do\\>")
9977 (not (js2-re-search-forward
9978 "\\<while\\>" (point-at-eol) t))
9979 (= (current-indentation) saved-indent)))))))))
9980
9981 (defun js2-multiline-decl-indentation ()
9982 "Returns the declaration indentation column if the current line belongs
9983 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9984 (let (forward-sexp-function ; use Lisp version
9985 at-opening-bracket)
9986 (save-excursion
9987 (back-to-indentation)
9988 (when (not (looking-at js2-declaration-keyword-re))
9989 (when (looking-at js2-indent-operator-re)
9990 (goto-char (match-end 0))) ; continued expressions are ok
9991 (while (and (not at-opening-bracket)
9992 (not (bobp))
9993 (let ((pos (point)))
9994 (save-excursion
9995 (js2-backward-sws)
9996 (or (eq (char-before) ?,)
9997 (and (not (eq (char-before) ?\;))
9998 (and
9999 (prog2 (skip-chars-backward "[[:punct:]]")
10000 (looking-at js2-indent-operator-re)
10001 (js2-backward-sws))
10002 (not (eq (char-before) ?\;))))
10003 (js2-same-line pos)))))
10004 (condition-case err
10005 (backward-sexp)
10006 (scan-error (setq at-opening-bracket t))))
10007 (when (looking-at js2-declaration-keyword-re)
10008 (- (1+ (match-end 0)) (point-at-bol)))))))
10009
10010 (defun js2-ctrl-statement-indentation ()
10011 "Returns the proper indentation of the current line if it
10012 starts the body of a control statement without braces, else
10013 returns nil."
10014 (let (forward-sexp-function) ; temporarily unbind it
10015 (save-excursion
10016 (back-to-indentation)
10017 (when (and (not (js2-same-line (point-min)))
10018 (not (looking-at "{"))
10019 (js2-re-search-backward "[[:graph:]]" nil t)
10020 (not (looking-at "[{([]"))
10021 (progn
10022 (forward-char)
10023 (when (= (char-before) ?\))
10024 ;; scan-sexps sometimes throws an error
10025 (ignore-errors (backward-sexp))
10026 (skip-chars-backward " \t" (point-at-bol)))
10027 (let ((pt (point)))
10028 (back-to-indentation)
10029 (and (looking-at js2-possibly-braceless-keywords-re)
10030 (= (match-end 0) pt)
10031 (not (js2-end-of-do-while-loop-p))))))
10032 (+ (current-indentation) js2-basic-offset)))))
10033
10034 (defun js2-indent-in-array-comp (parse-status)
10035 "Return non-nil if we think we're in an array comprehension.
10036 In particular, return the buffer position of the first `for' kwd."
10037 (let ((bracket (nth 1 parse-status))
10038 (end (point)))
10039 (when bracket
10040 (save-excursion
10041 (goto-char bracket)
10042 (when (looking-at "\\[")
10043 (forward-char 1)
10044 (js2-forward-sws)
10045 (if (looking-at "[[{]")
10046 (let (forward-sexp-function) ; use lisp version
10047 (forward-sexp) ; skip destructuring form
10048 (js2-forward-sws)
10049 (if (and (/= (char-after) ?,) ; regular array
10050 (looking-at "for"))
10051 (match-beginning 0)))
10052 ;; to skip arbitrary expressions we need the parser,
10053 ;; so we'll just guess at it.
10054 (if (and (> end (point)) ; not empty literal
10055 (re-search-forward "[^,]]* \\(for\\) " end t)
10056 ;; not inside comment or string literal
10057 (let ((state (parse-partial-sexp bracket (point))))
10058 (not (or (nth 3 state) (nth 4 state)))))
10059 (match-beginning 1))))))))
10060
10061 (defun js2-array-comp-indentation (parse-status for-kwd)
10062 (if (js2-same-line for-kwd)
10063 ;; first continuation line
10064 (save-excursion
10065 (goto-char (nth 1 parse-status))
10066 (forward-char 1)
10067 (skip-chars-forward " \t")
10068 (current-column))
10069 (save-excursion
10070 (goto-char for-kwd)
10071 (current-column))))
10072
10073 (defun js2-proper-indentation (parse-status)
10074 "Return the proper indentation for the current line."
10075 (save-excursion
10076 (back-to-indentation)
10077 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10078 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
10079 (continued-expr-p (js2-continued-expression-p))
10080 (declaration-indent (and js2-pretty-multiline-declarations
10081 (js2-multiline-decl-indentation)))
10082 (bracket (nth 1 parse-status))
10083 beg)
10084 (cond
10085 ;; indent array comprehension continuation lines specially
10086 ((and bracket
10087 (>= js2-language-version 170)
10088 (not (js2-same-line bracket))
10089 (setq beg (js2-indent-in-array-comp parse-status))
10090 (>= (point) (save-excursion
10091 (goto-char beg)
10092 (point-at-bol)))) ; at or after first loop?
10093 (js2-array-comp-indentation parse-status beg))
10094
10095 (ctrl-stmt-indent)
10096
10097 ((and declaration-indent continued-expr-p)
10098 (+ declaration-indent js2-basic-offset))
10099
10100 (declaration-indent)
10101
10102 (bracket
10103 (goto-char bracket)
10104 (cond
10105 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10106 (when (save-excursion (skip-chars-backward " \t)")
10107 (looking-at ")"))
10108 (backward-list))
10109 (back-to-indentation)
10110 (and (eq js2-pretty-multiline-declarations 'all)
10111 (looking-at js2-declaration-keyword-re)
10112 (goto-char (1+ (match-end 0))))
10113 (cond (same-indent-p
10114 (current-column))
10115 (continued-expr-p
10116 (+ (current-column) (* 2 js2-basic-offset)))
10117 (t
10118 (+ (current-column) js2-basic-offset))))
10119 (t
10120 (unless same-indent-p
10121 (forward-char)
10122 (skip-chars-forward " \t"))
10123 (current-column))))
10124
10125 (continued-expr-p js2-basic-offset)
10126
10127 (t 0)))))
10128
10129 (defun js2-lineup-comment (parse-status)
10130 "Indent a multi-line block comment continuation line."
10131 (let* ((beg (nth 8 parse-status))
10132 (first-line (js2-same-line beg))
10133 (offset (save-excursion
10134 (goto-char beg)
10135 (if (looking-at "/\\*")
10136 (+ 1 (current-column))
10137 0))))
10138 (unless first-line
10139 (indent-line-to offset))))
10140
10141 (defun js2-backward-sws ()
10142 "Move backward through whitespace and comments."
10143 (interactive)
10144 (while (forward-comment -1)))
10145
10146 (defun js2-forward-sws ()
10147 "Move forward through whitespace and comments."
10148 (interactive)
10149 (while (forward-comment 1)))
10150
10151 (defsubst js2-current-indent (&optional pos)
10152 "Return column of indentation on current line.
10153 If POS is non-nil, go to that point and return indentation for that line."
10154 (save-excursion
10155 (if pos
10156 (goto-char pos))
10157 (back-to-indentation)
10158 (current-column)))
10159
10160 (defsubst js2-arglist-close ()
10161 "Return non-nil if we're on a line beginning with a close-paren/brace."
10162 (save-match-data
10163 (save-excursion
10164 (goto-char (point-at-bol))
10165 (js2-forward-sws)
10166 (looking-at "[])}]"))))
10167
10168 (defsubst js2-indent-looks-like-label-p ()
10169 (goto-char (point-at-bol))
10170 (js2-forward-sws)
10171 (looking-at (concat js2-mode-identifier-re ":")))
10172
10173 (defun js2-indent-in-objlit-p (parse-status)
10174 "Return non-nil if this looks like an object-literal entry."
10175 (let ((start (nth 1 parse-status)))
10176 (and
10177 start
10178 (save-excursion
10179 (and (zerop (forward-line -1))
10180 (not (< (point) start)) ; crossed a {} boundary
10181 (js2-indent-looks-like-label-p)))
10182 (save-excursion
10183 (js2-indent-looks-like-label-p)))))
10184
10185 ;; if prev line looks like foobar({ then we're passing an object
10186 ;; literal to a function call, and people pretty much always want to
10187 ;; de-dent back to the previous line, so move the 'basic-offset'
10188 ;; position to the front.
10189 (defsubst js2-indent-objlit-arg-p (parse-status)
10190 (save-excursion
10191 (back-to-indentation)
10192 (js2-backward-sws)
10193 (and (eq (1- (point)) (nth 1 parse-status))
10194 (eq (char-before) ?{)
10195 (progn
10196 (forward-char -1)
10197 (skip-chars-backward " \t")
10198 (eq (char-before) ?\()))))
10199
10200 (defsubst js2-indent-case-block-p ()
10201 (save-excursion
10202 (back-to-indentation)
10203 (js2-backward-sws)
10204 (goto-char (point-at-bol))
10205 (skip-chars-forward " \t")
10206 (save-match-data
10207 (looking-at "case\\s-.+:"))))
10208
10209 (defsubst js2-syntax-bol ()
10210 "Return the point at the first non-whitespace char on the line.
10211 Returns `point-at-bol' if the line is empty."
10212 (save-excursion
10213 (beginning-of-line)
10214 (skip-chars-forward " \t")
10215 (point)))
10216
10217 (defun js2-bounce-indent (normal-col parse-status backwards)
10218 "Cycle among alternate computed indentation positions.
10219 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10220 of the buffer to the current point. NORMAL-COL is the indentation
10221 column computed by the heuristic guesser based on current paren,
10222 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10223 in reverse."
10224 (let ((cur-indent (js2-current-indent))
10225 (old-buffer-undo-list buffer-undo-list)
10226 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10227 (current-line (save-excursion
10228 (forward-line 0) ; move to bol
10229 (1+ (count-lines (point-min) (point)))))
10230 positions
10231 pos
10232 main-pos
10233 anchor
10234 arglist-cont
10235 same-indent
10236 prev-line-col
10237 basic-offset
10238 computed-pos)
10239 ;; temporarily don't record undo info, if user requested this
10240 (if js2-mode-indent-inhibit-undo
10241 (setq buffer-undo-list t))
10242 (unwind-protect
10243 (progn
10244 ;; first likely point: indent from beginning of previous code line
10245 (push (setq basic-offset
10246 (+ (save-excursion
10247 (back-to-indentation)
10248 (js2-backward-sws)
10249 (back-to-indentation)
10250 (setq prev-line-col (current-column)))
10251 js2-basic-offset))
10252 positions)
10253
10254 ;; (first + epsilon) likely point: indent 2x from beginning of
10255 ;; previous code line. Some companies like this approach. Ahem.
10256 ;; Seriously, though -- 4-space indent for expression continuation
10257 ;; lines isn't a bad idea. We should eventually implement it
10258 ;; that way.
10259 (push (setq basic-offset
10260 (+ (save-excursion
10261 (back-to-indentation)
10262 (js2-backward-sws)
10263 (back-to-indentation)
10264 (setq prev-line-col (current-column)))
10265 (* 2 js2-basic-offset)))
10266 positions)
10267
10268 ;; second likely point: indent from assign-expr RHS. This
10269 ;; is just a crude guess based on finding " = " on the previous
10270 ;; line containing actual code.
10271 (setq pos (save-excursion
10272 (save-match-data
10273 (forward-line -1)
10274 (goto-char (point-at-bol))
10275 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10276 (point-at-eol) t)
10277 (goto-char (match-end 1))
10278 (skip-chars-forward " \t\r\n")
10279 (current-column)))))
10280 (when pos
10281 (incf pos js2-basic-offset)
10282 (push pos positions))
10283
10284 ;; third likely point: same indent as previous line of code.
10285 ;; Make it the first likely point if we're not on an
10286 ;; arglist-close line and previous line ends in a comma, or
10287 ;; both this line and prev line look like object-literal
10288 ;; elements.
10289 (setq pos (save-excursion
10290 (goto-char (point-at-bol))
10291 (js2-backward-sws)
10292 (back-to-indentation)
10293 (prog1
10294 (current-column)
10295 ;; while we're here, look for trailing comma
10296 (if (save-excursion
10297 (goto-char (point-at-eol))
10298 (js2-backward-sws)
10299 (eq (char-before) ?,))
10300 (setq arglist-cont (1- (point)))))))
10301 (when pos
10302 (if (and (or arglist-cont
10303 (js2-indent-in-objlit-p parse-status))
10304 (not (js2-arglist-close)))
10305 (setq same-indent pos))
10306 (push pos positions))
10307
10308 ;; fourth likely point: first preceding code with less indentation
10309 ;; than the immediately preceding code line.
10310 (setq pos (save-excursion
10311 (back-to-indentation)
10312 (js2-backward-sws)
10313 (back-to-indentation)
10314 (setq anchor (current-column))
10315 (while (and (zerop (forward-line -1))
10316 (>= (progn
10317 (back-to-indentation)
10318 (current-column))
10319 anchor)))
10320 (setq pos (current-column))))
10321 (push pos positions)
10322
10323 ;; nesting-heuristic position, main by default
10324 (push (setq main-pos normal-col) positions)
10325
10326 ;; delete duplicates and sort positions list
10327 (setq positions (sort (delete-dups positions) '<))
10328
10329 ;; comma-list continuation lines: prev line indent takes precedence
10330 (if same-indent
10331 (setq main-pos same-indent))
10332
10333 ;; common special cases where we want to indent in from previous line
10334 (if (or (js2-indent-case-block-p)
10335 (js2-indent-objlit-arg-p parse-status))
10336 (setq main-pos basic-offset))
10337
10338 ;; if bouncing backwards, reverse positions list
10339 (if backwards
10340 (setq positions (reverse positions)))
10341
10342 ;; record whether we're already sitting on one of the alternatives
10343 (setq pos (member cur-indent positions))
10344
10345 (cond
10346 ;; case 0: we're one one of the alternatives and this is the
10347 ;; first time they've pressed TAB on this line (best-guess).
10348 ((and js2-mode-indent-ignore-first-tab
10349 pos
10350 ;; first time pressing TAB on this line?
10351 (not (eq js2-mode-last-indented-line current-line)))
10352 ;; do nothing
10353 (setq computed-pos nil))
10354 ;; case 1: only one computed position => use it
10355 ((null (cdr positions))
10356 (setq computed-pos 0))
10357 ;; case 2: not on any of the computed spots => use main spot
10358 ((not pos)
10359 (setq computed-pos (js2-position main-pos positions)))
10360 ;; case 3: on last position: cycle to first position
10361 ((null (cdr pos))
10362 (setq computed-pos 0))
10363 ;; case 4: on intermediate position: cycle to next position
10364 (t
10365 (setq computed-pos (js2-position (second pos) positions))))
10366
10367 ;; see if any hooks want to indent; otherwise we do it
10368 (loop with result = nil
10369 for hook in js2-indent-hook
10370 while (null result)
10371 do
10372 (setq result (funcall hook positions computed-pos))
10373 finally do
10374 (unless (or result (null computed-pos))
10375 (indent-line-to (nth computed-pos positions)))))
10376
10377 ;; finally
10378 (if js2-mode-indent-inhibit-undo
10379 (setq buffer-undo-list old-buffer-undo-list))
10380 ;; see commentary for `js2-mode-last-indented-line'
10381 (setq js2-mode-last-indented-line current-line))))
10382
10383 (defun js2-indent-bounce-backwards ()
10384 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10385 cycles between the computed indentation positions in reverse order."
10386 (interactive)
10387 (js2-indent-line t))
10388
10389 (defsubst js2-1-line-comment-continuation-p ()
10390 "Return t if we're in a 1-line comment continuation.
10391 If so, we don't ever want to use bounce-indent."
10392 (save-excursion
10393 (save-match-data
10394 (and (progn
10395 (forward-line 0)
10396 (looking-at "\\s-*//"))
10397 (progn
10398 (forward-line -1)
10399 (forward-line 0)
10400 (when (looking-at "\\s-*$")
10401 (js2-backward-sws)
10402 (forward-line 0))
10403 (looking-at "\\s-*//"))))))
10404
10405 (defun js2-indent-line (&optional bounce-backwards)
10406 "Indent the current line as JavaScript source text."
10407 (interactive)
10408 (let (parse-status
10409 offset
10410 indent-col
10411 moved
10412 ;; don't whine about errors/warnings when we're indenting.
10413 ;; This has to be set before calling parse-partial-sexp below.
10414 (inhibit-point-motion-hooks t))
10415 (setq parse-status (save-excursion
10416 (syntax-ppss (point-at-bol)))
10417 offset (- (point) (save-excursion
10418 (back-to-indentation)
10419 (point))))
10420 (js2-with-underscore-as-word-syntax
10421 (if (nth 4 parse-status)
10422 (js2-lineup-comment parse-status)
10423 (setq indent-col (js2-proper-indentation parse-status))
10424 ;; see comments below about js2-mode-last-indented-line
10425 (cond
10426 ;; bounce-indenting is disabled during electric-key indent.
10427 ;; It doesn't work well on first line of buffer.
10428 ((and js2-bounce-indent-p
10429 (not (js2-same-line (point-min)))
10430 (not (js2-1-line-comment-continuation-p)))
10431 (js2-bounce-indent indent-col parse-status bounce-backwards))
10432 ;; just indent to the guesser's likely spot
10433 (t (indent-line-to indent-col)))
10434 (when (plusp offset)
10435 (forward-char offset))))))
10436
10437 (defun js2-indent-region (start end)
10438 "Indent the region, but don't use bounce indenting."
10439 (let ((js2-bounce-indent-p nil)
10440 (indent-region-function nil)
10441 (after-change-functions (remq 'js2-mode-edit
10442 after-change-functions)))
10443 (indent-region start end nil) ; nil for byte-compiler
10444 (js2-mode-edit start end (- end start))))
10445
10446 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10447
10448 ;;;###autoload
10449 (defun js2-mode ()
10450 "Major mode for editing JavaScript code."
10451 (interactive)
10452 (kill-all-local-variables)
10453 (set-syntax-table js2-mode-syntax-table)
10454 (use-local-map js2-mode-map)
10455 (make-local-variable 'comment-start)
10456 (make-local-variable 'comment-end)
10457 (make-local-variable 'comment-start-skip)
10458 (setq major-mode 'js2-mode
10459 mode-name "JavaScript-IDE"
10460 comment-start "//" ; used by comment-region; don't change it
10461 comment-end "")
10462 (setq local-abbrev-table js2-mode-abbrev-table)
10463 (set (make-local-variable 'max-lisp-eval-depth)
10464 (max max-lisp-eval-depth 3000))
10465 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10466 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10467
10468 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10469 ;; on most platforms other than the one I originally wrote it on.
10470 ;; So it's back to `c-fill-paragraph'.
10471 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10472
10473 (add-hook 'before-save-hook #'js2-before-save nil t)
10474 (set (make-local-variable 'next-error-function) #'js2-next-error)
10475 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10476 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10477 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10478 ;; for characters inside regexp literals.
10479 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10480 ;; this is necessary to make `show-paren-function' work properly
10481 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10482 ;; needed for M-x rgrep, among other things
10483 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10484
10485 ;; some variables needed by cc-engine for paragraph-fill, etc.
10486 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10487 c-comment-start-regexp "/[*/]\\|\\s|"
10488 c-line-comment-starter "//"
10489 c-paragraph-start js2-paragraph-start
10490 c-paragraph-separate "$"
10491 comment-start-skip js2-comment-start-skip
10492 c-syntactic-ws-start js2-syntactic-ws-start
10493 c-syntactic-ws-end js2-syntactic-ws-end
10494 c-syntactic-eol js2-syntactic-eol)
10495
10496 (let ((c-buffer-is-cc-mode t))
10497 ;; Copied from `js-mode'. Also see Bug#6071.
10498 (make-local-variable 'paragraph-start)
10499 (make-local-variable 'paragraph-separate)
10500 (make-local-variable 'paragraph-ignore-fill-prefix)
10501 (make-local-variable 'adaptive-fill-mode)
10502 (make-local-variable 'adaptive-fill-regexp)
10503 (c-setup-paragraph-variables))
10504
10505 (setq js2-default-externs
10506 (append js2-ecma-262-externs
10507 (if js2-include-browser-externs
10508 js2-browser-externs)
10509 (if js2-include-gears-externs
10510 js2-gears-externs)
10511 (if js2-include-rhino-externs
10512 js2-rhino-externs)))
10513
10514 ;; We do our own syntax highlighting based on the parse tree.
10515 ;; However, we want minor modes that add keywords to highlight properly
10516 ;; (examples: doxymacs, column-marker).
10517 ;; To customize highlighted keywords, use `font-lock-add-keywords'.
10518 (setq font-lock-defaults '(nil t))
10519
10520 ;; Experiment: make reparse-delay longer for longer files.
10521 (if (plusp js2-dynamic-idle-timer-adjust)
10522 (setq js2-idle-timer-delay
10523 (* js2-idle-timer-delay
10524 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10525
10526 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10527 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10528 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10529 (imenu-add-to-menubar (concat "IM-" mode-name))
10530 (when js2-mirror-mode
10531 (js2-enter-mirror-mode))
10532 (add-to-invisibility-spec '(js2-outline . t))
10533 (set (make-local-variable 'line-move-ignore-invisible) t)
10534 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10535
10536 (if (fboundp 'run-mode-hooks)
10537 (run-mode-hooks 'js2-mode-hook)
10538 (run-hooks 'js2-mode-hook))
10539
10540 (setq js2-mode-functions-hidden nil
10541 js2-mode-comments-hidden nil
10542 js2-mode-buffer-dirty-p t
10543 js2-mode-parsing nil)
10544 (js2-reparse))
10545
10546 (defun js2-mode-exit ()
10547 "Exit `js2-mode' and clean up."
10548 (interactive)
10549 (when js2-mode-node-overlay
10550 (delete-overlay js2-mode-node-overlay)
10551 (setq js2-mode-node-overlay nil))
10552 (js2-remove-overlays)
10553 (setq js2-mode-ast nil)
10554 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10555 (remove-from-invisibility-spec '(js2-outline . t))
10556 (js2-mode-show-all)
10557 (js2-with-unmodifying-text-property-changes
10558 (js2-clear-face (point-min) (point-max))))
10559
10560 (defun js2-before-save ()
10561 "Clean up whitespace before saving file.
10562 You can disable this by customizing `js2-cleanup-whitespace'."
10563 (when js2-cleanup-whitespace
10564 (let ((col (current-column)))
10565 (delete-trailing-whitespace)
10566 ;; don't change trailing whitespace on current line
10567 (unless (eq (current-column) col)
10568 (indent-to col)))))
10569
10570 (defsubst js2-mode-reset-timer ()
10571 "Cancel any existing parse timer and schedule a new one."
10572 (if js2-mode-parse-timer
10573 (cancel-timer js2-mode-parse-timer))
10574 (setq js2-mode-parsing nil)
10575 (setq js2-mode-parse-timer
10576 (run-with-idle-timer js2-idle-timer-delay nil
10577 #'js2-mode-idle-reparse (current-buffer))))
10578
10579 (defun js2-mode-idle-reparse (buffer)
10580 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10581 it to be reparsed when the buffer is selected."
10582 (if (eq buffer (current-buffer))
10583 (js2-reparse)
10584 ;; reparse when the buffer is selected again
10585 (with-current-buffer buffer
10586 (add-hook 'window-configuration-change-hook
10587 #'js2-mode-idle-reparse-inner
10588 nil t))))
10589
10590 (defun js2-mode-idle-reparse-inner ()
10591 (remove-hook 'window-configuration-change-hook
10592 #'js2-mode-idle-reparse-inner
10593 t)
10594 (js2-reparse))
10595
10596 (defun js2-mode-edit (beg end len)
10597 "Schedule a new parse after buffer is edited.
10598 Buffer edit spans from BEG to END and is of length LEN.
10599 Also clears the `js2-magic' bit on autoinserted parens/brackets
10600 if the edit occurred on a line different from the magic paren."
10601 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10602 (line (if magic-pos (line-number-at-pos magic-pos))))
10603 (and line
10604 (or (/= (line-number-at-pos beg) line)
10605 (and (> 0 len)
10606 (/= (line-number-at-pos end) line)))
10607 (js2-mode-mundanify-parens)))
10608 (setq js2-mode-buffer-dirty-p t)
10609 (js2-mode-hide-overlay)
10610 (js2-mode-reset-timer))
10611
10612 (defun js2-reparse (&optional force)
10613 "Re-parse current buffer after user finishes some data entry.
10614 If we get any user input while parsing, including cursor motion,
10615 we discard the parse and reschedule it. If FORCE is nil, then the
10616 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10617 (let (time
10618 interrupted-p
10619 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10620 (unless js2-mode-parsing
10621 (setq js2-mode-parsing t)
10622 (unwind-protect
10623 (when (or js2-mode-buffer-dirty-p force)
10624 (js2-remove-overlays)
10625 (js2-with-unmodifying-text-property-changes
10626 (setq js2-mode-buffer-dirty-p nil
10627 js2-mode-fontifications nil
10628 js2-mode-deferred-properties nil)
10629 (if js2-mode-verbose-parse-p
10630 (message "parsing..."))
10631 (setq time
10632 (js2-time
10633 (setq interrupted-p
10634 (catch 'interrupted
10635 (setq js2-mode-ast (js2-parse))
10636 ;; if parsing is interrupted, comments and regex
10637 ;; literals stay ignored by `parse-partial-sexp'
10638 (remove-text-properties (point-min) (point-max)
10639 '(syntax-table))
10640 (js2-mode-apply-deferred-properties)
10641 (js2-mode-remove-suppressed-warnings)
10642 (js2-mode-show-warnings)
10643 (js2-mode-show-errors)
10644 (js2-mode-highlight-magic-parens)
10645 (if (>= js2-highlight-level 1)
10646 (js2-highlight-jsdoc js2-mode-ast))
10647 nil))))
10648 (if interrupted-p
10649 (progn
10650 ;; unfinished parse => try again
10651 (setq js2-mode-buffer-dirty-p t)
10652 (js2-mode-reset-timer))
10653 (if js2-mode-verbose-parse-p
10654 (message "Parse time: %s" time)))))
10655 (setq js2-mode-parsing nil)
10656 (unless interrupted-p
10657 (setq js2-mode-parse-timer nil))))))
10658
10659 (defun js2-mode-show-node ()
10660 "Debugging aid: highlight selected AST node on mouse click."
10661 (interactive)
10662 (let ((node (js2-node-at-point))
10663 beg
10664 end)
10665 (when js2-mode-show-overlay
10666 (if (null node)
10667 (message "No node found at location %s" (point))
10668 (setq beg (js2-node-abs-pos node)
10669 end (+ beg (js2-node-len node)))
10670 (if js2-mode-node-overlay
10671 (move-overlay js2-mode-node-overlay beg end)
10672 (setq js2-mode-node-overlay (make-overlay beg end))
10673 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10674 (js2-with-unmodifying-text-property-changes
10675 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10676 (message "%s, parent: %s"
10677 (js2-node-short-name node)
10678 (if (js2-node-parent node)
10679 (js2-node-short-name (js2-node-parent node))
10680 "nil"))))))
10681
10682 (defun js2-mode-hide-overlay (&optional p1 p2)
10683 "Remove the debugging overlay when the point moves.
10684 P1 and P2 are the old and new values of point, respectively."
10685 (when js2-mode-node-overlay
10686 (let ((beg (overlay-start js2-mode-node-overlay))
10687 (end (overlay-end js2-mode-node-overlay)))
10688 ;; Sometimes we're called spuriously.
10689 (unless (and p2
10690 (>= p2 beg)
10691 (<= p2 end))
10692 (js2-with-unmodifying-text-property-changes
10693 (remove-text-properties beg end '(point-left nil)))
10694 (delete-overlay js2-mode-node-overlay)
10695 (setq js2-mode-node-overlay nil)))))
10696
10697 (defun js2-mode-reset ()
10698 "Debugging helper: reset everything."
10699 (interactive)
10700 (js2-mode-exit)
10701 (js2-mode))
10702
10703 (defsubst js2-mode-show-warn-or-err (e face)
10704 "Highlight a warning or error E with FACE.
10705 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10706 (let* ((key (first e))
10707 (beg (second e))
10708 (end (+ beg (third e)))
10709 ;; Don't inadvertently go out of bounds.
10710 (beg (max (point-min) (min beg (point-max))))
10711 (end (max (point-min) (min end (point-max))))
10712 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10713 (ovl (make-overlay beg end)))
10714 (overlay-put ovl 'font-lock-face face)
10715 (overlay-put ovl 'js2-error t)
10716 (put-text-property beg end 'help-echo (js2-get-msg key))
10717 (put-text-property beg end 'point-entered #'js2-echo-error)))
10718
10719 (defun js2-remove-overlays ()
10720 "Remove overlays from buffer that have a `js2-error' property."
10721 (let ((beg (point-min))
10722 (end (point-max)))
10723 (save-excursion
10724 (dolist (o (overlays-in beg end))
10725 (when (overlay-get o 'js2-error)
10726 (delete-overlay o))))))
10727
10728 (defun js2-error-at-point (&optional pos)
10729 "Return non-nil if there's an error overlay at POS.
10730 Defaults to point."
10731 (loop with pos = (or pos (point))
10732 for o in (overlays-at pos)
10733 thereis (overlay-get o 'js2-error)))
10734
10735 (defun js2-mode-apply-deferred-properties ()
10736 "Apply fontifications and other text properties recorded during parsing."
10737 (when (plusp js2-highlight-level)
10738 ;; We defer clearing faces as long as possible to eliminate flashing.
10739 (js2-clear-face (point-min) (point-max))
10740 ;; Have to reverse the recorded fontifications list so that errors
10741 ;; and warnings overwrite the normal fontifications.
10742 (dolist (f (nreverse js2-mode-fontifications))
10743 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10744 (setq js2-mode-fontifications nil))
10745 (dolist (p js2-mode-deferred-properties)
10746 (apply #'put-text-property p))
10747 (setq js2-mode-deferred-properties nil))
10748
10749 (defun js2-mode-show-errors ()
10750 "Highlight syntax errors."
10751 (when js2-mode-show-parse-errors
10752 (dolist (e (js2-ast-root-errors js2-mode-ast))
10753 (js2-mode-show-warn-or-err e 'js2-error-face))))
10754
10755 (defun js2-mode-remove-suppressed-warnings ()
10756 "Take suppressed warnings out of the AST warnings list.
10757 This ensures that the counts and `next-error' are correct."
10758 (setf (js2-ast-root-warnings js2-mode-ast)
10759 (js2-delete-if
10760 (lambda (e)
10761 (let ((key (caar e)))
10762 (or
10763 (and (not js2-strict-trailing-comma-warning)
10764 (string-match "trailing\\.comma" key))
10765 (and (not js2-strict-cond-assign-warning)
10766 (string= key "msg.equal.as.assign"))
10767 (and js2-missing-semi-one-line-override
10768 (string= key "msg.missing.semi")
10769 (let* ((beg (second e))
10770 (node (js2-node-at-point beg))
10771 (fn (js2-mode-find-parent-fn node))
10772 (body (and fn (js2-function-node-body fn)))
10773 (lc (and body (js2-node-abs-pos body)))
10774 (rc (and lc (+ lc (js2-node-len body)))))
10775 (and fn
10776 (or (null body)
10777 (save-excursion
10778 (goto-char beg)
10779 (and (js2-same-line lc)
10780 (js2-same-line rc))))))))))
10781 (js2-ast-root-warnings js2-mode-ast))))
10782
10783 (defun js2-mode-show-warnings ()
10784 "Highlight strict-mode warnings."
10785 (when js2-mode-show-strict-warnings
10786 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10787 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10788
10789 (defun js2-echo-error (old-point new-point)
10790 "Called by point-motion hooks."
10791 (let ((msg (get-text-property new-point 'help-echo)))
10792 (if (and msg (or (not (current-message))
10793 (string= (current-message) "Quit")))
10794 (message msg))))
10795
10796 (defalias #'js2-echo-help #'js2-echo-error)
10797
10798 (defun js2-enter-key ()
10799 "Handle user pressing the Enter key."
10800 (interactive)
10801 (let ((parse-status (save-excursion
10802 (syntax-ppss (point))))
10803 (js2-bounce-indent-p nil))
10804 (cond
10805 ;; check if we're inside a string
10806 ((nth 3 parse-status)
10807 (if js2-concat-multiline-strings
10808 (js2-mode-split-string parse-status)
10809 (insert "\n")))
10810 ;; check if inside a block comment
10811 ((nth 4 parse-status)
10812 (js2-mode-extend-comment))
10813 (t
10814 ;; should probably figure out what the mode-map says we should do
10815 (if js2-indent-on-enter-key
10816 (js2-indent-line))
10817 (insert "\n")
10818 (if js2-enter-indents-newline
10819 (js2-indent-line))))))
10820
10821 (defun js2-mode-split-string (parse-status)
10822 "Turn a newline in mid-string into a string concatenation.
10823 PARSE-STATUS is as documented in `parse-partial-sexp'."
10824 (let* ((col (current-column))
10825 (quote-char (nth 3 parse-status))
10826 (quote-string (string quote-char))
10827 (string-beg (nth 8 parse-status))
10828 (at-eol (eq js2-concat-multiline-strings 'eol))
10829 (indent (save-match-data
10830 (or
10831 (save-excursion
10832 (back-to-indentation)
10833 (if (looking-at "\\+")
10834 (current-column)))
10835 (save-excursion
10836 (goto-char string-beg)
10837 (if (looking-back "\\+\\s-+")
10838 (goto-char (match-beginning 0)))
10839 (current-column))))))
10840 (insert quote-char)
10841 (if at-eol
10842 (insert " +\n")
10843 (insert "\n"))
10844 ;; FIXME: This does not match the behavior of `js2-indent-line'.
10845 (indent-to indent)
10846 (unless at-eol
10847 (insert "+ "))
10848 (insert quote-string)
10849 (when (eolp)
10850 (insert quote-string)
10851 (backward-char 1))))
10852
10853 (defun js2-mode-extend-comment ()
10854 "Indent the line and, when inside a comment block, add comment prefix."
10855 (let (star single col first-line needs-close)
10856 (save-excursion
10857 (back-to-indentation)
10858 (cond
10859 ((looking-at "\\*[^/]")
10860 (setq star t
10861 col (current-column)))
10862 ((looking-at "/\\*")
10863 (setq star t
10864 first-line t
10865 col (1+ (current-column))))
10866 ((looking-at "//")
10867 (setq single t
10868 col (current-column)))))
10869 ;; Heuristic for whether we need to close the comment:
10870 ;; if we've got a parse error here, assume it's an unterminated
10871 ;; comment.
10872 (setq needs-close
10873 (or
10874 (eq (get-text-property (1- (point)) 'point-entered)
10875 'js2-echo-error)
10876 ;; The heuristic above doesn't work well when we're
10877 ;; creating a comment and there's another one downstream,
10878 ;; as our parser thinks this one ends at the end of the
10879 ;; next one. (You can have a /* inside a js block comment.)
10880 ;; So just close it if the next non-ws char isn't a *.
10881 (and first-line
10882 (eolp)
10883 (save-excursion
10884 (skip-chars-forward " \t\r\n")
10885 (not (eq (char-after) ?*))))))
10886 (insert "\n")
10887 (cond
10888 (star
10889 (indent-to col)
10890 (insert "* ")
10891 (if (and first-line needs-close)
10892 (save-excursion
10893 (insert "\n")
10894 (indent-to col)
10895 (insert "*/"))))
10896 ((and single
10897 (save-excursion
10898 (and (zerop (forward-line 1))
10899 (looking-at "\\s-*//"))))
10900 (indent-to col)
10901 (insert "// "))
10902 ;; don't need to extend the comment after all
10903 (js2-enter-indents-newline
10904 (js2-indent-line)))))
10905
10906 (defun js2-beginning-of-line ()
10907 "Toggles point between bol and first non-whitespace char in line.
10908 Also moves past comment delimiters when inside comments."
10909 (interactive)
10910 (let (node beg)
10911 (cond
10912 ((bolp)
10913 (back-to-indentation))
10914 ((looking-at "//")
10915 (skip-chars-forward "/ \t"))
10916 ((and (eq (char-after) ?*)
10917 (setq node (js2-comment-at-point))
10918 (memq (js2-comment-node-format node) '(jsdoc block))
10919 (save-excursion
10920 (skip-chars-backward " \t")
10921 (bolp)))
10922 (skip-chars-forward "\* \t"))
10923 (t
10924 (goto-char (point-at-bol))))))
10925
10926 (defun js2-end-of-line ()
10927 "Toggles point between eol and last non-whitespace char in line."
10928 (interactive)
10929 (if (eolp)
10930 (skip-chars-backward " \t")
10931 (goto-char (point-at-eol))))
10932
10933 (defun js2-enter-mirror-mode()
10934 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10935 on insertion."
10936 (interactive)
10937 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10938 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10939 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10940 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10941 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10942 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10943 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10944 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10945
10946 (defun js2-leave-mirror-mode()
10947 "Turns off mirror mode."
10948 (interactive)
10949 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10950 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10951
10952 (defsubst js2-mode-inside-string ()
10953 "Return non-nil if inside a string.
10954 Actually returns the quote character that begins the string."
10955 (let ((parse-state (save-excursion
10956 (syntax-ppss (point)))))
10957 (nth 3 parse-state)))
10958
10959 (defsubst js2-mode-inside-comment-or-string ()
10960 "Return non-nil if inside a comment or string."
10961 (or
10962 (let ((comment-start
10963 (save-excursion
10964 (goto-char (point-at-bol))
10965 (if (re-search-forward "//" (point-at-eol) t)
10966 (match-beginning 0)))))
10967 (and comment-start
10968 (<= comment-start (point))))
10969 (let ((parse-state (save-excursion
10970 (syntax-ppss (point)))))
10971 (or (nth 3 parse-state)
10972 (nth 4 parse-state)))))
10973
10974 (defsubst js2-make-magic-delimiter (delim &optional pos)
10975 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10976 Sets value of `js2-magic' text property to line number at POS."
10977 (propertize delim
10978 'js2-magic (line-number-at-pos pos)
10979 'font-lock-face 'js2-magic-paren-face))
10980
10981 (defun js2-mode-match-delimiter (open close)
10982 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10983 The rule we use, which as far as we can tell is how Eclipse works,
10984 is that we insert the match if we're not in a comment or string,
10985 and the next non-whitespace character is either punctuation or
10986 occurs on another line."
10987 (insert open)
10988 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10989 (not (js2-mode-inside-comment-or-string)))
10990 (save-excursion
10991 (insert (js2-make-magic-delimiter close)))
10992 (when js2-auto-indent-p
10993 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10994 (js2-indent-line)))))
10995
10996 (defun js2-mode-match-bracket ()
10997 "Insert matching bracket."
10998 (interactive)
10999 (js2-mode-match-delimiter "[" "]"))
11000
11001 (defun js2-mode-match-paren ()
11002 "Insert matching paren unless already inserted."
11003 (interactive)
11004 (js2-mode-match-delimiter "(" ")"))
11005
11006 (defun js2-mode-match-curly (arg)
11007 "Insert matching curly-brace.
11008 With prefix arg, no formatting or indentation will occur -- the close-brace
11009 is simply inserted directly at the point."
11010 (interactive "p")
11011 (let (try-pos)
11012 (cond
11013 (current-prefix-arg
11014 (js2-mode-match-delimiter "{" "}"))
11015 ((and js2-auto-insert-catch-block
11016 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
11017 (point-at-bol))
11018 (match-beginning 1))))
11019 (js2-insert-catch-skel try-pos))
11020 (t
11021 ;; Otherwise try to do something smarter.
11022 (insert "{")
11023 (unless (or (not (looking-at "\\s-*$"))
11024 (save-excursion
11025 (skip-chars-forward " \t\r\n")
11026 (and (looking-at "}")
11027 (js2-error-at-point)))
11028 (js2-mode-inside-comment-or-string))
11029 (undo-boundary)
11030 ;; absolutely mystifying bug: when inserting the next "\n",
11031 ;; the buffer-undo-list is given two new entries: the inserted range,
11032 ;; and the incorrect position of the point. It's recorded incorrectly
11033 ;; as being before the opening "{", not after it. But it's recorded
11034 ;; as the correct value if you're debugging `js2-mode-match-curly'
11035 ;; in edebug. I have no idea why it's doing this, but incrementing
11036 ;; the inserted position fixes the problem, so that the undo takes us
11037 ;; back to just after the user-inserted "{".
11038 (insert "\n")
11039 (ignore-errors
11040 (incf (cadr buffer-undo-list)))
11041 (js2-indent-line)
11042 (save-excursion
11043 (insert "\n}")
11044 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
11045 (js2-indent-line))))))))
11046
11047 (defun js2-insert-catch-skel (try-pos)
11048 "Complete a try/catch block after inserting a { following a try keyword.
11049 Rationale is that a try always needs a catch or a finally, and the catch is
11050 the more likely of the two.
11051
11052 TRY-POS is the buffer position of the try keyword. The open-curly should
11053 already have been inserted."
11054 (insert "{")
11055 (let ((try-col (save-excursion
11056 (goto-char try-pos)
11057 (current-column))))
11058 (insert "\n")
11059 (undo-boundary)
11060 (js2-indent-line) ;; indent the blank line where cursor will end up
11061 (save-excursion
11062 (insert "\n")
11063 (indent-to try-col)
11064 (insert "} catch (x) {\n\n")
11065 (indent-to try-col)
11066 (insert "}"))))
11067
11068 (defun js2-mode-highlight-magic-parens ()
11069 "Re-highlight magic parens after parsing nukes the 'face prop."
11070 (let ((beg (point-min))
11071 end)
11072 (while (setq beg (next-single-property-change beg 'js2-magic))
11073 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11074 (if (get-text-property beg 'js2-magic)
11075 (js2-with-unmodifying-text-property-changes
11076 (put-text-property beg (or end (1+ beg))
11077 'font-lock-face 'js2-magic-paren-face))))))
11078
11079 (defun js2-mode-mundanify-parens ()
11080 "Clear all magic parens and brackets."
11081 (let ((beg (point-min))
11082 end)
11083 (while (setq beg (next-single-property-change beg 'js2-magic))
11084 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11085 (remove-text-properties beg (or end (1+ beg))
11086 '(js2-magic face)))))
11087
11088 (defsubst js2-match-quote (quote-string)
11089 (let ((start-quote (js2-mode-inside-string)))
11090 (cond
11091 ;; inside a comment - don't do quote-matching, since we can't
11092 ;; reliably figure out if we're in a string inside the comment
11093 ((js2-comment-at-point)
11094 (insert quote-string))
11095 ((not start-quote)
11096 ;; not in string => insert matched quotes
11097 (insert quote-string)
11098 ;; exception: if we're just before a word, don't double it.
11099 (unless (looking-at "[^ \t\r\n]")
11100 (save-excursion
11101 (insert quote-string))))
11102 ((looking-at quote-string)
11103 (if (looking-back "[^\\]\\\\")
11104 (insert quote-string)
11105 (forward-char 1)))
11106 ((and js2-mode-escape-quotes
11107 (save-excursion
11108 (save-match-data
11109 (re-search-forward quote-string (point-at-eol) t))))
11110 ;; inside terminated string, escape quote (unless already escaped)
11111 (insert (if (looking-back "[^\\]\\\\")
11112 quote-string
11113 (concat "\\" quote-string))))
11114 (t
11115 (insert quote-string))))) ; else terminate the string
11116
11117 (defun js2-mode-match-single-quote ()
11118 "Insert matching single-quote."
11119 (interactive)
11120 (let ((parse-status (syntax-ppss (point))))
11121 ;; don't match inside comments, since apostrophe is more common
11122 (if (nth 4 parse-status)
11123 (insert "'")
11124 (js2-match-quote "'"))))
11125
11126 (defun js2-mode-match-double-quote ()
11127 "Insert matching double-quote."
11128 (interactive)
11129 (js2-match-quote "\""))
11130
11131 ;; Eclipse works as follows:
11132 ;; * type an open-paren and it auto-inserts close-paren
11133 ;; - auto-inserted paren gets a green bracket
11134 ;; - green bracket means typing close-paren there will skip it
11135 ;; * if you insert any text on a different line, it turns off
11136 (defun js2-mode-magic-close-paren ()
11137 "Skip over close-paren rather than inserting, where appropriate."
11138 (interactive)
11139 (let* ((here (point))
11140 (parse-status (syntax-ppss here))
11141 (open-pos (nth 1 parse-status))
11142 (close last-input-event)
11143 (open (cond
11144 ((eq close ?\))
11145 ?\()
11146 ((eq close ?\])
11147 ?\[)
11148 ((eq close ?})
11149 ?{)
11150 (t nil))))
11151 (if (and (eq (char-after) close)
11152 (eq open (char-after open-pos))
11153 (js2-same-line open-pos)
11154 (get-text-property here 'js2-magic))
11155 (progn
11156 (remove-text-properties here (1+ here) '(js2-magic face))
11157 (forward-char 1))
11158 (insert-char close 1))
11159 (blink-matching-open)))
11160
11161 (defun js2-mode-wait-for-parse (callback)
11162 "Invoke CALLBACK when parsing is finished.
11163 If parsing is already finished, calls CALLBACK immediately."
11164 (if (not js2-mode-buffer-dirty-p)
11165 (funcall callback)
11166 (push callback js2-mode-pending-parse-callbacks)
11167 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11168
11169 (defun js2-mode-parse-finished ()
11170 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11171 ;; We can't let errors propagate up, since it prevents the
11172 ;; `js2-parse' method from completing normally and returning
11173 ;; the ast, which makes things mysteriously not work right.
11174 (unwind-protect
11175 (dolist (cb js2-mode-pending-parse-callbacks)
11176 (condition-case err
11177 (funcall cb)
11178 (error (message "%s" err))))
11179 (setq js2-mode-pending-parse-callbacks nil)))
11180
11181 (defun js2-mode-flag-region (from to flag)
11182 "Hide or show text from FROM to TO, according to FLAG.
11183 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11184 Returns the created overlay if FLAG is non-nil."
11185 (remove-overlays from to 'invisible 'js2-outline)
11186 (when flag
11187 (let ((o (make-overlay from to)))
11188 (overlay-put o 'invisible 'js2-outline)
11189 (overlay-put o 'isearch-open-invisible
11190 'js2-isearch-open-invisible)
11191 o)))
11192
11193 ;; Function to be set as an outline-isearch-open-invisible' property
11194 ;; to the overlay that makes the outline invisible (see
11195 ;; `js2-mode-flag-region').
11196 (defun js2-isearch-open-invisible (overlay)
11197 ;; We rely on the fact that isearch places point on the matched text.
11198 (js2-mode-show-element))
11199
11200 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11201 "Return cons cell of bounds of folding overlay at POS.
11202 Returns nil if not found."
11203 (let ((overlays (overlays-at (or pos (point))))
11204 o)
11205 (while (and overlays
11206 (not o))
11207 (if (overlay-get (car overlays) 'invisible)
11208 (setq o (car overlays))
11209 (setq overlays (cdr overlays))))
11210 (if o
11211 (cons (overlay-start o) (overlay-end o)))))
11212
11213 (defun js2-mode-function-at-point (&optional pos)
11214 "Return the innermost function node enclosing current point.
11215 Returns nil if point is not in a function."
11216 (let ((node (js2-node-at-point pos)))
11217 (while (and node (not (js2-function-node-p node)))
11218 (setq node (js2-node-parent node)))
11219 (if (js2-function-node-p node)
11220 node)))
11221
11222 (defun js2-mode-toggle-element ()
11223 "Hide or show the foldable element at the point."
11224 (interactive)
11225 (let (comment fn pos)
11226 (save-excursion
11227 (save-match-data
11228 (cond
11229 ;; /* ... */ comment?
11230 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11231 (if (js2-mode-invisible-overlay-bounds
11232 (setq pos (+ 3 (js2-node-abs-pos comment))))
11233 (progn
11234 (goto-char pos)
11235 (js2-mode-show-element))
11236 (js2-mode-hide-element)))
11237 ;; //-comment?
11238 ((save-excursion
11239 (back-to-indentation)
11240 (looking-at js2-mode-//-comment-re))
11241 (js2-mode-toggle-//-comment))
11242 ;; function?
11243 ((setq fn (js2-mode-function-at-point))
11244 (setq pos (and (js2-function-node-body fn)
11245 (js2-node-abs-pos (js2-function-node-body fn))))
11246 (goto-char (1+ pos))
11247 (if (js2-mode-invisible-overlay-bounds)
11248 (js2-mode-show-element)
11249 (js2-mode-hide-element)))
11250 (t
11251 (message "Nothing at point to hide or show")))))))
11252
11253 (defun js2-mode-hide-element ()
11254 "Fold/hide contents of a block, showing ellipses.
11255 Show the hidden text with \\[js2-mode-show-element]."
11256 (interactive)
11257 (if js2-mode-buffer-dirty-p
11258 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11259 (let (node body beg end)
11260 (cond
11261 ((js2-mode-invisible-overlay-bounds)
11262 (message "already hidden"))
11263 (t
11264 (setq node (js2-node-at-point))
11265 (cond
11266 ((js2-block-comment-p node)
11267 (js2-mode-hide-comment node))
11268 (t
11269 (while (and node (not (js2-function-node-p node)))
11270 (setq node (js2-node-parent node)))
11271 (if (and node
11272 (setq body (js2-function-node-body node)))
11273 (progn
11274 (setq beg (js2-node-abs-pos body)
11275 end (+ beg (js2-node-len body)))
11276 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11277 (message "No collapsable element found at point"))))))))
11278
11279 (defun js2-mode-show-element ()
11280 "Show the hidden element at current point."
11281 (interactive)
11282 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11283 (if bounds
11284 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11285 (message "Nothing to un-hide"))))
11286
11287 (defun js2-mode-show-all ()
11288 "Show all of the text in the buffer."
11289 (interactive)
11290 (js2-mode-flag-region (point-min) (point-max) nil))
11291
11292 (defun js2-mode-toggle-hide-functions ()
11293 (interactive)
11294 (if js2-mode-functions-hidden
11295 (js2-mode-show-functions)
11296 (js2-mode-hide-functions)))
11297
11298 (defun js2-mode-hide-functions ()
11299 "Hides all non-nested function bodies in the buffer.
11300 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11301 to open an individual entry."
11302 (interactive)
11303 (if js2-mode-buffer-dirty-p
11304 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11305 (if (null js2-mode-ast)
11306 (message "Oops - parsing failed")
11307 (setq js2-mode-functions-hidden t)
11308 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11309
11310 (defun js2-mode-function-hider (n endp)
11311 (when (not endp)
11312 (let ((tt (js2-node-type n))
11313 body beg end)
11314 (cond
11315 ((and (= tt js2-FUNCTION)
11316 (setq body (js2-function-node-body n)))
11317 (setq beg (js2-node-abs-pos body)
11318 end (+ beg (js2-node-len body)))
11319 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11320 nil) ; don't process children of function
11321 (t
11322 t))))) ; keep processing other AST nodes
11323
11324 (defun js2-mode-show-functions ()
11325 "Un-hide any folded function bodies in the buffer."
11326 (interactive)
11327 (setq js2-mode-functions-hidden nil)
11328 (save-excursion
11329 (goto-char (point-min))
11330 (while (/= (goto-char (next-overlay-change (point)))
11331 (point-max))
11332 (dolist (o (overlays-at (point)))
11333 (when (and (overlay-get o 'invisible)
11334 (not (overlay-get o 'comment)))
11335 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11336
11337 (defun js2-mode-hide-comment (n)
11338 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11339 3 ; /**
11340 2)) ; /*
11341 (beg (+ (js2-node-abs-pos n) head))
11342 (end (- (+ beg (js2-node-len n)) head 2))
11343 (o (js2-mode-flag-region beg end 'hide)))
11344 (overlay-put o 'comment t)))
11345
11346 (defun js2-mode-toggle-hide-comments ()
11347 "Folds all block comments in the buffer.
11348 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11349 to open an individual entry."
11350 (interactive)
11351 (if js2-mode-comments-hidden
11352 (js2-mode-show-comments)
11353 (js2-mode-hide-comments)))
11354
11355 (defun js2-mode-hide-comments ()
11356 (interactive)
11357 (if js2-mode-buffer-dirty-p
11358 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11359 (if (null js2-mode-ast)
11360 (message "Oops - parsing failed")
11361 (setq js2-mode-comments-hidden t)
11362 (dolist (n (js2-ast-root-comments js2-mode-ast))
11363 (let ((format (js2-comment-node-format n)))
11364 (when (js2-block-comment-p n)
11365 (js2-mode-hide-comment n))))
11366 (js2-mode-hide-//-comments)))
11367
11368 (defsubst js2-mode-extend-//-comment (direction)
11369 "Find start or end of a block of similar //-comment lines.
11370 DIRECTION is -1 to look back, 1 to look forward.
11371 INDENT is the indentation level to match.
11372 Returns the end-of-line position of the furthest adjacent
11373 //-comment line with the same indentation as the current line.
11374 If there is no such matching line, returns current end of line."
11375 (let ((pos (point-at-eol))
11376 (indent (current-indentation)))
11377 (save-excursion
11378 (save-match-data
11379 (while (and (zerop (forward-line direction))
11380 (looking-at js2-mode-//-comment-re)
11381 (eq indent (length (match-string 1))))
11382 (setq pos (point-at-eol)))
11383 pos))))
11384
11385 (defun js2-mode-hide-//-comments ()
11386 "Fold adjacent 1-line comments, showing only snippet of first one."
11387 (let (beg end)
11388 (save-excursion
11389 (save-match-data
11390 (goto-char (point-min))
11391 (while (re-search-forward js2-mode-//-comment-re nil t)
11392 (setq beg (point)
11393 end (js2-mode-extend-//-comment 1))
11394 (unless (eq beg end)
11395 (overlay-put (js2-mode-flag-region beg end 'hide)
11396 'comment t))
11397 (goto-char end)
11398 (forward-char 1))))))
11399
11400 (defun js2-mode-toggle-//-comment ()
11401 "Fold or un-fold any multi-line //-comment at point.
11402 Caller should have determined that this line starts with a //-comment."
11403 (let* ((beg (point-at-eol))
11404 (end beg))
11405 (save-excursion
11406 (goto-char end)
11407 (if (js2-mode-invisible-overlay-bounds)
11408 (js2-mode-show-element)
11409 ;; else hide the comment
11410 (setq beg (js2-mode-extend-//-comment -1)
11411 end (js2-mode-extend-//-comment 1))
11412 (unless (eq beg end)
11413 (overlay-put (js2-mode-flag-region beg end 'hide)
11414 'comment t))))))
11415
11416 (defun js2-mode-show-comments ()
11417 "Un-hide any hidden comments, leaving other hidden elements alone."
11418 (interactive)
11419 (setq js2-mode-comments-hidden nil)
11420 (save-excursion
11421 (goto-char (point-min))
11422 (while (/= (goto-char (next-overlay-change (point)))
11423 (point-max))
11424 (dolist (o (overlays-at (point)))
11425 (when (overlay-get o 'comment)
11426 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11427
11428 (defun js2-mode-display-warnings-and-errors ()
11429 "Turn on display of warnings and errors."
11430 (interactive)
11431 (setq js2-mode-show-parse-errors t
11432 js2-mode-show-strict-warnings t)
11433 (js2-reparse 'force))
11434
11435 (defun js2-mode-hide-warnings-and-errors ()
11436 "Turn off display of warnings and errors."
11437 (interactive)
11438 (setq js2-mode-show-parse-errors nil
11439 js2-mode-show-strict-warnings nil)
11440 (js2-reparse 'force))
11441
11442 (defun js2-mode-toggle-warnings-and-errors ()
11443 "Toggle the display of warnings and errors.
11444 Some users don't like having warnings/errors reported while they type."
11445 (interactive)
11446 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11447 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11448 (if (interactive-p)
11449 (message "warnings and errors %s"
11450 (if js2-mode-show-parse-errors
11451 "enabled"
11452 "disabled")))
11453 (js2-reparse 'force))
11454
11455 (defun js2-mode-customize ()
11456 (interactive)
11457 (customize-group 'js2-mode))
11458
11459 (defun js2-mode-forward-sexp (&optional arg)
11460 "Move forward across one statement or balanced expression.
11461 With ARG, do it that many times. Negative arg -N means
11462 move backward across N balanced expressions."
11463 (interactive "p")
11464 (setq arg (or arg 1))
11465 (if js2-mode-buffer-dirty-p
11466 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11467 (let (node end (start (point)))
11468 (cond
11469 ;; backward-sexp
11470 ;; could probably make this better for some cases:
11471 ;; - if in statement block (e.g. function body), go to parent
11472 ;; - infix exprs like (foo in bar) - maybe go to beginning
11473 ;; of infix expr if in the right-side expression?
11474 ((and arg (minusp arg))
11475 (dotimes (i (- arg))
11476 (js2-backward-sws)
11477 (forward-char -1) ; enter the node we backed up to
11478 (setq node (js2-node-at-point (point) t))
11479 (goto-char (if node
11480 (js2-node-abs-pos node)
11481 (point-min)))))
11482 (t
11483 ;; forward-sexp
11484 (js2-forward-sws)
11485 (dotimes (i arg)
11486 (js2-forward-sws)
11487 (setq node (js2-node-at-point (point) t)
11488 end (if node (+ (js2-node-abs-pos node)
11489 (js2-node-len node))))
11490 (goto-char (or end (point-max))))))))
11491
11492 (defun js2-next-error (&optional arg reset)
11493 "Move to next parse error.
11494 Typically invoked via \\[next-error].
11495 ARG is the number of errors, forward or backward, to move.
11496 RESET means start over from the beginning."
11497 (interactive "p")
11498 (if (or (null js2-mode-ast)
11499 (and (null (js2-ast-root-errors js2-mode-ast))
11500 (null (js2-ast-root-warnings js2-mode-ast))))
11501 (message "No errors")
11502 (when reset
11503 (goto-char (point-min)))
11504 (let* ((errs (copy-sequence
11505 (append (js2-ast-root-errors js2-mode-ast)
11506 (js2-ast-root-warnings js2-mode-ast))))
11507 (continue t)
11508 (start (point))
11509 (count (or arg 1))
11510 (backward (minusp count))
11511 (sorter (if backward '> '<))
11512 (stopper (if backward '< '>))
11513 (count (abs count))
11514 all-errs
11515 err)
11516 ;; sort by start position
11517 (setq errs (sort errs (lambda (e1 e2)
11518 (funcall sorter (second e1) (second e2))))
11519 all-errs errs)
11520 ;; find nth error with pos > start
11521 (while (and errs continue)
11522 (when (funcall stopper (cadar errs) start)
11523 (setq err (car errs))
11524 (if (zerop (decf count))
11525 (setq continue nil)))
11526 (setq errs (cdr errs)))
11527 (if err
11528 (goto-char (second err))
11529 ;; wrap around to first error
11530 (goto-char (second (car all-errs)))
11531 ;; if we were already on it, echo msg again
11532 (if (= (point) start)
11533 (js2-echo-error (point) (point)))))))
11534
11535 (defun js2-down-mouse-3 ()
11536 "Make right-click move the point to the click location.
11537 This makes right-click context menu operations a bit more intuitive.
11538 The point will not move if the region is active, however, to avoid
11539 destroying the region selection."
11540 (interactive)
11541 (when (and js2-move-point-on-right-click
11542 (not mark-active))
11543 (let ((e last-input-event))
11544 (ignore-errors
11545 (goto-char (cadadr e))))))
11546
11547 (defun js2-mode-create-imenu-index ()
11548 "Return an alist for `imenu--index-alist'."
11549 ;; This is built up in `js2-parse-record-imenu' during parsing.
11550 (when js2-mode-ast
11551 ;; if we have an ast but no recorder, they're requesting a rescan
11552 (unless js2-imenu-recorder
11553 (js2-reparse 'force))
11554 (prog1
11555 (js2-build-imenu-index)
11556 (setq js2-imenu-recorder nil
11557 js2-imenu-function-map nil))))
11558
11559 (defun js2-mode-find-tag ()
11560 "Replacement for `find-tag-default'.
11561 `find-tag-default' returns a ridiculous answer inside comments."
11562 (let (beg end)
11563 (js2-with-underscore-as-word-syntax
11564 (save-excursion
11565 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11566 (looking-back "[A-Za-z0-9_$]"))
11567 (setq beg (progn (forward-word -1) (point))
11568 end (progn (forward-word 1) (point)))
11569 (setq beg (progn (forward-word 1) (point))
11570 end (progn (forward-word -1) (point))))
11571 (replace-regexp-in-string
11572 "[\"']" ""
11573 (buffer-substring-no-properties beg end))))))
11574
11575 (defun js2-mode-forward-sibling ()
11576 "Move to the end of the sibling following point in parent.
11577 Returns non-nil if successful, or nil if there was no following sibling."
11578 (let* ((node (js2-node-at-point))
11579 (parent (js2-mode-find-enclosing-fn node))
11580 sib)
11581 (when (setq sib (js2-node-find-child-after (point) parent))
11582 (goto-char (+ (js2-node-abs-pos sib)
11583 (js2-node-len sib))))))
11584
11585 (defun js2-mode-backward-sibling ()
11586 "Move to the beginning of the sibling node preceding point in parent.
11587 Parent is defined as the enclosing script or function."
11588 (let* ((node (js2-node-at-point))
11589 (parent (js2-mode-find-enclosing-fn node))
11590 sib)
11591 (when (setq sib (js2-node-find-child-before (point) parent))
11592 (goto-char (js2-node-abs-pos sib)))))
11593
11594 (defun js2-beginning-of-defun (&optional arg)
11595 "Go to line on which current function starts, and return t on success.
11596 If we're not in a function or already at the beginning of one, go
11597 to beginning of previous script-level element.
11598 With ARG N, do that N times. If N is negative, move forward."
11599 (setq arg (or arg 1))
11600 (if (plusp arg)
11601 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11602 (when (cond
11603 ((js2-function-node-p parent)
11604 (goto-char (js2-node-abs-pos parent)))
11605 (t
11606 (js2-mode-backward-sibling)))
11607 (if (> arg 1)
11608 (js2-beginning-of-defun (1- arg))
11609 t)))
11610 (when (js2-end-of-defun)
11611 (if (>= arg -1)
11612 (js2-beginning-of-defun 1)
11613 (js2-beginning-of-defun (1+ arg))))))
11614
11615 (defun js2-end-of-defun ()
11616 "Go to the char after the last position of the current function
11617 or script-level element."
11618 (let* ((node (js2-node-at-point))
11619 (parent (or (and (js2-function-node-p node) node)
11620 (js2-node-parent-script-or-fn node)))
11621 script)
11622 (unless (js2-function-node-p parent)
11623 ;; use current script-level node, or, if none, the next one
11624 (setq script (or parent node))
11625 (setq parent (js2-node-find-child-before (point) script))
11626 (when (or (null parent)
11627 (>= (point) (+ (js2-node-abs-pos parent)
11628 (js2-node-len parent))))
11629 (setq parent (js2-node-find-child-after (point) script))))
11630 (when parent
11631 (goto-char (+ (js2-node-abs-pos parent)
11632 (js2-node-len parent))))))
11633
11634 (defun js2-mark-defun (&optional allow-extend)
11635 "Put mark at end of this function, point at beginning.
11636 The function marked is the one that contains point.
11637
11638 Interactively, if this command is repeated,
11639 or (in Transient Mark mode) if the mark is active,
11640 it marks the next defun after the ones already marked."
11641 (interactive "p")
11642 (let (extended)
11643 (when (and allow-extend
11644 (or (and (eq last-command this-command) (mark t))
11645 (and transient-mark-mode mark-active)))
11646 (let ((sib (save-excursion
11647 (goto-char (mark))
11648 (if (js2-mode-forward-sibling)
11649 (point))))
11650 node)
11651 (if sib
11652 (progn
11653 (set-mark sib)
11654 (setq extended t))
11655 ;; no more siblings - try extending to enclosing node
11656 (goto-char (mark t)))))
11657 (when (not extended)
11658 (let ((node (js2-node-at-point (point) t)) ; skip comments
11659 ast fn stmt parent beg end)
11660 (when (js2-ast-root-p node)
11661 (setq ast node
11662 node (or (js2-node-find-child-after (point) node)
11663 (js2-node-find-child-before (point) node))))
11664 ;; only mark whole buffer if we can't find any children
11665 (if (null node)
11666 (setq node ast))
11667 (if (js2-function-node-p node)
11668 (setq parent node)
11669 (setq fn (js2-mode-find-enclosing-fn node)
11670 stmt (if (or (null fn)
11671 (js2-ast-root-p fn))
11672 (js2-mode-find-first-stmt node))
11673 parent (or stmt fn)))
11674 (setq beg (js2-node-abs-pos parent)
11675 end (+ beg (js2-node-len parent)))
11676 (push-mark beg)
11677 (goto-char end)
11678 (exchange-point-and-mark)))))
11679
11680 (defun js2-narrow-to-defun ()
11681 "Narrow to the function enclosing point."
11682 (interactive)
11683 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11684 (fn (if (js2-script-node-p node)
11685 node
11686 (js2-mode-find-enclosing-fn node)))
11687 (beg (js2-node-abs-pos fn)))
11688 (unless (js2-ast-root-p fn)
11689 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11690
11691 (provide 'js2-mode)
11692
11693 ;;; js2-mode.el ends here