2017-07-29 21:02:41 -07:00
|
|
|
package org.nwapw.abacus.parsing;
|
|
|
|
|
|
|
|
import org.nwapw.abacus.tree.TreeNode;
|
|
|
|
|
|
|
|
import java.util.List;
|
|
|
|
|
2017-07-30 14:59:20 -07:00
|
|
|
/**
|
|
|
|
* TreeBuilder class used to piece together a Tokenizer and
|
|
|
|
* Parser of the same kind. This is used to essentially avoid
|
|
|
|
* working with any parameters at all, and the generics
|
|
|
|
* in this class are used only to ensure the tokenizer and parser
|
|
|
|
* are of the same type.
|
2017-07-30 21:11:32 -07:00
|
|
|
*
|
2017-07-30 14:59:20 -07:00
|
|
|
* @param <T> the type of tokens created by the tokenizer and used by the parser.
|
|
|
|
*/
|
2017-07-29 21:02:41 -07:00
|
|
|
public class TreeBuilder<T> {
|
|
|
|
|
2017-07-30 14:59:20 -07:00
|
|
|
/**
|
|
|
|
* The tokenizer used to convert a string into tokens.
|
|
|
|
*/
|
2017-07-29 21:02:41 -07:00
|
|
|
private Tokenizer<T> tokenizer;
|
2017-07-30 14:59:20 -07:00
|
|
|
/**
|
|
|
|
* The parser used to parse a list of tokens into a tree.
|
|
|
|
*/
|
2017-07-29 21:02:41 -07:00
|
|
|
private Parser<T> parser;
|
|
|
|
|
2017-07-30 14:59:20 -07:00
|
|
|
/**
|
|
|
|
* Create a new Tree Builder with the given tokenizer and parser
|
2017-07-30 21:11:32 -07:00
|
|
|
*
|
2017-07-30 14:59:20 -07:00
|
|
|
* @param tokenizer the tokenizer to turn strings into tokens
|
2017-07-30 21:11:32 -07:00
|
|
|
* @param parser the parser to turn tokens into a tree
|
2017-07-30 14:59:20 -07:00
|
|
|
*/
|
2017-07-30 21:11:32 -07:00
|
|
|
public TreeBuilder(Tokenizer<T> tokenizer, Parser<T> parser) {
|
2017-07-29 21:02:41 -07:00
|
|
|
this.tokenizer = tokenizer;
|
|
|
|
this.parser = parser;
|
|
|
|
}
|
|
|
|
|
2017-07-30 14:59:20 -07:00
|
|
|
/**
|
|
|
|
* Parse the given string into a tree.
|
2017-07-30 21:11:32 -07:00
|
|
|
*
|
2017-07-30 14:59:20 -07:00
|
|
|
* @param input the string to parse into a tree.
|
|
|
|
* @return the resulting tree.
|
|
|
|
*/
|
2017-07-30 21:11:32 -07:00
|
|
|
public TreeNode fromString(String input) {
|
2017-07-29 21:02:41 -07:00
|
|
|
List<T> tokens = tokenizer.tokenizeString(input);
|
2017-07-30 21:11:32 -07:00
|
|
|
if (tokens == null) return null;
|
2017-07-29 21:02:41 -07:00
|
|
|
return parser.constructTree(tokens);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|