Tim van der Lippe | 706ec96 | 2021-06-04 13:24:42 +0100 | [diff] [blame^] | 1 | var List = require('../common/List'); |
| 2 | |
| 3 | function getFirstMatchNode(matchNode) { |
| 4 | if ('node' in matchNode) { |
| 5 | return matchNode.node; |
| 6 | } |
| 7 | |
| 8 | return getFirstMatchNode(matchNode.match[0]); |
| 9 | } |
| 10 | |
| 11 | function getLastMatchNode(matchNode) { |
| 12 | if ('node' in matchNode) { |
| 13 | return matchNode.node; |
| 14 | } |
| 15 | |
| 16 | return getLastMatchNode(matchNode.match[matchNode.match.length - 1]); |
| 17 | } |
| 18 | |
| 19 | function matchFragments(lexer, ast, match, type, name) { |
| 20 | function findFragments(matchNode) { |
| 21 | if (matchNode.syntax !== null && |
| 22 | matchNode.syntax.type === type && |
| 23 | matchNode.syntax.name === name) { |
| 24 | var start = getFirstMatchNode(matchNode); |
| 25 | var end = getLastMatchNode(matchNode); |
| 26 | |
| 27 | lexer.syntax.walk(ast, function(node, item, list) { |
| 28 | if (node === start) { |
| 29 | var nodes = new List(); |
| 30 | |
| 31 | do { |
| 32 | nodes.appendData(item.data); |
| 33 | |
| 34 | if (item.data === end) { |
| 35 | break; |
| 36 | } |
| 37 | |
| 38 | item = item.next; |
| 39 | } while (item !== null); |
| 40 | |
| 41 | fragments.push({ |
| 42 | parent: list, |
| 43 | nodes: nodes |
| 44 | }); |
| 45 | } |
| 46 | }); |
| 47 | } |
| 48 | |
| 49 | if (Array.isArray(matchNode.match)) { |
| 50 | matchNode.match.forEach(findFragments); |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | var fragments = []; |
| 55 | |
| 56 | if (match.matched !== null) { |
| 57 | findFragments(match.matched); |
| 58 | } |
| 59 | |
| 60 | return fragments; |
| 61 | } |
| 62 | |
| 63 | module.exports = { |
| 64 | matchFragments: matchFragments |
| 65 | }; |