mirror of
https://github.com/fankes/moshi.git
synced 2025-10-18 15:39:22 +08:00
Update plugin spotless to v6.14.0 (#1620)
* Update plugin spotless to v6.14.0 * Update Spotless version and apply --------- Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: Jake Wharton <jw@squareup.com>
This commit is contained in:
@@ -51,14 +51,16 @@ spotless {
|
||||
targetExclude("**/build/**")
|
||||
}
|
||||
kotlin {
|
||||
ktlint(libs.versions.ktlint.get()).editorConfigOverride(mapOf("indent_size" to "2"))
|
||||
ktlint(libs.versions.ktlint.get()).editorConfigOverride(
|
||||
mapOf("ktlint_standard_filename" to "disabled"),
|
||||
)
|
||||
target("**/*.kt")
|
||||
trimTrailingWhitespace()
|
||||
endWithNewline()
|
||||
targetExclude("**/Dependencies.kt", "**/build/**")
|
||||
}
|
||||
kotlinGradle {
|
||||
ktlint(libs.versions.ktlint.get()).editorConfigOverride(mapOf("indent_size" to "2"))
|
||||
ktlint(libs.versions.ktlint.get())
|
||||
target("**/*.gradle.kts")
|
||||
trimTrailingWhitespace()
|
||||
endWithNewline()
|
||||
|
@@ -15,7 +15,7 @@ dependencies {
|
||||
tasks.withType<KotlinCompile>().configureEach {
|
||||
kotlinOptions {
|
||||
freeCompilerArgs += listOf(
|
||||
"-opt-in=kotlin.ExperimentalStdlibApi"
|
||||
"-opt-in=kotlin.ExperimentalStdlibApi",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
@@ -30,7 +30,7 @@ import kotlin.annotation.AnnotationRetention.RUNTIME
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class ExampleClass(
|
||||
val type: Int,
|
||||
@JsonString val rawJson: String
|
||||
@JsonString val rawJson: String,
|
||||
)
|
||||
|
||||
@Retention(RUNTIME)
|
||||
|
@@ -6,7 +6,7 @@ kotlin = "1.7.0"
|
||||
kotlinCompileTesting = "1.4.9"
|
||||
kotlinpoet = "1.12.0"
|
||||
ksp = "1.7.0-1.0.6"
|
||||
ktlint = "0.45.2"
|
||||
ktlint = "0.48.2"
|
||||
|
||||
[plugins]
|
||||
dokka = { id = "org.jetbrains.dokka", version = "1.7.20" }
|
||||
@@ -14,7 +14,7 @@ japicmp = { id = "me.champeau.gradle.japicmp", version = "0.2.9" }
|
||||
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
|
||||
mavenPublish = { id = "com.vanniktech.maven.publish", version = "0.24.0" }
|
||||
mavenShadow = { id = "com.github.johnrengelman.shadow", version = "7.1.2" }
|
||||
spotless = { id = "com.diffplug.spotless", version = "6.7.1" }
|
||||
spotless = { id = "com.diffplug.spotless", version = "6.14.0" }
|
||||
|
||||
[libraries]
|
||||
asm = "org.ow2.asm:asm:9.4"
|
||||
|
@@ -23,7 +23,7 @@ import java.util.Date
|
||||
"""This class moved to avoid a package name conflict in the Java Platform Module System.
|
||||
The new class is com.squareup.moshi.adapters.Rfc3339DateJsonAdapter.""",
|
||||
replaceWith = ReplaceWith("com.squareup.moshi.adapters.Rfc3339DateJsonAdapter"),
|
||||
level = DeprecationLevel.ERROR
|
||||
level = DeprecationLevel.ERROR,
|
||||
)
|
||||
public class Rfc3339DateJsonAdapter : JsonAdapter<Date>() {
|
||||
|
||||
|
@@ -78,12 +78,12 @@ public class EnumJsonAdapter<T : Enum<T>> internal constructor(
|
||||
if (!useFallbackValue) {
|
||||
val name = reader.nextString()
|
||||
throw JsonDataException(
|
||||
"Expected one of ${nameStrings.toList()} but was $name at path $path"
|
||||
"Expected one of ${nameStrings.toList()} but was $name at path $path",
|
||||
)
|
||||
}
|
||||
if (reader.peek() != STRING) {
|
||||
throw JsonDataException(
|
||||
"Expected a string but was ${reader.peek()} at path $path"
|
||||
"Expected a string but was ${reader.peek()} at path $path",
|
||||
)
|
||||
}
|
||||
reader.skipValue()
|
||||
@@ -94,7 +94,7 @@ public class EnumJsonAdapter<T : Enum<T>> internal constructor(
|
||||
override fun toJson(writer: JsonWriter, value: T?) {
|
||||
if (value == null) {
|
||||
throw NullPointerException(
|
||||
"value was null! Wrap in .nullSafe() to write nullable values."
|
||||
"value was null! Wrap in .nullSafe() to write nullable values.",
|
||||
)
|
||||
}
|
||||
writer.value(nameStrings[value.ordinal])
|
||||
|
@@ -107,7 +107,6 @@ internal fun String.parseIsoDate(): Date {
|
||||
return GregorianCalendar(year, month - 1, day).time
|
||||
}
|
||||
if (hasT) {
|
||||
|
||||
// extract hours, minutes, seconds and milliseconds
|
||||
hour = parseInt(this, 1.let { offset += it; offset }, 2.let { offset += it; offset })
|
||||
if (checkOffset(this, offset, ':')) {
|
||||
@@ -164,14 +163,14 @@ internal fun String.parseIsoDate(): Date {
|
||||
val cleaned = act.replace(":", "")
|
||||
if (cleaned != timezoneId) {
|
||||
throw IndexOutOfBoundsException(
|
||||
"Mismatching time zone indicator: $timezoneId given, resolves to ${timezone.id}"
|
||||
"Mismatching time zone indicator: $timezoneId given, resolves to ${timezone.id}",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw IndexOutOfBoundsException(
|
||||
"Invalid time zone indicator '$timezoneIndicator'"
|
||||
"Invalid time zone indicator '$timezoneIndicator'",
|
||||
)
|
||||
}
|
||||
val calendar: Calendar = GregorianCalendar(timezone)
|
||||
|
@@ -103,7 +103,7 @@ public class PolymorphicJsonAdapterFactory<T> internal constructor(
|
||||
private val labelKey: String,
|
||||
private val labels: List<String>,
|
||||
private val subtypes: List<Type>,
|
||||
private val fallbackJsonAdapter: JsonAdapter<Any>?
|
||||
private val fallbackJsonAdapter: JsonAdapter<Any>?,
|
||||
) : Factory {
|
||||
/** Returns a new factory that decodes instances of `subtype`. */
|
||||
public fun withSubtype(subtype: Class<out T>, label: String): PolymorphicJsonAdapterFactory<T> {
|
||||
@@ -121,7 +121,7 @@ public class PolymorphicJsonAdapterFactory<T> internal constructor(
|
||||
labelKey = labelKey,
|
||||
labels = newLabels,
|
||||
subtypes = newSubtypes,
|
||||
fallbackJsonAdapter = fallbackJsonAdapter
|
||||
fallbackJsonAdapter = fallbackJsonAdapter,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -133,14 +133,14 @@ public class PolymorphicJsonAdapterFactory<T> internal constructor(
|
||||
* it within your implementation of [JsonAdapter.fromJson]
|
||||
*/
|
||||
public fun withFallbackJsonAdapter(
|
||||
fallbackJsonAdapter: JsonAdapter<Any>?
|
||||
fallbackJsonAdapter: JsonAdapter<Any>?,
|
||||
): PolymorphicJsonAdapterFactory<T> {
|
||||
return PolymorphicJsonAdapterFactory(
|
||||
baseType = baseType,
|
||||
labelKey = labelKey,
|
||||
labels = labels,
|
||||
subtypes = subtypes,
|
||||
fallbackJsonAdapter = fallbackJsonAdapter
|
||||
fallbackJsonAdapter = fallbackJsonAdapter,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -161,7 +161,7 @@ public class PolymorphicJsonAdapterFactory<T> internal constructor(
|
||||
|
||||
override fun toJson(writer: JsonWriter, value: Any?) {
|
||||
throw IllegalArgumentException(
|
||||
"Expected one of $subtypes but found $value, a ${value?.javaClass}. Register this subtype."
|
||||
"Expected one of $subtypes but found $value, a ${value?.javaClass}. Register this subtype.",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -181,7 +181,7 @@ public class PolymorphicJsonAdapterFactory<T> internal constructor(
|
||||
private val labels: List<String>,
|
||||
private val subtypes: List<Type>,
|
||||
private val jsonAdapters: List<JsonAdapter<Any>>,
|
||||
private val fallbackJsonAdapter: JsonAdapter<Any>?
|
||||
private val fallbackJsonAdapter: JsonAdapter<Any>?,
|
||||
) : JsonAdapter<Any>() {
|
||||
/** Single-element options containing the label's key only. */
|
||||
private val labelKeyOptions: Options = Options.of(labelKey)
|
||||
@@ -211,7 +211,7 @@ public class PolymorphicJsonAdapterFactory<T> internal constructor(
|
||||
val labelIndex = reader.selectString(labelOptions)
|
||||
if (labelIndex == -1 && fallbackJsonAdapter == null) {
|
||||
throw JsonDataException(
|
||||
"Expected one of $labels for key '$labelKey' but found '${reader.nextString()}'. Register a subtype for this label."
|
||||
"Expected one of $labels for key '$labelKey' but found '${reader.nextString()}'. Register a subtype for this label.",
|
||||
)
|
||||
}
|
||||
return labelIndex
|
||||
@@ -259,7 +259,7 @@ public class PolymorphicJsonAdapterFactory<T> internal constructor(
|
||||
labelKey = labelKey,
|
||||
labels = emptyList(),
|
||||
subtypes = emptyList(),
|
||||
fallbackJsonAdapter = null
|
||||
fallbackJsonAdapter = null,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
@@ -34,7 +34,7 @@ tasks.withType<Test>().configureEach {
|
||||
"--add-opens=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED",
|
||||
"--add-opens=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED",
|
||||
"--add-opens=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED",
|
||||
"--add-opens=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED"
|
||||
"--add-opens=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -91,7 +91,7 @@ val shadowJar = tasks.shadowJar.apply {
|
||||
relocate("com.squareup.kotlinpoet.metadata", "com.squareup.moshi.kotlinpoet.metadata")
|
||||
relocate(
|
||||
"com.squareup.kotlinpoet.classinspector",
|
||||
"com.squareup.moshi.kotlinpoet.classinspector"
|
||||
"com.squareup.moshi.kotlinpoet.classinspector",
|
||||
)
|
||||
relocate("kotlinx.metadata", "com.squareup.moshi.kotlinx.metadata")
|
||||
transformers.add(ServiceFileTransformer())
|
||||
|
@@ -54,14 +54,14 @@ private const val TO_STRING_SIZE_BASE = TO_STRING_PREFIX.length + 1 // 1 is the
|
||||
@InternalMoshiCodegenApi
|
||||
public class AdapterGenerator(
|
||||
private val target: TargetType,
|
||||
private val propertyList: List<PropertyGenerator>
|
||||
private val propertyList: List<PropertyGenerator>,
|
||||
) {
|
||||
|
||||
private companion object {
|
||||
private val INT_TYPE_BLOCK = CodeBlock.of("%T::class.javaPrimitiveType", INT)
|
||||
private val DEFAULT_CONSTRUCTOR_MARKER_TYPE_BLOCK = CodeBlock.of(
|
||||
"%M",
|
||||
MemberName(MOSHI_UTIL_PACKAGE, "DEFAULT_CONSTRUCTOR_MARKER")
|
||||
MemberName(MOSHI_UTIL_PACKAGE, "DEFAULT_CONSTRUCTOR_MARKER"),
|
||||
)
|
||||
private val CN_MOSHI = Moshi::class.asClassName()
|
||||
private val CN_TYPE = Type::class.asClassName()
|
||||
@@ -89,13 +89,13 @@ public class AdapterGenerator(
|
||||
"PLATFORM_CLASS_MAPPED_TO_KOTLIN",
|
||||
// Cover for calling fromJson() on a Nothing property type. Theoretically nonsensical but we
|
||||
// support it
|
||||
"IMPLICIT_NOTHING_TYPE_ARGUMENT_IN_RETURN_POSITION"
|
||||
"IMPLICIT_NOTHING_TYPE_ARGUMENT_IN_RETURN_POSITION",
|
||||
).let { suppressions ->
|
||||
AnnotationSpec.builder(Suppress::class)
|
||||
.useSiteTarget(FILE)
|
||||
.addMember(
|
||||
suppressions.indices.joinToString { "%S" },
|
||||
*suppressions
|
||||
*suppressions,
|
||||
)
|
||||
.build()
|
||||
}
|
||||
@@ -116,54 +116,55 @@ public class AdapterGenerator(
|
||||
|
||||
private val moshiParam = ParameterSpec.builder(
|
||||
nameAllocator.newName("moshi"),
|
||||
CN_MOSHI
|
||||
CN_MOSHI,
|
||||
).build()
|
||||
private val typesParam = ParameterSpec.builder(
|
||||
nameAllocator.newName("types"),
|
||||
ARRAY.parameterizedBy(CN_TYPE)
|
||||
ARRAY.parameterizedBy(CN_TYPE),
|
||||
)
|
||||
.build()
|
||||
private val readerParam = ParameterSpec.builder(
|
||||
nameAllocator.newName("reader"),
|
||||
JsonReader::class
|
||||
JsonReader::class,
|
||||
)
|
||||
.build()
|
||||
private val writerParam = ParameterSpec.builder(
|
||||
nameAllocator.newName("writer"),
|
||||
JsonWriter::class
|
||||
JsonWriter::class,
|
||||
)
|
||||
.build()
|
||||
|
||||
// Don't use NameAllocator here because it will add `_` to the name since it's a keyword, and that
|
||||
// results in it warning about not matching the overridden function's params.
|
||||
// https://github.com/square/moshi/issues/1502
|
||||
private val valueParam = ParameterSpec.builder(
|
||||
"value",
|
||||
originalTypeName.copy(nullable = true)
|
||||
originalTypeName.copy(nullable = true),
|
||||
)
|
||||
.build()
|
||||
private val jsonAdapterTypeName = JsonAdapter::class.asClassName().parameterizedBy(
|
||||
originalTypeName
|
||||
originalTypeName,
|
||||
)
|
||||
|
||||
// selectName() API setup
|
||||
private val optionsProperty = PropertySpec.builder(
|
||||
nameAllocator.newName("options"),
|
||||
JsonReader.Options::class.asTypeName(),
|
||||
KModifier.PRIVATE
|
||||
KModifier.PRIVATE,
|
||||
)
|
||||
.initializer(
|
||||
"%T.of(%L)",
|
||||
JsonReader.Options::class.asTypeName(),
|
||||
nonTransientProperties
|
||||
.map { CodeBlock.of("%S", it.jsonName) }
|
||||
.joinToCode(", ")
|
||||
.joinToCode(", "),
|
||||
)
|
||||
.build()
|
||||
|
||||
private val constructorProperty = PropertySpec.builder(
|
||||
nameAllocator.newName("constructorRef"),
|
||||
Constructor::class.asClassName().parameterizedBy(originalTypeName).copy(nullable = true),
|
||||
KModifier.PRIVATE
|
||||
KModifier.PRIVATE,
|
||||
)
|
||||
.addAnnotation(Volatile::class)
|
||||
.mutable(true)
|
||||
@@ -245,10 +246,10 @@ public class AdapterGenerator(
|
||||
" ${if (typeVariables.size == 1) "type" else "types"} for generic type variables [",
|
||||
typeVariables.joinToString(", ") { it.name },
|
||||
"], but received ",
|
||||
"${typesParam.name}.size"
|
||||
"${typesParam.name}.size",
|
||||
)
|
||||
.endControlFlow()
|
||||
.build()
|
||||
.build(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -274,8 +275,8 @@ public class AdapterGenerator(
|
||||
nameAllocator,
|
||||
typeRenderer,
|
||||
moshiParam,
|
||||
uniqueAdapter.name
|
||||
)
|
||||
uniqueAdapter.name,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -309,7 +310,7 @@ public class AdapterGenerator(
|
||||
size,
|
||||
TO_STRING_PREFIX,
|
||||
name,
|
||||
")"
|
||||
")",
|
||||
)
|
||||
.build()
|
||||
}
|
||||
@@ -425,7 +426,7 @@ public class AdapterGenerator(
|
||||
"%N = %N.fromJson(%N)",
|
||||
property.localName,
|
||||
nameAllocator[property.delegateKey],
|
||||
readerParam
|
||||
readerParam,
|
||||
)
|
||||
} else {
|
||||
val exception = unexpectedNull(property, readerParam)
|
||||
@@ -434,7 +435,7 @@ public class AdapterGenerator(
|
||||
property.localName,
|
||||
nameAllocator[property.delegateKey],
|
||||
readerParam,
|
||||
exception
|
||||
exception,
|
||||
)
|
||||
}
|
||||
if (property.hasConstructorDefault) {
|
||||
@@ -446,7 +447,7 @@ public class AdapterGenerator(
|
||||
result.addStatement(
|
||||
"%1L = %1L and 0x%2L.toInt()",
|
||||
maskNames[maskNameIndex],
|
||||
Integer.toHexString(inverted)
|
||||
Integer.toHexString(inverted),
|
||||
)
|
||||
} else {
|
||||
// Presence tracker for a mutable property
|
||||
@@ -460,7 +461,7 @@ public class AdapterGenerator(
|
||||
propertyIndex,
|
||||
property.localName,
|
||||
nameAllocator[property.delegateKey],
|
||||
readerParam
|
||||
readerParam,
|
||||
)
|
||||
} else {
|
||||
val exception = unexpectedNull(property, readerParam)
|
||||
@@ -470,7 +471,7 @@ public class AdapterGenerator(
|
||||
property.localName,
|
||||
nameAllocator[property.delegateKey],
|
||||
readerParam,
|
||||
exception
|
||||
exception,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -550,7 +551,7 @@ public class AdapterGenerator(
|
||||
val coreLookupBlock = CodeBlock.of(
|
||||
"%T::class.java.getDeclaredConstructor(%L)",
|
||||
originalRawTypeName,
|
||||
args
|
||||
args,
|
||||
)
|
||||
val lookupBlock = if (originalTypeName is ParameterizedTypeName) {
|
||||
CodeBlock.of("(%L·as·%T)", coreLookupBlock, nonNullConstructorType)
|
||||
@@ -560,16 +561,16 @@ public class AdapterGenerator(
|
||||
val initializerBlock = CodeBlock.of(
|
||||
"this.%1N·?: %2L.also·{ this.%1N·= it }",
|
||||
constructorProperty,
|
||||
lookupBlock
|
||||
lookupBlock,
|
||||
)
|
||||
val localConstructorProperty = PropertySpec.builder(
|
||||
nameAllocator.newName("localConstructor"),
|
||||
nonNullConstructorType
|
||||
nonNullConstructorType,
|
||||
)
|
||||
.addAnnotation(
|
||||
AnnotationSpec.builder(Suppress::class)
|
||||
.addMember("%S", "UNCHECKED_CAST")
|
||||
.build()
|
||||
.build(),
|
||||
)
|
||||
.initializer(initializerBlock)
|
||||
.build()
|
||||
@@ -577,7 +578,7 @@ public class AdapterGenerator(
|
||||
result.addCode(
|
||||
"«%L%N.newInstance(",
|
||||
returnOrResultAssignment,
|
||||
localConstructorProperty
|
||||
localConstructorProperty,
|
||||
)
|
||||
} else {
|
||||
// Standard constructor call. Don't omit generics for parameterized types even if they can be
|
||||
@@ -597,7 +598,7 @@ public class AdapterGenerator(
|
||||
result.addCode(
|
||||
"/*·%L·*/·%L",
|
||||
input.parameter.name,
|
||||
input.type.rawType().defaultPrimitiveValue()
|
||||
input.type.rawType().defaultPrimitiveValue(),
|
||||
)
|
||||
} else {
|
||||
result.addCode("%N", (input as ParameterProperty).property.localName)
|
||||
@@ -638,7 +639,7 @@ public class AdapterGenerator(
|
||||
"%N.%N = %N",
|
||||
resultName,
|
||||
property.name,
|
||||
property.localName
|
||||
property.localName,
|
||||
)
|
||||
result.endControlFlow()
|
||||
} else {
|
||||
@@ -646,7 +647,7 @@ public class AdapterGenerator(
|
||||
"%1N.%2N = %3N ?: %1N.%2N",
|
||||
resultName,
|
||||
property.name,
|
||||
property.localName
|
||||
property.localName,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -663,7 +664,7 @@ public class AdapterGenerator(
|
||||
MemberName(MOSHI_UTIL_PACKAGE, "unexpectedNull"),
|
||||
property.localName,
|
||||
property.jsonName,
|
||||
reader
|
||||
reader,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -677,7 +678,7 @@ public class AdapterGenerator(
|
||||
result.addStatement(
|
||||
"throw·%T(%S)",
|
||||
NullPointerException::class,
|
||||
"${valueParam.name} was null! Wrap in .nullSafe() to write nullable values."
|
||||
"${valueParam.name} was null! Wrap in .nullSafe() to write nullable values.",
|
||||
)
|
||||
result.endControlFlow()
|
||||
|
||||
@@ -690,7 +691,7 @@ public class AdapterGenerator(
|
||||
nameAllocator[property.delegateKey],
|
||||
writerParam,
|
||||
valueParam,
|
||||
property.name
|
||||
property.name,
|
||||
)
|
||||
}
|
||||
result.addStatement("%N.endObject()", writerParam)
|
||||
@@ -706,7 +707,7 @@ private fun FunSpec.Builder.addMissingPropertyCheck(property: PropertyGenerator,
|
||||
MemberName(MOSHI_UTIL_PACKAGE, "missingProperty"),
|
||||
property.localName,
|
||||
property.jsonName,
|
||||
readerParam
|
||||
readerParam,
|
||||
)
|
||||
addCode(" ?: throw·%L", missingPropertyBlock)
|
||||
}
|
||||
@@ -753,20 +754,20 @@ private sealed class FromJsonComponent {
|
||||
abstract val type: TypeName
|
||||
|
||||
data class ParameterOnly(
|
||||
override val parameter: TargetParameter
|
||||
override val parameter: TargetParameter,
|
||||
) : FromJsonComponent(), ParameterComponent {
|
||||
override val type: TypeName = parameter.type
|
||||
}
|
||||
|
||||
data class PropertyOnly(
|
||||
override val property: PropertyGenerator
|
||||
override val property: PropertyGenerator,
|
||||
) : FromJsonComponent(), PropertyComponent {
|
||||
override val type: TypeName = property.target.type
|
||||
}
|
||||
|
||||
data class ParameterProperty(
|
||||
override val parameter: TargetParameter,
|
||||
override val property: PropertyGenerator
|
||||
override val property: PropertyGenerator,
|
||||
) : FromJsonComponent(), ParameterComponent, PropertyComponent {
|
||||
override val type: TypeName = parameter.type
|
||||
}
|
||||
|
@@ -46,20 +46,20 @@ public data class DelegateKey(
|
||||
nameAllocator: NameAllocator,
|
||||
typeRenderer: TypeRenderer,
|
||||
moshiParameter: ParameterSpec,
|
||||
propertyName: String
|
||||
propertyName: String,
|
||||
): PropertySpec {
|
||||
val qualifierNames = jsonQualifiers.joinToString("") {
|
||||
"At${it.typeName.rawType().simpleName}"
|
||||
}
|
||||
val adapterName = nameAllocator.newName(
|
||||
"${type.toVariableName().replaceFirstChar { it.lowercase(Locale.US) }}${qualifierNames}Adapter",
|
||||
this
|
||||
this,
|
||||
)
|
||||
|
||||
val adapterTypeName = JsonAdapter::class.asClassName().parameterizedBy(type)
|
||||
val standardArgs = arrayOf(
|
||||
moshiParameter,
|
||||
typeRenderer.render(type)
|
||||
typeRenderer.render(type),
|
||||
)
|
||||
|
||||
val (initializerString, args) = when {
|
||||
@@ -81,7 +81,7 @@ private fun AnnotationSpec.asInstantiationExpression(): CodeBlock {
|
||||
return CodeBlock.of(
|
||||
"%T(%L)",
|
||||
typeName,
|
||||
members.joinToCode()
|
||||
members.joinToCode(),
|
||||
)
|
||||
}
|
||||
|
||||
|
@@ -20,6 +20,6 @@ package com.squareup.moshi.kotlin.codegen.api
|
||||
@Retention(value = AnnotationRetention.BINARY)
|
||||
@RequiresOptIn(
|
||||
level = RequiresOptIn.Level.WARNING,
|
||||
message = "This is an internal API and may change at any time."
|
||||
message = "This is an internal API and may change at any time.",
|
||||
)
|
||||
public annotation class InternalMoshiCodegenApi
|
||||
|
@@ -47,6 +47,6 @@ public object Options {
|
||||
|
||||
public val POSSIBLE_GENERATED_NAMES: Map<String, ClassName> = arrayOf(
|
||||
ClassName("javax.annotation.processing", "Generated"),
|
||||
ClassName("javax.annotation", "Generated")
|
||||
ClassName("javax.annotation", "Generated"),
|
||||
).associateBy { it.canonicalName }
|
||||
}
|
||||
|
@@ -24,7 +24,7 @@ import com.squareup.kotlinpoet.PropertySpec
|
||||
public class PropertyGenerator(
|
||||
public val target: TargetProperty,
|
||||
public val delegateKey: DelegateKey,
|
||||
public val isTransient: Boolean = false
|
||||
public val isTransient: Boolean = false,
|
||||
) {
|
||||
public val name: String = target.name
|
||||
public val jsonName: String = target.jsonName ?: target.name
|
||||
|
@@ -22,7 +22,7 @@ import com.squareup.kotlinpoet.KModifier
|
||||
public data class TargetConstructor(
|
||||
val parameters: LinkedHashMap<String, TargetParameter>,
|
||||
val visibility: KModifier,
|
||||
val signature: String?
|
||||
val signature: String?,
|
||||
) {
|
||||
init {
|
||||
visibility.checkIsVisibility()
|
||||
|
@@ -27,5 +27,5 @@ public data class TargetParameter(
|
||||
val hasDefault: Boolean,
|
||||
val jsonName: String? = null,
|
||||
val jsonIgnore: Boolean = false,
|
||||
val qualifiers: Set<AnnotationSpec>? = null
|
||||
val qualifiers: Set<AnnotationSpec>? = null,
|
||||
)
|
||||
|
@@ -26,7 +26,7 @@ public data class TargetProperty(
|
||||
val parameter: TargetParameter?,
|
||||
val visibility: KModifier,
|
||||
val jsonName: String?,
|
||||
val jsonIgnore: Boolean
|
||||
val jsonIgnore: Boolean,
|
||||
) {
|
||||
val name: String get() = propertySpec.name
|
||||
val type: TypeName get() = propertySpec.type
|
||||
|
@@ -63,7 +63,7 @@ internal abstract class TypeRenderer {
|
||||
CodeBlock.of(
|
||||
"%T.arrayOf(%L)",
|
||||
Types::class,
|
||||
renderObjectType(typeName.typeArguments[0])
|
||||
renderObjectType(typeName.typeArguments[0]),
|
||||
)
|
||||
} else {
|
||||
val builder = CodeBlock.builder().apply {
|
||||
@@ -97,7 +97,7 @@ internal abstract class TypeRenderer {
|
||||
method = "subtypeOf"
|
||||
}
|
||||
else -> throw IllegalArgumentException(
|
||||
"Unrepresentable wildcard type. Cannot have more than one bound: $typeName"
|
||||
"Unrepresentable wildcard type. Cannot have more than one bound: $typeName",
|
||||
)
|
||||
}
|
||||
CodeBlock.of("%T.%L(%L)", Types::class, method, render(target, forceBox = true))
|
||||
|
@@ -95,7 +95,7 @@ internal fun TypeName.asTypeBlock(): CodeBlock {
|
||||
CodeBlock.of(
|
||||
"%T.newInstance(%L, 0).javaClass",
|
||||
Array::class.java.asClassName(),
|
||||
componentType.rawType.asTypeBlock()
|
||||
componentType.rawType.asTypeBlock(),
|
||||
)
|
||||
} else {
|
||||
CodeBlock.of("%T::class.java", copy(nullable = false))
|
||||
@@ -148,7 +148,7 @@ internal fun TypeName.stripTypeVarVariance(resolver: TypeVariableResolver): Type
|
||||
}
|
||||
|
||||
internal fun ParameterizedTypeName.deepCopy(
|
||||
transform: (TypeName) -> TypeName
|
||||
transform: (TypeName) -> TypeName,
|
||||
): ParameterizedTypeName {
|
||||
return rawType.parameterizedBy(typeArguments.map { transform(it) })
|
||||
.copy(nullable = isNullable, annotations = annotations, tags = tags)
|
||||
@@ -156,7 +156,7 @@ internal fun ParameterizedTypeName.deepCopy(
|
||||
|
||||
internal fun TypeVariableName.deepCopy(
|
||||
variance: KModifier? = this.variance,
|
||||
transform: (TypeName) -> TypeName
|
||||
transform: (TypeName) -> TypeName,
|
||||
): TypeVariableName {
|
||||
return TypeVariableName(name = name, bounds = bounds.map { transform(it) }, variance = variance)
|
||||
.copy(nullable = isNullable, annotations = annotations, tags = tags)
|
||||
@@ -184,7 +184,7 @@ internal fun LambdaTypeName.deepCopy(transform: (TypeName) -> TypeName): TypeNam
|
||||
return LambdaTypeName.get(
|
||||
receiver?.let(transform),
|
||||
parameters.map { it.toBuilder(type = transform(it.type)).build() },
|
||||
transform(returnType)
|
||||
transform(returnType),
|
||||
).copy(nullable = isNullable, annotations = annotations, suspending = isSuspending)
|
||||
}
|
||||
|
||||
|
@@ -31,13 +31,13 @@ private val OBJECT_CLASS = ClassName("java.lang", "Object")
|
||||
*/
|
||||
internal class AppliedType private constructor(
|
||||
val element: TypeElement,
|
||||
private val mirror: DeclaredType
|
||||
private val mirror: DeclaredType,
|
||||
) {
|
||||
/** Returns all supertypes of this, recursively. Only [CLASS] is used as we can't really use other types. */
|
||||
@OptIn(DelicateKotlinPoetApi::class)
|
||||
fun superclasses(
|
||||
types: Types,
|
||||
result: LinkedHashSet<AppliedType> = LinkedHashSet()
|
||||
result: LinkedHashSet<AppliedType> = LinkedHashSet(),
|
||||
): LinkedHashSet<AppliedType> {
|
||||
result.add(this)
|
||||
for (supertype in types.directSupertypes(mirror)) {
|
||||
|
@@ -73,7 +73,7 @@ public class JsonClassCodegenProcessor : AbstractProcessor() {
|
||||
generatedType = processingEnv.options[OPTION_GENERATED]?.let {
|
||||
POSSIBLE_GENERATED_NAMES[it] ?: error(
|
||||
"Invalid option value for $OPTION_GENERATED. Found $it, " +
|
||||
"allowable values are $POSSIBLE_GENERATED_NAMES."
|
||||
"allowable values are $POSSIBLE_GENERATED_NAMES.",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -98,7 +98,7 @@ public class JsonClassCodegenProcessor : AbstractProcessor() {
|
||||
messager.printMessage(
|
||||
Diagnostic.Kind.ERROR,
|
||||
"@JsonClass can't be applied to $type: must be a Kotlin class",
|
||||
type
|
||||
type,
|
||||
)
|
||||
continue
|
||||
}
|
||||
@@ -115,10 +115,10 @@ public class JsonClassCodegenProcessor : AbstractProcessor() {
|
||||
AnnotationSpec.builder(generatedClassName)
|
||||
.addMember(
|
||||
"value = [%S]",
|
||||
JsonClassCodegenProcessor::class.java.canonicalName
|
||||
JsonClassCodegenProcessor::class.java.canonicalName,
|
||||
)
|
||||
.addMember("comments = %S", "https://github.com/square/moshi")
|
||||
.build()
|
||||
.build(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -136,7 +136,7 @@ public class JsonClassCodegenProcessor : AbstractProcessor() {
|
||||
|
||||
private fun adapterGenerator(
|
||||
element: TypeElement,
|
||||
cachedClassInspector: MoshiCachedClassInspector
|
||||
cachedClassInspector: MoshiCachedClassInspector,
|
||||
): AdapterGenerator? {
|
||||
val type = targetType(
|
||||
messager,
|
||||
@@ -159,7 +159,7 @@ public class JsonClassCodegenProcessor : AbstractProcessor() {
|
||||
messager.printMessage(
|
||||
Diagnostic.Kind.ERROR,
|
||||
"No property for required constructor parameter $name",
|
||||
element
|
||||
element,
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
@@ -66,7 +66,7 @@ private val VISIBILITY_MODIFIERS = setOf(
|
||||
KModifier.INTERNAL,
|
||||
KModifier.PRIVATE,
|
||||
KModifier.PROTECTED,
|
||||
KModifier.PUBLIC
|
||||
KModifier.PUBLIC,
|
||||
)
|
||||
|
||||
private fun Collection<KModifier>.visibility(): KModifier {
|
||||
@@ -78,7 +78,7 @@ internal fun primaryConstructor(
|
||||
targetElement: TypeElement,
|
||||
kotlinApi: TypeSpec,
|
||||
elements: Elements,
|
||||
messager: Messager
|
||||
messager: Messager,
|
||||
): TargetConstructor? {
|
||||
val primaryConstructor = kotlinApi.primaryConstructor ?: return null
|
||||
|
||||
@@ -101,14 +101,14 @@ internal fun primaryConstructor(
|
||||
messager.printMessage(
|
||||
ERROR,
|
||||
"No KmConstructor found for primary constructor.",
|
||||
targetElement
|
||||
targetElement,
|
||||
)
|
||||
null
|
||||
}
|
||||
return TargetConstructor(
|
||||
parameters,
|
||||
primaryConstructor.modifiers.visibility(),
|
||||
kmConstructorSignature
|
||||
kmConstructorSignature,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -127,7 +127,7 @@ internal fun targetType(
|
||||
messager.printMessage(
|
||||
ERROR,
|
||||
"@JsonClass can't be applied to $element: must be a Kotlin class",
|
||||
element
|
||||
element,
|
||||
)
|
||||
return null
|
||||
}
|
||||
@@ -138,7 +138,7 @@ internal fun targetType(
|
||||
messager.printMessage(
|
||||
ERROR,
|
||||
"@JsonClass can't be applied to $element: must be a Class type",
|
||||
element
|
||||
element,
|
||||
)
|
||||
return null
|
||||
}
|
||||
@@ -148,7 +148,7 @@ internal fun targetType(
|
||||
messager.printMessage(
|
||||
ERROR,
|
||||
"@JsonClass with 'generateAdapter = \"true\"' can't be applied to $element: code gen for enums is not supported or necessary",
|
||||
element
|
||||
element,
|
||||
)
|
||||
return null
|
||||
}
|
||||
@@ -156,7 +156,7 @@ internal fun targetType(
|
||||
messager.printMessage(
|
||||
ERROR,
|
||||
"@JsonClass can't be applied to $element: must be a Kotlin class",
|
||||
element
|
||||
element,
|
||||
)
|
||||
return null
|
||||
}
|
||||
@@ -164,7 +164,7 @@ internal fun targetType(
|
||||
messager.printMessage(
|
||||
ERROR,
|
||||
"@JsonClass can't be applied to $element: must not be an inner class",
|
||||
element
|
||||
element,
|
||||
)
|
||||
return null
|
||||
}
|
||||
@@ -172,7 +172,7 @@ internal fun targetType(
|
||||
messager.printMessage(
|
||||
ERROR,
|
||||
"@JsonClass can't be applied to $element: must not be sealed",
|
||||
element
|
||||
element,
|
||||
)
|
||||
return null
|
||||
}
|
||||
@@ -180,7 +180,7 @@ internal fun targetType(
|
||||
messager.printMessage(
|
||||
ERROR,
|
||||
"@JsonClass can't be applied to $element: must not be abstract",
|
||||
element
|
||||
element,
|
||||
)
|
||||
return null
|
||||
}
|
||||
@@ -188,7 +188,7 @@ internal fun targetType(
|
||||
messager.printMessage(
|
||||
ERROR,
|
||||
"@JsonClass can't be applied to $element: must not be local",
|
||||
element
|
||||
element,
|
||||
)
|
||||
return null
|
||||
}
|
||||
@@ -196,7 +196,7 @@ internal fun targetType(
|
||||
messager.printMessage(
|
||||
ERROR,
|
||||
"@JsonClass can't be applied to $element: must be internal or public",
|
||||
element
|
||||
element,
|
||||
)
|
||||
return null
|
||||
}
|
||||
@@ -211,7 +211,7 @@ internal fun targetType(
|
||||
messager.printMessage(
|
||||
ERROR,
|
||||
"No primary constructor found on $element",
|
||||
element
|
||||
element,
|
||||
)
|
||||
return null
|
||||
}
|
||||
@@ -220,7 +220,7 @@ internal fun targetType(
|
||||
ERROR,
|
||||
"@JsonClass can't be applied to $element: " +
|
||||
"primary constructor is not internal or public",
|
||||
element
|
||||
element,
|
||||
)
|
||||
return null
|
||||
}
|
||||
@@ -234,7 +234,7 @@ internal fun targetType(
|
||||
messager.printMessage(
|
||||
ERROR,
|
||||
"@JsonClass can't be applied to $element: supertype $superclass is not a Kotlin type",
|
||||
element
|
||||
element,
|
||||
)
|
||||
return null
|
||||
}
|
||||
@@ -272,7 +272,7 @@ internal fun targetType(
|
||||
.cast<TypeVariableName>()
|
||||
.map(TypeVariableName::name)
|
||||
.zip(apiSuperClass.typeArguments.asSequence())
|
||||
.associate { it }
|
||||
.associate { it },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -286,7 +286,7 @@ internal fun targetType(
|
||||
kotlinApi = supertypeApi,
|
||||
allowedTypeVars = typeVariables.toSet(),
|
||||
currentClass = appliedClassName,
|
||||
resolvedTypes = resolvedTypes
|
||||
resolvedTypes = resolvedTypes,
|
||||
)
|
||||
for ((name, property) in supertypeProperties) {
|
||||
properties.putIfAbsent(name, property)
|
||||
@@ -328,7 +328,7 @@ private fun resolveTypeArgs(
|
||||
propertyType: TypeName,
|
||||
resolvedTypes: List<ResolvedTypeMapping>,
|
||||
allowedTypeVars: Set<TypeVariableName>,
|
||||
entryStartIndex: Int = resolvedTypes.indexOfLast { it.target == targetClass }
|
||||
entryStartIndex: Int = resolvedTypes.indexOfLast { it.target == targetClass },
|
||||
): TypeName {
|
||||
val unwrappedType = propertyType.unwrapTypeAlias()
|
||||
|
||||
@@ -370,7 +370,7 @@ private fun declaredProperties(
|
||||
kotlinApi: TypeSpec,
|
||||
allowedTypeVars: Set<TypeVariableName>,
|
||||
currentClass: ClassName,
|
||||
resolvedTypes: List<ResolvedTypeMapping>
|
||||
resolvedTypes: List<ResolvedTypeMapping>,
|
||||
): Map<String, TargetProperty> {
|
||||
val result = mutableMapOf<String, TargetProperty>()
|
||||
for (initialProperty in kotlinApi.propertySpecs) {
|
||||
@@ -378,7 +378,7 @@ private fun declaredProperties(
|
||||
targetClass = currentClass,
|
||||
propertyType = initialProperty.type,
|
||||
resolvedTypes = resolvedTypes,
|
||||
allowedTypeVars = allowedTypeVars
|
||||
allowedTypeVars = allowedTypeVars,
|
||||
)
|
||||
val property = initialProperty.toBuilder(type = resolvedType).build()
|
||||
val name = property.name
|
||||
@@ -391,7 +391,7 @@ private fun declaredProperties(
|
||||
parameter = parameter,
|
||||
visibility = property.modifiers.visibility(),
|
||||
jsonName = parameter?.jsonName ?: property.annotations.jsonName() ?: name,
|
||||
jsonIgnore = isIgnored
|
||||
jsonIgnore = isIgnored,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -420,7 +420,7 @@ internal fun TargetProperty.generator(
|
||||
messager.printMessage(
|
||||
ERROR,
|
||||
"No default value for transient/ignored property $name",
|
||||
sourceElement
|
||||
sourceElement,
|
||||
)
|
||||
return null
|
||||
}
|
||||
@@ -431,7 +431,7 @@ internal fun TargetProperty.generator(
|
||||
messager.printMessage(
|
||||
ERROR,
|
||||
"property $name is not visible",
|
||||
sourceElement
|
||||
sourceElement,
|
||||
)
|
||||
return null
|
||||
}
|
||||
@@ -452,7 +452,7 @@ internal fun TargetProperty.generator(
|
||||
if (it.value != RetentionPolicy.RUNTIME) {
|
||||
messager.printMessage(
|
||||
ERROR,
|
||||
"JsonQualifier @${qualifierRawType.simpleName} must have RUNTIME retention"
|
||||
"JsonQualifier @${qualifierRawType.simpleName} must have RUNTIME retention",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -466,13 +466,13 @@ internal fun TargetProperty.generator(
|
||||
|
||||
return PropertyGenerator(
|
||||
this,
|
||||
DelegateKey(type, jsonQualifierSpecs)
|
||||
DelegateKey(type, jsonQualifierSpecs),
|
||||
)
|
||||
}
|
||||
|
||||
private fun List<AnnotationSpec>?.qualifiers(
|
||||
messager: Messager,
|
||||
elements: Elements
|
||||
elements: Elements,
|
||||
): Set<AnnotationSpec> {
|
||||
if (this == null) return setOf()
|
||||
return filterTo(mutableSetOf()) {
|
||||
|
@@ -32,7 +32,7 @@ private val OBJECT_CLASS = java.lang.Object::class.asClassName()
|
||||
*/
|
||||
internal class AppliedType private constructor(
|
||||
val type: KSClassDeclaration,
|
||||
val typeName: TypeName = type.toClassName()
|
||||
val typeName: TypeName = type.toClassName(),
|
||||
) {
|
||||
|
||||
/** Returns all super classes of this, recursively. Only [CLASS] is used as we can't really use other types. */
|
||||
|
@@ -48,7 +48,7 @@ public class JsonClassSymbolProcessorProvider : SymbolProcessorProvider {
|
||||
}
|
||||
|
||||
private class JsonClassSymbolProcessor(
|
||||
environment: SymbolProcessorEnvironment
|
||||
environment: SymbolProcessorEnvironment,
|
||||
) : SymbolProcessor {
|
||||
|
||||
private companion object {
|
||||
@@ -103,7 +103,7 @@ private class JsonClassSymbolProcessor(
|
||||
preparedAdapter.proguardConfig?.writeTo(codeGenerator, originatingFile)
|
||||
} catch (e: Exception) {
|
||||
logger.error(
|
||||
"Error preparing ${type.simpleName.asString()}: ${e.stackTrace.joinToString("\n")}"
|
||||
"Error preparing ${type.simpleName.asString()}: ${e.stackTrace.joinToString("\n")}",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -152,7 +152,7 @@ private fun ProguardConfig.writeTo(codeGenerator: CodeGenerator, originatingKSFi
|
||||
dependencies = Dependencies(aggregating = false, originatingKSFile),
|
||||
packageName = "",
|
||||
fileName = outputFilePathWithoutExtension(targetClass.canonicalName),
|
||||
extensionName = "pro"
|
||||
extensionName = "pro",
|
||||
)
|
||||
// Don't use writeTo(file) because that tries to handle directories under the hood
|
||||
OutputStreamWriter(file, StandardCharsets.UTF_8)
|
||||
|
@@ -89,8 +89,9 @@ private fun addValueToBlock(value: Any, resolver: Resolver, member: CodeBlock.Bu
|
||||
}
|
||||
is KSName ->
|
||||
member.add(
|
||||
"%T.%L", ClassName.bestGuess(value.getQualifier()),
|
||||
value.getShortName()
|
||||
"%T.%L",
|
||||
ClassName.bestGuess(value.getQualifier()),
|
||||
value.getShortName(),
|
||||
)
|
||||
is KSAnnotation -> member.add("%L", value.toAnnotationSpec(resolver))
|
||||
else -> member.add(memberForValue(value))
|
||||
|
@@ -48,7 +48,7 @@ internal fun TargetProperty.generator(
|
||||
if (!hasDefault) {
|
||||
logger.error(
|
||||
"No default value for transient/ignored property $name",
|
||||
originalType
|
||||
originalType,
|
||||
)
|
||||
return null
|
||||
}
|
||||
@@ -58,7 +58,7 @@ internal fun TargetProperty.generator(
|
||||
if (!isVisible) {
|
||||
logger.error(
|
||||
"property $name is not visible",
|
||||
originalType
|
||||
originalType,
|
||||
)
|
||||
return null
|
||||
}
|
||||
@@ -76,7 +76,7 @@ internal fun TargetProperty.generator(
|
||||
annotationElement.findAnnotationWithType<Retention>()?.let {
|
||||
if (it.value != AnnotationRetention.RUNTIME) {
|
||||
logger.error(
|
||||
"JsonQualifier @${qualifierRawType.simpleName} must have RUNTIME retention"
|
||||
"JsonQualifier @${qualifierRawType.simpleName} must have RUNTIME retention",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -91,7 +91,7 @@ internal fun TargetProperty.generator(
|
||||
|
||||
return PropertyGenerator(
|
||||
this,
|
||||
DelegateKey(type, jsonQualifierSpecs)
|
||||
DelegateKey(type, jsonQualifierSpecs),
|
||||
)
|
||||
}
|
||||
|
||||
|
@@ -86,7 +86,7 @@ internal fun targetType(
|
||||
}
|
||||
|
||||
val classTypeParamsResolver = type.typeParameters.toTypeParameterResolver(
|
||||
sourceTypeHint = type.qualifiedName!!.asString()
|
||||
sourceTypeHint = type.qualifiedName!!.asString(),
|
||||
)
|
||||
val typeVariables = type.typeParameters.map { it.toTypeVariableName(classTypeParamsResolver) }
|
||||
val appliedType = AppliedType(type)
|
||||
@@ -100,7 +100,7 @@ internal fun targetType(
|
||||
logger.error(
|
||||
"@JsonClass can't be applied to $type: " +
|
||||
"primary constructor is not internal or public",
|
||||
type
|
||||
type,
|
||||
)
|
||||
return null
|
||||
}
|
||||
@@ -117,7 +117,7 @@ internal fun targetType(
|
||||
Origin=${classDecl.origin}
|
||||
Annotations=${classDecl.annotations.joinToString(prefix = "[", postfix = "]") { it.shortName.getShortName() }}
|
||||
""".trimIndent(),
|
||||
type
|
||||
type,
|
||||
)
|
||||
return null
|
||||
}
|
||||
@@ -127,7 +127,7 @@ internal fun targetType(
|
||||
classDecl = classDecl,
|
||||
resolver = resolver,
|
||||
typeParameterResolver = classDecl.typeParameters
|
||||
.toTypeParameterResolver(classTypeParamsResolver)
|
||||
.toTypeParameterResolver(classTypeParamsResolver),
|
||||
)
|
||||
for ((name, property) in supertypeProperties) {
|
||||
properties.putIfAbsent(name, property)
|
||||
@@ -169,7 +169,7 @@ internal fun primaryConstructor(
|
||||
resolver: Resolver,
|
||||
targetType: KSClassDeclaration,
|
||||
typeParameterResolver: TypeParameterResolver,
|
||||
logger: KSPLogger
|
||||
logger: KSPLogger,
|
||||
): TargetConstructor? {
|
||||
val primaryConstructor = targetType.primaryConstructor ?: return null
|
||||
|
||||
@@ -182,7 +182,7 @@ internal fun primaryConstructor(
|
||||
type = parameter.type.toTypeName(typeParameterResolver),
|
||||
hasDefault = parameter.hasDefault,
|
||||
qualifiers = parameter.qualifiers(resolver),
|
||||
jsonName = parameter.jsonName()
|
||||
jsonName = parameter.jsonName(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -194,7 +194,7 @@ internal fun primaryConstructor(
|
||||
return TargetConstructor(
|
||||
parameters,
|
||||
primaryConstructor.getVisibility().toKModifier() ?: KModifier.PUBLIC,
|
||||
kmConstructorSignature
|
||||
kmConstructorSignature,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -244,7 +244,7 @@ private fun declaredProperties(
|
||||
parameter = parameter,
|
||||
visibility = property.getVisibility().toKModifier() ?: KModifier.PUBLIC,
|
||||
jsonName = parameter?.jsonName ?: property.jsonName() ?: name,
|
||||
jsonIgnore = isTransient || parameter?.jsonIgnore == true || property.jsonIgnore()
|
||||
jsonIgnore = isTransient || parameter?.jsonIgnore == true || property.jsonIgnore(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -254,11 +254,11 @@ private fun declaredProperties(
|
||||
private fun KSPropertyDeclaration.toPropertySpec(
|
||||
resolver: Resolver,
|
||||
resolvedType: KSType,
|
||||
typeParameterResolver: TypeParameterResolver
|
||||
typeParameterResolver: TypeParameterResolver,
|
||||
): PropertySpec {
|
||||
return PropertySpec.builder(
|
||||
name = simpleName.getShortName(),
|
||||
type = resolvedType.toTypeName(typeParameterResolver).unwrapTypeAlias()
|
||||
type = resolvedType.toTypeName(typeParameterResolver).unwrapTypeAlias(),
|
||||
)
|
||||
.mutable(isMutable)
|
||||
.addModifiers(modifiers.map { KModifier.valueOf(it.name) })
|
||||
@@ -273,7 +273,7 @@ private fun KSPropertyDeclaration.toPropertySpec(
|
||||
null
|
||||
}
|
||||
}
|
||||
.asIterable()
|
||||
.asIterable(),
|
||||
)
|
||||
}
|
||||
.build()
|
||||
|
@@ -56,7 +56,7 @@ private fun <T : Annotation> KSAnnotation.toAnnotation(annotationClass: Class<T>
|
||||
return Proxy.newProxyInstance(
|
||||
annotationClass.classLoader,
|
||||
arrayOf(annotationClass),
|
||||
createInvocationHandler(annotationClass)
|
||||
createInvocationHandler(annotationClass),
|
||||
) as T
|
||||
}
|
||||
|
||||
@@ -119,8 +119,9 @@ private fun KSAnnotation.asAnnotation(
|
||||
annotationInterface: Class<*>,
|
||||
): Any {
|
||||
return Proxy.newProxyInstance(
|
||||
this.javaClass.classLoader, arrayOf(annotationInterface),
|
||||
this.createInvocationHandler(annotationInterface)
|
||||
this.javaClass.classLoader,
|
||||
arrayOf(annotationInterface),
|
||||
this.createInvocationHandler(annotationInterface),
|
||||
) as Proxy
|
||||
}
|
||||
|
||||
@@ -158,7 +159,7 @@ private fun List<*>.asArray(method: Method) =
|
||||
private fun List<*>.toArray(method: Method, valueProvider: (Any) -> Any): Array<Any?> {
|
||||
val array: Array<Any?> = java.lang.reflect.Array.newInstance(
|
||||
method.returnType.componentType,
|
||||
this.size
|
||||
this.size,
|
||||
) as Array<Any?>
|
||||
for (r in 0 until this.size) {
|
||||
array[r] = this[r]?.let { valueProvider.invoke(it) }
|
||||
@@ -176,7 +177,7 @@ private fun <T> Any.asEnum(returnType: Class<T>): T =
|
||||
this.declaration.simpleName.getShortName()
|
||||
} else {
|
||||
this.toString()
|
||||
}
|
||||
},
|
||||
) as T
|
||||
|
||||
private fun Any.asByte(): Byte = if (this is Int) this.toByte() else this as Byte
|
||||
|
@@ -39,7 +39,8 @@ import kotlin.reflect.full.declaredMemberProperties
|
||||
/** Execute kotlinc to confirm that either files are generated or errors are printed. */
|
||||
class JsonClassCodegenProcessorTest {
|
||||
|
||||
@Rule @JvmField val temporaryFolder: TemporaryFolder = TemporaryFolder()
|
||||
@Rule @JvmField
|
||||
val temporaryFolder: TemporaryFolder = TemporaryFolder()
|
||||
|
||||
@Test
|
||||
fun privateConstructor() {
|
||||
@@ -57,8 +58,8 @@ class JsonClassCodegenProcessorTest {
|
||||
fun newInstance(a: Int, b: Int) = PrivateConstructor(a, b)
|
||||
}
|
||||
}
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains("constructor is not internal or public")
|
||||
@@ -74,8 +75,8 @@ class JsonClassCodegenProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
class PrivateConstructorParameter(private var a: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains("property a is not visible")
|
||||
@@ -94,8 +95,8 @@ class JsonClassCodegenProcessorTest {
|
||||
private var a: Int = -1
|
||||
private var b: Int = -1
|
||||
}
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains("property a is not visible")
|
||||
@@ -111,12 +112,12 @@ class JsonClassCodegenProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
interface Interface
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"error: @JsonClass can't be applied to Interface: must be a Kotlin class"
|
||||
"error: @JsonClass can't be applied to Interface: must be a Kotlin class",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -130,8 +131,8 @@ class JsonClassCodegenProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true, generator="customGenerator")
|
||||
interface Interface
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.OK)
|
||||
}
|
||||
@@ -146,12 +147,12 @@ class JsonClassCodegenProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
abstract class AbstractClass(val a: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"error: @JsonClass can't be applied to AbstractClass: must not be abstract"
|
||||
"error: @JsonClass can't be applied to AbstractClass: must not be abstract",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -165,12 +166,12 @@ class JsonClassCodegenProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
sealed class SealedClass(val a: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"error: @JsonClass can't be applied to SealedClass: must not be sealed"
|
||||
"error: @JsonClass can't be applied to SealedClass: must not be sealed",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -186,12 +187,12 @@ class JsonClassCodegenProcessorTest {
|
||||
@JsonClass(generateAdapter = true)
|
||||
inner class InnerClass(val a: Int)
|
||||
}
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"error: @JsonClass can't be applied to Outer.InnerClass: must not be an inner class"
|
||||
"error: @JsonClass can't be applied to Outer.InnerClass: must not be an inner class",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -207,12 +208,12 @@ class JsonClassCodegenProcessorTest {
|
||||
enum class KotlinEnum {
|
||||
A, B
|
||||
}
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"error: @JsonClass with 'generateAdapter = \"true\"' can't be applied to KotlinEnum: code gen for enums is not supported or necessary"
|
||||
"error: @JsonClass with 'generateAdapter = \"true\"' can't be applied to KotlinEnum: code gen for enums is not supported or necessary",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -230,12 +231,12 @@ class JsonClassCodegenProcessorTest {
|
||||
@JsonClass(generateAdapter = true)
|
||||
class LocalClass(val a: Int)
|
||||
}
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"error: @JsonClass can't be applied to LocalClass: must not be local"
|
||||
"error: @JsonClass can't be applied to LocalClass: must not be local",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -249,12 +250,12 @@ class JsonClassCodegenProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
private class PrivateClass(val a: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"error: @JsonClass can't be applied to PrivateClass: must be internal or public"
|
||||
"error: @JsonClass can't be applied to PrivateClass: must be internal or public",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -270,12 +271,12 @@ class JsonClassCodegenProcessorTest {
|
||||
object ObjectDeclaration {
|
||||
var a = 5
|
||||
}
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"error: @JsonClass can't be applied to ObjectDeclaration: must be a Kotlin class"
|
||||
"error: @JsonClass can't be applied to ObjectDeclaration: must be a Kotlin class",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -291,12 +292,12 @@ class JsonClassCodegenProcessorTest {
|
||||
val expression = object : Any() {
|
||||
var a = 5
|
||||
}
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"error: @JsonClass can't be applied to getExpression\$annotations(): must be a Kotlin class"
|
||||
"error: @JsonClass can't be applied to getExpression\$annotations(): must be a Kotlin class",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -310,12 +311,12 @@ class JsonClassCodegenProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
class RequiredTransientConstructorParameter(@Transient var a: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"error: No default value for transient/ignored property a"
|
||||
"error: No default value for transient/ignored property a",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -330,12 +331,12 @@ class JsonClassCodegenProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
class RequiredIgnoredConstructorParameter(@Json(ignore = true) var a: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"error: No default value for transient/ignored property a"
|
||||
"error: No default value for transient/ignored property a",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -349,12 +350,12 @@ class JsonClassCodegenProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
class NonPropertyConstructorParameter(a: Int, val b: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"error: No property for required constructor parameter a"
|
||||
"error: No property for required constructor parameter a",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -368,15 +369,16 @@ class JsonClassCodegenProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class Foo(val a: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
).apply {
|
||||
kaptArgs[OPTION_GENERATED] = "javax.annotation.GeneratedBlerg"
|
||||
}.compile()
|
||||
assertThat(result.messages).contains(
|
||||
"Invalid option value for $OPTION_GENERATED"
|
||||
"Invalid option value for $OPTION_GENERATED",
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun disableProguardRulesGenerating() {
|
||||
val result = prepareCompilation(
|
||||
@@ -387,8 +389,8 @@ class JsonClassCodegenProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class Foo(val a: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
).apply {
|
||||
kaptArgs[OPTION_GENERATE_PROGUARD_RULES] = "false"
|
||||
}.compile()
|
||||
@@ -408,8 +410,8 @@ class JsonClassCodegenProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
class Class2(private var c: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains("property a is not visible")
|
||||
@@ -427,8 +429,8 @@ class JsonClassCodegenProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
class ExtendsPlatformClass(var a: Int) : Date()
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.messages).contains("supertype java.util.Date is not a Kotlin type")
|
||||
}
|
||||
@@ -444,8 +446,8 @@ class JsonClassCodegenProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
class ExtendsJavaType(var b: Int) : JavaSuperclass()
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages)
|
||||
@@ -472,8 +474,8 @@ class JsonClassCodegenProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
class ClassWithQualifier(@UpperCase val a: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
// We instantiate directly so doesn't need to be FIELD
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.OK)
|
||||
@@ -500,8 +502,8 @@ class JsonClassCodegenProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
class ClassWithQualifier(@UpperCase val a: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains("JsonQualifier @UpperCase must have RUNTIME retention")
|
||||
@@ -520,8 +522,8 @@ class JsonClassCodegenProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class Person(val firstName: FirstName, val lastName: LastName, val hairColor: String)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.OK)
|
||||
|
||||
@@ -530,7 +532,7 @@ class JsonClassCodegenProcessorTest {
|
||||
val adapterClass = result.classLoader.loadClass("PersonJsonAdapter").kotlin
|
||||
assertThat(adapterClass.declaredMemberProperties.map { it.returnType }).containsExactly(
|
||||
JsonReader.Options::class.createType(),
|
||||
JsonAdapter::class.parameterizedBy(String::class)
|
||||
JsonAdapter::class.parameterizedBy(String::class),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -648,8 +650,8 @@ class JsonClassCodegenProcessorTest {
|
||||
val arg64: Long = 64,
|
||||
val arg65: Long = 65
|
||||
)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.OK)
|
||||
|
||||
@@ -663,7 +665,7 @@ class JsonClassCodegenProcessorTest {
|
||||
-keep class testPackage.AliasesJsonAdapter {
|
||||
public <init>(com.squareup.moshi.Moshi);
|
||||
}
|
||||
""".trimIndent()
|
||||
""".trimIndent(),
|
||||
)
|
||||
"moshi-testPackage.Simple" -> assertThat(generatedFile.readText()).contains(
|
||||
"""
|
||||
@@ -673,7 +675,7 @@ class JsonClassCodegenProcessorTest {
|
||||
-keep class testPackage.SimpleJsonAdapter {
|
||||
public <init>(com.squareup.moshi.Moshi);
|
||||
}
|
||||
""".trimIndent()
|
||||
""".trimIndent(),
|
||||
)
|
||||
"moshi-testPackage.Generic" -> assertThat(generatedFile.readText()).contains(
|
||||
"""
|
||||
@@ -683,7 +685,7 @@ class JsonClassCodegenProcessorTest {
|
||||
-keep class testPackage.GenericJsonAdapter {
|
||||
public <init>(com.squareup.moshi.Moshi,java.lang.reflect.Type[]);
|
||||
}
|
||||
""".trimIndent()
|
||||
""".trimIndent(),
|
||||
)
|
||||
"moshi-testPackage.UsingQualifiers" -> {
|
||||
assertThat(generatedFile.readText()).contains(
|
||||
@@ -694,7 +696,7 @@ class JsonClassCodegenProcessorTest {
|
||||
-keep class testPackage.UsingQualifiersJsonAdapter {
|
||||
public <init>(com.squareup.moshi.Moshi);
|
||||
}
|
||||
""".trimIndent()
|
||||
""".trimIndent(),
|
||||
)
|
||||
}
|
||||
"moshi-testPackage.MixedTypes" -> assertThat(generatedFile.readText()).contains(
|
||||
@@ -705,7 +707,7 @@ class JsonClassCodegenProcessorTest {
|
||||
-keep class testPackage.MixedTypesJsonAdapter {
|
||||
public <init>(com.squareup.moshi.Moshi);
|
||||
}
|
||||
""".trimIndent()
|
||||
""".trimIndent(),
|
||||
)
|
||||
"moshi-testPackage.DefaultParams" -> assertThat(generatedFile.readText()).contains(
|
||||
"""
|
||||
@@ -721,7 +723,7 @@ class JsonClassCodegenProcessorTest {
|
||||
-keepclassmembers class testPackage.DefaultParams {
|
||||
public synthetic <init>(java.lang.String,int,kotlin.jvm.internal.DefaultConstructorMarker);
|
||||
}
|
||||
""".trimIndent()
|
||||
""".trimIndent(),
|
||||
)
|
||||
"moshi-testPackage.Complex" -> {
|
||||
assertThat(generatedFile.readText()).contains(
|
||||
@@ -738,7 +740,7 @@ class JsonClassCodegenProcessorTest {
|
||||
-keepclassmembers class testPackage.Complex {
|
||||
public synthetic <init>(java.lang.String,java.util.List,java.lang.Object,int,kotlin.jvm.internal.DefaultConstructorMarker);
|
||||
}
|
||||
""".trimIndent()
|
||||
""".trimIndent(),
|
||||
)
|
||||
}
|
||||
"moshi-testPackage.MultipleMasks" -> assertThat(generatedFile.readText()).contains(
|
||||
@@ -755,7 +757,7 @@ class JsonClassCodegenProcessorTest {
|
||||
-keepclassmembers class testPackage.MultipleMasks {
|
||||
public synthetic <init>(long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,int,int,int,kotlin.jvm.internal.DefaultConstructorMarker);
|
||||
}
|
||||
""".trimIndent()
|
||||
""".trimIndent(),
|
||||
)
|
||||
"moshi-testPackage.NestedType.NestedSimple" -> {
|
||||
assertThat(generatedFile.readText()).contains(
|
||||
@@ -766,7 +768,7 @@ class JsonClassCodegenProcessorTest {
|
||||
-keep class testPackage.NestedType_NestedSimpleJsonAdapter {
|
||||
public <init>(com.squareup.moshi.Moshi);
|
||||
}
|
||||
""".trimIndent()
|
||||
""".trimIndent(),
|
||||
)
|
||||
}
|
||||
else -> error("Unexpected proguard file! ${generatedFile.name}")
|
||||
@@ -795,7 +797,7 @@ class JsonClassCodegenProcessorTest {
|
||||
|
||||
private fun KClassifier.parameterizedBy(vararg types: KType): KType {
|
||||
return createType(
|
||||
types.map { it.asProjection() }
|
||||
types.map { it.asProjection() },
|
||||
)
|
||||
}
|
||||
|
||||
|
@@ -34,7 +34,8 @@ import org.junit.rules.TemporaryFolder
|
||||
/** Execute kotlinc to confirm that either files are generated or errors are printed. */
|
||||
class JsonClassSymbolProcessorTest {
|
||||
|
||||
@Rule @JvmField val temporaryFolder: TemporaryFolder = TemporaryFolder()
|
||||
@Rule @JvmField
|
||||
val temporaryFolder: TemporaryFolder = TemporaryFolder()
|
||||
|
||||
@Test
|
||||
fun privateConstructor() {
|
||||
@@ -53,8 +54,8 @@ class JsonClassSymbolProcessorTest {
|
||||
fun newInstance(a: Int, b: Int) = PrivateConstructor(a, b)
|
||||
}
|
||||
}
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains("constructor is not internal or public")
|
||||
@@ -71,8 +72,8 @@ class JsonClassSymbolProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
class PrivateConstructorParameter(private var a: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains("property a is not visible")
|
||||
@@ -92,8 +93,8 @@ class JsonClassSymbolProcessorTest {
|
||||
private var a: Int = -1
|
||||
private var b: Int = -1
|
||||
}
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains("property a is not visible")
|
||||
@@ -110,12 +111,12 @@ class JsonClassSymbolProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
interface Interface
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"@JsonClass can't be applied to test.Interface: must be a Kotlin class"
|
||||
"@JsonClass can't be applied to test.Interface: must be a Kotlin class",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -130,8 +131,8 @@ class JsonClassSymbolProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true, generator="customGenerator")
|
||||
interface Interface
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.OK)
|
||||
}
|
||||
@@ -147,12 +148,12 @@ class JsonClassSymbolProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
abstract class AbstractClass(val a: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"@JsonClass can't be applied to test.AbstractClass: must not be abstract"
|
||||
"@JsonClass can't be applied to test.AbstractClass: must not be abstract",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -167,12 +168,12 @@ class JsonClassSymbolProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
sealed class SealedClass(val a: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"@JsonClass can't be applied to test.SealedClass: must not be sealed"
|
||||
"@JsonClass can't be applied to test.SealedClass: must not be sealed",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -189,12 +190,12 @@ class JsonClassSymbolProcessorTest {
|
||||
@JsonClass(generateAdapter = true)
|
||||
inner class InnerClass(val a: Int)
|
||||
}
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"@JsonClass can't be applied to test.Outer.InnerClass: must not be an inner class"
|
||||
"@JsonClass can't be applied to test.Outer.InnerClass: must not be an inner class",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -211,12 +212,12 @@ class JsonClassSymbolProcessorTest {
|
||||
enum class KotlinEnum {
|
||||
A, B
|
||||
}
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"@JsonClass with 'generateAdapter = \"true\"' can't be applied to test.KotlinEnum: code gen for enums is not supported or necessary"
|
||||
"@JsonClass with 'generateAdapter = \"true\"' can't be applied to test.KotlinEnum: code gen for enums is not supported or necessary",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -235,12 +236,12 @@ class JsonClassSymbolProcessorTest {
|
||||
@JsonClass(generateAdapter = true)
|
||||
class LocalClass(val a: Int)
|
||||
}
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"@JsonClass can't be applied to LocalClass: must not be local"
|
||||
"@JsonClass can't be applied to LocalClass: must not be local",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -255,12 +256,12 @@ class JsonClassSymbolProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
private class PrivateClass(val a: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"@JsonClass can't be applied to test.PrivateClass: must be internal or public"
|
||||
"@JsonClass can't be applied to test.PrivateClass: must be internal or public",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -277,12 +278,12 @@ class JsonClassSymbolProcessorTest {
|
||||
object ObjectDeclaration {
|
||||
var a = 5
|
||||
}
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"@JsonClass can't be applied to test.ObjectDeclaration: must be a Kotlin class"
|
||||
"@JsonClass can't be applied to test.ObjectDeclaration: must be a Kotlin class",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -299,12 +300,12 @@ class JsonClassSymbolProcessorTest {
|
||||
val expression = object : Any() {
|
||||
var a = 5
|
||||
}
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"@JsonClass can't be applied to test.expression: must be a Kotlin class"
|
||||
"@JsonClass can't be applied to test.expression: must be a Kotlin class",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -319,12 +320,12 @@ class JsonClassSymbolProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
class RequiredTransientConstructorParameter(@Transient var a: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"No default value for transient/ignored property a"
|
||||
"No default value for transient/ignored property a",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -340,12 +341,12 @@ class JsonClassSymbolProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
class RequiredTransientConstructorParameter(@Json(ignore = true) var a: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"No default value for transient/ignored property a"
|
||||
"No default value for transient/ignored property a",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -360,12 +361,12 @@ class JsonClassSymbolProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
class NonPropertyConstructorParameter(a: Int, val b: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains(
|
||||
"No property for required constructor parameter a"
|
||||
"No property for required constructor parameter a",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -380,13 +381,13 @@ class JsonClassSymbolProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class Foo(val a: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
).apply {
|
||||
kspArgs[OPTION_GENERATED] = "javax.annotation.GeneratedBlerg"
|
||||
}.compile()
|
||||
assertThat(result.messages).contains(
|
||||
"Invalid option value for $OPTION_GENERATED"
|
||||
"Invalid option value for $OPTION_GENERATED",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -401,8 +402,8 @@ class JsonClassSymbolProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class Foo(val a: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
).apply {
|
||||
kspArgs[OPTION_GENERATE_PROGUARD_RULES] = "false"
|
||||
}
|
||||
@@ -425,8 +426,8 @@ class JsonClassSymbolProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
class Class2(private var c: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains("property a is not visible")
|
||||
@@ -445,8 +446,8 @@ class JsonClassSymbolProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
class ExtendsPlatformClass(var a: Int) : Date()
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.messages).contains("supertype java.util.Date is not a Kotlin type")
|
||||
}
|
||||
@@ -463,7 +464,7 @@ class JsonClassSymbolProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
class ExtendsJavaType(var b: Int) : JavaSuperclass()
|
||||
"""
|
||||
""",
|
||||
),
|
||||
java(
|
||||
"JavaSuperclass.java",
|
||||
@@ -472,8 +473,8 @@ class JsonClassSymbolProcessorTest {
|
||||
public class JavaSuperclass {
|
||||
public int a = 1;
|
||||
}
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages)
|
||||
@@ -501,8 +502,8 @@ class JsonClassSymbolProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
class ClassWithQualifier(@UpperCase val a: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
// We instantiate directly, no FIELD site target necessary
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.OK)
|
||||
@@ -530,8 +531,8 @@ class JsonClassSymbolProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
class ClassWithQualifier(@UpperCase val a: Int)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.COMPILATION_ERROR)
|
||||
assertThat(result.messages).contains("JsonQualifier @UpperCase must have RUNTIME retention")
|
||||
@@ -551,8 +552,8 @@ class JsonClassSymbolProcessorTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class Person(val firstName: FirstName, val lastName: LastName, val hairColor: String)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.OK)
|
||||
|
||||
@@ -680,8 +681,8 @@ class JsonClassSymbolProcessorTest {
|
||||
val arg64: Long = 64,
|
||||
val arg65: Long = 65
|
||||
)
|
||||
"""
|
||||
)
|
||||
""",
|
||||
),
|
||||
)
|
||||
val result = compilation.compile()
|
||||
assertThat(result.exitCode).isEqualTo(KotlinCompilation.ExitCode.OK)
|
||||
@@ -696,7 +697,7 @@ class JsonClassSymbolProcessorTest {
|
||||
-keep class testPackage.AliasesJsonAdapter {
|
||||
public <init>(com.squareup.moshi.Moshi);
|
||||
}
|
||||
""".trimIndent()
|
||||
""".trimIndent(),
|
||||
)
|
||||
"moshi-testPackage.Simple" -> assertThat(generatedFile.readText()).contains(
|
||||
"""
|
||||
@@ -706,7 +707,7 @@ class JsonClassSymbolProcessorTest {
|
||||
-keep class testPackage.SimpleJsonAdapter {
|
||||
public <init>(com.squareup.moshi.Moshi);
|
||||
}
|
||||
""".trimIndent()
|
||||
""".trimIndent(),
|
||||
)
|
||||
"moshi-testPackage.Generic" -> assertThat(generatedFile.readText()).contains(
|
||||
"""
|
||||
@@ -716,7 +717,7 @@ class JsonClassSymbolProcessorTest {
|
||||
-keep class testPackage.GenericJsonAdapter {
|
||||
public <init>(com.squareup.moshi.Moshi,java.lang.reflect.Type[]);
|
||||
}
|
||||
""".trimIndent()
|
||||
""".trimIndent(),
|
||||
)
|
||||
"moshi-testPackage.UsingQualifiers" -> {
|
||||
assertThat(generatedFile.readText()).contains(
|
||||
@@ -727,7 +728,7 @@ class JsonClassSymbolProcessorTest {
|
||||
-keep class testPackage.UsingQualifiersJsonAdapter {
|
||||
public <init>(com.squareup.moshi.Moshi);
|
||||
}
|
||||
""".trimIndent()
|
||||
""".trimIndent(),
|
||||
)
|
||||
}
|
||||
"moshi-testPackage.MixedTypes" -> assertThat(generatedFile.readText()).contains(
|
||||
@@ -738,7 +739,7 @@ class JsonClassSymbolProcessorTest {
|
||||
-keep class testPackage.MixedTypesJsonAdapter {
|
||||
public <init>(com.squareup.moshi.Moshi);
|
||||
}
|
||||
""".trimIndent()
|
||||
""".trimIndent(),
|
||||
)
|
||||
"moshi-testPackage.DefaultParams" -> assertThat(generatedFile.readText()).contains(
|
||||
"""
|
||||
@@ -754,7 +755,7 @@ class JsonClassSymbolProcessorTest {
|
||||
-keepclassmembers class testPackage.DefaultParams {
|
||||
public synthetic <init>(java.lang.String,int,kotlin.jvm.internal.DefaultConstructorMarker);
|
||||
}
|
||||
""".trimIndent()
|
||||
""".trimIndent(),
|
||||
)
|
||||
"moshi-testPackage.Complex" -> {
|
||||
assertThat(generatedFile.readText()).contains(
|
||||
@@ -771,7 +772,7 @@ class JsonClassSymbolProcessorTest {
|
||||
-keepclassmembers class testPackage.Complex {
|
||||
public synthetic <init>(java.lang.String,java.util.List,java.lang.Object,int,kotlin.jvm.internal.DefaultConstructorMarker);
|
||||
}
|
||||
""".trimIndent()
|
||||
""".trimIndent(),
|
||||
)
|
||||
}
|
||||
"moshi-testPackage.MultipleMasks" -> assertThat(generatedFile.readText()).contains(
|
||||
@@ -788,7 +789,7 @@ class JsonClassSymbolProcessorTest {
|
||||
-keepclassmembers class testPackage.MultipleMasks {
|
||||
public synthetic <init>(long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,long,int,int,int,kotlin.jvm.internal.DefaultConstructorMarker);
|
||||
}
|
||||
""".trimIndent()
|
||||
""".trimIndent(),
|
||||
)
|
||||
"moshi-testPackage.NestedType.NestedSimple" -> {
|
||||
assertThat(generatedFile.readText()).contains(
|
||||
@@ -799,7 +800,7 @@ class JsonClassSymbolProcessorTest {
|
||||
-keep class testPackage.NestedType_NestedSimpleJsonAdapter {
|
||||
public <init>(com.squareup.moshi.Moshi);
|
||||
}
|
||||
""".trimIndent()
|
||||
""".trimIndent(),
|
||||
)
|
||||
}
|
||||
else -> error("Unexpected proguard file! ${generatedFile.name}")
|
||||
|
@@ -42,7 +42,7 @@ tasks.withType<KotlinCompile>().configureEach {
|
||||
allWarningsAsErrors = useWError
|
||||
@Suppress("SuspiciousCollectionReassignment")
|
||||
freeCompilerArgs += listOf(
|
||||
"-opt-in=kotlin.ExperimentalStdlibApi"
|
||||
"-opt-in=kotlin.ExperimentalStdlibApi",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
@@ -43,7 +43,7 @@ tasks.withType<KotlinCompile>().configureEach {
|
||||
allWarningsAsErrors = useWError
|
||||
@Suppress("SuspiciousCollectionReassignment")
|
||||
freeCompilerArgs += listOf(
|
||||
"-opt-in=kotlin.ExperimentalStdlibApi"
|
||||
"-opt-in=kotlin.ExperimentalStdlibApi",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
@@ -30,7 +30,7 @@ import kotlin.annotation.AnnotationTarget.TYPE
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class GenericTestClassWithDefaults<T>(
|
||||
val input: String = "",
|
||||
val genericInput: T
|
||||
val genericInput: T,
|
||||
)
|
||||
|
||||
@Target(TYPE)
|
||||
@@ -43,28 +43,29 @@ annotation class TypeAnnotation
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class TypeAnnotationClass(
|
||||
val propertyWithAnnotatedType: @TypeAnnotation String = "",
|
||||
val generic: List<@TypeAnnotation String>
|
||||
val generic: List<@TypeAnnotation String>,
|
||||
)
|
||||
|
||||
// Regression test for https://github.com/square/moshi/issues/1277
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class OtherTestModel(val TestModel: TestModel? = null)
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class TestModel(
|
||||
val someVariable: Int,
|
||||
val anotherVariable: String
|
||||
val anotherVariable: String,
|
||||
)
|
||||
|
||||
// Regression test for https://github.com/square/moshi/issues/1022
|
||||
@JsonClass(generateAdapter = true)
|
||||
internal data class MismatchParentAndNestedClassVisibility(
|
||||
val type: Int,
|
||||
val name: String? = null
|
||||
val name: String? = null,
|
||||
) {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class NestedClass(
|
||||
val nestedProperty: String
|
||||
val nestedProperty: String,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -76,13 +77,13 @@ data class KeysWithSpaces(
|
||||
@Json(name = "3. Last Refreshed") val lastRefreshed: String,
|
||||
@Json(name = "4. Interval") val interval: String,
|
||||
@Json(name = "5. Output Size") val size: String,
|
||||
@Json(name = "6. Time Zone") val timeZone: String
|
||||
@Json(name = "6. Time Zone") val timeZone: String,
|
||||
)
|
||||
|
||||
// Regression test for https://github.com/square/moshi/issues/848
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class Hotwords(
|
||||
val `class`: List<String>?
|
||||
val `class`: List<String>?,
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -115,7 +116,7 @@ data class SmokeTestType(
|
||||
val aliasedName: TypeAliasName = "Woah",
|
||||
val genericAlias: GenericTypeAlias = listOf("Woah"),
|
||||
// Regression test for https://github.com/square/moshi/issues/1272
|
||||
val nestedArray: Array<Map<String, Any>>? = null
|
||||
val nestedArray: Array<Map<String, Any>>? = null,
|
||||
)
|
||||
|
||||
typealias TypeAliasName = String
|
||||
@@ -132,11 +133,11 @@ enum class Foo { BAR }
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class ClassWithQualifier(
|
||||
@UpperCase(foo = [Foo.BAR])
|
||||
val a: Int
|
||||
val a: Int,
|
||||
)
|
||||
|
||||
// Regression for https://github.com/ZacSweers/MoshiX/issues/120
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class DataClassInModuleB(
|
||||
val id: String
|
||||
val id: String,
|
||||
) : AbstractClassInModuleA()
|
||||
|
@@ -90,7 +90,7 @@ class ComplexGenericsInheritanceTest {
|
||||
data = Person("layer4F")
|
||||
data2 = "layer4F"
|
||||
data3 = "layer4F"
|
||||
}
|
||||
},
|
||||
).apply {
|
||||
layer3C = listOf(1, 2, 3)
|
||||
layer3D = "layer3D"
|
||||
@@ -115,7 +115,7 @@ data class Person(val name: String) : Personable
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class PersonResponse(
|
||||
val extra: String? = null
|
||||
val extra: String? = null,
|
||||
) : ResponseWithSettableProperty<Person, String>()
|
||||
|
||||
abstract class NestedResponse<T : Personable> : ResponseWithSettableProperty<T, String>()
|
||||
@@ -125,7 +125,7 @@ data class NestedPersonResponse(val extra: String? = null) : NestedResponse<Pers
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class UntypedNestedPersonResponse<T : Personable>(
|
||||
val extra: String? = null
|
||||
val extra: String? = null,
|
||||
) : NestedResponse<T>()
|
||||
|
||||
interface LayerInterface<I>
|
||||
@@ -146,5 +146,5 @@ abstract class Layer3<C, D> : Layer2<D>() {
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class Layer4<E : Personable, F>(
|
||||
val layer4E: E,
|
||||
val layer4F: F? = null
|
||||
val layer4F: F? = null,
|
||||
) : Layer3<List<Int>, String>(), LayerInterface<String>
|
||||
|
@@ -62,7 +62,7 @@ data class TestClass(
|
||||
val optional2: Int = 2,
|
||||
val dynamicSelfReferenceOptional: String = required,
|
||||
val dynamicOptional: Int = createInt(),
|
||||
val dynamicInlineOptional: Int = createInlineInt()
|
||||
val dynamicInlineOptional: Int = createInlineInt(),
|
||||
)
|
||||
|
||||
private fun createInt(): Int {
|
||||
|
@@ -62,8 +62,8 @@ class GeneratedAdaptersTest {
|
||||
|
||||
assertThat(
|
||||
adapter.toJson(
|
||||
JsonAnnotation("baz")
|
||||
)
|
||||
JsonAnnotation("baz"),
|
||||
),
|
||||
).isEqualTo(expectedJson)
|
||||
}
|
||||
|
||||
@@ -85,8 +85,8 @@ class GeneratedAdaptersTest {
|
||||
|
||||
assertThat(
|
||||
adapter.toJson(
|
||||
JsonAnnotationWithDollarSign("baz")
|
||||
)
|
||||
JsonAnnotationWithDollarSign("baz"),
|
||||
),
|
||||
).isEqualTo(expectedJson)
|
||||
}
|
||||
|
||||
@@ -110,8 +110,8 @@ class GeneratedAdaptersTest {
|
||||
|
||||
assertThat(
|
||||
adapter.toJson(
|
||||
JsonAnnotationWithQuotationMark("baz")
|
||||
)
|
||||
JsonAnnotationWithQuotationMark("baz"),
|
||||
),
|
||||
).isEqualTo(expectedJson)
|
||||
}
|
||||
|
||||
@@ -136,12 +136,13 @@ class GeneratedAdaptersTest {
|
||||
isEmpty()
|
||||
}
|
||||
|
||||
@Language("JSON") val expected =
|
||||
@Language("JSON")
|
||||
val expected =
|
||||
"""{"foo":"fooString","bar":"","bazList":[]}"""
|
||||
assertThat(
|
||||
adapter.toJson(
|
||||
DefaultValues("fooString")
|
||||
)
|
||||
DefaultValues("fooString"),
|
||||
),
|
||||
).isEqualTo(expected)
|
||||
|
||||
// Read/write with real values
|
||||
@@ -164,7 +165,7 @@ class GeneratedAdaptersTest {
|
||||
val foo: String,
|
||||
val bar: String = "",
|
||||
val nullableBar: String? = null,
|
||||
val bazList: List<String> = emptyList()
|
||||
val bazList: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
@Test
|
||||
@@ -206,6 +207,7 @@ class GeneratedAdaptersTest {
|
||||
@Language("JSON")
|
||||
val json =
|
||||
"""{"foo":"foo","nullableString":null}"""
|
||||
|
||||
@Language("JSON")
|
||||
val invalidJson =
|
||||
"""{"foo":null,"nullableString":null}"""
|
||||
@@ -225,7 +227,7 @@ class GeneratedAdaptersTest {
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class NullabeTypes(
|
||||
val foo: String,
|
||||
val nullableString: String?
|
||||
val nullableString: String?,
|
||||
)
|
||||
|
||||
@Test
|
||||
@@ -238,7 +240,7 @@ class GeneratedAdaptersTest {
|
||||
mutableMapOf(),
|
||||
emptyList(),
|
||||
emptySet(),
|
||||
emptyMap()
|
||||
emptyMap(),
|
||||
)
|
||||
|
||||
val json = adapter.toJson(specialCollections)
|
||||
@@ -253,7 +255,7 @@ class GeneratedAdaptersTest {
|
||||
val mutableMap: MutableMap<String, String>,
|
||||
val immutableList: List<String>,
|
||||
val immutableSet: Set<String>,
|
||||
val immutableMap: Map<String, String>
|
||||
val immutableMap: Map<String, String>,
|
||||
)
|
||||
|
||||
@Test
|
||||
@@ -272,7 +274,7 @@ class GeneratedAdaptersTest {
|
||||
mutableListOf("immutableMutableList"),
|
||||
mutableListOf("immutableImmutableList"),
|
||||
mutableListOf("mutableMutableList"),
|
||||
mutableListOf("mutableImmutableList")
|
||||
mutableListOf("mutableImmutableList"),
|
||||
)
|
||||
|
||||
val json = adapter.toJson(mutableProperties)
|
||||
@@ -293,7 +295,7 @@ class GeneratedAdaptersTest {
|
||||
val nullableImmutableMutableList: MutableList<String>?,
|
||||
val nullableImmutableImmutableList: List<String>?,
|
||||
var nullableMutableMutableList: MutableList<String>?,
|
||||
var nullableMutableImmutableList: List<String>
|
||||
var nullableMutableImmutableList: List<String>,
|
||||
)
|
||||
|
||||
@Test
|
||||
@@ -306,7 +308,7 @@ class GeneratedAdaptersTest {
|
||||
setOf("foo", null, "bar"),
|
||||
mapOf("foo" to "bar", "baz" to null),
|
||||
null,
|
||||
1
|
||||
1,
|
||||
)
|
||||
|
||||
val noNullsTypeParams = NullableTypeParams(
|
||||
@@ -314,7 +316,7 @@ class GeneratedAdaptersTest {
|
||||
nullableTypeParams.nullableSet,
|
||||
nullableTypeParams.nullableMap.filterValues { it != null },
|
||||
null,
|
||||
1
|
||||
1,
|
||||
)
|
||||
|
||||
val json = adapter.toJson(nullableTypeParams)
|
||||
@@ -332,7 +334,7 @@ class GeneratedAdaptersTest {
|
||||
val nullableSet: Set<String?>,
|
||||
val nullableMap: Map<String, String?>,
|
||||
val nullableT: T?,
|
||||
val nonNullT: T
|
||||
val nonNullT: T,
|
||||
)
|
||||
|
||||
@Test fun doNotGenerateAdapter() {
|
||||
@@ -352,7 +354,7 @@ class GeneratedAdaptersTest {
|
||||
|
||||
val encoded = ConstructorParameters(
|
||||
3,
|
||||
5
|
||||
5,
|
||||
)
|
||||
assertThat(jsonAdapter.toJson(encoded)).isEqualTo("""{"a":3,"b":5}""")
|
||||
|
||||
@@ -389,7 +391,7 @@ class GeneratedAdaptersTest {
|
||||
val jsonAdapter = moshi.adapter<ConstructorParametersAndProperties>()
|
||||
|
||||
val encoded = ConstructorParametersAndProperties(
|
||||
3
|
||||
3,
|
||||
)
|
||||
encoded.b = 5
|
||||
assertThat(jsonAdapter.toJson(encoded)).isEqualTo("""{"a":3,"b":5}""")
|
||||
@@ -410,7 +412,7 @@ class GeneratedAdaptersTest {
|
||||
|
||||
val encoded = ImmutableConstructorParameters(
|
||||
3,
|
||||
5
|
||||
5,
|
||||
)
|
||||
assertThat(jsonAdapter.toJson(encoded)).isEqualTo("""{"a":3,"b":5}""")
|
||||
|
||||
@@ -446,7 +448,7 @@ class GeneratedAdaptersTest {
|
||||
|
||||
val encoded = ConstructorDefaultValues(
|
||||
3,
|
||||
5
|
||||
5,
|
||||
)
|
||||
assertThat(jsonAdapter.toJson(encoded)).isEqualTo("""{"a":3,"b":5}""")
|
||||
|
||||
@@ -498,7 +500,7 @@ class GeneratedAdaptersTest {
|
||||
|
||||
val encoded = ConstructorParameterWithQualifier(
|
||||
"Android",
|
||||
"Banana"
|
||||
"Banana",
|
||||
)
|
||||
assertThat(jsonAdapter.toJson(encoded)).isEqualTo("""{"a":"ANDROID","b":"Banana"}""")
|
||||
|
||||
@@ -544,7 +546,8 @@ class GeneratedAdaptersTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
class PropertyWithQualifier {
|
||||
@Uppercase(inFrench = true) var a: String = ""
|
||||
@Uppercase(inFrench = true)
|
||||
var a: String = ""
|
||||
var b: String = ""
|
||||
}
|
||||
|
||||
@@ -554,7 +557,7 @@ class GeneratedAdaptersTest {
|
||||
|
||||
val encoded = ConstructorParameterWithJsonName(
|
||||
3,
|
||||
5
|
||||
5,
|
||||
)
|
||||
assertThat(jsonAdapter.toJson(encoded)).isEqualTo("""{"key a":3,"b":5}""")
|
||||
|
||||
@@ -582,7 +585,8 @@ class GeneratedAdaptersTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
class PropertyWithJsonName {
|
||||
@Json(name = "key a") var a: Int = -1
|
||||
@Json(name = "key a")
|
||||
var a: Int = -1
|
||||
var b: Int = -1
|
||||
}
|
||||
|
||||
@@ -592,7 +596,7 @@ class GeneratedAdaptersTest {
|
||||
|
||||
val encoded = TransientConstructorParameter(
|
||||
3,
|
||||
5
|
||||
5,
|
||||
)
|
||||
assertThat(jsonAdapter.toJson(encoded)).isEqualTo("""{"b":5}""")
|
||||
|
||||
@@ -639,6 +643,7 @@ class GeneratedAdaptersTest {
|
||||
@JsonClass(generateAdapter = true)
|
||||
class TransientProperty {
|
||||
@Transient var a: Int = -1
|
||||
|
||||
@Transient private var b: Int = -1
|
||||
var c: Int = -1
|
||||
|
||||
@@ -670,11 +675,13 @@ class GeneratedAdaptersTest {
|
||||
private fun <T> delegate(initial: T) = Delegates.observable(initial) { _, _, _ -> }
|
||||
|
||||
@delegate:Transient var a: Int by delegate(-1)
|
||||
|
||||
@delegate:Transient private var b: Int by delegate(-1)
|
||||
var c: Int by delegate(-1)
|
||||
|
||||
@JvmName("getBPublic")
|
||||
fun getB() = b
|
||||
|
||||
@JvmName("setBPublic")
|
||||
fun setB(b: Int) {
|
||||
this.b = b
|
||||
@@ -692,7 +699,7 @@ class GeneratedAdaptersTest {
|
||||
116, 117, 118, 119, 120,
|
||||
121, 122, 123, 124, 125,
|
||||
126, 127, 128, 129, 130,
|
||||
131, 132
|
||||
131, 132,
|
||||
)
|
||||
val json = (
|
||||
"""
|
||||
@@ -748,7 +755,7 @@ class GeneratedAdaptersTest {
|
||||
var v29: Int,
|
||||
var v30: Int,
|
||||
var v31: Int,
|
||||
var v32: Int
|
||||
var v32: Int,
|
||||
)
|
||||
|
||||
@Test fun manyProperties33() {
|
||||
@@ -762,7 +769,7 @@ class GeneratedAdaptersTest {
|
||||
116, 117, 118, 119, 120,
|
||||
121, 122, 123, 124, 125,
|
||||
126, 127, 128, 129, 130,
|
||||
131, 132, 133
|
||||
131, 132, 133,
|
||||
)
|
||||
val json = (
|
||||
"""
|
||||
@@ -820,7 +827,7 @@ class GeneratedAdaptersTest {
|
||||
var v30: Int,
|
||||
var v31: Int,
|
||||
var v32: Int,
|
||||
var v33: Int
|
||||
var v33: Int,
|
||||
)
|
||||
|
||||
@Test fun unsettablePropertyIgnored() {
|
||||
@@ -896,7 +903,7 @@ class GeneratedAdaptersTest {
|
||||
|
||||
val encoded = SubtypeConstructorParameters(
|
||||
3,
|
||||
5
|
||||
5,
|
||||
)
|
||||
assertThat(jsonAdapter.toJson(encoded)).isEqualTo("""{"a":3,"b":5}""")
|
||||
|
||||
@@ -934,7 +941,8 @@ class GeneratedAdaptersTest {
|
||||
}
|
||||
|
||||
/** Generated adapters don't track enough state to detect duplicated values. */
|
||||
@Ignore @Test fun duplicatedValueParameter() {
|
||||
@Ignore @Test
|
||||
fun duplicatedValueParameter() {
|
||||
val moshi = Moshi.Builder().build()
|
||||
val jsonAdapter = moshi.adapter<DuplicateValueParameter>()
|
||||
|
||||
@@ -949,7 +957,8 @@ class GeneratedAdaptersTest {
|
||||
class DuplicateValueParameter(var a: Int = -1, var b: Int = -2)
|
||||
|
||||
/** Generated adapters don't track enough state to detect duplicated values. */
|
||||
@Ignore @Test fun duplicatedValueProperty() {
|
||||
@Ignore @Test
|
||||
fun duplicatedValueProperty() {
|
||||
val moshi = Moshi.Builder().build()
|
||||
val jsonAdapter = moshi.adapter<DuplicateValueProperty>()
|
||||
|
||||
@@ -997,7 +1006,7 @@ class GeneratedAdaptersTest {
|
||||
|
||||
val encoded = MultiplePropertiesShareAdapter(
|
||||
"Android",
|
||||
"Banana"
|
||||
"Banana",
|
||||
)
|
||||
assertThat(jsonAdapter.toJson(encoded)).isEqualTo("""{"a":"ANDROID","b":"BANANA"}""")
|
||||
|
||||
@@ -1011,7 +1020,7 @@ class GeneratedAdaptersTest {
|
||||
@JsonClass(generateAdapter = true)
|
||||
class MultiplePropertiesShareAdapter(
|
||||
@Uppercase(true) var a: String,
|
||||
@Uppercase(true) var b: String
|
||||
@Uppercase(true) var b: String,
|
||||
)
|
||||
|
||||
@Test fun toJsonOnly() {
|
||||
@@ -1022,8 +1031,8 @@ class GeneratedAdaptersTest {
|
||||
|
||||
assertThat(
|
||||
jsonAdapter.toJson(
|
||||
CustomToJsonOnly(1, 2)
|
||||
)
|
||||
CustomToJsonOnly(1, 2),
|
||||
),
|
||||
).isEqualTo("""[1,2]""")
|
||||
|
||||
val fromJson = jsonAdapter.fromJson("""{"a":3,"b":4}""")!!
|
||||
@@ -1048,8 +1057,8 @@ class GeneratedAdaptersTest {
|
||||
|
||||
assertThat(
|
||||
jsonAdapter.toJson(
|
||||
CustomFromJsonOnly(1, 2)
|
||||
)
|
||||
CustomFromJsonOnly(1, 2),
|
||||
),
|
||||
).isEqualTo("""{"a":1,"b":2}""")
|
||||
|
||||
val fromJson = jsonAdapter.fromJson("""[3,4]""")!!
|
||||
@@ -1131,9 +1140,9 @@ class GeneratedAdaptersTest {
|
||||
assertThat(
|
||||
jsonAdapter.toJson(
|
||||
HasParameterizedProperty(
|
||||
Twins("1", "2")
|
||||
)
|
||||
)
|
||||
Twins("1", "2"),
|
||||
),
|
||||
),
|
||||
)
|
||||
.isEqualTo("""{"twins":{"a":"1","b":"2"}}""")
|
||||
|
||||
@@ -1157,8 +1166,8 @@ class GeneratedAdaptersTest {
|
||||
|
||||
assertThat(
|
||||
adapter.toJson(
|
||||
UppercasePropertyName(3, 4)
|
||||
)
|
||||
UppercasePropertyName(3, 4),
|
||||
),
|
||||
).isEqualTo("""{"AAA":3,"BBB":4}""")
|
||||
}
|
||||
|
||||
@@ -1193,6 +1202,7 @@ class GeneratedAdaptersTest {
|
||||
fun toJson(@Uppercase(inFrench = true) s: String): String {
|
||||
return s.uppercase(Locale.US)
|
||||
}
|
||||
|
||||
@FromJson
|
||||
@Uppercase(inFrench = true)
|
||||
fun fromJson(s: String): String {
|
||||
@@ -1223,7 +1233,7 @@ class GeneratedAdaptersTest {
|
||||
}
|
||||
}
|
||||
null
|
||||
}
|
||||
},
|
||||
)
|
||||
.build()
|
||||
val adapter = moshi.adapter<HasNullableBoolean>().serializeNulls()
|
||||
@@ -1231,8 +1241,8 @@ class GeneratedAdaptersTest {
|
||||
.isEqualTo(HasNullableBoolean(null))
|
||||
assertThat(
|
||||
adapter.toJson(
|
||||
HasNullableBoolean(null)
|
||||
)
|
||||
HasNullableBoolean(null),
|
||||
),
|
||||
).isEqualTo("""{"boolean":null}""")
|
||||
}
|
||||
|
||||
@@ -1251,15 +1261,15 @@ class GeneratedAdaptersTest {
|
||||
val adapter = moshi.adapter<HasCollectionOfPrimitives>()
|
||||
|
||||
val encoded = HasCollectionOfPrimitives(
|
||||
listOf(1, 2, -3)
|
||||
listOf(1, 2, -3),
|
||||
)
|
||||
assertThat(adapter.toJson(encoded)).isEqualTo("""{"listOfInts":[1,2,-3]}""")
|
||||
|
||||
val decoded = adapter.fromJson("""{"listOfInts":[4,-5,6]}""")!!
|
||||
assertThat(decoded).isEqualTo(
|
||||
HasCollectionOfPrimitives(
|
||||
listOf(4, -5, 6)
|
||||
)
|
||||
listOf(4, -5, 6),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1271,7 +1281,7 @@ class GeneratedAdaptersTest {
|
||||
val adapter = moshi.adapter<CustomGeneratedClass>()
|
||||
val unwrapped = (adapter as NullSafeJsonAdapter<CustomGeneratedClass>).delegate
|
||||
assertThat(unwrapped).isInstanceOf(
|
||||
GeneratedAdaptersTest_CustomGeneratedClassJsonAdapter::class.java
|
||||
GeneratedAdaptersTest_CustomGeneratedClassJsonAdapter::class.java,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1313,9 +1323,10 @@ class GeneratedAdaptersTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class ClassWithFieldJson(
|
||||
@field:Json(name = "_links") val links: String
|
||||
@field:Json(name = "_links") val links: String,
|
||||
) {
|
||||
@field:Json(name = "_ids") var ids: String? = null
|
||||
@field:Json(name = "_ids")
|
||||
var ids: String? = null
|
||||
}
|
||||
|
||||
// Regression test to ensure annotations with field site targets still use the right name
|
||||
@@ -1357,7 +1368,7 @@ class GeneratedAdaptersTest {
|
||||
try {
|
||||
GeneratedAdaptersTest_MultipleGenericsJsonAdapter<String, Any, Any, Any>(
|
||||
moshi,
|
||||
arrayOf(String::class.java)
|
||||
arrayOf(String::class.java),
|
||||
)
|
||||
fail("Should have failed to construct the adapter due to wrong number of generics")
|
||||
} catch (e: IllegalArgumentException) {
|
||||
@@ -1396,5 +1407,5 @@ data class NullableTypeParams<T>(
|
||||
val nullableSet: Set<String?>,
|
||||
val nullableMap: Map<String, String?>,
|
||||
val nullableT: T?,
|
||||
val nonNullT: T
|
||||
val nonNullT: T,
|
||||
)
|
||||
|
@@ -13,6 +13,8 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
@file:Suppress("PackageName")
|
||||
|
||||
package com.squareup.moshi.kotlin.codegen.LooksLikeAClass
|
||||
|
||||
import com.squareup.moshi.JsonClass
|
||||
|
@@ -35,7 +35,7 @@ class MixingReflectAndCodeGen {
|
||||
assertThat(reflectionAdapter.toString())
|
||||
.isEqualTo(
|
||||
"KotlinJsonAdapter(com.squareup.moshi.kotlin.codegen.MixingReflectAndCodeGen" +
|
||||
".UsesReflectionAdapter).nullSafe()"
|
||||
".UsesReflectionAdapter).nullSafe()",
|
||||
)
|
||||
}
|
||||
|
||||
|
@@ -35,7 +35,6 @@ import org.junit.Test
|
||||
*/
|
||||
class MultipleMasksTest {
|
||||
@Test fun testMultipleMasks() {
|
||||
|
||||
// Set some arbitrary values to make sure offsets are aligning correctly
|
||||
@Language("JSON")
|
||||
val json =
|
||||
@@ -121,5 +120,5 @@ class MultipleMasks(
|
||||
val arg62: Long = 62,
|
||||
val arg63: Long = 63,
|
||||
val arg64: Long = 64,
|
||||
val arg65: Long = 65
|
||||
val arg65: Long = 65,
|
||||
)
|
||||
|
@@ -28,6 +28,7 @@ class UppercaseInAnnotationPackageJsonAdapter {
|
||||
fun toJson(@UppercaseInAnnotationPackage s: String): String {
|
||||
return s.uppercase(Locale.US)
|
||||
}
|
||||
|
||||
@FromJson
|
||||
@UppercaseInAnnotationPackage
|
||||
fun fromJson(s: String): String {
|
||||
|
@@ -20,9 +20,14 @@ import com.squareup.moshi.Json
|
||||
public abstract class AbstractClassInModuleA {
|
||||
// Ignored/transient to ensure processor sees them across module boundaries.
|
||||
@Transient private lateinit var lateinitTransient: String
|
||||
|
||||
@Transient private var regularTransient: String = "regularTransient"
|
||||
|
||||
// Note that we target the field because otherwise it is stored on the synthetic holder method for
|
||||
// annotations, which isn't visible from kapt
|
||||
@field:Json(ignore = true) private lateinit var lateinitIgnored: String
|
||||
@field:Json(ignore = true) private var regularIgnored: String = "regularIgnored"
|
||||
@field:Json(ignore = true)
|
||||
private lateinit var lateinitIgnored: String
|
||||
|
||||
@field:Json(ignore = true)
|
||||
private var regularIgnored: String = "regularIgnored"
|
||||
}
|
||||
|
@@ -87,7 +87,7 @@ class DualKotlinTest {
|
||||
@Suppress("UNUSED_PARAMETER")
|
||||
@FromJson
|
||||
fun fromJson(string: String): String? = null
|
||||
}
|
||||
},
|
||||
)
|
||||
.build()
|
||||
.adapter<HasNonNullProperty>()
|
||||
@@ -125,7 +125,7 @@ class DualKotlinTest {
|
||||
@Suppress("UNUSED_PARAMETER")
|
||||
@FromJson
|
||||
fun fromJson(string: String): String? = null
|
||||
}
|
||||
},
|
||||
)
|
||||
.build()
|
||||
.adapter<HasNonNullPropertyDifferentJsonName>()
|
||||
@@ -141,7 +141,8 @@ class DualKotlinTest {
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
class HasNonNullPropertyDifferentJsonName {
|
||||
@Json(name = "aPrime") var a: String = ""
|
||||
@Json(name = "aPrime")
|
||||
var a: String = ""
|
||||
}
|
||||
|
||||
@Test fun nonNullConstructorParameterCalledWithNullFailsWithJsonDataException() {
|
||||
@@ -163,7 +164,7 @@ class DualKotlinTest {
|
||||
@Suppress("UNUSED_PARAMETER")
|
||||
@FromJson
|
||||
fun fromJson(string: String): String? = null
|
||||
}
|
||||
},
|
||||
)
|
||||
.build()
|
||||
.adapter<HasNonNullConstructorParameter>()
|
||||
@@ -199,7 +200,7 @@ class DualKotlinTest {
|
||||
fun toJson(@Nullable value: String?): String {
|
||||
return value ?: "fallback"
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
.build()
|
||||
|
||||
@@ -208,7 +209,7 @@ class DualKotlinTest {
|
||||
assertThat(
|
||||
//language=JSON
|
||||
hasNonNullConstructorParameterAdapter
|
||||
.fromJson("{\"a\":null}")
|
||||
.fromJson("{\"a\":null}"),
|
||||
).isEqualTo(HasNonNullConstructorParameter("fallback"))
|
||||
|
||||
val hasNullableConstructorParameterAdapter =
|
||||
@@ -216,12 +217,12 @@ class DualKotlinTest {
|
||||
assertThat(
|
||||
//language=JSON
|
||||
hasNullableConstructorParameterAdapter
|
||||
.fromJson("{\"a\":null}")
|
||||
.fromJson("{\"a\":null}"),
|
||||
).isEqualTo(HasNullableConstructorParameter("fallback"))
|
||||
//language=JSON
|
||||
assertThat(
|
||||
hasNullableConstructorParameterAdapter
|
||||
.toJson(HasNullableConstructorParameter(null))
|
||||
.toJson(HasNullableConstructorParameter(null)),
|
||||
).isEqualTo("{\"a\":\"fallback\"}")
|
||||
}
|
||||
|
||||
@@ -329,7 +330,7 @@ class DualKotlinTest {
|
||||
.isEqualTo(
|
||||
"""
|
||||
{"text":"root","r":{"number":0,"r":{"text":"grand child 1"},"t":{"number":1}},"t":{"text":"child 1"}}
|
||||
""".trimIndent()
|
||||
""".trimIndent(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -418,7 +419,7 @@ class DualKotlinTest {
|
||||
class MultipleNonPropertyParameters(
|
||||
val prop: Int,
|
||||
param1: Int = 1,
|
||||
param2: Int = 2
|
||||
param2: Int = 2,
|
||||
) {
|
||||
init {
|
||||
// Ensure the params always uses their default value
|
||||
@@ -445,7 +446,7 @@ class DualKotlinTest {
|
||||
@JsonClass(generateAdapter = true)
|
||||
class OnlyMultipleNonPropertyParameters(
|
||||
param1: Int = 1,
|
||||
param2: Int = 2
|
||||
param2: Int = 2,
|
||||
) {
|
||||
init {
|
||||
// Ensure the params always uses their default value
|
||||
@@ -472,7 +473,7 @@ class DualKotlinTest {
|
||||
parameterized = GenericClass(6),
|
||||
wildcardIn = GenericClass(6),
|
||||
wildcardOut = GenericClass(6),
|
||||
complex = GenericClass(listOf(GenericClass(6)))
|
||||
complex = GenericClass(listOf(GenericClass(6))),
|
||||
)
|
||||
assertThat(adapter.toJson(testValue)).isEqualTo(testJson)
|
||||
|
||||
@@ -486,7 +487,7 @@ class DualKotlinTest {
|
||||
val parameterized: GenericClass<TypeAlias>,
|
||||
val wildcardIn: GenericClass<in TypeAlias>,
|
||||
val wildcardOut: GenericClass<out TypeAlias>,
|
||||
val complex: GenericClass<GenericTypeAlias>?
|
||||
val complex: GenericClass<GenericTypeAlias>?,
|
||||
)
|
||||
|
||||
// Regression test for https://github.com/square/moshi/issues/991
|
||||
@@ -506,7 +507,7 @@ class DualKotlinTest {
|
||||
int = 3,
|
||||
long = 3,
|
||||
float = 3.2f,
|
||||
double = 3.2
|
||||
double = 3.2,
|
||||
)
|
||||
assertThat(adapter.toJson(instance))
|
||||
.isEqualTo(testJson)
|
||||
@@ -533,7 +534,7 @@ class DualKotlinTest {
|
||||
val float: Float,
|
||||
val nullableFloat: Float? = null,
|
||||
val double: Double,
|
||||
val nullableDouble: Double? = null
|
||||
val nullableDouble: Double? = null,
|
||||
)
|
||||
|
||||
// Regression test for https://github.com/square/moshi/issues/990
|
||||
@@ -577,7 +578,7 @@ class DualKotlinTest {
|
||||
val redundantNullableAShouldBeNullable: NullableA?,
|
||||
val manuallyNullableAShouldBeNullable: A?,
|
||||
val convolutedMultiNullableShouldBeNullable: NullableB?,
|
||||
val deepNestedNullableShouldBeNullable: E
|
||||
val deepNestedNullableShouldBeNullable: E,
|
||||
)
|
||||
|
||||
// Regression test for https://github.com/square/moshi/issues/1009
|
||||
@@ -617,12 +618,12 @@ class DualKotlinTest {
|
||||
interface IntersectionTypeInterface<E : Enum<E>>
|
||||
|
||||
enum class IntersectionTypesEnum : IntersectionTypeInterface<IntersectionTypesEnum> {
|
||||
VALUE
|
||||
VALUE,
|
||||
}
|
||||
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class IntersectionTypes<E>(
|
||||
val value: E
|
||||
val value: E,
|
||||
) where E : Enum<E>, E : IntersectionTypeInterface<E>
|
||||
|
||||
@Test fun transientConstructorParameter() {
|
||||
@@ -672,6 +673,7 @@ class DualKotlinTest {
|
||||
|
||||
class TransientProperty {
|
||||
@Transient var a: Int = -1
|
||||
|
||||
@Transient private var b: Int = -1
|
||||
var c: Int = -1
|
||||
|
||||
@@ -712,7 +714,7 @@ class DualKotlinTest {
|
||||
class MultipleIgnoredConstructorParameters(
|
||||
@Json(ignore = true) var a: Int = -1,
|
||||
var b: Int = -1,
|
||||
@Json(ignore = true) var c: Int = -1
|
||||
@Json(ignore = true) var c: Int = -1,
|
||||
)
|
||||
|
||||
@Test fun ignoredProperty() {
|
||||
@@ -732,8 +734,11 @@ class DualKotlinTest {
|
||||
}
|
||||
|
||||
class IgnoredProperty {
|
||||
@Json(ignore = true) var a: Int = -1
|
||||
@Json(ignore = true) private var b: Int = -1
|
||||
@Json(ignore = true)
|
||||
var a: Int = -1
|
||||
|
||||
@Json(ignore = true)
|
||||
private var b: Int = -1
|
||||
var c: Int = -1
|
||||
|
||||
fun getB() = b
|
||||
@@ -756,11 +761,12 @@ class DualKotlinTest {
|
||||
@JsonClass(generateAdapter = true)
|
||||
data class PropertyWithDollarSign(
|
||||
val `$a`: String,
|
||||
@Json(name = "\$b") val b: String
|
||||
@Json(name = "\$b") val b: String,
|
||||
)
|
||||
}
|
||||
|
||||
typealias TypeAlias = Int
|
||||
|
||||
@Suppress("REDUNDANT_PROJECTION")
|
||||
typealias GenericTypeAlias = List<out GenericClass<in TypeAlias>?>?
|
||||
|
||||
|
@@ -276,7 +276,8 @@ class KotlinJsonAdapterTest {
|
||||
}
|
||||
|
||||
class PropertyWithJsonName {
|
||||
@Json(name = "key a") var a: Int = -1
|
||||
@Json(name = "key a")
|
||||
var a: Int = -1
|
||||
var b: Int = -1
|
||||
}
|
||||
|
||||
@@ -289,7 +290,7 @@ class KotlinJsonAdapterTest {
|
||||
assertThat(expected).hasMessageThat().isEqualTo(
|
||||
"No default value for transient constructor parameter #0 " +
|
||||
"a of fun `<init>`(kotlin.Int): " +
|
||||
"com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterTest.RequiredTransientConstructorParameter"
|
||||
"com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterTest.RequiredTransientConstructorParameter",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -305,7 +306,7 @@ class KotlinJsonAdapterTest {
|
||||
assertThat(expected).hasMessageThat().isEqualTo(
|
||||
"No default value for ignored constructor parameter #0 " +
|
||||
"a of fun `<init>`(kotlin.Int): " +
|
||||
"com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterTest.RequiredIgnoredConstructorParameter"
|
||||
"com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterTest.RequiredIgnoredConstructorParameter",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -320,7 +321,7 @@ class KotlinJsonAdapterTest {
|
||||
} catch (expected: IllegalArgumentException) {
|
||||
assertThat(expected).hasMessageThat().isEqualTo(
|
||||
"'a' has a constructor parameter of type " +
|
||||
"kotlin.Int but a property of type kotlin.String."
|
||||
"kotlin.Int but a property of type kotlin.String.",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -406,7 +407,7 @@ class KotlinJsonAdapterTest {
|
||||
fail()
|
||||
} catch (e: IllegalArgumentException) {
|
||||
assertThat(e).hasMessageThat().isEqualTo(
|
||||
"Platform class kotlin.Triple in kotlin.Triple<?, ?, ?> requires explicit JsonAdapter to be registered"
|
||||
"Platform class kotlin.Triple in kotlin.Triple<?, ?, ?> requires explicit JsonAdapter to be registered",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -551,7 +552,7 @@ class KotlinJsonAdapterTest {
|
||||
} catch (expected: IllegalArgumentException) {
|
||||
assertThat(expected).hasMessageThat().isEqualTo(
|
||||
"No property for required constructor parameter #0 a of fun `<init>`(" +
|
||||
"kotlin.Int, kotlin.Int): ${NonPropertyConstructorParameter::class.qualifiedName}"
|
||||
"kotlin.Int, kotlin.Int): ${NonPropertyConstructorParameter::class.qualifiedName}",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -579,7 +580,7 @@ class KotlinJsonAdapterTest {
|
||||
} catch (e: IllegalArgumentException) {
|
||||
assertThat(e).hasMessageThat().isEqualTo(
|
||||
"No JsonAdapter for interface " +
|
||||
"com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterTest\$Interface (with no annotations)"
|
||||
"com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterTest\$Interface (with no annotations)",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -594,7 +595,7 @@ class KotlinJsonAdapterTest {
|
||||
} catch (e: IllegalArgumentException) {
|
||||
assertThat(e).hasMessageThat().isEqualTo(
|
||||
"Cannot serialize abstract class " +
|
||||
"com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterTest\$AbstractClass"
|
||||
"com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterTest\$AbstractClass",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -609,7 +610,7 @@ class KotlinJsonAdapterTest {
|
||||
} catch (e: IllegalArgumentException) {
|
||||
assertThat(e).hasMessageThat().isEqualTo(
|
||||
"Cannot serialize inner class " +
|
||||
"com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterTest\$InnerClass"
|
||||
"com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterTest\$InnerClass",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -625,7 +626,7 @@ class KotlinJsonAdapterTest {
|
||||
} catch (e: IllegalArgumentException) {
|
||||
assertThat(e).hasMessageThat().isEqualTo(
|
||||
"Cannot serialize local class or object expression " +
|
||||
"com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterTest\$localClassesNotSupported\$LocalClass"
|
||||
"com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterTest\$localClassesNotSupported\$LocalClass",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -638,7 +639,7 @@ class KotlinJsonAdapterTest {
|
||||
} catch (e: IllegalArgumentException) {
|
||||
assertThat(e).hasMessageThat().isEqualTo(
|
||||
"Cannot serialize object declaration " +
|
||||
"com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterTest\$ObjectDeclaration"
|
||||
"com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterTest\$ObjectDeclaration",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -666,7 +667,7 @@ class KotlinJsonAdapterTest {
|
||||
assertThat(e).hasMessageThat().isEqualTo(
|
||||
"Cannot serialize $type " +
|
||||
"com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterTest\$anonymousClassesNotSupported" +
|
||||
"\$expression$1"
|
||||
"\$expression$1",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -682,7 +683,7 @@ class KotlinJsonAdapterTest {
|
||||
116, 117, 118, 119, 120,
|
||||
121, 122, 123, 124, 125,
|
||||
126, 127, 128, 129, 130,
|
||||
131, 132
|
||||
131, 132,
|
||||
)
|
||||
val json = (
|
||||
"""
|
||||
@@ -737,7 +738,7 @@ class KotlinJsonAdapterTest {
|
||||
var v29: Int,
|
||||
var v30: Int,
|
||||
var v31: Int,
|
||||
var v32: Int
|
||||
var v32: Int,
|
||||
)
|
||||
|
||||
@Test fun manyProperties33() {
|
||||
@@ -751,7 +752,7 @@ class KotlinJsonAdapterTest {
|
||||
116, 117, 118, 119, 120,
|
||||
121, 122, 123, 124, 125,
|
||||
126, 127, 128, 129, 130,
|
||||
131, 132, 133
|
||||
131, 132, 133,
|
||||
)
|
||||
val json = (
|
||||
"""
|
||||
@@ -808,7 +809,7 @@ class KotlinJsonAdapterTest {
|
||||
var v30: Int,
|
||||
var v31: Int,
|
||||
var v32: Int,
|
||||
var v33: Int
|
||||
var v33: Int,
|
||||
)
|
||||
|
||||
data class Box<out T>(val data: T)
|
||||
@@ -856,6 +857,7 @@ class KotlinJsonAdapterTest {
|
||||
fun toJson(@Uppercase s: String): String {
|
||||
return s.uppercase(Locale.US)
|
||||
}
|
||||
|
||||
@FromJson
|
||||
@Uppercase
|
||||
fun fromJson(s: String): String {
|
||||
@@ -885,7 +887,7 @@ class KotlinJsonAdapterTest {
|
||||
}
|
||||
}
|
||||
null
|
||||
}
|
||||
},
|
||||
)
|
||||
.add(KotlinJsonAdapterFactory())
|
||||
.build()
|
||||
@@ -922,7 +924,7 @@ class KotlinJsonAdapterTest {
|
||||
mapWildcardsParameterizedTest(
|
||||
MapOfStringToStandardReflection::class.java,
|
||||
"""{"map":{"key":"value"}}""",
|
||||
MapOfStringToStandardReflection(mapOf("key" to "value"))
|
||||
MapOfStringToStandardReflection(mapOf("key" to "value")),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -933,7 +935,7 @@ class KotlinJsonAdapterTest {
|
||||
mapWildcardsParameterizedTest(
|
||||
MapOfStringToStandardCodegen::class.java,
|
||||
"""{"map":{"key":"value"}}""",
|
||||
MapOfStringToStandardCodegen(mapOf("key" to "value"))
|
||||
MapOfStringToStandardCodegen(mapOf("key" to "value")),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -945,7 +947,7 @@ class KotlinJsonAdapterTest {
|
||||
mapWildcardsParameterizedTest(
|
||||
MapOfStringToEnumReflection::class.java,
|
||||
"""{"map":{"key":"A"}}""",
|
||||
MapOfStringToEnumReflection(mapOf("key" to KotlinEnum.A))
|
||||
MapOfStringToEnumReflection(mapOf("key" to KotlinEnum.A)),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -956,7 +958,7 @@ class KotlinJsonAdapterTest {
|
||||
mapWildcardsParameterizedTest(
|
||||
MapOfStringToEnumCodegen::class.java,
|
||||
"""{"map":{"key":"A"}}""",
|
||||
MapOfStringToEnumCodegen(mapOf("key" to KotlinEnum.A))
|
||||
MapOfStringToEnumCodegen(mapOf("key" to KotlinEnum.A)),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -968,7 +970,7 @@ class KotlinJsonAdapterTest {
|
||||
mapWildcardsParameterizedTest(
|
||||
MapOfStringToCollectionReflection::class.java,
|
||||
"""{"map":{"key":[]}}""",
|
||||
MapOfStringToCollectionReflection(mapOf("key" to listOf()))
|
||||
MapOfStringToCollectionReflection(mapOf("key" to listOf())),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -979,7 +981,7 @@ class KotlinJsonAdapterTest {
|
||||
mapWildcardsParameterizedTest(
|
||||
MapOfStringToCollectionCodegen::class.java,
|
||||
"""{"map":{"key":[]}}""",
|
||||
MapOfStringToCollectionCodegen(mapOf("key" to listOf()))
|
||||
MapOfStringToCollectionCodegen(mapOf("key" to listOf())),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -991,7 +993,7 @@ class KotlinJsonAdapterTest {
|
||||
mapWildcardsParameterizedTest(
|
||||
MapOfStringToMapReflection::class.java,
|
||||
"""{"map":{"key":{}}}""",
|
||||
MapOfStringToMapReflection(mapOf("key" to mapOf()))
|
||||
MapOfStringToMapReflection(mapOf("key" to mapOf())),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1002,7 +1004,7 @@ class KotlinJsonAdapterTest {
|
||||
mapWildcardsParameterizedTest(
|
||||
MapOfStringToMapCodegen::class.java,
|
||||
"""{"map":{"key":{}}}""",
|
||||
MapOfStringToMapCodegen(mapOf("key" to mapOf()))
|
||||
MapOfStringToMapCodegen(mapOf("key" to mapOf())),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1014,7 +1016,7 @@ class KotlinJsonAdapterTest {
|
||||
mapWildcardsParameterizedTest(
|
||||
MapOfStringToArrayReflection::class.java,
|
||||
"""{"map":{"key":[]}}""",
|
||||
MapOfStringToArrayReflection(mapOf("key" to arrayOf()))
|
||||
MapOfStringToArrayReflection(mapOf("key" to arrayOf())),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1025,7 +1027,7 @@ class KotlinJsonAdapterTest {
|
||||
mapWildcardsParameterizedTest(
|
||||
MapOfStringToArrayCodegen::class.java,
|
||||
"""{"map":{"key":[]}}""",
|
||||
MapOfStringToArrayCodegen(mapOf("key" to arrayOf()))
|
||||
MapOfStringToArrayCodegen(mapOf("key" to arrayOf())),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1037,7 +1039,7 @@ class KotlinJsonAdapterTest {
|
||||
mapWildcardsParameterizedTest(
|
||||
MapOfStringToClassReflection::class.java,
|
||||
"""{"map":{"key":{"a":19,"b":42}}}""",
|
||||
MapOfStringToClassReflection(mapOf("key" to ConstructorParameters(19, 42)))
|
||||
MapOfStringToClassReflection(mapOf("key" to ConstructorParameters(19, 42))),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1048,7 +1050,7 @@ class KotlinJsonAdapterTest {
|
||||
mapWildcardsParameterizedTest(
|
||||
MapOfStringToClassCodegen::class.java,
|
||||
"""{"map":{"key":{"a":19,"b":42}}}""",
|
||||
MapOfStringToClassCodegen(mapOf("key" to ConstructorParameters(19, 42)))
|
||||
MapOfStringToClassCodegen(mapOf("key" to ConstructorParameters(19, 42))),
|
||||
)
|
||||
}
|
||||
|
||||
|
@@ -19,7 +19,7 @@ import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||
|
||||
@Deprecated(
|
||||
message = "this moved to avoid a package name conflict in the Java Platform Module System.",
|
||||
replaceWith = ReplaceWith("com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory")
|
||||
replaceWith = ReplaceWith("com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory"),
|
||||
)
|
||||
public class KotlinJsonAdapterFactory :
|
||||
JsonAdapter.Factory by KotlinJsonAdapterFactory()
|
||||
|
@@ -61,7 +61,7 @@ internal class KotlinJsonAdapter<T>(
|
||||
val constructor: KFunction<T>,
|
||||
val allBindings: List<Binding<T, Any?>?>,
|
||||
val nonIgnoredBindings: List<Binding<T, Any?>>,
|
||||
val options: JsonReader.Options
|
||||
val options: JsonReader.Options,
|
||||
) : JsonAdapter<T>() {
|
||||
|
||||
override fun fromJson(reader: JsonReader): T {
|
||||
@@ -82,7 +82,7 @@ internal class KotlinJsonAdapter<T>(
|
||||
val propertyIndex = binding.propertyIndex
|
||||
if (values[propertyIndex] !== ABSENT_VALUE) {
|
||||
throw JsonDataException(
|
||||
"Multiple values for '${binding.property.name}' at ${reader.path}"
|
||||
"Multiple values for '${binding.property.name}' at ${reader.path}",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ internal class KotlinJsonAdapter<T>(
|
||||
throw unexpectedNull(
|
||||
binding.property.name,
|
||||
binding.jsonName,
|
||||
reader
|
||||
reader,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -108,7 +108,7 @@ internal class KotlinJsonAdapter<T>(
|
||||
else -> throw missingProperty(
|
||||
constructor.parameters[i].name,
|
||||
allBindings[i]?.jsonName,
|
||||
reader
|
||||
reader,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -151,7 +151,7 @@ internal class KotlinJsonAdapter<T>(
|
||||
val adapter: JsonAdapter<P>,
|
||||
val property: KProperty1<K, P>,
|
||||
val parameter: KParameter?,
|
||||
val propertyIndex: Int
|
||||
val propertyIndex: Int,
|
||||
) {
|
||||
fun get(value: K) = property.get(value)
|
||||
|
||||
@@ -165,7 +165,7 @@ internal class KotlinJsonAdapter<T>(
|
||||
/** A simple [Map] that uses parameter indexes instead of sorting or hashing. */
|
||||
class IndexedParameterMap(
|
||||
private val parameterKeys: List<KParameter>,
|
||||
private val parameterValues: Array<Any?>
|
||||
private val parameterValues: Array<Any?>,
|
||||
) : AbstractMutableMap<KParameter, Any?>() {
|
||||
|
||||
override fun put(key: KParameter, value: Any?): Any? = null
|
||||
@@ -278,7 +278,7 @@ public class KotlinJsonAdapterFactory : JsonAdapter.Factory {
|
||||
} else {
|
||||
Types.newParameterizedType(
|
||||
rawClassifierType,
|
||||
*property.returnType.arguments.mapNotNull { it.type?.javaType }.toTypedArray()
|
||||
*property.returnType.arguments.mapNotNull { it.type?.javaType }.toTypedArray(),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
@@ -295,7 +295,7 @@ public class KotlinJsonAdapterFactory : JsonAdapter.Factory {
|
||||
val adapter = moshi.adapter<Any?>(
|
||||
resolvedPropertyType,
|
||||
allAnnotations.toTypedArray().jsonAnnotations,
|
||||
property.name
|
||||
property.name,
|
||||
)
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
@@ -304,7 +304,7 @@ public class KotlinJsonAdapterFactory : JsonAdapter.Factory {
|
||||
adapter,
|
||||
property as KProperty1<Any, Any?>,
|
||||
parameter,
|
||||
parameter?.index ?: -1
|
||||
parameter?.index ?: -1,
|
||||
)
|
||||
}
|
||||
|
||||
|
@@ -31,7 +31,7 @@ class KotlinJsonAdapterTest {
|
||||
.build()
|
||||
val adapter = moshi.adapter(Data::class.java)
|
||||
assertThat(adapter.toString()).isEqualTo(
|
||||
"KotlinJsonAdapter(com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterTest.Data).nullSafe()"
|
||||
"KotlinJsonAdapter(com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterTest.Data).nullSafe()",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
@@ -62,7 +62,7 @@ tasks.withType<KotlinCompile>()
|
||||
kotlinOptions {
|
||||
val toAdd = mutableListOf(
|
||||
"-opt-in=kotlin.contracts.ExperimentalContracts",
|
||||
"-Xjvm-default=all"
|
||||
"-Xjvm-default=all",
|
||||
)
|
||||
if (name.contains("test", true)) {
|
||||
toAdd += "-opt-in=kotlin.ExperimentalStdlibApi"
|
||||
|
@@ -29,12 +29,12 @@ import java.lang.reflect.Type
|
||||
|
||||
internal class AdapterMethodsFactory(
|
||||
private val toAdapters: List<AdapterMethod>,
|
||||
private val fromAdapters: List<AdapterMethod>
|
||||
private val fromAdapters: List<AdapterMethod>,
|
||||
) : JsonAdapter.Factory {
|
||||
override fun create(
|
||||
type: Type,
|
||||
annotations: Set<Annotation>,
|
||||
moshi: Moshi
|
||||
moshi: Moshi,
|
||||
): JsonAdapter<*>? {
|
||||
val toAdapter = get(toAdapters, type, annotations)
|
||||
val fromAdapter = get(fromAdapters, type, annotations)
|
||||
@@ -47,7 +47,7 @@ internal class AdapterMethodsFactory(
|
||||
val missingAnnotation = if (toAdapter == null) "@ToJson" else "@FromJson"
|
||||
throw IllegalArgumentException(
|
||||
"No $missingAnnotation adapter for ${type.toStringWithAnnotations(annotations)}",
|
||||
e
|
||||
e,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
@@ -154,7 +154,7 @@ internal class AdapterMethodsFactory(
|
||||
annotations = qualifierAnnotations,
|
||||
adapter = adapter,
|
||||
method = method,
|
||||
nullable = true
|
||||
nullable = true,
|
||||
) {
|
||||
override fun toJson(moshi: Moshi, writer: JsonWriter, value: Any?) {
|
||||
invokeMethod(writer, value)
|
||||
@@ -173,7 +173,7 @@ internal class AdapterMethodsFactory(
|
||||
annotations = qualifierAnnotations,
|
||||
adapter = adapter,
|
||||
method = method,
|
||||
nullable = nullable
|
||||
nullable = nullable,
|
||||
) {
|
||||
|
||||
private lateinit var delegate: JsonAdapter<Any>
|
||||
@@ -203,7 +203,7 @@ internal class AdapterMethodsFactory(
|
||||
<any access modifier> void toJson(JsonWriter writer, T value, JsonAdapter<any> delegate, <any more delegates>) throws <any>;
|
||||
<any access modifier> R toJson(T value) throws <any>;
|
||||
|
||||
""".trimIndent()
|
||||
""".trimIndent(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -244,7 +244,7 @@ internal class AdapterMethodsFactory(
|
||||
annotations = returnTypeAnnotations,
|
||||
adapter = adapter,
|
||||
method = method,
|
||||
nullable = true
|
||||
nullable = true,
|
||||
) {
|
||||
override fun fromJson(moshi: Moshi, reader: JsonReader) = invokeMethod(reader)
|
||||
}
|
||||
@@ -260,7 +260,7 @@ internal class AdapterMethodsFactory(
|
||||
annotations = returnTypeAnnotations,
|
||||
adapter = adapter,
|
||||
method = method,
|
||||
nullable = nullable
|
||||
nullable = nullable,
|
||||
) {
|
||||
lateinit var delegate: JsonAdapter<Any>
|
||||
|
||||
@@ -288,7 +288,7 @@ internal class AdapterMethodsFactory(
|
||||
<any access modifier> R fromJson(JsonReader jsonReader, JsonAdapter<any> delegate, <any more delegates>) throws <any>;
|
||||
<any access modifier> R fromJson(T value) throws <any>;
|
||||
|
||||
""".trimIndent()
|
||||
""".trimIndent(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -298,7 +298,7 @@ internal class AdapterMethodsFactory(
|
||||
private fun get(
|
||||
adapterMethods: List<AdapterMethod>,
|
||||
type: Type,
|
||||
annotations: Set<Annotation>
|
||||
annotations: Set<Annotation>,
|
||||
): AdapterMethod? {
|
||||
for (adapterMethod in adapterMethods) {
|
||||
if (Types.equals(adapterMethod.type, type) && adapterMethod.annotations == annotations) {
|
||||
@@ -316,7 +316,7 @@ internal class AdapterMethodsFactory(
|
||||
val annotations: Set<Annotation>,
|
||||
val adapter: Any,
|
||||
val method: Method,
|
||||
val nullable: Boolean
|
||||
val nullable: Boolean,
|
||||
) {
|
||||
val type = type.canonicalize()
|
||||
private val jsonAdapters: Array<JsonAdapter<*>?> = arrayOfNulls(parameterCount - adaptersOffset)
|
||||
|
@@ -24,7 +24,7 @@ import java.lang.reflect.Array as JavaArray
|
||||
*/
|
||||
internal class ArrayJsonAdapter(
|
||||
private val elementClass: Class<*>,
|
||||
private val elementAdapter: JsonAdapter<Any>
|
||||
private val elementAdapter: JsonAdapter<Any>,
|
||||
) : JsonAdapter<Any?>() {
|
||||
override fun fromJson(reader: JsonReader): Any {
|
||||
val list = buildList<Any?> {
|
||||
|
@@ -87,7 +87,7 @@ internal abstract class ClassFactory<T> {
|
||||
val newInstance = ObjectStreamClass::class.java.getDeclaredMethod(
|
||||
"newInstance",
|
||||
Class::class.java,
|
||||
Int::class.javaPrimitiveType
|
||||
Int::class.javaPrimitiveType,
|
||||
)
|
||||
newInstance.isAccessible = true
|
||||
return object : ClassFactory<T>() {
|
||||
|
@@ -49,7 +49,7 @@ import java.lang.reflect.Type
|
||||
*/
|
||||
internal class ClassJsonAdapter<T>(
|
||||
private val classFactory: ClassFactory<T>,
|
||||
fieldsMap: Map<String, FieldBinding<*>>
|
||||
fieldsMap: Map<String, FieldBinding<*>>,
|
||||
) : JsonAdapter<T>() {
|
||||
private val fieldsArray = fieldsMap.values.toTypedArray()
|
||||
private val options = JsonReader.Options.of(*fieldsMap.keys.toTypedArray())
|
||||
@@ -115,7 +115,7 @@ internal class ClassJsonAdapter<T>(
|
||||
override fun create(
|
||||
type: Type,
|
||||
annotations: Set<Annotation>,
|
||||
moshi: Moshi
|
||||
moshi: Moshi,
|
||||
): JsonAdapter<*>? {
|
||||
if (type !is Class<*> && type !is ParameterizedType) {
|
||||
return null
|
||||
@@ -136,7 +136,7 @@ internal class ClassJsonAdapter<T>(
|
||||
}
|
||||
}
|
||||
throw IllegalArgumentException(
|
||||
"$messagePrefix requires explicit JsonAdapter to be registered"
|
||||
"$messagePrefix requires explicit JsonAdapter to be registered",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -185,7 +185,7 @@ internal class ClassJsonAdapter<T>(
|
||||
private fun createFieldBindings(
|
||||
moshi: Moshi,
|
||||
type: Type,
|
||||
fieldBindings: MutableMap<String, FieldBinding<*>>
|
||||
fieldBindings: MutableMap<String, FieldBinding<*>>,
|
||||
) {
|
||||
val rawType = type.rawType
|
||||
val platformType = rawType.isPlatformType
|
||||
@@ -201,7 +201,7 @@ internal class ClassJsonAdapter<T>(
|
||||
val adapter = moshi.adapter<Any>(
|
||||
type = fieldType,
|
||||
annotations = annotations,
|
||||
fieldName = fieldName
|
||||
fieldName = fieldName,
|
||||
)
|
||||
|
||||
// Create the binding between field and JSON.
|
||||
|
@@ -20,7 +20,7 @@ import java.lang.reflect.Type
|
||||
|
||||
/** Converts collection types to JSON arrays containing their converted contents. */
|
||||
internal abstract class CollectionJsonAdapter<C : MutableCollection<T?>, T> private constructor(
|
||||
private val elementAdapter: JsonAdapter<T>
|
||||
private val elementAdapter: JsonAdapter<T>,
|
||||
) : JsonAdapter<C>() {
|
||||
|
||||
abstract fun newCollection(): C
|
||||
|
@@ -39,7 +39,7 @@ public annotation class Json(
|
||||
*
|
||||
* **Note:** this has no effect in `enum` or `record` classes.
|
||||
*/
|
||||
val ignore: Boolean = false
|
||||
val ignore: Boolean = false,
|
||||
) {
|
||||
public companion object {
|
||||
/** The default value of [name]. Should only be used to check if it's been set. */
|
||||
|
@@ -63,5 +63,5 @@ public annotation class JsonClass(
|
||||
* generator to create the API signature to get started, then make your own generator match that
|
||||
* expected signature.
|
||||
*/
|
||||
val generator: String = ""
|
||||
val generator: String = "",
|
||||
)
|
||||
|
@@ -230,7 +230,6 @@ public sealed class JsonReader : Closeable {
|
||||
* useful in development and debugging because it means a typo like "locatiom" will be detected
|
||||
* early. It's potentially harmful in production because it complicates revising a JSON schema.
|
||||
*/
|
||||
/** Returns true if this parser forbids skipping names and values. */
|
||||
@get:JvmName("failOnUnknown")
|
||||
public var failOnUnknown: Boolean = false
|
||||
|
||||
@@ -578,7 +577,7 @@ public sealed class JsonReader : Closeable {
|
||||
*/
|
||||
public class Options private constructor(
|
||||
internal val strings: Array<out String>,
|
||||
internal val doubleQuoteSuffix: OkioOptions
|
||||
internal val doubleQuoteSuffix: OkioOptions,
|
||||
) {
|
||||
/** Returns a copy of this [Option's][Options] strings. */
|
||||
public fun strings(): List<String> {
|
||||
@@ -657,7 +656,7 @@ public sealed class JsonReader : Closeable {
|
||||
* The end of the JSON stream. This sentinel value is returned by [JsonReader.peek] to
|
||||
* signal that the JSON-encoded value has no more tokens.
|
||||
*/
|
||||
END_DOCUMENT
|
||||
END_DOCUMENT,
|
||||
}
|
||||
|
||||
public companion object {
|
||||
|
@@ -530,7 +530,9 @@ internal class JsonUtf8Reader : JsonReader {
|
||||
peeked = PEEKED_NONE
|
||||
pathNames[stackSize - 1] = name
|
||||
i
|
||||
} else -1
|
||||
} else {
|
||||
-1
|
||||
}
|
||||
}
|
||||
|
||||
override fun nextString(): String {
|
||||
@@ -586,7 +588,9 @@ internal class JsonUtf8Reader : JsonReader {
|
||||
peeked = PEEKED_NONE
|
||||
pathIndices[stackSize - 1]++
|
||||
i
|
||||
} else -1
|
||||
} else {
|
||||
-1
|
||||
}
|
||||
}
|
||||
|
||||
override fun nextBoolean(): Boolean {
|
||||
|
@@ -37,7 +37,7 @@ import kotlin.require
|
||||
|
||||
internal class JsonUtf8Writer(
|
||||
/** The output data, containing at most one top-level array or object. */
|
||||
private val sink: BufferedSink
|
||||
private val sink: BufferedSink,
|
||||
) : JsonWriter() {
|
||||
|
||||
/** The name/value separator; either ":" or ": ". */
|
||||
|
@@ -381,7 +381,7 @@ internal class JsonValueReader : JsonReader {
|
||||
internal class JsonIterator(
|
||||
val endToken: Token,
|
||||
val array: Array<Any?>,
|
||||
var next: Int
|
||||
var next: Int,
|
||||
) : Iterator<Any?>, Cloneable {
|
||||
override fun hasNext() = next < array.size
|
||||
|
||||
|
@@ -47,7 +47,7 @@ internal class JsonValueSource @JvmOverloads constructor(
|
||||
* reached, this should be compared against 0. If it is zero, then we've read a complete value and
|
||||
* this source is exhausted.
|
||||
*/
|
||||
private var stackSize: Int = 0
|
||||
private var stackSize: Int = 0,
|
||||
) : Source {
|
||||
private val buffer: Buffer = source.buffer
|
||||
|
||||
|
@@ -158,6 +158,7 @@ public sealed class JsonWriter : Closeable, Flushable {
|
||||
* the encoded document will be compact.
|
||||
*/
|
||||
get() = _indent.orEmpty()
|
||||
|
||||
/**
|
||||
* Sets the indentation string to be repeated for each level of indentation in the encoded
|
||||
* document. If `indent.isEmpty()` the encoded document will be compact. Otherwise, the
|
||||
|
@@ -22,7 +22,7 @@ internal class LinkedHashTreeMap<K, V>
|
||||
* @param comparator the comparator to order elements with, or null to use the natural ordering.
|
||||
*/
|
||||
constructor(
|
||||
comparator: Comparator<Any?>? = null
|
||||
comparator: Comparator<Any?>? = null,
|
||||
) : AbstractMutableMap<K, V>(), Serializable {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
private val comparator: Comparator<Any?> = (comparator ?: NATURAL_ORDER) as Comparator<Any?>
|
||||
@@ -83,6 +83,7 @@ constructor(
|
||||
|
||||
@JvmField
|
||||
var next: Node<K, V>?
|
||||
|
||||
@JvmField
|
||||
var prev: Node<K, V>?
|
||||
|
||||
|
@@ -51,7 +51,7 @@ internal class MapJsonAdapter<K, V>(moshi: Moshi, keyType: Type, valueType: Type
|
||||
val replaced = result.put(name, value)
|
||||
if (replaced != null) {
|
||||
throw JsonDataException(
|
||||
"Map key '$name' has multiple values at path ${reader.path}: $replaced and $value"
|
||||
"Map key '$name' has multiple values at path ${reader.path}: $replaced and $value",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
@@ -107,7 +107,7 @@ public class Moshi internal constructor(builder: Builder) {
|
||||
public fun <T> adapter(
|
||||
type: Type,
|
||||
annotations: Set<Annotation>,
|
||||
fieldName: String?
|
||||
fieldName: String?,
|
||||
): JsonAdapter<T> {
|
||||
val cleanedType = type.canonicalize().removeSubtypeWildcard()
|
||||
|
||||
@@ -150,7 +150,7 @@ public class Moshi internal constructor(builder: Builder) {
|
||||
public fun <T> nextAdapter(
|
||||
skipPast: JsonAdapter.Factory,
|
||||
type: Type,
|
||||
annotations: Set<Annotation>
|
||||
annotations: Set<Annotation>,
|
||||
): JsonAdapter<T> {
|
||||
val cleanedType = type.canonicalize().removeSubtypeWildcard()
|
||||
val skipPastIndex = factories.indexOf(skipPast)
|
||||
@@ -203,7 +203,7 @@ public class Moshi internal constructor(builder: Builder) {
|
||||
public fun <T> add(
|
||||
type: Type,
|
||||
annotation: Class<out Annotation>,
|
||||
jsonAdapter: JsonAdapter<T>
|
||||
jsonAdapter: JsonAdapter<T>,
|
||||
): Builder = apply {
|
||||
add(newAdapterFactory(type, annotation, jsonAdapter))
|
||||
}
|
||||
@@ -225,7 +225,7 @@ public class Moshi internal constructor(builder: Builder) {
|
||||
public fun <T> addLast(
|
||||
type: Type,
|
||||
annotation: Class<out Annotation>,
|
||||
jsonAdapter: JsonAdapter<T>
|
||||
jsonAdapter: JsonAdapter<T>,
|
||||
): Builder = apply {
|
||||
addLast(newAdapterFactory(type, annotation, jsonAdapter))
|
||||
}
|
||||
@@ -373,7 +373,7 @@ public class Moshi internal constructor(builder: Builder) {
|
||||
|
||||
fun <T> newAdapterFactory(
|
||||
type: Type,
|
||||
jsonAdapter: JsonAdapter<T>
|
||||
jsonAdapter: JsonAdapter<T>,
|
||||
): JsonAdapter.Factory {
|
||||
return JsonAdapter.Factory { targetType, annotations, _ ->
|
||||
if (annotations.isEmpty() && typesMatch(type, targetType)) jsonAdapter else null
|
||||
@@ -383,7 +383,7 @@ public class Moshi internal constructor(builder: Builder) {
|
||||
fun <T> newAdapterFactory(
|
||||
type: Type,
|
||||
annotation: Class<out Annotation>,
|
||||
jsonAdapter: JsonAdapter<T>
|
||||
jsonAdapter: JsonAdapter<T>,
|
||||
): JsonAdapter.Factory {
|
||||
require(annotation.isAnnotationPresent(JsonQualifier::class.java)) { "$annotation does not have @JsonQualifier" }
|
||||
require(annotation.declaredMethods.isEmpty()) { "Use JsonAdapter.Factory for annotations with elements" }
|
||||
|
@@ -53,7 +53,9 @@ internal object StandardJsonAdapters : JsonAdapter.Factory {
|
||||
return if (rawType.isEnum) {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
EnumJsonAdapter(rawType as Class<out Enum<*>>).nullSafe()
|
||||
} else null
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun rangeCheckNextInt(reader: JsonReader, typeMessage: String?, min: Int, max: Int): Int {
|
||||
@@ -120,7 +122,7 @@ internal object StandardJsonAdapters : JsonAdapter.Factory {
|
||||
// Double check for infinity after float conversion; many doubles > Float.MAX
|
||||
if (!reader.lenient && value.isInfinite()) {
|
||||
throw JsonDataException(
|
||||
"JSON forbids NaN and infinities: $value at path ${reader.path}"
|
||||
"JSON forbids NaN and infinities: $value at path ${reader.path}",
|
||||
)
|
||||
}
|
||||
return value
|
||||
@@ -207,7 +209,7 @@ internal object StandardJsonAdapters : JsonAdapter.Factory {
|
||||
val path = reader.path
|
||||
val name = reader.nextString()
|
||||
throw JsonDataException(
|
||||
"Expected one of ${nameStrings.toList()} but was $name at path $path"
|
||||
"Expected one of ${nameStrings.toList()} but was $name at path $path",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -242,7 +244,7 @@ internal object StandardJsonAdapters : JsonAdapter.Factory {
|
||||
JsonReader.Token.BOOLEAN -> booleanAdapter.fromJson(reader)
|
||||
JsonReader.Token.NULL -> reader.nextNull()
|
||||
else -> throw IllegalStateException(
|
||||
"Expected a value but was ${reader.peek()} at path ${reader.path}"
|
||||
"Expected a value but was ${reader.peek()} at path ${reader.path}",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
@@ -14,6 +14,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
@file:Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
|
||||
|
||||
package com.squareup.moshi
|
||||
|
||||
import com.squareup.moshi.internal.EMPTY_TYPE_ARRAY
|
||||
@@ -74,7 +75,7 @@ public object Types {
|
||||
@JvmStatic
|
||||
public fun nextAnnotations(
|
||||
annotations: Set<Annotation>,
|
||||
jsonQualifier: Class<out Annotation?>
|
||||
jsonQualifier: Class<out Annotation?>,
|
||||
): Set<Annotation>? {
|
||||
require(jsonQualifier.isAnnotationPresent(JsonQualifier::class.java)) {
|
||||
"$jsonQualifier is not a JsonQualifier."
|
||||
@@ -112,7 +113,7 @@ public object Types {
|
||||
public fun newParameterizedTypeWithOwner(
|
||||
ownerType: Type?,
|
||||
rawType: Type,
|
||||
vararg typeArguments: Type
|
||||
vararg typeArguments: Type,
|
||||
): ParameterizedType {
|
||||
require(typeArguments.isNotEmpty()) {
|
||||
"Missing type arguments for $rawType"
|
||||
@@ -198,7 +199,9 @@ public object Types {
|
||||
}
|
||||
return if (collectionType is ParameterizedType) {
|
||||
collectionType.actualTypeArguments[0]
|
||||
} else Any::class.java
|
||||
} else {
|
||||
Any::class.java
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns true if `a` and `b` are equal. */
|
||||
@@ -254,7 +257,7 @@ public object Types {
|
||||
@JvmStatic
|
||||
public fun getFieldJsonQualifierAnnotations(
|
||||
clazz: Class<*>,
|
||||
fieldName: String
|
||||
fieldName: String,
|
||||
): Set<Annotation> {
|
||||
try {
|
||||
val field = clazz.getDeclaredField(fieldName)
|
||||
@@ -271,7 +274,8 @@ public object Types {
|
||||
}
|
||||
} catch (e: NoSuchFieldException) {
|
||||
throw IllegalArgumentException(
|
||||
"Could not access field $fieldName on class ${clazz.canonicalName}", e
|
||||
"Could not access field $fieldName on class ${clazz.canonicalName}",
|
||||
e,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -289,7 +293,8 @@ public object Types {
|
||||
}
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
return Proxy.newProxyInstance(
|
||||
annotationType.classLoader, arrayOf<Class<*>>(annotationType)
|
||||
annotationType.classLoader,
|
||||
arrayOf<Class<*>>(annotationType),
|
||||
) { proxy, method, args ->
|
||||
when (method.name) {
|
||||
"annotationType" -> annotationType
|
||||
|
@@ -15,6 +15,7 @@
|
||||
*/
|
||||
@file:JvmName("Util")
|
||||
@file:Suppress("unused", "MemberVisibilityCanBePrivate")
|
||||
|
||||
package com.squareup.moshi.internal
|
||||
|
||||
import com.squareup.moshi.Json
|
||||
@@ -49,6 +50,7 @@ import java.util.LinkedHashSet
|
||||
import kotlin.contracts.contract
|
||||
|
||||
@JvmField internal val NO_ANNOTATIONS: Set<Annotation> = emptySet()
|
||||
|
||||
@JvmField internal val EMPTY_TYPE_ARRAY: Array<Type> = arrayOf()
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
@@ -108,7 +110,7 @@ public val Array<Annotation>.jsonAnnotations: Set<Annotation>
|
||||
for (annotation in this) {
|
||||
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
|
||||
if ((annotation as java.lang.annotation.Annotation).annotationType()
|
||||
.isAnnotationPresent(JsonQualifier::class.java)
|
||||
.isAnnotationPresent(JsonQualifier::class.java)
|
||||
) {
|
||||
if (result == null) result = LinkedHashSet()
|
||||
result.add(annotation)
|
||||
@@ -118,7 +120,7 @@ public val Array<Annotation>.jsonAnnotations: Set<Annotation>
|
||||
}
|
||||
|
||||
internal fun Set<Annotation>.isAnnotationPresent(
|
||||
annotationClass: Class<out Annotation>
|
||||
annotationClass: Class<out Annotation>,
|
||||
): Boolean {
|
||||
if (isEmpty()) return false // Save an iterator in the common case.
|
||||
for (annotation in this) {
|
||||
@@ -207,7 +209,7 @@ public fun Type.resolve(context: Type, contextRawType: Class<*>): Type {
|
||||
private fun Type.resolve(
|
||||
context: Type,
|
||||
contextRawType: Class<*>,
|
||||
visitedTypeVariables: MutableCollection<TypeVariable<*>>
|
||||
visitedTypeVariables: MutableCollection<TypeVariable<*>>,
|
||||
): Type {
|
||||
// This implementation is made a little more complicated in an attempt to avoid object-creation.
|
||||
var toResolve = this
|
||||
@@ -361,7 +363,7 @@ internal fun Type.toStringWithAnnotations(annotations: Set<Annotation>): String
|
||||
*/
|
||||
public fun Moshi.generatedAdapter(
|
||||
type: Type,
|
||||
rawType: Class<*>
|
||||
rawType: Class<*>,
|
||||
): JsonAdapter<*>? {
|
||||
val jsonClass = rawType.getAnnotation(JsonClass::class.java)
|
||||
if (jsonClass == null || !jsonClass.generateAdapter) {
|
||||
@@ -403,11 +405,12 @@ public fun Moshi.generatedAdapter(
|
||||
if (possiblyFoundAdapter != null && type !is ParameterizedType && possiblyFoundAdapter.typeParameters.isNotEmpty()) {
|
||||
throw RuntimeException(
|
||||
"Failed to find the generated JsonAdapter constructor for '$type'. Suspiciously, the type was not parameterized but the target class '${possiblyFoundAdapter.canonicalName}' is generic. Consider using Types#newParameterizedType() to define these missing type variables.",
|
||||
e
|
||||
e,
|
||||
)
|
||||
} else {
|
||||
throw RuntimeException(
|
||||
"Failed to find the generated JsonAdapter constructor for $type", e
|
||||
"Failed to find the generated JsonAdapter constructor for $type",
|
||||
e,
|
||||
)
|
||||
}
|
||||
} catch (e: IllegalAccessException) {
|
||||
@@ -452,7 +455,7 @@ private fun <T> Class<T>.findConstructor(): Constructor<T> {
|
||||
public fun missingProperty(
|
||||
propertyName: String?,
|
||||
jsonName: String?,
|
||||
reader: JsonReader
|
||||
reader: JsonReader,
|
||||
): JsonDataException {
|
||||
val path = reader.path
|
||||
val message = if (jsonName == propertyName) {
|
||||
@@ -466,7 +469,7 @@ public fun missingProperty(
|
||||
public fun unexpectedNull(
|
||||
propertyName: String,
|
||||
jsonName: String,
|
||||
reader: JsonReader
|
||||
reader: JsonReader,
|
||||
): JsonDataException {
|
||||
val path = reader.path
|
||||
val message: String = if (jsonName == propertyName) {
|
||||
@@ -512,7 +515,7 @@ internal class ParameterizedTypeImpl private constructor(
|
||||
private val ownerType: Type?,
|
||||
private val rawType: Type,
|
||||
@JvmField
|
||||
val typeArguments: Array<Type>
|
||||
val typeArguments: Array<Type>,
|
||||
) : ParameterizedType {
|
||||
override fun getActualTypeArguments() = typeArguments.clone()
|
||||
|
||||
@@ -547,14 +550,16 @@ internal class ParameterizedTypeImpl private constructor(
|
||||
operator fun invoke(
|
||||
ownerType: Type?,
|
||||
rawType: Type,
|
||||
vararg typeArguments: Type
|
||||
vararg typeArguments: Type,
|
||||
): ParameterizedTypeImpl {
|
||||
// Require an owner type if the raw type needs it.
|
||||
if (rawType is Class<*>) {
|
||||
val enclosingClass = rawType.enclosingClass
|
||||
if (ownerType != null) {
|
||||
require(!(enclosingClass == null || ownerType.rawType != enclosingClass)) { "unexpected owner type for $rawType: $ownerType" }
|
||||
} else require(enclosingClass == null) { "unexpected owner type for $rawType: null" }
|
||||
} else {
|
||||
require(enclosingClass == null) { "unexpected owner type for $rawType: null" }
|
||||
}
|
||||
}
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
val finalTypeArgs = typeArguments.clone() as Array<Type>
|
||||
@@ -594,7 +599,7 @@ internal class GenericArrayTypeImpl private constructor(private val componentTyp
|
||||
*/
|
||||
internal class WildcardTypeImpl private constructor(
|
||||
private val upperBound: Type,
|
||||
private val lowerBound: Type?
|
||||
private val lowerBound: Type?,
|
||||
) : WildcardType {
|
||||
|
||||
override fun getUpperBounds() = arrayOf(upperBound)
|
||||
@@ -622,7 +627,7 @@ internal class WildcardTypeImpl private constructor(
|
||||
@JvmName("create")
|
||||
operator fun invoke(
|
||||
upperBounds: Array<Type>,
|
||||
lowerBounds: Array<Type>
|
||||
lowerBounds: Array<Type>,
|
||||
): WildcardTypeImpl {
|
||||
require(lowerBounds.size <= 1)
|
||||
require(upperBounds.size == 1)
|
||||
@@ -631,13 +636,13 @@ internal class WildcardTypeImpl private constructor(
|
||||
require(!(upperBounds[0] !== Any::class.java))
|
||||
WildcardTypeImpl(
|
||||
lowerBound = lowerBounds[0].canonicalize(),
|
||||
upperBound = Any::class.java
|
||||
upperBound = Any::class.java,
|
||||
)
|
||||
} else {
|
||||
upperBounds[0].checkNotPrimitive()
|
||||
WildcardTypeImpl(
|
||||
lowerBound = null,
|
||||
upperBound = upperBounds[0].canonicalize()
|
||||
upperBound = upperBounds[0].canonicalize(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
@@ -37,14 +37,14 @@ import java.lang.reflect.Type
|
||||
internal class RecordJsonAdapter<T>(
|
||||
private val constructor: MethodHandle,
|
||||
private val targetClass: String,
|
||||
componentBindings: Map<String, ComponentBinding<Any>>
|
||||
componentBindings: Map<String, ComponentBinding<Any>>,
|
||||
) : JsonAdapter<T>() {
|
||||
|
||||
data class ComponentBinding<T>(
|
||||
val componentName: String,
|
||||
val jsonName: String,
|
||||
val adapter: JsonAdapter<T>,
|
||||
val accessor: MethodHandle
|
||||
val accessor: MethodHandle,
|
||||
)
|
||||
|
||||
private val componentBindingsArray = componentBindings.values.toTypedArray()
|
||||
@@ -77,7 +77,7 @@ internal class RecordJsonAdapter<T>(
|
||||
throw missingProperty(
|
||||
propertyName = componentBindingsArray[i].componentName,
|
||||
jsonName = componentBindingsArray[i].jsonName,
|
||||
reader = reader
|
||||
reader = reader,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -133,7 +133,7 @@ internal class RecordJsonAdapter<T>(
|
||||
val replaced = bindings.put(componentBinding.jsonName, componentBinding)
|
||||
if (replaced != null) {
|
||||
throw IllegalArgumentException(
|
||||
"Conflicting components:\n ${replaced.componentName}\n ${componentBinding.componentName}"
|
||||
"Conflicting components:\n ${replaced.componentName}\n ${componentBinding.componentName}",
|
||||
)
|
||||
}
|
||||
component.type
|
||||
@@ -155,7 +155,7 @@ internal class RecordJsonAdapter<T>(
|
||||
rawType: Class<*>,
|
||||
moshi: Moshi,
|
||||
lookup: MethodHandles.Lookup,
|
||||
component: RecordComponent
|
||||
component: RecordComponent,
|
||||
): ComponentBinding<Any> {
|
||||
val componentName = component.name
|
||||
val jsonName = component.jsonName(componentName)
|
||||
|
Reference in New Issue
Block a user