strip-cstyle-differential.test.ts 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. import { describe, it, expect } from 'vitest';
  2. import { stripCommentsForRegex } from '../src/resolution/strip-comments';
  3. /**
  4. * The pre-optimization split('')-based stripCStyle, kept verbatim as the
  5. * ORACLE: the rewritten segment-builder must be byte-identical on every
  6. * input (the C fn-pointer synthesizer's regexes run over this text, and any
  7. * divergence would silently change synthesized edges).
  8. */
  9. function referenceStripCStyle(src: string, allowSingleQuoteStrings: boolean): string {
  10. const out = src.split('');
  11. let i = 0;
  12. const n = src.length;
  13. const blankRange = (buf: string[], start: number, end: number): void => {
  14. for (let k = start; k < end; k++) {
  15. buf[k] = src[k] === '\n' ? '\n' : ' ';
  16. }
  17. };
  18. while (i < n) {
  19. const c = src[i]!;
  20. const c2 = src[i + 1] ?? '';
  21. if (c === '/' && c2 === '*') {
  22. const start = i;
  23. i += 2;
  24. while (i < n && !(src[i] === '*' && src[i + 1] === '/')) i++;
  25. if (i < n) i += 2;
  26. blankRange(out, start, i);
  27. continue;
  28. }
  29. if (c === '/' && c2 === '/') {
  30. const start = i;
  31. while (i < n && src[i] !== '\n') i++;
  32. blankRange(out, start, i);
  33. continue;
  34. }
  35. if (c === '"' || (allowSingleQuoteStrings && c === "'") || c === '`') {
  36. const quote = c;
  37. i++;
  38. while (i < n && src[i] !== quote) {
  39. if (src[i] === '\\' && i + 1 < n) {
  40. i += 2;
  41. continue;
  42. }
  43. if (quote !== '`' && src[i] === '\n') break;
  44. i++;
  45. }
  46. if (i < n && src[i] === quote) i++;
  47. continue;
  48. }
  49. i++;
  50. }
  51. return out.join('');
  52. }
  53. const FIXTURES: Array<[string, string]> = [
  54. ['plain code, no comments', 'int main(void) {\n\treturn a / b;\n}\n'],
  55. ['block comment', 'int x; /* a comment\nspanning lines */ int y;\n'],
  56. ['line comment', 'int x; // trailing\nint y;\n'],
  57. ['comment markers inside string', 'const char *s = "/* not a comment */ // nor this";\nint z;\n'],
  58. ['string inside comment', '/* "a string" inside */ int q;\n'],
  59. ['unterminated block comment', 'int a;\n/* runs to the end'],
  60. ['unterminated string', 'const char *s = "no close\nint b; /* real comment */\n'],
  61. ['escape at end of string', 'const char *s = "ends with backslash \\\\";\nint c;\n'],
  62. ['escape as last char of file', 'const char *s = "\\'],
  63. ['star at last char', 'int d; /*'],
  64. ['slash at last char', 'int e; /'],
  65. ['crlf line comment', 'int f; // comment\r\nint g;\r\n'],
  66. ['unicode in comment', 'int h; /* café résumé — dash */\nint i;\n'],
  67. ['astral chars in comment', 'int j; /* 🚀🎉 emoji */\nint k;\n'],
  68. ['unicode in string', 'const char *s = "café 🚀";\nint l;\n'],
  69. ['nested-looking block', '/* outer /* inner */ int m;\n'],
  70. ['comment right after string', '"str"/*c*/int n;\n'],
  71. ['backtick template (js mode relevance)', 'const t = `multi\nline ${x} // not comment`;\nint o;\n'],
  72. ['single quotes with escapes', "char c = '\\''; // char literal\nint p;\n"],
  73. ['empty input', ''],
  74. ['only a newline', '\n'],
  75. ['only a comment', '/*x*/'],
  76. ];
  77. describe('stripCStyle segment-builder vs split-based oracle', () => {
  78. for (const [name, src] of FIXTURES) {
  79. it(`fixture: ${name} (c mode)`, () => {
  80. expect(stripCommentsForRegex(src, 'c')).toBe(referenceStripCStyle(src, false));
  81. });
  82. it(`fixture: ${name} (js mode, single-quote strings on)`, () => {
  83. expect(stripCommentsForRegex(src, 'javascript')).toBe(referenceStripCStyle(src, true));
  84. });
  85. }
  86. it('randomized differential (seeded, 500 cases)', () => {
  87. // Tiny deterministic LCG — no Math.random in tests that must reproduce.
  88. let seed = 0x2fn;
  89. const rand = (max: number): number => {
  90. seed = (seed * 6364136223846793005n + 1442695040888963407n) & 0xffffffffffffffffn;
  91. return Number(seed % BigInt(max));
  92. };
  93. const ATOMS = ['/*', '*/', '//', '\n', '"', "'", '`', '\\', 'x', ' ', '/', '*', 'é', '🚀', '\r\n', 'int a;'];
  94. for (let caseN = 0; caseN < 500; caseN++) {
  95. let s = '';
  96. const len = rand(40);
  97. for (let k = 0; k < len; k++) s += ATOMS[rand(ATOMS.length)]!;
  98. expect(stripCommentsForRegex(s, 'c'), `c-mode case ${caseN}: ${JSON.stringify(s)}`).toBe(
  99. referenceStripCStyle(s, false)
  100. );
  101. expect(stripCommentsForRegex(s, 'javascript'), `js-mode case ${caseN}: ${JSON.stringify(s)}`).toBe(
  102. referenceStripCStyle(s, true)
  103. );
  104. }
  105. });
  106. it('comment-free input returns the identical string (zero-copy path)', () => {
  107. const src = 'static int add(int a, int b) {\n\treturn a + b;\n}\n';
  108. expect(stripCommentsForRegex(src, 'c')).toBe(src);
  109. });
  110. });