/*
- * Svjatoslav Commons - shared library of common functionality.
- * Copyright ©2012-2017, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of version 3 of the GNU Lesser General Public License
- * or later as published by the Free Software Foundation.
+ * Svjatoslav Commons - shared library of common functionality. Author: Svjatoslav Agejenko.
+ * This project is released under Creative Commons Zero (CC0) license.
*/
-
package eu.svjatoslav.commons.string.tokenizer;
import java.util.ArrayList;
import static eu.svjatoslav.commons.string.tokenizer.Terminator.TerminationStrategy.DROP;
import static eu.svjatoslav.commons.string.tokenizer.Terminator.TerminationStrategy.PRESERVE;
+import static java.lang.System.out;
public class Tokenizer {
- final Stack<Integer> tokenIndexes = new Stack<>();
+ /**
+ * Stack of token indexes. This allows to walk back in history and un-consume the token.
+ */
+ private final Stack<Integer> tokenIndexes = new Stack<>();
+
+ /**
+ * Terminators that will be searched for by given tokenizer within given source string.
+ */
private final List<Terminator> terminators = new ArrayList<>();
- private String source;
+
+ private String source; // string to be tokenized
+
private int currentIndex = 0;
+ private int cachedTerminatorIndex = -1;
+ private Terminator cachedTerminator;
+
public Tokenizer(final String source) {
this.source = source;
}
- public Tokenizer(){}
+ public Tokenizer() {
+ }
- public Tokenizer setSource(String source){
+ public Tokenizer setSource(String source) {
this.source = source;
currentIndex = 0;
tokenIndexes.clear();
+
+ cachedTerminatorIndex = -1;
+ cachedTerminator = null;
return this;
}
return this;
}
+ public Tokenizer addTerminator(Terminator terminator) {
+ terminators.add(terminator);
+ return this;
+ }
+
public Tokenizer addTerminator(final String startSequence,
final String endSequence, final Terminator.TerminationStrategy terminationStrategy) {
terminators.add(new Terminator(startSequence, endSequence, terminationStrategy));
+ "\" but got \"" + match.token + "\" instead.");
}
+ /**
+ * @return next @TokenizerMatch or <code>null</code> if end of input is reached.
+ * @throws InvalidSyntaxException
+ */
public TokenizerMatch getNextToken() throws InvalidSyntaxException {
tokenIndexes.push(currentIndex);
- StringBuilder token = new StringBuilder();
+ StringBuilder tokenAccumulator = new StringBuilder();
+
+ while (true) {
+
+ if (currentIndex >= source.length()) { // reached end of input
+ if (hasAccumulatedToken(tokenAccumulator))
+ return new TokenizerMatch(tokenAccumulator.toString(), null, null);
+ else
+ return null;
+ }
- while (true){
if (isOngoingToken()) {
- token.append(source.charAt(currentIndex));
+ tokenAccumulator.append(source.charAt(currentIndex));
currentIndex++;
continue;
}
- Terminator tokenTerminator = findTokenTerminator();
-
- if (tokenTerminator.termination == PRESERVE){
- return buildPreservedToken(token, tokenTerminator);
- } else if (tokenTerminator.termination == DROP){
- if (hasAccumulatedToken(token)){
- currentIndex++;
- return new TokenizerMatch(token.toString(), "", tokenTerminator);
- } else {
- currentIndex++;
- }
+ Terminator terminator = getOrFindTokenTerminator();
+
+ if (terminator.termination == PRESERVE)
+ return buildPreservedToken(tokenAccumulator, terminator);
+ else if (terminator.termination == DROP) {
+ skipUntilTerminatorEnd(terminator);
+
+ if (hasAccumulatedToken(tokenAccumulator))
+ return new TokenizerMatch(tokenAccumulator.toString(), null, terminator);
}
}
}
- private TokenizerMatch buildPreservedToken(StringBuilder token, Terminator terminator) throws InvalidSyntaxException {
+ private void skipUntilTerminatorEnd(Terminator terminator) throws InvalidSyntaxException {
+ if (terminator.hasEndSequence())
+ currentIndex = getEndSequenceIndex(terminator) + terminator.endSequence.length();
+ else
+ currentIndex += terminator.startSequence.length();
+ }
+
+ /**
+ * @throws InvalidSyntaxException if end sequence is not found as is expected by given token.
+ */
+ private TokenizerMatch buildPreservedToken(StringBuilder token, Terminator terminator)
+ throws InvalidSyntaxException {
if (hasAccumulatedToken(token))
- return new TokenizerMatch(token.toString(), "", terminator);
+ return new TokenizerMatch(token.toString(), null, terminator);
- if (terminator.hasEndSequence()){
- int endSequenceIndex = source.indexOf(terminator.endSequence,
- currentIndex + terminator.startSequence.length());
+ if (terminator.hasEndSequence())
+ return buildTokenWithExpectedENdSequence(terminator);
+ else
+ return buildTokenWithoutEndSequence(terminator);
+ }
- if (endSequenceIndex < 0)
- throw new InvalidSyntaxException("Expected \"" + terminator.endSequence + "\" but not found.");
+ private TokenizerMatch buildTokenWithoutEndSequence(Terminator terminator) {
+ currentIndex += terminator.startSequence.length();
+ return new TokenizerMatch(terminator.startSequence, null, terminator);
+ }
- String reminder = source.substring(currentIndex + terminator.startSequence.length(), endSequenceIndex);
- currentIndex = endSequenceIndex + terminator.endSequence.length();
+ private TokenizerMatch buildTokenWithExpectedENdSequence(Terminator terminator) throws InvalidSyntaxException {
+ int endSequenceIndex = getEndSequenceIndex(terminator);
+ String reminder = source.substring(currentIndex + terminator.startSequence.length(), endSequenceIndex);
+ currentIndex = endSequenceIndex + terminator.endSequence.length();
- return new TokenizerMatch(terminator.startSequence, reminder, terminator);
- } else {
- currentIndex += terminator.startSequence.length();
- return new TokenizerMatch(terminator.startSequence, "", terminator);
- }
+ return new TokenizerMatch(terminator.startSequence, reminder, terminator);
+ }
+
+ /**
+ * @throws InvalidSyntaxException if end of input is reached without finding expected end sequence.
+ */
+ private int getEndSequenceIndex(Terminator terminator) throws InvalidSyntaxException {
+ int endSequenceIndex = source.indexOf(terminator.endSequence,
+ currentIndex + terminator.startSequence.length());
+
+ if (endSequenceIndex < 0)
+ throw new InvalidSyntaxException("Expected \"" + terminator.endSequence + "\" but not found.");
+
+ return endSequenceIndex;
}
private boolean hasAccumulatedToken(StringBuilder token) {
}
private boolean isOngoingToken() {
- return findTokenTerminator() == null;
+ return getOrFindTokenTerminator() == null;
+ }
+
+ public boolean hasMoreContent() {
+ return currentIndex < source.length();
+ }
+
+ /**
+ * Attempts to cache terminator search result.
+ */
+ public Terminator getOrFindTokenTerminator() {
+ if (currentIndex == cachedTerminatorIndex)
+ return cachedTerminator;
+
+ cachedTerminatorIndex = currentIndex;
+ cachedTerminator = findTokenTerminator();
+ return cachedTerminator;
}
- public Terminator findTokenTerminator() {
+ private Terminator findTokenTerminator() {
for (Terminator terminator : terminators)
if (terminator.matches(source, currentIndex))
return terminator;
return result;
}
- public boolean peekIsOneOf(String ... possibilities) throws InvalidSyntaxException {
+ public boolean peekIsOneOf(String... possibilities) throws InvalidSyntaxException {
String nextToken = peekNextToken().token;
return Stream.of(possibilities).anyMatch(possibility -> possibility.equals(nextToken));
}
- public void peekExpectNoneOf(String ... possibilities) throws InvalidSyntaxException {
+ public void peekExpectNoneOf(String... possibilities) throws InvalidSyntaxException {
if (peekIsOneOf(possibilities))
throw new InvalidSyntaxException("Not expected \"" + peekNextToken().token + "\" here.");
}
+ public void unreadToken() {
+ currentIndex = tokenIndexes.pop();
+ }
- public boolean sequenceMatches(final String sequence) {
- if ((currentIndex + sequence.length()) > source.length())
- return false;
+ /**
+ * For debugging
+ */
+ public void enlistRemainingTokens(){
+ int redTokenCount = 0;
- for (int i = 0; i < sequence.length(); i++)
- if (sequence.charAt(i) != source.charAt(i + currentIndex))
- return false;
+ try {
+ while (hasMoreContent()) {
+ out.println(getNextToken().toString());
+ redTokenCount++;
+ }
+ } catch (InvalidSyntaxException e){
+ out.println("There is syntax exception");
+ }
- return true;
+ // restore pointer to original location
+ for (int i = 0; i< redTokenCount; i++ ) unreadToken();
}
+
public void skipUntilDataEnd() {
tokenIndexes.push(currentIndex);
currentIndex = source.length();
}
- public void skipUntilSequence(final String sequence) {
- while (currentIndex < source.length()) {
- if (sequenceMatches(sequence)) {
- currentIndex += sequence.length();
- return;
- }
-
- currentIndex++;
- }
- }
-
- public void unreadToken() {
- currentIndex = tokenIndexes.pop();
- }
-
}