59 lines
2.0 KiB
Java
59 lines
2.0 KiB
Java
package token;
|
|
|
|
import file.FilePosition;
|
|
import util.Characters;
|
|
|
|
import static java.lang.Character.isDigit;
|
|
|
|
public class TokenFactoryImpl implements TokenFactory {
|
|
|
|
@Override
|
|
public Token createToken(String text, FilePosition position) {
|
|
if (text.length() == 0)
|
|
throw new EmptyTokenTextException(position);
|
|
|
|
char firstCharacter = text.charAt(0);
|
|
|
|
switch (firstCharacter) {
|
|
case Characters.LEFT_PARENTHESIS:
|
|
return new LeftParenthesis(text, position);
|
|
case Characters.RIGHT_PARENTHESIS:
|
|
return new RightParenthesis(text, position);
|
|
case Characters.SINGLE_QUOTE:
|
|
return new QuoteMark(text, position);
|
|
case Characters.DOUBLE_QUOTE:
|
|
return new QuotedString(text, position);
|
|
case Characters.BACKQUOTE:
|
|
return new Backquote(text, position);
|
|
case Characters.AT_SIGN:
|
|
return new AtSign(text, position);
|
|
case Characters.COMMA:
|
|
return new Comma(text, position);
|
|
default:
|
|
if (isNumeric(firstCharacter, text))
|
|
return new Number(text, position);
|
|
else if (Characters.INSTANCE.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 Characters.INSTANCE.isNumberPrefix(firstCharacter) && isNextCharacterDigit(text);
|
|
}
|
|
|
|
private boolean isNextCharacterDigit(String text) {
|
|
return (text.length() > 1) && isDigit(text.charAt(1));
|
|
}
|
|
|
|
@Override
|
|
public Token createEofToken(FilePosition position) {
|
|
return new Eof("EOF", position);
|
|
}
|
|
}
|