]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Mark the obsolete variables as such
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2012 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; Version: 1.0
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 and up
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 (make-obsolete-variable 'js2-mirror-mode 'electric-pair-mode "1.0")
219
220 (defcustom js2-auto-indent-p nil
221 "Automatic indentation with punctuation characters.
222 If non-nil, the current line is indented when certain punctuations
223 are inserted."
224 :group 'js2-mode
225 :type 'boolean)
226
227 (make-obsolete-variable 'js2-auto-indent-p 'electric-indent-mode "1.0")
228
229 (defcustom js2-bounce-indent-p nil
230 "Non-nil to have indent-line function choose among alternatives.
231 If nil, the indent-line function will indent to a predetermined column
232 based on heuristic guessing. If non-nil, then if the current line is
233 already indented to that predetermined column, indenting will choose
234 another likely column and indent to that spot. Repeated invocation of
235 the indent-line function will cycle among the computed alternatives.
236 See the function `js2-bounce-indent' for details. When it is non-nil,
237 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
238 :type 'boolean
239 :group 'js2-mode)
240
241 (defcustom js2-pretty-multiline-declarations t
242 "Non-nil to line up multiline declarations vertically:
243
244 var a = 10,
245 b = 20,
246 c = 30;
247
248 If the value is not `all', and the first assigned value in
249 declaration is a function/array/object literal spanning several
250 lines, it won't be indented additionally:
251
252 var o = { var bar = 2,
253 foo: 3 vs. o = {
254 }, foo: 3
255 bar = 2; };"
256 :group 'js2-mode
257 :type 'symbol)
258 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
259
260 (defcustom js2-indent-on-enter-key nil
261 "Non-nil to have Enter/Return key indent the line.
262 This is unusual for Emacs modes but common in IDEs like Eclipse."
263 :type 'boolean
264 :group 'js2-mode)
265
266 (make-obsolete-variable 'js2-indent-on-enter-key nil "1.0")
267
268 (defcustom js2-enter-indents-newline nil
269 "Non-nil to have Enter/Return key indent the newly-inserted line.
270 This is unusual for Emacs modes but common in IDEs like Eclipse."
271 :type 'boolean
272 :group 'js2-mode)
273
274 (make-obsolete-variable 'js2-enter-indents-newline nil "1.0")
275
276 (defcustom js2-rebind-eol-bol-keys t
277 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
278 If non-nil, bounce between bol/eol and first/last non-whitespace char."
279 :group 'js2-mode
280 :type 'boolean)
281
282 (make-obsolete-variable 'js2-rebind-eol-bol-keys nil "1.0")
283
284 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
285 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
286 Each value in the list is passed to `define-key'."
287 :type 'list
288 :group 'js2-mode)
289
290 (make-obsolete-variable 'js2-electric-keys 'electric-indent-chars "1.0")
291
292 (defcustom js2-idle-timer-delay 0.2
293 "Delay in secs before re-parsing after user makes changes.
294 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
295 :type 'number
296 :group 'js2-mode)
297 (make-variable-buffer-local 'js2-idle-timer-delay)
298
299 (defcustom js2-dynamic-idle-timer-adjust 0
300 "Positive to adjust `js2-idle-timer-delay' based on file size.
301 The idea is that for short files, parsing is faster so we can be
302 more responsive to user edits without interfering with editing.
303 The buffer length in characters (typically bytes) is divided by
304 this value and used to multiply `js2-idle-timer-delay' for the
305 buffer. For example, a 21k file and 10k adjust yields 21k/10k
306 == 2, so js2-idle-timer-delay is multiplied by 2.
307 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
308 `js2-idle-timer-delay' is not dependent on the file size."
309 :type 'number
310 :group 'js2-mode)
311
312 (defcustom js2-mode-escape-quotes t
313 "Non-nil to disable automatic quote-escaping inside strings."
314 :type 'boolean
315 :group 'js2-mode)
316
317 (make-obsolete-variable 'js2-mode-escape-quotes nil "1.0")
318
319 (defcustom js2-concat-multiline-strings t
320 "Non-nil to automatically turn a newline in mid-string into a
321 string concatenation. When `eol', the '+' will be inserted at the
322 end of the line, otherwise, at the beginning of the next line."
323 :type '(choice (const t) (const eol) (const nil))
324 :group 'js2-mode)
325
326 (defcustom js2-mode-show-parse-errors t
327 "True to highlight parse errors."
328 :type 'boolean
329 :group 'js2-mode)
330
331 (defcustom js2-mode-show-strict-warnings t
332 "Non-nil to emit Ecma strict-mode warnings.
333 Some of the warnings can be individually disabled by other flags,
334 even if this flag is non-nil."
335 :type 'boolean
336 :group 'js2-mode)
337
338 (defcustom js2-strict-trailing-comma-warning t
339 "Non-nil to warn about trailing commas in array literals.
340 Ecma-262 forbids them, but many browsers permit them. IE is the
341 big exception, and can produce bugs if you have trailing commas."
342 :type 'boolean
343 :group 'js2-mode)
344
345 (defcustom js2-strict-missing-semi-warning t
346 "Non-nil to warn about semicolon auto-insertion after statement.
347 Technically this is legal per Ecma-262, but some style guides disallow
348 depending on it."
349 :type 'boolean
350 :group 'js2-mode)
351
352 (defcustom js2-missing-semi-one-line-override nil
353 "Non-nil to permit missing semicolons in one-line functions.
354 In one-liner functions such as `function identity(x) {return x}'
355 people often omit the semicolon for a cleaner look. If you are
356 such a person, you can suppress the missing-semicolon warning
357 by setting this variable to t."
358 :type 'boolean
359 :group 'js2-mode)
360
361 (defcustom js2-strict-inconsistent-return-warning t
362 "Non-nil to warn about mixing returns with value-returns.
363 It's perfectly legal to have a `return' and a `return foo' in the
364 same function, but it's often an indicator of a bug, and it also
365 interferes with type inference (in systems that support it.)"
366 :type 'boolean
367 :group 'js2-mode)
368
369 (defcustom js2-strict-cond-assign-warning t
370 "Non-nil to warn about expressions like if (a = b).
371 This often should have been '==' instead of '='. If the warning
372 is enabled, you can suppress it on a per-expression basis by
373 parenthesizing the expression, e.g. if ((a = b)) ..."
374 :type 'boolean
375 :group 'js2-mode)
376
377 (defcustom js2-strict-var-redeclaration-warning t
378 "Non-nil to warn about redeclaring variables in a script or function."
379 :type 'boolean
380 :group 'js2-mode)
381
382 (defcustom js2-strict-var-hides-function-arg-warning t
383 "Non-nil to warn about a var decl hiding a function argument."
384 :type 'boolean
385 :group 'js2-mode)
386
387 (defcustom js2-skip-preprocessor-directives nil
388 "Non-nil to treat lines beginning with # as comments.
389 Useful for viewing Mozilla JavaScript source code."
390 :type 'boolean
391 :group 'js2-mode)
392
393 (defcustom js2-language-version 200
394 "Configures what JavaScript language version to recognize.
395 Currently versions 150, 160, 170, 180 and 200 are supported,
396 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
397 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
398 yield, and Array comprehensions, and 1.8 adds function closures."
399 :type 'integer
400 :group 'js2-mode)
401
402 (defcustom js2-allow-keywords-as-property-names t
403 "If non-nil, you can use JavaScript keywords as object property names.
404 Examples:
405
406 var foo = {int: 5, while: 6, continue: 7};
407 foo.return = 8;
408
409 Ecma-262 forbids this syntax, but many browsers support it."
410 :type 'boolean
411 :group 'js2-mode)
412
413 (defcustom js2-instanceof-has-side-effects nil
414 "If non-nil, treats the instanceof operator as having side effects.
415 This is useful for xulrunner apps."
416 :type 'boolean
417 :group 'js2-mode)
418
419 (defcustom js2-cleanup-whitespace nil
420 "Non-nil to invoke `delete-trailing-whitespace' before saves."
421 :type 'boolean
422 :group 'js2-mode)
423
424 (make-obsolete-variable 'js2-cleanup-whitespace 'before-save-hook "1.0")
425
426 (defcustom js2-move-point-on-right-click t
427 "Non-nil to move insertion point when you right-click.
428 This makes right-click context menu behavior a bit more intuitive,
429 since menu operations generally apply to the point. The exception
430 is if there is a region selection, in which case the point does -not-
431 move, so cut/copy/paste etc. can work properly.
432
433 Note that IntelliJ moves the point, and Eclipse leaves it alone,
434 so this behavior is customizable."
435 :group 'js2-mode
436 :type 'boolean)
437
438 (defcustom js2-allow-rhino-new-expr-initializer t
439 "Non-nil to support a Rhino's experimental syntactic construct.
440
441 Rhino supports the ability to follow a `new' expression with an object
442 literal, which is used to set additional properties on the new object
443 after calling its constructor. Syntax:
444
445 new <expr> [ ( arglist ) ] [initializer]
446
447 Hence, this expression:
448
449 new Object {a: 1, b: 2}
450
451 results in an Object with properties a=1 and b=2. This syntax is
452 apparently not configurable in Rhino - it's currently always enabled,
453 as of Rhino version 1.7R2."
454 :type 'boolean
455 :group 'js2-mode)
456
457 (defcustom js2-allow-member-expr-as-function-name nil
458 "Non-nil to support experimental Rhino syntax for function names.
459
460 Rhino supports an experimental syntax configured via the Rhino Context
461 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
462
463 function <member-expr> ( [ arg-list ] ) { <body> }
464
465 Where member-expr is a non-parenthesized 'member expression', which
466 is anything at the grammar level of a new-expression or lower, meaning
467 any expression that does not involve infix or unary operators.
468
469 When <member-expr> is not a simple identifier, then it is syntactic
470 sugar for assigning the anonymous function to the <member-expr>. Hence,
471 this code:
472
473 function a.b().c[2] (x, y) { ... }
474
475 is rewritten as:
476
477 a.b().c[2] = function(x, y) {...}
478
479 which doesn't seem particularly useful, but Rhino permits it."
480 :type 'boolean
481 :group 'js2-mode)
482
483 ;; scanner variables
484
485 (defmacro js2-deflocal (name value &optional comment)
486 "Define a buffer-local variable NAME with VALUE and COMMENT."
487 `(progn
488 (defvar ,name ,value ,comment)
489 (make-variable-buffer-local ',name)))
490
491 ;; We record the start and end position of each token.
492 (js2-deflocal js2-token-beg 1)
493 (js2-deflocal js2-token-end -1)
494
495 (defvar js2-EOF_CHAR -1
496 "Represents end of stream. Distinct from js2-EOF token type.")
497
498 ;; I originally used symbols to represent tokens, but Rhino uses
499 ;; ints and then sets various flag bits in them, so ints it is.
500 ;; The upshot is that we need a `js2-' prefix in front of each name.
501 (defvar js2-ERROR -1)
502 (defvar js2-EOF 0)
503 (defvar js2-EOL 1)
504 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
505 (defvar js2-LEAVEWITH 3)
506 (defvar js2-RETURN 4)
507 (defvar js2-GOTO 5)
508 (defvar js2-IFEQ 6)
509 (defvar js2-IFNE 7)
510 (defvar js2-SETNAME 8)
511 (defvar js2-BITOR 9)
512 (defvar js2-BITXOR 10)
513 (defvar js2-BITAND 11)
514 (defvar js2-EQ 12)
515 (defvar js2-NE 13)
516 (defvar js2-LT 14)
517 (defvar js2-LE 15)
518 (defvar js2-GT 16)
519 (defvar js2-GE 17)
520 (defvar js2-LSH 18)
521 (defvar js2-RSH 19)
522 (defvar js2-URSH 20)
523 (defvar js2-ADD 21) ; infix plus
524 (defvar js2-SUB 22) ; infix minus
525 (defvar js2-MUL 23)
526 (defvar js2-DIV 24)
527 (defvar js2-MOD 25)
528 (defvar js2-NOT 26)
529 (defvar js2-BITNOT 27)
530 (defvar js2-POS 28) ; unary plus
531 (defvar js2-NEG 29) ; unary minus
532 (defvar js2-NEW 30)
533 (defvar js2-DELPROP 31)
534 (defvar js2-TYPEOF 32)
535 (defvar js2-GETPROP 33)
536 (defvar js2-GETPROPNOWARN 34)
537 (defvar js2-SETPROP 35)
538 (defvar js2-GETELEM 36)
539 (defvar js2-SETELEM 37)
540 (defvar js2-CALL 38)
541 (defvar js2-NAME 39) ; an identifier
542 (defvar js2-NUMBER 40)
543 (defvar js2-STRING 41)
544 (defvar js2-NULL 42)
545 (defvar js2-THIS 43)
546 (defvar js2-FALSE 44)
547 (defvar js2-TRUE 45)
548 (defvar js2-SHEQ 46) ; shallow equality (===)
549 (defvar js2-SHNE 47) ; shallow inequality (!==)
550 (defvar js2-REGEXP 48)
551 (defvar js2-BINDNAME 49)
552 (defvar js2-THROW 50)
553 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
554 (defvar js2-IN 52)
555 (defvar js2-INSTANCEOF 53)
556 (defvar js2-LOCAL_LOAD 54)
557 (defvar js2-GETVAR 55)
558 (defvar js2-SETVAR 56)
559 (defvar js2-CATCH_SCOPE 57)
560 (defvar js2-ENUM_INIT_KEYS 58)
561 (defvar js2-ENUM_INIT_VALUES 59)
562 (defvar js2-ENUM_INIT_ARRAY 60)
563 (defvar js2-ENUM_NEXT 61)
564 (defvar js2-ENUM_ID 62)
565 (defvar js2-THISFN 63)
566 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
567 (defvar js2-ARRAYLIT 65) ; array literal
568 (defvar js2-OBJECTLIT 66) ; object literal
569 (defvar js2-GET_REF 67) ; *reference
570 (defvar js2-SET_REF 68) ; *reference = something
571 (defvar js2-DEL_REF 69) ; delete reference
572 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
573 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
574 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
575
576 ;; XML support
577 (defvar js2-DEFAULTNAMESPACE 73)
578 (defvar js2-ESCXMLATTR 74)
579 (defvar js2-ESCXMLTEXT 75)
580 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
581 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
582 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
583 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
584
585 (defvar js2-first-bytecode js2-ENTERWITH)
586 (defvar js2-last-bytecode js2-REF_NS_NAME)
587
588 (defvar js2-TRY 80)
589 (defvar js2-SEMI 81) ; semicolon
590 (defvar js2-LB 82) ; left and right brackets
591 (defvar js2-RB 83)
592 (defvar js2-LC 84) ; left and right curly-braces
593 (defvar js2-RC 85)
594 (defvar js2-LP 86) ; left and right parens
595 (defvar js2-RP 87)
596 (defvar js2-COMMA 88) ; comma operator
597
598 (defvar js2-ASSIGN 89) ; simple assignment (=)
599 (defvar js2-ASSIGN_BITOR 90) ; |=
600 (defvar js2-ASSIGN_BITXOR 91) ; ^=
601 (defvar js2-ASSIGN_BITAND 92) ; &=
602 (defvar js2-ASSIGN_LSH 93) ; <<=
603 (defvar js2-ASSIGN_RSH 94) ; >>=
604 (defvar js2-ASSIGN_URSH 95) ; >>>=
605 (defvar js2-ASSIGN_ADD 96) ; +=
606 (defvar js2-ASSIGN_SUB 97) ; -=
607 (defvar js2-ASSIGN_MUL 98) ; *=
608 (defvar js2-ASSIGN_DIV 99) ; /=
609 (defvar js2-ASSIGN_MOD 100) ; %=
610
611 (defvar js2-first-assign js2-ASSIGN)
612 (defvar js2-last-assign js2-ASSIGN_MOD)
613
614 (defvar js2-HOOK 101) ; conditional (?:)
615 (defvar js2-COLON 102)
616 (defvar js2-OR 103) ; logical or (||)
617 (defvar js2-AND 104) ; logical and (&&)
618 (defvar js2-INC 105) ; increment/decrement (++ --)
619 (defvar js2-DEC 106)
620 (defvar js2-DOT 107) ; member operator (.)
621 (defvar js2-FUNCTION 108) ; function keyword
622 (defvar js2-EXPORT 109) ; export keyword
623 (defvar js2-IMPORT 110) ; import keyword
624 (defvar js2-IF 111) ; if keyword
625 (defvar js2-ELSE 112) ; else keyword
626 (defvar js2-SWITCH 113) ; switch keyword
627 (defvar js2-CASE 114) ; case keyword
628 (defvar js2-DEFAULT 115) ; default keyword
629 (defvar js2-WHILE 116) ; while keyword
630 (defvar js2-DO 117) ; do keyword
631 (defvar js2-FOR 118) ; for keyword
632 (defvar js2-BREAK 119) ; break keyword
633 (defvar js2-CONTINUE 120) ; continue keyword
634 (defvar js2-VAR 121) ; var keyword
635 (defvar js2-WITH 122) ; with keyword
636 (defvar js2-CATCH 123) ; catch keyword
637 (defvar js2-FINALLY 124) ; finally keyword
638 (defvar js2-VOID 125) ; void keyword
639 (defvar js2-RESERVED 126) ; reserved keywords
640
641 (defvar js2-EMPTY 127)
642
643 ;; Types used for the parse tree - never returned by scanner.
644
645 (defvar js2-BLOCK 128) ; statement block
646 (defvar js2-LABEL 129) ; label
647 (defvar js2-TARGET 130)
648 (defvar js2-LOOP 131)
649 (defvar js2-EXPR_VOID 132) ; expression statement in functions
650 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
651 (defvar js2-JSR 134)
652 (defvar js2-SCRIPT 135) ; top-level node for entire script
653 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
654 (defvar js2-USE_STACK 137)
655 (defvar js2-SETPROP_OP 138) ; x.y op= something
656 (defvar js2-SETELEM_OP 139) ; x[y] op= something
657 (defvar js2-LOCAL_BLOCK 140)
658 (defvar js2-SET_REF_OP 141) ; *reference op= something
659
660 ;; For XML support:
661 (defvar js2-DOTDOT 142) ; member operator (..)
662 (defvar js2-COLONCOLON 143) ; namespace::name
663 (defvar js2-XML 144) ; XML type
664 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
665 (defvar js2-XMLATTR 146) ; @
666 (defvar js2-XMLEND 147)
667
668 ;; Optimizer-only tokens
669 (defvar js2-TO_OBJECT 148)
670 (defvar js2-TO_DOUBLE 149)
671
672 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
673 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
674 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
675 (defvar js2-CONST 153)
676 (defvar js2-SETCONST 154)
677 (defvar js2-SETCONSTVAR 155)
678 (defvar js2-ARRAYCOMP 156)
679 (defvar js2-LETEXPR 157)
680 (defvar js2-WITHEXPR 158)
681 (defvar js2-DEBUGGER 159)
682
683 (defvar js2-COMMENT 160)
684 (defvar js2-ENUM 161) ; for "enum" reserved word
685 (defvar js2-TRIPLEDOT 162) ; for rest parameter
686
687 (defconst js2-num-tokens (1+ js2-TRIPLEDOT))
688
689 (defconst js2-debug-print-trees nil)
690
691 ;; Rhino accepts any string or stream as input. Emacs character
692 ;; processing works best in buffers, so we'll assume the input is a
693 ;; buffer. JavaScript strings can be copied into temp buffers before
694 ;; scanning them.
695
696 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
697 ;; They're the Emacs equivalent of instance variables, more or less.
698
699 (js2-deflocal js2-ts-dirty-line nil
700 "Token stream buffer-local variable.
701 Indicates stuff other than whitespace since start of line.")
702
703 (js2-deflocal js2-ts-regexp-flags nil
704 "Token stream buffer-local variable.")
705
706 (js2-deflocal js2-ts-string ""
707 "Token stream buffer-local variable.
708 Last string scanned.")
709
710 (js2-deflocal js2-ts-number nil
711 "Token stream buffer-local variable.
712 Last literal number scanned.")
713
714 (js2-deflocal js2-ts-hit-eof nil
715 "Token stream buffer-local variable.")
716
717 (js2-deflocal js2-ts-line-start 0
718 "Token stream buffer-local variable.")
719
720 (js2-deflocal js2-ts-lineno 1
721 "Token stream buffer-local variable.")
722
723 (js2-deflocal js2-ts-line-end-char -1
724 "Token stream buffer-local variable.")
725
726 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
727 "Token stream buffer-local variable.
728 Current scan position.")
729
730 (js2-deflocal js2-ts-is-xml-attribute nil
731 "Token stream buffer-local variable.")
732
733 (js2-deflocal js2-ts-xml-is-tag-content nil
734 "Token stream buffer-local variable.")
735
736 (js2-deflocal js2-ts-xml-open-tags-count 0
737 "Token stream buffer-local variable.")
738
739 (js2-deflocal js2-ts-string-buffer nil
740 "Token stream buffer-local variable.
741 List of chars built up while scanning various tokens.")
742
743 (js2-deflocal js2-ts-comment-type nil
744 "Token stream buffer-local variable.")
745
746 ;;; Parser variables
747
748 (js2-deflocal js2-parsed-errors nil
749 "List of errors produced during scanning/parsing.")
750
751 (js2-deflocal js2-parsed-warnings nil
752 "List of warnings produced during scanning/parsing.")
753
754 (js2-deflocal js2-recover-from-parse-errors t
755 "Non-nil to continue parsing after a syntax error.
756
757 In recovery mode, the AST will be built in full, and any error
758 nodes will be flagged with appropriate error information. If
759 this flag is nil, a syntax error will result in an error being
760 signaled.
761
762 The variable is automatically buffer-local, because different
763 modes that use the parser will need different settings.")
764
765 (js2-deflocal js2-parse-hook nil
766 "List of callbacks for receiving parsing progress.")
767
768 (defvar js2-parse-finished-hook nil
769 "List of callbacks to notify when parsing finishes.
770 Not called if parsing was interrupted.")
771
772 (js2-deflocal js2-is-eval-code nil
773 "True if we're evaluating code in a string.
774 If non-nil, the tokenizer will record the token text, and the AST nodes
775 will record their source text. Off by default for IDE modes, since the
776 text is available in the buffer.")
777
778 (defvar js2-parse-ide-mode t
779 "Non-nil if the parser is being used for `js2-mode'.
780 If non-nil, the parser will set text properties for fontification
781 and the syntax table. The value should be nil when using the
782 parser as a frontend to an interpreter or byte compiler.")
783
784 ;;; Parser instance variables (buffer-local vars for js2-parse)
785
786 (defconst js2-clear-ti-mask #xFFFF
787 "Mask to clear token information bits.")
788
789 (defconst js2-ti-after-eol (lsh 1 16)
790 "Flag: first token of the source line.")
791
792 (defconst js2-ti-check-label (lsh 1 17)
793 "Flag: indicates to check for label.")
794
795 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
796
797 (js2-deflocal js2-compiler-generate-debug-info t)
798 (js2-deflocal js2-compiler-use-dynamic-scope nil)
799 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
800 (js2-deflocal js2-compiler-xml-available t)
801 (js2-deflocal js2-compiler-optimization-level 0)
802 (js2-deflocal js2-compiler-generating-source t)
803 (js2-deflocal js2-compiler-strict-mode nil)
804 (js2-deflocal js2-compiler-report-warning-as-error nil)
805 (js2-deflocal js2-compiler-generate-observer-count nil)
806 (js2-deflocal js2-compiler-activation-names nil)
807
808 ;; SKIP: sourceURI
809
810 ;; There's a compileFunction method in Context.java - may need it.
811 (js2-deflocal js2-called-by-compile-function nil
812 "True if `js2-parse' was called by `js2-compile-function'.
813 Will only be used when we finish implementing the interpreter.")
814
815 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
816
817 (js2-deflocal js2-current-flagged-token js2-EOF)
818 (js2-deflocal js2-current-token js2-EOF)
819
820 ;; SKIP: node factory - we're going to just call functions directly,
821 ;; and eventually go to a unified AST format.
822
823 (js2-deflocal js2-nesting-of-function 0)
824
825 (js2-deflocal js2-recorded-identifiers nil
826 "Tracks identifiers found during parsing.")
827
828 (js2-deflocal js2-is-in-destructuring nil
829 "True while parsing destructuring expression.")
830
831 (defcustom js2-global-externs nil
832 "A list of any extern names you'd like to consider always declared.
833 This list is global and is used by all js2-mode files.
834 You can create buffer-local externs list using `js2-additional-externs'.
835
836 There is also a buffer-local variable `js2-default-externs',
837 which is initialized by default to include the Ecma-262 externs
838 and the standard browser externs. The three lists are all
839 checked during highlighting."
840 :type 'list
841 :group 'js2-mode)
842
843 (js2-deflocal js2-default-externs nil
844 "Default external declarations.
845
846 These are currently only used for highlighting undeclared variables,
847 which only worries about top-level (unqualified) references.
848 As js2-mode's processing improves, we will flesh out this list.
849
850 The initial value is set to `js2-ecma-262-externs', unless you
851 have set `js2-include-browser-externs', in which case the browser
852 externs are also included.
853
854 See `js2-additional-externs' for more information.")
855
856 (defcustom js2-include-browser-externs t
857 "Non-nil to include browser externs in the master externs list.
858 If you work on JavaScript files that are not intended for browsers,
859 such as Mozilla Rhino server-side JavaScript, set this to nil.
860 You can always include them on a per-file basis by calling
861 `js2-add-browser-externs' from a function on `js2-mode-hook'.
862
863 See `js2-additional-externs' for more information about externs."
864 :type 'boolean
865 :group 'js2-mode)
866
867 (defcustom js2-include-rhino-externs t
868 "Non-nil to include Mozilla Rhino externs in the master externs list.
869 See `js2-additional-externs' for more information about externs."
870 :type 'boolean
871 :group 'js2-mode)
872
873 (defcustom js2-include-gears-externs t
874 "Non-nil to include Google Gears externs in the master externs list.
875 See `js2-additional-externs' for more information about externs."
876 :type 'boolean
877 :group 'js2-mode)
878
879 (js2-deflocal js2-additional-externs nil
880 "A buffer-local list of additional external declarations.
881 It is used to decide whether variables are considered undeclared
882 for purposes of highlighting.
883
884 Each entry is a lisp string. The string should be the fully qualified
885 name of an external entity. All externs should be added to this list,
886 so that as js2-mode's processing improves it can take advantage of them.
887
888 You may want to declare your externs in three ways.
889 First, you can add externs that are valid for all your JavaScript files.
890 You should probably do this by adding them to `js2-global-externs', which
891 is a global list used for all js2-mode files.
892
893 Next, you can add a function to `js2-mode-hook' that adds additional
894 externs appropriate for the specific file, perhaps based on its path.
895 These should go in `js2-additional-externs', which is buffer-local.
896
897 Finally, you can add a function to `js2-post-parse-callbacks',
898 which is called after parsing completes, and `js2-mode-ast' is bound to
899 the root of the parse tree. At this stage you can set up an AST
900 node visitor using `js2-visit-ast' and examine the parse tree
901 for specific import patterns that may imply the existence of
902 other externs, possibly tied to your build system. These should also
903 be added to `js2-additional-externs'.
904
905 Your post-parse callback may of course also use the simpler and
906 faster (but perhaps less robust) approach of simply scanning the
907 buffer text for your imports, using regular expressions.")
908
909 ;; SKIP: decompiler
910 ;; SKIP: encoded-source
911
912 ;;; The following variables are per-function and should be saved/restored
913 ;;; during function parsing...
914
915 (js2-deflocal js2-current-script-or-fn nil)
916 (js2-deflocal js2-current-scope nil)
917 (js2-deflocal js2-nesting-of-with 0)
918 (js2-deflocal js2-label-set nil
919 "An alist mapping label names to nodes.")
920
921 (js2-deflocal js2-loop-set nil)
922 (js2-deflocal js2-loop-and-switch-set nil)
923 (js2-deflocal js2-has-return-value nil)
924 (js2-deflocal js2-end-flags 0)
925
926 ;;; ...end of per function variables
927
928 ;; Without 2-token lookahead, labels are a problem.
929 ;; These vars store the token info of the last matched name,
930 ;; iff it wasn't the last matched token. Only valid in some contexts.
931 (defvar js2-prev-name-token-start nil)
932 (defvar js2-prev-name-token-string nil)
933
934 (defsubst js2-save-name-token-data (pos name)
935 (setq js2-prev-name-token-start pos
936 js2-prev-name-token-string name))
937
938 ;; These flags enumerate the possible ways a statement/function can
939 ;; terminate. These flags are used by endCheck() and by the Parser to
940 ;; detect inconsistent return usage.
941 ;;
942 ;; END_UNREACHED is reserved for code paths that are assumed to always be
943 ;; able to execute (example: throw, continue)
944 ;;
945 ;; END_DROPS_OFF indicates if the statement can transfer control to the
946 ;; next one. Statement such as return dont. A compound statement may have
947 ;; some branch that drops off control to the next statement.
948 ;;
949 ;; END_RETURNS indicates that the statement can return (without arguments)
950 ;; END_RETURNS_VALUE indicates that the statement can return a value.
951 ;;
952 ;; A compound statement such as
953 ;; if (condition) {
954 ;; return value;
955 ;; }
956 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
957
958 (defconst js2-end-unreached #x0)
959 (defconst js2-end-drops-off #x1)
960 (defconst js2-end-returns #x2)
961 (defconst js2-end-returns-value #x4)
962 (defconst js2-end-yields #x8)
963
964 ;; Rhino awkwardly passes a statementLabel parameter to the
965 ;; statementHelper() function, the main statement parser, which
966 ;; is then used by quite a few of the sub-parsers. We just make
967 ;; it a buffer-local variable and make sure it's cleaned up properly.
968 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
969
970 ;; Similarly, Rhino passes an inForInit boolean through about half
971 ;; the expression parsers. We use a dynamically-scoped variable,
972 ;; which makes it easier to funcall the parsers individually without
973 ;; worrying about whether they take the parameter or not.
974 (js2-deflocal js2-in-for-init nil)
975 (js2-deflocal js2-temp-name-counter 0)
976 (js2-deflocal js2-parse-stmt-count 0)
977
978 (defsubst js2-get-next-temp-name ()
979 (format "$%d" (incf js2-temp-name-counter)))
980
981 (defvar js2-parse-interruptable-p t
982 "Set this to nil to force parse to continue until finished.
983 This will mostly be useful for interpreters.")
984
985 (defvar js2-statements-per-pause 50
986 "Pause after this many statements to check for user input.
987 If user input is pending, stop the parse and discard the tree.
988 This makes for a smoother user experience for large files.
989 You may have to wait a second or two before the highlighting
990 and error-reporting appear, but you can always type ahead if
991 you wish. This appears to be more or less how Eclipse, IntelliJ
992 and other editors work.")
993
994 (js2-deflocal js2-record-comments t
995 "Instructs the scanner to record comments in `js2-scanned-comments'.")
996
997 (js2-deflocal js2-scanned-comments nil
998 "List of all comments from the current parse.")
999
1000 (defcustom js2-mode-indent-inhibit-undo nil
1001 "Non-nil to disable collection of Undo information when indenting lines.
1002 Some users have requested this behavior. It's nil by default because
1003 other Emacs modes don't work this way."
1004 :type 'boolean
1005 :group 'js2-mode)
1006
1007 (defcustom js2-mode-indent-ignore-first-tab nil
1008 "If non-nil, ignore first TAB keypress if we look indented properly.
1009 It's fairly common for users to navigate to an already-indented line
1010 and press TAB for reassurance that it's been indented. For this class
1011 of users, we want the first TAB press on a line to be ignored if the
1012 line is already indented to one of the precomputed alternatives.
1013
1014 This behavior is only partly implemented. If you TAB-indent a line,
1015 navigate to another line, and then navigate back, it fails to clear
1016 the last-indented variable, so it thinks you've already hit TAB once,
1017 and performs the indent. A full solution would involve getting on the
1018 point-motion hooks for the entire buffer. If we come across another
1019 use cases that requires watching point motion, I'll consider doing it.
1020
1021 If you set this variable to nil, then the TAB key will always change
1022 the indentation of the current line, if more than one alternative
1023 indentation spot exists."
1024 :type 'boolean
1025 :group 'js2-mode)
1026
1027 (defvar js2-indent-hook nil
1028 "A hook for user-defined indentation rules.
1029
1030 Functions on this hook should expect two arguments: (LIST INDEX)
1031 The LIST argument is the list of computed indentation points for
1032 the current line. INDEX is the list index of the indentation point
1033 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1034 indent function is not going to change the current line indentation.
1035
1036 If a hook function on this list returns a non-nil value, then
1037 `js2-bounce-indent' assumes the hook function has performed its own
1038 indentation, and will do nothing. If all hook functions on the list
1039 return nil, then `js2-bounce-indent' will use its computed indentation
1040 and reindent the line.
1041
1042 When hook functions on this hook list are called, the variable
1043 `js2-mode-ast' may or may not be set, depending on whether the
1044 parse tree is available. If the variable is nil, you can pass a
1045 callback to `js2-mode-wait-for-parse', and your callback will be
1046 called after the new parse tree is built. This can take some time
1047 in large files.")
1048
1049 (defface js2-warning-face
1050 `((((class color) (background light))
1051 (:underline "orange"))
1052 (((class color) (background dark))
1053 (:underline "orange"))
1054 (t (:underline t)))
1055 "Face for JavaScript warnings."
1056 :group 'js2-mode)
1057
1058 (defface js2-error-face
1059 `((((class color) (background light))
1060 (:foreground "red"))
1061 (((class color) (background dark))
1062 (:foreground "red"))
1063 (t (:foreground "red")))
1064 "Face for JavaScript errors."
1065 :group 'js2-mode)
1066
1067 (defface js2-jsdoc-tag-face
1068 '((t :foreground "SlateGray"))
1069 "Face used to highlight @whatever tags in jsdoc comments."
1070 :group 'js2-mode)
1071
1072 (defface js2-jsdoc-type-face
1073 '((t :foreground "SteelBlue"))
1074 "Face used to highlight {FooBar} types in jsdoc comments."
1075 :group 'js2-mode)
1076
1077 (defface js2-jsdoc-value-face
1078 '((t :foreground "PeachPuff3"))
1079 "Face used to highlight tag values in jsdoc comments."
1080 :group 'js2-mode)
1081
1082 (defface js2-function-param-face
1083 '((t :foreground "SeaGreen"))
1084 "Face used to highlight function parameters in javascript."
1085 :group 'js2-mode)
1086
1087 (defface js2-instance-member-face
1088 '((t :foreground "DarkOrchid"))
1089 "Face used to highlight instance variables in javascript.
1090 Not currently used."
1091 :group 'js2-mode)
1092
1093 (defface js2-private-member-face
1094 '((t :foreground "PeachPuff3"))
1095 "Face used to highlight calls to private methods in javascript.
1096 Not currently used."
1097 :group 'js2-mode)
1098
1099 (defface js2-private-function-call-face
1100 '((t :foreground "goldenrod"))
1101 "Face used to highlight calls to private functions in javascript.
1102 Not currently used."
1103 :group 'js2-mode)
1104
1105 (defface js2-jsdoc-html-tag-name-face
1106 (if js2-emacs22
1107 '((((class color) (min-colors 88) (background light))
1108 (:foreground "rosybrown"))
1109 (((class color) (min-colors 8) (background dark))
1110 (:foreground "yellow"))
1111 (((class color) (min-colors 8) (background light))
1112 (:foreground "magenta")))
1113 '((((type tty pc) (class color) (background light))
1114 (:foreground "magenta"))
1115 (((type tty pc) (class color) (background dark))
1116 (:foreground "yellow"))
1117 (t (:foreground "RosyBrown"))))
1118 "Face used to highlight jsdoc html tag names"
1119 :group 'js2-mode)
1120
1121 (defface js2-jsdoc-html-tag-delimiter-face
1122 (if js2-emacs22
1123 '((((class color) (min-colors 88) (background light))
1124 (:foreground "dark khaki"))
1125 (((class color) (min-colors 8) (background dark))
1126 (:foreground "green"))
1127 (((class color) (min-colors 8) (background light))
1128 (:foreground "green")))
1129 '((((type tty pc) (class color) (background light))
1130 (:foreground "green"))
1131 (((type tty pc) (class color) (background dark))
1132 (:foreground "green"))
1133 (t (:foreground "dark khaki"))))
1134 "Face used to highlight brackets in jsdoc html tags."
1135 :group 'js2-mode)
1136
1137 (defface js2-magic-paren-face
1138 '((t :underline t))
1139 "Face used to color parens that will be auto-overwritten."
1140 :group 'js2-mode)
1141
1142 (defcustom js2-post-parse-callbacks nil
1143 "A list of callback functions invoked after parsing finishes.
1144 Currently, the main use for this function is to add synthetic
1145 declarations to `js2-recorded-identifiers', which see."
1146 :type 'list
1147 :group 'js2-mode)
1148
1149 (defface js2-external-variable-face
1150 '((t :foreground "orange"))
1151 "Face used to highlight undeclared variable identifiers.
1152 An undeclared variable is any variable not declared with var or let
1153 in the current scope or any lexically enclosing scope. If you use
1154 such a variable, then you are either expecting it to originate from
1155 another file, or you've got a potential bug."
1156 :group 'js2-mode)
1157
1158 (defcustom js2-highlight-external-variables t
1159 "Non-nil to highlight undeclared variable identifiers."
1160 :type 'boolean
1161 :group 'js2-mode)
1162
1163 (defcustom js2-auto-insert-catch-block t
1164 "Non-nil to insert matching catch block on open-curly after `try'."
1165 :type 'boolean
1166 :group 'js2-mode)
1167
1168 (defvar js2-mode-map
1169 (let ((map (make-sparse-keymap))
1170 keys)
1171 (define-key map [mouse-1] #'js2-mode-show-node)
1172 (define-key map (kbd "C-m") #'js2-enter-key)
1173 (when js2-rebind-eol-bol-keys
1174 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1175 (define-key map (kbd "C-e") #'js2-end-of-line))
1176 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1177 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1178 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1179 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1180 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1181 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1182 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1183 (define-key map (kbd "C-c C-`") #'js2-next-error)
1184 (define-key map (or (car (where-is-internal #'mark-defun))
1185 (kbd "M-C-h"))
1186 #'js2-mark-defun)
1187 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1188 (kbd "C-x nd"))
1189 #'js2-narrow-to-defun)
1190 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1191 (when js2-auto-indent-p
1192 (mapc (lambda (key)
1193 (define-key map key #'js2-insert-and-indent))
1194 js2-electric-keys))
1195 (when js2-bounce-indent-p
1196 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1197
1198 (define-key map [menu-bar javascript]
1199 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1200
1201 (define-key map [menu-bar javascript customize-js2-mode]
1202 '(menu-item "Customize js2-mode" js2-mode-customize
1203 :help "Customize the behavior of this mode"))
1204
1205 (define-key map [menu-bar javascript js2-force-refresh]
1206 '(menu-item "Force buffer refresh" js2-mode-reset
1207 :help "Re-parse the buffer from scratch"))
1208
1209 (define-key map [menu-bar javascript separator-2]
1210 '("--"))
1211
1212 (define-key map [menu-bar javascript next-error]
1213 '(menu-item "Next warning or error" js2-next-error
1214 :enabled (and js2-mode-ast
1215 (or (js2-ast-root-errors js2-mode-ast)
1216 (js2-ast-root-warnings js2-mode-ast)))
1217 :help "Move to next warning or error"))
1218
1219 (define-key map [menu-bar javascript display-errors]
1220 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1221 :visible (not js2-mode-show-parse-errors)
1222 :help "Turn on display of warnings and errors"))
1223
1224 (define-key map [menu-bar javascript hide-errors]
1225 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1226 :visible js2-mode-show-parse-errors
1227 :help "Turn off display of warnings and errors"))
1228
1229 (define-key map [menu-bar javascript separator-1]
1230 '("--"))
1231
1232 (define-key map [menu-bar javascript js2-toggle-function]
1233 '(menu-item "Show/collapse element" js2-mode-toggle-element
1234 :help "Hide or show function body or comment"))
1235
1236 (define-key map [menu-bar javascript show-comments]
1237 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1238 :visible js2-mode-comments-hidden
1239 :help "Expand all hidden block comments"))
1240
1241 (define-key map [menu-bar javascript hide-comments]
1242 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1243 :visible (not js2-mode-comments-hidden)
1244 :help "Show block comments as /*...*/"))
1245
1246 (define-key map [menu-bar javascript show-all-functions]
1247 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1248 :visible js2-mode-functions-hidden
1249 :help "Expand all hidden function bodies"))
1250
1251 (define-key map [menu-bar javascript hide-all-functions]
1252 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1253 :visible (not js2-mode-functions-hidden)
1254 :help "Show {...} for all top-level function bodies"))
1255
1256 map)
1257 "Keymap used in `js2-mode' buffers.")
1258
1259 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1260
1261 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1262 "Matches a //-comment line. Must be first non-whitespace on line.
1263 First match-group is the leading whitespace.")
1264
1265 (defvar js2-mode-hook nil)
1266
1267 (js2-deflocal js2-mode-ast nil "Private variable.")
1268 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1269 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1270 (js2-deflocal js2-mode-parsing nil "Private variable.")
1271 (js2-deflocal js2-mode-node-overlay nil)
1272
1273 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1274 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1275
1276 (js2-deflocal js2-mode-fontifications nil "Private variable")
1277 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1278 (js2-deflocal js2-imenu-recorder nil "Private variable")
1279 (js2-deflocal js2-imenu-function-map nil "Private variable")
1280
1281 (defvar js2-paragraph-start
1282 "\\(@[a-zA-Z]+\\>\\|$\\)")
1283
1284 ;; Note that we also set a 'c-in-sws text property in html comments,
1285 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1286 (defvar js2-syntactic-ws-start
1287 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1288
1289 (defvar js2-syntactic-ws-end
1290 "\\s \\|[\n\r/]\\|\\s!")
1291
1292 (defvar js2-syntactic-eol
1293 (concat "\\s *\\(/\\*[^*\n\r]*"
1294 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1295 "\\*+/\\s *\\)*"
1296 "\\(//\\|/\\*[^*\n\r]*"
1297 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1298 "\\|\\\\$\\|$\\)")
1299 "Copied from `java-mode'. Needed for some cc-engine functions.")
1300
1301 (defvar js2-comment-prefix-regexp
1302 "//+\\|\\**")
1303
1304 (defvar js2-comment-start-skip
1305 "\\(//+\\|/\\*+\\)\\s *")
1306
1307 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1308 "Non-nil to emit status messages during parsing.")
1309
1310 (defvar js2-mode-functions-hidden nil "private variable")
1311 (defvar js2-mode-comments-hidden nil "private variable")
1312
1313 (defvar js2-mode-syntax-table
1314 (let ((table (make-syntax-table)))
1315 (c-populate-syntax-table table)
1316 table)
1317 "Syntax table used in js2-mode buffers.")
1318
1319 (defvar js2-mode-abbrev-table nil
1320 "Abbrev table in use in `js2-mode' buffers.")
1321 (define-abbrev-table 'js2-mode-abbrev-table ())
1322
1323 (defvar js2-mode-pending-parse-callbacks nil
1324 "List of functions waiting to be notified that parse is finished.")
1325
1326 (defvar js2-mode-last-indented-line -1)
1327
1328 ;;; Localizable error and warning messages
1329
1330 ;; Messages are copied from Rhino's Messages.properties.
1331 ;; Many of the Java-specific messages have been elided.
1332 ;; Add any js2-specific ones at the end, so we can keep
1333 ;; this file synced with changes to Rhino's.
1334
1335 (defvar js2-message-table
1336 (make-hash-table :test 'equal :size 250)
1337 "Contains localized messages for js2-mode.")
1338
1339 ;; TODO(stevey): construct this table at compile-time.
1340 (defmacro js2-msg (key &rest strings)
1341 `(puthash ,key (funcall #'concat ,@strings)
1342 js2-message-table))
1343
1344 (defun js2-get-msg (msg-key)
1345 "Look up a localized message.
1346 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1347 the correct number of ARGS must be provided."
1348 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1349 (args (if (listp msg-key) (cdr msg-key)))
1350 (msg (gethash key js2-message-table)))
1351 (if msg
1352 (apply #'format msg args)
1353 key))) ; default to showing the key
1354
1355 (js2-msg "msg.dup.parms"
1356 "Duplicate parameter name '%s'.")
1357
1358 (js2-msg "msg.too.big.jump"
1359 "Program too complex: jump offset too big.")
1360
1361 (js2-msg "msg.too.big.index"
1362 "Program too complex: internal index exceeds 64K limit.")
1363
1364 (js2-msg "msg.while.compiling.fn"
1365 "Encountered code generation error while compiling function '%s': %s")
1366
1367 (js2-msg "msg.while.compiling.script"
1368 "Encountered code generation error while compiling script: %s")
1369
1370 ;; Context
1371 (js2-msg "msg.ctor.not.found"
1372 "Constructor for '%s' not found.")
1373
1374 (js2-msg "msg.not.ctor"
1375 "'%s' is not a constructor.")
1376
1377 ;; FunctionObject
1378 (js2-msg "msg.varargs.ctor"
1379 "Method or constructor '%s' must be static "
1380 "with the signature (Context cx, Object[] args, "
1381 "Function ctorObj, boolean inNewExpr) "
1382 "to define a variable arguments constructor.")
1383
1384 (js2-msg "msg.varargs.fun"
1385 "Method '%s' must be static with the signature "
1386 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1387 "to define a variable arguments function.")
1388
1389 (js2-msg "msg.incompat.call"
1390 "Method '%s' called on incompatible object.")
1391
1392 (js2-msg "msg.bad.parms"
1393 "Unsupported parameter type '%s' in method '%s'.")
1394
1395 (js2-msg "msg.bad.method.return"
1396 "Unsupported return type '%s' in method '%s'.")
1397
1398 (js2-msg "msg.bad.ctor.return"
1399 "Construction of objects of type '%s' is not supported.")
1400
1401 (js2-msg "msg.no.overload"
1402 "Method '%s' occurs multiple times in class '%s'.")
1403
1404 (js2-msg "msg.method.not.found"
1405 "Method '%s' not found in '%s'.")
1406
1407 ;; IRFactory
1408
1409 (js2-msg "msg.bad.for.in.lhs"
1410 "Invalid left-hand side of for..in loop.")
1411
1412 (js2-msg "msg.mult.index"
1413 "Only one variable allowed in for..in loop.")
1414
1415 (js2-msg "msg.bad.for.in.destruct"
1416 "Left hand side of for..in loop must be an array of "
1417 "length 2 to accept key/value pair.")
1418
1419 (js2-msg "msg.cant.convert"
1420 "Can't convert to type '%s'.")
1421
1422 (js2-msg "msg.bad.assign.left"
1423 "Invalid assignment left-hand side.")
1424
1425 (js2-msg "msg.bad.decr"
1426 "Invalid decerement operand.")
1427
1428 (js2-msg "msg.bad.incr"
1429 "Invalid increment operand.")
1430
1431 (js2-msg "msg.bad.yield"
1432 "yield must be in a function.")
1433
1434 (js2-msg "msg.yield.parenthesized"
1435 "yield expression must be parenthesized.")
1436
1437 ;; NativeGlobal
1438 (js2-msg "msg.cant.call.indirect"
1439 "Function '%s' must be called directly, and not by way of a "
1440 "function of another name.")
1441
1442 (js2-msg "msg.eval.nonstring"
1443 "Calling eval() with anything other than a primitive "
1444 "string value will simply return the value. "
1445 "Is this what you intended?")
1446
1447 (js2-msg "msg.eval.nonstring.strict"
1448 "Calling eval() with anything other than a primitive "
1449 "string value is not allowed in strict mode.")
1450
1451 (js2-msg "msg.bad.destruct.op"
1452 "Invalid destructuring assignment operator")
1453
1454 ;; NativeCall
1455 (js2-msg "msg.only.from.new"
1456 "'%s' may only be invoked from a `new' expression.")
1457
1458 (js2-msg "msg.deprec.ctor"
1459 "The '%s' constructor is deprecated.")
1460
1461 ;; NativeFunction
1462 (js2-msg "msg.no.function.ref.found"
1463 "no source found to decompile function reference %s")
1464
1465 (js2-msg "msg.arg.isnt.array"
1466 "second argument to Function.prototype.apply must be an array")
1467
1468 ;; NativeGlobal
1469 (js2-msg "msg.bad.esc.mask"
1470 "invalid string escape mask")
1471
1472 ;; NativeRegExp
1473 (js2-msg "msg.bad.quant"
1474 "Invalid quantifier %s")
1475
1476 (js2-msg "msg.overlarge.backref"
1477 "Overly large back reference %s")
1478
1479 (js2-msg "msg.overlarge.min"
1480 "Overly large minimum %s")
1481
1482 (js2-msg "msg.overlarge.max"
1483 "Overly large maximum %s")
1484
1485 (js2-msg "msg.zero.quant"
1486 "Zero quantifier %s")
1487
1488 (js2-msg "msg.max.lt.min"
1489 "Maximum %s less than minimum")
1490
1491 (js2-msg "msg.unterm.quant"
1492 "Unterminated quantifier %s")
1493
1494 (js2-msg "msg.unterm.paren"
1495 "Unterminated parenthetical %s")
1496
1497 (js2-msg "msg.unterm.class"
1498 "Unterminated character class %s")
1499
1500 (js2-msg "msg.bad.range"
1501 "Invalid range in character class.")
1502
1503 (js2-msg "msg.trail.backslash"
1504 "Trailing \\ in regular expression.")
1505
1506 (js2-msg "msg.re.unmatched.right.paren"
1507 "unmatched ) in regular expression.")
1508
1509 (js2-msg "msg.no.regexp"
1510 "Regular expressions are not available.")
1511
1512 (js2-msg "msg.bad.backref"
1513 "back-reference exceeds number of capturing parentheses.")
1514
1515 (js2-msg "msg.bad.regexp.compile"
1516 "Only one argument may be specified if the first "
1517 "argument to RegExp.prototype.compile is a RegExp object.")
1518
1519 ;; Parser
1520 (js2-msg "msg.got.syntax.errors"
1521 "Compilation produced %s syntax errors.")
1522
1523 (js2-msg "msg.var.redecl"
1524 "TypeError: redeclaration of var %s.")
1525
1526 (js2-msg "msg.const.redecl"
1527 "TypeError: redeclaration of const %s.")
1528
1529 (js2-msg "msg.let.redecl"
1530 "TypeError: redeclaration of variable %s.")
1531
1532 (js2-msg "msg.parm.redecl"
1533 "TypeError: redeclaration of formal parameter %s.")
1534
1535 (js2-msg "msg.fn.redecl"
1536 "TypeError: redeclaration of function %s.")
1537
1538 (js2-msg "msg.let.decl.not.in.block"
1539 "SyntaxError: let declaration not directly within block")
1540
1541 ;; NodeTransformer
1542 (js2-msg "msg.dup.label"
1543 "duplicated label")
1544
1545 (js2-msg "msg.undef.label"
1546 "undefined label")
1547
1548 (js2-msg "msg.bad.break"
1549 "unlabelled break must be inside loop or switch")
1550
1551 (js2-msg "msg.continue.outside"
1552 "continue must be inside loop")
1553
1554 (js2-msg "msg.continue.nonloop"
1555 "continue can only use labels of iteration statements")
1556
1557 (js2-msg "msg.bad.throw.eol"
1558 "Line terminator is not allowed between the throw "
1559 "keyword and throw expression.")
1560
1561 (js2-msg "msg.no.paren.parms"
1562 "missing ( before function parameters.")
1563
1564 (js2-msg "msg.no.parm"
1565 "missing formal parameter")
1566
1567 (js2-msg "msg.no.paren.after.parms"
1568 "missing ) after formal parameters")
1569
1570 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1571 "parameter without default follows parameter with default")
1572
1573 (js2-msg "msg.param.after.rest" ; added by js2-mode
1574 "parameter after rest parameter")
1575
1576 (js2-msg "msg.no.brace.body"
1577 "missing '{' before function body")
1578
1579 (js2-msg "msg.no.brace.after.body"
1580 "missing } after function body")
1581
1582 (js2-msg "msg.no.paren.cond"
1583 "missing ( before condition")
1584
1585 (js2-msg "msg.no.paren.after.cond"
1586 "missing ) after condition")
1587
1588 (js2-msg "msg.no.semi.stmt"
1589 "missing ; before statement")
1590
1591 (js2-msg "msg.missing.semi"
1592 "missing ; after statement")
1593
1594 (js2-msg "msg.no.name.after.dot"
1595 "missing name after . operator")
1596
1597 (js2-msg "msg.no.name.after.coloncolon"
1598 "missing name after :: operator")
1599
1600 (js2-msg "msg.no.name.after.dotdot"
1601 "missing name after .. operator")
1602
1603 (js2-msg "msg.no.name.after.xmlAttr"
1604 "missing name after .@")
1605
1606 (js2-msg "msg.no.bracket.index"
1607 "missing ] in index expression")
1608
1609 (js2-msg "msg.no.paren.switch"
1610 "missing ( before switch expression")
1611
1612 (js2-msg "msg.no.paren.after.switch"
1613 "missing ) after switch expression")
1614
1615 (js2-msg "msg.no.brace.switch"
1616 "missing '{' before switch body")
1617
1618 (js2-msg "msg.bad.switch"
1619 "invalid switch statement")
1620
1621 (js2-msg "msg.no.colon.case"
1622 "missing : after case expression")
1623
1624 (js2-msg "msg.double.switch.default"
1625 "double default label in the switch statement")
1626
1627 (js2-msg "msg.no.while.do"
1628 "missing while after do-loop body")
1629
1630 (js2-msg "msg.no.paren.for"
1631 "missing ( after for")
1632
1633 (js2-msg "msg.no.semi.for"
1634 "missing ; after for-loop initializer")
1635
1636 (js2-msg "msg.no.semi.for.cond"
1637 "missing ; after for-loop condition")
1638
1639 (js2-msg "msg.in.after.for.name"
1640 "missing in or of after for")
1641
1642 (js2-msg "msg.no.paren.for.ctrl"
1643 "missing ) after for-loop control")
1644
1645 (js2-msg "msg.no.paren.with"
1646 "missing ( before with-statement object")
1647
1648 (js2-msg "msg.no.paren.after.with"
1649 "missing ) after with-statement object")
1650
1651 (js2-msg "msg.no.paren.after.let"
1652 "missing ( after let")
1653
1654 (js2-msg "msg.no.paren.let"
1655 "missing ) after variable list")
1656
1657 (js2-msg "msg.no.curly.let"
1658 "missing } after let statement")
1659
1660 (js2-msg "msg.bad.return"
1661 "invalid return")
1662
1663 (js2-msg "msg.no.brace.block"
1664 "missing } in compound statement")
1665
1666 (js2-msg "msg.bad.label"
1667 "invalid label")
1668
1669 (js2-msg "msg.bad.var"
1670 "missing variable name")
1671
1672 (js2-msg "msg.bad.var.init"
1673 "invalid variable initialization")
1674
1675 (js2-msg "msg.no.colon.cond"
1676 "missing : in conditional expression")
1677
1678 (js2-msg "msg.no.paren.arg"
1679 "missing ) after argument list")
1680
1681 (js2-msg "msg.no.bracket.arg"
1682 "missing ] after element list")
1683
1684 (js2-msg "msg.bad.prop"
1685 "invalid property id")
1686
1687 (js2-msg "msg.no.colon.prop"
1688 "missing : after property id")
1689
1690 (js2-msg "msg.no.brace.prop"
1691 "missing } after property list")
1692
1693 (js2-msg "msg.no.paren"
1694 "missing ) in parenthetical")
1695
1696 (js2-msg "msg.reserved.id"
1697 "identifier is a reserved word")
1698
1699 (js2-msg "msg.no.paren.catch"
1700 "missing ( before catch-block condition")
1701
1702 (js2-msg "msg.bad.catchcond"
1703 "invalid catch block condition")
1704
1705 (js2-msg "msg.catch.unreachable"
1706 "any catch clauses following an unqualified catch are unreachable")
1707
1708 (js2-msg "msg.no.brace.try"
1709 "missing '{' before try block")
1710
1711 (js2-msg "msg.no.brace.catchblock"
1712 "missing '{' before catch-block body")
1713
1714 (js2-msg "msg.try.no.catchfinally"
1715 "'try' without 'catch' or 'finally'")
1716
1717 (js2-msg "msg.no.return.value"
1718 "function %s does not always return a value")
1719
1720 (js2-msg "msg.anon.no.return.value"
1721 "anonymous function does not always return a value")
1722
1723 (js2-msg "msg.return.inconsistent"
1724 "return statement is inconsistent with previous usage")
1725
1726 (js2-msg "msg.generator.returns"
1727 "TypeError: generator function '%s' returns a value")
1728
1729 (js2-msg "msg.anon.generator.returns"
1730 "TypeError: anonymous generator function returns a value")
1731
1732 (js2-msg "msg.syntax"
1733 "syntax error")
1734
1735 (js2-msg "msg.unexpected.eof"
1736 "Unexpected end of file")
1737
1738 (js2-msg "msg.XML.bad.form"
1739 "illegally formed XML syntax")
1740
1741 (js2-msg "msg.XML.not.available"
1742 "XML runtime not available")
1743
1744 (js2-msg "msg.too.deep.parser.recursion"
1745 "Too deep recursion while parsing")
1746
1747 (js2-msg "msg.no.side.effects"
1748 "Code has no side effects")
1749
1750 (js2-msg "msg.extra.trailing.comma"
1751 "Trailing comma is not legal in an ECMA-262 object initializer")
1752
1753 (js2-msg "msg.array.trailing.comma"
1754 "Trailing comma yields different behavior across browsers")
1755
1756 (js2-msg "msg.equal.as.assign"
1757 (concat "Test for equality (==) mistyped as assignment (=)?"
1758 " (parenthesize to suppress warning)"))
1759
1760 (js2-msg "msg.var.hides.arg"
1761 "Variable %s hides argument")
1762
1763 (js2-msg "msg.destruct.assign.no.init"
1764 "Missing = in destructuring declaration")
1765
1766 ;; ScriptRuntime
1767 (js2-msg "msg.no.properties"
1768 "%s has no properties.")
1769
1770 (js2-msg "msg.invalid.iterator"
1771 "Invalid iterator value")
1772
1773 (js2-msg "msg.iterator.primitive"
1774 "__iterator__ returned a primitive value")
1775
1776 (js2-msg "msg.assn.create.strict"
1777 "Assignment to undeclared variable %s")
1778
1779 (js2-msg "msg.ref.undefined.prop"
1780 "Reference to undefined property '%s'")
1781
1782 (js2-msg "msg.prop.not.found"
1783 "Property %s not found.")
1784
1785 (js2-msg "msg.invalid.type"
1786 "Invalid JavaScript value of type %s")
1787
1788 (js2-msg "msg.primitive.expected"
1789 "Primitive type expected (had %s instead)")
1790
1791 (js2-msg "msg.namespace.expected"
1792 "Namespace object expected to left of :: (found %s instead)")
1793
1794 (js2-msg "msg.null.to.object"
1795 "Cannot convert null to an object.")
1796
1797 (js2-msg "msg.undef.to.object"
1798 "Cannot convert undefined to an object.")
1799
1800 (js2-msg "msg.cyclic.value"
1801 "Cyclic %s value not allowed.")
1802
1803 (js2-msg "msg.is.not.defined"
1804 "'%s' is not defined.")
1805
1806 (js2-msg "msg.undef.prop.read"
1807 "Cannot read property '%s' from %s")
1808
1809 (js2-msg "msg.undef.prop.write"
1810 "Cannot set property '%s' of %s to '%s'")
1811
1812 (js2-msg "msg.undef.prop.delete"
1813 "Cannot delete property '%s' of %s")
1814
1815 (js2-msg "msg.undef.method.call"
1816 "Cannot call method '%s' of %s")
1817
1818 (js2-msg "msg.undef.with"
1819 "Cannot apply 'with' to %s")
1820
1821 (js2-msg "msg.isnt.function"
1822 "%s is not a function, it is %s.")
1823
1824 (js2-msg "msg.isnt.function.in"
1825 "Cannot call property %s in object %s. "
1826 "It is not a function, it is '%s'.")
1827
1828 (js2-msg "msg.function.not.found"
1829 "Cannot find function %s.")
1830
1831 (js2-msg "msg.function.not.found.in"
1832 "Cannot find function %s in object %s.")
1833
1834 (js2-msg "msg.isnt.xml.object"
1835 "%s is not an xml object.")
1836
1837 (js2-msg "msg.no.ref.to.get"
1838 "%s is not a reference to read reference value.")
1839
1840 (js2-msg "msg.no.ref.to.set"
1841 "%s is not a reference to set reference value to %s.")
1842
1843 (js2-msg "msg.no.ref.from.function"
1844 "Function %s can not be used as the left-hand "
1845 "side of assignment or as an operand of ++ or -- operator.")
1846
1847 (js2-msg "msg.bad.default.value"
1848 "Object's getDefaultValue() method returned an object.")
1849
1850 (js2-msg "msg.instanceof.not.object"
1851 "Can't use instanceof on a non-object.")
1852
1853 (js2-msg "msg.instanceof.bad.prototype"
1854 "'prototype' property of %s is not an object.")
1855
1856 (js2-msg "msg.bad.radix"
1857 "illegal radix %s.")
1858
1859 ;; ScriptableObject
1860 (js2-msg "msg.default.value"
1861 "Cannot find default value for object.")
1862
1863 (js2-msg "msg.zero.arg.ctor"
1864 "Cannot load class '%s' which has no zero-parameter constructor.")
1865
1866 (js2-msg "msg.ctor.multiple.parms"
1867 "Can't define constructor or class %s since more than "
1868 "one constructor has multiple parameters.")
1869
1870 (js2-msg "msg.extend.scriptable"
1871 "%s must extend ScriptableObject in order to define property %s.")
1872
1873 (js2-msg "msg.bad.getter.parms"
1874 "In order to define a property, getter %s must have zero "
1875 "parameters or a single ScriptableObject parameter.")
1876
1877 (js2-msg "msg.obj.getter.parms"
1878 "Expected static or delegated getter %s to take "
1879 "a ScriptableObject parameter.")
1880
1881 (js2-msg "msg.getter.static"
1882 "Getter and setter must both be static or neither be static.")
1883
1884 (js2-msg "msg.setter.return"
1885 "Setter must have void return type: %s")
1886
1887 (js2-msg "msg.setter2.parms"
1888 "Two-parameter setter must take a ScriptableObject as "
1889 "its first parameter.")
1890
1891 (js2-msg "msg.setter1.parms"
1892 "Expected single parameter setter for %s")
1893
1894 (js2-msg "msg.setter2.expected"
1895 "Expected static or delegated setter %s to take two parameters.")
1896
1897 (js2-msg "msg.setter.parms"
1898 "Expected either one or two parameters for setter.")
1899
1900 (js2-msg "msg.setter.bad.type"
1901 "Unsupported parameter type '%s' in setter '%s'.")
1902
1903 (js2-msg "msg.add.sealed"
1904 "Cannot add a property to a sealed object: %s.")
1905
1906 (js2-msg "msg.remove.sealed"
1907 "Cannot remove a property from a sealed object: %s.")
1908
1909 (js2-msg "msg.modify.sealed"
1910 "Cannot modify a property of a sealed object: %s.")
1911
1912 (js2-msg "msg.modify.readonly"
1913 "Cannot modify readonly property: %s.")
1914
1915 ;; TokenStream
1916 (js2-msg "msg.missing.exponent"
1917 "missing exponent")
1918
1919 (js2-msg "msg.caught.nfe"
1920 "number format error")
1921
1922 (js2-msg "msg.unterminated.string.lit"
1923 "unterminated string literal")
1924
1925 (js2-msg "msg.unterminated.comment"
1926 "unterminated comment")
1927
1928 (js2-msg "msg.unterminated.re.lit"
1929 "unterminated regular expression literal")
1930
1931 (js2-msg "msg.invalid.re.flag"
1932 "invalid flag after regular expression")
1933
1934 (js2-msg "msg.no.re.input.for"
1935 "no input for %s")
1936
1937 (js2-msg "msg.illegal.character"
1938 "illegal character")
1939
1940 (js2-msg "msg.invalid.escape"
1941 "invalid Unicode escape sequence")
1942
1943 (js2-msg "msg.bad.namespace"
1944 "not a valid default namespace statement. "
1945 "Syntax is: default xml namespace = EXPRESSION;")
1946
1947 ;; TokensStream warnings
1948 (js2-msg "msg.bad.octal.literal"
1949 "illegal octal literal digit %s; "
1950 "interpreting it as a decimal digit")
1951
1952 (js2-msg "msg.reserved.keyword"
1953 "illegal usage of future reserved keyword %s; "
1954 "interpreting it as ordinary identifier")
1955
1956 (js2-msg "msg.script.is.not.constructor"
1957 "Script objects are not constructors.")
1958
1959 ;; Arrays
1960 (js2-msg "msg.arraylength.bad"
1961 "Inappropriate array length.")
1962
1963 ;; Arrays
1964 (js2-msg "msg.arraylength.too.big"
1965 "Array length %s exceeds supported capacity limit.")
1966
1967 ;; URI
1968 (js2-msg "msg.bad.uri"
1969 "Malformed URI sequence.")
1970
1971 ;; Number
1972 (js2-msg "msg.bad.precision"
1973 "Precision %s out of range.")
1974
1975 ;; NativeGenerator
1976 (js2-msg "msg.send.newborn"
1977 "Attempt to send value to newborn generator")
1978
1979 (js2-msg "msg.already.exec.gen"
1980 "Already executing generator")
1981
1982 (js2-msg "msg.StopIteration.invalid"
1983 "StopIteration may not be changed to an arbitrary object.")
1984
1985 ;; Interpreter
1986 (js2-msg "msg.yield.closing"
1987 "Yield from closing generator")
1988
1989 ;;; Utilities
1990
1991 (defun js2-delete-if (predicate list)
1992 "Remove all items satisfying PREDICATE in LIST."
1993 (loop for item in list
1994 if (not (funcall predicate item))
1995 collect item))
1996
1997 (defun js2-position (element list)
1998 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1999 Returns nil if element is not found in the list."
2000 (let ((count 0)
2001 found)
2002 (while (and list (not found))
2003 (if (eq element (car list))
2004 (setq found t)
2005 (setq count (1+ count)
2006 list (cdr list))))
2007 (if found count)))
2008
2009 (defun js2-find-if (predicate list)
2010 "Find first item satisfying PREDICATE in LIST."
2011 (let (result)
2012 (while (and list (not result))
2013 (if (funcall predicate (car list))
2014 (setq result (car list)))
2015 (setq list (cdr list)))
2016 result))
2017
2018 (defmacro js2-time (form)
2019 "Evaluate FORM, discard result, and return elapsed time in sec"
2020 (declare (debug t))
2021 (let ((beg (make-symbol "--js2-time-beg--"))
2022 (delta (make-symbol "--js2-time-end--")))
2023 `(let ((,beg (current-time))
2024 ,delta)
2025 ,form
2026 (/ (truncate (* (- (float-time (current-time))
2027 (float-time ,beg))
2028 10000))
2029 10000.0))))
2030
2031 (defsubst js2-same-line (pos)
2032 "Return t if POS is on the same line as current point."
2033 (and (>= pos (point-at-bol))
2034 (<= pos (point-at-eol))))
2035
2036 (defsubst js2-same-line-2 (p1 p2)
2037 "Return t if p1 is on the same line as p2."
2038 (save-excursion
2039 (goto-char p1)
2040 (js2-same-line p2)))
2041
2042 (defun js2-code-bug ()
2043 "Signal an error when we encounter an unexpected code path."
2044 (error "failed assertion"))
2045
2046 (defsubst js2-record-text-property (beg end prop value)
2047 "Record a text property to set when parsing finishes."
2048 (push (list beg end prop value) js2-mode-deferred-properties))
2049
2050 ;; I'd like to associate errors with nodes, but for now the
2051 ;; easiest thing to do is get the context info from the last token.
2052 (defsubst js2-record-parse-error (msg &optional arg pos len)
2053 (push (list (list msg arg)
2054 (or pos js2-token-beg)
2055 (or len (- js2-token-end js2-token-beg)))
2056 js2-parsed-errors))
2057
2058 (defsubst js2-report-error (msg &optional msg-arg pos len)
2059 "Signal a syntax error or record a parse error."
2060 (if js2-recover-from-parse-errors
2061 (js2-record-parse-error msg msg-arg pos len)
2062 (signal 'js2-syntax-error
2063 (list msg
2064 js2-ts-lineno
2065 (save-excursion
2066 (goto-char js2-ts-cursor)
2067 (current-column))
2068 js2-ts-hit-eof))))
2069
2070 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2071 (if js2-compiler-report-warning-as-error
2072 (js2-report-error msg msg-arg pos len)
2073 (push (list (list msg msg-arg)
2074 (or pos js2-token-beg)
2075 (or len (- js2-token-end js2-token-beg)))
2076 js2-parsed-warnings)))
2077
2078 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2079 (if js2-compiler-strict-mode
2080 (js2-report-warning msg-id msg-arg beg
2081 (and beg end (- end beg)))))
2082
2083 (put 'js2-syntax-error 'error-conditions
2084 '(error syntax-error js2-syntax-error))
2085 (put 'js2-syntax-error 'error-message "Syntax error")
2086
2087 (put 'js2-parse-error 'error-conditions
2088 '(error parse-error js2-parse-error))
2089 (put 'js2-parse-error 'error-message "Parse error")
2090
2091 (defmacro js2-clear-flag (flags flag)
2092 `(setq ,flags (logand ,flags (lognot ,flag))))
2093
2094 (defmacro js2-set-flag (flags flag)
2095 "Logical-or FLAG into FLAGS."
2096 `(setq ,flags (logior ,flags ,flag)))
2097
2098 (defsubst js2-flag-set-p (flags flag)
2099 (/= 0 (logand flags flag)))
2100
2101 (defsubst js2-flag-not-set-p (flags flag)
2102 (zerop (logand flags flag)))
2103
2104 ;; Stolen shamelessly from James Clark's nxml-mode.
2105 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2106 "Evaluate BODY without any text property changes modifying the buffer.
2107 Any text properties changes happen as usual but the changes are not treated as
2108 modifications to the buffer."
2109 (declare (indent 0) (debug t))
2110 (let ((modified (make-symbol "modified")))
2111 `(let ((,modified (buffer-modified-p))
2112 (inhibit-read-only t)
2113 (inhibit-modification-hooks t)
2114 (buffer-undo-list t)
2115 (deactivate-mark nil)
2116 ;; Apparently these avoid file locking problems.
2117 (buffer-file-name nil)
2118 (buffer-file-truename nil))
2119 (unwind-protect
2120 (progn ,@body)
2121 (unless ,modified
2122 (restore-buffer-modified-p nil))))))
2123
2124 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2125 "Evaluate BODY with the _ character set to be word-syntax."
2126 (declare (indent 0) (debug t))
2127 (let ((old-syntax (make-symbol "old-syntax")))
2128 `(let ((,old-syntax (string (char-syntax ?_))))
2129 (unwind-protect
2130 (progn
2131 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2132 ,@body)
2133 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2134
2135 (defsubst js2-char-uppercase-p (c)
2136 "Return t if C is an uppercase character.
2137 Handles unicode and latin chars properly."
2138 (/= c (downcase c)))
2139
2140 (defsubst js2-char-lowercase-p (c)
2141 "Return t if C is an uppercase character.
2142 Handles unicode and latin chars properly."
2143 (/= c (upcase c)))
2144
2145 ;;; AST struct and function definitions
2146
2147 ;; flags for ast node property 'member-type (used for e4x operators)
2148 (defvar js2-property-flag #x1 "property access: element is valid name")
2149 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2150 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2151
2152 (defsubst js2-relpos (pos anchor)
2153 "Convert POS to be relative to ANCHOR.
2154 If POS is nil, returns nil."
2155 (and pos (- pos anchor)))
2156
2157 (defsubst js2-make-pad (indent)
2158 (if (zerop indent)
2159 ""
2160 (make-string (* indent js2-basic-offset) ? )))
2161
2162 (defsubst js2-visit-ast (node callback)
2163 "Visit every node in ast NODE with visitor CALLBACK.
2164
2165 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2166 called twice: once to visit the node, and again after all the node's
2167 children have been processed. The END-P argument is nil on the first
2168 call and non-nil on the second call. The return value of the callback
2169 affects the traversal: if non-nil, the children of NODE are processed.
2170 If the callback returns nil, or if the node has no children, then the
2171 callback is called immediately with a non-nil END-P argument.
2172
2173 The node traversal is approximately lexical-order, although there
2174 are currently no guarantees around this."
2175 (if node
2176 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2177 ;; visit the node
2178 (when (funcall callback node nil)
2179 ;; visit the kids
2180 (cond
2181 ((eq vfunc 'js2-visit-none)
2182 nil) ; don't even bother calling it
2183 ;; Each AST node type has to define a `js2-visitor' function
2184 ;; that takes a node and a callback, and calls `js2-visit-ast'
2185 ;; on each child of the node.
2186 (vfunc
2187 (funcall vfunc node callback))
2188 (t
2189 (error "%s does not define a visitor-traversal function"
2190 (aref node 0)))))
2191 ;; call the end-visit
2192 (funcall callback node t))))
2193
2194 (defstruct (js2-node
2195 (:constructor nil)) ; abstract
2196 "Base AST node type."
2197 (type -1) ; token type
2198 (pos -1) ; start position of this AST node in parsed input
2199 (len 1) ; num characters spanned by the node
2200 props ; optional node property list (an alist)
2201 parent) ; link to parent node; null for root
2202
2203 (defsubst js2-node-get-prop (node prop &optional default)
2204 (or (cadr (assoc prop (js2-node-props node))) default))
2205
2206 (defsubst js2-node-set-prop (node prop value)
2207 (setf (js2-node-props node)
2208 (cons (list prop value) (js2-node-props node))))
2209
2210 (defsubst js2-fixup-starts (n nodes)
2211 "Adjust the start positions of NODES to be relative to N.
2212 Any node in the list may be nil, for convenience."
2213 (dolist (node nodes)
2214 (when node
2215 (setf (js2-node-pos node) (- (js2-node-pos node)
2216 (js2-node-pos n))))))
2217
2218 (defsubst js2-node-add-children (parent &rest nodes)
2219 "Set parent node of NODES to PARENT, and return PARENT.
2220 Does nothing if we're not recording parent links.
2221 If any given node in NODES is nil, doesn't record that link."
2222 (js2-fixup-starts parent nodes)
2223 (dolist (node nodes)
2224 (and node
2225 (setf (js2-node-parent node) parent))))
2226
2227 ;; Non-recursive since it's called a frightening number of times.
2228 (defsubst js2-node-abs-pos (n)
2229 (let ((pos (js2-node-pos n)))
2230 (while (setq n (js2-node-parent n))
2231 (setq pos (+ pos (js2-node-pos n))))
2232 pos))
2233
2234 (defsubst js2-node-abs-end (n)
2235 "Return absolute buffer position of end of N."
2236 (+ (js2-node-abs-pos n) (js2-node-len n)))
2237
2238 ;; It's important to make sure block nodes have a lisp list for the
2239 ;; child nodes, to limit printing recursion depth in an AST that
2240 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2241 ;; a sufficiently large vector tree.
2242
2243 (defstruct (js2-block-node
2244 (:include js2-node)
2245 (:constructor nil)
2246 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2247 (pos js2-token-beg)
2248 len
2249 props
2250 kids)))
2251 "A block of statements."
2252 kids) ; a lisp list of the child statement nodes
2253
2254 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2255 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2256
2257 (defsubst js2-visit-block (ast callback)
2258 "Visit the `js2-block-node' children of AST."
2259 (dolist (kid (js2-block-node-kids ast))
2260 (js2-visit-ast kid callback)))
2261
2262 (defun js2-print-block (n i)
2263 (let ((pad (js2-make-pad i)))
2264 (insert pad "{\n")
2265 (dolist (kid (js2-block-node-kids n))
2266 (js2-print-ast kid (1+ i)))
2267 (insert pad "}")))
2268
2269 (defstruct (js2-scope
2270 (:include js2-block-node)
2271 (:constructor nil)
2272 (:constructor make-js2-scope (&key (type js2-BLOCK)
2273 (pos js2-token-beg)
2274 len
2275 kids)))
2276 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2277 ;; I don't have one of those handy, so I'll use an alist for now.
2278 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2279 ;; and is much lighter-weight to construct (both CPU and mem).
2280 ;; The keys are interned strings (symbols) for faster lookup.
2281 ;; Should switch to hybrid alist/hashtable eventually.
2282 symbol-table ; an alist of (symbol . js2-symbol)
2283 parent-scope ; a `js2-scope'
2284 top) ; top-level `js2-scope' (script/function)
2285
2286 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2287 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2288
2289 (defun js2-scope-set-parent-scope (scope parent)
2290 (setf (js2-scope-parent-scope scope) parent
2291 (js2-scope-top scope) (if (null parent)
2292 scope
2293 (js2-scope-top parent))))
2294
2295 (defun js2-node-get-enclosing-scope (node)
2296 "Return the innermost `js2-scope' node surrounding NODE.
2297 Returns nil if there is no enclosing scope node."
2298 (let ((parent (js2-node-parent node)))
2299 (while (not (js2-scope-p parent))
2300 (setq parent (js2-node-parent parent)))
2301 parent))
2302
2303 (defun js2-get-defining-scope (scope name)
2304 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2305 Returns `js2-scope' in which NAME is defined, or nil if not found."
2306 (let ((sym (if (symbolp name)
2307 name
2308 (intern name)))
2309 table
2310 result
2311 (continue t))
2312 (while (and scope continue)
2313 (if (and (setq table (js2-scope-symbol-table scope))
2314 (assq sym table))
2315 (setq continue nil
2316 result scope)
2317 (setq scope (js2-scope-parent-scope scope))))
2318 result))
2319
2320 (defsubst js2-scope-get-symbol (scope name)
2321 "Return symbol table entry for NAME in SCOPE.
2322 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2323 (and (js2-scope-symbol-table scope)
2324 (cdr (assq (if (symbolp name)
2325 name
2326 (intern name))
2327 (js2-scope-symbol-table scope)))))
2328
2329 (defsubst js2-scope-put-symbol (scope name symbol)
2330 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2331 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2332 (let* ((table (js2-scope-symbol-table scope))
2333 (sym (if (symbolp name) name (intern name)))
2334 (entry (assq sym table)))
2335 (if entry
2336 (setcdr entry symbol)
2337 (push (cons sym symbol)
2338 (js2-scope-symbol-table scope)))))
2339
2340 (defstruct (js2-symbol
2341 (:constructor nil)
2342 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2343 "A symbol table entry."
2344 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2345 ;; js2-LET, or js2-CONST
2346 decl-type
2347 name ; string
2348 ast-node) ; a `js2-node'
2349
2350 (defstruct (js2-error-node
2351 (:include js2-node)
2352 (:constructor nil) ; silence emacs21 byte-compiler
2353 (:constructor make-js2-error-node (&key (type js2-ERROR)
2354 (pos js2-token-beg)
2355 len)))
2356 "AST node representing a parse error.")
2357
2358 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2359 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2360
2361 (defstruct (js2-script-node
2362 (:include js2-scope)
2363 (:constructor nil)
2364 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2365 (pos js2-token-beg)
2366 len
2367 var-decls
2368 fun-decls)))
2369 functions ; lisp list of nested functions
2370 regexps ; lisp list of (string . flags)
2371 symbols ; alist (every symbol gets unique index)
2372 (param-count 0)
2373 var-names ; vector of string names
2374 consts ; bool-vector matching var-decls
2375 (temp-number 0)) ; for generating temp variables
2376
2377 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2378 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2379
2380 (defun js2-print-script (node indent)
2381 (dolist (kid (js2-block-node-kids node))
2382 (js2-print-ast kid indent)))
2383
2384 (defstruct (js2-ast-root
2385 (:include js2-script-node)
2386 (:constructor nil)
2387 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2388 (pos js2-token-beg)
2389 len
2390 buffer)))
2391 "The root node of a js2 AST."
2392 buffer ; the source buffer from which the code was parsed
2393 comments ; a lisp list of comments, ordered by start position
2394 errors ; a lisp list of errors found during parsing
2395 warnings ; a lisp list of warnings found during parsing
2396 node-count) ; number of nodes in the tree, including the root
2397
2398 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2399 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2400
2401 (defun js2-visit-ast-root (ast callback)
2402 (dolist (kid (js2-ast-root-kids ast))
2403 (js2-visit-ast kid callback))
2404 (dolist (comment (js2-ast-root-comments ast))
2405 (js2-visit-ast comment callback)))
2406
2407 (defstruct (js2-comment-node
2408 (:include js2-node)
2409 (:constructor nil)
2410 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2411 (pos js2-token-beg)
2412 len
2413 (format js2-ts-comment-type))))
2414 format) ; 'line, 'block, 'jsdoc or 'html
2415
2416 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2417 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2418
2419 (defun js2-print-comment (n i)
2420 ;; We really ought to link end-of-line comments to their nodes.
2421 ;; Or maybe we could add a new comment type, 'endline.
2422 (insert (js2-make-pad i)
2423 (js2-node-string n)))
2424
2425 (defstruct (js2-expr-stmt-node
2426 (:include js2-node)
2427 (:constructor nil)
2428 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2429 (pos js2-ts-cursor)
2430 len
2431 expr)))
2432 "An expression statement."
2433 expr)
2434
2435 (defsubst js2-expr-stmt-node-set-has-result (node)
2436 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2437 (setf (js2-node-type node) js2-EXPR_RESULT))
2438
2439 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2440 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2441
2442 (defun js2-visit-expr-stmt-node (n v)
2443 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2444
2445 (defun js2-print-expr-stmt-node (n indent)
2446 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2447 (insert ";\n"))
2448
2449 (defstruct (js2-loop-node
2450 (:include js2-scope)
2451 (:constructor nil))
2452 "Abstract supertype of loop nodes."
2453 body ; a `js2-block-node'
2454 lp ; position of left-paren, nil if omitted
2455 rp) ; position of right-paren, nil if omitted
2456
2457 (defstruct (js2-do-node
2458 (:include js2-loop-node)
2459 (:constructor nil)
2460 (:constructor make-js2-do-node (&key (type js2-DO)
2461 (pos js2-token-beg)
2462 len
2463 body
2464 condition
2465 while-pos
2466 lp
2467 rp)))
2468 "AST node for do-loop."
2469 condition ; while (expression)
2470 while-pos) ; buffer position of 'while' keyword
2471
2472 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2473 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2474
2475 (defun js2-visit-do-node (n v)
2476 (js2-visit-ast (js2-do-node-body n) v)
2477 (js2-visit-ast (js2-do-node-condition n) v))
2478
2479 (defun js2-print-do-node (n i)
2480 (let ((pad (js2-make-pad i)))
2481 (insert pad "do {\n")
2482 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2483 (js2-print-ast kid (1+ i)))
2484 (insert pad "} while (")
2485 (js2-print-ast (js2-do-node-condition n) 0)
2486 (insert ");\n")))
2487
2488 (defstruct (js2-while-node
2489 (:include js2-loop-node)
2490 (:constructor nil)
2491 (:constructor make-js2-while-node (&key (type js2-WHILE)
2492 (pos js2-token-beg)
2493 len
2494 body
2495 condition
2496 lp
2497 rp)))
2498 "AST node for while-loop."
2499 condition) ; while-condition
2500
2501 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2502 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2503
2504 (defun js2-visit-while-node (n v)
2505 (js2-visit-ast (js2-while-node-condition n) v)
2506 (js2-visit-ast (js2-while-node-body n) v))
2507
2508 (defun js2-print-while-node (n i)
2509 (let ((pad (js2-make-pad i)))
2510 (insert pad "while (")
2511 (js2-print-ast (js2-while-node-condition n) 0)
2512 (insert ") {\n")
2513 (js2-print-body (js2-while-node-body n) (1+ i))
2514 (insert pad "}\n")))
2515
2516 (defstruct (js2-for-node
2517 (:include js2-loop-node)
2518 (:constructor nil)
2519 (:constructor make-js2-for-node (&key (type js2-FOR)
2520 (pos js2-ts-cursor)
2521 len
2522 body
2523 init
2524 condition
2525 update
2526 lp
2527 rp)))
2528 "AST node for a C-style for-loop."
2529 init ; initialization expression
2530 condition ; loop condition
2531 update) ; update clause
2532
2533 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2534 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2535
2536 (defun js2-visit-for-node (n v)
2537 (js2-visit-ast (js2-for-node-init n) v)
2538 (js2-visit-ast (js2-for-node-condition n) v)
2539 (js2-visit-ast (js2-for-node-update n) v)
2540 (js2-visit-ast (js2-for-node-body n) v))
2541
2542 (defun js2-print-for-node (n i)
2543 (let ((pad (js2-make-pad i)))
2544 (insert pad "for (")
2545 (js2-print-ast (js2-for-node-init n) 0)
2546 (insert "; ")
2547 (js2-print-ast (js2-for-node-condition n) 0)
2548 (insert "; ")
2549 (js2-print-ast (js2-for-node-update n) 0)
2550 (insert ") {\n")
2551 (js2-print-body (js2-for-node-body n) (1+ i))
2552 (insert pad "}\n")))
2553
2554 (defstruct (js2-for-in-node
2555 (:include js2-loop-node)
2556 (:constructor nil)
2557 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2558 (pos js2-ts-cursor)
2559 len
2560 body
2561 iterator
2562 object
2563 in-pos
2564 each-pos
2565 foreach-p forof-p
2566 lp rp)))
2567 "AST node for a for..in loop."
2568 iterator ; [var] foo in ...
2569 object ; object over which we're iterating
2570 in-pos ; buffer position of 'in' keyword
2571 each-pos ; buffer position of 'each' keyword, if foreach-p
2572 foreach-p ; t if it's a for-each loop
2573 forof-p) ; t if it's a for-of loop
2574
2575 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2576 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2577
2578 (defun js2-visit-for-in-node (n v)
2579 (js2-visit-ast (js2-for-in-node-iterator n) v)
2580 (js2-visit-ast (js2-for-in-node-object n) v)
2581 (js2-visit-ast (js2-for-in-node-body n) v))
2582
2583 (defun js2-print-for-in-node (n i)
2584 (let ((pad (js2-make-pad i))
2585 (foreach (js2-for-in-node-foreach-p n))
2586 (forof (js2-for-in-node-forof-p n)))
2587 (insert pad "for ")
2588 (if foreach
2589 (insert "each "))
2590 (insert "(")
2591 (js2-print-ast (js2-for-in-node-iterator n) 0)
2592 (if forof
2593 (insert " of ")
2594 (insert " in "))
2595 (js2-print-ast (js2-for-in-node-object n) 0)
2596 (insert ") {\n")
2597 (js2-print-body (js2-for-in-node-body n) (1+ i))
2598 (insert pad "}\n")))
2599
2600 (defstruct (js2-return-node
2601 (:include js2-node)
2602 (:constructor nil)
2603 (:constructor make-js2-return-node (&key (type js2-RETURN)
2604 (pos js2-ts-cursor)
2605 len
2606 retval)))
2607 "AST node for a return statement."
2608 retval) ; expression to return, or 'undefined
2609
2610 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2611 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2612
2613 (defun js2-visit-return-node (n v)
2614 (js2-visit-ast (js2-return-node-retval n) v))
2615
2616 (defun js2-print-return-node (n i)
2617 (insert (js2-make-pad i) "return")
2618 (when (js2-return-node-retval n)
2619 (insert " ")
2620 (js2-print-ast (js2-return-node-retval n) 0))
2621 (insert ";\n"))
2622
2623 (defstruct (js2-if-node
2624 (:include js2-node)
2625 (:constructor nil)
2626 (:constructor make-js2-if-node (&key (type js2-IF)
2627 (pos js2-ts-cursor)
2628 len
2629 condition
2630 then-part
2631 else-pos
2632 else-part
2633 lp
2634 rp)))
2635 "AST node for an if-statement."
2636 condition ; expression
2637 then-part ; statement or block
2638 else-pos ; optional buffer position of 'else' keyword
2639 else-part ; optional statement or block
2640 lp ; position of left-paren, nil if omitted
2641 rp) ; position of right-paren, nil if omitted
2642
2643 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2644 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2645
2646 (defun js2-visit-if-node (n v)
2647 (js2-visit-ast (js2-if-node-condition n) v)
2648 (js2-visit-ast (js2-if-node-then-part n) v)
2649 (js2-visit-ast (js2-if-node-else-part n) v))
2650
2651 (defun js2-print-if-node (n i)
2652 (let ((pad (js2-make-pad i))
2653 (then-part (js2-if-node-then-part n))
2654 (else-part (js2-if-node-else-part n)))
2655 (insert pad "if (")
2656 (js2-print-ast (js2-if-node-condition n) 0)
2657 (insert ") {\n")
2658 (js2-print-body then-part (1+ i))
2659 (insert pad "}")
2660 (cond
2661 ((not else-part)
2662 (insert "\n"))
2663 ((js2-if-node-p else-part)
2664 (insert " else ")
2665 (js2-print-body else-part i))
2666 (t
2667 (insert " else {\n")
2668 (js2-print-body else-part (1+ i))
2669 (insert pad "}\n")))))
2670
2671 (defstruct (js2-try-node
2672 (:include js2-node)
2673 (:constructor nil)
2674 (:constructor make-js2-try-node (&key (type js2-TRY)
2675 (pos js2-ts-cursor)
2676 len
2677 try-block
2678 catch-clauses
2679 finally-block)))
2680 "AST node for a try-statement."
2681 try-block
2682 catch-clauses ; a lisp list of `js2-catch-node'
2683 finally-block) ; a `js2-finally-node'
2684
2685 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2686 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2687
2688 (defun js2-visit-try-node (n v)
2689 (js2-visit-ast (js2-try-node-try-block n) v)
2690 (dolist (clause (js2-try-node-catch-clauses n))
2691 (js2-visit-ast clause v))
2692 (js2-visit-ast (js2-try-node-finally-block n) v))
2693
2694 (defun js2-print-try-node (n i)
2695 (let ((pad (js2-make-pad i))
2696 (catches (js2-try-node-catch-clauses n))
2697 (finally (js2-try-node-finally-block n)))
2698 (insert pad "try {\n")
2699 (js2-print-body (js2-try-node-try-block n) (1+ i))
2700 (insert pad "}")
2701 (when catches
2702 (dolist (catch catches)
2703 (js2-print-ast catch i)))
2704 (if finally
2705 (js2-print-ast finally i)
2706 (insert "\n"))))
2707
2708 (defstruct (js2-catch-node
2709 (:include js2-node)
2710 (:constructor nil)
2711 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2712 (pos js2-ts-cursor)
2713 len
2714 param
2715 guard-kwd
2716 guard-expr
2717 block
2718 lp
2719 rp)))
2720 "AST node for a catch clause."
2721 param ; destructuring form or simple name node
2722 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2723 guard-expr ; catch condition, a `js2-node'
2724 block ; statements, a `js2-block-node'
2725 lp ; buffer position of left-paren, nil if omitted
2726 rp) ; buffer position of right-paren, nil if omitted
2727
2728 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2729 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2730
2731 (defun js2-visit-catch-node (n v)
2732 (js2-visit-ast (js2-catch-node-param n) v)
2733 (when (js2-catch-node-guard-kwd n)
2734 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2735 (js2-visit-ast (js2-catch-node-block n) v))
2736
2737 (defun js2-print-catch-node (n i)
2738 (let ((pad (js2-make-pad i))
2739 (guard-kwd (js2-catch-node-guard-kwd n))
2740 (guard-expr (js2-catch-node-guard-expr n)))
2741 (insert " catch (")
2742 (js2-print-ast (js2-catch-node-param n) 0)
2743 (when guard-kwd
2744 (insert " if ")
2745 (js2-print-ast guard-expr 0))
2746 (insert ") {\n")
2747 (js2-print-body (js2-catch-node-block n) (1+ i))
2748 (insert pad "}")))
2749
2750 (defstruct (js2-finally-node
2751 (:include js2-node)
2752 (:constructor nil)
2753 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2754 (pos js2-ts-cursor)
2755 len
2756 body)))
2757 "AST node for a finally clause."
2758 body) ; a `js2-node', often but not always a block node
2759
2760 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2761 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2762
2763 (defun js2-visit-finally-node (n v)
2764 (js2-visit-ast (js2-finally-node-body n) v))
2765
2766 (defun js2-print-finally-node (n i)
2767 (let ((pad (js2-make-pad i)))
2768 (insert " finally {\n")
2769 (js2-print-body (js2-finally-node-body n) (1+ i))
2770 (insert pad "}\n")))
2771
2772 (defstruct (js2-switch-node
2773 (:include js2-node)
2774 (:constructor nil)
2775 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2776 (pos js2-ts-cursor)
2777 len
2778 discriminant
2779 cases
2780 lp
2781 rp)))
2782 "AST node for a switch statement."
2783 discriminant ; a `js2-node' (switch expression)
2784 cases ; a lisp list of `js2-case-node'
2785 lp ; position of open-paren for discriminant, nil if omitted
2786 rp) ; position of close-paren for discriminant, nil if omitted
2787
2788 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2789 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2790
2791 (defun js2-visit-switch-node (n v)
2792 (js2-visit-ast (js2-switch-node-discriminant n) v)
2793 (dolist (c (js2-switch-node-cases n))
2794 (js2-visit-ast c v)))
2795
2796 (defun js2-print-switch-node (n i)
2797 (let ((pad (js2-make-pad i))
2798 (cases (js2-switch-node-cases n)))
2799 (insert pad "switch (")
2800 (js2-print-ast (js2-switch-node-discriminant n) 0)
2801 (insert ") {\n")
2802 (dolist (case cases)
2803 (js2-print-ast case i))
2804 (insert pad "}\n")))
2805
2806 (defstruct (js2-case-node
2807 (:include js2-block-node)
2808 (:constructor nil)
2809 (:constructor make-js2-case-node (&key (type js2-CASE)
2810 (pos js2-ts-cursor)
2811 len
2812 kids
2813 expr)))
2814 "AST node for a case clause of a switch statement."
2815 expr) ; the case expression (nil for default)
2816
2817 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2818 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2819
2820 (defun js2-visit-case-node (n v)
2821 (js2-visit-ast (js2-case-node-expr n) v)
2822 (js2-visit-block n v))
2823
2824 (defun js2-print-case-node (n i)
2825 (let ((pad (js2-make-pad i))
2826 (expr (js2-case-node-expr n)))
2827 (insert pad)
2828 (if (null expr)
2829 (insert "default:\n")
2830 (insert "case ")
2831 (js2-print-ast expr 0)
2832 (insert ":\n"))
2833 (dolist (kid (js2-case-node-kids n))
2834 (js2-print-ast kid (1+ i)))))
2835
2836 (defstruct (js2-throw-node
2837 (:include js2-node)
2838 (:constructor nil)
2839 (:constructor make-js2-throw-node (&key (type js2-THROW)
2840 (pos js2-ts-cursor)
2841 len
2842 expr)))
2843 "AST node for a throw statement."
2844 expr) ; the expression to throw
2845
2846 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2847 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2848
2849 (defun js2-visit-throw-node (n v)
2850 (js2-visit-ast (js2-throw-node-expr n) v))
2851
2852 (defun js2-print-throw-node (n i)
2853 (insert (js2-make-pad i) "throw ")
2854 (js2-print-ast (js2-throw-node-expr n) 0)
2855 (insert ";\n"))
2856
2857 (defstruct (js2-with-node
2858 (:include js2-node)
2859 (:constructor nil)
2860 (:constructor make-js2-with-node (&key (type js2-WITH)
2861 (pos js2-ts-cursor)
2862 len
2863 object
2864 body
2865 lp
2866 rp)))
2867 "AST node for a with-statement."
2868 object
2869 body
2870 lp ; buffer position of left-paren around object, nil if omitted
2871 rp) ; buffer position of right-paren around object, nil if omitted
2872
2873 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2874 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2875
2876 (defun js2-visit-with-node (n v)
2877 (js2-visit-ast (js2-with-node-object n) v)
2878 (js2-visit-ast (js2-with-node-body n) v))
2879
2880 (defun js2-print-with-node (n i)
2881 (let ((pad (js2-make-pad i)))
2882 (insert pad "with (")
2883 (js2-print-ast (js2-with-node-object n) 0)
2884 (insert ") {\n")
2885 (js2-print-body (js2-with-node-body n) (1+ i))
2886 (insert pad "}\n")))
2887
2888 (defstruct (js2-label-node
2889 (:include js2-node)
2890 (:constructor nil)
2891 (:constructor make-js2-label-node (&key (type js2-LABEL)
2892 (pos js2-ts-cursor)
2893 len
2894 name)))
2895 "AST node for a statement label or case label."
2896 name ; a string
2897 loop) ; for validating and code-generating continue-to-label
2898
2899 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2900 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2901
2902 (defun js2-print-label (n i)
2903 (insert (js2-make-pad i)
2904 (js2-label-node-name n)
2905 ":\n"))
2906
2907 (defstruct (js2-labeled-stmt-node
2908 (:include js2-node)
2909 (:constructor nil)
2910 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2911 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2912 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2913 (pos js2-ts-cursor)
2914 len
2915 labels
2916 stmt)))
2917 "AST node for a statement with one or more labels.
2918 Multiple labels for a statement are collapsed into the labels field."
2919 labels ; lisp list of `js2-label-node'
2920 stmt) ; the statement these labels are for
2921
2922 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2923 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2924
2925 (defun js2-get-label-by-name (lbl-stmt name)
2926 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2927 Returns nil if no such label is in the list."
2928 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2929 result)
2930 (while (and label-list (not result))
2931 (if (string= (js2-label-node-name (car label-list)) name)
2932 (setq result (car label-list))
2933 (setq label-list (cdr label-list))))
2934 result))
2935
2936 (defun js2-visit-labeled-stmt (n v)
2937 (dolist (label (js2-labeled-stmt-node-labels n))
2938 (js2-visit-ast label v))
2939 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2940
2941 (defun js2-print-labeled-stmt (n i)
2942 (dolist (label (js2-labeled-stmt-node-labels n))
2943 (js2-print-ast label i))
2944 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2945
2946 (defun js2-labeled-stmt-node-contains (node label)
2947 "Return t if NODE contains LABEL in its label set.
2948 NODE is a `js2-labels-node'. LABEL is an identifier."
2949 (loop for nl in (js2-labeled-stmt-node-labels node)
2950 if (string= label (js2-label-node-name nl))
2951 return t
2952 finally return nil))
2953
2954 (defsubst js2-labeled-stmt-node-add-label (node label)
2955 "Add a `js2-label-node' to the label set for this statement."
2956 (setf (js2-labeled-stmt-node-labels node)
2957 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2958
2959 (defstruct (js2-jump-node
2960 (:include js2-node)
2961 (:constructor nil))
2962 "Abstract supertype of break and continue nodes."
2963 label ; `js2-name-node' for location of label identifier, if present
2964 target) ; target js2-labels-node or loop/switch statement
2965
2966 (defun js2-visit-jump-node (n v)
2967 (js2-visit-ast (js2-jump-node-label n) v))
2968
2969 (defstruct (js2-break-node
2970 (:include js2-jump-node)
2971 (:constructor nil)
2972 (:constructor make-js2-break-node (&key (type js2-BREAK)
2973 (pos js2-ts-cursor)
2974 len
2975 label
2976 target)))
2977 "AST node for a break statement.
2978 The label field is a `js2-name-node', possibly nil, for the named label
2979 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2980 is the target of the break - a label node or enclosing loop/switch statement.")
2981
2982 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2983 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2984
2985 (defun js2-print-break-node (n i)
2986 (insert (js2-make-pad i) "break")
2987 (when (js2-break-node-label n)
2988 (insert " ")
2989 (js2-print-ast (js2-break-node-label n) 0))
2990 (insert ";\n"))
2991
2992 (defstruct (js2-continue-node
2993 (:include js2-jump-node)
2994 (:constructor nil)
2995 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2996 (pos js2-ts-cursor)
2997 len
2998 label
2999 target)))
3000 "AST node for a continue statement.
3001 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3002 It is nil if continue specifies no label. The target field is the jump target:
3003 a `js2-label-node' or the innermost enclosing loop.")
3004
3005 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3006 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3007
3008 (defun js2-print-continue-node (n i)
3009 (insert (js2-make-pad i) "continue")
3010 (when (js2-continue-node-label n)
3011 (insert " ")
3012 (js2-print-ast (js2-continue-node-label n) 0))
3013 (insert ";\n"))
3014
3015 (defstruct (js2-function-node
3016 (:include js2-script-node)
3017 (:constructor nil)
3018 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3019 (pos js2-ts-cursor)
3020 len
3021 (ftype 'FUNCTION)
3022 (form 'FUNCTION_STATEMENT)
3023 (name "")
3024 params rest-p
3025 body
3026 lp 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 rp)))
3806 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3807
3808 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3809 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3810
3811 (defun js2-visit-array-comp-loop (n v)
3812 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3813 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3814
3815 (defun js2-print-array-comp-loop (n i)
3816 (insert "for (")
3817 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3818 (if (js2-array-comp-loop-node-forof-p n)
3819 (insert " of ")
3820 (insert " in "))
3821 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3822 (insert ")"))
3823
3824 (defstruct (js2-empty-expr-node
3825 (:include js2-node)
3826 (:constructor nil)
3827 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3828 (pos js2-token-beg)
3829 len)))
3830 "AST node for an empty expression.")
3831
3832 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3833 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3834
3835 (defstruct (js2-xml-node
3836 (:include js2-block-node)
3837 (:constructor nil)
3838 (:constructor make-js2-xml-node (&key (type js2-XML)
3839 (pos js2-token-beg)
3840 len
3841 kids)))
3842 "AST node for initial parse of E4X literals.
3843 The kids field is a list of XML fragments, each a `js2-string-node' or
3844 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3845
3846 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3847 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3848
3849 (defun js2-print-xml-node (n i)
3850 (dolist (kid (js2-xml-node-kids n))
3851 (js2-print-ast kid i)))
3852
3853 (defstruct (js2-xml-js-expr-node
3854 (:include js2-xml-node)
3855 (:constructor nil)
3856 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3857 (pos js2-ts-cursor)
3858 len
3859 expr)))
3860 "AST node for an embedded JavaScript {expression} in an E4X literal.
3861 The start and end fields correspond to the curly-braces."
3862 expr) ; a `js2-expr-node' of some sort
3863
3864 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3865 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3866
3867 (defun js2-visit-xml-js-expr (n v)
3868 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3869
3870 (defun js2-print-xml-js-expr (n i)
3871 (insert (js2-make-pad i))
3872 (insert "{")
3873 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3874 (insert "}"))
3875
3876 (defstruct (js2-xml-dot-query-node
3877 (:include js2-infix-node)
3878 (:constructor nil)
3879 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3880 (pos js2-ts-cursor)
3881 op-pos
3882 len
3883 left
3884 right
3885 rp)))
3886 "AST node for an E4X foo.(bar) filter expression.
3887 Note that the left-paren is automatically the character immediately
3888 following the dot (.) in the operator. No whitespace is permitted
3889 between the dot and the lp by the scanner."
3890 rp)
3891
3892 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3893 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3894
3895 (defun js2-print-xml-dot-query (n i)
3896 (insert (js2-make-pad i))
3897 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3898 (insert ".(")
3899 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3900 (insert ")"))
3901
3902 (defstruct (js2-xml-ref-node
3903 (:include js2-node)
3904 (:constructor nil)) ; abstract
3905 "Base type for E4X XML attribute-access or property-get expressions.
3906 Such expressions can take a variety of forms. The general syntax has
3907 three parts:
3908
3909 - (optional) an @ (specifying an attribute access)
3910 - (optional) a namespace (a `js2-name-node') and double-colon
3911 - (required) either a `js2-name-node' or a bracketed [expression]
3912
3913 The property-name expressions (examples: ns::name, @name) are
3914 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3915 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3916
3917 This node type (or more specifically, its subclasses) will sometimes
3918 be the right-hand child of a `js2-prop-get-node' or a
3919 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3920 The `js2-xml-ref-node' may also be a standalone primary expression with
3921 no explicit target, which is valid in certain expression contexts such as
3922
3923 company..employee.(@id < 100)
3924
3925 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3926 expression whose parent is a `js2-xml-dot-query-node'."
3927 namespace
3928 at-pos
3929 colon-pos)
3930
3931 (defsubst js2-xml-ref-node-attr-access-p (node)
3932 "Return non-nil if this expression began with an @-token."
3933 (and (numberp (js2-xml-ref-node-at-pos node))
3934 (plusp (js2-xml-ref-node-at-pos node))))
3935
3936 (defstruct (js2-xml-prop-ref-node
3937 (:include js2-xml-ref-node)
3938 (:constructor nil)
3939 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3940 (pos js2-token-beg)
3941 len
3942 propname
3943 namespace
3944 at-pos
3945 colon-pos)))
3946 "AST node for an E4X XML [expr] property-ref expression.
3947 The JavaScript syntax is an optional @, an optional ns::, and a name.
3948
3949 [ '@' ] [ name '::' ] name
3950
3951 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3952 @ns::*, @*::attr, @*::*, and @*.
3953
3954 The node starts at the @ token, if present. Otherwise it starts at the
3955 namespace name. The node bounds extend through the closing right-bracket,
3956 or if it is missing due to a syntax error, through the end of the index
3957 expression."
3958 propname)
3959
3960 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3961 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3962
3963 (defun js2-visit-xml-prop-ref-node (n v)
3964 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3965 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3966
3967 (defun js2-print-xml-prop-ref-node (n i)
3968 (insert (js2-make-pad i))
3969 (if (js2-xml-ref-node-attr-access-p n)
3970 (insert "@"))
3971 (when (js2-xml-prop-ref-node-namespace n)
3972 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3973 (insert "::"))
3974 (if (js2-xml-prop-ref-node-propname n)
3975 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3976
3977 (defstruct (js2-xml-elem-ref-node
3978 (:include js2-xml-ref-node)
3979 (:constructor nil)
3980 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3981 (pos js2-token-beg)
3982 len
3983 expr
3984 lb
3985 rb
3986 namespace
3987 at-pos
3988 colon-pos)))
3989 "AST node for an E4X XML [expr] member-ref expression.
3990 Syntax:
3991
3992 [ '@' ] [ name '::' ] '[' expr ']'
3993
3994 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3995
3996 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3997 is not a legal E4X XML element-ref expression, since it's already used
3998 for standard JavaScript element-get array indexing. Hence, a
3999 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4000 non-nil namespace node, or both.
4001
4002 The node starts at the @ token, if present. Otherwise it starts
4003 at the namespace name. The node bounds extend through the closing
4004 right-bracket, or if it is missing due to a syntax error, through the
4005 end of the index expression."
4006 expr ; the bracketed index expression
4007 lb
4008 rb)
4009
4010 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4011 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4012
4013 (defun js2-visit-xml-elem-ref-node (n v)
4014 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4015 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4016
4017 (defun js2-print-xml-elem-ref-node (n i)
4018 (insert (js2-make-pad i))
4019 (if (js2-xml-ref-node-attr-access-p n)
4020 (insert "@"))
4021 (when (js2-xml-elem-ref-node-namespace n)
4022 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4023 (insert "::"))
4024 (insert "[")
4025 (if (js2-xml-elem-ref-node-expr n)
4026 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4027 (insert "]"))
4028
4029 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4030
4031 (defstruct (js2-xml-start-tag-node
4032 (:include js2-xml-node)
4033 (:constructor nil)
4034 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4035 (pos js2-ts-cursor)
4036 len
4037 name
4038 attrs
4039 kids
4040 empty-p)))
4041 "AST node for an XML start-tag. Not currently used.
4042 The `kids' field is a lisp list of child content nodes."
4043 name ; a `js2-xml-name-node'
4044 attrs ; a lisp list of `js2-xml-attr-node'
4045 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4046
4047 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4048 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4049
4050 (defun js2-visit-xml-start-tag (n v)
4051 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4052 (dolist (attr (js2-xml-start-tag-node-attrs n))
4053 (js2-visit-ast attr v))
4054 (js2-visit-block n v))
4055
4056 (defun js2-print-xml-start-tag (n i)
4057 (insert (js2-make-pad i) "<")
4058 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4059 (when (js2-xml-start-tag-node-attrs n)
4060 (insert " ")
4061 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4062 (insert ">"))
4063
4064 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4065 ;; and add the end-tag to the kids list of the parent as well.
4066 (defstruct (js2-xml-end-tag-node
4067 (:include js2-xml-node)
4068 (:constructor nil)
4069 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4070 (pos js2-ts-cursor)
4071 len
4072 name)))
4073 "AST node for an XML end-tag. Not currently used."
4074 name) ; a `js2-xml-name-node'
4075
4076 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4077 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4078
4079 (defun js2-visit-xml-end-tag (n v)
4080 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4081
4082 (defun js2-print-xml-end-tag (n i)
4083 (insert (js2-make-pad i))
4084 (insert "</")
4085 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4086 (insert ">"))
4087
4088 (defstruct (js2-xml-name-node
4089 (:include js2-xml-node)
4090 (:constructor nil)
4091 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4092 (pos js2-ts-cursor)
4093 len
4094 namespace
4095 kids)))
4096 "AST node for an E4X XML name. Not currently used.
4097 Any XML name can be qualified with a namespace, hence the namespace field.
4098 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4099 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4100 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4101 namespace) ; a `js2-string-node'
4102
4103 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4104 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4105
4106 (defun js2-visit-xml-name-node (n v)
4107 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4108
4109 (defun js2-print-xml-name-node (n i)
4110 (insert (js2-make-pad i))
4111 (when (js2-xml-name-node-namespace n)
4112 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4113 (insert "::"))
4114 (dolist (kid (js2-xml-name-node-kids n))
4115 (js2-print-ast kid 0)))
4116
4117 (defstruct (js2-xml-pi-node
4118 (:include js2-xml-node)
4119 (:constructor nil)
4120 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4121 (pos js2-ts-cursor)
4122 len
4123 name
4124 attrs)))
4125 "AST node for an E4X XML processing instruction. Not currently used."
4126 name ; a `js2-xml-name-node'
4127 attrs) ; a list of `js2-xml-attr-node'
4128
4129 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4130 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4131
4132 (defun js2-visit-xml-pi-node (n v)
4133 (js2-visit-ast (js2-xml-pi-node-name n) v)
4134 (dolist (attr (js2-xml-pi-node-attrs n))
4135 (js2-visit-ast attr v)))
4136
4137 (defun js2-print-xml-pi-node (n i)
4138 (insert (js2-make-pad i) "<?")
4139 (js2-print-ast (js2-xml-pi-node-name n))
4140 (when (js2-xml-pi-node-attrs n)
4141 (insert " ")
4142 (js2-print-list (js2-xml-pi-node-attrs n)))
4143 (insert "?>"))
4144
4145 (defstruct (js2-xml-cdata-node
4146 (:include js2-xml-node)
4147 (:constructor nil)
4148 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4149 (pos js2-ts-cursor)
4150 len
4151 content)))
4152 "AST node for a CDATA escape section. Not currently used."
4153 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4154
4155 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4156 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4157
4158 (defun js2-visit-xml-cdata-node (n v)
4159 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4160
4161 (defun js2-print-xml-cdata-node (n i)
4162 (insert (js2-make-pad i))
4163 (js2-print-ast (js2-xml-cdata-node-content n)))
4164
4165 (defstruct (js2-xml-attr-node
4166 (:include js2-xml-node)
4167 (:constructor nil)
4168 (:constructor make-js2-attr-node (&key (type js2-XML)
4169 (pos js2-ts-cursor)
4170 len
4171 name
4172 value
4173 eq-pos
4174 quote-type)))
4175 "AST node representing a foo='bar' XML attribute value. Not yet used."
4176 name ; a `js2-xml-name-node'
4177 value ; a `js2-xml-name-node'
4178 eq-pos ; buffer position of "=" sign
4179 quote-type) ; 'single or 'double
4180
4181 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4182 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4183
4184 (defun js2-visit-xml-attr-node (n v)
4185 (js2-visit-ast (js2-xml-attr-node-name n) v)
4186 (js2-visit-ast (js2-xml-attr-node-value n) v))
4187
4188 (defun js2-print-xml-attr-node (n i)
4189 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4190 "'"
4191 "\"")))
4192 (insert (js2-make-pad i))
4193 (js2-print-ast (js2-xml-attr-node-name n) 0)
4194 (insert "=" quote)
4195 (js2-print-ast (js2-xml-attr-node-value n) 0)
4196 (insert quote)))
4197
4198 (defstruct (js2-xml-text-node
4199 (:include js2-xml-node)
4200 (:constructor nil)
4201 (:constructor make-js2-text-node (&key (type js2-XML)
4202 (pos js2-ts-cursor)
4203 len
4204 content)))
4205 "AST node for an E4X XML text node. Not currently used."
4206 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4207
4208 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4209 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4210
4211 (defun js2-visit-xml-text-node (n v)
4212 (js2-visit-ast (js2-xml-text-node-content n) v))
4213
4214 (defun js2-print-xml-text-node (n i)
4215 (insert (js2-make-pad i))
4216 (dolist (kid (js2-xml-text-node-content n))
4217 (js2-print-ast kid)))
4218
4219 (defstruct (js2-xml-comment-node
4220 (:include js2-xml-node)
4221 (:constructor nil)
4222 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4223 (pos js2-ts-cursor)
4224 len)))
4225 "AST node for E4X XML comment. Not currently used.")
4226
4227 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4228 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4229
4230 (defun js2-print-xml-comment (n i)
4231 (insert (js2-make-pad i)
4232 (js2-node-string n)))
4233
4234 ;;; Node utilities
4235
4236 (defsubst js2-node-line (n)
4237 "Fetch the source line number at the start of node N.
4238 This is O(n) in the length of the source buffer; use prudently."
4239 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4240
4241 (defsubst js2-block-node-kid (n i)
4242 "Return child I of node N, or nil if there aren't that many."
4243 (nth i (js2-block-node-kids n)))
4244
4245 (defsubst js2-block-node-first (n)
4246 "Return first child of block node N, or nil if there is none."
4247 (first (js2-block-node-kids n)))
4248
4249 (defun js2-node-root (n)
4250 "Return the root of the AST containing N.
4251 If N has no parent pointer, returns N."
4252 (let ((parent (js2-node-parent n)))
4253 (if parent
4254 (js2-node-root parent)
4255 n)))
4256
4257 (defun js2-node-position-in-parent (node &optional parent)
4258 "Return the position of NODE in parent's block-kids list.
4259 PARENT can be supplied if known. Positioned returned is zero-indexed.
4260 Returns 0 if NODE is not a child of a block statement, or if NODE
4261 is not a statement node."
4262 (let ((p (or parent (js2-node-parent node)))
4263 (i 0))
4264 (if (not (js2-block-node-p p))
4265 i
4266 (or (js2-position node (js2-block-node-kids p))
4267 0))))
4268
4269 (defsubst js2-node-short-name (n)
4270 "Return the short name of node N as a string, e.g. `js2-if-node'."
4271 (substring (symbol-name (aref n 0))
4272 (length "cl-struct-")))
4273
4274 (defsubst js2-node-child-list (node)
4275 "Return the child list for NODE, a lisp list of nodes.
4276 Works for block nodes, array nodes, obj literals, funarg lists,
4277 var decls and try nodes (for catch clauses). Note that you should call
4278 `js2-block-node-kids' on the function body for the body statements.
4279 Returns nil for zero-length child lists or unsupported nodes."
4280 (cond
4281 ((js2-function-node-p node)
4282 (js2-function-node-params node))
4283 ((js2-block-node-p node)
4284 (js2-block-node-kids node))
4285 ((js2-try-node-p node)
4286 (js2-try-node-catch-clauses node))
4287 ((js2-array-node-p node)
4288 (js2-array-node-elems node))
4289 ((js2-object-node-p node)
4290 (js2-object-node-elems node))
4291 ((js2-call-node-p node)
4292 (js2-call-node-args node))
4293 ((js2-new-node-p node)
4294 (js2-new-node-args node))
4295 ((js2-var-decl-node-p node)
4296 (js2-var-decl-node-kids node))
4297 (t
4298 nil)))
4299
4300 (defsubst js2-node-set-child-list (node kids)
4301 "Set the child list for NODE to KIDS."
4302 (cond
4303 ((js2-function-node-p node)
4304 (setf (js2-function-node-params node) kids))
4305 ((js2-block-node-p node)
4306 (setf (js2-block-node-kids node) kids))
4307 ((js2-try-node-p node)
4308 (setf (js2-try-node-catch-clauses node) kids))
4309 ((js2-array-node-p node)
4310 (setf (js2-array-node-elems node) kids))
4311 ((js2-object-node-p node)
4312 (setf (js2-object-node-elems node) kids))
4313 ((js2-call-node-p node)
4314 (setf (js2-call-node-args node) kids))
4315 ((js2-new-node-p node)
4316 (setf (js2-new-node-args node) kids))
4317 ((js2-var-decl-node-p node)
4318 (setf (js2-var-decl-node-kids node) kids))
4319 (t
4320 (error "Unsupported node type: %s" (js2-node-short-name node))))
4321 kids)
4322
4323 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4324 (defconst js2-paren-expr-nodes
4325 '(cl-struct-js2-array-comp-loop-node
4326 cl-struct-js2-array-comp-node
4327 cl-struct-js2-call-node
4328 cl-struct-js2-catch-node
4329 cl-struct-js2-do-node
4330 cl-struct-js2-elem-get-node
4331 cl-struct-js2-for-in-node
4332 cl-struct-js2-for-node
4333 cl-struct-js2-function-node
4334 cl-struct-js2-if-node
4335 cl-struct-js2-let-node
4336 cl-struct-js2-new-node
4337 cl-struct-js2-paren-node
4338 cl-struct-js2-switch-node
4339 cl-struct-js2-while-node
4340 cl-struct-js2-with-node
4341 cl-struct-js2-xml-dot-query-node)
4342 "Node types that can have a parenthesized child expression.
4343 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4344
4345 (defsubst js2-paren-expr-node-p (node)
4346 "Return t for nodes that typically have a parenthesized child expression.
4347 Useful for computing the indentation anchors for arg-lists and conditions.
4348 Note that it may return a false positive, for instance when NODE is
4349 a `js2-new-node' and there are no arguments or parentheses."
4350 (memq (aref node 0) js2-paren-expr-nodes))
4351
4352 ;; Fake polymorphism... yech.
4353 (defsubst js2-node-lp (node)
4354 "Return relative left-paren position for NODE, if applicable.
4355 For `js2-elem-get-node' structs, returns left-bracket position.
4356 Note that the position may be nil in the case of a parse error."
4357 (cond
4358 ((js2-elem-get-node-p node)
4359 (js2-elem-get-node-lb node))
4360 ((js2-loop-node-p node)
4361 (js2-loop-node-lp node))
4362 ((js2-function-node-p node)
4363 (js2-function-node-lp node))
4364 ((js2-if-node-p node)
4365 (js2-if-node-lp node))
4366 ((js2-new-node-p node)
4367 (js2-new-node-lp node))
4368 ((js2-call-node-p node)
4369 (js2-call-node-lp node))
4370 ((js2-paren-node-p node)
4371 (js2-node-pos node))
4372 ((js2-switch-node-p node)
4373 (js2-switch-node-lp node))
4374 ((js2-catch-node-p node)
4375 (js2-catch-node-lp node))
4376 ((js2-let-node-p node)
4377 (js2-let-node-lp node))
4378 ((js2-array-comp-node-p node)
4379 (js2-array-comp-node-lp node))
4380 ((js2-with-node-p node)
4381 (js2-with-node-lp node))
4382 ((js2-xml-dot-query-node-p node)
4383 (1+ (js2-infix-node-op-pos node)))
4384 (t
4385 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4386
4387 ;; Fake polymorphism... blech.
4388 (defsubst js2-node-rp (node)
4389 "Return relative right-paren position for NODE, if applicable.
4390 For `js2-elem-get-node' structs, returns right-bracket position.
4391 Note that the position may be nil in the case of a parse error."
4392 (cond
4393 ((js2-elem-get-node-p node)
4394 (js2-elem-get-node-rb node))
4395 ((js2-loop-node-p node)
4396 (js2-loop-node-rp node))
4397 ((js2-function-node-p node)
4398 (js2-function-node-rp node))
4399 ((js2-if-node-p node)
4400 (js2-if-node-rp node))
4401 ((js2-new-node-p node)
4402 (js2-new-node-rp node))
4403 ((js2-call-node-p node)
4404 (js2-call-node-rp node))
4405 ((js2-paren-node-p node)
4406 (+ (js2-node-pos node) (js2-node-len node)))
4407 ((js2-switch-node-p node)
4408 (js2-switch-node-rp node))
4409 ((js2-catch-node-p node)
4410 (js2-catch-node-rp node))
4411 ((js2-let-node-p node)
4412 (js2-let-node-rp node))
4413 ((js2-array-comp-node-p node)
4414 (js2-array-comp-node-rp node))
4415 ((js2-with-node-p node)
4416 (js2-with-node-rp node))
4417 ((js2-xml-dot-query-node-p node)
4418 (1+ (js2-xml-dot-query-node-rp node)))
4419 (t
4420 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4421
4422 (defsubst js2-node-first-child (node)
4423 "Returns the first element of `js2-node-child-list' for NODE."
4424 (car (js2-node-child-list node)))
4425
4426 (defsubst js2-node-last-child (node)
4427 "Returns the last element of `js2-node-last-child' for NODE."
4428 (car (last (js2-node-child-list node))))
4429
4430 (defun js2-node-prev-sibling (node)
4431 "Return the previous statement in parent.
4432 Works for parents supported by `js2-node-child-list'.
4433 Returns nil if NODE is not in the parent, or PARENT is
4434 not a supported node, or if NODE is the first child."
4435 (let* ((p (js2-node-parent node))
4436 (kids (js2-node-child-list p))
4437 (sib (car kids)))
4438 (while (and kids
4439 (not (eq node (cadr kids))))
4440 (setq kids (cdr kids)
4441 sib (car kids)))
4442 sib))
4443
4444 (defun js2-node-next-sibling (node)
4445 "Return the next statement in parent block.
4446 Returns nil if NODE is not in the block, or PARENT is not
4447 a block node, or if NODE is the last statement."
4448 (let* ((p (js2-node-parent node))
4449 (kids (js2-node-child-list p)))
4450 (while (and kids
4451 (not (eq node (car kids))))
4452 (setq kids (cdr kids)))
4453 (cadr kids)))
4454
4455 (defun js2-node-find-child-before (pos parent &optional after)
4456 "Find the last child that starts before POS in parent.
4457 If AFTER is non-nil, returns first child starting after POS.
4458 POS is an absolute buffer position. PARENT is any node
4459 supported by `js2-node-child-list'.
4460 Returns nil if no applicable child is found."
4461 (let ((kids (if (js2-function-node-p parent)
4462 (js2-block-node-kids (js2-function-node-body parent))
4463 (js2-node-child-list parent)))
4464 (beg (if (js2-function-node-p parent)
4465 (js2-node-abs-pos (js2-function-node-body parent))
4466 (js2-node-abs-pos parent)))
4467 kid
4468 result
4469 fn
4470 (continue t))
4471 (setq fn (if after '>= '<))
4472 (while (and kids continue)
4473 (setq kid (car kids))
4474 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4475 (setq result kid
4476 continue (if after nil t))
4477 (setq continue (if after t nil)))
4478 (setq kids (cdr kids)))
4479 result))
4480
4481 (defun js2-node-find-child-after (pos parent)
4482 "Find first child that starts after POS in parent.
4483 POS is an absolute buffer position. PARENT is any node
4484 supported by `js2-node-child-list'.
4485 Returns nil if no applicable child is found."
4486 (js2-node-find-child-before pos parent 'after))
4487
4488 (defun js2-node-replace-child (pos parent new-node)
4489 "Replace node at index POS in PARENT with NEW-NODE.
4490 Only works for parents supported by `js2-node-child-list'."
4491 (let ((kids (js2-node-child-list parent))
4492 (i 0))
4493 (while (< i pos)
4494 (setq kids (cdr kids)
4495 i (1+ i)))
4496 (setcar kids new-node)
4497 (js2-node-add-children parent new-node)))
4498
4499 (defun js2-node-buffer (n)
4500 "Return the buffer associated with AST N.
4501 Returns nil if the buffer is not set as a property on the root
4502 node, or if parent links were not recorded during parsing."
4503 (let ((root (js2-node-root n)))
4504 (and root
4505 (js2-ast-root-p root)
4506 (js2-ast-root-buffer root))))
4507
4508 (defsubst js2-block-node-push (n kid)
4509 "Push js2-node KID onto the end of js2-block-node N's child list.
4510 KID is always added to the -end- of the kids list.
4511 Function also calls `js2-node-add-children' to add the parent link."
4512 (let ((kids (js2-node-child-list n)))
4513 (if kids
4514 (setcdr kids (nconc (cdr kids) (list kid)))
4515 (js2-node-set-child-list n (list kid)))
4516 (js2-node-add-children n kid)))
4517
4518 (defun js2-node-string (node)
4519 (let ((buf (js2-node-buffer node))
4520 pos)
4521 (unless buf
4522 (error "No buffer available for node %s" node))
4523 (with-current-buffer buf
4524 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4525 (+ pos (js2-node-len node))))))
4526
4527 ;; Container for storing the node we're looking for in a traversal.
4528 (js2-deflocal js2-discovered-node nil)
4529
4530 ;; Keep track of absolute node position during traversals.
4531 (js2-deflocal js2-visitor-offset nil)
4532
4533 (js2-deflocal js2-node-search-point nil)
4534
4535 (when js2-mode-dev-mode-p
4536 (defun js2-find-node-at-point ()
4537 (interactive)
4538 (let ((node (js2-node-at-point)))
4539 (message "%s" (or node "No node found at point"))))
4540 (defun js2-node-name-at-point ()
4541 (interactive)
4542 (let ((node (js2-node-at-point)))
4543 (message "%s" (if node
4544 (js2-node-short-name node)
4545 "No node found at point.")))))
4546
4547 (defun js2-node-at-point (&optional pos skip-comments)
4548 "Return AST node at POS, a buffer position, defaulting to current point.
4549 The `js2-mode-ast' variable must be set to the current parse tree.
4550 Signals an error if the AST (`js2-mode-ast') is nil.
4551 Always returns a node - if it can't find one, it returns the root.
4552 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4553 (let ((ast js2-mode-ast)
4554 result)
4555 (unless ast
4556 (error "No JavaScript AST available"))
4557 ;; Look through comments first, since they may be inside nodes that
4558 ;; would otherwise report a match.
4559 (setq pos (or pos (point))
4560 result (if (> pos (js2-node-abs-end ast))
4561 ast
4562 (if (not skip-comments)
4563 (js2-comment-at-point pos))))
4564 (unless result
4565 (setq js2-discovered-node nil
4566 js2-visitor-offset 0
4567 js2-node-search-point pos)
4568 (unwind-protect
4569 (catch 'js2-visit-done
4570 (js2-visit-ast ast #'js2-node-at-point-visitor))
4571 (setq js2-visitor-offset nil
4572 js2-node-search-point nil))
4573 (setq result js2-discovered-node))
4574 ;; may have found a comment beyond end of last child node,
4575 ;; since visiting the ast-root looks at the comment-list last.
4576 (if (and skip-comments
4577 (js2-comment-node-p result))
4578 (setq result nil))
4579 (or result js2-mode-ast)))
4580
4581 (defun js2-node-at-point-visitor (node end-p)
4582 (let ((rel-pos (js2-node-pos node))
4583 abs-pos
4584 abs-end
4585 (point js2-node-search-point))
4586 (cond
4587 (end-p
4588 ;; this evaluates to a non-nil return value, even if it's zero
4589 (decf js2-visitor-offset rel-pos))
4590 ;; we already looked for comments before visiting, and don't want them now
4591 ((js2-comment-node-p node)
4592 nil)
4593 (t
4594 (setq abs-pos (incf js2-visitor-offset rel-pos)
4595 ;; we only want to use the node if the point is before
4596 ;; the last character position in the node, so we decrement
4597 ;; the absolute end by 1.
4598 abs-end (+ abs-pos (js2-node-len node) -1))
4599 (cond
4600 ;; If this node starts after search-point, stop the search.
4601 ((> abs-pos point)
4602 (throw 'js2-visit-done nil))
4603 ;; If this node ends before the search-point, don't check kids.
4604 ((> point abs-end)
4605 nil)
4606 (t
4607 ;; Otherwise point is within this node, possibly in a child.
4608 (setq js2-discovered-node node)
4609 t)))))) ; keep processing kids to look for more specific match
4610
4611 (defsubst js2-block-comment-p (node)
4612 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4613 (and (js2-comment-node-p node)
4614 (memq (js2-comment-node-format node) '(jsdoc block))))
4615
4616 ;; TODO: put the comments in a vector and binary-search them instead
4617 (defun js2-comment-at-point (&optional pos)
4618 "Look through scanned comment nodes for one containing POS.
4619 POS is a buffer position that defaults to current point.
4620 Function returns nil if POS was not in any comment node."
4621 (let ((ast js2-mode-ast)
4622 (x (or pos (point)))
4623 beg
4624 end)
4625 (unless ast
4626 (error "No JavaScript AST available"))
4627 (catch 'done
4628 ;; Comments are stored in lexical order.
4629 (dolist (comment (js2-ast-root-comments ast) nil)
4630 (setq beg (js2-node-abs-pos comment)
4631 end (+ beg (js2-node-len comment)))
4632 (if (and (>= x beg)
4633 (<= x end))
4634 (throw 'done comment))))))
4635
4636 (defun js2-mode-find-parent-fn (node)
4637 "Find function enclosing NODE.
4638 Returns nil if NODE is not inside a function."
4639 (setq node (js2-node-parent node))
4640 (while (and node (not (js2-function-node-p node)))
4641 (setq node (js2-node-parent node)))
4642 (and (js2-function-node-p node) node))
4643
4644 (defun js2-mode-find-enclosing-fn (node)
4645 "Find function or root enclosing NODE."
4646 (if (js2-ast-root-p node)
4647 node
4648 (setq node (js2-node-parent node))
4649 (while (not (or (js2-ast-root-p node)
4650 (js2-function-node-p node)))
4651 (setq node (js2-node-parent node)))
4652 node))
4653
4654 (defun js2-mode-find-enclosing-node (beg end)
4655 "Find script or function fully enclosing BEG and END."
4656 (let ((node (js2-node-at-point beg))
4657 pos
4658 (continue t))
4659 (while continue
4660 (if (or (js2-ast-root-p node)
4661 (and (js2-function-node-p node)
4662 (<= (setq pos (js2-node-abs-pos node)) beg)
4663 (>= (+ pos (js2-node-len node)) end)))
4664 (setq continue nil)
4665 (setq node (js2-node-parent node))))
4666 node))
4667
4668 (defun js2-node-parent-script-or-fn (node)
4669 "Find script or function immediately enclosing NODE.
4670 If NODE is the ast-root, returns nil."
4671 (if (js2-ast-root-p node)
4672 nil
4673 (setq node (js2-node-parent node))
4674 (while (and node (not (or (js2-function-node-p node)
4675 (js2-script-node-p node))))
4676 (setq node (js2-node-parent node)))
4677 node))
4678
4679 (defsubst js2-nested-function-p (node)
4680 "Return t if NODE is a nested function, or is inside a nested function."
4681 (unless (js2-ast-root-p node)
4682 (js2-function-node-p (if (js2-function-node-p node)
4683 (js2-node-parent-script-or-fn node)
4684 (js2-node-parent-script-or-fn
4685 (js2-node-parent-script-or-fn node))))))
4686
4687 (defsubst js2-function-param-node-p (node)
4688 "Return non-nil if NODE is a param node of a `js2-function-node'."
4689 (let ((parent (js2-node-parent node)))
4690 (and parent
4691 (js2-function-node-p parent)
4692 (memq node (js2-function-node-params parent)))))
4693
4694 (defsubst js2-mode-shift-kids (kids start offset)
4695 (dolist (kid kids)
4696 (if (> (js2-node-pos kid) start)
4697 (incf (js2-node-pos kid) offset))))
4698
4699 (defsubst js2-mode-shift-children (parent start offset)
4700 "Update start-positions of all children of PARENT beyond START."
4701 (let ((root (js2-node-root parent)))
4702 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4703 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4704
4705 (defsubst js2-node-is-descendant (node ancestor)
4706 "Return t if NODE is a descendant of ANCESTOR."
4707 (while (and node
4708 (not (eq node ancestor)))
4709 (setq node (js2-node-parent node)))
4710 node)
4711
4712 ;;; visitor infrastructure
4713
4714 (defun js2-visit-none (node callback)
4715 "Visitor for AST node that have no node children."
4716 nil)
4717
4718 (defun js2-print-none (node indent)
4719 "Visitor for AST node with no printed representation.")
4720
4721 (defun js2-print-body (node indent)
4722 "Print a statement, or a block without braces."
4723 (if (js2-block-node-p node)
4724 (dolist (kid (js2-block-node-kids node))
4725 (js2-print-ast kid indent))
4726 (js2-print-ast node indent)))
4727
4728 (defun js2-print-list (args &optional delimiter)
4729 (loop with len = (length args)
4730 for arg in args
4731 for count from 1
4732 do
4733 (js2-print-ast arg 0)
4734 (if (< count len)
4735 (insert (or delimiter ", ")))))
4736
4737 (defun js2-print-tree (ast)
4738 "Prints an AST to the current buffer.
4739 Makes `js2-ast-parent-nodes' available to the printer functions."
4740 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4741 (js2-print-ast ast)))
4742
4743 (defun js2-print-ast (node &optional indent)
4744 "Helper function for printing AST nodes.
4745 Requires `js2-ast-parent-nodes' to be non-nil.
4746 You should use `js2-print-tree' instead of this function."
4747 (let ((printer (get (aref node 0) 'js2-printer))
4748 (i (or indent 0))
4749 (pos (js2-node-abs-pos node)))
4750 ;; TODO: wedge comments in here somewhere
4751 (if printer
4752 (funcall printer node i))))
4753
4754 (defconst js2-side-effecting-tokens
4755 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4756 (dolist (tt (list js2-ASSIGN
4757 js2-ASSIGN_ADD
4758 js2-ASSIGN_BITAND
4759 js2-ASSIGN_BITOR
4760 js2-ASSIGN_BITXOR
4761 js2-ASSIGN_DIV
4762 js2-ASSIGN_LSH
4763 js2-ASSIGN_MOD
4764 js2-ASSIGN_MUL
4765 js2-ASSIGN_RSH
4766 js2-ASSIGN_SUB
4767 js2-ASSIGN_URSH
4768 js2-BLOCK
4769 js2-BREAK
4770 js2-CALL
4771 js2-CATCH
4772 js2-CATCH_SCOPE
4773 js2-CONST
4774 js2-CONTINUE
4775 js2-DEBUGGER
4776 js2-DEC
4777 js2-DELPROP
4778 js2-DEL_REF
4779 js2-DO
4780 js2-ELSE
4781 js2-EMPTY
4782 js2-ENTERWITH
4783 js2-EXPORT
4784 js2-EXPR_RESULT
4785 js2-FINALLY
4786 js2-FOR
4787 js2-FUNCTION
4788 js2-GOTO
4789 js2-IF
4790 js2-IFEQ
4791 js2-IFNE
4792 js2-IMPORT
4793 js2-INC
4794 js2-JSR
4795 js2-LABEL
4796 js2-LEAVEWITH
4797 js2-LET
4798 js2-LETEXPR
4799 js2-LOCAL_BLOCK
4800 js2-LOOP
4801 js2-NEW
4802 js2-REF_CALL
4803 js2-RETHROW
4804 js2-RETURN
4805 js2-RETURN_RESULT
4806 js2-SEMI
4807 js2-SETELEM
4808 js2-SETELEM_OP
4809 js2-SETNAME
4810 js2-SETPROP
4811 js2-SETPROP_OP
4812 js2-SETVAR
4813 js2-SET_REF
4814 js2-SET_REF_OP
4815 js2-SWITCH
4816 js2-TARGET
4817 js2-THROW
4818 js2-TRY
4819 js2-VAR
4820 js2-WHILE
4821 js2-WITH
4822 js2-WITHEXPR
4823 js2-YIELD))
4824 (aset tokens tt t))
4825 (if js2-instanceof-has-side-effects
4826 (aset tokens js2-INSTANCEOF t))
4827 tokens))
4828
4829 (defun js2-node-has-side-effects (node)
4830 "Return t if NODE has side effects."
4831 (when node ; makes it easier to handle malformed expressions
4832 (let ((tt (js2-node-type node)))
4833 (cond
4834 ;; This doubtless needs some work, since EXPR_VOID is used
4835 ;; in several ways in Rhino, and I may not have caught them all.
4836 ;; I'll wait for people to notice incorrect warnings.
4837 ((and (= tt js2-EXPR_VOID)
4838 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4839 (let ((expr (js2-expr-stmt-node-expr node)))
4840 (or (js2-node-has-side-effects expr)
4841 (when (js2-string-node-p expr)
4842 (string= "use strict" (js2-string-node-value expr))))))
4843 ((= tt js2-COMMA)
4844 (js2-node-has-side-effects (js2-infix-node-right node)))
4845 ((or (= tt js2-AND)
4846 (= tt js2-OR))
4847 (or (js2-node-has-side-effects (js2-infix-node-right node))
4848 (js2-node-has-side-effects (js2-infix-node-left node))))
4849 ((= tt js2-HOOK)
4850 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4851 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4852 ((js2-paren-node-p node)
4853 (js2-node-has-side-effects (js2-paren-node-expr node)))
4854 ((= tt js2-ERROR) ; avoid cascaded error messages
4855 nil)
4856 (t
4857 (aref js2-side-effecting-tokens tt))))))
4858
4859 (defun js2-member-expr-leftmost-name (node)
4860 "For an expr such as foo.bar.baz, return leftmost node foo.
4861 NODE is any `js2-node' object. If it represents a member expression,
4862 which is any sequence of property gets, element-gets, function calls,
4863 or xml descendants/filter operators, then we look at the lexically
4864 leftmost (first) node in the chain. If it is a name-node we return it.
4865 Note that NODE can be a raw name-node and it will be returned as well.
4866 If NODE is not a name-node or member expression, or if it is a member
4867 expression whose leftmost target is not a name node, returns nil."
4868 (let ((continue t)
4869 result)
4870 (while (and continue (not result))
4871 (cond
4872 ((js2-name-node-p node)
4873 (setq result node))
4874 ((js2-prop-get-node-p node)
4875 (setq node (js2-prop-get-node-left node)))
4876 ;; TODO: handle call-nodes, xml-nodes, others?
4877 (t
4878 (setq continue nil))))
4879 result))
4880
4881 (defconst js2-stmt-node-types
4882 (list js2-BLOCK
4883 js2-BREAK
4884 js2-CONTINUE
4885 js2-DEFAULT ; e4x "default xml namespace" statement
4886 js2-DO
4887 js2-EXPR_RESULT
4888 js2-EXPR_VOID
4889 js2-FOR
4890 js2-IF
4891 js2-RETURN
4892 js2-SWITCH
4893 js2-THROW
4894 js2-TRY
4895 js2-WHILE
4896 js2-WITH)
4897 "Node types that only appear in statement contexts.
4898 The list does not include nodes that always appear as the child
4899 of another specific statement type, such as switch-cases,
4900 catch and finally blocks, and else-clauses. The list also excludes
4901 nodes like yield, let and var, which may appear in either expression
4902 or statement context, and in the latter context always have a
4903 `js2-expr-stmt-node' parent. Finally, the list does not include
4904 functions or scripts, which are treated separately from statements
4905 by the JavaScript parser and runtime.")
4906
4907 (defun js2-stmt-node-p (node)
4908 "Heuristic for figuring out if NODE is a statement.
4909 Some node types can appear in either an expression context or a
4910 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4911 For these node types in a statement context, the parent will be a
4912 `js2-expr-stmt-node'.
4913 Functions aren't included in the check."
4914 (memq (js2-node-type node) js2-stmt-node-types))
4915
4916 (defsubst js2-mode-find-first-stmt (node)
4917 "Search upward starting from NODE looking for a statement.
4918 For purposes of this function, a `js2-function-node' counts."
4919 (while (not (or (js2-stmt-node-p node)
4920 (js2-function-node-p node)))
4921 (setq node (js2-node-parent node)))
4922 node)
4923
4924 (defun js2-node-parent-stmt (node)
4925 "Return the node's first ancestor that is a statement.
4926 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4927 appearing in a statement context will have a parent that is a
4928 `js2-expr-stmt-node' that will be returned by this function."
4929 (let ((parent (js2-node-parent node)))
4930 (if (or (null parent)
4931 (js2-stmt-node-p parent)
4932 (and (js2-function-node-p parent)
4933 (not (eq (js2-function-node-form parent)
4934 'FUNCTION_EXPRESSION))))
4935 parent
4936 (js2-node-parent-stmt parent))))
4937
4938 ;; In the Mozilla Rhino sources, Roshan James writes:
4939 ;; Does consistent-return analysis on the function body when strict mode is
4940 ;; enabled.
4941 ;;
4942 ;; function (x) { return (x+1) }
4943 ;;
4944 ;; is ok, but
4945 ;;
4946 ;; function (x) { if (x < 0) return (x+1); }
4947 ;;
4948 ;; is not because the function can potentially return a value when the
4949 ;; condition is satisfied and if not, the function does not explicitly
4950 ;; return a value.
4951 ;;
4952 ;; This extends to checking mismatches such as "return" and "return <value>"
4953 ;; used in the same function. Warnings are not emitted if inconsistent
4954 ;; returns exist in code that can be statically shown to be unreachable.
4955 ;; Ex.
4956 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4957 ;;
4958 ;; emits no warning. However if the loop had a break statement, then a
4959 ;; warning would be emitted.
4960 ;;
4961 ;; The consistency analysis looks at control structures such as loops, ifs,
4962 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4963 ;; warns the user about an inconsistent set of termination possibilities.
4964 ;;
4965 ;; These flags enumerate the possible ways a statement/function can
4966 ;; terminate. These flags are used by endCheck() and by the Parser to
4967 ;; detect inconsistent return usage.
4968 ;;
4969 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4970 ;; able to execute (example: throw, continue)
4971 ;;
4972 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4973 ;; next one. Statement such as return dont. A compound statement may have
4974 ;; some branch that drops off control to the next statement.
4975 ;;
4976 ;; END_RETURNS indicates that the statement can return with no value.
4977 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4978 ;;
4979 ;; A compound statement such as
4980 ;; if (condition) {
4981 ;; return value;
4982 ;; }
4983 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4984
4985 (defconst js2-END_UNREACHED 0)
4986 (defconst js2-END_DROPS_OFF 1)
4987 (defconst js2-END_RETURNS 2)
4988 (defconst js2-END_RETURNS_VALUE 4)
4989 (defconst js2-END_YIELDS 8)
4990
4991 (defun js2-has-consistent-return-usage (node)
4992 "Check that every return usage in a function body is consistent.
4993 Returns t if the function satisfies strict mode requirement."
4994 (let ((n (js2-end-check node)))
4995 ;; either it doesn't return a value in any branch...
4996 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4997 ;; or it returns a value (or is unreached) at every branch
4998 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4999 js2-END_RETURNS
5000 js2-END_YIELDS)))))
5001
5002 (defun js2-end-check-if (node)
5003 "Returns in the then and else blocks must be consistent with each other.
5004 If there is no else block, then the return statement can fall through.
5005 Returns logical OR of END_* flags"
5006 (let ((th (js2-if-node-then-part node))
5007 (el (js2-if-node-else-part node)))
5008 (if (null th)
5009 js2-END_UNREACHED
5010 (logior (js2-end-check th) (if el
5011 (js2-end-check el)
5012 js2-END_DROPS_OFF)))))
5013
5014 (defun js2-end-check-switch (node)
5015 "Consistency of return statements is checked between the case statements.
5016 If there is no default, then the switch can fall through. If there is a
5017 default, we check to see if all code paths in the default return or if
5018 there is a code path that can fall through.
5019 Returns logical OR of END_* flags."
5020 (let ((rv js2-END_UNREACHED)
5021 default-case)
5022 ;; examine the cases
5023 (catch 'break
5024 (dolist (c (js2-switch-node-cases node))
5025 (if (js2-case-node-expr c)
5026 (js2-set-flag rv (js2-end-check-block c))
5027 (setq default-case c)
5028 (throw 'break nil))))
5029 ;; we don't care how the cases drop into each other
5030 (js2-clear-flag rv js2-END_DROPS_OFF)
5031 ;; examine the default
5032 (js2-set-flag rv (if default-case
5033 (js2-end-check default-case)
5034 js2-END_DROPS_OFF))
5035 rv))
5036
5037 (defun js2-end-check-try (node)
5038 "If the block has a finally, return consistency is checked in the
5039 finally block. If all code paths in the finally return, then the
5040 returns in the try-catch blocks don't matter. If there is a code path
5041 that does not return or if there is no finally block, the returns
5042 of the try and catch blocks are checked for mismatch.
5043 Returns logical OR of END_* flags."
5044 (let ((finally (js2-try-node-finally-block node))
5045 rv)
5046 ;; check the finally if it exists
5047 (setq rv (if finally
5048 (js2-end-check (js2-finally-node-body finally))
5049 js2-END_DROPS_OFF))
5050 ;; If the finally block always returns, then none of the returns
5051 ;; in the try or catch blocks matter.
5052 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5053 (js2-clear-flag rv js2-END_DROPS_OFF)
5054 ;; examine the try block
5055 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5056 ;; check each catch block
5057 (dolist (cb (js2-try-node-catch-clauses node))
5058 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5059 rv))
5060
5061 (defun js2-end-check-loop (node)
5062 "Return statement in the loop body must be consistent. The default
5063 assumption for any kind of a loop is that it will eventually terminate.
5064 The only exception is a loop with a constant true condition. Code that
5065 follows such a loop is examined only if one can statically determine
5066 that there is a break out of the loop.
5067
5068 for(... ; ... ; ...) {}
5069 for(... in ... ) {}
5070 while(...) { }
5071 do { } while(...)
5072
5073 Returns logical OR of END_* flags."
5074 (let ((rv (js2-end-check (js2-loop-node-body node)))
5075 (condition (cond
5076 ((js2-while-node-p node)
5077 (js2-while-node-condition node))
5078 ((js2-do-node-p node)
5079 (js2-do-node-condition node))
5080 ((js2-for-node-p node)
5081 (js2-for-node-condition node)))))
5082
5083 ;; check to see if the loop condition is always true
5084 (if (and condition
5085 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5086 (js2-clear-flag rv js2-END_DROPS_OFF))
5087
5088 ;; look for effect of breaks
5089 (js2-set-flag rv (js2-node-get-prop node
5090 'CONTROL_BLOCK_PROP
5091 js2-END_UNREACHED))
5092 rv))
5093
5094 (defun js2-end-check-block (node)
5095 "A general block of code is examined statement by statement.
5096 If any statement (even a compound one) returns in all branches, then
5097 subsequent statements are not examined.
5098 Returns logical OR of END_* flags."
5099 (let* ((rv js2-END_DROPS_OFF)
5100 (kids (js2-block-node-kids node))
5101 (n (car kids)))
5102 ;; Check each statment. If the statement can continue onto the next
5103 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5104 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5105 (js2-clear-flag rv js2-END_DROPS_OFF)
5106 (js2-set-flag rv (js2-end-check n))
5107 (setq kids (cdr kids)
5108 n (car kids)))
5109 rv))
5110
5111 (defun js2-end-check-label (node)
5112 "A labeled statement implies that there may be a break to the label.
5113 The function processes the labeled statement and then checks the
5114 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5115 particular label.
5116 Returns logical OR of END_* flags."
5117 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5118 (logior rv (js2-node-get-prop node
5119 'CONTROL_BLOCK_PROP
5120 js2-END_UNREACHED))))
5121
5122 (defun js2-end-check-break (node)
5123 "When a break is encountered annotate the statement being broken
5124 out of by setting its CONTROL_BLOCK_PROP property.
5125 Returns logical OR of END_* flags."
5126 (and (js2-break-node-target node)
5127 (js2-node-set-prop (js2-break-node-target node)
5128 'CONTROL_BLOCK_PROP
5129 js2-END_DROPS_OFF))
5130 js2-END_UNREACHED)
5131
5132 (defun js2-end-check (node)
5133 "Examine the body of a function, doing a basic reachability analysis.
5134 Returns a combination of flags END_* flags that indicate
5135 how the function execution can terminate. These constitute only the
5136 pessimistic set of termination conditions. It is possible that at
5137 runtime certain code paths will never be actually taken. Hence this
5138 analysis will flag errors in cases where there may not be errors.
5139 Returns logical OR of END_* flags"
5140 (let (kid)
5141 (cond
5142 ((js2-break-node-p node)
5143 (js2-end-check-break node))
5144 ((js2-expr-stmt-node-p node)
5145 (if (setq kid (js2-expr-stmt-node-expr node))
5146 (js2-end-check kid)
5147 js2-END_DROPS_OFF))
5148 ((or (js2-continue-node-p node)
5149 (js2-throw-node-p node))
5150 js2-END_UNREACHED)
5151 ((js2-return-node-p node)
5152 (if (setq kid (js2-return-node-retval node))
5153 js2-END_RETURNS_VALUE
5154 js2-END_RETURNS))
5155 ((js2-loop-node-p node)
5156 (js2-end-check-loop node))
5157 ((js2-switch-node-p node)
5158 (js2-end-check-switch node))
5159 ((js2-labeled-stmt-node-p node)
5160 (js2-end-check-label node))
5161 ((js2-if-node-p node)
5162 (js2-end-check-if node))
5163 ((js2-try-node-p node)
5164 (js2-end-check-try node))
5165 ((js2-block-node-p node)
5166 (if (null (js2-block-node-kids node))
5167 js2-END_DROPS_OFF
5168 (js2-end-check-block node)))
5169 ((js2-yield-node-p node)
5170 js2-END_YIELDS)
5171 (t
5172 js2-END_DROPS_OFF))))
5173
5174 (defun js2-always-defined-boolean-p (node)
5175 "Check if NODE always evaluates to true or false in boolean context.
5176 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5177 nor always false."
5178 (let ((tt (js2-node-type node))
5179 num)
5180 (cond
5181 ((or (= tt js2-FALSE) (= tt js2-NULL))
5182 'ALWAYS_FALSE)
5183 ((= tt js2-TRUE)
5184 'ALWAYS_TRUE)
5185 ((= tt js2-NUMBER)
5186 (setq num (js2-number-node-num-value node))
5187 (if (and (not (eq num 0.0e+NaN))
5188 (not (zerop num)))
5189 'ALWAYS_TRUE
5190 'ALWAYS_FALSE))
5191 (t
5192 nil))))
5193
5194 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5195 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5196
5197 (defvar js2-tokens nil
5198 "List of all defined token names.") ; initialized in `js2-token-names'
5199
5200 (defconst js2-token-names
5201 (let* ((names (make-vector js2-num-tokens -1))
5202 (case-fold-search nil) ; only match js2-UPPER_CASE
5203 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5204 (loop for sym in syms
5205 for i from 0
5206 do
5207 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5208 (not (boundp sym)))
5209 (aset names (symbol-value sym) ; code, e.g. 152
5210 (downcase
5211 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5212 (push sym js2-tokens)))
5213 names)
5214 "Vector mapping int values to token string names, sans `js2-' prefix.")
5215
5216 (defun js2-token-name (tok)
5217 "Return a string name for TOK, a token symbol or code.
5218 Signals an error if it's not a recognized token."
5219 (let ((code tok))
5220 (if (symbolp tok)
5221 (setq code (symbol-value tok)))
5222 (if (eq code -1)
5223 "ERROR"
5224 (if (and (numberp code)
5225 (not (minusp code))
5226 (< code js2-num-tokens))
5227 (aref js2-token-names code)
5228 (error "Invalid token: %s" code)))))
5229
5230 (defsubst js2-token-sym (tok)
5231 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5232 (intern (js2-token-name tok)))
5233
5234 (defconst js2-token-codes
5235 (let ((table (make-hash-table :test 'eq :size 256)))
5236 (loop for name across js2-token-names
5237 for sym = (intern (concat "js2-" (upcase name)))
5238 do
5239 (puthash sym (symbol-value sym) table))
5240 ;; clean up a few that are "wrong" in Rhino's token codes
5241 (puthash 'js2-DELETE js2-DELPROP table)
5242 table)
5243 "Hashtable mapping token symbols to their bytecodes.")
5244
5245 (defsubst js2-token-code (sym)
5246 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5247 (or (gethash sym js2-token-codes)
5248 (error "Invalid token symbol: %s " sym))) ; signal code bug
5249
5250 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5251 (setq js2-token-end js2-ts-cursor)
5252 (js2-report-error msg nil
5253 (or beg js2-token-beg)
5254 (or len (- js2-token-end js2-token-beg)))
5255 (unless no-throw
5256 (throw 'return js2-ERROR)))
5257
5258 (defsubst js2-get-string-from-buffer ()
5259 "Reverse the char accumulator and return it as a string."
5260 (setq js2-token-end js2-ts-cursor)
5261 (if js2-ts-string-buffer
5262 (apply #'string (nreverse js2-ts-string-buffer))
5263 ""))
5264
5265 ;; TODO: could potentially avoid a lot of consing by allocating a
5266 ;; char buffer the way Rhino does.
5267 (defsubst js2-add-to-string (c)
5268 (push c js2-ts-string-buffer))
5269
5270 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5271 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5272 ;; any other character: when it's not part of the current token, we
5273 ;; unget it, allowing it to be read again by the following call.
5274 (defsubst js2-unget-char ()
5275 (decf js2-ts-cursor))
5276
5277 ;; Rhino distinguishes \r and \n line endings. We don't need to
5278 ;; because we only scan from Emacs buffers, which always use \n.
5279 (defsubst js2-get-char ()
5280 "Read and return the next character from the input buffer.
5281 Increments `js2-ts-lineno' if the return value is a newline char.
5282 Updates `js2-ts-cursor' to the point after the returned char.
5283 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5284 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5285 (let (c)
5286 ;; check for end of buffer
5287 (if (>= js2-ts-cursor (point-max))
5288 (setq js2-ts-hit-eof t
5289 js2-ts-cursor (1+ js2-ts-cursor)
5290 c js2-EOF_CHAR) ; return value
5291 ;; otherwise read next char
5292 (setq c (char-before (incf js2-ts-cursor)))
5293 ;; if we read a newline, update counters
5294 (if (= c ?\n)
5295 (setq js2-ts-line-start js2-ts-cursor
5296 js2-ts-lineno (1+ js2-ts-lineno)))
5297 ;; TODO: skip over format characters
5298 c)))
5299
5300 (defsubst js2-read-unicode-escape ()
5301 "Read a \\uNNNN sequence from the input.
5302 Assumes the ?\ and ?u have already been read.
5303 Returns the unicode character, or nil if it wasn't a valid character.
5304 Doesn't change the values of any scanner variables."
5305 ;; I really wish I knew a better way to do this, but I can't
5306 ;; find the Emacs function that takes a 16-bit int and converts
5307 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5308 ;; Have to first check that it's 4 hex characters or it may stop
5309 ;; the read early.
5310 (ignore-errors
5311 (let ((s (buffer-substring-no-properties js2-ts-cursor
5312 (+ 4 js2-ts-cursor))))
5313 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5314 (read (concat "?\\u" s))))))
5315
5316 (defsubst js2-match-char (test)
5317 "Consume and return next character if it matches TEST, a character.
5318 Returns nil and consumes nothing if TEST is not the next character."
5319 (let ((c (js2-get-char)))
5320 (if (eq c test)
5321 t
5322 (js2-unget-char)
5323 nil)))
5324
5325 (defsubst js2-peek-char ()
5326 (prog1
5327 (js2-get-char)
5328 (js2-unget-char)))
5329
5330 (defsubst js2-java-identifier-start-p (c)
5331 (or
5332 (memq c '(?$ ?_))
5333 (js2-char-uppercase-p c)
5334 (js2-char-lowercase-p c)))
5335
5336 (defsubst js2-java-identifier-part-p (c)
5337 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5338 ;; TODO: make me Unicode-friendly. See comments above.
5339 (or
5340 (memq c '(?$ ?_))
5341 (js2-char-uppercase-p c)
5342 (js2-char-lowercase-p c)
5343 (and (>= c ?0) (<= c ?9))))
5344
5345 (defsubst js2-alpha-p (c)
5346 (cond ((and (<= ?A c) (<= c ?Z)) t)
5347 ((and (<= ?a c) (<= c ?z)) t)
5348 (t nil)))
5349
5350 (defsubst js2-digit-p (c)
5351 (and (<= ?0 c) (<= c ?9)))
5352
5353 (defsubst js2-js-space-p (c)
5354 (if (<= c 127)
5355 (memq c '(#x20 #x9 #xB #xC #xD))
5356 (or
5357 (eq c #xA0)
5358 ;; TODO: change this nil to check for Unicode space character
5359 nil)))
5360
5361 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5362
5363 (defsubst js2-skip-line ()
5364 "Skip to end of line"
5365 (let (c)
5366 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5367 (js2-unget-char)
5368 (setq js2-token-end js2-ts-cursor)))
5369
5370 (defun js2-init-scanner (&optional buf line)
5371 "Create token stream for BUF starting on LINE.
5372 BUF defaults to current-buffer and line defaults to 1.
5373
5374 A buffer can only have one scanner active at a time, which yields
5375 dramatically simpler code than using a defstruct. If you need to
5376 have simultaneous scanners in a buffer, copy the regions to scan
5377 into temp buffers."
5378 (save-excursion
5379 (when buf
5380 (set-buffer buf))
5381 (setq js2-ts-dirty-line nil
5382 js2-ts-regexp-flags nil
5383 js2-ts-string ""
5384 js2-ts-number nil
5385 js2-ts-hit-eof nil
5386 js2-ts-line-start 0
5387 js2-ts-lineno (or line 1)
5388 js2-ts-line-end-char -1
5389 js2-ts-cursor (point-min)
5390 js2-ts-is-xml-attribute nil
5391 js2-ts-xml-is-tag-content nil
5392 js2-ts-xml-open-tags-count 0
5393 js2-ts-string-buffer nil)))
5394
5395 ;; This function uses the cached op, string and number fields in
5396 ;; TokenStream; if getToken has been called since the passed token
5397 ;; was scanned, the op or string printed may be incorrect.
5398 (defun js2-token-to-string (token)
5399 ;; Not sure where this function is used in Rhino. Not tested.
5400 (if (not js2-debug-print-trees)
5401 ""
5402 (let ((name (js2-token-name token)))
5403 (cond
5404 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5405 (concat name " `" js2-ts-string "'"))
5406 ((eq token js2-NUMBER)
5407 (format "NUMBER %g" js2-ts-number))
5408 (t
5409 name)))))
5410
5411 (defconst js2-keywords
5412 '(break
5413 case catch const continue
5414 debugger default delete do
5415 else enum
5416 false finally for function
5417 if in instanceof import
5418 let
5419 new null
5420 return
5421 switch
5422 this throw true try typeof
5423 var void
5424 while with
5425 yield))
5426
5427 ;; Token names aren't exactly the same as the keywords, unfortunately.
5428 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5429 (defconst js2-kwd-tokens
5430 (let ((table (make-vector js2-num-tokens nil))
5431 (tokens
5432 (list js2-BREAK
5433 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5434 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5435 js2-ELSE
5436 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5437 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5438 js2-LET
5439 js2-NEW js2-NULL
5440 js2-RETURN
5441 js2-SWITCH
5442 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5443 js2-VAR
5444 js2-WHILE js2-WITH
5445 js2-YIELD)))
5446 (dolist (i tokens)
5447 (aset table i 'font-lock-keyword-face))
5448 (aset table js2-STRING 'font-lock-string-face)
5449 (aset table js2-REGEXP 'font-lock-string-face)
5450 (aset table js2-COMMENT 'font-lock-comment-face)
5451 (aset table js2-THIS 'font-lock-builtin-face)
5452 (aset table js2-VOID 'font-lock-constant-face)
5453 (aset table js2-NULL 'font-lock-constant-face)
5454 (aset table js2-TRUE 'font-lock-constant-face)
5455 (aset table js2-FALSE 'font-lock-constant-face)
5456 table)
5457 "Vector whose values are non-nil for tokens that are keywords.
5458 The values are default faces to use for highlighting the keywords.")
5459
5460 (defconst js2-reserved-words
5461 '(abstract
5462 boolean byte
5463 char class
5464 double
5465 enum export extends
5466 final float
5467 goto
5468 implements import int interface
5469 long
5470 native
5471 package private protected public
5472 short static super synchronized
5473 throws transient
5474 volatile))
5475
5476 (defconst js2-keyword-names
5477 (let ((table (make-hash-table :test 'equal)))
5478 (loop for k in js2-keywords
5479 do (puthash
5480 (symbol-name k) ; instanceof
5481 (intern (concat "js2-"
5482 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5483 table))
5484 table)
5485 "JavaScript keywords by name, mapped to their symbols.")
5486
5487 (defconst js2-reserved-word-names
5488 (let ((table (make-hash-table :test 'equal)))
5489 (loop for k in js2-reserved-words
5490 do
5491 (puthash (symbol-name k) 'js2-RESERVED table))
5492 table)
5493 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5494
5495 (defsubst js2-collect-string (buf)
5496 "Convert BUF, a list of chars, to a string.
5497 Reverses BUF before converting."
5498 (cond
5499 ((stringp buf)
5500 buf)
5501 ((null buf) ; for emacs21 compat
5502 "")
5503 (t
5504 (if buf
5505 (apply #'string (nreverse buf))
5506 ""))))
5507
5508 (defun js2-string-to-keyword (s)
5509 "Return token for S, a string, if S is a keyword or reserved word.
5510 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5511 (or (gethash s js2-keyword-names)
5512 (gethash s js2-reserved-word-names)))
5513
5514 (defsubst js2-ts-set-char-token-bounds ()
5515 "Used when next token is one character."
5516 (setq js2-token-beg (1- js2-ts-cursor)
5517 js2-token-end js2-ts-cursor))
5518
5519 (defsubst js2-ts-return (token)
5520 "Return an N-character TOKEN from `js2-get-token'.
5521 Updates `js2-token-end' accordingly."
5522 (setq js2-token-end js2-ts-cursor)
5523 (throw 'return token))
5524
5525 (defsubst js2-x-digit-to-int (c accumulator)
5526 "Build up a hex number.
5527 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5528 corresponding number. Otherwise return -1."
5529 (catch 'return
5530 (catch 'check
5531 ;; Use 0..9 < A..Z < a..z
5532 (cond
5533 ((<= c ?9)
5534 (decf c ?0)
5535 (if (<= 0 c)
5536 (throw 'check nil)))
5537 ((<= c ?F)
5538 (when (<= ?A c)
5539 (decf c (- ?A 10))
5540 (throw 'check nil)))
5541 ((<= c ?f)
5542 (when (<= ?a c)
5543 (decf c (- ?a 10))
5544 (throw 'check nil))))
5545 (throw 'return -1))
5546 (logior c (lsh accumulator 4))))
5547
5548 (defun js2-get-token ()
5549 "Return next JavaScript token, an int such as js2-RETURN."
5550 (let (c
5551 c1
5552 identifier-start
5553 is-unicode-escape-start
5554 contains-escape
5555 escape-val
5556 escape-start
5557 str
5558 result
5559 base
5560 is-integer
5561 quote-char
5562 val
5563 look-for-slash
5564 continue)
5565 (catch 'return
5566 (while t
5567 ;; Eat whitespace, possibly sensitive to newlines.
5568 (setq continue t)
5569 (while continue
5570 (setq c (js2-get-char))
5571 (cond
5572 ((eq c js2-EOF_CHAR)
5573 (js2-ts-set-char-token-bounds)
5574 (throw 'return js2-EOF))
5575 ((eq c ?\n)
5576 (js2-ts-set-char-token-bounds)
5577 (setq js2-ts-dirty-line nil)
5578 (throw 'return js2-EOL))
5579 ((not (js2-js-space-p c))
5580 (if (/= c ?-) ; in case end of HTML comment
5581 (setq js2-ts-dirty-line t))
5582 (setq continue nil))))
5583 ;; Assume the token will be 1 char - fixed up below.
5584 (js2-ts-set-char-token-bounds)
5585 (when (eq c ?@)
5586 (throw 'return js2-XMLATTR))
5587 ;; identifier/keyword/instanceof?
5588 ;; watch out for starting with a <backslash>
5589 (cond
5590 ((eq c ?\\)
5591 (setq c (js2-get-char))
5592 (if (eq c ?u)
5593 (setq identifier-start t
5594 is-unicode-escape-start t
5595 js2-ts-string-buffer nil)
5596 (setq identifier-start nil)
5597 (js2-unget-char)
5598 (setq c ?\\)))
5599 (t
5600 (when (setq identifier-start (js2-java-identifier-start-p c))
5601 (setq js2-ts-string-buffer nil)
5602 (js2-add-to-string c))))
5603 (when identifier-start
5604 (setq contains-escape is-unicode-escape-start)
5605 (catch 'break
5606 (while t
5607 (if is-unicode-escape-start
5608 ;; strictly speaking we should probably push-back
5609 ;; all the bad characters if the <backslash>uXXXX
5610 ;; sequence is malformed. But since there isn't a
5611 ;; correct context(is there?) for a bad Unicode
5612 ;; escape sequence in an identifier, we can report
5613 ;; an error here.
5614 (progn
5615 (setq escape-val 0)
5616 (dotimes (i 4)
5617 (setq c (js2-get-char)
5618 escape-val (js2-x-digit-to-int c escape-val))
5619 ;; Next check takes care of c < 0 and bad escape
5620 (if (minusp escape-val)
5621 (throw 'break nil)))
5622 (if (minusp escape-val)
5623 (js2-report-scan-error "msg.invalid.escape" t))
5624 (js2-add-to-string escape-val)
5625 (setq is-unicode-escape-start nil))
5626 (setq c (js2-get-char))
5627 (cond
5628 ((eq c ?\\)
5629 (setq c (js2-get-char))
5630 (if (eq c ?u)
5631 (setq is-unicode-escape-start t
5632 contains-escape t)
5633 (js2-report-scan-error "msg.illegal.character" t)))
5634 (t
5635 (if (or (eq c js2-EOF_CHAR)
5636 (not (js2-java-identifier-part-p c)))
5637 (throw 'break nil))
5638 (js2-add-to-string c))))))
5639 (js2-unget-char)
5640 (setq str (js2-get-string-from-buffer))
5641 (unless contains-escape
5642 ;; OPT we shouldn't have to make a string (object!) to
5643 ;; check if it's a keyword.
5644 ;; Return the corresponding token if it's a keyword
5645 (when (setq result (js2-string-to-keyword str))
5646 (if (and (< js2-language-version 170)
5647 (memq result '(js2-LET js2-YIELD)))
5648 ;; LET and YIELD are tokens only in 1.7 and later
5649 (setq result 'js2-NAME))
5650 (if (not (eq result 'js2-RESERVED))
5651 (throw 'return (js2-token-code result)))
5652 (js2-report-warning "msg.reserved.keyword" str)))
5653 ;; If we want to intern these as Rhino does, just use (intern str)
5654 (setq js2-ts-string str)
5655 (throw 'return js2-NAME)) ; end identifier/kwd check
5656 ;; is it a number?
5657 (when (or (js2-digit-p c)
5658 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5659 (setq js2-ts-string-buffer nil
5660 base 10)
5661 (when (eq c ?0)
5662 (setq c (js2-get-char))
5663 (cond
5664 ((or (eq c ?x) (eq c ?X))
5665 (setq base 16)
5666 (setq c (js2-get-char)))
5667 ((js2-digit-p c)
5668 (setq base 8))
5669 (t
5670 (js2-add-to-string ?0))))
5671 (if (eq base 16)
5672 (while (<= 0 (js2-x-digit-to-int c 0))
5673 (js2-add-to-string c)
5674 (setq c (js2-get-char)))
5675 (while (and (<= ?0 c) (<= c ?9))
5676 ;; We permit 08 and 09 as decimal numbers, which
5677 ;; makes our behavior a superset of the ECMA
5678 ;; numeric grammar. We might not always be so
5679 ;; permissive, so we warn about it.
5680 (when (and (eq base 8) (>= c ?8))
5681 (js2-report-warning "msg.bad.octal.literal"
5682 (if (eq c ?8) "8" "9"))
5683 (setq base 10))
5684 (js2-add-to-string c)
5685 (setq c (js2-get-char))))
5686 (setq is-integer t)
5687 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5688 (setq is-integer nil)
5689 (when (eq c ?.)
5690 (loop do
5691 (js2-add-to-string c)
5692 (setq c (js2-get-char))
5693 while (js2-digit-p c)))
5694 (when (memq c '(?e ?E))
5695 (js2-add-to-string c)
5696 (setq c (js2-get-char))
5697 (when (memq c '(?+ ?-))
5698 (js2-add-to-string c)
5699 (setq c (js2-get-char)))
5700 (unless (js2-digit-p c)
5701 (js2-report-scan-error "msg.missing.exponent" t))
5702 (loop do
5703 (js2-add-to-string c)
5704 (setq c (js2-get-char))
5705 while (js2-digit-p c))))
5706 (js2-unget-char)
5707 (setq js2-ts-string (js2-get-string-from-buffer)
5708 js2-ts-number
5709 (if (and (eq base 10) (not is-integer))
5710 (string-to-number js2-ts-string)
5711 ;; TODO: call runtime number-parser. Some of it is in
5712 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5713 (string-to-number js2-ts-string)))
5714 (throw 'return js2-NUMBER))
5715 ;; is it a string?
5716 (when (memq c '(?\" ?\'))
5717 ;; We attempt to accumulate a string the fast way, by
5718 ;; building it directly out of the reader. But if there
5719 ;; are any escaped characters in the string, we revert to
5720 ;; building it out of a string buffer.
5721 (setq quote-char c
5722 js2-ts-string-buffer nil
5723 c (js2-get-char))
5724 (catch 'break
5725 (while (/= c quote-char)
5726 (catch 'continue
5727 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5728 (js2-unget-char)
5729 (setq js2-token-end js2-ts-cursor)
5730 (js2-report-error "msg.unterminated.string.lit")
5731 (throw 'return js2-STRING))
5732 (when (eq c ?\\)
5733 ;; We've hit an escaped character
5734 (setq c (js2-get-char))
5735 (case c
5736 (?b (setq c ?\b))
5737 (?f (setq c ?\f))
5738 (?n (setq c ?\n))
5739 (?r (setq c ?\r))
5740 (?t (setq c ?\t))
5741 (?v (setq c ?\v))
5742 (?u
5743 (setq c1 (js2-read-unicode-escape))
5744 (if js2-parse-ide-mode
5745 (if c1
5746 (progn
5747 ;; just copy the string in IDE-mode
5748 (js2-add-to-string ?\\)
5749 (js2-add-to-string ?u)
5750 (dotimes (i 3)
5751 (js2-add-to-string (js2-get-char)))
5752 (setq c (js2-get-char))) ; added at end of loop
5753 ;; flag it as an invalid escape
5754 (js2-report-warning "msg.invalid.escape"
5755 nil (- js2-ts-cursor 2) 6))
5756 ;; Get 4 hex digits; if the u escape is not
5757 ;; followed by 4 hex digits, use 'u' + the
5758 ;; literal character sequence that follows.
5759 (js2-add-to-string ?u)
5760 (setq escape-val 0)
5761 (dotimes (i 4)
5762 (setq c (js2-get-char)
5763 escape-val (js2-x-digit-to-int c escape-val))
5764 (if (minusp escape-val)
5765 (throw 'continue nil))
5766 (js2-add-to-string c))
5767 ;; prepare for replace of stored 'u' sequence by escape value
5768 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5769 c escape-val)))
5770 (?x
5771 ;; Get 2 hex digits, defaulting to 'x'+literal
5772 ;; sequence, as above.
5773 (setq c (js2-get-char)
5774 escape-val (js2-x-digit-to-int c 0))
5775 (if (minusp escape-val)
5776 (progn
5777 (js2-add-to-string ?x)
5778 (throw 'continue nil))
5779 (setq c1 c
5780 c (js2-get-char)
5781 escape-val (js2-x-digit-to-int c escape-val))
5782 (if (minusp escape-val)
5783 (progn
5784 (js2-add-to-string ?x)
5785 (js2-add-to-string c1)
5786 (throw 'continue nil))
5787 ;; got 2 hex digits
5788 (setq c escape-val))))
5789 (?\n
5790 ;; Remove line terminator after escape to follow
5791 ;; SpiderMonkey and C/C++
5792 (setq c (js2-get-char))
5793 (throw 'continue nil))
5794 (t
5795 (when (and (<= ?0 c) (< c ?8))
5796 (setq val (- c ?0)
5797 c (js2-get-char))
5798 (when (and (<= ?0 c) (< c ?8))
5799 (setq val (- (+ (* 8 val) c) ?0)
5800 c (js2-get-char))
5801 (when (and (<= ?0 c)
5802 (< c ?8)
5803 (< val #o37))
5804 ;; c is 3rd char of octal sequence only
5805 ;; if the resulting val <= 0377
5806 (setq val (- (+ (* 8 val) c) ?0)
5807 c (js2-get-char))))
5808 (js2-unget-char)
5809 (setq c val)))))
5810 (js2-add-to-string c)
5811 (setq c (js2-get-char)))))
5812 (setq js2-ts-string (js2-get-string-from-buffer))
5813 (throw 'return js2-STRING))
5814 (case c
5815 (?\;
5816 (throw 'return js2-SEMI))
5817 (?\[
5818 (throw 'return js2-LB))
5819 (?\]
5820 (throw 'return js2-RB))
5821 (?{
5822 (throw 'return js2-LC))
5823 (?}
5824 (throw 'return js2-RC))
5825 (?\(
5826 (throw 'return js2-LP))
5827 (?\)
5828 (throw 'return js2-RP))
5829 (?,
5830 (throw 'return js2-COMMA))
5831 (??
5832 (throw 'return js2-HOOK))
5833 (?:
5834 (if (js2-match-char ?:)
5835 (js2-ts-return js2-COLONCOLON)
5836 (throw 'return js2-COLON)))
5837 (?.
5838 (if (js2-match-char ?.)
5839 (if (js2-match-char ?.)
5840 (js2-ts-return js2-TRIPLEDOT)
5841 (js2-ts-return js2-DOTDOT))
5842 (if (js2-match-char ?\()
5843 (js2-ts-return js2-DOTQUERY)
5844 (throw 'return js2-DOT))))
5845 (?|
5846 (if (js2-match-char ?|)
5847 (throw 'return js2-OR)
5848 (if (js2-match-char ?=)
5849 (js2-ts-return js2-ASSIGN_BITOR)
5850 (throw 'return js2-BITOR))))
5851 (?^
5852 (if (js2-match-char ?=)
5853 (js2-ts-return js2-ASSIGN_BITOR)
5854 (throw 'return js2-BITXOR)))
5855 (?&
5856 (if (js2-match-char ?&)
5857 (throw 'return js2-AND)
5858 (if (js2-match-char ?=)
5859 (js2-ts-return js2-ASSIGN_BITAND)
5860 (throw 'return js2-BITAND))))
5861 (?=
5862 (if (js2-match-char ?=)
5863 (if (js2-match-char ?=)
5864 (js2-ts-return js2-SHEQ)
5865 (throw 'return js2-EQ))
5866 (throw 'return js2-ASSIGN)))
5867 (?!
5868 (if (js2-match-char ?=)
5869 (if (js2-match-char ?=)
5870 (js2-ts-return js2-SHNE)
5871 (js2-ts-return js2-NE))
5872 (throw 'return js2-NOT)))
5873 (?<
5874 ;; NB:treat HTML begin-comment as comment-till-eol
5875 (when (js2-match-char ?!)
5876 (when (js2-match-char ?-)
5877 (when (js2-match-char ?-)
5878 (js2-skip-line)
5879 (setq js2-ts-comment-type 'html)
5880 (throw 'return js2-COMMENT)))
5881 (js2-unget-char))
5882 (if (js2-match-char ?<)
5883 (if (js2-match-char ?=)
5884 (js2-ts-return js2-ASSIGN_LSH)
5885 (js2-ts-return js2-LSH))
5886 (if (js2-match-char ?=)
5887 (js2-ts-return js2-LE)
5888 (throw 'return js2-LT))))
5889 (?>
5890 (if (js2-match-char ?>)
5891 (if (js2-match-char ?>)
5892 (if (js2-match-char ?=)
5893 (js2-ts-return js2-ASSIGN_URSH)
5894 (js2-ts-return js2-URSH))
5895 (if (js2-match-char ?=)
5896 (js2-ts-return js2-ASSIGN_RSH)
5897 (js2-ts-return js2-RSH)))
5898 (if (js2-match-char ?=)
5899 (js2-ts-return js2-GE)
5900 (throw 'return js2-GT))))
5901 (?*
5902 (if (js2-match-char ?=)
5903 (js2-ts-return js2-ASSIGN_MUL)
5904 (throw 'return js2-MUL)))
5905 (?/
5906 ;; is it a // comment?
5907 (when (js2-match-char ?/)
5908 (setq js2-token-beg (- js2-ts-cursor 2))
5909 (js2-skip-line)
5910 (setq js2-ts-comment-type 'line)
5911 ;; include newline so highlighting goes to end of window
5912 (incf js2-token-end)
5913 (throw 'return js2-COMMENT))
5914 ;; is it a /* comment?
5915 (when (js2-match-char ?*)
5916 (setq look-for-slash nil
5917 js2-token-beg (- js2-ts-cursor 2)
5918 js2-ts-comment-type
5919 (if (js2-match-char ?*)
5920 (progn
5921 (setq look-for-slash t)
5922 'jsdoc)
5923 'block))
5924 (while t
5925 (setq c (js2-get-char))
5926 (cond
5927 ((eq c js2-EOF_CHAR)
5928 (setq js2-token-end (1- js2-ts-cursor))
5929 (js2-report-error "msg.unterminated.comment")
5930 (throw 'return js2-COMMENT))
5931 ((eq c ?*)
5932 (setq look-for-slash t))
5933 ((eq c ?/)
5934 (if look-for-slash
5935 (js2-ts-return js2-COMMENT)))
5936 (t
5937 (setq look-for-slash nil
5938 js2-token-end js2-ts-cursor)))))
5939 (if (js2-match-char ?=)
5940 (js2-ts-return js2-ASSIGN_DIV)
5941 (throw 'return js2-DIV)))
5942 (?#
5943 (when js2-skip-preprocessor-directives
5944 (js2-skip-line)
5945 (setq js2-ts-comment-type 'preprocessor
5946 js2-token-end js2-ts-cursor)
5947 (throw 'return js2-COMMENT))
5948 (throw 'return js2-ERROR))
5949 (?%
5950 (if (js2-match-char ?=)
5951 (js2-ts-return js2-ASSIGN_MOD)
5952 (throw 'return js2-MOD)))
5953 (?~
5954 (throw 'return js2-BITNOT))
5955 (?+
5956 (if (js2-match-char ?=)
5957 (js2-ts-return js2-ASSIGN_ADD)
5958 (if (js2-match-char ?+)
5959 (js2-ts-return js2-INC)
5960 (throw 'return js2-ADD))))
5961 (?-
5962 (cond
5963 ((js2-match-char ?=)
5964 (setq c js2-ASSIGN_SUB))
5965 ((js2-match-char ?-)
5966 (unless js2-ts-dirty-line
5967 ;; treat HTML end-comment after possible whitespace
5968 ;; after line start as comment-until-eol
5969 (when (js2-match-char ?>)
5970 (js2-skip-line)
5971 (setq js2-ts-comment-type 'html)
5972 (throw 'return js2-COMMENT)))
5973 (setq c js2-DEC))
5974 (t
5975 (setq c js2-SUB)))
5976 (setq js2-ts-dirty-line t)
5977 (js2-ts-return c))
5978 (otherwise
5979 (js2-report-scan-error "msg.illegal.character")))))))
5980
5981 (defun js2-read-regexp (start-token)
5982 "Called by parser when it gets / or /= in literal context."
5983 (let (c
5984 err
5985 in-class ; inside a '[' .. ']' character-class
5986 flags
5987 (continue t))
5988 (setq js2-token-beg js2-ts-cursor
5989 js2-ts-string-buffer nil
5990 js2-ts-regexp-flags nil)
5991 (if (eq start-token js2-ASSIGN_DIV)
5992 ;; mis-scanned /=
5993 (js2-add-to-string ?=)
5994 (if (not (eq start-token js2-DIV))
5995 (error "failed assertion")))
5996 (while (and (not err)
5997 (or (/= (setq c (js2-get-char)) ?/)
5998 in-class))
5999 (cond
6000 ((or (= c ?\n)
6001 (= c js2-EOF_CHAR))
6002 (setq js2-token-end (1- js2-ts-cursor)
6003 err t
6004 js2-ts-string (js2-collect-string js2-ts-string-buffer))
6005 (js2-report-error "msg.unterminated.re.lit"))
6006 (t (cond
6007 ((= c ?\\)
6008 (js2-add-to-string c)
6009 (setq c (js2-get-char)))
6010 ((= c ?\[)
6011 (setq in-class t))
6012 ((= c ?\])
6013 (setq in-class nil)))
6014 (js2-add-to-string c))))
6015 (unless err
6016 (while continue
6017 (cond
6018 ((js2-match-char ?g)
6019 (push ?g flags))
6020 ((js2-match-char ?i)
6021 (push ?i flags))
6022 ((js2-match-char ?m)
6023 (push ?m flags))
6024 (t
6025 (setq continue nil))))
6026 (if (js2-alpha-p (js2-peek-char))
6027 (js2-report-scan-error "msg.invalid.re.flag" t
6028 js2-ts-cursor 1))
6029 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6030 js2-ts-regexp-flags (js2-collect-string flags)
6031 js2-token-end js2-ts-cursor)
6032 ;; tell `parse-partial-sexp' to ignore this range of chars
6033 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6034
6035 (defun js2-get-first-xml-token ()
6036 (setq js2-ts-xml-open-tags-count 0
6037 js2-ts-is-xml-attribute nil
6038 js2-ts-xml-is-tag-content nil)
6039 (js2-unget-char)
6040 (js2-get-next-xml-token))
6041
6042 (defsubst js2-xml-discard-string ()
6043 "Throw away the string in progress and flag an XML parse error."
6044 (setq js2-ts-string-buffer nil
6045 js2-ts-string nil)
6046 (js2-report-scan-error "msg.XML.bad.form" t))
6047
6048 (defun js2-get-next-xml-token ()
6049 (setq js2-ts-string-buffer nil ; for recording the XML
6050 js2-token-beg js2-ts-cursor)
6051 (let (c result)
6052 (setq result
6053 (catch 'return
6054 (while t
6055 (setq c (js2-get-char))
6056 (cond
6057 ((= c js2-EOF_CHAR)
6058 (throw 'return js2-ERROR))
6059 (js2-ts-xml-is-tag-content
6060 (case c
6061 (?>
6062 (js2-add-to-string c)
6063 (setq js2-ts-xml-is-tag-content nil
6064 js2-ts-is-xml-attribute nil))
6065 (?/
6066 (js2-add-to-string c)
6067 (when (eq ?> (js2-peek-char))
6068 (setq c (js2-get-char))
6069 (js2-add-to-string c)
6070 (setq js2-ts-xml-is-tag-content nil)
6071 (decf js2-ts-xml-open-tags-count)))
6072 (?{
6073 (js2-unget-char)
6074 (setq js2-ts-string (js2-get-string-from-buffer))
6075 (throw 'return js2-XML))
6076 ((?\' ?\")
6077 (js2-add-to-string c)
6078 (unless (js2-read-quoted-string c)
6079 (throw 'return js2-ERROR)))
6080 (?=
6081 (js2-add-to-string c)
6082 (setq js2-ts-is-xml-attribute t))
6083 ((? ?\t ?\r ?\n)
6084 (js2-add-to-string c))
6085 (t
6086 (js2-add-to-string c)
6087 (setq js2-ts-is-xml-attribute nil)))
6088 (when (and (not js2-ts-xml-is-tag-content)
6089 (zerop js2-ts-xml-open-tags-count))
6090 (setq js2-ts-string (js2-get-string-from-buffer))
6091 (throw 'return js2-XMLEND)))
6092 (t
6093 ;; else not tag content
6094 (case c
6095 (?<
6096 (js2-add-to-string c)
6097 (setq c (js2-peek-char))
6098 (case c
6099 (?!
6100 (setq c (js2-get-char)) ;; skip !
6101 (js2-add-to-string c)
6102 (setq c (js2-peek-char))
6103 (case c
6104 (?-
6105 (setq c (js2-get-char)) ;; skip -
6106 (js2-add-to-string c)
6107 (if (eq c ?-)
6108 (progn
6109 (js2-add-to-string c)
6110 (unless (js2-read-xml-comment)
6111 (throw 'return js2-ERROR)))
6112 (js2-xml-discard-string)
6113 (throw 'return js2-ERROR)))
6114 (?\[
6115 (setq c (js2-get-char)) ;; skip [
6116 (js2-add-to-string c)
6117 (if (and (= (js2-get-char) ?C)
6118 (= (js2-get-char) ?D)
6119 (= (js2-get-char) ?A)
6120 (= (js2-get-char) ?T)
6121 (= (js2-get-char) ?A)
6122 (= (js2-get-char) ?\[))
6123 (progn
6124 (js2-add-to-string ?C)
6125 (js2-add-to-string ?D)
6126 (js2-add-to-string ?A)
6127 (js2-add-to-string ?T)
6128 (js2-add-to-string ?A)
6129 (js2-add-to-string ?\[)
6130 (unless (js2-read-cdata)
6131 (throw 'return js2-ERROR)))
6132 (js2-xml-discard-string)
6133 (throw 'return js2-ERROR)))
6134 (t
6135 (unless (js2-read-entity)
6136 (throw 'return js2-ERROR))))
6137 ;; allow bare CDATA section
6138 ;; ex) let xml = <![CDATA[ foo bar baz ]]>;
6139 (when (zerop js2-ts-xml-open-tags-count)
6140 (throw 'return js2-XMLEND)))
6141 (??
6142 (setq c (js2-get-char)) ;; skip ?
6143 (js2-add-to-string c)
6144 (unless (js2-read-PI)
6145 (throw 'return js2-ERROR)))
6146 (?/
6147 ;; end tag
6148 (setq c (js2-get-char)) ;; skip /
6149 (js2-add-to-string c)
6150 (when (zerop js2-ts-xml-open-tags-count)
6151 (js2-xml-discard-string)
6152 (throw 'return js2-ERROR))
6153 (setq js2-ts-xml-is-tag-content t)
6154 (decf js2-ts-xml-open-tags-count))
6155 (t
6156 ;; start tag
6157 (setq js2-ts-xml-is-tag-content t)
6158 (incf js2-ts-xml-open-tags-count))))
6159 (?{
6160 (js2-unget-char)
6161 (setq js2-ts-string (js2-get-string-from-buffer))
6162 (throw 'return js2-XML))
6163 (t
6164 (js2-add-to-string c))))))))
6165 (setq js2-token-end js2-ts-cursor)
6166 result))
6167
6168 (defun js2-read-quoted-string (quote)
6169 (let (c)
6170 (catch 'return
6171 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6172 (js2-add-to-string c)
6173 (if (eq c quote)
6174 (throw 'return t)))
6175 (js2-xml-discard-string) ;; throw away string in progress
6176 nil)))
6177
6178 (defun js2-read-xml-comment ()
6179 (let ((c (js2-get-char)))
6180 (catch 'return
6181 (while (/= c js2-EOF_CHAR)
6182 (catch 'continue
6183 (js2-add-to-string c)
6184 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6185 (setq c (js2-get-char))
6186 (js2-add-to-string c)
6187 (if (eq (js2-peek-char) ?>)
6188 (progn
6189 (setq c (js2-get-char)) ;; skip >
6190 (js2-add-to-string c)
6191 (throw 'return t))
6192 (throw 'continue nil)))
6193 (setq c (js2-get-char))))
6194 (js2-xml-discard-string)
6195 nil)))
6196
6197 (defun js2-read-cdata ()
6198 (let ((c (js2-get-char)))
6199 (catch 'return
6200 (while (/= c js2-EOF_CHAR)
6201 (catch 'continue
6202 (js2-add-to-string c)
6203 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6204 (setq c (js2-get-char))
6205 (js2-add-to-string c)
6206 (if (eq (js2-peek-char) ?>)
6207 (progn
6208 (setq c (js2-get-char)) ;; Skip >
6209 (js2-add-to-string c)
6210 (throw 'return t))
6211 (throw 'continue nil)))
6212 (setq c (js2-get-char))))
6213 (js2-xml-discard-string)
6214 nil)))
6215
6216 (defun js2-read-entity ()
6217 (let ((decl-tags 1)
6218 c)
6219 (catch 'return
6220 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6221 (js2-add-to-string c)
6222 (case c
6223 (?<
6224 (incf decl-tags))
6225 (?>
6226 (decf decl-tags)
6227 (if (zerop decl-tags)
6228 (throw 'return t)))))
6229 (js2-xml-discard-string)
6230 nil)))
6231
6232 (defun js2-read-PI ()
6233 "Scan an XML processing instruction."
6234 (let (c)
6235 (catch 'return
6236 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6237 (js2-add-to-string c)
6238 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6239 (setq c (js2-get-char)) ;; Skip >
6240 (js2-add-to-string c)
6241 (throw 'return t)))
6242 (js2-xml-discard-string)
6243 nil)))
6244
6245 (defun js2-scanner-get-line ()
6246 "Return the text of the current scan line."
6247 (buffer-substring (point-at-bol) (point-at-eol)))
6248
6249 ;;; Highlighting
6250
6251 (defsubst js2-set-face (beg end face &optional record)
6252 "Fontify a region. If RECORD is non-nil, record for later."
6253 (when (plusp js2-highlight-level)
6254 (setq beg (min (point-max) beg)
6255 beg (max (point-min) beg)
6256 end (min (point-max) end)
6257 end (max (point-min) end))
6258 (if record
6259 (push (list beg end face) js2-mode-fontifications)
6260 (put-text-property beg end 'font-lock-face face))))
6261
6262 (defsubst js2-set-kid-face (pos kid len face)
6263 "Set-face on a child node.
6264 POS is absolute buffer position of parent.
6265 KID is the child node.
6266 LEN is the length to fontify.
6267 FACE is the face to fontify with."
6268 (js2-set-face (+ pos (js2-node-pos kid))
6269 (+ pos (js2-node-pos kid) (js2-node-len kid))
6270 face))
6271
6272 (defsubst js2-fontify-kwd (start length)
6273 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6274
6275 (defsubst js2-clear-face (beg end)
6276 (remove-text-properties beg end '(font-lock-face nil
6277 help-echo nil
6278 point-entered nil
6279 c-in-sws nil)))
6280
6281 (defconst js2-ecma-global-props
6282 (concat "^"
6283 (regexp-opt
6284 '("Infinity" "NaN" "undefined" "arguments") t)
6285 "$")
6286 "Value properties of the Ecma-262 Global Object.
6287 Shown at or above `js2-highlight-level' 2.")
6288
6289 ;; might want to add the name "arguments" to this list?
6290 (defconst js2-ecma-object-props
6291 (concat "^"
6292 (regexp-opt
6293 '("prototype" "__proto__" "__parent__") t)
6294 "$")
6295 "Value properties of the Ecma-262 Object constructor.
6296 Shown at or above `js2-highlight-level' 2.")
6297
6298 (defconst js2-ecma-global-funcs
6299 (concat
6300 "^"
6301 (regexp-opt
6302 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6303 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6304 "$")
6305 "Function properties of the Ecma-262 Global object.
6306 Shown at or above `js2-highlight-level' 2.")
6307
6308 (defconst js2-ecma-number-props
6309 (concat "^"
6310 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6311 "NEGATIVE_INFINITY"
6312 "POSITIVE_INFINITY") t)
6313 "$")
6314 "Properties of the Ecma-262 Number constructor.
6315 Shown at or above `js2-highlight-level' 2.")
6316
6317 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6318 "Properties of the Ecma-262 Date constructor.
6319 Shown at or above `js2-highlight-level' 2.")
6320
6321 (defconst js2-ecma-math-props
6322 (concat "^"
6323 (regexp-opt
6324 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6325 t)
6326 "$")
6327 "Properties of the Ecma-262 Math object.
6328 Shown at or above `js2-highlight-level' 2.")
6329
6330 (defconst js2-ecma-math-funcs
6331 (concat "^"
6332 (regexp-opt
6333 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6334 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6335 "$")
6336 "Function properties of the Ecma-262 Math object.
6337 Shown at or above `js2-highlight-level' 2.")
6338
6339 (defconst js2-ecma-function-props
6340 (concat
6341 "^"
6342 (regexp-opt
6343 '(;; properties of the Object prototype object
6344 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6345 "toLocaleString" "toString" "valueOf"
6346 ;; properties of the Function prototype object
6347 "apply" "call"
6348 ;; properties of the Array prototype object
6349 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6350 "splice" "unshift"
6351 ;; properties of the String prototype object
6352 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6353 "localeCompare" "match" "replace" "search" "split" "substring"
6354 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6355 "toUpperCase"
6356 ;; properties of the Number prototype object
6357 "toExponential" "toFixed" "toPrecision"
6358 ;; properties of the Date prototype object
6359 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6360 "getMinutes" "getMonth" "getSeconds" "getTime"
6361 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6362 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6363 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6364 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6365 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6366 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6367 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6368 "toTimeString" "toUTCString"
6369 ;; properties of the RegExp prototype object
6370 "exec" "test"
6371 ;; properties of the JSON prototype object
6372 "parse" "stringify"
6373 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6374 "toSource" "__defineGetter__" "__defineSetter__"
6375 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6376 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6377 t)
6378 "$")
6379 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6380 Shown at or above `js2-highlight-level' 3.")
6381
6382 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6383 (let ((target-name (and target
6384 (js2-name-node-p target)
6385 (js2-name-node-name target)))
6386 (prop-name (if prop (js2-name-node-name prop)))
6387 (level1 (>= js2-highlight-level 1))
6388 (level2 (>= js2-highlight-level 2))
6389 (level3 (>= js2-highlight-level 3))
6390 pos
6391 face)
6392 (when level2
6393 (if call-p
6394 (cond
6395 ((and target prop)
6396 (cond
6397 ((and level3 (string-match js2-ecma-function-props prop-name))
6398 (setq face 'font-lock-builtin-face))
6399 ((and target-name prop)
6400 (cond
6401 ((string= target-name "Date")
6402 (if (string-match js2-ecma-date-props prop-name)
6403 (setq face 'font-lock-builtin-face)))
6404 ((string= target-name "Math")
6405 (if (string-match js2-ecma-math-funcs prop-name)
6406 (setq face 'font-lock-builtin-face)))))))
6407 (prop
6408 (if (string-match js2-ecma-global-funcs prop-name)
6409 (setq face 'font-lock-builtin-face))))
6410 (cond
6411 ((and target prop)
6412 (cond
6413 ((string= target-name "Number")
6414 (if (string-match js2-ecma-number-props prop-name)
6415 (setq face 'font-lock-constant-face)))
6416 ((string= target-name "Math")
6417 (if (string-match js2-ecma-math-props prop-name)
6418 (setq face 'font-lock-constant-face)))))
6419 (prop
6420 (if (string-match js2-ecma-object-props prop-name)
6421 (setq face 'font-lock-constant-face)))))
6422 (when face
6423 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6424 (js2-node-pos prop))) ; relative
6425 (+ pos (js2-node-len prop))
6426 face 'record)))))
6427
6428 (defun js2-parse-highlight-member-expr-node (node)
6429 "Perform syntax highlighting of EcmaScript built-in properties.
6430 The variable `js2-highlight-level' governs this highighting."
6431 (let (face target prop name pos end parent call-p callee)
6432 (cond
6433 ;; case 1: simple name, e.g. foo
6434 ((js2-name-node-p node)
6435 (setq name (js2-name-node-name node))
6436 ;; possible for name to be nil in rare cases - saw it when
6437 ;; running js2-mode on an elisp buffer. Might as well try to
6438 ;; make it so js2-mode never barfs.
6439 (when name
6440 (setq face (if (string-match js2-ecma-global-props name)
6441 'font-lock-constant-face))
6442 (when face
6443 (setq pos (js2-node-pos node)
6444 end (+ pos (js2-node-len node)))
6445 (js2-set-face pos end face 'record))))
6446 ;; case 2: property access or function call
6447 ((or (js2-prop-get-node-p node)
6448 ;; highlight function call if expr is a prop-get node
6449 ;; or a plain name (i.e. unqualified function call)
6450 (and (setq call-p (js2-call-node-p node))
6451 (setq callee (js2-call-node-target node)) ; separate setq!
6452 (or (js2-prop-get-node-p callee)
6453 (js2-name-node-p callee))))
6454 (setq parent node
6455 node (if call-p callee node))
6456 (if (and call-p (js2-name-node-p callee))
6457 (setq prop callee)
6458 (setq target (js2-prop-get-node-left node)
6459 prop (js2-prop-get-node-right node)))
6460 (cond
6461 ((js2-name-node-p target)
6462 (if (js2-name-node-p prop)
6463 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6464 (js2-parse-highlight-prop-get parent target prop call-p)
6465 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6466 (js2-parse-highlight-prop-get parent target nil call-p)))
6467 ((js2-name-node-p prop)
6468 ;; case 2c: complex target, simple name, e.g. x[y].bar
6469 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6470
6471 (defun js2-parse-highlight-member-expr-fn-name (expr)
6472 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6473 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6474 We currently only handle the case where the last component is a prop-get
6475 of a simple name. Called before EXPR has a parent node."
6476 (let (pos
6477 (name (and (js2-prop-get-node-p expr)
6478 (js2-prop-get-node-right expr))))
6479 (when (js2-name-node-p name)
6480 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6481 (js2-node-pos name)))
6482 (+ pos (js2-node-len name))
6483 'font-lock-function-name-face
6484 'record))))
6485
6486 ;; source: http://jsdoc.sourceforge.net/
6487 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6488 ;; allows type specifications, and needs work before entering the wild.
6489
6490 (defconst js2-jsdoc-param-tag-regexp
6491 (concat "^\\s-*\\*+\\s-*\\(@"
6492 "\\(?:param\\|argument\\)"
6493 "\\)"
6494 "\\s-*\\({[^}]+}\\)?" ; optional type
6495 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6496 "\\>")
6497 "Matches jsdoc tags with optional type and optional param name.")
6498
6499 (defconst js2-jsdoc-typed-tag-regexp
6500 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6501 (regexp-opt
6502 '("enum"
6503 "extends"
6504 "field"
6505 "id"
6506 "implements"
6507 "lends"
6508 "mods"
6509 "requires"
6510 "return"
6511 "returns"
6512 "throw"
6513 "throws"))
6514 "\\)\\)\\s-*\\({[^}]+}\\)?")
6515 "Matches jsdoc tags with optional type.")
6516
6517 (defconst js2-jsdoc-arg-tag-regexp
6518 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6519 (regexp-opt
6520 '("alias"
6521 "augments"
6522 "borrows"
6523 "bug"
6524 "base"
6525 "config"
6526 "default"
6527 "define"
6528 "exception"
6529 "function"
6530 "member"
6531 "memberOf"
6532 "name"
6533 "namespace"
6534 "property"
6535 "since"
6536 "suppress"
6537 "this"
6538 "throws"
6539 "type"
6540 "version"))
6541 "\\)\\)\\s-+\\([^ \t]+\\)")
6542 "Matches jsdoc tags with a single argument.")
6543
6544 (defconst js2-jsdoc-empty-tag-regexp
6545 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6546 (regexp-opt
6547 '("addon"
6548 "author"
6549 "class"
6550 "const"
6551 "constant"
6552 "constructor"
6553 "constructs"
6554 "deprecated"
6555 "desc"
6556 "description"
6557 "event"
6558 "example"
6559 "exec"
6560 "export"
6561 "fileoverview"
6562 "final"
6563 "function"
6564 "hidden"
6565 "ignore"
6566 "implicitCast"
6567 "inheritDoc"
6568 "inner"
6569 "interface"
6570 "license"
6571 "noalias"
6572 "noshadow"
6573 "notypecheck"
6574 "override"
6575 "owner"
6576 "preserve"
6577 "preserveTry"
6578 "private"
6579 "protected"
6580 "public"
6581 "static"
6582 "supported"
6583 ))
6584 "\\)\\)\\s-*")
6585 "Matches empty jsdoc tags.")
6586
6587 (defconst js2-jsdoc-link-tag-regexp
6588 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6589 "Matches a jsdoc link or code tag.")
6590
6591 (defconst js2-jsdoc-see-tag-regexp
6592 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6593 "Matches a jsdoc @see tag.")
6594
6595 (defconst js2-jsdoc-html-tag-regexp
6596 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6597 "Matches a simple (no attributes) html start- or end-tag.")
6598
6599 (defsubst js2-jsdoc-highlight-helper ()
6600 (js2-set-face (match-beginning 1)
6601 (match-end 1)
6602 'js2-jsdoc-tag-face)
6603 (if (match-beginning 2)
6604 (if (save-excursion
6605 (goto-char (match-beginning 2))
6606 (= (char-after) ?{))
6607 (js2-set-face (1+ (match-beginning 2))
6608 (1- (match-end 2))
6609 'js2-jsdoc-type-face)
6610 (js2-set-face (match-beginning 2)
6611 (match-end 2)
6612 'js2-jsdoc-value-face)))
6613 (if (match-beginning 3)
6614 (js2-set-face (match-beginning 3)
6615 (match-end 3)
6616 'js2-jsdoc-value-face)))
6617
6618 (defun js2-highlight-jsdoc (ast)
6619 "Highlight doc comment tags."
6620 (let ((comments (js2-ast-root-comments ast))
6621 beg end)
6622 (save-excursion
6623 (dolist (node comments)
6624 (when (eq (js2-comment-node-format node) 'jsdoc)
6625 (setq beg (js2-node-abs-pos node)
6626 end (+ beg (js2-node-len node)))
6627 (save-restriction
6628 (narrow-to-region beg end)
6629 (dolist (re (list js2-jsdoc-param-tag-regexp
6630 js2-jsdoc-typed-tag-regexp
6631 js2-jsdoc-arg-tag-regexp
6632 js2-jsdoc-link-tag-regexp
6633 js2-jsdoc-see-tag-regexp
6634 js2-jsdoc-empty-tag-regexp))
6635 (goto-char beg)
6636 (while (re-search-forward re nil t)
6637 (js2-jsdoc-highlight-helper)))
6638 ;; simple highlighting for html tags
6639 (goto-char beg)
6640 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6641 (js2-set-face (match-beginning 1)
6642 (match-end 1)
6643 'js2-jsdoc-html-tag-delimiter-face)
6644 (js2-set-face (match-beginning 2)
6645 (match-end 2)
6646 'js2-jsdoc-html-tag-name-face)
6647 (js2-set-face (match-beginning 3)
6648 (match-end 3)
6649 'js2-jsdoc-html-tag-delimiter-face))))))))
6650
6651 (defun js2-highlight-assign-targets (node left right)
6652 "Highlight function properties and external variables."
6653 (let (leftpos end name)
6654 ;; highlight vars and props assigned function values
6655 (when (js2-function-node-p right)
6656 (cond
6657 ;; var foo = function() {...}
6658 ((js2-name-node-p left)
6659 (setq name left))
6660 ;; foo.bar.baz = function() {...}
6661 ((and (js2-prop-get-node-p left)
6662 (js2-name-node-p (js2-prop-get-node-right left)))
6663 (setq name (js2-prop-get-node-right left))))
6664 (when name
6665 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6666 (+ leftpos (js2-node-len name))
6667 'font-lock-function-name-face
6668 'record)))))
6669
6670 (defun js2-record-name-node (node)
6671 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6672 later. NODE must be a name node."
6673 (let (leftpos end)
6674 (push (list node js2-current-scope
6675 (setq leftpos (js2-node-abs-pos node))
6676 (setq end (+ leftpos (js2-node-len node))))
6677 js2-recorded-identifiers)))
6678
6679 (defun js2-highlight-undeclared-vars ()
6680 "After entire parse is finished, look for undeclared variable references.
6681 We have to wait until entire buffer is parsed, since JavaScript permits var
6682 decls to occur after they're used.
6683
6684 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6685 it is considered declared."
6686 (let (name)
6687 (dolist (entry js2-recorded-identifiers)
6688 (destructuring-bind (name-node scope pos end) entry
6689 (setq name (js2-name-node-name name-node))
6690 (unless (or (member name js2-global-externs)
6691 (member name js2-default-externs)
6692 (member name js2-additional-externs)
6693 (js2-get-defining-scope scope name))
6694 (js2-set-face pos end 'js2-external-variable-face 'record)
6695 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6696 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6697 (setq js2-recorded-identifiers nil)))
6698
6699 ;;; IMenu support
6700
6701 ;; We currently only support imenu, but eventually should support speedbar and
6702 ;; possibly other browsing mechanisms.
6703
6704 ;; The basic strategy is to identify function assignment targets of the form
6705 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6706 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6707 ;; for imenu after parsing is finished.
6708
6709 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6710 ;; JavaScript, and the general problem is undecidable. However, several forms
6711 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6712 ;; include:
6713
6714 ;; function foo() -- function declaration
6715 ;; foo = function() -- function expression assigned to variable
6716 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6717 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6718 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6719 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6720 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6721 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6722 ;; function foo() {function bar() {...}} -- nested function
6723 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6724
6725 ;; This list boils down to a few forms that can be combined recursively.
6726 ;; Top-level named function declarations include both the left-hand (name)
6727 ;; and the right-hand (function value) expressions needed to produce an imenu
6728 ;; entry. The other "right-hand" forms we need to look for are:
6729 ;; - functions declared as props/getters/setters in object literals
6730 ;; - nested named function declarations
6731 ;; The "left-hand" expressions that functions can be assigned to include:
6732 ;; - local/global variables
6733 ;; - nested property-get expressions like a.b.c.d
6734 ;; - element gets like foo[10] or foo['bar'] where the index
6735 ;; expression can be trivially converted to a property name. They
6736 ;; effectively then become property gets.
6737
6738 ;; All the different definition types are canonicalized into the form
6739 ;; foo.bar.baz = position-of-function-keyword
6740
6741 ;; We need to build a trie-like structure for imenu. As an example,
6742 ;; consider the following JavaScript code:
6743
6744 ;; a = function() {...} // function at position 5
6745 ;; b = function() {...} // function at position 25
6746 ;; foo = function() {...} // function at position 100
6747 ;; foo.bar = function() {...} // function at position 200
6748 ;; foo.bar.baz = function() {...} // function at position 300
6749 ;; foo.bar.zab = function() {...} // function at position 400
6750
6751 ;; During parsing we accumulate an entry for each definition in
6752 ;; the variable `js2-imenu-recorder', like so:
6753
6754 ;; '((fn a 5)
6755 ;; (fn b 25)
6756 ;; (fn foo 100)
6757 ;; (fn foo bar 200)
6758 ;; (fn foo bar baz 300)
6759 ;; (fn foo bar zab 400))
6760
6761 ;; Where 'fn' is the respective function node.
6762 ;; After parsing these entries are merged into this alist-trie:
6763
6764 ;; '((a . 1)
6765 ;; (b . 2)
6766 ;; (foo (<definition> . 3)
6767 ;; (bar (<definition> . 6)
6768 ;; (baz . 100)
6769 ;; (zab . 200))))
6770
6771 ;; Note the wacky need for a <definition> name. The token can be anything
6772 ;; that isn't a valid JavaScript identifier, because you might make foo
6773 ;; a function and then start setting properties on it that are also functions.
6774
6775 (defsubst js2-prop-node-name (node)
6776 "Return the name of a node that may be a property-get/property-name.
6777 If NODE is not a valid name-node, string-node or integral number-node,
6778 returns nil. Otherwise returns the string name/value of the node."
6779 (cond
6780 ((js2-name-node-p node)
6781 (js2-name-node-name node))
6782 ((js2-string-node-p node)
6783 (js2-string-node-value node))
6784 ((and (js2-number-node-p node)
6785 (string-match "^[0-9]+$" (js2-number-node-value node)))
6786 (js2-number-node-value node))
6787 ((js2-this-node-p node)
6788 "this")))
6789
6790 (defsubst js2-node-qname-component (node)
6791 "Return the name of this node, if it contributes to a qname.
6792 Returns nil if the node doesn't contribute."
6793 (copy-sequence
6794 (or (js2-prop-node-name node)
6795 (if (and (js2-function-node-p node)
6796 (js2-function-node-name node))
6797 (js2-name-node-name (js2-function-node-name node))))))
6798
6799 (defsubst js2-record-imenu-entry (fn-node qname pos)
6800 "Add an entry to `js2-imenu-recorder'.
6801 FN-NODE should be the current item's function node.
6802
6803 Associate FN-NODE with its QNAME for later lookup.
6804 This is used in postprocessing the chain list. For each chain, we find
6805 the parent function, look up its qname, then prepend a copy of it to the chain."
6806 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6807 (unless js2-imenu-function-map
6808 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6809 (puthash fn-node qname js2-imenu-function-map))
6810
6811 (defun js2-record-imenu-functions (node &optional var)
6812 "Record function definitions for imenu.
6813 NODE is a function node or an object literal.
6814 VAR, if non-nil, is the expression that NODE is being assigned to.
6815 When passed arguments of wrong type, does nothing."
6816 (when js2-parse-ide-mode
6817 (let ((fun-p (js2-function-node-p node))
6818 qname left fname-node pos)
6819 (cond
6820 ;; non-anonymous function declaration?
6821 ((and fun-p
6822 (not var)
6823 (setq fname-node (js2-function-node-name node)))
6824 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6825 ;; for remaining forms, compute left-side tree branch first
6826 ((and var (setq qname (js2-compute-nested-prop-get var)))
6827 (cond
6828 ;; foo.bar.baz = function
6829 (fun-p
6830 (js2-record-imenu-entry node qname (js2-node-pos node)))
6831 ;; foo.bar.baz = object-literal
6832 ;; look for nested functions: {a: {b: function() {...} }}
6833 ((js2-object-node-p node)
6834 ;; Node position here is still absolute, since the parser
6835 ;; passes the assignment target and value expressions
6836 ;; to us before they are added as children of the assignment node.
6837 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6838
6839 (defun js2-compute-nested-prop-get (node)
6840 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6841 component nodes as a list. Otherwise return nil. Element-gets are treated
6842 as property-gets if the index expression is a string, or a positive integer."
6843 (let (left right head)
6844 (cond
6845 ((or (js2-name-node-p node)
6846 (js2-this-node-p node))
6847 (list node))
6848 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6849 ((js2-prop-get-node-p node) ; foo.bar
6850 (setq left (js2-prop-get-node-left node)
6851 right (js2-prop-get-node-right node))
6852 (if (setq head (js2-compute-nested-prop-get left))
6853 (nconc head (list right))))
6854 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6855 (setq left (js2-elem-get-node-target node)
6856 right (js2-elem-get-node-element node))
6857 (if (or (js2-string-node-p right) ; ['bar']
6858 (and (js2-number-node-p right) ; [10]
6859 (string-match "^[0-9]+$"
6860 (js2-number-node-value right))))
6861 (if (setq head (js2-compute-nested-prop-get left))
6862 (nconc head (list right))))))))
6863
6864 (defun js2-record-object-literal (node qname pos)
6865 "Recursively process an object literal looking for functions.
6866 NODE is an object literal that is the right-hand child of an assignment
6867 expression. QNAME is a list of nodes representing the assignment target,
6868 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6869 POS is the absolute position of the node.
6870 We do a depth-first traversal of NODE. For any functions we find,
6871 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6872 (let (left right prop-qname)
6873 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6874 (let ((left (js2-infix-node-left e))
6875 ;; Element positions are relative to the parent position.
6876 (pos (+ pos (js2-node-pos e))))
6877 (cond
6878 ;; foo: function() {...}
6879 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6880 (when (js2-prop-node-name left)
6881 ;; As a policy decision, we record the position of the property,
6882 ;; not the position of the `function' keyword, since the property
6883 ;; is effectively the name of the function.
6884 (js2-record-imenu-entry right (append qname (list left)) pos)))
6885 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6886 ((js2-object-node-p right)
6887 (js2-record-object-literal right
6888 (append qname (list (js2-infix-node-left e)))
6889 (+ pos (js2-node-pos right)))))))))
6890
6891 (defsubst js2-node-top-level-decl-p (node)
6892 "Return t if NODE's name is defined in the top-level scope.
6893 Also returns t if NODE's name is not defined in any scope, since it implies
6894 that it's an external variable, which must also be in the top-level scope."
6895 (let* ((name (js2-prop-node-name node))
6896 (this-scope (js2-node-get-enclosing-scope node))
6897 defining-scope)
6898 (cond
6899 ((js2-this-node-p node)
6900 nil)
6901 ((null this-scope)
6902 t)
6903 ((setq defining-scope (js2-get-defining-scope this-scope name))
6904 (js2-ast-root-p defining-scope))
6905 (t t))))
6906
6907 (defsubst js2-wrapper-function-p (node)
6908 "Returns t if NODE is a function expression that's immediately invoked.
6909 NODE must be `js2-function-node'."
6910 (let ((parent (js2-node-parent node)))
6911 (or
6912 ;; function(){...}();
6913 (js2-call-node-p parent)
6914 (and (js2-paren-node-p parent)
6915 ;; (function(){...})();
6916 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6917 ;; (function(){...}).call(this);
6918 (and (js2-prop-get-node-p parent)
6919 (member (js2-name-node-name (js2-prop-get-node-right parent))
6920 '("call" "apply"))
6921 (js2-call-node-p (js2-node-parent parent))))))))
6922
6923 (defun js2-browse-postprocess-chains (entries)
6924 "Modify function-declaration name chains after parsing finishes.
6925 Some of the information is only available after the parse tree is complete.
6926 For instance, processing a nested scope requires a parent function node."
6927 (let (result head fn current-fn parent-qname qname p elem)
6928 (dolist (entry entries)
6929 ;; function node goes first
6930 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6931 ;; Examine head's defining scope:
6932 ;; Pre-processed chain, or top-level/external, keep as-is.
6933 (if (or (stringp head) (js2-node-top-level-decl-p head))
6934 (push chain result)
6935 (when (js2-this-node-p head)
6936 (setq chain (cdr chain))) ; discard this-node
6937 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6938 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6939 (when (eq parent-qname 'not-found)
6940 ;; anonymous function expressions are not recorded
6941 ;; during the parse, so we need to handle this case here
6942 (setq parent-qname
6943 (if (js2-wrapper-function-p fn)
6944 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6945 (if (js2-ast-root-p grandparent)
6946 nil
6947 (gethash grandparent js2-imenu-function-map 'skip)))
6948 'skip))
6949 (puthash fn parent-qname js2-imenu-function-map))
6950 (unless (eq parent-qname 'skip)
6951 ;; prefix parent fn qname to this chain.
6952 (let ((qname (append parent-qname chain)))
6953 (puthash current-fn (butlast qname) js2-imenu-function-map)
6954 (push qname result)))))))
6955 ;; finally replace each node in each chain with its name.
6956 (dolist (chain result)
6957 (setq p chain)
6958 (while p
6959 (if (js2-node-p (setq elem (car p)))
6960 (setcar p (js2-node-qname-component elem)))
6961 (setq p (cdr p))))
6962 result))
6963
6964 ;; Merge name chains into a trie-like tree structure of nested lists.
6965 ;; To simplify construction of the trie, we first build it out using the rule
6966 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6967 ;; [key, num-or-list]. The second element can be a number; if so, this key
6968 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6969 ;; associated with the key at this level.) Otherwise the second element is
6970 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6971 ;; a simple recursive formulation.
6972 ;;
6973 ;; js2-mode is building the data structure for imenu. The imenu documentation
6974 ;; claims that it's the structure above, but in practice it wants the children
6975 ;; at the same list level as the key for that level, which is how I've drawn
6976 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6977 ;; list wrapper around the children at each level.
6978 ;;
6979 ;; A completed nested imenu-alist entry looks like this:
6980 ;; '(("foo"
6981 ;; ("<definition>" . 7)
6982 ;; ("bar"
6983 ;; ("a" . 40)
6984 ;; ("b" . 60))))
6985 ;;
6986 ;; In particular, the documentation for `imenu--index-alist' says that
6987 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6988 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6989
6990 (defun js2-treeify (lst)
6991 "Convert (a b c d) to (a ((b ((c d)))))"
6992 (if (null (cddr lst)) ; list length <= 2
6993 lst
6994 (list (car lst) (list (js2-treeify (cdr lst))))))
6995
6996 (defun js2-build-alist-trie (chains trie)
6997 "Merge declaration name chains into a trie-like alist structure for imenu.
6998 CHAINS is the qname chain list produced during parsing. TRIE is a
6999 list of elements built up so far."
7000 (let (head tail pos branch kids)
7001 (dolist (chain chains)
7002 (setq head (car chain)
7003 tail (cdr chain)
7004 pos (if (numberp (car tail)) (car tail))
7005 branch (js2-find-if (lambda (n)
7006 (string= (car n) head))
7007 trie)
7008 kids (second branch))
7009 (cond
7010 ;; case 1: this key isn't in the trie yet
7011 ((null branch)
7012 (if trie
7013 (setcdr (last trie) (list (js2-treeify chain)))
7014 (setq trie (list (js2-treeify chain)))))
7015 ;; case 2: key is present with a single number entry: replace w/ list
7016 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7017 ;; ("<definition>" 20)))
7018 ((numberp kids)
7019 (setcar (cdr branch)
7020 (list (list "<definition-1>" kids)
7021 (if pos
7022 (list "<definition-2>" pos)
7023 (js2-treeify tail)))))
7024 ;; case 3: key is there (with kids), and we're a number entry
7025 (pos
7026 (setcdr (last kids)
7027 (list
7028 (list (format "<definition-%d>"
7029 (1+ (loop for kid in kids
7030 count (eq ?< (aref (car kid) 0)))))
7031 pos))))
7032 ;; case 4: key is there with kids, need to merge in our chain
7033 (t
7034 (js2-build-alist-trie (list tail) kids))))
7035 trie))
7036
7037 (defun js2-flatten-trie (trie)
7038 "Convert TRIE to imenu-format.
7039 Recurses through nodes, and for each one whose second element is a list,
7040 appends the list's flattened elements to the current element. Also
7041 changes the tails into conses. For instance, this pre-flattened trie
7042
7043 '(a ((b 20)
7044 (c ((d 30)
7045 (e 40)))))
7046
7047 becomes
7048
7049 '(a (b . 20)
7050 (c (d . 30)
7051 (e . 40)))
7052
7053 Note that the root of the trie has no key, just a list of chains.
7054 This is also true for the value of any key with multiple children,
7055 e.g. key 'c' in the example above."
7056 (cond
7057 ((listp (car trie))
7058 (mapcar #'js2-flatten-trie trie))
7059 (t
7060 (if (numberp (second trie))
7061 (cons (car trie) (second trie))
7062 ;; else pop list and append its kids
7063 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7064
7065 (defun js2-build-imenu-index ()
7066 "Turn `js2-imenu-recorder' into an imenu data structure."
7067 (unless (eq js2-imenu-recorder 'empty)
7068 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7069 (result (js2-build-alist-trie chains nil)))
7070 (js2-flatten-trie result))))
7071
7072 (defun js2-test-print-chains (chains)
7073 "Print a list of qname chains.
7074 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7075 i.e. one or more nodes, and an integer position as the list tail."
7076 (mapconcat (lambda (chain)
7077 (concat "("
7078 (mapconcat (lambda (elem)
7079 (if (js2-node-p elem)
7080 (or (js2-node-qname-component elem)
7081 "nil")
7082 (number-to-string elem)))
7083 chain
7084 " ")
7085 ")"))
7086 chains
7087 "\n"))
7088
7089 ;;; Parser
7090
7091 (defconst js2-version "1.8.5"
7092 "Version of JavaScript supported.")
7093
7094 (defmacro js2-record-face (face)
7095 "Record a style run of FACE for the current token."
7096 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7097
7098 (defsubst js2-node-end (n)
7099 "Computes the absolute end of node N.
7100 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7101 is only true until the node is added to its parent; i.e., while parsing."
7102 (+ (js2-node-pos n)
7103 (js2-node-len n)))
7104
7105 (defsubst js2-record-comment ()
7106 "Record a comment in `js2-scanned-comments'."
7107 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7108 :format js2-ts-comment-type)
7109 js2-scanned-comments)
7110 (when js2-parse-ide-mode
7111 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7112 'font-lock-doc-face
7113 'font-lock-comment-face))
7114 (when (memq js2-ts-comment-type '(html preprocessor))
7115 ;; Tell cc-engine the bounds of the comment.
7116 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7117
7118 ;; This function is called depressingly often, so it should be fast.
7119 ;; Most of the time it's looking at the same token it peeked before.
7120 (defsubst js2-peek-token ()
7121 "Returns the next token without consuming it.
7122 If previous token was consumed, calls scanner to get new token.
7123 If previous token was -not- consumed, returns it (idempotent).
7124
7125 This function will not return a newline (js2-EOL) - instead, it
7126 gobbles newlines until it finds a non-newline token, and flags
7127 that token as appearing just after a newline.
7128
7129 This function will also not return a js2-COMMENT. Instead, it
7130 records comments found in `js2-scanned-comments'. If the token
7131 returned by this function immediately follows a jsdoc comment,
7132 the token is flagged as such.
7133
7134 Note that this function always returned the un-flagged token!
7135 The flags, if any, are saved in `js2-current-flagged-token'."
7136 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7137 js2-current-token ; most common case - return already-peeked token
7138 (let ((tt (js2-get-token)) ; call scanner
7139 saw-eol
7140 face)
7141 ;; process comments and whitespace
7142 (while (or (= tt js2-EOL)
7143 (= tt js2-COMMENT))
7144 (if (= tt js2-EOL)
7145 (setq saw-eol t)
7146 (setq saw-eol nil)
7147 (if js2-record-comments
7148 (js2-record-comment)))
7149 (setq tt (js2-get-token))) ; call scanner
7150 (setq js2-current-token tt
7151 js2-current-flagged-token (if saw-eol
7152 (logior tt js2-ti-after-eol)
7153 tt))
7154 ;; perform lexical fontification as soon as token is scanned
7155 (when js2-parse-ide-mode
7156 (cond
7157 ((minusp tt)
7158 (js2-record-face 'js2-error-face))
7159 ((setq face (aref js2-kwd-tokens tt))
7160 (js2-record-face face))
7161 ((and (= tt js2-NAME)
7162 (equal js2-ts-string "undefined"))
7163 (js2-record-face 'font-lock-constant-face))))
7164 tt))) ; return unflagged token
7165
7166 (defsubst js2-peek-flagged-token ()
7167 "Returns the current token along with any flags set for it."
7168 (js2-peek-token)
7169 js2-current-flagged-token)
7170
7171 (defsubst js2-consume-token ()
7172 (setq js2-current-flagged-token js2-EOF))
7173
7174 (defsubst js2-next-token ()
7175 (prog1
7176 (js2-peek-token)
7177 (js2-consume-token)))
7178
7179 (defsubst js2-next-flagged-token ()
7180 (js2-peek-token)
7181 (prog1 js2-current-flagged-token
7182 (js2-consume-token)))
7183
7184 (defsubst js2-match-token (match)
7185 "Consume and return t if next token matches MATCH, a bytecode.
7186 Returns nil and consumes nothing if MATCH is not the next token."
7187 (if (/= (js2-peek-token) match)
7188 nil
7189 (js2-consume-token)
7190 t))
7191
7192 (defun js2-match-contextual-kwd (name)
7193 "Consume and return t if next token is `js2-NAME', and its
7194 string is NAME. Returns nil and does nothing otherwise."
7195 (if (or (/= (js2-peek-token) js2-NAME)
7196 (not (string= js2-ts-string name)))
7197 nil
7198 (js2-consume-token)
7199 (js2-record-face 'font-lock-keyword-face)
7200 t))
7201
7202 (defsubst js2-valid-prop-name-token (tt)
7203 (or (= tt js2-NAME)
7204 (when (and js2-allow-keywords-as-property-names
7205 (plusp tt)
7206 (aref js2-kwd-tokens tt))
7207 (js2-save-name-token-data js2-token-beg (js2-token-name tt))
7208 t)))
7209
7210 (defsubst js2-match-prop-name ()
7211 "Consume token and return t if next token is a valid property name.
7212 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7213 is non-nil and it's a keyword token."
7214 (if (js2-valid-prop-name-token (js2-peek-token))
7215 (progn
7216 (js2-consume-token)
7217 t)
7218 nil))
7219
7220 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7221 (if (js2-match-prop-name)
7222 t
7223 (js2-report-error msg-id nil pos len)
7224 nil))
7225
7226 (defsubst js2-peek-token-or-eol ()
7227 "Return js2-EOL if the current token immediately follows a newline.
7228 Else returns the current token. Used in situations where we don't
7229 consider certain token types valid if they are preceded by a newline.
7230 One example is the postfix ++ or -- operator, which has to be on the
7231 same line as its operand."
7232 (let ((tt (js2-peek-token)))
7233 ;; Check for last peeked token flags
7234 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7235 js2-EOL
7236 tt)))
7237
7238 (defsubst js2-set-check-for-label ()
7239 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7240 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7241
7242 (defsubst js2-must-match (token msg-id &optional pos len)
7243 "Match next token to token code TOKEN, or record a syntax error.
7244 MSG-ID is the error message to report if the match fails.
7245 Returns t on match, nil if no match."
7246 (if (js2-match-token token)
7247 t
7248 (js2-report-error msg-id nil pos len)
7249 nil))
7250
7251 (defsubst js2-inside-function ()
7252 (plusp js2-nesting-of-function))
7253
7254 (defsubst js2-set-requires-activation ()
7255 (if (js2-function-node-p js2-current-script-or-fn)
7256 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7257
7258 (defsubst js2-check-activation-name (name token)
7259 (when (js2-inside-function)
7260 ;; skip language-version 1.2 check from Rhino
7261 (if (or (string= "arguments" name)
7262 (and js2-compiler-activation-names ; only used in codegen
7263 (gethash name js2-compiler-activation-names)))
7264 (js2-set-requires-activation))))
7265
7266 (defsubst js2-set-is-generator ()
7267 (if (js2-function-node-p js2-current-script-or-fn)
7268 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7269
7270 (defsubst js2-must-have-xml ()
7271 (unless js2-compiler-xml-available
7272 (js2-report-error "msg.XML.not.available")))
7273
7274 (defsubst js2-push-scope (scope)
7275 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7276 (assert (js2-scope-p scope))
7277 (assert (null (js2-scope-parent-scope scope)))
7278 (assert (not (eq js2-current-scope scope)))
7279 (setf (js2-scope-parent-scope scope) js2-current-scope
7280 js2-current-scope scope))
7281
7282 (defsubst js2-pop-scope ()
7283 (setq js2-current-scope
7284 (js2-scope-parent-scope js2-current-scope)))
7285
7286 (defsubst js2-enter-loop (loop-node)
7287 (push loop-node js2-loop-set)
7288 (push loop-node js2-loop-and-switch-set)
7289 (js2-push-scope loop-node)
7290 ;; Tell the current labeled statement (if any) its statement,
7291 ;; and set the jump target of the first label to the loop.
7292 ;; These are used in `js2-parse-continue' to verify that the
7293 ;; continue target is an actual labeled loop. (And for codegen.)
7294 (when js2-labeled-stmt
7295 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7296 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7297 js2-labeled-stmt))) loop-node)))
7298
7299 (defsubst js2-exit-loop ()
7300 (pop js2-loop-set)
7301 (pop js2-loop-and-switch-set)
7302 (js2-pop-scope))
7303
7304 (defsubst js2-enter-switch (switch-node)
7305 (push switch-node js2-loop-and-switch-set))
7306
7307 (defsubst js2-exit-switch ()
7308 (pop js2-loop-and-switch-set))
7309
7310 (defun js2-parse (&optional buf cb)
7311 "Tells the js2 parser to parse a region of JavaScript.
7312
7313 BUF is a buffer or buffer name containing the code to parse.
7314 Call `narrow-to-region' first to parse only part of the buffer.
7315
7316 The returned AST root node is given some additional properties:
7317 `node-count' - total number of nodes in the AST
7318 `buffer' - BUF. The buffer it refers to may change or be killed,
7319 so the value is not necessarily reliable.
7320
7321 An optional callback CB can be specified to report parsing
7322 progress. If `(functionp CB)' returns t, it will be called with
7323 the current line number once before parsing begins, then again
7324 each time the lexer reaches a new line number.
7325
7326 CB can also be a list of the form `(symbol cb ...)' to specify
7327 multiple callbacks with different criteria. Each symbol is a
7328 criterion keyword, and the following element is the callback to
7329 call
7330
7331 :line - called whenever the line number changes
7332 :token - called for each new token consumed
7333
7334 The list of criteria could be extended to include entering or
7335 leaving a statement, an expression, or a function definition."
7336 (if (and cb (not (functionp cb)))
7337 (error "criteria callbacks not yet implemented"))
7338 (let ((inhibit-point-motion-hooks t)
7339 (js2-compiler-xml-available (>= js2-language-version 160))
7340 ;; This is a recursive-descent parser, so give it a big stack.
7341 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7342 (max-specpdl-size (max max-specpdl-size 3000))
7343 (case-fold-search nil)
7344 ast)
7345 (message nil) ; clear any error message from previous parse
7346 (save-excursion
7347 (when buf (set-buffer buf))
7348 (setq js2-scanned-comments nil
7349 js2-parsed-errors nil
7350 js2-parsed-warnings nil
7351 js2-imenu-recorder nil
7352 js2-imenu-function-map nil
7353 js2-label-set nil)
7354 (js2-init-scanner)
7355 (setq ast (js2-with-unmodifying-text-property-changes
7356 (js2-do-parse)))
7357 (unless js2-ts-hit-eof
7358 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7359 (setf (js2-ast-root-errors ast) js2-parsed-errors
7360 (js2-ast-root-warnings ast) js2-parsed-warnings)
7361 ;; if we didn't find any declarations, put a dummy in this list so we
7362 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7363 (unless js2-imenu-recorder
7364 (setq js2-imenu-recorder 'empty))
7365 (run-hooks 'js2-parse-finished-hook)
7366 ast)))
7367
7368 ;; Corresponds to Rhino's Parser.parse() method.
7369 (defun js2-do-parse ()
7370 "Parse current buffer starting from current point.
7371 Scanner should be initialized."
7372 (let ((pos js2-ts-cursor)
7373 (end js2-ts-cursor) ; in case file is empty
7374 root n tt)
7375 ;; initialize buffer-local parsing vars
7376 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7377 js2-current-script-or-fn root
7378 js2-current-scope root
7379 js2-current-flagged-token js2-EOF
7380 js2-nesting-of-function 0
7381 js2-labeled-stmt nil
7382 js2-recorded-identifiers nil) ; for js2-highlight
7383 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7384 (if (= tt js2-FUNCTION)
7385 (progn
7386 (js2-consume-token)
7387 (setq n (js2-parse-function (if js2-called-by-compile-function
7388 'FUNCTION_EXPRESSION
7389 'FUNCTION_STATEMENT))))
7390 ;; not a function - parse a statement
7391 (setq n (js2-parse-statement)))
7392 ;; add function or statement to script
7393 (setq end (js2-node-end n))
7394 (js2-block-node-push root n))
7395 ;; add comments to root in lexical order
7396 (when js2-scanned-comments
7397 ;; if we find a comment beyond end of normal kids, use its end
7398 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7399 (dolist (comment js2-scanned-comments)
7400 (push comment (js2-ast-root-comments root))
7401 (js2-node-add-children root comment)))
7402 (setf (js2-node-len root) (- end pos))
7403 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
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 is-for-each is-for-in-or-of is-for-of
7962 in-pos each-pos tmp-pos
7963 init ; Node init is also foo in 'foo in object'
7964 cond ; Node cond is also object in 'foo in object'
7965 incr ; 3rd section of for-loop initializer
7966 body tt lp rp)
7967 (js2-consume-token)
7968 ;; See if this is a for each () instead of just a for ()
7969 (when (js2-match-token js2-NAME)
7970 (if (string= "each" js2-ts-string)
7971 (progn
7972 (setq is-for-each t
7973 each-pos (- js2-token-beg for-pos)) ; relative
7974 (js2-record-face 'font-lock-keyword-face))
7975 (js2-report-error "msg.no.paren.for")))
7976 (if (js2-must-match js2-LP "msg.no.paren.for")
7977 (setq lp (- js2-token-beg for-pos)))
7978 (setq tt (js2-peek-token))
7979 ;; 'for' makes local scope
7980 (js2-push-scope (make-js2-scope))
7981 (unwind-protect
7982 ;; parse init clause
7983 (let ((js2-in-for-init t)) ; set as dynamic variable
7984 (cond
7985 ((= tt js2-SEMI)
7986 (setq init (make-js2-empty-expr-node)))
7987 ((or (= tt js2-VAR) (= tt js2-LET))
7988 (js2-consume-token)
7989 (setq init (js2-parse-variables tt js2-token-beg)))
7990 (t
7991 (setq init (js2-parse-expr)))))
7992 (if (or (js2-match-token js2-IN)
7993 (and (>= js2-language-version 200)
7994 (js2-match-contextual-kwd "of")
7995 (setq is-for-of t)))
7996 (setq is-for-in-or-of t
7997 in-pos (- js2-token-beg for-pos)
7998 ;; scope of iteration target object is not the scope we've created above.
7999 ;; stash current scope temporary.
8000 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8001 (js2-parse-expr))) ; object over which we're iterating
8002 ;; else ordinary for loop - parse cond and incr
8003 (js2-must-match js2-SEMI "msg.no.semi.for")
8004 (setq cond (if (= (js2-peek-token) js2-SEMI)
8005 (make-js2-empty-expr-node) ; no loop condition
8006 (js2-parse-expr)))
8007 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8008 (setq tmp-pos js2-token-end
8009 incr (if (= (js2-peek-token) js2-RP)
8010 (make-js2-empty-expr-node :pos tmp-pos)
8011 (js2-parse-expr))))
8012 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8013 (setq rp (- js2-token-beg for-pos)))
8014 (if (not is-for-in-or-of)
8015 (setq pn (make-js2-for-node :init init
8016 :condition cond
8017 :update incr
8018 :lp lp
8019 :rp rp))
8020 ;; cond could be null if 'in obj' got eaten by the init node.
8021 (if (js2-infix-node-p init)
8022 ;; it was (foo in bar) instead of (var foo in bar)
8023 (setq cond (js2-infix-node-right init)
8024 init (js2-infix-node-left init))
8025 (if (and (js2-var-decl-node-p init)
8026 (> (length (js2-var-decl-node-kids init)) 1))
8027 (js2-report-error "msg.mult.index")))
8028 (setq pn (make-js2-for-in-node :iterator init
8029 :object cond
8030 :in-pos in-pos
8031 :foreach-p is-for-each
8032 :each-pos each-pos
8033 :forof-p is-for-of
8034 :lp lp
8035 :rp rp)))
8036 (unwind-protect
8037 (progn
8038 (js2-enter-loop pn)
8039 ;; We have to parse the body -after- creating the loop node,
8040 ;; so that the loop node appears in the js2-loop-set, allowing
8041 ;; break/continue statements to find the enclosing loop.
8042 (setf body (js2-parse-statement)
8043 (js2-loop-node-body pn) body
8044 (js2-node-pos pn) for-pos
8045 (js2-node-len pn) (- (js2-node-end body) for-pos))
8046 (js2-node-add-children pn init cond incr body))
8047 ;; finally
8048 (js2-exit-loop))
8049 (js2-pop-scope))
8050 pn))
8051
8052 (defun js2-parse-try ()
8053 "Parser for try-statement. Last matched token must be js2-TRY."
8054 (let ((try-pos js2-token-beg)
8055 try-end
8056 try-block
8057 catch-blocks
8058 finally-block
8059 saw-default-catch
8060 peek
8061 param
8062 catch-cond
8063 catch-node
8064 guard-kwd
8065 catch-pos
8066 finally-pos
8067 pn
8068 block
8069 lp
8070 rp)
8071 (js2-consume-token)
8072 (if (/= (js2-peek-token) js2-LC)
8073 (js2-report-error "msg.no.brace.try"))
8074 (setq try-block (js2-parse-statement)
8075 try-end (js2-node-end try-block)
8076 peek (js2-peek-token))
8077 (cond
8078 ((= peek js2-CATCH)
8079 (while (js2-match-token js2-CATCH)
8080 (setq catch-pos js2-token-beg
8081 guard-kwd nil
8082 catch-cond nil
8083 lp nil
8084 rp nil)
8085 (if saw-default-catch
8086 (js2-report-error "msg.catch.unreachable"))
8087 (if (js2-must-match js2-LP "msg.no.paren.catch")
8088 (setq lp (- js2-token-beg catch-pos)))
8089 (js2-push-scope (make-js2-scope))
8090 (let ((tt (js2-peek-token)))
8091 (cond
8092 ;; destructuring pattern
8093 ;; catch ({ message, file }) { ... }
8094 ((or (= tt js2-LB) (= tt js2-LC))
8095 (setq param (js2-parse-destruct-primary-expr))
8096 (js2-define-destruct-symbols param js2-LET nil))
8097 ;; simple name
8098 (t
8099 (js2-must-match js2-NAME "msg.bad.catchcond")
8100 (setq param (js2-create-name-node))
8101 (js2-define-symbol js2-LET js2-ts-string param))))
8102 ;; pattern guard
8103 (if (js2-match-token js2-IF)
8104 (setq guard-kwd (- js2-token-beg catch-pos)
8105 catch-cond (js2-parse-expr))
8106 (setq saw-default-catch t))
8107 (if (js2-must-match js2-RP "msg.bad.catchcond")
8108 (setq rp (- js2-token-beg catch-pos)))
8109 (js2-must-match js2-LC "msg.no.brace.catchblock")
8110 (setq block (js2-parse-statements)
8111 try-end (js2-node-end block)
8112 catch-node (make-js2-catch-node :pos catch-pos
8113 :param param
8114 :guard-expr catch-cond
8115 :guard-kwd guard-kwd
8116 :block block
8117 :lp lp
8118 :rp rp))
8119 (js2-pop-scope)
8120 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8121 (setq try-end js2-token-beg))
8122 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8123 (js2-node-len catch-node) (- try-end catch-pos))
8124 (js2-node-add-children catch-node param catch-cond block)
8125 (push catch-node catch-blocks)))
8126 ((/= peek js2-FINALLY)
8127 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8128 (js2-node-pos try-block)
8129 (- (setq try-end (js2-node-end try-block))
8130 (js2-node-pos try-block)))))
8131 (when (js2-match-token js2-FINALLY)
8132 (setq finally-pos js2-token-beg
8133 block (js2-parse-statement)
8134 try-end (js2-node-end block)
8135 finally-block (make-js2-finally-node :pos finally-pos
8136 :len (- try-end finally-pos)
8137 :body block))
8138 (js2-node-add-children finally-block block))
8139 (setq pn (make-js2-try-node :pos try-pos
8140 :len (- try-end try-pos)
8141 :try-block try-block
8142 :finally-block finally-block))
8143 (js2-node-add-children pn try-block finally-block)
8144 ;; push them onto the try-node, which reverses and corrects their order
8145 (dolist (cb catch-blocks)
8146 (js2-node-add-children pn cb)
8147 (push cb (js2-try-node-catch-clauses pn)))
8148 pn))
8149
8150 (defun js2-parse-throw ()
8151 "Parser for throw-statement. Last matched token must be js2-THROW."
8152 (let ((pos js2-token-beg)
8153 expr
8154 pn)
8155 (js2-consume-token)
8156 (if (= (js2-peek-token-or-eol) js2-EOL)
8157 ;; ECMAScript does not allow new lines before throw expression,
8158 ;; see bug 256617
8159 (js2-report-error "msg.bad.throw.eol"))
8160 (setq expr (js2-parse-expr)
8161 pn (make-js2-throw-node :pos pos
8162 :len (- (js2-node-end expr) pos)
8163 :expr expr))
8164 (js2-node-add-children pn expr)
8165 pn))
8166
8167 (defsubst js2-match-jump-label-name (label-name)
8168 "If break/continue specified a label, return that label's labeled stmt.
8169 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8170 does not match an existing label, reports an error and returns nil."
8171 (let ((bundle (cdr (assoc label-name js2-label-set))))
8172 (if (null bundle)
8173 (js2-report-error "msg.undef.label"))
8174 bundle))
8175
8176 (defun js2-parse-break ()
8177 "Parser for break-statement. Last matched token must be js2-BREAK."
8178 (let ((pos js2-token-beg)
8179 (end js2-token-end)
8180 break-target ; statement to break from
8181 break-label ; in "break foo", name-node representing the foo
8182 labels ; matching labeled statement to break to
8183 pn)
8184 (js2-consume-token) ; `break'
8185 (when (eq (js2-peek-token-or-eol) js2-NAME)
8186 (js2-consume-token)
8187 (setq break-label (js2-create-name-node)
8188 end (js2-node-end break-label)
8189 ;; matchJumpLabelName only matches if there is one
8190 labels (js2-match-jump-label-name js2-ts-string)
8191 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8192 (unless (or break-target break-label)
8193 ;; no break target specified - try for innermost enclosing loop/switch
8194 (if (null js2-loop-and-switch-set)
8195 (unless break-label
8196 (js2-report-error "msg.bad.break" nil pos (length "break")))
8197 (setq break-target (car js2-loop-and-switch-set))))
8198 (setq pn (make-js2-break-node :pos pos
8199 :len (- end pos)
8200 :label break-label
8201 :target break-target))
8202 (js2-node-add-children pn break-label) ; but not break-target
8203 pn))
8204
8205 (defun js2-parse-continue ()
8206 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8207 (let ((pos js2-token-beg)
8208 (end js2-token-end)
8209 label ; optional user-specified label, a `js2-name-node'
8210 labels ; current matching labeled stmt, if any
8211 target ; the `js2-loop-node' target of this continue stmt
8212 pn)
8213 (js2-consume-token) ; `continue'
8214 (when (= (js2-peek-token-or-eol) js2-NAME)
8215 (js2-consume-token)
8216 (setq label (js2-create-name-node)
8217 end (js2-node-end label)
8218 ;; matchJumpLabelName only matches if there is one
8219 labels (js2-match-jump-label-name js2-ts-string)))
8220 (cond
8221 ((null labels) ; no current label to go to
8222 (if (null js2-loop-set) ; no loop to continue to
8223 (js2-report-error "msg.continue.outside" nil pos
8224 (length "continue"))
8225 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8226 (t
8227 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8228 (setq target (js2-labeled-stmt-node-stmt labels))
8229 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8230 (setq pn (make-js2-continue-node :pos pos
8231 :len (- end pos)
8232 :label label
8233 :target target))
8234 (js2-node-add-children pn label) ; but not target - it's not our child
8235 pn))
8236
8237 (defun js2-parse-with ()
8238 "Parser for with-statement. Last matched token must be js2-WITH."
8239 (js2-consume-token)
8240 (let ((pos js2-token-beg)
8241 obj body pn lp rp)
8242 (if (js2-must-match js2-LP "msg.no.paren.with")
8243 (setq lp js2-token-beg))
8244 (setq obj (js2-parse-expr))
8245 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8246 (setq rp js2-token-beg))
8247 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8248 (setq body (js2-parse-statement)))
8249 (setq pn (make-js2-with-node :pos pos
8250 :len (- (js2-node-end body) pos)
8251 :object obj
8252 :body body
8253 :lp (js2-relpos lp pos)
8254 :rp (js2-relpos rp pos)))
8255 (js2-node-add-children pn obj body)
8256 pn))
8257
8258 (defun js2-parse-const-var ()
8259 "Parser for var- or const-statement.
8260 Last matched token must be js2-CONST or js2-VAR."
8261 (let ((tt (js2-peek-token))
8262 (pos js2-token-beg)
8263 expr
8264 pn)
8265 (js2-consume-token)
8266 (setq expr (js2-parse-variables tt js2-token-beg)
8267 pn (make-js2-expr-stmt-node :pos pos
8268 :len (- (js2-node-end expr) pos)
8269 :expr expr))
8270 (js2-node-add-children pn expr)
8271 pn))
8272
8273 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8274 (let ((pn (make-js2-expr-stmt-node :pos pos
8275 :len (js2-node-len expr)
8276 :type (if (js2-inside-function)
8277 js2-EXPR_VOID
8278 js2-EXPR_RESULT)
8279 :expr expr)))
8280 (if add-child
8281 (js2-node-add-children pn expr))
8282 pn))
8283
8284 (defun js2-parse-let-stmt ()
8285 "Parser for let-statement. Last matched token must be js2-LET."
8286 (js2-consume-token)
8287 (let ((pos js2-token-beg)
8288 expr
8289 pn)
8290 (if (= (js2-peek-token) js2-LP)
8291 ;; let expression in statement context
8292 (setq expr (js2-parse-let pos 'statement)
8293 pn (js2-wrap-with-expr-stmt pos expr t))
8294 ;; else we're looking at a statement like let x=6, y=7;
8295 (setf expr (js2-parse-variables js2-LET pos)
8296 pn (js2-wrap-with-expr-stmt pos expr t)
8297 (js2-node-type pn) js2-EXPR_RESULT))
8298 pn))
8299
8300 (defun js2-parse-ret-yield ()
8301 (js2-parse-return-or-yield (js2-peek-token) nil))
8302
8303 (defconst js2-parse-return-stmt-enders
8304 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8305
8306 (defsubst js2-now-all-set (before after mask)
8307 "Return whether or not the bits in the mask have changed to all set.
8308 BEFORE is bits before change, AFTER is bits after change, and MASK is
8309 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8310 but not BEFORE."
8311 (and (/= (logand before mask) mask)
8312 (= (logand after mask) mask)))
8313
8314 (defun js2-parse-return-or-yield (tt expr-context)
8315 (let ((pos js2-token-beg)
8316 (end js2-token-end)
8317 (before js2-end-flags)
8318 (inside-function (js2-inside-function))
8319 e
8320 ret
8321 name)
8322 (unless inside-function
8323 (js2-report-error (if (eq tt js2-RETURN)
8324 "msg.bad.return"
8325 "msg.bad.yield")))
8326 (js2-consume-token)
8327 ;; This is ugly, but we don't want to require a semicolon.
8328 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8329 (setq e (js2-parse-expr)
8330 end (js2-node-end e)))
8331 (cond
8332 ((eq tt js2-RETURN)
8333 (js2-set-flag js2-end-flags (if (null e)
8334 js2-end-returns
8335 js2-end-returns-value))
8336 (setq ret (make-js2-return-node :pos pos
8337 :len (- end pos)
8338 :retval e))
8339 (js2-node-add-children ret e)
8340 ;; See if we need a strict mode warning.
8341 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8342 ;; more thorough and accurate than this before/after flag check.
8343 ;; E.g. if there's a finally-block that always returns, we shouldn't
8344 ;; show a warning generated by inconsistent returns in the catch blocks.
8345 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8346 ;; so we know which returns/yields to highlight, and we should get rid of
8347 ;; all the checking in `js2-parse-return-or-yield'.
8348 (if (and js2-strict-inconsistent-return-warning
8349 (js2-now-all-set before js2-end-flags
8350 (logior js2-end-returns js2-end-returns-value)))
8351 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8352 (t
8353 (unless (js2-inside-function)
8354 (js2-report-error "msg.bad.yield"))
8355 (js2-set-flag js2-end-flags js2-end-yields)
8356 (setq ret (make-js2-yield-node :pos pos
8357 :len (- end pos)
8358 :value e))
8359 (js2-node-add-children ret e)
8360 (unless expr-context
8361 (setq e ret
8362 ret (js2-wrap-with-expr-stmt pos e t))
8363 (js2-set-requires-activation)
8364 (js2-set-is-generator))))
8365 ;; see if we are mixing yields and value returns.
8366 (when (and inside-function
8367 (js2-now-all-set before js2-end-flags
8368 (logior js2-end-yields js2-end-returns-value)))
8369 (setq name (js2-function-name js2-current-script-or-fn))
8370 (if (zerop (length name))
8371 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8372 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8373 ret))
8374
8375 (defun js2-parse-debugger ()
8376 (js2-consume-token)
8377 (make-js2-keyword-node :type js2-DEBUGGER))
8378
8379 (defun js2-parse-block ()
8380 "Parser for a curly-delimited statement block.
8381 Last token matched must be js2-LC."
8382 (let ((pos js2-token-beg)
8383 (pn (make-js2-scope)))
8384 (js2-consume-token)
8385 (js2-push-scope pn)
8386 (unwind-protect
8387 (progn
8388 (js2-parse-statements pn)
8389 (js2-must-match js2-RC "msg.no.brace.block")
8390 (setf (js2-node-len pn) (- js2-token-end pos)))
8391 (js2-pop-scope))
8392 pn))
8393
8394 ;; for js2-ERROR too, to have a node for error recovery to work on
8395 (defun js2-parse-semi ()
8396 "Parse a statement or handle an error.
8397 Last matched token is js2-SEMI or js2-ERROR."
8398 (let ((tt (js2-peek-token)) pos len)
8399 (js2-consume-token)
8400 (if (eq tt js2-SEMI)
8401 (make-js2-empty-expr-node :len 1)
8402 (setq pos js2-token-beg
8403 len (- js2-token-beg pos))
8404 (js2-report-error "msg.syntax" nil pos len)
8405 (make-js2-error-node :pos pos :len len))))
8406
8407 (defun js2-parse-default-xml-namespace ()
8408 "Parse a `default xml namespace = <expr>' e4x statement."
8409 (let ((pos js2-token-beg)
8410 end len expr unary es)
8411 (js2-consume-token)
8412 (js2-must-have-xml)
8413 (js2-set-requires-activation)
8414 (setq len (- js2-ts-cursor pos))
8415 (unless (and (js2-match-token js2-NAME)
8416 (string= js2-ts-string "xml"))
8417 (js2-report-error "msg.bad.namespace" nil pos len))
8418 (unless (and (js2-match-token js2-NAME)
8419 (string= js2-ts-string "namespace"))
8420 (js2-report-error "msg.bad.namespace" nil pos len))
8421 (unless (js2-match-token js2-ASSIGN)
8422 (js2-report-error "msg.bad.namespace" nil pos len))
8423 (setq expr (js2-parse-expr)
8424 end (js2-node-end expr)
8425 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8426 :pos pos
8427 :len (- end pos)
8428 :operand expr))
8429 (js2-node-add-children unary expr)
8430 (make-js2-expr-stmt-node :pos pos
8431 :len (- end pos)
8432 :expr unary)))
8433
8434 (defun js2-record-label (label bundle)
8435 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8436 (js2-consume-token)
8437 (let ((name (js2-label-node-name label))
8438 labeled-stmt
8439 dup)
8440 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8441 ;; flag both labels if possible when used in editing mode
8442 (if (and js2-parse-ide-mode
8443 (setq dup (js2-get-label-by-name labeled-stmt name)))
8444 (js2-report-error "msg.dup.label" nil
8445 (js2-node-abs-pos dup) (js2-node-len dup)))
8446 (js2-report-error "msg.dup.label" nil
8447 (js2-node-pos label) (js2-node-len label)))
8448 (js2-labeled-stmt-node-add-label bundle label)
8449 (js2-node-add-children bundle label)
8450 ;; Add one reference to the bundle per label in `js2-label-set'
8451 (push (cons name bundle) js2-label-set)))
8452
8453 (defun js2-parse-name-or-label ()
8454 "Parser for identifier or label. Last token matched must be js2-NAME.
8455 Called when we found a name in a statement context. If it's a label, we gather
8456 up any following labels and the next non-label statement into a
8457 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8458 expression and return it wrapped in a `js2-expr-stmt-node'."
8459 (let ((pos js2-token-beg)
8460 (end js2-token-end)
8461 expr
8462 stmt
8463 pn
8464 bundle
8465 (continue t))
8466 ;; set check for label and call down to `js2-parse-primary-expr'
8467 (js2-set-check-for-label)
8468 (setq expr (js2-parse-expr))
8469 (if (/= (js2-node-type expr) js2-LABEL)
8470 ;; Parsed non-label expression - wrap with expression stmt.
8471 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8472 ;; else parsed a label
8473 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8474 (js2-record-label expr bundle)
8475 ;; look for more labels
8476 (while (and continue (= (js2-peek-token) js2-NAME))
8477 (js2-set-check-for-label)
8478 (setq expr (js2-parse-expr))
8479 (if (/= (js2-node-type expr) js2-LABEL)
8480 (progn
8481 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8482 continue nil)
8483 (js2-auto-insert-semicolon stmt))
8484 (js2-record-label expr bundle)))
8485 ;; no more labels; now parse the labeled statement
8486 (unwind-protect
8487 (unless stmt
8488 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8489 (setq stmt (js2-statement-helper))))
8490 ;; remove the labels for this statement from the global set
8491 (dolist (label (js2-labeled-stmt-node-labels bundle))
8492 (setq js2-label-set (remove label js2-label-set))))
8493 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8494 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8495 (js2-node-add-children bundle stmt)
8496 bundle)))
8497
8498 (defun js2-parse-expr-stmt ()
8499 "Default parser in statement context, if no recognized statement found."
8500 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8501
8502 (defun js2-parse-variables (decl-type pos)
8503 "Parse a comma-separated list of variable declarations.
8504 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8505
8506 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8507 For 'var' or 'const', the keyword should be the token last scanned.
8508
8509 POS is the position where the node should start. It's sometimes the
8510 var/const/let keyword, and other times the beginning of the first token
8511 in the first variable declaration.
8512
8513 Returns the parsed `js2-var-decl-node' expression node."
8514 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8515 :pos pos))
8516 destructuring
8517 kid-pos
8518 tt
8519 init
8520 name
8521 end
8522 nbeg nend
8523 vi
8524 (continue t))
8525 ;; Example:
8526 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8527 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8528 ;; var {a, b} = baz;
8529 (while continue
8530 (setq destructuring nil
8531 name nil
8532 tt (js2-peek-token)
8533 kid-pos js2-token-beg
8534 end js2-token-end
8535 init nil)
8536 (if (or (= tt js2-LB) (= tt js2-LC))
8537 ;; Destructuring assignment, e.g., var [a, b] = ...
8538 (setq destructuring (js2-parse-destruct-primary-expr)
8539 end (js2-node-end destructuring))
8540 ;; Simple variable name
8541 (when (js2-must-match js2-NAME "msg.bad.var")
8542 (setq name (js2-create-name-node)
8543 nbeg js2-token-beg
8544 nend js2-token-end
8545 end nend)
8546 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8547 (when (js2-match-token js2-ASSIGN)
8548 (setq init (js2-parse-assign-expr)
8549 end (js2-node-end init))
8550 (js2-record-imenu-functions init name))
8551 (when name
8552 (js2-set-face nbeg nend (if (js2-function-node-p init)
8553 'font-lock-function-name-face
8554 'font-lock-variable-name-face)
8555 'record))
8556 (setq vi (make-js2-var-init-node :pos kid-pos
8557 :len (- end kid-pos)
8558 :type decl-type))
8559 (if destructuring
8560 (progn
8561 (if (and (null init) (not js2-in-for-init))
8562 (js2-report-error "msg.destruct.assign.no.init"))
8563 (js2-define-destruct-symbols destructuring
8564 decl-type
8565 'font-lock-variable-name-face)
8566 (setf (js2-var-init-node-target vi) destructuring))
8567 (setf (js2-var-init-node-target vi) name))
8568 (setf (js2-var-init-node-initializer vi) init)
8569 (js2-node-add-children vi name destructuring init)
8570 (js2-block-node-push result vi)
8571 (unless (js2-match-token js2-COMMA)
8572 (setq continue nil)))
8573 (setf (js2-node-len result) (- end pos))
8574 result))
8575
8576 (defun js2-parse-let (pos &optional stmt-p)
8577 "Parse a let expression or statement.
8578 A let-expression is of the form `let (vars) expr'.
8579 A let-statment is of the form `let (vars) {statements}'.
8580 The third form of let is a variable declaration list, handled
8581 by `js2-parse-variables'."
8582 (let ((pn (make-js2-let-node :pos pos))
8583 beg vars body)
8584 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8585 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8586 (js2-push-scope pn)
8587 (unwind-protect
8588 (progn
8589 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8590 (if (js2-must-match js2-RP "msg.no.paren.let")
8591 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8592 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8593 ;; let statement
8594 (progn
8595 (js2-consume-token)
8596 (setf beg js2-token-beg ; position stmt at LC
8597 body (js2-parse-statements))
8598 (js2-must-match js2-RC "msg.no.curly.let")
8599 (setf (js2-node-len body) (- js2-token-end beg)
8600 (js2-node-len pn) (- js2-token-end pos)
8601 (js2-let-node-body pn) body
8602 (js2-node-type pn) js2-LET))
8603 ;; let expression
8604 (setf body (js2-parse-expr)
8605 (js2-node-len pn) (- (js2-node-end body) pos)
8606 (js2-let-node-body pn) body))
8607 (js2-node-add-children pn vars body))
8608 (js2-pop-scope))
8609 pn))
8610
8611 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8612 (js2-scope-put-symbol (or scope js2-current-scope)
8613 name
8614 (make-js2-symbol decl-type name node)))
8615
8616 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8617 "Define a symbol in the current scope.
8618 If NODE is non-nil, it is the AST node associated with the symbol."
8619 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8620 (symbol (if defining-scope
8621 (js2-scope-get-symbol defining-scope name)))
8622 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8623 (cond
8624 ((and symbol ; already defined
8625 (or (= sdt js2-CONST) ; old version is const
8626 (= decl-type js2-CONST) ; new version is const
8627 ;; two let-bound vars in this block have same name
8628 (and (= sdt js2-LET)
8629 (eq defining-scope js2-current-scope))))
8630 (js2-report-error
8631 (cond
8632 ((= sdt js2-CONST) "msg.const.redecl")
8633 ((= sdt js2-LET) "msg.let.redecl")
8634 ((= sdt js2-VAR) "msg.var.redecl")
8635 ((= sdt js2-FUNCTION) "msg.function.redecl")
8636 (t "msg.parm.redecl"))
8637 name))
8638 ((= decl-type js2-LET)
8639 (if (and (not ignore-not-in-block)
8640 (or (= (js2-node-type js2-current-scope) js2-IF)
8641 (js2-loop-node-p js2-current-scope)))
8642 (js2-report-error "msg.let.decl.not.in.block")
8643 (js2-define-new-symbol decl-type name node)))
8644 ((or (= decl-type js2-VAR)
8645 (= decl-type js2-CONST)
8646 (= decl-type js2-FUNCTION))
8647 (if symbol
8648 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8649 (js2-add-strict-warning "msg.var.redecl" name)
8650 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8651 (js2-add-strict-warning "msg.var.hides.arg" name)))
8652 (js2-define-new-symbol decl-type name node
8653 js2-current-script-or-fn)))
8654 ((= decl-type js2-LP)
8655 (if symbol
8656 ;; must be duplicate parameter. Second parameter hides the
8657 ;; first, so go ahead and add the second pararameter
8658 (js2-report-warning "msg.dup.parms" name))
8659 (js2-define-new-symbol decl-type name node))
8660 (t (js2-code-bug)))))
8661
8662 (defun js2-parse-expr (&optional oneshot)
8663 (let* ((pn (js2-parse-assign-expr))
8664 (pos (js2-node-pos pn))
8665 left
8666 right
8667 op-pos)
8668 (while (and (not oneshot)
8669 (js2-match-token js2-COMMA))
8670 (setq op-pos (- js2-token-beg pos)) ; relative
8671 (if (= (js2-peek-token) js2-YIELD)
8672 (js2-report-error "msg.yield.parenthesized"))
8673 (setq right (js2-parse-assign-expr)
8674 left pn
8675 pn (make-js2-infix-node :type js2-COMMA
8676 :pos pos
8677 :len (- js2-ts-cursor pos)
8678 :op-pos op-pos
8679 :left left
8680 :right right))
8681 (js2-node-add-children pn left right))
8682 pn))
8683
8684 (defun js2-parse-assign-expr ()
8685 (let ((tt (js2-peek-token))
8686 (pos js2-token-beg)
8687 pn
8688 left
8689 right
8690 op-pos)
8691 (if (= tt js2-YIELD)
8692 (js2-parse-return-or-yield tt t)
8693 ;; not yield - parse assignment expression
8694 (setq pn (js2-parse-cond-expr)
8695 tt (js2-peek-token))
8696 (when (and (<= js2-first-assign tt)
8697 (<= tt js2-last-assign))
8698 ;; tt express assignment (=, |=, ^=, ..., %=)
8699 (js2-consume-token)
8700 (setq op-pos (- js2-token-beg pos) ; relative
8701 left pn
8702 right (js2-parse-assign-expr)
8703 pn (make-js2-assign-node :type tt
8704 :pos pos
8705 :len (- (js2-node-end right) pos)
8706 :op-pos op-pos
8707 :left left
8708 :right right))
8709 (when js2-parse-ide-mode
8710 (js2-highlight-assign-targets pn left right)
8711 (js2-record-imenu-functions right left))
8712 ;; do this last so ide checks above can use absolute positions
8713 (js2-node-add-children pn left right))
8714 pn)))
8715
8716 (defun js2-parse-cond-expr ()
8717 (let ((pos js2-token-beg)
8718 (pn (js2-parse-or-expr))
8719 test-expr
8720 if-true
8721 if-false
8722 q-pos
8723 c-pos)
8724 (when (js2-match-token js2-HOOK)
8725 (setq q-pos (- js2-token-beg pos)
8726 if-true (js2-parse-assign-expr))
8727 (js2-must-match js2-COLON "msg.no.colon.cond")
8728 (setq c-pos (- js2-token-beg pos)
8729 if-false (js2-parse-assign-expr)
8730 test-expr pn
8731 pn (make-js2-cond-node :pos pos
8732 :len (- (js2-node-end if-false) pos)
8733 :test-expr test-expr
8734 :true-expr if-true
8735 :false-expr if-false
8736 :q-pos q-pos
8737 :c-pos c-pos))
8738 (js2-node-add-children pn test-expr if-true if-false))
8739 pn))
8740
8741 (defun js2-make-binary (type left parser)
8742 "Helper for constructing a binary-operator AST node.
8743 LEFT is the left-side-expression, already parsed, and the
8744 binary operator should have just been matched.
8745 PARSER is a function to call to parse the right operand,
8746 or a `js2-node' struct if it has already been parsed."
8747 (let* ((pos (js2-node-pos left))
8748 (op-pos (- js2-token-beg pos))
8749 (right (if (js2-node-p parser)
8750 parser
8751 (funcall parser)))
8752 (pn (make-js2-infix-node :type type
8753 :pos pos
8754 :len (- (js2-node-end right) pos)
8755 :op-pos op-pos
8756 :left left
8757 :right right)))
8758 (js2-node-add-children pn left right)
8759 pn))
8760
8761 (defun js2-parse-or-expr ()
8762 (let ((pn (js2-parse-and-expr)))
8763 (when (js2-match-token js2-OR)
8764 (setq pn (js2-make-binary js2-OR
8765 pn
8766 'js2-parse-or-expr)))
8767 pn))
8768
8769 (defun js2-parse-and-expr ()
8770 (let ((pn (js2-parse-bit-or-expr)))
8771 (when (js2-match-token js2-AND)
8772 (setq pn (js2-make-binary js2-AND
8773 pn
8774 'js2-parse-and-expr)))
8775 pn))
8776
8777 (defun js2-parse-bit-or-expr ()
8778 (let ((pn (js2-parse-bit-xor-expr)))
8779 (while (js2-match-token js2-BITOR)
8780 (setq pn (js2-make-binary js2-BITOR
8781 pn
8782 'js2-parse-bit-xor-expr)))
8783 pn))
8784
8785 (defun js2-parse-bit-xor-expr ()
8786 (let ((pn (js2-parse-bit-and-expr)))
8787 (while (js2-match-token js2-BITXOR)
8788 (setq pn (js2-make-binary js2-BITXOR
8789 pn
8790 'js2-parse-bit-and-expr)))
8791 pn))
8792
8793 (defun js2-parse-bit-and-expr ()
8794 (let ((pn (js2-parse-eq-expr)))
8795 (while (js2-match-token js2-BITAND)
8796 (setq pn (js2-make-binary js2-BITAND
8797 pn
8798 'js2-parse-eq-expr)))
8799 pn))
8800
8801 (defconst js2-parse-eq-ops
8802 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8803
8804 (defun js2-parse-eq-expr ()
8805 (let ((pn (js2-parse-rel-expr))
8806 tt)
8807 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8808 (js2-consume-token)
8809 (setq pn (js2-make-binary tt
8810 pn
8811 'js2-parse-rel-expr)))
8812 pn))
8813
8814 (defconst js2-parse-rel-ops
8815 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8816
8817 (defun js2-parse-rel-expr ()
8818 (let ((pn (js2-parse-shift-expr))
8819 (continue t)
8820 tt)
8821 (while continue
8822 (setq tt (js2-peek-token))
8823 (cond
8824 ((and js2-in-for-init (= tt js2-IN))
8825 (setq continue nil))
8826 ((memq tt js2-parse-rel-ops)
8827 (js2-consume-token)
8828 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8829 (t
8830 (setq continue nil))))
8831 pn))
8832
8833 (defconst js2-parse-shift-ops
8834 (list js2-LSH js2-URSH js2-RSH))
8835
8836 (defun js2-parse-shift-expr ()
8837 (let ((pn (js2-parse-add-expr))
8838 tt
8839 (continue t))
8840 (while continue
8841 (setq tt (js2-peek-token))
8842 (if (memq tt js2-parse-shift-ops)
8843 (progn
8844 (js2-consume-token)
8845 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8846 (setq continue nil)))
8847 pn))
8848
8849 (defun js2-parse-add-expr ()
8850 (let ((pn (js2-parse-mul-expr))
8851 tt
8852 (continue t))
8853 (while continue
8854 (setq tt (js2-peek-token))
8855 (if (or (= tt js2-ADD) (= tt js2-SUB))
8856 (progn
8857 (js2-consume-token)
8858 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8859 (setq continue nil)))
8860 pn))
8861
8862 (defconst js2-parse-mul-ops
8863 (list js2-MUL js2-DIV js2-MOD))
8864
8865 (defun js2-parse-mul-expr ()
8866 (let ((pn (js2-parse-unary-expr))
8867 tt
8868 (continue t))
8869 (while continue
8870 (setq tt (js2-peek-token))
8871 (if (memq tt js2-parse-mul-ops)
8872 (progn
8873 (js2-consume-token)
8874 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8875 (setq continue nil)))
8876 pn))
8877
8878 (defsubst js2-make-unary (type parser &rest args)
8879 "Make a unary node of type TYPE.
8880 PARSER is either a node (for postfix operators) or a function to call
8881 to parse the operand (for prefix operators)."
8882 (let* ((pos js2-token-beg)
8883 (postfix (js2-node-p parser))
8884 (expr (if postfix
8885 parser
8886 (apply parser args)))
8887 end
8888 pn)
8889 (if postfix ; e.g. i++
8890 (setq pos (js2-node-pos expr)
8891 end js2-token-end)
8892 (setq end (js2-node-end expr)))
8893 (setq pn (make-js2-unary-node :type type
8894 :pos pos
8895 :len (- end pos)
8896 :operand expr))
8897 (js2-node-add-children pn expr)
8898 pn))
8899
8900 (defconst js2-incrementable-node-types
8901 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8902 "Node types that can be the operand of a ++ or -- operator.")
8903
8904 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8905 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8906 js2-incrementable-node-types)
8907 (js2-report-error (if (= tt js2-INC)
8908 "msg.bad.incr"
8909 "msg.bad.decr")
8910 nil beg (- end beg))))
8911
8912 (defun js2-parse-unary-expr ()
8913 (let ((tt (js2-peek-token))
8914 pn expr beg end)
8915 (cond
8916 ((or (= tt js2-VOID)
8917 (= tt js2-NOT)
8918 (= tt js2-BITNOT)
8919 (= tt js2-TYPEOF))
8920 (js2-consume-token)
8921 (js2-make-unary tt 'js2-parse-unary-expr))
8922 ((= tt js2-ADD)
8923 (js2-consume-token)
8924 ;; Convert to special POS token in decompiler and parse tree
8925 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8926 ((= tt js2-SUB)
8927 (js2-consume-token)
8928 ;; Convert to special NEG token in decompiler and parse tree
8929 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8930 ((or (= tt js2-INC)
8931 (= tt js2-DEC))
8932 (js2-consume-token)
8933 (prog1
8934 (setq beg js2-token-beg
8935 end js2-token-end
8936 expr (js2-make-unary tt 'js2-parse-member-expr t))
8937 (js2-check-bad-inc-dec tt beg end expr)))
8938 ((= tt js2-DELPROP)
8939 (js2-consume-token)
8940 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8941 ((= tt js2-ERROR)
8942 (js2-consume-token)
8943 (make-js2-error-node)) ; try to continue
8944 ((and (= tt js2-LT)
8945 js2-compiler-xml-available)
8946 ;; XML stream encountered in expression.
8947 (js2-consume-token)
8948 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8949 (t
8950 (setq pn (js2-parse-member-expr t)
8951 ;; Don't look across a newline boundary for a postfix incop.
8952 tt (js2-peek-token-or-eol))
8953 (when (or (= tt js2-INC) (= tt js2-DEC))
8954 (js2-consume-token)
8955 (setf expr pn
8956 pn (js2-make-unary tt expr))
8957 (js2-node-set-prop pn 'postfix t)
8958 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8959 pn))))
8960
8961 (defun js2-parse-xml-initializer ()
8962 "Parse an E4X XML initializer.
8963 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8964 Then I'll postprocess the result, depending on whether we're in IDE
8965 mode or codegen mode, and generate the appropriate rewritten AST.
8966 IDE mode uses a rich AST that models the XML structure. Codegen mode
8967 just concatenates everything and makes a new XML or XMLList out of it."
8968 (let ((tt (js2-get-first-xml-token))
8969 pn-xml
8970 pn
8971 expr
8972 kids
8973 expr-pos
8974 (continue t)
8975 (first-token t))
8976 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8977 (js2-report-error "msg.syntax"))
8978 (setq pn-xml (make-js2-xml-node))
8979 (while continue
8980 (if first-token
8981 (setq first-token nil)
8982 (setq tt (js2-get-next-xml-token)))
8983 (cond
8984 ;; js2-XML means we found a {expr} in the XML stream.
8985 ;; The js2-ts-string is the XML up to the left-curly.
8986 ((= tt js2-XML)
8987 (push (make-js2-string-node :pos js2-token-beg
8988 :len (- js2-ts-cursor js2-token-beg))
8989 kids)
8990 (js2-must-match js2-LC "msg.syntax")
8991 (setq expr-pos js2-ts-cursor
8992 expr (if (eq (js2-peek-token) js2-RC)
8993 (make-js2-empty-expr-node :pos expr-pos)
8994 (js2-parse-expr)))
8995 (js2-must-match js2-RC "msg.syntax")
8996 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8997 :len (js2-node-len expr)
8998 :expr expr))
8999 (js2-node-add-children pn expr)
9000 (push pn kids))
9001 ;; a js2-XMLEND token means we hit the final close-tag.
9002 ((= tt js2-XMLEND)
9003 (push (make-js2-string-node :pos js2-token-beg
9004 :len (- js2-ts-cursor js2-token-beg))
9005 kids)
9006 (dolist (kid (nreverse kids))
9007 (js2-block-node-push pn-xml kid))
9008 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9009 (js2-node-pos pn-xml))
9010 continue nil))
9011 (t
9012 (js2-report-error "msg.syntax")
9013 (setq continue nil))))
9014 pn-xml))
9015
9016
9017 (defun js2-parse-argument-list ()
9018 "Parse an argument list and return it as a lisp list of nodes.
9019 Returns the list in reverse order. Consumes the right-paren token."
9020 (let (result)
9021 (unless (js2-match-token js2-RP)
9022 (loop do
9023 (if (= (js2-peek-token) js2-YIELD)
9024 (js2-report-error "msg.yield.parenthesized"))
9025 (push (js2-parse-assign-expr) result)
9026 while
9027 (js2-match-token js2-COMMA))
9028 (js2-must-match js2-RP "msg.no.paren.arg")
9029 result)))
9030
9031 (defun js2-parse-member-expr (&optional allow-call-syntax)
9032 (let ((tt (js2-peek-token))
9033 pn
9034 pos
9035 target
9036 args
9037 beg
9038 end
9039 init
9040 tail)
9041 (if (/= tt js2-NEW)
9042 (setq pn (js2-parse-primary-expr))
9043 ;; parse a 'new' expression
9044 (js2-consume-token)
9045 (setq pos js2-token-beg
9046 beg pos
9047 target (js2-parse-member-expr)
9048 end (js2-node-end target)
9049 pn (make-js2-new-node :pos pos
9050 :target target
9051 :len (- end pos)))
9052 (js2-node-add-children pn target)
9053 (when (js2-match-token js2-LP)
9054 ;; Add the arguments to pn, if any are supplied.
9055 (setf beg pos ; start of "new" keyword
9056 pos js2-token-beg
9057 args (nreverse (js2-parse-argument-list))
9058 (js2-new-node-args pn) args
9059 end js2-token-end
9060 (js2-new-node-lp pn) (- pos beg)
9061 (js2-new-node-rp pn) (- end 1 beg))
9062 (apply #'js2-node-add-children pn args))
9063 (when (and js2-allow-rhino-new-expr-initializer
9064 (js2-match-token js2-LC))
9065 (setf init (js2-parse-object-literal)
9066 end (js2-node-end init)
9067 (js2-new-node-initializer pn) init)
9068 (js2-node-add-children pn init))
9069 (setf (js2-node-len pn) (- end beg))) ; end outer if
9070 (js2-parse-member-expr-tail allow-call-syntax pn)))
9071
9072 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9073 "Parse a chain of property/array accesses or function calls.
9074 Includes parsing for E4X operators like `..' and `.@'.
9075 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9076 Returns an expression tree that includes PN, the parent node."
9077 (let ((beg (js2-node-pos pn))
9078 tt
9079 (continue t))
9080 (while continue
9081 (setq tt (js2-peek-token))
9082 (cond
9083 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9084 (setq pn (js2-parse-property-access tt pn)))
9085 ((= tt js2-DOTQUERY)
9086 (setq pn (js2-parse-dot-query pn)))
9087 ((= tt js2-LB)
9088 (setq pn (js2-parse-element-get pn)))
9089 ((= tt js2-LP)
9090 (if allow-call-syntax
9091 (setq pn (js2-parse-function-call pn))
9092 (setq continue nil)))
9093 (t
9094 (setq continue nil))))
9095 (if (>= js2-highlight-level 2)
9096 (js2-parse-highlight-member-expr-node pn))
9097 pn))
9098
9099 (defun js2-parse-dot-query (pn)
9100 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9101 Last token parsed must be `js2-DOTQUERY'."
9102 (let ((pos (js2-node-pos pn))
9103 op-pos
9104 expr
9105 end)
9106 (js2-consume-token)
9107 (js2-must-have-xml)
9108 (js2-set-requires-activation)
9109 (setq op-pos js2-token-beg
9110 expr (js2-parse-expr)
9111 end (js2-node-end expr)
9112 pn (make-js2-xml-dot-query-node :left pn
9113 :pos pos
9114 :op-pos op-pos
9115 :right expr))
9116 (js2-node-add-children pn
9117 (js2-xml-dot-query-node-left pn)
9118 (js2-xml-dot-query-node-right pn))
9119 (if (js2-must-match js2-RP "msg.no.paren")
9120 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9121 end js2-token-end))
9122 (setf (js2-node-len pn) (- end pos))
9123 pn))
9124
9125 (defun js2-parse-element-get (pn)
9126 "Parse an element-get expression, e.g. foo[bar].
9127 Last token parsed must be `js2-RB'."
9128 (let ((lb js2-token-beg)
9129 (pos (js2-node-pos pn))
9130 rb
9131 expr)
9132 (js2-consume-token)
9133 (setq expr (js2-parse-expr))
9134 (if (js2-must-match js2-RB "msg.no.bracket.index")
9135 (setq rb js2-token-beg))
9136 (setq pn (make-js2-elem-get-node :target pn
9137 :pos pos
9138 :element expr
9139 :lb (js2-relpos lb pos)
9140 :rb (js2-relpos rb pos)
9141 :len (- js2-token-end pos)))
9142 (js2-node-add-children pn
9143 (js2-elem-get-node-target pn)
9144 (js2-elem-get-node-element pn))
9145 pn))
9146
9147 (defun js2-parse-function-call (pn)
9148 (let (args
9149 (pos (js2-node-pos pn)))
9150 (js2-consume-token)
9151 (setq pn (make-js2-call-node :pos pos
9152 :target pn
9153 :lp (- js2-token-beg pos)))
9154 (js2-node-add-children pn (js2-call-node-target pn))
9155 ;; Add the arguments to pn, if any are supplied.
9156 (setf args (nreverse (js2-parse-argument-list))
9157 (js2-call-node-rp pn) (- js2-token-beg pos)
9158 (js2-call-node-args pn) args)
9159 (apply #'js2-node-add-children pn args)
9160 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9161 pn))
9162
9163 (defun js2-parse-property-access (tt pn)
9164 "Parse a property access, XML descendants access, or XML attr access."
9165 (let ((member-type-flags 0)
9166 (dot-pos js2-token-beg)
9167 (dot-len (if (= tt js2-DOTDOT) 2 1))
9168 name
9169 ref ; right side of . or .. operator
9170 result)
9171 (js2-consume-token)
9172 (when (= tt js2-DOTDOT)
9173 (js2-must-have-xml)
9174 (setq member-type-flags js2-descendants-flag))
9175 (if (not js2-compiler-xml-available)
9176 (progn
9177 (js2-must-match-prop-name "msg.no.name.after.dot")
9178 (setq name (js2-create-name-node t js2-GETPROP)
9179 result (make-js2-prop-get-node :left pn
9180 :pos js2-token-beg
9181 :right name
9182 :len (- js2-token-end
9183 js2-token-beg)))
9184 (js2-node-add-children result pn name)
9185 result)
9186 ;; otherwise look for XML operators
9187 (setf result (if (= tt js2-DOT)
9188 (make-js2-prop-get-node)
9189 (make-js2-infix-node :type js2-DOTDOT))
9190 (js2-node-pos result) (js2-node-pos pn)
9191 (js2-infix-node-op-pos result) dot-pos
9192 (js2-infix-node-left result) pn ; do this after setting position
9193 tt (js2-next-token))
9194 (cond
9195 ;; needed for generator.throw()
9196 ((= tt js2-THROW)
9197 (js2-save-name-token-data js2-token-beg "throw")
9198 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9199 ;; handles: name, ns::name, ns::*, ns::[expr]
9200 ((js2-valid-prop-name-token tt)
9201 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9202 ;; handles: *, *::name, *::*, *::[expr]
9203 ((= tt js2-MUL)
9204 (js2-save-name-token-data js2-token-beg "*")
9205 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9206 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9207 ((= tt js2-XMLATTR)
9208 (setq result (js2-parse-attribute-access)))
9209 (t
9210 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9211 (if ref
9212 (setf (js2-node-len result) (- (js2-node-end ref)
9213 (js2-node-pos result))
9214 (js2-infix-node-right result) ref))
9215 (if (js2-infix-node-p result)
9216 (js2-node-add-children result
9217 (js2-infix-node-left result)
9218 (js2-infix-node-right result)))
9219 result)))
9220
9221 (defun js2-parse-attribute-access ()
9222 "Parse an E4X XML attribute expression.
9223 This includes expressions of the forms:
9224
9225 @attr @ns::attr @ns::*
9226 @* @*::attr @*::*
9227 @[expr] @*::[expr] @ns::[expr]
9228
9229 Called if we peeked an '@' token."
9230 (let ((tt (js2-next-token))
9231 (at-pos js2-token-beg))
9232 (cond
9233 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9234 ((js2-valid-prop-name-token tt)
9235 (js2-parse-property-name at-pos js2-ts-string 0))
9236 ;; handles: @*, @*::name, @*::*, @*::[expr]
9237 ((= tt js2-MUL)
9238 (js2-save-name-token-data js2-token-beg "*")
9239 (js2-parse-property-name js2-token-beg "*" 0))
9240 ;; handles @[expr]
9241 ((= tt js2-LB)
9242 (js2-parse-xml-elem-ref at-pos))
9243 (t
9244 (js2-report-error "msg.no.name.after.xmlAttr")
9245 ;; Avoid cascaded errors that happen if we make an error node here.
9246 (js2-save-name-token-data js2-token-beg "")
9247 (js2-parse-property-name js2-token-beg "" 0)))))
9248
9249 (defun js2-parse-property-name (at-pos s member-type-flags)
9250 "Check if :: follows name in which case it becomes qualified name.
9251
9252 AT-POS is a natural number if we just read an '@' token, else nil.
9253 S is the name or string that was matched: an identifier, 'throw' or '*'.
9254 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9255
9256 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9257 operator, or the name is followed by ::. For a plain name, returns a
9258 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9259 (let ((pos (or at-pos js2-token-beg))
9260 colon-pos
9261 (name (js2-create-name-node t js2-current-token))
9262 ns
9263 tt
9264 ref
9265 pn)
9266 (catch 'return
9267 (when (js2-match-token js2-COLONCOLON)
9268 (setq ns name
9269 colon-pos js2-token-beg
9270 tt (js2-next-token))
9271 (cond
9272 ;; handles name::name
9273 ((js2-valid-prop-name-token tt)
9274 (setq name (js2-create-name-node)))
9275 ;; handles name::*
9276 ((= tt js2-MUL)
9277 (js2-save-name-token-data js2-token-beg "*")
9278 (setq name (js2-create-name-node)))
9279 ;; handles name::[expr]
9280 ((= tt js2-LB)
9281 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9282 (t
9283 (js2-report-error "msg.no.name.after.coloncolon"))))
9284 (if (and (null ns) (zerop member-type-flags))
9285 name
9286 (prog1
9287 (setq pn
9288 (make-js2-xml-prop-ref-node :pos pos
9289 :len (- (js2-node-end name) pos)
9290 :at-pos at-pos
9291 :colon-pos colon-pos
9292 :propname name))
9293 (js2-node-add-children pn name))))))
9294
9295 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9296 "Parse the [expr] portion of an xml element reference.
9297 For instance, @[expr], @*::[expr], or ns::[expr]."
9298 (let* ((lb js2-token-beg)
9299 (pos (or at-pos lb))
9300 rb
9301 (expr (js2-parse-expr))
9302 (end (js2-node-end expr))
9303 pn)
9304 (if (js2-must-match js2-RB "msg.no.bracket.index")
9305 (setq rb js2-token-beg
9306 end js2-token-end))
9307 (prog1
9308 (setq pn
9309 (make-js2-xml-elem-ref-node :pos pos
9310 :len (- end pos)
9311 :namespace namespace
9312 :colon-pos colon-pos
9313 :at-pos at-pos
9314 :expr expr
9315 :lb (js2-relpos lb pos)
9316 :rb (js2-relpos rb pos)))
9317 (js2-node-add-children pn namespace expr))))
9318
9319 (defun js2-parse-destruct-primary-expr ()
9320 (let ((js2-is-in-destructuring t))
9321 (js2-parse-primary-expr)))
9322
9323 (defun js2-parse-primary-expr ()
9324 "Parses a literal (leaf) expression of some sort.
9325 Includes complex literals such as functions, object-literals,
9326 array-literals, array comprehensions and regular expressions."
9327 (let ((tt-flagged (js2-next-flagged-token))
9328 pn ; parent node (usually return value)
9329 tt
9330 px-pos ; paren-expr pos
9331 len
9332 flags ; regexp flags
9333 expr)
9334 (setq tt js2-current-token)
9335 (cond
9336 ((= tt js2-FUNCTION)
9337 (js2-parse-function 'FUNCTION_EXPRESSION))
9338 ((= tt js2-LB)
9339 (js2-parse-array-literal))
9340 ((= tt js2-LC)
9341 (js2-parse-object-literal))
9342 ((= tt js2-LET)
9343 (js2-parse-let js2-token-beg))
9344 ((= tt js2-LP)
9345 (setq px-pos js2-token-beg
9346 expr (js2-parse-expr))
9347 (js2-must-match js2-RP "msg.no.paren")
9348 (setq pn (make-js2-paren-node :pos px-pos
9349 :expr expr
9350 :len (- js2-token-end px-pos)))
9351 (js2-node-add-children pn (js2-paren-node-expr pn))
9352 pn)
9353 ((= tt js2-XMLATTR)
9354 (js2-must-have-xml)
9355 (js2-parse-attribute-access))
9356 ((= tt js2-NAME)
9357 (js2-parse-name tt-flagged tt))
9358 ((= tt js2-NUMBER)
9359 (make-js2-number-node))
9360 ((= tt js2-STRING)
9361 (prog1
9362 (make-js2-string-node)
9363 (js2-record-face 'font-lock-string-face)))
9364 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9365 ;; Got / or /= which in this context means a regexp literal
9366 (setq px-pos js2-token-beg)
9367 (js2-read-regexp tt)
9368 (setq flags js2-ts-regexp-flags
9369 js2-ts-regexp-flags nil)
9370 (prog1
9371 (make-js2-regexp-node :pos px-pos
9372 :len (- js2-ts-cursor px-pos)
9373 :value js2-ts-string
9374 :flags flags)
9375 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9376 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9377 ((or (= tt js2-NULL)
9378 (= tt js2-THIS)
9379 (= tt js2-FALSE)
9380 (= tt js2-TRUE))
9381 (make-js2-keyword-node :type tt))
9382 ((= tt js2-RESERVED)
9383 (js2-report-error "msg.reserved.id")
9384 (make-js2-name-node))
9385 ((= tt js2-ERROR)
9386 ;; the scanner or one of its subroutines reported the error.
9387 (make-js2-error-node))
9388 ((= tt js2-EOF)
9389 (setq px-pos (point-at-bol)
9390 len (- js2-ts-cursor px-pos))
9391 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9392 (make-js2-error-node :pos px-pos :len len))
9393 (t
9394 (js2-report-error "msg.syntax")
9395 (make-js2-error-node)))))
9396
9397 (defun js2-parse-name (tt-flagged tt)
9398 (let ((name js2-ts-string)
9399 (name-pos js2-token-beg)
9400 node)
9401 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9402 (= (js2-peek-token) js2-COLON))
9403 (prog1
9404 ;; Do not consume colon, it is used as unwind indicator
9405 ;; to return to statementHelper.
9406 (make-js2-label-node :pos name-pos
9407 :len (- js2-token-end name-pos)
9408 :name name)
9409 (js2-set-face name-pos
9410 js2-token-end
9411 'font-lock-variable-name-face 'record))
9412 ;; Otherwise not a label, just a name. Unfortunately peeking
9413 ;; the next token to check for a colon has biffed js2-token-beg
9414 ;; and js2-token-end. We store the name's bounds in buffer vars
9415 ;; and `js2-create-name-node' uses them.
9416 (js2-save-name-token-data name-pos name)
9417 (setq node (if js2-compiler-xml-available
9418 (js2-parse-property-name nil name 0)
9419 (js2-create-name-node 'check-activation)))
9420 (if js2-highlight-external-variables
9421 (js2-record-name-node node))
9422 node)))
9423
9424 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9425 (js2-add-strict-warning
9426 msg nil
9427 ;; back up from comma to beginning of line or array/objlit
9428 (max (if elems
9429 (js2-node-pos (car elems))
9430 pos)
9431 (save-excursion
9432 (goto-char comma-pos)
9433 (back-to-indentation)
9434 (point)))
9435 comma-pos))
9436
9437 (defun js2-parse-array-literal ()
9438 (let ((pos js2-token-beg)
9439 (end js2-token-end)
9440 (after-lb-or-comma t)
9441 after-comma
9442 tt
9443 elems
9444 pn
9445 (continue t))
9446 (unless js2-is-in-destructuring
9447 (js2-push-scope (make-js2-scope))) ; for array comp
9448 (while continue
9449 (setq tt (js2-peek-token))
9450 (cond
9451 ;; comma
9452 ((= tt js2-COMMA)
9453 (js2-consume-token)
9454 (setq after-comma js2-token-end)
9455 (if (not after-lb-or-comma)
9456 (setq after-lb-or-comma t)
9457 (push nil elems)))
9458 ;; end of array
9459 ((or (= tt js2-RB)
9460 (= tt js2-EOF)) ; prevent infinite loop
9461 (if (= tt js2-EOF)
9462 (js2-report-error "msg.no.bracket.arg" nil pos)
9463 (js2-consume-token))
9464 (setq continue nil
9465 end js2-token-end
9466 pn (make-js2-array-node :pos pos
9467 :len (- js2-ts-cursor pos)
9468 :elems (nreverse elems)))
9469 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9470 (when (and after-comma (not js2-is-in-destructuring))
9471 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9472 pos elems after-comma)))
9473 ;; destructuring binding
9474 (js2-is-in-destructuring
9475 (push (if (or (= tt js2-LC)
9476 (= tt js2-LB)
9477 (= tt js2-NAME))
9478 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9479 (js2-parse-destruct-primary-expr)
9480 ;; invalid pattern
9481 (js2-consume-token)
9482 (js2-report-error "msg.bad.var")
9483 (make-js2-error-node))
9484 elems)
9485 (setq after-lb-or-comma nil
9486 after-comma nil))
9487 ;; array comp
9488 ((and (>= js2-language-version 170)
9489 (= tt js2-FOR) ; check for array comprehension
9490 (not after-lb-or-comma) ; "for" can't follow a comma
9491 elems ; must have at least 1 element
9492 (not (cdr elems))) ; but no 2nd element
9493 (setf continue nil
9494 pn (js2-parse-array-comprehension (car elems) pos)))
9495
9496 ;; another element
9497 (t
9498 (unless after-lb-or-comma
9499 (js2-report-error "msg.no.bracket.arg"))
9500 (push (js2-parse-assign-expr) elems)
9501 (setq after-lb-or-comma nil
9502 after-comma nil))))
9503 (unless js2-is-in-destructuring
9504 (js2-pop-scope))
9505 pn))
9506
9507 (defun js2-parse-array-comprehension (expr pos)
9508 "Parse a JavaScript 1.7 Array Comprehension.
9509 EXPR is the first expression after the opening left-bracket.
9510 POS is the beginning of the LB token preceding EXPR.
9511 We should have just parsed the 'for' keyword before calling this function."
9512 (let (loops
9513 loop
9514 first
9515 prev
9516 filter
9517 if-pos
9518 result)
9519 (while (= (js2-peek-token) js2-FOR)
9520 (let ((prev (car loops))) ; rearrange scope chain
9521 (push (setq loop (js2-parse-array-comp-loop)) loops)
9522 (if prev ; each loop is parent scope to the next one
9523 (setf (js2-scope-parent-scope loop) prev)
9524 ; first loop takes expr scope's parent
9525 (setf (js2-scope-parent-scope (setq first loop))
9526 (js2-scope-parent-scope js2-current-scope)))))
9527 ;; set expr scope's parent to the last loop
9528 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9529 (when (= (js2-peek-token) js2-IF)
9530 (js2-consume-token)
9531 (setq if-pos (- js2-token-beg pos) ; relative
9532 filter (js2-parse-condition)))
9533 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9534 (setq result (make-js2-array-comp-node :pos pos
9535 :len (- js2-ts-cursor pos)
9536 :result expr
9537 :loops (nreverse loops)
9538 :filter (car filter)
9539 :lp (js2-relpos (second filter) pos)
9540 :rp (js2-relpos (third filter) pos)
9541 :if-pos if-pos))
9542 (apply #'js2-node-add-children result expr (car filter)
9543 (js2-array-comp-node-loops result))
9544 (setq js2-current-scope first) ; pop to the first loop
9545 result))
9546
9547 (defun js2-parse-array-comp-loop ()
9548 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9549 Last token peeked should be the initial FOR."
9550 (let ((pos js2-token-beg)
9551 (pn (make-js2-array-comp-loop-node))
9552 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9553 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9554 (js2-push-scope pn)
9555 (unwind-protect
9556 (progn
9557 (when (js2-match-token js2-NAME)
9558 (if (string= js2-ts-string "each")
9559 (progn
9560 (setq foreach-p t
9561 each-pos (- js2-token-beg pos)) ; relative
9562 (js2-record-face 'font-lock-keyword-face))
9563 (js2-report-error "msg.no.paren.for")))
9564 (if (js2-must-match js2-LP "msg.no.paren.for")
9565 (setq lp (- js2-token-beg pos)))
9566 (setq tt (js2-peek-token))
9567 (cond
9568 ((or (= tt js2-LB)
9569 (= tt js2-LC))
9570 (setq iter (js2-parse-destruct-primary-expr))
9571 (js2-define-destruct-symbols iter js2-LET
9572 'font-lock-variable-name-face t))
9573 ((js2-match-token js2-NAME)
9574 (setq iter (js2-create-name-node)))
9575 (t
9576 (js2-report-error "msg.bad.var")))
9577 ;; Define as a let since we want the scope of the variable to
9578 ;; be restricted to the array comprehension
9579 (if (js2-name-node-p iter)
9580 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9581 (if (or (js2-match-token js2-IN)
9582 (and (>= js2-language-version 200)
9583 (js2-match-contextual-kwd "of")
9584 (setq forof-p t)))
9585 (setq in-pos (- js2-token-beg pos))
9586 (js2-report-error "msg.in.after.for.name"))
9587 (setq obj (js2-parse-expr))
9588 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9589 (setq rp (- js2-token-beg pos)))
9590 (setf (js2-node-pos pn) pos
9591 (js2-node-len pn) (- js2-ts-cursor pos)
9592 (js2-array-comp-loop-node-iterator pn) iter
9593 (js2-array-comp-loop-node-object pn) obj
9594 (js2-array-comp-loop-node-in-pos pn) in-pos
9595 (js2-array-comp-loop-node-each-pos pn) each-pos
9596 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9597 (js2-array-comp-loop-node-forof-p pn) forof-p
9598 (js2-array-comp-loop-node-lp pn) lp
9599 (js2-array-comp-loop-node-rp pn) rp)
9600 (js2-node-add-children pn iter obj))
9601 (js2-pop-scope))
9602 pn))
9603
9604 (defun js2-parse-object-literal ()
9605 (let ((pos js2-token-beg)
9606 tt
9607 elems
9608 result
9609 after-comma
9610 (continue t))
9611 (while continue
9612 (setq tt (js2-peek-token))
9613 (cond
9614 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9615 ((or (js2-valid-prop-name-token tt)
9616 (= tt js2-STRING))
9617 (setq after-comma nil
9618 result (js2-parse-named-prop tt))
9619 (if (and (null result)
9620 (not js2-recover-from-parse-errors))
9621 (setq continue nil)
9622 (push result elems)))
9623 ;; {12: x} or {10.7: x}
9624 ((= tt js2-NUMBER)
9625 (js2-consume-token)
9626 (setq after-comma nil)
9627 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9628 ;; trailing comma
9629 ((= tt js2-RC)
9630 (setq continue nil)
9631 (if after-comma
9632 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9633 pos elems after-comma)))
9634 (t
9635 (js2-report-error "msg.bad.prop")
9636 (unless js2-recover-from-parse-errors
9637 (setq continue nil)))) ; end switch
9638 (if (js2-match-token js2-COMMA)
9639 (setq after-comma js2-token-end)
9640 (setq continue nil))) ; end loop
9641 (js2-must-match js2-RC "msg.no.brace.prop")
9642 (setq result (make-js2-object-node :pos pos
9643 :len (- js2-ts-cursor pos)
9644 :elems (nreverse elems)))
9645 (apply #'js2-node-add-children result (js2-object-node-elems result))
9646 result))
9647
9648 (defun js2-parse-named-prop (tt)
9649 "Parse a name, string, or getter/setter object property.
9650 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9651 (js2-consume-token)
9652 (let ((string-prop (and (= tt js2-STRING)
9653 (make-js2-string-node)))
9654 expr
9655 (ppos js2-token-beg)
9656 (pend js2-token-end)
9657 (name (js2-create-name-node))
9658 (prop js2-ts-string))
9659 (cond
9660 ;; getter/setter prop
9661 ((and (= tt js2-NAME)
9662 (= (js2-peek-token) js2-NAME)
9663 (or (string= prop "get")
9664 (string= prop "set")))
9665 (js2-consume-token)
9666 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9667 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9668 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9669 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9670 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9671 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9672 ;; when patterns are used in variable declarations, function parameters,
9673 ;; catch-clause, and iterators.
9674 ;; We have to set `js2-is-in-destructuring' to t when the current
9675 ;; expressions are on the left side of any assignment, but it's difficult
9676 ;; because it requires looking ahead of expression.
9677 ((and js2-is-in-destructuring
9678 (= tt js2-NAME)
9679 (let ((ctk (js2-peek-token)))
9680 (or (= ctk js2-COMMA)
9681 (= ctk js2-RC)
9682 (js2-valid-prop-name-token ctk))))
9683 name)
9684 ;; regular prop
9685 (t
9686 (prog1
9687 (setq expr (js2-parse-plain-property (or string-prop name)))
9688 (js2-set-face ppos pend
9689 (if (js2-function-node-p
9690 (js2-object-prop-node-right expr))
9691 'font-lock-function-name-face
9692 'font-lock-variable-name-face)
9693 'record))))))
9694
9695 (defun js2-parse-plain-property (prop)
9696 "Parse a non-getter/setter property in an object literal.
9697 PROP is the node representing the property: a number, name or string."
9698 (js2-must-match js2-COLON "msg.no.colon.prop")
9699 (let* ((pos (js2-node-pos prop))
9700 (colon (- js2-token-beg pos))
9701 (expr (js2-parse-assign-expr))
9702 (result (make-js2-object-prop-node
9703 :pos pos
9704 ;; don't include last consumed token in length
9705 :len (- (+ (js2-node-pos expr)
9706 (js2-node-len expr))
9707 pos)
9708 :left prop
9709 :right expr
9710 :op-pos colon)))
9711 (js2-node-add-children result prop expr)
9712 result))
9713
9714 (defun js2-parse-getter-setter-prop (pos prop get-p)
9715 "Parse getter or setter property in an object literal.
9716 JavaScript syntax is:
9717
9718 { get foo() {...}, set foo(x) {...} }
9719
9720 and expression closure style is also supported
9721
9722 { get foo() x, set foo(x) _x = x }
9723
9724 POS is the start position of the `get' or `set' keyword.
9725 PROP is the `js2-name-node' representing the property name.
9726 GET-P is non-nil if the keyword was `get'."
9727 (let ((type (if get-p js2-GET js2-SET))
9728 result
9729 end
9730 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9731 ;; it has to be an anonymous function, as we already parsed the name
9732 (if (/= (js2-node-type fn) js2-FUNCTION)
9733 (js2-report-error "msg.bad.prop")
9734 (if (plusp (length (js2-function-name fn)))
9735 (js2-report-error "msg.bad.prop")))
9736 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9737 (setq end (js2-node-end fn)
9738 result (make-js2-getter-setter-node :type type
9739 :pos pos
9740 :len (- end pos)
9741 :left prop
9742 :right fn))
9743 (js2-node-add-children result prop fn)
9744 result))
9745
9746 (defun js2-create-name-node (&optional check-activation-p token)
9747 "Create a name node using the token info from last scanned name.
9748 In some cases we need to either synthesize a name node, or we lost
9749 the name token information by peeking. If the TOKEN parameter is
9750 not `js2-NAME', then we use the token info saved in instance vars."
9751 (let ((beg js2-token-beg)
9752 (s js2-ts-string)
9753 name)
9754 (when (/= js2-current-token js2-NAME)
9755 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9756 s js2-prev-name-token-string
9757 js2-prev-name-token-start nil
9758 js2-prev-name-token-string nil))
9759 (setq name (make-js2-name-node :pos beg
9760 :name s
9761 :len (length s)))
9762 (if check-activation-p
9763 (js2-check-activation-name s (or token js2-NAME)))
9764 name))
9765
9766 ;;; Indentation support
9767
9768 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9769 ;; Karl cleverly deduces that the desired indentation level is often a
9770 ;; function of paren/bracket/brace nesting depth, which can be determined
9771 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9772 ;; then does some equally clever checks to see if we're in the context of a
9773 ;; substatement of a possibly braceless statement keyword such as if, while,
9774 ;; or finally. This approach yields pretty good results.
9775
9776 ;; The indenter is often "wrong", however, and needs to be overridden.
9777 ;; The right long-term solution is probably to emulate (or integrate
9778 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9779 ;; parse tree from `js2-parse' is present, which is not true at the
9780 ;; moment the user is typing, computing indentation is still thousands
9781 ;; of lines of code to handle every possible syntactic edge case.
9782
9783 ;; In the meantime, the compromise solution is that we offer a "bounce
9784 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9785 ;; current line indent among various likely guess points. This approach
9786 ;; is far from perfect, but should at least make it slightly easier to
9787 ;; move the line towards its desired indentation when manually
9788 ;; overriding Karl's heuristic nesting guesser.
9789
9790 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9791 ;; extensions such as `let' and Array comprehensions. Major kudos to
9792 ;; Karl for coming up with the initial approach, which packs a lot of
9793 ;; punch for so little code.
9794
9795 (defconst js2-possibly-braceless-keywords-re
9796 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9797 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9798 "try" "while" "with" "let")))
9799 "Regular expression matching keywords that are optionally
9800 followed by an opening brace.")
9801
9802 (defconst js2-indent-operator-re
9803 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9804 (regexp-opt '("in" "instanceof") 'words))
9805 "Regular expression matching operators that affect indentation
9806 of continued expressions.")
9807
9808 (defconst js2-declaration-keyword-re
9809 (regexp-opt '("var" "let" "const") 'words)
9810 "Regular expression matching variable declaration keywords.")
9811
9812 ;; This function has horrible results if you're typing an array
9813 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9814 ;; in conjunction with electric-indent, so just disabling it.
9815 (defsubst js2-code-at-bol-p ()
9816 "Return t if the first character on line is non-whitespace."
9817 nil)
9818
9819 (defun js2-insert-and-indent (key)
9820 "Run command bound to key and indent current line. Runs the command
9821 bound to KEY in the global keymap and indents the current line."
9822 (interactive (list (this-command-keys)))
9823 (let ((cmd (lookup-key (current-global-map) key)))
9824 (if (commandp cmd)
9825 (call-interactively cmd)))
9826 ;; don't do the electric keys inside comments or strings,
9827 ;; and don't do bounce-indent with them.
9828 (let ((parse-state (syntax-ppss (point)))
9829 (js2-bounce-indent-p (js2-code-at-bol-p)))
9830 (unless (or (nth 3 parse-state)
9831 (nth 4 parse-state))
9832 (indent-according-to-mode))))
9833
9834 (defun js2-re-search-forward-inner (regexp &optional bound count)
9835 "Auxiliary function for `js2-re-search-forward'."
9836 (let (parse saved-point)
9837 (while (> count 0)
9838 (re-search-forward regexp bound)
9839 (setq parse (if saved-point
9840 (parse-partial-sexp saved-point (point))
9841 (syntax-ppss (point))))
9842 (cond ((nth 3 parse)
9843 (re-search-forward
9844 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9845 (save-excursion (end-of-line) (point)) t))
9846 ((nth 7 parse)
9847 (forward-line))
9848 ((or (nth 4 parse)
9849 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9850 (re-search-forward "\\*/"))
9851 (t
9852 (setq count (1- count))))
9853 (setq saved-point (point))))
9854 (point))
9855
9856 (defun js2-re-search-forward (regexp &optional bound noerror count)
9857 "Search forward but ignore strings and comments. Invokes
9858 `re-search-forward' but treats the buffer as if strings and
9859 comments have been removed."
9860 (let ((saved-point (point))
9861 (search-expr
9862 (cond ((null count)
9863 '(js2-re-search-forward-inner regexp bound 1))
9864 ((< count 0)
9865 '(js2-re-search-backward-inner regexp bound (- count)))
9866 ((> count 0)
9867 '(js2-re-search-forward-inner regexp bound count)))))
9868 (condition-case err
9869 (eval search-expr)
9870 (search-failed
9871 (goto-char saved-point)
9872 (unless noerror
9873 (error (error-message-string err)))))))
9874
9875 (defun js2-re-search-backward-inner (regexp &optional bound count)
9876 "Auxiliary function for `js2-re-search-backward'."
9877 (let (parse saved-point)
9878 (while (> count 0)
9879 (re-search-backward regexp bound)
9880 (setq parse (if saved-point
9881 (parse-partial-sexp saved-point (point))
9882 (syntax-ppss (point))))
9883 (cond ((nth 3 parse)
9884 (re-search-backward
9885 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9886 (save-excursion (beginning-of-line) (point)) t))
9887 ((nth 7 parse)
9888 (goto-char (nth 8 parse)))
9889 ((or (nth 4 parse)
9890 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9891 (re-search-backward "/\\*"))
9892 (t
9893 (setq count (1- count))))))
9894 (point))
9895
9896 (defun js2-re-search-backward (regexp &optional bound noerror count)
9897 "Search backward but ignore strings and comments. Invokes
9898 `re-search-backward' but treats the buffer as if strings and
9899 comments have been removed."
9900 (let ((saved-point (point))
9901 (search-expr
9902 (cond ((null count)
9903 '(js2-re-search-backward-inner regexp bound 1))
9904 ((< count 0)
9905 '(js2-re-search-forward-inner regexp bound (- count)))
9906 ((> count 0)
9907 '(js2-re-search-backward-inner regexp bound count)))))
9908 (condition-case err
9909 (eval search-expr)
9910 (search-failed
9911 (goto-char saved-point)
9912 (unless noerror
9913 (error (error-message-string err)))))))
9914
9915 (defun js2-looking-at-operator-p ()
9916 "Return non-nil if text after point is an operator (that is not
9917 a comma)."
9918 (save-match-data
9919 (and (looking-at js2-indent-operator-re)
9920 (or (not (looking-at ":"))
9921 (save-excursion
9922 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9923 (looking-at "?")))))))
9924
9925 (defun js2-continued-expression-p ()
9926 "Returns non-nil if the current line continues an expression."
9927 (save-excursion
9928 (back-to-indentation)
9929 (or (js2-looking-at-operator-p)
9930 (when (catch 'found
9931 (while (and (re-search-backward "\n" nil t)
9932 (let ((state (syntax-ppss)))
9933 (when (nth 4 state)
9934 (goto-char (nth 8 state))) ;; skip comments
9935 (skip-chars-backward " \t")
9936 (if (bolp)
9937 t
9938 (throw 'found t))))))
9939 (backward-char)
9940 (when (js2-looking-at-operator-p)
9941 (backward-char)
9942 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))
9943
9944 (defun js2-end-of-do-while-loop-p ()
9945 "Returns non-nil if word after point is `while' of a do-while
9946 statement, else returns nil. A braceless do-while statement
9947 spanning several lines requires that the start of the loop is
9948 indented to the same column as the current line."
9949 (interactive)
9950 (save-excursion
9951 (save-match-data
9952 (when (looking-at "\\s-*\\<while\\>")
9953 (if (save-excursion
9954 (skip-chars-backward "[ \t\n]*}")
9955 (looking-at "[ \t\n]*}"))
9956 (save-excursion
9957 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9958 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9959 (or (looking-at "\\<do\\>")
9960 (let ((saved-indent (current-indentation)))
9961 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9962 (/= (current-indentation) saved-indent)))
9963 (and (looking-at "[ \t]*\\<do\\>")
9964 (not (js2-re-search-forward
9965 "\\<while\\>" (point-at-eol) t))
9966 (= (current-indentation) saved-indent)))))))))
9967
9968 (defun js2-multiline-decl-indentation ()
9969 "Returns the declaration indentation column if the current line belongs
9970 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9971 (let (forward-sexp-function ; use Lisp version
9972 at-opening-bracket)
9973 (save-excursion
9974 (back-to-indentation)
9975 (when (not (looking-at js2-declaration-keyword-re))
9976 (when (looking-at js2-indent-operator-re)
9977 (goto-char (match-end 0))) ; continued expressions are ok
9978 (while (and (not at-opening-bracket)
9979 (not (bobp))
9980 (let ((pos (point)))
9981 (save-excursion
9982 (js2-backward-sws)
9983 (or (eq (char-before) ?,)
9984 (and (not (eq (char-before) ?\;))
9985 (and
9986 (prog2 (skip-chars-backward "[[:punct:]]")
9987 (looking-at js2-indent-operator-re)
9988 (js2-backward-sws))
9989 (not (eq (char-before) ?\;))))
9990 (js2-same-line pos)))))
9991 (condition-case err
9992 (backward-sexp)
9993 (scan-error (setq at-opening-bracket t))))
9994 (when (looking-at js2-declaration-keyword-re)
9995 (goto-char (match-end 0))
9996 (1+ (current-column)))))))
9997
9998 (defun js2-ctrl-statement-indentation ()
9999 "Returns the proper indentation of the current line if it
10000 starts the body of a control statement without braces, else
10001 returns nil."
10002 (let (forward-sexp-function) ; temporarily unbind it
10003 (save-excursion
10004 (back-to-indentation)
10005 (when (and (not (js2-same-line (point-min)))
10006 (not (looking-at "{"))
10007 (js2-re-search-backward "[[:graph:]]" nil t)
10008 (not (looking-at "[{([]"))
10009 (progn
10010 (forward-char)
10011 (when (= (char-before) ?\))
10012 ;; scan-sexps sometimes throws an error
10013 (ignore-errors (backward-sexp))
10014 (skip-chars-backward " \t" (point-at-bol)))
10015 (let ((pt (point)))
10016 (back-to-indentation)
10017 (and (looking-at js2-possibly-braceless-keywords-re)
10018 (= (match-end 0) pt)
10019 (not (js2-end-of-do-while-loop-p))))))
10020 (+ (current-indentation) js2-basic-offset)))))
10021
10022 (defun js2-indent-in-array-comp (parse-status)
10023 "Return non-nil if we think we're in an array comprehension.
10024 In particular, return the buffer position of the first `for' kwd."
10025 (let ((bracket (nth 1 parse-status))
10026 (end (point)))
10027 (when bracket
10028 (save-excursion
10029 (goto-char bracket)
10030 (when (looking-at "\\[")
10031 (forward-char 1)
10032 (js2-forward-sws)
10033 (if (looking-at "[[{]")
10034 (let (forward-sexp-function) ; use lisp version
10035 (forward-sexp) ; skip destructuring form
10036 (js2-forward-sws)
10037 (if (and (/= (char-after) ?,) ; regular array
10038 (looking-at "for"))
10039 (match-beginning 0)))
10040 ;; to skip arbitrary expressions we need the parser,
10041 ;; so we'll just guess at it.
10042 (if (and (> end (point)) ; not empty literal
10043 (re-search-forward "[^,]]* \\(for\\) " end t)
10044 ;; not inside comment or string literal
10045 (let ((state (parse-partial-sexp bracket (point))))
10046 (not (or (nth 3 state) (nth 4 state)))))
10047 (match-beginning 1))))))))
10048
10049 (defun js2-array-comp-indentation (parse-status for-kwd)
10050 (if (js2-same-line for-kwd)
10051 ;; first continuation line
10052 (save-excursion
10053 (goto-char (nth 1 parse-status))
10054 (forward-char 1)
10055 (skip-chars-forward " \t")
10056 (current-column))
10057 (save-excursion
10058 (goto-char for-kwd)
10059 (current-column))))
10060
10061 (defun js2-proper-indentation (parse-status)
10062 "Return the proper indentation for the current line."
10063 (save-excursion
10064 (back-to-indentation)
10065 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10066 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
10067 (continued-expr-p (js2-continued-expression-p))
10068 (declaration-indent (and js2-pretty-multiline-declarations
10069 (js2-multiline-decl-indentation)))
10070 (bracket (nth 1 parse-status))
10071 beg)
10072 (cond
10073 ;; indent array comprehension continuation lines specially
10074 ((and bracket
10075 (>= js2-language-version 170)
10076 (not (js2-same-line bracket))
10077 (setq beg (js2-indent-in-array-comp parse-status))
10078 (>= (point) (save-excursion
10079 (goto-char beg)
10080 (point-at-bol)))) ; at or after first loop?
10081 (js2-array-comp-indentation parse-status beg))
10082
10083 (ctrl-stmt-indent)
10084
10085 ((and declaration-indent continued-expr-p)
10086 (+ declaration-indent js2-basic-offset))
10087
10088 (declaration-indent)
10089
10090 (bracket
10091 (goto-char bracket)
10092 (cond
10093 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10094 (when (save-excursion (skip-chars-backward " \t)")
10095 (looking-at ")"))
10096 (backward-list))
10097 (back-to-indentation)
10098 (and (eq js2-pretty-multiline-declarations 'all)
10099 (looking-at js2-declaration-keyword-re)
10100 (goto-char (1+ (match-end 0))))
10101 (cond (same-indent-p
10102 (current-column))
10103 (continued-expr-p
10104 (+ (current-column) (* 2 js2-basic-offset)))
10105 (t
10106 (+ (current-column) js2-basic-offset))))
10107 (t
10108 (unless same-indent-p
10109 (forward-char)
10110 (skip-chars-forward " \t"))
10111 (current-column))))
10112
10113 (continued-expr-p js2-basic-offset)
10114
10115 (t 0)))))
10116
10117 (defun js2-lineup-comment (parse-status)
10118 "Indent a multi-line block comment continuation line."
10119 (let* ((beg (nth 8 parse-status))
10120 (first-line (js2-same-line beg))
10121 (offset (save-excursion
10122 (goto-char beg)
10123 (if (looking-at "/\\*")
10124 (+ 1 (current-column))
10125 0))))
10126 (unless first-line
10127 (indent-line-to offset))))
10128
10129 (defun js2-backward-sws ()
10130 "Move backward through whitespace and comments."
10131 (interactive)
10132 (while (forward-comment -1)))
10133
10134 (defun js2-forward-sws ()
10135 "Move forward through whitespace and comments."
10136 (interactive)
10137 (while (forward-comment 1)))
10138
10139 (defsubst js2-current-indent (&optional pos)
10140 "Return column of indentation on current line.
10141 If POS is non-nil, go to that point and return indentation for that line."
10142 (save-excursion
10143 (if pos
10144 (goto-char pos))
10145 (back-to-indentation)
10146 (current-column)))
10147
10148 (defsubst js2-arglist-close ()
10149 "Return non-nil if we're on a line beginning with a close-paren/brace."
10150 (save-match-data
10151 (save-excursion
10152 (goto-char (point-at-bol))
10153 (js2-forward-sws)
10154 (looking-at "[])}]"))))
10155
10156 (defsubst js2-indent-looks-like-label-p ()
10157 (goto-char (point-at-bol))
10158 (js2-forward-sws)
10159 (looking-at (concat js2-mode-identifier-re ":")))
10160
10161 (defun js2-indent-in-objlit-p (parse-status)
10162 "Return non-nil if this looks like an object-literal entry."
10163 (let ((start (nth 1 parse-status)))
10164 (and
10165 start
10166 (save-excursion
10167 (and (zerop (forward-line -1))
10168 (not (< (point) start)) ; crossed a {} boundary
10169 (js2-indent-looks-like-label-p)))
10170 (save-excursion
10171 (js2-indent-looks-like-label-p)))))
10172
10173 ;; if prev line looks like foobar({ then we're passing an object
10174 ;; literal to a function call, and people pretty much always want to
10175 ;; de-dent back to the previous line, so move the 'basic-offset'
10176 ;; position to the front.
10177 (defsubst js2-indent-objlit-arg-p (parse-status)
10178 (save-excursion
10179 (back-to-indentation)
10180 (js2-backward-sws)
10181 (and (eq (1- (point)) (nth 1 parse-status))
10182 (eq (char-before) ?{)
10183 (progn
10184 (forward-char -1)
10185 (skip-chars-backward " \t")
10186 (eq (char-before) ?\()))))
10187
10188 (defsubst js2-indent-case-block-p ()
10189 (save-excursion
10190 (back-to-indentation)
10191 (js2-backward-sws)
10192 (goto-char (point-at-bol))
10193 (skip-chars-forward " \t")
10194 (save-match-data
10195 (looking-at "case\\s-.+:"))))
10196
10197 (defsubst js2-syntax-bol ()
10198 "Return the point at the first non-whitespace char on the line.
10199 Returns `point-at-bol' if the line is empty."
10200 (save-excursion
10201 (beginning-of-line)
10202 (skip-chars-forward " \t")
10203 (point)))
10204
10205 (defun js2-bounce-indent (normal-col parse-status backwards)
10206 "Cycle among alternate computed indentation positions.
10207 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10208 of the buffer to the current point. NORMAL-COL is the indentation
10209 column computed by the heuristic guesser based on current paren,
10210 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10211 in reverse."
10212 (let ((cur-indent (js2-current-indent))
10213 (old-buffer-undo-list buffer-undo-list)
10214 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10215 (current-line (save-excursion
10216 (forward-line 0) ; move to bol
10217 (1+ (count-lines (point-min) (point)))))
10218 positions
10219 pos
10220 main-pos
10221 anchor
10222 arglist-cont
10223 same-indent
10224 prev-line-col
10225 basic-offset
10226 computed-pos)
10227 ;; temporarily don't record undo info, if user requested this
10228 (if js2-mode-indent-inhibit-undo
10229 (setq buffer-undo-list t))
10230 (unwind-protect
10231 (progn
10232 ;; first likely point: indent from beginning of previous code line
10233 (push (setq basic-offset
10234 (+ (save-excursion
10235 (back-to-indentation)
10236 (js2-backward-sws)
10237 (back-to-indentation)
10238 (setq prev-line-col (current-column)))
10239 js2-basic-offset))
10240 positions)
10241
10242 ;; (first + epsilon) likely point: indent 2x from beginning of
10243 ;; previous code line. Some companies like this approach. Ahem.
10244 ;; Seriously, though -- 4-space indent for expression continuation
10245 ;; lines isn't a bad idea. We should eventually implement it
10246 ;; that way.
10247 (push (setq basic-offset
10248 (+ (save-excursion
10249 (back-to-indentation)
10250 (js2-backward-sws)
10251 (back-to-indentation)
10252 (setq prev-line-col (current-column)))
10253 (* 2 js2-basic-offset)))
10254 positions)
10255
10256 ;; second likely point: indent from assign-expr RHS. This
10257 ;; is just a crude guess based on finding " = " on the previous
10258 ;; line containing actual code.
10259 (setq pos (save-excursion
10260 (save-match-data
10261 (forward-line -1)
10262 (goto-char (point-at-bol))
10263 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10264 (point-at-eol) t)
10265 (goto-char (match-end 1))
10266 (skip-chars-forward " \t\r\n")
10267 (current-column)))))
10268 (when pos
10269 (incf pos js2-basic-offset)
10270 (push pos positions))
10271
10272 ;; third likely point: same indent as previous line of code.
10273 ;; Make it the first likely point if we're not on an
10274 ;; arglist-close line and previous line ends in a comma, or
10275 ;; both this line and prev line look like object-literal
10276 ;; elements.
10277 (setq pos (save-excursion
10278 (goto-char (point-at-bol))
10279 (js2-backward-sws)
10280 (back-to-indentation)
10281 (prog1
10282 (current-column)
10283 ;; while we're here, look for trailing comma
10284 (if (save-excursion
10285 (goto-char (point-at-eol))
10286 (js2-backward-sws)
10287 (eq (char-before) ?,))
10288 (setq arglist-cont (1- (point)))))))
10289 (when pos
10290 (if (and (or arglist-cont
10291 (js2-indent-in-objlit-p parse-status))
10292 (not (js2-arglist-close)))
10293 (setq same-indent pos))
10294 (push pos positions))
10295
10296 ;; fourth likely point: first preceding code with less indentation
10297 ;; than the immediately preceding code line.
10298 (setq pos (save-excursion
10299 (back-to-indentation)
10300 (js2-backward-sws)
10301 (back-to-indentation)
10302 (setq anchor (current-column))
10303 (while (and (zerop (forward-line -1))
10304 (>= (progn
10305 (back-to-indentation)
10306 (current-column))
10307 anchor)))
10308 (setq pos (current-column))))
10309 (push pos positions)
10310
10311 ;; nesting-heuristic position, main by default
10312 (push (setq main-pos normal-col) positions)
10313
10314 ;; delete duplicates and sort positions list
10315 (setq positions (sort (delete-dups positions) '<))
10316
10317 ;; comma-list continuation lines: prev line indent takes precedence
10318 (if same-indent
10319 (setq main-pos same-indent))
10320
10321 ;; common special cases where we want to indent in from previous line
10322 (if (or (js2-indent-case-block-p)
10323 (js2-indent-objlit-arg-p parse-status))
10324 (setq main-pos basic-offset))
10325
10326 ;; if bouncing backwards, reverse positions list
10327 (if backwards
10328 (setq positions (reverse positions)))
10329
10330 ;; record whether we're already sitting on one of the alternatives
10331 (setq pos (member cur-indent positions))
10332
10333 (cond
10334 ;; case 0: we're one one of the alternatives and this is the
10335 ;; first time they've pressed TAB on this line (best-guess).
10336 ((and js2-mode-indent-ignore-first-tab
10337 pos
10338 ;; first time pressing TAB on this line?
10339 (not (eq js2-mode-last-indented-line current-line)))
10340 ;; do nothing
10341 (setq computed-pos nil))
10342 ;; case 1: only one computed position => use it
10343 ((null (cdr positions))
10344 (setq computed-pos 0))
10345 ;; case 2: not on any of the computed spots => use main spot
10346 ((not pos)
10347 (setq computed-pos (js2-position main-pos positions)))
10348 ;; case 3: on last position: cycle to first position
10349 ((null (cdr pos))
10350 (setq computed-pos 0))
10351 ;; case 4: on intermediate position: cycle to next position
10352 (t
10353 (setq computed-pos (js2-position (second pos) positions))))
10354
10355 ;; see if any hooks want to indent; otherwise we do it
10356 (loop with result = nil
10357 for hook in js2-indent-hook
10358 while (null result)
10359 do
10360 (setq result (funcall hook positions computed-pos))
10361 finally do
10362 (unless (or result (null computed-pos))
10363 (indent-line-to (nth computed-pos positions)))))
10364
10365 ;; finally
10366 (if js2-mode-indent-inhibit-undo
10367 (setq buffer-undo-list old-buffer-undo-list))
10368 ;; see commentary for `js2-mode-last-indented-line'
10369 (setq js2-mode-last-indented-line current-line))))
10370
10371 (defun js2-indent-bounce-backwards ()
10372 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10373 cycles between the computed indentation positions in reverse order."
10374 (interactive)
10375 (js2-indent-line t))
10376
10377 (defsubst js2-1-line-comment-continuation-p ()
10378 "Return t if we're in a 1-line comment continuation.
10379 If so, we don't ever want to use bounce-indent."
10380 (save-excursion
10381 (save-match-data
10382 (and (progn
10383 (forward-line 0)
10384 (looking-at "\\s-*//"))
10385 (progn
10386 (forward-line -1)
10387 (forward-line 0)
10388 (when (looking-at "\\s-*$")
10389 (js2-backward-sws)
10390 (forward-line 0))
10391 (looking-at "\\s-*//"))))))
10392
10393 (defun js2-indent-line (&optional bounce-backwards)
10394 "Indent the current line as JavaScript source text."
10395 (interactive)
10396 (let (parse-status
10397 offset
10398 indent-col
10399 moved
10400 ;; don't whine about errors/warnings when we're indenting.
10401 ;; This has to be set before calling parse-partial-sexp below.
10402 (inhibit-point-motion-hooks t))
10403 (setq parse-status (save-excursion
10404 (syntax-ppss (point-at-bol)))
10405 offset (- (point) (save-excursion
10406 (back-to-indentation)
10407 (point))))
10408 (js2-with-underscore-as-word-syntax
10409 (if (nth 4 parse-status)
10410 (js2-lineup-comment parse-status)
10411 (setq indent-col (js2-proper-indentation parse-status))
10412 ;; see comments below about js2-mode-last-indented-line
10413 (cond
10414 ;; bounce-indenting is disabled during electric-key indent.
10415 ;; It doesn't work well on first line of buffer.
10416 ((and js2-bounce-indent-p
10417 (not (js2-same-line (point-min)))
10418 (not (js2-1-line-comment-continuation-p)))
10419 (js2-bounce-indent indent-col parse-status bounce-backwards))
10420 ;; just indent to the guesser's likely spot
10421 (t (indent-line-to indent-col))))
10422 (when (plusp offset)
10423 (forward-char offset)))))
10424
10425 (defun js2-indent-region (start end)
10426 "Indent the region, but don't use bounce indenting."
10427 (let ((js2-bounce-indent-p nil)
10428 (indent-region-function nil)
10429 (after-change-functions (remq 'js2-mode-edit
10430 after-change-functions)))
10431 (indent-region start end nil) ; nil for byte-compiler
10432 (js2-mode-edit start end (- end start))))
10433
10434 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10435
10436 ;;;###autoload
10437 (defun js2-mode ()
10438 "Major mode for editing JavaScript code.
10439
10440 \\{js2-mode-map}"
10441 (interactive)
10442 (kill-all-local-variables)
10443 (set-syntax-table js2-mode-syntax-table)
10444 (use-local-map js2-mode-map)
10445 (make-local-variable 'comment-start)
10446 (make-local-variable 'comment-end)
10447 (make-local-variable 'comment-start-skip)
10448 (setq major-mode 'js2-mode
10449 mode-name "JavaScript-IDE"
10450 comment-start "//" ; used by comment-region; don't change it
10451 comment-end "")
10452 (setq local-abbrev-table js2-mode-abbrev-table)
10453 (set (make-local-variable 'max-lisp-eval-depth)
10454 (max max-lisp-eval-depth 3000))
10455 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10456 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10457
10458 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10459 ;; on most platforms other than the one I originally wrote it on.
10460 ;; So it's back to `c-fill-paragraph'.
10461 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10462
10463 (add-hook 'before-save-hook #'js2-before-save nil t)
10464 (set (make-local-variable 'next-error-function) #'js2-next-error)
10465 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10466 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10467 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10468 ;; for characters inside regexp literals.
10469 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10470 ;; this is necessary to make `show-paren-function' work properly
10471 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10472 ;; needed for M-x rgrep, among other things
10473 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10474
10475 ;; some variables needed by cc-engine for paragraph-fill, etc.
10476 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10477 c-comment-start-regexp "/[*/]\\|\\s|"
10478 c-line-comment-starter "//"
10479 c-paragraph-start js2-paragraph-start
10480 c-paragraph-separate "$"
10481 comment-start-skip js2-comment-start-skip
10482 c-syntactic-ws-start js2-syntactic-ws-start
10483 c-syntactic-ws-end js2-syntactic-ws-end
10484 c-syntactic-eol js2-syntactic-eol)
10485
10486 (let ((c-buffer-is-cc-mode t))
10487 ;; Copied from `js-mode'. Also see Bug#6071.
10488 (make-local-variable 'paragraph-start)
10489 (make-local-variable 'paragraph-separate)
10490 (make-local-variable 'paragraph-ignore-fill-prefix)
10491 (make-local-variable 'adaptive-fill-mode)
10492 (make-local-variable 'adaptive-fill-regexp)
10493 (c-setup-paragraph-variables))
10494
10495 (setq js2-default-externs
10496 (append js2-ecma-262-externs
10497 (if js2-include-browser-externs
10498 js2-browser-externs)
10499 (if js2-include-gears-externs
10500 js2-gears-externs)
10501 (if js2-include-rhino-externs
10502 js2-rhino-externs)))
10503
10504 ;; We do our own syntax highlighting based on the parse tree.
10505 ;; However, we want minor modes that add keywords to highlight properly
10506 ;; (examples: doxymacs, column-marker).
10507 ;; To customize highlighted keywords, use `font-lock-add-keywords'.
10508 (setq font-lock-defaults '(nil t))
10509
10510 ;; Experiment: make reparse-delay longer for longer files.
10511 (if (plusp js2-dynamic-idle-timer-adjust)
10512 (setq js2-idle-timer-delay
10513 (* js2-idle-timer-delay
10514 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10515
10516 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10517 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10518 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10519 (imenu-add-to-menubar (concat "IM-" mode-name))
10520 (when js2-mirror-mode
10521 (js2-enter-mirror-mode))
10522 (add-to-invisibility-spec '(js2-outline . t))
10523 (set (make-local-variable 'line-move-ignore-invisible) t)
10524 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10525
10526 (if (fboundp 'run-mode-hooks)
10527 (run-mode-hooks 'js2-mode-hook)
10528 (run-hooks 'js2-mode-hook))
10529
10530 (setq js2-mode-functions-hidden nil
10531 js2-mode-comments-hidden nil
10532 js2-mode-buffer-dirty-p t
10533 js2-mode-parsing nil)
10534 (js2-reparse))
10535
10536 (defun js2-mode-exit ()
10537 "Exit `js2-mode' and clean up."
10538 (interactive)
10539 (when js2-mode-node-overlay
10540 (delete-overlay js2-mode-node-overlay)
10541 (setq js2-mode-node-overlay nil))
10542 (js2-remove-overlays)
10543 (setq js2-mode-ast nil)
10544 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10545 (remove-from-invisibility-spec '(js2-outline . t))
10546 (js2-mode-show-all)
10547 (js2-with-unmodifying-text-property-changes
10548 (js2-clear-face (point-min) (point-max))))
10549
10550 (defun js2-before-save ()
10551 "Clean up whitespace before saving file.
10552 You can disable this by customizing `js2-cleanup-whitespace'."
10553 (when js2-cleanup-whitespace
10554 (let ((col (current-column)))
10555 (delete-trailing-whitespace)
10556 ;; don't change trailing whitespace on current line
10557 (unless (eq (current-column) col)
10558 (indent-to col)))))
10559
10560 (defsubst js2-mode-reset-timer ()
10561 "Cancel any existing parse timer and schedule a new one."
10562 (if js2-mode-parse-timer
10563 (cancel-timer js2-mode-parse-timer))
10564 (setq js2-mode-parsing nil)
10565 (let ((timer (timer-create)))
10566 (setq js2-mode-parse-timer timer)
10567 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10568 (timer-set-idle-time timer js2-idle-timer-delay)
10569 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10570 (timer-activate-when-idle timer nil)))
10571
10572 (defun js2-mode-idle-reparse (buffer)
10573 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10574 it to be reparsed when the buffer is selected."
10575 (if (eq buffer (current-buffer))
10576 (js2-reparse)
10577 ;; reparse when the buffer is selected again
10578 (with-current-buffer buffer
10579 (add-hook 'window-configuration-change-hook
10580 #'js2-mode-idle-reparse-inner
10581 nil t))))
10582
10583 (defun js2-mode-idle-reparse-inner ()
10584 (remove-hook 'window-configuration-change-hook
10585 #'js2-mode-idle-reparse-inner
10586 t)
10587 (js2-reparse))
10588
10589 (defun js2-mode-edit (beg end len)
10590 "Schedule a new parse after buffer is edited.
10591 Buffer edit spans from BEG to END and is of length LEN.
10592 Also clears the `js2-magic' bit on autoinserted parens/brackets
10593 if the edit occurred on a line different from the magic paren."
10594 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10595 (line (if magic-pos (line-number-at-pos magic-pos))))
10596 (and line
10597 (or (/= (line-number-at-pos beg) line)
10598 (and (> 0 len)
10599 (/= (line-number-at-pos end) line)))
10600 (js2-mode-mundanify-parens)))
10601 (setq js2-mode-buffer-dirty-p t)
10602 (js2-mode-hide-overlay)
10603 (js2-mode-reset-timer))
10604
10605 (defun js2-reparse (&optional force)
10606 "Re-parse current buffer after user finishes some data entry.
10607 If we get any user input while parsing, including cursor motion,
10608 we discard the parse and reschedule it. If FORCE is nil, then the
10609 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10610 (let (time
10611 interrupted-p
10612 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10613 (unless js2-mode-parsing
10614 (setq js2-mode-parsing t)
10615 (unwind-protect
10616 (when (or js2-mode-buffer-dirty-p force)
10617 (js2-remove-overlays)
10618 (js2-with-unmodifying-text-property-changes
10619 (setq js2-mode-buffer-dirty-p nil
10620 js2-mode-fontifications nil
10621 js2-mode-deferred-properties nil)
10622 (if js2-mode-verbose-parse-p
10623 (message "parsing..."))
10624 (setq time
10625 (js2-time
10626 (setq interrupted-p
10627 (catch 'interrupted
10628 (js2-parse)
10629 ;; if parsing is interrupted, comments and regex
10630 ;; literals stay ignored by `parse-partial-sexp'
10631 (remove-text-properties (point-min) (point-max)
10632 '(syntax-table))
10633 (js2-mode-apply-deferred-properties)
10634 (js2-mode-remove-suppressed-warnings)
10635 (js2-mode-show-warnings)
10636 (js2-mode-show-errors)
10637 (js2-mode-highlight-magic-parens)
10638 (if (>= js2-highlight-level 1)
10639 (js2-highlight-jsdoc js2-mode-ast))
10640 nil))))
10641 (if interrupted-p
10642 (progn
10643 ;; unfinished parse => try again
10644 (setq js2-mode-buffer-dirty-p t)
10645 (js2-mode-reset-timer))
10646 (if js2-mode-verbose-parse-p
10647 (message "Parse time: %s" time)))))
10648 (setq js2-mode-parsing nil)
10649 (unless interrupted-p
10650 (setq js2-mode-parse-timer nil))))))
10651
10652 (defun js2-mode-show-node (event)
10653 "Debugging aid: highlight selected AST node on mouse click."
10654 (interactive "e")
10655 (mouse-set-point event)
10656 (setq deactivate-mark t)
10657 (when js2-mode-show-overlay
10658 (let ((node (js2-node-at-point))
10659 beg end)
10660 (if (null node)
10661 (message "No node found at location %s" (point))
10662 (setq beg (js2-node-abs-pos node)
10663 end (+ beg (js2-node-len node)))
10664 (if js2-mode-node-overlay
10665 (move-overlay js2-mode-node-overlay beg end)
10666 (setq js2-mode-node-overlay (make-overlay beg end))
10667 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10668 (js2-with-unmodifying-text-property-changes
10669 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10670 (message "%s, parent: %s"
10671 (js2-node-short-name node)
10672 (if (js2-node-parent node)
10673 (js2-node-short-name (js2-node-parent node))
10674 "nil"))))))
10675
10676 (defun js2-mode-hide-overlay (&optional p1 p2)
10677 "Remove the debugging overlay when the point moves.
10678 P1 and P2 are the old and new values of point, respectively."
10679 (when js2-mode-node-overlay
10680 (let ((beg (overlay-start js2-mode-node-overlay))
10681 (end (overlay-end js2-mode-node-overlay)))
10682 ;; Sometimes we're called spuriously.
10683 (unless (and p2
10684 (>= p2 beg)
10685 (<= p2 end))
10686 (js2-with-unmodifying-text-property-changes
10687 (remove-text-properties beg end '(point-left nil)))
10688 (delete-overlay js2-mode-node-overlay)
10689 (setq js2-mode-node-overlay nil)))))
10690
10691 (defun js2-mode-reset ()
10692 "Debugging helper: reset everything."
10693 (interactive)
10694 (js2-mode-exit)
10695 (js2-mode))
10696
10697 (defsubst js2-mode-show-warn-or-err (e face)
10698 "Highlight a warning or error E with FACE.
10699 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10700 (let* ((key (first e))
10701 (beg (second e))
10702 (end (+ beg (third e)))
10703 ;; Don't inadvertently go out of bounds.
10704 (beg (max (point-min) (min beg (point-max))))
10705 (end (max (point-min) (min end (point-max))))
10706 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10707 (ovl (make-overlay beg end)))
10708 (overlay-put ovl 'font-lock-face face)
10709 (overlay-put ovl 'js2-error t)
10710 (put-text-property beg end 'help-echo (js2-get-msg key))
10711 (put-text-property beg end 'point-entered #'js2-echo-error)))
10712
10713 (defun js2-remove-overlays ()
10714 "Remove overlays from buffer that have a `js2-error' property."
10715 (let ((beg (point-min))
10716 (end (point-max)))
10717 (save-excursion
10718 (dolist (o (overlays-in beg end))
10719 (when (overlay-get o 'js2-error)
10720 (delete-overlay o))))))
10721
10722 (defun js2-error-at-point (&optional pos)
10723 "Return non-nil if there's an error overlay at POS.
10724 Defaults to point."
10725 (loop with pos = (or pos (point))
10726 for o in (overlays-at pos)
10727 thereis (overlay-get o 'js2-error)))
10728
10729 (defun js2-mode-apply-deferred-properties ()
10730 "Apply fontifications and other text properties recorded during parsing."
10731 (when (plusp js2-highlight-level)
10732 ;; We defer clearing faces as long as possible to eliminate flashing.
10733 (js2-clear-face (point-min) (point-max))
10734 ;; Have to reverse the recorded fontifications list so that errors
10735 ;; and warnings overwrite the normal fontifications.
10736 (dolist (f (nreverse js2-mode-fontifications))
10737 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10738 (setq js2-mode-fontifications nil))
10739 (dolist (p js2-mode-deferred-properties)
10740 (apply #'put-text-property p))
10741 (setq js2-mode-deferred-properties nil))
10742
10743 (defun js2-mode-show-errors ()
10744 "Highlight syntax errors."
10745 (when js2-mode-show-parse-errors
10746 (dolist (e (js2-ast-root-errors js2-mode-ast))
10747 (js2-mode-show-warn-or-err e 'js2-error-face))))
10748
10749 (defun js2-mode-remove-suppressed-warnings ()
10750 "Take suppressed warnings out of the AST warnings list.
10751 This ensures that the counts and `next-error' are correct."
10752 (setf (js2-ast-root-warnings js2-mode-ast)
10753 (js2-delete-if
10754 (lambda (e)
10755 (let ((key (caar e)))
10756 (or
10757 (and (not js2-strict-trailing-comma-warning)
10758 (string-match "trailing\\.comma" key))
10759 (and (not js2-strict-cond-assign-warning)
10760 (string= key "msg.equal.as.assign"))
10761 (and js2-missing-semi-one-line-override
10762 (string= key "msg.missing.semi")
10763 (let* ((beg (second e))
10764 (node (js2-node-at-point beg))
10765 (fn (js2-mode-find-parent-fn node))
10766 (body (and fn (js2-function-node-body fn)))
10767 (lc (and body (js2-node-abs-pos body)))
10768 (rc (and lc (+ lc (js2-node-len body)))))
10769 (and fn
10770 (or (null body)
10771 (save-excursion
10772 (goto-char beg)
10773 (and (js2-same-line lc)
10774 (js2-same-line rc))))))))))
10775 (js2-ast-root-warnings js2-mode-ast))))
10776
10777 (defun js2-mode-show-warnings ()
10778 "Highlight strict-mode warnings."
10779 (when js2-mode-show-strict-warnings
10780 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10781 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10782
10783 (defun js2-echo-error (old-point new-point)
10784 "Called by point-motion hooks."
10785 (let ((msg (get-text-property new-point 'help-echo)))
10786 (if (and msg (or (not (current-message))
10787 (string= (current-message) "Quit")))
10788 (message msg))))
10789
10790 (defalias #'js2-echo-help #'js2-echo-error)
10791
10792 (defun js2-enter-key ()
10793 "Handle user pressing the Enter key."
10794 (interactive)
10795 (let ((parse-status (save-excursion
10796 (syntax-ppss (point))))
10797 (js2-bounce-indent-p nil))
10798 (cond
10799 ;; check if we're inside a string
10800 ((nth 3 parse-status)
10801 (if js2-concat-multiline-strings
10802 (js2-mode-split-string parse-status)
10803 (insert "\n")))
10804 ;; check if inside a block comment
10805 ((nth 4 parse-status)
10806 (js2-mode-extend-comment))
10807 (t
10808 ;; should probably figure out what the mode-map says we should do
10809 (if js2-indent-on-enter-key
10810 (js2-indent-line))
10811 (insert "\n")
10812 (if js2-enter-indents-newline
10813 (js2-indent-line))))))
10814
10815 (defun js2-mode-split-string (parse-status)
10816 "Turn a newline in mid-string into a string concatenation.
10817 PARSE-STATUS is as documented in `parse-partial-sexp'."
10818 (let* ((col (current-column))
10819 (quote-char (nth 3 parse-status))
10820 (quote-string (string quote-char))
10821 (string-beg (nth 8 parse-status))
10822 (at-eol (eq js2-concat-multiline-strings 'eol))
10823 (indent (save-match-data
10824 (or
10825 (save-excursion
10826 (back-to-indentation)
10827 (if (looking-at "\\+")
10828 (current-column)))
10829 (save-excursion
10830 (goto-char string-beg)
10831 (if (looking-back "\\+\\s-+")
10832 (goto-char (match-beginning 0)))
10833 (current-column))))))
10834 (insert quote-char)
10835 (if at-eol
10836 (insert " +\n")
10837 (insert "\n"))
10838 ;; FIXME: This does not match the behavior of `js2-indent-line'.
10839 (indent-to indent)
10840 (unless at-eol
10841 (insert "+ "))
10842 (insert quote-string)
10843 (when (eolp)
10844 (insert quote-string)
10845 (backward-char 1))))
10846
10847 (defun js2-mode-extend-comment ()
10848 "Indent the line and, when inside a comment block, add comment prefix."
10849 (let (star single col first-line needs-close)
10850 (save-excursion
10851 (back-to-indentation)
10852 (cond
10853 ((looking-at "\\*[^/]")
10854 (setq star t
10855 col (current-column)))
10856 ((looking-at "/\\*")
10857 (setq star t
10858 first-line t
10859 col (1+ (current-column))))
10860 ((looking-at "//")
10861 (setq single t
10862 col (current-column)))))
10863 ;; Heuristic for whether we need to close the comment:
10864 ;; if we've got a parse error here, assume it's an unterminated
10865 ;; comment.
10866 (setq needs-close
10867 (or
10868 (eq (get-text-property (1- (point)) 'point-entered)
10869 'js2-echo-error)
10870 ;; The heuristic above doesn't work well when we're
10871 ;; creating a comment and there's another one downstream,
10872 ;; as our parser thinks this one ends at the end of the
10873 ;; next one. (You can have a /* inside a js block comment.)
10874 ;; So just close it if the next non-ws char isn't a *.
10875 (and first-line
10876 (eolp)
10877 (save-excursion
10878 (skip-chars-forward " \t\r\n")
10879 (not (eq (char-after) ?*))))))
10880 (insert "\n")
10881 (cond
10882 (star
10883 (indent-to col)
10884 (insert "* ")
10885 (if (and first-line needs-close)
10886 (save-excursion
10887 (insert "\n")
10888 (indent-to col)
10889 (insert "*/"))))
10890 ((and single
10891 (save-excursion
10892 (and (zerop (forward-line 1))
10893 (looking-at "\\s-*//"))))
10894 (indent-to col)
10895 (insert "// "))
10896 ;; don't need to extend the comment after all
10897 (js2-enter-indents-newline
10898 (js2-indent-line)))))
10899
10900 (defun js2-beginning-of-line ()
10901 "Toggles point between bol and first non-whitespace char in line.
10902 Also moves past comment delimiters when inside comments."
10903 (interactive)
10904 (let (node beg)
10905 (cond
10906 ((bolp)
10907 (back-to-indentation))
10908 ((looking-at "//")
10909 (skip-chars-forward "/ \t"))
10910 ((and (eq (char-after) ?*)
10911 (setq node (js2-comment-at-point))
10912 (memq (js2-comment-node-format node) '(jsdoc block))
10913 (save-excursion
10914 (skip-chars-backward " \t")
10915 (bolp)))
10916 (skip-chars-forward "\* \t"))
10917 (t
10918 (goto-char (point-at-bol))))))
10919
10920 (defun js2-end-of-line ()
10921 "Toggles point between eol and last non-whitespace char in line."
10922 (interactive)
10923 (if (eolp)
10924 (skip-chars-backward " \t")
10925 (goto-char (point-at-eol))))
10926
10927 (defun js2-enter-mirror-mode()
10928 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10929 on insertion."
10930 (interactive)
10931 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10932 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10933 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10934 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10935 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10936 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10937 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10938 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10939
10940 (defun js2-leave-mirror-mode()
10941 "Turns off mirror mode."
10942 (interactive)
10943 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10944 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10945
10946 (defsubst js2-mode-inside-string ()
10947 "Return non-nil if inside a string.
10948 Actually returns the quote character that begins the string."
10949 (let ((parse-state (save-excursion
10950 (syntax-ppss (point)))))
10951 (nth 3 parse-state)))
10952
10953 (defsubst js2-mode-inside-comment-or-string ()
10954 "Return non-nil if inside a comment or string."
10955 (or
10956 (let ((comment-start
10957 (save-excursion
10958 (goto-char (point-at-bol))
10959 (if (re-search-forward "//" (point-at-eol) t)
10960 (match-beginning 0)))))
10961 (and comment-start
10962 (<= comment-start (point))))
10963 (let ((parse-state (save-excursion
10964 (syntax-ppss (point)))))
10965 (or (nth 3 parse-state)
10966 (nth 4 parse-state)))))
10967
10968 (defsubst js2-make-magic-delimiter (delim &optional pos)
10969 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10970 Sets value of `js2-magic' text property to line number at POS."
10971 (propertize delim
10972 'js2-magic (line-number-at-pos pos)
10973 'font-lock-face 'js2-magic-paren-face))
10974
10975 (defun js2-mode-match-delimiter (open close)
10976 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10977 The rule we use, which as far as we can tell is how Eclipse works,
10978 is that we insert the match if we're not in a comment or string,
10979 and the next non-whitespace character is either punctuation or
10980 occurs on another line."
10981 (insert open)
10982 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10983 (not (js2-mode-inside-comment-or-string)))
10984 (save-excursion
10985 (insert (js2-make-magic-delimiter close)))
10986 (when js2-auto-indent-p
10987 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10988 (js2-indent-line)))))
10989
10990 (defun js2-mode-match-bracket ()
10991 "Insert matching bracket."
10992 (interactive)
10993 (js2-mode-match-delimiter "[" "]"))
10994
10995 (defun js2-mode-match-paren ()
10996 "Insert matching paren unless already inserted."
10997 (interactive)
10998 (js2-mode-match-delimiter "(" ")"))
10999
11000 (defun js2-mode-match-curly (arg)
11001 "Insert matching curly-brace.
11002 With prefix arg, no formatting or indentation will occur -- the close-brace
11003 is simply inserted directly at the point."
11004 (interactive "p")
11005 (let (try-pos)
11006 (cond
11007 (current-prefix-arg
11008 (js2-mode-match-delimiter "{" "}"))
11009 ((and js2-auto-insert-catch-block
11010 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
11011 (point-at-bol))
11012 (match-beginning 1))))
11013 (js2-insert-catch-skel try-pos))
11014 (t
11015 ;; Otherwise try to do something smarter.
11016 (insert "{")
11017 (unless (or (not (looking-at "\\s-*$"))
11018 (save-excursion
11019 (skip-chars-forward " \t\r\n")
11020 (and (looking-at "}")
11021 (js2-error-at-point)))
11022 (js2-mode-inside-comment-or-string))
11023 (undo-boundary)
11024 ;; absolutely mystifying bug: when inserting the next "\n",
11025 ;; the buffer-undo-list is given two new entries: the inserted range,
11026 ;; and the incorrect position of the point. It's recorded incorrectly
11027 ;; as being before the opening "{", not after it. But it's recorded
11028 ;; as the correct value if you're debugging `js2-mode-match-curly'
11029 ;; in edebug. I have no idea why it's doing this, but incrementing
11030 ;; the inserted position fixes the problem, so that the undo takes us
11031 ;; back to just after the user-inserted "{".
11032 (insert "\n")
11033 (ignore-errors
11034 (incf (cadr buffer-undo-list)))
11035 (js2-indent-line)
11036 (save-excursion
11037 (insert "\n}")
11038 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
11039 (js2-indent-line))))))))
11040
11041 (defun js2-insert-catch-skel (try-pos)
11042 "Complete a try/catch block after inserting a { following a try keyword.
11043 Rationale is that a try always needs a catch or a finally, and the catch is
11044 the more likely of the two.
11045
11046 TRY-POS is the buffer position of the try keyword. The open-curly should
11047 already have been inserted."
11048 (insert "{")
11049 (let ((try-col (save-excursion
11050 (goto-char try-pos)
11051 (current-column))))
11052 (insert "\n")
11053 (undo-boundary)
11054 (js2-indent-line) ;; indent the blank line where cursor will end up
11055 (save-excursion
11056 (insert "\n")
11057 (indent-to try-col)
11058 (insert "} catch (x) {\n\n")
11059 (indent-to try-col)
11060 (insert "}"))))
11061
11062 (defun js2-mode-highlight-magic-parens ()
11063 "Re-highlight magic parens after parsing nukes the 'face prop."
11064 (let ((beg (point-min))
11065 end)
11066 (while (setq beg (next-single-property-change beg 'js2-magic))
11067 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11068 (if (get-text-property beg 'js2-magic)
11069 (js2-with-unmodifying-text-property-changes
11070 (put-text-property beg (or end (1+ beg))
11071 'font-lock-face 'js2-magic-paren-face))))))
11072
11073 (defun js2-mode-mundanify-parens ()
11074 "Clear all magic parens and brackets."
11075 (let ((beg (point-min))
11076 end)
11077 (while (setq beg (next-single-property-change beg 'js2-magic))
11078 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11079 (remove-text-properties beg (or end (1+ beg))
11080 '(js2-magic face)))))
11081
11082 (defsubst js2-match-quote (quote-string)
11083 (let ((start-quote (js2-mode-inside-string)))
11084 (cond
11085 ;; inside a comment - don't do quote-matching, since we can't
11086 ;; reliably figure out if we're in a string inside the comment
11087 ((js2-comment-at-point)
11088 (insert quote-string))
11089 ((not start-quote)
11090 ;; not in string => insert matched quotes
11091 (insert quote-string)
11092 ;; exception: if we're just before a word, don't double it.
11093 (unless (looking-at "[^ \t\r\n]")
11094 (save-excursion
11095 (insert quote-string))))
11096 ((looking-at quote-string)
11097 (if (looking-back "[^\\]\\\\")
11098 (insert quote-string)
11099 (forward-char 1)))
11100 ((and js2-mode-escape-quotes
11101 (save-excursion
11102 (save-match-data
11103 (re-search-forward quote-string (point-at-eol) t))))
11104 ;; inside terminated string, escape quote (unless already escaped)
11105 (insert (if (looking-back "[^\\]\\\\")
11106 quote-string
11107 (concat "\\" quote-string))))
11108 (t
11109 (insert quote-string))))) ; else terminate the string
11110
11111 (defun js2-mode-match-single-quote ()
11112 "Insert matching single-quote."
11113 (interactive)
11114 (let ((parse-status (syntax-ppss (point))))
11115 ;; don't match inside comments, since apostrophe is more common
11116 (if (nth 4 parse-status)
11117 (insert "'")
11118 (js2-match-quote "'"))))
11119
11120 (defun js2-mode-match-double-quote ()
11121 "Insert matching double-quote."
11122 (interactive)
11123 (js2-match-quote "\""))
11124
11125 ;; Eclipse works as follows:
11126 ;; * type an open-paren and it auto-inserts close-paren
11127 ;; - auto-inserted paren gets a green bracket
11128 ;; - green bracket means typing close-paren there will skip it
11129 ;; * if you insert any text on a different line, it turns off
11130 (defun js2-mode-magic-close-paren ()
11131 "Skip over close-paren rather than inserting, where appropriate."
11132 (interactive)
11133 (let* ((here (point))
11134 (parse-status (syntax-ppss here))
11135 (open-pos (nth 1 parse-status))
11136 (close last-input-event)
11137 (open (cond
11138 ((eq close ?\))
11139 ?\()
11140 ((eq close ?\])
11141 ?\[)
11142 ((eq close ?})
11143 ?{)
11144 (t nil))))
11145 (if (and (eq (char-after) close)
11146 (eq open (char-after open-pos))
11147 (js2-same-line open-pos)
11148 (get-text-property here 'js2-magic))
11149 (progn
11150 (remove-text-properties here (1+ here) '(js2-magic face))
11151 (forward-char 1))
11152 (insert-char close 1))
11153 (blink-matching-open)))
11154
11155 (defun js2-mode-wait-for-parse (callback)
11156 "Invoke CALLBACK when parsing is finished.
11157 If parsing is already finished, calls CALLBACK immediately."
11158 (if (not js2-mode-buffer-dirty-p)
11159 (funcall callback)
11160 (push callback js2-mode-pending-parse-callbacks)
11161 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11162
11163 (defun js2-mode-parse-finished ()
11164 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11165 ;; We can't let errors propagate up, since it prevents the
11166 ;; `js2-parse' method from completing normally and returning
11167 ;; the ast, which makes things mysteriously not work right.
11168 (unwind-protect
11169 (dolist (cb js2-mode-pending-parse-callbacks)
11170 (condition-case err
11171 (funcall cb)
11172 (error (message "%s" err))))
11173 (setq js2-mode-pending-parse-callbacks nil)))
11174
11175 (defun js2-mode-flag-region (from to flag)
11176 "Hide or show text from FROM to TO, according to FLAG.
11177 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11178 Returns the created overlay if FLAG is non-nil."
11179 (remove-overlays from to 'invisible 'js2-outline)
11180 (when flag
11181 (let ((o (make-overlay from to)))
11182 (overlay-put o 'invisible 'js2-outline)
11183 (overlay-put o 'isearch-open-invisible
11184 'js2-isearch-open-invisible)
11185 o)))
11186
11187 ;; Function to be set as an outline-isearch-open-invisible' property
11188 ;; to the overlay that makes the outline invisible (see
11189 ;; `js2-mode-flag-region').
11190 (defun js2-isearch-open-invisible (overlay)
11191 ;; We rely on the fact that isearch places point on the matched text.
11192 (js2-mode-show-element))
11193
11194 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11195 "Return cons cell of bounds of folding overlay at POS.
11196 Returns nil if not found."
11197 (let ((overlays (overlays-at (or pos (point))))
11198 o)
11199 (while (and overlays
11200 (not o))
11201 (if (overlay-get (car overlays) 'invisible)
11202 (setq o (car overlays))
11203 (setq overlays (cdr overlays))))
11204 (if o
11205 (cons (overlay-start o) (overlay-end o)))))
11206
11207 (defun js2-mode-function-at-point (&optional pos)
11208 "Return the innermost function node enclosing current point.
11209 Returns nil if point is not in a function."
11210 (let ((node (js2-node-at-point pos)))
11211 (while (and node (not (js2-function-node-p node)))
11212 (setq node (js2-node-parent node)))
11213 (if (js2-function-node-p node)
11214 node)))
11215
11216 (defun js2-mode-toggle-element ()
11217 "Hide or show the foldable element at the point."
11218 (interactive)
11219 (let (comment fn pos)
11220 (save-excursion
11221 (save-match-data
11222 (cond
11223 ;; /* ... */ comment?
11224 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11225 (if (js2-mode-invisible-overlay-bounds
11226 (setq pos (+ 3 (js2-node-abs-pos comment))))
11227 (progn
11228 (goto-char pos)
11229 (js2-mode-show-element))
11230 (js2-mode-hide-element)))
11231 ;; //-comment?
11232 ((save-excursion
11233 (back-to-indentation)
11234 (looking-at js2-mode-//-comment-re))
11235 (js2-mode-toggle-//-comment))
11236 ;; function?
11237 ((setq fn (js2-mode-function-at-point))
11238 (setq pos (and (js2-function-node-body fn)
11239 (js2-node-abs-pos (js2-function-node-body fn))))
11240 (goto-char (1+ pos))
11241 (if (js2-mode-invisible-overlay-bounds)
11242 (js2-mode-show-element)
11243 (js2-mode-hide-element)))
11244 (t
11245 (message "Nothing at point to hide or show")))))))
11246
11247 (defun js2-mode-hide-element ()
11248 "Fold/hide contents of a block, showing ellipses.
11249 Show the hidden text with \\[js2-mode-show-element]."
11250 (interactive)
11251 (if js2-mode-buffer-dirty-p
11252 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11253 (let (node body beg end)
11254 (cond
11255 ((js2-mode-invisible-overlay-bounds)
11256 (message "already hidden"))
11257 (t
11258 (setq node (js2-node-at-point))
11259 (cond
11260 ((js2-block-comment-p node)
11261 (js2-mode-hide-comment node))
11262 (t
11263 (while (and node (not (js2-function-node-p node)))
11264 (setq node (js2-node-parent node)))
11265 (if (and node
11266 (setq body (js2-function-node-body node)))
11267 (progn
11268 (setq beg (js2-node-abs-pos body)
11269 end (+ beg (js2-node-len body)))
11270 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11271 (message "No collapsable element found at point"))))))))
11272
11273 (defun js2-mode-show-element ()
11274 "Show the hidden element at current point."
11275 (interactive)
11276 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11277 (if bounds
11278 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11279 (message "Nothing to un-hide"))))
11280
11281 (defun js2-mode-show-all ()
11282 "Show all of the text in the buffer."
11283 (interactive)
11284 (js2-mode-flag-region (point-min) (point-max) nil))
11285
11286 (defun js2-mode-toggle-hide-functions ()
11287 (interactive)
11288 (if js2-mode-functions-hidden
11289 (js2-mode-show-functions)
11290 (js2-mode-hide-functions)))
11291
11292 (defun js2-mode-hide-functions ()
11293 "Hides all non-nested function bodies in the buffer.
11294 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11295 to open an individual entry."
11296 (interactive)
11297 (if js2-mode-buffer-dirty-p
11298 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11299 (if (null js2-mode-ast)
11300 (message "Oops - parsing failed")
11301 (setq js2-mode-functions-hidden t)
11302 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11303
11304 (defun js2-mode-function-hider (n endp)
11305 (when (not endp)
11306 (let ((tt (js2-node-type n))
11307 body beg end)
11308 (cond
11309 ((and (= tt js2-FUNCTION)
11310 (setq body (js2-function-node-body n)))
11311 (setq beg (js2-node-abs-pos body)
11312 end (+ beg (js2-node-len body)))
11313 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11314 nil) ; don't process children of function
11315 (t
11316 t))))) ; keep processing other AST nodes
11317
11318 (defun js2-mode-show-functions ()
11319 "Un-hide any folded function bodies in the buffer."
11320 (interactive)
11321 (setq js2-mode-functions-hidden nil)
11322 (save-excursion
11323 (goto-char (point-min))
11324 (while (/= (goto-char (next-overlay-change (point)))
11325 (point-max))
11326 (dolist (o (overlays-at (point)))
11327 (when (and (overlay-get o 'invisible)
11328 (not (overlay-get o 'comment)))
11329 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11330
11331 (defun js2-mode-hide-comment (n)
11332 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11333 3 ; /**
11334 2)) ; /*
11335 (beg (+ (js2-node-abs-pos n) head))
11336 (end (- (+ beg (js2-node-len n)) head 2))
11337 (o (js2-mode-flag-region beg end 'hide)))
11338 (overlay-put o 'comment t)))
11339
11340 (defun js2-mode-toggle-hide-comments ()
11341 "Folds all block comments in the buffer.
11342 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11343 to open an individual entry."
11344 (interactive)
11345 (if js2-mode-comments-hidden
11346 (js2-mode-show-comments)
11347 (js2-mode-hide-comments)))
11348
11349 (defun js2-mode-hide-comments ()
11350 (interactive)
11351 (if js2-mode-buffer-dirty-p
11352 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11353 (if (null js2-mode-ast)
11354 (message "Oops - parsing failed")
11355 (setq js2-mode-comments-hidden t)
11356 (dolist (n (js2-ast-root-comments js2-mode-ast))
11357 (let ((format (js2-comment-node-format n)))
11358 (when (js2-block-comment-p n)
11359 (js2-mode-hide-comment n))))
11360 (js2-mode-hide-//-comments)))
11361
11362 (defsubst js2-mode-extend-//-comment (direction)
11363 "Find start or end of a block of similar //-comment lines.
11364 DIRECTION is -1 to look back, 1 to look forward.
11365 INDENT is the indentation level to match.
11366 Returns the end-of-line position of the furthest adjacent
11367 //-comment line with the same indentation as the current line.
11368 If there is no such matching line, returns current end of line."
11369 (let ((pos (point-at-eol))
11370 (indent (current-indentation)))
11371 (save-excursion
11372 (save-match-data
11373 (while (and (zerop (forward-line direction))
11374 (looking-at js2-mode-//-comment-re)
11375 (eq indent (length (match-string 1))))
11376 (setq pos (point-at-eol)))
11377 pos))))
11378
11379 (defun js2-mode-hide-//-comments ()
11380 "Fold adjacent 1-line comments, showing only snippet of first one."
11381 (let (beg end)
11382 (save-excursion
11383 (save-match-data
11384 (goto-char (point-min))
11385 (while (re-search-forward js2-mode-//-comment-re nil t)
11386 (setq beg (point)
11387 end (js2-mode-extend-//-comment 1))
11388 (unless (eq beg end)
11389 (overlay-put (js2-mode-flag-region beg end 'hide)
11390 'comment t))
11391 (goto-char end)
11392 (forward-char 1))))))
11393
11394 (defun js2-mode-toggle-//-comment ()
11395 "Fold or un-fold any multi-line //-comment at point.
11396 Caller should have determined that this line starts with a //-comment."
11397 (let* ((beg (point-at-eol))
11398 (end beg))
11399 (save-excursion
11400 (goto-char end)
11401 (if (js2-mode-invisible-overlay-bounds)
11402 (js2-mode-show-element)
11403 ;; else hide the comment
11404 (setq beg (js2-mode-extend-//-comment -1)
11405 end (js2-mode-extend-//-comment 1))
11406 (unless (eq beg end)
11407 (overlay-put (js2-mode-flag-region beg end 'hide)
11408 'comment t))))))
11409
11410 (defun js2-mode-show-comments ()
11411 "Un-hide any hidden comments, leaving other hidden elements alone."
11412 (interactive)
11413 (setq js2-mode-comments-hidden nil)
11414 (save-excursion
11415 (goto-char (point-min))
11416 (while (/= (goto-char (next-overlay-change (point)))
11417 (point-max))
11418 (dolist (o (overlays-at (point)))
11419 (when (overlay-get o 'comment)
11420 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11421
11422 (defun js2-mode-display-warnings-and-errors ()
11423 "Turn on display of warnings and errors."
11424 (interactive)
11425 (setq js2-mode-show-parse-errors t
11426 js2-mode-show-strict-warnings t)
11427 (js2-reparse 'force))
11428
11429 (defun js2-mode-hide-warnings-and-errors ()
11430 "Turn off display of warnings and errors."
11431 (interactive)
11432 (setq js2-mode-show-parse-errors nil
11433 js2-mode-show-strict-warnings nil)
11434 (js2-reparse 'force))
11435
11436 (defun js2-mode-toggle-warnings-and-errors ()
11437 "Toggle the display of warnings and errors.
11438 Some users don't like having warnings/errors reported while they type."
11439 (interactive)
11440 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11441 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11442 (if (interactive-p)
11443 (message "warnings and errors %s"
11444 (if js2-mode-show-parse-errors
11445 "enabled"
11446 "disabled")))
11447 (js2-reparse 'force))
11448
11449 (defun js2-mode-customize ()
11450 (interactive)
11451 (customize-group 'js2-mode))
11452
11453 (defun js2-mode-forward-sexp (&optional arg)
11454 "Move forward across one statement or balanced expression.
11455 With ARG, do it that many times. Negative arg -N means
11456 move backward across N balanced expressions."
11457 (interactive "p")
11458 (setq arg (or arg 1))
11459 (save-restriction
11460 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11461 (js2-reparse))
11462 (let ((scan-msg "Containing expression ends prematurely")
11463 node (start (point)) pos lp rp child)
11464 (cond
11465 ;; backward-sexp
11466 ;; could probably make this better for some cases:
11467 ;; - if in statement block (e.g. function body), go to parent
11468 ;; - infix exprs like (foo in bar) - maybe go to beginning
11469 ;; of infix expr if in the right-side expression?
11470 ((and arg (minusp arg))
11471 (dotimes (i (- arg))
11472 (js2-backward-sws)
11473 (forward-char -1) ; enter the node we backed up to
11474 (when (setq node (js2-node-at-point (point) t))
11475 (setq pos (js2-node-abs-pos node))
11476 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11477 (setq lp (car parens)
11478 rp (cdr parens))))
11479 (goto-char
11480 (or (when (and lp (> start lp))
11481 (if (and rp (<= start rp))
11482 (if (setq child (js2-node-closest-child node (point) lp t))
11483 (js2-node-abs-pos child)
11484 (goto-char start)
11485 (signal 'scan-error (list scan-msg lp lp)))
11486 lp))
11487 pos
11488 (point-min)))))
11489 (t
11490 ;; forward-sexp
11491 (js2-forward-sws)
11492 (dotimes (i arg)
11493 (js2-forward-sws)
11494 (when (setq node (js2-node-at-point (point) t))
11495 (setq pos (js2-node-abs-pos node))
11496 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11497 (setq lp (car parens)
11498 rp (cdr parens))))
11499 (goto-char
11500 (or (when (and rp (<= start rp))
11501 (if (> start lp)
11502 (if (setq child (js2-node-closest-child node (point) rp))
11503 (js2-node-abs-end child)
11504 (goto-char start)
11505 (signal 'scan-error (list scan-msg rp (1+ rp))))
11506 (1+ rp)))
11507 (and pos
11508 (+ pos
11509 (js2-node-len
11510 (if (js2-expr-stmt-node-p (js2-node-parent node))
11511 ;; stop after the semicolon
11512 (js2-node-parent node)
11513 node))))
11514 (point-max))))))))
11515
11516 (defun js2-mode-forward-sexp-parens (node abs-pos)
11517 (cond
11518 ((or (js2-array-node-p node)
11519 (js2-object-node-p node)
11520 (js2-array-comp-node-p node)
11521 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11522 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11523 ((js2-paren-expr-node-p node)
11524 (let ((lp (js2-node-lp node))
11525 (rp (js2-node-rp node)))
11526 (cons (when lp (+ abs-pos lp))
11527 (when rp (+ abs-pos rp)))))))
11528
11529 (defun js2-node-closest-child (parent point limit &optional before)
11530 (let* ((parent-pos (js2-node-abs-pos parent))
11531 (rpoint (- point parent-pos))
11532 (rlimit (- limit parent-pos))
11533 (min (min rpoint rlimit))
11534 (max (max rpoint rlimit))
11535 found)
11536 (catch 'done
11537 (js2-visit-ast
11538 parent
11539 (lambda (node end-p)
11540 (if (eq node parent)
11541 t
11542 (let ((pos (js2-node-pos node)) ;; Both relative values.
11543 (end (+ (js2-node-pos node) (js2-node-len node))))
11544 (when (and (>= pos min) (<= end max)
11545 (if before (< pos rpoint) (> end rpoint)))
11546 (setq found node))
11547 (when (> end rpoint)
11548 (throw 'done nil)))
11549 nil))))
11550 found))
11551
11552 (defun js2-next-error (&optional arg reset)
11553 "Move to next parse error.
11554 Typically invoked via \\[next-error].
11555 ARG is the number of errors, forward or backward, to move.
11556 RESET means start over from the beginning."
11557 (interactive "p")
11558 (if (or (null js2-mode-ast)
11559 (and (null (js2-ast-root-errors js2-mode-ast))
11560 (null (js2-ast-root-warnings js2-mode-ast))))
11561 (message "No errors")
11562 (when reset
11563 (goto-char (point-min)))
11564 (let* ((errs (copy-sequence
11565 (append (js2-ast-root-errors js2-mode-ast)
11566 (js2-ast-root-warnings js2-mode-ast))))
11567 (continue t)
11568 (start (point))
11569 (count (or arg 1))
11570 (backward (minusp count))
11571 (sorter (if backward '> '<))
11572 (stopper (if backward '< '>))
11573 (count (abs count))
11574 all-errs
11575 err)
11576 ;; sort by start position
11577 (setq errs (sort errs (lambda (e1 e2)
11578 (funcall sorter (second e1) (second e2))))
11579 all-errs errs)
11580 ;; find nth error with pos > start
11581 (while (and errs continue)
11582 (when (funcall stopper (cadar errs) start)
11583 (setq err (car errs))
11584 (if (zerop (decf count))
11585 (setq continue nil)))
11586 (setq errs (cdr errs)))
11587 (if err
11588 (goto-char (second err))
11589 ;; wrap around to first error
11590 (goto-char (second (car all-errs)))
11591 ;; if we were already on it, echo msg again
11592 (if (= (point) start)
11593 (js2-echo-error (point) (point)))))))
11594
11595 (defun js2-down-mouse-3 ()
11596 "Make right-click move the point to the click location.
11597 This makes right-click context menu operations a bit more intuitive.
11598 The point will not move if the region is active, however, to avoid
11599 destroying the region selection."
11600 (interactive)
11601 (when (and js2-move-point-on-right-click
11602 (not mark-active))
11603 (let ((e last-input-event))
11604 (ignore-errors
11605 (goto-char (cadadr e))))))
11606
11607 (defun js2-mode-create-imenu-index ()
11608 "Return an alist for `imenu--index-alist'."
11609 ;; This is built up in `js2-parse-record-imenu' during parsing.
11610 (when js2-mode-ast
11611 ;; if we have an ast but no recorder, they're requesting a rescan
11612 (unless js2-imenu-recorder
11613 (js2-reparse 'force))
11614 (prog1
11615 (js2-build-imenu-index)
11616 (setq js2-imenu-recorder nil
11617 js2-imenu-function-map nil))))
11618
11619 (defun js2-mode-find-tag ()
11620 "Replacement for `find-tag-default'.
11621 `find-tag-default' returns a ridiculous answer inside comments."
11622 (let (beg end)
11623 (js2-with-underscore-as-word-syntax
11624 (save-excursion
11625 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11626 (looking-back "[A-Za-z0-9_$]"))
11627 (setq beg (progn (forward-word -1) (point))
11628 end (progn (forward-word 1) (point)))
11629 (setq beg (progn (forward-word 1) (point))
11630 end (progn (forward-word -1) (point))))
11631 (replace-regexp-in-string
11632 "[\"']" ""
11633 (buffer-substring-no-properties beg end))))))
11634
11635 (defun js2-mode-forward-sibling ()
11636 "Move to the end of the sibling following point in parent.
11637 Returns non-nil if successful, or nil if there was no following sibling."
11638 (let* ((node (js2-node-at-point))
11639 (parent (js2-mode-find-enclosing-fn node))
11640 sib)
11641 (when (setq sib (js2-node-find-child-after (point) parent))
11642 (goto-char (+ (js2-node-abs-pos sib)
11643 (js2-node-len sib))))))
11644
11645 (defun js2-mode-backward-sibling ()
11646 "Move to the beginning of the sibling node preceding point in parent.
11647 Parent is defined as the enclosing script or function."
11648 (let* ((node (js2-node-at-point))
11649 (parent (js2-mode-find-enclosing-fn node))
11650 sib)
11651 (when (setq sib (js2-node-find-child-before (point) parent))
11652 (goto-char (js2-node-abs-pos sib)))))
11653
11654 (defun js2-beginning-of-defun (&optional arg)
11655 "Go to line on which current function starts, and return t on success.
11656 If we're not in a function or already at the beginning of one, go
11657 to beginning of previous script-level element.
11658 With ARG N, do that N times. If N is negative, move forward."
11659 (setq arg (or arg 1))
11660 (if (plusp arg)
11661 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11662 (when (cond
11663 ((js2-function-node-p parent)
11664 (goto-char (js2-node-abs-pos parent)))
11665 (t
11666 (js2-mode-backward-sibling)))
11667 (if (> arg 1)
11668 (js2-beginning-of-defun (1- arg))
11669 t)))
11670 (when (js2-end-of-defun)
11671 (if (>= arg -1)
11672 (js2-beginning-of-defun 1)
11673 (js2-beginning-of-defun (1+ arg))))))
11674
11675 (defun js2-end-of-defun ()
11676 "Go to the char after the last position of the current function
11677 or script-level element."
11678 (let* ((node (js2-node-at-point))
11679 (parent (or (and (js2-function-node-p node) node)
11680 (js2-node-parent-script-or-fn node)))
11681 script)
11682 (unless (js2-function-node-p parent)
11683 ;; use current script-level node, or, if none, the next one
11684 (setq script (or parent node))
11685 (setq parent (js2-node-find-child-before (point) script))
11686 (when (or (null parent)
11687 (>= (point) (+ (js2-node-abs-pos parent)
11688 (js2-node-len parent))))
11689 (setq parent (js2-node-find-child-after (point) script))))
11690 (when parent
11691 (goto-char (+ (js2-node-abs-pos parent)
11692 (js2-node-len parent))))))
11693
11694 (defun js2-mark-defun (&optional allow-extend)
11695 "Put mark at end of this function, point at beginning.
11696 The function marked is the one that contains point.
11697
11698 Interactively, if this command is repeated,
11699 or (in Transient Mark mode) if the mark is active,
11700 it marks the next defun after the ones already marked."
11701 (interactive "p")
11702 (let (extended)
11703 (when (and allow-extend
11704 (or (and (eq last-command this-command) (mark t))
11705 (and transient-mark-mode mark-active)))
11706 (let ((sib (save-excursion
11707 (goto-char (mark))
11708 (if (js2-mode-forward-sibling)
11709 (point))))
11710 node)
11711 (if sib
11712 (progn
11713 (set-mark sib)
11714 (setq extended t))
11715 ;; no more siblings - try extending to enclosing node
11716 (goto-char (mark t)))))
11717 (when (not extended)
11718 (let ((node (js2-node-at-point (point) t)) ; skip comments
11719 ast fn stmt parent beg end)
11720 (when (js2-ast-root-p node)
11721 (setq ast node
11722 node (or (js2-node-find-child-after (point) node)
11723 (js2-node-find-child-before (point) node))))
11724 ;; only mark whole buffer if we can't find any children
11725 (if (null node)
11726 (setq node ast))
11727 (if (js2-function-node-p node)
11728 (setq parent node)
11729 (setq fn (js2-mode-find-enclosing-fn node)
11730 stmt (if (or (null fn)
11731 (js2-ast-root-p fn))
11732 (js2-mode-find-first-stmt node))
11733 parent (or stmt fn)))
11734 (setq beg (js2-node-abs-pos parent)
11735 end (+ beg (js2-node-len parent)))
11736 (push-mark beg)
11737 (goto-char end)
11738 (exchange-point-and-mark)))))
11739
11740 (defun js2-narrow-to-defun ()
11741 "Narrow to the function enclosing point."
11742 (interactive)
11743 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11744 (fn (if (js2-script-node-p node)
11745 node
11746 (js2-mode-find-enclosing-fn node)))
11747 (beg (js2-node-abs-pos fn)))
11748 (unless (js2-ast-root-p fn)
11749 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11750
11751 (provide 'js2-mode)
11752
11753 ;;; js2-mode.el ends here