From f1f25b04a70a081843370c84a1b31ee1330aaaeb Mon Sep 17 00:00:00 2001 From: 0xMemoryGrinder <35138272+0xMemoryGrinder@users.noreply.github.com> Date: Wed, 6 Dec 2023 15:39:07 -0500 Subject: [PATCH] chore: ran lint and format --- libs/foundry-wrapper/src/compiler.rs | 21 ++- libs/foundry-wrapper/src/error.rs | 5 +- libs/foundry-wrapper/src/lib.rs | 2 +- libs/foundry-wrapper/src/types.rs | 17 +- libs/foundry-wrapper/src/utils.rs | 2 +- libs/foundry-wrapper/src/utils/executable.rs | 8 +- libs/foundry-wrapper/src/utils/path.rs | 12 +- libs/lsp-handler/src/dispatcher.rs | 9 +- libs/lsp-handler/src/handler.rs | 5 +- .../src/affected_files_store.rs | 2 +- .../foundry-compiler-server/src/main.rs | 161 ++++++++++++------ .../foundry-compiler-server/src/utils.rs | 4 +- 12 files changed, 156 insertions(+), 92 deletions(-) diff --git a/libs/foundry-wrapper/src/compiler.rs b/libs/foundry-wrapper/src/compiler.rs index 80fdba3e..ee71b359 100644 --- a/libs/foundry-wrapper/src/compiler.rs +++ b/libs/foundry-wrapper/src/compiler.rs @@ -1,5 +1,9 @@ +use crate::{ + error::Error, + types::ProjectCompileOutput, + utils::{check_executable_argument, find_forge_executable, find_projects_paths}, +}; use std::process::Command; -use crate::{types::ProjectCompileOutput, error::Error, utils::{find_projects_paths, find_forge_executable, check_executable_argument}}; #[derive(Debug)] struct CompilerInner { @@ -22,12 +26,13 @@ impl Compiler { root_path: String::new(), workspaces: Vec::new(), executable_path: executable_path.to_str().unwrap_or_default().to_string(), - } + }, }) } fn find_closest_workspace(&self, file_path: &str) -> Option { - self.inner.workspaces + self.inner + .workspaces .iter() .filter(|path| file_path.starts_with(path.as_str())) .max_by_key(|path| path.len()) @@ -50,17 +55,17 @@ impl Compiler { } pub fn compile(&mut self, file_path: &str) -> Result<(String, ProjectCompileOutput), Error> { - let workspace_path = self.find_closest_workspace(&file_path).ok_or_else(|| Error::InvalidFilePath(file_path.to_string()))?; + let workspace_path = self + .find_closest_workspace(&file_path) + .ok_or_else(|| Error::InvalidFilePath(file_path.to_string()))?; let json = Command::new(&self.inner.executable_path) .current_dir(&workspace_path) .arg("compile") .arg("--format-json") .output() - .map_err(|e| { - Error::ExecutableError(e) - })?; + .map_err(|e| Error::ExecutableError(e))?; let output_str = String::from_utf8_lossy(&json.stdout); let compile_output: ProjectCompileOutput = serde_json::from_str(&output_str)?; return Ok((workspace_path, compile_output)); } -} \ No newline at end of file +} diff --git a/libs/foundry-wrapper/src/error.rs b/libs/foundry-wrapper/src/error.rs index fdd056a2..13736e48 100644 --- a/libs/foundry-wrapper/src/error.rs +++ b/libs/foundry-wrapper/src/error.rs @@ -2,10 +2,9 @@ use thiserror::Error; #[derive(Debug, Error)] pub enum Error { - #[error("Workspace loading error: {0}")] InvalidRootPath(#[from] glob::PatternError), - + #[error("Invalid file path: {0}")] InvalidFilePath(String), @@ -23,4 +22,4 @@ pub enum Error { #[error("Invalid json output: {0}")] InvalidJsonOutput(#[from] serde_json::Error), -} \ No newline at end of file +} diff --git a/libs/foundry-wrapper/src/lib.rs b/libs/foundry-wrapper/src/lib.rs index 01ee27c6..e7db777d 100644 --- a/libs/foundry-wrapper/src/lib.rs +++ b/libs/foundry-wrapper/src/lib.rs @@ -7,4 +7,4 @@ mod compiler; pub use compiler::*; mod error; -pub use error::*; \ No newline at end of file +pub use error::*; diff --git a/libs/foundry-wrapper/src/types.rs b/libs/foundry-wrapper/src/types.rs index eee2bdc9..f2dd707f 100644 --- a/libs/foundry-wrapper/src/types.rs +++ b/libs/foundry-wrapper/src/types.rs @@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ProjectCompileOutput { - errors: Vec + errors: Vec, } impl ProjectCompileOutput { @@ -11,7 +11,6 @@ impl ProjectCompileOutput { } } - #[derive(Clone, Debug, Serialize, Deserialize)] pub struct CompilationError { #[serde(rename = "sourceLocation")] @@ -64,7 +63,7 @@ impl CompilationError { pub fn get_range(&self, source_content: &str) -> Option { Some(Range { start: self.get_start_position(source_content)?, - end: self.get_end_position(source_content)? + end: self.get_end_position(source_content)?, }) } @@ -79,7 +78,7 @@ impl CompilationError { #[derive(Clone, Debug)] pub struct Position { pub line: u32, - pub column: u32 + pub column: u32, } impl Position { @@ -89,8 +88,8 @@ impl Position { if idx < l.len() { return Some(Self { line: i as u32, - column: idx as u32 - }) + column: idx as u32, + }); } idx -= l.len() + 1; } @@ -101,7 +100,7 @@ impl Position { #[derive(Clone, Debug)] pub struct Range { pub start: Position, - pub end: Position + pub end: Position, } #[derive(Clone, Debug)] @@ -117,7 +116,7 @@ impl From for Severity { s if s.to_uppercase() == "ERROR" => Self::Error, s if s.to_uppercase() == "WARNING" => Self::Warning, s if s.to_uppercase() == "INFO" => Self::Info, - _ => Self::Info + _ => Self::Info, } } -} \ No newline at end of file +} diff --git a/libs/foundry-wrapper/src/utils.rs b/libs/foundry-wrapper/src/utils.rs index 9ba43e43..da523b06 100644 --- a/libs/foundry-wrapper/src/utils.rs +++ b/libs/foundry-wrapper/src/utils.rs @@ -2,4 +2,4 @@ mod executable; pub use executable::*; mod path; -pub use path::*; \ No newline at end of file +pub use path::*; diff --git a/libs/foundry-wrapper/src/utils/executable.rs b/libs/foundry-wrapper/src/utils/executable.rs index 4abdf6e4..0566d885 100644 --- a/libs/foundry-wrapper/src/utils/executable.rs +++ b/libs/foundry-wrapper/src/utils/executable.rs @@ -1,5 +1,5 @@ -use std::path::PathBuf; use crate::Error; +use std::path::PathBuf; pub fn find_forge_executable() -> Result { which::which("forge").map_err(|_| Error::FoundryExecutableNotFound) @@ -10,13 +10,11 @@ pub fn check_executable_argument(executable_path: &str) -> Result<(), Error> { .arg("compile") .arg("--format-json") .output() - .map_err(|e| { - Error::ExecutableError(e) - })?; + .map_err(|e| Error::ExecutableError(e))?; let stderr_str = String::from_utf8_lossy(&output.stderr); if stderr_str.contains("unexpected argument '--format-json'") { return Err(Error::InvalidFoundryVersion); } Ok(()) -} \ No newline at end of file +} diff --git a/libs/foundry-wrapper/src/utils/path.rs b/libs/foundry-wrapper/src/utils/path.rs index ef31b08d..6a8999e6 100644 --- a/libs/foundry-wrapper/src/utils/path.rs +++ b/libs/foundry-wrapper/src/utils/path.rs @@ -8,10 +8,8 @@ pub fn find_projects_paths(root_path: &str) -> Result, glob::Patter .collect::>(); // remove foundry.toml at the end of the filepath - Ok( - filespaths - .iter() - .map(|path| path.parent().unwrap().to_path_buf()) - .collect() - ) -} \ No newline at end of file + Ok(filespaths + .iter() + .map(|path| path.parent().unwrap().to_path_buf()) + .collect()) +} diff --git a/libs/lsp-handler/src/dispatcher.rs b/libs/lsp-handler/src/dispatcher.rs index 06b7b9fc..cd596129 100644 --- a/libs/lsp-handler/src/dispatcher.rs +++ b/libs/lsp-handler/src/dispatcher.rs @@ -36,14 +36,14 @@ use wasm_bindgen::prelude::*; pub struct Dispatcher { handlers: Vec>, connection: Connection, - } +} impl Dispatcher { pub fn new(connection: Connection) -> Self { Dispatcher { handlers: Vec::new(), connection, - } + } } pub fn setup(&mut self, creators: Vec) @@ -1535,7 +1535,10 @@ impl Handler for Dispatcher { Ok(Some(text_edit)) } - fn selection_range(&mut self, params: SelectionRangeParams) -> Result>> { + fn selection_range( + &mut self, + params: SelectionRangeParams, + ) -> Result>> { let mut text_edit: Vec = vec![]; for handler in &mut self.handlers { let res = handler.selection_range(params.clone()); diff --git a/libs/lsp-handler/src/handler.rs b/libs/lsp-handler/src/handler.rs index 98acd3bf..e534782d 100644 --- a/libs/lsp-handler/src/handler.rs +++ b/libs/lsp-handler/src/handler.rs @@ -490,7 +490,10 @@ pub trait Handler { /// /// This request was introduced in specification version 3.15.0. - fn selection_range(&mut self, params: SelectionRangeParams) -> Result>> { + fn selection_range( + &mut self, + params: SelectionRangeParams, + ) -> Result>> { let _ = params; log("Got a textDocument/selectionRange request, but it is not implemented"); Err(Error::method_not_found()) diff --git a/toolchains/solidity/core/crates/foundry-compiler-server/src/affected_files_store.rs b/toolchains/solidity/core/crates/foundry-compiler-server/src/affected_files_store.rs index 6330d2a7..79e20c6e 100644 --- a/toolchains/solidity/core/crates/foundry-compiler-server/src/affected_files_store.rs +++ b/toolchains/solidity/core/crates/foundry-compiler-server/src/affected_files_store.rs @@ -26,4 +26,4 @@ impl AffectedFilesStore { pub fn get_affected_files(&self, project_path: &str) -> Vec { self.projects_files.get(project_path).unwrap().clone() } -} \ No newline at end of file +} diff --git a/toolchains/solidity/core/crates/foundry-compiler-server/src/main.rs b/toolchains/solidity/core/crates/foundry-compiler-server/src/main.rs index 2ed85515..85a42309 100644 --- a/toolchains/solidity/core/crates/foundry-compiler-server/src/main.rs +++ b/toolchains/solidity/core/crates/foundry-compiler-server/src/main.rs @@ -1,13 +1,13 @@ +use osmium_libs_foundry_wrapper::{CompilationError, Compiler, Error, ProjectCompileOutput}; use std::collections::HashMap; -use std::path::{Path, PathBuf}; use std::fmt::Debug; +use std::path::{Path, PathBuf}; use tokio::sync::Mutex; use tower_lsp::jsonrpc::Result; use tower_lsp::lsp_types::*; use tower_lsp::{Client, LanguageServer, LspService, Server}; -use osmium_libs_foundry_wrapper::{Compiler, ProjectCompileOutput, CompilationError, Error}; mod utils; -use utils::{get_root_path, convert_severity}; +use utils::{convert_severity, get_root_path}; mod affected_files_store; use affected_files_store::AffectedFilesStore; @@ -33,12 +33,21 @@ impl LanguageServer for Backend { let opt_path = get_root_path(params.clone()); if let Some(path) = opt_path { self.client - .log_message(MessageType::INFO, &format!("Foundry server initializing with workspace path: {:?}", path)) + .log_message( + MessageType::INFO, + &format!( + "Foundry server initializing with workspace path: {:?}", + path + ), + ) .await; self.load_workspace(path).await; } else { self.client - .log_message(MessageType::INFO, "Foundry server not initialized : no workspace path!") + .log_message( + MessageType::INFO, + "Foundry server not initialized : no workspace path!", + ) .await; } Ok(InitializeResult { @@ -60,16 +69,24 @@ impl LanguageServer for Backend { async fn did_open(&self, params: DidOpenTextDocumentParams) { self.client - .log_message(MessageType::INFO, format!("file opened!: {:}", params.text_document.uri)) + .log_message( + MessageType::INFO, + format!("file opened!: {:}", params.text_document.uri), + ) + .await; + self.compile(params.text_document.uri.path().to_string()) .await; - self.compile(params.text_document.uri.path().to_string()).await; } async fn did_save(&self, params: DidSaveTextDocumentParams) { self.client - .log_message(MessageType::INFO, format!("file changed!: {:}", params.text_document.uri)) + .log_message( + MessageType::INFO, + format!("file changed!: {:}", params.text_document.uri), + ) + .await; + self.compile(params.text_document.uri.path().to_string()) .await; - self.compile(params.text_document.uri.path().to_string()).await; } async fn shutdown(&self) -> Result<()> { @@ -87,23 +104,29 @@ impl Backend { .show_message(MessageType::WARNING, "Foundry executable not found. Please install foundry and restart the extension.") .await; return; - }, + } Err(Error::InvalidFoundryVersion) => { self.client .show_message(MessageType::WARNING, "Foundry executable version is not compatible with this extension. Please update foundry and restart the extension.") .await; return; - }, + } Err(err) => { self.client - .log_message(MessageType::ERROR, &format!("Foundry server failed to initialize: {:?}", err)) + .log_message( + MessageType::ERROR, + &format!("Foundry server failed to initialize: {:?}", err), + ) .await; return; } } if let Err(err) = state.compiler.as_mut().unwrap().load_workspace(path) { self.client - .log_message(MessageType::ERROR, &format!("Foundry server failed to initialize: {:?}", err)) + .log_message( + MessageType::ERROR, + &format!("Foundry server failed to initialize: {:?}", err), + ) .await; } else { state.initialized = true; @@ -122,7 +145,12 @@ impl Backend { self.client .log_message(MessageType::INFO, "Foundry server initializing!") .await; - let folder_path = Path::new(&filepath).parent().unwrap().to_str().unwrap().to_string(); + let folder_path = Path::new(&filepath) + .parent() + .unwrap() + .to_str() + .unwrap() + .to_string(); self.load_workspace(folder_path).await; state = self.state.lock().await; } @@ -133,28 +161,37 @@ impl Backend { match output { Ok((project_path, output)) => { /*self.client - .log_message(MessageType::INFO, format!("Compile errors: {:?}", output.get_errors())) - .await;*/ + .log_message(MessageType::INFO, format!("Compile errors: {:?}", output.get_errors())) + .await;*/ drop(state); - self.publish_errors_diagnostics(project_path, filepath, output).await; + self.publish_errors_diagnostics(project_path, filepath, output) + .await; } Err(err) => { self.client - .log_message(MessageType::ERROR, format!("error while compiling: {:?}", err)) + .log_message( + MessageType::ERROR, + format!("error while compiling: {:?}", err), + ) .await; } } - } - pub async fn publish_errors_diagnostics(&self, project_path: String, filepath: String, output: ProjectCompileOutput) { + pub async fn publish_errors_diagnostics( + &self, + project_path: String, + filepath: String, + output: ProjectCompileOutput, + ) { let mut diagnostics = HashMap::>::new(); for error in output.get_errors() { eprintln!("error: {:?}", error); - let (source_content_filepath, range) = match self.extract_diagnostic_range(&project_path, &error).await { - Some((source_content_filepath, range)) => (source_content_filepath, range), - None => continue, - }; + let (source_content_filepath, range) = + match self.extract_diagnostic_range(&project_path, error).await { + Some((source_content_filepath, range)) => (source_content_filepath, range), + None => continue, + }; let diagnostic = Diagnostic { range: Range { start: Position { @@ -175,7 +212,11 @@ impl Backend { tags: None, data: None, }; - let url = Url::parse(&format!("file://{}", source_content_filepath.to_str().unwrap())).unwrap(); + let url = Url::parse(&format!( + "file://{}", + source_content_filepath.to_str().unwrap() + )) + .unwrap(); if !diagnostics.contains_key(&url) { diagnostics.insert(url.clone(), vec![diagnostic]); } else { @@ -183,26 +224,30 @@ impl Backend { } } - self.add_not_affected_files(project_path, filepath, &mut diagnostics).await; + self.add_not_affected_files(project_path, filepath, &mut diagnostics) + .await; for (uri, diags) in diagnostics.iter() { self.client .publish_diagnostics(uri.clone(), diags.clone(), None) .await; } - } - async fn extract_diagnostic_range(&self, project_path: &str, error: &CompilationError) -> Option<(PathBuf, osmium_libs_foundry_wrapper::Range)> { + async fn extract_diagnostic_range( + &self, + project_path: &str, + error: &CompilationError, + ) -> Option<(PathBuf, osmium_libs_foundry_wrapper::Range)> { let source_content_filepath = match error.get_file_path() { Some(source_path) => { let mut complete_path = Path::new(project_path).to_path_buf(); complete_path.push(source_path); complete_path } - None => { + None => { /*self.client - .log_message(MessageType::ERROR, format!("error, cannot get filepath: {:?}", error)) - .await;*/ + .log_message(MessageType::ERROR, format!("error, cannot get filepath: {:?}", error)) + .await;*/ return None; } }; @@ -210,7 +255,13 @@ impl Backend { Ok(content) => content, Err(err) => { self.client - .log_message(MessageType::ERROR, format!("error, cannot read file: {:?}, error: {:?}", &source_content_filepath, err)) + .log_message( + MessageType::ERROR, + format!( + "error, cannot read file: {:?}, error: {:?}", + &source_content_filepath, err + ), + ) .await; return None; } @@ -219,7 +270,10 @@ impl Backend { Some(range) => range, None => { self.client - .log_message(MessageType::ERROR, format!("error, cannot get range: {:?}", error)) + .log_message( + MessageType::ERROR, + format!("error, cannot get range: {:?}", error), + ) .await; return None; } @@ -227,28 +281,36 @@ impl Backend { Some((source_content_filepath, range)) } - async fn add_not_affected_files(&self, project_path: String, filepath: String, files: &mut HashMap>) { + async fn add_not_affected_files( + &self, + project_path: String, + filepath: String, + files: &mut HashMap>, + ) { let mut state = self.state.lock().await; - state.affected_files.add_project_file(project_path.clone(), filepath.clone()); + state + .affected_files + .add_project_file(project_path.clone(), filepath.clone()); let affected_files = state.affected_files.get_affected_files(&project_path); drop(state); let mut without_diagnostics = vec![]; for file in affected_files { let url = Url::parse(&format!("file://{}", file)).unwrap(); - if !files.contains_key(&url) { - files.insert(url, vec![]); + if let std::collections::hash_map::Entry::Vacant(e) = files.entry(url) { + e.insert(vec![]); without_diagnostics.push(file); } } self.client - .log_message(MessageType::INFO, format!("files without diagnostic: {:?}", without_diagnostics)) + .log_message( + MessageType::INFO, + format!("files without diagnostic: {:?}", without_diagnostics), + ) .await; } - - } #[tokio::main] @@ -256,16 +318,13 @@ async fn main() { let stdin = tokio::io::stdin(); let stdout = tokio::io::stdout(); - let (service, socket) = LspService::new(|client| - Backend { - client, - state: Mutex::new(State { - compiler: None, - initialized: false, - affected_files: AffectedFilesStore::new(), - }) - } - ); + let (service, socket) = LspService::new(|client| Backend { + client, + state: Mutex::new(State { + compiler: None, + initialized: false, + affected_files: AffectedFilesStore::new(), + }), + }); Server::new(stdin, stdout, socket).serve(service).await; } - diff --git a/toolchains/solidity/core/crates/foundry-compiler-server/src/utils.rs b/toolchains/solidity/core/crates/foundry-compiler-server/src/utils.rs index 73f930eb..a53dd1bb 100644 --- a/toolchains/solidity/core/crates/foundry-compiler-server/src/utils.rs +++ b/toolchains/solidity/core/crates/foundry-compiler-server/src/utils.rs @@ -1,5 +1,5 @@ use osmium_libs_foundry_wrapper::Severity; -use tower_lsp::lsp_types::{InitializeParams, DiagnosticSeverity}; +use tower_lsp::lsp_types::{DiagnosticSeverity, InitializeParams}; pub fn get_root_path(params: InitializeParams) -> Option { if let Some(root_uri) = params.root_uri { @@ -16,4 +16,4 @@ pub fn convert_severity(severity: Severity) -> DiagnosticSeverity { Severity::Warning => DiagnosticSeverity::WARNING, Severity::Info => DiagnosticSeverity::INFORMATION, } -} \ No newline at end of file +}