[MECHDB] Grammar refactor, validation, scoping and formatting