final List<Object> result = Lists.newArrayListWithCapacity(after.size() + 2);
final boolean useBrackets = tokens.size() > template.size();
if (useBrackets) {
result.add("(");
}
final TokenList input = tokens.subList(templatePos, templatePos + template.size());
final Map<String, Object> varMap = Maps.newHashMapWithExpectedSize(variables.size());
try {
bind(before, input, variables, varMap);
for (final Object o : after) {
final Object val = varMap.get(o);
if (val != null) {
result.add(val);
} else {
result.add(o);
}
}
} catch (final BindException e) {
return ParseResult.fail();
}
if (useBrackets) {
result.add(")");
}
final TokenList resultTL = TokenList.create(result);
final TokenList flattened = PreParser.flatten(resultTL);
return ParseResult.success(
tokens.replaceWithTokenList(templatePos, templatePos + template.size(), flattened),
Math.min(0, -flattened.size())
);
}