Skip to content
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

Add optional return_value_from_void_function rule using SwiftSyntax #3054

Merged
merged 26 commits into from
Feb 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
60bb35b
Add optional return_value_from_void_function rule using SwiftSyntax
marcelofabri Jan 26, 2020
5becf79
Use Script/bootstrap in CI
marcelofabri Jan 26, 2020
6390b96
Make SwiftSyntax optional
marcelofabri Jan 26, 2020
869b14c
Make SwiftSyntax optional in SPM
marcelofabri Jan 26, 2020
7527df6
Fix Package.swift
marcelofabri Jan 26, 2020
982eb42
Try again
marcelofabri Jan 26, 2020
727a917
Add minSwiftVersion
marcelofabri Jan 26, 2020
56e39e1
Fix thread sanitizer issue
marcelofabri Jan 26, 2020
5c3560c
Take 2
marcelofabri Jan 26, 2020
a7095dd
Fix false positive on nested computed variables
marcelofabri Jan 26, 2020
3449126
Remove support for Xcode 10.x
marcelofabri Jan 26, 2020
f4bb9e1
Fix rule description
marcelofabri Jan 26, 2020
c682522
Enable opt-in rule in configuration file
marcelofabri Feb 2, 2020
ab55188
Extract code into `SyntaxRule` protocol
marcelofabri Feb 2, 2020
71c784f
nit: make property private
marcelofabri Feb 2, 2020
e836c1c
Missing docs
marcelofabri Feb 2, 2020
416cd4e
Fix MasterRuleList.swift
marcelofabri Feb 2, 2020
e50984b
Update CHANGELOG
marcelofabri Feb 2, 2020
fb57841
Remove unused imports
marcelofabri Feb 2, 2020
aadbeee
Use Example type
marcelofabri Feb 2, 2020
aed9f47
Change rule kind to .idiomatic
marcelofabri Feb 3, 2020
9bde483
Update CHANGELOG
marcelofabri Feb 3, 2020
33e16b4
Bump deployment target to macOS 10.12
marcelofabri Feb 3, 2020
5b2c367
Simplify SyntaxRule.validate(file:visitor)
marcelofabri Feb 3, 2020
a0970e0
Make TSan happy
marcelofabri Feb 3, 2020
1e6dc6c
Use script/bootstrap in the README
marcelofabri Feb 8, 2020
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
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,6 @@
[submodule "Carthage/Checkouts/Yams"]
path = Carthage/Checkouts/Yams
url = https://github.com/jpsim/Yams.git
[submodule "SwiftSyntax"]
path = SwiftSyntax
url = https://github.com/apple/swift-syntax.git
1 change: 1 addition & 0 deletions .swiftlint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ opt_in_rules:
- reduce_into
- redundant_nil_coalescing
- redundant_type_annotation
- return_value_from_void_function
- single_test_class
- sorted_first_last
- sorted_imports
Expand Down
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
[Paul Taykalo](https://github.com/PaulTaykalo)
[JP Simard](https://github.com/jpsim)

* SwiftLint now imports [SwiftSyntax](https://github.com/apple/swift-syntax)
and requires Xcode 11.0 to build.
[Marcelo Fabri](https://github.com/marcelofabri)

#### Experimental

* None.
Expand All @@ -26,6 +30,14 @@
[ZevEisenberg](https://github.com/ZevEisenberg)
[#3040](https://github.com/realm/SwiftLint/pull/3040)

* Introduce a new `SyntaxRule` that enables writing rules using
[SwiftSyntax](https://github.com/apple/swift-syntax).
[Marcelo Fabri](https://github.com/marcelofabri)

* Add `return_value_from_void_function` opt-in rule to warn against using
`return <expression>` in a function that is `Void`.
[Marcelo Fabri](https://github.com/marcelofabri)

#### Bug Fixes

* Fix `discarded_notification_center_observer` false positives when
Expand Down
9 changes: 9 additions & 0 deletions Package.resolved
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,15 @@
"version": "0.29.0"
}
},
{
"package": "SwiftSyntax",
"repositoryURL": "https://github.com/apple/swift-syntax.git",
"state": {
"branch": null,
"revision": "3e3eb191fcdbecc6031522660c4ed6ce25282c25",
"version": "0.50100.0"
}
},
{
"package": "SwiftyTextTable",
"repositoryURL": "https://github.com/scottrhoyt/SwiftyTextTable.git",
Expand Down
15 changes: 13 additions & 2 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,17 @@ private let addCryptoSwift = false
private let addCryptoSwift = true
#endif

#if compiler(>=5.1.0)
private let addSwiftSyntax = true
#else
private let addSwiftSyntax = false
#endif

let package = Package(
name: "SwiftLint",
platforms: [
.macOS(.v10_12)
],
products: [
.executable(name: "swiftlint", targets: ["swiftlint"]),
.library(name: "SwiftLintFramework", targets: ["SwiftLintFramework"])
Expand All @@ -18,7 +27,8 @@ let package = Package(
.package(url: "https://github.com/jpsim/SourceKitten.git", .upToNextMinor(from: "0.29.0")),
.package(url: "https://github.com/jpsim/Yams.git", from: "2.0.0"),
.package(url: "https://github.com/scottrhoyt/SwiftyTextTable.git", from: "0.9.0"),
] + (addCryptoSwift ? [.package(url: "https://github.com/krzyzanowskim/CryptoSwift.git", .upToNextMinor(from: "1.0.0"))] : []),
] + (addCryptoSwift ? [.package(url: "https://github.com/krzyzanowskim/CryptoSwift.git", .upToNextMinor(from: "1.0.0"))] : []) +
(addSwiftSyntax ? [.package(url: "https://github.com/apple/swift-syntax.git", .exact("0.50100.0"))] : []),
targets: [
.target(
name: "swiftlint",
Expand All @@ -33,7 +43,8 @@ let package = Package(
dependencies: [
"SourceKittenFramework",
"Yams",
] + (addCryptoSwift ? ["CryptoSwift"] : [])
] + (addCryptoSwift ? ["CryptoSwift"] : []) +
(addSwiftSyntax ? ["SwiftSyntax"] : [])
),
.testTarget(
name: "SwiftLintFrameworkTests",
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ running it.
### Compiling from source:

You can also build from source by cloning this project and running
`git submodule update --init --recursive; make install` (Xcode 10.2 or later).
`script/bootstrap; make install` (Xcode 11.0 or later).

### Known Installation Issues On MacOS Before 10.14.4

Expand Down
36 changes: 36 additions & 0 deletions Source/SwiftLintFramework/Extensions/SwiftLintFile+Cache.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import Foundation
import SourceKittenFramework
#if canImport(SwiftSyntax)
import SwiftSyntax
#endif

private typealias FileCacheKey = Int
private var responseCache = Cache({ file -> [String: SourceKitRepresentable]? in
Expand Down Expand Up @@ -30,6 +33,20 @@ private var syntaxMapCache = Cache({ file in
private var syntaxKindsByLinesCache = Cache({ file in file.syntaxKindsByLine() })
private var syntaxTokensByLinesCache = Cache({ file in file.syntaxTokensByLine() })

#if canImport(SwiftSyntax)
private var syntaxCache = Cache({ file -> SourceFileSyntax? in
do {
if let path = file.path {
return try SyntaxParser.parse(URL(fileURLWithPath: path))
}

return try SyntaxParser.parse(source: file.contents)
} catch {
return nil
}
})
#endif

internal typealias AssertHandler = () -> Void

private var assertHandlers = [FileCacheKey: AssertHandler]()
Expand Down Expand Up @@ -158,6 +175,19 @@ extension SwiftLintFile {
return syntaxMap
}

#if canImport(SwiftSyntax)
internal var syntax: SourceFileSyntax {
guard let syntax = syntaxCache.get(self) else {
if let handler = assertHandler {
handler()
return SourceFileSyntax({ _ in })
}
queuedFatalError("Never call this for file that sourcekitd fails.")
}
return syntax
}
#endif

internal var syntaxTokensByLines: [[SwiftLintSyntaxToken]] {
guard let syntaxTokensByLines = syntaxTokensByLinesCache.get(self) else {
if let handler = assertHandler {
Expand Down Expand Up @@ -189,6 +219,9 @@ extension SwiftLintFile {
syntaxMapCache.invalidate(self)
syntaxTokensByLinesCache.invalidate(self)
syntaxKindsByLinesCache.invalidate(self)
#if canImport(SwiftSyntax)
syntaxCache.invalidate(self)
#endif
}

internal static func clearCaches() {
Expand All @@ -200,5 +233,8 @@ extension SwiftLintFile {
syntaxMapCache.clear()
syntaxTokensByLinesCache.clear()
syntaxKindsByLinesCache.clear()
#if canImport(SwiftSyntax)
syntaxCache.clear()
#endif
}
}
1 change: 1 addition & 0 deletions Source/SwiftLintFramework/Models/MasterRuleList.swift
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ public let masterRuleList = RuleList(rules: [
RequiredDeinitRule.self,
RequiredEnumCaseRule.self,
ReturnArrowWhitespaceRule.self,
ReturnValueFromVoidFunctionRule.self,
ShorthandOperatorRule.self,
SingleTestClassRule.self,
SortedFirstLastRule.self,
Expand Down
44 changes: 44 additions & 0 deletions Source/SwiftLintFramework/Protocols/SyntaxRule.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import Foundation
#if canImport(SwiftSyntax)
import SwiftSyntax
#endif

/// A rule that leverages the SwiftSyntax library.
public protocol SyntaxRule: Rule {}

#if canImport(SwiftSyntax)
/// A SwiftSyntax visitor that collects data to provide violations for a specific rule.
public protocol SyntaxRuleVisitor: SyntaxVisitor {
/// The rule that uses this visitor.
associatedtype Rule: SyntaxRule

/// Returns the violations that should be calculated based on data that was accumulated during the `visit` methods.
func violations(for rule: Rule, in file: SwiftLintFile) -> [StyleViolation]
}

public extension SyntaxRule {
/// Wraps computation of violations based on a visitor.
func validate<Visitor: SyntaxRuleVisitor>(file: SwiftLintFile,
visitor: Visitor) -> [StyleViolation] where Visitor.Rule == Self {
let lock = NSLock()
var visitor = visitor

// https://bugs.swift.org/browse/SR-11170
let work = DispatchWorkItem {
lock.lock()
file.syntax.walk(&visitor)
lock.unlock()
}
let thread = Thread {
work.perform()
}
thread.stackSize = 8 << 20 // 8 MB.
thread.start()
work.wait()

lock.lock()
defer { lock.unlock() }
return visitor.violations(for: self, in: file)
}
}
#endif
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import SourceKittenFramework
#if canImport(SwiftSyntax)
import SwiftSyntax
#endif

public struct ReturnValueFromVoidFunctionRule: ConfigurationProviderRule, SyntaxRule, OptInRule,
AutomaticTestableRule {
public var configuration = SeverityConfiguration(.warning)

public init() {}

public static let description = RuleDescription(
identifier: "return_value_from_void_function",
name: "Return Value from Void Function",
description: "Returning values from Void functions should be avoided.",
kind: .idiomatic,
minSwiftVersion: .fiveDotOne,
nonTriggeringExamples: ReturnValueFromVoidFunctionRuleExamples.nonTriggeringExamples,
triggeringExamples: ReturnValueFromVoidFunctionRuleExamples.triggeringExamples
)

public func validate(file: SwiftLintFile) -> [StyleViolation] {
#if canImport(SwiftSyntax)
return validate(file: file, visitor: ReturnVisitor())
#else
return []
#endif
}
}

#if canImport(SwiftSyntax)
private class ReturnVisitor: SyntaxRuleVisitor {
private var positions = [AbsolutePosition]()

func visit(_ node: ReturnStmtSyntax) -> SyntaxVisitorContinueKind {
if node.expression != nil,
let functionNode = node.enclosingFunction(),
functionNode.returnsVoid {
positions.append(node.positionAfterSkippingLeadingTrivia)
}
return .visitChildren
}

func violations(for rule: ReturnValueFromVoidFunctionRule, in file: SwiftLintFile) -> [StyleViolation] {
return positions.map { position in
StyleViolation(ruleDescription: type(of: rule).description,
severity: rule.configuration.severity,
location: Location(file: file, byteOffset: ByteCount(position.utf8Offset)))
}
}
}

private extension Syntax {
func enclosingFunction() -> FunctionDeclSyntax? {
if let node = self as? FunctionDeclSyntax {
return node
}

if self is ClosureExprSyntax || self is VariableDeclSyntax {
return nil
}

return parent?.enclosingFunction()
}
}

private extension FunctionDeclSyntax {
var returnsVoid: Bool {
if let type = signature.output?.returnType as? SimpleTypeIdentifierSyntax {
return type.name.text == "Void"
}

return signature.output?.returnType == nil
}
}
#endif
Loading