Skip to content

Commit

Permalink
psl: allow to remove position information from ast
Browse files Browse the repository at this point in the history
  • Loading branch information
SevInf committed Mar 25, 2024
1 parent 1e42d35 commit feffe03
Show file tree
Hide file tree
Showing 19 changed files with 200 additions and 105 deletions.
8 changes: 4 additions & 4 deletions prisma-fmt/src/code_actions.rs
Expand Up @@ -208,15 +208,15 @@ fn create_missing_attribute<'a>(
}

fn range_after_span(schema: &str, span: Span) -> Range {
let start = crate::offset_to_position(span.end - 1, schema);
let end = crate::offset_to_position(span.end, schema);
let start = crate::offset_to_position(span.end() - 1, schema);
let end = crate::offset_to_position(span.end(), schema);

Range { start, end }
}

fn span_to_range(schema: &str, span: Span) -> Range {
let start = crate::offset_to_position(span.start, schema);
let end = crate::offset_to_position(span.end, schema);
let start = crate::offset_to_position(span.start(), schema);
let end = crate::offset_to_position(span.end(), schema);

Range { start, end }
}
Expand Down
2 changes: 1 addition & 1 deletion prisma-fmt/src/code_actions/multi_schema.rs
Expand Up @@ -142,7 +142,7 @@ pub(super) fn add_schema_to_schemas(
formatted_attribute,
true,
// todo: update spans so that we can just append to the end of the _inside_ of the array. Instead of needing to re-append the `]` or taking the span end -1
Span::new(span.start, span.end - 1, psl::parser_database::FileId::ZERO),
Span::new(span.start(), span.end() - 1, psl::parser_database::FileId::ZERO),
params,
)
}
Expand Down
2 changes: 1 addition & 1 deletion prisma-fmt/src/lib.rs
Expand Up @@ -230,7 +230,7 @@ pub(crate) fn range_to_span(range: Range, document: &str) -> ast::Span {

/// Gives the LSP position right after the given span.
pub(crate) fn position_after_span(span: ast::Span, document: &str) -> Position {
offset_to_position(span.end - 1, document)
offset_to_position(span.end() - 1, document)
}

/// Converts a byte offset to an LSP position, if the given offset
Expand Down
8 changes: 4 additions & 4 deletions prisma-fmt/src/lint.rs
Expand Up @@ -16,8 +16,8 @@ pub(crate) fn run(schema: &str) -> String {
.errors()
.iter()
.map(|err: &DatamodelError| MiniError {
start: err.span().start,
end: err.span().end,
start: err.span().start(),
end: err.span().end(),
text: err.message().to_string(),
is_warning: false,
})
Expand All @@ -27,8 +27,8 @@ pub(crate) fn run(schema: &str) -> String {
.warnings()
.iter()
.map(|warn: &DatamodelWarning| MiniError {
start: warn.span().start,
end: warn.span().end,
start: warn.span().start(),
end: warn.span().end(),
text: warn.message().to_owned(),
is_warning: true,
})
Expand Down
8 changes: 4 additions & 4 deletions prisma-fmt/tests/code_actions/test_api.rs
Expand Up @@ -19,8 +19,8 @@ fn parse_schema_diagnostics(file: impl Into<SourceFile>) -> Option<Vec<Diagnosti
severity: Some(DiagnosticSeverity::WARNING),
message: warn.message().to_owned(),
range: lsp_types::Range {
start: offset_to_position(warn.span().start, schema.db.source_assert_single()),
end: offset_to_position(warn.span().end, schema.db.source_assert_single()),
start: offset_to_position(warn.span().start(), schema.db.source_assert_single()),
end: offset_to_position(warn.span().end(), schema.db.source_assert_single()),
},
..Default::default()
});
Expand All @@ -31,8 +31,8 @@ fn parse_schema_diagnostics(file: impl Into<SourceFile>) -> Option<Vec<Diagnosti
severity: Some(DiagnosticSeverity::ERROR),
message: error.message().to_owned(),
range: lsp_types::Range {
start: offset_to_position(error.span().start, schema.db.source_assert_single()),
end: offset_to_position(error.span().end, schema.db.source_assert_single()),
start: offset_to_position(error.span().start(), schema.db.source_assert_single()),
end: offset_to_position(error.span().end(), schema.db.source_assert_single()),
},
..Default::default()
});
Expand Down
3 changes: 3 additions & 0 deletions psl/diagnostics/Cargo.toml
Expand Up @@ -3,6 +3,9 @@ name = "diagnostics"
version = "0.1.0"
edition = "2021"

[features]
full-spans = []

[dependencies]
colored = "2"
pest = "2.1.3"
Expand Down
8 changes: 4 additions & 4 deletions psl/diagnostics/src/pretty_print.rs
Expand Up @@ -17,8 +17,8 @@ pub(crate) fn pretty_print(
description: &str,
colorer: &'static dyn DiagnosticColorer,
) -> std::io::Result<()> {
let start_line_number = text[..span.start].matches('\n').count();
let end_line_number = text[..span.end].matches('\n').count();
let start_line_number = text[..span.start()].matches('\n').count();
let end_line_number = text[..span.end()].matches('\n').count();
let file_lines = text.split('\n').collect::<Vec<&str>>();

let chars_in_line_before: usize = file_lines[..start_line_number].iter().map(|l| l.len()).sum();
Expand All @@ -27,8 +27,8 @@ pub(crate) fn pretty_print(

let line = &file_lines[start_line_number];

let start_in_line = span.start - chars_in_line_before;
let end_in_line = std::cmp::min(start_in_line + (span.end - span.start), line.len());
let start_in_line = span.start() - chars_in_line_before;
let end_in_line = std::cmp::min(start_in_line + (span.end() - span.start()), line.len());

let prefix = &line[..start_in_line];
let offending = colorer.primary_color(&line[start_in_line..end_in_line]).bold();
Expand Down
62 changes: 9 additions & 53 deletions psl/diagnostics/src/span.rs
@@ -1,53 +1,9 @@
/// The stable identifier for a PSL file.
#[derive(Debug, PartialEq, Clone, Copy, Hash, Eq, PartialOrd, Ord)]
pub struct FileId(pub u32); // we can't encapsulate because it would be a circular crate
// dependency between diagnostics and parser-database

impl FileId {
pub const ZERO: FileId = FileId(0);
pub const MAX: FileId = FileId(u32::MAX);
}

/// Represents a location in a datamodel's text representation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Span {
pub start: usize,
pub end: usize,
pub file_id: FileId,
}

impl Span {
/// Constructor.
pub fn new(start: usize, end: usize, file_id: FileId) -> Span {
Span { start, end, file_id }
}

/// Creates a new empty span.
pub fn empty() -> Span {
Span {
start: 0,
end: 0,
file_id: FileId::ZERO,
}
}

/// Is the given position inside the span? (boundaries included)
pub fn contains(&self, position: usize) -> bool {
position >= self.start && position <= self.end
}

/// Is the given span overlapping with the current span.
pub fn overlaps(self, other: Span) -> bool {
self.contains(other.start) || self.contains(other.end)
}
}

impl From<(FileId, pest::Span<'_>)> for Span {
fn from((file_id, s): (FileId, pest::Span<'_>)) -> Self {
Span {
start: s.start(),
end: s.end(),
file_id,
}
}
}
#[cfg(feature = "full-spans")]
mod full;
#[cfg(not(feature = "full-spans"))]
mod noop;

#[cfg(feature = "full-spans")]
pub use full::{FileId, Span};
#[cfg(not(feature = "full-spans"))]
pub use noop::{FileId, Span};
71 changes: 71 additions & 0 deletions psl/diagnostics/src/span/full.rs
@@ -0,0 +1,71 @@
/// The stable identifier for a PSL file.
#[derive(Debug, PartialEq, Clone, Copy, Hash, Eq, PartialOrd, Ord)]
pub struct FileId(pub u32); // we can't encapsulate because it would be a circular crate
// dependency between diagnostics and parser-database

impl FileId {
pub const ZERO: FileId = FileId(0);
pub const MAX: FileId = FileId(u32::MAX);
}

/// Represents a location in a datamodel's text representation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Span {
start: usize,
end: usize,
file_id: FileId,
}

impl Span {
/// Constructor.
pub fn new(start: usize, end: usize, file_id: FileId) -> Span {
Span { start, end, file_id }
}

pub fn start(&self) -> usize {
self.start
}
pub fn set_start(&mut self, start: usize) {
self.start = start
}

pub fn end(&self) -> usize {
self.end
}
pub fn set_end(&mut self, end: usize) {
self.end = end
}

pub fn file_id(&self) -> FileId {
self.file_id
}

/// Creates a new empty span.
pub fn empty() -> Span {
Span {
start: 0,
end: 0,
file_id: FileId::ZERO,
}
}

/// Is the given position inside the span? (boundaries included)
pub fn contains(&self, position: usize) -> bool {
position >= self.start && position <= self.end
}

/// Is the given span overlapping with the current span.
pub fn overlaps(self, other: Span) -> bool {
self.contains(other.start) || self.contains(other.end)
}
}

impl From<(FileId, pest::Span<'_>)> for Span {
fn from((file_id, s): (FileId, pest::Span<'_>)) -> Self {
Span {
start: s.start(),
end: s.end(),
file_id,
}
}
}
56 changes: 56 additions & 0 deletions psl/diagnostics/src/span/noop.rs
@@ -0,0 +1,56 @@
/// The stable identifier for a PSL file.
#[derive(Debug, PartialEq, Clone, Copy, Hash, Eq, PartialOrd, Ord)]
pub struct FileId(pub u32); // we can't encapsulate because it would be a circular crate
// dependency between diagnostics and parser-database

impl FileId {
pub const ZERO: FileId = FileId(0);
pub const MAX: FileId = FileId(u32::MAX);
}

/// Represents a location in a datamodel's text representation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Span {}

impl Span {
/// Constructor.
pub fn new(_start: usize, _end: usize, _file_id: FileId) -> Span {
Span {}
}

pub fn start(&self) -> usize {
0
}

pub fn set_start(&mut self, _start: usize) {}

pub fn end(&self) -> usize {
0
}
pub fn set_end(&mut self, _end: usize) {}

pub fn file_id(&self) -> FileId {
FileId::ZERO
}

/// Creates a new empty span.
pub fn empty() -> Span {
Span {}
}

/// Is the given position inside the span? (boundaries included)
pub fn contains(&self, _position: usize) -> bool {
false
}

/// Is the given span overlapping with the current span.
pub fn overlaps(self, _other: Span) -> bool {
false
}
}

impl From<(FileId, pest::Span<'_>)> for Span {
fn from((_file_id, _s): (FileId, pest::Span<'_>)) -> Self {
Span {}
}
}
4 changes: 2 additions & 2 deletions psl/parser-database/src/walkers/model.rs
Expand Up @@ -213,7 +213,7 @@ impl<'db> ModelWalker<'db> {
};

let src = self.db.source(self.id.0);
let start = field.ast_field().span().start;
let start = field.ast_field().span().start();

let mut spaces = 0;

Expand All @@ -238,7 +238,7 @@ impl<'db> ModelWalker<'db> {
};

let src = self.db.source(self.id.0);
let start = field.ast_field().span().end - 2;
let start = field.ast_field().span().end() - 2;

match src.chars().nth(start) {
Some('\r') => NewlineType::Windows,
Expand Down
1 change: 1 addition & 0 deletions psl/psl-core/Cargo.toml
Expand Up @@ -10,6 +10,7 @@ mysql = []
cockroachdb = []
mssql = []
mongodb = []
full-spans = ["diagnostics/full-spans"]

[dependencies]
diagnostics = { path = "../diagnostics" }
Expand Down
2 changes: 1 addition & 1 deletion psl/psl-core/src/configuration/datasource.rs
Expand Up @@ -252,7 +252,7 @@ impl Datasource {
}

pub fn url_defined(&self) -> bool {
self.url_span.end > self.url_span.start
self.url_span.end() > self.url_span.start()
}

pub fn direct_url_defined(&self) -> bool {
Expand Down
2 changes: 1 addition & 1 deletion psl/psl-core/src/lib.rs
Expand Up @@ -57,7 +57,7 @@ impl ValidatedSchema {
let mut out = Vec::new();

for error in self.diagnostics.errors() {
let (file_name, source, _) = &self.db[error.span().file_id];
let (file_name, source, _) = &self.db[error.span().file_id()];
error.pretty_print(&mut out, file_name, source.as_str()).unwrap();
}

Expand Down

0 comments on commit feffe03

Please sign in to comment.