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
_tokenize ask 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
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:
The main ideas would be:
_tokenizeask the source for a view or copy of a span.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
tokenizehas 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