summaryrefslogtreecommitdiffstats
path: root/libksieve/parser/lexer.cpp
blob: d8b76da71430c6a76a43efe6399c192a4598303a (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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
/*  -*- c++ -*-
    parser/lexer.cpp

    This file is part of KSieve,
    the KDE internet mail/usenet news message filtering library.
    Copyright (c) 2002-2003 Marc Mutz <mutz@kde.org>

    KSieve is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

    KSieve 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
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include <config.h>

#include <ksieve/lexer.h>
#include <impl/lexer.h>

#include <impl/utf8validator.h>
#include <ksieve/error.h>

#include <qstring.h>
#include <qstringlist.h>
#include <qtextcodec.h>

#include <memory> // std::auto_ptr

#include <assert.h>
#include <ctype.h> // isdigit

#ifdef STR_DIM
# undef STR_DIM
#endif
#define STR_DIM(x) (sizeof(x) - 1)

namespace KSieve {

  //
  //
  // Lexer Bridge implementation
  //
  //

  Lexer::Lexer( const char * scursor, const char * send, int options )
    : i( 0 )
  {
    i = new Impl( scursor, send, options );
  }

  Lexer::~Lexer() {
    delete i; i = 0;
  }

  bool Lexer::ignoreComments() const {
    assert( i );
    return i->ignoreComments();
  }

  const Error & Lexer::error() const {
    assert( i );
    return i->error();
  }

  bool Lexer::atEnd() const {
    assert( i );
    return i->atEnd();
  }

  int Lexer::column() const {
    assert( i );
    return i->column();
  }

  int Lexer::line() const {
    assert( i );
    return i->line();
  }

  void Lexer::save() {
    assert( i );
    i->save();
  }

  void Lexer::restore() {
    assert( i );
    i->restore();
  }

  Lexer::Token Lexer::nextToken( QString & result ) {
    assert( i );
    return i->nextToken( result );
  }

} // namespace KSieve


// none except a-zA-Z0-9_
static const unsigned char iTextMap[16] = {
    0x00, 0x00, 0x00, 0x00, // CTLs:        none
    0x00, 0x00, 0xFF, 0xC0, // SP ... '?':  0-9
    0x7F, 0xFF, 0xFF, 0xE1, // '@' ... '_': A-Z_
    0x7F, 0xFF, 0xFF, 0xE0  // '`' ... DEL: a-z
};

// SP, HT, CR, LF, {}[]();,#/
// ### exclude '['? Why would one want to write identifier["foo"]?
static const unsigned char delimMap[16] = {
    0x00, 0x64, 0x00, 0x00, // CTLs:        CR, HT, LF
    0x90, 0xC9, 0x00, 0x10, // SP ... '?':  SP, #(),;
    0x00, 0x00, 0x00, 0x16, // '@' ... '_': []
    0x00, 0x00, 0x00, 0x16  // '`' ... DEL: {}
};

// All except iText, delim, "*:
static const unsigned char illegalMap[16] = {
    0xFF, 0x9B, 0xFF, 0xFF,
    0x4F, 0x16, 0x00, 0x0F,
    0x80, 0x00, 0x00, 0x0A,
    0x80, 0x00, 0x00, 0x0A
};

static inline bool isOfSet( const unsigned char map[16], unsigned char ch ) {
    assert( ch < 128 );
    return ( map[ ch/8 ] & 0x80 >> ch%8 );
}

static inline bool isIText( unsigned char ch ) {
    return ch <= 'z' && isOfSet( iTextMap, ch );
}

static inline bool isDelim( unsigned char ch ) {
    return ch <= '}' && isOfSet( delimMap, ch );
}

static inline bool isIllegal( unsigned char ch ) {
    return ch >= '~' || isOfSet( illegalMap, ch );
}

static inline bool is8Bit( signed char ch ) {
    return ch < 0;
}

static QString removeCRLF( const QString & s ) {
  const bool CRLF = s.endsWith( "\r\n" );
  const bool LF = !CRLF && s.endsWith( "\n" );

  const int e = CRLF ? 2 : LF ? 1 : 0 ;  // what to chop off at the end

  return s.left( s.length() - e );
}

static QString removeDotStuff( const QString & s ) {
    return s.startsWith( ".." ) ? s.mid( 1 ) : s ;
}

namespace KSieve {

  //
  //
  // Lexer Implementation
  //
  //

  Lexer::Impl::Impl( const char * scursor, const char * send, int options )
    : mState( scursor ? scursor : send ),
      mEnd( send ? send : scursor ),
      mIgnoreComments( options & IgnoreComments ),
      mIgnoreLF( options & IgnoreLineFeeds )
  {
    if ( !scursor || !send )
      assert( atEnd() );
  }

  Lexer::Token Lexer::Impl::nextToken( QString & result ) {
    assert( !atEnd() );
    result = QString::null;
    //clearErrors();

    const int oldLine = line();

    const bool eatingWSSucceeded = ignoreComments() ? eatCWS() : eatWS() ;

    if ( !ignoreLineFeeds() && oldLine != line() ) {
      result.setNum( line() - oldLine ); // return number of linefeeds encountered
      return LineFeeds;
    }

    if ( !eatingWSSucceeded )
      return None;

    if ( atEnd() )
      return None;

    switch ( *mState.cursor ) {
    case '#': // HashComment
      assert( !ignoreComments() );
      ++mState.cursor;
      if ( !atEnd() )
	parseHashComment( result, true );
      return HashComment;
    case '/': // BracketComment
      assert( !ignoreComments() );
      ++mState.cursor; // eat slash
      if ( atEnd() || *mState.cursor != '*' ) {
	makeError( Error::SlashWithoutAsterisk );
	return BracketComment;
      }
      ++mState.cursor; // eat asterisk
      if ( atEnd() ) {
	makeError( Error::UnfinishedBracketComment );
	return BracketComment;
      }
      parseBracketComment( result, true );
      return BracketComment;
    case ':': // Tag
      ++mState.cursor;
      if ( atEnd() ) {
	makeError( Error::UnexpectedCharacter, line(), column() - 1 );
	return Tag;
      }
      if ( !isIText( *mState.cursor ) ) {
	makeIllegalCharError( *mState.cursor );
	return Tag;
      }
      parseTag( result );
      return Tag;
    case '"': // QuotedString
      ++mState.cursor;
      parseQuotedString( result );
      return QuotedString;
    case '{':
    case '}':
    case '[':
    case ']':
    case '(':
    case ')':
    case ';':
    case ',': // Special
      result = *mState.cursor++;
      return Special;
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9': // Number
      parseNumber( result );
      return Number;
    case 't': // maybe MultiLineString, else Identifier
      if ( _strnicmp( mState.cursor, "text:", STR_DIM("text:") ) == 0 ) {
	// MultiLineString
	mState.cursor += STR_DIM("text:");
	parseMultiLine( result );
	// ### FIXME: There can be a hash-comment between "text:"
	// and CRLF! That should be preserved somehow...
	return MultiLineString;
      }
      // else fall through:
    default: // Identifier (first must not be 0-9, and can't (caught by Number above))
      if ( !isIText( *mState.cursor ) ) {
	makeError( Error::IllegalCharacter );
	return None;
      }
      parseIdentifier( result );
      return Identifier;
    }
  }

  bool Lexer::Impl::eatWS() {
    while ( !atEnd() )
      switch ( *mState.cursor ) {
      case '\r':
      case '\n':
	if ( !eatCRLF() )
	  return false;
	break;
      case ' ':
      case '\t':
	++mState.cursor;
	break;
      default:
	return true;
      }

    // at end:
    return true;
  }

  bool Lexer::Impl::eatCRLF() {
    assert( !atEnd() );
    assert( *mState.cursor == '\n' || *mState.cursor == '\r' );

    if ( *mState.cursor == '\r' ) {
      ++mState.cursor;
      if ( atEnd() || *mState.cursor != '\n' ) {
	// CR w/o LF -> error
	makeError( Error::CRWithoutLF );
	return false;
      } else {
	// good CRLF
	newLine();
	return true;
      }
    } else /* *mState.cursor == '\n' */ {
      // good, LF only
      newLine();
      return true;
    }
  }
      

  bool Lexer::Impl::parseHashComment( QString & result, bool reallySave ) {
    // hash-comment := "#" *CHAR-NOT-CRLF CRLF

    // check that the caller plays by the rules:
    assert( *(mState.cursor-1) == '#' );

    const char * const commentStart = mState.cursor;

    // find next CRLF:
    while ( !atEnd() ) {
      if ( *mState.cursor == '\n' || *mState.cursor == '\r' ) break;
      ++mState.cursor;
    }

    const char * const commentEnd = mState.cursor - 1;

    if ( commentEnd == commentStart ) return true; // # was last char in script...

    if ( atEnd() || eatCRLF() ) {
      const int commentLength = commentEnd - commentStart + 1;
      if ( commentLength > 0 ) {
	if ( !isValidUtf8( commentStart, commentLength ) ) {
	  makeError( Error::InvalidUTF8 );
	  return false;
	}
	if ( reallySave )
	  result += QString::fromUtf8( commentStart, commentLength );
      }
      return true;
    }

    return false;
  }

  bool Lexer::Impl::parseBracketComment( QString & result, bool reallySave ) {
    // bracket-comment := "/*" *(CHAR-NOT-STAR / ("*" CHAR-NOT-SLASH )) "*/"

    // check that caller plays by the rules:
    assert( *(mState.cursor-2) == '/' );
    assert( *(mState.cursor-1) == '*' );

    const char * const commentStart = mState.cursor;
    const int commentCol = column() - 2;
    const int commentLine = line();

    // find next asterisk:
    do {
      if ( !skipTo( '*' ) ) {
	if ( !error() )
	  makeError( Error::UnfinishedBracketComment, commentLine, commentCol );
	return false;
      }
    } while ( !atEnd() && *++mState.cursor != '/' );

    if ( atEnd() ) {
      makeError( Error::UnfinishedBracketComment, commentLine, commentCol );
      return false;
    }

    assert( *mState.cursor == '/' );

    const int commentLength = mState.cursor - commentStart - 1;
    if ( commentLength > 0 ) {
      if ( !isValidUtf8( commentStart, commentLength ) ) {
	makeError( Error::InvalidUTF8 );
	return false;
      }
      if ( reallySave ) {
	QString tmp = QString::fromUtf8( commentStart, commentLength );
	result += tmp.remove( '\r' ); // get rid of CR in CRLF pairs
      }
    }

    ++mState.cursor; // eat '/'
    return true;
  }

  bool Lexer::Impl::parseComment( QString & result, bool reallySave ) {
    // comment := hash-comment / bracket-comment

    switch( *mState.cursor ) {
    case '#':
      ++mState.cursor;
      return parseHashComment( result, reallySave );
    case '/':
      if ( charsLeft() < 2 || mState.cursor[1] != '*' ) {
	makeError( Error::IllegalCharacter );
	return false;
      } else {
	mState.cursor += 2; // eat "/*"
	return parseBracketComment( result, reallySave );
      }
    default:
      return false; // don't set an error here - there was no comment
    }
  }

  bool Lexer::Impl::eatCWS() {
    // white-space := 1*(SP / CRLF / HTAB / comment )

    while ( !atEnd() ) {
      switch( *mState.cursor ) {
      case ' ':
      case '\t': // SP / HTAB
	++mState.cursor;
	break;;
      case '\n':
      case '\r': // CRLF
	if ( !eatCRLF() )
	  return false;
	break;
      case '#':
      case '/': // comments
	{
	  QString dummy;
	  if ( !parseComment( dummy ) )
	    return false;
	}
	break;
      default:
	return true;
      }
    }
    return true;
  }

  bool Lexer::Impl::parseIdentifier( QString & result ) {
    // identifier := (ALPHA / "_") *(ALPHA DIGIT "_")

    assert( isIText( *mState.cursor ) );

    const char * const identifierStart = mState.cursor;

    // first char:
    if ( isdigit( *mState.cursor ) ) { // no digits for the first
      makeError( Error::NoLeadingDigits );
      return false;
    }

    // rest of identifier chars ( now digits are allowed ):
    for ( ++mState.cursor ; !atEnd() && isIText( *mState.cursor ) ; ++mState.cursor );

    const int identifierLength = mState.cursor - identifierStart;

    // Can use the fast fromLatin1 here, since identifiers are always
    // in the us-ascii subset:
    result += QString::fromLatin1( identifierStart, identifierLength );

    if ( atEnd() || isDelim( *mState.cursor ) )
      return true;

    makeIllegalCharError( *mState.cursor );
    return false;
  }

  bool Lexer::Impl::parseTag( QString & result ) {
    // tag := ":" identifier

    // check that the caller plays by the rules:
    assert( *(mState.cursor-1) == ':' );
    assert( !atEnd() );
    assert( isIText( *mState.cursor ) );

    return parseIdentifier( result );
  }

  bool Lexer::Impl::parseNumber( QString & result ) {
    // number     := 1*DIGIT [QUANTIFIER]
    // QUANTIFIER := "K" / "M" / "G"

    assert( isdigit( *mState.cursor ) );

    while ( !atEnd() && isdigit( *mState.cursor ) )
      result += *mState.cursor++;

    if ( atEnd() || isDelim( *mState.cursor ) )
      return true;

    switch ( *mState.cursor ) {
    case 'G':
    case 'g':
    case 'M':
    case 'm':
    case 'K':
    case 'k':
      result += *mState.cursor++;
      break;
    default:
      makeIllegalCharError();
      return false;
    }

    // quantifier found. Check for delimiter:
    if ( atEnd() || isDelim( *mState.cursor ) )
      return true;
    makeIllegalCharError();
    return false;
  }

  bool Lexer::Impl::parseMultiLine( QString & result ) {
    // multi-line          := "text:" *(SP / HTAB) (hash-comment / CRLF)
    //                        *(multi-line-literal / multi-line-dotstuff)
    //                        "." CRLF
    // multi-line-literal  := [CHAR-NOT-DOT *CHAR-NOT-CRLF] CRLF
    // multi-line-dotstuff := "." 1*CHAR-NOT-CRLF CRLF
    //         ;; A line containing only "." ends the multi-line.
    //         ;; Remove a leading '.' if followed by another '.'.

    assert( _strnicmp( mState.cursor - 5, "text:", STR_DIM("text:") ) == 0 );

    const int mlBeginLine = line();
    const int mlBeginCol = column() - 5;

    while ( !atEnd() ) {
      switch ( *mState.cursor ) {
      case ' ':
      case '\t':
	++mState.cursor;
	break;
      case '#':
	{
	  ++mState.cursor;
	  QString dummy;
	  if ( !parseHashComment( dummy ) )
	    return false;
	  goto MultiLineStart; // break from switch _and_ while
	}
      case '\n':
      case '\r':
	if ( !eatCRLF() ) return false;
	goto MultiLineStart; // break from switch _and_ while
      default:
	makeError( Error::NonCWSAfterTextColon );
	return false;
      }
    }

  MultiLineStart:
    if ( atEnd() ) {
      makeError( Error::PrematureEndOfMultiLine, mlBeginLine, mlBeginCol );
      return false;
    }

    // Now, collect the single lines until one with only a single dot is found:
    QStringList lines;
    while ( !atEnd() ) {
      const char * const oldBeginOfLine = beginOfLine();
      if ( !skipToCRLF() )
	return false;
      const int lineLength = mState.cursor - oldBeginOfLine;
      if ( lineLength > 0 ) {
	if ( !isValidUtf8( oldBeginOfLine, lineLength ) ) {
	  makeError( Error::InvalidUTF8 );
	  return false;
	}
	const QString line = removeCRLF( QString::fromUtf8( oldBeginOfLine, lineLength ) );
	lines.push_back( removeDotStuff( line ) );
	if ( line == "." )
	  break;
      } else {
	lines.push_back( QString::null );
      }
    }

    if ( lines.back() != "." ) {
      makeError( Error::PrematureEndOfMultiLine, mlBeginLine, mlBeginCol );
      return false;
    }

    assert( !lines.empty() );
    lines.erase( --lines.end() ); // don't include the lone dot.
    result = lines.join("\n");
    return true;
  }

  bool Lexer::Impl::parseQuotedString( QString & result ) {
    // quoted-string := DQUOTE *CHAR DQUOTE

    // check that caller plays by the rules:
    assert( *(mState.cursor-1) == '"' );

    const int qsBeginCol = column() - 1;
    const int qsBeginLine = line();

    const QTextCodec * const codec = QTextCodec::codecForMib( 106 ); // UTF-8
    assert( codec );
    const std::auto_ptr<QTextDecoder> dec( codec->makeDecoder() );
    assert( dec.get() );

    while ( !atEnd() )
      switch ( *mState.cursor ) {
      case '"':
	++mState.cursor;
	return true;
      case '\r':
      case '\n':
	if ( !eatCRLF() )
	  return false;
	result += '\n';
	break;
      case '\\':
	++mState.cursor;
	if ( atEnd() )
	  break;
	// else fall through:
      default:
	if ( !is8Bit( *mState.cursor ) )
	  result += *mState.cursor++;
	else { // probably UTF-8
	  const char * const eightBitBegin = mState.cursor;
	  skipTo8BitEnd();
	  const int eightBitLen = mState.cursor - eightBitBegin;
	  assert( eightBitLen > 0 );
	  if ( isValidUtf8( eightBitBegin, eightBitLen ) )
	    result += dec->toUnicode( eightBitBegin, eightBitLen );
	  else {
	    assert( column() >= eightBitLen );
	    makeError( Error::InvalidUTF8, line(), column() - eightBitLen );
	    return false;
	  }
	}
      }

    makeError( Error::PrematureEndOfQuotedString, qsBeginLine, qsBeginCol );
    return false;
  }

  void Lexer::Impl::makeIllegalCharError( char ch ) {
    makeError( isIllegal( ch ) ? Error::IllegalCharacter : Error::UnexpectedCharacter );
  }

} // namespace KSieve