Skip to content
This repository has been archived by the owner on Jul 3, 2024. It is now read-only.

Commit

Permalink
fix(solidity/core/slither-server): cleaned code and added workspace c…
Browse files Browse the repository at this point in the history
…wd to slither command
  • Loading branch information
0xSwapFeeder committed Feb 21, 2024
1 parent e6b1cd9 commit 5828ac8
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 49 deletions.
76 changes: 35 additions & 41 deletions toolchains/solidity/core/crates/slither-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::{error::SlitherError, slither::parse_slither_out, types::*};

use std::sync::Arc;
use std::vec;
use tokio::sync::Mutex;
use tokio::sync::{Mutex, MutexGuard};
use tokio_util::sync::CancellationToken;
use tower_lsp::jsonrpc::Result;
use tower_lsp::lsp_types::*;
Expand Down Expand Up @@ -56,8 +56,12 @@ impl LanguageServer for Backend {
self.client
.log_message(MessageType::INFO, "Initializing diagnostic receiver ...")
.await;

let mut receiver = self.data.lock().await.receiver.take().unwrap();
let mut state = self.data.lock().await;
state.workspace = match params.workspace_folders {
Some(workspaces) => normalize_slither_path(workspaces[0].uri.path()),
None => normalize_slither_path(params.root_uri.unwrap().path()),
};
let mut receiver = state.receiver.take().unwrap();
let client = self.client.clone();
self.join_handle
.lock()
Expand All @@ -76,19 +80,13 @@ impl LanguageServer for Backend {
)
.await;

let folders = params.workspace_folders;
if let Some(folder) = folders {
eprintln!("Initializing filters ...");
match self.initialize_filters(folder).await {
Ok(_) => {
eprintln!("Filters initialized!");
}
Err(e) => {
eprintln!("Error while initializing filters: {:?}", e);
}
match self.initialize_filters(&mut state) {
Ok(_) => {
eprintln!("Filters initialized!");
}
Err(e) => {
eprintln!("Error while initializing filters: {:?}", e);
}
} else {
eprintln!("No workspace folders found!");
}

Ok(InitializeResult {
Expand Down Expand Up @@ -183,7 +181,6 @@ impl Backend {
let state = self.data.lock().await;
for lib in state.libs_paths.iter() {
let fsrc = format!("/{}/", lib.replace('\"', ""));
eprintln!("Check path: '{}' contains lib: '{}'", path, fsrc);
if path.contains(&fsrc) {
return true;
}
Expand All @@ -195,7 +192,6 @@ impl Backend {
let state = self.data.lock().await;
for src in state.src_paths.iter() {
let fsrc = format!("/{}/", src.replace('\"', ""));
eprintln!("Check path: '{}' contains src: '{}'", path, fsrc);
if path.contains(&fsrc) {
return true;
}
Expand All @@ -207,51 +203,49 @@ impl Backend {
let state = self.data.lock().await;
for test in state.tests_paths.iter() {
let fsrc = format!("/{}/", test.replace('\"', ""));
eprintln!("Check path: '{}' contains test: '{}'", path, fsrc);
if path.contains(&fsrc) {
return true;
}
}
false
}

async fn initialize_filters(&self, workspaces: Vec<WorkspaceFolder>) -> Result<()> {
let mut state = self.data.lock().await;
fn initialize_filters(&self, state: &mut MutexGuard<SlitherData>) -> Result<()> {
//register all work directories folder aliases using foundry.toml for each workspace folder
for folder in workspaces {
let folderpath = normalize_slither_path(folder.uri.path());
let foundry_path = find_foundry_toml_config(&folderpath);
if let Ok(path) = foundry_path {
let foundry = std::fs::read_to_string(path.clone());
match foundry {
Ok(foundry) => {
parse_foundry_toml(foundry, &mut state);
}
Err(e) => {
eprintln!(
"Error while reading foundry.toml file: {:?}, path: {}",
e, path
);
}
}
let foundry_path = find_foundry_toml_config(&state.workspace);
if let Ok(path) = foundry_path {
let foundry = std::fs::read_to_string(path.clone());
match foundry {
Ok(foundry) => {
parse_foundry_toml(foundry, state);
}
Err(e) => {
eprintln!(
"Error while reading foundry.toml file: {:?}, path: {}",
e, path
);
}
}
}
Ok(())
}

async fn launch_slither(&self, uri: Url) {
let filepath = normalize_slither_path(uri.path());
let mut state = self.data.lock().await;
let token = CancellationToken::new();
let clone = token.clone();
self.data.lock().await.slither_processes.push(token);
let sender_handle = self.data.lock().await.sender.clone();
state.slither_processes.push(token);
let sender_handle = state.sender.clone();
let client = self.client.clone();
let workspace = state.workspace.clone();

tokio::spawn(async move {
tokio::select! {
_ = clone.cancelled() => {
eprintln!("SLITHER CANCELLED");
}
output = parse_slither_out(uri.path()) => {
output = parse_slither_out(&filepath, &workspace) => {
match output {
Ok(res) => {
let _ = sender_handle.send(SlitherDiag::new(uri, res)).await;
Expand All @@ -262,7 +256,7 @@ impl Backend {
MessageType::ERROR,
format!(
"File '{}' did generate an error while parsing the output: {:?}",
uri.path(),
filepath,
e
),
)
Expand All @@ -273,7 +267,7 @@ impl Backend {
client
.log_message(
MessageType::ERROR,
format!("File '{}' did generate an error: {:?}", uri.path(), e),
format!("File '{}' did generate an error: {:?}", filepath, e),
)
.await;
}
Expand Down
17 changes: 9 additions & 8 deletions toolchains/solidity/core/crates/slither-server/src/slither.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
use crate::{error::SlitherError, types::SlitherResult, utils::normalize_slither_path};
use crate::{error::SlitherError, types::SlitherResult};
use std::process::Stdio;
use tokio::{io::AsyncReadExt, process::Command};
use tower_lsp::lsp_types::Diagnostic;

pub async fn parse_slither_out(uri: &str) -> Result<Vec<Diagnostic>, SlitherError> {
pub async fn parse_slither_out(
uri: &str,
workspace: &str,
) -> Result<Vec<Diagnostic>, SlitherError> {
let mut results: Vec<Diagnostic> = Vec::new();

eprintln!("SLITHER STARTING");
let mut output = exec_slither(uri)?;
let mut output = exec_slither(uri, workspace)?;
let out = match output.stdout.take() {
Some(out) => out,
None => {
Expand All @@ -21,11 +23,9 @@ pub async fn parse_slither_out(uri: &str) -> Result<Vec<Diagnostic>, SlitherErro
let mut dst = String::new();

output.wait().await?;
eprintln!("SLITHER FINISHED");

buffer.read_to_string(&mut dst).await?;
let json: Result<SlitherResult, serde_json::Error> = serde_json::from_str(&dst);

match json {
Ok(json) => {
for detector in json.results.detectors {
Expand All @@ -41,9 +41,10 @@ pub async fn parse_slither_out(uri: &str) -> Result<Vec<Diagnostic>, SlitherErro
Ok(results)
}

fn exec_slither(uri: &str) -> Result<tokio::process::Child, std::io::Error> {
fn exec_slither(uri: &str, workspace: &str) -> Result<tokio::process::Child, std::io::Error> {
Command::new("slither")
.arg(normalize_slither_path(uri))
.current_dir(workspace)
.arg(uri)
.arg("--exclude")
.arg("naming-convention")
.arg("--json")
Expand Down
2 changes: 2 additions & 0 deletions toolchains/solidity/core/crates/slither-server/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ pub struct SlitherData {
pub libs_paths: Vec<String>,
pub src_paths: Vec<String>,
pub tests_paths: Vec<String>,
pub workspace: String,
}

impl SlitherData {
Expand All @@ -37,6 +38,7 @@ impl SlitherData {
slither_processes: vec![],
receiver: Some(receiver),
sender,
workspace: String::new(),
}
}
}
Expand Down

0 comments on commit 5828ac8

Please sign in to comment.