expressionTo.js 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*eslint no-loop-func: 0, no-use-before-define: 0*/
  2. import resolveToValue from './resolveToValue.js';
  3. /**
  4. * Splits a MemberExpression or CallExpression into parts.
  5. * E.g. foo.bar.baz becomes ['foo', 'bar', 'baz']
  6. */
  7. function toArray(path) {
  8. const parts = [path];
  9. let result = [];
  10. while (parts.length > 0) {
  11. path = parts.shift();
  12. if (path.isCallExpression()) {
  13. parts.push(path.get('callee'));
  14. continue;
  15. }
  16. else if (path.isMemberExpression()) {
  17. parts.push(path.get('object'));
  18. const property = path.get('property');
  19. if (path.node.computed) {
  20. const resolvedPath = resolveToValue(property);
  21. if (resolvedPath !== undefined) {
  22. result = result.concat(toArray(resolvedPath));
  23. }
  24. else {
  25. result.push('<computed>');
  26. }
  27. }
  28. else if (property.isIdentifier()) {
  29. result.push(property.node.name);
  30. }
  31. else if (property.isPrivateName()) {
  32. // new test
  33. result.push(`#${property.get('id').node.name}`);
  34. }
  35. continue;
  36. }
  37. else if (path.isIdentifier()) {
  38. result.push(path.node.name);
  39. continue;
  40. }
  41. else if (path.isTSAsExpression()) {
  42. const expression = path.get('expression');
  43. if (expression.isIdentifier()) {
  44. result.push(expression.node.name);
  45. }
  46. continue;
  47. }
  48. else if (path.isLiteral() && path.node.extra?.raw) {
  49. result.push(path.node.extra.raw);
  50. continue;
  51. }
  52. else if (path.isThisExpression()) {
  53. result.push('this');
  54. continue;
  55. }
  56. else if (path.isObjectExpression()) {
  57. const properties = path.get('properties').map(function (property) {
  58. if (property.isSpreadElement()) {
  59. return `...${toString(property.get('argument'))}`;
  60. }
  61. else if (property.isObjectProperty()) {
  62. return (toString(property.get('key')) +
  63. ': ' +
  64. toString(property.get('value')));
  65. }
  66. else if (property.isObjectMethod()) {
  67. return toString(property.get('key')) + ': <function>';
  68. }
  69. else {
  70. throw new Error('Unrecognized object property type');
  71. }
  72. });
  73. result.push('{' + properties.join(', ') + '}');
  74. continue;
  75. }
  76. else if (path.isArrayExpression()) {
  77. result.push('[' +
  78. path
  79. .get('elements')
  80. .map(function (el) {
  81. return toString(el);
  82. })
  83. .join(', ') +
  84. ']');
  85. continue;
  86. }
  87. }
  88. return result.reverse();
  89. }
  90. /**
  91. * Creates a string representation of a member expression.
  92. */
  93. function toString(path) {
  94. return toArray(path).join('.');
  95. }
  96. export { toString as String, toArray as Array };