@@ -58,7 +58,8 @@ public final class SwiftFormatter {
5858 throw SwiftFormatError . isDirectory
5959 }
6060 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)
6263 }
6364
6465 /// Formats the given Swift source code and writes the result to an output stream.
@@ -75,11 +76,13 @@ public final class SwiftFormatter {
7576 source: String , assumingFileURL url: URL ? , to outputStream: inout Output
7677 ) throws {
7778 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)
7980 }
8081
8182 /// Formats the given Swift syntax tree and writes the result to an output stream.
8283 ///
84+ /// - Note: The formatter may be faster using the source text, if it's available.
85+ ///
8386 /// - Parameters:
8487 /// - syntax: The Swift syntax tree to be converted to source code and formatted.
8588 /// - url: A file URL denoting the filename/path that should be assumed for this syntax tree,
@@ -90,6 +93,13 @@ public final class SwiftFormatter {
9093 /// - Throws: If an unrecoverable error occurs when formatting the code.
9194 public func format< Output: TextOutputStream > (
9295 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
93103 ) throws {
94104 if let position = firstInvalidSyntaxPosition ( in: Syntax ( syntax) ) {
95105 throw SwiftFormatError . fileContainsInvalidSyntax ( position: position)
@@ -98,7 +108,7 @@ public final class SwiftFormatter {
98108 let assumedURL = url ?? URL ( fileURLWithPath: " source " )
99109 let context = Context (
100110 configuration: configuration, diagnosticEngine: diagnosticEngine, fileURL: assumedURL,
101- sourceFileSyntax: syntax)
111+ sourceFileSyntax: syntax, source : source )
102112 let pipeline = FormatPipeline ( context: context)
103113 let transformedSyntax = pipeline. visit ( Syntax ( syntax) )
104114
0 commit comments