Commit graph

17 commits

Author SHA1 Message Date
Jesse Wilson
d1df4740d5 Support properties that don't have a backing field.
Currently our main loop to gather PropertyGenerators goes over the backing fields.
This needs to change to iterate over the properties themselves. That leads to a lot
of churn. The net result is slightly more compatibility with the reflective adapter.
2018-04-09 00:08:15 -04:00
Jesse Wilson
cb9c084d30 Use JsonAdapter.nonNull() in generated adapters.
Also extract a type for the delegate key.

Also fix the generator to reject inner classes, abstract classes,
and local classes.
2018-04-08 20:54:50 -04:00
Eric Cochran
ba1318cc45 Make "no adapter" error message friendlier.
In the very common case, there are no JsonQualifier annotations for the type.
2018-04-08 00:48:38 -07:00
Jesse Wilson
b52d63dfbf
Merge pull request #486 from square/eric.integration-reflect
Remove kotlin-reflect dep from integration-test.
2018-04-06 20:19:55 -07:00
Eric Cochran
083210eb40 Add generated code file comment. (#485) 2018-04-06 20:18:43 -07:00
Eric Cochran
7d4a10f521
Remove kotlin-reflect dep from integration-test. 2018-04-06 16:17:26 -07:00
Jesse Wilson
466f77aabe JsonAdapter.nonNull() forbids explicit nulls in the JSON body
This adapter modifier throws exceptions if an unexpected null is
encountered. This may pair nicely with Kotlin.
2018-04-04 23:08:36 -07:00
Jesse Wilson
75f2d5c8dd
Merge pull request #474 from hzsweers/z/newmetadata
Update to kotlin-metadata 1.3.0 and just use mavencentral
2018-04-04 01:16:03 -04:00
Jesse Wilson
42f4f956e0
Merge pull request #473 from square/jwilson.0403.qualifiers_names_transient
Handle qualifiers, names, and transient in generated adapters
2018-04-04 00:42:47 -04:00
Zac Sweers
5f4c46f402 Update to kotlin-metadata 1.3.0 and just use mavencentral 2018-04-03 13:23:38 -07:00
Jesse Wilson
d555d24d94 Handle qualifiers, names, and transient in generated adapters 2018-04-03 11:00:40 -04:00
Zac Sweers
5c45d1e0d9 Generate @Generated annotation onto adapters when possible (#466)
* Generate `@Generated` annotation onto adapters when possible

Part of #461

This leverages AutoCommon's `GeneratedAnnotations#generatedAnnotation` API to generate a `@Generated` annotation where possible. This keeps with conventions in other code gen tools, and also allows for more fine grained proguard rules for keeping generated adapter names, like so:

```proguard
-keepnames @com.squareup.moshi.<wherever this ends up>.MoshiSerializable class *

# Java < 9
-keepnames @javax.annotation.Generated class **JsonAdapter

#  Java 9+
-keepnames @javax.annotation.processing.Generated class **JsonAdapter
```

Generated annotation looks like this:

```kotlin
@Generated(
        value = ["com.squareup.moshi.MoshiKotlinCodeGenProcessor"],
        comments = "https://github.com/square/moshi"
)
```

This doooooes also replace `elements` in `AdapterGenerator` with a `ProcessingEnv`, but I figured that was less evil than polluting it with both `elements` and plumbing down an `env` separately simultaneously. This does also hit a weird ambiguity case due to `KotlinMetadataUtils`' repeat declaration, so a good reason for removing that in the future. Figured it best to punt on a better final place for this to another time.

* Remove names and brackets

* Add moshi.generated option

* Switch back to element property rather than processingEnv

* Fold the kotlin-codegen-runtime into Moshi itself.

Rename @MoshiSerializable to @JsonClass. Like @Json, I'm anticipating
a future where there are other interesting properties on this annotation.
Perhaps a future feature where Moshi is strict and only adapts types that
have a '@JsonClass' annotation.

Also rename MoshiKotlinCodeGenProcessor to JsonClassCodeGenProcessor. We
may later support other ways of generating code here; perhaps for regular
Java types.

* Generate `@Generated` annotation onto adapters when possible

Part of #461

This leverages AutoCommon's `GeneratedAnnotations#generatedAnnotation` API to generate a `@Generated` annotation where possible. This keeps with conventions in other code gen tools, and also allows for more fine grained proguard rules for keeping generated adapter names, like so:

```proguard
-keepnames @com.squareup.moshi.<wherever this ends up>.MoshiSerializable class *

# Java < 9
-keepnames @javax.annotation.Generated class **JsonAdapter

#  Java 9+
-keepnames @javax.annotation.processing.Generated class **JsonAdapter
```

Generated annotation looks like this:

```kotlin
@Generated(
        value = ["com.squareup.moshi.MoshiKotlinCodeGenProcessor"],
        comments = "https://github.com/square/moshi"
)
```

This doooooes also replace `elements` in `AdapterGenerator` with a `ProcessingEnv`, but I figured that was less evil than polluting it with both `elements` and plumbing down an `env` separately simultaneously. This does also hit a weird ambiguity case due to `KotlinMetadataUtils`' repeat declaration, so a good reason for removing that in the future. Figured it best to punt on a better final place for this to another time.

* Fix rebase conflicts and sync with remote
2018-04-03 03:27:57 -04:00
Jesse Wilson
b3d7dfd603 Support non-data classes for generated JsonAdapters
This is towards making the reflection and codegen adapters work the same.
The process is relatively straightforward: try to promote all of the tests
in KotlinCodeGenTest to be passing tests in GeneratedAdaptersTest or
compile failures in CompilerTest
2018-04-02 00:37:17 -04:00
Jesse Wilson
0c24bd4846 Call the kotlin compiler from within a test case.
This is a fragile first step.
2018-03-31 00:57:50 -04:00
Jesse Wilson
982f9c94f6 Fold the kotlin-codegen-runtime into Moshi itself.
Rename @MoshiSerializable to @JsonClass. Like @Json, I'm anticipating
a future where there are other interesting properties on this annotation.
Perhaps a future feature where Moshi is strict and only adapts types that
have a '@JsonClass' annotation.

Also rename MoshiKotlinCodeGenProcessor to JsonClassCodeGenProcessor. We
may later support other ways of generating code here; perhaps for regular
Java types.
2018-03-28 20:26:20 -04:00
Jesse Wilson
d045947ea7
Split the MoshiKotlinCodeGenProcessor into multiple types. (#462)
Move more behavior into the types: Adapter and Property now have many
instance methods and are now mutable value classes rather than immutable
data classes.

This changes how some of the bookkeeping code works. Previously there were
some pretty tricky types: maps with pairs as keys, indexed and non-indexed
lists of properties. With this change more of the logic operates directly
on the properties.
2018-03-24 20:53:08 -04:00
Zac Sweers
96e074d030 Kotlin Code Gen module (#435)
* Add kotlin code gen modules

* Update kotlin to 1.2

* Add a serializable dummy class

* Try using kapt configuration from kotlin-examples repo

Still no luck!

* Use proper allocated name for assignment too

* Use selectName() API

* Clean up constructor parameter annotations & plumbing for qualifiers

* Updates poms and kotlin code gen processor to support tests.

* Ignore kotlin code gen tests for now

None of these are data classes tests right now, which is the only thing this supports right now

* Replace $ with _ in class names for consistency

* Shortcut Array types to arrayOf

* Add DataClassTest

* Try generated option first, fall back to maven after

* More idiomatic handling

* Only use nonnullable types for adapter properties

* Code dump of kotshi tests

* Comment out specifics to get compiling

* Generics support!

* Fix double primitive default

* Pick up temporary snapshot for Any fix

* Invariance should just be null

* Better handling of nullably-bound variance

* Just assume the first jvm constructor for now as jvmMethodSig is flaky

* Specify types param if needed

* Don't do lazy delegation

* Clean up nullable typevariablename boundaries

* Add type variables to extension function on companion object

* Use properties instead of allocated names for more robustness

Since we're already on a snapshot

* If there are no type variables, make it null for simpler handling

* Fix generics and Type[] handling

* Fix unnecessary as casts on primitive defaults

* Reference spec directly for possible bangs

* Use nullSafe() adapters for anything nullable or with default values

* Use object type in makeType()

Types.java cares

* Make TestPrimitiveDefaultValues work

* Re-enable TestClassWithJavaKeyword

* Ignore remaining tests that are pending decisions or JsonQualifier support

* Remove customnames test as we're just going to stick with simple @Json

* Add toString() implementations

* Reenable default values testing, adapt to kotlin lang support

* Remove primitive adapters bits since we're not using it

* Clean up a bunch of leftover comments

* Switch to only nullable handling, report missing properties

This makes all nullable handling for local properties the same, and removes defaults for primitives in the process. It simplifies the handling a lot, and leans on kotlin language features to take care of null handling (null checking and then throwing the lazily evaluated list of missing properties).

One minor change from what kotshi does - this reports the serialized name in the missing properties, not the property name. We could look at supporting this though if we want.

* Implement JsonQualifier support

* Use Kapt for AutoService/processor declaration

* Checkstyle

* Remove unused primite type checks

* Add test verifying mutable and immutable collections work

* Fix test name

* Standardize isRequired checks

* Add more nullability and mutability tests

* Kotlinpoet 0.7.0 final

* Switch to new vararg overload for annotation class adapter()

* Make suffix just JsonAdapter without underscore

* Switch to just a regular constructor for MoshiSerializableFactory

* Remove constructor caching

* Remove unnecessary framework class checks

* Nix unnecessary superclass lookups, inline constructor lookup

* Nix null token check in reads

* Nix null check in writes, do !! on first value use

* Nix null checks in favor of serializeNulls

* Inline null checks and fail eagerly

* Fix double _Adapter

* First pass at simplifying adapter names

* Inline names to options property, life into class and rm companion

* Differentiate between absent and null, use nullSafe() as needed

* Group together compile and test dependencies

* Remove incorrect comment

* Revert formatting

* Set, not mutable set

* Collapse else-if nesting to one when

* Cleaner formatting test code

* Collapse more to locals

* Collapse more

* Return a nonnullable type in fromJson

* Remove redundant out variance

* Use KClass where appropriate

* End comment in period

* Remove redundant comment

* Throw on unrecognized type in simplified name

* Use illegalargumentexception instead

* Emit a nullcheck at the beginning of toJson instead

* Remove extra newline

* Simplify processing to be less abusive

* Skip using asClassName() when possible

* Use addComment()

* Switch to declared constructors

Technically more correct since we're defining these

* Unmodifiable set

* return adapter(type, annotationTypes[0])

* Slight optimization - check if the type is parameterized first

If the type is a parameterized type, then we know they'll have the two-arg constructor. This way we don't always try and fail the single arg constructor on parameterized types

* Add test for type aliases, optimize to reuse adapters if possible

This is a tiny optimization to make type aliases (which did already work) reuse adapter properties if they already exist for the backing type. What this means is that if you have:

typealias Foo = String

and properties
foo: Foo
bar: String

you'll only get one adapter property field for String, and both will use it

* Use string templating where possible

* Remove all the kotshi tests
2018-03-11 21:17:55 -04:00