Skip to content

Commit

Permalink
refactor(forge): rewrite geiger with Solar
Browse files Browse the repository at this point in the history
  • Loading branch information
DaniPopes committed Nov 22, 2024
1 parent cf66dea commit 1de7945
Show file tree
Hide file tree
Showing 13 changed files with 265 additions and 635 deletions.
2 changes: 2 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ foundry-block-explorers = { version = "0.9.0", default-features = false }
foundry-compilers = { version = "0.12.3", default-features = false }
foundry-fork-db = "0.7.0"
solang-parser = "=0.3.3"
solar-ast = { version = "=0.1.0", default-features = false }
solar-parse = { version = "=0.1.0", default-features = false }

## revm
Expand Down
2 changes: 2 additions & 0 deletions crates/forge/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,8 @@ semver.workspace = true
serde_json.workspace = true
similar = { version = "2", features = ["inline"] }
solang-parser.workspace = true
solar-ast.workspace = true
solar-parse.workspace = true
strum = { workspace = true, features = ["derive"] }
thiserror.workspace = true
tokio = { workspace = true, features = ["time"] }
Expand Down
158 changes: 158 additions & 0 deletions crates/forge/bin/cmd/geiger.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
use clap::{Parser, ValueHint};
use eyre::{Result, WrapErr};
use foundry_cli::utils::LoadConfig;
use foundry_compilers::{resolver::parse::SolData, Graph};
use foundry_config::{impl_figment_convert_basic, Config};
use itertools::Itertools;
use solar_ast::visit::Visit;
use solar_parse::{ast, interface::Session};
use std::path::{Path, PathBuf};

/// CLI arguments for `forge geiger`.
#[derive(Clone, Debug, Parser)]
pub struct GeigerArgs {
/// Paths to files or directories to detect.
#[arg(
conflicts_with = "root",
value_hint = ValueHint::FilePath,
value_name = "PATH",
num_args(1..),
)]
paths: Vec<PathBuf>,

/// The project's root path.
///
/// By default root of the Git repository, if in one,
/// or the current working directory.
#[arg(long, value_hint = ValueHint::DirPath, value_name = "PATH")]
root: Option<PathBuf>,

/// Globs to ignore.
#[arg(
long,
value_hint = ValueHint::FilePath,
value_name = "PATH",
num_args(1..),
)]
ignore: Vec<PathBuf>,

#[arg(long, hide = true)]
check: bool,
#[arg(long, hide = true)]
full: bool,
}

impl_figment_convert_basic!(GeigerArgs);

impl GeigerArgs {
pub fn sources(&self, config: &Config) -> Result<Vec<PathBuf>> {
let cwd = std::env::current_dir()?;

let mut sources: Vec<PathBuf> = {
if self.paths.is_empty() {
let paths = config.project_paths();
Graph::<SolData>::resolve(&paths)?
.files()
.keys()
.filter(|f| !paths.libraries.iter().any(|lib| f.starts_with(lib)))
.cloned()
.collect()
} else {
self.paths
.iter()
.flat_map(|path| foundry_common::fs::files_with_ext(path, "sol"))
.unique()
.collect()
}
};

sources.retain(|path| {
let abs_path = if path.is_absolute() { path.clone() } else { cwd.join(path) };
!self.ignore.iter().any(|ignore| {
if ignore.is_absolute() {
abs_path.starts_with(ignore)
} else {
abs_path.starts_with(cwd.join(ignore))
}
})
});

Ok(sources)
}

pub fn run(self) -> Result<usize> {
if self.check {
sh_warn!("`--check` is deprecated as it's now the default behavior\n")?;
}
if self.full {
sh_warn!("`--full` is deprecated as reports are not generated anymore\n")?;
}

let config = self.try_load_config_emit_warnings()?;
let sources = self.sources(&config).wrap_err("Failed to resolve files")?;

if config.ffi {
sh_warn!("FFI enabled\n")?;
}

let mut sess = Session::builder().with_stderr_emitter().build();
sess.dcx = sess.dcx.set_flags(|flags| flags.track_diagnostics = false);
let unsafe_cheatcodes = &[
"ffi".to_string(),
"readFile".to_string(),
"readLine".to_string(),
"writeFile".to_string(),
"writeLine".to_string(),
"removeFile".to_string(),
"closeFile".to_string(),
"setEnv".to_string(),
"deriveKey".to_string(),
];
Ok(sess
.enter(|| sources.iter().map(|file| lint_file(&sess, unsafe_cheatcodes, file)).sum()))
}
}

fn lint_file(sess: &Session, unsafe_cheatcodes: &[String], path: &Path) -> usize {
try_lint_file(sess, unsafe_cheatcodes, path).unwrap_or(0)
}

fn try_lint_file(
sess: &Session,
unsafe_cheatcodes: &[String],
path: &Path,
) -> solar_parse::interface::Result<usize> {
let arena = solar_parse::ast::Arena::new();
let mut parser = solar_parse::Parser::from_file(sess, &arena, path)?;
let ast = parser.parse_file().map_err(|e| e.emit())?;
let mut visitor = Visitor::new(sess, unsafe_cheatcodes);
visitor.visit_source_unit(&ast);
Ok(visitor.count)
}

struct Visitor<'a> {
sess: &'a Session,
count: usize,
unsafe_cheatcodes: &'a [String],
}

impl<'a> Visitor<'a> {
fn new(sess: &'a Session, unsafe_cheatcodes: &'a [String]) -> Self {
Self { sess, count: 0, unsafe_cheatcodes }
}
}

impl<'ast> Visit<'ast> for Visitor<'_> {
fn visit_expr(&mut self, expr: &'ast ast::Expr<'ast>) {
if let ast::ExprKind::Call(lhs, _args) = &expr.kind {
if let ast::ExprKind::Member(_lhs, member) = &lhs.kind {
if self.unsafe_cheatcodes.iter().any(|c| c.as_str() == member.as_str()) {
let msg = format!("usage of unsafe cheatcode `vm.{member}`");
self.sess.dcx.err(msg).span(member.span).emit();
self.count += 1;
}
}
}
self.walk_expr(expr);
}
}
11 changes: 0 additions & 11 deletions crates/forge/bin/cmd/geiger/error.rs

This file was deleted.

165 changes: 0 additions & 165 deletions crates/forge/bin/cmd/geiger/find.rs

This file was deleted.

Loading

0 comments on commit 1de7945

Please sign in to comment.