Repository: Kotlin/kotlinx.coroutines
File: kotlinx-coroutines-core/common/src/JobSupport.kt (Kotlin)

Code before:
                                }
                            }
                            return handle
                        } else {
                            val node = makeNode(handler, onCancelling)
                            val res = addLast(state, list, node).also { nodeAdded = node }
                            if (res) return node
                        }
                    }
                }
                else -> { // is complete
                    // :KLUDGE: We have to invoke a handler in platform-specific way via `invokeIt` extension,
                    // because we play type tricks on Kotlin/JS and handler is not necessarily a function there
                    if (invokeImmediately) {
                        if (nodeAdded != null) {
                            nodeAdded!!.invoke((state as? CompletedExceptionally)?.cause)
                        } else {
                            handler.invokeIt((state as? CompletedExceptionally)?.cause)
                        }
                    }
                    return NonDisposableHandle
                }
            }
        }
    }

    private fun makeNode(handler: CompletionHandler, onCancelling: Boolean): JobNode<*> {
        return if (onCancelling)
            (handler as? JobCancellingNode<*>)?.also { assert { it.job === this } }
                ?: InvokeOnCancelling(this, handler)
        else
            (handler as? JobNode<*>)?.also { assert { it.job === this && it !is JobCancellingNode } }
                ?: InvokeOnCompletion(this, handler)
    }

    private fun addLast(expectedState: Any, list: NodeList, node: JobNode<*>): Boolean {
        list.addLast(node)
        if (this.state === expectedState) return true
        if (node is ChildCompletion && !node.markInvoked()) return true
        node.dispose()
        return false
    }

    private fun promoteEmptyToNodeList(state: Empty) {
        // try to promote it to LIST state with the corresponding state
        val list = NodeList()
        val update = if (state.isActive) list else InactiveNodeList(list)
        _state.compareAndSet(state, update)
    }

    private fun promoteSingleToNodeList(state: JobNode<*>) {

Review comment (refactor):
`(state as? CompletedExceptionally)?.cause` can be extracted to a variable to avoid copy-paste

Code after:
                                     * invoked or skipped the node, thus we additionally synchronize on 'markInvoked'.
                                     */
                                    if (node is ChildCompletion && !node.markInvoked()) return node
                                    // The state can only change to Complete here, so the node can stay in the list, just retry
                                    return@loopOnState
                                }
                                // just return node if we don't have to invoke handler (not cancelling yet)
                                if (rootCause == null) return node
                                // otherwise handler is invoked immediately out of the synchronized section & handle returned
                                handle = node
                            }
                        }
                    }
                    if (rootCause != null) {
                        // Note: attachChild uses invokeImmediately, so it gets invoked when adding to cancelled job
                        if (invokeImmediately) {
                            node.invoke(rootCause)
                        }
                        return handle
                    } else {
                        if (!isNodeAdded) list.addLast(node)
                        if (this.state !== state) {
                            // Here again, we try to prevent concurrent finalization of the parent,
                            // if the parent fails to add ChildCompletion because the child changed it's state to Completed.
                            if (node is ChildCompletion && !node.markInvoked()) return node
                            // If the state has changed to Complete, the node can stay in the list, just retry.
                            if (this.state !is Incomplete) return@loopOnState
                            // If the state is Incomplete, set the flag that the node is already added to the list instead of removing it.
                            isNodeAdded = true
                        } else {
                            return node
                        }
                    }
                }
                else -> { // is complete
                    if (invokeImmediately) {
                        node.invoke((state as? CompletedExceptionally)?.cause)
                    }
                    return NonDisposableHandle
                }
            }
        }
    }

    private fun makeNode(handler: CompletionHandler, onCancelling: Boolean): JobNode {
        val node = if (onCancelling) {
            (handler as? JobCancellingNode)
                ?: InvokeOnCancelling(handler)
        } else {
            (handler as? JobNode)
                ?.also { assert { it !is JobCancellingNode } }