semantic_ordering.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { SemanticRole, SemanticType } from './semantic_meaning.js';
  2. const comparators = [];
  3. function add(comparator) {
  4. comparators.push(comparator);
  5. }
  6. function apply(meaning1, meaning2) {
  7. for (let i = 0, comparator; (comparator = comparators[i]); i++) {
  8. const result = comparator.compare(meaning1, meaning2);
  9. if (result !== 0) {
  10. return result;
  11. }
  12. }
  13. return 0;
  14. }
  15. function sort(meanings) {
  16. meanings.sort(apply);
  17. }
  18. export function reduce(meanings) {
  19. if (meanings.length <= 1) {
  20. return meanings;
  21. }
  22. const copy = meanings.slice();
  23. sort(copy);
  24. const result = [];
  25. let last;
  26. do {
  27. last = copy.pop();
  28. result.push(last);
  29. } while (last && copy.length && apply(copy[copy.length - 1], last) === 0);
  30. return result;
  31. }
  32. class SemanticComparator {
  33. constructor(comparator, type = null) {
  34. this.comparator = comparator;
  35. this.type = type;
  36. add(this);
  37. }
  38. compare(meaning1, meaning2) {
  39. return this.type &&
  40. this.type === meaning1.type &&
  41. this.type === meaning2.type
  42. ? this.comparator(meaning1, meaning2)
  43. : 0;
  44. }
  45. }
  46. function simpleFunction(meaning1, meaning2) {
  47. if (meaning1.role === SemanticRole.SIMPLEFUNC) {
  48. return 1;
  49. }
  50. if (meaning2.role === SemanticRole.SIMPLEFUNC) {
  51. return -1;
  52. }
  53. return 0;
  54. }
  55. new SemanticComparator(simpleFunction, SemanticType.IDENTIFIER);