Skip to content

gh-153569: Add tokenizer source and cursor primitives#153587

Open
pablogsal wants to merge 3 commits into
python:mainfrom
pablogsal:gh-153569-tokenizer-offset-api
Open

gh-153569: Add tokenizer source and cursor primitives#153587
pablogsal wants to merge 3 commits into
python:mainfrom
pablogsal:gh-153569-tokenizer-offset-api

Conversation

@pablogsal

@pablogsal pablogsal commented Jul 11, 2026

Copy link
Copy Markdown
Member

This adds the decoded source store, offset spans, and an offset-only cursor as the foundation for moving tokenizer state away from buffer pointers.

For example:

// Own decoded bytes by line.
_PyTok_SourceText source;
_PyTok_SourceInit(&source);

static const char text[] = "answer = 42\n";
_PyTok_Off line_start = _PyTok_SourceAppendLine(
    &source, text, sizeof(text) - 1, 0);
assert(line_start >= 0);

// Navigate by source offset.
_PyTok_Cursor cursor;
_PyTok_CursorInit(&cursor, &source);
assert(_PyTok_CursorSetOffset(&cursor, line_start) == 0);

_PyTok_Off name_start = cursor.pos;
while (_PyTok_CursorPeek(&cursor, 0) != ' ') {
    assert(_PyTok_CursorAdvance(&cursor) != EOF);
}

// Keep token text as a half-open span.
_PyTok_Span name = _PyTok_SpanFromBounds(name_start, cursor.pos);

// Borrow a temporary view.
Py_ssize_t name_len;
const char *name_text = _PyTok_SourceSpanView(&source, name, &name_len);
assert(name_text != NULL);
assert(name_len == 6 && memcmp(name_text, "answer", name_len) == 0);

_PyTok_SourceClear(&source);

This PR only adds these primitives and their direct tests. It does not migrate the existing readers, lexer and f-string state, pegen, or _tokenize; those changes can be built on this API in separate PRs.

@pablogsal
pablogsal marked this pull request as ready for review July 11, 2026 19:26
@pablogsal
pablogsal marked this pull request as draft July 11, 2026 19:27
@pablogsal
pablogsal force-pushed the gh-153569-tokenizer-offset-api branch from bce3caa to 2682fe5 Compare July 11, 2026 19:38
@pablogsal pablogsal changed the title gh-153569: Base the tokenizer API on source offsets gh-153569: Add tokenizer source and cursor primitives Jul 11, 2026
@pablogsal
pablogsal marked this pull request as ready for review July 11, 2026 20:37
@pablogsal
pablogsal force-pushed the gh-153569-tokenizer-offset-api branch from 2682fe5 to 1bf43aa Compare July 11, 2026 21:15
Comment thread Parser/tokenizer/source.c Outdated
@pablogsal
pablogsal enabled auto-merge (squash) July 18, 2026 12:55
@pablogsal
pablogsal disabled auto-merge July 18, 2026 12:55
@pablogsal
pablogsal force-pushed the gh-153569-tokenizer-offset-api branch from b19b995 to 0dea29d Compare July 18, 2026 13:56
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.

2 participants