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.

12993 lines
504 KiB

  1. ;;; js2-mode.el --- Improved JavaScript editing mode -*- lexical-binding: t -*-
  2. ;; Copyright (C) 2009, 2011-2020 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: 20201220
  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. ;; Use Emacs 27 and want to write JSX? Then use `js2-minor-mode' as described
  48. ;; above. Use Emacs 26 or earlier? Then use `js2-jsx-mode':
  49. ;; (add-to-list 'auto-mode-alist '("\\.jsx?\\'" . js2-jsx-mode))
  50. ;; (add-to-list 'interpreter-mode-alist '("node" . js2-jsx-mode))
  51. ;; Note that linting of JSX code may fail in both modes.
  52. ;; To customize how it works:
  53. ;; M-x customize-group RET js2-mode RET
  54. ;; Notes:
  55. ;; This mode includes a port of Mozilla Rhino's scanner, parser and
  56. ;; symbol table. Ideally it should stay in sync with Rhino, keeping
  57. ;; `js2-mode' current as the EcmaScript language standard evolves.
  58. ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
  59. ;; customizable. It is a surprising amount of work to support customizable
  60. ;; indentation. The current compromise is that the tab key lets you cycle among
  61. ;; various likely indentation points, similar to the behavior of python-mode.
  62. ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
  63. ;; and `mumamo', although it could be made to do so with some effort.
  64. ;; This means that `js2-mode' is currently only useful for editing JavaScript
  65. ;; files, and not for editing JavaScript within <script> tags or templates.
  66. ;; The project page on GitHub is used for development and issue tracking.
  67. ;; The original homepage at Google Code has outdated information and is mostly
  68. ;; unmaintained.
  69. ;;; Code:
  70. (require 'cl-lib)
  71. (require 'imenu)
  72. (require 'js)
  73. (require 'etags)
  74. (eval-and-compile
  75. (if (version< emacs-version "25.0")
  76. (require 'js2-old-indent)
  77. (defvaralias 'js2-basic-offset 'js-indent-level nil)
  78. (defalias 'js2-proper-indentation 'js--proper-indentation)
  79. (defalias 'js2-jsx-indent-line 'js-jsx-indent-line)
  80. (defalias 'js2-indent-line 'js-indent-line)
  81. (defalias 'js2-re-search-forward 'js--re-search-forward)))
  82. ;;; Externs (variables presumed to be defined by the host system)
  83. (defvar js2-ecma-262-externs
  84. (mapcar 'symbol-name
  85. '(Array Boolean Date Error EvalError Function Infinity JSON
  86. Math NaN Number Object RangeError ReferenceError RegExp
  87. String SyntaxError TypeError URIError
  88. decodeURI decodeURIComponent encodeURI
  89. encodeURIComponent escape eval isFinite isNaN
  90. parseFloat parseInt undefined unescape))
  91. "Ecma-262 externs. Never highlighted as undeclared variables.")
  92. (defvar js2-browser-externs
  93. (mapcar 'symbol-name
  94. '(;; DOM level 1
  95. Attr CDATASection CharacterData Comment DOMException
  96. DOMImplementation Document DocumentFragment
  97. DocumentType Element Entity EntityReference
  98. ExceptionCode NamedNodeMap Node NodeList Notation
  99. ProcessingInstruction Text
  100. ;; DOM level 2
  101. HTMLAnchorElement HTMLAppletElement HTMLAreaElement
  102. HTMLBRElement HTMLBaseElement HTMLBaseFontElement
  103. HTMLBodyElement HTMLButtonElement HTMLCollection
  104. HTMLDListElement HTMLDirectoryElement HTMLDivElement
  105. HTMLDocument HTMLElement HTMLFieldSetElement
  106. HTMLFontElement HTMLFormElement HTMLFrameElement
  107. HTMLFrameSetElement HTMLHRElement HTMLHeadElement
  108. HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
  109. HTMLImageElement HTMLInputElement HTMLIsIndexElement
  110. HTMLLIElement HTMLLabelElement HTMLLegendElement
  111. HTMLLinkElement HTMLMapElement HTMLMenuElement
  112. HTMLMetaElement HTMLModElement HTMLOListElement
  113. HTMLObjectElement HTMLOptGroupElement
  114. HTMLOptionElement HTMLOptionsCollection
  115. HTMLParagraphElement HTMLParamElement HTMLPreElement
  116. HTMLQuoteElement HTMLScriptElement HTMLSelectElement
  117. HTMLStyleElement HTMLTableCaptionElement
  118. HTMLTableCellElement HTMLTableColElement
  119. HTMLTableElement HTMLTableRowElement
  120. HTMLTableSectionElement HTMLTextAreaElement
  121. HTMLTitleElement HTMLUListElement
  122. ;; DOM level 3
  123. DOMConfiguration DOMError DOMException
  124. DOMImplementationList DOMImplementationSource
  125. DOMLocator DOMStringList NameList TypeInfo
  126. UserDataHandler
  127. ;; Window
  128. window alert confirm document java navigator prompt screen
  129. self top requestAnimationFrame cancelAnimationFrame
  130. ;; Window or WorkerGlobalScope with support in Chromium and Firefox:
  131. ;; https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope
  132. ;; properties
  133. caches indexedDB isSecureContext origin
  134. ;; methods
  135. atob btoa clearInterval clearTimeout
  136. createImageBitmap fetch queueMicrotask setInterval
  137. setTimeout
  138. ;; from jslint "browser"
  139. history location
  140. ;; HTML element constructors
  141. Audio Image Option
  142. ;; W3C CSS
  143. CSSCharsetRule CSSFontFace CSSFontFaceRule
  144. CSSImportRule CSSMediaRule CSSPageRule
  145. CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
  146. CSSStyleDeclaration CSSStyleRule CSSStyleSheet
  147. CSSValue CSSValueList Counter DOMImplementationCSS
  148. DocumentCSS DocumentStyle ElementCSSInlineStyle
  149. LinkStyle MediaList RGBColor Rect StyleSheet
  150. StyleSheetList ViewCSS
  151. ;; W3C Event
  152. EventListener EventTarget Event DocumentEvent UIEvent
  153. MouseEvent MutationEvent KeyboardEvent
  154. ;; W3C Range
  155. DocumentRange Range RangeException
  156. ;; W3C XML
  157. XPathResult XMLHttpRequest
  158. ;; console object. Provided by at least Chrome and Firefox.
  159. console))
  160. "Browser externs.
  161. You can cause these to be included or excluded with the custom
  162. variable `js2-include-browser-externs'.")
  163. (defvar js2-rhino-externs
  164. (mapcar 'symbol-name
  165. '(Packages importClass importPackage com org java
  166. ;; Global object (shell) externs.
  167. defineClass deserialize doctest gc help load
  168. loadClass print quit readFile readUrl runCommand seal
  169. serialize spawn sync toint32 version))
  170. "Mozilla Rhino externs.
  171. Set `js2-include-rhino-externs' to t to include them.")
  172. (defvar js2-node-externs
  173. (mapcar 'symbol-name
  174. '(__dirname __filename Buffer clearInterval clearTimeout require
  175. console exports global module process setInterval setTimeout
  176. querystring setImmediate clearImmediate))
  177. "Node.js externs.
  178. Set `js2-include-node-externs' to t to include them.")
  179. (defvar js2-typed-array-externs
  180. (mapcar 'symbol-name
  181. '(ArrayBuffer Uint8ClampedArray DataView
  182. Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
  183. Float32Array Float64Array))
  184. "Khronos typed array externs. Available in most modern browsers and
  185. in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
  186. are enabled, these will also be included.")
  187. (defvar js2-harmony-externs
  188. (mapcar 'symbol-name
  189. '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
  190. "ES6 externs. If `js2-include-browser-externs' is enabled and
  191. `js2-language-version' is sufficiently high, these will be included.")
  192. ;;; Variables
  193. (defcustom js2-ignored-warnings nil
  194. "A list of warning message types that will not be reported.
  195. Possible values are the keys of `js2-message-table'."
  196. :group 'js2-mode
  197. :type '(repeat string))
  198. (defcustom js2-highlight-level 2
  199. "Amount of syntax highlighting to perform.
  200. 0 or a negative value means none.
  201. 1 adds basic syntax highlighting.
  202. 2 adds highlighting of some Ecma built-in properties.
  203. 3 adds highlighting of many Ecma built-in functions."
  204. :group 'js2-mode
  205. :type '(choice (const :tag "None" 0)
  206. (const :tag "Basic" 1)
  207. (const :tag "Include Properties" 2)
  208. (const :tag "Include Functions" 3)))
  209. (defvar js2-mode-dev-mode-p nil
  210. "Non-nil if running in development mode. Normally nil.")
  211. (defgroup js2-mode nil
  212. "An improved JavaScript mode."
  213. :group 'languages)
  214. (defcustom js2-idle-timer-delay 0.2
  215. "Delay in secs before re-parsing after user makes changes.
  216. Multiplied by `js2-dynamic-idle-timer-adjust', which see."
  217. :type 'number
  218. :group 'js2-mode)
  219. (make-variable-buffer-local 'js2-idle-timer-delay)
  220. (defcustom js2-dynamic-idle-timer-adjust 0
  221. "Positive to adjust `js2-idle-timer-delay' based on file size.
  222. The idea is that for short files, parsing is faster so we can be
  223. more responsive to user edits without interfering with editing.
  224. The buffer length in characters (typically bytes) is divided by
  225. this value and used to multiply `js2-idle-timer-delay' for the
  226. buffer. For example, a 21k file and 10k adjust yields 21k/10k
  227. == 2, so js2-idle-timer-delay is multiplied by 2.
  228. If `js2-dynamic-idle-timer-adjust' is 0 or negative,
  229. `js2-idle-timer-delay' is not dependent on the file size."
  230. :type 'number
  231. :group 'js2-mode)
  232. (defcustom js2-concat-multiline-strings t
  233. "When non-nil, `js2-line-break' in mid-string will make it a
  234. string concatenation. When `eol', the '+' will be inserted at the
  235. end of the line, otherwise, at the beginning of the next line."
  236. :type '(choice (const t) (const eol) (const nil))
  237. :group 'js2-mode)
  238. (defcustom js2-mode-show-parse-errors t
  239. "True to highlight parse errors."
  240. :type 'boolean
  241. :group 'js2-mode)
  242. (defcustom js2-mode-assume-strict nil
  243. "Non-nil to start files in strict mode automatically."
  244. :type 'boolean
  245. :group 'js2-mode)
  246. (defcustom js2-mode-show-strict-warnings t
  247. "Non-nil to emit Ecma strict-mode warnings.
  248. Some of the warnings can be individually disabled by other flags,
  249. even if this flag is non-nil."
  250. :type 'boolean
  251. :group 'js2-mode)
  252. (defcustom js2-strict-trailing-comma-warning nil
  253. "Non-nil to warn about trailing commas in array literals.
  254. Ecma-262-5.1 allows them, but older versions of IE raise an error."
  255. :type 'boolean
  256. :group 'js2-mode)
  257. (defcustom js2-strict-missing-semi-warning t
  258. "Non-nil to warn about semicolon auto-insertion after statement.
  259. Technically this is legal per Ecma-262, but some style guides disallow
  260. depending on it."
  261. :type 'boolean
  262. :group 'js2-mode)
  263. (defcustom js2-missing-semi-one-line-override nil
  264. "Non-nil to permit missing semicolons in one-line functions.
  265. In one-liner functions such as `function identity(x) {return x}'
  266. people often omit the semicolon for a cleaner look. If you are
  267. such a person, you can suppress the missing-semicolon warning
  268. by setting this variable to t."
  269. :type 'boolean
  270. :group 'js2-mode)
  271. (defcustom js2-strict-inconsistent-return-warning t
  272. "Non-nil to warn about mixing returns with value-returns.
  273. It's perfectly legal to have a `return' and a `return foo' in the
  274. same function, but it's often an indicator of a bug, and it also
  275. interferes with type inference (in systems that support it.)"
  276. :type 'boolean
  277. :group 'js2-mode)
  278. (defcustom js2-strict-cond-assign-warning t
  279. "Non-nil to warn about expressions like if (a = b).
  280. This often should have been '==' instead of '='. If the warning
  281. is enabled, you can suppress it on a per-expression basis by
  282. parenthesizing the expression, e.g. if ((a = b)) ..."
  283. :type 'boolean
  284. :group 'js2-mode)
  285. (defcustom js2-strict-var-redeclaration-warning t
  286. "Non-nil to warn about redeclaring variables in a script or function."
  287. :type 'boolean
  288. :group 'js2-mode)
  289. (defcustom js2-strict-var-hides-function-arg-warning t
  290. "Non-nil to warn about a var decl hiding a function argument."
  291. :type 'boolean
  292. :group 'js2-mode)
  293. (defcustom js2-skip-preprocessor-directives nil
  294. "Non-nil to treat lines beginning with # as comments.
  295. Useful for viewing Mozilla JavaScript source code."
  296. :type 'boolean
  297. :group 'js2-mode)
  298. (defcustom js2-language-version 200
  299. "Configures what JavaScript language version to recognize.
  300. Currently versions 150, 160, 170, 180 and 200 are supported,
  301. corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
  302. respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
  303. yield, and Array comprehensions, and 1.8 adds function closures."
  304. :type 'integer
  305. :group 'js2-mode)
  306. (defcustom js2-instanceof-has-side-effects nil
  307. "If non-nil, treats the instanceof operator as having side effects.
  308. This is useful for xulrunner apps."
  309. :type 'boolean
  310. :group 'js2-mode)
  311. (defcustom js2-getprop-has-side-effects nil
  312. "If non-nil, treats the getprop operator as having side effects.
  313. This is useful for testing libraries with nontrivial getters and for
  314. compilers that use empty getprops to declare interface properties."
  315. :type 'boolean
  316. :group 'js2-mode)
  317. (defcustom js2-move-point-on-right-click t
  318. "Non-nil to move insertion point when you right-click.
  319. This makes right-click context menu behavior a bit more intuitive,
  320. since menu operations generally apply to the point. The exception
  321. is if there is a region selection, in which case the point does -not-
  322. move, so cut/copy/paste can work properly.
  323. Note that IntelliJ moves the point, and Eclipse leaves it alone,
  324. so this behavior is customizable."
  325. :group 'js2-mode
  326. :type 'boolean)
  327. (defcustom js2-allow-rhino-new-expr-initializer t
  328. "Non-nil to support a Rhino's experimental syntactic construct.
  329. Rhino supports the ability to follow a `new' expression with an object
  330. literal, which is used to set additional properties on the new object
  331. after calling its constructor. Syntax:
  332. new <expr> [ ( arglist ) ] [initializer]
  333. Hence, this expression:
  334. new Object {a: 1, b: 2}
  335. results in an Object with properties a=1 and b=2. This syntax is
  336. apparently not configurable in Rhino - it's currently always enabled,
  337. as of Rhino version 1.7R2."
  338. :type 'boolean
  339. :group 'js2-mode)
  340. (defcustom js2-allow-member-expr-as-function-name nil
  341. "Non-nil to support experimental Rhino syntax for function names.
  342. Rhino supports an experimental syntax configured via the Rhino Context
  343. setting `allowMemberExprAsFunctionName'. The experimental syntax is:
  344. function <member-expr> ( [ arg-list ] ) { <body> }
  345. Where member-expr is a non-parenthesized 'member expression', which
  346. is anything at the grammar level of a new-expression or lower, meaning
  347. any expression that does not involve infix or unary operators.
  348. When <member-expr> is not a simple identifier, then it is syntactic
  349. sugar for assigning the anonymous function to the <member-expr>. Hence,
  350. this code:
  351. function a.b().c[2] (x, y) { ... }
  352. is rewritten as:
  353. a.b().c[2] = function(x, y) {...}
  354. which doesn't seem particularly useful, but Rhino permits it."
  355. :type 'boolean
  356. :group 'js2-mode)
  357. ;; scanner variables
  358. (defmacro js2-deflocal (name value &optional comment)
  359. "Define a buffer-local variable NAME with VALUE and COMMENT."
  360. (declare (debug defvar) (doc-string 3))
  361. `(progn
  362. (defvar ,name ,value ,comment)
  363. (make-variable-buffer-local ',name)))
  364. (defvar js2-EOF_CHAR -1
  365. "Represents end of stream. Distinct from js2-EOF token type.")
  366. ;; I originally used symbols to represent tokens, but Rhino uses
  367. ;; ints and then sets various flag bits in them, so ints it is.
  368. ;; The upshot is that we need a `js2-' prefix in front of each name.
  369. (defvar js2-ERROR -1)
  370. (defvar js2-EOF 0)
  371. (defvar js2-EOL 1)
  372. (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
  373. (defvar js2-LEAVEWITH 3)
  374. (defvar js2-RETURN 4)
  375. (defvar js2-GOTO 5)
  376. (defvar js2-IFEQ 6)
  377. (defvar js2-IFNE 7)
  378. (defvar js2-SETNAME 8)
  379. (defvar js2-BITOR 9)
  380. (defvar js2-BITXOR 10)
  381. (defvar js2-BITAND 11)
  382. (defvar js2-EQ 12)
  383. (defvar js2-NE 13)
  384. (defvar js2-LT 14)
  385. (defvar js2-LE 15)
  386. (defvar js2-GT 16)
  387. (defvar js2-GE 17)
  388. (defvar js2-LSH 18)
  389. (defvar js2-RSH 19)
  390. (defvar js2-URSH 20)
  391. (defvar js2-ADD 21) ; infix plus
  392. (defvar js2-SUB 22) ; infix minus
  393. (defvar js2-MUL 23)
  394. (defvar js2-DIV 24)
  395. (defvar js2-MOD 25)
  396. (defvar js2-NOT 26)
  397. (defvar js2-BITNOT 27)
  398. (defvar js2-POS 28) ; unary plus
  399. (defvar js2-NEG 29) ; unary minus
  400. (defvar js2-NEW 30)
  401. (defvar js2-DELPROP 31)
  402. (defvar js2-TYPEOF 32)
  403. (defvar js2-GETPROP 33)
  404. (defvar js2-GETPROPNOWARN 34)
  405. (defvar js2-SETPROP 35)
  406. (defvar js2-GETELEM 36)
  407. (defvar js2-SETELEM 37)
  408. (defvar js2-CALL 38)
  409. (defvar js2-NAME 39) ; an identifier
  410. (defvar js2-NUMBER 40)
  411. (defvar js2-STRING 41)
  412. (defvar js2-NULL 42)
  413. (defvar js2-THIS 43)
  414. (defvar js2-FALSE 44)
  415. (defvar js2-TRUE 45)
  416. (defvar js2-SHEQ 46) ; shallow equality (===)
  417. (defvar js2-SHNE 47) ; shallow inequality (!==)
  418. (defvar js2-REGEXP 48)
  419. (defvar js2-BINDNAME 49)
  420. (defvar js2-THROW 50)
  421. (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
  422. (defvar js2-IN 52)
  423. (defvar js2-INSTANCEOF 53)
  424. (defvar js2-LOCAL_LOAD 54)
  425. (defvar js2-GETVAR 55)
  426. (defvar js2-SETVAR 56)
  427. (defvar js2-CATCH_SCOPE 57)
  428. (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
  429. (defvar js2-ENUM_INIT_VALUES 59)
  430. (defvar js2-ENUM_INIT_ARRAY 60)
  431. (defvar js2-ENUM_NEXT 61)
  432. (defvar js2-ENUM_ID 62)
  433. (defvar js2-THISFN 63)
  434. (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
  435. (defvar js2-ARRAYLIT 65) ; array literal
  436. (defvar js2-OBJECTLIT 66) ; object literal
  437. (defvar js2-GET_REF 67) ; *reference
  438. (defvar js2-SET_REF 68) ; *reference = something
  439. (defvar js2-DEL_REF 69) ; delete reference
  440. (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
  441. (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
  442. (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
  443. ;; XML support
  444. (defvar js2-DEFAULTNAMESPACE 73)
  445. (defvar js2-ESCXMLATTR 74)
  446. (defvar js2-ESCXMLTEXT 75)
  447. (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
  448. (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
  449. (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
  450. (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
  451. (defvar js2-first-bytecode js2-ENTERWITH)
  452. (defvar js2-last-bytecode js2-REF_NS_NAME)
  453. (defvar js2-TRY 80)
  454. (defvar js2-SEMI 81) ; semicolon
  455. (defvar js2-LB 82) ; left and right brackets
  456. (defvar js2-RB 83)
  457. (defvar js2-LC 84) ; left and right curly-braces
  458. (defvar js2-RC 85)
  459. (defvar js2-LP 86) ; left and right parens
  460. (defvar js2-RP 87)
  461. (defvar js2-COMMA 88) ; comma operator
  462. (defvar js2-ASSIGN 89) ; simple assignment (=)
  463. (defvar js2-ASSIGN_BITOR 90) ; |=
  464. (defvar js2-ASSIGN_BITXOR 91) ; ^=
  465. (defvar js2-ASSIGN_BITAND 92) ; &=
  466. (defvar js2-ASSIGN_LSH 93) ; <<=
  467. (defvar js2-ASSIGN_RSH 94) ; >>=
  468. (defvar js2-ASSIGN_URSH 95) ; >>>=
  469. (defvar js2-ASSIGN_ADD 96) ; +=
  470. (defvar js2-ASSIGN_SUB 97) ; -=
  471. (defvar js2-ASSIGN_MUL 98) ; *=
  472. (defvar js2-ASSIGN_DIV 99) ; /=
  473. (defvar js2-ASSIGN_MOD 100) ; %=
  474. (defvar js2-ASSIGN_EXPON 101) ; **=
  475. (defvar js2-ASSIGN_AND 102) ; &&=
  476. (defvar js2-ASSIGN_OR 103) ; ||=
  477. (defvar js2-ASSIGN_NULLISH 104) ; ??=
  478. (defvar js2-first-assign js2-ASSIGN)
  479. (defvar js2-last-assign js2-ASSIGN_NULLISH)
  480. (defvar js2-COLON 105)
  481. (defvar js2-OR 106) ; logical or (||)
  482. (defvar js2-AND 107) ; logical and (&&)
  483. (defvar js2-INC 108) ; increment/decrement (++ --)
  484. (defvar js2-DEC 109)
  485. (defvar js2-DOT 110) ; member operator (.)
  486. (defvar js2-FUNCTION 111) ; function keyword
  487. (defvar js2-EXPORT 112) ; export keyword
  488. (defvar js2-IMPORT 113) ; import keyword
  489. (defvar js2-IF 114) ; if keyword
  490. (defvar js2-ELSE 115) ; else keyword
  491. (defvar js2-SWITCH 116) ; switch keyword
  492. (defvar js2-CASE 117) ; case keyword
  493. (defvar js2-DEFAULT 118) ; default keyword
  494. (defvar js2-WHILE 119) ; while keyword
  495. (defvar js2-DO 120) ; do keyword
  496. (defvar js2-FOR 121) ; for keyword
  497. (defvar js2-BREAK 122) ; break keyword
  498. (defvar js2-CONTINUE 123) ; continue keyword
  499. (defvar js2-VAR 124) ; var keyword
  500. (defvar js2-WITH 125) ; with keyword
  501. (defvar js2-CATCH 126) ; catch keyword
  502. (defvar js2-FINALLY 127) ; finally keyword
  503. (defvar js2-VOID 128) ; void keyword
  504. (defvar js2-RESERVED 129) ; reserved keywords
  505. (defvar js2-EMPTY 130)
  506. ;; Types used for the parse tree - never returned by scanner.
  507. (defvar js2-BLOCK 131) ; statement block
  508. (defvar js2-LABEL 132) ; label
  509. (defvar js2-TARGET 133)
  510. (defvar js2-LOOP 134)
  511. (defvar js2-EXPR_VOID 135) ; expression statement in functions
  512. (defvar js2-EXPR_RESULT 136) ; expression statement in scripts
  513. (defvar js2-JSR 137)
  514. (defvar js2-SCRIPT 138) ; top-level node for entire script
  515. (defvar js2-TYPEOFNAME 139) ; for typeof(simple-name)
  516. (defvar js2-USE_STACK 140)
  517. (defvar js2-SETPROP_OP 141) ; x.y op= something
  518. (defvar js2-SETELEM_OP 142) ; x[y] op= something
  519. (defvar js2-LOCAL_BLOCK 143)
  520. (defvar js2-SET_REF_OP 144) ; *reference op= something
  521. ;; For XML support:
  522. (defvar js2-DOTDOT 145) ; member operator (..)
  523. (defvar js2-COLONCOLON 146) ; namespace::name
  524. (defvar js2-XML 147) ; XML type
  525. (defvar js2-DOTQUERY 148) ; .() -- e.g., x.emps.emp.(name == "terry")
  526. (defvar js2-XMLATTR 149) ; @
  527. (defvar js2-XMLEND 150)
  528. ;; Optimizer-only tokens
  529. (defvar js2-TO_OBJECT 151)
  530. (defvar js2-TO_DOUBLE 152)
  531. (defvar js2-GET 153) ; JS 1.5 get pseudo keyword
  532. (defvar js2-SET 154) ; JS 1.5 set pseudo keyword
  533. (defvar js2-LET 155) ; JS 1.7 let pseudo keyword
  534. (defvar js2-CONST 156)
  535. (defvar js2-SETCONST 157)
  536. (defvar js2-SETCONSTVAR 158)
  537. (defvar js2-ARRAYCOMP 159)
  538. (defvar js2-LETEXPR 160)
  539. (defvar js2-WITHEXPR 161)
  540. (defvar js2-DEBUGGER 162)
  541. (defvar js2-COMMENT 163)
  542. (defvar js2-TRIPLEDOT 164) ; for rest parameter
  543. (defvar js2-ARROW 165) ; function arrow (=>)
  544. (defvar js2-CLASS 166)
  545. (defvar js2-EXTENDS 167)
  546. (defvar js2-SUPER 168)
  547. (defvar js2-TEMPLATE_HEAD 169) ; part of template literal before substitution
  548. (defvar js2-NO_SUBS_TEMPLATE 170) ; template literal without substitutions
  549. (defvar js2-TAGGED_TEMPLATE 171) ; tagged template literal
  550. (defvar js2-AWAIT 172) ; await (pseudo keyword)
  551. (defvar js2-HOOK 173) ; conditional (?:)
  552. (defvar js2-OPTIONAL-CHAINING 174) ; optional chaining (?.prop obj?.[expr] func?.())
  553. (defvar js2-EXPON 175)
  554. (defvar js2-NULLISH-COALESCING 176) ; nullish coalescing (obj.value ?? obj.defaultValue ?? 0))
  555. (defconst js2-num-tokens (1+ js2-NULLISH-COALESCING))
  556. (defconst js2-debug-print-trees nil)
  557. ;; Rhino accepts any string or stream as input. Emacs character
  558. ;; processing works best in buffers, so we'll assume the input is a
  559. ;; buffer. JavaScript strings can be copied into temp buffers before
  560. ;; scanning them.
  561. ;; Buffer-local variables yield much cleaner code than using `defstruct'.
  562. ;; They're the Emacs equivalent of instance variables, more or less.
  563. (js2-deflocal js2-ts-dirty-line nil
  564. "Token stream buffer-local variable.
  565. Indicates stuff other than whitespace since start of line.")
  566. (js2-deflocal js2-ts-hit-eof nil
  567. "Token stream buffer-local variable.")
  568. ;; FIXME: Unused.
  569. (js2-deflocal js2-ts-line-start 0
  570. "Token stream buffer-local variable.")
  571. (js2-deflocal js2-ts-lineno 1
  572. "Token stream buffer-local variable.")
  573. ;; FIXME: Unused.
  574. (js2-deflocal js2-ts-line-end-char -1
  575. "Token stream buffer-local variable.")
  576. (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
  577. "Token stream buffer-local variable.
  578. Current scan position.")
  579. ;; FIXME: Unused.
  580. (js2-deflocal js2-ts-is-xml-attribute nil
  581. "Token stream buffer-local variable.")
  582. (js2-deflocal js2-ts-xml-is-tag-content nil
  583. "Token stream buffer-local variable.")
  584. (js2-deflocal js2-ts-xml-open-tags-count 0
  585. "Token stream buffer-local variable.")
  586. (js2-deflocal js2-ts-string-buffer nil
  587. "Token stream buffer-local variable.
  588. List of chars built up while scanning various tokens.")
  589. (cl-defstruct (js2-token
  590. (:constructor make-js2-token (beg)))
  591. "Value returned from the token stream."
  592. (type js2-EOF)
  593. (beg 1)
  594. (end -1)
  595. (string "")
  596. number
  597. number-base
  598. number-legacy-octal-p
  599. regexp-flags
  600. comment-type
  601. follows-eol-p)
  602. ;; Have to call `js2-init-scanner' to initialize the values.
  603. (js2-deflocal js2-ti-tokens nil)
  604. (js2-deflocal js2-ti-tokens-cursor nil)
  605. (js2-deflocal js2-ti-lookahead nil)
  606. (cl-defstruct (js2-ts-state
  607. (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
  608. (cursor js2-ts-cursor)
  609. (tokens (copy-sequence js2-ti-tokens))
  610. (tokens-cursor js2-ti-tokens-cursor)
  611. (lookahead js2-ti-lookahead))))
  612. lineno
  613. cursor
  614. tokens
  615. tokens-cursor
  616. lookahead)
  617. ;;; Parser variables
  618. (js2-deflocal js2-parsed-errors nil
  619. "List of errors produced during scanning/parsing.")
  620. (js2-deflocal js2-parsed-warnings nil
  621. "List of warnings produced during scanning/parsing.")
  622. (js2-deflocal js2-recover-from-parse-errors t
  623. "Non-nil to continue parsing after a syntax error.
  624. In recovery mode, the AST will be built in full, and any error
  625. nodes will be flagged with appropriate error information. If
  626. this flag is nil, a syntax error will result in an error being
  627. signaled.
  628. The variable is automatically buffer-local, because different
  629. modes that use the parser will need different settings.")
  630. (js2-deflocal js2-parse-hook nil
  631. "List of callbacks for receiving parsing progress.")
  632. (defvar js2-parse-finished-hook nil
  633. "List of callbacks to notify when parsing finishes.
  634. Not called if parsing was interrupted.")
  635. (js2-deflocal js2-is-eval-code nil
  636. "True if we're evaluating code in a string.
  637. If non-nil, the tokenizer will record the token text, and the AST nodes
  638. will record their source text. Off by default for IDE modes, since the
  639. text is available in the buffer.")
  640. (defvar js2-parse-ide-mode t
  641. "Non-nil if the parser is being used for `js2-mode'.
  642. If non-nil, the parser will set text properties for fontification
  643. and the syntax table. The value should be nil when using the
  644. parser as a frontend to an interpreter or byte compiler.")
  645. ;;; Parser instance variables (buffer-local vars for js2-parse)
  646. (defconst js2-ti-after-eol (lsh 1 16)
  647. "Flag: first token of the source line.")
  648. ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
  649. (js2-deflocal js2-compiler-generate-debug-info t)
  650. (js2-deflocal js2-compiler-use-dynamic-scope nil)
  651. (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
  652. (js2-deflocal js2-compiler-xml-available t)
  653. (js2-deflocal js2-compiler-optimization-level 0)
  654. (js2-deflocal js2-compiler-generating-source t)
  655. (js2-deflocal js2-compiler-strict-mode nil)
  656. (js2-deflocal js2-compiler-report-warning-as-error nil)
  657. (js2-deflocal js2-compiler-generate-observer-count nil)
  658. (js2-deflocal js2-compiler-activation-names nil)
  659. ;; SKIP: sourceURI
  660. ;; There's a compileFunction method in Context.java - may need it.
  661. (js2-deflocal js2-called-by-compile-function nil
  662. "True if `js2-parse' was called by `js2-compile-function'.
  663. Will only be used when we finish implementing the interpreter.")
  664. ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
  665. ;; SKIP: node factory - we're going to just call functions directly,
  666. ;; and eventually go to a unified AST format.
  667. (js2-deflocal js2-nesting-of-function 0)
  668. (js2-deflocal js2-recorded-identifiers nil
  669. "Tracks identifiers found during parsing.")
  670. (js2-deflocal js2-is-in-destructuring nil
  671. "True while parsing destructuring expression.")
  672. (js2-deflocal js2-in-use-strict-directive nil
  673. "True while inside a script or function under strict mode.")
  674. (defcustom js2-global-externs nil
  675. "A list of any extern names you'd like to consider always declared.
  676. This list is global and is used by all `js2-mode' files.
  677. You can create buffer-local externs list using `js2-additional-externs'."
  678. :type 'list
  679. :group 'js2-mode)
  680. (defcustom js2-include-browser-externs t
  681. "Non-nil to include browser externs in the master externs list.
  682. If you work on JavaScript files that are not intended for browsers,
  683. such as Mozilla Rhino server-side JavaScript, set this to nil.
  684. See `js2-additional-externs' for more information about externs."
  685. :type 'boolean
  686. :group 'js2-mode)
  687. (defcustom js2-include-rhino-externs nil
  688. "Non-nil to include Mozilla Rhino externs in the master externs list.
  689. See `js2-additional-externs' for more information about externs."
  690. :type 'boolean
  691. :group 'js2-mode)
  692. (defcustom js2-include-node-externs nil
  693. "Non-nil to include Node.js externs in the master externs list.
  694. See `js2-additional-externs' for more information about externs."
  695. :type 'boolean
  696. :group 'js2-mode)
  697. (js2-deflocal js2-additional-externs nil
  698. "A buffer-local list of additional external declarations.
  699. It is used to decide whether variables are considered undeclared
  700. for purposes of highlighting. See `js2-highlight-undeclared-vars'.
  701. Each entry is a Lisp string. The string should be the fully qualified
  702. name of an external entity. All externs should be added to this list,
  703. so that as js2-mode's processing improves it can take advantage of them.
  704. You may want to declare your externs in three ways.
  705. First, you can add externs that are valid for all your JavaScript files.
  706. You should probably do this by adding them to `js2-global-externs', which
  707. is a global list used for all js2-mode files.
  708. Next, you can add a function to `js2-init-hook' that adds additional
  709. externs appropriate for the specific file, perhaps based on its path.
  710. These should go in `js2-additional-externs', which is buffer-local.
  711. Third, you can use JSLint's global declaration, as long as
  712. `js2-include-jslint-globals' is non-nil, which see.
  713. Finally, you can add a function to `js2-post-parse-callbacks',
  714. which is called after parsing completes, and `js2-mode-ast' is bound to
  715. the root of the parse tree. At this stage you can set up an AST
  716. node visitor using `js2-visit-ast' and examine the parse tree
  717. for specific import patterns that may imply the existence of
  718. other externs, possibly tied to your build system. These should also
  719. be added to `js2-additional-externs'.
  720. Your post-parse callback may of course also use the simpler and
  721. faster (but perhaps less robust) approach of simply scanning the
  722. buffer text for your imports, using regular expressions.")
  723. (put 'js2-additional-externs 'safe-local-variable
  724. (lambda (val) (cl-every #'stringp val)))
  725. ;; SKIP: decompiler
  726. ;; SKIP: encoded-source
  727. ;;; The following variables are per-function and should be saved/restored
  728. ;;; during function parsing...
  729. (js2-deflocal js2-current-script-or-fn nil)
  730. (js2-deflocal js2-current-scope nil)
  731. (js2-deflocal js2-nesting-of-with 0)
  732. (js2-deflocal js2-label-set nil
  733. "An alist mapping label names to nodes.")
  734. (js2-deflocal js2-loop-set nil)
  735. (js2-deflocal js2-loop-and-switch-set nil)
  736. (js2-deflocal js2-has-return-value nil)
  737. (js2-deflocal js2-end-flags 0)
  738. ;;; ...end of per function variables
  739. ;; These flags enumerate the possible ways a statement/function can
  740. ;; terminate. These flags are used by endCheck() and by the Parser to
  741. ;; detect inconsistent return usage.
  742. ;;
  743. ;; END_UNREACHED is reserved for code paths that are assumed to always be
  744. ;; able to execute (example: throw, continue)
  745. ;;
  746. ;; END_DROPS_OFF indicates if the statement can transfer control to the
  747. ;; next one. Statement such as return dont. A compound statement may have
  748. ;; some branch that drops off control to the next statement.
  749. ;;
  750. ;; END_RETURNS indicates that the statement can return (without arguments)
  751. ;; END_RETURNS_VALUE indicates that the statement can return a value.
  752. ;;
  753. ;; A compound statement such as
  754. ;; if (condition) {
  755. ;; return value;
  756. ;; }
  757. ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
  758. (defconst js2-end-unreached #x0)
  759. (defconst js2-end-drops-off #x1)
  760. (defconst js2-end-returns #x2)
  761. (defconst js2-end-returns-value #x4)
  762. ;; Rhino awkwardly passes a statementLabel parameter to the
  763. ;; statementHelper() function, the main statement parser, which
  764. ;; is then used by quite a few of the sub-parsers. We just make
  765. ;; it a buffer-local variable and make sure it's cleaned up properly.
  766. (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
  767. ;; Similarly, Rhino passes an inForInit boolean through about half
  768. ;; the expression parsers. We use a dynamically-scoped variable,
  769. ;; which makes it easier to funcall the parsers individually without
  770. ;; worrying about whether they take the parameter or not.
  771. (js2-deflocal js2-in-for-init nil)
  772. (js2-deflocal js2-temp-name-counter 0)
  773. (js2-deflocal js2-parse-stmt-count 0)
  774. (defsubst js2-get-next-temp-name ()
  775. (format "$%d" (cl-incf js2-temp-name-counter)))
  776. (defvar js2-parse-interruptable-p t
  777. "Set this to nil to force parse to continue until finished.
  778. This will mostly be useful for interpreters.")
  779. (defvar js2-statements-per-pause 50
  780. "Pause after this many statements to check for user input.
  781. If user input is pending, stop the parse and discard the tree.
  782. This makes for a smoother user experience for large files.
  783. You may have to wait a second or two before the highlighting
  784. and error-reporting appear, but you can always type ahead if
  785. you wish. This appears to be more or less how Eclipse, IntelliJ
  786. and other editors work.")
  787. (js2-deflocal js2-record-comments t
  788. "Instructs the scanner to record comments in `js2-scanned-comments'.")
  789. (js2-deflocal js2-scanned-comments nil
  790. "List of all comments from the current parse.")
  791. (defcustom js2-mode-indent-inhibit-undo nil
  792. "Non-nil to disable collection of Undo information when indenting lines.
  793. Some users have requested this behavior. It's nil by default because
  794. other Emacs modes don't work this way."
  795. :type 'boolean
  796. :group 'js2-mode)
  797. (defcustom js2-mode-indent-ignore-first-tab nil
  798. "If non-nil, ignore first TAB keypress if we look indented properly.
  799. It's fairly common for users to navigate to an already-indented line
  800. and press TAB for reassurance that it's been indented. For this class
  801. of users, we want the first TAB press on a line to be ignored if the
  802. line is already indented to one of the precomputed alternatives.
  803. This behavior is only partly implemented. If you TAB-indent a line,
  804. navigate to another line, and then navigate back, it fails to clear
  805. the last-indented variable, so it thinks you've already hit TAB once,
  806. and performs the indent. A full solution would involve getting on the
  807. point-motion hooks for the entire buffer. If we come across another
  808. use cases that requires watching point motion, I'll consider doing it.
  809. If you set this variable to nil, then the TAB key will always change
  810. the indentation of the current line, if more than one alternative
  811. indentation spot exists."
  812. :type 'boolean
  813. :group 'js2-mode)
  814. (defvar js2-indent-hook nil
  815. "A hook for user-defined indentation rules.
  816. Functions on this hook should expect two arguments: (LIST INDEX)
  817. The LIST argument is the list of computed indentation points for
  818. the current line. INDEX is the list index of the indentation point
  819. that `js2-bounce-indent' plans to use. If INDEX is nil, then the
  820. indent function is not going to change the current line indentation.
  821. If a hook function on this list returns a non-nil value, then
  822. `js2-bounce-indent' assumes the hook function has performed its own
  823. indentation, and will do nothing. If all hook functions on the list
  824. return nil, then `js2-bounce-indent' will use its computed indentation
  825. and reindent the line.
  826. When hook functions on this hook list are called, the variable
  827. `js2-mode-ast' may or may not be set, depending on whether the
  828. parse tree is available. If the variable is nil, you can pass a
  829. callback to `js2-mode-wait-for-parse', and your callback will be
  830. called after the new parse tree is built. This can take some time
  831. in large files.")
  832. (defface js2-warning
  833. `((((class color) (background light))
  834. (:underline "orange"))
  835. (((class color) (background dark))
  836. (:underline "orange"))
  837. (t (:underline t)))
  838. "Face for JavaScript warnings."
  839. :group 'js2-mode)
  840. (defface js2-error
  841. `((((class color) (background light))
  842. (:foreground "red"))
  843. (((class color) (background dark))
  844. (:foreground "red"))
  845. (t (:foreground "red")))
  846. "Face for JavaScript errors."
  847. :group 'js2-mode)
  848. (defface js2-jsdoc-tag
  849. '((t :foreground "SlateGray"))
  850. "Face used to highlight @whatever tags in jsdoc comments."
  851. :group 'js2-mode)
  852. (defface js2-jsdoc-type
  853. '((t :foreground "SteelBlue"))
  854. "Face used to highlight {FooBar} types in jsdoc comments."
  855. :group 'js2-mode)
  856. (defface js2-jsdoc-value
  857. '((t :foreground "PeachPuff3"))
  858. "Face used to highlight tag values in jsdoc comments."
  859. :group 'js2-mode)
  860. (defface js2-function-param
  861. '((t :foreground "SeaGreen"))
  862. "Face used to highlight function parameters in javascript."
  863. :group 'js2-mode)
  864. (defface js2-function-call
  865. '((t :inherit default))
  866. "Face used to highlight function name in calls."
  867. :group 'js2-mode)
  868. (defface js2-object-property
  869. '((t :inherit default))
  870. "Face used to highlight named property in object literal."
  871. :group 'js2-mode)
  872. (defface js2-object-property-access
  873. '((t :inherit js2-object-property))
  874. "Face used to highlight property access with dot on an object."
  875. :group 'js2-mode)
  876. (defface js2-instance-member
  877. '((t :foreground "DarkOrchid"))
  878. "Face used to highlight instance variables in javascript.
  879. Not currently used."
  880. :group 'js2-mode)
  881. (defface js2-private-member
  882. '((t :foreground "PeachPuff3"))
  883. "Face used to highlight calls to private methods in javascript.
  884. Not currently used."
  885. :group 'js2-mode)
  886. (defface js2-private-function-call
  887. '((t :foreground "goldenrod"))
  888. "Face used to highlight calls to private functions in javascript.
  889. Not currently used."
  890. :group 'js2-mode)
  891. (defface js2-jsdoc-html-tag-name
  892. '((((class color) (min-colors 88) (background light))
  893. (:foreground "rosybrown"))
  894. (((class color) (min-colors 8) (background dark))
  895. (:foreground "yellow"))
  896. (((class color) (min-colors 8) (background light))
  897. (:foreground "magenta")))
  898. "Face used to highlight jsdoc html tag names"
  899. :group 'js2-mode)
  900. (defface js2-jsdoc-html-tag-delimiter
  901. '((((class color) (min-colors 88) (background light))
  902. (:foreground "dark khaki"))
  903. (((class color) (min-colors 8) (background dark))
  904. (:foreground "green"))
  905. (((class color) (min-colors 8) (background light))
  906. (:foreground "green")))
  907. "Face used to highlight brackets in jsdoc html tags."
  908. :group 'js2-mode)
  909. (defface js2-external-variable
  910. '((t :foreground "orange"))
  911. "Face used to highlight undeclared variable identifiers.")
  912. (defcustom js2-init-hook nil
  913. ;; FIXME: We don't really need this anymore.
  914. "List of functions to be called after `js2-mode' or
  915. `js2-minor-mode' has initialized all variables, before parsing
  916. the buffer for the first time."
  917. :type 'hook
  918. :group 'js2-mode
  919. :version "20130608")
  920. (defcustom js2-post-parse-callbacks nil
  921. "List of callback functions invoked after parsing finishes.
  922. Currently, the main use for this function is to add synthetic
  923. declarations to `js2-recorded-identifiers', which see."
  924. :type 'hook
  925. :group 'js2-mode)
  926. (defcustom js2-build-imenu-callbacks nil
  927. "List of functions called during Imenu index generation.
  928. It's a good place to add additional entries to it, using
  929. `js2-record-imenu-entry'."
  930. :type 'hook
  931. :group 'js2-mode)
  932. (defcustom js2-highlight-external-variables t
  933. "Non-nil to highlight undeclared variable identifiers.
  934. An undeclared variable is any variable not declared with var or let
  935. in the current scope or any lexically enclosing scope. If you use
  936. such a variable, then you are either expecting it to originate from
  937. another file, or you've got a potential bug."
  938. :type 'boolean
  939. :group 'js2-mode)
  940. (defcustom js2-warn-about-unused-function-arguments nil
  941. "Non-nil to treat function arguments like declared-but-unused variables."
  942. :type 'booleanp
  943. :group 'js2-mode)
  944. (defcustom js2-include-jslint-globals t
  945. "Non-nil to include the identifiers from JSLint global
  946. declaration (see http://www.jslint.com/help.html#global) in the
  947. buffer-local externs list. See `js2-additional-externs' for more
  948. information."
  949. :type 'boolean
  950. :group 'js2-mode)
  951. (defcustom js2-include-jslint-declaration-externs t
  952. "Non-nil to include the identifiers JSLint assumes to be there
  953. under certain declarations in the buffer-local externs list. See
  954. `js2-additional-externs' for more information."
  955. :type 'boolean
  956. :group 'js2-mode)
  957. (defvar js2-mode-map
  958. (let ((map (make-sparse-keymap)))
  959. (define-key map [remap indent-new-comment-line] #'js2-line-break)
  960. (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
  961. (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
  962. (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
  963. (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
  964. (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
  965. (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
  966. (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
  967. (define-key map [down-mouse-3] #'js2-down-mouse-3)
  968. (define-key map [remap js-find-symbol] #'js2-jump-to-definition)
  969. (define-key map [menu-bar javascript]
  970. (cons "JavaScript" (make-sparse-keymap "JavaScript")))
  971. (define-key map [menu-bar javascript customize-js2-mode]
  972. '(menu-item "Customize js2-mode" js2-mode-customize
  973. :help "Customize the behavior of this mode"))
  974. (define-key map [menu-bar javascript js2-force-refresh]
  975. '(menu-item "Force buffer refresh" js2-mode-reset
  976. :help "Re-parse the buffer from scratch"))
  977. (define-key map [menu-bar javascript separator-2]
  978. '("--"))
  979. (define-key map [menu-bar javascript next-error]
  980. '(menu-item "Next warning or error" next-error
  981. :enabled (and js2-mode-ast
  982. (or (js2-ast-root-errors js2-mode-ast)
  983. (js2-ast-root-warnings js2-mode-ast)))
  984. :help "Move to next warning or error"))
  985. (define-key map [menu-bar javascript display-errors]
  986. '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
  987. :visible (not js2-mode-show-parse-errors)
  988. :help "Turn on display of warnings and errors"))
  989. (define-key map [menu-bar javascript hide-errors]
  990. '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
  991. :visible js2-mode-show-parse-errors
  992. :help "Turn off display of warnings and errors"))
  993. (define-key map [menu-bar javascript separator-1]
  994. '("--"))
  995. (define-key map [menu-bar javascript js2-toggle-function]
  996. '(menu-item "Show/collapse element" js2-mode-toggle-element
  997. :help "Hide or show function body or comment"))
  998. (define-key map [menu-bar javascript show-comments]
  999. '(menu-item "Show block comments" js2-mode-toggle-hide-comments
  1000. :visible js2-mode-comments-hidden
  1001. :help "Expand all hidden block comments"))
  1002. (define-key map [menu-bar javascript hide-comments]
  1003. '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
  1004. :visible (not js2-mode-comments-hidden)
  1005. :help "Show block comments as /*...*/"))
  1006. (define-key map [menu-bar javascript show-all-functions]
  1007. '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
  1008. :visible js2-mode-functions-hidden
  1009. :help "Expand all hidden function bodies"))
  1010. (define-key map [menu-bar javascript hide-all-functions]
  1011. '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
  1012. :visible (not js2-mode-functions-hidden)
  1013. :help "Show {...} for all top-level function bodies"))
  1014. map)
  1015. "Keymap used in `js2-mode' buffers.")
  1016. (defcustom js2-bounce-indent-p nil
  1017. "Non-nil to bind `js2-indent-bounce' and `js2-indent-bounce-backward'.
  1018. They will augment the default indent-line behavior with cycling
  1019. among several computed alternatives. See the function
  1020. `js2-bounce-indent' for details. The above commands will be
  1021. bound to TAB and backtab."
  1022. :type 'boolean
  1023. :group 'js2-mode
  1024. :set (lambda (sym value)
  1025. (set-default sym value)
  1026. (let ((map js2-mode-map))
  1027. (if (not value)
  1028. (progn
  1029. (define-key map "\t" nil)
  1030. (define-key map (kbd "<backtab>") nil))
  1031. (define-key map "\t" #'js2-indent-bounce)
  1032. (define-key map (kbd "<backtab>") #'js2-indent-bounce-backward)))))
  1033. (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
  1034. (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
  1035. "Matches a //-comment line. Must be first non-whitespace on line.
  1036. First match-group is the leading whitespace.")
  1037. (defvar js2-mode-hook nil)
  1038. (js2-deflocal js2-mode-ast nil "Private variable.")
  1039. (js2-deflocal js2-mode-parse-timer nil "Private variable.")
  1040. (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
  1041. (js2-deflocal js2-mode-parsing nil "Private variable.")
  1042. (js2-deflocal js2-mode-node-overlay nil)
  1043. (defvar js2-mode-show-overlay js2-mode-dev-mode-p
  1044. "Debug: Non-nil to highlight AST nodes on mouse-down.")
  1045. (js2-deflocal js2-mode-fontifications nil "Private variable")
  1046. (js2-deflocal js2-mode-deferred-properties nil "Private variable")
  1047. (js2-deflocal js2-imenu-recorder nil "Private variable")
  1048. (js2-deflocal js2-imenu-function-map nil "Private variable")
  1049. (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
  1050. "Non-nil to emit status messages during parsing.")
  1051. (defvar js2-mode-change-syntax-p t
  1052. "Non-nil to set the syntax-table text property on certain literals.")
  1053. (defvar js2-mode-functions-hidden nil "Private variable.")
  1054. (defvar js2-mode-comments-hidden nil "Private variable.")
  1055. (defvar js2-mode-syntax-table
  1056. (let ((table (make-syntax-table)))
  1057. (c-populate-syntax-table table)
  1058. (modify-syntax-entry ?` "\"" table)
  1059. table)
  1060. "Syntax table used in `js2-mode' buffers.")
  1061. (defvar js2-mode-abbrev-table nil
  1062. "Abbrev table in use in `js2-mode' buffers.")
  1063. (define-abbrev-table 'js2-mode-abbrev-table ())
  1064. (defvar js2-mode-pending-parse-callbacks nil
  1065. "List of functions waiting to be notified that parse is finished.")
  1066. (defvar js2-mode-last-indented-line -1)
  1067. ;;; Localizable error and warning messages
  1068. ;; Messages are copied from Rhino's Messages.properties.
  1069. ;; Many of the Java-specific messages have been elided.
  1070. ;; Add any js2-specific ones at the end, so we can keep
  1071. ;; this file synced with changes to Rhino's.
  1072. (defvar js2-message-table
  1073. (make-hash-table :test 'equal :size 250)
  1074. "Contains localized messages for `js2-mode'.")
  1075. ;; TODO(stevey): construct this table at compile-time.
  1076. (defmacro js2-msg (key &rest strings)
  1077. `(puthash ,key (concat ,@strings)
  1078. js2-message-table))
  1079. (defun js2-get-msg (msg-key)
  1080. "Look up a localized message.
  1081. MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
  1082. the correct number of ARGS must be provided."
  1083. (let* ((key (if (listp msg-key) (car msg-key) msg-key))
  1084. (args (if (listp msg-key) (cdr msg-key)))
  1085. (msg (gethash key js2-message-table)))
  1086. (if msg
  1087. (apply #'format msg args)
  1088. key))) ; default to showing the key
  1089. (js2-msg "msg.dup.parms"
  1090. "Duplicate parameter name '%s'.")
  1091. (js2-msg "msg.too.big.jump"
  1092. "Program too complex: jump offset too big.")
  1093. (js2-msg "msg.too.big.index"
  1094. "Program too complex: internal index exceeds 64K limit.")
  1095. (js2-msg "msg.while.compiling.fn"
  1096. "Encountered code generation error while compiling function '%s': %s")
  1097. (js2-msg "msg.while.compiling.script"
  1098. "Encountered code generation error while compiling script: %s")
  1099. ;; Context
  1100. (js2-msg "msg.ctor.not.found"
  1101. "Constructor for '%s' not found.")
  1102. (js2-msg "msg.not.ctor"
  1103. "'%s' is not a constructor.")
  1104. ;; FunctionObject
  1105. (js2-msg "msg.varargs.ctor"
  1106. "Method or constructor '%s' must be static "
  1107. "with the signature (Context cx, Object[] args, "
  1108. "Function ctorObj, boolean inNewExpr) "
  1109. "to define a variable arguments constructor.")
  1110. (js2-msg "msg.varargs.fun"
  1111. "Method '%s' must be static with the signature "
  1112. "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
  1113. "to define a variable arguments function.")
  1114. (js2-msg "msg.incompat.call"
  1115. "Method '%s' called on incompatible object.")
  1116. (js2-msg "msg.bad.parms"
  1117. "Unsupported parameter type '%s' in method '%s'.")
  1118. (js2-msg "msg.bad.method.return"
  1119. "Unsupported return type '%s' in method '%s'.")
  1120. (js2-msg "msg.bad.ctor.return"
  1121. "Construction of objects of type '%s' is not supported.")
  1122. (js2-msg "msg.no.overload"
  1123. "Method '%s' occurs multiple times in class '%s'.")
  1124. (js2-msg "msg.method.not.found"
  1125. "Method '%s' not found in '%s'.")
  1126. ;; IRFactory
  1127. (js2-msg "msg.bad.for.in.lhs"
  1128. "Invalid left-hand side of for..in loop.")
  1129. (js2-msg "msg.mult.index"
  1130. "Only one variable allowed in for..in loop.")
  1131. (js2-msg "msg.bad.for.in.destruct"
  1132. "Left hand side of for..in loop must be an array of "
  1133. "length 2 to accept key/value pair.")
  1134. (js2-msg "msg.cant.convert"
  1135. "Can't convert to type '%s'.")
  1136. (js2-msg "msg.bad.assign.left"
  1137. "Invalid assignment left-hand side.")
  1138. (js2-msg "msg.bad.decr"
  1139. "Invalid decrement operand.")
  1140. (js2-msg "msg.bad.incr"
  1141. "Invalid increment operand.")
  1142. (js2-msg "msg.bad.yield"
  1143. "yield must be in a function.")
  1144. (js2-msg "msg.bad.await"
  1145. "await must be in async functions.")
  1146. ;; NativeGlobal
  1147. (js2-msg "msg.cant.call.indirect"
  1148. "Function '%s' must be called directly, and not by way of a "
  1149. "function of another name.")
  1150. (js2-msg "msg.eval.nonstring"
  1151. "Calling eval() with anything other than a primitive "
  1152. "string value will simply return the value. "
  1153. "Is this what you intended?")
  1154. (js2-msg "msg.eval.nonstring.strict"
  1155. "Calling eval() with anything other than a primitive "
  1156. "string value is not allowed in strict mode.")
  1157. (js2-msg "msg.bad.destruct.op"
  1158. "Invalid destructuring assignment operator")
  1159. ;; NativeCall
  1160. (js2-msg "msg.only.from.new"
  1161. "'%s' may only be invoked from a `new' expression.")
  1162. (js2-msg "msg.deprec.ctor"
  1163. "The '%s' constructor is deprecated.")
  1164. ;; NativeFunction
  1165. (js2-msg "msg.no.function.ref.found"
  1166. "no source found to decompile function reference %s")
  1167. (js2-msg "msg.arg.isnt.array"
  1168. "second argument to Function.prototype.apply must be an array")
  1169. ;; NativeGlobal
  1170. (js2-msg "msg.bad.esc.mask"
  1171. "invalid string escape mask")
  1172. ;; NativeRegExp
  1173. (js2-msg "msg.bad.quant"
  1174. "Invalid quantifier %s")
  1175. (js2-msg "msg.overlarge.backref"
  1176. "Overly large back reference %s")
  1177. (js2-msg "msg.overlarge.min"
  1178. "Overly large minimum %s")
  1179. (js2-msg "msg.overlarge.max"
  1180. "Overly large maximum %s")
  1181. (js2-msg "msg.zero.quant"
  1182. "Zero quantifier %s")
  1183. (js2-msg "msg.max.lt.min"
  1184. "Maximum %s less than minimum")
  1185. (js2-msg "msg.unterm.quant"
  1186. "Unterminated quantifier %s")
  1187. (js2-msg "msg.unterm.paren"
  1188. "Unterminated parenthetical %s")
  1189. (js2-msg "msg.unterm.class"
  1190. "Unterminated character class %s")
  1191. (js2-msg "msg.bad.range"
  1192. "Invalid range in character class.")
  1193. (js2-msg "msg.trail.backslash"
  1194. "Trailing \\ in regular expression.")
  1195. (js2-msg "msg.re.unmatched.right.paren"
  1196. "unmatched ) in regular expression.")
  1197. (js2-msg "msg.no.regexp"
  1198. "Regular expressions are not available.")
  1199. (js2-msg "msg.bad.backref"
  1200. "back-reference exceeds number of capturing parentheses.")
  1201. (js2-msg "msg.bad.regexp.compile"
  1202. "Only one argument may be specified if the first "
  1203. "argument to RegExp.prototype.compile is a RegExp object.")
  1204. ;; Parser
  1205. (js2-msg "msg.got.syntax.errors"
  1206. "Compilation produced %s syntax errors.")
  1207. (js2-msg "msg.var.redecl"
  1208. "Redeclaration of var %s.")
  1209. (js2-msg "msg.const.redecl"
  1210. "TypeError: redeclaration of const %s.")
  1211. (js2-msg "msg.let.redecl"
  1212. "TypeError: redeclaration of variable %s.")
  1213. (js2-msg "msg.parm.redecl"
  1214. "TypeError: redeclaration of formal parameter %s.")
  1215. (js2-msg "msg.fn.redecl"
  1216. "TypeError: redeclaration of function %s.")
  1217. (js2-msg "msg.let.decl.not.in.block"
  1218. "SyntaxError: let declaration not directly within block")
  1219. (js2-msg "msg.mod.import.decl.at.top.level"
  1220. "SyntaxError: import declarations may only appear at the top level")
  1221. (js2-msg "msg.mod.as.after.reserved.word"
  1222. "SyntaxError: missing keyword 'as' after reserved word %s")
  1223. (js2-msg "msg.mod.rc.after.import.spec.list"
  1224. "SyntaxError: missing '}' after module specifier list")
  1225. (js2-msg "msg.mod.from.after.import.spec.set"
  1226. "SyntaxError: missing keyword 'from' after import specifier set")
  1227. (js2-msg "msg.mod.declaration.after.import"
  1228. "SyntaxError: missing declaration after 'import' keyword")
  1229. (js2-msg "msg.mod.spec.after.from"
  1230. "SyntaxError: missing module specifier after 'from' keyword")
  1231. (js2-msg "msg.mod.export.decl.at.top.level"
  1232. "SyntaxError: export declarations may only appear at top level")
  1233. (js2-msg "msg.mod.rc.after.export.spec.list"
  1234. "SyntaxError: missing '}' after export specifier list")
  1235. ;; NodeTransformer
  1236. (js2-msg "msg.dup.label"
  1237. "duplicated label")
  1238. (js2-msg "msg.undef.label"
  1239. "undefined label")
  1240. (js2-msg "msg.bad.break"
  1241. "unlabelled break must be inside loop or switch")
  1242. (js2-msg "msg.continue.outside"
  1243. "continue must be inside loop")
  1244. (js2-msg "msg.continue.nonloop"
  1245. "continue can only use labels of iteration statements")
  1246. (js2-msg "msg.bad.throw.eol"
  1247. "Line terminator is not allowed between the throw "
  1248. "keyword and throw expression.")
  1249. (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
  1250. "function statement requires a name")
  1251. (js2-msg "msg.no.paren.parms"
  1252. "missing ( before function parameters.")
  1253. (js2-msg "msg.no.parm"
  1254. "missing formal parameter")
  1255. (js2-msg "msg.no.paren.after.parms"
  1256. "missing ) after formal parameters")
  1257. (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
  1258. "parameter without default follows parameter with default")
  1259. (js2-msg "msg.param.after.rest" ; added by js2-mode
  1260. "parameter after rest parameter")
  1261. (js2-msg "msg.bad.arrow.args" ; added by js2-mode
  1262. "invalid arrow-function arguments (parentheses around the arrow-function may help)")
  1263. (js2-msg "msg.no.brace.body"
  1264. "missing '{' before function body")
  1265. (js2-msg "msg.no.brace.after.body"
  1266. "missing } after function body")
  1267. (js2-msg "msg.no.paren.cond"
  1268. "missing ( before condition")
  1269. (js2-msg "msg.no.paren.after.cond"
  1270. "missing ) after condition")
  1271. (js2-msg "msg.no.semi.stmt"
  1272. "missing ; before statement")
  1273. (js2-msg "msg.missing.semi"
  1274. "missing ; after statement")
  1275. (js2-msg "msg.no.name.after.dot"
  1276. "missing name after . operator")
  1277. (js2-msg "msg.no.name.after.coloncolon"
  1278. "missing name after :: operator")
  1279. (js2-msg "msg.no.name.after.dotdot"
  1280. "missing name after .. operator")
  1281. (js2-msg "msg.no.name.after.xmlAttr"
  1282. "missing name after .@")
  1283. (js2-msg "msg.no.bracket.index"
  1284. "missing ] in index expression")
  1285. (js2-msg "msg.no.paren.switch"
  1286. "missing ( before switch expression")
  1287. (js2-msg "msg.no.paren.after.switch"
  1288. "missing ) after switch expression")
  1289. (js2-msg "msg.no.brace.switch"
  1290. "missing '{' before switch body")
  1291. (js2-msg "msg.bad.switch"
  1292. "invalid switch statement")
  1293. (js2-msg "msg.no.colon.case"
  1294. "missing : after case expression")
  1295. (js2-msg "msg.double.switch.default"
  1296. "double default label in the switch statement")
  1297. (js2-msg "msg.no.while.do"
  1298. "missing while after do-loop body")
  1299. (js2-msg "msg.no.paren.for"
  1300. "missing ( after for")
  1301. (js2-msg "msg.no.semi.for"
  1302. "missing ; after for-loop initializer")
  1303. (js2-msg "msg.no.semi.for.cond"
  1304. "missing ; after for-loop condition")
  1305. (js2-msg "msg.in.after.for.name"
  1306. "missing in or of after for")
  1307. (js2-msg "msg.no.paren.for.ctrl"
  1308. "missing ) after for-loop control")
  1309. (js2-msg "msg.no.paren.with"
  1310. "missing ( before with-statement object")
  1311. (js2-msg "msg.no.paren.after.with"
  1312. "missing ) after with-statement object")
  1313. (js2-msg "msg.no.with.strict"
  1314. "with statements not allowed in strict mode")
  1315. (js2-msg "msg.no.paren.after.let"
  1316. "missing ( after let")
  1317. (js2-msg "msg.no.paren.let"
  1318. "missing ) after variable list")
  1319. (js2-msg "msg.no.curly.let"
  1320. "missing } after let statement")
  1321. (js2-msg "msg.bad.return"
  1322. "invalid return")
  1323. (js2-msg "msg.no.brace.block"
  1324. "missing } in compound statement")
  1325. (js2-msg "msg.bad.label"
  1326. "invalid label")
  1327. (js2-msg "msg.bad.var"
  1328. "missing variable name")
  1329. (js2-msg "msg.bad.var.init"
  1330. "invalid variable initialization")
  1331. (js2-msg "msg.no.colon.cond"
  1332. "missing : in conditional expression")
  1333. (js2-msg "msg.bad.optional.chaining"
  1334. "missing property name or [ or ( after optional chaining operator")
  1335. (js2-msg "msg.no.paren.arg"
  1336. "missing ) after argument list")
  1337. (js2-msg "msg.no.bracket.arg"
  1338. "missing ] after element list")
  1339. (js2-msg "msg.bad.prop"
  1340. "invalid property id")
  1341. (js2-msg "msg.no.colon.prop"
  1342. "missing : after property id")
  1343. (js2-msg "msg.no.brace.prop"
  1344. "missing } after property list")
  1345. (js2-msg "msg.no.paren"
  1346. "missing ) in parenthetical")
  1347. (js2-msg "msg.reserved.id"
  1348. "'%s' is a reserved identifier")
  1349. (js2-msg "msg.no.paren.catch"
  1350. "missing ( before catch-block condition")
  1351. (js2-msg "msg.bad.catchcond"
  1352. "invalid catch block condition")
  1353. (js2-msg "msg.catch.unreachable"
  1354. "any catch clauses following an unqualified catch are unreachable")
  1355. (js2-msg "msg.no.brace.try"
  1356. "missing '{' before try block")
  1357. (js2-msg "msg.no.brace.catchblock"
  1358. "missing '{' before catch-block body")
  1359. (js2-msg "msg.try.no.catchfinally"
  1360. "'try' without 'catch' or 'finally'")
  1361. (js2-msg "msg.no.return.value"
  1362. "function %s does not always return a value")
  1363. (js2-msg "msg.anon.no.return.value"
  1364. "anonymous function does not always return a value")
  1365. (js2-msg "msg.return.inconsistent"
  1366. "return statement is inconsistent with previous usage")
  1367. (js2-msg "msg.generator.returns"
  1368. "TypeError: legacy generator function '%s' returns a value")
  1369. (js2-msg "msg.anon.generator.returns"
  1370. "TypeError: anonymous legacy generator function returns a value")
  1371. (js2-msg "msg.syntax"
  1372. "syntax error")
  1373. (js2-msg "msg.unexpected.eof"
  1374. "Unexpected end of file")
  1375. (js2-msg "msg.XML.bad.form"
  1376. "illegally formed XML syntax")
  1377. (js2-msg "msg.XML.not.available"
  1378. "XML runtime not available")
  1379. (js2-msg "msg.too.deep.parser.recursion"
  1380. "Too deep recursion while parsing")
  1381. (js2-msg "msg.no.side.effects"
  1382. "Code has no side effects")
  1383. (js2-msg "msg.extra.trailing.comma"
  1384. "Trailing comma is not supported in some browsers")
  1385. (js2-msg "msg.array.trailing.comma"
  1386. "Trailing comma yields different behavior across browsers")
  1387. (js2-msg "msg.equal.as.assign"
  1388. (concat "Test for equality (==) mistyped as assignment (=)?"
  1389. " (parenthesize to suppress warning)"))
  1390. (js2-msg "msg.var.hides.arg"
  1391. "Variable %s hides argument")
  1392. (js2-msg "msg.destruct.assign.no.init"
  1393. "Missing = in destructuring declaration")
  1394. (js2-msg "msg.init.no.destruct"
  1395. "Binding initializer not in destructuring assignment")
  1396. (js2-msg "msg.no.octal.strict"
  1397. "Octal numbers prohibited in strict mode.")
  1398. (js2-msg "msg.dup.obj.lit.prop.strict"
  1399. "Property '%s' already defined in this object literal.")
  1400. (js2-msg "msg.dup.param.strict"
  1401. "Parameter '%s' already declared in this function.")
  1402. (js2-msg "msg.bad.id.strict"
  1403. "'%s' is not a valid identifier for this use in strict mode.")
  1404. ;; ScriptRuntime
  1405. (js2-msg "msg.no.properties"
  1406. "%s has no properties.")
  1407. (js2-msg "msg.invalid.iterator"
  1408. "Invalid iterator value")
  1409. (js2-msg "msg.iterator.primitive"
  1410. "__iterator__ returned a primitive value")
  1411. (js2-msg "msg.assn.create.strict"
  1412. "Assignment to undeclared variable %s")
  1413. (js2-msg "msg.undeclared.variable" ; added by js2-mode
  1414. "Undeclared variable or function '%s'")
  1415. (js2-msg "msg.unused.variable" ; added by js2-mode
  1416. "Unused variable or function '%s'")
  1417. (js2-msg "msg.uninitialized.variable" ; added by js2-mode
  1418. "Variable '%s' referenced but never initialized")
  1419. (js2-msg "msg.ref.undefined.prop"
  1420. "Reference to undefined property '%s'")
  1421. (js2-msg "msg.prop.not.found"
  1422. "Property %s not found.")
  1423. (js2-msg "msg.invalid.type"
  1424. "Invalid JavaScript value of type %s")
  1425. (js2-msg "msg.primitive.expected"
  1426. "Primitive type expected (had %s instead)")
  1427. (js2-msg "msg.namespace.expected"
  1428. "Namespace object expected to left of :: (found %s instead)")
  1429. (js2-msg "msg.null.to.object"
  1430. "Cannot convert null to an object.")
  1431. (js2-msg "msg.undef.to.object"
  1432. "Cannot convert undefined to an object.")
  1433. (js2-msg "msg.cyclic.value"
  1434. "Cyclic %s value not allowed.")
  1435. (js2-msg "msg.is.not.defined"
  1436. "'%s' is not defined.")
  1437. (js2-msg "msg.undef.prop.read"
  1438. "Cannot read property '%s' from %s")
  1439. (js2-msg "msg.undef.prop.write"
  1440. "Cannot set property '%s' of %s to '%s'")
  1441. (js2-msg "msg.undef.prop.delete"
  1442. "Cannot delete property '%s' of %s")
  1443. (js2-msg "msg.undef.method.call"
  1444. "Cannot call method '%s' of %s")
  1445. (js2-msg "msg.undef.with"
  1446. "Cannot apply 'with' to %s")
  1447. (js2-msg "msg.isnt.function"
  1448. "%s is not a function, it is %s.")
  1449. (js2-msg "msg.isnt.function.in"
  1450. "Cannot call property %s in object %s. "
  1451. "It is not a function, it is '%s'.")
  1452. (js2-msg "msg.function.not.found"
  1453. "Cannot find function %s.")
  1454. (js2-msg "msg.function.not.found.in"
  1455. "Cannot find function %s in object %s.")
  1456. (js2-msg "msg.isnt.xml.object"
  1457. "%s is not an xml object.")
  1458. (js2-msg "msg.no.ref.to.get"
  1459. "%s is not a reference to read reference value.")
  1460. (js2-msg "msg.no.ref.to.set"
  1461. "%s is not a reference to set reference value to %s.")
  1462. (js2-msg "msg.no.ref.from.function"
  1463. "Function %s can not be used as the left-hand "
  1464. "side of assignment or as an operand of ++ or -- operator.")
  1465. (js2-msg "msg.bad.default.value"
  1466. "Object's getDefaultValue() method returned an object.")
  1467. (js2-msg "msg.instanceof.not.object"
  1468. "Can't use instanceof on a non-object.")
  1469. (js2-msg "msg.instanceof.bad.prototype"
  1470. "'prototype' property of %s is not an object.")
  1471. (js2-msg "msg.bad.radix"
  1472. "illegal radix %s.")
  1473. ;; ScriptableObject
  1474. (js2-msg "msg.default.value"
  1475. "Cannot find default value for object.")
  1476. (js2-msg "msg.zero.arg.ctor"
  1477. "Cannot load class '%s' which has no zero-parameter constructor.")
  1478. (js2-msg "msg.ctor.multiple.parms"
  1479. "Can't define constructor or class %s since more than "
  1480. "one constructor has multiple parameters.")
  1481. (js2-msg "msg.extend.scriptable"
  1482. "%s must extend ScriptableObject in order to define property %s.")
  1483. (js2-msg "msg.bad.getter.parms"
  1484. "In order to define a property, getter %s must have zero "
  1485. "parameters or a single ScriptableObject parameter.")
  1486. (js2-msg "msg.obj.getter.parms"
  1487. "Expected static or delegated getter %s to take "
  1488. "a ScriptableObject parameter.")
  1489. (js2-msg "msg.getter.static"
  1490. "Getter and setter must both be static or neither be static.")
  1491. (js2-msg "msg.setter.return"
  1492. "Setter must have void return type: %s")
  1493. (js2-msg "msg.setter2.parms"
  1494. "Two-parameter setter must take a ScriptableObject as "
  1495. "its first parameter.")
  1496. (js2-msg "msg.setter1.parms"
  1497. "Expected single parameter setter for %s")
  1498. (js2-msg "msg.setter2.expected"
  1499. "Expected static or delegated setter %s to take two parameters.")
  1500. (js2-msg "msg.setter.parms"
  1501. "Expected either one or two parameters for setter.")
  1502. (js2-msg "msg.setter.bad.type"
  1503. "Unsupported parameter type '%s' in setter '%s'.")
  1504. (js2-msg "msg.add.sealed"
  1505. "Cannot add a property to a sealed object: %s.")
  1506. (js2-msg "msg.remove.sealed"
  1507. "Cannot remove a property from a sealed object: %s.")
  1508. (js2-msg "msg.modify.sealed"
  1509. "Cannot modify a property of a sealed object: %s.")
  1510. (js2-msg "msg.modify.readonly"
  1511. "Cannot modify readonly property: %s.")
  1512. ;; TokenStream
  1513. (js2-msg "msg.missing.exponent"
  1514. "missing exponent")
  1515. (js2-msg "msg.caught.nfe"
  1516. "number format error")
  1517. (js2-msg "msg.unterminated.string.lit"
  1518. "unterminated string literal")
  1519. (js2-msg "msg.unterminated.comment"
  1520. "unterminated comment")
  1521. (js2-msg "msg.unterminated.re.lit"
  1522. "unterminated regular expression literal")
  1523. (js2-msg "msg.invalid.re.flag"
  1524. "invalid flag after regular expression")
  1525. (js2-msg "msg.no.re.input.for"
  1526. "no input for %s")
  1527. (js2-msg "msg.illegal.character"
  1528. "illegal character")
  1529. (js2-msg "msg.invalid.escape"
  1530. "invalid Unicode escape sequence")
  1531. (js2-msg "msg.bad.namespace"
  1532. "not a valid default namespace statement. "
  1533. "Syntax is: default xml namespace = EXPRESSION;")
  1534. ;; TokensStream warnings
  1535. (js2-msg "msg.bad.octal.literal"
  1536. "illegal octal literal digit %s; "
  1537. "interpreting it as a decimal digit")
  1538. (js2-msg "msg.missing.hex.digits"
  1539. "missing hexadecimal digits after '0x'")
  1540. (js2-msg "msg.missing.binary.digits"
  1541. "missing binary digits after '0b'")
  1542. (js2-msg "msg.missing.octal.digits"
  1543. "missing octal digits after '0o'")
  1544. (js2-msg "msg.script.is.not.constructor"
  1545. "Script objects are not constructors.")
  1546. ;; Arrays
  1547. (js2-msg "msg.arraylength.bad"
  1548. "Inappropriate array length.")
  1549. ;; Arrays
  1550. (js2-msg "msg.arraylength.too.big"
  1551. "Array length %s exceeds supported capacity limit.")
  1552. ;; URI
  1553. (js2-msg "msg.bad.uri"
  1554. "Malformed URI sequence.")
  1555. ;; Number
  1556. (js2-msg "msg.bad.precision"
  1557. "Precision %s out of range.")
  1558. ;; NativeGenerator
  1559. (js2-msg "msg.send.newborn"
  1560. "Attempt to send value to newborn generator")
  1561. (js2-msg "msg.already.exec.gen"
  1562. "Already executing generator")
  1563. (js2-msg "msg.StopIteration.invalid"
  1564. "StopIteration may not be changed to an arbitrary object.")
  1565. ;; Interpreter
  1566. (js2-msg "msg.yield.closing"
  1567. "Yield from closing generator")
  1568. ;; Classes
  1569. (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
  1570. "class statement requires a name")
  1571. (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
  1572. "unexpected ',' between class properties")
  1573. (js2-msg "msg.unexpected.static" ; added by js2-mode
  1574. "unexpected 'static'")
  1575. (js2-msg "msg.missing.extends" ; added by js2-mode
  1576. "name is required after extends")
  1577. (js2-msg "msg.no.brace.class" ; added by js2-mode
  1578. "missing '{' before class body")
  1579. (js2-msg "msg.missing.computed.rb" ; added by js2-mode
  1580. "missing ']' after computed property expression")
  1581. ;;; Tokens Buffer
  1582. (defconst js2-ti-max-lookahead 2)
  1583. (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
  1584. (defun js2-new-token (offset)
  1585. (let ((token (make-js2-token (+ offset js2-ts-cursor))))
  1586. (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
  1587. (aset js2-ti-tokens js2-ti-tokens-cursor token)
  1588. token))
  1589. (defsubst js2-current-token ()
  1590. (aref js2-ti-tokens js2-ti-tokens-cursor))
  1591. (defsubst js2-current-token-string ()
  1592. (js2-token-string (js2-current-token)))
  1593. (defsubst js2-current-token-type ()
  1594. (js2-token-type (js2-current-token)))
  1595. (defsubst js2-current-token-beg ()
  1596. (js2-token-beg (js2-current-token)))
  1597. (defsubst js2-current-token-end ()
  1598. (js2-token-end (js2-current-token)))
  1599. (defun js2-current-token-len ()
  1600. (let ((token (js2-current-token)))
  1601. (- (js2-token-end token)
  1602. (js2-token-beg token))))
  1603. (defun js2-ts-seek (state)
  1604. (setq js2-ts-lineno (js2-ts-state-lineno state)
  1605. js2-ts-cursor (js2-ts-state-cursor state)
  1606. js2-ti-tokens (js2-ts-state-tokens state)
  1607. js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
  1608. js2-ti-lookahead (js2-ts-state-lookahead state)))
  1609. ;;; Utilities
  1610. (defun js2-delete-if (predicate list)
  1611. "Remove all items satisfying PREDICATE in LIST."
  1612. (cl-loop for item in list
  1613. if (not (funcall predicate item))
  1614. collect item))
  1615. (defun js2-position (element list)
  1616. "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
  1617. Returns nil if element is not found in the list."
  1618. (let ((count 0)
  1619. found)
  1620. (while (and list (not found))
  1621. (if (eq element (car list))
  1622. (setq found t)
  1623. (setq count (1+ count)
  1624. list (cdr list))))
  1625. (if found count)))
  1626. (defun js2-find-if (predicate list)
  1627. "Find first item satisfying PREDICATE in LIST."
  1628. (let (result)
  1629. (while (and list (not result))
  1630. (if (funcall predicate (car list))
  1631. (setq result (car list)))
  1632. (setq list (cdr list)))
  1633. result))
  1634. (defmacro js2-time (form)
  1635. "Evaluate FORM, discard result, and return elapsed time in sec."
  1636. (declare (debug t))
  1637. (let ((beg (make-symbol "--js2-time-beg--")))
  1638. `(let ((,beg (current-time)))
  1639. ,form
  1640. (/ (truncate (* (- (float-time (current-time))
  1641. (float-time ,beg))
  1642. 10000))
  1643. 10000.0))))
  1644. (defsubst js2-same-line (pos)
  1645. "Return t if POS is on the same line as current point."
  1646. (and (>= pos (point-at-bol))
  1647. (<= pos (point-at-eol))))
  1648. (defun js2-code-bug ()
  1649. "Signal an error when we encounter an unexpected code path."
  1650. (error "failed assertion"))
  1651. (defsubst js2-record-text-property (beg end prop value)
  1652. "Record a text property to set when parsing finishes."
  1653. (push (list beg end prop value) js2-mode-deferred-properties))
  1654. ;; I'd like to associate errors with nodes, but for now the
  1655. ;; easiest thing to do is get the context info from the last token.
  1656. (defun js2-record-parse-error (msg &optional arg pos len)
  1657. (push (list (list msg arg)
  1658. (or pos (js2-current-token-beg))
  1659. (or len (js2-current-token-len)))
  1660. js2-parsed-errors))
  1661. (defun js2-report-error (msg &optional msg-arg pos len)
  1662. "Signal a syntax error or record a parse error."
  1663. (if js2-recover-from-parse-errors
  1664. (js2-record-parse-error msg msg-arg pos len)
  1665. (signal 'js2-syntax-error
  1666. (list msg
  1667. js2-ts-lineno
  1668. (save-excursion
  1669. (goto-char js2-ts-cursor)
  1670. (current-column))
  1671. js2-ts-hit-eof))))
  1672. (defun js2-report-warning (msg &optional msg-arg pos len face)
  1673. (if js2-compiler-report-warning-as-error
  1674. (js2-report-error msg msg-arg pos len)
  1675. (push (list (list msg msg-arg)
  1676. (or pos (js2-current-token-beg))
  1677. (or len (js2-current-token-len))
  1678. face)
  1679. js2-parsed-warnings)))
  1680. (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
  1681. (if js2-compiler-strict-mode
  1682. (js2-report-warning msg-id msg-arg beg
  1683. (and beg end (- end beg)))))
  1684. (put 'js2-syntax-error 'error-conditions
  1685. '(error syntax-error js2-syntax-error))
  1686. (put 'js2-syntax-error 'error-message "Syntax error")
  1687. (put 'js2-parse-error 'error-conditions
  1688. '(error parse-error js2-parse-error))
  1689. (put 'js2-parse-error 'error-message "Parse error")
  1690. (defmacro js2-clear-flag (flags flag)
  1691. `(setq ,flags (logand ,flags (lognot ,flag))))
  1692. (defmacro js2-set-flag (flags flag)
  1693. "Logical-or FLAG into FLAGS."
  1694. `(setq ,flags (logior ,flags ,flag)))
  1695. (defsubst js2-flag-set-p (flags flag)
  1696. (/= 0 (logand flags flag)))
  1697. (defsubst js2-flag-not-set-p (flags flag)
  1698. (zerop (logand flags flag)))
  1699. ;;; AST struct and function definitions
  1700. ;; flags for ast node property 'member-type (used for e4x operators)
  1701. (defvar js2-property-flag #x1 "Property access: element is valid name.")
  1702. (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
  1703. (defvar js2-descendants-flag #x4 "x..y or x..@i.")
  1704. (defsubst js2-relpos (pos anchor)
  1705. "Convert POS to be relative to ANCHOR.
  1706. If POS is nil, returns nil."
  1707. (and pos (- pos anchor)))
  1708. (defun js2-make-pad (indent)
  1709. (if (zerop indent)
  1710. ""
  1711. (make-string (* indent js2-basic-offset) ? )))
  1712. (defun js2-visit-ast (node callback)
  1713. "Visit every node in ast NODE with visitor CALLBACK.
  1714. CALLBACK is a function that takes two arguments: (NODE END-P). It is
  1715. called twice: once to visit the node, and again after all the node's
  1716. children have been processed. The END-P argument is nil on the first
  1717. call and non-nil on the second call. The return value of the callback
  1718. affects the traversal: if non-nil, the children of NODE are processed.
  1719. If the callback returns nil, or if the node has no children, then the
  1720. callback is called immediately with a non-nil END-P argument.
  1721. The node traversal is approximately lexical-order, although there
  1722. are currently no guarantees around this."
  1723. (when node
  1724. (let ((vfunc (get (aref node 0) 'js2-visitor)))
  1725. ;; visit the node
  1726. (when (funcall callback node nil)
  1727. ;; visit the kids
  1728. (cond
  1729. ((eq vfunc 'js2-visit-none)
  1730. nil) ; don't even bother calling it
  1731. ;; Each AST node type has to define a `js2-visitor' function
  1732. ;; that takes a node and a callback, and calls `js2-visit-ast'
  1733. ;; on each child of the node.
  1734. (vfunc
  1735. (funcall vfunc node callback))
  1736. (t
  1737. (error "%s does not define a visitor-traversal function"
  1738. (aref node 0)))))
  1739. ;; call the end-visit
  1740. (funcall callback node t))))
  1741. (cl-defstruct (js2-node
  1742. (:constructor nil)) ; abstract
  1743. "Base AST node type."
  1744. (type -1) ; token type
  1745. (pos -1) ; start position of this AST node in parsed input
  1746. (len 1) ; num characters spanned by the node
  1747. props ; optional node property list (an alist)
  1748. parent) ; link to parent node; null for root
  1749. (defsubst js2-node-get-prop (node prop &optional default)
  1750. (or (cadr (assoc prop (js2-node-props node))) default))
  1751. (defsubst js2-node-set-prop (node prop value)
  1752. (setf (js2-node-props node)
  1753. (cons (list prop value) (js2-node-props node))))
  1754. (defun js2-fixup-starts (n nodes)
  1755. "Adjust the start positions of NODES to be relative to N.
  1756. Any node in the list may be nil, for convenience."
  1757. (dolist (node nodes)
  1758. (when node
  1759. (setf (js2-node-pos node) (- (js2-node-pos node)
  1760. (js2-node-pos n))))))
  1761. (defun js2-node-add-children (parent &rest nodes)
  1762. "Set parent node of NODES to PARENT, and return PARENT.
  1763. Does nothing if we're not recording parent links.
  1764. If any given node in NODES is nil, doesn't record that link."
  1765. (js2-fixup-starts parent nodes)
  1766. (dolist (node nodes)
  1767. (and node
  1768. (setf (js2-node-parent node) parent))))
  1769. ;; Non-recursive since it's called a frightening number of times.
  1770. (defun js2-node-abs-pos (n)
  1771. (let ((pos (js2-node-pos n)))
  1772. (while (setq n (js2-node-parent n))
  1773. (setq pos (+ pos (js2-node-pos n))))
  1774. pos))
  1775. (defsubst js2-node-abs-end (n)
  1776. "Return absolute buffer position of end of N."
  1777. (+ (js2-node-abs-pos n) (js2-node-len n)))
  1778. (defun js2--struct-put (name key value)
  1779. (put name key value)
  1780. (put (intern (format "cl-struct-%s" name)) key value))
  1781. ;; It's important to make sure block nodes have a Lisp list for the
  1782. ;; child nodes, to limit printing recursion depth in an AST that
  1783. ;; otherwise consists of defstruct vectors. Emacs will crash printing
  1784. ;; a sufficiently large vector tree.
  1785. (cl-defstruct (js2-block-node
  1786. (:include js2-node)
  1787. (:constructor make-js2-block-node (&key (type js2-BLOCK)
  1788. (pos (js2-current-token-beg))
  1789. len
  1790. props
  1791. kids)))
  1792. "A block of statements."
  1793. kids) ; a Lisp list of the child statement nodes
  1794. (js2--struct-put 'js2-block-node 'js2-visitor 'js2-visit-block)
  1795. (js2--struct-put 'js2-block-node 'js2-printer 'js2-print-block)
  1796. (defun js2-visit-block (ast callback)
  1797. "Visit the `js2-block-node' children of AST."
  1798. (dolist (kid (js2-block-node-kids ast))
  1799. (js2-visit-ast kid callback)))
  1800. (defun js2-print-block (n i)
  1801. (let ((pad (js2-make-pad i)))
  1802. (insert pad "{\n")
  1803. (dolist (kid (js2-block-node-kids n))
  1804. (js2-print-ast kid (1+ i)))
  1805. (insert pad "}")))
  1806. (cl-defstruct (js2-scope
  1807. (:include js2-block-node)
  1808. (:constructor make-js2-scope (&key (type js2-BLOCK)
  1809. (pos (js2-current-token-beg))
  1810. len
  1811. kids)))
  1812. ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
  1813. ;; I don't have one of those handy, so I'll use an alist for now.
  1814. ;; It's as fast as an emacs hashtable for up to about 50 elements,
  1815. ;; and is much lighter-weight to construct (both CPU and mem).
  1816. ;; The keys are interned strings (symbols) for faster lookup.
  1817. ;; Should switch to hybrid alist/hashtable eventually.
  1818. symbol-table ; an alist of (symbol . js2-symbol)
  1819. parent-scope ; a `js2-scope'
  1820. top) ; top-level `js2-scope' (script/function)
  1821. (js2--struct-put 'js2-scope 'js2-visitor 'js2-visit-block)
  1822. (js2--struct-put 'js2-scope 'js2-printer 'js2-print-none)
  1823. (defun js2-node-get-enclosing-scope (node)
  1824. "Return the innermost `js2-scope' node surrounding NODE.
  1825. Returns nil if there is no enclosing scope node."
  1826. (while (and (setq node (js2-node-parent node))
  1827. (not (js2-scope-p node))))
  1828. node)
  1829. (defun js2-get-defining-scope (scope name &optional point)
  1830. "Search up scope chain from SCOPE looking for NAME, a string or symbol.
  1831. Returns `js2-scope' in which NAME is defined, or nil if not found.
  1832. If POINT is non-nil, and if the found declaration type is
  1833. `js2-LET', also check that the declaration node is before POINT."
  1834. (let ((sym (if (symbolp name)
  1835. name
  1836. (intern name)))
  1837. result
  1838. (continue t))
  1839. (while (and scope continue)
  1840. (if (or
  1841. (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
  1842. (and entry
  1843. (or (not point)
  1844. (not (eq js2-LET (js2-symbol-decl-type entry)))
  1845. (>= point
  1846. (js2-node-abs-pos (js2-symbol-ast-node entry))))))
  1847. (and (eq sym 'arguments)
  1848. (js2-function-node-p scope)))
  1849. (setq continue nil
  1850. result scope)
  1851. (setq scope (js2-scope-parent-scope scope))))
  1852. result))
  1853. (defun js2-scope-get-symbol (scope name)
  1854. "Return symbol table entry for NAME in SCOPE.
  1855. NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
  1856. (and (js2-scope-symbol-table scope)
  1857. (cdr (assq (if (symbolp name)
  1858. name
  1859. (intern name))
  1860. (js2-scope-symbol-table scope)))))
  1861. (defun js2-scope-put-symbol (scope name symbol)
  1862. "Enter SYMBOL into symbol-table for SCOPE under NAME.
  1863. NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
  1864. (let* ((table (js2-scope-symbol-table scope))
  1865. (sym (if (symbolp name) name (intern name)))
  1866. (entry (assq sym table)))
  1867. (if entry
  1868. (setcdr entry symbol)
  1869. (push (cons sym symbol)
  1870. (js2-scope-symbol-table scope)))))
  1871. (cl-defstruct (js2-symbol
  1872. (:constructor make-js2-symbol (decl-type name &optional ast-node)))
  1873. "A symbol table entry."
  1874. ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
  1875. ;; js2-LET, or js2-CONST
  1876. decl-type
  1877. name ; string
  1878. ast-node) ; a `js2-node'
  1879. (cl-defstruct (js2-error-node
  1880. (:include js2-node)
  1881. (:constructor make-js2-error-node (&key (type js2-ERROR)
  1882. (pos (js2-current-token-beg))
  1883. len)))
  1884. "AST node representing a parse error.")
  1885. (js2--struct-put 'js2-error-node 'js2-visitor 'js2-visit-none)
  1886. (js2--struct-put 'js2-error-node 'js2-printer 'js2-print-none)
  1887. (cl-defstruct (js2-script-node
  1888. (:include js2-scope)
  1889. (:constructor make-js2-script-node (&key (type js2-SCRIPT)
  1890. (pos (js2-current-token-beg))
  1891. len)))
  1892. functions ; Lisp list of nested functions
  1893. regexps ; Lisp list of (string . flags)
  1894. symbols ; alist (every symbol gets unique index)
  1895. (param-count 0)
  1896. var-names ; vector of string names
  1897. consts ; bool-vector matching var-decls
  1898. (temp-number 0)) ; for generating temp variables
  1899. (js2--struct-put 'js2-script-node 'js2-visitor 'js2-visit-block)
  1900. (js2--struct-put 'js2-script-node 'js2-printer 'js2-print-script)
  1901. (defun js2-print-script (node indent)
  1902. (dolist (kid (js2-block-node-kids node))
  1903. (js2-print-ast kid indent)))
  1904. (cl-defstruct (js2-ast-root
  1905. (:include js2-script-node)
  1906. (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
  1907. (pos (js2-current-token-beg))
  1908. len
  1909. buffer)))
  1910. "The root node of a js2 AST."
  1911. buffer ; the source buffer from which the code was parsed
  1912. comments ; a Lisp list of comments, ordered by start position
  1913. errors ; a Lisp list of errors found during parsing
  1914. warnings ; a Lisp list of warnings found during parsing
  1915. node-count) ; number of nodes in the tree, including the root
  1916. (js2--struct-put 'js2-ast-root 'js2-visitor 'js2-visit-ast-root)
  1917. (js2--struct-put 'js2-ast-root 'js2-printer 'js2-print-script)
  1918. (defun js2-visit-ast-root (ast callback)
  1919. (dolist (kid (js2-ast-root-kids ast))
  1920. (js2-visit-ast kid callback))
  1921. (dolist (comment (js2-ast-root-comments ast))
  1922. (js2-visit-ast comment callback)))
  1923. (cl-defstruct (js2-comment-node
  1924. (:include js2-node)
  1925. (:constructor make-js2-comment-node (&key (type js2-COMMENT)
  1926. (pos (js2-current-token-beg))
  1927. len
  1928. format)))
  1929. format) ; 'line, 'block, 'jsdoc or 'html
  1930. (js2--struct-put 'js2-comment-node 'js2-visitor 'js2-visit-none)
  1931. (js2--struct-put 'js2-comment-node 'js2-printer 'js2-print-comment)
  1932. (defun js2-print-comment (n i)
  1933. ;; We really ought to link end-of-line comments to their nodes.
  1934. ;; Or maybe we could add a new comment type, 'endline.
  1935. (insert (js2-make-pad i)
  1936. (js2-node-string n)))
  1937. (cl-defstruct (js2-expr-stmt-node
  1938. (:include js2-node)
  1939. (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
  1940. (pos js2-ts-cursor)
  1941. len
  1942. expr)))
  1943. "An expression statement."
  1944. expr)
  1945. (defsubst js2-expr-stmt-node-set-has-result (node)
  1946. "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
  1947. (setf (js2-node-type node) js2-EXPR_RESULT))
  1948. (js2--struct-put 'js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
  1949. (js2--struct-put 'js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
  1950. (defun js2-visit-expr-stmt-node (n v)
  1951. (js2-visit-ast (js2-expr-stmt-node-expr n) v))
  1952. (defun js2-print-expr-stmt-node (n indent)
  1953. (js2-print-ast (js2-expr-stmt-node-expr n) indent)
  1954. (insert ";\n"))
  1955. (cl-defstruct (js2-loop-node
  1956. (:include js2-scope)
  1957. (:constructor nil))
  1958. "Abstract supertype of loop nodes."
  1959. body ; a `js2-block-node'
  1960. lp ; position of left-paren, nil if omitted
  1961. rp) ; position of right-paren, nil if omitted
  1962. (cl-defstruct (js2-do-node
  1963. (:include js2-loop-node)
  1964. (:constructor make-js2-do-node (&key (type js2-DO)
  1965. (pos (js2-current-token-beg))
  1966. len
  1967. body
  1968. condition
  1969. while-pos
  1970. lp
  1971. rp)))
  1972. "AST node for do-loop."
  1973. condition ; while (expression)
  1974. while-pos) ; buffer position of 'while' keyword
  1975. (js2--struct-put 'js2-do-node 'js2-visitor 'js2-visit-do-node)
  1976. (js2--struct-put 'js2-do-node 'js2-printer 'js2-print-do-node)
  1977. (defun js2-visit-do-node (n v)
  1978. (js2-visit-ast (js2-do-node-body n) v)
  1979. (js2-visit-ast (js2-do-node-condition n) v))
  1980. (defun js2-print-do-node (n i)
  1981. (let ((pad (js2-make-pad i)))
  1982. (insert pad "do {\n")
  1983. (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
  1984. (js2-print-ast kid (1+ i)))
  1985. (insert pad "} while (")
  1986. (js2-print-ast (js2-do-node-condition n) 0)
  1987. (insert ");\n")))
  1988. (cl-defstruct (js2-export-node
  1989. (:include js2-node)
  1990. (:constructor make-js2-export-node (&key (type js2-EXPORT)
  1991. (pos (js2-current-token-beg))
  1992. len
  1993. exports-list
  1994. from-clause
  1995. declaration
  1996. default)))
  1997. "AST node for an export statement. There are many things that can be exported,
  1998. so many of its properties will be nil.
  1999. "
  2000. exports-list ; lisp list of js2-export-binding-node to export
  2001. from-clause ; js2-from-clause-node for re-exporting symbols from another module
  2002. declaration ; js2-var-decl-node (var, let, const) or js2-class-node
  2003. default) ; js2-function-node or js2-assign-node
  2004. (js2--struct-put 'js2-export-node 'js2-visitor 'js2-visit-export-node)
  2005. (js2--struct-put 'js2-export-node 'js2-printer 'js2-print-export-node)
  2006. (defun js2-visit-export-node (n v)
  2007. (let ((exports-list (js2-export-node-exports-list n))
  2008. (from (js2-export-node-from-clause n))
  2009. (declaration (js2-export-node-declaration n))
  2010. (default (js2-export-node-default n)))
  2011. (when exports-list
  2012. (dolist (export exports-list)
  2013. (js2-visit-ast export v)))
  2014. (when from
  2015. (js2-visit-ast from v))
  2016. (when declaration
  2017. (js2-visit-ast declaration v))
  2018. (when default
  2019. (js2-visit-ast default v))))
  2020. (defun js2-print-export-node (n i)
  2021. (let ((pad (js2-make-pad i))
  2022. (exports-list (js2-export-node-exports-list n))
  2023. (from (js2-export-node-from-clause n))
  2024. (declaration (js2-export-node-declaration n))
  2025. (default (js2-export-node-default n)))
  2026. (insert pad "export ")
  2027. (cond
  2028. (default
  2029. (insert "default ")
  2030. (js2-print-ast default i))
  2031. (declaration
  2032. (js2-print-ast declaration i))
  2033. ((and exports-list from)
  2034. (js2-print-named-imports exports-list)
  2035. (insert " ")
  2036. (js2-print-from-clause from))
  2037. (from
  2038. (insert "* ")
  2039. (js2-print-from-clause from))
  2040. (exports-list
  2041. (js2-print-named-imports exports-list)))
  2042. (unless (or (and default (not (js2-assign-node-p default)))
  2043. (and declaration (or (js2-function-node-p declaration)
  2044. (js2-class-node-p declaration))))
  2045. (insert ";\n"))))
  2046. (cl-defstruct (js2-while-node
  2047. (:include js2-loop-node)
  2048. (:constructor make-js2-while-node (&key (type js2-WHILE)
  2049. (pos (js2-current-token-beg))
  2050. len body
  2051. condition lp
  2052. rp)))
  2053. "AST node for while-loop."
  2054. condition) ; while-condition
  2055. (js2--struct-put 'js2-while-node 'js2-visitor 'js2-visit-while-node)
  2056. (js2--struct-put 'js2-while-node 'js2-printer 'js2-print-while-node)
  2057. (defun js2-visit-while-node (n v)
  2058. (js2-visit-ast (js2-while-node-condition n) v)
  2059. (js2-visit-ast (js2-while-node-body n) v))
  2060. (defun js2-print-while-node (n i)
  2061. (let ((pad (js2-make-pad i)))
  2062. (insert pad "while (")
  2063. (js2-print-ast (js2-while-node-condition n) 0)
  2064. (insert ") {\n")
  2065. (js2-print-body (js2-while-node-body n) (1+ i))
  2066. (insert pad "}\n")))
  2067. (cl-defstruct (js2-for-node
  2068. (:include js2-loop-node)
  2069. (:constructor make-js2-for-node (&key (type js2-FOR)
  2070. (pos js2-ts-cursor)
  2071. len body init
  2072. condition
  2073. update lp rp)))
  2074. "AST node for a C-style for-loop."
  2075. init ; initialization expression
  2076. condition ; loop condition
  2077. update) ; update clause
  2078. (js2--struct-put 'js2-for-node 'js2-visitor 'js2-visit-for-node)
  2079. (js2--struct-put 'js2-for-node 'js2-printer 'js2-print-for-node)
  2080. (defun js2-visit-for-node (n v)
  2081. (js2-visit-ast (js2-for-node-init n) v)
  2082. (js2-visit-ast (js2-for-node-condition n) v)
  2083. (js2-visit-ast (js2-for-node-update n) v)
  2084. (js2-visit-ast (js2-for-node-body n) v))
  2085. (defun js2-print-for-node (n i)
  2086. (let ((pad (js2-make-pad i)))
  2087. (insert pad "for (")
  2088. (js2-print-ast (js2-for-node-init n) 0)
  2089. (insert "; ")
  2090. (js2-print-ast (js2-for-node-condition n) 0)
  2091. (insert "; ")
  2092. (js2-print-ast (js2-for-node-update n) 0)
  2093. (insert ") {\n")
  2094. (js2-print-body (js2-for-node-body n) (1+ i))
  2095. (insert pad "}\n")))
  2096. (cl-defstruct (js2-for-in-node
  2097. (:include js2-loop-node)
  2098. (:constructor make-js2-for-in-node (&key (type js2-FOR)
  2099. (pos js2-ts-cursor)
  2100. len body
  2101. iterator
  2102. object
  2103. in-pos
  2104. each-pos
  2105. foreach-p forof-p
  2106. lp rp)))
  2107. "AST node for a for..in loop."
  2108. iterator ; [var] foo in ...
  2109. object ; object over which we're iterating
  2110. in-pos ; buffer position of 'in' keyword
  2111. each-pos ; buffer position of 'each' keyword, if foreach-p
  2112. foreach-p ; t if it's a for-each loop
  2113. forof-p) ; t if it's a for-of loop
  2114. (js2--struct-put 'js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
  2115. (js2--struct-put 'js2-for-in-node 'js2-printer 'js2-print-for-in-node)
  2116. (defun js2-visit-for-in-node (n v)
  2117. (js2-visit-ast (js2-for-in-node-iterator n) v)
  2118. (js2-visit-ast (js2-for-in-node-object n) v)
  2119. (js2-visit-ast (js2-for-in-node-body n) v))
  2120. (defun js2-print-for-in-node (n i)
  2121. (let ((pad (js2-make-pad i))
  2122. (foreach (js2-for-in-node-foreach-p n))
  2123. (forof (js2-for-in-node-forof-p n)))
  2124. (insert pad "for ")
  2125. (if foreach
  2126. (insert "each "))
  2127. (insert "(")
  2128. (js2-print-ast (js2-for-in-node-iterator n) 0)
  2129. (insert (if forof " of " " in "))
  2130. (js2-print-ast (js2-for-in-node-object n) 0)
  2131. (insert ") {\n")
  2132. (js2-print-body (js2-for-in-node-body n) (1+ i))
  2133. (insert pad "}\n")))
  2134. (cl-defstruct (js2-return-node
  2135. (:include js2-node)
  2136. (:constructor make-js2-return-node (&key (type js2-RETURN)
  2137. (pos js2-ts-cursor)
  2138. len
  2139. retval)))
  2140. "AST node for a return statement."
  2141. retval) ; expression to return, or 'undefined
  2142. (js2--struct-put 'js2-return-node 'js2-visitor 'js2-visit-return-node)
  2143. (js2--struct-put 'js2-return-node 'js2-printer 'js2-print-return-node)
  2144. (defun js2-visit-return-node (n v)
  2145. (js2-visit-ast (js2-return-node-retval n) v))
  2146. (defun js2-print-return-node (n i)
  2147. (insert (js2-make-pad i) "return")
  2148. (when (js2-return-node-retval n)
  2149. (insert " ")
  2150. (js2-print-ast (js2-return-node-retval n) 0))
  2151. (insert ";\n"))
  2152. (cl-defstruct (js2-if-node
  2153. (:include js2-node)
  2154. (:constructor make-js2-if-node (&key (type js2-IF)
  2155. (pos js2-ts-cursor)
  2156. len condition
  2157. then-part
  2158. else-pos
  2159. else-part lp
  2160. rp)))
  2161. "AST node for an if-statement."
  2162. condition ; expression
  2163. then-part ; statement or block
  2164. else-pos ; optional buffer position of 'else' keyword
  2165. else-part ; optional statement or block
  2166. lp ; position of left-paren, nil if omitted
  2167. rp) ; position of right-paren, nil if omitted
  2168. (js2--struct-put 'js2-if-node 'js2-visitor 'js2-visit-if-node)
  2169. (js2--struct-put 'js2-if-node 'js2-printer 'js2-print-if-node)
  2170. (defun js2-visit-if-node (n v)
  2171. (js2-visit-ast (js2-if-node-condition n) v)
  2172. (js2-visit-ast (js2-if-node-then-part n) v)
  2173. (js2-visit-ast (js2-if-node-else-part n) v))
  2174. (defun js2-print-if-node (n i)
  2175. (let ((pad (js2-make-pad i))
  2176. (then-part (js2-if-node-then-part n))
  2177. (else-part (js2-if-node-else-part n)))
  2178. (insert pad "if (")
  2179. (js2-print-ast (js2-if-node-condition n) 0)
  2180. (insert ") {\n")
  2181. (js2-print-body then-part (1+ i))
  2182. (insert pad "}")
  2183. (cond
  2184. ((not else-part)
  2185. (insert "\n"))
  2186. ((js2-if-node-p else-part)
  2187. (insert " else ")
  2188. (js2-print-body else-part i))
  2189. (t
  2190. (insert " else {\n")
  2191. (js2-print-body else-part (1+ i))
  2192. (insert pad "}\n")))))
  2193. (cl-defstruct (js2-export-binding-node
  2194. (:include js2-node)
  2195. (:constructor make-js2-export-binding-node (&key (type -1)
  2196. pos
  2197. len
  2198. local-name
  2199. extern-name)))
  2200. "AST node for an external symbol binding.
  2201. It contains a local-name node which is the name of the value in the
  2202. current scope, and extern-name which is the name of the value in the
  2203. imported or exported scope. By default these are the same, but if the
  2204. name is aliased as in {foo as bar}, it would have an extern-name node
  2205. containing 'foo' and a local-name node containing 'bar'."
  2206. local-name ; js2-name-node with the variable name in this scope
  2207. extern-name) ; js2-name-node with the value name in the exporting module
  2208. (js2--struct-put 'js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
  2209. (js2--struct-put 'js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
  2210. (defun js2-visit-extern-binding (n v)
  2211. "Visit an extern binding node. First visit the local-name, and, if
  2212. different, visit the extern-name."
  2213. (let ((local-name (js2-export-binding-node-local-name n))
  2214. (extern-name (js2-export-binding-node-extern-name n)))
  2215. (when local-name
  2216. (js2-visit-ast local-name v))
  2217. (when (not (equal local-name extern-name))
  2218. (js2-visit-ast extern-name v))))
  2219. (defun js2-print-extern-binding (n _i)
  2220. "Print a representation of a single extern binding. E.g. 'foo' or
  2221. 'foo as bar'."
  2222. (let ((local-name (js2-export-binding-node-local-name n))
  2223. (extern-name (js2-export-binding-node-extern-name n)))
  2224. (insert (js2-name-node-name extern-name))
  2225. (when (not (equal local-name extern-name))
  2226. (insert " as ")
  2227. (insert (js2-name-node-name local-name)))))
  2228. (cl-defstruct (js2-import-node
  2229. (:include js2-node)
  2230. (:constructor make-js2-import-node (&key (type js2-IMPORT)
  2231. (pos (js2-current-token-beg))
  2232. len
  2233. import
  2234. from
  2235. module-id)))
  2236. "AST node for an import statement. It follows the form
  2237. import ModuleSpecifier;
  2238. import ImportClause FromClause;"
  2239. import ; js2-import-clause-node specifying which names are to imported.
  2240. from ; js2-from-clause-node indicating the module from which to import.
  2241. module-id) ; module-id of the import. E.g. 'src/mylib'.
  2242. (js2--struct-put 'js2-import-node 'js2-printer 'js2-print-import)
  2243. (js2--struct-put 'js2-import-node 'js2-visitor 'js2-visit-import)
  2244. (defun js2-visit-import (n v)
  2245. (let ((import-clause (js2-import-node-import n))
  2246. (from-clause (js2-import-node-from n)))
  2247. (when import-clause
  2248. (js2-visit-ast import-clause v))
  2249. (when from-clause
  2250. (js2-visit-ast from-clause v))))
  2251. (defun js2-print-import (n i)
  2252. "Prints a representation of the import node"
  2253. (let ((pad (js2-make-pad i))
  2254. (import-clause (js2-import-node-import n))
  2255. (from-clause (js2-import-node-from n))
  2256. (module-id (js2-import-node-module-id n)))
  2257. (insert pad "import ")
  2258. (if import-clause
  2259. (progn
  2260. (js2-print-import-clause import-clause)
  2261. (insert " ")
  2262. (js2-print-from-clause from-clause))
  2263. (insert "'")
  2264. (insert module-id)
  2265. (insert "'"))
  2266. (insert ";\n")))
  2267. (cl-defstruct (js2-import-clause-node
  2268. (:include js2-node)
  2269. (:constructor make-js2-import-clause-node (&key (type -1)
  2270. pos
  2271. len
  2272. namespace-import
  2273. named-imports
  2274. default-binding)))
  2275. "AST node corresponding to the import clause of an import statement. This is
  2276. the portion of the import that bindings names from the external context to the
  2277. local context."
  2278. namespace-import ; js2-namespace-import-node. E.g. '* as lib'
  2279. named-imports ; lisp list of js2-export-binding-node for all named imports.
  2280. default-binding) ; js2-export-binding-node for the default import binding
  2281. (js2--struct-put 'js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
  2282. (js2--struct-put 'js2-import-clause-node 'js2-printer 'js2-print-import-clause)
  2283. (defun js2-visit-import-clause (n v)
  2284. (let ((ns-import (js2-import-clause-node-namespace-import n))
  2285. (named-imports (js2-import-clause-node-named-imports n))
  2286. (default (js2-import-clause-node-default-binding n)))
  2287. (when default
  2288. (js2-visit-ast default v))
  2289. (when ns-import
  2290. (js2-visit-ast ns-import v))
  2291. (when named-imports
  2292. (dolist (import named-imports)
  2293. (js2-visit-ast import v)))))
  2294. (defun js2-print-import-clause (n)
  2295. (let ((ns-import (js2-import-clause-node-namespace-import n))
  2296. (named-imports (js2-import-clause-node-named-imports n))
  2297. (default (js2-import-clause-node-default-binding n)))
  2298. (cond
  2299. ((and default ns-import)
  2300. (js2-print-ast default)
  2301. (insert ", ")
  2302. (js2-print-namespace-import ns-import))
  2303. ((and default named-imports)
  2304. (js2-print-ast default)
  2305. (insert ", ")
  2306. (js2-print-named-imports named-imports))
  2307. (default
  2308. (js2-print-ast default))
  2309. (ns-import
  2310. (js2-print-namespace-import ns-import))
  2311. (named-imports
  2312. (js2-print-named-imports named-imports)))))
  2313. (defun js2-print-namespace-import (node)
  2314. (insert "* as ")
  2315. (insert (js2-name-node-name (js2-namespace-import-node-name node))))
  2316. (defun js2-print-named-imports (imports)
  2317. (insert "{")
  2318. (let ((len (length imports))
  2319. (n 0))
  2320. (while (< n len)
  2321. (js2-print-extern-binding (nth n imports) 0)
  2322. (unless (= n (- len 1))
  2323. (insert ", "))
  2324. (setq n (+ n 1))))
  2325. (insert "}"))
  2326. (cl-defstruct (js2-namespace-import-node
  2327. (:include js2-node)
  2328. (:constructor make-js2-namespace-import-node (&key (type -1)
  2329. pos
  2330. len
  2331. name)))
  2332. "AST node for a complete namespace import.
  2333. E.g. the '* as lib' expression in:
  2334. import * as lib from 'src/lib'
  2335. It contains a single name node referring to the bound name."
  2336. name) ; js2-name-node of the bound name.
  2337. (defun js2-visit-namespace-import (n v)
  2338. (js2-visit-ast (js2-namespace-import-node-name n) v))
  2339. (js2--struct-put 'js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
  2340. (js2--struct-put 'js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
  2341. (cl-defstruct (js2-from-clause-node
  2342. (:include js2-node)
  2343. (:constructor make-js2-from-clause-node (&key (type js2-NAME)
  2344. pos
  2345. len
  2346. module-id
  2347. metadata-p)))
  2348. "AST node for the from clause in an import or export statement.
  2349. E.g. from 'my/module'. It can refere to either an external module, or to the
  2350. modules metadata itself."
  2351. module-id ; string containing the module specifier.
  2352. metadata-p) ; true if this clause refers to the module's metadata
  2353. (js2--struct-put 'js2-from-clause-node 'js2-visitor 'js2-visit-none)
  2354. (js2--struct-put 'js2-from-clause-node 'js2-printer 'js2-print-from-clause)
  2355. (defun js2-print-from-clause (n)
  2356. (insert "from ")
  2357. (if (js2-from-clause-node-metadata-p n)
  2358. (insert "this module")
  2359. (insert "'")
  2360. (insert (js2-from-clause-node-module-id n))
  2361. (insert "'")))
  2362. (cl-defstruct (js2-try-node
  2363. (:include js2-node)
  2364. (:constructor make-js2-try-node (&key (type js2-TRY)
  2365. (pos js2-ts-cursor)
  2366. len
  2367. try-block
  2368. catch-clauses
  2369. finally-block)))
  2370. "AST node for a try-statement."
  2371. try-block
  2372. catch-clauses ; a Lisp list of `js2-catch-node'
  2373. finally-block) ; a `js2-finally-node'
  2374. (js2--struct-put 'js2-try-node 'js2-visitor 'js2-visit-try-node)
  2375. (js2--struct-put 'js2-try-node 'js2-printer 'js2-print-try-node)
  2376. (defun js2-visit-try-node (n v)
  2377. (js2-visit-ast (js2-try-node-try-block n) v)
  2378. (dolist (clause (js2-try-node-catch-clauses n))
  2379. (js2-visit-ast clause v))
  2380. (js2-visit-ast (js2-try-node-finally-block n) v))
  2381. (defun js2-print-try-node (n i)
  2382. (let ((pad (js2-make-pad i))
  2383. (catches (js2-try-node-catch-clauses n))
  2384. (finally (js2-try-node-finally-block n)))
  2385. (insert pad "try {\n")
  2386. (js2-print-body (js2-try-node-try-block n) (1+ i))
  2387. (insert pad "}")
  2388. (when catches
  2389. (dolist (catch catches)
  2390. (js2-print-ast catch i)))
  2391. (if finally
  2392. (js2-print-ast finally i)
  2393. (insert "\n"))))
  2394. (cl-defstruct (js2-catch-node
  2395. (:include js2-scope)
  2396. (:constructor make-js2-catch-node (&key (type js2-CATCH)
  2397. (pos js2-ts-cursor)
  2398. len
  2399. param
  2400. guard-kwd
  2401. guard-expr
  2402. lp rp)))
  2403. "AST node for a catch clause."
  2404. param ; destructuring form or simple name node
  2405. guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
  2406. guard-expr ; catch condition, a `js2-node'
  2407. lp ; buffer position of left-paren, nil if omitted
  2408. rp) ; buffer position of right-paren, nil if omitted
  2409. (js2--struct-put 'js2-catch-node 'js2-visitor 'js2-visit-catch-node)
  2410. (js2--struct-put 'js2-catch-node 'js2-printer 'js2-print-catch-node)
  2411. (defun js2-visit-catch-node (n v)
  2412. (js2-visit-ast (js2-catch-node-param n) v)
  2413. (when (js2-catch-node-guard-kwd n)
  2414. (js2-visit-ast (js2-catch-node-guard-expr n) v))
  2415. (js2-visit-block n v))
  2416. (defun js2-print-catch-node (n i)
  2417. (let ((pad (js2-make-pad i))
  2418. (guard-kwd (js2-catch-node-guard-kwd n))
  2419. (guard-expr (js2-catch-node-guard-expr n)))
  2420. (insert " catch (")
  2421. (js2-print-ast (js2-catch-node-param n) 0)
  2422. (when guard-kwd
  2423. (insert " if ")
  2424. (js2-print-ast guard-expr 0))
  2425. (insert ") {\n")
  2426. (js2-print-body n (1+ i))
  2427. (insert pad "}")))
  2428. (cl-defstruct (js2-finally-node
  2429. (:include js2-node)
  2430. (:constructor make-js2-finally-node (&key (type js2-FINALLY)
  2431. (pos js2-ts-cursor)
  2432. len body)))
  2433. "AST node for a finally clause."
  2434. body) ; a `js2-node', often but not always a block node
  2435. (js2--struct-put 'js2-finally-node 'js2-visitor 'js2-visit-finally-node)
  2436. (js2--struct-put 'js2-finally-node 'js2-printer 'js2-print-finally-node)
  2437. (defun js2-visit-finally-node (n v)
  2438. (js2-visit-ast (js2-finally-node-body n) v))
  2439. (defun js2-print-finally-node (n i)
  2440. (let ((pad (js2-make-pad i)))
  2441. (insert " finally {\n")
  2442. (js2-print-body (js2-finally-node-body n) (1+ i))
  2443. (insert pad "}\n")))
  2444. (cl-defstruct (js2-switch-node
  2445. (:include js2-scope)
  2446. (:constructor make-js2-switch-node (&key (type js2-SWITCH)
  2447. (pos js2-ts-cursor)
  2448. len
  2449. discriminant
  2450. cases lp
  2451. rp)))
  2452. "AST node for a switch statement."
  2453. discriminant ; a `js2-node' (switch expression)
  2454. cases ; a Lisp list of `js2-case-node'
  2455. lp ; position of open-paren for discriminant, nil if omitted
  2456. rp) ; position of close-paren for discriminant, nil if omitted
  2457. (js2--struct-put 'js2-switch-node 'js2-visitor 'js2-visit-switch-node)
  2458. (js2--struct-put 'js2-switch-node 'js2-printer 'js2-print-switch-node)
  2459. (defun js2-visit-switch-node (n v)
  2460. (js2-visit-ast (js2-switch-node-discriminant n) v)
  2461. (dolist (c (js2-switch-node-cases n))
  2462. (js2-visit-ast c v)))
  2463. (defun js2-print-switch-node (n i)
  2464. (let ((pad (js2-make-pad i))
  2465. (cases (js2-switch-node-cases n)))
  2466. (insert pad "switch (")
  2467. (js2-print-ast (js2-switch-node-discriminant n) 0)
  2468. (insert ") {\n")
  2469. (dolist (case cases)
  2470. (js2-print-ast case i))
  2471. (insert pad "}\n")))
  2472. (cl-defstruct (js2-case-node
  2473. (:include js2-block-node)
  2474. (:constructor make-js2-case-node (&key (type js2-CASE)
  2475. (pos js2-ts-cursor)
  2476. len kids expr)))
  2477. "AST node for a case clause of a switch statement."
  2478. expr) ; the case expression (nil for default)
  2479. (js2--struct-put 'js2-case-node 'js2-visitor 'js2-visit-case-node)
  2480. (js2--struct-put 'js2-case-node 'js2-printer 'js2-print-case-node)
  2481. (defun js2-visit-case-node (n v)
  2482. (js2-visit-ast (js2-case-node-expr n) v)
  2483. (js2-visit-block n v))
  2484. (defun js2-print-case-node (n i)
  2485. (let ((pad (js2-make-pad i))
  2486. (expr (js2-case-node-expr n)))
  2487. (insert pad)
  2488. (if (null expr)
  2489. (insert "default:\n")
  2490. (insert "case ")
  2491. (js2-print-ast expr 0)
  2492. (insert ":\n"))
  2493. (dolist (kid (js2-case-node-kids n))
  2494. (js2-print-ast kid (1+ i)))))
  2495. (cl-defstruct (js2-throw-node
  2496. (:include js2-node)
  2497. (:constructor make-js2-throw-node (&key (type js2-THROW)
  2498. (pos js2-ts-cursor)
  2499. len expr)))
  2500. "AST node for a throw statement."
  2501. expr) ; the expression to throw
  2502. (js2--struct-put 'js2-throw-node 'js2-visitor 'js2-visit-throw-node)
  2503. (js2--struct-put 'js2-throw-node 'js2-printer 'js2-print-throw-node)
  2504. (defun js2-visit-throw-node (n v)
  2505. (js2-visit-ast (js2-throw-node-expr n) v))
  2506. (defun js2-print-throw-node (n i)
  2507. (insert (js2-make-pad i) "throw ")
  2508. (js2-print-ast (js2-throw-node-expr n) 0)
  2509. (insert ";\n"))
  2510. (cl-defstruct (js2-with-node
  2511. (:include js2-node)
  2512. (:constructor make-js2-with-node (&key (type js2-WITH)
  2513. (pos js2-ts-cursor)
  2514. len object
  2515. body lp rp)))
  2516. "AST node for a with-statement."
  2517. object
  2518. body
  2519. lp ; buffer position of left-paren around object, nil if omitted
  2520. rp) ; buffer position of right-paren around object, nil if omitted
  2521. (js2--struct-put 'js2-with-node 'js2-visitor 'js2-visit-with-node)
  2522. (js2--struct-put 'js2-with-node 'js2-printer 'js2-print-with-node)
  2523. (defun js2-visit-with-node (n v)
  2524. (js2-visit-ast (js2-with-node-object n) v)
  2525. (js2-visit-ast (js2-with-node-body n) v))
  2526. (defun js2-print-with-node (n i)
  2527. (let ((pad (js2-make-pad i)))
  2528. (insert pad "with (")
  2529. (js2-print-ast (js2-with-node-object n) 0)
  2530. (insert ") {\n")
  2531. (js2-print-body (js2-with-node-body n) (1+ i))
  2532. (insert pad "}\n")))
  2533. (cl-defstruct (js2-label-node
  2534. (:include js2-node)
  2535. (:constructor make-js2-label-node (&key (type js2-LABEL)
  2536. (pos js2-ts-cursor)
  2537. len name)))
  2538. "AST node for a statement label or case label."
  2539. name ; a string
  2540. loop) ; for validating and code-generating continue-to-label
  2541. (js2--struct-put 'js2-label-node 'js2-visitor 'js2-visit-none)
  2542. (js2--struct-put 'js2-label-node 'js2-printer 'js2-print-label)
  2543. (defun js2-print-label (n i)
  2544. (insert (js2-make-pad i)
  2545. (js2-label-node-name n)
  2546. ":\n"))
  2547. (cl-defstruct (js2-labeled-stmt-node
  2548. (:include js2-node)
  2549. ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
  2550. ;; no-side-effects warnings, hence js2-EXPR_RESULT.
  2551. (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
  2552. (pos js2-ts-cursor)
  2553. len labels stmt)))
  2554. "AST node for a statement with one or more labels.
  2555. Multiple labels for a statement are collapsed into the labels field."
  2556. labels ; Lisp list of `js2-label-node'
  2557. stmt) ; the statement these labels are for
  2558. (js2--struct-put 'js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
  2559. (js2--struct-put 'js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
  2560. (defun js2-get-label-by-name (lbl-stmt name)
  2561. "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
  2562. Returns nil if no such label is in the list."
  2563. (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
  2564. result)
  2565. (while (and label-list (not result))
  2566. (if (string= (js2-label-node-name (car label-list)) name)
  2567. (setq result (car label-list))
  2568. (setq label-list (cdr label-list))))
  2569. result))
  2570. (defun js2-visit-labeled-stmt (n v)
  2571. (dolist (label (js2-labeled-stmt-node-labels n))
  2572. (js2-visit-ast label v))
  2573. (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
  2574. (defun js2-print-labeled-stmt (n i)
  2575. (dolist (label (js2-labeled-stmt-node-labels n))
  2576. (js2-print-ast label i))
  2577. (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
  2578. (defun js2-labeled-stmt-node-contains (node label)
  2579. "Return t if NODE contains LABEL in its label set.
  2580. NODE is a `js2-labels-node'. LABEL is an identifier."
  2581. (cl-loop for nl in (js2-labeled-stmt-node-labels node)
  2582. if (string= label (js2-label-node-name nl))
  2583. return t
  2584. finally return nil))
  2585. (defsubst js2-labeled-stmt-node-add-label (node label)
  2586. "Add a `js2-label-node' to the label set for this statement."
  2587. (setf (js2-labeled-stmt-node-labels node)
  2588. (nconc (js2-labeled-stmt-node-labels node) (list label))))
  2589. (cl-defstruct (js2-jump-node
  2590. (:include js2-node)
  2591. (:constructor nil))
  2592. "Abstract supertype of break and continue nodes."
  2593. label ; `js2-name-node' for location of label identifier, if present
  2594. target) ; target js2-labels-node or loop/switch statement
  2595. (defun js2-visit-jump-node (n v)
  2596. ;; We don't visit the target, since it's a back-link.
  2597. (js2-visit-ast (js2-jump-node-label n) v))
  2598. (cl-defstruct (js2-break-node
  2599. (:include js2-jump-node)
  2600. (:constructor make-js2-break-node (&key (type js2-BREAK)
  2601. (pos js2-ts-cursor)
  2602. len label target)))
  2603. "AST node for a break statement.
  2604. The label field is a `js2-name-node', possibly nil, for the named label
  2605. if provided. E.g. in 'break foo', it represents 'foo'. The target field
  2606. is the target of the break - a label node or enclosing loop/switch statement.")
  2607. (js2--struct-put 'js2-break-node 'js2-visitor 'js2-visit-jump-node)
  2608. (js2--struct-put 'js2-break-node 'js2-printer 'js2-print-break-node)
  2609. (defun js2-print-break-node (n i)
  2610. (insert (js2-make-pad i) "break")
  2611. (when (js2-break-node-label n)
  2612. (insert " ")
  2613. (js2-print-ast (js2-break-node-label n) 0))
  2614. (insert ";\n"))
  2615. (cl-defstruct (js2-continue-node
  2616. (:include js2-jump-node)
  2617. (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
  2618. (pos js2-ts-cursor)
  2619. len label target)))
  2620. "AST node for a continue statement.
  2621. The label field is the user-supplied enclosing label name, a `js2-name-node'.
  2622. It is nil if continue specifies no label. The target field is the jump target:
  2623. a `js2-label-node' or the innermost enclosing loop.")
  2624. (js2--struct-put 'js2-continue-node 'js2-visitor 'js2-visit-jump-node)
  2625. (js2--struct-put 'js2-continue-node 'js2-printer 'js2-print-continue-node)
  2626. (defun js2-print-continue-node (n i)
  2627. (insert (js2-make-pad i) "continue")
  2628. (when (js2-continue-node-label n)
  2629. (insert " ")
  2630. (js2-print-ast (js2-continue-node-label n) 0))
  2631. (insert ";\n"))
  2632. (cl-defstruct (js2-function-node
  2633. (:include js2-script-node)
  2634. (:constructor make-js2-function-node (&key (type js2-FUNCTION)
  2635. (pos js2-ts-cursor)
  2636. len
  2637. (ftype 'FUNCTION)
  2638. (form 'FUNCTION_STATEMENT)
  2639. (name "")
  2640. params rest-p
  2641. body
  2642. generator-type
  2643. async
  2644. lp rp)))
  2645. "AST node for a function declaration.
  2646. The `params' field is a Lisp list of nodes. Each node is either a simple
  2647. `js2-name-node', or if it's a destructuring-assignment parameter, a
  2648. `js2-array-node' or `js2-object-node'."
  2649. ftype ; FUNCTION, GETTER or SETTER
  2650. form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
  2651. name ; function name (a `js2-name-node', or nil if anonymous)
  2652. params ; a Lisp list of destructuring forms or simple name nodes
  2653. rest-p ; if t, the last parameter is rest parameter
  2654. body ; a `js2-block-node' or expression node (1.8 only)
  2655. lp ; position of arg-list open-paren, or nil if omitted
  2656. rp ; position of arg-list close-paren, or nil if omitted
  2657. ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
  2658. needs-activation ; t if we need an activation object for this frame
  2659. generator-type ; STAR, LEGACY, COMPREHENSION or nil
  2660. async ; t if the function is defined as `async function`
  2661. member-expr) ; nonstandard Ecma extension from Rhino
  2662. (js2--struct-put 'js2-function-node 'js2-visitor 'js2-visit-function-node)
  2663. (js2--struct-put 'js2-function-node 'js2-printer 'js2-print-function-node)
  2664. (defun js2-visit-function-node (n v)
  2665. (js2-visit-ast (js2-function-node-name n) v)
  2666. (dolist (p (js2-function-node-params n))
  2667. (js2-visit-ast p v))
  2668. (js2-visit-ast (js2-function-node-body n) v))
  2669. (defun js2-print-function-node (n i)
  2670. (let* ((pad (js2-make-pad i))
  2671. (method (js2-node-get-prop n 'METHOD_TYPE))
  2672. (name (or (js2-function-node-name n)
  2673. (js2-function-node-member-expr n)))
  2674. (params (js2-function-node-params n))
  2675. (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
  2676. (rest-p (js2-function-node-rest-p n))
  2677. (body (js2-function-node-body n))
  2678. (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
  2679. (unless method
  2680. (insert pad)
  2681. (when (js2-function-node-async n) (insert "async "))
  2682. (unless arrow (insert "function"))
  2683. (when (eq (js2-function-node-generator-type n) 'STAR)
  2684. (insert "*")))
  2685. (when name
  2686. (insert " ")
  2687. (js2-print-ast name 0))
  2688. (insert "(")
  2689. (cl-loop with len = (length params)
  2690. for param in params
  2691. for count from 1
  2692. do
  2693. (when (and rest-p (= count len))
  2694. (insert "..."))
  2695. (js2-print-ast param 0)
  2696. (when (< count len)
  2697. (insert ", ")))
  2698. (insert ") ")
  2699. (when arrow
  2700. (insert "=> "))
  2701. (insert "{")
  2702. ;; TODO: fix this to be smarter about indenting, etc.
  2703. (unless expr
  2704. (insert "\n"))
  2705. (if (js2-block-node-p body)
  2706. (js2-print-body body (1+ i))
  2707. (js2-print-ast body 0))
  2708. (insert pad "}")
  2709. (unless expr
  2710. (insert "\n"))))
  2711. (defun js2-function-name (node)
  2712. "Return function name for NODE, a `js2-function-node', or nil if anonymous."
  2713. (and (js2-function-node-name node)
  2714. (js2-name-node-name (js2-function-node-name node))))
  2715. ;; Having this be an expression node makes it more flexible.
  2716. ;; There are IDE contexts, such as indentation in a for-loop initializer,
  2717. ;; that work better if you assume it's an expression. Whenever we have
  2718. ;; a standalone var/const declaration, we just wrap with an expr stmt.
  2719. ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
  2720. (cl-defstruct (js2-var-decl-node
  2721. (:include js2-node)
  2722. (:constructor make-js2-var-decl-node (&key (type js2-VAR)
  2723. (pos (js2-current-token-beg))
  2724. len kids
  2725. decl-type)))
  2726. "AST node for a variable declaration list (VAR, CONST or LET).
  2727. The node bounds differ depending on the declaration type. For VAR or
  2728. CONST declarations, the bounds include the var/const keyword. For LET
  2729. declarations, the node begins at the position of the first child."
  2730. kids ; a Lisp list of `js2-var-init-node' structs.
  2731. decl-type) ; js2-VAR, js2-CONST or js2-LET
  2732. (js2--struct-put 'js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
  2733. (js2--struct-put 'js2-var-decl-node 'js2-printer 'js2-print-var-decl)
  2734. (defun js2-visit-var-decl (n v)
  2735. (dolist (kid (js2-var-decl-node-kids n))
  2736. (js2-visit-ast kid v)))
  2737. (defun js2-print-var-decl (n i)
  2738. (let ((pad (js2-make-pad i))
  2739. (tt (js2-var-decl-node-decl-type n)))
  2740. (insert pad)
  2741. (insert (cond
  2742. ((= tt js2-VAR) "var ")
  2743. ((= tt js2-LET) "let ")
  2744. ((= tt js2-CONST) "const ")
  2745. (t
  2746. (error "malformed var-decl node"))))
  2747. (cl-loop with kids = (js2-var-decl-node-kids n)
  2748. with len = (length kids)
  2749. for kid in kids
  2750. for count from 1
  2751. do
  2752. (js2-print-ast kid 0)
  2753. (if (< count len)
  2754. (insert ", ")))))
  2755. (cl-defstruct (js2-var-init-node
  2756. (:include js2-node)
  2757. (:constructor make-js2-var-init-node (&key (type js2-VAR)
  2758. (pos js2-ts-cursor)
  2759. len target
  2760. initializer)))
  2761. "AST node for a variable declaration.
  2762. The type field will be js2-CONST for a const decl."
  2763. target ; `js2-name-node', `js2-object-node', or `js2-array-node'
  2764. initializer) ; initializer expression, a `js2-node'
  2765. (js2--struct-put 'js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
  2766. (js2--struct-put 'js2-var-init-node 'js2-printer 'js2-print-var-init-node)
  2767. (defun js2-visit-var-init-node (n v)
  2768. (js2-visit-ast (js2-var-init-node-target n) v)
  2769. (js2-visit-ast (js2-var-init-node-initializer n) v))
  2770. (defun js2-print-var-init-node (n i)
  2771. (let ((pad (js2-make-pad i))
  2772. (name (js2-var-init-node-target n))
  2773. (init (js2-var-init-node-initializer n)))
  2774. (insert pad)
  2775. (js2-print-ast name 0)
  2776. (when init
  2777. (insert " = ")
  2778. (js2-print-ast init 0))))
  2779. (cl-defstruct (js2-cond-node
  2780. (:include js2-node)
  2781. (:constructor make-js2-cond-node (&key (type js2-HOOK)
  2782. (pos js2-ts-cursor)
  2783. len
  2784. test-expr
  2785. true-expr
  2786. false-expr
  2787. q-pos c-pos)))
  2788. "AST node for the ternary operator"
  2789. test-expr
  2790. true-expr
  2791. false-expr
  2792. q-pos ; buffer position of ?
  2793. c-pos) ; buffer position of :
  2794. (js2--struct-put 'js2-cond-node 'js2-visitor 'js2-visit-cond-node)
  2795. (js2--struct-put 'js2-cond-node 'js2-printer 'js2-print-cond-node)
  2796. (defun js2-visit-cond-node (n v)
  2797. (js2-visit-ast (js2-cond-node-test-expr n) v)
  2798. (js2-visit-ast (js2-cond-node-true-expr n) v)
  2799. (js2-visit-ast (js2-cond-node-false-expr n) v))
  2800. (defun js2-print-cond-node (n i)
  2801. (let ((pad (js2-make-pad i)))
  2802. (insert pad)
  2803. (js2-print-ast (js2-cond-node-test-expr n) 0)
  2804. (insert " ? ")
  2805. (js2-print-ast (js2-cond-node-true-expr n) 0)
  2806. (insert " : ")
  2807. (js2-print-ast (js2-cond-node-false-expr n) 0)))
  2808. (cl-defstruct (js2-infix-node
  2809. (:include js2-node)
  2810. (:constructor make-js2-infix-node (&key type
  2811. (pos js2-ts-cursor)
  2812. len op-pos
  2813. left right)))
  2814. "Represents infix expressions.
  2815. Includes assignment ops like `|=', and the comma operator.
  2816. The type field inherited from `js2-node' holds the operator."
  2817. op-pos ; buffer position where operator begins
  2818. left ; any `js2-node'
  2819. right) ; any `js2-node'
  2820. (js2--struct-put 'js2-infix-node 'js2-visitor 'js2-visit-infix-node)
  2821. (js2--struct-put 'js2-infix-node 'js2-printer 'js2-print-infix-node)
  2822. (defun js2-visit-infix-node (n v)
  2823. (js2-visit-ast (js2-infix-node-left n) v)
  2824. (js2-visit-ast (js2-infix-node-right n) v))
  2825. (defconst js2-operator-tokens
  2826. (let ((table (make-hash-table :test 'eq))
  2827. (tokens
  2828. (list (cons js2-IN "in")
  2829. (cons js2-TYPEOF "typeof")
  2830. (cons js2-INSTANCEOF "instanceof")
  2831. (cons js2-DELPROP "delete")
  2832. (cons js2-AWAIT "await")
  2833. (cons js2-VOID "void")
  2834. (cons js2-COMMA ",")
  2835. (cons js2-COLON ":")
  2836. (cons js2-OR "||")
  2837. (cons js2-AND "&&")
  2838. (cons js2-NULLISH-COALESCING "??")
  2839. (cons js2-INC "++")
  2840. (cons js2-DEC "--")
  2841. (cons js2-BITOR "|")
  2842. (cons js2-BITXOR "^")
  2843. (cons js2-BITAND "&")
  2844. (cons js2-EQ "==")
  2845. (cons js2-NE "!=")
  2846. (cons js2-LT "<")
  2847. (cons js2-LE "<=")
  2848. (cons js2-GT ">")
  2849. (cons js2-GE ">=")
  2850. (cons js2-LSH "<<")
  2851. (cons js2-RSH ">>")
  2852. (cons js2-URSH ">>>")
  2853. (cons js2-ADD "+") ; infix plus
  2854. (cons js2-SUB "-") ; infix minus
  2855. (cons js2-MUL "*")
  2856. (cons js2-EXPON "**")
  2857. (cons js2-DIV "/")
  2858. (cons js2-MOD "%")
  2859. (cons js2-NOT "!")
  2860. (cons js2-BITNOT "~")
  2861. (cons js2-POS "+") ; unary plus
  2862. (cons js2-NEG "-") ; unary minus
  2863. (cons js2-TRIPLEDOT "...")
  2864. (cons js2-SHEQ "===") ; shallow equality
  2865. (cons js2-SHNE "!==") ; shallow inequality
  2866. (cons js2-ASSIGN "=")
  2867. (cons js2-ASSIGN_BITOR "|=")
  2868. (cons js2-ASSIGN_BITXOR "^=")
  2869. (cons js2-ASSIGN_BITAND "&=")
  2870. (cons js2-ASSIGN_LSH "<<=")
  2871. (cons js2-ASSIGN_RSH ">>=")
  2872. (cons js2-ASSIGN_URSH ">>>=")
  2873. (cons js2-ASSIGN_ADD "+=")
  2874. (cons js2-ASSIGN_SUB "-=")
  2875. (cons js2-ASSIGN_MUL "*=")
  2876. (cons js2-ASSIGN_EXPON "**=")
  2877. (cons js2-ASSIGN_DIV "/=")
  2878. (cons js2-ASSIGN_MOD "%=")
  2879. (cons js2-ASSIGN_AND "&&=")
  2880. (cons js2-ASSIGN_OR "||=")
  2881. (cons js2-ASSIGN_NULLISH "??="))))
  2882. (cl-loop for (k . v) in tokens do
  2883. (puthash k v table))
  2884. table))
  2885. (defun js2-print-infix-node (n i)
  2886. (let* ((tt (js2-node-type n))
  2887. (op (gethash tt js2-operator-tokens)))
  2888. (unless op
  2889. (error "unrecognized infix operator %s" (js2-node-type n)))
  2890. (insert (js2-make-pad i))
  2891. (js2-print-ast (js2-infix-node-left n) 0)
  2892. (unless (= tt js2-COMMA)
  2893. (insert " "))
  2894. (insert op)
  2895. (insert " ")
  2896. (js2-print-ast (js2-infix-node-right n) 0)))
  2897. (cl-defstruct (js2-assign-node
  2898. (:include js2-infix-node)
  2899. (:constructor make-js2-assign-node (&key type
  2900. (pos js2-ts-cursor)
  2901. len op-pos
  2902. left right)))
  2903. "Represents any assignment.
  2904. The type field holds the actual assignment operator.")
  2905. (js2--struct-put 'js2-assign-node 'js2-visitor 'js2-visit-infix-node)
  2906. (js2--struct-put 'js2-assign-node 'js2-printer 'js2-print-infix-node)
  2907. (cl-defstruct (js2-unary-node
  2908. (:include js2-node)
  2909. (:constructor make-js2-unary-node (&key type ; required
  2910. (pos js2-ts-cursor)
  2911. len operand)))
  2912. "AST node type for unary operator nodes.
  2913. The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
  2914. TYPEOF, DELPROP, TRIPLEDOT or AWAIT. For INC or DEC, a 'postfix node
  2915. property is added if the operator follows the operand."
  2916. operand) ; a `js2-node' expression
  2917. (js2--struct-put 'js2-unary-node 'js2-visitor 'js2-visit-unary-node)
  2918. (js2--struct-put 'js2-unary-node 'js2-printer 'js2-print-unary-node)
  2919. (defun js2-visit-unary-node (n v)
  2920. (js2-visit-ast (js2-unary-node-operand n) v))
  2921. (defun js2-print-unary-node (n i)
  2922. (let* ((tt (js2-node-type n))
  2923. (op (gethash tt js2-operator-tokens))
  2924. (postfix (js2-node-get-prop n 'postfix)))
  2925. (unless op
  2926. (error "unrecognized unary operator %s" tt))
  2927. (insert (js2-make-pad i))
  2928. (unless postfix
  2929. (insert op))
  2930. (if (or (= tt js2-TYPEOF)
  2931. (= tt js2-DELPROP)
  2932. (= tt js2-AWAIT)
  2933. (= tt js2-VOID))
  2934. (insert " "))
  2935. (js2-print-ast (js2-unary-node-operand n) 0)
  2936. (when postfix
  2937. (insert op))))
  2938. (cl-defstruct (js2-let-node
  2939. (:include js2-scope)
  2940. (:constructor make-js2-let-node (&key (type js2-LETEXPR)
  2941. (pos (js2-current-token-beg))
  2942. len vars body
  2943. lp rp)))
  2944. "AST node for a let expression or a let statement.
  2945. Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
  2946. vars ; a `js2-var-decl-node'
  2947. body ; a `js2-node' representing the expression or body block
  2948. lp
  2949. rp)
  2950. (js2--struct-put 'js2-let-node 'js2-visitor 'js2-visit-let-node)
  2951. (js2--struct-put 'js2-let-node 'js2-printer 'js2-print-let-node)
  2952. (defun js2-visit-let-node (n v)
  2953. (js2-visit-ast (js2-let-node-vars n) v)
  2954. (js2-visit-ast (js2-let-node-body n) v))
  2955. (defun js2-print-let-node (n i)
  2956. (insert (js2-make-pad i) "let (")
  2957. (let ((p (point)))
  2958. (js2-print-ast (js2-let-node-vars n) 0)
  2959. (delete-region p (+ p 4)))
  2960. (insert ") ")
  2961. (js2-print-ast (js2-let-node-body n) i))
  2962. (cl-defstruct (js2-keyword-node
  2963. (:include js2-node)
  2964. (:constructor make-js2-keyword-node (&key type
  2965. (pos (js2-current-token-beg))
  2966. (len (- js2-ts-cursor pos)))))
  2967. "AST node representing a literal keyword such as `null'.
  2968. Used for `null', `this', `true', `false' and `debugger'.
  2969. The node type is set to js2-NULL, js2-THIS, etc.")
  2970. (js2--struct-put 'js2-keyword-node 'js2-visitor 'js2-visit-none)
  2971. (js2--struct-put 'js2-keyword-node 'js2-printer 'js2-print-keyword-node)
  2972. (defun js2-print-keyword-node (n i)
  2973. (insert (js2-make-pad i)
  2974. (let ((tt (js2-node-type n)))
  2975. (cond
  2976. ((= tt js2-THIS) "this")
  2977. ((= tt js2-SUPER) "super")
  2978. ((= tt js2-NULL) "null")
  2979. ((= tt js2-TRUE) "true")
  2980. ((= tt js2-FALSE) "false")
  2981. ((= tt js2-DEBUGGER) "debugger")
  2982. (t (error "Invalid keyword literal type: %d" tt))))))
  2983. (defsubst js2-this-or-super-node-p (node)
  2984. "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
  2985. (let ((type (js2-node-type node)))
  2986. (or (eq type js2-THIS) (eq type js2-SUPER))))
  2987. (cl-defstruct (js2-new-node
  2988. (:include js2-node)
  2989. (:constructor make-js2-new-node (&key (type js2-NEW)
  2990. (pos (js2-current-token-beg))
  2991. len target
  2992. args initializer
  2993. lp rp)))
  2994. "AST node for new-expression such as new Foo()."
  2995. target ; an identifier or reference
  2996. args ; a Lisp list of argument nodes
  2997. lp ; position of left-paren, nil if omitted
  2998. rp ; position of right-paren, nil if omitted
  2999. initializer) ; experimental Rhino syntax: optional `js2-object-node'
  3000. (js2--struct-put 'js2-new-node 'js2-visitor 'js2-visit-new-node)
  3001. (js2--struct-put 'js2-new-node 'js2-printer 'js2-print-new-node)
  3002. (defun js2-visit-new-node (n v)
  3003. (js2-visit-ast (js2-new-node-target n) v)
  3004. (dolist (arg (js2-new-node-args n))
  3005. (js2-visit-ast arg v))
  3006. (js2-visit-ast (js2-new-node-initializer n) v))
  3007. (defun js2-print-new-node (n i)
  3008. (insert (js2-make-pad i) "new ")
  3009. (js2-print-ast (js2-new-node-target n))
  3010. (insert "(")
  3011. (js2-print-list (js2-new-node-args n))
  3012. (insert ")")
  3013. (when (js2-new-node-initializer n)
  3014. (insert " ")
  3015. (js2-print-ast (js2-new-node-initializer n))))
  3016. (cl-defstruct (js2-name-node
  3017. (:include js2-node)
  3018. (:constructor make-js2-name-node (&key (type js2-NAME)
  3019. (pos (js2-current-token-beg))
  3020. (len (- js2-ts-cursor
  3021. (js2-current-token-beg)))
  3022. (name (js2-current-token-string)))))
  3023. "AST node for a JavaScript identifier"
  3024. name ; a string
  3025. scope) ; a `js2-scope' (optional, used for codegen)
  3026. (js2--struct-put 'js2-name-node 'js2-visitor 'js2-visit-none)
  3027. (js2--struct-put 'js2-name-node 'js2-printer 'js2-print-name-node)
  3028. (defun js2-print-name-node (n i)
  3029. (insert (js2-make-pad i)
  3030. (js2-name-node-name n)))
  3031. (defsubst js2-name-node-length (node)
  3032. "Return identifier length of NODE, a `js2-name-node'.
  3033. Returns 0 if NODE is nil or its identifier field is nil."
  3034. (if node
  3035. (length (js2-name-node-name node))
  3036. 0))
  3037. (cl-defstruct (js2-number-node
  3038. (:include js2-node)
  3039. (:constructor make-js2-number-node (&key (type js2-NUMBER)
  3040. (pos (js2-current-token-beg))
  3041. (len (- js2-ts-cursor
  3042. (js2-current-token-beg)))
  3043. (value (js2-current-token-string))
  3044. (num-value (js2-token-number
  3045. (js2-current-token)))
  3046. (num-base (js2-token-number-base
  3047. (js2-current-token)))
  3048. (legacy-octal-p (js2-token-number-legacy-octal-p
  3049. (js2-current-token))))))
  3050. "AST node for a number literal."
  3051. value ; the original string, e.g. "6.02e23"
  3052. num-value ; the parsed number value
  3053. num-base ; the number's base
  3054. legacy-octal-p) ; whether the number is a legacy octal (0123 instead of 0o123)
  3055. (js2--struct-put 'js2-number-node 'js2-visitor 'js2-visit-none)
  3056. (js2--struct-put 'js2-number-node 'js2-printer 'js2-print-number-node)
  3057. (defun js2-print-number-node (n i)
  3058. (insert (js2-make-pad i)
  3059. (number-to-string (js2-number-node-num-value n))))
  3060. (cl-defstruct (js2-regexp-node
  3061. (:include js2-node)
  3062. (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
  3063. (pos (js2-current-token-beg))
  3064. (len (- js2-ts-cursor
  3065. (js2-current-token-beg)))
  3066. value flags)))
  3067. "AST node for a regular expression literal."
  3068. value ; the regexp string, without // delimiters
  3069. flags) ; a string of flags, e.g. `mi'.
  3070. (js2--struct-put 'js2-regexp-node 'js2-visitor 'js2-visit-none)
  3071. (js2--struct-put 'js2-regexp-node 'js2-printer 'js2-print-regexp)
  3072. (defun js2-print-regexp (n i)
  3073. (insert (js2-make-pad i)
  3074. "/"
  3075. (js2-regexp-node-value n)
  3076. "/")
  3077. (if (js2-regexp-node-flags n)
  3078. (insert (js2-regexp-node-flags n))))
  3079. (cl-defstruct (js2-string-node
  3080. (:include js2-node)
  3081. (:constructor make-js2-string-node (&key (type js2-STRING)
  3082. (pos (js2-current-token-beg))
  3083. (len (- js2-ts-cursor
  3084. (js2-current-token-beg)))
  3085. (value (js2-current-token-string)))))
  3086. "String literal.
  3087. Escape characters are not evaluated; e.g. \n is 2 chars in value field.
  3088. You can tell the quote type by looking at the first character."
  3089. value) ; the characters of the string, including the quotes
  3090. (js2--struct-put 'js2-string-node 'js2-visitor 'js2-visit-none)
  3091. (js2--struct-put 'js2-string-node 'js2-printer 'js2-print-string-node)
  3092. (defun js2-print-string-node (n i)
  3093. (insert (js2-make-pad i)
  3094. (js2-node-string n)))
  3095. (cl-defstruct (js2-template-node
  3096. (:include js2-node)
  3097. (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
  3098. pos len kids)))
  3099. "Template literal."
  3100. kids) ; `js2-string-node' is used for string segments, other nodes
  3101. ; for substitutions inside.
  3102. (js2--struct-put 'js2-template-node 'js2-visitor 'js2-visit-template)
  3103. (js2--struct-put 'js2-template-node 'js2-printer 'js2-print-template)
  3104. (defun js2-visit-template (n callback)
  3105. (dolist (kid (js2-template-node-kids n))
  3106. (js2-visit-ast kid callback)))
  3107. (defun js2-print-template (n i)
  3108. (insert (js2-make-pad i))
  3109. (dolist (kid (js2-template-node-kids n))
  3110. (if (js2-string-node-p kid)
  3111. (insert (js2-node-string kid))
  3112. (js2-print-ast kid))))
  3113. (cl-defstruct (js2-tagged-template-node
  3114. (:include js2-node)
  3115. (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
  3116. pos len tag template)))
  3117. "Tagged template literal."
  3118. tag ; `js2-node' with the tag expression.
  3119. template) ; `js2-template-node' with the template.
  3120. (js2--struct-put 'js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
  3121. (js2--struct-put 'js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
  3122. (defun js2-visit-tagged-template (n callback)
  3123. (js2-visit-ast (js2-tagged-template-node-tag n) callback)
  3124. (js2-visit-ast (js2-tagged-template-node-template n) callback))
  3125. (defun js2-print-tagged-template (n i)
  3126. (insert (js2-make-pad i))
  3127. (js2-print-ast (js2-tagged-template-node-tag n))
  3128. (js2-print-ast (js2-tagged-template-node-template n)))
  3129. (cl-defstruct (js2-array-node
  3130. (:include js2-node)
  3131. (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
  3132. (pos js2-ts-cursor)
  3133. len elems)))
  3134. "AST node for an array literal."
  3135. elems) ; list of expressions. [foo,,bar] yields a nil middle element.
  3136. (js2--struct-put 'js2-array-node 'js2-visitor 'js2-visit-array-node)
  3137. (js2--struct-put 'js2-array-node 'js2-printer 'js2-print-array-node)
  3138. (defun js2-visit-array-node (n v)
  3139. (dolist (e (js2-array-node-elems n))
  3140. (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
  3141. (defun js2-print-array-node (n i)
  3142. (insert (js2-make-pad i) "[")
  3143. (let ((elems (js2-array-node-elems n)))
  3144. (js2-print-list elems)
  3145. (when (and elems (null (car (last elems))))
  3146. (insert ",")))
  3147. (insert "]"))
  3148. (cl-defstruct (js2-object-node
  3149. (:include js2-node)
  3150. (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
  3151. (pos js2-ts-cursor)
  3152. len
  3153. elems)))
  3154. "AST node for an object literal expression.
  3155. `elems' is a list of `js2-object-prop-node'."
  3156. elems)
  3157. (js2--struct-put 'js2-object-node 'js2-visitor 'js2-visit-object-node)
  3158. (js2--struct-put 'js2-object-node 'js2-printer 'js2-print-object-node)
  3159. (defun js2-visit-object-node (n v)
  3160. (dolist (e (js2-object-node-elems n))
  3161. (js2-visit-ast e v)))
  3162. (defun js2-print-object-node (n i)
  3163. (insert (js2-make-pad i) "{")
  3164. (js2-print-list (js2-object-node-elems n))
  3165. (insert "}"))
  3166. (cl-defstruct (js2-class-node
  3167. (:include js2-object-node)
  3168. (:constructor make-js2-class-node (&key (type js2-CLASS)
  3169. (pos js2-ts-cursor)
  3170. (form 'CLASS_STATEMENT)
  3171. (name "")
  3172. extends len elems)))
  3173. "AST node for an class expression.
  3174. `elems' is a list of `js2-object-prop-node', and `extends' is an
  3175. optional `js2-expr-node'"
  3176. form ; CLASS_{STATEMENT|EXPRESSION}
  3177. name ; class name (a `js2-node-name', or nil if anonymous)
  3178. extends ; class heritage (a `js2-expr-node', or nil if none)
  3179. )
  3180. (js2--struct-put 'js2-class-node 'js2-visitor 'js2-visit-class-node)
  3181. (js2--struct-put 'js2-class-node 'js2-printer 'js2-print-class-node)
  3182. (defun js2-visit-class-node (n v)
  3183. (js2-visit-ast (js2-class-node-name n) v)
  3184. (js2-visit-ast (js2-class-node-extends n) v)
  3185. (dolist (e (js2-class-node-elems n))
  3186. (js2-visit-ast e v)))
  3187. (defun js2-print-class-node (n i)
  3188. (let* ((pad (js2-make-pad i))
  3189. (name (js2-class-node-name n))
  3190. (extends (js2-class-node-extends n))
  3191. (elems (js2-class-node-elems n)))
  3192. (insert pad "class")
  3193. (when name
  3194. (insert " ")
  3195. (js2-print-ast name 0))
  3196. (when extends
  3197. (insert " extends ")
  3198. (js2-print-ast extends))
  3199. (insert " {")
  3200. (dolist (elem elems)
  3201. (insert "\n")
  3202. (if (js2-node-get-prop elem 'STATIC)
  3203. (progn (insert (js2-make-pad (1+ i)) "static ")
  3204. (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
  3205. (js2-print-ast elem (1+ i))))
  3206. (insert "\n" pad "}")))
  3207. (cl-defstruct (js2-computed-prop-name-node
  3208. (:include js2-node)
  3209. (:constructor make-js2-computed-prop-name-node
  3210. (&key
  3211. (type js2-LB)
  3212. expr
  3213. (pos (js2-current-token-beg))
  3214. (len (- js2-ts-cursor
  3215. (js2-current-token-beg))))))
  3216. "AST node for a `ComputedPropertyName'."
  3217. expr)
  3218. (js2--struct-put 'js2-computed-prop-name-node 'js2-visitor 'js2-visit-computed-prop-name-node)
  3219. (js2--struct-put 'js2-computed-prop-name-node 'js2-printer 'js2-print-computed-prop-name-node)
  3220. (defun js2-visit-computed-prop-name-node (n v)
  3221. (js2-visit-ast (js2-computed-prop-name-node-expr n) v))
  3222. (defun js2-print-computed-prop-name-node (n i)
  3223. (insert (js2-make-pad i) "[")
  3224. (js2-print-ast (js2-computed-prop-name-node-expr n) 0)
  3225. (insert "]"))
  3226. (cl-defstruct (js2-object-prop-node
  3227. (:include js2-infix-node)
  3228. (:constructor make-js2-object-prop-node (&key (type js2-COLON)
  3229. (pos js2-ts-cursor)
  3230. len left
  3231. right op-pos)))
  3232. "AST node for an object literal prop:value entry.
  3233. The `left' field is the property: a name node, string node,
  3234. number node or expression node. The `right' field is a
  3235. `js2-node' representing the initializer value. If the property
  3236. is abbreviated, the node's `SHORTHAND' property is non-nil and
  3237. both fields have the same value.")
  3238. (js2--struct-put 'js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
  3239. (js2--struct-put 'js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
  3240. (defun js2-print-object-prop-node (n i)
  3241. (let* ((left (js2-object-prop-node-left n))
  3242. (right (js2-object-prop-node-right n)))
  3243. (js2-print-ast left i)
  3244. (if (not (js2-node-get-prop n 'SHORTHAND))
  3245. (progn
  3246. (insert ": ")
  3247. (js2-print-ast right 0)))))
  3248. (cl-defstruct (js2-method-node
  3249. (:include js2-infix-node)
  3250. (:constructor make-js2-method-node (&key (pos js2-ts-cursor)
  3251. len left right)))
  3252. "AST node for a method in an object literal or a class body.
  3253. The `left' field is the `js2-name-node' naming the method.
  3254. The `right' field is always an anonymous `js2-function-node' with a node
  3255. property `METHOD_TYPE' set to 'GET or 'SET. ")
  3256. (js2--struct-put 'js2-method-node 'js2-visitor 'js2-visit-infix-node)
  3257. (js2--struct-put 'js2-method-node 'js2-printer 'js2-print-method)
  3258. (defun js2-print-method (n i)
  3259. (let* ((pad (js2-make-pad i))
  3260. (left (js2-method-node-left n))
  3261. (right (js2-method-node-right n))
  3262. (type (js2-node-get-prop right 'METHOD_TYPE)))
  3263. (insert pad)
  3264. (when type
  3265. (insert (cdr (assoc type '((GET . "get ")
  3266. (SET . "set ")
  3267. (ASYNC . "async ")
  3268. (FUNCTION . ""))))))
  3269. (when (and (js2-function-node-p right)
  3270. (eq 'STAR (js2-function-node-generator-type right)))
  3271. (insert "*"))
  3272. (js2-print-ast left 0)
  3273. (js2-print-ast right 0)))
  3274. (cl-defstruct (js2-prop-get-node
  3275. (:include js2-infix-node)
  3276. (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
  3277. (pos js2-ts-cursor)
  3278. len left right)))
  3279. "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
  3280. (js2--struct-put 'js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
  3281. (js2--struct-put 'js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
  3282. (defun js2-visit-prop-get-node (n v)
  3283. (js2-visit-ast (js2-prop-get-node-left n) v)
  3284. (js2-visit-ast (js2-prop-get-node-right n) v))
  3285. (defun js2-print-prop-get-node (n i)
  3286. (insert (js2-make-pad i))
  3287. (js2-print-ast (js2-prop-get-node-left n) 0)
  3288. (insert ".")
  3289. (js2-print-ast (js2-prop-get-node-right n) 0))
  3290. (cl-defstruct (js2-elem-get-node
  3291. (:include js2-node)
  3292. (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
  3293. (pos js2-ts-cursor)
  3294. len target element
  3295. lb rb)))
  3296. "AST node for an array index expression such as foo[bar]."
  3297. target ; a `js2-node' - the expression preceding the "."
  3298. element ; a `js2-node' - the expression in brackets
  3299. lb ; position of left-bracket, nil if omitted
  3300. rb) ; position of right-bracket, nil if omitted
  3301. (js2--struct-put 'js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
  3302. (js2--struct-put 'js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
  3303. (defun js2-visit-elem-get-node (n v)
  3304. (js2-visit-ast (js2-elem-get-node-target n) v)
  3305. (js2-visit-ast (js2-elem-get-node-element n) v))
  3306. (defun js2-print-elem-get-node (n i)
  3307. (insert (js2-make-pad i))
  3308. (js2-print-ast (js2-elem-get-node-target n) 0)
  3309. (insert "[")
  3310. (js2-print-ast (js2-elem-get-node-element n) 0)
  3311. (insert "]"))
  3312. (cl-defstruct (js2-call-node
  3313. (:include js2-node)
  3314. (:constructor make-js2-call-node (&key (type js2-CALL)
  3315. (pos js2-ts-cursor)
  3316. len target args
  3317. lp rp)))
  3318. "AST node for a JavaScript function call."
  3319. target ; a `js2-node' evaluating to the function to call
  3320. args ; a Lisp list of `js2-node' arguments
  3321. lp ; position of open-paren, or nil if missing
  3322. rp) ; position of close-paren, or nil if missing
  3323. (js2--struct-put 'js2-call-node 'js2-visitor 'js2-visit-call-node)
  3324. (js2--struct-put 'js2-call-node 'js2-printer 'js2-print-call-node)
  3325. (defun js2-visit-call-node (n v)
  3326. (js2-visit-ast (js2-call-node-target n) v)
  3327. (dolist (arg (js2-call-node-args n))
  3328. (js2-visit-ast arg v)))
  3329. (defun js2-print-call-node (n i)
  3330. (insert (js2-make-pad i))
  3331. (js2-print-ast (js2-call-node-target n) 0)
  3332. (insert "(")
  3333. (js2-print-list (js2-call-node-args n))
  3334. (insert ")"))
  3335. (cl-defstruct (js2-yield-node
  3336. (:include js2-node)
  3337. (:constructor make-js2-yield-node (&key (type js2-YIELD)
  3338. (pos js2-ts-cursor)
  3339. len value star-p)))
  3340. "AST node for yield statement or expression."
  3341. star-p ; whether it's yield*
  3342. value) ; optional: value to be yielded
  3343. (js2--struct-put 'js2-yield-node 'js2-visitor 'js2-visit-yield-node)
  3344. (js2--struct-put 'js2-yield-node 'js2-printer 'js2-print-yield-node)
  3345. (defun js2-visit-yield-node (n v)
  3346. (js2-visit-ast (js2-yield-node-value n) v))
  3347. (defun js2-print-yield-node (n i)
  3348. (insert (js2-make-pad i))
  3349. (insert "yield")
  3350. (when (js2-yield-node-star-p n)
  3351. (insert "*"))
  3352. (when (js2-yield-node-value n)
  3353. (insert " ")
  3354. (js2-print-ast (js2-yield-node-value n) 0)))
  3355. (cl-defstruct (js2-paren-node
  3356. (:include js2-node)
  3357. (:constructor make-js2-paren-node (&key (type js2-LP)
  3358. (pos js2-ts-cursor)
  3359. len expr)))
  3360. "AST node for a parenthesized expression.
  3361. In particular, used when the parens are syntactically optional,
  3362. as opposed to required parens such as those enclosing an if-conditional."
  3363. expr) ; `js2-node'
  3364. (js2--struct-put 'js2-paren-node 'js2-visitor 'js2-visit-paren-node)
  3365. (js2--struct-put 'js2-paren-node 'js2-printer 'js2-print-paren-node)
  3366. (defun js2-visit-paren-node (n v)
  3367. (js2-visit-ast (js2-paren-node-expr n) v))
  3368. (defun js2-print-paren-node (n i)
  3369. (insert (js2-make-pad i))
  3370. (insert "(")
  3371. (js2-print-ast (js2-paren-node-expr n) 0)
  3372. (insert ")"))
  3373. (cl-defstruct (js2-comp-node
  3374. (:include js2-scope)
  3375. (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
  3376. (pos js2-ts-cursor)
  3377. len result
  3378. loops filters
  3379. form)))
  3380. "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
  3381. result ; result expression (just after left-bracket)
  3382. loops ; a Lisp list of `js2-comp-loop-node'
  3383. filters ; a Lisp list of guard/filter expressions
  3384. form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
  3385. ; SpiderMonkey also supports "legacy generator expressions", but we dont.
  3386. )
  3387. (js2--struct-put 'js2-comp-node 'js2-visitor 'js2-visit-comp-node)
  3388. (js2--struct-put 'js2-comp-node 'js2-printer 'js2-print-comp-node)
  3389. (defun js2-visit-comp-node (n v)
  3390. (js2-visit-ast (js2-comp-node-result n) v)
  3391. (dolist (l (js2-comp-node-loops n))
  3392. (js2-visit-ast l v))
  3393. (dolist (f (js2-comp-node-filters n))
  3394. (js2-visit-ast f v)))
  3395. (defun js2-print-comp-node (n i)
  3396. (let ((pad (js2-make-pad i))
  3397. (result (js2-comp-node-result n))
  3398. (loops (js2-comp-node-loops n))
  3399. (filters (js2-comp-node-filters n))
  3400. (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
  3401. (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
  3402. (insert pad (if gen-p "(" "["))
  3403. (when legacy-p
  3404. (js2-print-ast result 0))
  3405. (dolist (l loops)
  3406. (when legacy-p
  3407. (insert " "))
  3408. (js2-print-ast l 0)
  3409. (unless legacy-p
  3410. (insert " ")))
  3411. (dolist (f filters)
  3412. (when legacy-p
  3413. (insert " "))
  3414. (insert "if (")
  3415. (js2-print-ast f 0)
  3416. (insert ")")
  3417. (unless legacy-p
  3418. (insert " ")))
  3419. (unless legacy-p
  3420. (js2-print-ast result 0))
  3421. (insert (if gen-p ")" "]"))))
  3422. (cl-defstruct (js2-comp-loop-node
  3423. (:include js2-for-in-node)
  3424. (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
  3425. (pos js2-ts-cursor)
  3426. len iterator
  3427. object in-pos
  3428. foreach-p
  3429. each-pos
  3430. forof-p
  3431. lp rp)))
  3432. "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
  3433. (js2--struct-put 'js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
  3434. (js2--struct-put 'js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
  3435. (defun js2-visit-comp-loop (n v)
  3436. (js2-visit-ast (js2-comp-loop-node-iterator n) v)
  3437. (js2-visit-ast (js2-comp-loop-node-object n) v))
  3438. (defun js2-print-comp-loop (n _i)
  3439. (insert "for ")
  3440. (when (js2-comp-loop-node-foreach-p n) (insert "each "))
  3441. (insert "(")
  3442. (js2-print-ast (js2-comp-loop-node-iterator n) 0)
  3443. (insert (if (js2-comp-loop-node-forof-p n)
  3444. " of " " in "))
  3445. (js2-print-ast (js2-comp-loop-node-object n) 0)
  3446. (insert ")"))
  3447. (cl-defstruct (js2-empty-expr-node
  3448. (:include js2-node)
  3449. (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
  3450. (pos (js2-current-token-beg))
  3451. len)))
  3452. "AST node for an empty expression.")
  3453. (js2--struct-put 'js2-empty-expr-node 'js2-visitor 'js2-visit-none)
  3454. (js2--struct-put 'js2-empty-expr-node 'js2-printer 'js2-print-none)
  3455. (cl-defstruct (js2-xml-node
  3456. (:include js2-block-node)
  3457. (:constructor make-js2-xml-node (&key (type js2-XML)
  3458. (pos (js2-current-token-beg))
  3459. len kids)))
  3460. "AST node for initial parse of E4X literals.
  3461. The kids field is a list of XML fragments, each a `js2-string-node' or
  3462. a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
  3463. (js2--struct-put 'js2-xml-node 'js2-visitor 'js2-visit-block)
  3464. (js2--struct-put 'js2-xml-node 'js2-printer 'js2-print-xml-node)
  3465. (defun js2-print-xml-node (n i)
  3466. (dolist (kid (js2-xml-node-kids n))
  3467. (js2-print-ast kid i)))
  3468. (cl-defstruct (js2-xml-js-expr-node
  3469. (:include js2-xml-node)
  3470. (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
  3471. (pos js2-ts-cursor)
  3472. len expr)))
  3473. "AST node for an embedded JavaScript {expression} in an E4X literal.
  3474. The start and end fields correspond to the curly-braces."
  3475. expr) ; a `js2-expr-node' of some sort
  3476. (js2--struct-put 'js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
  3477. (js2--struct-put 'js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
  3478. (defun js2-visit-xml-js-expr (n v)
  3479. (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
  3480. (defun js2-print-xml-js-expr (n i)
  3481. (insert (js2-make-pad i))
  3482. (insert "{")
  3483. (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
  3484. (insert "}"))
  3485. (cl-defstruct (js2-xml-dot-query-node
  3486. (:include js2-infix-node)
  3487. (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
  3488. (pos js2-ts-cursor)
  3489. op-pos len left
  3490. right rp)))
  3491. "AST node for an E4X foo.(bar) filter expression.
  3492. Note that the left-paren is automatically the character immediately
  3493. following the dot (.) in the operator. No whitespace is permitted
  3494. between the dot and the lp by the scanner."
  3495. rp)
  3496. (js2--struct-put 'js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
  3497. (js2--struct-put 'js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
  3498. (defun js2-print-xml-dot-query (n i)
  3499. (insert (js2-make-pad i))
  3500. (js2-print-ast (js2-xml-dot-query-node-left n) 0)
  3501. (insert ".(")
  3502. (js2-print-ast (js2-xml-dot-query-node-right n) 0)
  3503. (insert ")"))
  3504. (cl-defstruct (js2-xml-ref-node
  3505. (:include js2-node)
  3506. (:constructor nil)) ; abstract
  3507. "Base type for E4X XML attribute-access or property-get expressions.
  3508. Such expressions can take a variety of forms. The general syntax has
  3509. three parts:
  3510. - (optional) an @ (specifying an attribute access)
  3511. - (optional) a namespace (a `js2-name-node') and double-colon
  3512. - (required) either a `js2-name-node' or a bracketed [expression]
  3513. The property-name expressions (examples: ns::name, @name) are
  3514. represented as `js2-xml-prop-ref' nodes. The bracketed-expression
  3515. versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
  3516. This node type (or more specifically, its subclasses) will sometimes
  3517. be the right-hand child of a `js2-prop-get-node' or a
  3518. `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
  3519. The `js2-xml-ref-node' may also be a standalone primary expression with
  3520. no explicit target, which is valid in certain expression contexts such as
  3521. company..employee.(@id < 100)
  3522. in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
  3523. expression whose parent is a `js2-xml-dot-query-node'."
  3524. namespace
  3525. at-pos
  3526. colon-pos)
  3527. (defsubst js2-xml-ref-node-attr-access-p (node)
  3528. "Return non-nil if this expression began with an @-token."
  3529. (and (numberp (js2-xml-ref-node-at-pos node))
  3530. (cl-plusp (js2-xml-ref-node-at-pos node))))
  3531. (cl-defstruct (js2-xml-prop-ref-node
  3532. (:include js2-xml-ref-node)
  3533. (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
  3534. (pos (js2-current-token-beg))
  3535. len propname
  3536. namespace at-pos
  3537. colon-pos)))
  3538. "AST node for an E4X XML [expr] property-ref expression.
  3539. The JavaScript syntax is an optional @, an optional ns::, and a name.
  3540. [ '@' ] [ name '::' ] name
  3541. Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
  3542. @ns::*, @*::attr, @*::*, and @*.
  3543. The node starts at the @ token, if present. Otherwise it starts at the
  3544. namespace name. The node bounds extend through the closing right-bracket,
  3545. or if it is missing due to a syntax error, through the end of the index
  3546. expression."
  3547. propname)
  3548. (js2--struct-put 'js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
  3549. (js2--struct-put 'js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
  3550. (defun js2-visit-xml-prop-ref-node (n v)
  3551. (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
  3552. (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
  3553. (defun js2-print-xml-prop-ref-node (n i)
  3554. (insert (js2-make-pad i))
  3555. (if (js2-xml-ref-node-attr-access-p n)
  3556. (insert "@"))
  3557. (when (js2-xml-prop-ref-node-namespace n)
  3558. (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
  3559. (insert "::"))
  3560. (if (js2-xml-prop-ref-node-propname n)
  3561. (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
  3562. (cl-defstruct (js2-xml-elem-ref-node
  3563. (:include js2-xml-ref-node)
  3564. (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
  3565. (pos (js2-current-token-beg))
  3566. len expr lb rb
  3567. namespace at-pos
  3568. colon-pos)))
  3569. "AST node for an E4X XML [expr] member-ref expression.
  3570. Syntax:
  3571. [ '@' ] [ name '::' ] '[' expr ']'
  3572. Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
  3573. Note that the form [expr] (i.e. no namespace or attribute-qualifier)
  3574. is not a legal E4X XML element-ref expression, since it's already used
  3575. for standard JavaScript element-get array indexing. Hence, a
  3576. `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
  3577. non-nil namespace node, or both.
  3578. The node starts at the @ token, if present. Otherwise it starts
  3579. at the namespace name. The node bounds extend through the closing
  3580. right-bracket, or if it is missing due to a syntax error, through the
  3581. end of the index expression."
  3582. expr ; the bracketed index expression
  3583. lb
  3584. rb)
  3585. (js2--struct-put 'js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
  3586. (js2--struct-put 'js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
  3587. (defun js2-visit-xml-elem-ref-node (n v)
  3588. (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
  3589. (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
  3590. (defun js2-print-xml-elem-ref-node (n i)
  3591. (insert (js2-make-pad i))
  3592. (if (js2-xml-ref-node-attr-access-p n)
  3593. (insert "@"))
  3594. (when (js2-xml-elem-ref-node-namespace n)
  3595. (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
  3596. (insert "::"))
  3597. (insert "[")
  3598. (if (js2-xml-elem-ref-node-expr n)
  3599. (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
  3600. (insert "]"))
  3601. ;;; Placeholder nodes for when we try parsing the XML literals structurally.
  3602. (cl-defstruct (js2-xml-start-tag-node
  3603. (:include js2-xml-node)
  3604. (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
  3605. (pos js2-ts-cursor)
  3606. len name attrs kids
  3607. empty-p)))
  3608. "AST node for an XML start-tag. Not currently used.
  3609. The `kids' field is a Lisp list of child content nodes."
  3610. name ; a `js2-xml-name-node'
  3611. attrs ; a Lisp list of `js2-xml-attr-node'
  3612. empty-p) ; t if this is an empty element such as <foo bar="baz"/>
  3613. (js2--struct-put 'js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
  3614. (js2--struct-put 'js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
  3615. (defun js2-visit-xml-start-tag (n v)
  3616. (js2-visit-ast (js2-xml-start-tag-node-name n) v)
  3617. (dolist (attr (js2-xml-start-tag-node-attrs n))
  3618. (js2-visit-ast attr v))
  3619. (js2-visit-block n v))
  3620. (defun js2-print-xml-start-tag (n i)
  3621. (insert (js2-make-pad i) "<")
  3622. (js2-print-ast (js2-xml-start-tag-node-name n) 0)
  3623. (when (js2-xml-start-tag-node-attrs n)
  3624. (insert " ")
  3625. (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
  3626. (insert ">"))
  3627. ;; I -think- I'm going to make the parent node the corresponding start-tag,
  3628. ;; and add the end-tag to the kids list of the parent as well.
  3629. (cl-defstruct (js2-xml-end-tag-node
  3630. (:include js2-xml-node)
  3631. (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
  3632. (pos js2-ts-cursor)
  3633. len name)))
  3634. "AST node for an XML end-tag. Not currently used."
  3635. name) ; a `js2-xml-name-node'
  3636. (js2--struct-put 'js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
  3637. (js2--struct-put 'js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
  3638. (defun js2-visit-xml-end-tag (n v)
  3639. (js2-visit-ast (js2-xml-end-tag-node-name n) v))
  3640. (defun js2-print-xml-end-tag (n i)
  3641. (insert (js2-make-pad i))
  3642. (insert "</")
  3643. (js2-print-ast (js2-xml-end-tag-node-name n) 0)
  3644. (insert ">"))
  3645. (cl-defstruct (js2-xml-name-node
  3646. (:include js2-xml-node)
  3647. (:constructor make-js2-xml-name-node (&key (type js2-XML)
  3648. (pos js2-ts-cursor)
  3649. len namespace kids)))
  3650. "AST node for an E4X XML name. Not currently used.
  3651. Any XML name can be qualified with a namespace, hence the namespace field.
  3652. Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
  3653. The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
  3654. For a simple name, the kids list has exactly one node, a `js2-name-node'."
  3655. namespace) ; a `js2-string-node'
  3656. (js2--struct-put 'js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
  3657. (js2--struct-put 'js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
  3658. (defun js2-visit-xml-name-node (n v)
  3659. (js2-visit-ast (js2-xml-name-node-namespace n) v))
  3660. (defun js2-print-xml-name-node (n i)
  3661. (insert (js2-make-pad i))
  3662. (when (js2-xml-name-node-namespace n)
  3663. (js2-print-ast (js2-xml-name-node-namespace n) 0)
  3664. (insert "::"))
  3665. (dolist (kid (js2-xml-name-node-kids n))
  3666. (js2-print-ast kid 0)))
  3667. (cl-defstruct (js2-xml-pi-node
  3668. (:include js2-xml-node)
  3669. (:constructor make-js2-xml-pi-node (&key (type js2-XML)
  3670. (pos js2-ts-cursor)
  3671. len name attrs)))
  3672. "AST node for an E4X XML processing instruction. Not currently used."
  3673. name ; a `js2-xml-name-node'
  3674. attrs) ; a list of `js2-xml-attr-node'
  3675. (js2--struct-put 'js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
  3676. (js2--struct-put 'js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
  3677. (defun js2-visit-xml-pi-node (n v)
  3678. (js2-visit-ast (js2-xml-pi-node-name n) v)
  3679. (dolist (attr (js2-xml-pi-node-attrs n))
  3680. (js2-visit-ast attr v)))
  3681. (defun js2-print-xml-pi-node (n i)
  3682. (insert (js2-make-pad i) "<?")
  3683. (js2-print-ast (js2-xml-pi-node-name n))
  3684. (when (js2-xml-pi-node-attrs n)
  3685. (insert " ")
  3686. (js2-print-list (js2-xml-pi-node-attrs n)))
  3687. (insert "?>"))
  3688. (cl-defstruct (js2-xml-cdata-node
  3689. (:include js2-xml-node)
  3690. (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
  3691. (pos js2-ts-cursor)
  3692. len content)))
  3693. "AST node for a CDATA escape section. Not currently used."
  3694. content) ; a `js2-string-node' with node-property 'quote-type 'cdata
  3695. (js2--struct-put 'js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
  3696. (js2--struct-put 'js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
  3697. (defun js2-visit-xml-cdata-node (n v)
  3698. (js2-visit-ast (js2-xml-cdata-node-content n) v))
  3699. (defun js2-print-xml-cdata-node (n i)
  3700. (insert (js2-make-pad i))
  3701. (js2-print-ast (js2-xml-cdata-node-content n)))
  3702. (cl-defstruct (js2-xml-attr-node
  3703. (:include js2-xml-node)
  3704. (:constructor make-js2-attr-node (&key (type js2-XML)
  3705. (pos js2-ts-cursor)
  3706. len name value
  3707. eq-pos quote-type)))
  3708. "AST node representing a foo='bar' XML attribute value. Not yet used."
  3709. name ; a `js2-xml-name-node'
  3710. value ; a `js2-xml-name-node'
  3711. eq-pos ; buffer position of "=" sign
  3712. quote-type) ; 'single or 'double
  3713. (js2--struct-put 'js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
  3714. (js2--struct-put 'js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
  3715. (defun js2-visit-xml-attr-node (n v)
  3716. (js2-visit-ast (js2-xml-attr-node-name n) v)
  3717. (js2-visit-ast (js2-xml-attr-node-value n) v))
  3718. (defun js2-print-xml-attr-node (n i)
  3719. (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
  3720. "'"
  3721. "\"")))
  3722. (insert (js2-make-pad i))
  3723. (js2-print-ast (js2-xml-attr-node-name n) 0)
  3724. (insert "=" quote)
  3725. (js2-print-ast (js2-xml-attr-node-value n) 0)
  3726. (insert quote)))
  3727. (cl-defstruct (js2-xml-text-node
  3728. (:include js2-xml-node)
  3729. (:constructor make-js2-text-node (&key (type js2-XML)
  3730. (pos js2-ts-cursor)
  3731. len content)))
  3732. "AST node for an E4X XML text node. Not currently used."
  3733. content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
  3734. (js2--struct-put 'js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
  3735. (js2--struct-put 'js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
  3736. (defun js2-visit-xml-text-node (n v)
  3737. (js2-visit-ast (js2-xml-text-node-content n) v))
  3738. (defun js2-print-xml-text-node (n i)
  3739. (insert (js2-make-pad i))
  3740. (dolist (kid (js2-xml-text-node-content n))
  3741. (js2-print-ast kid)))
  3742. (cl-defstruct (js2-xml-comment-node
  3743. (:include js2-xml-node)
  3744. (:constructor make-js2-xml-comment-node (&key (type js2-XML)
  3745. (pos js2-ts-cursor)
  3746. len)))
  3747. "AST node for E4X XML comment. Not currently used.")
  3748. (js2--struct-put 'js2-xml-comment-node 'js2-visitor 'js2-visit-none)
  3749. (js2--struct-put 'js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
  3750. (defun js2-print-xml-comment (n i)
  3751. (insert (js2-make-pad i)
  3752. (js2-node-string n)))
  3753. ;;; Node utilities
  3754. (defsubst js2-node-line (n)
  3755. "Fetch the source line number at the start of node N.
  3756. This is O(n) in the length of the source buffer; use prudently."
  3757. (1+ (count-lines (point-min) (js2-node-abs-pos n))))
  3758. (defsubst js2-block-node-kid (n i)
  3759. "Return child I of node N, or nil if there aren't that many."
  3760. (nth i (js2-block-node-kids n)))
  3761. (defsubst js2-block-node-first (n)
  3762. "Return first child of block node N, or nil if there is none."
  3763. (cl-first (js2-block-node-kids n)))
  3764. (defun js2-node-root (n)
  3765. "Return the root of the AST containing N.
  3766. If N has no parent pointer, returns N."
  3767. (let ((parent (js2-node-parent n)))
  3768. (if parent
  3769. (js2-node-root parent)
  3770. n)))
  3771. (defsubst js2-node-short-name (n)
  3772. "Return the short name of node N as a string, e.g. `js2-if-node'."
  3773. (let ((name (symbol-name (aref n 0))))
  3774. (if (string-prefix-p "cl-struct-" name)
  3775. (substring (symbol-name (aref n 0))
  3776. (length "cl-struct-"))
  3777. name)))
  3778. (defun js2-node-child-list (node)
  3779. "Return the child list for NODE, a Lisp list of nodes.
  3780. Works for block nodes, array nodes, obj literals, funarg lists,
  3781. var decls and try nodes (for catch clauses). Note that you should call
  3782. `js2-block-node-kids' on the function body for the body statements.
  3783. Returns nil for zero-length child lists or unsupported nodes."
  3784. (cond
  3785. ((js2-function-node-p node)
  3786. (js2-function-node-params node))
  3787. ((js2-block-node-p node)
  3788. (js2-block-node-kids node))
  3789. ((js2-try-node-p node)
  3790. (js2-try-node-catch-clauses node))
  3791. ((js2-array-node-p node)
  3792. (js2-array-node-elems node))
  3793. ((js2-object-node-p node)
  3794. (js2-object-node-elems node))
  3795. ((js2-call-node-p node)
  3796. (js2-call-node-args node))
  3797. ((js2-new-node-p node)
  3798. (js2-new-node-args node))
  3799. ((js2-var-decl-node-p node)
  3800. (js2-var-decl-node-kids node))
  3801. (t
  3802. nil)))
  3803. (defun js2-node-set-child-list (node kids)
  3804. "Set the child list for NODE to KIDS."
  3805. (cond
  3806. ((js2-function-node-p node)
  3807. (setf (js2-function-node-params node) kids))
  3808. ((js2-block-node-p node)
  3809. (setf (js2-block-node-kids node) kids))
  3810. ((js2-try-node-p node)
  3811. (setf (js2-try-node-catch-clauses node) kids))
  3812. ((js2-array-node-p node)
  3813. (setf (js2-array-node-elems node) kids))
  3814. ((js2-object-node-p node)
  3815. (setf (js2-object-node-elems node) kids))
  3816. ((js2-call-node-p node)
  3817. (setf (js2-call-node-args node) kids))
  3818. ((js2-new-node-p node)
  3819. (setf (js2-new-node-args node) kids))
  3820. ((js2-var-decl-node-p node)
  3821. (setf (js2-var-decl-node-kids node) kids))
  3822. (t
  3823. (error "Unsupported node type: %s" (js2-node-short-name node))))
  3824. kids)
  3825. ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
  3826. (defconst js2-paren-expr-nodes
  3827. '(cl-struct-js2-comp-loop-node
  3828. cl-struct-js2-comp-node
  3829. cl-struct-js2-call-node
  3830. cl-struct-js2-catch-node
  3831. cl-struct-js2-do-node
  3832. cl-struct-js2-elem-get-node
  3833. cl-struct-js2-for-in-node
  3834. cl-struct-js2-for-node
  3835. cl-struct-js2-function-node
  3836. cl-struct-js2-if-node
  3837. cl-struct-js2-let-node
  3838. cl-struct-js2-new-node
  3839. cl-struct-js2-paren-node
  3840. cl-struct-js2-switch-node
  3841. cl-struct-js2-while-node
  3842. cl-struct-js2-with-node
  3843. cl-struct-js2-xml-dot-query-node)
  3844. "Node types that can have a parenthesized child expression.
  3845. In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
  3846. (defsubst js2-paren-expr-node-p (node)
  3847. "Return t for nodes that typically have a parenthesized child expression.
  3848. Useful for computing the indentation anchors for arg-lists and conditions.
  3849. Note that it may return a false positive, for instance when NODE is
  3850. a `js2-new-node' and there are no arguments or parentheses."
  3851. (memq (aref node 0) js2-paren-expr-nodes))
  3852. ;; Fake polymorphism... yech.
  3853. (defun js2-node-lp (node)
  3854. "Return relative left-paren position for NODE, if applicable.
  3855. For `js2-elem-get-node' structs, returns left-bracket position.
  3856. Note that the position may be nil in the case of a parse error."
  3857. (cond
  3858. ((js2-elem-get-node-p node)
  3859. (js2-elem-get-node-lb node))
  3860. ((js2-loop-node-p node)
  3861. (js2-loop-node-lp node))
  3862. ((js2-function-node-p node)
  3863. (js2-function-node-lp node))
  3864. ((js2-if-node-p node)
  3865. (js2-if-node-lp node))
  3866. ((js2-new-node-p node)
  3867. (js2-new-node-lp node))
  3868. ((js2-call-node-p node)
  3869. (js2-call-node-lp node))
  3870. ((js2-paren-node-p node)
  3871. 0)
  3872. ((js2-switch-node-p node)
  3873. (js2-switch-node-lp node))
  3874. ((js2-catch-node-p node)
  3875. (js2-catch-node-lp node))
  3876. ((js2-let-node-p node)
  3877. (js2-let-node-lp node))
  3878. ((js2-comp-node-p node)
  3879. 0)
  3880. ((js2-with-node-p node)
  3881. (js2-with-node-lp node))
  3882. ((js2-xml-dot-query-node-p node)
  3883. (1+ (js2-infix-node-op-pos node)))
  3884. (t
  3885. (error "Unsupported node type: %s" (js2-node-short-name node)))))
  3886. ;; Fake polymorphism... blech.
  3887. (defun js2-node-rp (node)
  3888. "Return relative right-paren position for NODE, if applicable.
  3889. For `js2-elem-get-node' structs, returns right-bracket position.
  3890. Note that the position may be nil in the case of a parse error."
  3891. (cond
  3892. ((js2-elem-get-node-p node)
  3893. (js2-elem-get-node-rb node))
  3894. ((js2-loop-node-p node)
  3895. (js2-loop-node-rp node))
  3896. ((js2-function-node-p node)
  3897. (js2-function-node-rp node))
  3898. ((js2-if-node-p node)
  3899. (js2-if-node-rp node))
  3900. ((js2-new-node-p node)
  3901. (js2-new-node-rp node))
  3902. ((js2-call-node-p node)
  3903. (js2-call-node-rp node))
  3904. ((js2-paren-node-p node)
  3905. (1- (js2-node-len node)))
  3906. ((js2-switch-node-p node)
  3907. (js2-switch-node-rp node))
  3908. ((js2-catch-node-p node)
  3909. (js2-catch-node-rp node))
  3910. ((js2-let-node-p node)
  3911. (js2-let-node-rp node))
  3912. ((js2-comp-node-p node)
  3913. (1- (js2-node-len node)))
  3914. ((js2-with-node-p node)
  3915. (js2-with-node-rp node))
  3916. ((js2-xml-dot-query-node-p node)
  3917. (1+ (js2-xml-dot-query-node-rp node)))
  3918. (t
  3919. (error "Unsupported node type: %s" (js2-node-short-name node)))))
  3920. (defsubst js2-node-first-child (node)
  3921. "Return the first element of `js2-node-child-list' for NODE."
  3922. (car (js2-node-child-list node)))
  3923. (defsubst js2-node-last-child (node)
  3924. "Return the last element of `js2-node-last-child' for NODE."
  3925. (car (last (js2-node-child-list node))))
  3926. (defun js2-node-prev-sibling (node)
  3927. "Return the previous statement in parent.
  3928. Works for parents supported by `js2-node-child-list'.
  3929. Returns nil if NODE is not in the parent, or PARENT is
  3930. not a supported node, or if NODE is the first child."
  3931. (let* ((p (js2-node-parent node))
  3932. (kids (js2-node-child-list p))
  3933. (sib (car kids)))
  3934. (while (and kids
  3935. (not (eq node (cadr kids))))
  3936. (setq kids (cdr kids)
  3937. sib (car kids)))
  3938. sib))
  3939. (defun js2-node-next-sibling (node)
  3940. "Return the next statement in parent block.
  3941. Returns nil if NODE is not in the block, or PARENT is not
  3942. a block node, or if NODE is the last statement."
  3943. (let* ((p (js2-node-parent node))
  3944. (kids (js2-node-child-list p)))
  3945. (while (and kids
  3946. (not (eq node (car kids))))
  3947. (setq kids (cdr kids)))
  3948. (cadr kids)))
  3949. (defun js2-node-find-child-before (pos parent &optional after)
  3950. "Find the last child that starts before POS in parent.
  3951. If AFTER is non-nil, returns first child starting after POS.
  3952. POS is an absolute buffer position. PARENT is any node
  3953. supported by `js2-node-child-list'.
  3954. Returns nil if no applicable child is found."
  3955. (let ((kids (if (js2-function-node-p parent)
  3956. (js2-block-node-kids (js2-function-node-body parent))
  3957. (js2-node-child-list parent)))
  3958. (beg (js2-node-abs-pos (if (js2-function-node-p parent)
  3959. (js2-function-node-body parent)
  3960. parent)))
  3961. kid result fn
  3962. (continue t))
  3963. (setq fn (if after '>= '<))
  3964. (while (and kids continue)
  3965. (setq kid (car kids))
  3966. (if (funcall fn (+ beg (js2-node-pos kid)) pos)
  3967. (setq result kid
  3968. continue (not after))
  3969. (setq continue after))
  3970. (setq kids (cdr kids)))
  3971. result))
  3972. (defun js2-node-find-child-after (pos parent)
  3973. "Find first child that starts after POS in parent.
  3974. POS is an absolute buffer position. PARENT is any node
  3975. supported by `js2-node-child-list'.
  3976. Returns nil if no applicable child is found."
  3977. (js2-node-find-child-before pos parent 'after))
  3978. (defun js2-node-replace-child (pos parent new-node)
  3979. "Replace node at index POS in PARENT with NEW-NODE.
  3980. Only works for parents supported by `js2-node-child-list'."
  3981. (let ((kids (js2-node-child-list parent))
  3982. (i 0))
  3983. (while (< i pos)
  3984. (setq kids (cdr kids)
  3985. i (1+ i)))
  3986. (setcar kids new-node)
  3987. (js2-node-add-children parent new-node)))
  3988. (defun js2-node-buffer (n)
  3989. "Return the buffer associated with AST N.
  3990. Returns nil if the buffer is not set as a property on the root
  3991. node, or if parent links were not recorded during parsing."
  3992. (let ((root (js2-node-root n)))
  3993. (and root
  3994. (js2-ast-root-p root)
  3995. (js2-ast-root-buffer root))))
  3996. (defun js2-block-node-push (n kid)
  3997. "Push js2-node KID onto the end of js2-block-node N's child list.
  3998. KID is always added to the -end- of the kids list.
  3999. Function also calls `js2-node-add-children' to add the parent link."
  4000. (let ((kids (js2-node-child-list n)))
  4001. (if kids
  4002. (setcdr kids (nconc (cdr kids) (list kid)))
  4003. (js2-node-set-child-list n (list kid)))
  4004. (js2-node-add-children n kid)))
  4005. (defun js2-node-string (node)
  4006. (with-current-buffer (or (js2-node-buffer node)
  4007. (error "No buffer available for node %s" node))
  4008. (let ((pos (js2-node-abs-pos node)))
  4009. (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
  4010. ;; Container for storing the node we're looking for in a traversal.
  4011. (js2-deflocal js2-discovered-node nil)
  4012. ;; Keep track of absolute node position during traversals.
  4013. (js2-deflocal js2-visitor-offset nil)
  4014. (js2-deflocal js2-node-search-point nil)
  4015. (when js2-mode-dev-mode-p
  4016. (defun js2-find-node-at-point ()
  4017. (interactive)
  4018. (let ((node (js2-node-at-point)))
  4019. (message "%s" (or node "No node found at point"))))
  4020. (defun js2-node-name-at-point ()
  4021. (interactive)
  4022. (let ((node (js2-node-at-point)))
  4023. (message "%s" (if node
  4024. (js2-node-short-name node)
  4025. "No node found at point.")))))
  4026. (defun js2-node-at-point (&optional pos skip-comments)
  4027. "Return AST node at POS, a buffer position, defaulting to current point.
  4028. The `js2-mode-ast' variable must be set to the current parse tree.
  4029. Signals an error if the AST (`js2-mode-ast') is nil.
  4030. Always returns a node - if it can't find one, it returns the root.
  4031. If SKIP-COMMENTS is non-nil, comment nodes are ignored."
  4032. (let ((ast js2-mode-ast)
  4033. result)
  4034. (unless ast
  4035. (error "No JavaScript AST available"))
  4036. ;; Look through comments first, since they may be inside nodes that
  4037. ;; would otherwise report a match.
  4038. (setq pos (or pos (point))
  4039. result (if (> pos (js2-node-abs-end ast))
  4040. ast
  4041. (if (not skip-comments)
  4042. (js2-comment-at-point pos))))
  4043. (unless result
  4044. (setq js2-discovered-node nil
  4045. js2-visitor-offset 0
  4046. js2-node-search-point pos)
  4047. (unwind-protect
  4048. (catch 'js2-visit-done
  4049. (js2-visit-ast ast #'js2-node-at-point-visitor))
  4050. (setq js2-visitor-offset nil
  4051. js2-node-search-point nil))
  4052. (setq result js2-discovered-node))
  4053. ;; may have found a comment beyond end of last child node,
  4054. ;; since visiting the ast-root looks at the comment-list last.
  4055. (if (and skip-comments
  4056. (js2-comment-node-p result))
  4057. (setq result nil))
  4058. (or result js2-mode-ast)))
  4059. (defun js2-node-at-point-visitor (node end-p)
  4060. (let ((rel-pos (js2-node-pos node))
  4061. abs-pos
  4062. abs-end
  4063. (point js2-node-search-point))
  4064. (cond
  4065. (end-p
  4066. ;; this evaluates to a non-nil return value, even if it's zero
  4067. (cl-decf js2-visitor-offset rel-pos))
  4068. ;; we already looked for comments before visiting, and don't want them now
  4069. ((js2-comment-node-p node)
  4070. nil)
  4071. (t
  4072. (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
  4073. ;; we only want to use the node if the point is before
  4074. ;; the last character position in the node, so we decrement
  4075. ;; the absolute end by 1.
  4076. abs-end (+ abs-pos (js2-node-len node) -1))
  4077. (cond
  4078. ;; If this node starts after search-point, stop the search.
  4079. ((> abs-pos point)
  4080. (throw 'js2-visit-done nil))
  4081. ;; If this node ends before the search-point, don't check kids.
  4082. ((> point abs-end)
  4083. nil)
  4084. (t
  4085. ;; Otherwise point is within this node, possibly in a child.
  4086. (setq js2-discovered-node node)
  4087. t)))))) ; keep processing kids to look for more specific match
  4088. (defsubst js2-block-comment-p (node)
  4089. "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
  4090. (and (js2-comment-node-p node)
  4091. (memq (js2-comment-node-format node) '(jsdoc block))))
  4092. ;; TODO: put the comments in a vector and binary-search them instead
  4093. (defun js2-comment-at-point (&optional pos)
  4094. "Look through scanned comment nodes for one containing POS.
  4095. POS is a buffer position that defaults to current point.
  4096. Function returns nil if POS was not in any comment node."
  4097. (let ((ast js2-mode-ast)
  4098. (x (or pos (point)))
  4099. beg end)
  4100. (unless ast
  4101. (error "No JavaScript AST available"))
  4102. (catch 'done
  4103. ;; Comments are stored in lexical order.
  4104. (dolist (comment (js2-ast-root-comments ast) nil)
  4105. (setq beg (js2-node-abs-pos comment)
  4106. end (+ beg (js2-node-len comment)))
  4107. (if (and (>= x beg)
  4108. (<= x end))
  4109. (throw 'done comment))))))
  4110. (defun js2-comments-between (start end comments-list)
  4111. "Return comment nodes between START and END, nil if not found.
  4112. START and END are absolute positions in current buffer.
  4113. COMMENTS-LIST is the comments list to check."
  4114. (let (comments c-start c-end)
  4115. (nreverse
  4116. (dolist (comment comments-list comments)
  4117. (setq c-start (js2-node-abs-pos comment)
  4118. c-end (1- (+ c-start (js2-node-len comment))))
  4119. (unless (or (< c-end start)
  4120. (> c-start end))
  4121. (push comment comments))))))
  4122. (defun js2-mode-find-parent-fn (node)
  4123. "Find function enclosing NODE.
  4124. Returns nil if NODE is not inside a function."
  4125. (setq node (js2-node-parent node))
  4126. (while (and node (not (js2-function-node-p node)))
  4127. (setq node (js2-node-parent node)))
  4128. (and (js2-function-node-p node) node))
  4129. (defun js2-mode-find-enclosing-fn (node)
  4130. "Find function or root enclosing NODE."
  4131. (if (js2-ast-root-p node)
  4132. node
  4133. (setq node (js2-node-parent node))
  4134. (while (not (or (js2-ast-root-p node)
  4135. (js2-function-node-p node)))
  4136. (setq node (js2-node-parent node)))
  4137. node))
  4138. (defun js2-mode-find-enclosing-node (beg end)
  4139. "Find node fully enclosing BEG and END."
  4140. (let ((node (js2-node-at-point beg))
  4141. pos
  4142. (continue t))
  4143. (while continue
  4144. (if (or (js2-ast-root-p node)
  4145. (and
  4146. (<= (setq pos (js2-node-abs-pos node)) beg)
  4147. (>= (+ pos (js2-node-len node)) end)))
  4148. (setq continue nil)
  4149. (setq node (js2-node-parent node))))
  4150. node))
  4151. (defun js2-node-parent-script-or-fn (node)
  4152. "Find script or function immediately enclosing NODE.
  4153. If NODE is the ast-root, returns nil."
  4154. (if (js2-ast-root-p node)
  4155. nil
  4156. (setq node (js2-node-parent node))
  4157. (while (and node (not (or (js2-function-node-p node)
  4158. (js2-script-node-p node))))
  4159. (setq node (js2-node-parent node)))
  4160. node))
  4161. (defun js2-node-is-descendant (node ancestor)
  4162. "Return t if NODE is a descendant of ANCESTOR."
  4163. (while (and node
  4164. (not (eq node ancestor)))
  4165. (setq node (js2-node-parent node)))
  4166. node)
  4167. ;;; visitor infrastructure
  4168. (defun js2-visit-none (_node _callback)
  4169. "Visitor for AST node that have no node children."
  4170. nil)
  4171. (defun js2-print-none (_node _indent)
  4172. "Visitor for AST node with no printed representation.")
  4173. (defun js2-print-body (node indent)
  4174. "Print a statement, or a block without braces."
  4175. (if (js2-block-node-p node)
  4176. (dolist (kid (js2-block-node-kids node))
  4177. (js2-print-ast kid indent))
  4178. (js2-print-ast node indent)))
  4179. (defun js2-print-list (args &optional delimiter)
  4180. (cl-loop with len = (length args)
  4181. for arg in args
  4182. for count from 1
  4183. do
  4184. (when arg (js2-print-ast arg 0))
  4185. (if (< count len)
  4186. (insert (or delimiter ", ")))))
  4187. (defun js2-print-tree (ast)
  4188. "Prints an AST to the current buffer.
  4189. Makes `js2-ast-parent-nodes' available to the printer functions."
  4190. (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
  4191. (js2-print-ast ast)))
  4192. (defun js2-print-ast (node &optional indent)
  4193. "Helper function for printing AST nodes.
  4194. Requires `js2-ast-parent-nodes' to be non-nil.
  4195. You should use `js2-print-tree' instead of this function."
  4196. (let ((printer (get (aref node 0) 'js2-printer))
  4197. (i (or indent 0)))
  4198. ;; TODO: wedge comments in here somewhere
  4199. (if printer
  4200. (funcall printer node i))))
  4201. (defconst js2-side-effecting-tokens
  4202. (let ((tokens (make-bool-vector js2-num-tokens nil)))
  4203. (dolist (tt (list js2-ASSIGN
  4204. js2-ASSIGN_ADD
  4205. js2-ASSIGN_BITAND
  4206. js2-ASSIGN_BITOR
  4207. js2-ASSIGN_BITXOR
  4208. js2-ASSIGN_DIV
  4209. js2-ASSIGN_LSH
  4210. js2-ASSIGN_MOD
  4211. js2-ASSIGN_MUL
  4212. js2-ASSIGN_RSH
  4213. js2-ASSIGN_SUB
  4214. js2-ASSIGN_URSH
  4215. js2-ASSIGN_EXPON
  4216. js2-ASSIGN_AND
  4217. js2-ASSIGN_OR
  4218. js2-ASSIGN_NULLISH
  4219. js2-BLOCK
  4220. js2-BREAK
  4221. js2-CALL
  4222. js2-CATCH
  4223. js2-CATCH_SCOPE
  4224. js2-CLASS
  4225. js2-CONST
  4226. js2-CONTINUE
  4227. js2-DEBUGGER
  4228. js2-DEC
  4229. js2-DELPROP
  4230. js2-DEL_REF
  4231. js2-DO
  4232. js2-ELSE
  4233. js2-EMPTY
  4234. js2-ENTERWITH
  4235. js2-EXPORT
  4236. js2-EXPR_RESULT
  4237. js2-FINALLY
  4238. js2-FOR
  4239. js2-FUNCTION
  4240. js2-GOTO
  4241. js2-IF
  4242. js2-IFEQ
  4243. js2-IFNE
  4244. js2-IMPORT
  4245. js2-INC
  4246. js2-JSR
  4247. js2-LABEL
  4248. js2-LEAVEWITH
  4249. js2-LET
  4250. js2-LETEXPR
  4251. js2-LOCAL_BLOCK
  4252. js2-LOOP
  4253. js2-NEW
  4254. js2-REF_CALL
  4255. js2-RETHROW
  4256. js2-RETURN
  4257. js2-RETURN_RESULT
  4258. js2-SEMI
  4259. js2-SETELEM
  4260. js2-SETELEM_OP
  4261. js2-SETNAME
  4262. js2-SETPROP
  4263. js2-SETPROP_OP
  4264. js2-SETVAR
  4265. js2-SET_REF
  4266. js2-SET_REF_OP
  4267. js2-SWITCH
  4268. js2-TARGET
  4269. js2-THROW
  4270. js2-TRY
  4271. js2-VAR
  4272. js2-WHILE
  4273. js2-WITH
  4274. js2-WITHEXPR
  4275. js2-YIELD))
  4276. (aset tokens tt t))
  4277. tokens))
  4278. (defun js2-node-has-side-effects (node)
  4279. "Return t if NODE has side effects."
  4280. (when node ; makes it easier to handle malformed expressions
  4281. (let ((tt (js2-node-type node)))
  4282. (cond
  4283. ;; This doubtless needs some work, since EXPR_VOID is used
  4284. ;; in several ways in Rhino and I may not have caught them all.
  4285. ;; I'll wait for people to notice incorrect warnings.
  4286. ((and (= tt js2-EXPR_VOID)
  4287. (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
  4288. (let ((expr (js2-expr-stmt-node-expr node)))
  4289. (or (js2-node-has-side-effects expr)
  4290. (when (js2-string-node-p expr)
  4291. (member (js2-string-node-value expr) '("use strict" "use asm"))))))
  4292. ((= tt js2-AWAIT) t)
  4293. ((= tt js2-COMMA)
  4294. (js2-node-has-side-effects (js2-infix-node-right node)))
  4295. ((or (= tt js2-AND)
  4296. (= tt js2-OR)
  4297. (= tt js2-NULLISH-COALESCING))
  4298. (or (js2-node-has-side-effects (js2-infix-node-right node))
  4299. (js2-node-has-side-effects (js2-infix-node-left node))))
  4300. ((= tt js2-HOOK)
  4301. (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
  4302. (js2-node-has-side-effects (js2-cond-node-false-expr node))))
  4303. ((js2-paren-node-p node)
  4304. (js2-node-has-side-effects (js2-paren-node-expr node)))
  4305. ((= tt js2-ERROR) ; avoid cascaded error messages
  4306. nil)
  4307. ((or (and js2-instanceof-has-side-effects (= tt js2-INSTANCEOF))
  4308. (and js2-getprop-has-side-effects (= tt js2-GETPROP)))
  4309. t)
  4310. (t
  4311. (aref js2-side-effecting-tokens tt))))))
  4312. (defconst js2-stmt-node-types
  4313. (list js2-BLOCK
  4314. js2-BREAK
  4315. js2-CONTINUE
  4316. js2-DEFAULT ; e4x "default xml namespace" statement
  4317. js2-DO
  4318. js2-EXPORT
  4319. js2-EXPR_RESULT
  4320. js2-EXPR_VOID
  4321. js2-FOR
  4322. js2-IF
  4323. js2-IMPORT
  4324. js2-RETURN
  4325. js2-SWITCH
  4326. js2-THROW
  4327. js2-TRY
  4328. js2-WHILE
  4329. js2-WITH)
  4330. "Node types that only appear in statement contexts.
  4331. The list does not include nodes that always appear as the child
  4332. of another specific statement type, such as switch-cases,
  4333. catch and finally blocks, and else-clauses. The list also excludes
  4334. nodes like yield, let and var, which may appear in either expression
  4335. or statement context, and in the latter context always have a
  4336. `js2-expr-stmt-node' parent. Finally, the list does not include
  4337. functions or scripts, which are treated separately from statements
  4338. by the JavaScript parser and runtime.")
  4339. (defun js2-stmt-node-p (node)
  4340. "Heuristic for figuring out if NODE is a statement.
  4341. Some node types can appear in either an expression context or a
  4342. statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
  4343. For these node types in a statement context, the parent will be a
  4344. `js2-expr-stmt-node'.
  4345. Functions aren't included in the check."
  4346. (memq (js2-node-type node) js2-stmt-node-types))
  4347. (defun js2-mode-find-first-stmt (node)
  4348. "Search upward starting from NODE looking for a statement.
  4349. For purposes of this function, a `js2-function-node' counts."
  4350. (while (not (or (js2-stmt-node-p node)
  4351. (js2-function-node-p node)))
  4352. (setq node (js2-node-parent node)))
  4353. node)
  4354. (defun js2-node-parent-stmt (node)
  4355. "Return the node's first ancestor that is a statement.
  4356. Returns nil if NODE is a `js2-ast-root'. Note that any expression
  4357. appearing in a statement context will have a parent that is a
  4358. `js2-expr-stmt-node' that will be returned by this function."
  4359. (let ((parent (js2-node-parent node)))
  4360. (if (or (null parent)
  4361. (js2-stmt-node-p parent)
  4362. (and (js2-function-node-p parent)
  4363. (eq (js2-function-node-form parent) 'FUNCTION_STATEMENT)))
  4364. parent
  4365. (js2-node-parent-stmt parent))))
  4366. ;; In the Mozilla Rhino sources, Roshan James writes:
  4367. ;; Does consistent-return analysis on the function body when strict mode is
  4368. ;; enabled.
  4369. ;;
  4370. ;; function (x) { return (x+1) }
  4371. ;;
  4372. ;; is ok, but
  4373. ;;
  4374. ;; function (x) { if (x < 0) return (x+1); }
  4375. ;;
  4376. ;; is not because the function can potentially return a value when the
  4377. ;; condition is satisfied and if not, the function does not explicitly
  4378. ;; return a value.
  4379. ;;
  4380. ;; This extends to checking mismatches such as "return" and "return <value>"
  4381. ;; used in the same function. Warnings are not emitted if inconsistent
  4382. ;; returns exist in code that can be statically shown to be unreachable.
  4383. ;; Ex.
  4384. ;; function (x) { while (true) { ... if (..) { return value } ... } }
  4385. ;;
  4386. ;; emits no warning. However if the loop had a break statement, then a
  4387. ;; warning would be emitted.
  4388. ;;
  4389. ;; The consistency analysis looks at control structures such as loops, ifs,
  4390. ;; switch, try-catch-finally blocks, examines the reachable code paths and
  4391. ;; warns the user about an inconsistent set of termination possibilities.
  4392. ;;
  4393. ;; These flags enumerate the possible ways a statement/function can
  4394. ;; terminate. These flags are used by endCheck() and by the Parser to
  4395. ;; detect inconsistent return usage.
  4396. ;;
  4397. ;; END_UNREACHED is reserved for code paths that are assumed to always be
  4398. ;; able to execute (example: throw, continue)
  4399. ;;
  4400. ;; END_DROPS_OFF indicates if the statement can transfer control to the
  4401. ;; next one. Statement such as return dont. A compound statement may have
  4402. ;; some branch that drops off control to the next statement.
  4403. ;;
  4404. ;; END_RETURNS indicates that the statement can return with no value.
  4405. ;; END_RETURNS_VALUE indicates that the statement can return a value.
  4406. ;;
  4407. ;; A compound statement such as
  4408. ;; if (condition) {
  4409. ;; return value;
  4410. ;; }
  4411. ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
  4412. (defconst js2-END_UNREACHED 0)
  4413. (defconst js2-END_DROPS_OFF 1)
  4414. (defconst js2-END_RETURNS 2)
  4415. (defconst js2-END_RETURNS_VALUE 4)
  4416. (defconst js2-END_YIELDS 8)
  4417. (defun js2-has-consistent-return-usage (node)
  4418. "Check that every return usage in a function body is consistent.
  4419. Returns t if the function satisfies strict mode requirement."
  4420. (let ((n (js2-end-check node)))
  4421. ;; either it doesn't return a value in any branch...
  4422. (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
  4423. ;; or it returns a value (or is unreached) at every branch
  4424. (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
  4425. js2-END_RETURNS
  4426. js2-END_YIELDS)))))
  4427. (defun js2-end-check-if (node)
  4428. "Ensure that return usage in then/else blocks is consistent.
  4429. If there is no else block, then the return statement can fall through.
  4430. Returns logical OR of END_* flags"
  4431. (let ((th (js2-if-node-then-part node))
  4432. (el (js2-if-node-else-part node)))
  4433. (if (null th)
  4434. js2-END_UNREACHED
  4435. (logior (js2-end-check th) (if el
  4436. (js2-end-check el)
  4437. js2-END_DROPS_OFF)))))
  4438. (defun js2-end-check-switch (node)
  4439. "Consistency of return statements is checked between the case statements.
  4440. If there is no default, then the switch can fall through. If there is a
  4441. default, we check to see if all code paths in the default return or if
  4442. there is a code path that can fall through.
  4443. Returns logical OR of END_* flags."
  4444. (let ((rv js2-END_UNREACHED)
  4445. default-case)
  4446. ;; examine the cases
  4447. (catch 'break
  4448. (dolist (c (js2-switch-node-cases node))
  4449. (if (js2-case-node-expr c)
  4450. (js2-set-flag rv (js2-end-check-block c))
  4451. (setq default-case c)
  4452. (throw 'break nil))))
  4453. ;; we don't care how the cases drop into each other
  4454. (js2-clear-flag rv js2-END_DROPS_OFF)
  4455. ;; examine the default
  4456. (js2-set-flag rv (if default-case
  4457. (js2-end-check default-case)
  4458. js2-END_DROPS_OFF))
  4459. rv))
  4460. (defun js2-end-check-try (node)
  4461. "If the block has a finally, return consistency is checked in the
  4462. finally block. If all code paths in the finally return, then the
  4463. returns in the try-catch blocks don't matter. If there is a code path
  4464. that does not return or if there is no finally block, the returns
  4465. of the try and catch blocks are checked for mismatch.
  4466. Returns logical OR of END_* flags."
  4467. (let ((finally (js2-try-node-finally-block node))
  4468. rv)
  4469. ;; check the finally if it exists
  4470. (setq rv (if finally
  4471. (js2-end-check (js2-finally-node-body finally))
  4472. js2-END_DROPS_OFF))
  4473. ;; If the finally block always returns, then none of the returns
  4474. ;; in the try or catch blocks matter.
  4475. (when (js2-flag-set-p rv js2-END_DROPS_OFF)
  4476. (js2-clear-flag rv js2-END_DROPS_OFF)
  4477. ;; examine the try block
  4478. (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
  4479. ;; check each catch block
  4480. (dolist (cb (js2-try-node-catch-clauses node))
  4481. (js2-set-flag rv (js2-end-check cb))))
  4482. rv))
  4483. (defun js2-end-check-loop (node)
  4484. "Return statement in the loop body must be consistent.
  4485. The default assumption for any kind of a loop is that it will eventually
  4486. terminate. The only exception is a loop with a constant true condition.
  4487. Code that follows such a loop is examined only if one can determine
  4488. statically that there is a break out of the loop.
  4489. for(... ; ... ; ...) {}
  4490. for(... in ... ) {}
  4491. while(...) { }
  4492. do { } while(...)
  4493. Returns logical OR of END_* flags."
  4494. (let ((rv (js2-end-check (js2-loop-node-body node)))
  4495. (condition (cond
  4496. ((js2-while-node-p node)
  4497. (js2-while-node-condition node))
  4498. ((js2-do-node-p node)
  4499. (js2-do-node-condition node))
  4500. ((js2-for-node-p node)
  4501. (js2-for-node-condition node)))))
  4502. ;; check to see if the loop condition is always true
  4503. (if (and condition
  4504. (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
  4505. (js2-clear-flag rv js2-END_DROPS_OFF))
  4506. ;; look for effect of breaks
  4507. (js2-set-flag rv (js2-node-get-prop node
  4508. 'CONTROL_BLOCK_PROP
  4509. js2-END_UNREACHED))
  4510. rv))
  4511. (defun js2-end-check-block (node)
  4512. "A general block of code is examined statement by statement.
  4513. If any statement (even a compound one) returns in all branches, then
  4514. subsequent statements are not examined.
  4515. Returns logical OR of END_* flags."
  4516. (let* ((rv js2-END_DROPS_OFF)
  4517. (kids (js2-block-node-kids node))
  4518. (n (car kids)))
  4519. ;; Check each statement. If the statement can continue onto the next
  4520. ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
  4521. (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
  4522. (js2-clear-flag rv js2-END_DROPS_OFF)
  4523. (js2-set-flag rv (js2-end-check n))
  4524. (setq kids (cdr kids)
  4525. n (car kids)))
  4526. rv))
  4527. (defun js2-end-check-label (node)
  4528. "A labeled statement implies that there may be a break to the label.
  4529. The function processes the labeled statement and then checks the
  4530. CONTROL_BLOCK_PROP property to see if there is ever a break to the
  4531. particular label.
  4532. Returns logical OR of END_* flags."
  4533. (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
  4534. (logior rv (js2-node-get-prop node
  4535. 'CONTROL_BLOCK_PROP
  4536. js2-END_UNREACHED))))
  4537. (defun js2-end-check-break (node)
  4538. "When a break is encountered annotate the statement being broken
  4539. out of by setting its CONTROL_BLOCK_PROP property.
  4540. Returns logical OR of END_* flags."
  4541. (and (js2-break-node-target node)
  4542. (js2-node-set-prop (js2-break-node-target node)
  4543. 'CONTROL_BLOCK_PROP
  4544. js2-END_DROPS_OFF))
  4545. js2-END_UNREACHED)
  4546. (defun js2-end-check (node)
  4547. "Examine the body of a function, doing a basic reachability analysis.
  4548. Returns a combination of flags END_* flags that indicate
  4549. how the function execution can terminate. These constitute only the
  4550. pessimistic set of termination conditions. It is possible that at
  4551. runtime certain code paths will never be actually taken. Hence this
  4552. analysis will flag errors in cases where there may not be errors.
  4553. Returns logical OR of END_* flags"
  4554. (let (kid)
  4555. (cond
  4556. ((js2-break-node-p node)
  4557. (js2-end-check-break node))
  4558. ((js2-expr-stmt-node-p node)
  4559. (if (setq kid (js2-expr-stmt-node-expr node))
  4560. (js2-end-check kid)
  4561. js2-END_DROPS_OFF))
  4562. ((or (js2-continue-node-p node)
  4563. (js2-throw-node-p node))
  4564. js2-END_UNREACHED)
  4565. ((js2-return-node-p node)
  4566. (if (setq kid (js2-return-node-retval node))
  4567. js2-END_RETURNS_VALUE
  4568. js2-END_RETURNS))
  4569. ((js2-loop-node-p node)
  4570. (js2-end-check-loop node))
  4571. ((js2-switch-node-p node)
  4572. (js2-end-check-switch node))
  4573. ((js2-labeled-stmt-node-p node)
  4574. (js2-end-check-label node))
  4575. ((js2-if-node-p node)
  4576. (js2-end-check-if node))
  4577. ((js2-try-node-p node)
  4578. (js2-end-check-try node))
  4579. ((js2-block-node-p node)
  4580. (if (null (js2-block-node-kids node))
  4581. js2-END_DROPS_OFF
  4582. (js2-end-check-block node)))
  4583. ((js2-yield-node-p node)
  4584. js2-END_YIELDS)
  4585. (t
  4586. js2-END_DROPS_OFF))))
  4587. (defun js2-always-defined-boolean-p (node)
  4588. "Check if NODE always evaluates to true or false in boolean context.
  4589. Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
  4590. nor always false."
  4591. (let ((tt (js2-node-type node))
  4592. num)
  4593. (cond
  4594. ((or (= tt js2-FALSE) (= tt js2-NULL))
  4595. 'ALWAYS_FALSE)
  4596. ((= tt js2-TRUE)
  4597. 'ALWAYS_TRUE)
  4598. ((= tt js2-NUMBER)
  4599. (setq num (js2-number-node-num-value node))
  4600. (if (and (not (eq num 0.0e+NaN))
  4601. (not (zerop num)))
  4602. 'ALWAYS_TRUE
  4603. 'ALWAYS_FALSE))
  4604. (t
  4605. nil))))
  4606. ;;; Scanner -- a port of Mozilla Rhino's lexer.
  4607. ;; Corresponds to Rhino files Token.java and TokenStream.java.
  4608. (defvar js2-tokens nil
  4609. "List of all defined token names.") ; initialized in `js2-token-names'
  4610. (defconst js2-token-names
  4611. (let* ((names (make-vector js2-num-tokens -1))
  4612. (case-fold-search nil) ; only match js2-UPPER_CASE
  4613. (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
  4614. (cl-loop for sym in syms
  4615. for i from 0
  4616. do
  4617. (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
  4618. (not (boundp sym)))
  4619. (aset names (symbol-value sym) ; code, e.g. 152
  4620. (downcase
  4621. (substring (symbol-name sym) 4))) ; name, e.g. "let"
  4622. (push sym js2-tokens)))
  4623. names)
  4624. "Vector mapping int values to token string names, sans `js2-' prefix.")
  4625. (defun js2-tt-name (tok)
  4626. "Return a string name for TOK, a token symbol or code.
  4627. Signals an error if it's not a recognized token."
  4628. (let ((code tok))
  4629. (if (symbolp tok)
  4630. (setq code (symbol-value tok)))
  4631. (if (eq code -1)
  4632. "ERROR"
  4633. (if (and (numberp code)
  4634. (not (cl-minusp code))
  4635. (< code js2-num-tokens))
  4636. (aref js2-token-names code)
  4637. (error "Invalid token: %s" code)))))
  4638. (defsubst js2-tt-sym (tok)
  4639. "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
  4640. (intern (js2-tt-name tok)))
  4641. (defconst js2-token-codes
  4642. (let ((table (make-hash-table :test 'eq :size 256)))
  4643. (cl-loop for name across js2-token-names
  4644. for sym = (intern (concat "js2-" (upcase name)))
  4645. do
  4646. (puthash sym (symbol-value sym) table))
  4647. ;; clean up a few that are "wrong" in Rhino's token codes
  4648. (puthash 'js2-DELETE js2-DELPROP table)
  4649. table)
  4650. "Hashtable mapping token type symbols to their bytecodes.")
  4651. (defsubst js2-tt-code (sym)
  4652. "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
  4653. (or (gethash sym js2-token-codes)
  4654. (error "Invalid token symbol: %s " sym))) ; signal code bug
  4655. (defun js2-report-scan-error (msg &optional no-throw beg len)
  4656. (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
  4657. (js2-report-error msg nil
  4658. (or beg (js2-current-token-beg))
  4659. (or len (js2-current-token-len)))
  4660. (unless no-throw
  4661. (throw 'return js2-ERROR)))
  4662. (defun js2-set-string-from-buffer (token)
  4663. "Set `string' and `end' slots for TOKEN, return the string."
  4664. (setf (js2-token-end token) js2-ts-cursor
  4665. (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
  4666. ;; TODO: could potentially avoid a lot of consing by allocating a
  4667. ;; char buffer the way Rhino does.
  4668. (defsubst js2-add-to-string (c)
  4669. (push c js2-ts-string-buffer))
  4670. ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
  4671. ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
  4672. ;; any other character: when it's not part of the current token, we
  4673. ;; unget it, allowing it to be read again by the following call.
  4674. (defsubst js2-unget-char ()
  4675. (cl-decf js2-ts-cursor))
  4676. ;; Rhino distinguishes \r and \n line endings. We don't need to
  4677. ;; because we only scan from Emacs buffers, which always use \n.
  4678. (defun js2-get-char ()
  4679. "Read and return the next character from the input buffer.
  4680. Increments `js2-ts-lineno' if the return value is a newline char.
  4681. Updates `js2-ts-cursor' to the point after the returned char.
  4682. Returns `js2-EOF_CHAR' if we hit the end of the buffer.
  4683. Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
  4684. (let (c)
  4685. ;; check for end of buffer
  4686. (if (>= js2-ts-cursor (point-max))
  4687. (setq js2-ts-hit-eof t
  4688. js2-ts-cursor (1+ js2-ts-cursor)
  4689. c js2-EOF_CHAR) ; return value
  4690. ;; otherwise read next char
  4691. (setq c (char-before (cl-incf js2-ts-cursor)))
  4692. ;; if we read a newline, update counters
  4693. (if (= c ?\n)
  4694. (setq js2-ts-line-start js2-ts-cursor
  4695. js2-ts-lineno (1+ js2-ts-lineno)))
  4696. ;; TODO: skip over format characters
  4697. c)))
  4698. (defun js2-read-unicode-escape ()
  4699. "Read a \\uNNNN sequence from the input.
  4700. Assumes the ?\ and ?u have already been read.
  4701. Returns the unicode character, or nil if it wasn't a valid character.
  4702. Doesn't change the values of any scanner variables."
  4703. ;; I really wish I knew a better way to do this, but I can't
  4704. ;; find the Emacs function that takes a 16-bit int and converts
  4705. ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
  4706. ;; Have to first check that it's 4 hex characters or it may stop
  4707. ;; the read early.
  4708. (ignore-errors
  4709. (let ((s (buffer-substring-no-properties js2-ts-cursor
  4710. (+ 4 js2-ts-cursor))))
  4711. (if (string-match "[0-9a-fA-F]\\{4\\}" s)
  4712. (read (concat "?\\u" s))))))
  4713. (defun js2-match-char (test)
  4714. "Consume and return next character if it matches TEST, a character.
  4715. Returns nil and consumes nothing if TEST is not the next character."
  4716. (let ((c (js2-get-char)))
  4717. (if (eq c test)
  4718. t
  4719. (js2-unget-char)
  4720. nil)))
  4721. (defun js2-peek-char ()
  4722. (prog1
  4723. (js2-get-char)
  4724. (js2-unget-char)))
  4725. (defun js2-identifier-start-p (c)
  4726. "Is C a valid start to an ES5 Identifier?
  4727. See http://es5.github.io/#x7.6"
  4728. (or
  4729. (memq c '(?$ ?_))
  4730. (memq (get-char-code-property c 'general-category)
  4731. ;; Letters
  4732. '(Lu Ll Lt Lm Lo Nl))))
  4733. (defun js2-identifier-part-p (c)
  4734. "Is C a valid part of an ES5 Identifier?
  4735. See http://es5.github.io/#x7.6"
  4736. (or
  4737. (memq c '(?$ ?_ ?\u200c ?\u200d))
  4738. (memq (get-char-code-property c 'general-category)
  4739. '(;; Letters
  4740. Lu Ll Lt Lm Lo Nl
  4741. ;; Combining Marks
  4742. Mn Mc
  4743. ;; Digits
  4744. Nd
  4745. ;; Connector Punctuation
  4746. Pc))))
  4747. (defun js2-alpha-p (c)
  4748. (cond ((and (<= ?A c) (<= c ?Z)) t)
  4749. ((and (<= ?a c) (<= c ?z)) t)
  4750. (t nil)))
  4751. (defsubst js2-digit-p (c)
  4752. (and (<= ?0 c) (<= c ?9)))
  4753. (defun js2-js-space-p (c)
  4754. (if (<= c 127)
  4755. (memq c '(#x20 #x9 #xB #xC #xD))
  4756. (or
  4757. (eq c #xA0)
  4758. ;; TODO: change this nil to check for Unicode space character
  4759. nil)))
  4760. (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
  4761. (defun js2-skip-line ()
  4762. "Skip to end of line."
  4763. (while (not (memq (js2-get-char) js2-eol-chars)))
  4764. (js2-unget-char)
  4765. (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
  4766. (defun js2-init-scanner (&optional buf line)
  4767. "Create token stream for BUF starting on LINE.
  4768. BUF defaults to `current-buffer' and LINE defaults to 1.
  4769. A buffer can only have one scanner active at a time, which yields
  4770. dramatically simpler code than using a defstruct. If you need to
  4771. have simultaneous scanners in a buffer, copy the regions to scan
  4772. into temp buffers."
  4773. (with-current-buffer (or buf (current-buffer))
  4774. (setq js2-ts-dirty-line nil
  4775. js2-ts-hit-eof nil
  4776. js2-ts-line-start 0
  4777. js2-ts-lineno (or line 1)
  4778. js2-ts-line-end-char -1
  4779. js2-ts-cursor (point-min)
  4780. js2-ti-tokens (make-vector js2-ti-ntokens nil)
  4781. js2-ti-tokens-cursor 0
  4782. js2-ti-lookahead 0
  4783. js2-ts-is-xml-attribute nil
  4784. js2-ts-xml-is-tag-content nil
  4785. js2-ts-xml-open-tags-count 0
  4786. js2-ts-string-buffer nil)))
  4787. ;; This function uses the cached op, string and number fields in
  4788. ;; TokenStream; if getToken has been called since the passed token
  4789. ;; was scanned, the op or string printed may be incorrect.
  4790. (defun js2-token-to-string (token)
  4791. ;; Not sure where this function is used in Rhino. Not tested.
  4792. (if (not js2-debug-print-trees)
  4793. ""
  4794. (let ((name (js2-tt-name token)))
  4795. (cond
  4796. ((memq token '(js2-STRING js2-REGEXP js2-NAME
  4797. js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
  4798. (concat name " `" (js2-current-token-string) "'"))
  4799. ((eq token js2-NUMBER)
  4800. (format "NUMBER %g" (js2-token-number (js2-current-token))))
  4801. (t
  4802. name)))))
  4803. (defconst js2-keywords
  4804. '(break
  4805. case catch class const continue
  4806. debugger default delete do
  4807. else extends export
  4808. false finally for function
  4809. if in instanceof import
  4810. let
  4811. new null
  4812. return
  4813. super switch
  4814. this throw true try typeof
  4815. var void
  4816. while with
  4817. yield))
  4818. ;; Token names aren't exactly the same as the keywords, unfortunately.
  4819. ;; E.g. delete is js2-DELPROP.
  4820. (defconst js2-kwd-tokens
  4821. (let ((table (make-vector js2-num-tokens nil))
  4822. (tokens
  4823. (list js2-BREAK
  4824. js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
  4825. js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
  4826. js2-ELSE js2-EXPORT
  4827. js2-ELSE js2-EXTENDS js2-EXPORT
  4828. js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
  4829. js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
  4830. js2-LET
  4831. js2-NEW js2-NULL
  4832. js2-RETURN
  4833. js2-SUPER js2-SWITCH
  4834. js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
  4835. js2-VAR
  4836. js2-WHILE js2-WITH
  4837. js2-YIELD)))
  4838. (dolist (i tokens)
  4839. (aset table i 'font-lock-keyword-face))
  4840. (aset table js2-STRING 'font-lock-string-face)
  4841. (aset table js2-REGEXP 'font-lock-string-face)
  4842. (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
  4843. (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
  4844. (aset table js2-COMMENT 'font-lock-comment-face)
  4845. (aset table js2-THIS 'font-lock-builtin-face)
  4846. (aset table js2-SUPER 'font-lock-builtin-face)
  4847. (aset table js2-VOID 'font-lock-constant-face)
  4848. (aset table js2-NULL 'font-lock-constant-face)
  4849. (aset table js2-TRUE 'font-lock-constant-face)
  4850. (aset table js2-FALSE 'font-lock-constant-face)
  4851. (aset table js2-NOT 'font-lock-negation-char-face)
  4852. table)
  4853. "Vector whose values are non-nil for tokens that are keywords.
  4854. The values are default faces to use for highlighting the keywords.")
  4855. ;; FIXME: Support strict mode-only future reserved words, after we know
  4856. ;; which parts scopes are in strict mode, and which are not.
  4857. (defconst js2-reserved-words '(class enum export extends import static super)
  4858. "Future reserved keywords in ECMAScript 5.1.")
  4859. (defconst js2-keyword-names
  4860. (let ((table (make-hash-table :test 'equal)))
  4861. (cl-loop for k in js2-keywords
  4862. do (puthash
  4863. (symbol-name k) ; instanceof
  4864. (intern (concat "js2-"
  4865. (upcase (symbol-name k)))) ; js2-INSTANCEOF
  4866. table))
  4867. table)
  4868. "JavaScript keywords by name, mapped to their symbols.")
  4869. (defconst js2-reserved-word-names
  4870. (let ((table (make-hash-table :test 'equal)))
  4871. (cl-loop for k in js2-reserved-words
  4872. do
  4873. (puthash (symbol-name k) 'js2-RESERVED table))
  4874. table)
  4875. "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
  4876. (defun js2-collect-string (buf)
  4877. "Convert BUF, a list of chars, to a string.
  4878. Reverses BUF before converting."
  4879. (if buf
  4880. (apply #'string (nreverse buf))
  4881. ""))
  4882. (defun js2-string-to-keyword (s)
  4883. "Return token for S, a string, if S is a keyword or reserved word.
  4884. Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
  4885. (or (gethash s js2-keyword-names)
  4886. (gethash s js2-reserved-word-names)))
  4887. (defsubst js2-ts-set-char-token-bounds (token)
  4888. "Used when next token is one character."
  4889. (setf (js2-token-beg token) (1- js2-ts-cursor)
  4890. (js2-token-end token) js2-ts-cursor))
  4891. (defsubst js2-ts-return (token type)
  4892. "Update the `end' and `type' slots of TOKEN,
  4893. then throw `return' with value TYPE."
  4894. (setf (js2-token-end token) js2-ts-cursor
  4895. (js2-token-type token) type)
  4896. (throw 'return type))
  4897. (defun js2-x-digit-to-int (c accumulator)
  4898. "Build up a hex number.
  4899. If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
  4900. corresponding number. Otherwise return -1."
  4901. (catch 'return
  4902. (catch 'check
  4903. ;; Use 0..9 < A..Z < a..z
  4904. (cond
  4905. ((<= c ?9)
  4906. (cl-decf c ?0)
  4907. (if (<= 0 c)
  4908. (throw 'check nil)))
  4909. ((<= c ?F)
  4910. (when (<= ?A c)
  4911. (cl-decf c (- ?A 10))
  4912. (throw 'check nil)))
  4913. ((<= c ?f)
  4914. (when (<= ?a c)
  4915. (cl-decf c (- ?a 10))
  4916. (throw 'check nil))))
  4917. (throw 'return -1))
  4918. (logior c (lsh accumulator 4))))
  4919. (defun js2-get-token (&optional modifier)
  4920. "If `js2-ti-lookahead' is zero, call scanner to get new token.
  4921. Otherwise, move `js2-ti-tokens-cursor' and return the type of
  4922. next saved token.
  4923. This function will not return a newline (js2-EOL) - instead, it
  4924. gobbles newlines until it finds a non-newline token. Call
  4925. `js2-peek-token-or-eol' when you care about newlines.
  4926. This function will also not return a js2-COMMENT. Instead, it
  4927. records comments found in `js2-scanned-comments'. If the token
  4928. returned by this function immediately follows a jsdoc comment,
  4929. the token is flagged as such."
  4930. (if (zerop js2-ti-lookahead)
  4931. (js2-get-token-internal modifier)
  4932. (cl-decf js2-ti-lookahead)
  4933. (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
  4934. (let ((tt (js2-current-token-type)))
  4935. (cl-assert (not (= tt js2-EOL)))
  4936. tt)))
  4937. (defun js2-unget-token ()
  4938. (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
  4939. (cl-incf js2-ti-lookahead)
  4940. (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
  4941. (defun js2-get-token-internal (modifier)
  4942. (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
  4943. (tt (js2-token-type token))
  4944. saw-eol
  4945. face)
  4946. ;; process comments
  4947. (while (or (= tt js2-EOL) (= tt js2-COMMENT))
  4948. (if (= tt js2-EOL)
  4949. (setq saw-eol t)
  4950. (setq saw-eol nil)
  4951. (when js2-record-comments
  4952. (js2-record-comment token)))
  4953. (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
  4954. (setq token (js2-get-token-internal-1 modifier) ; call scanner again
  4955. tt (js2-token-type token)))
  4956. (when saw-eol
  4957. (setf (js2-token-follows-eol-p token) t))
  4958. ;; perform lexical fontification as soon as token is scanned
  4959. (when js2-parse-ide-mode
  4960. (cond
  4961. ((cl-minusp tt)
  4962. (js2-record-face 'js2-error token))
  4963. ((setq face (aref js2-kwd-tokens tt))
  4964. (js2-record-face face token))
  4965. ((and (= tt js2-NAME)
  4966. (equal (js2-token-string token) "undefined"))
  4967. (js2-record-face 'font-lock-constant-face token))))
  4968. tt))
  4969. (defsubst js2-string-to-number (str base)
  4970. ;; TODO: Maybe port ScriptRuntime.stringToNumber.
  4971. (condition-case nil
  4972. (string-to-number str base)
  4973. (overflow-error -1)))
  4974. (defun js2-get-token-internal-1 (modifier)
  4975. "Return next JavaScript token type, an int such as js2-RETURN.
  4976. During operation, creates an instance of `js2-token' struct, sets
  4977. its relevant fields and puts it into `js2-ti-tokens'."
  4978. (let (identifier-start
  4979. is-unicode-escape-start c
  4980. contains-escape escape-val str result base
  4981. look-for-slash continue tt legacy-octal
  4982. (token (js2-new-token 0)))
  4983. (setq
  4984. tt
  4985. (catch 'return
  4986. (when (eq modifier 'TEMPLATE_TAIL)
  4987. (setf (js2-token-beg token) (1- js2-ts-cursor))
  4988. (throw 'return (js2-get-string-or-template-token ?` token)))
  4989. (while t
  4990. ;; Eat whitespace, possibly sensitive to newlines.
  4991. (setq continue t)
  4992. (while continue
  4993. (setq c (js2-get-char))
  4994. (cond
  4995. ((eq c js2-EOF_CHAR)
  4996. (js2-unget-char)
  4997. (js2-ts-set-char-token-bounds token)
  4998. (throw 'return js2-EOF))
  4999. ((eq c ?\n)
  5000. (js2-ts-set-char-token-bounds token)
  5001. (setq js2-ts-dirty-line nil)
  5002. (throw 'return js2-EOL))
  5003. ((not (js2-js-space-p c))
  5004. (if (/= c ?-) ; in case end of HTML comment
  5005. (setq js2-ts-dirty-line t))
  5006. (setq continue nil))))
  5007. ;; Assume the token will be 1 char - fixed up below.
  5008. (js2-ts-set-char-token-bounds token)
  5009. (when (eq c ?@)
  5010. (throw 'return js2-XMLATTR))
  5011. ;; identifier/keyword/instanceof?
  5012. ;; watch out for starting with a <backslash>
  5013. (cond
  5014. ((eq c ?\\)
  5015. (setq c (js2-get-char))
  5016. (if (eq c ?u)
  5017. (setq identifier-start t
  5018. is-unicode-escape-start t
  5019. js2-ts-string-buffer nil)
  5020. (setq identifier-start nil)
  5021. (js2-unget-char)
  5022. (setq c ?\\)))
  5023. (t
  5024. (when (setq identifier-start (js2-identifier-start-p c))
  5025. (setq js2-ts-string-buffer nil)
  5026. (js2-add-to-string c))))
  5027. (when identifier-start
  5028. (setq contains-escape is-unicode-escape-start)
  5029. (catch 'break
  5030. (while t
  5031. (if is-unicode-escape-start
  5032. ;; strictly speaking we should probably push-back
  5033. ;; all the bad characters if the <backslash>uXXXX
  5034. ;; sequence is malformed. But since there isn't a
  5035. ;; correct context(is there?) for a bad Unicode
  5036. ;; escape sequence in an identifier, we can report
  5037. ;; an error here.
  5038. (progn
  5039. (setq escape-val 0)
  5040. (dotimes (_ 4)
  5041. (setq c (js2-get-char)
  5042. escape-val (js2-x-digit-to-int c escape-val))
  5043. ;; Next check takes care of c < 0 and bad escape
  5044. (if (cl-minusp escape-val)
  5045. (throw 'break nil)))
  5046. (if (cl-minusp escape-val)
  5047. (js2-report-scan-error "msg.invalid.escape" t))
  5048. (js2-add-to-string escape-val)
  5049. (setq is-unicode-escape-start nil))
  5050. (setq c (js2-get-char))
  5051. (cond
  5052. ((eq c ?\\)
  5053. (setq c (js2-get-char))
  5054. (if (eq c ?u)
  5055. (setq is-unicode-escape-start t
  5056. contains-escape t)
  5057. (js2-report-scan-error "msg.illegal.character" t)))
  5058. (t
  5059. (if (or (eq c js2-EOF_CHAR)
  5060. (not (js2-identifier-part-p c)))
  5061. (throw 'break nil))
  5062. (js2-add-to-string c))))))
  5063. (js2-unget-char)
  5064. (setf str (js2-collect-string js2-ts-string-buffer)
  5065. (js2-token-end token) js2-ts-cursor)
  5066. ;; FIXME: Invalid in ES5 and ES6, see
  5067. ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
  5068. ;; Probably should just drop this conditional.
  5069. (unless contains-escape
  5070. ;; OPT we shouldn't have to make a string (object!) to
  5071. ;; check if it's a keyword.
  5072. ;; Return the corresponding token if it's a keyword
  5073. (when (and (not (eq modifier 'KEYWORD_IS_NAME))
  5074. (setq result (js2-string-to-keyword str)))
  5075. (if (and (< js2-language-version 170)
  5076. (memq result '(js2-LET js2-YIELD)))
  5077. ;; LET and YIELD are tokens only in 1.7 and later
  5078. (setq result 'js2-NAME))
  5079. (when (eq result 'js2-RESERVED)
  5080. (setf (js2-token-string token) str))
  5081. (throw 'return (js2-tt-code result))))
  5082. ;; If we want to intern these as Rhino does, just use (intern str)
  5083. (setf (js2-token-string token) str)
  5084. (throw 'return js2-NAME)) ; end identifier/kwd check
  5085. ;; is it a number?
  5086. (when (or (js2-digit-p c)
  5087. (and (eq c ?.) (js2-digit-p (js2-peek-char))))
  5088. (setq js2-ts-string-buffer nil
  5089. base 10)
  5090. (when (eq c ?0)
  5091. (setq c (js2-get-char))
  5092. (cond
  5093. ((or (eq c ?x) (eq c ?X))
  5094. (setq base 16)
  5095. (setq c (js2-get-char)))
  5096. ((and (or (eq c ?b) (eq c ?B))
  5097. (>= js2-language-version 200))
  5098. (setq base 2)
  5099. (setq c (js2-get-char)))
  5100. ((and (or (eq c ?o) (eq c ?O))
  5101. (>= js2-language-version 200))
  5102. (setq base 8)
  5103. (setq legacy-octal nil)
  5104. (setq c (js2-get-char)))
  5105. ((js2-digit-p c)
  5106. (setq base 'maybe-8))
  5107. (t
  5108. (js2-add-to-string ?0))))
  5109. (cond
  5110. ((eq base 16)
  5111. (if (> 0 (js2-x-digit-to-int c 0))
  5112. (js2-report-scan-error "msg.missing.hex.digits")
  5113. (while (<= 0 (js2-x-digit-to-int c 0))
  5114. (js2-add-to-string c)
  5115. (setq c (js2-get-char)))))
  5116. ((eq base 2)
  5117. (if (not (memq c '(?0 ?1)))
  5118. (js2-report-scan-error "msg.missing.binary.digits")
  5119. (while (memq c '(?0 ?1))
  5120. (js2-add-to-string c)
  5121. (setq c (js2-get-char)))))
  5122. ((eq base 8)
  5123. (if (or (> ?0 c) (< ?7 c))
  5124. (js2-report-scan-error "msg.missing.octal.digits")
  5125. (while (and (<= ?0 c) (>= ?7 c))
  5126. (js2-add-to-string c)
  5127. (setq c (js2-get-char)))))
  5128. (t
  5129. (while (and (<= ?0 c) (<= c ?9))
  5130. ;; We permit 08 and 09 as decimal numbers, which
  5131. ;; makes our behavior a superset of the ECMA
  5132. ;; numeric grammar. We might not always be so
  5133. ;; permissive, so we warn about it.
  5134. (when (and (eq base 'maybe-8) (>= c ?8))
  5135. (js2-report-warning "msg.bad.octal.literal"
  5136. (if (eq c ?8) "8" "9"))
  5137. (setq base 10))
  5138. (js2-add-to-string c)
  5139. (setq c (js2-get-char)))
  5140. (when (eq base 'maybe-8)
  5141. (setq base 8
  5142. legacy-octal t))))
  5143. (when (and (eq base 10) (memq c '(?. ?e ?E)))
  5144. (when (eq c ?.)
  5145. (cl-loop do
  5146. (js2-add-to-string c)
  5147. (setq c (js2-get-char))
  5148. while (js2-digit-p c)))
  5149. (when (memq c '(?e ?E))
  5150. (js2-add-to-string c)
  5151. (setq c (js2-get-char))
  5152. (when (memq c '(?+ ?-))
  5153. (js2-add-to-string c)
  5154. (setq c (js2-get-char)))
  5155. (unless (js2-digit-p c)
  5156. (js2-report-scan-error "msg.missing.exponent" t))
  5157. (cl-loop do
  5158. (js2-add-to-string c)
  5159. (setq c (js2-get-char))
  5160. while (js2-digit-p c))))
  5161. (js2-unget-char)
  5162. (let ((str (js2-set-string-from-buffer token)))
  5163. (setf (js2-token-number token) (js2-string-to-number str base)
  5164. (js2-token-number-base token) base
  5165. (js2-token-number-legacy-octal-p token) (and (= base 8) legacy-octal)))
  5166. (throw 'return js2-NUMBER))
  5167. ;; is it a string?
  5168. (when (or (memq c '(?\" ?\'))
  5169. (and (>= js2-language-version 200)
  5170. (= c ?`)))
  5171. (throw 'return
  5172. (js2-get-string-or-template-token c token)))
  5173. (js2-ts-return token
  5174. (cl-case c
  5175. (?\;
  5176. (throw 'return js2-SEMI))
  5177. (?\[
  5178. (throw 'return js2-LB))
  5179. (?\]
  5180. (throw 'return js2-RB))
  5181. (?{
  5182. (throw 'return js2-LC))
  5183. (?}
  5184. (throw 'return js2-RC))
  5185. (?\(
  5186. (throw 'return js2-LP))
  5187. (?\)
  5188. (throw 'return js2-RP))
  5189. (?,
  5190. (throw 'return js2-COMMA))
  5191. (??
  5192. (if (js2-match-char ??)
  5193. (if (js2-match-char ?=)
  5194. js2-ASSIGN_NULLISH
  5195. (throw 'return js2-NULLISH-COALESCING))
  5196. (if (js2-match-char ?.)
  5197. (throw 'return js2-OPTIONAL-CHAINING)
  5198. (throw 'return js2-HOOK))))
  5199. (?:
  5200. (if (js2-match-char ?:)
  5201. js2-COLONCOLON
  5202. (throw 'return js2-COLON)))
  5203. (?.
  5204. (if (js2-match-char ?.)
  5205. (if (js2-match-char ?.)
  5206. js2-TRIPLEDOT js2-DOTDOT)
  5207. (if (js2-match-char ?\()
  5208. js2-DOTQUERY
  5209. (throw 'return js2-DOT))))
  5210. (?|
  5211. (if (js2-match-char ?|)
  5212. (if (js2-match-char ?=)
  5213. js2-ASSIGN_OR
  5214. (throw 'return js2-OR))
  5215. (if (js2-match-char ?=)
  5216. js2-ASSIGN_BITOR
  5217. (throw 'return js2-BITOR))))
  5218. (?^
  5219. (if (js2-match-char ?=)
  5220. js2-ASSIGN_BITOR
  5221. (throw 'return js2-BITXOR)))
  5222. (?&
  5223. (if (js2-match-char ?&)
  5224. (if (js2-match-char ?=)
  5225. js2-ASSIGN_AND
  5226. (throw 'return js2-AND))
  5227. (if (js2-match-char ?=)
  5228. js2-ASSIGN_BITAND
  5229. (throw 'return js2-BITAND))))
  5230. (?=
  5231. (if (js2-match-char ?=)
  5232. (if (js2-match-char ?=)
  5233. js2-SHEQ
  5234. (throw 'return js2-EQ))
  5235. (if (js2-match-char ?>)
  5236. (js2-ts-return token js2-ARROW)
  5237. (throw 'return js2-ASSIGN))))
  5238. (?!
  5239. (if (js2-match-char ?=)
  5240. (if (js2-match-char ?=)
  5241. js2-SHNE
  5242. js2-NE)
  5243. (throw 'return js2-NOT)))
  5244. (?<
  5245. ;; NB:treat HTML begin-comment as comment-till-eol
  5246. (when (js2-match-char ?!)
  5247. (when (js2-match-char ?-)
  5248. (when (js2-match-char ?-)
  5249. (js2-skip-line)
  5250. (setf (js2-token-comment-type (js2-current-token)) 'html)
  5251. (throw 'return js2-COMMENT)))
  5252. (js2-unget-char))
  5253. (if (js2-match-char ?<)
  5254. (if (js2-match-char ?=)
  5255. js2-ASSIGN_LSH
  5256. js2-LSH)
  5257. (if (js2-match-char ?=)
  5258. js2-LE
  5259. (throw 'return js2-LT))))
  5260. (?>
  5261. (if (js2-match-char ?>)
  5262. (if (js2-match-char ?>)
  5263. (if (js2-match-char ?=)
  5264. js2-ASSIGN_URSH
  5265. js2-URSH)
  5266. (if (js2-match-char ?=)
  5267. js2-ASSIGN_RSH
  5268. js2-RSH))
  5269. (if (js2-match-char ?=)
  5270. js2-GE
  5271. (throw 'return js2-GT))))
  5272. (?*
  5273. (if (js2-match-char ?=)
  5274. js2-ASSIGN_MUL
  5275. (if (js2-match-char ?*)
  5276. (if (js2-match-char ?=)
  5277. js2-ASSIGN_EXPON
  5278. js2-EXPON)
  5279. (throw 'return js2-MUL))))
  5280. (?/
  5281. ;; is it a // comment?
  5282. (when (js2-match-char ?/)
  5283. (setf (js2-token-beg token) (- js2-ts-cursor 2))
  5284. (js2-skip-line)
  5285. (setf (js2-token-comment-type token) 'line)
  5286. ;; include newline so highlighting goes to end of
  5287. ;; window, if there actually is a newline; if we
  5288. ;; hit eof, then implicitly there isn't
  5289. (unless js2-ts-hit-eof
  5290. (cl-incf (js2-token-end token)))
  5291. (throw 'return js2-COMMENT))
  5292. ;; is it a /* comment?
  5293. (when (js2-match-char ?*)
  5294. (setf look-for-slash nil
  5295. (js2-token-beg token) (- js2-ts-cursor 2)
  5296. (js2-token-comment-type token)
  5297. (if (js2-match-char ?*)
  5298. (progn
  5299. (setq look-for-slash t)
  5300. 'jsdoc)
  5301. 'block))
  5302. (while t
  5303. (setq c (js2-get-char))
  5304. (cond
  5305. ((eq c js2-EOF_CHAR)
  5306. (setf (js2-token-end token) (1- js2-ts-cursor))
  5307. (js2-report-error "msg.unterminated.comment")
  5308. (throw 'return js2-COMMENT))
  5309. ((eq c ?*)
  5310. (setq look-for-slash t))
  5311. ((eq c ?/)
  5312. (if look-for-slash
  5313. (js2-ts-return token js2-COMMENT)))
  5314. (t
  5315. (setf look-for-slash nil
  5316. (js2-token-end token) js2-ts-cursor)))))
  5317. (if (js2-match-char ?=)
  5318. js2-ASSIGN_DIV
  5319. (throw 'return js2-DIV)))
  5320. (?#
  5321. (when js2-skip-preprocessor-directives
  5322. (js2-skip-line)
  5323. (setf (js2-token-comment-type token) 'preprocessor
  5324. (js2-token-end token) js2-ts-cursor)
  5325. (throw 'return js2-COMMENT))
  5326. (throw 'return js2-ERROR))
  5327. (?%
  5328. (if (js2-match-char ?=)
  5329. js2-ASSIGN_MOD
  5330. (throw 'return js2-MOD)))
  5331. (?~
  5332. (throw 'return js2-BITNOT))
  5333. (?+
  5334. (if (js2-match-char ?=)
  5335. js2-ASSIGN_ADD
  5336. (if (js2-match-char ?+)
  5337. js2-INC
  5338. (throw 'return js2-ADD))))
  5339. (?-
  5340. (cond
  5341. ((js2-match-char ?=)
  5342. (setq c js2-ASSIGN_SUB))
  5343. ((js2-match-char ?-)
  5344. (unless js2-ts-dirty-line
  5345. ;; treat HTML end-comment after possible whitespace
  5346. ;; after line start as comment-until-eol
  5347. (when (js2-match-char ?>)
  5348. (js2-skip-line)
  5349. (setf (js2-token-comment-type (js2-current-token)) 'html)
  5350. (throw 'return js2-COMMENT)))
  5351. (setq c js2-DEC))
  5352. (t
  5353. (setq c js2-SUB)))
  5354. (setq js2-ts-dirty-line t)
  5355. c)
  5356. (otherwise
  5357. (js2-report-scan-error "msg.illegal.character")))))))
  5358. (setf (js2-token-type token) tt)
  5359. token))
  5360. (defun js2-get-string-or-template-token (quote-char token)
  5361. ;; We attempt to accumulate a string the fast way, by
  5362. ;; building it directly out of the reader. But if there
  5363. ;; are any escaped characters in the string, we revert to
  5364. ;; building it out of a string buffer.
  5365. (let ((c (js2-get-char))
  5366. js2-ts-string-buffer
  5367. nc c1 val escape-val)
  5368. (catch 'break
  5369. (while (/= c quote-char)
  5370. (catch 'continue
  5371. (when (eq c js2-EOF_CHAR)
  5372. (js2-unget-char)
  5373. (js2-report-error "msg.unterminated.string.lit")
  5374. (throw 'break nil))
  5375. (when (and (eq c ?\n) (not (eq quote-char ?`)))
  5376. (js2-unget-char)
  5377. (js2-report-error "msg.unterminated.string.lit")
  5378. (throw 'break nil))
  5379. (when (eq c ?\\)
  5380. ;; We've hit an escaped character
  5381. (setq c (js2-get-char))
  5382. (cl-case c
  5383. (?b (setq c ?\b))
  5384. (?f (setq c ?\f))
  5385. (?n (setq c ?\n))
  5386. (?r (setq c ?\r))
  5387. (?t (setq c ?\t))
  5388. (?v (setq c ?\v))
  5389. (?u
  5390. (setq c1 (js2-read-unicode-escape))
  5391. (if js2-parse-ide-mode
  5392. (if c1
  5393. (progn
  5394. ;; just copy the string in IDE-mode
  5395. (js2-add-to-string ?\\)
  5396. (js2-add-to-string ?u)
  5397. (dotimes (_ 3)
  5398. (js2-add-to-string (js2-get-char)))
  5399. (setq c (js2-get-char))) ; added at end of loop
  5400. ;; flag it as an invalid escape
  5401. (js2-report-warning "msg.invalid.escape"
  5402. nil (- js2-ts-cursor 2) 6))
  5403. ;; Get 4 hex digits; if the u escape is not
  5404. ;; followed by 4 hex digits, use 'u' + the
  5405. ;; literal character sequence that follows.
  5406. (js2-add-to-string ?u)
  5407. (setq escape-val 0)
  5408. (dotimes (_ 4)
  5409. (setq c (js2-get-char)
  5410. escape-val (js2-x-digit-to-int c escape-val))
  5411. (if (cl-minusp escape-val)
  5412. (throw 'continue nil))
  5413. (js2-add-to-string c))
  5414. ;; prepare for replace of stored 'u' sequence by escape value
  5415. (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
  5416. c escape-val)))
  5417. (?x
  5418. ;; Get 2 hex digits, defaulting to 'x'+literal
  5419. ;; sequence, as above.
  5420. (setq c (js2-get-char)
  5421. escape-val (js2-x-digit-to-int c 0))
  5422. (if (cl-minusp escape-val)
  5423. (progn
  5424. (js2-add-to-string ?x)
  5425. (throw 'continue nil))
  5426. (setq c1 c
  5427. c (js2-get-char)
  5428. escape-val (js2-x-digit-to-int c escape-val))
  5429. (if (cl-minusp escape-val)
  5430. (progn
  5431. (js2-add-to-string ?x)
  5432. (js2-add-to-string c1)
  5433. (throw 'continue nil))
  5434. ;; got 2 hex digits
  5435. (setq c escape-val))))
  5436. (?\n
  5437. ;; Remove line terminator after escape to follow
  5438. ;; SpiderMonkey and C/C++
  5439. (setq c (js2-get-char))
  5440. (throw 'continue nil))
  5441. (t
  5442. (when (and (<= ?0 c) (< c ?8))
  5443. (setq val (- c ?0)
  5444. c (js2-get-char))
  5445. (when (and (<= ?0 c) (< c ?8))
  5446. (setq val (- (+ (* 8 val) c) ?0)
  5447. c (js2-get-char))
  5448. (when (and (<= ?0 c)
  5449. (< c ?8)
  5450. (< val #o37))
  5451. ;; c is 3rd char of octal sequence only
  5452. ;; if the resulting val <= 0377
  5453. (setq val (- (+ (* 8 val) c) ?0)
  5454. c (js2-get-char))))
  5455. (js2-unget-char)
  5456. (setq c val)))))
  5457. (when (and (eq quote-char ?`) (eq c ?$))
  5458. (when (eq (setq nc (js2-get-char)) ?\{)
  5459. (throw 'break nil))
  5460. (js2-unget-char))
  5461. (js2-add-to-string c)
  5462. (setq c (js2-get-char)))))
  5463. (js2-set-string-from-buffer token)
  5464. (if (not (eq quote-char ?`))
  5465. js2-STRING
  5466. (if (and (eq c ?$) (eq nc ?\{))
  5467. js2-TEMPLATE_HEAD
  5468. js2-NO_SUBS_TEMPLATE))))
  5469. (defun js2-read-regexp (start-tt start-pos)
  5470. "Called by parser when it gets / or /= in literal context."
  5471. (let (c err
  5472. in-class ; inside a '[' .. ']' character-class
  5473. flags
  5474. (continue t)
  5475. (token (js2-new-token 0)))
  5476. (when js2-mode-change-syntax-p
  5477. (js2-record-text-property start-pos (1+ start-pos)
  5478. 'syntax-table (string-to-syntax "\"/")))
  5479. (setq js2-ts-string-buffer nil)
  5480. (if (eq start-tt js2-ASSIGN_DIV)
  5481. ;; mis-scanned /=
  5482. (js2-add-to-string ?=)
  5483. (if (not (eq start-tt js2-DIV))
  5484. (error "failed assertion")))
  5485. (while (and (not err)
  5486. (or (/= (setq c (js2-get-char)) ?/)
  5487. in-class))
  5488. (cond
  5489. ((or (= c ?\n)
  5490. (= c js2-EOF_CHAR))
  5491. (setf (js2-token-end token) (1- js2-ts-cursor)
  5492. err t
  5493. (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
  5494. (js2-report-error "msg.unterminated.re.lit"))
  5495. (t (cond
  5496. ((= c ?\\)
  5497. (js2-add-to-string c)
  5498. (setq c (js2-get-char)))
  5499. ((= c ?\[)
  5500. (setq in-class t))
  5501. ((= c ?\])
  5502. (setq in-class nil)))
  5503. (js2-add-to-string c))))
  5504. (unless err
  5505. (when js2-mode-change-syntax-p
  5506. (js2-record-text-property (1- js2-ts-cursor) js2-ts-cursor
  5507. 'syntax-table (string-to-syntax "\"/")))
  5508. (while continue
  5509. (cond
  5510. ((js2-match-char ?g)
  5511. (push ?g flags))
  5512. ((js2-match-char ?i)
  5513. (push ?i flags))
  5514. ((js2-match-char ?m)
  5515. (push ?m flags))
  5516. ((and (js2-match-char ?u)
  5517. (>= js2-language-version 200))
  5518. (push ?u flags))
  5519. ((and (js2-match-char ?y)
  5520. (>= js2-language-version 200))
  5521. (push ?y flags))
  5522. (t
  5523. (setq continue nil))))
  5524. (if (js2-alpha-p (js2-peek-char))
  5525. (js2-report-scan-error "msg.invalid.re.flag" t
  5526. js2-ts-cursor 1))
  5527. (js2-set-string-from-buffer token))
  5528. (js2-collect-string flags)))
  5529. (defun js2-get-first-xml-token ()
  5530. (setq js2-ts-xml-open-tags-count 0
  5531. js2-ts-is-xml-attribute nil
  5532. js2-ts-xml-is-tag-content nil)
  5533. (js2-unget-char)
  5534. (js2-get-next-xml-token))
  5535. (defun js2-xml-discard-string (token)
  5536. "Throw away the string in progress and flag an XML parse error."
  5537. (setf js2-ts-string-buffer nil
  5538. (js2-token-string token) nil)
  5539. (js2-report-scan-error "msg.XML.bad.form" t))
  5540. (defun js2-get-next-xml-token ()
  5541. (setq js2-ts-string-buffer nil) ; for recording the XML
  5542. (let ((token (js2-new-token 0))
  5543. c result)
  5544. (setq result
  5545. (catch 'return
  5546. (while t
  5547. (setq c (js2-get-char))
  5548. (cond
  5549. ((= c js2-EOF_CHAR)
  5550. (throw 'return js2-ERROR))
  5551. (js2-ts-xml-is-tag-content
  5552. (cl-case c
  5553. (?>
  5554. (js2-add-to-string c)
  5555. (setq js2-ts-xml-is-tag-content nil
  5556. js2-ts-is-xml-attribute nil))
  5557. (?/
  5558. (js2-add-to-string c)
  5559. (when (eq ?> (js2-peek-char))
  5560. (setq c (js2-get-char))
  5561. (js2-add-to-string c)
  5562. (setq js2-ts-xml-is-tag-content nil)
  5563. (cl-decf js2-ts-xml-open-tags-count)))
  5564. (?{
  5565. (js2-unget-char)
  5566. (js2-set-string-from-buffer token)
  5567. (throw 'return js2-XML))
  5568. ((?\' ?\")
  5569. (js2-add-to-string c)
  5570. (unless (js2-read-quoted-string c token)
  5571. (throw 'return js2-ERROR)))
  5572. (?=
  5573. (js2-add-to-string c)
  5574. (setq js2-ts-is-xml-attribute t))
  5575. ((? ?\t ?\r ?\n)
  5576. (js2-add-to-string c))
  5577. (t
  5578. (js2-add-to-string c)
  5579. (setq js2-ts-is-xml-attribute nil)))
  5580. (when (and (not js2-ts-xml-is-tag-content)
  5581. (zerop js2-ts-xml-open-tags-count))
  5582. (js2-set-string-from-buffer token)
  5583. (throw 'return js2-XMLEND)))
  5584. (t
  5585. ;; else not tag content
  5586. (cl-case c
  5587. (?<
  5588. (js2-add-to-string c)
  5589. (setq c (js2-peek-char))
  5590. (cl-case c
  5591. (?!
  5592. (setq c (js2-get-char)) ;; skip !
  5593. (js2-add-to-string c)
  5594. (setq c (js2-peek-char))
  5595. (cl-case c
  5596. (?-
  5597. (setq c (js2-get-char)) ;; skip -
  5598. (js2-add-to-string c)
  5599. (if (eq c ?-)
  5600. (progn
  5601. (js2-add-to-string c)
  5602. (unless (js2-read-xml-comment token)
  5603. (throw 'return js2-ERROR)))
  5604. (js2-xml-discard-string token)
  5605. (throw 'return js2-ERROR)))
  5606. (?\[
  5607. (setq c (js2-get-char)) ;; skip [
  5608. (js2-add-to-string c)
  5609. (if (and (= (js2-get-char) ?C)
  5610. (= (js2-get-char) ?D)
  5611. (= (js2-get-char) ?A)
  5612. (= (js2-get-char) ?T)
  5613. (= (js2-get-char) ?A)
  5614. (= (js2-get-char) ?\[))
  5615. (progn
  5616. (js2-add-to-string ?C)
  5617. (js2-add-to-string ?D)
  5618. (js2-add-to-string ?A)
  5619. (js2-add-to-string ?T)
  5620. (js2-add-to-string ?A)
  5621. (js2-add-to-string ?\[)
  5622. (unless (js2-read-cdata token)
  5623. (throw 'return js2-ERROR)))
  5624. (js2-xml-discard-string token)
  5625. (throw 'return js2-ERROR)))
  5626. (t
  5627. (unless (js2-read-entity token)
  5628. (throw 'return js2-ERROR))))
  5629. ;; Allow bare CDATA section, e.g.:
  5630. ;; let xml = <![CDATA[ foo bar baz ]]>;
  5631. (when (zerop js2-ts-xml-open-tags-count)
  5632. (throw 'return js2-XMLEND)))
  5633. (??
  5634. (setq c (js2-get-char)) ;; skip ?
  5635. (js2-add-to-string c)
  5636. (unless (js2-read-PI token)
  5637. (throw 'return js2-ERROR)))
  5638. (?/
  5639. ;; end tag
  5640. (setq c (js2-get-char)) ;; skip /
  5641. (js2-add-to-string c)
  5642. (when (zerop js2-ts-xml-open-tags-count)
  5643. (js2-xml-discard-string token)
  5644. (throw 'return js2-ERROR))
  5645. (setq js2-ts-xml-is-tag-content t)
  5646. (cl-decf js2-ts-xml-open-tags-count))
  5647. (t
  5648. ;; start tag
  5649. (setq js2-ts-xml-is-tag-content t)
  5650. (cl-incf js2-ts-xml-open-tags-count))))
  5651. (?{
  5652. (js2-unget-char)
  5653. (js2-set-string-from-buffer token)
  5654. (throw 'return js2-XML))
  5655. (t
  5656. (js2-add-to-string c))))))))
  5657. (setf (js2-token-end token) js2-ts-cursor)
  5658. (setf (js2-token-type token) result)
  5659. result))
  5660. (defun js2-read-quoted-string (quote token)
  5661. (let (c)
  5662. (catch 'return
  5663. (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
  5664. (js2-add-to-string c)
  5665. (if (eq c quote)
  5666. (throw 'return t)))
  5667. (js2-xml-discard-string token) ;; throw away string in progress
  5668. nil)))
  5669. (defun js2-read-xml-comment (token)
  5670. (let ((c (js2-get-char)))
  5671. (catch 'return
  5672. (while (/= c js2-EOF_CHAR)
  5673. (catch 'continue
  5674. (js2-add-to-string c)
  5675. (when (and (eq c ?-) (eq ?- (js2-peek-char)))
  5676. (setq c (js2-get-char))
  5677. (js2-add-to-string c)
  5678. (if (eq (js2-peek-char) ?>)
  5679. (progn
  5680. (setq c (js2-get-char)) ;; skip >
  5681. (js2-add-to-string c)
  5682. (throw 'return t))
  5683. (throw 'continue nil)))
  5684. (setq c (js2-get-char))))
  5685. (js2-xml-discard-string token)
  5686. nil)))
  5687. (defun js2-read-cdata (token)
  5688. (let ((c (js2-get-char)))
  5689. (catch 'return
  5690. (while (/= c js2-EOF_CHAR)
  5691. (catch 'continue
  5692. (js2-add-to-string c)
  5693. (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
  5694. (setq c (js2-get-char))
  5695. (js2-add-to-string c)
  5696. (if (eq (js2-peek-char) ?>)
  5697. (progn
  5698. (setq c (js2-get-char)) ;; Skip >
  5699. (js2-add-to-string c)
  5700. (throw 'return t))
  5701. (throw 'continue nil)))
  5702. (setq c (js2-get-char))))
  5703. (js2-xml-discard-string token)
  5704. nil)))
  5705. (defun js2-read-entity (token)
  5706. (let ((decl-tags 1)
  5707. c)
  5708. (catch 'return
  5709. (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
  5710. (js2-add-to-string c)
  5711. (cl-case c
  5712. (?<
  5713. (cl-incf decl-tags))
  5714. (?>
  5715. (cl-decf decl-tags)
  5716. (if (zerop decl-tags)
  5717. (throw 'return t)))))
  5718. (js2-xml-discard-string token)
  5719. nil)))
  5720. (defun js2-read-PI (token)
  5721. "Scan an XML processing instruction."
  5722. (let (c)
  5723. (catch 'return
  5724. (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
  5725. (js2-add-to-string c)
  5726. (when (and (eq c ??) (eq (js2-peek-char) ?>))
  5727. (setq c (js2-get-char)) ;; Skip >
  5728. (js2-add-to-string c)
  5729. (throw 'return t)))
  5730. (js2-xml-discard-string token)
  5731. nil)))
  5732. ;;; Highlighting
  5733. (defun js2-set-face (beg end face &optional record)
  5734. "Fontify a region. If RECORD is non-nil, record for later."
  5735. (when (cl-plusp js2-highlight-level)
  5736. (setq beg (min (point-max) beg)
  5737. beg (max (point-min) beg)
  5738. end (min (point-max) end)
  5739. end (max (point-min) end))
  5740. (if record
  5741. (push (list beg end face) js2-mode-fontifications)
  5742. (put-text-property beg end 'font-lock-face face))))
  5743. (defsubst js2-clear-face (beg end)
  5744. (remove-text-properties beg end '(font-lock-face nil
  5745. help-echo nil
  5746. point-entered nil
  5747. cursor-sensor-functions nil
  5748. c-in-sws nil)))
  5749. (defconst js2-ecma-global-props
  5750. (concat "^"
  5751. (regexp-opt
  5752. '("Infinity" "NaN" "undefined" "arguments") t)
  5753. "$")
  5754. "Value properties of the Ecma-262 Global Object.
  5755. Shown at or above `js2-highlight-level' 2.")
  5756. ;; might want to add the name "arguments" to this list?
  5757. (defconst js2-ecma-object-props
  5758. (concat "^"
  5759. (regexp-opt
  5760. '("prototype" "__proto__" "__parent__") t)
  5761. "$")
  5762. "Value properties of the Ecma-262 Object constructor.
  5763. Shown at or above `js2-highlight-level' 2.")
  5764. (defconst js2-ecma-global-funcs
  5765. (concat
  5766. "^"
  5767. (regexp-opt
  5768. '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
  5769. "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
  5770. "$")
  5771. "Function properties of the Ecma-262 Global object.
  5772. Shown at or above `js2-highlight-level' 2.")
  5773. (defconst js2-ecma-number-props
  5774. (concat "^"
  5775. (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
  5776. "NEGATIVE_INFINITY"
  5777. "POSITIVE_INFINITY") t)
  5778. "$")
  5779. "Properties of the Ecma-262 Number constructor.
  5780. Shown at or above `js2-highlight-level' 2.")
  5781. (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
  5782. "Properties of the Ecma-262 Date constructor.
  5783. Shown at or above `js2-highlight-level' 2.")
  5784. (defconst js2-ecma-math-props
  5785. (concat "^"
  5786. (regexp-opt
  5787. '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
  5788. t)
  5789. "$")
  5790. "Properties of the Ecma-262 Math object.
  5791. Shown at or above `js2-highlight-level' 2.")
  5792. (defconst js2-ecma-math-funcs
  5793. (concat "^"
  5794. (regexp-opt
  5795. '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
  5796. "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
  5797. "$")
  5798. "Function properties of the Ecma-262 Math object.
  5799. Shown at or above `js2-highlight-level' 2.")
  5800. (defconst js2-ecma-function-props
  5801. (concat
  5802. "^"
  5803. (regexp-opt
  5804. '(;; properties of the Object prototype object
  5805. "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
  5806. "toLocaleString" "toString" "valueOf"
  5807. ;; properties of the Function prototype object
  5808. "apply" "call"
  5809. ;; properties of the Array prototype object
  5810. "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
  5811. "splice" "unshift"
  5812. ;; properties of the String prototype object
  5813. "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
  5814. "localeCompare" "match" "replace" "search" "split" "substring"
  5815. "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
  5816. "toUpperCase"
  5817. ;; properties of the Number prototype object
  5818. "toExponential" "toFixed" "toPrecision"
  5819. ;; properties of the Date prototype object
  5820. "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
  5821. "getMinutes" "getMonth" "getSeconds" "getTime"
  5822. "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
  5823. "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
  5824. "getUTCSeconds" "setDate" "setFullYear" "setHours"
  5825. "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
  5826. "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
  5827. "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
  5828. "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
  5829. "toTimeString" "toUTCString"
  5830. ;; properties of the RegExp prototype object
  5831. "exec" "test"
  5832. ;; properties of the JSON prototype object
  5833. "parse" "stringify"
  5834. ;; SpiderMonkey/Rhino extensions, versions 1.5+
  5835. "toSource" "__defineGetter__" "__defineSetter__"
  5836. "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
  5837. "every" "filter" "forEach" "lastIndexOf" "map" "some")
  5838. t)
  5839. "$")
  5840. "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
  5841. Shown at or above `js2-highlight-level' 3.")
  5842. (defun js2-parse-highlight-prop-get (parent target prop call-p)
  5843. (let ((target-name (and target
  5844. (js2-name-node-p target)
  5845. (js2-name-node-name target)))
  5846. (prop-name (if prop (js2-name-node-name prop)))
  5847. (level2 (>= js2-highlight-level 2))
  5848. (level3 (>= js2-highlight-level 3)))
  5849. (when level2
  5850. (let ((face
  5851. (if call-p
  5852. (cond
  5853. ((and target prop)
  5854. (cond
  5855. ((and level3 (string-match js2-ecma-function-props prop-name))
  5856. 'font-lock-builtin-face)
  5857. ((and target-name prop)
  5858. (cond
  5859. ((string= target-name "Date")
  5860. (if (string-match js2-ecma-date-props prop-name)
  5861. 'font-lock-builtin-face))
  5862. ((string= target-name "Math")
  5863. (if (string-match js2-ecma-math-funcs prop-name)
  5864. 'font-lock-builtin-face))))))
  5865. (prop
  5866. (if (string-match js2-ecma-global-funcs prop-name)
  5867. 'font-lock-builtin-face)))
  5868. (cond
  5869. ((and target prop)
  5870. (cond
  5871. ((string= target-name "Number")
  5872. (if (string-match js2-ecma-number-props prop-name)
  5873. 'font-lock-constant-face))
  5874. ((string= target-name "Math")
  5875. (if (string-match js2-ecma-math-props prop-name)
  5876. 'font-lock-constant-face))))
  5877. (prop
  5878. (if (string-match js2-ecma-object-props prop-name)
  5879. 'font-lock-constant-face))))))
  5880. (when (and (not face) target (not call-p) prop-name)
  5881. (setq face 'js2-object-property-access))
  5882. (when face
  5883. (let ((pos (+ (js2-node-pos parent) ; absolute
  5884. (js2-node-pos prop)))) ; relative
  5885. (js2-set-face pos
  5886. (+ pos (js2-node-len prop))
  5887. face 'record)))))))
  5888. (defun js2-parse-highlight-member-expr-node (node)
  5889. "Perform syntax highlighting of EcmaScript built-in properties.
  5890. The variable `js2-highlight-level' governs this highlighting."
  5891. (let (face target prop name pos end parent call-p callee)
  5892. (cond
  5893. ;; case 1: simple name, e.g. foo
  5894. ((js2-name-node-p node)
  5895. (setq name (js2-name-node-name node))
  5896. ;; possible for name to be nil in rare cases - saw it when
  5897. ;; running js2-mode on an elisp buffer. Might as well try to
  5898. ;; make it so js2-mode never barfs.
  5899. (when name
  5900. (setq face (if (string-match js2-ecma-global-props name)
  5901. 'font-lock-constant-face))
  5902. (when face
  5903. (setq pos (js2-node-pos node)
  5904. end (+ pos (js2-node-len node)))
  5905. (js2-set-face pos end face 'record))))
  5906. ;; case 2: property access or function call
  5907. ((or (js2-prop-get-node-p node)
  5908. ;; highlight function call if expr is a prop-get node
  5909. ;; or a plain name (i.e. unqualified function call)
  5910. (and (setq call-p (js2-call-node-p node))
  5911. (setq callee (js2-call-node-target node)) ; separate setq!
  5912. (or (js2-prop-get-node-p callee)
  5913. (js2-name-node-p callee))))
  5914. (setq parent node
  5915. node (if call-p callee node))
  5916. (if (and call-p (js2-name-node-p callee))
  5917. (setq prop callee)
  5918. (setq target (js2-prop-get-node-left node)
  5919. prop (js2-prop-get-node-right node)))
  5920. (cond
  5921. ((js2-name-node-p prop)
  5922. ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
  5923. (js2-parse-highlight-prop-get parent target prop call-p))
  5924. ((js2-name-node-p target)
  5925. ;; case 2b: simple target, complex name, e.g. foo.x[y]
  5926. (js2-parse-highlight-prop-get parent target nil call-p)))))))
  5927. (defun js2-parse-highlight-member-expr-fn-name (expr)
  5928. "Highlight the `baz' in function foo.bar.baz(args) {...}.
  5929. This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
  5930. We currently only handle the case where the last component is a prop-get
  5931. of a simple name. Called before EXPR has a parent node."
  5932. (let (pos
  5933. (name (and (js2-prop-get-node-p expr)
  5934. (js2-prop-get-node-right expr))))
  5935. (when (js2-name-node-p name)
  5936. (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
  5937. (js2-node-pos name)))
  5938. (+ pos (js2-node-len name))
  5939. 'font-lock-function-name-face
  5940. 'record))))
  5941. ;; source: http://jsdoc.sourceforge.net/
  5942. ;; Note - this syntax is for Google's enhanced jsdoc parser that
  5943. ;; allows type specifications, and needs work before entering the wild.
  5944. (defconst js2-jsdoc-param-tag-regexp
  5945. (concat "^\\s-*\\*+\\s-*\\(@"
  5946. (regexp-opt '("param" "arg" "argument" "prop" "property" "typedef"))
  5947. "\\)"
  5948. "\\s-*\\({[^}]+}\\)?" ; optional type
  5949. "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
  5950. "\\_>")
  5951. "Matches jsdoc tags with optional type and optional param name.")
  5952. (defconst js2-jsdoc-typed-tag-regexp
  5953. (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
  5954. (regexp-opt
  5955. '("enum"
  5956. "extends"
  5957. "field"
  5958. "id"
  5959. "implements"
  5960. "lends"
  5961. "mods"
  5962. "requires"
  5963. "return"
  5964. "returns"
  5965. "yield"
  5966. "yields"
  5967. "type"
  5968. "throw"
  5969. "throws"))
  5970. "\\)\\)\\s-*\\({[^}]+}\\)?")
  5971. "Matches jsdoc tags with optional type.")
  5972. (defconst js2-jsdoc-arg-tag-regexp
  5973. (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
  5974. (regexp-opt
  5975. '("alias"
  5976. "augments"
  5977. "borrows"
  5978. "callback"
  5979. "bug"
  5980. "base"
  5981. "config"
  5982. "default"
  5983. "define"
  5984. "exception"
  5985. "func"
  5986. "function"
  5987. "member"
  5988. "memberOf"
  5989. "method"
  5990. "module"
  5991. "name"
  5992. "namespace"
  5993. "since"
  5994. "suppress"
  5995. "this"
  5996. "throws"
  5997. "version"))
  5998. "\\)\\)\\s-+\\([^ \t\n]+\\)")
  5999. "Matches jsdoc tags with a single argument.")
  6000. (defconst js2-jsdoc-empty-tag-regexp
  6001. (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
  6002. (regexp-opt
  6003. '("abstract"
  6004. "addon"
  6005. "author"
  6006. "class"
  6007. "const"
  6008. "constant"
  6009. "constructor"
  6010. "constructs"
  6011. "deprecated"
  6012. "desc"
  6013. "description"
  6014. "event"
  6015. "example"
  6016. "exec"
  6017. "export"
  6018. "fileoverview"
  6019. "final"
  6020. "func"
  6021. "function"
  6022. "hidden"
  6023. "ignore"
  6024. "implicitCast"
  6025. "inheritDoc"
  6026. "inner"
  6027. "interface"
  6028. "license"
  6029. "method"
  6030. "noalias"
  6031. "noshadow"
  6032. "notypecheck"
  6033. "override"
  6034. "owner"
  6035. "preserve"
  6036. "preserveTry"
  6037. "private"
  6038. "protected"
  6039. "public"
  6040. "static"
  6041. "supported"
  6042. "virtual"
  6043. ))
  6044. "\\)\\)\\s-*")
  6045. "Matches empty jsdoc tags.")
  6046. (defconst js2-jsdoc-link-tag-regexp
  6047. "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
  6048. "Matches a jsdoc link or code tag.")
  6049. (defconst js2-jsdoc-see-tag-regexp
  6050. "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
  6051. "Matches a jsdoc @see tag.")
  6052. (defconst js2-jsdoc-html-tag-regexp
  6053. "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
  6054. "Matches a simple (no attributes) html start- or end-tag.")
  6055. (defun js2-jsdoc-highlight-helper ()
  6056. (js2-set-face (match-beginning 1)
  6057. (match-end 1)
  6058. 'js2-jsdoc-tag)
  6059. (if (match-beginning 2)
  6060. (if (save-excursion
  6061. (goto-char (match-beginning 2))
  6062. (= (char-after) ?{))
  6063. (js2-set-face (1+ (match-beginning 2))
  6064. (1- (match-end 2))
  6065. 'js2-jsdoc-type)
  6066. (js2-set-face (match-beginning 2)
  6067. (match-end 2)
  6068. 'js2-jsdoc-value)))
  6069. (if (match-beginning 3)
  6070. (js2-set-face (match-beginning 3)
  6071. (match-end 3)
  6072. 'js2-jsdoc-value)))
  6073. (defun js2-highlight-jsdoc (ast)
  6074. "Highlight doc comment tags."
  6075. (let ((comments (js2-ast-root-comments ast))
  6076. beg end)
  6077. (save-excursion
  6078. (dolist (node comments)
  6079. (when (eq (js2-comment-node-format node) 'jsdoc)
  6080. ;; Slice off the leading /* and trailing */ in case there
  6081. ;; are tags on the first line
  6082. (setq beg (+ 2 (js2-node-abs-pos node))
  6083. end (+ beg -4 (js2-node-len node)))
  6084. (save-restriction
  6085. (narrow-to-region beg end)
  6086. (dolist (re (list js2-jsdoc-param-tag-regexp
  6087. js2-jsdoc-typed-tag-regexp
  6088. js2-jsdoc-arg-tag-regexp
  6089. js2-jsdoc-link-tag-regexp
  6090. js2-jsdoc-see-tag-regexp
  6091. js2-jsdoc-empty-tag-regexp))
  6092. (goto-char beg)
  6093. (while (re-search-forward re nil t)
  6094. (js2-jsdoc-highlight-helper)))
  6095. ;; simple highlighting for html tags
  6096. (goto-char beg)
  6097. (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
  6098. (js2-set-face (match-beginning 1)
  6099. (match-end 1)
  6100. 'js2-jsdoc-html-tag-delimiter)
  6101. (js2-set-face (match-beginning 2)
  6102. (match-end 2)
  6103. 'js2-jsdoc-html-tag-name)
  6104. (js2-set-face (match-beginning 3)
  6105. (match-end 3)
  6106. 'js2-jsdoc-html-tag-delimiter))))))))
  6107. (defun js2-highlight-assign-targets (_node left right)
  6108. "Highlight function properties and external variables."
  6109. (let (leftpos name)
  6110. ;; highlight vars and props assigned function values
  6111. (when (or (js2-function-node-p right)
  6112. (js2-class-node-p right))
  6113. (cond
  6114. ;; var foo = function() {...}
  6115. ((js2-name-node-p left)
  6116. (setq name left))
  6117. ;; foo.bar.baz = function() {...}
  6118. ((and (js2-prop-get-node-p left)
  6119. (js2-name-node-p (js2-prop-get-node-right left)))
  6120. (setq name (js2-prop-get-node-right left))))
  6121. (when name
  6122. (js2-set-face (setq leftpos (js2-node-abs-pos name))
  6123. (+ leftpos (js2-node-len name))
  6124. 'font-lock-function-name-face
  6125. 'record)))))
  6126. (defun js2-record-name-node (node)
  6127. "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
  6128. later. NODE must be a name node."
  6129. (let ((leftpos (js2-node-abs-pos node)))
  6130. (push (list node js2-current-scope
  6131. leftpos
  6132. (+ leftpos (js2-node-len node)))
  6133. js2-recorded-identifiers)))
  6134. (defun js2-highlight-undeclared-vars ()
  6135. "After entire parse is finished, look for undeclared variable references.
  6136. We have to wait until entire buffer is parsed, since JavaScript permits var
  6137. declarations to occur after they're used.
  6138. Some identifiers may be assumed to be externally defined.
  6139. These externs are not highlighted, even if there is no declaration
  6140. for them in the source code (in the current file).
  6141. The list of externs consists of the following:
  6142. - `js2-ecma262-externs' for basic names from the ECMAScript language standard.
  6143. - Depending on the buffer-local variables `js2-include-*-externs'
  6144. the corresponding `js2-*-externs' to add names for certain environments
  6145. like the browser, Node or Rhino.
  6146. - Two customizable lists `js2-global-externs' and `js2-additional-externs',
  6147. the latter of which should be set per-buffer.
  6148. See especially `js2-additional-externs' for further details about externs."
  6149. (let ((default-externs
  6150. (append js2-ecma-262-externs
  6151. (if (and js2-include-browser-externs
  6152. (>= js2-language-version 200)) js2-harmony-externs)
  6153. (if js2-include-rhino-externs js2-rhino-externs)
  6154. (if js2-include-node-externs js2-node-externs)
  6155. (if (or js2-include-browser-externs js2-include-node-externs)
  6156. js2-typed-array-externs)
  6157. (if js2-include-browser-externs js2-browser-externs)))
  6158. name)
  6159. (dolist (entry js2-recorded-identifiers)
  6160. (cl-destructuring-bind (name-node scope pos end) entry
  6161. (setq name (js2-name-node-name name-node))
  6162. (unless (or (member name js2-global-externs)
  6163. (member name default-externs)
  6164. (member name js2-additional-externs)
  6165. (js2-get-defining-scope scope name pos))
  6166. (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
  6167. 'js2-external-variable))))))
  6168. (defun js2--add-or-update-symbol (symbol inition used vars)
  6169. "Add or update SYMBOL entry in VARS, an hash table.
  6170. SYMBOL is a js2-name-node, INITION either nil, t, or ?P,
  6171. respectively meaning that SYMBOL is a mere declaration, an
  6172. assignment or a function parameter; when USED is t, the symbol
  6173. node is assumed to be an usage and thus added to the list stored
  6174. in the cdr of the entry.
  6175. "
  6176. (let* ((nm (js2-name-node-name symbol))
  6177. (es (js2-node-get-enclosing-scope symbol))
  6178. (ds (js2-get-defining-scope es nm)))
  6179. (when (and ds (not (equal nm "arguments")))
  6180. (let* ((sym (js2-scope-get-symbol ds nm))
  6181. (var (gethash sym vars))
  6182. (err-var-p (js2-catch-node-p ds)))
  6183. (unless inition
  6184. (setq inition err-var-p))
  6185. (if var
  6186. (progn
  6187. (when (and inition (not (equal (car var) ?P)))
  6188. (setcar var inition))
  6189. (when (and used (not (memq symbol (cdr var))))
  6190. (push symbol (cdr var))))
  6191. ;; do not consider the declaration of catch parameter as an usage
  6192. (when (and err-var-p used)
  6193. (setq used nil))
  6194. (puthash sym (cons inition (if used (list symbol))) vars))))))
  6195. (defun js2--collect-target-symbols (node strict)
  6196. "Collect the `js-name-node' symbols declared in NODE and return a list of them.
  6197. NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'.
  6198. When STRICT, signal an error if NODE is not one of the expected types."
  6199. (let (targets)
  6200. (cond
  6201. ((js2-name-node-p node)
  6202. (push node targets))
  6203. ((js2-array-node-p node)
  6204. (dolist (elt (js2-array-node-elems node))
  6205. (when elt
  6206. (setq elt (cond ((js2-infix-node-p elt) ;; default (=)
  6207. (js2-infix-node-left elt))
  6208. ((js2-unary-node-p elt) ;; rest (...)
  6209. (js2-unary-node-operand elt))
  6210. (t elt)))
  6211. (setq targets (append (js2--collect-target-symbols elt strict)
  6212. targets)))))
  6213. ((js2-object-node-p node)
  6214. (dolist (elt (js2-object-node-elems node))
  6215. (let ((subexpr (cond
  6216. ((and (js2-infix-node-p elt)
  6217. (= js2-ASSIGN (js2-infix-node-type elt)))
  6218. ;; Destructuring with default argument.
  6219. (js2-infix-node-left elt))
  6220. ((and (js2-infix-node-p elt)
  6221. (= js2-COLON (js2-infix-node-type elt)))
  6222. ;; In regular destructuring {a: aa, b: bb},
  6223. ;; the var is on the right. In abbreviated
  6224. ;; destructuring {a, b}, right == left.
  6225. (js2-infix-node-right elt))
  6226. ((and (js2-unary-node-p elt)
  6227. (= js2-TRIPLEDOT (js2-unary-node-type elt)))
  6228. ;; Destructuring with spread.
  6229. (js2-unary-node-operand elt)))))
  6230. (when subexpr
  6231. (setq targets (append
  6232. (js2--collect-target-symbols subexpr strict)
  6233. targets))))))
  6234. ((js2-assign-node-p node)
  6235. (setq targets (append (js2--collect-target-symbols
  6236. (js2-assign-node-left node) strict)
  6237. targets)))
  6238. (strict
  6239. (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
  6240. (js2-node-len node))
  6241. nil))
  6242. targets))
  6243. (defun js2--examine-variable (parent node var-init-node)
  6244. "Examine the usage of the variable NODE, a js2-name-node.
  6245. PARENT is its direct ancestor and VAR-INIT-NODE is the node to be
  6246. examined: return a list of three values, respectively if the
  6247. variable is declared and/or assigned or whether it is simply a
  6248. key of a literal object."
  6249. (let ((target (js2-var-init-node-target var-init-node))
  6250. declared assigned object-key)
  6251. (setq declared (memq node (js2--collect-target-symbols target nil)))
  6252. ;; Is there an initializer for the declared variable?
  6253. (when (js2-var-init-node-initializer var-init-node)
  6254. (setq assigned declared)
  6255. ;; Determine if the name is actually a literal object key that we shall
  6256. ;; ignore later
  6257. (when (and (not declared)
  6258. (js2-object-prop-node-p parent)
  6259. (eq node (js2-object-prop-node-left parent))
  6260. (not (eq node (js2-object-prop-node-right parent))))
  6261. (setq object-key t)))
  6262. ;; Maybe this is a for loop and the variable is one of its iterators?
  6263. (unless assigned
  6264. (let* ((gp (js2-node-parent parent))
  6265. (ggp (if gp (js2-node-parent gp))))
  6266. (when (and ggp (js2-for-in-node-p ggp))
  6267. (setq assigned (memq node
  6268. (cl-loop
  6269. for kid in (js2-var-decl-node-kids
  6270. (js2-for-in-node-iterator ggp))
  6271. with syms = '()
  6272. do
  6273. (setq syms (append syms
  6274. (js2--collect-target-symbols
  6275. (js2-var-init-node-target kid)
  6276. nil)))
  6277. finally return syms))))))
  6278. (list declared assigned object-key)))
  6279. (defun js2--is-param (var-node params)
  6280. "Recursively determine whether VAR-NODE is contained in PARAMS."
  6281. (cond ((js2-object-prop-node-p params)
  6282. (eq var-node (js2-object-prop-node-left params)))
  6283. ((js2-name-node-p params)
  6284. (eq var-node params))
  6285. (t
  6286. (let ((isparam (if (listp params)
  6287. (memq var-node params)
  6288. (cl-loop with found = nil
  6289. for p in (js2-node-child-list params)
  6290. while (null found)
  6291. do (setq found (eq var-node p))))))
  6292. (unless isparam
  6293. (let ((kids (if (listp params)
  6294. params
  6295. (js2-node-child-list params))))
  6296. (cl-loop for p in kids
  6297. while (null isparam)
  6298. do (setq isparam (js2--is-param var-node p)))))
  6299. isparam))))
  6300. (defun js2--is-function-param (parent var-node)
  6301. "Determine whether VAR-NODE is a function parameter."
  6302. (while (and parent (not (js2-function-node-p parent)))
  6303. (if (or (js2-var-init-node-p parent)
  6304. (js2-assign-node-p parent))
  6305. (setq parent nil)
  6306. (setq parent (js2-node-parent parent))))
  6307. (when parent
  6308. (js2--is-param var-node (js2-function-node-params parent))))
  6309. (defun js2--classify-variable (parent node vars)
  6310. "Classify the single variable NODE, a js2-name-node, updating the VARS collection."
  6311. (let ((function-param (js2--is-function-param parent node)))
  6312. (if (js2-prop-get-node-p parent)
  6313. ;; If we are within a prop-get, e.g. the "bar" in "foo.bar",
  6314. ;; just mark "foo" as used
  6315. (let ((left (js2-prop-get-node-left parent)))
  6316. (when (js2-name-node-p left)
  6317. (js2--add-or-update-symbol left nil t vars)))
  6318. ;; If the node is the external name of an export-binding-node, and
  6319. ;; it is different from the local name, ignore it
  6320. (when (or (not (js2-export-binding-node-p parent))
  6321. (not (and (eq (js2-export-binding-node-extern-name parent) node)
  6322. (not (eq (js2-export-binding-node-local-name parent) node)))))
  6323. (let ((granparent parent)
  6324. var-init-node
  6325. assign-node
  6326. object-key ; is name actually an object prop key?
  6327. declared ; is it declared in narrowest scope?
  6328. assigned ; does it get assigned or initialized?
  6329. (used (null function-param)))
  6330. ;; Determine the closest var-init-node and assign-node: this
  6331. ;; is needed because the name may be within a "destructured"
  6332. ;; declaration/assignment, so we cannot just take its parent
  6333. (while (and granparent (not (js2-scope-p granparent)))
  6334. (cond
  6335. ((js2-var-init-node-p granparent)
  6336. (when (null var-init-node)
  6337. (setq var-init-node granparent)))
  6338. ((js2-assign-node-p granparent)
  6339. (when (null assign-node)
  6340. (setq assign-node granparent))))
  6341. (setq granparent (js2-node-parent granparent)))
  6342. ;; If we are within a var-init-node, determine if the name is
  6343. ;; declared and initialized
  6344. (when var-init-node
  6345. (let ((result (js2--examine-variable parent node var-init-node)))
  6346. (setq declared (car result)
  6347. assigned (cadr result)
  6348. object-key (car (cddr result)))))
  6349. ;; Ignore literal object keys, which are not really variables
  6350. (unless object-key
  6351. (when function-param
  6352. (setq assigned ?P))
  6353. (when (null assigned)
  6354. (cond
  6355. ((js2-for-in-node-p parent)
  6356. (setq assigned (eq node (js2-for-in-node-iterator parent))
  6357. used (not assigned)))
  6358. ((js2-function-node-p parent)
  6359. (setq assigned t
  6360. used (js2-wrapper-function-p parent)))
  6361. ((js2-export-binding-node-p parent)
  6362. (if (js2-import-clause-node-p (js2-node-parent parent))
  6363. (setq declared t
  6364. assigned t)
  6365. (setq used t)))
  6366. ((js2-namespace-import-node-p parent)
  6367. (setq assigned t
  6368. used nil))
  6369. ((js2-class-node-p parent)
  6370. (setq declared t
  6371. assigned t))
  6372. (assign-node
  6373. (setq assigned (memq node
  6374. (js2--collect-target-symbols
  6375. (js2-assign-node-left assign-node)
  6376. nil))
  6377. used (not assigned)))))
  6378. (when declared
  6379. (setq used nil))
  6380. (js2--add-or-update-symbol node assigned used vars)))))))
  6381. (defun js2--classify-variables ()
  6382. "Collect and classify variables declared or used within js2-mode-ast.
  6383. Traverse the whole ast tree returning a summary of the variables
  6384. usage as an hash-table, keyed by their corresponding symbol table
  6385. entry.
  6386. Each variable is described by a tuple where the car is a flag
  6387. indicating whether the variable has been initialized and the cdr
  6388. is a possibly empty list of name nodes where it is used. External
  6389. symbols, i.e. those not present in the whole scopes hierarchy,
  6390. are ignored."
  6391. (let ((vars (make-hash-table :test #'eq :size 100)))
  6392. (js2-visit-ast
  6393. js2-mode-ast
  6394. (lambda (node end-p)
  6395. (when (and (null end-p) (js2-name-node-p node))
  6396. (let ((parent (js2-node-parent node)))
  6397. (when parent
  6398. (js2--classify-variable parent node vars))))
  6399. t))
  6400. vars))
  6401. (defun js2--get-name-node (node)
  6402. (cond
  6403. ((js2-name-node-p node) node)
  6404. ((js2-function-node-p node)
  6405. (js2-function-node-name node))
  6406. ((js2-class-node-p node)
  6407. (js2-class-node-name node))
  6408. ((js2-comp-loop-node-p node)
  6409. (js2-comp-loop-node-iterator node))
  6410. (t node)))
  6411. (defun js2--highlight-unused-variable (symbol info)
  6412. (let ((name (js2-symbol-name symbol))
  6413. (inited (car info))
  6414. (refs (cdr info))
  6415. pos len)
  6416. (unless (and inited refs)
  6417. (if refs
  6418. (dolist (ref refs)
  6419. (setq pos (js2-node-abs-pos ref))
  6420. (setq len (js2-name-node-len ref))
  6421. (js2-report-warning "msg.uninitialized.variable" name pos len
  6422. 'js2-warning))
  6423. (when (or js2-warn-about-unused-function-arguments
  6424. (not (eq inited ?P)))
  6425. (let* ((symn (js2-symbol-ast-node symbol))
  6426. (namen (js2--get-name-node symn)))
  6427. (unless (js2-node-top-level-decl-p namen)
  6428. (setq pos (js2-node-abs-pos namen))
  6429. (setq len (js2-name-node-len namen))
  6430. (js2-report-warning "msg.unused.variable" name pos len
  6431. 'js2-warning))))))))
  6432. (defun js2-highlight-unused-variables ()
  6433. "Highlight unused variables."
  6434. (let ((vars (js2--classify-variables)))
  6435. (maphash #'js2--highlight-unused-variable vars)))
  6436. ;;;###autoload
  6437. (define-minor-mode js2-highlight-unused-variables-mode
  6438. "Toggle highlight of unused variables."
  6439. :lighter ""
  6440. (if js2-highlight-unused-variables-mode
  6441. (add-hook 'js2-post-parse-callbacks
  6442. #'js2-highlight-unused-variables nil t)
  6443. (remove-hook 'js2-post-parse-callbacks
  6444. #'js2-highlight-unused-variables t)))
  6445. (defun js2-add-additional-externs (externs)
  6446. (setq js2-additional-externs
  6447. (nconc externs
  6448. js2-additional-externs)))
  6449. (defun js2-get-jslint-comment-identifiers (comment)
  6450. (js2-reparse)
  6451. (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
  6452. when (and (eq 'block (js2-comment-node-format node))
  6453. (save-excursion
  6454. (goto-char (js2-node-abs-pos node))
  6455. (looking-at (concat "/\\* *" comment "\\(?: \\|$\\)"))))
  6456. append (js2-get-jslint-comment-identifiers-in
  6457. (match-end 0)
  6458. (js2-node-abs-end node))))
  6459. (defun js2-get-jslint-comment-identifiers-in (beg end)
  6460. (let (res)
  6461. (save-excursion
  6462. (goto-char beg)
  6463. (while (re-search-forward js2-mode-identifier-re end t)
  6464. (let ((match (match-string 0)))
  6465. (unless (member match '("true" "false"))
  6466. (push match res)))))
  6467. (nreverse res)))
  6468. (defun js2-apply-jslint-globals ()
  6469. (js2-add-additional-externs (js2-get-jslint-globals)))
  6470. (defun js2-get-jslint-globals ()
  6471. (js2-get-jslint-comment-identifiers "global"))
  6472. (defun js2-apply-jslint-declaration-externs ()
  6473. (js2-add-additional-externs (js2-get-jslint-declaration-externs)))
  6474. (defvar js2-jslint-declaration-externs
  6475. `(("browser" . ,(mapcar 'symbol-name
  6476. '(Audio clearInterval clearTimeout document
  6477. event history Image location name
  6478. navigator Option screen setInterval
  6479. setTimeout XMLHttpRequest)))
  6480. ("node" . ,(mapcar 'symbol-name
  6481. '(Buffer clearImmediate clearInterval
  6482. clearTimeout console exports global module
  6483. process querystring require setImmediate
  6484. setInterval setTimeout __dirname
  6485. __filename)))
  6486. ("es6" . ,(mapcar 'symbol-name
  6487. '(ArrayBuffer DataView Float32Array
  6488. Float64Array Int8Array Int16Array Int32Array
  6489. Intl Map Promise Proxy Reflect Set Symbol
  6490. System Uint8Array Uint8ClampedArray
  6491. Uint16Array Uint32Array WeakMap WeakSet)))
  6492. ("couch" . ,(mapcar 'symbol-name
  6493. '(emit getRow isArray log provides
  6494. registerType require send start sum
  6495. toJSON)))
  6496. ("devel" . ,(mapcar 'symbol-name
  6497. '(alert confirm console Debug opera prompt
  6498. WSH)))))
  6499. (defun js2-get-jslint-declaration-externs ()
  6500. (apply 'append
  6501. (mapcar (lambda (identifier)
  6502. (cdr (assoc identifier
  6503. js2-jslint-declaration-externs)))
  6504. (js2-get-jslint-comment-identifiers "jslint"))))
  6505. ;;; IMenu support
  6506. ;; We currently only support imenu, but eventually should support speedbar and
  6507. ;; possibly other browsing mechanisms.
  6508. ;; The basic strategy is to identify function assignment targets of the form
  6509. ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
  6510. ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
  6511. ;; for imenu after parsing is finished.
  6512. ;; A `foo.bar.baz' assignment target may be expressed in many ways in
  6513. ;; JavaScript, and the general problem is undecidable. However, several forms
  6514. ;; are readily recognizable at parse-time; the forms we attempt to recognize
  6515. ;; include:
  6516. ;; function foo() -- function declaration
  6517. ;; foo = function() -- function expression assigned to variable
  6518. ;; foo.bar.baz = function() -- function expr assigned to nested property-get
  6519. ;; foo = {bar: function()} -- fun prop in object literal assigned to var
  6520. ;; foo = {bar: {baz: function()}} -- inside nested object literal
  6521. ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
  6522. ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
  6523. ;; foo = {get bar() {...}} -- getter/setter in obj literal
  6524. ;; function foo() {function bar() {...}} -- nested function
  6525. ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
  6526. ;; This list boils down to a few forms that can be combined recursively.
  6527. ;; Top-level named function declarations include both the left-hand (name)
  6528. ;; and the right-hand (function value) expressions needed to produce an imenu
  6529. ;; entry. The other "right-hand" forms we need to look for are:
  6530. ;; - functions declared as props/getters/setters in object literals
  6531. ;; - nested named function declarations
  6532. ;; The "left-hand" expressions that functions can be assigned to include:
  6533. ;; - local/global variables
  6534. ;; - nested property-get expressions like a.b.c.d
  6535. ;; - element gets like foo[10] or foo['bar'] where the index
  6536. ;; expression can be trivially converted to a property name. They
  6537. ;; effectively then become property gets.
  6538. ;; All the different definition types are canonicalized into the form
  6539. ;; foo.bar.baz = position-of-function-keyword
  6540. ;; We need to build a trie-like structure for imenu. As an example,
  6541. ;; consider the following JavaScript code:
  6542. ;; a = function() {...} // function at position 5
  6543. ;; b = function() {...} // function at position 25
  6544. ;; foo = function() {...} // function at position 100
  6545. ;; foo.bar = function() {...} // function at position 200
  6546. ;; foo.bar.baz = function() {...} // function at position 300
  6547. ;; foo.bar.zab = function() {...} // function at position 400
  6548. ;; During parsing we accumulate an entry for each definition in
  6549. ;; the variable `js2-imenu-recorder', like so:
  6550. ;; '((fn a 5)
  6551. ;; (fn b 25)
  6552. ;; (fn foo 100)
  6553. ;; (fn foo bar 200)
  6554. ;; (fn foo bar baz 300)
  6555. ;; (fn foo bar zab 400))
  6556. ;; Where 'fn' is the respective function node.
  6557. ;; After parsing these entries are merged into this alist-trie:
  6558. ;; '((a . 1)
  6559. ;; (b . 2)
  6560. ;; (foo (<definition> . 3)
  6561. ;; (bar (<definition> . 6)
  6562. ;; (baz . 100)
  6563. ;; (zab . 200))))
  6564. ;; Note the wacky need for a <definition> name. The token can be anything
  6565. ;; that isn't a valid JavaScript identifier, because you might make foo
  6566. ;; a function and then start setting properties on it that are also functions.
  6567. (defun js2-prop-node-name (node)
  6568. "Return the name of a node that may be a property-get/property-name.
  6569. If NODE is not a valid name-node, string-node or integral number-node,
  6570. returns nil. Otherwise returns the string name/value of the node."
  6571. (cond
  6572. ((js2-name-node-p node)
  6573. (js2-name-node-name node))
  6574. ((js2-string-node-p node)
  6575. (js2-string-node-value node))
  6576. ((and (js2-number-node-p node)
  6577. (string-match "^[0-9]+$" (js2-number-node-value node)))
  6578. (js2-number-node-value node))
  6579. ((eq (js2-node-type node) js2-THIS)
  6580. "this")
  6581. ((eq (js2-node-type node) js2-SUPER)
  6582. "super")))
  6583. (defun js2-node-qname-component (node)
  6584. "Return the name of this node, if it contributes to a qname.
  6585. Returns nil if the node doesn't contribute."
  6586. (copy-sequence
  6587. (or (js2-prop-node-name node)
  6588. (cond
  6589. ((and (js2-function-node-p node)
  6590. (js2-function-node-name node))
  6591. (js2-name-node-name (js2-function-node-name node)))
  6592. ((js2-computed-prop-name-node-p node)
  6593. "[computed]")))))
  6594. (defun js2-record-imenu-entry (fn-node qname pos)
  6595. "Add an entry to `js2-imenu-recorder'.
  6596. FN-NODE should be the current item's function node.
  6597. Associate FN-NODE with its QNAME for later lookup.
  6598. This is used in postprocessing the chain list. For each chain, we find
  6599. the parent function, look up its qname, then prepend a copy of it to the chain."
  6600. (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
  6601. (unless js2-imenu-function-map
  6602. (setq js2-imenu-function-map (make-hash-table :test 'eq)))
  6603. (puthash fn-node qname js2-imenu-function-map))
  6604. (defun js2-record-imenu-functions (node &optional var)
  6605. "Record function definitions for imenu.
  6606. NODE is a function node or an object literal.
  6607. VAR, if non-nil, is the expression that NODE is being assigned to.
  6608. When passed arguments of wrong type, does nothing."
  6609. (when js2-parse-ide-mode
  6610. (let ((fun-p (js2-function-node-p node))
  6611. qname fname-node)
  6612. (cond
  6613. ;; non-anonymous function declaration?
  6614. ((and fun-p
  6615. (not var)
  6616. (setq fname-node (js2-function-node-name node)))
  6617. (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
  6618. ;; for remaining forms, compute left-side tree branch first
  6619. ((and var (setq qname (js2-compute-nested-prop-get var)))
  6620. (cond
  6621. ;; foo.bar.baz = function
  6622. (fun-p
  6623. (js2-record-imenu-entry node qname (js2-node-pos node)))
  6624. ;; foo.bar.baz = object-literal
  6625. ;; look for nested functions: {a: {b: function() {...} }}
  6626. ((js2-object-node-p node)
  6627. ;; Node position here is still absolute, since the parser
  6628. ;; passes the assignment target and value expressions
  6629. ;; to us before they are added as children of the assignment node.
  6630. (js2-record-object-literal node qname (js2-node-pos node)))))))))
  6631. (defun js2-compute-nested-prop-get (node)
  6632. "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
  6633. component nodes as a list. Otherwise return nil. Element-gets are treated
  6634. as property-gets if the index expression is a string, or a positive integer."
  6635. (let (left right head)
  6636. (cond
  6637. ((or (js2-name-node-p node)
  6638. (js2-this-or-super-node-p node))
  6639. (list node))
  6640. ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
  6641. ((js2-prop-get-node-p node) ; foo.bar
  6642. (setq left (js2-prop-get-node-left node)
  6643. right (js2-prop-get-node-right node))
  6644. (if (setq head (js2-compute-nested-prop-get left))
  6645. (nconc head (list right))))
  6646. ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
  6647. (setq left (js2-elem-get-node-target node)
  6648. right (js2-elem-get-node-element node))
  6649. (if (or (js2-string-node-p right) ; ['bar']
  6650. (and (js2-number-node-p right) ; [10]
  6651. (string-match "^[0-9]+$"
  6652. (js2-number-node-value right))))
  6653. (if (setq head (js2-compute-nested-prop-get left))
  6654. (nconc head (list right))))))))
  6655. (defun js2-record-object-literal (node qname pos)
  6656. "Recursively process an object literal looking for functions.
  6657. NODE is an object literal that is the right-hand child of an assignment
  6658. expression. QNAME is a list of nodes representing the assignment target,
  6659. e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
  6660. POS is the absolute position of the node.
  6661. We do a depth-first traversal of NODE. For any functions we find,
  6662. we append the property name to QNAME, then call `js2-record-imenu-entry'."
  6663. (let (right)
  6664. (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
  6665. (when (js2-infix-node-p e)
  6666. (let ((left (js2-infix-node-left e))
  6667. ;; Element positions are relative to the parent position.
  6668. (pos (+ pos (js2-node-pos e))))
  6669. (cond
  6670. ;; foo: function() {...}
  6671. ((js2-function-node-p (setq right (js2-infix-node-right e)))
  6672. (when (js2-prop-node-name left)
  6673. ;; As a policy decision, we record the position of the property,
  6674. ;; not the position of the `function' keyword, since the property
  6675. ;; is effectively the name of the function.
  6676. (js2-record-imenu-entry right (append qname (list left)) pos)))
  6677. ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
  6678. ((js2-object-node-p right)
  6679. (js2-record-object-literal right
  6680. (append qname (list (js2-infix-node-left e)))
  6681. (+ pos (js2-node-pos right))))))))))
  6682. (defun js2-node-top-level-decl-p (node)
  6683. "Return t if NODE's name is defined in the top-level scope.
  6684. Also returns t if NODE's name is not defined in any scope, since it implies
  6685. that it's an external variable, which must also be in the top-level scope."
  6686. (let* ((name (js2-prop-node-name node))
  6687. (this-scope (js2-node-get-enclosing-scope node))
  6688. defining-scope)
  6689. (cond
  6690. ((js2-this-or-super-node-p node)
  6691. nil)
  6692. ((null this-scope)
  6693. t)
  6694. ((setq defining-scope (js2-get-defining-scope this-scope name))
  6695. (js2-ast-root-p defining-scope))
  6696. (t t))))
  6697. (defun js2-wrapper-function-p (node)
  6698. "Return t if NODE is a function expression that's immediately invoked.
  6699. NODE must be `js2-function-node'."
  6700. (let ((parent (js2-node-parent node)))
  6701. (or
  6702. ;; function(){...}();
  6703. (and (js2-call-node-p parent)
  6704. (eq node (js2-call-node-target parent)))
  6705. (and (js2-paren-node-p parent)
  6706. ;; (function(){...})();
  6707. (or (js2-call-node-p (setq parent (js2-node-parent parent)))
  6708. ;; (function(){...}).call(this);
  6709. (and (js2-prop-get-node-p parent)
  6710. (member (js2-name-node-name (js2-prop-get-node-right parent))
  6711. '("call" "apply"))
  6712. (js2-call-node-p (js2-node-parent parent))))))))
  6713. (defun js2-browse-postprocess-chains ()
  6714. "Modify function-declaration name chains after parsing finishes.
  6715. Some of the information is only available after the parse tree is complete.
  6716. For instance, processing a nested scope requires a parent function node."
  6717. (let (result fn parent-qname p elem)
  6718. (dolist (entry js2-imenu-recorder)
  6719. ;; function node goes first
  6720. (cl-destructuring-bind
  6721. (current-fn &rest (&whole chain head &rest rest)) entry
  6722. ;; Examine head's defining scope:
  6723. ;; Pre-processed chain, or top-level/external, keep as-is.
  6724. (if (or (stringp head) (js2-node-top-level-decl-p head))
  6725. (push chain result)
  6726. (when (js2-this-or-super-node-p head)
  6727. (setq chain (cdr chain))) ; discard this-node
  6728. (when (setq fn (js2-node-parent-script-or-fn current-fn))
  6729. (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
  6730. (when (eq parent-qname 'not-found)
  6731. ;; anonymous function expressions are not recorded
  6732. ;; during the parse, so we need to handle this case here
  6733. (setq parent-qname
  6734. (if (js2-wrapper-function-p fn)
  6735. (let ((grandparent (js2-node-parent-script-or-fn fn)))
  6736. (if (js2-ast-root-p grandparent)
  6737. nil
  6738. (gethash grandparent js2-imenu-function-map 'skip)))
  6739. 'skip))
  6740. (puthash fn parent-qname js2-imenu-function-map))
  6741. (if (eq parent-qname 'skip)
  6742. ;; We don't show it, let's record that fact.
  6743. (remhash current-fn js2-imenu-function-map)
  6744. ;; Prepend parent fn qname to this chain.
  6745. (let ((qname (append parent-qname chain)))
  6746. (puthash current-fn (butlast qname) js2-imenu-function-map)
  6747. (push qname result)))))))
  6748. ;; Collect chains obtained by third-party code.
  6749. (let (js2-imenu-recorder)
  6750. (run-hooks 'js2-build-imenu-callbacks)
  6751. (dolist (entry js2-imenu-recorder)
  6752. (push (cdr entry) result)))
  6753. ;; Finally replace each node in each chain with its name.
  6754. (dolist (chain result)
  6755. (setq p chain)
  6756. (while p
  6757. (if (js2-node-p (setq elem (car p)))
  6758. (setcar p (js2-node-qname-component elem)))
  6759. (setq p (cdr p))))
  6760. result))
  6761. ;; Merge name chains into a trie-like tree structure of nested lists.
  6762. ;; To simplify construction of the trie, we first build it out using the rule
  6763. ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
  6764. ;; [key, num-or-list]. The second element can be a number; if so, this key
  6765. ;; is a leaf-node with only one value. (I.e. there is only one declaration
  6766. ;; associated with the key at this level.) Otherwise the second element is
  6767. ;; a list of pairs, with the rule applied recursively. This symmetry permits
  6768. ;; a simple recursive formulation.
  6769. ;;
  6770. ;; js2-mode is building the data structure for imenu. The imenu documentation
  6771. ;; claims that it's the structure above, but in practice it wants the children
  6772. ;; at the same list level as the key for that level, which is how I've drawn
  6773. ;; the "Expected final result" above. We'll postprocess the trie to remove the
  6774. ;; list wrapper around the children at each level.
  6775. ;;
  6776. ;; A completed nested imenu-alist entry looks like this:
  6777. ;; '(("foo"
  6778. ;; ("<definition>" . 7)
  6779. ;; ("bar"
  6780. ;; ("a" . 40)
  6781. ;; ("b" . 60))))
  6782. ;;
  6783. ;; In particular, the documentation for `imenu--index-alist' says that
  6784. ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
  6785. ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
  6786. (defun js2-treeify (lst)
  6787. "Convert (a b c d) to (a ((b ((c d)))))."
  6788. (if (null (cddr lst)) ; list length <= 2
  6789. lst
  6790. (list (car lst) (list (js2-treeify (cdr lst))))))
  6791. (defun js2-build-alist-trie (chains trie)
  6792. "Merge declaration name chains into a trie-like alist structure for imenu.
  6793. CHAINS is the qname chain list produced during parsing. TRIE is a
  6794. list of elements built up so far."
  6795. (let (head tail pos branch kids)
  6796. (dolist (chain chains)
  6797. (setq head (car chain)
  6798. tail (cdr chain)
  6799. pos (if (numberp (car tail)) (car tail))
  6800. branch (js2-find-if (lambda (n)
  6801. (string= (car n) head))
  6802. trie)
  6803. kids (cl-second branch))
  6804. (cond
  6805. ;; case 1: this key isn't in the trie yet
  6806. ((null branch)
  6807. (if trie
  6808. (setcdr (last trie) (list (js2-treeify chain)))
  6809. (setq trie (list (js2-treeify chain)))))
  6810. ;; case 2: key is present with a single number entry: replace w/ list
  6811. ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
  6812. ;; ("<definition>" 20)))
  6813. ((numberp kids)
  6814. (setcar (cdr branch)
  6815. (list (list "<definition-1>" kids)
  6816. (if pos
  6817. (list "<definition-2>" pos)
  6818. (js2-treeify tail)))))
  6819. ;; case 3: key is there (with kids), and we're a number entry
  6820. (pos
  6821. (setcdr (last kids)
  6822. (list
  6823. (list (format "<definition-%d>"
  6824. (1+ (cl-loop for kid in kids
  6825. count (eq ?< (aref (car kid) 0)))))
  6826. pos))))
  6827. ;; case 4: key is there with kids, need to merge in our chain
  6828. (t
  6829. (js2-build-alist-trie (list tail) kids))))
  6830. trie))
  6831. (defun js2-flatten-trie (trie)
  6832. "Convert TRIE to imenu-format.
  6833. Recurses through nodes, and for each one whose second element is a list,
  6834. appends the list's flattened elements to the current element. Also
  6835. changes the tails into conses. For instance, this pre-flattened trie
  6836. '(a ((b 20)
  6837. (c ((d 30)
  6838. (e 40)))))
  6839. becomes
  6840. '(a (b . 20)
  6841. (c (d . 30)
  6842. (e . 40)))
  6843. Note that the root of the trie has no key, just a list of chains.
  6844. This is also true for the value of any key with multiple children,
  6845. e.g. key 'c' in the example above."
  6846. (cond
  6847. ((listp (car trie))
  6848. (mapcar #'js2-flatten-trie trie))
  6849. (t
  6850. (if (numberp (cl-second trie))
  6851. (cons (car trie) (cl-second trie))
  6852. ;; else pop list and append its kids
  6853. (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
  6854. (defun js2-build-imenu-index ()
  6855. "Turn `js2-imenu-recorder' into an imenu data structure."
  6856. (when (eq js2-imenu-recorder 'empty)
  6857. (setq js2-imenu-recorder nil))
  6858. (let* ((chains (js2-browse-postprocess-chains))
  6859. (result (js2-build-alist-trie chains nil)))
  6860. (js2-flatten-trie result)))
  6861. (defun js2-test-print-chains (chains)
  6862. "Print a list of qname chains.
  6863. Each element of CHAINS is a list of the form (NODE [NODE *] pos);
  6864. i.e. one or more nodes, and an integer position as the list tail."
  6865. (mapconcat (lambda (chain)
  6866. (concat "("
  6867. (mapconcat (lambda (elem)
  6868. (if (js2-node-p elem)
  6869. (or (js2-node-qname-component elem)
  6870. "nil")
  6871. (number-to-string elem)))
  6872. chain
  6873. " ")
  6874. ")"))
  6875. chains
  6876. "\n"))
  6877. ;;; Parser
  6878. (defconst js2-version "1.8.5"
  6879. "Version of JavaScript supported.")
  6880. (defun js2-record-face (face &optional token)
  6881. "Record a style run of FACE for TOKEN or the current token."
  6882. (unless token (setq token (js2-current-token)))
  6883. (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
  6884. (defsubst js2-node-end (n)
  6885. "Computes the absolute end of node N.
  6886. Use with caution! Assumes `js2-node-pos' is -absolute-, which
  6887. is only true until the node is added to its parent; i.e., while parsing."
  6888. (+ (js2-node-pos n)
  6889. (js2-node-len n)))
  6890. (defun js2-record-comment (token)
  6891. "Record a comment in `js2-scanned-comments'."
  6892. (let ((ct (js2-token-comment-type token))
  6893. (beg (js2-token-beg token))
  6894. (end (js2-token-end token)))
  6895. (push (make-js2-comment-node :len (- end beg)
  6896. :format ct)
  6897. js2-scanned-comments)
  6898. (when js2-parse-ide-mode
  6899. (js2-record-face (if (eq ct 'jsdoc)
  6900. 'font-lock-doc-face
  6901. 'font-lock-comment-face)
  6902. token)
  6903. (when (memq ct '(html preprocessor))
  6904. ;; Tell cc-engine the bounds of the comment.
  6905. (js2-record-text-property beg (1- end) 'c-in-sws t)))))
  6906. (defun js2-peek-token (&optional modifier)
  6907. "Return the next token type without consuming it.
  6908. If `js2-ti-lookahead' is positive, return the type of next token
  6909. from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
  6910. (if (not (zerop js2-ti-lookahead))
  6911. (js2-token-type
  6912. (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
  6913. (let ((tt (js2-get-token-internal modifier)))
  6914. (js2-unget-token)
  6915. tt)))
  6916. (defalias 'js2-next-token 'js2-get-token)
  6917. (defun js2-match-token (match &optional dont-unget)
  6918. "Get next token and return t if it matches MATCH, a bytecode.
  6919. Returns nil and consumes nothing if MATCH is not the next token."
  6920. (if (/= (js2-get-token) match)
  6921. (ignore (unless dont-unget (js2-unget-token)))
  6922. t))
  6923. (defun js2-match-contextual-kwd (name)
  6924. "Consume and return t if next token is `js2-NAME', and its
  6925. string is NAME. Returns nil and keeps current token otherwise."
  6926. (if (js2-contextual-kwd-p (progn (js2-get-token)
  6927. (js2-current-token))
  6928. name)
  6929. (progn (js2-record-face 'font-lock-keyword-face) t)
  6930. (js2-unget-token)
  6931. nil))
  6932. (defun js2-contextual-kwd-p (token name)
  6933. "Return t if TOKEN is `js2-NAME', and its string is NAME."
  6934. (and (= (js2-token-type token) js2-NAME)
  6935. (string= (js2-token-string token) name)))
  6936. (defun js2-match-async-function ()
  6937. (when (and (js2-contextual-kwd-p (js2-current-token) "async")
  6938. (= (js2-peek-token) js2-FUNCTION))
  6939. (js2-record-face 'font-lock-keyword-face)
  6940. (js2-get-token)
  6941. t))
  6942. (defun js2-match-async-arrow-function ()
  6943. (and (js2-contextual-kwd-p (js2-current-token) "async")
  6944. (/= (js2-peek-token) js2-FUNCTION)))
  6945. (defsubst js2-inside-function ()
  6946. (cl-plusp js2-nesting-of-function))
  6947. (defsubst js2-inside-async-function ()
  6948. (and (js2-inside-function)
  6949. (js2-function-node-async js2-current-script-or-fn)))
  6950. (defun js2-parse-await-maybe (tt)
  6951. "Parse \"await\" as an AwaitExpression, if it is one."
  6952. (and (= tt js2-NAME)
  6953. (js2-contextual-kwd-p (js2-current-token) "await")
  6954. ;; Per the proposal, AwaitExpression consists of "await"
  6955. ;; followed by a UnaryExpression. So look ahead for one.
  6956. (let ((ts-state (make-js2-ts-state))
  6957. (recorded-identifiers js2-recorded-identifiers)
  6958. (parsed-errors js2-parsed-errors)
  6959. (current-token (js2-current-token))
  6960. (beg (js2-current-token-beg))
  6961. (end (js2-current-token-end))
  6962. pn)
  6963. (js2-get-token)
  6964. (setq pn (js2-make-unary beg js2-AWAIT 'js2-parse-unary-expr))
  6965. (if (= (js2-node-type (js2-unary-node-operand pn)) js2-ERROR)
  6966. ;; The parse failed, so pretend like nothing happened and restore
  6967. ;; the previous parsing state.
  6968. (progn
  6969. (js2-ts-seek ts-state)
  6970. (setq js2-recorded-identifiers recorded-identifiers
  6971. js2-parsed-errors parsed-errors)
  6972. ;; And ensure the caller knows about the failure.
  6973. nil)
  6974. ;; The parse was successful, so process and return the "await".
  6975. (js2-record-face 'font-lock-keyword-face current-token)
  6976. (unless (js2-inside-async-function)
  6977. (js2-report-error "msg.bad.await" nil
  6978. beg (- end beg)))
  6979. pn))))
  6980. (defun js2-get-prop-name-token ()
  6981. (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
  6982. (defun js2-match-prop-name ()
  6983. "Consume token and return t if next token is a valid property name.
  6984. If `js2-language-version' is >= 180, a keyword or reserved word
  6985. is considered valid name as well."
  6986. (if (eq js2-NAME (js2-get-prop-name-token))
  6987. t
  6988. (js2-unget-token)
  6989. nil))
  6990. (defun js2-must-match-prop-name (msg-id &optional pos len)
  6991. (if (js2-match-prop-name)
  6992. t
  6993. (js2-report-error msg-id nil pos len)
  6994. nil))
  6995. (defun js2-peek-token-or-eol ()
  6996. "Return js2-EOL if the next token immediately follows a newline.
  6997. Else returns the next token. Used in situations where we don't
  6998. consider certain token types valid if they are preceded by a newline.
  6999. One example is the postfix ++ or -- operator, which has to be on the
  7000. same line as its operand."
  7001. (let ((tt (js2-get-token))
  7002. (follows-eol (js2-token-follows-eol-p (js2-current-token))))
  7003. (js2-unget-token)
  7004. (if follows-eol
  7005. js2-EOL
  7006. tt)))
  7007. (defun js2-must-match (token msg-id &optional pos len)
  7008. "Match next token to token code TOKEN, or record a syntax error.
  7009. MSG-ID is the error message to report if the match fails.
  7010. Returns t on match, nil if no match."
  7011. (if (js2-match-token token t)
  7012. t
  7013. (js2-report-error msg-id nil pos len)
  7014. (js2-unget-token)
  7015. nil))
  7016. (defun js2-must-match-name (msg-id)
  7017. (if (js2-match-token js2-NAME t)
  7018. t
  7019. (if (eq (js2-current-token-type) js2-RESERVED)
  7020. (js2-report-error "msg.reserved.id" (js2-current-token-string))
  7021. (js2-report-error msg-id)
  7022. (js2-unget-token))
  7023. nil))
  7024. (defun js2-set-requires-activation ()
  7025. (if (js2-function-node-p js2-current-script-or-fn)
  7026. (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
  7027. (defun js2-check-activation-name (name _token)
  7028. (when (js2-inside-function)
  7029. ;; skip language-version 1.2 check from Rhino
  7030. (if (or (string= "arguments" name)
  7031. (and js2-compiler-activation-names ; only used in codegen
  7032. (gethash name js2-compiler-activation-names)))
  7033. (js2-set-requires-activation))))
  7034. (defun js2-set-is-generator ()
  7035. (let ((fn-node js2-current-script-or-fn))
  7036. (when (and (js2-function-node-p fn-node)
  7037. (not (js2-function-node-generator-type fn-node)))
  7038. (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
  7039. (defun js2-must-have-xml ()
  7040. (unless js2-compiler-xml-available
  7041. (js2-report-error "msg.XML.not.available")))
  7042. (defun js2-push-scope (scope)
  7043. "Push SCOPE, a `js2-scope', onto the lexical scope chain."
  7044. (cl-assert (js2-scope-p scope))
  7045. (cl-assert (null (js2-scope-parent-scope scope)))
  7046. (cl-assert (not (eq js2-current-scope scope)))
  7047. (setf (js2-scope-parent-scope scope) js2-current-scope
  7048. js2-current-scope scope))
  7049. (defsubst js2-pop-scope ()
  7050. (setq js2-current-scope
  7051. (js2-scope-parent-scope js2-current-scope)))
  7052. (defun js2-enter-loop (loop-node)
  7053. (push loop-node js2-loop-set)
  7054. (push loop-node js2-loop-and-switch-set)
  7055. (js2-push-scope loop-node)
  7056. ;; Tell the current labeled statement (if any) its statement,
  7057. ;; and set the jump target of the first label to the loop.
  7058. ;; These are used in `js2-parse-continue' to verify that the
  7059. ;; continue target is an actual labeled loop. (And for codegen.)
  7060. (when js2-labeled-stmt
  7061. (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
  7062. (js2-label-node-loop (car (js2-labeled-stmt-node-labels
  7063. js2-labeled-stmt))) loop-node)))
  7064. (defun js2-exit-loop ()
  7065. (pop js2-loop-set)
  7066. (pop js2-loop-and-switch-set)
  7067. (js2-pop-scope))
  7068. (defsubst js2-enter-switch (switch-node)
  7069. (js2-push-scope switch-node)
  7070. (push switch-node js2-loop-and-switch-set))
  7071. (defsubst js2-exit-switch ()
  7072. (js2-pop-scope)
  7073. (pop js2-loop-and-switch-set))
  7074. (defsubst js2-get-directive (node)
  7075. "Return NODE's value if it is a directive, nil otherwise.
  7076. A directive is an otherwise-meaningless expression statement
  7077. consisting of a string literal, such as \"use strict\"."
  7078. (and (js2-expr-stmt-node-p node)
  7079. (js2-string-node-p (setq node (js2-expr-stmt-node-expr node)))
  7080. (js2-string-node-value node)))
  7081. (defun js2-parse (&optional buf cb)
  7082. "Tell the js2 parser to parse a region of JavaScript.
  7083. BUF is a buffer or buffer name containing the code to parse.
  7084. Call `narrow-to-region' first to parse only part of the buffer.
  7085. The returned AST root node is given some additional properties:
  7086. `node-count' - total number of nodes in the AST
  7087. `buffer' - BUF. The buffer it refers to may change or be killed,
  7088. so the value is not necessarily reliable.
  7089. An optional callback CB can be specified to report parsing
  7090. progress. If `(functionp CB)' returns t, it will be called with
  7091. the current line number once before parsing begins, then again
  7092. each time the lexer reaches a new line number.
  7093. CB can also be a list of the form `(symbol cb ...)' to specify
  7094. multiple callbacks with different criteria. Each symbol is a
  7095. criterion keyword, and the following element is the callback to
  7096. call
  7097. :line - called whenever the line number changes
  7098. :token - called for each new token consumed
  7099. The list of criteria could be extended to include entering or
  7100. leaving a statement, an expression, or a function definition."
  7101. (if (and cb (not (functionp cb)))
  7102. (error "criteria callbacks not yet implemented"))
  7103. (let ((inhibit-point-motion-hooks t)
  7104. (js2-compiler-xml-available (>= js2-language-version 160))
  7105. ;; This is a recursive-descent parser, so give it a big stack.
  7106. (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
  7107. (max-specpdl-size (max max-specpdl-size 3000))
  7108. (case-fold-search nil)
  7109. ast)
  7110. (with-current-buffer (or buf (current-buffer))
  7111. (setq js2-scanned-comments nil
  7112. js2-parsed-errors nil
  7113. js2-parsed-warnings nil
  7114. js2-imenu-recorder nil
  7115. js2-imenu-function-map nil
  7116. js2-label-set nil)
  7117. (js2-init-scanner)
  7118. (setq ast (js2-do-parse))
  7119. (unless js2-ts-hit-eof
  7120. (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
  7121. (setf (js2-ast-root-errors ast) js2-parsed-errors
  7122. (js2-ast-root-warnings ast) js2-parsed-warnings)
  7123. ;; if we didn't find any declarations, put a dummy in this list so we
  7124. ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
  7125. (unless js2-imenu-recorder
  7126. (setq js2-imenu-recorder 'empty))
  7127. (run-hooks 'js2-parse-finished-hook)
  7128. ast)))
  7129. ;; Corresponds to Rhino's Parser.parse() method.
  7130. (defun js2-do-parse ()
  7131. "Parse current buffer starting from current point.
  7132. Scanner should be initialized."
  7133. (let ((pos js2-ts-cursor)
  7134. (end js2-ts-cursor) ; in case file is empty
  7135. root n tt
  7136. (in-directive-prologue t)
  7137. (js2-in-use-strict-directive js2-in-use-strict-directive)
  7138. directive)
  7139. ;; initialize buffer-local parsing vars
  7140. (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
  7141. js2-current-script-or-fn root
  7142. js2-current-scope root
  7143. js2-nesting-of-function 0
  7144. js2-labeled-stmt nil
  7145. js2-recorded-identifiers nil ; for js2-highlight
  7146. js2-in-use-strict-directive js2-mode-assume-strict)
  7147. (while (/= (setq tt (js2-get-token)) js2-EOF)
  7148. (if (= tt js2-FUNCTION)
  7149. (progn
  7150. (setq n (if js2-called-by-compile-function
  7151. (js2-parse-function-expr)
  7152. (js2-parse-function-stmt))))
  7153. ;; not a function - parse a statement
  7154. (js2-unget-token)
  7155. (setq n (js2-parse-statement))
  7156. (when in-directive-prologue
  7157. (setq directive (js2-get-directive n))
  7158. (cond
  7159. ((null directive)
  7160. (setq in-directive-prologue nil))
  7161. ((string= directive "use strict")
  7162. (setq js2-in-use-strict-directive t)))))
  7163. ;; add function or statement to script
  7164. (setq end (js2-node-end n))
  7165. (js2-block-node-push root n))
  7166. ;; add comments to root in lexical order
  7167. (when js2-scanned-comments
  7168. ;; if we find a comment beyond end of normal kids, use its end
  7169. (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
  7170. (dolist (comment js2-scanned-comments)
  7171. (push comment (js2-ast-root-comments root))
  7172. (js2-node-add-children root comment)))
  7173. (setf (js2-node-len root) (- end pos))
  7174. (setq js2-mode-ast root) ; Make sure this is available for callbacks.
  7175. ;; Give extensions a chance to muck with things before highlighting starts.
  7176. (let ((js2-additional-externs js2-additional-externs))
  7177. (js2-filter-parsed-warnings)
  7178. (save-excursion
  7179. (run-hooks 'js2-post-parse-callbacks))
  7180. (js2-highlight-undeclared-vars))
  7181. root))
  7182. (defun js2-filter-parsed-warnings ()
  7183. "Remove `js2-parsed-warnings' elements that match `js2-ignored-warnings'."
  7184. (when js2-ignored-warnings
  7185. (setq js2-parsed-warnings
  7186. (cl-remove-if
  7187. (lambda (warning)
  7188. (let ((msg (caar warning)))
  7189. (member msg js2-ignored-warnings)))
  7190. js2-parsed-warnings)))
  7191. js2-parsed-warnings)
  7192. (defun js2-parse-function-closure-body (fn-node)
  7193. "Parse a JavaScript 1.8 function closure body."
  7194. (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
  7195. (if js2-ts-hit-eof
  7196. (js2-report-error "msg.no.brace.body" nil
  7197. (js2-node-pos fn-node)
  7198. (- js2-ts-cursor (js2-node-pos fn-node)))
  7199. (js2-node-add-children fn-node
  7200. (setf (js2-function-node-body fn-node)
  7201. (js2-parse-expr t))))))
  7202. (defun js2-parse-function-body (fn-node)
  7203. (js2-must-match js2-LC "msg.no.brace.body"
  7204. (js2-node-pos fn-node)
  7205. (- js2-ts-cursor (js2-node-pos fn-node)))
  7206. (let ((pos (js2-current-token-beg)) ; LC position
  7207. (pn (make-js2-block-node)) ; starts at LC position
  7208. tt
  7209. end
  7210. not-in-directive-prologue
  7211. node
  7212. directive)
  7213. (cl-incf js2-nesting-of-function)
  7214. (unwind-protect
  7215. (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
  7216. (= tt js2-EOF)
  7217. (= tt js2-RC)))
  7218. (js2-block-node-push
  7219. pn
  7220. (if (/= tt js2-FUNCTION)
  7221. (if not-in-directive-prologue
  7222. (js2-parse-statement)
  7223. (setq node (js2-parse-statement)
  7224. directive (js2-get-directive node))
  7225. (cond
  7226. ((null directive)
  7227. (setq not-in-directive-prologue t))
  7228. ((string= directive "use strict")
  7229. ;; Back up and reparse the function, because new rules apply
  7230. ;; to the function name and parameters.
  7231. (when (not js2-in-use-strict-directive)
  7232. (setq js2-in-use-strict-directive t)
  7233. (throw 'reparse t))))
  7234. node)
  7235. (js2-get-token)
  7236. (js2-parse-function-stmt))))
  7237. (cl-decf js2-nesting-of-function))
  7238. (setq end (js2-current-token-end)) ; assume no curly and leave at current token
  7239. (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
  7240. (setq end (js2-current-token-end)))
  7241. (setf (js2-node-pos pn) pos
  7242. (js2-node-len pn) (- end pos))
  7243. (setf (js2-function-node-body fn-node) pn)
  7244. (js2-node-add-children fn-node pn)
  7245. pn))
  7246. (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
  7247. "Declare and fontify destructuring parameters inside NODE.
  7248. NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'.
  7249. Return a list of `js2-name-node' nodes representing the symbols
  7250. declared; probably to check them for errors."
  7251. (let ((name-nodes (js2--collect-target-symbols node t)))
  7252. (dolist (node name-nodes)
  7253. (let (leftpos)
  7254. (js2-define-symbol decl-type (js2-name-node-name node)
  7255. node ignore-not-in-block)
  7256. (when face
  7257. (js2-set-face (setq leftpos (js2-node-abs-pos node))
  7258. (+ leftpos (js2-node-len node))
  7259. face 'record))))
  7260. name-nodes))
  7261. (defvar js2-illegal-strict-identifiers
  7262. '("eval" "arguments")
  7263. "Identifiers not allowed as variables in strict mode.")
  7264. (defun js2-check-strict-identifier (name-node)
  7265. "Check that NAME-NODE makes a legal strict mode identifier."
  7266. (when js2-in-use-strict-directive
  7267. (let ((param-name (js2-name-node-name name-node)))
  7268. (when (member param-name js2-illegal-strict-identifiers)
  7269. (js2-report-error "msg.bad.id.strict" param-name
  7270. (js2-node-abs-pos name-node) (js2-node-len name-node))))))
  7271. (defun js2-check-strict-function-params (preceding-params params)
  7272. "Given PRECEDING-PARAMS in a function's parameter list, check
  7273. for strict mode errors caused by PARAMS."
  7274. (when js2-in-use-strict-directive
  7275. (dolist (param params)
  7276. (let ((param-name (js2-name-node-name param)))
  7277. (js2-check-strict-identifier param)
  7278. (when (cl-some (lambda (param)
  7279. (string= (js2-name-node-name param) param-name))
  7280. preceding-params)
  7281. (js2-report-error "msg.dup.param.strict" param-name
  7282. (js2-node-abs-pos param) (js2-node-len param)))))))
  7283. (defun js2-parse-function-params (function-type fn-node pos)
  7284. "Parse the parameters of a function of FUNCTION-TYPE
  7285. represented by FN-NODE at POS."
  7286. (if (js2-match-token js2-RP)
  7287. (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
  7288. (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
  7289. (eq (js2-current-token-type) js2-NAME)))
  7290. params param
  7291. param-name-nodes new-param-name-nodes
  7292. rest-param-at)
  7293. (when paren-free-arrow
  7294. (js2-unget-token))
  7295. (cl-loop for tt = (js2-peek-token)
  7296. do
  7297. (cond
  7298. ;; destructuring param
  7299. ((and (not paren-free-arrow)
  7300. (or (= tt js2-LB) (= tt js2-LC)))
  7301. (js2-get-token)
  7302. (setq param (js2-parse-destruct-primary-expr)
  7303. new-param-name-nodes (js2-define-destruct-symbols
  7304. param js2-LP 'js2-function-param))
  7305. (js2-check-strict-function-params param-name-nodes new-param-name-nodes)
  7306. (setq param-name-nodes (append param-name-nodes new-param-name-nodes)))
  7307. ;; variable name
  7308. (t
  7309. (when (and (>= js2-language-version 200)
  7310. (not paren-free-arrow)
  7311. (js2-match-token js2-TRIPLEDOT)
  7312. (not rest-param-at))
  7313. ;; to report errors if there are more parameters
  7314. (setq rest-param-at (length params)))
  7315. (js2-must-match-name "msg.no.parm")
  7316. (js2-record-face 'js2-function-param)
  7317. (setq param (js2-create-name-node))
  7318. (js2-define-symbol js2-LP (js2-current-token-string) param)
  7319. (js2-check-strict-function-params param-name-nodes (list param))
  7320. (setq param-name-nodes (append param-name-nodes (list param)))))
  7321. ;; default parameter value
  7322. (when (and (not rest-param-at)
  7323. (>= js2-language-version 200)
  7324. (js2-match-token js2-ASSIGN))
  7325. (cl-assert (not paren-free-arrow))
  7326. (let* ((pos (js2-node-pos param))
  7327. (tt (js2-current-token-type))
  7328. (op-pos (- (js2-current-token-beg) pos))
  7329. (left param)
  7330. (right (js2-parse-assign-expr))
  7331. (len (- (js2-node-end right) pos)))
  7332. (setq param (make-js2-assign-node
  7333. :type tt :pos pos :len len :op-pos op-pos
  7334. :left left :right right))
  7335. (js2-node-add-children param left right)))
  7336. (push param params)
  7337. (when (and rest-param-at (> (length params) (1+ rest-param-at)))
  7338. (js2-report-error "msg.param.after.rest" nil
  7339. (js2-node-pos param) (js2-node-len param)))
  7340. while
  7341. (and (js2-match-token js2-COMMA)
  7342. (or (< js2-language-version 200)
  7343. (not (= js2-RP (js2-peek-token))))))
  7344. (when (and (not paren-free-arrow)
  7345. (js2-must-match js2-RP "msg.no.paren.after.parms"))
  7346. (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
  7347. (when rest-param-at
  7348. (setf (js2-function-node-rest-p fn-node) t))
  7349. (dolist (p params)
  7350. (js2-node-add-children fn-node p)
  7351. (push p (js2-function-node-params fn-node))))))
  7352. (defun js2-check-inconsistent-return-warning (fn-node name)
  7353. "Possibly show inconsistent-return warning.
  7354. Last token scanned is the close-curly for the function body."
  7355. (when (and js2-mode-show-strict-warnings
  7356. js2-strict-inconsistent-return-warning
  7357. (not (js2-has-consistent-return-usage
  7358. (js2-function-node-body fn-node))))
  7359. ;; Have it extend from close-curly to bol or beginning of block.
  7360. (let ((pos (save-excursion
  7361. (goto-char (js2-current-token-end))
  7362. (max (js2-node-abs-pos (js2-function-node-body fn-node))
  7363. (point-at-bol))))
  7364. (end (js2-current-token-end)))
  7365. (if (cl-plusp (js2-name-node-length name))
  7366. (js2-add-strict-warning "msg.no.return.value"
  7367. (js2-name-node-name name) pos end)
  7368. (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
  7369. (defun js2-parse-function-stmt (&optional async-p)
  7370. (let ((pos (js2-current-token-beg))
  7371. (star-p (js2-match-token js2-MUL)))
  7372. (js2-must-match-name "msg.unnamed.function.stmt")
  7373. (let ((name (js2-create-name-node t))
  7374. pn member-expr)
  7375. (cond
  7376. ((js2-match-token js2-LP)
  7377. (js2-parse-function 'FUNCTION_STATEMENT pos star-p async-p name))
  7378. (js2-allow-member-expr-as-function-name
  7379. (setq member-expr (js2-parse-member-expr-tail nil name))
  7380. (js2-parse-highlight-member-expr-fn-name member-expr)
  7381. (js2-must-match js2-LP "msg.no.paren.parms")
  7382. (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p async-p)
  7383. (js2-function-node-member-expr pn) member-expr)
  7384. pn)
  7385. (t
  7386. (js2-report-error "msg.no.paren.parms")
  7387. (make-js2-error-node))))))
  7388. (defun js2-parse-async-function-stmt ()
  7389. (js2-parse-function-stmt t))
  7390. (defun js2-parse-function-expr (&optional async-p)
  7391. (let ((pos (js2-current-token-beg))
  7392. (star-p (js2-match-token js2-MUL))
  7393. name)
  7394. (when (js2-match-token js2-NAME)
  7395. (setq name (js2-create-name-node t)))
  7396. (js2-must-match js2-LP "msg.no.paren.parms")
  7397. (js2-parse-function 'FUNCTION_EXPRESSION pos star-p async-p name)))
  7398. (defun js2-parse-function-internal (function-type pos star-p &optional async-p name)
  7399. (let (fn-node lp)
  7400. (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
  7401. (setq lp (js2-current-token-beg)))
  7402. (setf fn-node (make-js2-function-node :pos pos
  7403. :name name
  7404. :form function-type
  7405. :lp (if lp (- lp pos))
  7406. :generator-type (and star-p 'STAR)
  7407. :async async-p))
  7408. (when name
  7409. (js2-set-face (js2-node-pos name) (js2-node-end name)
  7410. 'font-lock-function-name-face 'record)
  7411. (when (and (eq function-type 'FUNCTION_STATEMENT)
  7412. (cl-plusp (js2-name-node-length name)))
  7413. ;; Function statements define a symbol in the enclosing scope
  7414. (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
  7415. (when js2-in-use-strict-directive
  7416. (js2-check-strict-identifier name)))
  7417. (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
  7418. ;; 1. Nested functions are not affected by the dynamic scope flag
  7419. ;; as dynamic scope is already a parent of their scope.
  7420. ;; 2. Functions defined under the with statement also immune to
  7421. ;; this setup, in which case dynamic scope is ignored in favor
  7422. ;; of the with object.
  7423. (setf (js2-function-node-ignore-dynamic fn-node) t))
  7424. ;; dynamically bind all the per-function variables
  7425. (let ((js2-current-script-or-fn fn-node)
  7426. (js2-current-scope fn-node)
  7427. (js2-nesting-of-with 0)
  7428. (js2-end-flags 0)
  7429. js2-label-set
  7430. js2-loop-set
  7431. js2-loop-and-switch-set)
  7432. (js2-parse-function-params function-type fn-node pos)
  7433. (when (eq function-type 'FUNCTION_ARROW)
  7434. (js2-must-match js2-ARROW "msg.bad.arrow.args"))
  7435. (if (and (>= js2-language-version 180)
  7436. (/= (js2-peek-token) js2-LC))
  7437. (js2-parse-function-closure-body fn-node)
  7438. (js2-parse-function-body fn-node))
  7439. (js2-check-inconsistent-return-warning fn-node name)
  7440. (when name
  7441. (js2-node-add-children fn-node name)
  7442. ;; Function expressions define a name only in the body of the
  7443. ;; function, and only if not hidden by a parameter name
  7444. (when (and (eq function-type 'FUNCTION_EXPRESSION)
  7445. (null (js2-scope-get-symbol js2-current-scope
  7446. (js2-name-node-name name))))
  7447. (js2-define-symbol js2-FUNCTION
  7448. (js2-name-node-name name)
  7449. fn-node))
  7450. (when (eq function-type 'FUNCTION_STATEMENT)
  7451. (js2-record-imenu-functions fn-node))))
  7452. (setf (js2-node-len fn-node) (- (js2-current-token-end) pos))
  7453. ;; Rhino doesn't do this, but we need it for finding undeclared vars.
  7454. ;; We wait until after parsing the function to set its parent scope,
  7455. ;; since `js2-define-symbol' needs the defining-scope check to stop
  7456. ;; at the function boundary when checking for redeclarations.
  7457. (setf (js2-scope-parent-scope fn-node) js2-current-scope)
  7458. fn-node))
  7459. (defun js2-parse-function (function-type pos star-p &optional async-p name)
  7460. "Function parser. FUNCTION-TYPE is a symbol, POS is the
  7461. beginning of the first token (function keyword, unless it's an
  7462. arrow function), NAME is js2-name-node."
  7463. (let ((continue t)
  7464. ts-state
  7465. fn-node
  7466. ;; Preserve strict state outside this function.
  7467. (js2-in-use-strict-directive js2-in-use-strict-directive))
  7468. ;; Parse multiple times if a new strict mode directive is discovered in the
  7469. ;; function body, as new rules will be retroactively applied to the legality
  7470. ;; of function names and parameters.
  7471. (while continue
  7472. (setq ts-state (make-js2-ts-state))
  7473. (setq continue (catch 'reparse
  7474. (setq fn-node (js2-parse-function-internal
  7475. function-type pos star-p async-p name))
  7476. ;; Don't continue.
  7477. nil))
  7478. (when continue
  7479. (js2-ts-seek ts-state)))
  7480. fn-node))
  7481. (defun js2-parse-statements (&optional parent)
  7482. "Parse a statement list. Last token consumed must be js2-LC.
  7483. PARENT can be a `js2-block-node', in which case the statements are
  7484. appended to PARENT. Otherwise a new `js2-block-node' is created
  7485. and returned.
  7486. This function does not match the closing js2-RC: the caller
  7487. matches the RC so it can provide a suitable error message if not
  7488. matched. This means it's up to the caller to set the length of
  7489. the node to include the closing RC. The node start pos is set to
  7490. the absolute buffer start position, and the caller should fix it
  7491. up to be relative to the parent node. All children of this block
  7492. node are given relative start positions and correct lengths."
  7493. (let ((pn (or parent (make-js2-block-node)))
  7494. tt)
  7495. (while (and (> (setq tt (js2-peek-token)) js2-EOF)
  7496. (/= tt js2-RC))
  7497. (js2-block-node-push pn (js2-parse-statement)))
  7498. pn))
  7499. (defun js2-parse-statement ()
  7500. (let (pn beg end)
  7501. ;; coarse-grained user-interrupt check - needs work
  7502. (and js2-parse-interruptable-p
  7503. (zerop (% (cl-incf js2-parse-stmt-count)
  7504. js2-statements-per-pause))
  7505. (input-pending-p)
  7506. (throw 'interrupted t))
  7507. (setq pn (js2-statement-helper))
  7508. ;; no-side-effects warning check
  7509. (unless (js2-node-has-side-effects pn)
  7510. (setq end (js2-node-end pn))
  7511. (save-excursion
  7512. (goto-char end)
  7513. (setq beg (max (js2-node-pos pn) (point-at-bol))))
  7514. (js2-add-strict-warning "msg.no.side.effects" nil beg end))
  7515. pn))
  7516. ;; These correspond to the switch cases in Parser.statementHelper
  7517. (defconst js2-parsers
  7518. (let ((parsers (make-vector js2-num-tokens
  7519. #'js2-parse-expr-stmt)))
  7520. (aset parsers js2-BREAK #'js2-parse-break)
  7521. (aset parsers js2-CLASS #'js2-parse-class-stmt)
  7522. (aset parsers js2-CONST #'js2-parse-const-var)
  7523. (aset parsers js2-CONTINUE #'js2-parse-continue)
  7524. (aset parsers js2-DEBUGGER #'js2-parse-debugger)
  7525. (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
  7526. (aset parsers js2-DO #'js2-parse-do)
  7527. (aset parsers js2-EXPORT #'js2-parse-export)
  7528. (aset parsers js2-FOR #'js2-parse-for)
  7529. (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
  7530. (aset parsers js2-IF #'js2-parse-if)
  7531. (aset parsers js2-IMPORT #'js2-parse-import)
  7532. (aset parsers js2-LC #'js2-parse-block)
  7533. (aset parsers js2-LET #'js2-parse-let-stmt)
  7534. (aset parsers js2-NAME #'js2-parse-name-or-label)
  7535. (aset parsers js2-RETURN #'js2-parse-ret-yield)
  7536. (aset parsers js2-SEMI #'js2-parse-semi)
  7537. (aset parsers js2-SWITCH #'js2-parse-switch)
  7538. (aset parsers js2-THROW #'js2-parse-throw)
  7539. (aset parsers js2-TRY #'js2-parse-try)
  7540. (aset parsers js2-VAR #'js2-parse-const-var)
  7541. (aset parsers js2-WHILE #'js2-parse-while)
  7542. (aset parsers js2-WITH #'js2-parse-with)
  7543. (aset parsers js2-YIELD #'js2-parse-ret-yield)
  7544. parsers)
  7545. "A vector mapping token types to parser functions.")
  7546. (defun js2-parse-warn-missing-semi (beg end)
  7547. (and js2-mode-show-strict-warnings
  7548. js2-strict-missing-semi-warning
  7549. (js2-add-strict-warning
  7550. "msg.missing.semi" nil
  7551. ;; back up to beginning of statement or line
  7552. (max beg (save-excursion
  7553. (goto-char end)
  7554. (point-at-bol)))
  7555. end)))
  7556. (defconst js2-no-semi-insertion
  7557. (list js2-IF
  7558. js2-SWITCH
  7559. js2-WHILE
  7560. js2-DO
  7561. js2-FOR
  7562. js2-TRY
  7563. js2-WITH
  7564. js2-LC
  7565. js2-ERROR
  7566. js2-SEMI
  7567. js2-CLASS
  7568. js2-FUNCTION
  7569. js2-EXPORT)
  7570. "List of tokens that don't do automatic semicolon insertion.")
  7571. (defconst js2-autoinsert-semi-and-warn
  7572. (list js2-ERROR js2-EOF js2-RC))
  7573. (defun js2-statement-helper ()
  7574. (let* ((tt (js2-get-token))
  7575. (first-tt tt)
  7576. (async-stmt (js2-match-async-function))
  7577. (parser (if (= tt js2-ERROR)
  7578. #'js2-parse-semi
  7579. (if async-stmt
  7580. #'js2-parse-async-function-stmt
  7581. (aref js2-parsers tt))))
  7582. pn)
  7583. ;; If the statement is set, then it's been told its label by now.
  7584. (and js2-labeled-stmt
  7585. (js2-labeled-stmt-node-stmt js2-labeled-stmt)
  7586. (setq js2-labeled-stmt nil))
  7587. (setq pn (funcall parser))
  7588. ;; Don't do auto semi insertion for certain statement types.
  7589. (unless (or (memq first-tt js2-no-semi-insertion)
  7590. (js2-labeled-stmt-node-p pn)
  7591. async-stmt)
  7592. (js2-auto-insert-semicolon pn))
  7593. pn))
  7594. (defun js2-auto-insert-semicolon (pn)
  7595. (let* ((tt (js2-get-token))
  7596. (pos (js2-node-pos pn)))
  7597. (cond
  7598. ((= tt js2-SEMI)
  7599. ;; extend the node bounds to include the semicolon.
  7600. (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
  7601. ((memq tt js2-autoinsert-semi-and-warn)
  7602. (js2-unget-token) ; Not ';', do not consume.
  7603. ;; Autoinsert ;
  7604. (js2-parse-warn-missing-semi pos (js2-node-end pn)))
  7605. (t
  7606. (if (not (js2-token-follows-eol-p (js2-current-token)))
  7607. ;; Report error if no EOL or autoinsert ';' otherwise
  7608. (js2-report-error "msg.no.semi.stmt")
  7609. (js2-parse-warn-missing-semi pos (js2-node-end pn)))
  7610. (js2-unget-token) ; Not ';', do not consume.
  7611. ))))
  7612. (defun js2-parse-condition ()
  7613. "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
  7614. The parens are discarded and the expression node is returned.
  7615. The `pos' field of the return value is set to an absolute position
  7616. that must be fixed up by the caller.
  7617. Return value is a list (EXPR LP RP), with absolute paren positions."
  7618. (let (pn lp rp)
  7619. (if (js2-must-match js2-LP "msg.no.paren.cond")
  7620. (setq lp (js2-current-token-beg)))
  7621. (setq pn (js2-parse-expr))
  7622. (if (js2-must-match js2-RP "msg.no.paren.after.cond")
  7623. (setq rp (js2-current-token-beg)))
  7624. ;; Report strict warning on code like "if (a = 7) ..."
  7625. (if (and js2-strict-cond-assign-warning
  7626. (js2-assign-node-p pn))
  7627. (js2-add-strict-warning "msg.equal.as.assign" nil
  7628. (js2-node-pos pn)
  7629. (+ (js2-node-pos pn)
  7630. (js2-node-len pn))))
  7631. (list pn lp rp)))
  7632. (defun js2-parse-if ()
  7633. "Parser for if-statement. Last matched token must be js2-IF."
  7634. (let ((pos (js2-current-token-beg))
  7635. cond if-true if-false else-pos end pn)
  7636. (setq cond (js2-parse-condition)
  7637. if-true (js2-parse-statement)
  7638. if-false (if (js2-match-token js2-ELSE)
  7639. (progn
  7640. (setq else-pos (- (js2-current-token-beg) pos))
  7641. (js2-parse-statement)))
  7642. end (js2-node-end (or if-false if-true))
  7643. pn (make-js2-if-node :pos pos
  7644. :len (- end pos)
  7645. :condition (car cond)
  7646. :then-part if-true
  7647. :else-part if-false
  7648. :else-pos else-pos
  7649. :lp (js2-relpos (cl-second cond) pos)
  7650. :rp (js2-relpos (cl-third cond) pos)))
  7651. (js2-node-add-children pn (car cond) if-true if-false)
  7652. pn))
  7653. (defun js2-parse-import ()
  7654. "Parse import statement. The current token must be js2-IMPORT."
  7655. (unless (js2-ast-root-p js2-current-scope)
  7656. (js2-report-error "msg.mod.import.decl.at.top.level"))
  7657. (let ((beg (js2-current-token-beg)))
  7658. (cond ((js2-match-token js2-STRING)
  7659. (make-js2-import-node
  7660. :pos beg
  7661. :len (- (js2-current-token-end) beg)
  7662. :module-id (js2-current-token-string)))
  7663. (t
  7664. (let* ((import-clause (js2-parse-import-clause))
  7665. (from-clause (and import-clause (js2-parse-from-clause)))
  7666. (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
  7667. (node (make-js2-import-node
  7668. :pos beg
  7669. :len (- (js2-current-token-end) beg)
  7670. :import import-clause
  7671. :from from-clause
  7672. :module-id module-id)))
  7673. (when import-clause
  7674. (js2-node-add-children node import-clause))
  7675. (when from-clause
  7676. (js2-node-add-children node from-clause))
  7677. node)))))
  7678. (defun js2-parse-import-clause ()
  7679. "Parse the bindings in an import statement.
  7680. This can take many forms:
  7681. ImportedDefaultBinding -> 'foo'
  7682. NameSpaceImport -> '* as lib'
  7683. NamedImports -> '{foo as bar, bang}'
  7684. ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
  7685. ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
  7686. Try to match namespace imports and named imports first because nothing can
  7687. come after them. If it is an imported default binding, then it could have named
  7688. imports or a namespace import that follows it.
  7689. "
  7690. (let* ((beg (js2-current-token-beg))
  7691. (clause (make-js2-import-clause-node
  7692. :pos beg))
  7693. (children (list)))
  7694. (cond
  7695. ((js2-match-token js2-MUL)
  7696. (let ((ns-import (js2-parse-namespace-import)))
  7697. (when ns-import
  7698. (let ((name-node (js2-namespace-import-node-name ns-import)))
  7699. (js2-define-symbol
  7700. js2-LET (js2-name-node-name name-node) name-node t))
  7701. (setf (js2-import-clause-node-namespace-import clause) ns-import)
  7702. (push ns-import children))))
  7703. ((js2-match-token js2-LC)
  7704. (let ((imports (js2-parse-export-bindings t)))
  7705. (setf (js2-import-clause-node-named-imports clause) imports)
  7706. (dolist (import imports)
  7707. (push import children)
  7708. (let ((name-node (js2-export-binding-node-local-name import)))
  7709. (when name-node
  7710. (js2-define-symbol
  7711. js2-LET (js2-name-node-name name-node) name-node t))))))
  7712. ((= (js2-peek-token) js2-NAME)
  7713. (let ((binding (js2-maybe-parse-export-binding t)))
  7714. (let ((node-name (js2-export-binding-node-local-name binding)))
  7715. (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
  7716. (setf (js2-import-clause-node-default-binding clause) binding)
  7717. (push binding children))
  7718. (when (js2-match-token js2-COMMA)
  7719. (cond
  7720. ((js2-match-token js2-MUL)
  7721. (let ((ns-import (js2-parse-namespace-import)))
  7722. (let ((name-node (js2-namespace-import-node-name ns-import)))
  7723. (js2-define-symbol
  7724. js2-LET (js2-name-node-name name-node) name-node t))
  7725. (setf (js2-import-clause-node-namespace-import clause) ns-import)
  7726. (push ns-import children)))
  7727. ((js2-match-token js2-LC)
  7728. (let ((imports (js2-parse-export-bindings t)))
  7729. (setf (js2-import-clause-node-named-imports clause) imports)
  7730. (dolist (import imports)
  7731. (push import children)
  7732. (let ((name-node (js2-export-binding-node-local-name import)))
  7733. (when name-node
  7734. (js2-define-symbol
  7735. js2-LET (js2-name-node-name name-node) name-node t))))))
  7736. (t (js2-report-error "msg.syntax")))))
  7737. (t (js2-report-error "msg.mod.declaration.after.import")))
  7738. (setf (js2-node-len clause) (- (js2-current-token-end) beg))
  7739. (apply #'js2-node-add-children clause children)
  7740. clause))
  7741. (defun js2-parse-namespace-import ()
  7742. "Parse a namespace import expression such as '* as bar'.
  7743. The current token must be js2-MUL."
  7744. (let ((beg (js2-current-token-beg)))
  7745. (cond
  7746. ((js2-match-contextual-kwd "as")
  7747. (when (js2-must-match-prop-name "msg.syntax")
  7748. (let ((node (make-js2-namespace-import-node
  7749. :pos beg
  7750. :len (- (js2-current-token-end) beg)
  7751. :name (make-js2-name-node
  7752. :pos (js2-current-token-beg)
  7753. :len (- (js2-current-token-end)
  7754. (js2-current-token-beg))
  7755. :name (js2-current-token-string)))))
  7756. (js2-node-add-children node (js2-namespace-import-node-name node))
  7757. node)))
  7758. (t
  7759. (js2-unget-token)
  7760. (js2-report-error "msg.syntax")
  7761. nil))))
  7762. (defun js2-parse-from-clause ()
  7763. "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
  7764. (if (js2-match-contextual-kwd "from")
  7765. (let ((beg (js2-current-token-beg)))
  7766. (cond
  7767. ((js2-match-token js2-STRING)
  7768. (make-js2-from-clause-node
  7769. :pos beg
  7770. :len (- (js2-current-token-end) beg)
  7771. :module-id (js2-current-token-string)
  7772. :metadata-p nil))
  7773. ((js2-match-token js2-THIS)
  7774. (when (js2-must-match-name "msg.mod.spec.after.from")
  7775. (if (equal "module" (js2-current-token-string))
  7776. (make-js2-from-clause-node
  7777. :pos beg
  7778. :len (- (js2-current-token-end) beg)
  7779. :module-id "this"
  7780. :metadata-p t)
  7781. (js2-unget-token)
  7782. (js2-unget-token)
  7783. (js2-report-error "msg.mod.spec.after.from")
  7784. nil)))
  7785. (t (js2-report-error "msg.mod.spec.after.from") nil)))
  7786. (js2-report-error "msg.mod.from.after.import.spec.set")
  7787. nil))
  7788. (defun js2-parse-export-bindings (&optional import-p)
  7789. "Parse a list of export binding expressions such as {}, {foo, bar}, and
  7790. {foo as bar, baz as bang}. The current token must be
  7791. js2-LC. Return a lisp list of js2-export-binding-node"
  7792. (let ((bindings (list)))
  7793. (while
  7794. (let ((binding (js2-maybe-parse-export-binding import-p)))
  7795. (when binding
  7796. (push binding bindings))
  7797. (js2-match-token js2-COMMA)))
  7798. (when (js2-must-match js2-RC (if import-p
  7799. "msg.mod.rc.after.import.spec.list"
  7800. "msg.mod.rc.after.export.spec.list"))
  7801. (reverse bindings))))
  7802. (defun js2-maybe-parse-export-binding (&optional import-p)
  7803. "Attempt to parse a binding expression found inside an import/export statement.
  7804. This can take the form of either as single js2-NAME token as in 'foo' or as in a
  7805. rebinding expression 'bar as foo'. If it matches, it will return an instance of
  7806. js2-export-binding-node and consume all the tokens. If it does not match, it
  7807. consumes no tokens."
  7808. (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
  7809. (beg (js2-current-token-beg))
  7810. (extern-name-len (js2-current-token-len))
  7811. (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
  7812. (aref js2-kwd-tokens (js2-current-token-type)))))
  7813. (if extern-name
  7814. (if (js2-match-contextual-kwd "as")
  7815. (let ((name
  7816. (or
  7817. (and (js2-match-token js2-DEFAULT) "default")
  7818. (and (js2-match-token js2-NAME) (js2-current-token-string)))))
  7819. (if name
  7820. (let ((node (make-js2-export-binding-node
  7821. :pos beg
  7822. :len (- (js2-current-token-end) beg)
  7823. :local-name (make-js2-name-node
  7824. :name name
  7825. :pos (js2-current-token-beg)
  7826. :len (js2-current-token-len))
  7827. :extern-name (make-js2-name-node
  7828. :name extern-name
  7829. :pos beg
  7830. :len extern-name-len))))
  7831. (js2-node-add-children
  7832. node
  7833. (js2-export-binding-node-local-name node)
  7834. (js2-export-binding-node-extern-name node))
  7835. (if import-p
  7836. (js2-set-face (js2-current-token-beg) (js2-current-token-end)
  7837. 'font-lock-variable-name-face 'record))
  7838. node)
  7839. (js2-unget-token)
  7840. nil))
  7841. (let* ((name-node (make-js2-name-node
  7842. :name (js2-current-token-string)
  7843. :pos (js2-current-token-beg)
  7844. :len (js2-current-token-len)))
  7845. (node (make-js2-export-binding-node
  7846. :pos (js2-current-token-beg)
  7847. :len (js2-current-token-len)
  7848. :local-name name-node
  7849. :extern-name name-node)))
  7850. (when is-reserved-name
  7851. (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
  7852. (js2-node-add-children node name-node)
  7853. (if import-p
  7854. (js2-set-face (js2-current-token-beg) (js2-current-token-end)
  7855. 'font-lock-variable-name-face 'record))
  7856. node))
  7857. nil)))
  7858. (defun js2-parse-switch ()
  7859. "Parser for switch-statement. Last matched token must be js2-SWITCH."
  7860. (let ((pos (js2-current-token-beg))
  7861. tt pn discriminant has-default case-expr case-node
  7862. case-pos cases stmt lp)
  7863. (if (js2-must-match js2-LP "msg.no.paren.switch")
  7864. (setq lp (js2-current-token-beg)))
  7865. (setq discriminant (js2-parse-expr)
  7866. pn (make-js2-switch-node :discriminant discriminant
  7867. :pos pos
  7868. :lp (js2-relpos lp pos)))
  7869. (js2-node-add-children pn discriminant)
  7870. (js2-enter-switch pn)
  7871. (unwind-protect
  7872. (progn
  7873. (if (js2-must-match js2-RP "msg.no.paren.after.switch")
  7874. (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
  7875. (js2-must-match js2-LC "msg.no.brace.switch")
  7876. (catch 'break
  7877. (while t
  7878. (setq tt (js2-next-token)
  7879. case-pos (js2-current-token-beg))
  7880. (cond
  7881. ((= tt js2-RC)
  7882. (setf (js2-node-len pn) (- (js2-current-token-end) pos))
  7883. (throw 'break nil)) ; done
  7884. ((= tt js2-CASE)
  7885. (setq case-expr (js2-parse-expr))
  7886. (js2-must-match js2-COLON "msg.no.colon.case"))
  7887. ((= tt js2-DEFAULT)
  7888. (if has-default
  7889. (js2-report-error "msg.double.switch.default"))
  7890. (setq has-default t
  7891. case-expr nil)
  7892. (js2-must-match js2-COLON "msg.no.colon.case"))
  7893. (t
  7894. (js2-report-error "msg.bad.switch")
  7895. (throw 'break nil)))
  7896. (setq case-node (make-js2-case-node :pos case-pos
  7897. :len (- (js2-current-token-end) case-pos)
  7898. :expr case-expr))
  7899. (js2-node-add-children case-node case-expr)
  7900. (while (and (/= (setq tt (js2-peek-token)) js2-RC)
  7901. (/= tt js2-CASE)
  7902. (/= tt js2-DEFAULT)
  7903. (/= tt js2-EOF))
  7904. (setf stmt (js2-parse-statement)
  7905. (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
  7906. (js2-block-node-push case-node stmt))
  7907. (push case-node cases)))
  7908. ;; add cases last, as pushing reverses the order to be correct
  7909. (dolist (kid cases)
  7910. (js2-node-add-children pn kid)
  7911. (push kid (js2-switch-node-cases pn)))
  7912. pn) ; return value
  7913. (js2-exit-switch))))
  7914. (defun js2-parse-while ()
  7915. "Parser for while-statement. Last matched token must be js2-WHILE."
  7916. (let ((pos (js2-current-token-beg))
  7917. (pn (make-js2-while-node))
  7918. cond body)
  7919. (js2-enter-loop pn)
  7920. (unwind-protect
  7921. (progn
  7922. (setf cond (js2-parse-condition)
  7923. (js2-while-node-condition pn) (car cond)
  7924. body (js2-parse-statement)
  7925. (js2-while-node-body pn) body
  7926. (js2-node-len pn) (- (js2-node-end body) pos)
  7927. (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
  7928. (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
  7929. (js2-node-add-children pn body (car cond)))
  7930. (js2-exit-loop))
  7931. pn))
  7932. (defun js2-parse-do ()
  7933. "Parser for do-statement. Last matched token must be js2-DO."
  7934. (let ((pos (js2-current-token-beg))
  7935. (pn (make-js2-do-node))
  7936. cond body end)
  7937. (js2-enter-loop pn)
  7938. (unwind-protect
  7939. (progn
  7940. (setq body (js2-parse-statement))
  7941. (js2-must-match js2-WHILE "msg.no.while.do")
  7942. (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
  7943. cond (js2-parse-condition)
  7944. (js2-do-node-condition pn) (car cond)
  7945. (js2-do-node-body pn) body
  7946. end js2-ts-cursor
  7947. (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
  7948. (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
  7949. (js2-node-add-children pn (car cond) body))
  7950. (js2-exit-loop))
  7951. ;; Always auto-insert semicolon to follow SpiderMonkey:
  7952. ;; It is required by ECMAScript but is ignored by the rest of
  7953. ;; world; see bug 238945
  7954. (if (js2-match-token js2-SEMI)
  7955. (setq end js2-ts-cursor))
  7956. (setf (js2-node-len pn) (- end pos))
  7957. pn))
  7958. (defun js2-parse-export ()
  7959. "Parse an export statement.
  7960. The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
  7961. expressions should only be either hoistable expressions (function or generator)
  7962. or assignment expressions, but there is no checking to enforce that and so it
  7963. will parse without error a small subset of
  7964. invalid export statements."
  7965. (unless (js2-ast-root-p js2-current-scope)
  7966. (js2-report-error "msg.mod.export.decl.at.top.level"))
  7967. (let ((beg (js2-current-token-beg))
  7968. (children (list))
  7969. exports-list from-clause declaration default)
  7970. (cond
  7971. ((js2-match-token js2-MUL)
  7972. (setq from-clause (js2-parse-from-clause))
  7973. (when from-clause
  7974. (push from-clause children)))
  7975. ((js2-match-token js2-LC)
  7976. (setq exports-list (js2-parse-export-bindings))
  7977. (when exports-list
  7978. (dolist (export exports-list)
  7979. (push export children)))
  7980. (when (js2-match-contextual-kwd "from")
  7981. (js2-unget-token)
  7982. (setq from-clause (js2-parse-from-clause))))
  7983. ((js2-match-token js2-DEFAULT)
  7984. (setq default (cond ((js2-match-token js2-CLASS)
  7985. (if (eq (js2-peek-token) js2-NAME)
  7986. (js2-parse-class-stmt)
  7987. (js2-parse-class-expr)))
  7988. ((js2-match-token js2-NAME)
  7989. (if (js2-match-async-function)
  7990. (if (eq (js2-peek-token) js2-NAME)
  7991. (js2-parse-async-function-stmt)
  7992. (js2-parse-function-expr t))
  7993. (js2-unget-token)
  7994. (js2-parse-expr)))
  7995. ((js2-match-token js2-FUNCTION)
  7996. (if (eq (js2-peek-token) js2-NAME)
  7997. (js2-parse-function-stmt)
  7998. (js2-parse-function-expr)))
  7999. (t (js2-parse-expr)))))
  8000. ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
  8001. (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
  8002. ((js2-match-token js2-CLASS)
  8003. (setq declaration (js2-parse-class-stmt)))
  8004. ((js2-match-token js2-NAME)
  8005. (setq declaration
  8006. (if (js2-match-async-function)
  8007. (js2-parse-async-function-stmt)
  8008. (js2-unget-token)
  8009. (js2-parse-expr))))
  8010. ((js2-match-token js2-FUNCTION)
  8011. (setq declaration (js2-parse-function-stmt)))
  8012. (t
  8013. (setq declaration (js2-parse-expr))))
  8014. (when from-clause
  8015. (push from-clause children))
  8016. (when declaration
  8017. (push declaration children)
  8018. (when (not (or (js2-function-node-p declaration)
  8019. (js2-class-node-p declaration)))
  8020. (js2-auto-insert-semicolon declaration)))
  8021. (when default
  8022. (push default children)
  8023. (when (not (or (js2-function-node-p default)
  8024. (js2-class-node-p default)))
  8025. (js2-auto-insert-semicolon default)))
  8026. (let ((node (make-js2-export-node
  8027. :pos beg
  8028. :len (- (js2-current-token-end) beg)
  8029. :exports-list exports-list
  8030. :from-clause from-clause
  8031. :declaration declaration
  8032. :default default)))
  8033. (apply #'js2-node-add-children node children)
  8034. node)))
  8035. (defun js2-parse-for ()
  8036. "Parse a for, for-in or for each-in statement.
  8037. Last matched token must be js2-FOR."
  8038. (let ((for-pos (js2-current-token-beg))
  8039. (tmp-scope (make-js2-scope))
  8040. pn is-for-each is-for-in-or-of is-for-of
  8041. in-pos each-pos tmp-pos
  8042. init ; Node init is also foo in 'foo in object'.
  8043. cond ; Node cond is also object in 'foo in object'.
  8044. incr ; 3rd section of for-loop initializer.
  8045. body tt lp rp)
  8046. ;; See if this is a for each () instead of just a for ()
  8047. (when (js2-match-token js2-NAME)
  8048. (if (string= "each" (js2-current-token-string))
  8049. (progn
  8050. (setq is-for-each t
  8051. each-pos (- (js2-current-token-beg) for-pos)) ; relative
  8052. (js2-record-face 'font-lock-keyword-face))
  8053. (js2-report-error "msg.no.paren.for")))
  8054. (if (js2-must-match js2-LP "msg.no.paren.for")
  8055. (setq lp (- (js2-current-token-beg) for-pos)))
  8056. (setq tt (js2-get-token))
  8057. ;; Capture identifiers inside parens. We can't create the node
  8058. ;; (and use it as the current scope) until we know its type.
  8059. (js2-push-scope tmp-scope)
  8060. (unwind-protect
  8061. (progn
  8062. ;; parse init clause
  8063. (let ((js2-in-for-init t)) ; set as dynamic variable
  8064. (cond
  8065. ((= tt js2-SEMI)
  8066. (js2-unget-token)
  8067. (setq init (make-js2-empty-expr-node)))
  8068. ((or (= tt js2-VAR) (= tt js2-LET) (= tt js2-CONST))
  8069. (setq init (js2-parse-variables tt (js2-current-token-beg))))
  8070. (t
  8071. (js2-unget-token)
  8072. (setq init (js2-parse-expr)))))
  8073. (if (or (js2-match-token js2-IN)
  8074. (and (>= js2-language-version 200)
  8075. (js2-match-contextual-kwd "of")
  8076. (setq is-for-of t)))
  8077. (setq is-for-in-or-of t
  8078. in-pos (- (js2-current-token-beg) for-pos)
  8079. ;; scope of iteration target object is not the scope we've created above.
  8080. ;; stash current scope temporary.
  8081. cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
  8082. (js2-parse-expr))) ; object over which we're iterating
  8083. ;; else ordinary for loop - parse cond and incr
  8084. (js2-must-match js2-SEMI "msg.no.semi.for")
  8085. (setq cond (if (= (js2-peek-token) js2-SEMI)
  8086. (make-js2-empty-expr-node) ; no loop condition
  8087. (js2-parse-expr)))
  8088. (js2-must-match js2-SEMI "msg.no.semi.for.cond")
  8089. (setq tmp-pos (js2-current-token-end)
  8090. incr (if (= (js2-peek-token) js2-RP)
  8091. (make-js2-empty-expr-node :pos tmp-pos)
  8092. (js2-parse-expr)))))
  8093. (js2-pop-scope))
  8094. (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
  8095. (setq rp (- (js2-current-token-beg) for-pos)))
  8096. (if (not is-for-in-or-of)
  8097. (setq pn (make-js2-for-node :init init
  8098. :condition cond
  8099. :update incr
  8100. :lp lp
  8101. :rp rp))
  8102. ;; cond could be null if 'in obj' got eaten by the init node.
  8103. (if (js2-infix-node-p init)
  8104. ;; it was (foo in bar) instead of (var foo in bar)
  8105. (setq cond (js2-infix-node-right init)
  8106. init (js2-infix-node-left init))
  8107. (if (and (js2-var-decl-node-p init)
  8108. (> (length (js2-var-decl-node-kids init)) 1))
  8109. (js2-report-error "msg.mult.index")))
  8110. (setq pn (make-js2-for-in-node :iterator init
  8111. :object cond
  8112. :in-pos in-pos
  8113. :foreach-p is-for-each
  8114. :each-pos each-pos
  8115. :forof-p is-for-of
  8116. :lp lp
  8117. :rp rp)))
  8118. ;; Transplant the declarations.
  8119. (setf (js2-scope-symbol-table pn)
  8120. (js2-scope-symbol-table tmp-scope))
  8121. (unwind-protect
  8122. (progn
  8123. (js2-enter-loop pn)
  8124. ;; We have to parse the body -after- creating the loop node,
  8125. ;; so that the loop node appears in the js2-loop-set, allowing
  8126. ;; break/continue statements to find the enclosing loop.
  8127. (setf body (js2-parse-statement)
  8128. (js2-loop-node-body pn) body
  8129. (js2-node-pos pn) for-pos
  8130. (js2-node-len pn) (- (js2-node-end body) for-pos))
  8131. (js2-node-add-children pn init cond incr body))
  8132. ;; finally
  8133. (js2-exit-loop))
  8134. pn))
  8135. (defun js2-parse-try ()
  8136. "Parse a try statement. Last matched token must be js2-TRY."
  8137. (let ((try-pos (js2-current-token-beg))
  8138. try-end
  8139. try-block
  8140. catch-blocks
  8141. finally-block
  8142. saw-default-catch
  8143. peek)
  8144. (if (/= (js2-peek-token) js2-LC)
  8145. (js2-report-error "msg.no.brace.try"))
  8146. (setq try-block (js2-parse-statement)
  8147. try-end (js2-node-end try-block)
  8148. peek (js2-peek-token))
  8149. (cond
  8150. ((= peek js2-CATCH)
  8151. (while (js2-match-token js2-CATCH)
  8152. (let* ((catch-pos (js2-current-token-beg))
  8153. (catch-node (make-js2-catch-node :pos catch-pos))
  8154. param
  8155. guard-kwd
  8156. catch-cond
  8157. lp rp)
  8158. (if saw-default-catch
  8159. (js2-report-error "msg.catch.unreachable"))
  8160. (if (js2-must-match js2-LP "msg.no.paren.catch")
  8161. (setq lp (- (js2-current-token-beg) catch-pos)))
  8162. (js2-push-scope catch-node)
  8163. (let ((tt (js2-peek-token)))
  8164. (cond
  8165. ;; Destructuring pattern:
  8166. ;; catch ({ message, file }) { ... }
  8167. ((or (= tt js2-LB) (= tt js2-LC))
  8168. (js2-get-token)
  8169. (setq param (js2-parse-destruct-primary-expr))
  8170. (js2-define-destruct-symbols param js2-LET nil))
  8171. ;; Simple name.
  8172. (t
  8173. (js2-must-match-name "msg.bad.catchcond")
  8174. (setq param (js2-create-name-node))
  8175. (js2-define-symbol js2-LET (js2-current-token-string) param)
  8176. (js2-check-strict-identifier param))))
  8177. ;; Catch condition.
  8178. (if (js2-match-token js2-IF)
  8179. (setq guard-kwd (- (js2-current-token-beg) catch-pos)
  8180. catch-cond (js2-parse-expr))
  8181. (setq saw-default-catch t))
  8182. (if (js2-must-match js2-RP "msg.bad.catchcond")
  8183. (setq rp (- (js2-current-token-beg) catch-pos)))
  8184. (js2-must-match js2-LC "msg.no.brace.catchblock")
  8185. (js2-parse-statements catch-node)
  8186. (if (js2-must-match js2-RC "msg.no.brace.after.body")
  8187. (setq try-end (js2-current-token-end)))
  8188. (js2-pop-scope)
  8189. (setf (js2-node-len catch-node) (- try-end catch-pos)
  8190. (js2-catch-node-param catch-node) param
  8191. (js2-catch-node-guard-expr catch-node) catch-cond
  8192. (js2-catch-node-guard-kwd catch-node) guard-kwd
  8193. (js2-catch-node-lp catch-node) lp
  8194. (js2-catch-node-rp catch-node) rp)
  8195. (js2-node-add-children catch-node param catch-cond)
  8196. (push catch-node catch-blocks))))
  8197. ((/= peek js2-FINALLY)
  8198. (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
  8199. (js2-node-pos try-block)
  8200. (- (setq try-end (js2-node-end try-block))
  8201. (js2-node-pos try-block)))))
  8202. (when (js2-match-token js2-FINALLY)
  8203. (let ((finally-pos (js2-current-token-beg))
  8204. (block (js2-parse-statement)))
  8205. (setq try-end (js2-node-end block)
  8206. finally-block (make-js2-finally-node :pos finally-pos
  8207. :len (- try-end finally-pos)
  8208. :body block))
  8209. (js2-node-add-children finally-block block)))
  8210. (let ((pn (make-js2-try-node :pos try-pos
  8211. :len (- try-end try-pos)
  8212. :try-block try-block
  8213. :finally-block finally-block)))
  8214. (js2-node-add-children pn try-block finally-block)
  8215. ;; Push them onto the try-node, which reverses and corrects their order.
  8216. (dolist (cb catch-blocks)
  8217. (js2-node-add-children pn cb)
  8218. (push cb (js2-try-node-catch-clauses pn)))
  8219. pn)))
  8220. (defun js2-parse-throw ()
  8221. "Parser for throw-statement. Last matched token must be js2-THROW."
  8222. (let ((pos (js2-current-token-beg))
  8223. expr pn)
  8224. (if (= (js2-peek-token-or-eol) js2-EOL)
  8225. ;; ECMAScript does not allow new lines before throw expression,
  8226. ;; see bug 256617
  8227. (js2-report-error "msg.bad.throw.eol"))
  8228. (setq expr (js2-parse-expr)
  8229. pn (make-js2-throw-node :pos pos
  8230. :len (- (js2-node-end expr) pos)
  8231. :expr expr))
  8232. (js2-node-add-children pn expr)
  8233. pn))
  8234. (defun js2-match-jump-label-name (label-name)
  8235. "If break/continue specified a label, return that label's labeled stmt.
  8236. Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
  8237. does not match an existing label, reports an error and returns nil."
  8238. (let ((bundle (cdr (assoc label-name js2-label-set))))
  8239. (if (null bundle)
  8240. (js2-report-error "msg.undef.label"))
  8241. bundle))
  8242. (defun js2-parse-break ()
  8243. "Parser for break-statement. Last matched token must be js2-BREAK."
  8244. (let ((pos (js2-current-token-beg))
  8245. (end (js2-current-token-end))
  8246. break-target ; statement to break from
  8247. break-label ; in "break foo", name-node representing the foo
  8248. labels ; matching labeled statement to break to
  8249. pn)
  8250. (when (eq (js2-peek-token-or-eol) js2-NAME)
  8251. (js2-get-token)
  8252. (setq break-label (js2-create-name-node)
  8253. end (js2-node-end break-label)
  8254. ;; matchJumpLabelName only matches if there is one
  8255. labels (js2-match-jump-label-name (js2-current-token-string))
  8256. break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
  8257. (unless (or break-target break-label)
  8258. ;; no break target specified - try for innermost enclosing loop/switch
  8259. (if (null js2-loop-and-switch-set)
  8260. (unless break-label
  8261. (js2-report-error "msg.bad.break" nil pos (length "break")))
  8262. (setq break-target (car js2-loop-and-switch-set))))
  8263. (setq pn (make-js2-break-node :pos pos
  8264. :len (- end pos)
  8265. :label break-label
  8266. :target break-target))
  8267. (js2-node-add-children pn break-label) ; but not break-target
  8268. pn))
  8269. (defun js2-parse-continue ()
  8270. "Parser for continue-statement. Last matched token must be js2-CONTINUE."
  8271. (let ((pos (js2-current-token-beg))
  8272. (end (js2-current-token-end))
  8273. label ; optional user-specified label, a `js2-name-node'
  8274. labels ; current matching labeled stmt, if any
  8275. target ; the `js2-loop-node' target of this continue stmt
  8276. pn)
  8277. (when (= (js2-peek-token-or-eol) js2-NAME)
  8278. (js2-get-token)
  8279. (setq label (js2-create-name-node)
  8280. end (js2-node-end label)
  8281. ;; matchJumpLabelName only matches if there is one
  8282. labels (js2-match-jump-label-name (js2-current-token-string))))
  8283. (cond
  8284. ((null labels) ; no current label to go to
  8285. (if (null js2-loop-set) ; no loop to continue to
  8286. (js2-report-error "msg.continue.outside" nil pos
  8287. (length "continue"))
  8288. (setq target (car js2-loop-set)))) ; innermost enclosing loop
  8289. (t
  8290. (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
  8291. (setq target (js2-labeled-stmt-node-stmt labels))
  8292. (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
  8293. (setq pn (make-js2-continue-node :pos pos
  8294. :len (- end pos)
  8295. :label label
  8296. :target target))
  8297. (js2-node-add-children pn label) ; but not target - it's not our child
  8298. pn))
  8299. (defun js2-parse-with ()
  8300. "Parser for with-statement. Last matched token must be js2-WITH."
  8301. (when js2-in-use-strict-directive
  8302. (js2-report-error "msg.no.with.strict"))
  8303. (let ((pos (js2-current-token-beg))
  8304. obj body pn lp rp)
  8305. (if (js2-must-match js2-LP "msg.no.paren.with")
  8306. (setq lp (js2-current-token-beg)))
  8307. (setq obj (js2-parse-expr))
  8308. (if (js2-must-match js2-RP "msg.no.paren.after.with")
  8309. (setq rp (js2-current-token-beg)))
  8310. (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
  8311. (setq body (js2-parse-statement)))
  8312. (setq pn (make-js2-with-node :pos pos
  8313. :len (- (js2-node-end body) pos)
  8314. :object obj
  8315. :body body
  8316. :lp (js2-relpos lp pos)
  8317. :rp (js2-relpos rp pos)))
  8318. (js2-node-add-children pn obj body)
  8319. pn))
  8320. (defun js2-parse-const-var ()
  8321. "Parser for var- or const-statement.
  8322. Last matched token must be js2-CONST or js2-VAR."
  8323. (let ((tt (js2-current-token-type))
  8324. (pos (js2-current-token-beg))
  8325. expr pn)
  8326. (setq expr (js2-parse-variables tt (js2-current-token-beg))
  8327. pn (make-js2-expr-stmt-node :pos pos
  8328. :len (- (js2-node-end expr) pos)
  8329. :expr expr))
  8330. (js2-node-add-children pn expr)
  8331. pn))
  8332. (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
  8333. (let ((pn (make-js2-expr-stmt-node :pos pos
  8334. :len (js2-node-len expr)
  8335. :type (if (js2-inside-function)
  8336. js2-EXPR_VOID
  8337. js2-EXPR_RESULT)
  8338. :expr expr)))
  8339. (if add-child
  8340. (js2-node-add-children pn expr))
  8341. pn))
  8342. (defun js2-parse-let-stmt ()
  8343. "Parser for let-statement. Last matched token must be js2-LET."
  8344. (let ((pos (js2-current-token-beg))
  8345. expr pn)
  8346. (if (= (js2-peek-token) js2-LP)
  8347. ;; let expression in statement context
  8348. (setq expr (js2-parse-let pos 'statement)
  8349. pn (js2-wrap-with-expr-stmt pos expr t))
  8350. ;; else we're looking at a statement like let x=6, y=7;
  8351. (setf expr (js2-parse-variables js2-LET pos)
  8352. pn (js2-wrap-with-expr-stmt pos expr t)
  8353. (js2-node-type pn) js2-EXPR_RESULT))
  8354. pn))
  8355. (defun js2-parse-ret-yield ()
  8356. (js2-parse-return-or-yield (js2-current-token-type) nil))
  8357. (defconst js2-parse-return-stmt-enders
  8358. (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP))
  8359. (defsubst js2-now-all-set (before after mask)
  8360. "Return whether or not the bits in the mask have changed to all set.
  8361. BEFORE is bits before change, AFTER is bits after change, and MASK is
  8362. the mask for bits. Returns t if all the bits in the mask are set in AFTER
  8363. but not BEFORE."
  8364. (and (/= (logand before mask) mask)
  8365. (= (logand after mask) mask)))
  8366. (defun js2-parse-return-or-yield (tt expr-context)
  8367. (let* ((pos (js2-current-token-beg))
  8368. (end (js2-current-token-end))
  8369. (before js2-end-flags)
  8370. (inside-function (js2-inside-function))
  8371. (gen-type (and inside-function (js2-function-node-generator-type
  8372. js2-current-script-or-fn)))
  8373. e ret name yield-star-p)
  8374. (unless inside-function
  8375. (js2-report-error (if (eq tt js2-RETURN)
  8376. "msg.bad.return"
  8377. "msg.bad.yield")))
  8378. (when (and inside-function
  8379. (eq gen-type 'STAR)
  8380. (js2-match-token js2-MUL))
  8381. (setq yield-star-p t))
  8382. ;; This is ugly, but we don't want to require a semicolon.
  8383. (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
  8384. (setq e (if (eq gen-type 'STAR)
  8385. (js2-parse-assign-expr)
  8386. (js2-parse-expr))
  8387. end (js2-node-end e)))
  8388. (cond
  8389. ((eq tt js2-RETURN)
  8390. (js2-set-flag js2-end-flags (if (null e)
  8391. js2-end-returns
  8392. js2-end-returns-value))
  8393. (setq ret (make-js2-return-node :pos pos
  8394. :len (- end pos)
  8395. :retval e))
  8396. (js2-node-add-children ret e)
  8397. ;; See if we need a strict mode warning.
  8398. ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
  8399. ;; more thorough and accurate than this before/after flag check.
  8400. ;; E.g. if there's a finally-block that always returns, we shouldn't
  8401. ;; show a warning generated by inconsistent returns in the catch blocks.
  8402. ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
  8403. ;; so we know which returns/yields to highlight, and we should get rid of
  8404. ;; all the checking in `js2-parse-return-or-yield'.
  8405. (if (and js2-strict-inconsistent-return-warning
  8406. (js2-now-all-set before js2-end-flags
  8407. (logior js2-end-returns js2-end-returns-value)))
  8408. (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
  8409. ((eq gen-type 'COMPREHENSION)
  8410. ;; FIXME: We should probably switch to saving and using lastYieldOffset,
  8411. ;; like SpiderMonkey does.
  8412. (js2-report-error "msg.syntax" nil pos 5))
  8413. (t
  8414. (setq ret (make-js2-yield-node :pos pos
  8415. :len (- end pos)
  8416. :value e
  8417. :star-p yield-star-p))
  8418. (js2-node-add-children ret e)
  8419. (unless expr-context
  8420. (setq e ret
  8421. ret (js2-wrap-with-expr-stmt pos e t))
  8422. (js2-set-requires-activation)
  8423. (js2-set-is-generator))))
  8424. ;; see if we are mixing yields and value returns.
  8425. (when (and inside-function
  8426. (js2-flag-set-p js2-end-flags js2-end-returns-value)
  8427. (eq (js2-function-node-generator-type js2-current-script-or-fn)
  8428. 'LEGACY))
  8429. (setq name (js2-function-name js2-current-script-or-fn))
  8430. (if (zerop (length name))
  8431. (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
  8432. (js2-report-error "msg.generator.returns" name pos (- end pos))))
  8433. ret))
  8434. (defun js2-parse-debugger ()
  8435. (make-js2-keyword-node :type js2-DEBUGGER))
  8436. (defun js2-parse-block ()
  8437. "Parser for a curly-delimited statement block.
  8438. Last token matched must be `js2-LC'."
  8439. (let ((pos (js2-current-token-beg))
  8440. (pn (make-js2-scope)))
  8441. (js2-push-scope pn)
  8442. (unwind-protect
  8443. (progn
  8444. (js2-parse-statements pn)
  8445. (js2-must-match js2-RC "msg.no.brace.block")
  8446. (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
  8447. (js2-pop-scope))
  8448. pn))
  8449. ;; For `js2-ERROR' too, to have a node for error recovery to work on.
  8450. (defun js2-parse-semi ()
  8451. "Parse a statement or handle an error.
  8452. Current token type is `js2-SEMI' or `js2-ERROR'."
  8453. (let ((tt (js2-current-token-type)) pos len)
  8454. (if (eq tt js2-SEMI)
  8455. (make-js2-empty-expr-node :len 1)
  8456. (setq pos (js2-current-token-beg)
  8457. len (- (js2-current-token-end) pos))
  8458. (js2-report-error "msg.syntax" nil pos len)
  8459. (make-js2-error-node :pos pos :len len))))
  8460. (defun js2-parse-default-xml-namespace ()
  8461. "Parse a `default xml namespace = <expr>' e4x statement."
  8462. (let ((pos (js2-current-token-beg))
  8463. end len expr unary)
  8464. (js2-must-have-xml)
  8465. (js2-set-requires-activation)
  8466. (setq len (- js2-ts-cursor pos))
  8467. (unless (and (js2-match-token js2-NAME)
  8468. (string= (js2-current-token-string) "xml"))
  8469. (js2-report-error "msg.bad.namespace" nil pos len))
  8470. (unless (and (js2-match-token js2-NAME)
  8471. (string= (js2-current-token-string) "namespace"))
  8472. (js2-report-error "msg.bad.namespace" nil pos len))
  8473. (unless (js2-match-token js2-ASSIGN)
  8474. (js2-report-error "msg.bad.namespace" nil pos len))
  8475. (setq expr (js2-parse-expr)
  8476. end (js2-node-end expr)
  8477. unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
  8478. :pos pos
  8479. :len (- end pos)
  8480. :operand expr))
  8481. (js2-node-add-children unary expr)
  8482. (make-js2-expr-stmt-node :pos pos
  8483. :len (- end pos)
  8484. :expr unary)))
  8485. (defun js2-record-label (label bundle)
  8486. ;; current token should be colon that `js2-parse-primary-expr' left untouched
  8487. (js2-get-token)
  8488. (let ((name (js2-label-node-name label))
  8489. labeled-stmt
  8490. dup)
  8491. (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
  8492. ;; flag both labels if possible when used in editing mode
  8493. (if (and js2-parse-ide-mode
  8494. (setq dup (js2-get-label-by-name labeled-stmt name)))
  8495. (js2-report-error "msg.dup.label" nil
  8496. (js2-node-abs-pos dup) (js2-node-len dup)))
  8497. (js2-report-error "msg.dup.label" nil
  8498. (js2-node-pos label) (js2-node-len label)))
  8499. (js2-labeled-stmt-node-add-label bundle label)
  8500. (js2-node-add-children bundle label)
  8501. ;; Add one reference to the bundle per label in `js2-label-set'
  8502. (push (cons name bundle) js2-label-set)))
  8503. (defun js2-parse-name-or-label ()
  8504. "Parser for identifier or label. Last token matched must be js2-NAME.
  8505. Called when we found a name in a statement context. If it's a label, we gather
  8506. up any following labels and the next non-label statement into a
  8507. `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
  8508. expression and return it wrapped in a `js2-expr-stmt-node'."
  8509. (let ((pos (js2-current-token-beg))
  8510. expr stmt bundle
  8511. (continue t))
  8512. ;; set check for label and call down to `js2-parse-primary-expr'
  8513. (setq expr (js2-maybe-parse-label))
  8514. (if (null expr)
  8515. ;; Parse the non-label expression and wrap with expression stmt.
  8516. (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
  8517. ;; else parsed a label
  8518. (setq bundle (make-js2-labeled-stmt-node :pos pos))
  8519. (js2-record-label expr bundle)
  8520. ;; look for more labels
  8521. (while (and continue (= (js2-get-token) js2-NAME))
  8522. (if (setq expr (js2-maybe-parse-label))
  8523. (js2-record-label expr bundle)
  8524. (setq expr (js2-parse-expr)
  8525. stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
  8526. continue nil)
  8527. (js2-auto-insert-semicolon stmt)))
  8528. ;; no more labels; now parse the labeled statement
  8529. (unwind-protect
  8530. (unless stmt
  8531. (let ((js2-labeled-stmt bundle)) ; bind dynamically
  8532. (js2-unget-token)
  8533. (setq stmt (js2-statement-helper))))
  8534. ;; remove the labels for this statement from the global set
  8535. (dolist (label (js2-labeled-stmt-node-labels bundle))
  8536. (setq js2-label-set (remove label js2-label-set))))
  8537. (setf (js2-labeled-stmt-node-stmt bundle) stmt
  8538. (js2-node-len bundle) (- (js2-node-end stmt) pos))
  8539. (js2-node-add-children bundle stmt)
  8540. bundle)))
  8541. (defun js2-maybe-parse-label ()
  8542. (cl-assert (= (js2-current-token-type) js2-NAME))
  8543. (let (label-pos
  8544. (next-tt (js2-get-token))
  8545. (label-end (js2-current-token-end)))
  8546. ;; Do not consume colon, it is used as unwind indicator
  8547. ;; to return to statementHelper.
  8548. (js2-unget-token)
  8549. (if (= next-tt js2-COLON)
  8550. (prog2
  8551. (setq label-pos (js2-current-token-beg))
  8552. (make-js2-label-node :pos label-pos
  8553. :len (- label-end label-pos)
  8554. :name (js2-current-token-string))
  8555. (js2-set-face label-pos
  8556. label-end
  8557. 'font-lock-variable-name-face 'record))
  8558. ;; Backtrack from the name token, too.
  8559. (js2-unget-token)
  8560. nil)))
  8561. (defun js2-parse-expr-stmt ()
  8562. "Default parser in statement context, if no recognized statement found."
  8563. (js2-wrap-with-expr-stmt (js2-current-token-beg)
  8564. (progn
  8565. (js2-unget-token)
  8566. (js2-parse-expr)) t))
  8567. (defun js2-parse-variables (decl-type pos)
  8568. "Parse a comma-separated list of variable declarations.
  8569. Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
  8570. DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
  8571. For 'var' or 'const', the keyword should be the token last scanned.
  8572. POS is the position where the node should start. It's sometimes the
  8573. var/const/let keyword, and other times the beginning of the first token
  8574. in the first variable declaration.
  8575. Returns the parsed `js2-var-decl-node' expression node."
  8576. (let* ((result (make-js2-var-decl-node :decl-type decl-type
  8577. :pos pos))
  8578. destructuring kid-pos tt init name end nbeg nend vi
  8579. (continue t))
  8580. ;; Example:
  8581. ;; var foo = {a: 1, b: 2}, bar = [3, 4];
  8582. ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
  8583. ;; var {a, b} = baz;
  8584. (while continue
  8585. (setq destructuring nil
  8586. name nil
  8587. tt (js2-get-token)
  8588. kid-pos (js2-current-token-beg)
  8589. end (js2-current-token-end)
  8590. init nil)
  8591. (if (or (= tt js2-LB) (= tt js2-LC))
  8592. ;; Destructuring assignment, e.g., var [a, b] = ...
  8593. (setq destructuring (js2-parse-destruct-primary-expr)
  8594. end (js2-node-end destructuring))
  8595. ;; Simple variable name
  8596. (js2-unget-token)
  8597. (when (js2-must-match-name "msg.bad.var")
  8598. (setq name (js2-create-name-node)
  8599. nbeg (js2-current-token-beg)
  8600. nend (js2-current-token-end)
  8601. end nend)
  8602. (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)
  8603. (js2-check-strict-identifier name)))
  8604. (when (js2-match-token js2-ASSIGN)
  8605. (setq init (js2-parse-assign-expr)
  8606. end (js2-node-end init))
  8607. (js2-record-imenu-functions init name))
  8608. (when name
  8609. (js2-set-face nbeg nend (if (js2-function-node-p init)
  8610. 'font-lock-function-name-face
  8611. 'font-lock-variable-name-face)
  8612. 'record))
  8613. (setq vi (make-js2-var-init-node :pos kid-pos
  8614. :len (- end kid-pos)
  8615. :type decl-type))
  8616. (if destructuring
  8617. (progn
  8618. (if (and (null init) (not js2-in-for-init))
  8619. (js2-report-error "msg.destruct.assign.no.init"))
  8620. (js2-define-destruct-symbols destructuring
  8621. decl-type
  8622. 'font-lock-variable-name-face)
  8623. (setf (js2-var-init-node-target vi) destructuring))
  8624. (setf (js2-var-init-node-target vi) name))
  8625. (setf (js2-var-init-node-initializer vi) init)
  8626. (js2-node-add-children vi name destructuring init)
  8627. (js2-block-node-push result vi)
  8628. (unless (js2-match-token js2-COMMA)
  8629. (setq continue nil)))
  8630. (setf (js2-node-len result) (- end pos))
  8631. result))
  8632. (defun js2-parse-let (pos &optional stmt-p)
  8633. "Parse a let expression or statement.
  8634. A let-expression is of the form `let (vars) expr'.
  8635. A let-statement is of the form `let (vars) {statements}'.
  8636. The third form of let is a variable declaration list, handled
  8637. by `js2-parse-variables'."
  8638. (let ((pn (make-js2-let-node :pos pos))
  8639. beg vars body)
  8640. (if (js2-must-match js2-LP "msg.no.paren.after.let")
  8641. (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
  8642. (js2-push-scope pn)
  8643. (unwind-protect
  8644. (progn
  8645. (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
  8646. (if (js2-must-match js2-RP "msg.no.paren.let")
  8647. (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
  8648. (if (and stmt-p (js2-match-token js2-LC))
  8649. ;; let statement
  8650. (progn
  8651. (setf beg (js2-current-token-beg) ; position stmt at LC
  8652. body (js2-parse-statements))
  8653. (js2-must-match js2-RC "msg.no.curly.let")
  8654. (setf (js2-node-len body) (- (js2-current-token-end) beg)
  8655. (js2-node-len pn) (- (js2-current-token-end) pos)
  8656. (js2-let-node-body pn) body
  8657. (js2-node-type pn) js2-LET))
  8658. ;; let expression
  8659. (setf body (js2-parse-expr)
  8660. (js2-node-len pn) (- (js2-node-end body) pos)
  8661. (js2-let-node-body pn) body))
  8662. (setf (js2-let-node-vars pn) vars)
  8663. (js2-node-add-children pn vars body))
  8664. (js2-pop-scope))
  8665. pn))
  8666. (defun js2-define-new-symbol (decl-type name node &optional scope)
  8667. (js2-scope-put-symbol (or scope js2-current-scope)
  8668. name
  8669. (make-js2-symbol decl-type name node)))
  8670. (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
  8671. "Define a symbol in the current scope.
  8672. If NODE is non-nil, it is the AST node associated with the symbol."
  8673. (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
  8674. (symbol (if defining-scope
  8675. (js2-scope-get-symbol defining-scope name)))
  8676. (sdt (if symbol (js2-symbol-decl-type symbol) -1))
  8677. (pos (if node (js2-node-abs-pos node)))
  8678. (len (if node (js2-node-len node))))
  8679. (cond
  8680. ((and symbol ; already defined in this block
  8681. (or (= sdt js2-LET)
  8682. (= sdt js2-CONST))
  8683. (eq defining-scope js2-current-scope))
  8684. (js2-report-error
  8685. (cond
  8686. ((= sdt js2-CONST) "msg.const.redecl")
  8687. ((= sdt js2-LET) "msg.let.redecl")
  8688. ((= sdt js2-VAR) "msg.var.redecl")
  8689. ((= sdt js2-FUNCTION) "msg.function.redecl")
  8690. (t "msg.parm.redecl"))
  8691. name pos len))
  8692. ((or (= decl-type js2-LET)
  8693. (= decl-type js2-CONST))
  8694. (if (and (= decl-type js2-LET)
  8695. (not ignore-not-in-block)
  8696. (or (= (js2-node-type js2-current-scope) js2-IF)
  8697. (js2-loop-node-p js2-current-scope)))
  8698. (js2-report-error "msg.let.decl.not.in.block")
  8699. (js2-define-new-symbol decl-type name node)))
  8700. ((or (= decl-type js2-VAR)
  8701. (= decl-type js2-FUNCTION))
  8702. (if symbol
  8703. (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
  8704. (js2-add-strict-warning "msg.var.redecl" name)
  8705. (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
  8706. (js2-add-strict-warning "msg.var.hides.arg" name)))
  8707. (js2-define-new-symbol decl-type name node
  8708. js2-current-script-or-fn)))
  8709. ((= decl-type js2-LP)
  8710. (if symbol
  8711. ;; must be duplicate parameter. Second parameter hides the
  8712. ;; first, so go ahead and add the second pararameter
  8713. (js2-report-warning "msg.dup.parms" name))
  8714. (js2-define-new-symbol decl-type name node))
  8715. (t (js2-code-bug)))))
  8716. (defun js2-parse-paren-expr-or-generator-comp ()
  8717. (let ((px-pos (js2-current-token-beg)))
  8718. (cond
  8719. ((and (>= js2-language-version 200)
  8720. (js2-match-token js2-FOR))
  8721. (js2-parse-generator-comp px-pos))
  8722. ((and (>= js2-language-version 200)
  8723. (js2-match-token js2-RP))
  8724. ;; Not valid expression syntax, but this is valid in an arrow
  8725. ;; function with no params: () => body.
  8726. (if (eq (js2-peek-token) js2-ARROW)
  8727. ;; Return whatever, it will hopefully be rewinded and
  8728. ;; reparsed when we reach the =>.
  8729. (make-js2-keyword-node :type js2-NULL)
  8730. (js2-report-error "msg.syntax")
  8731. (make-js2-error-node)))
  8732. (t
  8733. (let* ((js2-in-for-init nil)
  8734. (expr (js2-parse-expr))
  8735. (pn (make-js2-paren-node :pos px-pos
  8736. :expr expr)))
  8737. (js2-node-add-children pn (js2-paren-node-expr pn))
  8738. (js2-must-match js2-RP "msg.no.paren")
  8739. (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
  8740. pn)))))
  8741. (defun js2-parse-expr (&optional oneshot)
  8742. (let* ((pn (js2-parse-assign-expr))
  8743. (pos (js2-node-pos pn))
  8744. left
  8745. right
  8746. op-pos)
  8747. (while (and (not oneshot)
  8748. (js2-match-token js2-COMMA))
  8749. (setq op-pos (- (js2-current-token-beg) pos)) ; relative
  8750. (setq right (js2-parse-assign-expr)
  8751. left pn
  8752. pn (make-js2-infix-node :type js2-COMMA
  8753. :pos pos
  8754. :len (- js2-ts-cursor pos)
  8755. :op-pos op-pos
  8756. :left left
  8757. :right right))
  8758. (js2-node-add-children pn left right))
  8759. pn))
  8760. (defun js2-parse-assign-expr ()
  8761. (let ((tt (js2-get-token))
  8762. (pos (js2-current-token-beg))
  8763. pn left right op-pos
  8764. ts-state recorded-identifiers parsed-errors
  8765. async-p)
  8766. (if (= tt js2-YIELD)
  8767. (js2-parse-return-or-yield tt t)
  8768. ;; TODO(mooz): Bit confusing.
  8769. ;; If we meet `async` token and it's not part of `async
  8770. ;; function`, then this `async` is for a succeeding async arrow
  8771. ;; function.
  8772. ;; Since arrow function parsing doesn't rely on neither
  8773. ;; `js2-parse-function-stmt' nor `js2-parse-function-expr' that
  8774. ;; interpret `async` token, we trash `async` and just remember
  8775. ;; we met `async` keyword to `async-p'.
  8776. (when (js2-match-async-arrow-function)
  8777. (setq async-p t))
  8778. ;; Save the tokenizer state in case we find an arrow function
  8779. ;; and have to rewind.
  8780. (setq ts-state (make-js2-ts-state)
  8781. recorded-identifiers js2-recorded-identifiers
  8782. parsed-errors js2-parsed-errors)
  8783. ;; not yield - parse assignment expression
  8784. (setq pn (js2-parse-cond-expr)
  8785. tt (js2-get-token))
  8786. (cond
  8787. ((and (<= js2-first-assign tt)
  8788. (<= tt js2-last-assign))
  8789. ;; tt express assignment (=, |=, ^=, ..., %=)
  8790. (setq op-pos (- (js2-current-token-beg) pos) ; relative
  8791. left pn)
  8792. ;; The assigned node could be a js2-prop-get-node (foo.bar = 0), we only
  8793. ;; care about assignment to strict variable names.
  8794. (when (js2-name-node-p left)
  8795. (js2-check-strict-identifier left))
  8796. (setq right (js2-parse-assign-expr)
  8797. pn (make-js2-assign-node :type tt
  8798. :pos pos
  8799. :len (- (js2-node-end right) pos)
  8800. :op-pos op-pos
  8801. :left left
  8802. :right right))
  8803. (when js2-parse-ide-mode
  8804. (js2-highlight-assign-targets pn left right)
  8805. (js2-record-imenu-functions right left))
  8806. ;; do this last so ide checks above can use absolute positions
  8807. (js2-node-add-children pn left right))
  8808. ((and (>= js2-language-version 200)
  8809. (or
  8810. (= tt js2-ARROW)
  8811. (and async-p
  8812. (= (js2-peek-token) js2-ARROW))))
  8813. (js2-ts-seek ts-state)
  8814. (when async-p
  8815. (js2-record-face 'font-lock-keyword-face)
  8816. (js2-get-token))
  8817. (setq js2-recorded-identifiers recorded-identifiers
  8818. js2-parsed-errors parsed-errors)
  8819. (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil async-p)))
  8820. (t
  8821. (js2-unget-token)))
  8822. pn)))
  8823. (defun js2-parse-cond-expr ()
  8824. (let ((pos (js2-current-token-beg))
  8825. (pn (js2-parse-nullish-coalescing-expr))
  8826. test-expr
  8827. if-true
  8828. if-false
  8829. q-pos
  8830. c-pos)
  8831. (when (js2-match-token js2-HOOK)
  8832. (setq q-pos (- (js2-current-token-beg) pos)
  8833. if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
  8834. (js2-must-match js2-COLON "msg.no.colon.cond")
  8835. (setq c-pos (- (js2-current-token-beg) pos)
  8836. if-false (js2-parse-assign-expr)
  8837. test-expr pn
  8838. pn (make-js2-cond-node :pos pos
  8839. :len (- (js2-node-end if-false) pos)
  8840. :test-expr test-expr
  8841. :true-expr if-true
  8842. :false-expr if-false
  8843. :q-pos q-pos
  8844. :c-pos c-pos))
  8845. (js2-node-add-children pn test-expr if-true if-false))
  8846. pn))
  8847. (defun js2-make-binary (type left parser &optional no-get)
  8848. "Helper for constructing a binary-operator AST node.
  8849. LEFT is the left-side-expression, already parsed, and the
  8850. binary operator should have just been matched.
  8851. PARSER is a function to call to parse the right operand,
  8852. or a `js2-node' struct if it has already been parsed.
  8853. FIXME: The latter option is unused?"
  8854. (let* ((pos (js2-node-pos left))
  8855. (op-pos (- (js2-current-token-beg) pos))
  8856. (right (if (js2-node-p parser)
  8857. parser
  8858. (unless no-get (js2-get-token))
  8859. (funcall parser)))
  8860. (pn (make-js2-infix-node :type type
  8861. :pos pos
  8862. :len (- (js2-node-end right) pos)
  8863. :op-pos op-pos
  8864. :left left
  8865. :right right)))
  8866. (js2-node-add-children pn left right)
  8867. pn))
  8868. (defun js2-parse-or-expr ()
  8869. (let ((pn (js2-parse-and-expr)))
  8870. (when (js2-match-token js2-OR)
  8871. (setq pn (js2-make-binary js2-OR
  8872. pn
  8873. 'js2-parse-or-expr)))
  8874. pn))
  8875. (defun js2-parse-and-expr ()
  8876. (let ((pn (js2-parse-bit-or-expr)))
  8877. (when (js2-match-token js2-AND)
  8878. (setq pn (js2-make-binary js2-AND
  8879. pn
  8880. 'js2-parse-and-expr)))
  8881. pn))
  8882. (defun js2-parse-bit-or-expr ()
  8883. (let ((pn (js2-parse-bit-xor-expr)))
  8884. (while (js2-match-token js2-BITOR)
  8885. (setq pn (js2-make-binary js2-BITOR
  8886. pn
  8887. 'js2-parse-bit-xor-expr)))
  8888. pn))
  8889. (defun js2-parse-bit-xor-expr ()
  8890. (let ((pn (js2-parse-bit-and-expr)))
  8891. (while (js2-match-token js2-BITXOR)
  8892. (setq pn (js2-make-binary js2-BITXOR
  8893. pn
  8894. 'js2-parse-bit-and-expr)))
  8895. pn))
  8896. (defun js2-parse-bit-and-expr ()
  8897. (let ((pn (js2-parse-eq-expr)))
  8898. (while (js2-match-token js2-BITAND)
  8899. (setq pn (js2-make-binary js2-BITAND
  8900. pn
  8901. 'js2-parse-eq-expr)))
  8902. pn))
  8903. (defun js2-parse-nullish-coalescing-expr ()
  8904. (let ((pn (js2-parse-or-expr)))
  8905. (when (js2-match-token js2-NULLISH-COALESCING)
  8906. (setq pn (js2-make-binary js2-NULLISH-COALESCING
  8907. pn
  8908. 'js2-parse-nullish-coalescing-expr)))
  8909. pn))
  8910. (defconst js2-parse-eq-ops
  8911. (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
  8912. (defun js2-parse-eq-expr ()
  8913. (let ((pn (js2-parse-rel-expr))
  8914. tt)
  8915. (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
  8916. (setq pn (js2-make-binary tt
  8917. pn
  8918. 'js2-parse-rel-expr)))
  8919. (js2-unget-token)
  8920. pn))
  8921. (defconst js2-parse-rel-ops
  8922. (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
  8923. (defun js2-parse-rel-expr ()
  8924. (let ((pn (js2-parse-shift-expr))
  8925. (continue t)
  8926. tt)
  8927. (while continue
  8928. (setq tt (js2-get-token))
  8929. (cond
  8930. ((and js2-in-for-init (= tt js2-IN))
  8931. (js2-unget-token)
  8932. (setq continue nil))
  8933. ((memq tt js2-parse-rel-ops)
  8934. (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
  8935. (t
  8936. (js2-unget-token)
  8937. (setq continue nil))))
  8938. pn))
  8939. (defconst js2-parse-shift-ops
  8940. (list js2-LSH js2-URSH js2-RSH))
  8941. (defun js2-parse-shift-expr ()
  8942. (let ((pn (js2-parse-add-expr))
  8943. tt
  8944. (continue t))
  8945. (while continue
  8946. (setq tt (js2-get-token))
  8947. (if (memq tt js2-parse-shift-ops)
  8948. (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
  8949. (js2-unget-token)
  8950. (setq continue nil)))
  8951. pn))
  8952. (defun js2-parse-add-expr ()
  8953. (let ((pn (js2-parse-mul-expr))
  8954. tt
  8955. (continue t))
  8956. (while continue
  8957. (setq tt (js2-get-token))
  8958. (if (or (= tt js2-ADD) (= tt js2-SUB))
  8959. (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
  8960. (js2-unget-token)
  8961. (setq continue nil)))
  8962. pn))
  8963. (defconst js2-parse-mul-ops
  8964. (list js2-MUL js2-DIV js2-MOD))
  8965. (defun js2-parse-mul-expr ()
  8966. (let ((pn (js2-parse-expon-expr))
  8967. tt
  8968. (continue t))
  8969. (while continue
  8970. (setq tt (js2-get-token))
  8971. (if (memq tt js2-parse-mul-ops)
  8972. (setq pn (js2-make-binary tt pn 'js2-parse-expon-expr))
  8973. (js2-unget-token)
  8974. (setq continue nil)))
  8975. pn))
  8976. (defun js2-parse-expon-expr ()
  8977. (let ((pn (js2-parse-unary-expr)))
  8978. (when (>= js2-language-version 200)
  8979. (while (js2-match-token js2-EXPON)
  8980. (when (and (js2-unary-node-p pn)
  8981. (not (memq (js2-node-type pn) '(js2-INC js2-DEC))))
  8982. (js2-report-error "msg.syntax" nil
  8983. (js2-node-abs-pos pn) (js2-node-len pn)))
  8984. ;; Make it right-associative.
  8985. (setq pn (js2-make-binary js2-EXPON pn 'js2-parse-expon-expr))))
  8986. pn))
  8987. (defun js2-make-unary (beg type parser &rest args)
  8988. "Make a unary node starting at BEG of type TYPE.
  8989. If BEG is nil, `(js2-current-token-beg)' is used for the node
  8990. start position. PARSER is either a node (for postfix operators)
  8991. or a function to call to parse the operand (for prefix
  8992. operators)."
  8993. (let* ((pos (or beg (js2-current-token-beg)))
  8994. (postfix (js2-node-p parser))
  8995. (expr (if postfix
  8996. parser
  8997. (apply parser args)))
  8998. end
  8999. pn)
  9000. (if postfix ; e.g. i++
  9001. (setq pos (js2-node-pos expr)
  9002. end (js2-current-token-end))
  9003. (setq end (js2-node-end expr)))
  9004. (setq pn (make-js2-unary-node :type type
  9005. :pos pos
  9006. :len (- end pos)
  9007. :operand expr))
  9008. (js2-node-add-children pn expr)
  9009. pn))
  9010. (defconst js2-incrementable-node-types
  9011. (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
  9012. "Node types that can be the operand of a ++ or -- operator.")
  9013. (defun js2-check-bad-inc-dec (tt beg end unary)
  9014. (unless (memq (js2-node-type (js2-unary-node-operand unary))
  9015. js2-incrementable-node-types)
  9016. (js2-report-error (if (= tt js2-INC)
  9017. "msg.bad.incr"
  9018. "msg.bad.decr")
  9019. nil beg (- end beg))))
  9020. (defun js2-parse-unary-expr ()
  9021. (let ((tt (js2-current-token-type))
  9022. (beg (js2-current-token-beg)))
  9023. (cond
  9024. ((or (= tt js2-VOID)
  9025. (= tt js2-NOT)
  9026. (= tt js2-BITNOT)
  9027. (= tt js2-TYPEOF))
  9028. (js2-get-token)
  9029. (js2-make-unary beg tt 'js2-parse-unary-expr))
  9030. ((= tt js2-ADD)
  9031. (js2-get-token)
  9032. ;; Convert to special POS token in decompiler and parse tree
  9033. (js2-make-unary beg js2-POS 'js2-parse-unary-expr))
  9034. ((= tt js2-SUB)
  9035. (js2-get-token)
  9036. ;; Convert to special NEG token in decompiler and parse tree
  9037. (js2-make-unary beg js2-NEG 'js2-parse-unary-expr))
  9038. ((or (= tt js2-INC)
  9039. (= tt js2-DEC))
  9040. (js2-get-token)
  9041. (let ((beg2 (js2-current-token-beg))
  9042. (end (js2-current-token-end))
  9043. (expr (js2-make-unary beg tt 'js2-parse-member-expr t)))
  9044. (js2-check-bad-inc-dec tt beg2 end expr)
  9045. expr))
  9046. ((= tt js2-DELPROP)
  9047. (js2-get-token)
  9048. (js2-make-unary beg js2-DELPROP 'js2-parse-unary-expr))
  9049. ((js2-parse-await-maybe tt))
  9050. ((= tt js2-ERROR)
  9051. (js2-get-token)
  9052. (make-js2-error-node)) ; try to continue
  9053. ((and (= tt js2-LT)
  9054. js2-compiler-xml-available)
  9055. ;; XML stream encountered in expression.
  9056. (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
  9057. (t
  9058. (let ((pn (js2-parse-member-expr t))
  9059. ;; Don't look across a newline boundary for a postfix incop.
  9060. (tt (js2-peek-token-or-eol))
  9061. expr)
  9062. (when (or (= tt js2-INC) (= tt js2-DEC))
  9063. (js2-get-token)
  9064. (setf expr pn
  9065. pn (js2-make-unary (js2-node-pos expr) tt expr))
  9066. (js2-node-set-prop pn 'postfix t)
  9067. (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
  9068. pn)))))
  9069. (defun js2-parse-xml-initializer ()
  9070. "Parse an E4X XML initializer.
  9071. I'm parsing it the way Rhino parses it, but without the tree-rewriting.
  9072. Then I'll postprocess the result, depending on whether we're in IDE
  9073. mode or codegen mode, and generate the appropriate rewritten AST.
  9074. IDE mode uses a rich AST that models the XML structure. Codegen mode
  9075. just concatenates everything and makes a new XML or XMLList out of it."
  9076. (let ((tt (js2-get-first-xml-token))
  9077. pn-xml pn expr kids expr-pos
  9078. (continue t)
  9079. (first-token t))
  9080. (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
  9081. (js2-report-error "msg.syntax"))
  9082. (setq pn-xml (make-js2-xml-node))
  9083. (while continue
  9084. (if first-token
  9085. (setq first-token nil)
  9086. (setq tt (js2-get-next-xml-token)))
  9087. (cond
  9088. ;; js2-XML means we found a {expr} in the XML stream.
  9089. ;; The token string is the XML up to the left-curly.
  9090. ((= tt js2-XML)
  9091. (push (make-js2-string-node :pos (js2-current-token-beg)
  9092. :len (- js2-ts-cursor (js2-current-token-beg)))
  9093. kids)
  9094. (js2-must-match js2-LC "msg.syntax")
  9095. (setq expr-pos js2-ts-cursor
  9096. expr (if (eq (js2-peek-token) js2-RC)
  9097. (make-js2-empty-expr-node :pos expr-pos)
  9098. (js2-parse-expr)))
  9099. (js2-must-match js2-RC "msg.syntax")
  9100. (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
  9101. :len (js2-node-len expr)
  9102. :expr expr))
  9103. (js2-node-add-children pn expr)
  9104. (push pn kids))
  9105. ;; a js2-XMLEND token means we hit the final close-tag.
  9106. ((= tt js2-XMLEND)
  9107. (push (make-js2-string-node :pos (js2-current-token-beg)
  9108. :len (- js2-ts-cursor (js2-current-token-beg)))
  9109. kids)
  9110. (dolist (kid (nreverse kids))
  9111. (js2-block-node-push pn-xml kid))
  9112. (setf (js2-node-len pn-xml) (- js2-ts-cursor
  9113. (js2-node-pos pn-xml))
  9114. continue nil))
  9115. (t
  9116. (js2-report-error "msg.syntax")
  9117. (setq continue nil))))
  9118. pn-xml))
  9119. (defun js2-parse-argument-list ()
  9120. "Parse an argument list and return it as a Lisp list of nodes.
  9121. Returns the list in reverse order. Consumes the right-paren token."
  9122. (let (result)
  9123. (unless (js2-match-token js2-RP)
  9124. (cl-loop do
  9125. (let ((tt (js2-get-token))
  9126. (beg (js2-current-token-beg)))
  9127. (if (and (= tt js2-TRIPLEDOT)
  9128. (>= js2-language-version 200))
  9129. (push (js2-make-unary beg tt 'js2-parse-assign-expr) result)
  9130. (js2-unget-token)
  9131. (push (js2-parse-assign-expr) result)))
  9132. while
  9133. (and (js2-match-token js2-COMMA)
  9134. (or (< js2-language-version 200)
  9135. (not (= js2-RP (js2-peek-token))))))
  9136. (js2-must-match js2-RP "msg.no.paren.arg")
  9137. result)))
  9138. (defun js2-parse-member-expr (&optional allow-call-syntax)
  9139. (let ((tt (js2-current-token-type))
  9140. pn pos target args beg end init)
  9141. (if (/= tt js2-NEW)
  9142. (setq pn (js2-parse-primary-expr))
  9143. ;; parse a 'new' expression
  9144. (js2-get-token)
  9145. (setq pos (js2-current-token-beg)
  9146. beg pos
  9147. target (js2-parse-member-expr)
  9148. end (js2-node-end target)
  9149. pn (make-js2-new-node :pos pos
  9150. :target target
  9151. :len (- end pos)))
  9152. (js2-highlight-function-call (js2-current-token))
  9153. (js2-node-add-children pn target)
  9154. (when (js2-match-token js2-LP)
  9155. ;; Add the arguments to pn, if any are supplied.
  9156. (setf beg pos ; start of "new" keyword
  9157. pos (js2-current-token-beg)
  9158. args (nreverse (js2-parse-argument-list))
  9159. (js2-new-node-args pn) args
  9160. end (js2-current-token-end)
  9161. (js2-new-node-lp pn) (- pos beg)
  9162. (js2-new-node-rp pn) (- end 1 beg))
  9163. (apply #'js2-node-add-children pn args))
  9164. (when (and js2-allow-rhino-new-expr-initializer
  9165. (js2-match-token js2-LC))
  9166. (setf init (js2-parse-object-literal)
  9167. end (js2-node-end init)
  9168. (js2-new-node-initializer pn) init)
  9169. (js2-node-add-children pn init))
  9170. (setf (js2-node-len pn) (- end beg))) ; end outer if
  9171. (js2-parse-member-expr-tail allow-call-syntax pn)))
  9172. (defun js2-parse-optional-chaining-operator (allow-call-syntax pn)
  9173. (let ((tt (js2-peek-token)))
  9174. (cond
  9175. ((eq tt js2-NAME)
  9176. (setq pn (js2-parse-property-access js2-DOT pn)))
  9177. ((eq tt js2-LB)
  9178. ;; skip left bracket token
  9179. (js2-get-token)
  9180. (setq pn (js2-parse-element-get pn)))
  9181. ((and (eq tt js2-LP) allow-call-syntax)
  9182. ;; unget optional chaining operator
  9183. ;; so current token is function name and could be highlighted
  9184. (js2-unget-token)
  9185. (setq pn (js2-parse-function-call pn t)))
  9186. (t
  9187. (js2-report-error "msg.bad.optional.chaining")))
  9188. pn))
  9189. (defun js2-parse-member-expr-tail (allow-call-syntax pn)
  9190. "Parse a chain of property/array accesses or function calls.
  9191. Includes parsing for E4X operators like `..' and `.@'.
  9192. If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
  9193. Returns an expression tree that includes PN, the parent node."
  9194. (let (tt
  9195. (continue t))
  9196. (while continue
  9197. (setq tt (js2-get-token))
  9198. (cond
  9199. ((or (= tt js2-DOT) (= tt js2-DOTDOT))
  9200. (setq pn (js2-parse-property-access tt pn)))
  9201. ((= tt js2-OPTIONAL-CHAINING)
  9202. (setq pn (js2-parse-optional-chaining-operator allow-call-syntax pn))
  9203. (unless pn (setq continue nil)))
  9204. ((= tt js2-DOTQUERY)
  9205. (setq pn (js2-parse-dot-query pn)))
  9206. ((= tt js2-LB)
  9207. (setq pn (js2-parse-element-get pn)))
  9208. ((= tt js2-LP)
  9209. (js2-unget-token)
  9210. (if allow-call-syntax
  9211. (setq pn (js2-parse-function-call pn))
  9212. (setq continue nil)))
  9213. ((= tt js2-TEMPLATE_HEAD)
  9214. (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
  9215. ((= tt js2-NO_SUBS_TEMPLATE)
  9216. (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
  9217. (t
  9218. (js2-unget-token)
  9219. (setq continue nil)))
  9220. (if (>= js2-highlight-level 2)
  9221. (js2-parse-highlight-member-expr-node pn)))
  9222. pn))
  9223. (defun js2-parse-tagged-template (tag-node tpl-node)
  9224. "Parse tagged template expression."
  9225. (let* ((pos (js2-node-pos tag-node))
  9226. (pn (make-js2-tagged-template-node :pos pos
  9227. :len (- (js2-current-token-end) pos)
  9228. :tag tag-node
  9229. :template tpl-node)))
  9230. (js2-node-add-children pn tag-node tpl-node)
  9231. pn))
  9232. (defun js2-parse-dot-query (pn)
  9233. "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
  9234. Last token parsed must be `js2-DOTQUERY'."
  9235. (let ((pos (js2-node-pos pn))
  9236. op-pos expr end)
  9237. (js2-must-have-xml)
  9238. (js2-set-requires-activation)
  9239. (setq op-pos (js2-current-token-beg)
  9240. expr (js2-parse-expr)
  9241. end (js2-node-end expr)
  9242. pn (make-js2-xml-dot-query-node :left pn
  9243. :pos pos
  9244. :op-pos op-pos
  9245. :right expr))
  9246. (js2-node-add-children pn
  9247. (js2-xml-dot-query-node-left pn)
  9248. (js2-xml-dot-query-node-right pn))
  9249. (if (js2-must-match js2-RP "msg.no.paren")
  9250. (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
  9251. end (js2-current-token-end)))
  9252. (setf (js2-node-len pn) (- end pos))
  9253. pn))
  9254. (defun js2-parse-element-get (pn)
  9255. "Parse an element-get expression, e.g. foo[bar].
  9256. Last token parsed must be `js2-RB'."
  9257. (let ((lb (js2-current-token-beg))
  9258. (pos (js2-node-pos pn))
  9259. rb expr)
  9260. (setq expr (js2-parse-expr))
  9261. (if (js2-must-match js2-RB "msg.no.bracket.index")
  9262. (setq rb (js2-current-token-beg)))
  9263. (setq pn (make-js2-elem-get-node :target pn
  9264. :pos pos
  9265. :element expr
  9266. :lb (js2-relpos lb pos)
  9267. :rb (js2-relpos rb pos)
  9268. :len (- (js2-current-token-end) pos)))
  9269. (js2-node-add-children pn
  9270. (js2-elem-get-node-target pn)
  9271. (js2-elem-get-node-element pn))
  9272. pn))
  9273. (defun js2-highlight-function-call (token)
  9274. (when (eq (js2-token-type token) js2-NAME)
  9275. (js2-record-face 'js2-function-call token)))
  9276. (defun js2-parse-function-call (pn &optional use-optional-chaining-p)
  9277. (js2-highlight-function-call (js2-current-token))
  9278. (js2-get-token)
  9279. (let (args
  9280. (pos (js2-node-pos pn)))
  9281. (when use-optional-chaining-p
  9282. ;; skip optional chaining operator
  9283. (js2-get-token))
  9284. (setq pn (make-js2-call-node :pos pos
  9285. :target pn
  9286. :lp (- (js2-current-token-beg) pos)))
  9287. (js2-node-add-children pn (js2-call-node-target pn))
  9288. ;; Add the arguments to pn, if any are supplied.
  9289. (setf args (nreverse (js2-parse-argument-list))
  9290. (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
  9291. (js2-call-node-args pn) args)
  9292. (apply #'js2-node-add-children pn args)
  9293. (setf (js2-node-len pn) (- js2-ts-cursor pos))
  9294. pn))
  9295. (defun js2-parse-property-access (tt pn)
  9296. "Parse a property access, XML descendants access, or XML attr access."
  9297. (let ((member-type-flags 0)
  9298. (dot-pos (js2-current-token-beg))
  9299. (dot-len (if (= tt js2-DOTDOT) 2 1))
  9300. name
  9301. ref ; right side of . or .. operator
  9302. result)
  9303. (when (= tt js2-DOTDOT)
  9304. (js2-must-have-xml)
  9305. (setq member-type-flags js2-descendants-flag))
  9306. (if (not js2-compiler-xml-available)
  9307. (progn
  9308. (js2-must-match-prop-name "msg.no.name.after.dot")
  9309. (setq name (js2-create-name-node t js2-GETPROP)
  9310. result (make-js2-prop-get-node :left pn
  9311. :pos (js2-current-token-beg)
  9312. :right name
  9313. :len (js2-current-token-len)))
  9314. (js2-node-add-children result pn name)
  9315. result)
  9316. ;; otherwise look for XML operators
  9317. (setf result (if (= tt js2-DOT)
  9318. (make-js2-prop-get-node)
  9319. (make-js2-infix-node :type js2-DOTDOT))
  9320. (js2-node-pos result) (js2-node-pos pn)
  9321. (js2-infix-node-op-pos result) dot-pos
  9322. (js2-infix-node-left result) pn ; do this after setting position
  9323. tt (js2-get-prop-name-token))
  9324. (cond
  9325. ;; handles: name, ns::name, ns::*, ns::[expr]
  9326. ((= tt js2-NAME)
  9327. (setq ref (js2-parse-property-name -1 nil member-type-flags)))
  9328. ;; handles: *, *::name, *::*, *::[expr]
  9329. ((= tt js2-MUL)
  9330. (setq ref (js2-parse-property-name nil "*" member-type-flags)))
  9331. ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
  9332. ((= tt js2-XMLATTR)
  9333. (setq result (js2-parse-attribute-access)))
  9334. (t
  9335. (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
  9336. (if ref
  9337. (setf (js2-node-len result) (- (js2-node-end ref)
  9338. (js2-node-pos result))
  9339. (js2-infix-node-right result) ref))
  9340. (if (js2-infix-node-p result)
  9341. (js2-node-add-children result
  9342. (js2-infix-node-left result)
  9343. (js2-infix-node-right result)))
  9344. result)))
  9345. (defun js2-parse-attribute-access ()
  9346. "Parse an E4X XML attribute expression.
  9347. This includes expressions of the forms:
  9348. @attr @ns::attr @ns::*
  9349. @* @*::attr @*::*
  9350. @[expr] @*::[expr] @ns::[expr]
  9351. Called if we peeked an '@' token."
  9352. (let ((tt (js2-get-prop-name-token))
  9353. (at-pos (js2-current-token-beg)))
  9354. (cond
  9355. ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
  9356. ((= tt js2-NAME)
  9357. (js2-parse-property-name at-pos nil 0))
  9358. ;; handles: @*, @*::name, @*::*, @*::[expr]
  9359. ((= tt js2-MUL)
  9360. (js2-parse-property-name (js2-current-token-beg) "*" 0))
  9361. ;; handles @[expr]
  9362. ((= tt js2-LB)
  9363. (js2-parse-xml-elem-ref at-pos))
  9364. (t
  9365. (js2-report-error "msg.no.name.after.xmlAttr")
  9366. ;; Avoid cascaded errors that happen if we make an error node here.
  9367. (js2-parse-property-name (js2-current-token-beg) "" 0)))))
  9368. (defun js2-parse-property-name (at-pos s member-type-flags)
  9369. "Check if :: follows name in which case it becomes qualified name.
  9370. AT-POS is a natural number if we just read an '@' token, else nil.
  9371. S is the name or string that was matched: an identifier, 'throw' or '*'.
  9372. MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
  9373. Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
  9374. operator, or the name is followed by ::. For a plain name, returns a
  9375. `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
  9376. (let ((pos (or at-pos (js2-current-token-beg)))
  9377. colon-pos
  9378. (name (js2-create-name-node t (js2-current-token-type) s))
  9379. ns tt pn)
  9380. (catch 'return
  9381. (when (js2-match-token js2-COLONCOLON)
  9382. (setq ns name
  9383. colon-pos (js2-current-token-beg)
  9384. tt (js2-get-prop-name-token))
  9385. (cond
  9386. ;; handles name::name
  9387. ((= tt js2-NAME)
  9388. (setq name (js2-create-name-node)))
  9389. ;; handles name::*
  9390. ((= tt js2-MUL)
  9391. (setq name (js2-create-name-node nil nil "*")))
  9392. ;; handles name::[expr]
  9393. ((= tt js2-LB)
  9394. (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
  9395. (t
  9396. (js2-report-error "msg.no.name.after.coloncolon"))))
  9397. (if (and (null ns) (zerop member-type-flags))
  9398. name
  9399. (prog1
  9400. (setq pn
  9401. (make-js2-xml-prop-ref-node :pos pos
  9402. :len (- (js2-node-end name) pos)
  9403. :at-pos at-pos
  9404. :colon-pos colon-pos
  9405. :propname name))
  9406. (js2-node-add-children pn name))))))
  9407. (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
  9408. "Parse the [expr] portion of an xml element reference.
  9409. For instance, @[expr], @*::[expr], or ns::[expr]."
  9410. (let* ((lb (js2-current-token-beg))
  9411. (pos (or at-pos lb))
  9412. rb
  9413. (expr (js2-parse-expr))
  9414. (end (js2-node-end expr))
  9415. pn)
  9416. (if (js2-must-match js2-RB "msg.no.bracket.index")
  9417. (setq rb (js2-current-token-beg)
  9418. end (js2-current-token-end)))
  9419. (prog1
  9420. (setq pn
  9421. (make-js2-xml-elem-ref-node :pos pos
  9422. :len (- end pos)
  9423. :namespace namespace
  9424. :colon-pos colon-pos
  9425. :at-pos at-pos
  9426. :expr expr
  9427. :lb (js2-relpos lb pos)
  9428. :rb (js2-relpos rb pos)))
  9429. (js2-node-add-children pn namespace expr))))
  9430. (defun js2-parse-destruct-primary-expr ()
  9431. (let ((js2-is-in-destructuring t))
  9432. (js2-parse-primary-expr)))
  9433. (defun js2-parse-primary-expr ()
  9434. "Parse a literal (leaf) expression of some sort.
  9435. Includes complex literals such as functions, object-literals,
  9436. array-literals, array comprehensions and regular expressions."
  9437. (let (tt node)
  9438. (setq tt (js2-current-token-type))
  9439. (cond
  9440. ((= tt js2-CLASS)
  9441. (js2-parse-class-expr))
  9442. ((= tt js2-FUNCTION)
  9443. (js2-parse-function-expr))
  9444. ((js2-match-async-function)
  9445. (js2-parse-function-expr t))
  9446. ((= tt js2-LB)
  9447. (js2-parse-array-comp-or-literal))
  9448. ((= tt js2-LC)
  9449. (js2-parse-object-literal))
  9450. ((= tt js2-LET)
  9451. (js2-parse-let (js2-current-token-beg)))
  9452. ((= tt js2-LP)
  9453. (js2-parse-paren-expr-or-generator-comp))
  9454. ((= tt js2-XMLATTR)
  9455. (js2-must-have-xml)
  9456. (js2-parse-attribute-access))
  9457. ((= tt js2-NAME)
  9458. (js2-parse-name tt))
  9459. ((= tt js2-NUMBER)
  9460. (setq node (make-js2-number-node))
  9461. (when (and js2-in-use-strict-directive
  9462. (= (js2-number-node-num-base node) 8)
  9463. (js2-number-node-legacy-octal-p node))
  9464. (js2-report-error "msg.no.octal.strict"))
  9465. node)
  9466. ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
  9467. (make-js2-string-node :type tt))
  9468. ((= tt js2-TEMPLATE_HEAD)
  9469. (js2-parse-template-literal))
  9470. ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
  9471. ;; Got / or /= which in this context means a regexp literal
  9472. (let* ((px-pos (js2-current-token-beg))
  9473. (flags (js2-read-regexp tt px-pos))
  9474. (end (js2-current-token-end)))
  9475. (prog1
  9476. (make-js2-regexp-node :pos px-pos
  9477. :len (- end px-pos)
  9478. :value (js2-current-token-string)
  9479. :flags flags)
  9480. (js2-set-face px-pos end 'font-lock-string-face 'record))))
  9481. ((or (= tt js2-NULL)
  9482. (= tt js2-THIS)
  9483. (= tt js2-SUPER)
  9484. (= tt js2-FALSE)
  9485. (= tt js2-TRUE))
  9486. (make-js2-keyword-node :type tt))
  9487. ((= tt js2-TRIPLEDOT)
  9488. ;; Likewise, only valid in an arrow function with a rest param.
  9489. (if (and (js2-match-token js2-NAME)
  9490. (js2-match-token js2-RP)
  9491. (eq (js2-peek-token) js2-ARROW))
  9492. (progn
  9493. (js2-unget-token) ; Put back the right paren.
  9494. ;; See the previous case.
  9495. (make-js2-keyword-node :type js2-NULL))
  9496. (js2-report-error "msg.syntax")
  9497. (make-js2-error-node)))
  9498. ((= tt js2-RESERVED)
  9499. (js2-report-error "msg.reserved.id")
  9500. (make-js2-name-node))
  9501. ((= tt js2-ERROR)
  9502. ;; the scanner or one of its subroutines reported the error.
  9503. (make-js2-error-node))
  9504. ((= tt js2-EOF)
  9505. (let* ((px-pos (point-at-bol))
  9506. (len (- js2-ts-cursor px-pos)))
  9507. (js2-report-error "msg.unexpected.eof" nil px-pos len))
  9508. (make-js2-error-node :pos (1- js2-ts-cursor)))
  9509. (t
  9510. (js2-report-error "msg.syntax")
  9511. (make-js2-error-node)))))
  9512. (defun js2-parse-template-literal ()
  9513. (let ((beg (js2-current-token-beg))
  9514. (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
  9515. (tt js2-TEMPLATE_HEAD))
  9516. (while (eq tt js2-TEMPLATE_HEAD)
  9517. (push (js2-parse-expr) kids)
  9518. (js2-must-match js2-RC "msg.syntax")
  9519. (setq tt (js2-get-token 'TEMPLATE_TAIL))
  9520. (push (make-js2-string-node :type tt) kids))
  9521. (setq kids (nreverse kids))
  9522. (let ((tpl (make-js2-template-node :pos beg
  9523. :len (- (js2-current-token-end) beg)
  9524. :kids kids)))
  9525. (apply #'js2-node-add-children tpl kids)
  9526. tpl)))
  9527. (defun js2-parse-name (_tt)
  9528. (let ((name (js2-current-token-string))
  9529. node)
  9530. (setq node (if js2-compiler-xml-available
  9531. (js2-parse-property-name nil name 0)
  9532. (js2-create-name-node 'check-activation nil name)))
  9533. (if (and js2-highlight-external-variables
  9534. ;; FIXME: What's TRT for `js2-xml-ref-node'?
  9535. (js2-name-node-p node))
  9536. (js2-record-name-node node))
  9537. node))
  9538. (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
  9539. (js2-add-strict-warning
  9540. msg nil
  9541. ;; back up from comma to beginning of line or array/objlit
  9542. (max (if elems
  9543. (js2-node-pos (car elems))
  9544. pos)
  9545. (save-excursion
  9546. (goto-char comma-pos)
  9547. (back-to-indentation)
  9548. (point)))
  9549. comma-pos))
  9550. (defun js2-parse-array-comp-or-literal ()
  9551. (let ((pos (js2-current-token-beg)))
  9552. (if (and (>= js2-language-version 200)
  9553. (js2-match-token js2-FOR))
  9554. (js2-parse-array-comp pos)
  9555. (js2-parse-array-literal pos))))
  9556. (defun js2-parse-array-literal (pos)
  9557. (let ((after-lb-or-comma t)
  9558. after-comma tt elems pn was-rest
  9559. (continue t))
  9560. (unless js2-is-in-destructuring
  9561. (js2-push-scope (make-js2-scope))) ; for the legacy array comp
  9562. (while continue
  9563. (setq tt (js2-get-token))
  9564. (cond
  9565. ;; end of array
  9566. ((or (= tt js2-RB)
  9567. (= tt js2-EOF)) ; prevent infinite loop
  9568. (if (= tt js2-EOF)
  9569. (js2-report-error "msg.no.bracket.arg" nil pos))
  9570. (when (and after-comma (< js2-language-version 170))
  9571. (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
  9572. pos (remove nil elems) after-comma))
  9573. (setq continue nil
  9574. pn (make-js2-array-node :pos pos
  9575. :len (- js2-ts-cursor pos)
  9576. :elems (nreverse elems)))
  9577. (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
  9578. ;; anything after rest element (...foo)
  9579. (was-rest
  9580. (js2-report-error "msg.param.after.rest"))
  9581. ;; comma
  9582. ((= tt js2-COMMA)
  9583. (setq after-comma (js2-current-token-end))
  9584. (if (not after-lb-or-comma)
  9585. (setq after-lb-or-comma t)
  9586. (push nil elems)))
  9587. ;; array comp
  9588. ((and (>= js2-language-version 170)
  9589. (not js2-is-in-destructuring)
  9590. (= tt js2-FOR) ; check for array comprehension
  9591. (not after-lb-or-comma) ; "for" can't follow a comma
  9592. elems ; must have at least 1 element
  9593. (not (cdr elems))) ; but no 2nd element
  9594. (js2-unget-token)
  9595. (setf continue nil
  9596. pn (js2-parse-legacy-array-comp (car elems) pos)))
  9597. ;; another element
  9598. (t
  9599. (unless after-lb-or-comma
  9600. (js2-report-error "msg.no.bracket.arg"))
  9601. (if (and (= tt js2-TRIPLEDOT)
  9602. (>= js2-language-version 200))
  9603. ;; rest/spread operator
  9604. (progn
  9605. (push (js2-make-unary nil tt 'js2-parse-assign-expr)
  9606. elems)
  9607. (if js2-is-in-destructuring
  9608. (setq was-rest t)))
  9609. (js2-unget-token)
  9610. (push (js2-parse-assign-expr) elems))
  9611. (setq after-lb-or-comma nil
  9612. after-comma nil))))
  9613. (unless js2-is-in-destructuring
  9614. (js2-pop-scope))
  9615. pn))
  9616. (defun js2-parse-legacy-array-comp (expr pos)
  9617. "Parse a legacy array comprehension (JavaScript 1.7).
  9618. EXPR is the first expression after the opening left-bracket.
  9619. POS is the beginning of the LB token preceding EXPR.
  9620. We should have just parsed the 'for' keyword before calling this function."
  9621. (let ((current-scope js2-current-scope)
  9622. loops first filter result)
  9623. (unwind-protect
  9624. (progn
  9625. (while (js2-match-token js2-FOR)
  9626. (let ((loop (make-js2-comp-loop-node)))
  9627. (js2-push-scope loop)
  9628. (push loop loops)
  9629. (js2-parse-comp-loop loop)))
  9630. ;; First loop takes expr scope's parent.
  9631. (setf (js2-scope-parent-scope (setq first (car (last loops))))
  9632. (js2-scope-parent-scope current-scope))
  9633. ;; Set expr scope's parent to the last loop.
  9634. (setf (js2-scope-parent-scope current-scope) (car loops))
  9635. (if (/= (js2-get-token) js2-IF)
  9636. (js2-unget-token)
  9637. (setq filter (js2-parse-condition))))
  9638. (dotimes (_ (1- (length loops)))
  9639. (js2-pop-scope)))
  9640. (js2-must-match js2-RB "msg.no.bracket.arg" pos)
  9641. (setq result (make-js2-comp-node :pos pos
  9642. :len (- js2-ts-cursor pos)
  9643. :result expr
  9644. :loops (nreverse loops)
  9645. :filters (and filter (list (car filter)))
  9646. :form 'LEGACY_ARRAY))
  9647. ;; Set comp loop's parent to the last loop.
  9648. ;; TODO: Get rid of the bogus expr scope.
  9649. (setf (js2-scope-parent-scope result) first)
  9650. (apply #'js2-node-add-children result expr (car filter)
  9651. (js2-comp-node-loops result))
  9652. result))
  9653. (defun js2-parse-array-comp (pos)
  9654. "Parse an ES6 array comprehension.
  9655. POS is the beginning of the LB token.
  9656. We should have just parsed the 'for' keyword before calling this function."
  9657. (let ((pn (js2-parse-comprehension pos 'ARRAY)))
  9658. (js2-must-match js2-RB "msg.no.bracket.arg" pos)
  9659. pn))
  9660. (defun js2-parse-generator-comp (pos)
  9661. (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
  9662. (js2-current-script-or-fn
  9663. (make-js2-function-node :generator-type 'COMPREHENSION))
  9664. (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
  9665. (js2-must-match js2-RP "msg.no.paren" pos)
  9666. pn))
  9667. (defun js2-parse-comprehension (pos form)
  9668. (let (loops filters expr result last)
  9669. (unwind-protect
  9670. (progn
  9671. (js2-unget-token)
  9672. (while (js2-match-token js2-FOR)
  9673. (let ((loop (make-js2-comp-loop-node)))
  9674. (js2-push-scope loop)
  9675. (push loop loops)
  9676. (js2-parse-comp-loop loop)))
  9677. (while (js2-match-token js2-IF)
  9678. (push (car (js2-parse-condition)) filters))
  9679. (setq expr (js2-parse-assign-expr))
  9680. (setq last (car loops)))
  9681. (dolist (_ loops)
  9682. (js2-pop-scope)))
  9683. (setq result (make-js2-comp-node :pos pos
  9684. :len (- js2-ts-cursor pos)
  9685. :result expr
  9686. :loops (nreverse loops)
  9687. :filters (nreverse filters)
  9688. :form form))
  9689. (apply #'js2-node-add-children result (js2-comp-node-loops result))
  9690. (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
  9691. (setf (js2-scope-parent-scope result) last)
  9692. result))
  9693. (defun js2-parse-comp-loop (pn &optional only-of-p)
  9694. "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
  9695. The current token should be the initial FOR.
  9696. If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
  9697. (let ((pos (js2-comp-loop-node-pos pn))
  9698. tt iter obj foreach-p forof-p in-pos each-pos lp rp)
  9699. (when (and (not only-of-p) (js2-match-token js2-NAME))
  9700. (if (string= (js2-current-token-string) "each")
  9701. (progn
  9702. (setq foreach-p t
  9703. each-pos (- (js2-current-token-beg) pos)) ; relative
  9704. (js2-record-face 'font-lock-keyword-face))
  9705. (js2-report-error "msg.no.paren.for")))
  9706. (if (js2-must-match js2-LP "msg.no.paren.for")
  9707. (setq lp (- (js2-current-token-beg) pos)))
  9708. (setq tt (js2-peek-token))
  9709. (cond
  9710. ((or (= tt js2-LB)
  9711. (= tt js2-LC))
  9712. (js2-get-token)
  9713. (setq iter (js2-parse-destruct-primary-expr))
  9714. (js2-define-destruct-symbols iter js2-LET
  9715. 'font-lock-variable-name-face t))
  9716. ((js2-match-token js2-NAME)
  9717. (setq iter (js2-create-name-node)))
  9718. (t
  9719. (js2-report-error "msg.bad.var")))
  9720. ;; Define as a let since we want the scope of the variable to
  9721. ;; be restricted to the array comprehension
  9722. (if (js2-name-node-p iter)
  9723. (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
  9724. (if (or (and (not only-of-p) (js2-match-token js2-IN))
  9725. (and (>= js2-language-version 200)
  9726. (js2-match-contextual-kwd "of")
  9727. (setq forof-p t)))
  9728. (setq in-pos (- (js2-current-token-beg) pos))
  9729. (js2-report-error "msg.in.after.for.name"))
  9730. (setq obj (js2-parse-expr))
  9731. (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
  9732. (setq rp (- (js2-current-token-beg) pos)))
  9733. (setf (js2-node-pos pn) pos
  9734. (js2-node-len pn) (- js2-ts-cursor pos)
  9735. (js2-comp-loop-node-iterator pn) iter
  9736. (js2-comp-loop-node-object pn) obj
  9737. (js2-comp-loop-node-in-pos pn) in-pos
  9738. (js2-comp-loop-node-each-pos pn) each-pos
  9739. (js2-comp-loop-node-foreach-p pn) foreach-p
  9740. (js2-comp-loop-node-forof-p pn) forof-p
  9741. (js2-comp-loop-node-lp pn) lp
  9742. (js2-comp-loop-node-rp pn) rp)
  9743. (js2-node-add-children pn iter obj)
  9744. pn))
  9745. (defun js2-parse-class-stmt ()
  9746. (let ((pos (js2-current-token-beg))
  9747. (_ (js2-must-match-name "msg.unnamed.class.stmt"))
  9748. (name (js2-create-name-node t)))
  9749. (js2-set-face (js2-node-pos name) (js2-node-end name)
  9750. 'font-lock-type-face 'record)
  9751. (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
  9752. (js2-record-imenu-functions node name)
  9753. (js2-define-symbol js2-FUNCTION
  9754. (js2-name-node-name name)
  9755. node)
  9756. node)))
  9757. (defun js2-parse-class-expr ()
  9758. (let ((pos (js2-current-token-beg))
  9759. name)
  9760. (when (js2-match-token js2-NAME)
  9761. (setq name (js2-create-name-node t)))
  9762. (js2-parse-class pos 'CLASS_EXPRESSION name)))
  9763. (defun js2-parse-class (pos form name)
  9764. ;; class X [extends ...] {
  9765. (let (pn elems extends)
  9766. (if (js2-match-token js2-EXTENDS)
  9767. (if (= (js2-peek-token) js2-LC)
  9768. (js2-report-error "msg.missing.extends")
  9769. ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
  9770. (setq extends (js2-parse-assign-expr))
  9771. (if (not extends)
  9772. (js2-report-error "msg.bad.extends"))))
  9773. (js2-must-match js2-LC "msg.no.brace.class")
  9774. (setq elems (js2-parse-object-literal-elems t)
  9775. pn (make-js2-class-node :pos pos
  9776. :len (- js2-ts-cursor pos)
  9777. :form form
  9778. :name name
  9779. :extends extends
  9780. :elems elems))
  9781. (apply #'js2-node-add-children
  9782. pn name extends (js2-class-node-elems pn))
  9783. pn))
  9784. (defun js2-parse-object-literal ()
  9785. (let* ((pos (js2-current-token-beg))
  9786. (elems (js2-parse-object-literal-elems))
  9787. (result (make-js2-object-node :pos pos
  9788. :len (- js2-ts-cursor pos)
  9789. :elems elems)))
  9790. (apply #'js2-node-add-children result (js2-object-node-elems result))
  9791. result))
  9792. (defun js2-property-key-string (property-node)
  9793. "Return the key of PROPERTY-NODE (a `js2-object-prop-node' or
  9794. `js2-method-node') as a string, or nil if it can't be
  9795. represented as a string (e.g., the key is computed by an
  9796. expression)."
  9797. (cond
  9798. ((js2-unary-node-p property-node) nil) ;; {...foo}
  9799. (t
  9800. (let ((key (js2-infix-node-left property-node)))
  9801. (when (js2-computed-prop-name-node-p key)
  9802. (setq key (js2-computed-prop-name-node-expr key)))
  9803. (cond
  9804. ((js2-name-node-p key)
  9805. (js2-name-node-name key))
  9806. ((js2-string-node-p key)
  9807. (js2-string-node-value key))
  9808. ((js2-number-node-p key)
  9809. (js2-number-node-value key)))))))
  9810. (defun js2-parse-object-literal-elems (&optional class-p)
  9811. (let ((pos (js2-current-token-beg))
  9812. (static nil)
  9813. (continue t)
  9814. tt elems elem
  9815. elem-key-string previous-elem-key-string
  9816. after-comma previous-token)
  9817. (while continue
  9818. ;; Clear out any lookahead tokens (possibly wrong modifier).
  9819. ;; FIXME: Deal with this problem in a more systematic fashion.
  9820. ;; Perhaps by making this modifier affect not how the token
  9821. ;; struct value is constructed, but what js2-get-token returns
  9822. ;; based on it.
  9823. (when (> js2-ti-lookahead 0)
  9824. (setq js2-ti-lookahead 0)
  9825. (setq js2-ts-cursor (js2-current-token-end)))
  9826. (setq tt (js2-get-prop-name-token)
  9827. static nil
  9828. elem nil
  9829. previous-token nil)
  9830. ;; Handle 'static' keyword only if we're in a class
  9831. (when (and class-p (= js2-NAME tt)
  9832. (string= "static" (js2-current-token-string)))
  9833. (js2-record-face 'font-lock-keyword-face)
  9834. (setq static t
  9835. tt (js2-get-prop-name-token)))
  9836. ;; Handle generator * before the property name for in-line functions
  9837. (when (and (>= js2-language-version 200)
  9838. (= js2-MUL tt))
  9839. (setq previous-token (js2-current-token)
  9840. tt (js2-get-prop-name-token)))
  9841. ;; Handle getter, setter and async methods
  9842. (let ((prop (js2-current-token-string)))
  9843. (when (and (>= js2-language-version 200)
  9844. (= js2-NAME tt)
  9845. (member prop '("get" "set" "async"))
  9846. (member (js2-peek-token 'KEYWORD_IS_NAME)
  9847. (list js2-NAME js2-STRING js2-NUMBER js2-LB)))
  9848. (setq previous-token (js2-current-token)
  9849. tt (js2-get-prop-name-token))))
  9850. (cond
  9851. ;; Rest/spread (...expr)
  9852. ((and (>= js2-language-version 200)
  9853. (not class-p) (not static) (not previous-token)
  9854. (= js2-TRIPLEDOT tt))
  9855. (setq after-comma nil
  9856. elem (js2-make-unary nil js2-TRIPLEDOT 'js2-parse-assign-expr)))
  9857. ;; Found a key/value property (of any sort)
  9858. ((member tt (list js2-NAME js2-STRING js2-NUMBER js2-LB))
  9859. (setq after-comma nil
  9860. elem (js2-parse-named-prop tt previous-token class-p))
  9861. (if (and (null elem)
  9862. (not js2-recover-from-parse-errors))
  9863. (setq continue nil)))
  9864. ;; Break out of loop, and handle trailing commas.
  9865. ((or (= tt js2-RC)
  9866. (= tt js2-EOF))
  9867. (js2-unget-token)
  9868. (setq continue nil)
  9869. (if after-comma
  9870. (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
  9871. pos elems after-comma)))
  9872. ;; Skip semicolons in a class body
  9873. ((and class-p
  9874. (= tt js2-SEMI))
  9875. nil)
  9876. (t
  9877. (js2-report-error "msg.bad.prop")
  9878. (unless js2-recover-from-parse-errors
  9879. (setq continue nil)))) ; end switch
  9880. ;; Handle static for classes' codegen.
  9881. (if static
  9882. (if elem (js2-node-set-prop elem 'STATIC t)
  9883. (js2-report-error "msg.unexpected.static")))
  9884. ;; Handle commas, depending on class-p.
  9885. (let ((tok (js2-get-prop-name-token)))
  9886. (if (eq tok js2-COMMA)
  9887. (if class-p
  9888. (js2-report-error "msg.class.unexpected.comma")
  9889. (setq after-comma (js2-current-token-end)))
  9890. (js2-unget-token)
  9891. (unless class-p (setq continue nil))))
  9892. (when elem
  9893. (when (and js2-in-use-strict-directive
  9894. (setq elem-key-string (js2-property-key-string elem))
  9895. (cl-some
  9896. (lambda (previous-elem)
  9897. (and (setq previous-elem-key-string
  9898. (js2-property-key-string previous-elem))
  9899. ;; Check if the property is a duplicate.
  9900. (string= previous-elem-key-string elem-key-string)
  9901. ;; But make an exception for getter / setter pairs.
  9902. (not (and (js2-method-node-p elem)
  9903. (js2-method-node-p previous-elem)
  9904. (let ((type (js2-node-get-prop (js2-method-node-right elem) 'METHOD_TYPE))
  9905. (previous-type (js2-node-get-prop (js2-method-node-right previous-elem) 'METHOD_TYPE)))
  9906. (and (member type '(GET SET))
  9907. (member previous-type '(GET SET))
  9908. (not (eq type previous-type))))))))
  9909. elems))
  9910. (js2-report-error "msg.dup.obj.lit.prop.strict"
  9911. elem-key-string
  9912. (js2-node-abs-pos (js2-infix-node-left elem))
  9913. (js2-node-len (js2-infix-node-left elem))))
  9914. ;; Append any parsed element.
  9915. (push elem elems))) ; end loop
  9916. (js2-must-match js2-RC "msg.no.brace.prop")
  9917. (nreverse elems)))
  9918. (defun js2-parse-named-prop (tt previous-token &optional class-p)
  9919. "Parse a name, string, or getter/setter object property.
  9920. When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
  9921. (let ((key (js2-parse-prop-name tt))
  9922. (prop (and previous-token (js2-token-string previous-token)))
  9923. (property-type (when previous-token
  9924. (if (= (js2-token-type previous-token) js2-MUL)
  9925. "*"
  9926. (js2-token-string previous-token))))
  9927. pos)
  9928. (when (member prop '("get" "set" "async"))
  9929. (setq pos (js2-token-beg previous-token))
  9930. (js2-set-face (js2-token-beg previous-token)
  9931. (js2-token-end previous-token)
  9932. 'font-lock-keyword-face 'record)) ; get/set/async
  9933. (cond
  9934. ;; method definition: {f() {...}}
  9935. ((and (= (js2-peek-token) js2-LP)
  9936. (>= js2-language-version 200))
  9937. (when (or (js2-name-node-p key) (js2-string-node-p key))
  9938. ;; highlight function name properties
  9939. (js2-record-face 'font-lock-function-name-face))
  9940. (js2-parse-method-prop pos key property-type))
  9941. ;; class field or binding element with initializer
  9942. ((and (= (js2-peek-token) js2-ASSIGN)
  9943. (>= js2-language-version 200))
  9944. (if (not (or class-p
  9945. js2-is-in-destructuring))
  9946. (js2-report-error "msg.init.no.destruct"))
  9947. (js2-parse-initialized-binding key))
  9948. ;; regular prop
  9949. (t
  9950. (let ((beg (js2-current-token-beg))
  9951. (end (js2-current-token-end))
  9952. (expr (js2-parse-plain-property key class-p)))
  9953. (when (and (= tt js2-NAME)
  9954. (not js2-is-in-destructuring)
  9955. js2-highlight-external-variables
  9956. (js2-node-get-prop expr 'SHORTHAND))
  9957. (js2-record-name-node key))
  9958. (js2-set-face beg end
  9959. (if (js2-function-node-p
  9960. (js2-object-prop-node-right expr))
  9961. 'font-lock-function-name-face
  9962. 'js2-object-property)
  9963. 'record)
  9964. expr)))))
  9965. (defun js2-parse-initialized-binding (name)
  9966. "Parse a `SingleNameBinding' with initializer.
  9967. `name' is the `BindingIdentifier'."
  9968. (when (js2-match-token js2-ASSIGN)
  9969. (js2-make-binary js2-ASSIGN name 'js2-parse-assign-expr t)))
  9970. (defun js2-parse-prop-name (tt)
  9971. (cond
  9972. ;; Literal string keys: {'foo': 'bar'}
  9973. ((= tt js2-STRING)
  9974. (make-js2-string-node))
  9975. ;; Handle computed keys: {[Symbol.iterator]: ...}, *[1+2]() {...}},
  9976. ;; {[foo + bar]() { ... }}, {[get ['x' + 1]() {...}}
  9977. ((and (= tt js2-LB)
  9978. (>= js2-language-version 200))
  9979. (make-js2-computed-prop-name-node
  9980. :expr (prog1 (js2-parse-assign-expr)
  9981. (js2-must-match js2-RB "msg.missing.computed.rb"))))
  9982. ;; Numeric keys: {12: 'foo'}, {10.7: 'bar'}
  9983. ((= tt js2-NUMBER)
  9984. (make-js2-number-node))
  9985. ;; Unquoted names: {foo: 12}
  9986. ((= tt js2-NAME)
  9987. (js2-create-name-node))
  9988. ;; Anything else is an error
  9989. (t (js2-report-error "msg.bad.prop"))))
  9990. (defun js2-parse-plain-property (prop &optional class-p)
  9991. "Parse a non-getter/setter property in an object literal.
  9992. PROP is the node representing the property: a number, name,
  9993. string or expression."
  9994. (let* (tt
  9995. (pos (js2-node-pos prop))
  9996. colon expr result)
  9997. (cond
  9998. ;; Abbreviated property, as in {foo, bar} or class {a; b}
  9999. ((and (>= js2-language-version 200)
  10000. (if class-p
  10001. (and (setq tt (js2-peek-token-or-eol))
  10002. (member tt (list js2-EOL js2-RC js2-SEMI)))
  10003. (and (setq tt (js2-peek-token))
  10004. (member tt (list js2-COMMA js2-RC))
  10005. (js2-name-node-p prop))))
  10006. (setq result (make-js2-object-prop-node
  10007. :pos pos
  10008. :len (js2-node-len prop)
  10009. :left prop
  10010. :right prop
  10011. :op-pos (- (js2-current-token-beg) pos)))
  10012. (js2-node-add-children result prop)
  10013. (js2-node-set-prop result 'SHORTHAND t)
  10014. result)
  10015. ;; Normal property
  10016. (t
  10017. (setq tt (js2-get-token))
  10018. (if (= tt js2-COLON)
  10019. (setq colon (- (js2-current-token-beg) pos)
  10020. expr (js2-parse-assign-expr))
  10021. (js2-report-error "msg.no.colon.prop")
  10022. (setq expr (make-js2-error-node)))
  10023. (setq result (make-js2-object-prop-node
  10024. :pos pos
  10025. ;; don't include last consumed token in length
  10026. :len (- (+ (js2-node-pos expr)
  10027. (js2-node-len expr))
  10028. pos)
  10029. :left prop
  10030. :right expr
  10031. :op-pos colon))
  10032. (js2-node-add-children result prop expr)
  10033. result))))
  10034. (defun js2-parse-method-prop (pos prop type-string)
  10035. "Parse method property in an object literal or a class body.
  10036. JavaScript syntax is:
  10037. { foo(...) {...}, get foo() {...}, set foo(x) {...}, *foo(...) {...},
  10038. async foo(...) {...} }
  10039. and expression closure style is also supported
  10040. { get foo() x, set foo(x) _x = x }
  10041. POS is the start position of the `get' or `set' keyword, if any.
  10042. PROP is the `js2-name-node' representing the property name.
  10043. TYPE-STRING is a string `get', `set', `*', or nil, indicating a found keyword."
  10044. (let* ((type (or (cdr (assoc type-string '(("get" . GET)
  10045. ("set" . SET)
  10046. ("async" . ASYNC))))
  10047. 'FUNCTION))
  10048. result end
  10049. (pos (or pos (js2-current-token-beg)))
  10050. (_ (js2-must-match js2-LP "msg.no.paren.parms"))
  10051. (fn (js2-parse-function 'FUNCTION_EXPRESSION pos
  10052. (string= type-string "*")
  10053. (eq type 'ASYNC)
  10054. nil)))
  10055. (js2-node-set-prop fn 'METHOD_TYPE type) ; for codegen
  10056. (unless pos (setq pos (js2-node-pos prop)))
  10057. (setq end (js2-node-end fn)
  10058. result (make-js2-method-node :pos pos
  10059. :len (- end pos)
  10060. :left prop
  10061. :right fn))
  10062. (js2-node-add-children result prop fn)
  10063. result))
  10064. (defun js2-create-name-node (&optional check-activation-p token string)
  10065. "Create a name node using the current token and, optionally, STRING.
  10066. And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
  10067. (let* ((beg (js2-current-token-beg))
  10068. (tt (js2-current-token-type))
  10069. (s (or string
  10070. (if (= js2-NAME tt)
  10071. (js2-current-token-string)
  10072. (js2-tt-name tt))))
  10073. name)
  10074. (setq name (make-js2-name-node :pos beg
  10075. :name s
  10076. :len (length s)))
  10077. (if check-activation-p
  10078. (js2-check-activation-name s (or token js2-NAME)))
  10079. name))
  10080. ;;; Use AST to extract semantic information
  10081. (defun js2-get-element-index-from-array-node (elem array-node &optional hardcoded-array-index)
  10082. "Get index of ELEM from ARRAY-NODE or 0 and return it as string."
  10083. (let ((idx 0) elems (rlt hardcoded-array-index))
  10084. (setq elems (js2-array-node-elems array-node))
  10085. (if (and elem (not hardcoded-array-index))
  10086. (setq rlt (catch 'nth-elt
  10087. (dolist (x elems)
  10088. ;; We know the ELEM does belong to ARRAY-NODE,
  10089. (if (eq elem x) (throw 'nth-elt idx))
  10090. (setq idx (1+ idx)))
  10091. 0)))
  10092. (format "[%s]" rlt)))
  10093. (defun js2-print-json-path (&optional hardcoded-array-index)
  10094. "Print the path to the JSON value under point, and save it in the kill ring.
  10095. If HARDCODED-ARRAY-INDEX provided, array index in JSON path is replaced with it."
  10096. (interactive "P")
  10097. (js2-reparse)
  10098. (let (previous-node current-node
  10099. key-name
  10100. rlt)
  10101. ;; The `js2-node-at-point' starts scanning from AST root node.
  10102. ;; So there is no way to optimize it.
  10103. (setq current-node (js2-node-at-point))
  10104. (while (not (js2-ast-root-p current-node))
  10105. (cond
  10106. ;; JSON property node
  10107. ((js2-object-prop-node-p current-node)
  10108. (setq key-name (js2-prop-node-name (js2-object-prop-node-left current-node)))
  10109. (if rlt (setq rlt (concat "." key-name rlt))
  10110. (setq rlt (concat "." key-name))))
  10111. ;; Array node
  10112. ((or (js2-array-node-p current-node))
  10113. (setq rlt (concat (js2-get-element-index-from-array-node previous-node
  10114. current-node
  10115. hardcoded-array-index)
  10116. rlt)))
  10117. ;; Other nodes are ignored
  10118. (t))
  10119. ;; current node is archived
  10120. (setq previous-node current-node)
  10121. ;; Get parent node and continue the loop
  10122. (setq current-node (js2-node-parent current-node)))
  10123. (cond
  10124. (rlt
  10125. ;; Clean the final result
  10126. (setq rlt (replace-regexp-in-string "^\\." "" rlt))
  10127. (kill-new rlt)
  10128. (message "%s => kill-ring" rlt))
  10129. (t
  10130. (message "No JSON path found!")))
  10131. rlt))
  10132. ;;; Indentation support (bouncing)
  10133. ;; In recent-enough Emacs, we reuse the indentation code from
  10134. ;; `js-mode'. To continue support for the older versions, some code
  10135. ;; that was here previously was moved to `js2-old-indent.el'.
  10136. ;; Whichever indenter is used, it's often "wrong", however, and needs
  10137. ;; to be overridden. The right long-term solution is probably to
  10138. ;; emulate (or integrate with) cc-engine, but it's a nontrivial amount
  10139. ;; of coding. Even when a parse tree from `js2-parse' is present,
  10140. ;; which is not true at the moment the user is typing, computing
  10141. ;; indentation is still thousands of lines of code to handle every
  10142. ;; possible syntactic edge case.
  10143. ;; In the meantime, the compromise solution is that we offer a "bounce
  10144. ;; indenter", configured with `js2-bounce-indent-p', which cycles the
  10145. ;; current line indent among various likely guess points. This approach
  10146. ;; is far from perfect, but should at least make it slightly easier to
  10147. ;; move the line towards its desired indentation when manually
  10148. ;; overriding Karl's heuristic nesting guesser.
  10149. (defun js2-backward-sws ()
  10150. "Move backward through whitespace and comments."
  10151. (interactive)
  10152. (while (forward-comment -1)))
  10153. (defun js2-forward-sws ()
  10154. "Move forward through whitespace and comments."
  10155. (interactive)
  10156. (while (forward-comment 1)))
  10157. (defun js2-arglist-close ()
  10158. "Return non-nil if we're on a line beginning with a close-paren/brace."
  10159. (save-excursion
  10160. (goto-char (point-at-bol))
  10161. (js2-forward-sws)
  10162. (looking-at "[])}]")))
  10163. (defun js2-indent-looks-like-label-p ()
  10164. (goto-char (point-at-bol))
  10165. (js2-forward-sws)
  10166. (looking-at (concat js2-mode-identifier-re ":")))
  10167. (defun js2-indent-in-objlit-p (parse-status)
  10168. "Return non-nil if this looks like an object-literal entry."
  10169. (let ((start (nth 1 parse-status)))
  10170. (and
  10171. start
  10172. (save-excursion
  10173. (and (zerop (forward-line -1))
  10174. (not (< (point) start)) ; crossed a {} boundary
  10175. (js2-indent-looks-like-label-p)))
  10176. (save-excursion
  10177. (js2-indent-looks-like-label-p)))))
  10178. ;; If prev line looks like foobar({ then we're passing an object
  10179. ;; literal to a function call, and people pretty much always want to
  10180. ;; de-dent back to the previous line, so move the 'basic-offset'
  10181. ;; position to the front.
  10182. (defun js2-indent-objlit-arg-p (parse-status)
  10183. (save-excursion
  10184. (back-to-indentation)
  10185. (js2-backward-sws)
  10186. (and (eq (1- (point)) (nth 1 parse-status))
  10187. (eq (char-before) ?{)
  10188. (progn
  10189. (forward-char -1)
  10190. (skip-chars-backward " \t")
  10191. (eq (char-before) ?\()))))
  10192. (defun js2-indent-case-block-p ()
  10193. (save-excursion
  10194. (back-to-indentation)
  10195. (js2-backward-sws)
  10196. (goto-char (point-at-bol))
  10197. (skip-chars-forward " \t")
  10198. (looking-at "case\\s-.+:")))
  10199. (defun js2-bounce-indent (normal-col parse-status &optional backward)
  10200. "Cycle among alternate computed indentation positions.
  10201. PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
  10202. of the buffer to the current point. NORMAL-COL is the indentation
  10203. column computed by the heuristic guesser based on current paren,
  10204. bracket, brace and statement nesting. If BACKWARDS, cycle positions
  10205. in reverse."
  10206. (let ((cur-indent (current-indentation))
  10207. (old-buffer-undo-list buffer-undo-list)
  10208. ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
  10209. (current-line (save-excursion
  10210. (forward-line 0) ; move to bol
  10211. (1+ (count-lines (point-min) (point)))))
  10212. positions pos main-pos anchor arglist-cont same-indent
  10213. basic-offset computed-pos)
  10214. ;; temporarily don't record undo info, if user requested this
  10215. (when js2-mode-indent-inhibit-undo
  10216. (setq buffer-undo-list t))
  10217. (unwind-protect
  10218. (progn
  10219. ;; First likely point: indent from beginning of previous code line
  10220. (push (setq basic-offset
  10221. (+ (save-excursion
  10222. (back-to-indentation)
  10223. (js2-backward-sws)
  10224. (back-to-indentation)
  10225. (current-column))
  10226. js2-basic-offset))
  10227. positions)
  10228. ;; (First + epsilon) likely point: indent 2x from beginning of
  10229. ;; previous code line. Google does it this way.
  10230. (push (setq basic-offset
  10231. (+ (save-excursion
  10232. (back-to-indentation)
  10233. (js2-backward-sws)
  10234. (back-to-indentation)
  10235. (current-column))
  10236. (* 2 js2-basic-offset)))
  10237. positions)
  10238. ;; Second likely point: indent from assign-expr RHS. This
  10239. ;; is just a crude guess based on finding " = " on the previous
  10240. ;; line containing actual code.
  10241. (setq pos (save-excursion
  10242. (forward-line -1)
  10243. (goto-char (point-at-bol))
  10244. (when (re-search-forward "\\s-+\\(=\\)\\s-+"
  10245. (point-at-eol) t)
  10246. (goto-char (match-end 1))
  10247. (skip-chars-forward " \t\r\n")
  10248. (current-column))))
  10249. (when pos
  10250. (cl-incf pos js2-basic-offset)
  10251. (push pos positions))
  10252. ;; Third likely point: same indent as previous line of code.
  10253. ;; Make it the first likely point if we're not on an
  10254. ;; arglist-close line and previous line ends in a comma, or
  10255. ;; both this line and prev line look like object-literal
  10256. ;; elements.
  10257. (setq pos (save-excursion
  10258. (goto-char (point-at-bol))
  10259. (js2-backward-sws)
  10260. (back-to-indentation)
  10261. (prog1
  10262. (current-column)
  10263. ;; while we're here, look for trailing comma
  10264. (if (save-excursion
  10265. (goto-char (point-at-eol))
  10266. (js2-backward-sws)
  10267. (eq (char-before) ?,))
  10268. (setq arglist-cont (1- (point)))))))
  10269. (when pos
  10270. (if (and (or arglist-cont
  10271. (js2-indent-in-objlit-p parse-status))
  10272. (not (js2-arglist-close)))
  10273. (setq same-indent pos))
  10274. (push pos positions))
  10275. ;; Fourth likely point: first preceding code with less indentation.
  10276. ;; than the immediately preceding code line.
  10277. (setq pos (save-excursion
  10278. (back-to-indentation)
  10279. (js2-backward-sws)
  10280. (back-to-indentation)
  10281. (setq anchor (current-column))
  10282. (while (and (zerop (forward-line -1))
  10283. (>= (progn
  10284. (back-to-indentation)
  10285. (current-column))
  10286. anchor)))
  10287. (setq pos (current-column))))
  10288. (push pos positions)
  10289. ;; nesting-heuristic position, main by default
  10290. (push (setq main-pos normal-col) positions)
  10291. ;; delete duplicates and sort positions list
  10292. (setq positions (sort (delete-dups positions) '<))
  10293. ;; comma-list continuation lines: prev line indent takes precedence
  10294. (if same-indent
  10295. (setq main-pos same-indent))
  10296. ;; common special cases where we want to indent in from previous line
  10297. (if (or (js2-indent-case-block-p)
  10298. (js2-indent-objlit-arg-p parse-status))
  10299. (setq main-pos basic-offset))
  10300. ;; if bouncing backward, reverse positions list
  10301. (if backward
  10302. (setq positions (reverse positions)))
  10303. ;; record whether we're already sitting on one of the alternatives
  10304. (setq pos (member cur-indent positions))
  10305. (cond
  10306. ;; case 0: we're one one of the alternatives and this is the
  10307. ;; first time they've pressed TAB on this line (best-guess).
  10308. ((and js2-mode-indent-ignore-first-tab
  10309. pos
  10310. ;; first time pressing TAB on this line?
  10311. (not (eq js2-mode-last-indented-line current-line)))
  10312. ;; do nothing
  10313. (setq computed-pos nil))
  10314. ;; case 1: only one computed position => use it
  10315. ((null (cdr positions))
  10316. (setq computed-pos 0))
  10317. ;; case 2: not on any of the computed spots => use main spot
  10318. ((not pos)
  10319. (setq computed-pos (js2-position main-pos positions)))
  10320. ;; case 3: on last position: cycle to first position
  10321. ((null (cdr pos))
  10322. (setq computed-pos 0))
  10323. ;; case 4: on intermediate position: cycle to next position
  10324. (t
  10325. (setq computed-pos (js2-position (cl-second pos) positions))))
  10326. ;; see if any hooks want to indent; otherwise we do it
  10327. (cl-loop with result = nil
  10328. for hook in js2-indent-hook
  10329. while (null result)
  10330. do
  10331. (setq result (funcall hook positions computed-pos))
  10332. finally do
  10333. (unless (or result (null computed-pos))
  10334. (indent-line-to (nth computed-pos positions)))))
  10335. ;; finally
  10336. (if js2-mode-indent-inhibit-undo
  10337. (setq buffer-undo-list old-buffer-undo-list))
  10338. ;; see commentary for `js2-mode-last-indented-line'
  10339. (setq js2-mode-last-indented-line current-line))))
  10340. (defun js2-1-line-comment-continuation-p ()
  10341. "Return t if we're in a 1-line comment continuation.
  10342. If so, we don't ever want to use bounce-indent."
  10343. (save-excursion
  10344. (and (progn
  10345. (forward-line 0)
  10346. (looking-at "\\s-*//"))
  10347. (progn
  10348. (forward-line -1)
  10349. (forward-line 0)
  10350. (when (looking-at "\\s-*$")
  10351. (js2-backward-sws)
  10352. (forward-line 0))
  10353. (looking-at "\\s-*//")))))
  10354. (defun js2-indent-bounce (&optional backward)
  10355. "Indent the current line, bouncing between several positions."
  10356. (interactive)
  10357. (let (parse-status offset indent-col
  10358. ;; Don't whine about errors/warnings when we're indenting.
  10359. ;; This has to be set before calling parse-partial-sexp below.
  10360. (inhibit-point-motion-hooks t))
  10361. (setq parse-status (save-excursion
  10362. (syntax-ppss (point-at-bol)))
  10363. offset (- (point) (save-excursion
  10364. (back-to-indentation)
  10365. (point))))
  10366. ;; Don't touch multiline strings.
  10367. (unless (nth 3 parse-status)
  10368. (setq indent-col (js2-proper-indentation parse-status))
  10369. (cond
  10370. ;; It doesn't work well on first line of buffer.
  10371. ((and (not (nth 4 parse-status))
  10372. (not (js2-same-line (point-min)))
  10373. (not (js2-1-line-comment-continuation-p)))
  10374. (js2-bounce-indent indent-col parse-status backward))
  10375. ;; just indent to the guesser's likely spot
  10376. (t (indent-line-to indent-col)))
  10377. (when (cl-plusp offset)
  10378. (forward-char offset)))))
  10379. (defun js2-indent-bounce-backward ()
  10380. "Indent the current line, bouncing between positions in reverse."
  10381. (interactive)
  10382. (js2-indent-bounce t))
  10383. (defun js2-indent-region (start end)
  10384. "Indent the region, but don't use bounce indenting."
  10385. (let ((js2-bounce-indent-p nil)
  10386. (indent-region-function nil)
  10387. (after-change-functions (remq 'js2-mode-edit
  10388. after-change-functions)))
  10389. (indent-region start end nil) ; nil for byte-compiler
  10390. (js2-mode-edit start end (- end start))))
  10391. (defvar js2-minor-mode-map
  10392. (let ((map (make-sparse-keymap)))
  10393. (define-key map (kbd "C-c C-`") #'js2-next-error)
  10394. map)
  10395. "Keymap used when `js2-minor-mode' is active.")
  10396. ;;;###autoload
  10397. (define-minor-mode js2-minor-mode
  10398. "Minor mode for running js2 as a background linter.
  10399. This allows you to use a different major mode for JavaScript editing,
  10400. such as `js-mode', while retaining the asynchronous error/warning
  10401. highlighting features of `js2-mode'."
  10402. :group 'js2-mode
  10403. :lighter " js-lint"
  10404. (if (derived-mode-p 'js2-mode)
  10405. (setq js2-minor-mode nil)
  10406. (if js2-minor-mode
  10407. (js2-minor-mode-enter)
  10408. (js2-minor-mode-exit))))
  10409. (defun js2-minor-mode-enter ()
  10410. "Initialization for `js2-minor-mode'."
  10411. (set (make-local-variable 'max-lisp-eval-depth)
  10412. (max max-lisp-eval-depth 3000))
  10413. (setq next-error-function #'js2-next-error)
  10414. ;; Experiment: make reparse-delay longer for longer files.
  10415. (if (cl-plusp js2-dynamic-idle-timer-adjust)
  10416. (setq js2-idle-timer-delay
  10417. (* js2-idle-timer-delay
  10418. (/ (point-max) js2-dynamic-idle-timer-adjust))))
  10419. (setq js2-mode-buffer-dirty-p t
  10420. js2-mode-parsing nil)
  10421. (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
  10422. (set (make-local-variable 'js2-mode-change-syntax-p) nil)
  10423. (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
  10424. (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
  10425. (when js2-include-jslint-globals
  10426. (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
  10427. (when js2-include-jslint-declaration-externs
  10428. (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-declaration-externs nil t))
  10429. (run-hooks 'js2-init-hook)
  10430. (js2-reparse))
  10431. (defun js2-minor-mode-exit ()
  10432. "Turn off `js2-minor-mode'."
  10433. (setq next-error-function nil)
  10434. (remove-hook 'after-change-functions #'js2-mode-edit t)
  10435. (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
  10436. (when js2-mode-node-overlay
  10437. (delete-overlay js2-mode-node-overlay)
  10438. (setq js2-mode-node-overlay nil))
  10439. (js2-remove-overlays)
  10440. (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
  10441. (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-declaration-externs t)
  10442. (setq js2-mode-ast nil))
  10443. (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
  10444. (make-variable-buffer-local 'js2-source-buffer)
  10445. (cl-defun js2-display-error-list ()
  10446. "Display a navigable buffer listing parse errors/warnings."
  10447. (interactive)
  10448. (unless (js2-have-errors-p)
  10449. (message "No errors")
  10450. (cl-return-from js2-display-error-list))
  10451. (cl-labels ((annotate-list
  10452. (lst type)
  10453. "Add diagnostic TYPE and line number to errs list"
  10454. (mapcar (lambda (err)
  10455. (list err type (line-number-at-pos (nth 1 err))))
  10456. lst)))
  10457. (let* ((srcbuf (current-buffer))
  10458. (errbuf (get-buffer-create "*js-lint*"))
  10459. (errors (annotate-list
  10460. (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
  10461. 'js2-error)) ; must be a valid face name
  10462. (warnings (annotate-list
  10463. (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
  10464. 'js2-warning)) ; must be a valid face name
  10465. (all-errs (sort (append errors warnings)
  10466. (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
  10467. (with-current-buffer errbuf
  10468. (let ((inhibit-read-only t))
  10469. (erase-buffer)
  10470. (dolist (err all-errs)
  10471. (cl-destructuring-bind ((msg-key beg _end &rest rest) type line) err
  10472. (insert-text-button
  10473. (format "line %d: %s" line (js2-get-msg msg-key))
  10474. 'face type
  10475. 'follow-link "\C-m"
  10476. 'action 'js2-error-buffer-jump
  10477. 'js2-msg (js2-get-msg msg-key)
  10478. 'js2-pos beg)
  10479. (insert "\n"))))
  10480. (js2-error-buffer-mode)
  10481. (setq js2-source-buffer srcbuf)
  10482. (pop-to-buffer errbuf)
  10483. (goto-char (point-min))
  10484. (unless (eobp)
  10485. (js2-error-buffer-view))))))
  10486. (defvar js2-error-buffer-mode-map
  10487. (let ((map (make-sparse-keymap)))
  10488. (define-key map "n" #'js2-error-buffer-next)
  10489. (define-key map "p" #'js2-error-buffer-prev)
  10490. (define-key map (kbd "RET") #'js2-error-buffer-jump)
  10491. (define-key map "o" #'js2-error-buffer-view)
  10492. (define-key map "q" #'js2-error-buffer-quit)
  10493. map)
  10494. "Keymap used for js2 diagnostics buffers.")
  10495. (defun js2-error-buffer-mode ()
  10496. "Major mode for js2 diagnostics buffers.
  10497. Selecting an error will jump it to the corresponding source-buffer error.
  10498. \\{js2-error-buffer-mode-map}"
  10499. (interactive)
  10500. (setq major-mode 'js2-error-buffer-mode
  10501. mode-name "JS Lint Diagnostics")
  10502. (use-local-map js2-error-buffer-mode-map)
  10503. (setq truncate-lines t)
  10504. (set-buffer-modified-p nil)
  10505. (setq buffer-read-only t)
  10506. (run-hooks 'js2-error-buffer-mode-hook))
  10507. (defun js2-error-buffer-next ()
  10508. "Move to next error and view it."
  10509. (interactive)
  10510. (when (zerop (forward-line 1))
  10511. (js2-error-buffer-view)))
  10512. (defun js2-error-buffer-prev ()
  10513. "Move to previous error and view it."
  10514. (interactive)
  10515. (when (zerop (forward-line -1))
  10516. (js2-error-buffer-view)))
  10517. (defun js2-error-buffer-quit ()
  10518. "Kill the current buffer."
  10519. (interactive)
  10520. (kill-buffer))
  10521. (defun js2-error-buffer-jump (&rest ignored)
  10522. "Jump cursor to current error in source buffer."
  10523. (interactive)
  10524. (when (js2-error-buffer-view)
  10525. (pop-to-buffer js2-source-buffer)))
  10526. (defun js2-error-buffer-view ()
  10527. "Scroll source buffer to show error at current line."
  10528. (interactive)
  10529. (cond
  10530. ((not (eq major-mode 'js2-error-buffer-mode))
  10531. (message "Not in a js2 errors buffer"))
  10532. ((not (buffer-live-p js2-source-buffer))
  10533. (message "Source buffer has been killed"))
  10534. ((not (wholenump (get-text-property (point) 'js2-pos)))
  10535. (message "There does not seem to be an error here"))
  10536. (t
  10537. (let ((pos (get-text-property (point) 'js2-pos))
  10538. (msg (get-text-property (point) 'js2-msg)))
  10539. (save-selected-window
  10540. (pop-to-buffer js2-source-buffer)
  10541. (goto-char pos)
  10542. (message msg))))))
  10543. ;;;###autoload
  10544. (define-derived-mode js2-mode js-mode "Javascript-IDE"
  10545. "Major mode for editing JavaScript code."
  10546. (set (make-local-variable 'max-lisp-eval-depth)
  10547. (max max-lisp-eval-depth 3000))
  10548. (set (make-local-variable 'indent-line-function) #'js2-indent-line)
  10549. (set (make-local-variable 'indent-region-function) #'js2-indent-region)
  10550. (set (make-local-variable 'syntax-propertize-function) nil)
  10551. (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
  10552. (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
  10553. (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
  10554. ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
  10555. ;; for characters inside regexp literals.
  10556. (set (make-local-variable 'parse-sexp-lookup-properties) t)
  10557. ;; this is necessary to make `show-paren-function' work properly
  10558. (set (make-local-variable 'parse-sexp-ignore-comments) t)
  10559. ;; needed for M-x rgrep, among other things
  10560. (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
  10561. (setq font-lock-defaults '(nil t))
  10562. ;; Experiment: make reparse-delay longer for longer files.
  10563. (when (cl-plusp js2-dynamic-idle-timer-adjust)
  10564. (setq js2-idle-timer-delay
  10565. (* js2-idle-timer-delay
  10566. (/ (point-max) js2-dynamic-idle-timer-adjust))))
  10567. (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
  10568. (add-hook 'after-change-functions #'js2-mode-edit nil t)
  10569. (setq imenu-create-index-function #'js2-mode-create-imenu-index)
  10570. (setq next-error-function #'js2-next-error)
  10571. (imenu-add-to-menubar (concat "IM-" mode-name))
  10572. (add-to-invisibility-spec '(js2-outline . t))
  10573. (set (make-local-variable 'line-move-ignore-invisible) t)
  10574. (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
  10575. (when (fboundp 'cursor-sensor-mode) (cursor-sensor-mode 1))
  10576. (setq js2-mode-functions-hidden nil
  10577. js2-mode-comments-hidden nil
  10578. js2-mode-buffer-dirty-p t
  10579. js2-mode-parsing nil)
  10580. (when js2-include-jslint-globals
  10581. (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
  10582. (when js2-include-jslint-declaration-externs
  10583. (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-declaration-externs nil t))
  10584. (run-hooks 'js2-init-hook)
  10585. (let ((js2-idle-timer-delay 0))
  10586. ;; Schedule parsing for after when the mode hooks run.
  10587. (js2-mode-reset-timer)))
  10588. ;;;###autoload
  10589. (define-derived-mode js2-jsx-mode js2-mode "JSX-IDE"
  10590. "Major mode for editing JSX code in Emacs 26 and earlier.
  10591. To edit JSX code in Emacs 27, use `js-mode' as your major mode
  10592. with `js2-minor-mode' enabled.
  10593. To customize the indentation for this mode, set the SGML offset
  10594. variables (`sgml-basic-offset' et al) locally, like so:
  10595. (defun set-jsx-indentation ()
  10596. (setq-local sgml-basic-offset js2-basic-offset))
  10597. (add-hook \\='js2-jsx-mode-hook #\\='set-jsx-indentation)"
  10598. (unless (version< emacs-version "27.0")
  10599. ;; Emacs 27 causes a regression in this mode since JSX indentation
  10600. ;; begins to rely on js-mode’s `syntax-propertize-function', which
  10601. ;; JS2 is not currently using.
  10602. ;; https://github.com/mooz/js2-mode/issues/529 should address
  10603. ;; this. https://github.com/mooz/js2-mode/issues/530 also has a
  10604. ;; piece related to the design of `js2-jsx-mode'. Until these
  10605. ;; issues are addressed, ward Emacs 27 users away from this mode.
  10606. (display-warning 'js2-mode "For JSX support, use js-mode with js2-minor-mode"))
  10607. (set (make-local-variable 'indent-line-function) #'js2-jsx-indent-line))
  10608. (defun js2-mode-exit ()
  10609. "Exit `js2-mode' and clean up."
  10610. (interactive)
  10611. (when js2-mode-node-overlay
  10612. (delete-overlay js2-mode-node-overlay)
  10613. (setq js2-mode-node-overlay nil))
  10614. (js2-remove-overlays)
  10615. (setq js2-mode-ast nil)
  10616. (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
  10617. (remove-from-invisibility-spec '(js2-outline . t))
  10618. (js2-mode-show-all)
  10619. (with-silent-modifications
  10620. (js2-clear-face (point-min) (point-max))))
  10621. (defun js2-mode-reset-timer ()
  10622. "Cancel any existing parse timer and schedule a new one."
  10623. (if js2-mode-parse-timer
  10624. (cancel-timer js2-mode-parse-timer))
  10625. (setq js2-mode-parsing nil)
  10626. (let ((timer (timer-create)))
  10627. (setq js2-mode-parse-timer timer)
  10628. (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
  10629. (timer-set-idle-time timer js2-idle-timer-delay)
  10630. ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
  10631. (timer-activate-when-idle timer nil)))
  10632. (defun js2-mode-idle-reparse (buffer)
  10633. "Run `js2-reparse' if BUFFER is the current buffer, or schedule
  10634. it to be reparsed when the buffer is selected."
  10635. (cond ((eq buffer (current-buffer))
  10636. (js2-reparse))
  10637. ((buffer-live-p buffer)
  10638. ;; reparse when the buffer is selected again
  10639. (with-current-buffer buffer
  10640. (add-hook 'window-configuration-change-hook
  10641. #'js2-mode-idle-reparse-inner
  10642. nil t)))))
  10643. (defun js2-mode-idle-reparse-inner ()
  10644. (remove-hook 'window-configuration-change-hook
  10645. #'js2-mode-idle-reparse-inner
  10646. t)
  10647. (js2-reparse))
  10648. (defun js2-mode-edit (_beg _end _len)
  10649. "Schedule a new parse after buffer is edited.
  10650. Buffer edit spans from BEG to END and is of length LEN."
  10651. (setq js2-mode-buffer-dirty-p t)
  10652. (js2-mode-hide-overlay)
  10653. (js2-mode-reset-timer))
  10654. (defun js2-minor-mode-edit (_beg _end _len)
  10655. "Callback for buffer edits in `js2-mode'.
  10656. Schedules a new parse after buffer is edited.
  10657. Buffer edit spans from BEG to END and is of length LEN."
  10658. (setq js2-mode-buffer-dirty-p t)
  10659. (js2-mode-hide-overlay)
  10660. (js2-mode-reset-timer))
  10661. (defun js2-reparse (&optional force)
  10662. "Re-parse current buffer after user finishes some data entry.
  10663. If we get any user input while parsing, including cursor motion,
  10664. we discard the parse and reschedule it. If FORCE is nil, then the
  10665. buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
  10666. (let (time
  10667. interrupted-p
  10668. (js2-compiler-strict-mode js2-mode-show-strict-warnings))
  10669. (unless js2-mode-parsing
  10670. (setq js2-mode-parsing t)
  10671. (unwind-protect
  10672. (when (or js2-mode-buffer-dirty-p force)
  10673. (js2-remove-overlays)
  10674. (setq js2-mode-buffer-dirty-p nil
  10675. js2-mode-fontifications nil
  10676. js2-mode-deferred-properties nil)
  10677. (if js2-mode-verbose-parse-p
  10678. (message "parsing..."))
  10679. (setq time
  10680. (js2-time
  10681. (setq interrupted-p
  10682. (catch 'interrupted
  10683. (js2-parse)
  10684. (with-silent-modifications
  10685. ;; if parsing is interrupted, comments and regex
  10686. ;; literals stay ignored by `parse-partial-sexp'
  10687. (when js2-mode-change-syntax-p
  10688. (remove-text-properties (point-min) (point-max)
  10689. '(syntax-table)))
  10690. (js2-mode-apply-deferred-properties)
  10691. (js2-mode-remove-suppressed-warnings)
  10692. (js2-mode-show-warnings)
  10693. (js2-mode-show-errors)
  10694. (if (>= js2-highlight-level 1)
  10695. (js2-highlight-jsdoc js2-mode-ast)))
  10696. nil))))
  10697. (if interrupted-p
  10698. (progn
  10699. ;; unfinished parse => try again
  10700. (setq js2-mode-buffer-dirty-p t)
  10701. (js2-mode-reset-timer))
  10702. (if js2-mode-verbose-parse-p
  10703. (message "Parse time: %s" time))))
  10704. (setq js2-mode-parsing nil)
  10705. (unless interrupted-p
  10706. (setq js2-mode-parse-timer nil))))))
  10707. ;; We bound it to [mouse-1] previously. But the signature of
  10708. ;; mouse-set-point changed around 24.4, so it's kind of hard to keep
  10709. ;; it working in 24.1-24.3. Since the command is not hugely
  10710. ;; important, we removed the binding (#356). Maybe we'll bring it
  10711. ;; back when supporting <24.4 is not a goal anymore.
  10712. (defun js2-mode-show-node (event &optional promote-to-region)
  10713. "Debugging aid: highlight selected AST node on mouse click."
  10714. (interactive "e\np")
  10715. (mouse-set-point event promote-to-region)
  10716. (when js2-mode-show-overlay
  10717. (let ((node (js2-node-at-point))
  10718. beg end)
  10719. (if (null node)
  10720. (message "No node found at location %s" (point))
  10721. (setq beg (js2-node-abs-pos node)
  10722. end (+ beg (js2-node-len node)))
  10723. (if js2-mode-node-overlay
  10724. (move-overlay js2-mode-node-overlay beg end)
  10725. (setq js2-mode-node-overlay (make-overlay beg end))
  10726. (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
  10727. (with-silent-modifications
  10728. (if (fboundp 'cursor-sensor-mode)
  10729. (put-text-property beg end 'cursor-sensor-functions
  10730. '(js2-mode-hide-overlay))
  10731. (put-text-property beg end 'point-left #'js2-mode-hide-overlay)))
  10732. (message "%s, parent: %s"
  10733. (js2-node-short-name node)
  10734. (if (js2-node-parent node)
  10735. (js2-node-short-name (js2-node-parent node))
  10736. "nil"))))))
  10737. (defun js2-mode-hide-overlay (&optional arg1 arg2 _arg3)
  10738. "Remove the debugging overlay when point moves.
  10739. ARG1, ARG2 and ARG3 have different values depending on whether this function
  10740. was found on `point-left' or in `cursor-sensor-functions'."
  10741. (when js2-mode-node-overlay
  10742. (let ((beg (overlay-start js2-mode-node-overlay))
  10743. (end (overlay-end js2-mode-node-overlay))
  10744. (p2 (if (windowp arg1)
  10745. ;; Called from cursor-sensor-functions.
  10746. (window-point arg1)
  10747. ;; Called from point-left.
  10748. arg2)))
  10749. ;; Sometimes we're called spuriously.
  10750. (unless (and p2
  10751. (>= p2 beg)
  10752. (<= p2 end))
  10753. (with-silent-modifications
  10754. (remove-text-properties beg end
  10755. '(point-left nil cursor-sensor-functions)))
  10756. (delete-overlay js2-mode-node-overlay)
  10757. (setq js2-mode-node-overlay nil)))))
  10758. (defun js2-mode-reset ()
  10759. "Debugging helper: reset everything."
  10760. (interactive)
  10761. (js2-mode-exit)
  10762. (js2-mode))
  10763. (defun js2-mode-show-warn-or-err (e face)
  10764. "Highlight a warning or error E with FACE.
  10765. E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
  10766. The last element is optional. When present, use instead of FACE."
  10767. (let* ((key (cl-first e))
  10768. (beg (cl-second e))
  10769. (end (+ beg (cl-third e)))
  10770. ;; Don't inadvertently go out of bounds.
  10771. (beg (max (point-min) (min beg (point-max))))
  10772. (end (max (point-min) (min end (point-max))))
  10773. (ovl (make-overlay beg end)))
  10774. ;; FIXME: Why a mix of overlays and text-properties?
  10775. (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
  10776. (overlay-put ovl 'js2-error t)
  10777. (put-text-property beg end 'help-echo (js2-get-msg key))
  10778. (if (fboundp 'cursor-sensor-mode)
  10779. (put-text-property beg end 'cursor-sensor-functions '(js2-echo-error))
  10780. (put-text-property beg end 'point-entered #'js2-echo-error))))
  10781. (defun js2-remove-overlays ()
  10782. "Remove overlays from buffer that have a `js2-error' property."
  10783. (let ((beg (point-min))
  10784. (end (point-max)))
  10785. (save-excursion
  10786. (dolist (o (overlays-in beg end))
  10787. (when (overlay-get o 'js2-error)
  10788. (delete-overlay o))))))
  10789. (defun js2-mode-apply-deferred-properties ()
  10790. "Apply fontifications and other text properties recorded during parsing."
  10791. (when (cl-plusp js2-highlight-level)
  10792. ;; We defer clearing faces as long as possible to eliminate flashing.
  10793. (js2-clear-face (point-min) (point-max))
  10794. ;; Have to reverse the recorded fontifications list so that errors
  10795. ;; and warnings overwrite the normal fontifications.
  10796. (dolist (f (nreverse js2-mode-fontifications))
  10797. (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
  10798. (setq js2-mode-fontifications nil))
  10799. (dolist (p js2-mode-deferred-properties)
  10800. (apply #'put-text-property p))
  10801. (setq js2-mode-deferred-properties nil))
  10802. (defun js2-mode-show-errors ()
  10803. "Highlight syntax errors."
  10804. (when js2-mode-show-parse-errors
  10805. (dolist (e (js2-ast-root-errors js2-mode-ast))
  10806. (js2-mode-show-warn-or-err e 'js2-error))))
  10807. (defun js2-mode-remove-suppressed-warnings ()
  10808. "Take suppressed warnings out of the AST warnings list.
  10809. This ensures that the counts and `next-error' are correct."
  10810. (setf (js2-ast-root-warnings js2-mode-ast)
  10811. (js2-delete-if
  10812. (lambda (e)
  10813. (let ((key (caar e)))
  10814. (or
  10815. (and (not js2-strict-trailing-comma-warning)
  10816. (string-match "trailing\\.comma" key))
  10817. (and (not js2-strict-cond-assign-warning)
  10818. (string= key "msg.equal.as.assign"))
  10819. (and js2-missing-semi-one-line-override
  10820. (string= key "msg.missing.semi")
  10821. (let* ((beg (cl-second e))
  10822. (node (js2-node-at-point beg))
  10823. (fn (js2-mode-find-parent-fn node))
  10824. (body (and fn (js2-function-node-body fn)))
  10825. (lc (and body (js2-node-abs-pos body)))
  10826. (rc (and lc (+ lc (js2-node-len body)))))
  10827. (and fn
  10828. (or (null body)
  10829. (save-excursion
  10830. (goto-char beg)
  10831. (and (js2-same-line lc)
  10832. (js2-same-line rc))))))))))
  10833. (js2-ast-root-warnings js2-mode-ast))))
  10834. (defun js2-mode-show-warnings ()
  10835. "Highlight strict-mode warnings."
  10836. (when js2-mode-show-strict-warnings
  10837. (dolist (e (js2-ast-root-warnings js2-mode-ast))
  10838. (js2-mode-show-warn-or-err e 'js2-warning))))
  10839. (defun js2-echo-error (arg1 arg2 &optional _arg3)
  10840. "Called by point-motion hooks.
  10841. ARG1, ARG2 and ARG3 have different values depending on whether this function
  10842. was found on `point-entered' or in `cursor-sensor-functions'."
  10843. (let* ((new-point (if (windowp arg1)
  10844. ;; Called from cursor-sensor-functions.
  10845. (window-point arg1)
  10846. ;; Called from point-left.
  10847. arg2))
  10848. (msg (get-text-property new-point 'help-echo)))
  10849. (when (and (stringp msg)
  10850. (not (active-minibuffer-window))
  10851. (not (current-message)))
  10852. (message msg))))
  10853. (defun js2-line-break (&optional _soft)
  10854. "Break line at point and indent, continuing comment if within one.
  10855. If inside a string, and `js2-concat-multiline-strings' is not
  10856. nil, turn it into concatenation."
  10857. (interactive)
  10858. (let ((parse-status (syntax-ppss)))
  10859. (cond
  10860. ;; Check if we're inside a string.
  10861. ((nth 3 parse-status)
  10862. (if js2-concat-multiline-strings
  10863. (js2-mode-split-string parse-status)
  10864. (insert "\n")))
  10865. ;; Check if inside a block comment.
  10866. ((nth 4 parse-status)
  10867. (js2-mode-extend-comment (nth 8 parse-status)))
  10868. (t
  10869. (newline-and-indent)))))
  10870. (defun js2-mode-split-string (parse-status)
  10871. "Turn a newline in mid-string into a string concatenation.
  10872. PARSE-STATUS is as documented in `parse-partial-sexp'."
  10873. (let* ((quote-char (nth 3 parse-status))
  10874. (at-eol (eq js2-concat-multiline-strings 'eol)))
  10875. (insert quote-char)
  10876. (insert (if at-eol " +\n" "\n"))
  10877. (unless at-eol
  10878. (insert "+ "))
  10879. (js2-indent-line)
  10880. (insert quote-char)
  10881. (when (eolp)
  10882. (insert quote-char)
  10883. (backward-char 1))))
  10884. (defun js2-mode-extend-comment (start-pos)
  10885. "Indent the line and, when inside a comment block, add comment prefix."
  10886. (let (star single col first-line needs-close)
  10887. (save-excursion
  10888. (back-to-indentation)
  10889. (when (< (point) start-pos)
  10890. (goto-char start-pos))
  10891. (cond
  10892. ((looking-at "\\*[^/]")
  10893. (setq star t
  10894. col (current-column)))
  10895. ((looking-at "/\\*")
  10896. (setq star t
  10897. first-line t
  10898. col (1+ (current-column))))
  10899. ((looking-at "//")
  10900. (setq single t
  10901. col (current-column)))))
  10902. ;; Heuristic for whether we need to close the comment:
  10903. ;; if we've got a parse error here, assume it's an unterminated
  10904. ;; comment.
  10905. (setq needs-close
  10906. (or
  10907. (get-char-property (1- (point)) 'js2-error)
  10908. ;; The heuristic above doesn't work well when we're
  10909. ;; creating a comment and there's another one downstream,
  10910. ;; as our parser thinks this one ends at the end of the
  10911. ;; next one. (You can have a /* inside a js block comment.)
  10912. ;; So just close it if the next non-ws char isn't a *.
  10913. (and first-line
  10914. (eolp)
  10915. (save-excursion
  10916. (skip-chars-forward " \t\r\n")
  10917. (not (eq (char-after) ?*))))))
  10918. (delete-horizontal-space)
  10919. (insert "\n")
  10920. (cond
  10921. (star
  10922. (indent-to col)
  10923. (insert "* ")
  10924. (if (and first-line needs-close)
  10925. (save-excursion
  10926. (insert "\n")
  10927. (indent-to col)
  10928. (insert "*/"))))
  10929. (single
  10930. (indent-to col)
  10931. (insert "// ")))
  10932. ;; Don't need to extend the comment after all.
  10933. (js2-indent-line)))
  10934. (defun js2-beginning-of-line ()
  10935. "Toggle point between bol and first non-whitespace char in line.
  10936. Also moves past comment delimiters when inside comments."
  10937. (interactive)
  10938. (let (node)
  10939. (cond
  10940. ((bolp)
  10941. (back-to-indentation))
  10942. ((looking-at "//")
  10943. (skip-chars-forward "/ \t"))
  10944. ((and (eq (char-after) ?*)
  10945. (setq node (js2-comment-at-point))
  10946. (memq (js2-comment-node-format node) '(jsdoc block))
  10947. (save-excursion
  10948. (skip-chars-backward " \t")
  10949. (bolp)))
  10950. (skip-chars-forward "\* \t"))
  10951. (t
  10952. (goto-char (point-at-bol))))))
  10953. (defun js2-end-of-line ()
  10954. "Toggle point between eol and last non-whitespace char in line."
  10955. (interactive)
  10956. (if (eolp)
  10957. (skip-chars-backward " \t")
  10958. (goto-char (point-at-eol))))
  10959. (defun js2-mode-wait-for-parse (callback)
  10960. "Invoke CALLBACK when parsing is finished.
  10961. If parsing is already finished, calls CALLBACK immediately."
  10962. (if (not js2-mode-buffer-dirty-p)
  10963. (funcall callback)
  10964. (push callback js2-mode-pending-parse-callbacks)
  10965. (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
  10966. (defun js2-mode-parse-finished ()
  10967. "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
  10968. ;; We can't let errors propagate up, since it prevents the
  10969. ;; `js2-parse' method from completing normally and returning
  10970. ;; the ast, which makes things mysteriously not work right.
  10971. (unwind-protect
  10972. (dolist (cb js2-mode-pending-parse-callbacks)
  10973. (condition-case err
  10974. (funcall cb)
  10975. (error (message "%s" err))))
  10976. (setq js2-mode-pending-parse-callbacks nil)))
  10977. (defun js2-mode-flag-region (from to flag)
  10978. "Hide or show text from FROM to TO, according to FLAG.
  10979. If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
  10980. Returns the created overlay if FLAG is non-nil."
  10981. (remove-overlays from to 'invisible 'js2-outline)
  10982. (when flag
  10983. (let ((o (make-overlay from to)))
  10984. (overlay-put o 'invisible 'js2-outline)
  10985. (overlay-put o 'isearch-open-invisible
  10986. 'js2-isearch-open-invisible)
  10987. o)))
  10988. ;; Function to be set as an outline-isearch-open-invisible' property
  10989. ;; to the overlay that makes the outline invisible (see
  10990. ;; `js2-mode-flag-region').
  10991. (defun js2-isearch-open-invisible (_overlay)
  10992. ;; We rely on the fact that isearch places point on the matched text.
  10993. (js2-mode-show-element))
  10994. (defun js2-mode-invisible-overlay-bounds (&optional pos)
  10995. "Return cons cell of bounds of folding overlay at POS.
  10996. Returns nil if not found."
  10997. (let ((overlays (overlays-at (or pos (point))))
  10998. o)
  10999. (while (and overlays
  11000. (not o))
  11001. (if (overlay-get (car overlays) 'invisible)
  11002. (setq o (car overlays))
  11003. (setq overlays (cdr overlays))))
  11004. (if o
  11005. (cons (overlay-start o) (overlay-end o)))))
  11006. (defun js2-mode-function-at-point (&optional pos)
  11007. "Return the innermost function node enclosing current point.
  11008. Returns nil if point is not in a function."
  11009. (let ((node (js2-node-at-point pos)))
  11010. (while (and node (not (js2-function-node-p node)))
  11011. (setq node (js2-node-parent node)))
  11012. (if (js2-function-node-p node)
  11013. node)))
  11014. (defun js2-mode-toggle-element ()
  11015. "Hide or show the foldable element at the point."
  11016. (interactive)
  11017. (let (comment fn pos)
  11018. (save-excursion
  11019. (cond
  11020. ;; /* ... */ comment?
  11021. ((js2-block-comment-p (setq comment (js2-comment-at-point)))
  11022. (if (js2-mode-invisible-overlay-bounds
  11023. (setq pos (+ 3 (js2-node-abs-pos comment))))
  11024. (progn
  11025. (goto-char pos)
  11026. (js2-mode-show-element))
  11027. (js2-mode-hide-element)))
  11028. ;; //-comment?
  11029. ((save-excursion
  11030. (back-to-indentation)
  11031. (looking-at js2-mode-//-comment-re))
  11032. (js2-mode-toggle-//-comment))
  11033. ;; function?
  11034. ((setq fn (js2-mode-function-at-point))
  11035. (setq pos (and (js2-function-node-body fn)
  11036. (js2-node-abs-pos (js2-function-node-body fn))))
  11037. (goto-char (1+ pos))
  11038. (if (js2-mode-invisible-overlay-bounds)
  11039. (js2-mode-show-element)
  11040. (js2-mode-hide-element)))
  11041. (t
  11042. (message "Nothing at point to hide or show"))))))
  11043. (defun js2-mode-hide-element ()
  11044. "Fold/hide contents of a block, showing ellipses.
  11045. Show the hidden text with \\[js2-mode-show-element]."
  11046. (interactive)
  11047. (if js2-mode-buffer-dirty-p
  11048. (js2-mode-wait-for-parse #'js2-mode-hide-element))
  11049. (let (node body beg end)
  11050. (cond
  11051. ((js2-mode-invisible-overlay-bounds)
  11052. (message "already hidden"))
  11053. (t
  11054. (setq node (js2-node-at-point))
  11055. (cond
  11056. ((js2-block-comment-p node)
  11057. (js2-mode-hide-comment node))
  11058. (t
  11059. (while (and node (not (js2-function-node-p node)))
  11060. (setq node (js2-node-parent node)))
  11061. (if (and node
  11062. (setq body (js2-function-node-body node)))
  11063. (progn
  11064. (setq beg (js2-node-abs-pos body)
  11065. end (+ beg (js2-node-len body)))
  11066. (js2-mode-flag-region (1+ beg) (1- end) 'hide))
  11067. (message "No collapsable element found at point"))))))))
  11068. (defun js2-mode-show-element ()
  11069. "Show the hidden element at current point."
  11070. (interactive)
  11071. (let ((bounds (js2-mode-invisible-overlay-bounds)))
  11072. (if bounds
  11073. (js2-mode-flag-region (car bounds) (cdr bounds) nil)
  11074. (message "Nothing to un-hide"))))
  11075. (defun js2-mode-show-all ()
  11076. "Show all of the text in the buffer."
  11077. (interactive)
  11078. (js2-mode-flag-region (point-min) (point-max) nil))
  11079. (defun js2-mode-toggle-hide-functions ()
  11080. (interactive)
  11081. (if js2-mode-functions-hidden
  11082. (js2-mode-show-functions)
  11083. (js2-mode-hide-functions)))
  11084. (defun js2-mode-hide-functions ()
  11085. "Hides all non-nested function bodies in the buffer.
  11086. Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
  11087. to open an individual entry."
  11088. (interactive)
  11089. (if js2-mode-buffer-dirty-p
  11090. (js2-mode-wait-for-parse #'js2-mode-hide-functions))
  11091. (if (null js2-mode-ast)
  11092. (message "Oops - parsing failed")
  11093. (setq js2-mode-functions-hidden t)
  11094. (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
  11095. (defun js2-mode-function-hider (n endp)
  11096. (when (not endp)
  11097. (let ((tt (js2-node-type n))
  11098. body beg end)
  11099. (cond
  11100. ((and (= tt js2-FUNCTION)
  11101. (setq body (js2-function-node-body n)))
  11102. (setq beg (js2-node-abs-pos body)
  11103. end (+ beg (js2-node-len body)))
  11104. (js2-mode-flag-region (1+ beg) (1- end) 'hide)
  11105. nil) ; don't process children of function
  11106. (t
  11107. t))))) ; keep processing other AST nodes
  11108. (defun js2-mode-show-functions ()
  11109. "Un-hide any folded function bodies in the buffer."
  11110. (interactive)
  11111. (setq js2-mode-functions-hidden nil)
  11112. (save-excursion
  11113. (goto-char (point-min))
  11114. (while (/= (goto-char (next-overlay-change (point)))
  11115. (point-max))
  11116. (dolist (o (overlays-at (point)))
  11117. (when (and (overlay-get o 'invisible)
  11118. (not (overlay-get o 'comment)))
  11119. (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
  11120. (defun js2-mode-hide-comment (n)
  11121. (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
  11122. 3 ; /**
  11123. 2)) ; /*
  11124. (beg (+ (js2-node-abs-pos n) head))
  11125. (end (- (+ beg (js2-node-len n)) head 2))
  11126. (o (js2-mode-flag-region beg end 'hide)))
  11127. (overlay-put o 'comment t)))
  11128. (defun js2-mode-toggle-hide-comments ()
  11129. "Folds all block comments in the buffer.
  11130. Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
  11131. to open an individual entry."
  11132. (interactive)
  11133. (if js2-mode-comments-hidden
  11134. (js2-mode-show-comments)
  11135. (js2-mode-hide-comments)))
  11136. (defun js2-mode-hide-comments ()
  11137. (interactive)
  11138. (if js2-mode-buffer-dirty-p
  11139. (js2-mode-wait-for-parse #'js2-mode-hide-comments))
  11140. (if (null js2-mode-ast)
  11141. (message "Oops - parsing failed")
  11142. (setq js2-mode-comments-hidden t)
  11143. (dolist (n (js2-ast-root-comments js2-mode-ast))
  11144. (when (js2-block-comment-p n)
  11145. (js2-mode-hide-comment n)))
  11146. (js2-mode-hide-//-comments)))
  11147. (defun js2-mode-extend-//-comment (direction)
  11148. "Find start or end of a block of similar //-comment lines.
  11149. DIRECTION is -1 to look back, 1 to look forward.
  11150. INDENT is the indentation level to match.
  11151. Returns the end-of-line position of the furthest adjacent
  11152. //-comment line with the same indentation as the current line.
  11153. If there is no such matching line, returns current end of line."
  11154. (let ((pos (point-at-eol))
  11155. (indent (current-indentation)))
  11156. (save-excursion
  11157. (while (and (zerop (forward-line direction))
  11158. (looking-at js2-mode-//-comment-re)
  11159. (eq indent (length (match-string 1))))
  11160. (setq pos (point-at-eol)))
  11161. pos)))
  11162. (defun js2-mode-hide-//-comments ()
  11163. "Fold adjacent 1-line comments, showing only snippet of first one."
  11164. (let (beg end)
  11165. (save-excursion
  11166. (goto-char (point-min))
  11167. (while (re-search-forward js2-mode-//-comment-re nil t)
  11168. (setq beg (point)
  11169. end (js2-mode-extend-//-comment 1))
  11170. (unless (eq beg end)
  11171. (overlay-put (js2-mode-flag-region beg end 'hide)
  11172. 'comment t))
  11173. (goto-char end)
  11174. (forward-char 1)))))
  11175. (defun js2-mode-toggle-//-comment ()
  11176. "Fold or un-fold any multi-line //-comment at point.
  11177. Caller should have determined that this line starts with a //-comment."
  11178. (let* ((beg (point-at-eol))
  11179. (end beg))
  11180. (save-excursion
  11181. (goto-char end)
  11182. (if (js2-mode-invisible-overlay-bounds)
  11183. (js2-mode-show-element)
  11184. ;; else hide the comment
  11185. (setq beg (js2-mode-extend-//-comment -1)
  11186. end (js2-mode-extend-//-comment 1))
  11187. (unless (eq beg end)
  11188. (overlay-put (js2-mode-flag-region beg end 'hide)
  11189. 'comment t))))))
  11190. (defun js2-mode-show-comments ()
  11191. "Un-hide any hidden comments, leaving other hidden elements alone."
  11192. (interactive)
  11193. (setq js2-mode-comments-hidden nil)
  11194. (save-excursion
  11195. (goto-char (point-min))
  11196. (while (/= (goto-char (next-overlay-change (point)))
  11197. (point-max))
  11198. (dolist (o (overlays-at (point)))
  11199. (when (overlay-get o 'comment)
  11200. (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
  11201. (defun js2-mode-display-warnings-and-errors ()
  11202. "Turn on display of warnings and errors."
  11203. (interactive)
  11204. (setq js2-mode-show-parse-errors t
  11205. js2-mode-show-strict-warnings t)
  11206. (js2-reparse 'force))
  11207. (defun js2-mode-hide-warnings-and-errors ()
  11208. "Turn off display of warnings and errors."
  11209. (interactive)
  11210. (setq js2-mode-show-parse-errors nil
  11211. js2-mode-show-strict-warnings nil)
  11212. (js2-reparse 'force))
  11213. (defun js2-mode-toggle-warnings-and-errors ()
  11214. "Toggle the display of warnings and errors.
  11215. Some users don't like having warnings/errors reported while they type."
  11216. (interactive)
  11217. (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
  11218. js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
  11219. (if (called-interactively-p 'any)
  11220. (message "warnings and errors %s"
  11221. (if js2-mode-show-parse-errors
  11222. "enabled"
  11223. "disabled")))
  11224. (js2-reparse 'force))
  11225. (defun js2-mode-customize ()
  11226. (interactive)
  11227. (customize-group 'js2-mode))
  11228. (defun js2-mode-forward-sexp (&optional arg)
  11229. "Move forward across one statement or balanced expression.
  11230. With ARG, do it that many times. Negative arg -N means
  11231. move backward across N balanced expressions."
  11232. (interactive "p")
  11233. (setq arg (or arg 1))
  11234. (save-restriction
  11235. (widen) ;; `blink-matching-open' calls `narrow-to-region'
  11236. (js2-reparse)
  11237. (let (forward-sexp-function
  11238. node (start (point)) pos lp rp child)
  11239. (cond
  11240. ((js2-string-node-p (js2-node-at-point))
  11241. (forward-sexp arg))
  11242. ;; backward-sexp
  11243. ;; could probably make this better for some cases:
  11244. ;; - if in statement block (e.g. function body), go to parent
  11245. ;; - infix exprs like (foo in bar) - maybe go to beginning
  11246. ;; of infix expr if in the right-side expression?
  11247. ((and arg (cl-minusp arg))
  11248. (dotimes (_ (- arg))
  11249. (js2-backward-sws)
  11250. (forward-char -1) ; Enter the node we backed up to.
  11251. (when (setq node (js2-node-at-point (point) t))
  11252. (setq pos (js2-node-abs-pos node))
  11253. (let ((parens (js2-mode-forward-sexp-parens node pos)))
  11254. (setq lp (car parens)
  11255. rp (cdr parens)))
  11256. (when (and lp (> start lp))
  11257. (if (and rp (<= start rp))
  11258. ;; Between parens, check if there's a child node we can jump.
  11259. (when (setq child (js2-node-closest-child node (point) lp t))
  11260. (setq pos (js2-node-abs-pos child)))
  11261. ;; Before both parens.
  11262. (setq pos lp)))
  11263. (let ((state (parse-partial-sexp start pos)))
  11264. (goto-char (if (not (zerop (car state)))
  11265. ;; Stumble at the unbalanced paren if < 0, or
  11266. ;; jump a bit further if > 0.
  11267. (scan-sexps start -1)
  11268. pos))))
  11269. (unless pos (goto-char (point-min)))))
  11270. (t
  11271. ;; forward-sexp
  11272. (dotimes (_ arg)
  11273. (js2-forward-sws)
  11274. (when (setq node (js2-node-at-point (point) t))
  11275. (setq pos (js2-node-abs-pos node))
  11276. (let ((parens (js2-mode-forward-sexp-parens node pos)))
  11277. (setq lp (car parens)
  11278. rp (cdr parens)))
  11279. (or
  11280. (when (and rp (<= start rp))
  11281. (if (> start lp)
  11282. (when (setq child (js2-node-closest-child node (point) rp))
  11283. (setq pos (js2-node-abs-end child)))
  11284. (setq pos (1+ rp))))
  11285. ;; No parens or child nodes, looks for the end of the current node.
  11286. (cl-incf pos (js2-node-len
  11287. (if (js2-expr-stmt-node-p (js2-node-parent node))
  11288. ;; Stop after the semicolon.
  11289. (js2-node-parent node)
  11290. node))))
  11291. (let ((state (save-excursion (parse-partial-sexp start pos))))
  11292. (goto-char (if (not (zerop (car state)))
  11293. (scan-sexps start 1)
  11294. pos))))
  11295. (unless pos (goto-char (point-max)))))))))
  11296. (defun js2-mode-forward-sexp-parens (node abs-pos)
  11297. "Return a cons cell with positions of main parens in NODE."
  11298. (cond
  11299. ((or (js2-array-node-p node)
  11300. (js2-object-node-p node)
  11301. (js2-comp-node-p node)
  11302. (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
  11303. (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
  11304. ((js2-paren-expr-node-p node)
  11305. (let ((lp (js2-node-lp node))
  11306. (rp (js2-node-rp node)))
  11307. (cons (when lp (+ abs-pos lp))
  11308. (when rp (+ abs-pos rp)))))))
  11309. (defun js2-node-closest-child (parent point limit &optional before)
  11310. (let* ((parent-pos (js2-node-abs-pos parent))
  11311. (rpoint (- point parent-pos))
  11312. (rlimit (- limit parent-pos))
  11313. (min (min rpoint rlimit))
  11314. (max (max rpoint rlimit))
  11315. found)
  11316. (catch 'done
  11317. (js2-visit-ast
  11318. parent
  11319. (lambda (node _end-p)
  11320. (if (eq node parent)
  11321. t
  11322. (let ((pos (js2-node-pos node)) ;; Both relative values.
  11323. (end (+ (js2-node-pos node) (js2-node-len node))))
  11324. (when (and (>= pos min) (<= end max)
  11325. (if before (< pos rpoint) (> end rpoint)))
  11326. (setq found node))
  11327. (when (> end rpoint)
  11328. (throw 'done nil)))
  11329. nil))))
  11330. found))
  11331. (defun js2-errors ()
  11332. "Return a list of errors found."
  11333. (and js2-mode-ast
  11334. (js2-ast-root-errors js2-mode-ast)))
  11335. (defun js2-warnings ()
  11336. "Return a list of warnings found."
  11337. (and js2-mode-ast
  11338. (js2-ast-root-warnings js2-mode-ast)))
  11339. (defun js2-have-errors-p ()
  11340. "Return non-nil if any parse errors or warnings were found."
  11341. (or (js2-errors) (js2-warnings)))
  11342. (defun js2-errors-and-warnings ()
  11343. "Return a copy of the concatenated errors and warnings lists.
  11344. They are appended: first the errors, then the warnings.
  11345. Entries are of the form (MSG BEG END)."
  11346. (when js2-mode-ast
  11347. (append (js2-ast-root-errors js2-mode-ast)
  11348. (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
  11349. (defun js2-next-error (&optional arg reset)
  11350. "Move to next parse error.
  11351. Typically invoked via \\[next-error].
  11352. ARG is the number of errors, forward or backward, to move.
  11353. RESET means start over from the beginning."
  11354. (interactive "p")
  11355. (if (not (or (js2-errors) (js2-warnings)))
  11356. (message "No errors")
  11357. (when reset
  11358. (goto-char (point-min)))
  11359. (let* ((errs (js2-errors-and-warnings))
  11360. (continue t)
  11361. (start (point))
  11362. (count (or arg 1))
  11363. (backward (cl-minusp count))
  11364. (sorter (if backward '> '<))
  11365. (stopper (if backward '< '>))
  11366. (count (abs count))
  11367. all-errs err)
  11368. ;; Sort by start position.
  11369. (setq errs (sort errs (lambda (e1 e2)
  11370. (funcall sorter (cl-second e1) (cl-second e2))))
  11371. all-errs errs)
  11372. ;; Find nth error with pos > start.
  11373. (while (and errs continue)
  11374. (when (funcall stopper (cl-cadar errs) start)
  11375. (setq err (car errs))
  11376. (if (zerop (cl-decf count))
  11377. (setq continue nil)))
  11378. (setq errs (cdr errs)))
  11379. ;; Clear for `js2-echo-error'.
  11380. (message nil)
  11381. (if err
  11382. (goto-char (cl-second err))
  11383. ;; Wrap around to first error.
  11384. (goto-char (cl-second (car all-errs)))
  11385. ;; If we were already on it, echo msg again.
  11386. (if (= (point) start)
  11387. (js2-echo-error (point) (point)))))))
  11388. (defun js2-down-mouse-3 ()
  11389. "Make right-click move the point to the click location.
  11390. This makes right-click context menu operations a bit more intuitive.
  11391. The point will not move if the region is active, however, to avoid
  11392. destroying the region selection."
  11393. (interactive)
  11394. (when (and js2-move-point-on-right-click
  11395. (not mark-active))
  11396. (let ((e last-input-event))
  11397. (ignore-errors
  11398. (goto-char (cl-cadadr e))))))
  11399. (defun js2-mode-create-imenu-index ()
  11400. "Returns an alist for `imenu--index-alist'. Returns nil on first
  11401. scan if buffer size > `imenu-auto-rescan-maxout'."
  11402. (when (and (not js2-mode-ast)
  11403. (<= (buffer-size) imenu-auto-rescan-maxout))
  11404. (js2-reparse))
  11405. (when js2-mode-ast
  11406. ;; if we have an ast but no recorder, they're requesting a rescan
  11407. (unless js2-imenu-recorder
  11408. (js2-reparse 'force))
  11409. (prog1
  11410. (js2-build-imenu-index)
  11411. (setq js2-imenu-recorder nil
  11412. js2-imenu-function-map nil))))
  11413. (defun js2-mode-find-tag ()
  11414. "Replacement for `find-tag-default'.
  11415. `find-tag-default' returns a ridiculous answer inside comments."
  11416. (let (beg end)
  11417. (save-excursion
  11418. (if (looking-at "\\_>")
  11419. (setq beg (progn (forward-symbol -1) (point))
  11420. end (progn (forward-symbol 1) (point)))
  11421. (setq beg (progn (forward-symbol 1) (point))
  11422. end (progn (forward-symbol -1) (point))))
  11423. (replace-regexp-in-string
  11424. "[\"']" ""
  11425. (buffer-substring-no-properties beg end)))))
  11426. (defun js2-mode-forward-sibling ()
  11427. "Move to the end of the sibling following point in parent.
  11428. Returns non-nil if successful, or nil if there was no following sibling."
  11429. (let* ((node (js2-node-at-point))
  11430. (parent (js2-mode-find-enclosing-fn node))
  11431. sib)
  11432. (when (setq sib (js2-node-find-child-after (point) parent))
  11433. (goto-char (+ (js2-node-abs-pos sib)
  11434. (js2-node-len sib))))))
  11435. (defun js2-mode-backward-sibling ()
  11436. "Move to the beginning of the sibling node preceding point in parent.
  11437. Parent is defined as the enclosing script or function."
  11438. (let* ((node (js2-node-at-point))
  11439. (parent (js2-mode-find-enclosing-fn node))
  11440. sib)
  11441. (when (setq sib (js2-node-find-child-before (point) parent))
  11442. (goto-char (js2-node-abs-pos sib)))))
  11443. (defun js2-beginning-of-defun (&optional arg)
  11444. "Go to line on which current function starts, and return t on success.
  11445. If we're not in a function or already at the beginning of one, go
  11446. to beginning of previous script-level element.
  11447. With ARG N, do that N times. If N is negative, move forward."
  11448. (setq arg (or arg 1))
  11449. (if (cl-plusp arg)
  11450. (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
  11451. (when (cond
  11452. ((js2-function-node-p parent)
  11453. (goto-char (js2-node-abs-pos parent)))
  11454. (t
  11455. (js2-mode-backward-sibling)))
  11456. (if (> arg 1)
  11457. (js2-beginning-of-defun (1- arg))
  11458. t)))
  11459. (when (js2-end-of-defun)
  11460. (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
  11461. (defun js2-end-of-defun ()
  11462. "Go to the char after the last position of the current function
  11463. or script-level element."
  11464. (let* ((node (js2-node-at-point))
  11465. (parent (or (and (js2-function-node-p node) node)
  11466. (js2-node-parent-script-or-fn node)))
  11467. script)
  11468. (unless (js2-function-node-p parent)
  11469. ;; Use current script-level node, or, if none, the next one.
  11470. (setq script (or parent node)
  11471. parent (js2-node-find-child-before (point) script))
  11472. (when (or (null parent)
  11473. (>= (point) (+ (js2-node-abs-pos parent)
  11474. (js2-node-len parent))))
  11475. (setq parent (js2-node-find-child-after (point) script))))
  11476. (when parent
  11477. (goto-char (+ (js2-node-abs-pos parent)
  11478. (js2-node-len parent))))))
  11479. (defun js2-mark-defun (&optional allow-extend)
  11480. "Put mark at end of this function, point at beginning.
  11481. The function marked is the one that contains point.
  11482. Interactively, if this command is repeated,
  11483. or (in Transient Mark mode) if the mark is active,
  11484. it marks the next defun after the ones already marked."
  11485. (interactive "p")
  11486. (let (extended)
  11487. (when (and allow-extend
  11488. (or (and (eq last-command this-command) (mark t))
  11489. (and transient-mark-mode mark-active)))
  11490. (let ((sib (save-excursion
  11491. (goto-char (mark))
  11492. (if (js2-mode-forward-sibling)
  11493. (point)))))
  11494. (if sib
  11495. (progn
  11496. (set-mark sib)
  11497. (setq extended t))
  11498. ;; no more siblings - try extending to enclosing node
  11499. (goto-char (mark t)))))
  11500. (when (not extended)
  11501. (let ((node (js2-node-at-point (point) t)) ; skip comments
  11502. ast fn stmt parent beg end)
  11503. (when (js2-ast-root-p node)
  11504. (setq ast node
  11505. node (or (js2-node-find-child-after (point) node)
  11506. (js2-node-find-child-before (point) node))))
  11507. ;; only mark whole buffer if we can't find any children
  11508. (if (null node)
  11509. (setq node ast))
  11510. (if (js2-function-node-p node)
  11511. (setq parent node)
  11512. (setq fn (js2-mode-find-enclosing-fn node)
  11513. stmt (if (or (null fn)
  11514. (js2-ast-root-p fn))
  11515. (js2-mode-find-first-stmt node))
  11516. parent (or stmt fn)))
  11517. (setq beg (js2-node-abs-pos parent)
  11518. end (+ beg (js2-node-len parent)))
  11519. (push-mark beg)
  11520. (goto-char end)
  11521. (exchange-point-and-mark)))))
  11522. (defun js2-narrow-to-defun ()
  11523. "Narrow to the function enclosing point."
  11524. (interactive)
  11525. (let* ((node (js2-node-at-point (point) t)) ; skip comments
  11526. (fn (if (js2-script-node-p node)
  11527. node
  11528. (js2-mode-find-enclosing-fn node)))
  11529. (beg (js2-node-abs-pos fn)))
  11530. (unless (js2-ast-root-p fn)
  11531. (narrow-to-region beg (+ beg (js2-node-len fn))))))
  11532. (defun js2-jump-to-definition (&optional arg)
  11533. "Jump to the definition of an object's property, variable or function."
  11534. (interactive "P")
  11535. (if (eval-when-compile (fboundp 'xref-push-marker-stack))
  11536. (xref-push-marker-stack)
  11537. (ring-insert find-tag-marker-ring (point-marker)))
  11538. (js2-reparse)
  11539. (let* ((node (js2-node-at-point))
  11540. (parent (js2-node-parent node))
  11541. (names (if (js2-prop-get-node-p parent)
  11542. (reverse (let ((temp (js2-compute-nested-prop-get parent)))
  11543. (cl-loop for n in temp
  11544. with result = '()
  11545. do (push n result)
  11546. until (equal node n)
  11547. finally return result)))))
  11548. node-init)
  11549. (unless (and (js2-name-node-p node)
  11550. (not (js2-var-init-node-p parent))
  11551. (not (js2-function-node-p parent)))
  11552. (error "Node is not a supported jump node"))
  11553. (push (or (and names (pop names))
  11554. (unless (and (js2-object-prop-node-p parent)
  11555. (eq node (js2-object-prop-node-left parent))
  11556. (not (js2-node-get-prop parent 'SHORTHAND)))
  11557. node)
  11558. (error "Node is not a supported jump node")) names)
  11559. (setq node-init (js2-search-scope node names))
  11560. ;; todo: display list of results in buffer
  11561. ;; todo: group found references by buffer
  11562. (unless node-init
  11563. (switch-to-buffer
  11564. (catch 'found
  11565. (unless arg
  11566. (mapc (lambda (b)
  11567. (with-current-buffer b
  11568. (when (derived-mode-p 'js2-mode)
  11569. (setq node-init (js2-search-scope js2-mode-ast names))
  11570. (if node-init
  11571. (throw 'found b)))))
  11572. (buffer-list)))
  11573. nil)))
  11574. (setq node-init (if (listp node-init) (car node-init) node-init))
  11575. (unless node-init
  11576. (pop-tag-mark)
  11577. (error "No jump location found"))
  11578. (goto-char (js2-node-abs-pos node-init))))
  11579. (defun js2-search-object (node name-node)
  11580. "Check if object NODE contains element with NAME-NODE."
  11581. (cl-assert (js2-object-node-p node))
  11582. ;; Only support name-node and nodes for the time being
  11583. (cl-loop for elem in (js2-object-node-elems node)
  11584. for left = (js2-object-prop-node-left elem)
  11585. if (or (and (js2-name-node-p left)
  11586. (equal (js2-name-node-name name-node)
  11587. (js2-name-node-name left)))
  11588. (and (js2-string-node-p left)
  11589. (string= (js2-name-node-name name-node)
  11590. (js2-string-node-value left))))
  11591. return elem))
  11592. (defun js2-search-object-for-prop (object prop-names)
  11593. "Return node in OBJECT that matches PROP-NAMES or nil.
  11594. PROP-NAMES is a list of values representing a path to a value in OBJECT.
  11595. i.e. ('name' 'value') = {name : { value: 3}}"
  11596. (let (node
  11597. (temp-object object)
  11598. (temp t) ;temporay node
  11599. (names prop-names))
  11600. (while (and temp names (js2-object-node-p temp-object))
  11601. (setq temp (js2-search-object temp-object (pop names)))
  11602. (and (setq node temp)
  11603. (setq temp-object (js2-object-prop-node-right temp))))
  11604. (unless names node)))
  11605. (defun js2-search-scope (node names)
  11606. "Searches NODE scope for jump location matching NAMES.
  11607. NAMES is a list of property values to search for. For functions
  11608. and variables NAMES will contain one element."
  11609. (let (node-init
  11610. (val (js2-name-node-name (car names))))
  11611. (setq node-init (js2-get-symbol-declaration node val))
  11612. (when (> (length names) 1)
  11613. ;; Check var declarations
  11614. (when (and node-init (string= val (js2-name-node-name node-init)))
  11615. (let ((parent (js2-node-parent node-init))
  11616. (temp-names names))
  11617. (pop temp-names) ;; First element is var name
  11618. (setq node-init (when (js2-var-init-node-p parent)
  11619. (js2-search-object-for-prop
  11620. (js2-var-init-node-initializer parent)
  11621. temp-names)))))
  11622. ;; Check all assign nodes
  11623. (js2-visit-ast
  11624. js2-mode-ast
  11625. (lambda (node endp)
  11626. (unless endp
  11627. (if (js2-assign-node-p node)
  11628. (let ((left (js2-assign-node-left node))
  11629. (right (js2-assign-node-right node))
  11630. (temp-names names))
  11631. (when (js2-prop-get-node-p left)
  11632. (let* ((prop-list (js2-compute-nested-prop-get left))
  11633. (found (cl-loop for prop in prop-list
  11634. until (not (string= (js2-name-node-name
  11635. (pop temp-names))
  11636. (js2-name-node-name prop)))
  11637. if (not temp-names) return prop))
  11638. (found-node (or found
  11639. (when (js2-object-node-p right)
  11640. (js2-search-object-for-prop right
  11641. temp-names)))))
  11642. (if found-node (push found-node node-init))))))
  11643. t))))
  11644. node-init))
  11645. (defun js2-get-symbol-declaration (node name)
  11646. "Find scope for NAME from NODE."
  11647. (let ((scope (js2-get-defining-scope
  11648. (or (js2-node-get-enclosing-scope node)
  11649. node) name)))
  11650. (if scope (js2-symbol-ast-node (js2-scope-get-symbol scope name)))))
  11651. (provide 'js2-mode)
  11652. ;;; js2-mode.el ends here