A left-right parser for the Java language.
You can download the latest version here. But you can also clone this repository and build the project using maven (mvn >= 3.3 and java 8 are recommended):
mvn clean installAfter building the project, grab the target/jleri-0.0-SNAPSHOT.jar file and add it to your own project as library.
We recommend using pyleri for creating a grammar and export the grammar to jleri. This way you can create one single grammar and export the grammar to program languages like C, JavaScript, Go, Java and Python.
// MyGrammar.javaimporttechnology.transceptor.jleri.Grammar;
importtechnology.transceptor.jleri.Element;
importtechnology.transceptor.jleri.Sequence;
importtechnology.transceptor.jleri.Regex;
importtechnology.transceptor.jleri.Keyword;
importtechnology.transceptor.jleri.Result;
importtechnology.transceptor.jleri.MaxRecursionException;
publicclassMyGrammarextendsGrammar {
privatestaticfinalElementR_NAME = newRegex("^(?:\"(?:[^\"]*)\")+");
privatestaticfinalElementK_HI = newKeyword("hi");
privatestaticfinalElementSTART = newSequence(K_HI, R_NAME);
publicMyGrammar() {
super(START);
}
publicstaticvoidmain(String []args) {
MyGrammargrammar = newMyGrammar();
try {
Resultres = grammar.parse("hi \"Iris\"");
/** * res.isValid * true or false depending if the string is successful parsed * by the grammar or not. * res.tree * contains the parse tree. * res.pos * the position in the string where parsing has end. * (if successful this will be equal to the string length) * res.getExpecting() * returns a HashSet<Element> with elements which are expected at * position res.pos. This can be used for auto-completion, * auto correction or suggestions. */System.out.println(res.isValid); // true
} catch (MaxRecursionExceptionex) {
// Maximum recursion occurred
}
}
}Compile and run:
javac -cp jleri.jar MyGrammar.java && java -cp ./:jleri.jar MyGrammar
Jleri has several elements which can be used to create a grammar. Each element is a subclass of jleri.Element and accepts an optional first Enum id which
can be used to identify the Element, for example in an node tree. The default id is set to null but as a user of jleri
you should never set the id to null yourself, just omit the id in that case.
importtechnology.transceptor.jleri.Keyword;
// Keyword(Enum id=null, String keyword, boolean ignCase=false)The parser needs to match the keyword which is just a string. When matching keywords we need to tell the parser what characters are allowed in keywords. By default Jleri uses ^\w+ which is equal to ^[A-Za-z0-9_]+. We can overwrite the default by using a second argument while calling super inside the grammar constructor.
Keyword() accepts a boolean argument ignCase which when omitted is set to false and tells the parser if we should match case insensitive.
Example:
publicclassTicTacToeextendsGrammar {
privatestaticfinalElementSTART = newKeyword("tic-tac-toe", true);
publicTicTacToe() {
// Let's allow keywords with alphabetic characters and dashes.super(START, "^[A-Za-z-]+");
}
publicstaticvoidmain(String []args) {
TicTacToegrammar = newTicTacToe();
try {
System.out.println(grammar.parse("Tic-Tac-Toe").isValid); // true
} catch (MaxRecursionExceptionex) {
// Maximum recursion occurred
}
}
}importtechnology.transceptor.jleri.Regex;
// Regex(Enum id=null, <java.util.regex.Pattern, String> pattern)The parser uses a regular expression for matching this element.
See Quick usage for an example on how to use jleri.Regex.
importtechnology.transceptor.jleri.Token;
// Token(Enum id=null, <String, Char> token)A token can be one or more characters and is usually used to match operators like +, -, // and so on.
Example:
publicclassNiextendsGrammar {
privatestaticfinalElementK_NI = newKeyword("ni");
privatestaticfinalElementSTART = newSequence(
K_NI, newToken('+'), K_NI);
publicNi() {
super(START);
}
publicstaticvoidmain(String []args) {
Nigrammar = newNi();
try {
System.out.println(grammar.parse("ni+ni").isValid); // true
} catch (MaxRecursionExceptionex) {
// Maximum recursion occurred
}
}
}importtechnology.transceptor.jleri.Tokens;
// Tokens(Enum id=null, String tokens)Can be used to register multiple tokens at once. The tokens argument should be a string with tokens separated by spaces. If given tokens are different in size the parser will try to match the longest tokens first.
Example:
publicclassNiextendsGrammar {
privatestaticfinalElementTKS = newTokens("+ - !=");
privatestaticfinalElementSTART = newList(
newKeyword("ni"), TKS, 0, null, false
);
publicNi() {
super(START);
}
publicstaticvoidmain(String []args) {
Nigrammar = newNi();
try {
System.out.println(
grammar.parse("ni + ni != ni- ni").isValid
); // true
} catch (MaxRecursionExceptionex) {
// Maximum recursion occurred
}
}
}importtechnology.transceptor.jleri.Sequence;
// Sequence(Enum id=null, Element... elems)The parser needs to match each element in a sequence.
Example:
publicclassTicTacToeextendsGrammar {
privatestaticfinalElementSTART = newSequence(
newKeyword("Tic"),
newKeyword("Tac"),
newKeyword("Toe")
);
publicTicTacToe() {
super(START);
}
publicstaticvoidmain(String []args) {
TicTacToegrammar = newTicTacToe();
try {
System.out.println(grammar.parse("Tic Tac Toe").isValid); // true
} catch (MaxRecursionExceptionex) {
// Maximum recursion occurred
}
}
}importtechnology.transceptor.jleri.Choice;
// Choice(Enum id=null, boolean mostGreedy=true, Element... elems)The parser needs to choose between one of the given elements. Choice accepts a boolean argument mostGreedy which when omitted defaults to true. When mostGreedy is set to false the parser will stop at the first match. When true the parser will try each element and returns the longest match. Setting mostGreedy to false can provide some extra performance. Note that the parser will try to match each element in the exact same order they are parsed to Choice.
Example: let us use Choice to modify the Quick usage example to allow the string bye "Iris"
publicclassMyGrammarextendsGrammar {
privatestaticfinalElementR_NAME = newRegex("^(?:\"(?:[^\"]*)\")+");
privatestaticfinalElementK_HI = newKeyword("hi");
privatestaticfinalElementK_BYE = newKeyword("bye");
privatestaticfinalElementSTART = newSequence(
newChoice(K_HI, K_BYE),
R_NAME
);
publicMyGrammar() {
super(START);
}
publicstaticvoidmain(String []args) {
MyGrammargrammar = newMyGrammar();
try {
System.out.println(grammar.parse("hi \"Iris\"").isValid); // trueSystem.out.println(grammar.parse("bye \"Iris\"").isValid); // true
} catch (MaxRecursionExceptionex) {
// Maximum recursion occurred
}
}
}importtechnology.transceptor.jleri.Repeat;
// Repeat(Enum id=null, Element elem, int min=0, Integer max=null)The parser needs at least min elements and at most max elements. min can be any integer value equal or higher than 0. When max is set to null we allow unlimited number of elements or in case a value is used it must al least equal or higher than min.
Example:
publicclassNiextendsGrammar {
privatestaticfinalElementSTART = newRepeat(newKeyword("ni"));
publicNi() {
super(START);
}
publicstaticvoidmain(String []args) {
Nigrammar = newNi();
try {
System.out.println(grammar.parse("ni ni ni ni").isValid); // true
} catch (MaxRecursionExceptionex) {
// Maximum recursion occurred
}
}
}It is not allowed to bind a name to the same element twice and Repeat(elem, 1, 1) is a common solution to bind the element a second (or more) time(s).
For example consider the following:
publicclassMyGrammarextendsGrammar {
privatestaticfinalElementR_NAME = newRegex("^(?:\"(?:[^\"]*)\")+");
/** * We should avoid using this: * private static final Element R_ADDRESS = R_NAME * * Instead use Repeat: */privatestaticfinalElementR_ADDRESS = newRepeat(R_NAME, 1, 1);
}importtechnology.transceptor.jleri.List;
/** * List(Enum id=null, * Element elem, * Element delimiter=new Token(','), * int min=0, * Integer max=null, * boolean optClose=false); */List is like Repeat but with a delimiter. A comma (Token) is used as default delimiter but any element is allowed. mix and max work exactly like with Repeat. Argument optClose can be set to true to allow the list to end with a delimiter. When omitted this is set to false which means the list has to end with an element.
Example:
publicclassNiextendsGrammar {
privatestaticfinalElementSTART = newList(newKeyword("ni"));
publicNi() {
super(START);
}
publicstaticvoidmain(String []args) {
Nigrammar = newNi();
try {
System.out.println(grammar.parse("ni, ni, ni").isValid); // true
} catch (MaxRecursionExceptionex) {
// Maximum recursion occurred
}
}
}importtechnology.transceptor.jleri.Optional;
// Optional(Enum id=null, Element elem)The parser looks for an optional element. It is like using Repeat(element, 0, 1) but we encourage to use Optional since it is more readable. (and slightly faster)
Example:
publicclassMyGrammarextendsGrammar {
privatestaticfinalElementR_NAME = newRegex("^(?:\"(?:[^\"]*)\")+");
privatestaticfinalElementK_HI = newKeyword("hi");
privatestaticfinalElementSTART = newSequence(
K_HI,
newOptional(R_NAME)
);
publicMyGrammar() {
super(START);
}
publicstaticvoidmain(String []args) {
MyGrammargrammar = newMyGrammar();
try {
System.out.println(grammar.parse("hi \"Iris\"").isValid); // trueSystem.out.println(grammar.parse("hi").isValid); // true
} catch (MaxRecursionExceptionex) {
// Maximum recursion occurred
}
}
}importtechnology.transceptor.jleri.Ref;
// Ref()The grammar can make a forward reference to make recursion possible. In the example below we create a forward reference to START but note that
a reference to any element can be made. Ref() accepts no arguments.
Warning: A reference is not protected against testing the same position in in a string. This could potentially lead to an infinite loop. For example:
Elementr = newRef(); ((Ref) r).set(newOptional(r)); // DON'T DO THISUse Prio if such recursive construction is required.
Example:
publicclassNestedNiextendsGrammar {
privatestaticfinalElementSTART = newRef();
privatestaticfinalElementNI_ITM = newChoice(newKeyword('ni'), START);
publicNestedNi() {
super(START);
((Ref) START).set(newSequence(
newToken('['), newList(NI_ITM), newToken(']')
));
}
publicstaticvoidmain(String []args) {
NestedNigrammar = newNestedNi();
try {
System.out.println(grammar.parse(
"[ni, ni, [ni, [], [ni, ni]]").isValid); // true
} catch (MaxRecursionExceptionex) {
// Maximum recursion occurred
}
}
}importtechnology.transceptor.jleri.Prio;
importtechnology.transceptor.jleri.This; // exposes This.THIS// Prio(Enum id, Element... elems)Choose the first match from the Prio elements and allow This.THIS for recursive operations. With This.THIS we point to the Prio element.
Probably the example below explains how Prio and This.THIS can be used.
Note: Use a Ref when possible. A
Prioelement is required when the same position in a string is potentially checked more than once.
Example:
publicclassNiextendsGrammar {
privatestaticfinalElementK_NI = newKeyword("ni");
privatestaticfinalElementSTART = newPrio(
K_NI,
newSequence(newToken('('), This.THIS, newToken(')')),
newSequence(This.THIS, newKeyword("or"), This.THIS),
newSequence(This.THIS, newKeyword("and"), This.THIS)
);
publicNi() {
super(START);
}
publicstaticvoidmain(String []args) {
Nigrammar = newNi();
try {
System.out.println(
grammar.parse("(ni or ni) and (ni or ni)").isValid
); // true
} catch (MaxRecursionExceptionex) {
// Maximum recursion occurred
}
}
}