-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathCodeGen.scala
1396 lines (1286 loc) · 62 KB
/
CodeGen.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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package overflowdb.codegen
import better.files._
import overflowdb.codegen.CodeGen.ConstantContext
import overflowdb.schema._
import overflowdb.storage.ValueTypes
import scala.collection.mutable
/** Generates a domain model for OverflowDb traversals for a given domain-specific schema. */
class CodeGen(schema: Schema) {
import Helpers._
val basePackage = schema.basePackage
val nodesPackage = s"$basePackage.nodes"
val edgesPackage = s"$basePackage.edges"
def run(outputDir: java.io.File): Seq[java.io.File] = {
val _outputDir = outputDir.toScala
val results = writeConstants(_outputDir) ++ writeEdgeFiles(_outputDir) ++ writeNodeFiles(_outputDir) :+ writeNewNodeFile(_outputDir)
println(s"generated ${results.size} files in ${_outputDir}")
results.map(_.toJava)
}
protected def writeConstants(outputDir: File): Seq[File] = {
val results = mutable.Buffer.empty[File]
val baseDir = outputDir / basePackage.replaceAll("\\.", "/")
baseDir.createDirectories()
def writeConstantsFile(className: String, constants: Seq[ConstantContext]): Unit = {
val constantsSource = constants.map { constant =>
val documentation = constant.documentation.filter(_.nonEmpty).map(comment => s"""/** $comment */""").getOrElse("")
s""" $documentation
| ${constant.source}
|""".stripMargin
}.mkString("\n")
val allConstantsSetType = if (constantsSource.contains("PropertyKey")) "PropertyKey" else "String"
val allConstantsBody = constants.map { constant =>
s" add(${constant.name});"
}.mkString("\n").stripSuffix("\n")
val allConstantsSet =
s"""
| public static Set<$allConstantsSetType> ALL = new HashSet<$allConstantsSetType>() {{
|$allConstantsBody
| }};
|""".stripMargin
val file = baseDir.createChild(s"$className.java").write(
s"""package $basePackage;
|
|import overflowdb.*;
|
|import java.util.Collection;
|import java.util.HashSet;
|import java.util.Set;
|
|public class $className {
|
|$constantsSource
|$allConstantsSet
|}""".stripMargin
)
results.append(file)
}
writeConstantsFile("PropertyNames", schema.properties.map { property =>
ConstantContext(property.name, s"""public static final String ${property.name} = "${property.name}";""", property.comment)
})
writeConstantsFile("NodeTypes", schema.nodeTypes.map { nodeType =>
ConstantContext(nodeType.name, s"""public static final String ${nodeType.name} = "${nodeType.name}";""", nodeType.comment)
})
writeConstantsFile("EdgeTypes", schema.edgeTypes.map { edgeType =>
ConstantContext(edgeType.name, s"""public static final String ${edgeType.name} = "${edgeType.name}";""", edgeType.comment)
})
schema.constantsByCategory.foreach { case (category, constants) =>
writeConstantsFile(category, constants.map { constant =>
ConstantContext(constant.name, s"""public static final String ${constant.name} = "${constant.value}";""", constant.comment)
})
}
writeConstantsFile("Properties", schema.properties.map { property =>
val src = {
val valueType = typeFor(property.valueType)
val cardinality = property.cardinality
val completeType = cardinality match {
case Cardinality.One => valueType
case Cardinality.ZeroOrOne => valueType
case Cardinality.List => s"scala.collection.Seq<$valueType>"
case Cardinality.ISeq => s"collection.immutable.IndexedSeq<$valueType>"
}
s"""public static final overflowdb.PropertyKey<$completeType> ${property.name} = new overflowdb.PropertyKey<>("${property.name}");"""
}
ConstantContext(property.name, src, property.comment)
})
results.toSeq
}
protected def writeEdgeFiles(outputDir: File): Seq[File] = {
val staticHeader =
s"""package $edgesPackage
|
|import overflowdb._
|import scala.jdk.CollectionConverters._
|""".stripMargin
val packageObject = {
val factories = {
val edgeFactories = schema.edgeTypes.map(edgeType => edgeType.className + ".factory").mkString(", ")
s"""object Factories {
| lazy val all: List[EdgeFactory[_]] = List($edgeFactories)
| lazy val allAsJava: java.util.List[EdgeFactory[_]] = all.asJava
|}
|""".stripMargin
}
s"""$staticHeader
|$propertyErrorRegisterImpl
|$factories
|""".stripMargin
}
def generateEdgeSource(edgeType: EdgeType, properties: Seq[Property]) = {
val edgeClassName = edgeType.className
val propertyNames = properties.map(_.className)
val propertyNameDefs = properties.map { p =>
s"""val ${p.className} = "${p.name}" """
}.mkString("\n| ")
val propertyDefs = properties.map { p =>
propertyKeyDef(p.name, typeFor(p.valueType), p.cardinality)
}.mkString("\n| ")
val companionObject =
s"""object $edgeClassName {
| val Label = "${edgeType.name}"
|
| object PropertyNames {
| $propertyNameDefs
| val all: Set[String] = Set(${propertyNames.mkString(", ")})
| val allAsJava: java.util.Set[String] = all.asJava
| }
|
| object Properties {
| $propertyDefs
| }
|
| val layoutInformation = new EdgeLayoutInformation(Label, PropertyNames.allAsJava)
|
| val factory = new EdgeFactory[$edgeClassName] {
| override val forLabel = $edgeClassName.Label
|
| override def createEdge(graph: Graph, outNode: NodeRef[NodeDb], inNode: NodeRef[NodeDb]) =
| new $edgeClassName(graph, outNode, inNode)
| }
|}
|""".stripMargin
def propertyBasedFieldAccessors(properties: Seq[Property]): String =
properties.map { property =>
val name = camelCase(property.name)
val tpe = getCompleteType(property)
getHigherType(property.cardinality) match {
case HigherValueType.None =>
s"""def $name: $tpe = property("${property.name}").asInstanceOf[$tpe]"""
case HigherValueType.Option =>
s"""def $name: $tpe = Option(property("${property.name}")).asInstanceOf[$tpe]""".stripMargin
case HigherValueType.List =>
s"""private var _$name: $tpe = Nil
|def $name: $tpe = {
| val p = property("${property.name}")
| if (p != null) p.asInstanceOf[JList].asScala
| else Nil
|}""".stripMargin
}
}.mkString("\n\n")
val classImpl =
s"""class $edgeClassName(_graph: Graph, _outNode: NodeRef[NodeDb], _inNode: NodeRef[NodeDb])
|extends Edge(_graph, $edgeClassName.Label, _outNode, _inNode, $edgeClassName.PropertyNames.allAsJava) {
|${propertyBasedFieldAccessors(properties)}
|}
|""".stripMargin
s"""$staticHeader
|$companionObject
|$classImpl
|""".stripMargin
}
val baseDir = outputDir / edgesPackage.replaceAll("\\.", "/")
if (baseDir.exists) baseDir.delete()
baseDir.createDirectories()
val pkgObjFile = baseDir.createChild("package.scala").write(packageObject)
val edgeTypeFiles = schema.edgeTypes.map { edge =>
val src = generateEdgeSource(edge, edge.properties)
val srcFile = edge.className + ".scala"
baseDir.createChild(srcFile).write(src)
}
pkgObjFile +: edgeTypeFiles
}
protected def neighborAccessorNameForEdge(edge: EdgeType, direction: Direction.Value): String =
"_" + camelCase(edge.name + "_" + direction)
protected def writeNodeFiles(outputDir: File): Seq[File] = {
val rootTypeImpl = {
val genericNeighborAccessors = for {
direction <- Direction.all
edgeType <- schema.edgeTypes
accessor = neighborAccessorNameForEdge(edgeType, direction)
} yield s"def $accessor: java.util.Iterator[StoredNode] = { java.util.Collections.emptyIterator() }"
val factories = {
val nodeFactories =
schema.nodeTypes.map(nodeType => nodeType.className + ".factory").mkString(", ")
s"""object Factories {
| lazy val all: Seq[NodeFactory[_]] = Seq($nodeFactories)
| lazy val allAsJava: java.util.List[NodeFactory[_]] = all.asJava
|}
|""".stripMargin
}
val reChars = "[](){}*+&|?.,\\\\$"
s"""package $nodesPackage
|
|import overflowdb._
|import scala.jdk.CollectionConverters._
|
|$propertyErrorRegisterImpl
|
|object Misc {
| val reChars = "$reChars"
| def isRegex(pattern: String): Boolean = pattern.exists(reChars.contains(_))
|}
|
|trait CpgNode {
| def label: String
|}
|
|/* A node that is stored inside an Graph (rather than e.g. DiffGraph) */
|trait StoredNode extends Node with CpgNode with Product {
| /* underlying Node in the graph.
| * since this is a StoredNode, this is always set */
| def underlying: Node = this
|
| /** labels of product elements, used e.g. for pretty-printing */
| def productElementLabel(n: Int): String
|
| /* all properties plus label and id */
| def toMap: Map[String, Any] = {
| val map = valueMap
| map.put("_label", label)
| map.put("_id", id: java.lang.Long)
| map.asScala.toMap
| }
|
| /*Sets fields from newNode*/
| def fromNewNode(newNode: NewNode, mapping: NewNode => StoredNode):Unit = ???
|
| /* all properties */
| def valueMap: java.util.Map[String, AnyRef]
|
| ${genericNeighborAccessors.mkString("\n")}
|}
|
| $factories
|""".stripMargin
}
val staticHeader =
s"""package $nodesPackage
|
|import overflowdb._
|import overflowdb.traversal.Traversal
|import scala.jdk.CollectionConverters._
|""".stripMargin
lazy val nodeTraversalImplicits = {
def implicitForNodeType(name: String) = {
val traversalName = s"${name}Traversal"
s"implicit def to$traversalName[NodeType <: $name](trav: Traversal[NodeType]): ${traversalName}[NodeType] = new $traversalName(trav)"
}
def implicitForNewNodeBuilder(name : String) = {
val newNodeName = s"New${name}"
val newNodeBuilderName = s"${newNodeName}Builder"
s"implicit def ${newNodeBuilderName}To${newNodeName}(x : $newNodeBuilderName) : $newNodeName = x.build"
}
val implicitsForNodeTraversals =
schema.nodeTypes.map(_.className).sorted.map(implicitForNodeType).mkString("\n")
val implicitsForNodeBaseTypeTraversals =
schema.nodeBaseTypes.map(_.className).sorted.map(implicitForNodeType).mkString("\n")
val nonBaseTypes = (schema.nodeTypes.map(_.className).toSet -- schema.nodeBaseTypes.map(_.className).toSet).toList.sorted
val implicitsForNewNodeBuilders =
nonBaseTypes.map(implicitForNewNodeBuilder).mkString("\n")
s"""package $nodesPackage
|
|import overflowdb.traversal.Traversal
|
|trait NodeTraversalImplicits extends NodeBaseTypeTraversalImplicits {
| $implicitsForNodeTraversals
|
| $implicitsForNewNodeBuilders
|}
|
|// lower priority implicits for base types
|trait NodeBaseTypeTraversalImplicits {
| $implicitsForNodeBaseTypeTraversals
|}
|""".stripMargin
}
def generatePropertyTraversals(className: String, properties: Seq[Property]): String = {
val propertyTraversals = properties.map { property =>
val nameCamelCase = camelCase(property.name)
val baseType = typeFor(property.valueType)
val cardinality = property.cardinality
val mapOrFlatMap = cardinality match {
case Cardinality.One => "map"
case Cardinality.ZeroOrOne | Cardinality.List | Cardinality.ISeq => "flatMap"
}
def filterStepsForSingleString(propertyName: String) =
s""" /**
| * Traverse to nodes where the $nameCamelCase matches the regular expression `value`
| * */
| def $nameCamelCase(pattern: $baseType): Traversal[NodeType] = {
| if(!Misc.isRegex(pattern)){
| traversal.filter{node => node.${nameCamelCase} == pattern}
| } else {
| val matcher = java.util.regex.Pattern.compile(pattern).matcher("")
| traversal.filter{node => matcher.reset(node.$nameCamelCase); matcher.matches()}
| }
| }
|
| /**
| * Traverse to nodes where the $nameCamelCase matches at least one of the regular expressions in `values`
| * */
| def $nameCamelCase(patterns: $baseType*): Traversal[NodeType] = {
| val matchers = patterns.map{pattern => java.util.regex.Pattern.compile(pattern).matcher("")}.toArray
| traversal.filter{node => matchers.exists{ matcher => matcher.reset(node.$nameCamelCase); matcher.matches()}}
| }
|
| /**
| * Traverse to nodes where $nameCamelCase matches `value` exactly.
| * */
| def ${nameCamelCase}Exact(value: $baseType): Traversal[NodeType] =
| traversal.filter{node => node.${nameCamelCase} == value}
|
| /**
| * Traverse to nodes where $nameCamelCase matches one of the elements in `values` exactly.
| * */
| def ${nameCamelCase}Exact(values: $baseType*): Traversal[NodeType] = {
| val vset = values.to(Set)
| traversal.filter{node => vset.contains(node.${nameCamelCase})}
| }
|
| /**
| * Traverse to nodes where $nameCamelCase does not match the regular expression `value`.
| * */
| def ${nameCamelCase}Not(pattern: $baseType): Traversal[NodeType] = {
| if(!Misc.isRegex(pattern)){
| traversal.filter{node => node.${nameCamelCase} != pattern}
| } else {
| val matcher = java.util.regex.Pattern.compile(pattern).matcher("")
| traversal.filter{node => matcher.reset(node.$nameCamelCase); !matcher.matches()}
| }
| }
|
| /**
| * Traverse to nodes where $nameCamelCase does not match any of the regular expressions in `values`.
| * */
| def ${nameCamelCase}Not(patterns: $baseType*): Traversal[NodeType] = {
| val matchers = patterns.map{pattern => java.util.regex.Pattern.compile(pattern).matcher("")}.toArray
| traversal.filter{node => !matchers.exists{ matcher => matcher.reset(node.$nameCamelCase); matcher.matches()}}
| }
|
|""".stripMargin
def filterStepsForOptionalString(propertyName: String) =
s""" /**
| * Traverse to nodes where the $nameCamelCase matches the regular expression `value`
| * */
| def $nameCamelCase(pattern: $baseType): Traversal[NodeType] = {
| if(!Misc.isRegex(pattern)){
| traversal.filter{node => node.$nameCamelCase.isDefined && node.${nameCamelCase}.get == pattern}
| } else {
| val matcher = java.util.regex.Pattern.compile(pattern).matcher("")
| traversal.filter{node => node.$nameCamelCase.isDefined && {matcher.reset(node.$nameCamelCase.get); matcher.matches()}}
| }
| }
|
| /**
| * Traverse to nodes where the $nameCamelCase matches at least one of the regular expressions in `values`
| * */
| def $nameCamelCase(patterns: $baseType*): Traversal[NodeType] = {
| val matchers = patterns.map{pattern => java.util.regex.Pattern.compile(pattern).matcher("")}.toArray
| traversal.filter{node => node.$nameCamelCase.isDefined && matchers.exists{ matcher => matcher.reset(node.$nameCamelCase.get); matcher.matches()}}
| }
|
| /**
| * Traverse to nodes where $nameCamelCase matches `value` exactly.
| * */
| def ${nameCamelCase}Exact(value: $baseType): Traversal[NodeType] =
| traversal.filter{node => node.$nameCamelCase.isDefined && node.${nameCamelCase}.get == value}
|
| /**
| * Traverse to nodes where $nameCamelCase matches one of the elements in `values` exactly.
| * */
| def ${nameCamelCase}Exact(values: $baseType*): Traversal[NodeType] = {
| val vset = values.to(Set)
| traversal.filter{node => node.$nameCamelCase.isDefined && vset.contains(node.${nameCamelCase}.get)}
| }
|
| /**
| * Traverse to nodes where $nameCamelCase does not match the regular expression `value`.
| * */
| def ${nameCamelCase}Not(pattern: $baseType): Traversal[NodeType] = {
| if(!Misc.isRegex(pattern)){
| traversal.filter{node => node.$nameCamelCase.isEmpty || node.${nameCamelCase}.get != pattern}
| } else {
| val matcher = java.util.regex.Pattern.compile(pattern).matcher("")
| traversal.filter{node => node.$nameCamelCase.isEmpty || {matcher.reset(node.$nameCamelCase.get); !matcher.matches()}}
| }
| }
|
| /**
| * Traverse to nodes where $nameCamelCase does not match any of the regular expressions in `values`.
| * */
| def ${nameCamelCase}Not(patterns: $baseType*): Traversal[NodeType] = {
| val matchers = patterns.map{pattern => java.util.regex.Pattern.compile(pattern).matcher("")}.toArray
| traversal.filter{node => node.$nameCamelCase.isEmpty || !matchers.exists{ matcher => matcher.reset(node.$nameCamelCase.get); matcher.matches()}}
| }
|
|""".stripMargin
def filterStepsForSingleBoolean(propertyName: String) =
s""" /**
| * Traverse to nodes where the $nameCamelCase equals the given `value`
| * */
| def $nameCamelCase(value: $baseType): Traversal[NodeType] =
| traversal.filter{_.$nameCamelCase == value}
|
| /**
| * Traverse to nodes where $nameCamelCase is not equal to the given `value`.
| * */
| def ${nameCamelCase}Not(value: $baseType): Traversal[NodeType] =
| traversal.filter{_.$nameCamelCase != value}
|""".stripMargin
def filterStepsForOptionalBoolean(propertyName: String) =
s""" /**
| * Traverse to nodes where the $nameCamelCase equals the given `value`
| * */
| def $nameCamelCase(value: $baseType): Traversal[NodeType] =
| traversal.filter{node => node.${nameCamelCase}.isDefined && node.$nameCamelCase.get == value}
|
| /**
| * Traverse to nodes where $nameCamelCase is not equal to the given `value`.
| * */
| def ${nameCamelCase}Not(value: $baseType): Traversal[NodeType] =
| traversal.filter{node => !node.${nameCamelCase}.isDefined || node.$nameCamelCase.get == value}
|""".stripMargin
def filterStepsForSingleInt(propertyName: String) =
s""" /**
| * Traverse to nodes where the $nameCamelCase equals the given `value`
| * */
| def $nameCamelCase(value: $baseType): Traversal[NodeType] =
| traversal.filter{_.$nameCamelCase == value}
|
| /**
| * Traverse to nodes where the $nameCamelCase equals at least one of the given `values`
| * */
| def $nameCamelCase(values: $baseType*): Traversal[NodeType] = {
| val vset = values.toSet
| traversal.filter{node => vset.contains(node.$nameCamelCase)}
| }
|
| /**
| * Traverse to nodes where the $nameCamelCase is greater than the given `value`
| * */
| def ${nameCamelCase}Gt(value: $baseType): Traversal[NodeType] =
| traversal.filter{_.$nameCamelCase > value}
|
| /**
| * Traverse to nodes where the $nameCamelCase is greater than or equal the given `value`
| * */
| def ${nameCamelCase}Gte(value: $baseType): Traversal[NodeType] =
| traversal.filter{_.$nameCamelCase >= value}
|
| /**
| * Traverse to nodes where the $nameCamelCase is less than the given `value`
| * */
| def ${nameCamelCase}Lt(value: $baseType): Traversal[NodeType] =
| traversal.filter{_.$nameCamelCase < value}
|
| /**
| * Traverse to nodes where the $nameCamelCase is less than or equal the given `value`
| * */
| def ${nameCamelCase}Lte(value: $baseType): Traversal[NodeType] =
| traversal.filter{_.$nameCamelCase <= value}
|
| /**
| * Traverse to nodes where $nameCamelCase is not equal to the given `value`.
| * */
| def ${nameCamelCase}Not(value: $baseType): Traversal[NodeType] =
| traversal.filter{_.$nameCamelCase != value}
|
| /**
| * Traverse to nodes where $nameCamelCase is not equal to any of the given `values`.
| * */
| def ${nameCamelCase}Not(values: $baseType*): Traversal[NodeType] = {
| val vset = values.toSet
| traversal.filter{node => !vset.contains(node.$nameCamelCase)}
| }
|""".stripMargin
def filterStepsForOptionalInt(propertyName: String) =
s""" /**
| * Traverse to nodes where the $nameCamelCase equals the given `value`
| * */
| def $nameCamelCase(value: $baseType): Traversal[NodeType] =
| traversal.filter{node => node.$nameCamelCase.isDefined && node.$nameCamelCase.get == value}
|
| /**
| * Traverse to nodes where the $nameCamelCase equals at least one of the given `values`
| * */
| def $nameCamelCase(values: $baseType*): Traversal[NodeType] = {
| val vset = values.toSet
| traversal.filter{node => node.$nameCamelCase.isDefined && vset.contains(node.$nameCamelCase.get)}
| }
|
| /**
| * Traverse to nodes where the $nameCamelCase is greater than the given `value`
| * */
| def ${nameCamelCase}Gt(value: $baseType): Traversal[NodeType] =
| traversal.filter{node => node.$nameCamelCase.isDefined && node.$nameCamelCase.get > value}
|
| /**
| * Traverse to nodes where the $nameCamelCase is greater than or equal the given `value`
| * */
| def ${nameCamelCase}Gte(value: $baseType): Traversal[NodeType] =
| traversal.filter{node => node.$nameCamelCase.isDefined && node.$nameCamelCase.get >= value}
|
| /**
| * Traverse to nodes where the $nameCamelCase is less than the given `value`
| * */
| def ${nameCamelCase}Lt(value: $baseType): Traversal[NodeType] =
| traversal.filter{node => node.$nameCamelCase.isDefined && node.$nameCamelCase.get < value}
|
| /**
| * Traverse to nodes where the $nameCamelCase is less than or equal the given `value`
| * */
| def ${nameCamelCase}Lte(value: $baseType): Traversal[NodeType] =
| traversal.filter{node => node.$nameCamelCase.isDefined && node.$nameCamelCase.get <= value}
|
| /**
| * Traverse to nodes where $nameCamelCase is not equal to the given `value`.
| * */
| def ${nameCamelCase}Not(value: $baseType): Traversal[NodeType] =
| traversal.filter{node => !node.$nameCamelCase.isDefined || node.$nameCamelCase.get != value}
|
| /**
| * Traverse to nodes where $nameCamelCase is not equal to any of the given `values`.
| * */
| def ${nameCamelCase}Not(values: $baseType*): Traversal[NodeType] = {
| val vset = values.toSet
| traversal.filter{node => !node.$nameCamelCase.isDefined || !vset.contains(node.$nameCamelCase.get)}
| }
|""".stripMargin
def filterStepsGenericSingle(propertyName: String) =
s""" /**
| * Traverse to nodes where the $nameCamelCase equals the given `value`
| * */
| def $nameCamelCase(value: $baseType): Traversal[NodeType] =
| traversal.filter{_.$nameCamelCase == value}
|
| /**
| * Traverse to nodes where the $nameCamelCase equals at least one of the given `values`
| * */
| def $nameCamelCase(values: $baseType*): Traversal[NodeType] = {
| val vset = values.toSet
| traversal.filter{node => !vset.contains(node.$nameCamelCase)}
| }
|
| /**
| * Traverse to nodes where $nameCamelCase is not equal to the given `value`.
| * */
| def ${nameCamelCase}Not(value: $baseType): Traversal[NodeType] =
| traversal.filter{_.$nameCamelCase != value}
|
| /**
| * Traverse to nodes where $nameCamelCase is not equal to any of the given `values`.
| * */
| def ${nameCamelCase}Not(values: $baseType*): Traversal[NodeType] = {
| val vset = values.toSet
| traversal.filter{node => !vset.contains(node.$nameCamelCase)}
| }
|""".stripMargin
def filterStepsGenericOption(propertyName: String) =
s""" /**
| * Traverse to nodes where the $nameCamelCase equals the given `value`
| * */
| def $nameCamelCase(value: $baseType): Traversal[NodeType] =
| traversal.filter{node => node.$nameCamelCase.isDefined && node.$nameCamelCase.get == value}
|
| /**
| * Traverse to nodes where the $nameCamelCase equals at least one of the given `values`
| * */
| def $nameCamelCase(values: $baseType*): Traversal[NodeType] = {
| val vset = values.toSet
| traversal.filter{node => node.$nameCamelCase.isDefined && !vset.contains(node.$nameCamelCase.get)}
| }
|
| /**
| * Traverse to nodes where $nameCamelCase is not equal to the given `value`.
| * */
| def ${nameCamelCase}Not(value: $baseType): Traversal[NodeType] =
| traversal.filter{node => !node.$nameCamelCase.isDefined || node.$nameCamelCase.get != value}
|
| /**
| * Traverse to nodes where $nameCamelCase is not equal to any of the given `values`.
| * */
| def ${nameCamelCase}Not(values: $baseType*): Traversal[NodeType] = {
| val vset = values.toSet
| traversal.filter{node => !node.$nameCamelCase.isDefined || !vset.contains(node.$nameCamelCase.get)}
| }
|""".stripMargin
val filterSteps = (cardinality, property.valueType) match {
case (Cardinality.List | Cardinality.ISeq, _) => ""
case (Cardinality.One, ValueTypes.STRING) => filterStepsForSingleString(property.name)
case (Cardinality.ZeroOrOne, ValueTypes.STRING) => filterStepsForOptionalString(property.name)
case (Cardinality.One, ValueTypes.BOOLEAN) => filterStepsForSingleBoolean(property.name)
case (Cardinality.ZeroOrOne, ValueTypes.BOOLEAN) => filterStepsForOptionalBoolean(property.name)
case (Cardinality.One, ValueTypes.INTEGER) => filterStepsForSingleInt(property.name)
case (Cardinality.ZeroOrOne, ValueTypes.INTEGER) => filterStepsForOptionalInt(property.name)
case (Cardinality.One, _) => filterStepsGenericSingle(property.name)
case (Cardinality.ZeroOrOne, _) => filterStepsGenericOption(property.name)
case _ => ""
}
s""" /** Traverse to $nameCamelCase property */
| def $nameCamelCase: Traversal[$baseType] =
| traversal.$mapOrFlatMap(_.$nameCamelCase)
|
| $filterSteps
|""".stripMargin
}.mkString("\n")
s"""
|/** Traversal steps for $className */
|class ${className}Traversal[NodeType <: $className](val traversal: Traversal[NodeType]) extends AnyVal {
|
|$propertyTraversals
|
|}""".stripMargin
}
def generateNodeBaseTypeSource(nodeBaseTrait: NodeBaseType): String = {
val className = nodeBaseTrait.className
val properties = nodeBaseTrait.properties
val mixins = nodeBaseTrait.properties.map { property =>
s"with Has${property.className}"
}.mkString(" ")
val mixinTraits = nodeBaseTrait.extendz.map { baseTrait =>
s"with ${baseTrait.className}"
}.mkString(" ")
val mixinTraitsForBase = nodeBaseTrait.extendz.map { baseTrait =>
s"with ${baseTrait.className}Base"
}.mkString(" ")
s"""package $nodesPackage
|
|import overflowdb.traversal.Traversal
|
|trait ${className}Base extends CpgNode
|$mixins
|$mixinTraitsForBase
|
|trait $className extends StoredNode with ${className}Base
|$mixinTraits
|
|${generatePropertyTraversals(className, properties)}
|
|""".stripMargin
}
def generateNodeSource(nodeType: NodeType) = {
val properties = nodeType.properties
val propertyNames = nodeType.properties.map(_.name) ++ nodeType.containedNodes.map(_.localName)
val propertyNameDefs = propertyNames.map { name =>
s"""val ${camelCaseCaps(name)} = "$name" """
}.mkString("\n| ")
val propertyDefs = properties.map { p =>
propertyKeyDef(p.name, typeFor(p.valueType), p.cardinality)
}.mkString("\n| ")
val propertyDefsForContainedNodes = nodeType.containedNodes.map { containedNode =>
propertyKeyDef(containedNode.localName, containedNode.nodeType.className, containedNode.cardinality)
}.mkString("\n| ")
val (neighborOutInfos, neighborInInfos) = {
/** the offsetPos determines the index into the adjacent nodes array of a given node type
* assigning numbers here must follow the same way as in NodeLayoutInformation, i.e. starting at 0,
* first assign ids to the outEdges based on their order in the list, and then the same for inEdges */
var _currOffsetPos = -1
def nextOffsetPos = { _currOffsetPos += 1; _currOffsetPos }
def createNeighborNodeInfo(nodeName: String, neighborClassName: String, edgeAndDirection: String, cardinality: Cardinality) = {
val accessorName = s"_${camelCase(nodeName)}Via${edgeAndDirection.capitalize}"
NeighborNodeInfo(Helpers.escapeIfKeyword(accessorName), neighborClassName, cardinality)
}
val neighborOutInfos =
nodeType.outEdges.groupBy(_.viaEdge).map { case (edge, outEdges) =>
val viaEdgeAndDirection = edge.className + "Out"
val neighborNodeInfos = outEdges.map { case AdjacentNode(_, inNode, cardinality) =>
createNeighborNodeInfo(inNode.name, inNode.className, viaEdgeAndDirection, cardinality)
}
NeighborInfo(edge, neighborNodeInfos, nextOffsetPos)
}.toSeq
val neighborInInfos =
nodeType.inEdges.groupBy(_.viaEdge).map { case (edge, inEdges) =>
val viaEdgeAndDirection = edge.className + "In"
val neighborNodeInfos = inEdges.map { case AdjacentNode(_, outNode, cardinality) =>
createNeighborNodeInfo(outNode.name, outNode.className, viaEdgeAndDirection, cardinality)
}
NeighborInfo(edge, neighborNodeInfos, nextOffsetPos)
}.toSeq
(neighborOutInfos, neighborInInfos)
}
val neighborInfos: Seq[(NeighborInfo, Direction.Value)] =
neighborOutInfos.map((_, Direction.OUT)) ++ neighborInInfos.map((_, Direction.IN))
def toLayoutInformationEntry(neighborInfos: Seq[NeighborInfo]): String = {
neighborInfos.sortBy(_.offsetPosition).map { neighborInfo =>
val edgeClass = neighborInfo.edge.className
s"$edgesPackage.$edgeClass.layoutInformation"
}.mkString(",\n")
}
val List(outEdgeLayouts, inEdgeLayouts) = List(neighborOutInfos, neighborInInfos).map(toLayoutInformationEntry)
val className = nodeType.className
val classNameDb = nodeType.classNameDb
val companionObject =
s"""object $className {
| def apply(graph: Graph, id: Long) = new $className(graph, id)
|
| val Label = "${nodeType.name}"
|
| object PropertyNames {
| $propertyNameDefs
| val all: Set[String] = Set(${propertyNames.map(camelCaseCaps).mkString(", ")})
| val allAsJava: java.util.Set[String] = all.asJava
| }
|
| object Properties {
| $propertyDefs
| $propertyDefsForContainedNodes
| }
|
| val layoutInformation = new NodeLayoutInformation(
| Label,
| PropertyNames.allAsJava,
| List($outEdgeLayouts).asJava,
| List($inEdgeLayouts).asJava)
|
|
| object Edges {
| val Out: Array[String] = Array(${quoted(neighborOutInfos.map(_.edge.name).sorted).mkString(",")})
| val In: Array[String] = Array(${quoted(neighborInInfos.map(_.edge.name).sorted).mkString(",")})
| }
|
| val factory = new NodeFactory[$classNameDb] {
| override val forLabel = $className.Label
|
| override def createNode(ref: NodeRef[$classNameDb]) =
| new $classNameDb(ref.asInstanceOf[NodeRef[NodeDb]])
|
| override def createNodeRef(graph: Graph, id: Long) = $className(graph, id)
| }
|}
|""".stripMargin
val mixinTraits: String =
nodeType.extendz
.map { traitName =>
s"with ${traitName.className}"
}
.mkString(" ")
val mixinTraitsForBase: String =
nodeType.extendz
.map { traitName =>
s"with ${traitName.className}Base"
}
.mkString(" ")
val propertyBasedTraits = properties.map(p => s"with Has${p.className}").mkString(" ")
val valueMapImpl = {
val putKeysImpl = properties
.map { key: Property =>
val memberName = camelCase(key.name)
key.cardinality match {
case Cardinality.One =>
s"""if ($memberName != null) { properties.put("${key.name}", $memberName) }"""
case Cardinality.ZeroOrOne =>
s"""$memberName.map { value => properties.put("${key.name}", value) }"""
case Cardinality.List | Cardinality.ISeq => // need java list, e.g. for NodeSerializer
s"""if (this._$memberName != null && this._$memberName.nonEmpty) { properties.put("${key.name}", $memberName.asJava) }"""
}
}
.mkString("\n")
val putRefsImpl = {
nodeType.containedNodes.map { cnt =>
val memberName = cnt.localName
cnt.cardinality match {
case Cardinality.One =>
s""" if (this._$memberName != null) { properties.put("${memberName}", this._$memberName) }"""
case Cardinality.ZeroOrOne =>
s""" if (this._$memberName != null && this._$memberName.nonEmpty) { properties.put("${memberName}", this._$memberName.get) }"""
case Cardinality.List | Cardinality.ISeq => // need java list, e.g. for NodeSerializer
s""" if (this._$memberName != null && this._$memberName.nonEmpty) { properties.put("${memberName}", this.$memberName.asJava) }"""
}
}
}.mkString("\n")
s""" {
| val properties = new java.util.HashMap[String, AnyRef]
|$putKeysImpl
|$putRefsImpl
| properties
|}""".stripMargin
}
val fromNew = {
val initKeysImpl = properties
.map { key: Property =>
val memberName = camelCase(key.name)
key.cardinality match {
case Cardinality.One =>
s""" this._$memberName = other.$memberName""".stripMargin
case Cardinality.ZeroOrOne =>
s""" this._$memberName = if(other.$memberName != null) other.$memberName else None""".stripMargin
case Cardinality.List =>
s""" this._$memberName = if(other.$memberName != null) other.$memberName else Nil""".stripMargin
case Cardinality.ISeq => ???
}
}
.mkString("\n")
val initRefsImpl = {
nodeType.containedNodes.map { containedNode =>
val memberName = containedNode.localName
val containedNodeType = containedNode.nodeType.className
containedNode.cardinality match {
case Cardinality.One =>
s""" this._$memberName = other.$memberName match {
| case null => null
| case newNode: NewNode => mapping(newNode).asInstanceOf[$containedNodeType]
| case oldNode: StoredNode => oldNode.asInstanceOf[$containedNodeType]
| case _ => throw new MatchError("unreachable")
| }""".stripMargin
case Cardinality.ZeroOrOne =>
s""" this._$memberName = other.$memberName match {
| case null | None => None
| case Some(newNode:NewNode) => Some(mapping(newNode).asInstanceOf[$containedNodeType])
| case Some(oldNode:StoredNode) => Some(oldNode.asInstanceOf[$containedNodeType])
| case _ => throw new MatchError("unreachable")
| }""".stripMargin
case Cardinality.List => // need java list, e.g. for NodeSerializer
s""" this._$memberName = if(other.$memberName == null) Nil else other.$memberName.map { nodeRef => nodeRef match {
| case null => throw new NullPointerException("Nullpointers forbidden in contained nodes")
| case newNode:NewNode => mapping(newNode).asInstanceOf[$containedNodeType]
| case oldNode:StoredNode => oldNode.asInstanceOf[$containedNodeType]
| case _ => throw new MatchError("unreachable")
| }}""".stripMargin
case Cardinality.ISeq =>
s"""{
| val arr = if(other.$memberName == null || other.$memberName.isEmpty) null
| else other.$memberName.map { nodeRef => nodeRef match {
| case null => throw new NullPointerException("Nullpointers forbidden in contained nodes")
| case newNode:NewNode => mapping(newNode).asInstanceOf[$containedNodeType]
| case oldNode:StoredNode => oldNode.asInstanceOf[$containedNodeType]
| case _ => throw new MatchError("unreachable")
| }}.toArray
|
| this._$memberName = if(arr == null) collection.immutable.ArraySeq.empty
| else collection.immutable.ArraySeq.unsafeWrapArray(arr)
|}""".stripMargin
}
}
}.mkString("\n\n")
val registerFullName = if(!properties.map{_.name}.contains("FULL_NAME")) "" else {
s""" graph.indexManager.putIfIndexed("FULL_NAME", other.fullName, this.ref)"""
}
s"""override def fromNewNode(someNewNode: NewNode, mapping: NewNode => StoredNode):Unit = {
| //this will throw for bad types -- no need to check by hand, we don't have a better error message
| val other = someNewNode.asInstanceOf[New${nodeType.className}]
|$initKeysImpl
|$initRefsImpl
|$registerFullName
|}""".stripMargin
}
val containedNodesAsMembers =
nodeType.containedNodes
.map { containedNode =>
val containedNodeType = containedNode.nodeType.className
containedNode.cardinality match {
case Cardinality.One =>
s"""
|private var _${containedNode.localName}: $containedNodeType = null
|def ${containedNode.localName}: $containedNodeType = this._${containedNode.localName}
|""".stripMargin
case Cardinality.ZeroOrOne =>
s"""
|private var _${containedNode.localName}: Option[$containedNodeType] = None
|def ${containedNode.localName}: Option[$containedNodeType] = this._${containedNode.localName}
|""".stripMargin
case Cardinality.List =>
s"""
|private var _${containedNode.localName}: Seq[$containedNodeType] = Seq.empty
|def ${containedNode.localName}: Seq[$containedNodeType] = this._${containedNode.localName}
|""".stripMargin
case Cardinality.ISeq =>
s"""
|private var _${containedNode.localName}: collection.immutable.ArraySeq[$containedNodeType] = collection.immutable.ArraySeq.empty
|def ${containedNode.localName}: collection.immutable.IndexedSeq[$containedNodeType] = this._${containedNode.localName}
|""".stripMargin
}
}
.mkString("\n")
val productElements: Seq[ProductElement] = {
var currIndex = -1
def nextIdx = { currIndex += 1; currIndex }
val forId = ProductElement("id", "id", nextIdx)
val forKeys = properties.map { key =>
val name = camelCase(key.name)
ProductElement(name, name, nextIdx)
}
val forContainedNodes = nodeType.containedNodes.map { containedNode =>
ProductElement(
containedNode.localName,
containedNode.localName,
nextIdx)
}
forId +: (forKeys ++ forContainedNodes)
}
val productElementLabels =
productElements.map { case ProductElement(name, accessorSrc, index) =>
s"""case $index => "$name" """
}.mkString("\n")
val productElementAccessors =
productElements.map { case ProductElement(name, accessorSrc, index) =>
s"case $index => $accessorSrc"
}.mkString("\n")
val abstractContainedNodeAccessors = nodeType.containedNodes.map { containedNode =>
s"""def ${containedNode.localName}: ${getCompleteType(containedNode)}"""
}.mkString("\n")
val delegatingContainedNodeAccessors = nodeType.containedNodes.map { containedNode =>
containedNode.cardinality match {
case Cardinality.One =>
s""" def ${containedNode.localName}: ${containedNode.nodeType.className} = get().${containedNode.localName}"""
case Cardinality.ZeroOrOne =>
s""" def ${containedNode.localName}: Option[${containedNode.nodeType.className}] = get().${containedNode.localName}"""
case Cardinality.List =>
s""" def ${containedNode.localName}: Seq[${containedNode.nodeType.className}] = get().${containedNode.localName}"""
case Cardinality.ISeq =>
s""" def ${containedNode.localName}: collection.immutable.IndexedSeq[${containedNode.nodeType.className}] = get().${containedNode.localName}"""
}
}.mkString("\n")