trace.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. function getTrace(node) {
  2. function hasMatch(matchNode) {
  3. if (matchNode.type === 'ASTNode') {
  4. if (matchNode.node === node) {
  5. result = [];
  6. return true;
  7. }
  8. if (matchNode.childrenMatch) {
  9. // use for-loop for better perfomance
  10. for (var i = 0; i < matchNode.childrenMatch.length; i++) {
  11. if (hasMatch(matchNode.childrenMatch[i])) {
  12. return true;
  13. }
  14. }
  15. }
  16. } else {
  17. // use for-loop for better perfomance
  18. for (var i = 0; i < matchNode.match.length; i++) {
  19. if (hasMatch(matchNode.match[i])) {
  20. if (matchNode.syntax.type === 'Type' ||
  21. matchNode.syntax.type === 'Property' ||
  22. matchNode.syntax.type === 'Keyword') {
  23. result.unshift(matchNode.syntax);
  24. }
  25. return true;
  26. }
  27. }
  28. }
  29. return false;
  30. }
  31. var result = null;
  32. if (this.matched !== null) {
  33. hasMatch(this.matched);
  34. }
  35. return result;
  36. }
  37. function testNode(match, node, fn) {
  38. var trace = getTrace.call(match, node);
  39. if (trace === null) {
  40. return false;
  41. }
  42. return trace.some(fn);
  43. }
  44. function isType(node, type) {
  45. return testNode(this, node, function(matchNode) {
  46. return matchNode.type === 'Type' && matchNode.name === type;
  47. });
  48. }
  49. function isProperty(node, property) {
  50. return testNode(this, node, function(matchNode) {
  51. return matchNode.type === 'Property' && matchNode.name === property;
  52. });
  53. }
  54. function isKeyword(node) {
  55. return testNode(this, node, function(matchNode) {
  56. return matchNode.type === 'Keyword';
  57. });
  58. }
  59. module.exports = {
  60. getTrace: getTrace,
  61. isType: isType,
  62. isProperty: isProperty,
  63. isKeyword: isKeyword
  64. };