package bjc.utils.parserutils.pratt; import bjc.utils.data.ITree; import bjc.utils.funcutils.NumberUtils; import bjc.utils.parserutils.ParserException; import java.util.HashMap; import java.util.Map; /** * A configurable Pratt parser for expressions. * * @author EVE * * @param * The key type for the tokens. * * @param * The value type for the tokens. * * @param * The state type of the parser. * * */ public class PrattParser { private final LeftCommand DEFAULT_LEFT_COMMAND = new DefaultLeftCommand<>(); private final NullCommand DEFAULT_NULL_COMMAND = new DefaultNullCommand<>(); private Map> leftCommands; private Map> nullCommands; private Map> statementCommands; /** * Create a new Pratt parser. * * @param terminal * The terminal symbol. */ public PrattParser() { leftCommands = new HashMap<>(); nullCommands = new HashMap<>(); statementCommands = new HashMap<>(); } /** * Parse an expression. * * @param precedence * The initial precedence for the expression. * * @param tokens * The tokens for the expression. * * @param state * The state of the parser. * * @return The expression as an AST. * * @throws ParserException * If something goes wrong during parsing. */ public ITree> parseExpression(int precedence, TokenStream tokens, C state, boolean isStatement) throws ParserException { if (precedence < 0) { throw new IllegalArgumentException("Precedence must be greater than zero"); } Token initToken = tokens.current(); tokens.next(); ITree> ast; if (isStatement && statementCommands.containsKey(initToken.getKey())) { ast = statementCommands.getOrDefault(initToken.getKey(), DEFAULT_NULL_COMMAND).nullDenotation(initToken, new ParserContext<>(tokens, this, state)); } else { ast = nullCommands.getOrDefault(initToken.getKey(), DEFAULT_NULL_COMMAND).nullDenotation(initToken, new ParserContext<>(tokens, this, state)); } int rightPrec = Integer.MAX_VALUE; while (true) { Token tok = tokens.current(); K key = tok.getKey(); LeftCommand command = leftCommands.getOrDefault(key, DEFAULT_LEFT_COMMAND); int leftBind = command.leftBinding(); if (NumberUtils.between(precedence, rightPrec, leftBind)) { tokens.next(); ast = command.leftDenote(ast, tok, new ParserContext<>(tokens, this, state)); rightPrec = command.nextBinding(); } else { break; } } return ast; } /** * Add a non-initial command to this parser. * * @param marker * The key that marks the command. * * @param comm * The command. */ public void addNonInitialCommand(K marker, LeftCommand comm) { leftCommands.put(marker, comm); } /** * Add a initial command to this parser. * * @param marker * The key that marks the command. * * @param comm * The command. */ public void addInitialCommand(K marker, NullCommand comm) { nullCommands.put(marker, comm); } }