zz-scratch2.test.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { describe, it, beforeAll } from 'vitest';
  2. import { extractFromSource } from '../src/extraction';
  3. import { initGrammars, loadAllGrammars, getParser } from '../src/extraction/grammars';
  4. beforeAll(async () => { await initGrammars(); await loadAllGrammars(); });
  5. const CASES: Record<string,string> = {
  6. dot_plus: 'V f(V a, V b) { return a.operator+(b); }',
  7. arrow_plus: 'V f(V* a, V b) { return a->operator+(b); }',
  8. dot_sub: 'V f(V a) { return a.operator[](3); }',
  9. dot_call: 'V f(V a) { return a.operator()(3); }',
  10. dot_eq: 'bool f(V a, V b) { return a.operator==(b); }',
  11. dot_bool: 'bool f(V a) { return a.operator bool(); }',
  12. qualified: 'V f(V a, V b) { return V::operator+(a, b); }',
  13. free_op: 'V f(V a, V b) { return operator+(a, b); }',
  14. this_op: 'struct V { V g(V b) { return this->operator+(b); } };',
  15. member_op: 'struct V { V x; V g(V b) { return x.operator+(b); } };',
  16. arrow_deref: 'V f(V a) { return a.operator->(); }',
  17. dot_notop: 'bool f(V a) { return a.operator!(); }',
  18. };
  19. describe('dump', () => {
  20. it('all', () => {
  21. const p: any = getParser('cpp' as any);
  22. for (const [k, code] of Object.entries(CASES)) {
  23. const tree = p.parse(code);
  24. const dump = (n: any, d = 0): string => {
  25. let out = `${' '.repeat(d)}${n.type}${n.childCount === 0 ? ' ' + JSON.stringify(n.text) : ''}\n`;
  26. for (let i = 0; i < n.childCount; i++) out += dump(n.child(i), d + 1);
  27. return out;
  28. };
  29. const call = (function find(n: any): any {
  30. if (n.type === 'call_expression') return n;
  31. for (let i = 0; i < n.childCount; i++) { const r = find(n.child(i)); if (r) return r; }
  32. return null;
  33. })(tree.rootNode);
  34. const refs = extractFromSource('t.cpp', code).unresolvedReferences.filter((r: any) => r.referenceKind === 'calls');
  35. console.log(`\n=== ${k}: ${code}\n${call ? dump(call) : '(no call_expression)'}refs: ${JSON.stringify(refs.map((r: any) => r.referenceName))} hasError=${tree.rootNode.hasError}`);
  36. }
  37. });
  38. });