-
Notifications
You must be signed in to change notification settings - Fork 180
/
RustWriter.kt
354 lines (322 loc) · 11.9 KB
/
RustWriter.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
package software.amazon.smithy.rust.codegen.rustlang
import org.intellij.lang.annotations.Language
import software.amazon.smithy.codegen.core.CodegenException
import software.amazon.smithy.codegen.core.Symbol
import software.amazon.smithy.codegen.core.writer.CodegenWriter
import software.amazon.smithy.codegen.core.writer.CodegenWriterFactory
import software.amazon.smithy.model.Model
import software.amazon.smithy.model.shapes.BooleanShape
import software.amazon.smithy.model.shapes.CollectionShape
import software.amazon.smithy.model.shapes.NumberShape
import software.amazon.smithy.model.shapes.Shape
import software.amazon.smithy.model.shapes.ShapeId
import software.amazon.smithy.model.traits.DocumentationTrait
import software.amazon.smithy.rust.codegen.smithy.RuntimeType
import software.amazon.smithy.rust.codegen.smithy.isOptional
import software.amazon.smithy.rust.codegen.smithy.rustType
import software.amazon.smithy.rust.codegen.util.orNull
import software.amazon.smithy.utils.CodeWriter
import java.util.function.BiFunction
fun <T : CodeWriter> T.withBlock(
textBeforeNewLine: String,
textAfterNewLine: String,
vararg args: Any,
block: T.() -> Unit
): T {
return conditionalBlock(textBeforeNewLine, textAfterNewLine, conditional = true, block = block, args = args)
}
/**
* Write a block to the writer.
* If [conditional] is true, the [textBeforeNewLine], followed by [block], followed by [textAfterNewLine]
* If [conditional] is false, only [block] is written.
* This enables conditionally wrapping a block in a prefix/suffix, eg.
*
* ```
* writer.withBlock("Some(", ")", conditional = symbol.isOptional()) {
* write("symbolValue")
* }
* ```
*/
fun <T : CodeWriter> T.conditionalBlock(
textBeforeNewLine: String,
textAfterNewLine: String,
conditional: Boolean = true,
vararg args: Any,
block: T.() -> Unit
): T {
if (conditional) {
openBlock(textBeforeNewLine, *args)
}
block(this)
if (conditional) {
closeBlock(textAfterNewLine)
}
return this
}
/**
* Convenience wrapper that tells Intellij that the contents of this block are Rust
*/
fun <T : CodeWriter> T.rust(
@Language("Rust", prefix = "macro_rules! foo { () => {{ ", suffix = "}}}") contents: String,
vararg args: Any
) {
this.write(contents, *args)
}
/**
* Experimental API for templating long blocks of Rust
*
* This enables writing code like:
*
* ```kotlin
* writer.rustTemplate("""
* let some_val = #{operation}::from_response(response);
* let serialized = #{serde_json}::to_json(some_val);
* """, "operation" to operationSymbol, "serde_json" to RuntimeType.SerdeJson)
* ```
*
* Before being passed to the underlying code writer, this syntax is rewritten to match the slightly more verbose
* `CodeWriter` formatting: `#{name:T}`
*/
fun <T : CodeWriter> T.rustTemplate(
@Language("Rust", prefix = "macro_rules! foo { () => {{ ", suffix = "}}}") contents: String,
vararg ctx: Pair<String, Any>
) {
this.pushState()
this.putContext(ctx.toMap())
this.write(contents.replace(Regex("""#\{([a-zA-Z_0-9]+)\}""")) { matchResult -> "#{${matchResult.groupValues[1]}:T}" })
this.popState()
}
/*
* Writes a Rust-style block, demarcated by curly braces
*/
fun <T : CodeWriter> T.rustBlock(
@Language("Rust", prefix = "macro_rules! foo { () => {{ ", suffix = "}}}")
header: String,
vararg args: Any,
block: T.() -> Unit
): T {
openBlock("$header {", *args)
block(this)
closeBlock("}")
return this
}
/**
* Generate a RustDoc comment for [shape]
*/
fun <T : CodeWriter> T.documentShape(shape: Shape, model: Model): T {
// TODO: support additional Smithy documentation traits like @example
val docTrait = shape.getMemberTrait(model, DocumentationTrait::class.java).orNull()
docTrait?.value?.also {
this.docs(escape(it))
}
return this
}
/**
* Write RustDoc-style docs into the writer
*
* Several modifications are made to provide consistent RustDoc formatting:
* - All lines will be prefixed by `///`
* - Tabs are replaced with spaces
* - Empty newlines are removed
*/
fun <T : CodeWriter> T.docs(text: String, vararg args: Any, newlinePrefix: String = "/// "): T {
pushState()
setNewlinePrefix(newlinePrefix)
// TODO: Smithy updates should remove the need for a number of these changes
val cleaned = text.lines()
// We need to filter out blank lines—an empty line causes the markdown parser to interpret the subsequent
// docs as a code block because they are indented.
.filter { it.isNotBlank() }
.joinToString("\n") {
// Rustdoc warns on tabs in documentation
it.trimStart().replace("\t", " ")
}
write(cleaned, *args)
popState()
return this
}
/** Escape the [expressionStart] character to avoid problems during formatting */
fun CodeWriter.escape(text: String): String = text.replace("$expressionStart", "$expressionStart$expressionStart")
/**
* Write _exactly_ the text as written into the code writer without newlines or formatting
*/
fun CodeWriter.raw(text: String) = writeInline(escape(text))
typealias Writable = RustWriter.() -> Unit
/** Helper to allow coercing the Writeable signature
* writable { rust("fn foo() { }")
*/
fun writable(w: Writable): Writable = w
fun writable(w: String): Writable = writable { rust(w) }
class RustWriter private constructor(
private val filename: String,
val namespace: String,
private val commentCharacter: String = "//",
private var printWarning: Boolean = true
) :
CodegenWriter<RustWriter, UseDeclarations>(null, UseDeclarations(namespace)) {
private var headerDocs: String? = null
fun setHeaderDocs(docs: String) {
headerDocs = RustWriter("", "", printWarning = false).docs(docs, newlinePrefix = "//! ").toString()
}
companion object {
fun root() = forModule(null)
fun forModule(module: String?): RustWriter = if (module == null) {
RustWriter("lib.rs", "crate")
} else {
RustWriter("$module.rs", "crate::$module")
}
val Factory: CodegenWriterFactory<RustWriter> =
CodegenWriterFactory<RustWriter> { filename, namespace ->
when {
filename.endsWith(".toml") -> RustWriter(filename, namespace, "#")
filename == "LICENSE" -> RustWriter(
filename,
namespace = "ignore",
commentCharacter = "ignore",
printWarning = false
)
else -> RustWriter(filename, namespace)
}
}
}
private val formatter = RustSymbolFormatter()
private var n = 0
init {
expressionStart = '#'
if (filename.endsWith(".rs")) {
require(namespace.startsWith("crate")) { "We can only write into files in the crate (got $namespace)" }
}
putFormatter('T', formatter)
putFormatter('D', RustDocLinker())
}
fun module(): String? = if (filename.endsWith(".rs")) {
filename.removeSuffix(".rs").split('/').last()
} else null
fun safeName(prefix: String = "var"): String {
n += 1
return "${prefix}_$n"
}
/**
* Create an inline module.
*
* Callers must take care to use [this] when writing to ensure code is written to the right place:
* ```kotlin
* val writer = RustWriter.forModule("model")
* writer.withModule("nested") {
* Generator(...).render(this) // GOOD
* Generator(...).render(writer) // WRONG!
* }
* ```
*
* The returned writer will inject any local imports into the module as needed.
*/
fun withModule(
moduleName: String,
rustMetadata: RustMetadata = RustMetadata(public = true),
moduleWriter: RustWriter.() -> Unit
): RustWriter {
// In Rust, modules must specify their own imports—they don't have access to the parent scope.
// To easily handle this, create a new inner writer to collect imports, then dump it
// into an inline module.
val innerWriter = RustWriter(this.filename, "${this.namespace}::$moduleName", printWarning = false)
moduleWriter(innerWriter)
rustMetadata.render(this)
rustBlock("mod $moduleName") {
writeWithNoFormatting(innerWriter.toString())
}
innerWriter.dependencies.forEach { addDependency(it) }
return this
}
/**
* Generate a wrapping if statement around a field.
*
* - If the field is optional, it will only be called if the field is present
* - If the field is an unboxed primitive, it will only be called if the field is non-zero
*
*/
fun ifSet(shape: Shape, member: Symbol, outerField: String, block: CodeWriter.(field: String) -> Unit) {
// TODO: this API should be refactored so that we don't need to strip `&` to get reference comparisons to work.
when {
member.isOptional() -> {
val derefName = safeName("inner")
rustBlock("if let Some($derefName) = $outerField") {
block(derefName)
}
}
shape is NumberShape -> rustBlock("if ${outerField.removePrefix("&")} != 0") {
block(outerField)
}
shape is BooleanShape -> rustBlock("if ${outerField.removePrefix("&")}") {
block(outerField)
}
else -> this.block(outerField)
}
}
fun ListForEach(
target: Shape,
outerField: String,
block: CodeWriter.(field: String, target: ShapeId) -> Unit
) {
if (target is CollectionShape) {
val derefName = safeName("inner")
rustBlock("for $derefName in $outerField") {
block(derefName, target.member.target)
}
} else {
this.block(outerField, target.toShapeId())
}
}
override fun toString(): String {
val contents = super.toString()
// Hack to support TOML
// TODO: consider creating a TOML writer
val header = if (printWarning) {
"$commentCharacter Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT."
} else null
val useDecls = importContainer.toString().let {
if (it.isEmpty()) {
null
} else it
}
return listOfNotNull(headerDocs, header, useDecls, contents).joinToString(separator = "\n", postfix = "\n")
}
fun format(r: Any):
String {
return formatter.apply(r, "")
}
fun addDepsRecursively(symbol: Symbol) {
addDependency(symbol)
symbol.references.forEach { addDepsRecursively(it.symbol) }
}
/**
* Generate RustDoc links, eg. [`Abc`](crate::module::Abc)
*/
inner class RustDocLinker : BiFunction<Any, String, String> {
override fun apply(t: Any, u: String): String {
return when (t) {
is Symbol -> "[`${t.name}`](${t.fullName})"
else -> throw CodegenException("Invalid type provided to RustDocLinker ($t) expected Symbol")
}
}
}
inner class RustSymbolFormatter : BiFunction<Any, String, String> {
override fun apply(t: Any, u: String): String {
return when (t) {
is RuntimeType -> {
t.dependency?.also { addDependency(it) }
// for now, use the fully qualified type name
t.fullyQualifiedName()
}
is Symbol -> {
addDepsRecursively(t)
t.rustType().render(fullyQualified = true)
}
else -> throw CodegenException("Invalid type provided to RustSymbolFormatter: $t")
}
}
}
}