-
Notifications
You must be signed in to change notification settings - Fork 422
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Rework Pickler for coproducts and enums #3222
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
9a8f84f
Rework handling for enumeration
kciesielski 0e8fad8
Remove EnumValueDiscriminator
kciesielski b76356e
Test signatures
kciesielski 4ca7130
Split tests into smaller suites
kciesielski 718232a
Extend documentation about enumerations
kciesielski c0d32a2
Restore section name
kciesielski 5222bf3
Rework coproducts and configuration
kciesielski f7be39b
Add missing file
kciesielski f3792c3
Adjust documentation
kciesielski 23384c9
Organize imports
kciesielski 6368534
Restore original file state
kciesielski 7088450
Refactor handling default discriminator in writers
kciesielski File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,15 @@ | ||
package sttp.tapir.json.pickler | ||
|
||
import sttp.tapir.generic.Configuration | ||
import _root_.upickle.implicits.{macros => upickleMacros} | ||
import sttp.tapir.macros.CreateDerivedEnumerationSchema | ||
import sttp.tapir.{Schema, SchemaAnnotations, SchemaType, Validator} | ||
import upickle.core.{Annotator, Types} | ||
|
||
import scala.deriving.Mirror | ||
import scala.reflect.ClassTag | ||
|
||
import compiletime.* | ||
|
||
/** A builder allowing deriving Pickler for enums, used by [[Pickler.derivedEnumeration]]. Can be used to set non-standard encoding logic, | ||
* schema type or default value for an enum. | ||
*/ | ||
|
@@ -23,37 +26,77 @@ class CreateDerivedEnumerationPickler[T: ClassTag]( | |
* The low-level representation of the enumeration. Defaults to a string. | ||
*/ | ||
inline def apply( | ||
encode: Option[T => Any] = Some(identity), | ||
encode: T => Any = identity, | ||
schemaType: SchemaType[T] = SchemaType.SString[T](), | ||
default: Option[T] = None | ||
)(using m: Mirror.Of[T]): Pickler[T] = { | ||
)(using m: Mirror.SumOf[T]): Pickler[T] = { | ||
val schema: Schema[T] = new CreateDerivedEnumerationSchema(validator, schemaAnnotations).apply( | ||
encode, | ||
Some(encode), | ||
schemaType, | ||
default | ||
) | ||
given Configuration = Configuration.default | ||
given SubtypeDiscriminator[T] = EnumValueDiscriminator[T]( | ||
encode.map(_.andThen(_.toString)).getOrElse(_.toString), | ||
validator | ||
) | ||
lazy val childPicklers: Tuple.Map[m.MirroredElemTypes, Pickler] = Pickler.summonChildPicklerInstances[T, m.MirroredElemTypes] | ||
Pickler.picklerSum(schema, childPicklers) | ||
lazy val childReadWriters = buildEnumerationReadWriters[T, m.MirroredElemTypes] | ||
val tapirPickle = new TapirPickle[T] { | ||
override lazy val reader: Reader[T] = { | ||
val readersForPossibleValues: Seq[TaggedReader[T]] = | ||
validator.possibleValues.zip(childReadWriters.map(_._1)).map { case (enumValue, reader) => | ||
TaggedReader.Leaf[T](encode(enumValue).toString, reader.asInstanceOf[LeafWrapper[_]].r.asInstanceOf[Reader[T]]) | ||
} | ||
new TaggedReader.Node[T](readersForPossibleValues: _*) | ||
} | ||
|
||
override lazy val writer: Writer[T] = | ||
new TaggedWriter.Node[T](childReadWriters.map(_._2.asInstanceOf[TaggedWriter[T]]): _*) { | ||
override def findWriter(v: Any): (String, ObjectWriter[T]) = | ||
val (t, writer) = super.findWriter(v) | ||
// Here our custom encoding transforms the value of a singleton object | ||
val overriddenTag = encode(v.asInstanceOf[T]).toString | ||
(overriddenTag, writer) | ||
} | ||
} | ||
new Pickler[T](tapirPickle, schema) | ||
} | ||
|
||
private inline def buildEnumerationReadWriters[T: ClassTag, Cases <: Tuple]: List[(Types#Reader[_], Types#Writer[_])] = | ||
inline erasedValue[Cases] match { | ||
case _: (enumerationCase *: enumerationCasesTail) => | ||
val processedHead = readWriterForEnumerationCase[enumerationCase] | ||
val processedTail = buildEnumerationReadWriters[T, enumerationCasesTail] | ||
(processedHead +: processedTail) | ||
case _: EmptyTuple.type => Nil | ||
} | ||
|
||
/** Enumeration cases and case objects in an enumeration need special writers and readers, which are generated here, instead of being | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. thanks, much clearer now :) |
||
* taken from child picklers. For example, for enum Color and case values Red and Blue, a Writer should just use the object Red or Blue | ||
* and serialize it to "Red" or "Blue". If user needs to encode the singleton object using a custom function, this happens on a higher | ||
* level - the top level of coproduct reader and writer. | ||
*/ | ||
private inline def readWriterForEnumerationCase[C]: (Types#Reader[C], Types#Writer[C]) = | ||
val pickle = new TapirPickle[C] { | ||
// We probably don't need a separate TapirPickle for each C, this could be optimized. | ||
// https://github.com/softwaremill/tapir/issues/3192 | ||
override lazy val writer = annotate[C]( | ||
SingletonWriter[C](null.asInstanceOf[C]), | ||
upickleMacros.tagName[C], | ||
Annotator.Checker.Val(upickleMacros.getSingleton[C]) | ||
) | ||
override lazy val reader = annotate[C](SingletonReader[C](upickleMacros.getSingleton[C]), upickleMacros.tagName[C]) | ||
} | ||
(pickle.reader, pickle.writer) | ||
|
||
/** Creates the Pickler assuming the low-level representation is a `String`. The encoding function passes the object unchanged (which | ||
* means `.toString` will be used to represent the enumeration in JSON and documentation). Typically you don't need to explicitly use | ||
* `Pickler.derivedEnumeration[T].defaultStringBased`, as this is the default behavior of [[Pickler.derived]] for enums. | ||
*/ | ||
inline def defaultStringBased(using Mirror.Of[T]) = apply() | ||
inline def defaultStringBased(using Mirror.SumOf[T]) = apply() | ||
|
||
/** Creates the Pickler assuming the low-level representation is a `String`. Provide your custom encoding function for representing an | ||
* enum value as a String. It will be used to represent the enumeration in JSON and documentation. This approach is recommended if you | ||
* need to encode enums using a common field in their base trait, or another specific logic for extracting string representation. | ||
*/ | ||
inline def customStringBased(encode: T => String)(using Mirror.Of[T]): Pickler[T] = | ||
inline def customStringBased(encode: T => String)(using Mirror.SumOf[T]): Pickler[T] = | ||
apply( | ||
Some(encode), | ||
encode, | ||
schemaType = SchemaType.SString[T](), | ||
default = None | ||
) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍