1use super::{CoverageItem, CoverageItemKind, RevertGuard, SourceLocation};
2use alloy_primitives::map::HashMap;
3use foundry_common::TestFunctionExt;
4use foundry_compilers::ProjectCompileOutput;
5use rayon::prelude::*;
6use solar::{
7 ast::{self, ExprKind, ItemKind, StmtKind, yul},
8 data_structures::{Never, map::FxHashMap},
9 interface::{RelativeBytePos, Span, sym},
10 sema::{Gcx, hir},
11};
12use std::{
13 ops::{ControlFlow, Range},
14 path::PathBuf,
15 sync::Arc,
16};
17
18#[derive(Clone)]
20struct SourceVisitor<'gcx> {
21 source_id: u32,
23 gcx: Gcx<'gcx>,
25
26 contract_name: Arc<str>,
28
29 branch_id: u32,
31
32 items: Vec<CoverageItem>,
34 anchor_hints: HashMap<usize, AnchorHints>,
36
37 all_lines: Vec<u32>,
38 branch_kinds: Vec<(u32, BranchKind)>,
40 function_calls: Vec<(Span, Arc<str>)>,
43 function_call_scopes: FxHashMap<Span, Arc<str>>,
44 stmts_after_if: FxHashMap<Span, Span>,
46 hir_source_ids: Arc<HashMap<hir::SourceId, u32>>,
48 callees: Vec<(Range<u32>, Vec<SourceLocation>)>,
51 revert_guards: Vec<PendingRevertGuard>,
53 current_function: Option<SourceLocation>,
54}
55
56#[derive(Clone, Debug, Default)]
58pub(crate) struct AnchorHints {
59 pub revert_guard: Option<RevertGuard>,
60 pub alias_function: Option<SourceLocation>,
61}
62
63#[derive(Clone)]
64struct PendingRevertGuard {
65 call: Span,
66 condition: SourceLocation,
67 body: SourceLocation,
68 statement: SourceLocation,
69 function: SourceLocation,
70}
71
72struct SourceVisitorCheckpoint {
73 items: usize,
74 all_lines: usize,
75 function_calls: usize,
76 branch_kinds: usize,
77 revert_guards: usize,
78}
79
80#[derive(Clone, Debug)]
82pub(crate) enum BranchKind {
83 Require,
85 Ternary(TernaryArms),
87 If(IfArms),
89 YulIf(SourceLocation),
91}
92
93#[derive(Clone, Debug)]
95pub(crate) struct IfArms {
96 pub(crate) then_arm: SourceLocation,
98 pub(crate) else_arm: Option<SourceLocation>,
100 pub(crate) after: Option<SourceLocation>,
103 pub(crate) then_callees: Vec<SourceLocation>,
106 pub(crate) else_callees: Vec<SourceLocation>,
108}
109
110#[derive(Clone, Debug)]
112pub(crate) struct TernaryArms {
113 pub(crate) true_arm: SourceLocation,
115 pub(crate) false_arm: SourceLocation,
117}
118
119#[derive(Clone, Copy, Debug, PartialEq, Eq)]
120pub(crate) enum EmptySpecialFunctionKind {
121 Constructor,
122 Receive,
123 Fallback,
124}
125
126struct ResolvedEmptySpecialFunction {
127 contract_source_id: u32,
128 contract_name: Arc<str>,
129 function_source_id: u32,
130 function_contract_name: Arc<str>,
131 function_bytes: Range<u32>,
132 kind: EmptySpecialFunctionKind,
133}
134
135fn resolve_empty_special_functions(
136 gcx: Gcx<'_>,
137 hir_source_ids: &HashMap<hir::SourceId, u32>,
138) -> Vec<ResolvedEmptySpecialFunction> {
139 let mut resolved = Vec::new();
140 for contract_id in gcx.hir.contract_ids() {
141 let contract = gcx.hir.contract(contract_id);
142 let Some(&contract_source_id) = hir_source_ids.get(&contract.source) else { continue };
143 let constructors = contract.linearized_bases.iter().filter_map(|&base_id| {
144 gcx.hir
145 .contract(base_id)
146 .ctor
147 .map(|function_id| (function_id, EmptySpecialFunctionKind::Constructor))
148 });
149 let runtime_functions = [
150 (contract.receive, EmptySpecialFunctionKind::Receive),
151 (contract.fallback, EmptySpecialFunctionKind::Fallback),
152 ]
153 .into_iter()
154 .filter_map(|(function_id, kind)| function_id.map(|function_id| (function_id, kind)));
155 for (function_id, kind) in constructors.chain(runtime_functions) {
156 let function = gcx.hir.function(function_id);
157 if !function.body.is_some_and(|body| body.is_empty()) {
158 continue;
159 }
160 let Some(&function_source_id) = hir_source_ids.get(&function.source) else { continue };
161 let Some(function_contract_id) = function.contract else { continue };
162 let function_contract = gcx.hir.contract(function_contract_id);
163 let function_bytes = gcx.sess.source_map().span_to_source(function.span).unwrap().data;
164 resolved.push(ResolvedEmptySpecialFunction {
165 contract_source_id,
166 contract_name: contract.name.as_str().into(),
167 function_source_id,
168 function_contract_name: function_contract.name.as_str().into(),
169 function_bytes: function_bytes.start as u32..function_bytes.end as u32,
170 kind,
171 });
172 }
173 }
174 resolved
175}
176
177impl<'gcx> SourceVisitor<'gcx> {
178 fn new(
179 source_id: u32,
180 gcx: Gcx<'gcx>,
181 hir_source_ids: Arc<HashMap<hir::SourceId, u32>>,
182 ) -> Self {
183 Self {
184 source_id,
185 gcx,
186 contract_name: Arc::default(),
187 branch_id: 0,
188 branch_kinds: Default::default(),
189 all_lines: Default::default(),
190 function_calls: Default::default(),
191 function_call_scopes: Default::default(),
192 stmts_after_if: Default::default(),
193 hir_source_ids,
194 callees: Default::default(),
195 revert_guards: Default::default(),
196 current_function: None,
197 items: Default::default(),
198 anchor_hints: Default::default(),
199 }
200 }
201
202 const fn checkpoint(&self) -> SourceVisitorCheckpoint {
203 SourceVisitorCheckpoint {
204 items: self.items.len(),
205 all_lines: self.all_lines.len(),
206 function_calls: self.function_calls.len(),
207 branch_kinds: self.branch_kinds.len(),
208 revert_guards: self.revert_guards.len(),
209 }
210 }
211
212 fn restore_checkpoint(&mut self, checkpoint: SourceVisitorCheckpoint) {
213 let SourceVisitorCheckpoint {
214 items,
215 all_lines,
216 function_calls,
217 branch_kinds,
218 revert_guards,
219 } = checkpoint;
220 self.items.truncate(items);
221 self.anchor_hints.retain(|&id, _| id < items);
222 self.all_lines.truncate(all_lines);
223 self.function_calls.truncate(function_calls);
224 self.branch_kinds.truncate(branch_kinds);
225 self.revert_guards.truncate(revert_guards);
226 }
227
228 fn visit_contract<'ast>(&mut self, contract: &'ast ast::ItemContract<'ast>) {
229 let _ = ast::Visit::visit_item_contract(self, contract);
230 }
231
232 fn has_tests(&self, checkpoint: &SourceVisitorCheckpoint) -> bool {
234 self.items[checkpoint.items..].iter().any(|item| {
235 if let CoverageItemKind::Function { name } = &item.kind {
236 name.is_any_test()
237 } else {
238 false
239 }
240 })
241 }
242
243 fn disambiguate_functions(&mut self) {
247 let mut dups = HashMap::<_, Vec<usize>>::default();
248 for (i, item) in self.items.iter().enumerate() {
249 if let CoverageItemKind::Function { name } = &item.kind {
250 dups.entry((item.loc.contract_name.clone(), name.clone())).or_default().push(i);
251 }
252 }
253 for dups in dups.values() {
254 if dups.len() > 1 {
255 for (i, &dup) in dups.iter().enumerate() {
256 let item = &mut self.items[dup];
257 if let CoverageItemKind::Function { name } = &item.kind {
258 item.kind =
259 CoverageItemKind::Function { name: format!("{name}.{i}").into() };
260 }
261 }
262 }
263 }
264 }
265
266 fn resolve_function_calls(&mut self, hir_source_id: hir::SourceId) {
267 self.function_call_scopes = self.function_calls.iter().cloned().collect();
268 let _ = hir::Visit::visit_nested_source(self, hir_source_id);
269 self.callees.sort_unstable_by_key(|(range, _)| range.start);
270 let callees = std::mem::take(&mut self.callees);
271 let callees_in = |arm: &SourceLocation| {
272 let start = callees.partition_point(|(range, _)| range.start < arm.bytes.start);
273 let mut found = callees[start..]
274 .iter()
275 .take_while(|(range, _)| range.start < arm.bytes.end)
276 .filter(|(range, _)| range.end <= arm.bytes.end)
277 .flat_map(|(_, callees)| callees.iter().cloned())
278 .filter(|callee| {
281 callee.source_id != arm.source_id
282 || callee.bytes.start > arm.bytes.start
283 || arm.bytes.end > callee.bytes.end
284 })
285 .collect::<Vec<_>>();
286 found.sort_by_key(|callee| (callee.source_id, callee.bytes.start, callee.bytes.end));
287 found.dedup_by_key(|callee| (callee.source_id, callee.bytes.clone()));
288 found
289 };
290 for (_, kind) in &mut self.branch_kinds {
291 if let BranchKind::If(arms) = kind {
292 arms.then_callees = callees_in(&arms.then_arm);
293 arms.else_callees = arms.else_arm.as_ref().map(callees_in).unwrap_or_default();
294 }
295 }
296 }
297
298 fn sort(&mut self) {
299 if self.anchor_hints.is_empty() {
300 self.items.sort();
301 return;
302 }
303 let mut items = std::mem::take(&mut self.items).into_iter().enumerate().collect::<Vec<_>>();
305 items.sort_by(|(_, lhs), (_, rhs)| lhs.cmp(rhs));
306 let mut hints = std::mem::take(&mut self.anchor_hints);
307 self.items = items
308 .into_iter()
309 .enumerate()
310 .map(|(id, (old_id, item))| {
311 if let Some(hint) = hints.remove(&old_id) {
312 self.anchor_hints.insert(id, hint);
313 }
314 item
315 })
316 .collect();
317 }
318
319 fn push_lines(&mut self) {
320 self.all_lines.sort_unstable();
321 self.all_lines.dedup();
322 let mut lines = Vec::with_capacity(self.all_lines.len());
323 let mut items = self.items.iter().enumerate().peekable();
325 for &line in &self.all_lines {
326 while items.peek().is_some_and(|(_, item)| item.loc.lines.start < line) {
327 items.next();
328 }
329 if let Some((mut reference_id, mut reference_item)) =
330 items.next_if(|(_, item)| item.loc.lines.start == line)
331 {
332 while let Some((id, item)) = items.next_if(|(_, item)| item.loc.lines.start == line)
335 {
336 if item.loc.bytes.start < reference_item.loc.bytes.start {
337 reference_id = id;
338 reference_item = item;
339 }
340 }
341 if let Some(hints) = self.anchor_hints.get(&reference_id).cloned() {
342 self.anchor_hints.insert(self.items.len() + lines.len(), hints);
343 }
344 lines.push(CoverageItem {
345 kind: CoverageItemKind::Line,
346 loc: reference_item.loc.clone(),
347 anchor_loc: None,
348 hits: 0,
349 });
350 }
351 }
352 self.items.extend(lines);
353 }
354
355 fn push_stmt(&mut self, span: Span) {
356 self.push_item_kind(CoverageItemKind::Statement, span);
357 }
358
359 fn push_item_kind(&mut self, kind: CoverageItemKind, span: Span) -> &mut CoverageItem {
362 let item =
363 CoverageItem { kind, loc: self.source_location_for(span), anchor_loc: None, hits: 0 };
364
365 debug_assert!(!matches!(item.kind, CoverageItemKind::Line));
366 self.all_lines.push(item.loc.lines.start);
367
368 self.items.push(item);
369 self.items.last_mut().unwrap()
370 }
371
372 fn source_location_for(&self, span: Span) -> SourceLocation {
373 self.location(span, self.source_id, self.contract_name.clone())
374 }
375
376 fn location(&self, span: Span, source_id: u32, contract_name: Arc<str>) -> SourceLocation {
377 let files = self.gcx.sess.source_map().files();
378 let source = files.span_to_source(span).unwrap();
379 let mut bytes = source.data;
380 if let Some(snippet) = source.file.src.get(bytes.clone())
382 && let Some(stripped) = snippet.strip_suffix(';')
383 {
384 bytes.end -= snippet.len() - stripped.trim_end().len();
385 }
386
387 assert!(!span.is_dummy());
389 let first = source.file.lookup_line(RelativeBytePos::from_usize(bytes.start)).unwrap();
390 let last = source.file.lookup_line(RelativeBytePos::from_usize(bytes.end)).unwrap();
391 SourceLocation {
392 source_id: source_id as usize,
393 contract_name,
394 bytes: bytes.start as u32..bytes.end as u32,
395 lines: first as u32 + 1..last as u32 + 2,
396 }
397 }
398
399 fn push_callees(&mut self, call: &hir::Expr<'_>, callee: &hir::Expr<'_>) {
402 let hir::ExprKind::Ident(res) = &callee.peel_parens().kind else { return };
403 let callees = res
404 .iter()
405 .filter_map(|res| match res {
406 hir::Res::Item(hir::ItemId::Function(id)) => Some(self.gcx.hir.function(*id)),
407 _ => None,
408 })
409 .filter(|function| function.body.is_some())
410 .filter_map(|function| {
411 let &source_id = self.hir_source_ids.get(&function.source)?;
412 let contract = function.contract.map(|id| self.gcx.hir.contract(id).name.as_str());
413 Some(self.location(function.span, source_id, contract.unwrap_or_default().into()))
414 })
415 .collect::<Vec<_>>();
416 if !callees.is_empty() {
417 let bytes = self.gcx.sess.source_map().span_to_source(call.span).unwrap().data;
418 self.callees.push((bytes.start as u32..bytes.end as u32, callees));
419 }
420 }
421
422 const fn next_branch_id(&mut self) -> u32 {
423 let id = self.branch_id;
424 self.branch_id = id + 1;
425 id
426 }
427}
428
429impl<'ast> ast::Visit<'ast> for SourceVisitor<'_> {
430 type BreakValue = Never;
431
432 fn visit_item_contract(
433 &mut self,
434 contract: &'ast ast::ItemContract<'ast>,
435 ) -> ControlFlow<Self::BreakValue> {
436 self.contract_name = contract.name.as_str().into();
437 self.walk_item_contract(contract)
438 }
439
440 #[expect(clippy::single_match)]
441 fn visit_item(&mut self, item: &'ast ast::Item<'ast>) -> ControlFlow<Self::BreakValue> {
442 match &item.kind {
443 ItemKind::Function(func) => {
444 if func.kind == ast::FunctionKind::Modifier && !has_statements(func.body.as_ref()) {
447 return ControlFlow::Continue(());
448 }
449
450 let name = func.header.name.as_ref().map(|n| n.as_str()).unwrap_or_else(|| {
451 match func.kind {
452 ast::FunctionKind::Constructor => "constructor",
453 ast::FunctionKind::Receive => "receive",
454 ast::FunctionKind::Fallback => "fallback",
455 ast::FunctionKind::Function | ast::FunctionKind::Modifier => unreachable!(),
456 }
457 });
458
459 let exclude_func = func.header.virtual_() && !func.is_implemented();
461 if !exclude_func {
462 self.push_item_kind(
463 CoverageItemKind::Function { name: name.into() },
464 item.span,
465 );
466 }
467
468 TernaryVisitor(self).walk_item(item)?;
470 let first = self.items.len();
471 let location = self.source_location_for(item.span);
472 let previous_function = self.current_function.replace(location.clone());
473 self.walk_item(item)?;
474 self.current_function = previous_function;
475 if storage_alias_body(func) {
476 for id in first..self.items.len() {
477 self.anchor_hints.entry(id).or_default().alias_function =
478 Some(location.clone());
479 }
480 }
481 }
482 _ => {}
483 }
484 ControlFlow::Continue(())
486 }
487
488 fn visit_block(&mut self, block: &'ast ast::Block<'ast>) -> ControlFlow<Self::BreakValue> {
489 for stmts in block.windows(2) {
490 if matches!(stmts[0].kind, StmtKind::If(..)) {
491 self.stmts_after_if.insert(stmts[0].span, stmts[1].span);
492 }
493 }
494 self.walk_block(block)
495 }
496
497 fn visit_stmt(&mut self, stmt: &'ast ast::Stmt<'ast>) -> ControlFlow<Self::BreakValue> {
498 match &stmt.kind {
499 StmtKind::Break | StmtKind::Continue | StmtKind::Emit(..) | StmtKind::Revert(..) => {
500 self.push_stmt(stmt.span);
501 return ControlFlow::Continue(());
503 }
504 StmtKind::Return(_) | StmtKind::DeclSingle(_) | StmtKind::DeclMulti(..) => {
505 self.push_stmt(stmt.span);
506 }
507
508 StmtKind::If(cond, then_stmt, else_stmt) => {
509 let body = match &then_stmt.kind {
510 StmtKind::Block(block) if block.stmts.len() == 1 => &block.stmts[0],
511 _ => then_stmt,
512 };
513 if matches!(body.kind, StmtKind::Revert(..))
514 && else_stmt.is_none()
515 && let Some(function) = self.current_function.clone()
516 {
517 self.revert_guards.push(PendingRevertGuard {
518 call: body.span,
519 condition: self.source_location_for(cond.span),
520 body: self.source_location_for(body.span),
521 statement: self.source_location_for(stmt.span),
522 function,
523 });
524 }
525 let branch_id = self.next_branch_id();
526
527 if stmt_has_statements(then_stmt)
529 || else_stmt.as_ref().is_some_and(|s| stmt_has_statements(s))
530 {
531 let anchor_loc = self.source_location_for(then_stmt.span);
534 let after_span = self.stmts_after_if.get(&stmt.span).copied();
535 let after = after_span.map(|span| self.source_location_for(span));
536 let mut arms = IfArms {
537 then_arm: anchor_loc.clone(),
538 else_arm: None,
539 after,
540 then_callees: Vec::new(),
541 else_callees: Vec::new(),
542 };
543 self.push_item_kind(
544 CoverageItemKind::Branch { branch_id, path_id: 0, is_first_opcode: true },
545 stmt.span,
546 )
547 .anchor_loc = Some(anchor_loc);
548 if let Some(else_stmt) = else_stmt {
549 if let Some(span) = after_span {
551 self.stmts_after_if.insert(else_stmt.span, span);
552 }
553 let is_first_opcode = stmt_has_statements(else_stmt);
554 let anchor_loc =
555 is_first_opcode.then(|| self.source_location_for(else_stmt.span));
556 arms.else_arm.clone_from(&anchor_loc);
557 self.push_item_kind(
558 CoverageItemKind::Branch { branch_id, path_id: 1, is_first_opcode },
559 stmt.span,
560 )
561 .anchor_loc = anchor_loc;
562 }
563 self.branch_kinds.push((branch_id, BranchKind::If(arms)));
564 }
565 }
566
567 StmtKind::Try(ast::StmtTry { expr: _, clauses }) => {
568 let branch_id = self.next_branch_id();
569
570 let mut path_id = 0;
571 for catch in clauses.iter() {
572 let ast::TryCatchClause { span, name: _, args, block } = catch;
573 let span = if path_id == 0 { stmt.span.to(*span) } else { *span };
574 if path_id == 0 || has_statements(Some(block)) {
575 self.push_item_kind(
576 CoverageItemKind::Branch { branch_id, path_id, is_first_opcode: true },
577 span,
578 );
579 path_id += 1;
580 } else if !args.is_empty() {
581 self.push_stmt(span);
585 }
586 }
587 }
588
589 StmtKind::Assembly(_)
591 | StmtKind::Block(_)
592 | StmtKind::UncheckedBlock(_)
593 | StmtKind::Placeholder
594 | StmtKind::Expr(_)
595 | StmtKind::While(..)
596 | StmtKind::DoWhile(..)
597 | StmtKind::For { .. } => {}
598 }
599 self.walk_stmt(stmt)
600 }
601
602 fn visit_expr(&mut self, expr: &'ast ast::Expr<'ast>) -> ControlFlow<Self::BreakValue> {
603 match &expr.kind {
604 ExprKind::Assign(..)
605 | ExprKind::Unary(..)
606 | ExprKind::Binary(..)
607 | ExprKind::Ternary(..) => {
608 self.push_stmt(expr.span);
609 if matches!(expr.kind, ExprKind::Binary(..)) {
610 return self.walk_expr(expr);
611 }
612 }
613 ExprKind::Call(callee, _args) => {
614 self.function_calls.push((expr.span, self.contract_name.clone()));
616
617 if let ExprKind::Ident(ident) = &callee.kind {
618 if ident.as_str() == "require" {
621 let branch_id = self.next_branch_id();
622 self.branch_kinds.push((branch_id, BranchKind::Require));
623 self.push_item_kind(
624 CoverageItemKind::Branch {
625 branch_id,
626 path_id: 0,
627 is_first_opcode: false,
628 },
629 expr.span,
630 );
631 self.push_item_kind(
632 CoverageItemKind::Branch {
633 branch_id,
634 path_id: 1,
635 is_first_opcode: false,
636 },
637 expr.span,
638 );
639 }
640 }
641 }
642 _ => {}
643 }
644 ControlFlow::Continue(())
646 }
647
648 fn visit_yul_stmt(&mut self, stmt: &'ast yul::Stmt<'ast>) -> ControlFlow<Self::BreakValue> {
649 use yul::StmtKind;
650 match &stmt.kind {
651 StmtKind::VarDecl(..)
652 | StmtKind::AssignSingle(..)
653 | StmtKind::AssignMulti(..)
654 | StmtKind::Leave
655 | StmtKind::Break
656 | StmtKind::Continue => {
657 self.push_stmt(stmt.span);
658 return ControlFlow::Continue(());
660 }
661 StmtKind::If(_, body) => {
662 let branch_id = self.next_branch_id();
663 let body = self.source_location_for(body.span);
664 self.branch_kinds.push((branch_id, BranchKind::YulIf(body)));
665 for path_id in 0..2 {
667 self.push_item_kind(
668 CoverageItemKind::Branch { branch_id, path_id, is_first_opcode: false },
669 stmt.span,
670 );
671 }
672 }
673 StmtKind::For(yul::StmtFor { body, .. }) => {
674 self.push_stmt(body.span);
675 }
676 StmtKind::Switch(switch) => {
677 for case in switch.cases.iter() {
678 self.push_stmt(case.span);
679 self.push_stmt(case.body.span);
680 }
681 }
682 StmtKind::FunctionDef(func) => {
683 let name = func.name.as_str();
684 self.push_item_kind(CoverageItemKind::Function { name: name.into() }, stmt.span);
685 }
686 StmtKind::Expr(_) => {
688 self.push_stmt(stmt.span);
689 return ControlFlow::Continue(());
690 }
691 StmtKind::Block(_) => {}
692 }
693 self.walk_yul_stmt(stmt)
694 }
695
696 fn visit_yul_expr(&mut self, expr: &'ast yul::Expr<'ast>) -> ControlFlow<Self::BreakValue> {
697 use yul::ExprKind;
698 match &expr.kind {
699 ExprKind::Path(_) | ExprKind::Lit(_) => {}
700 ExprKind::Call(_) => self.push_stmt(expr.span),
701 }
702 ControlFlow::Continue(())
704 }
705}
706
707struct TernaryVisitor<'a, 'gcx>(&'a mut SourceVisitor<'gcx>);
710
711impl<'ast> ast::Visit<'ast> for TernaryVisitor<'_, '_> {
712 type BreakValue = Never;
713
714 fn visit_expr(&mut self, expr: &'ast ast::Expr<'ast>) -> ControlFlow<Self::BreakValue> {
715 if let ExprKind::Ternary(_, true_arm, false_arm) = &expr.kind {
716 let branch_id = self.0.next_branch_id();
717 let arms = TernaryArms {
718 true_arm: self.0.source_location_for(true_arm.span),
719 false_arm: self.0.source_location_for(false_arm.span),
720 };
721 self.0.branch_kinds.push((branch_id, BranchKind::Ternary(arms)));
722 for path_id in 0..2 {
725 self.0.push_item_kind(
726 CoverageItemKind::Branch { branch_id, path_id, is_first_opcode: false },
727 expr.span,
728 );
729 }
730 }
731 self.walk_expr(expr)
732 }
733}
734
735impl<'gcx> hir::Visit<'gcx> for SourceVisitor<'gcx> {
736 type BreakValue = Never;
737
738 fn hir(&self) -> &'gcx hir::Hir<'gcx> {
739 &self.gcx.hir
740 }
741
742 fn visit_expr(&mut self, expr: &'gcx hir::Expr<'gcx>) -> ControlFlow<Self::BreakValue> {
743 if let Some((callee, args, _)) = expr.as_call()
744 && args.is_empty()
745 && let Some(hir::Res::Item(hir::ItemId::Error(error))) = self.gcx.resolved_expr(callee)
746 {
747 let selector = self.gcx.function_selector(error).0;
748 for guard in &self.revert_guards {
749 if guard.call != expr.span {
750 continue;
751 }
752 for (id, item) in self.items.iter().enumerate() {
753 if item.loc.contract_name == guard.body.contract_name
754 && (item.loc.bytes == guard.body.bytes
755 || (item.loc.bytes == guard.statement.bytes
756 && matches!(
757 item.kind,
758 CoverageItemKind::Branch { path_id: 0, .. }
759 )))
760 {
761 self.anchor_hints.entry(id).or_default().revert_guard = Some(RevertGuard {
762 condition: guard.condition.clone(),
763 statement: guard.statement.clone(),
764 function: guard.function.clone(),
765 selector,
766 });
767 }
768 }
769 }
770 }
771 if let hir::ExprKind::Call(lhs, ..) = &expr.kind
772 && is_regular_call(lhs)
773 && let Some(scope) = self.function_call_scopes.get(&expr.span).cloned()
774 {
775 let prev = std::mem::replace(&mut self.contract_name, scope);
778 self.push_stmt(expr.span);
779 self.contract_name = prev;
780 self.push_callees(expr, lhs);
781 }
782 self.walk_expr(expr)
783 }
784}
785
786fn is_regular_call(lhs: &hir::Expr<'_>) -> bool {
789 match lhs.peel_parens().kind {
790 hir::ExprKind::Ident([hir::Res::Item(hir::ItemId::Struct(_))]) => false,
792 hir::ExprKind::Type(_) => false,
794 _ => true,
795 }
796}
797
798fn storage_alias_body(function: &ast::ItemFunction<'_>) -> bool {
801 if !matches!(
802 function.header.visibility(),
803 Some(ast::Visibility::Internal | ast::Visibility::Private)
804 ) || !function.header.modifiers.is_empty()
805 || function.header.returns().is_empty()
806 || !function.header.returns().iter().all(|parameter| {
807 parameter.name.is_some() && parameter.data_location == Some(ast::DataLocation::Storage)
808 })
809 {
810 return false;
811 }
812 let Some(body) = &function.body else { return false };
813 !body.is_empty()
814 && body.iter().all(|statement| match &statement.kind {
815 StmtKind::DeclSingle(variable) => {
816 variable.initializer.as_ref().is_some_and(|initializer| {
817 matches!(initializer.peel_parens().kind, ExprKind::Ident(_) | ExprKind::Lit(..))
818 })
819 }
820 StmtKind::Assembly(assembly) => assembly.block.iter().all(|statement| {
821 let yul::StmtKind::AssignSingle(path, value) = &statement.kind else {
822 return false;
823 };
824 let [name, suffix] = path.segments() else { return false };
825 suffix.name == sym::slot
826 && function
827 .header
828 .returns()
829 .iter()
830 .any(|parameter| parameter.name.is_some_and(|id| id.name == name.name))
831 && matches!(value.kind, yul::ExprKind::Path(_) | yul::ExprKind::Lit(_))
832 }),
833 _ => false,
834 })
835}
836
837fn has_statements(block: Option<&ast::Block<'_>>) -> bool {
838 block.is_some_and(|block| !block.is_empty())
839}
840
841fn stmt_has_statements(stmt: &ast::Stmt<'_>) -> bool {
842 match &stmt.kind {
843 StmtKind::Assembly(a) => !a.block.is_empty(),
844 StmtKind::Block(b) | StmtKind::UncheckedBlock(b) => has_statements(Some(b)),
845 _ => true,
846 }
847}
848
849#[derive(Clone, Debug, Default)]
851pub struct SourceAnalysis {
852 all_items: Vec<CoverageItem>,
854 anchor_hints: HashMap<u32, AnchorHints>,
856 branch_kinds: HashMap<(u32, u32), BranchKind>,
858 map: Vec<(u32, u32)>,
860 empty_special_functions: HashMap<u32, EmptySpecialFunctionKind>,
862 contract_empty_special_functions: HashMap<u32, HashMap<Arc<str>, Vec<u32>>>,
864}
865
866impl SourceAnalysis {
867 #[instrument(name = "SourceAnalysis::new", skip_all)]
881 pub fn new(data: &SourceFiles, output: &ProjectCompileOutput) -> eyre::Result<Self> {
882 let mut resolved_empty_special_functions = Vec::new();
883 let mut sourced_items = output.parser().solc().compiler().enter(|compiler| {
884 let hir_source_ids = Arc::new(
885 data.sources
886 .iter()
887 .map(|(&source_id, path)| {
888 let (hir_source_id, _) = compiler.gcx().get_hir_source(path).unwrap();
889 (hir_source_id, source_id)
890 })
891 .collect::<HashMap<_, _>>(),
892 );
893 resolved_empty_special_functions =
894 resolve_empty_special_functions(compiler.gcx(), &hir_source_ids);
895 data.sources
896 .par_iter()
897 .map(|(&source_id, path)| {
898 let _guard = debug_span!("SourceAnalysis::new::visit", ?path).entered();
899
900 let (_, source) = compiler.gcx().get_ast_source(path).unwrap();
901 let ast = source.ast.as_ref().unwrap();
902 let (hir_source_id, _) = compiler.gcx().get_hir_source(path).unwrap();
903
904 let mut visitor =
905 SourceVisitor::new(source_id, compiler.gcx(), hir_source_ids.clone());
906 for item in ast.items.iter() {
907 match &item.kind {
908 ItemKind::Contract(contract) => {
910 if contract.kind.is_interface() {
912 continue;
913 }
914
915 let checkpoint = visitor.checkpoint();
916 visitor.visit_contract(contract);
917 if visitor.has_tests(&checkpoint) {
918 visitor.restore_checkpoint(checkpoint);
919 }
920 }
921 ItemKind::Function(_) => {
925 visitor.contract_name = Arc::default();
929 let _ = ast::Visit::visit_item(&mut visitor, item);
930 }
931 _ => {}
932 }
933 }
934
935 if !visitor.function_calls.is_empty() || !visitor.revert_guards.is_empty() {
936 visitor.resolve_function_calls(hir_source_id);
937 }
938
939 if !visitor.items.is_empty() {
940 visitor.disambiguate_functions();
941 visitor.sort();
942 visitor.push_lines();
943 visitor.sort();
944 }
945 (source_id, visitor.items, visitor.anchor_hints, visitor.branch_kinds)
946 })
947 .collect::<Vec<_>>()
948 });
949
950 sourced_items
952 .sort_by_key(|(id, items, _, _)| (*id, items.first().map(|i| i.loc.bytes.start)));
953 let Some(&(max_idx, _, _, _)) = sourced_items.last() else { return Ok(Self::default()) };
954 let len = max_idx + 1;
955 let mut all_items = Vec::new();
956 let mut anchor_hints = HashMap::default();
957 let mut map = vec![(u32::MAX, 0); len as usize];
958 let mut branch_kinds = HashMap::default();
959 for (idx, items, hints, branches) in sourced_items {
960 let base = all_items.len() as u32;
961 anchor_hints.extend(hints.into_iter().map(|(id, hint)| (base + id as u32, hint)));
962 branch_kinds.extend(branches.into_iter().map(|(branch, kind)| ((idx, branch), kind)));
963 let idx = idx as usize;
965 if map[idx].0 == u32::MAX {
966 map[idx].0 = all_items.len() as u32;
967 }
968 map[idx].1 += items.len() as u32;
969 all_items.extend(items);
970 }
971
972 let mut empty_special_functions = HashMap::default();
973 let mut contract_empty_special_functions =
974 HashMap::<u32, HashMap<Arc<str>, Vec<u32>>>::default();
975 for resolved in resolved_empty_special_functions {
976 let item_ids = all_items
977 .iter()
978 .enumerate()
979 .filter(|(_, item)| {
980 item.loc.source_id == resolved.function_source_id as usize
981 && item.loc.contract_name == resolved.function_contract_name
982 && item.loc.bytes == resolved.function_bytes
983 })
984 .map(|(item_id, _)| item_id as u32)
985 .collect::<Vec<_>>();
986 empty_special_functions
987 .extend(item_ids.iter().map(|&item_id| (item_id, resolved.kind)));
988 contract_empty_special_functions
989 .entry(resolved.contract_source_id)
990 .or_default()
991 .entry(resolved.contract_name)
992 .or_default()
993 .extend(item_ids);
994 }
995
996 Ok(Self {
997 all_items,
998 anchor_hints,
999 map,
1000 branch_kinds,
1001 empty_special_functions,
1002 contract_empty_special_functions,
1003 })
1004 }
1005
1006 pub(crate) fn anchor_hints(&self, item_id: u32) -> Option<&AnchorHints> {
1007 self.anchor_hints.get(&item_id)
1008 }
1009
1010 pub(crate) fn branch_kind(&self, source_id: u32, branch_id: u32) -> Option<&BranchKind> {
1011 self.branch_kinds.get(&(source_id, branch_id))
1012 }
1013
1014 pub fn all_items(&self) -> &[CoverageItem] {
1016 &self.all_items
1017 }
1018
1019 pub const fn all_items_mut(&mut self) -> &mut Vec<CoverageItem> {
1021 &mut self.all_items
1022 }
1023
1024 pub fn items_for_source_enumerated(
1026 &self,
1027 source_id: u32,
1028 ) -> impl Iterator<Item = (u32, &CoverageItem)> {
1029 let (base_id, items) = self.items_for_source(source_id);
1030 items.iter().enumerate().map(move |(idx, item)| (base_id + idx as u32, item))
1031 }
1032
1033 pub fn items_for_source(&self, source_id: u32) -> (u32, &[CoverageItem]) {
1035 let (mut offset, len) = self.map.get(source_id as usize).copied().unwrap_or_default();
1036 if offset == u32::MAX {
1037 offset = 0;
1038 }
1039 (offset, &self.all_items[offset as usize..][..len as usize])
1040 }
1041
1042 #[inline]
1044 pub fn get(&self, item_id: u32) -> Option<&CoverageItem> {
1045 self.all_items.get(item_id as usize)
1046 }
1047
1048 pub(crate) fn empty_special_function_kind(
1049 &self,
1050 item_id: u32,
1051 ) -> Option<EmptySpecialFunctionKind> {
1052 self.empty_special_functions.get(&item_id).copied()
1053 }
1054
1055 pub(crate) fn empty_special_function_ids(
1056 &self,
1057 source_id: u32,
1058 contract_name: &str,
1059 ) -> impl Iterator<Item = u32> + '_ {
1060 self.contract_empty_special_functions
1061 .get(&source_id)
1062 .and_then(|contracts| contracts.get(contract_name))
1063 .into_iter()
1064 .flatten()
1065 .copied()
1066 }
1067
1068 #[cfg(test)]
1070 pub(crate) fn for_test(items: Vec<CoverageItem>, branch_kinds: Vec<(u32, BranchKind)>) -> Self {
1071 Self {
1072 map: vec![(0, items.len() as u32)],
1073 all_items: items,
1074 branch_kinds: branch_kinds.into_iter().map(|(id, kind)| ((0, id), kind)).collect(),
1075 ..Default::default()
1076 }
1077 }
1078}
1079
1080#[derive(Default)]
1082pub struct SourceFiles {
1083 pub sources: HashMap<u32, PathBuf>,
1085}
1086
1087#[cfg(test)]
1088mod tests {
1089 use super::*;
1090 use evm2::interpreter::op as opcode;
1091 use foundry_compilers::artifacts::sourcemap;
1092 use foundry_evm_core::ic::IcPcMap;
1093
1094 fn item(start: u32, line: u32) -> CoverageItem {
1095 CoverageItem {
1096 kind: CoverageItemKind::Statement,
1097 loc: SourceLocation {
1098 source_id: 0,
1099 contract_name: "T".into(),
1100 bytes: start..start + 1,
1101 lines: line..line + 1,
1102 },
1103 anchor_loc: None,
1104 hits: 0,
1105 }
1106 }
1107
1108 #[test]
1109 fn hints_follow_sorting_lines_and_checkpoint_reuse() {
1110 let session = solar::interface::Session::builder()
1111 .with_buffer_emitter(solar::interface::ColorChoice::Never)
1112 .build();
1113 let compiler = solar::sema::Compiler::new(session);
1114 compiler.enter(|compiler| {
1115 let mut visitor = SourceVisitor::new(0, compiler.gcx(), Default::default());
1116 visitor.items = vec![item(30, 3), item(10, 1), item(20, 2)];
1117 visitor.all_lines = vec![3, 1, 2];
1118 visitor.anchor_hints.insert(
1119 0,
1120 AnchorHints { alias_function: Some(item(30, 3).loc), ..Default::default() },
1121 );
1122 visitor.anchor_hints.insert(
1123 2,
1124 AnchorHints {
1125 revert_guard: Some(RevertGuard {
1126 condition: item(20, 2).loc,
1127 statement: item(20, 2).loc,
1128 function: item(20, 2).loc,
1129 selector: [1, 2, 3, 4],
1130 }),
1131 ..Default::default()
1132 },
1133 );
1134 visitor.sort();
1135 visitor.push_lines();
1136 visitor.sort();
1137 assert_eq!(visitor.items.len(), 6);
1138 assert_eq!(visitor.anchor_hints.len(), 4);
1139 for (id, covered) in visitor.items.iter().enumerate() {
1140 match covered.loc.bytes.start {
1141 10 => assert!(!visitor.anchor_hints.contains_key(&id)),
1142 20 => assert_eq!(
1143 visitor.anchor_hints[&id].revert_guard.as_ref().unwrap().condition.bytes,
1144 covered.loc.bytes
1145 ),
1146 30 => assert_eq!(
1147 visitor.anchor_hints[&id].alias_function.as_ref().unwrap().bytes,
1148 covered.loc.bytes
1149 ),
1150 _ => unreachable!(),
1151 }
1152 }
1153 let checkpoint = visitor.checkpoint();
1155 let reused = visitor.items.len();
1156 visitor.items.push(item(40, 4));
1157 visitor.anchor_hints.insert(
1158 reused,
1159 AnchorHints { alias_function: Some(item(40, 4).loc), ..Default::default() },
1160 );
1161 visitor.restore_checkpoint(checkpoint);
1162 visitor.items.push(item(50, 5));
1163 assert!(!visitor.anchor_hints.contains_key(&reused));
1164 visitor.sort();
1165 assert_eq!(visitor.anchor_hints.len(), 4);
1166 });
1167 }
1168
1169 #[test]
1170 fn codeless_if_keeps_shared_revert_recovery() {
1171 let location = |bytes| SourceLocation { bytes, ..item(0, 1).loc };
1172 let statement = location(10..40);
1173 let mut analysis = SourceAnalysis {
1174 all_items: vec![CoverageItem {
1175 kind: CoverageItemKind::Branch { branch_id: 0, path_id: 0, is_first_opcode: false },
1176 loc: statement.clone(),
1177 anchor_loc: None,
1178 hits: 0,
1179 }],
1180 branch_kinds: [(
1181 (0, 0),
1182 BranchKind::If(IfArms {
1183 then_arm: location(30..40),
1184 else_arm: None,
1185 after: None,
1187 then_callees: vec![],
1188 else_callees: vec![],
1189 }),
1190 )]
1191 .into_iter()
1192 .collect(),
1193 anchor_hints: [(
1194 0,
1195 AnchorHints {
1196 revert_guard: Some(RevertGuard {
1197 condition: location(10..20),
1198 statement,
1199 function: location(0..100),
1200 selector: [0xe3, 0x37, 0x2e, 0x2d],
1201 }),
1202 ..Default::default()
1203 },
1204 )]
1205 .into_iter()
1206 .collect(),
1207 map: vec![(0, 1)],
1208 ..Default::default()
1209 };
1210 let bytecode = [
1211 opcode::PUSH0,
1212 opcode::ISZERO,
1213 opcode::PUSH1,
1214 7,
1215 opcode::JUMPI,
1216 opcode::POP,
1217 opcode::STOP,
1218 opcode::JUMPDEST,
1219 opcode::PUSH4,
1220 0xe3,
1221 0x37,
1222 0x2e,
1223 0x2d,
1224 opcode::PUSH0,
1225 opcode::MSTORE,
1226 opcode::PUSH1,
1227 4,
1228 opcode::PUSH1,
1229 28,
1230 opcode::REVERT,
1231 ];
1232 let source_map = sourcemap::parse("10:10:0;;;;50:10:0;-1:-1:-1;;;;;;;;").unwrap();
1233 let ic_pc_map = IcPcMap::new(&bytecode);
1234 let anchors = crate::anchors::find_anchors(&bytecode, &source_map, &ic_pc_map, &analysis);
1235 assert_eq!(anchors.anchors.len(), 1);
1236 assert_eq!(anchors.anchors[0].instruction, 7);
1237 assert_eq!(anchors.jumps.get(&0), Some(&4));
1238
1239 analysis.anchor_hints.clear();
1240 let anchors = crate::anchors::find_anchors(&bytecode, &source_map, &ic_pc_map, &analysis);
1241 assert!(
1242 anchors.anchors.is_empty(),
1243 "an ambiguous arm without recovery evidence stays unanchored"
1244 );
1245 }
1246}