fix many custom mro() edge cases and improve code quality (#22735)

Patch by Eldar Abusalimov.
4 files changed