Skip to content

Instantly share code, notes, and snippets.

@abailly
Created June 20, 2013 20:14
Show Gist options
  • Save abailly/5826206 to your computer and use it in GitHub Desktop.
Save abailly/5826206 to your computer and use it in GitHub Desktop.
Possible use of Locatable to add source information to parsers
public class AnnotatedASTParserTest {
//~ ----------------------------------------------------------------------------------------------------------------
//~ Methods
//~ ----------------------------------------------------------------------------------------------------------------
@Test
public void canProduceAnASTWithSourceForEachNode() throws Exception {
Parser<?> lparen = Scanners.isChar('(');
Parser<?> rparen = Scanners.isChar(')');
Parser<AnnotatedPair<String, String>> pairOfInts = Mapper.curry(AnnotatedPair.class).sequence(Scanners.INTEGER, //
Mapper._(Scanners.isChar(',')), //
Scanners.INTEGER).between(lparen, rparen).locate().cast();
Parser<List<AnnotatedPair<String, String>>> listOfPairsOfIntegers = pairOfInts.sepBy(Scanners.WHITESPACES);
List<AnnotatedPair<String, String>> result = listOfPairsOfIntegers.parse("(5,2) (45,12)");
assertThat(result.size(), is(2));
assertThat(result.get(0).endIndex,is(5));
}
public static class AnnotatedPair<A, B> implements Locatable {
private final A a;
private final B b;
private String source;
private int beginIndex;
private int endIndex;
public AnnotatedPair(A a, B b) {
this.a = a;
this.b = b;
}
@Override
public void setSource(String source) {
this.source = source;
}
@Override
public void setLocation(int beginIndex, int endIndex) {
this.beginIndex = beginIndex;
this.endIndex = endIndex;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment