Skip to content

Commit

Permalink
LS: Partially revert #5214, remove error code book
Browse files Browse the repository at this point in the history
commit-id:791d2a15
  • Loading branch information
mkaput committed Mar 11, 2024
1 parent 3fb1a1a commit dec6b5a
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 31 deletions.
23 changes: 11 additions & 12 deletions crates/cairo-lang-diagnostics/src/error_code.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,16 @@ impl ErrorCode {
/// Format this error code in a way that is suitable for display in error message.
///
/// ```
/// # use cairo_lang_diagnostics::{codes, error_code};
/// assert_eq!(error_code!(codes::UNUSED_VARIABLE).display_bracketed(), "[E0001]");
/// # use cairo_lang_diagnostics::error_code;
/// assert_eq!(error_code!(E0001).display_bracketed(), "[E0001]");
/// ```
pub fn display_bracketed(self) -> String {
format!("[{}]", self)
}

pub fn as_str(&self) -> &str {
self.0
}
}

impl fmt::Display for ErrorCode {
Expand All @@ -39,16 +43,16 @@ impl fmt::Display for ErrorCode {
/// Constructs an [`ErrorCode`].
///
/// ```
/// # use cairo_lang_diagnostics::{codes, error_code, ErrorCode};
/// let code: ErrorCode = error_code!(codes::UNUSED_VARIABLE);
/// # use cairo_lang_diagnostics::{error_code, ErrorCode};
/// let code: ErrorCode = error_code!(E0001);
/// # assert_eq!(format!("{code}"), "E0001");
/// ```
#[macro_export]
macro_rules! error_code {
($code:expr) => {{
use $crate::ErrorCode;
// NOTE: This is a magic trick to trigger the validation in compile time.
const ENSURE_CONST: ErrorCode = ErrorCode::new($code);
const ENSURE_CONST: ErrorCode = ErrorCode::new(stringify!($code));
ENSURE_CONST
}};
}
Expand All @@ -62,16 +66,11 @@ impl OptionErrorCodeExt for Option<ErrorCode> {
/// Format this error code in a way that is suitable for display in error message.
///
/// ```
/// # use cairo_lang_diagnostics::{codes, error_code, OptionErrorCodeExt};
/// assert_eq!(Some(error_code!(codes::UNUSED_VARIABLE)).display_bracketed(), "[E0001]");
/// # use cairo_lang_diagnostics::{error_code, OptionErrorCodeExt};
/// assert_eq!(Some(error_code!(E0001)).display_bracketed(), "[E0001]");
/// assert_eq!(None.display_bracketed(), "");
/// ```
fn display_bracketed(self) -> String {
self.map(ErrorCode::display_bracketed).unwrap_or_default()
}
}

pub mod codes {
/// Unused variable.
pub const UNUSED_VARIABLE: &str = "E0001";
}
2 changes: 1 addition & 1 deletion crates/cairo-lang-diagnostics/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ pub use diagnostics::{
DiagnosticNote, Diagnostics, DiagnosticsBuilder, FormattedDiagnosticEntry, Maybe, Severity,
ToMaybe, ToOption,
};
pub use error_code::{codes, ErrorCode, OptionErrorCodeExt};
pub use error_code::{ErrorCode, OptionErrorCodeExt};
pub use location_marks::get_location_marks;

mod diagnostics;
Expand Down
63 changes: 47 additions & 16 deletions crates/cairo-lang-language-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use cairo_lang_defs::ids::{
TraitItemId, TraitLongId, UseLongId,
};
use cairo_lang_diagnostics::{
codes, DiagnosticEntry, DiagnosticLocation, Diagnostics, Severity, ToOption,
DiagnosticEntry, DiagnosticLocation, Diagnostics, Severity, ToOption,
};
use cairo_lang_filesystem::cfg::{Cfg, CfgSet};
use cairo_lang_filesystem::db::{
Expand Down Expand Up @@ -936,33 +936,64 @@ impl LanguageServer for Backend {

#[tracing::instrument(level = "debug", skip_all, fields(uri = %params.text_document.uri))]
async fn code_action(&self, params: CodeActionParams) -> LSPResult<Option<CodeActionResponse>> {
eprintln!("Code action");
self.with_db(|db| {
let mut actions = Vec::with_capacity(params.context.diagnostics.len());
let file_id = file(db, params.text_document.uri.clone());
let (node, _lookup_items) = get_node_and_lookup_items(db, file_id, params.range.start)?;
for diagnostic in params.context.diagnostics.iter() {
let action = if let Some(NumberOrString::String(code)) = &diagnostic.code {
match code.as_str() {
codes::UNUSED_VARIABLE => unused_variable(
db,
&node,
diagnostic.clone(),
params.text_document.uri.clone(),
),
_ => CodeAction::default(),
}
} else {
CodeAction::default()
};
actions.push(CodeActionOrCommand::from(action));
actions.extend(
get_code_actions_for_diagnostic(db, &node, diagnostic, &params)
.into_iter()
.map(CodeActionOrCommand::from),
);
}
Some(actions)
})
.await
}
}

/// Generate code actions for a given diagnostic.
///
/// # Arguments
///
/// * `db` - A reference to the Salsa database.
/// * `node` - The syntax node where the diagnostic is located.
/// * `diagnostic` - The diagnostic for which to generate code actions.
/// * `params` - The parameters for the code action request.
///
/// # Returns
///
/// A vector of [`CodeAction`] objects that can be applied to resolve the diagnostic.
fn get_code_actions_for_diagnostic(
db: &dyn SemanticGroup,
node: &SyntaxNode,
diagnostic: &Diagnostic,
params: &CodeActionParams,
) -> Vec<CodeAction> {
let code = match &diagnostic.code {
Some(NumberOrString::String(code)) => code,
Some(NumberOrString::Number(code)) => {
debug!("diagnostic code is not a string: `{code}`");
return vec![];
}
None => {
debug!("diagnostic code is missing");
return vec![];
}
};

match code.as_str() {
"E0001" => {
vec![unused_variable(db, node, diagnostic.clone(), params.text_document.uri.clone())]
}
code => {
debug!("no code actions for diagnostic code: {code}");
vec![]
}
}
}

/// Create a code action that prefixes an unused variable with an `_`.
#[tracing::instrument(level = "trace", skip_all)]
fn unused_variable(
Expand Down
4 changes: 2 additions & 2 deletions crates/cairo-lang-semantic/src/diagnostic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use cairo_lang_defs::ids::{
};
use cairo_lang_defs::plugin::PluginDiagnostic;
use cairo_lang_diagnostics::{
codes, error_code, DiagnosticAdded, DiagnosticEntry, DiagnosticLocation, Diagnostics,
error_code, DiagnosticAdded, DiagnosticEntry, DiagnosticLocation, Diagnostics,
DiagnosticsBuilder, ErrorCode, Severity,
};
use cairo_lang_filesystem::ids::FileId;
Expand Down Expand Up @@ -1099,7 +1099,7 @@ pub enum SemanticDiagnosticKind {
impl SemanticDiagnosticKind {
pub fn error_code(&self) -> Option<ErrorCode> {
Some(match &self {
Self::UnusedVariable => error_code!(codes::UNUSED_VARIABLE),
Self::UnusedVariable => error_code!(E0001),
_ => return None,
})
}
Expand Down

0 comments on commit dec6b5a

Please sign in to comment.