Skip to content

Conversation

@eyalleshem
Copy link
Contributor

refactor: Make Parser methods immutable using interior mutability

Changed all parsing methods to take &self instead of &mut self.
Mutable parser state (token index and parser state) now uses Cell
for interior mutability.

This refactoring is preparation for the borrowed tokenizer work. When
holding borrowed tokens from the parser (with lifetime tied to &self),
we cannot call methods requiring &mut self due to Rust's borrowing
rules. Using interior mutability resolves this conflict by allowing
state mutations through shared references.

eyalsatori and others added 2 commits November 6, 2025 20:44
Key points for this commit:
- The peekable trait isn't sufficient for using string slices, as we need
  the byte indexes (start/end) to create string slices, so added the current
  byte position to the State struct
  (Note: in the long term we could potentially remove peekable and use only
  the current position as an iterator)
- Created internal functions that create slices from the original query
  instead of allocating strings, then converted these functions to return
  String to maintain compatibility (the idea is to make a small, reviewable
  commit without changing the Token struct or the parser)
  Add internal _borrowed() functions that return Cow<\'a, str> to prepare for
  zero-copy tokenization. When the source string needs no transformation
  (no escaping), return Cow::Borrowed. When transformation is required,
  return Cow::Owned.

  The Token enum still uses String, so borrowed values are converted via
  to_owned() for now. This maintains API compatibility while preparing the
  codebase for a future refactor where Token can hold borrowed strings.

  Optimized: comments, quoted strings, dollar-quoted strings, quoted identifiers.
Changed all parsing methods to take '&self' instead of '\&mut self'.
Mutable parser state (token index and parser state) now uses
for interior mutability.

This refactoring is preparation for the borrowed tokenizer work. When
holding borrowed tokens from the parser (with lifetime tied to '\&self'),
we cannot call methods requiring '\&mut self' due to Rust's borrowing
rules. Using interior mutability resolves this conflict by allowing
state mutations through shared references.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants