Skip to content

migrate typechecker to new lsp #169

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

Merged
merged 5 commits into from
Jan 14, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion crates/pg_completions/src/relevance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ impl CompletionRelevance<'_> {
Some(ct) => ct,
};

let has_mentioned_tables = ctx.mentioned_relations.len() > 0;
let has_mentioned_tables = !ctx.mentioned_relations.is_empty();

self.score += match self.data {
CompletionRelevanceData::Table(_) => match clause_type {
Expand Down
2 changes: 1 addition & 1 deletion crates/pg_completions/src/test_helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ pub(crate) async fn get_test_deps(
.set_language(tree_sitter_sql::language())
.expect("Error loading sql language");

let tree = parser.parse(&input.to_string(), None).unwrap();
let tree = parser.parse(input.to_string(), None).unwrap();

(tree, schema_cache)
}
Expand Down
1 change: 1 addition & 0 deletions crates/pg_diagnostics_categories/src/categories.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ define_categories! {
"internalError/fs",
"flags/invalid",
"project",
"typecheck",
"internalError/panic",
"syntax",
"dummy",
Expand Down
4 changes: 1 addition & 3 deletions crates/pg_test_utils/src/test_database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ use uuid::Uuid;
// TODO: Work with proper config objects instead of a connection_string.
// With the current implementation, we can't parse the password from the connection string.
pub async fn get_new_test_db() -> PgPool {
dotenv::dotenv()
.ok()
.expect("Unable to load .env file for tests");
dotenv::dotenv().expect("Unable to load .env file for tests");

let connection_string = std::env::var("DATABASE_URL").expect("DATABASE_URL not set");
let password = std::env::var("DB_PASSWORD").unwrap_or("postgres".into());
Expand Down
10 changes: 5 additions & 5 deletions crates/pg_treesitter_queries/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ impl<'a> TreeSitterQueriesExecutor<'a> {

#[allow(private_bounds)]
pub fn add_query_results<Q: Query<'a>>(&mut self) {
let mut results = Q::execute(self.root_node, &self.stmt);
let mut results = Q::execute(self.root_node, self.stmt);
self.results.append(&mut results);
}

Expand Down Expand Up @@ -104,9 +104,9 @@ where
let mut parser = tree_sitter::Parser::new();
parser.set_language(tree_sitter_sql::language()).unwrap();

let tree = parser.parse(&sql, None).unwrap();
let tree = parser.parse(sql, None).unwrap();

let mut executor = TreeSitterQueriesExecutor::new(tree.root_node(), &sql);
let mut executor = TreeSitterQueriesExecutor::new(tree.root_node(), sql);

executor.add_query_results::<RelationMatch>();

Expand Down Expand Up @@ -152,7 +152,7 @@ on sq1.id = pt.id;
let mut parser = tree_sitter::Parser::new();
parser.set_language(tree_sitter_sql::language()).unwrap();

let tree = parser.parse(&sql, None).unwrap();
let tree = parser.parse(sql, None).unwrap();

// trust me bro
let range = {
Expand All @@ -172,7 +172,7 @@ on sq1.id = pt.id;
cursor.node().range()
};

let mut executor = TreeSitterQueriesExecutor::new(tree.root_node(), &sql);
let mut executor = TreeSitterQueriesExecutor::new(tree.root_node(), sql);

executor.add_query_results::<RelationMatch>();

Expand Down
2 changes: 1 addition & 1 deletion crates/pg_treesitter_queries/src/queries/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ pub enum QueryResult<'a> {
Relation(RelationMatch<'a>),
}

impl<'a> QueryResult<'a> {
impl QueryResult<'_> {
pub fn within_range(&self, range: &tree_sitter::Range) -> bool {
match self {
Self::Relation(rm) => {
Expand Down
8 changes: 4 additions & 4 deletions crates/pg_treesitter_queries/src/queries/relations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::{Query, QueryResult};
use super::QueryTryFrom;

static TS_QUERY: LazyLock<tree_sitter::Query> = LazyLock::new(|| {
static QUERY_STR: &'static str = r#"
static QUERY_STR: &str = r#"
(relation
(object_reference
.
Expand All @@ -15,7 +15,7 @@ static TS_QUERY: LazyLock<tree_sitter::Query> = LazyLock::new(|| {
)+
)
"#;
tree_sitter::Query::new(tree_sitter_sql::language(), &QUERY_STR).expect("Invalid TS Query")
tree_sitter::Query::new(tree_sitter_sql::language(), QUERY_STR).expect("Invalid TS Query")
});

#[derive(Debug)]
Expand All @@ -24,7 +24,7 @@ pub struct RelationMatch<'a> {
pub(crate) table: tree_sitter::Node<'a>,
}

impl<'a> RelationMatch<'a> {
impl RelationMatch<'_> {
pub fn get_schema(&self, sql: &str) -> Option<String> {
let str = self
.schema
Expand All @@ -48,7 +48,7 @@ impl<'a> TryFrom<&'a QueryResult<'a>> for &'a RelationMatch<'a> {

fn try_from(q: &'a QueryResult<'a>) -> Result<Self, Self::Error> {
match q {
QueryResult::Relation(r) => Ok(&r),
QueryResult::Relation(r) => Ok(r),

#[allow(unreachable_patterns)]
_ => Err("Invalid QueryResult type".into()),
Expand Down
14 changes: 7 additions & 7 deletions crates/pg_typecheck/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,16 @@ version = "0.0.0"


[dependencies]
pg_base_db.workspace = true
insta = "1.31.0"
pg_console.workspace = true
pg_diagnostics.workspace = true
pg_query_ext.workspace = true
pg_schema_cache.workspace = true
pg_syntax.workspace = true
sqlx.workspace = true
text-size.workspace = true

sqlx.workspace = true

async-std = "1.12.0"

tokio.workspace = true
tree-sitter.workspace = true
tree_sitter_sql.workspace = true

[dev-dependencies]
pg_test_utils.workspace = true
Expand Down
217 changes: 217 additions & 0 deletions crates/pg_typecheck/src/diagnostics.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
use std::io;

use pg_console::markup;
use pg_diagnostics::{Advices, Diagnostic, LogCategory, MessageAndDescription, Severity, Visit};
use sqlx::postgres::{PgDatabaseError, PgSeverity};
use text_size::TextRange;

/// A specialized diagnostic for the typechecker.
///
/// Type diagnostics are always **errors**.
#[derive(Clone, Debug, Diagnostic)]
#[diagnostic(category = "typecheck")]
pub struct TypecheckDiagnostic {
#[location(span)]
span: Option<TextRange>,
#[description]
#[message]
message: MessageAndDescription,
#[advice]
advices: TypecheckAdvices,
#[severity]
severity: Severity,
}

#[derive(Debug, Clone)]
struct TypecheckAdvices {
code: String,
schema: Option<String>,
table: Option<String>,
column: Option<String>,
data_type: Option<String>,
constraint: Option<String>,
line: Option<usize>,
file: Option<String>,
detail: Option<String>,
routine: Option<String>,
where_: Option<String>,
hint: Option<String>,
}

impl Advices for TypecheckAdvices {
fn record(&self, visitor: &mut dyn Visit) -> io::Result<()> {
// First, show the error code
visitor.record_log(
LogCategory::Error,
&markup! { "Error Code: " <Emphasis>{&self.code}</Emphasis> },
)?;

// Show detailed message if available
if let Some(detail) = &self.detail {
visitor.record_log(LogCategory::Info, &detail)?;
}

// Show object location information
if let (Some(schema), Some(table)) = (&self.schema, &self.table) {
let mut location = format!("In table: {schema}.{table}");
if let Some(column) = &self.column {
location.push_str(&format!(", column: {column}"));
}
visitor.record_log(LogCategory::Info, &location)?;
}

// Show constraint information
if let Some(constraint) = &self.constraint {
visitor.record_log(
LogCategory::Info,
&markup! { "Constraint: " <Emphasis>{constraint}</Emphasis> },
)?;
}

// Show data type information
if let Some(data_type) = &self.data_type {
visitor.record_log(
LogCategory::Info,
&markup! { "Data type: " <Emphasis>{data_type}</Emphasis> },
)?;
}

// Show context information
if let Some(where_) = &self.where_ {
visitor.record_log(LogCategory::Info, &markup! { "Context:\n"{where_}"" })?;
}

// Show hint if available
if let Some(hint) = &self.hint {
visitor.record_log(LogCategory::Info, &markup! { "Hint: "{hint}"" })?;
}

// Show source location if available
if let (Some(file), Some(line)) = (&self.file, &self.line) {
if let Some(routine) = &self.routine {
visitor.record_log(
LogCategory::Info,
&markup! { "Source: "{file}":"{line}" in "{routine}"" },
)?;
} else {
visitor.record_log(LogCategory::Info, &markup! { "Source: "{file}":"{line}"" })?;
}
}

Ok(())
}
}

pub(crate) fn create_type_error(
pg_err: &PgDatabaseError,
ts: Option<&tree_sitter::Tree>,
) -> TypecheckDiagnostic {
let position = pg_err.position().and_then(|pos| match pos {
sqlx::postgres::PgErrorPosition::Original(pos) => Some(pos - 1),
_ => None,
});

let range = position.and_then(|pos| {
ts.and_then(|tree| {
tree.root_node()
.named_descendant_for_byte_range(pos, pos)
.map(|node| {
TextRange::new(
node.start_byte().try_into().unwrap(),
node.end_byte().try_into().unwrap(),
)
})
})
});

let severity = match pg_err.severity() {
PgSeverity::Panic => Severity::Error,
PgSeverity::Fatal => Severity::Error,
PgSeverity::Error => Severity::Error,
PgSeverity::Warning => Severity::Warning,
PgSeverity::Notice => Severity::Hint,
PgSeverity::Debug => Severity::Hint,
PgSeverity::Info => Severity::Information,
PgSeverity::Log => Severity::Information,
};

TypecheckDiagnostic {
message: pg_err.to_string().into(),
severity,
span: range,
advices: TypecheckAdvices {
code: pg_err.code().to_string(),
hint: pg_err.hint().and_then(|s| {
if !s.is_empty() {
Some(s.to_string())
} else {
None
}
}),
schema: pg_err.schema().and_then(|s| {
if !s.is_empty() {
Some(s.to_string())
} else {
None
}
}),
table: pg_err.table().and_then(|s| {
if !s.is_empty() {
Some(s.to_string())
} else {
None
}
}),
detail: pg_err.detail().and_then(|s| {
if !s.is_empty() {
Some(s.to_string())
} else {
None
}
}),
column: pg_err.column().and_then(|s| {
if !s.is_empty() {
Some(s.to_string())
} else {
None
}
}),
data_type: pg_err.data_type().and_then(|s| {
if !s.is_empty() {
Some(s.to_string())
} else {
None
}
}),
constraint: pg_err.constraint().and_then(|s| {
if !s.is_empty() {
Some(s.to_string())
} else {
None
}
}),
line: pg_err.line(),
file: pg_err.file().and_then(|s| {
if !s.is_empty() {
Some(s.to_string())
} else {
None
}
}),
routine: pg_err.routine().and_then(|s| {
if !s.is_empty() {
Some(s.to_string())
} else {
None
}
}),
where_: pg_err.r#where().and_then(|s| {
if !s.is_empty() {
Some(s.to_string())
} else {
None
}
}),
},
}
}
Loading
Loading