1 // Copyright 2011 Google Inc. All Rights Reserved.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 package com.hughes.android.dictionary.parser;
18 import java.util.regex.Matcher;
19 import java.util.regex.Pattern;
21 public final class WikiTokenizer {
23 public interface Callback {
24 void onPlainText(final String text);
25 void onMarkup(WikiTokenizer wikiTokenizer);
26 void onWikiLink(WikiTokenizer wikiTokenizer);
27 void onNewline(WikiTokenizer wikiTokenizer);
28 void onFunction(final WikiTokenizer tokenizer, String functionName, List<String> functionPositionArgs,
29 Map<String, String> functionNamedArgs);
30 void onHeading(WikiTokenizer wikiTokenizer);
31 void onListItem(WikiTokenizer wikiTokenizer);
32 void onComment(WikiTokenizer wikiTokenizer);
33 void onHtml(WikiTokenizer wikiTokenizer);
36 public static class DoNothingCallback implements Callback {
39 public void onPlainText(String text) {
43 public void onMarkup(WikiTokenizer wikiTokenizer) {
47 public void onWikiLink(WikiTokenizer wikiTokenizer) {
51 public void onNewline(WikiTokenizer wikiTokenizer) {
55 public void onFunction(WikiTokenizer tokenizer, String functionName,
56 List<String> functionPositionArgs, Map<String, String> functionNamedArgs) {
60 public void onHeading(WikiTokenizer wikiTokenizer) {
64 public void onListItem(WikiTokenizer wikiTokenizer) {
68 public void onComment(WikiTokenizer wikiTokenizer) {
72 public void onHtml(WikiTokenizer wikiTokenizer) {
76 //private static final Pattern wikiTokenEvent = Pattern.compile("($)", Pattern.MULTILINE);
77 private static final Pattern wikiTokenEvent = Pattern.compile("(" +
80 "\\||" + // Need the | because we might have to find unescaped pipes
81 "=|" + // Need the = because we might have to find unescaped =
87 "$)", Pattern.MULTILINE);
88 private static final String listChars = "*#:;";
91 final String wikiText;
92 final Matcher matcher;
94 boolean justReturnedNewline = true;
95 int lastLineStart = 0;
99 final List<String> errors = new ArrayList<>();
100 final List<String> tokenStack = new ArrayList<>();
103 private String headingWikiText;
104 private int headingDepth;
105 private int listPrefixEnd;
106 private boolean isPlainText;
107 private boolean isMarkup;
108 private boolean isComment;
109 private boolean isFunction;
110 private boolean isWikiLink;
111 private boolean isHtml;
112 private int firstUnescapedPipePos;
114 private int lastUnescapedPipePos;
115 private int lastUnescapedEqualsPos;
116 private final List<String> positionArgs = new ArrayList<>();
117 private final Map<String,String> namedArgs = new LinkedHashMap<>();
120 public WikiTokenizer(final String wikiText) {
121 this(wikiText, true);
124 public WikiTokenizer(String wikiText, final boolean isNewline) {
125 wikiText = wikiText.replace('\u2028', '\n');
126 wikiText = wikiText.replace('\u0085', '\n');
127 this.wikiText = wikiText;
128 this.matcher = wikiTokenEvent.matcher(wikiText);
129 justReturnedNewline = isNewline;
132 private void clear() {
136 headingWikiText = null;
146 firstUnescapedPipePos = -1;
147 lastUnescapedPipePos = -1;
148 lastUnescapedEqualsPos = -1;
149 positionArgs.clear();
153 private static final Matcher POSSIBLE_WIKI_TEXT = Pattern.compile(
164 public static void dispatch(final String wikiText, final boolean isNewline, final Callback callback) {
165 // Statistical background, from EN-DE dictionary generation:
166 // out of 12083000 calls, 9697686 can be skipped via the test
167 // for ', \n and ((c - 0x3b) & 0xff9f) < 2 (which covers among others
169 // This increased to 10006466 checking for <, { and [ specifically,
170 // and is minimally faster overall.
171 // A even more precise one using regex and checking for {{, [[, <!--, '',
172 // <pre>, <math>, <ref> and \n increased that to 10032846.
173 // Regex thus seems far too costly for a measly increase from 80%/82% to 83% rejection rate
174 // However completely removing it changes output (likely a bug), so leave it in for now
175 // but at least run it only on the 18% not caught by the faster logic.
176 // Original runtime: 1m29.708s
177 // Optimized: 1m19.170s
178 // Regex removed: 1m20.314s (not statistically significant)
179 boolean matched = false;
180 for (int i = 0; i < wikiText.length(); i++) {
181 int c = wikiText.charAt(i);
182 if (c == '\'' || c == '\n' || c == '<' || c == '[' || c == '{') {
187 if (!matched || !POSSIBLE_WIKI_TEXT.reset(wikiText).find()) {
188 callback.onPlainText(wikiText);
190 final WikiTokenizer tokenizer = new WikiTokenizer(wikiText, isNewline);
191 while (tokenizer.nextToken() != null) {
192 if (tokenizer.isPlainText()) {
193 callback.onPlainText(tokenizer.token());
194 } else if (tokenizer.isMarkup()) {
195 callback.onMarkup(tokenizer);
196 } else if (tokenizer.isWikiLink()) {
197 callback.onWikiLink(tokenizer);
198 } else if (tokenizer.isNewline()) {
199 callback.onNewline(tokenizer);
200 } else if (tokenizer.isFunction()) {
201 callback.onFunction(tokenizer, tokenizer.functionName(), tokenizer.functionPositionArgs(), tokenizer.functionNamedArgs());
202 } else if (tokenizer.isHeading()) {
203 callback.onHeading(tokenizer);
204 } else if (tokenizer.isListItem()) {
205 callback.onListItem(tokenizer);
206 } else if (tokenizer.isComment()) {
207 callback.onComment(tokenizer);
208 } else if (tokenizer.isHtml()) {
209 callback.onHtml(tokenizer);
210 } else if (!tokenizer.errors.isEmpty()) {
211 // Log was already printed....
213 throw new IllegalStateException("Unknown wiki state: " + tokenizer.token());
219 public List<String> errors() {
223 public boolean isNewline() {
224 return justReturnedNewline;
227 public void returnToLineStart() {
228 end = start = lastLineStart;
229 justReturnedNewline = true;
232 public boolean isHeading() {
233 return headingWikiText != null;
236 public String headingWikiText() {
238 return headingWikiText;
241 public int headingDepth() {
246 public boolean isMarkup() {
250 public boolean isComment() {
254 public boolean isListItem() {
255 return listPrefixEnd != -1;
258 public String listItemPrefix() {
260 return wikiText.substring(start, listPrefixEnd);
263 public static String getListTag(char c) {
270 public String listItemWikiText() {
272 return wikiText.substring(listPrefixEnd, end);
275 public boolean isFunction() {
279 public String functionName() {
282 if (firstUnescapedPipePos != -1) {
283 return trimNewlines(wikiText.substring(start + 2, firstUnescapedPipePos).trim());
285 final int safeEnd = Math.max(start + 2, end - 2);
286 return trimNewlines(wikiText.substring(start + 2, safeEnd).trim());
289 public List<String> functionPositionArgs() {
293 public Map<String, String> functionNamedArgs() {
297 public boolean isPlainText() {
301 public boolean isWikiLink() {
305 public String wikiLinkText() {
308 if (lastUnescapedPipePos != -1) {
309 return trimNewlines(wikiText.substring(lastUnescapedPipePos + 1, end - 2));
311 assert start + 2 < wikiText.length() && end >= 2: wikiText;
312 return trimNewlines(wikiText.substring(start + 2, end - 2));
315 public String wikiLinkDest() {
318 if (firstUnescapedPipePos != -1) {
319 return trimNewlines(wikiText.substring(start + 2, firstUnescapedPipePos));
324 public boolean isHtml() {
328 public boolean remainderStartsWith(final String prefix) {
329 return wikiText.startsWith(prefix, start);
332 public void nextLine() {
333 final int oldStart = start;
334 while(nextToken() != null && !isNewline()) {}
342 public WikiTokenizer nextToken() {
347 if (justReturnedNewline) {
348 lastLineStart = start;
353 final int len = wikiText.length();
358 // Eat a newline if we're looking at one:
359 final boolean atNewline = wikiText.charAt(end) == '\n' || wikiText.charAt(end) == '\u2028' || wikiText.charAt(end) == '\u2029';
361 justReturnedNewline = true;
366 if (justReturnedNewline) {
367 justReturnedNewline = false;
369 final char firstChar = wikiText.charAt(end);
370 if (firstChar == '=') {
371 final int headerStart = end;
373 while (++end < len && wikiText.charAt(end) == '=') {}
374 final int headerTitleStart = end;
375 headingDepth = headerTitleStart - headerStart;
378 final int nextNewline = safeIndexOf(wikiText, end, "\n", "\n");
379 final int closingEquals = escapedFindEnd(end, "=");
380 if (wikiText.charAt(closingEquals - 1) == '=') {
381 end = closingEquals - 1;
386 final int headerTitleEnd = end;
387 headingWikiText = wikiText.substring(headerTitleStart, headerTitleEnd);
389 while (end < len && ++end < len && wikiText.charAt(end) == '=') {}
390 final int headerEnd = end;
391 if (headerEnd - headerTitleEnd != headingDepth) {
392 errors.add("Mismatched header depth: " + token());
396 if (listChars.indexOf(firstChar) != -1) {
397 while (++end < len && listChars.indexOf(wikiText.charAt(end)) != -1) {}
399 end = escapedFindEnd(start, "\n");
404 if (wikiText.startsWith("'''", start)) {
410 if (wikiText.startsWith("''", start)) {
416 if (wikiText.startsWith("[[", start)) {
417 end = escapedFindEnd(start + 2, "]]");
418 isWikiLink = errors.isEmpty();
422 if (wikiText.startsWith("{{", start)) {
423 end = escapedFindEnd(start + 2, "}}");
424 isFunction = errors.isEmpty();
428 if (wikiText.startsWith("<pre>", start)) {
429 end = safeIndexOf(wikiText, start, "</pre>", "\n");
434 if (wikiText.startsWith("<ref>", start)) {
435 end = safeIndexOf(wikiText, start, "</ref>", "\n");
440 if (wikiText.startsWith("<math>", start)) {
441 end = safeIndexOf(wikiText, start, "</math>", "\n");
446 if (wikiText.startsWith("<!--", start)) {
448 end = safeIndexOf(wikiText, start, "-->", "\n");
452 if (wikiText.startsWith("}}", start) || wikiText.startsWith("]]", start)) {
453 errors.add("Close without open!");
458 if (wikiText.charAt(start) == '|' || wikiText.charAt(start) == '=') {
465 if (this.matcher.find(start)) {
466 end = this.matcher.start(1);
469 // stumbled over a new type of newline?
470 // Or matcher is out of sync with checks above
471 errors.add("Empty group: " + this.matcher.group() + " char: " + (int)wikiText.charAt(end));
473 throw new RuntimeException("matcher not in sync with code, or new type of newline, errors :" + errors);
478 end = wikiText.length();
482 if (!errors.isEmpty()) {
483 System.err.println("Errors: " + errors + ", token=" + token());
489 public String token() {
490 final String token = wikiText.substring(start, end);
491 assert token.equals("\n") || !token.endsWith("\n") : "token='" + token + "'";
495 static final String[] patterns = { "\n", "{{", "}}", "[[", "]]", "[", "]", "|", "=", "<!--" };
496 private int escapedFindEnd(final int start, final String toFind) {
497 assert tokenStack.isEmpty();
499 final boolean insideFunction = toFind.equals("}}");
502 int firstNewline = -1;
503 int[] nextMatch = new int[patterns.length];
504 Arrays.fill(nextMatch, -2);
505 int singleBrackets = 0;
506 while (end < wikiText.length()) {
507 // Manual replacement for matcher.find(end),
508 // because Java regexp is a ridiculously slow implementation.
509 // Initialize to always match the end.
511 for (int i = 0; i < nextMatch.length; ++i) {
512 if (nextMatch[i] <= end) {
513 nextMatch[i] = wikiText.indexOf(patterns[i], end);
514 if (nextMatch[i] == -1) nextMatch[i] = i > 0 ? 0x7fffffff : wikiText.length();
516 if (nextMatch[i] < nextMatch[matchIdx]) {
521 int matchStart = nextMatch[matchIdx];
522 String matchText = patterns[matchIdx];
523 int matchEnd = matchStart + matchText.length();
526 matchEnd = matchStart;
529 assert matchEnd > end || matchText.length() == 0: "Group=" + matchText;
530 if (matchText.length() == 0) {
531 assert matchStart == wikiText.length() || wikiText.charAt(matchStart) == '\n' : wikiText + ", " + matchStart;
532 if (firstNewline == -1) {
533 firstNewline = matchEnd;
535 if (tokenStack.isEmpty() && toFind.equals("\n")) {
539 } else if (tokenStack.isEmpty() && matchText.equals(toFind)) {
540 // The normal return....
541 if (insideFunction) {
542 addFunctionArg(insideFunction, matchStart);
545 } else if (matchText.equals("[")) {
547 } else if (matchText.equals("]")) {
548 if (singleBrackets > 0) singleBrackets--;
549 } else if (matchText.equals("[[") || matchText.equals("{{")) {
550 tokenStack.add(matchText);
551 } else if (matchText.equals("]]") || matchText.equals("}}")) {
552 if (tokenStack.size() > 0) {
553 final String removed = tokenStack.remove(tokenStack.size() - 1);
554 if (removed.equals("{{") && !matchText.equals("}}")) {
555 if (singleBrackets >= 2) { // assume this is really two closing single ]
557 tokenStack.add(removed);
559 errors.add("Unmatched {{ error: " + wikiText.substring(start, matchEnd));
560 return safeIndexOf(wikiText, start, "\n", "\n");
562 } else if (removed.equals("[[") && !matchText.equals("]]")) {
563 errors.add("Unmatched [[ error: " + wikiText.substring(start, matchEnd));
564 return safeIndexOf(wikiText, start, "\n", "\n");
567 errors.add("Pop too many " + matchText + " error: " + wikiText.substring(start, matchEnd).replace("\n", "\\\\n"));
568 // If we were looking for a newline
569 return safeIndexOf(wikiText, start, "\n", "\n");
571 } else if (matchText.equals("|")) {
572 if (tokenStack.isEmpty()) {
573 addFunctionArg(insideFunction, matchStart);
575 } else if (matchText.equals("=")) {
576 if (tokenStack.isEmpty()) {
577 lastUnescapedEqualsPos = matchStart;
579 // Do nothing. These can match spuriously, and if it's not the thing
580 // we're looking for, keep on going.
581 } else if (matchText.equals("<!--")) {
582 end = wikiText.indexOf("-->", matchStart);
584 errors.add("Unmatched <!-- error: " + wikiText.substring(start));
585 return safeIndexOf(wikiText, start, "\n", "\n");
587 } else if (matchText.equals("''") || (matchText.startsWith("<") && matchText.endsWith(">"))) {
590 assert false : "Match text='" + matchText + "'";
591 throw new IllegalStateException();
594 // Inside the while loop. Just go forward.
595 end = Math.max(end, matchEnd);
597 if (toFind.equals("\n") && tokenStack.isEmpty()) {
598 // We were looking for the end, we got it.
601 errors.add("Couldn't find: " + (toFind.equals("\n") ? "newline" : toFind) + ", "+ wikiText.substring(start));
602 if (firstNewline != -1) {
608 private void addFunctionArg(final boolean insideFunction, final int matchStart) {
609 if (firstUnescapedPipePos == -1) {
610 firstUnescapedPipePos = lastUnescapedPipePos = matchStart;
611 } else if (insideFunction) {
612 if (lastUnescapedEqualsPos > lastUnescapedPipePos) {
613 final String key = wikiText.substring(lastUnescapedPipePos + 1, lastUnescapedEqualsPos);
614 final String value = wikiText.substring(lastUnescapedEqualsPos + 1, matchStart);
615 namedArgs.put(trimNewlines(key), trimNewlines(value));
617 final String value = wikiText.substring(lastUnescapedPipePos + 1, matchStart);
618 positionArgs.add(trimNewlines(value));
621 lastUnescapedPipePos = matchStart;
624 static String trimNewlines(String s) {
625 while (s.startsWith("\n")) {
628 while (s.endsWith("\n")) {
629 s = s.substring(0, s.length() - 1);
631 return s.replace('\n', ' ');
634 static int safeIndexOf(final String s, final int start, final String target, final String backup) {
635 int close = s.indexOf(target, start);
637 // Don't step over a \n.
638 return close + (target.equals("\n") ? 0 : target.length());
640 close = s.indexOf(backup, start);
642 return close + (backup.equals("\n") ? 0 : backup.length());
647 public static String toPlainText(final String wikiText) {
648 final WikiTokenizer wikiTokenizer = new WikiTokenizer(wikiText);
649 final StringBuilder builder = new StringBuilder();
650 while (wikiTokenizer.nextToken() != null) {
651 if (wikiTokenizer.isPlainText()) {
652 builder.append(wikiTokenizer.token());
653 } else if (wikiTokenizer.isWikiLink()) {
654 builder.append(wikiTokenizer.wikiLinkText());
655 } else if (wikiTokenizer.isNewline()) {
656 builder.append("\n");
657 } else if (wikiTokenizer.isFunction()) {
658 builder.append(wikiTokenizer.token());
661 return builder.toString();
664 public static StringBuilder appendFunction(final StringBuilder builder, final String name, List<String> args,
665 final Map<String, String> namedArgs) {
666 builder.append(name);
667 for (final String arg : args) {
668 builder.append("|").append(arg);
670 for (final Map.Entry<String, String> entry : namedArgs.entrySet()) {
671 builder.append("|").append(entry.getKey()).append("=").append(entry.getValue());