diff options
| author | bculkin2442 <bjculkin@mix.wvu.edu> | 2016-04-10 20:10:36 -0400 |
|---|---|---|
| committer | bculkin2442 <bjculkin@mix.wvu.edu> | 2016-04-10 20:10:36 -0400 |
| commit | bf726639e1bc70b30dc5e5ae2cf349a5bbdfb0ae (patch) | |
| tree | 0ebe89df2fe7f2b1c6ff9564959191e3ede2e002 /dice-lang/src/main/java/bjc/dicelang/ast/DiceASTParser.java | |
| parent | 90d1cc6c9f47f1b6f74fb57e07865795a46c23b8 (diff) | |
Moved things around for rewrite of AST mechanisms
Diffstat (limited to 'dice-lang/src/main/java/bjc/dicelang/ast/DiceASTParser.java')
| -rw-r--r-- | dice-lang/src/main/java/bjc/dicelang/ast/DiceASTParser.java | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/dice-lang/src/main/java/bjc/dicelang/ast/DiceASTParser.java b/dice-lang/src/main/java/bjc/dicelang/ast/DiceASTParser.java new file mode 100644 index 0000000..db2ba98 --- /dev/null +++ b/dice-lang/src/main/java/bjc/dicelang/ast/DiceASTParser.java @@ -0,0 +1,70 @@ +package bjc.dicelang.ast; + +import java.util.InputMismatchException; + +import bjc.dicelang.old.ast.nodes.IDiceASTNode; +import bjc.dicelang.old.ast.nodes.LiteralDiceNode; +import bjc.dicelang.old.ast.nodes.OperatorDiceNode; +import bjc.dicelang.old.ast.nodes.VariableDiceNode; +import bjc.utils.funcdata.IFunctionalList; +import bjc.utils.parserutils.AST; +import bjc.utils.parserutils.TreeConstructor; + +/** + * Parse a string expression into AST form. Doesn't do anything else + * + * @author ben + * + */ +public class DiceASTParser { + /** + * Create an AST from a list of tokens + * + * @param tokens + * The list of tokens to convert + * @return An AST built from the tokens + */ + public static AST<IDiceASTNode> createFromString( + IFunctionalList<String> tokens) { + AST<String> rawTokens = + TreeConstructor.constructTree(tokens, (token) -> { + return isOperatorNode(token); + }, (operator) -> false, null); + // The last argument is valid because there are no special + // operators yet, so it'll never get called + + return rawTokens.rebuildTree(DiceASTParser::convertLeafNode, + DiceASTParser::convertOperatorNode); + } + + private static boolean isOperatorNode(String token) { + try { + OperatorDiceNode.fromString(token); + return true; + } catch (@SuppressWarnings("unused") IllegalArgumentException iaex) { + // We don't care about details + return false; + } + } + + private static IDiceASTNode convertLeafNode(String leafNode) { + if (LiteralDiceNode.isLiteral(leafNode)) { + return new LiteralDiceNode(leafNode); + } + + return new VariableDiceNode(leafNode); + } + + private static IDiceASTNode convertOperatorNode(String operatorNode) { + try { + return OperatorDiceNode.fromString(operatorNode); + } catch (IllegalArgumentException iaex) { + InputMismatchException imex = new InputMismatchException( + "Attempted to parse invalid operator " + operatorNode); + + imex.initCause(iaex); + + throw imex; + } + } +} |
