-
Notifications
You must be signed in to change notification settings - Fork 250
Add EnvironmentLoader for ruby-rbs crate #3050
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
dak2
wants to merge
1
commit into
ruby:master
Choose a base branch
from
dak2:environment-loader-ruby-rbs-crate
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+2,775
−3
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,199 @@ | ||
| use std::cell::OnceCell; | ||
| use std::ops::Range; | ||
| use std::path::{Path, PathBuf}; | ||
|
|
||
| /// A signature file's content with byte position <-> line/column conversion, | ||
| /// mirroring `RBS::Buffer`. | ||
| /// | ||
| /// Positions and columns are byte offsets, unlike Ruby's character offsets; | ||
| /// they agree on ASCII-only content. Use the parser's `RBSLocationRange` when | ||
| /// character offsets are needed. | ||
| /// | ||
| /// The line table is built on first use, not in [`Buffer::new`]: a normal | ||
| /// load never converts a position, and eagerly scanning every file would | ||
| /// cost more than the parse it accompanies. | ||
| #[derive(Debug, Clone)] | ||
| pub struct Buffer { | ||
| name: PathBuf, | ||
| content: String, | ||
| line_ranges: OnceCell<Vec<Range<usize>>>, | ||
| } | ||
|
|
||
| impl Buffer { | ||
| pub fn new(name: PathBuf, content: String) -> Self { | ||
| Self { | ||
| name, | ||
| content, | ||
| line_ranges: OnceCell::new(), | ||
| } | ||
| } | ||
|
|
||
| pub fn name(&self) -> &Path { | ||
| &self.name | ||
| } | ||
|
|
||
| pub fn content(&self) -> &str { | ||
| &self.content | ||
| } | ||
|
|
||
| fn line_ranges(&self) -> &[Range<usize>] { | ||
| self.line_ranges | ||
| .get_or_init(|| compute_line_ranges(&self.content)) | ||
| } | ||
|
|
||
| pub fn line_count(&self) -> usize { | ||
| self.line_ranges().len() | ||
| } | ||
|
|
||
| /// Returns the 1-origin `line` without its line terminator. | ||
| pub fn line(&self, line: usize) -> Option<&str> { | ||
| let range = self.line_ranges().get(line.checked_sub(1)?)?; | ||
| Some(&self.content[range.clone()]) | ||
| } | ||
|
|
||
| /// Converts a byte position into `(line, column)`. | ||
| /// | ||
| /// A position past the end of the content maps to `(line_count + 1, 0)`, | ||
| /// same as the Ruby implementation. | ||
| pub fn pos_to_loc(&self, pos: usize) -> (usize, usize) { | ||
| let ranges = self.line_ranges(); | ||
| let index = ranges.partition_point(|range| range.end < pos); | ||
| match ranges.get(index) { | ||
| // saturating_sub: positions inside a line terminator do not occur | ||
| // for parser-produced token boundaries. | ||
| Some(range) => (index + 1, pos.saturating_sub(range.start)), | ||
| None => (ranges.len() + 1, 0), | ||
| } | ||
| } | ||
|
|
||
| /// Converts `(line, column)` into a byte position. Line 0 maps into the | ||
| /// last line, mirroring the Ruby implementation's `Array#fetch(-1)` | ||
| /// negative indexing; lines past the end map to `last_position`. | ||
| pub fn loc_to_pos(&self, line: usize, column: usize) -> usize { | ||
| let ranges = self.line_ranges(); | ||
| let range = match line.checked_sub(1) { | ||
| None => ranges.last(), | ||
| Some(index) => ranges.get(index), | ||
| }; | ||
| match range { | ||
| Some(range) => range.start + column, | ||
| None => self.last_position(), | ||
| } | ||
| } | ||
|
|
||
| pub fn last_position(&self) -> usize { | ||
| self.line_ranges().last().map_or(0, |range| range.end) | ||
| } | ||
| } | ||
|
|
||
| fn compute_line_ranges(content: &str) -> Vec<Range<usize>> { | ||
| let mut ranges = Vec::new(); | ||
| let mut offset = 0; | ||
|
|
||
| for line in content.split_inclusive('\n') { | ||
| // Like Ruby's String#chomp: strip "\r\n" or "\n", and a bare | ||
| // trailing "\r" (which can only occur on the final line). | ||
| let without_terminator = match line.strip_suffix('\n') { | ||
| Some(l) => l.strip_suffix('\r').unwrap_or(l), | ||
| None => line.strip_suffix('\r').unwrap_or(line), | ||
| }; | ||
| ranges.push(offset..offset + without_terminator.len()); | ||
| offset += line.len(); | ||
| } | ||
|
|
||
| // Empty content is one empty line, and content ending in a newline has an | ||
| // empty line after it; both are the same trailing empty range. | ||
| if content.is_empty() || content.ends_with('\n') { | ||
| ranges.push(offset..offset); | ||
| } | ||
|
|
||
| ranges | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
||
| fn buffer(content: &str) -> Buffer { | ||
| Buffer::new(PathBuf::from("a.rbs"), content.to_string()) | ||
| } | ||
|
|
||
| #[test] | ||
| fn lines_of_content_with_trailing_newline() { | ||
| let buffer = buffer("123\nabc\n"); | ||
| assert_eq!(buffer.line_count(), 3); | ||
| assert_eq!(buffer.line(1), Some("123")); | ||
| assert_eq!(buffer.line(2), Some("abc")); | ||
| assert_eq!(buffer.line(3), Some("")); | ||
| assert_eq!(buffer.line(4), None); | ||
| assert_eq!(buffer.line(0), None); | ||
| } | ||
|
|
||
| #[test] | ||
| fn lines_of_content_without_trailing_newline() { | ||
| let buffer = buffer("123\nabc"); | ||
| assert_eq!(buffer.line_count(), 2); | ||
| assert_eq!(buffer.line(2), Some("abc")); | ||
| assert_eq!(buffer.last_position(), 7); | ||
| } | ||
|
|
||
| #[test] | ||
| fn empty_content_has_one_empty_line() { | ||
| let buffer = buffer(""); | ||
| assert_eq!(buffer.line_count(), 1); | ||
| assert_eq!(buffer.line(1), Some("")); | ||
| assert_eq!(buffer.last_position(), 0); | ||
| assert_eq!(buffer.pos_to_loc(0), (1, 0)); | ||
| } | ||
|
|
||
| #[test] | ||
| fn crlf_is_excluded_from_line_ranges() { | ||
| let buffer = buffer("abc\r\ndef\r\n"); | ||
| assert_eq!(buffer.line(1), Some("abc")); | ||
| assert_eq!(buffer.line(2), Some("def")); | ||
| assert_eq!(buffer.pos_to_loc(5), (2, 0)); | ||
| } | ||
|
|
||
| #[test] | ||
| fn pos_to_loc_matches_ruby_buffer_for_ascii() { | ||
| let buffer = buffer("123\nabc\n"); | ||
| assert_eq!(buffer.pos_to_loc(0), (1, 0)); | ||
| assert_eq!(buffer.pos_to_loc(3), (1, 3)); | ||
| assert_eq!(buffer.pos_to_loc(4), (2, 0)); | ||
| assert_eq!(buffer.pos_to_loc(7), (2, 3)); | ||
| assert_eq!(buffer.pos_to_loc(8), (3, 0)); | ||
| assert_eq!(buffer.pos_to_loc(9), (4, 0)); | ||
| } | ||
|
|
||
| #[test] | ||
| fn loc_to_pos_matches_ruby_buffer_for_ascii() { | ||
| let buffer = buffer("123\nabc\n"); | ||
| assert_eq!(buffer.loc_to_pos(1, 0), 0); | ||
| assert_eq!(buffer.loc_to_pos(2, 3), 7); | ||
| assert_eq!(buffer.loc_to_pos(3, 0), 8); | ||
| assert_eq!(buffer.loc_to_pos(10, 5), 8); | ||
| assert_eq!(buffer.last_position(), 8); | ||
| } | ||
|
|
||
| #[test] | ||
| fn trailing_carriage_return_without_newline_is_chomped() { | ||
| let buffer = buffer("abc\ndef\r"); | ||
| assert_eq!(buffer.line(2), Some("def")); | ||
| assert_eq!(buffer.last_position(), 7); | ||
| } | ||
|
|
||
| #[test] | ||
| fn line_zero_maps_to_the_last_line() { | ||
| let buffer = buffer("123\nabc"); | ||
| assert_eq!(buffer.loc_to_pos(0, 2), 6); | ||
| } | ||
|
|
||
| #[test] | ||
| fn the_line_table_is_built_only_on_demand() { | ||
| let buffer = buffer("123\nabc\n"); | ||
| assert!(buffer.line_ranges.get().is_none()); | ||
|
|
||
| buffer.pos_to_loc(4); | ||
| assert!(buffer.line_ranges.get().is_some()); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| pub mod source; | ||
|
|
||
| pub use source::{Source, SourceKind}; | ||
|
|
||
| use crate::interners::Interners; | ||
| use crate::loader::{EnvironmentLoader, LoadError}; | ||
|
|
||
| /// Owns the interners and the loaded sources. | ||
| /// | ||
| /// Owning the interners here gives a single `Environment` value the same | ||
| /// role as the Ruby implementation's global name pool: names interned while | ||
| /// loading stay resolvable and displayable for the environment's lifetime. | ||
| pub struct Environment { | ||
| interners: Interners, | ||
| sources: Vec<Source>, | ||
| } | ||
|
|
||
| impl Environment { | ||
| pub fn new() -> Self { | ||
| Environment { | ||
| interners: Interners::new(), | ||
| sources: Vec::new(), | ||
| } | ||
| } | ||
|
|
||
| pub fn interners(&self) -> &Interners { | ||
| &self.interners | ||
| } | ||
|
|
||
| pub fn sources(&self) -> &[Source] { | ||
| &self.sources | ||
| } | ||
|
|
||
| /// Crate-private: only a caller that interned the source's names into | ||
| /// *this* environment can safely add it. | ||
| pub(crate) fn interners_mut(&mut self) -> &mut Interners { | ||
| &mut self.interners | ||
| } | ||
|
|
||
| pub(crate) fn add_source(&mut self, source: Source) { | ||
| self.sources.push(source); | ||
| } | ||
|
|
||
| /// Loads every signature file the loader resolves, in load order | ||
| /// (equivalent to Ruby's `Environment.from_loader(loader)`). | ||
| /// | ||
| /// On `Err` the environment is dropped, so the partially loaded state | ||
| /// `load` leaves behind is not observable here. | ||
| pub fn from_loader(loader: &EnvironmentLoader) -> Result<Environment, LoadError> { | ||
| let mut env = Environment::new(); | ||
| loader.load(&mut env)?; | ||
| Ok(env) | ||
| } | ||
| } | ||
|
|
||
| impl Default for Environment { | ||
| fn default() -> Self { | ||
| Self::new() | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn environment_owns_interners() { | ||
| let mut env = Environment::new(); | ||
|
|
||
| let interners = env.interners_mut(); | ||
| let symbol = interners.strings.intern("Foo"); | ||
| let root = interners.type_names.absolute_root(); | ||
| let name = interners.type_names.append(root, symbol); | ||
|
|
||
| let interners = env.interners(); | ||
| assert_eq!( | ||
| interners.type_names.display(name, &interners.strings), | ||
| "::Foo" | ||
| ); | ||
| assert!(env.sources().is_empty()); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| use std::path::PathBuf; | ||
|
|
||
| use crate::ast::{Declaration, Directive}; | ||
| use crate::buffer::Buffer; | ||
|
|
||
| /// Where a loaded signature file came from, corresponding to the `source` | ||
| /// values yielded by `RBS::EnvironmentLoader#each_dir`. | ||
| #[derive(Debug, Clone, PartialEq, Eq)] | ||
| pub enum SourceKind { | ||
| /// Core library signatures (`:core` in Ruby). | ||
| Core, | ||
| /// A library resolved through the repository or a `GemSigResolver`. | ||
| /// | ||
| /// Carries the requested version as well as the name: Ruby keys its | ||
| /// library set on the `(name, version)` pair, so `uri` and `uri` 1.0 are | ||
| /// distinct entries yielded separately by `each_dir`. | ||
| Library { | ||
| name: String, | ||
| version: Option<String>, | ||
| }, | ||
| /// An explicitly added signature directory. | ||
| Dir { path: PathBuf }, | ||
| } | ||
|
|
||
| /// A parsed signature file: its buffer, `use` directives, and declarations | ||
| /// (`RBS::Source::RBS` equivalent). | ||
| #[derive(Debug)] | ||
| pub struct Source { | ||
| pub buffer: Buffer, | ||
| pub directives: Vec<Directive>, | ||
| pub declarations: Vec<Declaration>, | ||
| pub kind: SourceKind, | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ruby runtime will fill the path for the library root, where adding
sigdir name gives the path for the directory of RBS files.