summaryrefslogtreecommitdiff
path: root/comphelper/source/misc/syntaxhighlight.cxx
blob: 89dcb73752e4aae9f97bd8fefbd8b961cb01bea4 (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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <sal/config.h>

#include <cassert>

#include <rtl/character.hxx>
#include <rtl/ustring.hxx>
#include <unicode/uchar.h>
#include <comphelper/syntaxhighlight.hxx>
#include <o3tl/typed_flags_set.hxx>

namespace {

// Flags for character properties
enum class CharFlags {
    StartIdentifier   = 0x0001,
    InIdentifier      = 0x0002,
    StartNumber       = 0x0004,
    InNumber          = 0x0008,
    InHexNumber       = 0x0010,
    InOctNumber       = 0x0020,
    StartString       = 0x0040,
    Operator          = 0x0080,
    Space             = 0x0100,
    EOL               = 0x0200
};

}

namespace o3tl {
    template<> struct typed_flags<CharFlags> : is_typed_flags<CharFlags, 0x03ff> {};
}

// ##########################################################################
// ATTENTION: all these words need to be in lower case
// ##########################################################################
static const char* strListBasicKeyWords[] = {
    "access",
    "alias",
    "and",
    "any",
    "append",
    "as",
    "attribute",
    "base",
    "binary",
    "boolean",
    "byref",
    "byte",
    "byval",
    "call",
    "case",
    "cdecl",
    "classmodule",
    "close",
    "compare",
    "compatible",
    "const",
    "currency",
    "date",
    "declare",
    "defbool",
    "defcur",
    "defdate",
    "defdbl",
    "deferr",
    "defint",
    "deflng",
    "defobj",
    "defsng",
    "defstr",
    "defvar",
    "dim",
    "do",
    "doevents",
    "double",
    "each",
    "else",
    "elseif",
    "end",
    "end enum",
    "end function",
    "end if",
    "end property",
    "end select",
    "end sub",
    "end type",
    "endif",
    "enum",
    "eqv",
    "erase",
    "error",
    "exit",
    "explicit",
    "for",
    "function",
    "get",
    "global",
    "gosub",
    "goto",
    "if",
    "imp",
    "implements",
    "in",
    "input",
    "integer",
    "is",
    "let",
    "lib",
    "like",
    "line",
    "line input",
    "local",
    "lock",
    "long",
    "loop",
    "lprint",
    "lset",
    "mod",
    "name",
    "new",
    "next",
    "not",
    "object",
    "on",
    "open",
    "option",
    "optional",
    "or",
    "output",
    "paramarray",
    "preserve",
    "print",
    "private",
    "property",
    "public",
    "random",
    "read",
    "redim",
    "rem",
    "resume",
    "return",
    "rset",
    "select",
    "set",
    "shared",
    "single",
    "static",
    "step",
    "stop",
    "string",
    "sub",
    "system",
    "text",
    "then",
    "to",
    "type",
    "typeof",
    "until",
    "variant",
    "vbasupport",
    "wend",
    "while",
    "with",
    "withevents",
    "write",
    "xor"
};


static const char* strListSqlKeyWords[] = {
    "all",
    "and",
    "any",
    "as",
    "asc",
    "avg",
    "between",
    "by",
    "cast",
    "corresponding",
    "count",
    "create",
    "cross",
    "delete",
    "desc",
    "distinct",
    "drop",
    "escape",
    "except",
    "exists",
    "false",
    "from",
    "full",
    "global",
    "group",
    "having",
    "in",
    "inner",
    "insert",
    "intersect",
    "into",
    "is",
    "join",
    "left",
    "like",
    "limit",
    "local",
    "match",
    "max",
    "min",
    "natural",
    "not",
    "null",
    "on",
    "or",
    "order",
    "outer",
    "right",
    "select",
    "set",
    "some",
    "sum",
    "table",
    "temporary",
    "true",
    "union",
    "unique",
    "unknown",
    "update",
    "using",
    "values",
    "where"
};


extern "C" {

static int compare_strings( const void *arg1, const void *arg2 )
{
    return strcmp( static_cast<char const *>(arg1), *static_cast<char * const *>(arg2) );
}

}

namespace
{
    bool isAlpha(sal_Unicode c)
    {
        if (rtl::isAsciiAlpha(c))
            return true;
        return u_isalpha(c);
    }
}

class SyntaxHighlighter::Tokenizer
{
    // Character information tables
    CharFlags aCharTypeTab[256] = {};

    // Auxiliary function: testing of the character flags
    bool testCharFlags(sal_Unicode c, CharFlags nTestFlags) const;

    // Get new token, EmptyString == nothing more over there
    bool getNextToken(std::u16string_view::const_iterator& pos, std::u16string_view::const_iterator end, /*out*/TokenType& reType,
        /*out*/std::u16string_view::const_iterator& rpStartPos, /*out*/std::u16string_view::const_iterator& rpEndPos) const;

    const char** ppListKeyWords;
    sal_uInt16 nKeyWordCount;

public:
    HighlighterLanguage const aLanguage;

    explicit Tokenizer( HighlighterLanguage aLang );

    void getHighlightPortions(std::u16string_view rLine,
                               /*out*/std::vector<HighlightPortion>& portions) const;
    void setKeyWords( const char** ppKeyWords, sal_uInt16 nCount );
};

// Helper function: test character flag
bool SyntaxHighlighter::Tokenizer::testCharFlags(sal_Unicode c, CharFlags nTestFlags) const
{
    bool bRet = false;
    if( c != 0 && c <= 255 )
    {
        bRet = bool(aCharTypeTab[c] & nTestFlags);
    }
    else if( c > 255 )
    {
        bRet = (( CharFlags::StartIdentifier | CharFlags::InIdentifier ) & nTestFlags)
            && isAlpha(c);
    }
    return bRet;
}

void SyntaxHighlighter::Tokenizer::setKeyWords( const char** ppKeyWords, sal_uInt16 nCount )
{
    ppListKeyWords = ppKeyWords;
    nKeyWordCount = nCount;
}

bool SyntaxHighlighter::Tokenizer::getNextToken(std::u16string_view::const_iterator& pos, std::u16string_view::const_iterator end,
    /*out*/TokenType& reType,
    /*out*/std::u16string_view::const_iterator& rpStartPos, /*out*/std::u16string_view::const_iterator& rpEndPos) const
{
    reType = TokenType::Unknown;

    rpStartPos = pos;

    if( pos == end )
        return false;

    sal_Unicode c = *pos;
    ++pos;

    //*** Go through all possibilities ***
    // Space?
    if ( testCharFlags( c, CharFlags::Space ) )
    {
        while( pos != end && testCharFlags( *pos, CharFlags::Space ) )
            ++pos;

        reType = TokenType::Whitespace;
    }

    // Identifier?
    else if ( testCharFlags( c, CharFlags::StartIdentifier ) )
    {
        bool bIdentifierChar;
        do
        {
            if (pos == end)
                break;
            // Fetch next character
            c = *pos;
            bIdentifierChar = testCharFlags( c, CharFlags::InIdentifier );
            if( bIdentifierChar )
                ++pos;
        }
        while( bIdentifierChar );

        reType = TokenType::Identifier;

        // Keyword table
        if (ppListKeyWords != nullptr)
        {
            int nCount = pos - rpStartPos;

            // No keyword if string contains char > 255
            bool bCanBeKeyword = true;
            for( int i = 0 ; i < nCount ; i++ )
            {
                if( rpStartPos[i] > 255 )
                {
                    bCanBeKeyword = false;
                    break;
                }
            }

            if( bCanBeKeyword )
            {
                std::u16string_view aKWString(&*rpStartPos, nCount);
                OString aByteStr = OUStringToOString(aKWString,
                    RTL_TEXTENCODING_ASCII_US).toAsciiLowerCase();
                if ( bsearch( aByteStr.getStr(), ppListKeyWords, nKeyWordCount, sizeof( char* ),
                                                                        compare_strings ) )
                {
                    reType = TokenType::Keywords;

                    if( aByteStr == "rem" )
                    {
                        // Remove all characters until end of line or EOF
                        for (;;)
                        {
                            if (pos == end)
                                break;
                            sal_Unicode cPeek = *pos;
                            if ( testCharFlags( cPeek, CharFlags::EOL ) )
                                break;
                            ++pos;
                        }

                        reType = TokenType::Comment;
                    }
                }
            }
        }
    }

    // Operator?
    // only for BASIC '\'' should be a comment, otherwise it is a normal string and handled there
    else if ( testCharFlags( c, CharFlags::Operator ) || ( (c == '\'') && (aLanguage==HighlighterLanguage::Basic)) )
    {
        // parameters for SQL view
        if (((c==':') || (c=='?')) && (aLanguage == HighlighterLanguage::SQL))
        {
            if (c!='?')
            {
                bool bIdentifierChar;
                do
                {
                    // Get next character
                    if (pos == end)
                        break;
                    c = *pos;
                    bIdentifierChar = isAlpha(c);
                    if( bIdentifierChar )
                        ++pos;
                }
                while( bIdentifierChar );
            }
            reType = TokenType::Parameter;
        }
        else if ((c=='-') && (aLanguage == HighlighterLanguage::SQL))
        {
            if (pos != end && *pos=='-')
            {
                // Remove all characters until end of line or EOF
                while( pos != end && !testCharFlags( *pos, CharFlags::EOL ) )
                {
                    ++pos;
                }
                reType = TokenType::Comment;
            }
            else
                reType = TokenType::Operator;
        }
        else if ((c=='/') && (aLanguage == HighlighterLanguage::SQL))
        {
            if (pos != end && *pos=='/')
            {
                // Remove all characters until end of line or EOF
                while( pos != end && !testCharFlags( *pos, CharFlags::EOL ) )
                {
                    ++pos;
                }
                reType = TokenType::Comment;
            }
            else
                reType = TokenType::Operator;
        }
        else
        {
            // Apostrophe is Basic comment
            if (( c == '\'') && (aLanguage == HighlighterLanguage::Basic))
            {
                // Skip all characters until end of input or end of line:
                for (;;) {
                    if (pos == end)
                        break;
                    c = *pos;
                    if (testCharFlags(c, CharFlags::EOL)) {
                        break;
                    }
                    ++pos;
                }

                reType = TokenType::Comment;
            }

            // The real operator; can be easily used since not the actual
            // operator (e.g. +=) is concerned, but the fact that it is one
            if( reType != TokenType::Comment )
            {
                reType = TokenType::Operator;
            }

        }
    }

    // Object separator? Must be handled before Number
    else if( c == '.' && ( pos == end || *pos < '0' || *pos > '9' ) )
    {
        reType = TokenType::Operator;
    }

    // Number?
    else if( testCharFlags( c, CharFlags::StartNumber ) )
    {
        reType = TokenType::Number;

        // Number system, 10 = normal, it is changed for Oct/Hex
        int nRadix = 10;

        // Is it an Oct or a Hex number?
        if( c == '&' )
        {
            // Octal?
            if( pos != end && (*pos == 'o' || *pos == 'O' ))
            {
                // remove o
                ++pos;
                nRadix = 8;     // Octal base

                // Read all numbers
                while( pos != end && testCharFlags( *pos, CharFlags::InOctNumber ) )
                    ++pos;
            }
            // Hexadecimal?
            else if( pos != end && (*pos == 'h' || *pos == 'H' ))
            {
                // remove x
                ++pos;
                nRadix = 16;     // Hexadecimal base

                // Read all numbers
                while( pos != end && testCharFlags( *pos, CharFlags::InHexNumber ) )
                    ++pos;
            }
            else
            {
                reType = TokenType::Operator;
            }
        }

        // When it is not Oct or Hex, then it is double
        if( reType == TokenType::Number && nRadix == 10 )
        {
            // Flag if the last character is an exponent
            bool bAfterExpChar = false;

            // Read all numbers
            while( pos != end && (testCharFlags( *pos, CharFlags::InNumber ) ||
                    (bAfterExpChar && *pos == '+' ) ||
                    (bAfterExpChar && *pos == '-' ) ))
                    // After exponent +/- are OK, too
            {
                c = *pos++;
                bAfterExpChar = ( c == 'e' || c == 'E' );
            }
        }
    }

    // String?
    else if( testCharFlags( c, CharFlags::StartString ) )
    {
        // Remember which character has opened the string
        sal_Unicode cEndString = c;
        if( c == '[' )
            cEndString = ']';

        // Read all characters
        while( pos == end || *pos != cEndString )
        {
            // Detect EOF before reading next char, so we do not lose EOF
            if( pos == end )
            {
                // ERROR: unterminated string literal
                reType = TokenType::Error;
                break;
            }
            c = *pos++;
            if( testCharFlags( c, CharFlags::EOL ) )
            {
                // ERROR: unterminated string literal
                reType = TokenType::Error;
                break;
            }
        }

        if( reType != TokenType::Error )
        {
            ++pos;
            if( cEndString == ']' )
                reType = TokenType::Identifier;
            else
                reType = TokenType::String;
        }
    }

    // End of line?
    else if( testCharFlags( c, CharFlags::EOL ) )
    {
        // If another EOL character comes, read it
        if (pos != end)
        {
            sal_Unicode cNext = *pos;
            if( cNext != c && testCharFlags( cNext, CharFlags::EOL ) )
                ++pos;
        }

        reType = TokenType::EOL;
    }

    // All other will remain TokenType::Unknown

    // Save end position
    rpEndPos = pos;
    return true;
}

SyntaxHighlighter::Tokenizer::Tokenizer( HighlighterLanguage aLang ): aLanguage(aLang)
{
    // Fill character table
    sal_uInt16 i;

    // Allowed characters for identifiers
    CharFlags nHelpMask = CharFlags::StartIdentifier | CharFlags::InIdentifier;
    for( i = 'a' ; i <= 'z' ; i++ )
        aCharTypeTab[i] |= nHelpMask;
    for( i = 'A' ; i <= 'Z' ; i++ )
        aCharTypeTab[i] |= nHelpMask;
    aCharTypeTab[int('_')] |= nHelpMask;
    aCharTypeTab[int('$')] |= nHelpMask;

    // Digit (can be identifier and number)
    nHelpMask = CharFlags::InIdentifier | CharFlags::StartNumber |
                         CharFlags::InNumber | CharFlags::InHexNumber;
    for( i = '0' ; i <= '9' ; i++ )
        aCharTypeTab[i] |= nHelpMask;

    // Add e, E, . and & here manually
    aCharTypeTab[int('e')] |= CharFlags::InNumber;
    aCharTypeTab[int('E')] |= CharFlags::InNumber;
    aCharTypeTab[int('.')] |= CharFlags::InNumber | CharFlags::StartNumber;
    aCharTypeTab[int('&')] |= CharFlags::StartNumber;

    // Hexadecimal digit
    for( i = 'a' ; i <= 'f' ; i++ )
        aCharTypeTab[i] |= CharFlags::InHexNumber;
    for( i = 'A' ; i <= 'F' ; i++ )
        aCharTypeTab[i] |= CharFlags::InHexNumber;

    // Octal digit
    for( i = '0' ; i <= '7' ; i++ )
        aCharTypeTab[i] |= CharFlags::InOctNumber;

    // String literal start/end characters
    aCharTypeTab[int('\'')] |= CharFlags::StartString;
    aCharTypeTab[int('\"')] |= CharFlags::StartString;
    aCharTypeTab[int('[')]  |= CharFlags::StartString;
    aCharTypeTab[int('`')]  |= CharFlags::StartString;

    // Operator characters
    aCharTypeTab[int('!')] |= CharFlags::Operator;
    aCharTypeTab[int('%')] |= CharFlags::Operator;
    // aCharTypeTab[(int)'&'] |= CharFlags::Operator;     Removed because of #i14140
    aCharTypeTab[int('(')] |= CharFlags::Operator;
    aCharTypeTab[int(')')] |= CharFlags::Operator;
    aCharTypeTab[int('*')] |= CharFlags::Operator;
    aCharTypeTab[int('+')] |= CharFlags::Operator;
    aCharTypeTab[int(',')] |= CharFlags::Operator;
    aCharTypeTab[int('-')] |= CharFlags::Operator;
    aCharTypeTab[int('/')] |= CharFlags::Operator;
    aCharTypeTab[int(':')] |= CharFlags::Operator;
    aCharTypeTab[int('<')] |= CharFlags::Operator;
    aCharTypeTab[int('=')] |= CharFlags::Operator;
    aCharTypeTab[int('>')] |= CharFlags::Operator;
    aCharTypeTab[int('?')] |= CharFlags::Operator;
    aCharTypeTab[int('^')] |= CharFlags::Operator;
    aCharTypeTab[int('|')] |= CharFlags::Operator;
    aCharTypeTab[int('~')] |= CharFlags::Operator;
    aCharTypeTab[int('{')] |= CharFlags::Operator;
    aCharTypeTab[int('}')] |= CharFlags::Operator;
    // aCharTypeTab[(int)'['] |= CharFlags::Operator;     Removed because of #i17826
    aCharTypeTab[int(']')] |= CharFlags::Operator;
    aCharTypeTab[int(';')] |= CharFlags::Operator;

    // Space
    aCharTypeTab[int(' ') ] |= CharFlags::Space;
    aCharTypeTab[int('\t')] |= CharFlags::Space;

    // End of line characters
    aCharTypeTab[int('\r')] |= CharFlags::EOL;
    aCharTypeTab[int('\n')] |= CharFlags::EOL;

    ppListKeyWords = nullptr;
    nKeyWordCount = 0;
}

void SyntaxHighlighter::Tokenizer::getHighlightPortions(std::u16string_view rLine,
                                                 /*out*/std::vector<HighlightPortion>& portions) const
{
    // Set the position to the beginning of the source string
    auto pos = rLine.begin();

    // Variables for the out parameter
    TokenType eType;
    std::u16string_view::const_iterator pStartPos;
    std::u16string_view::const_iterator pEndPos;

    // Loop over all the tokens
    while( getNextToken( pos, rLine.end(), eType, pStartPos, pEndPos ) )
    {
        portions.emplace_back(
                pStartPos - rLine.begin(), pEndPos - rLine.begin(), eType);
    }
}


SyntaxHighlighter::SyntaxHighlighter(HighlighterLanguage language):
    m_tokenizer(new SyntaxHighlighter::Tokenizer(language))
{
    switch (language)
    {
        case HighlighterLanguage::Basic:
            m_tokenizer->setKeyWords( strListBasicKeyWords,
                                      std::size( strListBasicKeyWords ));
            break;
        case HighlighterLanguage::SQL:
            m_tokenizer->setKeyWords( strListSqlKeyWords,
                                      std::size( strListSqlKeyWords ));
            break;
        default:
            assert(false); // this cannot happen
    }
}

SyntaxHighlighter::~SyntaxHighlighter() {}

void SyntaxHighlighter::getHighlightPortions(std::u16string_view rLine,
                                              /*out*/std::vector<HighlightPortion>& portions) const
{
    m_tokenizer->getHighlightPortions( rLine, portions );
}

HighlighterLanguage SyntaxHighlighter::GetLanguage() const
{
    return m_tokenizer->aLanguage;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */