Skip to content
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

Remove importresolver package #5

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
7beadd7
Use 4 spaces instead of 2 for default indent
pranjalvachaspati-toast Oct 12, 2021
5665e73
Remove message.stg
pranjalvachaspati-toast Oct 13, 2021
2cc5b3a
Remove Descriptor template
pranjalvachaspati-toast Oct 13, 2021
7ecc79f
Remove Descriptor template
pranjalvachaspati-toast Oct 13, 2021
14bd064
Remove dead code in header template and most of services template.
pranjalvachaspati-toast Oct 13, 2021
0861dcd
Set locale for decapitalize to get rid of compiler warning.
pranjalvachaspati-toast Oct 13, 2021
1cca8d0
Remove unused templates
pranjalvachaspati-toast Oct 13, 2021
151e25c
Create subpackage for annotators.
pranjalvachaspati-toast Oct 13, 2021
945b990
Merge branch 'kotlinpoet' of https://github.com/andrewparmet/protokt …
pranjalvachaspati-toast Oct 13, 2021
e24fb1d
Move methodType to kotlinpoet and get rid of services.stg
pranjalvachaspati-toast Oct 13, 2021
0369624
Remove Oneof stringtemplates.
pranjalvachaspati-toast Oct 13, 2021
5964ab4
Get rid of a couple renderers
pranjalvachaspati-toast Oct 13, 2021
46839ce
Migrate boxing & default value renderers away from StringTemplate.
pranjalvachaspati-toast Oct 14, 2021
f12ca3c
Remove sizeof stringtemplates.
pranjalvachaspati-toast Oct 15, 2021
9981c53
Add non-stringtemplate serializer generation
pranjalvachaspati-toast Oct 15, 2021
ec526a1
Get rid of renderers stringtemplate
pranjalvachaspati-toast Oct 15, 2021
91accd6
Remove options stringtemplate
pranjalvachaspati-toast Oct 15, 2021
8aec02e
--amend
pranjalvachaspati-toast Oct 15, 2021
8223782
Merge branch 'kotlinpoet' of https://github.com/andrewparmet/protokt …
pranjalvachaspati-toast Oct 15, 2021
4f4d40a
Convert deserializer to use kotlinpoet
pranjalvachaspati-toast Oct 16, 2021
d4af5e5
Create packages for import resolution and descriptor stuff
pranjalvachaspati-toast Oct 16, 2021
f38ffed
Create packages for import resolution and descriptor stuff
pranjalvachaspati-toast Oct 16, 2021
2125158
This merge required some additional changes - mostly changing Strings…
pranjalvachaspati-toast Oct 18, 2021
9b264a3
Additional changes from Strings to CodeBlocks
pranjalvachaspati-toast Oct 18, 2021
8bb76ce
Disable non-kotlinpoet import resolution
pranjalvachaspati-toast Oct 18, 2021
db9d992
Remove importresolution package
pranjalvachaspati-toast Oct 18, 2021
764782c
Merge branch 'kotlinpoet' of https://github.com/andrewparmet/protokt …
pranjalvachaspati-toast Oct 18, 2021
1f53989
Make fixes for PR comments
pranjalvachaspati-toast Oct 19, 2021
e84eae0
Use DSL typename in DeserializerAnnotator
pranjalvachaspati-toast Oct 19, 2021
a4193df
Remove dependency on stringtemplate
pranjalvachaspati-toast Oct 19, 2021
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
Prev Previous commit
Next Next commit
Convert deserializer to use kotlinpoet
  • Loading branch information
pranjalvachaspati-toast committed Oct 16, 2021
commit 4f4d40ad500fbbe8c95ace955c6a2acb3b4223ec
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.TypeVariableName
import com.squareup.kotlinpoet.asTypeName
import com.squareup.kotlinpoet.buildCodeBlock
import com.toasttab.protokt.codegen.annotators.Annotator.Context
import com.toasttab.protokt.codegen.annotators.MessageAnnotator.Companion.IDEAL_MAX_WIDTH
import com.toasttab.protokt.codegen.annotators.PropertyAnnotator.Companion.annotateProperties
Expand All @@ -38,6 +39,7 @@ import com.toasttab.protokt.codegen.impl.Wrapper.valueWrapped
import com.toasttab.protokt.codegen.impl.Wrapper.wrapField
import com.toasttab.protokt.codegen.impl.Wrapper.wrapped
import com.toasttab.protokt.codegen.impl.Wrapper.wrapperName
import com.toasttab.protokt.codegen.impl.buildFunSpec
import com.toasttab.protokt.codegen.model.FieldType
import com.toasttab.protokt.codegen.protoc.Message
import com.toasttab.protokt.codegen.protoc.Oneof
Expand All @@ -48,22 +50,32 @@ import com.toasttab.protokt.codegen.template.Message.Message.DeserializerInfo.As
import com.toasttab.protokt.codegen.template.Message.Message.PropertyInfo
import com.toasttab.protokt.rt.KtDeserializer
import com.toasttab.protokt.rt.KtMessageDeserializer
import com.toasttab.protokt.rt.UnknownFieldSet

internal class DeserializerAnnotator
private constructor(
private val msg: Message,
private val ctx: Context
) {
/** Creates a {@see KtDeserializer<T>} companion object, where T is the Kotlin type for this Message.
*
* Contains functions:
* - deserialize(deserializer : KTMessageDeserializer) : T
* - invoke(dsl: ApiDsl.() -> Unit): Api
*
* */
private fun annotateDeserializer(): TypeSpec {
val deserializerInfo = annotateDeserializerOld()
val properties = annotateProperties(msg, ctx)

return TypeSpec.companionObjectBuilder("Deserializer")
// KtDeserializer<MessageType>
.addSuperinterface(
KtDeserializer::class
.asTypeName()
.parameterizedBy(TypeVariableName(msg.name))
)
// (MessageTypeDsl.() -> Unit) -> Message
pranjalvachaspati-toast marked this conversation as resolved.
Show resolved Hide resolved
.addSuperinterface(
LambdaTypeName.get(
null,
Expand All @@ -79,38 +91,27 @@ private constructor(
TypeVariableName(msg.name)
)
)
.addFunction(
FunSpec.builder("deserialize")
.addModifiers(KModifier.OVERRIDE)
.addParameter("deserializer", KtMessageDeserializer::class)
.returns(TypeVariableName(msg.name))
.addCode(
if (properties.isNotEmpty()) {
properties.joinToString("\n") { "var " + deserializeVar(it) } + "\n"
} else {
""
} +
"""
|var unknownFields: UnknownFieldSet.Builder? = null
|
|while (true) {
| when (deserializer.readTag()) {
| 0 ->
| return ${msg.name}(
| ${constructorLines(properties)}
| )
|${assignmentLines(deserializerInfo)}
| else ->
| unknownFields =
| (unknownFields ?: UnknownFieldSet.Builder()).also {
| it.add(deserializer.readUnknown())
| }
| }
|}
""".trimMargin()
)
.build()
)
.addFunction( buildFunSpec("deserialize") {

addModifiers(KModifier.OVERRIDE)
addParameter("deserializer", KtMessageDeserializer::class)
returns(TypeVariableName(msg.name))


if (properties.isNotEmpty()) {
properties.forEach {addStatement("var %L", deserializeVar(it))}
}
addStatement("var unknownFields: %T? = null", UnknownFieldSet.Builder::class )
beginControlFlow("while (true)")
beginControlFlow("when(deserializer.readTag())")
addStatement("0 -> return %N(%L)", msg.name, constructorLines(properties))
deserializerInfo.forEach() { addStatement("%L -> %L = %L", it.tag, it.assignment.fieldName, it.assignment.value)}
// We need to do this statement as two addStatements because otherwise it wraps the line after also, which is invalid Kotlin.
addStatement("else -> unknownFields = (unknownFields ?: %T.Builder()).also {", UnknownFieldSet::class)
addStatement("it.add(deserializer.readUnknown()) }")
endControlFlow()
endControlFlow()
} )
.addFunction(
FunSpec.builder("invoke")
.addModifiers(KModifier.OVERRIDE)
Expand All @@ -123,29 +124,17 @@ private constructor(
Unit::class.asTypeName()
)
)
.addCode("return ${msg.name}Dsl().apply(dsl).build()")
.addStatement("return ${msg.name}Dsl().apply(dsl).build()")
pranjalvachaspati-toast marked this conversation as resolved.
Show resolved Hide resolved
.build()
)
.build()
}

private fun constructorLines(properties: List<PropertyInfo>) =
properties.joinToString("") {
deserializeWrapper(it) + ",\n "
} + "UnknownFieldSet.from(unknownFields)"
private fun constructorLines(properties: List<PropertyInfo>) = buildCodeBlock {
properties.forEach() {add("%L,\n", deserializeWrapper(it))}
add("%T.from(unknownFields)", UnknownFieldSet::class)
}

private fun assignmentLines(deserializerInfo: List<DeserializerInfo>) =
deserializerInfo.joinToString("\n") {
if (it.repeated) {
"""
| ${it.tag} ->
| ${it.assignment.fieldName} =
| ${it.assignment.value}
""".trimMargin()
} else {
" ${it.tag} -> ${it.assignment.fieldName} = ${it.assignment.value}"
}
}

private fun annotateDeserializerOld(): List<DeserializerInfo> =
msg.flattenedSortedFields().flatMap { (field, oneOf) ->
Expand Down Expand Up @@ -191,7 +180,7 @@ private constructor(
4 + // when (...)
field.tag.toString().length +
4 + // ` -> `
field.name.length +
field.fieldName.length +
3 // ` = `

val spaceLeft = IDEAL_MAX_WIDTH - spaceTaken
Expand All @@ -215,7 +204,7 @@ private constructor(
)

private fun oneofDes(f: Oneof, ff: StandardField) =
"${f.name}.${f.fieldTypeNames.getValue(ff.name)}(${deserializeString(ff, ctx, false)})"
"${f.name}.${f.fieldTypeNames.getValue(ff.fieldName)}(${deserializeString(ff, ctx, false)})"
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yikes. (I know this came straight from StringTemplate.)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup, there are a few messy templates in here that should probably be cleaned up and kotlinpoet-ified.


companion object {
fun annotateDeserializer(msg: Message, ctx: Context) =
Expand All @@ -235,7 +224,7 @@ fun deserializeString(f: StandardField, ctx: Context, packed: Boolean): String {
| add($wrappedRead)
| }
| }
""".trimIndent()
""".trimMargin()
else -> wrappedRead
}
}
Expand All @@ -253,7 +242,7 @@ fun deserializeMap(f: StandardField, options: Options?, read: String): String {
| ) }
| }
| }
""".trimIndent()
""".trimMargin()
}

private fun StandardField.readFn(ctx: Context) =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ import com.toasttab.protokt.codegen.impl.Deprecation.hasDeprecation
import com.toasttab.protokt.codegen.impl.Deprecation.renderOptions
import com.toasttab.protokt.codegen.impl.Implements.doesImplement
import com.toasttab.protokt.codegen.impl.Implements.implements
import com.toasttab.protokt.codegen.model.PPackage
import com.toasttab.protokt.codegen.protoc.Message
import com.toasttab.protokt.codegen.template.Message.Message.MessageInfo
import com.toasttab.protokt.codegen.template.Message.Message.PropertyInfo
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ private constructor(
}

private fun condition(f: Oneof, ff: StandardField, type: String) =
"${oneOfScope(f, type, ctx)}.${f.fieldTypeNames.getValue(ff.name)}"
"${oneOfScope(f, type, ctx)}.${f.fieldTypeNames.getValue(ff.fieldName)}"

private fun oneofSizeOfString(o: Oneof, f: StandardField) =
if (!o.hasNonNullOption) {
Expand Down Expand Up @@ -183,7 +183,7 @@ private constructor(
private fun oneofSize(f: Oneof, type: String) =
f.fields.map {
ConditionalParams(
"${oneOfScope(f, type, ctx)}.${f.fieldTypeNames.getValue(it.name)}",
"${oneOfScope(f, type, ctx)}.${f.fieldTypeNames.getValue(it.fieldName)}",
sizeOfString(
it,
interceptSizeof(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ private constructor(
}

private fun oneof(f: Oneof, ff: StandardField) =
f.fieldTypeNames.getValue(ff.name).let { oneofFieldTypeName ->
f.fieldTypeNames.getValue(ff.fieldName).let { oneofFieldTypeName ->
oneofFieldTypeName to info(ff, oneofFieldTypeName)
}

Expand All @@ -111,7 +111,7 @@ private constructor(
oneofFieldTypeName: String
) =
Info(
fieldName = f.name,
fieldName = f.fieldName,
type = qualifyWrapperType(
f,
PClass.fromName(oneofFieldTypeName),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.toasttab.protokt.codegen.annotators

import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.ParameterizedTypeName
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.toasttab.protokt.codegen.template.Message.Message.PropertyInfo
Expand All @@ -23,13 +24,11 @@ fun deserializeValue(p: PropertyInfo) =
}

fun deserializeVar(p: PropertyInfo) =
p.name +
if (p.fieldType == "MESSAGE" || p.repeated || p.oneof || p.nullable || p.wrapped) {
": " + deserializeType(p)
} else {
""
} +
" = " + deserializeValue(p)
if (p.fieldType == "MESSAGE" || p.repeated || p.oneof || p.nullable || p.wrapped) {
CodeBlock.of("%L : %T = %L", p.name, deserializeType(p), deserializeValue(p))
} else {
CodeBlock.of("%L = %L", p.name, deserializeValue(p))
}

fun deserializeWrapper(p: PropertyInfo) =
if (p.nonNullOption) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ private constructor(

private fun oneOfSer(f: Oneof, ff: StandardField, type: String) =
ConditionalParams(
"${oneOfScope(f, type, ctx)}.${f.fieldTypeNames.getValue(ff.name)}",
"${oneOfScope(f, type, ctx)}.${f.fieldTypeNames.getValue(ff.fieldName)}",
serializeString(ff, Some(f.fieldName))
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,5 @@ private fun typeNames(m: Message): Sequence<String> =

private fun typeNames(o: Oneof) =
o.fields.asSequence()
.map { o.fieldTypeNames.getValue(it.name) }
.map { o.fieldTypeNames.getValue(it.fieldName) }
.map { PClass.fromName(it).simpleName }
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

package com.toasttab.protokt.codegen.impl

import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.TypeName
Expand Down Expand Up @@ -44,3 +45,7 @@ fun constructorProperty(name: String, type: TypeName, override: Boolean = false)
addModifiers(KModifier.OVERRIDE)
}
}.build()

fun buildFunSpec(name : String, funSpecBuilder: FunSpec.Builder.() -> Unit): FunSpec {
return FunSpec.builder(name).apply(funSpecBuilder).build()
}
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ object Wrapper {
// Protobuf primitives have no typeName
requireNotNull(type.kotlinRepresentation) {
"no kotlin representation for type of " +
"$name: $type"
"$fieldName: $type"
}
},
{ getClass(typePClass, ctx) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,6 @@ private fun toStandard(
toFieldType(fdp.type).let { type ->
StandardField(
number = fdp.number,
name = newFieldName(fdp.name, usedFieldNames),
type = type,
repeated = fdp.label == LABEL_REPEATED,
optional = optional(alwaysRequired, fdp, ctx),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,6 @@ sealed class Field {

class StandardField(
val number: Int,
val name: String,
override val fieldName: String,
val type: FieldType,
val typePClass: PClass,
Expand All @@ -117,6 +116,15 @@ class StandardField(
get() = mapEntry != null
}

class Oneof(
val name: String,
override val fieldName: String,
val fields: List<StandardField>,
val fieldTypeNames: Map<String, String>,
val options: OneofOptions,
val index: Int
) : Field()

class MapEntry(
val key: StandardField,
val value: StandardField
Expand All @@ -127,14 +135,6 @@ class FieldOptions(
val protokt: Protokt.ProtoktFieldOptions
)

class Oneof(
val name: String,
override val fieldName: String,
val fields: List<StandardField>,
val fieldTypeNames: Map<String, String>,
val options: OneofOptions,
val index: Int
) : Field()

class OneofOptions(
val default: DescriptorProtos.OneofOptions,
Expand Down