1import Foundation
2
3/// The coverage of every source file in one `llvm-cov export -format=text` run.
4///
5/// Reads format version 3 (LLVM 12 and later). Only the parts the report uses are
6/// decoded. Of llvm-cov's own summaries that is just the region counts: its line
7/// counts add up lines per function, so a line holding a closure counts twice.
8public struct CoverageExport: Sendable {
9 public let files: [FileCoverage]
10
11 /// Decodes an export.
12 ///
13 /// - Throws: `CoverageExportError` when the JSON isn't a version 3 llvm-cov export
14 /// holding exactly one set of files, or `DecodingError` when it is malformed.
1545 public init(json: Data) throws {
1645 let decoder = JSONDecoder()
1745 let format = try decoder.decode(Format.self, from: json)
1845 guard format.type == "llvm.coverage.json.export", format.version.hasPrefix("3.") else {
192 throw CoverageExportError.unsupportedFormat(type: format.type, version: format.version)
2043 }
2143 let contents = try decoder.decode(Contents.self, from: json)
2241 guard contents.data.count == 1 else {
231 throw CoverageExportError.unexpectedDataCount(contents.data.count)
2440 }
2540 files = contents.data[0].files
2640 }
27
28 /// Read on its own first, so an export of another version fails on its version
29 /// instead of on whichever field changed shape.
30 private struct Format: Decodable {
31 let type: String
32 let version: String
33 }
34
35 private struct Contents: Decodable {
36 struct Entry: Decodable {
37 let files: [FileCoverage]
38 }
39 let data: [Entry]
40 }
41}
42
43public enum CoverageExportError: Error, Equatable {
44 case unsupportedFormat(type: String, version: String)
45 /// llvm-cov writes one entry per export; more would mean a merged or unknown file.
46 case unexpectedDataCount(Int)
47}
48
49/// One source file's coverage as llvm-cov reports it.
50public struct FileCoverage: Sendable, Decodable {
51 /// The absolute path llvm-cov recorded at build time.
52 public let path: String
53 /// Ordered by line, then column.
54 public let segments: [CoverageSegment]
55 /// Empty for Swift, which llvm-cov exports no branch data for.
56 public let branches: [BranchRegion]
57 /// Empty unless the code was built with clang's `-fcoverage-mcdc`.
58 public let conditionRecords: [ConditionRecord]
59 /// Covered of all regions, as llvm-cov's summary of the file counts them; nil when
60 /// the export gives no summary or the file has no regions.
61 public let regionCount: CoverageCount?
62
63 private enum CodingKeys: String, CodingKey {
64 case path = "filename"
65 case segments
66 case branches
67 case conditionRecords = "mcdc_records"
68 case summary
69 }
70
71 /// The part of a file's `summary` the report uses.
72 private struct Summary: Decodable {
73 struct Regions: Decodable {
74 let count: Int
75 let covered: Int
76 }
77 let regions: Regions
78 }
79
80 /// The branch keys and the summary may be missing; the file then has no such data.
8178 public init(from decoder: any Decoder) throws {
8278 let values = try decoder.container(keyedBy: CodingKeys.self)
8378 path = try values.decode(String.self, forKey: .path)
8478 segments = try values.decode([CoverageSegment].self, forKey: .segments)
8577 branches = try values.decodeIfPresent([BranchRegion].self, forKey: .branches) ?? []
8677 conditionRecords =
8777 try values.decodeIfPresent([ConditionRecord].self, forKey: .conditionRecords) ?? []
8877 let regions = try values.decodeIfPresent(Summary.self, forKey: .summary)?.regions
8976 regionCount = regions.flatMap {
9018 $0.count == 0 ? nil : CoverageCount(total: $0.count, covered: $0.covered)
9118 }
9276 }
93}
94
95/// A point in a file where the active coverage region changes.
96///
97/// The region that starts here runs until the next segment. Encoded by llvm-cov as
98/// `[line, column, count, hasCount, isRegionEntry, isGapRegion]`.
99public struct CoverageSegment: Sendable, Equatable {
100 public let line: Int
101 /// 1-based.
102 public let column: Int
103 public let count: UInt64
104 /// False for code the compiler skipped (for example an inactive `#if` branch).
105 public let hasCount: Bool
106 /// True when a region starts here; false when an enclosing region resumes.
107 public let isRegionEntry: Bool
108 /// True for the whitespace between regions, which never counts as code.
109 public let isGapRegion: Bool
110
111 public init(
112 line: Int, column: Int, count: UInt64, hasCount: Bool = true,
113 isRegionEntry: Bool = true, isGapRegion: Bool = false
114321 ) {
115321 self.line = line
116321 self.column = column
117321 self.count = count
118321 self.hasCount = hasCount
119321 self.isRegionEntry = isRegionEntry
120321 self.isGapRegion = isGapRegion
121321 }
122}
123
124extension CoverageSegment: Decodable {
125301 public init(from decoder: any Decoder) throws {
126301 var fields = try decoder.unkeyedContainer()
127301 self.init(
128301 line: try fields.decode(Int.self),
129301 column: try fields.decode(Int.self),
130301 count: try fields.decode(UInt64.self),
131301 hasCount: try fields.decode(Bool.self),
132300 isRegionEntry: try fields.decode(Bool.self),
133300 isGapRegion: try fields.decode(Bool.self)
134300 )
135300 }
136}