Skip to content

Commit

Permalink
Introduce Diagnostic trait and remove error rendering in public API
Browse files Browse the repository at this point in the history
  • Loading branch information
Xanewok committed May 15, 2024
1 parent 69fdb85 commit 9c80db6
Show file tree
Hide file tree
Showing 40 changed files with 618 additions and 227 deletions.
3 changes: 0 additions & 3 deletions Cargo.lock

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

28 changes: 28 additions & 0 deletions crates/codegen/parser/runtime/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#![allow(dead_code)]

#[macro_use]
mod parser_support;

pub mod cst;
pub mod cursor;
pub mod diagnostic;
pub mod kinds;
pub(crate) mod lexer;
pub mod parse_error;
pub mod parse_output;
pub mod query;
pub mod text_index;

#[cfg(feature = "slang_napi_interfaces")]
pub mod napi_interface;

// TODO(#863): replace with the same hierarchy as the product crate:
mod user_defined {
pub mod query {
pub struct UserDefinedQueriesImpl;

impl crate::query::UserDefinedQueries for UserDefinedQueriesImpl {
// Empty Stub
}
}
}
4 changes: 3 additions & 1 deletion crates/codegen/runtime/cargo/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ anyhow = { workspace = true }
codegen_runtime_generator = { workspace = true }

[dependencies]
ariadne = { workspace = true }
ariadne = { workspace = true, optional = true }
napi = { workspace = true, optional = true }
napi-derive = { workspace = true, optional = true }
nom = { workspace = true }
Expand All @@ -28,6 +28,8 @@ thiserror = { workspace = true }
[features]
default = ["slang_napi_interfaces"]
slang_napi_interfaces = ["dep:napi", "dep:napi-derive", "dep:serde_json"]
# Only used by the `slang_solidity` CLI
__private_ariadne = ["dep:ariadne"]

[lints]
workspace = true
65 changes: 65 additions & 0 deletions crates/codegen/runtime/cargo/src/runtime/diagnostic.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
use std::borrow::Cow;
use std::error::Error;

use crate::text_index::TextRange;

#[repr(u8)]
pub enum Severity {
Error = 1,
Warning = 2,
Information = 3,
Hint = 4,
}

pub trait Diagnostic: Error {
fn range(&self) -> TextRange;
fn code(&self) -> Option<Cow<'_, str>> {
None
}
fn severity(&self) -> Severity;
fn message(&self) -> String;
}

#[cfg(feature = "__private_ariadne")]
pub fn render<D: Diagnostic>(error: &D, source_id: &str, source: &str, with_color: bool) -> String {
use ariadne::{Color, Config, Label, Report, ReportKind, Source};

use crate::text_index::TextRangeExtensions as _;

let kind = match error.severity() {
Severity::Error => ReportKind::Error,
Severity::Warning => ReportKind::Warning,
Severity::Information => ReportKind::Advice,
Severity::Hint => ReportKind::Advice,
};

let color = if with_color { Color::Red } else { Color::Unset };

let message = error.message();

if source.is_empty() {
return format!("{kind}: {message}\n ─[{source_id}:0:0]");
}

let range = error.range().char();

let report = Report::build(kind, source_id, range.start)
.with_config(Config::default().with_color(with_color))
.with_message(message)
.with_label(
Label::new((source_id, range))
.with_color(color)
.with_message("Error occurred here."),
)
.finish();

let mut result = vec![];
report
.write((source_id, Source::from(&source)), &mut result)
.expect("Failed to write report");

return String::from_utf8(result)
.expect("Failed to convert report to utf8")
.trim()
.to_string();
}
1 change: 1 addition & 0 deletions crates/codegen/runtime/cargo/src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pub(crate) mod lexer;

pub mod cst;
pub mod cursor;
pub mod diagnostic;
pub mod parse_error;
pub mod parse_output;
pub mod query;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use napi_derive::napi;

use crate::napi_interface::text_index::TextRange;

/// Severity of the compiler diagnostic.
///
/// Explicitly compatible with the LSP protocol.
#[napi(namespace = "diagnostic")]
pub enum Severity {
Error = 1,
Warning = 2,
Information = 3,
Hint = 4,
}

impl From<crate::diagnostic::Severity> for Severity {
fn from(value: crate::diagnostic::Severity) -> Severity {
match value {
crate::diagnostic::Severity::Error => Self::Error,
crate::diagnostic::Severity::Warning => Self::Warning,
crate::diagnostic::Severity::Information => Self::Information,
crate::diagnostic::Severity::Hint => Self::Hint,
}
}
}

#[napi(namespace = "diagnostic")]
pub struct Diagnostic(pub(crate) Box<dyn crate::diagnostic::Diagnostic>);

#[napi(namespace = "diagnostic")]
impl Diagnostic {
#[napi]
pub fn severity(&self) -> Severity {
self.0.severity().into()
}

#[napi(ts_return_type = "text_index.TextRange")]
pub fn text_range(&self) -> TextRange {
self.0.range().into()
}

#[napi]
pub fn message(&self) -> String {
self.0.message()
}

#[napi]
pub fn code(&self) -> String {
self.0.code().unwrap_or_default().into_owned()
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub mod cst;
pub mod cursor;
pub mod diagnostic;
pub mod parse_error;
pub mod parse_output;
pub mod query;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
use napi_derive::napi;
use text_index::TextRange;

use crate::napi_interface::diagnostic::Diagnostic;
use crate::napi_interface::{text_index, RustParseError};

#[napi(namespace = "parse_error")]
Expand All @@ -23,8 +24,10 @@ impl ParseError {
self.0.text_range().clone().into()
}

#[napi(catch_unwind)]
pub fn to_error_report(&self, source_id: String, source: String, with_color: bool) -> String {
self.0.to_error_report(&source_id, &source, with_color)
#[napi(ts_return_type = "diagnostic.Diagnostic", catch_unwind)]
pub fn to_diagnostic(&self) -> Diagnostic {
// TODO: Figure out if we can auto-gen Diagnostics methods
// in TS for this implementor rather than having to clone here
Diagnostic(Box::new(self.0.clone()))
}
}
97 changes: 36 additions & 61 deletions crates/codegen/runtime/cargo/src/runtime/parse_error.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use std::collections::BTreeSet;
use std::error::Error;
use std::fmt;

use crate::diagnostic::{self, Diagnostic};
use crate::kinds::TokenKind;
use crate::text_index::{TextRange, TextRangeExtensions};
use crate::text_index::TextRange;

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct ParseError {
Expand All @@ -13,22 +16,6 @@ impl ParseError {
pub fn text_range(&self) -> &TextRange {
&self.text_range
}

pub fn tokens_that_would_have_allowed_more_progress(&self) -> Vec<String> {
let tokens_that_would_have_allowed_more_progress = self
.tokens_that_would_have_allowed_more_progress
.iter()
.collect::<BTreeSet<_>>();

tokens_that_would_have_allowed_more_progress
.into_iter()
.map(TokenKind::to_string)
.collect()
}

pub fn to_error_report(&self, source_id: &str, source: &str, with_color: bool) -> String {
render_error_report(self, source_id, source, with_color)
}
}

impl ParseError {
Expand All @@ -43,52 +30,40 @@ impl ParseError {
}
}

pub(crate) fn render_error_report(
error: &ParseError,
source_id: &str,
source: &str,
with_color: bool,
) -> String {
use ariadne::{Color, Config, Label, Report, ReportKind, Source};

let kind = ReportKind::Error;
let color = if with_color { Color::Red } else { Color::Unset };

let tokens_that_would_have_allowed_more_progress =
error.tokens_that_would_have_allowed_more_progress();
let message = if tokens_that_would_have_allowed_more_progress.is_empty() {
"Expected end of file.".to_string()
} else {
format!(
"Expected {expectations}.",
expectations = tokens_that_would_have_allowed_more_progress.join(" or ")
)
};

if source.is_empty() {
return format!("{kind}: {message}\n ─[{source_id}:0:0]");
impl Error for ParseError {}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.tokens_that_would_have_allowed_more_progress.is_empty() {
write!(f, "Expected end of file.")
} else {
let deduped = self
.tokens_that_would_have_allowed_more_progress
.iter()
.collect::<BTreeSet<_>>();

write!(f, "Expected ")?;

for kind in deduped.iter().take(deduped.len() - 1) {
write!(f, "{kind} or ")?;
}
let last = deduped.last().expect("we just checked that it's not empty");
write!(f, "{last}.")?;

Ok(())
}
}
}

let range = error.text_range.char();

let mut builder = Report::build(kind, source_id, range.start)
.with_config(Config::default().with_color(with_color))
.with_message(message);

builder.add_label(
Label::new((source_id, range))
.with_color(color)
.with_message("Error occurred here.".to_string()),
);
impl Diagnostic for ParseError {
fn range(&self) -> TextRange {
self.text_range.clone()
}

let mut result = vec![];
builder
.finish()
.write((source_id, Source::from(&source)), &mut result)
.expect("Failed to write report");
fn severity(&self) -> diagnostic::Severity {
diagnostic::Severity::Error
}

return String::from_utf8(result)
.expect("Failed to convert report to utf8")
.trim()
.to_string();
fn message(&self) -> String {
ToString::to_string(&self)
}
}

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

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

Loading

0 comments on commit 9c80db6

Please sign in to comment.