oxc-project / backlog

backlog for collborators only
1 stars 0 forks source link

`Source` structure to hold source text, source type, and file path #118

Open overlookmotel opened 1 month ago

overlookmotel commented 1 month ago

@Boshen said in https://github.com/oxc-project/oxc/issues/6248#issuecomment-2388851234:

Source with path, text and related friends.

Let's do that. I propose that we could also combine it with #94.

Preferred API

This would be the API we recommend to users:

let source = Source::from_file(path);

This would:

A one-stop shop!

Full API

We can also provide other ways to create a Source for advanced use cases:

struct Source<'a> {
  source_text: &'a str,
  source_type: SourceType,
  path: Option<Path>, // or `PathBuf`?
}

// Methods to create a `Source`
impl<'a> Source<'a> {
  // Load source text into arena
  fn from_file(path: Path, allocator: &'a Allocator) -> Self;
  fn from_reader<R: std::io::Read>(reader: R, size: Option<usize>, allocator: &'a Allocator) -> Self;
  // From string already in arena
  fn from_arena_string(source_text: oxc_allocator::String<'a>) -> Self;
  // From borrowed types
  fn from_str<'s: 'a>(source_text: &'s str, allocator: &'a Allocator) -> Self;
  fn from_bytes<'s: 'a>(source_text: &'s [u8], allocator: &'a Allocator) -> Self;
}

// Methods to override source type and path
impl<'a> Source<'a> {
  fn with_type(&mut self, source_type: SourceType);
  fn with_path(&mut self, path: Path);
}

from_file and from_reader take an &Allocator. It's ideal if they load the source text into the arena, for the reasons discussed in #94 (re-use allocations, warm cache).

My suggestion is that from_str and from_bytes also take an &Allocator. They don't need to right now, but if we decide in future that we always need source text to be in the arena, then we could make that change without breaking changes to the public API.

Boshen commented 1 month ago

We are never going to achieve v1 aren't we?