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 "\n", 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('\u2029', '\n');
127 wikiText = wikiText.replace('\u0085', '\n');
128 this.wikiText = wikiText;
129 this.matcher = wikiTokenEvent.matcher(wikiText);
130 justReturnedNewline = isNewline;
133 private void clear() {
137 headingWikiText = null;
147 firstUnescapedPipePos = -1;
148 lastUnescapedPipePos = -1;
149 lastUnescapedEqualsPos = -1;
150 positionArgs.clear();
154 private static final Matcher POSSIBLE_WIKI_TEXT = Pattern.compile(
165 public static void dispatch(final String wikiText, final boolean isNewline, final Callback callback) {
166 // Statistical background, from EN-DE dictionary generation:
167 // out of 12083000 calls, 9697686 can be skipped via the test
168 // for ', \n and ((c - 0x3b) & 0xff9f) < 2 (which covers among others
170 // This increased to 10006466 checking for <, { and [ specifically,
171 // and is minimally faster overall.
172 // A even more precise one using regex and checking for {{, [[, <!--, '',
173 // <pre>, <math>, <ref> and \n increased that to 10032846.
174 // Regex thus seems far too costly for a measly increase from 80%/82% to 83% rejection rate
175 // However completely removing it changes output (likely a bug), so leave it in for now
176 // but at least run it only on the 18% not caught by the faster logic.
177 // Original runtime: 1m29.708s
178 // Optimized: 1m19.170s
179 // Regex removed: 1m20.314s (not statistically significant)
180 boolean matched = false;
181 for (int i = 0; i < wikiText.length(); i++) {
182 int c = wikiText.charAt(i);
183 if (c == '\'' || c == '\n' || c == '<' || c == '[' || c == '{') {
188 if (!matched || !POSSIBLE_WIKI_TEXT.reset(wikiText).find()) {
189 callback.onPlainText(wikiText);
191 final WikiTokenizer tokenizer = new WikiTokenizer(wikiText, isNewline);
192 while (tokenizer.nextToken() != null) {
193 if (tokenizer.isPlainText()) {
194 callback.onPlainText(tokenizer.token());
195 } else if (tokenizer.isMarkup()) {
196 callback.onMarkup(tokenizer);
197 } else if (tokenizer.isWikiLink()) {
198 callback.onWikiLink(tokenizer);
199 } else if (tokenizer.isNewline()) {
200 callback.onNewline(tokenizer);
201 } else if (tokenizer.isFunction()) {
202 callback.onFunction(tokenizer, tokenizer.functionName(), tokenizer.functionPositionArgs(), tokenizer.functionNamedArgs());
203 } else if (tokenizer.isHeading()) {
204 callback.onHeading(tokenizer);
205 } else if (tokenizer.isListItem()) {
206 callback.onListItem(tokenizer);
207 } else if (tokenizer.isComment()) {
208 callback.onComment(tokenizer);
209 } else if (tokenizer.isHtml()) {
210 callback.onHtml(tokenizer);
211 } else if (!tokenizer.errors.isEmpty()) {
212 // Log was already printed....
214 throw new IllegalStateException("Unknown wiki state: " + tokenizer.token());
220 public List<String> errors() {
224 public boolean isNewline() {
225 return justReturnedNewline;
228 public void returnToLineStart() {
229 end = start = lastLineStart;
230 justReturnedNewline = true;
233 public boolean isHeading() {
234 return headingWikiText != null;
237 public String headingWikiText() {
239 return headingWikiText;
242 public int headingDepth() {
247 public boolean isMarkup() {
251 public boolean isComment() {
255 public boolean isListItem() {
256 return listPrefixEnd != -1;
259 public String listItemPrefix() {
261 return wikiText.substring(start, listPrefixEnd);
264 public static String getListTag(char c) {
271 public String listItemWikiText() {
273 return wikiText.substring(listPrefixEnd, end);
276 public boolean isFunction() {
280 public String functionName() {
283 if (firstUnescapedPipePos != -1) {
284 return trimNewlines(wikiText.substring(start + 2, firstUnescapedPipePos).trim());
286 final int safeEnd = Math.max(start + 2, end - 2);
287 return trimNewlines(wikiText.substring(start + 2, safeEnd).trim());
290 public List<String> functionPositionArgs() {
294 public Map<String, String> functionNamedArgs() {
298 public boolean isPlainText() {
302 public boolean isWikiLink() {
306 public String wikiLinkText() {
309 if (lastUnescapedPipePos != -1) {
310 return trimNewlines(wikiText.substring(lastUnescapedPipePos + 1, end - 2));
312 assert start + 2 < wikiText.length() && end >= 2: wikiText;
313 return trimNewlines(wikiText.substring(start + 2, end - 2));
316 public String wikiLinkDest() {
319 if (firstUnescapedPipePos != -1) {
320 return trimNewlines(wikiText.substring(start + 2, firstUnescapedPipePos));
325 public boolean isHtml() {
329 public boolean remainderStartsWith(final String prefix) {
330 return wikiText.startsWith(prefix, start);
333 public void nextLine() {
334 final int oldStart = start;
335 while(nextToken() != null && !isNewline()) {}
343 public WikiTokenizer nextToken() {
348 if (justReturnedNewline) {
349 lastLineStart = start;
354 final int len = wikiText.length();
359 // Eat a newline if we're looking at one:
360 final boolean atNewline = wikiText.charAt(end) == '\n';
362 justReturnedNewline = true;
367 if (justReturnedNewline) {
368 justReturnedNewline = false;
370 final char firstChar = wikiText.charAt(end);
371 if (firstChar == '=') {
372 final int headerStart = end;
374 while (++end < len && wikiText.charAt(end) == '=') {}
375 final int headerTitleStart = end;
376 headingDepth = headerTitleStart - headerStart;
379 final int nextNewline = safeIndexOf(wikiText, end, "\n", "\n");
380 final int closingEquals = escapedFindEnd(end, "=");
381 if (wikiText.charAt(closingEquals - 1) == '=') {
382 end = closingEquals - 1;
387 final int headerTitleEnd = end;
388 headingWikiText = wikiText.substring(headerTitleStart, headerTitleEnd);
390 while (end < len && ++end < len && wikiText.charAt(end) == '=') {}
391 final int headerEnd = end;
392 if (headerEnd - headerTitleEnd != headingDepth) {
393 errors.add("Mismatched header depth: " + token());
397 if (listChars.indexOf(firstChar) != -1) {
398 while (++end < len && listChars.indexOf(wikiText.charAt(end)) != -1) {}
400 end = escapedFindEnd(start, "\n");
405 if (wikiText.startsWith("'''", start)) {
411 if (wikiText.startsWith("''", start)) {
417 if (wikiText.startsWith("[[", start)) {
418 end = escapedFindEnd(start + 2, "]]");
419 isWikiLink = errors.isEmpty();
423 if (wikiText.startsWith("{{", start)) {
424 end = escapedFindEnd(start + 2, "}}");
425 isFunction = errors.isEmpty();
429 if (wikiText.startsWith("<pre>", start)) {
430 end = safeIndexOf(wikiText, start, "</pre>", "\n");
435 if (wikiText.startsWith("<ref>", start)) {
436 end = safeIndexOf(wikiText, start, "</ref>", "\n");
441 if (wikiText.startsWith("<math>", start)) {
442 end = safeIndexOf(wikiText, start, "</math>", "\n");
447 if (wikiText.startsWith("<!--", start)) {
449 end = safeIndexOf(wikiText, start, "-->", "\n");
453 if (wikiText.startsWith("}}", start) || wikiText.startsWith("]]", start)) {
454 errors.add("Close without open!");
459 if (wikiText.charAt(start) == '|' || wikiText.charAt(start) == '=') {
466 while (end < wikiText.length()) {
467 int c = wikiText.charAt(end);
468 if (c == '\n' || c == '\'' || ((c - 0x1b) & 0xff9f) < 3) {
469 matcher.region(end, wikiText.length());
470 if (matcher.lookingAt()) break;
474 if (end != wikiText.length()) {
477 // stumbled over a new type of newline?
478 // Or matcher is out of sync with checks above
479 errors.add("Empty group: " + this.matcher.group() + " char: " + (int)wikiText.charAt(end));
481 // Note: all newlines should be normalize to \n before calling this function
482 throw new RuntimeException("matcher not in sync with code, or new type of newline, errors :" + errors);
491 if (!errors.isEmpty()) {
492 System.err.println("Errors: " + errors + ", token=" + token());
498 public String token() {
499 final String token = wikiText.substring(start, end);
500 assert token.equals("\n") || !token.endsWith("\n") : "token='" + token + "'";
504 static final String[] patterns = { "\n", "{{", "}}", "[[", "]]", "[", "]", "|", "=", "<!--" };
505 private int escapedFindEnd(final int start, final String toFind) {
506 assert tokenStack.isEmpty();
508 final boolean insideFunction = toFind.equals("}}");
511 int firstNewline = -1;
512 int[] nextMatch = new int[patterns.length];
513 Arrays.fill(nextMatch, -2);
514 int singleBrackets = 0;
515 while (end < wikiText.length()) {
516 // Manual replacement for matcher.find(end),
517 // because Java regexp is a ridiculously slow implementation.
518 // Initialize to always match the end.
520 for (int i = 0; i < nextMatch.length; ++i) {
521 if (nextMatch[i] <= end) {
522 nextMatch[i] = wikiText.indexOf(patterns[i], end);
523 if (nextMatch[i] == -1) nextMatch[i] = i > 0 ? 0x7fffffff : wikiText.length();
525 if (nextMatch[i] < nextMatch[matchIdx]) {
530 int matchStart = nextMatch[matchIdx];
531 String matchText = patterns[matchIdx];
532 int matchEnd = matchStart + matchText.length();
535 matchEnd = matchStart;
538 assert matchEnd > end || matchText.length() == 0: "Group=" + matchText;
539 if (matchText.length() == 0) {
540 assert matchStart == wikiText.length() || wikiText.charAt(matchStart) == '\n' : wikiText + ", " + matchStart;
541 if (firstNewline == -1) {
542 firstNewline = matchEnd;
544 if (tokenStack.isEmpty() && toFind.equals("\n")) {
548 } else if (tokenStack.isEmpty() && matchText.equals(toFind)) {
549 // The normal return....
550 if (insideFunction) {
551 addFunctionArg(insideFunction, matchStart);
554 } else if (matchText.equals("[")) {
556 } else if (matchText.equals("]")) {
557 if (singleBrackets > 0) singleBrackets--;
558 } else if (matchText.equals("[[") || matchText.equals("{{")) {
559 tokenStack.add(matchText);
560 } else if (matchText.equals("]]") || matchText.equals("}}")) {
561 if (tokenStack.size() > 0) {
562 final String removed = tokenStack.remove(tokenStack.size() - 1);
563 if (removed.equals("{{") && !matchText.equals("}}")) {
564 if (singleBrackets >= 2) { // assume this is really two closing single ]
566 tokenStack.add(removed);
568 errors.add("Unmatched {{ error: " + wikiText.substring(start, matchEnd));
569 return safeIndexOf(wikiText, start, "\n", "\n");
571 } else if (removed.equals("[[") && !matchText.equals("]]")) {
572 errors.add("Unmatched [[ error: " + wikiText.substring(start, matchEnd));
573 return safeIndexOf(wikiText, start, "\n", "\n");
576 errors.add("Pop too many " + matchText + " error: " + wikiText.substring(start, matchEnd).replace("\n", "\\\\n"));
577 // If we were looking for a newline
578 return safeIndexOf(wikiText, start, "\n", "\n");
580 } else if (matchText.equals("|")) {
581 if (tokenStack.isEmpty()) {
582 addFunctionArg(insideFunction, matchStart);
584 } else if (matchText.equals("=")) {
585 if (tokenStack.isEmpty()) {
586 lastUnescapedEqualsPos = matchStart;
588 // Do nothing. These can match spuriously, and if it's not the thing
589 // we're looking for, keep on going.
590 } else if (matchText.equals("<!--")) {
591 end = wikiText.indexOf("-->", matchStart);
593 errors.add("Unmatched <!-- error: " + wikiText.substring(start));
594 return safeIndexOf(wikiText, start, "\n", "\n");
596 } else if (matchText.equals("''") || (matchText.startsWith("<") && matchText.endsWith(">"))) {
599 assert false : "Match text='" + matchText + "'";
600 throw new IllegalStateException();
603 // Inside the while loop. Just go forward.
604 end = Math.max(end, matchEnd);
606 if (toFind.equals("\n") && tokenStack.isEmpty()) {
607 // We were looking for the end, we got it.
610 errors.add("Couldn't find: " + (toFind.equals("\n") ? "newline" : toFind) + ", "+ wikiText.substring(start));
611 if (firstNewline != -1) {
617 private void addFunctionArg(final boolean insideFunction, final int matchStart) {
618 if (firstUnescapedPipePos == -1) {
619 firstUnescapedPipePos = lastUnescapedPipePos = matchStart;
620 } else if (insideFunction) {
621 if (lastUnescapedEqualsPos > lastUnescapedPipePos) {
622 final String key = wikiText.substring(lastUnescapedPipePos + 1, lastUnescapedEqualsPos);
623 final String value = wikiText.substring(lastUnescapedEqualsPos + 1, matchStart);
624 namedArgs.put(trimNewlines(key), trimNewlines(value));
626 final String value = wikiText.substring(lastUnescapedPipePos + 1, matchStart);
627 positionArgs.add(trimNewlines(value));
630 lastUnescapedPipePos = matchStart;
633 static String trimNewlines(String s) {
634 while (s.startsWith("\n")) {
637 while (s.endsWith("\n")) {
638 s = s.substring(0, s.length() - 1);
640 return s.replace('\n', ' ');
643 static int safeIndexOf(final String s, final int start, final String target, final String backup) {
644 int close = s.indexOf(target, start);
646 // Don't step over a \n.
647 return close + (target.equals("\n") ? 0 : target.length());
649 close = s.indexOf(backup, start);
651 return close + (backup.equals("\n") ? 0 : backup.length());
656 public static String toPlainText(final String wikiText) {
657 final WikiTokenizer wikiTokenizer = new WikiTokenizer(wikiText);
658 final StringBuilder builder = new StringBuilder();
659 while (wikiTokenizer.nextToken() != null) {
660 if (wikiTokenizer.isPlainText()) {
661 builder.append(wikiTokenizer.token());
662 } else if (wikiTokenizer.isWikiLink()) {
663 builder.append(wikiTokenizer.wikiLinkText());
664 } else if (wikiTokenizer.isNewline()) {
665 builder.append("\n");
666 } else if (wikiTokenizer.isFunction()) {
667 builder.append(wikiTokenizer.token());
670 return builder.toString();
673 public static StringBuilder appendFunction(final StringBuilder builder, final String name, List<String> args,
674 final Map<String, String> namedArgs) {
675 builder.append(name);
676 for (final String arg : args) {
677 builder.append("|").append(arg);
679 for (final Map.Entry<String, String> entry : namedArgs.entrySet()) {
680 builder.append("|").append(entry.getKey()).append("=").append(entry.getValue());