| 14 | } |
| 15 | |
| 16 | public String[] tokenize(String src) { |
| 17 | List<String> tokens = new ArrayList<>(); |
| 18 | |
| 19 | int index = 0; |
| 20 | while (index < src.length()) { |
| 21 | final int contextStart = index; |
| 22 | ITokenizingContext ctx = (relStart, relEnd) -> { |
| 23 | int start = contextStart + relStart; |
| 24 | int end = contextStart + relEnd; |
| 25 | int stringEnd = src.length(); |
| 26 | String gotten = src.substring(start, Math.min(end, stringEnd)); |
| 27 | while (gotten.length() < end - start) { |
| 28 | gotten += END_OF_LINE; |
| 29 | } |
| 30 | return gotten; |
| 31 | }; |
| 32 | boolean consumed = false; |
| 33 | for (ITokenizerGobbler token : tokenizers) { |
| 34 | TokenResult res = token.tokenizePart(ctx); |
| 35 | if (res == ResultSpecific.IGNORE) continue; |
| 36 | if (res == ResultSpecific.INVALID) { |
| 37 | throw new InputMismatchException("Invalid src \"" + ctx.get(10).replace("\n", "\\n") + "\""); |
| 38 | } |
| 39 | if (res instanceof ResultInvalid) { |
| 40 | throw new InputMismatchException("Invalid src \"" + ctx.get(((ResultInvalid) res).length).replace("\n", "\\n") + "\""); |
| 41 | } |
| 42 | if (res instanceof ResultDiscard) { |
| 43 | int discardLength = ((ResultDiscard) res).length; |
| 44 | index += discardLength; |
| 45 | consumed = true; |
| 46 | break; |
| 47 | } |
| 48 | if (res instanceof ResultConsume) { |
| 49 | int consumedLength = ((ResultConsume) res).length; |
| 50 | String at = ctx.get(consumedLength); |
| 51 | tokens.add(at); |
| 52 | index += consumedLength; |
| 53 | consumed = true; |
| 54 | break; |
| 55 | } |
| 56 | } |
| 57 | if (!consumed) { |
| 58 | throw new IllegalStateException("Did not consume:" + ctx.get(50)); |
| 59 | } |
| 60 | } |
| 61 | return tokens.toArray(new String[tokens.size()]); |
| 62 | } |
| 63 | |
| 64 | @FunctionalInterface |
| 65 | public interface ITokenizingContext { |