Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Documentation/Changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## Unreleased

### Improvements

- Add `IsReachable` to branch points, computed from the method's control-flow graph, and exclude unreachable branches from branch-coverage totals and from branch details in Cobertura, LCOV and OpenCover reports (follow-up to [#2047](https://github.com/coverlet-coverage/coverlet/pull/2047))

## Release date 2026-09-27
### Packages
coverlet.msbuild 10.1.0
Expand Down
8 changes: 4 additions & 4 deletions src/coverlet.core/Coverage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -256,14 +256,14 @@ public CoverageResult GetCoverageResult()
if (methods.TryGetValue(branch.Method, out Method method))
{
method.Branches.Add(new BranchInfo
{ Line = branch.Number, Hits = branch.Hits, Offset = branch.Offset, EndOffset = branch.EndOffset, Path = branch.Path, Ordinal = branch.Ordinal }
{ Line = branch.Number, Hits = branch.Hits, Offset = branch.Offset, EndOffset = branch.EndOffset, Path = branch.Path, Ordinal = branch.Ordinal, IsReachable = branch.IsReachable }
);
}
else
{
documents[doc.Path][branch.Class].Add(branch.Method, new Method());
documents[doc.Path][branch.Class][branch.Method].Branches.Add(new BranchInfo
{ Line = branch.Number, Hits = branch.Hits, Offset = branch.Offset, EndOffset = branch.EndOffset, Path = branch.Path, Ordinal = branch.Ordinal }
{ Line = branch.Number, Hits = branch.Hits, Offset = branch.Offset, EndOffset = branch.EndOffset, Path = branch.Path, Ordinal = branch.Ordinal, IsReachable = branch.IsReachable }
);
}
}
Expand All @@ -272,7 +272,7 @@ public CoverageResult GetCoverageResult()
documents[doc.Path].Add(branch.Class, []);
documents[doc.Path][branch.Class].Add(branch.Method, new Method());
documents[doc.Path][branch.Class][branch.Method].Branches.Add(new BranchInfo
{ Line = branch.Number, Hits = branch.Hits, Offset = branch.Offset, EndOffset = branch.EndOffset, Path = branch.Path, Ordinal = branch.Ordinal }
{ Line = branch.Number, Hits = branch.Hits, Offset = branch.Offset, EndOffset = branch.EndOffset, Path = branch.Path, Ordinal = branch.Ordinal, IsReachable = branch.IsReachable }
);
}
}
Expand All @@ -282,7 +282,7 @@ public CoverageResult GetCoverageResult()
documents[doc.Path].Add(branch.Class, []);
documents[doc.Path][branch.Class].Add(branch.Method, new Method());
documents[doc.Path][branch.Class][branch.Method].Branches.Add(new BranchInfo
{ Line = branch.Number, Hits = branch.Hits, Offset = branch.Offset, EndOffset = branch.EndOffset, Path = branch.Path, Ordinal = branch.Ordinal }
{ Line = branch.Number, Hits = branch.Hits, Offset = branch.Offset, EndOffset = branch.EndOffset, Path = branch.Path, Ordinal = branch.Ordinal, IsReachable = branch.IsReachable }
);
}
}
Expand Down
7 changes: 7 additions & 0 deletions src/coverlet.core/CoverageResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ internal class BranchInfo
public int Path { get; set; }
public uint Ordinal { get; set; }
public int Hits { get; set; }

/// <summary>
/// Indicates whether this branch can be reached from the method entry.
/// Unreachable branches are not counted in branch coverage.
/// Default value: true (assume all branches are reachable unless proven otherwise)
/// </summary>
public bool IsReachable { get; set; } = true;
}
internal class Lines : SortedDictionary<int, int> { }
internal class Branches : List<BranchInfo> { }
Expand Down
7 changes: 5 additions & 2 deletions src/coverlet.core/CoverageSummary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,13 @@ public static CoverageDetails CalculateLineCoverage(Modules modules)

public static CoverageDetails CalculateBranchCoverage(IList<BranchInfo> branches)
{
// Unreachable branches cannot be covered, so they do not count against coverage
var reachableBranches = branches.Where(b => b.IsReachable).ToList();

var details = new CoverageDetails
{
Covered = branches.Count(bi => bi.Hits > 0),
Total = branches.Count
Covered = reachableBranches.Count(bi => bi.Hits > 0),
Total = reachableBranches.Count
};
return details;
}
Expand Down
6 changes: 4 additions & 2 deletions src/coverlet.core/Instrumentation/Instrumenter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1039,7 +1039,8 @@ private Instruction AddInstrumentationCode(MethodDefinition method, ILProcessor
Offset = branchPoint.Offset,
EndOffset = branchPoint.EndOffset,
Path = branchPoint.Path,
Ordinal = branchPoint.Ordinal
Ordinal = branchPoint.Ordinal,
IsReachable = branchPoint.IsReachable
}
);

Expand Down Expand Up @@ -1111,7 +1112,8 @@ private Instruction AddBranchTrampolineCode(MethodDefinition method, ILProcessor
Offset = branchPoint.Offset,
EndOffset = branchPoint.EndOffset,
Path = branchPoint.Path,
Ordinal = branchPoint.Ordinal
Ordinal = branchPoint.Ordinal,
IsReachable = branchPoint.IsReachable
}
);

Expand Down
7 changes: 7 additions & 0 deletions src/coverlet.core/Instrumentation/InstrumenterResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@ internal class Branch : Line
public int Path;
[DataMember]
public uint Ordinal;
[DataMember]
public bool IsReachable = true;

// DataContractSerializer does not run field initializers, so without this a state file
// written before IsReachable existed would read back with every branch unreachable
[OnDeserializing]
private void OnDeserializing(StreamingContext context) => IsReachable = true;
}

[DebuggerDisplay("line = {Line} Ordinal = {Ordinal}")]
Expand Down
4 changes: 2 additions & 2 deletions src/coverlet.core/Reporters/CoberturaReporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,15 +93,15 @@ public string Report(CoverageResult result, ISourceRootTranslator sourceRootTran
var lines = new XElement("lines");
foreach (KeyValuePair<int, int> ln in meth.Value.Lines)
{
bool isBranchPoint = meth.Value.Branches.Any(b => b.Line == ln.Key);
bool isBranchPoint = meth.Value.Branches.Any(b => b.Line == ln.Key && b.IsReachable);
var line = new XElement("line");
line.Add(new XAttribute("number", ln.Key.ToString()));
line.Add(new XAttribute("hits", ln.Value.ToString()));
line.Add(new XAttribute("branch", isBranchPoint.ToString()));

if (isBranchPoint)
{
var branches = meth.Value.Branches.Where(b => b.Line == ln.Key).ToList();
var branches = meth.Value.Branches.Where(b => b.Line == ln.Key && b.IsReachable).ToList();
CoverageDetails branchInfoCoverage = CoverageSummary.CalculateBranchCoverage(branches);
line.Add(new XAttribute("condition-coverage", $"{branchInfoCoverage.Percent.ToString(CultureInfo.InvariantCulture)}% ({branchInfoCoverage.Covered.ToString(CultureInfo.InvariantCulture)}/{branchInfoCoverage.Total.ToString(CultureInfo.InvariantCulture)})"));
var conditions = new XElement("conditions");
Expand Down
2 changes: 1 addition & 1 deletion src/coverlet.core/Reporters/LcovReporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public string Report(CoverageResult result, ISourceRootTranslator sourceRootTran
foreach (KeyValuePair<int, int> line in method.Value.Lines)
lcov.Add($"DA:{line.Key},{line.Value}");

foreach (BranchInfo branch in method.Value.Branches)
foreach (BranchInfo branch in method.Value.Branches.Where(b => b.IsReachable))
{
lcov.Add($"BRDA:{branch.Line},{branch.Offset},{branch.Path},{branch.Hits}");
}
Expand Down
2 changes: 1 addition & 1 deletion src/coverlet.core/Reporters/OpenCoverReporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ public string Report(CoverageResult result, ISourceRootTranslator sourceRootTran
k++;
}

foreach (BranchInfo branche in meth.Value.Branches)
foreach (BranchInfo branche in meth.Value.Branches.Where(b => b.IsReachable))
{
var branchPoint = new XElement("BranchPoint");
branchPoint.Add(new XAttribute("vc", branche.Hits.ToString()));
Expand Down
8 changes: 8 additions & 0 deletions src/coverlet.core/Symbols/BranchPoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,5 +47,13 @@ internal class BranchPoint
/// The url to the document if an entry was not mapped to an id
/// </summary>
public string Document { get; set; }

/// <summary>
/// Indicates whether this branch path can be reached from the method entry.
/// A path is reachable when its branching instruction is reachable in the
/// method's control-flow graph, including through exception handlers.
/// Default value: true (branch is considered reachable unless proven otherwise)
/// </summary>
public bool IsReachable { get; set; } = true;
}
}
100 changes: 95 additions & 5 deletions src/coverlet.core/Symbols/CecilSymbolHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1019,6 +1019,91 @@ private static bool SkipExpressionBreakpointsBranches(Instruction instruction) =
instruction.Next is not null && instruction.Next.OpCode == OpCodes.Nop &&
instruction.Operand == instruction.Next?.Next;

/// <summary>
/// Computes the instructions reachable from the method entry using control-flow edges:
/// branch targets, the next instruction unless control transfers unconditionally
/// (br, leave, ret, jmp, throw, rethrow, endfinally, endfilter), and the filter and handler
/// entries of every exception handler whose try block is reachable.
/// </summary>
/// <param name="body">Method body to analyze.</param>
/// <returns>Set of reachable instructions.</returns>
private static HashSet<Instruction> ComputeReachableInstructions(MethodBody body)
{
var reached = new HashSet<Instruction>();
if (body.Instructions.Count == 0)
{
return reached;
}

var work = new Stack<Instruction>();

void Visit(Instruction instruction)
{
if (instruction is not null && reached.Add(instruction))
{
work.Push(instruction);
}
}

Visit(body.Instructions[0]);

bool grew = true;
while (grew)
{
while (work.Count > 0)
{
Instruction instruction = work.Pop();
switch (instruction.OpCode.FlowControl)
{
case FlowControl.Branch:
Visit(instruction.Operand as Instruction);
break;
case FlowControl.Cond_Branch:
if (instruction.Operand is Instruction conditionalTarget)
{
Visit(conditionalTarget);
}
else if (instruction.Operand is Instruction[] switchTargets)
{
foreach (Instruction switchTarget in switchTargets)
{
Visit(switchTarget);
}
}

Visit(instruction.Next);
break;
case FlowControl.Return:
case FlowControl.Throw:
break;
case FlowControl.Call when instruction.OpCode.Code == Code.Jmp:
// jmp leaves the method; Cecil classifies it as a call
break;
default:
Visit(instruction.Next);
break;
}
}

// Handlers are entered from their try block, not by a branch
grew = false;
foreach (ExceptionHandler exceptionHandler in body.ExceptionHandlers)
{
if (!reached.Contains(exceptionHandler.TryStart))
{
continue;
}

int before = reached.Count;
Visit(exceptionHandler.FilterStart);
Visit(exceptionHandler.HandlerStart);
grew |= reached.Count != before;
}
}

return reached;
}

public IReadOnlyList<BranchPoint> GetBranchPoints(MethodDefinition methodDefinition)
{
var list = new List<BranchPoint>();
Expand All @@ -1029,6 +1114,7 @@ public IReadOnlyList<BranchPoint> GetBranchPoints(MethodDefinition methodDefinit

uint ordinal = 0;
var instructions = methodDefinition.Body.Instructions.ToList();
HashSet<Instruction> reachableInstructions = ComputeReachableInstructions(methodDefinition.Body);

bool isAsyncStateMachineMoveNext = IsMoveNextInsideAsyncStateMachine(methodDefinition);
bool isMoveNextInsideAsyncStateMachineProlog = isAsyncStateMachineMoveNext && IsMoveNextInsideAsyncStateMachineProlog(methodDefinition);
Expand Down Expand Up @@ -1134,7 +1220,7 @@ public IReadOnlyList<BranchPoint> GetBranchPoints(MethodDefinition methodDefinit
return list;
}

if (!BuildPointsForConditionalBranch(list, instruction, branchingInstructionLine, document, branchOffset, pathCounter, instructions, ref ordinal, methodDefinition))
if (!BuildPointsForConditionalBranch(list, instruction, branchingInstructionLine, document, branchOffset, pathCounter, instructions, ref ordinal, methodDefinition, reachableInstructions.Contains(instruction)))
{
return list;
}
Expand All @@ -1149,7 +1235,7 @@ public IReadOnlyList<BranchPoint> GetBranchPoints(MethodDefinition methodDefinit

private static bool BuildPointsForConditionalBranch(List<BranchPoint> list, Instruction instruction,
int branchingInstructionLine, string document, int branchOffset, int pathCounter,
List<Instruction> instructions, ref uint ordinal, MethodDefinition methodDefinition)
List<Instruction> instructions, ref uint ordinal, MethodDefinition methodDefinition, bool branchInstructionReachable)
{
// Add Default branch (Path=0)

Expand All @@ -1170,7 +1256,9 @@ private static bool BuildPointsForConditionalBranch(List<BranchPoint> list, Inst
pathOffsetList.Count > 1
? pathOffsetList.GetRange(0, pathOffsetList.Count - 1)
: [],
EndOffset = pathOffsetList.Last()
EndOffset = pathOffsetList.Last(),
// Every path of a branch is reachable exactly when the branch instruction is reachable
IsReachable = branchInstructionReachable
};

// Add Conditional Branch (Path=1)
Expand Down Expand Up @@ -1211,7 +1299,8 @@ private static uint BuildPointsForBranch(List<BranchPoint> list, Instruction the
pathOffsetList1.Count > 1
? pathOffsetList1.GetRange(0, pathOffsetList1.Count - 1)
: [],
EndOffset = pathOffsetList1.Last()
EndOffset = pathOffsetList1.Last(),
IsReachable = path0.IsReachable
};

// only add branch if branch does not match a known sequence
Expand Down Expand Up @@ -1269,7 +1358,8 @@ private static uint BuildPointsForSwitchCases(List<BranchPoint> list, BranchPoin
pathOffsetList1.Count > 1
? pathOffsetList1.GetRange(0, pathOffsetList1.Count - 1)
: [],
EndOffset = pathOffsetList1.Last()
EndOffset = pathOffsetList1.Last(),
IsReachable = path0.IsReachable
}));
pathCounter = counter;
return ordinal;
Expand Down
Loading
Loading