|
1 | 1 | import Foundation |
2 | 2 |
|
3 | | -public enum PNCompilationError: Error { |
4 | | - case cycle |
5 | | -} |
6 | | - |
| 3 | +/// The main class for building and compiling dependency graphs. |
| 4 | +/// |
| 5 | +/// This class provides methods to add nodes, define dependencies between them, |
| 6 | +/// and compile the graph into a topologically sorted order. |
7 | 7 | public final class PNGraph { |
| 8 | + /// A dictionary of all nodes in the graph, keyed by their identifiers. |
8 | 9 | private var nodes: [String: PNNode] = [:] |
9 | 10 |
|
| 11 | + /// Adds a new node to the graph with the specified identifier. |
| 12 | + /// |
| 13 | + /// If a node with this identifier already exists, it is returned instead of creating a new one. |
| 14 | + /// |
| 15 | + /// - Parameter identifier: A unique identifier for the node. |
| 16 | + /// - Returns: The node associated with the provided identifier. |
10 | 17 | public func add(identifier: String) -> PNNode { |
11 | 18 | if let existing = nodes[identifier] { return existing } |
12 | 19 | let node = PNNode(identifier: identifier) |
13 | 20 | nodes[identifier] = node |
14 | 21 | return node |
15 | 22 | } |
16 | 23 |
|
| 24 | + /// Initializes an empty dependency graph. |
17 | 25 | public init() { |
18 | 26 |
|
19 | 27 | } |
20 | 28 |
|
| 29 | + /// Retrieves a node from the graph by its identifier. |
| 30 | + /// |
| 31 | + /// - Parameter identifier: The identifier of the node to retrieve. |
| 32 | + /// - Returns: The node with the specified identifier, or `nil` if not found. |
21 | 33 | public func get(identifier: String) -> PNNode? { |
22 | 34 | nodes[identifier] |
23 | 35 | } |
24 | 36 |
|
| 37 | + /// Compiles the dependency graph into a topologically sorted order. |
| 38 | + /// |
| 39 | + /// This method performs a depth-first search to detect cycles and generate an execution order. |
| 40 | + /// If a cycle is detected, it throws `PNCompilationError.cycle`. |
| 41 | + /// |
| 42 | + /// - Returns: A compiled graph containing nodes in topological order. |
| 43 | + /// - Throws: `PNCompilationError.cycle` if the graph contains a cycle. |
25 | 44 | public func compile() throws -> PNCompiledGraph { |
26 | 45 | var visited: Set<String> = [] |
27 | 46 | var visiting: Set<String> = [] |
|
0 commit comments