square / wire

gRPC and protocol buffers for Android, Kotlin, Swift and Java.
https://square.github.io/wire/
Apache License 2.0
4.25k stars 571 forks source link

Generated Kotlin code adds unnecessary underscore #3157

Closed simonsickle closed 1 week ago

simonsickle commented 2 weeks ago

Context

I have a simple proto file that is essentially representing a map with a name and value field.

message TestMap {
  optional string name = 2;
  optional string value = 3;
}

I expect the generated Kotlin code to look something like

Actual

The generated Kotlin code is generated with an underscore appended to the end of the value property name.

public class TestMap(
  @field:WireField(
    tag = 2,
    adapter = "com.squareup.wire.ProtoAdapter#STRING",
    schemaIndex = 0,
  )
  public val name: String? = null,
  @field:WireField(
    tag = 3,
    adapter = "com.squareup.wire.ProtoAdapter#STRING",
    declaredName = "value",
    schemaIndex = 1,
  )
  public val value_: String? = null,
  unknownFields: ByteString = ByteString.EMPTY,
) : Message<TestMap, Nothing>(ADAPTER, unknownFields)

Expected

I expect value to not contain an underscore since it is not a keyword as a property name.

public class TestMap(
  @field:WireField(
    tag = 2,
    adapter = "com.squareup.wire.ProtoAdapter#STRING",
    schemaIndex = 0,
  )
  public val name: String? = null,
  @field:WireField(
    tag = 3,
    adapter = "com.squareup.wire.ProtoAdapter#STRING",
    declaredName = "value",
    schemaIndex = 1,
  )
  public val value: String? = null,
  unknownFields: ByteString = ByteString.EMPTY,
) : Message<TestMap, Nothing>(ADAPTER, unknownFields)
oldergod commented 1 week ago

The _ is adding by KotlinPoet which does so because value can be a keyword depending on its usage. If you want backtick instead, you can use escapeKotlinKeywords = true in the kotlin {} block like so

wire {
  kotlin {
    escapeKotlinKeywords = true
  }
}
simonsickle commented 1 week ago

Since it isn't a keyword in this scenario, escaping doesn't seem like the correct behavior to me (and the conventions plugin here won't let me configure wire as far as I can tell, no one internally seems to be using escapeKotlinKeywords).

That said, this issue is in the KotlinPoet project, not Wire.

simonsickle commented 1 week ago

Further context for the next person, https://github.com/square/kotlinpoet/pull/994

This seems to be expected behavior to avoid having to write all of the compiler rules into KotlinPoet