Files
SwiftLint/Source/SwiftLintFramework/Rules/Idiomatic/ExplicitACLRule.swift
Zev Eisenberg fcf848608e Add Inline test failure messages (#3040)
* Add Example wrapper in order to display test failures inline when running in Xcode.
* Stop using Swift 5.1-only features so we can compile on Xcode 10.2.
* Wrap strings in Example.
* Add Changelog entry.
* Wrap all examples in Example struct.
* Better and more complete capturing of line numbers.
* Fix broken test.
* Better test traceability.
* Address or disable linting warnings.
* Add documentation comments.
* Disable linter for a few cases.
* Limit mutability and add copy-and-mutate utility functions.
* Limit scope of mutability.
2020-02-02 10:35:37 +02:00

159 lines
6.5 KiB
Swift

import Foundation
import SourceKittenFramework
private typealias SourceKittenElement = SourceKittenDictionary
public struct ExplicitACLRule: OptInRule, ConfigurationProviderRule, AutomaticTestableRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "explicit_acl",
name: "Explicit ACL",
description: "All declarations should specify Access Control Level keywords explicitly.",
kind: .idiomatic,
nonTriggeringExamples: [
Example("internal enum A {}\n"),
Example("public final class B {}\n"),
Example("private struct C {}\n"),
Example("internal enum A {\n internal enum B {}\n}"),
Example("internal final class Foo {}"),
Example("""
internal
class Foo {
private let bar = 5
}
"""),
Example("internal func a() { let a = }\n"),
Example("private func a() { func innerFunction() { } }"),
Example("private enum Foo { enum Bar { } }"),
Example("private struct C { let d = 5 }"),
Example("""
internal protocol A {
func b()
}
"""),
Example("""
internal protocol A {
var b: Int
}
"""),
Example("internal class A { deinit {} }"),
Example("extension A: Equatable {}"),
Example("extension A {}")
],
triggeringExamples: [
Example("enum A {}\n"),
Example("final class B {}\n"),
Example("internal struct C { let d = 5 }\n"),
Example("public struct C { let d = 5 }\n"),
Example("func a() {}\n"),
Example("internal let a = 0\nfunc b() {}\n")
]
)
private func findAllExplicitInternalTokens(in file: SwiftLintFile) -> [ByteRange] {
let contents = file.stringView
return file.match(pattern: "internal", with: [.attributeBuiltin]).compactMap {
contents.NSRangeToByteRange(start: $0.location, length: $0.length)
}
}
private func offsetOfElements(from elements: [SourceKittenElement], in file: SwiftLintFile,
thatAreNotInRanges ranges: [ByteRange]) -> [ByteCount] {
let extensionKinds: Set<SwiftDeclarationKind> = [.extension, .extensionClass, .extensionEnum,
.extensionProtocol, .extensionStruct]
return elements.compactMap { element in
guard let typeOffset = element.offset else {
return nil
}
guard let kind = element.declarationKind,
!extensionKinds.contains(kind) else {
return nil
}
// find the last "internal" token before the type
guard let previousInternalByteRange = lastInternalByteRange(before: typeOffset, in: ranges) else {
return typeOffset
}
// the "internal" token correspond to the type if there're only
// attributeBuiltin (`final` for example) tokens between them
let length = typeOffset - previousInternalByteRange.location
let range = ByteRange(location: previousInternalByteRange.location, length: length)
let internalDoesntBelongToType = Set(file.syntaxMap.kinds(inByteRange: range)) != [.attributeBuiltin]
return internalDoesntBelongToType ? typeOffset : nil
}
}
public func validate(file: SwiftLintFile) -> [StyleViolation] {
let implicitAndExplicitInternalElements = internalTypeElements(in: file.structureDictionary )
guard !implicitAndExplicitInternalElements.isEmpty else {
return []
}
let explicitInternalRanges = findAllExplicitInternalTokens(in: file)
let violations = offsetOfElements(from: implicitAndExplicitInternalElements, in: file,
thatAreNotInRanges: explicitInternalRanges)
return violations.map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: $0))
}
}
private func lastInternalByteRange(before typeOffset: ByteCount, in ranges: [ByteRange]) -> ByteRange? {
let firstPartition = ranges.prefix(while: { typeOffset > $0.location })
return firstPartition.last
}
private func internalTypeElements(in element: SourceKittenElement) -> [SourceKittenElement] {
return element.substructure.flatMap { element -> [SourceKittenElement] in
guard let elementKind = element.declarationKind else {
return []
}
let isDeinit = elementKind == .functionMethodInstance && element.name == "deinit"
guard !isDeinit else {
return []
}
let isPrivate = element.accessibility?.isPrivate ?? false
let internalTypeElementsInSubstructure = elementKind.childsAreExemptFromACL || isPrivate ? [] :
internalTypeElements(in: element)
if element.accessibility == .internal {
return internalTypeElementsInSubstructure + [element]
}
return internalTypeElementsInSubstructure
}
}
}
private extension SwiftDeclarationKind {
var childsAreExemptFromACL: Bool {
switch self {
case .associatedtype, .enumcase, .enumelement, .functionAccessorAddress,
.functionAccessorDidset, .functionAccessorGetter, .functionAccessorMutableaddress,
.functionAccessorSetter, .functionAccessorWillset, .genericTypeParam, .module,
.precedenceGroup, .varLocal, .varParameter, .varClass,
.varGlobal, .varInstance, .varStatic, .typealias, .functionAccessorModify, .functionAccessorRead,
.functionConstructor, .functionDestructor, .functionFree, .functionMethodClass,
.functionMethodInstance, .functionMethodStatic, .functionOperator, .functionOperatorInfix,
.functionOperatorPostfix, .functionOperatorPrefix, .functionSubscript, .protocol, .opaqueType:
return true
case .class, .enum, .extension, .extensionClass, .extensionEnum,
.extensionProtocol, .extensionStruct, .struct:
return false
}
}
}