Skip to content

Use a Set to track visited exprs. #198

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

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 5 additions & 12 deletions Sources/SwiftFormatPrettyPrint/TokenStreamCreator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor {

/// Lists the expressions that have been visited, from the outermost expression, where contextual
/// breaks and start/end contextual breaking tokens have been inserted.
private var preVisitedExprs = [ExprSyntax]()
private var preVisitedExprs = Set<ExprSyntax>()

/// Lists the tokens that are the closing or final delimiter of a node that shouldn't be split
/// from the preceding token. When breaks are inserted around compound expressions, the breaks are
Expand Down Expand Up @@ -3181,20 +3181,13 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor {
/// necessary for contextual breaking throughout the expression. Records the nodes that were
/// visited so that they can be skipped later.
private func preVisitInsertingContextualBreaks<T: ExprSyntaxProtocol & Equatable>(_ expr: T) {
if !hasPreVisited(expr) {
let (visited, _, _) = insertContextualBreaks(ExprSyntax(expr), isTopLevel: true)
preVisitedExprs.append(contentsOf: visited)
let exprSyntax = ExprSyntax(expr)
if !preVisitedExprs.contains(exprSyntax) {
let (visited, _, _) = insertContextualBreaks(exprSyntax, isTopLevel: true)
preVisitedExprs.formUnion(visited)
}
}

/// Returns whether the given expression node has been pre-visited, from a parent expression.
private func hasPreVisited<T: ExprSyntaxProtocol & Equatable>(_ expr: T) -> Bool {
for item in preVisitedExprs {
if item == ExprSyntax(expr) { return true }
}
return false
}

/// Recursively visits nested expressions from the given expression inserting contextual breaking
/// tokens. When visiting an expression node, `preVisitInsertingContextualBreaks(_:)` should be
/// called instead of this helper.
Expand Down