1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
|
//===---------- DependencyGraphDotFileWriter.swift - Swift GraphViz -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import protocol TSCBasic.WritableByteStream
// MARK: - Asking to write dot files / interface
public struct DependencyGraphDotFileWriter {
/// Holds file-system and options
private let info: IncrementalCompilationState.IncrementalDependencyAndInputSetup
private var versionNumber = 0
init(_ info: IncrementalCompilationState.IncrementalDependencyAndInputSetup) {
self.info = info
}
mutating func write(_ sfdg: SourceFileDependencyGraph, for file: TypedVirtualPath,
internedStringTable: InternedStringTable) {
let basename = file.file.basename
write(sfdg, basename: basename, internedStringTable: internedStringTable)
}
mutating func write(_ mdg: ModuleDependencyGraph) {
write(mdg, basename: Self.moduleDependencyGraphBasename,
internedStringTable: mdg.internedStringTable)
}
@_spi(Testing) public static let moduleDependencyGraphBasename = "moduleDependencyGraph"
}
// MARK: Asking to write dot files / implementation
fileprivate extension DependencyGraphDotFileWriter {
mutating func write<Graph: ExportableGraph>(
_ graph: Graph,
basename: String,
internedStringTable: InternedStringTable
) {
let path = dotFilePath(for: basename)
try! info.fileSystem.writeFileContents(path) { stream in
var s = DOTDependencyGraphSerializer<Graph>(
graph,
graphID: basename,
stream,
includeExternals: info.dependencyDotFilesIncludeExternals,
includeAPINotes: info.dependencyDotFilesIncludeAPINotes,
internedStringTable: internedStringTable)
s.emit()
}
}
mutating func dotFilePath(for basename: String) -> VirtualPath {
let nextVersionNumber = versionNumber
// Update the version number so that successive saved dot files for the graph
// (for instance the ModuleDependencyGraph) can be examined in order to see
// how an import changed the graph.
versionNumber += 1
return info.buildRecordInfo.dotFileDirectory
.appending(component: "\(basename).\(nextVersionNumber).dot")
}
}
// MARK: - Making dependency graphs exportable
fileprivate protocol ExportableGraph {
associatedtype Node: ExportableNode
func forEachExportableNode(_ visit: (Node) -> Void)
func forEachExportableArc(_ visit: (Node, Node) -> Void)
}
extension SourceFileDependencyGraph: ExportableGraph {
fileprivate func forEachExportableNode<Node: ExportableNode>(_ visit: (Node) -> Void) {
forEachNode { visit($0 as! Node) }
}
fileprivate func forEachExportableArc<Node: ExportableNode>(_ visit: (Node, Node) -> Void) {
forEachNode { use in
forEachDefDependedUpon(by: use) { def in
visit(def as! Node, use as! Node)
}
}
}
}
extension ModuleDependencyGraph: ExportableGraph {
fileprivate var graphID: String {
return "ModuleDependencyGraph"
}
fileprivate func forEachExportableNode<Node: ExportableNode>(
_ visit: (Node) -> Void) {
nodeFinder.forEachNode { visit($0 as! Node) }
}
fileprivate func forEachExportableArc<Node: ExportableNode>(
_ visit: (Node, Node) -> Void
) {
nodeFinder.forEachNode {def in
for use in nodeFinder.uses(of: def) {
visit(def as! Node, use as! Node)
}
}
}
}
// MARK: - Making dependency graph nodes exportable
fileprivate protocol ExportableNode: Hashable {
var key: DependencyKey {get}
var definitionVsUse: DefinitionVsUse {get}
func label(in: InternedStringTable) -> String
}
extension SourceFileDependencyGraph.Node: ExportableNode {
}
extension ModuleDependencyGraph.Node: ExportableNode {
fileprivate var definitionVsUse: DefinitionVsUse {
definitionLocation == .unknown ? .use : .definition
}
}
extension ExportableNode {
fileprivate func emit(id: Int, to out: inout WritableByteStream, _ t: InternedStringTable) {
out.send("\(DotFileNode(id: id, node: self, in: t).description)\n")
}
fileprivate func label(in t: InternedStringTable) -> String {
"\(key.description(in: t)) \(definitionVsUse == .definition ? "here" : "somewhere else")"
}
fileprivate var isExternal: Bool {
key.designator.externalDependency != nil
}
fileprivate var isAPINotes: Bool {
key.designator.externalDependency?.fileNameString.hasSuffix(".apinotes")
?? false
}
fileprivate var shape: Shape {
key.designator.shape
}
fileprivate var fillColor: Color {
switch (definitionVsUse, key.aspect) {
case (.definition, _ ): return .azure
case (.use, .interface ): return .yellow
case (.use, .implementation): return .white
}
}
fileprivate var style: Style? {
definitionVsUse == .definition ? .solid : .dotted
}
}
fileprivate extension DependencyKey.Designator {
var shape: Shape {
switch self {
case .topLevel:
return .box
case .dynamicLookup:
return .diamond
case .externalDepend:
return .house
case .sourceFileProvide:
return .hexagon
case .nominal:
return .parallelogram
case .potentialMember:
return .ellipse
case .member:
return .triangle
}
}
static var oneOfEachKind: [DependencyKey.Designator] {
[
.topLevel(name: .empty),
.dynamicLookup(name: .empty),
.externalDepend(.dummy),
.sourceFileProvide(name: .empty),
.nominal(context: .empty),
.potentialMember(context: .empty),
.member(context: .empty, name: .empty)
]}
}
// MARK: - writing one dot file
fileprivate struct DOTDependencyGraphSerializer<Graph: ExportableGraph>: InternedStringTableHolder {
private let includeExternals: Bool
private let includeAPINotes: Bool
private let graphID: String
private let graph: Graph
fileprivate let internedStringTable: InternedStringTable
private var nodeIDs = [Graph.Node: Int]()
private var out: WritableByteStream
fileprivate init(
_ graph: Graph,
graphID: String,
_ stream: WritableByteStream,
includeExternals: Bool,
includeAPINotes: Bool,
internedStringTable: InternedStringTable
) {
self.graph = graph
self.internedStringTable = internedStringTable
self.graphID = graphID
self.out = stream
self.includeExternals = includeExternals
self.includeAPINotes = includeAPINotes
}
fileprivate mutating func emit() {
emitPrelude()
emitLegend()
emitNodes()
emitArcs()
emitPostlude()
}
private func emitPrelude() {
out.send("digraph \(graphID.quoted) {\n")
}
private mutating func emitLegend() {
for dummy in DependencyKey.Designator.oneOfEachKind {
out.send("\(DotFileNode(forLegend: dummy).description)\n")
}
}
private mutating func emitNodes() {
graph.forEachExportableNode { (n: Graph.Node) in
if include(n) {
n.emit(id: register(n), to: &out, internedStringTable)
}
}
}
private mutating func register(_ n: Graph.Node) -> Int {
let newValue = nodeIDs.count
let oldValue = nodeIDs.updateValue(newValue, forKey: n)
assert(oldValue == nil, "not nil")
return newValue
}
private func emitArcs() {
graph.forEachExportableArc { (def: Graph.Node, use: Graph.Node) in
if include(def: def, use: use) {
out.send("\(DotFileArc(defID: nodeIDs[def]!, useID: nodeIDs[use]!).description)\n")
}
}
}
private func emitPostlude() {
out.send("\n}\n")
}
func include(_ n: Graph.Node) -> Bool {
let externalPredicate = includeExternals || !n.isExternal
let apiPredicate = includeAPINotes || !n.isAPINotes
return externalPredicate && apiPredicate;
}
func include(def: Graph.Node, use: Graph.Node) -> Bool {
include(def) && include(use)
}
}
fileprivate extension String {
var quoted: String {
"\"" + replacingOccurrences(of: "\"", with: "\\\"") + "\""
}
}
fileprivate struct DotFileNode: CustomStringConvertible {
let id: String
let label: String
let shape: Shape
let fillColor: Color
let style: Style?
init<Node: ExportableNode>(id: Int, node: Node, in t: InternedStringTable) {
self.id = String(id)
self.label = node.label(in: t)
self.shape = node.shape
self.fillColor = node.fillColor
self.style = node.style
}
init(forLegend designator: DependencyKey.Designator) {
self.id = designator.shape.rawValue
self.label = designator.kindName
self.shape = designator.shape
self.fillColor = .azure
self.style = nil
}
var description: String {
let bodyString: String = [
("label", label),
("shape", shape.rawValue),
("fillcolor", fillColor.rawValue),
style.map {("style", $0.rawValue)}
]
.compactMap {
$0.map {name, value in "\(name) = \"\(value)\""}
}
.joined(separator: ", ")
return "\(id.quoted) [ \(bodyString) ]"
}
}
fileprivate struct DotFileArc: CustomStringConvertible {
let defID, useID: Int
var description: String {
"\(defID) -> \(useID);"
}
}
fileprivate enum Shape: String {
case box, parallelogram, ellipse, triangle, diamond, house, hexagon
}
fileprivate enum Color: String {
case azure, white, yellow
}
fileprivate enum Style: String {
case solid, dotted
}
|