AI 代码审查实战:用 JavaScript 后缀自动机实现不可变 Unicode 子串索引

10-19 5阅读

同一篇长文本需要回答很多次子串查询时,问题的重点会从怎样扫描一次,变成怎样建立可复用的索引。本文把后缀自动机作为一次 AI 代码审查练习:由 JavaScript 建图,只对外提供只读查询,再用独立的穷举程序核验结果。它处理的是一份文本中的所有连续子串,既不是词典的前缀检索,也不是把单个模式重新扫描一遍。

我们给实现划定四条边界:字符单位是 Unicode 码点;输入必须是良构 UTF-16 字符串;空模式始终存在,但不同子串的计数不包含空串;计数始终返回 BigInt。所谓不可变,是构建完成后没有公开的修改入口,旧索引的结果不会因创建新索引而改变。构建过程仍然使用可变 Map,这里没有实现支持低成本追加与版本共享的持久化数据结构。

审查 AI 生成的算法时,仅看几组英文查询很容易漏掉问题。本次重点追问三个地方:字符有没有被代理项拆开,克隆状态是否真正复制了转移表,冻结对象是否真的阻止了外部修改。每个问题都要有可以运行的反例,而不是用一句看起来正确的注释代替验证。

AI 代码审查实战:用 JavaScript 后缀自动机实现不可变 Unicode 子串索引
AI 生成概念图:符号流汇入共享状态网络,检查镜与锁象征审查和只读接口。图中连线仅作视觉表达,不是本文自动机的真实状态图。

运行说明:下文恰好九段 JavaScript,分别保存为 01.cjs 至 09.cjs,每段都包含所需定义,可独立执行。统一命令格式为 node --unhandled-rejections=strict 01.cjs,其他文件替换编号即可。实测环境为 Node.js v24.19.0,无第三方依赖。每段后面的普通文本块都是实际标准输出;后文重复完整构建器,是为了避免复制示例时依赖前面的运行状态。

一、先把 Unicode 与异常行为写进契约

JavaScript 的字符串长度按 UTF-16 码元计数,一个补充平面的符号可能占两个码元。我们用 for...of 或 Array.from 读取码点,因此笑脸不会被拆成两个节点。但码点不等于用户眼中的完整字符:组合重音是独立码点,零宽连接符也会被保留。将这一层语义写清楚,比事后给函数加上 Unicode 字样更重要。

本实现拒绝孤立高代理项与孤立低代理项,抛出 TypeError;不会悄悄调用 toWellFormed 把它们替换成占位符。构建文本与查询模式使用同一条校验规则,而且查询必须先检查完整模式,不能因为第一个字符没有转移就跳过后面的非法代理项。字符串包装对象、数字和空值同样被拒绝,避免隐式转换带来意外调用。

匹配是区分大小写的原样比较,不自动进行 NFC 归一化。预组合的 é 与 e 加组合重音可能看起来相同,在这个接口中仍是不同的码点序列。若业务希望把它们视作相同,应在调用边界对文本和每个模式采用一致的归一化策略,并承认索引对象已经是转换后的文本。这里也不声称能按字素簇执行匹配。

语言依据是 ECMAScript 字符串迭代器与 isWellFormed 规范。先跑下面的契约测试,再讨论图结构,能把编码错误和算法错误分开定位。

示例 1,独立运行:

'use strict';
const assert = require('node:assert/strict');
function points(value) {
  if (typeof value !== 'string' || !value.isWellFormed()) {
    throw new TypeError('expected a well-formed string');
  }
  return Array.from(value);
}
const text = 'A😀e\u0301';
assert.equal(text.length, 5);
assert.equal(points(text).length, 4);
assert.notDeepEqual(points('é'), points('e\u0301'));
assert.deepEqual(points(''), []);
assert.throws(() => points('\uD800'), TypeError);
assert.throws(() => points('\uDC00'), TypeError);
assert.throws(() => points(123), TypeError);
console.log(`codeUnits=${text.length} codePoints=${points(text).length}`);
console.log('lone surrogates and non-strings: rejected');

实际输出:

codeUnits=5 codePoints=4
lone surrogates and non-strings: rejected

二、完整构建器:可变施工,只读交付

每个状态存三个字段:len 是它能代表的最长子串的码点长度,link 指向较短的后缀等价类,next 是按单个码点标记的转移表。根状态的长度为零,后缀链接为负一。每读入一个码点,先创建代表当前整个前缀的新状态,再沿旧末状态的后缀链接补齐缺失的转移。

如果回退到负一,说明新字符没有可复用的旧转移,新状态链接根即可。如果遇到旧转移 p 到 q,且 q 的最长长度恰好比 p 多一,新状态直接链接 q。否则要拆分旧等价类:复制 q 的出边,给克隆状态设置更短的最长长度,再把相应后缀链上仍指向 q 的这条出边改向克隆。q 与新状态的链接都需要更新,不能只更新其中一个。

查询从根出发,逐码点沿边行走;所有字符都能走完就返回 true。这里有个常见术语陷阱:经典后缀自动机若用于识别后缀,需要标记终态;本接口查询的是任意子串,所以只要路径存在就算成功,不需要终态标记,也不宣称这张图是所有子串语言的最小 DFA。这个区分可对照 Crochemore 与 Rytter 的 Text Algorithms 第六章及书目说明。

计数在整个构建完成后统一求和。这样可以避开构建中途后缀链接被克隆步骤改写所造成的误算。外部只能读到两个数字属性、一个成员查询方法和一个计数方法,无法拿到状态数组或任何内部 Map。以下代码就是后续回归测试使用的完整实现。

示例 2,独立运行:

'use strict';
const assert = require('node:assert/strict');
function requireText(value, name) {
  if (typeof value !== 'string') {
    throw new TypeError(`${name} must be a string`);
  }
  if (!value.isWellFormed()) {
    throw new TypeError(`${name} must be well-formed UTF-16`);
  }
}
function createSuffixIndex(text) {
  requireText(text, 'text');
  const states = [{ len: 0, link: -1, next: new Map() }];
  let last = 0;
  let length = 0;
  for (const symbol of text) {
    const current = states.length;
    states.push({ len: ++length, link: 0, next: new Map() });
    let p = last;
    while (p !== -1 && !states[p].next.has(symbol)) {
      states[p].next.set(symbol, current);
      p = states[p].link;
    }
    if (p !== -1) {
      const q = states[p].next.get(symbol);
      if (states[p].len + 1 === states[q].len) {
        states[current].link = q;
      } else {
        const clone = states.length;
        states.push({
          len: states[p].len + 1,
          link: states[q].link,
          next: new Map(states[q].next)
        });
        while (p !== -1 && states[p].next.get(symbol) === q) {
          states[p].next.set(symbol, clone);
          p = states[p].link;
        }
        states[q].link = clone;
        states[current].link = clone;
      }
    }
    last = current;
  }
  let total = 0n;
  for (let v = 1; v < states.length; v++) {
    total += BigInt(states[v].len) - BigInt(states[states[v].link].len);
  }
  return Object.freeze({
    codePointLength: length,
    stateCount: states.length,
    has(pattern) {
      requireText(pattern, 'pattern');
      let v = 0;
      for (const symbol of pattern) {
        const next = states[v].next.get(symbol);
        if (next === undefined) return false;
        v = next;
      }
      return true;
    },
    distinctCount() { return total; }
  });
}

const index = createSuffixIndex('banana😀');
assert.equal(index.has('ana'), true);
assert.equal(index.has('na😀'), true);
assert.equal(index.has('nab'), false);
assert.equal(index.has(''), true);
assert.equal(index.distinctCount(), 22n);
console.log(index.has('ana'), index.has('na😀'), index.has('nab'), index.has(''));
console.log(`points=${index.codePointLength} distinct=${index.distinctCount()}`);

实际输出:

true true false true
points=7 distinct=22

三、用 abb 钉住克隆分支与空串边界

许多错误实现能够通过全不相同字符的测试,因为那些输入几乎没有真正考验克隆逻辑。abb 是一个足够短、又能进入克隆分支的回归用例。处理到最后一个 b 时,原有状态曾同时容纳 b 与 ab;新的出现位置迫使这两种后缀行为分开,克隆因此产生。最终一共有五个状态,包含根,以及 a、b、ab 和合并表示 bb 与 abb 的类。

审查时要逐项核对:克隆的 len 来自 p 的长度加一,不是直接保留 q 的长度;克隆继承 q 的旧 link;转移表由 new Map 复制,不能与 q 共用同一个可变容器;回退重定向必须以旧目标仍然等于 q 为条件。只检查下一条边是否存在,可能把不属于这次拆分的路径也一起改坏。

另一个容易被漂亮示例遮住的边界是空文本。它仍然有根状态,非空子串数为零;空查询不需要经过任何边,因此返回 true。我们不把这个行为藏在特殊分支里,而让零次循环自然产生结果。计数跳过根状态,从而避免把空串加进去。下面把克隆与空文本放进同一段独立回归脚本。

示例 3,独立运行:

'use strict';
const assert = require('node:assert/strict');
function requireText(value, name) {
  if (typeof value !== 'string') {
    throw new TypeError(`${name} must be a string`);
  }
  if (!value.isWellFormed()) {
    throw new TypeError(`${name} must be well-formed UTF-16`);
  }
}
function createSuffixIndex(text) {
  requireText(text, 'text');
  const states = [{ len: 0, link: -1, next: new Map() }];
  let last = 0;
  let length = 0;
  for (const symbol of text) {
    const current = states.length;
    states.push({ len: ++length, link: 0, next: new Map() });
    let p = last;
    while (p !== -1 && !states[p].next.has(symbol)) {
      states[p].next.set(symbol, current);
      p = states[p].link;
    }
    if (p !== -1) {
      const q = states[p].next.get(symbol);
      if (states[p].len + 1 === states[q].len) {
        states[current].link = q;
      } else {
        const clone = states.length;
        states.push({
          len: states[p].len + 1,
          link: states[q].link,
          next: new Map(states[q].next)
        });
        while (p !== -1 && states[p].next.get(symbol) === q) {
          states[p].next.set(symbol, clone);
          p = states[p].link;
        }
        states[q].link = clone;
        states[current].link = clone;
      }
    }
    last = current;
  }
  let total = 0n;
  for (let v = 1; v < states.length; v++) {
    total += BigInt(states[v].len) - BigInt(states[states[v].link].len);
  }
  return Object.freeze({
    codePointLength: length,
    stateCount: states.length,
    has(pattern) {
      requireText(pattern, 'pattern');
      let v = 0;
      for (const symbol of pattern) {
        const next = states[v].next.get(symbol);
        if (next === undefined) return false;
        v = next;
      }
      return true;
    },
    distinctCount() { return total; }
  });
}

const index = createSuffixIndex('abb');
assert.equal(index.stateCount, 5);
assert.equal(index.distinctCount(), 5n);
for (const value of ['a', 'b', 'ab', 'bb', 'abb']) assert(index.has(value));
for (const value of ['ba', 'aa', 'bbb']) assert.equal(index.has(value), false);
const empty = createSuffixIndex('');
assert.equal(empty.stateCount, 1);
assert.equal(empty.distinctCount(), 0n);
assert.equal(empty.has(''), true);
assert.equal(empty.has('a'), false);
console.log('abb: states=5 distinct=5');
console.log('empty: states=1 distinct=0 acceptsEmpty=true');

实际输出:

abb: states=5 distinct=5
empty: states=1 distinct=0 acceptsEmpty=true

四、从长度区间推导 BigInt 计数

为什么不枚举每一条路径?因为不同子串最多可以有二次数量。后缀自动机把具有相同结束位置集合的子串分到一个状态里。对非根状态 v,它所代表的长度连续覆盖从 len[link[v]] 加一到 len[v],每个长度恰好对应这个类中的一个子串。因此该状态的贡献就是两个长度之差,遍历所有非根状态相加即可。结束位置等价类的定义可核对这篇 DAWG 研究论文的第二节。

把这个事实应用到 abb,四个非根状态分别贡献一、一、二、一,共五个非空不同子串。这里统计的是不同内容,而不是出现次数。b 出现了两次,仍然只贡献一种内容;同理,不能把状态数直接当成子串数,某个状态完全可能覆盖多个长度。

BigInt 应在做计数运算之前介入,不能先用 Number 算出一个已经舍入的总和,再把舍入结果转换。示例保留 Number 作为实际状态长度,累计时先把两个长度各自转成 BigInt。下面的算术边界测试只展示转换时机,不是假装构造出一份巨大文本或有效的巨大自动机。BigInt 保证计数的整数精度,并不会解除字符串、数组或机器内存的容量限制。

示例 4,独立运行:

'use strict';
const assert = require('node:assert/strict');
function countIntervals(states) {
  let total = 0n;
  for (let v = 1; v < states.length; v++) {
    const { len, link } = states[v];
    assert(Number.isSafeInteger(len) && len > 0);
    assert(Number.isInteger(link) && link >= 0 && link < states.length);
    assert(Number.isSafeInteger(states[link].len) && states[link].len < len);
    total += BigInt(len) - BigInt(states[link].len);
  }
  return total;
}
// Length/link projection of the automaton for abb; clone is state 4.
const abb = [
  { len: 0, link: -1 }, { len: 1, link: 0 },
  { len: 2, link: 4 }, { len: 3, link: 4 },
  { len: 1, link: 0 }
];
assert.equal(countIntervals(abb), 5n);
// Arithmetic boundary only: this is not an actual automaton fixture.
const maximum = Number.MAX_SAFE_INTEGER;
const exact = BigInt(maximum) + 2n;
const late = BigInt(maximum + 2);
assert.notEqual(exact, late);
console.log(`abb=${countIntervals(abb)}`);
console.log(`early=${exact} late=${late}`);

实际输出:

abb=5
early=9007199254740993 late=9007199254740992

五、不可变的重点是隐藏可变对象

AI 很容易提出把每个 Map 都交给 Object.freeze,然后宣布索引不可变。这个承诺并不成立。冻结限制的是对象属性层面的变化,Map.prototype.set 仍会修改 Map 的内部条目。下面先展示一份冻结后仍能写入的 Map,作为可执行反例,再检查我们真正交付的接口。

这里的保护来自封装:状态数组和转移表只被构建器内部闭包持有,没有 getter、调试快照或导出函数把引用泄漏给调用者。返回对象自身被冻结,属性不能替换,也不能追加一个伪造的 states 属性。查询只读转移表,不维护缓存,不偷偷更新命中次数,因此重复调用不会改变可观察结果。

这种不可变保证针对正常调用者与标准内建对象环境,不是对同一运行环境里恶意篡改全局原型的沙箱防御。我们也没有把整个对象图做物理深冻结,而是让外部拿不到可变部分。方法不依赖 this,所以取出 has 单独调用仍然有效。严格模式里的赋值异常只是测试信号;核心承诺是数据无法经公开接口被改写。

这一区别可以直接对照 Object.freeze 与 Map.prototype.set 的规范步骤,不应从函数名字推断深层容器语义。

示例 5,独立运行:

'use strict';
const assert = require('node:assert/strict');
function requireText(value, name) {
  if (typeof value !== 'string') {
    throw new TypeError(`${name} must be a string`);
  }
  if (!value.isWellFormed()) {
    throw new TypeError(`${name} must be well-formed UTF-16`);
  }
}
function createSuffixIndex(text) {
  requireText(text, 'text');
  const states = [{ len: 0, link: -1, next: new Map() }];
  let last = 0;
  let length = 0;
  for (const symbol of text) {
    const current = states.length;
    states.push({ len: ++length, link: 0, next: new Map() });
    let p = last;
    while (p !== -1 && !states[p].next.has(symbol)) {
      states[p].next.set(symbol, current);
      p = states[p].link;
    }
    if (p !== -1) {
      const q = states[p].next.get(symbol);
      if (states[p].len + 1 === states[q].len) {
        states[current].link = q;
      } else {
        const clone = states.length;
        states.push({
          len: states[p].len + 1,
          link: states[q].link,
          next: new Map(states[q].next)
        });
        while (p !== -1 && states[p].next.get(symbol) === q) {
          states[p].next.set(symbol, clone);
          p = states[p].link;
        }
        states[q].link = clone;
        states[current].link = clone;
      }
    }
    last = current;
  }
  let total = 0n;
  for (let v = 1; v < states.length; v++) {
    total += BigInt(states[v].len) - BigInt(states[states[v].link].len);
  }
  return Object.freeze({
    codePointLength: length,
    stateCount: states.length,
    has(pattern) {
      requireText(pattern, 'pattern');
      let v = 0;
      for (const symbol of pattern) {
        const next = states[v].next.get(symbol);
        if (next === undefined) return false;
        v = next;
      }
      return true;
    },
    distinctCount() { return total; }
  });
}

const exposed = Object.freeze(new Map([['x', 1]]));
exposed.set('x', 2);
assert.equal(exposed.get('x'), 2);
const index = createSuffixIndex('😀aba');
assert(Object.isFrozen(index));
assert.throws(() => { index.stateCount = 0; }, TypeError);
assert.throws(() => { index.has = () => false; }, TypeError);
assert.throws(() => { index.states = []; }, TypeError);
const before = index.distinctCount();
const detachedHas = index.has;
for (let i = 0; i < 1000; i++) assert(detachedHas('aba'));
assert.equal(index.distinctCount(), before);
assert.deepEqual(Object.keys(index), ['codePointLength', 'stateCount', 'has', 'distinctCount']);
console.log('frozen Map still changes: 2');
console.log('frozen API, private maps, detached reads: PASS');

实际输出:

frozen Map still changes: 2
frozen API, private maps, detached reads: PASS

六、建立与自动机无关的穷举裁判

验证一个算法最危险的做法,是再写一份形状几乎一样的算法作为参考。两份程序可能共享同一种错误。这里的参考实现完全不使用状态、后缀链接或克隆:计数器用两层循环枚举码点数组的所有连续区间,再用 Set 去重;成员查询器逐起点、逐码点进行比较。它们慢,但短小、直接,适合短输入上的正确性裁判。

我们枚举由 a、b 和笑脸组成、长度不超过五的全部文本,共三百六十四份。模式集覆盖另一个四字符表上长度不超过三的所有字符串,并额外加入每份文本的全部真实子串。额外的界字专门提供负例,空模式也在集合中。这既检查已知出现的长模式,也检查不存在的短模式,而不是只从原文抽取永远应该为真的样本。

实测产生三万一千七百四十七次成员比较,每份文本还核对了不同子串总数和码点长度。有限穷举当然不是数学证明,它覆盖的是明确列出的输入域;它的价值在于让后续改动拥有可以重复运行的证据。若 AI 建议合并某个分支或复用某张 Map,应先让它说明不变量,再让这组测试决定改动能否保留。

示例 6,独立运行:

'use strict';
const assert = require('node:assert/strict');
function requireText(value, name) {
  if (typeof value !== 'string') {
    throw new TypeError(`${name} must be a string`);
  }
  if (!value.isWellFormed()) {
    throw new TypeError(`${name} must be well-formed UTF-16`);
  }
}
function createSuffixIndex(text) {
  requireText(text, 'text');
  const states = [{ len: 0, link: -1, next: new Map() }];
  let last = 0;
  let length = 0;
  for (const symbol of text) {
    const current = states.length;
    states.push({ len: ++length, link: 0, next: new Map() });
    let p = last;
    while (p !== -1 && !states[p].next.has(symbol)) {
      states[p].next.set(symbol, current);
      p = states[p].link;
    }
    if (p !== -1) {
      const q = states[p].next.get(symbol);
      if (states[p].len + 1 === states[q].len) {
        states[current].link = q;
      } else {
        const clone = states.length;
        states.push({
          len: states[p].len + 1,
          link: states[q].link,
          next: new Map(states[q].next)
        });
        while (p !== -1 && states[p].next.get(symbol) === q) {
          states[p].next.set(symbol, clone);
          p = states[p].link;
        }
        states[q].link = clone;
        states[current].link = clone;
      }
    }
    last = current;
  }
  let total = 0n;
  for (let v = 1; v < states.length; v++) {
    total += BigInt(states[v].len) - BigInt(states[states[v].link].len);
  }
  return Object.freeze({
    codePointLength: length,
    stateCount: states.length,
    has(pattern) {
      requireText(pattern, 'pattern');
      let v = 0;
      for (const symbol of pattern) {
        const next = states[v].next.get(symbol);
        if (next === undefined) return false;
        v = next;
      }
      return true;
    },
    distinctCount() { return total; }
  });
}
function bruteSubstrings(text) {
  const points = Array.from(text);
  const found = new Set();
  for (let start = 0; start < points.length; start++) {
    let value = '';
    for (let end = start; end < points.length; end++) {
      value += points[end];
      found.add(value);
    }
  }
  return found;
}
function bruteHas(text, pattern) {
  const source = Array.from(text), query = Array.from(pattern);
  for (let start = 0; start <= source.length - query.length; start++) {
    let k = 0;
    while (k < query.length && source[start + k] === query[k]) k++;
    if (k === query.length) return true;
  }
  return false;
}

function words(alphabet, maxLength) {
  const all = [''];
  let layer = [''];
  for (let length = 1; length <= maxLength; length++) {
    layer = layer.flatMap(prefix => alphabet.map(symbol => prefix + symbol));
    all.push(...layer);
  }
  return all;
}
const texts = words(['a', 'b', '😀'], 5);
const queries = words(['a', 'b', '😀', '界'], 3);
let checks = 0;
for (const text of texts) {
  const index = createSuffixIndex(text);
  const expected = bruteSubstrings(text);
  assert.equal(index.distinctCount(), BigInt(expected.size));
  assert.equal(index.codePointLength, Array.from(text).length);
  for (const query of new Set([...queries, ...expected])) {
    assert.equal(index.has(query), bruteHas(text, query));
    checks++;
  }
}
console.log(`texts=${texts.length} membershipChecks=${checks}`);
console.log('exhaustive membership and counts: PASS');

实际输出:

texts=364 membershipChecks=31747
exhaustive membership and counts: PASS

七、把组合符、连接符与非法输入补进测试矩阵

小字母表穷举能够压实结构分支,却不能代替字符语义测试。接下来使用固定种子的伪随机生成器,在普通字母、汉字、补充平面符号、组合重音、零宽连接符和空字符之间取样。五百个文本分别与暴力计数器比对,真实子串必须全部可查,再加入每份文本二十个独立模式。固定种子让失败能够在下一台机器上复现,而不是依赖偶然的随机结果。

错误路径同样值得测试:孤立代理项不能在构建时被拒绝,却在查询时被默默接受;模式前面已经没有转移,也不能使尾部的非法编码逃过检查。示例中的 z 加孤立高代理项专门验证完整校验发生在查询之前。字符串包装对象也按契约拒绝,不会因它看起来像字符串就绕过类型边界。

最后两个断言故意挑战直觉:预组合重音与分解形式不匹配,而由女性、零宽连接符和电脑构成的表情序列包含三个码点,其中的连接符本身也是合法子串。这并不代表适合直接拿结果驱动用户界面的选区;若产品需求是完整可见字符,必须换成字素簇分段后的另一套契约和参考实现。

示例 7,独立运行:

'use strict';
const assert = require('node:assert/strict');
function requireText(value, name) {
  if (typeof value !== 'string') {
    throw new TypeError(`${name} must be a string`);
  }
  if (!value.isWellFormed()) {
    throw new TypeError(`${name} must be well-formed UTF-16`);
  }
}
function createSuffixIndex(text) {
  requireText(text, 'text');
  const states = [{ len: 0, link: -1, next: new Map() }];
  let last = 0;
  let length = 0;
  for (const symbol of text) {
    const current = states.length;
    states.push({ len: ++length, link: 0, next: new Map() });
    let p = last;
    while (p !== -1 && !states[p].next.has(symbol)) {
      states[p].next.set(symbol, current);
      p = states[p].link;
    }
    if (p !== -1) {
      const q = states[p].next.get(symbol);
      if (states[p].len + 1 === states[q].len) {
        states[current].link = q;
      } else {
        const clone = states.length;
        states.push({
          len: states[p].len + 1,
          link: states[q].link,
          next: new Map(states[q].next)
        });
        while (p !== -1 && states[p].next.get(symbol) === q) {
          states[p].next.set(symbol, clone);
          p = states[p].link;
        }
        states[q].link = clone;
        states[current].link = clone;
      }
    }
    last = current;
  }
  let total = 0n;
  for (let v = 1; v < states.length; v++) {
    total += BigInt(states[v].len) - BigInt(states[states[v].link].len);
  }
  return Object.freeze({
    codePointLength: length,
    stateCount: states.length,
    has(pattern) {
      requireText(pattern, 'pattern');
      let v = 0;
      for (const symbol of pattern) {
        const next = states[v].next.get(symbol);
        if (next === undefined) return false;
        v = next;
      }
      return true;
    },
    distinctCount() { return total; }
  });
}
function bruteSubstrings(text) {
  const points = Array.from(text);
  const found = new Set();
  for (let start = 0; start < points.length; start++) {
    let value = '';
    for (let end = start; end < points.length; end++) {
      value += points[end];
      found.add(value);
    }
  }
  return found;
}
function bruteHas(text, pattern) {
  const source = Array.from(text), query = Array.from(pattern);
  for (let start = 0; start <= source.length - query.length; start++) {
    let k = 0;
    while (k < query.length && source[start + k] === query[k]) k++;
    if (k === query.length) return true;
  }
  return false;
}

let seed = 0x12345678;
function random() {
  seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
  return seed;
}
const alphabet = ['a', '😀', '界', '\u0301', '\u200D', '\0'];
function randomWord(max) {
  const n = random() % (max + 1);
  return Array.from({ length: n }, () => alphabet[random() % alphabet.length]).join('');
}
for (let run = 0; run < 500; run++) {
  const text = randomWord(14), index = createSuffixIndex(text);
  const expected = bruteSubstrings(text);
  assert.equal(index.distinctCount(), BigInt(expected.size));
  for (const query of expected) assert(index.has(query));
  for (let i = 0; i < 20; i++) {
    const query = randomWord(8);
    assert.equal(index.has(query), bruteHas(text, query));
  }
}
const index = createSuffixIndex('😀');
for (const bad of [null, 1, {}, new String('a'), '\uD800', '\uDC00', 'z\uD800']) {
  assert.throws(() => createSuffixIndex(bad), TypeError);
  assert.throws(() => index.has(bad), TypeError);
}
assert.equal(createSuffixIndex('é').has('e\u0301'), false);
assert.equal(createSuffixIndex('👩\u200D💻').codePointLength, 3);
assert.equal(createSuffixIndex('👩\u200D💻').has('\u200D'), true);
console.log('seed=0x12345678 randomTexts=500: PASS');
console.log('types, surrogates, normalization, ZWJ: PASS');

实际输出:

seed=0x12345678 randomTexts=500: PASS
types, surrogates, normalization, ZWJ: PASS

八、检查长链与状态增长,别把测试当性能承诺

重复同一个符号是很有价值的结构测试:两万个笑脸应该产生两万种非空不同子串,以及包含根在内的两万零一个状态。它同时检查码元长度和码点长度是否混淆。另一个输入由 a 后接一千个 b 组成,会频繁走到拆分类别的场景,状态数和不同子串数都应为两千零一。

后缀自动机的图规模是线性的;长度至少为二时,经典状态上界为两倍长度减一。实现只保存图,没有保存每个子串的正文。若把 Map 的查询和更新视作平均常数时间,构建可按线性预期时间理解,成员查询按模式长度线性进行,额外索引空间为线性。克隆复制的是出边表,每份新增条目会保留为图中的出边,不是在复制整份历史文本。

这类复杂度表述必须带上模型假设。ECMAScript 对 Map 的要求是平均访问时间相对于条目数次线性,并没有为所有引擎承诺严格的常数时间。BigInt 的加减也有随位数增长的成本,不能在位复杂度模型里一概当作免费。源码的状态长度使用普通机器整数,而计数位数至多随文本长度的对数增长。

此外,has 先对完整模式执行良构校验,所以即使第一条边就失败,也已经扫描过模式。这段测试没有输出耗时,更没有据此宣称适合某个吞吐量或内存预算。实际部署前应按真实字符分布、文本长度、同时存活的索引数量和进程堆上限测量;公开接口接收不受信任的大文本时,还应在业务入口设置尺寸限制。

示例 8,独立运行:

'use strict';
const assert = require('node:assert/strict');
function requireText(value, name) {
  if (typeof value !== 'string') {
    throw new TypeError(`${name} must be a string`);
  }
  if (!value.isWellFormed()) {
    throw new TypeError(`${name} must be well-formed UTF-16`);
  }
}
function createSuffixIndex(text) {
  requireText(text, 'text');
  const states = [{ len: 0, link: -1, next: new Map() }];
  let last = 0;
  let length = 0;
  for (const symbol of text) {
    const current = states.length;
    states.push({ len: ++length, link: 0, next: new Map() });
    let p = last;
    while (p !== -1 && !states[p].next.has(symbol)) {
      states[p].next.set(symbol, current);
      p = states[p].link;
    }
    if (p !== -1) {
      const q = states[p].next.get(symbol);
      if (states[p].len + 1 === states[q].len) {
        states[current].link = q;
      } else {
        const clone = states.length;
        states.push({
          len: states[p].len + 1,
          link: states[q].link,
          next: new Map(states[q].next)
        });
        while (p !== -1 && states[p].next.get(symbol) === q) {
          states[p].next.set(symbol, clone);
          p = states[p].link;
        }
        states[q].link = clone;
        states[current].link = clone;
      }
    }
    last = current;
  }
  let total = 0n;
  for (let v = 1; v < states.length; v++) {
    total += BigInt(states[v].len) - BigInt(states[states[v].link].len);
  }
  return Object.freeze({
    codePointLength: length,
    stateCount: states.length,
    has(pattern) {
      requireText(pattern, 'pattern');
      let v = 0;
      for (const symbol of pattern) {
        const next = states[v].next.get(symbol);
        if (next === undefined) return false;
        v = next;
      }
      return true;
    },
    distinctCount() { return total; }
  });
}

const n = 20000;
const text = '😀'.repeat(n);
const index = createSuffixIndex(text);
assert.equal(text.length, n * 2);
assert.equal(index.codePointLength, n);
assert.equal(index.stateCount, n + 1);
assert.equal(index.distinctCount(), BigInt(n));
assert(index.has('😀'.repeat(n)));
assert.equal(index.has('😀'.repeat(n + 1)), false);
assert.equal(index.has('😀a'), false);
const growing = createSuffixIndex('a' + 'b'.repeat(1000));
assert.equal(growing.stateCount, 2001);
assert.equal(growing.distinctCount(), 2001n);
console.log('repeat: points=20000 states=20001 distinct=20000');
console.log('ab^1000: states=2001 distinct=2001');

实际输出:

repeat: points=20000 states=20001 distinct=20000
ab^1000: states=2001 distinct=2001

九、接入 JSON 边界,并保留旧快照

算法返回 BigInt 是类型契约,网络协议如何表达它是另一层问题。直接把含 BigInt 的对象交给 JSON.stringify 会抛出 TypeError,因而下面显式把计数转成十进制字符串。同时写明单位是 Unicode 码点,以及计数不包含空串,避免下游把一个精确整数重新转成可能失真的 Number,或与包含空串的另一个系统相差一。

请求中的模式数组仍逐项经过 has 的完整验证,不会因为最外层是数组就默认元素合法。示例只展示一个内存中的适配函数,不包含网络发送、服务器框架或隐含的文件读取。生产接口还需要自己的请求大小、批次数量和错误响应策略,这些都不应在算法演示里悄悄替业务做决定。

旧文本 ab 与新文本 abc 分别创建索引后,旧对象依然不能匹配 c,新对象可以。这个测试说明两个构建结果互相独立;它并不表示追加一个字符只需固定成本。当前设计选择重新构建来换取容易审查的静态边界。如果以后需要流式追加、返回出现位置或计算出现次数,应另起设计与测试,尤其不能直接把目前的长度差计数当成频次。

示例 9,独立运行:

'use strict';
const assert = require('node:assert/strict');
function requireText(value, name) {
  if (typeof value !== 'string') {
    throw new TypeError(`${name} must be a string`);
  }
  if (!value.isWellFormed()) {
    throw new TypeError(`${name} must be well-formed UTF-16`);
  }
}
function createSuffixIndex(text) {
  requireText(text, 'text');
  const states = [{ len: 0, link: -1, next: new Map() }];
  let last = 0;
  let length = 0;
  for (const symbol of text) {
    const current = states.length;
    states.push({ len: ++length, link: 0, next: new Map() });
    let p = last;
    while (p !== -1 && !states[p].next.has(symbol)) {
      states[p].next.set(symbol, current);
      p = states[p].link;
    }
    if (p !== -1) {
      const q = states[p].next.get(symbol);
      if (states[p].len + 1 === states[q].len) {
        states[current].link = q;
      } else {
        const clone = states.length;
        states.push({
          len: states[p].len + 1,
          link: states[q].link,
          next: new Map(states[q].next)
        });
        while (p !== -1 && states[p].next.get(symbol) === q) {
          states[p].next.set(symbol, clone);
          p = states[p].link;
        }
        states[q].link = clone;
        states[current].link = clone;
      }
    }
    last = current;
  }
  let total = 0n;
  for (let v = 1; v < states.length; v++) {
    total += BigInt(states[v].len) - BigInt(states[states[v].link].len);
  }
  return Object.freeze({
    codePointLength: length,
    stateCount: states.length,
    has(pattern) {
      requireText(pattern, 'pattern');
      let v = 0;
      for (const symbol of pattern) {
        const next = states[v].next.get(symbol);
        if (next === undefined) return false;
        v = next;
      }
      return true;
    },
    distinctCount() { return total; }
  });
}

function inspectRequest(request) {
  const index = createSuffixIndex(request.text);
  if (!Array.isArray(request.patterns)) throw new TypeError('patterns must be an array');
  const matches = request.patterns.map(pattern => ({ pattern, present: index.has(pattern) }));
  return JSON.stringify({
    unit: 'Unicode code point',
    emptyIncludedInCount: false,
    distinct: index.distinctCount().toString(),
    matches
  });
}
const older = createSuffixIndex('ab');
const newer = createSuffixIndex('abc');
assert.equal(older.has('c'), false);
assert.equal(newer.has('c'), true);
assert.throws(() => JSON.stringify({ count: older.distinctCount() }), TypeError);
const result = inspectRequest({ text: '😀a😀', patterns: ['', 'a😀', '😀😀'] });
assert.equal(JSON.parse(result).distinct, '5');
console.log(result);
console.log('separate snapshots: PASS');

实际输出:

{"unit":"Unicode code point","emptyIncludedInCount":false,"distinct":"5","matches":[{"pattern":"","present":true},{"pattern":"a😀","present":true},{"pattern":"😀😀","present":false}]}
separate snapshots: PASS

把 AI 审查变成可复核的交付

一份可靠的审查结论应当能回答:输入的字符单位是什么,非法编码在哪里失败,空串在哪些接口被包含,克隆复制了哪些内容,外部究竟能拿到哪些引用,以及计数什么时候进入精确整数域。本文的实现把这些问题变成了接口契约和九段独立程序,而不是把正确性寄托在自动机这个名字上。

复核时可以按顺序执行三步:先运行单独的语义与克隆回归,再运行有独立裁判的穷举和固定种子测试,最后检查长输入及序列化边界。所有断言通过后,还要阅读失败分支和复杂度假设。AI 适合帮助生成反例、解释不变量和整理重复测试,但最终应以实际执行结果与可追溯的定义为依据。文章中的代码、输出和有限测试范围构成可复查的证据,不构成对所有运行环境的性能或安全保证。

资料核对日期:2026 年 10 月 19 日。算法定义参考作者资料 Text Algorithms 与 DAWG 研究论文;JavaScript 行为参考 TC39 的 ECMAScript 规范。本文代码、示例数据、测试设计与解释均为围绕本接口重新编写,图像为独立生成的 AI 概念插画。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。