Files
SwiftLint/Source/SwiftLintFramework/Rules/Lint/OrphanedDocCommentRule.swift
T
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

81 lines
2.9 KiB
Swift

import Foundation
import SourceKittenFramework
public struct OrphanedDocCommentRule: ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "orphaned_doc_comment",
name: "Orphaned Doc Comment",
description: "A doc comment should be attached to a declaration.",
kind: .lint,
minSwiftVersion: .fourDotOne,
nonTriggeringExamples: [
Example("""
/// My great property
var myGreatProperty: String!
"""),
Example("""
//////////////////////////////////////
//
// Copyright header.
//
//////////////////////////////////////
"""),
Example("""
/// Look here for more info: https://github.com.
var myGreatProperty: String!
"""),
Example("""
/// Look here for more info:
/// https://github.com.
var myGreatProperty: String!
""")
],
triggeringExamples: [
Example("""
↓/// My great property
// Not a doc string
var myGreatProperty: String!
"""),
Example("""
↓/// Look here for more info: https://github.com.
// Not a doc string
var myGreatProperty: String!
""")
]
)
private static let characterSet = CharacterSet.whitespacesAndNewlines.union(CharacterSet(charactersIn: "/"))
public func validate(file: SwiftLintFile) -> [StyleViolation] {
let docStringsTokens = file.syntaxMap.tokens.filter { token in
return token.kind == .docComment || token.kind == .docCommentField
}
let docummentedDeclsRanges = file.structureDictionary.traverseDepthFirst { dictionary -> [ByteRange]? in
guard let docOffset = dictionary.docOffset, let docLength = dictionary.docLength else {
return nil
}
return [ByteRange(location: docOffset, length: docLength)]
}.sorted { $0.location < $1.location }
return docStringsTokens
.filter { token in
guard docummentedDeclsRanges.firstIndexAssumingSorted(where: token.range.intersects) == nil,
let contents = file.contents(for: token) else {
return false
}
return !contents.trimmingCharacters(in: type(of: self).characterSet).isEmpty
}.map { token in
return StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: token.offset))
}
}
}