search.js 1.6 KB

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