Skip to content

Commit

Permalink
Satisfy ktlint
Browse files Browse the repository at this point in the history
  • Loading branch information
KyleMayes committed Mar 28, 2024
1 parent 0184ab6 commit 5366325
Show file tree
Hide file tree
Showing 34 changed files with 891 additions and 700 deletions.
30 changes: 19 additions & 11 deletions generator/src/main/kotlin/com/kylemayes/generator/Input.kt
Original file line number Diff line number Diff line change
Expand Up @@ -86,17 +86,23 @@ private fun <T> getRepositoryInput(
}

/** Fetches the contents of a file for a generator input pulled from a GitHub repository. */
private fun getFile(commit: GHCommit, path: RepositoryPath): String {
private fun getFile(
commit: GHCommit,
path: RepositoryPath,
): String {
val content = commit.owner.getFileContent(path.path, commit.shA1)
return if (content.size <= 1024 * 1024 /* 1 MiB */) {
return if (content.size <= 1024 * 1024) {
content.read().readAllBytes().decodeToString()
} else {
commit.owner.getBlob(content.sha).read().readAllBytes().decodeToString()
}
}

/** Fetches the contents of the files in a directory for a generator input pulled from a GitHub repository. */
private fun getDirectory(commit: GHCommit, path: RepositoryPath): Map<String, String> {
private fun getDirectory(
commit: GHCommit,
path: RepositoryPath,
): Map<String, String> {
return commit
.owner
.getDirectoryContent(path.path, commit.shA1)
Expand All @@ -119,11 +125,13 @@ private fun getLocalCommitHashes(context: GeneratorContext): Map<RepositoryPath,
}

/** Writes the locally tracked commit hashes for repository inputs. */
private fun setLocalCommitHashes(context: GeneratorContext, inputs: List<RepositoryInput<Any>>) =
Files.writeString(
context.directory.resolve(".commits"),
inputs.joinToString("\n") {
val (name, branch, path) = it.path
"$name/$branch/$path => ${it.latest.commit.shA1}"
},
)
private fun setLocalCommitHashes(
context: GeneratorContext,
inputs: List<RepositoryInput<Any>>,
) = Files.writeString(
context.directory.resolve(".commits"),
inputs.joinToString("\n") {
val (name, branch, path) = it.path
"$name/$branch/$path => ${it.latest.commit.shA1}"
},
)
32 changes: 17 additions & 15 deletions generator/src/main/kotlin/com/kylemayes/generator/Main.kt
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,10 @@ import kotlin.system.exitProcess

private val log = KotlinLogging.logger { /* */ }

fun main(args: Array<String>) = Generator()
.subcommands(Check(), Index(), Update())
.main(args)
fun main(args: Array<String>) =
Generator()
.subcommands(Check(), Index(), Update())
.main(args)

data class GeneratorContext(
val directory: Path,
Expand Down Expand Up @@ -147,13 +148,13 @@ class Update : CliktCommand(help = "Updates generated Vulkan bindings") {

// Parse

val xmlVersion = if (skipUpgrade) { inputs.registry.local } else { inputs.registry.latest }
val xmlVersion = if (skipUpgrade) inputs.registry.local else inputs.registry.latest
val xml = log.time("Fetch Registry") { xmlVersion.lazy.value }
val registry = log.time("Parse Registry") { parseRegistry(xml) }

// Headers (video)

val videoVersion = if (skipUpgrade) { inputs.video.local } else { inputs.video.latest }
val videoVersion = if (skipUpgrade) inputs.video.local else inputs.video.latest
val video = log.time("Fetch Video Headers") { videoVersion.lazy.value }

// Generate
Expand Down Expand Up @@ -187,10 +188,11 @@ class Update : CliktCommand(help = "Updates generated Vulkan bindings") {
val markdown = context.directory.resolve("CHANGELOG.md")
val changelog = parseMarkdown(Files.readString(markdown))

val commits = inputs.list
.flatMap { it.getIntermediateCommits() }
.toSet()
.sortedBy { it.commitDate }
val commits =
inputs.list
.flatMap { it.getIntermediateCommits() }
.toSet()
.sortedBy { it.commitDate }

for (commit in commits) {
log.info { "Intermediate commit hash = ${commit.shA1}" }
Expand Down Expand Up @@ -224,17 +226,17 @@ class Update : CliktCommand(help = "Updates generated Vulkan bindings") {
val head = "vk-$hash"
val base = "master"

val existing = repo.queryPullRequests()
.head(head)
.base(base)
.list()
.firstOrNull()
val existing =
repo.queryPullRequests()
.head(head)
.base(base)
.list()
.firstOrNull()
if (existing != null) {
log.info { "Pull request already exists (#${existing.number})!" }
return
}


log.info { "Creating branch, committing changes, and pushing branch..." }
val git = Git(FileRepositoryBuilder.create(context.directory.resolve(".git").toFile()))
git.checkout()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,20 @@ import java.nio.file.Path
private val log = KotlinLogging.logger { /* */ }

/** The additional `bindgen` options for the Vulkan video headers. */
private val videoOptions = listOf(
"--allowlist-item", "StdVideo.*",
"--allowlist-item", "STD_VIDEO_.*",
"--no-prepend-enum-name",
"--default-enum-style", "newtype_global",
"--with-derive-custom-enum", ".*=Default",
)
private val videoOptions =
listOf(
"--allowlist-item", "StdVideo.*",
"--allowlist-item", "STD_VIDEO_.*",
"--no-prepend-enum-name",
"--default-enum-style", "newtype_global",
"--with-derive-custom-enum", ".*=Default",
)

/** Generates Rust files for a Vulkan API registry and Vulkan video headers. */
fun generateRustFiles(registry: Registry, video: Map<String, String>) = listOf(
fun generateRustFiles(
registry: Registry,
video: Map<String, String>,
) = listOf(
generateRustFile("vulkanalia-sys", "bitmasks.rs", registry.generateBitmasks()),
generateRustFile("vulkanalia-sys", "commands.rs", registry.generateCommands()),
generateRustFile("vulkanalia-sys", "constants.rs", registry.generateConstants()),
Expand Down Expand Up @@ -81,15 +85,16 @@ data class File(
fun matches(directory: Path): Boolean {
val full = directory.resolve(path)

matches = if (Files.exists(full)) {
val contents = Files.readString(full)
val matches = contents == this.contents
if (!matches) log.info { "$path does not match file on disk." }
matches
} else {
log.info { "$path does not exist on disk." }
false
}
matches =
if (Files.exists(full)) {
val contents = Files.readString(full)
val matches = contents == this.contents
if (!matches) log.info { "$path does not match file on disk." }
matches
} else {
log.info { "$path does not exist on disk." }
false
}

return matches!!
}
Expand All @@ -111,11 +116,11 @@ private fun generateRustFile(
): File {
val path = Path.of(crate).resolve("src").resolve(name)
log.info { "Generating $path..." }
return File(path, "$prefix\n$contents".replace(Regex("\\r\\n?"), "\n"))
return File(path, "$PREFIX\n$contents".replace(Regex("\\r\\n?"), "\n"))
}

/** The Rust file prefix. */
private const val prefix =
private const val PREFIX =
"""
// SPDX-License-Identifier: Apache-2.0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,16 @@ ${generateAliases(bitmasks.keys)}
/** Generates a Rust `bitflags!` struct for a Vulkan bitmask. */
private fun Registry.generateBitmask(bitmask: Bitmask): String {
val long = bitmask.bitflags.any { it.value.bitLength() > 32 }
val repr = "Flags" + (if (long) { "64" } else { "" })
val repr = "Flags" + (if (long) "64" else "")

val values = bitmask.bitflags.associateBy { it.value }
val flags = generateBitflags(values, bitmask.bitflags).joinToString("\n ")
val block = if (flags.isNotBlank()) {
"{\n $flags\n }"
} else {
"{ }"
}
val block =
if (flags.isNotBlank()) {
"{\n $flags\n }"
} else {
"{ }"
}

return """
bitflags! {
Expand All @@ -47,27 +48,33 @@ bitflags! {
}

/** Generates Rust `bitflags!` bitflags for a list of Vulkan bitflags. */
private fun generateBitflags(values: Map<BigInteger, Bitflag>, bitflags: List<Bitflag>) =
if (bitflags.isNotEmpty()) {
bitflags
.sortedBy { it.value }
.map { "const ${it.name} = ${generateExpr(values, it.value)};" }
} else {
emptyList()
}
private fun generateBitflags(
values: Map<BigInteger, Bitflag>,
bitflags: List<Bitflag>,
) = if (bitflags.isNotEmpty()) {
bitflags
.sortedBy { it.value }
.map { "const ${it.name} = ${generateExpr(values, it.value)};" }
} else {
emptyList()
}

/** Generates a Rust expression for a Vulkan bitflag value. */
private fun generateExpr(values: Map<BigInteger, Bitflag>, value: BigInteger): String {
val bits = (0..value.bitLength())
.map { it to value.testBit(it) }
.filter { it.second }
.map { it.first }
private fun generateExpr(
values: Map<BigInteger, Bitflag>,
value: BigInteger,
): String {
val bits =
(0..value.bitLength())
.map { it to value.testBit(it) }
.filter { it.second }
.map { it.first }

return if (bits.isEmpty()) {
"0"
} else if (bits.size == 1) {
val bit = bits[0]
if (bit == 0) { "1" } else { "1 << $bit" }
if (bit == 0) "1" else "1 << $bit"
} else if (bits.size == 31) {
return "i32::MAX as u32"
} else {
Expand Down
Loading

0 comments on commit 5366325

Please sign in to comment.