Generator { public void generate( String start, Output output ) { generateTree( start ).write( output ); } @SafeVarargs  Generator( Grammar grammar, ProductionReplacement<Void>... replacements ); @SafeVarargs <T> Generator( Grammar grammar, Supplier<T> context, ProductionReplacement<T>... replacements ); @SafeVarargs  Generator( Choices random, Grammar grammar, ProductionReplacement<Void>... replacements ); @SafeVarargs <T> Generator( Choices random, Grammar grammar, Supplier<T> context,
                          ProductionReplacement<T>... replacements ); void generate( String start, Output output ); void generate( Output output );  }
@Test public void shouldReplaceProductions() throws Exception { String generated = generate( grammar( "foo" ) .production( "foo", nonTerminal( "bar" ) ) .production( "bar", literal( "WRONG!" ) ), replace( "bar", bar -> bar.write( "OK" ) ) ); assertEquals( "OK", generated ); }
@Test public void shouldAllowContextSensitiveReplacements() throws Exception { assertEquals( "one - two", generate( grammar( "lang" ).production( "lang", sequence( nonTerminal( "alpha" ), literal( " - " ), nonTerminal( "beta" ) ) ) .production( "alpha", nonTerminal( "symbol" ) ) .production( "beta", nonTerminal( "symbol" ) ) .production( "symbol", literal( "<NOT REPLACED>" ) ), replace("symbol", symbol -> { switch ( symbol.node().parent().name() ) { case "alpha": symbol.write( "one" ); break; case "beta": symbol.write( "two" ); break; default: symbol.generateDefault(); break; } } ) ) ); }