Skip to content

Instantly share code, notes, and snippets.

@OndraZizka
Created October 10, 2023 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OndraZizka/7bbe63204ae36b08850517ce3da63fb7 to your computer and use it in GitHub Desktop.
Save OndraZizka/7bbe63204ae36b08850517ce3da63fb7 to your computer and use it in GitHub Desktop.
A Stack-based Processing Context for Kotlin
class StackBasedContext(
val nestingStack: Deque<NestingLevel> = ArrayDeque(),
val problems: MutableList<Pair<String, List<NestingLevel>>> = mutableListOf(),
) {
override fun toString() = nestingStack.ifEmpty { listOf("(root)") }.joinToString("/")
fun addProblem(msg: String) { problems.add(msg to nestingStack.descendingIterator().asSequence().toList()) }
fun pushLevel(dataParam: KParameter): PopOnClose { nestingStack.push(NestingLevel(dataParam)); return PopOnClose() }
fun pushLevel(collectionIndex: Int): PopOnClose { nestingStack.push(NestingLevel(collectionIndex = collectionIndex)); return PopOnClose() }
fun popLevel(): NestingLevel = nestingStack.pop()
data class NestingLevel(
// ... Whatever your processing context needs on each level.
) {
override fun toString() = ...
}
/** Allows to leverage use { } with MapperContext. */
inner class PopOnClose : AutoCloseable {
override fun close() { this@StackBasedContext.nestingStack.pop() }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment