FunctionDeclarationCalleeDataExtractor.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { injectable } from 'inversify';
  2. import * as estraverse from 'estraverse';
  3. import * as ESTree from 'estree';
  4. import { ICalleeData } from '../../interfaces/stack-trace-analyzer/ICalleeData';
  5. import { AbstractCalleeDataExtractor } from './AbstractCalleeDataExtractor';
  6. import { Node } from '../../node/Node';
  7. import { NodeUtils } from '../../node/NodeUtils';
  8. @injectable()
  9. export class FunctionDeclarationCalleeDataExtractor extends AbstractCalleeDataExtractor {
  10. /**
  11. * @param {Node[]} blockScopeBody
  12. * @param {Identifier} callee
  13. * @returns {ICalleeData}
  14. */
  15. public extract (blockScopeBody: ESTree.Node[], callee: ESTree.Identifier): ICalleeData|null {
  16. if (!Node.isIdentifierNode(callee)) {
  17. return null;
  18. }
  19. const calleeBlockStatement: ESTree.BlockStatement|null = this.getCalleeBlockStatement(
  20. NodeUtils.getBlockScopesOfNode(blockScopeBody[0])[0],
  21. callee.name
  22. );
  23. if (!calleeBlockStatement) {
  24. return null;
  25. }
  26. return {
  27. callee: calleeBlockStatement,
  28. name: callee.name
  29. };
  30. }
  31. /**
  32. * @param {Node} targetNode
  33. * @param {string} name
  34. * @returns {BlockStatement}
  35. */
  36. private getCalleeBlockStatement (targetNode: ESTree.Node, name: string): ESTree.BlockStatement|null {
  37. let calleeBlockStatement: ESTree.BlockStatement|null = null;
  38. estraverse.traverse(targetNode, {
  39. enter: (node: ESTree.Node): any => {
  40. if (Node.isFunctionDeclarationNode(node) && node.id.name === name) {
  41. calleeBlockStatement = node.body;
  42. return estraverse.VisitorOption.Break;
  43. }
  44. }
  45. });
  46. return calleeBlockStatement;
  47. }
  48. }