no-deprecated-api.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. /**
  2. * @fileoverview Rule to disallow deprecated API.
  3. * @author Toru Nagashima
  4. * @copyright 2016 Toru Nagashima. All rights reserved.
  5. * See LICENSE file in root directory for full license.
  6. */
  7. "use strict"
  8. //------------------------------------------------------------------------------
  9. // Requirements
  10. //------------------------------------------------------------------------------
  11. const deprecatedApis = require("../util/deprecated-apis")
  12. const getValueIfString = require("../util/get-value-if-string")
  13. //------------------------------------------------------------------------------
  14. // Helpers
  15. //------------------------------------------------------------------------------
  16. const SENTINEL_TYPE = /^(?:.+?Statement|.+?Declaration|(?:Array|ArrowFunction|Assignment|Call|Class|Function|Member|New|Object)Expression|AssignmentPattern|Program|VariableDeclarator)$/
  17. const MODULE_ITEMS = getDeprecatedItems(deprecatedApis.modules, [], [])
  18. const GLOBAL_ITEMS = getDeprecatedItems(deprecatedApis.globals, [], [])
  19. /**
  20. * Gets the array of deprecated items.
  21. *
  22. * It's the paths which are separated by dots.
  23. * E.g. `buffer.Buffer`, `events.EventEmitter.listenerCount`
  24. *
  25. * @param {object} definition - The definition of deprecated APIs.
  26. * @param {string[]} result - The array of the result.
  27. * @param {string[]} stack - The array to manage the stack of paths.
  28. * @returns {string[]} `result`.
  29. */
  30. function getDeprecatedItems(definition, result, stack) {
  31. for (const key of Object.keys(definition)) {
  32. const item = definition[key]
  33. if (key === "$call") {
  34. result.push(`${stack.join(".")}()`)
  35. }
  36. else if (key === "$constructor") {
  37. result.push(`new ${stack.join(".")}()`)
  38. }
  39. else {
  40. stack.push(key)
  41. if (item.$deprecated) {
  42. result.push(stack.join("."))
  43. }
  44. else {
  45. getDeprecatedItems(item, result, stack)
  46. }
  47. stack.pop()
  48. }
  49. }
  50. return result
  51. }
  52. /**
  53. * Converts from a version number to a version text to display.
  54. *
  55. * @param {number} value - A version number to convert.
  56. * @returns {string} Covnerted text.
  57. */
  58. function toVersionText(value) {
  59. if (value <= 0.12) {
  60. return value.toFixed(2)
  61. }
  62. if (value < 1) {
  63. return value.toFixed(1)
  64. }
  65. return String(value)
  66. }
  67. /**
  68. * Makes a replacement message.
  69. *
  70. * @param {string|null} replacedBy - The text of substitute way.
  71. * @returns {string} Replacement message.
  72. */
  73. function toReplaceMessage(replacedBy) {
  74. return replacedBy ? ` Use ${replacedBy} instead.` : ""
  75. }
  76. /**
  77. * Gets the property name from a MemberExpression node or a Property node.
  78. *
  79. * @param {ASTNode} node - A node to get.
  80. * @returns {string|null} The property name of the node.
  81. */
  82. function getPropertyName(node) {
  83. switch (node.type) {
  84. case "MemberExpression":
  85. if (node.computed) {
  86. return getValueIfString(node.property)
  87. }
  88. return node.property.name
  89. case "Property":
  90. if (node.computed) {
  91. return getValueIfString(node.key)
  92. }
  93. if (node.key.type === "Literal") {
  94. return String(node.key.value)
  95. }
  96. return node.key.name
  97. // no default
  98. }
  99. /* istanbul ignore next: unreachable */
  100. return null
  101. }
  102. /**
  103. * Checks a given node is a ImportDeclaration node.
  104. *
  105. * @param {ASTNode} node - A node to check.
  106. * @returns {boolean} `true` if the node is a ImportDeclaration node.
  107. */
  108. function isImportDeclaration(node) {
  109. return node.type === "ImportDeclaration"
  110. }
  111. /**
  112. * Finds the variable object of a given Identifier node.
  113. *
  114. * @param {ASTNode} node - An Identifier node to find.
  115. * @param {escope.Scope} initialScope - A scope to start searching.
  116. * @returns {escope.Variable} Found variable object.
  117. */
  118. function findVariable(node, initialScope) {
  119. const location = node.range[0]
  120. let variable = null
  121. // Dive into the scope that the node exists.
  122. for (const childScope of initialScope.childScopes) {
  123. const range = childScope.block.range
  124. if (range[0] <= location && location < range[1]) {
  125. variable = findVariable(node, childScope)
  126. if (variable != null) {
  127. return variable
  128. }
  129. }
  130. }
  131. // Find the variable of that name in this scope or ancestor scopes.
  132. let scope = initialScope
  133. while (scope != null) {
  134. variable = scope.set.get(node.name)
  135. if (variable != null) {
  136. return variable
  137. }
  138. scope = scope.upper
  139. }
  140. return null
  141. }
  142. /**
  143. * Gets the top member expression node.
  144. *
  145. * @param {ASTNode} identifier - The node to get.
  146. * @returns {ASTNode} The top member expression node.
  147. */
  148. function getTopMemberExpression(identifier) {
  149. if (identifier.type !== "Identifier" && identifier.type !== "Literal") {
  150. return identifier
  151. }
  152. let node = identifier
  153. while (node.parent.type === "MemberExpression") {
  154. node = node.parent
  155. }
  156. return node
  157. }
  158. /**
  159. * The definition of this rule.
  160. *
  161. * @param {RuleContext} context - The rule context to check.
  162. * @returns {object} The definition of this rule.
  163. */
  164. function create(context) {
  165. const options = context.options[0] || {}
  166. const ignoredModuleItems = options.ignoreModuleItems || []
  167. const ignoredGlobalItems = options.ignoreGlobalItems || []
  168. let globalScope = null
  169. const varStack = []
  170. /**
  171. * Reports a use of a deprecated API.
  172. *
  173. * @param {ASTNode} node - A node to report.
  174. * @param {string} name - The name of a deprecated API.
  175. * @param {{since: number, replacedBy: string}} info - Information of the API.
  176. * @returns {void}
  177. */
  178. function report(node, name, info) {
  179. context.report({
  180. node,
  181. loc: getTopMemberExpression(node).loc,
  182. message: "{{name}} was deprecated since v{{version}}.{{replace}}",
  183. data: {
  184. name,
  185. version: toVersionText(info.since),
  186. replace: toReplaceMessage(info.replacedBy),
  187. },
  188. })
  189. }
  190. /**
  191. * Reports a use of a deprecated module.
  192. *
  193. * @param {ASTNode} node - A node to report.
  194. * @param {string} name - The name of a deprecated module.
  195. * @param {{since: number, replacedBy: string, global: boolean}} info - Information of the module.
  196. * @returns {void}
  197. */
  198. function reportModule(node, name, info) {
  199. if (ignoredModuleItems.indexOf(name) === -1) {
  200. report(node, `'${name}' module`, info)
  201. }
  202. }
  203. /**
  204. * Reports a use of a deprecated property.
  205. *
  206. * @param {ASTNode} node - A node to report.
  207. * @param {string[]} path - The path to a deprecated property.
  208. * @param {{since: number, replacedBy: string, global: boolean}} info - Information of the property.
  209. * @returns {void}
  210. */
  211. function reportCall(node, path, info) {
  212. const ignored = info.global ? ignoredGlobalItems : ignoredModuleItems
  213. const name = `${path.join(".")}()`
  214. if (ignored.indexOf(name) === -1) {
  215. report(node, `'${name}'`, info)
  216. }
  217. }
  218. /**
  219. * Reports a use of a deprecated property.
  220. *
  221. * @param {ASTNode} node - A node to report.
  222. * @param {string[]} path - The path to a deprecated property.
  223. * @param {{since: number, replacedBy: string, global: boolean}} info - Information of the property.
  224. * @returns {void}
  225. */
  226. function reportConstructor(node, path, info) {
  227. const ignored = info.global ? ignoredGlobalItems : ignoredModuleItems
  228. const name = `new ${path.join(".")}()`
  229. if (ignored.indexOf(name) === -1) {
  230. report(node, `'${name}'`, info)
  231. }
  232. }
  233. /**
  234. * Reports a use of a deprecated property.
  235. *
  236. * @param {ASTNode} node - A node to report.
  237. * @param {string[]} path - The path to a deprecated property.
  238. * @param {string} key - The name of the property.
  239. * @param {{since: number, replacedBy: string, global: boolean}} info - Information of the property.
  240. * @returns {void}
  241. */
  242. function reportProperty(node, path, key, info) {
  243. const ignored = info.global ? ignoredGlobalItems : ignoredModuleItems
  244. path.push(key)
  245. const name = path.join(".")
  246. path.pop()
  247. if (ignored.indexOf(name) === -1) {
  248. report(node, `'${name}'`, info)
  249. }
  250. }
  251. /**
  252. * Checks violations in destructuring assignments.
  253. *
  254. * @param {ASTNode} node - A pattern node to check.
  255. * @param {string[]} path - The path to a deprecated property.
  256. * @param {object} infoMap - A map of properties' information.
  257. * @returns {void}
  258. */
  259. function checkDestructuring(node, path, infoMap) {
  260. switch (node.type) {
  261. case "AssignmentPattern":
  262. checkDestructuring(node.left, path, infoMap)
  263. break
  264. case "Identifier": {
  265. const variable = findVariable(node, globalScope)
  266. if (variable != null) {
  267. checkVariable(variable, path, infoMap)
  268. }
  269. break
  270. }
  271. case "ObjectPattern":
  272. for (const property of node.properties) {
  273. const key = getPropertyName(property)
  274. if (key != null && hasOwnProperty.call(infoMap, key)) {
  275. const keyInfo = infoMap[key]
  276. if (keyInfo.$deprecated) {
  277. reportProperty(property.key, path, key, keyInfo)
  278. }
  279. else {
  280. path.push(key)
  281. checkDestructuring(property.value, path, keyInfo)
  282. path.pop()
  283. }
  284. }
  285. }
  286. break
  287. // no default
  288. }
  289. }
  290. /**
  291. * Checks violations in properties.
  292. *
  293. * @param {ASTNode} root - A node to check.
  294. * @param {string[]} path - The path to a deprecated property.
  295. * @param {object} infoMap - A map of properties' information.
  296. * @returns {void}
  297. */
  298. function checkProperties(root, path, infoMap) { //eslint-disable-line complexity
  299. let node = root
  300. while (!SENTINEL_TYPE.test(node.parent.type)) {
  301. node = node.parent
  302. }
  303. const parent = node.parent
  304. switch (parent.type) {
  305. case "CallExpression":
  306. if (parent.callee === node && infoMap.$call != null) {
  307. reportCall(parent, path, infoMap.$call)
  308. }
  309. break
  310. case "NewExpression":
  311. if (parent.callee === node && infoMap.$constructor != null) {
  312. reportConstructor(parent, path, infoMap.$constructor)
  313. }
  314. break
  315. case "MemberExpression":
  316. if (parent.object === node) {
  317. const key = getPropertyName(parent)
  318. if (key != null && hasOwnProperty.call(infoMap, key)) {
  319. const keyInfo = infoMap[key]
  320. if (keyInfo.$deprecated) {
  321. reportProperty(parent.property, path, key, keyInfo)
  322. }
  323. else {
  324. path.push(key)
  325. checkProperties(parent, path, keyInfo)
  326. path.pop()
  327. }
  328. }
  329. }
  330. break
  331. case "AssignmentExpression":
  332. if (parent.right === node) {
  333. checkDestructuring(parent.left, path, infoMap)
  334. checkProperties(parent, path, infoMap)
  335. }
  336. break
  337. case "AssignmentPattern":
  338. if (parent.right === node) {
  339. checkDestructuring(parent.left, path, infoMap)
  340. }
  341. break
  342. case "VariableDeclarator":
  343. if (parent.init === node) {
  344. checkDestructuring(parent.id, path, infoMap)
  345. }
  346. break
  347. // no default
  348. }
  349. }
  350. /**
  351. * Checks violations in the references of a given variable.
  352. *
  353. * @param {escope.Variable} variable - A variable to check.
  354. * @param {string[]} path - The path to a deprecated property.
  355. * @param {object} infoMap - A map of properties' information.
  356. * @returns {void}
  357. */
  358. function checkVariable(variable, path, infoMap) {
  359. if (varStack.indexOf(variable) !== -1) {
  360. return
  361. }
  362. varStack.push(variable)
  363. if (infoMap.$deprecated) {
  364. const key = path.pop()
  365. for (const reference of variable.references.filter(r => r.isRead())) {
  366. reportProperty(reference.identifier, path, key, infoMap)
  367. }
  368. }
  369. else {
  370. for (const reference of variable.references.filter(r => r.isRead())) {
  371. checkProperties(reference.identifier, path, infoMap)
  372. }
  373. }
  374. varStack.pop()
  375. }
  376. /**
  377. * Checks violations in a ModuleSpecifier node.
  378. *
  379. * @param {ASTNode} node - A ModuleSpecifier node to check.
  380. * @param {string[]} path - The path to a deprecated property.
  381. * @param {object} infoMap - A map of properties' information.
  382. * @returns {void}
  383. */
  384. function checkImportSpecifier(node, path, infoMap) {
  385. switch (node.type) {
  386. case "ImportSpecifier": {
  387. const key = node.imported.name
  388. if (hasOwnProperty.call(infoMap, key)) {
  389. const keyInfo = infoMap[key]
  390. if (keyInfo.$deprecated) {
  391. reportProperty(node.imported, path, key, keyInfo)
  392. }
  393. else {
  394. path.push(key)
  395. checkVariable(
  396. findVariable(node.local, globalScope),
  397. path,
  398. keyInfo
  399. )
  400. path.pop()
  401. }
  402. }
  403. break
  404. }
  405. case "ImportDefaultSpecifier":
  406. checkVariable(
  407. findVariable(node.local, globalScope),
  408. path,
  409. infoMap
  410. )
  411. break
  412. case "ImportNamespaceSpecifier":
  413. checkVariable(
  414. findVariable(node.local, globalScope),
  415. path,
  416. Object.assign({}, infoMap, {default: infoMap})
  417. )
  418. break
  419. // no default
  420. }
  421. }
  422. /**
  423. * Checks violations for CommonJS modules.
  424. * @returns {void}
  425. */
  426. function checkCommonJsModules() {
  427. const infoMap = deprecatedApis.modules
  428. const variable = globalScope.set.get("require")
  429. if (variable == null || variable.defs.length !== 0) {
  430. return
  431. }
  432. for (const reference of variable.references.filter(r => r.isRead())) {
  433. const id = reference.identifier
  434. const node = id.parent
  435. if (node.type === "CallExpression" && node.callee === id) {
  436. const key = getValueIfString(node.arguments[0])
  437. if (key != null && hasOwnProperty.call(infoMap, key)) {
  438. const moduleInfo = infoMap[key]
  439. if (moduleInfo.$deprecated) {
  440. reportModule(node, key, moduleInfo)
  441. }
  442. else {
  443. checkProperties(node, [key], moduleInfo)
  444. }
  445. }
  446. }
  447. }
  448. }
  449. /**
  450. * Checks violations for ES2015 modules.
  451. * @param {ASTNode} programNode - A program node to check.
  452. * @returns {void}
  453. */
  454. function checkES2015Modules(programNode) {
  455. const infoMap = deprecatedApis.modules
  456. for (const node of programNode.body.filter(isImportDeclaration)) {
  457. const key = node.source.value
  458. if (hasOwnProperty.call(infoMap, key)) {
  459. const moduleInfo = infoMap[key]
  460. if (moduleInfo.$deprecated) {
  461. reportModule(node, key, moduleInfo)
  462. }
  463. else {
  464. for (const specifier of node.specifiers) {
  465. checkImportSpecifier(specifier, [key], moduleInfo)
  466. }
  467. }
  468. }
  469. }
  470. }
  471. /**
  472. * Checks violations for global variables.
  473. * @returns {void}
  474. */
  475. function checkGlobals() {
  476. const infoMap = deprecatedApis.globals
  477. for (const key of Object.keys(infoMap)) {
  478. const keyInfo = infoMap[key]
  479. const variable = globalScope.set.get(key)
  480. if (variable != null && variable.defs.length === 0) {
  481. checkVariable(variable, [key], keyInfo)
  482. }
  483. }
  484. }
  485. return {
  486. "Program:exit"(node) {
  487. globalScope = context.getScope()
  488. checkCommonJsModules()
  489. checkES2015Modules(node)
  490. checkGlobals()
  491. },
  492. }
  493. }
  494. //------------------------------------------------------------------------------
  495. // Rule Definition
  496. //------------------------------------------------------------------------------
  497. module.exports = {
  498. create,
  499. meta: {
  500. docs: {
  501. description: "disallow deprecated APIs",
  502. category: "Best Practices",
  503. recommended: true,
  504. },
  505. fixable: false,
  506. schema: [
  507. {
  508. type: "object",
  509. properties: {
  510. ignoreModuleItems: {
  511. type: "array",
  512. items: {enum: MODULE_ITEMS},
  513. additionalItems: false,
  514. uniqueItems: true,
  515. },
  516. ignoreGlobalItems: {
  517. type: "array",
  518. items: {enum: GLOBAL_ITEMS},
  519. additionalItems: false,
  520. uniqueItems: true,
  521. },
  522. // Deprecated since v4.2.0
  523. ignoreIndirectDependencies: {type: "boolean"},
  524. },
  525. additionalProperties: false,
  526. },
  527. ],
  528. },
  529. }