FormatRhsFunction extends AbstractRhsFunctionHandler { @Override public Symbol execute(RhsFunctionContext context, List<Symbol> arguments) throws RhsFunctionException { RhsFunctions.checkArgumentCount(this, arguments); final String format = arguments.get(0).toString(); final Object[] derefed = new Object[arguments.size() - 1]; for(int i = 0; i < derefed.length; i++) { derefed[i] = Symbols.valueOf(arguments.get(i + 1)); } try { return context.getSymbols().createString(String.format(format, derefed)); } catch(IllegalFormatConversionException e) { final Production p = context.getProductionBeingFired(); throw new RhsFunctionException("Invalid format '" + format + "' in rule '" + (p != null ? p.getName() : "unknown") + "': " + e.getMessage(), e); } } FormatRhsFunction(); @Override Symbol execute(RhsFunctionContext context, List<Symbol> arguments);  }
@Test public void testCanFormatAStringWithNoArguments() throws Exception { checkResult("hello, world", func.execute(rhsFuncContext, Symbols.asList(syms, "hello, world"))); }
@Test public void testFormatWithSeveralArgs() throws Exception { checkResult("S1: hi 987 3.140000 null", func.execute(rhsFuncContext, Symbols.asList(syms, "%s: %s %d %f %s", syms.createIdentifier('S'), "hi", 987, 3.14, null))); }
@Test(expected=RhsFunctionException.class) public void testFormatThrowsExceptionWhenGivenAnInvalidFormatSpecifier() throws Exception { func.execute(rhsFuncContext, Symbols.asList(syms, "%d", "hello")); }