-
Notifications
You must be signed in to change notification settings - Fork 439
Add API to infer the indentation of a syntax tree #2514
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,127 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the Swift.org open source project | ||
// | ||
// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors | ||
// Licensed under Apache License v2.0 with Runtime Library Exception | ||
// | ||
// See https://swift.org/LICENSE.txt for license information | ||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
import SwiftSyntax | ||
|
||
extension BasicFormat { | ||
/// Uses heuristics to infer the indentation width used in the given syntax tree. | ||
/// | ||
/// Returns `nil` if the indentation could not be inferred, eg. because it is inconsistent or there are not enough | ||
/// indented lines to infer the indentation with sufficient accuracy. | ||
public static func inferIndentation(of tree: some SyntaxProtocol) -> Trivia? { | ||
return IndentationInferrer.inferIndentation(of: tree) | ||
} | ||
} | ||
|
||
private class IndentationInferrer: SyntaxVisitor { | ||
/// The trivia of the previous visited token. | ||
/// | ||
/// The previous token's trailing trivia will be concatenated with the current token's leading trivia to infer | ||
/// indentation. | ||
/// | ||
/// We start with .newline to indicate that the first token starts on a newline, even if it technically doesn't have | ||
/// a leading newline character. | ||
private var previousTokenTrailingTrivia: Trivia = .newline | ||
|
||
/// Counts how many lines had how many spaces of indentation. | ||
/// | ||
/// For example, spaceIndentedLines[2] = 4 means that for lines had exactly 2 spaces of indentation. | ||
private var spaceIndentedLines: [Int: Int] = [:] | ||
|
||
/// See `spaceIndentedLines` | ||
private var tabIndentedLines: [Int: Int] = [:] | ||
|
||
/// The number of lines that were processed for indentation inference. | ||
/// | ||
/// This will be lower than the actual number of lines in the syntax node because | ||
/// - It does not count lines without indentation | ||
//// - It does not count newlines in block doc comments (because we don't process the comment's contents) | ||
private var linesProcessed = 0 | ||
|
||
override func visit(_ token: TokenSyntax) -> SyntaxVisitorContinueKind { | ||
defer { previousTokenTrailingTrivia = token.trailingTrivia } | ||
let triviaAtStartOfLine = | ||
(previousTokenTrailingTrivia + token.leadingTrivia) | ||
.drop(while: { !$0.isNewline }) // Ignore any trivia that's on the previous line | ||
.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline) // Split trivia into the lines it occurs on | ||
.dropFirst() // Drop the first empty array; exists because we dropped non-newline prefix and newline is separator | ||
|
||
LINE_TRIVIA_LOOP: for lineTrivia in triviaAtStartOfLine { | ||
switch lineTrivia.first { | ||
case .spaces(var spaces): | ||
linesProcessed += 1 | ||
for triviaPiece in lineTrivia.dropFirst() { | ||
switch triviaPiece { | ||
case .spaces(let followupSpaces): spaces += followupSpaces | ||
case .tabs: break LINE_TRIVIA_LOOP // Count as processed line but don't add to any indentation count | ||
default: break | ||
} | ||
} | ||
spaceIndentedLines[spaces, default: 0] += 1 | ||
case .tabs(var tabs): | ||
linesProcessed += 1 | ||
for triviaPiece in lineTrivia.dropFirst() { | ||
switch triviaPiece { | ||
case .tabs(let followupTabs): tabs += followupTabs | ||
case .spaces: break LINE_TRIVIA_LOOP // Count as processed line but don't add to any indentation count | ||
default: break | ||
} | ||
} | ||
tabIndentedLines[tabs, default: 0] += 1 | ||
default: | ||
break | ||
} | ||
} | ||
return .skipChildren | ||
} | ||
|
||
static func inferIndentation(of tree: some SyntaxProtocol) -> Trivia? { | ||
let visitor = IndentationInferrer(viewMode: .sourceAccurate) | ||
visitor.walk(tree) | ||
if visitor.linesProcessed < 3 { | ||
// We don't have enough lines to infer indentation reliably | ||
return nil | ||
} | ||
|
||
// Pick biggest indentation that encompasses at least 90% of the source lines. | ||
let threshold = Int(Double(visitor.linesProcessed) * 0.9) | ||
|
||
for spaceIndentation in [8, 4, 2] { | ||
let linesMatchingIndentation = visitor | ||
.spaceIndentedLines | ||
.filter { $0.key.isMultiple(of: spaceIndentation) } | ||
.map { $0.value } | ||
.sum | ||
if linesMatchingIndentation > threshold { | ||
return .spaces(spaceIndentation) | ||
} | ||
} | ||
|
||
for tabIndentation in [2, 1] { | ||
let linesMatchingIndentation = visitor | ||
.tabIndentedLines | ||
.filter { $0.key.isMultiple(of: tabIndentation) } | ||
.map { $0.value } | ||
.sum | ||
if linesMatchingIndentation > threshold { | ||
return .tabs(tabIndentation) | ||
} | ||
} | ||
return nil | ||
} | ||
} | ||
|
||
fileprivate extension Array<Int> { | ||
var sum: Int { | ||
return self.reduce(0) { return $0 + $1 } | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,196 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the Swift.org open source project | ||
// | ||
// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors | ||
// Licensed under Apache License v2.0 with Runtime Library Exception | ||
// | ||
// See https://swift.org/LICENSE.txt for license information | ||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
import SwiftBasicFormat | ||
import SwiftSyntax | ||
import SwiftSyntaxBuilder | ||
import XCTest | ||
|
||
fileprivate func assertIndentation( | ||
of sourceFile: SourceFileSyntax, | ||
_ expected: Trivia?, | ||
file: StaticString = #file, | ||
line: UInt = #line | ||
) { | ||
let inferred = BasicFormat.inferIndentation(of: sourceFile) | ||
XCTAssertEqual(inferred, expected, file: file, line: line) | ||
} | ||
|
||
final class InferIndentationTests: XCTestCase { | ||
func testTwoSpaceIndentation() { | ||
assertIndentation( | ||
of: """ | ||
class Foo { | ||
func bar() { | ||
print("hello world") | ||
} | ||
} | ||
""", | ||
.spaces(2) | ||
) | ||
} | ||
|
||
func testTwoSpaceIndentationWithMultipleFourSpaceLines() { | ||
assertIndentation( | ||
of: """ | ||
class Foo { | ||
func bar() { | ||
print("hello world") | ||
print("test") | ||
print("another") | ||
} | ||
} | ||
""", | ||
.spaces(2) | ||
) | ||
} | ||
|
||
func testTabIndentation() { | ||
assertIndentation( | ||
of: """ | ||
class Foo { | ||
\tfunc bar() { | ||
\tprint("hello world") | ||
\t} | ||
} | ||
""", | ||
.tabs(1) | ||
) | ||
} | ||
|
||
func testUseLineCommentsForInference() { | ||
assertIndentation( | ||
of: """ | ||
class Foo { | ||
/// Some doc comment | ||
/// And another | ||
func bar() { | ||
} | ||
} | ||
""", | ||
.spaces(2) | ||
) | ||
} | ||
|
||
func testBlockCommentContentsDontCountForInference() { | ||
assertIndentation( | ||
of: """ | ||
class Foo { | ||
/* | ||
* Test abc | ||
*/ | ||
func bar() {} | ||
} | ||
""", | ||
nil | ||
) | ||
} | ||
|
||
func testWithBlockComment() { | ||
assertIndentation( | ||
of: """ | ||
class Foo { | ||
/* | ||
* Test abc | ||
*/ | ||
func bar() { | ||
print("test") | ||
} | ||
} | ||
""", | ||
.spaces(2) | ||
) | ||
} | ||
|
||
func testDontGetConfusedBySingleIncorrectIndentation() { | ||
assertIndentation( | ||
of: """ | ||
class Foo { | ||
func bar() { | ||
print("1") | ||
print("2") | ||
print("3") | ||
print("4") | ||
print("5") | ||
print("6") | ||
print("7") | ||
print("8") | ||
print("9") | ||
print("10") | ||
} | ||
} | ||
""", | ||
.spaces(4) | ||
) | ||
} | ||
|
||
func testMixedTwoAndFourSpaceIndentation() { | ||
assertIndentation( | ||
of: """ | ||
class Foo { | ||
func bar() { | ||
print("1") | ||
print("2") | ||
print("3") | ||
print("4") | ||
print("5") | ||
print("6") | ||
print("7") | ||
print("8") | ||
print("9") | ||
print("10") | ||
} | ||
} | ||
""", | ||
.spaces(2) | ||
) | ||
} | ||
|
||
func testMixedSpaceAndTabIndentation() { | ||
assertIndentation( | ||
of: """ | ||
class Foo { | ||
func bar() { | ||
print("1") | ||
print("2") | ||
print("3") | ||
print("4") | ||
print("5") | ||
\t\tprint("6") | ||
\t\tprint("7") | ||
\t\tprint("8") | ||
\t\tprint("9") | ||
\t\tprint("10") | ||
\t} | ||
} | ||
""", | ||
nil | ||
) | ||
} | ||
|
||
func testMultilineStringLiteralWithInternalIndentation() { | ||
assertIndentation( | ||
of: #""" | ||
class Foo { | ||
func bar() { | ||
print(""" | ||
To Do: | ||
- Ignore string literals | ||
- Infer indentation | ||
""") | ||
} | ||
} | ||
"""#, | ||
.spaces(2) | ||
) | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Poor 3 space users 😅. Is 8 actually a thing that people use?
I think one issue we're likely to run into here is that for highly nested snippets, this is often going to return 8 even if it's eg. 2 space. Is the idea that this would only be run on entire files/functions/something else?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That shouldn’t be an issue. If we have 4 lines indented with 8 spaces and 1 line indented with 10 spaces, we’ll infer the indentation to 2 spaces because only 80% of the lines have an indentation that’s a multiple of 8 but all lines have an indentation that’s a multiple of 2.
And I think I’ve seen codebases with 8 spaces of indentation. Can’t remember where and when, though.