trace.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. function getTrace(node) {
  2. function shouldPutToTrace(syntax) {
  3. if (syntax === null) {
  4. return false;
  5. }
  6. return (
  7. syntax.type === 'Type' ||
  8. syntax.type === 'Property' ||
  9. syntax.type === 'Keyword'
  10. );
  11. }
  12. function hasMatch(matchNode) {
  13. if (Array.isArray(matchNode.match)) {
  14. // use for-loop for better perfomance
  15. for (var i = 0; i < matchNode.match.length; i++) {
  16. if (hasMatch(matchNode.match[i])) {
  17. if (shouldPutToTrace(matchNode.syntax)) {
  18. result.unshift(matchNode.syntax);
  19. }
  20. return true;
  21. }
  22. }
  23. } else if (matchNode.node === node) {
  24. result = shouldPutToTrace(matchNode.syntax)
  25. ? [matchNode.syntax]
  26. : [];
  27. return true;
  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. };