in Sources/SwiftSyntax/SyntaxChildren.swift [174:208]
func index(before index: SyntaxChildrenIndex) -> SyntaxChildrenIndex {
if let index = index.data {
// We are reversing a non-end index.
let previousNode = parent.child(at: Int(index.indexInParent - 1))
let previousNodeLength = UInt32(previousNode?.totalLength.utf8Length ?? 0)
let reversedIndexInTree = index.indexInTree.reversedBy(previousNode)
return SyntaxChildrenIndex(offset: index.offset - previousNodeLength,
indexInParent: index.indexInParent - 1,
indexInTree: reversedIndexInTree)
} else {
// We need to reverse the end index. For this we need to compute a
// materialized version of the end index that points one past the end of
// the collection. After we have that materialized index, we can reverse
// it using the above logic.
// If the start index is nil, then the collection is empty and we are
// reversing before the start index. That is undefined behaviour, so we
// can assume a non-end index.
let startIndex = self.startIndex.data!
// Compute a materialized index.
let offset = startIndex.offset + UInt32(parent.totalLength.utf8Length)
let indexInParent = startIndex.indexInParent +
UInt32(parent.numberOfChildren)
let indexInTree = startIndex.indexInTree.indexInTree +
UInt32(parent.totalNodes) - 1
let syntaxIndexInTree = SyntaxIndexInTree(indexInTree: indexInTree)
let materialized = SyntaxChildrenIndex(offset: offset,
indexInParent: indexInParent,
indexInTree: syntaxIndexInTree)
// Reverse index based on the above logic
return self.index(before: materialized)
}
}