@@ -58,7 +58,8 @@ public final class SwiftFormatter {
58
58
throw SwiftFormatError . isDirectory
59
59
}
60
60
let sourceFile = try SyntaxParser . parse ( url)
61
- try format ( syntax: sourceFile, assumingFileURL: url, to: & outputStream)
61
+ let source = try String ( contentsOf: url, encoding: . utf8)
62
+ try format ( syntax: sourceFile, assumingFileURL: url, source: source, to: & outputStream)
62
63
}
63
64
64
65
/// Formats the given Swift source code and writes the result to an output stream.
@@ -75,11 +76,13 @@ public final class SwiftFormatter {
75
76
source: String , assumingFileURL url: URL ? , to outputStream: inout Output
76
77
) throws {
77
78
let sourceFile = try SyntaxParser . parse ( source: source)
78
- try format ( syntax: sourceFile, assumingFileURL: url, to: & outputStream)
79
+ try format ( syntax: sourceFile, assumingFileURL: url, source : source , to: & outputStream)
79
80
}
80
81
81
82
/// Formats the given Swift syntax tree and writes the result to an output stream.
82
83
///
84
+ /// - Note: The formatter may be faster using the source text, if it's available.
85
+ ///
83
86
/// - Parameters:
84
87
/// - syntax: The Swift syntax tree to be converted to source code and formatted.
85
88
/// - url: A file URL denoting the filename/path that should be assumed for this syntax tree,
@@ -90,6 +93,13 @@ public final class SwiftFormatter {
90
93
/// - Throws: If an unrecoverable error occurs when formatting the code.
91
94
public func format< Output: TextOutputStream > (
92
95
syntax: SourceFileSyntax , assumingFileURL url: URL ? , to outputStream: inout Output
96
+ ) throws {
97
+ try format ( syntax: syntax, assumingFileURL: url, source: nil , to: & outputStream)
98
+ }
99
+
100
+ private func format< Output: TextOutputStream > (
101
+ syntax: SourceFileSyntax , assumingFileURL url: URL ? , source: String ? ,
102
+ to outputStream: inout Output
93
103
) throws {
94
104
if let position = firstInvalidSyntaxPosition ( in: Syntax ( syntax) ) {
95
105
throw SwiftFormatError . fileContainsInvalidSyntax ( position: position)
@@ -98,7 +108,7 @@ public final class SwiftFormatter {
98
108
let assumedURL = url ?? URL ( fileURLWithPath: " source " )
99
109
let context = Context (
100
110
configuration: configuration, diagnosticEngine: diagnosticEngine, fileURL: assumedURL,
101
- sourceFileSyntax: syntax)
111
+ sourceFileSyntax: syntax, source : source )
102
112
let pipeline = FormatPipeline ( context: context)
103
113
let transformedSyntax = pipeline. visit ( Syntax ( syntax) )
104
114
0 commit comments