Created
December 18, 2011 17:25
-
-
Save terazzo/1493976 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
package sample.jparsec; | |
import static org.junit.Assert.assertEquals; | |
import java.util.List; | |
import org.codehaus.jparsec.*; | |
import org.codehaus.jparsec.functors.*; | |
import org.junit.Test; | |
public class JparsecSample { | |
public static Parser<String> str(String s) { | |
return Scanners.string(s).source(); | |
} | |
@Test | |
public void recursiveTest() { | |
// <a1star> ::= { "a" "1" } | |
Parser<String> a1star = Parsers.sequence( | |
str("a"), str("1"), | |
new Map2<String, String, String>() { | |
public String map(String s1,String s2) { | |
return s1 + s2; | |
} | |
} | |
).many().map(new Map<List<String>, String>() { | |
public String map(List<String> strings) { | |
String acc = ""; | |
for (String s :strings) { | |
acc += s; | |
} | |
return acc; | |
} | |
}); | |
// <a> ::= [ "a" ] | |
Parser<String> a = str("a").optional(""); | |
// <p4> ::= <a1star> <a> | |
Parser<String> p4 = Parsers.sequence( | |
a1star, a, | |
new Map2<String, String, String>() { | |
public String map(String s1,String s2) { | |
return s1 + s2; | |
} | |
} | |
); | |
assertEquals("a1", p4.parse("a1")); // OK | |
assertEquals("a1a1a1", p4.parse("a1a1a1")); // OK | |
assertEquals("a1a", p4.parse("a1a")); // NG...? | |
/* | |
org.codehaus.jparsec.error.ParserException: line 1, column 4: | |
1 expected, EOF encountered. | |
at org.codehaus.jparsec.Parsers.parse(Parsers.java:98) | |
... | |
*/ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment