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 ability for SwiftLint to lint files with full type-checked AST awareness #2379

Merged
merged 20 commits into from
Sep 2, 2018
Merged
Show file tree
Hide file tree
Changes from 14 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
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,20 @@
configuration files.
[JP Simard](https://github.com/jpsim)

#### Experimental

* Add a new `swiftlint analyze` command which can lint Swift files using the
full type-checked AST. Rules of the `AnalyzerRule` type will be added over
time. The compiler log path containing the clean `swiftc` build command
invocation (incremental builds will fail) must be passed to `analyze` via
the `--compiler-log-path` flag.
e.g. `--compiler-log-path /path/to/xcodebuild.log`
[JP Simard](https://github.com/jpsim)

* Add a new opt-in `explicit_self` analyzer rule to enforce the use of explicit
references to `self.` when accessing instance variables or functions.
[JP Simard](https://github.com/jpsim)

#### Enhancements

* Improve performance of `line_length` and
Expand Down
18 changes: 16 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ swiftlint(
$ swiftlint help
Available commands:

analyze [Experimental] Run analysis rules
autocorrect Automatically correct warnings and errors
generate-docs Generates markdown documentation for all rules
help Display general or command-specific help
Expand All @@ -153,8 +154,8 @@ Available commands:
Run `swiftlint` in the directory containing the Swift files to lint. Directories
will be searched recursively.

To specify a list of files when using `lint` or `autocorrect` (like the list of
files modified by Xcode specified by the
To specify a list of files when using `lint`, `autocorrect` or `analyze`
(like the list of files modified by Xcode specified by the
[`ExtraBuildPhase`](https://github.com/norio-nomura/ExtraBuildPhase) Xcode
plugin, or modified files in the working tree based on `git ls-files -m`), you
can do so by passing the option `--use-script-input-files` and setting the
Expand Down Expand Up @@ -322,6 +323,8 @@ excluded: # paths to ignore during linting. Takes precedence over `included`.
- Source/ExcludedFolder
- Source/ExcludedFile.swift
- Source/*/ExcludedFile.swift # Exclude files with a wildcard
analyzer_rules: # Rules run by `swiftlint analyze` (experimental)
- explicit_self
jpsim marked this conversation as resolved.
Show resolved Hide resolved

# configurable rules can be customized from this configuration file
# binary rules can set their severity level
Expand Down Expand Up @@ -437,6 +440,17 @@ Standard linting is disabled while correcting because of the high likelihood of
violations (or their offsets) being incorrect after modifying a file while
applying corrections.

### Analyze (experimental)

The _experimental_ `swiftlint analyze` command can lint Swift files using the
full type-checked AST. The compiler log path containing the clean `swiftc` build
command invocation (incremental builds will fail) must be passed to `analyze`
via the `--compiler-log-path` flag.
e.g. `--compiler-log-path /path/to/xcodebuild.log`

This command and related code in SwiftLint is subject to substantial changes at
jpsim marked this conversation as resolved.
Show resolved Hide resolved
any time while this feature is marked as experimental.

## License

[MIT licensed.](LICENSE)
Expand Down
58 changes: 58 additions & 0 deletions Rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
* [Explicit ACL](#explicit-acl)
* [Explicit Enum Raw Value](#explicit-enum-raw-value)
* [Explicit Init](#explicit-init)
* [Explicit Self](#explicit-self)
* [Explicit Top Level ACL](#explicit-top-level-acl)
* [Explicit Type Interface](#explicit-type-interface)
* [Extension Access Modifier](#extension-access-modifier)
Expand Down Expand Up @@ -5344,6 +5345,63 @@ func foo() -> [String] {



## Explicit Self

Identifier | Enabled by default | Supports autocorrection | Kind | Minimum Swift Compiler Version
--- | --- | --- | --- | ---
`explicit_self` | Disabled | Yes | style | 3.0.0
jpsim marked this conversation as resolved.
Show resolved Hide resolved

Instance variables and functions should be explicitly accessed with 'self.'.

### Examples

<details>
<summary>Non Triggering Examples</summary>

```swift
struct A {
func f1() {}
func f2() {
self.f1()
}
}
```

```swift
struct A {
let p1: Int
func f1() {
_ = self.p1
}
}
```

</details>
<details>
<summary>Triggering Examples</summary>

```swift
struct A {
func f1() {}
func f2() {
↓f1()
}
}
```

```swift
struct A {
let p1: Int
func f1() {
_ = ↓p1
}
}
```

</details>



## Explicit Top Level ACL

Identifier | Enabled by default | Supports autocorrection | Kind | Minimum Swift Compiler Version
Expand Down
12 changes: 8 additions & 4 deletions Source/SwiftLintFramework/Extensions/Configuration+Parsing.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ extension Configuration {
case warningThreshold = "warning_threshold"
case whitelistRules = "whitelist_rules"
case indentation = "indentation"
case analyzerRules = "analyzer_rules"
}

private static func validKeys(ruleList: RuleList) -> [String] {
Expand All @@ -29,7 +30,8 @@ extension Configuration {
.useNestedConfigs,
.warningThreshold,
.whitelistRules,
.indentation
.indentation,
.analyzerRules
].map({ $0.rawValue }) + ruleList.allValidIdentifiers()
}

Expand Down Expand Up @@ -65,6 +67,7 @@ extension Configuration {

let disabledRules = defaultStringArray(dict[Key.disabledRules.rawValue])
let whitelistRules = defaultStringArray(dict[Key.whitelistRules.rawValue])
let analyzerRules = defaultStringArray(dict[Key.analyzerRules.rawValue])
let included = defaultStringArray(dict[Key.included.rawValue])
let excluded = defaultStringArray(dict[Key.excluded.rawValue])
let indentation = Configuration.getIndentationLogIfInvalid(from: dict)
Expand All @@ -88,6 +91,7 @@ extension Configuration {
optInRules: optInRules,
enableAllRules: enableAllRules,
whitelistRules: whitelistRules,
analyzerRules: analyzerRules,
included: included,
excluded: excluded,
warningThreshold: dict[Key.warningThreshold.rawValue] as? Int,
Expand All @@ -103,6 +107,7 @@ extension Configuration {
optInRules: [String],
enableAllRules: Bool,
whitelistRules: [String],
analyzerRules: [String],
included: [String],
excluded: [String],
warningThreshold: Int?,
Expand All @@ -112,7 +117,6 @@ extension Configuration {
swiftlintVersion: String?,
cachePath: String?,
indentation: IndentationStyle) {

let rulesMode: RulesMode
if enableAllRules {
rulesMode = .allEnabled
Expand All @@ -123,9 +127,9 @@ extension Configuration {
"with '\(Key.whitelistRules.rawValue)'")
return nil
}
rulesMode = .whitelisted(whitelistRules)
rulesMode = .whitelisted(whitelistRules + analyzerRules)
} else {
rulesMode = .default(disabled: disabledRules, optIn: optInRules)
rulesMode = .default(disabled: disabledRules, optIn: optInRules + analyzerRules)
}

self.init(rulesMode: rulesMode,
Expand Down
28 changes: 19 additions & 9 deletions Source/SwiftLintFramework/Models/Linter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ private extension Rule {
}

func lint(file: File, regions: [Region], benchmark: Bool,
superfluousDisableCommandRule: SuperfluousDisableCommandRule?) -> LintResult? {
superfluousDisableCommandRule: SuperfluousDisableCommandRule?,
compilerArguments: [String]) -> LintResult? {
if !(self is SourceKitFreeRule) && file.sourcekitdFailed {
return nil
}
Expand All @@ -57,10 +58,10 @@ private extension Rule {
let ruleTime: (String, Double)?
if benchmark {
let start = Date()
violations = validate(file: file)
violations = validate(file: file, compilerArguments: compilerArguments)
ruleTime = (ruleID, -start.timeIntervalSinceNow)
} else {
violations = validate(file: file)
violations = validate(file: file, compilerArguments: compilerArguments)
ruleTime = nil
}

Expand Down Expand Up @@ -104,6 +105,7 @@ public struct Linter {
private let rules: [Rule]
private let cache: LinterCache?
private let configuration: Configuration
private let compilerArguments: [String]

public var styleViolations: [StyleViolation] {
return getStyleViolations().0
Expand All @@ -114,7 +116,6 @@ public struct Linter {
}

private func getStyleViolations(benchmark: Bool = false) -> ([StyleViolation], [(id: String, time: Double)]) {

if let cached = cachedStyleViolations(benchmark: benchmark) {
return cached
}
Expand All @@ -128,7 +129,8 @@ public struct Linter {
}) as? SuperfluousDisableCommandRule
let validationResults = rules.parallelFlatMap {
$0.lint(file: self.file, regions: regions, benchmark: benchmark,
superfluousDisableCommandRule: superfluousDisableCommandRule)
superfluousDisableCommandRule: superfluousDisableCommandRule,
compilerArguments: self.compilerArguments)
}
let violations = validationResults.flatMap { $0.violations }
let ruleTimes = validationResults.compactMap { $0.ruleTime }
Expand Down Expand Up @@ -170,11 +172,19 @@ public struct Linter {
return (cachedViolations, ruleTimes)
}

public init(file: File, configuration: Configuration = Configuration()!, cache: LinterCache? = nil) {
public init(file: File, configuration: Configuration = Configuration()!, cache: LinterCache? = nil,
compilerArguments: [String] = []) {
self.file = file
self.cache = cache
self.configuration = configuration
rules = configuration.rules
self.cache = cache
self.compilerArguments = compilerArguments
self.rules = configuration.rules.filter { rule in
if compilerArguments.isEmpty {
return !(rule is AnalyzerRule)
} else {
return rule is AnalyzerRule
}
}
}

public func correct() -> [Correction] {
Expand All @@ -184,7 +194,7 @@ public struct Linter {

var corrections = [Correction]()
for rule in rules.compactMap({ $0 as? CorrectableRule }) {
let newCorrections = rule.correct(file: file)
let newCorrections = rule.correct(file: file, compilerArguments: compilerArguments)
corrections += newCorrections
if !newCorrections.isEmpty {
file.invalidateCache()
Expand Down
1 change: 1 addition & 0 deletions Source/SwiftLintFramework/Models/MasterRuleList.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ public let masterRuleList = RuleList(rules: [
ExplicitACLRule.self,
ExplicitEnumRawValueRule.self,
ExplicitInitRule.self,
ExplicitSelfRule.self,
ExplicitTopLevelACLRule.self,
ExplicitTypeInterfaceRule.self,
ExtensionAccessModifierRule.self,
Expand Down
5 changes: 4 additions & 1 deletion Source/SwiftLintFramework/Models/RuleDescription.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ public struct RuleDescription: Equatable {
public let corrections: [String: String]
public let deprecatedAliases: Set<String>
public let minSwiftVersion: SwiftVersion
public let requiresFileOnDisk: Bool

public var consoleDescription: String { return "\(name) (\(identifier)): \(description)" }

Expand All @@ -19,7 +20,8 @@ public struct RuleDescription: Equatable {
minSwiftVersion: SwiftVersion = .three,
nonTriggeringExamples: [String] = [], triggeringExamples: [String] = [],
corrections: [String: String] = [:],
deprecatedAliases: Set<String> = []) {
deprecatedAliases: Set<String> = [],
requiresFileOnDisk: Bool = false) {
self.identifier = identifier
self.name = name
self.description = description
Expand All @@ -29,6 +31,7 @@ public struct RuleDescription: Equatable {
self.corrections = corrections
self.deprecatedAliases = deprecatedAliases
self.minSwiftVersion = minSwiftVersion
self.requiresFileOnDisk = requiresFileOnDisk
}
}

Expand Down
26 changes: 26 additions & 0 deletions Source/SwiftLintFramework/Protocols/Rule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,16 @@ public protocol Rule {
init() // Rules need to be able to be initialized with default values
init(configuration: Any) throws

func validate(file: File, compilerArguments: [String]) -> [StyleViolation]
func validate(file: File) -> [StyleViolation]
func isEqualTo(_ rule: Rule) -> Bool
}

extension Rule {
public func validate(file: File, compilerArguments: [String]) -> [StyleViolation] {
return validate(file: file)
}

public func isEqualTo(_ rule: Rule) -> Bool {
return type(of: self).description == type(of: rule).description
}
Expand All @@ -32,11 +37,32 @@ public protocol ConfigurationProviderRule: Rule {
}

public protocol CorrectableRule: Rule {
func correct(file: File, compilerArguments: [String]) -> [Correction]
func correct(file: File) -> [Correction]
}

public extension CorrectableRule {
func correct(file: File, compilerArguments: [String]) -> [Correction] {
return correct(file: file)
}
}

public protocol SourceKitFreeRule: Rule {}

public protocol AnalyzerRule: Rule {}
jpsim marked this conversation as resolved.
Show resolved Hide resolved

public extension AnalyzerRule {
func validate(file: File) -> [StyleViolation] {
queuedFatalError("Must call `validate(file:compilerArguments:)` for AnalyzerRule")
}
}

public extension AnalyzerRule where Self: CorrectableRule {
func correct(file: File) -> [Correction] {
queuedFatalError("Must call `correct(file:compilerArguments:)` for AnalyzerRule")
}
}

// MARK: - ConfigurationProviderRule conformance to Configurable

public extension ConfigurationProviderRule {
Expand Down
Loading