Skip to content

Commit c0a3702

Browse files
committed
Migrate deprecated NSLinguisticTagger API to Natural Language framework
1 parent a8ab390 commit c0a3702

File tree

1 file changed

+23
-8
lines changed

1 file changed

+23
-8
lines changed

Sources/SwiftFormat/Rules/BeginDocumentationCommentWithOneLineSummary.swift

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@
1111
//===----------------------------------------------------------------------===//
1212

1313
import Foundation
14+
#if os(macOS)
15+
import NaturalLanguage
16+
#endif
1417
import SwiftSyntax
1518

1619
/// All documentation comments must begin with a one-line summary of the declaration.
@@ -125,19 +128,31 @@ public final class BeginDocumentationCommentWithOneLineSummary: SyntaxLintRule {
125128
}
126129

127130
var sentences = [String]()
131+
var tags = [NLTag]()
128132
var tokenRanges = [Range<String.Index>]()
129-
let tags = text.linguisticTags(
133+
134+
let tagger = NLTagger(tagSchemes: [.lexicalClass])
135+
tagger.string = text
136+
tagger.enumerateTags(
130137
in: text.startIndex..<text.endIndex,
131-
scheme: NSLinguisticTagScheme.lexicalClass.rawValue,
132-
tokenRanges: &tokenRanges)
138+
unit: .word,
139+
scheme: .lexicalClass
140+
) { tag, range in
141+
if let tag {
142+
tags.append(tag)
143+
tokenRanges.append(range)
144+
}
145+
return true
146+
}
147+
133148
var isInsideQuotes = false
134149
let sentenceTerminatorIndices = tags.enumerated().filter {
135-
if $0.element == "OpenQuote" {
150+
if $0.element == NLTag.openQuote {
136151
isInsideQuotes = true
137-
} else if $0.element == "CloseQuote" {
152+
} else if $0.element == NLTag.closeQuote {
138153
isInsideQuotes = false
139154
}
140-
return !isInsideQuotes && $0.element == "SentenceTerminator"
155+
return !isInsideQuotes && $0.element == NLTag.sentenceTerminator
141156
}.map {
142157
tokenRanges[$0.offset].lowerBound
143158
}
@@ -158,8 +173,8 @@ public final class BeginDocumentationCommentWithOneLineSummary: SyntaxLintRule {
158173
/// Returns the best approximation of sentences in the given text using string splitting around
159174
/// periods that are followed by spaces.
160175
///
161-
/// This method is a fallback for platforms (like Linux, currently) where `String` does not
162-
/// support `NSLinguisticTagger` and its related APIs. It will fail to catch certain kinds of
176+
/// This method is a fallback for platforms (like Linux, currently) that does not
177+
/// support `NaturalLanguage` and its related APIs. It will fail to catch certain kinds of
163178
/// sentences (such as those containing abbreviations that are followed by a period, like "Dr.")
164179
/// that the more advanced API can handle.
165180
private func nonLinguisticSentenceApproximations(in text: String) -> (

0 commit comments

Comments
 (0)