compiler: Support Querying For Files In Preprocessed Code

Signed-off-by: Will Hawkins <hawkinsw@obs.cr>
This commit is contained in:
Will Hawkins
2026-05-11 07:26:29 -04:00
parent f0f7a660a6
commit 0e2b13be93
5 changed files with 58 additions and 0 deletions
+20
View File
@@ -129,6 +129,22 @@ public struct FileSourceLocation: Equatable, CustomStringConvertible {
return "\(location)" return "\(location)"
}).joined(separator: ",") + ")" }).joined(separator: ",") + ")"
} }
public func pathForLocation(_ location: Int) -> FilePath? {
let queried_location = SourceLocation(location, 1)
if !self.location.contains(queried_location) {
return .none
}
for nested in self.nested {
if nested.location.contains(queried_location) {
return nested.pathForLocation(location)
}
}
return self.getPath()
}
} }
/// Represent preprocessed P4 code. /// Represent preprocessed P4 code.
@@ -197,6 +213,10 @@ public struct SourceCode {
public func getLocations() -> FileSourceLocation { public func getLocations() -> FileSourceLocation {
return self.locations return self.locations
} }
public func pathForLocation(_ location: Int) -> FilePath? {
return self.locations.pathForLocation(location)
}
} }
func do_preprocess( func do_preprocess(
@@ -0,0 +1,9 @@
state start {
Testing ts;
ts.yesno = true;
ts.count = 5;
transition select (ts.count == 5) {
true: accept;
false: reject;
};
}
+3
View File
@@ -0,0 +1,3 @@
parser main_parser() {
#include <file-loc-parser-state.p4>
}
+5
View File
@@ -0,0 +1,5 @@
struct Testing {
bool yesno;
int count;
};
#include <file-loc-parser.p4>
@@ -185,6 +185,27 @@ import TreeSitterP4
#expect(source.getSource(annotated: true) == expected) #expect(source.getSource(annotated: true) == expected)
} }
@Test func test_preprocessor_nested_includes_get_file_location() async throws {
let sm = SourceManager(["./TestData/Sources/"], FileManager()) // Add a FileManager to get absolute paths.
let prep = SourceCodePreprocessor(sm)
let file = FilePath.init(stringLiteral: "./TestData/Sources/file-loc.p4")
let source = try! (#UseOkResult(prep.preprocess(file)))
let expected_file = FilePath.init(FileManager().currentDirectoryPath + "/" + file.string)
.lexicallyNormalized()
let expected_nested_file = sm.firstExisting("file-loc-parser.p4")!.lexicallyNormalized()
let expected_nested_nested_file = sm.firstExisting("file-loc-parser-state.p4")!
.lexicallyNormalized()
let found_file = try! #require(source.pathForLocation(0))
let found_nested_file = try! #require(source.pathForLocation(55))
let found_nested_nested_file = try! #require(source.pathForLocation(78))
#expect(found_file == expected_file)
#expect(found_nested_file == expected_nested_file)
#expect(found_nested_nested_file == expected_nested_nested_file)
}
@Test func test_source_location_contains() async throws { @Test func test_source_location_contains() async throws {
let outer = SourceLocation(0..<500) let outer = SourceLocation(0..<500)