Files
SwiftLint/Source/SwiftLintFramework/Rules/Lint/OrphanedDocCommentRule.swift
T
Danny Mösch 449190d324 Verify examples in rules by default and enforce explicit exclusion (#4065)
A rule must conform to ManuallyTestedExamplesRule to skip generation of a test for its examples.
2022-08-09 22:32:09 +02:00

80 lines
2.8 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,
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: Self.characterSet).isNotEmpty
}.map { token in
return StyleViolation(ruleDescription: Self.description,
severity: configuration.severity,
location: Location(file: file, byteOffset: token.offset))
}
}
}