Personal emacs config
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

12856 lines
498 KiB

  1. ;;; js2-mode.el --- Improved JavaScript editing mode -*- lexical-binding: t -*-
  2. ;; Copyright (C) 2009, 2011-2018 Free Software Foundation, Inc.
  3. ;; Author: Steve Yegge <steve.yegge@gmail.com>
  4. ;; mooz <stillpedant@gmail.com>
  5. ;; Dmitry Gutov <dgutov@yandex.ru>
  6. ;; URL: https://github.com/mooz/js2-mode/
  7. ;; http://code.google.com/p/js2-mode/
  8. ;; Version: 20190219
  9. ;; Keywords: languages, javascript
  10. ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
  11. ;; This file is part of GNU Emacs.
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  22. ;;; Commentary:
  23. ;; This JavaScript editing mode supports:
  24. ;; - strict recognition of the Ecma-262 language standard
  25. ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
  26. ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
  27. ;; - accurate syntax highlighting using a recursive-descent parser
  28. ;; - on-the-fly reporting of syntax errors and strict-mode warnings
  29. ;; - undeclared-variable warnings using a configurable externs framework
  30. ;; - "bouncing" line indentation to choose among alternate indentation points
  31. ;; - smart line-wrapping within comments and strings
  32. ;; - code folding:
  33. ;; - show some or all function bodies as {...}
  34. ;; - show some or all block comments as /*...*/
  35. ;; - context-sensitive menu bar and popup menus
  36. ;; - code browsing using the `imenu' package
  37. ;; - many customization options
  38. ;; Installation:
  39. ;;
  40. ;; To install it as your major mode for JavaScript editing:
  41. ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
  42. ;; Alternatively, to install it as a minor mode just for JavaScript linting,
  43. ;; you must add it to the appropriate major-mode hook. Normally this would be:
  44. ;; (add-hook 'js-mode-hook 'js2-minor-mode)
  45. ;; You may also want to hook it in for shell scripts running via node.js:
  46. ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
  47. ;; Support for JSX is available via the derived mode `js2-jsx-mode'. If you
  48. ;; also want JSX support, use that mode instead:
  49. ;; (add-to-list 'auto-mode-alist '("\\.jsx?\\'" . js2-jsx-mode))
  50. ;; (add-to-list 'interpreter-mode-alist '("node" . js2-jsx-mode))
  51. ;; To customize how it works:
  52. ;; M-x customize-group RET js2-mode RET
  53. ;; Notes:
  54. ;; This mode includes a port of Mozilla Rhino's scanner, parser and
  55. ;; symbol table. Ideally it should stay in sync with Rhino, keeping
  56. ;; `js2-mode' current as the EcmaScript language standard evolves.
  57. ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
  58. ;; customizable. It is a surprising amount of work to support customizable
  59. ;; indentation. The current compromise is that the tab key lets you cycle among
  60. ;; various likely indentation points, similar to the behavior of python-mode.
  61. ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
  62. ;; and `mumamo', although it could be made to do so with some effort.
  63. ;; This means that `js2-mode' is currently only useful for editing JavaScript
  64. ;; files, and not for editing JavaScript within <script> tags or templates.
  65. ;; The project page on GitHub is used for development and issue tracking.
  66. ;; The original homepage at Google Code has outdated information and is mostly
  67. ;; unmaintained.
  68. ;;; Code:
  69. (require 'cl-lib)
  70. (require 'imenu)
  71. (require 'js)
  72. (require 'etags)
  73. (eval-and-compile
  74. (if (version< emacs-version "25.0")
  75. (require 'js2-old-indent)
  76. (defvaralias 'js2-basic-offset 'js-indent-level nil)
  77. (defalias 'js2-proper-indentation 'js--proper-indentation)
  78. (defalias 'js2-jsx-indent-line 'js-jsx-indent-line)
  79. (defalias 'js2-indent-line 'js-indent-line)
  80. (defalias 'js2-re-search-forward 'js--re-search-forward)))
  81. ;;; Externs (variables presumed to be defined by the host system)
  82. (defvar js2-ecma-262-externs
  83. (mapcar 'symbol-name
  84. '(Array Boolean Date Error EvalError Function Infinity JSON
  85. Math NaN Number Object RangeError ReferenceError RegExp
  86. String SyntaxError TypeError URIError
  87. decodeURI decodeURIComponent encodeURI
  88. encodeURIComponent escape eval isFinite isNaN
  89. parseFloat parseInt undefined unescape))
  90. "Ecma-262 externs. Never highlighted as undeclared variables.")
  91. (defvar js2-browser-externs
  92. (mapcar 'symbol-name
  93. '(;; DOM level 1
  94. Attr CDATASection CharacterData Comment DOMException
  95. DOMImplementation Document DocumentFragment
  96. DocumentType Element Entity EntityReference
  97. ExceptionCode NamedNodeMap Node NodeList Notation
  98. ProcessingInstruction Text
  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. ;; DOM level 3
  122. DOMConfiguration DOMError DOMException
  123. DOMImplementationList DOMImplementationSource
  124. DOMLocator DOMStringList NameList TypeInfo
  125. UserDataHandler
  126. ;; Window
  127. window alert confirm document java navigator prompt screen
  128. self top requestAnimationFrame cancelAnimationFrame
  129. ;; W3C CSS
  130. CSSCharsetRule CSSFontFace CSSFontFaceRule
  131. CSSImportRule CSSMediaRule CSSPageRule
  132. CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
  133. CSSStyleDeclaration CSSStyleRule CSSStyleSheet
  134. CSSValue CSSValueList Counter DOMImplementationCSS
  135. DocumentCSS DocumentStyle ElementCSSInlineStyle
  136. LinkStyle MediaList RGBColor Rect StyleSheet
  137. StyleSheetList ViewCSS
  138. ;; W3C Event
  139. EventListener EventTarget Event DocumentEvent UIEvent
  140. MouseEvent MutationEvent KeyboardEvent
  141. ;; W3C Range
  142. DocumentRange Range RangeException
  143. ;; W3C XML
  144. XPathResult XMLHttpRequest
  145. ;; console object. Provided by at least Chrome and Firefox.
  146. console))
  147. "Browser externs.
  148. You can cause these to be included or excluded with the custom
  149. variable `js2-include-browser-externs'.")
  150. (defvar js2-rhino-externs
  151. (mapcar 'symbol-name
  152. '(Packages importClass importPackage com org java
  153. ;; Global object (shell) externs.
  154. defineClass deserialize doctest gc help load
  155. loadClass print quit readFile readUrl runCommand seal
  156. serialize spawn sync toint32 version))
  157. "Mozilla Rhino externs.
  158. Set `js2-include-rhino-externs' to t to include them.")
  159. (defvar js2-node-externs
  160. (mapcar 'symbol-name
  161. '(__dirname __filename Buffer clearInterval clearTimeout require
  162. console exports global module process setInterval setTimeout
  163. querystring setImmediate clearImmediate))
  164. "Node.js externs.
  165. Set `js2-include-node-externs' to t to include them.")
  166. (defvar js2-typed-array-externs
  167. (mapcar 'symbol-name
  168. '(ArrayBuffer Uint8ClampedArray DataView
  169. Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
  170. Float32Array Float64Array))
  171. "Khronos typed array externs. Available in most modern browsers and
  172. in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
  173. are enabled, these will also be included.")
  174. (defvar js2-harmony-externs
  175. (mapcar 'symbol-name
  176. '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
  177. "ES6 externs. If `js2-include-browser-externs' is enabled and
  178. `js2-language-version' is sufficiently high, these will be included.")
  179. ;;; Variables
  180. (defcustom js2-ignored-warnings nil
  181. "A list of warning message types that will not be reported.
  182. Possible values are the keys of `js2-message-table'."
  183. :group 'js2-mode
  184. :type '(repeat string))
  185. (defcustom js2-highlight-level 2
  186. "Amount of syntax highlighting to perform.
  187. 0 or a negative value means none.
  188. 1 adds basic syntax highlighting.
  189. 2 adds highlighting of some Ecma built-in properties.
  190. 3 adds highlighting of many Ecma built-in functions."
  191. :group 'js2-mode
  192. :type '(choice (const :tag "None" 0)
  193. (const :tag "Basic" 1)
  194. (const :tag "Include Properties" 2)
  195. (const :tag "Include Functions" 3)))
  196. (defvar js2-mode-dev-mode-p nil
  197. "Non-nil if running in development mode. Normally nil.")
  198. (defgroup js2-mode nil
  199. "An improved JavaScript mode."
  200. :group 'languages)
  201. (defcustom js2-idle-timer-delay 0.2
  202. "Delay in secs before re-parsing after user makes changes.
  203. Multiplied by `js2-dynamic-idle-timer-adjust', which see."
  204. :type 'number
  205. :group 'js2-mode)
  206. (make-variable-buffer-local 'js2-idle-timer-delay)
  207. (defcustom js2-dynamic-idle-timer-adjust 0
  208. "Positive to adjust `js2-idle-timer-delay' based on file size.
  209. The idea is that for short files, parsing is faster so we can be
  210. more responsive to user edits without interfering with editing.
  211. The buffer length in characters (typically bytes) is divided by
  212. this value and used to multiply `js2-idle-timer-delay' for the
  213. buffer. For example, a 21k file and 10k adjust yields 21k/10k
  214. == 2, so js2-idle-timer-delay is multiplied by 2.
  215. If `js2-dynamic-idle-timer-adjust' is 0 or negative,
  216. `js2-idle-timer-delay' is not dependent on the file size."
  217. :type 'number
  218. :group 'js2-mode)
  219. (defcustom js2-concat-multiline-strings t
  220. "When non-nil, `js2-line-break' in mid-string will make it a
  221. string concatenation. When `eol', the '+' will be inserted at the
  222. end of the line, otherwise, at the beginning of the next line."
  223. :type '(choice (const t) (const eol) (const nil))
  224. :group 'js2-mode)
  225. (defcustom js2-mode-show-parse-errors t
  226. "True to highlight parse errors."
  227. :type 'boolean
  228. :group 'js2-mode)
  229. (defcustom js2-mode-assume-strict nil
  230. "Non-nil to start files in strict mode automatically."
  231. :type 'boolean
  232. :group 'js2-mode)
  233. (defcustom js2-mode-show-strict-warnings t
  234. "Non-nil to emit Ecma strict-mode warnings.
  235. Some of the warnings can be individually disabled by other flags,
  236. even if this flag is non-nil."
  237. :type 'boolean
  238. :group 'js2-mode)
  239. (defcustom js2-strict-trailing-comma-warning nil
  240. "Non-nil to warn about trailing commas in array literals.
  241. Ecma-262-5.1 allows them, but older versions of IE raise an error."
  242. :type 'boolean
  243. :group 'js2-mode)
  244. (defcustom js2-strict-missing-semi-warning t
  245. "Non-nil to warn about semicolon auto-insertion after statement.
  246. Technically this is legal per Ecma-262, but some style guides disallow
  247. depending on it."
  248. :type 'boolean
  249. :group 'js2-mode)
  250. (defcustom js2-missing-semi-one-line-override nil
  251. "Non-nil to permit missing semicolons in one-line functions.
  252. In one-liner functions such as `function identity(x) {return x}'
  253. people often omit the semicolon for a cleaner look. If you are
  254. such a person, you can suppress the missing-semicolon warning
  255. by setting this variable to t."
  256. :type 'boolean
  257. :group 'js2-mode)
  258. (defcustom js2-strict-inconsistent-return-warning t
  259. "Non-nil to warn about mixing returns with value-returns.
  260. It's perfectly legal to have a `return' and a `return foo' in the
  261. same function, but it's often an indicator of a bug, and it also
  262. interferes with type inference (in systems that support it.)"
  263. :type 'boolean
  264. :group 'js2-mode)
  265. (defcustom js2-strict-cond-assign-warning t
  266. "Non-nil to warn about expressions like if (a = b).
  267. This often should have been '==' instead of '='. If the warning
  268. is enabled, you can suppress it on a per-expression basis by
  269. parenthesizing the expression, e.g. if ((a = b)) ..."
  270. :type 'boolean
  271. :group 'js2-mode)
  272. (defcustom js2-strict-var-redeclaration-warning t
  273. "Non-nil to warn about redeclaring variables in a script or function."
  274. :type 'boolean
  275. :group 'js2-mode)
  276. (defcustom js2-strict-var-hides-function-arg-warning t
  277. "Non-nil to warn about a var decl hiding a function argument."
  278. :type 'boolean
  279. :group 'js2-mode)
  280. (defcustom js2-skip-preprocessor-directives nil
  281. "Non-nil to treat lines beginning with # as comments.
  282. Useful for viewing Mozilla JavaScript source code."
  283. :type 'boolean
  284. :group 'js2-mode)
  285. (defcustom js2-language-version 200
  286. "Configures what JavaScript language version to recognize.
  287. Currently versions 150, 160, 170, 180 and 200 are supported,
  288. corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
  289. respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
  290. yield, and Array comprehensions, and 1.8 adds function closures."
  291. :type 'integer
  292. :group 'js2-mode)
  293. (defcustom js2-instanceof-has-side-effects nil
  294. "If non-nil, treats the instanceof operator as having side effects.
  295. This is useful for xulrunner apps."
  296. :type 'boolean
  297. :group 'js2-mode)
  298. (defcustom js2-getprop-has-side-effects nil
  299. "If non-nil, treats the getprop operator as having side effects.
  300. This is useful for testing libraries with nontrivial getters and for
  301. compilers that use empty getprops to declare interface properties."
  302. :type 'boolean
  303. :group 'js2-mode)
  304. (defcustom js2-move-point-on-right-click t
  305. "Non-nil to move insertion point when you right-click.
  306. This makes right-click context menu behavior a bit more intuitive,
  307. since menu operations generally apply to the point. The exception
  308. is if there is a region selection, in which case the point does -not-
  309. move, so cut/copy/paste can work properly.
  310. Note that IntelliJ moves the point, and Eclipse leaves it alone,
  311. so this behavior is customizable."
  312. :group 'js2-mode
  313. :type 'boolean)
  314. (defcustom js2-allow-rhino-new-expr-initializer t
  315. "Non-nil to support a Rhino's experimental syntactic construct.
  316. Rhino supports the ability to follow a `new' expression with an object
  317. literal, which is used to set additional properties on the new object
  318. after calling its constructor. Syntax:
  319. new <expr> [ ( arglist ) ] [initializer]
  320. Hence, this expression:
  321. new Object {a: 1, b: 2}
  322. results in an Object with properties a=1 and b=2. This syntax is
  323. apparently not configurable in Rhino - it's currently always enabled,
  324. as of Rhino version 1.7R2."
  325. :type 'boolean
  326. :group 'js2-mode)
  327. (defcustom js2-allow-member-expr-as-function-name nil
  328. "Non-nil to support experimental Rhino syntax for function names.
  329. Rhino supports an experimental syntax configured via the Rhino Context
  330. setting `allowMemberExprAsFunctionName'. The experimental syntax is:
  331. function <member-expr> ( [ arg-list ] ) { <body> }
  332. Where member-expr is a non-parenthesized 'member expression', which
  333. is anything at the grammar level of a new-expression or lower, meaning
  334. any expression that does not involve infix or unary operators.
  335. When <member-expr> is not a simple identifier, then it is syntactic
  336. sugar for assigning the anonymous function to the <member-expr>. Hence,
  337. this code:
  338. function a.b().c[2] (x, y) { ... }
  339. is rewritten as:
  340. a.b().c[2] = function(x, y) {...}
  341. which doesn't seem particularly useful, but Rhino permits it."
  342. :type 'boolean
  343. :group 'js2-mode)
  344. ;; scanner variables
  345. (defmacro js2-deflocal (name value &optional comment)
  346. "Define a buffer-local variable NAME with VALUE and COMMENT."
  347. (declare (debug defvar) (doc-string 3))
  348. `(progn
  349. (defvar ,name ,value ,comment)
  350. (make-variable-buffer-local ',name)))
  351. (defvar js2-EOF_CHAR -1
  352. "Represents end of stream. Distinct from js2-EOF token type.")
  353. ;; I originally used symbols to represent tokens, but Rhino uses
  354. ;; ints and then sets various flag bits in them, so ints it is.
  355. ;; The upshot is that we need a `js2-' prefix in front of each name.
  356. (defvar js2-ERROR -1)
  357. (defvar js2-EOF 0)
  358. (defvar js2-EOL 1)
  359. (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
  360. (defvar js2-LEAVEWITH 3)
  361. (defvar js2-RETURN 4)
  362. (defvar js2-GOTO 5)
  363. (defvar js2-IFEQ 6)
  364. (defvar js2-IFNE 7)
  365. (defvar js2-SETNAME 8)
  366. (defvar js2-BITOR 9)
  367. (defvar js2-BITXOR 10)
  368. (defvar js2-BITAND 11)
  369. (defvar js2-EQ 12)
  370. (defvar js2-NE 13)
  371. (defvar js2-LT 14)
  372. (defvar js2-LE 15)
  373. (defvar js2-GT 16)
  374. (defvar js2-GE 17)
  375. (defvar js2-LSH 18)
  376. (defvar js2-RSH 19)
  377. (defvar js2-URSH 20)
  378. (defvar js2-ADD 21) ; infix plus
  379. (defvar js2-SUB 22) ; infix minus
  380. (defvar js2-MUL 23)
  381. (defvar js2-DIV 24)
  382. (defvar js2-MOD 25)
  383. (defvar js2-NOT 26)
  384. (defvar js2-BITNOT 27)
  385. (defvar js2-POS 28) ; unary plus
  386. (defvar js2-NEG 29) ; unary minus
  387. (defvar js2-NEW 30)
  388. (defvar js2-DELPROP 31)
  389. (defvar js2-TYPEOF 32)
  390. (defvar js2-GETPROP 33)
  391. (defvar js2-GETPROPNOWARN 34)
  392. (defvar js2-SETPROP 35)
  393. (defvar js2-GETELEM 36)
  394. (defvar js2-SETELEM 37)
  395. (defvar js2-CALL 38)
  396. (defvar js2-NAME 39) ; an identifier
  397. (defvar js2-NUMBER 40)
  398. (defvar js2-STRING 41)
  399. (defvar js2-NULL 42)
  400. (defvar js2-THIS 43)
  401. (defvar js2-FALSE 44)
  402. (defvar js2-TRUE 45)
  403. (defvar js2-SHEQ 46) ; shallow equality (===)
  404. (defvar js2-SHNE 47) ; shallow inequality (!==)
  405. (defvar js2-REGEXP 48)
  406. (defvar js2-BINDNAME 49)
  407. (defvar js2-THROW 50)
  408. (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
  409. (defvar js2-IN 52)
  410. (defvar js2-INSTANCEOF 53)
  411. (defvar js2-LOCAL_LOAD 54)
  412. (defvar js2-GETVAR 55)
  413. (defvar js2-SETVAR 56)
  414. (defvar js2-CATCH_SCOPE 57)
  415. (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
  416. (defvar js2-ENUM_INIT_VALUES 59)
  417. (defvar js2-ENUM_INIT_ARRAY 60)
  418. (defvar js2-ENUM_NEXT 61)
  419. (defvar js2-ENUM_ID 62)
  420. (defvar js2-THISFN 63)
  421. (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
  422. (defvar js2-ARRAYLIT 65) ; array literal
  423. (defvar js2-OBJECTLIT 66) ; object literal
  424. (defvar js2-GET_REF 67) ; *reference
  425. (defvar js2-SET_REF 68) ; *reference = something
  426. (defvar js2-DEL_REF 69) ; delete reference
  427. (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
  428. (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
  429. (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
  430. ;; XML support
  431. (defvar js2-DEFAULTNAMESPACE 73)
  432. (defvar js2-ESCXMLATTR 74)
  433. (defvar js2-ESCXMLTEXT 75)
  434. (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
  435. (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
  436. (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
  437. (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
  438. (defvar js2-first-bytecode js2-ENTERWITH)
  439. (defvar js2-last-bytecode js2-REF_NS_NAME)
  440. (defvar js2-TRY 80)
  441. (defvar js2-SEMI 81) ; semicolon
  442. (defvar js2-LB 82) ; left and right brackets
  443. (defvar js2-RB 83)
  444. (defvar js2-LC 84) ; left and right curly-braces
  445. (defvar js2-RC 85)
  446. (defvar js2-LP 86) ; left and right parens
  447. (defvar js2-RP 87)
  448. (defvar js2-COMMA 88) ; comma operator
  449. (defvar js2-ASSIGN 89) ; simple assignment (=)
  450. (defvar js2-ASSIGN_BITOR 90) ; |=
  451. (defvar js2-ASSIGN_BITXOR 91) ; ^=
  452. (defvar js2-ASSIGN_BITAND 92) ; &=
  453. (defvar js2-ASSIGN_LSH 93) ; <<=
  454. (defvar js2-ASSIGN_RSH 94) ; >>=
  455. (defvar js2-ASSIGN_URSH 95) ; >>>=
  456. (defvar js2-ASSIGN_ADD 96) ; +=
  457. (defvar js2-ASSIGN_SUB 97) ; -=
  458. (defvar js2-ASSIGN_MUL 98) ; *=
  459. (defvar js2-ASSIGN_DIV 99) ; /=
  460. (defvar js2-ASSIGN_MOD 100) ; %=
  461. (defvar js2-ASSIGN_EXPON 101)
  462. (defvar js2-first-assign js2-ASSIGN)
  463. (defvar js2-last-assign js2-ASSIGN_EXPON)
  464. (defvar js2-COLON 102)
  465. (defvar js2-OR 103) ; logical or (||)
  466. (defvar js2-AND 104) ; logical and (&&)
  467. (defvar js2-INC 105) ; increment/decrement (++ --)
  468. (defvar js2-DEC 106)
  469. (defvar js2-DOT 107) ; member operator (.)
  470. (defvar js2-FUNCTION 108) ; function keyword
  471. (defvar js2-EXPORT 109) ; export keyword
  472. (defvar js2-IMPORT 110) ; import keyword
  473. (defvar js2-IF 111) ; if keyword
  474. (defvar js2-ELSE 112) ; else keyword
  475. (defvar js2-SWITCH 113) ; switch keyword
  476. (defvar js2-CASE 114) ; case keyword
  477. (defvar js2-DEFAULT 115) ; default keyword
  478. (defvar js2-WHILE 116) ; while keyword
  479. (defvar js2-DO 117) ; do keyword
  480. (defvar js2-FOR 118) ; for keyword
  481. (defvar js2-BREAK 119) ; break keyword
  482. (defvar js2-CONTINUE 120) ; continue keyword
  483. (defvar js2-VAR 121) ; var keyword
  484. (defvar js2-WITH 122) ; with keyword
  485. (defvar js2-CATCH 123) ; catch keyword
  486. (defvar js2-FINALLY 124) ; finally keyword
  487. (defvar js2-VOID 125) ; void keyword
  488. (defvar js2-RESERVED 126) ; reserved keywords
  489. (defvar js2-EMPTY 127)
  490. ;; Types used for the parse tree - never returned by scanner.
  491. (defvar js2-BLOCK 128) ; statement block
  492. (defvar js2-LABEL 129) ; label
  493. (defvar js2-TARGET 130)
  494. (defvar js2-LOOP 131)
  495. (defvar js2-EXPR_VOID 132) ; expression statement in functions
  496. (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
  497. (defvar js2-JSR 134)
  498. (defvar js2-SCRIPT 135) ; top-level node for entire script
  499. (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
  500. (defvar js2-USE_STACK 137)
  501. (defvar js2-SETPROP_OP 138) ; x.y op= something
  502. (defvar js2-SETELEM_OP 139) ; x[y] op= something
  503. (defvar js2-LOCAL_BLOCK 140)
  504. (defvar js2-SET_REF_OP 141) ; *reference op= something
  505. ;; For XML support:
  506. (defvar js2-DOTDOT 142) ; member operator (..)
  507. (defvar js2-COLONCOLON 143) ; namespace::name
  508. (defvar js2-XML 144) ; XML type
  509. (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
  510. (defvar js2-XMLATTR 146) ; @
  511. (defvar js2-XMLEND 147)
  512. ;; Optimizer-only tokens
  513. (defvar js2-TO_OBJECT 148)
  514. (defvar js2-TO_DOUBLE 149)
  515. (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
  516. (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
  517. (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
  518. (defvar js2-CONST 153)
  519. (defvar js2-SETCONST 154)
  520. (defvar js2-SETCONSTVAR 155)
  521. (defvar js2-ARRAYCOMP 156)
  522. (defvar js2-LETEXPR 157)
  523. (defvar js2-WITHEXPR 158)
  524. (defvar js2-DEBUGGER 159)
  525. (defvar js2-COMMENT 160)
  526. (defvar js2-TRIPLEDOT 161) ; for rest parameter
  527. (defvar js2-ARROW 162) ; function arrow (=>)
  528. (defvar js2-CLASS 163)
  529. (defvar js2-EXTENDS 164)
  530. (defvar js2-SUPER 165)
  531. (defvar js2-TEMPLATE_HEAD 166) ; part of template literal before substitution
  532. (defvar js2-NO_SUBS_TEMPLATE 167) ; template literal without substitutions
  533. (defvar js2-TAGGED_TEMPLATE 168) ; tagged template literal
  534. (defvar js2-AWAIT 169) ; await (pseudo keyword)
  535. (defvar js2-HOOK 170) ; conditional (?:)
  536. (defvar js2-EXPON 171)
  537. (defconst js2-num-tokens (1+ js2-EXPON))
  538. (defconst js2-debug-print-trees nil)
  539. ;; Rhino accepts any string or stream as input. Emacs character
  540. ;; processing works best in buffers, so we'll assume the input is a
  541. ;; buffer. JavaScript strings can be copied into temp buffers before
  542. ;; scanning them.
  543. ;; Buffer-local variables yield much cleaner code than using `defstruct'.
  544. ;; They're the Emacs equivalent of instance variables, more or less.
  545. (js2-deflocal js2-ts-dirty-line nil
  546. "Token stream buffer-local variable.
  547. Indicates stuff other than whitespace since start of line.")
  548. (js2-deflocal js2-ts-hit-eof nil
  549. "Token stream buffer-local variable.")
  550. ;; FIXME: Unused.
  551. (js2-deflocal js2-ts-line-start 0
  552. "Token stream buffer-local variable.")
  553. (js2-deflocal js2-ts-lineno 1
  554. "Token stream buffer-local variable.")
  555. ;; FIXME: Unused.
  556. (js2-deflocal js2-ts-line-end-char -1
  557. "Token stream buffer-local variable.")
  558. (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
  559. "Token stream buffer-local variable.
  560. Current scan position.")
  561. ;; FIXME: Unused.
  562. (js2-deflocal js2-ts-is-xml-attribute nil
  563. "Token stream buffer-local variable.")
  564. (js2-deflocal js2-ts-xml-is-tag-content nil
  565. "Token stream buffer-local variable.")
  566. (js2-deflocal js2-ts-xml-open-tags-count 0
  567. "Token stream buffer-local variable.")
  568. (js2-deflocal js2-ts-string-buffer nil
  569. "Token stream buffer-local variable.
  570. List of chars built up while scanning various tokens.")
  571. (cl-defstruct (js2-token
  572. (:constructor make-js2-token (beg)))
  573. "Value returned from the token stream."
  574. (type js2-EOF)
  575. (beg 1)
  576. (end -1)
  577. (string "")
  578. number
  579. number-base
  580. number-legacy-octal-p
  581. regexp-flags
  582. comment-type
  583. follows-eol-p)
  584. ;; Have to call `js2-init-scanner' to initialize the values.
  585. (js2-deflocal js2-ti-tokens nil)
  586. (js2-deflocal js2-ti-tokens-cursor nil)
  587. (js2-deflocal js2-ti-lookahead nil)
  588. (cl-defstruct (js2-ts-state
  589. (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
  590. (cursor js2-ts-cursor)
  591. (tokens (copy-sequence js2-ti-tokens))
  592. (tokens-cursor js2-ti-tokens-cursor)
  593. (lookahead js2-ti-lookahead))))
  594. lineno
  595. cursor
  596. tokens
  597. tokens-cursor
  598. lookahead)
  599. ;;; Parser variables
  600. (js2-deflocal js2-parsed-errors nil
  601. "List of errors produced during scanning/parsing.")
  602. (js2-deflocal js2-parsed-warnings nil
  603. "List of warnings produced during scanning/parsing.")
  604. (js2-deflocal js2-recover-from-parse-errors t
  605. "Non-nil to continue parsing after a syntax error.
  606. In recovery mode, the AST will be built in full, and any error
  607. nodes will be flagged with appropriate error information. If
  608. this flag is nil, a syntax error will result in an error being
  609. signaled.
  610. The variable is automatically buffer-local, because different
  611. modes that use the parser will need different settings.")
  612. (js2-deflocal js2-parse-hook nil
  613. "List of callbacks for receiving parsing progress.")
  614. (defvar js2-parse-finished-hook nil
  615. "List of callbacks to notify when parsing finishes.
  616. Not called if parsing was interrupted.")
  617. (js2-deflocal js2-is-eval-code nil
  618. "True if we're evaluating code in a string.
  619. If non-nil, the tokenizer will record the token text, and the AST nodes
  620. will record their source text. Off by default for IDE modes, since the
  621. text is available in the buffer.")
  622. (defvar js2-parse-ide-mode t
  623. "Non-nil if the parser is being used for `js2-mode'.
  624. If non-nil, the parser will set text properties for fontification
  625. and the syntax table. The value should be nil when using the
  626. parser as a frontend to an interpreter or byte compiler.")
  627. ;;; Parser instance variables (buffer-local vars for js2-parse)
  628. (defconst js2-ti-after-eol (lsh 1 16)
  629. "Flag: first token of the source line.")
  630. ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
  631. (js2-deflocal js2-compiler-generate-debug-info t)
  632. (js2-deflocal js2-compiler-use-dynamic-scope nil)
  633. (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
  634. (js2-deflocal js2-compiler-xml-available t)
  635. (js2-deflocal js2-compiler-optimization-level 0)
  636. (js2-deflocal js2-compiler-generating-source t)
  637. (js2-deflocal js2-compiler-strict-mode nil)
  638. (js2-deflocal js2-compiler-report-warning-as-error nil)
  639. (js2-deflocal js2-compiler-generate-observer-count nil)
  640. (js2-deflocal js2-compiler-activation-names nil)
  641. ;; SKIP: sourceURI
  642. ;; There's a compileFunction method in Context.java - may need it.
  643. (js2-deflocal js2-called-by-compile-function nil
  644. "True if `js2-parse' was called by `js2-compile-function'.
  645. Will only be used when we finish implementing the interpreter.")
  646. ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
  647. ;; SKIP: node factory - we're going to just call functions directly,
  648. ;; and eventually go to a unified AST format.
  649. (js2-deflocal js2-nesting-of-function 0)
  650. (js2-deflocal js2-recorded-identifiers nil
  651. "Tracks identifiers found during parsing.")
  652. (js2-deflocal js2-is-in-destructuring nil
  653. "True while parsing destructuring expression.")
  654. (js2-deflocal js2-in-use-strict-directive nil
  655. "True while inside a script or function under strict mode.")
  656. (defcustom js2-global-externs nil
  657. "A list of any extern names you'd like to consider always declared.
  658. This list is global and is used by all `js2-mode' files.
  659. You can create buffer-local externs list using `js2-additional-externs'."
  660. :type 'list
  661. :group 'js2-mode)
  662. (defcustom js2-include-browser-externs t
  663. "Non-nil to include browser externs in the master externs list.
  664. If you work on JavaScript files that are not intended for browsers,
  665. such as Mozilla Rhino server-side JavaScript, set this to nil.
  666. See `js2-additional-externs' for more information about externs."
  667. :type 'boolean
  668. :group 'js2-mode)
  669. (defcustom js2-include-rhino-externs nil
  670. "Non-nil to include Mozilla Rhino externs in the master externs list.
  671. See `js2-additional-externs' for more information about externs."
  672. :type 'boolean
  673. :group 'js2-mode)
  674. (defcustom js2-include-node-externs nil
  675. "Non-nil to include Node.js externs in the master externs list.
  676. See `js2-additional-externs' for more information about externs."
  677. :type 'boolean
  678. :group 'js2-mode)
  679. (js2-deflocal js2-additional-externs nil
  680. "A buffer-local list of additional external declarations.
  681. It is used to decide whether variables are considered undeclared
  682. for purposes of highlighting. See `js2-highlight-undeclared-vars'.
  683. Each entry is a Lisp string. The string should be the fully qualified
  684. name of an external entity. All externs should be added to this list,
  685. so that as js2-mode's processing improves it can take advantage of them.
  686. You may want to declare your externs in three ways.
  687. First, you can add externs that are valid for all your JavaScript files.
  688. You should probably do this by adding them to `js2-global-externs', which
  689. is a global list used for all js2-mode files.
  690. Next, you can add a function to `js2-init-hook' that adds additional
  691. externs appropriate for the specific file, perhaps based on its path.
  692. These should go in `js2-additional-externs', which is buffer-local.
  693. Third, you can use JSLint's global declaration, as long as
  694. `js2-include-jslint-globals' is non-nil, which see.
  695. Finally, you can add a function to `js2-post-parse-callbacks',
  696. which is called after parsing completes, and `js2-mode-ast' is bound to
  697. the root of the parse tree. At this stage you can set up an AST
  698. node visitor using `js2-visit-ast' and examine the parse tree
  699. for specific import patterns that may imply the existence of
  700. other externs, possibly tied to your build system. These should also
  701. be added to `js2-additional-externs'.
  702. Your post-parse callback may of course also use the simpler and
  703. faster (but perhaps less robust) approach of simply scanning the
  704. buffer text for your imports, using regular expressions.")
  705. (put 'js2-additional-externs 'safe-local-variable
  706. (lambda (val) (cl-every #'stringp val)))
  707. ;; SKIP: decompiler
  708. ;; SKIP: encoded-source
  709. ;;; The following variables are per-function and should be saved/restored
  710. ;;; during function parsing...
  711. (js2-deflocal js2-current-script-or-fn nil)
  712. (js2-deflocal js2-current-scope nil)
  713. (js2-deflocal js2-nesting-of-with 0)
  714. (js2-deflocal js2-label-set nil
  715. "An alist mapping label names to nodes.")
  716. (js2-deflocal js2-loop-set nil)
  717. (js2-deflocal js2-loop-and-switch-set nil)
  718. (js2-deflocal js2-has-return-value nil)
  719. (js2-deflocal js2-end-flags 0)
  720. ;;; ...end of per function variables
  721. ;; These flags enumerate the possible ways a statement/function can
  722. ;; terminate. These flags are used by endCheck() and by the Parser to
  723. ;; detect inconsistent return usage.
  724. ;;
  725. ;; END_UNREACHED is reserved for code paths that are assumed to always be
  726. ;; able to execute (example: throw, continue)
  727. ;;
  728. ;; END_DROPS_OFF indicates if the statement can transfer control to the
  729. ;; next one. Statement such as return dont. A compound statement may have
  730. ;; some branch that drops off control to the next statement.
  731. ;;
  732. ;; END_RETURNS indicates that the statement can return (without arguments)
  733. ;; END_RETURNS_VALUE indicates that the statement can return a value.
  734. ;;
  735. ;; A compound statement such as
  736. ;; if (condition) {
  737. ;; return value;
  738. ;; }
  739. ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
  740. (defconst js2-end-unreached #x0)
  741. (defconst js2-end-drops-off #x1)
  742. (defconst js2-end-returns #x2)
  743. (defconst js2-end-returns-value #x4)
  744. ;; Rhino awkwardly passes a statementLabel parameter to the
  745. ;; statementHelper() function, the main statement parser, which
  746. ;; is then used by quite a few of the sub-parsers. We just make
  747. ;; it a buffer-local variable and make sure it's cleaned up properly.
  748. (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
  749. ;; Similarly, Rhino passes an inForInit boolean through about half
  750. ;; the expression parsers. We use a dynamically-scoped variable,
  751. ;; which makes it easier to funcall the parsers individually without
  752. ;; worrying about whether they take the parameter or not.
  753. (js2-deflocal js2-in-for-init nil)
  754. (js2-deflocal js2-temp-name-counter 0)
  755. (js2-deflocal js2-parse-stmt-count 0)
  756. (defsubst js2-get-next-temp-name ()
  757. (format "$%d" (cl-incf js2-temp-name-counter)))
  758. (defvar js2-parse-interruptable-p t
  759. "Set this to nil to force parse to continue until finished.
  760. This will mostly be useful for interpreters.")
  761. (defvar js2-statements-per-pause 50
  762. "Pause after this many statements to check for user input.
  763. If user input is pending, stop the parse and discard the tree.
  764. This makes for a smoother user experience for large files.
  765. You may have to wait a second or two before the highlighting
  766. and error-reporting appear, but you can always type ahead if
  767. you wish. This appears to be more or less how Eclipse, IntelliJ
  768. and other editors work.")
  769. (js2-deflocal js2-record-comments t
  770. "Instructs the scanner to record comments in `js2-scanned-comments'.")
  771. (js2-deflocal js2-scanned-comments nil
  772. "List of all comments from the current parse.")
  773. (defcustom js2-mode-indent-inhibit-undo nil
  774. "Non-nil to disable collection of Undo information when indenting lines.
  775. Some users have requested this behavior. It's nil by default because
  776. other Emacs modes don't work this way."
  777. :type 'boolean
  778. :group 'js2-mode)
  779. (defcustom js2-mode-indent-ignore-first-tab nil
  780. "If non-nil, ignore first TAB keypress if we look indented properly.
  781. It's fairly common for users to navigate to an already-indented line
  782. and press TAB for reassurance that it's been indented. For this class
  783. of users, we want the first TAB press on a line to be ignored if the
  784. line is already indented to one of the precomputed alternatives.
  785. This behavior is only partly implemented. If you TAB-indent a line,
  786. navigate to another line, and then navigate back, it fails to clear
  787. the last-indented variable, so it thinks you've already hit TAB once,
  788. and performs the indent. A full solution would involve getting on the
  789. point-motion hooks for the entire buffer. If we come across another
  790. use cases that requires watching point motion, I'll consider doing it.
  791. If you set this variable to nil, then the TAB key will always change
  792. the indentation of the current line, if more than one alternative
  793. indentation spot exists."
  794. :type 'boolean
  795. :group 'js2-mode)
  796. (defvar js2-indent-hook nil
  797. "A hook for user-defined indentation rules.
  798. Functions on this hook should expect two arguments: (LIST INDEX)
  799. The LIST argument is the list of computed indentation points for
  800. the current line. INDEX is the list index of the indentation point
  801. that `js2-bounce-indent' plans to use. If INDEX is nil, then the
  802. indent function is not going to change the current line indentation.
  803. If a hook function on this list returns a non-nil value, then
  804. `js2-bounce-indent' assumes the hook function has performed its own
  805. indentation, and will do nothing. If all hook functions on the list
  806. return nil, then `js2-bounce-indent' will use its computed indentation
  807. and reindent the line.
  808. When hook functions on this hook list are called, the variable
  809. `js2-mode-ast' may or may not be set, depending on whether the
  810. parse tree is available. If the variable is nil, you can pass a
  811. callback to `js2-mode-wait-for-parse', and your callback will be
  812. called after the new parse tree is built. This can take some time
  813. in large files.")
  814. (defface js2-warning
  815. `((((class color) (background light))
  816. (:underline "orange"))
  817. (((class color) (background dark))
  818. (:underline "orange"))
  819. (t (:underline t)))
  820. "Face for JavaScript warnings."
  821. :group 'js2-mode)
  822. (defface js2-error
  823. `((((class color) (background light))
  824. (:foreground "red"))
  825. (((class color) (background dark))
  826. (:foreground "red"))
  827. (t (:foreground "red")))
  828. "Face for JavaScript errors."
  829. :group 'js2-mode)
  830. (defface js2-jsdoc-tag
  831. '((t :foreground "SlateGray"))
  832. "Face used to highlight @whatever tags in jsdoc comments."
  833. :group 'js2-mode)
  834. (defface js2-jsdoc-type
  835. '((t :foreground "SteelBlue"))
  836. "Face used to highlight {FooBar} types in jsdoc comments."
  837. :group 'js2-mode)
  838. (defface js2-jsdoc-value
  839. '((t :foreground "PeachPuff3"))
  840. "Face used to highlight tag values in jsdoc comments."
  841. :group 'js2-mode)
  842. (defface js2-function-param
  843. '((t :foreground "SeaGreen"))
  844. "Face used to highlight function parameters in javascript."
  845. :group 'js2-mode)
  846. (defface js2-function-call
  847. '((t :inherit default))
  848. "Face used to highlight function name in calls."
  849. :group 'js2-mode)
  850. (defface js2-object-property
  851. '((t :inherit default))
  852. "Face used to highlight named property in object literal."
  853. :group 'js2-mode)
  854. (defface js2-object-property-access
  855. '((t :inherit js2-object-property))
  856. "Face used to highlight property access with dot on an object."
  857. :group 'js2-mode)
  858. (defface js2-instance-member
  859. '((t :foreground "DarkOrchid"))
  860. "Face used to highlight instance variables in javascript.
  861. Not currently used."
  862. :group 'js2-mode)
  863. (defface js2-private-member
  864. '((t :foreground "PeachPuff3"))
  865. "Face used to highlight calls to private methods in javascript.
  866. Not currently used."
  867. :group 'js2-mode)
  868. (defface js2-private-function-call
  869. '((t :foreground "goldenrod"))
  870. "Face used to highlight calls to private functions in javascript.
  871. Not currently used."
  872. :group 'js2-mode)
  873. (defface js2-jsdoc-html-tag-name
  874. '((((class color) (min-colors 88) (background light))
  875. (:foreground "rosybrown"))
  876. (((class color) (min-colors 8) (background dark))
  877. (:foreground "yellow"))
  878. (((class color) (min-colors 8) (background light))
  879. (:foreground "magenta")))
  880. "Face used to highlight jsdoc html tag names"
  881. :group 'js2-mode)
  882. (defface js2-jsdoc-html-tag-delimiter
  883. '((((class color) (min-colors 88) (background light))
  884. (:foreground "dark khaki"))
  885. (((class color) (min-colors 8) (background dark))
  886. (:foreground "green"))
  887. (((class color) (min-colors 8) (background light))
  888. (:foreground "green")))
  889. "Face used to highlight brackets in jsdoc html tags."
  890. :group 'js2-mode)
  891. (defface js2-external-variable
  892. '((t :foreground "orange"))
  893. "Face used to highlight undeclared variable identifiers.")
  894. (defcustom js2-init-hook nil
  895. ;; FIXME: We don't really need this anymore.
  896. "List of functions to be called after `js2-mode' or
  897. `js2-minor-mode' has initialized all variables, before parsing
  898. the buffer for the first time."
  899. :type 'hook
  900. :group 'js2-mode
  901. :version "20130608")
  902. (defcustom js2-post-parse-callbacks nil
  903. "List of callback functions invoked after parsing finishes.
  904. Currently, the main use for this function is to add synthetic
  905. declarations to `js2-recorded-identifiers', which see."
  906. :type 'hook
  907. :group 'js2-mode)
  908. (defcustom js2-build-imenu-callbacks nil
  909. "List of functions called during Imenu index generation.
  910. It's a good place to add additional entries to it, using
  911. `js2-record-imenu-entry'."
  912. :type 'hook
  913. :group 'js2-mode)
  914. (defcustom js2-highlight-external-variables t
  915. "Non-nil to highlight undeclared variable identifiers.
  916. An undeclared variable is any variable not declared with var or let
  917. in the current scope or any lexically enclosing scope. If you use
  918. such a variable, then you are either expecting it to originate from
  919. another file, or you've got a potential bug."
  920. :type 'boolean
  921. :group 'js2-mode)
  922. (defcustom js2-warn-about-unused-function-arguments nil
  923. "Non-nil to treat function arguments like declared-but-unused variables."
  924. :type 'booleanp
  925. :group 'js2-mode)
  926. (defcustom js2-include-jslint-globals t
  927. "Non-nil to include the identifiers from JSLint global
  928. declaration (see http://www.jslint.com/help.html#global) in the
  929. buffer-local externs list. See `js2-additional-externs' for more
  930. information."
  931. :type 'boolean
  932. :group 'js2-mode)
  933. (defcustom js2-include-jslint-declaration-externs t
  934. "Non-nil to include the identifiers JSLint assumes to be there
  935. under certain declarations in the buffer-local externs list. See
  936. `js2-additional-externs' for more information."
  937. :type 'boolean
  938. :group 'js2-mode)
  939. (defvar js2-mode-map
  940. (let ((map (make-sparse-keymap)))
  941. (define-key map [remap indent-new-comment-line] #'js2-line-break)
  942. (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
  943. (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
  944. (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
  945. (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
  946. (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
  947. (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
  948. (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
  949. (define-key map [down-mouse-3] #'js2-down-mouse-3)
  950. (define-key map [remap js-find-symbol] #'js2-jump-to-definition)
  951. (define-key map [menu-bar javascript]
  952. (cons "JavaScript" (make-sparse-keymap "JavaScript")))
  953. (define-key map [menu-bar javascript customize-js2-mode]
  954. '(menu-item "Customize js2-mode" js2-mode-customize
  955. :help "Customize the behavior of this mode"))
  956. (define-key map [menu-bar javascript js2-force-refresh]
  957. '(menu-item "Force buffer refresh" js2-mode-reset
  958. :help "Re-parse the buffer from scratch"))
  959. (define-key map [menu-bar javascript separator-2]
  960. '("--"))
  961. (define-key map [menu-bar javascript next-error]
  962. '(menu-item "Next warning or error" next-error
  963. :enabled (and js2-mode-ast
  964. (or (js2-ast-root-errors js2-mode-ast)
  965. (js2-ast-root-warnings js2-mode-ast)))
  966. :help "Move to next warning or error"))
  967. (define-key map [menu-bar javascript display-errors]
  968. '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
  969. :visible (not js2-mode-show-parse-errors)
  970. :help "Turn on display of warnings and errors"))
  971. (define-key map [menu-bar javascript hide-errors]
  972. '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
  973. :visible js2-mode-show-parse-errors
  974. :help "Turn off display of warnings and errors"))
  975. (define-key map [menu-bar javascript separator-1]
  976. '("--"))
  977. (define-key map [menu-bar javascript js2-toggle-function]
  978. '(menu-item "Show/collapse element" js2-mode-toggle-element
  979. :help "Hide or show function body or comment"))
  980. (define-key map [menu-bar javascript show-comments]
  981. '(menu-item "Show block comments" js2-mode-toggle-hide-comments
  982. :visible js2-mode-comments-hidden
  983. :help "Expand all hidden block comments"))
  984. (define-key map [menu-bar javascript hide-comments]
  985. '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
  986. :visible (not js2-mode-comments-hidden)
  987. :help "Show block comments as /*...*/"))
  988. (define-key map [menu-bar javascript show-all-functions]
  989. '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
  990. :visible js2-mode-functions-hidden
  991. :help "Expand all hidden function bodies"))
  992. (define-key map [menu-bar javascript hide-all-functions]
  993. '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
  994. :visible (not js2-mode-functions-hidden)
  995. :help "Show {...} for all top-level function bodies"))
  996. map)
  997. "Keymap used in `js2-mode' buffers.")
  998. (defcustom js2-bounce-indent-p nil
  999. "Non-nil to bind `js2-indent-bounce' and `js2-indent-bounce-backward'.
  1000. They will augment the default indent-line behavior with cycling
  1001. among several computed alternatives. See the function
  1002. `js2-bounce-indent' for details. The above commands will be
  1003. bound to TAB and backtab."
  1004. :type 'boolean
  1005. :group 'js2-mode
  1006. :set (lambda (sym value)
  1007. (set-default sym value)
  1008. (let ((map js2-mode-map))
  1009. (if (not value)
  1010. (progn
  1011. (define-key map "\t" nil)
  1012. (define-key map (kbd "<backtab>") nil))
  1013. (define-key map "\t" #'js2-indent-bounce)
  1014. (define-key map (kbd "<backtab>") #'js2-indent-bounce-backward)))))
  1015. (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
  1016. (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
  1017. "Matches a //-comment line. Must be first non-whitespace on line.
  1018. First match-group is the leading whitespace.")
  1019. (defvar js2-mode-hook nil)
  1020. (js2-deflocal js2-mode-ast nil "Private variable.")
  1021. (js2-deflocal js2-mode-parse-timer nil "Private variable.")
  1022. (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
  1023. (js2-deflocal js2-mode-parsing nil "Private variable.")
  1024. (js2-deflocal js2-mode-node-overlay nil)
  1025. (defvar js2-mode-show-overlay js2-mode-dev-mode-p
  1026. "Debug: Non-nil to highlight AST nodes on mouse-down.")
  1027. (js2-deflocal js2-mode-fontifications nil "Private variable")
  1028. (js2-deflocal js2-mode-deferred-properties nil "Private variable")
  1029. (js2-deflocal js2-imenu-recorder nil "Private variable")
  1030. (js2-deflocal js2-imenu-function-map nil "Private variable")
  1031. (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
  1032. "Non-nil to emit status messages during parsing.")
  1033. (defvar js2-mode-functions-hidden nil "Private variable.")
  1034. (defvar js2-mode-comments-hidden nil "Private variable.")
  1035. (defvar js2-mode-syntax-table
  1036. (let ((table (make-syntax-table)))
  1037. (c-populate-syntax-table table)
  1038. (modify-syntax-entry ?` "\"" table)
  1039. table)
  1040. "Syntax table used in `js2-mode' buffers.")
  1041. (defvar js2-mode-abbrev-table nil
  1042. "Abbrev table in use in `js2-mode' buffers.")
  1043. (define-abbrev-table 'js2-mode-abbrev-table ())
  1044. (defvar js2-mode-pending-parse-callbacks nil
  1045. "List of functions waiting to be notified that parse is finished.")
  1046. (defvar js2-mode-last-indented-line -1)
  1047. ;;; Localizable error and warning messages
  1048. ;; Messages are copied from Rhino's Messages.properties.
  1049. ;; Many of the Java-specific messages have been elided.
  1050. ;; Add any js2-specific ones at the end, so we can keep
  1051. ;; this file synced with changes to Rhino's.
  1052. (defvar js2-message-table
  1053. (make-hash-table :test 'equal :size 250)
  1054. "Contains localized messages for `js2-mode'.")
  1055. ;; TODO(stevey): construct this table at compile-time.
  1056. (defmacro js2-msg (key &rest strings)
  1057. `(puthash ,key (concat ,@strings)
  1058. js2-message-table))
  1059. (defun js2-get-msg (msg-key)
  1060. "Look up a localized message.
  1061. MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
  1062. the correct number of ARGS must be provided."
  1063. (let* ((key (if (listp msg-key) (car msg-key) msg-key))
  1064. (args (if (listp msg-key) (cdr msg-key)))
  1065. (msg (gethash key js2-message-table)))
  1066. (if msg
  1067. (apply #'format msg args)
  1068. key))) ; default to showing the key
  1069. (js2-msg "msg.dup.parms"
  1070. "Duplicate parameter name '%s'.")
  1071. (js2-msg "msg.too.big.jump"
  1072. "Program too complex: jump offset too big.")
  1073. (js2-msg "msg.too.big.index"
  1074. "Program too complex: internal index exceeds 64K limit.")
  1075. (js2-msg "msg.while.compiling.fn"
  1076. "Encountered code generation error while compiling function '%s': %s")
  1077. (js2-msg "msg.while.compiling.script"
  1078. "Encountered code generation error while compiling script: %s")
  1079. ;; Context
  1080. (js2-msg "msg.ctor.not.found"
  1081. "Constructor for '%s' not found.")
  1082. (js2-msg "msg.not.ctor"
  1083. "'%s' is not a constructor.")
  1084. ;; FunctionObject
  1085. (js2-msg "msg.varargs.ctor"
  1086. "Method or constructor '%s' must be static "
  1087. "with the signature (Context cx, Object[] args, "
  1088. "Function ctorObj, boolean inNewExpr) "
  1089. "to define a variable arguments constructor.")
  1090. (js2-msg "msg.varargs.fun"
  1091. "Method '%s' must be static with the signature "
  1092. "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
  1093. "to define a variable arguments function.")
  1094. (js2-msg "msg.incompat.call"
  1095. "Method '%s' called on incompatible object.")
  1096. (js2-msg "msg.bad.parms"
  1097. "Unsupported parameter type '%s' in method '%s'.")
  1098. (js2-msg "msg.bad.method.return"
  1099. "Unsupported return type '%s' in method '%s'.")
  1100. (js2-msg "msg.bad.ctor.return"
  1101. "Construction of objects of type '%s' is not supported.")
  1102. (js2-msg "msg.no.overload"
  1103. "Method '%s' occurs multiple times in class '%s'.")
  1104. (js2-msg "msg.method.not.found"
  1105. "Method '%s' not found in '%s'.")
  1106. ;; IRFactory
  1107. (js2-msg "msg.bad.for.in.lhs"
  1108. "Invalid left-hand side of for..in loop.")
  1109. (js2-msg "msg.mult.index"
  1110. "Only one variable allowed in for..in loop.")
  1111. (js2-msg "msg.bad.for.in.destruct"
  1112. "Left hand side of for..in loop must be an array of "
  1113. "length 2 to accept key/value pair.")
  1114. (js2-msg "msg.cant.convert"
  1115. "Can't convert to type '%s'.")
  1116. (js2-msg "msg.bad.assign.left"
  1117. "Invalid assignment left-hand side.")
  1118. (js2-msg "msg.bad.decr"
  1119. "Invalid decrement operand.")
  1120. (js2-msg "msg.bad.incr"
  1121. "Invalid increment operand.")
  1122. (js2-msg "msg.bad.yield"
  1123. "yield must be in a function.")
  1124. (js2-msg "msg.bad.await"
  1125. "await must be in async functions.")
  1126. ;; NativeGlobal
  1127. (js2-msg "msg.cant.call.indirect"
  1128. "Function '%s' must be called directly, and not by way of a "
  1129. "function of another name.")
  1130. (js2-msg "msg.eval.nonstring"
  1131. "Calling eval() with anything other than a primitive "
  1132. "string value will simply return the value. "
  1133. "Is this what you intended?")
  1134. (js2-msg "msg.eval.nonstring.strict"
  1135. "Calling eval() with anything other than a primitive "
  1136. "string value is not allowed in strict mode.")
  1137. (js2-msg "msg.bad.destruct.op"
  1138. "Invalid destructuring assignment operator")
  1139. ;; NativeCall
  1140. (js2-msg "msg.only.from.new"
  1141. "'%s' may only be invoked from a `new' expression.")
  1142. (js2-msg "msg.deprec.ctor"
  1143. "The '%s' constructor is deprecated.")
  1144. ;; NativeFunction
  1145. (js2-msg "msg.no.function.ref.found"
  1146. "no source found to decompile function reference %s")
  1147. (js2-msg "msg.arg.isnt.array"
  1148. "second argument to Function.prototype.apply must be an array")
  1149. ;; NativeGlobal
  1150. (js2-msg "msg.bad.esc.mask"
  1151. "invalid string escape mask")
  1152. ;; NativeRegExp
  1153. (js2-msg "msg.bad.quant"
  1154. "Invalid quantifier %s")
  1155. (js2-msg "msg.overlarge.backref"
  1156. "Overly large back reference %s")
  1157. (js2-msg "msg.overlarge.min"
  1158. "Overly large minimum %s")
  1159. (js2-msg "msg.overlarge.max"
  1160. "Overly large maximum %s")
  1161. (js2-msg "msg.zero.quant"
  1162. "Zero quantifier %s")
  1163. (js2-msg "msg.max.lt.min"
  1164. "Maximum %s less than minimum")
  1165. (js2-msg "msg.unterm.quant"
  1166. "Unterminated quantifier %s")
  1167. (js2-msg "msg.unterm.paren"
  1168. "Unterminated parenthetical %s")
  1169. (js2-msg "msg.unterm.class"
  1170. "Unterminated character class %s")
  1171. (js2-msg "msg.bad.range"
  1172. "Invalid range in character class.")
  1173. (js2-msg "msg.trail.backslash"
  1174. "Trailing \\ in regular expression.")
  1175. (js2-msg "msg.re.unmatched.right.paren"
  1176. "unmatched ) in regular expression.")
  1177. (js2-msg "msg.no.regexp"
  1178. "Regular expressions are not available.")
  1179. (js2-msg "msg.bad.backref"
  1180. "back-reference exceeds number of capturing parentheses.")
  1181. (js2-msg "msg.bad.regexp.compile"
  1182. "Only one argument may be specified if the first "
  1183. "argument to RegExp.prototype.compile is a RegExp object.")
  1184. ;; Parser
  1185. (js2-msg "msg.got.syntax.errors"
  1186. "Compilation produced %s syntax errors.")
  1187. (js2-msg "msg.var.redecl"
  1188. "Redeclaration of var %s.")
  1189. (js2-msg "msg.const.redecl"
  1190. "TypeError: redeclaration of const %s.")
  1191. (js2-msg "msg.let.redecl"
  1192. "TypeError: redeclaration of variable %s.")
  1193. (js2-msg "msg.parm.redecl"
  1194. "TypeError: redeclaration of formal parameter %s.")
  1195. (js2-msg "msg.fn.redecl"
  1196. "TypeError: redeclaration of function %s.")
  1197. (js2-msg "msg.let.decl.not.in.block"
  1198. "SyntaxError: let declaration not directly within block")
  1199. (js2-msg "msg.mod.import.decl.at.top.level"
  1200. "SyntaxError: import declarations may only appear at the top level")
  1201. (js2-msg "msg.mod.as.after.reserved.word"
  1202. "SyntaxError: missing keyword 'as' after reserved word %s")
  1203. (js2-msg "msg.mod.rc.after.import.spec.list"
  1204. "SyntaxError: missing '}' after module specifier list")
  1205. (js2-msg "msg.mod.from.after.import.spec.set"
  1206. "SyntaxError: missing keyword 'from' after import specifier set")
  1207. (js2-msg "msg.mod.declaration.after.import"
  1208. "SyntaxError: missing declaration after 'import' keyword")
  1209. (js2-msg "msg.mod.spec.after.from"
  1210. "SyntaxError: missing module specifier after 'from' keyword")
  1211. (js2-msg "msg.mod.export.decl.at.top.level"
  1212. "SyntaxError: export declarations may only appear at top level")
  1213. (js2-msg "msg.mod.rc.after.export.spec.list"
  1214. "SyntaxError: missing '}' after export specifier list")
  1215. ;; NodeTransformer
  1216. (js2-msg "msg.dup.label"
  1217. "duplicated label")
  1218. (js2-msg "msg.undef.label"
  1219. "undefined label")
  1220. (js2-msg "msg.bad.break"
  1221. "unlabelled break must be inside loop or switch")
  1222. (js2-msg "msg.continue.outside"
  1223. "continue must be inside loop")
  1224. (js2-msg "msg.continue.nonloop"
  1225. "continue can only use labels of iteration statements")
  1226. (js2-msg "msg.bad.throw.eol"
  1227. "Line terminator is not allowed between the throw "
  1228. "keyword and throw expression.")
  1229. (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
  1230. "function statement requires a name")
  1231. (js2-msg "msg.no.paren.parms"
  1232. "missing ( before function parameters.")
  1233. (js2-msg "msg.no.parm"
  1234. "missing formal parameter")
  1235. (js2-msg "msg.no.paren.after.parms"
  1236. "missing ) after formal parameters")
  1237. (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
  1238. "parameter without default follows parameter with default")
  1239. (js2-msg "msg.param.after.rest" ; added by js2-mode
  1240. "parameter after rest parameter")
  1241. (js2-msg "msg.bad.arrow.args" ; added by js2-mode
  1242. "invalid arrow-function arguments (parentheses around the arrow-function may help)")
  1243. (js2-msg "msg.no.brace.body"
  1244. "missing '{' before function body")
  1245. (js2-msg "msg.no.brace.after.body"
  1246. "missing } after function body")
  1247. (js2-msg "msg.no.paren.cond"
  1248. "missing ( before condition")
  1249. (js2-msg "msg.no.paren.after.cond"
  1250. "missing ) after condition")
  1251. (js2-msg "msg.no.semi.stmt"
  1252. "missing ; before statement")
  1253. (js2-msg "msg.missing.semi"
  1254. "missing ; after statement")
  1255. (js2-msg "msg.no.name.after.dot"
  1256. "missing name after . operator")
  1257. (js2-msg "msg.no.name.after.coloncolon"
  1258. "missing name after :: operator")
  1259. (js2-msg "msg.no.name.after.dotdot"
  1260. "missing name after .. operator")
  1261. (js2-msg "msg.no.name.after.xmlAttr"
  1262. "missing name after .@")
  1263. (js2-msg "msg.no.bracket.index"
  1264. "missing ] in index expression")
  1265. (js2-msg "msg.no.paren.switch"
  1266. "missing ( before switch expression")
  1267. (js2-msg "msg.no.paren.after.switch"
  1268. "missing ) after switch expression")
  1269. (js2-msg "msg.no.brace.switch"
  1270. "missing '{' before switch body")
  1271. (js2-msg "msg.bad.switch"
  1272. "invalid switch statement")
  1273. (js2-msg "msg.no.colon.case"
  1274. "missing : after case expression")
  1275. (js2-msg "msg.double.switch.default"
  1276. "double default label in the switch statement")
  1277. (js2-msg "msg.no.while.do"
  1278. "missing while after do-loop body")
  1279. (js2-msg "msg.no.paren.for"
  1280. "missing ( after for")
  1281. (js2-msg "msg.no.semi.for"
  1282. "missing ; after for-loop initializer")
  1283. (js2-msg "msg.no.semi.for.cond"
  1284. "missing ; after for-loop condition")
  1285. (js2-msg "msg.in.after.for.name"
  1286. "missing in or of after for")
  1287. (js2-msg "msg.no.paren.for.ctrl"
  1288. "missing ) after for-loop control")
  1289. (js2-msg "msg.no.paren.with"
  1290. "missing ( before with-statement object")
  1291. (js2-msg "msg.no.paren.after.with"
  1292. "missing ) after with-statement object")
  1293. (js2-msg "msg.no.with.strict"
  1294. "with statements not allowed in strict mode")
  1295. (js2-msg "msg.no.paren.after.let"
  1296. "missing ( after let")
  1297. (js2-msg "msg.no.paren.let"
  1298. "missing ) after variable list")
  1299. (js2-msg "msg.no.curly.let"
  1300. "missing } after let statement")
  1301. (js2-msg "msg.bad.return"
  1302. "invalid return")
  1303. (js2-msg "msg.no.brace.block"
  1304. "missing } in compound statement")
  1305. (js2-msg "msg.bad.label"
  1306. "invalid label")
  1307. (js2-msg "msg.bad.var"
  1308. "missing variable name")
  1309. (js2-msg "msg.bad.var.init"
  1310. "invalid variable initialization")
  1311. (js2-msg "msg.no.colon.cond"
  1312. "missing : in conditional expression")
  1313. (js2-msg "msg.no.paren.arg"
  1314. "missing ) after argument list")
  1315. (js2-msg "msg.no.bracket.arg"
  1316. "missing ] after element list")
  1317. (js2-msg "msg.bad.prop"
  1318. "invalid property id")
  1319. (js2-msg "msg.no.colon.prop"
  1320. "missing : after property id")
  1321. (js2-msg "msg.no.brace.prop"
  1322. "missing } after property list")
  1323. (js2-msg "msg.no.paren"
  1324. "missing ) in parenthetical")
  1325. (js2-msg "msg.reserved.id"
  1326. "'%s' is a reserved identifier")
  1327. (js2-msg "msg.no.paren.catch"
  1328. "missing ( before catch-block condition")
  1329. (js2-msg "msg.bad.catchcond"
  1330. "invalid catch block condition")
  1331. (js2-msg "msg.catch.unreachable"
  1332. "any catch clauses following an unqualified catch are unreachable")
  1333. (js2-msg "msg.no.brace.try"
  1334. "missing '{' before try block")
  1335. (js2-msg "msg.no.brace.catchblock"
  1336. "missing '{' before catch-block body")
  1337. (js2-msg "msg.try.no.catchfinally"
  1338. "'try' without 'catch' or 'finally'")
  1339. (js2-msg "msg.no.return.value"
  1340. "function %s does not always return a value")
  1341. (js2-msg "msg.anon.no.return.value"
  1342. "anonymous function does not always return a value")
  1343. (js2-msg "msg.return.inconsistent"
  1344. "return statement is inconsistent with previous usage")
  1345. (js2-msg "msg.generator.returns"
  1346. "TypeError: legacy generator function '%s' returns a value")
  1347. (js2-msg "msg.anon.generator.returns"
  1348. "TypeError: anonymous legacy generator function returns a value")
  1349. (js2-msg "msg.syntax"
  1350. "syntax error")
  1351. (js2-msg "msg.unexpected.eof"
  1352. "Unexpected end of file")
  1353. (js2-msg "msg.XML.bad.form"
  1354. "illegally formed XML syntax")
  1355. (js2-msg "msg.XML.not.available"
  1356. "XML runtime not available")
  1357. (js2-msg "msg.too.deep.parser.recursion"
  1358. "Too deep recursion while parsing")
  1359. (js2-msg "msg.no.side.effects"
  1360. "Code has no side effects")
  1361. (js2-msg "msg.extra.trailing.comma"
  1362. "Trailing comma is not supported in some browsers")
  1363. (js2-msg "msg.array.trailing.comma"
  1364. "Trailing comma yields different behavior across browsers")
  1365. (js2-msg "msg.equal.as.assign"
  1366. (concat "Test for equality (==) mistyped as assignment (=)?"
  1367. " (parenthesize to suppress warning)"))
  1368. (js2-msg "msg.var.hides.arg"
  1369. "Variable %s hides argument")
  1370. (js2-msg "msg.destruct.assign.no.init"
  1371. "Missing = in destructuring declaration")
  1372. (js2-msg "msg.init.no.destruct"
  1373. "Binding initializer not in destructuring assignment")
  1374. (js2-msg "msg.no.octal.strict"
  1375. "Octal numbers prohibited in strict mode.")
  1376. (js2-msg "msg.dup.obj.lit.prop.strict"
  1377. "Property '%s' already defined in this object literal.")
  1378. (js2-msg "msg.dup.param.strict"
  1379. "Parameter '%s' already declared in this function.")
  1380. (js2-msg "msg.bad.id.strict"
  1381. "'%s' is not a valid identifier for this use in strict mode.")
  1382. ;; ScriptRuntime
  1383. (js2-msg "msg.no.properties"
  1384. "%s has no properties.")
  1385. (js2-msg "msg.invalid.iterator"
  1386. "Invalid iterator value")
  1387. (js2-msg "msg.iterator.primitive"
  1388. "__iterator__ returned a primitive value")
  1389. (js2-msg "msg.assn.create.strict"
  1390. "Assignment to undeclared variable %s")
  1391. (js2-msg "msg.undeclared.variable" ; added by js2-mode
  1392. "Undeclared variable or function '%s'")
  1393. (js2-msg "msg.unused.variable" ; added by js2-mode
  1394. "Unused variable or function '%s'")
  1395. (js2-msg "msg.uninitialized.variable" ; added by js2-mode
  1396. "Variable '%s' referenced but never initialized")
  1397. (js2-msg "msg.ref.undefined.prop"
  1398. "Reference to undefined property '%s'")
  1399. (js2-msg "msg.prop.not.found"
  1400. "Property %s not found.")
  1401. (js2-msg "msg.invalid.type"
  1402. "Invalid JavaScript value of type %s")
  1403. (js2-msg "msg.primitive.expected"
  1404. "Primitive type expected (had %s instead)")
  1405. (js2-msg "msg.namespace.expected"
  1406. "Namespace object expected to left of :: (found %s instead)")
  1407. (js2-msg "msg.null.to.object"
  1408. "Cannot convert null to an object.")
  1409. (js2-msg "msg.undef.to.object"
  1410. "Cannot convert undefined to an object.")
  1411. (js2-msg "msg.cyclic.value"
  1412. "Cyclic %s value not allowed.")
  1413. (js2-msg "msg.is.not.defined"
  1414. "'%s' is not defined.")
  1415. (js2-msg "msg.undef.prop.read"
  1416. "Cannot read property '%s' from %s")
  1417. (js2-msg "msg.undef.prop.write"
  1418. "Cannot set property '%s' of %s to '%s'")
  1419. (js2-msg "msg.undef.prop.delete"
  1420. "Cannot delete property '%s' of %s")
  1421. (js2-msg "msg.undef.method.call"
  1422. "Cannot call method '%s' of %s")
  1423. (js2-msg "msg.undef.with"
  1424. "Cannot apply 'with' to %s")
  1425. (js2-msg "msg.isnt.function"
  1426. "%s is not a function, it is %s.")
  1427. (js2-msg "msg.isnt.function.in"
  1428. "Cannot call property %s in object %s. "
  1429. "It is not a function, it is '%s'.")
  1430. (js2-msg "msg.function.not.found"
  1431. "Cannot find function %s.")
  1432. (js2-msg "msg.function.not.found.in"
  1433. "Cannot find function %s in object %s.")
  1434. (js2-msg "msg.isnt.xml.object"
  1435. "%s is not an xml object.")
  1436. (js2-msg "msg.no.ref.to.get"
  1437. "%s is not a reference to read reference value.")
  1438. (js2-msg "msg.no.ref.to.set"
  1439. "%s is not a reference to set reference value to %s.")
  1440. (js2-msg "msg.no.ref.from.function"
  1441. "Function %s can not be used as the left-hand "
  1442. "side of assignment or as an operand of ++ or -- operator.")
  1443. (js2-msg "msg.bad.default.value"
  1444. "Object's getDefaultValue() method returned an object.")
  1445. (js2-msg "msg.instanceof.not.object"
  1446. "Can't use instanceof on a non-object.")
  1447. (js2-msg "msg.instanceof.bad.prototype"
  1448. "'prototype' property of %s is not an object.")
  1449. (js2-msg "msg.bad.radix"
  1450. "illegal radix %s.")
  1451. ;; ScriptableObject
  1452. (js2-msg "msg.default.value"
  1453. "Cannot find default value for object.")
  1454. (js2-msg "msg.zero.arg.ctor"
  1455. "Cannot load class '%s' which has no zero-parameter constructor.")
  1456. (js2-msg "msg.ctor.multiple.parms"
  1457. "Can't define constructor or class %s since more than "
  1458. "one constructor has multiple parameters.")
  1459. (js2-msg "msg.extend.scriptable"
  1460. "%s must extend ScriptableObject in order to define property %s.")
  1461. (js2-msg "msg.bad.getter.parms"
  1462. "In order to define a property, getter %s must have zero "
  1463. "parameters or a single ScriptableObject parameter.")
  1464. (js2-msg "msg.obj.getter.parms"
  1465. "Expected static or delegated getter %s to take "
  1466. "a ScriptableObject parameter.")
  1467. (js2-msg "msg.getter.static"
  1468. "Getter and setter must both be static or neither be static.")
  1469. (js2-msg "msg.setter.return"
  1470. "Setter must have void return type: %s")
  1471. (js2-msg "msg.setter2.parms"
  1472. "Two-parameter setter must take a ScriptableObject as "
  1473. "its first parameter.")
  1474. (js2-msg "msg.setter1.parms"
  1475. "Expected single parameter setter for %s")
  1476. (js2-msg "msg.setter2.expected"
  1477. "Expected static or delegated setter %s to take two parameters.")
  1478. (js2-msg "msg.setter.parms"
  1479. "Expected either one or two parameters for setter.")
  1480. (js2-msg "msg.setter.bad.type"
  1481. "Unsupported parameter type '%s' in setter '%s'.")
  1482. (js2-msg "msg.add.sealed"
  1483. "Cannot add a property to a sealed object: %s.")
  1484. (js2-msg "msg.remove.sealed"
  1485. "Cannot remove a property from a sealed object: %s.")
  1486. (js2-msg "msg.modify.sealed"
  1487. "Cannot modify a property of a sealed object: %s.")
  1488. (js2-msg "msg.modify.readonly"
  1489. "Cannot modify readonly property: %s.")
  1490. ;; TokenStream
  1491. (js2-msg "msg.missing.exponent"
  1492. "missing exponent")
  1493. (js2-msg "msg.caught.nfe"
  1494. "number format error")
  1495. (js2-msg "msg.unterminated.string.lit"
  1496. "unterminated string literal")
  1497. (js2-msg "msg.unterminated.comment"
  1498. "unterminated comment")
  1499. (js2-msg "msg.unterminated.re.lit"
  1500. "unterminated regular expression literal")
  1501. (js2-msg "msg.invalid.re.flag"
  1502. "invalid flag after regular expression")
  1503. (js2-msg "msg.no.re.input.for"
  1504. "no input for %s")
  1505. (js2-msg "msg.illegal.character"
  1506. "illegal character")
  1507. (js2-msg "msg.invalid.escape"
  1508. "invalid Unicode escape sequence")
  1509. (js2-msg "msg.bad.namespace"
  1510. "not a valid default namespace statement. "
  1511. "Syntax is: default xml namespace = EXPRESSION;")
  1512. ;; TokensStream warnings
  1513. (js2-msg "msg.bad.octal.literal"
  1514. "illegal octal literal digit %s; "
  1515. "interpreting it as a decimal digit")
  1516. (js2-msg "msg.missing.hex.digits"
  1517. "missing hexadecimal digits after '0x'")
  1518. (js2-msg "msg.missing.binary.digits"
  1519. "missing binary digits after '0b'")
  1520. (js2-msg "msg.missing.octal.digits"
  1521. "missing octal digits after '0o'")
  1522. (js2-msg "msg.script.is.not.constructor"
  1523. "Script objects are not constructors.")
  1524. ;; Arrays
  1525. (js2-msg "msg.arraylength.bad"
  1526. "Inappropriate array length.")
  1527. ;; Arrays
  1528. (js2-msg "msg.arraylength.too.big"
  1529. "Array length %s exceeds supported capacity limit.")
  1530. ;; URI
  1531. (js2-msg "msg.bad.uri"
  1532. "Malformed URI sequence.")
  1533. ;; Number
  1534. (js2-msg "msg.bad.precision"
  1535. "Precision %s out of range.")
  1536. ;; NativeGenerator
  1537. (js2-msg "msg.send.newborn"
  1538. "Attempt to send value to newborn generator")
  1539. (js2-msg "msg.already.exec.gen"
  1540. "Already executing generator")
  1541. (js2-msg "msg.StopIteration.invalid"
  1542. "StopIteration may not be changed to an arbitrary object.")
  1543. ;; Interpreter
  1544. (js2-msg "msg.yield.closing"
  1545. "Yield from closing generator")
  1546. ;; Classes
  1547. (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
  1548. "class statement requires a name")
  1549. (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
  1550. "unexpected ',' between class properties")
  1551. (js2-msg "msg.unexpected.static" ; added by js2-mode
  1552. "unexpected 'static'")
  1553. (js2-msg "msg.missing.extends" ; added by js2-mode
  1554. "name is required after extends")
  1555. (js2-msg "msg.no.brace.class" ; added by js2-mode
  1556. "missing '{' before class body")
  1557. (js2-msg "msg.missing.computed.rb" ; added by js2-mode
  1558. "missing ']' after computed property expression")
  1559. ;;; Tokens Buffer
  1560. (defconst js2-ti-max-lookahead 2)
  1561. (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
  1562. (defun js2-new-token (offset)
  1563. (let ((token (make-js2-token (+ offset js2-ts-cursor))))
  1564. (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
  1565. (aset js2-ti-tokens js2-ti-tokens-cursor token)
  1566. token))
  1567. (defsubst js2-current-token ()
  1568. (aref js2-ti-tokens js2-ti-tokens-cursor))
  1569. (defsubst js2-current-token-string ()
  1570. (js2-token-string (js2-current-token)))
  1571. (defsubst js2-current-token-type ()
  1572. (js2-token-type (js2-current-token)))
  1573. (defsubst js2-current-token-beg ()
  1574. (js2-token-beg (js2-current-token)))
  1575. (defsubst js2-current-token-end ()
  1576. (js2-token-end (js2-current-token)))
  1577. (defun js2-current-token-len ()
  1578. (let ((token (js2-current-token)))
  1579. (- (js2-token-end token)
  1580. (js2-token-beg token))))
  1581. (defun js2-ts-seek (state)
  1582. (setq js2-ts-lineno (js2-ts-state-lineno state)
  1583. js2-ts-cursor (js2-ts-state-cursor state)
  1584. js2-ti-tokens (js2-ts-state-tokens state)
  1585. js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
  1586. js2-ti-lookahead (js2-ts-state-lookahead state)))
  1587. ;;; Utilities
  1588. (defun js2-delete-if (predicate list)
  1589. "Remove all items satisfying PREDICATE in LIST."
  1590. (cl-loop for item in list
  1591. if (not (funcall predicate item))
  1592. collect item))
  1593. (defun js2-position (element list)
  1594. "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
  1595. Returns nil if element is not found in the list."
  1596. (let ((count 0)
  1597. found)
  1598. (while (and list (not found))
  1599. (if (eq element (car list))
  1600. (setq found t)
  1601. (setq count (1+ count)
  1602. list (cdr list))))
  1603. (if found count)))
  1604. (defun js2-find-if (predicate list)
  1605. "Find first item satisfying PREDICATE in LIST."
  1606. (let (result)
  1607. (while (and list (not result))
  1608. (if (funcall predicate (car list))
  1609. (setq result (car list)))
  1610. (setq list (cdr list)))
  1611. result))
  1612. (defmacro js2-time (form)
  1613. "Evaluate FORM, discard result, and return elapsed time in sec."
  1614. (declare (debug t))
  1615. (let ((beg (make-symbol "--js2-time-beg--")))
  1616. `(let ((,beg (current-time)))
  1617. ,form
  1618. (/ (truncate (* (- (float-time (current-time))
  1619. (float-time ,beg))
  1620. 10000))
  1621. 10000.0))))
  1622. (defsubst js2-same-line (pos)
  1623. "Return t if POS is on the same line as current point."
  1624. (and (>= pos (point-at-bol))
  1625. (<= pos (point-at-eol))))
  1626. (defun js2-code-bug ()
  1627. "Signal an error when we encounter an unexpected code path."
  1628. (error "failed assertion"))
  1629. (defsubst js2-record-text-property (beg end prop value)
  1630. "Record a text property to set when parsing finishes."
  1631. (push (list beg end prop value) js2-mode-deferred-properties))
  1632. ;; I'd like to associate errors with nodes, but for now the
  1633. ;; easiest thing to do is get the context info from the last token.
  1634. (defun js2-record-parse-error (msg &optional arg pos len)
  1635. (push (list (list msg arg)
  1636. (or pos (js2-current-token-beg))
  1637. (or len (js2-current-token-len)))
  1638. js2-parsed-errors))
  1639. (defun js2-report-error (msg &optional msg-arg pos len)
  1640. "Signal a syntax error or record a parse error."
  1641. (if js2-recover-from-parse-errors
  1642. (js2-record-parse-error msg msg-arg pos len)
  1643. (signal 'js2-syntax-error
  1644. (list msg
  1645. js2-ts-lineno
  1646. (save-excursion
  1647. (goto-char js2-ts-cursor)
  1648. (current-column))
  1649. js2-ts-hit-eof))))
  1650. (defun js2-report-warning (msg &optional msg-arg pos len face)
  1651. (if js2-compiler-report-warning-as-error
  1652. (js2-report-error msg msg-arg pos len)
  1653. (push (list (list msg msg-arg)
  1654. (or pos (js2-current-token-beg))
  1655. (or len (js2-current-token-len))
  1656. face)
  1657. js2-parsed-warnings)))
  1658. (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
  1659. (if js2-compiler-strict-mode
  1660. (js2-report-warning msg-id msg-arg beg
  1661. (and beg end (- end beg)))))
  1662. (put 'js2-syntax-error 'error-conditions
  1663. '(error syntax-error js2-syntax-error))
  1664. (put 'js2-syntax-error 'error-message "Syntax error")
  1665. (put 'js2-parse-error 'error-conditions
  1666. '(error parse-error js2-parse-error))
  1667. (put 'js2-parse-error 'error-message "Parse error")
  1668. (defmacro js2-clear-flag (flags flag)
  1669. `(setq ,flags (logand ,flags (lognot ,flag))))
  1670. (defmacro js2-set-flag (flags flag)
  1671. "Logical-or FLAG into FLAGS."
  1672. `(setq ,flags (logior ,flags ,flag)))
  1673. (defsubst js2-flag-set-p (flags flag)
  1674. (/= 0 (logand flags flag)))
  1675. (defsubst js2-flag-not-set-p (flags flag)
  1676. (zerop (logand flags flag)))
  1677. ;;; AST struct and function definitions
  1678. ;; flags for ast node property 'member-type (used for e4x operators)
  1679. (defvar js2-property-flag #x1 "Property access: element is valid name.")
  1680. (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
  1681. (defvar js2-descendants-flag #x4 "x..y or x..@i.")
  1682. (defsubst js2-relpos (pos anchor)
  1683. "Convert POS to be relative to ANCHOR.
  1684. If POS is nil, returns nil."
  1685. (and pos (- pos anchor)))
  1686. (defun js2-make-pad (indent)
  1687. (if (zerop indent)
  1688. ""
  1689. (make-string (* indent js2-basic-offset) ? )))
  1690. (defun js2-visit-ast (node callback)
  1691. "Visit every node in ast NODE with visitor CALLBACK.
  1692. CALLBACK is a function that takes two arguments: (NODE END-P). It is
  1693. called twice: once to visit the node, and again after all the node's
  1694. children have been processed. The END-P argument is nil on the first
  1695. call and non-nil on the second call. The return value of the callback
  1696. affects the traversal: if non-nil, the children of NODE are processed.
  1697. If the callback returns nil, or if the node has no children, then the
  1698. callback is called immediately with a non-nil END-P argument.
  1699. The node traversal is approximately lexical-order, although there
  1700. are currently no guarantees around this."
  1701. (when node
  1702. (let ((vfunc (get (aref node 0) 'js2-visitor)))
  1703. ;; visit the node
  1704. (when (funcall callback node nil)
  1705. ;; visit the kids
  1706. (cond
  1707. ((eq vfunc 'js2-visit-none)
  1708. nil) ; don't even bother calling it
  1709. ;; Each AST node type has to define a `js2-visitor' function
  1710. ;; that takes a node and a callback, and calls `js2-visit-ast'
  1711. ;; on each child of the node.
  1712. (vfunc
  1713. (funcall vfunc node callback))
  1714. (t
  1715. (error "%s does not define a visitor-traversal function"
  1716. (aref node 0)))))
  1717. ;; call the end-visit
  1718. (funcall callback node t))))
  1719. (cl-defstruct (js2-node
  1720. (:constructor nil)) ; abstract
  1721. "Base AST node type."
  1722. (type -1) ; token type
  1723. (pos -1) ; start position of this AST node in parsed input
  1724. (len 1) ; num characters spanned by the node
  1725. props ; optional node property list (an alist)
  1726. parent) ; link to parent node; null for root
  1727. (defsubst js2-node-get-prop (node prop &optional default)
  1728. (or (cadr (assoc prop (js2-node-props node))) default))
  1729. (defsubst js2-node-set-prop (node prop value)
  1730. (setf (js2-node-props node)
  1731. (cons (list prop value) (js2-node-props node))))
  1732. (defun js2-fixup-starts (n nodes)
  1733. "Adjust the start positions of NODES to be relative to N.
  1734. Any node in the list may be nil, for convenience."
  1735. (dolist (node nodes)
  1736. (when node
  1737. (setf (js2-node-pos node) (- (js2-node-pos node)
  1738. (js2-node-pos n))))))
  1739. (defun js2-node-add-children (parent &rest nodes)
  1740. "Set parent node of NODES to PARENT, and return PARENT.
  1741. Does nothing if we're not recording parent links.
  1742. If any given node in NODES is nil, doesn't record that link."
  1743. (js2-fixup-starts parent nodes)
  1744. (dolist (node nodes)
  1745. (and node
  1746. (setf (js2-node-parent node) parent))))
  1747. ;; Non-recursive since it's called a frightening number of times.
  1748. (defun js2-node-abs-pos (n)
  1749. (let ((pos (js2-node-pos n)))
  1750. (while (setq n (js2-node-parent n))
  1751. (setq pos (+ pos (js2-node-pos n))))
  1752. pos))
  1753. (defsubst js2-node-abs-end (n)
  1754. "Return absolute buffer position of end of N."
  1755. (+ (js2-node-abs-pos n) (js2-node-len n)))
  1756. (defun js2--struct-put (name key value)
  1757. (put name key value)
  1758. (put (intern (format "cl-struct-%s" name)) key value))
  1759. ;; It's important to make sure block nodes have a Lisp list for the
  1760. ;; child nodes, to limit printing recursion depth in an AST that
  1761. ;; otherwise consists of defstruct vectors. Emacs will crash printing
  1762. ;; a sufficiently large vector tree.
  1763. (cl-defstruct (js2-block-node
  1764. (:include js2-node)
  1765. (:constructor make-js2-block-node (&key (type js2-BLOCK)
  1766. (pos (js2-current-token-beg))
  1767. len
  1768. props
  1769. kids)))
  1770. "A block of statements."
  1771. kids) ; a Lisp list of the child statement nodes
  1772. (js2--struct-put 'js2-block-node 'js2-visitor 'js2-visit-block)
  1773. (js2--struct-put 'js2-block-node 'js2-printer 'js2-print-block)
  1774. (defun js2-visit-block (ast callback)
  1775. "Visit the `js2-block-node' children of AST."
  1776. (dolist (kid (js2-block-node-kids ast))
  1777. (js2-visit-ast kid callback)))
  1778. (defun js2-print-block (n i)
  1779. (let ((pad (js2-make-pad i)))
  1780. (insert pad "{\n")
  1781. (dolist (kid (js2-block-node-kids n))
  1782. (js2-print-ast kid (1+ i)))
  1783. (insert pad "}")))
  1784. (cl-defstruct (js2-scope
  1785. (:include js2-block-node)
  1786. (:constructor make-js2-scope (&key (type js2-BLOCK)
  1787. (pos (js2-current-token-beg))
  1788. len
  1789. kids)))
  1790. ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
  1791. ;; I don't have one of those handy, so I'll use an alist for now.
  1792. ;; It's as fast as an emacs hashtable for up to about 50 elements,
  1793. ;; and is much lighter-weight to construct (both CPU and mem).
  1794. ;; The keys are interned strings (symbols) for faster lookup.
  1795. ;; Should switch to hybrid alist/hashtable eventually.
  1796. symbol-table ; an alist of (symbol . js2-symbol)
  1797. parent-scope ; a `js2-scope'
  1798. top) ; top-level `js2-scope' (script/function)
  1799. (js2--struct-put 'js2-scope 'js2-visitor 'js2-visit-block)
  1800. (js2--struct-put 'js2-scope 'js2-printer 'js2-print-none)
  1801. (defun js2-node-get-enclosing-scope (node)
  1802. "Return the innermost `js2-scope' node surrounding NODE.
  1803. Returns nil if there is no enclosing scope node."
  1804. (while (and (setq node (js2-node-parent node))
  1805. (not (js2-scope-p node))))
  1806. node)
  1807. (defun js2-get-defining-scope (scope name &optional point)
  1808. "Search up scope chain from SCOPE looking for NAME, a string or symbol.
  1809. Returns `js2-scope' in which NAME is defined, or nil if not found.
  1810. If POINT is non-nil, and if the found declaration type is
  1811. `js2-LET', also check that the declaration node is before POINT."
  1812. (let ((sym (if (symbolp name)
  1813. name
  1814. (intern name)))
  1815. result
  1816. (continue t))
  1817. (while (and scope continue)
  1818. (if (or
  1819. (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
  1820. (and entry
  1821. (or (not point)
  1822. (not (eq js2-LET (js2-symbol-decl-type entry)))
  1823. (>= point
  1824. (js2-node-abs-pos (js2-symbol-ast-node entry))))))
  1825. (and (eq sym 'arguments)
  1826. (js2-function-node-p scope)))
  1827. (setq continue nil
  1828. result scope)
  1829. (setq scope (js2-scope-parent-scope scope))))
  1830. result))
  1831. (defun js2-scope-get-symbol (scope name)
  1832. "Return symbol table entry for NAME in SCOPE.
  1833. NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
  1834. (and (js2-scope-symbol-table scope)
  1835. (cdr (assq (if (symbolp name)
  1836. name
  1837. (intern name))
  1838. (js2-scope-symbol-table scope)))))
  1839. (defun js2-scope-put-symbol (scope name symbol)
  1840. "Enter SYMBOL into symbol-table for SCOPE under NAME.
  1841. NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
  1842. (let* ((table (js2-scope-symbol-table scope))
  1843. (sym (if (symbolp name) name (intern name)))
  1844. (entry (assq sym table)))
  1845. (if entry
  1846. (setcdr entry symbol)
  1847. (push (cons sym symbol)
  1848. (js2-scope-symbol-table scope)))))
  1849. (cl-defstruct (js2-symbol
  1850. (:constructor make-js2-symbol (decl-type name &optional ast-node)))
  1851. "A symbol table entry."
  1852. ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
  1853. ;; js2-LET, or js2-CONST
  1854. decl-type
  1855. name ; string
  1856. ast-node) ; a `js2-node'
  1857. (cl-defstruct (js2-error-node
  1858. (:include js2-node)
  1859. (:constructor make-js2-error-node (&key (type js2-ERROR)
  1860. (pos (js2-current-token-beg))
  1861. len)))
  1862. "AST node representing a parse error.")
  1863. (js2--struct-put 'js2-error-node 'js2-visitor 'js2-visit-none)
  1864. (js2--struct-put 'js2-error-node 'js2-printer 'js2-print-none)
  1865. (cl-defstruct (js2-script-node
  1866. (:include js2-scope)
  1867. (:constructor make-js2-script-node (&key (type js2-SCRIPT)
  1868. (pos (js2-current-token-beg))
  1869. len)))
  1870. functions ; Lisp list of nested functions
  1871. regexps ; Lisp list of (string . flags)
  1872. symbols ; alist (every symbol gets unique index)
  1873. (param-count 0)
  1874. var-names ; vector of string names
  1875. consts ; bool-vector matching var-decls
  1876. (temp-number 0)) ; for generating temp variables
  1877. (js2--struct-put 'js2-script-node 'js2-visitor 'js2-visit-block)
  1878. (js2--struct-put 'js2-script-node 'js2-printer 'js2-print-script)
  1879. (defun js2-print-script (node indent)
  1880. (dolist (kid (js2-block-node-kids node))
  1881. (js2-print-ast kid indent)))
  1882. (cl-defstruct (js2-ast-root
  1883. (:include js2-script-node)
  1884. (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
  1885. (pos (js2-current-token-beg))
  1886. len
  1887. buffer)))
  1888. "The root node of a js2 AST."
  1889. buffer ; the source buffer from which the code was parsed
  1890. comments ; a Lisp list of comments, ordered by start position
  1891. errors ; a Lisp list of errors found during parsing
  1892. warnings ; a Lisp list of warnings found during parsing
  1893. node-count) ; number of nodes in the tree, including the root
  1894. (js2--struct-put 'js2-ast-root 'js2-visitor 'js2-visit-ast-root)
  1895. (js2--struct-put 'js2-ast-root 'js2-printer 'js2-print-script)
  1896. (defun js2-visit-ast-root (ast callback)
  1897. (dolist (kid (js2-ast-root-kids ast))
  1898. (js2-visit-ast kid callback))
  1899. (dolist (comment (js2-ast-root-comments ast))
  1900. (js2-visit-ast comment callback)))
  1901. (cl-defstruct (js2-comment-node
  1902. (:include js2-node)
  1903. (:constructor make-js2-comment-node (&key (type js2-COMMENT)
  1904. (pos (js2-current-token-beg))
  1905. len
  1906. format)))
  1907. format) ; 'line, 'block, 'jsdoc or 'html
  1908. (js2--struct-put 'js2-comment-node 'js2-visitor 'js2-visit-none)
  1909. (js2--struct-put 'js2-comment-node 'js2-printer 'js2-print-comment)
  1910. (defun js2-print-comment (n i)
  1911. ;; We really ought to link end-of-line comments to their nodes.
  1912. ;; Or maybe we could add a new comment type, 'endline.
  1913. (insert (js2-make-pad i)
  1914. (js2-node-string n)))
  1915. (cl-defstruct (js2-expr-stmt-node
  1916. (:include js2-node)
  1917. (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
  1918. (pos js2-ts-cursor)
  1919. len
  1920. expr)))
  1921. "An expression statement."
  1922. expr)
  1923. (defsubst js2-expr-stmt-node-set-has-result (node)
  1924. "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
  1925. (setf (js2-node-type node) js2-EXPR_RESULT))
  1926. (js2--struct-put 'js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
  1927. (js2--struct-put 'js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
  1928. (defun js2-visit-expr-stmt-node (n v)
  1929. (js2-visit-ast (js2-expr-stmt-node-expr n) v))
  1930. (defun js2-print-expr-stmt-node (n indent)
  1931. (js2-print-ast (js2-expr-stmt-node-expr n) indent)
  1932. (insert ";\n"))
  1933. (cl-defstruct (js2-loop-node
  1934. (:include js2-scope)
  1935. (:constructor nil))
  1936. "Abstract supertype of loop nodes."
  1937. body ; a `js2-block-node'
  1938. lp ; position of left-paren, nil if omitted
  1939. rp) ; position of right-paren, nil if omitted
  1940. (cl-defstruct (js2-do-node
  1941. (:include js2-loop-node)
  1942. (:constructor make-js2-do-node (&key (type js2-DO)
  1943. (pos (js2-current-token-beg))
  1944. len
  1945. body
  1946. condition
  1947. while-pos
  1948. lp
  1949. rp)))
  1950. "AST node for do-loop."
  1951. condition ; while (expression)
  1952. while-pos) ; buffer position of 'while' keyword
  1953. (js2--struct-put 'js2-do-node 'js2-visitor 'js2-visit-do-node)
  1954. (js2--struct-put 'js2-do-node 'js2-printer 'js2-print-do-node)
  1955. (defun js2-visit-do-node (n v)
  1956. (js2-visit-ast (js2-do-node-body n) v)
  1957. (js2-visit-ast (js2-do-node-condition n) v))
  1958. (defun js2-print-do-node (n i)
  1959. (let ((pad (js2-make-pad i)))
  1960. (insert pad "do {\n")
  1961. (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
  1962. (js2-print-ast kid (1+ i)))
  1963. (insert pad "} while (")
  1964. (js2-print-ast (js2-do-node-condition n) 0)
  1965. (insert ");\n")))
  1966. (cl-defstruct (js2-export-node
  1967. (:include js2-node)
  1968. (:constructor make-js2-export-node (&key (type js2-EXPORT)
  1969. (pos (js2-current-token-beg))
  1970. len
  1971. exports-list
  1972. from-clause
  1973. declaration
  1974. default)))
  1975. "AST node for an export statement. There are many things that can be exported,
  1976. so many of its properties will be nil.
  1977. "
  1978. exports-list ; lisp list of js2-export-binding-node to export
  1979. from-clause ; js2-from-clause-node for re-exporting symbols from another module
  1980. declaration ; js2-var-decl-node (var, let, const) or js2-class-node
  1981. default) ; js2-function-node or js2-assign-node
  1982. (js2--struct-put 'js2-export-node 'js2-visitor 'js2-visit-export-node)
  1983. (js2--struct-put 'js2-export-node 'js2-printer 'js2-print-export-node)
  1984. (defun js2-visit-export-node (n v)
  1985. (let ((exports-list (js2-export-node-exports-list n))
  1986. (from (js2-export-node-from-clause n))
  1987. (declaration (js2-export-node-declaration n))
  1988. (default (js2-export-node-default n)))
  1989. (when exports-list
  1990. (dolist (export exports-list)
  1991. (js2-visit-ast export v)))
  1992. (when from
  1993. (js2-visit-ast from v))
  1994. (when declaration
  1995. (js2-visit-ast declaration v))
  1996. (when default
  1997. (js2-visit-ast default v))))
  1998. (defun js2-print-export-node (n i)
  1999. (let ((pad (js2-make-pad i))
  2000. (exports-list (js2-export-node-exports-list n))
  2001. (from (js2-export-node-from-clause n))
  2002. (declaration (js2-export-node-declaration n))
  2003. (default (js2-export-node-default n)))
  2004. (insert pad "export ")
  2005. (cond
  2006. (default
  2007. (insert "default ")
  2008. (js2-print-ast default i))
  2009. (declaration
  2010. (js2-print-ast declaration i))
  2011. ((and exports-list from)
  2012. (js2-print-named-imports exports-list)
  2013. (insert " ")
  2014. (js2-print-from-clause from))
  2015. (from
  2016. (insert "* ")
  2017. (js2-print-from-clause from))
  2018. (exports-list
  2019. (js2-print-named-imports exports-list)))
  2020. (unless (or (and default (not (js2-assign-node-p default)))
  2021. (and declaration (or (js2-function-node-p declaration)
  2022. (js2-class-node-p declaration))))
  2023. (insert ";\n"))))
  2024. (cl-defstruct (js2-while-node
  2025. (:include js2-loop-node)
  2026. (:constructor make-js2-while-node (&key (type js2-WHILE)
  2027. (pos (js2-current-token-beg))
  2028. len body
  2029. condition lp
  2030. rp)))
  2031. "AST node for while-loop."
  2032. condition) ; while-condition
  2033. (js2--struct-put 'js2-while-node 'js2-visitor 'js2-visit-while-node)
  2034. (js2--struct-put 'js2-while-node 'js2-printer 'js2-print-while-node)
  2035. (defun js2-visit-while-node (n v)
  2036. (js2-visit-ast (js2-while-node-condition n) v)
  2037. (js2-visit-ast (js2-while-node-body n) v))
  2038. (defun js2-print-while-node (n i)
  2039. (let ((pad (js2-make-pad i)))
  2040. (insert pad "while (")
  2041. (js2-print-ast (js2-while-node-condition n) 0)
  2042. (insert ") {\n")
  2043. (js2-print-body (js2-while-node-body n) (1+ i))
  2044. (insert pad "}\n")))
  2045. (cl-defstruct (js2-for-node
  2046. (:include js2-loop-node)
  2047. (:constructor make-js2-for-node (&key (type js2-FOR)
  2048. (pos js2-ts-cursor)
  2049. len body init
  2050. condition
  2051. update lp rp)))
  2052. "AST node for a C-style for-loop."
  2053. init ; initialization expression
  2054. condition ; loop condition
  2055. update) ; update clause
  2056. (js2--struct-put 'js2-for-node 'js2-visitor 'js2-visit-for-node)
  2057. (js2--struct-put 'js2-for-node 'js2-printer 'js2-print-for-node)
  2058. (defun js2-visit-for-node (n v)
  2059. (js2-visit-ast (js2-for-node-init n) v)
  2060. (js2-visit-ast (js2-for-node-condition n) v)
  2061. (js2-visit-ast (js2-for-node-update n) v)
  2062. (js2-visit-ast (js2-for-node-body n) v))
  2063. (defun js2-print-for-node (n i)
  2064. (let ((pad (js2-make-pad i)))
  2065. (insert pad "for (")
  2066. (js2-print-ast (js2-for-node-init n) 0)
  2067. (insert "; ")
  2068. (js2-print-ast (js2-for-node-condition n) 0)
  2069. (insert "; ")
  2070. (js2-print-ast (js2-for-node-update n) 0)
  2071. (insert ") {\n")
  2072. (js2-print-body (js2-for-node-body n) (1+ i))
  2073. (insert pad "}\n")))
  2074. (cl-defstruct (js2-for-in-node
  2075. (:include js2-loop-node)
  2076. (:constructor make-js2-for-in-node (&key (type js2-FOR)
  2077. (pos js2-ts-cursor)
  2078. len body
  2079. iterator
  2080. object
  2081. in-pos
  2082. each-pos
  2083. foreach-p forof-p
  2084. lp rp)))
  2085. "AST node for a for..in loop."
  2086. iterator ; [var] foo in ...
  2087. object ; object over which we're iterating
  2088. in-pos ; buffer position of 'in' keyword
  2089. each-pos ; buffer position of 'each' keyword, if foreach-p
  2090. foreach-p ; t if it's a for-each loop
  2091. forof-p) ; t if it's a for-of loop
  2092. (js2--struct-put 'js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
  2093. (js2--struct-put 'js2-for-in-node 'js2-printer 'js2-print-for-in-node)
  2094. (defun js2-visit-for-in-node (n v)
  2095. (js2-visit-ast (js2-for-in-node-iterator n) v)
  2096. (js2-visit-ast (js2-for-in-node-object n) v)
  2097. (js2-visit-ast (js2-for-in-node-body n) v))
  2098. (defun js2-print-for-in-node (n i)
  2099. (let ((pad (js2-make-pad i))
  2100. (foreach (js2-for-in-node-foreach-p n))
  2101. (forof (js2-for-in-node-forof-p n)))
  2102. (insert pad "for ")
  2103. (if foreach
  2104. (insert "each "))
  2105. (insert "(")
  2106. (js2-print-ast (js2-for-in-node-iterator n) 0)
  2107. (insert (if forof " of " " in "))
  2108. (js2-print-ast (js2-for-in-node-object n) 0)
  2109. (insert ") {\n")
  2110. (js2-print-body (js2-for-in-node-body n) (1+ i))
  2111. (insert pad "}\n")))
  2112. (cl-defstruct (js2-return-node
  2113. (:include js2-node)
  2114. (:constructor make-js2-return-node (&key (type js2-RETURN)
  2115. (pos js2-ts-cursor)
  2116. len
  2117. retval)))
  2118. "AST node for a return statement."
  2119. retval) ; expression to return, or 'undefined
  2120. (js2--struct-put 'js2-return-node 'js2-visitor 'js2-visit-return-node)
  2121. (js2--struct-put 'js2-return-node 'js2-printer 'js2-print-return-node)
  2122. (defun js2-visit-return-node (n v)
  2123. (js2-visit-ast (js2-return-node-retval n) v))
  2124. (defun js2-print-return-node (n i)
  2125. (insert (js2-make-pad i) "return")
  2126. (when (js2-return-node-retval n)
  2127. (insert " ")
  2128. (js2-print-ast (js2-return-node-retval n) 0))
  2129. (insert ";\n"))
  2130. (cl-defstruct (js2-if-node
  2131. (:include js2-node)
  2132. (:constructor make-js2-if-node (&key (type js2-IF)
  2133. (pos js2-ts-cursor)
  2134. len condition
  2135. then-part
  2136. else-pos
  2137. else-part lp
  2138. rp)))
  2139. "AST node for an if-statement."
  2140. condition ; expression
  2141. then-part ; statement or block
  2142. else-pos ; optional buffer position of 'else' keyword
  2143. else-part ; optional statement or block
  2144. lp ; position of left-paren, nil if omitted
  2145. rp) ; position of right-paren, nil if omitted
  2146. (js2--struct-put 'js2-if-node 'js2-visitor 'js2-visit-if-node)
  2147. (js2--struct-put 'js2-if-node 'js2-printer 'js2-print-if-node)
  2148. (defun js2-visit-if-node (n v)
  2149. (js2-visit-ast (js2-if-node-condition n) v)
  2150. (js2-visit-ast (js2-if-node-then-part n) v)
  2151. (js2-visit-ast (js2-if-node-else-part n) v))
  2152. (defun js2-print-if-node (n i)
  2153. (let ((pad (js2-make-pad i))
  2154. (then-part (js2-if-node-then-part n))
  2155. (else-part (js2-if-node-else-part n)))
  2156. (insert pad "if (")
  2157. (js2-print-ast (js2-if-node-condition n) 0)
  2158. (insert ") {\n")
  2159. (js2-print-body then-part (1+ i))
  2160. (insert pad "}")
  2161. (cond
  2162. ((not else-part)
  2163. (insert "\n"))
  2164. ((js2-if-node-p else-part)
  2165. (insert " else ")
  2166. (js2-print-body else-part i))
  2167. (t
  2168. (insert " else {\n")
  2169. (js2-print-body else-part (1+ i))
  2170. (insert pad "}\n")))))
  2171. (cl-defstruct (js2-export-binding-node
  2172. (:include js2-node)
  2173. (:constructor make-js2-export-binding-node (&key (type -1)
  2174. pos
  2175. len
  2176. local-name
  2177. extern-name)))
  2178. "AST node for an external symbol binding.
  2179. It contains a local-name node which is the name of the value in the
  2180. current scope, and extern-name which is the name of the value in the
  2181. imported or exported scope. By default these are the same, but if the
  2182. name is aliased as in {foo as bar}, it would have an extern-name node
  2183. containing 'foo' and a local-name node containing 'bar'."
  2184. local-name ; js2-name-node with the variable name in this scope
  2185. extern-name) ; js2-name-node with the value name in the exporting module
  2186. (js2--struct-put 'js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
  2187. (js2--struct-put 'js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
  2188. (defun js2-visit-extern-binding (n v)
  2189. "Visit an extern binding node. First visit the local-name, and, if
  2190. different, visit the extern-name."
  2191. (let ((local-name (js2-export-binding-node-local-name n))
  2192. (extern-name (js2-export-binding-node-extern-name n)))
  2193. (when local-name
  2194. (js2-visit-ast local-name v))
  2195. (when (not (equal local-name extern-name))
  2196. (js2-visit-ast extern-name v))))
  2197. (defun js2-print-extern-binding (n _i)
  2198. "Print a representation of a single extern binding. E.g. 'foo' or
  2199. 'foo as bar'."
  2200. (let ((local-name (js2-export-binding-node-local-name n))
  2201. (extern-name (js2-export-binding-node-extern-name n)))
  2202. (insert (js2-name-node-name extern-name))
  2203. (when (not (equal local-name extern-name))
  2204. (insert " as ")
  2205. (insert (js2-name-node-name local-name)))))
  2206. (cl-defstruct (js2-import-node
  2207. (:include js2-node)
  2208. (:constructor make-js2-import-node (&key (type js2-IMPORT)
  2209. (pos (js2-current-token-beg))
  2210. len
  2211. import
  2212. from
  2213. module-id)))
  2214. "AST node for an import statement. It follows the form
  2215. import ModuleSpecifier;
  2216. import ImportClause FromClause;"
  2217. import ; js2-import-clause-node specifying which names are to imported.
  2218. from ; js2-from-clause-node indicating the module from which to import.
  2219. module-id) ; module-id of the import. E.g. 'src/mylib'.
  2220. (js2--struct-put 'js2-import-node 'js2-printer 'js2-print-import)
  2221. (js2--struct-put 'js2-import-node 'js2-visitor 'js2-visit-import)
  2222. (defun js2-visit-import (n v)
  2223. (let ((import-clause (js2-import-node-import n))
  2224. (from-clause (js2-import-node-from n)))
  2225. (when import-clause
  2226. (js2-visit-ast import-clause v))
  2227. (when from-clause
  2228. (js2-visit-ast from-clause v))))
  2229. (defun js2-print-import (n i)
  2230. "Prints a representation of the import node"
  2231. (let ((pad (js2-make-pad i))
  2232. (import-clause (js2-import-node-import n))
  2233. (from-clause (js2-import-node-from n))
  2234. (module-id (js2-import-node-module-id n)))
  2235. (insert pad "import ")
  2236. (if import-clause
  2237. (progn
  2238. (js2-print-import-clause import-clause)
  2239. (insert " ")
  2240. (js2-print-from-clause from-clause))
  2241. (insert "'")
  2242. (insert module-id)
  2243. (insert "'"))
  2244. (insert ";\n")))
  2245. (cl-defstruct (js2-import-clause-node
  2246. (:include js2-node)
  2247. (:constructor make-js2-import-clause-node (&key (type -1)
  2248. pos
  2249. len
  2250. namespace-import
  2251. named-imports
  2252. default-binding)))
  2253. "AST node corresponding to the import clause of an import statement. This is
  2254. the portion of the import that bindings names from the external context to the
  2255. local context."
  2256. namespace-import ; js2-namespace-import-node. E.g. '* as lib'
  2257. named-imports ; lisp list of js2-export-binding-node for all named imports.
  2258. default-binding) ; js2-export-binding-node for the default import binding
  2259. (js2--struct-put 'js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
  2260. (js2--struct-put 'js2-import-clause-node 'js2-printer 'js2-print-import-clause)
  2261. (defun js2-visit-import-clause (n v)
  2262. (let ((ns-import (js2-import-clause-node-namespace-import n))
  2263. (named-imports (js2-import-clause-node-named-imports n))
  2264. (default (js2-import-clause-node-default-binding n)))
  2265. (when default
  2266. (js2-visit-ast default v))
  2267. (when ns-import
  2268. (js2-visit-ast ns-import v))
  2269. (when named-imports
  2270. (dolist (import named-imports)
  2271. (js2-visit-ast import v)))))
  2272. (defun js2-print-import-clause (n)
  2273. (let ((ns-import (js2-import-clause-node-namespace-import n))
  2274. (named-imports (js2-import-clause-node-named-imports n))
  2275. (default (js2-import-clause-node-default-binding n)))
  2276. (cond
  2277. ((and default ns-import)
  2278. (js2-print-ast default)
  2279. (insert ", ")
  2280. (js2-print-namespace-import ns-import))
  2281. ((and default named-imports)
  2282. (js2-print-ast default)
  2283. (insert ", ")
  2284. (js2-print-named-imports named-imports))
  2285. (default
  2286. (js2-print-ast default))
  2287. (ns-import
  2288. (js2-print-namespace-import ns-import))
  2289. (named-imports
  2290. (js2-print-named-imports named-imports)))))
  2291. (defun js2-print-namespace-import (node)
  2292. (insert "* as ")
  2293. (insert (js2-name-node-name (js2-namespace-import-node-name node))))
  2294. (defun js2-print-named-imports (imports)
  2295. (insert "{")
  2296. (let ((len (length imports))
  2297. (n 0))
  2298. (while (< n len)
  2299. (js2-print-extern-binding (nth n imports) 0)
  2300. (unless (= n (- len 1))
  2301. (insert ", "))
  2302. (setq n (+ n 1))))
  2303. (insert "}"))
  2304. (cl-defstruct (js2-namespace-import-node
  2305. (:include js2-node)
  2306. (:constructor make-js2-namespace-import-node (&key (type -1)
  2307. pos
  2308. len
  2309. name)))
  2310. "AST node for a complete namespace import.
  2311. E.g. the '* as lib' expression in:
  2312. import * as lib from 'src/lib'
  2313. It contains a single name node referring to the bound name."
  2314. name) ; js2-name-node of the bound name.
  2315. (defun js2-visit-namespace-import (n v)
  2316. (js2-visit-ast (js2-namespace-import-node-name n) v))
  2317. (js2--struct-put 'js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
  2318. (js2--struct-put 'js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
  2319. (cl-defstruct (js2-from-clause-node
  2320. (:include js2-node)
  2321. (:constructor make-js2-from-clause-node (&key (type js2-NAME)
  2322. pos
  2323. len
  2324. module-id
  2325. metadata-p)))
  2326. "AST node for the from clause in an import or export statement.
  2327. E.g. from 'my/module'. It can refere to either an external module, or to the
  2328. modules metadata itself."
  2329. module-id ; string containing the module specifier.
  2330. metadata-p) ; true if this clause refers to the module's metadata
  2331. (js2--struct-put 'js2-from-clause-node 'js2-visitor 'js2-visit-none)
  2332. (js2--struct-put 'js2-from-clause-node 'js2-printer 'js2-print-from-clause)
  2333. (defun js2-print-from-clause (n)
  2334. (insert "from ")
  2335. (if (js2-from-clause-node-metadata-p n)
  2336. (insert "this module")
  2337. (insert "'")
  2338. (insert (js2-from-clause-node-module-id n))
  2339. (insert "'")))
  2340. (cl-defstruct (js2-try-node
  2341. (:include js2-node)
  2342. (:constructor make-js2-try-node (&key (type js2-TRY)
  2343. (pos js2-ts-cursor)
  2344. len
  2345. try-block
  2346. catch-clauses
  2347. finally-block)))
  2348. "AST node for a try-statement."
  2349. try-block
  2350. catch-clauses ; a Lisp list of `js2-catch-node'
  2351. finally-block) ; a `js2-finally-node'
  2352. (js2--struct-put 'js2-try-node 'js2-visitor 'js2-visit-try-node)
  2353. (js2--struct-put 'js2-try-node 'js2-printer 'js2-print-try-node)
  2354. (defun js2-visit-try-node (n v)
  2355. (js2-visit-ast (js2-try-node-try-block n) v)
  2356. (dolist (clause (js2-try-node-catch-clauses n))
  2357. (js2-visit-ast clause v))
  2358. (js2-visit-ast (js2-try-node-finally-block n) v))
  2359. (defun js2-print-try-node (n i)
  2360. (let ((pad (js2-make-pad i))
  2361. (catches (js2-try-node-catch-clauses n))
  2362. (finally (js2-try-node-finally-block n)))
  2363. (insert pad "try {\n")
  2364. (js2-print-body (js2-try-node-try-block n) (1+ i))
  2365. (insert pad "}")
  2366. (when catches
  2367. (dolist (catch catches)
  2368. (js2-print-ast catch i)))
  2369. (if finally
  2370. (js2-print-ast finally i)
  2371. (insert "\n"))))
  2372. (cl-defstruct (js2-catch-node
  2373. (:include js2-scope)
  2374. (:constructor make-js2-catch-node (&key (type js2-CATCH)
  2375. (pos js2-ts-cursor)
  2376. len
  2377. param
  2378. guard-kwd
  2379. guard-expr
  2380. lp rp)))
  2381. "AST node for a catch clause."
  2382. param ; destructuring form or simple name node
  2383. guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
  2384. guard-expr ; catch condition, a `js2-node'
  2385. lp ; buffer position of left-paren, nil if omitted
  2386. rp) ; buffer position of right-paren, nil if omitted
  2387. (js2--struct-put 'js2-catch-node 'js2-visitor 'js2-visit-catch-node)
  2388. (js2--struct-put 'js2-catch-node 'js2-printer 'js2-print-catch-node)
  2389. (defun js2-visit-catch-node (n v)
  2390. (js2-visit-ast (js2-catch-node-param n) v)
  2391. (when (js2-catch-node-guard-kwd n)
  2392. (js2-visit-ast (js2-catch-node-guard-expr n) v))
  2393. (js2-visit-block n v))
  2394. (defun js2-print-catch-node (n i)
  2395. (let ((pad (js2-make-pad i))
  2396. (guard-kwd (js2-catch-node-guard-kwd n))
  2397. (guard-expr (js2-catch-node-guard-expr n)))
  2398. (insert " catch (")
  2399. (js2-print-ast (js2-catch-node-param n) 0)
  2400. (when guard-kwd
  2401. (insert " if ")
  2402. (js2-print-ast guard-expr 0))
  2403. (insert ") {\n")
  2404. (js2-print-body n (1+ i))
  2405. (insert pad "}")))
  2406. (cl-defstruct (js2-finally-node
  2407. (:include js2-node)
  2408. (:constructor make-js2-finally-node (&key (type js2-FINALLY)
  2409. (pos js2-ts-cursor)
  2410. len body)))
  2411. "AST node for a finally clause."
  2412. body) ; a `js2-node', often but not always a block node
  2413. (js2--struct-put 'js2-finally-node 'js2-visitor 'js2-visit-finally-node)
  2414. (js2--struct-put 'js2-finally-node 'js2-printer 'js2-print-finally-node)
  2415. (defun js2-visit-finally-node (n v)
  2416. (js2-visit-ast (js2-finally-node-body n) v))
  2417. (defun js2-print-finally-node (n i)
  2418. (let ((pad (js2-make-pad i)))
  2419. (insert " finally {\n")
  2420. (js2-print-body (js2-finally-node-body n) (1+ i))
  2421. (insert pad "}\n")))
  2422. (cl-defstruct (js2-switch-node
  2423. (:include js2-scope)
  2424. (:constructor make-js2-switch-node (&key (type js2-SWITCH)
  2425. (pos js2-ts-cursor)
  2426. len
  2427. discriminant
  2428. cases lp
  2429. rp)))
  2430. "AST node for a switch statement."
  2431. discriminant ; a `js2-node' (switch expression)
  2432. cases ; a Lisp list of `js2-case-node'
  2433. lp ; position of open-paren for discriminant, nil if omitted
  2434. rp) ; position of close-paren for discriminant, nil if omitted
  2435. (js2--struct-put 'js2-switch-node 'js2-visitor 'js2-visit-switch-node)
  2436. (js2--struct-put 'js2-switch-node 'js2-printer 'js2-print-switch-node)
  2437. (defun js2-visit-switch-node (n v)
  2438. (js2-visit-ast (js2-switch-node-discriminant n) v)
  2439. (dolist (c (js2-switch-node-cases n))
  2440. (js2-visit-ast c v)))
  2441. (defun js2-print-switch-node (n i)
  2442. (let ((pad (js2-make-pad i))
  2443. (cases (js2-switch-node-cases n)))
  2444. (insert pad "switch (")
  2445. (js2-print-ast (js2-switch-node-discriminant n) 0)
  2446. (insert ") {\n")
  2447. (dolist (case cases)
  2448. (js2-print-ast case i))
  2449. (insert pad "}\n")))
  2450. (cl-defstruct (js2-case-node
  2451. (:include js2-block-node)
  2452. (:constructor make-js2-case-node (&key (type js2-CASE)
  2453. (pos js2-ts-cursor)
  2454. len kids expr)))
  2455. "AST node for a case clause of a switch statement."
  2456. expr) ; the case expression (nil for default)
  2457. (js2--struct-put 'js2-case-node 'js2-visitor 'js2-visit-case-node)
  2458. (js2--struct-put 'js2-case-node 'js2-printer 'js2-print-case-node)
  2459. (defun js2-visit-case-node (n v)
  2460. (js2-visit-ast (js2-case-node-expr n) v)
  2461. (js2-visit-block n v))
  2462. (defun js2-print-case-node (n i)
  2463. (let ((pad (js2-make-pad i))
  2464. (expr (js2-case-node-expr n)))
  2465. (insert pad)
  2466. (if (null expr)
  2467. (insert "default:\n")
  2468. (insert "case ")
  2469. (js2-print-ast expr 0)
  2470. (insert ":\n"))
  2471. (dolist (kid (js2-case-node-kids n))
  2472. (js2-print-ast kid (1+ i)))))
  2473. (cl-defstruct (js2-throw-node
  2474. (:include js2-node)
  2475. (:constructor make-js2-throw-node (&key (type js2-THROW)
  2476. (pos js2-ts-cursor)
  2477. len expr)))
  2478. "AST node for a throw statement."
  2479. expr) ; the expression to throw
  2480. (js2--struct-put 'js2-throw-node 'js2-visitor 'js2-visit-throw-node)
  2481. (js2--struct-put 'js2-throw-node 'js2-printer 'js2-print-throw-node)
  2482. (defun js2-visit-throw-node (n v)
  2483. (js2-visit-ast (js2-throw-node-expr n) v))
  2484. (defun js2-print-throw-node (n i)
  2485. (insert (js2-make-pad i) "throw ")
  2486. (js2-print-ast (js2-throw-node-expr n) 0)
  2487. (insert ";\n"))
  2488. (cl-defstruct (js2-with-node
  2489. (:include js2-node)
  2490. (:constructor make-js2-with-node (&key (type js2-WITH)
  2491. (pos js2-ts-cursor)
  2492. len object
  2493. body lp rp)))
  2494. "AST node for a with-statement."
  2495. object
  2496. body
  2497. lp ; buffer position of left-paren around object, nil if omitted
  2498. rp) ; buffer position of right-paren around object, nil if omitted
  2499. (js2--struct-put 'js2-with-node 'js2-visitor 'js2-visit-with-node)
  2500. (js2--struct-put 'js2-with-node 'js2-printer 'js2-print-with-node)
  2501. (defun js2-visit-with-node (n v)
  2502. (js2-visit-ast (js2-with-node-object n) v)
  2503. (js2-visit-ast (js2-with-node-body n) v))
  2504. (defun js2-print-with-node (n i)
  2505. (let ((pad (js2-make-pad i)))
  2506. (insert pad "with (")
  2507. (js2-print-ast (js2-with-node-object n) 0)
  2508. (insert ") {\n")
  2509. (js2-print-body (js2-with-node-body n) (1+ i))
  2510. (insert pad "}\n")))
  2511. (cl-defstruct (js2-label-node
  2512. (:include js2-node)
  2513. (:constructor make-js2-label-node (&key (type js2-LABEL)
  2514. (pos js2-ts-cursor)
  2515. len name)))
  2516. "AST node for a statement label or case label."
  2517. name ; a string
  2518. loop) ; for validating and code-generating continue-to-label
  2519. (js2--struct-put 'js2-label-node 'js2-visitor 'js2-visit-none)
  2520. (js2--struct-put 'js2-label-node 'js2-printer 'js2-print-label)
  2521. (defun js2-print-label (n i)
  2522. (insert (js2-make-pad i)
  2523. (js2-label-node-name n)
  2524. ":\n"))
  2525. (cl-defstruct (js2-labeled-stmt-node
  2526. (:include js2-node)
  2527. ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
  2528. ;; no-side-effects warnings, hence js2-EXPR_RESULT.
  2529. (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
  2530. (pos js2-ts-cursor)
  2531. len labels stmt)))
  2532. "AST node for a statement with one or more labels.
  2533. Multiple labels for a statement are collapsed into the labels field."
  2534. labels ; Lisp list of `js2-label-node'
  2535. stmt) ; the statement these labels are for
  2536. (js2--struct-put 'js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
  2537. (js2--struct-put 'js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
  2538. (defun js2-get-label-by-name (lbl-stmt name)
  2539. "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
  2540. Returns nil if no such label is in the list."
  2541. (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
  2542. result)
  2543. (while (and label-list (not result))
  2544. (if (string= (js2-label-node-name (car label-list)) name)
  2545. (setq result (car label-list))
  2546. (setq label-list (cdr label-list))))
  2547. result))
  2548. (defun js2-visit-labeled-stmt (n v)
  2549. (dolist (label (js2-labeled-stmt-node-labels n))
  2550. (js2-visit-ast label v))
  2551. (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
  2552. (defun js2-print-labeled-stmt (n i)
  2553. (dolist (label (js2-labeled-stmt-node-labels n))
  2554. (js2-print-ast label i))
  2555. (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
  2556. (defun js2-labeled-stmt-node-contains (node label)
  2557. "Return t if NODE contains LABEL in its label set.
  2558. NODE is a `js2-labels-node'. LABEL is an identifier."
  2559. (cl-loop for nl in (js2-labeled-stmt-node-labels node)
  2560. if (string= label (js2-label-node-name nl))
  2561. return t
  2562. finally return nil))
  2563. (defsubst js2-labeled-stmt-node-add-label (node label)
  2564. "Add a `js2-label-node' to the label set for this statement."
  2565. (setf (js2-labeled-stmt-node-labels node)
  2566. (nconc (js2-labeled-stmt-node-labels node) (list label))))
  2567. (cl-defstruct (js2-jump-node
  2568. (:include js2-node)
  2569. (:constructor nil))
  2570. "Abstract supertype of break and continue nodes."
  2571. label ; `js2-name-node' for location of label identifier, if present
  2572. target) ; target js2-labels-node or loop/switch statement
  2573. (defun js2-visit-jump-node (n v)
  2574. ;; We don't visit the target, since it's a back-link.
  2575. (js2-visit-ast (js2-jump-node-label n) v))
  2576. (cl-defstruct (js2-break-node
  2577. (:include js2-jump-node)
  2578. (:constructor make-js2-break-node (&key (type js2-BREAK)
  2579. (pos js2-ts-cursor)
  2580. len label target)))
  2581. "AST node for a break statement.
  2582. The label field is a `js2-name-node', possibly nil, for the named label
  2583. if provided. E.g. in 'break foo', it represents 'foo'. The target field
  2584. is the target of the break - a label node or enclosing loop/switch statement.")
  2585. (js2--struct-put 'js2-break-node 'js2-visitor 'js2-visit-jump-node)
  2586. (js2--struct-put 'js2-break-node 'js2-printer 'js2-print-break-node)
  2587. (defun js2-print-break-node (n i)
  2588. (insert (js2-make-pad i) "break")
  2589. (when (js2-break-node-label n)
  2590. (insert " ")
  2591. (js2-print-ast (js2-break-node-label n) 0))
  2592. (insert ";\n"))
  2593. (cl-defstruct (js2-continue-node
  2594. (:include js2-jump-node)
  2595. (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
  2596. (pos js2-ts-cursor)
  2597. len label target)))
  2598. "AST node for a continue statement.
  2599. The label field is the user-supplied enclosing label name, a `js2-name-node'.
  2600. It is nil if continue specifies no label. The target field is the jump target:
  2601. a `js2-label-node' or the innermost enclosing loop.")
  2602. (js2--struct-put 'js2-continue-node 'js2-visitor 'js2-visit-jump-node)
  2603. (js2--struct-put 'js2-continue-node 'js2-printer 'js2-print-continue-node)
  2604. (defun js2-print-continue-node (n i)
  2605. (insert (js2-make-pad i) "continue")
  2606. (when (js2-continue-node-label n)
  2607. (insert " ")
  2608. (js2-print-ast (js2-continue-node-label n) 0))
  2609. (insert ";\n"))
  2610. (cl-defstruct (js2-function-node
  2611. (:include js2-script-node)
  2612. (:constructor make-js2-function-node (&key (type js2-FUNCTION)
  2613. (pos js2-ts-cursor)
  2614. len
  2615. (ftype 'FUNCTION)
  2616. (form 'FUNCTION_STATEMENT)
  2617. (name "")
  2618. params rest-p
  2619. body
  2620. generator-type
  2621. async
  2622. lp rp)))
  2623. "AST node for a function declaration.
  2624. The `params' field is a Lisp list of nodes. Each node is either a simple
  2625. `js2-name-node', or if it's a destructuring-assignment parameter, a
  2626. `js2-array-node' or `js2-object-node'."
  2627. ftype ; FUNCTION, GETTER or SETTER
  2628. form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
  2629. name ; function name (a `js2-name-node', or nil if anonymous)
  2630. params ; a Lisp list of destructuring forms or simple name nodes
  2631. rest-p ; if t, the last parameter is rest parameter
  2632. body ; a `js2-block-node' or expression node (1.8 only)
  2633. lp ; position of arg-list open-paren, or nil if omitted
  2634. rp ; position of arg-list close-paren, or nil if omitted
  2635. ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
  2636. needs-activation ; t if we need an activation object for this frame
  2637. generator-type ; STAR, LEGACY, COMPREHENSION or nil
  2638. async ; t if the function is defined as `async function`
  2639. member-expr) ; nonstandard Ecma extension from Rhino
  2640. (js2--struct-put 'js2-function-node 'js2-visitor 'js2-visit-function-node)
  2641. (js2--struct-put 'js2-function-node 'js2-printer 'js2-print-function-node)
  2642. (defun js2-visit-function-node (n v)
  2643. (js2-visit-ast (js2-function-node-name n) v)
  2644. (dolist (p (js2-function-node-params n))
  2645. (js2-visit-ast p v))
  2646. (js2-visit-ast (js2-function-node-body n) v))
  2647. (defun js2-print-function-node (n i)
  2648. (let* ((pad (js2-make-pad i))
  2649. (method (js2-node-get-prop n 'METHOD_TYPE))
  2650. (name (or (js2-function-node-name n)
  2651. (js2-function-node-member-expr n)))
  2652. (params (js2-function-node-params n))
  2653. (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
  2654. (rest-p (js2-function-node-rest-p n))
  2655. (body (js2-function-node-body n))
  2656. (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
  2657. (unless method
  2658. (insert pad)
  2659. (when (js2-function-node-async n) (insert "async "))
  2660. (unless arrow (insert "function"))
  2661. (when (eq (js2-function-node-generator-type n) 'STAR)
  2662. (insert "*")))
  2663. (when name
  2664. (insert " ")
  2665. (js2-print-ast name 0))
  2666. (insert "(")
  2667. (cl-loop with len = (length params)
  2668. for param in params
  2669. for count from 1
  2670. do
  2671. (when (and rest-p (= count len))
  2672. (insert "..."))
  2673. (js2-print-ast param 0)
  2674. (when (< count len)
  2675. (insert ", ")))
  2676. (insert ") ")
  2677. (when arrow
  2678. (insert "=> "))
  2679. (insert "{")
  2680. ;; TODO: fix this to be smarter about indenting, etc.
  2681. (unless expr
  2682. (insert "\n"))
  2683. (if (js2-block-node-p body)
  2684. (js2-print-body body (1+ i))
  2685. (js2-print-ast body 0))
  2686. (insert pad "}")
  2687. (unless expr
  2688. (insert "\n"))))
  2689. (defun js2-function-name (node)
  2690. "Return function name for NODE, a `js2-function-node', or nil if anonymous."
  2691. (and (js2-function-node-name node)
  2692. (js2-name-node-name (js2-function-node-name node))))
  2693. ;; Having this be an expression node makes it more flexible.
  2694. ;; There are IDE contexts, such as indentation in a for-loop initializer,
  2695. ;; that work better if you assume it's an expression. Whenever we have
  2696. ;; a standalone var/const declaration, we just wrap with an expr stmt.
  2697. ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
  2698. (cl-defstruct (js2-var-decl-node
  2699. (:include js2-node)
  2700. (:constructor make-js2-var-decl-node (&key (type js2-VAR)
  2701. (pos (js2-current-token-beg))
  2702. len kids
  2703. decl-type)))
  2704. "AST node for a variable declaration list (VAR, CONST or LET).
  2705. The node bounds differ depending on the declaration type. For VAR or
  2706. CONST declarations, the bounds include the var/const keyword. For LET
  2707. declarations, the node begins at the position of the first child."
  2708. kids ; a Lisp list of `js2-var-init-node' structs.
  2709. decl-type) ; js2-VAR, js2-CONST or js2-LET
  2710. (js2--struct-put 'js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
  2711. (js2--struct-put 'js2-var-decl-node 'js2-printer 'js2-print-var-decl)
  2712. (defun js2-visit-var-decl (n v)
  2713. (dolist (kid (js2-var-decl-node-kids n))
  2714. (js2-visit-ast kid v)))
  2715. (defun js2-print-var-decl (n i)
  2716. (let ((pad (js2-make-pad i))
  2717. (tt (js2-var-decl-node-decl-type n)))
  2718. (insert pad)
  2719. (insert (cond
  2720. ((= tt js2-VAR) "var ")
  2721. ((= tt js2-LET) "let ")
  2722. ((= tt js2-CONST) "const ")
  2723. (t
  2724. (error "malformed var-decl node"))))
  2725. (cl-loop with kids = (js2-var-decl-node-kids n)
  2726. with len = (length kids)
  2727. for kid in kids
  2728. for count from 1
  2729. do
  2730. (js2-print-ast kid 0)
  2731. (if (< count len)
  2732. (insert ", ")))))
  2733. (cl-defstruct (js2-var-init-node
  2734. (:include js2-node)
  2735. (:constructor make-js2-var-init-node (&key (type js2-VAR)
  2736. (pos js2-ts-cursor)
  2737. len target
  2738. initializer)))
  2739. "AST node for a variable declaration.
  2740. The type field will be js2-CONST for a const decl."
  2741. target ; `js2-name-node', `js2-object-node', or `js2-array-node'
  2742. initializer) ; initializer expression, a `js2-node'
  2743. (js2--struct-put 'js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
  2744. (js2--struct-put 'js2-var-init-node 'js2-printer 'js2-print-var-init-node)
  2745. (defun js2-visit-var-init-node (n v)
  2746. (js2-visit-ast (js2-var-init-node-target n) v)
  2747. (js2-visit-ast (js2-var-init-node-initializer n) v))
  2748. (defun js2-print-var-init-node (n i)
  2749. (let ((pad (js2-make-pad i))
  2750. (name (js2-var-init-node-target n))
  2751. (init (js2-var-init-node-initializer n)))
  2752. (insert pad)
  2753. (js2-print-ast name 0)
  2754. (when init
  2755. (insert " = ")
  2756. (js2-print-ast init 0))))
  2757. (cl-defstruct (js2-cond-node
  2758. (:include js2-node)
  2759. (:constructor make-js2-cond-node (&key (type js2-HOOK)
  2760. (pos js2-ts-cursor)
  2761. len
  2762. test-expr
  2763. true-expr
  2764. false-expr
  2765. q-pos c-pos)))
  2766. "AST node for the ternary operator"
  2767. test-expr
  2768. true-expr
  2769. false-expr
  2770. q-pos ; buffer position of ?
  2771. c-pos) ; buffer position of :
  2772. (js2--struct-put 'js2-cond-node 'js2-visitor 'js2-visit-cond-node)
  2773. (js2--struct-put 'js2-cond-node 'js2-printer 'js2-print-cond-node)
  2774. (defun js2-visit-cond-node (n v)
  2775. (js2-visit-ast (js2-cond-node-test-expr n) v)
  2776. (js2-visit-ast (js2-cond-node-true-expr n) v)
  2777. (js2-visit-ast (js2-cond-node-false-expr n) v))
  2778. (defun js2-print-cond-node (n i)
  2779. (let ((pad (js2-make-pad i)))
  2780. (insert pad)
  2781. (js2-print-ast (js2-cond-node-test-expr n) 0)
  2782. (insert " ? ")
  2783. (js2-print-ast (js2-cond-node-true-expr n) 0)
  2784. (insert " : ")
  2785. (js2-print-ast (js2-cond-node-false-expr n) 0)))
  2786. (cl-defstruct (js2-infix-node
  2787. (:include js2-node)
  2788. (:constructor make-js2-infix-node (&key type
  2789. (pos js2-ts-cursor)
  2790. len op-pos
  2791. left right)))
  2792. "Represents infix expressions.
  2793. Includes assignment ops like `|=', and the comma operator.
  2794. The type field inherited from `js2-node' holds the operator."
  2795. op-pos ; buffer position where operator begins
  2796. left ; any `js2-node'
  2797. right) ; any `js2-node'
  2798. (js2--struct-put 'js2-infix-node 'js2-visitor 'js2-visit-infix-node)
  2799. (js2--struct-put 'js2-infix-node 'js2-printer 'js2-print-infix-node)
  2800. (defun js2-visit-infix-node (n v)
  2801. (js2-visit-ast (js2-infix-node-left n) v)
  2802. (js2-visit-ast (js2-infix-node-right n) v))
  2803. (defconst js2-operator-tokens
  2804. (let ((table (make-hash-table :test 'eq))
  2805. (tokens
  2806. (list (cons js2-IN "in")
  2807. (cons js2-TYPEOF "typeof")
  2808. (cons js2-INSTANCEOF "instanceof")
  2809. (cons js2-DELPROP "delete")
  2810. (cons js2-AWAIT "await")
  2811. (cons js2-VOID "void")
  2812. (cons js2-COMMA ",")
  2813. (cons js2-COLON ":")
  2814. (cons js2-OR "||")
  2815. (cons js2-AND "&&")
  2816. (cons js2-INC "++")
  2817. (cons js2-DEC "--")
  2818. (cons js2-BITOR "|")
  2819. (cons js2-BITXOR "^")
  2820. (cons js2-BITAND "&")
  2821. (cons js2-EQ "==")
  2822. (cons js2-NE "!=")
  2823. (cons js2-LT "<")
  2824. (cons js2-LE "<=")
  2825. (cons js2-GT ">")
  2826. (cons js2-GE ">=")
  2827. (cons js2-LSH "<<")
  2828. (cons js2-RSH ">>")
  2829. (cons js2-URSH ">>>")
  2830. (cons js2-ADD "+") ; infix plus
  2831. (cons js2-SUB "-") ; infix minus
  2832. (cons js2-MUL "*")
  2833. (cons js2-EXPON "**")
  2834. (cons js2-DIV "/")
  2835. (cons js2-MOD "%")
  2836. (cons js2-NOT "!")
  2837. (cons js2-BITNOT "~")
  2838. (cons js2-POS "+") ; unary plus
  2839. (cons js2-NEG "-") ; unary minus
  2840. (cons js2-TRIPLEDOT "...")
  2841. (cons js2-SHEQ "===") ; shallow equality
  2842. (cons js2-SHNE "!==") ; shallow inequality
  2843. (cons js2-ASSIGN "=")
  2844. (cons js2-ASSIGN_BITOR "|=")
  2845. (cons js2-ASSIGN_BITXOR "^=")
  2846. (cons js2-ASSIGN_BITAND "&=")
  2847. (cons js2-ASSIGN_LSH "<<=")
  2848. (cons js2-ASSIGN_RSH ">>=")
  2849. (cons js2-ASSIGN_URSH ">>>=")
  2850. (cons js2-ASSIGN_ADD "+=")
  2851. (cons js2-ASSIGN_SUB "-=")
  2852. (cons js2-ASSIGN_MUL "*=")
  2853. (cons js2-ASSIGN_EXPON "**=")
  2854. (cons js2-ASSIGN_DIV "/=")
  2855. (cons js2-ASSIGN_MOD "%="))))
  2856. (cl-loop for (k . v) in tokens do
  2857. (puthash k v table))
  2858. table))
  2859. (defun js2-print-infix-node (n i)
  2860. (let* ((tt (js2-node-type n))
  2861. (op (gethash tt js2-operator-tokens)))
  2862. (unless op
  2863. (error "unrecognized infix operator %s" (js2-node-type n)))
  2864. (insert (js2-make-pad i))
  2865. (js2-print-ast (js2-infix-node-left n) 0)
  2866. (unless (= tt js2-COMMA)
  2867. (insert " "))
  2868. (insert op)
  2869. (insert " ")
  2870. (js2-print-ast (js2-infix-node-right n) 0)))
  2871. (cl-defstruct (js2-assign-node
  2872. (:include js2-infix-node)
  2873. (:constructor make-js2-assign-node (&key type
  2874. (pos js2-ts-cursor)
  2875. len op-pos
  2876. left right)))
  2877. "Represents any assignment.
  2878. The type field holds the actual assignment operator.")
  2879. (js2--struct-put 'js2-assign-node 'js2-visitor 'js2-visit-infix-node)
  2880. (js2--struct-put 'js2-assign-node 'js2-printer 'js2-print-infix-node)
  2881. (cl-defstruct (js2-unary-node
  2882. (:include js2-node)
  2883. (:constructor make-js2-unary-node (&key type ; required
  2884. (pos js2-ts-cursor)
  2885. len operand)))
  2886. "AST node type for unary operator nodes.
  2887. The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
  2888. TYPEOF, DELPROP, TRIPLEDOT or AWAIT. For INC or DEC, a 'postfix node
  2889. property is added if the operator follows the operand."
  2890. operand) ; a `js2-node' expression
  2891. (js2--struct-put 'js2-unary-node 'js2-visitor 'js2-visit-unary-node)
  2892. (js2--struct-put 'js2-unary-node 'js2-printer 'js2-print-unary-node)
  2893. (defun js2-visit-unary-node (n v)
  2894. (js2-visit-ast (js2-unary-node-operand n) v))
  2895. (defun js2-print-unary-node (n i)
  2896. (let* ((tt (js2-node-type n))
  2897. (op (gethash tt js2-operator-tokens))
  2898. (postfix (js2-node-get-prop n 'postfix)))
  2899. (unless op
  2900. (error "unrecognized unary operator %s" tt))
  2901. (insert (js2-make-pad i))
  2902. (unless postfix
  2903. (insert op))
  2904. (if (or (= tt js2-TYPEOF)
  2905. (= tt js2-DELPROP)
  2906. (= tt js2-AWAIT)
  2907. (= tt js2-VOID))
  2908. (insert " "))
  2909. (js2-print-ast (js2-unary-node-operand n) 0)
  2910. (when postfix
  2911. (insert op))))
  2912. (cl-defstruct (js2-let-node
  2913. (:include js2-scope)
  2914. (:constructor make-js2-let-node (&key (type js2-LETEXPR)
  2915. (pos (js2-current-token-beg))
  2916. len vars body
  2917. lp rp)))
  2918. "AST node for a let expression or a let statement.
  2919. Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
  2920. vars ; a `js2-var-decl-node'
  2921. body ; a `js2-node' representing the expression or body block
  2922. lp
  2923. rp)
  2924. (js2--struct-put 'js2-let-node 'js2-visitor 'js2-visit-let-node)
  2925. (js2--struct-put 'js2-let-node 'js2-printer 'js2-print-let-node)
  2926. (defun js2-visit-let-node (n v)
  2927. (js2-visit-ast (js2-let-node-vars n) v)
  2928. (js2-visit-ast (js2-let-node-body n) v))
  2929. (defun js2-print-let-node (n i)
  2930. (insert (js2-make-pad i) "let (")
  2931. (let ((p (point)))
  2932. (js2-print-ast (js2-let-node-vars n) 0)
  2933. (delete-region p (+ p 4)))
  2934. (insert ") ")
  2935. (js2-print-ast (js2-let-node-body n) i))
  2936. (cl-defstruct (js2-keyword-node
  2937. (:include js2-node)
  2938. (:constructor make-js2-keyword-node (&key type
  2939. (pos (js2-current-token-beg))
  2940. (len (- js2-ts-cursor pos)))))
  2941. "AST node representing a literal keyword such as `null'.
  2942. Used for `null', `this', `true', `false' and `debugger'.
  2943. The node type is set to js2-NULL, js2-THIS, etc.")
  2944. (js2--struct-put 'js2-keyword-node 'js2-visitor 'js2-visit-none)
  2945. (js2--struct-put 'js2-keyword-node 'js2-printer 'js2-print-keyword-node)
  2946. (defun js2-print-keyword-node (n i)
  2947. (insert (js2-make-pad i)
  2948. (let ((tt (js2-node-type n)))
  2949. (cond
  2950. ((= tt js2-THIS) "this")
  2951. ((= tt js2-SUPER) "super")
  2952. ((= tt js2-NULL) "null")
  2953. ((= tt js2-TRUE) "true")
  2954. ((= tt js2-FALSE) "false")
  2955. ((= tt js2-DEBUGGER) "debugger")
  2956. (t (error "Invalid keyword literal type: %d" tt))))))
  2957. (defsubst js2-this-or-super-node-p (node)
  2958. "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
  2959. (let ((type (js2-node-type node)))
  2960. (or (eq type js2-THIS) (eq type js2-SUPER))))
  2961. (cl-defstruct (js2-new-node
  2962. (:include js2-node)
  2963. (:constructor make-js2-new-node (&key (type js2-NEW)
  2964. (pos (js2-current-token-beg))
  2965. len target
  2966. args initializer
  2967. lp rp)))
  2968. "AST node for new-expression such as new Foo()."
  2969. target ; an identifier or reference
  2970. args ; a Lisp list of argument nodes
  2971. lp ; position of left-paren, nil if omitted
  2972. rp ; position of right-paren, nil if omitted
  2973. initializer) ; experimental Rhino syntax: optional `js2-object-node'
  2974. (js2--struct-put 'js2-new-node 'js2-visitor 'js2-visit-new-node)
  2975. (js2--struct-put 'js2-new-node 'js2-printer 'js2-print-new-node)
  2976. (defun js2-visit-new-node (n v)
  2977. (js2-visit-ast (js2-new-node-target n) v)
  2978. (dolist (arg (js2-new-node-args n))
  2979. (js2-visit-ast arg v))
  2980. (js2-visit-ast (js2-new-node-initializer n) v))
  2981. (defun js2-print-new-node (n i)
  2982. (insert (js2-make-pad i) "new ")
  2983. (js2-print-ast (js2-new-node-target n))
  2984. (insert "(")
  2985. (js2-print-list (js2-new-node-args n))
  2986. (insert ")")
  2987. (when (js2-new-node-initializer n)
  2988. (insert " ")
  2989. (js2-print-ast (js2-new-node-initializer n))))
  2990. (cl-defstruct (js2-name-node
  2991. (:include js2-node)
  2992. (:constructor make-js2-name-node (&key (type js2-NAME)
  2993. (pos (js2-current-token-beg))
  2994. (len (- js2-ts-cursor
  2995. (js2-current-token-beg)))
  2996. (name (js2-current-token-string)))))
  2997. "AST node for a JavaScript identifier"
  2998. name ; a string
  2999. scope) ; a `js2-scope' (optional, used for codegen)
  3000. (js2--struct-put 'js2-name-node 'js2-visitor 'js2-visit-none)
  3001. (js2--struct-put 'js2-name-node 'js2-printer 'js2-print-name-node)
  3002. (defun js2-print-name-node (n i)
  3003. (insert (js2-make-pad i)
  3004. (js2-name-node-name n)))
  3005. (defsubst js2-name-node-length (node)
  3006. "Return identifier length of NODE, a `js2-name-node'.
  3007. Returns 0 if NODE is nil or its identifier field is nil."
  3008. (if node
  3009. (length (js2-name-node-name node))
  3010. 0))
  3011. (cl-defstruct (js2-number-node
  3012. (:include js2-node)
  3013. (:constructor make-js2-number-node (&key (type js2-NUMBER)
  3014. (pos (js2-current-token-beg))
  3015. (len (- js2-ts-cursor
  3016. (js2-current-token-beg)))
  3017. (value (js2-current-token-string))
  3018. (num-value (js2-token-number
  3019. (js2-current-token)))
  3020. (num-base (js2-token-number-base
  3021. (js2-current-token)))
  3022. (legacy-octal-p (js2-token-number-legacy-octal-p
  3023. (js2-current-token))))))
  3024. "AST node for a number literal."
  3025. value ; the original string, e.g. "6.02e23"
  3026. num-value ; the parsed number value
  3027. num-base ; the number's base
  3028. legacy-octal-p) ; whether the number is a legacy octal (0123 instead of 0o123)
  3029. (js2--struct-put 'js2-number-node 'js2-visitor 'js2-visit-none)
  3030. (js2--struct-put 'js2-number-node 'js2-printer 'js2-print-number-node)
  3031. (defun js2-print-number-node (n i)
  3032. (insert (js2-make-pad i)
  3033. (number-to-string (js2-number-node-num-value n))))
  3034. (cl-defstruct (js2-regexp-node
  3035. (:include js2-node)
  3036. (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
  3037. (pos (js2-current-token-beg))
  3038. (len (- js2-ts-cursor
  3039. (js2-current-token-beg)))
  3040. value flags)))
  3041. "AST node for a regular expression literal."
  3042. value ; the regexp string, without // delimiters
  3043. flags) ; a string of flags, e.g. `mi'.
  3044. (js2--struct-put 'js2-regexp-node 'js2-visitor 'js2-visit-none)
  3045. (js2--struct-put 'js2-regexp-node 'js2-printer 'js2-print-regexp)
  3046. (defun js2-print-regexp (n i)
  3047. (insert (js2-make-pad i)
  3048. "/"
  3049. (js2-regexp-node-value n)
  3050. "/")
  3051. (if (js2-regexp-node-flags n)
  3052. (insert (js2-regexp-node-flags n))))
  3053. (cl-defstruct (js2-string-node
  3054. (:include js2-node)
  3055. (:constructor make-js2-string-node (&key (type js2-STRING)
  3056. (pos (js2-current-token-beg))
  3057. (len (- js2-ts-cursor
  3058. (js2-current-token-beg)))
  3059. (value (js2-current-token-string)))))
  3060. "String literal.
  3061. Escape characters are not evaluated; e.g. \n is 2 chars in value field.
  3062. You can tell the quote type by looking at the first character."
  3063. value) ; the characters of the string, including the quotes
  3064. (js2--struct-put 'js2-string-node 'js2-visitor 'js2-visit-none)
  3065. (js2--struct-put 'js2-string-node 'js2-printer 'js2-print-string-node)
  3066. (defun js2-print-string-node (n i)
  3067. (insert (js2-make-pad i)
  3068. (js2-node-string n)))
  3069. (cl-defstruct (js2-template-node
  3070. (:include js2-node)
  3071. (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
  3072. pos len kids)))
  3073. "Template literal."
  3074. kids) ; `js2-string-node' is used for string segments, other nodes
  3075. ; for substitutions inside.
  3076. (js2--struct-put 'js2-template-node 'js2-visitor 'js2-visit-template)
  3077. (js2--struct-put 'js2-template-node 'js2-printer 'js2-print-template)
  3078. (defun js2-visit-template (n callback)
  3079. (dolist (kid (js2-template-node-kids n))
  3080. (js2-visit-ast kid callback)))
  3081. (defun js2-print-template (n i)
  3082. (insert (js2-make-pad i))
  3083. (dolist (kid (js2-template-node-kids n))
  3084. (if (js2-string-node-p kid)
  3085. (insert (js2-node-string kid))
  3086. (js2-print-ast kid))))
  3087. (cl-defstruct (js2-tagged-template-node
  3088. (:include js2-node)
  3089. (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
  3090. pos len tag template)))
  3091. "Tagged template literal."
  3092. tag ; `js2-node' with the tag expression.
  3093. template) ; `js2-template-node' with the template.
  3094. (js2--struct-put 'js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
  3095. (js2--struct-put 'js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
  3096. (defun js2-visit-tagged-template (n callback)
  3097. (js2-visit-ast (js2-tagged-template-node-tag n) callback)
  3098. (js2-visit-ast (js2-tagged-template-node-template n) callback))
  3099. (defun js2-print-tagged-template (n i)
  3100. (insert (js2-make-pad i))
  3101. (js2-print-ast (js2-tagged-template-node-tag n))
  3102. (js2-print-ast (js2-tagged-template-node-template n)))
  3103. (cl-defstruct (js2-array-node
  3104. (:include js2-node)
  3105. (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
  3106. (pos js2-ts-cursor)
  3107. len elems)))
  3108. "AST node for an array literal."
  3109. elems) ; list of expressions. [foo,,bar] yields a nil middle element.
  3110. (js2--struct-put 'js2-array-node 'js2-visitor 'js2-visit-array-node)
  3111. (js2--struct-put 'js2-array-node 'js2-printer 'js2-print-array-node)
  3112. (defun js2-visit-array-node (n v)
  3113. (dolist (e (js2-array-node-elems n))
  3114. (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
  3115. (defun js2-print-array-node (n i)
  3116. (insert (js2-make-pad i) "[")
  3117. (let ((elems (js2-array-node-elems n)))
  3118. (js2-print-list elems)
  3119. (when (and elems (null (car (last elems))))
  3120. (insert ",")))
  3121. (insert "]"))
  3122. (cl-defstruct (js2-object-node
  3123. (:include js2-node)
  3124. (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
  3125. (pos js2-ts-cursor)
  3126. len
  3127. elems)))
  3128. "AST node for an object literal expression.
  3129. `elems' is a list of `js2-object-prop-node'."
  3130. elems)
  3131. (js2--struct-put 'js2-object-node 'js2-visitor 'js2-visit-object-node)
  3132. (js2--struct-put 'js2-object-node 'js2-printer 'js2-print-object-node)
  3133. (defun js2-visit-object-node (n v)
  3134. (dolist (e (js2-object-node-elems n))
  3135. (js2-visit-ast e v)))
  3136. (defun js2-print-object-node (n i)
  3137. (insert (js2-make-pad i) "{")
  3138. (js2-print-list (js2-object-node-elems n))
  3139. (insert "}"))
  3140. (cl-defstruct (js2-class-node
  3141. (:include js2-object-node)
  3142. (:constructor make-js2-class-node (&key (type js2-CLASS)
  3143. (pos js2-ts-cursor)
  3144. (form 'CLASS_STATEMENT)
  3145. (name "")
  3146. extends len elems)))
  3147. "AST node for an class expression.
  3148. `elems' is a list of `js2-object-prop-node', and `extends' is an
  3149. optional `js2-expr-node'"
  3150. form ; CLASS_{STATEMENT|EXPRESSION}
  3151. name ; class name (a `js2-node-name', or nil if anonymous)
  3152. extends ; class heritage (a `js2-expr-node', or nil if none)
  3153. )
  3154. (js2--struct-put 'js2-class-node 'js2-visitor 'js2-visit-class-node)
  3155. (js2--struct-put 'js2-class-node 'js2-printer 'js2-print-class-node)
  3156. (defun js2-visit-class-node (n v)
  3157. (js2-visit-ast (js2-class-node-name n) v)
  3158. (js2-visit-ast (js2-class-node-extends n) v)
  3159. (dolist (e (js2-class-node-elems n))
  3160. (js2-visit-ast e v)))
  3161. (defun js2-print-class-node (n i)
  3162. (let* ((pad (js2-make-pad i))
  3163. (name (js2-class-node-name n))
  3164. (extends (js2-class-node-extends n))
  3165. (elems (js2-class-node-elems n)))
  3166. (insert pad "class")
  3167. (when name
  3168. (insert " ")
  3169. (js2-print-ast name 0))
  3170. (when extends
  3171. (insert " extends ")
  3172. (js2-print-ast extends))
  3173. (insert " {")
  3174. (dolist (elem elems)
  3175. (insert "\n")
  3176. (if (js2-node-get-prop elem 'STATIC)
  3177. (progn (insert (js2-make-pad (1+ i)) "static ")
  3178. (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
  3179. (js2-print-ast elem (1+ i))))
  3180. (insert "\n" pad "}")))
  3181. (cl-defstruct (js2-computed-prop-name-node
  3182. (:include js2-node)
  3183. (:constructor make-js2-computed-prop-name-node
  3184. (&key
  3185. (type js2-LB)
  3186. expr
  3187. (pos (js2-current-token-beg))
  3188. (len (- js2-ts-cursor
  3189. (js2-current-token-beg))))))
  3190. "AST node for a `ComputedPropertyName'."
  3191. expr)
  3192. (js2--struct-put 'js2-computed-prop-name-node 'js2-visitor 'js2-visit-computed-prop-name-node)
  3193. (js2--struct-put 'js2-computed-prop-name-node 'js2-printer 'js2-print-computed-prop-name-node)
  3194. (defun js2-visit-computed-prop-name-node (n v)
  3195. (js2-visit-ast (js2-computed-prop-name-node-expr n) v))
  3196. (defun js2-print-computed-prop-name-node (n i)
  3197. (insert (js2-make-pad i) "[")
  3198. (js2-print-ast (js2-computed-prop-name-node-expr n) 0)
  3199. (insert "]"))
  3200. (cl-defstruct (js2-object-prop-node
  3201. (:include js2-infix-node)
  3202. (:constructor make-js2-object-prop-node (&key (type js2-COLON)
  3203. (pos js2-ts-cursor)
  3204. len left
  3205. right op-pos)))
  3206. "AST node for an object literal prop:value entry.
  3207. The `left' field is the property: a name node, string node,
  3208. number node or expression node. The `right' field is a
  3209. `js2-node' representing the initializer value. If the property
  3210. is abbreviated, the node's `SHORTHAND' property is non-nil and
  3211. both fields have the same value.")
  3212. (js2--struct-put 'js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
  3213. (js2--struct-put 'js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
  3214. (defun js2-print-object-prop-node (n i)
  3215. (let* ((left (js2-object-prop-node-left n))
  3216. (right (js2-object-prop-node-right n)))
  3217. (js2-print-ast left i)
  3218. (if (not (js2-node-get-prop n 'SHORTHAND))
  3219. (progn
  3220. (insert ": ")
  3221. (js2-print-ast right 0)))))
  3222. (cl-defstruct (js2-method-node
  3223. (:include js2-infix-node)
  3224. (:constructor make-js2-method-node (&key (pos js2-ts-cursor)
  3225. len left right)))
  3226. "AST node for a method in an object literal or a class body.
  3227. The `left' field is the `js2-name-node' naming the method.
  3228. The `right' field is always an anonymous `js2-function-node' with a node
  3229. property `METHOD_TYPE' set to 'GET or 'SET. ")
  3230. (js2--struct-put 'js2-method-node 'js2-visitor 'js2-visit-infix-node)
  3231. (js2--struct-put 'js2-method-node 'js2-printer 'js2-print-method)
  3232. (defun js2-print-method (n i)
  3233. (let* ((pad (js2-make-pad i))
  3234. (left (js2-method-node-left n))
  3235. (right (js2-method-node-right n))
  3236. (type (js2-node-get-prop right 'METHOD_TYPE)))
  3237. (insert pad)
  3238. (when type
  3239. (insert (cdr (assoc type '((GET . "get ")
  3240. (SET . "set ")
  3241. (ASYNC . "async ")
  3242. (FUNCTION . ""))))))
  3243. (when (and (js2-function-node-p right)
  3244. (eq 'STAR (js2-function-node-generator-type right)))
  3245. (insert "*"))
  3246. (js2-print-ast left 0)
  3247. (js2-print-ast right 0)))
  3248. (cl-defstruct (js2-prop-get-node
  3249. (:include js2-infix-node)
  3250. (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
  3251. (pos js2-ts-cursor)
  3252. len left right)))
  3253. "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
  3254. (js2--struct-put 'js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
  3255. (js2--struct-put 'js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
  3256. (defun js2-visit-prop-get-node (n v)
  3257. (js2-visit-ast (js2-prop-get-node-left n) v)
  3258. (js2-visit-ast (js2-prop-get-node-right n) v))
  3259. (defun js2-print-prop-get-node (n i)
  3260. (insert (js2-make-pad i))
  3261. (js2-print-ast (js2-prop-get-node-left n) 0)
  3262. (insert ".")
  3263. (js2-print-ast (js2-prop-get-node-right n) 0))
  3264. (cl-defstruct (js2-elem-get-node
  3265. (:include js2-node)
  3266. (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
  3267. (pos js2-ts-cursor)
  3268. len target element
  3269. lb rb)))
  3270. "AST node for an array index expression such as foo[bar]."
  3271. target ; a `js2-node' - the expression preceding the "."
  3272. element ; a `js2-node' - the expression in brackets
  3273. lb ; position of left-bracket, nil if omitted
  3274. rb) ; position of right-bracket, nil if omitted
  3275. (js2--struct-put 'js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
  3276. (js2--struct-put 'js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
  3277. (defun js2-visit-elem-get-node (n v)
  3278. (js2-visit-ast (js2-elem-get-node-target n) v)
  3279. (js2-visit-ast (js2-elem-get-node-element n) v))
  3280. (defun js2-print-elem-get-node (n i)
  3281. (insert (js2-make-pad i))
  3282. (js2-print-ast (js2-elem-get-node-target n) 0)
  3283. (insert "[")
  3284. (js2-print-ast (js2-elem-get-node-element n) 0)
  3285. (insert "]"))
  3286. (cl-defstruct (js2-call-node
  3287. (:include js2-node)
  3288. (:constructor make-js2-call-node (&key (type js2-CALL)
  3289. (pos js2-ts-cursor)
  3290. len target args
  3291. lp rp)))
  3292. "AST node for a JavaScript function call."
  3293. target ; a `js2-node' evaluating to the function to call
  3294. args ; a Lisp list of `js2-node' arguments
  3295. lp ; position of open-paren, or nil if missing
  3296. rp) ; position of close-paren, or nil if missing
  3297. (js2--struct-put 'js2-call-node 'js2-visitor 'js2-visit-call-node)
  3298. (js2--struct-put 'js2-call-node 'js2-printer 'js2-print-call-node)
  3299. (defun js2-visit-call-node (n v)
  3300. (js2-visit-ast (js2-call-node-target n) v)
  3301. (dolist (arg (js2-call-node-args n))
  3302. (js2-visit-ast arg v)))
  3303. (defun js2-print-call-node (n i)
  3304. (insert (js2-make-pad i))
  3305. (js2-print-ast (js2-call-node-target n) 0)
  3306. (insert "(")
  3307. (js2-print-list (js2-call-node-args n))
  3308. (insert ")"))
  3309. (cl-defstruct (js2-yield-node
  3310. (:include js2-node)
  3311. (:constructor make-js2-yield-node (&key (type js2-YIELD)
  3312. (pos js2-ts-cursor)
  3313. len value star-p)))
  3314. "AST node for yield statement or expression."
  3315. star-p ; whether it's yield*
  3316. value) ; optional: value to be yielded
  3317. (js2--struct-put 'js2-yield-node 'js2-visitor 'js2-visit-yield-node)
  3318. (js2--struct-put 'js2-yield-node 'js2-printer 'js2-print-yield-node)
  3319. (defun js2-visit-yield-node (n v)
  3320. (js2-visit-ast (js2-yield-node-value n) v))
  3321. (defun js2-print-yield-node (n i)
  3322. (insert (js2-make-pad i))
  3323. (insert "yield")
  3324. (when (js2-yield-node-star-p n)
  3325. (insert "*"))
  3326. (when (js2-yield-node-value n)
  3327. (insert " ")
  3328. (js2-print-ast (js2-yield-node-value n) 0)))
  3329. (cl-defstruct (js2-paren-node
  3330. (:include js2-node)
  3331. (:constructor make-js2-paren-node (&key (type js2-LP)
  3332. (pos js2-ts-cursor)
  3333. len expr)))
  3334. "AST node for a parenthesized expression.
  3335. In particular, used when the parens are syntactically optional,
  3336. as opposed to required parens such as those enclosing an if-conditional."
  3337. expr) ; `js2-node'
  3338. (js2--struct-put 'js2-paren-node 'js2-visitor 'js2-visit-paren-node)
  3339. (js2--struct-put 'js2-paren-node 'js2-printer 'js2-print-paren-node)
  3340. (defun js2-visit-paren-node (n v)
  3341. (js2-visit-ast (js2-paren-node-expr n) v))
  3342. (defun js2-print-paren-node (n i)
  3343. (insert (js2-make-pad i))
  3344. (insert "(")
  3345. (js2-print-ast (js2-paren-node-expr n) 0)
  3346. (insert ")"))
  3347. (cl-defstruct (js2-comp-node
  3348. (:include js2-scope)
  3349. (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
  3350. (pos js2-ts-cursor)
  3351. len result
  3352. loops filters
  3353. form)))
  3354. "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
  3355. result ; result expression (just after left-bracket)
  3356. loops ; a Lisp list of `js2-comp-loop-node'
  3357. filters ; a Lisp list of guard/filter expressions
  3358. form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
  3359. ; SpiderMonkey also supports "legacy generator expressions", but we dont.
  3360. )
  3361. (js2--struct-put 'js2-comp-node 'js2-visitor 'js2-visit-comp-node)
  3362. (js2--struct-put 'js2-comp-node 'js2-printer 'js2-print-comp-node)
  3363. (defun js2-visit-comp-node (n v)
  3364. (js2-visit-ast (js2-comp-node-result n) v)
  3365. (dolist (l (js2-comp-node-loops n))
  3366. (js2-visit-ast l v))
  3367. (dolist (f (js2-comp-node-filters n))
  3368. (js2-visit-ast f v)))
  3369. (defun js2-print-comp-node (n i)
  3370. (let ((pad (js2-make-pad i))
  3371. (result (js2-comp-node-result n))
  3372. (loops (js2-comp-node-loops n))
  3373. (filters (js2-comp-node-filters n))
  3374. (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
  3375. (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
  3376. (insert pad (if gen-p "(" "["))
  3377. (when legacy-p
  3378. (js2-print-ast result 0))
  3379. (dolist (l loops)
  3380. (when legacy-p
  3381. (insert " "))
  3382. (js2-print-ast l 0)
  3383. (unless legacy-p
  3384. (insert " ")))
  3385. (dolist (f filters)
  3386. (when legacy-p
  3387. (insert " "))
  3388. (insert "if (")
  3389. (js2-print-ast f 0)
  3390. (insert ")")
  3391. (unless legacy-p
  3392. (insert " ")))
  3393. (unless legacy-p
  3394. (js2-print-ast result 0))
  3395. (insert (if gen-p ")" "]"))))
  3396. (cl-defstruct (js2-comp-loop-node
  3397. (:include js2-for-in-node)
  3398. (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
  3399. (pos js2-ts-cursor)
  3400. len iterator
  3401. object in-pos
  3402. foreach-p
  3403. each-pos
  3404. forof-p
  3405. lp rp)))
  3406. "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
  3407. (js2--struct-put 'js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
  3408. (js2--struct-put 'js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
  3409. (defun js2-visit-comp-loop (n v)
  3410. (js2-visit-ast (js2-comp-loop-node-iterator n) v)
  3411. (js2-visit-ast (js2-comp-loop-node-object n) v))
  3412. (defun js2-print-comp-loop (n _i)
  3413. (insert "for ")
  3414. (when (js2-comp-loop-node-foreach-p n) (insert "each "))
  3415. (insert "(")
  3416. (js2-print-ast (js2-comp-loop-node-iterator n) 0)
  3417. (insert (if (js2-comp-loop-node-forof-p n)
  3418. " of " " in "))
  3419. (js2-print-ast (js2-comp-loop-node-object n) 0)
  3420. (insert ")"))
  3421. (cl-defstruct (js2-empty-expr-node
  3422. (:include js2-node)
  3423. (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
  3424. (pos (js2-current-token-beg))
  3425. len)))
  3426. "AST node for an empty expression.")
  3427. (js2--struct-put 'js2-empty-expr-node 'js2-visitor 'js2-visit-none)
  3428. (js2--struct-put 'js2-empty-expr-node 'js2-printer 'js2-print-none)
  3429. (cl-defstruct (js2-xml-node
  3430. (:include js2-block-node)
  3431. (:constructor make-js2-xml-node (&key (type js2-XML)
  3432. (pos (js2-current-token-beg))
  3433. len kids)))
  3434. "AST node for initial parse of E4X literals.
  3435. The kids field is a list of XML fragments, each a `js2-string-node' or
  3436. a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
  3437. (js2--struct-put 'js2-xml-node 'js2-visitor 'js2-visit-block)
  3438. (js2--struct-put 'js2-xml-node 'js2-printer 'js2-print-xml-node)
  3439. (defun js2-print-xml-node (n i)
  3440. (dolist (kid (js2-xml-node-kids n))
  3441. (js2-print-ast kid i)))
  3442. (cl-defstruct (js2-xml-js-expr-node
  3443. (:include js2-xml-node)
  3444. (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
  3445. (pos js2-ts-cursor)
  3446. len expr)))
  3447. "AST node for an embedded JavaScript {expression} in an E4X literal.
  3448. The start and end fields correspond to the curly-braces."
  3449. expr) ; a `js2-expr-node' of some sort
  3450. (js2--struct-put 'js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
  3451. (js2--struct-put 'js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
  3452. (defun js2-visit-xml-js-expr (n v)
  3453. (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
  3454. (defun js2-print-xml-js-expr (n i)
  3455. (insert (js2-make-pad i))
  3456. (insert "{")
  3457. (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
  3458. (insert "}"))
  3459. (cl-defstruct (js2-xml-dot-query-node
  3460. (:include js2-infix-node)
  3461. (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
  3462. (pos js2-ts-cursor)
  3463. op-pos len left
  3464. right rp)))
  3465. "AST node for an E4X foo.(bar) filter expression.
  3466. Note that the left-paren is automatically the character immediately
  3467. following the dot (.) in the operator. No whitespace is permitted
  3468. between the dot and the lp by the scanner."
  3469. rp)
  3470. (js2--struct-put 'js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
  3471. (js2--struct-put 'js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
  3472. (defun js2-print-xml-dot-query (n i)
  3473. (insert (js2-make-pad i))
  3474. (js2-print-ast (js2-xml-dot-query-node-left n) 0)
  3475. (insert ".(")
  3476. (js2-print-ast (js2-xml-dot-query-node-right n) 0)
  3477. (insert ")"))
  3478. (cl-defstruct (js2-xml-ref-node
  3479. (:include js2-node)
  3480. (:constructor nil)) ; abstract
  3481. "Base type for E4X XML attribute-access or property-get expressions.
  3482. Such expressions can take a variety of forms. The general syntax has
  3483. three parts:
  3484. - (optional) an @ (specifying an attribute access)
  3485. - (optional) a namespace (a `js2-name-node') and double-colon
  3486. - (required) either a `js2-name-node' or a bracketed [expression]
  3487. The property-name expressions (examples: ns::name, @name) are
  3488. represented as `js2-xml-prop-ref' nodes. The bracketed-expression
  3489. versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
  3490. This node type (or more specifically, its subclasses) will sometimes
  3491. be the right-hand child of a `js2-prop-get-node' or a
  3492. `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
  3493. The `js2-xml-ref-node' may also be a standalone primary expression with
  3494. no explicit target, which is valid in certain expression contexts such as
  3495. company..employee.(@id < 100)
  3496. in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
  3497. expression whose parent is a `js2-xml-dot-query-node'."
  3498. namespace
  3499. at-pos
  3500. colon-pos)
  3501. (defsubst js2-xml-ref-node-attr-access-p (node)
  3502. "Return non-nil if this expression began with an @-token."
  3503. (and (numberp (js2-xml-ref-node-at-pos node))
  3504. (cl-plusp (js2-xml-ref-node-at-pos node))))
  3505. (cl-defstruct (js2-xml-prop-ref-node
  3506. (:include js2-xml-ref-node)
  3507. (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
  3508. (pos (js2-current-token-beg))
  3509. len propname
  3510. namespace at-pos
  3511. colon-pos)))
  3512. "AST node for an E4X XML [expr] property-ref expression.
  3513. The JavaScript syntax is an optional @, an optional ns::, and a name.
  3514. [ '@' ] [ name '::' ] name
  3515. Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
  3516. @ns::*, @*::attr, @*::*, and @*.
  3517. The node starts at the @ token, if present. Otherwise it starts at the
  3518. namespace name. The node bounds extend through the closing right-bracket,
  3519. or if it is missing due to a syntax error, through the end of the index
  3520. expression."
  3521. propname)
  3522. (js2--struct-put 'js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
  3523. (js2--struct-put 'js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
  3524. (defun js2-visit-xml-prop-ref-node (n v)
  3525. (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
  3526. (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
  3527. (defun js2-print-xml-prop-ref-node (n i)
  3528. (insert (js2-make-pad i))
  3529. (if (js2-xml-ref-node-attr-access-p n)
  3530. (insert "@"))
  3531. (when (js2-xml-prop-ref-node-namespace n)
  3532. (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
  3533. (insert "::"))
  3534. (if (js2-xml-prop-ref-node-propname n)
  3535. (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
  3536. (cl-defstruct (js2-xml-elem-ref-node
  3537. (:include js2-xml-ref-node)
  3538. (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
  3539. (pos (js2-current-token-beg))
  3540. len expr lb rb
  3541. namespace at-pos
  3542. colon-pos)))
  3543. "AST node for an E4X XML [expr] member-ref expression.
  3544. Syntax:
  3545. [ '@' ] [ name '::' ] '[' expr ']'
  3546. Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
  3547. Note that the form [expr] (i.e. no namespace or attribute-qualifier)
  3548. is not a legal E4X XML element-ref expression, since it's already used
  3549. for standard JavaScript element-get array indexing. Hence, a
  3550. `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
  3551. non-nil namespace node, or both.
  3552. The node starts at the @ token, if present. Otherwise it starts
  3553. at the namespace name. The node bounds extend through the closing
  3554. right-bracket, or if it is missing due to a syntax error, through the
  3555. end of the index expression."
  3556. expr ; the bracketed index expression
  3557. lb
  3558. rb)
  3559. (js2--struct-put 'js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
  3560. (js2--struct-put 'js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
  3561. (defun js2-visit-xml-elem-ref-node (n v)
  3562. (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
  3563. (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
  3564. (defun js2-print-xml-elem-ref-node (n i)
  3565. (insert (js2-make-pad i))
  3566. (if (js2-xml-ref-node-attr-access-p n)
  3567. (insert "@"))
  3568. (when (js2-xml-elem-ref-node-namespace n)
  3569. (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
  3570. (insert "::"))
  3571. (insert "[")
  3572. (if (js2-xml-elem-ref-node-expr n)
  3573. (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
  3574. (insert "]"))
  3575. ;;; Placeholder nodes for when we try parsing the XML literals structurally.
  3576. (cl-defstruct (js2-xml-start-tag-node
  3577. (:include js2-xml-node)
  3578. (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
  3579. (pos js2-ts-cursor)
  3580. len name attrs kids
  3581. empty-p)))
  3582. "AST node for an XML start-tag. Not currently used.
  3583. The `kids' field is a Lisp list of child content nodes."
  3584. name ; a `js2-xml-name-node'
  3585. attrs ; a Lisp list of `js2-xml-attr-node'
  3586. empty-p) ; t if this is an empty element such as <foo bar="baz"/>
  3587. (js2--struct-put 'js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
  3588. (js2--struct-put 'js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
  3589. (defun js2-visit-xml-start-tag (n v)
  3590. (js2-visit-ast (js2-xml-start-tag-node-name n) v)
  3591. (dolist (attr (js2-xml-start-tag-node-attrs n))
  3592. (js2-visit-ast attr v))
  3593. (js2-visit-block n v))
  3594. (defun js2-print-xml-start-tag (n i)
  3595. (insert (js2-make-pad i) "<")
  3596. (js2-print-ast (js2-xml-start-tag-node-name n) 0)
  3597. (when (js2-xml-start-tag-node-attrs n)
  3598. (insert " ")
  3599. (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
  3600. (insert ">"))
  3601. ;; I -think- I'm going to make the parent node the corresponding start-tag,
  3602. ;; and add the end-tag to the kids list of the parent as well.
  3603. (cl-defstruct (js2-xml-end-tag-node
  3604. (:include js2-xml-node)
  3605. (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
  3606. (pos js2-ts-cursor)
  3607. len name)))
  3608. "AST node for an XML end-tag. Not currently used."
  3609. name) ; a `js2-xml-name-node'
  3610. (js2--struct-put 'js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
  3611. (js2--struct-put 'js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
  3612. (defun js2-visit-xml-end-tag (n v)
  3613. (js2-visit-ast (js2-xml-end-tag-node-name n) v))
  3614. (defun js2-print-xml-end-tag (n i)
  3615. (insert (js2-make-pad i))
  3616. (insert "</")
  3617. (js2-print-ast (js2-xml-end-tag-node-name n) 0)
  3618. (insert ">"))
  3619. (cl-defstruct (js2-xml-name-node
  3620. (:include js2-xml-node)
  3621. (:constructor make-js2-xml-name-node (&key (type js2-XML)
  3622. (pos js2-ts-cursor)
  3623. len namespace kids)))
  3624. "AST node for an E4X XML name. Not currently used.
  3625. Any XML name can be qualified with a namespace, hence the namespace field.
  3626. Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
  3627. The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
  3628. For a simple name, the kids list has exactly one node, a `js2-name-node'."
  3629. namespace) ; a `js2-string-node'
  3630. (js2--struct-put 'js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
  3631. (js2--struct-put 'js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
  3632. (defun js2-visit-xml-name-node (n v)
  3633. (js2-visit-ast (js2-xml-name-node-namespace n) v))
  3634. (defun js2-print-xml-name-node (n i)
  3635. (insert (js2-make-pad i))
  3636. (when (js2-xml-name-node-namespace n)
  3637. (js2-print-ast (js2-xml-name-node-namespace n) 0)
  3638. (insert "::"))
  3639. (dolist (kid (js2-xml-name-node-kids n))
  3640. (js2-print-ast kid 0)))
  3641. (cl-defstruct (js2-xml-pi-node
  3642. (:include js2-xml-node)
  3643. (:constructor make-js2-xml-pi-node (&key (type js2-XML)
  3644. (pos js2-ts-cursor)
  3645. len name attrs)))
  3646. "AST node for an E4X XML processing instruction. Not currently used."
  3647. name ; a `js2-xml-name-node'
  3648. attrs) ; a list of `js2-xml-attr-node'
  3649. (js2--struct-put 'js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
  3650. (js2--struct-put 'js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
  3651. (defun js2-visit-xml-pi-node (n v)
  3652. (js2-visit-ast (js2-xml-pi-node-name n) v)
  3653. (dolist (attr (js2-xml-pi-node-attrs n))
  3654. (js2-visit-ast attr v)))
  3655. (defun js2-print-xml-pi-node (n i)
  3656. (insert (js2-make-pad i) "<?")
  3657. (js2-print-ast (js2-xml-pi-node-name n))
  3658. (when (js2-xml-pi-node-attrs n)
  3659. (insert " ")
  3660. (js2-print-list (js2-xml-pi-node-attrs n)))
  3661. (insert "?>"))
  3662. (cl-defstruct (js2-xml-cdata-node
  3663. (:include js2-xml-node)
  3664. (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
  3665. (pos js2-ts-cursor)
  3666. len content)))
  3667. "AST node for a CDATA escape section. Not currently used."
  3668. content) ; a `js2-string-node' with node-property 'quote-type 'cdata
  3669. (js2--struct-put 'js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
  3670. (js2--struct-put 'js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
  3671. (defun js2-visit-xml-cdata-node (n v)
  3672. (js2-visit-ast (js2-xml-cdata-node-content n) v))
  3673. (defun js2-print-xml-cdata-node (n i)
  3674. (insert (js2-make-pad i))
  3675. (js2-print-ast (js2-xml-cdata-node-content n)))
  3676. (cl-defstruct (js2-xml-attr-node
  3677. (:include js2-xml-node)
  3678. (:constructor make-js2-attr-node (&key (type js2-XML)
  3679. (pos js2-ts-cursor)
  3680. len name value
  3681. eq-pos quote-type)))
  3682. "AST node representing a foo='bar' XML attribute value. Not yet used."
  3683. name ; a `js2-xml-name-node'
  3684. value ; a `js2-xml-name-node'
  3685. eq-pos ; buffer position of "=" sign
  3686. quote-type) ; 'single or 'double
  3687. (js2--struct-put 'js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
  3688. (js2--struct-put 'js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
  3689. (defun js2-visit-xml-attr-node (n v)
  3690. (js2-visit-ast (js2-xml-attr-node-name n) v)
  3691. (js2-visit-ast (js2-xml-attr-node-value n) v))
  3692. (defun js2-print-xml-attr-node (n i)
  3693. (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
  3694. "'"
  3695. "\"")))
  3696. (insert (js2-make-pad i))
  3697. (js2-print-ast (js2-xml-attr-node-name n) 0)
  3698. (insert "=" quote)
  3699. (js2-print-ast (js2-xml-attr-node-value n) 0)
  3700. (insert quote)))
  3701. (cl-defstruct (js2-xml-text-node
  3702. (:include js2-xml-node)
  3703. (:constructor make-js2-text-node (&key (type js2-XML)
  3704. (pos js2-ts-cursor)
  3705. len content)))
  3706. "AST node for an E4X XML text node. Not currently used."
  3707. content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
  3708. (js2--struct-put 'js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
  3709. (js2--struct-put 'js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
  3710. (defun js2-visit-xml-text-node (n v)
  3711. (js2-visit-ast (js2-xml-text-node-content n) v))
  3712. (defun js2-print-xml-text-node (n i)
  3713. (insert (js2-make-pad i))
  3714. (dolist (kid (js2-xml-text-node-content n))
  3715. (js2-print-ast kid)))
  3716. (cl-defstruct (js2-xml-comment-node
  3717. (:include js2-xml-node)
  3718. (:constructor make-js2-xml-comment-node (&key (type js2-XML)
  3719. (pos js2-ts-cursor)
  3720. len)))
  3721. "AST node for E4X XML comment. Not currently used.")
  3722. (js2--struct-put 'js2-xml-comment-node 'js2-visitor 'js2-visit-none)
  3723. (js2--struct-put 'js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
  3724. (defun js2-print-xml-comment (n i)
  3725. (insert (js2-make-pad i)
  3726. (js2-node-string n)))
  3727. ;;; Node utilities
  3728. (defsubst js2-node-line (n)
  3729. "Fetch the source line number at the start of node N.
  3730. This is O(n) in the length of the source buffer; use prudently."
  3731. (1+ (count-lines (point-min) (js2-node-abs-pos n))))
  3732. (defsubst js2-block-node-kid (n i)
  3733. "Return child I of node N, or nil if there aren't that many."
  3734. (nth i (js2-block-node-kids n)))
  3735. (defsubst js2-block-node-first (n)
  3736. "Return first child of block node N, or nil if there is none."
  3737. (cl-first (js2-block-node-kids n)))
  3738. (defun js2-node-root (n)
  3739. "Return the root of the AST containing N.
  3740. If N has no parent pointer, returns N."
  3741. (let ((parent (js2-node-parent n)))
  3742. (if parent
  3743. (js2-node-root parent)
  3744. n)))
  3745. (defsubst js2-node-short-name (n)
  3746. "Return the short name of node N as a string, e.g. `js2-if-node'."
  3747. (let ((name (symbol-name (aref n 0))))
  3748. (if (string-prefix-p "cl-struct-" name)
  3749. (substring (symbol-name (aref n 0))
  3750. (length "cl-struct-"))
  3751. name)))
  3752. (defun js2-node-child-list (node)
  3753. "Return the child list for NODE, a Lisp list of nodes.
  3754. Works for block nodes, array nodes, obj literals, funarg lists,
  3755. var decls and try nodes (for catch clauses). Note that you should call
  3756. `js2-block-node-kids' on the function body for the body statements.
  3757. Returns nil for zero-length child lists or unsupported nodes."
  3758. (cond
  3759. ((js2-function-node-p node)
  3760. (js2-function-node-params node))
  3761. ((js2-block-node-p node)
  3762. (js2-block-node-kids node))
  3763. ((js2-try-node-p node)
  3764. (js2-try-node-catch-clauses node))
  3765. ((js2-array-node-p node)
  3766. (js2-array-node-elems node))
  3767. ((js2-object-node-p node)
  3768. (js2-object-node-elems node))
  3769. ((js2-call-node-p node)
  3770. (js2-call-node-args node))
  3771. ((js2-new-node-p node)
  3772. (js2-new-node-args node))
  3773. ((js2-var-decl-node-p node)
  3774. (js2-var-decl-node-kids node))
  3775. (t
  3776. nil)))
  3777. (defun js2-node-set-child-list (node kids)
  3778. "Set the child list for NODE to KIDS."
  3779. (cond
  3780. ((js2-function-node-p node)
  3781. (setf (js2-function-node-params node) kids))
  3782. ((js2-block-node-p node)
  3783. (setf (js2-block-node-kids node) kids))
  3784. ((js2-try-node-p node)
  3785. (setf (js2-try-node-catch-clauses node) kids))
  3786. ((js2-array-node-p node)
  3787. (setf (js2-array-node-elems node) kids))
  3788. ((js2-object-node-p node)
  3789. (setf (js2-object-node-elems node) kids))
  3790. ((js2-call-node-p node)
  3791. (setf (js2-call-node-args node) kids))
  3792. ((js2-new-node-p node)
  3793. (setf (js2-new-node-args node) kids))
  3794. ((js2-var-decl-node-p node)
  3795. (setf (js2-var-decl-node-kids node) kids))
  3796. (t
  3797. (error "Unsupported node type: %s" (js2-node-short-name node))))
  3798. kids)
  3799. ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
  3800. (defconst js2-paren-expr-nodes
  3801. '(cl-struct-js2-comp-loop-node
  3802. cl-struct-js2-comp-node
  3803. cl-struct-js2-call-node
  3804. cl-struct-js2-catch-node
  3805. cl-struct-js2-do-node
  3806. cl-struct-js2-elem-get-node
  3807. cl-struct-js2-for-in-node
  3808. cl-struct-js2-for-node
  3809. cl-struct-js2-function-node
  3810. cl-struct-js2-if-node
  3811. cl-struct-js2-let-node
  3812. cl-struct-js2-new-node
  3813. cl-struct-js2-paren-node
  3814. cl-struct-js2-switch-node
  3815. cl-struct-js2-while-node
  3816. cl-struct-js2-with-node
  3817. cl-struct-js2-xml-dot-query-node)
  3818. "Node types that can have a parenthesized child expression.
  3819. In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
  3820. (defsubst js2-paren-expr-node-p (node)
  3821. "Return t for nodes that typically have a parenthesized child expression.
  3822. Useful for computing the indentation anchors for arg-lists and conditions.
  3823. Note that it may return a false positive, for instance when NODE is
  3824. a `js2-new-node' and there are no arguments or parentheses."
  3825. (memq (aref node 0) js2-paren-expr-nodes))
  3826. ;; Fake polymorphism... yech.
  3827. (defun js2-node-lp (node)
  3828. "Return relative left-paren position for NODE, if applicable.
  3829. For `js2-elem-get-node' structs, returns left-bracket position.
  3830. Note that the position may be nil in the case of a parse error."
  3831. (cond
  3832. ((js2-elem-get-node-p node)
  3833. (js2-elem-get-node-lb node))
  3834. ((js2-loop-node-p node)
  3835. (js2-loop-node-lp node))
  3836. ((js2-function-node-p node)
  3837. (js2-function-node-lp node))
  3838. ((js2-if-node-p node)
  3839. (js2-if-node-lp node))
  3840. ((js2-new-node-p node)
  3841. (js2-new-node-lp node))
  3842. ((js2-call-node-p node)
  3843. (js2-call-node-lp node))
  3844. ((js2-paren-node-p node)
  3845. 0)
  3846. ((js2-switch-node-p node)
  3847. (js2-switch-node-lp node))
  3848. ((js2-catch-node-p node)
  3849. (js2-catch-node-lp node))
  3850. ((js2-let-node-p node)
  3851. (js2-let-node-lp node))
  3852. ((js2-comp-node-p node)
  3853. 0)
  3854. ((js2-with-node-p node)
  3855. (js2-with-node-lp node))
  3856. ((js2-xml-dot-query-node-p node)
  3857. (1+ (js2-infix-node-op-pos node)))
  3858. (t
  3859. (error "Unsupported node type: %s" (js2-node-short-name node)))))
  3860. ;; Fake polymorphism... blech.
  3861. (defun js2-node-rp (node)
  3862. "Return relative right-paren position for NODE, if applicable.
  3863. For `js2-elem-get-node' structs, returns right-bracket position.
  3864. Note that the position may be nil in the case of a parse error."
  3865. (cond
  3866. ((js2-elem-get-node-p node)
  3867. (js2-elem-get-node-rb node))
  3868. ((js2-loop-node-p node)
  3869. (js2-loop-node-rp node))
  3870. ((js2-function-node-p node)
  3871. (js2-function-node-rp node))
  3872. ((js2-if-node-p node)
  3873. (js2-if-node-rp node))
  3874. ((js2-new-node-p node)
  3875. (js2-new-node-rp node))
  3876. ((js2-call-node-p node)
  3877. (js2-call-node-rp node))
  3878. ((js2-paren-node-p node)
  3879. (1- (js2-node-len node)))
  3880. ((js2-switch-node-p node)
  3881. (js2-switch-node-rp node))
  3882. ((js2-catch-node-p node)
  3883. (js2-catch-node-rp node))
  3884. ((js2-let-node-p node)
  3885. (js2-let-node-rp node))
  3886. ((js2-comp-node-p node)
  3887. (1- (js2-node-len node)))
  3888. ((js2-with-node-p node)
  3889. (js2-with-node-rp node))
  3890. ((js2-xml-dot-query-node-p node)
  3891. (1+ (js2-xml-dot-query-node-rp node)))
  3892. (t
  3893. (error "Unsupported node type: %s" (js2-node-short-name node)))))
  3894. (defsubst js2-node-first-child (node)
  3895. "Return the first element of `js2-node-child-list' for NODE."
  3896. (car (js2-node-child-list node)))
  3897. (defsubst js2-node-last-child (node)
  3898. "Return the last element of `js2-node-last-child' for NODE."
  3899. (car (last (js2-node-child-list node))))
  3900. (defun js2-node-prev-sibling (node)
  3901. "Return the previous statement in parent.
  3902. Works for parents supported by `js2-node-child-list'.
  3903. Returns nil if NODE is not in the parent, or PARENT is
  3904. not a supported node, or if NODE is the first child."
  3905. (let* ((p (js2-node-parent node))
  3906. (kids (js2-node-child-list p))
  3907. (sib (car kids)))
  3908. (while (and kids
  3909. (not (eq node (cadr kids))))
  3910. (setq kids (cdr kids)
  3911. sib (car kids)))
  3912. sib))
  3913. (defun js2-node-next-sibling (node)
  3914. "Return the next statement in parent block.
  3915. Returns nil if NODE is not in the block, or PARENT is not
  3916. a block node, or if NODE is the last statement."
  3917. (let* ((p (js2-node-parent node))
  3918. (kids (js2-node-child-list p)))
  3919. (while (and kids
  3920. (not (eq node (car kids))))
  3921. (setq kids (cdr kids)))
  3922. (cadr kids)))
  3923. (defun js2-node-find-child-before (pos parent &optional after)
  3924. "Find the last child that starts before POS in parent.
  3925. If AFTER is non-nil, returns first child starting after POS.
  3926. POS is an absolute buffer position. PARENT is any node
  3927. supported by `js2-node-child-list'.
  3928. Returns nil if no applicable child is found."
  3929. (let ((kids (if (js2-function-node-p parent)
  3930. (js2-block-node-kids (js2-function-node-body parent))
  3931. (js2-node-child-list parent)))
  3932. (beg (js2-node-abs-pos (if (js2-function-node-p parent)
  3933. (js2-function-node-body parent)
  3934. parent)))
  3935. kid result fn
  3936. (continue t))
  3937. (setq fn (if after '>= '<))
  3938. (while (and kids continue)
  3939. (setq kid (car kids))
  3940. (if (funcall fn (+ beg (js2-node-pos kid)) pos)
  3941. (setq result kid
  3942. continue (not after))
  3943. (setq continue after))
  3944. (setq kids (cdr kids)))
  3945. result))
  3946. (defun js2-node-find-child-after (pos parent)
  3947. "Find first child that starts after POS in parent.
  3948. POS is an absolute buffer position. PARENT is any node
  3949. supported by `js2-node-child-list'.
  3950. Returns nil if no applicable child is found."
  3951. (js2-node-find-child-before pos parent 'after))
  3952. (defun js2-node-replace-child (pos parent new-node)
  3953. "Replace node at index POS in PARENT with NEW-NODE.
  3954. Only works for parents supported by `js2-node-child-list'."
  3955. (let ((kids (js2-node-child-list parent))
  3956. (i 0))
  3957. (while (< i pos)
  3958. (setq kids (cdr kids)
  3959. i (1+ i)))
  3960. (setcar kids new-node)
  3961. (js2-node-add-children parent new-node)))
  3962. (defun js2-node-buffer (n)
  3963. "Return the buffer associated with AST N.
  3964. Returns nil if the buffer is not set as a property on the root
  3965. node, or if parent links were not recorded during parsing."
  3966. (let ((root (js2-node-root n)))
  3967. (and root
  3968. (js2-ast-root-p root)
  3969. (js2-ast-root-buffer root))))
  3970. (defun js2-block-node-push (n kid)
  3971. "Push js2-node KID onto the end of js2-block-node N's child list.
  3972. KID is always added to the -end- of the kids list.
  3973. Function also calls `js2-node-add-children' to add the parent link."
  3974. (let ((kids (js2-node-child-list n)))
  3975. (if kids
  3976. (setcdr kids (nconc (cdr kids) (list kid)))
  3977. (js2-node-set-child-list n (list kid)))
  3978. (js2-node-add-children n kid)))
  3979. (defun js2-node-string (node)
  3980. (with-current-buffer (or (js2-node-buffer node)
  3981. (error "No buffer available for node %s" node))
  3982. (let ((pos (js2-node-abs-pos node)))
  3983. (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
  3984. ;; Container for storing the node we're looking for in a traversal.
  3985. (js2-deflocal js2-discovered-node nil)
  3986. ;; Keep track of absolute node position during traversals.
  3987. (js2-deflocal js2-visitor-offset nil)
  3988. (js2-deflocal js2-node-search-point nil)
  3989. (when js2-mode-dev-mode-p
  3990. (defun js2-find-node-at-point ()
  3991. (interactive)
  3992. (let ((node (js2-node-at-point)))
  3993. (message "%s" (or node "No node found at point"))))
  3994. (defun js2-node-name-at-point ()
  3995. (interactive)
  3996. (let ((node (js2-node-at-point)))
  3997. (message "%s" (if node
  3998. (js2-node-short-name node)
  3999. "No node found at point.")))))
  4000. (defun js2-node-at-point (&optional pos skip-comments)
  4001. "Return AST node at POS, a buffer position, defaulting to current point.
  4002. The `js2-mode-ast' variable must be set to the current parse tree.
  4003. Signals an error if the AST (`js2-mode-ast') is nil.
  4004. Always returns a node - if it can't find one, it returns the root.
  4005. If SKIP-COMMENTS is non-nil, comment nodes are ignored."
  4006. (let ((ast js2-mode-ast)
  4007. result)
  4008. (unless ast
  4009. (error "No JavaScript AST available"))
  4010. ;; Look through comments first, since they may be inside nodes that
  4011. ;; would otherwise report a match.
  4012. (setq pos (or pos (point))
  4013. result (if (> pos (js2-node-abs-end ast))
  4014. ast
  4015. (if (not skip-comments)
  4016. (js2-comment-at-point pos))))
  4017. (unless result
  4018. (setq js2-discovered-node nil
  4019. js2-visitor-offset 0
  4020. js2-node-search-point pos)
  4021. (unwind-protect
  4022. (catch 'js2-visit-done
  4023. (js2-visit-ast ast #'js2-node-at-point-visitor))
  4024. (setq js2-visitor-offset nil
  4025. js2-node-search-point nil))
  4026. (setq result js2-discovered-node))
  4027. ;; may have found a comment beyond end of last child node,
  4028. ;; since visiting the ast-root looks at the comment-list last.
  4029. (if (and skip-comments
  4030. (js2-comment-node-p result))
  4031. (setq result nil))
  4032. (or result js2-mode-ast)))
  4033. (defun js2-node-at-point-visitor (node end-p)
  4034. (let ((rel-pos (js2-node-pos node))
  4035. abs-pos
  4036. abs-end
  4037. (point js2-node-search-point))
  4038. (cond
  4039. (end-p
  4040. ;; this evaluates to a non-nil return value, even if it's zero
  4041. (cl-decf js2-visitor-offset rel-pos))
  4042. ;; we already looked for comments before visiting, and don't want them now
  4043. ((js2-comment-node-p node)
  4044. nil)
  4045. (t
  4046. (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
  4047. ;; we only want to use the node if the point is before
  4048. ;; the last character position in the node, so we decrement
  4049. ;; the absolute end by 1.
  4050. abs-end (+ abs-pos (js2-node-len node) -1))
  4051. (cond
  4052. ;; If this node starts after search-point, stop the search.
  4053. ((> abs-pos point)
  4054. (throw 'js2-visit-done nil))
  4055. ;; If this node ends before the search-point, don't check kids.
  4056. ((> point abs-end)
  4057. nil)
  4058. (t
  4059. ;; Otherwise point is within this node, possibly in a child.
  4060. (setq js2-discovered-node node)
  4061. t)))))) ; keep processing kids to look for more specific match
  4062. (defsubst js2-block-comment-p (node)
  4063. "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
  4064. (and (js2-comment-node-p node)
  4065. (memq (js2-comment-node-format node) '(jsdoc block))))
  4066. ;; TODO: put the comments in a vector and binary-search them instead
  4067. (defun js2-comment-at-point (&optional pos)
  4068. "Look through scanned comment nodes for one containing POS.
  4069. POS is a buffer position that defaults to current point.
  4070. Function returns nil if POS was not in any comment node."
  4071. (let ((ast js2-mode-ast)
  4072. (x (or pos (point)))
  4073. beg end)
  4074. (unless ast
  4075. (error "No JavaScript AST available"))
  4076. (catch 'done
  4077. ;; Comments are stored in lexical order.
  4078. (dolist (comment (js2-ast-root-comments ast) nil)
  4079. (setq beg (js2-node-abs-pos comment)
  4080. end (+ beg (js2-node-len comment)))
  4081. (if (and (>= x beg)
  4082. (<= x end))
  4083. (throw 'done comment))))))
  4084. (defun js2-comments-between (start end comments-list)
  4085. "Return comment nodes between START and END, nil if not found.
  4086. START and END are absolute positions in current buffer.
  4087. COMMENTS-LIST is the comments list to check."
  4088. (let (comments c-start c-end)
  4089. (nreverse
  4090. (dolist (comment comments-list comments)
  4091. (setq c-start (js2-node-abs-pos comment)
  4092. c-end (1- (+ c-start (js2-node-len comment))))
  4093. (unless (or (< c-end start)
  4094. (> c-start end))
  4095. (push comment comments))))))
  4096. (defun js2-mode-find-parent-fn (node)
  4097. "Find function enclosing NODE.
  4098. Returns nil if NODE is not inside a function."
  4099. (setq node (js2-node-parent node))
  4100. (while (and node (not (js2-function-node-p node)))
  4101. (setq node (js2-node-parent node)))
  4102. (and (js2-function-node-p node) node))
  4103. (defun js2-mode-find-enclosing-fn (node)
  4104. "Find function or root enclosing NODE."
  4105. (if (js2-ast-root-p node)
  4106. node
  4107. (setq node (js2-node-parent node))
  4108. (while (not (or (js2-ast-root-p node)
  4109. (js2-function-node-p node)))
  4110. (setq node (js2-node-parent node)))
  4111. node))
  4112. (defun js2-mode-find-enclosing-node (beg end)
  4113. "Find node fully enclosing BEG and END."
  4114. (let ((node (js2-node-at-point beg))
  4115. pos
  4116. (continue t))
  4117. (while continue
  4118. (if (or (js2-ast-root-p node)
  4119. (and
  4120. (<= (setq pos (js2-node-abs-pos node)) beg)
  4121. (>= (+ pos (js2-node-len node)) end)))
  4122. (setq continue nil)
  4123. (setq node (js2-node-parent node))))
  4124. node))
  4125. (defun js2-node-parent-script-or-fn (node)
  4126. "Find script or function immediately enclosing NODE.
  4127. If NODE is the ast-root, returns nil."
  4128. (if (js2-ast-root-p node)
  4129. nil
  4130. (setq node (js2-node-parent node))
  4131. (while (and node (not (or (js2-function-node-p node)
  4132. (js2-script-node-p node))))
  4133. (setq node (js2-node-parent node)))
  4134. node))
  4135. (defun js2-node-is-descendant (node ancestor)
  4136. "Return t if NODE is a descendant of ANCESTOR."
  4137. (while (and node
  4138. (not (eq node ancestor)))
  4139. (setq node (js2-node-parent node)))
  4140. node)
  4141. ;;; visitor infrastructure
  4142. (defun js2-visit-none (_node _callback)
  4143. "Visitor for AST node that have no node children."
  4144. nil)
  4145. (defun js2-print-none (_node _indent)
  4146. "Visitor for AST node with no printed representation.")
  4147. (defun js2-print-body (node indent)
  4148. "Print a statement, or a block without braces."
  4149. (if (js2-block-node-p node)
  4150. (dolist (kid (js2-block-node-kids node))
  4151. (js2-print-ast kid indent))
  4152. (js2-print-ast node indent)))
  4153. (defun js2-print-list (args &optional delimiter)
  4154. (cl-loop with len = (length args)
  4155. for arg in args
  4156. for count from 1
  4157. do
  4158. (when arg (js2-print-ast arg 0))
  4159. (if (< count len)
  4160. (insert (or delimiter ", ")))))
  4161. (defun js2-print-tree (ast)
  4162. "Prints an AST to the current buffer.
  4163. Makes `js2-ast-parent-nodes' available to the printer functions."
  4164. (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
  4165. (js2-print-ast ast)))
  4166. (defun js2-print-ast (node &optional indent)
  4167. "Helper function for printing AST nodes.
  4168. Requires `js2-ast-parent-nodes' to be non-nil.
  4169. You should use `js2-print-tree' instead of this function."
  4170. (let ((printer (get (aref node 0) 'js2-printer))
  4171. (i (or indent 0)))
  4172. ;; TODO: wedge comments in here somewhere
  4173. (if printer
  4174. (funcall printer node i))))
  4175. (defconst js2-side-effecting-tokens
  4176. (let ((tokens (make-bool-vector js2-num-tokens nil)))
  4177. (dolist (tt (list js2-ASSIGN
  4178. js2-ASSIGN_ADD
  4179. js2-ASSIGN_BITAND
  4180. js2-ASSIGN_BITOR
  4181. js2-ASSIGN_BITXOR
  4182. js2-ASSIGN_DIV
  4183. js2-ASSIGN_LSH
  4184. js2-ASSIGN_MOD
  4185. js2-ASSIGN_MUL
  4186. js2-ASSIGN_RSH
  4187. js2-ASSIGN_SUB
  4188. js2-ASSIGN_URSH
  4189. js2-ASSIGN_EXPON
  4190. js2-BLOCK
  4191. js2-BREAK
  4192. js2-CALL
  4193. js2-CATCH
  4194. js2-CATCH_SCOPE
  4195. js2-CLASS
  4196. js2-CONST
  4197. js2-CONTINUE
  4198. js2-DEBUGGER
  4199. js2-DEC
  4200. js2-DELPROP
  4201. js2-DEL_REF
  4202. js2-DO
  4203. js2-ELSE
  4204. js2-EMPTY
  4205. js2-ENTERWITH
  4206. js2-EXPORT
  4207. js2-EXPR_RESULT
  4208. js2-FINALLY
  4209. js2-FOR
  4210. js2-FUNCTION
  4211. js2-GOTO
  4212. js2-IF
  4213. js2-IFEQ
  4214. js2-IFNE
  4215. js2-IMPORT
  4216. js2-INC
  4217. js2-JSR
  4218. js2-LABEL
  4219. js2-LEAVEWITH
  4220. js2-LET
  4221. js2-LETEXPR
  4222. js2-LOCAL_BLOCK
  4223. js2-LOOP
  4224. js2-NEW
  4225. js2-REF_CALL
  4226. js2-RETHROW
  4227. js2-RETURN
  4228. js2-RETURN_RESULT
  4229. js2-SEMI
  4230. js2-SETELEM
  4231. js2-SETELEM_OP
  4232. js2-SETNAME
  4233. js2-SETPROP
  4234. js2-SETPROP_OP
  4235. js2-SETVAR
  4236. js2-SET_REF
  4237. js2-SET_REF_OP
  4238. js2-SWITCH
  4239. js2-TARGET
  4240. js2-THROW
  4241. js2-TRY
  4242. js2-VAR
  4243. js2-WHILE
  4244. js2-WITH
  4245. js2-WITHEXPR
  4246. js2-YIELD))
  4247. (aset tokens tt t))
  4248. tokens))
  4249. (defun js2-node-has-side-effects (node)
  4250. "Return t if NODE has side effects."
  4251. (when node ; makes it easier to handle malformed expressions
  4252. (let ((tt (js2-node-type node)))
  4253. (cond
  4254. ;; This doubtless needs some work, since EXPR_VOID is used
  4255. ;; in several ways in Rhino and I may not have caught them all.
  4256. ;; I'll wait for people to notice incorrect warnings.
  4257. ((and (= tt js2-EXPR_VOID)
  4258. (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
  4259. (let ((expr (js2-expr-stmt-node-expr node)))
  4260. (or (js2-node-has-side-effects expr)
  4261. (when (js2-string-node-p expr)
  4262. (member (js2-string-node-value expr) '("use strict" "use asm"))))))
  4263. ((= tt js2-AWAIT) t)
  4264. ((= tt js2-COMMA)
  4265. (js2-node-has-side-effects (js2-infix-node-right node)))
  4266. ((or (= tt js2-AND)
  4267. (= tt js2-OR))
  4268. (or (js2-node-has-side-effects (js2-infix-node-right node))
  4269. (js2-node-has-side-effects (js2-infix-node-left node))))
  4270. ((= tt js2-HOOK)
  4271. (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
  4272. (js2-node-has-side-effects (js2-cond-node-false-expr node))))
  4273. ((js2-paren-node-p node)
  4274. (js2-node-has-side-effects (js2-paren-node-expr node)))
  4275. ((= tt js2-ERROR) ; avoid cascaded error messages
  4276. nil)
  4277. ((or (and js2-instanceof-has-side-effects (= tt js2-INSTANCEOF))
  4278. (and js2-getprop-has-side-effects (= tt js2-GETPROP)))
  4279. t)
  4280. (t
  4281. (aref js2-side-effecting-tokens tt))))))
  4282. (defconst js2-stmt-node-types
  4283. (list js2-BLOCK
  4284. js2-BREAK
  4285. js2-CONTINUE
  4286. js2-DEFAULT ; e4x "default xml namespace" statement
  4287. js2-DO
  4288. js2-EXPORT
  4289. js2-EXPR_RESULT
  4290. js2-EXPR_VOID
  4291. js2-FOR
  4292. js2-IF
  4293. js2-IMPORT
  4294. js2-RETURN
  4295. js2-SWITCH
  4296. js2-THROW
  4297. js2-TRY
  4298. js2-WHILE
  4299. js2-WITH)
  4300. "Node types that only appear in statement contexts.
  4301. The list does not include nodes that always appear as the child
  4302. of another specific statement type, such as switch-cases,
  4303. catch and finally blocks, and else-clauses. The list also excludes
  4304. nodes like yield, let and var, which may appear in either expression
  4305. or statement context, and in the latter context always have a
  4306. `js2-expr-stmt-node' parent. Finally, the list does not include
  4307. functions or scripts, which are treated separately from statements
  4308. by the JavaScript parser and runtime.")
  4309. (defun js2-stmt-node-p (node)
  4310. "Heuristic for figuring out if NODE is a statement.
  4311. Some node types can appear in either an expression context or a
  4312. statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
  4313. For these node types in a statement context, the parent will be a
  4314. `js2-expr-stmt-node'.
  4315. Functions aren't included in the check."
  4316. (memq (js2-node-type node) js2-stmt-node-types))
  4317. (defun js2-mode-find-first-stmt (node)
  4318. "Search upward starting from NODE looking for a statement.
  4319. For purposes of this function, a `js2-function-node' counts."
  4320. (while (not (or (js2-stmt-node-p node)
  4321. (js2-function-node-p node)))
  4322. (setq node (js2-node-parent node)))
  4323. node)
  4324. (defun js2-node-parent-stmt (node)
  4325. "Return the node's first ancestor that is a statement.
  4326. Returns nil if NODE is a `js2-ast-root'. Note that any expression
  4327. appearing in a statement context will have a parent that is a
  4328. `js2-expr-stmt-node' that will be returned by this function."
  4329. (let ((parent (js2-node-parent node)))
  4330. (if (or (null parent)
  4331. (js2-stmt-node-p parent)
  4332. (and (js2-function-node-p parent)
  4333. (eq (js2-function-node-form parent) 'FUNCTION_STATEMENT)))
  4334. parent
  4335. (js2-node-parent-stmt parent))))
  4336. ;; In the Mozilla Rhino sources, Roshan James writes:
  4337. ;; Does consistent-return analysis on the function body when strict mode is
  4338. ;; enabled.
  4339. ;;
  4340. ;; function (x) { return (x+1) }
  4341. ;;
  4342. ;; is ok, but
  4343. ;;
  4344. ;; function (x) { if (x < 0) return (x+1); }
  4345. ;;
  4346. ;; is not because the function can potentially return a value when the
  4347. ;; condition is satisfied and if not, the function does not explicitly
  4348. ;; return a value.
  4349. ;;
  4350. ;; This extends to checking mismatches such as "return" and "return <value>"
  4351. ;; used in the same function. Warnings are not emitted if inconsistent
  4352. ;; returns exist in code that can be statically shown to be unreachable.
  4353. ;; Ex.
  4354. ;; function (x) { while (true) { ... if (..) { return value } ... } }
  4355. ;;
  4356. ;; emits no warning. However if the loop had a break statement, then a
  4357. ;; warning would be emitted.
  4358. ;;
  4359. ;; The consistency analysis looks at control structures such as loops, ifs,
  4360. ;; switch, try-catch-finally blocks, examines the reachable code paths and
  4361. ;; warns the user about an inconsistent set of termination possibilities.
  4362. ;;
  4363. ;; These flags enumerate the possible ways a statement/function can
  4364. ;; terminate. These flags are used by endCheck() and by the Parser to
  4365. ;; detect inconsistent return usage.
  4366. ;;
  4367. ;; END_UNREACHED is reserved for code paths that are assumed to always be
  4368. ;; able to execute (example: throw, continue)
  4369. ;;
  4370. ;; END_DROPS_OFF indicates if the statement can transfer control to the
  4371. ;; next one. Statement such as return dont. A compound statement may have
  4372. ;; some branch that drops off control to the next statement.
  4373. ;;
  4374. ;; END_RETURNS indicates that the statement can return with no value.
  4375. ;; END_RETURNS_VALUE indicates that the statement can return a value.
  4376. ;;
  4377. ;; A compound statement such as
  4378. ;; if (condition) {
  4379. ;; return value;
  4380. ;; }
  4381. ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
  4382. (defconst js2-END_UNREACHED 0)
  4383. (defconst js2-END_DROPS_OFF 1)
  4384. (defconst js2-END_RETURNS 2)
  4385. (defconst js2-END_RETURNS_VALUE 4)
  4386. (defconst js2-END_YIELDS 8)
  4387. (defun js2-has-consistent-return-usage (node)
  4388. "Check that every return usage in a function body is consistent.
  4389. Returns t if the function satisfies strict mode requirement."
  4390. (let ((n (js2-end-check node)))
  4391. ;; either it doesn't return a value in any branch...
  4392. (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
  4393. ;; or it returns a value (or is unreached) at every branch
  4394. (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
  4395. js2-END_RETURNS
  4396. js2-END_YIELDS)))))
  4397. (defun js2-end-check-if (node)
  4398. "Ensure that return usage in then/else blocks is consistent.
  4399. If there is no else block, then the return statement can fall through.
  4400. Returns logical OR of END_* flags"
  4401. (let ((th (js2-if-node-then-part node))
  4402. (el (js2-if-node-else-part node)))
  4403. (if (null th)
  4404. js2-END_UNREACHED
  4405. (logior (js2-end-check th) (if el
  4406. (js2-end-check el)
  4407. js2-END_DROPS_OFF)))))
  4408. (defun js2-end-check-switch (node)
  4409. "Consistency of return statements is checked between the case statements.
  4410. If there is no default, then the switch can fall through. If there is a
  4411. default, we check to see if all code paths in the default return or if
  4412. there is a code path that can fall through.
  4413. Returns logical OR of END_* flags."
  4414. (let ((rv js2-END_UNREACHED)
  4415. default-case)
  4416. ;; examine the cases
  4417. (catch 'break
  4418. (dolist (c (js2-switch-node-cases node))
  4419. (if (js2-case-node-expr c)
  4420. (js2-set-flag rv (js2-end-check-block c))
  4421. (setq default-case c)
  4422. (throw 'break nil))))
  4423. ;; we don't care how the cases drop into each other
  4424. (js2-clear-flag rv js2-END_DROPS_OFF)
  4425. ;; examine the default
  4426. (js2-set-flag rv (if default-case
  4427. (js2-end-check default-case)
  4428. js2-END_DROPS_OFF))
  4429. rv))
  4430. (defun js2-end-check-try (node)
  4431. "If the block has a finally, return consistency is checked in the
  4432. finally block. If all code paths in the finally return, then the
  4433. returns in the try-catch blocks don't matter. If there is a code path
  4434. that does not return or if there is no finally block, the returns
  4435. of the try and catch blocks are checked for mismatch.
  4436. Returns logical OR of END_* flags."
  4437. (let ((finally (js2-try-node-finally-block node))
  4438. rv)
  4439. ;; check the finally if it exists
  4440. (setq rv (if finally
  4441. (js2-end-check (js2-finally-node-body finally))
  4442. js2-END_DROPS_OFF))
  4443. ;; If the finally block always returns, then none of the returns
  4444. ;; in the try or catch blocks matter.
  4445. (when (js2-flag-set-p rv js2-END_DROPS_OFF)
  4446. (js2-clear-flag rv js2-END_DROPS_OFF)
  4447. ;; examine the try block
  4448. (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
  4449. ;; check each catch block
  4450. (dolist (cb (js2-try-node-catch-clauses node))
  4451. (js2-set-flag rv (js2-end-check cb))))
  4452. rv))
  4453. (defun js2-end-check-loop (node)
  4454. "Return statement in the loop body must be consistent.
  4455. The default assumption for any kind of a loop is that it will eventually
  4456. terminate. The only exception is a loop with a constant true condition.
  4457. Code that follows such a loop is examined only if one can determine
  4458. statically that there is a break out of the loop.
  4459. for(... ; ... ; ...) {}
  4460. for(... in ... ) {}
  4461. while(...) { }
  4462. do { } while(...)
  4463. Returns logical OR of END_* flags."
  4464. (let ((rv (js2-end-check (js2-loop-node-body node)))
  4465. (condition (cond
  4466. ((js2-while-node-p node)
  4467. (js2-while-node-condition node))
  4468. ((js2-do-node-p node)
  4469. (js2-do-node-condition node))
  4470. ((js2-for-node-p node)
  4471. (js2-for-node-condition node)))))
  4472. ;; check to see if the loop condition is always true
  4473. (if (and condition
  4474. (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
  4475. (js2-clear-flag rv js2-END_DROPS_OFF))
  4476. ;; look for effect of breaks
  4477. (js2-set-flag rv (js2-node-get-prop node
  4478. 'CONTROL_BLOCK_PROP
  4479. js2-END_UNREACHED))
  4480. rv))
  4481. (defun js2-end-check-block (node)
  4482. "A general block of code is examined statement by statement.
  4483. If any statement (even a compound one) returns in all branches, then
  4484. subsequent statements are not examined.
  4485. Returns logical OR of END_* flags."
  4486. (let* ((rv js2-END_DROPS_OFF)
  4487. (kids (js2-block-node-kids node))
  4488. (n (car kids)))
  4489. ;; Check each statement. If the statement can continue onto the next
  4490. ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
  4491. (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
  4492. (js2-clear-flag rv js2-END_DROPS_OFF)
  4493. (js2-set-flag rv (js2-end-check n))
  4494. (setq kids (cdr kids)
  4495. n (car kids)))
  4496. rv))
  4497. (defun js2-end-check-label (node)
  4498. "A labeled statement implies that there may be a break to the label.
  4499. The function processes the labeled statement and then checks the
  4500. CONTROL_BLOCK_PROP property to see if there is ever a break to the
  4501. particular label.
  4502. Returns logical OR of END_* flags."
  4503. (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
  4504. (logior rv (js2-node-get-prop node
  4505. 'CONTROL_BLOCK_PROP
  4506. js2-END_UNREACHED))))
  4507. (defun js2-end-check-break (node)
  4508. "When a break is encountered annotate the statement being broken
  4509. out of by setting its CONTROL_BLOCK_PROP property.
  4510. Returns logical OR of END_* flags."
  4511. (and (js2-break-node-target node)
  4512. (js2-node-set-prop (js2-break-node-target node)
  4513. 'CONTROL_BLOCK_PROP
  4514. js2-END_DROPS_OFF))
  4515. js2-END_UNREACHED)
  4516. (defun js2-end-check (node)
  4517. "Examine the body of a function, doing a basic reachability analysis.
  4518. Returns a combination of flags END_* flags that indicate
  4519. how the function execution can terminate. These constitute only the
  4520. pessimistic set of termination conditions. It is possible that at
  4521. runtime certain code paths will never be actually taken. Hence this
  4522. analysis will flag errors in cases where there may not be errors.
  4523. Returns logical OR of END_* flags"
  4524. (let (kid)
  4525. (cond
  4526. ((js2-break-node-p node)
  4527. (js2-end-check-break node))
  4528. ((js2-expr-stmt-node-p node)
  4529. (if (setq kid (js2-expr-stmt-node-expr node))
  4530. (js2-end-check kid)
  4531. js2-END_DROPS_OFF))
  4532. ((or (js2-continue-node-p node)
  4533. (js2-throw-node-p node))
  4534. js2-END_UNREACHED)
  4535. ((js2-return-node-p node)
  4536. (if (setq kid (js2-return-node-retval node))
  4537. js2-END_RETURNS_VALUE
  4538. js2-END_RETURNS))
  4539. ((js2-loop-node-p node)
  4540. (js2-end-check-loop node))
  4541. ((js2-switch-node-p node)
  4542. (js2-end-check-switch node))
  4543. ((js2-labeled-stmt-node-p node)
  4544. (js2-end-check-label node))
  4545. ((js2-if-node-p node)
  4546. (js2-end-check-if node))
  4547. ((js2-try-node-p node)
  4548. (js2-end-check-try node))
  4549. ((js2-block-node-p node)
  4550. (if (null (js2-block-node-kids node))
  4551. js2-END_DROPS_OFF
  4552. (js2-end-check-block node)))
  4553. ((js2-yield-node-p node)
  4554. js2-END_YIELDS)
  4555. (t
  4556. js2-END_DROPS_OFF))))
  4557. (defun js2-always-defined-boolean-p (node)
  4558. "Check if NODE always evaluates to true or false in boolean context.
  4559. Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
  4560. nor always false."
  4561. (let ((tt (js2-node-type node))
  4562. num)
  4563. (cond
  4564. ((or (= tt js2-FALSE) (= tt js2-NULL))
  4565. 'ALWAYS_FALSE)
  4566. ((= tt js2-TRUE)
  4567. 'ALWAYS_TRUE)
  4568. ((= tt js2-NUMBER)
  4569. (setq num (js2-number-node-num-value node))
  4570. (if (and (not (eq num 0.0e+NaN))
  4571. (not (zerop num)))
  4572. 'ALWAYS_TRUE
  4573. 'ALWAYS_FALSE))
  4574. (t
  4575. nil))))
  4576. ;;; Scanner -- a port of Mozilla Rhino's lexer.
  4577. ;; Corresponds to Rhino files Token.java and TokenStream.java.
  4578. (defvar js2-tokens nil
  4579. "List of all defined token names.") ; initialized in `js2-token-names'
  4580. (defconst js2-token-names
  4581. (let* ((names (make-vector js2-num-tokens -1))
  4582. (case-fold-search nil) ; only match js2-UPPER_CASE
  4583. (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
  4584. (cl-loop for sym in syms
  4585. for i from 0
  4586. do
  4587. (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
  4588. (not (boundp sym)))
  4589. (aset names (symbol-value sym) ; code, e.g. 152
  4590. (downcase
  4591. (substring (symbol-name sym) 4))) ; name, e.g. "let"
  4592. (push sym js2-tokens)))
  4593. names)
  4594. "Vector mapping int values to token string names, sans `js2-' prefix.")
  4595. (defun js2-tt-name (tok)
  4596. "Return a string name for TOK, a token symbol or code.
  4597. Signals an error if it's not a recognized token."
  4598. (let ((code tok))
  4599. (if (symbolp tok)
  4600. (setq code (symbol-value tok)))
  4601. (if (eq code -1)
  4602. "ERROR"
  4603. (if (and (numberp code)
  4604. (not (cl-minusp code))
  4605. (< code js2-num-tokens))
  4606. (aref js2-token-names code)
  4607. (error "Invalid token: %s" code)))))
  4608. (defsubst js2-tt-sym (tok)
  4609. "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
  4610. (intern (js2-tt-name tok)))
  4611. (defconst js2-token-codes
  4612. (let ((table (make-hash-table :test 'eq :size 256)))
  4613. (cl-loop for name across js2-token-names
  4614. for sym = (intern (concat "js2-" (upcase name)))
  4615. do
  4616. (puthash sym (symbol-value sym) table))
  4617. ;; clean up a few that are "wrong" in Rhino's token codes
  4618. (puthash 'js2-DELETE js2-DELPROP table)
  4619. table)
  4620. "Hashtable mapping token type symbols to their bytecodes.")
  4621. (defsubst js2-tt-code (sym)
  4622. "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
  4623. (or (gethash sym js2-token-codes)
  4624. (error "Invalid token symbol: %s " sym))) ; signal code bug
  4625. (defun js2-report-scan-error (msg &optional no-throw beg len)
  4626. (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
  4627. (js2-report-error msg nil
  4628. (or beg (js2-current-token-beg))
  4629. (or len (js2-current-token-len)))
  4630. (unless no-throw
  4631. (throw 'return js2-ERROR)))
  4632. (defun js2-set-string-from-buffer (token)
  4633. "Set `string' and `end' slots for TOKEN, return the string."
  4634. (setf (js2-token-end token) js2-ts-cursor
  4635. (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
  4636. ;; TODO: could potentially avoid a lot of consing by allocating a
  4637. ;; char buffer the way Rhino does.
  4638. (defsubst js2-add-to-string (c)
  4639. (push c js2-ts-string-buffer))
  4640. ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
  4641. ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
  4642. ;; any other character: when it's not part of the current token, we
  4643. ;; unget it, allowing it to be read again by the following call.
  4644. (defsubst js2-unget-char ()
  4645. (cl-decf js2-ts-cursor))
  4646. ;; Rhino distinguishes \r and \n line endings. We don't need to
  4647. ;; because we only scan from Emacs buffers, which always use \n.
  4648. (defun js2-get-char ()
  4649. "Read and return the next character from the input buffer.
  4650. Increments `js2-ts-lineno' if the return value is a newline char.
  4651. Updates `js2-ts-cursor' to the point after the returned char.
  4652. Returns `js2-EOF_CHAR' if we hit the end of the buffer.
  4653. Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
  4654. (let (c)
  4655. ;; check for end of buffer
  4656. (if (>= js2-ts-cursor (point-max))
  4657. (setq js2-ts-hit-eof t
  4658. js2-ts-cursor (1+ js2-ts-cursor)
  4659. c js2-EOF_CHAR) ; return value
  4660. ;; otherwise read next char
  4661. (setq c (char-before (cl-incf js2-ts-cursor)))
  4662. ;; if we read a newline, update counters
  4663. (if (= c ?\n)
  4664. (setq js2-ts-line-start js2-ts-cursor
  4665. js2-ts-lineno (1+ js2-ts-lineno)))
  4666. ;; TODO: skip over format characters
  4667. c)))
  4668. (defun js2-read-unicode-escape ()
  4669. "Read a \\uNNNN sequence from the input.
  4670. Assumes the ?\ and ?u have already been read.
  4671. Returns the unicode character, or nil if it wasn't a valid character.
  4672. Doesn't change the values of any scanner variables."
  4673. ;; I really wish I knew a better way to do this, but I can't
  4674. ;; find the Emacs function that takes a 16-bit int and converts
  4675. ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
  4676. ;; Have to first check that it's 4 hex characters or it may stop
  4677. ;; the read early.
  4678. (ignore-errors
  4679. (let ((s (buffer-substring-no-properties js2-ts-cursor
  4680. (+ 4 js2-ts-cursor))))
  4681. (if (string-match "[0-9a-fA-F]\\{4\\}" s)
  4682. (read (concat "?\\u" s))))))
  4683. (defun js2-match-char (test)
  4684. "Consume and return next character if it matches TEST, a character.
  4685. Returns nil and consumes nothing if TEST is not the next character."
  4686. (let ((c (js2-get-char)))
  4687. (if (eq c test)
  4688. t
  4689. (js2-unget-char)
  4690. nil)))
  4691. (defun js2-peek-char ()
  4692. (prog1
  4693. (js2-get-char)
  4694. (js2-unget-char)))
  4695. (defun js2-identifier-start-p (c)
  4696. "Is C a valid start to an ES5 Identifier?
  4697. See http://es5.github.io/#x7.6"
  4698. (or
  4699. (memq c '(?$ ?_))
  4700. (memq (get-char-code-property c 'general-category)
  4701. ;; Letters
  4702. '(Lu Ll Lt Lm Lo Nl))))
  4703. (defun js2-identifier-part-p (c)
  4704. "Is C a valid part of an ES5 Identifier?
  4705. See http://es5.github.io/#x7.6"
  4706. (or
  4707. (memq c '(?$ ?_ ?\u200c ?\u200d))
  4708. (memq (get-char-code-property c 'general-category)
  4709. '(;; Letters
  4710. Lu Ll Lt Lm Lo Nl
  4711. ;; Combining Marks
  4712. Mn Mc
  4713. ;; Digits
  4714. Nd
  4715. ;; Connector Punctuation
  4716. Pc))))
  4717. (defun js2-alpha-p (c)
  4718. (cond ((and (<= ?A c) (<= c ?Z)) t)
  4719. ((and (<= ?a c) (<= c ?z)) t)
  4720. (t nil)))
  4721. (defsubst js2-digit-p (c)
  4722. (and (<= ?0 c) (<= c ?9)))
  4723. (defun js2-js-space-p (c)
  4724. (if (<= c 127)
  4725. (memq c '(#x20 #x9 #xB #xC #xD))
  4726. (or
  4727. (eq c #xA0)
  4728. ;; TODO: change this nil to check for Unicode space character
  4729. nil)))
  4730. (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
  4731. (defun js2-skip-line ()
  4732. "Skip to end of line."
  4733. (while (not (memq (js2-get-char) js2-eol-chars)))
  4734. (js2-unget-char)
  4735. (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
  4736. (defun js2-init-scanner (&optional buf line)
  4737. "Create token stream for BUF starting on LINE.
  4738. BUF defaults to `current-buffer' and LINE defaults to 1.
  4739. A buffer can only have one scanner active at a time, which yields
  4740. dramatically simpler code than using a defstruct. If you need to
  4741. have simultaneous scanners in a buffer, copy the regions to scan
  4742. into temp buffers."
  4743. (with-current-buffer (or buf (current-buffer))
  4744. (setq js2-ts-dirty-line nil
  4745. js2-ts-hit-eof nil
  4746. js2-ts-line-start 0
  4747. js2-ts-lineno (or line 1)
  4748. js2-ts-line-end-char -1
  4749. js2-ts-cursor (point-min)
  4750. js2-ti-tokens (make-vector js2-ti-ntokens nil)
  4751. js2-ti-tokens-cursor 0
  4752. js2-ti-lookahead 0
  4753. js2-ts-is-xml-attribute nil
  4754. js2-ts-xml-is-tag-content nil
  4755. js2-ts-xml-open-tags-count 0
  4756. js2-ts-string-buffer nil)))
  4757. ;; This function uses the cached op, string and number fields in
  4758. ;; TokenStream; if getToken has been called since the passed token
  4759. ;; was scanned, the op or string printed may be incorrect.
  4760. (defun js2-token-to-string (token)
  4761. ;; Not sure where this function is used in Rhino. Not tested.
  4762. (if (not js2-debug-print-trees)
  4763. ""
  4764. (let ((name (js2-tt-name token)))
  4765. (cond
  4766. ((memq token '(js2-STRING js2-REGEXP js2-NAME
  4767. js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
  4768. (concat name " `" (js2-current-token-string) "'"))
  4769. ((eq token js2-NUMBER)
  4770. (format "NUMBER %g" (js2-token-number (js2-current-token))))
  4771. (t
  4772. name)))))
  4773. (defconst js2-keywords
  4774. '(break
  4775. case catch class const continue
  4776. debugger default delete do
  4777. else extends export
  4778. false finally for function
  4779. if in instanceof import
  4780. let
  4781. new null
  4782. return
  4783. super switch
  4784. this throw true try typeof
  4785. var void
  4786. while with
  4787. yield))
  4788. ;; Token names aren't exactly the same as the keywords, unfortunately.
  4789. ;; E.g. delete is js2-DELPROP.
  4790. (defconst js2-kwd-tokens
  4791. (let ((table (make-vector js2-num-tokens nil))
  4792. (tokens
  4793. (list js2-BREAK
  4794. js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
  4795. js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
  4796. js2-ELSE js2-EXPORT
  4797. js2-ELSE js2-EXTENDS js2-EXPORT
  4798. js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
  4799. js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
  4800. js2-LET
  4801. js2-NEW js2-NULL
  4802. js2-RETURN
  4803. js2-SUPER js2-SWITCH
  4804. js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
  4805. js2-VAR
  4806. js2-WHILE js2-WITH
  4807. js2-YIELD)))
  4808. (dolist (i tokens)
  4809. (aset table i 'font-lock-keyword-face))
  4810. (aset table js2-STRING 'font-lock-string-face)
  4811. (aset table js2-REGEXP 'font-lock-string-face)
  4812. (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
  4813. (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
  4814. (aset table js2-COMMENT 'font-lock-comment-face)
  4815. (aset table js2-THIS 'font-lock-builtin-face)
  4816. (aset table js2-SUPER 'font-lock-builtin-face)
  4817. (aset table js2-VOID 'font-lock-constant-face)
  4818. (aset table js2-NULL 'font-lock-constant-face)
  4819. (aset table js2-TRUE 'font-lock-constant-face)
  4820. (aset table js2-FALSE 'font-lock-constant-face)
  4821. (aset table js2-NOT 'font-lock-negation-char-face)
  4822. table)
  4823. "Vector whose values are non-nil for tokens that are keywords.
  4824. The values are default faces to use for highlighting the keywords.")
  4825. ;; FIXME: Support strict mode-only future reserved words, after we know
  4826. ;; which parts scopes are in strict mode, and which are not.
  4827. (defconst js2-reserved-words '(class enum export extends import static super)
  4828. "Future reserved keywords in ECMAScript 5.1.")
  4829. (defconst js2-keyword-names
  4830. (let ((table (make-hash-table :test 'equal)))
  4831. (cl-loop for k in js2-keywords
  4832. do (puthash
  4833. (symbol-name k) ; instanceof
  4834. (intern (concat "js2-"
  4835. (upcase (symbol-name k)))) ; js2-INSTANCEOF
  4836. table))
  4837. table)
  4838. "JavaScript keywords by name, mapped to their symbols.")
  4839. (defconst js2-reserved-word-names
  4840. (let ((table (make-hash-table :test 'equal)))
  4841. (cl-loop for k in js2-reserved-words
  4842. do
  4843. (puthash (symbol-name k) 'js2-RESERVED table))
  4844. table)
  4845. "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
  4846. (defun js2-collect-string (buf)
  4847. "Convert BUF, a list of chars, to a string.
  4848. Reverses BUF before converting."
  4849. (if buf
  4850. (apply #'string (nreverse buf))
  4851. ""))
  4852. (defun js2-string-to-keyword (s)
  4853. "Return token for S, a string, if S is a keyword or reserved word.
  4854. Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
  4855. (or (gethash s js2-keyword-names)
  4856. (gethash s js2-reserved-word-names)))
  4857. (defsubst js2-ts-set-char-token-bounds (token)
  4858. "Used when next token is one character."
  4859. (setf (js2-token-beg token) (1- js2-ts-cursor)
  4860. (js2-token-end token) js2-ts-cursor))
  4861. (defsubst js2-ts-return (token type)
  4862. "Update the `end' and `type' slots of TOKEN,
  4863. then throw `return' with value TYPE."
  4864. (setf (js2-token-end token) js2-ts-cursor
  4865. (js2-token-type token) type)
  4866. (throw 'return type))
  4867. (defun js2-x-digit-to-int (c accumulator)
  4868. "Build up a hex number.
  4869. If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
  4870. corresponding number. Otherwise return -1."
  4871. (catch 'return
  4872. (catch 'check
  4873. ;; Use 0..9 < A..Z < a..z
  4874. (cond
  4875. ((<= c ?9)
  4876. (cl-decf c ?0)
  4877. (if (<= 0 c)
  4878. (throw 'check nil)))
  4879. ((<= c ?F)
  4880. (when (<= ?A c)
  4881. (cl-decf c (- ?A 10))
  4882. (throw 'check nil)))
  4883. ((<= c ?f)
  4884. (when (<= ?a c)
  4885. (cl-decf c (- ?a 10))
  4886. (throw 'check nil))))
  4887. (throw 'return -1))
  4888. (logior c (lsh accumulator 4))))
  4889. (defun js2-get-token (&optional modifier)
  4890. "If `js2-ti-lookahead' is zero, call scanner to get new token.
  4891. Otherwise, move `js2-ti-tokens-cursor' and return the type of
  4892. next saved token.
  4893. This function will not return a newline (js2-EOL) - instead, it
  4894. gobbles newlines until it finds a non-newline token. Call
  4895. `js2-peek-token-or-eol' when you care about newlines.
  4896. This function will also not return a js2-COMMENT. Instead, it
  4897. records comments found in `js2-scanned-comments'. If the token
  4898. returned by this function immediately follows a jsdoc comment,
  4899. the token is flagged as such."
  4900. (if (zerop js2-ti-lookahead)
  4901. (js2-get-token-internal modifier)
  4902. (cl-decf js2-ti-lookahead)
  4903. (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
  4904. (let ((tt (js2-current-token-type)))
  4905. (cl-assert (not (= tt js2-EOL)))
  4906. tt)))
  4907. (defun js2-unget-token ()
  4908. (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
  4909. (cl-incf js2-ti-lookahead)
  4910. (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
  4911. (defun js2-get-token-internal (modifier)
  4912. (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
  4913. (tt (js2-token-type token))
  4914. saw-eol
  4915. face)
  4916. ;; process comments
  4917. (while (or (= tt js2-EOL) (= tt js2-COMMENT))
  4918. (if (= tt js2-EOL)
  4919. (setq saw-eol t)
  4920. (setq saw-eol nil)
  4921. (when js2-record-comments
  4922. (js2-record-comment token)))
  4923. (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
  4924. (setq token (js2-get-token-internal-1 modifier) ; call scanner again
  4925. tt (js2-token-type token)))
  4926. (when saw-eol
  4927. (setf (js2-token-follows-eol-p token) t))
  4928. ;; perform lexical fontification as soon as token is scanned
  4929. (when js2-parse-ide-mode
  4930. (cond
  4931. ((cl-minusp tt)
  4932. (js2-record-face 'js2-error token))
  4933. ((setq face (aref js2-kwd-tokens tt))
  4934. (js2-record-face face token))
  4935. ((and (= tt js2-NAME)
  4936. (equal (js2-token-string token) "undefined"))
  4937. (js2-record-face 'font-lock-constant-face token))))
  4938. tt))
  4939. (defsubst js2-string-to-number (str base)
  4940. ;; TODO: Maybe port ScriptRuntime.stringToNumber.
  4941. (condition-case nil
  4942. (string-to-number str base)
  4943. (overflow-error -1)))
  4944. (defun js2-get-token-internal-1 (modifier)
  4945. "Return next JavaScript token type, an int such as js2-RETURN.
  4946. During operation, creates an instance of `js2-token' struct, sets
  4947. its relevant fields and puts it into `js2-ti-tokens'."
  4948. (let (identifier-start
  4949. is-unicode-escape-start c
  4950. contains-escape escape-val str result base
  4951. look-for-slash continue tt legacy-octal
  4952. (token (js2-new-token 0)))
  4953. (setq
  4954. tt
  4955. (catch 'return
  4956. (when (eq modifier 'TEMPLATE_TAIL)
  4957. (setf (js2-token-beg token) (1- js2-ts-cursor))
  4958. (throw 'return (js2-get-string-or-template-token ?` token)))
  4959. (while t
  4960. ;; Eat whitespace, possibly sensitive to newlines.
  4961. (setq continue t)
  4962. (while continue
  4963. (setq c (js2-get-char))
  4964. (cond
  4965. ((eq c js2-EOF_CHAR)
  4966. (js2-unget-char)
  4967. (js2-ts-set-char-token-bounds token)
  4968. (throw 'return js2-EOF))
  4969. ((eq c ?\n)
  4970. (js2-ts-set-char-token-bounds token)
  4971. (setq js2-ts-dirty-line nil)
  4972. (throw 'return js2-EOL))
  4973. ((not (js2-js-space-p c))
  4974. (if (/= c ?-) ; in case end of HTML comment
  4975. (setq js2-ts-dirty-line t))
  4976. (setq continue nil))))
  4977. ;; Assume the token will be 1 char - fixed up below.
  4978. (js2-ts-set-char-token-bounds token)
  4979. (when (eq c ?@)
  4980. (throw 'return js2-XMLATTR))
  4981. ;; identifier/keyword/instanceof?
  4982. ;; watch out for starting with a <backslash>
  4983. (cond
  4984. ((eq c ?\\)
  4985. (setq c (js2-get-char))
  4986. (if (eq c ?u)
  4987. (setq identifier-start t
  4988. is-unicode-escape-start t
  4989. js2-ts-string-buffer nil)
  4990. (setq identifier-start nil)
  4991. (js2-unget-char)
  4992. (setq c ?\\)))
  4993. (t
  4994. (when (setq identifier-start (js2-identifier-start-p c))
  4995. (setq js2-ts-string-buffer nil)
  4996. (js2-add-to-string c))))
  4997. (when identifier-start
  4998. (setq contains-escape is-unicode-escape-start)
  4999. (catch 'break
  5000. (while t
  5001. (if is-unicode-escape-start
  5002. ;; strictly speaking we should probably push-back
  5003. ;; all the bad characters if the <backslash>uXXXX
  5004. ;; sequence is malformed. But since there isn't a
  5005. ;; correct context(is there?) for a bad Unicode
  5006. ;; escape sequence in an identifier, we can report
  5007. ;; an error here.
  5008. (progn
  5009. (setq escape-val 0)
  5010. (dotimes (_ 4)
  5011. (setq c (js2-get-char)
  5012. escape-val (js2-x-digit-to-int c escape-val))
  5013. ;; Next check takes care of c < 0 and bad escape
  5014. (if (cl-minusp escape-val)
  5015. (throw 'break nil)))
  5016. (if (cl-minusp escape-val)
  5017. (js2-report-scan-error "msg.invalid.escape" t))
  5018. (js2-add-to-string escape-val)
  5019. (setq is-unicode-escape-start nil))
  5020. (setq c (js2-get-char))
  5021. (cond
  5022. ((eq c ?\\)
  5023. (setq c (js2-get-char))
  5024. (if (eq c ?u)
  5025. (setq is-unicode-escape-start t
  5026. contains-escape t)
  5027. (js2-report-scan-error "msg.illegal.character" t)))
  5028. (t
  5029. (if (or (eq c js2-EOF_CHAR)
  5030. (not (js2-identifier-part-p c)))
  5031. (throw 'break nil))
  5032. (js2-add-to-string c))))))
  5033. (js2-unget-char)
  5034. (setf str (js2-collect-string js2-ts-string-buffer)
  5035. (js2-token-end token) js2-ts-cursor)
  5036. ;; FIXME: Invalid in ES5 and ES6, see
  5037. ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
  5038. ;; Probably should just drop this conditional.
  5039. (unless contains-escape
  5040. ;; OPT we shouldn't have to make a string (object!) to
  5041. ;; check if it's a keyword.
  5042. ;; Return the corresponding token if it's a keyword
  5043. (when (and (not (eq modifier 'KEYWORD_IS_NAME))
  5044. (setq result (js2-string-to-keyword str)))
  5045. (if (and (< js2-language-version 170)
  5046. (memq result '(js2-LET js2-YIELD)))
  5047. ;; LET and YIELD are tokens only in 1.7 and later
  5048. (setq result 'js2-NAME))
  5049. (when (eq result 'js2-RESERVED)
  5050. (setf (js2-token-string token) str))
  5051. (throw 'return (js2-tt-code result))))
  5052. ;; If we want to intern these as Rhino does, just use (intern str)
  5053. (setf (js2-token-string token) str)
  5054. (throw 'return js2-NAME)) ; end identifier/kwd check
  5055. ;; is it a number?
  5056. (when (or (js2-digit-p c)
  5057. (and (eq c ?.) (js2-digit-p (js2-peek-char))))
  5058. (setq js2-ts-string-buffer nil
  5059. base 10)
  5060. (when (eq c ?0)
  5061. (setq c (js2-get-char))
  5062. (cond
  5063. ((or (eq c ?x) (eq c ?X))
  5064. (setq base 16)
  5065. (setq c (js2-get-char)))
  5066. ((and (or (eq c ?b) (eq c ?B))
  5067. (>= js2-language-version 200))
  5068. (setq base 2)
  5069. (setq c (js2-get-char)))
  5070. ((and (or (eq c ?o) (eq c ?O))
  5071. (>= js2-language-version 200))
  5072. (setq base 8)
  5073. (setq legacy-octal nil)
  5074. (setq c (js2-get-char)))
  5075. ((js2-digit-p c)
  5076. (setq base 'maybe-8))
  5077. (t
  5078. (js2-add-to-string ?0))))
  5079. (cond
  5080. ((eq base 16)
  5081. (if (> 0 (js2-x-digit-to-int c 0))
  5082. (js2-report-scan-error "msg.missing.hex.digits")
  5083. (while (<= 0 (js2-x-digit-to-int c 0))
  5084. (js2-add-to-string c)
  5085. (setq c (js2-get-char)))))
  5086. ((eq base 2)
  5087. (if (not (memq c '(?0 ?1)))
  5088. (js2-report-scan-error "msg.missing.binary.digits")
  5089. (while (memq c '(?0 ?1))
  5090. (js2-add-to-string c)
  5091. (setq c (js2-get-char)))))
  5092. ((eq base 8)
  5093. (if (or (> ?0 c) (< ?7 c))
  5094. (js2-report-scan-error "msg.missing.octal.digits")
  5095. (while (and (<= ?0 c) (>= ?7 c))
  5096. (js2-add-to-string c)
  5097. (setq c (js2-get-char)))))
  5098. (t
  5099. (while (and (<= ?0 c) (<= c ?9))
  5100. ;; We permit 08 and 09 as decimal numbers, which
  5101. ;; makes our behavior a superset of the ECMA
  5102. ;; numeric grammar. We might not always be so
  5103. ;; permissive, so we warn about it.
  5104. (when (and (eq base 'maybe-8) (>= c ?8))
  5105. (js2-report-warning "msg.bad.octal.literal"
  5106. (if (eq c ?8) "8" "9"))
  5107. (setq base 10))
  5108. (js2-add-to-string c)
  5109. (setq c (js2-get-char)))
  5110. (when (eq base 'maybe-8)
  5111. (setq base 8
  5112. legacy-octal t))))
  5113. (when (and (eq base 10) (memq c '(?. ?e ?E)))
  5114. (when (eq c ?.)
  5115. (cl-loop do
  5116. (js2-add-to-string c)
  5117. (setq c (js2-get-char))
  5118. while (js2-digit-p c)))
  5119. (when (memq c '(?e ?E))
  5120. (js2-add-to-string c)
  5121. (setq c (js2-get-char))
  5122. (when (memq c '(?+ ?-))
  5123. (js2-add-to-string c)
  5124. (setq c (js2-get-char)))
  5125. (unless (js2-digit-p c)
  5126. (js2-report-scan-error "msg.missing.exponent" t))
  5127. (cl-loop do
  5128. (js2-add-to-string c)
  5129. (setq c (js2-get-char))
  5130. while (js2-digit-p c))))
  5131. (js2-unget-char)
  5132. (let ((str (js2-set-string-from-buffer token)))
  5133. (setf (js2-token-number token) (js2-string-to-number str base)
  5134. (js2-token-number-base token) base
  5135. (js2-token-number-legacy-octal-p token) (and (= base 8) legacy-octal)))
  5136. (throw 'return js2-NUMBER))
  5137. ;; is it a string?
  5138. (when (or (memq c '(?\" ?\'))
  5139. (and (>= js2-language-version 200)
  5140. (= c ?`)))
  5141. (throw 'return
  5142. (js2-get-string-or-template-token c token)))
  5143. (js2-ts-return token
  5144. (cl-case c
  5145. (?\;
  5146. (throw 'return js2-SEMI))
  5147. (?\[
  5148. (throw 'return js2-LB))
  5149. (?\]
  5150. (throw 'return js2-RB))
  5151. (?{
  5152. (throw 'return js2-LC))
  5153. (?}
  5154. (throw 'return js2-RC))
  5155. (?\(
  5156. (throw 'return js2-LP))
  5157. (?\)
  5158. (throw 'return js2-RP))
  5159. (?,
  5160. (throw 'return js2-COMMA))
  5161. (??
  5162. (throw 'return js2-HOOK))
  5163. (?:
  5164. (if (js2-match-char ?:)
  5165. js2-COLONCOLON
  5166. (throw 'return js2-COLON)))
  5167. (?.
  5168. (if (js2-match-char ?.)
  5169. (if (js2-match-char ?.)
  5170. js2-TRIPLEDOT js2-DOTDOT)
  5171. (if (js2-match-char ?\()
  5172. js2-DOTQUERY
  5173. (throw 'return js2-DOT))))
  5174. (?|
  5175. (if (js2-match-char ?|)
  5176. (throw 'return js2-OR)
  5177. (if (js2-match-char ?=)
  5178. js2-ASSIGN_BITOR
  5179. (throw 'return js2-BITOR))))
  5180. (?^
  5181. (if (js2-match-char ?=)
  5182. js2-ASSIGN_BITOR
  5183. (throw 'return js2-BITXOR)))
  5184. (?&
  5185. (if (js2-match-char ?&)
  5186. (throw 'return js2-AND)
  5187. (if (js2-match-char ?=)
  5188. js2-ASSIGN_BITAND
  5189. (throw 'return js2-BITAND))))
  5190. (?=
  5191. (if (js2-match-char ?=)
  5192. (if (js2-match-char ?=)
  5193. js2-SHEQ
  5194. (throw 'return js2-EQ))
  5195. (if (js2-match-char ?>)
  5196. (js2-ts-return token js2-ARROW)
  5197. (throw 'return js2-ASSIGN))))
  5198. (?!
  5199. (if (js2-match-char ?=)
  5200. (if (js2-match-char ?=)
  5201. js2-SHNE
  5202. js2-NE)
  5203. (throw 'return js2-NOT)))
  5204. (?<
  5205. ;; NB:treat HTML begin-comment as comment-till-eol
  5206. (when (js2-match-char ?!)
  5207. (when (js2-match-char ?-)
  5208. (when (js2-match-char ?-)
  5209. (js2-skip-line)
  5210. (setf (js2-token-comment-type (js2-current-token)) 'html)
  5211. (throw 'return js2-COMMENT)))
  5212. (js2-unget-char))
  5213. (if (js2-match-char ?<)
  5214. (if (js2-match-char ?=)
  5215. js2-ASSIGN_LSH
  5216. js2-LSH)
  5217. (if (js2-match-char ?=)
  5218. js2-LE
  5219. (throw 'return js2-LT))))
  5220. (?>
  5221. (if (js2-match-char ?>)
  5222. (if (js2-match-char ?>)
  5223. (if (js2-match-char ?=)
  5224. js2-ASSIGN_URSH
  5225. js2-URSH)
  5226. (if (js2-match-char ?=)
  5227. js2-ASSIGN_RSH
  5228. js2-RSH))
  5229. (if (js2-match-char ?=)
  5230. js2-GE
  5231. (throw 'return js2-GT))))
  5232. (?*
  5233. (if (js2-match-char ?=)
  5234. js2-ASSIGN_MUL
  5235. (if (js2-match-char ?*)
  5236. (if (js2-match-char ?=)
  5237. js2-ASSIGN_EXPON
  5238. js2-EXPON)
  5239. (throw 'return js2-MUL))))
  5240. (?/
  5241. ;; is it a // comment?
  5242. (when (js2-match-char ?/)
  5243. (setf (js2-token-beg token) (- js2-ts-cursor 2))
  5244. (js2-skip-line)
  5245. (setf (js2-token-comment-type token) 'line)
  5246. ;; include newline so highlighting goes to end of
  5247. ;; window, if there actually is a newline; if we
  5248. ;; hit eof, then implicitly there isn't
  5249. (unless js2-ts-hit-eof
  5250. (cl-incf (js2-token-end token)))
  5251. (throw 'return js2-COMMENT))
  5252. ;; is it a /* comment?
  5253. (when (js2-match-char ?*)
  5254. (setf look-for-slash nil
  5255. (js2-token-beg token) (- js2-ts-cursor 2)
  5256. (js2-token-comment-type token)
  5257. (if (js2-match-char ?*)
  5258. (progn
  5259. (setq look-for-slash t)
  5260. 'jsdoc)
  5261. 'block))
  5262. (while t
  5263. (setq c (js2-get-char))
  5264. (cond
  5265. ((eq c js2-EOF_CHAR)
  5266. (setf (js2-token-end token) (1- js2-ts-cursor))
  5267. (js2-report-error "msg.unterminated.comment")
  5268. (throw 'return js2-COMMENT))
  5269. ((eq c ?*)
  5270. (setq look-for-slash t))
  5271. ((eq c ?/)
  5272. (if look-for-slash
  5273. (js2-ts-return token js2-COMMENT)))
  5274. (t
  5275. (setf look-for-slash nil
  5276. (js2-token-end token) js2-ts-cursor)))))
  5277. (if (js2-match-char ?=)
  5278. js2-ASSIGN_DIV
  5279. (throw 'return js2-DIV)))
  5280. (?#
  5281. (when js2-skip-preprocessor-directives
  5282. (js2-skip-line)
  5283. (setf (js2-token-comment-type token) 'preprocessor
  5284. (js2-token-end token) js2-ts-cursor)
  5285. (throw 'return js2-COMMENT))
  5286. (throw 'return js2-ERROR))
  5287. (?%
  5288. (if (js2-match-char ?=)
  5289. js2-ASSIGN_MOD
  5290. (throw 'return js2-MOD)))
  5291. (?~
  5292. (throw 'return js2-BITNOT))
  5293. (?+
  5294. (if (js2-match-char ?=)
  5295. js2-ASSIGN_ADD
  5296. (if (js2-match-char ?+)
  5297. js2-INC
  5298. (throw 'return js2-ADD))))
  5299. (?-
  5300. (cond
  5301. ((js2-match-char ?=)
  5302. (setq c js2-ASSIGN_SUB))
  5303. ((js2-match-char ?-)
  5304. (unless js2-ts-dirty-line
  5305. ;; treat HTML end-comment after possible whitespace
  5306. ;; after line start as comment-until-eol
  5307. (when (js2-match-char ?>)
  5308. (js2-skip-line)
  5309. (setf (js2-token-comment-type (js2-current-token)) 'html)
  5310. (throw 'return js2-COMMENT)))
  5311. (setq c js2-DEC))
  5312. (t
  5313. (setq c js2-SUB)))
  5314. (setq js2-ts-dirty-line t)
  5315. c)
  5316. (otherwise
  5317. (js2-report-scan-error "msg.illegal.character")))))))
  5318. (setf (js2-token-type token) tt)
  5319. token))
  5320. (defun js2-get-string-or-template-token (quote-char token)
  5321. ;; We attempt to accumulate a string the fast way, by
  5322. ;; building it directly out of the reader. But if there
  5323. ;; are any escaped characters in the string, we revert to
  5324. ;; building it out of a string buffer.
  5325. (let ((c (js2-get-char))
  5326. js2-ts-string-buffer
  5327. nc c1 val escape-val)
  5328. (catch 'break
  5329. (while (/= c quote-char)
  5330. (catch 'continue
  5331. (when (eq c js2-EOF_CHAR)
  5332. (js2-unget-char)
  5333. (js2-report-error "msg.unterminated.string.lit")
  5334. (throw 'break nil))
  5335. (when (and (eq c ?\n) (not (eq quote-char ?`)))
  5336. (js2-unget-char)
  5337. (js2-report-error "msg.unterminated.string.lit")
  5338. (throw 'break nil))
  5339. (when (eq c ?\\)
  5340. ;; We've hit an escaped character
  5341. (setq c (js2-get-char))
  5342. (cl-case c
  5343. (?b (setq c ?\b))
  5344. (?f (setq c ?\f))
  5345. (?n (setq c ?\n))
  5346. (?r (setq c ?\r))
  5347. (?t (setq c ?\t))
  5348. (?v (setq c ?\v))
  5349. (?u
  5350. (setq c1 (js2-read-unicode-escape))
  5351. (if js2-parse-ide-mode
  5352. (if c1
  5353. (progn
  5354. ;; just copy the string in IDE-mode
  5355. (js2-add-to-string ?\\)
  5356. (js2-add-to-string ?u)
  5357. (dotimes (_ 3)
  5358. (js2-add-to-string (js2-get-char)))
  5359. (setq c (js2-get-char))) ; added at end of loop
  5360. ;; flag it as an invalid escape
  5361. (js2-report-warning "msg.invalid.escape"
  5362. nil (- js2-ts-cursor 2) 6))
  5363. ;; Get 4 hex digits; if the u escape is not
  5364. ;; followed by 4 hex digits, use 'u' + the
  5365. ;; literal character sequence that follows.
  5366. (js2-add-to-string ?u)
  5367. (setq escape-val 0)
  5368. (dotimes (_ 4)
  5369. (setq c (js2-get-char)
  5370. escape-val (js2-x-digit-to-int c escape-val))
  5371. (if (cl-minusp escape-val)
  5372. (throw 'continue nil))
  5373. (js2-add-to-string c))
  5374. ;; prepare for replace of stored 'u' sequence by escape value
  5375. (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
  5376. c escape-val)))
  5377. (?x
  5378. ;; Get 2 hex digits, defaulting to 'x'+literal
  5379. ;; sequence, as above.
  5380. (setq c (js2-get-char)
  5381. escape-val (js2-x-digit-to-int c 0))
  5382. (if (cl-minusp escape-val)
  5383. (progn
  5384. (js2-add-to-string ?x)
  5385. (throw 'continue nil))
  5386. (setq c1 c
  5387. c (js2-get-char)
  5388. escape-val (js2-x-digit-to-int c escape-val))
  5389. (if (cl-minusp escape-val)
  5390. (progn
  5391. (js2-add-to-string ?x)
  5392. (js2-add-to-string c1)
  5393. (throw 'continue nil))
  5394. ;; got 2 hex digits
  5395. (setq c escape-val))))
  5396. (?\n
  5397. ;; Remove line terminator after escape to follow
  5398. ;; SpiderMonkey and C/C++
  5399. (setq c (js2-get-char))
  5400. (throw 'continue nil))
  5401. (t
  5402. (when (and (<= ?0 c) (< c ?8))
  5403. (setq val (- c ?0)
  5404. c (js2-get-char))
  5405. (when (and (<= ?0 c) (< c ?8))
  5406. (setq val (- (+ (* 8 val) c) ?0)
  5407. c (js2-get-char))
  5408. (when (and (<= ?0 c)
  5409. (< c ?8)
  5410. (< val #o37))
  5411. ;; c is 3rd char of octal sequence only
  5412. ;; if the resulting val <= 0377
  5413. (setq val (- (+ (* 8 val) c) ?0)
  5414. c (js2-get-char))))
  5415. (js2-unget-char)
  5416. (setq c val)))))
  5417. (when (and (eq quote-char ?`) (eq c ?$))
  5418. (when (eq (setq nc (js2-get-char)) ?\{)
  5419. (throw 'break nil))
  5420. (js2-unget-char))
  5421. (js2-add-to-string c)
  5422. (setq c (js2-get-char)))))
  5423. (js2-set-string-from-buffer token)
  5424. (if (not (eq quote-char ?`))
  5425. js2-STRING
  5426. (if (and (eq c ?$) (eq nc ?\{))
  5427. js2-TEMPLATE_HEAD
  5428. js2-NO_SUBS_TEMPLATE))))
  5429. (defun js2-read-regexp (start-tt start-pos)
  5430. "Called by parser when it gets / or /= in literal context."
  5431. (let (c err
  5432. in-class ; inside a '[' .. ']' character-class
  5433. flags
  5434. (continue t)
  5435. (token (js2-new-token 0)))
  5436. (js2-record-text-property start-pos (1+ start-pos)
  5437. 'syntax-table (string-to-syntax "\"/"))
  5438. (setq js2-ts-string-buffer nil)
  5439. (if (eq start-tt js2-ASSIGN_DIV)
  5440. ;; mis-scanned /=
  5441. (js2-add-to-string ?=)
  5442. (if (not (eq start-tt js2-DIV))
  5443. (error "failed assertion")))
  5444. (while (and (not err)
  5445. (or (/= (setq c (js2-get-char)) ?/)
  5446. in-class))
  5447. (cond
  5448. ((or (= c ?\n)
  5449. (= c js2-EOF_CHAR))
  5450. (setf (js2-token-end token) (1- js2-ts-cursor)
  5451. err t
  5452. (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
  5453. (js2-report-error "msg.unterminated.re.lit"))
  5454. (t (cond
  5455. ((= c ?\\)
  5456. (js2-add-to-string c)
  5457. (setq c (js2-get-char)))
  5458. ((= c ?\[)
  5459. (setq in-class t))
  5460. ((= c ?\])
  5461. (setq in-class nil)))
  5462. (js2-add-to-string c))))
  5463. (unless err
  5464. (js2-record-text-property (1- js2-ts-cursor) js2-ts-cursor
  5465. 'syntax-table (string-to-syntax "\"/"))
  5466. (while continue
  5467. (cond
  5468. ((js2-match-char ?g)
  5469. (push ?g flags))
  5470. ((js2-match-char ?i)
  5471. (push ?i flags))
  5472. ((js2-match-char ?m)
  5473. (push ?m flags))
  5474. ((and (js2-match-char ?u)
  5475. (>= js2-language-version 200))
  5476. (push ?u flags))
  5477. ((and (js2-match-char ?y)
  5478. (>= js2-language-version 200))
  5479. (push ?y flags))
  5480. (t
  5481. (setq continue nil))))
  5482. (if (js2-alpha-p (js2-peek-char))
  5483. (js2-report-scan-error "msg.invalid.re.flag" t
  5484. js2-ts-cursor 1))
  5485. (js2-set-string-from-buffer token))
  5486. (js2-collect-string flags)))
  5487. (defun js2-get-first-xml-token ()
  5488. (setq js2-ts-xml-open-tags-count 0
  5489. js2-ts-is-xml-attribute nil
  5490. js2-ts-xml-is-tag-content nil)
  5491. (js2-unget-char)
  5492. (js2-get-next-xml-token))
  5493. (defun js2-xml-discard-string (token)
  5494. "Throw away the string in progress and flag an XML parse error."
  5495. (setf js2-ts-string-buffer nil
  5496. (js2-token-string token) nil)
  5497. (js2-report-scan-error "msg.XML.bad.form" t))
  5498. (defun js2-get-next-xml-token ()
  5499. (setq js2-ts-string-buffer nil) ; for recording the XML
  5500. (let ((token (js2-new-token 0))
  5501. c result)
  5502. (setq result
  5503. (catch 'return
  5504. (while t
  5505. (setq c (js2-get-char))
  5506. (cond
  5507. ((= c js2-EOF_CHAR)
  5508. (throw 'return js2-ERROR))
  5509. (js2-ts-xml-is-tag-content
  5510. (cl-case c
  5511. (?>
  5512. (js2-add-to-string c)
  5513. (setq js2-ts-xml-is-tag-content nil
  5514. js2-ts-is-xml-attribute nil))
  5515. (?/
  5516. (js2-add-to-string c)
  5517. (when (eq ?> (js2-peek-char))
  5518. (setq c (js2-get-char))
  5519. (js2-add-to-string c)
  5520. (setq js2-ts-xml-is-tag-content nil)
  5521. (cl-decf js2-ts-xml-open-tags-count)))
  5522. (?{
  5523. (js2-unget-char)
  5524. (js2-set-string-from-buffer token)
  5525. (throw 'return js2-XML))
  5526. ((?\' ?\")
  5527. (js2-add-to-string c)
  5528. (unless (js2-read-quoted-string c token)
  5529. (throw 'return js2-ERROR)))
  5530. (?=
  5531. (js2-add-to-string c)
  5532. (setq js2-ts-is-xml-attribute t))
  5533. ((? ?\t ?\r ?\n)
  5534. (js2-add-to-string c))
  5535. (t
  5536. (js2-add-to-string c)
  5537. (setq js2-ts-is-xml-attribute nil)))
  5538. (when (and (not js2-ts-xml-is-tag-content)
  5539. (zerop js2-ts-xml-open-tags-count))
  5540. (js2-set-string-from-buffer token)
  5541. (throw 'return js2-XMLEND)))
  5542. (t
  5543. ;; else not tag content
  5544. (cl-case c
  5545. (?<
  5546. (js2-add-to-string c)
  5547. (setq c (js2-peek-char))
  5548. (cl-case c
  5549. (?!
  5550. (setq c (js2-get-char)) ;; skip !
  5551. (js2-add-to-string c)
  5552. (setq c (js2-peek-char))
  5553. (cl-case c
  5554. (?-
  5555. (setq c (js2-get-char)) ;; skip -
  5556. (js2-add-to-string c)
  5557. (if (eq c ?-)
  5558. (progn
  5559. (js2-add-to-string c)
  5560. (unless (js2-read-xml-comment token)
  5561. (throw 'return js2-ERROR)))
  5562. (js2-xml-discard-string token)
  5563. (throw 'return js2-ERROR)))
  5564. (?\[
  5565. (setq c (js2-get-char)) ;; skip [
  5566. (js2-add-to-string c)
  5567. (if (and (= (js2-get-char) ?C)
  5568. (= (js2-get-char) ?D)
  5569. (= (js2-get-char) ?A)
  5570. (= (js2-get-char) ?T)
  5571. (= (js2-get-char) ?A)
  5572. (= (js2-get-char) ?\[))
  5573. (progn
  5574. (js2-add-to-string ?C)
  5575. (js2-add-to-string ?D)
  5576. (js2-add-to-string ?A)
  5577. (js2-add-to-string ?T)
  5578. (js2-add-to-string ?A)
  5579. (js2-add-to-string ?\[)
  5580. (unless (js2-read-cdata token)
  5581. (throw 'return js2-ERROR)))
  5582. (js2-xml-discard-string token)
  5583. (throw 'return js2-ERROR)))
  5584. (t
  5585. (unless (js2-read-entity token)
  5586. (throw 'return js2-ERROR))))
  5587. ;; Allow bare CDATA section, e.g.:
  5588. ;; let xml = <![CDATA[ foo bar baz ]]>;
  5589. (when (zerop js2-ts-xml-open-tags-count)
  5590. (throw 'return js2-XMLEND)))
  5591. (??
  5592. (setq c (js2-get-char)) ;; skip ?
  5593. (js2-add-to-string c)
  5594. (unless (js2-read-PI token)
  5595. (throw 'return js2-ERROR)))
  5596. (?/
  5597. ;; end tag
  5598. (setq c (js2-get-char)) ;; skip /
  5599. (js2-add-to-string c)
  5600. (when (zerop js2-ts-xml-open-tags-count)
  5601. (js2-xml-discard-string token)
  5602. (throw 'return js2-ERROR))
  5603. (setq js2-ts-xml-is-tag-content t)
  5604. (cl-decf js2-ts-xml-open-tags-count))
  5605. (t
  5606. ;; start tag
  5607. (setq js2-ts-xml-is-tag-content t)
  5608. (cl-incf js2-ts-xml-open-tags-count))))
  5609. (?{
  5610. (js2-unget-char)
  5611. (js2-set-string-from-buffer token)
  5612. (throw 'return js2-XML))
  5613. (t
  5614. (js2-add-to-string c))))))))
  5615. (setf (js2-token-end token) js2-ts-cursor)
  5616. (setf (js2-token-type token) result)
  5617. result))
  5618. (defun js2-read-quoted-string (quote token)
  5619. (let (c)
  5620. (catch 'return
  5621. (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
  5622. (js2-add-to-string c)
  5623. (if (eq c quote)
  5624. (throw 'return t)))
  5625. (js2-xml-discard-string token) ;; throw away string in progress
  5626. nil)))
  5627. (defun js2-read-xml-comment (token)
  5628. (let ((c (js2-get-char)))
  5629. (catch 'return
  5630. (while (/= c js2-EOF_CHAR)
  5631. (catch 'continue
  5632. (js2-add-to-string c)
  5633. (when (and (eq c ?-) (eq ?- (js2-peek-char)))
  5634. (setq c (js2-get-char))
  5635. (js2-add-to-string c)
  5636. (if (eq (js2-peek-char) ?>)
  5637. (progn
  5638. (setq c (js2-get-char)) ;; skip >
  5639. (js2-add-to-string c)
  5640. (throw 'return t))
  5641. (throw 'continue nil)))
  5642. (setq c (js2-get-char))))
  5643. (js2-xml-discard-string token)
  5644. nil)))
  5645. (defun js2-read-cdata (token)
  5646. (let ((c (js2-get-char)))
  5647. (catch 'return
  5648. (while (/= c js2-EOF_CHAR)
  5649. (catch 'continue
  5650. (js2-add-to-string c)
  5651. (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
  5652. (setq c (js2-get-char))
  5653. (js2-add-to-string c)
  5654. (if (eq (js2-peek-char) ?>)
  5655. (progn
  5656. (setq c (js2-get-char)) ;; Skip >
  5657. (js2-add-to-string c)
  5658. (throw 'return t))
  5659. (throw 'continue nil)))
  5660. (setq c (js2-get-char))))
  5661. (js2-xml-discard-string token)
  5662. nil)))
  5663. (defun js2-read-entity (token)
  5664. (let ((decl-tags 1)
  5665. c)
  5666. (catch 'return
  5667. (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
  5668. (js2-add-to-string c)
  5669. (cl-case c
  5670. (?<
  5671. (cl-incf decl-tags))
  5672. (?>
  5673. (cl-decf decl-tags)
  5674. (if (zerop decl-tags)
  5675. (throw 'return t)))))
  5676. (js2-xml-discard-string token)
  5677. nil)))
  5678. (defun js2-read-PI (token)
  5679. "Scan an XML processing instruction."
  5680. (let (c)
  5681. (catch 'return
  5682. (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
  5683. (js2-add-to-string c)
  5684. (when (and (eq c ??) (eq (js2-peek-char) ?>))
  5685. (setq c (js2-get-char)) ;; Skip >
  5686. (js2-add-to-string c)
  5687. (throw 'return t)))
  5688. (js2-xml-discard-string token)
  5689. nil)))
  5690. ;;; Highlighting
  5691. (defun js2-set-face (beg end face &optional record)
  5692. "Fontify a region. If RECORD is non-nil, record for later."
  5693. (when (cl-plusp js2-highlight-level)
  5694. (setq beg (min (point-max) beg)
  5695. beg (max (point-min) beg)
  5696. end (min (point-max) end)
  5697. end (max (point-min) end))
  5698. (if record
  5699. (push (list beg end face) js2-mode-fontifications)
  5700. (put-text-property beg end 'font-lock-face face))))
  5701. (defsubst js2-clear-face (beg end)
  5702. (remove-text-properties beg end '(font-lock-face nil
  5703. help-echo nil
  5704. point-entered nil
  5705. cursor-sensor-functions nil
  5706. c-in-sws nil)))
  5707. (defconst js2-ecma-global-props
  5708. (concat "^"
  5709. (regexp-opt
  5710. '("Infinity" "NaN" "undefined" "arguments") t)
  5711. "$")
  5712. "Value properties of the Ecma-262 Global Object.
  5713. Shown at or above `js2-highlight-level' 2.")
  5714. ;; might want to add the name "arguments" to this list?
  5715. (defconst js2-ecma-object-props
  5716. (concat "^"
  5717. (regexp-opt
  5718. '("prototype" "__proto__" "__parent__") t)
  5719. "$")
  5720. "Value properties of the Ecma-262 Object constructor.
  5721. Shown at or above `js2-highlight-level' 2.")
  5722. (defconst js2-ecma-global-funcs
  5723. (concat
  5724. "^"
  5725. (regexp-opt
  5726. '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
  5727. "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
  5728. "$")
  5729. "Function properties of the Ecma-262 Global object.
  5730. Shown at or above `js2-highlight-level' 2.")
  5731. (defconst js2-ecma-number-props
  5732. (concat "^"
  5733. (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
  5734. "NEGATIVE_INFINITY"
  5735. "POSITIVE_INFINITY") t)
  5736. "$")
  5737. "Properties of the Ecma-262 Number constructor.
  5738. Shown at or above `js2-highlight-level' 2.")
  5739. (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
  5740. "Properties of the Ecma-262 Date constructor.
  5741. Shown at or above `js2-highlight-level' 2.")
  5742. (defconst js2-ecma-math-props
  5743. (concat "^"
  5744. (regexp-opt
  5745. '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
  5746. t)
  5747. "$")
  5748. "Properties of the Ecma-262 Math object.
  5749. Shown at or above `js2-highlight-level' 2.")
  5750. (defconst js2-ecma-math-funcs
  5751. (concat "^"
  5752. (regexp-opt
  5753. '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
  5754. "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
  5755. "$")
  5756. "Function properties of the Ecma-262 Math object.
  5757. Shown at or above `js2-highlight-level' 2.")
  5758. (defconst js2-ecma-function-props
  5759. (concat
  5760. "^"
  5761. (regexp-opt
  5762. '(;; properties of the Object prototype object
  5763. "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
  5764. "toLocaleString" "toString" "valueOf"
  5765. ;; properties of the Function prototype object
  5766. "apply" "call"
  5767. ;; properties of the Array prototype object
  5768. "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
  5769. "splice" "unshift"
  5770. ;; properties of the String prototype object
  5771. "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
  5772. "localeCompare" "match" "replace" "search" "split" "substring"
  5773. "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
  5774. "toUpperCase"
  5775. ;; properties of the Number prototype object
  5776. "toExponential" "toFixed" "toPrecision"
  5777. ;; properties of the Date prototype object
  5778. "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
  5779. "getMinutes" "getMonth" "getSeconds" "getTime"
  5780. "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
  5781. "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
  5782. "getUTCSeconds" "setDate" "setFullYear" "setHours"
  5783. "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
  5784. "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
  5785. "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
  5786. "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
  5787. "toTimeString" "toUTCString"
  5788. ;; properties of the RegExp prototype object
  5789. "exec" "test"
  5790. ;; properties of the JSON prototype object
  5791. "parse" "stringify"
  5792. ;; SpiderMonkey/Rhino extensions, versions 1.5+
  5793. "toSource" "__defineGetter__" "__defineSetter__"
  5794. "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
  5795. "every" "filter" "forEach" "lastIndexOf" "map" "some")
  5796. t)
  5797. "$")
  5798. "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
  5799. Shown at or above `js2-highlight-level' 3.")
  5800. (defun js2-parse-highlight-prop-get (parent target prop call-p)
  5801. (let ((target-name (and target
  5802. (js2-name-node-p target)
  5803. (js2-name-node-name target)))
  5804. (prop-name (if prop (js2-name-node-name prop)))
  5805. (level2 (>= js2-highlight-level 2))
  5806. (level3 (>= js2-highlight-level 3)))
  5807. (when level2
  5808. (let ((face
  5809. (if call-p
  5810. (cond
  5811. ((and target prop)
  5812. (cond
  5813. ((and level3 (string-match js2-ecma-function-props prop-name))
  5814. 'font-lock-builtin-face)
  5815. ((and target-name prop)
  5816. (cond
  5817. ((string= target-name "Date")
  5818. (if (string-match js2-ecma-date-props prop-name)
  5819. 'font-lock-builtin-face))
  5820. ((string= target-name "Math")
  5821. (if (string-match js2-ecma-math-funcs prop-name)
  5822. 'font-lock-builtin-face))))))
  5823. (prop
  5824. (if (string-match js2-ecma-global-funcs prop-name)
  5825. 'font-lock-builtin-face)))
  5826. (cond
  5827. ((and target prop)
  5828. (cond
  5829. ((string= target-name "Number")
  5830. (if (string-match js2-ecma-number-props prop-name)
  5831. 'font-lock-constant-face))
  5832. ((string= target-name "Math")
  5833. (if (string-match js2-ecma-math-props prop-name)
  5834. 'font-lock-constant-face))))
  5835. (prop
  5836. (if (string-match js2-ecma-object-props prop-name)
  5837. 'font-lock-constant-face))))))
  5838. (when (and (not face) target (not call-p) prop-name)
  5839. (setq face 'js2-object-property-access))
  5840. (when face
  5841. (let ((pos (+ (js2-node-pos parent) ; absolute
  5842. (js2-node-pos prop)))) ; relative
  5843. (js2-set-face pos
  5844. (+ pos (js2-node-len prop))
  5845. face 'record)))))))
  5846. (defun js2-parse-highlight-member-expr-node (node)
  5847. "Perform syntax highlighting of EcmaScript built-in properties.
  5848. The variable `js2-highlight-level' governs this highlighting."
  5849. (let (face target prop name pos end parent call-p callee)
  5850. (cond
  5851. ;; case 1: simple name, e.g. foo
  5852. ((js2-name-node-p node)
  5853. (setq name (js2-name-node-name node))
  5854. ;; possible for name to be nil in rare cases - saw it when
  5855. ;; running js2-mode on an elisp buffer. Might as well try to
  5856. ;; make it so js2-mode never barfs.
  5857. (when name
  5858. (setq face (if (string-match js2-ecma-global-props name)
  5859. 'font-lock-constant-face))
  5860. (when face
  5861. (setq pos (js2-node-pos node)
  5862. end (+ pos (js2-node-len node)))
  5863. (js2-set-face pos end face 'record))))
  5864. ;; case 2: property access or function call
  5865. ((or (js2-prop-get-node-p node)
  5866. ;; highlight function call if expr is a prop-get node
  5867. ;; or a plain name (i.e. unqualified function call)
  5868. (and (setq call-p (js2-call-node-p node))
  5869. (setq callee (js2-call-node-target node)) ; separate setq!
  5870. (or (js2-prop-get-node-p callee)
  5871. (js2-name-node-p callee))))
  5872. (setq parent node
  5873. node (if call-p callee node))
  5874. (if (and call-p (js2-name-node-p callee))
  5875. (setq prop callee)
  5876. (setq target (js2-prop-get-node-left node)
  5877. prop (js2-prop-get-node-right node)))
  5878. (cond
  5879. ((js2-name-node-p prop)
  5880. ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
  5881. (js2-parse-highlight-prop-get parent target prop call-p))
  5882. ((js2-name-node-p target)
  5883. ;; case 2b: simple target, complex name, e.g. foo.x[y]
  5884. (js2-parse-highlight-prop-get parent target nil call-p)))))))
  5885. (defun js2-parse-highlight-member-expr-fn-name (expr)
  5886. "Highlight the `baz' in function foo.bar.baz(args) {...}.
  5887. This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
  5888. We currently only handle the case where the last component is a prop-get
  5889. of a simple name. Called before EXPR has a parent node."
  5890. (let (pos
  5891. (name (and (js2-prop-get-node-p expr)
  5892. (js2-prop-get-node-right expr))))
  5893. (when (js2-name-node-p name)
  5894. (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
  5895. (js2-node-pos name)))
  5896. (+ pos (js2-node-len name))
  5897. 'font-lock-function-name-face
  5898. 'record))))
  5899. ;; source: http://jsdoc.sourceforge.net/
  5900. ;; Note - this syntax is for Google's enhanced jsdoc parser that
  5901. ;; allows type specifications, and needs work before entering the wild.
  5902. (defconst js2-jsdoc-param-tag-regexp
  5903. (concat "^\\s-*\\*+\\s-*\\(@"
  5904. (regexp-opt '("param" "arg" "argument" "prop" "property" "typedef"))
  5905. "\\)"
  5906. "\\s-*\\({[^}]+}\\)?" ; optional type
  5907. "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
  5908. "\\_>")
  5909. "Matches jsdoc tags with optional type and optional param name.")
  5910. (defconst js2-jsdoc-typed-tag-regexp
  5911. (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
  5912. (regexp-opt
  5913. '("enum"
  5914. "extends"
  5915. "field"
  5916. "id"
  5917. "implements"
  5918. "lends"
  5919. "mods"
  5920. "requires"
  5921. "return"
  5922. "returns"
  5923. "yield"
  5924. "yields"
  5925. "type"
  5926. "throw"
  5927. "throws"))
  5928. "\\)\\)\\s-*\\({[^}]+}\\)?")
  5929. "Matches jsdoc tags with optional type.")
  5930. (defconst js2-jsdoc-arg-tag-regexp
  5931. (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
  5932. (regexp-opt
  5933. '("alias"
  5934. "augments"
  5935. "borrows"
  5936. "callback"
  5937. "bug"
  5938. "base"
  5939. "config"
  5940. "default"
  5941. "define"
  5942. "exception"
  5943. "func"
  5944. "function"
  5945. "member"
  5946. "memberOf"
  5947. "method"
  5948. "module"
  5949. "name"
  5950. "namespace"
  5951. "since"
  5952. "suppress"
  5953. "this"
  5954. "throws"
  5955. "version"))
  5956. "\\)\\)\\s-+\\([^ \t\n]+\\)")
  5957. "Matches jsdoc tags with a single argument.")
  5958. (defconst js2-jsdoc-empty-tag-regexp
  5959. (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
  5960. (regexp-opt
  5961. '("abstract"
  5962. "addon"
  5963. "author"
  5964. "class"
  5965. "const"
  5966. "constant"
  5967. "constructor"
  5968. "constructs"
  5969. "deprecated"
  5970. "desc"
  5971. "description"
  5972. "event"
  5973. "example"
  5974. "exec"
  5975. "export"
  5976. "fileoverview"
  5977. "final"
  5978. "func"
  5979. "function"
  5980. "hidden"
  5981. "ignore"
  5982. "implicitCast"
  5983. "inheritDoc"
  5984. "inner"
  5985. "interface"
  5986. "license"
  5987. "method"
  5988. "noalias"
  5989. "noshadow"
  5990. "notypecheck"
  5991. "override"
  5992. "owner"
  5993. "preserve"
  5994. "preserveTry"
  5995. "private"
  5996. "protected"
  5997. "public"
  5998. "static"
  5999. "supported"
  6000. "virtual"
  6001. ))
  6002. "\\)\\)\\s-*")
  6003. "Matches empty jsdoc tags.")
  6004. (defconst js2-jsdoc-link-tag-regexp
  6005. "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
  6006. "Matches a jsdoc link or code tag.")
  6007. (defconst js2-jsdoc-see-tag-regexp
  6008. "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
  6009. "Matches a jsdoc @see tag.")
  6010. (defconst js2-jsdoc-html-tag-regexp
  6011. "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
  6012. "Matches a simple (no attributes) html start- or end-tag.")
  6013. (defun js2-jsdoc-highlight-helper ()
  6014. (js2-set-face (match-beginning 1)
  6015. (match-end 1)
  6016. 'js2-jsdoc-tag)
  6017. (if (match-beginning 2)
  6018. (if (save-excursion
  6019. (goto-char (match-beginning 2))
  6020. (= (char-after) ?{))
  6021. (js2-set-face (1+ (match-beginning 2))
  6022. (1- (match-end 2))
  6023. 'js2-jsdoc-type)
  6024. (js2-set-face (match-beginning 2)
  6025. (match-end 2)
  6026. 'js2-jsdoc-value)))
  6027. (if (match-beginning 3)
  6028. (js2-set-face (match-beginning 3)
  6029. (match-end 3)
  6030. 'js2-jsdoc-value)))
  6031. (defun js2-highlight-jsdoc (ast)
  6032. "Highlight doc comment tags."
  6033. (let ((comments (js2-ast-root-comments ast))
  6034. beg end)
  6035. (save-excursion
  6036. (dolist (node comments)
  6037. (when (eq (js2-comment-node-format node) 'jsdoc)
  6038. ;; Slice off the leading /* and trailing */ in case there
  6039. ;; are tags on the first line
  6040. (setq beg (+ 2 (js2-node-abs-pos node))
  6041. end (+ beg -4 (js2-node-len node)))
  6042. (save-restriction
  6043. (narrow-to-region beg end)
  6044. (dolist (re (list js2-jsdoc-param-tag-regexp
  6045. js2-jsdoc-typed-tag-regexp
  6046. js2-jsdoc-arg-tag-regexp
  6047. js2-jsdoc-link-tag-regexp
  6048. js2-jsdoc-see-tag-regexp
  6049. js2-jsdoc-empty-tag-regexp))
  6050. (goto-char beg)
  6051. (while (re-search-forward re nil t)
  6052. (js2-jsdoc-highlight-helper)))
  6053. ;; simple highlighting for html tags
  6054. (goto-char beg)
  6055. (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
  6056. (js2-set-face (match-beginning 1)
  6057. (match-end 1)
  6058. 'js2-jsdoc-html-tag-delimiter)
  6059. (js2-set-face (match-beginning 2)
  6060. (match-end 2)
  6061. 'js2-jsdoc-html-tag-name)
  6062. (js2-set-face (match-beginning 3)
  6063. (match-end 3)
  6064. 'js2-jsdoc-html-tag-delimiter))))))))
  6065. (defun js2-highlight-assign-targets (_node left right)
  6066. "Highlight function properties and external variables."
  6067. (let (leftpos name)
  6068. ;; highlight vars and props assigned function values
  6069. (when (or (js2-function-node-p right)
  6070. (js2-class-node-p right))
  6071. (cond
  6072. ;; var foo = function() {...}
  6073. ((js2-name-node-p left)
  6074. (setq name left))
  6075. ;; foo.bar.baz = function() {...}
  6076. ((and (js2-prop-get-node-p left)
  6077. (js2-name-node-p (js2-prop-get-node-right left)))
  6078. (setq name (js2-prop-get-node-right left))))
  6079. (when name
  6080. (js2-set-face (setq leftpos (js2-node-abs-pos name))
  6081. (+ leftpos (js2-node-len name))
  6082. 'font-lock-function-name-face
  6083. 'record)))))
  6084. (defun js2-record-name-node (node)
  6085. "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
  6086. later. NODE must be a name node."
  6087. (let ((leftpos (js2-node-abs-pos node)))
  6088. (push (list node js2-current-scope
  6089. leftpos
  6090. (+ leftpos (js2-node-len node)))
  6091. js2-recorded-identifiers)))
  6092. (defun js2-highlight-undeclared-vars ()
  6093. "After entire parse is finished, look for undeclared variable references.
  6094. We have to wait until entire buffer is parsed, since JavaScript permits var
  6095. declarations to occur after they're used.
  6096. Some identifiers may be assumed to be externally defined.
  6097. These externs are not highlighted, even if there is no declaration
  6098. for them in the source code (in the current file).
  6099. The list of externs consists of the following:
  6100. - `js2-ecma262-externs' for basic names from the ECMAScript language standard.
  6101. - Depending on the buffer-local variables `js2-include-*-externs'
  6102. the corresponding `js2-*-externs' to add names for certain environments
  6103. like the browser, Node or Rhino.
  6104. - Two customizable lists `js2-global-externs' and `js2-additional-externs',
  6105. the latter of which should be set per-buffer.
  6106. See especially `js2-additional-externs' for further details about externs."
  6107. (let ((default-externs
  6108. (append js2-ecma-262-externs
  6109. (if (and js2-include-browser-externs
  6110. (>= js2-language-version 200)) js2-harmony-externs)
  6111. (if js2-include-rhino-externs js2-rhino-externs)
  6112. (if js2-include-node-externs js2-node-externs)
  6113. (if (or js2-include-browser-externs js2-include-node-externs)
  6114. js2-typed-array-externs)
  6115. (if js2-include-browser-externs js2-browser-externs)))
  6116. name)
  6117. (dolist (entry js2-recorded-identifiers)
  6118. (cl-destructuring-bind (name-node scope pos end) entry
  6119. (setq name (js2-name-node-name name-node))
  6120. (unless (or (member name js2-global-externs)
  6121. (member name default-externs)
  6122. (member name js2-additional-externs)
  6123. (js2-get-defining-scope scope name pos))
  6124. (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
  6125. 'js2-external-variable))))))
  6126. (defun js2--add-or-update-symbol (symbol inition used vars)
  6127. "Add or update SYMBOL entry in VARS, an hash table.
  6128. SYMBOL is a js2-name-node, INITION either nil, t, or ?P,
  6129. respectively meaning that SYMBOL is a mere declaration, an
  6130. assignment or a function parameter; when USED is t, the symbol
  6131. node is assumed to be an usage and thus added to the list stored
  6132. in the cdr of the entry.
  6133. "
  6134. (let* ((nm (js2-name-node-name symbol))
  6135. (es (js2-node-get-enclosing-scope symbol))
  6136. (ds (js2-get-defining-scope es nm)))
  6137. (when (and ds (not (equal nm "arguments")))
  6138. (let* ((sym (js2-scope-get-symbol ds nm))
  6139. (var (gethash sym vars))
  6140. (err-var-p (js2-catch-node-p ds)))
  6141. (unless inition
  6142. (setq inition err-var-p))
  6143. (if var
  6144. (progn
  6145. (when (and inition (not (equal (car var) ?P)))
  6146. (setcar var inition))
  6147. (when (and used (not (memq symbol (cdr var))))
  6148. (push symbol (cdr var))))
  6149. ;; do not consider the declaration of catch parameter as an usage
  6150. (when (and err-var-p used)
  6151. (setq used nil))
  6152. (puthash sym (cons inition (if used (list symbol))) vars))))))
  6153. (defun js2--collect-target-symbols (node strict)
  6154. "Collect the `js-name-node' symbols declared in NODE and return a list of them.
  6155. NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'.
  6156. When STRICT, signal an error if NODE is not one of the expected types."
  6157. (let (targets)
  6158. (cond
  6159. ((js2-name-node-p node)
  6160. (push node targets))
  6161. ((js2-array-node-p node)
  6162. (dolist (elt (js2-array-node-elems node))
  6163. (when elt
  6164. (setq elt (cond ((js2-infix-node-p elt) ;; default (=)
  6165. (js2-infix-node-left elt))
  6166. ((js2-unary-node-p elt) ;; rest (...)
  6167. (js2-unary-node-operand elt))
  6168. (t elt)))
  6169. (setq targets (append (js2--collect-target-symbols elt strict)
  6170. targets)))))
  6171. ((js2-object-node-p node)
  6172. (dolist (elt (js2-object-node-elems node))
  6173. (let ((subexpr (cond
  6174. ((and (js2-infix-node-p elt)
  6175. (= js2-ASSIGN (js2-infix-node-type elt)))
  6176. ;; Destructuring with default argument.
  6177. (js2-infix-node-left elt))
  6178. ((and (js2-infix-node-p elt)
  6179. (= js2-COLON (js2-infix-node-type elt)))
  6180. ;; In regular destructuring {a: aa, b: bb},
  6181. ;; the var is on the right. In abbreviated
  6182. ;; destructuring {a, b}, right == left.
  6183. (js2-infix-node-right elt))
  6184. ((and (js2-unary-node-p elt)
  6185. (= js2-TRIPLEDOT (js2-unary-node-type elt)))
  6186. ;; Destructuring with spread.
  6187. (js2-unary-node-operand elt)))))
  6188. (when subexpr
  6189. (setq targets (append
  6190. (js2--collect-target-symbols subexpr strict)
  6191. targets))))))
  6192. ((js2-assign-node-p node)
  6193. (setq targets (append (js2--collect-target-symbols
  6194. (js2-assign-node-left node) strict)
  6195. targets)))
  6196. (strict
  6197. (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
  6198. (js2-node-len node))
  6199. nil))
  6200. targets))
  6201. (defun js2--examine-variable (parent node var-init-node)
  6202. "Examine the usage of the variable NODE, a js2-name-node.
  6203. PARENT is its direct ancestor and VAR-INIT-NODE is the node to be
  6204. examined: return a list of three values, respectively if the
  6205. variable is declared and/or assigned or whether it is simply a
  6206. key of a literal object."
  6207. (let ((target (js2-var-init-node-target var-init-node))
  6208. declared assigned object-key)
  6209. (setq declared (memq node (js2--collect-target-symbols target nil)))
  6210. ;; Is there an initializer for the declared variable?
  6211. (when (js2-var-init-node-initializer var-init-node)
  6212. (setq assigned declared)
  6213. ;; Determine if the name is actually a literal object key that we shall
  6214. ;; ignore later
  6215. (when (and (not declared)
  6216. (js2-object-prop-node-p parent)
  6217. (eq node (js2-object-prop-node-left parent)))
  6218. (setq object-key t)))
  6219. ;; Maybe this is a for loop and the variable is one of its iterators?
  6220. (unless assigned
  6221. (let* ((gp (js2-node-parent parent))
  6222. (ggp (if gp (js2-node-parent gp))))
  6223. (when (and ggp (js2-for-in-node-p ggp))
  6224. (setq assigned (memq node
  6225. (cl-loop
  6226. for kid in (js2-var-decl-node-kids
  6227. (js2-for-in-node-iterator ggp))
  6228. with syms = '()
  6229. do
  6230. (setq syms (append syms
  6231. (js2--collect-target-symbols
  6232. (js2-var-init-node-target kid)
  6233. nil)))
  6234. finally return syms))))))
  6235. (list declared assigned object-key)))
  6236. (defun js2--classify-variable (parent node vars)
  6237. "Classify the single variable NODE, a js2-name-node."
  6238. (let ((function-param (and (js2-function-node-p parent)
  6239. (memq node (js2-function-node-params parent)))))
  6240. (if (js2-prop-get-node-p parent)
  6241. ;; If we are within a prop-get, e.g. the "bar" in "foo.bar",
  6242. ;; just mark "foo" as used
  6243. (let ((left (js2-prop-get-node-left parent)))
  6244. (when (js2-name-node-p left)
  6245. (js2--add-or-update-symbol left nil t vars)))
  6246. ;; If the node is the external name of an export-binding-node, and
  6247. ;; it is different from the local name, ignore it
  6248. (when (or (not (js2-export-binding-node-p parent))
  6249. (not (and (eq (js2-export-binding-node-extern-name parent) node)
  6250. (not (eq (js2-export-binding-node-local-name parent) node)))))
  6251. (let ((granparent parent)
  6252. var-init-node
  6253. assign-node
  6254. object-key ; is name actually an object prop key?
  6255. declared ; is it declared in narrowest scope?
  6256. assigned ; does it get assigned or initialized?
  6257. (used (null function-param)))
  6258. ;; Determine the closest var-init-node and assign-node: this
  6259. ;; is needed because the name may be within a "destructured"
  6260. ;; declaration/assignment, so we cannot just take its parent
  6261. (while (and granparent (not (js2-scope-p granparent)))
  6262. (cond
  6263. ((js2-var-init-node-p granparent)
  6264. (when (null var-init-node)
  6265. (setq var-init-node granparent)))
  6266. ((js2-assign-node-p granparent)
  6267. (when (null assign-node)
  6268. (setq assign-node granparent))))
  6269. (setq granparent (js2-node-parent granparent)))
  6270. ;; If we are within a var-init-node, determine if the name is
  6271. ;; declared and initialized
  6272. (when var-init-node
  6273. (let ((result (js2--examine-variable parent node var-init-node)))
  6274. (setq declared (car result)
  6275. assigned (cadr result)
  6276. object-key (car (cddr result)))))
  6277. ;; Ignore literal object keys, which are not really variables
  6278. (unless object-key
  6279. (when function-param
  6280. (setq assigned ?P))
  6281. (when (null assigned)
  6282. (cond
  6283. ((js2-for-in-node-p parent)
  6284. (setq assigned (eq node (js2-for-in-node-iterator parent))
  6285. used (not assigned)))
  6286. ((js2-function-node-p parent)
  6287. (setq assigned t
  6288. used (js2-wrapper-function-p parent)))
  6289. ((js2-export-binding-node-p parent)
  6290. (if (js2-import-clause-node-p (js2-node-parent parent))
  6291. (setq declared t
  6292. assigned t)
  6293. (setq used t)))
  6294. ((js2-namespace-import-node-p parent)
  6295. (setq assigned t
  6296. used nil))
  6297. (assign-node
  6298. (setq assigned (memq node
  6299. (js2--collect-target-symbols
  6300. (js2-assign-node-left assign-node)
  6301. nil))
  6302. used (not assigned)))))
  6303. (when declared
  6304. (setq used nil))
  6305. (js2--add-or-update-symbol node assigned used vars)))))))
  6306. (defun js2--classify-variables ()
  6307. "Collect and classify variables declared or used within js2-mode-ast.
  6308. Traverse the whole ast tree returning a summary of the variables
  6309. usage as an hash-table, keyed by their corresponding symbol table
  6310. entry.
  6311. Each variable is described by a tuple where the car is a flag
  6312. indicating whether the variable has been initialized and the cdr
  6313. is a possibly empty list of name nodes where it is used. External
  6314. symbols, i.e. those not present in the whole scopes hierarchy,
  6315. are ignored."
  6316. (let ((vars (make-hash-table :test #'eq :size 100)))
  6317. (js2-visit-ast
  6318. js2-mode-ast
  6319. (lambda (node end-p)
  6320. (when (and (null end-p) (js2-name-node-p node))
  6321. (let ((parent (js2-node-parent node)))
  6322. (when parent
  6323. (js2--classify-variable parent node vars))))
  6324. t))
  6325. vars))
  6326. (defun js2--get-name-node (node)
  6327. (cond
  6328. ((js2-name-node-p node) node)
  6329. ((js2-function-node-p node)
  6330. (js2-function-node-name node))
  6331. ((js2-class-node-p node)
  6332. (js2-class-node-name node))
  6333. ((js2-comp-loop-node-p node)
  6334. (js2-comp-loop-node-iterator node))
  6335. (t node)))
  6336. (defun js2--highlight-unused-variable (symbol info)
  6337. (let ((name (js2-symbol-name symbol))
  6338. (inited (car info))
  6339. (refs (cdr info))
  6340. pos len)
  6341. (unless (and inited refs)
  6342. (if refs
  6343. (dolist (ref refs)
  6344. (setq pos (js2-node-abs-pos ref))
  6345. (setq len (js2-name-node-len ref))
  6346. (js2-report-warning "msg.uninitialized.variable" name pos len
  6347. 'js2-warning))
  6348. (when (or js2-warn-about-unused-function-arguments
  6349. (not (eq inited ?P)))
  6350. (let* ((symn (js2-symbol-ast-node symbol))
  6351. (namen (js2--get-name-node symn)))
  6352. (unless (js2-node-top-level-decl-p namen)
  6353. (setq pos (js2-node-abs-pos namen))
  6354. (setq len (js2-name-node-len namen))
  6355. (js2-report-warning "msg.unused.variable" name pos len
  6356. 'js2-warning))))))))
  6357. (defun js2-highlight-unused-variables ()
  6358. "Highlight unused variables."
  6359. (let ((vars (js2--classify-variables)))
  6360. (maphash #'js2--highlight-unused-variable vars)))
  6361. ;;;###autoload
  6362. (define-minor-mode js2-highlight-unused-variables-mode
  6363. "Toggle highlight of unused variables."
  6364. :lighter ""
  6365. (if js2-highlight-unused-variables-mode
  6366. (add-hook 'js2-post-parse-callbacks
  6367. #'js2-highlight-unused-variables nil t)
  6368. (remove-hook 'js2-post-parse-callbacks
  6369. #'js2-highlight-unused-variables t)))
  6370. (defun js2-add-additional-externs (externs)
  6371. (setq js2-additional-externs
  6372. (nconc externs
  6373. js2-additional-externs)))
  6374. (defun js2-get-jslint-comment-identifiers (comment)
  6375. (js2-reparse)
  6376. (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
  6377. when (and (eq 'block (js2-comment-node-format node))
  6378. (save-excursion
  6379. (goto-char (js2-node-abs-pos node))
  6380. (looking-at (concat "/\\* *" comment "\\(?: \\|$\\)"))))
  6381. append (js2-get-jslint-comment-identifiers-in
  6382. (match-end 0)
  6383. (js2-node-abs-end node))))
  6384. (defun js2-get-jslint-comment-identifiers-in (beg end)
  6385. (let (res)
  6386. (save-excursion
  6387. (goto-char beg)
  6388. (while (re-search-forward js2-mode-identifier-re end t)
  6389. (let ((match (match-string 0)))
  6390. (unless (member match '("true" "false"))
  6391. (push match res)))))
  6392. (nreverse res)))
  6393. (defun js2-apply-jslint-globals ()
  6394. (js2-add-additional-externs (js2-get-jslint-globals)))
  6395. (defun js2-get-jslint-globals ()
  6396. (js2-get-jslint-comment-identifiers "global"))
  6397. (defun js2-apply-jslint-declaration-externs ()
  6398. (js2-add-additional-externs (js2-get-jslint-declaration-externs)))
  6399. (defvar js2-jslint-declaration-externs
  6400. `(("browser" . ,(mapcar 'symbol-name
  6401. '(Audio clearInterval clearTimeout document
  6402. event history Image location name
  6403. navigator Option screen setInterval
  6404. setTimeout XMLHttpRequest)))
  6405. ("node" . ,(mapcar 'symbol-name
  6406. '(Buffer clearImmediate clearInterval
  6407. clearTimeout console exports global module
  6408. process querystring require setImmediate
  6409. setInterval setTimeout __dirname
  6410. __filename)))
  6411. ("es6" . ,(mapcar 'symbol-name
  6412. '(ArrayBuffer DataView Float32Array
  6413. Float64Array Int8Array Int16Array Int32Array
  6414. Intl Map Promise Proxy Reflect Set Symbol
  6415. System Uint8Array Uint8ClampedArray
  6416. Uint16Array Uint32Array WeakMap WeakSet)))
  6417. ("couch" . ,(mapcar 'symbol-name
  6418. '(emit getRow isArray log provides
  6419. registerType require send start sum
  6420. toJSON)))
  6421. ("devel" . ,(mapcar 'symbol-name
  6422. '(alert confirm console Debug opera prompt
  6423. WSH)))))
  6424. (defun js2-get-jslint-declaration-externs ()
  6425. (apply 'append
  6426. (mapcar (lambda (identifier)
  6427. (cdr (assoc identifier
  6428. js2-jslint-declaration-externs)))
  6429. (js2-get-jslint-comment-identifiers "jslint"))))
  6430. ;;; IMenu support
  6431. ;; We currently only support imenu, but eventually should support speedbar and
  6432. ;; possibly other browsing mechanisms.
  6433. ;; The basic strategy is to identify function assignment targets of the form
  6434. ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
  6435. ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
  6436. ;; for imenu after parsing is finished.
  6437. ;; A `foo.bar.baz' assignment target may be expressed in many ways in
  6438. ;; JavaScript, and the general problem is undecidable. However, several forms
  6439. ;; are readily recognizable at parse-time; the forms we attempt to recognize
  6440. ;; include:
  6441. ;; function foo() -- function declaration
  6442. ;; foo = function() -- function expression assigned to variable
  6443. ;; foo.bar.baz = function() -- function expr assigned to nested property-get
  6444. ;; foo = {bar: function()} -- fun prop in object literal assigned to var
  6445. ;; foo = {bar: {baz: function()}} -- inside nested object literal
  6446. ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
  6447. ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
  6448. ;; foo = {get bar() {...}} -- getter/setter in obj literal
  6449. ;; function foo() {function bar() {...}} -- nested function
  6450. ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
  6451. ;; This list boils down to a few forms that can be combined recursively.
  6452. ;; Top-level named function declarations include both the left-hand (name)
  6453. ;; and the right-hand (function value) expressions needed to produce an imenu
  6454. ;; entry. The other "right-hand" forms we need to look for are:
  6455. ;; - functions declared as props/getters/setters in object literals
  6456. ;; - nested named function declarations
  6457. ;; The "left-hand" expressions that functions can be assigned to include:
  6458. ;; - local/global variables
  6459. ;; - nested property-get expressions like a.b.c.d
  6460. ;; - element gets like foo[10] or foo['bar'] where the index
  6461. ;; expression can be trivially converted to a property name. They
  6462. ;; effectively then become property gets.
  6463. ;; All the different definition types are canonicalized into the form
  6464. ;; foo.bar.baz = position-of-function-keyword
  6465. ;; We need to build a trie-like structure for imenu. As an example,
  6466. ;; consider the following JavaScript code:
  6467. ;; a = function() {...} // function at position 5
  6468. ;; b = function() {...} // function at position 25
  6469. ;; foo = function() {...} // function at position 100
  6470. ;; foo.bar = function() {...} // function at position 200
  6471. ;; foo.bar.baz = function() {...} // function at position 300
  6472. ;; foo.bar.zab = function() {...} // function at position 400
  6473. ;; During parsing we accumulate an entry for each definition in
  6474. ;; the variable `js2-imenu-recorder', like so:
  6475. ;; '((fn a 5)
  6476. ;; (fn b 25)
  6477. ;; (fn foo 100)
  6478. ;; (fn foo bar 200)
  6479. ;; (fn foo bar baz 300)
  6480. ;; (fn foo bar zab 400))
  6481. ;; Where 'fn' is the respective function node.
  6482. ;; After parsing these entries are merged into this alist-trie:
  6483. ;; '((a . 1)
  6484. ;; (b . 2)
  6485. ;; (foo (<definition> . 3)
  6486. ;; (bar (<definition> . 6)
  6487. ;; (baz . 100)
  6488. ;; (zab . 200))))
  6489. ;; Note the wacky need for a <definition> name. The token can be anything
  6490. ;; that isn't a valid JavaScript identifier, because you might make foo
  6491. ;; a function and then start setting properties on it that are also functions.
  6492. (defun js2-prop-node-name (node)
  6493. "Return the name of a node that may be a property-get/property-name.
  6494. If NODE is not a valid name-node, string-node or integral number-node,
  6495. returns nil. Otherwise returns the string name/value of the node."
  6496. (cond
  6497. ((js2-name-node-p node)
  6498. (js2-name-node-name node))
  6499. ((js2-string-node-p node)
  6500. (js2-string-node-value node))
  6501. ((and (js2-number-node-p node)
  6502. (string-match "^[0-9]+$" (js2-number-node-value node)))
  6503. (js2-number-node-value node))
  6504. ((eq (js2-node-type node) js2-THIS)
  6505. "this")
  6506. ((eq (js2-node-type node) js2-SUPER)
  6507. "super")))
  6508. (defun js2-node-qname-component (node)
  6509. "Return the name of this node, if it contributes to a qname.
  6510. Returns nil if the node doesn't contribute."
  6511. (copy-sequence
  6512. (or (js2-prop-node-name node)
  6513. (cond
  6514. ((and (js2-function-node-p node)
  6515. (js2-function-node-name node))
  6516. (js2-name-node-name (js2-function-node-name node)))
  6517. ((js2-computed-prop-name-node-p node)
  6518. "[computed]")))))
  6519. (defun js2-record-imenu-entry (fn-node qname pos)
  6520. "Add an entry to `js2-imenu-recorder'.
  6521. FN-NODE should be the current item's function node.
  6522. Associate FN-NODE with its QNAME for later lookup.
  6523. This is used in postprocessing the chain list. For each chain, we find
  6524. the parent function, look up its qname, then prepend a copy of it to the chain."
  6525. (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
  6526. (unless js2-imenu-function-map
  6527. (setq js2-imenu-function-map (make-hash-table :test 'eq)))
  6528. (puthash fn-node qname js2-imenu-function-map))
  6529. (defun js2-record-imenu-functions (node &optional var)
  6530. "Record function definitions for imenu.
  6531. NODE is a function node or an object literal.
  6532. VAR, if non-nil, is the expression that NODE is being assigned to.
  6533. When passed arguments of wrong type, does nothing."
  6534. (when js2-parse-ide-mode
  6535. (let ((fun-p (js2-function-node-p node))
  6536. qname fname-node)
  6537. (cond
  6538. ;; non-anonymous function declaration?
  6539. ((and fun-p
  6540. (not var)
  6541. (setq fname-node (js2-function-node-name node)))
  6542. (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
  6543. ;; for remaining forms, compute left-side tree branch first
  6544. ((and var (setq qname (js2-compute-nested-prop-get var)))
  6545. (cond
  6546. ;; foo.bar.baz = function
  6547. (fun-p
  6548. (js2-record-imenu-entry node qname (js2-node-pos node)))
  6549. ;; foo.bar.baz = object-literal
  6550. ;; look for nested functions: {a: {b: function() {...} }}
  6551. ((js2-object-node-p node)
  6552. ;; Node position here is still absolute, since the parser
  6553. ;; passes the assignment target and value expressions
  6554. ;; to us before they are added as children of the assignment node.
  6555. (js2-record-object-literal node qname (js2-node-pos node)))))))))
  6556. (defun js2-compute-nested-prop-get (node)
  6557. "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
  6558. component nodes as a list. Otherwise return nil. Element-gets are treated
  6559. as property-gets if the index expression is a string, or a positive integer."
  6560. (let (left right head)
  6561. (cond
  6562. ((or (js2-name-node-p node)
  6563. (js2-this-or-super-node-p node))
  6564. (list node))
  6565. ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
  6566. ((js2-prop-get-node-p node) ; foo.bar
  6567. (setq left (js2-prop-get-node-left node)
  6568. right (js2-prop-get-node-right node))
  6569. (if (setq head (js2-compute-nested-prop-get left))
  6570. (nconc head (list right))))
  6571. ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
  6572. (setq left (js2-elem-get-node-target node)
  6573. right (js2-elem-get-node-element node))
  6574. (if (or (js2-string-node-p right) ; ['bar']
  6575. (and (js2-number-node-p right) ; [10]
  6576. (string-match "^[0-9]+$"
  6577. (js2-number-node-value right))))
  6578. (if (setq head (js2-compute-nested-prop-get left))
  6579. (nconc head (list right))))))))
  6580. (defun js2-record-object-literal (node qname pos)
  6581. "Recursively process an object literal looking for functions.
  6582. NODE is an object literal that is the right-hand child of an assignment
  6583. expression. QNAME is a list of nodes representing the assignment target,
  6584. e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
  6585. POS is the absolute position of the node.
  6586. We do a depth-first traversal of NODE. For any functions we find,
  6587. we append the property name to QNAME, then call `js2-record-imenu-entry'."
  6588. (let (right)
  6589. (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
  6590. (when (js2-infix-node-p e)
  6591. (let ((left (js2-infix-node-left e))
  6592. ;; Element positions are relative to the parent position.
  6593. (pos (+ pos (js2-node-pos e))))
  6594. (cond
  6595. ;; foo: function() {...}
  6596. ((js2-function-node-p (setq right (js2-infix-node-right e)))
  6597. (when (js2-prop-node-name left)
  6598. ;; As a policy decision, we record the position of the property,
  6599. ;; not the position of the `function' keyword, since the property
  6600. ;; is effectively the name of the function.
  6601. (js2-record-imenu-entry right (append qname (list left)) pos)))
  6602. ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
  6603. ((js2-object-node-p right)
  6604. (js2-record-object-literal right
  6605. (append qname (list (js2-infix-node-left e)))
  6606. (+ pos (js2-node-pos right))))))))))
  6607. (defun js2-node-top-level-decl-p (node)
  6608. "Return t if NODE's name is defined in the top-level scope.
  6609. Also returns t if NODE's name is not defined in any scope, since it implies
  6610. that it's an external variable, which must also be in the top-level scope."
  6611. (let* ((name (js2-prop-node-name node))
  6612. (this-scope (js2-node-get-enclosing-scope node))
  6613. defining-scope)
  6614. (cond
  6615. ((js2-this-or-super-node-p node)
  6616. nil)
  6617. ((null this-scope)
  6618. t)
  6619. ((setq defining-scope (js2-get-defining-scope this-scope name))
  6620. (js2-ast-root-p defining-scope))
  6621. (t t))))
  6622. (defun js2-wrapper-function-p (node)
  6623. "Return t if NODE is a function expression that's immediately invoked.
  6624. NODE must be `js2-function-node'."
  6625. (let ((parent (js2-node-parent node)))
  6626. (or
  6627. ;; function(){...}();
  6628. (and (js2-call-node-p parent)
  6629. (eq node (js2-call-node-target parent)))
  6630. (and (js2-paren-node-p parent)
  6631. ;; (function(){...})();
  6632. (or (js2-call-node-p (setq parent (js2-node-parent parent)))
  6633. ;; (function(){...}).call(this);
  6634. (and (js2-prop-get-node-p parent)
  6635. (member (js2-name-node-name (js2-prop-get-node-right parent))
  6636. '("call" "apply"))
  6637. (js2-call-node-p (js2-node-parent parent))))))))
  6638. (defun js2-browse-postprocess-chains ()
  6639. "Modify function-declaration name chains after parsing finishes.
  6640. Some of the information is only available after the parse tree is complete.
  6641. For instance, processing a nested scope requires a parent function node."
  6642. (let (result fn parent-qname p elem)
  6643. (dolist (entry js2-imenu-recorder)
  6644. ;; function node goes first
  6645. (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
  6646. ;; Examine head's defining scope:
  6647. ;; Pre-processed chain, or top-level/external, keep as-is.
  6648. (if (or (stringp head) (js2-node-top-level-decl-p head))
  6649. (push chain result)
  6650. (when (js2-this-or-super-node-p head)
  6651. (setq chain (cdr chain))) ; discard this-node
  6652. (when (setq fn (js2-node-parent-script-or-fn current-fn))
  6653. (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
  6654. (when (eq parent-qname 'not-found)
  6655. ;; anonymous function expressions are not recorded
  6656. ;; during the parse, so we need to handle this case here
  6657. (setq parent-qname
  6658. (if (js2-wrapper-function-p fn)
  6659. (let ((grandparent (js2-node-parent-script-or-fn fn)))
  6660. (if (js2-ast-root-p grandparent)
  6661. nil
  6662. (gethash grandparent js2-imenu-function-map 'skip)))
  6663. 'skip))
  6664. (puthash fn parent-qname js2-imenu-function-map))
  6665. (if (eq parent-qname 'skip)
  6666. ;; We don't show it, let's record that fact.
  6667. (remhash current-fn js2-imenu-function-map)
  6668. ;; Prepend parent fn qname to this chain.
  6669. (let ((qname (append parent-qname chain)))
  6670. (puthash current-fn (butlast qname) js2-imenu-function-map)
  6671. (push qname result)))))))
  6672. ;; Collect chains obtained by third-party code.
  6673. (let (js2-imenu-recorder)
  6674. (run-hooks 'js2-build-imenu-callbacks)
  6675. (dolist (entry js2-imenu-recorder)
  6676. (push (cdr entry) result)))
  6677. ;; Finally replace each node in each chain with its name.
  6678. (dolist (chain result)
  6679. (setq p chain)
  6680. (while p
  6681. (if (js2-node-p (setq elem (car p)))
  6682. (setcar p (js2-node-qname-component elem)))
  6683. (setq p (cdr p))))
  6684. result))
  6685. ;; Merge name chains into a trie-like tree structure of nested lists.
  6686. ;; To simplify construction of the trie, we first build it out using the rule
  6687. ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
  6688. ;; [key, num-or-list]. The second element can be a number; if so, this key
  6689. ;; is a leaf-node with only one value. (I.e. there is only one declaration
  6690. ;; associated with the key at this level.) Otherwise the second element is
  6691. ;; a list of pairs, with the rule applied recursively. This symmetry permits
  6692. ;; a simple recursive formulation.
  6693. ;;
  6694. ;; js2-mode is building the data structure for imenu. The imenu documentation
  6695. ;; claims that it's the structure above, but in practice it wants the children
  6696. ;; at the same list level as the key for that level, which is how I've drawn
  6697. ;; the "Expected final result" above. We'll postprocess the trie to remove the
  6698. ;; list wrapper around the children at each level.
  6699. ;;
  6700. ;; A completed nested imenu-alist entry looks like this:
  6701. ;; '(("foo"
  6702. ;; ("<definition>" . 7)
  6703. ;; ("bar"
  6704. ;; ("a" . 40)
  6705. ;; ("b" . 60))))
  6706. ;;
  6707. ;; In particular, the documentation for `imenu--index-alist' says that
  6708. ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
  6709. ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
  6710. (defun js2-treeify (lst)
  6711. "Convert (a b c d) to (a ((b ((c d)))))."
  6712. (if (null (cddr lst)) ; list length <= 2
  6713. lst
  6714. (list (car lst) (list (js2-treeify (cdr lst))))))
  6715. (defun js2-build-alist-trie (chains trie)
  6716. "Merge declaration name chains into a trie-like alist structure for imenu.
  6717. CHAINS is the qname chain list produced during parsing. TRIE is a
  6718. list of elements built up so far."
  6719. (let (head tail pos branch kids)
  6720. (dolist (chain chains)
  6721. (setq head (car chain)
  6722. tail (cdr chain)
  6723. pos (if (numberp (car tail)) (car tail))
  6724. branch (js2-find-if (lambda (n)
  6725. (string= (car n) head))
  6726. trie)
  6727. kids (cl-second branch))
  6728. (cond
  6729. ;; case 1: this key isn't in the trie yet
  6730. ((null branch)
  6731. (if trie
  6732. (setcdr (last trie) (list (js2-treeify chain)))
  6733. (setq trie (list (js2-treeify chain)))))
  6734. ;; case 2: key is present with a single number entry: replace w/ list
  6735. ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
  6736. ;; ("<definition>" 20)))
  6737. ((numberp kids)
  6738. (setcar (cdr branch)
  6739. (list (list "<definition-1>" kids)
  6740. (if pos
  6741. (list "<definition-2>" pos)
  6742. (js2-treeify tail)))))
  6743. ;; case 3: key is there (with kids), and we're a number entry
  6744. (pos
  6745. (setcdr (last kids)
  6746. (list
  6747. (list (format "<definition-%d>"
  6748. (1+ (cl-loop for kid in kids
  6749. count (eq ?< (aref (car kid) 0)))))
  6750. pos))))
  6751. ;; case 4: key is there with kids, need to merge in our chain
  6752. (t
  6753. (js2-build-alist-trie (list tail) kids))))
  6754. trie))
  6755. (defun js2-flatten-trie (trie)
  6756. "Convert TRIE to imenu-format.
  6757. Recurses through nodes, and for each one whose second element is a list,
  6758. appends the list's flattened elements to the current element. Also
  6759. changes the tails into conses. For instance, this pre-flattened trie
  6760. '(a ((b 20)
  6761. (c ((d 30)
  6762. (e 40)))))
  6763. becomes
  6764. '(a (b . 20)
  6765. (c (d . 30)
  6766. (e . 40)))
  6767. Note that the root of the trie has no key, just a list of chains.
  6768. This is also true for the value of any key with multiple children,
  6769. e.g. key 'c' in the example above."
  6770. (cond
  6771. ((listp (car trie))
  6772. (mapcar #'js2-flatten-trie trie))
  6773. (t
  6774. (if (numberp (cl-second trie))
  6775. (cons (car trie) (cl-second trie))
  6776. ;; else pop list and append its kids
  6777. (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
  6778. (defun js2-build-imenu-index ()
  6779. "Turn `js2-imenu-recorder' into an imenu data structure."
  6780. (when (eq js2-imenu-recorder 'empty)
  6781. (setq js2-imenu-recorder nil))
  6782. (let* ((chains (js2-browse-postprocess-chains))
  6783. (result (js2-build-alist-trie chains nil)))
  6784. (js2-flatten-trie result)))
  6785. (defun js2-test-print-chains (chains)
  6786. "Print a list of qname chains.
  6787. Each element of CHAINS is a list of the form (NODE [NODE *] pos);
  6788. i.e. one or more nodes, and an integer position as the list tail."
  6789. (mapconcat (lambda (chain)
  6790. (concat "("
  6791. (mapconcat (lambda (elem)
  6792. (if (js2-node-p elem)
  6793. (or (js2-node-qname-component elem)
  6794. "nil")
  6795. (number-to-string elem)))
  6796. chain
  6797. " ")
  6798. ")"))
  6799. chains
  6800. "\n"))
  6801. ;;; Parser
  6802. (defconst js2-version "1.8.5"
  6803. "Version of JavaScript supported.")
  6804. (defun js2-record-face (face &optional token)
  6805. "Record a style run of FACE for TOKEN or the current token."
  6806. (unless token (setq token (js2-current-token)))
  6807. (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
  6808. (defsubst js2-node-end (n)
  6809. "Computes the absolute end of node N.
  6810. Use with caution! Assumes `js2-node-pos' is -absolute-, which
  6811. is only true until the node is added to its parent; i.e., while parsing."
  6812. (+ (js2-node-pos n)
  6813. (js2-node-len n)))
  6814. (defun js2-record-comment (token)
  6815. "Record a comment in `js2-scanned-comments'."
  6816. (let ((ct (js2-token-comment-type token))
  6817. (beg (js2-token-beg token))
  6818. (end (js2-token-end token)))
  6819. (push (make-js2-comment-node :len (- end beg)
  6820. :format ct)
  6821. js2-scanned-comments)
  6822. (when js2-parse-ide-mode
  6823. (js2-record-face (if (eq ct 'jsdoc)
  6824. 'font-lock-doc-face
  6825. 'font-lock-comment-face)
  6826. token)
  6827. (when (memq ct '(html preprocessor))
  6828. ;; Tell cc-engine the bounds of the comment.
  6829. (js2-record-text-property beg (1- end) 'c-in-sws t)))))
  6830. (defun js2-peek-token (&optional modifier)
  6831. "Return the next token type without consuming it.
  6832. If `js2-ti-lookahead' is positive, return the type of next token
  6833. from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
  6834. (if (not (zerop js2-ti-lookahead))
  6835. (js2-token-type
  6836. (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
  6837. (let ((tt (js2-get-token-internal modifier)))
  6838. (js2-unget-token)
  6839. tt)))
  6840. (defalias 'js2-next-token 'js2-get-token)
  6841. (defun js2-match-token (match &optional dont-unget)
  6842. "Get next token and return t if it matches MATCH, a bytecode.
  6843. Returns nil and consumes nothing if MATCH is not the next token."
  6844. (if (/= (js2-get-token) match)
  6845. (ignore (unless dont-unget (js2-unget-token)))
  6846. t))
  6847. (defun js2-match-contextual-kwd (name)
  6848. "Consume and return t if next token is `js2-NAME', and its
  6849. string is NAME. Returns nil and keeps current token otherwise."
  6850. (if (js2-contextual-kwd-p (progn (js2-get-token)
  6851. (js2-current-token))
  6852. name)
  6853. (progn (js2-record-face 'font-lock-keyword-face) t)
  6854. (js2-unget-token)
  6855. nil))
  6856. (defun js2-contextual-kwd-p (token name)
  6857. "Return t if TOKEN is `js2-NAME', and its string is NAME."
  6858. (and (= (js2-token-type token) js2-NAME)
  6859. (string= (js2-token-string token) name)))
  6860. (defun js2-match-async-function ()
  6861. (when (and (js2-contextual-kwd-p (js2-current-token) "async")
  6862. (= (js2-peek-token) js2-FUNCTION))
  6863. (js2-record-face 'font-lock-keyword-face)
  6864. (js2-get-token)
  6865. t))
  6866. (defun js2-match-async-arrow-function ()
  6867. (and (js2-contextual-kwd-p (js2-current-token) "async")
  6868. (/= (js2-peek-token) js2-FUNCTION)))
  6869. (defsubst js2-inside-function ()
  6870. (cl-plusp js2-nesting-of-function))
  6871. (defsubst js2-inside-async-function ()
  6872. (and (js2-inside-function)
  6873. (js2-function-node-async js2-current-script-or-fn)))
  6874. (defun js2-parse-await-maybe (tt)
  6875. "Parse \"await\" as an AwaitExpression, if it is one."
  6876. (and (= tt js2-NAME)
  6877. (js2-contextual-kwd-p (js2-current-token) "await")
  6878. ;; Per the proposal, AwaitExpression consists of "await"
  6879. ;; followed by a UnaryExpression. So look ahead for one.
  6880. (let ((ts-state (make-js2-ts-state))
  6881. (recorded-identifiers js2-recorded-identifiers)
  6882. (parsed-errors js2-parsed-errors)
  6883. (current-token (js2-current-token))
  6884. (beg (js2-current-token-beg))
  6885. (end (js2-current-token-end))
  6886. pn)
  6887. (js2-get-token)
  6888. (setq pn (js2-make-unary beg js2-AWAIT 'js2-parse-unary-expr))
  6889. (if (= (js2-node-type (js2-unary-node-operand pn)) js2-ERROR)
  6890. ;; The parse failed, so pretend like nothing happened and restore
  6891. ;; the previous parsing state.
  6892. (progn
  6893. (js2-ts-seek ts-state)
  6894. (setq js2-recorded-identifiers recorded-identifiers
  6895. js2-parsed-errors parsed-errors)
  6896. ;; And ensure the caller knows about the failure.
  6897. nil)
  6898. ;; The parse was successful, so process and return the "await".
  6899. (js2-record-face 'font-lock-keyword-face current-token)
  6900. (unless (js2-inside-async-function)
  6901. (js2-report-error "msg.bad.await" nil
  6902. beg (- end beg)))
  6903. pn))))
  6904. (defun js2-get-prop-name-token ()
  6905. (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
  6906. (defun js2-match-prop-name ()
  6907. "Consume token and return t if next token is a valid property name.
  6908. If `js2-language-version' is >= 180, a keyword or reserved word
  6909. is considered valid name as well."
  6910. (if (eq js2-NAME (js2-get-prop-name-token))
  6911. t
  6912. (js2-unget-token)
  6913. nil))
  6914. (defun js2-must-match-prop-name (msg-id &optional pos len)
  6915. (if (js2-match-prop-name)
  6916. t
  6917. (js2-report-error msg-id nil pos len)
  6918. nil))
  6919. (defun js2-peek-token-or-eol ()
  6920. "Return js2-EOL if the next token immediately follows a newline.
  6921. Else returns the next token. Used in situations where we don't
  6922. consider certain token types valid if they are preceded by a newline.
  6923. One example is the postfix ++ or -- operator, which has to be on the
  6924. same line as its operand."
  6925. (let ((tt (js2-get-token))
  6926. (follows-eol (js2-token-follows-eol-p (js2-current-token))))
  6927. (js2-unget-token)
  6928. (if follows-eol
  6929. js2-EOL
  6930. tt)))
  6931. (defun js2-must-match (token msg-id &optional pos len)
  6932. "Match next token to token code TOKEN, or record a syntax error.
  6933. MSG-ID is the error message to report if the match fails.
  6934. Returns t on match, nil if no match."
  6935. (if (js2-match-token token t)
  6936. t
  6937. (js2-report-error msg-id nil pos len)
  6938. (js2-unget-token)
  6939. nil))
  6940. (defun js2-must-match-name (msg-id)
  6941. (if (js2-match-token js2-NAME t)
  6942. t
  6943. (if (eq (js2-current-token-type) js2-RESERVED)
  6944. (js2-report-error "msg.reserved.id" (js2-current-token-string))
  6945. (js2-report-error msg-id)
  6946. (js2-unget-token))
  6947. nil))
  6948. (defun js2-set-requires-activation ()
  6949. (if (js2-function-node-p js2-current-script-or-fn)
  6950. (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
  6951. (defun js2-check-activation-name (name _token)
  6952. (when (js2-inside-function)
  6953. ;; skip language-version 1.2 check from Rhino
  6954. (if (or (string= "arguments" name)
  6955. (and js2-compiler-activation-names ; only used in codegen
  6956. (gethash name js2-compiler-activation-names)))
  6957. (js2-set-requires-activation))))
  6958. (defun js2-set-is-generator ()
  6959. (let ((fn-node js2-current-script-or-fn))
  6960. (when (and (js2-function-node-p fn-node)
  6961. (not (js2-function-node-generator-type fn-node)))
  6962. (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
  6963. (defun js2-must-have-xml ()
  6964. (unless js2-compiler-xml-available
  6965. (js2-report-error "msg.XML.not.available")))
  6966. (defun js2-push-scope (scope)
  6967. "Push SCOPE, a `js2-scope', onto the lexical scope chain."
  6968. (cl-assert (js2-scope-p scope))
  6969. (cl-assert (null (js2-scope-parent-scope scope)))
  6970. (cl-assert (not (eq js2-current-scope scope)))
  6971. (setf (js2-scope-parent-scope scope) js2-current-scope
  6972. js2-current-scope scope))
  6973. (defsubst js2-pop-scope ()
  6974. (setq js2-current-scope
  6975. (js2-scope-parent-scope js2-current-scope)))
  6976. (defun js2-enter-loop (loop-node)
  6977. (push loop-node js2-loop-set)
  6978. (push loop-node js2-loop-and-switch-set)
  6979. (js2-push-scope loop-node)
  6980. ;; Tell the current labeled statement (if any) its statement,
  6981. ;; and set the jump target of the first label to the loop.
  6982. ;; These are used in `js2-parse-continue' to verify that the
  6983. ;; continue target is an actual labeled loop. (And for codegen.)
  6984. (when js2-labeled-stmt
  6985. (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
  6986. (js2-label-node-loop (car (js2-labeled-stmt-node-labels
  6987. js2-labeled-stmt))) loop-node)))
  6988. (defun js2-exit-loop ()
  6989. (pop js2-loop-set)
  6990. (pop js2-loop-and-switch-set)
  6991. (js2-pop-scope))
  6992. (defsubst js2-enter-switch (switch-node)
  6993. (js2-push-scope switch-node)
  6994. (push switch-node js2-loop-and-switch-set))
  6995. (defsubst js2-exit-switch ()
  6996. (js2-pop-scope)
  6997. (pop js2-loop-and-switch-set))
  6998. (defsubst js2-get-directive (node)
  6999. "Return NODE's value if it is a directive, nil otherwise.
  7000. A directive is an otherwise-meaningless expression statement
  7001. consisting of a string literal, such as \"use strict\"."
  7002. (and (js2-expr-stmt-node-p node)
  7003. (js2-string-node-p (setq node (js2-expr-stmt-node-expr node)))
  7004. (js2-string-node-value node)))
  7005. (defun js2-parse (&optional buf cb)
  7006. "Tell the js2 parser to parse a region of JavaScript.
  7007. BUF is a buffer or buffer name containing the code to parse.
  7008. Call `narrow-to-region' first to parse only part of the buffer.
  7009. The returned AST root node is given some additional properties:
  7010. `node-count' - total number of nodes in the AST
  7011. `buffer' - BUF. The buffer it refers to may change or be killed,
  7012. so the value is not necessarily reliable.
  7013. An optional callback CB can be specified to report parsing
  7014. progress. If `(functionp CB)' returns t, it will be called with
  7015. the current line number once before parsing begins, then again
  7016. each time the lexer reaches a new line number.
  7017. CB can also be a list of the form `(symbol cb ...)' to specify
  7018. multiple callbacks with different criteria. Each symbol is a
  7019. criterion keyword, and the following element is the callback to
  7020. call
  7021. :line - called whenever the line number changes
  7022. :token - called for each new token consumed
  7023. The list of criteria could be extended to include entering or
  7024. leaving a statement, an expression, or a function definition."
  7025. (if (and cb (not (functionp cb)))
  7026. (error "criteria callbacks not yet implemented"))
  7027. (let ((inhibit-point-motion-hooks t)
  7028. (js2-compiler-xml-available (>= js2-language-version 160))
  7029. ;; This is a recursive-descent parser, so give it a big stack.
  7030. (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
  7031. (max-specpdl-size (max max-specpdl-size 3000))
  7032. (case-fold-search nil)
  7033. ast)
  7034. (with-current-buffer (or buf (current-buffer))
  7035. (setq js2-scanned-comments nil
  7036. js2-parsed-errors nil
  7037. js2-parsed-warnings nil
  7038. js2-imenu-recorder nil
  7039. js2-imenu-function-map nil
  7040. js2-label-set nil)
  7041. (js2-init-scanner)
  7042. (setq ast (js2-do-parse))
  7043. (unless js2-ts-hit-eof
  7044. (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
  7045. (setf (js2-ast-root-errors ast) js2-parsed-errors
  7046. (js2-ast-root-warnings ast) js2-parsed-warnings)
  7047. ;; if we didn't find any declarations, put a dummy in this list so we
  7048. ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
  7049. (unless js2-imenu-recorder
  7050. (setq js2-imenu-recorder 'empty))
  7051. (run-hooks 'js2-parse-finished-hook)
  7052. ast)))
  7053. ;; Corresponds to Rhino's Parser.parse() method.
  7054. (defun js2-do-parse ()
  7055. "Parse current buffer starting from current point.
  7056. Scanner should be initialized."
  7057. (let ((pos js2-ts-cursor)
  7058. (end js2-ts-cursor) ; in case file is empty
  7059. root n tt
  7060. (in-directive-prologue t)
  7061. (js2-in-use-strict-directive js2-in-use-strict-directive)
  7062. directive)
  7063. ;; initialize buffer-local parsing vars
  7064. (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
  7065. js2-current-script-or-fn root
  7066. js2-current-scope root
  7067. js2-nesting-of-function 0
  7068. js2-labeled-stmt nil
  7069. js2-recorded-identifiers nil ; for js2-highlight
  7070. js2-in-use-strict-directive js2-mode-assume-strict)
  7071. (while (/= (setq tt (js2-get-token)) js2-EOF)
  7072. (if (= tt js2-FUNCTION)
  7073. (progn
  7074. (setq n (if js2-called-by-compile-function
  7075. (js2-parse-function-expr)
  7076. (js2-parse-function-stmt))))
  7077. ;; not a function - parse a statement
  7078. (js2-unget-token)
  7079. (setq n (js2-parse-statement))
  7080. (when in-directive-prologue
  7081. (setq directive (js2-get-directive n))
  7082. (cond
  7083. ((null directive)
  7084. (setq in-directive-prologue nil))
  7085. ((string= directive "use strict")
  7086. (setq js2-in-use-strict-directive t)))))
  7087. ;; add function or statement to script
  7088. (setq end (js2-node-end n))
  7089. (js2-block-node-push root n))
  7090. ;; add comments to root in lexical order
  7091. (when js2-scanned-comments
  7092. ;; if we find a comment beyond end of normal kids, use its end
  7093. (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
  7094. (dolist (comment js2-scanned-comments)
  7095. (push comment (js2-ast-root-comments root))
  7096. (js2-node-add-children root comment)))
  7097. (setf (js2-node-len root) (- end pos))
  7098. (setq js2-mode-ast root) ; Make sure this is available for callbacks.
  7099. ;; Give extensions a chance to muck with things before highlighting starts.
  7100. (let ((js2-additional-externs js2-additional-externs))
  7101. (js2-filter-parsed-warnings)
  7102. (save-excursion
  7103. (run-hooks 'js2-post-parse-callbacks))
  7104. (js2-highlight-undeclared-vars))
  7105. root))
  7106. (defun js2-filter-parsed-warnings ()
  7107. "Remove `js2-parsed-warnings' elements that match `js2-ignored-warnings'."
  7108. (when js2-ignored-warnings
  7109. (setq js2-parsed-warnings
  7110. (cl-remove-if
  7111. (lambda (warning)
  7112. (let ((msg (caar warning)))
  7113. (member msg js2-ignored-warnings)))
  7114. js2-parsed-warnings)))
  7115. js2-parsed-warnings)
  7116. (defun js2-parse-function-closure-body (fn-node)
  7117. "Parse a JavaScript 1.8 function closure body."
  7118. (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
  7119. (if js2-ts-hit-eof
  7120. (js2-report-error "msg.no.brace.body" nil
  7121. (js2-node-pos fn-node)
  7122. (- js2-ts-cursor (js2-node-pos fn-node)))
  7123. (js2-node-add-children fn-node
  7124. (setf (js2-function-node-body fn-node)
  7125. (js2-parse-expr t))))))
  7126. (defun js2-parse-function-body (fn-node)
  7127. (js2-must-match js2-LC "msg.no.brace.body"
  7128. (js2-node-pos fn-node)
  7129. (- js2-ts-cursor (js2-node-pos fn-node)))
  7130. (let ((pos (js2-current-token-beg)) ; LC position
  7131. (pn (make-js2-block-node)) ; starts at LC position
  7132. tt
  7133. end
  7134. not-in-directive-prologue
  7135. node
  7136. directive)
  7137. (cl-incf js2-nesting-of-function)
  7138. (unwind-protect
  7139. (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
  7140. (= tt js2-EOF)
  7141. (= tt js2-RC)))
  7142. (js2-block-node-push
  7143. pn
  7144. (if (/= tt js2-FUNCTION)
  7145. (if not-in-directive-prologue
  7146. (js2-parse-statement)
  7147. (setq node (js2-parse-statement)
  7148. directive (js2-get-directive node))
  7149. (cond
  7150. ((null directive)
  7151. (setq not-in-directive-prologue t))
  7152. ((string= directive "use strict")
  7153. ;; Back up and reparse the function, because new rules apply
  7154. ;; to the function name and parameters.
  7155. (when (not js2-in-use-strict-directive)
  7156. (setq js2-in-use-strict-directive t)
  7157. (throw 'reparse t))))
  7158. node)
  7159. (js2-get-token)
  7160. (js2-parse-function-stmt))))
  7161. (cl-decf js2-nesting-of-function))
  7162. (setq end (js2-current-token-end)) ; assume no curly and leave at current token
  7163. (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
  7164. (setq end (js2-current-token-end)))
  7165. (setf (js2-node-pos pn) pos
  7166. (js2-node-len pn) (- end pos))
  7167. (setf (js2-function-node-body fn-node) pn)
  7168. (js2-node-add-children fn-node pn)
  7169. pn))
  7170. (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
  7171. "Declare and fontify destructuring parameters inside NODE.
  7172. NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'.
  7173. Return a list of `js2-name-node' nodes representing the symbols
  7174. declared; probably to check them for errors."
  7175. (let ((name-nodes (js2--collect-target-symbols node t)))
  7176. (dolist (node name-nodes)
  7177. (let (leftpos)
  7178. (js2-define-symbol decl-type (js2-name-node-name node)
  7179. node ignore-not-in-block)
  7180. (when face
  7181. (js2-set-face (setq leftpos (js2-node-abs-pos node))
  7182. (+ leftpos (js2-node-len node))
  7183. face 'record))))
  7184. name-nodes))
  7185. (defvar js2-illegal-strict-identifiers
  7186. '("eval" "arguments")
  7187. "Identifiers not allowed as variables in strict mode.")
  7188. (defun js2-check-strict-identifier (name-node)
  7189. "Check that NAME-NODE makes a legal strict mode identifier."
  7190. (when js2-in-use-strict-directive
  7191. (let ((param-name (js2-name-node-name name-node)))
  7192. (when (member param-name js2-illegal-strict-identifiers)
  7193. (js2-report-error "msg.bad.id.strict" param-name
  7194. (js2-node-abs-pos name-node) (js2-node-len name-node))))))
  7195. (defun js2-check-strict-function-params (preceding-params params)
  7196. "Given PRECEDING-PARAMS in a function's parameter list, check
  7197. for strict mode errors caused by PARAMS."
  7198. (when js2-in-use-strict-directive
  7199. (dolist (param params)
  7200. (let ((param-name (js2-name-node-name param)))
  7201. (js2-check-strict-identifier param)
  7202. (when (cl-some (lambda (param)
  7203. (string= (js2-name-node-name param) param-name))
  7204. preceding-params)
  7205. (js2-report-error "msg.dup.param.strict" param-name
  7206. (js2-node-abs-pos param) (js2-node-len param)))))))
  7207. (defun js2-parse-function-params (function-type fn-node pos)
  7208. "Parse the parameters of a function of FUNCTION-TYPE
  7209. represented by FN-NODE at POS."
  7210. (if (js2-match-token js2-RP)
  7211. (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
  7212. (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
  7213. (eq (js2-current-token-type) js2-NAME)))
  7214. params param
  7215. param-name-nodes new-param-name-nodes
  7216. rest-param-at)
  7217. (when paren-free-arrow
  7218. (js2-unget-token))
  7219. (cl-loop for tt = (js2-peek-token)
  7220. do
  7221. (cond
  7222. ;; destructuring param
  7223. ((and (not paren-free-arrow)
  7224. (or (= tt js2-LB) (= tt js2-LC)))
  7225. (js2-get-token)
  7226. (setq param (js2-parse-destruct-primary-expr)
  7227. new-param-name-nodes (js2-define-destruct-symbols
  7228. param js2-LP 'js2-function-param))
  7229. (js2-check-strict-function-params param-name-nodes new-param-name-nodes)
  7230. (setq param-name-nodes (append param-name-nodes new-param-name-nodes)))
  7231. ;; variable name
  7232. (t
  7233. (when (and (>= js2-language-version 200)
  7234. (not paren-free-arrow)
  7235. (js2-match-token js2-TRIPLEDOT)
  7236. (not rest-param-at))
  7237. ;; to report errors if there are more parameters
  7238. (setq rest-param-at (length params)))
  7239. (js2-must-match-name "msg.no.parm")
  7240. (js2-record-face 'js2-function-param)
  7241. (setq param (js2-create-name-node))
  7242. (js2-define-symbol js2-LP (js2-current-token-string) param)
  7243. (js2-check-strict-function-params param-name-nodes (list param))
  7244. (setq param-name-nodes (append param-name-nodes (list param)))))
  7245. ;; default parameter value
  7246. (when (and (not rest-param-at)
  7247. (>= js2-language-version 200)
  7248. (js2-match-token js2-ASSIGN))
  7249. (cl-assert (not paren-free-arrow))
  7250. (let* ((pos (js2-node-pos param))
  7251. (tt (js2-current-token-type))
  7252. (op-pos (- (js2-current-token-beg) pos))
  7253. (left param)
  7254. (right (js2-parse-assign-expr))
  7255. (len (- (js2-node-end right) pos)))
  7256. (setq param (make-js2-assign-node
  7257. :type tt :pos pos :len len :op-pos op-pos
  7258. :left left :right right))
  7259. (js2-node-add-children param left right)))
  7260. (push param params)
  7261. (when (and rest-param-at (> (length params) (1+ rest-param-at)))
  7262. (js2-report-error "msg.param.after.rest" nil
  7263. (js2-node-pos param) (js2-node-len param)))
  7264. while
  7265. (and (js2-match-token js2-COMMA)
  7266. (or (< js2-language-version 200)
  7267. (not (= js2-RP (js2-peek-token))))))
  7268. (when (and (not paren-free-arrow)
  7269. (js2-must-match js2-RP "msg.no.paren.after.parms"))
  7270. (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
  7271. (when rest-param-at
  7272. (setf (js2-function-node-rest-p fn-node) t))
  7273. (dolist (p params)
  7274. (js2-node-add-children fn-node p)
  7275. (push p (js2-function-node-params fn-node))))))
  7276. (defun js2-check-inconsistent-return-warning (fn-node name)
  7277. "Possibly show inconsistent-return warning.
  7278. Last token scanned is the close-curly for the function body."
  7279. (when (and js2-mode-show-strict-warnings
  7280. js2-strict-inconsistent-return-warning
  7281. (not (js2-has-consistent-return-usage
  7282. (js2-function-node-body fn-node))))
  7283. ;; Have it extend from close-curly to bol or beginning of block.
  7284. (let ((pos (save-excursion
  7285. (goto-char (js2-current-token-end))
  7286. (max (js2-node-abs-pos (js2-function-node-body fn-node))
  7287. (point-at-bol))))
  7288. (end (js2-current-token-end)))
  7289. (if (cl-plusp (js2-name-node-length name))
  7290. (js2-add-strict-warning "msg.no.return.value"
  7291. (js2-name-node-name name) pos end)
  7292. (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
  7293. (defun js2-parse-function-stmt (&optional async-p)
  7294. (let ((pos (js2-current-token-beg))
  7295. (star-p (js2-match-token js2-MUL)))
  7296. (js2-must-match-name "msg.unnamed.function.stmt")
  7297. (let ((name (js2-create-name-node t))
  7298. pn member-expr)
  7299. (cond
  7300. ((js2-match-token js2-LP)
  7301. (js2-parse-function 'FUNCTION_STATEMENT pos star-p async-p name))
  7302. (js2-allow-member-expr-as-function-name
  7303. (setq member-expr (js2-parse-member-expr-tail nil name))
  7304. (js2-parse-highlight-member-expr-fn-name member-expr)
  7305. (js2-must-match js2-LP "msg.no.paren.parms")
  7306. (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p async-p)
  7307. (js2-function-node-member-expr pn) member-expr)
  7308. pn)
  7309. (t
  7310. (js2-report-error "msg.no.paren.parms")
  7311. (make-js2-error-node))))))
  7312. (defun js2-parse-async-function-stmt ()
  7313. (js2-parse-function-stmt t))
  7314. (defun js2-parse-function-expr (&optional async-p)
  7315. (let ((pos (js2-current-token-beg))
  7316. (star-p (js2-match-token js2-MUL))
  7317. name)
  7318. (when (js2-match-token js2-NAME)
  7319. (setq name (js2-create-name-node t)))
  7320. (js2-must-match js2-LP "msg.no.paren.parms")
  7321. (js2-parse-function 'FUNCTION_EXPRESSION pos star-p async-p name)))
  7322. (defun js2-parse-function-internal (function-type pos star-p &optional async-p name)
  7323. (let (fn-node lp)
  7324. (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
  7325. (setq lp (js2-current-token-beg)))
  7326. (setf fn-node (make-js2-function-node :pos pos
  7327. :name name
  7328. :form function-type
  7329. :lp (if lp (- lp pos))
  7330. :generator-type (and star-p 'STAR)
  7331. :async async-p))
  7332. (when name
  7333. (js2-set-face (js2-node-pos name) (js2-node-end name)
  7334. 'font-lock-function-name-face 'record)
  7335. (when (and (eq function-type 'FUNCTION_STATEMENT)
  7336. (cl-plusp (js2-name-node-length name)))
  7337. ;; Function statements define a symbol in the enclosing scope
  7338. (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
  7339. (when js2-in-use-strict-directive
  7340. (js2-check-strict-identifier name)))
  7341. (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
  7342. ;; 1. Nested functions are not affected by the dynamic scope flag
  7343. ;; as dynamic scope is already a parent of their scope.
  7344. ;; 2. Functions defined under the with statement also immune to
  7345. ;; this setup, in which case dynamic scope is ignored in favor
  7346. ;; of the with object.
  7347. (setf (js2-function-node-ignore-dynamic fn-node) t))
  7348. ;; dynamically bind all the per-function variables
  7349. (let ((js2-current-script-or-fn fn-node)
  7350. (js2-current-scope fn-node)
  7351. (js2-nesting-of-with 0)
  7352. (js2-end-flags 0)
  7353. js2-label-set
  7354. js2-loop-set
  7355. js2-loop-and-switch-set)
  7356. (js2-parse-function-params function-type fn-node pos)
  7357. (when (eq function-type 'FUNCTION_ARROW)
  7358. (js2-must-match js2-ARROW "msg.bad.arrow.args"))
  7359. (if (and (>= js2-language-version 180)
  7360. (/= (js2-peek-token) js2-LC))
  7361. (js2-parse-function-closure-body fn-node)
  7362. (js2-parse-function-body fn-node))
  7363. (js2-check-inconsistent-return-warning fn-node name)
  7364. (when name
  7365. (js2-node-add-children fn-node name)
  7366. ;; Function expressions define a name only in the body of the
  7367. ;; function, and only if not hidden by a parameter name
  7368. (when (and (eq function-type 'FUNCTION_EXPRESSION)
  7369. (null (js2-scope-get-symbol js2-current-scope
  7370. (js2-name-node-name name))))
  7371. (js2-define-symbol js2-FUNCTION
  7372. (js2-name-node-name name)
  7373. fn-node))
  7374. (when (eq function-type 'FUNCTION_STATEMENT)
  7375. (js2-record-imenu-functions fn-node))))
  7376. (setf (js2-node-len fn-node) (- (js2-current-token-end) pos))
  7377. ;; Rhino doesn't do this, but we need it for finding undeclared vars.
  7378. ;; We wait until after parsing the function to set its parent scope,
  7379. ;; since `js2-define-symbol' needs the defining-scope check to stop
  7380. ;; at the function boundary when checking for redeclarations.
  7381. (setf (js2-scope-parent-scope fn-node) js2-current-scope)
  7382. fn-node))
  7383. (defun js2-parse-function (function-type pos star-p &optional async-p name)
  7384. "Function parser. FUNCTION-TYPE is a symbol, POS is the
  7385. beginning of the first token (function keyword, unless it's an
  7386. arrow function), NAME is js2-name-node."
  7387. (let ((continue t)
  7388. ts-state
  7389. fn-node
  7390. ;; Preserve strict state outside this function.
  7391. (js2-in-use-strict-directive js2-in-use-strict-directive))
  7392. ;; Parse multiple times if a new strict mode directive is discovered in the
  7393. ;; function body, as new rules will be retroactively applied to the legality
  7394. ;; of function names and parameters.
  7395. (while continue
  7396. (setq ts-state (make-js2-ts-state))
  7397. (setq continue (catch 'reparse
  7398. (setq fn-node (js2-parse-function-internal
  7399. function-type pos star-p async-p name))
  7400. ;; Don't continue.
  7401. nil))
  7402. (when continue
  7403. (js2-ts-seek ts-state)))
  7404. fn-node))
  7405. (defun js2-parse-statements (&optional parent)
  7406. "Parse a statement list. Last token consumed must be js2-LC.
  7407. PARENT can be a `js2-block-node', in which case the statements are
  7408. appended to PARENT. Otherwise a new `js2-block-node' is created
  7409. and returned.
  7410. This function does not match the closing js2-RC: the caller
  7411. matches the RC so it can provide a suitable error message if not
  7412. matched. This means it's up to the caller to set the length of
  7413. the node to include the closing RC. The node start pos is set to
  7414. the absolute buffer start position, and the caller should fix it
  7415. up to be relative to the parent node. All children of this block
  7416. node are given relative start positions and correct lengths."
  7417. (let ((pn (or parent (make-js2-block-node)))
  7418. tt)
  7419. (while (and (> (setq tt (js2-peek-token)) js2-EOF)
  7420. (/= tt js2-RC))
  7421. (js2-block-node-push pn (js2-parse-statement)))
  7422. pn))
  7423. (defun js2-parse-statement ()
  7424. (let (pn beg end)
  7425. ;; coarse-grained user-interrupt check - needs work
  7426. (and js2-parse-interruptable-p
  7427. (zerop (% (cl-incf js2-parse-stmt-count)
  7428. js2-statements-per-pause))
  7429. (input-pending-p)
  7430. (throw 'interrupted t))
  7431. (setq pn (js2-statement-helper))
  7432. ;; no-side-effects warning check
  7433. (unless (js2-node-has-side-effects pn)
  7434. (setq end (js2-node-end pn))
  7435. (save-excursion
  7436. (goto-char end)
  7437. (setq beg (max (js2-node-pos pn) (point-at-bol))))
  7438. (js2-add-strict-warning "msg.no.side.effects" nil beg end))
  7439. pn))
  7440. ;; These correspond to the switch cases in Parser.statementHelper
  7441. (defconst js2-parsers
  7442. (let ((parsers (make-vector js2-num-tokens
  7443. #'js2-parse-expr-stmt)))
  7444. (aset parsers js2-BREAK #'js2-parse-break)
  7445. (aset parsers js2-CLASS #'js2-parse-class-stmt)
  7446. (aset parsers js2-CONST #'js2-parse-const-var)
  7447. (aset parsers js2-CONTINUE #'js2-parse-continue)
  7448. (aset parsers js2-DEBUGGER #'js2-parse-debugger)
  7449. (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
  7450. (aset parsers js2-DO #'js2-parse-do)
  7451. (aset parsers js2-EXPORT #'js2-parse-export)
  7452. (aset parsers js2-FOR #'js2-parse-for)
  7453. (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
  7454. (aset parsers js2-IF #'js2-parse-if)
  7455. (aset parsers js2-IMPORT #'js2-parse-import)
  7456. (aset parsers js2-LC #'js2-parse-block)
  7457. (aset parsers js2-LET #'js2-parse-let-stmt)
  7458. (aset parsers js2-NAME #'js2-parse-name-or-label)
  7459. (aset parsers js2-RETURN #'js2-parse-ret-yield)
  7460. (aset parsers js2-SEMI #'js2-parse-semi)
  7461. (aset parsers js2-SWITCH #'js2-parse-switch)
  7462. (aset parsers js2-THROW #'js2-parse-throw)
  7463. (aset parsers js2-TRY #'js2-parse-try)
  7464. (aset parsers js2-VAR #'js2-parse-const-var)
  7465. (aset parsers js2-WHILE #'js2-parse-while)
  7466. (aset parsers js2-WITH #'js2-parse-with)
  7467. (aset parsers js2-YIELD #'js2-parse-ret-yield)
  7468. parsers)
  7469. "A vector mapping token types to parser functions.")
  7470. (defun js2-parse-warn-missing-semi (beg end)
  7471. (and js2-mode-show-strict-warnings
  7472. js2-strict-missing-semi-warning
  7473. (js2-add-strict-warning
  7474. "msg.missing.semi" nil
  7475. ;; back up to beginning of statement or line
  7476. (max beg (save-excursion
  7477. (goto-char end)
  7478. (point-at-bol)))
  7479. end)))
  7480. (defconst js2-no-semi-insertion
  7481. (list js2-IF
  7482. js2-SWITCH
  7483. js2-WHILE
  7484. js2-DO
  7485. js2-FOR
  7486. js2-TRY
  7487. js2-WITH
  7488. js2-LC
  7489. js2-ERROR
  7490. js2-SEMI
  7491. js2-CLASS
  7492. js2-FUNCTION
  7493. js2-EXPORT)
  7494. "List of tokens that don't do automatic semicolon insertion.")
  7495. (defconst js2-autoinsert-semi-and-warn
  7496. (list js2-ERROR js2-EOF js2-RC))
  7497. (defun js2-statement-helper ()
  7498. (let* ((tt (js2-get-token))
  7499. (first-tt tt)
  7500. (async-stmt (js2-match-async-function))
  7501. (parser (if (= tt js2-ERROR)
  7502. #'js2-parse-semi
  7503. (if async-stmt
  7504. #'js2-parse-async-function-stmt
  7505. (aref js2-parsers tt))))
  7506. pn)
  7507. ;; If the statement is set, then it's been told its label by now.
  7508. (and js2-labeled-stmt
  7509. (js2-labeled-stmt-node-stmt js2-labeled-stmt)
  7510. (setq js2-labeled-stmt nil))
  7511. (setq pn (funcall parser))
  7512. ;; Don't do auto semi insertion for certain statement types.
  7513. (unless (or (memq first-tt js2-no-semi-insertion)
  7514. (js2-labeled-stmt-node-p pn)
  7515. async-stmt)
  7516. (js2-auto-insert-semicolon pn))
  7517. pn))
  7518. (defun js2-auto-insert-semicolon (pn)
  7519. (let* ((tt (js2-get-token))
  7520. (pos (js2-node-pos pn)))
  7521. (cond
  7522. ((= tt js2-SEMI)
  7523. ;; extend the node bounds to include the semicolon.
  7524. (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
  7525. ((memq tt js2-autoinsert-semi-and-warn)
  7526. (js2-unget-token) ; Not ';', do not consume.
  7527. ;; Autoinsert ;
  7528. (js2-parse-warn-missing-semi pos (js2-node-end pn)))
  7529. (t
  7530. (if (not (js2-token-follows-eol-p (js2-current-token)))
  7531. ;; Report error if no EOL or autoinsert ';' otherwise
  7532. (js2-report-error "msg.no.semi.stmt")
  7533. (js2-parse-warn-missing-semi pos (js2-node-end pn)))
  7534. (js2-unget-token) ; Not ';', do not consume.
  7535. ))))
  7536. (defun js2-parse-condition ()
  7537. "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
  7538. The parens are discarded and the expression node is returned.
  7539. The `pos' field of the return value is set to an absolute position
  7540. that must be fixed up by the caller.
  7541. Return value is a list (EXPR LP RP), with absolute paren positions."
  7542. (let (pn lp rp)
  7543. (if (js2-must-match js2-LP "msg.no.paren.cond")
  7544. (setq lp (js2-current-token-beg)))
  7545. (setq pn (js2-parse-expr))
  7546. (if (js2-must-match js2-RP "msg.no.paren.after.cond")
  7547. (setq rp (js2-current-token-beg)))
  7548. ;; Report strict warning on code like "if (a = 7) ..."
  7549. (if (and js2-strict-cond-assign-warning
  7550. (js2-assign-node-p pn))
  7551. (js2-add-strict-warning "msg.equal.as.assign" nil
  7552. (js2-node-pos pn)
  7553. (+ (js2-node-pos pn)
  7554. (js2-node-len pn))))
  7555. (list pn lp rp)))
  7556. (defun js2-parse-if ()
  7557. "Parser for if-statement. Last matched token must be js2-IF."
  7558. (let ((pos (js2-current-token-beg))
  7559. cond if-true if-false else-pos end pn)
  7560. (setq cond (js2-parse-condition)
  7561. if-true (js2-parse-statement)
  7562. if-false (if (js2-match-token js2-ELSE)
  7563. (progn
  7564. (setq else-pos (- (js2-current-token-beg) pos))
  7565. (js2-parse-statement)))
  7566. end (js2-node-end (or if-false if-true))
  7567. pn (make-js2-if-node :pos pos
  7568. :len (- end pos)
  7569. :condition (car cond)
  7570. :then-part if-true
  7571. :else-part if-false
  7572. :else-pos else-pos
  7573. :lp (js2-relpos (cl-second cond) pos)
  7574. :rp (js2-relpos (cl-third cond) pos)))
  7575. (js2-node-add-children pn (car cond) if-true if-false)
  7576. pn))
  7577. (defun js2-parse-import ()
  7578. "Parse import statement. The current token must be js2-IMPORT."
  7579. (unless (js2-ast-root-p js2-current-scope)
  7580. (js2-report-error "msg.mod.import.decl.at.top.level"))
  7581. (let ((beg (js2-current-token-beg)))
  7582. (cond ((js2-match-token js2-STRING)
  7583. (make-js2-import-node
  7584. :pos beg
  7585. :len (- (js2-current-token-end) beg)
  7586. :module-id (js2-current-token-string)))
  7587. (t
  7588. (let* ((import-clause (js2-parse-import-clause))
  7589. (from-clause (and import-clause (js2-parse-from-clause)))
  7590. (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
  7591. (node (make-js2-import-node
  7592. :pos beg
  7593. :len (- (js2-current-token-end) beg)
  7594. :import import-clause
  7595. :from from-clause
  7596. :module-id module-id)))
  7597. (when import-clause
  7598. (js2-node-add-children node import-clause))
  7599. (when from-clause
  7600. (js2-node-add-children node from-clause))
  7601. node)))))
  7602. (defun js2-parse-import-clause ()
  7603. "Parse the bindings in an import statement.
  7604. This can take many forms:
  7605. ImportedDefaultBinding -> 'foo'
  7606. NameSpaceImport -> '* as lib'
  7607. NamedImports -> '{foo as bar, bang}'
  7608. ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
  7609. ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
  7610. Try to match namespace imports and named imports first because nothing can
  7611. come after them. If it is an imported default binding, then it could have named
  7612. imports or a namespace import that follows it.
  7613. "
  7614. (let* ((beg (js2-current-token-beg))
  7615. (clause (make-js2-import-clause-node
  7616. :pos beg))
  7617. (children (list)))
  7618. (cond
  7619. ((js2-match-token js2-MUL)
  7620. (let ((ns-import (js2-parse-namespace-import)))
  7621. (when ns-import
  7622. (let ((name-node (js2-namespace-import-node-name ns-import)))
  7623. (js2-define-symbol
  7624. js2-LET (js2-name-node-name name-node) name-node t))
  7625. (setf (js2-import-clause-node-namespace-import clause) ns-import)
  7626. (push ns-import children))))
  7627. ((js2-match-token js2-LC)
  7628. (let ((imports (js2-parse-export-bindings t)))
  7629. (setf (js2-import-clause-node-named-imports clause) imports)
  7630. (dolist (import imports)
  7631. (push import children)
  7632. (let ((name-node (js2-export-binding-node-local-name import)))
  7633. (when name-node
  7634. (js2-define-symbol
  7635. js2-LET (js2-name-node-name name-node) name-node t))))))
  7636. ((= (js2-peek-token) js2-NAME)
  7637. (let ((binding (js2-maybe-parse-export-binding t)))
  7638. (let ((node-name (js2-export-binding-node-local-name binding)))
  7639. (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
  7640. (setf (js2-import-clause-node-default-binding clause) binding)
  7641. (push binding children))
  7642. (when (js2-match-token js2-COMMA)
  7643. (cond
  7644. ((js2-match-token js2-MUL)
  7645. (let ((ns-import (js2-parse-namespace-import)))
  7646. (let ((name-node (js2-namespace-import-node-name ns-import)))
  7647. (js2-define-symbol
  7648. js2-LET (js2-name-node-name name-node) name-node t))
  7649. (setf (js2-import-clause-node-namespace-import clause) ns-import)
  7650. (push ns-import children)))
  7651. ((js2-match-token js2-LC)
  7652. (let ((imports (js2-parse-export-bindings t)))
  7653. (setf (js2-import-clause-node-named-imports clause) imports)
  7654. (dolist (import imports)
  7655. (push import children)
  7656. (let ((name-node (js2-export-binding-node-local-name import)))
  7657. (when name-node
  7658. (js2-define-symbol
  7659. js2-LET (js2-name-node-name name-node) name-node t))))))
  7660. (t (js2-report-error "msg.syntax")))))
  7661. (t (js2-report-error "msg.mod.declaration.after.import")))
  7662. (setf (js2-node-len clause) (- (js2-current-token-end) beg))
  7663. (apply #'js2-node-add-children clause children)
  7664. clause))
  7665. (defun js2-parse-namespace-import ()
  7666. "Parse a namespace import expression such as '* as bar'.
  7667. The current token must be js2-MUL."
  7668. (let ((beg (js2-current-token-beg)))
  7669. (cond
  7670. ((js2-match-contextual-kwd "as")
  7671. (when (js2-must-match-prop-name "msg.syntax")
  7672. (let ((node (make-js2-namespace-import-node
  7673. :pos beg
  7674. :len (- (js2-current-token-end) beg)
  7675. :name (make-js2-name-node
  7676. :pos (js2-current-token-beg)
  7677. :len (- (js2-current-token-end)
  7678. (js2-current-token-beg))
  7679. :name (js2-current-token-string)))))
  7680. (js2-node-add-children node (js2-namespace-import-node-name node))
  7681. node)))
  7682. (t
  7683. (js2-unget-token)
  7684. (js2-report-error "msg.syntax")
  7685. nil))))
  7686. (defun js2-parse-from-clause ()
  7687. "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
  7688. (if (js2-match-contextual-kwd "from")
  7689. (let ((beg (js2-current-token-beg)))
  7690. (cond
  7691. ((js2-match-token js2-STRING)
  7692. (make-js2-from-clause-node
  7693. :pos beg
  7694. :len (- (js2-current-token-end) beg)
  7695. :module-id (js2-current-token-string)
  7696. :metadata-p nil))
  7697. ((js2-match-token js2-THIS)
  7698. (when (js2-must-match-name "msg.mod.spec.after.from")
  7699. (if (equal "module" (js2-current-token-string))
  7700. (make-js2-from-clause-node
  7701. :pos beg
  7702. :len (- (js2-current-token-end) beg)
  7703. :module-id "this"
  7704. :metadata-p t)
  7705. (js2-unget-token)
  7706. (js2-unget-token)
  7707. (js2-report-error "msg.mod.spec.after.from")
  7708. nil)))
  7709. (t (js2-report-error "msg.mod.spec.after.from") nil)))
  7710. (js2-report-error "msg.mod.from.after.import.spec.set")
  7711. nil))
  7712. (defun js2-parse-export-bindings (&optional import-p)
  7713. "Parse a list of export binding expressions such as {}, {foo, bar}, and
  7714. {foo as bar, baz as bang}. The current token must be
  7715. js2-LC. Return a lisp list of js2-export-binding-node"
  7716. (let ((bindings (list)))
  7717. (while
  7718. (let ((binding (js2-maybe-parse-export-binding import-p)))
  7719. (when binding
  7720. (push binding bindings))
  7721. (js2-match-token js2-COMMA)))
  7722. (when (js2-must-match js2-RC (if import-p
  7723. "msg.mod.rc.after.import.spec.list"
  7724. "msg.mod.rc.after.export.spec.list"))
  7725. (reverse bindings))))
  7726. (defun js2-maybe-parse-export-binding (&optional import-p)
  7727. "Attempt to parse a binding expression found inside an import/export statement.
  7728. This can take the form of either as single js2-NAME token as in 'foo' or as in a
  7729. rebinding expression 'bar as foo'. If it matches, it will return an instance of
  7730. js2-export-binding-node and consume all the tokens. If it does not match, it
  7731. consumes no tokens."
  7732. (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
  7733. (beg (js2-current-token-beg))
  7734. (extern-name-len (js2-current-token-len))
  7735. (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
  7736. (aref js2-kwd-tokens (js2-current-token-type)))))
  7737. (if extern-name
  7738. (if (js2-match-contextual-kwd "as")
  7739. (let ((name
  7740. (or
  7741. (and (js2-match-token js2-DEFAULT) "default")
  7742. (and (js2-match-token js2-NAME) (js2-current-token-string)))))
  7743. (if name
  7744. (let ((node (make-js2-export-binding-node
  7745. :pos beg
  7746. :len (- (js2-current-token-end) beg)
  7747. :local-name (make-js2-name-node
  7748. :name name
  7749. :pos (js2-current-token-beg)
  7750. :len (js2-current-token-len))
  7751. :extern-name (make-js2-name-node
  7752. :name extern-name
  7753. :pos beg
  7754. :len extern-name-len))))
  7755. (js2-node-add-children
  7756. node
  7757. (js2-export-binding-node-local-name node)
  7758. (js2-export-binding-node-extern-name node))
  7759. (if import-p
  7760. (js2-set-face (js2-current-token-beg) (js2-current-token-end)
  7761. 'font-lock-variable-name-face 'record))
  7762. node)
  7763. (js2-unget-token)
  7764. nil))
  7765. (let* ((name-node (make-js2-name-node
  7766. :name (js2-current-token-string)
  7767. :pos (js2-current-token-beg)
  7768. :len (js2-current-token-len)))
  7769. (node (make-js2-export-binding-node
  7770. :pos (js2-current-token-beg)
  7771. :len (js2-current-token-len)
  7772. :local-name name-node
  7773. :extern-name name-node)))
  7774. (when is-reserved-name
  7775. (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
  7776. (js2-node-add-children node name-node)
  7777. (if import-p
  7778. (js2-set-face (js2-current-token-beg) (js2-current-token-end)
  7779. 'font-lock-variable-name-face 'record))
  7780. node))
  7781. nil)))
  7782. (defun js2-parse-switch ()
  7783. "Parser for switch-statement. Last matched token must be js2-SWITCH."
  7784. (let ((pos (js2-current-token-beg))
  7785. tt pn discriminant has-default case-expr case-node
  7786. case-pos cases stmt lp)
  7787. (if (js2-must-match js2-LP "msg.no.paren.switch")
  7788. (setq lp (js2-current-token-beg)))
  7789. (setq discriminant (js2-parse-expr)
  7790. pn (make-js2-switch-node :discriminant discriminant
  7791. :pos pos
  7792. :lp (js2-relpos lp pos)))
  7793. (js2-node-add-children pn discriminant)
  7794. (js2-enter-switch pn)
  7795. (unwind-protect
  7796. (progn
  7797. (if (js2-must-match js2-RP "msg.no.paren.after.switch")
  7798. (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
  7799. (js2-must-match js2-LC "msg.no.brace.switch")
  7800. (catch 'break
  7801. (while t
  7802. (setq tt (js2-next-token)
  7803. case-pos (js2-current-token-beg))
  7804. (cond
  7805. ((= tt js2-RC)
  7806. (setf (js2-node-len pn) (- (js2-current-token-end) pos))
  7807. (throw 'break nil)) ; done
  7808. ((= tt js2-CASE)
  7809. (setq case-expr (js2-parse-expr))
  7810. (js2-must-match js2-COLON "msg.no.colon.case"))
  7811. ((= tt js2-DEFAULT)
  7812. (if has-default
  7813. (js2-report-error "msg.double.switch.default"))
  7814. (setq has-default t
  7815. case-expr nil)
  7816. (js2-must-match js2-COLON "msg.no.colon.case"))
  7817. (t
  7818. (js2-report-error "msg.bad.switch")
  7819. (throw 'break nil)))
  7820. (setq case-node (make-js2-case-node :pos case-pos
  7821. :len (- (js2-current-token-end) case-pos)
  7822. :expr case-expr))
  7823. (js2-node-add-children case-node case-expr)
  7824. (while (and (/= (setq tt (js2-peek-token)) js2-RC)
  7825. (/= tt js2-CASE)
  7826. (/= tt js2-DEFAULT)
  7827. (/= tt js2-EOF))
  7828. (setf stmt (js2-parse-statement)
  7829. (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
  7830. (js2-block-node-push case-node stmt))
  7831. (push case-node cases)))
  7832. ;; add cases last, as pushing reverses the order to be correct
  7833. (dolist (kid cases)
  7834. (js2-node-add-children pn kid)
  7835. (push kid (js2-switch-node-cases pn)))
  7836. pn) ; return value
  7837. (js2-exit-switch))))
  7838. (defun js2-parse-while ()
  7839. "Parser for while-statement. Last matched token must be js2-WHILE."
  7840. (let ((pos (js2-current-token-beg))
  7841. (pn (make-js2-while-node))
  7842. cond body)
  7843. (js2-enter-loop pn)
  7844. (unwind-protect
  7845. (progn
  7846. (setf cond (js2-parse-condition)
  7847. (js2-while-node-condition pn) (car cond)
  7848. body (js2-parse-statement)
  7849. (js2-while-node-body pn) body
  7850. (js2-node-len pn) (- (js2-node-end body) pos)
  7851. (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
  7852. (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
  7853. (js2-node-add-children pn body (car cond)))
  7854. (js2-exit-loop))
  7855. pn))
  7856. (defun js2-parse-do ()
  7857. "Parser for do-statement. Last matched token must be js2-DO."
  7858. (let ((pos (js2-current-token-beg))
  7859. (pn (make-js2-do-node))
  7860. cond body end)
  7861. (js2-enter-loop pn)
  7862. (unwind-protect
  7863. (progn
  7864. (setq body (js2-parse-statement))
  7865. (js2-must-match js2-WHILE "msg.no.while.do")
  7866. (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
  7867. cond (js2-parse-condition)
  7868. (js2-do-node-condition pn) (car cond)
  7869. (js2-do-node-body pn) body
  7870. end js2-ts-cursor
  7871. (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
  7872. (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
  7873. (js2-node-add-children pn (car cond) body))
  7874. (js2-exit-loop))
  7875. ;; Always auto-insert semicolon to follow SpiderMonkey:
  7876. ;; It is required by ECMAScript but is ignored by the rest of
  7877. ;; world; see bug 238945
  7878. (if (js2-match-token js2-SEMI)
  7879. (setq end js2-ts-cursor))
  7880. (setf (js2-node-len pn) (- end pos))
  7881. pn))
  7882. (defun js2-parse-export ()
  7883. "Parse an export statement.
  7884. The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
  7885. expressions should only be either hoistable expressions (function or generator)
  7886. or assignment expressions, but there is no checking to enforce that and so it
  7887. will parse without error a small subset of
  7888. invalid export statements."
  7889. (unless (js2-ast-root-p js2-current-scope)
  7890. (js2-report-error "msg.mod.export.decl.at.top.level"))
  7891. (let ((beg (js2-current-token-beg))
  7892. (children (list))
  7893. exports-list from-clause declaration default)
  7894. (cond
  7895. ((js2-match-token js2-MUL)
  7896. (setq from-clause (js2-parse-from-clause))
  7897. (when from-clause
  7898. (push from-clause children)))
  7899. ((js2-match-token js2-LC)
  7900. (setq exports-list (js2-parse-export-bindings))
  7901. (when exports-list
  7902. (dolist (export exports-list)
  7903. (push export children)))
  7904. (when (js2-match-contextual-kwd "from")
  7905. (js2-unget-token)
  7906. (setq from-clause (js2-parse-from-clause))))
  7907. ((js2-match-token js2-DEFAULT)
  7908. (setq default (cond ((js2-match-token js2-CLASS)
  7909. (if (eq (js2-peek-token) js2-NAME)
  7910. (js2-parse-class-stmt)
  7911. (js2-parse-class-expr)))
  7912. ((js2-match-token js2-NAME)
  7913. (if (js2-match-async-function)
  7914. (if (eq (js2-peek-token) js2-NAME)
  7915. (js2-parse-async-function-stmt)
  7916. (js2-parse-function-expr t))
  7917. (js2-unget-token)
  7918. (js2-parse-expr)))
  7919. ((js2-match-token js2-FUNCTION)
  7920. (if (eq (js2-peek-token) js2-NAME)
  7921. (js2-parse-function-stmt)
  7922. (js2-parse-function-expr)))
  7923. (t (js2-parse-expr)))))
  7924. ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
  7925. (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
  7926. ((js2-match-token js2-CLASS)
  7927. (setq declaration (js2-parse-class-stmt)))
  7928. ((js2-match-token js2-NAME)
  7929. (setq declaration
  7930. (if (js2-match-async-function)
  7931. (js2-parse-async-function-stmt)
  7932. (js2-unget-token)
  7933. (js2-parse-expr))))
  7934. ((js2-match-token js2-FUNCTION)
  7935. (setq declaration (js2-parse-function-stmt)))
  7936. (t
  7937. (setq declaration (js2-parse-expr))))
  7938. (when from-clause
  7939. (push from-clause children))
  7940. (when declaration
  7941. (push declaration children)
  7942. (when (not (or (js2-function-node-p declaration)
  7943. (js2-class-node-p declaration)))
  7944. (js2-auto-insert-semicolon declaration)))
  7945. (when default
  7946. (push default children)
  7947. (when (not (or (js2-function-node-p default)
  7948. (js2-class-node-p default)))
  7949. (js2-auto-insert-semicolon default)))
  7950. (let ((node (make-js2-export-node
  7951. :pos beg
  7952. :len (- (js2-current-token-end) beg)
  7953. :exports-list exports-list
  7954. :from-clause from-clause
  7955. :declaration declaration
  7956. :default default)))
  7957. (apply #'js2-node-add-children node children)
  7958. node)))
  7959. (defun js2-parse-for ()
  7960. "Parse a for, for-in or for each-in statement.
  7961. Last matched token must be js2-FOR."
  7962. (let ((for-pos (js2-current-token-beg))
  7963. (tmp-scope (make-js2-scope))
  7964. pn is-for-each is-for-in-or-of is-for-of
  7965. in-pos each-pos tmp-pos
  7966. init ; Node init is also foo in 'foo in object'.
  7967. cond ; Node cond is also object in 'foo in object'.
  7968. incr ; 3rd section of for-loop initializer.
  7969. body tt lp rp)
  7970. ;; See if this is a for each () instead of just a for ()
  7971. (when (js2-match-token js2-NAME)
  7972. (if (string= "each" (js2-current-token-string))
  7973. (progn
  7974. (setq is-for-each t
  7975. each-pos (- (js2-current-token-beg) for-pos)) ; relative
  7976. (js2-record-face 'font-lock-keyword-face))
  7977. (js2-report-error "msg.no.paren.for")))
  7978. (if (js2-must-match js2-LP "msg.no.paren.for")
  7979. (setq lp (- (js2-current-token-beg) for-pos)))
  7980. (setq tt (js2-get-token))
  7981. ;; Capture identifiers inside parens. We can't create the node
  7982. ;; (and use it as the current scope) until we know its type.
  7983. (js2-push-scope tmp-scope)
  7984. (unwind-protect
  7985. (progn
  7986. ;; parse init clause
  7987. (let ((js2-in-for-init t)) ; set as dynamic variable
  7988. (cond
  7989. ((= tt js2-SEMI)
  7990. (js2-unget-token)
  7991. (setq init (make-js2-empty-expr-node)))
  7992. ((or (= tt js2-VAR) (= tt js2-LET) (= tt js2-CONST))
  7993. (setq init (js2-parse-variables tt (js2-current-token-beg))))
  7994. (t
  7995. (js2-unget-token)
  7996. (setq init (js2-parse-expr)))))
  7997. (if (or (js2-match-token js2-IN)
  7998. (and (>= js2-language-version 200)
  7999. (js2-match-contextual-kwd "of")
  8000. (setq is-for-of t)))
  8001. (setq is-for-in-or-of t
  8002. in-pos (- (js2-current-token-beg) for-pos)
  8003. ;; scope of iteration target object is not the scope we've created above.
  8004. ;; stash current scope temporary.
  8005. cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
  8006. (js2-parse-expr))) ; object over which we're iterating
  8007. ;; else ordinary for loop - parse cond and incr
  8008. (js2-must-match js2-SEMI "msg.no.semi.for")
  8009. (setq cond (if (= (js2-peek-token) js2-SEMI)
  8010. (make-js2-empty-expr-node) ; no loop condition
  8011. (js2-parse-expr)))
  8012. (js2-must-match js2-SEMI "msg.no.semi.for.cond")
  8013. (setq tmp-pos (js2-current-token-end)
  8014. incr (if (= (js2-peek-token) js2-RP)
  8015. (make-js2-empty-expr-node :pos tmp-pos)
  8016. (js2-parse-expr)))))
  8017. (js2-pop-scope))
  8018. (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
  8019. (setq rp (- (js2-current-token-beg) for-pos)))
  8020. (if (not is-for-in-or-of)
  8021. (setq pn (make-js2-for-node :init init
  8022. :condition cond
  8023. :update incr
  8024. :lp lp
  8025. :rp rp))
  8026. ;; cond could be null if 'in obj' got eaten by the init node.
  8027. (if (js2-infix-node-p init)
  8028. ;; it was (foo in bar) instead of (var foo in bar)
  8029. (setq cond (js2-infix-node-right init)
  8030. init (js2-infix-node-left init))
  8031. (if (and (js2-var-decl-node-p init)
  8032. (> (length (js2-var-decl-node-kids init)) 1))
  8033. (js2-report-error "msg.mult.index")))
  8034. (setq pn (make-js2-for-in-node :iterator init
  8035. :object cond
  8036. :in-pos in-pos
  8037. :foreach-p is-for-each
  8038. :each-pos each-pos
  8039. :forof-p is-for-of
  8040. :lp lp
  8041. :rp rp)))
  8042. ;; Transplant the declarations.
  8043. (setf (js2-scope-symbol-table pn)
  8044. (js2-scope-symbol-table tmp-scope))
  8045. (unwind-protect
  8046. (progn
  8047. (js2-enter-loop pn)
  8048. ;; We have to parse the body -after- creating the loop node,
  8049. ;; so that the loop node appears in the js2-loop-set, allowing
  8050. ;; break/continue statements to find the enclosing loop.
  8051. (setf body (js2-parse-statement)
  8052. (js2-loop-node-body pn) body
  8053. (js2-node-pos pn) for-pos
  8054. (js2-node-len pn) (- (js2-node-end body) for-pos))
  8055. (js2-node-add-children pn init cond incr body))
  8056. ;; finally
  8057. (js2-exit-loop))
  8058. pn))
  8059. (defun js2-parse-try ()
  8060. "Parse a try statement. Last matched token must be js2-TRY."
  8061. (let ((try-pos (js2-current-token-beg))
  8062. try-end
  8063. try-block
  8064. catch-blocks
  8065. finally-block
  8066. saw-default-catch
  8067. peek)
  8068. (if (/= (js2-peek-token) js2-LC)
  8069. (js2-report-error "msg.no.brace.try"))
  8070. (setq try-block (js2-parse-statement)
  8071. try-end (js2-node-end try-block)
  8072. peek (js2-peek-token))
  8073. (cond
  8074. ((= peek js2-CATCH)
  8075. (while (js2-match-token js2-CATCH)
  8076. (let* ((catch-pos (js2-current-token-beg))
  8077. (catch-node (make-js2-catch-node :pos catch-pos))
  8078. param
  8079. guard-kwd
  8080. catch-cond
  8081. lp rp)
  8082. (if saw-default-catch
  8083. (js2-report-error "msg.catch.unreachable"))
  8084. (if (js2-must-match js2-LP "msg.no.paren.catch")
  8085. (setq lp (- (js2-current-token-beg) catch-pos)))
  8086. (js2-push-scope catch-node)
  8087. (let ((tt (js2-peek-token)))
  8088. (cond
  8089. ;; Destructuring pattern:
  8090. ;; catch ({ message, file }) { ... }
  8091. ((or (= tt js2-LB) (= tt js2-LC))
  8092. (js2-get-token)
  8093. (setq param (js2-parse-destruct-primary-expr))
  8094. (js2-define-destruct-symbols param js2-LET nil))
  8095. ;; Simple name.
  8096. (t
  8097. (js2-must-match-name "msg.bad.catchcond")
  8098. (setq param (js2-create-name-node))
  8099. (js2-define-symbol js2-LET (js2-current-token-string) param)
  8100. (js2-check-strict-identifier param))))
  8101. ;; Catch condition.
  8102. (if (js2-match-token js2-IF)
  8103. (setq guard-kwd (- (js2-current-token-beg) catch-pos)
  8104. catch-cond (js2-parse-expr))
  8105. (setq saw-default-catch t))
  8106. (if (js2-must-match js2-RP "msg.bad.catchcond")
  8107. (setq rp (- (js2-current-token-beg) catch-pos)))
  8108. (js2-must-match js2-LC "msg.no.brace.catchblock")
  8109. (js2-parse-statements catch-node)
  8110. (if (js2-must-match js2-RC "msg.no.brace.after.body")
  8111. (setq try-end (js2-current-token-end)))
  8112. (js2-pop-scope)
  8113. (setf (js2-node-len catch-node) (- try-end catch-pos)
  8114. (js2-catch-node-param catch-node) param
  8115. (js2-catch-node-guard-expr catch-node) catch-cond
  8116. (js2-catch-node-guard-kwd catch-node) guard-kwd
  8117. (js2-catch-node-lp catch-node) lp
  8118. (js2-catch-node-rp catch-node) rp)
  8119. (js2-node-add-children catch-node param catch-cond)
  8120. (push catch-node catch-blocks))))
  8121. ((/= peek js2-FINALLY)
  8122. (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
  8123. (js2-node-pos try-block)
  8124. (- (setq try-end (js2-node-end try-block))
  8125. (js2-node-pos try-block)))))
  8126. (when (js2-match-token js2-FINALLY)
  8127. (let ((finally-pos (js2-current-token-beg))
  8128. (block (js2-parse-statement)))
  8129. (setq try-end (js2-node-end block)
  8130. finally-block (make-js2-finally-node :pos finally-pos
  8131. :len (- try-end finally-pos)
  8132. :body block))
  8133. (js2-node-add-children finally-block block)))
  8134. (let ((pn (make-js2-try-node :pos try-pos
  8135. :len (- try-end try-pos)
  8136. :try-block try-block
  8137. :finally-block finally-block)))
  8138. (js2-node-add-children pn try-block finally-block)
  8139. ;; Push them onto the try-node, which reverses and corrects their order.
  8140. (dolist (cb catch-blocks)
  8141. (js2-node-add-children pn cb)
  8142. (push cb (js2-try-node-catch-clauses pn)))
  8143. pn)))
  8144. (defun js2-parse-throw ()
  8145. "Parser for throw-statement. Last matched token must be js2-THROW."
  8146. (let ((pos (js2-current-token-beg))
  8147. expr pn)
  8148. (if (= (js2-peek-token-or-eol) js2-EOL)
  8149. ;; ECMAScript does not allow new lines before throw expression,
  8150. ;; see bug 256617
  8151. (js2-report-error "msg.bad.throw.eol"))
  8152. (setq expr (js2-parse-expr)
  8153. pn (make-js2-throw-node :pos pos
  8154. :len (- (js2-node-end expr) pos)
  8155. :expr expr))
  8156. (js2-node-add-children pn expr)
  8157. pn))
  8158. (defun js2-match-jump-label-name (label-name)
  8159. "If break/continue specified a label, return that label's labeled stmt.
  8160. Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
  8161. does not match an existing label, reports an error and returns nil."
  8162. (let ((bundle (cdr (assoc label-name js2-label-set))))
  8163. (if (null bundle)
  8164. (js2-report-error "msg.undef.label"))
  8165. bundle))
  8166. (defun js2-parse-break ()
  8167. "Parser for break-statement. Last matched token must be js2-BREAK."
  8168. (let ((pos (js2-current-token-beg))
  8169. (end (js2-current-token-end))
  8170. break-target ; statement to break from
  8171. break-label ; in "break foo", name-node representing the foo
  8172. labels ; matching labeled statement to break to
  8173. pn)
  8174. (when (eq (js2-peek-token-or-eol) js2-NAME)
  8175. (js2-get-token)
  8176. (setq break-label (js2-create-name-node)
  8177. end (js2-node-end break-label)
  8178. ;; matchJumpLabelName only matches if there is one
  8179. labels (js2-match-jump-label-name (js2-current-token-string))
  8180. break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
  8181. (unless (or break-target break-label)
  8182. ;; no break target specified - try for innermost enclosing loop/switch
  8183. (if (null js2-loop-and-switch-set)
  8184. (unless break-label
  8185. (js2-report-error "msg.bad.break" nil pos (length "break")))
  8186. (setq break-target (car js2-loop-and-switch-set))))
  8187. (setq pn (make-js2-break-node :pos pos
  8188. :len (- end pos)
  8189. :label break-label
  8190. :target break-target))
  8191. (js2-node-add-children pn break-label) ; but not break-target
  8192. pn))
  8193. (defun js2-parse-continue ()
  8194. "Parser for continue-statement. Last matched token must be js2-CONTINUE."
  8195. (let ((pos (js2-current-token-beg))
  8196. (end (js2-current-token-end))
  8197. label ; optional user-specified label, a `js2-name-node'
  8198. labels ; current matching labeled stmt, if any
  8199. target ; the `js2-loop-node' target of this continue stmt
  8200. pn)
  8201. (when (= (js2-peek-token-or-eol) js2-NAME)
  8202. (js2-get-token)
  8203. (setq label (js2-create-name-node)
  8204. end (js2-node-end label)
  8205. ;; matchJumpLabelName only matches if there is one
  8206. labels (js2-match-jump-label-name (js2-current-token-string))))
  8207. (cond
  8208. ((null labels) ; no current label to go to
  8209. (if (null js2-loop-set) ; no loop to continue to
  8210. (js2-report-error "msg.continue.outside" nil pos
  8211. (length "continue"))
  8212. (setq target (car js2-loop-set)))) ; innermost enclosing loop
  8213. (t
  8214. (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
  8215. (setq target (js2-labeled-stmt-node-stmt labels))
  8216. (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
  8217. (setq pn (make-js2-continue-node :pos pos
  8218. :len (- end pos)
  8219. :label label
  8220. :target target))
  8221. (js2-node-add-children pn label) ; but not target - it's not our child
  8222. pn))
  8223. (defun js2-parse-with ()
  8224. "Parser for with-statement. Last matched token must be js2-WITH."
  8225. (when js2-in-use-strict-directive
  8226. (js2-report-error "msg.no.with.strict"))
  8227. (let ((pos (js2-current-token-beg))
  8228. obj body pn lp rp)
  8229. (if (js2-must-match js2-LP "msg.no.paren.with")
  8230. (setq lp (js2-current-token-beg)))
  8231. (setq obj (js2-parse-expr))
  8232. (if (js2-must-match js2-RP "msg.no.paren.after.with")
  8233. (setq rp (js2-current-token-beg)))
  8234. (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
  8235. (setq body (js2-parse-statement)))
  8236. (setq pn (make-js2-with-node :pos pos
  8237. :len (- (js2-node-end body) pos)
  8238. :object obj
  8239. :body body
  8240. :lp (js2-relpos lp pos)
  8241. :rp (js2-relpos rp pos)))
  8242. (js2-node-add-children pn obj body)
  8243. pn))
  8244. (defun js2-parse-const-var ()
  8245. "Parser for var- or const-statement.
  8246. Last matched token must be js2-CONST or js2-VAR."
  8247. (let ((tt (js2-current-token-type))
  8248. (pos (js2-current-token-beg))
  8249. expr pn)
  8250. (setq expr (js2-parse-variables tt (js2-current-token-beg))
  8251. pn (make-js2-expr-stmt-node :pos pos
  8252. :len (- (js2-node-end expr) pos)
  8253. :expr expr))
  8254. (js2-node-add-children pn expr)
  8255. pn))
  8256. (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
  8257. (let ((pn (make-js2-expr-stmt-node :pos pos
  8258. :len (js2-node-len expr)
  8259. :type (if (js2-inside-function)
  8260. js2-EXPR_VOID
  8261. js2-EXPR_RESULT)
  8262. :expr expr)))
  8263. (if add-child
  8264. (js2-node-add-children pn expr))
  8265. pn))
  8266. (defun js2-parse-let-stmt ()
  8267. "Parser for let-statement. Last matched token must be js2-LET."
  8268. (let ((pos (js2-current-token-beg))
  8269. expr pn)
  8270. (if (= (js2-peek-token) js2-LP)
  8271. ;; let expression in statement context
  8272. (setq expr (js2-parse-let pos 'statement)
  8273. pn (js2-wrap-with-expr-stmt pos expr t))
  8274. ;; else we're looking at a statement like let x=6, y=7;
  8275. (setf expr (js2-parse-variables js2-LET pos)
  8276. pn (js2-wrap-with-expr-stmt pos expr t)
  8277. (js2-node-type pn) js2-EXPR_RESULT))
  8278. pn))
  8279. (defun js2-parse-ret-yield ()
  8280. (js2-parse-return-or-yield (js2-current-token-type) nil))
  8281. (defconst js2-parse-return-stmt-enders
  8282. (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP))
  8283. (defsubst js2-now-all-set (before after mask)
  8284. "Return whether or not the bits in the mask have changed to all set.
  8285. BEFORE is bits before change, AFTER is bits after change, and MASK is
  8286. the mask for bits. Returns t if all the bits in the mask are set in AFTER
  8287. but not BEFORE."
  8288. (and (/= (logand before mask) mask)
  8289. (= (logand after mask) mask)))
  8290. (defun js2-parse-return-or-yield (tt expr-context)
  8291. (let* ((pos (js2-current-token-beg))
  8292. (end (js2-current-token-end))
  8293. (before js2-end-flags)
  8294. (inside-function (js2-inside-function))
  8295. (gen-type (and inside-function (js2-function-node-generator-type
  8296. js2-current-script-or-fn)))
  8297. e ret name yield-star-p)
  8298. (unless inside-function
  8299. (js2-report-error (if (eq tt js2-RETURN)
  8300. "msg.bad.return"
  8301. "msg.bad.yield")))
  8302. (when (and inside-function
  8303. (eq gen-type 'STAR)
  8304. (js2-match-token js2-MUL))
  8305. (setq yield-star-p t))
  8306. ;; This is ugly, but we don't want to require a semicolon.
  8307. (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
  8308. (setq e (if (eq gen-type 'STAR)
  8309. (js2-parse-assign-expr)
  8310. (js2-parse-expr))
  8311. end (js2-node-end e)))
  8312. (cond
  8313. ((eq tt js2-RETURN)
  8314. (js2-set-flag js2-end-flags (if (null e)
  8315. js2-end-returns
  8316. js2-end-returns-value))
  8317. (setq ret (make-js2-return-node :pos pos
  8318. :len (- end pos)
  8319. :retval e))
  8320. (js2-node-add-children ret e)
  8321. ;; See if we need a strict mode warning.
  8322. ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
  8323. ;; more thorough and accurate than this before/after flag check.
  8324. ;; E.g. if there's a finally-block that always returns, we shouldn't
  8325. ;; show a warning generated by inconsistent returns in the catch blocks.
  8326. ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
  8327. ;; so we know which returns/yields to highlight, and we should get rid of
  8328. ;; all the checking in `js2-parse-return-or-yield'.
  8329. (if (and js2-strict-inconsistent-return-warning
  8330. (js2-now-all-set before js2-end-flags
  8331. (logior js2-end-returns js2-end-returns-value)))
  8332. (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
  8333. ((eq gen-type 'COMPREHENSION)
  8334. ;; FIXME: We should probably switch to saving and using lastYieldOffset,
  8335. ;; like SpiderMonkey does.
  8336. (js2-report-error "msg.syntax" nil pos 5))
  8337. (t
  8338. (setq ret (make-js2-yield-node :pos pos
  8339. :len (- end pos)
  8340. :value e
  8341. :star-p yield-star-p))
  8342. (js2-node-add-children ret e)
  8343. (unless expr-context
  8344. (setq e ret
  8345. ret (js2-wrap-with-expr-stmt pos e t))
  8346. (js2-set-requires-activation)
  8347. (js2-set-is-generator))))
  8348. ;; see if we are mixing yields and value returns.
  8349. (when (and inside-function
  8350. (js2-flag-set-p js2-end-flags js2-end-returns-value)
  8351. (eq (js2-function-node-generator-type js2-current-script-or-fn)
  8352. 'LEGACY))
  8353. (setq name (js2-function-name js2-current-script-or-fn))
  8354. (if (zerop (length name))
  8355. (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
  8356. (js2-report-error "msg.generator.returns" name pos (- end pos))))
  8357. ret))
  8358. (defun js2-parse-debugger ()
  8359. (make-js2-keyword-node :type js2-DEBUGGER))
  8360. (defun js2-parse-block ()
  8361. "Parser for a curly-delimited statement block.
  8362. Last token matched must be `js2-LC'."
  8363. (let ((pos (js2-current-token-beg))
  8364. (pn (make-js2-scope)))
  8365. (js2-push-scope pn)
  8366. (unwind-protect
  8367. (progn
  8368. (js2-parse-statements pn)
  8369. (js2-must-match js2-RC "msg.no.brace.block")
  8370. (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
  8371. (js2-pop-scope))
  8372. pn))
  8373. ;; For `js2-ERROR' too, to have a node for error recovery to work on.
  8374. (defun js2-parse-semi ()
  8375. "Parse a statement or handle an error.
  8376. Current token type is `js2-SEMI' or `js2-ERROR'."
  8377. (let ((tt (js2-current-token-type)) pos len)
  8378. (if (eq tt js2-SEMI)
  8379. (make-js2-empty-expr-node :len 1)
  8380. (setq pos (js2-current-token-beg)
  8381. len (- (js2-current-token-end) pos))
  8382. (js2-report-error "msg.syntax" nil pos len)
  8383. (make-js2-error-node :pos pos :len len))))
  8384. (defun js2-parse-default-xml-namespace ()
  8385. "Parse a `default xml namespace = <expr>' e4x statement."
  8386. (let ((pos (js2-current-token-beg))
  8387. end len expr unary)
  8388. (js2-must-have-xml)
  8389. (js2-set-requires-activation)
  8390. (setq len (- js2-ts-cursor pos))
  8391. (unless (and (js2-match-token js2-NAME)
  8392. (string= (js2-current-token-string) "xml"))
  8393. (js2-report-error "msg.bad.namespace" nil pos len))
  8394. (unless (and (js2-match-token js2-NAME)
  8395. (string= (js2-current-token-string) "namespace"))
  8396. (js2-report-error "msg.bad.namespace" nil pos len))
  8397. (unless (js2-match-token js2-ASSIGN)
  8398. (js2-report-error "msg.bad.namespace" nil pos len))
  8399. (setq expr (js2-parse-expr)
  8400. end (js2-node-end expr)
  8401. unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
  8402. :pos pos
  8403. :len (- end pos)
  8404. :operand expr))
  8405. (js2-node-add-children unary expr)
  8406. (make-js2-expr-stmt-node :pos pos
  8407. :len (- end pos)
  8408. :expr unary)))
  8409. (defun js2-record-label (label bundle)
  8410. ;; current token should be colon that `js2-parse-primary-expr' left untouched
  8411. (js2-get-token)
  8412. (let ((name (js2-label-node-name label))
  8413. labeled-stmt
  8414. dup)
  8415. (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
  8416. ;; flag both labels if possible when used in editing mode
  8417. (if (and js2-parse-ide-mode
  8418. (setq dup (js2-get-label-by-name labeled-stmt name)))
  8419. (js2-report-error "msg.dup.label" nil
  8420. (js2-node-abs-pos dup) (js2-node-len dup)))
  8421. (js2-report-error "msg.dup.label" nil
  8422. (js2-node-pos label) (js2-node-len label)))
  8423. (js2-labeled-stmt-node-add-label bundle label)
  8424. (js2-node-add-children bundle label)
  8425. ;; Add one reference to the bundle per label in `js2-label-set'
  8426. (push (cons name bundle) js2-label-set)))
  8427. (defun js2-parse-name-or-label ()
  8428. "Parser for identifier or label. Last token matched must be js2-NAME.
  8429. Called when we found a name in a statement context. If it's a label, we gather
  8430. up any following labels and the next non-label statement into a
  8431. `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
  8432. expression and return it wrapped in a `js2-expr-stmt-node'."
  8433. (let ((pos (js2-current-token-beg))
  8434. expr stmt bundle
  8435. (continue t))
  8436. ;; set check for label and call down to `js2-parse-primary-expr'
  8437. (setq expr (js2-maybe-parse-label))
  8438. (if (null expr)
  8439. ;; Parse the non-label expression and wrap with expression stmt.
  8440. (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
  8441. ;; else parsed a label
  8442. (setq bundle (make-js2-labeled-stmt-node :pos pos))
  8443. (js2-record-label expr bundle)
  8444. ;; look for more labels
  8445. (while (and continue (= (js2-get-token) js2-NAME))
  8446. (if (setq expr (js2-maybe-parse-label))
  8447. (js2-record-label expr bundle)
  8448. (setq expr (js2-parse-expr)
  8449. stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
  8450. continue nil)
  8451. (js2-auto-insert-semicolon stmt)))
  8452. ;; no more labels; now parse the labeled statement
  8453. (unwind-protect
  8454. (unless stmt
  8455. (let ((js2-labeled-stmt bundle)) ; bind dynamically
  8456. (js2-unget-token)
  8457. (setq stmt (js2-statement-helper))))
  8458. ;; remove the labels for this statement from the global set
  8459. (dolist (label (js2-labeled-stmt-node-labels bundle))
  8460. (setq js2-label-set (remove label js2-label-set))))
  8461. (setf (js2-labeled-stmt-node-stmt bundle) stmt
  8462. (js2-node-len bundle) (- (js2-node-end stmt) pos))
  8463. (js2-node-add-children bundle stmt)
  8464. bundle)))
  8465. (defun js2-maybe-parse-label ()
  8466. (cl-assert (= (js2-current-token-type) js2-NAME))
  8467. (let (label-pos
  8468. (next-tt (js2-get-token))
  8469. (label-end (js2-current-token-end)))
  8470. ;; Do not consume colon, it is used as unwind indicator
  8471. ;; to return to statementHelper.
  8472. (js2-unget-token)
  8473. (if (= next-tt js2-COLON)
  8474. (prog2
  8475. (setq label-pos (js2-current-token-beg))
  8476. (make-js2-label-node :pos label-pos
  8477. :len (- label-end label-pos)
  8478. :name (js2-current-token-string))
  8479. (js2-set-face label-pos
  8480. label-end
  8481. 'font-lock-variable-name-face 'record))
  8482. ;; Backtrack from the name token, too.
  8483. (js2-unget-token)
  8484. nil)))
  8485. (defun js2-parse-expr-stmt ()
  8486. "Default parser in statement context, if no recognized statement found."
  8487. (js2-wrap-with-expr-stmt (js2-current-token-beg)
  8488. (progn
  8489. (js2-unget-token)
  8490. (js2-parse-expr)) t))
  8491. (defun js2-parse-variables (decl-type pos)
  8492. "Parse a comma-separated list of variable declarations.
  8493. Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
  8494. DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
  8495. For 'var' or 'const', the keyword should be the token last scanned.
  8496. POS is the position where the node should start. It's sometimes the
  8497. var/const/let keyword, and other times the beginning of the first token
  8498. in the first variable declaration.
  8499. Returns the parsed `js2-var-decl-node' expression node."
  8500. (let* ((result (make-js2-var-decl-node :decl-type decl-type
  8501. :pos pos))
  8502. destructuring kid-pos tt init name end nbeg nend vi
  8503. (continue t))
  8504. ;; Example:
  8505. ;; var foo = {a: 1, b: 2}, bar = [3, 4];
  8506. ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
  8507. ;; var {a, b} = baz;
  8508. (while continue
  8509. (setq destructuring nil
  8510. name nil
  8511. tt (js2-get-token)
  8512. kid-pos (js2-current-token-beg)
  8513. end (js2-current-token-end)
  8514. init nil)
  8515. (if (or (= tt js2-LB) (= tt js2-LC))
  8516. ;; Destructuring assignment, e.g., var [a, b] = ...
  8517. (setq destructuring (js2-parse-destruct-primary-expr)
  8518. end (js2-node-end destructuring))
  8519. ;; Simple variable name
  8520. (js2-unget-token)
  8521. (when (js2-must-match-name "msg.bad.var")
  8522. (setq name (js2-create-name-node)
  8523. nbeg (js2-current-token-beg)
  8524. nend (js2-current-token-end)
  8525. end nend)
  8526. (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)
  8527. (js2-check-strict-identifier name)))
  8528. (when (js2-match-token js2-ASSIGN)
  8529. (setq init (js2-parse-assign-expr)
  8530. end (js2-node-end init))
  8531. (js2-record-imenu-functions init name))
  8532. (when name
  8533. (js2-set-face nbeg nend (if (js2-function-node-p init)
  8534. 'font-lock-function-name-face
  8535. 'font-lock-variable-name-face)
  8536. 'record))
  8537. (setq vi (make-js2-var-init-node :pos kid-pos
  8538. :len (- end kid-pos)
  8539. :type decl-type))
  8540. (if destructuring
  8541. (progn
  8542. (if (and (null init) (not js2-in-for-init))
  8543. (js2-report-error "msg.destruct.assign.no.init"))
  8544. (js2-define-destruct-symbols destructuring
  8545. decl-type
  8546. 'font-lock-variable-name-face)
  8547. (setf (js2-var-init-node-target vi) destructuring))
  8548. (setf (js2-var-init-node-target vi) name))
  8549. (setf (js2-var-init-node-initializer vi) init)
  8550. (js2-node-add-children vi name destructuring init)
  8551. (js2-block-node-push result vi)
  8552. (unless (js2-match-token js2-COMMA)
  8553. (setq continue nil)))
  8554. (setf (js2-node-len result) (- end pos))
  8555. result))
  8556. (defun js2-parse-let (pos &optional stmt-p)
  8557. "Parse a let expression or statement.
  8558. A let-expression is of the form `let (vars) expr'.
  8559. A let-statement is of the form `let (vars) {statements}'.
  8560. The third form of let is a variable declaration list, handled
  8561. by `js2-parse-variables'."
  8562. (let ((pn (make-js2-let-node :pos pos))
  8563. beg vars body)
  8564. (if (js2-must-match js2-LP "msg.no.paren.after.let")
  8565. (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
  8566. (js2-push-scope pn)
  8567. (unwind-protect
  8568. (progn
  8569. (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
  8570. (if (js2-must-match js2-RP "msg.no.paren.let")
  8571. (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
  8572. (if (and stmt-p (js2-match-token js2-LC))
  8573. ;; let statement
  8574. (progn
  8575. (setf beg (js2-current-token-beg) ; position stmt at LC
  8576. body (js2-parse-statements))
  8577. (js2-must-match js2-RC "msg.no.curly.let")
  8578. (setf (js2-node-len body) (- (js2-current-token-end) beg)
  8579. (js2-node-len pn) (- (js2-current-token-end) pos)
  8580. (js2-let-node-body pn) body
  8581. (js2-node-type pn) js2-LET))
  8582. ;; let expression
  8583. (setf body (js2-parse-expr)
  8584. (js2-node-len pn) (- (js2-node-end body) pos)
  8585. (js2-let-node-body pn) body))
  8586. (setf (js2-let-node-vars pn) vars)
  8587. (js2-node-add-children pn vars body))
  8588. (js2-pop-scope))
  8589. pn))
  8590. (defun js2-define-new-symbol (decl-type name node &optional scope)
  8591. (js2-scope-put-symbol (or scope js2-current-scope)
  8592. name
  8593. (make-js2-symbol decl-type name node)))
  8594. (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
  8595. "Define a symbol in the current scope.
  8596. If NODE is non-nil, it is the AST node associated with the symbol."
  8597. (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
  8598. (symbol (if defining-scope
  8599. (js2-scope-get-symbol defining-scope name)))
  8600. (sdt (if symbol (js2-symbol-decl-type symbol) -1))
  8601. (pos (if node (js2-node-abs-pos node)))
  8602. (len (if node (js2-node-len node))))
  8603. (cond
  8604. ((and symbol ; already defined in this block
  8605. (or (= sdt js2-LET)
  8606. (= sdt js2-CONST))
  8607. (eq defining-scope js2-current-scope))
  8608. (js2-report-error
  8609. (cond
  8610. ((= sdt js2-CONST) "msg.const.redecl")
  8611. ((= sdt js2-LET) "msg.let.redecl")
  8612. ((= sdt js2-VAR) "msg.var.redecl")
  8613. ((= sdt js2-FUNCTION) "msg.function.redecl")
  8614. (t "msg.parm.redecl"))
  8615. name pos len))
  8616. ((or (= decl-type js2-LET)
  8617. (= decl-type js2-CONST))
  8618. (if (and (= decl-type js2-LET)
  8619. (not ignore-not-in-block)
  8620. (or (= (js2-node-type js2-current-scope) js2-IF)
  8621. (js2-loop-node-p js2-current-scope)))
  8622. (js2-report-error "msg.let.decl.not.in.block")
  8623. (js2-define-new-symbol decl-type name node)))
  8624. ((or (= decl-type js2-VAR)
  8625. (= decl-type js2-FUNCTION))
  8626. (if symbol
  8627. (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
  8628. (js2-add-strict-warning "msg.var.redecl" name)
  8629. (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
  8630. (js2-add-strict-warning "msg.var.hides.arg" name)))
  8631. (js2-define-new-symbol decl-type name node
  8632. js2-current-script-or-fn)))
  8633. ((= decl-type js2-LP)
  8634. (if symbol
  8635. ;; must be duplicate parameter. Second parameter hides the
  8636. ;; first, so go ahead and add the second pararameter
  8637. (js2-report-warning "msg.dup.parms" name))
  8638. (js2-define-new-symbol decl-type name node))
  8639. (t (js2-code-bug)))))
  8640. (defun js2-parse-paren-expr-or-generator-comp ()
  8641. (let ((px-pos (js2-current-token-beg)))
  8642. (cond
  8643. ((and (>= js2-language-version 200)
  8644. (js2-match-token js2-FOR))
  8645. (js2-parse-generator-comp px-pos))
  8646. ((and (>= js2-language-version 200)
  8647. (js2-match-token js2-RP))
  8648. ;; Not valid expression syntax, but this is valid in an arrow
  8649. ;; function with no params: () => body.
  8650. (if (eq (js2-peek-token) js2-ARROW)
  8651. ;; Return whatever, it will hopefully be rewinded and
  8652. ;; reparsed when we reach the =>.
  8653. (make-js2-keyword-node :type js2-NULL)
  8654. (js2-report-error "msg.syntax")
  8655. (make-js2-error-node)))
  8656. (t
  8657. (let* ((js2-in-for-init nil)
  8658. (expr (js2-parse-expr))
  8659. (pn (make-js2-paren-node :pos px-pos
  8660. :expr expr)))
  8661. (js2-node-add-children pn (js2-paren-node-expr pn))
  8662. (js2-must-match js2-RP "msg.no.paren")
  8663. (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
  8664. pn)))))
  8665. (defun js2-parse-expr (&optional oneshot)
  8666. (let* ((pn (js2-parse-assign-expr))
  8667. (pos (js2-node-pos pn))
  8668. left
  8669. right
  8670. op-pos)
  8671. (while (and (not oneshot)
  8672. (js2-match-token js2-COMMA))
  8673. (setq op-pos (- (js2-current-token-beg) pos)) ; relative
  8674. (setq right (js2-parse-assign-expr)
  8675. left pn
  8676. pn (make-js2-infix-node :type js2-COMMA
  8677. :pos pos
  8678. :len (- js2-ts-cursor pos)
  8679. :op-pos op-pos
  8680. :left left
  8681. :right right))
  8682. (js2-node-add-children pn left right))
  8683. pn))
  8684. (defun js2-parse-assign-expr ()
  8685. (let ((tt (js2-get-token))
  8686. (pos (js2-current-token-beg))
  8687. pn left right op-pos
  8688. ts-state recorded-identifiers parsed-errors
  8689. async-p)
  8690. (if (= tt js2-YIELD)
  8691. (js2-parse-return-or-yield tt t)
  8692. ;; TODO(mooz): Bit confusing.
  8693. ;; If we meet `async` token and it's not part of `async
  8694. ;; function`, then this `async` is for a succeeding async arrow
  8695. ;; function.
  8696. ;; Since arrow function parsing doesn't rely on neither
  8697. ;; `js2-parse-function-stmt' nor `js2-parse-function-expr' that
  8698. ;; interpret `async` token, we trash `async` and just remember
  8699. ;; we met `async` keyword to `async-p'.
  8700. (when (js2-match-async-arrow-function)
  8701. (setq async-p t))
  8702. ;; Save the tokenizer state in case we find an arrow function
  8703. ;; and have to rewind.
  8704. (setq ts-state (make-js2-ts-state)
  8705. recorded-identifiers js2-recorded-identifiers
  8706. parsed-errors js2-parsed-errors)
  8707. ;; not yield - parse assignment expression
  8708. (setq pn (js2-parse-cond-expr)
  8709. tt (js2-get-token))
  8710. (cond
  8711. ((and (<= js2-first-assign tt)
  8712. (<= tt js2-last-assign))
  8713. ;; tt express assignment (=, |=, ^=, ..., %=)
  8714. (setq op-pos (- (js2-current-token-beg) pos) ; relative
  8715. left pn)
  8716. ;; The assigned node could be a js2-prop-get-node (foo.bar = 0), we only
  8717. ;; care about assignment to strict variable names.
  8718. (when (js2-name-node-p left)
  8719. (js2-check-strict-identifier left))
  8720. (setq right (js2-parse-assign-expr)
  8721. pn (make-js2-assign-node :type tt
  8722. :pos pos
  8723. :len (- (js2-node-end right) pos)
  8724. :op-pos op-pos
  8725. :left left
  8726. :right right))
  8727. (when js2-parse-ide-mode
  8728. (js2-highlight-assign-targets pn left right)
  8729. (js2-record-imenu-functions right left))
  8730. ;; do this last so ide checks above can use absolute positions
  8731. (js2-node-add-children pn left right))
  8732. ((and (>= js2-language-version 200)
  8733. (or
  8734. (= tt js2-ARROW)
  8735. (and async-p
  8736. (= (js2-peek-token) js2-ARROW))))
  8737. (js2-ts-seek ts-state)
  8738. (when async-p
  8739. (js2-record-face 'font-lock-keyword-face)
  8740. (js2-get-token))
  8741. (setq js2-recorded-identifiers recorded-identifiers
  8742. js2-parsed-errors parsed-errors)
  8743. (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil async-p)))
  8744. (t
  8745. (js2-unget-token)))
  8746. pn)))
  8747. (defun js2-parse-cond-expr ()
  8748. (let ((pos (js2-current-token-beg))
  8749. (pn (js2-parse-or-expr))
  8750. test-expr
  8751. if-true
  8752. if-false
  8753. q-pos
  8754. c-pos)
  8755. (when (js2-match-token js2-HOOK)
  8756. (setq q-pos (- (js2-current-token-beg) pos)
  8757. if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
  8758. (js2-must-match js2-COLON "msg.no.colon.cond")
  8759. (setq c-pos (- (js2-current-token-beg) pos)
  8760. if-false (js2-parse-assign-expr)
  8761. test-expr pn
  8762. pn (make-js2-cond-node :pos pos
  8763. :len (- (js2-node-end if-false) pos)
  8764. :test-expr test-expr
  8765. :true-expr if-true
  8766. :false-expr if-false
  8767. :q-pos q-pos
  8768. :c-pos c-pos))
  8769. (js2-node-add-children pn test-expr if-true if-false))
  8770. pn))
  8771. (defun js2-make-binary (type left parser &optional no-get)
  8772. "Helper for constructing a binary-operator AST node.
  8773. LEFT is the left-side-expression, already parsed, and the
  8774. binary operator should have just been matched.
  8775. PARSER is a function to call to parse the right operand,
  8776. or a `js2-node' struct if it has already been parsed.
  8777. FIXME: The latter option is unused?"
  8778. (let* ((pos (js2-node-pos left))
  8779. (op-pos (- (js2-current-token-beg) pos))
  8780. (right (if (js2-node-p parser)
  8781. parser
  8782. (unless no-get (js2-get-token))
  8783. (funcall parser)))
  8784. (pn (make-js2-infix-node :type type
  8785. :pos pos
  8786. :len (- (js2-node-end right) pos)
  8787. :op-pos op-pos
  8788. :left left
  8789. :right right)))
  8790. (js2-node-add-children pn left right)
  8791. pn))
  8792. (defun js2-parse-or-expr ()
  8793. (let ((pn (js2-parse-and-expr)))
  8794. (when (js2-match-token js2-OR)
  8795. (setq pn (js2-make-binary js2-OR
  8796. pn
  8797. 'js2-parse-or-expr)))
  8798. pn))
  8799. (defun js2-parse-and-expr ()
  8800. (let ((pn (js2-parse-bit-or-expr)))
  8801. (when (js2-match-token js2-AND)
  8802. (setq pn (js2-make-binary js2-AND
  8803. pn
  8804. 'js2-parse-and-expr)))
  8805. pn))
  8806. (defun js2-parse-bit-or-expr ()
  8807. (let ((pn (js2-parse-bit-xor-expr)))
  8808. (while (js2-match-token js2-BITOR)
  8809. (setq pn (js2-make-binary js2-BITOR
  8810. pn
  8811. 'js2-parse-bit-xor-expr)))
  8812. pn))
  8813. (defun js2-parse-bit-xor-expr ()
  8814. (let ((pn (js2-parse-bit-and-expr)))
  8815. (while (js2-match-token js2-BITXOR)
  8816. (setq pn (js2-make-binary js2-BITXOR
  8817. pn
  8818. 'js2-parse-bit-and-expr)))
  8819. pn))
  8820. (defun js2-parse-bit-and-expr ()
  8821. (let ((pn (js2-parse-eq-expr)))
  8822. (while (js2-match-token js2-BITAND)
  8823. (setq pn (js2-make-binary js2-BITAND
  8824. pn
  8825. 'js2-parse-eq-expr)))
  8826. pn))
  8827. (defconst js2-parse-eq-ops
  8828. (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
  8829. (defun js2-parse-eq-expr ()
  8830. (let ((pn (js2-parse-rel-expr))
  8831. tt)
  8832. (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
  8833. (setq pn (js2-make-binary tt
  8834. pn
  8835. 'js2-parse-rel-expr)))
  8836. (js2-unget-token)
  8837. pn))
  8838. (defconst js2-parse-rel-ops
  8839. (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
  8840. (defun js2-parse-rel-expr ()
  8841. (let ((pn (js2-parse-shift-expr))
  8842. (continue t)
  8843. tt)
  8844. (while continue
  8845. (setq tt (js2-get-token))
  8846. (cond
  8847. ((and js2-in-for-init (= tt js2-IN))
  8848. (js2-unget-token)
  8849. (setq continue nil))
  8850. ((memq tt js2-parse-rel-ops)
  8851. (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
  8852. (t
  8853. (js2-unget-token)
  8854. (setq continue nil))))
  8855. pn))
  8856. (defconst js2-parse-shift-ops
  8857. (list js2-LSH js2-URSH js2-RSH))
  8858. (defun js2-parse-shift-expr ()
  8859. (let ((pn (js2-parse-add-expr))
  8860. tt
  8861. (continue t))
  8862. (while continue
  8863. (setq tt (js2-get-token))
  8864. (if (memq tt js2-parse-shift-ops)
  8865. (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
  8866. (js2-unget-token)
  8867. (setq continue nil)))
  8868. pn))
  8869. (defun js2-parse-add-expr ()
  8870. (let ((pn (js2-parse-mul-expr))
  8871. tt
  8872. (continue t))
  8873. (while continue
  8874. (setq tt (js2-get-token))
  8875. (if (or (= tt js2-ADD) (= tt js2-SUB))
  8876. (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
  8877. (js2-unget-token)
  8878. (setq continue nil)))
  8879. pn))
  8880. (defconst js2-parse-mul-ops
  8881. (list js2-MUL js2-DIV js2-MOD))
  8882. (defun js2-parse-mul-expr ()
  8883. (let ((pn (js2-parse-expon-expr))
  8884. tt
  8885. (continue t))
  8886. (while continue
  8887. (setq tt (js2-get-token))
  8888. (if (memq tt js2-parse-mul-ops)
  8889. (setq pn (js2-make-binary tt pn 'js2-parse-expon-expr))
  8890. (js2-unget-token)
  8891. (setq continue nil)))
  8892. pn))
  8893. (defun js2-parse-expon-expr ()
  8894. (let ((pn (js2-parse-unary-expr)))
  8895. (when (>= js2-language-version 200)
  8896. (while (js2-match-token js2-EXPON)
  8897. (when (and (js2-unary-node-p pn)
  8898. (not (memq (js2-node-type pn) '(js2-INC js2-DEC))))
  8899. (js2-report-error "msg.syntax" nil
  8900. (js2-node-abs-pos pn) (js2-node-len pn)))
  8901. ;; Make it right-associative.
  8902. (setq pn (js2-make-binary js2-EXPON pn 'js2-parse-expon-expr))))
  8903. pn))
  8904. (defun js2-make-unary (beg type parser &rest args)
  8905. "Make a unary node starting at BEG of type TYPE.
  8906. If BEG is nil, `(js2-current-token-beg)' is used for the node
  8907. start position. PARSER is either a node (for postfix operators)
  8908. or a function to call to parse the operand (for prefix
  8909. operators)."
  8910. (let* ((pos (or beg (js2-current-token-beg)))
  8911. (postfix (js2-node-p parser))
  8912. (expr (if postfix
  8913. parser
  8914. (apply parser args)))
  8915. end
  8916. pn)
  8917. (if postfix ; e.g. i++
  8918. (setq pos (js2-node-pos expr)
  8919. end (js2-current-token-end))
  8920. (setq end (js2-node-end expr)))
  8921. (setq pn (make-js2-unary-node :type type
  8922. :pos pos
  8923. :len (- end pos)
  8924. :operand expr))
  8925. (js2-node-add-children pn expr)
  8926. pn))
  8927. (defconst js2-incrementable-node-types
  8928. (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
  8929. "Node types that can be the operand of a ++ or -- operator.")
  8930. (defun js2-check-bad-inc-dec (tt beg end unary)
  8931. (unless (memq (js2-node-type (js2-unary-node-operand unary))
  8932. js2-incrementable-node-types)
  8933. (js2-report-error (if (= tt js2-INC)
  8934. "msg.bad.incr"
  8935. "msg.bad.decr")
  8936. nil beg (- end beg))))
  8937. (defun js2-parse-unary-expr ()
  8938. (let ((tt (js2-current-token-type))
  8939. (beg (js2-current-token-beg)))
  8940. (cond
  8941. ((or (= tt js2-VOID)
  8942. (= tt js2-NOT)
  8943. (= tt js2-BITNOT)
  8944. (= tt js2-TYPEOF))
  8945. (js2-get-token)
  8946. (js2-make-unary beg tt 'js2-parse-unary-expr))
  8947. ((= tt js2-ADD)
  8948. (js2-get-token)
  8949. ;; Convert to special POS token in decompiler and parse tree
  8950. (js2-make-unary beg js2-POS 'js2-parse-unary-expr))
  8951. ((= tt js2-SUB)
  8952. (js2-get-token)
  8953. ;; Convert to special NEG token in decompiler and parse tree
  8954. (js2-make-unary beg js2-NEG 'js2-parse-unary-expr))
  8955. ((or (= tt js2-INC)
  8956. (= tt js2-DEC))
  8957. (js2-get-token)
  8958. (let ((beg2 (js2-current-token-beg))
  8959. (end (js2-current-token-end))
  8960. (expr (js2-make-unary beg tt 'js2-parse-member-expr t)))
  8961. (js2-check-bad-inc-dec tt beg2 end expr)
  8962. expr))
  8963. ((= tt js2-DELPROP)
  8964. (js2-get-token)
  8965. (js2-make-unary beg js2-DELPROP 'js2-parse-unary-expr))
  8966. ((js2-parse-await-maybe tt))
  8967. ((= tt js2-ERROR)
  8968. (js2-get-token)
  8969. (make-js2-error-node)) ; try to continue
  8970. ((and (= tt js2-LT)
  8971. js2-compiler-xml-available)
  8972. ;; XML stream encountered in expression.
  8973. (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
  8974. (t
  8975. (let ((pn (js2-parse-member-expr t))
  8976. ;; Don't look across a newline boundary for a postfix incop.
  8977. (tt (js2-peek-token-or-eol))
  8978. expr)
  8979. (when (or (= tt js2-INC) (= tt js2-DEC))
  8980. (js2-get-token)
  8981. (setf expr pn
  8982. pn (js2-make-unary (js2-node-pos expr) tt expr))
  8983. (js2-node-set-prop pn 'postfix t)
  8984. (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
  8985. pn)))))
  8986. (defun js2-parse-xml-initializer ()
  8987. "Parse an E4X XML initializer.
  8988. I'm parsing it the way Rhino parses it, but without the tree-rewriting.
  8989. Then I'll postprocess the result, depending on whether we're in IDE
  8990. mode or codegen mode, and generate the appropriate rewritten AST.
  8991. IDE mode uses a rich AST that models the XML structure. Codegen mode
  8992. just concatenates everything and makes a new XML or XMLList out of it."
  8993. (let ((tt (js2-get-first-xml-token))
  8994. pn-xml pn expr kids expr-pos
  8995. (continue t)
  8996. (first-token t))
  8997. (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
  8998. (js2-report-error "msg.syntax"))
  8999. (setq pn-xml (make-js2-xml-node))
  9000. (while continue
  9001. (if first-token
  9002. (setq first-token nil)
  9003. (setq tt (js2-get-next-xml-token)))
  9004. (cond
  9005. ;; js2-XML means we found a {expr} in the XML stream.
  9006. ;; The token string is the XML up to the left-curly.
  9007. ((= tt js2-XML)
  9008. (push (make-js2-string-node :pos (js2-current-token-beg)
  9009. :len (- js2-ts-cursor (js2-current-token-beg)))
  9010. kids)
  9011. (js2-must-match js2-LC "msg.syntax")
  9012. (setq expr-pos js2-ts-cursor
  9013. expr (if (eq (js2-peek-token) js2-RC)
  9014. (make-js2-empty-expr-node :pos expr-pos)
  9015. (js2-parse-expr)))
  9016. (js2-must-match js2-RC "msg.syntax")
  9017. (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
  9018. :len (js2-node-len expr)
  9019. :expr expr))
  9020. (js2-node-add-children pn expr)
  9021. (push pn kids))
  9022. ;; a js2-XMLEND token means we hit the final close-tag.
  9023. ((= tt js2-XMLEND)
  9024. (push (make-js2-string-node :pos (js2-current-token-beg)
  9025. :len (- js2-ts-cursor (js2-current-token-beg)))
  9026. kids)
  9027. (dolist (kid (nreverse kids))
  9028. (js2-block-node-push pn-xml kid))
  9029. (setf (js2-node-len pn-xml) (- js2-ts-cursor
  9030. (js2-node-pos pn-xml))
  9031. continue nil))
  9032. (t
  9033. (js2-report-error "msg.syntax")
  9034. (setq continue nil))))
  9035. pn-xml))
  9036. (defun js2-parse-argument-list ()
  9037. "Parse an argument list and return it as a Lisp list of nodes.
  9038. Returns the list in reverse order. Consumes the right-paren token."
  9039. (let (result)
  9040. (unless (js2-match-token js2-RP)
  9041. (cl-loop do
  9042. (let ((tt (js2-get-token))
  9043. (beg (js2-current-token-beg)))
  9044. (if (and (= tt js2-TRIPLEDOT)
  9045. (>= js2-language-version 200))
  9046. (push (js2-make-unary beg tt 'js2-parse-assign-expr) result)
  9047. (js2-unget-token)
  9048. (push (js2-parse-assign-expr) result)))
  9049. while
  9050. (and (js2-match-token js2-COMMA)
  9051. (or (< js2-language-version 200)
  9052. (not (= js2-RP (js2-peek-token))))))
  9053. (js2-must-match js2-RP "msg.no.paren.arg")
  9054. result)))
  9055. (defun js2-parse-member-expr (&optional allow-call-syntax)
  9056. (let ((tt (js2-current-token-type))
  9057. pn pos target args beg end init)
  9058. (if (/= tt js2-NEW)
  9059. (setq pn (js2-parse-primary-expr))
  9060. ;; parse a 'new' expression
  9061. (js2-get-token)
  9062. (setq pos (js2-current-token-beg)
  9063. beg pos
  9064. target (js2-parse-member-expr)
  9065. end (js2-node-end target)
  9066. pn (make-js2-new-node :pos pos
  9067. :target target
  9068. :len (- end pos)))
  9069. (js2-highlight-function-call (js2-current-token))
  9070. (js2-node-add-children pn target)
  9071. (when (js2-match-token js2-LP)
  9072. ;; Add the arguments to pn, if any are supplied.
  9073. (setf beg pos ; start of "new" keyword
  9074. pos (js2-current-token-beg)
  9075. args (nreverse (js2-parse-argument-list))
  9076. (js2-new-node-args pn) args
  9077. end (js2-current-token-end)
  9078. (js2-new-node-lp pn) (- pos beg)
  9079. (js2-new-node-rp pn) (- end 1 beg))
  9080. (apply #'js2-node-add-children pn args))
  9081. (when (and js2-allow-rhino-new-expr-initializer
  9082. (js2-match-token js2-LC))
  9083. (setf init (js2-parse-object-literal)
  9084. end (js2-node-end init)
  9085. (js2-new-node-initializer pn) init)
  9086. (js2-node-add-children pn init))
  9087. (setf (js2-node-len pn) (- end beg))) ; end outer if
  9088. (js2-parse-member-expr-tail allow-call-syntax pn)))
  9089. (defun js2-parse-member-expr-tail (allow-call-syntax pn)
  9090. "Parse a chain of property/array accesses or function calls.
  9091. Includes parsing for E4X operators like `..' and `.@'.
  9092. If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
  9093. Returns an expression tree that includes PN, the parent node."
  9094. (let (tt
  9095. (continue t))
  9096. (while continue
  9097. (setq tt (js2-get-token))
  9098. (cond
  9099. ((or (= tt js2-DOT) (= tt js2-DOTDOT))
  9100. (setq pn (js2-parse-property-access tt pn)))
  9101. ((= tt js2-DOTQUERY)
  9102. (setq pn (js2-parse-dot-query pn)))
  9103. ((= tt js2-LB)
  9104. (setq pn (js2-parse-element-get pn)))
  9105. ((= tt js2-LP)
  9106. (js2-unget-token)
  9107. (if allow-call-syntax
  9108. (setq pn (js2-parse-function-call pn))
  9109. (setq continue nil)))
  9110. ((= tt js2-TEMPLATE_HEAD)
  9111. (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
  9112. ((= tt js2-NO_SUBS_TEMPLATE)
  9113. (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
  9114. (t
  9115. (js2-unget-token)
  9116. (setq continue nil)))
  9117. (if (>= js2-highlight-level 2)
  9118. (js2-parse-highlight-member-expr-node pn)))
  9119. pn))
  9120. (defun js2-parse-tagged-template (tag-node tpl-node)
  9121. "Parse tagged template expression."
  9122. (let* ((pos (js2-node-pos tag-node))
  9123. (pn (make-js2-tagged-template-node :pos pos
  9124. :len (- (js2-current-token-end) pos)
  9125. :tag tag-node
  9126. :template tpl-node)))
  9127. (js2-node-add-children pn tag-node tpl-node)
  9128. pn))
  9129. (defun js2-parse-dot-query (pn)
  9130. "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
  9131. Last token parsed must be `js2-DOTQUERY'."
  9132. (let ((pos (js2-node-pos pn))
  9133. op-pos expr end)
  9134. (js2-must-have-xml)
  9135. (js2-set-requires-activation)
  9136. (setq op-pos (js2-current-token-beg)
  9137. expr (js2-parse-expr)
  9138. end (js2-node-end expr)
  9139. pn (make-js2-xml-dot-query-node :left pn
  9140. :pos pos
  9141. :op-pos op-pos
  9142. :right expr))
  9143. (js2-node-add-children pn
  9144. (js2-xml-dot-query-node-left pn)
  9145. (js2-xml-dot-query-node-right pn))
  9146. (if (js2-must-match js2-RP "msg.no.paren")
  9147. (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
  9148. end (js2-current-token-end)))
  9149. (setf (js2-node-len pn) (- end pos))
  9150. pn))
  9151. (defun js2-parse-element-get (pn)
  9152. "Parse an element-get expression, e.g. foo[bar].
  9153. Last token parsed must be `js2-RB'."
  9154. (let ((lb (js2-current-token-beg))
  9155. (pos (js2-node-pos pn))
  9156. rb expr)
  9157. (setq expr (js2-parse-expr))
  9158. (if (js2-must-match js2-RB "msg.no.bracket.index")
  9159. (setq rb (js2-current-token-beg)))
  9160. (setq pn (make-js2-elem-get-node :target pn
  9161. :pos pos
  9162. :element expr
  9163. :lb (js2-relpos lb pos)
  9164. :rb (js2-relpos rb pos)
  9165. :len (- (js2-current-token-end) pos)))
  9166. (js2-node-add-children pn
  9167. (js2-elem-get-node-target pn)
  9168. (js2-elem-get-node-element pn))
  9169. pn))
  9170. (defun js2-highlight-function-call (token)
  9171. (when (eq (js2-token-type token) js2-NAME)
  9172. (js2-record-face 'js2-function-call token)))
  9173. (defun js2-parse-function-call (pn)
  9174. (js2-highlight-function-call (js2-current-token))
  9175. (js2-get-token)
  9176. (let (args
  9177. (pos (js2-node-pos pn)))
  9178. (setq pn (make-js2-call-node :pos pos
  9179. :target pn
  9180. :lp (- (js2-current-token-beg) pos)))
  9181. (js2-node-add-children pn (js2-call-node-target pn))
  9182. ;; Add the arguments to pn, if any are supplied.
  9183. (setf args (nreverse (js2-parse-argument-list))
  9184. (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
  9185. (js2-call-node-args pn) args)
  9186. (apply #'js2-node-add-children pn args)
  9187. (setf (js2-node-len pn) (- js2-ts-cursor pos))
  9188. pn))
  9189. (defun js2-parse-property-access (tt pn)
  9190. "Parse a property access, XML descendants access, or XML attr access."
  9191. (let ((member-type-flags 0)
  9192. (dot-pos (js2-current-token-beg))
  9193. (dot-len (if (= tt js2-DOTDOT) 2 1))
  9194. name
  9195. ref ; right side of . or .. operator
  9196. result)
  9197. (when (= tt js2-DOTDOT)
  9198. (js2-must-have-xml)
  9199. (setq member-type-flags js2-descendants-flag))
  9200. (if (not js2-compiler-xml-available)
  9201. (progn
  9202. (js2-must-match-prop-name "msg.no.name.after.dot")
  9203. (setq name (js2-create-name-node t js2-GETPROP)
  9204. result (make-js2-prop-get-node :left pn
  9205. :pos (js2-current-token-beg)
  9206. :right name
  9207. :len (js2-current-token-len)))
  9208. (js2-node-add-children result pn name)
  9209. result)
  9210. ;; otherwise look for XML operators
  9211. (setf result (if (= tt js2-DOT)
  9212. (make-js2-prop-get-node)
  9213. (make-js2-infix-node :type js2-DOTDOT))
  9214. (js2-node-pos result) (js2-node-pos pn)
  9215. (js2-infix-node-op-pos result) dot-pos
  9216. (js2-infix-node-left result) pn ; do this after setting position
  9217. tt (js2-get-prop-name-token))
  9218. (cond
  9219. ;; handles: name, ns::name, ns::*, ns::[expr]
  9220. ((= tt js2-NAME)
  9221. (setq ref (js2-parse-property-name -1 nil member-type-flags)))
  9222. ;; handles: *, *::name, *::*, *::[expr]
  9223. ((= tt js2-MUL)
  9224. (setq ref (js2-parse-property-name nil "*" member-type-flags)))
  9225. ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
  9226. ((= tt js2-XMLATTR)
  9227. (setq result (js2-parse-attribute-access)))
  9228. (t
  9229. (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
  9230. (if ref
  9231. (setf (js2-node-len result) (- (js2-node-end ref)
  9232. (js2-node-pos result))
  9233. (js2-infix-node-right result) ref))
  9234. (if (js2-infix-node-p result)
  9235. (js2-node-add-children result
  9236. (js2-infix-node-left result)
  9237. (js2-infix-node-right result)))
  9238. result)))
  9239. (defun js2-parse-attribute-access ()
  9240. "Parse an E4X XML attribute expression.
  9241. This includes expressions of the forms:
  9242. @attr @ns::attr @ns::*
  9243. @* @*::attr @*::*
  9244. @[expr] @*::[expr] @ns::[expr]
  9245. Called if we peeked an '@' token."
  9246. (let ((tt (js2-get-prop-name-token))
  9247. (at-pos (js2-current-token-beg)))
  9248. (cond
  9249. ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
  9250. ((= tt js2-NAME)
  9251. (js2-parse-property-name at-pos nil 0))
  9252. ;; handles: @*, @*::name, @*::*, @*::[expr]
  9253. ((= tt js2-MUL)
  9254. (js2-parse-property-name (js2-current-token-beg) "*" 0))
  9255. ;; handles @[expr]
  9256. ((= tt js2-LB)
  9257. (js2-parse-xml-elem-ref at-pos))
  9258. (t
  9259. (js2-report-error "msg.no.name.after.xmlAttr")
  9260. ;; Avoid cascaded errors that happen if we make an error node here.
  9261. (js2-parse-property-name (js2-current-token-beg) "" 0)))))
  9262. (defun js2-parse-property-name (at-pos s member-type-flags)
  9263. "Check if :: follows name in which case it becomes qualified name.
  9264. AT-POS is a natural number if we just read an '@' token, else nil.
  9265. S is the name or string that was matched: an identifier, 'throw' or '*'.
  9266. MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
  9267. Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
  9268. operator, or the name is followed by ::. For a plain name, returns a
  9269. `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
  9270. (let ((pos (or at-pos (js2-current-token-beg)))
  9271. colon-pos
  9272. (name (js2-create-name-node t (js2-current-token-type) s))
  9273. ns tt pn)
  9274. (catch 'return
  9275. (when (js2-match-token js2-COLONCOLON)
  9276. (setq ns name
  9277. colon-pos (js2-current-token-beg)
  9278. tt (js2-get-prop-name-token))
  9279. (cond
  9280. ;; handles name::name
  9281. ((= tt js2-NAME)
  9282. (setq name (js2-create-name-node)))
  9283. ;; handles name::*
  9284. ((= tt js2-MUL)
  9285. (setq name (js2-create-name-node nil nil "*")))
  9286. ;; handles name::[expr]
  9287. ((= tt js2-LB)
  9288. (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
  9289. (t
  9290. (js2-report-error "msg.no.name.after.coloncolon"))))
  9291. (if (and (null ns) (zerop member-type-flags))
  9292. name
  9293. (prog1
  9294. (setq pn
  9295. (make-js2-xml-prop-ref-node :pos pos
  9296. :len (- (js2-node-end name) pos)
  9297. :at-pos at-pos
  9298. :colon-pos colon-pos
  9299. :propname name))
  9300. (js2-node-add-children pn name))))))
  9301. (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
  9302. "Parse the [expr] portion of an xml element reference.
  9303. For instance, @[expr], @*::[expr], or ns::[expr]."
  9304. (let* ((lb (js2-current-token-beg))
  9305. (pos (or at-pos lb))
  9306. rb
  9307. (expr (js2-parse-expr))
  9308. (end (js2-node-end expr))
  9309. pn)
  9310. (if (js2-must-match js2-RB "msg.no.bracket.index")
  9311. (setq rb (js2-current-token-beg)
  9312. end (js2-current-token-end)))
  9313. (prog1
  9314. (setq pn
  9315. (make-js2-xml-elem-ref-node :pos pos
  9316. :len (- end pos)
  9317. :namespace namespace
  9318. :colon-pos colon-pos
  9319. :at-pos at-pos
  9320. :expr expr
  9321. :lb (js2-relpos lb pos)
  9322. :rb (js2-relpos rb pos)))
  9323. (js2-node-add-children pn namespace expr))))
  9324. (defun js2-parse-destruct-primary-expr ()
  9325. (let ((js2-is-in-destructuring t))
  9326. (js2-parse-primary-expr)))
  9327. (defun js2-parse-primary-expr ()
  9328. "Parse a literal (leaf) expression of some sort.
  9329. Includes complex literals such as functions, object-literals,
  9330. array-literals, array comprehensions and regular expressions."
  9331. (let (tt node)
  9332. (setq tt (js2-current-token-type))
  9333. (cond
  9334. ((= tt js2-CLASS)
  9335. (js2-parse-class-expr))
  9336. ((= tt js2-FUNCTION)
  9337. (js2-parse-function-expr))
  9338. ((js2-match-async-function)
  9339. (js2-parse-function-expr t))
  9340. ((= tt js2-LB)
  9341. (js2-parse-array-comp-or-literal))
  9342. ((= tt js2-LC)
  9343. (js2-parse-object-literal))
  9344. ((= tt js2-LET)
  9345. (js2-parse-let (js2-current-token-beg)))
  9346. ((= tt js2-LP)
  9347. (js2-parse-paren-expr-or-generator-comp))
  9348. ((= tt js2-XMLATTR)
  9349. (js2-must-have-xml)
  9350. (js2-parse-attribute-access))
  9351. ((= tt js2-NAME)
  9352. (js2-parse-name tt))
  9353. ((= tt js2-NUMBER)
  9354. (setq node (make-js2-number-node))
  9355. (when (and js2-in-use-strict-directive
  9356. (= (js2-number-node-num-base node) 8)
  9357. (js2-number-node-legacy-octal-p node))
  9358. (js2-report-error "msg.no.octal.strict"))
  9359. node)
  9360. ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
  9361. (make-js2-string-node :type tt))
  9362. ((= tt js2-TEMPLATE_HEAD)
  9363. (js2-parse-template-literal))
  9364. ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
  9365. ;; Got / or /= which in this context means a regexp literal
  9366. (let* ((px-pos (js2-current-token-beg))
  9367. (flags (js2-read-regexp tt px-pos))
  9368. (end (js2-current-token-end)))
  9369. (prog1
  9370. (make-js2-regexp-node :pos px-pos
  9371. :len (- end px-pos)
  9372. :value (js2-current-token-string)
  9373. :flags flags)
  9374. (js2-set-face px-pos end 'font-lock-string-face 'record))))
  9375. ((or (= tt js2-NULL)
  9376. (= tt js2-THIS)
  9377. (= tt js2-SUPER)
  9378. (= tt js2-FALSE)
  9379. (= tt js2-TRUE))
  9380. (make-js2-keyword-node :type tt))
  9381. ((= tt js2-TRIPLEDOT)
  9382. ;; Likewise, only valid in an arrow function with a rest param.
  9383. (if (and (js2-match-token js2-NAME)
  9384. (js2-match-token js2-RP)
  9385. (eq (js2-peek-token) js2-ARROW))
  9386. (progn
  9387. (js2-unget-token) ; Put back the right paren.
  9388. ;; See the previous case.
  9389. (make-js2-keyword-node :type js2-NULL))
  9390. (js2-report-error "msg.syntax")
  9391. (make-js2-error-node)))
  9392. ((= tt js2-RESERVED)
  9393. (js2-report-error "msg.reserved.id")
  9394. (make-js2-name-node))
  9395. ((= tt js2-ERROR)
  9396. ;; the scanner or one of its subroutines reported the error.
  9397. (make-js2-error-node))
  9398. ((= tt js2-EOF)
  9399. (let* ((px-pos (point-at-bol))
  9400. (len (- js2-ts-cursor px-pos)))
  9401. (js2-report-error "msg.unexpected.eof" nil px-pos len))
  9402. (make-js2-error-node :pos (1- js2-ts-cursor)))
  9403. (t
  9404. (js2-report-error "msg.syntax")
  9405. (make-js2-error-node)))))
  9406. (defun js2-parse-template-literal ()
  9407. (let ((beg (js2-current-token-beg))
  9408. (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
  9409. (tt js2-TEMPLATE_HEAD))
  9410. (while (eq tt js2-TEMPLATE_HEAD)
  9411. (push (js2-parse-expr) kids)
  9412. (js2-must-match js2-RC "msg.syntax")
  9413. (setq tt (js2-get-token 'TEMPLATE_TAIL))
  9414. (push (make-js2-string-node :type tt) kids))
  9415. (setq kids (nreverse kids))
  9416. (let ((tpl (make-js2-template-node :pos beg
  9417. :len (- (js2-current-token-end) beg)
  9418. :kids kids)))
  9419. (apply #'js2-node-add-children tpl kids)
  9420. tpl)))
  9421. (defun js2-parse-name (_tt)
  9422. (let ((name (js2-current-token-string))
  9423. node)
  9424. (setq node (if js2-compiler-xml-available
  9425. (js2-parse-property-name nil name 0)
  9426. (js2-create-name-node 'check-activation nil name)))
  9427. (if (and js2-highlight-external-variables
  9428. ;; FIXME: What's TRT for `js2-xml-ref-node'?
  9429. (js2-name-node-p node))
  9430. (js2-record-name-node node))
  9431. node))
  9432. (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
  9433. (js2-add-strict-warning
  9434. msg nil
  9435. ;; back up from comma to beginning of line or array/objlit
  9436. (max (if elems
  9437. (js2-node-pos (car elems))
  9438. pos)
  9439. (save-excursion
  9440. (goto-char comma-pos)
  9441. (back-to-indentation)
  9442. (point)))
  9443. comma-pos))
  9444. (defun js2-parse-array-comp-or-literal ()
  9445. (let ((pos (js2-current-token-beg)))
  9446. (if (and (>= js2-language-version 200)
  9447. (js2-match-token js2-FOR))
  9448. (js2-parse-array-comp pos)
  9449. (js2-parse-array-literal pos))))
  9450. (defun js2-parse-array-literal (pos)
  9451. (let ((after-lb-or-comma t)
  9452. after-comma tt elems pn was-rest
  9453. (continue t))
  9454. (unless js2-is-in-destructuring
  9455. (js2-push-scope (make-js2-scope))) ; for the legacy array comp
  9456. (while continue
  9457. (setq tt (js2-get-token))
  9458. (cond
  9459. ;; end of array
  9460. ((or (= tt js2-RB)
  9461. (= tt js2-EOF)) ; prevent infinite loop
  9462. (if (= tt js2-EOF)
  9463. (js2-report-error "msg.no.bracket.arg" nil pos))
  9464. (when (and after-comma (< js2-language-version 170))
  9465. (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
  9466. pos (remove nil elems) after-comma))
  9467. (setq continue nil
  9468. pn (make-js2-array-node :pos pos
  9469. :len (- js2-ts-cursor pos)
  9470. :elems (nreverse elems)))
  9471. (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
  9472. ;; anything after rest element (...foo)
  9473. (was-rest
  9474. (js2-report-error "msg.param.after.rest"))
  9475. ;; comma
  9476. ((= tt js2-COMMA)
  9477. (setq after-comma (js2-current-token-end))
  9478. (if (not after-lb-or-comma)
  9479. (setq after-lb-or-comma t)
  9480. (push nil elems)))
  9481. ;; array comp
  9482. ((and (>= js2-language-version 170)
  9483. (not js2-is-in-destructuring)
  9484. (= tt js2-FOR) ; check for array comprehension
  9485. (not after-lb-or-comma) ; "for" can't follow a comma
  9486. elems ; must have at least 1 element
  9487. (not (cdr elems))) ; but no 2nd element
  9488. (js2-unget-token)
  9489. (setf continue nil
  9490. pn (js2-parse-legacy-array-comp (car elems) pos)))
  9491. ;; another element
  9492. (t
  9493. (unless after-lb-or-comma
  9494. (js2-report-error "msg.no.bracket.arg"))
  9495. (if (and (= tt js2-TRIPLEDOT)
  9496. (>= js2-language-version 200))
  9497. ;; rest/spread operator
  9498. (progn
  9499. (push (js2-make-unary nil tt 'js2-parse-assign-expr)
  9500. elems)
  9501. (if js2-is-in-destructuring
  9502. (setq was-rest t)))
  9503. (js2-unget-token)
  9504. (push (js2-parse-assign-expr) elems))
  9505. (setq after-lb-or-comma nil
  9506. after-comma nil))))
  9507. (unless js2-is-in-destructuring
  9508. (js2-pop-scope))
  9509. pn))
  9510. (defun js2-parse-legacy-array-comp (expr pos)
  9511. "Parse a legacy array comprehension (JavaScript 1.7).
  9512. EXPR is the first expression after the opening left-bracket.
  9513. POS is the beginning of the LB token preceding EXPR.
  9514. We should have just parsed the 'for' keyword before calling this function."
  9515. (let ((current-scope js2-current-scope)
  9516. loops first filter result)
  9517. (unwind-protect
  9518. (progn
  9519. (while (js2-match-token js2-FOR)
  9520. (let ((loop (make-js2-comp-loop-node)))
  9521. (js2-push-scope loop)
  9522. (push loop loops)
  9523. (js2-parse-comp-loop loop)))
  9524. ;; First loop takes expr scope's parent.
  9525. (setf (js2-scope-parent-scope (setq first (car (last loops))))
  9526. (js2-scope-parent-scope current-scope))
  9527. ;; Set expr scope's parent to the last loop.
  9528. (setf (js2-scope-parent-scope current-scope) (car loops))
  9529. (if (/= (js2-get-token) js2-IF)
  9530. (js2-unget-token)
  9531. (setq filter (js2-parse-condition))))
  9532. (dotimes (_ (1- (length loops)))
  9533. (js2-pop-scope)))
  9534. (js2-must-match js2-RB "msg.no.bracket.arg" pos)
  9535. (setq result (make-js2-comp-node :pos pos
  9536. :len (- js2-ts-cursor pos)
  9537. :result expr
  9538. :loops (nreverse loops)
  9539. :filters (and filter (list (car filter)))
  9540. :form 'LEGACY_ARRAY))
  9541. ;; Set comp loop's parent to the last loop.
  9542. ;; TODO: Get rid of the bogus expr scope.
  9543. (setf (js2-scope-parent-scope result) first)
  9544. (apply #'js2-node-add-children result expr (car filter)
  9545. (js2-comp-node-loops result))
  9546. result))
  9547. (defun js2-parse-array-comp (pos)
  9548. "Parse an ES6 array comprehension.
  9549. POS is the beginning of the LB token.
  9550. We should have just parsed the 'for' keyword before calling this function."
  9551. (let ((pn (js2-parse-comprehension pos 'ARRAY)))
  9552. (js2-must-match js2-RB "msg.no.bracket.arg" pos)
  9553. pn))
  9554. (defun js2-parse-generator-comp (pos)
  9555. (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
  9556. (js2-current-script-or-fn
  9557. (make-js2-function-node :generator-type 'COMPREHENSION))
  9558. (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
  9559. (js2-must-match js2-RP "msg.no.paren" pos)
  9560. pn))
  9561. (defun js2-parse-comprehension (pos form)
  9562. (let (loops filters expr result last)
  9563. (unwind-protect
  9564. (progn
  9565. (js2-unget-token)
  9566. (while (js2-match-token js2-FOR)
  9567. (let ((loop (make-js2-comp-loop-node)))
  9568. (js2-push-scope loop)
  9569. (push loop loops)
  9570. (js2-parse-comp-loop loop)))
  9571. (while (js2-match-token js2-IF)
  9572. (push (car (js2-parse-condition)) filters))
  9573. (setq expr (js2-parse-assign-expr))
  9574. (setq last (car loops)))
  9575. (dolist (_ loops)
  9576. (js2-pop-scope)))
  9577. (setq result (make-js2-comp-node :pos pos
  9578. :len (- js2-ts-cursor pos)
  9579. :result expr
  9580. :loops (nreverse loops)
  9581. :filters (nreverse filters)
  9582. :form form))
  9583. (apply #'js2-node-add-children result (js2-comp-node-loops result))
  9584. (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
  9585. (setf (js2-scope-parent-scope result) last)
  9586. result))
  9587. (defun js2-parse-comp-loop (pn &optional only-of-p)
  9588. "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
  9589. The current token should be the initial FOR.
  9590. If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
  9591. (let ((pos (js2-comp-loop-node-pos pn))
  9592. tt iter obj foreach-p forof-p in-pos each-pos lp rp)
  9593. (when (and (not only-of-p) (js2-match-token js2-NAME))
  9594. (if (string= (js2-current-token-string) "each")
  9595. (progn
  9596. (setq foreach-p t
  9597. each-pos (- (js2-current-token-beg) pos)) ; relative
  9598. (js2-record-face 'font-lock-keyword-face))
  9599. (js2-report-error "msg.no.paren.for")))
  9600. (if (js2-must-match js2-LP "msg.no.paren.for")
  9601. (setq lp (- (js2-current-token-beg) pos)))
  9602. (setq tt (js2-peek-token))
  9603. (cond
  9604. ((or (= tt js2-LB)
  9605. (= tt js2-LC))
  9606. (js2-get-token)
  9607. (setq iter (js2-parse-destruct-primary-expr))
  9608. (js2-define-destruct-symbols iter js2-LET
  9609. 'font-lock-variable-name-face t))
  9610. ((js2-match-token js2-NAME)
  9611. (setq iter (js2-create-name-node)))
  9612. (t
  9613. (js2-report-error "msg.bad.var")))
  9614. ;; Define as a let since we want the scope of the variable to
  9615. ;; be restricted to the array comprehension
  9616. (if (js2-name-node-p iter)
  9617. (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
  9618. (if (or (and (not only-of-p) (js2-match-token js2-IN))
  9619. (and (>= js2-language-version 200)
  9620. (js2-match-contextual-kwd "of")
  9621. (setq forof-p t)))
  9622. (setq in-pos (- (js2-current-token-beg) pos))
  9623. (js2-report-error "msg.in.after.for.name"))
  9624. (setq obj (js2-parse-expr))
  9625. (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
  9626. (setq rp (- (js2-current-token-beg) pos)))
  9627. (setf (js2-node-pos pn) pos
  9628. (js2-node-len pn) (- js2-ts-cursor pos)
  9629. (js2-comp-loop-node-iterator pn) iter
  9630. (js2-comp-loop-node-object pn) obj
  9631. (js2-comp-loop-node-in-pos pn) in-pos
  9632. (js2-comp-loop-node-each-pos pn) each-pos
  9633. (js2-comp-loop-node-foreach-p pn) foreach-p
  9634. (js2-comp-loop-node-forof-p pn) forof-p
  9635. (js2-comp-loop-node-lp pn) lp
  9636. (js2-comp-loop-node-rp pn) rp)
  9637. (js2-node-add-children pn iter obj)
  9638. pn))
  9639. (defun js2-parse-class-stmt ()
  9640. (let ((pos (js2-current-token-beg))
  9641. (_ (js2-must-match-name "msg.unnamed.class.stmt"))
  9642. (name (js2-create-name-node t)))
  9643. (js2-set-face (js2-node-pos name) (js2-node-end name)
  9644. 'font-lock-function-name-face 'record)
  9645. (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
  9646. (js2-record-imenu-functions node name)
  9647. (js2-define-symbol js2-FUNCTION
  9648. (js2-name-node-name name)
  9649. node)
  9650. node)))
  9651. (defun js2-parse-class-expr ()
  9652. (let ((pos (js2-current-token-beg))
  9653. name)
  9654. (when (js2-match-token js2-NAME)
  9655. (setq name (js2-create-name-node t)))
  9656. (js2-parse-class pos 'CLASS_EXPRESSION name)))
  9657. (defun js2-parse-class (pos form name)
  9658. ;; class X [extends ...] {
  9659. (let (pn elems extends)
  9660. (if (js2-match-token js2-EXTENDS)
  9661. (if (= (js2-peek-token) js2-LC)
  9662. (js2-report-error "msg.missing.extends")
  9663. ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
  9664. (setq extends (js2-parse-assign-expr))
  9665. (if (not extends)
  9666. (js2-report-error "msg.bad.extends"))))
  9667. (js2-must-match js2-LC "msg.no.brace.class")
  9668. (setq elems (js2-parse-object-literal-elems t)
  9669. pn (make-js2-class-node :pos pos
  9670. :len (- js2-ts-cursor pos)
  9671. :form form
  9672. :name name
  9673. :extends extends
  9674. :elems elems))
  9675. (apply #'js2-node-add-children
  9676. pn name extends (js2-class-node-elems pn))
  9677. pn))
  9678. (defun js2-parse-object-literal ()
  9679. (let* ((pos (js2-current-token-beg))
  9680. (elems (js2-parse-object-literal-elems))
  9681. (result (make-js2-object-node :pos pos
  9682. :len (- js2-ts-cursor pos)
  9683. :elems elems)))
  9684. (apply #'js2-node-add-children result (js2-object-node-elems result))
  9685. result))
  9686. (defun js2-property-key-string (property-node)
  9687. "Return the key of PROPERTY-NODE (a `js2-object-prop-node' or
  9688. `js2-method-node') as a string, or nil if it can't be
  9689. represented as a string (e.g., the key is computed by an
  9690. expression)."
  9691. (cond
  9692. ((js2-unary-node-p property-node) nil) ;; {...foo}
  9693. (t
  9694. (let ((key (js2-infix-node-left property-node)))
  9695. (when (js2-computed-prop-name-node-p key)
  9696. (setq key (js2-computed-prop-name-node-expr key)))
  9697. (cond
  9698. ((js2-name-node-p key)
  9699. (js2-name-node-name key))
  9700. ((js2-string-node-p key)
  9701. (js2-string-node-value key))
  9702. ((js2-number-node-p key)
  9703. (js2-number-node-value key)))))))
  9704. (defun js2-parse-object-literal-elems (&optional class-p)
  9705. (let ((pos (js2-current-token-beg))
  9706. (static nil)
  9707. (continue t)
  9708. tt elems elem
  9709. elem-key-string previous-elem-key-string
  9710. after-comma previous-token)
  9711. (while continue
  9712. (setq tt (js2-get-prop-name-token)
  9713. static nil
  9714. elem nil
  9715. previous-token nil)
  9716. ;; Handle 'static' keyword only if we're in a class
  9717. (when (and class-p (= js2-NAME tt)
  9718. (string= "static" (js2-current-token-string)))
  9719. (js2-record-face 'font-lock-keyword-face)
  9720. (setq static t
  9721. tt (js2-get-prop-name-token)))
  9722. ;; Handle generator * before the property name for in-line functions
  9723. (when (and (>= js2-language-version 200)
  9724. (= js2-MUL tt))
  9725. (setq previous-token (js2-current-token)
  9726. tt (js2-get-prop-name-token)))
  9727. ;; Handle getter, setter and async methods
  9728. (let ((prop (js2-current-token-string)))
  9729. (when (and (>= js2-language-version 200)
  9730. (= js2-NAME tt)
  9731. (member prop '("get" "set" "async"))
  9732. (member (js2-peek-token 'KEYWORD_IS_NAME)
  9733. (list js2-NAME js2-STRING js2-NUMBER js2-LB)))
  9734. (setq previous-token (js2-current-token)
  9735. tt (js2-get-prop-name-token))))
  9736. (cond
  9737. ;; Rest/spread (...expr)
  9738. ((and (>= js2-language-version 200)
  9739. (not class-p) (not static) (not previous-token)
  9740. (= js2-TRIPLEDOT tt))
  9741. (setq after-comma nil
  9742. elem (js2-make-unary nil js2-TRIPLEDOT 'js2-parse-assign-expr)))
  9743. ;; Found a key/value property (of any sort)
  9744. ((member tt (list js2-NAME js2-STRING js2-NUMBER js2-LB))
  9745. (setq after-comma nil
  9746. elem (js2-parse-named-prop tt previous-token class-p))
  9747. (if (and (null elem)
  9748. (not js2-recover-from-parse-errors))
  9749. (setq continue nil)))
  9750. ;; Break out of loop, and handle trailing commas.
  9751. ((or (= tt js2-RC)
  9752. (= tt js2-EOF))
  9753. (js2-unget-token)
  9754. (setq continue nil)
  9755. (if after-comma
  9756. (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
  9757. pos elems after-comma)))
  9758. ;; Skip semicolons in a class body
  9759. ((and class-p
  9760. (= tt js2-SEMI))
  9761. nil)
  9762. (t
  9763. (js2-report-error "msg.bad.prop")
  9764. (unless js2-recover-from-parse-errors
  9765. (setq continue nil)))) ; end switch
  9766. ;; Handle static for classes' codegen.
  9767. (if static
  9768. (if elem (js2-node-set-prop elem 'STATIC t)
  9769. (js2-report-error "msg.unexpected.static")))
  9770. ;; Handle commas, depending on class-p.
  9771. (let ((tok (js2-get-prop-name-token)))
  9772. (if (eq tok js2-COMMA)
  9773. (if class-p
  9774. (js2-report-error "msg.class.unexpected.comma")
  9775. (setq after-comma (js2-current-token-end)))
  9776. (js2-unget-token)
  9777. (unless class-p (setq continue nil))))
  9778. (when elem
  9779. (when (and js2-in-use-strict-directive
  9780. (setq elem-key-string (js2-property-key-string elem))
  9781. (cl-some
  9782. (lambda (previous-elem)
  9783. (and (setq previous-elem-key-string
  9784. (js2-property-key-string previous-elem))
  9785. ;; Check if the property is a duplicate.
  9786. (string= previous-elem-key-string elem-key-string)
  9787. ;; But make an exception for getter / setter pairs.
  9788. (not (and (js2-method-node-p elem)
  9789. (js2-method-node-p previous-elem)
  9790. (let ((type (js2-node-get-prop (js2-method-node-right elem) 'METHOD_TYPE))
  9791. (previous-type (js2-node-get-prop (js2-method-node-right previous-elem) 'METHOD_TYPE)))
  9792. (and (member type '(GET SET))
  9793. (member previous-type '(GET SET))
  9794. (not (eq type previous-type))))))))
  9795. elems))
  9796. (js2-report-error "msg.dup.obj.lit.prop.strict"
  9797. elem-key-string
  9798. (js2-node-abs-pos (js2-infix-node-left elem))
  9799. (js2-node-len (js2-infix-node-left elem))))
  9800. ;; Append any parsed element.
  9801. (push elem elems))) ; end loop
  9802. (js2-must-match js2-RC "msg.no.brace.prop")
  9803. (nreverse elems)))
  9804. (defun js2-parse-named-prop (tt previous-token &optional class-p)
  9805. "Parse a name, string, or getter/setter object property.
  9806. When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
  9807. (let ((key (js2-parse-prop-name tt))
  9808. (prop (and previous-token (js2-token-string previous-token)))
  9809. (property-type (when previous-token
  9810. (if (= (js2-token-type previous-token) js2-MUL)
  9811. "*"
  9812. (js2-token-string previous-token))))
  9813. pos)
  9814. (when (member prop '("get" "set" "async"))
  9815. (setq pos (js2-token-beg previous-token))
  9816. (js2-set-face (js2-token-beg previous-token)
  9817. (js2-token-end previous-token)
  9818. 'font-lock-keyword-face 'record)) ; get/set/async
  9819. (cond
  9820. ;; method definition: {f() {...}}
  9821. ((and (= (js2-peek-token) js2-LP)
  9822. (>= js2-language-version 200))
  9823. (when (or (js2-name-node-p key) (js2-string-node-p key))
  9824. ;; highlight function name properties
  9825. (js2-record-face 'font-lock-function-name-face))
  9826. (js2-parse-method-prop pos key property-type))
  9827. ;; class field or binding element with initializer
  9828. ((and (= (js2-peek-token) js2-ASSIGN)
  9829. (>= js2-language-version 200))
  9830. (if (not (or class-p
  9831. js2-is-in-destructuring))
  9832. (js2-report-error "msg.init.no.destruct"))
  9833. (js2-parse-initialized-binding key))
  9834. ;; regular prop
  9835. (t
  9836. (let ((beg (js2-current-token-beg))
  9837. (end (js2-current-token-end))
  9838. (expr (js2-parse-plain-property key class-p)))
  9839. (when (and (= tt js2-NAME)
  9840. (not js2-is-in-destructuring)
  9841. js2-highlight-external-variables
  9842. (js2-node-get-prop expr 'SHORTHAND))
  9843. (js2-record-name-node key))
  9844. (js2-set-face beg end
  9845. (if (js2-function-node-p
  9846. (js2-object-prop-node-right expr))
  9847. 'font-lock-function-name-face
  9848. 'js2-object-property)
  9849. 'record)
  9850. expr)))))
  9851. (defun js2-parse-initialized-binding (name)
  9852. "Parse a `SingleNameBinding' with initializer.
  9853. `name' is the `BindingIdentifier'."
  9854. (when (js2-match-token js2-ASSIGN)
  9855. (js2-make-binary js2-ASSIGN name 'js2-parse-assign-expr t)))
  9856. (defun js2-parse-prop-name (tt)
  9857. (cond
  9858. ;; Literal string keys: {'foo': 'bar'}
  9859. ((= tt js2-STRING)
  9860. (make-js2-string-node))
  9861. ;; Handle computed keys: {[Symbol.iterator]: ...}, *[1+2]() {...}},
  9862. ;; {[foo + bar]() { ... }}, {[get ['x' + 1]() {...}}
  9863. ((and (= tt js2-LB)
  9864. (>= js2-language-version 200))
  9865. (make-js2-computed-prop-name-node
  9866. :expr (prog1 (js2-parse-assign-expr)
  9867. (js2-must-match js2-RB "msg.missing.computed.rb"))))
  9868. ;; Numeric keys: {12: 'foo'}, {10.7: 'bar'}
  9869. ((= tt js2-NUMBER)
  9870. (make-js2-number-node))
  9871. ;; Unquoted names: {foo: 12}
  9872. ((= tt js2-NAME)
  9873. (js2-create-name-node))
  9874. ;; Anything else is an error
  9875. (t (js2-report-error "msg.bad.prop"))))
  9876. (defun js2-parse-plain-property (prop &optional class-p)
  9877. "Parse a non-getter/setter property in an object literal.
  9878. PROP is the node representing the property: a number, name,
  9879. string or expression."
  9880. (let* (tt
  9881. (pos (js2-node-pos prop))
  9882. colon expr result)
  9883. (cond
  9884. ;; Abbreviated property, as in {foo, bar} or class {a; b}
  9885. ((and (>= js2-language-version 200)
  9886. (if class-p
  9887. (and (setq tt (js2-peek-token-or-eol))
  9888. (member tt (list js2-EOL js2-RC js2-SEMI)))
  9889. (and (setq tt (js2-peek-token))
  9890. (member tt (list js2-COMMA js2-RC))
  9891. (js2-name-node-p prop))))
  9892. (setq result (make-js2-object-prop-node
  9893. :pos pos
  9894. :len (js2-node-len prop)
  9895. :left prop
  9896. :right prop
  9897. :op-pos (- (js2-current-token-beg) pos)))
  9898. (js2-node-add-children result prop)
  9899. (js2-node-set-prop result 'SHORTHAND t)
  9900. result)
  9901. ;; Normal property
  9902. (t
  9903. (setq tt (js2-get-token))
  9904. (if (= tt js2-COLON)
  9905. (setq colon (- (js2-current-token-beg) pos)
  9906. expr (js2-parse-assign-expr))
  9907. (js2-report-error "msg.no.colon.prop")
  9908. (setq expr (make-js2-error-node)))
  9909. (setq result (make-js2-object-prop-node
  9910. :pos pos
  9911. ;; don't include last consumed token in length
  9912. :len (- (+ (js2-node-pos expr)
  9913. (js2-node-len expr))
  9914. pos)
  9915. :left prop
  9916. :right expr
  9917. :op-pos colon))
  9918. (js2-node-add-children result prop expr)
  9919. result))))
  9920. (defun js2-parse-method-prop (pos prop type-string)
  9921. "Parse method property in an object literal or a class body.
  9922. JavaScript syntax is:
  9923. { foo(...) {...}, get foo() {...}, set foo(x) {...}, *foo(...) {...},
  9924. async foo(...) {...} }
  9925. and expression closure style is also supported
  9926. { get foo() x, set foo(x) _x = x }
  9927. POS is the start position of the `get' or `set' keyword, if any.
  9928. PROP is the `js2-name-node' representing the property name.
  9929. TYPE-STRING is a string `get', `set', `*', or nil, indicating a found keyword."
  9930. (let* ((type (or (cdr (assoc type-string '(("get" . GET)
  9931. ("set" . SET)
  9932. ("async" . ASYNC))))
  9933. 'FUNCTION))
  9934. result end
  9935. (pos (or pos (js2-current-token-beg)))
  9936. (_ (js2-must-match js2-LP "msg.no.paren.parms"))
  9937. (fn (js2-parse-function 'FUNCTION_EXPRESSION pos
  9938. (string= type-string "*")
  9939. (eq type 'ASYNC)
  9940. nil)))
  9941. (js2-node-set-prop fn 'METHOD_TYPE type) ; for codegen
  9942. (unless pos (setq pos (js2-node-pos prop)))
  9943. (setq end (js2-node-end fn)
  9944. result (make-js2-method-node :pos pos
  9945. :len (- end pos)
  9946. :left prop
  9947. :right fn))
  9948. (js2-node-add-children result prop fn)
  9949. result))
  9950. (defun js2-create-name-node (&optional check-activation-p token string)
  9951. "Create a name node using the current token and, optionally, STRING.
  9952. And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
  9953. (let* ((beg (js2-current-token-beg))
  9954. (tt (js2-current-token-type))
  9955. (s (or string
  9956. (if (= js2-NAME tt)
  9957. (js2-current-token-string)
  9958. (js2-tt-name tt))))
  9959. name)
  9960. (setq name (make-js2-name-node :pos beg
  9961. :name s
  9962. :len (length s)))
  9963. (if check-activation-p
  9964. (js2-check-activation-name s (or token js2-NAME)))
  9965. name))
  9966. ;;; Use AST to extract semantic information
  9967. (defun js2-get-element-index-from-array-node (elem array-node &optional hardcoded-array-index)
  9968. "Get index of ELEM from ARRAY-NODE or 0 and return it as string."
  9969. (let ((idx 0) elems (rlt hardcoded-array-index))
  9970. (setq elems (js2-array-node-elems array-node))
  9971. (if (and elem (not hardcoded-array-index))
  9972. (setq rlt (catch 'nth-elt
  9973. (dolist (x elems)
  9974. ;; We know the ELEM does belong to ARRAY-NODE,
  9975. (if (eq elem x) (throw 'nth-elt idx))
  9976. (setq idx (1+ idx)))
  9977. 0)))
  9978. (format "[%s]" rlt)))
  9979. (defun js2-print-json-path (&optional hardcoded-array-index)
  9980. "Print the path to the JSON value under point, and save it in the kill ring.
  9981. If HARDCODED-ARRAY-INDEX provided, array index in JSON path is replaced with it."
  9982. (interactive "P")
  9983. (js2-reparse)
  9984. (let (previous-node current-node
  9985. key-name
  9986. rlt)
  9987. ;; The `js2-node-at-point' starts scanning from AST root node.
  9988. ;; So there is no way to optimize it.
  9989. (setq current-node (js2-node-at-point))
  9990. (while (not (js2-ast-root-p current-node))
  9991. (cond
  9992. ;; JSON property node
  9993. ((js2-object-prop-node-p current-node)
  9994. (setq key-name (js2-prop-node-name (js2-object-prop-node-left current-node)))
  9995. (if rlt (setq rlt (concat "." key-name rlt))
  9996. (setq rlt (concat "." key-name))))
  9997. ;; Array node
  9998. ((or (js2-array-node-p current-node))
  9999. (setq rlt (concat (js2-get-element-index-from-array-node previous-node
  10000. current-node
  10001. hardcoded-array-index)
  10002. rlt)))
  10003. ;; Other nodes are ignored
  10004. (t))
  10005. ;; current node is archived
  10006. (setq previous-node current-node)
  10007. ;; Get parent node and continue the loop
  10008. (setq current-node (js2-node-parent current-node)))
  10009. (cond
  10010. (rlt
  10011. ;; Clean the final result
  10012. (setq rlt (replace-regexp-in-string "^\\." "" rlt))
  10013. (kill-new rlt)
  10014. (message "%s => kill-ring" rlt))
  10015. (t
  10016. (message "No JSON path found!")))
  10017. rlt))
  10018. ;;; Indentation support (bouncing)
  10019. ;; In recent-enough Emacs, we reuse the indentation code from
  10020. ;; `js-mode'. To continue support for the older versions, some code
  10021. ;; that was here previously was moved to `js2-old-indent.el'.
  10022. ;; Whichever indenter is used, it's often "wrong", however, and needs
  10023. ;; to be overridden. The right long-term solution is probably to
  10024. ;; emulate (or integrate with) cc-engine, but it's a nontrivial amount
  10025. ;; of coding. Even when a parse tree from `js2-parse' is present,
  10026. ;; which is not true at the moment the user is typing, computing
  10027. ;; indentation is still thousands of lines of code to handle every
  10028. ;; possible syntactic edge case.
  10029. ;; In the meantime, the compromise solution is that we offer a "bounce
  10030. ;; indenter", configured with `js2-bounce-indent-p', which cycles the
  10031. ;; current line indent among various likely guess points. This approach
  10032. ;; is far from perfect, but should at least make it slightly easier to
  10033. ;; move the line towards its desired indentation when manually
  10034. ;; overriding Karl's heuristic nesting guesser.
  10035. (defun js2-backward-sws ()
  10036. "Move backward through whitespace and comments."
  10037. (interactive)
  10038. (while (forward-comment -1)))
  10039. (defun js2-forward-sws ()
  10040. "Move forward through whitespace and comments."
  10041. (interactive)
  10042. (while (forward-comment 1)))
  10043. (defun js2-arglist-close ()
  10044. "Return non-nil if we're on a line beginning with a close-paren/brace."
  10045. (save-excursion
  10046. (goto-char (point-at-bol))
  10047. (js2-forward-sws)
  10048. (looking-at "[])}]")))
  10049. (defun js2-indent-looks-like-label-p ()
  10050. (goto-char (point-at-bol))
  10051. (js2-forward-sws)
  10052. (looking-at (concat js2-mode-identifier-re ":")))
  10053. (defun js2-indent-in-objlit-p (parse-status)
  10054. "Return non-nil if this looks like an object-literal entry."
  10055. (let ((start (nth 1 parse-status)))
  10056. (and
  10057. start
  10058. (save-excursion
  10059. (and (zerop (forward-line -1))
  10060. (not (< (point) start)) ; crossed a {} boundary
  10061. (js2-indent-looks-like-label-p)))
  10062. (save-excursion
  10063. (js2-indent-looks-like-label-p)))))
  10064. ;; If prev line looks like foobar({ then we're passing an object
  10065. ;; literal to a function call, and people pretty much always want to
  10066. ;; de-dent back to the previous line, so move the 'basic-offset'
  10067. ;; position to the front.
  10068. (defun js2-indent-objlit-arg-p (parse-status)
  10069. (save-excursion
  10070. (back-to-indentation)
  10071. (js2-backward-sws)
  10072. (and (eq (1- (point)) (nth 1 parse-status))
  10073. (eq (char-before) ?{)
  10074. (progn
  10075. (forward-char -1)
  10076. (skip-chars-backward " \t")
  10077. (eq (char-before) ?\()))))
  10078. (defun js2-indent-case-block-p ()
  10079. (save-excursion
  10080. (back-to-indentation)
  10081. (js2-backward-sws)
  10082. (goto-char (point-at-bol))
  10083. (skip-chars-forward " \t")
  10084. (looking-at "case\\s-.+:")))
  10085. (defun js2-bounce-indent (normal-col parse-status &optional backward)
  10086. "Cycle among alternate computed indentation positions.
  10087. PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
  10088. of the buffer to the current point. NORMAL-COL is the indentation
  10089. column computed by the heuristic guesser based on current paren,
  10090. bracket, brace and statement nesting. If BACKWARDS, cycle positions
  10091. in reverse."
  10092. (let ((cur-indent (current-indentation))
  10093. (old-buffer-undo-list buffer-undo-list)
  10094. ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
  10095. (current-line (save-excursion
  10096. (forward-line 0) ; move to bol
  10097. (1+ (count-lines (point-min) (point)))))
  10098. positions pos main-pos anchor arglist-cont same-indent
  10099. basic-offset computed-pos)
  10100. ;; temporarily don't record undo info, if user requested this
  10101. (when js2-mode-indent-inhibit-undo
  10102. (setq buffer-undo-list t))
  10103. (unwind-protect
  10104. (progn
  10105. ;; First likely point: indent from beginning of previous code line
  10106. (push (setq basic-offset
  10107. (+ (save-excursion
  10108. (back-to-indentation)
  10109. (js2-backward-sws)
  10110. (back-to-indentation)
  10111. (current-column))
  10112. js2-basic-offset))
  10113. positions)
  10114. ;; (First + epsilon) likely point: indent 2x from beginning of
  10115. ;; previous code line. Google does it this way.
  10116. (push (setq basic-offset
  10117. (+ (save-excursion
  10118. (back-to-indentation)
  10119. (js2-backward-sws)
  10120. (back-to-indentation)
  10121. (current-column))
  10122. (* 2 js2-basic-offset)))
  10123. positions)
  10124. ;; Second likely point: indent from assign-expr RHS. This
  10125. ;; is just a crude guess based on finding " = " on the previous
  10126. ;; line containing actual code.
  10127. (setq pos (save-excursion
  10128. (forward-line -1)
  10129. (goto-char (point-at-bol))
  10130. (when (re-search-forward "\\s-+\\(=\\)\\s-+"
  10131. (point-at-eol) t)
  10132. (goto-char (match-end 1))
  10133. (skip-chars-forward " \t\r\n")
  10134. (current-column))))
  10135. (when pos
  10136. (cl-incf pos js2-basic-offset)
  10137. (push pos positions))
  10138. ;; Third likely point: same indent as previous line of code.
  10139. ;; Make it the first likely point if we're not on an
  10140. ;; arglist-close line and previous line ends in a comma, or
  10141. ;; both this line and prev line look like object-literal
  10142. ;; elements.
  10143. (setq pos (save-excursion
  10144. (goto-char (point-at-bol))
  10145. (js2-backward-sws)
  10146. (back-to-indentation)
  10147. (prog1
  10148. (current-column)
  10149. ;; while we're here, look for trailing comma
  10150. (if (save-excursion
  10151. (goto-char (point-at-eol))
  10152. (js2-backward-sws)
  10153. (eq (char-before) ?,))
  10154. (setq arglist-cont (1- (point)))))))
  10155. (when pos
  10156. (if (and (or arglist-cont
  10157. (js2-indent-in-objlit-p parse-status))
  10158. (not (js2-arglist-close)))
  10159. (setq same-indent pos))
  10160. (push pos positions))
  10161. ;; Fourth likely point: first preceding code with less indentation.
  10162. ;; than the immediately preceding code line.
  10163. (setq pos (save-excursion
  10164. (back-to-indentation)
  10165. (js2-backward-sws)
  10166. (back-to-indentation)
  10167. (setq anchor (current-column))
  10168. (while (and (zerop (forward-line -1))
  10169. (>= (progn
  10170. (back-to-indentation)
  10171. (current-column))
  10172. anchor)))
  10173. (setq pos (current-column))))
  10174. (push pos positions)
  10175. ;; nesting-heuristic position, main by default
  10176. (push (setq main-pos normal-col) positions)
  10177. ;; delete duplicates and sort positions list
  10178. (setq positions (sort (delete-dups positions) '<))
  10179. ;; comma-list continuation lines: prev line indent takes precedence
  10180. (if same-indent
  10181. (setq main-pos same-indent))
  10182. ;; common special cases where we want to indent in from previous line
  10183. (if (or (js2-indent-case-block-p)
  10184. (js2-indent-objlit-arg-p parse-status))
  10185. (setq main-pos basic-offset))
  10186. ;; if bouncing backward, reverse positions list
  10187. (if backward
  10188. (setq positions (reverse positions)))
  10189. ;; record whether we're already sitting on one of the alternatives
  10190. (setq pos (member cur-indent positions))
  10191. (cond
  10192. ;; case 0: we're one one of the alternatives and this is the
  10193. ;; first time they've pressed TAB on this line (best-guess).
  10194. ((and js2-mode-indent-ignore-first-tab
  10195. pos
  10196. ;; first time pressing TAB on this line?
  10197. (not (eq js2-mode-last-indented-line current-line)))
  10198. ;; do nothing
  10199. (setq computed-pos nil))
  10200. ;; case 1: only one computed position => use it
  10201. ((null (cdr positions))
  10202. (setq computed-pos 0))
  10203. ;; case 2: not on any of the computed spots => use main spot
  10204. ((not pos)
  10205. (setq computed-pos (js2-position main-pos positions)))
  10206. ;; case 3: on last position: cycle to first position
  10207. ((null (cdr pos))
  10208. (setq computed-pos 0))
  10209. ;; case 4: on intermediate position: cycle to next position
  10210. (t
  10211. (setq computed-pos (js2-position (cl-second pos) positions))))
  10212. ;; see if any hooks want to indent; otherwise we do it
  10213. (cl-loop with result = nil
  10214. for hook in js2-indent-hook
  10215. while (null result)
  10216. do
  10217. (setq result (funcall hook positions computed-pos))
  10218. finally do
  10219. (unless (or result (null computed-pos))
  10220. (indent-line-to (nth computed-pos positions)))))
  10221. ;; finally
  10222. (if js2-mode-indent-inhibit-undo
  10223. (setq buffer-undo-list old-buffer-undo-list))
  10224. ;; see commentary for `js2-mode-last-indented-line'
  10225. (setq js2-mode-last-indented-line current-line))))
  10226. (defun js2-1-line-comment-continuation-p ()
  10227. "Return t if we're in a 1-line comment continuation.
  10228. If so, we don't ever want to use bounce-indent."
  10229. (save-excursion
  10230. (and (progn
  10231. (forward-line 0)
  10232. (looking-at "\\s-*//"))
  10233. (progn
  10234. (forward-line -1)
  10235. (forward-line 0)
  10236. (when (looking-at "\\s-*$")
  10237. (js2-backward-sws)
  10238. (forward-line 0))
  10239. (looking-at "\\s-*//")))))
  10240. (defun js2-indent-bounce (&optional backward)
  10241. "Indent the current line, bouncing between several positions."
  10242. (interactive)
  10243. (let (parse-status offset indent-col
  10244. ;; Don't whine about errors/warnings when we're indenting.
  10245. ;; This has to be set before calling parse-partial-sexp below.
  10246. (inhibit-point-motion-hooks t))
  10247. (setq parse-status (save-excursion
  10248. (syntax-ppss (point-at-bol)))
  10249. offset (- (point) (save-excursion
  10250. (back-to-indentation)
  10251. (point))))
  10252. ;; Don't touch multiline strings.
  10253. (unless (nth 3 parse-status)
  10254. (setq indent-col (js2-proper-indentation parse-status))
  10255. (cond
  10256. ;; It doesn't work well on first line of buffer.
  10257. ((and (not (nth 4 parse-status))
  10258. (not (js2-same-line (point-min)))
  10259. (not (js2-1-line-comment-continuation-p)))
  10260. (js2-bounce-indent indent-col parse-status backward))
  10261. ;; just indent to the guesser's likely spot
  10262. (t (indent-line-to indent-col)))
  10263. (when (cl-plusp offset)
  10264. (forward-char offset)))))
  10265. (defun js2-indent-bounce-backward ()
  10266. "Indent the current line, bouncing between positions in reverse."
  10267. (interactive)
  10268. (js2-indent-bounce t))
  10269. (defun js2-indent-region (start end)
  10270. "Indent the region, but don't use bounce indenting."
  10271. (let ((js2-bounce-indent-p nil)
  10272. (indent-region-function nil)
  10273. (after-change-functions (remq 'js2-mode-edit
  10274. after-change-functions)))
  10275. (indent-region start end nil) ; nil for byte-compiler
  10276. (js2-mode-edit start end (- end start))))
  10277. (defvar js2-minor-mode-map
  10278. (let ((map (make-sparse-keymap)))
  10279. (define-key map (kbd "C-c C-`") #'js2-next-error)
  10280. map)
  10281. "Keymap used when `js2-minor-mode' is active.")
  10282. ;;;###autoload
  10283. (define-minor-mode js2-minor-mode
  10284. "Minor mode for running js2 as a background linter.
  10285. This allows you to use a different major mode for JavaScript editing,
  10286. such as `js-mode', while retaining the asynchronous error/warning
  10287. highlighting features of `js2-mode'."
  10288. :group 'js2-mode
  10289. :lighter " js-lint"
  10290. (if (derived-mode-p 'js2-mode)
  10291. (setq js2-minor-mode nil)
  10292. (if js2-minor-mode
  10293. (js2-minor-mode-enter)
  10294. (js2-minor-mode-exit))))
  10295. (defun js2-minor-mode-enter ()
  10296. "Initialization for `js2-minor-mode'."
  10297. (set (make-local-variable 'max-lisp-eval-depth)
  10298. (max max-lisp-eval-depth 3000))
  10299. (setq next-error-function #'js2-next-error)
  10300. ;; Experiment: make reparse-delay longer for longer files.
  10301. (if (cl-plusp js2-dynamic-idle-timer-adjust)
  10302. (setq js2-idle-timer-delay
  10303. (* js2-idle-timer-delay
  10304. (/ (point-max) js2-dynamic-idle-timer-adjust))))
  10305. (setq js2-mode-buffer-dirty-p t
  10306. js2-mode-parsing nil)
  10307. (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
  10308. (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
  10309. (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
  10310. (when js2-include-jslint-globals
  10311. (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
  10312. (when js2-include-jslint-declaration-externs
  10313. (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-declaration-externs nil t))
  10314. (run-hooks 'js2-init-hook)
  10315. (js2-reparse))
  10316. (defun js2-minor-mode-exit ()
  10317. "Turn off `js2-minor-mode'."
  10318. (setq next-error-function nil)
  10319. (remove-hook 'after-change-functions #'js2-mode-edit t)
  10320. (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
  10321. (when js2-mode-node-overlay
  10322. (delete-overlay js2-mode-node-overlay)
  10323. (setq js2-mode-node-overlay nil))
  10324. (js2-remove-overlays)
  10325. (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
  10326. (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-declaration-externs t)
  10327. (setq js2-mode-ast nil))
  10328. (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
  10329. (make-variable-buffer-local 'js2-source-buffer)
  10330. (cl-defun js2-display-error-list ()
  10331. "Display a navigable buffer listing parse errors/warnings."
  10332. (interactive)
  10333. (unless (js2-have-errors-p)
  10334. (message "No errors")
  10335. (cl-return-from js2-display-error-list))
  10336. (cl-labels ((annotate-list
  10337. (lst type)
  10338. "Add diagnostic TYPE and line number to errs list"
  10339. (mapcar (lambda (err)
  10340. (list err type (line-number-at-pos (nth 1 err))))
  10341. lst)))
  10342. (let* ((srcbuf (current-buffer))
  10343. (errbuf (get-buffer-create "*js-lint*"))
  10344. (errors (annotate-list
  10345. (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
  10346. 'js2-error)) ; must be a valid face name
  10347. (warnings (annotate-list
  10348. (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
  10349. 'js2-warning)) ; must be a valid face name
  10350. (all-errs (sort (append errors warnings)
  10351. (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
  10352. (with-current-buffer errbuf
  10353. (let ((inhibit-read-only t))
  10354. (erase-buffer)
  10355. (dolist (err all-errs)
  10356. (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
  10357. (insert-text-button
  10358. (format "line %d: %s" line (js2-get-msg msg-key))
  10359. 'face type
  10360. 'follow-link "\C-m"
  10361. 'action 'js2-error-buffer-jump
  10362. 'js2-msg (js2-get-msg msg-key)
  10363. 'js2-pos beg)
  10364. (insert "\n"))))
  10365. (js2-error-buffer-mode)
  10366. (setq js2-source-buffer srcbuf)
  10367. (pop-to-buffer errbuf)
  10368. (goto-char (point-min))
  10369. (unless (eobp)
  10370. (js2-error-buffer-view))))))
  10371. (defvar js2-error-buffer-mode-map
  10372. (let ((map (make-sparse-keymap)))
  10373. (define-key map "n" #'js2-error-buffer-next)
  10374. (define-key map "p" #'js2-error-buffer-prev)
  10375. (define-key map (kbd "RET") #'js2-error-buffer-jump)
  10376. (define-key map "o" #'js2-error-buffer-view)
  10377. (define-key map "q" #'js2-error-buffer-quit)
  10378. map)
  10379. "Keymap used for js2 diagnostics buffers.")
  10380. (defun js2-error-buffer-mode ()
  10381. "Major mode for js2 diagnostics buffers.
  10382. Selecting an error will jump it to the corresponding source-buffer error.
  10383. \\{js2-error-buffer-mode-map}"
  10384. (interactive)
  10385. (setq major-mode 'js2-error-buffer-mode
  10386. mode-name "JS Lint Diagnostics")
  10387. (use-local-map js2-error-buffer-mode-map)
  10388. (setq truncate-lines t)
  10389. (set-buffer-modified-p nil)
  10390. (setq buffer-read-only t)
  10391. (run-hooks 'js2-error-buffer-mode-hook))
  10392. (defun js2-error-buffer-next ()
  10393. "Move to next error and view it."
  10394. (interactive)
  10395. (when (zerop (forward-line 1))
  10396. (js2-error-buffer-view)))
  10397. (defun js2-error-buffer-prev ()
  10398. "Move to previous error and view it."
  10399. (interactive)
  10400. (when (zerop (forward-line -1))
  10401. (js2-error-buffer-view)))
  10402. (defun js2-error-buffer-quit ()
  10403. "Kill the current buffer."
  10404. (interactive)
  10405. (kill-buffer))
  10406. (defun js2-error-buffer-jump (&rest ignored)
  10407. "Jump cursor to current error in source buffer."
  10408. (interactive)
  10409. (when (js2-error-buffer-view)
  10410. (pop-to-buffer js2-source-buffer)))
  10411. (defun js2-error-buffer-view ()
  10412. "Scroll source buffer to show error at current line."
  10413. (interactive)
  10414. (cond
  10415. ((not (eq major-mode 'js2-error-buffer-mode))
  10416. (message "Not in a js2 errors buffer"))
  10417. ((not (buffer-live-p js2-source-buffer))
  10418. (message "Source buffer has been killed"))
  10419. ((not (wholenump (get-text-property (point) 'js2-pos)))
  10420. (message "There does not seem to be an error here"))
  10421. (t
  10422. (let ((pos (get-text-property (point) 'js2-pos))
  10423. (msg (get-text-property (point) 'js2-msg)))
  10424. (save-selected-window
  10425. (pop-to-buffer js2-source-buffer)
  10426. (goto-char pos)
  10427. (message msg))))))
  10428. ;;;###autoload
  10429. (define-derived-mode js2-mode js-mode "Javascript-IDE"
  10430. "Major mode for editing JavaScript code."
  10431. (set (make-local-variable 'max-lisp-eval-depth)
  10432. (max max-lisp-eval-depth 3000))
  10433. (set (make-local-variable 'indent-line-function) #'js2-indent-line)
  10434. (set (make-local-variable 'indent-region-function) #'js2-indent-region)
  10435. (set (make-local-variable 'syntax-propertize-function) nil)
  10436. (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
  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. (setq font-lock-defaults '(nil t))
  10447. ;; Experiment: make reparse-delay longer for longer files.
  10448. (when (cl-plusp js2-dynamic-idle-timer-adjust)
  10449. (setq js2-idle-timer-delay
  10450. (* js2-idle-timer-delay
  10451. (/ (point-max) js2-dynamic-idle-timer-adjust))))
  10452. (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
  10453. (add-hook 'after-change-functions #'js2-mode-edit nil t)
  10454. (setq imenu-create-index-function #'js2-mode-create-imenu-index)
  10455. (setq next-error-function #'js2-next-error)
  10456. (imenu-add-to-menubar (concat "IM-" mode-name))
  10457. (add-to-invisibility-spec '(js2-outline . t))
  10458. (set (make-local-variable 'line-move-ignore-invisible) t)
  10459. (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
  10460. (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
  10461. (setq js2-mode-functions-hidden nil
  10462. js2-mode-comments-hidden nil
  10463. js2-mode-buffer-dirty-p t
  10464. js2-mode-parsing nil)
  10465. (when js2-include-jslint-globals
  10466. (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
  10467. (when js2-include-jslint-declaration-externs
  10468. (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-declaration-externs nil t))
  10469. (run-hooks 'js2-init-hook)
  10470. (let ((js2-idle-timer-delay 0))
  10471. ;; Schedule parsing for after when the mode hooks run.
  10472. (js2-mode-reset-timer)))
  10473. ;; We may eventually want js2-jsx-mode to derive from js-jsx-mode, but that'd be
  10474. ;; a bit more complicated and it doesn't net us much yet.
  10475. ;;;###autoload
  10476. (define-derived-mode js2-jsx-mode js2-mode "JSX-IDE"
  10477. "Major mode for editing JSX code.
  10478. To customize the indentation for this mode, set the SGML offset
  10479. variables (`sgml-basic-offset' et al) locally, like so:
  10480. (defun set-jsx-indentation ()
  10481. (setq-local sgml-basic-offset js2-basic-offset))
  10482. (add-hook \\='js2-jsx-mode-hook #\\='set-jsx-indentation)"
  10483. (set (make-local-variable 'indent-line-function) #'js2-jsx-indent-line))
  10484. (defun js2-mode-exit ()
  10485. "Exit `js2-mode' and clean up."
  10486. (interactive)
  10487. (when js2-mode-node-overlay
  10488. (delete-overlay js2-mode-node-overlay)
  10489. (setq js2-mode-node-overlay nil))
  10490. (js2-remove-overlays)
  10491. (setq js2-mode-ast nil)
  10492. (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
  10493. (remove-from-invisibility-spec '(js2-outline . t))
  10494. (js2-mode-show-all)
  10495. (with-silent-modifications
  10496. (js2-clear-face (point-min) (point-max))))
  10497. (defun js2-mode-reset-timer ()
  10498. "Cancel any existing parse timer and schedule a new one."
  10499. (if js2-mode-parse-timer
  10500. (cancel-timer js2-mode-parse-timer))
  10501. (setq js2-mode-parsing nil)
  10502. (let ((timer (timer-create)))
  10503. (setq js2-mode-parse-timer timer)
  10504. (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
  10505. (timer-set-idle-time timer js2-idle-timer-delay)
  10506. ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
  10507. (timer-activate-when-idle timer nil)))
  10508. (defun js2-mode-idle-reparse (buffer)
  10509. "Run `js2-reparse' if BUFFER is the current buffer, or schedule
  10510. it to be reparsed when the buffer is selected."
  10511. (cond ((eq buffer (current-buffer))
  10512. (js2-reparse))
  10513. ((buffer-live-p buffer)
  10514. ;; reparse when the buffer is selected again
  10515. (with-current-buffer buffer
  10516. (add-hook 'window-configuration-change-hook
  10517. #'js2-mode-idle-reparse-inner
  10518. nil t)))))
  10519. (defun js2-mode-idle-reparse-inner ()
  10520. (remove-hook 'window-configuration-change-hook
  10521. #'js2-mode-idle-reparse-inner
  10522. t)
  10523. (js2-reparse))
  10524. (defun js2-mode-edit (_beg _end _len)
  10525. "Schedule a new parse after buffer is edited.
  10526. Buffer edit spans from BEG to END and is of length LEN."
  10527. (setq js2-mode-buffer-dirty-p t)
  10528. (js2-mode-hide-overlay)
  10529. (js2-mode-reset-timer))
  10530. (defun js2-minor-mode-edit (_beg _end _len)
  10531. "Callback for buffer edits in `js2-mode'.
  10532. Schedules a new parse after buffer is edited.
  10533. Buffer edit spans from BEG to END and is of length LEN."
  10534. (setq js2-mode-buffer-dirty-p t)
  10535. (js2-mode-hide-overlay)
  10536. (js2-mode-reset-timer))
  10537. (defun js2-reparse (&optional force)
  10538. "Re-parse current buffer after user finishes some data entry.
  10539. If we get any user input while parsing, including cursor motion,
  10540. we discard the parse and reschedule it. If FORCE is nil, then the
  10541. buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
  10542. (let (time
  10543. interrupted-p
  10544. (js2-compiler-strict-mode js2-mode-show-strict-warnings))
  10545. (unless js2-mode-parsing
  10546. (setq js2-mode-parsing t)
  10547. (unwind-protect
  10548. (when (or js2-mode-buffer-dirty-p force)
  10549. (js2-remove-overlays)
  10550. (setq js2-mode-buffer-dirty-p nil
  10551. js2-mode-fontifications nil
  10552. js2-mode-deferred-properties nil)
  10553. (if js2-mode-verbose-parse-p
  10554. (message "parsing..."))
  10555. (setq time
  10556. (js2-time
  10557. (setq interrupted-p
  10558. (catch 'interrupted
  10559. (js2-parse)
  10560. (with-silent-modifications
  10561. ;; if parsing is interrupted, comments and regex
  10562. ;; literals stay ignored by `parse-partial-sexp'
  10563. (remove-text-properties (point-min) (point-max)
  10564. '(syntax-table))
  10565. (js2-mode-apply-deferred-properties)
  10566. (js2-mode-remove-suppressed-warnings)
  10567. (js2-mode-show-warnings)
  10568. (js2-mode-show-errors)
  10569. (if (>= js2-highlight-level 1)
  10570. (js2-highlight-jsdoc js2-mode-ast)))
  10571. nil))))
  10572. (if interrupted-p
  10573. (progn
  10574. ;; unfinished parse => try again
  10575. (setq js2-mode-buffer-dirty-p t)
  10576. (js2-mode-reset-timer))
  10577. (if js2-mode-verbose-parse-p
  10578. (message "Parse time: %s" time))))
  10579. (setq js2-mode-parsing nil)
  10580. (unless interrupted-p
  10581. (setq js2-mode-parse-timer nil))))))
  10582. ;; We bound it to [mouse-1] previously. But the signature of
  10583. ;; mouse-set-point changed around 24.4, so it's kind of hard to keep
  10584. ;; it working in 24.1-24.3. Since the command is not hugely
  10585. ;; important, we removed the binding (#356). Maybe we'll bring it
  10586. ;; back when supporting <24.4 is not a goal anymore.
  10587. (defun js2-mode-show-node (event &optional promote-to-region)
  10588. "Debugging aid: highlight selected AST node on mouse click."
  10589. (interactive "e\np")
  10590. (mouse-set-point event promote-to-region)
  10591. (when js2-mode-show-overlay
  10592. (let ((node (js2-node-at-point))
  10593. beg end)
  10594. (if (null node)
  10595. (message "No node found at location %s" (point))
  10596. (setq beg (js2-node-abs-pos node)
  10597. end (+ beg (js2-node-len node)))
  10598. (if js2-mode-node-overlay
  10599. (move-overlay js2-mode-node-overlay beg end)
  10600. (setq js2-mode-node-overlay (make-overlay beg end))
  10601. (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
  10602. (with-silent-modifications
  10603. (if (fboundp 'cursor-sensor-mode)
  10604. (put-text-property beg end 'cursor-sensor-functions
  10605. '(js2-mode-hide-overlay))
  10606. (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
  10607. (message "%s, parent: %s"
  10608. (js2-node-short-name node)
  10609. (if (js2-node-parent node)
  10610. (js2-node-short-name (js2-node-parent node))
  10611. "nil"))))))
  10612. (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
  10613. "Remove the debugging overlay when point moves.
  10614. ARG1, ARG2 and ARG3 have different values depending on whether this function
  10615. was found on `point-left' or in `cursor-sensor-functions'."
  10616. (when js2-mode-node-overlay
  10617. (let ((beg (overlay-start js2-mode-node-overlay))
  10618. (end (overlay-end js2-mode-node-overlay))
  10619. (p2 (if (windowp arg1)
  10620. ;; Called from cursor-sensor-functions.
  10621. (window-point arg1)
  10622. ;; Called from point-left.
  10623. arg2)))
  10624. ;; Sometimes we're called spuriously.
  10625. (unless (and p2
  10626. (>= p2 beg)
  10627. (<= p2 end))
  10628. (with-silent-modifications
  10629. (remove-text-properties beg end
  10630. '(point-left nil cursor-sensor-functions)))
  10631. (delete-overlay js2-mode-node-overlay)
  10632. (setq js2-mode-node-overlay nil)))))
  10633. (defun js2-mode-reset ()
  10634. "Debugging helper: reset everything."
  10635. (interactive)
  10636. (js2-mode-exit)
  10637. (js2-mode))
  10638. (defun js2-mode-show-warn-or-err (e face)
  10639. "Highlight a warning or error E with FACE.
  10640. E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
  10641. The last element is optional. When present, use instead of FACE."
  10642. (let* ((key (cl-first e))
  10643. (beg (cl-second e))
  10644. (end (+ beg (cl-third e)))
  10645. ;; Don't inadvertently go out of bounds.
  10646. (beg (max (point-min) (min beg (point-max))))
  10647. (end (max (point-min) (min end (point-max))))
  10648. (ovl (make-overlay beg end)))
  10649. ;; FIXME: Why a mix of overlays and text-properties?
  10650. (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
  10651. (overlay-put ovl 'js2-error t)
  10652. (put-text-property beg end 'help-echo (js2-get-msg key))
  10653. (if (fboundp 'cursor-sensor-mode)
  10654. (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
  10655. (put-text-property beg end 'point-entered #'js2-echo-error))))
  10656. (defun js2-remove-overlays ()
  10657. "Remove overlays from buffer that have a `js2-error' property."
  10658. (let ((beg (point-min))
  10659. (end (point-max)))
  10660. (save-excursion
  10661. (dolist (o (overlays-in beg end))
  10662. (when (overlay-get o 'js2-error)
  10663. (delete-overlay o))))))
  10664. (defun js2-mode-apply-deferred-properties ()
  10665. "Apply fontifications and other text properties recorded during parsing."
  10666. (when (cl-plusp js2-highlight-level)
  10667. ;; We defer clearing faces as long as possible to eliminate flashing.
  10668. (js2-clear-face (point-min) (point-max))
  10669. ;; Have to reverse the recorded fontifications list so that errors
  10670. ;; and warnings overwrite the normal fontifications.
  10671. (dolist (f (nreverse js2-mode-fontifications))
  10672. (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
  10673. (setq js2-mode-fontifications nil))
  10674. (dolist (p js2-mode-deferred-properties)
  10675. (apply #'put-text-property p))
  10676. (setq js2-mode-deferred-properties nil))
  10677. (defun js2-mode-show-errors ()
  10678. "Highlight syntax errors."
  10679. (when js2-mode-show-parse-errors
  10680. (dolist (e (js2-ast-root-errors js2-mode-ast))
  10681. (js2-mode-show-warn-or-err e 'js2-error))))
  10682. (defun js2-mode-remove-suppressed-warnings ()
  10683. "Take suppressed warnings out of the AST warnings list.
  10684. This ensures that the counts and `next-error' are correct."
  10685. (setf (js2-ast-root-warnings js2-mode-ast)
  10686. (js2-delete-if
  10687. (lambda (e)
  10688. (let ((key (caar e)))
  10689. (or
  10690. (and (not js2-strict-trailing-comma-warning)
  10691. (string-match "trailing\\.comma" key))
  10692. (and (not js2-strict-cond-assign-warning)
  10693. (string= key "msg.equal.as.assign"))
  10694. (and js2-missing-semi-one-line-override
  10695. (string= key "msg.missing.semi")
  10696. (let* ((beg (cl-second e))
  10697. (node (js2-node-at-point beg))
  10698. (fn (js2-mode-find-parent-fn node))
  10699. (body (and fn (js2-function-node-body fn)))
  10700. (lc (and body (js2-node-abs-pos body)))
  10701. (rc (and lc (+ lc (js2-node-len body)))))
  10702. (and fn
  10703. (or (null body)
  10704. (save-excursion
  10705. (goto-char beg)
  10706. (and (js2-same-line lc)
  10707. (js2-same-line rc))))))))))
  10708. (js2-ast-root-warnings js2-mode-ast))))
  10709. (defun js2-mode-show-warnings ()
  10710. "Highlight strict-mode warnings."
  10711. (when js2-mode-show-strict-warnings
  10712. (dolist (e (js2-ast-root-warnings js2-mode-ast))
  10713. (js2-mode-show-warn-or-err e 'js2-warning))))
  10714. (defun js2-echo-error (arg1 arg2 &optional _arg3)
  10715. "Called by point-motion hooks.
  10716. ARG1, ARG2 and ARG3 have different values depending on whether this function
  10717. was found on `point-entered' or in `cursor-sensor-functions'."
  10718. (let* ((new-point (if (windowp arg1)
  10719. ;; Called from cursor-sensor-functions.
  10720. (window-point arg1)
  10721. ;; Called from point-left.
  10722. arg2))
  10723. (msg (get-text-property new-point 'help-echo)))
  10724. (when (and (stringp msg)
  10725. (not (active-minibuffer-window))
  10726. (not (current-message)))
  10727. (message msg))))
  10728. (defun js2-line-break (&optional _soft)
  10729. "Break line at point and indent, continuing comment if within one.
  10730. If inside a string, and `js2-concat-multiline-strings' is not
  10731. nil, turn it into concatenation."
  10732. (interactive)
  10733. (let ((parse-status (syntax-ppss)))
  10734. (cond
  10735. ;; Check if we're inside a string.
  10736. ((nth 3 parse-status)
  10737. (if js2-concat-multiline-strings
  10738. (js2-mode-split-string parse-status)
  10739. (insert "\n")))
  10740. ;; Check if inside a block comment.
  10741. ((nth 4 parse-status)
  10742. (js2-mode-extend-comment (nth 8 parse-status)))
  10743. (t
  10744. (newline-and-indent)))))
  10745. (defun js2-mode-split-string (parse-status)
  10746. "Turn a newline in mid-string into a string concatenation.
  10747. PARSE-STATUS is as documented in `parse-partial-sexp'."
  10748. (let* ((quote-char (nth 3 parse-status))
  10749. (at-eol (eq js2-concat-multiline-strings 'eol)))
  10750. (insert quote-char)
  10751. (insert (if at-eol " +\n" "\n"))
  10752. (unless at-eol
  10753. (insert "+ "))
  10754. (js2-indent-line)
  10755. (insert quote-char)
  10756. (when (eolp)
  10757. (insert quote-char)
  10758. (backward-char 1))))
  10759. (defun js2-mode-extend-comment (start-pos)
  10760. "Indent the line and, when inside a comment block, add comment prefix."
  10761. (let (star single col first-line needs-close)
  10762. (save-excursion
  10763. (back-to-indentation)
  10764. (when (< (point) start-pos)
  10765. (goto-char start-pos))
  10766. (cond
  10767. ((looking-at "\\*[^/]")
  10768. (setq star t
  10769. col (current-column)))
  10770. ((looking-at "/\\*")
  10771. (setq star t
  10772. first-line t
  10773. col (1+ (current-column))))
  10774. ((looking-at "//")
  10775. (setq single t
  10776. col (current-column)))))
  10777. ;; Heuristic for whether we need to close the comment:
  10778. ;; if we've got a parse error here, assume it's an unterminated
  10779. ;; comment.
  10780. (setq needs-close
  10781. (or
  10782. (get-char-property (1- (point)) 'js2-error)
  10783. ;; The heuristic above doesn't work well when we're
  10784. ;; creating a comment and there's another one downstream,
  10785. ;; as our parser thinks this one ends at the end of the
  10786. ;; next one. (You can have a /* inside a js block comment.)
  10787. ;; So just close it if the next non-ws char isn't a *.
  10788. (and first-line
  10789. (eolp)
  10790. (save-excursion
  10791. (skip-chars-forward " \t\r\n")
  10792. (not (eq (char-after) ?*))))))
  10793. (delete-horizontal-space)
  10794. (insert "\n")
  10795. (cond
  10796. (star
  10797. (indent-to col)
  10798. (insert "* ")
  10799. (if (and first-line needs-close)
  10800. (save-excursion
  10801. (insert "\n")
  10802. (indent-to col)
  10803. (insert "*/"))))
  10804. (single
  10805. (indent-to col)
  10806. (insert "// ")))
  10807. ;; Don't need to extend the comment after all.
  10808. (js2-indent-line)))
  10809. (defun js2-beginning-of-line ()
  10810. "Toggle point between bol and first non-whitespace char in line.
  10811. Also moves past comment delimiters when inside comments."
  10812. (interactive)
  10813. (let (node)
  10814. (cond
  10815. ((bolp)
  10816. (back-to-indentation))
  10817. ((looking-at "//")
  10818. (skip-chars-forward "/ \t"))
  10819. ((and (eq (char-after) ?*)
  10820. (setq node (js2-comment-at-point))
  10821. (memq (js2-comment-node-format node) '(jsdoc block))
  10822. (save-excursion
  10823. (skip-chars-backward " \t")
  10824. (bolp)))
  10825. (skip-chars-forward "\* \t"))
  10826. (t
  10827. (goto-char (point-at-bol))))))
  10828. (defun js2-end-of-line ()
  10829. "Toggle point between eol and last non-whitespace char in line."
  10830. (interactive)
  10831. (if (eolp)
  10832. (skip-chars-backward " \t")
  10833. (goto-char (point-at-eol))))
  10834. (defun js2-mode-wait-for-parse (callback)
  10835. "Invoke CALLBACK when parsing is finished.
  10836. If parsing is already finished, calls CALLBACK immediately."
  10837. (if (not js2-mode-buffer-dirty-p)
  10838. (funcall callback)
  10839. (push callback js2-mode-pending-parse-callbacks)
  10840. (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
  10841. (defun js2-mode-parse-finished ()
  10842. "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
  10843. ;; We can't let errors propagate up, since it prevents the
  10844. ;; `js2-parse' method from completing normally and returning
  10845. ;; the ast, which makes things mysteriously not work right.
  10846. (unwind-protect
  10847. (dolist (cb js2-mode-pending-parse-callbacks)
  10848. (condition-case err
  10849. (funcall cb)
  10850. (error (message "%s" err))))
  10851. (setq js2-mode-pending-parse-callbacks nil)))
  10852. (defun js2-mode-flag-region (from to flag)
  10853. "Hide or show text from FROM to TO, according to FLAG.
  10854. If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
  10855. Returns the created overlay if FLAG is non-nil."
  10856. (remove-overlays from to 'invisible 'js2-outline)
  10857. (when flag
  10858. (let ((o (make-overlay from to)))
  10859. (overlay-put o 'invisible 'js2-outline)
  10860. (overlay-put o 'isearch-open-invisible
  10861. 'js2-isearch-open-invisible)
  10862. o)))
  10863. ;; Function to be set as an outline-isearch-open-invisible' property
  10864. ;; to the overlay that makes the outline invisible (see
  10865. ;; `js2-mode-flag-region').
  10866. (defun js2-isearch-open-invisible (_overlay)
  10867. ;; We rely on the fact that isearch places point on the matched text.
  10868. (js2-mode-show-element))
  10869. (defun js2-mode-invisible-overlay-bounds (&optional pos)
  10870. "Return cons cell of bounds of folding overlay at POS.
  10871. Returns nil if not found."
  10872. (let ((overlays (overlays-at (or pos (point))))
  10873. o)
  10874. (while (and overlays
  10875. (not o))
  10876. (if (overlay-get (car overlays) 'invisible)
  10877. (setq o (car overlays))
  10878. (setq overlays (cdr overlays))))
  10879. (if o
  10880. (cons (overlay-start o) (overlay-end o)))))
  10881. (defun js2-mode-function-at-point (&optional pos)
  10882. "Return the innermost function node enclosing current point.
  10883. Returns nil if point is not in a function."
  10884. (let ((node (js2-node-at-point pos)))
  10885. (while (and node (not (js2-function-node-p node)))
  10886. (setq node (js2-node-parent node)))
  10887. (if (js2-function-node-p node)
  10888. node)))
  10889. (defun js2-mode-toggle-element ()
  10890. "Hide or show the foldable element at the point."
  10891. (interactive)
  10892. (let (comment fn pos)
  10893. (save-excursion
  10894. (cond
  10895. ;; /* ... */ comment?
  10896. ((js2-block-comment-p (setq comment (js2-comment-at-point)))
  10897. (if (js2-mode-invisible-overlay-bounds
  10898. (setq pos (+ 3 (js2-node-abs-pos comment))))
  10899. (progn
  10900. (goto-char pos)
  10901. (js2-mode-show-element))
  10902. (js2-mode-hide-element)))
  10903. ;; //-comment?
  10904. ((save-excursion
  10905. (back-to-indentation)
  10906. (looking-at js2-mode-//-comment-re))
  10907. (js2-mode-toggle-//-comment))
  10908. ;; function?
  10909. ((setq fn (js2-mode-function-at-point))
  10910. (setq pos (and (js2-function-node-body fn)
  10911. (js2-node-abs-pos (js2-function-node-body fn))))
  10912. (goto-char (1+ pos))
  10913. (if (js2-mode-invisible-overlay-bounds)
  10914. (js2-mode-show-element)
  10915. (js2-mode-hide-element)))
  10916. (t
  10917. (message "Nothing at point to hide or show"))))))
  10918. (defun js2-mode-hide-element ()
  10919. "Fold/hide contents of a block, showing ellipses.
  10920. Show the hidden text with \\[js2-mode-show-element]."
  10921. (interactive)
  10922. (if js2-mode-buffer-dirty-p
  10923. (js2-mode-wait-for-parse #'js2-mode-hide-element))
  10924. (let (node body beg end)
  10925. (cond
  10926. ((js2-mode-invisible-overlay-bounds)
  10927. (message "already hidden"))
  10928. (t
  10929. (setq node (js2-node-at-point))
  10930. (cond
  10931. ((js2-block-comment-p node)
  10932. (js2-mode-hide-comment node))
  10933. (t
  10934. (while (and node (not (js2-function-node-p node)))
  10935. (setq node (js2-node-parent node)))
  10936. (if (and node
  10937. (setq body (js2-function-node-body node)))
  10938. (progn
  10939. (setq beg (js2-node-abs-pos body)
  10940. end (+ beg (js2-node-len body)))
  10941. (js2-mode-flag-region (1+ beg) (1- end) 'hide))
  10942. (message "No collapsable element found at point"))))))))
  10943. (defun js2-mode-show-element ()
  10944. "Show the hidden element at current point."
  10945. (interactive)
  10946. (let ((bounds (js2-mode-invisible-overlay-bounds)))
  10947. (if bounds
  10948. (js2-mode-flag-region (car bounds) (cdr bounds) nil)
  10949. (message "Nothing to un-hide"))))
  10950. (defun js2-mode-show-all ()
  10951. "Show all of the text in the buffer."
  10952. (interactive)
  10953. (js2-mode-flag-region (point-min) (point-max) nil))
  10954. (defun js2-mode-toggle-hide-functions ()
  10955. (interactive)
  10956. (if js2-mode-functions-hidden
  10957. (js2-mode-show-functions)
  10958. (js2-mode-hide-functions)))
  10959. (defun js2-mode-hide-functions ()
  10960. "Hides all non-nested function bodies in the buffer.
  10961. Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
  10962. to open an individual entry."
  10963. (interactive)
  10964. (if js2-mode-buffer-dirty-p
  10965. (js2-mode-wait-for-parse #'js2-mode-hide-functions))
  10966. (if (null js2-mode-ast)
  10967. (message "Oops - parsing failed")
  10968. (setq js2-mode-functions-hidden t)
  10969. (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
  10970. (defun js2-mode-function-hider (n endp)
  10971. (when (not endp)
  10972. (let ((tt (js2-node-type n))
  10973. body beg end)
  10974. (cond
  10975. ((and (= tt js2-FUNCTION)
  10976. (setq body (js2-function-node-body n)))
  10977. (setq beg (js2-node-abs-pos body)
  10978. end (+ beg (js2-node-len body)))
  10979. (js2-mode-flag-region (1+ beg) (1- end) 'hide)
  10980. nil) ; don't process children of function
  10981. (t
  10982. t))))) ; keep processing other AST nodes
  10983. (defun js2-mode-show-functions ()
  10984. "Un-hide any folded function bodies in the buffer."
  10985. (interactive)
  10986. (setq js2-mode-functions-hidden nil)
  10987. (save-excursion
  10988. (goto-char (point-min))
  10989. (while (/= (goto-char (next-overlay-change (point)))
  10990. (point-max))
  10991. (dolist (o (overlays-at (point)))
  10992. (when (and (overlay-get o 'invisible)
  10993. (not (overlay-get o 'comment)))
  10994. (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
  10995. (defun js2-mode-hide-comment (n)
  10996. (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
  10997. 3 ; /**
  10998. 2)) ; /*
  10999. (beg (+ (js2-node-abs-pos n) head))
  11000. (end (- (+ beg (js2-node-len n)) head 2))
  11001. (o (js2-mode-flag-region beg end 'hide)))
  11002. (overlay-put o 'comment t)))
  11003. (defun js2-mode-toggle-hide-comments ()
  11004. "Folds all block comments in the buffer.
  11005. Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
  11006. to open an individual entry."
  11007. (interactive)
  11008. (if js2-mode-comments-hidden
  11009. (js2-mode-show-comments)
  11010. (js2-mode-hide-comments)))
  11011. (defun js2-mode-hide-comments ()
  11012. (interactive)
  11013. (if js2-mode-buffer-dirty-p
  11014. (js2-mode-wait-for-parse #'js2-mode-hide-comments))
  11015. (if (null js2-mode-ast)
  11016. (message "Oops - parsing failed")
  11017. (setq js2-mode-comments-hidden t)
  11018. (dolist (n (js2-ast-root-comments js2-mode-ast))
  11019. (when (js2-block-comment-p n)
  11020. (js2-mode-hide-comment n)))
  11021. (js2-mode-hide-//-comments)))
  11022. (defun js2-mode-extend-//-comment (direction)
  11023. "Find start or end of a block of similar //-comment lines.
  11024. DIRECTION is -1 to look back, 1 to look forward.
  11025. INDENT is the indentation level to match.
  11026. Returns the end-of-line position of the furthest adjacent
  11027. //-comment line with the same indentation as the current line.
  11028. If there is no such matching line, returns current end of line."
  11029. (let ((pos (point-at-eol))
  11030. (indent (current-indentation)))
  11031. (save-excursion
  11032. (while (and (zerop (forward-line direction))
  11033. (looking-at js2-mode-//-comment-re)
  11034. (eq indent (length (match-string 1))))
  11035. (setq pos (point-at-eol)))
  11036. pos)))
  11037. (defun js2-mode-hide-//-comments ()
  11038. "Fold adjacent 1-line comments, showing only snippet of first one."
  11039. (let (beg end)
  11040. (save-excursion
  11041. (goto-char (point-min))
  11042. (while (re-search-forward js2-mode-//-comment-re nil t)
  11043. (setq beg (point)
  11044. end (js2-mode-extend-//-comment 1))
  11045. (unless (eq beg end)
  11046. (overlay-put (js2-mode-flag-region beg end 'hide)
  11047. 'comment t))
  11048. (goto-char end)
  11049. (forward-char 1)))))
  11050. (defun js2-mode-toggle-//-comment ()
  11051. "Fold or un-fold any multi-line //-comment at point.
  11052. Caller should have determined that this line starts with a //-comment."
  11053. (let* ((beg (point-at-eol))
  11054. (end beg))
  11055. (save-excursion
  11056. (goto-char end)
  11057. (if (js2-mode-invisible-overlay-bounds)
  11058. (js2-mode-show-element)
  11059. ;; else hide the comment
  11060. (setq beg (js2-mode-extend-//-comment -1)
  11061. end (js2-mode-extend-//-comment 1))
  11062. (unless (eq beg end)
  11063. (overlay-put (js2-mode-flag-region beg end 'hide)
  11064. 'comment t))))))
  11065. (defun js2-mode-show-comments ()
  11066. "Un-hide any hidden comments, leaving other hidden elements alone."
  11067. (interactive)
  11068. (setq js2-mode-comments-hidden nil)
  11069. (save-excursion
  11070. (goto-char (point-min))
  11071. (while (/= (goto-char (next-overlay-change (point)))
  11072. (point-max))
  11073. (dolist (o (overlays-at (point)))
  11074. (when (overlay-get o 'comment)
  11075. (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
  11076. (defun js2-mode-display-warnings-and-errors ()
  11077. "Turn on display of warnings and errors."
  11078. (interactive)
  11079. (setq js2-mode-show-parse-errors t
  11080. js2-mode-show-strict-warnings t)
  11081. (js2-reparse 'force))
  11082. (defun js2-mode-hide-warnings-and-errors ()
  11083. "Turn off display of warnings and errors."
  11084. (interactive)
  11085. (setq js2-mode-show-parse-errors nil
  11086. js2-mode-show-strict-warnings nil)
  11087. (js2-reparse 'force))
  11088. (defun js2-mode-toggle-warnings-and-errors ()
  11089. "Toggle the display of warnings and errors.
  11090. Some users don't like having warnings/errors reported while they type."
  11091. (interactive)
  11092. (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
  11093. js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
  11094. (if (called-interactively-p 'any)
  11095. (message "warnings and errors %s"
  11096. (if js2-mode-show-parse-errors
  11097. "enabled"
  11098. "disabled")))
  11099. (js2-reparse 'force))
  11100. (defun js2-mode-customize ()
  11101. (interactive)
  11102. (customize-group 'js2-mode))
  11103. (defun js2-mode-forward-sexp (&optional arg)
  11104. "Move forward across one statement or balanced expression.
  11105. With ARG, do it that many times. Negative arg -N means
  11106. move backward across N balanced expressions."
  11107. (interactive "p")
  11108. (setq arg (or arg 1))
  11109. (save-restriction
  11110. (widen) ;; `blink-matching-open' calls `narrow-to-region'
  11111. (js2-reparse)
  11112. (let (forward-sexp-function
  11113. node (start (point)) pos lp rp child)
  11114. (cond
  11115. ((js2-string-node-p (js2-node-at-point))
  11116. (forward-sexp arg))
  11117. ;; backward-sexp
  11118. ;; could probably make this better for some cases:
  11119. ;; - if in statement block (e.g. function body), go to parent
  11120. ;; - infix exprs like (foo in bar) - maybe go to beginning
  11121. ;; of infix expr if in the right-side expression?
  11122. ((and arg (cl-minusp arg))
  11123. (dotimes (_ (- arg))
  11124. (js2-backward-sws)
  11125. (forward-char -1) ; Enter the node we backed up to.
  11126. (when (setq node (js2-node-at-point (point) t))
  11127. (setq pos (js2-node-abs-pos node))
  11128. (let ((parens (js2-mode-forward-sexp-parens node pos)))
  11129. (setq lp (car parens)
  11130. rp (cdr parens)))
  11131. (when (and lp (> start lp))
  11132. (if (and rp (<= start rp))
  11133. ;; Between parens, check if there's a child node we can jump.
  11134. (when (setq child (js2-node-closest-child node (point) lp t))
  11135. (setq pos (js2-node-abs-pos child)))
  11136. ;; Before both parens.
  11137. (setq pos lp)))
  11138. (let ((state (parse-partial-sexp start pos)))
  11139. (goto-char (if (not (zerop (car state)))
  11140. ;; Stumble at the unbalanced paren if < 0, or
  11141. ;; jump a bit further if > 0.
  11142. (scan-sexps start -1)
  11143. pos))))
  11144. (unless pos (goto-char (point-min)))))
  11145. (t
  11146. ;; forward-sexp
  11147. (dotimes (_ arg)
  11148. (js2-forward-sws)
  11149. (when (setq node (js2-node-at-point (point) t))
  11150. (setq pos (js2-node-abs-pos node))
  11151. (let ((parens (js2-mode-forward-sexp-parens node pos)))
  11152. (setq lp (car parens)
  11153. rp (cdr parens)))
  11154. (or
  11155. (when (and rp (<= start rp))
  11156. (if (> start lp)
  11157. (when (setq child (js2-node-closest-child node (point) rp))
  11158. (setq pos (js2-node-abs-end child)))
  11159. (setq pos (1+ rp))))
  11160. ;; No parens or child nodes, looks for the end of the current node.
  11161. (cl-incf pos (js2-node-len
  11162. (if (js2-expr-stmt-node-p (js2-node-parent node))
  11163. ;; Stop after the semicolon.
  11164. (js2-node-parent node)
  11165. node))))
  11166. (let ((state (save-excursion (parse-partial-sexp start pos))))
  11167. (goto-char (if (not (zerop (car state)))
  11168. (scan-sexps start 1)
  11169. pos))))
  11170. (unless pos (goto-char (point-max)))))))))
  11171. (defun js2-mode-forward-sexp-parens (node abs-pos)
  11172. "Return a cons cell with positions of main parens in NODE."
  11173. (cond
  11174. ((or (js2-array-node-p node)
  11175. (js2-object-node-p node)
  11176. (js2-comp-node-p node)
  11177. (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
  11178. (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
  11179. ((js2-paren-expr-node-p node)
  11180. (let ((lp (js2-node-lp node))
  11181. (rp (js2-node-rp node)))
  11182. (cons (when lp (+ abs-pos lp))
  11183. (when rp (+ abs-pos rp)))))))
  11184. (defun js2-node-closest-child (parent point limit &optional before)
  11185. (let* ((parent-pos (js2-node-abs-pos parent))
  11186. (rpoint (- point parent-pos))
  11187. (rlimit (- limit parent-pos))
  11188. (min (min rpoint rlimit))
  11189. (max (max rpoint rlimit))
  11190. found)
  11191. (catch 'done
  11192. (js2-visit-ast
  11193. parent
  11194. (lambda (node _end-p)
  11195. (if (eq node parent)
  11196. t
  11197. (let ((pos (js2-node-pos node)) ;; Both relative values.
  11198. (end (+ (js2-node-pos node) (js2-node-len node))))
  11199. (when (and (>= pos min) (<= end max)
  11200. (if before (< pos rpoint) (> end rpoint)))
  11201. (setq found node))
  11202. (when (> end rpoint)
  11203. (throw 'done nil)))
  11204. nil))))
  11205. found))
  11206. (defun js2-errors ()
  11207. "Return a list of errors found."
  11208. (and js2-mode-ast
  11209. (js2-ast-root-errors js2-mode-ast)))
  11210. (defun js2-warnings ()
  11211. "Return a list of warnings found."
  11212. (and js2-mode-ast
  11213. (js2-ast-root-warnings js2-mode-ast)))
  11214. (defun js2-have-errors-p ()
  11215. "Return non-nil if any parse errors or warnings were found."
  11216. (or (js2-errors) (js2-warnings)))
  11217. (defun js2-errors-and-warnings ()
  11218. "Return a copy of the concatenated errors and warnings lists.
  11219. They are appended: first the errors, then the warnings.
  11220. Entries are of the form (MSG BEG END)."
  11221. (when js2-mode-ast
  11222. (append (js2-ast-root-errors js2-mode-ast)
  11223. (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
  11224. (defun js2-next-error (&optional arg reset)
  11225. "Move to next parse error.
  11226. Typically invoked via \\[next-error].
  11227. ARG is the number of errors, forward or backward, to move.
  11228. RESET means start over from the beginning."
  11229. (interactive "p")
  11230. (if (not (or (js2-errors) (js2-warnings)))
  11231. (message "No errors")
  11232. (when reset
  11233. (goto-char (point-min)))
  11234. (let* ((errs (js2-errors-and-warnings))
  11235. (continue t)
  11236. (start (point))
  11237. (count (or arg 1))
  11238. (backward (cl-minusp count))
  11239. (sorter (if backward '> '<))
  11240. (stopper (if backward '< '>))
  11241. (count (abs count))
  11242. all-errs err)
  11243. ;; Sort by start position.
  11244. (setq errs (sort errs (lambda (e1 e2)
  11245. (funcall sorter (cl-second e1) (cl-second e2))))
  11246. all-errs errs)
  11247. ;; Find nth error with pos > start.
  11248. (while (and errs continue)
  11249. (when (funcall stopper (cl-cadar errs) start)
  11250. (setq err (car errs))
  11251. (if (zerop (cl-decf count))
  11252. (setq continue nil)))
  11253. (setq errs (cdr errs)))
  11254. ;; Clear for `js2-echo-error'.
  11255. (message nil)
  11256. (if err
  11257. (goto-char (cl-second err))
  11258. ;; Wrap around to first error.
  11259. (goto-char (cl-second (car all-errs)))
  11260. ;; If we were already on it, echo msg again.
  11261. (if (= (point) start)
  11262. (js2-echo-error (point) (point)))))))
  11263. (defun js2-down-mouse-3 ()
  11264. "Make right-click move the point to the click location.
  11265. This makes right-click context menu operations a bit more intuitive.
  11266. The point will not move if the region is active, however, to avoid
  11267. destroying the region selection."
  11268. (interactive)
  11269. (when (and js2-move-point-on-right-click
  11270. (not mark-active))
  11271. (let ((e last-input-event))
  11272. (ignore-errors
  11273. (goto-char (cl-cadadr e))))))
  11274. (defun js2-mode-create-imenu-index ()
  11275. "Returns an alist for `imenu--index-alist'. Returns nil on first
  11276. scan if buffer size > `imenu-auto-rescan-maxout'."
  11277. (when (and (not js2-mode-ast)
  11278. (<= (buffer-size) imenu-auto-rescan-maxout))
  11279. (js2-reparse))
  11280. (when js2-mode-ast
  11281. ;; if we have an ast but no recorder, they're requesting a rescan
  11282. (unless js2-imenu-recorder
  11283. (js2-reparse 'force))
  11284. (prog1
  11285. (js2-build-imenu-index)
  11286. (setq js2-imenu-recorder nil
  11287. js2-imenu-function-map nil))))
  11288. (defun js2-mode-find-tag ()
  11289. "Replacement for `find-tag-default'.
  11290. `find-tag-default' returns a ridiculous answer inside comments."
  11291. (let (beg end)
  11292. (save-excursion
  11293. (if (looking-at "\\_>")
  11294. (setq beg (progn (forward-symbol -1) (point))
  11295. end (progn (forward-symbol 1) (point)))
  11296. (setq beg (progn (forward-symbol 1) (point))
  11297. end (progn (forward-symbol -1) (point))))
  11298. (replace-regexp-in-string
  11299. "[\"']" ""
  11300. (buffer-substring-no-properties beg end)))))
  11301. (defun js2-mode-forward-sibling ()
  11302. "Move to the end of the sibling following point in parent.
  11303. Returns non-nil if successful, or nil if there was no following sibling."
  11304. (let* ((node (js2-node-at-point))
  11305. (parent (js2-mode-find-enclosing-fn node))
  11306. sib)
  11307. (when (setq sib (js2-node-find-child-after (point) parent))
  11308. (goto-char (+ (js2-node-abs-pos sib)
  11309. (js2-node-len sib))))))
  11310. (defun js2-mode-backward-sibling ()
  11311. "Move to the beginning of the sibling node preceding point in parent.
  11312. Parent is defined as the enclosing script or function."
  11313. (let* ((node (js2-node-at-point))
  11314. (parent (js2-mode-find-enclosing-fn node))
  11315. sib)
  11316. (when (setq sib (js2-node-find-child-before (point) parent))
  11317. (goto-char (js2-node-abs-pos sib)))))
  11318. (defun js2-beginning-of-defun (&optional arg)
  11319. "Go to line on which current function starts, and return t on success.
  11320. If we're not in a function or already at the beginning of one, go
  11321. to beginning of previous script-level element.
  11322. With ARG N, do that N times. If N is negative, move forward."
  11323. (setq arg (or arg 1))
  11324. (if (cl-plusp arg)
  11325. (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
  11326. (when (cond
  11327. ((js2-function-node-p parent)
  11328. (goto-char (js2-node-abs-pos parent)))
  11329. (t
  11330. (js2-mode-backward-sibling)))
  11331. (if (> arg 1)
  11332. (js2-beginning-of-defun (1- arg))
  11333. t)))
  11334. (when (js2-end-of-defun)
  11335. (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
  11336. (defun js2-end-of-defun ()
  11337. "Go to the char after the last position of the current function
  11338. or script-level element."
  11339. (let* ((node (js2-node-at-point))
  11340. (parent (or (and (js2-function-node-p node) node)
  11341. (js2-node-parent-script-or-fn node)))
  11342. script)
  11343. (unless (js2-function-node-p parent)
  11344. ;; Use current script-level node, or, if none, the next one.
  11345. (setq script (or parent node)
  11346. parent (js2-node-find-child-before (point) script))
  11347. (when (or (null parent)
  11348. (>= (point) (+ (js2-node-abs-pos parent)
  11349. (js2-node-len parent))))
  11350. (setq parent (js2-node-find-child-after (point) script))))
  11351. (when parent
  11352. (goto-char (+ (js2-node-abs-pos parent)
  11353. (js2-node-len parent))))))
  11354. (defun js2-mark-defun (&optional allow-extend)
  11355. "Put mark at end of this function, point at beginning.
  11356. The function marked is the one that contains point.
  11357. Interactively, if this command is repeated,
  11358. or (in Transient Mark mode) if the mark is active,
  11359. it marks the next defun after the ones already marked."
  11360. (interactive "p")
  11361. (let (extended)
  11362. (when (and allow-extend
  11363. (or (and (eq last-command this-command) (mark t))
  11364. (and transient-mark-mode mark-active)))
  11365. (let ((sib (save-excursion
  11366. (goto-char (mark))
  11367. (if (js2-mode-forward-sibling)
  11368. (point)))))
  11369. (if sib
  11370. (progn
  11371. (set-mark sib)
  11372. (setq extended t))
  11373. ;; no more siblings - try extending to enclosing node
  11374. (goto-char (mark t)))))
  11375. (when (not extended)
  11376. (let ((node (js2-node-at-point (point) t)) ; skip comments
  11377. ast fn stmt parent beg end)
  11378. (when (js2-ast-root-p node)
  11379. (setq ast node
  11380. node (or (js2-node-find-child-after (point) node)
  11381. (js2-node-find-child-before (point) node))))
  11382. ;; only mark whole buffer if we can't find any children
  11383. (if (null node)
  11384. (setq node ast))
  11385. (if (js2-function-node-p node)
  11386. (setq parent node)
  11387. (setq fn (js2-mode-find-enclosing-fn node)
  11388. stmt (if (or (null fn)
  11389. (js2-ast-root-p fn))
  11390. (js2-mode-find-first-stmt node))
  11391. parent (or stmt fn)))
  11392. (setq beg (js2-node-abs-pos parent)
  11393. end (+ beg (js2-node-len parent)))
  11394. (push-mark beg)
  11395. (goto-char end)
  11396. (exchange-point-and-mark)))))
  11397. (defun js2-narrow-to-defun ()
  11398. "Narrow to the function enclosing point."
  11399. (interactive)
  11400. (let* ((node (js2-node-at-point (point) t)) ; skip comments
  11401. (fn (if (js2-script-node-p node)
  11402. node
  11403. (js2-mode-find-enclosing-fn node)))
  11404. (beg (js2-node-abs-pos fn)))
  11405. (unless (js2-ast-root-p fn)
  11406. (narrow-to-region beg (+ beg (js2-node-len fn))))))
  11407. (defun js2-jump-to-definition (&optional arg)
  11408. "Jump to the definition of an object's property, variable or function."
  11409. (interactive "P")
  11410. (if (eval-when-compile (fboundp 'xref-push-marker-stack))
  11411. (xref-push-marker-stack)
  11412. (ring-insert find-tag-marker-ring (point-marker)))
  11413. (js2-reparse)
  11414. (let* ((node (js2-node-at-point))
  11415. (parent (js2-node-parent node))
  11416. (names (if (js2-prop-get-node-p parent)
  11417. (reverse (let ((temp (js2-compute-nested-prop-get parent)))
  11418. (cl-loop for n in temp
  11419. with result = '()
  11420. do (push n result)
  11421. until (equal node n)
  11422. finally return result)))))
  11423. node-init)
  11424. (unless (and (js2-name-node-p node)
  11425. (not (js2-var-init-node-p parent))
  11426. (not (js2-function-node-p parent)))
  11427. (error "Node is not a supported jump node"))
  11428. (push (or (and names (pop names))
  11429. (unless (and (js2-object-prop-node-p parent)
  11430. (eq node (js2-object-prop-node-left parent))
  11431. (not (js2-node-get-prop parent 'SHORTHAND)))
  11432. node)
  11433. (error "Node is not a supported jump node")) names)
  11434. (setq node-init (js2-search-scope node names))
  11435. ;; todo: display list of results in buffer
  11436. ;; todo: group found references by buffer
  11437. (unless node-init
  11438. (switch-to-buffer
  11439. (catch 'found
  11440. (unless arg
  11441. (mapc (lambda (b)
  11442. (with-current-buffer b
  11443. (when (derived-mode-p 'js2-mode)
  11444. (setq node-init (js2-search-scope js2-mode-ast names))
  11445. (if node-init
  11446. (throw 'found b)))))
  11447. (buffer-list)))
  11448. nil)))
  11449. (setq node-init (if (listp node-init) (car node-init) node-init))
  11450. (unless node-init
  11451. (pop-tag-mark)
  11452. (error "No jump location found"))
  11453. (goto-char (js2-node-abs-pos node-init))))
  11454. (defun js2-search-object (node name-node)
  11455. "Check if object NODE contains element with NAME-NODE."
  11456. (cl-assert (js2-object-node-p node))
  11457. ;; Only support name-node and nodes for the time being
  11458. (cl-loop for elem in (js2-object-node-elems node)
  11459. for left = (js2-object-prop-node-left elem)
  11460. if (or (and (js2-name-node-p left)
  11461. (equal (js2-name-node-name name-node)
  11462. (js2-name-node-name left)))
  11463. (and (js2-string-node-p left)
  11464. (string= (js2-name-node-name name-node)
  11465. (js2-string-node-value left))))
  11466. return elem))
  11467. (defun js2-search-object-for-prop (object prop-names)
  11468. "Return node in OBJECT that matches PROP-NAMES or nil.
  11469. PROP-NAMES is a list of values representing a path to a value in OBJECT.
  11470. i.e. ('name' 'value') = {name : { value: 3}}"
  11471. (let (node
  11472. (temp-object object)
  11473. (temp t) ;temporay node
  11474. (names prop-names))
  11475. (while (and temp names (js2-object-node-p temp-object))
  11476. (setq temp (js2-search-object temp-object (pop names)))
  11477. (and (setq node temp)
  11478. (setq temp-object (js2-object-prop-node-right temp))))
  11479. (unless names node)))
  11480. (defun js2-search-scope (node names)
  11481. "Searches NODE scope for jump location matching NAMES.
  11482. NAMES is a list of property values to search for. For functions
  11483. and variables NAMES will contain one element."
  11484. (let (node-init
  11485. (val (js2-name-node-name (car names))))
  11486. (setq node-init (js2-get-symbol-declaration node val))
  11487. (when (> (length names) 1)
  11488. ;; Check var declarations
  11489. (when (and node-init (string= val (js2-name-node-name node-init)))
  11490. (let ((parent (js2-node-parent node-init))
  11491. (temp-names names))
  11492. (pop temp-names) ;; First element is var name
  11493. (setq node-init (when (js2-var-init-node-p parent)
  11494. (js2-search-object-for-prop
  11495. (js2-var-init-node-initializer parent)
  11496. temp-names)))))
  11497. ;; Check all assign nodes
  11498. (js2-visit-ast
  11499. js2-mode-ast
  11500. (lambda (node endp)
  11501. (unless endp
  11502. (if (js2-assign-node-p node)
  11503. (let ((left (js2-assign-node-left node))
  11504. (right (js2-assign-node-right node))
  11505. (temp-names names))
  11506. (when (js2-prop-get-node-p left)
  11507. (let* ((prop-list (js2-compute-nested-prop-get left))
  11508. (found (cl-loop for prop in prop-list
  11509. until (not (string= (js2-name-node-name
  11510. (pop temp-names))
  11511. (js2-name-node-name prop)))
  11512. if (not temp-names) return prop))
  11513. (found-node (or found
  11514. (when (js2-object-node-p right)
  11515. (js2-search-object-for-prop right
  11516. temp-names)))))
  11517. (if found-node (push found-node node-init))))))
  11518. t))))
  11519. node-init))
  11520. (defun js2-get-symbol-declaration (node name)
  11521. "Find scope for NAME from NODE."
  11522. (let ((scope (js2-get-defining-scope
  11523. (or (js2-node-get-enclosing-scope node)
  11524. node) name)))
  11525. (if scope (js2-symbol-ast-node (js2-scope-get-symbol scope name)))))
  11526. (provide 'js2-mode)
  11527. ;;; js2-mode.el ends here