Created
June 20, 2013 20:14
-
-
Save abailly/5826206 to your computer and use it in GitHub Desktop.
Possible use of Locatable to add source information to parsers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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