Skip to content

Commit

Permalink
Allow mapping scalars to simple generic types (#6158)
Browse files Browse the repository at this point in the history
* Allow mapping scalars to simple generic types

* Automatically prefix a few common Kotlin and Java types with their package names
  • Loading branch information
BoD authored Sep 24, 2024
1 parent 426364e commit c7f608d
Show file tree
Hide file tree
Showing 21 changed files with 615 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import com.apollographql.apollo.compiler.codegen.ResolverClassName
import com.apollographql.apollo.compiler.codegen.ResolverEntry
import com.apollographql.apollo.compiler.codegen.ResolverKey
import com.apollographql.apollo.compiler.codegen.ResolverKeyKind
import com.apollographql.apollo.compiler.codegen.java.helpers.bestGuess
import com.apollographql.apollo.compiler.codegen.java.helpers.singletonAdapterInitializer
import com.apollographql.apollo.compiler.ir.IrCatchTo
import com.apollographql.apollo.compiler.ir.IrCompositeType2
Expand Down Expand Up @@ -96,7 +97,7 @@ internal class JavaResolver(
val result = resolve(ResolverKey(kind, id))

check(result != null) {
"Cannot resolve $kind($id). " +
"Cannot resolve $kind($id). " +
"Have you set up an 'opposite link' on the downstream project to the schema module as a isADependencyOf(..)?"
}
return result
Expand Down Expand Up @@ -239,9 +240,9 @@ internal class JavaResolver(
}
}

private fun resolveScalarTarget(name: String): ClassName? {
private fun resolveScalarTarget(name: String): TypeName? {
return scalarMapping[name]?.targetName?.let {
ClassName.bestGuess(it)
bestGuess(it)
}
}

Expand Down Expand Up @@ -427,7 +428,8 @@ internal class JavaResolver(
}


internal fun ResolverClassName.toJavaPoetClassName(): ClassName = ClassName.get(packageName, simpleNames[0], *simpleNames.drop(1).toTypedArray())
internal fun ResolverClassName.toJavaPoetClassName(): ClassName =
ClassName.get(packageName, simpleNames[0], *simpleNames.drop(1).toTypedArray())


private val primitiveTypeNames = setOf(TypeName.DOUBLE, TypeName.INT, TypeName.BOOLEAN)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.apollographql.apollo.compiler.codegen.java.helpers

import com.squareup.javapoet.ClassName
import com.squareup.javapoet.ParameterizedTypeName
import com.squareup.javapoet.TypeName

/**
* Best guess a type name. Handles simple generics like `Map<String, Integer>`, but no variance or wildcards.
*/
internal fun bestGuess(name: String): TypeName? {
val className = ClassName.bestGuess(name.substringBefore('<').withPackage())
val typeArgs = name.substringAfter('<', "").substringBefore('>', "")
.split(',')
.filterNot { it.isEmpty() }
.map { it.trim() }
return if (typeArgs.isEmpty()) {
className
} else {
ParameterizedTypeName.get(className, *typeArgs.map { bestGuess(it) }.toTypedArray())
}
}

private fun String.withPackage(): String {
return if (this in commonJavaTypes) {
"java.lang.${this}"
} else if (this in commonJavaCollectionsTypes) {
"java.util.${this}"
} else {
this
}
}

private val commonJavaTypes = setOf(
"Boolean",
"Byte",
"Character",
"Double",
"Float",
"Integer",
"Iterable",
"Long",
"Short",
"String",
)

private val commonJavaCollectionsTypes = setOf(
"Collection",
"List",
"Map",
"Set",
)
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import com.apollographql.apollo.compiler.codegen.ResolverClassName
import com.apollographql.apollo.compiler.codegen.ResolverEntry
import com.apollographql.apollo.compiler.codegen.ResolverKey
import com.apollographql.apollo.compiler.codegen.ResolverKeyKind
import com.apollographql.apollo.compiler.codegen.kotlin.helpers.bestGuess
import com.apollographql.apollo.compiler.codegen.kotlin.helpers.obj
import com.apollographql.apollo.compiler.ir.IrCatchTo
import com.apollographql.apollo.compiler.ir.IrCompositeType2
Expand Down Expand Up @@ -43,7 +44,7 @@ internal class KotlinResolver(
private val scalarMapping: Map<String, ScalarInfo>,
private val requiresOptInAnnotation: String?,
) {
fun resolve(key: ResolverKey): ClassName? {
fun resolve(key: ResolverKey): ClassName? {
return classNames[key] ?: next?.resolve(key)
}

Expand All @@ -60,7 +61,7 @@ internal class KotlinResolver(

check(result != null) {
"Cannot resolve $kind($id). " +
"Have you set up an 'opposite link' on the downstream project to the schema module as a isADependencyOf(..)?"
"Have you set up an 'opposite link' on the downstream project to the schema module as a isADependencyOf(..)?"
}
return result
}
Expand All @@ -85,6 +86,7 @@ internal class KotlinResolver(
type.optional -> {
KotlinSymbols.Optional.parameterizedBy(resolveIrType(type.optional(false), jsExport, isInterface))
}

type.catchTo != IrCatchTo.NoCatch -> {
resolveIrType(type.catchTo(IrCatchTo.NoCatch), jsExport, isInterface).let {
when (type.catchTo) {
Expand All @@ -94,9 +96,11 @@ internal class KotlinResolver(
}
}
}

type.nullable -> {
resolveIrType(type.nullable(false), jsExport, isInterface).copy(nullable = true)
}

else -> {
when (type) {
is IrListType -> resolveIrType(type.ofType, jsExport, isInterface).wrapInList(jsExport, isInterface)
Expand Down Expand Up @@ -139,9 +143,9 @@ internal class KotlinResolver(
return listType.parameterizedBy(param)
}

private fun resolveScalarTarget(name: String): ClassName? {
private fun resolveScalarTarget(name: String): TypeName? {
return scalarMapping[name]?.targetName?.let {
ClassName.bestGuess(it)
bestGuess(it)
}
}

Expand Down Expand Up @@ -203,6 +207,7 @@ internal class KotlinResolver(
val presentFun = MemberName("com.apollographql.apollo.api", "present")
CodeBlock.of("%L.%M()", adapterInitializer(type.optional(false), requiresBuffering, jsExport), presentFun)
}

type.catchTo != IrCatchTo.NoCatch -> {
adapterInitializer(type.catchTo(IrCatchTo.NoCatch), requiresBuffering, jsExport).let {
val member = when (type.catchTo) {
Expand All @@ -213,11 +218,13 @@ internal class KotlinResolver(
CodeBlock.of("%L.%M()", it, member)
}
}

type.maybeError -> {
adapterInitializer(type.maybeError(false), requiresBuffering, jsExport).let {
CodeBlock.of("%L.%M()", it, KotlinSymbols.errorAware)
}
}

type.nullable -> {
// Don't hardcode the adapter when the scalar is mapped to a user-defined type
val scalarWithoutCustomMapping = type is IrScalarType && !scalarMapping.containsKey(type.name)
Expand All @@ -237,6 +244,7 @@ internal class KotlinResolver(
}
}
}

else -> {
when (type) {
is IrListType -> {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package com.apollographql.apollo.compiler.codegen.kotlin.helpers

import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.TypeName

/**
* Best guess a type name. Handles simple generics like `Map<String, Int?>`, but no variance or wildcards.
* Common types such as `String`, `List`, `Map` are automatically prefixed with `kotlin.` or `kotlin.collections.`.
*/
internal fun bestGuess(name: String): TypeName {
val isNullable = name.endsWith('?')
val className = ClassName.bestGuess(name.substringBeforeLast('?').substringBefore('<').withPackage())
val typeArgs = name.substringAfter('<', "").substringBefore('>', "")
.split(',')
.filterNot { it.isEmpty() }
.map { it.trim() }
return if (typeArgs.isEmpty()) {
className
} else {
className.parameterizedBy(typeArgs.map { bestGuess(it) })
}
.copy(nullable = isNullable)
}

private fun String.withPackage(): String {
return if (this in commonKotlinTypes) {
"kotlin.${this}"
} else if (this in commonKotlinCollectionsTypes) {
"kotlin.collections.${this}"
} else {
this
}
}

private val commonKotlinTypes = setOf(
"Any",
"Boolean",
"Byte",
"Char",
"CharSequence",
"Double",
"Float",
"Int",
"Long",
"Number",
"Short",
"String",
"UByte",
"UInt",
"ULong",
"Unit",
"UShort",
)

private val commonKotlinCollectionsTypes = setOf(
"Array",
"Collection",
"Iterable",
"List",
"Map",
"Set",
)
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,7 @@ query TestQuery {
links
}
}

query ScalarWithGenericType {
listOfString
}
Loading

0 comments on commit c7f608d

Please sign in to comment.