From a0c6b7730c906f46ee591fe063548d54ac976862 Mon Sep 17 00:00:00 2001 From: Will Hawkins Date: Mon, 11 May 2026 07:20:51 -0400 Subject: [PATCH] documentation: Document SourceCode-related structs Signed-off-by: Will Hawkins --- Sources/Common/SourceCode.swift | 46 ++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/Sources/Common/SourceCode.swift b/Sources/Common/SourceCode.swift index 7411228..17fb591 100644 --- a/Sources/Common/SourceCode.swift +++ b/Sources/Common/SourceCode.swift @@ -40,14 +40,49 @@ public struct SourceLocation: Equatable, CustomStringConvertible { } } -/// Represent a set of directories containing P4 code that can be accessed with relative paths. +/// Represent search paths for P4 code that can be accessed with relative paths. public struct SourceManager { let paths: [FilePath] - public init(_ paths: [FilePath]) { - self.paths = paths + + /// Create a `SourceManager` + /// + /// Any relative `FilePath`s in `paths` will be absolutized + /// if a `FileManager` is given. + /// + /// parameters: + /// - paths: The include paths searched for files with relative paths. + /// - fm: An optional instance of a `FileManager` that will be used to + /// convert relative paths in `paths` to absolute paths. + public init(_ paths: [FilePath], _ fm: FileManager? = .none) { + + // If the user gives a file manager, we will convert relative paths + // to absolute paths. Otherwise, we do not. + guard let fm else { + self.paths = paths + return + } + + // There is a file manager, so we should try to absolutize any + // relative paths + self.paths = paths.map { + if !$0.isAbsolute { + return FilePath(fm.currentDirectoryPath + "/" + $0.string).lexicallyNormalized() + } + return $0 + } } + /// Return `FilePath` of `file` in search paths. + /// + /// Only if `file` is relative will the search paths be searched. + /// + /// parameters: + /// - file: A file to look for in the search paths. public func firstExisting(_ file: FilePath) -> FilePath? { + if file.isAbsolute { + return file + } + let fm = FileManager() for path in self.paths { let combined = path.pushing(file) @@ -59,7 +94,10 @@ public struct SourceManager { } } -/// Represent preprocessed P4 code and retain information about source filenames. +/// Represent preprocessed P4 code +/// +/// The preprocessed code has metadata to recover the paths of any +/// code generated by a preprocessor directive. public struct FileSourceLocation: Equatable, CustomStringConvertible { let location: SourceLocation let path: FilePath