summaryrefslogtreecommitdiffstats
path: root/tdecore/tdestringmatcher.cpp
blob: 7e9f1ee0d0bd45074d385ddec496b8de8f2e9da0 (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
#include "tdestringmatcher.h"
#include "tequivchars.h"

#include <tdeglobal.h>
#include <tqregexp.h>
#include <kdebug.h>

#include <features.h>
#ifdef __GLIBC__
#include <fnmatch.h>
#pragma message "TSM using GLIBC fnmatch() for wildcard matching"
#endif

//================================================================================================

namespace TSM {

class AuxData
{
public:
  AuxData();
  TQString  patternConverted; // Pattern converted from original (e.g ANCHandling::EQUIVALENCE)
  TQRegExp* matchEngine;      // Used when PatternType::REGEX
#ifdef __GLIBC__
  int       fnmatchFlags;     // Used by fnmatch() when PatternType::WILDCARD
#endif
  bool      isCaseSensitive;  // PatternType::SUBSTRING
};

AuxData::AuxData()
{
  isCaseSensitive = true;
#ifdef __GLIBC__
  fnmatchFlags = FNM_EXTMATCH; // Bash shell option 'extglob'
#endif
  matchEngine = nullptr;
  patternConverted = "";
}

} // End of namespace TSM

//================================================================================================

using namespace TSM;

typedef TQValueVector<AuxData> AuxDataList;

class TDEStringMatcher::TDEStringMatcherPrivate {
public:

  // Properties that may be set / accessed through the TSM interface
  TQString      m_matchSpecString;
  MatchSpecList m_matchSpecList;

  // Properties that are internal implementation only
  AuxDataList   m_auxData;
  void          clearAll();
};

void TDEStringMatcher::TDEStringMatcherPrivate::clearAll()
{
  m_matchSpecString = "";
  m_matchSpecList.clear();
  for ( size_t index = 0 ; index < m_auxData.count() ; index++ ) {
    if ( m_auxData[index].matchEngine != nullptr ) {
      TSMTRACE << "Freeing match engine " << m_auxData[index].matchEngine << endl;
      delete m_auxData[index].matchEngine;
    }
  }
  m_auxData.clear();
}

//================================================================================================

TDEStringMatcher::TDEStringMatcher()
{
  TSMTRACE << "TSM::TDEStringMatcher(): New instance created: " << this << endl;
  d = new TDEStringMatcherPrivate;
}

TDEStringMatcher::~TDEStringMatcher()
{
  d->clearAll();
  delete d;
  TSMTRACE << "TSM::~TDEStringMatcher(): Instance destroyed: " << this << endl;
}


//================================================================================================
//  Match specification output functions
//================================================================================================

const TQString TDEStringMatcher::getMatchSpecString() const 
{
  return d->m_matchSpecString;
}

const MatchSpecList TDEStringMatcher::getMatchSpecs() const
{
  return d->m_matchSpecList;
}


//================================================================================================
//  Match specification input functions
//================================================================================================

bool TDEStringMatcher::setMatchSpecs( MatchSpecList newMatchSpecList )
{
  TDEStringMatcherPrivate workArea;

  TQStringList newMatchSpecs;

  TSMTRACE << "TSM::setPatterns(): validating match specification list"  << endl;

  for ( MatchSpec matchSpec : newMatchSpecList ) {

    if ( matchSpec.pattern.isEmpty() ) {
      TSMTRACE << "  Error: empty pattern!"  << endl;
      workArea.clearAll();
      return false;
    }
    if ( matchSpec.pattern.find( TQChar(PatterStringDivider) ) >= 0 ) {
      TSMTRACE << "  Error: pattern contains reserved separator character" << endl;
      workArea.clearAll();
      return false;
    }

    AuxData  auxWork;
    TQString inferredOptionString;

    // Validate / process PatternType

    auxWork.patternConverted = matchSpec.pattern;
    switch ( matchSpec.patternType ) {
      case PatternType::WILDCARD :
        inferredOptionString += TQChar('w');
#ifndef __GLIBC__
        auxWork.patternConverted = wildcardToRegex( auxWork.patternConverted );
        TSMTRACE << "    Converted wildcard expression '" << matchSpec.pattern << "' to regex '" << auxWork.patternConverted << "'" << endl;
#endif
        break;
      case PatternType::REGEX :
        inferredOptionString += TQChar('r');
        break;
      case PatternType::SUBSTRING :
        inferredOptionString += TQChar('s');
        break;
      default:
        TSMTRACE << "  Error: pattern type out of range" << endl;
        workArea.clearAll();
        return false;
    }

    // Validate / process ANCHandling

    TQString before = auxWork.patternConverted;
    switch ( matchSpec.ancHandling ) {
      case ANCHandling::CASE_SENSITIVE :
        inferredOptionString += TQChar('c');
        auxWork.isCaseSensitive = true;
        break;
      case ANCHandling::CASE_INSENSITIVE :
        inferredOptionString += TQChar('i');
        auxWork.isCaseSensitive = false;
#ifdef __GLIBC__
        auxWork.fnmatchFlags |= FNM_CASEFOLD;
#endif
        break;
      case ANCHandling::EQUIVALENCE :
        inferredOptionString += TQChar('e');
        auxWork.isCaseSensitive = true;
        auxWork.patternConverted = TDEGlobal::equivChars()->replaceChars( auxWork.patternConverted, true );
        TSMTRACE << "  Converted match pattern '" << before << "' to equivalent '" << auxWork.patternConverted << "'" << endl;
        break;
      default:
        TSMTRACE << "  Error: alphabetic character handling specification out of range" << endl;
        workArea.clearAll();
        return false;
    }

    if ( matchSpec.expectMatch )
      inferredOptionString += TQChar('=');
    else
      inferredOptionString += TQChar('!');

    // Test validity of pattern

    TQRegExp rxWork;
    int      result;

    switch ( matchSpec.patternType ) {
      case PatternType::WILDCARD :
#ifdef __GLIBC__ // Test wildcard expression using a subject matter expert
      result = fnmatch(
         auxWork.patternConverted.local8Bit().data(),
         auxWork.patternConverted.local8Bit().data(),
         auxWork.fnmatchFlags
      ); // Comparison should fail
      switch ( result ) {
        case 0: // matched
        case FNM_NOMATCH: // not matched
          break;
        default:
          TSMTRACE << "  Error: invalid wildcard syntax" << endl;
          workArea.clearAll();
          return false;
      }
      break;
#endif // Otherwise we will test wildcard expression as one converted to a regex
      case PatternType::REGEX :
        // Prepare regex
        rxWork.setPattern( auxWork.patternConverted );
        rxWork.setCaseSensitive( auxWork.isCaseSensitive );
        // Test regex
        if ( rxWork.isValid() ) {
          auxWork.matchEngine = new TQRegExp;
          *auxWork.matchEngine = rxWork;
          TSMTRACE << "AuxData: Allocated regex engine for matching '" << auxWork.matchEngine->pattern() << "'" << endl;
        }
        else {
          TSMTRACE << "  Error: invalid regex syntax'" << endl;
          workArea.clearAll();
          return false;
        }
        break;
        // if (! rxWork.isReallyWhatUserIntended() ) { HA HA
    }

    // This particular match specification is good

    newMatchSpecs.append( inferredOptionString );
    newMatchSpecs.append( matchSpec.pattern );
    workArea.m_auxData.append( auxWork );
  }

  // All proposed match specifications are good, update everything accordingly

  workArea.m_matchSpecList = newMatchSpecList;
  workArea.m_matchSpecString = newMatchSpecs.join( TQChar(PatterStringDivider) );
  d->clearAll();
  *d = workArea;
  //-Debug: TSMTRACE << "  Notifying slots of pattern change" << endl;
  emit patternsChanged();
  //-Debug: TSMTRACE << "  All slots have been notified" << endl;
  TSMTRACE << "TSM::setPatterns(): Patterns were successfully regenerated from list" << endl << endl;
  return true;
}

//=================================================================================================

bool TDEStringMatcher::setMatchSpecs( TQString newMatchSpecString )
{
  if ( newMatchSpecString == d->m_matchSpecString )
    return true;

  TDEStringMatcherPrivate workArea;

  MatchSpec matchSpec = {
     PatternType::DEFAULT,
     ANCHandling::DEFAULT,
     true, // seeking matches, not non-matches
     ""
  };

  TSMTRACE << "TSM::setPatterns: Proposed match specification string: <" << newMatchSpecString << ">" << endl;

  if ( newMatchSpecString.isEmpty() ) {
    TSMTRACE << "  Empty pattern string => match specifications will be cleared" << endl;
    d->m_matchSpecList.clear();
    d->m_matchSpecString = "";
    emit patternsChanged();
    return true;
  }

  TQStringList newMatchSpecs = TQStringList::split( PatterStringDivider, newMatchSpecString, true );

  if ( newMatchSpecs.count() % 2 != 0 ) {
    TSMTRACE << "  Error: match specification string must contain an even number of components" << endl;
    return false;
  }

  bool processingOptionString = true; // expected format: option string , pattern string, ...

  for ( TQString &specification : newMatchSpecs ) {

    if ( processingOptionString ) {
      specification = specification.lower();
      TSMTRACE << "    Processing match option string: '" << specification << "'" << endl;
      for ( int i = 0 ; i < specification.length() ; i++ ) {

        TQChar optionChar = specification[i];
        //Debug: TSMTRACE << "      Option character: '" <<  optionChar << "'" << endl;

        switch ( optionChar ) {
          case 'r' : matchSpec.patternType    = PatternType::REGEX           ; break;
          case 'w' : matchSpec.patternType    = PatternType::WILDCARD        ; break;
          case 's' : matchSpec.patternType    = PatternType::SUBSTRING       ; break;
          case 'c' : matchSpec.ancHandling    = ANCHandling::CASE_SENSITIVE  ; break;
          case 'i' : matchSpec.ancHandling    = ANCHandling::CASE_INSENSITIVE; break;
          case 'e' : matchSpec.ancHandling    = ANCHandling::EQUIVALENCE     ; break;
          case '=' : matchSpec.expectMatch    = true                         ; break;
          case '!' : matchSpec.expectMatch    = false                        ; break;
          default:
            // We reserve ALL other possible option characters for future use!
            TSMTRACE << "      Error: invalid option character" << endl;
            workArea.clearAll();
            return false;
        }
      }

      processingOptionString = false; // next spec should be a pattern string
    } // processingOptionString

    else { // ! processingOptionString

      TSMTRACE << "    Processing match pattern string: '" << specification << "'" << endl;

      if ( specification.isEmpty() ) {
        TSMTRACE << "  Error: empty pattern!"  << endl;
        workArea.clearAll();
        return false;
      }

      AuxData  auxWork;

      // Validate / process PatternType

      auxWork.patternConverted = specification;
      switch ( matchSpec.patternType ) {
        case PatternType::WILDCARD :
#ifndef __GLIBC__
          auxWork.patternConverted = wildcardToRegex( specification );
          TSMTRACE << "    Converted wildcard expression '" << specification << "' to regex '" << auxWork.patternConverted << "'" << endl;
          break;
#endif
        case PatternType::REGEX :
        case PatternType::SUBSTRING :
          break;
        default :
          // This should never arise since the content of this field was set within this function
          kdWarning() << "Error while processing '" << specification
            << "' pattern type out of range: " << (uchar) matchSpec.patternType
          << endl;
          workArea.clearAll();
          return false;
      }

      // Validate / process ANCHandling

      TQString before = auxWork.patternConverted;
      switch ( matchSpec.ancHandling ) {
        case ANCHandling::CASE_SENSITIVE :
          auxWork.isCaseSensitive = true;
          break;
        case ANCHandling::CASE_INSENSITIVE :
          auxWork.isCaseSensitive = false;
#ifdef __GLIBC__
          auxWork.fnmatchFlags |= FNM_CASEFOLD;
#endif
          break;
        case ANCHandling::EQUIVALENCE :
          auxWork.isCaseSensitive = true;
          auxWork.patternConverted = TDEGlobal::equivChars()->replaceChars( auxWork.patternConverted, true );
          TSMTRACE << "    Converted match pattern '" << before << "' to equivalent '" << auxWork.patternConverted << "'" << endl;
          break;
        default: break;
          kdWarning() << "Error while processing '" << specification
             << "' alphabetic character handling specification out of range: " << (uchar) matchSpec.ancHandling
          << endl;
          workArea.clearAll();
          return false;
      }

    // Test validity of pattern

      TQRegExp rxWork; // single working copy == each pattern inherits previous options
      int result;

      switch ( matchSpec.patternType ) {
        case PatternType::WILDCARD :
#ifdef __GLIBC__  // Test wildcard expression using a subject matter expert
        result = fnmatch(
           auxWork.patternConverted.local8Bit().data(),
           auxWork.patternConverted.local8Bit().data(),
           auxWork.fnmatchFlags
        ); // Comparison should fail
        switch ( result ) {
          case 0: // matched
          case FNM_NOMATCH: // not matched
            break;
          default:
            TSMTRACE << "  Error: invalid wildcard syntax" << endl;
            workArea.clearAll();
            return false;
        }
        break;
#endif // Otherwise we will test wildcard expression as one converted to x regex
        case PatternType::REGEX :
          // Prepare regex
          rxWork.setPattern( auxWork.patternConverted );
          rxWork.setCaseSensitive( auxWork.isCaseSensitive );
          // Test regex
          if ( rxWork.isValid() ) {
            auxWork.matchEngine = new TQRegExp;
            *auxWork.matchEngine = rxWork;
            TSMTRACE << "      AuxData: Allocated regex engine " << auxWork.matchEngine << "for pattern: " << auxWork.matchEngine->pattern() << endl;
          }
          else {
            TSMTRACE << "  Error: invalid regex syntax" << endl;
            workArea.clearAll();
            return false;
          }
          break;
          // if (! rxWork.isReallyWhatUserIntended() ) { HA HA
      }

      matchSpec.pattern = specification;
      workArea.m_matchSpecList.push_back( matchSpec );
      workArea.m_auxData.append( auxWork );

      processingOptionString = true; // next spec should be an option string
    } // ! processingOptionString completed
  }

  workArea.m_matchSpecString = newMatchSpecString;
  d->clearAll();
  *d = workArea;
  TSMTRACE << "  Final patternString: '" << d->m_matchSpecString << "'" << endl;
  TSMTRACE << "  Number of match patterns in list: '" << d->m_matchSpecList.count() << "'" << endl;
  //-Debug: TSMTRACE << "  Notifying slots of pattern change" << endl;
  emit patternsChanged();
  //-Debug: TSMTRACE << "  All slots have been notified" << endl;
  TSMTRACE << "TSM::setPatterns(): Patterns were successfully regenerated from string" << endl << endl;
  return true;
}

//================================================================================================
//  Match functions
//================================================================================================

bool TDEStringMatcher::matchAny( const TQString& stringToMatch ) const
{
/* DEBUG
  TSMTRACE << "TSM:matchAny(): Attempting to match string '" << stringToMatch << "' against stored patterns" << endl;
  if ( d->m_matchSpecList.isEmpty() ) {
    //-Debug: TSMTRACE << "Match failed on empty pattern list!" << endl;
    return false;
  }
*/
  TQString equivalentString;

  for ( size_t index = 0 ; index < d->m_matchSpecList.count() ; index++ )
  {
    TQString matchWhat = stringToMatch;
    TQString matchThis = d->m_auxData[index].patternConverted;

    if ( d->m_matchSpecList[index].ancHandling == ANCHandling::EQUIVALENCE ) {
      if ( equivalentString.isEmpty() ) {
        equivalentString = TDEGlobal::equivChars()->replaceChars( stringToMatch, false ) ;
      }
      matchWhat = equivalentString;
    }

    bool matchFound  = false;
    switch ( d->m_matchSpecList[index].patternType ) {
      case PatternType::WILDCARD  :
#ifdef __GLIBC__
      matchFound = ( fnmatch(
         matchThis.local8Bit().data(),
         matchWhat.local8Bit().data(),
         d->m_auxData[index].fnmatchFlags
      ) == 0 );
      break;
#endif
      case PatternType::REGEX     :
        matchFound  = ( d->m_auxData[index].matchEngine->search( matchWhat ) >= 0 );
        break;
      case PatternType::SUBSTRING :
        matchFound = ( matchWhat.find( matchThis, 0, d->m_auxData[index].isCaseSensitive ) >= 0 );
        break;
    }

    if ( matchFound == d->m_matchSpecList[index].expectMatch ) {
      TSMTRACE << "  Success! match of pattern '" << matchThis << "' against '" << matchWhat << "' turned out as expected" << endl;
      return true;
    }
  }

  TSMTRACE << "  Match failed, there were no pattern matches against '" << stringToMatch << "' that turned out as expected" << endl;
  return false ;
}

bool TDEStringMatcher::matchAll( const TQString& stringToMatch ) const
{
  TSMTRACE << "TSM:matchAll(): Attempting to match string '" << stringToMatch << "' against stored patterns" << endl;
  if ( d->m_matchSpecList.isEmpty() ) {
    //-Debug: TSMTRACE << "Match failed on empty pattern list!" << endl;
    return false;
  }

  TQString equivalentString;

  for ( size_t index = 0 ; index < d->m_matchSpecList.count() ; index++ )
  {
    TQString matchWhat = stringToMatch;
    TQString matchThis = d->m_auxData[index].patternConverted;

    if ( d->m_matchSpecList[index].ancHandling == ANCHandling::EQUIVALENCE ) {
      if ( equivalentString.isEmpty() ) {
        equivalentString = TDEGlobal::equivChars()->replaceChars( stringToMatch, false ) ;
      }
      matchWhat = equivalentString;
    }

    bool matchFound  = false;
    switch ( d->m_matchSpecList[index].patternType ) {
      case PatternType::WILDCARD  :
#ifdef __GLIBC__
      matchFound = ( fnmatch(
         matchThis.local8Bit().data(),
         matchWhat.local8Bit().data(),
         d->m_auxData[index].fnmatchFlags
      ) == 0 );
      break;
#endif
      case PatternType::REGEX     :
        matchFound  = ( d->m_auxData[index].matchEngine->search( matchWhat ) >= 0 );
        break;
      case PatternType::SUBSTRING :
        matchFound = ( matchWhat.find( matchThis, 0, d->m_auxData[index].isCaseSensitive ) >= 0 );
        break;
    }

    if ( matchFound != d->m_matchSpecList[index].expectMatch ) {
      TSMTRACE << "  Match of pattern '" << matchThis << "' against '" << matchWhat << "' did not turn out as expected" << endl;
      return false;
    }
  }

  TSMTRACE << "  Expected pattern matching succeeded" << endl;
  return true;
}

//================================================================================================
//  Utility functions
//================================================================================================

/*
   The following code is a modified copy of that found in tqt3/src/tools/qregexp.cpp.
   We export this as utility function for applications that wish to convert a basic
   wildcard expression into a basic regular expression. TSM will not use this unless
   GLIBC fnmatch() is not available.
*/
TQString TDEStringMatcher::wildcardToRegex( const TQString& wildcardPattern )
{
  int wclen = wildcardPattern.length();
  TQString rx = TQString::fromLatin1( "" );
  int i = 0;
  const TQChar *wc = wildcardPattern.unicode();
  while ( i < wclen ) {
    TQChar c = wc[i++];
    switch ( c.unicode() ) {
    case '*':
        rx += TQString::fromLatin1( ".*" );
        break;
    case '?':
        rx += TQChar( '.' );
        break;
    case '$':
    case '(':
    case ')':
    case '+':
    case '.':
    case '\\':
    case '^':
    case '{':
    case '|':
    case '}':
      rx += TQChar( '\\' );
      rx += c;
      break;
    case '[':
      rx += c;
      /* This is not correct, POSIX states that negation character is '!'
      if ( wc[i] == TQChar('^') )
        rx += wc[i++];
      */
      if ( wc[i] == TQChar('!') ) {
        rx += TQChar('^');
        i++;
      } else if ( wc[i] == TQChar('^') ) {
        rx += TQChar( '\\' );
        rx += wc[i++];
      }
      if ( i < wclen ) {
        if ( rx[i] == ']' )
          rx += wc[i++];
        while ( i < wclen && wc[i] != TQChar(']') ) {
          if ( wc[i] == '\\' )
            rx += TQChar( '\\' );
          rx += wc[i++];
        }
      }
      break;
    default:
      rx += c;
    }
  }
  /* Wildcard patterns must match entire string */
  return TQChar('^') + rx + TQChar('$');
  /* TBD: Add support for extglob */
}
static TQString escapeRegexChars( const TQString& basicString )
{
  int wclen = basicString.length();
  TQString outputString = TQString::fromLatin1( "" );
  int i = 0;
  const TQChar *wc = basicString.unicode();
  while ( i < wclen ) {
    TQChar c = wc[i++];
    switch ( c.unicode() ) {
      case '+':
      case '.':
      case '^':
      case '(':
      case ')':
      case '[':
      case ']':
      case '{':
      case '}':
      case '|':
      case '$':
      case '?':
      case '*':
      case '\\':
        outputString += TQChar( '\\' );
        outputString += c;
        break;
      default:
        outputString += c;
    }
  }
  return outputString;
}

//================================================================================================

#include "tdestringmatcher.moc"