<commit_before>package io.jentz.winter

/**
 * The dependency graph class that retrieves and instantiates dependencies from a component.
 *
 * An instance is created by calling [Component.init] or [Graph.initSubcomponent].
 */
class Graph internal constructor(
    parent: Graph?,
    component: Component,
    val application: WinterApplication,
    block: ComponentBuilderBlock?
) {

    private sealed class State {
        data class Initialized(
            val component: Component,
            val parent: Graph?,
            val stack: DependenciesStack,
            val cache: MutableMap<TypeKey, BoundService<*, *>> = mutableMapOf()
        ) : State()

        object Disposed : State()
    }

    private var state: State
    private val plugins = application.plugins

    private inline fun <T> fold(ifDisposed: () -> T, ifInitialized: (State.Initialized) -> T): T {
        return synchronized(this) {
            val state = state
            if (state is State.Initialized) ifInitialized(state) else ifDisposed()
        }
    }

    private inline fun <T> map(block: (State.Initialized) -> T): T =
        fold({ throw WinterException("Graph is already disposed.") }, block)

    /**
     * The parent [Graph] instance or null if no parent exists.
     */
    val parent: Graph? get() = map { it.parent }

    /**
     * The [Component] instance.
     */
    val component: Component get() = map { it.component }

    /**
     * Indicates if the graph is disposed.
     */
    val isDisposed: Boolean get() = fold({ true }, { false })

    init {
        val baseComponent = if (plugins.isNotEmpty() || block != null) {
            component(component.qualifier) {
                include(component)
                block?.invoke(this)
                plugins.runInitializingComponent(parent, this)
            }
        } else {
            component
        }

        state = State.Initialized(baseComponent, parent, DependenciesStack(this))

        val eagerDependencies = serviceOrNull<Unit, Set<TypeKey>>(eagerDependenciesKey)
        eagerDependencies?.instance(Unit)?.forEach { key ->
            val service = serviceOrNull<Unit, Any>(key)
                ?: throw EntryNotFoundException(
                    key,
                    "BUG: Eager dependency with key `$key` doesn't exist."
                )
            service.instance(Unit)
        }
    }


    /**<commit_msg>Use derive in Graph init to extend component<commit_after>package io.jentz.winter

/**
 * The dependency graph class that retrieves and instantiates dependencies from a component.
 *
 * An instance is created by calling [Component.init] or [Graph.initSubcomponent].
 */
class Graph internal constructor(
    parent: Graph?,
    component: Component,
    val application: WinterApplication,
    block: ComponentBuilderBlock?
) {

    private sealed class State {
        data class Initialized(
            val component: Component,
            val parent: Graph?,
            val stack: DependenciesStack,
            val cache: MutableMap<TypeKey, BoundService<*, *>> = mutableMapOf()
        ) : State()

        object Disposed : State()
    }

    private var state: State
    private val plugins = application.plugins

    private inline fun <T> fold(ifDisposed: () -> T, ifInitialized: (State.Initialized) -> T): T {
        return synchronized(this) {
            val state = state
            if (state is State.Initialized) ifInitialized(state) else ifDisposed()
        }
    }

    private inline fun <T> map(block: (State.Initialized) -> T): T =
        fold({ throw WinterException("Graph is already disposed.") }, block)

    /**
     * The parent [Graph] instance or null if no parent exists.
     */
    val parent: Graph? get() = map { it.parent }

    /**
     * The [Component] instance.
     */
    val component: Component get() = map { it.component }

    /**
     * Indicates if the graph is disposed.
     */
    val isDisposed: Boolean get() = fold({ true }, { false })

    init {
        val baseComponent = if (plugins.isNotEmpty() || block != null) {
            component.derive {
                block?.invoke(this)
                plugins.runInitializingComponent(parent, this)
            }
        } else {
            component
        }

        state = State.Initialized(baseComponent, parent, DependenciesStack(this))

        val eagerDependencies = serviceOrNull<Unit, Set<TypeKey>>(eagerDependenciesKey)
        eagerDependencies?.instance(Unit)?.forEach { key ->
            val service = serviceOrNull<Unit, Any>(key)
                ?: throw EntryNotFoundException(
                    key,
                    "BUG: Eager dependency with key `$key` doesn't exist."
                )
            service.instance(Unit)
        }
    }


    /**
{'fraction_non_alphanumeric': 0.10387984981226533, 'fraction_numerical': 0.0, 'mean_word_length': 2.131939908556499, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '971078', 'n_tokens_mistral': 1259, 'n_tokens_neox': 1214, 'n_words': 374}