-
Notifications
You must be signed in to change notification settings - Fork 247
[Lint] Add a rule to detect and transform [<Type>]()
into literal …
#617
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
allevato
merged 6 commits into
swiftlang:main
from
xedin:upstream-literal-array-init-rewrite
Sep 14, 2023
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
5a48d08
[Format/Lint] Add a rule to detect and transform `[<Type>]()` into l…
xedin cef2c6e
Make AlwaysUseLiteralForEmptyArrayInit rule opt-in and disabled by de…
xedin afaa91d
[Lint/Format] Extend empty literal initialization rule to support dic…
xedin 7463405
[Lint/Format] Rename `AlwaysUseLiteralForEmptyArrayInit` into `Always…
xedin 2ca2c46
[Lint/Format] Extend empty literal rewritting rule to support paramet…
xedin 9ab323e
[Tests] Add a few tests to make sure that empty collection init rule …
xedin 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
208 changes: 208 additions & 0 deletions
208
Sources/SwiftFormat/Rules/AlwaysUseLiteralForEmptyCollectionInit.swift
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,208 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the Swift.org open source project | ||
// | ||
// Copyright (c) 2014 - 2023 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 Foundation | ||
import SwiftSyntax | ||
import SwiftParser | ||
|
||
/// Never use `[<Type>]()` syntax. In call sites that should be replaced with `[]`, | ||
/// for initializations use explicit type combined with empty array literal `let _: [<Type>] = []` | ||
/// Static properties of a type that return that type should not include a reference to their type. | ||
/// | ||
/// Lint: Non-literal empty array initialization will yield a lint error. | ||
/// Format: All invalid use sites would be related with empty literal (with or without explicit type annotation). | ||
@_spi(Rules) | ||
public final class AlwaysUseLiteralForEmptyCollectionInit : SyntaxFormatRule { | ||
public override class var isOptIn: Bool { return true } | ||
|
||
public override func visit(_ node: PatternBindingSyntax) -> PatternBindingSyntax { | ||
guard let initializer = node.initializer, | ||
let type = isRewritable(initializer) else { | ||
return node | ||
} | ||
|
||
if let type = type.as(ArrayTypeSyntax.self) { | ||
return rewrite(node, type: type) | ||
} | ||
|
||
if let type = type.as(DictionaryTypeSyntax.self) { | ||
return rewrite(node, type: type) | ||
} | ||
|
||
return node | ||
} | ||
|
||
public override func visit(_ param: FunctionParameterSyntax) -> FunctionParameterSyntax { | ||
guard let initializer = param.defaultValue, | ||
let type = isRewritable(initializer) else { | ||
return param | ||
} | ||
|
||
if let type = type.as(ArrayTypeSyntax.self) { | ||
return rewrite(param, type: type) | ||
} | ||
|
||
if let type = type.as(DictionaryTypeSyntax.self) { | ||
return rewrite(param, type: type) | ||
} | ||
|
||
return param | ||
} | ||
|
||
/// Check whether the initializer is `[<Type>]()` and, if so, it could be rewritten to use an empty collection literal. | ||
/// Return a type of the collection. | ||
public func isRewritable(_ initializer: InitializerClauseSyntax) -> TypeSyntax? { | ||
guard let initCall = initializer.value.as(FunctionCallExprSyntax.self), | ||
initCall.arguments.isEmpty else { | ||
return nil | ||
} | ||
|
||
if let arrayLiteral = initCall.calledExpression.as(ArrayExprSyntax.self) { | ||
return getLiteralType(arrayLiteral) | ||
} | ||
|
||
if let dictLiteral = initCall.calledExpression.as(DictionaryExprSyntax.self) { | ||
return getLiteralType(dictLiteral) | ||
} | ||
|
||
return nil | ||
} | ||
|
||
private func rewrite(_ node: PatternBindingSyntax, | ||
type: ArrayTypeSyntax) -> PatternBindingSyntax { | ||
var replacement = node | ||
|
||
diagnose(node, type: type) | ||
|
||
if replacement.typeAnnotation == nil { | ||
// Drop trailing trivia after pattern because ':' has to appear connected to it. | ||
replacement.pattern = node.pattern.with(\.trailingTrivia, []) | ||
// Add explicit type annotiation: ': [<Type>]` | ||
replacement.typeAnnotation = .init(type: type.with(\.leadingTrivia, .space) | ||
.with(\.trailingTrivia, .space)) | ||
} | ||
|
||
let initializer = node.initializer! | ||
let emptyArrayExpr = ArrayExprSyntax(elements: ArrayElementListSyntax.init([])) | ||
|
||
// Replace initializer call with empty array literal: `[<Type>]()` -> `[]` | ||
replacement.initializer = initializer.with(\.value, ExprSyntax(emptyArrayExpr)) | ||
|
||
return replacement | ||
} | ||
|
||
private func rewrite(_ node: PatternBindingSyntax, | ||
type: DictionaryTypeSyntax) -> PatternBindingSyntax { | ||
var replacement = node | ||
|
||
diagnose(node, type: type) | ||
|
||
if replacement.typeAnnotation == nil { | ||
// Drop trailing trivia after pattern because ':' has to appear connected to it. | ||
replacement.pattern = node.pattern.with(\.trailingTrivia, []) | ||
// Add explicit type annotiation: ': [<Type>]` | ||
replacement.typeAnnotation = .init(type: type.with(\.leadingTrivia, .space) | ||
.with(\.trailingTrivia, .space)) | ||
} | ||
|
||
let initializer = node.initializer! | ||
// Replace initializer call with empty dictionary literal: `[<Type>]()` -> `[]` | ||
replacement.initializer = initializer.with(\.value, ExprSyntax(getEmptyDictionaryLiteral())) | ||
|
||
return replacement | ||
} | ||
|
||
private func rewrite(_ param: FunctionParameterSyntax, | ||
type: ArrayTypeSyntax) -> FunctionParameterSyntax { | ||
guard let initializer = param.defaultValue else { | ||
return param | ||
} | ||
|
||
emitDiagnostic(replace: "\(initializer.value)", with: "[]", on: initializer.value) | ||
return param.with(\.defaultValue, initializer.with(\.value, getEmptyArrayLiteral())) | ||
} | ||
|
||
private func rewrite(_ param: FunctionParameterSyntax, | ||
type: DictionaryTypeSyntax) -> FunctionParameterSyntax { | ||
guard let initializer = param.defaultValue else { | ||
return param | ||
} | ||
|
||
emitDiagnostic(replace: "\(initializer.value)", with: "[:]", on: initializer.value) | ||
return param.with(\.defaultValue, initializer.with(\.value, getEmptyDictionaryLiteral())) | ||
} | ||
|
||
private func diagnose(_ node: PatternBindingSyntax, type: ArrayTypeSyntax) { | ||
var withFixIt = "[]" | ||
if node.typeAnnotation == nil { | ||
withFixIt = ": \(type) = []" | ||
} | ||
|
||
let initCall = node.initializer!.value | ||
emitDiagnostic(replace: "\(initCall)", with: withFixIt, on: initCall) | ||
} | ||
|
||
private func diagnose(_ node: PatternBindingSyntax, type: DictionaryTypeSyntax) { | ||
var withFixIt = "[:]" | ||
if node.typeAnnotation == nil { | ||
withFixIt = ": \(type) = [:]" | ||
} | ||
|
||
let initCall = node.initializer!.value | ||
emitDiagnostic(replace: "\(initCall)", with: withFixIt, on: initCall) | ||
} | ||
|
||
private func emitDiagnostic(replace: String, with fixIt: String, on: ExprSyntax?) { | ||
diagnose(.refactorIntoEmptyLiteral(replace: replace, with: fixIt), on: on) | ||
} | ||
|
||
private func getLiteralType(_ arrayLiteral: ArrayExprSyntax) -> TypeSyntax? { | ||
guard let elementExpr = arrayLiteral.elements.firstAndOnly, | ||
elementExpr.is(ArrayElementSyntax.self) else { | ||
return nil | ||
} | ||
|
||
var parser = Parser(arrayLiteral.description) | ||
let elementType = TypeSyntax.parse(from: &parser) | ||
|
||
guard !elementType.hasError, elementType.is(ArrayTypeSyntax.self) else { | ||
return nil | ||
} | ||
|
||
return elementType | ||
} | ||
|
||
private func getLiteralType(_ dictLiteral: DictionaryExprSyntax) -> TypeSyntax? { | ||
var parser = Parser(dictLiteral.description) | ||
let elementType = TypeSyntax.parse(from: &parser) | ||
|
||
guard !elementType.hasError, elementType.is(DictionaryTypeSyntax.self) else { | ||
return nil | ||
} | ||
|
||
return elementType | ||
} | ||
|
||
private func getEmptyArrayLiteral() -> ExprSyntax { | ||
ExprSyntax(ArrayExprSyntax(elements: ArrayElementListSyntax.init([]))) | ||
} | ||
|
||
private func getEmptyDictionaryLiteral() -> ExprSyntax { | ||
ExprSyntax(DictionaryExprSyntax(content: .colon(.colonToken()))) | ||
} | ||
} | ||
|
||
extension Finding.Message { | ||
public static func refactorIntoEmptyLiteral(replace: String, with: String) -> Finding.Message { | ||
"replace '\(replace)' with '\(with)'" | ||
} | ||
} |
Oops, something went wrong.
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.
Do you think we need
Init
in the name here? Not that other rule names aren't already a mouthful, but it seems like we could drop it and have the same meaning.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.
I think it’s useful to have it in the name to indicate that this is for initialization only, but I am open to suggestions if you have a better name in mind :)
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.
I can't think of anything better off the top of my head, so if you think it's helpful to disambiguate, I'm ok with it 🙂
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.
We can always change it later if something better comes up :)