-
Notifications
You must be signed in to change notification settings - Fork 18
/
ScalaGen.scala
425 lines (355 loc) · 14.5 KB
/
ScalaGen.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
package tscfg.generators.scala
import tscfg.{ModelBuilder, model}
import tscfg.generators.scala.scalaUtil.scalaIdentifier
import tscfg.generators.{Generator, GenOpts, GenResult, tsConfigUtil}
import tscfg.model._
class ScalaGen(genOpts: GenOpts) extends Generator(genOpts) {
val accessors = new Accessors
import defs._
implicit val methodNames = MethodNames()
val getter = Getter(hasPath, accessors, methodNames)
import methodNames._
def generate(objectType: ObjectType): GenResult = {
genResults = GenResult()
checkUserSymbol(className)
val res = generateForObj(objectType, className = className, isRoot = true)
val packageStr = s"package ${genOpts.packageName}\n\n"
val definition = (packageStr + res.definition).trim
res.copy(definition = res.definition.trim)
genResults.copy(code = definition)
}
private def generate(typ: Type,
classNamesPrefix: List[String],
className: String
): Res = typ match {
case ot: ObjectType ⇒ generateForObj(ot, classNamesPrefix, className)
case lt: ListType ⇒ generateForList(lt,classNamesPrefix, className)
case bt: BasicType ⇒ generateForBasic(bt)
}
private def generateForObj(ot: ObjectType,
classNamesPrefix: List[String] = List.empty,
className: String,
isRoot: Boolean = false
): Res = {
genResults = genResults.copy(classNames = genResults.classNames + className)
val symbols = ot.members.keys.toList.sorted
symbols.foreach(checkUserSymbol)
val padScalaIdLength = if (symbols.isEmpty) 0 else
symbols.map(scalaIdentifier).maxBy(_.length).length
def padId(id: String) = id + (" " * (padScalaIdLength - id.length))
val results = symbols.map { symbol ⇒
val scalaId = scalaIdentifier(symbol)
genResults = genResults.copy(fieldNames = genResults.fieldNames + scalaId)
val a = ot.members(symbol)
val res = generate(a.t,
classNamesPrefix = className+"." :: classNamesPrefix,
className = scalaUtil.getClassName(symbol)
)
(symbol, res)
}
val classMembersStr = results.map { case (symbol, res) ⇒
val a = ot.members(symbol)
val memberType = res.scalaType
val typ = if (a.optional && a.default.isEmpty) s"scala.Option[$memberType]" else memberType
val scalaId = scalaIdentifier(symbol)
padId(scalaId) + " : " + typ
}.mkString(",\n ")
val classStr = {
s"""case class $className(
| $classMembersStr
|)
|""".stripMargin
}
implicit val listAccessors = collection.mutable.LinkedHashMap[String,String]()
val objectMembersStr = results.map { case (symbol, res) ⇒
val a = ot.members(symbol)
val scalaId = scalaIdentifier(symbol)
padId(scalaId) + " = " + getter.instance(a, res, symbol)
}.mkString(",\n ")
val innerClassesStr = {
val defs = results.map(_._2.definition).filter(_.nonEmpty)
if (defs.isEmpty) "" else {
"\n " + defs.mkString("\n").replaceAll("\n", "\n ")
}
}
val elemAccessorsStr = {
val objOnes = if (listAccessors.isEmpty) "" else {
"\n " + listAccessors.keys.toList.sorted.map { methodName ⇒
listAccessors(methodName).replaceAll("\n", "\n ")
}.mkString("\n ")
}
val rootOnes = if (!isRoot) "" else {
if (accessors.rootListAccessors.isEmpty) "" else {
"\n\n " + accessors.rootListAccessors.keys.toList.sorted.map { methodName ⇒
accessors.rootListAccessors(methodName).replaceAll("\n", "\n ")
}.mkString("\n ")
}
}
objOnes + rootOnes
}
val fullClassName = classNamesPrefix.reverse.mkString + className
val objectString = {
s"""object $className {$innerClassesStr
| def apply(c: com.typesafe.config.Config): $fullClassName = {
| $fullClassName(
| $objectMembersStr
| )
| }$elemAccessorsStr
|}
""".stripMargin
}
Res(ot,
scalaType = BaseScalaType(classNamesPrefix.reverse.mkString + className),
definition = classStr + objectString
)
}
private def generateForList(lt: ListType,
classNamesPrefix: List[String],
className: String
): Res = {
val className2 = className + (if (className.endsWith("$Elm")) "" else "$Elm")
val elem = generate(lt.t, classNamesPrefix, className2)
Res(lt,
scalaType = ListScalaType(elem.scalaType),
definition = elem.definition
)
}
private def generateForBasic(b: BasicType): Res = {
Res(b, scalaType = BaseScalaType(name = b match {
case STRING ⇒ "java.lang.String"
case INTEGER ⇒ "scala.Int"
case LONG ⇒ "scala.Long"
case DOUBLE ⇒ "scala.Double"
case BOOLEAN ⇒ "scala.Boolean"
case DURATION(_) ⇒ "scala.Long"
}))
}
}
object ScalaGen {
import java.io.{File, PrintWriter, FileWriter}
import tscfg.util
// $COVERAGE-OFF$
def generate(filename: String, showOut: Boolean = false): GenResult = {
val file = new File(filename)
val source = io.Source.fromFile(file).mkString.trim
if (showOut)
println("source:\n |" + source.replaceAll("\n", "\n |"))
val className = "Scala" + {
val noPath = filename.substring(filename.lastIndexOf('/') + 1)
val noDef = noPath.replaceAll("""^def\.""", "")
val symbol = noDef.substring(0, noDef.indexOf('.'))
util.upperFirst(symbol) + "Cfg"
}
val buildResult = ModelBuilder(source)
val objectType = buildResult.objectType
if (showOut) {
println("\nobjectType:\n |" + model.util.format(objectType).replaceAll("\n", "\n |"))
if (buildResult.warnings.nonEmpty) {
println("warnings:")
buildResult.warnings.foreach(w ⇒ println(s" line ${w.line}: ${w.source}: ${w.message}"))
}
}
val genOpts = GenOpts("tscfg.example", className, j7 = false)
val generator = new ScalaGen(genOpts)
val results = generator.generate(objectType)
//println("\n" + results.code)
val destFilename = s"src/main/scala/tscfg/example/$className.scala"
val destFile = new File(destFilename)
val out = new PrintWriter(new FileWriter(destFile), true)
out.println(results.code)
results
}
def main(args: Array[String]): Unit = {
val filename = args(0)
val results = generate(filename, showOut = true)
println(
s"""classNames: ${results.classNames}
|fieldNames: ${results.fieldNames}
""".stripMargin)
}
// $COVERAGE-ON$
}
private[scala] object defs {
abstract sealed class ScalaType
case class BaseScalaType(name: String) extends ScalaType {
override def toString: String = name
}
case class ListScalaType(st: ScalaType) extends ScalaType {
override def toString: String = s"scala.List[$st]"
}
case class Res(typ: Type,
scalaType: ScalaType,
definition: String = "")
}
private[scala] case class MethodNames(prefix: String = "$_") {
val strA = prefix + "str"
val intA = prefix + "int"
val lngA = prefix + "lng"
val dblA = prefix + "dbl"
val blnA = prefix + "bln"
val durA = prefix + "dur"
val expE = prefix + "expE"
val listPrefix = prefix + "L"
def checkUserSymbol(symbol: String): Unit = {
if (symbol.startsWith(prefix))
println(
s"""
|WARNING: Symbol $symbol may cause conflict with generated code.
| Avoid the $prefix prefix in your spec's identifiers.
""".stripMargin
)
}
// definition of methods used to access list's elements of basic type
val basicElemAccessDefinition: Map[String, String] = {
Map(
strA → s"""
|private def $strA(cv:com.typesafe.config.ConfigValue) =
| java.lang.String.valueOf(cv.unwrapped())
|""".stripMargin.trim,
intA → s"""
|private def $intA(cv:com.typesafe.config.ConfigValue): scala.Int = {
| val u: Any = cv.unwrapped
| if ((cv.valueType != com.typesafe.config.ConfigValueType.NUMBER) ||
| !u.isInstanceOf[Integer]) throw $expE(cv, "integer")
| u.asInstanceOf[Integer]
|}""".stripMargin.trim,
lngA → s"""
|private def $lngA(cv:com.typesafe.config.ConfigValue): scala.Long = {
| val u: Any = cv.unwrapped
| if ((cv.valueType != com.typesafe.config.ConfigValueType.NUMBER) ||
| !u.isInstanceOf[java.lang.Integer] && !u.isInstanceOf[java.lang.Long]) throw $expE(cv, "long")
| u.asInstanceOf[java.lang.Number].longValue()
|}""".stripMargin.trim,
dblA → s"""
|private def $dblA(cv:com.typesafe.config.ConfigValue): scala.Double = {
| val u: Any = cv.unwrapped
| if ((cv.valueType != com.typesafe.config.ConfigValueType.NUMBER) ||
| !u.isInstanceOf[java.lang.Number]) throw $expE(cv, "double")
| u.asInstanceOf[java.lang.Number].doubleValue()
|}""".stripMargin.trim,
blnA → s"""
|private def $blnA(cv:com.typesafe.config.ConfigValue): scala.Boolean = {
| val u: Any = cv.unwrapped
| if ((cv.valueType != com.typesafe.config.ConfigValueType.BOOLEAN) ||
| !u.isInstanceOf[java.lang.Boolean]) throw $expE(cv, "boolean")
| u.asInstanceOf[java.lang.Boolean].booleanValue()
|}""".stripMargin.trim
)
}
val expEDef: String = {
s"""
|private def $expE(cv:com.typesafe.config.ConfigValue, exp:java.lang.String) = {
| val u: Any = cv.unwrapped
| new java.lang.RuntimeException(cv.origin.lineNumber +
| ": expecting: " + exp + " got: " +
| (if (u.isInstanceOf[java.lang.String]) "\\"" + u + "\\"" else u))
|}""".stripMargin.trim
}
}
private[scala] case class Getter(hasPath: String, accessors: Accessors, implicit val methodNames: MethodNames) {
import defs._
def instance(a: AnnType, res: Res, path: String)
(implicit listAccessors: collection.mutable.LinkedHashMap[String, String]): String = {
a.t match {
case bt:BasicType ⇒ basicInstance(a, bt, path)
case _:ObjectType ⇒ objectInstance(a, res, path)
case lt:ListType ⇒ listInstance(a, lt, res, path)
}
}
private def objectInstance(a: AnnType, res: Res, path: String): String = {
val className = res.scalaType.toString
if (a.optional) {
s"""if(c.$hasPath("$path")) scala.Some($className(c.getConfig("$path"))) else None"""
}
else s"""$className(c.getConfig("$path"))"""
}
private def listInstance(a: AnnType, lt: ListType, res: Res, path: String)
(implicit listAccessors: collection.mutable.Map[String, String]
): String = {
val scalaType: ListScalaType = res.scalaType.asInstanceOf[ListScalaType]
val base = accessors.listMethodName(scalaType, lt, path)
if (a.optional) {
s"""if(c.$hasPath("$path")) scala.Some($base) else None"""
}
else base
}
private def basicInstance(a: AnnType, bt: BasicType, path: String): String = {
val getter = tsConfigUtil.basicGetter(bt, path)
a.default match {
case Some(v) ⇒
val value = tsConfigUtil.basicValue(a.t, v)
s"""if(c.$hasPath("$path")) c.$getter else $value"""
case None if a.optional ⇒
s"""if(c.$hasPath("$path")) Some(c.$getter) else None"""
case _ ⇒
s"""c.$getter"""
}
}
}
private[scala] class Accessors {
import defs._
val rootListAccessors = collection.mutable.LinkedHashMap[String,String]()
def listMethodName(scalaType: ListScalaType,
lt: ListType,
path: String
)
(implicit listAccessors: collection.mutable.Map[String, String],
methodNames: MethodNames
): String = {
val (_, methodName) = rec(scalaType, lt, "")
methodName + s"""(c.getList("$path"))"""
}
private def rec(lst: ListScalaType, lt: ListType, prefix: String
)(implicit listAccessors: collection.mutable.Map[String, String],
methodNames: MethodNames
): (Boolean, String) = {
val (isBasic, elemMethodName) = lst.st match {
case bst:BaseScalaType ⇒
val basic = lt.t.isInstanceOf[BasicType]
val methodName = baseName(lt.t, bst.toString)
if (basic) {
rootListAccessors += methodName → methodNames.basicElemAccessDefinition(methodName)
rootListAccessors += methodNames.expE → methodNames.expEDef
}
(basic, methodName)
case lst:ListScalaType ⇒
rec(lst, lt.t.asInstanceOf[ListType], prefix + methodNames.listPrefix)
}
val (methodName, methodBody) = listMethodDefinition(elemMethodName, lst.st)
if (isBasic)
rootListAccessors += methodName → methodBody
else
listAccessors += methodName → methodBody
(isBasic, methodName)
}
private def baseName(t: Type, name: String)
(implicit methodNames: MethodNames): String = t match {
case STRING ⇒ methodNames.strA
case INTEGER ⇒ methodNames.intA
case LONG ⇒ methodNames.lngA
case DOUBLE ⇒ methodNames.dblA
case BOOLEAN ⇒ methodNames.blnA
case DURATION(_) ⇒ methodNames.durA
case _: ObjectType ⇒ name.replace('.', '_')
case _: ListType ⇒ throw new AssertionError()
}
def listMethodDefinition(elemMethodName: String, scalaType: ScalaType)
(implicit methodNames: MethodNames): (String, String) = {
val elem = if (elemMethodName.startsWith(methodNames.listPrefix))
s"$elemMethodName(cv.asInstanceOf[com.typesafe.config.ConfigList])"
else if (elemMethodName.startsWith("$"))
s"$elemMethodName(cv)"
else {
val adjusted = elemMethodName.replace("_", ".")
s"$adjusted(cv.asInstanceOf[com.typesafe.config.ConfigObject].toConfig)"
}
val methodName = methodNames.listPrefix + elemMethodName
val methodDef =
s"""
|private def $methodName(cl:com.typesafe.config.ConfigList): scala.List[$scalaType] = {
| import scala.collection.JavaConversions._
| cl.map(cv => $elem).toList
|}""".stripMargin.trim
(methodName, methodDef)
}
}