AI 代码审查实战:用 Aho–Corasick 实现不可变 Unicode 多模式匹配器

10-19 4阅读

同一份文本要同时寻找几十个关键词时,逐个调用字符串查找当然能写出功能,但它并没有回答一个更有意思的问题:能否把词典编译一次,让每段新文本只沿同一台机器前进?本文把这个问题作为 AI 代码审查练习,用 JavaScript 实现一个按 Unicode 码点工作的 Aho–Corasick 多模式匹配器。审查目标不仅是找到某个词,还包括保留重叠、记录重复模式的身份、给出可复现的结果顺序,以及保护已经构建好的词典快照。

这里的任务与单模式 KMP、普通 Trie 前缀检索、固定文本的后缀自动机不同:我们固定的是一组模式,随后扫描任意文本。Trie 只提供共享前缀,失败链接把已读文本的有用后缀接回词典,输出链接再枚举所有在当前位置结束的模式。三个职责都存在,才是本次需要审查的多模式失败自动机。

AI 代码审查实战:用 Aho–Corasick 实现不可变 Unicode 多模式匹配器
AI 生成概念图:分支表示共享前缀,虚线表示回退,重叠光框表示同一文本上的多个命中。画面为算法意象,不是可以直接执行的状态图。

全文恰好九段 JavaScript,分别保存为 01.cjs 至 09.cjs。每段都有完整依赖定义,无需运行前一段,也不需要安装第三方包。实测环境为 Node.js v24.19.0,统一执行方式是 node --unhandled-rejections=strict 01.cjs,其余替换编号。普通文本框记录实际标准输出;重复出现的完整构建器是为了让每段都能复制运行。

一、先审查草稿的承诺,而不是变量命名

下面是一段专门用于演示审查缺陷的最小草稿。它对每个模式只调用一次 indexOf,因此最多报告第一次命中,也没有表达结束位置、重叠和同义规则的身份。更隐蔽的问题是索引单位:笑脸在 UTF-16 中占两个码元,接下来的 aa 起点被写成二,而我们的契约要的是一码点。即使把函数重命名为 UnicodeMatcher,行为也不会改变。

同一示例还展示一个不可变性陷阱。Object.freeze 约束对象属性,却不会禁止 Map 的 set 修改内部条目。因此,公开一个冻结的 Map 不是只读索引。审查 AI 生成代码时,应追问外部是否能拿到可变引用,而不是只搜索源码里有没有 freeze。这里的断言故意证明草稿存在的问题,所以整段程序依旧应成功退出。

这一点可以对照 ECMAScript 的 Object.freeze 定义与 Map.prototype.set 的内部条目操作核验。本文的防线是封装和不再写入,冻结公开外壳只是额外约束。

示例 1,独立运行:

'use strict';
const assert = require('node:assert/strict');
function firstOnly(patterns, text) {
  return patterns.map((pattern, id) => ({ id, start: text.indexOf(pattern) }));
}
const wrong = firstOnly(['😀', 'aa'], '😀aaa');
assert.deepEqual(wrong, [{ id: 0, start: 0 }, { id: 1, start: 2 }]);
assert.notEqual(wrong[1].start, Array.from('😀').length);
const exposed = Object.freeze(new Map([['a', 1]]));
exposed.set('a', 99);
assert.equal(exposed.get('a'), 99);
console.log('firstOnly: UTF-16 offset 2; expected codepoint offset 1');
console.log('overlap omitted; frozen Map still accepts set');

实际输出:

firstOnly: UTF-16 offset 2; expected codepoint offset 1
overlap omitted; frozen Map still accepts set

二、把字符单位、异常和位置变成协议

本实现只接受字符串原始值,拒绝字符串包装对象、数字、空值以及任何包含孤立代理项的非良构 UTF-16 字符串。模式列表必须是数组,数组空洞也会作为非法元素被拒绝。每个模式必须非空;空词典合法,空文本合法。拒绝空模式是明确的产品选择:否则每个边界都应考虑零长度命中,根节点和位置零也需要专门的输出规则。我们不让这些规则隐式混入非空匹配。

字符串迭代器按码点返回字符串,本文以它作为边的标签,结束位置 end 是已经读过的码点数量。命中区间统一采用从零开始的左闭右开形式 [start,end),因此长度始终等于 end 减 start。语言依据是 ECMAScript 字符串迭代器和 isWellFormed。

码点也不是屏幕上一个完整字符。组合重音、零宽连接符和表情序列可能包含多个码点,Unicode 文本分割规范对字素簇有另一套边界规则。下面的边界数组只负责把本接口的码点坐标转换成 JavaScript slice 使用的码元坐标,不能拿来宣称获得了字素簇索引。转换应建立在同一份原文上,不能在文本变更后继续复用。

示例 2,独立运行:

'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.equal(points('👩‍💻').length, 3);
assert.throws(() => points('\uD800'), TypeError);
assert.throws(() => points(new String('a')), TypeError);
const boundaries = [0];
for (const ch of text) boundaries.push(boundaries.at(-1) + ch.length);
assert.deepEqual(boundaries, [0, 1, 3, 4, 5]);
assert.equal(text.slice(boundaries[1], boundaries[2]), '😀');
console.log('code units=5; codepoints=4; boundaries=0,1,3,4,5');

实际输出:

code units=5; codepoints=4; boundaries=0,1,3,4,5

三、建 Trie,再按层建立失败链接与输出链接

节点有四类信息:next 保存显式的词典边,fail 指向最长的可用真后缀,out 只保存恰好在该节点结束的原始模式编号,dict 指向失败链上最近的非空终止节点。根节点编号为零,也作为不存在输出链接的哨兵。第一层节点的失败链接保持为根;广度优先遍历更深的边时,父节点以及所有较浅的失败目标已经准备完毕。队列使用递增头下标,避免反复删除数组首项。

处理父节点的一条字符边时,先取父节点的 fail;如果那里没有对应边,就继续沿失败链回退。找到转移后,它就是子节点的失败目标,根也没有则回到零。输出链接不是把所有后缀模式复制到每个节点,而是连接到最近终止节点,查询时沿链走。这样,一个模式编号只存放在自己的终止节点,重复模式也只是同一 out 中的多个编号。

Aho 与 Corasick 的原始论文 Efficient String Matching: An Aid to Bibliographic Search建立了由模式集合构造机器、再扫描文本的基本框架。这里的输出链接、冻结接口和重复编号协议属于本文的工程实现选择,不把某一库的默认行为当作算法的必然定义。下面先用经典词典核验:she 命中时,其后缀 he 也必须出现,随后 hers 仍然能够继续匹配。

示例 3,独立运行:

'use strict';
const assert = require('node:assert/strict');
function checkString(value) {
  if (typeof value !== 'string' || !value.isWellFormed()) {
    throw new TypeError('expected a well-formed string');
  }
  return value;
}
function buildMatcher(input) {
  if (!Array.isArray(input)) throw new TypeError('expected an array');
  const patterns = [], lengths = [];
  for (let id = 0; id < input.length; id++) {
    const pattern = checkString(input[id]);
    if (pattern === '') throw new RangeError('empty pattern');
    patterns.push(pattern);
    lengths.push(Array.from(pattern).length);
  }
  const node = () => ({ next: new Map(), fail: 0, out: [], dict: 0 });
  const nodes = [node()];
  for (let id = 0; id < patterns.length; id++) {
    let state = 0;
    for (const ch of patterns[id]) {
      if (!nodes[state].next.has(ch)) {
        nodes[state].next.set(ch, nodes.length);
        nodes.push(node());
      }
      state = nodes[state].next.get(ch);
    }
    nodes[state].out.push(id);
  }
  const queue = [...nodes[0].next.values()];
  for (let head = 0; head < queue.length; head++) {
    const state = queue[head];
    for (const [ch, child] of nodes[state].next) {
      let fallback = nodes[state].fail;
      while (fallback !== 0 && !nodes[fallback].next.has(ch)) {
        fallback = nodes[fallback].fail;
      }
      const target = nodes[fallback].next.get(ch) ?? 0;
      nodes[child].fail = target;
      nodes[child].dict = nodes[target].out.length ? target : nodes[target].dict;
      queue.push(child);
    }
  }
  Object.freeze(patterns);
  Object.freeze(lengths);
  for (const item of nodes) {
    Object.freeze(item.out);
    Object.freeze(item);
  }
  Object.freeze(nodes);
  function find(text) {
    checkString(text);
    const matches = [];
    let state = 0, end = 0;
    for (const ch of text) {
      end++;
      while (state !== 0 && !nodes[state].next.has(ch)) {
        state = nodes[state].fail;
      }
      state = nodes[state].next.get(ch) ?? 0;
      for (let terminal = state; terminal !== 0; terminal = nodes[terminal].dict) {
        for (const id of nodes[terminal].out) {
          matches.push(Object.freeze({
            id, pattern: patterns[id], start: end - lengths[id], end
          }));
        }
      }
    }
    return Object.freeze(matches);
  }
  return Object.freeze({ patternCount: patterns.length, find });
}
const matcher = buildMatcher(['he', 'she', 'his', 'hers']);
const actual = matcher.find('ushers');
assert.deepEqual(actual, [
  { id: 1, pattern: 'she', start: 1, end: 4 },
  { id: 0, pattern: 'he', start: 2, end: 4 },
  { id: 3, pattern: 'hers', start: 2, end: 6 }
]);
for (const m of actual) console.log(`${m.pattern}#${m.id} [${m.start},${m.end})`);

实际输出:

she#1 [1,4)
he#0 [2,4)
hers#3 [2,6)

四、重叠与重复模式必须在同一条顺序规则下工作

相同字符串在词典中出现两次,可能代表两条不同的业务规则,本文保留两个原始下标,不自动去重。每个命中返回 id、pattern、start、end,调用方可以把 id 映射回自己的配置。若业务需要按字符串去重,应在构建前明确执行,并自行维护旧编号到新编号的关系;不能在自动机内部悄悄改变身份。

结果顺序定义为 end 升序,再按 start 升序,最后按 id 升序。它不是按起点全局排序:较短的后置命中可能更早结束,所以先被报告。扫描天然按结束位置前进;同一终点先报告当前状态,再沿输出链接走向更短的后缀,起点便越来越大;同一节点的重复编号按输入顺序追加,最后一个比较键也已经稳定。不需要查询结束后再做全局排序。

注意匹配后不能把 state 重置为根,也不能把文本游标跳过一个完整模式。那样会遗漏 aaa 中相互覆盖的 aa。下面同时验证深层后缀、重复身份、三字符长模式与空输入策略,九条命中缺一条都说明契约被破坏。

示例 4,独立运行:

'use strict';
const assert = require('node:assert/strict');
function checkString(value) {
  if (typeof value !== 'string' || !value.isWellFormed()) {
    throw new TypeError('expected a well-formed string');
  }
  return value;
}
function buildMatcher(input) {
  if (!Array.isArray(input)) throw new TypeError('expected an array');
  const patterns = [], lengths = [];
  for (let id = 0; id < input.length; id++) {
    const pattern = checkString(input[id]);
    if (pattern === '') throw new RangeError('empty pattern');
    patterns.push(pattern);
    lengths.push(Array.from(pattern).length);
  }
  const node = () => ({ next: new Map(), fail: 0, out: [], dict: 0 });
  const nodes = [node()];
  for (let id = 0; id < patterns.length; id++) {
    let state = 0;
    for (const ch of patterns[id]) {
      if (!nodes[state].next.has(ch)) {
        nodes[state].next.set(ch, nodes.length);
        nodes.push(node());
      }
      state = nodes[state].next.get(ch);
    }
    nodes[state].out.push(id);
  }
  const queue = [...nodes[0].next.values()];
  for (let head = 0; head < queue.length; head++) {
    const state = queue[head];
    for (const [ch, child] of nodes[state].next) {
      let fallback = nodes[state].fail;
      while (fallback !== 0 && !nodes[fallback].next.has(ch)) {
        fallback = nodes[fallback].fail;
      }
      const target = nodes[fallback].next.get(ch) ?? 0;
      nodes[child].fail = target;
      nodes[child].dict = nodes[target].out.length ? target : nodes[target].dict;
      queue.push(child);
    }
  }
  Object.freeze(patterns);
  Object.freeze(lengths);
  for (const item of nodes) {
    Object.freeze(item.out);
    Object.freeze(item);
  }
  Object.freeze(nodes);
  function find(text) {
    checkString(text);
    const matches = [];
    let state = 0, end = 0;
    for (const ch of text) {
      end++;
      while (state !== 0 && !nodes[state].next.has(ch)) {
        state = nodes[state].fail;
      }
      state = nodes[state].next.get(ch) ?? 0;
      for (let terminal = state; terminal !== 0; terminal = nodes[terminal].dict) {
        for (const id of nodes[terminal].out) {
          matches.push(Object.freeze({
            id, pattern: patterns[id], start: end - lengths[id], end
          }));
        }
      }
    }
    return Object.freeze(matches);
  }
  return Object.freeze({ patternCount: patterns.length, find });
}
const matcher = buildMatcher(['a', 'aa', 'a', 'aaa']);
const actual = matcher.find('aaa');
assert.deepEqual(actual.map(m => [m.end, m.start, m.id]), [
  [1, 0, 0], [1, 0, 2],
  [2, 0, 1], [2, 1, 0], [2, 1, 2],
  [3, 0, 3], [3, 1, 1], [3, 2, 0], [3, 2, 2]
]);
assert.equal(buildMatcher([]).find('anything').length, 0);
assert.equal(matcher.find('').length, 0);
assert.throws(() => buildMatcher(['a', '']), RangeError);
console.log(actual.map(m => `${m.end}:${m.start}:${m.id}`).join(' '));
console.log('empty dictionary allowed; empty pattern rejected');

实际输出:

1:0:0 1:0:2 2:0:1 2:1:0 2:1:2 3:0:3 3:1:1 3:2:0 3:2:2
empty dictionary allowed; empty pattern rejected

五、Unicode 的正确性包括拒绝偷偷归一化

我们做区分大小写的精确码点序列比较,不进行 NFC 归一化,不做大小写折叠,也不根据地区改变等价关系。预组合 é 与 e 后接组合重音在本接口中不同;后一种形式占两个码点,因此命中的结束位置也不同。是否应把它们视作相等,是调用方的数据协议,不能由一个看似友好的清理步骤代替决定。

如果调用方确实要先归一化,模式和文本必须采用一致方式,而且结果位置属于归一化后的文本。原文中的码点数可能已经改变,不能直接把结果带回原文高亮。保留坐标映射是另一项工作。下面还匹配由多个码点组成的程序员表情:整串命中和末尾电脑码点命中都合法,这清楚表明本实现允许命中落在用户感知字符的内部。

示例 5,独立运行:

'use strict';
const assert = require('node:assert/strict');
function checkString(value) {
  if (typeof value !== 'string' || !value.isWellFormed()) {
    throw new TypeError('expected a well-formed string');
  }
  return value;
}
function buildMatcher(input) {
  if (!Array.isArray(input)) throw new TypeError('expected an array');
  const patterns = [], lengths = [];
  for (let id = 0; id < input.length; id++) {
    const pattern = checkString(input[id]);
    if (pattern === '') throw new RangeError('empty pattern');
    patterns.push(pattern);
    lengths.push(Array.from(pattern).length);
  }
  const node = () => ({ next: new Map(), fail: 0, out: [], dict: 0 });
  const nodes = [node()];
  for (let id = 0; id < patterns.length; id++) {
    let state = 0;
    for (const ch of patterns[id]) {
      if (!nodes[state].next.has(ch)) {
        nodes[state].next.set(ch, nodes.length);
        nodes.push(node());
      }
      state = nodes[state].next.get(ch);
    }
    nodes[state].out.push(id);
  }
  const queue = [...nodes[0].next.values()];
  for (let head = 0; head < queue.length; head++) {
    const state = queue[head];
    for (const [ch, child] of nodes[state].next) {
      let fallback = nodes[state].fail;
      while (fallback !== 0 && !nodes[fallback].next.has(ch)) {
        fallback = nodes[fallback].fail;
      }
      const target = nodes[fallback].next.get(ch) ?? 0;
      nodes[child].fail = target;
      nodes[child].dict = nodes[target].out.length ? target : nodes[target].dict;
      queue.push(child);
    }
  }
  Object.freeze(patterns);
  Object.freeze(lengths);
  for (const item of nodes) {
    Object.freeze(item.out);
    Object.freeze(item);
  }
  Object.freeze(nodes);
  function find(text) {
    checkString(text);
    const matches = [];
    let state = 0, end = 0;
    for (const ch of text) {
      end++;
      while (state !== 0 && !nodes[state].next.has(ch)) {
        state = nodes[state].fail;
      }
      state = nodes[state].next.get(ch) ?? 0;
      for (let terminal = state; terminal !== 0; terminal = nodes[terminal].dict) {
        for (const id of nodes[terminal].out) {
          matches.push(Object.freeze({
            id, pattern: patterns[id], start: end - lengths[id], end
          }));
        }
      }
    }
    return Object.freeze(matches);
  }
  return Object.freeze({ patternCount: patterns.length, find });
}
const text = '😀e\u0301😀é';
const matcher = buildMatcher(['😀', 'e\u0301', 'é', '😀é']);
assert.deepEqual(matcher.find(text).map(m => [m.id, m.start, m.end]), [
  [0, 0, 1], [1, 1, 3], [0, 3, 4], [3, 3, 5], [2, 4, 5]
]);
assert.equal(buildMatcher(['é']).find('e\u0301').length, 0);
assert.deepEqual(buildMatcher(['💻', '👩‍💻']).find('👩‍💻').map(m => [m.id, m.start, m.end]), [
  [1, 0, 3], [0, 2, 3]
]);
const normalized = buildMatcher(['é']).find('e\u0301'.normalize('NFC'));
assert.equal(normalized[0].end, 1);
for (const m of matcher.find(text)) console.log(`${m.id} [${m.start},${m.end})`);
console.log('NFC end=1 refers to normalized text');

实际输出:

0 [0,1)
1 [1,3)
0 [3,4)
3 [3,5)
2 [4,5)
NFC end=1 refers to normalized text

六、不可变是一条引用边界,不是一个装饰器

构建器先读取并校验全部模式,再复制字符串和长度,之后只在内部建立状态。所有 Map 留在闭包中,不通过返回值、调试属性或回调暴露。构建完成后 find 只读取图,每次调用都拥有自己的 state、end 和结果数组。公开对象、结果数组以及每条结果记录都冻结,所以调用方既不能替换方法,也不能把一个查询的记录改写成另一个查询的事实。

这是一种构建后只读快照,并不是支持增量添加和结构共享的持久化数据结构。需要更换词典时,构建一个新实例,再由业务替换持有它的引用;旧实例继续表达旧词典。本文假定普通数组和标准内建对象,没有把带恶意 getter、Proxy 或被篡改的内建原型当作安全隔离边界。面对不可信进程,应在更外层处理数据验证和执行隔离。

测试时不能只调用 Object.isFrozen。还要真的尝试修改输入数组、替换查询方法、修改结果字段和追加结果,并在严格模式下检查异常。随后重新查询,确认旧实例的答案没有变化。下面的新实例使用另一份词典,验证的是实例隔离,没有把重新构建当成原地更新。

示例 6,独立运行:

'use strict';
const assert = require('node:assert/strict');
function checkString(value) {
  if (typeof value !== 'string' || !value.isWellFormed()) {
    throw new TypeError('expected a well-formed string');
  }
  return value;
}
function buildMatcher(input) {
  if (!Array.isArray(input)) throw new TypeError('expected an array');
  const patterns = [], lengths = [];
  for (let id = 0; id < input.length; id++) {
    const pattern = checkString(input[id]);
    if (pattern === '') throw new RangeError('empty pattern');
    patterns.push(pattern);
    lengths.push(Array.from(pattern).length);
  }
  const node = () => ({ next: new Map(), fail: 0, out: [], dict: 0 });
  const nodes = [node()];
  for (let id = 0; id < patterns.length; id++) {
    let state = 0;
    for (const ch of patterns[id]) {
      if (!nodes[state].next.has(ch)) {
        nodes[state].next.set(ch, nodes.length);
        nodes.push(node());
      }
      state = nodes[state].next.get(ch);
    }
    nodes[state].out.push(id);
  }
  const queue = [...nodes[0].next.values()];
  for (let head = 0; head < queue.length; head++) {
    const state = queue[head];
    for (const [ch, child] of nodes[state].next) {
      let fallback = nodes[state].fail;
      while (fallback !== 0 && !nodes[fallback].next.has(ch)) {
        fallback = nodes[fallback].fail;
      }
      const target = nodes[fallback].next.get(ch) ?? 0;
      nodes[child].fail = target;
      nodes[child].dict = nodes[target].out.length ? target : nodes[target].dict;
      queue.push(child);
    }
  }
  Object.freeze(patterns);
  Object.freeze(lengths);
  for (const item of nodes) {
    Object.freeze(item.out);
    Object.freeze(item);
  }
  Object.freeze(nodes);
  function find(text) {
    checkString(text);
    const matches = [];
    let state = 0, end = 0;
    for (const ch of text) {
      end++;
      while (state !== 0 && !nodes[state].next.has(ch)) {
        state = nodes[state].fail;
      }
      state = nodes[state].next.get(ch) ?? 0;
      for (let terminal = state; terminal !== 0; terminal = nodes[terminal].dict) {
        for (const id of nodes[terminal].out) {
          matches.push(Object.freeze({
            id, pattern: patterns[id], start: end - lengths[id], end
          }));
        }
      }
    }
    return Object.freeze(matches);
  }
  return Object.freeze({ patternCount: patterns.length, find });
}
const input = ['aba', 'ba'];
const matcher = buildMatcher(input);
const before = matcher.find('ababa');
input[0] = 'x'; input.push('a');
assert.equal(matcher.patternCount, 2);
assert.deepEqual(matcher.find('ababa'), before);
assert(Object.isFrozen(matcher));
assert(Object.isFrozen(before));
assert(before.every(Object.isFrozen));
assert.throws(() => { matcher.find = () => []; }, TypeError);
assert.throws(() => { before[0].start = 99; }, TypeError);
assert.throws(() => before.push({}), TypeError);
assert.notStrictEqual(matcher.find('ababa'), before);
const second = buildMatcher(['x']);
assert.equal(second.find('ababa').length, 0);
assert.deepEqual(matcher.find('ababa'), before);
console.log('snapshot, API, result records and repeated queries: PASS');

实际输出:

snapshot, API, result records and repeated queries: PASS

七、用完全不同的算法穷举结果,而不是复制错误

如果参考实现也沿 fail 链输出,它与被测代码可能共享同一种缺陷。这里的 oracle 完全不建图:对每个模式枚举全部合法起点,逐码点比较,然后按照公开协议排序。它很慢,但足够简单,适合小规模验证。断言比较完整记录数组,因而同时检查是否漏报、重复报错、位置算错以及输出顺序不稳定。

穷举的域要写清楚,不能把一次随机运行称为完整证明。模式池由 a、b 组成、长度为一或二的六个字符串构成;枚举长度从零到三的全部有序词典,允许重复,共二百五十九个。文本枚举长度零到五的全部二进制字符串,共六十三个。两者相乘得到一万六千三百一十七次完整结果比较,覆盖空词典、短前缀、失败回退和重复身份。

这个有限域不能证明任意长度都正确,但它特别擅长抓出常见结构错误:把根当普通终止节点、失败目标误连到自身、遗漏继承输出、同一节点只存一个编号等。测试通过后仍要阅读链接深度递减这一不变量,不能把穷举数量当作省略推理的理由。

示例 7,独立运行:

'use strict';
const assert = require('node:assert/strict');
function checkString(value) {
  if (typeof value !== 'string' || !value.isWellFormed()) {
    throw new TypeError('expected a well-formed string');
  }
  return value;
}
function buildMatcher(input) {
  if (!Array.isArray(input)) throw new TypeError('expected an array');
  const patterns = [], lengths = [];
  for (let id = 0; id < input.length; id++) {
    const pattern = checkString(input[id]);
    if (pattern === '') throw new RangeError('empty pattern');
    patterns.push(pattern);
    lengths.push(Array.from(pattern).length);
  }
  const node = () => ({ next: new Map(), fail: 0, out: [], dict: 0 });
  const nodes = [node()];
  for (let id = 0; id < patterns.length; id++) {
    let state = 0;
    for (const ch of patterns[id]) {
      if (!nodes[state].next.has(ch)) {
        nodes[state].next.set(ch, nodes.length);
        nodes.push(node());
      }
      state = nodes[state].next.get(ch);
    }
    nodes[state].out.push(id);
  }
  const queue = [...nodes[0].next.values()];
  for (let head = 0; head < queue.length; head++) {
    const state = queue[head];
    for (const [ch, child] of nodes[state].next) {
      let fallback = nodes[state].fail;
      while (fallback !== 0 && !nodes[fallback].next.has(ch)) {
        fallback = nodes[fallback].fail;
      }
      const target = nodes[fallback].next.get(ch) ?? 0;
      nodes[child].fail = target;
      nodes[child].dict = nodes[target].out.length ? target : nodes[target].dict;
      queue.push(child);
    }
  }
  Object.freeze(patterns);
  Object.freeze(lengths);
  for (const item of nodes) {
    Object.freeze(item.out);
    Object.freeze(item);
  }
  Object.freeze(nodes);
  function find(text) {
    checkString(text);
    const matches = [];
    let state = 0, end = 0;
    for (const ch of text) {
      end++;
      while (state !== 0 && !nodes[state].next.has(ch)) {
        state = nodes[state].fail;
      }
      state = nodes[state].next.get(ch) ?? 0;
      for (let terminal = state; terminal !== 0; terminal = nodes[terminal].dict) {
        for (const id of nodes[terminal].out) {
          matches.push(Object.freeze({
            id, pattern: patterns[id], start: end - lengths[id], end
          }));
        }
      }
    }
    return Object.freeze(matches);
  }
  return Object.freeze({ patternCount: patterns.length, find });
}
function brute(patterns, text) {
  const chars = Array.from(text), result = [];
  for (let id = 0; id < patterns.length; id++) {
    const word = Array.from(patterns[id]);
    for (let start = 0; start + word.length <= chars.length; start++) {
      let same = true;
      for (let j = 0; j < word.length; j++) {
        if (chars[start + j] !== word[j]) { same = false; break; }
      }
      if (same) result.push({ id, pattern: patterns[id], start, end: start + word.length });
    }
  }
  return result.sort((a, b) => a.end - b.end || a.start - b.start || a.id - b.id);
}
function words(alphabet, max) {
  const all = [''];
  let layer = [''];
  for (let length = 1; length <= max; length++) {
    layer = layer.flatMap(prefix => alphabet.map(ch => prefix + ch));
    all.push(...layer);
  }
  return all;
}

const pool = words(['a', 'b'], 2).filter(Boolean);
const texts = words(['a', 'b'], 5);
let checks = 0;
function visit(patterns, remaining) {
  const matcher = buildMatcher(patterns);
  for (const text of texts) {
    assert.deepEqual(matcher.find(text), brute(patterns, text));
    checks++;
  }
  if (remaining > 0) for (const p of pool) visit([...patterns, p], remaining - 1);
}
visit([], 3);
assert.equal(checks, 16317);
console.log(`exhaustive ordered dictionaries and texts: ${checks} PASS`);

实际输出:

exhaustive ordered dictionaries and texts: 16317 PASS

八、再扩大字符域,并检查失败后的复用

小字母表穷举负责系统覆盖,固定种子的差分测试负责扩大字符和长度组合。下面的字符池同时包含汉字、补充平面表情、组合重音、零宽连接符和空字符。每次随机选择词典大小、模式长度与文本长度,并主动制造重复模式;固定种子让失败能够重新运行,而不是留下难以重现的日志。

随机测试之外还要逐项验证非法输入。完整文本必须在扫描前检查,即使开头已经没有可匹配转移,也不能忽略末尾的孤立代理项。构建器也不能部分接受一份词典:某一元素非法就整个构建失败。查询失败后,既有实例没有残留的游标,所以下一次合法查询仍从根开始。错误类型同样是接口的一部分,不能只要求某处抛出了任意异常。

示例 8,独立运行:

'use strict';
const assert = require('node:assert/strict');
function checkString(value) {
  if (typeof value !== 'string' || !value.isWellFormed()) {
    throw new TypeError('expected a well-formed string');
  }
  return value;
}
function buildMatcher(input) {
  if (!Array.isArray(input)) throw new TypeError('expected an array');
  const patterns = [], lengths = [];
  for (let id = 0; id < input.length; id++) {
    const pattern = checkString(input[id]);
    if (pattern === '') throw new RangeError('empty pattern');
    patterns.push(pattern);
    lengths.push(Array.from(pattern).length);
  }
  const node = () => ({ next: new Map(), fail: 0, out: [], dict: 0 });
  const nodes = [node()];
  for (let id = 0; id < patterns.length; id++) {
    let state = 0;
    for (const ch of patterns[id]) {
      if (!nodes[state].next.has(ch)) {
        nodes[state].next.set(ch, nodes.length);
        nodes.push(node());
      }
      state = nodes[state].next.get(ch);
    }
    nodes[state].out.push(id);
  }
  const queue = [...nodes[0].next.values()];
  for (let head = 0; head < queue.length; head++) {
    const state = queue[head];
    for (const [ch, child] of nodes[state].next) {
      let fallback = nodes[state].fail;
      while (fallback !== 0 && !nodes[fallback].next.has(ch)) {
        fallback = nodes[fallback].fail;
      }
      const target = nodes[fallback].next.get(ch) ?? 0;
      nodes[child].fail = target;
      nodes[child].dict = nodes[target].out.length ? target : nodes[target].dict;
      queue.push(child);
    }
  }
  Object.freeze(patterns);
  Object.freeze(lengths);
  for (const item of nodes) {
    Object.freeze(item.out);
    Object.freeze(item);
  }
  Object.freeze(nodes);
  function find(text) {
    checkString(text);
    const matches = [];
    let state = 0, end = 0;
    for (const ch of text) {
      end++;
      while (state !== 0 && !nodes[state].next.has(ch)) {
        state = nodes[state].fail;
      }
      state = nodes[state].next.get(ch) ?? 0;
      for (let terminal = state; terminal !== 0; terminal = nodes[terminal].dict) {
        for (const id of nodes[terminal].out) {
          matches.push(Object.freeze({
            id, pattern: patterns[id], start: end - lengths[id], end
          }));
        }
      }
    }
    return Object.freeze(matches);
  }
  return Object.freeze({ patternCount: patterns.length, find });
}
function brute(patterns, text) {
  const chars = Array.from(text), result = [];
  for (let id = 0; id < patterns.length; id++) {
    const word = Array.from(patterns[id]);
    for (let start = 0; start + word.length <= chars.length; start++) {
      let same = true;
      for (let j = 0; j < word.length; j++) {
        if (chars[start + j] !== word[j]) { same = false; break; }
      }
      if (same) result.push({ id, pattern: patterns[id], start, end: start + word.length });
    }
  }
  return result.sort((a, b) => a.end - b.end || a.start - b.start || a.id - b.id);
}
function words(alphabet, max) {
  const all = [''];
  let layer = [''];
  for (let length = 1; length <= max; length++) {
    layer = layer.flatMap(prefix => alphabet.map(ch => prefix + ch));
    all.push(...layer);
  }
  return all;
}

let seed = 0x54e2187b;
function random(n) {
  seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5;
  return (seed >>> 0) % n;
}
const alphabet = ['a', '中', '😀', '\u0301', '\u0000', 'é', '👩', '‍', '💻'];
function textOf(n) {
  let s = '';
  for (let i = 0; i < n; i++) s += alphabet[random(alphabet.length)];
  return s;
}
for (let trial = 0; trial < 1500; trial++) {
  const patterns = Array.from({ length: random(7) }, () => textOf(1 + random(5)));
  if (patterns.length > 1) patterns[1] = patterns[0];
  const text = textOf(random(25));
  assert.deepEqual(buildMatcher(patterns).find(text), brute(patterns, text));
}
const matcher = buildMatcher(['a']);
const invalid = [null, 1, {}, new String('a'), '\uD800', '\uDC00', 'x\uD800'];
for (const value of invalid) {
  assert.throws(() => matcher.find(value), TypeError);
  assert.throws(() => buildMatcher([value]), TypeError);
}
assert.throws(() => buildMatcher('a'), TypeError);
assert.throws(() => buildMatcher(new Array(1)), TypeError);
assert.throws(() => buildMatcher(['a', '']), RangeError);
assert.deepEqual(matcher.find('a'), [{ id: 0, pattern: 'a', start: 0, end: 1 }]);
console.log('seeded Unicode differential cases: 1500 PASS');
console.log('invalid input and post-error reuse: PASS');

实际输出:

seeded Unicode differential cases: 1500 PASS
invalid input and post-error reuse: PASS

九、报告复杂度时,把输出规模与预处理都算进去

令 M 为所有模式的码点总数,K 为模式个数,L 为最长模式长度,N 为文本码点数,Z 为实际命中记录数。图节点和显式边最多与 M 成正比,每个编号只存一次,因此结构空间是 O(M+K),返回记录额外需要 O(Z)。在按常数期望成本访问 Map 的工程假设下,扫描阶段为 O(N+Z):每读一个码点最多把状态深度增加一,失败回退总量可以摊还;输出链接每到一个终止节点至少产生一条结果。

这里不把预处理也无条件写成线性。当前实现为每条边单独沿失败链寻找目标,保守上界可写为 O(M×L),再加输入复制与校验;它没有补全整个 Unicode 字母表的转移表,也没有引入转移缓存。ECMAScript 对 Map 的要求不是承诺所有环境都拥有严格常数时间,因此上述成本模型需要与实际运行环境一起说明。本文没有测量吞吐量,也不会用一张输出截图证明某种速度优势。

最后的稠密输入提醒我们:文本扫描一遍不意味着结果很少。长度一到三十二的连续 a 模式,在二百个 a 上产生五千九百零四条记录,这是业务确实要求的输出,不能称为算法多算了。若实际服务只要存在性、计数或前若干条,应另设计相应接口和终止语义,而不是在当前 find 中悄悄截断。返回整个数组也不适合无限流,分块扫描还需要跨块保留状态并处理被拆开的代理项,本版本没有提供该能力。

Promise.all 示例只验证多次调用的局部状态互不污染,不表示同步 JavaScript 匹配已经获得多线程并行。严格的未处理拒绝模式与明确的顶层错误处理确保异步断言失败会让进程失败。对算法文章而言,这比一个始终显示成功的日志更重要。

示例 9,独立运行:

'use strict';
const assert = require('node:assert/strict');
function checkString(value) {
  if (typeof value !== 'string' || !value.isWellFormed()) {
    throw new TypeError('expected a well-formed string');
  }
  return value;
}
function buildMatcher(input) {
  if (!Array.isArray(input)) throw new TypeError('expected an array');
  const patterns = [], lengths = [];
  for (let id = 0; id < input.length; id++) {
    const pattern = checkString(input[id]);
    if (pattern === '') throw new RangeError('empty pattern');
    patterns.push(pattern);
    lengths.push(Array.from(pattern).length);
  }
  const node = () => ({ next: new Map(), fail: 0, out: [], dict: 0 });
  const nodes = [node()];
  for (let id = 0; id < patterns.length; id++) {
    let state = 0;
    for (const ch of patterns[id]) {
      if (!nodes[state].next.has(ch)) {
        nodes[state].next.set(ch, nodes.length);
        nodes.push(node());
      }
      state = nodes[state].next.get(ch);
    }
    nodes[state].out.push(id);
  }
  const queue = [...nodes[0].next.values()];
  for (let head = 0; head < queue.length; head++) {
    const state = queue[head];
    for (const [ch, child] of nodes[state].next) {
      let fallback = nodes[state].fail;
      while (fallback !== 0 && !nodes[fallback].next.has(ch)) {
        fallback = nodes[fallback].fail;
      }
      const target = nodes[fallback].next.get(ch) ?? 0;
      nodes[child].fail = target;
      nodes[child].dict = nodes[target].out.length ? target : nodes[target].dict;
      queue.push(child);
    }
  }
  Object.freeze(patterns);
  Object.freeze(lengths);
  for (const item of nodes) {
    Object.freeze(item.out);
    Object.freeze(item);
  }
  Object.freeze(nodes);
  function find(text) {
    checkString(text);
    const matches = [];
    let state = 0, end = 0;
    for (const ch of text) {
      end++;
      while (state !== 0 && !nodes[state].next.has(ch)) {
        state = nodes[state].fail;
      }
      state = nodes[state].next.get(ch) ?? 0;
      for (let terminal = state; terminal !== 0; terminal = nodes[terminal].dict) {
        for (const id of nodes[terminal].out) {
          matches.push(Object.freeze({
            id, pattern: patterns[id], start: end - lengths[id], end
          }));
        }
      }
    }
    return Object.freeze(matches);
  }
  return Object.freeze({ patternCount: patterns.length, find });
}
async function main() {
  const patterns = Array.from({ length: 32 }, (_, i) => 'a'.repeat(i + 1));
  const matcher = buildMatcher(patterns);
  const n = 200;
  const hits = matcher.find('a'.repeat(n));
  const expected = 32 * (n + 1) - 32 * 33 / 2;
  assert.equal(hits.length, expected);
  for (let i = 1; i < hits.length; i++) {
    const a = hits[i - 1], b = hits[i];
    assert(a.end < b.end || (a.end === b.end && a.start <= b.start));
  }
  const results = await Promise.all(['aa', 'aaaa', 'b'].map(async text => matcher.find(text)));
  assert.deepEqual(results.map(x => x.length), [3, 10, 0]);
  await assert.rejects(async () => matcher.find('\uD800'), TypeError);
  assert.equal(matcher.find('a').length, 1);
  console.log(`dense overlapping matches: ${hits.length} PASS`);
  console.log('independent calls through Promise.all: 3,10,0');
}
main().catch(error => { console.error(error); process.exitCode = 1; });

实际输出:

dense overlapping matches: 5904 PASS
independent calls through Promise.all: 3,10,0

审查结论:让实现、协议和测试互相约束

这次审查的关键成果不是把九个例子跑绿,而是把几个容易被省略的选择固定下来:非空模式、允许空词典、保留重复编号、保留全部重叠、码点半开区间、结束位置优先的稳定顺序,以及不归一化的精确匹配。它们共同决定了接口行为。只要改变其中一条,参考实现、断言和调用方展示逻辑也需要同步调整。

复查 AI 给出的多模式搜索代码时,可以依次问:状态代表什么后缀,失败目标是否严格更浅,终止输出是否完整,重复模式的身份是否丢失,外部能否改写图,位置属于哪一份文本,以及复杂度是否包含实际输出。每个回答都应落到代码和可运行证据中。本文选择的实现没有覆盖所有生产需求,但边界清楚、输出可核验,也给进一步优化留下了可靠的基线。

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