ast.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * @fileoverview Utility functions for AST
  3. */
  4. 'use strict';
  5. /**
  6. * Find a return statment in the current node
  7. *
  8. * @param {ASTNode} ASTnode The AST node being checked
  9. */
  10. function findReturnStatement(node) {
  11. if (
  12. (!node.value || !node.value.body || !node.value.body.body) &&
  13. (!node.body || !node.body.body)
  14. ) {
  15. return false;
  16. }
  17. const bodyNodes = (node.value ? node.value.body.body : node.body.body);
  18. let i = bodyNodes.length - 1;
  19. for (; i >= 0; i--) {
  20. if (bodyNodes[i].type === 'ReturnStatement') {
  21. return bodyNodes[i];
  22. }
  23. }
  24. return false;
  25. }
  26. /**
  27. * Get properties name
  28. * @param {Object} node - Property.
  29. * @returns {String} Property name.
  30. */
  31. function getPropertyName(node) {
  32. if (node.key || ['MethodDefinition', 'Property'].indexOf(node.type) !== -1) {
  33. return node.key.name;
  34. } else if (node.type === 'MemberExpression') {
  35. return node.property.name;
  36. }
  37. return '';
  38. }
  39. /**
  40. * Get properties for a given AST node
  41. * @param {ASTNode} node The AST node being checked.
  42. * @returns {Array} Properties array.
  43. */
  44. function getComponentProperties(node) {
  45. switch (node.type) {
  46. case 'ClassDeclaration':
  47. case 'ClassExpression':
  48. return node.body.body;
  49. case 'ObjectExpression':
  50. // return node.properties;
  51. return node.properties;
  52. default:
  53. return [];
  54. }
  55. }
  56. /**
  57. * Checks if the node is the first in its line, excluding whitespace.
  58. * @param {Object} context The node to check
  59. * @param {ASTNode} node The node to check
  60. * @return {Boolean} true if its the first node in its line
  61. */
  62. function isNodeFirstInLine(context, node) {
  63. const sourceCode = context.getSourceCode();
  64. let token = node;
  65. let lines;
  66. do {
  67. token = sourceCode.getTokenBefore(token);
  68. lines = token.type === 'JSXText'
  69. ? token.value.split('\n')
  70. : null;
  71. } while (
  72. token.type === 'JSXText' &&
  73. /^\s*$/.test(lines[lines.length - 1])
  74. );
  75. const startLine = node.loc.start.line;
  76. const endLine = token ? token.loc.end.line : -1;
  77. return startLine !== endLine;
  78. }
  79. module.exports = {
  80. findReturnStatement: findReturnStatement,
  81. getPropertyName: getPropertyName,
  82. getComponentProperties: getComponentProperties,
  83. isNodeFirstInLine: isNodeFirstInLine
  84. };