Skip to content

Commit

Permalink
feat: 🎸 implement tree similarity comparison methods
Browse files Browse the repository at this point in the history
  • Loading branch information
Xanonymous-GitHub committed Jul 17, 2024
1 parent 07e63c9 commit b62cec8
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
41 changes: 41 additions & 0 deletions core/src/main/kotlin/tw/xcc/gumtree/model/CompareHelper.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package tw.xcc.gumtree.model

import tw.xcc.gumtree.api.tree.Comparable

class CompareHelper(private val tree: GumTree) : Comparable<GumTree> {
override fun isIsomorphicTo(other: GumTree): Boolean =
compareTrees(other, true) { child, otherChild ->
child isIsomorphicTo otherChild
}

override fun isIsoStructuralTo(other: GumTree): Boolean =
compareTrees(other, false) { child, otherChild ->
child isIsoStructuralTo otherChild
}

private inline fun compareTrees(
other: GumTree,
shouldCheckLabel: Boolean,
childComparison: (GumTree, GumTree) -> Boolean
): Boolean {
synchronized(tree) {
if (!(tree hasSameTypeAs other && tree.childCount() == other.childCount())) {
return false
}

if (shouldCheckLabel && !(tree hasSameLabelAs other)) {
return false
}

for (i in 0 until tree.childCount()) {
val child = tree.childAt(i) ?: return false
val otherChild = other.childAt(i) ?: return false
if (!childComparison(child, otherChild)) {
return false
}
}

return true
}
}
}
10 changes: 9 additions & 1 deletion core/src/main/kotlin/tw/xcc/gumtree/model/GumTree.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@ class GumTree :
private val traversalHelper = TraversalHelper(this)
private val compareHelper = CompareHelper(this)


val type: TreeType = TreeType("")
var label: String = ""
val pos: Int = -1
val length: Int = -1

fun insertChildAt(
pos: Int,
child: GumTree
Expand All @@ -31,6 +35,10 @@ class GumTree :
}
}

infix fun hasSameTypeAs(other: GumTree): Boolean = type == other.type

infix fun hasSameLabelAs(other: GumTree): Boolean = label == other.label

override fun preOrdered(): List<GumTree> = traversalHelper.preOrdered()

override fun postOrdered(): List<GumTree> = traversalHelper.postOrdered()
Expand Down
5 changes: 5 additions & 0 deletions core/src/main/kotlin/tw/xcc/gumtree/model/TreeType.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package tw.xcc.gumtree.model

data class TreeType(val name: String) {
fun isEmpty(): Boolean = name.isEmpty()
}

0 comments on commit b62cec8

Please sign in to comment.