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 if (this.matcher.find(start)) {
467 end = this.matcher.start();
470 // stumbled over a new type of newline?
471 // Or matcher is out of sync with checks above
472 errors.add("Empty group: " + this.matcher.group() + " char: " + (int)wikiText.charAt(end));
474 // Note: all newlines should be normalize to \n before calling this function
475 throw new RuntimeException("matcher not in sync with code, or new type of newline, errors :" + errors);
480 end = wikiText.length();
485 if (!errors.isEmpty()) {
486 System.err.println("Errors: " + errors + ", token=" + token());
492 public String token() {
493 final String token = wikiText.substring(start, end);
494 assert token.equals("\n") || !token.endsWith("\n") : "token='" + token + "'";
498 static final String[] patterns = { "\n", "{{", "}}", "[[", "]]", "[", "]", "|", "=", "<!--" };
499 private int escapedFindEnd(final int start, final String toFind) {
500 assert tokenStack.isEmpty();
502 final boolean insideFunction = toFind.equals("}}");
505 int firstNewline = -1;
506 int[] nextMatch = new int[patterns.length];
507 Arrays.fill(nextMatch, -2);
508 int singleBrackets = 0;
509 while (end < wikiText.length()) {
510 // Manual replacement for matcher.find(end),
511 // because Java regexp is a ridiculously slow implementation.
512 // Initialize to always match the end.
514 for (int i = 0; i < nextMatch.length; ++i) {
515 if (nextMatch[i] <= end) {
516 nextMatch[i] = wikiText.indexOf(patterns[i], end);
517 if (nextMatch[i] == -1) nextMatch[i] = i > 0 ? 0x7fffffff : wikiText.length();
519 if (nextMatch[i] < nextMatch[matchIdx]) {
524 int matchStart = nextMatch[matchIdx];
525 String matchText = patterns[matchIdx];
526 int matchEnd = matchStart + matchText.length();
529 matchEnd = matchStart;
532 assert matchEnd > end || matchText.length() == 0: "Group=" + matchText;
533 if (matchText.length() == 0) {
534 assert matchStart == wikiText.length() || wikiText.charAt(matchStart) == '\n' : wikiText + ", " + matchStart;
535 if (firstNewline == -1) {
536 firstNewline = matchEnd;
538 if (tokenStack.isEmpty() && toFind.equals("\n")) {
542 } else if (tokenStack.isEmpty() && matchText.equals(toFind)) {
543 // The normal return....
544 if (insideFunction) {
545 addFunctionArg(insideFunction, matchStart);
548 } else if (matchText.equals("[")) {
550 } else if (matchText.equals("]")) {
551 if (singleBrackets > 0) singleBrackets--;
552 } else if (matchText.equals("[[") || matchText.equals("{{")) {
553 tokenStack.add(matchText);
554 } else if (matchText.equals("]]") || matchText.equals("}}")) {
555 if (tokenStack.size() > 0) {
556 final String removed = tokenStack.remove(tokenStack.size() - 1);
557 if (removed.equals("{{") && !matchText.equals("}}")) {
558 if (singleBrackets >= 2) { // assume this is really two closing single ]
560 tokenStack.add(removed);
562 errors.add("Unmatched {{ error: " + wikiText.substring(start, matchEnd));
563 return safeIndexOf(wikiText, start, "\n", "\n");
565 } else if (removed.equals("[[") && !matchText.equals("]]")) {
566 errors.add("Unmatched [[ error: " + wikiText.substring(start, matchEnd));
567 return safeIndexOf(wikiText, start, "\n", "\n");
570 errors.add("Pop too many " + matchText + " error: " + wikiText.substring(start, matchEnd).replace("\n", "\\\\n"));
571 // If we were looking for a newline
572 return safeIndexOf(wikiText, start, "\n", "\n");
574 } else if (matchText.equals("|")) {
575 if (tokenStack.isEmpty()) {
576 addFunctionArg(insideFunction, matchStart);
578 } else if (matchText.equals("=")) {
579 if (tokenStack.isEmpty()) {
580 lastUnescapedEqualsPos = matchStart;
582 // Do nothing. These can match spuriously, and if it's not the thing
583 // we're looking for, keep on going.
584 } else if (matchText.equals("<!--")) {
585 end = wikiText.indexOf("-->", matchStart);
587 errors.add("Unmatched <!-- error: " + wikiText.substring(start));
588 return safeIndexOf(wikiText, start, "\n", "\n");
590 } else if (matchText.equals("''") || (matchText.startsWith("<") && matchText.endsWith(">"))) {
593 assert false : "Match text='" + matchText + "'";
594 throw new IllegalStateException();
597 // Inside the while loop. Just go forward.
598 end = Math.max(end, matchEnd);
600 if (toFind.equals("\n") && tokenStack.isEmpty()) {
601 // We were looking for the end, we got it.
604 errors.add("Couldn't find: " + (toFind.equals("\n") ? "newline" : toFind) + ", "+ wikiText.substring(start));
605 if (firstNewline != -1) {
611 private void addFunctionArg(final boolean insideFunction, final int matchStart) {
612 if (firstUnescapedPipePos == -1) {
613 firstUnescapedPipePos = lastUnescapedPipePos = matchStart;
614 } else if (insideFunction) {
615 if (lastUnescapedEqualsPos > lastUnescapedPipePos) {
616 final String key = wikiText.substring(lastUnescapedPipePos + 1, lastUnescapedEqualsPos);
617 final String value = wikiText.substring(lastUnescapedEqualsPos + 1, matchStart);
618 namedArgs.put(trimNewlines(key), trimNewlines(value));
620 final String value = wikiText.substring(lastUnescapedPipePos + 1, matchStart);
621 positionArgs.add(trimNewlines(value));
624 lastUnescapedPipePos = matchStart;
627 static String trimNewlines(String s) {
628 while (s.startsWith("\n")) {
631 while (s.endsWith("\n")) {
632 s = s.substring(0, s.length() - 1);
634 return s.replace('\n', ' ');
637 static int safeIndexOf(final String s, final int start, final String target, final String backup) {
638 int close = s.indexOf(target, start);
640 // Don't step over a \n.
641 return close + (target.equals("\n") ? 0 : target.length());
643 close = s.indexOf(backup, start);
645 return close + (backup.equals("\n") ? 0 : backup.length());
650 public static String toPlainText(final String wikiText) {
651 final WikiTokenizer wikiTokenizer = new WikiTokenizer(wikiText);
652 final StringBuilder builder = new StringBuilder();
653 while (wikiTokenizer.nextToken() != null) {
654 if (wikiTokenizer.isPlainText()) {
655 builder.append(wikiTokenizer.token());
656 } else if (wikiTokenizer.isWikiLink()) {
657 builder.append(wikiTokenizer.wikiLinkText());
658 } else if (wikiTokenizer.isNewline()) {
659 builder.append("\n");
660 } else if (wikiTokenizer.isFunction()) {
661 builder.append(wikiTokenizer.token());
664 return builder.toString();
667 public static StringBuilder appendFunction(final StringBuilder builder, final String name, List<String> args,
668 final Map<String, String> namedArgs) {
669 builder.append(name);
670 for (final String arg : args) {
671 builder.append("|").append(arg);
673 for (final Map.Entry<String, String> entry : namedArgs.entrySet()) {
674 builder.append("|").append(entry.getKey()).append("=").append(entry.getValue());