-
Notifications
You must be signed in to change notification settings - Fork 11
/
Processing.kt
572 lines (521 loc) · 19.8 KB
/
Processing.kt
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
@file:JvmName("Processing")
package com.strumenta.kolasu.model
import org.antlr.v4.runtime.ParserRuleContext
import java.util.*
import kotlin.reflect.*
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.full.isSubclassOf
import kotlin.reflect.full.memberProperties
import kotlin.reflect.full.primaryConstructor
val <T : Any> Class<T>.nodeProperties: Collection<KProperty1<T, *>>
get() = this.kotlin.nodeProperties
val <T : Any> KClass<T>.nodeProperties: Collection<KProperty1<T, *>>
get() = memberProperties
.filter { it.visibility == KVisibility.PUBLIC }
.filter { it.findAnnotation<Derived>() == null }
.filter { it.findAnnotation<Link>() == null }
.filter { it.name != "parent" }
.filter { it.name != "position" }
.filter { it.name != "specifiedPosition" }
.filter { it.name != "parseTreeNode" }
/**
* @return all properties of this node that are considered AST properties.
*/
val <T : Node> T.nodeProperties: Collection<KProperty1<T, *>>
get() = this.javaClass.nodeProperties
/**
* Sets or corrects the parent of all AST nodes.
* Kolasu does not see set/add/delete operations on the AST nodes,
* so this function should be called manually after modifying the AST.
*/
fun Node.assignParents() {
this.walkChildren().forEach {
if (it == this) {
throw java.lang.IllegalStateException("A node cannot be parent of itself: $this")
}
it.parent = this
it.assignParents()
}
}
/**
* Recursively execute [operation] on [this] node, and all nodes below this node.
* @param walker the function that generates the nodes to operate on in the desired sequence.
*/
fun Node.processNodes(operation: (Node) -> Unit, walker: KFunction1<Node, Sequence<Node>> = Node::walk) {
walker.invoke(this).forEach(operation)
}
fun Node.invalidPositions(): Sequence<Node> = this.walk().filter {
it.position == null || run {
val parentPos = it.parent?.position
// If the parent position is null, we can't say anything about this node's position
(parentPos != null && !(parentPos.contains(it.position!!.start) && parentPos.contains(it.position!!.end)))
}
}
fun Node.findInvalidPosition(): Node? = this.invalidPositions().firstOrNull()
fun <T : Node> T.withParseTreeNode(tree: ParserRuleContext?): T {
this.parseTreeNode = tree
return this
}
fun <T : Node> T.withParent(parent: Node?): T {
this.parent = parent
return this
}
private fun providesNodes(kTypeProjection: KTypeProjection): Boolean {
val ktype = kTypeProjection.type
return when (ktype) {
is KClass<*> -> providesNodes(ktype as? KClass<*>)
is KType -> providesNodes((ktype as? KType)?.classifier)
else -> throw UnsupportedOperationException(
"We are not able to determine if the type $ktype provides AST Nodes or not"
)
}
}
private fun providesNodes(classifier: KClassifier?): Boolean {
if (classifier == null) {
return false
}
if (classifier is KClass<*>) {
return providesNodes(classifier as? KClass<*>)
} else {
throw UnsupportedOperationException(
"We are not able to determine if the classifier $classifier provides AST Nodes or not"
)
}
}
private fun providesNodes(kclass: KClass<*>?): Boolean {
return kclass?.isANode() ?: false
}
/**
* @return can [this] class be considered an AST node?
*/
fun KClass<*>.isANode(): Boolean {
return this.isSubclassOf(Node::class) || this.isMarkedAsNodeType()
}
/**
* @return is [this] class annotated with NodeType?
*/
fun KClass<*>.isMarkedAsNodeType(): Boolean {
return this.annotations.any { it.annotationClass == NodeType::class }
}
data class PropertyTypeDescription(
val name: String,
val provideNodes: Boolean,
val multiple: Boolean,
val valueType: KType
) {
companion object {
fun buildFor(property: KProperty1<*, *>): PropertyTypeDescription {
val propertyType = property.returnType
val classifier = propertyType.classifier as? KClass<*>
val multiple = (classifier?.isSubclassOf(Collection::class) == true)
var valueType: KType
val provideNodes = if (multiple) {
valueType = propertyType.arguments[0].type!!
providesNodes(propertyType.arguments[0])
} else {
valueType = propertyType
providesNodes(classifier)
}
return PropertyTypeDescription(
name = property.name,
provideNodes = provideNodes,
multiple = multiple,
valueType = valueType
)
}
}
}
enum class Multeplicity {
OPTIONAL,
SINGULAR,
MANY
}
data class PropertyDescription(
val name: String,
val provideNodes: Boolean,
val multeplicity: Multeplicity,
val value: Any?
) {
val multiple: Boolean
get() = multeplicity == Multeplicity.MANY
companion object {
fun multiple(property: KProperty1<in Node, *>): Boolean {
val propertyType = property.returnType
val classifier = propertyType.classifier as? KClass<*>
return (classifier?.isSubclassOf(Collection::class) == true)
}
fun optional(property: KProperty1<in Node, *>): Boolean {
val propertyType = property.returnType
return !multiple(property) && propertyType.isMarkedNullable
}
fun multeplicity(property: KProperty1<in Node, *>): Multeplicity {
return when {
multiple(property) -> Multeplicity.MANY
optional(property) -> Multeplicity.OPTIONAL
else -> Multeplicity.SINGULAR
}
}
fun provideNodes(property: KProperty1<in Node, *>): Boolean {
val propertyType = property.returnType
val classifier = propertyType.classifier as? KClass<*>
return if (multiple(property)) {
providesNodes(propertyType.arguments[0])
} else {
providesNodes(classifier)
}
}
fun buildFor(property: KProperty1<in Node, *>, node: Node): PropertyDescription {
val multeplicity = multeplicity(property)
val provideNodes = provideNodes(property)
return PropertyDescription(
name = property.name,
provideNodes = provideNodes,
multeplicity = multeplicity,
value = property.get(node)
)
}
}
}
val DEFAULT_IGNORED_PROPERTIES = setOf("nodeType", "parseTreeNode", "position", "specifiedPosition")
/**
* Executes an operation on the properties of a node.
* @param propertiesToIgnore which properties to ignore. @see DEFAULT_IGNORED_PROPERTIES
* @param propertyOperation the operation to perform on each property.
*/
@JvmOverloads
fun Node.processProperties(
propertiesToIgnore: Set<String> = DEFAULT_IGNORED_PROPERTIES,
propertyOperation: (PropertyDescription) -> Unit
) {
this.properties.filter { it.name !in propertiesToIgnore }.forEach {
try {
propertyOperation(it)
} catch (t: Throwable) {
throw java.lang.RuntimeException("Issue processing property $it in $this", t)
}
}
}
/**
* Executes an operation on the properties definitions of a node class.
* @param propertiesToIgnore which properties to ignore. @see DEFAULT_IGNORED_PROPERTIES
* @param propertyTypeOperation the operation to perform on each property.
*/
fun <T : Any> Class<T>.processProperties(
propertiesToIgnore: Set<String> = DEFAULT_IGNORED_PROPERTIES,
propertyTypeOperation: (PropertyTypeDescription) -> Unit
) = kotlin.processProperties(propertiesToIgnore, propertyTypeOperation)
/**
* Executes an operation on the properties definitions of a node class.
* @param propertiesToIgnore which properties to ignore. @see DEFAULT_IGNORED_PROPERTIES
* @param propertyTypeOperation the operation to perform on each property.
*/
fun <T : Any> KClass<T>.processProperties(
propertiesToIgnore: Set<String> = DEFAULT_IGNORED_PROPERTIES,
propertyTypeOperation: (PropertyTypeDescription) -> Unit
) {
nodeProperties.forEach { p ->
if (!propertiesToIgnore.contains(p.name)) {
propertyTypeOperation(PropertyTypeDescription.buildFor(p))
}
}
}
/**
* @param walker the function that generates the nodes to operate on in the desired sequence.
* @return the first node in the AST for which the [predicate] is true. Null if none are found.
*/
fun Node.find(predicate: (Node) -> Boolean, walker: KFunction1<Node, Sequence<Node>> = Node::walk): Node? {
return walker.invoke(this).find(predicate)
}
/**
* Recursively execute [operation] on this node, and all nodes below this node that extend [klass].
*
* T is not forced to be a subtype of Node to support using interfaces.
*
* @param walker the function that generates the nodes to operate on in the desired sequence.
*/
fun <T> Node.processNodesOfType(
klass: Class<T>,
operation: (T) -> Unit,
walker: KFunction1<Node, Sequence<Node>> = Node::walk
) {
walker.invoke(this).filterIsInstance(klass).forEach(operation)
}
/**
* T is not forced to be a subtype of Node to support using interfaces.
*
* @param walker the function that generates the nodes to operate on in the desired sequence.
* @return all nodes in this AST (sub)tree that are instances of, or extend [klass].
*/
fun <T> Node.collectByType(klass: Class<T>, walker: KFunction1<Node, Sequence<Node>> = Node::walk): List<T> {
return walker.invoke(this).filterIsInstance(klass).toList()
}
/**
* Recursively execute [operation] on this node, and all nodes below this node.
* Every node is informed about its [parent] node. (But not about the parent's parent!)
*/
fun Node.processConsideringDirectParent(operation: (Node, Node?) -> Unit, parent: Node? = null) {
operation(this, parent)
this.nodeProperties.forEach { p ->
val v = p.get(this)
when (v) {
is Node -> v.processConsideringDirectParent(operation, this)
is Collection<*> -> v.forEach { (it as? Node)?.processConsideringDirectParent(operation, this) }
}
}
}
/**
* @return all direct children of this node.
*/
val Node.children: List<Node>
get() {
val children = mutableListOf<Node>()
this.properties.forEach { p ->
val v = p.value
when (v) {
is Node -> children.add(v)
is Collection<*> -> v.forEach { if (it is Node) children.add(it) }
}
}
return children
}
// TODO reimplement using transformChildren
fun Node.transformTree(
operation: (Node) -> Node,
inPlace: Boolean = false,
mutationsCache: IdentityHashMap<Node, Node> = IdentityHashMap<Node, Node>()
): Node {
if (inPlace) TODO()
mutationsCache.computeIfAbsent(this) { operation(this) }
val changes = mutableMapOf<String, Any>()
relevantMemberProperties().forEach { p ->
val v = p.get(this)
when (v) {
is Node -> {
val newValue = v.transformTree(operation, inPlace, mutationsCache)
if (newValue != v) changes[p.name] = newValue
}
is Collection<*> -> {
val newValue = v.map { if (it is Node) it.transformTree(operation, inPlace, mutationsCache) else it }
if (newValue != v) changes[p.name] = newValue
}
}
}
var instanceToTransform = this
if (changes.isNotEmpty()) {
val constructor = this.javaClass.kotlin.primaryConstructor!!
val params = mutableMapOf<KParameter, Any?>()
constructor.parameters.forEach { param ->
if (changes.containsKey(param.name)) {
params[param] = changes[param.name]
} else {
params[param] = this.javaClass.kotlin.memberProperties.find { param.name == it.name }!!.get(this)
}
}
instanceToTransform = constructor.callBy(params)
}
return mutationsCache.computeIfAbsent(instanceToTransform) { operation(instanceToTransform) }
}
class ImmutablePropertyException(property: KProperty<*>, node: Node) :
RuntimeException("Cannot mutate property '${property.name}' of node $node (class: ${node.javaClass.canonicalName})")
// assumption: every MutableList in the AST contains Nodes.
@Suppress("UNCHECKED_CAST")
fun Node.transformChildren(operation: (Node) -> Node) {
relevantMemberProperties().forEach { property ->
val value = property.get(this)
when (value) {
is Node -> {
val newValue = operation(value)
if (newValue != value) {
if (property is KMutableProperty<*>) {
property.setter.call(this, newValue)
newValue.parent = this
} else {
throw ImmutablePropertyException(property, value)
}
}
}
is Collection<*> -> {
if (value is List<*>) {
for (i in 0 until value.size) {
val element = value[i]
if (element is Node) {
val newValue = operation(element)
if (newValue != element) {
if (value is MutableList<*>) {
(value as MutableList<Node>)[i] = newValue
newValue.parent = this
} else {
throw ImmutablePropertyException(property, element)
}
}
}
}
} else {
throw UnsupportedOperationException(
"Only modifications in a List and MutableList are supported, not ${value::class}"
)
}
}
}
}
}
fun Node.mapChildren(operation: (Node) -> Node): Node {
val changes = mutableMapOf<String, Any>()
relevantMemberProperties().forEach { property ->
val value = property.get(this)
when (value) {
is Node -> {
val newValue = operation(value)
if (newValue != value) {
changes[property.name] = newValue
}
}
is Collection<*> -> {
val newValue = value.map { if (it is Node) operation(it) else it }
if (newValue != value) {
changes[property.name] = newValue
}
}
}
}
var instanceToTransform = this
if (changes.isNotEmpty()) {
val constructor = this.javaClass.kotlin.primaryConstructor!!
val params = mutableMapOf<KParameter, Any?>()
constructor.parameters.forEach { param ->
if (changes.containsKey(param.name)) {
params[param] = changes[param.name]
} else {
params[param] = this.javaClass.kotlin.memberProperties.find { param.name == it.name }!!.get(this)
}
}
instanceToTransform = constructor.callBy(params)
}
return instanceToTransform
}
/**
* Replace [this] node with [other] (by modifying the children of the parent node.)
* For this to work, [Node.assignParents] must have been called.
*/
fun Node.replaceWith(other: Node) {
if (this.parent == null) {
throw IllegalStateException("Parent not set")
}
this.parent!!.transformChildren { if (it == this) other else it }
}
/**
* Looks for [oldNode] in the lists of nodes in this node.
* When found, it is removed, and in its place the [newNodes] are inserted.
* When not found, an [IllegalStateException] is thrown.
*/
fun Node.replaceWithSeveral(oldNode: Node, newNodes: List<Node>) {
findMutableListContainingChild(oldNode) { nodeList, index ->
nodeList.replaceWithSeveral(index, newNodes)
oldNode.parent = null
newNodes.forEach { node -> node.parent = this }
}
}
/**
* Looks for [targetNode] in the lists of nodes in this node.
* When found, it is removed.
* When not found, an [IllegalStateException] is thrown.
*/
fun Node.removeFromList(targetNode: Node) {
findMutableListContainingChild(targetNode) { nodeList, index ->
nodeList.removeAt(index)
targetNode.parent = null
}
}
/**
* Looks for [targetNode] in the lists of nodes in this node.
* When found, [newNodes] are inserted before it.
* When not found, an [IllegalStateException] is thrown.
*/
fun Node.addSeveralBefore(targetNode: Node, newNodes: List<Node>) {
findMutableListContainingChild(targetNode) { nodeList, index ->
nodeList.addSeveralBefore(index, newNodes)
newNodes.forEach { node -> node.parent = this }
}
}
/**
* Looks for [targetNode] in the lists of nodes in this node.
* When found, [newNodes] are inserted after it.
* When not found, an [IllegalStateException] is thrown.
*/
fun Node.addSeveralAfter(targetNode: Node, newNodes: List<Node>) {
findMutableListContainingChild(targetNode) { nodeList, index ->
nodeList.addSeveralAfter(index, newNodes)
newNodes.forEach { node -> node.parent = this }
}
}
/**
* Supports functions that manipulate a list of child nodes by finding [targetNode] in the [MutableList]s of nodes contained in [this] node.
*/
@Suppress("UNCHECKED_CAST") // assumption: a MutableList with a Node in it is a MutableList<Node>
private fun Node.findMutableListContainingChild(
targetNode: Node,
whenFoundDo: (nodeList: MutableList<Node>, index: Int) -> Unit
) {
relevantMemberProperties().forEach { property ->
when (val value = property.get(this)) {
is MutableList<*> -> {
for (i in 0 until value.size) {
if (value[i] == targetNode) {
whenFoundDo(value as MutableList<Node>, i)
return
}
}
}
}
}
throw IllegalStateException("Did not find $targetNode in any MutableList in $this.")
}
/**
* Replaces [this] node with any amount of other nodes if it is in a [MutableList].
* <p/>Looks for [this] in the lists of nodes in the parent node.
* When found, [this] is removed, and in its place [newNodes] are inserted.
* For this to work, [Node.assignParents] must have been called.
*/
fun Node.replaceWithSeveral(newNodes: List<Node>) {
parent?.replaceWithSeveral(this, newNodes) ?: throw IllegalStateException("Parent not set")
}
/**
* Inserts the [newNodes] before [this] node if it is in a [MutableList].
* For this to work, [Node.assignParents] must have been called.
*/
fun Node.addSeveralBefore(newNodes: List<Node>) {
parent?.addSeveralBefore(this, newNodes) ?: throw IllegalStateException("Parent not set")
}
/**
* Inserts the [newNodes] after [this] node if it is in a [MutableList].
* For this to work, [Node.assignParents] must have been called.
*/
fun Node.addSeveralAfter(newNodes: List<Node>) {
parent?.addSeveralAfter(this, newNodes) ?: throw IllegalStateException("Parent not set")
}
/**
* Removes [this] node from the parent if it is in a [MutableList].
* For this to work, [Node.assignParents] must have been called.
*/
fun Node.removeFromList() {
parent?.removeFromList(this) ?: throw IllegalStateException("Parent not set")
}
/**
* Replaces the element at [index] with [replacements].
*/
fun <T> MutableList<T>.replaceWithSeveral(index: Int, replacements: List<T>) {
removeAt(index)
addAll(index, replacements)
}
/**
* Replaces the element at [index] with [additions].
*/
fun <T> MutableList<T>.addSeveralBefore(index: Int, additions: List<T>) {
addAll(index, additions)
}
/**
* Replaces the element at [index] with [additions].
*/
fun <T> MutableList<T>.addSeveralAfter(index: Int, additions: List<T>) {
addAll(index + 1, additions)
}