refactoring grammar loops