variable.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /**
  2. * @fileoverview Utility functions for React components detection
  3. * @author Yannick Croissant
  4. */
  5. 'use strict';
  6. /**
  7. * Record that a particular variable has been used in code
  8. *
  9. * @param {String} name The name of the variable to mark as used.
  10. * @returns {Boolean} True if the variable was found and marked as used, false if not.
  11. */
  12. function markVariableAsUsed(context, name) {
  13. let scope = context.getScope();
  14. let variables;
  15. let i;
  16. let len;
  17. let found = false;
  18. // Special Node.js scope means we need to start one level deeper
  19. if (scope.type === 'global') {
  20. while (scope.childScopes.length) {
  21. ([scope] = scope.childScopes);
  22. }
  23. }
  24. do {
  25. variables = scope.variables;
  26. for (i = 0, len = variables.length; i < len; i++) { // eslint-disable-line no-plusplus
  27. if (variables[i].name === name) {
  28. variables[i].eslintUsed = true;
  29. found = true;
  30. }
  31. }
  32. scope = scope.upper;
  33. } while (scope);
  34. return found;
  35. }
  36. /**
  37. * Search a particular variable in a list
  38. * @param {Array} variables The variables list.
  39. * @param {Array} name The name of the variable to search.
  40. * @returns {Boolean} True if the variable was found, false if not.
  41. */
  42. function findVariable(variables, name) {
  43. let i;
  44. let len;
  45. for (i = 0, len = variables.length; i < len; i++) { // eslint-disable-line no-plusplus
  46. if (variables[i].name === name) {
  47. return true;
  48. }
  49. }
  50. return false;
  51. }
  52. /**
  53. * List all variable in a given scope
  54. *
  55. * Contain a patch for babel-eslint to avoid https://github.com/babel/babel-eslint/issues/21
  56. *
  57. * @param {Object} context The current rule context.
  58. * @param {Array} name The name of the variable to search.
  59. * @returns {Boolean} True if the variable was found, false if not.
  60. */
  61. function variablesInScope(context) {
  62. let scope = context.getScope();
  63. let { variables } = scope;
  64. while (scope.type !== 'global') {
  65. scope = scope.upper;
  66. variables = scope.variables.concat(variables);
  67. }
  68. if (scope.childScopes.length) {
  69. variables = scope.childScopes[0].variables.concat(variables);
  70. if (scope.childScopes[0].childScopes.length) {
  71. variables = scope.childScopes[0].childScopes[0].variables.concat(variables);
  72. }
  73. }
  74. return variables;
  75. }
  76. module.exports = {
  77. findVariable: findVariable,
  78. variablesInScope: variablesInScope,
  79. markVariableAsUsed: markVariableAsUsed,
  80. };