Skip to content

[APIDiff] Improve API digester integration & polish of experimental-api-diff #3485

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
merged 22 commits into from
May 27, 2021
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
fd3e92d
[APIDiff] Parse serialized diagnostics from API digester to different…
owenv May 8, 2021
8d6b0f6
[APIDiff] Refactoring and documentation to make the diffing process e…
owenv May 8, 2021
80b8864
[APIDiff] Diff and print results from one module at a time
owenv May 8, 2021
1f5a34b
[APIDiff] Improve test coverage
owenv May 8, 2021
125818f
[APIDiff] Use per-module baselines
owenv May 8, 2021
ba89eaa
[APIDiff] Only diagnose API breakage in modules vended by library pro…
owenv May 8, 2021
3a421a4
[APIDiff] Add a test case involving a C-family target
owenv May 8, 2021
5c1e2db
[APIDiff] Print a message if a module has no breaking changes
owenv May 8, 2021
fbeb00a
[APIDiff] Skip comparison of modules which aren't present in the base…
owenv May 8, 2021
1407c66
[APIDiff] Refactor API digester tool to accept a BuildPlan instead of…
owenv May 8, 2021
7bbf999
[APIDiff] Remove an option-parsing hack that's no longer needed
owenv May 8, 2021
3557105
[APIDiff] Improve failure diagnostics
owenv May 8, 2021
5415614
[APIDiff] Remove an obsolete test
owenv May 8, 2021
2738aa0
[APIDiff] Adapt to a TSC API change
owenv May 9, 2021
2457b7d
[APIDiff] Rename SwiftAPIDigester.ComparisonResult.isSuccessful -> Sw…
owenv May 16, 2021
81b4d2d
[APIDiff] Allow restricting the diff to specific products and/or targets
owenv May 22, 2021
59f13f9
[APIDiff] Improve subcommand help
owenv May 22, 2021
cd88df0
[APIDiff] Parallelize diff operation
owenv May 22, 2021
3f07326
[APIDiff] Parallelize baseline generation
owenv May 22, 2021
e45725d
[APIDiff] Clarify filtering options
owenv May 26, 2021
9167479
[APIDiff] Control paralellism of api-digester invocations with -j
owenv May 26, 2021
cc0bdf4
Update help text
owenv May 26, 2021
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
14 changes: 14 additions & 0 deletions Fixtures/Miscellaneous/APIDiff/Bar/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// swift-tools-version:4.2
import PackageDescription

let package = Package(
name: "Bar",
products: [
.library(name: "Baz", targets: ["Baz"]),
.library(name: "Qux", targets: ["Qux"]),
],
targets: [
.target(name: "Baz"),
.target(name: "Qux")
]
)
3 changes: 3 additions & 0 deletions Fixtures/Miscellaneous/APIDiff/Bar/Sources/Baz/Baz.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
public func bar() -> Int {
42
}
1 change: 1 addition & 0 deletions Fixtures/Miscellaneous/APIDiff/Bar/Sources/Qux/Qux.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
public class Qux<T> { public let x = 1 }
13 changes: 13 additions & 0 deletions Fixtures/Miscellaneous/APIDiff/CTargetDep/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// swift-tools-version:4.2
import PackageDescription

let package = Package(
name: "CLibrarySources",
products: [
.library(name: "Lib", targets: ["Bar"])
],
targets: [
.target(name: "Foo"),
.target(name: "Bar", dependencies: ["Foo"])
]
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import Foo

public func bar() -> Int {
foo()
return 42
}
8 changes: 8 additions & 0 deletions Fixtures/Miscellaneous/APIDiff/CTargetDep/Sources/Foo/Foo.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#include "Foo.h"

int foo() {
int a = 5;
int b = a;
a = b;
return a;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
int foo();
3 changes: 3 additions & 0 deletions Fixtures/Miscellaneous/APIDiff/Foo/Foo.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
public func foo() {
{}()
}
12 changes: 12 additions & 0 deletions Fixtures/Miscellaneous/APIDiff/Foo/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// swift-tools-version:4.2
import PackageDescription

let package = Package(
name: "Foo",
products: [
.library(name: "Foo", targets: ["Foo"]),
],
targets: [
.target(name: "Foo", path: "./"),
]
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// swift-tools-version:4.2
import PackageDescription

let package = Package(
name: "NonAPILibraryTargets",
products: [
.library(name: "One", targets: ["Foo"]),
.library(name: "Two", targets: ["Bar", "Baz"]),
.executable(name: "Exec", targets: ["Exec", "Qux"])
],
targets: [
.target(name: "Foo"),
.target(name: "Bar", dependencies: ["Baz"]),
.target(name: "Baz"),
.target(name: "Qux"),
.target(name: "Exec", dependencies: ["Qux"])
]
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import Baz

public func bar() -> Int {
42
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
public enum Baz {
case a, c
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import Qux

print("Hello, world!")
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
public struct Foo {
func doThing() {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
public class Qux<T> { public let x = 1 }
9 changes: 1 addition & 8 deletions Sources/Build/BuildPlan.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1919,14 +1919,7 @@ public class BuildPlan {
// Add search paths from the system library targets.
for target in graph.reachableTargets {
if let systemLib = target.underlyingTarget as? SystemLibraryTarget {
for flag in self.pkgConfig(for: systemLib).cFlags {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are these changes unnecessary now?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, as of swiftlang/swift#37206 this is unnecessary because the API digester and compiler are using the same option definitions

// The api-digester tool doesn't like `-I<Foo>` style for some reason.
if flag.hasPrefix("-I") && flag.count > 2 {
arguments += ["-I", String(flag.dropFirst(2))]
} else {
arguments.append(flag)
}
}
arguments.append(contentsOf: self.pkgConfig(for: systemLib).cFlags)
// Add the path to the module map.
arguments += ["-I", systemLib.moduleMapPath.parentDirectory.pathString]
}
Expand Down
131 changes: 86 additions & 45 deletions Sources/Commands/APIDigester.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/*
This source file is part of the Swift.org open source project

Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception

See http://swift.org/LICENSE.txt for license information
Expand All @@ -18,11 +18,10 @@ import PackageModel
import SourceControl
import Workspace

/// Helper for dumping the SDK JSON file for the baseline.
/// Helper for emitting a JSON API baseline for a module.
struct APIDigesterBaselineDumper {
/// The baseline we're diffing against.
///
/// This is the git treeish.

/// The git treeish to emit a baseline for.
let baselineTreeish: String

/// The root package path.
Expand Down Expand Up @@ -61,17 +60,18 @@ struct APIDigesterBaselineDumper {
self.diags = diags
}

/// Dump the baseline SDK JSON and return its path.
func dumpBaselineSDKJSON() throws -> AbsolutePath {
/// Emit the API baseline files and return the path to their directory.
func emitAPIBaseline() throws -> AbsolutePath {
let apiDiffDir = inputBuildParameters.apiDiff
let sdkJSON = apiDiffDir.appending(component: baselineTreeish + ".json")
let baselineDir = apiDiffDir.appending(component: baselineTreeish)

// We're done if the JSON already exists on disk.
if localFileSystem.exists(sdkJSON) {
return sdkJSON
// We're done if the baseline already exists on disk.
if localFileSystem.exists(baselineDir) {
return baselineDir
}

let baselinePackageRoot = apiDiffDir.appending(component: baselineTreeish)
// Setup a temporary directory where we can checkout and build the baseline treeish.
let baselinePackageRoot = apiDiffDir.appending(component: "\(baselineTreeish)-checkout")
if localFileSystem.exists(baselinePackageRoot) {
try localFileSystem.removeFileTree(baselinePackageRoot)
}
Expand Down Expand Up @@ -116,66 +116,85 @@ struct APIDigesterBaselineDumper {
stdoutStream: stdoutStream
)

// FIXME: Need a way to register this build operation with the interrupt handler.

try buildOp.build()

// Dump the SDK JSON.
try apiDigesterTool.dumpSDKJSON(
at: sdkJSON,
modules: graph.apiDigesterModules,
additionalArgs: buildOp.buildPlan!.createAPIToolCommonArgs(includeLibrarySearchPaths: false)
)
for module in graph.apiDigesterModules {
let moduleBaselinePath = baselineDir.appending(component: module + ".json")
try apiDigesterTool.emitAPIBaseline(
to: moduleBaselinePath,
for: module,
buildPlan: buildOp.buildPlan!,
diagnosticsEngine: diags
)
}

return sdkJSON
return baselineDir
}
}

/// A wrapper for swift-api-digester tool.
/// A wrapper for the swift-api-digester tool.
public struct SwiftAPIDigester {

/// The absolute path to `swift-api-digester` in the toolchain.
let tool: AbsolutePath

init(tool: AbsolutePath) {
self.tool = tool
}

public func dumpSDKJSON(
at json: AbsolutePath,
modules: [String],
additionalArgs: [String]
/// Emit an API baseline file for the specified module at the specified location.
public func emitAPIBaseline(
to outputPath: AbsolutePath,
for module: String,
buildPlan: BuildPlan,
diagnosticsEngine: DiagnosticsEngine
) throws {
var args = ["-dump-sdk"]
args += additionalArgs
args += modules.flatMap { ["-module", $0] }
args += ["-o", json.pathString]
try localFileSystem.createDirectory(json.parentDirectory, recursive: true)
args += buildPlan.createAPIToolCommonArgs(includeLibrarySearchPaths: false)
args += ["-module", module, "-o", outputPath.pathString]
try localFileSystem.createDirectory(outputPath.parentDirectory, recursive: true)

try runTool(args)

// FIXME: The tool doesn't exit with 1 if it fails.
if !localFileSystem.exists(json) {
if !localFileSystem.exists(outputPath) {
diagnosticsEngine.emit(error: "failed to generate baseline for \(module)")
throw Diagnostics.fatalError
}
}

public func diagnoseSDK(
baselineSDKJSON: AbsolutePath,
apiToolArgs: [String],
modules: [String]
) throws {
/// Compare the current package API to a provided baseline file.
public func compareAPIToBaseline(
at baselinePath: AbsolutePath,
for module: String,
buildPlan: BuildPlan,
diagnosticsEngine: DiagnosticsEngine
) throws -> ComparisonResult {
var args = [
"-diagnose-sdk",
"-baseline-path", baselineSDKJSON.pathString,
"-baseline-path", baselinePath.pathString,
"-module", module
]
args.append(contentsOf: apiToolArgs)
for module in modules {
args.append(contentsOf: ["-module", module])
args.append(contentsOf: buildPlan.createAPIToolCommonArgs(includeLibrarySearchPaths: false))

return try withTemporaryFile(deleteOnClose: false) { file in
args.append(contentsOf: ["-serialize-diagnostics-path", file.path.pathString])
try runTool(args)
let contents = try localFileSystem.readFileContents(file.path)
guard contents.count > 0 else {
diagnosticsEngine.emit(error: "failed to read API digester output for \(module)")
throw Diagnostics.fatalError
}
let serializedDiagnostics = try SerializedDiagnostics(bytes: contents)
let apiDigesterCategory = "api-digester-breaking-change"
let apiBreakingChanges = serializedDiagnostics.diagnostics.filter { $0.category == apiDigesterCategory }
let otherDiagnostics = serializedDiagnostics.diagnostics.filter { $0.category != apiDigesterCategory }
return ComparisonResult(apiBreakingChanges: apiBreakingChanges,
otherDiagnostics: otherDiagnostics)
}

try runTool(args)
}

func runTool(_ args: [String]) throws {
private func runTool(_ args: [String]) throws {
let arguments = [tool.pathString] + args
let process = Process(
arguments: arguments,
Expand All @@ -187,6 +206,21 @@ public struct SwiftAPIDigester {
}
}

extension SwiftAPIDigester {
/// The result of comparing a module's API to a provided baseline.
public struct ComparisonResult {
/// Breaking changes made to the API since the baseline was generated.
var apiBreakingChanges: [SerializedDiagnostics.Diagnostic]
/// Other diagnostics emitted while comparing the current API to the baseline.
var otherDiagnostics: [SerializedDiagnostics.Diagnostic]

/// `true` if the comparison succeeded and no breaking changes were found, otherwise `false`.
var hasNoAPIBreakingChanges: Bool {
apiBreakingChanges.isEmpty && otherDiagnostics.filter { [.fatal, .error].contains($0.level) }.isEmpty
}
}
}

extension BuildParameters {
/// The directory containing artifacts for API diffing operations.
var apiDiff: AbsolutePath {
Expand All @@ -198,9 +232,16 @@ extension PackageGraph {
/// The list of modules that should be used as an input to the API digester.
var apiDigesterModules: [String] {
self.rootPackages
.flatMap { $0.targets }
.filter { $0.type == .library }
.flatMap(\.products)
.filter { $0.type.isLibrary }
.flatMap(\.targets)
.filter { $0.underlyingTarget is SwiftTarget }
.map { $0.c99name }
}
}

extension SerializedDiagnostics.SourceLocation: DiagnosticLocation {
public var description: String {
return "\(filename):\(line):\(column)"
}
}
55 changes: 48 additions & 7 deletions Sources/Commands/SwiftPackageTool.swift
Original file line number Diff line number Diff line change
Expand Up @@ -319,14 +319,55 @@ extension SwiftPackageTool {
apiDigesterTool: apiDigesterTool,
diags: swiftTool.diagnostics
)
let baselineSDKJSON = try baselineDumper.dumpBaselineSDKJSON()
let baselineDir = try baselineDumper.emitAPIBaseline()

var succeeded = true
for module in try buildOp.getPackageGraph().apiDigesterModules {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you provide a reason for doing this per module? This triggers a process launch for each, which can cause issues such as a (noticeable) perf regression even when there's a minor non-api breaking change.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right now the API digester assumes the baseline was generated from the same set of modules it's loading, so generating a baseline from multiple and then comparing that to one module at a time returns a bunch of false positives. I also didn't want to load every module at once because currently the source module for each breaking change isn't serialized, so there isn't a reliable way to sort the changes by product/target. Future compiler improvements might let us rollback this part of the change

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like making changes in the detection logic itself in the frontend should be the way to go (cc @nkcsgexi). Having to iterate over each module and launching the process for each won't scale. Is there at least a way to find depending modules that are affected by a diff so only those can be iterated over?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Eliminating false positives at all from the API digester tool is a very challenging and long-term task. Why do you think it won't scale for iterating over each module? Build system/swift-driver iterates each modules and build them.

Copy link
Contributor

@elsh elsh May 21, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@nkcsgexi Build system performs several things including dependency scanning and caching/cache lookups so incremental builds are faster. The api-digester doesn't do any of that and this change launches a frontend process for each module even when there's a very minor change at the top module. This won't be a problem if there are a few modules but projects containing over 100 modules are not uncommon.

let moduleBaselinePath = baselineDir.appending(component: "\(module).json")
guard localFileSystem.exists(moduleBaselinePath) else {
print("\nSkipping \(module) because it does not exist in the baseline")
continue
}
let comparisonResult = try apiDigesterTool.compareAPIToBaseline(
at: moduleBaselinePath,
for: module,
buildPlan: buildOp.buildPlan!,
diagnosticsEngine: swiftTool.diagnostics
)
printComparisonResult(comparisonResult, moduleName: module, diagnosticsEngine: swiftTool.diagnostics)
succeeded = succeeded && comparisonResult.hasNoAPIBreakingChanges
}

// Run the diagnose tool which will print the diff.
try apiDigesterTool.diagnoseSDK(
baselineSDKJSON: baselineSDKJSON,
apiToolArgs: buildOp.buildPlan!.createAPIToolCommonArgs(includeLibrarySearchPaths: false),
modules: try buildOp.getPackageGraph().apiDigesterModules
)
guard succeeded else { throw ExitCode.failure }
}

private func printComparisonResult(_ comparisonResult: SwiftAPIDigester.ComparisonResult,
moduleName: String,
diagnosticsEngine: DiagnosticsEngine) {
for diagnostic in comparisonResult.otherDiagnostics {
switch diagnostic.level {
case .error, .fatal:
diagnosticsEngine.emit(error: diagnostic.text, location: diagnostic.location)
case .warning:
diagnosticsEngine.emit(warning: diagnostic.text, location: diagnostic.location)
case .note:
diagnosticsEngine.emit(note: diagnostic.text, location: diagnostic.location)
case .remark:
diagnosticsEngine.emit(remark: diagnostic.text, location: diagnostic.location)
case .ignored:
break
}
}

if comparisonResult.apiBreakingChanges.isEmpty {
print("\nNo breaking changes detected in \(moduleName)")
} else {
let count = comparisonResult.apiBreakingChanges.count
print("\n\(count) breaking \(count > 1 ? "changes" : "change") detected in \(moduleName):")
for change in comparisonResult.apiBreakingChanges {
print(" 💔 \(change.text)")
}
}
}
}

Expand Down
Loading