Ports over the fix for expander's stack-overflow in flatten.