private void insertWithDesiredParentType(List<Item> items, int index, CompositeItem parent, TermType desiredParentType, boolean replacing) {
        CompositeItem parentsParent = parent.getParent();

        CompositeItem newParent = newParent(desiredParentType);

        if (parentsParent != null && (! (parentsParent instanceof QueryTree) && parentsParent.getItemType() == newParent.getItemType())) { // Collapse
            for (Item item : items)
                parentsParent.addItem(item);
            return;
        }

        for (Item item : items)
            newParent.addItem(item);

        Item current = parent;
        if (parent instanceof QueryTree && parent.getItemCount() > 0)
            current = parent.getItem(0);
        if (current instanceof CompositeItem && !replacing) { // insert new parent below the current
            if (parent.getItemCount() > index) {
                var combinedItem = combineItems(newParent, parent.getItem(index), desiredParentType);
                parent.setItem(index, combinedItem);
            }
            else{
                parent.addItem(newParent);
            }
        }
        else if (newParent.acceptsItemsOfType(current.getItemType())) { // insert new parent above the current
            newParent.addItem(current);
            if (newParent != parentsParent) { // Insert new parent as root or child of old parent's parent
                if (parentsParent != null)
                    parentsParent.setItem(parentsParent.getItemIndex(current), newParent);
                else
                    parent.setItem(0, newParent);
            }
        }
        else {
            ((CompositeItem)current).addItem(newParent); // not an acceptable child -> composite
        }
    }
A special purpose check used to simplify the above
container-search/src/main/java/com/yahoo/prelude/semantics/engine/Evaluation.java