`state_reset()` does not clear `save_marks` after an aborted match

未关闭
#157,705 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
3/5
预计耗时
1-2 天
新手友好度
30/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
停滞
技术栈
python
领域
backend

调研方向

从 Modules/_sre/sre.c 中的 state_reset 以及 finditer() 和 pattern.scanner() 使用的 scanner-loop 路径开始。先运行 repro.py 对比,然后验证已中止的 match 不会拖慢后续迭代,并且恢复后的 spans 保持不变。

由索引模型根据 Issue 内容生成。

描述

extension-modules type-bug
Bug description:

state_reset() in Modules/_sre/sre.c clears the per-match state at the start of each match in a scanner loop, including state->repeat, but not state->save_marks, which is zeroed only in state_init(). A match aborted by a signal returns straight out of SRE(match), so that counter stays above zero for the rest of the iterator and every later match saves and restores marks on backtracking that it would otherwise skip. Only finditer() and pattern.scanner() can observe it, because the findall/sub/split loops abandon the state on error. Results are unchanged, only the cost.

$ cat repro.py
import re, signal, time

class Alarm(Exception): pass

def boom(*args): raise Alarm
signal.signal(signal.SIGALRM, boom)

PAT = r"(z)*" + "(a)" * 200 + r"(?:xy|x)" * 300
SUBJECT = "z" * 400000 + ("a" * 200 + "x" * 300) * 400

def run(interrupt):
    it = re.compile(PAT).finditer(SUBJECT)
    if interrupt:
        signal.setitimer(signal.ITIMER_REAL, 0.02)
        try:
            next(it)
        except Alarm:
            pass
        signal.setitimer(signal.ITIMER_REAL, 0)
    next(it)
    t = time.perf_counter()
    spans = [m.span() for m in it]
    return time.perf_counter() - t, spans

clean, clean_spans = run(False)
dirty, dirty_spans = run(True)
print("clean iterator          : %.4fs, %d matches" % (clean, len(clean_spans)))
print("resumed after one abort : %.4fs, %d matches" % (dirty, len(dirty_spans)))
print("same results            : %s" % (clean_spans == dirty_spans,))

$ ./python repro.py
clean iterator          : 0.0087s, 399 matches
resumed after one abort : 0.0238s, 399 matches
same results            : True

Expected: an iterator resumed after an aborted match costs the same as a clean one.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs
  • gh-157707
主要语言
Python
星标
77.2k
派生
36k
平均合并
1 天 9 小时
30 天内合并 PR
558

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

python/cpython 的其他 Issue

查看 python/cpython 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。