Upstream refactoring from Fireplace in nunjucks.compat