prepare-tokens.cjs 1.1 KB

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