summaryrefslogtreecommitdiffstats
path: root/JLanguageTool/src/java/de/danielnaber/languagetool/rules/patterns/PatternRule.java
blob: 843ef9817e931a327cd93a31896a4d232c1fede0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
/* LanguageTool, a natural language style checker 
 * Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de)
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301
 * USA
 */
package de.danielnaber.languagetool.rules.patterns;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import de.danielnaber.languagetool.AnalyzedSentence;
import de.danielnaber.languagetool.AnalyzedTokenReadings;
import de.danielnaber.languagetool.Language;
import de.danielnaber.languagetool.rules.IncorrectExample;
import de.danielnaber.languagetool.rules.RuleMatch;
import de.danielnaber.languagetool.tools.StringTools;

/**
 * A Rule that describes a language error as a simple pattern of words or of
 * part-of-speech tags.
 * 
 * @author Daniel Naber
 */
public class PatternRule extends AbstractPatternRule {

  private static final String SUGG_TAG = "<suggestion>";
  private static final String END_SUGG_TAG = "</suggestion>";

  private String subId; // because there can be more than one rule in a rule
  // group

  private String message;
  private String shortMessage;

  /** Formatted suggestion elements. **/
  private List<Match> suggestionMatches;

  /**
   * A list of elements as they appear in XML file (phrases count as single
   * tokens in case of matches or skipping).
   */
  private List<Integer> elementNo;

  /**
   * This property is used for short-circuiting evaluation of the elementNo list
   * order.
   */
  private boolean useList;

  /**
   * Marks whether the rule is a member of a disjunctive set (in case of OR
   * operation on phraserefs).
   **/
  private boolean isMemberOfDisjunctiveSet;

  /**
   * @param id
   *          Id of the Rule
   * @param language
   *          Language of the Rule
   * @param elements
   *          Element (token) list
   * @param description
   *          Description to be shown (name)
   * @param message
   *          Message to be displayed to the user
   */

  public PatternRule(final String id, final Language language,
      final List<Element> elements, final String description,
      final String message, final String shortMessage) {
    super(id, description, language, elements, false);
    if (id == null) {
      throw new NullPointerException("id cannot be null");
    }
    if (language == null) {
      throw new NullPointerException("language cannot be null");
    }
    if (elements == null) {
      throw new NullPointerException("elements cannot be null");
    }
    if (description == null) {
      throw new NullPointerException("description cannot be null");
    }

    this.message = message;
    this.shortMessage = shortMessage;
    this.elementNo = new ArrayList<Integer>();
    String prevName = "";
    String curName = "";
    int cnt = 0;
    int loopCnt = 0;
    for (final Element e : patternElements) {
      if (e.isPartOfPhrase()) {
        curName = e.getPhraseName();
        if (prevName.equals(curName) || StringTools.isEmpty(prevName)) {
          cnt++;
          useList = true;
        } else {
          elementNo.add(cnt);
          prevName = "";
          curName = "";
          cnt = 0;
        }
        prevName = curName;
        loopCnt++;
        if (loopCnt == patternElements.size() && !StringTools.isEmpty(prevName)) {
          elementNo.add(cnt);
        }
      } else {
        if (cnt > 0) {
          elementNo.add(cnt);
        }
        elementNo.add(1);
        loopCnt++;
      }
    }    
  }  

  public PatternRule(final String id, final Language language,
      final List<Element> elements, final String description,
      final String message, final String shortMessage, final boolean isMember) {
    this(id, language, elements, description, message, shortMessage);
    this.isMemberOfDisjunctiveSet = isMember;
  }  

  public final String getSubId() {
    return subId;
  }

  public final void setSubId(final String subId) {
    this.subId = subId;
  }

  public final String getMessage() {
    return message;
  }

  /**
   * Used for testing rules: only one of the set can match.
   * 
   * @return Whether the rule can non-match (as a member of disjunctive set of
   *         rules generated by phraseref in includephrases element).
   */
  public final boolean isWithComplexPhrase() {
    return isMemberOfDisjunctiveSet;
  }

  /** Reset complex status - used for testing. **/
  public final void notComplexPhrase() {
    isMemberOfDisjunctiveSet = false;
  }

  /**
   * Return the pattern as a string.
   * 
   * @since 0.9.2
   */
  public final String toPatternString() {
    final List<String> strList = new ArrayList<String>();
    for (Element patternElement : patternElements) {
      strList.add(patternElement.toString());
    }
    return StringTools.listToString(strList, ", ");
  }

  /**
   * Return the pattern as an XML string. FIXME: this is not complete, information might be lost!
   * 
   * @since 0.9.3
   */
  public final String toXML() {
    final StringBuilder sb = new StringBuilder();
    sb.append("<rule id=\"");
    sb.append(StringTools.escapeXML(getId()));
    sb.append("\" name=\"");
    sb.append(StringTools.escapeXML(getDescription()));
    sb.append("\">\n");
    sb.append("<pattern mark_from=\"");
    sb.append(startPositionCorrection);
    sb.append("\" mark_to=\"");
    sb.append(endPositionCorrection);
    sb.append('"');
    // for now, case sensitivity is per pattern, not per element,
    // so just use the setting of the first element:
    if (!patternElements.isEmpty() && patternElements.get(0).getCaseSensitive()) {
      sb.append(" case_sensitive=\"yes\"");
    }
    sb.append(">\n");
    for (Element patternElement : patternElements) {
      sb.append("<token");
      if (patternElement.getNegation()) {
        sb.append(" negate=\"yes\"");
      }
      if (patternElement.isRegularExpression()) {
        sb.append(" regexp=\"yes\"");
      }
      if (patternElement.getPOStag() != null) {
        sb.append(" postag=\"");
        sb.append(patternElement.getPOStag());
        sb.append('"');
      }
      if (patternElement.getPOSNegation()) {
        sb.append(" negate_pos=\"yes\"");
      }
      if (patternElement.isInflected()) {
        sb.append(" inflected=\"yes\"");
      }
      sb.append('>');
      if (patternElement.getString() != null) {
        sb.append(StringTools.escapeXML(patternElement.getString()));
      } else {
        // TODO
      }
      sb.append("</token>\n");
    }
    sb.append("</pattern>\n");
    sb.append("<message>");
    sb.append(StringTools.escapeXML(message));
    sb.append("</message>\n");
    if (getIncorrectExamples() != null) {
      for (IncorrectExample example : getIncorrectExamples()) {
        sb.append("<example type=\"incorrect\">");
        sb.append(StringTools.escapeXML(example.getExample()));
        sb.append("</example>\n");
      }
    }
    if (getCorrectExamples() != null) {
      for (String example : getCorrectExamples()) {
        sb.append("<example type=\"correct\">");
        sb.append(StringTools.escapeXML(example));
        sb.append("</example>\n");
      }
    }
    sb.append("</rule>");
    return sb.toString();
  }

  public final void setMessage(final String message) {
    this.message = message;
  }

  @Override
  public final RuleMatch[] match(final AnalyzedSentence text)
  throws IOException {
    final List<RuleMatch> ruleMatches = new ArrayList<RuleMatch>();
    final AnalyzedTokenReadings[] tokens = text.getTokensWithoutWhitespace();
    final int[] tokenPositions = new int[tokens.length + 1];
    final int patternSize = patternElements.size();
    final int limit = Math.max(0, tokens.length - patternSize + 1);
    Element elem = null;
    int i = 0;
    while (i < limit && !(sentStart && i > 0)) {
      boolean allElementsMatch = false;
      int firstMatchToken = -1;
      int lastMatchToken = -1;
      int matchingTokens = 0;
      int prevSkipNext = 0;
      // this variable keeps the total number
      // of tokens skipped
      int skipShiftTotal = 0;
      if (testUnification) {
        unifier.reset();
      }
      for (int k = 0; k < patternSize; k++) {
        final Element prevElement = elem;
        elem = patternElements.get(k);
        setupRef(firstMatchToken, elem, tokens);
        final int nextPos = i + k + skipShiftTotal;
        prevMatched = false;
        if (prevSkipNext + nextPos >= tokens.length || prevSkipNext < 0) { // SENT_END?
          prevSkipNext = tokens.length - (nextPos + 1);
        }        
        final int maxTok = Math.min(nextPos + prevSkipNext, tokens.length - (patternSize - k));
        for (int m = nextPos; m <= maxTok; m++) {
          allElementsMatch = testAllReadings(tokens, elem, prevElement, m,
              firstMatchToken, prevSkipNext);
          if (allElementsMatch) {
            lastMatchToken = m;
            final int skipShift = lastMatchToken - nextPos;
            tokenPositions[matchingTokens] = skipShift + 1;
            prevSkipNext = translateElementNo(elem.getSkipNext());
            matchingTokens++;
            skipShiftTotal += skipShift;
            if (firstMatchToken == -1) {
              firstMatchToken = lastMatchToken;              
            }
            break;
          }          
        }
        if (!allElementsMatch) {
          break;
        }
      }

      if (allElementsMatch && matchingTokens == patternSize) {
        final RuleMatch rM = createRuleMatch(tokenPositions, tokens,
            firstMatchToken, lastMatchToken, matchingTokens);
        if (rM != null) {
          ruleMatches.add(rM);
        }
      }
      i++;
    }
    return ruleMatches.toArray(new RuleMatch[ruleMatches.size()]);
  }

  private RuleMatch createRuleMatch(final int[] tokenPositions,
      final AnalyzedTokenReadings[] tokens, final int firstMatchToken,
      final int lastMatchToken, final int matchingTokens) throws IOException {
    final String errMessage = formatMatches(tokens, tokenPositions,
        firstMatchToken, message);
    int correctedStPos = 0;
    if (startPositionCorrection > 0) {
      for (int l = 0; l <= startPositionCorrection; l++) {
        correctedStPos += tokenPositions[l];
      }
      correctedStPos--;
    }
    int correctedEndPos = 0;
    if (endPositionCorrection < 0) {
      int l = 0;
      while (l > endPositionCorrection) {
        correctedEndPos -= tokenPositions[matchingTokens + l - 1];
        l--;
      }
    }
    AnalyzedTokenReadings firstMatchTokenObj = tokens[firstMatchToken
                                                      + correctedStPos];
    boolean startsWithUppercase = StringTools
    .startsWithUppercase(firstMatchTokenObj.getToken())
    && !matchConvertsCase();

    if (firstMatchTokenObj.isSentStart()
        && tokens.length > firstMatchToken + correctedStPos + 1) {
      // make uppercasing work also at sentence start:
      firstMatchTokenObj = tokens[firstMatchToken + correctedStPos + 1];
      startsWithUppercase = StringTools.startsWithUppercase(firstMatchTokenObj
          .getToken());
    }
    int fromPos = tokens[firstMatchToken + correctedStPos].getStartPos();
    // FIXME: this is fishy, assumes that comma should always come before
    // whitespace
    if (errMessage.contains(SUGG_TAG + ",")
        && firstMatchToken + correctedStPos >= 1) {
      fromPos = tokens[firstMatchToken + correctedStPos - 1].getStartPos()
      + tokens[firstMatchToken + correctedStPos - 1].getToken().length();
    }

    final int toPos = tokens[lastMatchToken + correctedEndPos].getStartPos()
    + tokens[lastMatchToken + correctedEndPos].getToken().length();
    if (fromPos < toPos) { // this can happen with some skip="-1" when the last
      // token is not matched
      return new RuleMatch(this, fromPos, toPos,
          errMessage, shortMessage, startsWithUppercase);
    } // failed to create any rule match...
    return null;
  }

  /**
   * Checks if the suggestion starts with a match that is supposed to convert
   * case. If it does, stop the default conversion to uppercase.
   * 
   * @return true, if the match converts the case of the token.
   */
  private boolean matchConvertsCase() {
	  if (suggestionMatches != null && !suggestionMatches.isEmpty()) {
		  final int sugStart = message.indexOf(SUGG_TAG) + SUGG_TAG.length();
		  for (Match sMatch : suggestionMatches) {
			  if (!sMatch.isInMessageOnly() && sMatch.convertsCase()
					  && message.charAt(sugStart) == '\\') {
				  return true;
			  }
		  }
	  }
	  return false;
  }

  public final void addSuggestionMatch(final Match m) {
    if (suggestionMatches == null) {
      suggestionMatches = new ArrayList<Match>();
    }
    suggestionMatches.add(m);
  }

  /**
   * Gets the index of the element indexed by i, adding any offsets because of
   * the phrases in the rule.
   * 
   * @param i
   *          Current element index.
   * @return int Index translated into XML element no.
   */
  private int translateElementNo(final int i) {
    if (!useList || i < 0) {
      return i;
    }
    int j = 0;
    for (int k = 0; k < i; k++) {
      j += elementNo.get(k);
    }
    return j;
  }

  /**
   * Returns true when the token in the rule references a phrase composed of
   * many tokens.
   * 
   * @param i
   *          The index of the token.
   * @return true if the phrase is under the index, false otherwise.
   **/
  private int phraseLen(final int i) {
    if (!useList || i > (elementNo.size() - 1)) {
      return 1;
    }
    return elementNo.get(i);
  }

  /**
   * Creates a Cartesian product of the arrays stored in the input array.
   * 
   * @param input
   *          Array of string arrays to combine.
   * @param output
   *          Work array of strings.
   * @param r
   *          Starting parameter (use 0 to get all combinations).
   * @param lang
   *          Text language for adding spaces in some languages.
   * @return Combined array of @String.
   */
  private static String[] combineLists(final String[][] input,
      final String[] output, final int r, final Language lang) {
    final List<String> outputList = new ArrayList<String>();
    if (r == input.length) {
      final StringBuilder sb = new StringBuilder();
      for (int k = 0; k < output.length; k++) {
        sb.append(output[k]);
        if (k < output.length - 1) {
          sb.append(StringTools.addSpace(output[k + 1], lang));
        }
      }
      outputList.add(sb.toString());
    } else {
      for (int c = 0; c < input[r].length; c++) {
        output[r] = input[r][c];
        final String[] sList = combineLists(input, output, r + 1, lang);
        outputList.addAll(Arrays.asList(sList));
      }
    }
    return outputList.toArray(new String[outputList.size()]);
  }

  /**
   * Concatenates the matches, and takes care of phrases (including inflection
   * using synthesis).
   * 
   * @param start
   *          Position of the element as referenced by match element in the
   *          rule.
   * @param index
   *          The index of the element found in the matching sentence.
   * @param tokenIndex
   *          The position of the token in the AnalyzedTokenReadings array.
   * @param tokens
   *          Array of @AnalyzedTokenReadings
   * @return @String[] Array of concatenated strings
   * @throws IOException
   *           in case disk operations (used in synthesizer) go wrong.
   */
  private String[] concatMatches(final int start, final int index,
      final int tokenIndex, final AnalyzedTokenReadings[] tokens,
      final int nextTokenPos)
  throws IOException {
    String[] finalMatch = null;
    if (suggestionMatches.get(start) != null) {
      final int len = phraseLen(index);
      if (len == 1) {
        final int skippedTokens = nextTokenPos - tokenIndex;
        suggestionMatches.get(start).setToken(tokens, tokenIndex - 1, skippedTokens);
        suggestionMatches.get(start).setSynthesizer(language.getSynthesizer());
        finalMatch = suggestionMatches.get(start).toFinalString();
      } else {
        final List<String[]> matchList = new ArrayList<String[]>();
        for (int i = 0; i < len; i++) {
          final int skippedTokens = nextTokenPos - (tokenIndex + i);
          suggestionMatches.get(start).setToken(tokens, tokenIndex - 1 + i, skippedTokens);          
          suggestionMatches.get(start)
          .setSynthesizer(language.getSynthesizer());
          matchList.add(suggestionMatches.get(start).toFinalString());
        }
        return combineLists(matchList.toArray(new String[matchList.size()][]),
            new String[matchList.size()], 0, language);
      }
    }
    return finalMatch;
  }

  /**
   * Replace back references generated with &lt;match&gt; and \\1 in message
   * using Match class, and take care of skipping. *
   * 
   * @param tokenReadings
   *          Array of AnalyzedTokenReadings that were matched against the
   *          pattern
   * @param positions
   *          Array of relative positions of matched tokens
   * @param firstMatchTok
   *          Position of the first matched token
   * @param errorMsg
   *          String containing suggestion markup
   * @return String Formatted message.
   * @throws IOException
   * 
   **/
  private String formatMatches(final AnalyzedTokenReadings[] tokenReadings,
      final int[] positions, final int firstMatchTok, final String errorMsg)
  throws IOException {
    String errorMessage = errorMsg;
    int matchCounter = 0;
    final int[] numbersToMatches = new int[errorMsg.length()];
    boolean newWay = false;
    int errLen = errorMessage.length();
    int errMarker = errorMessage.indexOf('\\');
    boolean numberFollows = false;
    if (errMarker > 0 && errMarker < errLen - 1) {
      numberFollows = StringTools.isPositiveNumber(errorMessage
          .charAt(errMarker + 1));
    }
    while (errMarker > 0 && numberFollows) {
      final int ind = errorMessage.indexOf('\\');
      if (ind > 0 && StringTools.isPositiveNumber(errorMessage.charAt(ind + 1))) {
        int numLen = 1;
        while (ind + numLen < errorMessage.length()
            && StringTools.isPositiveNumber(errorMessage.charAt(ind + numLen))) {
          numLen++;
        }
        final int j = Integer.parseInt(errorMessage.substring(ind + 1, ind
            + numLen)) - 1;
        int repTokenPos = 0;
        int nextTokenPos = 0;
        for (int l = 0; l <= j; l++) {
          repTokenPos += positions[l];
        }
        if (j <= positions.length) {
          nextTokenPos = firstMatchTok + repTokenPos + positions[j + 1];
        }
        if (suggestionMatches != null) {
          if (matchCounter < suggestionMatches.size()) {
            numbersToMatches[j] = matchCounter;
            if (suggestionMatches.get(matchCounter) != null) {
              final String[] matches = concatMatches(matchCounter, j,
                  firstMatchTok + repTokenPos, tokenReadings, nextTokenPos);
              final String leftSide = errorMessage.substring(0, ind);
              final String rightSide = errorMessage.substring(ind + numLen);
              if (matches.length == 1) {
                errorMessage = leftSide + matches[0] + rightSide;
              } else {
                errorMessage = formatMultipleSynthesis(matches, leftSide,
                    rightSide);
              }
              matchCounter++;
              newWay = true;
            }
          } else {
            // FIXME: is this correct? this is how we deal with multiple matches
            suggestionMatches.add(suggestionMatches.get(numbersToMatches[j]));
          }
        }

        if (!newWay) {
          // in case <match> elements weren't used (yet)
          errorMessage = errorMessage.replace("\\" + (j + 1),
              tokenReadings[firstMatchTok + repTokenPos - 1].getToken());
        }
      }
      errMarker = errorMessage.indexOf('\\');
      numberFollows = false;
      errLen = errorMessage.length();
      if (errMarker > 0 && errMarker < errLen - 1) {
        numberFollows = StringTools.isPositiveNumber(errorMessage
            .charAt(errMarker + 1));
      }
    }
    return errorMessage;
  }

  private static String formatMultipleSynthesis(final String[] matches,
      final String leftSide, final String rightSide) {
    String errorMessage = "";
    String suggestionLeft = "";
    String suggestionRight = "";
    String rightSideNew = rightSide;
    final int sPos = leftSide.lastIndexOf(SUGG_TAG);
    if (sPos > 0) {
      suggestionLeft = leftSide.substring(sPos + SUGG_TAG.length());
    }
    if (StringTools.isEmpty(suggestionLeft)) {
      errorMessage = leftSide;
    } else {
      errorMessage = leftSide.substring(0, leftSide.lastIndexOf(SUGG_TAG))
      + SUGG_TAG;
    }
    final int rPos = rightSide.indexOf(END_SUGG_TAG);
    if (rPos > 0) {
      suggestionRight = rightSide.substring(0, rPos);
    }
    if (!StringTools.isEmpty(suggestionRight)) {
      rightSideNew = rightSide.substring(rightSide.indexOf(END_SUGG_TAG));
    }
    final int lastLeftSugEnd = leftSide.indexOf(END_SUGG_TAG);
    final int lastLeftSugStart = leftSide.lastIndexOf(SUGG_TAG);
    final StringBuilder sb = new StringBuilder();
    sb.append(errorMessage);
    for (int z = 0; z < matches.length; z++) {
      sb.append(suggestionLeft);
      sb.append(matches[z]);
      sb.append(suggestionRight);
      if ((z < matches.length - 1) && lastLeftSugEnd < lastLeftSugStart) {
        sb.append(END_SUGG_TAG);
        sb.append(", ");
        sb.append(SUGG_TAG);
      }
    }
    sb.append(rightSideNew);
    return sb.toString();
  }

  /**
   * For testing only.
   */
  public final List<Element> getElements() {
    return patternElements;
  }

}