-
Notifications
You must be signed in to change notification settings - Fork 2.1k
feat(forge-lint): [claude] check for unwrapped modifiers #10967
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
grandizzy
merged 27 commits into
foundry-rs:master
from
0xClandestine:feat/claude-unwrapped-modifier-lint
Jul 25, 2025
Merged
Changes from all commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
b01c759
feat: add `unwrapped_modifier_logic` gas lint
0xClandestine 7e9d6c6
cleanup
0xClandestine 7cea74a
cleanup test
0xClandestine 8480ae1
nits
0xClandestine d7a6829
nit: shorten warning
0xClandestine 37680b3
fix: rebase error
0xClandestine 9f0a28b
suggest fix
0xClandestine 9009636
cleanup
0xClandestine d9f0d06
parse indents + restructure
0xClandestine 48fed74
improve suggestion
0xClandestine 380359f
chore: normalize ind of the code to be removed
0xrusowsky ccbe0d1
Merge branch 'master' into feat/claude-unwrapped-modifier-lint
0xrusowsky 71688eb
Merge branch 'master' of github.com:foundry-rs/foundry into rusowsky/…
0xrusowsky ea05d4b
improve devex + docs
0xrusowsky 1d4cb00
Merge branch 'rusowsky/trim-rmv-span' of github.com:foundry-rs/foundr…
0xrusowsky 9f5557f
feat: simplify + use built-in indentation alignment
0xrusowsky 394bb59
fix: false positive library member calls
0xClandestine b0d793d
nit
0xClandestine e6c08dd
test: external calls throw lint
0xClandestine 7949511
refactor: simplify + document fns
0xrusowsky a6a3183
style: clippy
0xrusowsky 83c9ffe
Merge branch 'master' into feat/claude-unwrapped-modifier-lint
0xrusowsky c876c5e
nit
0xrusowsky 0d04465
Merge branch 'feat/claude-unwrapped-modifier-lint' of github.com:0xCl…
0xrusowsky b9799e6
refactor: move to new `codesize` lint group
0xrusowsky 1883e22
fix: typo
0xrusowsky 5dd172c
chore: code clarity + more docs
0xrusowsky File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
use crate::sol::{EarlyLintPass, LateLintPass, SolLint}; | ||
|
||
mod unwrapped_modifier_logic; | ||
use unwrapped_modifier_logic::UNWRAPPED_MODIFIER_LOGIC; | ||
|
||
register_lints!((UnwrappedModifierLogic, late, (UNWRAPPED_MODIFIER_LOGIC))); |
168 changes: 168 additions & 0 deletions
168
crates/lint/src/sol/codesize/unwrapped_modifier_logic.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,168 @@ | ||
use super::UnwrappedModifierLogic; | ||
use crate::{ | ||
linter::{LateLintPass, LintContext, Snippet}, | ||
sol::{Severity, SolLint}, | ||
}; | ||
use solar_ast::{self as ast, Span}; | ||
use solar_sema::hir::{self, Res}; | ||
|
||
declare_forge_lint!( | ||
UNWRAPPED_MODIFIER_LOGIC, | ||
Severity::Gas, | ||
"unwrapped-modifier-logic", | ||
"wrap modifier logic to reduce code size" | ||
); | ||
|
||
impl<'hir> LateLintPass<'hir> for UnwrappedModifierLogic { | ||
fn check_function( | ||
&mut self, | ||
ctx: &LintContext<'_>, | ||
hir: &'hir hir::Hir<'hir>, | ||
func: &'hir hir::Function<'hir>, | ||
) { | ||
// Only check modifiers with a body and a name | ||
let (body, name) = match (func.kind, &func.body, func.name) { | ||
(ast::FunctionKind::Modifier, Some(body), Some(name)) => (body, name), | ||
_ => return, | ||
}; | ||
|
||
// Split statements into before and after the placeholder `_`. | ||
let stmts = body.stmts[..].as_ref(); | ||
let (before, after) = stmts | ||
.iter() | ||
.position(|s| matches!(s.kind, hir::StmtKind::Placeholder)) | ||
.map_or((stmts, &[][..]), |idx| (&stmts[..idx], &stmts[idx + 1..])); | ||
|
||
// Generate a fix snippet if the modifier logic should be wrapped. | ||
if let Some(snippet) = self.get_snippet(ctx, hir, func, before, after) { | ||
ctx.emit_with_fix(&UNWRAPPED_MODIFIER_LOGIC, name.span, snippet); | ||
} | ||
} | ||
} | ||
|
||
impl UnwrappedModifierLogic { | ||
/// Returns `true` if an expr is not a built-in ('require' or 'assert') call or a lib function. | ||
fn is_valid_expr(&self, hir: &hir::Hir<'_>, expr: &hir::Expr<'_>) -> bool { | ||
if let hir::ExprKind::Call(func_expr, _, _) = &expr.kind { | ||
if let hir::ExprKind::Ident(resolutions) = &func_expr.kind { | ||
return !resolutions.iter().any(|r| matches!(r, Res::Builtin(_))); | ||
} | ||
|
||
if let hir::ExprKind::Member(base, _) = &func_expr.kind | ||
&& let hir::ExprKind::Ident(resolutions) = &base.kind | ||
{ | ||
return resolutions.iter().any(|r| { | ||
matches!(r, Res::Item(hir::ItemId::Contract(id)) if hir.contract(*id).kind == ast::ContractKind::Library) | ||
}); | ||
} | ||
} | ||
|
||
false | ||
} | ||
|
||
/// Checks if a block of statements is complex and should be wrapped in a helper function. | ||
/// | ||
/// This is true if the block contains: | ||
/// 1. Any statement that is not a placeholder or a valid expression. | ||
/// 2. More than one simple call expression. | ||
fn stmts_require_wrapping(&self, hir: &hir::Hir<'_>, stmts: &[hir::Stmt<'_>]) -> bool { | ||
let mut has_valid_stmt = false; | ||
for stmt in stmts { | ||
match &stmt.kind { | ||
hir::StmtKind::Placeholder => continue, | ||
hir::StmtKind::Expr(expr) => { | ||
if !self.is_valid_expr(hir, expr) || has_valid_stmt { | ||
return true; | ||
} | ||
has_valid_stmt = true; | ||
} | ||
_ => return true, | ||
} | ||
} | ||
|
||
false | ||
} | ||
|
||
fn get_snippet<'a>( | ||
&self, | ||
ctx: &LintContext<'_>, | ||
hir: &hir::Hir<'_>, | ||
func: &hir::Function<'_>, | ||
before: &'a [hir::Stmt<'a>], | ||
after: &'a [hir::Stmt<'a>], | ||
) -> Option<Snippet> { | ||
let wrap_before = !before.is_empty() && self.stmts_require_wrapping(hir, before); | ||
let wrap_after = !after.is_empty() && self.stmts_require_wrapping(hir, after); | ||
|
||
if !(wrap_before || wrap_after) { | ||
return None; | ||
} | ||
|
||
let binding = func.name.unwrap(); | ||
let modifier_name = binding.name.as_str(); | ||
let mut param_list = vec![]; | ||
let mut param_decls = vec![]; | ||
|
||
for var_id in func.parameters { | ||
let var = hir.variable(*var_id); | ||
let ty = ctx | ||
.span_to_snippet(var.ty.span) | ||
.unwrap_or_else(|| "/* unknown type */".to_string()); | ||
|
||
// solidity functions should always have named parameters | ||
if let Some(ident) = var.name { | ||
param_list.push(ident.to_string()); | ||
param_decls.push(format!("{ty} {}", ident.to_string())); | ||
} | ||
} | ||
|
||
let param_list = param_list.join(", "); | ||
let param_decls = param_decls.join(", "); | ||
|
||
let body_indent = " ".repeat(ctx.get_span_indentation( | ||
before.first().or(after.first()).map(|stmt| stmt.span).unwrap_or(func.span), | ||
)); | ||
let body = match (wrap_before, wrap_after) { | ||
(true, true) => format!( | ||
"{body_indent}_{modifier_name}Before({param_list});\n{body_indent}_;\n{body_indent}_{modifier_name}After({param_list});" | ||
), | ||
(true, false) => { | ||
format!("{body_indent}_{modifier_name}({param_list});\n{body_indent}_;") | ||
} | ||
(false, true) => { | ||
format!("{body_indent}_;\n{body_indent}_{modifier_name}({param_list});") | ||
} | ||
_ => unreachable!(), | ||
}; | ||
|
||
let mod_indent = " ".repeat(ctx.get_span_indentation(func.span)); | ||
let mut replacement = format!( | ||
"{mod_indent}modifier {modifier_name}({param_decls}) {{\n{body}\n{mod_indent}}}" | ||
); | ||
|
||
let build_func = |stmts: &[hir::Stmt<'_>], suffix: &str| { | ||
let body_stmts = stmts | ||
.iter() | ||
.filter_map(|s| ctx.span_to_snippet(s.span)) | ||
.map(|code| format!("\n{body_indent}{code}")) | ||
.collect::<String>(); | ||
format!( | ||
"\n\n{mod_indent}function _{modifier_name}{suffix}({param_decls}) internal {{{body_stmts}\n{mod_indent}}}" | ||
) | ||
}; | ||
|
||
if wrap_before { | ||
replacement.push_str(&build_func(before, if wrap_after { "Before" } else { "" })); | ||
} | ||
if wrap_after { | ||
replacement.push_str(&build_func(after, if wrap_before { "After" } else { "" })); | ||
} | ||
|
||
Some(Snippet::Diff { | ||
desc: Some("wrap modifier logic to reduce code size"), | ||
span: Some(Span::new(func.span.lo(), func.body_span.hi())), | ||
add: replacement, | ||
trim_code: true, | ||
}) | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.