Base the tokenizer API on source offsets
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 35.9k
- PR merge metrics
- PR metrics pending
Description
The tokenizer currently stores many source positions as pointers into buffers that can move. Reallocating the input means rebasing all these pointers, and missing one is very easy, especially with incremental input and f-strings.
I think tokenizer positions should be offsets into the decoded source instead:
typedef Py_ssize_t TokenizerOffset;
typedef struct {
TokenizerOffset start;
TokenizerOffset end;
} TokenizerSpan;
The main ideas would be:
- One source object owns the decoded text.
- The cursor only stores its current offset and line boundaries.
- Tokens, errors and f-string state use offset spans instead of pointers.
- pegen and
_tokenizeask the source for a view or copy of a span. - Sequential tokenization keeps the current line in the cursor, while uncommon line lookups can use a small sparse index.
- Normal parsing can keep one contiguous buffer, while
tokenize(readline)can eventually use reclaimable chunks.
For incremental tokenization, new decoded input would be appended only when the cursor needs more data. Existing offsets would remain valid even if the underlying storage moves. Once tokenize has returned copied token and line strings, old input could be discarded when no active token, cursor, f-string frame or error still refers to it.
This is very nice because it separates source storage from tokenizer state, removes pointer rebasing, and means consumers no longer need to access tokenizer internals.
Linked PRs
- gh-153585
- gh-153587
- gh-156472
- gh-156482
- gh-156484
- gh-156654
- gh-157055
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reading the tokenizer implementation and the interfaces used by pegen and _tokenize, then review the linked PRs gh-153585, gh-153587, gh-156472, gh-156482, gh-156484, gh-156654, and gh-157055. Done would mean tokenizer state, tokens, errors, and f-string state use source offset spans without pointer rebasing while preserving normal and incremental tokenization.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- c, python
- Domain
- compilers
- Issue type
- Refactor
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100