Skip to main content

solidity_language_server/
runner.rs

1use crate::{
2    build::build_output_to_diagnostics, config::LintSettings, lint::lint_output_to_diagnostics,
3    solc::normalize_forge_output,
4};
5use serde::{Deserialize, Serialize};
6use std::{io, path::PathBuf};
7use thiserror::Error;
8use tokio::process::Command;
9use tower_lsp::{
10    async_trait,
11    lsp_types::{Diagnostic, Url},
12};
13
14pub struct ForgeRunner;
15
16#[async_trait]
17pub trait Runner: Send + Sync {
18    async fn build(&self, file: &str) -> Result<serde_json::Value, RunnerError>;
19    async fn lint(
20        &self,
21        file: &str,
22        lint_settings: &LintSettings,
23    ) -> Result<serde_json::Value, RunnerError>;
24    async fn ast(&self, file: &str) -> Result<serde_json::Value, RunnerError>;
25    async fn format(&self, file: &str) -> Result<String, RunnerError>;
26    async fn get_build_diagnostics(&self, file: &Url) -> Result<Vec<Diagnostic>, RunnerError>;
27    async fn get_lint_diagnostics(
28        &self,
29        file: &Url,
30        lint_settings: &LintSettings,
31    ) -> Result<Vec<Diagnostic>, RunnerError>;
32}
33
34#[async_trait]
35impl Runner for ForgeRunner {
36    async fn lint(
37        &self,
38        file_path: &str,
39        lint_settings: &LintSettings,
40    ) -> Result<serde_json::Value, RunnerError> {
41        let mut cmd = Command::new("forge");
42        cmd.arg("lint")
43            .arg(file_path)
44            .arg("--json")
45            .env("FOUNDRY_DISABLE_NIGHTLY_WARNING", "1");
46
47        // Pass --severity flags from settings
48        for sev in &lint_settings.severity {
49            cmd.args(["--severity", sev]);
50        }
51
52        // Pass --only-lint flags from settings
53        for lint_id in &lint_settings.only {
54            cmd.args(["--only-lint", lint_id]);
55        }
56
57        let output = cmd.output().await?;
58
59        let stderr_str = String::from_utf8_lossy(&output.stderr);
60
61        // Parse JSON output line by line
62        let mut diagnostics = Vec::new();
63        for line in stderr_str.lines() {
64            if line.trim().is_empty() {
65                continue;
66            }
67
68            match serde_json::from_str::<serde_json::Value>(line) {
69                Ok(value) => diagnostics.push(value),
70                Err(_e) => {
71                    continue;
72                }
73            }
74        }
75
76        Ok(serde_json::Value::Array(diagnostics))
77    }
78
79    async fn build(&self, file_path: &str) -> Result<serde_json::Value, RunnerError> {
80        let output = Command::new("forge")
81            .arg("build")
82            .arg(file_path)
83            .arg("--json")
84            .arg("--no-cache")
85            .arg("--ast")
86            .arg("--ignore-eip-3860")
87            .args(["--ignored-error-codes", "5574"])
88            .env("FOUNDRY_DISABLE_NIGHTLY_WARNING", "1")
89            .env("FOUNDRY_LINT_LINT_ON_BUILD", "false")
90            .output()
91            .await?;
92
93        let stdout_str = String::from_utf8_lossy(&output.stdout);
94        let parsed: serde_json::Value = serde_json::from_str(&stdout_str)?;
95
96        Ok(parsed)
97    }
98
99    async fn ast(&self, file_path: &str) -> Result<serde_json::Value, RunnerError> {
100        let output = Command::new("forge")
101            .arg("build")
102            .arg(file_path)
103            .arg("--json")
104            .arg("--no-cache")
105            .arg("--ast")
106            .arg("--ignore-eip-3860")
107            .args(["--ignored-error-codes", "5574"])
108            .env("FOUNDRY_DISABLE_NIGHTLY_WARNING", "1")
109            .env("FOUNDRY_LINT_LINT_ON_BUILD", "false")
110            .output()
111            .await?;
112
113        let stdout_str = String::from_utf8_lossy(&output.stdout);
114        let parsed: serde_json::Value = serde_json::from_str(&stdout_str)?;
115
116        Ok(normalize_forge_output(parsed))
117    }
118
119    async fn format(&self, file_path: &str) -> Result<String, RunnerError> {
120        let output = Command::new("forge")
121            .arg("fmt")
122            .arg(file_path)
123            .arg("--check")
124            .arg("--raw")
125            .env("FOUNDRY_DISABLE_NIGHTLY_WARNING", "1")
126            .output()
127            .await?;
128        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
129        let stderr = String::from_utf8_lossy(&output.stderr);
130        match output.status.code() {
131            Some(0) => {
132                // Already formatted, read the current file content
133                tokio::fs::read_to_string(file_path)
134                    .await
135                    .map_err(|_| RunnerError::ReadError)
136            }
137            Some(1) => {
138                // Needs formatting, stdout has the formatted content
139                if stdout.is_empty() {
140                    Err(RunnerError::CommandError(io::Error::other(format!(
141                        "forge fmt unexpected empty output on {}: exit code {}, stderr: {}",
142                        file_path, output.status, stderr
143                    ))))
144                } else {
145                    Ok(stdout)
146                }
147            }
148            _ => Err(RunnerError::CommandError(io::Error::other(format!(
149                "forge fmt failed on {}: exit code {}, stderr: {}",
150                file_path, output.status, stderr
151            )))),
152        }
153    }
154
155    async fn get_lint_diagnostics(
156        &self,
157        file: &Url,
158        lint_settings: &LintSettings,
159    ) -> Result<Vec<Diagnostic>, RunnerError> {
160        let path: PathBuf = file.to_file_path().map_err(|_| RunnerError::InvalidUrl)?;
161        let path_str = path.to_str().ok_or(RunnerError::InvalidUrl)?;
162        let lint_output = self.lint(path_str, lint_settings).await?;
163        let diagnostics = lint_output_to_diagnostics(&lint_output, path_str);
164        Ok(diagnostics)
165    }
166
167    async fn get_build_diagnostics(&self, file: &Url) -> Result<Vec<Diagnostic>, RunnerError> {
168        let path = file.to_file_path().map_err(|_| RunnerError::InvalidUrl)?;
169        let path_str = path.to_str().ok_or(RunnerError::InvalidUrl)?;
170        let content = tokio::fs::read_to_string(&path)
171            .await
172            .map_err(|_| RunnerError::ReadError)?;
173        let build_output = self.build(path_str).await?;
174        let diagnostics = build_output_to_diagnostics(&build_output, &path, &content, &[]);
175        Ok(diagnostics)
176    }
177}
178
179#[derive(Error, Debug)]
180pub enum RunnerError {
181    #[error("Invalid file URL")]
182    InvalidUrl,
183    #[error("Failed to run command: {0}")]
184    CommandError(#[from] io::Error),
185    #[error("JSON error: {0}")]
186    JsonError(#[from] serde_json::Error),
187    #[error("Empty output from compiler")]
188    EmptyOutput,
189    #[error("ReadError")]
190    ReadError,
191}
192
193#[derive(Debug, Deserialize, Serialize)]
194pub struct SourceLocation {
195    file: String,
196    start: i32, // Changed to i32 to handle -1 values
197    end: i32,   // Changed to i32 to handle -1 values
198}
199
200#[derive(Debug, Deserialize, Serialize)]
201pub struct ForgeDiagnosticMessage {
202    #[serde(rename = "sourceLocation")]
203    source_location: SourceLocation,
204    #[serde(rename = "type")]
205    error_type: String,
206    component: String,
207    severity: String,
208    #[serde(rename = "errorCode")]
209    error_code: String,
210    message: String,
211    #[serde(rename = "formattedMessage")]
212    formatted_message: String,
213}
214
215#[derive(Debug, Deserialize, Serialize)]
216pub struct CompileOutput {
217    errors: Option<Vec<ForgeDiagnosticMessage>>,
218    sources: serde_json::Value,
219    contracts: serde_json::Value,
220    build_infos: Vec<serde_json::Value>,
221}