审查 AI 写的匹配器:用 JavaScript 构造极小 Thompson NFA

10-20 4阅读

设想一次代码审查:AI 根据需求写出了一个小型正则匹配器,演示中的几个字符串都返回正确结果,代码里也出现了状态、分支和循环。此时最危险的判断,是把术语齐全当作实现正确。真正需要审查的是:哪些模式属于语言、什么时候允许不消耗字符地前进、同一状态能否在同一轮被重复展开,以及输入结束之后才应该判断什么。

这是一个教学假设,不是某个模型或线上系统的事故记录。我们将独立实现一个极小的 Thompson 风格 ε-NFA,用九个可执行例子把审查问题变成断言。重点是语言语义、自动机构造和独立验证,不讨论 JavaScript 原生正则 API 的用法,也不复用通用表达式解释器。代码不调用原生 RegExp、不使用 eval,也不会把模式转换成 JavaScript 执行。

审查 AI 写的匹配器:用 JavaScript 构造极小 Thompson NFA
AI 生成的原创主题插画。分支与回环仅作视觉隐喻,不是本文某个模式的精确状态图。

历史背景可以追溯到 Ken Thompson 的《Regular Expression Search Algorithm》原论文:它逐字符更新可能的运行位置。Russ Cox 的作者实现说明展示了片段拼接与状态集合模拟。下面采用易于检查的显式入口、出口节点,代码、边界约定和测试均围绕本文的小语言重新组织。

一、先审查契约:小语言必须真的小

模式只支持大小写敏感的 ASCII 字母、隐式连接、竖线选择、星号重复和圆括号。星号表示前一个原子出现零次或多次;优先级依次为星号、连接、选择。括号只分组,不捕获。空模式、空括号和空分支全部拒绝,例如 a| 与 |a 都是语法错误。连续星号 a** 也拒绝,不过分组后的重复 (a*)* 合法,这会成为后面的环路测试。

匹配接口只做整串匹配。模式 a 不能接受 xa,也不能接受 a 后面的换行。任意字符串都可以作为待匹配文本传入;在资源预算足够时,含非字母字符的文本不会被这个语言接受。类型错误与资源耗尽会抛异常,不能被包装成普通的不匹配。字母范围以直接比较判断,避免连词法检查都暗中借用另一个正则引擎。

第一段只验证字符集合和长度,故意让 a||b 通过。这个断言说明职责边界:字符合法不等于语法合法。审查 AI 代码时,如果一个名为 validate 的函数只做白名单过滤,却被注释描述为完整验证,应当立即补上解析层,而不是再增加几个成功样例。

九段代码都可以各自保存为 example-01.cjs 至 example-09.cjs,在 Node.js 中独立运行,例如 node --unhandled-rejections=strict example-01.cjs。本次验证环境为 Node.js v24.19.0。使用 node:assert/strict;其严格比较和异常断言语义参见Node.js 官方断言文档。各段的输出都来自实际执行,不是性能测量。

'use strict';
const assert = require('node:assert/strict');
function checkPattern(p) {
  if (typeof p !== 'string') throw new TypeError('pattern');
  if (p.length > 512) throw new RangeError('pattern limit');
  const letter = c => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
  for (let i = 0; i < p.length; i++) {
    if (!letter(p[i]) && !'|*()'.includes(p[i])) {
      throw new SyntaxError(`unsupported at ${i}`);
    }
  }
  return p;
}
assert.equal(checkPattern('(a|B)*c'), '(a|B)*c');
for (const p of ['a+', '.', 'a b', '[ab]', '\\w', '中']) {
  assert.throws(() => checkPattern(p), SyntaxError);
}
assert.throws(() => checkPattern(3), TypeError);
assert.throws(() => checkPattern('a'.repeat(513)), RangeError);
// Character validation alone does not establish grammatical validity.
assert.equal(checkPattern('a||b'), 'a||b');
console.log('01 lexical contract OK');

运行输出:

01 lexical contract OK

二、用分层语法锁定优先级

解析层分成 alt、seq、repeat、atom 四层。alt 处理选择,seq 吃掉一个或多个相邻重复项,repeat 最多接受一个星号,atom 只接受字母或括号内的表达式。因此 ab*|C 的树根是选择,左侧是连接,星号只包住 b。这里用递归下降把固定的四层语法直接写出来,不需要运算符表或可扩展的表达式框架。

seq 先无条件读取一个 repeat,保证每个连接序列至少含一个项;这也让空分支自然报错。解析整个模式后还要检查游标是否到末尾,否则 a) 可能被错误地当成 a。深度限制数的是括号嵌套,而不是模式中括号的总数。长连接通过循环处理,不会为每个字母额外递归一层。

这个例子输出 AST,目的是让优先级断言可见。正式匹配器会在解析时直接产生自动机片段,因此不会保留这棵树。错误位置只服务于定位,第二段的简化游标推进不保证所有错误都指向违规字符本身;正式版本在消费括号前后做了更明确的检查。不要把教学解析器的错误文字当成稳定的公共协议。

'use strict';
const assert = require('node:assert/strict');
function parse(p) {
  if (typeof p !== 'string') throw new TypeError('pattern');
  if (p.length > 512) throw new RangeError('pattern limit');
  let i = 0, depth = 0;
  const bad = () => { throw new SyntaxError(`at ${i}`); };
  const letter = c => c !== undefined &&
    ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
  function atom() {
    if (letter(p[i])) return { kind: 'lit', value: p[i++] };
    if (p[i++] !== '(') bad();
    if (++depth > 32) throw new RangeError('depth limit');
    const a = alt();
    if (p[i++] !== ')') bad();
    depth--; return a;
  }
  function repeat() {
    let a = atom();
    if (p[i] === '*') { i++; a = { kind: 'star', a }; }
    return a;
  }
  function seq() {
    let a = repeat();
    while (i < p.length && p[i] !== '|' && p[i] !== ')') {
      a = { kind: 'seq', a, b: repeat() };
    }
    return a;
  }
  function alt() {
    let a = seq();
    while (p[i] === '|') { i++; a = { kind: 'alt', a, b: seq() }; }
    return a;
  }
  const tree = alt();
  if (i !== p.length) bad();
  return tree;
}
const lit = value => ({ kind: 'lit', value });
assert.deepEqual(parse('ab*|C'), {
  kind: 'alt', a: { kind: 'seq', a: lit('a'),
    b: { kind: 'star', a: lit('b') } }, b: lit('C')
});
for (const p of ['', '()', '|a', 'a|', 'a||b', '*a', 'a**', '(a', 'a)', '.']) {
  assert.throws(() => parse(p), SyntaxError, p);
}
assert.equal(parse('(a*)*').kind, 'star');
console.log('02 precedence and syntax OK');

运行输出:

02 precedence and syntax OK

三、审查片段不变量,而不只是画出分支

一个片段有入口 start 和出口 end。构造期间,出口暂时没有后续边,父表达式可以把它接到新的位置。字母片段有一条消耗该字母的边;连接把左出口用 ε 边接到右入口;选择增加公共入口和出口;星号除了回到子片段入口的边,还必须提供直接到出口的空路径。ε 边表示不消耗输入,不是匹配某个特殊字符。

下面的 build 只接受我们自己提供的可信小 AST,不是对外的编译接口,也不验证恶意对象或循环引用。它单独展示拓扑:ab* 使用六个状态,其中两个带字母转换。连接不增加状态;字母、选择、星号各增加两个。正式解析器不会复用同一片段对象去表示两个不同的语法位置,因而每次给出口接边时都满足尚未被父结构接走的不变量。

这比检查某个具体状态编号更有价值。编号顺序取决于构造顺序,没有语言意义;真正应当检查的是出口、边类型和可达关系。当前表示中每个状态最多两条 ε 边,字符状态只有一条字符边。后面估算状态访问次数时,必须依赖这个出度约束,而不能对任意图照搬同一个结论。

'use strict';
const assert = require('node:assert/strict');
function build(tree) {
  const states = [];
  const node = (ch = null, to = null) => states.push({ ch, to, eps: [] }) - 1;
  function go(t) {
    if (t.kind === 'lit') {
      const end = node(), start = node(t.value, end);
      return { start, end };
    }
    const a = go(t.a);
    if (t.kind === 'seq') {
      const b = go(t.b); states[a.end].eps.push(b.start);
      return { start: a.start, end: b.end };
    }
    const start = node(), end = node();
    if (t.kind === 'star') {
      states[start].eps.push(a.start, end);
      states[a.end].eps.push(a.start, end);
    } else if (t.kind === 'alt') {
      const b = go(t.b);
      states[start].eps.push(a.start, b.start);
      states[a.end].eps.push(end); states[b.end].eps.push(end);
    } else throw new TypeError('trusted AST expected');
    return { start, end };
  }
  return { ...go(tree), states };
}
const lit = value => ({ kind: 'lit', value });
const n = build({ kind: 'seq', a: lit('a'),
  b: { kind: 'star', a: lit('b') } });
assert.equal(n.states.length, 6);
assert.equal(n.states[n.start].ch, 'a');
assert.deepEqual(n.states[n.end].eps, []);
assert.ok(n.states.every(s => s.eps.length <= 2));
assert.equal(n.states.filter(s => s.ch !== null).length, 2);
console.log('03 fragment topology OK');

运行输出:

03 fragment topology OK

四、ε 闭包:先登记,再继续展开

ε 闭包是从一组种子状态出发,只走 ε 边能够到达的全部状态,种子自己也属于闭包。错误实现常把它写成遇到 ε 边就递归展开,却没有访问集合。对于能接受空串的子表达式再次加星号,图中就可能出现不消耗字符的环;递归会在读到第一个输入字符前失控。

关键顺序是:检查 seen,把新状态登记进去,再压入待处理栈。这样一个状态在本次闭包中最多展开一次。seen 的生命期只能覆盖一次闭包,不能作为整个匹配期间永久累积的访问记录,否则下一字符重新到达的状态会被错误跳过。栈只是工作清单,集合才负责判重。

下面直接构造含环的小图,并同时检查重复种子、空种子和孤立节点。测试闭包不必先相信解析器与编译器,这种拆分能避免多个错误相互遮盖。本例按有效的内部状态编号工作,不宣称能够修复损坏的图。正式接口不向外暴露状态数组,减少外部修改带来的契约负担。

'use strict';
const assert = require('node:assert/strict');
function closure(states, seeds) {
  const seen = new Set(), stack = [];
  const add = id => {
    if (!seen.has(id)) { seen.add(id); stack.push(id); }
  };
  for (const id of seeds) add(id);
  while (stack.length) {
    for (const id of states[stack.pop()].eps) add(id);
  }
  return seen;
}
// Epsilon cycle: 0 -> 1 -> 2 -> 0; state 2 also reaches 3.
const states = [{ eps: [1] }, { eps: [2] },
  { eps: [0, 3] }, { eps: [] }, { eps: [] }];
assert.deepEqual([...closure(states, [0, 0])].sort(), [0, 1, 2, 3]);
assert.deepEqual([...closure(states, [])], []);
assert.deepEqual([...closure(states, [4])], [4]);
assert.equal(closure(states, [0]).size, 4);
console.log('04 epsilon cycle terminates OK');

运行输出:

04 epsilon cycle terminates OK

五、整串匹配:接受状态不能提前交卷

模拟开始时先计算入口闭包;每读一个字符,收集当前集合中匹配该字符的所有边的终点,然后再做闭包。只有全部输入都处理完,才能判断最终出口是否在集合中。中途到达出口并不等于成功,因为文本可能还有未消费的后缀。反过来,初始闭包已经含出口,则表示空输入有机会被接受。

下面手写一个识别 ab* 的图,故意绕开编译器,让运行器测试有独立输入。xa 检查是否意外实现了子串搜索,abx 检查是否提前接受,空串检查起始状态,换行检查整串边界。这里没有捕获组,因此只需保留可达状态,不需要保留哪条路径先到达、重复了几次或每组的起止位置。

审查时还要警惕悄悄向每一轮集合重新加入入口的做法。那会允许在任意位置重新开始,改变整串匹配语义。本文只在开始时加入一次入口;状态集合不是线程,也没有真正并行运行,它只是用一个集合表示当前仍可能成功的位置。

'use strict';
const assert = require('node:assert/strict');
// This hand-built NFA recognizes exactly a followed by zero or more b.
const states = [
  { eps: [], ch: 'a', to: 1 },
  { eps: [2, 3] },
  { eps: [], ch: 'b', to: 1 },
  { eps: [] }
];
function close(seeds) {
  const seen = new Set(seeds), stack = [...seen];
  while (stack.length) {
    for (const id of states[stack.pop()].eps) {
      if (!seen.has(id)) { seen.add(id); stack.push(id); }
    }
  }
  return seen;
}
function fullmatch(text) {
  if (typeof text !== 'string') throw new TypeError('text');
  let active = close([0]);
  for (const ch of text) {
    const seeds = new Set();
    for (const id of active) {
      if (states[id].ch === ch) seeds.add(states[id].to);
    }
    active = close(seeds);
  }
  return active.has(3);
}
for (const text of ['a', 'ab', 'abbb']) assert.equal(fullmatch(text), true);
for (const text of ['', 'b', 'xa', 'abx', 'a\n']) assert.equal(fullmatch(text), false);
console.log('05 whole-string simulation OK');

运行输出:

05 whole-string simulation OK

六、合并成可复用的最小匹配器

现在把解析、片段构造和运行器接起来。compile 的闭包保存私有状态数组,只返回 fullmatch 与 stateCount。每次 fullmatch 都创建新的工作计数和活动集合;一个文本的失败或预算异常不会污染下一次调用。Object.freeze 只冻结返回对象,不是深度冻结整张图;图的保护来自没有把可变引用交给调用方。

下面是完整实现。后面三段为了能单独复制执行,会再次包含同一份 compile 定义;真实项目应把它抽成一个模块,测试引用同一实现,避免维护四份副本。前五段分解示例也不应直接当成已经加固的公共 API 使用。完整版本提前检查模式字符、限制长度与深度,并且在节点创建和匹配时执行资源检查。

用归纳方式读这份代码会更可靠:字母片段接受一个字母;连接接受两个片段语言的拼接;选择接受任一分支;星号接受有限次重复,其中包括零次。运行器则维持另一个不变量:处理了输入前缀后,active 恰好是读完该前缀后能经 ε 边继续到达的状态集合。构造不变量和运行不变量相接,才构成整串匹配正确性的论证骨架。

'use strict';
const assert = require('node:assert/strict');
function compile(pattern) {
  const LIMIT = { pattern: 512, depth: 32, states: 1024,
                  text: 4096, work: 250000 };
  if (typeof pattern !== 'string') throw new TypeError('pattern');
  if (pattern.length > LIMIT.pattern) throw new RangeError('pattern limit');
  let pos = 0, depth = 0;
  const states = [];
  const letter = c => c !== undefined &&
    ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
  const fail = () => { throw new SyntaxError(`pattern at ${pos}`); };
  for (let i = 0; i < pattern.length; i++) {
    if (!letter(pattern[i]) && !'|*()'.includes(pattern[i])) {
      pos = i; fail();
    }
  }
  pos = 0;
  function node(ch = null, to = null) {
    if (states.length >= LIMIT.states) throw new RangeError('state limit');
    return states.push({ ch, to, eps: [] }) - 1;
  }
  function literal(ch) {
    const end = node(), start = node(ch, end);
    return { start, end };
  }
  function join(a, b) {
    states[a.end].eps.push(b.start);
    return { start: a.start, end: b.end };
  }
  function either(a, b) {
    const start = node(), end = node();
    states[start].eps.push(a.start, b.start);
    states[a.end].eps.push(end); states[b.end].eps.push(end);
    return { start, end };
  }
  function star(a) {
    const start = node(), end = node();
    states[start].eps.push(a.start, end);
    states[a.end].eps.push(a.start, end);
    return { start, end };
  }
  function atom() {
    const ch = pattern[pos];
    if (letter(ch)) { pos++; return literal(ch); }
    if (ch !== '(') fail();
    pos++;
    if (++depth > LIMIT.depth) throw new RangeError('depth limit');
    const a = alt();
    if (pattern[pos] !== ')') fail();
    pos++; depth--; return a;
  }
  function repeat() {
    let a = atom();
    if (pattern[pos] === '*') { pos++; a = star(a); }
    return a;
  }
  function seq() {
    let a = repeat();
    while (pos < pattern.length && pattern[pos] !== '|' && pattern[pos] !== ')') {
      a = join(a, repeat());
    }
    return a;
  }
  function alt() {
    let a = seq();
    while (pattern[pos] === '|') { pos++; a = either(a, seq()); }
    return a;
  }
  const nfa = alt();
  if (pos !== pattern.length) fail();
  function fullmatch(text) {
    if (typeof text !== 'string') throw new TypeError('text');
    if (text.length > LIMIT.text) throw new RangeError('text limit');
    let work = 0;
    const tick = () => {
      if (++work > LIMIT.work) throw new RangeError('work limit');
    };
    function close(seeds) {
      const seen = new Set(), stack = [];
      const add = id => {
        if (!seen.has(id)) { tick(); seen.add(id); stack.push(id); }
      };
      for (const id of seeds) add(id);
      while (stack.length) {
        const id = stack.pop();
        for (const next of states[id].eps) add(next);
      }
      return seen;
    }
    let active = close([nfa.start]);
    for (let i = 0; i < text.length; i++) {
      const seeds = new Set();
      for (const id of active) {
        tick();
        if (states[id].ch === text[i]) seeds.add(states[id].to);
      }
      active = close(seeds);
      if (active.size === 0) return false;
    }
    return active.has(nfa.end);
  }
  return Object.freeze({ fullmatch, stateCount: states.length });
}
const r = compile('ab*|C');
for (const s of ['a', 'abbb', 'C']) assert.equal(r.fullmatch(s), true);
for (const s of ['', 'abC', 'xa', 'C\n']) assert.equal(r.fullmatch(s), false);
assert.equal(compile('(a|b)*abb').fullmatch('aabb'), true);
assert.equal(compile('(a|b)*abb').fullmatch('abab'), false);
assert.equal(compile('(a*)*').fullmatch(''), true);
assert.equal(compile('(a*)*').fullmatch('aaa'), true);
assert.equal(compile('a').fullmatch('A'), false);
assert.equal(compile('a*').fullmatch('中'), false);
assert.ok(Object.isFrozen(r));
console.log('06 complete matcher OK');

运行输出:

06 complete matcher OK

七、有界执行:报错与不匹配必须分开

完整版本把模式限制为五百一十二个代码单元,括号深度限制为三十二层,状态最多一千零二十四个,文本最多四千零九十六个代码单元。模式全部为 ASCII,所以模式长度也等于其字节长度;文本上限仍按 JavaScript 字符串的 UTF-16 代码单元计数。状态上限是防御性检查:本构造中每个字母、选择号和星号贡献两个状态,括号与连接不贡献状态,所以有效模式的状态数不超过模式长度的两倍。

单次匹配另有二十五万次工作计数预算。每个新加入闭包的状态、每个被扫描的活动状态各记一次;预算用完抛出 RangeError。它限制的是这些被明确计数的图操作,不是机器指令总数,更不是硬实时超时保证。字符串读取、集合操作、内存分配和垃圾回收仍有成本,部署到服务端还需根据环境增加并发隔离和总体配额。

设状态数为 S,文本长度为 n,未触发预算时,闭包初始最多登记 S 个状态,每个字符至多扫描 S 个并再次登记 S 个。因而这类状态访问次数为 O((n+1)S),工作集合额外空间为 O(S)。把它换算成通常的 O((n+1)m) 运行时间需要集合访问近似常数成本等模型假设;ECMAScript 官方 Set 规范只要求平均访问时间相对集合大小为次线性,并未承诺每次操作严格常数时间。本文不据此宣称比任何当前引擎更快。

预算耗尽应由调用方单独处理。若 catch 所有异常并返回 false,就会把尚未算完的合法匹配伪装成确定的不匹配。测试中的宽模式在长文本上触发预算,之后同一个编译结果仍能匹配短文本;这同时验证了限制确实生效,以及异常之后没有残留运行状态。

'use strict';
const assert = require('node:assert/strict');
function compile(pattern) {
  const LIMIT = { pattern: 512, depth: 32, states: 1024,
                  text: 4096, work: 250000 };
  if (typeof pattern !== 'string') throw new TypeError('pattern');
  if (pattern.length > LIMIT.pattern) throw new RangeError('pattern limit');
  let pos = 0, depth = 0;
  const states = [];
  const letter = c => c !== undefined &&
    ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
  const fail = () => { throw new SyntaxError(`pattern at ${pos}`); };
  for (let i = 0; i < pattern.length; i++) {
    if (!letter(pattern[i]) && !'|*()'.includes(pattern[i])) {
      pos = i; fail();
    }
  }
  pos = 0;
  function node(ch = null, to = null) {
    if (states.length >= LIMIT.states) throw new RangeError('state limit');
    return states.push({ ch, to, eps: [] }) - 1;
  }
  function literal(ch) {
    const end = node(), start = node(ch, end);
    return { start, end };
  }
  function join(a, b) {
    states[a.end].eps.push(b.start);
    return { start: a.start, end: b.end };
  }
  function either(a, b) {
    const start = node(), end = node();
    states[start].eps.push(a.start, b.start);
    states[a.end].eps.push(end); states[b.end].eps.push(end);
    return { start, end };
  }
  function star(a) {
    const start = node(), end = node();
    states[start].eps.push(a.start, end);
    states[a.end].eps.push(a.start, end);
    return { start, end };
  }
  function atom() {
    const ch = pattern[pos];
    if (letter(ch)) { pos++; return literal(ch); }
    if (ch !== '(') fail();
    pos++;
    if (++depth > LIMIT.depth) throw new RangeError('depth limit');
    const a = alt();
    if (pattern[pos] !== ')') fail();
    pos++; depth--; return a;
  }
  function repeat() {
    let a = atom();
    if (pattern[pos] === '*') { pos++; a = star(a); }
    return a;
  }
  function seq() {
    let a = repeat();
    while (pos < pattern.length && pattern[pos] !== '|' && pattern[pos] !== ')') {
      a = join(a, repeat());
    }
    return a;
  }
  function alt() {
    let a = seq();
    while (pattern[pos] === '|') { pos++; a = either(a, seq()); }
    return a;
  }
  const nfa = alt();
  if (pos !== pattern.length) fail();
  function fullmatch(text) {
    if (typeof text !== 'string') throw new TypeError('text');
    if (text.length > LIMIT.text) throw new RangeError('text limit');
    let work = 0;
    const tick = () => {
      if (++work > LIMIT.work) throw new RangeError('work limit');
    };
    function close(seeds) {
      const seen = new Set(), stack = [];
      const add = id => {
        if (!seen.has(id)) { tick(); seen.add(id); stack.push(id); }
      };
      for (const id of seeds) add(id);
      while (stack.length) {
        const id = stack.pop();
        for (const next of states[id].eps) add(next);
      }
      return seen;
    }
    let active = close([nfa.start]);
    for (let i = 0; i < text.length; i++) {
      const seeds = new Set();
      for (const id of active) {
        tick();
        if (states[id].ch === text[i]) seeds.add(states[id].to);
      }
      active = close(seeds);
      if (active.size === 0) return false;
    }
    return active.has(nfa.end);
  }
  return Object.freeze({ fullmatch, stateCount: states.length });
}
for (const p of ['', '()', '|a', 'a|', 'a||b', '*a', 'a**',
                 '(a', 'a)', 'a+', '.', '[a]', '\\w', 'a b', '中']) {
  assert.throws(() => compile(p), SyntaxError, p);
}
assert.throws(() => compile(null), TypeError);
assert.throws(() => compile('a'.repeat(513)), RangeError);
assert.throws(() => compile('('.repeat(33) + 'a' + ')'.repeat(33)),
  { name: 'RangeError', message: 'depth limit' });
assert.equal(compile('('.repeat(32) + 'a' + ')'.repeat(32)).fullmatch('a'), true);
const r = compile('a*');
assert.throws(() => r.fullmatch(3), TypeError);
assert.throws(() => r.fullmatch('a'.repeat(4097)),
  { name: 'RangeError', message: 'text limit' });
assert.equal(r.fullmatch('a'.repeat(4096)), true);
const wide = compile('a*'.repeat(200));
assert.throws(() => wide.fullmatch('a'.repeat(4096)),
  { name: 'RangeError', message: 'work limit' });
assert.equal(wide.fullmatch('a'), true); // Budget resets after an exception.
const edge = compile(Array(256).fill('a').join('|'));
assert.equal(edge.stateCount, 1022);
assert.ok(edge.stateCount <= 2 * 511);
console.log('07 rejection and resource boundaries OK');

运行输出:

07 rejection and resource boundaries OK

八、独立预言机:直接计算有限语言集合

只拿更多人工样例喂给同一个实现,仍可能漏掉共同假设。这里让预言机从语法树直接生成长度不超过四的字符串集合:选择取并集,连接做笛卡尔积并拼接,星号从空串开始反复扩张,直到集合不再变大。它不调用解析器,不建状态图,也不执行匹配器,因此走的是不同的验证路线。

为什么可以在中间步骤丢弃超长字符串?因为我们的运算只有拼接、选择与重复,后续操作不会删除已经产生的字符。超过上限的结果不可能再次缩短成候选词。为什么星号循环会停止?候选字母只有 a、b,长度上限固定,可能的字符串总数有限;集合每轮只增加不减少。即使子表达式本身包含空串,固定点检查也能终止。

模式生成器枚举深度至多二的语法树,共三百零二棵;测试文本枚举 a、b 上长度零到四的全部三十一个词,总计九千三百六十二次比较。不同语法树可能表达相同语言,因此不能把三百零二说成三百零二种不同语义。渲染时全部加括号,减少模式生成器自身的优先级歧义;没有括号的优先级仍由第二、六段的定向断言负责。

这是一组有界穷举,不是对所有模式与所有输入的形式证明。它也没有覆盖全部五十二个 ASCII 字母。独立性来自语义计算路线不同,而不是预言机天然正确;仍应审查集合运算、截断条件和固定点本身。不要把原生 RegExp 包装后作为唯一裁判,因为那样既复用了外部语言语义,也绕过了这篇教程要验证的能力。

'use strict';
const assert = require('node:assert/strict');
function compile(pattern) {
  const LIMIT = { pattern: 512, depth: 32, states: 1024,
                  text: 4096, work: 250000 };
  if (typeof pattern !== 'string') throw new TypeError('pattern');
  if (pattern.length > LIMIT.pattern) throw new RangeError('pattern limit');
  let pos = 0, depth = 0;
  const states = [];
  const letter = c => c !== undefined &&
    ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
  const fail = () => { throw new SyntaxError(`pattern at ${pos}`); };
  for (let i = 0; i < pattern.length; i++) {
    if (!letter(pattern[i]) && !'|*()'.includes(pattern[i])) {
      pos = i; fail();
    }
  }
  pos = 0;
  function node(ch = null, to = null) {
    if (states.length >= LIMIT.states) throw new RangeError('state limit');
    return states.push({ ch, to, eps: [] }) - 1;
  }
  function literal(ch) {
    const end = node(), start = node(ch, end);
    return { start, end };
  }
  function join(a, b) {
    states[a.end].eps.push(b.start);
    return { start: a.start, end: b.end };
  }
  function either(a, b) {
    const start = node(), end = node();
    states[start].eps.push(a.start, b.start);
    states[a.end].eps.push(end); states[b.end].eps.push(end);
    return { start, end };
  }
  function star(a) {
    const start = node(), end = node();
    states[start].eps.push(a.start, end);
    states[a.end].eps.push(a.start, end);
    return { start, end };
  }
  function atom() {
    const ch = pattern[pos];
    if (letter(ch)) { pos++; return literal(ch); }
    if (ch !== '(') fail();
    pos++;
    if (++depth > LIMIT.depth) throw new RangeError('depth limit');
    const a = alt();
    if (pattern[pos] !== ')') fail();
    pos++; depth--; return a;
  }
  function repeat() {
    let a = atom();
    if (pattern[pos] === '*') { pos++; a = star(a); }
    return a;
  }
  function seq() {
    let a = repeat();
    while (pos < pattern.length && pattern[pos] !== '|' && pattern[pos] !== ')') {
      a = join(a, repeat());
    }
    return a;
  }
  function alt() {
    let a = seq();
    while (pattern[pos] === '|') { pos++; a = either(a, seq()); }
    return a;
  }
  const nfa = alt();
  if (pos !== pattern.length) fail();
  function fullmatch(text) {
    if (typeof text !== 'string') throw new TypeError('text');
    if (text.length > LIMIT.text) throw new RangeError('text limit');
    let work = 0;
    const tick = () => {
      if (++work > LIMIT.work) throw new RangeError('work limit');
    };
    function close(seeds) {
      const seen = new Set(), stack = [];
      const add = id => {
        if (!seen.has(id)) { tick(); seen.add(id); stack.push(id); }
      };
      for (const id of seeds) add(id);
      while (stack.length) {
        const id = stack.pop();
        for (const next of states[id].eps) add(next);
      }
      return seen;
    }
    let active = close([nfa.start]);
    for (let i = 0; i < text.length; i++) {
      const seeds = new Set();
      for (const id of active) {
        tick();
        if (states[id].ch === text[i]) seeds.add(states[id].to);
      }
      active = close(seeds);
      if (active.size === 0) return false;
    }
    return active.has(nfa.end);
  }
  return Object.freeze({ fullmatch, stateCount: states.length });
}
function words(max) {
  const all = ['']; let layer = [''];
  for (let i = 0; i < max; i++) {
    layer = layer.flatMap(s => ['a', 'b'].map(c => s + c));
    all.push(...layer);
  }
  return all;
}
const L = c => ({ k: 'lit', c });
function trees(depth) {
  const out = [L('a'), L('b')];
  if (depth === 0) return out;
  const sub = trees(depth - 1);
  for (const a of sub) out.push({ k: 'star', a });
  for (const a of sub) for (const b of sub) {
    out.push({ k: 'seq', a, b }, { k: 'alt', a, b });
  }
  return out;
}
function render(t) {
  if (t.k === 'lit') return t.c;
  if (t.k === 'star') return `(${render(t.a)})*`;
  const op = t.k === 'alt' ? '|' : '';
  return `(${render(t.a)}${op}${render(t.b)})`;
}
// Independent finite-language oracle: no parser, graph, or matcher calls.
function language(t, max) {
  const product = (a, b) => new Set([...a].flatMap(x =>
    [...b].map(y => x + y).filter(s => s.length <= max)));
  if (t.k === 'lit') return new Set(max >= 1 ? [t.c] : []);
  const a = language(t.a, max);
  if (t.k === 'star') {
    let out = new Set(['']);
    while (true) {
      const next = new Set([...out, ...product(out, a)]);
      if (next.size === out.size) return next;
      out = next;
    }
  }
  const b = language(t.b, max);
  return t.k === 'alt' ? new Set([...a, ...b]) : product(a, b);
}
const corpus = words(4), patterns = trees(2);
let comparisons = 0;
for (const tree of patterns) {
  const p = render(tree), r = compile(p), expected = language(tree, 4);
  for (const text of corpus) {
    assert.equal(r.fullmatch(text), expected.has(text), `${p} / ${text}`);
    comparisons++;
  }
}
assert.equal(patterns.length, 302);
assert.equal(corpus.length, 31);
assert.equal(comparisons, 9362);
console.log(`08 exhaustive finite oracle OK: ${comparisons}`);

运行输出:

08 exhaustive finite oracle OK: 9362

九、代数性质与复用测试补齐审查清单

最后增加一些变形关系:重复的选择分支不改变语言,星号再加星号不改变语言,连接对选择满足左右分配律,连接也满足结合律。每对模式对相同候选词给出相同结果,共三百三十五次等价检查。额外加入含 c 与大写字母的文本,避免全部测试只在二字母世界里循环。

这些性质很适合发现构造时把左右片段接反、复用活动集合或出口连接错误等问题,但不能取代独立预言机。两个模式若都被同一个缺陷算错,等价断言仍可能通过。两条证据应当互相补充:一条比较独立语义集合,另一条寻找实现内部是否违反已知关系。反复交错调用 a* 与 b* 则专门检查编译结果之间、同一结果多次调用之间有没有状态泄漏。

如果继续扩充语法,不要只让 AI 在字符白名单里加入一个符号。新增可选项需要明确空串语义,新增通配符需要重新确定字符域,新增捕获需要确定路径与组边界,新增反向引用则已经超出本文这种有限状态模型的功能契约。每一项都应当先更新语义与预言机,再考虑改变图的构造规则。

'use strict';
const assert = require('node:assert/strict');
function compile(pattern) {
  const LIMIT = { pattern: 512, depth: 32, states: 1024,
                  text: 4096, work: 250000 };
  if (typeof pattern !== 'string') throw new TypeError('pattern');
  if (pattern.length > LIMIT.pattern) throw new RangeError('pattern limit');
  let pos = 0, depth = 0;
  const states = [];
  const letter = c => c !== undefined &&
    ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
  const fail = () => { throw new SyntaxError(`pattern at ${pos}`); };
  for (let i = 0; i < pattern.length; i++) {
    if (!letter(pattern[i]) && !'|*()'.includes(pattern[i])) {
      pos = i; fail();
    }
  }
  pos = 0;
  function node(ch = null, to = null) {
    if (states.length >= LIMIT.states) throw new RangeError('state limit');
    return states.push({ ch, to, eps: [] }) - 1;
  }
  function literal(ch) {
    const end = node(), start = node(ch, end);
    return { start, end };
  }
  function join(a, b) {
    states[a.end].eps.push(b.start);
    return { start: a.start, end: b.end };
  }
  function either(a, b) {
    const start = node(), end = node();
    states[start].eps.push(a.start, b.start);
    states[a.end].eps.push(end); states[b.end].eps.push(end);
    return { start, end };
  }
  function star(a) {
    const start = node(), end = node();
    states[start].eps.push(a.start, end);
    states[a.end].eps.push(a.start, end);
    return { start, end };
  }
  function atom() {
    const ch = pattern[pos];
    if (letter(ch)) { pos++; return literal(ch); }
    if (ch !== '(') fail();
    pos++;
    if (++depth > LIMIT.depth) throw new RangeError('depth limit');
    const a = alt();
    if (pattern[pos] !== ')') fail();
    pos++; depth--; return a;
  }
  function repeat() {
    let a = atom();
    if (pattern[pos] === '*') { pos++; a = star(a); }
    return a;
  }
  function seq() {
    let a = repeat();
    while (pos < pattern.length && pattern[pos] !== '|' && pattern[pos] !== ')') {
      a = join(a, repeat());
    }
    return a;
  }
  function alt() {
    let a = seq();
    while (pattern[pos] === '|') { pos++; a = either(a, seq()); }
    return a;
  }
  const nfa = alt();
  if (pos !== pattern.length) fail();
  function fullmatch(text) {
    if (typeof text !== 'string') throw new TypeError('text');
    if (text.length > LIMIT.text) throw new RangeError('text limit');
    let work = 0;
    const tick = () => {
      if (++work > LIMIT.work) throw new RangeError('work limit');
    };
    function close(seeds) {
      const seen = new Set(), stack = [];
      const add = id => {
        if (!seen.has(id)) { tick(); seen.add(id); stack.push(id); }
      };
      for (const id of seeds) add(id);
      while (stack.length) {
        const id = stack.pop();
        for (const next of states[id].eps) add(next);
      }
      return seen;
    }
    let active = close([nfa.start]);
    for (let i = 0; i < text.length; i++) {
      const seeds = new Set();
      for (const id of active) {
        tick();
        if (states[id].ch === text[i]) seeds.add(states[id].to);
      }
      active = close(seeds);
      if (active.size === 0) return false;
    }
    return active.has(nfa.end);
  }
  return Object.freeze({ fullmatch, stateCount: states.length });
}
function words(max) {
  const all = ['']; let layer = [''];
  for (let i = 0; i < max; i++) {
    layer = layer.flatMap(s => ['a', 'b'].map(c => s + c));
    all.push(...layer);
  }
  return all;
}
const corpus = words(5);
const pairs = [
  ['a|a', 'a'],
  ['((a|b)*)*', '(a|b)*'],
  ['a(b|a)', 'ab|aa'],
  ['(a|b)a', 'aa|ba'],
  ['(ab)c', 'a(bc)']
];
let checks = 0;
for (const [p, q] of pairs) {
  const a = compile(p), b = compile(q);
  for (const s of [...corpus, 'abc', 'abcc', 'c', 'A']) {
    assert.equal(a.fullmatch(s), b.fullmatch(s), `${p} = ${q} / ${s}`);
    checks++;
  }
}
// Reusing one compilation must not retain the previous input's state set.
const a = compile('a*'), b = compile('b*');
for (let i = 0; i < 10; i++) {
  assert.equal(a.fullmatch('aaa'), true);
  assert.equal(a.fullmatch('b'), false);
  assert.equal(a.fullmatch(''), true);
  assert.equal(b.fullmatch('bbb'), true);
  assert.equal(b.fullmatch('a'), false);
}
assert.equal(checks, 335);
console.log(`09 algebra and reuse OK: ${checks}`);

运行输出:

09 algebra and reuse OK: 335

收尾:把看起来正确拆成可以检查的证据

这次审查最终留下四类证据:语法拒绝表说明哪些请求不属于语言,片段与闭包断言说明内部结构满足什么约束,预算测试说明资源不足如何被明确报告,有限语言预言机说明一批系统生成的输入确实符合独立语义。九段脚本已经逐一以严格未处理拒绝模式执行通过,但这些结果不会替代生产环境的故障隔离、负载测试和代码维护。

面对 AI 生成的算法代码,最值得追问的往往不是能否再写短一些,而是:哪个不变量让下一步成立,哪个反例能打破它,测试答案是否来自一条足够独立的计算路线。把这三个问题回答清楚,即使只实现一个很小的语言,也能得到比一长串成功演示更扎实的信心。

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