diff --git a/core/src/main/kotlin/tw/xcc/gumtree/model/CompareHelper.kt b/core/src/main/kotlin/tw/xcc/gumtree/model/CompareHelper.kt new file mode 100644 index 0000000..d2ea9ae --- /dev/null +++ b/core/src/main/kotlin/tw/xcc/gumtree/model/CompareHelper.kt @@ -0,0 +1,41 @@ +package tw.xcc.gumtree.model + +import tw.xcc.gumtree.api.tree.Comparable + +class CompareHelper(private val tree: GumTree) : Comparable { + 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 + } + } +} \ No newline at end of file diff --git a/core/src/main/kotlin/tw/xcc/gumtree/model/GumTree.kt b/core/src/main/kotlin/tw/xcc/gumtree/model/GumTree.kt index af26c14..274a7d7 100644 --- a/core/src/main/kotlin/tw/xcc/gumtree/model/GumTree.kt +++ b/core/src/main/kotlin/tw/xcc/gumtree/model/GumTree.kt @@ -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 @@ -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 = traversalHelper.preOrdered() override fun postOrdered(): List = traversalHelper.postOrdered() diff --git a/core/src/main/kotlin/tw/xcc/gumtree/model/TreeType.kt b/core/src/main/kotlin/tw/xcc/gumtree/model/TreeType.kt new file mode 100644 index 0000000..5979daa --- /dev/null +++ b/core/src/main/kotlin/tw/xcc/gumtree/model/TreeType.kt @@ -0,0 +1,5 @@ +package tw.xcc.gumtree.model + +data class TreeType(val name: String) { + fun isEmpty(): Boolean = name.isEmpty() +} \ No newline at end of file