Created
May 16, 2020 13:35
-
-
Save abailly/d0ee2811a3d023906d115adace399244 to your computer and use it in GitHub Desktop.
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
package org.jparsec.examples.dsl; | |
import org.jparsec.Parser; | |
import org.jparsec.Parsers; | |
import org.jparsec.Scanners; | |
import org.jparsec.Terminals; | |
import java.util.Arrays; | |
public class DSL { | |
// TOKENS | |
private static final String[] KEYWORDS = { | |
"attack", "with" | |
}; | |
private static final Terminals TERMS = | |
Terminals.operators().words(Scanners.IDENTIFIER).caseInsensitiveKeywords(Arrays.asList(KEYWORDS)).build(); | |
static final Parser<Void> IGNORED = Scanners.WHITESPACES.skipMany(); | |
static final Parser<String> QUOTE = Terminals.StringLiteral.SINGLE_QUOTE_TOKENIZER.or(Terminals.StringLiteral.DOUBLE_QUOTE_TOKENIZER); | |
// TOKENIZER: Reads chars and produces a stream of Tokens | |
static Parser<?> tokenizer = Parsers.or(TERMS.tokenizer(), QUOTE); | |
// Actual parsers, built from Tokens | |
static final Parser<Spell> SPELL = Terminals.StringLiteral.PARSER.map(s -> new Spell(s)); | |
static final Parser<Action> ATTACK_PARSER = | |
Parsers.sequence(TERMS.token("attack"), TERMS.token("with"), SPELL) | |
.map(spell -> new AttackWith(spell)); | |
public static void main(String[] args) { | |
String toParse = "attack with 'waterfall'"; | |
System.out.println(ATTACK_PARSER.from(tokenizer, IGNORED).parse(toParse)); | |
} | |
private static class Spell { | |
public final String spell; | |
public Spell(String s) { | |
spell = s; | |
} | |
@Override | |
public String toString() { | |
return "Spell{" + | |
"spell='" + spell + '\'' + | |
'}'; | |
} | |
} | |
public interface Action { | |
} | |
private static class AttackWith implements Action { | |
private Spell spell; | |
public AttackWith(Spell spell) { | |
this.spell = spell; | |
} | |
@Override | |
public String toString() { | |
return "AttackWith{" + | |
"spell=" + spell + | |
'}'; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment