/
SerializationMacros.scala
226 lines (184 loc) · 6.39 KB
/
SerializationMacros.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
/*
* Copyright 2016 eiennohito (Tolmachev Arseny)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.kotonoha.lift.json
import net.liftweb.common.{Box, Empty, Failure, Full}
import net.liftweb.json.JsonAST.{JField, JValue}
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
/**
* @author eiennohito
* @since 2016/08/12
*/
object JLCaseClass {
def write[T <: Product]: JWrite[T] = macro SerializationMacros.writeCaseClass[T]
def read[T <: Product]: JRead[T] = macro SerializationMacros.readCaseClass[T]
def format[T <: Product]: JFormat[T] = macro SerializationMacros.formatCaseClass[T]
}
class SerializationMacros(val c: blackbox.Context) {
import c.universe._
def formatCaseClass[T](implicit tt: WeakTypeTag[T]): Tree = {
val q"new $rt { ..$wb }" = readCaseClass[T]
val q"new $wt { ..$rb }" = writeCaseClass[T]
val ft = weakTypeOf[JFormat[T]]
q"new $rt with $wt with $ft { ..$wb ; ..$rb }"
}
def writeCaseClass[T](implicit tt: WeakTypeTag[T]): Tree = {
val wr = weakTypeOf[JWrite[T]]
val tp = weakTypeOf[T]
val jv = weakTypeOf[JValue]
val obj = TermName("obj")
val bname = TermName("__bldr___")
val decls = tp.decls.filter {
case m: MethodSymbol => m.isCaseAccessor
case _ => false
}.map { i =>
new FieldSpawner(i.name.decodedName.toString, i.info.resultType)
}
val bldr = reify { List.newBuilder[JField] }
val tree = q"""
new $wr {
def write($obj: $tp): $jv = {
val $bname = $bldr
..${decls.map(_.serializeField(obj, bname))}
net.liftweb.json.JsonAST.JObject($bname.result())
}
}
"""
//println(tree)
tree
}
private val option = weakTypeOf[Option[Int]].typeConstructor
class FieldSpawner(name: String, tp: Type) {
val nm = TermName(name)
val backingFieldName = TermName(s"___backing_field___$name")
val backingVarName = TermName(s"___backing_var___$name")
val isOptional = {
val tpc = tp.typeConstructor
tpc != NoType && tpc == option
}
val myType = if (isOptional) tp.typeArgs.head else tp
val backingType = tq"net.liftweb.common.Box[$myType]"
val tread = tq"ws.kotonoha.lift.json.JRead[$myType]"
def backingField = {
q"private[this] var $backingFieldName: $backingType = null"
}
def caseEmitter(tree: Tree) = {
cq"$name => $backingFieldName = implicitly[$tread].read($tree)"
}
def backingVar = q"var $backingVarName: $tp = $varExpansion"
val f = TermName("f")
def noValueError = q"""addError(net.liftweb.common.Failure("no value found for field " + $name)); ${defaultTrees(myType)}"""
def varExpansion =
q"""
$backingFieldName match {
case net.liftweb.common.Full($f) => ${if(isOptional) q"Some($f)" else q"f"}
case null | net.liftweb.common.Empty =>
${if (isOptional) q"None" else noValueError}
case e: net.liftweb.common.Failure =>
addError(e)
${if (isOptional) q"None" else defaultTrees(myType)}
}
"""
def serializeField(obj: TermName, bldr: TermName): Tree = {
val root = q"$obj.$nm"
val access = if (isOptional) q"$root.get" else root
val jout = tq"ws.kotonoha.lift.json.JWrite[$myType]"
val jvtree = q"implicitly[$jout].write($access)"
val rhs = q"new net.liftweb.json.JsonAST.JField($name, $jvtree)"
if (isOptional) {
q"""
if ($root.isDefined) {
$bldr += $rhs
}
"""
} else {
q"$bldr += $rhs"
}
}
}
private val wttString = weakTypeOf[String]
private val defaultTrees = Map[Type, Tree] (
wttString -> q""" "" """,
WeakTypeTag.Int.tpe -> q"0",
WeakTypeTag.Long.tpe -> q"0L",
WeakTypeTag.Short.tpe -> q"0",
WeakTypeTag.Byte.tpe -> q"0",
WeakTypeTag.Boolean.tpe -> q"false",
WeakTypeTag.Float.tpe -> q"0.0f",
WeakTypeTag.Double.tpe -> q"0.0"
).withDefaultValue(q"null")
def readCaseClass[T](implicit tt: WeakTypeTag[T]): Tree = {
val readType = weakTypeOf[JRead[T]]
val objType = weakTypeOf[Box[T]]
val jvType = weakTypeOf[JValue]
val jfType = weakTypeOf[JField]
val bldrType = weakTypeOf[AbstractBuilder[T]]
val input = TermName("jv")
val bldr = TermName("bldr")
val ourType = weakTypeOf[T]
val decls = ourType.decls.filter {
case m: MethodSymbol => m.isCaseAccessor
case _ => false
}.map {
s => new FieldSpawner(s.name.encodedName.toString, s.info.resultType)
}
val resultBody =
q"""
..${decls.map(_.backingVar)}
if (this.errors.isEmpty) {
net.liftweb.common.Full(
new $ourType(..${decls.map(_.backingVarName)})
)
} else {
this.errors.openOrThrowException("should be full here")
}
"""
val bldrTree = q"""
new $bldrType {
..${decls.map(_.backingField)}
def appendField(f: $jfType) = {
f.name match {
case ..${decls.map(_.caseEmitter(q"f.value"))}
case _ =>
}
}
def result(): $objType = $resultBody
}
"""
val tree = q"""
new $readType {
def read($input: $jvType): $objType = {
$input match {
case net.liftweb.json.JsonAST.JObject(fields) =>
val bldr = $bldrTree
val iter = fields.iterator
while(iter.hasNext) {
val f: $jfType = iter.next()
f.value match {
case net.liftweb.json.JsonAST.JNull | net.liftweb.json.JsonAST.JNothing =>
case _ => bldr.appendField(f)
}
}
bldr.result()
case _ => net.liftweb.common.Failure("input was not a JObject on top level " + $input)
}
}
}
"""
//println(tree)
tree
}
}