compiler: Add Ability to Annotate Preprocessed Source
Signed-off-by: Will Hawkins <hawkinsw@obs.cr>
This commit is contained in:
@@ -143,14 +143,57 @@ public struct SourceCode {
|
||||
self.locations = locations
|
||||
}
|
||||
|
||||
public func getSource() -> String {
|
||||
return self.code
|
||||
}
|
||||
|
||||
public func getManager() -> SourceManager {
|
||||
return self.manager
|
||||
}
|
||||
|
||||
static func do_annotate(
|
||||
_ contents: String, _ manager: SourceManager, _ locations: FileSourceLocation,
|
||||
_ formatter: Formattable, _ style: Style
|
||||
) -> String {
|
||||
var result = ""
|
||||
|
||||
// Keep track of the start of any gap between nested locations.
|
||||
var gap_start = contents.startIndex
|
||||
|
||||
// contents are devoid of any preceding source code, but the locations do not know that. So,
|
||||
// when we use a range from locations we must adjust appropriately.
|
||||
let offset = locations.location.range.lowerBound
|
||||
|
||||
for nested in locations.getNestedLocations() {
|
||||
let nested_start = contents.index(
|
||||
contents.startIndex, offsetBy: nested.location.range.lowerBound - offset)
|
||||
let nested_end = contents.index(
|
||||
contents.startIndex, offsetBy: nested.location.range.upperBound - offset)
|
||||
|
||||
// Add in any gap.
|
||||
result += contents[gap_start..<nested_start]
|
||||
|
||||
// Handle this range (recursively)
|
||||
result += do_annotate(
|
||||
"\(contents[nested_start ..< nested_end])", manager, nested, formatter, style)
|
||||
|
||||
// Adjust where the next gap will start.
|
||||
gap_start = nested_end
|
||||
}
|
||||
|
||||
// Is there anything left?
|
||||
let remainder = contents[gap_start...]
|
||||
|
||||
return formatter.formatWithStyle(result + remainder, style)
|
||||
}
|
||||
|
||||
public func getSource(
|
||||
annotated: Bool = false, formatter: Formattable = FormatterDelimited("<", ">"),
|
||||
initialStyle: Style = Style(StyleColor.Red)
|
||||
) -> String {
|
||||
if annotated {
|
||||
return SourceCode.do_annotate(
|
||||
self.code, self.manager, self.locations, formatter, initialStyle)
|
||||
}
|
||||
return self.code
|
||||
}
|
||||
|
||||
public func getLocations() -> FileSourceLocation {
|
||||
return self.locations
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user