prepare-tokens.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { tokenize } from '../tokenizer/index.js';
  2. const astToTokens = {
  3. decorator(handlers) {
  4. const tokens = [];
  5. let curNode = null;
  6. return {
  7. ...handlers,
  8. node(node) {
  9. const tmp = curNode;
  10. curNode = node;
  11. handlers.node.call(this, node);
  12. curNode = tmp;
  13. },
  14. emit(value, type, auto) {
  15. tokens.push({
  16. type,
  17. value,
  18. node: auto ? null : curNode
  19. });
  20. },
  21. result() {
  22. return tokens;
  23. }
  24. };
  25. }
  26. };
  27. function stringToTokens(str) {
  28. const tokens = [];
  29. tokenize(str, (type, start, end) =>
  30. tokens.push({
  31. type,
  32. value: str.slice(start, end),
  33. node: null
  34. })
  35. );
  36. return tokens;
  37. }
  38. export default function(value, syntax) {
  39. if (typeof value === 'string') {
  40. return stringToTokens(value);
  41. }
  42. return syntax.generate(value, astToTokens);
  43. };