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;
17 import java.util.ArrayList;
18 import java.util.LinkedHashMap;
19 import java.util.List;
21 import java.util.regex.Matcher;
22 import java.util.regex.Pattern;
24 public final class WikiTokenizer {
26 //private static final Pattern wikiTokenEvent = Pattern.compile("($)", Pattern.MULTILINE);
27 private static final Pattern wikiTokenEvent = Pattern.compile("(" +
30 "\\||" + // Need the | because we might have to find unescaped pipes
31 "=|" + // Need the = because we might have to find unescaped =
34 "$)", Pattern.MULTILINE);
35 private static final String listChars = "*#:;";
38 final String wikiText;
39 final Matcher matcher;
41 boolean justReturnedNewline = true;
42 int lastLineStart = 0;
46 final List<String> errors = new ArrayList<String>();
47 final List<String> tokenStack = new ArrayList<String>();
50 private String headingWikiText;
51 private int headingDepth;
52 private int listPrefixEnd;
53 private boolean isPlainText;
54 private boolean isMarkup;
55 private boolean isComment;
56 private boolean isFunction;
57 private boolean isWikiLink;
58 private int firstUnescapedPipePos;
60 private int lastUnescapedPipePos;
61 private int lastUnescapedEqualsPos;
62 private final List<String> positionArgs = new ArrayList<String>();
63 private final Map<String,String> namedArgs = new LinkedHashMap<String,String>();
66 public WikiTokenizer(final String wikiText) {
70 public WikiTokenizer(final String wikiText, final boolean isNewline) {
71 this.wikiText = wikiText;
72 this.matcher = wikiTokenEvent.matcher(wikiText);
73 justReturnedNewline = isNewline;
76 private void clear() {
80 headingWikiText = null;
89 firstUnescapedPipePos = -1;
90 lastUnescapedPipePos = -1;
91 lastUnescapedEqualsPos = -1;
96 public boolean isNewline() {
97 return justReturnedNewline;
100 public void returnToLineStart() {
101 end = start = lastLineStart;
102 justReturnedNewline = true;
105 public boolean isHeading() {
106 return headingWikiText != null;
109 public String headingWikiText() {
111 return headingWikiText;
114 public int headingDepth() {
119 public boolean isMarkup() {
123 public boolean isComment() {
127 public boolean isListItem() {
128 return listPrefixEnd != -1;
131 public String listItemPrefix() {
133 return wikiText.substring(start, listPrefixEnd);
136 public String listItemWikiText() {
138 return wikiText.substring(listPrefixEnd, end);
141 public boolean isFunction() {
145 public String functionName() {
148 if (firstUnescapedPipePos != -1) {
149 return wikiText.substring(start + 2, firstUnescapedPipePos);
151 return wikiText.substring(start + 2, end - 2);
154 public List<String> functionPositionArgs() {
158 public Map<String, String> functionNamedArgs() {
162 public boolean isPlainText() {
166 public boolean isWikiLink() {
170 public String wikiLinkText() {
173 if (lastUnescapedPipePos != -1) {
174 return wikiText.substring(lastUnescapedPipePos + 1, end - 2);
176 return wikiText.substring(start + 2, end - 2);
179 public String wikiLinkDest() {
182 if (firstUnescapedPipePos != -1) {
183 return wikiText.substring(start + 2, firstUnescapedPipePos);
188 public boolean remainderStartsWith(final String prefix) {
189 return wikiText.startsWith(prefix, start);
192 public void nextLine() {
193 final int oldStart = start;
194 while(nextToken() != null && !isNewline()) {}
202 public WikiTokenizer nextToken() {
207 if (justReturnedNewline) {
208 lastLineStart = start;
213 final int len = wikiText.length();
218 // Eat a newline if we're looking at one:
219 final boolean atNewline = wikiText.charAt(end) == '\n' || wikiText.charAt(end) == '\u2028';
221 justReturnedNewline = true;
226 if (justReturnedNewline) {
227 justReturnedNewline = false;
229 final char firstChar = wikiText.charAt(end);
230 if (firstChar == '=') {
231 final int headerStart = end;
233 while (++end < len && wikiText.charAt(end) == '=') {}
234 final int headerTitleStart = end;
235 headingDepth = headerTitleStart - headerStart;
238 final int nextNewline = safeIndexOf(wikiText, end, "\n", "\n");
239 final int closingEquals = escapedFindEnd(end, "=");
240 if (wikiText.charAt(closingEquals - 1) == '=') {
241 end = closingEquals - 1;
246 final int headerTitleEnd = end;
247 headingWikiText = wikiText.substring(headerTitleStart, headerTitleEnd);
249 while (end < len && ++end < len && wikiText.charAt(end) == '=') {}
250 final int headerEnd = end;
251 if (headerEnd - headerTitleEnd != headingDepth) {
252 errors.add("Mismatched header depth: " + token());
256 if (listChars.indexOf(firstChar) != -1) {
257 while (++end < len && listChars.indexOf(wikiText.charAt(end)) != -1) {}
259 end = escapedFindEnd(start, "\n");
264 if (wikiText.startsWith("'''", start)) {
270 if (wikiText.startsWith("''", start)) {
276 if (wikiText.startsWith("[[", start)) {
277 end = escapedFindEnd(start + 2, "]]");
278 isWikiLink = errors.isEmpty();
282 if (wikiText.startsWith("{{", start)) {
283 end = escapedFindEnd(start + 2, "}}");
284 isFunction = errors.isEmpty();
288 if (wikiText.startsWith("<pre>", start)) {
289 end = safeIndexOf(wikiText, start, "</pre>", "\n");
293 if (wikiText.startsWith("<math>", start)) {
294 end = safeIndexOf(wikiText, start, "</math>", "\n");
298 if (wikiText.startsWith("<!--", start)) {
300 end = safeIndexOf(wikiText, start, "-->", "\n");
304 if (wikiText.startsWith("}}", start) || wikiText.startsWith("]]", start)) {
305 errors.add("Close without open!");
310 if (wikiText.charAt(start) == '|' || wikiText.charAt(start) == '=') {
317 if (this.matcher.find(start)) {
318 end = this.matcher.start(1);
321 errors.add("Empty group: " + this.matcher.group());
327 end = wikiText.length();
331 if (!errors.isEmpty()) {
332 System.err.println("Errors: " + errors + ", token=" + token());
338 public String token() {
339 final String token = wikiText.substring(start, end);
340 assert token.equals("\n") || !token.endsWith("\n") : token;
344 private int escapedFindEnd(final int start, final String toFind) {
345 assert tokenStack.isEmpty();
347 final boolean insideFunction = toFind.equals("}}");
350 while (end < wikiText.length()) {
351 if (matcher.find(end)) {
352 final String matchText = matcher.group();
353 final int matchStart = matcher.start();
355 assert matcher.end() > end || matchText.length() == 0: "Group=" + matcher.group();
356 if (matchText.length() == 0) {
357 assert matchStart == wikiText.length() || wikiText.charAt(matchStart) == '\n';
358 if (tokenStack.isEmpty() && toFind.equals("\n")) {
362 } else if (tokenStack.isEmpty() && matchText.equals(toFind)) {
363 // The normal return....
364 if (insideFunction) {
365 addFunctionArg(insideFunction, matchStart);
367 return matcher.end();
368 } else if (matchText.equals("[[") || matchText.equals("{{")) {
369 tokenStack.add(matchText);
370 } else if (matchText.equals("]]") || matchText.equals("}}")) {
371 if (tokenStack.size() > 0) {
372 final String removed = tokenStack.remove(tokenStack.size() - 1);
373 if (removed.equals("{{") && !matcher.group().equals("}}")) {
374 errors.add("Unmatched {{ error: " + wikiText.substring(start));
375 return safeIndexOf(wikiText, start, "\n", "\n");
376 } else if (removed.equals("[[") && !matcher.group().equals("]]")) {
377 errors.add("Unmatched [[ error: " + wikiText.substring(start));
378 return safeIndexOf(wikiText, start, "\n", "\n");
381 errors.add("Pop too many error: " + wikiText.substring(start).replaceAll("\n", "\\\\n"));
382 // If we were looking for a newline
383 return safeIndexOf(wikiText, start, "\n", "\n");
385 } else if (matchText.equals("|")) {
386 if (tokenStack.isEmpty()) {
387 addFunctionArg(insideFunction, matchStart);
389 } else if (matchText.equals("=")) {
390 if (tokenStack.isEmpty()) {
391 lastUnescapedEqualsPos = matchStart;
393 // Do nothing. These can match spuriously, and if it's not the thing
394 // we're looking for, keep on going.
395 } else if (matchText.equals("<!--")) {
396 end = wikiText.indexOf("-->");
398 errors.add("Unmatched <!-- error: " + wikiText.substring(start));
399 return safeIndexOf(wikiText, start, "\n", "\n");
401 } else if (matchText.equals("''")) {
404 assert false : "Match text='" + matchText + "'";
405 throw new IllegalStateException();
408 // Hmmm, we didn't find the closing symbol we were looking for...
409 errors.add("Couldn't find: " + toFind + ", "+ wikiText.substring(start));
410 return safeIndexOf(wikiText, start, "\n", "\n");
413 // Inside the while loop. Just go forward.
414 end = Math.max(end, matcher.end());
419 private void addFunctionArg(final boolean insideFunction, final int matchStart) {
420 if (firstUnescapedPipePos == -1) {
421 firstUnescapedPipePos = lastUnescapedPipePos = matchStart;
422 } else if (insideFunction) {
423 if (lastUnescapedEqualsPos > lastUnescapedPipePos) {
424 final String key = wikiText.substring(lastUnescapedPipePos + 1, lastUnescapedEqualsPos);
425 final String value = wikiText.substring(lastUnescapedEqualsPos + 1, matchStart);
426 namedArgs.put(key, value);
428 final String value = wikiText.substring(lastUnescapedPipePos + 1, matchStart);
429 positionArgs.add(value);
432 lastUnescapedPipePos = matchStart;
435 static int safeIndexOf(final String s, final int start, final String target, final String backup) {
436 int close = s.indexOf(target, start);
438 // Don't step over a \n.
439 return close + (target.equals("\n") ? 0 : target.length());
441 close = s.indexOf(backup, start);
443 return close + (backup.equals("\n") ? 0 : backup.length());
448 public static String toPlainText(String sense) {
449 final WikiTokenizer wikiTokenizer = new WikiTokenizer(sense);
450 final StringBuilder builder = new StringBuilder();
451 while (wikiTokenizer.nextToken() != null) {
452 if (wikiTokenizer.isPlainText()) {
453 builder.append(wikiTokenizer.token());
454 } else if (wikiTokenizer.isWikiLink()) {
455 builder.append(wikiTokenizer.wikiLinkText());
456 } else if (wikiTokenizer.isNewline()) {
457 builder.append("\n");
458 } else if (wikiTokenizer.isFunction()) {
459 builder.append(wikiTokenizer.token());
462 return builder.toString();