Ohm-Management - Projektarbeit B-ME
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.

index.mjs 44KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370
  1. /*! @author Toru Nagashima <https://github.com/mysticatea> */
  2. /**
  3. * Get the innermost scope which contains a given location.
  4. * @param {Scope} initialScope The initial scope to search.
  5. * @param {Node} node The location to search.
  6. * @returns {Scope} The innermost scope.
  7. */
  8. function getInnermostScope(initialScope, node) {
  9. const location = node.range[0];
  10. let scope = initialScope;
  11. let found = false;
  12. do {
  13. found = false;
  14. for (const childScope of scope.childScopes) {
  15. const range = childScope.block.range;
  16. if (range[0] <= location && location < range[1]) {
  17. scope = childScope;
  18. found = true;
  19. break
  20. }
  21. }
  22. } while (found)
  23. return scope
  24. }
  25. /**
  26. * Find the variable of a given name.
  27. * @param {Scope} initialScope The scope to start finding.
  28. * @param {string|Node} nameOrNode The variable name to find. If this is a Node object then it should be an Identifier node.
  29. * @returns {Variable|null} The found variable or null.
  30. */
  31. function findVariable(initialScope, nameOrNode) {
  32. let name = "";
  33. let scope = initialScope;
  34. if (typeof nameOrNode === "string") {
  35. name = nameOrNode;
  36. } else {
  37. name = nameOrNode.name;
  38. scope = getInnermostScope(scope, nameOrNode);
  39. }
  40. while (scope != null) {
  41. const variable = scope.set.get(name);
  42. if (variable != null) {
  43. return variable
  44. }
  45. scope = scope.upper;
  46. }
  47. return null
  48. }
  49. /**
  50. * Negate the result of `this` calling.
  51. * @param {Token} token The token to check.
  52. * @returns {boolean} `true` if the result of `this(token)` is `false`.
  53. */
  54. function negate0(token) {
  55. return !this(token) //eslint-disable-line no-invalid-this
  56. }
  57. /**
  58. * Creates the negate function of the given function.
  59. * @param {function(Token):boolean} f - The function to negate.
  60. * @returns {function(Token):boolean} Negated function.
  61. */
  62. function negate(f) {
  63. return negate0.bind(f)
  64. }
  65. /**
  66. * Checks if the given token is an arrow token or not.
  67. * @param {Token} token - The token to check.
  68. * @returns {boolean} `true` if the token is an arrow token.
  69. */
  70. function isArrowToken(token) {
  71. return token.value === "=>" && token.type === "Punctuator"
  72. }
  73. /**
  74. * Checks if the given token is a comma token or not.
  75. * @param {Token} token - The token to check.
  76. * @returns {boolean} `true` if the token is a comma token.
  77. */
  78. function isCommaToken(token) {
  79. return token.value === "," && token.type === "Punctuator"
  80. }
  81. /**
  82. * Checks if the given token is a semicolon token or not.
  83. * @param {Token} token - The token to check.
  84. * @returns {boolean} `true` if the token is a semicolon token.
  85. */
  86. function isSemicolonToken(token) {
  87. return token.value === ";" && token.type === "Punctuator"
  88. }
  89. /**
  90. * Checks if the given token is a colon token or not.
  91. * @param {Token} token - The token to check.
  92. * @returns {boolean} `true` if the token is a colon token.
  93. */
  94. function isColonToken(token) {
  95. return token.value === ":" && token.type === "Punctuator"
  96. }
  97. /**
  98. * Checks if the given token is an opening parenthesis token or not.
  99. * @param {Token} token - The token to check.
  100. * @returns {boolean} `true` if the token is an opening parenthesis token.
  101. */
  102. function isOpeningParenToken(token) {
  103. return token.value === "(" && token.type === "Punctuator"
  104. }
  105. /**
  106. * Checks if the given token is a closing parenthesis token or not.
  107. * @param {Token} token - The token to check.
  108. * @returns {boolean} `true` if the token is a closing parenthesis token.
  109. */
  110. function isClosingParenToken(token) {
  111. return token.value === ")" && token.type === "Punctuator"
  112. }
  113. /**
  114. * Checks if the given token is an opening square bracket token or not.
  115. * @param {Token} token - The token to check.
  116. * @returns {boolean} `true` if the token is an opening square bracket token.
  117. */
  118. function isOpeningBracketToken(token) {
  119. return token.value === "[" && token.type === "Punctuator"
  120. }
  121. /**
  122. * Checks if the given token is a closing square bracket token or not.
  123. * @param {Token} token - The token to check.
  124. * @returns {boolean} `true` if the token is a closing square bracket token.
  125. */
  126. function isClosingBracketToken(token) {
  127. return token.value === "]" && token.type === "Punctuator"
  128. }
  129. /**
  130. * Checks if the given token is an opening brace token or not.
  131. * @param {Token} token - The token to check.
  132. * @returns {boolean} `true` if the token is an opening brace token.
  133. */
  134. function isOpeningBraceToken(token) {
  135. return token.value === "{" && token.type === "Punctuator"
  136. }
  137. /**
  138. * Checks if the given token is a closing brace token or not.
  139. * @param {Token} token - The token to check.
  140. * @returns {boolean} `true` if the token is a closing brace token.
  141. */
  142. function isClosingBraceToken(token) {
  143. return token.value === "}" && token.type === "Punctuator"
  144. }
  145. /**
  146. * Checks if the given token is a comment token or not.
  147. * @param {Token} token - The token to check.
  148. * @returns {boolean} `true` if the token is a comment token.
  149. */
  150. function isCommentToken(token) {
  151. return (
  152. token.type === "Line" ||
  153. token.type === "Block" ||
  154. token.type === "Shebang"
  155. )
  156. }
  157. const isNotArrowToken = negate(isArrowToken);
  158. const isNotCommaToken = negate(isCommaToken);
  159. const isNotSemicolonToken = negate(isSemicolonToken);
  160. const isNotColonToken = negate(isColonToken);
  161. const isNotOpeningParenToken = negate(isOpeningParenToken);
  162. const isNotClosingParenToken = negate(isClosingParenToken);
  163. const isNotOpeningBracketToken = negate(isOpeningBracketToken);
  164. const isNotClosingBracketToken = negate(isClosingBracketToken);
  165. const isNotOpeningBraceToken = negate(isOpeningBraceToken);
  166. const isNotClosingBraceToken = negate(isClosingBraceToken);
  167. const isNotCommentToken = negate(isCommentToken);
  168. /**
  169. * Get the `(` token of the given function node.
  170. * @param {Node} node - The function node to get.
  171. * @param {SourceCode} sourceCode - The source code object to get tokens.
  172. * @returns {Token} `(` token.
  173. */
  174. function getOpeningParenOfParams(node, sourceCode) {
  175. return node.id
  176. ? sourceCode.getTokenAfter(node.id, isOpeningParenToken)
  177. : sourceCode.getFirstToken(node, isOpeningParenToken)
  178. }
  179. /**
  180. * Get the location of the given function node for reporting.
  181. * @param {Node} node - The function node to get.
  182. * @param {SourceCode} sourceCode - The source code object to get tokens.
  183. * @returns {string} The location of the function node for reporting.
  184. */
  185. function getFunctionHeadLocation(node, sourceCode) {
  186. const parent = node.parent;
  187. let start = null;
  188. let end = null;
  189. if (node.type === "ArrowFunctionExpression") {
  190. const arrowToken = sourceCode.getTokenBefore(node.body, isArrowToken);
  191. start = arrowToken.loc.start;
  192. end = arrowToken.loc.end;
  193. } else if (
  194. parent.type === "Property" ||
  195. parent.type === "MethodDefinition"
  196. ) {
  197. start = parent.loc.start;
  198. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  199. } else {
  200. start = node.loc.start;
  201. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  202. }
  203. return {
  204. start: Object.assign({}, start),
  205. end: Object.assign({}, end),
  206. }
  207. }
  208. const builtinNames = Object.freeze(
  209. new Set([
  210. "Array",
  211. "ArrayBuffer",
  212. "Boolean",
  213. "DataView",
  214. "Date",
  215. "decodeURI",
  216. "decodeURIComponent",
  217. "encodeURI",
  218. "encodeURIComponent",
  219. "Error",
  220. "escape",
  221. "EvalError",
  222. "Float32Array",
  223. "Float64Array",
  224. "Function",
  225. "Infinity",
  226. "Int16Array",
  227. "Int32Array",
  228. "Int8Array",
  229. "isFinite",
  230. "isNaN",
  231. "isPrototypeOf",
  232. "JSON",
  233. "Map",
  234. "Math",
  235. "NaN",
  236. "Number",
  237. "Object",
  238. "parseFloat",
  239. "parseInt",
  240. "Promise",
  241. "Proxy",
  242. "RangeError",
  243. "ReferenceError",
  244. "Reflect",
  245. "RegExp",
  246. "Set",
  247. "String",
  248. "Symbol",
  249. "SyntaxError",
  250. "TypeError",
  251. "Uint16Array",
  252. "Uint32Array",
  253. "Uint8Array",
  254. "Uint8ClampedArray",
  255. "undefined",
  256. "unescape",
  257. "URIError",
  258. "WeakMap",
  259. "WeakSet",
  260. ])
  261. );
  262. /**
  263. * Get the element values of a given node list.
  264. * @param {Node[]} nodeList The node list to get values.
  265. * @param {Scope|undefined} initialScope The initial scope to find variables.
  266. * @returns {any[]|null} The value list if all nodes are constant. Otherwise, null.
  267. */
  268. function getElementValues(nodeList, initialScope) {
  269. const valueList = [];
  270. for (let i = 0; i < nodeList.length; ++i) {
  271. const elementNode = nodeList[i];
  272. if (elementNode == null) {
  273. valueList.length = i + 1;
  274. } else if (elementNode.type === "SpreadElement") {
  275. const argument = getStaticValueR(elementNode.argument, initialScope);
  276. if (argument == null) {
  277. return null
  278. }
  279. valueList.push(...argument.value);
  280. } else {
  281. const element = getStaticValueR(elementNode, initialScope);
  282. if (element == null) {
  283. return null
  284. }
  285. valueList.push(element.value);
  286. }
  287. }
  288. return valueList
  289. }
  290. const operations = Object.freeze({
  291. ArrayExpression(node, initialScope) {
  292. const elements = getElementValues(node.elements, initialScope);
  293. return elements != null ? { value: elements } : null
  294. },
  295. AssignmentExpression(node, initialScope) {
  296. if (node.operator === "=") {
  297. return getStaticValueR(node.right, initialScope)
  298. }
  299. return null
  300. },
  301. //eslint-disable-next-line complexity
  302. BinaryExpression(node, initialScope) {
  303. if (node.operator === "in" || node.operator === "instanceof") {
  304. // Not supported.
  305. return null
  306. }
  307. const left = getStaticValueR(node.left, initialScope);
  308. const right = getStaticValueR(node.right, initialScope);
  309. if (left != null && right != null) {
  310. switch (node.operator) {
  311. case "==":
  312. return { value: left.value == right.value } //eslint-disable-line eqeqeq
  313. case "!=":
  314. return { value: left.value != right.value } //eslint-disable-line eqeqeq
  315. case "===":
  316. return { value: left.value === right.value }
  317. case "!==":
  318. return { value: left.value !== right.value }
  319. case "<":
  320. return { value: left.value < right.value }
  321. case "<=":
  322. return { value: left.value <= right.value }
  323. case ">":
  324. return { value: left.value > right.value }
  325. case ">=":
  326. return { value: left.value >= right.value }
  327. case "<<":
  328. return { value: left.value << right.value }
  329. case ">>":
  330. return { value: left.value >> right.value }
  331. case ">>>":
  332. return { value: left.value >>> right.value }
  333. case "+":
  334. return { value: left.value + right.value }
  335. case "-":
  336. return { value: left.value - right.value }
  337. case "*":
  338. return { value: left.value * right.value }
  339. case "/":
  340. return { value: left.value / right.value }
  341. case "%":
  342. return { value: left.value % right.value }
  343. case "**":
  344. return { value: Math.pow(left.value, right.value) }
  345. case "|":
  346. return { value: left.value | right.value }
  347. case "^":
  348. return { value: left.value ^ right.value }
  349. case "&":
  350. return { value: left.value & right.value }
  351. // no default
  352. }
  353. }
  354. return null
  355. },
  356. CallExpression(node, initialScope) {
  357. const calleeNode = node.callee;
  358. const args = getElementValues(node.arguments, initialScope);
  359. if (args != null) {
  360. if (calleeNode.type === "MemberExpression") {
  361. const object = getStaticValueR(calleeNode.object, initialScope);
  362. const property = calleeNode.computed
  363. ? getStaticValueR(calleeNode.property, initialScope)
  364. : { value: calleeNode.property.name };
  365. if (object != null && property != null) {
  366. const receiver = object.value;
  367. const methodName = property.value;
  368. return { value: receiver[methodName](...args) }
  369. }
  370. } else {
  371. const callee = getStaticValueR(calleeNode, initialScope);
  372. if (callee != null) {
  373. const func = callee.value;
  374. return { value: func(...args) }
  375. }
  376. }
  377. }
  378. return null
  379. },
  380. ConditionalExpression(node, initialScope) {
  381. const test = getStaticValueR(node.test, initialScope);
  382. if (test != null) {
  383. return test.value
  384. ? getStaticValueR(node.consequent, initialScope)
  385. : getStaticValueR(node.alternate, initialScope)
  386. }
  387. return null
  388. },
  389. ExpressionStatement(node, initialScope) {
  390. return getStaticValueR(node.expression, initialScope)
  391. },
  392. Identifier(node, initialScope) {
  393. if (initialScope != null) {
  394. const variable = findVariable(initialScope, node);
  395. // Built-in globals.
  396. if (
  397. variable != null &&
  398. variable.defs.length === 0 &&
  399. builtinNames.has(variable.name) &&
  400. variable.name in global
  401. ) {
  402. return { value: global[variable.name] }
  403. }
  404. // Constants.
  405. if (variable != null && variable.defs.length === 1) {
  406. const def = variable.defs[0];
  407. if (
  408. def.parent &&
  409. def.parent.kind === "const" &&
  410. // TODO(mysticatea): don't support destructuring here.
  411. def.node.id.type === "Identifier"
  412. ) {
  413. return getStaticValueR(def.node.init, initialScope)
  414. }
  415. }
  416. }
  417. return null
  418. },
  419. Literal(node) {
  420. //istanbul ignore if : this is implementation-specific behavior.
  421. if (node.regex != null && node.value == null) {
  422. // It was a RegExp literal, but Node.js didn't support it.
  423. return null
  424. }
  425. return node
  426. },
  427. LogicalExpression(node, initialScope) {
  428. const left = getStaticValueR(node.left, initialScope);
  429. if (left != null) {
  430. if (
  431. (node.operator === "||" && Boolean(left.value) === true) ||
  432. (node.operator === "&&" && Boolean(left.value) === false)
  433. ) {
  434. return left
  435. }
  436. const right = getStaticValueR(node.right, initialScope);
  437. if (right != null) {
  438. return right
  439. }
  440. }
  441. return null
  442. },
  443. MemberExpression(node, initialScope) {
  444. const object = getStaticValueR(node.object, initialScope);
  445. const property = node.computed
  446. ? getStaticValueR(node.property, initialScope)
  447. : { value: node.property.name };
  448. if (object != null && property != null) {
  449. return { value: object.value[property.value] }
  450. }
  451. return null
  452. },
  453. NewExpression(node, initialScope) {
  454. const callee = getStaticValueR(node.callee, initialScope);
  455. const args = getElementValues(node.arguments, initialScope);
  456. if (callee != null && args != null) {
  457. const Func = callee.value;
  458. return { value: new Func(...args) }
  459. }
  460. return null
  461. },
  462. ObjectExpression(node, initialScope) {
  463. const object = {};
  464. for (const propertyNode of node.properties) {
  465. if (propertyNode.type === "Property") {
  466. if (propertyNode.kind !== "init") {
  467. return null
  468. }
  469. const key = propertyNode.computed
  470. ? getStaticValueR(propertyNode.key, initialScope)
  471. : { value: propertyNode.key.name };
  472. const value = getStaticValueR(propertyNode.value, initialScope);
  473. if (key == null || value == null) {
  474. return null
  475. }
  476. object[key.value] = value.value;
  477. } else if (
  478. propertyNode.type === "SpreadElement" ||
  479. propertyNode.type === "ExperimentalSpreadProperty"
  480. ) {
  481. const argument = getStaticValueR(
  482. propertyNode.argument,
  483. initialScope
  484. );
  485. if (argument == null) {
  486. return null
  487. }
  488. Object.assign(object, argument.value);
  489. } else {
  490. return null
  491. }
  492. }
  493. return { value: object }
  494. },
  495. SequenceExpression(node, initialScope) {
  496. const last = node.expressions[node.expressions.length - 1];
  497. return getStaticValueR(last, initialScope)
  498. },
  499. TaggedTemplateExpression(node, initialScope) {
  500. const tag = getStaticValueR(node.tag, initialScope);
  501. const expressions = getElementValues(
  502. node.quasi.expressions,
  503. initialScope
  504. );
  505. if (tag != null && expressions != null) {
  506. const func = tag.value;
  507. const strings = node.quasi.quasis.map(q => q.value.cooked);
  508. strings.raw = node.quasi.quasis.map(q => q.value.raw);
  509. return { value: func(strings, ...expressions) }
  510. }
  511. return null
  512. },
  513. TemplateLiteral(node, initialScope) {
  514. const expressions = getElementValues(node.expressions, initialScope);
  515. if (expressions != null) {
  516. let value = node.quasis[0].value.cooked;
  517. for (let i = 0; i < expressions.length; ++i) {
  518. value += expressions[i];
  519. value += node.quasis[i + 1].value.cooked;
  520. }
  521. return { value }
  522. }
  523. return null
  524. },
  525. UnaryExpression(node, initialScope) {
  526. if (node.operator === "delete") {
  527. // Not supported.
  528. return null
  529. }
  530. if (node.operator === "void") {
  531. return { value: undefined }
  532. }
  533. const arg = getStaticValueR(node.argument, initialScope);
  534. if (arg != null) {
  535. switch (node.operator) {
  536. case "-":
  537. return { value: -arg.value }
  538. case "+":
  539. return { value: +arg.value } //eslint-disable-line no-implicit-coercion
  540. case "!":
  541. return { value: !arg.value }
  542. case "~":
  543. return { value: ~arg.value }
  544. case "typeof":
  545. return { value: typeof arg.value }
  546. // no default
  547. }
  548. }
  549. return null
  550. },
  551. });
  552. /**
  553. * Get the value of a given node if it's a static value.
  554. * @param {Node} node The node to get.
  555. * @param {Scope|undefined} initialScope The scope to start finding variable.
  556. * @returns {{value:any}|null} The static value of the node, or `null`.
  557. */
  558. function getStaticValueR(node, initialScope) {
  559. if (node != null && Object.hasOwnProperty.call(operations, node.type)) {
  560. return operations[node.type](node, initialScope)
  561. }
  562. return null
  563. }
  564. /**
  565. * Get the value of a given node if it's a static value.
  566. * @param {Node} node The node to get.
  567. * @param {Scope} [initialScope] The scope to start finding variable. Optional. If this scope was given, this tries to resolve identifier references which are in the given node as much as possible.
  568. * @returns {{value:any}|null} The static value of the node, or `null`.
  569. */
  570. function getStaticValue(node, initialScope = null) {
  571. try {
  572. return getStaticValueR(node, initialScope)
  573. } catch (_error) {
  574. return null
  575. }
  576. }
  577. /**
  578. * Get the value of a given node if it's a literal or a template literal.
  579. * @param {Node} node The node to get.
  580. * @param {Scope} [initialScope] The scope to start finding variable. Optional. If the node is an Identifier node and this scope was given, this checks the variable of the identifier, and returns the value of it if the variable is a constant.
  581. * @returns {string|null} The value of the node, or `null`.
  582. */
  583. function getStringIfConstant(node, initialScope = null) {
  584. const evaluated = getStaticValue(node, initialScope);
  585. return evaluated && String(evaluated.value)
  586. }
  587. /**
  588. * Get the property name from a MemberExpression node or a Property node.
  589. * @param {Node} node The node to get.
  590. * @param {Scope} [initialScope] The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it.
  591. * @returns {string|null} The property name of the node.
  592. */
  593. function getPropertyName(node, initialScope) {
  594. switch (node.type) {
  595. case "MemberExpression":
  596. if (node.computed) {
  597. return getStringIfConstant(node.property, initialScope)
  598. }
  599. return node.property.name
  600. case "Property":
  601. case "MethodDefinition":
  602. if (node.computed) {
  603. return getStringIfConstant(node.key, initialScope)
  604. }
  605. if (node.key.type === "Literal") {
  606. return String(node.key.value)
  607. }
  608. return node.key.name
  609. // no default
  610. }
  611. return null
  612. }
  613. /**
  614. * Get the name and kind of the given function node.
  615. * @param {ASTNode} node - The function node to get.
  616. * @returns {string} The name and kind of the function node.
  617. */
  618. function getFunctionNameWithKind(node) {
  619. const parent = node.parent;
  620. const tokens = [];
  621. if (parent.type === "MethodDefinition" && parent.static) {
  622. tokens.push("static");
  623. }
  624. if (node.async) {
  625. tokens.push("async");
  626. }
  627. if (node.generator) {
  628. tokens.push("generator");
  629. }
  630. if (node.type === "ArrowFunctionExpression") {
  631. tokens.push("arrow", "function");
  632. } else if (
  633. parent.type === "Property" ||
  634. parent.type === "MethodDefinition"
  635. ) {
  636. if (parent.kind === "constructor") {
  637. return "constructor"
  638. }
  639. if (parent.kind === "get") {
  640. tokens.push("getter");
  641. } else if (parent.kind === "set") {
  642. tokens.push("setter");
  643. } else {
  644. tokens.push("method");
  645. }
  646. } else {
  647. tokens.push("function");
  648. }
  649. if (node.id) {
  650. tokens.push(`'${node.id.name}'`);
  651. } else {
  652. const name = getPropertyName(parent);
  653. if (name) {
  654. tokens.push(`'${name}'`);
  655. }
  656. }
  657. return tokens.join(" ")
  658. }
  659. /**
  660. * @author Toru Nagashima <https://github.com/mysticatea>
  661. * See LICENSE file in root directory for full license.
  662. */
  663. const placeholder = /\$(?:[$&`']|[1-9][0-9]?)/g;
  664. /** @type {WeakMap<PatternMatcher, {pattern:RegExp,escaped:boolean}>} */
  665. const internal = new WeakMap();
  666. /**
  667. * Check whether a given character is escaped or not.
  668. * @param {string} str The string to check.
  669. * @param {number} index The location of the character to check.
  670. * @returns {boolean} `true` if the character is escaped.
  671. */
  672. function isEscaped(str, index) {
  673. let escaped = false;
  674. for (let i = index - 1; i >= 0 && str.charCodeAt(i) === 0x5c; --i) {
  675. escaped = !escaped;
  676. }
  677. return escaped
  678. }
  679. /**
  680. * Replace a given string by a given matcher.
  681. * @param {PatternMatcher} matcher The pattern matcher.
  682. * @param {string} str The string to be replaced.
  683. * @param {string} replacement The new substring to replace each matched part.
  684. * @returns {string} The replaced string.
  685. */
  686. function replaceS(matcher, str, replacement) {
  687. const chunks = [];
  688. let index = 0;
  689. /** @type {RegExpExecArray} */
  690. let match = null;
  691. /**
  692. * @param {string} key The placeholder.
  693. * @returns {string} The replaced string.
  694. */
  695. function replacer(key) {
  696. switch (key) {
  697. case "$$":
  698. return "$"
  699. case "$&":
  700. return match[0]
  701. case "$`":
  702. return str.slice(0, match.index)
  703. case "$'":
  704. return str.slice(match.index + match[0].length)
  705. default: {
  706. const i = key.slice(1);
  707. if (i in match) {
  708. return match[i]
  709. }
  710. return key
  711. }
  712. }
  713. }
  714. for (match of matcher.execAll(str)) {
  715. chunks.push(str.slice(index, match.index));
  716. chunks.push(replacement.replace(placeholder, replacer));
  717. index = match.index + match[0].length;
  718. }
  719. chunks.push(str.slice(index));
  720. return chunks.join("")
  721. }
  722. //eslint-disable-next-line valid-jsdoc
  723. /**
  724. * Replace a given string by a given matcher.
  725. * @param {PatternMatcher} matcher The pattern matcher.
  726. * @param {string} str The string to be replaced.
  727. * @param {(...strs[])=>string} replace The function to replace each matched part.
  728. * @returns {string} The replaced string.
  729. */
  730. function replaceF(matcher, str, replace) {
  731. const chunks = [];
  732. let index = 0;
  733. for (const match of matcher.execAll(str)) {
  734. chunks.push(str.slice(index, match.index));
  735. chunks.push(String(replace(...match, match.index, match.input)));
  736. index = match.index + match[0].length;
  737. }
  738. chunks.push(str.slice(index));
  739. return chunks.join("")
  740. }
  741. /**
  742. * The class to find patterns as considering escape sequences.
  743. */
  744. class PatternMatcher {
  745. /**
  746. * Initialize this matcher.
  747. * @param {RegExp} pattern The pattern to match.
  748. * @param {{escaped:boolean}} options The options.
  749. */
  750. constructor(pattern, { escaped = false } = {}) {
  751. if (!(pattern instanceof RegExp)) {
  752. throw new TypeError("'pattern' should be a RegExp instance.")
  753. }
  754. if (!pattern.flags.includes("g")) {
  755. throw new Error("'pattern' should contains 'g' flag.")
  756. }
  757. internal.set(this, {
  758. pattern: new RegExp(pattern.source, pattern.flags),
  759. escaped: Boolean(escaped),
  760. });
  761. }
  762. /**
  763. * Find the pattern in a given string.
  764. * @param {string} str The string to find.
  765. * @returns {IterableIterator<RegExpExecArray>} The iterator which iterate the matched information.
  766. */
  767. *execAll(str) {
  768. const { pattern, escaped } = internal.get(this);
  769. let match = null;
  770. let lastIndex = 0;
  771. pattern.lastIndex = 0;
  772. while ((match = pattern.exec(str)) != null) {
  773. if (escaped || !isEscaped(str, match.index)) {
  774. lastIndex = pattern.lastIndex;
  775. yield match;
  776. pattern.lastIndex = lastIndex;
  777. }
  778. }
  779. }
  780. /**
  781. * Check whether the pattern is found in a given string.
  782. * @param {string} str The string to check.
  783. * @returns {boolean} `true` if the pattern was found in the string.
  784. */
  785. test(str) {
  786. const it = this.execAll(str);
  787. const ret = it.next();
  788. return !ret.done
  789. }
  790. //eslint-disable-next-line valid-jsdoc
  791. /**
  792. * Replace a given string.
  793. * @param {string} str The string to be replaced.
  794. * @param {(string|((...strs:string[])=>string))} replacer The string or function to replace. This is the same as the 2nd argument of `String.prototype.replace`.
  795. * @returns {string} The replaced string.
  796. */
  797. [Symbol.replace](str, replacer) {
  798. return typeof replacer === "function"
  799. ? replaceF(this, String(str), replacer)
  800. : replaceS(this, String(str), String(replacer))
  801. }
  802. }
  803. const SENTINEL_TYPE = /^(?:.+?Statement|.+?Declaration|(?:Array|ArrowFunction|Assignment|Call|Class|Function|Member|New|Object)Expression|AssignmentPattern|Program|VariableDeclarator)$/;
  804. const IMPORT_TYPE = /^(?:Import|Export(?:All|Default|Named))Declaration$/;
  805. const has = Function.call.bind(Object.hasOwnProperty);
  806. const READ = Symbol("read");
  807. const CALL = Symbol("call");
  808. const CONSTRUCT = Symbol("construct");
  809. const ESM = Symbol("esm");
  810. const requireCall = { require: { [CALL]: true } };
  811. /**
  812. * Check whether a given variable is modified or not.
  813. * @param {Variable} variable The variable to check.
  814. * @returns {boolean} `true` if the variable is modified.
  815. */
  816. function isModifiedGlobal(variable) {
  817. return (
  818. variable == null ||
  819. variable.defs.length !== 0 ||
  820. variable.references.some(r => r.isWrite())
  821. )
  822. }
  823. /**
  824. * The reference tracker.
  825. */
  826. class ReferenceTracker {
  827. /**
  828. * Initialize this tracker.
  829. * @param {Scope} globalScope The global scope.
  830. * @param {object} [options] The options.
  831. * @param {"legacy"|"strict"} [options.mode="strict"] The mode to determine the ImportDeclaration's behavior for CJS modules.
  832. * @param {string[]} [options.globalObjectNames=["global","self","window"]] The variable names for Global Object.
  833. */
  834. constructor(
  835. globalScope,
  836. {
  837. mode = "strict",
  838. globalObjectNames = ["global", "self", "window"],
  839. } = {}
  840. ) {
  841. this.variableStack = [];
  842. this.globalScope = globalScope;
  843. this.mode = mode;
  844. this.globalObjectNames = globalObjectNames.slice(0);
  845. }
  846. /**
  847. * Iterate the references of global variables.
  848. * @param {object} traceMap The trace map.
  849. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  850. */
  851. *iterateGlobalReferences(traceMap) {
  852. for (const key of Object.keys(traceMap)) {
  853. const nextTraceMap = traceMap[key];
  854. const path = [key];
  855. const variable = this.globalScope.set.get(key);
  856. if (isModifiedGlobal(variable)) {
  857. continue
  858. }
  859. yield* this._iterateVariableReferences(
  860. variable,
  861. path,
  862. nextTraceMap,
  863. true
  864. );
  865. }
  866. for (const key of this.globalObjectNames) {
  867. const path = [];
  868. const variable = this.globalScope.set.get(key);
  869. if (isModifiedGlobal(variable)) {
  870. continue
  871. }
  872. yield* this._iterateVariableReferences(
  873. variable,
  874. path,
  875. traceMap,
  876. false
  877. );
  878. }
  879. }
  880. /**
  881. * Iterate the references of CommonJS modules.
  882. * @param {object} traceMap The trace map.
  883. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  884. */
  885. *iterateCjsReferences(traceMap) {
  886. for (const { node } of this.iterateGlobalReferences(requireCall)) {
  887. const key = getStringIfConstant(node.arguments[0]);
  888. if (key == null || !has(traceMap, key)) {
  889. continue
  890. }
  891. const nextTraceMap = traceMap[key];
  892. const path = [key];
  893. if (nextTraceMap[READ]) {
  894. yield {
  895. node,
  896. path,
  897. type: READ,
  898. info: nextTraceMap[READ],
  899. };
  900. }
  901. yield* this._iteratePropertyReferences(node, path, nextTraceMap);
  902. }
  903. }
  904. /**
  905. * Iterate the references of ES modules.
  906. * @param {object} traceMap The trace map.
  907. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  908. */
  909. *iterateEsmReferences(traceMap) {
  910. const programNode = this.globalScope.block;
  911. for (const node of programNode.body) {
  912. if (!IMPORT_TYPE.test(node.type) || node.source == null) {
  913. continue
  914. }
  915. const moduleId = node.source.value;
  916. if (!has(traceMap, moduleId)) {
  917. continue
  918. }
  919. const nextTraceMap = traceMap[moduleId];
  920. const path = [moduleId];
  921. if (nextTraceMap[READ]) {
  922. yield { node, path, type: READ, info: nextTraceMap[READ] };
  923. }
  924. if (node.type === "ExportAllDeclaration") {
  925. for (const key of Object.keys(nextTraceMap)) {
  926. const exportTraceMap = nextTraceMap[key];
  927. if (exportTraceMap[READ]) {
  928. yield {
  929. node,
  930. path: path.concat(key),
  931. type: READ,
  932. info: exportTraceMap[READ],
  933. };
  934. }
  935. }
  936. } else {
  937. for (const specifier of node.specifiers) {
  938. const esm = has(nextTraceMap, ESM);
  939. const it = this._iterateImportReferences(
  940. specifier,
  941. path,
  942. esm
  943. ? nextTraceMap
  944. : this.mode === "legacy"
  945. ? Object.assign(
  946. { default: nextTraceMap },
  947. nextTraceMap
  948. )
  949. : { default: nextTraceMap }
  950. );
  951. if (esm) {
  952. yield* it;
  953. } else {
  954. for (const report of it) {
  955. report.path = report.path.filter(exceptDefault);
  956. if (
  957. report.path.length >= 2 ||
  958. report.type !== READ
  959. ) {
  960. yield report;
  961. }
  962. }
  963. }
  964. }
  965. }
  966. }
  967. }
  968. /**
  969. * Iterate the references for a given variable.
  970. * @param {Variable} variable The variable to iterate that references.
  971. * @param {string[]} path The current path.
  972. * @param {object} traceMap The trace map.
  973. * @param {boolean} shouldReport = The flag to report those references.
  974. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  975. */
  976. *_iterateVariableReferences(variable, path, traceMap, shouldReport) {
  977. if (this.variableStack.includes(variable)) {
  978. return
  979. }
  980. this.variableStack.push(variable);
  981. try {
  982. for (const reference of variable.references) {
  983. if (!reference.isRead()) {
  984. continue
  985. }
  986. const node = reference.identifier;
  987. if (shouldReport && traceMap[READ]) {
  988. yield { node, path, type: READ, info: traceMap[READ] };
  989. }
  990. yield* this._iteratePropertyReferences(node, path, traceMap);
  991. }
  992. } finally {
  993. this.variableStack.pop();
  994. }
  995. }
  996. /**
  997. * Iterate the references for a given AST node.
  998. * @param rootNode The AST node to iterate references.
  999. * @param {string[]} path The current path.
  1000. * @param {object} traceMap The trace map.
  1001. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1002. */
  1003. //eslint-disable-next-line complexity, require-jsdoc
  1004. *_iteratePropertyReferences(rootNode, path, traceMap) {
  1005. let node = rootNode;
  1006. while (!SENTINEL_TYPE.test(node.parent.type)) {
  1007. node = node.parent;
  1008. }
  1009. const parent = node.parent;
  1010. if (parent.type === "MemberExpression") {
  1011. if (parent.object === node) {
  1012. const key = getPropertyName(parent);
  1013. if (key == null || !has(traceMap, key)) {
  1014. return
  1015. }
  1016. path = path.concat(key); //eslint-disable-line no-param-reassign
  1017. const nextTraceMap = traceMap[key];
  1018. if (nextTraceMap[READ]) {
  1019. yield {
  1020. node: parent,
  1021. path,
  1022. type: READ,
  1023. info: nextTraceMap[READ],
  1024. };
  1025. }
  1026. yield* this._iteratePropertyReferences(
  1027. parent,
  1028. path,
  1029. nextTraceMap
  1030. );
  1031. }
  1032. return
  1033. }
  1034. if (parent.type === "CallExpression") {
  1035. if (parent.callee === node && traceMap[CALL]) {
  1036. yield { node: parent, path, type: CALL, info: traceMap[CALL] };
  1037. }
  1038. return
  1039. }
  1040. if (parent.type === "NewExpression") {
  1041. if (parent.callee === node && traceMap[CONSTRUCT]) {
  1042. yield {
  1043. node: parent,
  1044. path,
  1045. type: CONSTRUCT,
  1046. info: traceMap[CONSTRUCT],
  1047. };
  1048. }
  1049. return
  1050. }
  1051. if (parent.type === "AssignmentExpression") {
  1052. if (parent.right === node) {
  1053. yield* this._iterateLhsReferences(parent.left, path, traceMap);
  1054. yield* this._iteratePropertyReferences(parent, path, traceMap);
  1055. }
  1056. return
  1057. }
  1058. if (parent.type === "AssignmentPattern") {
  1059. if (parent.right === node) {
  1060. yield* this._iterateLhsReferences(parent.left, path, traceMap);
  1061. }
  1062. return
  1063. }
  1064. if (parent.type === "VariableDeclarator") {
  1065. if (parent.init === node) {
  1066. yield* this._iterateLhsReferences(parent.id, path, traceMap);
  1067. }
  1068. }
  1069. }
  1070. /**
  1071. * Iterate the references for a given Pattern node.
  1072. * @param {Node} patternNode The Pattern node to iterate references.
  1073. * @param {string[]} path The current path.
  1074. * @param {object} traceMap The trace map.
  1075. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1076. */
  1077. *_iterateLhsReferences(patternNode, path, traceMap) {
  1078. if (patternNode.type === "Identifier") {
  1079. const variable = findVariable(this.globalScope, patternNode);
  1080. if (variable != null) {
  1081. yield* this._iterateVariableReferences(
  1082. variable,
  1083. path,
  1084. traceMap,
  1085. false
  1086. );
  1087. }
  1088. return
  1089. }
  1090. if (patternNode.type === "ObjectPattern") {
  1091. for (const property of patternNode.properties) {
  1092. const key = getPropertyName(property);
  1093. if (key == null || !has(traceMap, key)) {
  1094. continue
  1095. }
  1096. const nextPath = path.concat(key);
  1097. const nextTraceMap = traceMap[key];
  1098. if (nextTraceMap[READ]) {
  1099. yield {
  1100. node: property,
  1101. path: nextPath,
  1102. type: READ,
  1103. info: nextTraceMap[READ],
  1104. };
  1105. }
  1106. yield* this._iterateLhsReferences(
  1107. property.value,
  1108. nextPath,
  1109. nextTraceMap
  1110. );
  1111. }
  1112. return
  1113. }
  1114. if (patternNode.type === "AssignmentPattern") {
  1115. yield* this._iterateLhsReferences(patternNode.left, path, traceMap);
  1116. }
  1117. }
  1118. /**
  1119. * Iterate the references for a given ModuleSpecifier node.
  1120. * @param {Node} specifierNode The ModuleSpecifier node to iterate references.
  1121. * @param {string[]} path The current path.
  1122. * @param {object} traceMap The trace map.
  1123. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1124. */
  1125. *_iterateImportReferences(specifierNode, path, traceMap) {
  1126. const type = specifierNode.type;
  1127. if (type === "ImportSpecifier" || type === "ImportDefaultSpecifier") {
  1128. const key =
  1129. type === "ImportDefaultSpecifier"
  1130. ? "default"
  1131. : specifierNode.imported.name;
  1132. if (!has(traceMap, key)) {
  1133. return
  1134. }
  1135. path = path.concat(key); //eslint-disable-line no-param-reassign
  1136. const nextTraceMap = traceMap[key];
  1137. if (nextTraceMap[READ]) {
  1138. yield {
  1139. node: specifierNode,
  1140. path,
  1141. type: READ,
  1142. info: nextTraceMap[READ],
  1143. };
  1144. }
  1145. yield* this._iterateVariableReferences(
  1146. findVariable(this.globalScope, specifierNode.local),
  1147. path,
  1148. nextTraceMap,
  1149. false
  1150. );
  1151. return
  1152. }
  1153. if (type === "ImportNamespaceSpecifier") {
  1154. yield* this._iterateVariableReferences(
  1155. findVariable(this.globalScope, specifierNode.local),
  1156. path,
  1157. traceMap,
  1158. false
  1159. );
  1160. return
  1161. }
  1162. if (type === "ExportSpecifier") {
  1163. const key = specifierNode.local.name;
  1164. if (!has(traceMap, key)) {
  1165. return
  1166. }
  1167. path = path.concat(key); //eslint-disable-line no-param-reassign
  1168. const nextTraceMap = traceMap[key];
  1169. if (nextTraceMap[READ]) {
  1170. yield {
  1171. node: specifierNode,
  1172. path,
  1173. type: READ,
  1174. info: nextTraceMap[READ],
  1175. };
  1176. }
  1177. }
  1178. }
  1179. }
  1180. ReferenceTracker.READ = READ;
  1181. ReferenceTracker.CALL = CALL;
  1182. ReferenceTracker.CONSTRUCT = CONSTRUCT;
  1183. ReferenceTracker.ESM = ESM;
  1184. /**
  1185. * This is a predicate function for Array#filter.
  1186. * @param {string} name A name part.
  1187. * @param {number} index The index of the name.
  1188. * @returns {boolean} `false` if it's default.
  1189. */
  1190. function exceptDefault(name, index) {
  1191. return !(index === 1 && name === "default")
  1192. }
  1193. var index = {
  1194. CALL,
  1195. CONSTRUCT,
  1196. ESM,
  1197. findVariable,
  1198. getFunctionHeadLocation,
  1199. getFunctionNameWithKind,
  1200. getInnermostScope,
  1201. getPropertyName,
  1202. getStaticValue,
  1203. getStringIfConstant,
  1204. isArrowToken,
  1205. isClosingBraceToken,
  1206. isClosingBracketToken,
  1207. isClosingParenToken,
  1208. isColonToken,
  1209. isCommaToken,
  1210. isCommentToken,
  1211. isNotArrowToken,
  1212. isNotClosingBraceToken,
  1213. isNotClosingBracketToken,
  1214. isNotClosingParenToken,
  1215. isNotColonToken,
  1216. isNotCommaToken,
  1217. isNotCommentToken,
  1218. isNotOpeningBraceToken,
  1219. isNotOpeningBracketToken,
  1220. isNotOpeningParenToken,
  1221. isNotSemicolonToken,
  1222. isOpeningBraceToken,
  1223. isOpeningBracketToken,
  1224. isOpeningParenToken,
  1225. isSemicolonToken,
  1226. PatternMatcher,
  1227. READ,
  1228. ReferenceTracker,
  1229. };
  1230. export default index;
  1231. export { CALL, CONSTRUCT, ESM, findVariable, getFunctionHeadLocation, getFunctionNameWithKind, getInnermostScope, getPropertyName, getStaticValue, getStringIfConstant, isArrowToken, isClosingBraceToken, isClosingBracketToken, isClosingParenToken, isColonToken, isCommaToken, isCommentToken, isNotArrowToken, isNotClosingBraceToken, isNotClosingBracketToken, isNotClosingParenToken, isNotColonToken, isNotCommaToken, isNotCommentToken, isNotOpeningBraceToken, isNotOpeningBracketToken, isNotOpeningParenToken, isNotSemicolonToken, isOpeningBraceToken, isOpeningBracketToken, isOpeningParenToken, isSemicolonToken, PatternMatcher, READ, ReferenceTracker };
  1232. //# sourceMappingURL=index.mjs.map