Skip to content

Fix build errors, test failures, and move to non-deprecated APIs in latest swift-syntax. #390

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 1 commit into from
Aug 21, 2022
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions Sources/SwiftFormat/Pipelines+Generated.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ class LintPipeline: SyntaxVisitor {
/// Creates a new lint pipeline.
init(context: Context) {
self.context = context
super.init(viewMode: .sourceAccurate)
}

override func visit(_ node: AsExprSyntax) -> SyntaxVisitorContinueKind {
Expand Down
2 changes: 1 addition & 1 deletion Sources/SwiftFormat/SyntaxValidatingVisitor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ fileprivate class SyntaxValidatingVisitor: SyntaxVisitor {
///
/// - Parameter syntax: The root of a tree of syntax nodes to check for compatibility.
public func _firstInvalidSyntaxPosition(in syntax: Syntax) -> AbsolutePosition? {
let visitor = SyntaxValidatingVisitor()
let visitor = SyntaxValidatingVisitor(viewMode: .sourceAccurate)
visitor.walk(syntax)
return visitor.invalidSyntaxStartPosition
}
1 change: 1 addition & 0 deletions Sources/SwiftFormatCore/RuleMask.swift
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ fileprivate class RuleStatusCollectionVisitor: SyntaxVisitor {
ignoreFileRegex = try! NSRegularExpression(pattern: ignoreFilePattern, options: [])

self.sourceLocationConverter = sourceLocationConverter
super.init(viewMode: .sourceAccurate)
}

// MARK: - Syntax Visitation Methods
Expand Down
1 change: 1 addition & 0 deletions Sources/SwiftFormatCore/SyntaxLintRule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,6 @@ open class SyntaxLintRule: SyntaxVisitor, Rule {
/// Creates a new rule in a given context.
public required init(context: Context) {
self.context = context
super.init(viewMode: .sourceAccurate)
}
}
4 changes: 2 additions & 2 deletions Sources/SwiftFormatCore/Trivia+Convenience.swift
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,8 @@ extension Trivia {
prev = .carriageReturnLineFeeds(l + r)
case (.verticalTabs(let l), .verticalTabs(let r)):
prev = .verticalTabs(l + r)
case (.garbageText(let l), .garbageText(let r)):
prev = .garbageText(l + r)
case (.unexpectedText(let l), .unexpectedText(let r)):
prev = .unexpectedText(l + r)
case (.formfeeds(let l), .formfeeds(let r)):
prev = .formfeeds(l + r)
default:
Expand Down
40 changes: 14 additions & 26 deletions Sources/SwiftFormatPrettyPrint/SequenceExprFolding.swift
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ extension SequenceExprSyntax {
case 1:
// A sequence with one element will not be changed by folding unless that
// element is a ternary expression.
return elements.first!.is(TernaryExprSyntax.self)
return elements.first!.is(UnresolvedTernaryExprSyntax.self)

case 2:
// A sequence with two elements might be changed by folding if the first
Expand All @@ -91,7 +91,7 @@ extension SequenceExprSyntax {
var elementsIterator = elements.makeIterator()
let first = elementsIterator.next()!
let second = elementsIterator.next()!
return first.is(TernaryExprSyntax.self)
return first.is(UnresolvedTernaryExprSyntax.self)
|| !(second.is(AsExprSyntax.self) || second.is(IsExprSyntax.self))

case 3:
Expand All @@ -100,7 +100,8 @@ extension SequenceExprSyntax {
// be more inclusive than it needs to be.)
return elements.contains {
$0.is(AsExprSyntax.self) || $0.is(IsExprSyntax.self)
|| $0.is(TernaryExprSyntax.self) || $0.is(AwaitExprSyntax.self)
|| $0.is(UnresolvedTernaryExprSyntax.self)
|| $0.is(AwaitExprSyntax.self)
|| $0.is(TryExprSyntax.self)
}

Expand Down Expand Up @@ -283,19 +284,6 @@ extension SequenceExprSyntax {
// (or begins with) an operator.
elements.append(expr)
elements.append(expr)
} else if let ternaryExpr = expr.as(TernaryExprSyntax.self) {
// In the compiler implementation, ternary expressions have their
// condition and false choice appear in the main sequence, with the true
// choice nested inside an `if-expr` with null values for the other two
// parts. In order to match that behavior, we extract the condition and
// false choice from the ternary and put them directly in the sequence.
// We can't null out those properties of a `TernaryExprSyntax` because
// they are non-optional, so instead we simply insert the original
// ternary in that slot and the rest of the algorithm will ignore
// everything except for the true choice.
normalizeExpression(ternaryExpr.conditionExpression, into: &elements)
elements.append(ExprSyntax(ternaryExpr))
normalizeExpression(ternaryExpr.secondChoice, into: &elements)
} else {
elements.append(expr)
}
Expand All @@ -317,7 +305,7 @@ extension SequenceExprSyntax {
case .binaryOperatorExpr(let binOpExpr):
let infixOpName = binOpExpr.operatorToken.text
return context.infixOperator(named: infixOpName)?.precedenceGroup
case .ternaryExpr:
case .unresolvedTernaryExpr:
return context.precedenceGroup(named: .ternary)
default:
// This branch will cover any potential new nodes that might arise in the
Expand Down Expand Up @@ -378,26 +366,26 @@ extension SequenceExprSyntax {
}

switch Syntax(op).as(SyntaxEnum.self) {
case .ternaryExpr(let ternaryExpr):
case .unresolvedTernaryExpr(let unresolvedTernaryExpr):
// Resolve the ternary expression by pulling the LHS and RHS that we
// actually want into it.

let result = ternaryExpr
.withConditionExpression(lhs)
.withSecondChoice(rhs)
let result = TernaryExprSyntax(
conditionExpression: lhs,
questionMark: unresolvedTernaryExpr.questionMark,
firstChoice: unresolvedTernaryExpr.firstChoice,
colonMark: unresolvedTernaryExpr.colonMark,
secondChoice: rhs)
return makeResultExpression(ExprSyntax(result))
case .asExpr, .isExpr:
// A normalized cast expression will have a regular LHS, then `as/is Type`
// as the operator *and* the RHS. We resolve it by returning a new
// sequence expression that discards the extra RHS.
let result = SyntaxFactory.makeSequenceExpr(
elements: SyntaxFactory.makeExprList([lhs, op]))
let result = SequenceExprSyntax(elements: ExprListSyntax([lhs, op]))
return makeResultExpression(ExprSyntax(result))
default:
// For any other binary operator, we simply return a sequence that has the
// three elements.
let result = SyntaxFactory.makeSequenceExpr(
elements: SyntaxFactory.makeExprList([lhs, op, rhs]))
let result = SequenceExprSyntax(elements: ExprListSyntax([lhs, op, rhs]))
return makeResultExpression(ExprSyntax(result))
}
}
Expand Down
27 changes: 13 additions & 14 deletions Sources/SwiftFormatPrettyPrint/TokenStreamCreator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor {
self.config = configuration
self.operatorContext = operatorContext
self.maxlinelength = config.lineLength
super.init(viewMode: .sourceAccurate)
}

func makeStream(from node: Syntax) -> [Token] {
Expand Down Expand Up @@ -486,14 +487,18 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor {

// MARK: - Control flow statement nodes

override func visit(_ node: LabeledStmtSyntax) -> SyntaxVisitorContinueKind {
after(node.labelColon, tokens: .space)
return .visitChildren
}

override func visit(_ node: IfStmtSyntax) -> SyntaxVisitorContinueKind {
// There may be a consistent breaking group around this node, see `CodeBlockItemSyntax`. This
// group is necessary so that breaks around and inside of the conditions aren't forced to break
// when the if-stmt spans multiple lines.
before(node.conditions.firstToken, tokens: .open)
after(node.conditions.lastToken, tokens: .close)

after(node.labelColon, tokens: .space)
after(node.ifKeyword, tokens: .space)

// Add break groups, using open continuation breaks, around any conditions after the first so
Expand Down Expand Up @@ -553,8 +558,6 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor {
}

override func visit(_ node: ForInStmtSyntax) -> SyntaxVisitorContinueKind {
after(node.labelColon, tokens: .space)

// If we have a `(try) await` clause, allow breaking after the `for` so that the `(try) await`
// can fall onto the next line if needed, and if both `try await` are present, keep them
// together. Otherwise, keep `for` glued to the token after it so that we break somewhere later
Expand Down Expand Up @@ -589,7 +592,6 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor {
}

override func visit(_ node: WhileStmtSyntax) -> SyntaxVisitorContinueKind {
after(node.labelColon, tokens: .space)
after(node.whileKeyword, tokens: .space)

// Add break groups, using open continuation breaks, around any conditions after the first so
Expand All @@ -611,7 +613,6 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor {
}

override func visit(_ node: RepeatWhileStmtSyntax) -> SyntaxVisitorContinueKind {
after(node.labelColon, tokens: .space)
arrangeBracesAndContents(of: node.body, contentsKeyPath: \.statements)

if config.lineBreakBeforeControlFlowKeywords {
Expand All @@ -631,7 +632,6 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor {
}

override func visit(_ node: DoStmtSyntax) -> SyntaxVisitorContinueKind {
after(node.labelColon, tokens: .space)
arrangeBracesAndContents(of: node.body, contentsKeyPath: \.statements)
return .visitChildren
}
Expand Down Expand Up @@ -686,7 +686,6 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor {
}

override func visit(_ node: SwitchStmtSyntax) -> SyntaxVisitorContinueKind {
after(node.labelColon, tokens: .space)
before(node.switchKeyword, tokens: .open)
after(node.switchKeyword, tokens: .space)
before(node.leftBrace, tokens: .break(.reset))
Expand Down Expand Up @@ -2498,14 +2497,14 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor {
/// same place but still let surrounding formatting occur somewhat as expected.
private func appendTrailingTrivia(_ token: TokenSyntax) {
let trailingTrivia = Array(token.trailingTrivia)
guard let lastGarbageIndex = trailingTrivia.lastIndex(where: { $0.isGarbageText }) else {
guard let lastUnexpectedIndex = trailingTrivia.lastIndex(where: { $0.isUnexpectedText }) else {
return
}

var verbatimText = ""
for piece in trailingTrivia[...lastGarbageIndex] {
for piece in trailingTrivia[...lastUnexpectedIndex] {
switch piece {
case .shebang, .garbageText, .spaces, .tabs, .formfeeds, .verticalTabs:
case .shebang, .unexpectedText, .spaces, .tabs, .formfeeds, .verticalTabs:
piece.write(to: &verbatimText)
default:
// The implementation of the lexer today ensures that newlines, carriage returns, and
Expand Down Expand Up @@ -2956,7 +2955,7 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor {
}
}

case .shebang(let text), .garbageText(let text):
case .shebang(let text), .unexpectedText(let text):
// Garbage text in leading trivia might be something meaningful that would be disruptive to
// throw away when formatting the file, like a hashbang line or Unicode byte-order marker at
// the beginning of a file, or source control conflict markers. Keep it as verbatim text so
Expand Down Expand Up @@ -3610,10 +3609,10 @@ class CommentMovingRewriter: SyntaxRewriter {
}

extension TriviaPiece {
/// True if the trivia piece is garbage text.
fileprivate var isGarbageText: Bool {
/// True if the trivia piece is unexpected text.
fileprivate var isUnexpectedText: Bool {
switch self {
case .garbageText: return true
case .unexpectedText: return true
default: return false
}
}
Expand Down
15 changes: 9 additions & 6 deletions Sources/SwiftFormatRules/DoNotUseSemicolons.swift
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,16 @@ public final class DoNotUseSemicolons: SyntaxFormatRule {
// If there's a semicolon, diagnose and remove it.
if let semicolon = item.semicolon {

// Exception: do not remove the semicolon if it is separating a 'do' statement from a 'while' statement.
if Syntax(item).as(CodeBlockItemSyntax.self)?.children.first?.is(DoStmtSyntax.self) == true,
// Exception: do not remove the semicolon if it is separating a 'do' statement from a
// 'while' statement.
if Syntax(item).as(CodeBlockItemSyntax.self)?
.children(viewMode: .sourceAccurate).first?.is(DoStmtSyntax.self) == true,
idx < node.count - 1
{
let nextItem = node.children[node.children.index(after: item.index)]
let children = node.children(viewMode: .sourceAccurate)
let nextItem = children[children.index(after: item.index)]
if Syntax(nextItem).as(CodeBlockItemSyntax.self)?
.children.first?.is(WhileStmtSyntax.self) == true
.children(viewMode: .sourceAccurate).first?.is(WhileStmtSyntax.self) == true
{
continue
}
Expand All @@ -96,11 +99,11 @@ public final class DoNotUseSemicolons: SyntaxFormatRule {
}

public override func visit(_ node: CodeBlockItemListSyntax) -> Syntax {
return Syntax(nodeByRemovingSemicolons(from: node, nodeCreator: SyntaxFactory.makeCodeBlockItemList))
return Syntax(nodeByRemovingSemicolons(from: node, nodeCreator: CodeBlockItemListSyntax.init))
}

public override func visit(_ node: MemberDeclListSyntax) -> Syntax {
return Syntax(nodeByRemovingSemicolons(from: node, nodeCreator: SyntaxFactory.makeMemberDeclList))
return Syntax(nodeByRemovingSemicolons(from: node, nodeCreator: MemberDeclListSyntax.init))
}
}

Expand Down
6 changes: 3 additions & 3 deletions Sources/SwiftFormatRules/FileScopedDeclarationPrivacy.swift
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public final class FileScopedDeclarationPrivacy: SyntaxFormatRule {
return codeBlockItem
}
}
return SyntaxFactory.makeCodeBlockItemList(newCodeBlockItems)
return CodeBlockItemListSyntax(newCodeBlockItems)
}

/// Returns a new `IfConfigDeclSyntax` equivalent to the given node, but where any file-scoped
Expand All @@ -116,7 +116,7 @@ public final class FileScopedDeclarationPrivacy: SyntaxFormatRule {
return clause
}
}
return ifConfigDecl.withClauses(SyntaxFactory.makeIfConfigClauseList(newClauses))
return ifConfigDecl.withClauses(IfConfigClauseListSyntax(newClauses))
}

/// Returns a rewritten version of the given declaration if its modifier list contains `private`
Expand Down Expand Up @@ -163,7 +163,7 @@ public final class FileScopedDeclarationPrivacy: SyntaxFormatRule {
}
return modifier
}
return factory(SyntaxFactory.makeModifierList(newModifiers))
return factory(ModifierListSyntax(newModifiers))
}
}

Expand Down
6 changes: 3 additions & 3 deletions Sources/SwiftFormatRules/FullyIndirectEnum.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,11 @@ public final class FullyIndirectEnum: SyntaxFormatRule {
newEnumDecl = node
}

let newModifier = SyntaxFactory.makeDeclModifier(
name: SyntaxFactory.makeIdentifier(
let newModifier = DeclModifierSyntax(
name: TokenSyntax.identifier(
"indirect", leadingTrivia: leadingTrivia, trailingTrivia: .spaces(1)), detail: nil)

let newMemberBlock = node.members.withMembers(SyntaxFactory.makeMemberDeclList(newMembers))
let newMemberBlock = node.members.withMembers(MemberDeclListSyntax(newMembers))
return DeclSyntax(newEnumDecl.addModifier(newModifier).withMembers(newMemberBlock))
}

Expand Down
2 changes: 1 addition & 1 deletion Sources/SwiftFormatRules/GroupNumericLiterals.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public final class GroupNumericLiterals: SyntaxFormatRule {

newDigits = isNegative ? "-" + newDigits : newDigits
let result = node.withDigits(
SyntaxFactory.makeIntegerLiteral(
TokenSyntax.integerLiteral(
newDigits,
leadingTrivia: node.digits.leadingTrivia,
trailingTrivia: node.digits.trailingTrivia))
Expand Down
1 change: 1 addition & 0 deletions Sources/SwiftFormatRules/ImportsXCTestVisitor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ fileprivate class ImportsXCTestVisitor: SyntaxVisitor {

init(context: Context) {
self.context = context
super.init(viewMode: .sourceAccurate)
}

override func visit(_ node: SourceFileSyntax) -> SyntaxVisitorContinueKind {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,8 @@ extension ModifierListSyntax {

/// Returns a foramatted declaration modifier token with the given name.
func createModifierToken(name: String) -> DeclModifierSyntax {
let id = SyntaxFactory.makeIdentifier(name, trailingTrivia: .spaces(1))
let newModifier = SyntaxFactory.makeDeclModifier(
name: id, detail: nil)
let id = TokenSyntax.identifier(name, trailingTrivia: .spaces(1))
let newModifier = DeclModifierSyntax(name: id, detail: nil)
return newModifier
}

Expand Down Expand Up @@ -86,7 +85,7 @@ extension ModifierListSyntax {
leadingTrivia: [],
trailingTrivia: .spaces(1))
newModifiers.insert(formattedMod, at: 0)
return SyntaxFactory.makeModifierList(newModifiers)
return ModifierListSyntax(newModifiers)
} else {
return inserting(modifier, at: index)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public final class NoAccessLevelOnExtensionDeclaration: SyntaxFormatRule {
accessKeywordToAdd = accessKeyword
}

let newMembers = SyntaxFactory.makeMemberDeclBlock(
let newMembers = MemberDeclBlockSyntax(
leftBrace: node.members.leftBrace,
members: addMemberAccessKeywords(memDeclBlock: node.members, keyword: accessKeywordToAdd),
rightBrace: node.members.rightBrace)
Expand Down Expand Up @@ -96,7 +96,7 @@ public final class NoAccessLevelOnExtensionDeclaration: SyntaxFormatRule {
else { continue }
newMembers.append(memberItem.withDecl(newDecl))
}
return SyntaxFactory.makeMemberDeclList(newMembers)
return MemberDeclListSyntax(newMembers)
}
}

Expand Down
Loading