search.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. var List = require('../utils/list');
  2. function getFirstMatchNode(matchNode) {
  3. if (matchNode.type === 'ASTNode') {
  4. return matchNode.node;
  5. }
  6. return getFirstMatchNode(matchNode.match[0]);
  7. }
  8. function getLastMatchNode(matchNode) {
  9. if (matchNode.type === 'ASTNode') {
  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.type === 'ASTNode') {
  17. return;
  18. }
  19. if (matchNode.syntax.type === type &&
  20. matchNode.syntax.name === name) {
  21. var start = getFirstMatchNode(matchNode);
  22. var end = getLastMatchNode(matchNode);
  23. lexer.syntax.walk(ast, function(node, item, list) {
  24. if (node === start) {
  25. var nodes = new List();
  26. do {
  27. nodes.appendData(item.data);
  28. if (item.data === end) {
  29. break;
  30. }
  31. item = item.next;
  32. } while (item !== null);
  33. fragments.push({
  34. parent: list,
  35. nodes: nodes
  36. });
  37. }
  38. });
  39. }
  40. matchNode.match.forEach(findFragments);
  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. };