search.cjs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict';
  2. const List = require('../utils/List.cjs');
  3. function getFirstMatchNode(matchNode) {
  4. if ('node' in matchNode) {
  5. return matchNode.node;
  6. }
  7. return getFirstMatchNode(matchNode.match[0]);
  8. }
  9. function getLastMatchNode(matchNode) {
  10. if ('node' in matchNode) {
  11. return matchNode.node;
  12. }
  13. return getLastMatchNode(matchNode.match[matchNode.match.length - 1]);
  14. }
  15. function matchFragments(lexer, ast, match, type, name) {
  16. function findFragments(matchNode) {
  17. if (matchNode.syntax !== null &&
  18. matchNode.syntax.type === type &&
  19. matchNode.syntax.name === name) {
  20. const start = getFirstMatchNode(matchNode);
  21. const end = getLastMatchNode(matchNode);
  22. lexer.syntax.walk(ast, function(node, item, list) {
  23. if (node === start) {
  24. const nodes = new List.List();
  25. do {
  26. nodes.appendData(item.data);
  27. if (item.data === end) {
  28. break;
  29. }
  30. item = item.next;
  31. } while (item !== null);
  32. fragments.push({
  33. parent: list,
  34. nodes
  35. });
  36. }
  37. });
  38. }
  39. if (Array.isArray(matchNode.match)) {
  40. matchNode.match.forEach(findFragments);
  41. }
  42. }
  43. const fragments = [];
  44. if (match.matched !== null) {
  45. findFragments(match.matched);
  46. }
  47. return fragments;
  48. }
  49. exports.matchFragments = matchFragments;