transcendental-lisp/src/token/TokenFactoryImpl.java

53 lines
1.6 KiB
Java

package token;
import static java.lang.Character.isDigit;
import static util.Characters.*;
import file.FilePosition;
public class TokenFactoryImpl implements TokenFactory {
public Token createToken(String text, FilePosition position) {
if (text.length() == 0)
throw new EmptyTokenTextException(position);
char firstCharacter = text.charAt(0);
switch (firstCharacter) {
case LEFT_PARENTHESIS:
return new LeftParenthesis(text, position);
case RIGHT_PARENTHESIS:
return new RightParenthesis(text, position);
case SINGLE_QUOTE:
return new QuoteMark(text, position);
case DOUBLE_QUOTE:
return new QuotedString(text, position);
default:
if (isNumeric(firstCharacter, text)) {
return new Number(text, position);
} else if (isLegalIdentifierCharacter(firstCharacter)) {
return new Identifier(text, position);
}
}
throw new BadCharacterException(text, position);
}
private boolean isNumeric(char firstCharacter, String text) {
return isDigit(firstCharacter) || isPrefixedNumeric(firstCharacter, text);
}
private boolean isPrefixedNumeric(char firstCharacter, String text) {
return isNumberPrefix(firstCharacter) && isNextCharacterDigit(text);
}
private boolean isNextCharacterDigit(String text) {
return (text.length() > 1) && isDigit(text.charAt(1));
}
public Token createEofToken(FilePosition position) {
return new Eof("EOF", position);
}
}