-
Notifications
You must be signed in to change notification settings - Fork 74
jextract: extract swift func docs as Java docs #497
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
madsodgaard
wants to merge
6
commits into
swiftlang:main
Choose a base branch
from
madsodgaard:swift-docs-in-java
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
175 changes: 175 additions & 0 deletions
175
Sources/JExtractSwiftLib/SwiftDocumentationParsing.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,175 @@ | ||
| //===----------------------------------------------------------------------===// | ||
| // | ||
| // This source file is part of the Swift.org open source project | ||
| // | ||
| // Copyright (c) 2025 Apple Inc. and the Swift.org project authors | ||
| // Licensed under Apache License v2.0 | ||
| // | ||
| // See LICENSE.txt for license information | ||
| // See CONTRIBUTORS.txt for the list of Swift.org project authors | ||
| // | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| // | ||
| //===----------------------------------------------------------------------===// | ||
|
|
||
| import Foundation | ||
| import SwiftSyntax | ||
|
|
||
| struct SwiftDocumentation: Equatable { | ||
| struct Parameter: Equatable { | ||
| var name: String | ||
| var description: String | ||
| } | ||
|
|
||
| var summary: String? | ||
| var discussion: String? | ||
| var parameters: [Parameter] = [] | ||
| var returns: String? | ||
| } | ||
|
|
||
| enum SwiftDocumentationParser { | ||
| private enum State { | ||
| case summary | ||
| case discussion | ||
| case parameter(Int) | ||
| case returns | ||
| } | ||
|
|
||
| // TODO: Replace with Regex | ||
| // Capture Groups: 1=Tag, 2=Arg(Optional), 3=Description | ||
| private static let tagRegex = try! NSRegularExpression(pattern: "^-\\s*(\\w+)(?:\\s+([^:]+))?\\s*:\\s*(.*)$") | ||
|
|
||
| static func parse(_ syntax: some SyntaxProtocol) -> SwiftDocumentation? { | ||
| // We must have at least one docline and newline, for this to be valid | ||
| guard syntax.leadingTrivia.count >= 2 else { return nil } | ||
|
|
||
| var comments = [String]() | ||
| var pieces = syntax.leadingTrivia.pieces | ||
|
|
||
| // We always expect a newline follows a docline comment | ||
| while case .newlines(1) = pieces.popLast(), case .docLineComment(let text) = pieces.popLast() { | ||
| comments.append(text) | ||
| } | ||
|
|
||
| guard !comments.isEmpty else { return nil } | ||
|
|
||
| return parse(comments.reversed()) | ||
| } | ||
|
|
||
| private static func parse(_ doclines: [String]) -> SwiftDocumentation? { | ||
| var doc = SwiftDocumentation() | ||
| var state: State = .summary | ||
|
|
||
| let lines = doclines.map { line -> String in | ||
| let trimmed = line.trimmingCharacters(in: .whitespaces) | ||
| return trimmed.hasPrefix("///") ? String(trimmed.dropFirst(3)).trimmingCharacters(in: .whitespaces) : trimmed | ||
| } | ||
|
|
||
| // If no lines or all empty, we don't have any documentation. | ||
| if lines.isEmpty || lines.allSatisfy(\.isEmpty) { | ||
| return nil | ||
| } | ||
|
|
||
| for line in lines { | ||
| if line.starts(with: "-"), let (tag, arg, content) = Self.parseTagHeader(line) { | ||
| switch tag.lowercased() { | ||
| case "parameter": | ||
| guard let arg else { continue } | ||
| doc.parameters.append( | ||
| SwiftDocumentation.Parameter( | ||
| name: arg, | ||
| description: content | ||
| ) | ||
| ) | ||
| state = .parameter(doc.parameters.count > 0 ? doc.parameters.count : 0) | ||
|
|
||
| case "parameters": | ||
| state = .parameter(0) | ||
|
|
||
| case "returns": | ||
| doc.returns = content | ||
| state = .returns | ||
|
|
||
| default: | ||
| // Parameter names are marked like | ||
| // - myString: description | ||
| if case .parameter = state { | ||
| state = .parameter(doc.parameters.count > 0 ? doc.parameters.count : 0) | ||
|
|
||
| doc.parameters.append( | ||
| SwiftDocumentation.Parameter( | ||
| name: tag, | ||
| description: content | ||
| ) | ||
| ) | ||
| } else { | ||
| state = .discussion | ||
| append(&doc.discussion, line) | ||
| } | ||
| } | ||
| } else if line.isEmpty { | ||
| // Any blank lines will move us to discussion | ||
| state = .discussion | ||
| if let discussion = doc.discussion, !discussion.isEmpty { | ||
| if !discussion.hasSuffix("\n") { | ||
| doc.discussion?.append("\n") | ||
| } | ||
| } | ||
| } else { | ||
| appendLineToState(state, line: line, doc: &doc) | ||
| } | ||
| } | ||
|
|
||
| // Remove any trailing newlines in discussion | ||
| while doc.discussion?.last == "\n" { | ||
| doc.discussion?.removeLast() | ||
| } | ||
|
|
||
| return doc | ||
| } | ||
|
|
||
| private static func appendLineToState(_ state: State, line: String, doc: inout SwiftDocumentation) { | ||
madsodgaard marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| switch state { | ||
| case .summary: append(&doc.summary, line) | ||
| case .discussion: append(&doc.discussion, line) | ||
| case .returns: append(&doc.returns, line) | ||
| case .parameter(let index): | ||
| if index < doc.parameters.count { | ||
| append(&doc.parameters[index].description, line) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private static func append(_ existing: inout String, _ new: String) { | ||
| existing += "\n" + new | ||
| } | ||
|
|
||
| private static func append(_ existing: inout String?, _ new: String) { | ||
| if existing == nil { existing = new } | ||
| else { | ||
| existing! += "\n" + new | ||
| } | ||
| } | ||
|
|
||
| private static func parseTagHeader(_ line: String) -> (type: String, arg: String?, description: String)? { | ||
| let range = NSRange(location: 0, length: line.utf16.count) | ||
| guard let match = Self.tagRegex.firstMatch(in: line, options: [], range: range) else { return nil } | ||
|
|
||
| // Group 1: Tag Name | ||
| guard let typeRange = Range(match.range(at: 1), in: line) else { return nil } | ||
| let type = String(line[typeRange]) | ||
|
|
||
| // Group 2: Argument (Optional) | ||
| var arg: String? = nil | ||
| let argRangeNs = match.range(at: 2) | ||
| if argRangeNs.location != NSNotFound, let argRange = Range(argRangeNs, in: line) { | ||
| arg = String(line[argRange]) | ||
| } | ||
|
|
||
| // Group 3: Description (Always present, potentially empty) | ||
| guard let descRange = Range(match.range(at: 3), in: line) else { return nil } | ||
| let description = String(line[descRange]) | ||
|
|
||
| return (type, arg, description) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| //===----------------------------------------------------------------------===// | ||
| // | ||
| // This source file is part of the Swift.org open source project | ||
| // | ||
| // Copyright (c) 2025 Apple Inc. and the Swift.org project authors | ||
| // Licensed under Apache License v2.0 | ||
| // | ||
| // See LICENSE.txt for license information | ||
| // See CONTRIBUTORS.txt for the list of Swift.org project authors | ||
| // | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| // | ||
| //===----------------------------------------------------------------------===// | ||
|
|
||
| import SwiftSyntax | ||
|
|
||
| enum TranslatedDocumentation { | ||
| static func printDocumentation( | ||
| importedFunc: ImportedFunc, | ||
| translatedDecl: FFMSwift2JavaGenerator.TranslatedFunctionDecl, | ||
| in printer: inout CodePrinter | ||
| ) { | ||
| var documentation = SwiftDocumentationParser.parse(importedFunc.swiftDecl) | ||
|
|
||
| if translatedDecl.translatedSignature.requiresSwiftArena { | ||
| documentation?.parameters.append( | ||
| SwiftDocumentation.Parameter( | ||
| name: "swiftArena$", | ||
| description: "the arena that will manage the lifetime and allocation of Swift objects" | ||
| ) | ||
| ) | ||
| } | ||
|
|
||
| printDocumentation(documentation, syntax: importedFunc.swiftDecl, in: &printer) | ||
| } | ||
|
|
||
| static func printDocumentation( | ||
| importedFunc: ImportedFunc, | ||
| translatedDecl: JNISwift2JavaGenerator.TranslatedFunctionDecl, | ||
| in printer: inout CodePrinter | ||
| ) { | ||
| var documentation = SwiftDocumentationParser.parse(importedFunc.swiftDecl) | ||
|
|
||
| if translatedDecl.translatedFunctionSignature.requiresSwiftArena { | ||
| documentation?.parameters.append( | ||
| SwiftDocumentation.Parameter( | ||
| name: "swiftArena$", | ||
| description: "the arena that the the returned object will be attached to" | ||
| ) | ||
| ) | ||
| } | ||
|
|
||
| printDocumentation(documentation, syntax: importedFunc.swiftDecl, in: &printer) | ||
| } | ||
|
|
||
| private static func printDocumentation( | ||
| _ parsedDocumentation: SwiftDocumentation?, | ||
| syntax: some DeclSyntaxProtocol, | ||
| in printer: inout CodePrinter | ||
| ) { | ||
| var groups = [String]() | ||
| if let summary = parsedDocumentation?.summary { | ||
| groups.append("\(summary)") | ||
| } | ||
|
|
||
| if let discussion = parsedDocumentation?.discussion { | ||
| let paragraphs = discussion.split(separator: "\n\n") | ||
| for paragraph in paragraphs { | ||
| groups.append("<p>\(paragraph)") | ||
| } | ||
| } | ||
|
|
||
| groups.append( | ||
| """ | ||
| \(parsedDocumentation != nil ? "<p>" : "")Downcall to Swift: | ||
| {@snippet lang=swift : | ||
| \(syntax.signatureString) | ||
| } | ||
| """ | ||
| ) | ||
|
|
||
| var annotationsGroup = [String]() | ||
|
|
||
| for param in parsedDocumentation?.parameters ?? [] { | ||
| annotationsGroup.append("@param \(param.name) \(param.description)") | ||
| } | ||
|
|
||
| if let returns = parsedDocumentation?.returns { | ||
| annotationsGroup.append("@return \(returns)") | ||
| } | ||
|
|
||
| if !annotationsGroup.isEmpty { | ||
| groups.append(annotationsGroup.joined(separator: "\n")) | ||
| } | ||
|
|
||
| printer.print("/**") | ||
| let oldIdentationText = printer.indentationText | ||
| printer.indentationText += " * " | ||
| for (idx, group) in groups.enumerated() { | ||
| printer.print(group) | ||
| if idx < groups.count - 1 { | ||
| printer.print("") | ||
| } | ||
| } | ||
| printer.indentationText = oldIdentationText | ||
| printer.print(" */") | ||
|
|
||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.