Skip to content

Add commentValue property to Trivia for cleaned comments #2966

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

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 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
4 changes: 4 additions & 0 deletions Release Notes/602.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
- Pull request: https://github.com/swiftlang/swift-syntax/pull/3030
- Migration stems: None required.

- `Trivia` has a new `commentValue` property.
- Description: Extracts sanitized comment text from comment trivia pieces, omitting leading comment markers (`//`, `///`, `/*`, `*/`).
- Pull Request: https://github.com/swiftlang/swift-syntax/pull/2966

## API Behavior Changes

## Deprecations
Expand Down
131 changes: 131 additions & 0 deletions Sources/SwiftSyntax/Trivia.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,137 @@ public struct Trivia: Sendable {
pieces.isEmpty
}

/// The string contents of all the comment pieces with any comments tokens trimmed.
public var commentValue: String? {
var comments = [Substring]()
var hasBlockComment = false
var hasLineComment = false

// Determine if all line comments have a single space
lazy var allLineCommentsHaveSpace: Bool = {
return pieces.allSatisfy { piece in
switch piece {
case .lineComment(let text):
return text.hasPrefix("// ")
case .docLineComment(let text):
return text.hasPrefix("/// ")
default:
return true
}
}
}()

// Returns a substring with leading and trailing spaces removed.
func trimWhitespace(_ text: Substring) -> Substring {
let trimmed = text.drop(while: { $0 == " " })
let reversed = trimmed.reversed()
let trimmedEnd = reversed.drop(while: { $0 == " " })
let final = trimmedEnd.reversed()
return Substring(final)
}

// Strips /* */ markers and aligns content by removing common indentation.
func processBlockComment(_ text: Substring) -> String {
var lines = text.split(separator: "\n", omittingEmptySubsequences: false)

let (minSpaceIndentation, minTabIndentation) =
lines
.dropFirst()
.filter { !$0.isEmpty }
.reduce((Int.max, Int.max)) { (currentMin, line) in
var spaceCount = 0, tabCount = 0
var inLeadingWhitespace = true

for char in line {
guard inLeadingWhitespace else { break }

switch char {
case " ":
spaceCount += 1
case "\t":
tabCount += 1
default:
inLeadingWhitespace = false
}
}

return (Swift.min(currentMin.0, spaceCount), Swift.min(currentMin.1, tabCount))
}

var minIndentation = minSpaceIndentation == Int.max ? 0 : minSpaceIndentation
minIndentation += minTabIndentation == Int.max ? 0 : minTabIndentation

if let first = lines.first {
let prefixToDrop = first.hasPrefix("/**") ? 3 : 2
lines[0] = first.dropFirst(prefixToDrop)
}

var firstLineRemoved = false
if trimWhitespace(lines[0]).isEmpty {
lines.removeFirst()
firstLineRemoved = true
}

var unindentedLines = lines.enumerated().map { index, line -> Substring in
if index == 0 && firstLineRemoved == false {
return line
}
return line.count >= minIndentation ? line.dropFirst(minIndentation) : line
}

if let last = unindentedLines.last, last.hasSuffix("*/") {
unindentedLines[unindentedLines.count - 1] = last.dropLast(2)
}

if trimWhitespace(unindentedLines[unindentedLines.count - 1]).isEmpty {
unindentedLines.removeLast()
}

return unindentedLines.joined(separator: "\n")
}

for piece in pieces {
switch piece {
case .blockComment(let text), .docBlockComment(let text):
if hasBlockComment || hasLineComment {
return nil
}
hasBlockComment = true
let processedText = processBlockComment(text[...])
comments.append(processedText[...])

case .lineComment(let text):
if hasBlockComment {
return nil
}
hasLineComment = true
let prefix = allLineCommentsHaveSpace ? "// " : "//"
comments.append(text.dropFirst(prefix.count))

case .docLineComment(let text):
if hasBlockComment {
return nil
}
hasLineComment = true
let prefix = allLineCommentsHaveSpace ? "/// " : "///"
comments.append(text.dropFirst(prefix.count))

default:
break
}
}

guard !comments.isEmpty else { return nil }

// If we have multiple line comments, they can be joined with newlines
if hasLineComment {
return comments.joined(separator: "\n")
}

// In case of block comments, we should only have one
return comments.first.map(String.init)
}

/// The length of all the pieces in this ``Trivia``.
public var sourceLength: SourceLength {
return pieces.map({ $0.sourceLength }).reduce(.zero, +)
Expand Down
Loading