Thanks to visit codestin.com
Credit goes to github.com

Skip to content

gh-153568: Make the parser's per-rule stack check an inline comparison - #153573

Open
pablogsal wants to merge 2 commits into
python:mainfrom
pablogsal:gh-153568-stack-check
Open

gh-153568: Make the parser's per-rule stack check an inline comparison#153573
pablogsal wants to merge 2 commits into
python:mainfrom
pablogsal:gh-153568-stack-check

Conversation

@pablogsal

@pablogsal pablogsal commented Jul 11, 2026

Copy link
Copy Markdown
Member

Every rule entry paid a thread-state fetch plus an out-of-line call just to ask whether the C stack is about to overflow. Caching the thread state and soft stack limit in the parser turns that into one inline pointer comparison, and the overflow guard still fires exactly as before.

Benchmark (parsing 8 of the largest stdlib files, 1.3 MB, 20 times per run with _PyParser_ASTFromString — parser only, no AST-to-Python conversion; pyperf, interleaved runs):

build time per run speedup
main 1.86 s
this PR 1.65 s 1.13x faster

…parison

The parser now caches the thread state and stack limit up front and
only falls back to the full check when the stack is nearly exhausted.
Comment thread Parser/pegen.c Outdated
Comment thread Parser/pegen.c
p->known_err_token = NULL;
p->tstate = PyThreadState_Get();
// Force the stack limits to be initialized before caching them.
(void)_Py_ReachedRecursionLimitWithMargin(p->tstate, 1);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to Claude the initialization has either been done already, or the soft limit is still UINTPTR_MAX and we have a wrap around.

Comment thread Parser/pegen.h
_PyPegen_stack_exhausted(Parser *p)
{
#if _Py_STACK_GROWS_DOWN
if (_Py_get_machine_stack_pointer() > p->stack_soft_limit) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add an assert so in debug builds we check this corresponds to _Py_ReachedRecursionLimitWithMargin(p->tstate, 1)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants