Tim van der Lippe | 706ec96 | 2021-06-04 13:24:42 +0100 | [diff] [blame^] | 1 | function getTrace(node) { |
| 2 | function shouldPutToTrace(syntax) { |
| 3 | if (syntax === null) { |
| 4 | return false; |
| 5 | } |
| 6 | |
| 7 | return ( |
| 8 | syntax.type === 'Type' || |
| 9 | syntax.type === 'Property' || |
| 10 | syntax.type === 'Keyword' |
| 11 | ); |
| 12 | } |
| 13 | |
| 14 | function hasMatch(matchNode) { |
| 15 | if (Array.isArray(matchNode.match)) { |
| 16 | // use for-loop for better perfomance |
| 17 | for (var i = 0; i < matchNode.match.length; i++) { |
| 18 | if (hasMatch(matchNode.match[i])) { |
| 19 | if (shouldPutToTrace(matchNode.syntax)) { |
| 20 | result.unshift(matchNode.syntax); |
| 21 | } |
| 22 | |
| 23 | return true; |
| 24 | } |
| 25 | } |
| 26 | } else if (matchNode.node === node) { |
| 27 | result = shouldPutToTrace(matchNode.syntax) |
| 28 | ? [matchNode.syntax] |
| 29 | : []; |
| 30 | |
| 31 | return true; |
| 32 | } |
| 33 | |
| 34 | return false; |
| 35 | } |
| 36 | |
| 37 | var result = null; |
| 38 | |
| 39 | if (this.matched !== null) { |
| 40 | hasMatch(this.matched); |
| 41 | } |
| 42 | |
| 43 | return result; |
| 44 | } |
| 45 | |
| 46 | function testNode(match, node, fn) { |
| 47 | var trace = getTrace.call(match, node); |
| 48 | |
| 49 | if (trace === null) { |
| 50 | return false; |
| 51 | } |
| 52 | |
| 53 | return trace.some(fn); |
| 54 | } |
| 55 | |
| 56 | function isType(node, type) { |
| 57 | return testNode(this, node, function(matchNode) { |
| 58 | return matchNode.type === 'Type' && matchNode.name === type; |
| 59 | }); |
| 60 | } |
| 61 | |
| 62 | function isProperty(node, property) { |
| 63 | return testNode(this, node, function(matchNode) { |
| 64 | return matchNode.type === 'Property' && matchNode.name === property; |
| 65 | }); |
| 66 | } |
| 67 | |
| 68 | function isKeyword(node) { |
| 69 | return testNode(this, node, function(matchNode) { |
| 70 | return matchNode.type === 'Keyword'; |
| 71 | }); |
| 72 | } |
| 73 | |
| 74 | module.exports = { |
| 75 | getTrace: getTrace, |
| 76 | isType: isType, |
| 77 | isProperty: isProperty, |
| 78 | isKeyword: isKeyword |
| 79 | }; |