]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Make 'of' contextual keyword
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- an improved JavaScript editing mode
2
3 ;; Copyright (C) 2009 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; Contributors: mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; Version: See `js2-mode-version'
9 ;; Keywords: languages, javascript
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27
28 ;; This JavaScript editing mode supports:
29
30 ;; - strict recognition of the Ecma-262 language standard
31 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 to 1.8
32 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
33 ;; - accurate syntax highlighting using a recursive-descent parser
34 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
35 ;; - undeclared-variable warnings using a configurable externs framework
36 ;; - "bouncing" line indentation to choose among alternate indentation points
37 ;; - smart line-wrapping within comments and strings
38 ;; - code folding:
39 ;; - show some or all function bodies as {...}
40 ;; - show some or all block comments as /*...*/
41 ;; - context-sensitive menu bar and popup menus
42 ;; - code browsing using the `imenu' package
43 ;; - typing helpers such as automatic insertion of matching braces/parens
44 ;; - many customization options
45
46 ;; To customize how it works:
47 ;; M-x customize-group RET js2-mode RET
48
49 ;; Notes:
50
51 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
52 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
53 ;; `js2-mode' current as the EcmaScript language standard evolves.
54
55 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
56 ;; customizable. It is a surprising amount of work to support customizable
57 ;; indentation. The current compromise is that the tab key lets you cycle among
58 ;; various likely indentation points, similar to the behavior of python-mode.
59
60 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
61 ;; and `mumamo', although it could be made to do so with some effort.
62 ;; This means that `js2-mode' is currently only useful for editing JavaScript
63 ;; files, and not for editing JavaScript within <script> tags or templates.
64
65 ;;; Code:
66
67 (eval-when-compile
68 (require 'cl))
69
70 (require 'imenu)
71 (require 'cc-cmds) ; for `c-fill-paragraph'
72
73 (eval-and-compile
74 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
75 (require 'cc-langs) ; it's here in Emacs 21...
76 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
77
78 ;;; Externs (variables presumed to be defined by the host system)
79
80 (defvar js2-ecma-262-externs
81 (mapcar 'symbol-name
82 '(Array Boolean Date Error EvalError Function Infinity JSON
83 Math NaN Number Object RangeError ReferenceError RegExp
84 String SyntaxError TypeError URIError arguments
85 decodeURI decodeURIComponent encodeURI
86 encodeURIComponent escape eval isFinite isNaN
87 parseFloat parseInt undefined unescape))
88 "Ecma-262 externs. Included in `js2-externs' by default.")
89
90 (defvar js2-browser-externs
91 (mapcar 'symbol-name
92 '(;; DOM level 1
93 Attr CDATASection CharacterData Comment DOMException
94 DOMImplementation Document DocumentFragment
95 DocumentType Element Entity EntityReference
96 ExceptionCode NamedNodeMap Node NodeList Notation
97 ProcessingInstruction Text
98
99 ;; DOM level 2
100 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
101 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
102 HTMLBodyElement HTMLButtonElement HTMLCollection
103 HTMLDListElement HTMLDirectoryElement HTMLDivElement
104 HTMLDocument HTMLElement HTMLFieldSetElement
105 HTMLFontElement HTMLFormElement HTMLFrameElement
106 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
107 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
108 HTMLImageElement HTMLInputElement HTMLIsIndexElement
109 HTMLLIElement HTMLLabelElement HTMLLegendElement
110 HTMLLinkElement HTMLMapElement HTMLMenuElement
111 HTMLMetaElement HTMLModElement HTMLOListElement
112 HTMLObjectElement HTMLOptGroupElement
113 HTMLOptionElement HTMLOptionsCollection
114 HTMLParagraphElement HTMLParamElement HTMLPreElement
115 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
116 HTMLStyleElement HTMLTableCaptionElement
117 HTMLTableCellElement HTMLTableColElement
118 HTMLTableElement HTMLTableRowElement
119 HTMLTableSectionElement HTMLTextAreaElement
120 HTMLTitleElement HTMLUListElement
121
122 ;; DOM level 3
123 DOMConfiguration DOMError DOMException
124 DOMImplementationList DOMImplementationSource
125 DOMLocator DOMStringList NameList TypeInfo
126 UserDataHandler
127
128 ;; Window
129 window alert confirm document java navigator prompt screen
130 self top
131
132 ;; W3C CSS
133 CSSCharsetRule CSSFontFace CSSFontFaceRule
134 CSSImportRule CSSMediaRule CSSPageRule
135 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
136 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
137 CSSValue CSSValueList Counter DOMImplementationCSS
138 DocumentCSS DocumentStyle ElementCSSInlineStyle
139 LinkStyle MediaList RGBColor Rect StyleSheet
140 StyleSheetList ViewCSS
141
142 ;; W3C Event
143 EventListener EventTarget Event DocumentEvent UIEvent
144 MouseEvent MutationEvent KeyboardEvent
145
146 ;; W3C Range
147 DocumentRange Range RangeException
148
149 ;; W3C XML
150 XPathResult XMLHttpRequest))
151 "Browser externs.
152 You can cause these to be included or excluded with the custom
153 variable `js2-include-browser-externs'.")
154
155 (defvar js2-rhino-externs
156 (mapcar 'symbol-name
157 '(Packages importClass importPackage com org java
158 ;; Global object (shell) externs
159 defineClass deserialize doctest gc help load
160 loadClass print quit readFile readUrl runCommand seal
161 serialize spawn sync toint32 version))
162 "Mozilla Rhino externs.
163 Set `js2-include-rhino-externs' to t to include them.")
164
165 (defvar js2-gears-externs
166 (mapcar 'symbol-name
167 '(
168 ;; TODO(stevey): add these
169 ))
170 "Google Gears externs.
171 Set `js2-include-gears-externs' to t to include them.")
172
173 ;;; Variables
174
175 (defun js2-mark-safe-local (name pred)
176 "Make the variable NAME buffer-local and mark it as safe file-local
177 variable with predicate PRED."
178 (make-variable-buffer-local name)
179 (put name 'safe-local-variable pred))
180
181 (defvar js2-emacs22 (>= emacs-major-version 22))
182
183 (defcustom js2-highlight-level 2
184 "Amount of syntax highlighting to perform.
185 0 or a negative value means do no highlighting.
186 1 adds basic syntax highlighting.
187 2 adds highlighting of some Ecma built-in properties.
188 3 adds highlighting of many Ecma built-in functions."
189 :group 'js2-mode
190 :type '(choice (const :tag "None" 0)
191 (const :tag "Basic" 1)
192 (const :tag "Include Properties" 2)
193 (const :tag "Include Functions" 3)))
194
195 (defvar js2-mode-dev-mode-p nil
196 "Non-nil if running in development mode. Normally nil.")
197
198 (defgroup js2-mode nil
199 "An improved JavaScript mode."
200 :group 'languages)
201
202 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
203 (numberp c-basic-offset))
204 c-basic-offset
205 4)
206 "Number of spaces to indent nested statements.
207 Similar to `c-basic-offset'."
208 :group 'js2-mode
209 :type 'integer)
210 (js2-mark-safe-local 'js2-basic-offset 'integerp)
211
212 ;; TODO(stevey): move this code into a separate minor mode.
213 (defcustom js2-mirror-mode nil
214 "Non-nil to insert closing brackets, parens, etc. automatically."
215 :group 'js2-mode
216 :type 'boolean)
217
218 (defcustom js2-auto-indent-p nil
219 "Automatic indentation with punctuation characters.
220 If non-nil, the current line is indented when certain punctuations
221 are inserted."
222 :group 'js2-mode
223 :type 'boolean)
224
225 (defcustom js2-bounce-indent-p nil
226 "Non-nil to have indent-line function choose among alternatives.
227 If nil, the indent-line function will indent to a predetermined column
228 based on heuristic guessing. If non-nil, then if the current line is
229 already indented to that predetermined column, indenting will choose
230 another likely column and indent to that spot. Repeated invocation of
231 the indent-line function will cycle among the computed alternatives.
232 See the function `js2-bounce-indent' for details. When it is non-nil,
233 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
234 :type 'boolean
235 :group 'js2-mode)
236
237 (defcustom js2-pretty-multiline-declarations t
238 "Non-nil to line up multiline declarations vertically:
239
240 var a = 10,
241 b = 20,
242 c = 30;
243
244 If the value is not `all', and the first assigned value in
245 declaration is a function/array/object literal spanning several
246 lines, it won't be indented additionally:
247
248 var o = { var bar = 2,
249 foo: 3 vs. o = {
250 }, foo: 3
251 bar = 2; };"
252 :group 'js2-mode
253 :type 'symbol)
254 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
255
256 (defcustom js2-indent-on-enter-key nil
257 "Non-nil to have Enter/Return key indent the line.
258 This is unusual for Emacs modes but common in IDEs like Eclipse."
259 :type 'boolean
260 :group 'js2-mode)
261
262 (defcustom js2-enter-indents-newline nil
263 "Non-nil to have Enter/Return key indent the newly-inserted line.
264 This is unusual for Emacs modes but common in IDEs like Eclipse."
265 :type 'boolean
266 :group 'js2-mode)
267
268 (defcustom js2-rebind-eol-bol-keys t
269 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
270 If non-nil, bounce between bol/eol and first/last non-whitespace char."
271 :group 'js2-mode
272 :type 'boolean)
273
274 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
275 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
276 Each value in the list is passed to `define-key'."
277 :type 'list
278 :group 'js2-mode)
279
280 (defcustom js2-idle-timer-delay 0.2
281 "Delay in secs before re-parsing after user makes changes.
282 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
283 :type 'number
284 :group 'js2-mode)
285 (make-variable-buffer-local 'js2-idle-timer-delay)
286
287 (defcustom js2-dynamic-idle-timer-adjust 0
288 "Positive to adjust `js2-idle-timer-delay' based on file size.
289 The idea is that for short files, parsing is faster so we can be
290 more responsive to user edits without interfering with editing.
291 The buffer length in characters (typically bytes) is divided by
292 this value and used to multiply `js2-idle-timer-delay' for the
293 buffer. For example, a 21k file and 10k adjust yields 21k/10k
294 == 2, so js2-idle-timer-delay is multiplied by 2.
295 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
296 `js2-idle-timer-delay' is not dependent on the file size."
297 :type 'number
298 :group 'js2-mode)
299
300 (defcustom js2-mode-escape-quotes t
301 "Non-nil to disable automatic quote-escaping inside strings."
302 :type 'boolean
303 :group 'js2-mode)
304
305 (defcustom js2-concat-multiline-strings t
306 "Non-nil to automatically turn a newline in mid-string into a
307 string concatenation. When `eol', the '+' will be inserted at the
308 end of the line, otherwise, at the beginning of the next line."
309 :type '(choice (const t) (const eol) (const nil))
310 :group 'js2-mode)
311
312 (defcustom js2-mode-squeeze-spaces t
313 "Non-nil to normalize whitespace when filling in comments.
314 Multiple runs of spaces are converted to a single space."
315 :type 'boolean
316 :group 'js2-mode)
317
318 (defcustom js2-mode-show-parse-errors t
319 "True to highlight parse errors."
320 :type 'boolean
321 :group 'js2-mode)
322
323 (defcustom js2-mode-show-strict-warnings t
324 "Non-nil to emit Ecma strict-mode warnings.
325 Some of the warnings can be individually disabled by other flags,
326 even if this flag is non-nil."
327 :type 'boolean
328 :group 'js2-mode)
329
330 (defcustom js2-strict-trailing-comma-warning t
331 "Non-nil to warn about trailing commas in array literals.
332 Ecma-262 forbids them, but many browsers permit them. IE is the
333 big exception, and can produce bugs if you have trailing commas."
334 :type 'boolean
335 :group 'js2-mode)
336
337 (defcustom js2-strict-missing-semi-warning t
338 "Non-nil to warn about semicolon auto-insertion after statement.
339 Technically this is legal per Ecma-262, but some style guides disallow
340 depending on it."
341 :type 'boolean
342 :group 'js2-mode)
343
344 (defcustom js2-missing-semi-one-line-override nil
345 "Non-nil to permit missing semicolons in one-line functions.
346 In one-liner functions such as `function identity(x) {return x}'
347 people often omit the semicolon for a cleaner look. If you are
348 such a person, you can suppress the missing-semicolon warning
349 by setting this variable to t."
350 :type 'boolean
351 :group 'js2-mode)
352
353 (defcustom js2-strict-inconsistent-return-warning t
354 "Non-nil to warn about mixing returns with value-returns.
355 It's perfectly legal to have a `return' and a `return foo' in the
356 same function, but it's often an indicator of a bug, and it also
357 interferes with type inference (in systems that support it.)"
358 :type 'boolean
359 :group 'js2-mode)
360
361 (defcustom js2-strict-cond-assign-warning t
362 "Non-nil to warn about expressions like if (a = b).
363 This often should have been '==' instead of '='. If the warning
364 is enabled, you can suppress it on a per-expression basis by
365 parenthesizing the expression, e.g. if ((a = b)) ..."
366 :type 'boolean
367 :group 'js2-mode)
368
369 (defcustom js2-strict-var-redeclaration-warning t
370 "Non-nil to warn about redeclaring variables in a script or function."
371 :type 'boolean
372 :group 'js2-mode)
373
374 (defcustom js2-strict-var-hides-function-arg-warning t
375 "Non-nil to warn about a var decl hiding a function argument."
376 :type 'boolean
377 :group 'js2-mode)
378
379 (defcustom js2-skip-preprocessor-directives nil
380 "Non-nil to treat lines beginning with # as comments.
381 Useful for viewing Mozilla JavaScript source code."
382 :type 'boolean
383 :group 'js2-mode)
384
385 (defcustom js2-language-version 200
386 "Configures what JavaScript language version to recognize.
387 Currently versions 150, 160, 170, 180 and 200 are supported,
388 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
389 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
390 yield, and Array comprehensions, and 1.8 adds function closures."
391 :type 'integer
392 :group 'js2-mode)
393
394 (defcustom js2-allow-keywords-as-property-names t
395 "If non-nil, you can use JavaScript keywords as object property names.
396 Examples:
397
398 var foo = {int: 5, while: 6, continue: 7};
399 foo.return = 8;
400
401 Ecma-262 forbids this syntax, but many browsers support it."
402 :type 'boolean
403 :group 'js2-mode)
404
405 (defcustom js2-instanceof-has-side-effects nil
406 "If non-nil, treats the instanceof operator as having side effects.
407 This is useful for xulrunner apps."
408 :type 'boolean
409 :group 'js2-mode)
410
411 (defcustom js2-cleanup-whitespace nil
412 "Non-nil to invoke `delete-trailing-whitespace' before saves."
413 :type 'boolean
414 :group 'js2-mode)
415
416 (defcustom js2-move-point-on-right-click t
417 "Non-nil to move insertion point when you right-click.
418 This makes right-click context menu behavior a bit more intuitive,
419 since menu operations generally apply to the point. The exception
420 is if there is a region selection, in which case the point does -not-
421 move, so cut/copy/paste etc. can work properly.
422
423 Note that IntelliJ moves the point, and Eclipse leaves it alone,
424 so this behavior is customizable."
425 :group 'js2-mode
426 :type 'boolean)
427
428 (defcustom js2-allow-rhino-new-expr-initializer t
429 "Non-nil to support a Rhino's experimental syntactic construct.
430
431 Rhino supports the ability to follow a `new' expression with an object
432 literal, which is used to set additional properties on the new object
433 after calling its constructor. Syntax:
434
435 new <expr> [ ( arglist ) ] [initializer]
436
437 Hence, this expression:
438
439 new Object {a: 1, b: 2}
440
441 results in an Object with properties a=1 and b=2. This syntax is
442 apparently not configurable in Rhino - it's currently always enabled,
443 as of Rhino version 1.7R2."
444 :type 'boolean
445 :group 'js2-mode)
446
447 (defcustom js2-allow-member-expr-as-function-name nil
448 "Non-nil to support experimental Rhino syntax for function names.
449
450 Rhino supports an experimental syntax configured via the Rhino Context
451 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
452
453 function <member-expr> ( [ arg-list ] ) { <body> }
454
455 Where member-expr is a non-parenthesized 'member expression', which
456 is anything at the grammar level of a new-expression or lower, meaning
457 any expression that does not involve infix or unary operators.
458
459 When <member-expr> is not a simple identifier, then it is syntactic
460 sugar for assigning the anonymous function to the <member-expr>. Hence,
461 this code:
462
463 function a.b().c[2] (x, y) { ... }
464
465 is rewritten as:
466
467 a.b().c[2] = function(x, y) {...}
468
469 which doesn't seem particularly useful, but Rhino permits it."
470 :type 'boolean
471 :group 'js2-mode)
472
473 (defvar js2-mode-version 20101228
474 "Release number for `js2-mode'.")
475
476 ;; scanner variables
477
478 (defmacro js2-deflocal (name value &optional comment)
479 "Define a buffer-local variable NAME with VALUE and COMMENT."
480 `(progn
481 (defvar ,name ,value ,comment)
482 (make-variable-buffer-local ',name)))
483
484 ;; We record the start and end position of each token.
485 (js2-deflocal js2-token-beg 1)
486 (js2-deflocal js2-token-end -1)
487
488 (defvar js2-EOF_CHAR -1
489 "Represents end of stream. Distinct from js2-EOF token type.")
490
491 ;; I originally used symbols to represent tokens, but Rhino uses
492 ;; ints and then sets various flag bits in them, so ints it is.
493 ;; The upshot is that we need a `js2-' prefix in front of each name.
494 (defvar js2-ERROR -1)
495 (defvar js2-EOF 0)
496 (defvar js2-EOL 1)
497 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
498 (defvar js2-LEAVEWITH 3)
499 (defvar js2-RETURN 4)
500 (defvar js2-GOTO 5)
501 (defvar js2-IFEQ 6)
502 (defvar js2-IFNE 7)
503 (defvar js2-SETNAME 8)
504 (defvar js2-BITOR 9)
505 (defvar js2-BITXOR 10)
506 (defvar js2-BITAND 11)
507 (defvar js2-EQ 12)
508 (defvar js2-NE 13)
509 (defvar js2-LT 14)
510 (defvar js2-LE 15)
511 (defvar js2-GT 16)
512 (defvar js2-GE 17)
513 (defvar js2-LSH 18)
514 (defvar js2-RSH 19)
515 (defvar js2-URSH 20)
516 (defvar js2-ADD 21) ; infix plus
517 (defvar js2-SUB 22) ; infix minus
518 (defvar js2-MUL 23)
519 (defvar js2-DIV 24)
520 (defvar js2-MOD 25)
521 (defvar js2-NOT 26)
522 (defvar js2-BITNOT 27)
523 (defvar js2-POS 28) ; unary plus
524 (defvar js2-NEG 29) ; unary minus
525 (defvar js2-NEW 30)
526 (defvar js2-DELPROP 31)
527 (defvar js2-TYPEOF 32)
528 (defvar js2-GETPROP 33)
529 (defvar js2-GETPROPNOWARN 34)
530 (defvar js2-SETPROP 35)
531 (defvar js2-GETELEM 36)
532 (defvar js2-SETELEM 37)
533 (defvar js2-CALL 38)
534 (defvar js2-NAME 39) ; an identifier
535 (defvar js2-NUMBER 40)
536 (defvar js2-STRING 41)
537 (defvar js2-NULL 42)
538 (defvar js2-THIS 43)
539 (defvar js2-FALSE 44)
540 (defvar js2-TRUE 45)
541 (defvar js2-SHEQ 46) ; shallow equality (===)
542 (defvar js2-SHNE 47) ; shallow inequality (!==)
543 (defvar js2-REGEXP 48)
544 (defvar js2-BINDNAME 49)
545 (defvar js2-THROW 50)
546 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
547 (defvar js2-IN 52)
548 (defvar js2-INSTANCEOF 53)
549 (defvar js2-LOCAL_LOAD 54)
550 (defvar js2-GETVAR 55)
551 (defvar js2-SETVAR 56)
552 (defvar js2-CATCH_SCOPE 57)
553 (defvar js2-ENUM_INIT_KEYS 58)
554 (defvar js2-ENUM_INIT_VALUES 59)
555 (defvar js2-ENUM_INIT_ARRAY 60)
556 (defvar js2-ENUM_NEXT 61)
557 (defvar js2-ENUM_ID 62)
558 (defvar js2-THISFN 63)
559 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
560 (defvar js2-ARRAYLIT 65) ; array literal
561 (defvar js2-OBJECTLIT 66) ; object literal
562 (defvar js2-GET_REF 67) ; *reference
563 (defvar js2-SET_REF 68) ; *reference = something
564 (defvar js2-DEL_REF 69) ; delete reference
565 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
566 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
567 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
568
569 ;; XML support
570 (defvar js2-DEFAULTNAMESPACE 73)
571 (defvar js2-ESCXMLATTR 74)
572 (defvar js2-ESCXMLTEXT 75)
573 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
574 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
575 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
576 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
577
578 (defvar js2-first-bytecode js2-ENTERWITH)
579 (defvar js2-last-bytecode js2-REF_NS_NAME)
580
581 (defvar js2-TRY 80)
582 (defvar js2-SEMI 81) ; semicolon
583 (defvar js2-LB 82) ; left and right brackets
584 (defvar js2-RB 83)
585 (defvar js2-LC 84) ; left and right curly-braces
586 (defvar js2-RC 85)
587 (defvar js2-LP 86) ; left and right parens
588 (defvar js2-RP 87)
589 (defvar js2-COMMA 88) ; comma operator
590
591 (defvar js2-ASSIGN 89) ; simple assignment (=)
592 (defvar js2-ASSIGN_BITOR 90) ; |=
593 (defvar js2-ASSIGN_BITXOR 91) ; ^=
594 (defvar js2-ASSIGN_BITAND 92) ; &=
595 (defvar js2-ASSIGN_LSH 93) ; <<=
596 (defvar js2-ASSIGN_RSH 94) ; >>=
597 (defvar js2-ASSIGN_URSH 95) ; >>>=
598 (defvar js2-ASSIGN_ADD 96) ; +=
599 (defvar js2-ASSIGN_SUB 97) ; -=
600 (defvar js2-ASSIGN_MUL 98) ; *=
601 (defvar js2-ASSIGN_DIV 99) ; /=
602 (defvar js2-ASSIGN_MOD 100) ; %=
603
604 (defvar js2-first-assign js2-ASSIGN)
605 (defvar js2-last-assign js2-ASSIGN_MOD)
606
607 (defvar js2-HOOK 101) ; conditional (?:)
608 (defvar js2-COLON 102)
609 (defvar js2-OR 103) ; logical or (||)
610 (defvar js2-AND 104) ; logical and (&&)
611 (defvar js2-INC 105) ; increment/decrement (++ --)
612 (defvar js2-DEC 106)
613 (defvar js2-DOT 107) ; member operator (.)
614 (defvar js2-FUNCTION 108) ; function keyword
615 (defvar js2-EXPORT 109) ; export keyword
616 (defvar js2-IMPORT 110) ; import keyword
617 (defvar js2-IF 111) ; if keyword
618 (defvar js2-ELSE 112) ; else keyword
619 (defvar js2-SWITCH 113) ; switch keyword
620 (defvar js2-CASE 114) ; case keyword
621 (defvar js2-DEFAULT 115) ; default keyword
622 (defvar js2-WHILE 116) ; while keyword
623 (defvar js2-DO 117) ; do keyword
624 (defvar js2-FOR 118) ; for keyword
625 (defvar js2-BREAK 119) ; break keyword
626 (defvar js2-CONTINUE 120) ; continue keyword
627 (defvar js2-VAR 121) ; var keyword
628 (defvar js2-WITH 122) ; with keyword
629 (defvar js2-CATCH 123) ; catch keyword
630 (defvar js2-FINALLY 124) ; finally keyword
631 (defvar js2-VOID 125) ; void keyword
632 (defvar js2-RESERVED 126) ; reserved keywords
633
634 (defvar js2-EMPTY 127)
635
636 ;; Types used for the parse tree - never returned by scanner.
637
638 (defvar js2-BLOCK 128) ; statement block
639 (defvar js2-LABEL 129) ; label
640 (defvar js2-TARGET 130)
641 (defvar js2-LOOP 131)
642 (defvar js2-EXPR_VOID 132) ; expression statement in functions
643 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
644 (defvar js2-JSR 134)
645 (defvar js2-SCRIPT 135) ; top-level node for entire script
646 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
647 (defvar js2-USE_STACK 137)
648 (defvar js2-SETPROP_OP 138) ; x.y op= something
649 (defvar js2-SETELEM_OP 139) ; x[y] op= something
650 (defvar js2-LOCAL_BLOCK 140)
651 (defvar js2-SET_REF_OP 141) ; *reference op= something
652
653 ;; For XML support:
654 (defvar js2-DOTDOT 142) ; member operator (..)
655 (defvar js2-COLONCOLON 143) ; namespace::name
656 (defvar js2-XML 144) ; XML type
657 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
658 (defvar js2-XMLATTR 146) ; @
659 (defvar js2-XMLEND 147)
660
661 ;; Optimizer-only tokens
662 (defvar js2-TO_OBJECT 148)
663 (defvar js2-TO_DOUBLE 149)
664
665 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
666 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
667 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
668 (defvar js2-CONST 153)
669 (defvar js2-SETCONST 154)
670 (defvar js2-SETCONSTVAR 155)
671 (defvar js2-ARRAYCOMP 156)
672 (defvar js2-LETEXPR 157)
673 (defvar js2-WITHEXPR 158)
674 (defvar js2-DEBUGGER 159)
675
676 (defvar js2-COMMENT 160)
677 (defvar js2-ENUM 161) ; for "enum" reserved word
678
679 (defconst js2-num-tokens (1+ js2-ENUM))
680
681 (defconst js2-debug-print-trees nil)
682
683 ;; Rhino accepts any string or stream as input. Emacs character
684 ;; processing works best in buffers, so we'll assume the input is a
685 ;; buffer. JavaScript strings can be copied into temp buffers before
686 ;; scanning them.
687
688 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
689 ;; They're the Emacs equivalent of instance variables, more or less.
690
691 (js2-deflocal js2-ts-dirty-line nil
692 "Token stream buffer-local variable.
693 Indicates stuff other than whitespace since start of line.")
694
695 (js2-deflocal js2-ts-regexp-flags nil
696 "Token stream buffer-local variable.")
697
698 (js2-deflocal js2-ts-string ""
699 "Token stream buffer-local variable.
700 Last string scanned.")
701
702 (js2-deflocal js2-ts-number nil
703 "Token stream buffer-local variable.
704 Last literal number scanned.")
705
706 (js2-deflocal js2-ts-hit-eof nil
707 "Token stream buffer-local variable.")
708
709 (js2-deflocal js2-ts-line-start 0
710 "Token stream buffer-local variable.")
711
712 (js2-deflocal js2-ts-lineno 1
713 "Token stream buffer-local variable.")
714
715 (js2-deflocal js2-ts-line-end-char -1
716 "Token stream buffer-local variable.")
717
718 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
719 "Token stream buffer-local variable.
720 Current scan position.")
721
722 (js2-deflocal js2-ts-is-xml-attribute nil
723 "Token stream buffer-local variable.")
724
725 (js2-deflocal js2-ts-xml-is-tag-content nil
726 "Token stream buffer-local variable.")
727
728 (js2-deflocal js2-ts-xml-open-tags-count 0
729 "Token stream buffer-local variable.")
730
731 (js2-deflocal js2-ts-string-buffer nil
732 "Token stream buffer-local variable.
733 List of chars built up while scanning various tokens.")
734
735 (js2-deflocal js2-ts-comment-type nil
736 "Token stream buffer-local variable.")
737
738 ;;; Parser variables
739
740 (js2-deflocal js2-parsed-errors nil
741 "List of errors produced during scanning/parsing.")
742
743 (js2-deflocal js2-parsed-warnings nil
744 "List of warnings produced during scanning/parsing.")
745
746 (js2-deflocal js2-recover-from-parse-errors t
747 "Non-nil to continue parsing after a syntax error.
748
749 In recovery mode, the AST will be built in full, and any error
750 nodes will be flagged with appropriate error information. If
751 this flag is nil, a syntax error will result in an error being
752 signaled.
753
754 The variable is automatically buffer-local, because different
755 modes that use the parser will need different settings.")
756
757 (js2-deflocal js2-parse-hook nil
758 "List of callbacks for receiving parsing progress.")
759
760 (defvar js2-parse-finished-hook nil
761 "List of callbacks to notify when parsing finishes.
762 Not called if parsing was interrupted.")
763
764 (js2-deflocal js2-is-eval-code nil
765 "True if we're evaluating code in a string.
766 If non-nil, the tokenizer will record the token text, and the AST nodes
767 will record their source text. Off by default for IDE modes, since the
768 text is available in the buffer.")
769
770 (defvar js2-parse-ide-mode t
771 "Non-nil if the parser is being used for `js2-mode'.
772 If non-nil, the parser will set text properties for fontification
773 and the syntax table. The value should be nil when using the
774 parser as a frontend to an interpreter or byte compiler.")
775
776 ;;; Parser instance variables (buffer-local vars for js2-parse)
777
778 (defconst js2-clear-ti-mask #xFFFF
779 "Mask to clear token information bits.")
780
781 (defconst js2-ti-after-eol (lsh 1 16)
782 "Flag: first token of the source line.")
783
784 (defconst js2-ti-check-label (lsh 1 17)
785 "Flag: indicates to check for label.")
786
787 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
788
789 (js2-deflocal js2-compiler-generate-debug-info t)
790 (js2-deflocal js2-compiler-use-dynamic-scope nil)
791 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
792 (js2-deflocal js2-compiler-xml-available t)
793 (js2-deflocal js2-compiler-optimization-level 0)
794 (js2-deflocal js2-compiler-generating-source t)
795 (js2-deflocal js2-compiler-strict-mode nil)
796 (js2-deflocal js2-compiler-report-warning-as-error nil)
797 (js2-deflocal js2-compiler-generate-observer-count nil)
798 (js2-deflocal js2-compiler-activation-names nil)
799
800 ;; SKIP: sourceURI
801
802 ;; There's a compileFunction method in Context.java - may need it.
803 (js2-deflocal js2-called-by-compile-function nil
804 "True if `js2-parse' was called by `js2-compile-function'.
805 Will only be used when we finish implementing the interpreter.")
806
807 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
808
809 (js2-deflocal js2-current-flagged-token js2-EOF)
810 (js2-deflocal js2-current-token js2-EOF)
811
812 ;; SKIP: node factory - we're going to just call functions directly,
813 ;; and eventually go to a unified AST format.
814
815 (js2-deflocal js2-nesting-of-function 0)
816
817 (js2-deflocal js2-recorded-identifiers nil
818 "Tracks identifiers found during parsing.")
819
820 (defmacro js2-in-lhs (body)
821 `(let ((js2-is-in-lhs t))
822 ,body))
823
824 (defmacro js2-in-rhs (body)
825 `(let ((js2-is-in-lhs nil))
826 ,body))
827
828 (js2-deflocal js2-is-in-lhs nil
829 "True while parsing lhs statement")
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 `root' 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 ;; also define user's preference for next-error, if available
1185 (if (setq keys (where-is-internal #'next-error))
1186 (define-key map (car keys) #'js2-next-error))
1187 (define-key map (or (car (where-is-internal #'mark-defun))
1188 (kbd "M-C-h"))
1189 #'js2-mark-defun)
1190 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1191 (kbd "C-x nd"))
1192 #'js2-narrow-to-defun)
1193 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1194 (when js2-auto-indent-p
1195 (mapc (lambda (key)
1196 (define-key map key #'js2-insert-and-indent))
1197 js2-electric-keys))
1198 (when js2-bounce-indent-p
1199 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1200
1201 (define-key map [menu-bar javascript]
1202 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1203
1204 (define-key map [menu-bar javascript customize-js2-mode]
1205 '(menu-item "Customize js2-mode" js2-mode-customize
1206 :help "Customize the behavior of this mode"))
1207
1208 (define-key map [menu-bar javascript js2-force-refresh]
1209 '(menu-item "Force buffer refresh" js2-mode-reset
1210 :help "Re-parse the buffer from scratch"))
1211
1212 (define-key map [menu-bar javascript separator-2]
1213 '("--"))
1214
1215 (define-key map [menu-bar javascript next-error]
1216 '(menu-item "Next warning or error" js2-next-error
1217 :enabled (and js2-mode-ast
1218 (or (js2-ast-root-errors js2-mode-ast)
1219 (js2-ast-root-warnings js2-mode-ast)))
1220 :help "Move to next warning or error"))
1221
1222 (define-key map [menu-bar javascript display-errors]
1223 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1224 :visible (not js2-mode-show-parse-errors)
1225 :help "Turn on display of warnings and errors"))
1226
1227 (define-key map [menu-bar javascript hide-errors]
1228 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1229 :visible js2-mode-show-parse-errors
1230 :help "Turn off display of warnings and errors"))
1231
1232 (define-key map [menu-bar javascript separator-1]
1233 '("--"))
1234
1235 (define-key map [menu-bar javascript js2-toggle-function]
1236 '(menu-item "Show/collapse element" js2-mode-toggle-element
1237 :help "Hide or show function body or comment"))
1238
1239 (define-key map [menu-bar javascript show-comments]
1240 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1241 :visible js2-mode-comments-hidden
1242 :help "Expand all hidden block comments"))
1243
1244 (define-key map [menu-bar javascript hide-comments]
1245 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1246 :visible (not js2-mode-comments-hidden)
1247 :help "Show block comments as /*...*/"))
1248
1249 (define-key map [menu-bar javascript show-all-functions]
1250 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1251 :visible js2-mode-functions-hidden
1252 :help "Expand all hidden function bodies"))
1253
1254 (define-key map [menu-bar javascript hide-all-functions]
1255 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1256 :visible (not js2-mode-functions-hidden)
1257 :help "Show {...} for all top-level function bodies"))
1258
1259 map)
1260 "Keymap used in `js2-mode' buffers.")
1261
1262 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1263
1264 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1265 "Matches a //-comment line. Must be first non-whitespace on line.
1266 First match-group is the leading whitespace.")
1267
1268 (defvar js2-mode-hook nil)
1269
1270 (js2-deflocal js2-mode-ast nil "Private variable.")
1271 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1272 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1273 (js2-deflocal js2-mode-parsing nil "Private variable.")
1274 (js2-deflocal js2-mode-node-overlay nil)
1275
1276 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1277 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1278
1279 (js2-deflocal js2-mode-fontifications nil "Private variable")
1280 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1281 (js2-deflocal js2-imenu-recorder nil "Private variable")
1282 (js2-deflocal js2-imenu-function-map nil "Private variable")
1283
1284 (defvar js2-paragraph-start
1285 "\\(@[a-zA-Z]+\\>\\|$\\)")
1286
1287 ;; Note that we also set a 'c-in-sws text property in html comments,
1288 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1289 (defvar js2-syntactic-ws-start
1290 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1291
1292 (defvar js2-syntactic-ws-end
1293 "\\s \\|[\n\r/]\\|\\s!")
1294
1295 (defvar js2-syntactic-eol
1296 (concat "\\s *\\(/\\*[^*\n\r]*"
1297 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1298 "\\*+/\\s *\\)*"
1299 "\\(//\\|/\\*[^*\n\r]*"
1300 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1301 "\\|\\\\$\\|$\\)")
1302 "Copied from `java-mode'. Needed for some cc-engine functions.")
1303
1304 (defvar js2-comment-prefix-regexp
1305 "//+\\|\\**")
1306
1307 (defvar js2-comment-start-skip
1308 "\\(//+\\|/\\*+\\)\\s *")
1309
1310 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1311 "Non-nil to emit status messages during parsing.")
1312
1313 (defvar js2-mode-functions-hidden nil "private variable")
1314 (defvar js2-mode-comments-hidden nil "private variable")
1315
1316 (defvar js2-mode-syntax-table
1317 (let ((table (make-syntax-table)))
1318 (c-populate-syntax-table table)
1319 table)
1320 "Syntax table used in js2-mode buffers.")
1321
1322 (defvar js2-mode-abbrev-table nil
1323 "Abbrev table in use in `js2-mode' buffers.")
1324 (define-abbrev-table 'js2-mode-abbrev-table ())
1325
1326 (defvar js2-mode-pending-parse-callbacks nil
1327 "List of functions waiting to be notified that parse is finished.")
1328
1329 (defvar js2-mode-last-indented-line -1)
1330
1331 ;;; Localizable error and warning messages
1332
1333 ;; Messages are copied from Rhino's Messages.properties.
1334 ;; Many of the Java-specific messages have been elided.
1335 ;; Add any js2-specific ones at the end, so we can keep
1336 ;; this file synced with changes to Rhino's.
1337
1338 (defvar js2-message-table
1339 (make-hash-table :test 'equal :size 250)
1340 "Contains localized messages for js2-mode.")
1341
1342 ;; TODO(stevey): construct this table at compile-time.
1343 (defmacro js2-msg (key &rest strings)
1344 `(puthash ,key (funcall #'concat ,@strings)
1345 js2-message-table))
1346
1347 (defun js2-get-msg (msg-key)
1348 "Look up a localized message.
1349 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1350 the correct number of ARGS must be provided."
1351 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1352 (args (if (listp msg-key) (cdr msg-key)))
1353 (msg (gethash key js2-message-table)))
1354 (if msg
1355 (apply #'format msg args)
1356 key))) ; default to showing the key
1357
1358 (js2-msg "msg.dup.parms"
1359 "Duplicate parameter name '%s'.")
1360
1361 (js2-msg "msg.too.big.jump"
1362 "Program too complex: jump offset too big.")
1363
1364 (js2-msg "msg.too.big.index"
1365 "Program too complex: internal index exceeds 64K limit.")
1366
1367 (js2-msg "msg.while.compiling.fn"
1368 "Encountered code generation error while compiling function '%s': %s")
1369
1370 (js2-msg "msg.while.compiling.script"
1371 "Encountered code generation error while compiling script: %s")
1372
1373 ;; Context
1374 (js2-msg "msg.ctor.not.found"
1375 "Constructor for '%s' not found.")
1376
1377 (js2-msg "msg.not.ctor"
1378 "'%s' is not a constructor.")
1379
1380 ;; FunctionObject
1381 (js2-msg "msg.varargs.ctor"
1382 "Method or constructor '%s' must be static "
1383 "with the signature (Context cx, Object[] args, "
1384 "Function ctorObj, boolean inNewExpr) "
1385 "to define a variable arguments constructor.")
1386
1387 (js2-msg "msg.varargs.fun"
1388 "Method '%s' must be static with the signature "
1389 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1390 "to define a variable arguments function.")
1391
1392 (js2-msg "msg.incompat.call"
1393 "Method '%s' called on incompatible object.")
1394
1395 (js2-msg "msg.bad.parms"
1396 "Unsupported parameter type '%s' in method '%s'.")
1397
1398 (js2-msg "msg.bad.method.return"
1399 "Unsupported return type '%s' in method '%s'.")
1400
1401 (js2-msg "msg.bad.ctor.return"
1402 "Construction of objects of type '%s' is not supported.")
1403
1404 (js2-msg "msg.no.overload"
1405 "Method '%s' occurs multiple times in class '%s'.")
1406
1407 (js2-msg "msg.method.not.found"
1408 "Method '%s' not found in '%s'.")
1409
1410 ;; IRFactory
1411
1412 (js2-msg "msg.bad.for.in.lhs"
1413 "Invalid left-hand side of for..in loop.")
1414
1415 (js2-msg "msg.mult.index"
1416 "Only one variable allowed in for..in loop.")
1417
1418 (js2-msg "msg.bad.for.in.destruct"
1419 "Left hand side of for..in loop must be an array of "
1420 "length 2 to accept key/value pair.")
1421
1422 (js2-msg "msg.cant.convert"
1423 "Can't convert to type '%s'.")
1424
1425 (js2-msg "msg.bad.assign.left"
1426 "Invalid assignment left-hand side.")
1427
1428 (js2-msg "msg.bad.decr"
1429 "Invalid decerement operand.")
1430
1431 (js2-msg "msg.bad.incr"
1432 "Invalid increment operand.")
1433
1434 (js2-msg "msg.bad.yield"
1435 "yield must be in a function.")
1436
1437 (js2-msg "msg.yield.parenthesized"
1438 "yield expression must be parenthesized.")
1439
1440 ;; NativeGlobal
1441 (js2-msg "msg.cant.call.indirect"
1442 "Function '%s' must be called directly, and not by way of a "
1443 "function of another name.")
1444
1445 (js2-msg "msg.eval.nonstring"
1446 "Calling eval() with anything other than a primitive "
1447 "string value will simply return the value. "
1448 "Is this what you intended?")
1449
1450 (js2-msg "msg.eval.nonstring.strict"
1451 "Calling eval() with anything other than a primitive "
1452 "string value is not allowed in strict mode.")
1453
1454 (js2-msg "msg.bad.destruct.op"
1455 "Invalid destructuring assignment operator")
1456
1457 ;; NativeCall
1458 (js2-msg "msg.only.from.new"
1459 "'%s' may only be invoked from a `new' expression.")
1460
1461 (js2-msg "msg.deprec.ctor"
1462 "The '%s' constructor is deprecated.")
1463
1464 ;; NativeFunction
1465 (js2-msg "msg.no.function.ref.found"
1466 "no source found to decompile function reference %s")
1467
1468 (js2-msg "msg.arg.isnt.array"
1469 "second argument to Function.prototype.apply must be an array")
1470
1471 ;; NativeGlobal
1472 (js2-msg "msg.bad.esc.mask"
1473 "invalid string escape mask")
1474
1475 ;; NativeRegExp
1476 (js2-msg "msg.bad.quant"
1477 "Invalid quantifier %s")
1478
1479 (js2-msg "msg.overlarge.backref"
1480 "Overly large back reference %s")
1481
1482 (js2-msg "msg.overlarge.min"
1483 "Overly large minimum %s")
1484
1485 (js2-msg "msg.overlarge.max"
1486 "Overly large maximum %s")
1487
1488 (js2-msg "msg.zero.quant"
1489 "Zero quantifier %s")
1490
1491 (js2-msg "msg.max.lt.min"
1492 "Maximum %s less than minimum")
1493
1494 (js2-msg "msg.unterm.quant"
1495 "Unterminated quantifier %s")
1496
1497 (js2-msg "msg.unterm.paren"
1498 "Unterminated parenthetical %s")
1499
1500 (js2-msg "msg.unterm.class"
1501 "Unterminated character class %s")
1502
1503 (js2-msg "msg.bad.range"
1504 "Invalid range in character class.")
1505
1506 (js2-msg "msg.trail.backslash"
1507 "Trailing \\ in regular expression.")
1508
1509 (js2-msg "msg.re.unmatched.right.paren"
1510 "unmatched ) in regular expression.")
1511
1512 (js2-msg "msg.no.regexp"
1513 "Regular expressions are not available.")
1514
1515 (js2-msg "msg.bad.backref"
1516 "back-reference exceeds number of capturing parentheses.")
1517
1518 (js2-msg "msg.bad.regexp.compile"
1519 "Only one argument may be specified if the first "
1520 "argument to RegExp.prototype.compile is a RegExp object.")
1521
1522 ;; Parser
1523 (js2-msg "msg.got.syntax.errors"
1524 "Compilation produced %s syntax errors.")
1525
1526 (js2-msg "msg.var.redecl"
1527 "TypeError: redeclaration of var %s.")
1528
1529 (js2-msg "msg.const.redecl"
1530 "TypeError: redeclaration of const %s.")
1531
1532 (js2-msg "msg.let.redecl"
1533 "TypeError: redeclaration of variable %s.")
1534
1535 (js2-msg "msg.parm.redecl"
1536 "TypeError: redeclaration of formal parameter %s.")
1537
1538 (js2-msg "msg.fn.redecl"
1539 "TypeError: redeclaration of function %s.")
1540
1541 (js2-msg "msg.let.decl.not.in.block"
1542 "SyntaxError: let declaration not directly within block")
1543
1544 ;; NodeTransformer
1545 (js2-msg "msg.dup.label"
1546 "duplicated label")
1547
1548 (js2-msg "msg.undef.label"
1549 "undefined label")
1550
1551 (js2-msg "msg.bad.break"
1552 "unlabelled break must be inside loop or switch")
1553
1554 (js2-msg "msg.continue.outside"
1555 "continue must be inside loop")
1556
1557 (js2-msg "msg.continue.nonloop"
1558 "continue can only use labels of iteration statements")
1559
1560 (js2-msg "msg.bad.throw.eol"
1561 "Line terminator is not allowed between the throw "
1562 "keyword and throw expression.")
1563
1564 (js2-msg "msg.no.paren.parms"
1565 "missing ( before function parameters.")
1566
1567 (js2-msg "msg.no.parm"
1568 "missing formal parameter")
1569
1570 (js2-msg "msg.no.paren.after.parms"
1571 "missing ) after formal parameters")
1572
1573 (js2-msg "msg.no.brace.body"
1574 "missing '{' before function body")
1575
1576 (js2-msg "msg.no.brace.after.body"
1577 "missing } after function body")
1578
1579 (js2-msg "msg.no.paren.cond"
1580 "missing ( before condition")
1581
1582 (js2-msg "msg.no.paren.after.cond"
1583 "missing ) after condition")
1584
1585 (js2-msg "msg.no.semi.stmt"
1586 "missing ; before statement")
1587
1588 (js2-msg "msg.missing.semi"
1589 "missing ; after statement")
1590
1591 (js2-msg "msg.no.name.after.dot"
1592 "missing name after . operator")
1593
1594 (js2-msg "msg.no.name.after.coloncolon"
1595 "missing name after :: operator")
1596
1597 (js2-msg "msg.no.name.after.dotdot"
1598 "missing name after .. operator")
1599
1600 (js2-msg "msg.no.name.after.xmlAttr"
1601 "missing name after .@")
1602
1603 (js2-msg "msg.no.bracket.index"
1604 "missing ] in index expression")
1605
1606 (js2-msg "msg.no.paren.switch"
1607 "missing ( before switch expression")
1608
1609 (js2-msg "msg.no.paren.after.switch"
1610 "missing ) after switch expression")
1611
1612 (js2-msg "msg.no.brace.switch"
1613 "missing '{' before switch body")
1614
1615 (js2-msg "msg.bad.switch"
1616 "invalid switch statement")
1617
1618 (js2-msg "msg.no.colon.case"
1619 "missing : after case expression")
1620
1621 (js2-msg "msg.double.switch.default"
1622 "double default label in the switch statement")
1623
1624 (js2-msg "msg.no.while.do"
1625 "missing while after do-loop body")
1626
1627 (js2-msg "msg.no.paren.for"
1628 "missing ( after for")
1629
1630 (js2-msg "msg.no.semi.for"
1631 "missing ; after for-loop initializer")
1632
1633 (js2-msg "msg.no.semi.for.cond"
1634 "missing ; after for-loop condition")
1635
1636 (js2-msg "msg.in.after.for.name"
1637 "missing in or of after for")
1638
1639 (js2-msg "msg.no.paren.for.ctrl"
1640 "missing ) after for-loop control")
1641
1642 (js2-msg "msg.no.paren.with"
1643 "missing ( before with-statement object")
1644
1645 (js2-msg "msg.no.paren.after.with"
1646 "missing ) after with-statement object")
1647
1648 (js2-msg "msg.no.paren.after.let"
1649 "missing ( after let")
1650
1651 (js2-msg "msg.no.paren.let"
1652 "missing ) after variable list")
1653
1654 (js2-msg "msg.no.curly.let"
1655 "missing } after let statement")
1656
1657 (js2-msg "msg.bad.return"
1658 "invalid return")
1659
1660 (js2-msg "msg.no.brace.block"
1661 "missing } in compound statement")
1662
1663 (js2-msg "msg.bad.label"
1664 "invalid label")
1665
1666 (js2-msg "msg.bad.var"
1667 "missing variable name")
1668
1669 (js2-msg "msg.bad.var.init"
1670 "invalid variable initialization")
1671
1672 (js2-msg "msg.no.colon.cond"
1673 "missing : in conditional expression")
1674
1675 (js2-msg "msg.no.paren.arg"
1676 "missing ) after argument list")
1677
1678 (js2-msg "msg.no.bracket.arg"
1679 "missing ] after element list")
1680
1681 (js2-msg "msg.bad.prop"
1682 "invalid property id")
1683
1684 (js2-msg "msg.no.colon.prop"
1685 "missing : after property id")
1686
1687 (js2-msg "msg.no.brace.prop"
1688 "missing } after property list")
1689
1690 (js2-msg "msg.no.paren"
1691 "missing ) in parenthetical")
1692
1693 (js2-msg "msg.reserved.id"
1694 "identifier is a reserved word")
1695
1696 (js2-msg "msg.no.paren.catch"
1697 "missing ( before catch-block condition")
1698
1699 (js2-msg "msg.bad.catchcond"
1700 "invalid catch block condition")
1701
1702 (js2-msg "msg.catch.unreachable"
1703 "any catch clauses following an unqualified catch are unreachable")
1704
1705 (js2-msg "msg.no.brace.try"
1706 "missing '{' before try block")
1707
1708 (js2-msg "msg.no.brace.catchblock"
1709 "missing '{' before catch-block body")
1710
1711 (js2-msg "msg.try.no.catchfinally"
1712 "'try' without 'catch' or 'finally'")
1713
1714 (js2-msg "msg.no.return.value"
1715 "function %s does not always return a value")
1716
1717 (js2-msg "msg.anon.no.return.value"
1718 "anonymous function does not always return a value")
1719
1720 (js2-msg "msg.return.inconsistent"
1721 "return statement is inconsistent with previous usage")
1722
1723 (js2-msg "msg.generator.returns"
1724 "TypeError: generator function '%s' returns a value")
1725
1726 (js2-msg "msg.anon.generator.returns"
1727 "TypeError: anonymous generator function returns a value")
1728
1729 (js2-msg "msg.syntax"
1730 "syntax error")
1731
1732 (js2-msg "msg.unexpected.eof"
1733 "Unexpected end of file")
1734
1735 (js2-msg "msg.XML.bad.form"
1736 "illegally formed XML syntax")
1737
1738 (js2-msg "msg.XML.not.available"
1739 "XML runtime not available")
1740
1741 (js2-msg "msg.too.deep.parser.recursion"
1742 "Too deep recursion while parsing")
1743
1744 (js2-msg "msg.no.side.effects"
1745 "Code has no side effects")
1746
1747 (js2-msg "msg.extra.trailing.comma"
1748 "Trailing comma is not legal in an ECMA-262 object initializer")
1749
1750 (js2-msg "msg.array.trailing.comma"
1751 "Trailing comma yields different behavior across browsers")
1752
1753 (js2-msg "msg.equal.as.assign"
1754 (concat "Test for equality (==) mistyped as assignment (=)?"
1755 " (parenthesize to suppress warning)"))
1756
1757 (js2-msg "msg.var.hides.arg"
1758 "Variable %s hides argument")
1759
1760 (js2-msg "msg.destruct.assign.no.init"
1761 "Missing = in destructuring declaration")
1762
1763 ;; ScriptRuntime
1764 (js2-msg "msg.no.properties"
1765 "%s has no properties.")
1766
1767 (js2-msg "msg.invalid.iterator"
1768 "Invalid iterator value")
1769
1770 (js2-msg "msg.iterator.primitive"
1771 "__iterator__ returned a primitive value")
1772
1773 (js2-msg "msg.assn.create.strict"
1774 "Assignment to undeclared variable %s")
1775
1776 (js2-msg "msg.ref.undefined.prop"
1777 "Reference to undefined property '%s'")
1778
1779 (js2-msg "msg.prop.not.found"
1780 "Property %s not found.")
1781
1782 (js2-msg "msg.invalid.type"
1783 "Invalid JavaScript value of type %s")
1784
1785 (js2-msg "msg.primitive.expected"
1786 "Primitive type expected (had %s instead)")
1787
1788 (js2-msg "msg.namespace.expected"
1789 "Namespace object expected to left of :: (found %s instead)")
1790
1791 (js2-msg "msg.null.to.object"
1792 "Cannot convert null to an object.")
1793
1794 (js2-msg "msg.undef.to.object"
1795 "Cannot convert undefined to an object.")
1796
1797 (js2-msg "msg.cyclic.value"
1798 "Cyclic %s value not allowed.")
1799
1800 (js2-msg "msg.is.not.defined"
1801 "'%s' is not defined.")
1802
1803 (js2-msg "msg.undef.prop.read"
1804 "Cannot read property '%s' from %s")
1805
1806 (js2-msg "msg.undef.prop.write"
1807 "Cannot set property '%s' of %s to '%s'")
1808
1809 (js2-msg "msg.undef.prop.delete"
1810 "Cannot delete property '%s' of %s")
1811
1812 (js2-msg "msg.undef.method.call"
1813 "Cannot call method '%s' of %s")
1814
1815 (js2-msg "msg.undef.with"
1816 "Cannot apply 'with' to %s")
1817
1818 (js2-msg "msg.isnt.function"
1819 "%s is not a function, it is %s.")
1820
1821 (js2-msg "msg.isnt.function.in"
1822 "Cannot call property %s in object %s. "
1823 "It is not a function, it is '%s'.")
1824
1825 (js2-msg "msg.function.not.found"
1826 "Cannot find function %s.")
1827
1828 (js2-msg "msg.function.not.found.in"
1829 "Cannot find function %s in object %s.")
1830
1831 (js2-msg "msg.isnt.xml.object"
1832 "%s is not an xml object.")
1833
1834 (js2-msg "msg.no.ref.to.get"
1835 "%s is not a reference to read reference value.")
1836
1837 (js2-msg "msg.no.ref.to.set"
1838 "%s is not a reference to set reference value to %s.")
1839
1840 (js2-msg "msg.no.ref.from.function"
1841 "Function %s can not be used as the left-hand "
1842 "side of assignment or as an operand of ++ or -- operator.")
1843
1844 (js2-msg "msg.bad.default.value"
1845 "Object's getDefaultValue() method returned an object.")
1846
1847 (js2-msg "msg.instanceof.not.object"
1848 "Can't use instanceof on a non-object.")
1849
1850 (js2-msg "msg.instanceof.bad.prototype"
1851 "'prototype' property of %s is not an object.")
1852
1853 (js2-msg "msg.bad.radix"
1854 "illegal radix %s.")
1855
1856 ;; ScriptableObject
1857 (js2-msg "msg.default.value"
1858 "Cannot find default value for object.")
1859
1860 (js2-msg "msg.zero.arg.ctor"
1861 "Cannot load class '%s' which has no zero-parameter constructor.")
1862
1863 (js2-msg "msg.ctor.multiple.parms"
1864 "Can't define constructor or class %s since more than "
1865 "one constructor has multiple parameters.")
1866
1867 (js2-msg "msg.extend.scriptable"
1868 "%s must extend ScriptableObject in order to define property %s.")
1869
1870 (js2-msg "msg.bad.getter.parms"
1871 "In order to define a property, getter %s must have zero "
1872 "parameters or a single ScriptableObject parameter.")
1873
1874 (js2-msg "msg.obj.getter.parms"
1875 "Expected static or delegated getter %s to take "
1876 "a ScriptableObject parameter.")
1877
1878 (js2-msg "msg.getter.static"
1879 "Getter and setter must both be static or neither be static.")
1880
1881 (js2-msg "msg.setter.return"
1882 "Setter must have void return type: %s")
1883
1884 (js2-msg "msg.setter2.parms"
1885 "Two-parameter setter must take a ScriptableObject as "
1886 "its first parameter.")
1887
1888 (js2-msg "msg.setter1.parms"
1889 "Expected single parameter setter for %s")
1890
1891 (js2-msg "msg.setter2.expected"
1892 "Expected static or delegated setter %s to take two parameters.")
1893
1894 (js2-msg "msg.setter.parms"
1895 "Expected either one or two parameters for setter.")
1896
1897 (js2-msg "msg.setter.bad.type"
1898 "Unsupported parameter type '%s' in setter '%s'.")
1899
1900 (js2-msg "msg.add.sealed"
1901 "Cannot add a property to a sealed object: %s.")
1902
1903 (js2-msg "msg.remove.sealed"
1904 "Cannot remove a property from a sealed object: %s.")
1905
1906 (js2-msg "msg.modify.sealed"
1907 "Cannot modify a property of a sealed object: %s.")
1908
1909 (js2-msg "msg.modify.readonly"
1910 "Cannot modify readonly property: %s.")
1911
1912 ;; TokenStream
1913 (js2-msg "msg.missing.exponent"
1914 "missing exponent")
1915
1916 (js2-msg "msg.caught.nfe"
1917 "number format error")
1918
1919 (js2-msg "msg.unterminated.string.lit"
1920 "unterminated string literal")
1921
1922 (js2-msg "msg.unterminated.comment"
1923 "unterminated comment")
1924
1925 (js2-msg "msg.unterminated.re.lit"
1926 "unterminated regular expression literal")
1927
1928 (js2-msg "msg.invalid.re.flag"
1929 "invalid flag after regular expression")
1930
1931 (js2-msg "msg.no.re.input.for"
1932 "no input for %s")
1933
1934 (js2-msg "msg.illegal.character"
1935 "illegal character")
1936
1937 (js2-msg "msg.invalid.escape"
1938 "invalid Unicode escape sequence")
1939
1940 (js2-msg "msg.bad.namespace"
1941 "not a valid default namespace statement. "
1942 "Syntax is: default xml namespace = EXPRESSION;")
1943
1944 ;; TokensStream warnings
1945 (js2-msg "msg.bad.octal.literal"
1946 "illegal octal literal digit %s; "
1947 "interpreting it as a decimal digit")
1948
1949 (js2-msg "msg.reserved.keyword"
1950 "illegal usage of future reserved keyword %s; "
1951 "interpreting it as ordinary identifier")
1952
1953 (js2-msg "msg.script.is.not.constructor"
1954 "Script objects are not constructors.")
1955
1956 ;; Arrays
1957 (js2-msg "msg.arraylength.bad"
1958 "Inappropriate array length.")
1959
1960 ;; Arrays
1961 (js2-msg "msg.arraylength.too.big"
1962 "Array length %s exceeds supported capacity limit.")
1963
1964 ;; URI
1965 (js2-msg "msg.bad.uri"
1966 "Malformed URI sequence.")
1967
1968 ;; Number
1969 (js2-msg "msg.bad.precision"
1970 "Precision %s out of range.")
1971
1972 ;; NativeGenerator
1973 (js2-msg "msg.send.newborn"
1974 "Attempt to send value to newborn generator")
1975
1976 (js2-msg "msg.already.exec.gen"
1977 "Already executing generator")
1978
1979 (js2-msg "msg.StopIteration.invalid"
1980 "StopIteration may not be changed to an arbitrary object.")
1981
1982 ;; Interpreter
1983 (js2-msg "msg.yield.closing"
1984 "Yield from closing generator")
1985
1986 ;;; Utilities
1987
1988 (defun js2-delete-if (predicate list)
1989 "Remove all items satisfying PREDICATE in LIST."
1990 (loop for item in list
1991 if (not (funcall predicate item))
1992 collect item))
1993
1994 (defun js2-position (element list)
1995 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1996 Returns nil if element is not found in the list."
1997 (let ((count 0)
1998 found)
1999 (while (and list (not found))
2000 (if (eq element (car list))
2001 (setq found t)
2002 (setq count (1+ count)
2003 list (cdr list))))
2004 (if found count)))
2005
2006 (defun js2-find-if (predicate list)
2007 "Find first item satisfying PREDICATE in LIST."
2008 (let (result)
2009 (while (and list (not result))
2010 (if (funcall predicate (car list))
2011 (setq result (car list)))
2012 (setq list (cdr list)))
2013 result))
2014
2015 (defmacro js2-time (form)
2016 "Evaluate FORM, discard result, and return elapsed time in sec"
2017 (declare (debug t))
2018 (let ((beg (make-symbol "--js2-time-beg--"))
2019 (delta (make-symbol "--js2-time-end--")))
2020 `(let ((,beg (current-time))
2021 ,delta)
2022 ,form
2023 (/ (truncate (* (- (float-time (current-time))
2024 (float-time ,beg))
2025 10000))
2026 10000.0))))
2027
2028 (defsubst js2-same-line (pos)
2029 "Return t if POS is on the same line as current point."
2030 (and (>= pos (point-at-bol))
2031 (<= pos (point-at-eol))))
2032
2033 (defsubst js2-same-line-2 (p1 p2)
2034 "Return t if p1 is on the same line as p2."
2035 (save-excursion
2036 (goto-char p1)
2037 (js2-same-line p2)))
2038
2039 (defun js2-code-bug ()
2040 "Signal an error when we encounter an unexpected code path."
2041 (error "failed assertion"))
2042
2043 (defsubst js2-record-text-property (beg end prop value)
2044 "Record a text property to set when parsing finishes."
2045 (push (list beg end prop value) js2-mode-deferred-properties))
2046
2047 ;; I'd like to associate errors with nodes, but for now the
2048 ;; easiest thing to do is get the context info from the last token.
2049 (defsubst js2-record-parse-error (msg &optional arg pos len)
2050 (push (list (list msg arg)
2051 (or pos js2-token-beg)
2052 (or len (- js2-token-end js2-token-beg)))
2053 js2-parsed-errors))
2054
2055 (defsubst js2-report-error (msg &optional msg-arg pos len)
2056 "Signal a syntax error or record a parse error."
2057 (if js2-recover-from-parse-errors
2058 (js2-record-parse-error msg msg-arg pos len)
2059 (signal 'js2-syntax-error
2060 (list msg
2061 js2-ts-lineno
2062 (save-excursion
2063 (goto-char js2-ts-cursor)
2064 (current-column))
2065 js2-ts-hit-eof))))
2066
2067 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2068 (if js2-compiler-report-warning-as-error
2069 (js2-report-error msg msg-arg pos len)
2070 (push (list (list msg msg-arg)
2071 (or pos js2-token-beg)
2072 (or len (- js2-token-end js2-token-beg)))
2073 js2-parsed-warnings)))
2074
2075 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2076 (if js2-compiler-strict-mode
2077 (js2-report-warning msg-id msg-arg beg
2078 (and beg end (- end beg)))))
2079
2080 (put 'js2-syntax-error 'error-conditions
2081 '(error syntax-error js2-syntax-error))
2082 (put 'js2-syntax-error 'error-message "Syntax error")
2083
2084 (put 'js2-parse-error 'error-conditions
2085 '(error parse-error js2-parse-error))
2086 (put 'js2-parse-error 'error-message "Parse error")
2087
2088 (defmacro js2-clear-flag (flags flag)
2089 `(setq ,flags (logand ,flags (lognot ,flag))))
2090
2091 (defmacro js2-set-flag (flags flag)
2092 "Logical-or FLAG into FLAGS."
2093 `(setq ,flags (logior ,flags ,flag)))
2094
2095 (defsubst js2-flag-set-p (flags flag)
2096 (/= 0 (logand flags flag)))
2097
2098 (defsubst js2-flag-not-set-p (flags flag)
2099 (zerop (logand flags flag)))
2100
2101 ;; Stolen shamelessly from James Clark's nxml-mode.
2102 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2103 "Evaluate BODY without any text property changes modifying the buffer.
2104 Any text properties changes happen as usual but the changes are not treated as
2105 modifications to the buffer."
2106 (declare (indent 0) (debug t))
2107 (let ((modified (make-symbol "modified")))
2108 `(let ((,modified (buffer-modified-p))
2109 (inhibit-read-only t)
2110 (inhibit-modification-hooks t)
2111 (buffer-undo-list t)
2112 (deactivate-mark nil)
2113 ;; Apparently these avoid file locking problems.
2114 (buffer-file-name nil)
2115 (buffer-file-truename nil))
2116 (unwind-protect
2117 (progn ,@body)
2118 (unless ,modified
2119 (restore-buffer-modified-p nil))))))
2120
2121 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2122 "Evaluate BODY with the _ character set to be word-syntax."
2123 (declare (indent 0) (debug t))
2124 (let ((old-syntax (make-symbol "old-syntax")))
2125 `(let ((,old-syntax (string (char-syntax ?_))))
2126 (unwind-protect
2127 (progn
2128 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2129 ,@body)
2130 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2131
2132 (defsubst js2-char-uppercase-p (c)
2133 "Return t if C is an uppercase character.
2134 Handles unicode and latin chars properly."
2135 (/= c (downcase c)))
2136
2137 (defsubst js2-char-lowercase-p (c)
2138 "Return t if C is an uppercase character.
2139 Handles unicode and latin chars properly."
2140 (/= c (upcase c)))
2141
2142 ;;; AST struct and function definitions
2143
2144 ;; flags for ast node property 'member-type (used for e4x operators)
2145 (defvar js2-property-flag #x1 "property access: element is valid name")
2146 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2147 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2148
2149 (defsubst js2-relpos (pos anchor)
2150 "Convert POS to be relative to ANCHOR.
2151 If POS is nil, returns nil."
2152 (and pos (- pos anchor)))
2153
2154 (defsubst js2-make-pad (indent)
2155 (if (zerop indent)
2156 ""
2157 (make-string (* indent js2-basic-offset) ? )))
2158
2159 (defsubst js2-visit-ast (node callback)
2160 "Visit every node in ast NODE with visitor CALLBACK.
2161
2162 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2163 called twice: once to visit the node, and again after all the node's
2164 children have been processed. The END-P argument is nil on the first
2165 call and non-nil on the second call. The return value of the callback
2166 affects the traversal: if non-nil, the children of NODE are processed.
2167 If the callback returns nil, or if the node has no children, then the
2168 callback is called immediately with a non-nil END-P argument.
2169
2170 The node traversal is approximately lexical-order, although there
2171 are currently no guarantees around this."
2172 (if node
2173 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2174 ;; visit the node
2175 (when (funcall callback node nil)
2176 ;; visit the kids
2177 (cond
2178 ((eq vfunc 'js2-visit-none)
2179 nil) ; don't even bother calling it
2180 ;; Each AST node type has to define a `js2-visitor' function
2181 ;; that takes a node and a callback, and calls `js2-visit-ast'
2182 ;; on each child of the node.
2183 (vfunc
2184 (funcall vfunc node callback))
2185 (t
2186 (error "%s does not define a visitor-traversal function"
2187 (aref node 0)))))
2188 ;; call the end-visit
2189 (funcall callback node t))))
2190
2191 (defstruct (js2-node
2192 (:constructor nil)) ; abstract
2193 "Base AST node type."
2194 (type -1) ; token type
2195 (pos -1) ; start position of this AST node in parsed input
2196 (len 1) ; num characters spanned by the node
2197 props ; optional node property list (an alist)
2198 parent) ; link to parent node; null for root
2199
2200 (defsubst js2-node-get-prop (node prop &optional default)
2201 (or (cadr (assoc prop (js2-node-props node))) default))
2202
2203 (defsubst js2-node-set-prop (node prop value)
2204 (setf (js2-node-props node)
2205 (cons (list prop value) (js2-node-props node))))
2206
2207 (defsubst js2-fixup-starts (n nodes)
2208 "Adjust the start positions of NODES to be relative to N.
2209 Any node in the list may be nil, for convenience."
2210 (dolist (node nodes)
2211 (when node
2212 (setf (js2-node-pos node) (- (js2-node-pos node)
2213 (js2-node-pos n))))))
2214
2215 (defsubst js2-node-add-children (parent &rest nodes)
2216 "Set parent node of NODES to PARENT, and return PARENT.
2217 Does nothing if we're not recording parent links.
2218 If any given node in NODES is nil, doesn't record that link."
2219 (js2-fixup-starts parent nodes)
2220 (dolist (node nodes)
2221 (and node
2222 (setf (js2-node-parent node) parent))))
2223
2224 ;; Non-recursive since it's called a frightening number of times.
2225 (defsubst js2-node-abs-pos (n)
2226 (let ((pos (js2-node-pos n)))
2227 (while (setq n (js2-node-parent n))
2228 (setq pos (+ pos (js2-node-pos n))))
2229 pos))
2230
2231 (defsubst js2-node-abs-end (n)
2232 "Return absolute buffer position of end of N."
2233 (+ (js2-node-abs-pos n) (js2-node-len n)))
2234
2235 ;; It's important to make sure block nodes have a lisp list for the
2236 ;; child nodes, to limit printing recursion depth in an AST that
2237 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2238 ;; a sufficiently large vector tree.
2239
2240 (defstruct (js2-block-node
2241 (:include js2-node)
2242 (:constructor nil)
2243 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2244 (pos js2-token-beg)
2245 len
2246 props
2247 kids)))
2248 "A block of statements."
2249 kids) ; a lisp list of the child statement nodes
2250
2251 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2252 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2253
2254 (defsubst js2-visit-block (ast callback)
2255 "Visit the `js2-block-node' children of AST."
2256 (dolist (kid (js2-block-node-kids ast))
2257 (js2-visit-ast kid callback)))
2258
2259 (defun js2-print-block (n i)
2260 (let ((pad (js2-make-pad i)))
2261 (insert pad "{\n")
2262 (dolist (kid (js2-block-node-kids n))
2263 (js2-print-ast kid (1+ i)))
2264 (insert pad "}")))
2265
2266 (defstruct (js2-scope
2267 (:include js2-block-node)
2268 (:constructor nil)
2269 (:constructor make-js2-scope (&key (type js2-BLOCK)
2270 (pos js2-token-beg)
2271 len
2272 kids)))
2273 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2274 ;; I don't have one of those handy, so I'll use an alist for now.
2275 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2276 ;; and is much lighter-weight to construct (both CPU and mem).
2277 ;; The keys are interned strings (symbols) for faster lookup.
2278 ;; Should switch to hybrid alist/hashtable eventually.
2279 symbol-table ; an alist of (symbol . js2-symbol)
2280 parent-scope ; a `js2-scope'
2281 top) ; top-level `js2-scope' (script/function)
2282
2283 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2284 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2285
2286 (defun js2-scope-set-parent-scope (scope parent)
2287 (setf (js2-scope-parent-scope scope) parent
2288 (js2-scope-top scope) (if (null parent)
2289 scope
2290 (js2-scope-top parent))))
2291
2292 (defun js2-node-get-enclosing-scope (node)
2293 "Return the innermost `js2-scope' node surrounding NODE.
2294 Returns nil if there is no enclosing scope node."
2295 (let ((parent (js2-node-parent node)))
2296 (while (not (js2-scope-p parent))
2297 (setq parent (js2-node-parent parent)))
2298 parent))
2299
2300 (defun js2-get-defining-scope (scope name)
2301 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2302 Returns `js2-scope' in which NAME is defined, or nil if not found."
2303 (let ((sym (if (symbolp name)
2304 name
2305 (intern name)))
2306 table
2307 result
2308 (continue t))
2309 (while (and scope continue)
2310 (if (and (setq table (js2-scope-symbol-table scope))
2311 (assq sym table))
2312 (setq continue nil
2313 result scope)
2314 (setq scope (js2-scope-parent-scope scope))))
2315 result))
2316
2317 (defsubst js2-scope-get-symbol (scope name)
2318 "Return symbol table entry for NAME in SCOPE.
2319 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2320 (and (js2-scope-symbol-table scope)
2321 (cdr (assq (if (symbolp name)
2322 name
2323 (intern name))
2324 (js2-scope-symbol-table scope)))))
2325
2326 (defsubst js2-scope-put-symbol (scope name symbol)
2327 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2328 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2329 (let* ((table (js2-scope-symbol-table scope))
2330 (sym (if (symbolp name) name (intern name)))
2331 (entry (assq sym table)))
2332 (if entry
2333 (setcdr entry symbol)
2334 (push (cons sym symbol)
2335 (js2-scope-symbol-table scope)))))
2336
2337 (defstruct (js2-symbol
2338 (:constructor nil)
2339 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2340 "A symbol table entry."
2341 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2342 ;; js2-LET, or js2-CONST
2343 decl-type
2344 name ; string
2345 ast-node) ; a `js2-node'
2346
2347 (defstruct (js2-error-node
2348 (:include js2-node)
2349 (:constructor nil) ; silence emacs21 byte-compiler
2350 (:constructor make-js2-error-node (&key (type js2-ERROR)
2351 (pos js2-token-beg)
2352 len)))
2353 "AST node representing a parse error.")
2354
2355 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2356 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2357
2358 (defstruct (js2-script-node
2359 (:include js2-scope)
2360 (:constructor nil)
2361 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2362 (pos js2-token-beg)
2363 len
2364 var-decls
2365 fun-decls)))
2366 functions ; lisp list of nested functions
2367 regexps ; lisp list of (string . flags)
2368 symbols ; alist (every symbol gets unique index)
2369 (param-count 0)
2370 var-names ; vector of string names
2371 consts ; bool-vector matching var-decls
2372 (temp-number 0)) ; for generating temp variables
2373
2374 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2375 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2376
2377 (defun js2-print-script (node indent)
2378 (dolist (kid (js2-block-node-kids node))
2379 (js2-print-ast kid indent)))
2380
2381 (defstruct (js2-ast-root
2382 (:include js2-script-node)
2383 (:constructor nil)
2384 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2385 (pos js2-token-beg)
2386 len
2387 buffer)))
2388 "The root node of a js2 AST."
2389 buffer ; the source buffer from which the code was parsed
2390 comments ; a lisp list of comments, ordered by start position
2391 errors ; a lisp list of errors found during parsing
2392 warnings ; a lisp list of warnings found during parsing
2393 node-count) ; number of nodes in the tree, including the root
2394
2395 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2396 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2397
2398 (defun js2-visit-ast-root (ast callback)
2399 (dolist (kid (js2-ast-root-kids ast))
2400 (js2-visit-ast kid callback))
2401 (dolist (comment (js2-ast-root-comments ast))
2402 (js2-visit-ast comment callback)))
2403
2404 (defstruct (js2-comment-node
2405 (:include js2-node)
2406 (:constructor nil)
2407 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2408 (pos js2-token-beg)
2409 len
2410 (format js2-ts-comment-type))))
2411 format) ; 'line, 'block, 'jsdoc or 'html
2412
2413 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2414 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2415
2416 (defun js2-print-comment (n i)
2417 ;; We really ought to link end-of-line comments to their nodes.
2418 ;; Or maybe we could add a new comment type, 'endline.
2419 (insert (js2-make-pad i)
2420 (js2-node-string n)))
2421
2422 (defstruct (js2-expr-stmt-node
2423 (:include js2-node)
2424 (:constructor nil)
2425 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2426 (pos js2-ts-cursor)
2427 len
2428 expr)))
2429 "An expression statement."
2430 expr)
2431
2432 (defsubst js2-expr-stmt-node-set-has-result (node)
2433 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2434 (setf (js2-node-type node) js2-EXPR_RESULT))
2435
2436 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2437 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2438
2439 (defun js2-visit-expr-stmt-node (n v)
2440 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2441
2442 (defun js2-print-expr-stmt-node (n indent)
2443 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2444 (insert ";\n"))
2445
2446 (defstruct (js2-loop-node
2447 (:include js2-scope)
2448 (:constructor nil))
2449 "Abstract supertype of loop nodes."
2450 body ; a `js2-block-node'
2451 lp ; position of left-paren, nil if omitted
2452 rp) ; position of right-paren, nil if omitted
2453
2454 (defstruct (js2-do-node
2455 (:include js2-loop-node)
2456 (:constructor nil)
2457 (:constructor make-js2-do-node (&key (type js2-DO)
2458 (pos js2-token-beg)
2459 len
2460 body
2461 condition
2462 while-pos
2463 lp
2464 rp)))
2465 "AST node for do-loop."
2466 condition ; while (expression)
2467 while-pos) ; buffer position of 'while' keyword
2468
2469 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2470 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2471
2472 (defun js2-visit-do-node (n v)
2473 (js2-visit-ast (js2-do-node-body n) v)
2474 (js2-visit-ast (js2-do-node-condition n) v))
2475
2476 (defun js2-print-do-node (n i)
2477 (let ((pad (js2-make-pad i)))
2478 (insert pad "do {\n")
2479 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2480 (js2-print-ast kid (1+ i)))
2481 (insert pad "} while (")
2482 (js2-print-ast (js2-do-node-condition n) 0)
2483 (insert ");\n")))
2484
2485 (defstruct (js2-while-node
2486 (:include js2-loop-node)
2487 (:constructor nil)
2488 (:constructor make-js2-while-node (&key (type js2-WHILE)
2489 (pos js2-token-beg)
2490 len
2491 body
2492 condition
2493 lp
2494 rp)))
2495 "AST node for while-loop."
2496 condition) ; while-condition
2497
2498 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2499 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2500
2501 (defun js2-visit-while-node (n v)
2502 (js2-visit-ast (js2-while-node-condition n) v)
2503 (js2-visit-ast (js2-while-node-body n) v))
2504
2505 (defun js2-print-while-node (n i)
2506 (let ((pad (js2-make-pad i)))
2507 (insert pad "while (")
2508 (js2-print-ast (js2-while-node-condition n) 0)
2509 (insert ") {\n")
2510 (js2-print-body (js2-while-node-body n) (1+ i))
2511 (insert pad "}\n")))
2512
2513 (defstruct (js2-for-node
2514 (:include js2-loop-node)
2515 (:constructor nil)
2516 (:constructor make-js2-for-node (&key (type js2-FOR)
2517 (pos js2-ts-cursor)
2518 len
2519 body
2520 init
2521 condition
2522 update
2523 lp
2524 rp)))
2525 "AST node for a C-style for-loop."
2526 init ; initialization expression
2527 condition ; loop condition
2528 update) ; update clause
2529
2530 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2531 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2532
2533 (defun js2-visit-for-node (n v)
2534 (js2-visit-ast (js2-for-node-init n) v)
2535 (js2-visit-ast (js2-for-node-condition n) v)
2536 (js2-visit-ast (js2-for-node-update n) v)
2537 (js2-visit-ast (js2-for-node-body n) v))
2538
2539 (defun js2-print-for-node (n i)
2540 (let ((pad (js2-make-pad i)))
2541 (insert pad "for (")
2542 (js2-print-ast (js2-for-node-init n) 0)
2543 (insert "; ")
2544 (js2-print-ast (js2-for-node-condition n) 0)
2545 (insert "; ")
2546 (js2-print-ast (js2-for-node-update n) 0)
2547 (insert ") {\n")
2548 (js2-print-body (js2-for-node-body n) (1+ i))
2549 (insert pad "}\n")))
2550
2551 (defstruct (js2-for-in-node
2552 (:include js2-loop-node)
2553 (:constructor nil)
2554 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2555 (pos js2-ts-cursor)
2556 len
2557 body
2558 iterator
2559 object
2560 in-pos
2561 each-pos
2562 foreach-p
2563 forof-p
2564 lp
2565 rp)))
2566 "AST node for a for..in loop."
2567 iterator ; [var] foo in ...
2568 object ; object over which we're iterating
2569 in-pos ; buffer position of 'in' keyword
2570 each-pos ; buffer position of 'each' keyword, if foreach-p
2571 foreach-p ; t if it's a for-each loop
2572 forof-p) ; t if it's a for-of loop
2573
2574 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2575 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2576
2577 (defun js2-visit-for-in-node (n v)
2578 (js2-visit-ast (js2-for-in-node-iterator n) v)
2579 (js2-visit-ast (js2-for-in-node-object n) v)
2580 (js2-visit-ast (js2-for-in-node-body n) v))
2581
2582 (defun js2-print-for-in-node (n i)
2583 (let ((pad (js2-make-pad i))
2584 (foreach (js2-for-in-node-foreach-p n))
2585 (forof (js2-for-in-node-forof-p n)))
2586 (insert pad "for ")
2587 (if foreach
2588 (insert "each "))
2589 (insert "(")
2590 (js2-print-ast (js2-for-in-node-iterator n) 0)
2591 (if forof
2592 (insert " of ")
2593 (insert " in "))
2594 (js2-print-ast (js2-for-in-node-object n) 0)
2595 (insert ") {\n")
2596 (js2-print-body (js2-for-in-node-body n) (1+ i))
2597 (insert pad "}\n")))
2598
2599 (defstruct (js2-return-node
2600 (:include js2-node)
2601 (:constructor nil)
2602 (:constructor make-js2-return-node (&key (type js2-RETURN)
2603 (pos js2-ts-cursor)
2604 len
2605 retval)))
2606 "AST node for a return statement."
2607 retval) ; expression to return, or 'undefined
2608
2609 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2610 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2611
2612 (defun js2-visit-return-node (n v)
2613 (js2-visit-ast (js2-return-node-retval n) v))
2614
2615 (defun js2-print-return-node (n i)
2616 (insert (js2-make-pad i) "return")
2617 (when (js2-return-node-retval n)
2618 (insert " ")
2619 (js2-print-ast (js2-return-node-retval n) 0))
2620 (insert ";\n"))
2621
2622 (defstruct (js2-if-node
2623 (:include js2-node)
2624 (:constructor nil)
2625 (:constructor make-js2-if-node (&key (type js2-IF)
2626 (pos js2-ts-cursor)
2627 len
2628 condition
2629 then-part
2630 else-pos
2631 else-part
2632 lp
2633 rp)))
2634 "AST node for an if-statement."
2635 condition ; expression
2636 then-part ; statement or block
2637 else-pos ; optional buffer position of 'else' keyword
2638 else-part ; optional statement or block
2639 lp ; position of left-paren, nil if omitted
2640 rp) ; position of right-paren, nil if omitted
2641
2642 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2643 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2644
2645 (defun js2-visit-if-node (n v)
2646 (js2-visit-ast (js2-if-node-condition n) v)
2647 (js2-visit-ast (js2-if-node-then-part n) v)
2648 (js2-visit-ast (js2-if-node-else-part n) v))
2649
2650 (defun js2-print-if-node (n i)
2651 (let ((pad (js2-make-pad i))
2652 (then-part (js2-if-node-then-part n))
2653 (else-part (js2-if-node-else-part n)))
2654 (insert pad "if (")
2655 (js2-print-ast (js2-if-node-condition n) 0)
2656 (insert ") {\n")
2657 (js2-print-body then-part (1+ i))
2658 (insert pad "}")
2659 (cond
2660 ((not else-part)
2661 (insert "\n"))
2662 ((js2-if-node-p else-part)
2663 (insert " else ")
2664 (js2-print-body else-part i))
2665 (t
2666 (insert " else {\n")
2667 (js2-print-body else-part (1+ i))
2668 (insert pad "}\n")))))
2669
2670 (defstruct (js2-try-node
2671 (:include js2-node)
2672 (:constructor nil)
2673 (:constructor make-js2-try-node (&key (type js2-TRY)
2674 (pos js2-ts-cursor)
2675 len
2676 try-block
2677 catch-clauses
2678 finally-block)))
2679 "AST node for a try-statement."
2680 try-block
2681 catch-clauses ; a lisp list of `js2-catch-node'
2682 finally-block) ; a `js2-finally-node'
2683
2684 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2685 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2686
2687 (defun js2-visit-try-node (n v)
2688 (js2-visit-ast (js2-try-node-try-block n) v)
2689 (dolist (clause (js2-try-node-catch-clauses n))
2690 (js2-visit-ast clause v))
2691 (js2-visit-ast (js2-try-node-finally-block n) v))
2692
2693 (defun js2-print-try-node (n i)
2694 (let ((pad (js2-make-pad i))
2695 (catches (js2-try-node-catch-clauses n))
2696 (finally (js2-try-node-finally-block n)))
2697 (insert pad "try {\n")
2698 (js2-print-body (js2-try-node-try-block n) (1+ i))
2699 (insert pad "}")
2700 (when catches
2701 (dolist (catch catches)
2702 (js2-print-ast catch i)))
2703 (if finally
2704 (js2-print-ast finally i)
2705 (insert "\n"))))
2706
2707 (defstruct (js2-catch-node
2708 (:include js2-node)
2709 (:constructor nil)
2710 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2711 (pos js2-ts-cursor)
2712 len
2713 param
2714 guard-kwd
2715 guard-expr
2716 block
2717 lp
2718 rp)))
2719 "AST node for a catch clause."
2720 param ; destructuring form or simple name node
2721 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2722 guard-expr ; catch condition, a `js2-node'
2723 block ; statements, a `js2-block-node'
2724 lp ; buffer position of left-paren, nil if omitted
2725 rp) ; buffer position of right-paren, nil if omitted
2726
2727 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2728 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2729
2730 (defun js2-visit-catch-node (n v)
2731 (js2-visit-ast (js2-catch-node-param n) v)
2732 (when (js2-catch-node-guard-kwd n)
2733 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2734 (js2-visit-ast (js2-catch-node-block n) v))
2735
2736 (defun js2-print-catch-node (n i)
2737 (let ((pad (js2-make-pad i))
2738 (guard-kwd (js2-catch-node-guard-kwd n))
2739 (guard-expr (js2-catch-node-guard-expr n)))
2740 (insert " catch (")
2741 (js2-print-ast (js2-catch-node-param n) 0)
2742 (when guard-kwd
2743 (insert " if ")
2744 (js2-print-ast guard-expr 0))
2745 (insert ") {\n")
2746 (js2-print-body (js2-catch-node-block n) (1+ i))
2747 (insert pad "}")))
2748
2749 (defstruct (js2-finally-node
2750 (:include js2-node)
2751 (:constructor nil)
2752 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2753 (pos js2-ts-cursor)
2754 len
2755 body)))
2756 "AST node for a finally clause."
2757 body) ; a `js2-node', often but not always a block node
2758
2759 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2760 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2761
2762 (defun js2-visit-finally-node (n v)
2763 (js2-visit-ast (js2-finally-node-body n) v))
2764
2765 (defun js2-print-finally-node (n i)
2766 (let ((pad (js2-make-pad i)))
2767 (insert " finally {\n")
2768 (js2-print-body (js2-finally-node-body n) (1+ i))
2769 (insert pad "}\n")))
2770
2771 (defstruct (js2-switch-node
2772 (:include js2-node)
2773 (:constructor nil)
2774 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2775 (pos js2-ts-cursor)
2776 len
2777 discriminant
2778 cases
2779 lp
2780 rp)))
2781 "AST node for a switch statement."
2782 discriminant ; a `js2-node' (switch expression)
2783 cases ; a lisp list of `js2-case-node'
2784 lp ; position of open-paren for discriminant, nil if omitted
2785 rp) ; position of close-paren for discriminant, nil if omitted
2786
2787 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2788 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2789
2790 (defun js2-visit-switch-node (n v)
2791 (js2-visit-ast (js2-switch-node-discriminant n) v)
2792 (dolist (c (js2-switch-node-cases n))
2793 (js2-visit-ast c v)))
2794
2795 (defun js2-print-switch-node (n i)
2796 (let ((pad (js2-make-pad i))
2797 (cases (js2-switch-node-cases n)))
2798 (insert pad "switch (")
2799 (js2-print-ast (js2-switch-node-discriminant n) 0)
2800 (insert ") {\n")
2801 (dolist (case cases)
2802 (js2-print-ast case i))
2803 (insert pad "}\n")))
2804
2805 (defstruct (js2-case-node
2806 (:include js2-block-node)
2807 (:constructor nil)
2808 (:constructor make-js2-case-node (&key (type js2-CASE)
2809 (pos js2-ts-cursor)
2810 len
2811 kids
2812 expr)))
2813 "AST node for a case clause of a switch statement."
2814 expr) ; the case expression (nil for default)
2815
2816 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2817 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2818
2819 (defun js2-visit-case-node (n v)
2820 (js2-visit-ast (js2-case-node-expr n) v)
2821 (js2-visit-block n v))
2822
2823 (defun js2-print-case-node (n i)
2824 (let ((pad (js2-make-pad i))
2825 (expr (js2-case-node-expr n)))
2826 (insert pad)
2827 (if (null expr)
2828 (insert "default:\n")
2829 (insert "case ")
2830 (js2-print-ast expr 0)
2831 (insert ":\n"))
2832 (dolist (kid (js2-case-node-kids n))
2833 (js2-print-ast kid (1+ i)))))
2834
2835 (defstruct (js2-throw-node
2836 (:include js2-node)
2837 (:constructor nil)
2838 (:constructor make-js2-throw-node (&key (type js2-THROW)
2839 (pos js2-ts-cursor)
2840 len
2841 expr)))
2842 "AST node for a throw statement."
2843 expr) ; the expression to throw
2844
2845 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2846 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2847
2848 (defun js2-visit-throw-node (n v)
2849 (js2-visit-ast (js2-throw-node-expr n) v))
2850
2851 (defun js2-print-throw-node (n i)
2852 (insert (js2-make-pad i) "throw ")
2853 (js2-print-ast (js2-throw-node-expr n) 0)
2854 (insert ";\n"))
2855
2856 (defstruct (js2-with-node
2857 (:include js2-node)
2858 (:constructor nil)
2859 (:constructor make-js2-with-node (&key (type js2-WITH)
2860 (pos js2-ts-cursor)
2861 len
2862 object
2863 body
2864 lp
2865 rp)))
2866 "AST node for a with-statement."
2867 object
2868 body
2869 lp ; buffer position of left-paren around object, nil if omitted
2870 rp) ; buffer position of right-paren around object, nil if omitted
2871
2872 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2873 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2874
2875 (defun js2-visit-with-node (n v)
2876 (js2-visit-ast (js2-with-node-object n) v)
2877 (js2-visit-ast (js2-with-node-body n) v))
2878
2879 (defun js2-print-with-node (n i)
2880 (let ((pad (js2-make-pad i)))
2881 (insert pad "with (")
2882 (js2-print-ast (js2-with-node-object n) 0)
2883 (insert ") {\n")
2884 (js2-print-body (js2-with-node-body n) (1+ i))
2885 (insert pad "}\n")))
2886
2887 (defstruct (js2-label-node
2888 (:include js2-node)
2889 (:constructor nil)
2890 (:constructor make-js2-label-node (&key (type js2-LABEL)
2891 (pos js2-ts-cursor)
2892 len
2893 name)))
2894 "AST node for a statement label or case label."
2895 name ; a string
2896 loop) ; for validating and code-generating continue-to-label
2897
2898 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2899 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2900
2901 (defun js2-print-label (n i)
2902 (insert (js2-make-pad i)
2903 (js2-label-node-name n)
2904 ":\n"))
2905
2906 (defstruct (js2-labeled-stmt-node
2907 (:include js2-node)
2908 (:constructor nil)
2909 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2910 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2911 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2912 (pos js2-ts-cursor)
2913 len
2914 labels
2915 stmt)))
2916 "AST node for a statement with one or more labels.
2917 Multiple labels for a statement are collapsed into the labels field."
2918 labels ; lisp list of `js2-label-node'
2919 stmt) ; the statement these labels are for
2920
2921 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2922 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2923
2924 (defun js2-get-label-by-name (lbl-stmt name)
2925 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2926 Returns nil if no such label is in the list."
2927 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2928 result)
2929 (while (and label-list (not result))
2930 (if (string= (js2-label-node-name (car label-list)) name)
2931 (setq result (car label-list))
2932 (setq label-list (cdr label-list))))
2933 result))
2934
2935 (defun js2-visit-labeled-stmt (n v)
2936 (dolist (label (js2-labeled-stmt-node-labels n))
2937 (js2-visit-ast label v))
2938 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2939
2940 (defun js2-print-labeled-stmt (n i)
2941 (dolist (label (js2-labeled-stmt-node-labels n))
2942 (js2-print-ast label i))
2943 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2944
2945 (defun js2-labeled-stmt-node-contains (node label)
2946 "Return t if NODE contains LABEL in its label set.
2947 NODE is a `js2-labels-node'. LABEL is an identifier."
2948 (loop for nl in (js2-labeled-stmt-node-labels node)
2949 if (string= label (js2-label-node-name nl))
2950 return t
2951 finally return nil))
2952
2953 (defsubst js2-labeled-stmt-node-add-label (node label)
2954 "Add a `js2-label-node' to the label set for this statement."
2955 (setf (js2-labeled-stmt-node-labels node)
2956 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2957
2958 (defstruct (js2-jump-node
2959 (:include js2-node)
2960 (:constructor nil))
2961 "Abstract supertype of break and continue nodes."
2962 label ; `js2-name-node' for location of label identifier, if present
2963 target) ; target js2-labels-node or loop/switch statement
2964
2965 (defun js2-visit-jump-node (n v)
2966 (js2-visit-ast (js2-jump-node-label n) v))
2967
2968 (defstruct (js2-break-node
2969 (:include js2-jump-node)
2970 (:constructor nil)
2971 (:constructor make-js2-break-node (&key (type js2-BREAK)
2972 (pos js2-ts-cursor)
2973 len
2974 label
2975 target)))
2976 "AST node for a break statement.
2977 The label field is a `js2-name-node', possibly nil, for the named label
2978 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2979 is the target of the break - a label node or enclosing loop/switch statement.")
2980
2981 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2982 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2983
2984 (defun js2-print-break-node (n i)
2985 (insert (js2-make-pad i) "break")
2986 (when (js2-break-node-label n)
2987 (insert " ")
2988 (js2-print-ast (js2-break-node-label n) 0))
2989 (insert ";\n"))
2990
2991 (defstruct (js2-continue-node
2992 (:include js2-jump-node)
2993 (:constructor nil)
2994 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2995 (pos js2-ts-cursor)
2996 len
2997 label
2998 target)))
2999 "AST node for a continue statement.
3000 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3001 It is nil if continue specifies no label. The target field is the jump target:
3002 a `js2-label-node' or the innermost enclosing loop.")
3003
3004 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3005 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3006
3007 (defun js2-print-continue-node (n i)
3008 (insert (js2-make-pad i) "continue")
3009 (when (js2-continue-node-label n)
3010 (insert " ")
3011 (js2-print-ast (js2-continue-node-label n) 0))
3012 (insert ";\n"))
3013
3014 (defstruct (js2-function-node
3015 (:include js2-script-node)
3016 (:constructor nil)
3017 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3018 (pos js2-ts-cursor)
3019 len
3020 (ftype 'FUNCTION)
3021 (form 'FUNCTION_STATEMENT)
3022 (name "")
3023 params
3024 body
3025 lp
3026 rp)))
3027 "AST node for a function declaration.
3028 The `params' field is a lisp list of nodes. Each node is either a simple
3029 `js2-name-node', or if it's a destructuring-assignment parameter, a
3030 `js2-array-node' or `js2-object-node'."
3031 ftype ; FUNCTION, GETTER or SETTER
3032 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3033 name ; function name (a `js2-name-node', or nil if anonymous)
3034 params ; a lisp list of destructuring forms or simple name nodes
3035 body ; a `js2-block-node' or expression node (1.8 only)
3036 lp ; position of arg-list open-paren, or nil if omitted
3037 rp ; position of arg-list close-paren, or nil if omitted
3038 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3039 needs-activation ; t if we need an activation object for this frame
3040 is-generator ; t if this function contains a yield
3041 member-expr) ; nonstandard Ecma extension from Rhino
3042
3043 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3044 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3045
3046 (defun js2-visit-function-node (n v)
3047 (js2-visit-ast (js2-function-node-name n) v)
3048 (dolist (p (js2-function-node-params n))
3049 (js2-visit-ast p v))
3050 (js2-visit-ast (js2-function-node-body n) v))
3051
3052 (defun js2-print-function-node (n i)
3053 (let ((pad (js2-make-pad i))
3054 (getter (js2-node-get-prop n 'GETTER_SETTER))
3055 (name (js2-function-node-name n))
3056 (params (js2-function-node-params n))
3057 (body (js2-function-node-body n))
3058 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3059 (unless getter
3060 (insert pad "function"))
3061 (when name
3062 (insert " ")
3063 (js2-print-ast name 0))
3064 (insert "(")
3065 (loop with len = (length params)
3066 for param in params
3067 for count from 1
3068 do
3069 (js2-print-ast param 0)
3070 (if (< count len)
3071 (insert ", ")))
3072 (insert ") {")
3073 (unless expr
3074 (insert "\n"))
3075 ;; TODO: fix this to be smarter about indenting, etc.
3076 (js2-print-body body (1+ i))
3077 (insert pad "}")
3078 (unless expr
3079 (insert "\n"))))
3080
3081 (defsubst js2-function-name (node)
3082 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3083 (and (js2-function-node-name node)
3084 (js2-name-node-name (js2-function-node-name node))))
3085
3086 ;; Having this be an expression node makes it more flexible.
3087 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3088 ;; that work better if you assume it's an expression. Whenever we have
3089 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3090 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3091 (defstruct (js2-var-decl-node
3092 (:include js2-node)
3093 (:constructor nil)
3094 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3095 (pos js2-token-beg)
3096 len
3097 kids
3098 decl-type)))
3099 "AST node for a variable declaration list (VAR, CONST or LET).
3100 The node bounds differ depending on the declaration type. For VAR or
3101 CONST declarations, the bounds include the var/const keyword. For LET
3102 declarations, the node begins at the position of the first child."
3103 kids ; a lisp list of `js2-var-init-node' structs.
3104 decl-type) ; js2-VAR, js2-CONST or js2-LET
3105
3106 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3107 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3108
3109 (defun js2-visit-var-decl (n v)
3110 (dolist (kid (js2-var-decl-node-kids n))
3111 (js2-visit-ast kid v)))
3112
3113 (defun js2-print-var-decl (n i)
3114 (let ((pad (js2-make-pad i))
3115 (tt (js2-var-decl-node-decl-type n)))
3116 (insert pad)
3117 (insert (cond
3118 ((= tt js2-VAR) "var ")
3119 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3120 ((= tt js2-CONST) "const ")
3121 (t
3122 (error "malformed var-decl node"))))
3123 (loop with kids = (js2-var-decl-node-kids n)
3124 with len = (length kids)
3125 for kid in kids
3126 for count from 1
3127 do
3128 (js2-print-ast kid 0)
3129 (if (< count len)
3130 (insert ", ")))))
3131
3132 (defstruct (js2-var-init-node
3133 (:include js2-node)
3134 (:constructor nil)
3135 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3136 (pos js2-ts-cursor)
3137 len
3138 target
3139 initializer)))
3140 "AST node for a variable declaration.
3141 The type field will be js2-CONST for a const decl."
3142 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3143 initializer) ; initializer expression, a `js2-node'
3144
3145 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3146 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3147
3148 (defun js2-visit-var-init-node (n v)
3149 (js2-visit-ast (js2-var-init-node-target n) v)
3150 (js2-visit-ast (js2-var-init-node-initializer n) v))
3151
3152 (defun js2-print-var-init-node (n i)
3153 (let ((pad (js2-make-pad i))
3154 (name (js2-var-init-node-target n))
3155 (init (js2-var-init-node-initializer n)))
3156 (insert pad)
3157 (js2-print-ast name 0)
3158 (when init
3159 (insert " = ")
3160 (js2-print-ast init 0))))
3161
3162 (defstruct (js2-cond-node
3163 (:include js2-node)
3164 (:constructor nil)
3165 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3166 (pos js2-ts-cursor)
3167 len
3168 test-expr
3169 true-expr
3170 false-expr
3171 q-pos
3172 c-pos)))
3173 "AST node for the ternary operator"
3174 test-expr
3175 true-expr
3176 false-expr
3177 q-pos ; buffer position of ?
3178 c-pos) ; buffer position of :
3179
3180 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3181 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3182
3183 (defun js2-visit-cond-node (n v)
3184 (js2-visit-ast (js2-cond-node-test-expr n) v)
3185 (js2-visit-ast (js2-cond-node-true-expr n) v)
3186 (js2-visit-ast (js2-cond-node-false-expr n) v))
3187
3188 (defun js2-print-cond-node (n i)
3189 (let ((pad (js2-make-pad i)))
3190 (insert pad)
3191 (js2-print-ast (js2-cond-node-test-expr n) 0)
3192 (insert " ? ")
3193 (js2-print-ast (js2-cond-node-true-expr n) 0)
3194 (insert " : ")
3195 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3196
3197 (defstruct (js2-infix-node
3198 (:include js2-node)
3199 (:constructor nil)
3200 (:constructor make-js2-infix-node (&key type
3201 (pos js2-ts-cursor)
3202 len
3203 op-pos
3204 left
3205 right)))
3206 "Represents infix expressions.
3207 Includes assignment ops like `|=', and the comma operator.
3208 The type field inherited from `js2-node' holds the operator."
3209 op-pos ; buffer position where operator begins
3210 left ; any `js2-node'
3211 right) ; any `js2-node'
3212
3213 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3214 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3215
3216 (defun js2-visit-infix-node (n v)
3217 (js2-visit-ast (js2-infix-node-left n) v)
3218 (js2-visit-ast (js2-infix-node-right n) v))
3219
3220 (defconst js2-operator-tokens
3221 (let ((table (make-hash-table :test 'eq))
3222 (tokens
3223 (list (cons js2-IN "in")
3224 (cons js2-TYPEOF "typeof")
3225 (cons js2-INSTANCEOF "instanceof")
3226 (cons js2-DELPROP "delete")
3227 (cons js2-COMMA ",")
3228 (cons js2-COLON ":")
3229 (cons js2-OR "||")
3230 (cons js2-AND "&&")
3231 (cons js2-INC "++")
3232 (cons js2-DEC "--")
3233 (cons js2-BITOR "|")
3234 (cons js2-BITXOR "^")
3235 (cons js2-BITAND "&")
3236 (cons js2-EQ "==")
3237 (cons js2-NE "!=")
3238 (cons js2-LT "<")
3239 (cons js2-LE "<=")
3240 (cons js2-GT ">")
3241 (cons js2-GE ">=")
3242 (cons js2-LSH "<<")
3243 (cons js2-RSH ">>")
3244 (cons js2-URSH ">>>")
3245 (cons js2-ADD "+") ; infix plus
3246 (cons js2-SUB "-") ; infix minus
3247 (cons js2-MUL "*")
3248 (cons js2-DIV "/")
3249 (cons js2-MOD "%")
3250 (cons js2-NOT "!")
3251 (cons js2-BITNOT "~")
3252 (cons js2-POS "+") ; unary plus
3253 (cons js2-NEG "-") ; unary minus
3254 (cons js2-SHEQ "===") ; shallow equality
3255 (cons js2-SHNE "!==") ; shallow inequality
3256 (cons js2-ASSIGN "=")
3257 (cons js2-ASSIGN_BITOR "|=")
3258 (cons js2-ASSIGN_BITXOR "^=")
3259 (cons js2-ASSIGN_BITAND "&=")
3260 (cons js2-ASSIGN_LSH "<<=")
3261 (cons js2-ASSIGN_RSH ">>=")
3262 (cons js2-ASSIGN_URSH ">>>=")
3263 (cons js2-ASSIGN_ADD "+=")
3264 (cons js2-ASSIGN_SUB "-=")
3265 (cons js2-ASSIGN_MUL "*=")
3266 (cons js2-ASSIGN_DIV "/=")
3267 (cons js2-ASSIGN_MOD "%="))))
3268 (loop for (k . v) in tokens do
3269 (puthash k v table))
3270 table))
3271
3272 (defun js2-print-infix-node (n i)
3273 (let* ((tt (js2-node-type n))
3274 (op (gethash tt js2-operator-tokens)))
3275 (unless op
3276 (error "unrecognized infix operator %s" (js2-node-type n)))
3277 (insert (js2-make-pad i))
3278 (js2-print-ast (js2-infix-node-left n) 0)
3279 (unless (= tt js2-COMMA)
3280 (insert " "))
3281 (insert op)
3282 (insert " ")
3283 (js2-print-ast (js2-infix-node-right n) 0)))
3284
3285 (defstruct (js2-assign-node
3286 (:include js2-infix-node)
3287 (:constructor nil)
3288 (:constructor make-js2-assign-node (&key type
3289 (pos js2-ts-cursor)
3290 len
3291 op-pos
3292 left
3293 right)))
3294 "Represents any assignment.
3295 The type field holds the actual assignment operator.")
3296
3297 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3298 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3299
3300 (defstruct (js2-unary-node
3301 (:include js2-node)
3302 (:constructor nil)
3303 (:constructor make-js2-unary-node (&key type ; required
3304 (pos js2-ts-cursor)
3305 len
3306 operand)))
3307 "AST node type for unary operator nodes.
3308 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3309 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3310 property is added if the operator follows the operand."
3311 operand) ; a `js2-node' expression
3312
3313 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3314 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3315
3316 (defun js2-visit-unary-node (n v)
3317 (js2-visit-ast (js2-unary-node-operand n) v))
3318
3319 (defun js2-print-unary-node (n i)
3320 (let* ((tt (js2-node-type n))
3321 (op (gethash tt js2-operator-tokens))
3322 (postfix (js2-node-get-prop n 'postfix)))
3323 (unless op
3324 (error "unrecognized unary operator %s" tt))
3325 (insert (js2-make-pad i))
3326 (unless postfix
3327 (insert op))
3328 (if (or (= tt js2-TYPEOF)
3329 (= tt js2-DELPROP))
3330 (insert " "))
3331 (js2-print-ast (js2-unary-node-operand n) 0)
3332 (when postfix
3333 (insert op))))
3334
3335 (defstruct (js2-let-node
3336 (:include js2-scope)
3337 (:constructor nil)
3338 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3339 (pos js2-token-beg)
3340 len
3341 vars
3342 body
3343 lp
3344 rp)))
3345 "AST node for a let expression or a let statement.
3346 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3347 vars ; a `js2-var-decl-node'
3348 body ; a `js2-node' representing the expression or body block
3349 lp
3350 rp)
3351
3352 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3353 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3354
3355 (defun js2-visit-let-node (n v)
3356 (js2-visit-ast (js2-let-node-vars n) v)
3357 (js2-visit-ast (js2-let-node-body n) v))
3358
3359 (defun js2-print-let-node (n i)
3360 (insert (js2-make-pad i) "let (")
3361 (js2-print-ast (js2-let-node-vars n) 0)
3362 (insert ") ")
3363 (js2-print-ast (js2-let-node-body n) i))
3364
3365 (defstruct (js2-keyword-node
3366 (:include js2-node)
3367 (:constructor nil)
3368 (:constructor make-js2-keyword-node (&key type
3369 (pos js2-token-beg)
3370 (len (- js2-ts-cursor pos)))))
3371 "AST node representing a literal keyword such as `null'.
3372 Used for `null', `this', `true', `false' and `debugger'.
3373 The node type is set to js2-NULL, js2-THIS, etc.")
3374
3375 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3376 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3377
3378 (defun js2-print-keyword-node (n i)
3379 (insert (js2-make-pad i)
3380 (let ((tt (js2-node-type n)))
3381 (cond
3382 ((= tt js2-THIS) "this")
3383 ((= tt js2-NULL) "null")
3384 ((= tt js2-TRUE) "true")
3385 ((= tt js2-FALSE) "false")
3386 ((= tt js2-DEBUGGER) "debugger")
3387 (t (error "Invalid keyword literal type: %d" tt))))))
3388
3389 (defsubst js2-this-node-p (node)
3390 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3391 (eq (js2-node-type node) js2-THIS))
3392
3393 (defstruct (js2-new-node
3394 (:include js2-node)
3395 (:constructor nil)
3396 (:constructor make-js2-new-node (&key (type js2-NEW)
3397 (pos js2-token-beg)
3398 len
3399 target
3400 args
3401 initializer
3402 lp
3403 rp)))
3404 "AST node for new-expression such as new Foo()."
3405 target ; an identifier or reference
3406 args ; a lisp list of argument nodes
3407 lp ; position of left-paren, nil if omitted
3408 rp ; position of right-paren, nil if omitted
3409 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3410
3411 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3412 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3413
3414 (defun js2-visit-new-node (n v)
3415 (js2-visit-ast (js2-new-node-target n) v)
3416 (dolist (arg (js2-new-node-args n))
3417 (js2-visit-ast arg v))
3418 (js2-visit-ast (js2-new-node-initializer n) v))
3419
3420 (defun js2-print-new-node (n i)
3421 (insert (js2-make-pad i) "new ")
3422 (js2-print-ast (js2-new-node-target n))
3423 (insert "(")
3424 (js2-print-list (js2-new-node-args n))
3425 (insert ")")
3426 (when (js2-new-node-initializer n)
3427 (insert " ")
3428 (js2-print-ast (js2-new-node-initializer n))))
3429
3430 (defstruct (js2-name-node
3431 (:include js2-node)
3432 (:constructor nil)
3433 (:constructor make-js2-name-node (&key (type js2-NAME)
3434 (pos js2-token-beg)
3435 (len (- js2-ts-cursor
3436 js2-token-beg))
3437 (name js2-ts-string))))
3438 "AST node for a JavaScript identifier"
3439 name ; a string
3440 scope) ; a `js2-scope' (optional, used for codegen)
3441
3442 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3443 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3444
3445 (defun js2-print-name-node (n i)
3446 (insert (js2-make-pad i)
3447 (js2-name-node-name n)))
3448
3449 (defsubst js2-name-node-length (node)
3450 "Return identifier length of NODE, a `js2-name-node'.
3451 Returns 0 if NODE is nil or its identifier field is nil."
3452 (if node
3453 (length (js2-name-node-name node))
3454 0))
3455
3456 (defstruct (js2-number-node
3457 (:include js2-node)
3458 (:constructor nil)
3459 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3460 (pos js2-token-beg)
3461 (len (- js2-ts-cursor
3462 js2-token-beg))
3463 (value js2-ts-string)
3464 (num-value js2-ts-number))))
3465 "AST node for a number literal."
3466 value ; the original string, e.g. "6.02e23"
3467 num-value) ; the parsed number value
3468
3469 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3470 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3471
3472 (defun js2-print-number-node (n i)
3473 (insert (js2-make-pad i)
3474 (number-to-string (js2-number-node-num-value n))))
3475
3476 (defstruct (js2-regexp-node
3477 (:include js2-node)
3478 (:constructor nil)
3479 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3480 (pos js2-token-beg)
3481 (len (- js2-ts-cursor
3482 js2-token-beg))
3483 value
3484 flags)))
3485 "AST node for a regular expression literal."
3486 value ; the regexp string, without // delimiters
3487 flags) ; a string of flags, e.g. `mi'.
3488
3489 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3490 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3491
3492 (defun js2-print-regexp (n i)
3493 (insert (js2-make-pad i)
3494 "/"
3495 (js2-regexp-node-value n)
3496 "/")
3497 (if (js2-regexp-node-flags n)
3498 (insert (js2-regexp-node-flags n))))
3499
3500 (defstruct (js2-string-node
3501 (:include js2-node)
3502 (:constructor nil)
3503 (:constructor make-js2-string-node (&key (type js2-STRING)
3504 (pos js2-token-beg)
3505 (len (- js2-ts-cursor
3506 js2-token-beg))
3507 (value js2-ts-string))))
3508 "String literal.
3509 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3510 You can tell the quote type by looking at the first character."
3511 value) ; the characters of the string, including the quotes
3512
3513 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3514 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3515
3516 (defun js2-print-string-node (n i)
3517 (insert (js2-make-pad i)
3518 (js2-node-string n)))
3519
3520 (defstruct (js2-array-node
3521 (:include js2-node)
3522 (:constructor nil)
3523 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3524 (pos js2-ts-cursor)
3525 len
3526 elems)))
3527 "AST node for an array literal."
3528 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3529
3530 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3531 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3532
3533 (defun js2-visit-array-node (n v)
3534 (dolist (e (js2-array-node-elems n))
3535 (js2-visit-ast e v)))
3536
3537 (defun js2-print-array-node (n i)
3538 (insert (js2-make-pad i) "[")
3539 (js2-print-list (js2-array-node-elems n))
3540 (insert "]"))
3541
3542 (defstruct (js2-object-node
3543 (:include js2-node)
3544 (:constructor nil)
3545 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3546 (pos js2-ts-cursor)
3547 len
3548 elems)))
3549 "AST node for an object literal expression.
3550 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3551 the latter represents abbreviation in destructuring expressions."
3552 elems)
3553
3554 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3555 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3556
3557 (defun js2-visit-object-node (n v)
3558 (dolist (e (js2-object-node-elems n))
3559 (js2-visit-ast e v)))
3560
3561 (defun js2-print-object-node (n i)
3562 (insert (js2-make-pad i) "{")
3563 (js2-print-list (js2-object-node-elems n))
3564 (insert "}"))
3565
3566 (defstruct (js2-object-prop-node
3567 (:include js2-infix-node)
3568 (:constructor nil)
3569 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3570 (pos js2-ts-cursor)
3571 len
3572 left
3573 right
3574 op-pos)))
3575 "AST node for an object literal prop:value entry.
3576 The `left' field is the property: a name node, string node or number node.
3577 The `right' field is a `js2-node' representing the initializer value.")
3578
3579 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3580 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3581
3582 (defun js2-print-object-prop-node (n i)
3583 (insert (js2-make-pad i))
3584 (js2-print-ast (js2-object-prop-node-left n) 0)
3585 (insert ":")
3586 (js2-print-ast (js2-object-prop-node-right n) 0))
3587
3588 (defstruct (js2-getter-setter-node
3589 (:include js2-infix-node)
3590 (:constructor nil)
3591 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3592 (pos js2-ts-cursor)
3593 len
3594 left
3595 right)))
3596 "AST node for a getter/setter property in an object literal.
3597 The `left' field is the `js2-name-node' naming the getter/setter prop.
3598 The `right' field is always an anonymous `js2-function-node' with a node
3599 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3600
3601 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3602 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3603
3604 (defun js2-print-getter-setter (n i)
3605 (let ((pad (js2-make-pad i))
3606 (left (js2-getter-setter-node-left n))
3607 (right (js2-getter-setter-node-right n)))
3608 (insert pad)
3609 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3610 (js2-print-ast left 0)
3611 (js2-print-ast right 0)))
3612
3613 (defstruct (js2-prop-get-node
3614 (:include js2-infix-node)
3615 (:constructor nil)
3616 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3617 (pos js2-ts-cursor)
3618 len
3619 left
3620 right)))
3621 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3622
3623 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3624 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3625
3626 (defun js2-visit-prop-get-node (n v)
3627 (js2-visit-ast (js2-prop-get-node-left n) v)
3628 (js2-visit-ast (js2-prop-get-node-right n) v))
3629
3630 (defun js2-print-prop-get-node (n i)
3631 (insert (js2-make-pad i))
3632 (js2-print-ast (js2-prop-get-node-left n) 0)
3633 (insert ".")
3634 (js2-print-ast (js2-prop-get-node-right n) 0))
3635
3636 (defstruct (js2-elem-get-node
3637 (:include js2-node)
3638 (:constructor nil)
3639 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3640 (pos js2-ts-cursor)
3641 len
3642 target
3643 element
3644 lb
3645 rb)))
3646 "AST node for an array index expression such as foo[bar]."
3647 target ; a `js2-node' - the expression preceding the "."
3648 element ; a `js2-node' - the expression in brackets
3649 lb ; position of left-bracket, nil if omitted
3650 rb) ; position of right-bracket, nil if omitted
3651
3652 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3653 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3654
3655 (defun js2-visit-elem-get-node (n v)
3656 (js2-visit-ast (js2-elem-get-node-target n) v)
3657 (js2-visit-ast (js2-elem-get-node-element n) v))
3658
3659 (defun js2-print-elem-get-node (n i)
3660 (insert (js2-make-pad i))
3661 (js2-print-ast (js2-elem-get-node-target n) 0)
3662 (insert "[")
3663 (js2-print-ast (js2-elem-get-node-element n) 0)
3664 (insert "]"))
3665
3666 (defstruct (js2-call-node
3667 (:include js2-node)
3668 (:constructor nil)
3669 (:constructor make-js2-call-node (&key (type js2-CALL)
3670 (pos js2-ts-cursor)
3671 len
3672 target
3673 args
3674 lp
3675 rp)))
3676 "AST node for a JavaScript function call."
3677 target ; a `js2-node' evaluating to the function to call
3678 args ; a lisp list of `js2-node' arguments
3679 lp ; position of open-paren, or nil if missing
3680 rp) ; position of close-paren, or nil if missing
3681
3682 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3683 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3684
3685 (defun js2-visit-call-node (n v)
3686 (js2-visit-ast (js2-call-node-target n) v)
3687 (dolist (arg (js2-call-node-args n))
3688 (js2-visit-ast arg v)))
3689
3690 (defun js2-print-call-node (n i)
3691 (insert (js2-make-pad i))
3692 (js2-print-ast (js2-call-node-target n) 0)
3693 (insert "(")
3694 (js2-print-list (js2-call-node-args n))
3695 (insert ")"))
3696
3697 (defstruct (js2-yield-node
3698 (:include js2-node)
3699 (:constructor nil)
3700 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3701 (pos js2-ts-cursor)
3702 len
3703 value)))
3704 "AST node for yield statement or expression."
3705 value) ; optional: value to be yielded
3706
3707 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3708 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3709
3710 (defun js2-visit-yield-node (n v)
3711 (js2-visit-ast (js2-yield-node-value n) v))
3712
3713 (defun js2-print-yield-node (n i)
3714 (insert (js2-make-pad i))
3715 (insert "yield")
3716 (when (js2-yield-node-value n)
3717 (insert " ")
3718 (js2-print-ast (js2-yield-node-value n) 0)))
3719
3720 (defstruct (js2-paren-node
3721 (:include js2-node)
3722 (:constructor nil)
3723 (:constructor make-js2-paren-node (&key (type js2-LP)
3724 (pos js2-ts-cursor)
3725 len
3726 expr)))
3727 "AST node for a parenthesized expression.
3728 In particular, used when the parens are syntactically optional,
3729 as opposed to required parens such as those enclosing an if-conditional."
3730 expr) ; `js2-node'
3731
3732 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3733 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3734
3735 (defun js2-visit-paren-node (n v)
3736 (js2-visit-ast (js2-paren-node-expr n) v))
3737
3738 (defun js2-print-paren-node (n i)
3739 (insert (js2-make-pad i))
3740 (insert "(")
3741 (js2-print-ast (js2-paren-node-expr n) 0)
3742 (insert ")"))
3743
3744 (defstruct (js2-array-comp-node
3745 (:include js2-scope)
3746 (:constructor nil)
3747 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3748 (pos js2-ts-cursor)
3749 len
3750 result
3751 loops
3752 filter
3753 if-pos
3754 lp
3755 rp)))
3756 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3757 result ; result expression (just after left-bracket)
3758 loops ; a lisp list of `js2-array-comp-loop-node'
3759 filter ; guard/filter expression
3760 if-pos ; buffer pos of 'if' keyword, if present, else nil
3761 lp ; buffer position of if-guard left-paren, or nil if not present
3762 rp) ; buffer position of if-guard right-paren, or nil if not present
3763
3764 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3765 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3766
3767 (defun js2-visit-array-comp-node (n v)
3768 (js2-visit-ast (js2-array-comp-node-result n) v)
3769 (dolist (l (js2-array-comp-node-loops n))
3770 (js2-visit-ast l v))
3771 (js2-visit-ast (js2-array-comp-node-filter n) v))
3772
3773 (defun js2-print-array-comp-node (n i)
3774 (let ((pad (js2-make-pad i))
3775 (result (js2-array-comp-node-result n))
3776 (loops (js2-array-comp-node-loops n))
3777 (filter (js2-array-comp-node-filter n)))
3778 (insert pad "[")
3779 (js2-print-ast result 0)
3780 (dolist (l loops)
3781 (insert " ")
3782 (js2-print-ast l 0))
3783 (when filter
3784 (insert " if (")
3785 (js2-print-ast filter 0)
3786 (insert ")"))
3787 (insert "]")))
3788
3789 (defstruct (js2-array-comp-loop-node
3790 (:include js2-for-in-node)
3791 (:constructor nil)
3792 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3793 (pos js2-ts-cursor)
3794 len
3795 iterator
3796 object
3797 in-pos
3798 foreach-p
3799 each-pos
3800 forof-p
3801 lp
3802 rp)))
3803 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3804
3805 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3806 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3807
3808 (defun js2-visit-array-comp-loop (n v)
3809 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3810 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3811
3812 (defun js2-print-array-comp-loop (n i)
3813 (insert "for (")
3814 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3815 (if (js2-array-comp-loop-node-forof-p n)
3816 (insert " of ")
3817 (insert " in "))
3818 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3819 (insert ")"))
3820
3821 (defstruct (js2-empty-expr-node
3822 (:include js2-node)
3823 (:constructor nil)
3824 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3825 (pos js2-token-beg)
3826 len)))
3827 "AST node for an empty expression.")
3828
3829 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3830 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3831
3832 (defstruct (js2-xml-node
3833 (:include js2-block-node)
3834 (:constructor nil)
3835 (:constructor make-js2-xml-node (&key (type js2-XML)
3836 (pos js2-token-beg)
3837 len
3838 kids)))
3839 "AST node for initial parse of E4X literals.
3840 The kids field is a list of XML fragments, each a `js2-string-node' or
3841 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3842
3843 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3844 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3845
3846 (defun js2-print-xml-node (n i)
3847 (dolist (kid (js2-xml-node-kids n))
3848 (js2-print-ast kid i)))
3849
3850 (defstruct (js2-xml-js-expr-node
3851 (:include js2-xml-node)
3852 (:constructor nil)
3853 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3854 (pos js2-ts-cursor)
3855 len
3856 expr)))
3857 "AST node for an embedded JavaScript {expression} in an E4X literal.
3858 The start and end fields correspond to the curly-braces."
3859 expr) ; a `js2-expr-node' of some sort
3860
3861 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3862 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3863
3864 (defun js2-visit-xml-js-expr (n v)
3865 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3866
3867 (defun js2-print-xml-js-expr (n i)
3868 (insert (js2-make-pad i))
3869 (insert "{")
3870 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3871 (insert "}"))
3872
3873 (defstruct (js2-xml-dot-query-node
3874 (:include js2-infix-node)
3875 (:constructor nil)
3876 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3877 (pos js2-ts-cursor)
3878 op-pos
3879 len
3880 left
3881 right
3882 rp)))
3883 "AST node for an E4X foo.(bar) filter expression.
3884 Note that the left-paren is automatically the character immediately
3885 following the dot (.) in the operator. No whitespace is permitted
3886 between the dot and the lp by the scanner."
3887 rp)
3888
3889 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3890 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3891
3892 (defun js2-print-xml-dot-query (n i)
3893 (insert (js2-make-pad i))
3894 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3895 (insert ".(")
3896 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3897 (insert ")"))
3898
3899 (defstruct (js2-xml-ref-node
3900 (:include js2-node)
3901 (:constructor nil)) ; abstract
3902 "Base type for E4X XML attribute-access or property-get expressions.
3903 Such expressions can take a variety of forms. The general syntax has
3904 three parts:
3905
3906 - (optional) an @ (specifying an attribute access)
3907 - (optional) a namespace (a `js2-name-node') and double-colon
3908 - (required) either a `js2-name-node' or a bracketed [expression]
3909
3910 The property-name expressions (examples: ns::name, @name) are
3911 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3912 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3913
3914 This node type (or more specifically, its subclasses) will sometimes
3915 be the right-hand child of a `js2-prop-get-node' or a
3916 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3917 The `js2-xml-ref-node' may also be a standalone primary expression with
3918 no explicit target, which is valid in certain expression contexts such as
3919
3920 company..employee.(@id < 100)
3921
3922 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3923 expression whose parent is a `js2-xml-dot-query-node'."
3924 namespace
3925 at-pos
3926 colon-pos)
3927
3928 (defsubst js2-xml-ref-node-attr-access-p (node)
3929 "Return non-nil if this expression began with an @-token."
3930 (and (numberp (js2-xml-ref-node-at-pos node))
3931 (plusp (js2-xml-ref-node-at-pos node))))
3932
3933 (defstruct (js2-xml-prop-ref-node
3934 (:include js2-xml-ref-node)
3935 (:constructor nil)
3936 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3937 (pos js2-token-beg)
3938 len
3939 propname
3940 namespace
3941 at-pos
3942 colon-pos)))
3943 "AST node for an E4X XML [expr] property-ref expression.
3944 The JavaScript syntax is an optional @, an optional ns::, and a name.
3945
3946 [ '@' ] [ name '::' ] name
3947
3948 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3949 @ns::*, @*::attr, @*::*, and @*.
3950
3951 The node starts at the @ token, if present. Otherwise it starts at the
3952 namespace name. The node bounds extend through the closing right-bracket,
3953 or if it is missing due to a syntax error, through the end of the index
3954 expression."
3955 propname)
3956
3957 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3958 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3959
3960 (defun js2-visit-xml-prop-ref-node (n v)
3961 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3962 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3963
3964 (defun js2-print-xml-prop-ref-node (n i)
3965 (insert (js2-make-pad i))
3966 (if (js2-xml-ref-node-attr-access-p n)
3967 (insert "@"))
3968 (when (js2-xml-prop-ref-node-namespace n)
3969 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3970 (insert "::"))
3971 (if (js2-xml-prop-ref-node-propname n)
3972 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3973
3974 (defstruct (js2-xml-elem-ref-node
3975 (:include js2-xml-ref-node)
3976 (:constructor nil)
3977 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3978 (pos js2-token-beg)
3979 len
3980 expr
3981 lb
3982 rb
3983 namespace
3984 at-pos
3985 colon-pos)))
3986 "AST node for an E4X XML [expr] member-ref expression.
3987 Syntax:
3988
3989 [ '@' ] [ name '::' ] '[' expr ']'
3990
3991 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3992
3993 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3994 is not a legal E4X XML element-ref expression, since it's already used
3995 for standard JavaScript element-get array indexing. Hence, a
3996 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3997 non-nil namespace node, or both.
3998
3999 The node starts at the @ token, if present. Otherwise it starts
4000 at the namespace name. The node bounds extend through the closing
4001 right-bracket, or if it is missing due to a syntax error, through the
4002 end of the index expression."
4003 expr ; the bracketed index expression
4004 lb
4005 rb)
4006
4007 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4008 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4009
4010 (defun js2-visit-xml-elem-ref-node (n v)
4011 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4012 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4013
4014 (defun js2-print-xml-elem-ref-node (n i)
4015 (insert (js2-make-pad i))
4016 (if (js2-xml-ref-node-attr-access-p n)
4017 (insert "@"))
4018 (when (js2-xml-elem-ref-node-namespace n)
4019 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4020 (insert "::"))
4021 (insert "[")
4022 (if (js2-xml-elem-ref-node-expr n)
4023 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4024 (insert "]"))
4025
4026 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4027
4028 (defstruct (js2-xml-start-tag-node
4029 (:include js2-xml-node)
4030 (:constructor nil)
4031 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4032 (pos js2-ts-cursor)
4033 len
4034 name
4035 attrs
4036 kids
4037 empty-p)))
4038 "AST node for an XML start-tag. Not currently used.
4039 The `kids' field is a lisp list of child content nodes."
4040 name ; a `js2-xml-name-node'
4041 attrs ; a lisp list of `js2-xml-attr-node'
4042 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4043
4044 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4045 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4046
4047 (defun js2-visit-xml-start-tag (n v)
4048 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4049 (dolist (attr (js2-xml-start-tag-node-attrs n))
4050 (js2-visit-ast attr v))
4051 (js2-visit-block n v))
4052
4053 (defun js2-print-xml-start-tag (n i)
4054 (insert (js2-make-pad i) "<")
4055 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4056 (when (js2-xml-start-tag-node-attrs n)
4057 (insert " ")
4058 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4059 (insert ">"))
4060
4061 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4062 ;; and add the end-tag to the kids list of the parent as well.
4063 (defstruct (js2-xml-end-tag-node
4064 (:include js2-xml-node)
4065 (:constructor nil)
4066 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4067 (pos js2-ts-cursor)
4068 len
4069 name)))
4070 "AST node for an XML end-tag. Not currently used."
4071 name) ; a `js2-xml-name-node'
4072
4073 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4074 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4075
4076 (defun js2-visit-xml-end-tag (n v)
4077 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4078
4079 (defun js2-print-xml-end-tag (n i)
4080 (insert (js2-make-pad i))
4081 (insert "</")
4082 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4083 (insert ">"))
4084
4085 (defstruct (js2-xml-name-node
4086 (:include js2-xml-node)
4087 (:constructor nil)
4088 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4089 (pos js2-ts-cursor)
4090 len
4091 namespace
4092 kids)))
4093 "AST node for an E4X XML name. Not currently used.
4094 Any XML name can be qualified with a namespace, hence the namespace field.
4095 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4096 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4097 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4098 namespace) ; a `js2-string-node'
4099
4100 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4101 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4102
4103 (defun js2-visit-xml-name-node (n v)
4104 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4105
4106 (defun js2-print-xml-name-node (n i)
4107 (insert (js2-make-pad i))
4108 (when (js2-xml-name-node-namespace n)
4109 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4110 (insert "::"))
4111 (dolist (kid (js2-xml-name-node-kids n))
4112 (js2-print-ast kid 0)))
4113
4114 (defstruct (js2-xml-pi-node
4115 (:include js2-xml-node)
4116 (:constructor nil)
4117 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4118 (pos js2-ts-cursor)
4119 len
4120 name
4121 attrs)))
4122 "AST node for an E4X XML processing instruction. Not currently used."
4123 name ; a `js2-xml-name-node'
4124 attrs) ; a list of `js2-xml-attr-node'
4125
4126 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4127 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4128
4129 (defun js2-visit-xml-pi-node (n v)
4130 (js2-visit-ast (js2-xml-pi-node-name n) v)
4131 (dolist (attr (js2-xml-pi-node-attrs n))
4132 (js2-visit-ast attr v)))
4133
4134 (defun js2-print-xml-pi-node (n i)
4135 (insert (js2-make-pad i) "<?")
4136 (js2-print-ast (js2-xml-pi-node-name n))
4137 (when (js2-xml-pi-node-attrs n)
4138 (insert " ")
4139 (js2-print-list (js2-xml-pi-node-attrs n)))
4140 (insert "?>"))
4141
4142 (defstruct (js2-xml-cdata-node
4143 (:include js2-xml-node)
4144 (:constructor nil)
4145 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4146 (pos js2-ts-cursor)
4147 len
4148 content)))
4149 "AST node for a CDATA escape section. Not currently used."
4150 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4151
4152 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4153 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4154
4155 (defun js2-visit-xml-cdata-node (n v)
4156 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4157
4158 (defun js2-print-xml-cdata-node (n i)
4159 (insert (js2-make-pad i))
4160 (js2-print-ast (js2-xml-cdata-node-content n)))
4161
4162 (defstruct (js2-xml-attr-node
4163 (:include js2-xml-node)
4164 (:constructor nil)
4165 (:constructor make-js2-attr-node (&key (type js2-XML)
4166 (pos js2-ts-cursor)
4167 len
4168 name
4169 value
4170 eq-pos
4171 quote-type)))
4172 "AST node representing a foo='bar' XML attribute value. Not yet used."
4173 name ; a `js2-xml-name-node'
4174 value ; a `js2-xml-name-node'
4175 eq-pos ; buffer position of "=" sign
4176 quote-type) ; 'single or 'double
4177
4178 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4179 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4180
4181 (defun js2-visit-xml-attr-node (n v)
4182 (js2-visit-ast (js2-xml-attr-node-name n) v)
4183 (js2-visit-ast (js2-xml-attr-node-value n) v))
4184
4185 (defun js2-print-xml-attr-node (n i)
4186 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4187 "'"
4188 "\"")))
4189 (insert (js2-make-pad i))
4190 (js2-print-ast (js2-xml-attr-node-name n) 0)
4191 (insert "=" quote)
4192 (js2-print-ast (js2-xml-attr-node-value n) 0)
4193 (insert quote)))
4194
4195 (defstruct (js2-xml-text-node
4196 (:include js2-xml-node)
4197 (:constructor nil)
4198 (:constructor make-js2-text-node (&key (type js2-XML)
4199 (pos js2-ts-cursor)
4200 len
4201 content)))
4202 "AST node for an E4X XML text node. Not currently used."
4203 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4204
4205 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4206 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4207
4208 (defun js2-visit-xml-text-node (n v)
4209 (js2-visit-ast (js2-xml-text-node-content n) v))
4210
4211 (defun js2-print-xml-text-node (n i)
4212 (insert (js2-make-pad i))
4213 (dolist (kid (js2-xml-text-node-content n))
4214 (js2-print-ast kid)))
4215
4216 (defstruct (js2-xml-comment-node
4217 (:include js2-xml-node)
4218 (:constructor nil)
4219 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4220 (pos js2-ts-cursor)
4221 len)))
4222 "AST node for E4X XML comment. Not currently used.")
4223
4224 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4225 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4226
4227 (defun js2-print-xml-comment (n i)
4228 (insert (js2-make-pad i)
4229 (js2-node-string n)))
4230
4231 ;;; Node utilities
4232
4233 (defsubst js2-node-line (n)
4234 "Fetch the source line number at the start of node N.
4235 This is O(n) in the length of the source buffer; use prudently."
4236 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4237
4238 (defsubst js2-block-node-kid (n i)
4239 "Return child I of node N, or nil if there aren't that many."
4240 (nth i (js2-block-node-kids n)))
4241
4242 (defsubst js2-block-node-first (n)
4243 "Return first child of block node N, or nil if there is none."
4244 (first (js2-block-node-kids n)))
4245
4246 (defun js2-node-root (n)
4247 "Return the root of the AST containing N.
4248 If N has no parent pointer, returns N."
4249 (let ((parent (js2-node-parent n)))
4250 (if parent
4251 (js2-node-root parent)
4252 n)))
4253
4254 (defun js2-node-position-in-parent (node &optional parent)
4255 "Return the position of NODE in parent's block-kids list.
4256 PARENT can be supplied if known. Positioned returned is zero-indexed.
4257 Returns 0 if NODE is not a child of a block statement, or if NODE
4258 is not a statement node."
4259 (let ((p (or parent (js2-node-parent node)))
4260 (i 0))
4261 (if (not (js2-block-node-p p))
4262 i
4263 (or (js2-position node (js2-block-node-kids p))
4264 0))))
4265
4266 (defsubst js2-node-short-name (n)
4267 "Return the short name of node N as a string, e.g. `js2-if-node'."
4268 (substring (symbol-name (aref n 0))
4269 (length "cl-struct-")))
4270
4271 (defsubst js2-node-child-list (node)
4272 "Return the child list for NODE, a lisp list of nodes.
4273 Works for block nodes, array nodes, obj literals, funarg lists,
4274 var decls and try nodes (for catch clauses). Note that you should call
4275 `js2-block-node-kids' on the function body for the body statements.
4276 Returns nil for zero-length child lists or unsupported nodes."
4277 (cond
4278 ((js2-function-node-p node)
4279 (js2-function-node-params node))
4280 ((js2-block-node-p node)
4281 (js2-block-node-kids node))
4282 ((js2-try-node-p node)
4283 (js2-try-node-catch-clauses node))
4284 ((js2-array-node-p node)
4285 (js2-array-node-elems node))
4286 ((js2-object-node-p node)
4287 (js2-object-node-elems node))
4288 ((js2-call-node-p node)
4289 (js2-call-node-args node))
4290 ((js2-new-node-p node)
4291 (js2-new-node-args node))
4292 ((js2-var-decl-node-p node)
4293 (js2-var-decl-node-kids node))
4294 (t
4295 nil)))
4296
4297 (defsubst js2-node-set-child-list (node kids)
4298 "Set the child list for NODE to KIDS."
4299 (cond
4300 ((js2-function-node-p node)
4301 (setf (js2-function-node-params node) kids))
4302 ((js2-block-node-p node)
4303 (setf (js2-block-node-kids node) kids))
4304 ((js2-try-node-p node)
4305 (setf (js2-try-node-catch-clauses node) kids))
4306 ((js2-array-node-p node)
4307 (setf (js2-array-node-elems node) kids))
4308 ((js2-object-node-p node)
4309 (setf (js2-object-node-elems node) kids))
4310 ((js2-call-node-p node)
4311 (setf (js2-call-node-args node) kids))
4312 ((js2-new-node-p node)
4313 (setf (js2-new-node-args node) kids))
4314 ((js2-var-decl-node-p node)
4315 (setf (js2-var-decl-node-kids node) kids))
4316 (t
4317 (error "Unsupported node type: %s" (js2-node-short-name node))))
4318 kids)
4319
4320 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4321 (defconst js2-paren-expr-nodes
4322 '(cl-struct-js2-array-comp-loop-node
4323 cl-struct-js2-array-comp-node
4324 cl-struct-js2-call-node
4325 cl-struct-js2-catch-node
4326 cl-struct-js2-do-node
4327 cl-struct-js2-elem-get-node
4328 cl-struct-js2-for-in-node
4329 cl-struct-js2-for-node
4330 cl-struct-js2-function-node
4331 cl-struct-js2-if-node
4332 cl-struct-js2-let-node
4333 cl-struct-js2-new-node
4334 cl-struct-js2-paren-node
4335 cl-struct-js2-switch-node
4336 cl-struct-js2-while-node
4337 cl-struct-js2-with-node
4338 cl-struct-js2-xml-dot-query-node)
4339 "Node types that can have a parenthesized child expression.
4340 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4341
4342 (defsubst js2-paren-expr-node-p (node)
4343 "Return t for nodes that typically have a parenthesized child expression.
4344 Useful for computing the indentation anchors for arg-lists and conditions.
4345 Note that it may return a false positive, for instance when NODE is
4346 a `js2-new-node' and there are no arguments or parentheses."
4347 (memq (aref node 0) js2-paren-expr-nodes))
4348
4349 ;; Fake polymorphism... yech.
4350 (defsubst js2-node-lp (node)
4351 "Return relative left-paren position for NODE, if applicable.
4352 For `js2-elem-get-node' structs, returns left-bracket position.
4353 Note that the position may be nil in the case of a parse error."
4354 (cond
4355 ((js2-elem-get-node-p node)
4356 (js2-elem-get-node-lb node))
4357 ((js2-loop-node-p node)
4358 (js2-loop-node-lp node))
4359 ((js2-function-node-p node)
4360 (js2-function-node-lp node))
4361 ((js2-if-node-p node)
4362 (js2-if-node-lp node))
4363 ((js2-new-node-p node)
4364 (js2-new-node-lp node))
4365 ((js2-call-node-p node)
4366 (js2-call-node-lp node))
4367 ((js2-paren-node-p node)
4368 (js2-node-pos node))
4369 ((js2-switch-node-p node)
4370 (js2-switch-node-lp node))
4371 ((js2-catch-node-p node)
4372 (js2-catch-node-lp node))
4373 ((js2-let-node-p node)
4374 (js2-let-node-lp node))
4375 ((js2-array-comp-node-p node)
4376 (js2-array-comp-node-lp node))
4377 ((js2-with-node-p node)
4378 (js2-with-node-lp node))
4379 ((js2-xml-dot-query-node-p node)
4380 (1+ (js2-infix-node-op-pos node)))
4381 (t
4382 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4383
4384 ;; Fake polymorphism... blech.
4385 (defsubst js2-node-rp (node)
4386 "Return relative right-paren position for NODE, if applicable.
4387 For `js2-elem-get-node' structs, returns right-bracket position.
4388 Note that the position may be nil in the case of a parse error."
4389 (cond
4390 ((js2-elem-get-node-p node)
4391 (js2-elem-get-node-lb node))
4392 ((js2-loop-node-p node)
4393 (js2-loop-node-rp node))
4394 ((js2-function-node-p node)
4395 (js2-function-node-rp node))
4396 ((js2-if-node-p node)
4397 (js2-if-node-rp node))
4398 ((js2-new-node-p node)
4399 (js2-new-node-rp node))
4400 ((js2-call-node-p node)
4401 (js2-call-node-rp node))
4402 ((js2-paren-node-p node)
4403 (+ (js2-node-pos node) (js2-node-len node)))
4404 ((js2-switch-node-p node)
4405 (js2-switch-node-rp node))
4406 ((js2-catch-node-p node)
4407 (js2-catch-node-rp node))
4408 ((js2-let-node-p node)
4409 (js2-let-node-rp node))
4410 ((js2-array-comp-node-p node)
4411 (js2-array-comp-node-rp node))
4412 ((js2-with-node-p node)
4413 (js2-with-node-rp node))
4414 ((js2-xml-dot-query-node-p node)
4415 (1+ (js2-xml-dot-query-node-rp node)))
4416 (t
4417 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4418
4419 (defsubst js2-node-first-child (node)
4420 "Returns the first element of `js2-node-child-list' for NODE."
4421 (car (js2-node-child-list node)))
4422
4423 (defsubst js2-node-last-child (node)
4424 "Returns the last element of `js2-node-last-child' for NODE."
4425 (car (last (js2-node-child-list node))))
4426
4427 (defun js2-node-prev-sibling (node)
4428 "Return the previous statement in parent.
4429 Works for parents supported by `js2-node-child-list'.
4430 Returns nil if NODE is not in the parent, or PARENT is
4431 not a supported node, or if NODE is the first child."
4432 (let* ((p (js2-node-parent node))
4433 (kids (js2-node-child-list p))
4434 (sib (car kids)))
4435 (while (and kids
4436 (not (eq node (cadr kids))))
4437 (setq kids (cdr kids)
4438 sib (car kids)))
4439 sib))
4440
4441 (defun js2-node-next-sibling (node)
4442 "Return the next statement in parent block.
4443 Returns nil if NODE is not in the block, or PARENT is not
4444 a block node, or if NODE is the last statement."
4445 (let* ((p (js2-node-parent node))
4446 (kids (js2-node-child-list p)))
4447 (while (and kids
4448 (not (eq node (car kids))))
4449 (setq kids (cdr kids)))
4450 (cadr kids)))
4451
4452 (defun js2-node-find-child-before (pos parent &optional after)
4453 "Find the last child that starts before POS in parent.
4454 If AFTER is non-nil, returns first child starting after POS.
4455 POS is an absolute buffer position. PARENT is any node
4456 supported by `js2-node-child-list'.
4457 Returns nil if no applicable child is found."
4458 (let ((kids (if (js2-function-node-p parent)
4459 (js2-block-node-kids (js2-function-node-body parent))
4460 (js2-node-child-list parent)))
4461 (beg (if (js2-function-node-p parent)
4462 (js2-node-abs-pos (js2-function-node-body parent))
4463 (js2-node-abs-pos parent)))
4464 kid
4465 result
4466 fn
4467 (continue t))
4468 (setq fn (if after '>= '<))
4469 (while (and kids continue)
4470 (setq kid (car kids))
4471 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4472 (setq result kid
4473 continue (if after nil t))
4474 (setq continue (if after t nil)))
4475 (setq kids (cdr kids)))
4476 result))
4477
4478 (defun js2-node-find-child-after (pos parent)
4479 "Find first child that starts after POS in parent.
4480 POS is an absolute buffer position. PARENT is any node
4481 supported by `js2-node-child-list'.
4482 Returns nil if no applicable child is found."
4483 (js2-node-find-child-before pos parent 'after))
4484
4485 (defun js2-node-replace-child (pos parent new-node)
4486 "Replace node at index POS in PARENT with NEW-NODE.
4487 Only works for parents supported by `js2-node-child-list'."
4488 (let ((kids (js2-node-child-list parent))
4489 (i 0))
4490 (while (< i pos)
4491 (setq kids (cdr kids)
4492 i (1+ i)))
4493 (setcar kids new-node)
4494 (js2-node-add-children parent new-node)))
4495
4496 (defun js2-node-buffer (n)
4497 "Return the buffer associated with AST N.
4498 Returns nil if the buffer is not set as a property on the root
4499 node, or if parent links were not recorded during parsing."
4500 (let ((root (js2-node-root n)))
4501 (and root
4502 (js2-ast-root-p root)
4503 (js2-ast-root-buffer root))))
4504
4505 (defsubst js2-block-node-push (n kid)
4506 "Push js2-node KID onto the end of js2-block-node N's child list.
4507 KID is always added to the -end- of the kids list.
4508 Function also calls `js2-node-add-children' to add the parent link."
4509 (let ((kids (js2-node-child-list n)))
4510 (if kids
4511 (setcdr kids (nconc (cdr kids) (list kid)))
4512 (js2-node-set-child-list n (list kid)))
4513 (js2-node-add-children n kid)))
4514
4515 (defun js2-node-string (node)
4516 (let ((buf (js2-node-buffer node))
4517 pos)
4518 (unless buf
4519 (error "No buffer available for node %s" node))
4520 (with-current-buffer buf
4521 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4522 (+ pos (js2-node-len node))))))
4523
4524 ;; Container for storing the node we're looking for in a traversal.
4525 (js2-deflocal js2-discovered-node nil)
4526
4527 ;; Keep track of absolute node position during traversals.
4528 (js2-deflocal js2-visitor-offset nil)
4529
4530 (js2-deflocal js2-node-search-point nil)
4531
4532 (when js2-mode-dev-mode-p
4533 (defun js2-find-node-at-point ()
4534 (interactive)
4535 (let ((node (js2-node-at-point)))
4536 (message "%s" (or node "No node found at point"))))
4537 (defun js2-node-name-at-point ()
4538 (interactive)
4539 (let ((node (js2-node-at-point)))
4540 (message "%s" (if node
4541 (js2-node-short-name node)
4542 "No node found at point.")))))
4543
4544 (defun js2-node-at-point (&optional pos skip-comments)
4545 "Return AST node at POS, a buffer position, defaulting to current point.
4546 The `js2-mode-ast' variable must be set to the current parse tree.
4547 Signals an error if the AST (`js2-mode-ast') is nil.
4548 Always returns a node - if it can't find one, it returns the root.
4549 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4550 (let ((ast js2-mode-ast)
4551 result)
4552 (unless ast
4553 (error "No JavaScript AST available"))
4554 ;; Look through comments first, since they may be inside nodes that
4555 ;; would otherwise report a match.
4556 (setq pos (or pos (point))
4557 result (if (> pos (js2-node-abs-end ast))
4558 ast
4559 (if (not skip-comments)
4560 (js2-comment-at-point pos))))
4561 (unless result
4562 (setq js2-discovered-node nil
4563 js2-visitor-offset 0
4564 js2-node-search-point pos)
4565 (unwind-protect
4566 (catch 'js2-visit-done
4567 (js2-visit-ast ast #'js2-node-at-point-visitor))
4568 (setq js2-visitor-offset nil
4569 js2-node-search-point nil))
4570 (setq result js2-discovered-node))
4571 ;; may have found a comment beyond end of last child node,
4572 ;; since visiting the ast-root looks at the comment-list last.
4573 (if (and skip-comments
4574 (js2-comment-node-p result))
4575 (setq result nil))
4576 (or result js2-mode-ast)))
4577
4578 (defun js2-node-at-point-visitor (node end-p)
4579 (let ((rel-pos (js2-node-pos node))
4580 abs-pos
4581 abs-end
4582 (point js2-node-search-point))
4583 (cond
4584 (end-p
4585 ;; this evaluates to a non-nil return value, even if it's zero
4586 (decf js2-visitor-offset rel-pos))
4587 ;; we already looked for comments before visiting, and don't want them now
4588 ((js2-comment-node-p node)
4589 nil)
4590 (t
4591 (setq abs-pos (incf js2-visitor-offset rel-pos)
4592 ;; we only want to use the node if the point is before
4593 ;; the last character position in the node, so we decrement
4594 ;; the absolute end by 1.
4595 abs-end (+ abs-pos (js2-node-len node) -1))
4596 (cond
4597 ;; If this node starts after search-point, stop the search.
4598 ((> abs-pos point)
4599 (throw 'js2-visit-done nil))
4600 ;; If this node ends before the search-point, don't check kids.
4601 ((> point abs-end)
4602 nil)
4603 (t
4604 ;; Otherwise point is within this node, possibly in a child.
4605 (setq js2-discovered-node node)
4606 t)))))) ; keep processing kids to look for more specific match
4607
4608 (defsubst js2-block-comment-p (node)
4609 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4610 (and (js2-comment-node-p node)
4611 (memq (js2-comment-node-format node) '(jsdoc block))))
4612
4613 ;; TODO: put the comments in a vector and binary-search them instead
4614 (defun js2-comment-at-point (&optional pos)
4615 "Look through scanned comment nodes for one containing POS.
4616 POS is a buffer position that defaults to current point.
4617 Function returns nil if POS was not in any comment node."
4618 (let ((ast js2-mode-ast)
4619 (x (or pos (point)))
4620 beg
4621 end)
4622 (unless ast
4623 (error "No JavaScript AST available"))
4624 (catch 'done
4625 ;; Comments are stored in lexical order.
4626 (dolist (comment (js2-ast-root-comments ast) nil)
4627 (setq beg (js2-node-abs-pos comment)
4628 end (+ beg (js2-node-len comment)))
4629 (if (and (>= x beg)
4630 (<= x end))
4631 (throw 'done comment))))))
4632
4633 (defun js2-mode-find-parent-fn (node)
4634 "Find function enclosing NODE.
4635 Returns nil if NODE is not inside a function."
4636 (setq node (js2-node-parent node))
4637 (while (and node (not (js2-function-node-p node)))
4638 (setq node (js2-node-parent node)))
4639 (and (js2-function-node-p node) node))
4640
4641 (defun js2-mode-find-enclosing-fn (node)
4642 "Find function or root enclosing NODE."
4643 (if (js2-ast-root-p node)
4644 node
4645 (setq node (js2-node-parent node))
4646 (while (not (or (js2-ast-root-p node)
4647 (js2-function-node-p node)))
4648 (setq node (js2-node-parent node)))
4649 node))
4650
4651 (defun js2-mode-find-enclosing-node (beg end)
4652 "Find script or function fully enclosing BEG and END."
4653 (let ((node (js2-node-at-point beg))
4654 pos
4655 (continue t))
4656 (while continue
4657 (if (or (js2-ast-root-p node)
4658 (and (js2-function-node-p node)
4659 (<= (setq pos (js2-node-abs-pos node)) beg)
4660 (>= (+ pos (js2-node-len node)) end)))
4661 (setq continue nil)
4662 (setq node (js2-node-parent node))))
4663 node))
4664
4665 (defun js2-node-parent-script-or-fn (node)
4666 "Find script or function immediately enclosing NODE.
4667 If NODE is the ast-root, returns nil."
4668 (if (js2-ast-root-p node)
4669 nil
4670 (setq node (js2-node-parent node))
4671 (while (and node (not (or (js2-function-node-p node)
4672 (js2-script-node-p node))))
4673 (setq node (js2-node-parent node)))
4674 node))
4675
4676 (defsubst js2-nested-function-p (node)
4677 "Return t if NODE is a nested function, or is inside a nested function."
4678 (unless (js2-ast-root-p node)
4679 (js2-function-node-p (if (js2-function-node-p node)
4680 (js2-node-parent-script-or-fn node)
4681 (js2-node-parent-script-or-fn
4682 (js2-node-parent-script-or-fn node))))))
4683
4684 (defsubst js2-function-param-node-p (node)
4685 "Return non-nil if NODE is a param node of a `js2-function-node'."
4686 (let ((parent (js2-node-parent node)))
4687 (and parent
4688 (js2-function-node-p parent)
4689 (memq node (js2-function-node-params parent)))))
4690
4691 (defsubst js2-mode-shift-kids (kids start offset)
4692 (dolist (kid kids)
4693 (if (> (js2-node-pos kid) start)
4694 (incf (js2-node-pos kid) offset))))
4695
4696 (defsubst js2-mode-shift-children (parent start offset)
4697 "Update start-positions of all children of PARENT beyond START."
4698 (let ((root (js2-node-root parent)))
4699 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4700 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4701
4702 (defsubst js2-node-is-descendant (node ancestor)
4703 "Return t if NODE is a descendant of ANCESTOR."
4704 (while (and node
4705 (not (eq node ancestor)))
4706 (setq node (js2-node-parent node)))
4707 node)
4708
4709 ;;; visitor infrastructure
4710
4711 (defun js2-visit-none (node callback)
4712 "Visitor for AST node that have no node children."
4713 nil)
4714
4715 (defun js2-print-none (node indent)
4716 "Visitor for AST node with no printed representation.")
4717
4718 (defun js2-print-body (node indent)
4719 "Print a statement, or a block without braces."
4720 (if (js2-block-node-p node)
4721 (dolist (kid (js2-block-node-kids node))
4722 (js2-print-ast kid indent))
4723 (js2-print-ast node indent)))
4724
4725 (defun js2-print-list (args &optional delimiter)
4726 (loop with len = (length args)
4727 for arg in args
4728 for count from 1
4729 do
4730 (js2-print-ast arg 0)
4731 (if (< count len)
4732 (insert (or delimiter ", ")))))
4733
4734 (defun js2-print-tree (ast)
4735 "Prints an AST to the current buffer.
4736 Makes `js2-ast-parent-nodes' available to the printer functions."
4737 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4738 (js2-print-ast ast)))
4739
4740 (defun js2-print-ast (node &optional indent)
4741 "Helper function for printing AST nodes.
4742 Requires `js2-ast-parent-nodes' to be non-nil.
4743 You should use `js2-print-tree' instead of this function."
4744 (let ((printer (get (aref node 0) 'js2-printer))
4745 (i (or indent 0))
4746 (pos (js2-node-abs-pos node)))
4747 ;; TODO: wedge comments in here somewhere
4748 (if printer
4749 (funcall printer node i))))
4750
4751 (defconst js2-side-effecting-tokens
4752 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4753 (dolist (tt (list js2-ASSIGN
4754 js2-ASSIGN_ADD
4755 js2-ASSIGN_BITAND
4756 js2-ASSIGN_BITOR
4757 js2-ASSIGN_BITXOR
4758 js2-ASSIGN_DIV
4759 js2-ASSIGN_LSH
4760 js2-ASSIGN_MOD
4761 js2-ASSIGN_MUL
4762 js2-ASSIGN_RSH
4763 js2-ASSIGN_SUB
4764 js2-ASSIGN_URSH
4765 js2-BLOCK
4766 js2-BREAK
4767 js2-CALL
4768 js2-CATCH
4769 js2-CATCH_SCOPE
4770 js2-CONST
4771 js2-CONTINUE
4772 js2-DEBUGGER
4773 js2-DEC
4774 js2-DELPROP
4775 js2-DEL_REF
4776 js2-DO
4777 js2-ELSE
4778 js2-EMPTY
4779 js2-ENTERWITH
4780 js2-EXPORT
4781 js2-EXPR_RESULT
4782 js2-FINALLY
4783 js2-FOR
4784 js2-FUNCTION
4785 js2-GOTO
4786 js2-IF
4787 js2-IFEQ
4788 js2-IFNE
4789 js2-IMPORT
4790 js2-INC
4791 js2-JSR
4792 js2-LABEL
4793 js2-LEAVEWITH
4794 js2-LET
4795 js2-LETEXPR
4796 js2-LOCAL_BLOCK
4797 js2-LOOP
4798 js2-NEW
4799 js2-REF_CALL
4800 js2-RETHROW
4801 js2-RETURN
4802 js2-RETURN_RESULT
4803 js2-SEMI
4804 js2-SETELEM
4805 js2-SETELEM_OP
4806 js2-SETNAME
4807 js2-SETPROP
4808 js2-SETPROP_OP
4809 js2-SETVAR
4810 js2-SET_REF
4811 js2-SET_REF_OP
4812 js2-SWITCH
4813 js2-TARGET
4814 js2-THROW
4815 js2-TRY
4816 js2-VAR
4817 js2-WHILE
4818 js2-WITH
4819 js2-WITHEXPR
4820 js2-YIELD))
4821 (aset tokens tt t))
4822 (if js2-instanceof-has-side-effects
4823 (aset tokens js2-INSTANCEOF t))
4824 tokens))
4825
4826 (defun js2-node-has-side-effects (node)
4827 "Return t if NODE has side effects."
4828 (when node ; makes it easier to handle malformed expressions
4829 (let ((tt (js2-node-type node)))
4830 (cond
4831 ;; This doubtless needs some work, since EXPR_VOID is used
4832 ;; in several ways in Rhino, and I may not have caught them all.
4833 ;; I'll wait for people to notice incorrect warnings.
4834 ((and (= tt js2-EXPR_VOID)
4835 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4836 (let ((expr (js2-expr-stmt-node-expr node)))
4837 (or (js2-node-has-side-effects expr)
4838 (when (js2-string-node-p expr)
4839 (string= "use strict" (js2-string-node-value expr))))))
4840 ((= tt js2-COMMA)
4841 (js2-node-has-side-effects (js2-infix-node-right node)))
4842 ((or (= tt js2-AND)
4843 (= tt js2-OR))
4844 (or (js2-node-has-side-effects (js2-infix-node-right node))
4845 (js2-node-has-side-effects (js2-infix-node-left node))))
4846 ((= tt js2-HOOK)
4847 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4848 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4849 ((js2-paren-node-p node)
4850 (js2-node-has-side-effects (js2-paren-node-expr node)))
4851 ((= tt js2-ERROR) ; avoid cascaded error messages
4852 nil)
4853 (t
4854 (aref js2-side-effecting-tokens tt))))))
4855
4856 (defun js2-member-expr-leftmost-name (node)
4857 "For an expr such as foo.bar.baz, return leftmost node foo.
4858 NODE is any `js2-node' object. If it represents a member expression,
4859 which is any sequence of property gets, element-gets, function calls,
4860 or xml descendants/filter operators, then we look at the lexically
4861 leftmost (first) node in the chain. If it is a name-node we return it.
4862 Note that NODE can be a raw name-node and it will be returned as well.
4863 If NODE is not a name-node or member expression, or if it is a member
4864 expression whose leftmost target is not a name node, returns nil."
4865 (let ((continue t)
4866 result)
4867 (while (and continue (not result))
4868 (cond
4869 ((js2-name-node-p node)
4870 (setq result node))
4871 ((js2-prop-get-node-p node)
4872 (setq node (js2-prop-get-node-left node)))
4873 ;; TODO: handle call-nodes, xml-nodes, others?
4874 (t
4875 (setq continue nil))))
4876 result))
4877
4878 (defconst js2-stmt-node-types
4879 (list js2-BLOCK
4880 js2-BREAK
4881 js2-CONTINUE
4882 js2-DEFAULT ; e4x "default xml namespace" statement
4883 js2-DO
4884 js2-EXPR_RESULT
4885 js2-EXPR_VOID
4886 js2-FOR
4887 js2-IF
4888 js2-RETURN
4889 js2-SWITCH
4890 js2-THROW
4891 js2-TRY
4892 js2-WHILE
4893 js2-WITH)
4894 "Node types that only appear in statement contexts.
4895 The list does not include nodes that always appear as the child
4896 of another specific statement type, such as switch-cases,
4897 catch and finally blocks, and else-clauses. The list also excludes
4898 nodes like yield, let and var, which may appear in either expression
4899 or statement context, and in the latter context always have a
4900 `js2-expr-stmt-node' parent. Finally, the list does not include
4901 functions or scripts, which are treated separately from statements
4902 by the JavaScript parser and runtime.")
4903
4904 (defun js2-stmt-node-p (node)
4905 "Heuristic for figuring out if NODE is a statement.
4906 Some node types can appear in either an expression context or a
4907 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4908 For these node types in a statement context, the parent will be a
4909 `js2-expr-stmt-node'.
4910 Functions aren't included in the check."
4911 (memq (js2-node-type node) js2-stmt-node-types))
4912
4913 (defsubst js2-mode-find-first-stmt (node)
4914 "Search upward starting from NODE looking for a statement.
4915 For purposes of this function, a `js2-function-node' counts."
4916 (while (not (or (js2-stmt-node-p node)
4917 (js2-function-node-p node)))
4918 (setq node (js2-node-parent node)))
4919 node)
4920
4921 (defun js2-node-parent-stmt (node)
4922 "Return the node's first ancestor that is a statement.
4923 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4924 appearing in a statement context will have a parent that is a
4925 `js2-expr-stmt-node' that will be returned by this function."
4926 (let ((parent (js2-node-parent node)))
4927 (if (or (null parent)
4928 (js2-stmt-node-p parent)
4929 (and (js2-function-node-p parent)
4930 (not (eq (js2-function-node-form parent)
4931 'FUNCTION_EXPRESSION))))
4932 parent
4933 (js2-node-parent-stmt parent))))
4934
4935 ;; In the Mozilla Rhino sources, Roshan James writes:
4936 ;; Does consistent-return analysis on the function body when strict mode is
4937 ;; enabled.
4938 ;;
4939 ;; function (x) { return (x+1) }
4940 ;;
4941 ;; is ok, but
4942 ;;
4943 ;; function (x) { if (x < 0) return (x+1); }
4944 ;;
4945 ;; is not because the function can potentially return a value when the
4946 ;; condition is satisfied and if not, the function does not explicitly
4947 ;; return a value.
4948 ;;
4949 ;; This extends to checking mismatches such as "return" and "return <value>"
4950 ;; used in the same function. Warnings are not emitted if inconsistent
4951 ;; returns exist in code that can be statically shown to be unreachable.
4952 ;; Ex.
4953 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4954 ;;
4955 ;; emits no warning. However if the loop had a break statement, then a
4956 ;; warning would be emitted.
4957 ;;
4958 ;; The consistency analysis looks at control structures such as loops, ifs,
4959 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4960 ;; warns the user about an inconsistent set of termination possibilities.
4961 ;;
4962 ;; These flags enumerate the possible ways a statement/function can
4963 ;; terminate. These flags are used by endCheck() and by the Parser to
4964 ;; detect inconsistent return usage.
4965 ;;
4966 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4967 ;; able to execute (example: throw, continue)
4968 ;;
4969 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4970 ;; next one. Statement such as return dont. A compound statement may have
4971 ;; some branch that drops off control to the next statement.
4972 ;;
4973 ;; END_RETURNS indicates that the statement can return with no value.
4974 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4975 ;;
4976 ;; A compound statement such as
4977 ;; if (condition) {
4978 ;; return value;
4979 ;; }
4980 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4981
4982 (defconst js2-END_UNREACHED 0)
4983 (defconst js2-END_DROPS_OFF 1)
4984 (defconst js2-END_RETURNS 2)
4985 (defconst js2-END_RETURNS_VALUE 4)
4986 (defconst js2-END_YIELDS 8)
4987
4988 (defun js2-has-consistent-return-usage (node)
4989 "Check that every return usage in a function body is consistent.
4990 Returns t if the function satisfies strict mode requirement."
4991 (let ((n (js2-end-check node)))
4992 ;; either it doesn't return a value in any branch...
4993 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4994 ;; or it returns a value (or is unreached) at every branch
4995 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4996 js2-END_RETURNS
4997 js2-END_YIELDS)))))
4998
4999 (defun js2-end-check-if (node)
5000 "Returns in the then and else blocks must be consistent with each other.
5001 If there is no else block, then the return statement can fall through.
5002 Returns logical OR of END_* flags"
5003 (let ((th (js2-if-node-then-part node))
5004 (el (js2-if-node-else-part node)))
5005 (if (null th)
5006 js2-END_UNREACHED
5007 (logior (js2-end-check th) (if el
5008 (js2-end-check el)
5009 js2-END_DROPS_OFF)))))
5010
5011 (defun js2-end-check-switch (node)
5012 "Consistency of return statements is checked between the case statements.
5013 If there is no default, then the switch can fall through. If there is a
5014 default, we check to see if all code paths in the default return or if
5015 there is a code path that can fall through.
5016 Returns logical OR of END_* flags."
5017 (let ((rv js2-END_UNREACHED)
5018 default-case)
5019 ;; examine the cases
5020 (catch 'break
5021 (dolist (c (js2-switch-node-cases node))
5022 (if (js2-case-node-expr c)
5023 (js2-set-flag rv (js2-end-check-block c))
5024 (setq default-case c)
5025 (throw 'break nil))))
5026 ;; we don't care how the cases drop into each other
5027 (js2-clear-flag rv js2-END_DROPS_OFF)
5028 ;; examine the default
5029 (js2-set-flag rv (if default-case
5030 (js2-end-check default-case)
5031 js2-END_DROPS_OFF))
5032 rv))
5033
5034 (defun js2-end-check-try (node)
5035 "If the block has a finally, return consistency is checked in the
5036 finally block. If all code paths in the finally return, then the
5037 returns in the try-catch blocks don't matter. If there is a code path
5038 that does not return or if there is no finally block, the returns
5039 of the try and catch blocks are checked for mismatch.
5040 Returns logical OR of END_* flags."
5041 (let ((finally (js2-try-node-finally-block node))
5042 rv)
5043 ;; check the finally if it exists
5044 (setq rv (if finally
5045 (js2-end-check (js2-finally-node-body finally))
5046 js2-END_DROPS_OFF))
5047 ;; If the finally block always returns, then none of the returns
5048 ;; in the try or catch blocks matter.
5049 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5050 (js2-clear-flag rv js2-END_DROPS_OFF)
5051 ;; examine the try block
5052 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5053 ;; check each catch block
5054 (dolist (cb (js2-try-node-catch-clauses node))
5055 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5056 rv))
5057
5058 (defun js2-end-check-loop (node)
5059 "Return statement in the loop body must be consistent. The default
5060 assumption for any kind of a loop is that it will eventually terminate.
5061 The only exception is a loop with a constant true condition. Code that
5062 follows such a loop is examined only if one can statically determine
5063 that there is a break out of the loop.
5064
5065 for(... ; ... ; ...) {}
5066 for(... in ... ) {}
5067 while(...) { }
5068 do { } while(...)
5069
5070 Returns logical OR of END_* flags."
5071 (let ((rv (js2-end-check (js2-loop-node-body node)))
5072 (condition (cond
5073 ((js2-while-node-p node)
5074 (js2-while-node-condition node))
5075 ((js2-do-node-p node)
5076 (js2-do-node-condition node))
5077 ((js2-for-node-p node)
5078 (js2-for-node-condition node)))))
5079
5080 ;; check to see if the loop condition is always true
5081 (if (and condition
5082 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5083 (js2-clear-flag rv js2-END_DROPS_OFF))
5084
5085 ;; look for effect of breaks
5086 (js2-set-flag rv (js2-node-get-prop node
5087 'CONTROL_BLOCK_PROP
5088 js2-END_UNREACHED))
5089 rv))
5090
5091 (defun js2-end-check-block (node)
5092 "A general block of code is examined statement by statement.
5093 If any statement (even a compound one) returns in all branches, then
5094 subsequent statements are not examined.
5095 Returns logical OR of END_* flags."
5096 (let* ((rv js2-END_DROPS_OFF)
5097 (kids (js2-block-node-kids node))
5098 (n (car kids)))
5099 ;; Check each statment. If the statement can continue onto the next
5100 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5101 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5102 (js2-clear-flag rv js2-END_DROPS_OFF)
5103 (js2-set-flag rv (js2-end-check n))
5104 (setq kids (cdr kids)
5105 n (car kids)))
5106 rv))
5107
5108 (defun js2-end-check-label (node)
5109 "A labeled statement implies that there may be a break to the label.
5110 The function processes the labeled statement and then checks the
5111 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5112 particular label.
5113 Returns logical OR of END_* flags."
5114 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5115 (logior rv (js2-node-get-prop node
5116 'CONTROL_BLOCK_PROP
5117 js2-END_UNREACHED))))
5118
5119 (defun js2-end-check-break (node)
5120 "When a break is encountered annotate the statement being broken
5121 out of by setting its CONTROL_BLOCK_PROP property.
5122 Returns logical OR of END_* flags."
5123 (and (js2-break-node-target node)
5124 (js2-node-set-prop (js2-break-node-target node)
5125 'CONTROL_BLOCK_PROP
5126 js2-END_DROPS_OFF))
5127 js2-END_UNREACHED)
5128
5129 (defun js2-end-check (node)
5130 "Examine the body of a function, doing a basic reachability analysis.
5131 Returns a combination of flags END_* flags that indicate
5132 how the function execution can terminate. These constitute only the
5133 pessimistic set of termination conditions. It is possible that at
5134 runtime certain code paths will never be actually taken. Hence this
5135 analysis will flag errors in cases where there may not be errors.
5136 Returns logical OR of END_* flags"
5137 (let (kid)
5138 (cond
5139 ((js2-break-node-p node)
5140 (js2-end-check-break node))
5141 ((js2-expr-stmt-node-p node)
5142 (if (setq kid (js2-expr-stmt-node-expr node))
5143 (js2-end-check kid)
5144 js2-END_DROPS_OFF))
5145 ((or (js2-continue-node-p node)
5146 (js2-throw-node-p node))
5147 js2-END_UNREACHED)
5148 ((js2-return-node-p node)
5149 (if (setq kid (js2-return-node-retval node))
5150 js2-END_RETURNS_VALUE
5151 js2-END_RETURNS))
5152 ((js2-loop-node-p node)
5153 (js2-end-check-loop node))
5154 ((js2-switch-node-p node)
5155 (js2-end-check-switch node))
5156 ((js2-labeled-stmt-node-p node)
5157 (js2-end-check-label node))
5158 ((js2-if-node-p node)
5159 (js2-end-check-if node))
5160 ((js2-try-node-p node)
5161 (js2-end-check-try node))
5162 ((js2-block-node-p node)
5163 (if (null (js2-block-node-kids node))
5164 js2-END_DROPS_OFF
5165 (js2-end-check-block node)))
5166 ((js2-yield-node-p node)
5167 js2-END_YIELDS)
5168 (t
5169 js2-END_DROPS_OFF))))
5170
5171 (defun js2-always-defined-boolean-p (node)
5172 "Check if NODE always evaluates to true or false in boolean context.
5173 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5174 nor always false."
5175 (let ((tt (js2-node-type node))
5176 num)
5177 (cond
5178 ((or (= tt js2-FALSE) (= tt js2-NULL))
5179 'ALWAYS_FALSE)
5180 ((= tt js2-TRUE)
5181 'ALWAYS_TRUE)
5182 ((= tt js2-NUMBER)
5183 (setq num (js2-number-node-num-value node))
5184 (if (and (not (eq num 0.0e+NaN))
5185 (not (zerop num)))
5186 'ALWAYS_TRUE
5187 'ALWAYS_FALSE))
5188 (t
5189 nil))))
5190
5191 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5192 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5193
5194 (defvar js2-tokens nil
5195 "List of all defined token names.") ; initialized in `js2-token-names'
5196
5197 (defconst js2-token-names
5198 (let* ((names (make-vector js2-num-tokens -1))
5199 (case-fold-search nil) ; only match js2-UPPER_CASE
5200 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5201 (loop for sym in syms
5202 for i from 0
5203 do
5204 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5205 (not (boundp sym)))
5206 (aset names (symbol-value sym) ; code, e.g. 152
5207 (downcase
5208 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5209 (push sym js2-tokens)))
5210 names)
5211 "Vector mapping int values to token string names, sans `js2-' prefix.")
5212
5213 (defun js2-token-name (tok)
5214 "Return a string name for TOK, a token symbol or code.
5215 Signals an error if it's not a recognized token."
5216 (let ((code tok))
5217 (if (symbolp tok)
5218 (setq code (symbol-value tok)))
5219 (if (eq code -1)
5220 "ERROR"
5221 (if (and (numberp code)
5222 (not (minusp code))
5223 (< code js2-num-tokens))
5224 (aref js2-token-names code)
5225 (error "Invalid token: %s" code)))))
5226
5227 (defsubst js2-token-sym (tok)
5228 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5229 (intern (js2-token-name tok)))
5230
5231 (defconst js2-token-codes
5232 (let ((table (make-hash-table :test 'eq :size 256)))
5233 (loop for name across js2-token-names
5234 for sym = (intern (concat "js2-" (upcase name)))
5235 do
5236 (puthash sym (symbol-value sym) table))
5237 ;; clean up a few that are "wrong" in Rhino's token codes
5238 (puthash 'js2-DELETE js2-DELPROP table)
5239 table)
5240 "Hashtable mapping token symbols to their bytecodes.")
5241
5242 (defsubst js2-token-code (sym)
5243 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5244 (or (gethash sym js2-token-codes)
5245 (error "Invalid token symbol: %s " sym))) ; signal code bug
5246
5247 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5248 (setq js2-token-end js2-ts-cursor)
5249 (js2-report-error msg nil
5250 (or beg js2-token-beg)
5251 (or len (- js2-token-end js2-token-beg)))
5252 (unless no-throw
5253 (throw 'return js2-ERROR)))
5254
5255 (defsubst js2-get-string-from-buffer ()
5256 "Reverse the char accumulator and return it as a string."
5257 (setq js2-token-end js2-ts-cursor)
5258 (if js2-ts-string-buffer
5259 (apply #'string (nreverse js2-ts-string-buffer))
5260 ""))
5261
5262 ;; TODO: could potentially avoid a lot of consing by allocating a
5263 ;; char buffer the way Rhino does.
5264 (defsubst js2-add-to-string (c)
5265 (push c js2-ts-string-buffer))
5266
5267 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5268 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5269 ;; any other character: when it's not part of the current token, we
5270 ;; unget it, allowing it to be read again by the following call.
5271 (defsubst js2-unget-char ()
5272 (decf js2-ts-cursor))
5273
5274 ;; Rhino distinguishes \r and \n line endings. We don't need to
5275 ;; because we only scan from Emacs buffers, which always use \n.
5276 (defsubst js2-get-char ()
5277 "Read and return the next character from the input buffer.
5278 Increments `js2-ts-lineno' if the return value is a newline char.
5279 Updates `js2-ts-cursor' to the point after the returned char.
5280 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5281 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5282 (let (c)
5283 ;; check for end of buffer
5284 (if (>= js2-ts-cursor (point-max))
5285 (setq js2-ts-hit-eof t
5286 js2-ts-cursor (1+ js2-ts-cursor)
5287 c js2-EOF_CHAR) ; return value
5288 ;; otherwise read next char
5289 (setq c (char-before (incf js2-ts-cursor)))
5290 ;; if we read a newline, update counters
5291 (if (= c ?\n)
5292 (setq js2-ts-line-start js2-ts-cursor
5293 js2-ts-lineno (1+ js2-ts-lineno)))
5294 ;; TODO: skip over format characters
5295 c)))
5296
5297 (defsubst js2-read-unicode-escape ()
5298 "Read a \\uNNNN sequence from the input.
5299 Assumes the ?\ and ?u have already been read.
5300 Returns the unicode character, or nil if it wasn't a valid character.
5301 Doesn't change the values of any scanner variables."
5302 ;; I really wish I knew a better way to do this, but I can't
5303 ;; find the Emacs function that takes a 16-bit int and converts
5304 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5305 ;; Have to first check that it's 4 hex characters or it may stop
5306 ;; the read early.
5307 (ignore-errors
5308 (let ((s (buffer-substring-no-properties js2-ts-cursor
5309 (+ 4 js2-ts-cursor))))
5310 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5311 (read (concat "?\\u" s))))))
5312
5313 (defsubst js2-match-char (test)
5314 "Consume and return next character if it matches TEST, a character.
5315 Returns nil and consumes nothing if TEST is not the next character."
5316 (let ((c (js2-get-char)))
5317 (if (eq c test)
5318 t
5319 (js2-unget-char)
5320 nil)))
5321
5322 (defsubst js2-peek-char ()
5323 (prog1
5324 (js2-get-char)
5325 (js2-unget-char)))
5326
5327 (defsubst js2-java-identifier-start-p (c)
5328 (or
5329 (memq c '(?$ ?_))
5330 (js2-char-uppercase-p c)
5331 (js2-char-lowercase-p c)))
5332
5333 (defsubst js2-java-identifier-part-p (c)
5334 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5335 ;; TODO: make me Unicode-friendly. See comments above.
5336 (or
5337 (memq c '(?$ ?_))
5338 (js2-char-uppercase-p c)
5339 (js2-char-lowercase-p c)
5340 (and (>= c ?0) (<= c ?9))))
5341
5342 (defsubst js2-alpha-p (c)
5343 (cond ((and (<= ?A c) (<= c ?Z)) t)
5344 ((and (<= ?a c) (<= c ?z)) t)
5345 (t nil)))
5346
5347 (defsubst js2-digit-p (c)
5348 (and (<= ?0 c) (<= c ?9)))
5349
5350 (defsubst js2-js-space-p (c)
5351 (if (<= c 127)
5352 (memq c '(#x20 #x9 #xB #xC #xD))
5353 (or
5354 (eq c #xA0)
5355 ;; TODO: change this nil to check for Unicode space character
5356 nil)))
5357
5358 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5359
5360 (defsubst js2-skip-line ()
5361 "Skip to end of line"
5362 (let (c)
5363 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5364 (js2-unget-char)
5365 (setq js2-token-end js2-ts-cursor)))
5366
5367 (defun js2-init-scanner (&optional buf line)
5368 "Create token stream for BUF starting on LINE.
5369 BUF defaults to current-buffer and line defaults to 1.
5370
5371 A buffer can only have one scanner active at a time, which yields
5372 dramatically simpler code than using a defstruct. If you need to
5373 have simultaneous scanners in a buffer, copy the regions to scan
5374 into temp buffers."
5375 (save-excursion
5376 (when buf
5377 (set-buffer buf))
5378 (setq js2-ts-dirty-line nil
5379 js2-ts-regexp-flags nil
5380 js2-ts-string ""
5381 js2-ts-number nil
5382 js2-ts-hit-eof nil
5383 js2-ts-line-start 0
5384 js2-ts-lineno (or line 1)
5385 js2-ts-line-end-char -1
5386 js2-ts-cursor (point-min)
5387 js2-ts-is-xml-attribute nil
5388 js2-ts-xml-is-tag-content nil
5389 js2-ts-xml-open-tags-count 0
5390 js2-ts-string-buffer nil)))
5391
5392 ;; This function uses the cached op, string and number fields in
5393 ;; TokenStream; if getToken has been called since the passed token
5394 ;; was scanned, the op or string printed may be incorrect.
5395 (defun js2-token-to-string (token)
5396 ;; Not sure where this function is used in Rhino. Not tested.
5397 (if (not js2-debug-print-trees)
5398 ""
5399 (let ((name (js2-token-name token)))
5400 (cond
5401 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5402 (concat name " `" js2-ts-string "'"))
5403 ((eq token js2-NUMBER)
5404 (format "NUMBER %g" js2-ts-number))
5405 (t
5406 name)))))
5407
5408 (defconst js2-keywords
5409 '(break
5410 case catch const continue
5411 debugger default delete do
5412 else enum
5413 false finally for function
5414 if in instanceof import
5415 let
5416 new null
5417 return
5418 switch
5419 this throw true try typeof
5420 var void
5421 while with
5422 yield))
5423
5424 ;; Token names aren't exactly the same as the keywords, unfortunately.
5425 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5426 (defconst js2-kwd-tokens
5427 (let ((table (make-vector js2-num-tokens nil))
5428 (tokens
5429 (list js2-BREAK
5430 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5431 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5432 js2-ELSE
5433 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5434 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5435 js2-LET
5436 js2-NEW js2-NULL
5437 js2-RETURN
5438 js2-SWITCH
5439 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5440 js2-VAR
5441 js2-WHILE js2-WITH
5442 js2-YIELD)))
5443 (dolist (i tokens)
5444 (aset table i 'font-lock-keyword-face))
5445 (aset table js2-STRING 'font-lock-string-face)
5446 (aset table js2-REGEXP 'font-lock-string-face)
5447 (aset table js2-COMMENT 'font-lock-comment-face)
5448 (aset table js2-THIS 'font-lock-builtin-face)
5449 (aset table js2-VOID 'font-lock-constant-face)
5450 (aset table js2-NULL 'font-lock-constant-face)
5451 (aset table js2-TRUE 'font-lock-constant-face)
5452 (aset table js2-FALSE 'font-lock-constant-face)
5453 table)
5454 "Vector whose values are non-nil for tokens that are keywords.
5455 The values are default faces to use for highlighting the keywords.")
5456
5457 (defconst js2-reserved-words
5458 '(abstract
5459 boolean byte
5460 char class
5461 double
5462 enum export extends
5463 final float
5464 goto
5465 implements import int interface
5466 long
5467 native
5468 package private protected public
5469 short static super synchronized
5470 throws transient
5471 volatile))
5472
5473 (defconst js2-keyword-names
5474 (let ((table (make-hash-table :test 'equal)))
5475 (loop for k in js2-keywords
5476 do (puthash
5477 (symbol-name k) ; instanceof
5478 (intern (concat "js2-"
5479 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5480 table))
5481 table)
5482 "JavaScript keywords by name, mapped to their symbols.")
5483
5484 (defconst js2-reserved-word-names
5485 (let ((table (make-hash-table :test 'equal)))
5486 (loop for k in js2-reserved-words
5487 do
5488 (puthash (symbol-name k) 'js2-RESERVED table))
5489 table)
5490 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5491
5492 (defsubst js2-collect-string (buf)
5493 "Convert BUF, a list of chars, to a string.
5494 Reverses BUF before converting."
5495 (cond
5496 ((stringp buf)
5497 buf)
5498 ((null buf) ; for emacs21 compat
5499 "")
5500 (t
5501 (if buf
5502 (apply #'string (nreverse buf))
5503 ""))))
5504
5505 (defun js2-string-to-keyword (s)
5506 "Return token for S, a string, if S is a keyword or reserved word.
5507 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5508 (or (gethash s js2-keyword-names)
5509 (gethash s js2-reserved-word-names)))
5510
5511 (defsubst js2-ts-set-char-token-bounds ()
5512 "Used when next token is one character."
5513 (setq js2-token-beg (1- js2-ts-cursor)
5514 js2-token-end js2-ts-cursor))
5515
5516 (defsubst js2-ts-return (token)
5517 "Return an N-character TOKEN from `js2-get-token'.
5518 Updates `js2-token-end' accordingly."
5519 (setq js2-token-end js2-ts-cursor)
5520 (throw 'return token))
5521
5522 (defsubst js2-x-digit-to-int (c accumulator)
5523 "Build up a hex number.
5524 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5525 corresponding number. Otherwise return -1."
5526 (catch 'return
5527 (catch 'check
5528 ;; Use 0..9 < A..Z < a..z
5529 (cond
5530 ((<= c ?9)
5531 (decf c ?0)
5532 (if (<= 0 c)
5533 (throw 'check nil)))
5534 ((<= c ?F)
5535 (when (<= ?A c)
5536 (decf c (- ?A 10))
5537 (throw 'check nil)))
5538 ((<= c ?f)
5539 (when (<= ?a c)
5540 (decf c (- ?a 10))
5541 (throw 'check nil))))
5542 (throw 'return -1))
5543 (logior c (lsh accumulator 4))))
5544
5545 (defun js2-get-token ()
5546 "Return next JavaScript token, an int such as js2-RETURN."
5547 (let (c
5548 c1
5549 identifier-start
5550 is-unicode-escape-start
5551 contains-escape
5552 escape-val
5553 escape-start
5554 str
5555 result
5556 base
5557 is-integer
5558 quote-char
5559 val
5560 look-for-slash
5561 continue)
5562 (catch 'return
5563 (while t
5564 ;; Eat whitespace, possibly sensitive to newlines.
5565 (setq continue t)
5566 (while continue
5567 (setq c (js2-get-char))
5568 (cond
5569 ((eq c js2-EOF_CHAR)
5570 (js2-ts-set-char-token-bounds)
5571 (throw 'return js2-EOF))
5572 ((eq c ?\n)
5573 (js2-ts-set-char-token-bounds)
5574 (setq js2-ts-dirty-line nil)
5575 (throw 'return js2-EOL))
5576 ((not (js2-js-space-p c))
5577 (if (/= c ?-) ; in case end of HTML comment
5578 (setq js2-ts-dirty-line t))
5579 (setq continue nil))))
5580 ;; Assume the token will be 1 char - fixed up below.
5581 (js2-ts-set-char-token-bounds)
5582 (when (eq c ?@)
5583 (throw 'return js2-XMLATTR))
5584 ;; identifier/keyword/instanceof?
5585 ;; watch out for starting with a <backslash>
5586 (cond
5587 ((eq c ?\\)
5588 (setq c (js2-get-char))
5589 (if (eq c ?u)
5590 (setq identifier-start t
5591 is-unicode-escape-start t
5592 js2-ts-string-buffer nil)
5593 (setq identifier-start nil)
5594 (js2-unget-char)
5595 (setq c ?\\)))
5596 (t
5597 (when (setq identifier-start (js2-java-identifier-start-p c))
5598 (setq js2-ts-string-buffer nil)
5599 (js2-add-to-string c))))
5600 (when identifier-start
5601 (setq contains-escape is-unicode-escape-start)
5602 (catch 'break
5603 (while t
5604 (if is-unicode-escape-start
5605 ;; strictly speaking we should probably push-back
5606 ;; all the bad characters if the <backslash>uXXXX
5607 ;; sequence is malformed. But since there isn't a
5608 ;; correct context(is there?) for a bad Unicode
5609 ;; escape sequence in an identifier, we can report
5610 ;; an error here.
5611 (progn
5612 (setq escape-val 0)
5613 (dotimes (i 4)
5614 (setq c (js2-get-char)
5615 escape-val (js2-x-digit-to-int c escape-val))
5616 ;; Next check takes care of c < 0 and bad escape
5617 (if (minusp escape-val)
5618 (throw 'break nil)))
5619 (if (minusp escape-val)
5620 (js2-report-scan-error "msg.invalid.escape" t))
5621 (js2-add-to-string escape-val)
5622 (setq is-unicode-escape-start nil))
5623 (setq c (js2-get-char))
5624 (cond
5625 ((eq c ?\\)
5626 (setq c (js2-get-char))
5627 (if (eq c ?u)
5628 (setq is-unicode-escape-start t
5629 contains-escape t)
5630 (js2-report-scan-error "msg.illegal.character" t)))
5631 (t
5632 (if (or (eq c js2-EOF_CHAR)
5633 (not (js2-java-identifier-part-p c)))
5634 (throw 'break nil))
5635 (js2-add-to-string c))))))
5636 (js2-unget-char)
5637 (setq str (js2-get-string-from-buffer))
5638 (unless contains-escape
5639 ;; OPT we shouldn't have to make a string (object!) to
5640 ;; check if it's a keyword.
5641 ;; Return the corresponding token if it's a keyword
5642 (when (setq result (js2-string-to-keyword str))
5643 (if (and (< js2-language-version 170)
5644 (memq result '(js2-LET js2-YIELD)))
5645 ;; LET and YIELD are tokens only in 1.7 and later
5646 (setq result 'js2-NAME))
5647 (if (not (eq result 'js2-RESERVED))
5648 (throw 'return (js2-token-code result)))
5649 (js2-report-warning "msg.reserved.keyword" str)))
5650 ;; If we want to intern these as Rhino does, just use (intern str)
5651 (setq js2-ts-string str)
5652 (throw 'return js2-NAME)) ; end identifier/kwd check
5653 ;; is it a number?
5654 (when (or (js2-digit-p c)
5655 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5656 (setq js2-ts-string-buffer nil
5657 base 10)
5658 (when (eq c ?0)
5659 (setq c (js2-get-char))
5660 (cond
5661 ((or (eq c ?x) (eq c ?X))
5662 (setq base 16)
5663 (setq c (js2-get-char)))
5664 ((js2-digit-p c)
5665 (setq base 8))
5666 (t
5667 (js2-add-to-string ?0))))
5668 (if (eq base 16)
5669 (while (<= 0 (js2-x-digit-to-int c 0))
5670 (js2-add-to-string c)
5671 (setq c (js2-get-char)))
5672 (while (and (<= ?0 c) (<= c ?9))
5673 ;; We permit 08 and 09 as decimal numbers, which
5674 ;; makes our behavior a superset of the ECMA
5675 ;; numeric grammar. We might not always be so
5676 ;; permissive, so we warn about it.
5677 (when (and (eq base 8) (>= c ?8))
5678 (js2-report-warning "msg.bad.octal.literal"
5679 (if (eq c ?8) "8" "9"))
5680 (setq base 10))
5681 (js2-add-to-string c)
5682 (setq c (js2-get-char))))
5683 (setq is-integer t)
5684 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5685 (setq is-integer nil)
5686 (when (eq c ?.)
5687 (loop do
5688 (js2-add-to-string c)
5689 (setq c (js2-get-char))
5690 while (js2-digit-p c)))
5691 (when (memq c '(?e ?E))
5692 (js2-add-to-string c)
5693 (setq c (js2-get-char))
5694 (when (memq c '(?+ ?-))
5695 (js2-add-to-string c)
5696 (setq c (js2-get-char)))
5697 (unless (js2-digit-p c)
5698 (js2-report-scan-error "msg.missing.exponent" t))
5699 (loop do
5700 (js2-add-to-string c)
5701 (setq c (js2-get-char))
5702 while (js2-digit-p c))))
5703 (js2-unget-char)
5704 (setq js2-ts-string (js2-get-string-from-buffer)
5705 js2-ts-number
5706 (if (and (eq base 10) (not is-integer))
5707 (string-to-number js2-ts-string)
5708 ;; TODO: call runtime number-parser. Some of it is in
5709 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5710 (string-to-number js2-ts-string)))
5711 (throw 'return js2-NUMBER))
5712 ;; is it a string?
5713 (when (memq c '(?\" ?\'))
5714 ;; We attempt to accumulate a string the fast way, by
5715 ;; building it directly out of the reader. But if there
5716 ;; are any escaped characters in the string, we revert to
5717 ;; building it out of a string buffer.
5718 (setq quote-char c
5719 js2-ts-string-buffer nil
5720 c (js2-get-char))
5721 (catch 'break
5722 (while (/= c quote-char)
5723 (catch 'continue
5724 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5725 (js2-unget-char)
5726 (setq js2-token-end js2-ts-cursor)
5727 (js2-report-error "msg.unterminated.string.lit")
5728 (throw 'return js2-STRING))
5729 (when (eq c ?\\)
5730 ;; We've hit an escaped character
5731 (setq c (js2-get-char))
5732 (case c
5733 (?b (setq c ?\b))
5734 (?f (setq c ?\f))
5735 (?n (setq c ?\n))
5736 (?r (setq c ?\r))
5737 (?t (setq c ?\t))
5738 (?v (setq c ?\v))
5739 (?u
5740 (setq c1 (js2-read-unicode-escape))
5741 (if js2-parse-ide-mode
5742 (if c1
5743 (progn
5744 ;; just copy the string in IDE-mode
5745 (js2-add-to-string ?\\)
5746 (js2-add-to-string ?u)
5747 (dotimes (i 3)
5748 (js2-add-to-string (js2-get-char)))
5749 (setq c (js2-get-char))) ; added at end of loop
5750 ;; flag it as an invalid escape
5751 (js2-report-warning "msg.invalid.escape"
5752 nil (- js2-ts-cursor 2) 6))
5753 ;; Get 4 hex digits; if the u escape is not
5754 ;; followed by 4 hex digits, use 'u' + the
5755 ;; literal character sequence that follows.
5756 (js2-add-to-string ?u)
5757 (setq escape-val 0)
5758 (dotimes (i 4)
5759 (setq c (js2-get-char)
5760 escape-val (js2-x-digit-to-int c escape-val))
5761 (if (minusp escape-val)
5762 (throw 'continue nil))
5763 (js2-add-to-string c))
5764 ;; prepare for replace of stored 'u' sequence by escape value
5765 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5766 c escape-val)))
5767 (?x
5768 ;; Get 2 hex digits, defaulting to 'x'+literal
5769 ;; sequence, as above.
5770 (setq c (js2-get-char)
5771 escape-val (js2-x-digit-to-int c 0))
5772 (if (minusp escape-val)
5773 (progn
5774 (js2-add-to-string ?x)
5775 (throw 'continue nil))
5776 (setq c1 c
5777 c (js2-get-char)
5778 escape-val (js2-x-digit-to-int c escape-val))
5779 (if (minusp escape-val)
5780 (progn
5781 (js2-add-to-string ?x)
5782 (js2-add-to-string c1)
5783 (throw 'continue nil))
5784 ;; got 2 hex digits
5785 (setq c escape-val))))
5786 (?\n
5787 ;; Remove line terminator after escape to follow
5788 ;; SpiderMonkey and C/C++
5789 (setq c (js2-get-char))
5790 (throw 'continue nil))
5791 (t
5792 (when (and (<= ?0 c) (< c ?8))
5793 (setq val (- c ?0)
5794 c (js2-get-char))
5795 (when (and (<= ?0 c) (< c ?8))
5796 (setq val (- (+ (* 8 val) c) ?0)
5797 c (js2-get-char))
5798 (when (and (<= ?0 c)
5799 (< c ?8)
5800 (< val #o37))
5801 ;; c is 3rd char of octal sequence only
5802 ;; if the resulting val <= 0377
5803 (setq val (- (+ (* 8 val) c) ?0)
5804 c (js2-get-char))))
5805 (js2-unget-char)
5806 (setq c val)))))
5807 (js2-add-to-string c)
5808 (setq c (js2-get-char)))))
5809 (setq js2-ts-string (js2-get-string-from-buffer))
5810 (throw 'return js2-STRING))
5811 (case c
5812 (?\;
5813 (throw 'return js2-SEMI))
5814 (?\[
5815 (throw 'return js2-LB))
5816 (?\]
5817 (throw 'return js2-RB))
5818 (?{
5819 (throw 'return js2-LC))
5820 (?}
5821 (throw 'return js2-RC))
5822 (?\(
5823 (throw 'return js2-LP))
5824 (?\)
5825 (throw 'return js2-RP))
5826 (?,
5827 (throw 'return js2-COMMA))
5828 (??
5829 (throw 'return js2-HOOK))
5830 (?:
5831 (if (js2-match-char ?:)
5832 (js2-ts-return js2-COLONCOLON)
5833 (throw 'return js2-COLON)))
5834 (?.
5835 (if (js2-match-char ?.)
5836 (js2-ts-return js2-DOTDOT)
5837 (if (js2-match-char ?\()
5838 (js2-ts-return js2-DOTQUERY)
5839 (throw 'return js2-DOT))))
5840 (?|
5841 (if (js2-match-char ?|)
5842 (throw 'return js2-OR)
5843 (if (js2-match-char ?=)
5844 (js2-ts-return js2-ASSIGN_BITOR)
5845 (throw 'return js2-BITOR))))
5846 (?^
5847 (if (js2-match-char ?=)
5848 (js2-ts-return js2-ASSIGN_BITOR)
5849 (throw 'return js2-BITXOR)))
5850 (?&
5851 (if (js2-match-char ?&)
5852 (throw 'return js2-AND)
5853 (if (js2-match-char ?=)
5854 (js2-ts-return js2-ASSIGN_BITAND)
5855 (throw 'return js2-BITAND))))
5856 (?=
5857 (if (js2-match-char ?=)
5858 (if (js2-match-char ?=)
5859 (js2-ts-return js2-SHEQ)
5860 (throw 'return js2-EQ))
5861 (throw 'return js2-ASSIGN)))
5862 (?!
5863 (if (js2-match-char ?=)
5864 (if (js2-match-char ?=)
5865 (js2-ts-return js2-SHNE)
5866 (js2-ts-return js2-NE))
5867 (throw 'return js2-NOT)))
5868 (?<
5869 ;; NB:treat HTML begin-comment as comment-till-eol
5870 (when (js2-match-char ?!)
5871 (when (js2-match-char ?-)
5872 (when (js2-match-char ?-)
5873 (js2-skip-line)
5874 (setq js2-ts-comment-type 'html)
5875 (throw 'return js2-COMMENT)))
5876 (js2-unget-char))
5877 (if (js2-match-char ?<)
5878 (if (js2-match-char ?=)
5879 (js2-ts-return js2-ASSIGN_LSH)
5880 (js2-ts-return js2-LSH))
5881 (if (js2-match-char ?=)
5882 (js2-ts-return js2-LE)
5883 (throw 'return js2-LT))))
5884 (?>
5885 (if (js2-match-char ?>)
5886 (if (js2-match-char ?>)
5887 (if (js2-match-char ?=)
5888 (js2-ts-return js2-ASSIGN_URSH)
5889 (js2-ts-return js2-URSH))
5890 (if (js2-match-char ?=)
5891 (js2-ts-return js2-ASSIGN_RSH)
5892 (js2-ts-return js2-RSH)))
5893 (if (js2-match-char ?=)
5894 (js2-ts-return js2-GE)
5895 (throw 'return js2-GT))))
5896 (?*
5897 (if (js2-match-char ?=)
5898 (js2-ts-return js2-ASSIGN_MUL)
5899 (throw 'return js2-MUL)))
5900 (?/
5901 ;; is it a // comment?
5902 (when (js2-match-char ?/)
5903 (setq js2-token-beg (- js2-ts-cursor 2))
5904 (js2-skip-line)
5905 (setq js2-ts-comment-type 'line)
5906 ;; include newline so highlighting goes to end of window
5907 (incf js2-token-end)
5908 (throw 'return js2-COMMENT))
5909 ;; is it a /* comment?
5910 (when (js2-match-char ?*)
5911 (setq look-for-slash nil
5912 js2-token-beg (- js2-ts-cursor 2)
5913 js2-ts-comment-type
5914 (if (js2-match-char ?*)
5915 (progn
5916 (setq look-for-slash t)
5917 'jsdoc)
5918 'block))
5919 (while t
5920 (setq c (js2-get-char))
5921 (cond
5922 ((eq c js2-EOF_CHAR)
5923 (setq js2-token-end (1- js2-ts-cursor))
5924 (js2-report-error "msg.unterminated.comment")
5925 (throw 'return js2-COMMENT))
5926 ((eq c ?*)
5927 (setq look-for-slash t))
5928 ((eq c ?/)
5929 (if look-for-slash
5930 (js2-ts-return js2-COMMENT)))
5931 (t
5932 (setq look-for-slash nil
5933 js2-token-end js2-ts-cursor)))))
5934 (if (js2-match-char ?=)
5935 (js2-ts-return js2-ASSIGN_DIV)
5936 (throw 'return js2-DIV)))
5937 (?#
5938 (when js2-skip-preprocessor-directives
5939 (js2-skip-line)
5940 (setq js2-ts-comment-type 'preprocessor
5941 js2-token-end js2-ts-cursor)
5942 (throw 'return js2-COMMENT))
5943 (throw 'return js2-ERROR))
5944 (?%
5945 (if (js2-match-char ?=)
5946 (js2-ts-return js2-ASSIGN_MOD)
5947 (throw 'return js2-MOD)))
5948 (?~
5949 (throw 'return js2-BITNOT))
5950 (?+
5951 (if (js2-match-char ?=)
5952 (js2-ts-return js2-ASSIGN_ADD)
5953 (if (js2-match-char ?+)
5954 (js2-ts-return js2-INC)
5955 (throw 'return js2-ADD))))
5956 (?-
5957 (cond
5958 ((js2-match-char ?=)
5959 (setq c js2-ASSIGN_SUB))
5960 ((js2-match-char ?-)
5961 (unless js2-ts-dirty-line
5962 ;; treat HTML end-comment after possible whitespace
5963 ;; after line start as comment-until-eol
5964 (when (js2-match-char ?>)
5965 (js2-skip-line)
5966 (setq js2-ts-comment-type 'html)
5967 (throw 'return js2-COMMENT)))
5968 (setq c js2-DEC))
5969 (t
5970 (setq c js2-SUB)))
5971 (setq js2-ts-dirty-line t)
5972 (js2-ts-return c))
5973 (otherwise
5974 (js2-report-scan-error "msg.illegal.character")))))))
5975
5976 (defun js2-read-regexp (start-token)
5977 "Called by parser when it gets / or /= in literal context."
5978 (let (c
5979 err
5980 in-class ; inside a '[' .. ']' character-class
5981 flags
5982 (continue t))
5983 (setq js2-token-beg js2-ts-cursor
5984 js2-ts-string-buffer nil
5985 js2-ts-regexp-flags nil)
5986 (if (eq start-token js2-ASSIGN_DIV)
5987 ;; mis-scanned /=
5988 (js2-add-to-string ?=)
5989 (if (not (eq start-token js2-DIV))
5990 (error "failed assertion")))
5991 (while (and (not err)
5992 (or (/= (setq c (js2-get-char)) ?/)
5993 in-class))
5994 (cond
5995 ((or (= c ?\n)
5996 (= c js2-EOF_CHAR))
5997 (setq js2-token-end (1- js2-ts-cursor)
5998 err t
5999 js2-ts-string (js2-collect-string js2-ts-string-buffer))
6000 (js2-report-error "msg.unterminated.re.lit"))
6001 (t (cond
6002 ((= c ?\\)
6003 (js2-add-to-string c)
6004 (setq c (js2-get-char)))
6005 ((= c ?\[)
6006 (setq in-class t))
6007 ((= c ?\])
6008 (setq in-class nil)))
6009 (js2-add-to-string c))))
6010 (unless err
6011 (while continue
6012 (cond
6013 ((js2-match-char ?g)
6014 (push ?g flags))
6015 ((js2-match-char ?i)
6016 (push ?i flags))
6017 ((js2-match-char ?m)
6018 (push ?m flags))
6019 (t
6020 (setq continue nil))))
6021 (if (js2-alpha-p (js2-peek-char))
6022 (js2-report-scan-error "msg.invalid.re.flag" t
6023 js2-ts-cursor 1))
6024 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6025 js2-ts-regexp-flags (js2-collect-string flags)
6026 js2-token-end js2-ts-cursor)
6027 ;; tell `parse-partial-sexp' to ignore this range of chars
6028 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6029
6030 (defun js2-get-first-xml-token ()
6031 (setq js2-ts-xml-open-tags-count 0
6032 js2-ts-is-xml-attribute nil
6033 js2-ts-xml-is-tag-content nil)
6034 (js2-unget-char)
6035 (js2-get-next-xml-token))
6036
6037 (defsubst js2-xml-discard-string ()
6038 "Throw away the string in progress and flag an XML parse error."
6039 (setq js2-ts-string-buffer nil
6040 js2-ts-string nil)
6041 (js2-report-scan-error "msg.XML.bad.form" t))
6042
6043 (defun js2-get-next-xml-token ()
6044 (setq js2-ts-string-buffer nil ; for recording the XML
6045 js2-token-beg js2-ts-cursor)
6046 (let (c result)
6047 (setq result
6048 (catch 'return
6049 (while t
6050 (setq c (js2-get-char))
6051 (cond
6052 ((= c js2-EOF_CHAR)
6053 (throw 'return js2-ERROR))
6054 (js2-ts-xml-is-tag-content
6055 (case c
6056 (?>
6057 (js2-add-to-string c)
6058 (setq js2-ts-xml-is-tag-content nil
6059 js2-ts-is-xml-attribute nil))
6060 (?/
6061 (js2-add-to-string c)
6062 (when (eq ?> (js2-peek-char))
6063 (setq c (js2-get-char))
6064 (js2-add-to-string c)
6065 (setq js2-ts-xml-is-tag-content nil)
6066 (decf js2-ts-xml-open-tags-count)))
6067 (?{
6068 (js2-unget-char)
6069 (setq js2-ts-string (js2-get-string-from-buffer))
6070 (throw 'return js2-XML))
6071 ((?\' ?\")
6072 (js2-add-to-string c)
6073 (unless (js2-read-quoted-string c)
6074 (throw 'return js2-ERROR)))
6075 (?=
6076 (js2-add-to-string c)
6077 (setq js2-ts-is-xml-attribute t))
6078 ((? ?\t ?\r ?\n)
6079 (js2-add-to-string c))
6080 (t
6081 (js2-add-to-string c)
6082 (setq js2-ts-is-xml-attribute nil)))
6083 (when (and (not js2-ts-xml-is-tag-content)
6084 (zerop js2-ts-xml-open-tags-count))
6085 (setq js2-ts-string (js2-get-string-from-buffer))
6086 (throw 'return js2-XMLEND)))
6087 (t
6088 ;; else not tag content
6089 (case c
6090 (?<
6091 (js2-add-to-string c)
6092 (setq c (js2-peek-char))
6093 (case c
6094 (?!
6095 (setq c (js2-get-char)) ;; skip !
6096 (js2-add-to-string c)
6097 (setq c (js2-peek-char))
6098 (case c
6099 (?-
6100 (setq c (js2-get-char)) ;; skip -
6101 (js2-add-to-string c)
6102 (if (eq c ?-)
6103 (progn
6104 (js2-add-to-string c)
6105 (unless (js2-read-xml-comment)
6106 (throw 'return js2-ERROR)))
6107 (js2-xml-discard-string)
6108 (throw 'return js2-ERROR)))
6109 (?\[
6110 (setq c (js2-get-char)) ;; skip [
6111 (js2-add-to-string c)
6112 (if (and (= (js2-get-char) ?C)
6113 (= (js2-get-char) ?D)
6114 (= (js2-get-char) ?A)
6115 (= (js2-get-char) ?T)
6116 (= (js2-get-char) ?A)
6117 (= (js2-get-char) ?\[))
6118 (progn
6119 (js2-add-to-string ?C)
6120 (js2-add-to-string ?D)
6121 (js2-add-to-string ?A)
6122 (js2-add-to-string ?T)
6123 (js2-add-to-string ?A)
6124 (js2-add-to-string ?\[)
6125 (unless (js2-read-cdata)
6126 (throw 'return js2-ERROR)))
6127 (js2-xml-discard-string)
6128 (throw 'return js2-ERROR)))
6129 (t
6130 (unless (js2-read-entity)
6131 (throw 'return js2-ERROR))))
6132 ;; allow bare CDATA section
6133 ;; ex) let xml = <![CDATA[ foo bar baz ]]>;
6134 (when (zerop js2-ts-xml-open-tags-count)
6135 (throw 'return js2-XMLEND)))
6136 (??
6137 (setq c (js2-get-char)) ;; skip ?
6138 (js2-add-to-string c)
6139 (unless (js2-read-PI)
6140 (throw 'return js2-ERROR)))
6141 (?/
6142 ;; end tag
6143 (setq c (js2-get-char)) ;; skip /
6144 (js2-add-to-string c)
6145 (when (zerop js2-ts-xml-open-tags-count)
6146 (js2-xml-discard-string)
6147 (throw 'return js2-ERROR))
6148 (setq js2-ts-xml-is-tag-content t)
6149 (decf js2-ts-xml-open-tags-count))
6150 (t
6151 ;; start tag
6152 (setq js2-ts-xml-is-tag-content t)
6153 (incf js2-ts-xml-open-tags-count))))
6154 (?{
6155 (js2-unget-char)
6156 (setq js2-ts-string (js2-get-string-from-buffer))
6157 (throw 'return js2-XML))
6158 (t
6159 (js2-add-to-string c))))))))
6160 (setq js2-token-end js2-ts-cursor)
6161 result))
6162
6163 (defun js2-read-quoted-string (quote)
6164 (let (c)
6165 (catch 'return
6166 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6167 (js2-add-to-string c)
6168 (if (eq c quote)
6169 (throw 'return t)))
6170 (js2-xml-discard-string) ;; throw away string in progress
6171 nil)))
6172
6173 (defun js2-read-xml-comment ()
6174 (let ((c (js2-get-char)))
6175 (catch 'return
6176 (while (/= c js2-EOF_CHAR)
6177 (catch 'continue
6178 (js2-add-to-string c)
6179 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6180 (setq c (js2-get-char))
6181 (js2-add-to-string c)
6182 (if (eq (js2-peek-char) ?>)
6183 (progn
6184 (setq c (js2-get-char)) ;; skip >
6185 (js2-add-to-string c)
6186 (throw 'return t))
6187 (throw 'continue nil)))
6188 (setq c (js2-get-char))))
6189 (js2-xml-discard-string)
6190 nil)))
6191
6192 (defun js2-read-cdata ()
6193 (let ((c (js2-get-char)))
6194 (catch 'return
6195 (while (/= c js2-EOF_CHAR)
6196 (catch 'continue
6197 (js2-add-to-string c)
6198 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6199 (setq c (js2-get-char))
6200 (js2-add-to-string c)
6201 (if (eq (js2-peek-char) ?>)
6202 (progn
6203 (setq c (js2-get-char)) ;; Skip >
6204 (js2-add-to-string c)
6205 (throw 'return t))
6206 (throw 'continue nil)))
6207 (setq c (js2-get-char))))
6208 (js2-xml-discard-string)
6209 nil)))
6210
6211 (defun js2-read-entity ()
6212 (let ((decl-tags 1)
6213 c)
6214 (catch 'return
6215 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6216 (js2-add-to-string c)
6217 (case c
6218 (?<
6219 (incf decl-tags))
6220 (?>
6221 (decf decl-tags)
6222 (if (zerop decl-tags)
6223 (throw 'return t)))))
6224 (js2-xml-discard-string)
6225 nil)))
6226
6227 (defun js2-read-PI ()
6228 "Scan an XML processing instruction."
6229 (let (c)
6230 (catch 'return
6231 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6232 (js2-add-to-string c)
6233 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6234 (setq c (js2-get-char)) ;; Skip >
6235 (js2-add-to-string c)
6236 (throw 'return t)))
6237 (js2-xml-discard-string)
6238 nil)))
6239
6240 (defun js2-scanner-get-line ()
6241 "Return the text of the current scan line."
6242 (buffer-substring (point-at-bol) (point-at-eol)))
6243
6244 ;;; Highlighting
6245
6246 (defsubst js2-set-face (beg end face &optional record)
6247 "Fontify a region. If RECORD is non-nil, record for later."
6248 (when (plusp js2-highlight-level)
6249 (setq beg (min (point-max) beg)
6250 beg (max (point-min) beg)
6251 end (min (point-max) end)
6252 end (max (point-min) end))
6253 (if record
6254 (push (list beg end face) js2-mode-fontifications)
6255 (put-text-property beg end 'font-lock-face face))))
6256
6257 (defsubst js2-set-kid-face (pos kid len face)
6258 "Set-face on a child node.
6259 POS is absolute buffer position of parent.
6260 KID is the child node.
6261 LEN is the length to fontify.
6262 FACE is the face to fontify with."
6263 (js2-set-face (+ pos (js2-node-pos kid))
6264 (+ pos (js2-node-pos kid) (js2-node-len kid))
6265 face))
6266
6267 (defsubst js2-fontify-kwd (start length)
6268 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6269
6270 (defsubst js2-clear-face (beg end)
6271 (remove-text-properties beg end '(font-lock-face nil
6272 help-echo nil
6273 point-entered nil
6274 c-in-sws nil)))
6275
6276 (defconst js2-ecma-global-props
6277 (concat "^"
6278 (regexp-opt
6279 '("Infinity" "NaN" "undefined" "arguments") t)
6280 "$")
6281 "Value properties of the Ecma-262 Global Object.
6282 Shown at or above `js2-highlight-level' 2.")
6283
6284 ;; might want to add the name "arguments" to this list?
6285 (defconst js2-ecma-object-props
6286 (concat "^"
6287 (regexp-opt
6288 '("prototype" "__proto__" "__parent__") t)
6289 "$")
6290 "Value properties of the Ecma-262 Object constructor.
6291 Shown at or above `js2-highlight-level' 2.")
6292
6293 (defconst js2-ecma-global-funcs
6294 (concat
6295 "^"
6296 (regexp-opt
6297 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6298 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6299 "$")
6300 "Function properties of the Ecma-262 Global object.
6301 Shown at or above `js2-highlight-level' 2.")
6302
6303 (defconst js2-ecma-number-props
6304 (concat "^"
6305 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6306 "NEGATIVE_INFINITY"
6307 "POSITIVE_INFINITY") t)
6308 "$")
6309 "Properties of the Ecma-262 Number constructor.
6310 Shown at or above `js2-highlight-level' 2.")
6311
6312 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6313 "Properties of the Ecma-262 Date constructor.
6314 Shown at or above `js2-highlight-level' 2.")
6315
6316 (defconst js2-ecma-math-props
6317 (concat "^"
6318 (regexp-opt
6319 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6320 t)
6321 "$")
6322 "Properties of the Ecma-262 Math object.
6323 Shown at or above `js2-highlight-level' 2.")
6324
6325 (defconst js2-ecma-math-funcs
6326 (concat "^"
6327 (regexp-opt
6328 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6329 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6330 "$")
6331 "Function properties of the Ecma-262 Math object.
6332 Shown at or above `js2-highlight-level' 2.")
6333
6334 (defconst js2-ecma-function-props
6335 (concat
6336 "^"
6337 (regexp-opt
6338 '(;; properties of the Object prototype object
6339 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6340 "toLocaleString" "toString" "valueOf"
6341 ;; properties of the Function prototype object
6342 "apply" "call"
6343 ;; properties of the Array prototype object
6344 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6345 "splice" "unshift"
6346 ;; properties of the String prototype object
6347 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6348 "localeCompare" "match" "replace" "search" "split" "substring"
6349 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6350 "toUpperCase"
6351 ;; properties of the Number prototype object
6352 "toExponential" "toFixed" "toPrecision"
6353 ;; properties of the Date prototype object
6354 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6355 "getMinutes" "getMonth" "getSeconds" "getTime"
6356 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6357 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6358 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6359 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6360 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6361 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6362 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6363 "toTimeString" "toUTCString"
6364 ;; properties of the RegExp prototype object
6365 "exec" "test"
6366 ;; properties of the JSON prototype object
6367 "parse" "stringify"
6368 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6369 "toSource" "__defineGetter__" "__defineSetter__"
6370 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6371 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6372 t)
6373 "$")
6374 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6375 Shown at or above `js2-highlight-level' 3.")
6376
6377 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6378 (let ((target-name (and target
6379 (js2-name-node-p target)
6380 (js2-name-node-name target)))
6381 (prop-name (if prop (js2-name-node-name prop)))
6382 (level1 (>= js2-highlight-level 1))
6383 (level2 (>= js2-highlight-level 2))
6384 (level3 (>= js2-highlight-level 3))
6385 pos
6386 face)
6387 (when level2
6388 (if call-p
6389 (cond
6390 ((and target prop)
6391 (cond
6392 ((and level3 (string-match js2-ecma-function-props prop-name))
6393 (setq face 'font-lock-builtin-face))
6394 ((and target-name prop)
6395 (cond
6396 ((string= target-name "Date")
6397 (if (string-match js2-ecma-date-props prop-name)
6398 (setq face 'font-lock-builtin-face)))
6399 ((string= target-name "Math")
6400 (if (string-match js2-ecma-math-funcs prop-name)
6401 (setq face 'font-lock-builtin-face)))))))
6402 (prop
6403 (if (string-match js2-ecma-global-funcs prop-name)
6404 (setq face 'font-lock-builtin-face))))
6405 (cond
6406 ((and target prop)
6407 (cond
6408 ((string= target-name "Number")
6409 (if (string-match js2-ecma-number-props prop-name)
6410 (setq face 'font-lock-constant-face)))
6411 ((string= target-name "Math")
6412 (if (string-match js2-ecma-math-props prop-name)
6413 (setq face 'font-lock-constant-face)))))
6414 (prop
6415 (if (string-match js2-ecma-object-props prop-name)
6416 (setq face 'font-lock-constant-face)))))
6417 (when face
6418 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6419 (js2-node-pos prop))) ; relative
6420 (+ pos (js2-node-len prop))
6421 face 'record)))))
6422
6423 (defun js2-parse-highlight-member-expr-node (node)
6424 "Perform syntax highlighting of EcmaScript built-in properties.
6425 The variable `js2-highlight-level' governs this highighting."
6426 (let (face target prop name pos end parent call-p callee)
6427 (cond
6428 ;; case 1: simple name, e.g. foo
6429 ((js2-name-node-p node)
6430 (setq name (js2-name-node-name node))
6431 ;; possible for name to be nil in rare cases - saw it when
6432 ;; running js2-mode on an elisp buffer. Might as well try to
6433 ;; make it so js2-mode never barfs.
6434 (when name
6435 (setq face (if (string-match js2-ecma-global-props name)
6436 'font-lock-constant-face))
6437 (when face
6438 (setq pos (js2-node-pos node)
6439 end (+ pos (js2-node-len node)))
6440 (js2-set-face pos end face 'record))))
6441 ;; case 2: property access or function call
6442 ((or (js2-prop-get-node-p node)
6443 ;; highlight function call if expr is a prop-get node
6444 ;; or a plain name (i.e. unqualified function call)
6445 (and (setq call-p (js2-call-node-p node))
6446 (setq callee (js2-call-node-target node)) ; separate setq!
6447 (or (js2-prop-get-node-p callee)
6448 (js2-name-node-p callee))))
6449 (setq parent node
6450 node (if call-p callee node))
6451 (if (and call-p (js2-name-node-p callee))
6452 (setq prop callee)
6453 (setq target (js2-prop-get-node-left node)
6454 prop (js2-prop-get-node-right node)))
6455 (cond
6456 ((js2-name-node-p target)
6457 (if (js2-name-node-p prop)
6458 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6459 (js2-parse-highlight-prop-get parent target prop call-p)
6460 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6461 (js2-parse-highlight-prop-get parent target nil call-p)))
6462 ((js2-name-node-p prop)
6463 ;; case 2c: complex target, simple name, e.g. x[y].bar
6464 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6465
6466 (defun js2-parse-highlight-member-expr-fn-name (expr)
6467 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6468 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6469 We currently only handle the case where the last component is a prop-get
6470 of a simple name. Called before EXPR has a parent node."
6471 (let (pos
6472 (name (and (js2-prop-get-node-p expr)
6473 (js2-prop-get-node-right expr))))
6474 (when (js2-name-node-p name)
6475 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6476 (js2-node-pos name)))
6477 (+ pos (js2-node-len name))
6478 'font-lock-function-name-face
6479 'record))))
6480
6481 ;; source: http://jsdoc.sourceforge.net/
6482 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6483 ;; allows type specifications, and needs work before entering the wild.
6484
6485 (defconst js2-jsdoc-param-tag-regexp
6486 (concat "^\\s-*\\*+\\s-*\\(@"
6487 "\\(?:param\\|argument\\)"
6488 "\\)"
6489 "\\s-*\\({[^}]+}\\)?" ; optional type
6490 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6491 "\\>")
6492 "Matches jsdoc tags with optional type and optional param name.")
6493
6494 (defconst js2-jsdoc-typed-tag-regexp
6495 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6496 (regexp-opt
6497 '("enum"
6498 "extends"
6499 "field"
6500 "id"
6501 "implements"
6502 "lends"
6503 "mods"
6504 "requires"
6505 "return"
6506 "returns"
6507 "throw"
6508 "throws"))
6509 "\\)\\)\\s-*\\({[^}]+}\\)?")
6510 "Matches jsdoc tags with optional type.")
6511
6512 (defconst js2-jsdoc-arg-tag-regexp
6513 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6514 (regexp-opt
6515 '("alias"
6516 "augments"
6517 "borrows"
6518 "bug"
6519 "base"
6520 "config"
6521 "default"
6522 "define"
6523 "exception"
6524 "function"
6525 "member"
6526 "memberOf"
6527 "name"
6528 "namespace"
6529 "property"
6530 "since"
6531 "suppress"
6532 "this"
6533 "throws"
6534 "type"
6535 "version"))
6536 "\\)\\)\\s-+\\([^ \t]+\\)")
6537 "Matches jsdoc tags with a single argument.")
6538
6539 (defconst js2-jsdoc-empty-tag-regexp
6540 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6541 (regexp-opt
6542 '("addon"
6543 "author"
6544 "class"
6545 "const"
6546 "constant"
6547 "constructor"
6548 "constructs"
6549 "deprecated"
6550 "desc"
6551 "description"
6552 "event"
6553 "example"
6554 "exec"
6555 "export"
6556 "fileoverview"
6557 "final"
6558 "function"
6559 "hidden"
6560 "ignore"
6561 "implicitCast"
6562 "inheritDoc"
6563 "inner"
6564 "interface"
6565 "license"
6566 "noalias"
6567 "noshadow"
6568 "notypecheck"
6569 "override"
6570 "owner"
6571 "preserve"
6572 "preserveTry"
6573 "private"
6574 "protected"
6575 "public"
6576 "static"
6577 "supported"
6578 ))
6579 "\\)\\)\\s-*")
6580 "Matches empty jsdoc tags.")
6581
6582 (defconst js2-jsdoc-link-tag-regexp
6583 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6584 "Matches a jsdoc link or code tag.")
6585
6586 (defconst js2-jsdoc-see-tag-regexp
6587 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6588 "Matches a jsdoc @see tag.")
6589
6590 (defconst js2-jsdoc-html-tag-regexp
6591 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6592 "Matches a simple (no attributes) html start- or end-tag.")
6593
6594 (defsubst js2-jsdoc-highlight-helper ()
6595 (js2-set-face (match-beginning 1)
6596 (match-end 1)
6597 'js2-jsdoc-tag-face)
6598 (if (match-beginning 2)
6599 (if (save-excursion
6600 (goto-char (match-beginning 2))
6601 (= (char-after) ?{))
6602 (js2-set-face (1+ (match-beginning 2))
6603 (1- (match-end 2))
6604 'js2-jsdoc-type-face)
6605 (js2-set-face (match-beginning 2)
6606 (match-end 2)
6607 'js2-jsdoc-value-face)))
6608 (if (match-beginning 3)
6609 (js2-set-face (match-beginning 3)
6610 (match-end 3)
6611 'js2-jsdoc-value-face)))
6612
6613 (defun js2-highlight-jsdoc (ast)
6614 "Highlight doc comment tags."
6615 (let ((comments (js2-ast-root-comments ast))
6616 beg end)
6617 (save-excursion
6618 (dolist (node comments)
6619 (when (eq (js2-comment-node-format node) 'jsdoc)
6620 (setq beg (js2-node-abs-pos node)
6621 end (+ beg (js2-node-len node)))
6622 (save-restriction
6623 (narrow-to-region beg end)
6624 (dolist (re (list js2-jsdoc-param-tag-regexp
6625 js2-jsdoc-typed-tag-regexp
6626 js2-jsdoc-arg-tag-regexp
6627 js2-jsdoc-link-tag-regexp
6628 js2-jsdoc-see-tag-regexp
6629 js2-jsdoc-empty-tag-regexp))
6630 (goto-char beg)
6631 (while (re-search-forward re nil t)
6632 (js2-jsdoc-highlight-helper)))
6633 ;; simple highlighting for html tags
6634 (goto-char beg)
6635 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6636 (js2-set-face (match-beginning 1)
6637 (match-end 1)
6638 'js2-jsdoc-html-tag-delimiter-face)
6639 (js2-set-face (match-beginning 2)
6640 (match-end 2)
6641 'js2-jsdoc-html-tag-name-face)
6642 (js2-set-face (match-beginning 3)
6643 (match-end 3)
6644 'js2-jsdoc-html-tag-delimiter-face))))))))
6645
6646 (defun js2-highlight-assign-targets (node left right)
6647 "Highlight function properties and external variables."
6648 (let (leftpos end name)
6649 ;; highlight vars and props assigned function values
6650 (when (js2-function-node-p right)
6651 (cond
6652 ;; var foo = function() {...}
6653 ((js2-name-node-p left)
6654 (setq name left))
6655 ;; foo.bar.baz = function() {...}
6656 ((and (js2-prop-get-node-p left)
6657 (js2-name-node-p (js2-prop-get-node-right left)))
6658 (setq name (js2-prop-get-node-right left))))
6659 (when name
6660 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6661 (+ leftpos (js2-node-len name))
6662 'font-lock-function-name-face
6663 'record)))))
6664
6665 (defun js2-record-name-node (node)
6666 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6667 later. NODE must be a name node."
6668 (let (leftpos end)
6669 (push (list node js2-current-scope
6670 (setq leftpos (js2-node-abs-pos node))
6671 (setq end (+ leftpos (js2-node-len node))))
6672 js2-recorded-identifiers)))
6673
6674 (defun js2-highlight-undeclared-vars ()
6675 "After entire parse is finished, look for undeclared variable references.
6676 We have to wait until entire buffer is parsed, since JavaScript permits var
6677 decls to occur after they're used.
6678
6679 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6680 it is considered declared."
6681 (let (name)
6682 (dolist (entry js2-recorded-identifiers)
6683 (destructuring-bind (name-node scope pos end) entry
6684 (setq name (js2-name-node-name name-node))
6685 (unless (or (member name js2-global-externs)
6686 (member name js2-default-externs)
6687 (member name js2-additional-externs)
6688 (js2-get-defining-scope scope name))
6689 (js2-set-face pos end 'js2-external-variable-face 'record)
6690 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6691 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6692 (setq js2-recorded-identifiers nil)))
6693
6694 ;;; IMenu support
6695
6696 ;; We currently only support imenu, but eventually should support speedbar and
6697 ;; possibly other browsing mechanisms.
6698
6699 ;; The basic strategy is to identify function assignment targets of the form
6700 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6701 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6702 ;; for imenu after parsing is finished.
6703
6704 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6705 ;; JavaScript, and the general problem is undecidable. However, several forms
6706 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6707 ;; include:
6708
6709 ;; function foo() -- function declaration
6710 ;; foo = function() -- function expression assigned to variable
6711 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6712 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6713 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6714 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6715 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6716 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6717 ;; function foo() {function bar() {...}} -- nested function
6718 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6719
6720 ;; This list boils down to a few forms that can be combined recursively.
6721 ;; Top-level named function declarations include both the left-hand (name)
6722 ;; and the right-hand (function value) expressions needed to produce an imenu
6723 ;; entry. The other "right-hand" forms we need to look for are:
6724 ;; - functions declared as props/getters/setters in object literals
6725 ;; - nested named function declarations
6726 ;; The "left-hand" expressions that functions can be assigned to include:
6727 ;; - local/global variables
6728 ;; - nested property-get expressions like a.b.c.d
6729 ;; - element gets like foo[10] or foo['bar'] where the index
6730 ;; expression can be trivially converted to a property name. They
6731 ;; effectively then become property gets.
6732
6733 ;; All the different definition types are canonicalized into the form
6734 ;; foo.bar.baz = position-of-function-keyword
6735
6736 ;; We need to build a trie-like structure for imenu. As an example,
6737 ;; consider the following JavaScript code:
6738
6739 ;; a = function() {...} // function at position 5
6740 ;; b = function() {...} // function at position 25
6741 ;; foo = function() {...} // function at position 100
6742 ;; foo.bar = function() {...} // function at position 200
6743 ;; foo.bar.baz = function() {...} // function at position 300
6744 ;; foo.bar.zab = function() {...} // function at position 400
6745
6746 ;; During parsing we accumulate an entry for each definition in
6747 ;; the variable `js2-imenu-recorder', like so:
6748
6749 ;; '((fn a 5)
6750 ;; (fn b 25)
6751 ;; (fn foo 100)
6752 ;; (fn foo bar 200)
6753 ;; (fn foo bar baz 300)
6754 ;; (fn foo bar zab 400))
6755
6756 ;; Where 'fn' is the respective function node.
6757 ;; After parsing these entries are merged into this alist-trie:
6758
6759 ;; '((a . 1)
6760 ;; (b . 2)
6761 ;; (foo (<definition> . 3)
6762 ;; (bar (<definition> . 6)
6763 ;; (baz . 100)
6764 ;; (zab . 200))))
6765
6766 ;; Note the wacky need for a <definition> name. The token can be anything
6767 ;; that isn't a valid JavaScript identifier, because you might make foo
6768 ;; a function and then start setting properties on it that are also functions.
6769
6770 (defsubst js2-prop-node-name (node)
6771 "Return the name of a node that may be a property-get/property-name.
6772 If NODE is not a valid name-node, string-node or integral number-node,
6773 returns nil. Otherwise returns the string name/value of the node."
6774 (cond
6775 ((js2-name-node-p node)
6776 (js2-name-node-name node))
6777 ((js2-string-node-p node)
6778 (js2-string-node-value node))
6779 ((and (js2-number-node-p node)
6780 (string-match "^[0-9]+$" (js2-number-node-value node)))
6781 (js2-number-node-value node))
6782 ((js2-this-node-p node)
6783 "this")))
6784
6785 (defsubst js2-node-qname-component (node)
6786 "Return the name of this node, if it contributes to a qname.
6787 Returns nil if the node doesn't contribute."
6788 (copy-sequence
6789 (or (js2-prop-node-name node)
6790 (if (and (js2-function-node-p node)
6791 (js2-function-node-name node))
6792 (js2-name-node-name (js2-function-node-name node))))))
6793
6794 (defsubst js2-record-imenu-entry (fn-node qname pos)
6795 "Add an entry to `js2-imenu-recorder'.
6796 FN-NODE should be the current item's function node.
6797
6798 Associate FN-NODE with its QNAME for later lookup.
6799 This is used in postprocessing the chain list. For each chain, we find
6800 the parent function, look up its qname, then prepend a copy of it to the chain."
6801 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6802 (unless js2-imenu-function-map
6803 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6804 (puthash fn-node qname js2-imenu-function-map))
6805
6806 (defun js2-record-imenu-functions (node &optional var)
6807 "Record function definitions for imenu.
6808 NODE is a function node or an object literal.
6809 VAR, if non-nil, is the expression that NODE is being assigned to.
6810 When passed arguments of wrong type, does nothing."
6811 (when js2-parse-ide-mode
6812 (let ((fun-p (js2-function-node-p node))
6813 qname left fname-node pos)
6814 (cond
6815 ;; non-anonymous function declaration?
6816 ((and fun-p
6817 (not var)
6818 (setq fname-node (js2-function-node-name node)))
6819 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6820 ;; for remaining forms, compute left-side tree branch first
6821 ((and var (setq qname (js2-compute-nested-prop-get var)))
6822 (cond
6823 ;; foo.bar.baz = function
6824 (fun-p
6825 (js2-record-imenu-entry node qname (js2-node-pos node)))
6826 ;; foo.bar.baz = object-literal
6827 ;; look for nested functions: {a: {b: function() {...} }}
6828 ((js2-object-node-p node)
6829 ;; Node position here is still absolute, since the parser
6830 ;; passes the assignment target and value expressions
6831 ;; to us before they are added as children of the assignment node.
6832 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6833
6834 (defun js2-compute-nested-prop-get (node)
6835 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6836 component nodes as a list. Otherwise return nil. Element-gets are treated
6837 as property-gets if the index expression is a string, or a positive integer."
6838 (let (left right head)
6839 (cond
6840 ((or (js2-name-node-p node)
6841 (js2-this-node-p node))
6842 (list node))
6843 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6844 ((js2-prop-get-node-p node) ; foo.bar
6845 (setq left (js2-prop-get-node-left node)
6846 right (js2-prop-get-node-right node))
6847 (if (setq head (js2-compute-nested-prop-get left))
6848 (nconc head (list right))))
6849 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6850 (setq left (js2-elem-get-node-target node)
6851 right (js2-elem-get-node-element node))
6852 (if (or (js2-string-node-p right) ; ['bar']
6853 (and (js2-number-node-p right) ; [10]
6854 (string-match "^[0-9]+$"
6855 (js2-number-node-value right))))
6856 (if (setq head (js2-compute-nested-prop-get left))
6857 (nconc head (list right))))))))
6858
6859 (defun js2-record-object-literal (node qname pos)
6860 "Recursively process an object literal looking for functions.
6861 NODE is an object literal that is the right-hand child of an assignment
6862 expression. QNAME is a list of nodes representing the assignment target,
6863 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6864 POS is the absolute position of the node.
6865 We do a depth-first traversal of NODE. For any functions we find,
6866 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6867 (let (left right prop-qname)
6868 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6869 (let ((left (js2-infix-node-left e))
6870 ;; Element positions are relative to the parent position.
6871 (pos (+ pos (js2-node-pos e))))
6872 (cond
6873 ;; foo: function() {...}
6874 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6875 (when (js2-prop-node-name left)
6876 ;; As a policy decision, we record the position of the property,
6877 ;; not the position of the `function' keyword, since the property
6878 ;; is effectively the name of the function.
6879 (js2-record-imenu-entry right (append qname (list left)) pos)))
6880 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6881 ((js2-object-node-p right)
6882 (js2-record-object-literal right
6883 (append qname (list (js2-infix-node-left e)))
6884 (+ pos (js2-node-pos right)))))))))
6885
6886 (defsubst js2-node-top-level-decl-p (node)
6887 "Return t if NODE's name is defined in the top-level scope.
6888 Also returns t if NODE's name is not defined in any scope, since it implies
6889 that it's an external variable, which must also be in the top-level scope."
6890 (let* ((name (js2-prop-node-name node))
6891 (this-scope (js2-node-get-enclosing-scope node))
6892 defining-scope)
6893 (cond
6894 ((js2-this-node-p node)
6895 nil)
6896 ((null this-scope)
6897 t)
6898 ((setq defining-scope (js2-get-defining-scope this-scope name))
6899 (js2-ast-root-p defining-scope))
6900 (t t))))
6901
6902 (defsubst js2-wrapper-function-p (node)
6903 "Returns t if NODE is a function expression that's immediately invoked.
6904 NODE must be `js2-function-node'."
6905 (let ((parent (js2-node-parent node)))
6906 (or
6907 ;; function(){...}();
6908 (js2-call-node-p parent)
6909 (and (js2-paren-node-p parent)
6910 ;; (function(){...})();
6911 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6912 ;; (function(){...}).call(this);
6913 (and (js2-prop-get-node-p parent)
6914 (member (js2-name-node-name (js2-prop-get-node-right parent))
6915 '("call" "apply"))
6916 (js2-call-node-p (js2-node-parent parent))))))))
6917
6918 (defun js2-browse-postprocess-chains (entries)
6919 "Modify function-declaration name chains after parsing finishes.
6920 Some of the information is only available after the parse tree is complete.
6921 For instance, processing a nested scope requires a parent function node."
6922 (let (result head fn current-fn parent-qname qname p elem)
6923 (dolist (entry entries)
6924 ;; function node goes first
6925 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6926 ;; Examine head's defining scope:
6927 ;; Pre-processed chain, or top-level/external, keep as-is.
6928 (if (or (stringp head) (js2-node-top-level-decl-p head))
6929 (push chain result)
6930 (when (js2-this-node-p head)
6931 (setq chain (cdr chain))) ; discard this-node
6932 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6933 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6934 (when (eq parent-qname 'not-found)
6935 ;; anonymous function expressions are not recorded
6936 ;; during the parse, so we need to handle this case here
6937 (setq parent-qname
6938 (if (js2-wrapper-function-p fn)
6939 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6940 (if (js2-ast-root-p grandparent)
6941 nil
6942 (gethash grandparent js2-imenu-function-map 'skip)))
6943 'skip))
6944 (puthash fn parent-qname js2-imenu-function-map))
6945 (unless (eq parent-qname 'skip)
6946 ;; prefix parent fn qname to this chain.
6947 (let ((qname (append parent-qname chain)))
6948 (puthash current-fn (butlast qname) js2-imenu-function-map)
6949 (push qname result)))))))
6950 ;; finally replace each node in each chain with its name.
6951 (dolist (chain result)
6952 (setq p chain)
6953 (while p
6954 (if (js2-node-p (setq elem (car p)))
6955 (setcar p (js2-node-qname-component elem)))
6956 (setq p (cdr p))))
6957 result))
6958
6959 ;; Merge name chains into a trie-like tree structure of nested lists.
6960 ;; To simplify construction of the trie, we first build it out using the rule
6961 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6962 ;; [key, num-or-list]. The second element can be a number; if so, this key
6963 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6964 ;; associated with the key at this level.) Otherwise the second element is
6965 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6966 ;; a simple recursive formulation.
6967 ;;
6968 ;; js2-mode is building the data structure for imenu. The imenu documentation
6969 ;; claims that it's the structure above, but in practice it wants the children
6970 ;; at the same list level as the key for that level, which is how I've drawn
6971 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6972 ;; list wrapper around the children at each level.
6973 ;;
6974 ;; A completed nested imenu-alist entry looks like this:
6975 ;; '(("foo"
6976 ;; ("<definition>" . 7)
6977 ;; ("bar"
6978 ;; ("a" . 40)
6979 ;; ("b" . 60))))
6980 ;;
6981 ;; In particular, the documentation for `imenu--index-alist' says that
6982 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6983 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6984
6985 (defun js2-treeify (lst)
6986 "Convert (a b c d) to (a ((b ((c d)))))"
6987 (if (null (cddr lst)) ; list length <= 2
6988 lst
6989 (list (car lst) (list (js2-treeify (cdr lst))))))
6990
6991 (defun js2-build-alist-trie (chains trie)
6992 "Merge declaration name chains into a trie-like alist structure for imenu.
6993 CHAINS is the qname chain list produced during parsing. TRIE is a
6994 list of elements built up so far."
6995 (let (head tail pos branch kids)
6996 (dolist (chain chains)
6997 (setq head (car chain)
6998 tail (cdr chain)
6999 pos (if (numberp (car tail)) (car tail))
7000 branch (js2-find-if (lambda (n)
7001 (string= (car n) head))
7002 trie)
7003 kids (second branch))
7004 (cond
7005 ;; case 1: this key isn't in the trie yet
7006 ((null branch)
7007 (if trie
7008 (setcdr (last trie) (list (js2-treeify chain)))
7009 (setq trie (list (js2-treeify chain)))))
7010 ;; case 2: key is present with a single number entry: replace w/ list
7011 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7012 ;; ("<definition>" 20)))
7013 ((numberp kids)
7014 (setcar (cdr branch)
7015 (list (list "<definition-1>" kids)
7016 (if pos
7017 (list "<definition-2>" pos)
7018 (js2-treeify tail)))))
7019 ;; case 3: key is there (with kids), and we're a number entry
7020 (pos
7021 (setcdr (last kids)
7022 (list
7023 (list (format "<definition-%d>"
7024 (1+ (loop for kid in kids
7025 count (eq ?< (aref (car kid) 0)))))
7026 pos))))
7027 ;; case 4: key is there with kids, need to merge in our chain
7028 (t
7029 (js2-build-alist-trie (list tail) kids))))
7030 trie))
7031
7032 (defun js2-flatten-trie (trie)
7033 "Convert TRIE to imenu-format.
7034 Recurses through nodes, and for each one whose second element is a list,
7035 appends the list's flattened elements to the current element. Also
7036 changes the tails into conses. For instance, this pre-flattened trie
7037
7038 '(a ((b 20)
7039 (c ((d 30)
7040 (e 40)))))
7041
7042 becomes
7043
7044 '(a (b . 20)
7045 (c (d . 30)
7046 (e . 40)))
7047
7048 Note that the root of the trie has no key, just a list of chains.
7049 This is also true for the value of any key with multiple children,
7050 e.g. key 'c' in the example above."
7051 (cond
7052 ((listp (car trie))
7053 (mapcar #'js2-flatten-trie trie))
7054 (t
7055 (if (numberp (second trie))
7056 (cons (car trie) (second trie))
7057 ;; else pop list and append its kids
7058 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7059
7060 (defun js2-build-imenu-index ()
7061 "Turn `js2-imenu-recorder' into an imenu data structure."
7062 (unless (eq js2-imenu-recorder 'empty)
7063 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7064 (result (js2-build-alist-trie chains nil)))
7065 (js2-flatten-trie result))))
7066
7067 (defun js2-test-print-chains (chains)
7068 "Print a list of qname chains.
7069 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7070 i.e. one or more nodes, and an integer position as the list tail."
7071 (mapconcat (lambda (chain)
7072 (concat "("
7073 (mapconcat (lambda (elem)
7074 (if (js2-node-p elem)
7075 (or (js2-node-qname-component elem)
7076 "nil")
7077 (number-to-string elem)))
7078 chain
7079 " ")
7080 ")"))
7081 chains
7082 "\n"))
7083
7084 ;;; Parser
7085
7086 (defconst js2-version "1.8.0"
7087 "Version of JavaScript supported, plus minor js2 version.")
7088
7089 (defmacro js2-record-face (face)
7090 "Record a style run of FACE for the current token."
7091 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7092
7093 (defsubst js2-node-end (n)
7094 "Computes the absolute end of node N.
7095 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7096 is only true until the node is added to its parent; i.e., while parsing."
7097 (+ (js2-node-pos n)
7098 (js2-node-len n)))
7099
7100 (defsubst js2-record-comment ()
7101 "Record a comment in `js2-scanned-comments'."
7102 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7103 :format js2-ts-comment-type)
7104 js2-scanned-comments)
7105 (when js2-parse-ide-mode
7106 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7107 'font-lock-doc-face
7108 'font-lock-comment-face))
7109 (when (memq js2-ts-comment-type '(html preprocessor))
7110 ;; Tell cc-engine the bounds of the comment.
7111 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7112
7113 ;; This function is called depressingly often, so it should be fast.
7114 ;; Most of the time it's looking at the same token it peeked before.
7115 (defsubst js2-peek-token ()
7116 "Returns the next token without consuming it.
7117 If previous token was consumed, calls scanner to get new token.
7118 If previous token was -not- consumed, returns it (idempotent).
7119
7120 This function will not return a newline (js2-EOL) - instead, it
7121 gobbles newlines until it finds a non-newline token, and flags
7122 that token as appearing just after a newline.
7123
7124 This function will also not return a js2-COMMENT. Instead, it
7125 records comments found in `js2-scanned-comments'. If the token
7126 returned by this function immediately follows a jsdoc comment,
7127 the token is flagged as such.
7128
7129 Note that this function always returned the un-flagged token!
7130 The flags, if any, are saved in `js2-current-flagged-token'."
7131 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7132 js2-current-token ; most common case - return already-peeked token
7133 (let ((tt (js2-get-token)) ; call scanner
7134 saw-eol
7135 face)
7136 ;; process comments and whitespace
7137 (while (or (= tt js2-EOL)
7138 (= tt js2-COMMENT))
7139 (if (= tt js2-EOL)
7140 (setq saw-eol t)
7141 (setq saw-eol nil)
7142 (if js2-record-comments
7143 (js2-record-comment)))
7144 (setq tt (js2-get-token))) ; call scanner
7145 (setq js2-current-token tt
7146 js2-current-flagged-token (if saw-eol
7147 (logior tt js2-ti-after-eol)
7148 tt))
7149 ;; perform lexical fontification as soon as token is scanned
7150 (when js2-parse-ide-mode
7151 (cond
7152 ((minusp tt)
7153 (js2-record-face 'js2-error-face))
7154 ((setq face (aref js2-kwd-tokens tt))
7155 (js2-record-face face))
7156 ((and (= tt js2-NAME)
7157 (equal js2-ts-string "undefined"))
7158 (js2-record-face 'font-lock-constant-face))))
7159 tt))) ; return unflagged token
7160
7161 (defsubst js2-peek-flagged-token ()
7162 "Returns the current token along with any flags set for it."
7163 (js2-peek-token)
7164 js2-current-flagged-token)
7165
7166 (defsubst js2-consume-token ()
7167 (setq js2-current-flagged-token js2-EOF))
7168
7169 (defsubst js2-next-token ()
7170 (prog1
7171 (js2-peek-token)
7172 (js2-consume-token)))
7173
7174 (defsubst js2-next-flagged-token ()
7175 (js2-peek-token)
7176 (prog1 js2-current-flagged-token
7177 (js2-consume-token)))
7178
7179 (defsubst js2-match-token (match)
7180 "Consume and return t if next token matches MATCH, a bytecode.
7181 Returns nil and consumes nothing if MATCH is not the next token."
7182 (if (/= (js2-peek-token) match)
7183 nil
7184 (js2-consume-token)
7185 t))
7186
7187 (defun js2-match-contextual-kwd (name)
7188 "Consume and return t if next token is `js2-NAME', and its
7189 string is NAME. Returns nil and does nothing otherwise."
7190 (if (or (/= (js2-peek-token) js2-NAME)
7191 (not (string= js2-ts-string name)))
7192 nil
7193 (js2-consume-token)
7194 (js2-record-face 'font-lock-keyword-face)
7195 t))
7196
7197 (defsubst js2-valid-prop-name-token (tt)
7198 (or (= tt js2-NAME)
7199 (when (and js2-allow-keywords-as-property-names
7200 (plusp tt)
7201 (aref js2-kwd-tokens tt))
7202 (js2-save-name-token-data js2-token-beg (js2-token-name tt))
7203 t)))
7204
7205 (defsubst js2-match-prop-name ()
7206 "Consume token and return t if next token is a valid property name.
7207 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7208 is non-nil and it's a keyword token."
7209 (if (js2-valid-prop-name-token (js2-peek-token))
7210 (progn
7211 (js2-consume-token)
7212 t)
7213 nil))
7214
7215 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7216 (if (js2-match-prop-name)
7217 t
7218 (js2-report-error msg-id nil pos len)
7219 nil))
7220
7221 (defsubst js2-peek-token-or-eol ()
7222 "Return js2-EOL if the current token immediately follows a newline.
7223 Else returns the current token. Used in situations where we don't
7224 consider certain token types valid if they are preceded by a newline.
7225 One example is the postfix ++ or -- operator, which has to be on the
7226 same line as its operand."
7227 (let ((tt (js2-peek-token)))
7228 ;; Check for last peeked token flags
7229 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7230 js2-EOL
7231 tt)))
7232
7233 (defsubst js2-set-check-for-label ()
7234 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7235 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7236
7237 (defsubst js2-must-match (token msg-id &optional pos len)
7238 "Match next token to token code TOKEN, or record a syntax error.
7239 MSG-ID is the error message to report if the match fails.
7240 Returns t on match, nil if no match."
7241 (if (js2-match-token token)
7242 t
7243 (js2-report-error msg-id nil pos len)
7244 nil))
7245
7246 (defsubst js2-inside-function ()
7247 (plusp js2-nesting-of-function))
7248
7249 (defsubst js2-set-requires-activation ()
7250 (if (js2-function-node-p js2-current-script-or-fn)
7251 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7252
7253 (defsubst js2-check-activation-name (name token)
7254 (when (js2-inside-function)
7255 ;; skip language-version 1.2 check from Rhino
7256 (if (or (string= "arguments" name)
7257 (and js2-compiler-activation-names ; only used in codegen
7258 (gethash name js2-compiler-activation-names)))
7259 (js2-set-requires-activation))))
7260
7261 (defsubst js2-set-is-generator ()
7262 (if (js2-function-node-p js2-current-script-or-fn)
7263 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7264
7265 (defsubst js2-must-have-xml ()
7266 (unless js2-compiler-xml-available
7267 (js2-report-error "msg.XML.not.available")))
7268
7269 (defsubst js2-push-scope (scope)
7270 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7271 (assert (js2-scope-p scope))
7272 (assert (null (js2-scope-parent-scope scope)))
7273 (assert (not (eq js2-current-scope scope)))
7274 (setf (js2-scope-parent-scope scope) js2-current-scope
7275 js2-current-scope scope))
7276
7277 (defsubst js2-pop-scope ()
7278 (setq js2-current-scope
7279 (js2-scope-parent-scope js2-current-scope)))
7280
7281 (defsubst js2-enter-loop (loop-node)
7282 (push loop-node js2-loop-set)
7283 (push loop-node js2-loop-and-switch-set)
7284 (js2-push-scope loop-node)
7285 ;; Tell the current labeled statement (if any) its statement,
7286 ;; and set the jump target of the first label to the loop.
7287 ;; These are used in `js2-parse-continue' to verify that the
7288 ;; continue target is an actual labeled loop. (And for codegen.)
7289 (when js2-labeled-stmt
7290 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7291 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7292 js2-labeled-stmt))) loop-node)))
7293
7294 (defsubst js2-exit-loop ()
7295 (pop js2-loop-set)
7296 (pop js2-loop-and-switch-set)
7297 (js2-pop-scope))
7298
7299 (defsubst js2-enter-switch (switch-node)
7300 (push switch-node js2-loop-and-switch-set))
7301
7302 (defsubst js2-exit-switch ()
7303 (pop js2-loop-and-switch-set))
7304
7305 (defun js2-parse (&optional buf cb)
7306 "Tells the js2 parser to parse a region of JavaScript.
7307
7308 BUF is a buffer or buffer name containing the code to parse.
7309 Call `narrow-to-region' first to parse only part of the buffer.
7310
7311 The returned AST root node is given some additional properties:
7312 `node-count' - total number of nodes in the AST
7313 `buffer' - BUF. The buffer it refers to may change or be killed,
7314 so the value is not necessarily reliable.
7315
7316 An optional callback CB can be specified to report parsing
7317 progress. If `(functionp CB)' returns t, it will be called with
7318 the current line number once before parsing begins, then again
7319 each time the lexer reaches a new line number.
7320
7321 CB can also be a list of the form `(symbol cb ...)' to specify
7322 multiple callbacks with different criteria. Each symbol is a
7323 criterion keyword, and the following element is the callback to
7324 call
7325
7326 :line - called whenever the line number changes
7327 :token - called for each new token consumed
7328
7329 The list of criteria could be extended to include entering or
7330 leaving a statement, an expression, or a function definition."
7331 (if (and cb (not (functionp cb)))
7332 (error "criteria callbacks not yet implemented"))
7333 (let ((inhibit-point-motion-hooks t)
7334 (js2-compiler-xml-available (>= js2-language-version 160))
7335 ;; This is a recursive-descent parser, so give it a big stack.
7336 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7337 (max-specpdl-size (max max-specpdl-size 3000))
7338 (case-fold-search nil)
7339 ast)
7340 (message nil) ; clear any error message from previous parse
7341 (save-excursion
7342 (when buf (set-buffer buf))
7343 (setq js2-scanned-comments nil
7344 js2-parsed-errors nil
7345 js2-parsed-warnings nil
7346 js2-imenu-recorder nil
7347 js2-imenu-function-map nil
7348 js2-label-set nil)
7349 (js2-init-scanner)
7350 (setq ast (js2-with-unmodifying-text-property-changes
7351 (js2-do-parse)))
7352 (unless js2-ts-hit-eof
7353 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7354 (setf (js2-ast-root-errors ast) js2-parsed-errors
7355 (js2-ast-root-warnings ast) js2-parsed-warnings)
7356 ;; if we didn't find any declarations, put a dummy in this list so we
7357 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7358 (unless js2-imenu-recorder
7359 (setq js2-imenu-recorder 'empty))
7360 (run-hooks 'js2-parse-finished-hook)
7361 ast)))
7362
7363 ;; Corresponds to Rhino's Parser.parse() method.
7364 (defun js2-do-parse ()
7365 "Parse current buffer starting from current point.
7366 Scanner should be initialized."
7367 (let ((pos js2-ts-cursor)
7368 (end js2-ts-cursor) ; in case file is empty
7369 root n tt)
7370 ;; initialize buffer-local parsing vars
7371 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7372 js2-current-script-or-fn root
7373 js2-current-scope root
7374 js2-current-flagged-token js2-EOF
7375 js2-nesting-of-function 0
7376 js2-labeled-stmt nil
7377 js2-recorded-identifiers nil) ; for js2-highlight
7378 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7379 (if (= tt js2-FUNCTION)
7380 (progn
7381 (js2-consume-token)
7382 (setq n (js2-parse-function (if js2-called-by-compile-function
7383 'FUNCTION_EXPRESSION
7384 'FUNCTION_STATEMENT))))
7385 ;; not a function - parse a statement
7386 (setq n (js2-parse-statement)))
7387 ;; add function or statement to script
7388 (setq end (js2-node-end n))
7389 (js2-block-node-push root n))
7390 ;; add comments to root in lexical order
7391 (when js2-scanned-comments
7392 ;; if we find a comment beyond end of normal kids, use its end
7393 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7394 (dolist (comment js2-scanned-comments)
7395 (push comment (js2-ast-root-comments root))
7396 (js2-node-add-children root comment)))
7397 (setf (js2-node-len root) (- end pos))
7398 ;; Give extensions a chance to muck with things before highlighting starts.
7399 (let ((js2-additional-externs js2-additional-externs))
7400 (dolist (callback js2-post-parse-callbacks)
7401 (funcall callback))
7402 (js2-highlight-undeclared-vars))
7403 root))
7404
7405 (defun js2-function-parser ()
7406 (js2-consume-token)
7407 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7408
7409 (defun js2-parse-function-closure-body (fn-node)
7410 "Parse a JavaScript 1.8 function closure body."
7411 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7412 (if js2-ts-hit-eof
7413 (js2-report-error "msg.no.brace.body" nil
7414 (js2-node-pos fn-node)
7415 (- js2-ts-cursor (js2-node-pos fn-node)))
7416 (js2-node-add-children fn-node
7417 (setf (js2-function-node-body fn-node)
7418 (js2-parse-expr t))))))
7419
7420 (defun js2-parse-function-body (fn-node)
7421 (js2-must-match js2-LC "msg.no.brace.body"
7422 (js2-node-pos fn-node)
7423 (- js2-ts-cursor (js2-node-pos fn-node)))
7424 (let ((pos js2-token-beg) ; LC position
7425 (pn (make-js2-block-node)) ; starts at LC position
7426 tt
7427 end)
7428 (incf js2-nesting-of-function)
7429 (unwind-protect
7430 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7431 (= tt js2-EOF)
7432 (= tt js2-RC)))
7433 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7434 (js2-parse-statement)
7435 (js2-consume-token)
7436 (js2-parse-function 'FUNCTION_STATEMENT))))
7437 (decf js2-nesting-of-function))
7438 (setq end js2-token-end) ; assume no curly and leave at current token
7439 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7440 (setq end js2-token-end))
7441 (setf (js2-node-pos pn) pos
7442 (js2-node-len pn) (- end pos))
7443 (setf (js2-function-node-body fn-node) pn)
7444 (js2-node-add-children fn-node pn)
7445 pn))
7446
7447 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7448 "Declare and fontify destructuring parameters inside NODE.
7449 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7450 (cond
7451 ((js2-name-node-p node)
7452 (let (leftpos)
7453 (js2-define-symbol decl-type (js2-name-node-name node)
7454 node ignore-not-in-block)
7455 (when face
7456 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7457 (+ leftpos (js2-node-len node))
7458 face 'record))))
7459 ((js2-object-node-p node)
7460 (dolist (elem (js2-object-node-elems node))
7461 (js2-define-destruct-symbols
7462 (if (js2-object-prop-node-p elem)
7463 (js2-object-prop-node-right elem)
7464 ;; abbreviated destructuring {a, b}
7465 elem)
7466 decl-type face ignore-not-in-block)))
7467 ((js2-array-node-p node)
7468 (dolist (elem (js2-array-node-elems node))
7469 (when elem
7470 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7471 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7472 (js2-node-len node)))))
7473
7474 (defun js2-parse-function-params (fn-node pos)
7475 (if (js2-match-token js2-RP)
7476 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7477 (let (params len param)
7478 (loop for tt = (js2-peek-token)
7479 do
7480 (cond
7481 ;; destructuring param
7482 ((or (= tt js2-LB) (= tt js2-LC))
7483 (setq param (js2-parse-primary-expr-lhs))
7484 (js2-define-destruct-symbols param
7485 js2-LP
7486 'js2-function-param-face)
7487 (push param params))
7488 ;; simple name
7489 (t
7490 (js2-must-match js2-NAME "msg.no.parm")
7491 (js2-record-face 'js2-function-param-face)
7492 (setq param (js2-create-name-node))
7493 (js2-define-symbol js2-LP js2-ts-string param)
7494 (push param params)))
7495 while
7496 (js2-match-token js2-COMMA))
7497 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7498 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7499 (dolist (p params)
7500 (js2-node-add-children fn-node p)
7501 (push p (js2-function-node-params fn-node))))))
7502
7503 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7504 "Possibly show inconsistent-return warning.
7505 Last token scanned is the close-curly for the function body."
7506 (when (and js2-mode-show-strict-warnings
7507 js2-strict-inconsistent-return-warning
7508 (not (js2-has-consistent-return-usage
7509 (js2-function-node-body fn-node))))
7510 ;; Have it extend from close-curly to bol or beginning of block.
7511 (let ((pos (save-excursion
7512 (goto-char js2-token-end)
7513 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7514 (point-at-bol))))
7515 (end js2-token-end))
7516 (if (plusp (js2-name-node-length name))
7517 (js2-add-strict-warning "msg.no.return.value"
7518 (js2-name-node-name name) pos end)
7519 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7520
7521 (defun js2-parse-function (function-type)
7522 "Function parser. FUNCTION-TYPE is a symbol."
7523 (let ((pos js2-token-beg) ; start of 'function' keyword
7524 name
7525 name-beg
7526 name-end
7527 fn-node
7528 lp
7529 (synthetic-type function-type)
7530 member-expr-node)
7531 ;; parse function name, expression, or non-name (anonymous)
7532 (cond
7533 ;; function foo(...)
7534 ((js2-match-token js2-NAME)
7535 (setq name (js2-create-name-node t)
7536 name-beg js2-token-beg
7537 name-end js2-token-end)
7538 (unless (js2-match-token js2-LP)
7539 (when js2-allow-member-expr-as-function-name
7540 ;; function foo.bar(...)
7541 (setq member-expr-node name
7542 name nil
7543 member-expr-node (js2-parse-member-expr-tail
7544 nil member-expr-node)))
7545 (js2-must-match js2-LP "msg.no.paren.parms")))
7546 ((js2-match-token js2-LP)
7547 nil) ; anonymous function: leave name as null
7548 (t
7549 ;; function random-member-expr(...)
7550 (when js2-allow-member-expr-as-function-name
7551 ;; Note that memberExpr can not start with '(' like
7552 ;; in function (1+2).toString(), because 'function (' already
7553 ;; processed as anonymous function
7554 (setq member-expr-node (js2-parse-member-expr)))
7555 (js2-must-match js2-LP "msg.no.paren.parms")))
7556 (if (= js2-current-token js2-LP) ; eventually matched LP?
7557 (setq lp js2-token-beg))
7558 (if member-expr-node
7559 (progn
7560 (setq synthetic-type 'FUNCTION_EXPRESSION)
7561 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7562 (if name
7563 (js2-set-face name-beg name-end
7564 'font-lock-function-name-face 'record)))
7565 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7566 (plusp (js2-name-node-length name)))
7567 ;; Function statements define a symbol in the enclosing scope
7568 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7569 (setf fn-node (make-js2-function-node :pos pos
7570 :name name
7571 :form function-type
7572 :lp (if lp (- lp pos))))
7573 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7574 ;; 1. Nested functions are not affected by the dynamic scope flag
7575 ;; as dynamic scope is already a parent of their scope.
7576 ;; 2. Functions defined under the with statement also immune to
7577 ;; this setup, in which case dynamic scope is ignored in favor
7578 ;; of the with object.
7579 (setf (js2-function-node-ignore-dynamic fn-node) t))
7580 ;; dynamically bind all the per-function variables
7581 (let ((js2-current-script-or-fn fn-node)
7582 (js2-current-scope fn-node)
7583 (js2-nesting-of-with 0)
7584 (js2-end-flags 0)
7585 js2-label-set
7586 js2-loop-set
7587 js2-loop-and-switch-set)
7588 (js2-parse-function-params fn-node pos)
7589 (if (and (>= js2-language-version 180)
7590 (/= (js2-peek-token) js2-LC))
7591 (js2-parse-function-closure-body fn-node)
7592 (js2-parse-function-body fn-node))
7593 (if name
7594 (js2-node-add-children fn-node name))
7595 (js2-check-inconsistent-return-warning fn-node name)
7596 ;; Function expressions define a name only in the body of the
7597 ;; function, and only if not hidden by a parameter name
7598 (if (and name
7599 (eq synthetic-type 'FUNCTION_EXPRESSION)
7600 (null (js2-scope-get-symbol js2-current-scope
7601 (js2-name-node-name name))))
7602 (js2-define-symbol js2-FUNCTION
7603 (js2-name-node-name name)
7604 fn-node))
7605 (if (and name
7606 (not (eq function-type 'FUNCTION_EXPRESSION)))
7607 (js2-record-imenu-functions fn-node)))
7608 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7609 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7610 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7611 ;; We wait until after parsing the function to set its parent scope,
7612 ;; since `js2-define-symbol' needs the defining-scope check to stop
7613 ;; at the function boundary when checking for redeclarations.
7614 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7615 fn-node))
7616
7617 (defun js2-parse-statements (&optional parent)
7618 "Parse a statement list. Last token consumed must be js2-LC.
7619
7620 PARENT can be a `js2-block-node', in which case the statements are
7621 appended to PARENT. Otherwise a new `js2-block-node' is created
7622 and returned.
7623
7624 This function does not match the closing js2-RC: the caller
7625 matches the RC so it can provide a suitable error message if not
7626 matched. This means it's up to the caller to set the length of
7627 the node to include the closing RC. The node start pos is set to
7628 the absolute buffer start position, and the caller should fix it
7629 up to be relative to the parent node. All children of this block
7630 node are given relative start positions and correct lengths."
7631 (let ((pn (or parent (make-js2-block-node)))
7632 tt)
7633 (setf (js2-node-pos pn) js2-token-beg)
7634 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7635 (/= tt js2-RC))
7636 (js2-block-node-push pn (js2-parse-statement)))
7637 pn))
7638
7639 (defun js2-parse-statement ()
7640 (let (tt pn beg end)
7641 ;; coarse-grained user-interrupt check - needs work
7642 (and js2-parse-interruptable-p
7643 (zerop (% (incf js2-parse-stmt-count)
7644 js2-statements-per-pause))
7645 (input-pending-p)
7646 (throw 'interrupted t))
7647 (setq pn (js2-statement-helper))
7648 ;; no-side-effects warning check
7649 (unless (js2-node-has-side-effects pn)
7650 (setq end (js2-node-end pn))
7651 (save-excursion
7652 (goto-char end)
7653 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7654 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7655 pn))
7656
7657 ;; These correspond to the switch cases in Parser.statementHelper
7658 (defconst js2-parsers
7659 (let ((parsers (make-vector js2-num-tokens
7660 #'js2-parse-expr-stmt)))
7661 (aset parsers js2-BREAK #'js2-parse-break)
7662 (aset parsers js2-CONST #'js2-parse-const-var)
7663 (aset parsers js2-CONTINUE #'js2-parse-continue)
7664 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7665 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7666 (aset parsers js2-DO #'js2-parse-do)
7667 (aset parsers js2-FOR #'js2-parse-for)
7668 (aset parsers js2-FUNCTION #'js2-function-parser)
7669 (aset parsers js2-IF #'js2-parse-if)
7670 (aset parsers js2-LC #'js2-parse-block)
7671 (aset parsers js2-LET #'js2-parse-let-stmt)
7672 (aset parsers js2-NAME #'js2-parse-name-or-label)
7673 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7674 (aset parsers js2-SEMI #'js2-parse-semi)
7675 (aset parsers js2-SWITCH #'js2-parse-switch)
7676 (aset parsers js2-THROW #'js2-parse-throw)
7677 (aset parsers js2-TRY #'js2-parse-try)
7678 (aset parsers js2-VAR #'js2-parse-const-var)
7679 (aset parsers js2-WHILE #'js2-parse-while)
7680 (aset parsers js2-WITH #'js2-parse-with)
7681 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7682 parsers)
7683 "A vector mapping token types to parser functions.")
7684
7685 (defsubst js2-parse-warn-missing-semi (beg end)
7686 (and js2-mode-show-strict-warnings
7687 js2-strict-missing-semi-warning
7688 (js2-add-strict-warning
7689 "msg.missing.semi" nil
7690 ;; back up to beginning of statement or line
7691 (max beg (save-excursion
7692 (goto-char end)
7693 (point-at-bol)))
7694 end)))
7695
7696 (defconst js2-no-semi-insertion
7697 (list js2-IF
7698 js2-SWITCH
7699 js2-WHILE
7700 js2-DO
7701 js2-FOR
7702 js2-TRY
7703 js2-WITH
7704 js2-LC
7705 js2-ERROR
7706 js2-SEMI
7707 js2-FUNCTION)
7708 "List of tokens that don't do automatic semicolon insertion.")
7709
7710 (defconst js2-autoinsert-semi-and-warn
7711 (list js2-ERROR js2-EOF js2-RC))
7712
7713 (defun js2-statement-helper ()
7714 (let* ((tt (js2-peek-token))
7715 (first-tt tt)
7716 (beg js2-token-beg)
7717 (parser (if (= tt js2-ERROR)
7718 #'js2-parse-semi
7719 (aref js2-parsers tt)))
7720 pn
7721 tt-flagged)
7722 ;; If the statement is set, then it's been told its label by now.
7723 (and js2-labeled-stmt
7724 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7725 (setq js2-labeled-stmt nil))
7726 (setq pn (funcall parser))
7727 ;; Don't do auto semi insertion for certain statement types.
7728 (unless (or (memq first-tt js2-no-semi-insertion)
7729 (js2-labeled-stmt-node-p pn))
7730 (js2-auto-insert-semicolon pn))
7731 pn))
7732
7733 (defun js2-auto-insert-semicolon (pn)
7734 (let* ((tt-flagged (js2-peek-flagged-token))
7735 (tt (logand tt-flagged js2-clear-ti-mask))
7736 (pos (js2-node-pos pn)))
7737 (cond
7738 ((= tt js2-SEMI)
7739 ;; Consume ';' as a part of expression
7740 (js2-consume-token)
7741 ;; extend the node bounds to include the semicolon.
7742 (setf (js2-node-len pn) (- js2-token-end pos)))
7743 ((memq tt js2-autoinsert-semi-and-warn)
7744 ;; Autoinsert ;
7745 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7746 (t
7747 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7748 ;; Report error if no EOL or autoinsert ';' otherwise
7749 (js2-report-error "msg.no.semi.stmt")
7750 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7751
7752 (defun js2-parse-condition ()
7753 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7754 The parens are discarded and the expression node is returned.
7755 The `pos' field of the return value is set to an absolute position
7756 that must be fixed up by the caller.
7757 Return value is a list (EXPR LP RP), with absolute paren positions."
7758 (let (pn lp rp)
7759 (if (js2-must-match js2-LP "msg.no.paren.cond")
7760 (setq lp js2-token-beg))
7761 (setq pn (js2-parse-expr))
7762 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7763 (setq rp js2-token-beg))
7764 ;; Report strict warning on code like "if (a = 7) ..."
7765 (if (and js2-strict-cond-assign-warning
7766 (js2-assign-node-p pn))
7767 (js2-add-strict-warning "msg.equal.as.assign" nil
7768 (js2-node-pos pn)
7769 (+ (js2-node-pos pn)
7770 (js2-node-len pn))))
7771 (list pn lp rp)))
7772
7773 (defun js2-parse-if ()
7774 "Parser for if-statement. Last matched token must be js2-IF."
7775 (let ((pos js2-token-beg)
7776 cond
7777 if-true
7778 if-false
7779 else-pos
7780 end
7781 pn)
7782 (js2-consume-token)
7783 (setq cond (js2-parse-condition)
7784 if-true (js2-parse-statement)
7785 if-false (if (js2-match-token js2-ELSE)
7786 (progn
7787 (setq else-pos (- js2-token-beg pos))
7788 (js2-parse-statement)))
7789 end (js2-node-end (or if-false if-true))
7790 pn (make-js2-if-node :pos pos
7791 :len (- end pos)
7792 :condition (car cond)
7793 :then-part if-true
7794 :else-part if-false
7795 :else-pos else-pos
7796 :lp (js2-relpos (second cond) pos)
7797 :rp (js2-relpos (third cond) pos)))
7798 (js2-node-add-children pn (car cond) if-true if-false)
7799 pn))
7800
7801 (defun js2-parse-switch ()
7802 "Parser for if-statement. Last matched token must be js2-SWITCH."
7803 (let ((pos js2-token-beg)
7804 tt
7805 pn
7806 discriminant
7807 has-default
7808 case-expr
7809 case-node
7810 case-pos
7811 cases
7812 stmt
7813 lp
7814 rp)
7815 (js2-consume-token)
7816 (if (js2-must-match js2-LP "msg.no.paren.switch")
7817 (setq lp js2-token-beg))
7818 (setq discriminant (js2-parse-expr)
7819 pn (make-js2-switch-node :discriminant discriminant
7820 :pos pos
7821 :lp (js2-relpos lp pos)))
7822 (js2-node-add-children pn discriminant)
7823 (js2-enter-switch pn)
7824 (unwind-protect
7825 (progn
7826 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7827 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7828 (js2-must-match js2-LC "msg.no.brace.switch")
7829 (catch 'break
7830 (while t
7831 (setq tt (js2-next-token)
7832 case-pos js2-token-beg)
7833 (cond
7834 ((= tt js2-RC)
7835 (setf (js2-node-len pn) (- js2-token-end pos))
7836 (throw 'break nil)) ; done
7837 ((= tt js2-CASE)
7838 (setq case-expr (js2-parse-expr))
7839 (js2-must-match js2-COLON "msg.no.colon.case"))
7840 ((= tt js2-DEFAULT)
7841 (if has-default
7842 (js2-report-error "msg.double.switch.default"))
7843 (setq has-default t
7844 case-expr nil)
7845 (js2-must-match js2-COLON "msg.no.colon.case"))
7846 (t
7847 (js2-report-error "msg.bad.switch")
7848 (throw 'break nil)))
7849 (setq case-node (make-js2-case-node :pos case-pos
7850 :len (- js2-token-end case-pos)
7851 :expr case-expr))
7852 (js2-node-add-children case-node case-expr)
7853 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7854 (/= tt js2-CASE)
7855 (/= tt js2-DEFAULT)
7856 (/= tt js2-EOF))
7857 (setf stmt (js2-parse-statement)
7858 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7859 (js2-block-node-push case-node stmt))
7860 (push case-node cases)))
7861 ;; add cases last, as pushing reverses the order to be correct
7862 (dolist (kid cases)
7863 (js2-node-add-children pn kid)
7864 (push kid (js2-switch-node-cases pn)))
7865 pn) ; return value
7866 (js2-exit-switch))))
7867
7868 (defun js2-parse-while ()
7869 "Parser for while-statement. Last matched token must be js2-WHILE."
7870 (let ((pos js2-token-beg)
7871 (pn (make-js2-while-node))
7872 cond
7873 body)
7874 (js2-consume-token)
7875 (js2-enter-loop pn)
7876 (unwind-protect
7877 (progn
7878 (setf cond (js2-parse-condition)
7879 (js2-while-node-condition pn) (car cond)
7880 body (js2-parse-statement)
7881 (js2-while-node-body pn) body
7882 (js2-node-len pn) (- (js2-node-end body) pos)
7883 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7884 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7885 (js2-node-add-children pn body (car cond)))
7886 (js2-exit-loop))
7887 pn))
7888
7889 (defun js2-parse-do ()
7890 "Parser for do-statement. Last matched token must be js2-DO."
7891 (let ((pos js2-token-beg)
7892 (pn (make-js2-do-node))
7893 cond
7894 body
7895 end)
7896 (js2-consume-token)
7897 (js2-enter-loop pn)
7898 (unwind-protect
7899 (progn
7900 (setq body (js2-parse-statement))
7901 (js2-must-match js2-WHILE "msg.no.while.do")
7902 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7903 cond (js2-parse-condition)
7904 (js2-do-node-condition pn) (car cond)
7905 (js2-do-node-body pn) body
7906 end js2-ts-cursor
7907 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7908 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7909 (js2-node-add-children pn (car cond) body))
7910 (js2-exit-loop))
7911 ;; Always auto-insert semicolon to follow SpiderMonkey:
7912 ;; It is required by ECMAScript but is ignored by the rest of
7913 ;; world; see bug 238945
7914 (if (js2-match-token js2-SEMI)
7915 (setq end js2-ts-cursor))
7916 (setf (js2-node-len pn) (- end pos))
7917 pn))
7918
7919 (defun js2-parse-for ()
7920 "Parser for for-statement. Last matched token must be js2-FOR.
7921 Parses for, for-in, and for each-in statements."
7922 (let ((for-pos js2-token-beg)
7923 pn
7924 is-for-each
7925 is-for-in-or-of
7926 is-for-of
7927 in-pos
7928 each-pos
7929 tmp-pos
7930 init ; Node init is also foo in 'foo in object'
7931 cond ; Node cond is also object in 'foo in object'
7932 incr ; 3rd section of for-loop initializer
7933 body
7934 tt
7935 lp
7936 rp)
7937 (js2-consume-token)
7938 ;; See if this is a for each () instead of just a for ()
7939 (when (js2-match-token js2-NAME)
7940 (if (string= "each" js2-ts-string)
7941 (progn
7942 (setq is-for-each t
7943 each-pos (- js2-token-beg for-pos)) ; relative
7944 (js2-record-face 'font-lock-keyword-face))
7945 (js2-report-error "msg.no.paren.for")))
7946 (if (js2-must-match js2-LP "msg.no.paren.for")
7947 (setq lp (- js2-token-beg for-pos)))
7948 (setq tt (js2-peek-token))
7949 ;; 'for' makes local scope
7950 (js2-push-scope (make-js2-scope))
7951 (unwind-protect
7952 ;; parse init clause
7953 (let ((js2-in-for-init t)) ; set as dynamic variable
7954 (cond
7955 ((= tt js2-SEMI)
7956 (setq init (make-js2-empty-expr-node)))
7957 ((or (= tt js2-VAR) (= tt js2-LET))
7958 (js2-consume-token)
7959 (setq init (js2-parse-variables tt js2-token-beg)))
7960 (t
7961 (setq init (js2-parse-expr)))))
7962 (if (or (js2-match-token js2-IN)
7963 (and (>= js2-language-version 200)
7964 (js2-match-contextual-kwd "of")
7965 (setq is-for-of t)))
7966 (setq is-for-in-or-of t
7967 in-pos (- js2-token-beg for-pos)
7968 ;; scope of iteration target object is not the scope we've created above.
7969 ;; stash current scope temporary.
7970 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7971 (js2-parse-expr))) ; object over which we're iterating
7972 ;; else ordinary for loop - parse cond and incr
7973 (js2-must-match js2-SEMI "msg.no.semi.for")
7974 (setq cond (if (= (js2-peek-token) js2-SEMI)
7975 (make-js2-empty-expr-node) ; no loop condition
7976 (js2-parse-expr)))
7977 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7978 (setq tmp-pos js2-token-end
7979 incr (if (= (js2-peek-token) js2-RP)
7980 (make-js2-empty-expr-node :pos tmp-pos)
7981 (js2-parse-expr))))
7982 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7983 (setq rp (- js2-token-beg for-pos)))
7984 (if (not is-for-in-or-of)
7985 (setq pn (make-js2-for-node :init init
7986 :condition cond
7987 :update incr
7988 :lp lp
7989 :rp rp))
7990 ;; cond could be null if 'in obj' got eaten by the init node.
7991 (if (js2-infix-node-p init)
7992 ;; it was (foo in bar) instead of (var foo in bar)
7993 (setq cond (js2-infix-node-right init)
7994 init (js2-infix-node-left init))
7995 (if (and (js2-var-decl-node-p init)
7996 (> (length (js2-var-decl-node-kids init)) 1))
7997 (js2-report-error "msg.mult.index")))
7998 (setq pn (make-js2-for-in-node :iterator init
7999 :object cond
8000 :in-pos in-pos
8001 :foreach-p is-for-each
8002 :each-pos each-pos
8003 :forof-p is-for-of
8004 :lp lp
8005 :rp rp)))
8006 (unwind-protect
8007 (progn
8008 (js2-enter-loop pn)
8009 ;; We have to parse the body -after- creating the loop node,
8010 ;; so that the loop node appears in the js2-loop-set, allowing
8011 ;; break/continue statements to find the enclosing loop.
8012 (setf body (js2-parse-statement)
8013 (js2-loop-node-body pn) body
8014 (js2-node-pos pn) for-pos
8015 (js2-node-len pn) (- (js2-node-end body) for-pos))
8016 (js2-node-add-children pn init cond incr body))
8017 ;; finally
8018 (js2-exit-loop))
8019 (js2-pop-scope))
8020 pn))
8021
8022 (defun js2-parse-try ()
8023 "Parser for try-statement. Last matched token must be js2-TRY."
8024 (let ((try-pos js2-token-beg)
8025 try-end
8026 try-block
8027 catch-blocks
8028 finally-block
8029 saw-default-catch
8030 peek
8031 param
8032 catch-cond
8033 catch-node
8034 guard-kwd
8035 catch-pos
8036 finally-pos
8037 pn
8038 block
8039 lp
8040 rp)
8041 (js2-consume-token)
8042 (if (/= (js2-peek-token) js2-LC)
8043 (js2-report-error "msg.no.brace.try"))
8044 (setq try-block (js2-parse-statement)
8045 try-end (js2-node-end try-block)
8046 peek (js2-peek-token))
8047 (cond
8048 ((= peek js2-CATCH)
8049 (while (js2-match-token js2-CATCH)
8050 (setq catch-pos js2-token-beg
8051 guard-kwd nil
8052 catch-cond nil
8053 lp nil
8054 rp nil)
8055 (if saw-default-catch
8056 (js2-report-error "msg.catch.unreachable"))
8057 (if (js2-must-match js2-LP "msg.no.paren.catch")
8058 (setq lp (- js2-token-beg catch-pos)))
8059 (js2-push-scope (make-js2-scope))
8060 (let ((tt (js2-peek-token)))
8061 (cond
8062 ;; destructuring pattern
8063 ;; catch ({ message, file }) { ... }
8064 ((or (= tt js2-LB) (= tt js2-LC))
8065 (setq param
8066 (js2-define-destruct-symbols (js2-parse-primary-expr-lhs)
8067 js2-LET nil)))
8068 ;; simple name
8069 (t
8070 (js2-must-match js2-NAME "msg.bad.catchcond")
8071 (setq param (js2-create-name-node))
8072 (js2-define-symbol js2-LET js2-ts-string param))))
8073 ;; pattern guard
8074 (if (js2-match-token js2-IF)
8075 (setq guard-kwd (- js2-token-beg catch-pos)
8076 catch-cond (js2-parse-expr))
8077 (setq saw-default-catch t))
8078 (if (js2-must-match js2-RP "msg.bad.catchcond")
8079 (setq rp (- js2-token-beg catch-pos)))
8080 (js2-must-match js2-LC "msg.no.brace.catchblock")
8081 (setq block (js2-parse-statements)
8082 try-end (js2-node-end block)
8083 catch-node (make-js2-catch-node :pos catch-pos
8084 :param param
8085 :guard-expr catch-cond
8086 :guard-kwd guard-kwd
8087 :block block
8088 :lp lp
8089 :rp rp))
8090 (js2-pop-scope)
8091 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8092 (setq try-end js2-token-beg))
8093 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8094 (js2-node-len catch-node) (- try-end catch-pos))
8095 (js2-node-add-children catch-node param catch-cond block)
8096 (push catch-node catch-blocks)))
8097 ((/= peek js2-FINALLY)
8098 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8099 (js2-node-pos try-block)
8100 (- (setq try-end (js2-node-end try-block))
8101 (js2-node-pos try-block)))))
8102 (when (js2-match-token js2-FINALLY)
8103 (setq finally-pos js2-token-beg
8104 block (js2-parse-statement)
8105 try-end (js2-node-end block)
8106 finally-block (make-js2-finally-node :pos finally-pos
8107 :len (- try-end finally-pos)
8108 :body block))
8109 (js2-node-add-children finally-block block))
8110 (setq pn (make-js2-try-node :pos try-pos
8111 :len (- try-end try-pos)
8112 :try-block try-block
8113 :finally-block finally-block))
8114 (js2-node-add-children pn try-block finally-block)
8115 ;; push them onto the try-node, which reverses and corrects their order
8116 (dolist (cb catch-blocks)
8117 (js2-node-add-children pn cb)
8118 (push cb (js2-try-node-catch-clauses pn)))
8119 pn))
8120
8121 (defun js2-parse-throw ()
8122 "Parser for throw-statement. Last matched token must be js2-THROW."
8123 (let ((pos js2-token-beg)
8124 expr
8125 pn)
8126 (js2-consume-token)
8127 (if (= (js2-peek-token-or-eol) js2-EOL)
8128 ;; ECMAScript does not allow new lines before throw expression,
8129 ;; see bug 256617
8130 (js2-report-error "msg.bad.throw.eol"))
8131 (setq expr (js2-parse-expr)
8132 pn (make-js2-throw-node :pos pos
8133 :len (- (js2-node-end expr) pos)
8134 :expr expr))
8135 (js2-node-add-children pn expr)
8136 pn))
8137
8138 (defsubst js2-match-jump-label-name (label-name)
8139 "If break/continue specified a label, return that label's labeled stmt.
8140 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8141 does not match an existing label, reports an error and returns nil."
8142 (let ((bundle (cdr (assoc label-name js2-label-set))))
8143 (if (null bundle)
8144 (js2-report-error "msg.undef.label"))
8145 bundle))
8146
8147 (defun js2-parse-break ()
8148 "Parser for break-statement. Last matched token must be js2-BREAK."
8149 (let ((pos js2-token-beg)
8150 (end js2-token-end)
8151 break-target ; statement to break from
8152 break-label ; in "break foo", name-node representing the foo
8153 labels ; matching labeled statement to break to
8154 pn)
8155 (js2-consume-token) ; `break'
8156 (when (eq (js2-peek-token-or-eol) js2-NAME)
8157 (js2-consume-token)
8158 (setq break-label (js2-create-name-node)
8159 end (js2-node-end break-label)
8160 ;; matchJumpLabelName only matches if there is one
8161 labels (js2-match-jump-label-name js2-ts-string)
8162 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8163 (unless (or break-target break-label)
8164 ;; no break target specified - try for innermost enclosing loop/switch
8165 (if (null js2-loop-and-switch-set)
8166 (unless break-label
8167 (js2-report-error "msg.bad.break" nil pos (length "break")))
8168 (setq break-target (car js2-loop-and-switch-set))))
8169 (setq pn (make-js2-break-node :pos pos
8170 :len (- end pos)
8171 :label break-label
8172 :target break-target))
8173 (js2-node-add-children pn break-label) ; but not break-target
8174 pn))
8175
8176 (defun js2-parse-continue ()
8177 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8178 (let ((pos js2-token-beg)
8179 (end js2-token-end)
8180 label ; optional user-specified label, a `js2-name-node'
8181 labels ; current matching labeled stmt, if any
8182 target ; the `js2-loop-node' target of this continue stmt
8183 pn)
8184 (js2-consume-token) ; `continue'
8185 (when (= (js2-peek-token-or-eol) js2-NAME)
8186 (js2-consume-token)
8187 (setq label (js2-create-name-node)
8188 end (js2-node-end label)
8189 ;; matchJumpLabelName only matches if there is one
8190 labels (js2-match-jump-label-name js2-ts-string)))
8191 (cond
8192 ((null labels) ; no current label to go to
8193 (if (null js2-loop-set) ; no loop to continue to
8194 (js2-report-error "msg.continue.outside" nil pos
8195 (length "continue"))
8196 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8197 (t
8198 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8199 (setq target (js2-labeled-stmt-node-stmt labels))
8200 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8201 (setq pn (make-js2-continue-node :pos pos
8202 :len (- end pos)
8203 :label label
8204 :target target))
8205 (js2-node-add-children pn label) ; but not target - it's not our child
8206 pn))
8207
8208 (defun js2-parse-with ()
8209 "Parser for with-statement. Last matched token must be js2-WITH."
8210 (js2-consume-token)
8211 (let ((pos js2-token-beg)
8212 obj body pn lp rp)
8213 (if (js2-must-match js2-LP "msg.no.paren.with")
8214 (setq lp js2-token-beg))
8215 (setq obj (js2-parse-expr))
8216 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8217 (setq rp js2-token-beg))
8218 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8219 (setq body (js2-parse-statement)))
8220 (setq pn (make-js2-with-node :pos pos
8221 :len (- (js2-node-end body) pos)
8222 :object obj
8223 :body body
8224 :lp (js2-relpos lp pos)
8225 :rp (js2-relpos rp pos)))
8226 (js2-node-add-children pn obj body)
8227 pn))
8228
8229 (defun js2-parse-const-var ()
8230 "Parser for var- or const-statement.
8231 Last matched token must be js2-CONST or js2-VAR."
8232 (let ((tt (js2-peek-token))
8233 (pos js2-token-beg)
8234 expr
8235 pn)
8236 (js2-consume-token)
8237 (setq expr (js2-parse-variables tt js2-token-beg)
8238 pn (make-js2-expr-stmt-node :pos pos
8239 :len (- (js2-node-end expr) pos)
8240 :expr expr))
8241 (js2-node-add-children pn expr)
8242 pn))
8243
8244 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8245 (let ((pn (make-js2-expr-stmt-node :pos pos
8246 :len (js2-node-len expr)
8247 :type (if (js2-inside-function)
8248 js2-EXPR_VOID
8249 js2-EXPR_RESULT)
8250 :expr expr)))
8251 (if add-child
8252 (js2-node-add-children pn expr))
8253 pn))
8254
8255 (defun js2-parse-let-stmt ()
8256 "Parser for let-statement. Last matched token must be js2-LET."
8257 (js2-consume-token)
8258 (let ((pos js2-token-beg)
8259 expr
8260 pn)
8261 (if (= (js2-peek-token) js2-LP)
8262 ;; let expression in statement context
8263 (setq expr (js2-parse-let pos 'statement)
8264 pn (js2-wrap-with-expr-stmt pos expr t))
8265 ;; else we're looking at a statement like let x=6, y=7;
8266 (setf expr (js2-parse-variables js2-LET pos)
8267 pn (js2-wrap-with-expr-stmt pos expr t)
8268 (js2-node-type pn) js2-EXPR_RESULT))
8269 pn))
8270
8271 (defun js2-parse-ret-yield ()
8272 (js2-parse-return-or-yield (js2-peek-token) nil))
8273
8274 (defconst js2-parse-return-stmt-enders
8275 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8276
8277 (defsubst js2-now-all-set (before after mask)
8278 "Return whether or not the bits in the mask have changed to all set.
8279 BEFORE is bits before change, AFTER is bits after change, and MASK is
8280 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8281 but not BEFORE."
8282 (and (/= (logand before mask) mask)
8283 (= (logand after mask) mask)))
8284
8285 (defun js2-parse-return-or-yield (tt expr-context)
8286 (let ((pos js2-token-beg)
8287 (end js2-token-end)
8288 (before js2-end-flags)
8289 (inside-function (js2-inside-function))
8290 e
8291 ret
8292 name)
8293 (unless inside-function
8294 (js2-report-error (if (eq tt js2-RETURN)
8295 "msg.bad.return"
8296 "msg.bad.yield")))
8297 (js2-consume-token)
8298 ;; This is ugly, but we don't want to require a semicolon.
8299 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8300 (setq e (js2-parse-expr)
8301 end (js2-node-end e)))
8302 (cond
8303 ((eq tt js2-RETURN)
8304 (js2-set-flag js2-end-flags (if (null e)
8305 js2-end-returns
8306 js2-end-returns-value))
8307 (setq ret (make-js2-return-node :pos pos
8308 :len (- end pos)
8309 :retval e))
8310 (js2-node-add-children ret e)
8311 ;; See if we need a strict mode warning.
8312 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8313 ;; more thorough and accurate than this before/after flag check.
8314 ;; E.g. if there's a finally-block that always returns, we shouldn't
8315 ;; show a warning generated by inconsistent returns in the catch blocks.
8316 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8317 ;; so we know which returns/yields to highlight, and we should get rid of
8318 ;; all the checking in `js2-parse-return-or-yield'.
8319 (if (and js2-strict-inconsistent-return-warning
8320 (js2-now-all-set before js2-end-flags
8321 (logior js2-end-returns js2-end-returns-value)))
8322 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8323 (t
8324 (unless (js2-inside-function)
8325 (js2-report-error "msg.bad.yield"))
8326 (js2-set-flag js2-end-flags js2-end-yields)
8327 (setq ret (make-js2-yield-node :pos pos
8328 :len (- end pos)
8329 :value e))
8330 (js2-node-add-children ret e)
8331 (unless expr-context
8332 (setq e ret
8333 ret (js2-wrap-with-expr-stmt pos e t))
8334 (js2-set-requires-activation)
8335 (js2-set-is-generator))))
8336 ;; see if we are mixing yields and value returns.
8337 (when (and inside-function
8338 (js2-now-all-set before js2-end-flags
8339 (logior js2-end-yields js2-end-returns-value)))
8340 (setq name (js2-function-name js2-current-script-or-fn))
8341 (if (zerop (length name))
8342 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8343 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8344 ret))
8345
8346 (defun js2-parse-debugger ()
8347 (js2-consume-token)
8348 (make-js2-keyword-node :type js2-DEBUGGER))
8349
8350 (defun js2-parse-block ()
8351 "Parser for a curly-delimited statement block.
8352 Last token matched must be js2-LC."
8353 (let ((pos js2-token-beg)
8354 (pn (make-js2-scope)))
8355 (js2-consume-token)
8356 (js2-push-scope pn)
8357 (unwind-protect
8358 (progn
8359 (js2-parse-statements pn)
8360 (js2-must-match js2-RC "msg.no.brace.block")
8361 (setf (js2-node-len pn) (- js2-token-end pos)))
8362 (js2-pop-scope))
8363 pn))
8364
8365 ;; for js2-ERROR too, to have a node for error recovery to work on
8366 (defun js2-parse-semi ()
8367 "Parse a statement or handle an error.
8368 Last matched token is js2-SEMI or js2-ERROR."
8369 (let ((tt (js2-peek-token)) pos len)
8370 (js2-consume-token)
8371 (if (eq tt js2-SEMI)
8372 (make-js2-empty-expr-node :len 1)
8373 (setq pos js2-token-beg
8374 len (- js2-token-beg pos))
8375 (js2-report-error "msg.syntax" nil pos len)
8376 (make-js2-error-node :pos pos :len len))))
8377
8378 (defun js2-parse-default-xml-namespace ()
8379 "Parse a `default xml namespace = <expr>' e4x statement."
8380 (let ((pos js2-token-beg)
8381 end len expr unary es)
8382 (js2-consume-token)
8383 (js2-must-have-xml)
8384 (js2-set-requires-activation)
8385 (setq len (- js2-ts-cursor pos))
8386 (unless (and (js2-match-token js2-NAME)
8387 (string= js2-ts-string "xml"))
8388 (js2-report-error "msg.bad.namespace" nil pos len))
8389 (unless (and (js2-match-token js2-NAME)
8390 (string= js2-ts-string "namespace"))
8391 (js2-report-error "msg.bad.namespace" nil pos len))
8392 (unless (js2-match-token js2-ASSIGN)
8393 (js2-report-error "msg.bad.namespace" nil pos len))
8394 (setq expr (js2-parse-expr)
8395 end (js2-node-end expr)
8396 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8397 :pos pos
8398 :len (- end pos)
8399 :operand expr))
8400 (js2-node-add-children unary expr)
8401 (make-js2-expr-stmt-node :pos pos
8402 :len (- end pos)
8403 :expr unary)))
8404
8405 (defun js2-record-label (label bundle)
8406 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8407 (js2-consume-token)
8408 (let ((name (js2-label-node-name label))
8409 labeled-stmt
8410 dup)
8411 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8412 ;; flag both labels if possible when used in editing mode
8413 (if (and js2-parse-ide-mode
8414 (setq dup (js2-get-label-by-name labeled-stmt name)))
8415 (js2-report-error "msg.dup.label" nil
8416 (js2-node-abs-pos dup) (js2-node-len dup)))
8417 (js2-report-error "msg.dup.label" nil
8418 (js2-node-pos label) (js2-node-len label)))
8419 (js2-labeled-stmt-node-add-label bundle label)
8420 (js2-node-add-children bundle label)
8421 ;; Add one reference to the bundle per label in `js2-label-set'
8422 (push (cons name bundle) js2-label-set)))
8423
8424 (defun js2-parse-name-or-label ()
8425 "Parser for identifier or label. Last token matched must be js2-NAME.
8426 Called when we found a name in a statement context. If it's a label, we gather
8427 up any following labels and the next non-label statement into a
8428 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8429 expression and return it wrapped in a `js2-expr-stmt-node'."
8430 (let ((pos js2-token-beg)
8431 (end js2-token-end)
8432 expr
8433 stmt
8434 pn
8435 bundle
8436 (continue t))
8437 ;; set check for label and call down to `js2-parse-primary-expr'
8438 (js2-set-check-for-label)
8439 (setq expr (js2-parse-expr))
8440 (if (/= (js2-node-type expr) js2-LABEL)
8441 ;; Parsed non-label expression - wrap with expression stmt.
8442 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8443 ;; else parsed a label
8444 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8445 (js2-record-label expr bundle)
8446 ;; look for more labels
8447 (while (and continue (= (js2-peek-token) js2-NAME))
8448 (js2-set-check-for-label)
8449 (setq expr (js2-parse-expr))
8450 (if (/= (js2-node-type expr) js2-LABEL)
8451 (progn
8452 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8453 continue nil)
8454 (js2-auto-insert-semicolon stmt))
8455 (js2-record-label expr bundle)))
8456 ;; no more labels; now parse the labeled statement
8457 (unwind-protect
8458 (unless stmt
8459 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8460 (setq stmt (js2-statement-helper))))
8461 ;; remove the labels for this statement from the global set
8462 (dolist (label (js2-labeled-stmt-node-labels bundle))
8463 (setq js2-label-set (remove label js2-label-set))))
8464 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8465 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8466 (js2-node-add-children bundle stmt)
8467 bundle)))
8468
8469 (defun js2-parse-expr-stmt ()
8470 "Default parser in statement context, if no recognized statement found."
8471 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8472
8473 (defun js2-parse-variables (decl-type pos)
8474 "Parse a comma-separated list of variable declarations.
8475 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8476
8477 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8478 For 'var' or 'const', the keyword should be the token last scanned.
8479
8480 POS is the position where the node should start. It's sometimes the
8481 var/const/let keyword, and other times the beginning of the first token
8482 in the first variable declaration.
8483
8484 Returns the parsed `js2-var-decl-node' expression node."
8485 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8486 :pos pos))
8487 destructuring
8488 kid-pos
8489 tt
8490 init
8491 name
8492 end
8493 nbeg nend
8494 vi
8495 (continue t))
8496 ;; Example:
8497 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8498 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8499 ;; var {a, b} = baz;
8500 (while continue
8501 (setq destructuring nil
8502 name nil
8503 tt (js2-peek-token)
8504 kid-pos js2-token-beg
8505 end js2-token-end
8506 init nil)
8507 (if (or (= tt js2-LB) (= tt js2-LC))
8508 ;; Destructuring assignment, e.g., var [a, b] = ...
8509 (setq destructuring (js2-parse-primary-expr-lhs)
8510 end (js2-node-end destructuring))
8511 ;; Simple variable name
8512 (when (js2-must-match js2-NAME "msg.bad.var")
8513 (setq name (js2-create-name-node)
8514 nbeg js2-token-beg
8515 nend js2-token-end
8516 end nend)
8517 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8518 (when (js2-match-token js2-ASSIGN)
8519 (setq init (js2-parse-assign-expr)
8520 end (js2-node-end init))
8521 (js2-record-imenu-functions init name))
8522 (when name
8523 (js2-set-face nbeg nend (if (js2-function-node-p init)
8524 'font-lock-function-name-face
8525 'font-lock-variable-name-face)
8526 'record))
8527 (setq vi (make-js2-var-init-node :pos kid-pos
8528 :len (- end kid-pos)
8529 :type decl-type))
8530 (if destructuring
8531 (progn
8532 (if (and (null init) (not js2-in-for-init))
8533 (js2-report-error "msg.destruct.assign.no.init"))
8534 (js2-define-destruct-symbols destructuring
8535 decl-type
8536 'font-lock-variable-name-face)
8537 (setf (js2-var-init-node-target vi) destructuring))
8538 (setf (js2-var-init-node-target vi) name))
8539 (setf (js2-var-init-node-initializer vi) init)
8540 (js2-node-add-children vi name destructuring init)
8541 (js2-block-node-push result vi)
8542 (unless (js2-match-token js2-COMMA)
8543 (setq continue nil)))
8544 (setf (js2-node-len result) (- end pos))
8545 result))
8546
8547 (defun js2-parse-let (pos &optional stmt-p)
8548 "Parse a let expression or statement.
8549 A let-expression is of the form `let (vars) expr'.
8550 A let-statment is of the form `let (vars) {statements}'.
8551 The third form of let is a variable declaration list, handled
8552 by `js2-parse-variables'."
8553 (let ((pn (make-js2-let-node :pos pos))
8554 beg vars body)
8555 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8556 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8557 (js2-push-scope pn)
8558 (unwind-protect
8559 (progn
8560 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8561 (if (js2-must-match js2-RP "msg.no.paren.let")
8562 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8563 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8564 ;; let statement
8565 (progn
8566 (js2-consume-token)
8567 (setf beg js2-token-beg ; position stmt at LC
8568 body (js2-parse-statements))
8569 (js2-must-match js2-RC "msg.no.curly.let")
8570 (setf (js2-node-len body) (- js2-token-end beg)
8571 (js2-node-len pn) (- js2-token-end pos)
8572 (js2-let-node-body pn) body
8573 (js2-node-type pn) js2-LET))
8574 ;; let expression
8575 (setf body (js2-parse-expr)
8576 (js2-node-len pn) (- (js2-node-end body) pos)
8577 (js2-let-node-body pn) body))
8578 (js2-node-add-children pn vars body))
8579 (js2-pop-scope))
8580 pn))
8581
8582 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8583 (js2-scope-put-symbol (or scope js2-current-scope)
8584 name
8585 (make-js2-symbol decl-type name node)))
8586
8587 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8588 "Define a symbol in the current scope.
8589 If NODE is non-nil, it is the AST node associated with the symbol."
8590 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8591 (symbol (if defining-scope
8592 (js2-scope-get-symbol defining-scope name)))
8593 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8594 (cond
8595 ((and symbol ; already defined
8596 (or (= sdt js2-CONST) ; old version is const
8597 (= decl-type js2-CONST) ; new version is const
8598 ;; two let-bound vars in this block have same name
8599 (and (= sdt js2-LET)
8600 (eq defining-scope js2-current-scope))))
8601 (js2-report-error
8602 (cond
8603 ((= sdt js2-CONST) "msg.const.redecl")
8604 ((= sdt js2-LET) "msg.let.redecl")
8605 ((= sdt js2-VAR) "msg.var.redecl")
8606 ((= sdt js2-FUNCTION) "msg.function.redecl")
8607 (t "msg.parm.redecl"))
8608 name))
8609 ((= decl-type js2-LET)
8610 (if (and (not ignore-not-in-block)
8611 (or (= (js2-node-type js2-current-scope) js2-IF)
8612 (js2-loop-node-p js2-current-scope)))
8613 (js2-report-error "msg.let.decl.not.in.block")
8614 (js2-define-new-symbol decl-type name node)))
8615 ((or (= decl-type js2-VAR)
8616 (= decl-type js2-CONST)
8617 (= decl-type js2-FUNCTION))
8618 (if symbol
8619 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8620 (js2-add-strict-warning "msg.var.redecl" name)
8621 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8622 (js2-add-strict-warning "msg.var.hides.arg" name)))
8623 (js2-define-new-symbol decl-type name node
8624 js2-current-script-or-fn)))
8625 ((= decl-type js2-LP)
8626 (if symbol
8627 ;; must be duplicate parameter. Second parameter hides the
8628 ;; first, so go ahead and add the second pararameter
8629 (js2-report-warning "msg.dup.parms" name))
8630 (js2-define-new-symbol decl-type name node))
8631 (t (js2-code-bug)))))
8632
8633 (defun js2-parse-expr (&optional oneshot)
8634 (let* ((pn (js2-parse-assign-expr))
8635 (pos (js2-node-pos pn))
8636 left
8637 right
8638 op-pos)
8639 (while (and (not oneshot)
8640 (js2-match-token js2-COMMA))
8641 (setq op-pos (- js2-token-beg pos)) ; relative
8642 (if (= (js2-peek-token) js2-YIELD)
8643 (js2-report-error "msg.yield.parenthesized"))
8644 (setq right (js2-parse-assign-expr)
8645 left pn
8646 pn (make-js2-infix-node :type js2-COMMA
8647 :pos pos
8648 :len (- js2-ts-cursor pos)
8649 :op-pos op-pos
8650 :left left
8651 :right right))
8652 (js2-node-add-children pn left right))
8653 pn))
8654
8655 (defun js2-parse-assign-expr ()
8656 (let ((tt (js2-peek-token))
8657 (pos js2-token-beg)
8658 pn
8659 left
8660 right
8661 op-pos)
8662 (if (= tt js2-YIELD)
8663 (js2-parse-return-or-yield tt t)
8664 ;; not yield - parse assignment expression
8665 (setq pn (js2-parse-cond-expr)
8666 tt (js2-peek-token))
8667 (when (and (<= js2-first-assign tt)
8668 (<= tt js2-last-assign))
8669 ;; tt express assignment (=, |=, ^=, ..., %=)
8670 (js2-consume-token)
8671 (setq op-pos (- js2-token-beg pos) ; relative
8672 left pn
8673 right (js2-parse-assign-expr)
8674 pn (make-js2-assign-node :type tt
8675 :pos pos
8676 :len (- (js2-node-end right) pos)
8677 :op-pos op-pos
8678 :left left
8679 :right right))
8680 (when js2-parse-ide-mode
8681 (js2-highlight-assign-targets pn left right)
8682 (js2-record-imenu-functions right left))
8683 ;; do this last so ide checks above can use absolute positions
8684 (js2-node-add-children pn left right))
8685 pn)))
8686
8687 (defun js2-parse-cond-expr ()
8688 (let ((pos js2-token-beg)
8689 (pn (js2-parse-or-expr))
8690 test-expr
8691 if-true
8692 if-false
8693 q-pos
8694 c-pos)
8695 (when (js2-match-token js2-HOOK)
8696 (setq q-pos (- js2-token-beg pos)
8697 if-true (js2-parse-assign-expr))
8698 (js2-must-match js2-COLON "msg.no.colon.cond")
8699 (setq c-pos (- js2-token-beg pos)
8700 if-false (js2-parse-assign-expr)
8701 test-expr pn
8702 pn (make-js2-cond-node :pos pos
8703 :len (- (js2-node-end if-false) pos)
8704 :test-expr test-expr
8705 :true-expr if-true
8706 :false-expr if-false
8707 :q-pos q-pos
8708 :c-pos c-pos))
8709 (js2-node-add-children pn test-expr if-true if-false))
8710 pn))
8711
8712 (defun js2-make-binary (type left parser)
8713 "Helper for constructing a binary-operator AST node.
8714 LEFT is the left-side-expression, already parsed, and the
8715 binary operator should have just been matched.
8716 PARSER is a function to call to parse the right operand,
8717 or a `js2-node' struct if it has already been parsed."
8718 (let* ((pos (js2-node-pos left))
8719 (op-pos (- js2-token-beg pos))
8720 (right (if (js2-node-p parser)
8721 parser
8722 (funcall parser)))
8723 (pn (make-js2-infix-node :type type
8724 :pos pos
8725 :len (- (js2-node-end right) pos)
8726 :op-pos op-pos
8727 :left left
8728 :right right)))
8729 (js2-node-add-children pn left right)
8730 pn))
8731
8732 (defun js2-parse-or-expr ()
8733 (let ((pn (js2-parse-and-expr)))
8734 (when (js2-match-token js2-OR)
8735 (setq pn (js2-make-binary js2-OR
8736 pn
8737 'js2-parse-or-expr)))
8738 pn))
8739
8740 (defun js2-parse-and-expr ()
8741 (let ((pn (js2-parse-bit-or-expr)))
8742 (when (js2-match-token js2-AND)
8743 (setq pn (js2-make-binary js2-AND
8744 pn
8745 'js2-parse-and-expr)))
8746 pn))
8747
8748 (defun js2-parse-bit-or-expr ()
8749 (let ((pn (js2-parse-bit-xor-expr)))
8750 (while (js2-match-token js2-BITOR)
8751 (setq pn (js2-make-binary js2-BITOR
8752 pn
8753 'js2-parse-bit-xor-expr)))
8754 pn))
8755
8756 (defun js2-parse-bit-xor-expr ()
8757 (let ((pn (js2-parse-bit-and-expr)))
8758 (while (js2-match-token js2-BITXOR)
8759 (setq pn (js2-make-binary js2-BITXOR
8760 pn
8761 'js2-parse-bit-and-expr)))
8762 pn))
8763
8764 (defun js2-parse-bit-and-expr ()
8765 (let ((pn (js2-parse-eq-expr)))
8766 (while (js2-match-token js2-BITAND)
8767 (setq pn (js2-make-binary js2-BITAND
8768 pn
8769 'js2-parse-eq-expr)))
8770 pn))
8771
8772 (defconst js2-parse-eq-ops
8773 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8774
8775 (defun js2-parse-eq-expr ()
8776 (let ((pn (js2-parse-rel-expr))
8777 tt)
8778 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8779 (js2-consume-token)
8780 (setq pn (js2-make-binary tt
8781 pn
8782 'js2-parse-rel-expr)))
8783 pn))
8784
8785 (defconst js2-parse-rel-ops
8786 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8787
8788 (defun js2-parse-rel-expr ()
8789 (let ((pn (js2-parse-shift-expr))
8790 (continue t)
8791 tt)
8792 (while continue
8793 (setq tt (js2-peek-token))
8794 (cond
8795 ((and js2-in-for-init (= tt js2-IN))
8796 (setq continue nil))
8797 ((memq tt js2-parse-rel-ops)
8798 (js2-consume-token)
8799 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8800 (t
8801 (setq continue nil))))
8802 pn))
8803
8804 (defconst js2-parse-shift-ops
8805 (list js2-LSH js2-URSH js2-RSH))
8806
8807 (defun js2-parse-shift-expr ()
8808 (let ((pn (js2-parse-add-expr))
8809 tt
8810 (continue t))
8811 (while continue
8812 (setq tt (js2-peek-token))
8813 (if (memq tt js2-parse-shift-ops)
8814 (progn
8815 (js2-consume-token)
8816 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8817 (setq continue nil)))
8818 pn))
8819
8820 (defun js2-parse-add-expr ()
8821 (let ((pn (js2-parse-mul-expr))
8822 tt
8823 (continue t))
8824 (while continue
8825 (setq tt (js2-peek-token))
8826 (if (or (= tt js2-ADD) (= tt js2-SUB))
8827 (progn
8828 (js2-consume-token)
8829 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8830 (setq continue nil)))
8831 pn))
8832
8833 (defconst js2-parse-mul-ops
8834 (list js2-MUL js2-DIV js2-MOD))
8835
8836 (defun js2-parse-mul-expr ()
8837 (let ((pn (js2-parse-unary-expr))
8838 tt
8839 (continue t))
8840 (while continue
8841 (setq tt (js2-peek-token))
8842 (if (memq tt js2-parse-mul-ops)
8843 (progn
8844 (js2-consume-token)
8845 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8846 (setq continue nil)))
8847 pn))
8848
8849 (defsubst js2-make-unary (type parser &rest args)
8850 "Make a unary node of type TYPE.
8851 PARSER is either a node (for postfix operators) or a function to call
8852 to parse the operand (for prefix operators)."
8853 (let* ((pos js2-token-beg)
8854 (postfix (js2-node-p parser))
8855 (expr (if postfix
8856 parser
8857 (apply parser args)))
8858 end
8859 pn)
8860 (if postfix ; e.g. i++
8861 (setq pos (js2-node-pos expr)
8862 end js2-token-end)
8863 (setq end (js2-node-end expr)))
8864 (setq pn (make-js2-unary-node :type type
8865 :pos pos
8866 :len (- end pos)
8867 :operand expr))
8868 (js2-node-add-children pn expr)
8869 pn))
8870
8871 (defconst js2-incrementable-node-types
8872 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8873 "Node types that can be the operand of a ++ or -- operator.")
8874
8875 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8876 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8877 js2-incrementable-node-types)
8878 (js2-report-error (if (= tt js2-INC)
8879 "msg.bad.incr"
8880 "msg.bad.decr")
8881 nil beg (- end beg))))
8882
8883 (defun js2-parse-unary-expr ()
8884 (let ((tt (js2-peek-token))
8885 pn expr beg end)
8886 (cond
8887 ((or (= tt js2-VOID)
8888 (= tt js2-NOT)
8889 (= tt js2-BITNOT)
8890 (= tt js2-TYPEOF))
8891 (js2-consume-token)
8892 (js2-make-unary tt 'js2-parse-unary-expr))
8893 ((= tt js2-ADD)
8894 (js2-consume-token)
8895 ;; Convert to special POS token in decompiler and parse tree
8896 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8897 ((= tt js2-SUB)
8898 (js2-consume-token)
8899 ;; Convert to special NEG token in decompiler and parse tree
8900 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8901 ((or (= tt js2-INC)
8902 (= tt js2-DEC))
8903 (js2-consume-token)
8904 (prog1
8905 (setq beg js2-token-beg
8906 end js2-token-end
8907 expr (js2-make-unary tt 'js2-parse-member-expr t))
8908 (js2-check-bad-inc-dec tt beg end expr)))
8909 ((= tt js2-DELPROP)
8910 (js2-consume-token)
8911 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8912 ((= tt js2-ERROR)
8913 (js2-consume-token)
8914 (make-js2-error-node)) ; try to continue
8915 ((and (= tt js2-LT)
8916 js2-compiler-xml-available)
8917 ;; XML stream encountered in expression.
8918 (js2-consume-token)
8919 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8920 (t
8921 (setq pn (js2-parse-member-expr t)
8922 ;; Don't look across a newline boundary for a postfix incop.
8923 tt (js2-peek-token-or-eol))
8924 (when (or (= tt js2-INC) (= tt js2-DEC))
8925 (js2-consume-token)
8926 (setf expr pn
8927 pn (js2-make-unary tt expr))
8928 (js2-node-set-prop pn 'postfix t)
8929 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8930 pn))))
8931
8932 (defun js2-parse-xml-initializer ()
8933 "Parse an E4X XML initializer.
8934 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8935 Then I'll postprocess the result, depending on whether we're in IDE
8936 mode or codegen mode, and generate the appropriate rewritten AST.
8937 IDE mode uses a rich AST that models the XML structure. Codegen mode
8938 just concatenates everything and makes a new XML or XMLList out of it."
8939 (let ((tt (js2-get-first-xml-token))
8940 pn-xml
8941 pn
8942 expr
8943 kids
8944 expr-pos
8945 (continue t)
8946 (first-token t))
8947 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8948 (js2-report-error "msg.syntax"))
8949 (setq pn-xml (make-js2-xml-node))
8950 (while continue
8951 (if first-token
8952 (setq first-token nil)
8953 (setq tt (js2-get-next-xml-token)))
8954 (cond
8955 ;; js2-XML means we found a {expr} in the XML stream.
8956 ;; The js2-ts-string is the XML up to the left-curly.
8957 ((= tt js2-XML)
8958 (push (make-js2-string-node :pos js2-token-beg
8959 :len (- js2-ts-cursor js2-token-beg))
8960 kids)
8961 (js2-must-match js2-LC "msg.syntax")
8962 (setq expr-pos js2-ts-cursor
8963 expr (if (eq (js2-peek-token) js2-RC)
8964 (make-js2-empty-expr-node :pos expr-pos)
8965 (js2-parse-expr)))
8966 (js2-must-match js2-RC "msg.syntax")
8967 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8968 :len (js2-node-len expr)
8969 :expr expr))
8970 (js2-node-add-children pn expr)
8971 (push pn kids))
8972 ;; a js2-XMLEND token means we hit the final close-tag.
8973 ((= tt js2-XMLEND)
8974 (push (make-js2-string-node :pos js2-token-beg
8975 :len (- js2-ts-cursor js2-token-beg))
8976 kids)
8977 (dolist (kid (nreverse kids))
8978 (js2-block-node-push pn-xml kid))
8979 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8980 (js2-node-pos pn-xml))
8981 continue nil))
8982 (t
8983 (js2-report-error "msg.syntax")
8984 (setq continue nil))))
8985 pn-xml))
8986
8987
8988 (defun js2-parse-argument-list ()
8989 "Parse an argument list and return it as a lisp list of nodes.
8990 Returns the list in reverse order. Consumes the right-paren token."
8991 (let (result)
8992 (unless (js2-match-token js2-RP)
8993 (loop do
8994 (if (= (js2-peek-token) js2-YIELD)
8995 (js2-report-error "msg.yield.parenthesized"))
8996 (push (js2-parse-assign-expr) result)
8997 while
8998 (js2-match-token js2-COMMA))
8999 (js2-must-match js2-RP "msg.no.paren.arg")
9000 result)))
9001
9002 (defun js2-parse-member-expr (&optional allow-call-syntax)
9003 (let ((tt (js2-peek-token))
9004 pn
9005 pos
9006 target
9007 args
9008 beg
9009 end
9010 init
9011 tail)
9012 (if (/= tt js2-NEW)
9013 (setq pn (js2-parse-primary-expr))
9014 ;; parse a 'new' expression
9015 (js2-consume-token)
9016 (setq pos js2-token-beg
9017 beg pos
9018 target (js2-parse-member-expr)
9019 end (js2-node-end target)
9020 pn (make-js2-new-node :pos pos
9021 :target target
9022 :len (- end pos)))
9023 (js2-node-add-children pn target)
9024 (when (js2-match-token js2-LP)
9025 ;; Add the arguments to pn, if any are supplied.
9026 (setf beg pos ; start of "new" keyword
9027 pos js2-token-beg
9028 args (nreverse (js2-parse-argument-list))
9029 (js2-new-node-args pn) args
9030 end js2-token-end
9031 (js2-new-node-lp pn) (- pos beg)
9032 (js2-new-node-rp pn) (- end 1 beg))
9033 (apply #'js2-node-add-children pn args))
9034 (when (and js2-allow-rhino-new-expr-initializer
9035 (js2-match-token js2-LC))
9036 (setf init (js2-parse-object-literal)
9037 end (js2-node-end init)
9038 (js2-new-node-initializer pn) init)
9039 (js2-node-add-children pn init))
9040 (setf (js2-node-len pn) (- end beg))) ; end outer if
9041 (js2-parse-member-expr-tail allow-call-syntax pn)))
9042
9043 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9044 "Parse a chain of property/array accesses or function calls.
9045 Includes parsing for E4X operators like `..' and `.@'.
9046 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9047 Returns an expression tree that includes PN, the parent node."
9048 (let ((beg (js2-node-pos pn))
9049 tt
9050 (continue t))
9051 (while continue
9052 (setq tt (js2-peek-token))
9053 (cond
9054 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9055 (setq pn (js2-parse-property-access tt pn)))
9056 ((= tt js2-DOTQUERY)
9057 (setq pn (js2-parse-dot-query pn)))
9058 ((= tt js2-LB)
9059 (setq pn (js2-parse-element-get pn)))
9060 ((= tt js2-LP)
9061 (if allow-call-syntax
9062 (setq pn (js2-parse-function-call pn))
9063 (setq continue nil)))
9064 (t
9065 (setq continue nil))))
9066 (if (>= js2-highlight-level 2)
9067 (js2-parse-highlight-member-expr-node pn))
9068 pn))
9069
9070 (defun js2-parse-dot-query (pn)
9071 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9072 Last token parsed must be `js2-DOTQUERY'."
9073 (let ((pos (js2-node-pos pn))
9074 op-pos
9075 expr
9076 end)
9077 (js2-consume-token)
9078 (js2-must-have-xml)
9079 (js2-set-requires-activation)
9080 (setq op-pos js2-token-beg
9081 expr (js2-parse-expr)
9082 end (js2-node-end expr)
9083 pn (make-js2-xml-dot-query-node :left pn
9084 :pos pos
9085 :op-pos op-pos
9086 :right expr))
9087 (js2-node-add-children pn
9088 (js2-xml-dot-query-node-left pn)
9089 (js2-xml-dot-query-node-right pn))
9090 (if (js2-must-match js2-RP "msg.no.paren")
9091 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9092 end js2-token-end))
9093 (setf (js2-node-len pn) (- end pos))
9094 pn))
9095
9096 (defun js2-parse-element-get (pn)
9097 "Parse an element-get expression, e.g. foo[bar].
9098 Last token parsed must be `js2-RB'."
9099 (let ((lb js2-token-beg)
9100 (pos (js2-node-pos pn))
9101 rb
9102 expr)
9103 (js2-consume-token)
9104 (setq expr (js2-parse-expr))
9105 (if (js2-must-match js2-RB "msg.no.bracket.index")
9106 (setq rb js2-token-beg))
9107 (setq pn (make-js2-elem-get-node :target pn
9108 :pos pos
9109 :element expr
9110 :lb (js2-relpos lb pos)
9111 :rb (js2-relpos rb pos)
9112 :len (- js2-token-end pos)))
9113 (js2-node-add-children pn
9114 (js2-elem-get-node-target pn)
9115 (js2-elem-get-node-element pn))
9116 pn))
9117
9118 (defun js2-parse-function-call (pn)
9119 (let (args
9120 (pos (js2-node-pos pn)))
9121 (js2-consume-token)
9122 (setq pn (make-js2-call-node :pos pos
9123 :target pn
9124 :lp (- js2-token-beg pos)))
9125 (js2-node-add-children pn (js2-call-node-target pn))
9126 ;; Add the arguments to pn, if any are supplied.
9127 (setf args (nreverse (js2-parse-argument-list))
9128 (js2-call-node-rp pn) (- js2-token-beg pos)
9129 (js2-call-node-args pn) args)
9130 (apply #'js2-node-add-children pn args)
9131 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9132 pn))
9133
9134 (defun js2-parse-property-access (tt pn)
9135 "Parse a property access, XML descendants access, or XML attr access."
9136 (let ((member-type-flags 0)
9137 (dot-pos js2-token-beg)
9138 (dot-len (if (= tt js2-DOTDOT) 2 1))
9139 name
9140 ref ; right side of . or .. operator
9141 result)
9142 (js2-consume-token)
9143 (when (= tt js2-DOTDOT)
9144 (js2-must-have-xml)
9145 (setq member-type-flags js2-descendants-flag))
9146 (if (not js2-compiler-xml-available)
9147 (progn
9148 (js2-must-match-prop-name "msg.no.name.after.dot")
9149 (setq name (js2-create-name-node t js2-GETPROP)
9150 result (make-js2-prop-get-node :left pn
9151 :pos js2-token-beg
9152 :right name
9153 :len (- js2-token-end
9154 js2-token-beg)))
9155 (js2-node-add-children result pn name)
9156 result)
9157 ;; otherwise look for XML operators
9158 (setf result (if (= tt js2-DOT)
9159 (make-js2-prop-get-node)
9160 (make-js2-infix-node :type js2-DOTDOT))
9161 (js2-node-pos result) (js2-node-pos pn)
9162 (js2-infix-node-op-pos result) dot-pos
9163 (js2-infix-node-left result) pn ; do this after setting position
9164 tt (js2-next-token))
9165 (cond
9166 ;; needed for generator.throw()
9167 ((= tt js2-THROW)
9168 (js2-save-name-token-data js2-token-beg "throw")
9169 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9170 ;; handles: name, ns::name, ns::*, ns::[expr]
9171 ((js2-valid-prop-name-token tt)
9172 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9173 ;; handles: *, *::name, *::*, *::[expr]
9174 ((= tt js2-MUL)
9175 (js2-save-name-token-data js2-token-beg "*")
9176 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9177 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9178 ((= tt js2-XMLATTR)
9179 (setq result (js2-parse-attribute-access)))
9180 (t
9181 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9182 (if ref
9183 (setf (js2-node-len result) (- (js2-node-end ref)
9184 (js2-node-pos result))
9185 (js2-infix-node-right result) ref))
9186 (if (js2-infix-node-p result)
9187 (js2-node-add-children result
9188 (js2-infix-node-left result)
9189 (js2-infix-node-right result)))
9190 result)))
9191
9192 (defun js2-parse-attribute-access ()
9193 "Parse an E4X XML attribute expression.
9194 This includes expressions of the forms:
9195
9196 @attr @ns::attr @ns::*
9197 @* @*::attr @*::*
9198 @[expr] @*::[expr] @ns::[expr]
9199
9200 Called if we peeked an '@' token."
9201 (let ((tt (js2-next-token))
9202 (at-pos js2-token-beg))
9203 (cond
9204 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9205 ((js2-valid-prop-name-token tt)
9206 (js2-parse-property-name at-pos js2-ts-string 0))
9207 ;; handles: @*, @*::name, @*::*, @*::[expr]
9208 ((= tt js2-MUL)
9209 (js2-save-name-token-data js2-token-beg "*")
9210 (js2-parse-property-name js2-token-beg "*" 0))
9211 ;; handles @[expr]
9212 ((= tt js2-LB)
9213 (js2-parse-xml-elem-ref at-pos))
9214 (t
9215 (js2-report-error "msg.no.name.after.xmlAttr")
9216 ;; Avoid cascaded errors that happen if we make an error node here.
9217 (js2-save-name-token-data js2-token-beg "")
9218 (js2-parse-property-name js2-token-beg "" 0)))))
9219
9220 (defun js2-parse-property-name (at-pos s member-type-flags)
9221 "Check if :: follows name in which case it becomes qualified name.
9222
9223 AT-POS is a natural number if we just read an '@' token, else nil.
9224 S is the name or string that was matched: an identifier, 'throw' or '*'.
9225 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9226
9227 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9228 operator, or the name is followed by ::. For a plain name, returns a
9229 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9230 (let ((pos (or at-pos js2-token-beg))
9231 colon-pos
9232 (name (js2-create-name-node t js2-current-token))
9233 ns
9234 tt
9235 ref
9236 pn)
9237 (catch 'return
9238 (when (js2-match-token js2-COLONCOLON)
9239 (setq ns name
9240 colon-pos js2-token-beg
9241 tt (js2-next-token))
9242 (cond
9243 ;; handles name::name
9244 ((js2-valid-prop-name-token tt)
9245 (setq name (js2-create-name-node)))
9246 ;; handles name::*
9247 ((= tt js2-MUL)
9248 (js2-save-name-token-data js2-token-beg "*")
9249 (setq name (js2-create-name-node)))
9250 ;; handles name::[expr]
9251 ((= tt js2-LB)
9252 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9253 (t
9254 (js2-report-error "msg.no.name.after.coloncolon"))))
9255 (if (and (null ns) (zerop member-type-flags))
9256 name
9257 (prog1
9258 (setq pn
9259 (make-js2-xml-prop-ref-node :pos pos
9260 :len (- (js2-node-end name) pos)
9261 :at-pos at-pos
9262 :colon-pos colon-pos
9263 :propname name))
9264 (js2-node-add-children pn name))))))
9265
9266 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9267 "Parse the [expr] portion of an xml element reference.
9268 For instance, @[expr], @*::[expr], or ns::[expr]."
9269 (let* ((lb js2-token-beg)
9270 (pos (or at-pos lb))
9271 rb
9272 (expr (js2-parse-expr))
9273 (end (js2-node-end expr))
9274 pn)
9275 (if (js2-must-match js2-RB "msg.no.bracket.index")
9276 (setq rb js2-token-beg
9277 end js2-token-end))
9278 (prog1
9279 (setq pn
9280 (make-js2-xml-elem-ref-node :pos pos
9281 :len (- end pos)
9282 :namespace namespace
9283 :colon-pos colon-pos
9284 :at-pos at-pos
9285 :expr expr
9286 :lb (js2-relpos lb pos)
9287 :rb (js2-relpos rb pos)))
9288 (js2-node-add-children pn namespace expr))))
9289
9290 (defun js2-parse-primary-expr-lhs ()
9291 (let ((js2-is-in-lhs t))
9292 (js2-parse-primary-expr)))
9293
9294 (defun js2-parse-primary-expr ()
9295 "Parses a literal (leaf) expression of some sort.
9296 Includes complex literals such as functions, object-literals,
9297 array-literals, array comprehensions and regular expressions."
9298 (let ((tt-flagged (js2-next-flagged-token))
9299 pn ; parent node (usually return value)
9300 tt
9301 px-pos ; paren-expr pos
9302 len
9303 flags ; regexp flags
9304 expr)
9305 (setq tt js2-current-token)
9306 (cond
9307 ((= tt js2-FUNCTION)
9308 (js2-parse-function 'FUNCTION_EXPRESSION))
9309 ((= tt js2-LB)
9310 (js2-parse-array-literal))
9311 ((= tt js2-LC)
9312 (js2-parse-object-literal))
9313 ((= tt js2-LET)
9314 (js2-parse-let js2-token-beg))
9315 ((= tt js2-LP)
9316 (setq px-pos js2-token-beg
9317 expr (js2-parse-expr))
9318 (js2-must-match js2-RP "msg.no.paren")
9319 (setq pn (make-js2-paren-node :pos px-pos
9320 :expr expr
9321 :len (- js2-token-end px-pos)))
9322 (js2-node-add-children pn (js2-paren-node-expr pn))
9323 pn)
9324 ((= tt js2-XMLATTR)
9325 (js2-must-have-xml)
9326 (js2-parse-attribute-access))
9327 ((= tt js2-NAME)
9328 (js2-parse-name tt-flagged tt))
9329 ((= tt js2-NUMBER)
9330 (make-js2-number-node))
9331 ((= tt js2-STRING)
9332 (prog1
9333 (make-js2-string-node)
9334 (js2-record-face 'font-lock-string-face)))
9335 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9336 ;; Got / or /= which in this context means a regexp literal
9337 (setq px-pos js2-token-beg)
9338 (js2-read-regexp tt)
9339 (setq flags js2-ts-regexp-flags
9340 js2-ts-regexp-flags nil)
9341 (prog1
9342 (make-js2-regexp-node :pos px-pos
9343 :len (- js2-ts-cursor px-pos)
9344 :value js2-ts-string
9345 :flags flags)
9346 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9347 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9348 ((or (= tt js2-NULL)
9349 (= tt js2-THIS)
9350 (= tt js2-FALSE)
9351 (= tt js2-TRUE))
9352 (make-js2-keyword-node :type tt))
9353 ((= tt js2-RESERVED)
9354 (js2-report-error "msg.reserved.id")
9355 (make-js2-name-node))
9356 ((= tt js2-ERROR)
9357 ;; the scanner or one of its subroutines reported the error.
9358 (make-js2-error-node))
9359 ((= tt js2-EOF)
9360 (setq px-pos (point-at-bol)
9361 len (- js2-ts-cursor px-pos))
9362 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9363 (make-js2-error-node :pos px-pos :len len))
9364 (t
9365 (js2-report-error "msg.syntax")
9366 (make-js2-error-node)))))
9367
9368 (defun js2-parse-name (tt-flagged tt)
9369 (let ((name js2-ts-string)
9370 (name-pos js2-token-beg)
9371 node)
9372 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9373 (= (js2-peek-token) js2-COLON))
9374 (prog1
9375 ;; Do not consume colon, it is used as unwind indicator
9376 ;; to return to statementHelper.
9377 (make-js2-label-node :pos name-pos
9378 :len (- js2-token-end name-pos)
9379 :name name)
9380 (js2-set-face name-pos
9381 js2-token-end
9382 'font-lock-variable-name-face 'record))
9383 ;; Otherwise not a label, just a name. Unfortunately peeking
9384 ;; the next token to check for a colon has biffed js2-token-beg
9385 ;; and js2-token-end. We store the name's bounds in buffer vars
9386 ;; and `js2-create-name-node' uses them.
9387 (js2-save-name-token-data name-pos name)
9388 (setq node (if js2-compiler-xml-available
9389 (js2-parse-property-name nil name 0)
9390 (js2-create-name-node 'check-activation)))
9391 (if js2-highlight-external-variables
9392 (js2-record-name-node node))
9393 node)))
9394
9395 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9396 (js2-add-strict-warning
9397 msg nil
9398 ;; back up from comma to beginning of line or array/objlit
9399 (max (if elems
9400 (js2-node-pos (car elems))
9401 pos)
9402 (save-excursion
9403 (goto-char comma-pos)
9404 (back-to-indentation)
9405 (point)))
9406 comma-pos))
9407
9408 (defun js2-parse-array-literal ()
9409 (let ((pos js2-token-beg)
9410 (end js2-token-end)
9411 (after-lb-or-comma t)
9412 after-comma
9413 tt
9414 elems
9415 pn
9416 (continue t))
9417 (unless js2-is-in-lhs
9418 (js2-push-scope (make-js2-scope))) ; for array comp
9419 (while continue
9420 (setq tt (js2-peek-token))
9421 (cond
9422 ;; comma
9423 ((= tt js2-COMMA)
9424 (js2-consume-token)
9425 (setq after-comma js2-token-end)
9426 (if (not after-lb-or-comma)
9427 (setq after-lb-or-comma t)
9428 (push nil elems)))
9429 ;; end of array
9430 ((or (= tt js2-RB)
9431 (= tt js2-EOF)) ; prevent infinite loop
9432 (if (= tt js2-EOF)
9433 (js2-report-error "msg.no.bracket.arg" nil pos)
9434 (js2-consume-token))
9435 (setq continue nil
9436 end js2-token-end
9437 pn (make-js2-array-node :pos pos
9438 :len (- js2-ts-cursor pos)
9439 :elems (nreverse elems)))
9440 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9441 (when (and after-comma (not js2-is-in-lhs))
9442 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9443 pos elems after-comma)))
9444 ;; destructuring binding
9445 (js2-is-in-lhs
9446 (push (if (or (= tt js2-LC)
9447 (= tt js2-LB)
9448 (= tt js2-NAME))
9449 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9450 (js2-parse-primary-expr-lhs)
9451 ;; invalid pattern
9452 (js2-consume-token)
9453 (js2-report-error "msg.bad.var")
9454 (make-js2-error-node))
9455 elems)
9456 (setq after-lb-or-comma nil
9457 after-comma nil))
9458 ;; array comp
9459 ((and (>= js2-language-version 170)
9460 (= tt js2-FOR) ; check for array comprehension
9461 (not after-lb-or-comma) ; "for" can't follow a comma
9462 elems ; must have at least 1 element
9463 (not (cdr elems))) ; but no 2nd element
9464 (setf continue nil
9465 pn (js2-parse-array-comprehension (car elems) pos)))
9466
9467 ;; another element
9468 (t
9469 (unless after-lb-or-comma
9470 (js2-report-error "msg.no.bracket.arg"))
9471 (push (js2-parse-assign-expr) elems)
9472 (setq after-lb-or-comma nil
9473 after-comma nil))))
9474 (unless js2-is-in-lhs
9475 (js2-pop-scope))
9476 pn))
9477
9478 (defun js2-parse-array-comprehension (expr pos)
9479 "Parse a JavaScript 1.7 Array Comprehension.
9480 EXPR is the first expression after the opening left-bracket.
9481 POS is the beginning of the LB token preceding EXPR.
9482 We should have just parsed the 'for' keyword before calling this function."
9483 (let (loops
9484 loop
9485 first
9486 prev
9487 filter
9488 if-pos
9489 result)
9490 (while (= (js2-peek-token) js2-FOR)
9491 (let ((prev (car loops))) ; rearrange scope chain
9492 (push (setq loop (js2-parse-array-comp-loop)) loops)
9493 (if prev ; each loop is parent scope to the next one
9494 (setf (js2-scope-parent-scope loop) prev)
9495 ; first loop takes expr scope's parent
9496 (setf (js2-scope-parent-scope (setq first loop))
9497 (js2-scope-parent-scope js2-current-scope)))))
9498 ;; set expr scope's parent to the last loop
9499 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9500 (when (= (js2-peek-token) js2-IF)
9501 (js2-consume-token)
9502 (setq if-pos (- js2-token-beg pos) ; relative
9503 filter (js2-parse-condition)))
9504 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9505 (setq result (make-js2-array-comp-node :pos pos
9506 :len (- js2-ts-cursor pos)
9507 :result expr
9508 :loops (nreverse loops)
9509 :filter (car filter)
9510 :lp (js2-relpos (second filter) pos)
9511 :rp (js2-relpos (third filter) pos)
9512 :if-pos if-pos))
9513 (apply #'js2-node-add-children result expr (car filter)
9514 (js2-array-comp-node-loops result))
9515 (setq js2-current-scope first) ; pop to the first loop
9516 result))
9517
9518 (defun js2-parse-array-comp-loop ()
9519 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9520 Last token peeked should be the initial FOR."
9521 (let ((pos js2-token-beg)
9522 (pn (make-js2-array-comp-loop-node))
9523 tt
9524 iter
9525 obj
9526 foreach-p
9527 forof-p
9528 in-pos
9529 each-pos
9530 lp
9531 rp)
9532 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9533 (js2-push-scope pn)
9534 (unwind-protect
9535 (progn
9536 (when (js2-match-token js2-NAME)
9537 (if (string= js2-ts-string "each")
9538 (progn
9539 (setq foreach-p t
9540 each-pos (- js2-token-beg pos)) ; relative
9541 (js2-record-face 'font-lock-keyword-face))
9542 (js2-report-error "msg.no.paren.for")))
9543 (if (js2-must-match js2-LP "msg.no.paren.for")
9544 (setq lp (- js2-token-beg pos)))
9545 (setq tt (js2-peek-token))
9546 (cond
9547 ((or (= tt js2-LB)
9548 (= tt js2-LC))
9549 ;; handle destructuring assignment
9550 (setq iter (js2-parse-primary-expr-lhs))
9551 (js2-define-destruct-symbols iter js2-LET
9552 'font-lock-variable-name-face t))
9553 ((js2-match-token js2-NAME)
9554 (setq iter (js2-create-name-node)))
9555 (t
9556 (js2-report-error "msg.bad.var")))
9557 ;; Define as a let since we want the scope of the variable to
9558 ;; be restricted to the array comprehension
9559 (if (js2-name-node-p iter)
9560 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9561 (if (or (js2-match-token js2-IN)
9562 (and (>= js2-language-version 200)
9563 (js2-match-contextual-kwd "of")
9564 (setq forof-p t)))
9565 (setq in-pos (- js2-token-beg pos))
9566 (js2-report-error "msg.in.after.for.name"))
9567 (setq obj (js2-parse-expr))
9568 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9569 (setq rp (- js2-token-beg pos)))
9570 (setf (js2-node-pos pn) pos
9571 (js2-node-len pn) (- js2-ts-cursor pos)
9572 (js2-array-comp-loop-node-iterator pn) iter
9573 (js2-array-comp-loop-node-object pn) obj
9574 (js2-array-comp-loop-node-in-pos pn) in-pos
9575 (js2-array-comp-loop-node-each-pos pn) each-pos
9576 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9577 (js2-array-comp-loop-node-forof-p pn) forof-p
9578 (js2-array-comp-loop-node-lp pn) lp
9579 (js2-array-comp-loop-node-rp pn) rp)
9580 (js2-node-add-children pn iter obj))
9581 (js2-pop-scope))
9582 pn))
9583
9584 (defun js2-parse-object-literal ()
9585 (let ((pos js2-token-beg)
9586 tt
9587 elems
9588 result
9589 after-comma
9590 (continue t))
9591 (while continue
9592 (setq tt (js2-peek-token))
9593 (cond
9594 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9595 ((or (js2-valid-prop-name-token tt)
9596 (= tt js2-STRING))
9597 (setq after-comma nil
9598 result (js2-parse-named-prop tt))
9599 (if (and (null result)
9600 (not js2-recover-from-parse-errors))
9601 (setq continue nil)
9602 (push result elems)))
9603 ;; {12: x} or {10.7: x}
9604 ((= tt js2-NUMBER)
9605 (js2-consume-token)
9606 (setq after-comma nil)
9607 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9608 ;; trailing comma
9609 ((= tt js2-RC)
9610 (setq continue nil)
9611 (if after-comma
9612 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9613 pos elems after-comma)))
9614 (t
9615 (js2-report-error "msg.bad.prop")
9616 (unless js2-recover-from-parse-errors
9617 (setq continue nil)))) ; end switch
9618 (if (js2-match-token js2-COMMA)
9619 (setq after-comma js2-token-end)
9620 (setq continue nil))) ; end loop
9621 (js2-must-match js2-RC "msg.no.brace.prop")
9622 (setq result (make-js2-object-node :pos pos
9623 :len (- js2-ts-cursor pos)
9624 :elems (nreverse elems)))
9625 (apply #'js2-node-add-children result (js2-object-node-elems result))
9626 result))
9627
9628 (defun js2-parse-named-prop (tt)
9629 "Parse a name, string, or getter/setter object property.
9630 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9631 (js2-consume-token)
9632 (let ((string-prop (and (= tt js2-STRING)
9633 (make-js2-string-node)))
9634 expr
9635 (ppos js2-token-beg)
9636 (pend js2-token-end)
9637 (name (js2-create-name-node))
9638 (prop js2-ts-string))
9639 (cond
9640 ;; getter/setter prop
9641 ((and (= tt js2-NAME)
9642 (= (js2-peek-token) js2-NAME)
9643 (or (string= prop "get")
9644 (string= prop "set")))
9645 (js2-consume-token)
9646 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9647 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9648 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9649 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9650 ;; abbreviated destructuring bind e.g., {a, b} = c;
9651 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9652 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9653 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9654 ;; assignment but it's difficult because it requires looking ahead of expression.
9655 ((and js2-is-in-lhs
9656 (= tt js2-NAME)
9657 (let ((ctk (js2-peek-token)))
9658 (or (= ctk js2-COMMA)
9659 (= ctk js2-RC)
9660 (js2-valid-prop-name-token ctk))))
9661 name)
9662 ;; regular prop
9663 (t
9664 (prog1
9665 (setq expr (js2-parse-plain-property (or string-prop name)))
9666 (js2-set-face ppos pend
9667 (if (js2-function-node-p
9668 (js2-object-prop-node-right expr))
9669 'font-lock-function-name-face
9670 'font-lock-variable-name-face)
9671 'record))))))
9672
9673 (defun js2-parse-plain-property (prop)
9674 "Parse a non-getter/setter property in an object literal.
9675 PROP is the node representing the property: a number, name or string."
9676 (js2-must-match js2-COLON "msg.no.colon.prop")
9677 (let* ((pos (js2-node-pos prop))
9678 (colon (- js2-token-beg pos))
9679 (expr (js2-parse-assign-expr))
9680 (result (make-js2-object-prop-node
9681 :pos pos
9682 ;; don't include last consumed token in length
9683 :len (- (+ (js2-node-pos expr)
9684 (js2-node-len expr))
9685 pos)
9686 :left prop
9687 :right expr
9688 :op-pos colon)))
9689 (js2-node-add-children result prop expr)
9690 result))
9691
9692 (defun js2-parse-getter-setter-prop (pos prop get-p)
9693 "Parse getter or setter property in an object literal.
9694 JavaScript syntax is:
9695
9696 { get foo() {...}, set foo(x) {...} }
9697
9698 and expression closure style is also supported
9699
9700 { get foo() x, set foo(x) _x = x }
9701
9702 POS is the start position of the `get' or `set' keyword.
9703 PROP is the `js2-name-node' representing the property name.
9704 GET-P is non-nil if the keyword was `get'."
9705 (let ((type (if get-p js2-GET js2-SET))
9706 result
9707 end
9708 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9709 ;; it has to be an anonymous function, as we already parsed the name
9710 (if (/= (js2-node-type fn) js2-FUNCTION)
9711 (js2-report-error "msg.bad.prop")
9712 (if (plusp (length (js2-function-name fn)))
9713 (js2-report-error "msg.bad.prop")))
9714 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9715 (setq end (js2-node-end fn)
9716 result (make-js2-getter-setter-node :type type
9717 :pos pos
9718 :len (- end pos)
9719 :left prop
9720 :right fn))
9721 (js2-node-add-children result prop fn)
9722 result))
9723
9724 (defun js2-create-name-node (&optional check-activation-p token)
9725 "Create a name node using the token info from last scanned name.
9726 In some cases we need to either synthesize a name node, or we lost
9727 the name token information by peeking. If the TOKEN parameter is
9728 not `js2-NAME', then we use the token info saved in instance vars."
9729 (let ((beg js2-token-beg)
9730 (s js2-ts-string)
9731 name)
9732 (when (/= js2-current-token js2-NAME)
9733 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9734 s js2-prev-name-token-string
9735 js2-prev-name-token-start nil
9736 js2-prev-name-token-string nil))
9737 (setq name (make-js2-name-node :pos beg
9738 :name s
9739 :len (length s)))
9740 (if check-activation-p
9741 (js2-check-activation-name s (or token js2-NAME)))
9742 name))
9743
9744 ;;; Indentation support
9745
9746 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9747 ;; Karl cleverly deduces that the desired indentation level is often a
9748 ;; function of paren/bracket/brace nesting depth, which can be determined
9749 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9750 ;; then does some equally clever checks to see if we're in the context of a
9751 ;; substatement of a possibly braceless statement keyword such as if, while,
9752 ;; or finally. This approach yields pretty good results.
9753
9754 ;; The indenter is often "wrong", however, and needs to be overridden.
9755 ;; The right long-term solution is probably to emulate (or integrate
9756 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9757 ;; parse tree from `js2-parse' is present, which is not true at the
9758 ;; moment the user is typing, computing indentation is still thousands
9759 ;; of lines of code to handle every possible syntactic edge case.
9760
9761 ;; In the meantime, the compromise solution is that we offer a "bounce
9762 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9763 ;; current line indent among various likely guess points. This approach
9764 ;; is far from perfect, but should at least make it slightly easier to
9765 ;; move the line towards its desired indentation when manually
9766 ;; overriding Karl's heuristic nesting guesser.
9767
9768 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9769 ;; extensions such as `let' and Array comprehensions. Major kudos to
9770 ;; Karl for coming up with the initial approach, which packs a lot of
9771 ;; punch for so little code.
9772
9773 (defconst js2-possibly-braceless-keywords-re
9774 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9775 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9776 "try" "while" "with" "let")))
9777 "Regular expression matching keywords that are optionally
9778 followed by an opening brace.")
9779
9780 (defconst js2-indent-operator-re
9781 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9782 (regexp-opt '("in" "instanceof") 'words))
9783 "Regular expression matching operators that affect indentation
9784 of continued expressions.")
9785
9786 (defconst js2-declaration-keyword-re
9787 (regexp-opt '("var" "let" "const") 'words)
9788 "Regular expression matching variable declaration keywords.")
9789
9790 ;; This function has horrible results if you're typing an array
9791 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9792 ;; in conjunction with electric-indent, so just disabling it.
9793 (defsubst js2-code-at-bol-p ()
9794 "Return t if the first character on line is non-whitespace."
9795 nil)
9796
9797 (defun js2-insert-and-indent (key)
9798 "Run command bound to key and indent current line. Runs the command
9799 bound to KEY in the global keymap and indents the current line."
9800 (interactive (list (this-command-keys)))
9801 (let ((cmd (lookup-key (current-global-map) key)))
9802 (if (commandp cmd)
9803 (call-interactively cmd)))
9804 ;; don't do the electric keys inside comments or strings,
9805 ;; and don't do bounce-indent with them.
9806 (let ((parse-state (syntax-ppss (point)))
9807 (js2-bounce-indent-p (js2-code-at-bol-p)))
9808 (unless (or (nth 3 parse-state)
9809 (nth 4 parse-state))
9810 (indent-according-to-mode))))
9811
9812 (defun js2-re-search-forward-inner (regexp &optional bound count)
9813 "Auxiliary function for `js2-re-search-forward'."
9814 (let (parse saved-point)
9815 (while (> count 0)
9816 (re-search-forward regexp bound)
9817 (setq parse (if saved-point
9818 (parse-partial-sexp saved-point (point))
9819 (syntax-ppss (point))))
9820 (cond ((nth 3 parse)
9821 (re-search-forward
9822 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9823 (save-excursion (end-of-line) (point)) t))
9824 ((nth 7 parse)
9825 (forward-line))
9826 ((or (nth 4 parse)
9827 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9828 (re-search-forward "\\*/"))
9829 (t
9830 (setq count (1- count))))
9831 (setq saved-point (point))))
9832 (point))
9833
9834 (defun js2-re-search-forward (regexp &optional bound noerror count)
9835 "Search forward but ignore strings and comments. Invokes
9836 `re-search-forward' but treats the buffer as if strings and
9837 comments have been removed."
9838 (let ((saved-point (point))
9839 (search-expr
9840 (cond ((null count)
9841 '(js2-re-search-forward-inner regexp bound 1))
9842 ((< count 0)
9843 '(js2-re-search-backward-inner regexp bound (- count)))
9844 ((> count 0)
9845 '(js2-re-search-forward-inner regexp bound count)))))
9846 (condition-case err
9847 (eval search-expr)
9848 (search-failed
9849 (goto-char saved-point)
9850 (unless noerror
9851 (error (error-message-string err)))))))
9852
9853 (defun js2-re-search-backward-inner (regexp &optional bound count)
9854 "Auxiliary function for `js2-re-search-backward'."
9855 (let (parse saved-point)
9856 (while (> count 0)
9857 (re-search-backward regexp bound)
9858 (setq parse (if saved-point
9859 (parse-partial-sexp saved-point (point))
9860 (syntax-ppss (point))))
9861 (cond ((nth 3 parse)
9862 (re-search-backward
9863 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9864 (save-excursion (beginning-of-line) (point)) t))
9865 ((nth 7 parse)
9866 (goto-char (nth 8 parse)))
9867 ((or (nth 4 parse)
9868 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9869 (re-search-backward "/\\*"))
9870 (t
9871 (setq count (1- count))))))
9872 (point))
9873
9874 (defun js2-re-search-backward (regexp &optional bound noerror count)
9875 "Search backward but ignore strings and comments. Invokes
9876 `re-search-backward' but treats the buffer as if strings and
9877 comments have been removed."
9878 (let ((saved-point (point))
9879 (search-expr
9880 (cond ((null count)
9881 '(js2-re-search-backward-inner regexp bound 1))
9882 ((< count 0)
9883 '(js2-re-search-forward-inner regexp bound (- count)))
9884 ((> count 0)
9885 '(js2-re-search-backward-inner regexp bound count)))))
9886 (condition-case err
9887 (eval search-expr)
9888 (search-failed
9889 (goto-char saved-point)
9890 (unless noerror
9891 (error (error-message-string err)))))))
9892
9893 (defun js2-looking-at-operator-p ()
9894 "Return non-nil if text after point is an operator (that is not
9895 a comma)."
9896 (save-match-data
9897 (and (looking-at js2-indent-operator-re)
9898 (or (not (looking-at ":"))
9899 (save-excursion
9900 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9901 (looking-at "?")))))))
9902
9903 (defun js2-continued-expression-p ()
9904 "Returns non-nil if the current line continues an expression."
9905 (save-excursion
9906 (back-to-indentation)
9907 (or (js2-looking-at-operator-p)
9908 ;; comment
9909 (and (js2-re-search-backward "\n" nil t)
9910 (progn
9911 (skip-chars-backward " \t")
9912 (unless (bolp)
9913 (backward-char)
9914 (and (js2-looking-at-operator-p)
9915 (and (progn
9916 (backward-char)
9917 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))))))
9918
9919 (defun js2-end-of-do-while-loop-p ()
9920 "Returns non-nil if word after point is `while' of a do-while
9921 statement, else returns nil. A braceless do-while statement
9922 spanning several lines requires that the start of the loop is
9923 indented to the same column as the current line."
9924 (interactive)
9925 (save-excursion
9926 (save-match-data
9927 (when (looking-at "\\s-*\\<while\\>")
9928 (if (save-excursion
9929 (skip-chars-backward "[ \t\n]*}")
9930 (looking-at "[ \t\n]*}"))
9931 (save-excursion
9932 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9933 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9934 (or (looking-at "\\<do\\>")
9935 (let ((saved-indent (current-indentation)))
9936 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9937 (/= (current-indentation) saved-indent)))
9938 (and (looking-at "[ \t]*\\<do\\>")
9939 (not (js2-re-search-forward
9940 "\\<while\\>" (point-at-eol) t))
9941 (= (current-indentation) saved-indent)))))))))
9942
9943 (defun js2-multiline-decl-indentation ()
9944 "Returns the declaration indentation column if the current line belongs
9945 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9946 (let (forward-sexp-function ; use Lisp version
9947 at-opening-bracket)
9948 (save-excursion
9949 (back-to-indentation)
9950 (when (not (looking-at js2-declaration-keyword-re))
9951 (when (looking-at js2-indent-operator-re)
9952 (goto-char (match-end 0))) ; continued expressions are ok
9953 (while (and (not at-opening-bracket)
9954 (not (bobp))
9955 (let ((pos (point)))
9956 (save-excursion
9957 (js2-backward-sws)
9958 (or (eq (char-before) ?,)
9959 (and (not (eq (char-before) ?\;))
9960 (and
9961 (prog2 (skip-chars-backward "[[:punct:]]")
9962 (looking-at js2-indent-operator-re)
9963 (js2-backward-sws))
9964 (not (eq (char-before) ?\;))))
9965 (js2-same-line pos)))))
9966 (condition-case err
9967 (backward-sexp)
9968 (scan-error (setq at-opening-bracket t))))
9969 (when (looking-at js2-declaration-keyword-re)
9970 (- (1+ (match-end 0)) (point-at-bol)))))))
9971
9972 (defun js2-ctrl-statement-indentation ()
9973 "Returns the proper indentation of the current line if it
9974 starts the body of a control statement without braces, else
9975 returns nil."
9976 (let (forward-sexp-function) ; temporarily unbind it
9977 (save-excursion
9978 (back-to-indentation)
9979 (when (and (not (js2-same-line (point-min)))
9980 (not (looking-at "{"))
9981 (js2-re-search-backward "[[:graph:]]" nil t)
9982 (not (looking-at "[{([]"))
9983 (progn
9984 (forward-char)
9985 (when (= (char-before) ?\))
9986 ;; scan-sexps sometimes throws an error
9987 (ignore-errors (backward-sexp))
9988 (skip-chars-backward " \t" (point-at-bol)))
9989 (let ((pt (point)))
9990 (back-to-indentation)
9991 (and (looking-at js2-possibly-braceless-keywords-re)
9992 (= (match-end 0) pt)
9993 (not (js2-end-of-do-while-loop-p))))))
9994 (+ (current-indentation) js2-basic-offset)))))
9995
9996 (defun js2-indent-in-array-comp (parse-status)
9997 "Return non-nil if we think we're in an array comprehension.
9998 In particular, return the buffer position of the first `for' kwd."
9999 (let ((bracket (nth 1 parse-status))
10000 (end (point)))
10001 (when bracket
10002 (save-excursion
10003 (goto-char bracket)
10004 (when (looking-at "\\[")
10005 (forward-char 1)
10006 (js2-forward-sws)
10007 (if (looking-at "[[{]")
10008 (let (forward-sexp-function) ; use lisp version
10009 (forward-sexp) ; skip destructuring form
10010 (js2-forward-sws)
10011 (if (and (/= (char-after) ?,) ; regular array
10012 (looking-at "for"))
10013 (match-beginning 0)))
10014 ;; to skip arbitrary expressions we need the parser,
10015 ;; so we'll just guess at it.
10016 (if (and (> end (point)) ; not empty literal
10017 (re-search-forward "[^,]]* \\(for\\) " end t)
10018 ;; not inside comment or string literal
10019 (let ((state (parse-partial-sexp bracket (point))))
10020 (not (or (nth 3 state) (nth 4 state)))))
10021 (match-beginning 1))))))))
10022
10023 (defun js2-array-comp-indentation (parse-status for-kwd)
10024 (if (js2-same-line for-kwd)
10025 ;; first continuation line
10026 (save-excursion
10027 (goto-char (nth 1 parse-status))
10028 (forward-char 1)
10029 (skip-chars-forward " \t")
10030 (current-column))
10031 (save-excursion
10032 (goto-char for-kwd)
10033 (current-column))))
10034
10035 (defun js2-proper-indentation (parse-status)
10036 "Return the proper indentation for the current line."
10037 (save-excursion
10038 (back-to-indentation)
10039 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10040 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
10041 (continued-expr-p (js2-continued-expression-p))
10042 (declaration-indent (and js2-pretty-multiline-declarations
10043 (js2-multiline-decl-indentation)))
10044 (bracket (nth 1 parse-status))
10045 beg)
10046 (cond
10047 ;; indent array comprehension continuation lines specially
10048 ((and bracket
10049 (>= js2-language-version 170)
10050 (not (js2-same-line bracket))
10051 (setq beg (js2-indent-in-array-comp parse-status))
10052 (>= (point) (save-excursion
10053 (goto-char beg)
10054 (point-at-bol)))) ; at or after first loop?
10055 (js2-array-comp-indentation parse-status beg))
10056
10057 (ctrl-stmt-indent)
10058
10059 ((and declaration-indent continued-expr-p)
10060 (+ declaration-indent js2-basic-offset))
10061
10062 (declaration-indent)
10063
10064 (bracket
10065 (goto-char bracket)
10066 (cond
10067 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10068 (when (save-excursion (skip-chars-backward " \t)")
10069 (looking-at ")"))
10070 (backward-list))
10071 (back-to-indentation)
10072 (and (eq js2-pretty-multiline-declarations 'all)
10073 (looking-at js2-declaration-keyword-re)
10074 (goto-char (1+ (match-end 0))))
10075 (cond (same-indent-p
10076 (current-column))
10077 (continued-expr-p
10078 (+ (current-column) (* 2 js2-basic-offset)))
10079 (t
10080 (+ (current-column) js2-basic-offset))))
10081 (t
10082 (unless same-indent-p
10083 (forward-char)
10084 (skip-chars-forward " \t"))
10085 (current-column))))
10086
10087 (continued-expr-p js2-basic-offset)
10088
10089 (t 0)))))
10090
10091 (defun js2-lineup-comment (parse-status)
10092 "Indent a multi-line block comment continuation line."
10093 (let* ((beg (nth 8 parse-status))
10094 (first-line (js2-same-line beg))
10095 (offset (save-excursion
10096 (goto-char beg)
10097 (if (looking-at "/\\*")
10098 (+ 1 (current-column))
10099 0))))
10100 (unless first-line
10101 (indent-line-to offset))))
10102
10103 (defun js2-backward-sws ()
10104 "Move backward through whitespace and comments."
10105 (interactive)
10106 (while (forward-comment -1)))
10107
10108 (defun js2-forward-sws ()
10109 "Move forward through whitespace and comments."
10110 (interactive)
10111 (while (forward-comment 1)))
10112
10113 (defsubst js2-current-indent (&optional pos)
10114 "Return column of indentation on current line.
10115 If POS is non-nil, go to that point and return indentation for that line."
10116 (save-excursion
10117 (if pos
10118 (goto-char pos))
10119 (back-to-indentation)
10120 (current-column)))
10121
10122 (defsubst js2-arglist-close ()
10123 "Return non-nil if we're on a line beginning with a close-paren/brace."
10124 (save-match-data
10125 (save-excursion
10126 (goto-char (point-at-bol))
10127 (js2-forward-sws)
10128 (looking-at "[])}]"))))
10129
10130 (defsubst js2-indent-looks-like-label-p ()
10131 (goto-char (point-at-bol))
10132 (js2-forward-sws)
10133 (looking-at (concat js2-mode-identifier-re ":")))
10134
10135 (defun js2-indent-in-objlit-p (parse-status)
10136 "Return non-nil if this looks like an object-literal entry."
10137 (let ((start (nth 1 parse-status)))
10138 (and
10139 start
10140 (save-excursion
10141 (and (zerop (forward-line -1))
10142 (not (< (point) start)) ; crossed a {} boundary
10143 (js2-indent-looks-like-label-p)))
10144 (save-excursion
10145 (js2-indent-looks-like-label-p)))))
10146
10147 ;; if prev line looks like foobar({ then we're passing an object
10148 ;; literal to a function call, and people pretty much always want to
10149 ;; de-dent back to the previous line, so move the 'basic-offset'
10150 ;; position to the front.
10151 (defsubst js2-indent-objlit-arg-p (parse-status)
10152 (save-excursion
10153 (back-to-indentation)
10154 (js2-backward-sws)
10155 (and (eq (1- (point)) (nth 1 parse-status))
10156 (eq (char-before) ?{)
10157 (progn
10158 (forward-char -1)
10159 (skip-chars-backward " \t")
10160 (eq (char-before) ?\()))))
10161
10162 (defsubst js2-indent-case-block-p ()
10163 (save-excursion
10164 (back-to-indentation)
10165 (js2-backward-sws)
10166 (goto-char (point-at-bol))
10167 (skip-chars-forward " \t")
10168 (save-match-data
10169 (looking-at "case\\s-.+:"))))
10170
10171 (defsubst js2-syntax-bol ()
10172 "Return the point at the first non-whitespace char on the line.
10173 Returns `point-at-bol' if the line is empty."
10174 (save-excursion
10175 (beginning-of-line)
10176 (skip-chars-forward " \t")
10177 (point)))
10178
10179 (defun js2-bounce-indent (normal-col parse-status backwards)
10180 "Cycle among alternate computed indentation positions.
10181 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10182 of the buffer to the current point. NORMAL-COL is the indentation
10183 column computed by the heuristic guesser based on current paren,
10184 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10185 in reverse."
10186 (let ((cur-indent (js2-current-indent))
10187 (old-buffer-undo-list buffer-undo-list)
10188 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10189 (current-line (save-excursion
10190 (forward-line 0) ; move to bol
10191 (1+ (count-lines (point-min) (point)))))
10192 positions
10193 pos
10194 main-pos
10195 anchor
10196 arglist-cont
10197 same-indent
10198 prev-line-col
10199 basic-offset
10200 computed-pos)
10201 ;; temporarily don't record undo info, if user requested this
10202 (if js2-mode-indent-inhibit-undo
10203 (setq buffer-undo-list t))
10204 (unwind-protect
10205 (progn
10206 ;; first likely point: indent from beginning of previous code line
10207 (push (setq basic-offset
10208 (+ (save-excursion
10209 (back-to-indentation)
10210 (js2-backward-sws)
10211 (back-to-indentation)
10212 (setq prev-line-col (current-column)))
10213 js2-basic-offset))
10214 positions)
10215
10216 ;; (first + epsilon) likely point: indent 2x from beginning of
10217 ;; previous code line. Some companies like this approach. Ahem.
10218 ;; Seriously, though -- 4-space indent for expression continuation
10219 ;; lines isn't a bad idea. We should eventually implement it
10220 ;; that way.
10221 (push (setq basic-offset
10222 (+ (save-excursion
10223 (back-to-indentation)
10224 (js2-backward-sws)
10225 (back-to-indentation)
10226 (setq prev-line-col (current-column)))
10227 (* 2 js2-basic-offset)))
10228 positions)
10229
10230 ;; second likely point: indent from assign-expr RHS. This
10231 ;; is just a crude guess based on finding " = " on the previous
10232 ;; line containing actual code.
10233 (setq pos (save-excursion
10234 (save-match-data
10235 (forward-line -1)
10236 (goto-char (point-at-bol))
10237 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10238 (point-at-eol) t)
10239 (goto-char (match-end 1))
10240 (skip-chars-forward " \t\r\n")
10241 (current-column)))))
10242 (when pos
10243 (incf pos js2-basic-offset)
10244 (push pos positions))
10245
10246 ;; third likely point: same indent as previous line of code.
10247 ;; Make it the first likely point if we're not on an
10248 ;; arglist-close line and previous line ends in a comma, or
10249 ;; both this line and prev line look like object-literal
10250 ;; elements.
10251 (setq pos (save-excursion
10252 (goto-char (point-at-bol))
10253 (js2-backward-sws)
10254 (back-to-indentation)
10255 (prog1
10256 (current-column)
10257 ;; while we're here, look for trailing comma
10258 (if (save-excursion
10259 (goto-char (point-at-eol))
10260 (js2-backward-sws)
10261 (eq (char-before) ?,))
10262 (setq arglist-cont (1- (point)))))))
10263 (when pos
10264 (if (and (or arglist-cont
10265 (js2-indent-in-objlit-p parse-status))
10266 (not (js2-arglist-close)))
10267 (setq same-indent pos))
10268 (push pos positions))
10269
10270 ;; fourth likely point: first preceding code with less indentation
10271 ;; than the immediately preceding code line.
10272 (setq pos (save-excursion
10273 (back-to-indentation)
10274 (js2-backward-sws)
10275 (back-to-indentation)
10276 (setq anchor (current-column))
10277 (while (and (zerop (forward-line -1))
10278 (>= (progn
10279 (back-to-indentation)
10280 (current-column))
10281 anchor)))
10282 (setq pos (current-column))))
10283 (push pos positions)
10284
10285 ;; nesting-heuristic position, main by default
10286 (push (setq main-pos normal-col) positions)
10287
10288 ;; delete duplicates and sort positions list
10289 (setq positions (sort (delete-dups positions) '<))
10290
10291 ;; comma-list continuation lines: prev line indent takes precedence
10292 (if same-indent
10293 (setq main-pos same-indent))
10294
10295 ;; common special cases where we want to indent in from previous line
10296 (if (or (js2-indent-case-block-p)
10297 (js2-indent-objlit-arg-p parse-status))
10298 (setq main-pos basic-offset))
10299
10300 ;; if bouncing backwards, reverse positions list
10301 (if backwards
10302 (setq positions (reverse positions)))
10303
10304 ;; record whether we're already sitting on one of the alternatives
10305 (setq pos (member cur-indent positions))
10306
10307 (cond
10308 ;; case 0: we're one one of the alternatives and this is the
10309 ;; first time they've pressed TAB on this line (best-guess).
10310 ((and js2-mode-indent-ignore-first-tab
10311 pos
10312 ;; first time pressing TAB on this line?
10313 (not (eq js2-mode-last-indented-line current-line)))
10314 ;; do nothing
10315 (setq computed-pos nil))
10316 ;; case 1: only one computed position => use it
10317 ((null (cdr positions))
10318 (setq computed-pos 0))
10319 ;; case 2: not on any of the computed spots => use main spot
10320 ((not pos)
10321 (setq computed-pos (js2-position main-pos positions)))
10322 ;; case 3: on last position: cycle to first position
10323 ((null (cdr pos))
10324 (setq computed-pos 0))
10325 ;; case 4: on intermediate position: cycle to next position
10326 (t
10327 (setq computed-pos (js2-position (second pos) positions))))
10328
10329 ;; see if any hooks want to indent; otherwise we do it
10330 (loop with result = nil
10331 for hook in js2-indent-hook
10332 while (null result)
10333 do
10334 (setq result (funcall hook positions computed-pos))
10335 finally do
10336 (unless (or result (null computed-pos))
10337 (indent-line-to (nth computed-pos positions)))))
10338
10339 ;; finally
10340 (if js2-mode-indent-inhibit-undo
10341 (setq buffer-undo-list old-buffer-undo-list))
10342 ;; see commentary for `js2-mode-last-indented-line'
10343 (setq js2-mode-last-indented-line current-line))))
10344
10345 (defun js2-indent-bounce-backwards ()
10346 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10347 cycles between the computed indentation positions in reverse order."
10348 (interactive)
10349 (js2-indent-line t))
10350
10351 (defsubst js2-1-line-comment-continuation-p ()
10352 "Return t if we're in a 1-line comment continuation.
10353 If so, we don't ever want to use bounce-indent."
10354 (save-excursion
10355 (save-match-data
10356 (and (progn
10357 (forward-line 0)
10358 (looking-at "\\s-*//"))
10359 (progn
10360 (forward-line -1)
10361 (forward-line 0)
10362 (when (looking-at "\\s-*$")
10363 (js2-backward-sws)
10364 (forward-line 0))
10365 (looking-at "\\s-*//"))))))
10366
10367 (defun js2-indent-line (&optional bounce-backwards)
10368 "Indent the current line as JavaScript source text."
10369 (interactive)
10370 (let (parse-status
10371 offset
10372 indent-col
10373 moved
10374 ;; don't whine about errors/warnings when we're indenting.
10375 ;; This has to be set before calling parse-partial-sexp below.
10376 (inhibit-point-motion-hooks t))
10377 (setq parse-status (save-excursion
10378 (syntax-ppss (point-at-bol)))
10379 offset (- (point) (save-excursion
10380 (back-to-indentation)
10381 (point))))
10382 (js2-with-underscore-as-word-syntax
10383 (if (nth 4 parse-status)
10384 (js2-lineup-comment parse-status)
10385 (setq indent-col (js2-proper-indentation parse-status))
10386 ;; see comments below about js2-mode-last-indented-line
10387 (cond
10388 ;; bounce-indenting is disabled during electric-key indent.
10389 ;; It doesn't work well on first line of buffer.
10390 ((and js2-bounce-indent-p
10391 (not (js2-same-line (point-min)))
10392 (not (js2-1-line-comment-continuation-p)))
10393 (js2-bounce-indent indent-col parse-status bounce-backwards))
10394 ;; just indent to the guesser's likely spot
10395 (t (indent-line-to indent-col)))
10396 (when (plusp offset)
10397 (forward-char offset))))))
10398
10399 (defun js2-indent-region (start end)
10400 "Indent the region, but don't use bounce indenting."
10401 (let ((js2-bounce-indent-p nil)
10402 (indent-region-function nil)
10403 (after-change-functions (remq 'js2-mode-edit
10404 after-change-functions)))
10405 (indent-region start end nil) ; nil for byte-compiler
10406 (js2-mode-edit start end (- end start))))
10407
10408 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10409
10410 ;;;###autoload
10411 (defun js2-mode ()
10412 "Major mode for editing JavaScript code."
10413 (interactive)
10414 (kill-all-local-variables)
10415 (set-syntax-table js2-mode-syntax-table)
10416 (use-local-map js2-mode-map)
10417 (make-local-variable 'comment-start)
10418 (make-local-variable 'comment-end)
10419 (make-local-variable 'comment-start-skip)
10420 (setq major-mode 'js2-mode
10421 mode-name "JavaScript-IDE"
10422 comment-start "//" ; used by comment-region; don't change it
10423 comment-end "")
10424 (setq local-abbrev-table js2-mode-abbrev-table)
10425 (set (make-local-variable 'max-lisp-eval-depth)
10426 (max max-lisp-eval-depth 3000))
10427 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10428 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10429
10430 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10431 ;; on most platforms other than the one I originally wrote it on.
10432 ;; So it's back to `c-fill-paragraph'.
10433 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10434
10435 (add-hook 'before-save-hook #'js2-before-save nil t)
10436 (set (make-local-variable 'next-error-function) #'js2-next-error)
10437 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10438 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10439 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10440 ;; for characters inside regexp literals.
10441 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10442 ;; this is necessary to make `show-paren-function' work properly
10443 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10444 ;; needed for M-x rgrep, among other things
10445 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10446
10447 ;; some variables needed by cc-engine for paragraph-fill, etc.
10448 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10449 c-comment-start-regexp "/[*/]\\|\\s|"
10450 c-line-comment-starter "//"
10451 c-paragraph-start js2-paragraph-start
10452 c-paragraph-separate "$"
10453 comment-start-skip js2-comment-start-skip
10454 c-syntactic-ws-start js2-syntactic-ws-start
10455 c-syntactic-ws-end js2-syntactic-ws-end
10456 c-syntactic-eol js2-syntactic-eol)
10457
10458 (let ((c-buffer-is-cc-mode t))
10459 ;; Copied from `js-mode'. Also see Bug#6071.
10460 (make-local-variable 'paragraph-start)
10461 (make-local-variable 'paragraph-separate)
10462 (make-local-variable 'paragraph-ignore-fill-prefix)
10463 (make-local-variable 'adaptive-fill-mode)
10464 (make-local-variable 'adaptive-fill-regexp)
10465 (c-setup-paragraph-variables))
10466
10467 (setq js2-default-externs
10468 (append js2-ecma-262-externs
10469 (if js2-include-browser-externs
10470 js2-browser-externs)
10471 (if js2-include-gears-externs
10472 js2-gears-externs)
10473 (if js2-include-rhino-externs
10474 js2-rhino-externs)))
10475
10476 ;; We do our own syntax highlighting based on the parse tree.
10477 ;; However, we want minor modes that add keywords to highlight properly
10478 ;; (examples: doxymacs, column-marker).
10479 ;; To customize highlighted keywords, use `font-lock-add-keywords'.
10480 (setq font-lock-defaults '(nil t))
10481
10482 ;; Experiment: make reparse-delay longer for longer files.
10483 (if (plusp js2-dynamic-idle-timer-adjust)
10484 (setq js2-idle-timer-delay
10485 (* js2-idle-timer-delay
10486 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10487
10488 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10489 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10490 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10491 (imenu-add-to-menubar (concat "IM-" mode-name))
10492 (when js2-mirror-mode
10493 (js2-enter-mirror-mode))
10494 (add-to-invisibility-spec '(js2-outline . t))
10495 (set (make-local-variable 'line-move-ignore-invisible) t)
10496 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10497
10498 (if (fboundp 'run-mode-hooks)
10499 (run-mode-hooks 'js2-mode-hook)
10500 (run-hooks 'js2-mode-hook))
10501
10502 (setq js2-mode-functions-hidden nil
10503 js2-mode-comments-hidden nil
10504 js2-mode-buffer-dirty-p t
10505 js2-mode-parsing nil)
10506 (js2-reparse))
10507
10508 (defun js2-mode-exit ()
10509 "Exit `js2-mode' and clean up."
10510 (interactive)
10511 (when js2-mode-node-overlay
10512 (delete-overlay js2-mode-node-overlay)
10513 (setq js2-mode-node-overlay nil))
10514 (js2-remove-overlays)
10515 (setq js2-mode-ast nil)
10516 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10517 (remove-from-invisibility-spec '(js2-outline . t))
10518 (js2-mode-show-all)
10519 (js2-with-unmodifying-text-property-changes
10520 (js2-clear-face (point-min) (point-max))))
10521
10522 (defun js2-before-save ()
10523 "Clean up whitespace before saving file.
10524 You can disable this by customizing `js2-cleanup-whitespace'."
10525 (when js2-cleanup-whitespace
10526 (let ((col (current-column)))
10527 (delete-trailing-whitespace)
10528 ;; don't change trailing whitespace on current line
10529 (unless (eq (current-column) col)
10530 (indent-to col)))))
10531
10532 (defsubst js2-mode-reset-timer ()
10533 "Cancel any existing parse timer and schedule a new one."
10534 (if js2-mode-parse-timer
10535 (cancel-timer js2-mode-parse-timer))
10536 (setq js2-mode-parsing nil)
10537 (setq js2-mode-parse-timer
10538 (run-with-idle-timer js2-idle-timer-delay nil
10539 #'js2-mode-idle-reparse (current-buffer))))
10540
10541 (defun js2-mode-idle-reparse (buffer)
10542 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10543 it to be reparsed when the buffer is selected."
10544 (if (eq buffer (current-buffer))
10545 (js2-reparse)
10546 ;; reparse when the buffer is selected again
10547 (with-current-buffer buffer
10548 (add-hook 'window-configuration-change-hook
10549 #'js2-mode-idle-reparse-inner
10550 nil t))))
10551
10552 (defun js2-mode-idle-reparse-inner ()
10553 (remove-hook 'window-configuration-change-hook
10554 #'js2-mode-idle-reparse-inner
10555 t)
10556 (js2-reparse))
10557
10558 (defun js2-mode-edit (beg end len)
10559 "Schedule a new parse after buffer is edited.
10560 Buffer edit spans from BEG to END and is of length LEN.
10561 Also clears the `js2-magic' bit on autoinserted parens/brackets
10562 if the edit occurred on a line different from the magic paren."
10563 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10564 (line (if magic-pos (line-number-at-pos magic-pos))))
10565 (and line
10566 (or (/= (line-number-at-pos beg) line)
10567 (and (> 0 len)
10568 (/= (line-number-at-pos end) line)))
10569 (js2-mode-mundanify-parens)))
10570 (setq js2-mode-buffer-dirty-p t)
10571 (js2-mode-hide-overlay)
10572 (js2-mode-reset-timer))
10573
10574 (defun js2-reparse (&optional force)
10575 "Re-parse current buffer after user finishes some data entry.
10576 If we get any user input while parsing, including cursor motion,
10577 we discard the parse and reschedule it. If FORCE is nil, then the
10578 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10579 (let (time
10580 interrupted-p
10581 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10582 (unless js2-mode-parsing
10583 (setq js2-mode-parsing t)
10584 (unwind-protect
10585 (when (or js2-mode-buffer-dirty-p force)
10586 (js2-remove-overlays)
10587 (js2-with-unmodifying-text-property-changes
10588 (setq js2-mode-buffer-dirty-p nil
10589 js2-mode-fontifications nil
10590 js2-mode-deferred-properties nil)
10591 (if js2-mode-verbose-parse-p
10592 (message "parsing..."))
10593 (setq time
10594 (js2-time
10595 (setq interrupted-p
10596 (catch 'interrupted
10597 (setq js2-mode-ast (js2-parse))
10598 ;; if parsing is interrupted, comments and regex
10599 ;; literals stay ignored by `parse-partial-sexp'
10600 (remove-text-properties (point-min) (point-max)
10601 '(syntax-table))
10602 (js2-mode-apply-deferred-properties)
10603 (js2-mode-remove-suppressed-warnings)
10604 (js2-mode-show-warnings)
10605 (js2-mode-show-errors)
10606 (js2-mode-highlight-magic-parens)
10607 (if (>= js2-highlight-level 1)
10608 (js2-highlight-jsdoc js2-mode-ast))
10609 nil))))
10610 (if interrupted-p
10611 (progn
10612 ;; unfinished parse => try again
10613 (setq js2-mode-buffer-dirty-p t)
10614 (js2-mode-reset-timer))
10615 (if js2-mode-verbose-parse-p
10616 (message "Parse time: %s" time)))))
10617 (setq js2-mode-parsing nil)
10618 (unless interrupted-p
10619 (setq js2-mode-parse-timer nil))))))
10620
10621 (defun js2-mode-show-node ()
10622 "Debugging aid: highlight selected AST node on mouse click."
10623 (interactive)
10624 (let ((node (js2-node-at-point))
10625 beg
10626 end)
10627 (when js2-mode-show-overlay
10628 (if (null node)
10629 (message "No node found at location %s" (point))
10630 (setq beg (js2-node-abs-pos node)
10631 end (+ beg (js2-node-len node)))
10632 (if js2-mode-node-overlay
10633 (move-overlay js2-mode-node-overlay beg end)
10634 (setq js2-mode-node-overlay (make-overlay beg end))
10635 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10636 (js2-with-unmodifying-text-property-changes
10637 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10638 (message "%s, parent: %s"
10639 (js2-node-short-name node)
10640 (if (js2-node-parent node)
10641 (js2-node-short-name (js2-node-parent node))
10642 "nil"))))))
10643
10644 (defun js2-mode-hide-overlay (&optional p1 p2)
10645 "Remove the debugging overlay when the point moves.
10646 P1 and P2 are the old and new values of point, respectively."
10647 (when js2-mode-node-overlay
10648 (let ((beg (overlay-start js2-mode-node-overlay))
10649 (end (overlay-end js2-mode-node-overlay)))
10650 ;; Sometimes we're called spuriously.
10651 (unless (and p2
10652 (>= p2 beg)
10653 (<= p2 end))
10654 (js2-with-unmodifying-text-property-changes
10655 (remove-text-properties beg end '(point-left nil)))
10656 (delete-overlay js2-mode-node-overlay)
10657 (setq js2-mode-node-overlay nil)))))
10658
10659 (defun js2-mode-reset ()
10660 "Debugging helper: reset everything."
10661 (interactive)
10662 (js2-mode-exit)
10663 (js2-mode))
10664
10665 (defsubst js2-mode-show-warn-or-err (e face)
10666 "Highlight a warning or error E with FACE.
10667 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10668 (let* ((key (first e))
10669 (beg (second e))
10670 (end (+ beg (third e)))
10671 ;; Don't inadvertently go out of bounds.
10672 (beg (max (point-min) (min beg (point-max))))
10673 (end (max (point-min) (min end (point-max))))
10674 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10675 (ovl (make-overlay beg end)))
10676 (overlay-put ovl 'font-lock-face face)
10677 (overlay-put ovl 'js2-error t)
10678 (put-text-property beg end 'help-echo (js2-get-msg key))
10679 (put-text-property beg end 'point-entered #'js2-echo-error)))
10680
10681 (defun js2-remove-overlays ()
10682 "Remove overlays from buffer that have a `js2-error' property."
10683 (let ((beg (point-min))
10684 (end (point-max)))
10685 (save-excursion
10686 (dolist (o (overlays-in beg end))
10687 (when (overlay-get o 'js2-error)
10688 (delete-overlay o))))))
10689
10690 (defun js2-error-at-point (&optional pos)
10691 "Return non-nil if there's an error overlay at POS.
10692 Defaults to point."
10693 (loop with pos = (or pos (point))
10694 for o in (overlays-at pos)
10695 thereis (overlay-get o 'js2-error)))
10696
10697 (defun js2-mode-apply-deferred-properties ()
10698 "Apply fontifications and other text properties recorded during parsing."
10699 (when (plusp js2-highlight-level)
10700 ;; We defer clearing faces as long as possible to eliminate flashing.
10701 (js2-clear-face (point-min) (point-max))
10702 ;; Have to reverse the recorded fontifications list so that errors
10703 ;; and warnings overwrite the normal fontifications.
10704 (dolist (f (nreverse js2-mode-fontifications))
10705 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10706 (setq js2-mode-fontifications nil))
10707 (dolist (p js2-mode-deferred-properties)
10708 (apply #'put-text-property p))
10709 (setq js2-mode-deferred-properties nil))
10710
10711 (defun js2-mode-show-errors ()
10712 "Highlight syntax errors."
10713 (when js2-mode-show-parse-errors
10714 (dolist (e (js2-ast-root-errors js2-mode-ast))
10715 (js2-mode-show-warn-or-err e 'js2-error-face))))
10716
10717 (defun js2-mode-remove-suppressed-warnings ()
10718 "Take suppressed warnings out of the AST warnings list.
10719 This ensures that the counts and `next-error' are correct."
10720 (setf (js2-ast-root-warnings js2-mode-ast)
10721 (js2-delete-if
10722 (lambda (e)
10723 (let ((key (caar e)))
10724 (or
10725 (and (not js2-strict-trailing-comma-warning)
10726 (string-match "trailing\\.comma" key))
10727 (and (not js2-strict-cond-assign-warning)
10728 (string= key "msg.equal.as.assign"))
10729 (and js2-missing-semi-one-line-override
10730 (string= key "msg.missing.semi")
10731 (let* ((beg (second e))
10732 (node (js2-node-at-point beg))
10733 (fn (js2-mode-find-parent-fn node))
10734 (body (and fn (js2-function-node-body fn)))
10735 (lc (and body (js2-node-abs-pos body)))
10736 (rc (and lc (+ lc (js2-node-len body)))))
10737 (and fn
10738 (or (null body)
10739 (save-excursion
10740 (goto-char beg)
10741 (and (js2-same-line lc)
10742 (js2-same-line rc))))))))))
10743 (js2-ast-root-warnings js2-mode-ast))))
10744
10745 (defun js2-mode-show-warnings ()
10746 "Highlight strict-mode warnings."
10747 (when js2-mode-show-strict-warnings
10748 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10749 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10750
10751 (defun js2-echo-error (old-point new-point)
10752 "Called by point-motion hooks."
10753 (let ((msg (get-text-property new-point 'help-echo)))
10754 (if (and msg (or (not (current-message))
10755 (string= (current-message) "Quit")))
10756 (message msg))))
10757
10758 (defalias #'js2-echo-help #'js2-echo-error)
10759
10760 (defun js2-enter-key ()
10761 "Handle user pressing the Enter key."
10762 (interactive)
10763 (let ((parse-status (save-excursion
10764 (syntax-ppss (point))))
10765 (js2-bounce-indent-p nil))
10766 (cond
10767 ;; check if we're inside a string
10768 ((nth 3 parse-status)
10769 (if js2-concat-multiline-strings
10770 (js2-mode-split-string parse-status)
10771 (insert "\n")))
10772 ;; check if inside a block comment
10773 ((nth 4 parse-status)
10774 (js2-mode-extend-comment))
10775 (t
10776 ;; should probably figure out what the mode-map says we should do
10777 (if js2-indent-on-enter-key
10778 (js2-indent-line))
10779 (insert "\n")
10780 (if js2-enter-indents-newline
10781 (js2-indent-line))))))
10782
10783 (defun js2-mode-split-string (parse-status)
10784 "Turn a newline in mid-string into a string concatenation.
10785 PARSE-STATUS is as documented in `parse-partial-sexp'."
10786 (let* ((col (current-column))
10787 (quote-char (nth 3 parse-status))
10788 (quote-string (string quote-char))
10789 (string-beg (nth 8 parse-status))
10790 (at-eol (eq js2-concat-multiline-strings 'eol))
10791 (indent (save-match-data
10792 (or
10793 (save-excursion
10794 (back-to-indentation)
10795 (if (looking-at "\\+")
10796 (current-column)))
10797 (save-excursion
10798 (goto-char string-beg)
10799 (if (looking-back "\\+\\s-+")
10800 (goto-char (match-beginning 0)))
10801 (current-column))))))
10802 (insert quote-char)
10803 (if at-eol
10804 (insert " +\n")
10805 (insert "\n"))
10806 ;; FIXME: This does not match the behavior of `js2-indent-line'.
10807 (indent-to indent)
10808 (unless at-eol
10809 (insert "+ "))
10810 (insert quote-string)
10811 (when (eolp)
10812 (insert quote-string)
10813 (backward-char 1))))
10814
10815 (defun js2-mode-extend-comment ()
10816 "Indent the line and, when inside a comment block, add comment prefix."
10817 (let (star single col first-line needs-close)
10818 (save-excursion
10819 (back-to-indentation)
10820 (cond
10821 ((looking-at "\\*[^/]")
10822 (setq star t
10823 col (current-column)))
10824 ((looking-at "/\\*")
10825 (setq star t
10826 first-line t
10827 col (1+ (current-column))))
10828 ((looking-at "//")
10829 (setq single t
10830 col (current-column)))))
10831 ;; Heuristic for whether we need to close the comment:
10832 ;; if we've got a parse error here, assume it's an unterminated
10833 ;; comment.
10834 (setq needs-close
10835 (or
10836 (eq (get-text-property (1- (point)) 'point-entered)
10837 'js2-echo-error)
10838 ;; The heuristic above doesn't work well when we're
10839 ;; creating a comment and there's another one downstream,
10840 ;; as our parser thinks this one ends at the end of the
10841 ;; next one. (You can have a /* inside a js block comment.)
10842 ;; So just close it if the next non-ws char isn't a *.
10843 (and first-line
10844 (eolp)
10845 (save-excursion
10846 (skip-chars-forward " \t\r\n")
10847 (not (eq (char-after) ?*))))))
10848 (insert "\n")
10849 (cond
10850 (star
10851 (indent-to col)
10852 (insert "* ")
10853 (if (and first-line needs-close)
10854 (save-excursion
10855 (insert "\n")
10856 (indent-to col)
10857 (insert "*/"))))
10858 ((and single
10859 (save-excursion
10860 (and (zerop (forward-line 1))
10861 (looking-at "\\s-*//"))))
10862 (indent-to col)
10863 (insert "// "))
10864 ;; don't need to extend the comment after all
10865 (js2-enter-indents-newline
10866 (js2-indent-line)))))
10867
10868 (defun js2-beginning-of-line ()
10869 "Toggles point between bol and first non-whitespace char in line.
10870 Also moves past comment delimiters when inside comments."
10871 (interactive)
10872 (let (node beg)
10873 (cond
10874 ((bolp)
10875 (back-to-indentation))
10876 ((looking-at "//")
10877 (skip-chars-forward "/ \t"))
10878 ((and (eq (char-after) ?*)
10879 (setq node (js2-comment-at-point))
10880 (memq (js2-comment-node-format node) '(jsdoc block))
10881 (save-excursion
10882 (skip-chars-backward " \t")
10883 (bolp)))
10884 (skip-chars-forward "\* \t"))
10885 (t
10886 (goto-char (point-at-bol))))))
10887
10888 (defun js2-end-of-line ()
10889 "Toggles point between eol and last non-whitespace char in line."
10890 (interactive)
10891 (if (eolp)
10892 (skip-chars-backward " \t")
10893 (goto-char (point-at-eol))))
10894
10895 (defun js2-enter-mirror-mode()
10896 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10897 on insertion."
10898 (interactive)
10899 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10900 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10901 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10902 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10903 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10904 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10905 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10906 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10907
10908 (defun js2-leave-mirror-mode()
10909 "Turns off mirror mode."
10910 (interactive)
10911 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10912 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10913
10914 (defsubst js2-mode-inside-string ()
10915 "Return non-nil if inside a string.
10916 Actually returns the quote character that begins the string."
10917 (let ((parse-state (save-excursion
10918 (syntax-ppss (point)))))
10919 (nth 3 parse-state)))
10920
10921 (defsubst js2-mode-inside-comment-or-string ()
10922 "Return non-nil if inside a comment or string."
10923 (or
10924 (let ((comment-start
10925 (save-excursion
10926 (goto-char (point-at-bol))
10927 (if (re-search-forward "//" (point-at-eol) t)
10928 (match-beginning 0)))))
10929 (and comment-start
10930 (<= comment-start (point))))
10931 (let ((parse-state (save-excursion
10932 (syntax-ppss (point)))))
10933 (or (nth 3 parse-state)
10934 (nth 4 parse-state)))))
10935
10936 (defsubst js2-make-magic-delimiter (delim &optional pos)
10937 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10938 Sets value of `js2-magic' text property to line number at POS."
10939 (propertize delim
10940 'js2-magic (line-number-at-pos pos)
10941 'font-lock-face 'js2-magic-paren-face))
10942
10943 (defun js2-mode-match-delimiter (open close)
10944 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10945 The rule we use, which as far as we can tell is how Eclipse works,
10946 is that we insert the match if we're not in a comment or string,
10947 and the next non-whitespace character is either punctuation or
10948 occurs on another line."
10949 (insert open)
10950 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10951 (not (js2-mode-inside-comment-or-string)))
10952 (save-excursion
10953 (insert (js2-make-magic-delimiter close)))
10954 (when js2-auto-indent-p
10955 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10956 (js2-indent-line)))))
10957
10958 (defun js2-mode-match-bracket ()
10959 "Insert matching bracket."
10960 (interactive)
10961 (js2-mode-match-delimiter "[" "]"))
10962
10963 (defun js2-mode-match-paren ()
10964 "Insert matching paren unless already inserted."
10965 (interactive)
10966 (js2-mode-match-delimiter "(" ")"))
10967
10968 (defun js2-mode-match-curly (arg)
10969 "Insert matching curly-brace.
10970 With prefix arg, no formatting or indentation will occur -- the close-brace
10971 is simply inserted directly at the point."
10972 (interactive "p")
10973 (let (try-pos)
10974 (cond
10975 (current-prefix-arg
10976 (js2-mode-match-delimiter "{" "}"))
10977 ((and js2-auto-insert-catch-block
10978 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10979 (point-at-bol))
10980 (match-beginning 1))))
10981 (js2-insert-catch-skel try-pos))
10982 (t
10983 ;; Otherwise try to do something smarter.
10984 (insert "{")
10985 (unless (or (not (looking-at "\\s-*$"))
10986 (save-excursion
10987 (skip-chars-forward " \t\r\n")
10988 (and (looking-at "}")
10989 (js2-error-at-point)))
10990 (js2-mode-inside-comment-or-string))
10991 (undo-boundary)
10992 ;; absolutely mystifying bug: when inserting the next "\n",
10993 ;; the buffer-undo-list is given two new entries: the inserted range,
10994 ;; and the incorrect position of the point. It's recorded incorrectly
10995 ;; as being before the opening "{", not after it. But it's recorded
10996 ;; as the correct value if you're debugging `js2-mode-match-curly'
10997 ;; in edebug. I have no idea why it's doing this, but incrementing
10998 ;; the inserted position fixes the problem, so that the undo takes us
10999 ;; back to just after the user-inserted "{".
11000 (insert "\n")
11001 (ignore-errors
11002 (incf (cadr buffer-undo-list)))
11003 (js2-indent-line)
11004 (save-excursion
11005 (insert "\n}")
11006 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
11007 (js2-indent-line))))))))
11008
11009 (defun js2-insert-catch-skel (try-pos)
11010 "Complete a try/catch block after inserting a { following a try keyword.
11011 Rationale is that a try always needs a catch or a finally, and the catch is
11012 the more likely of the two.
11013
11014 TRY-POS is the buffer position of the try keyword. The open-curly should
11015 already have been inserted."
11016 (insert "{")
11017 (let ((try-col (save-excursion
11018 (goto-char try-pos)
11019 (current-column))))
11020 (insert "\n")
11021 (undo-boundary)
11022 (js2-indent-line) ;; indent the blank line where cursor will end up
11023 (save-excursion
11024 (insert "\n")
11025 (indent-to try-col)
11026 (insert "} catch (x) {\n\n")
11027 (indent-to try-col)
11028 (insert "}"))))
11029
11030 (defun js2-mode-highlight-magic-parens ()
11031 "Re-highlight magic parens after parsing nukes the 'face prop."
11032 (let ((beg (point-min))
11033 end)
11034 (while (setq beg (next-single-property-change beg 'js2-magic))
11035 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11036 (if (get-text-property beg 'js2-magic)
11037 (js2-with-unmodifying-text-property-changes
11038 (put-text-property beg (or end (1+ beg))
11039 'font-lock-face 'js2-magic-paren-face))))))
11040
11041 (defun js2-mode-mundanify-parens ()
11042 "Clear all magic parens and brackets."
11043 (let ((beg (point-min))
11044 end)
11045 (while (setq beg (next-single-property-change beg 'js2-magic))
11046 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11047 (remove-text-properties beg (or end (1+ beg))
11048 '(js2-magic face)))))
11049
11050 (defsubst js2-match-quote (quote-string)
11051 (let ((start-quote (js2-mode-inside-string)))
11052 (cond
11053 ;; inside a comment - don't do quote-matching, since we can't
11054 ;; reliably figure out if we're in a string inside the comment
11055 ((js2-comment-at-point)
11056 (insert quote-string))
11057 ((not start-quote)
11058 ;; not in string => insert matched quotes
11059 (insert quote-string)
11060 ;; exception: if we're just before a word, don't double it.
11061 (unless (looking-at "[^ \t\r\n]")
11062 (save-excursion
11063 (insert quote-string))))
11064 ((looking-at quote-string)
11065 (if (looking-back "[^\\]\\\\")
11066 (insert quote-string)
11067 (forward-char 1)))
11068 ((and js2-mode-escape-quotes
11069 (save-excursion
11070 (save-match-data
11071 (re-search-forward quote-string (point-at-eol) t))))
11072 ;; inside terminated string, escape quote (unless already escaped)
11073 (insert (if (looking-back "[^\\]\\\\")
11074 quote-string
11075 (concat "\\" quote-string))))
11076 (t
11077 (insert quote-string))))) ; else terminate the string
11078
11079 (defun js2-mode-match-single-quote ()
11080 "Insert matching single-quote."
11081 (interactive)
11082 (let ((parse-status (syntax-ppss (point))))
11083 ;; don't match inside comments, since apostrophe is more common
11084 (if (nth 4 parse-status)
11085 (insert "'")
11086 (js2-match-quote "'"))))
11087
11088 (defun js2-mode-match-double-quote ()
11089 "Insert matching double-quote."
11090 (interactive)
11091 (js2-match-quote "\""))
11092
11093 ;; Eclipse works as follows:
11094 ;; * type an open-paren and it auto-inserts close-paren
11095 ;; - auto-inserted paren gets a green bracket
11096 ;; - green bracket means typing close-paren there will skip it
11097 ;; * if you insert any text on a different line, it turns off
11098 (defun js2-mode-magic-close-paren ()
11099 "Skip over close-paren rather than inserting, where appropriate."
11100 (interactive)
11101 (let* ((here (point))
11102 (parse-status (syntax-ppss here))
11103 (open-pos (nth 1 parse-status))
11104 (close last-input-event)
11105 (open (cond
11106 ((eq close ?\))
11107 ?\()
11108 ((eq close ?\])
11109 ?\[)
11110 ((eq close ?})
11111 ?{)
11112 (t nil))))
11113 (if (and (eq (char-after) close)
11114 (eq open (char-after open-pos))
11115 (js2-same-line open-pos)
11116 (get-text-property here 'js2-magic))
11117 (progn
11118 (remove-text-properties here (1+ here) '(js2-magic face))
11119 (forward-char 1))
11120 (insert-char close 1))
11121 (blink-matching-open)))
11122
11123 (defun js2-mode-wait-for-parse (callback)
11124 "Invoke CALLBACK when parsing is finished.
11125 If parsing is already finished, calls CALLBACK immediately."
11126 (if (not js2-mode-buffer-dirty-p)
11127 (funcall callback)
11128 (push callback js2-mode-pending-parse-callbacks)
11129 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11130
11131 (defun js2-mode-parse-finished ()
11132 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11133 ;; We can't let errors propagate up, since it prevents the
11134 ;; `js2-parse' method from completing normally and returning
11135 ;; the ast, which makes things mysteriously not work right.
11136 (unwind-protect
11137 (dolist (cb js2-mode-pending-parse-callbacks)
11138 (condition-case err
11139 (funcall cb)
11140 (error (message "%s" err))))
11141 (setq js2-mode-pending-parse-callbacks nil)))
11142
11143 (defun js2-mode-flag-region (from to flag)
11144 "Hide or show text from FROM to TO, according to FLAG.
11145 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11146 Returns the created overlay if FLAG is non-nil."
11147 (remove-overlays from to 'invisible 'js2-outline)
11148 (when flag
11149 (let ((o (make-overlay from to)))
11150 (overlay-put o 'invisible 'js2-outline)
11151 (overlay-put o 'isearch-open-invisible
11152 'js2-isearch-open-invisible)
11153 o)))
11154
11155 ;; Function to be set as an outline-isearch-open-invisible' property
11156 ;; to the overlay that makes the outline invisible (see
11157 ;; `js2-mode-flag-region').
11158 (defun js2-isearch-open-invisible (overlay)
11159 ;; We rely on the fact that isearch places point on the matched text.
11160 (js2-mode-show-element))
11161
11162 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11163 "Return cons cell of bounds of folding overlay at POS.
11164 Returns nil if not found."
11165 (let ((overlays (overlays-at (or pos (point))))
11166 o)
11167 (while (and overlays
11168 (not o))
11169 (if (overlay-get (car overlays) 'invisible)
11170 (setq o (car overlays))
11171 (setq overlays (cdr overlays))))
11172 (if o
11173 (cons (overlay-start o) (overlay-end o)))))
11174
11175 (defun js2-mode-function-at-point (&optional pos)
11176 "Return the innermost function node enclosing current point.
11177 Returns nil if point is not in a function."
11178 (let ((node (js2-node-at-point pos)))
11179 (while (and node (not (js2-function-node-p node)))
11180 (setq node (js2-node-parent node)))
11181 (if (js2-function-node-p node)
11182 node)))
11183
11184 (defun js2-mode-toggle-element ()
11185 "Hide or show the foldable element at the point."
11186 (interactive)
11187 (let (comment fn pos)
11188 (save-excursion
11189 (save-match-data
11190 (cond
11191 ;; /* ... */ comment?
11192 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11193 (if (js2-mode-invisible-overlay-bounds
11194 (setq pos (+ 3 (js2-node-abs-pos comment))))
11195 (progn
11196 (goto-char pos)
11197 (js2-mode-show-element))
11198 (js2-mode-hide-element)))
11199 ;; //-comment?
11200 ((save-excursion
11201 (back-to-indentation)
11202 (looking-at js2-mode-//-comment-re))
11203 (js2-mode-toggle-//-comment))
11204 ;; function?
11205 ((setq fn (js2-mode-function-at-point))
11206 (setq pos (and (js2-function-node-body fn)
11207 (js2-node-abs-pos (js2-function-node-body fn))))
11208 (goto-char (1+ pos))
11209 (if (js2-mode-invisible-overlay-bounds)
11210 (js2-mode-show-element)
11211 (js2-mode-hide-element)))
11212 (t
11213 (message "Nothing at point to hide or show")))))))
11214
11215 (defun js2-mode-hide-element ()
11216 "Fold/hide contents of a block, showing ellipses.
11217 Show the hidden text with \\[js2-mode-show-element]."
11218 (interactive)
11219 (if js2-mode-buffer-dirty-p
11220 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11221 (let (node body beg end)
11222 (cond
11223 ((js2-mode-invisible-overlay-bounds)
11224 (message "already hidden"))
11225 (t
11226 (setq node (js2-node-at-point))
11227 (cond
11228 ((js2-block-comment-p node)
11229 (js2-mode-hide-comment node))
11230 (t
11231 (while (and node (not (js2-function-node-p node)))
11232 (setq node (js2-node-parent node)))
11233 (if (and node
11234 (setq body (js2-function-node-body node)))
11235 (progn
11236 (setq beg (js2-node-abs-pos body)
11237 end (+ beg (js2-node-len body)))
11238 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11239 (message "No collapsable element found at point"))))))))
11240
11241 (defun js2-mode-show-element ()
11242 "Show the hidden element at current point."
11243 (interactive)
11244 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11245 (if bounds
11246 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11247 (message "Nothing to un-hide"))))
11248
11249 (defun js2-mode-show-all ()
11250 "Show all of the text in the buffer."
11251 (interactive)
11252 (js2-mode-flag-region (point-min) (point-max) nil))
11253
11254 (defun js2-mode-toggle-hide-functions ()
11255 (interactive)
11256 (if js2-mode-functions-hidden
11257 (js2-mode-show-functions)
11258 (js2-mode-hide-functions)))
11259
11260 (defun js2-mode-hide-functions ()
11261 "Hides all non-nested function bodies in the buffer.
11262 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11263 to open an individual entry."
11264 (interactive)
11265 (if js2-mode-buffer-dirty-p
11266 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11267 (if (null js2-mode-ast)
11268 (message "Oops - parsing failed")
11269 (setq js2-mode-functions-hidden t)
11270 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11271
11272 (defun js2-mode-function-hider (n endp)
11273 (when (not endp)
11274 (let ((tt (js2-node-type n))
11275 body beg end)
11276 (cond
11277 ((and (= tt js2-FUNCTION)
11278 (setq body (js2-function-node-body n)))
11279 (setq beg (js2-node-abs-pos body)
11280 end (+ beg (js2-node-len body)))
11281 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11282 nil) ; don't process children of function
11283 (t
11284 t))))) ; keep processing other AST nodes
11285
11286 (defun js2-mode-show-functions ()
11287 "Un-hide any folded function bodies in the buffer."
11288 (interactive)
11289 (setq js2-mode-functions-hidden nil)
11290 (save-excursion
11291 (goto-char (point-min))
11292 (while (/= (goto-char (next-overlay-change (point)))
11293 (point-max))
11294 (dolist (o (overlays-at (point)))
11295 (when (and (overlay-get o 'invisible)
11296 (not (overlay-get o 'comment)))
11297 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11298
11299 (defun js2-mode-hide-comment (n)
11300 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11301 3 ; /**
11302 2)) ; /*
11303 (beg (+ (js2-node-abs-pos n) head))
11304 (end (- (+ beg (js2-node-len n)) head 2))
11305 (o (js2-mode-flag-region beg end 'hide)))
11306 (overlay-put o 'comment t)))
11307
11308 (defun js2-mode-toggle-hide-comments ()
11309 "Folds all block comments in the buffer.
11310 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11311 to open an individual entry."
11312 (interactive)
11313 (if js2-mode-comments-hidden
11314 (js2-mode-show-comments)
11315 (js2-mode-hide-comments)))
11316
11317 (defun js2-mode-hide-comments ()
11318 (interactive)
11319 (if js2-mode-buffer-dirty-p
11320 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11321 (if (null js2-mode-ast)
11322 (message "Oops - parsing failed")
11323 (setq js2-mode-comments-hidden t)
11324 (dolist (n (js2-ast-root-comments js2-mode-ast))
11325 (let ((format (js2-comment-node-format n)))
11326 (when (js2-block-comment-p n)
11327 (js2-mode-hide-comment n))))
11328 (js2-mode-hide-//-comments)))
11329
11330 (defsubst js2-mode-extend-//-comment (direction)
11331 "Find start or end of a block of similar //-comment lines.
11332 DIRECTION is -1 to look back, 1 to look forward.
11333 INDENT is the indentation level to match.
11334 Returns the end-of-line position of the furthest adjacent
11335 //-comment line with the same indentation as the current line.
11336 If there is no such matching line, returns current end of line."
11337 (let ((pos (point-at-eol))
11338 (indent (current-indentation)))
11339 (save-excursion
11340 (save-match-data
11341 (while (and (zerop (forward-line direction))
11342 (looking-at js2-mode-//-comment-re)
11343 (eq indent (length (match-string 1))))
11344 (setq pos (point-at-eol)))
11345 pos))))
11346
11347 (defun js2-mode-hide-//-comments ()
11348 "Fold adjacent 1-line comments, showing only snippet of first one."
11349 (let (beg end)
11350 (save-excursion
11351 (save-match-data
11352 (goto-char (point-min))
11353 (while (re-search-forward js2-mode-//-comment-re nil t)
11354 (setq beg (point)
11355 end (js2-mode-extend-//-comment 1))
11356 (unless (eq beg end)
11357 (overlay-put (js2-mode-flag-region beg end 'hide)
11358 'comment t))
11359 (goto-char end)
11360 (forward-char 1))))))
11361
11362 (defun js2-mode-toggle-//-comment ()
11363 "Fold or un-fold any multi-line //-comment at point.
11364 Caller should have determined that this line starts with a //-comment."
11365 (let* ((beg (point-at-eol))
11366 (end beg))
11367 (save-excursion
11368 (goto-char end)
11369 (if (js2-mode-invisible-overlay-bounds)
11370 (js2-mode-show-element)
11371 ;; else hide the comment
11372 (setq beg (js2-mode-extend-//-comment -1)
11373 end (js2-mode-extend-//-comment 1))
11374 (unless (eq beg end)
11375 (overlay-put (js2-mode-flag-region beg end 'hide)
11376 'comment t))))))
11377
11378 (defun js2-mode-show-comments ()
11379 "Un-hide any hidden comments, leaving other hidden elements alone."
11380 (interactive)
11381 (setq js2-mode-comments-hidden nil)
11382 (save-excursion
11383 (goto-char (point-min))
11384 (while (/= (goto-char (next-overlay-change (point)))
11385 (point-max))
11386 (dolist (o (overlays-at (point)))
11387 (when (overlay-get o 'comment)
11388 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11389
11390 (defun js2-mode-display-warnings-and-errors ()
11391 "Turn on display of warnings and errors."
11392 (interactive)
11393 (setq js2-mode-show-parse-errors t
11394 js2-mode-show-strict-warnings t)
11395 (js2-reparse 'force))
11396
11397 (defun js2-mode-hide-warnings-and-errors ()
11398 "Turn off display of warnings and errors."
11399 (interactive)
11400 (setq js2-mode-show-parse-errors nil
11401 js2-mode-show-strict-warnings nil)
11402 (js2-reparse 'force))
11403
11404 (defun js2-mode-toggle-warnings-and-errors ()
11405 "Toggle the display of warnings and errors.
11406 Some users don't like having warnings/errors reported while they type."
11407 (interactive)
11408 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11409 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11410 (if (interactive-p)
11411 (message "warnings and errors %s"
11412 (if js2-mode-show-parse-errors
11413 "enabled"
11414 "disabled")))
11415 (js2-reparse 'force))
11416
11417 (defun js2-mode-customize ()
11418 (interactive)
11419 (customize-group 'js2-mode))
11420
11421 (defun js2-mode-forward-sexp (&optional arg)
11422 "Move forward across one statement or balanced expression.
11423 With ARG, do it that many times. Negative arg -N means
11424 move backward across N balanced expressions."
11425 (interactive "p")
11426 (setq arg (or arg 1))
11427 (if js2-mode-buffer-dirty-p
11428 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11429 (let (node end (start (point)))
11430 (cond
11431 ;; backward-sexp
11432 ;; could probably make this better for some cases:
11433 ;; - if in statement block (e.g. function body), go to parent
11434 ;; - infix exprs like (foo in bar) - maybe go to beginning
11435 ;; of infix expr if in the right-side expression?
11436 ((and arg (minusp arg))
11437 (dotimes (i (- arg))
11438 (js2-backward-sws)
11439 (forward-char -1) ; enter the node we backed up to
11440 (setq node (js2-node-at-point (point) t))
11441 (goto-char (if node
11442 (js2-node-abs-pos node)
11443 (point-min)))))
11444 (t
11445 ;; forward-sexp
11446 (js2-forward-sws)
11447 (dotimes (i arg)
11448 (js2-forward-sws)
11449 (setq node (js2-node-at-point (point) t)
11450 end (if node (+ (js2-node-abs-pos node)
11451 (js2-node-len node))))
11452 (goto-char (or end (point-max))))))))
11453
11454 (defun js2-next-error (&optional arg reset)
11455 "Move to next parse error.
11456 Typically invoked via \\[next-error].
11457 ARG is the number of errors, forward or backward, to move.
11458 RESET means start over from the beginning."
11459 (interactive "p")
11460 (if (or (null js2-mode-ast)
11461 (and (null (js2-ast-root-errors js2-mode-ast))
11462 (null (js2-ast-root-warnings js2-mode-ast))))
11463 (message "No errors")
11464 (when reset
11465 (goto-char (point-min)))
11466 (let* ((errs (copy-sequence
11467 (append (js2-ast-root-errors js2-mode-ast)
11468 (js2-ast-root-warnings js2-mode-ast))))
11469 (continue t)
11470 (start (point))
11471 (count (or arg 1))
11472 (backward (minusp count))
11473 (sorter (if backward '> '<))
11474 (stopper (if backward '< '>))
11475 (count (abs count))
11476 all-errs
11477 err)
11478 ;; sort by start position
11479 (setq errs (sort errs (lambda (e1 e2)
11480 (funcall sorter (second e1) (second e2))))
11481 all-errs errs)
11482 ;; find nth error with pos > start
11483 (while (and errs continue)
11484 (when (funcall stopper (cadar errs) start)
11485 (setq err (car errs))
11486 (if (zerop (decf count))
11487 (setq continue nil)))
11488 (setq errs (cdr errs)))
11489 (if err
11490 (goto-char (second err))
11491 ;; wrap around to first error
11492 (goto-char (second (car all-errs)))
11493 ;; if we were already on it, echo msg again
11494 (if (= (point) start)
11495 (js2-echo-error (point) (point)))))))
11496
11497 (defun js2-down-mouse-3 ()
11498 "Make right-click move the point to the click location.
11499 This makes right-click context menu operations a bit more intuitive.
11500 The point will not move if the region is active, however, to avoid
11501 destroying the region selection."
11502 (interactive)
11503 (when (and js2-move-point-on-right-click
11504 (not mark-active))
11505 (let ((e last-input-event))
11506 (ignore-errors
11507 (goto-char (cadadr e))))))
11508
11509 (defun js2-mode-create-imenu-index ()
11510 "Return an alist for `imenu--index-alist'."
11511 ;; This is built up in `js2-parse-record-imenu' during parsing.
11512 (when js2-mode-ast
11513 ;; if we have an ast but no recorder, they're requesting a rescan
11514 (unless js2-imenu-recorder
11515 (js2-reparse 'force))
11516 (prog1
11517 (js2-build-imenu-index)
11518 (setq js2-imenu-recorder nil
11519 js2-imenu-function-map nil))))
11520
11521 (defun js2-mode-find-tag ()
11522 "Replacement for `find-tag-default'.
11523 `find-tag-default' returns a ridiculous answer inside comments."
11524 (let (beg end)
11525 (js2-with-underscore-as-word-syntax
11526 (save-excursion
11527 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11528 (looking-back "[A-Za-z0-9_$]"))
11529 (setq beg (progn (forward-word -1) (point))
11530 end (progn (forward-word 1) (point)))
11531 (setq beg (progn (forward-word 1) (point))
11532 end (progn (forward-word -1) (point))))
11533 (replace-regexp-in-string
11534 "[\"']" ""
11535 (buffer-substring-no-properties beg end))))))
11536
11537 (defun js2-mode-forward-sibling ()
11538 "Move to the end of the sibling following point in parent.
11539 Returns non-nil if successful, or nil if there was no following sibling."
11540 (let* ((node (js2-node-at-point))
11541 (parent (js2-mode-find-enclosing-fn node))
11542 sib)
11543 (when (setq sib (js2-node-find-child-after (point) parent))
11544 (goto-char (+ (js2-node-abs-pos sib)
11545 (js2-node-len sib))))))
11546
11547 (defun js2-mode-backward-sibling ()
11548 "Move to the beginning of the sibling node preceding point in parent.
11549 Parent is defined as the enclosing script or function."
11550 (let* ((node (js2-node-at-point))
11551 (parent (js2-mode-find-enclosing-fn node))
11552 sib)
11553 (when (setq sib (js2-node-find-child-before (point) parent))
11554 (goto-char (js2-node-abs-pos sib)))))
11555
11556 (defun js2-beginning-of-defun (&optional arg)
11557 "Go to line on which current function starts, and return t on success.
11558 If we're not in a function or already at the beginning of one, go
11559 to beginning of previous script-level element.
11560 With ARG N, do that N times. If N is negative, move forward."
11561 (setq arg (or arg 1))
11562 (if (plusp arg)
11563 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11564 (when (cond
11565 ((js2-function-node-p parent)
11566 (goto-char (js2-node-abs-pos parent)))
11567 (t
11568 (js2-mode-backward-sibling)))
11569 (if (> arg 1)
11570 (js2-beginning-of-defun (1- arg))
11571 t)))
11572 (when (js2-end-of-defun)
11573 (if (>= arg -1)
11574 (js2-beginning-of-defun 1)
11575 (js2-beginning-of-defun (1+ arg))))))
11576
11577 (defun js2-end-of-defun ()
11578 "Go to the char after the last position of the current function
11579 or script-level element."
11580 (let* ((node (js2-node-at-point))
11581 (parent (or (and (js2-function-node-p node) node)
11582 (js2-node-parent-script-or-fn node)))
11583 script)
11584 (unless (js2-function-node-p parent)
11585 ;; use current script-level node, or, if none, the next one
11586 (setq script (or parent node))
11587 (setq parent (js2-node-find-child-before (point) script))
11588 (when (or (null parent)
11589 (>= (point) (+ (js2-node-abs-pos parent)
11590 (js2-node-len parent))))
11591 (setq parent (js2-node-find-child-after (point) script))))
11592 (when parent
11593 (goto-char (+ (js2-node-abs-pos parent)
11594 (js2-node-len parent))))))
11595
11596 (defun js2-mark-defun (&optional allow-extend)
11597 "Put mark at end of this function, point at beginning.
11598 The function marked is the one that contains point.
11599
11600 Interactively, if this command is repeated,
11601 or (in Transient Mark mode) if the mark is active,
11602 it marks the next defun after the ones already marked."
11603 (interactive "p")
11604 (let (extended)
11605 (when (and allow-extend
11606 (or (and (eq last-command this-command) (mark t))
11607 (and transient-mark-mode mark-active)))
11608 (let ((sib (save-excursion
11609 (goto-char (mark))
11610 (if (js2-mode-forward-sibling)
11611 (point))))
11612 node)
11613 (if sib
11614 (progn
11615 (set-mark sib)
11616 (setq extended t))
11617 ;; no more siblings - try extending to enclosing node
11618 (goto-char (mark t)))))
11619 (when (not extended)
11620 (let ((node (js2-node-at-point (point) t)) ; skip comments
11621 ast fn stmt parent beg end)
11622 (when (js2-ast-root-p node)
11623 (setq ast node
11624 node (or (js2-node-find-child-after (point) node)
11625 (js2-node-find-child-before (point) node))))
11626 ;; only mark whole buffer if we can't find any children
11627 (if (null node)
11628 (setq node ast))
11629 (if (js2-function-node-p node)
11630 (setq parent node)
11631 (setq fn (js2-mode-find-enclosing-fn node)
11632 stmt (if (or (null fn)
11633 (js2-ast-root-p fn))
11634 (js2-mode-find-first-stmt node))
11635 parent (or stmt fn)))
11636 (setq beg (js2-node-abs-pos parent)
11637 end (+ beg (js2-node-len parent)))
11638 (push-mark beg)
11639 (goto-char end)
11640 (exchange-point-and-mark)))))
11641
11642 (defun js2-narrow-to-defun ()
11643 "Narrow to the function enclosing point."
11644 (interactive)
11645 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11646 (fn (if (js2-script-node-p node)
11647 node
11648 (js2-mode-find-enclosing-fn node)))
11649 (beg (js2-node-abs-pos fn)))
11650 (unless (js2-ast-root-p fn)
11651 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11652
11653 (provide 'js2-mode)
11654
11655 ;;; js2-mode.el ends here