tcpp 0.1.0

tcpp wrappings for c/cpp preprocessor
Documentation
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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
/*!
        \file tcppLibrary.hpp
        \date 29.12.2019
        \author Ildar Kasimov
        This file is a single-header library which was written in C++14
   standard. The main purpose of the library is to implement simple yet flexible
   C/C++ preprocessor. We've hardly tried to stick to C98 preprocessor's
   specifications, but if you've found some mistakes or inaccuracies, please,
   make us to know about them. The project has started as minimalistic
   implementation of preprocessor for GLSL and HLSL languages. The usage of the
   library is pretty simple, just copy this file into your enviornment and
        predefine TCPP_IMPLEMENTATION macro before its inclusion like the
   following


        \code
                #define TCPP_IMPLEMENTATION
                #include "tcppLibrary.hpp"
        \endcode
        Because of the initial goal of the project wasn't full featured C
   preprocessor but its subset that's useful for GLSL and HLSL, some points from
   the specification of the C preprocessor could not be applied to this library,
   at least for now. There is a list of unimplemented features placed below
        \todo Implement support of char literals
        \todo Improve existing performance for massive input files
        \todo Add support of integral literals like L, u, etc
        \todo Implement built-in directives like #pragma, #error and others
        \todo Provide support of variadic macros
*/

#pragma once

#include <algorithm>
#include <cctype>
#include <functional>
#include <list>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>

///< Library's configs
#define TCPP_DISABLE_EXCEPTIONS 1


#if TCPP_DISABLE_EXCEPTIONS
#define TCPP_NOEXCEPT noexcept

#else
#define TCPP_NOEXCEPT

#endif

#include <cassert>
#define TCPP_ASSERT(assertion) assert(assertion)


/*!
        interface IInputStream
        \brief The interface describes the functionality that all input streams
   should provide
*/

class IInputStream {
public:
    IInputStream() TCPP_NOEXCEPT = default;
    virtual ~IInputStream() TCPP_NOEXCEPT = default;

    virtual std::string ReadLine() TCPP_NOEXCEPT = 0;
    virtual bool HasNextLine() const TCPP_NOEXCEPT = 0;
};

/*!
        class StringInputStream
        \brief The class is the simplest implementation of the input stream,
   which is a simple string
*/

class StringInputStream : public IInputStream {
public:
    StringInputStream() TCPP_NOEXCEPT = delete;
    explicit StringInputStream(const std::string &source) TCPP_NOEXCEPT;
    StringInputStream(const StringInputStream &inputStream) TCPP_NOEXCEPT;
    StringInputStream(StringInputStream &&inputStream) TCPP_NOEXCEPT;
    virtual ~StringInputStream() TCPP_NOEXCEPT = default;

    std::string ReadLine() TCPP_NOEXCEPT override;
    bool HasNextLine() const TCPP_NOEXCEPT override;

private:
    std::string mSourceStr;
};

enum class E_TOKEN_TYPE : unsigned int {
    IDENTIFIER,
    DEFINE,
    IF,
    ELSE,
    ELIF,
    UNDEF,
    ENDIF,
    DEFINED,
    IFNDEF,
    IFDEF,
    SPACE,
    BLOB,
    OPEN_BRACKET,
    CLOSE_BRACKET,
    COMMA,
    NEWLINE,
    LESS,
    GREATER,
    QUOTES,
    KEYWORD,
    END,
    REJECT_MACRO, ///< Special type of a token to provide meta information
    STRINGIZE_OP,
    CONCAT_OP,
    NUMBER,
    PLUS,
    MINUS,
    SLASH,
    STAR,
    OR,
    AND,
    AMPERSAND,
    VLINE,
    LSHIFT,
    RSHIFT,
    NOT,
    GE,
    LE,
    EQ,
    NE,
    CUSTOM_DIRECTIVE,
    UNKNOWN,
};

/*!
        struct TToken
        \brief The structure is a type to contain all information about single
   token
*/

typedef struct TToken {
    E_TOKEN_TYPE mType;

    std::string mRawView;

    size_t mLineId;
    size_t mPos;
} TToken, *TTokenPtr;

/*!
        class Lexer
        \brief The class implements lexer's functionality
*/

class Lexer {
private:
    using TTokensQueue = std::list<TToken>;
    using TStreamStack = std::stack<IInputStream *>;
    using TDirectivesMap = std::vector<std::tuple<std::string, E_TOKEN_TYPE>>;
    using TDirectiveHandlersArray = std::unordered_set<std::string>;

public:
    Lexer() TCPP_NOEXCEPT = delete;
    explicit Lexer(IInputStream &inputStream) TCPP_NOEXCEPT;
    ~Lexer() TCPP_NOEXCEPT = default;

    bool AddCustomDirective(const std::string &directive) TCPP_NOEXCEPT;

    TToken GetNextToken() TCPP_NOEXCEPT;

    bool HasNextToken() const TCPP_NOEXCEPT;

    void AppendFront(const std::vector<TToken> &tokens) TCPP_NOEXCEPT;

    void PushStream(IInputStream &stream) TCPP_NOEXCEPT;
    void PopStream() TCPP_NOEXCEPT;

    size_t GetCurrLineIndex() const TCPP_NOEXCEPT;
    size_t GetCurrPos() const TCPP_NOEXCEPT;

private:
    TToken _scanTokens(std::string &inputLine) TCPP_NOEXCEPT;

    std::string
    _removeSingleLineComment(const std::string &line) const TCPP_NOEXCEPT;

    std::string
    _removeMultiLineComments(const std::string &currInput) TCPP_NOEXCEPT;

    std::string _requestSourceLine() TCPP_NOEXCEPT;

    TToken _scanSeparatorTokens(char ch, std::string &inputLine) TCPP_NOEXCEPT;

    IInputStream *_getActiveStream() const TCPP_NOEXCEPT;

private:
    static const TToken mEOFToken;

    TDirectivesMap mDirectivesTable;

    TTokensQueue mTokensQueue;

    std::string mCurrLine;

    size_t mCurrLineIndex = 0;
    size_t mCurrPos = 0;

    TStreamStack mStreamsContext;

    TDirectiveHandlersArray mCustomDirectivesMap;
};

/*!
        struct TMacroDesc
        \brief The type describes a single macro definition's description
*/

typedef struct TMacroDesc {
    std::string mName;

    std::vector<std::string> mArgsNames;

    std::vector<TToken> mValue;
} TMacroDesc, *TMacroDescPtr;

enum class E_ERROR_TYPE : unsigned int {
    UNEXPECTED_TOKEN,
    UNBALANCED_ENDIF,
    INVALID_MACRO_DEFINITION,
    MACRO_ALREADY_DEFINED,
    INCONSISTENT_MACRO_ARITY,
    UNDEFINED_MACRO,
    INVALID_INCLUDE_DIRECTIVE,
    UNEXPECTED_END_OF_INCLUDE_PATH,
    ANOTHER_ELSE_BLOCK_FOUND,
    ELIF_BLOCK_AFTER_ELSE_FOUND,
    UNDEFINED_DIRECTIVE,
};

std::string ErrorTypeToString(const E_ERROR_TYPE &errorType) TCPP_NOEXCEPT;

/*!
        struct TErrorInfo
        \brief The type contains all information about happened error
*/

typedef struct TErrorInfo {
    E_ERROR_TYPE mType;
    size_t mLine;
} TErrorInfo, *TErrorInfoPtr;

/*!
        class Preprocessor
        \brief The class implements main functionality of C preprocessor. To
   preprocess some source code string, create an instance of this class and call
   Process method. The usage of the class is the same as iterators.
*/

class Preprocessor {
public:
    using TOnErrorCallback = std::function<void(const TErrorInfo &)>;
    using TOnIncludeCallback =
    std::function<IInputStream *(const std::string &, bool)>;
    using TSymTable = std::vector<TMacroDesc>;
    using TContextStack = std::list<std::string>;
    using TDirectiveHandler =
    std::function<std::string(Preprocessor &, Lexer &, const std::string &)>;
    using TDirectivesMap = std::unordered_map<std::string, TDirectiveHandler>;

    typedef struct TIfStackEntry {
        bool mShouldBeSkipped = true;
        bool mHasElseBeenFound = false;

        TIfStackEntry(bool shouldBeSkipped)
                : mShouldBeSkipped(shouldBeSkipped), mHasElseBeenFound(false) {}
    } TIfStackEntry, *TIfStackEntryPtr;

    using TIfStack = std::stack<TIfStackEntry>;

public:
    Preprocessor() TCPP_NOEXCEPT = delete;
    Preprocessor(const Preprocessor &) TCPP_NOEXCEPT = delete;
    Preprocessor(Lexer &lexer, const TOnErrorCallback &onErrorCallback = {},
                 const TOnIncludeCallback &onIncludeCallback = {}) TCPP_NOEXCEPT;
    ~Preprocessor() TCPP_NOEXCEPT = default;

    bool
    AddCustomDirectiveHandler(const std::string &directive,
                              const TDirectiveHandler &handler) TCPP_NOEXCEPT;

    std::string Process() TCPP_NOEXCEPT;

    Preprocessor &operator=(const Preprocessor &) TCPP_NOEXCEPT = delete;

    TSymTable GetSymbolsTable() const TCPP_NOEXCEPT;

private:
    void _createMacroDefinition() TCPP_NOEXCEPT;
    void _removeMacroDefinition(const std::string &macroName) TCPP_NOEXCEPT;

    std::vector<TToken>
    _expandMacroDefinition(const TMacroDesc &macroDesc,
                           const TToken &idToken) TCPP_NOEXCEPT;

    void _expect(const E_TOKEN_TYPE &expectedType,
                 const E_TOKEN_TYPE &actualType) const TCPP_NOEXCEPT;

    TIfStackEntry _processIfConditional() TCPP_NOEXCEPT;
    TIfStackEntry _processIfdefConditional() TCPP_NOEXCEPT;
    TIfStackEntry _processIfndefConditional() TCPP_NOEXCEPT;
    void _processElseConditional(TIfStackEntry &currStackEntry) TCPP_NOEXCEPT;
    void _processElifConditional(TIfStackEntry &currStackEntry) TCPP_NOEXCEPT;

    int _evaluateExpression(const std::vector<TToken> &exprTokens) const
    TCPP_NOEXCEPT;

    bool _shouldTokenBeSkipped() const TCPP_NOEXCEPT;

private:
    Lexer *mpLexer;
    TOnErrorCallback mOnErrorCallback;
    TOnIncludeCallback mOnIncludeCallback;
    TSymTable mSymTable;
    TContextStack mContextStack;
    TIfStack mConditionalBlocksStack;
    TDirectivesMap mCustomDirectivesHandlersMap;
};

std::string ErrorTypeToString(const E_ERROR_TYPE &errorType) TCPP_NOEXCEPT {
    switch (errorType) {
        case E_ERROR_TYPE::UNEXPECTED_TOKEN:
            return "Unexpected token";
        case E_ERROR_TYPE::UNBALANCED_ENDIF:
            return "Unbalanced endif";
        case E_ERROR_TYPE::INVALID_MACRO_DEFINITION:
            return "Invalid macro definition";
        case E_ERROR_TYPE::MACRO_ALREADY_DEFINED:
            return "The macro is already defined";
        case E_ERROR_TYPE::INCONSISTENT_MACRO_ARITY:
            return "Inconsistent number of arguments between definition and invocation "
                   "of the macro";
        case E_ERROR_TYPE::UNDEFINED_MACRO:
            return "Undefined macro";
        case E_ERROR_TYPE::INVALID_INCLUDE_DIRECTIVE:
            return "Invalid #include directive";
        case E_ERROR_TYPE::UNEXPECTED_END_OF_INCLUDE_PATH:
            return "Unexpected end of include path";
        case E_ERROR_TYPE::ANOTHER_ELSE_BLOCK_FOUND:
            return "#else directive should be last one";
        case E_ERROR_TYPE::ELIF_BLOCK_AFTER_ELSE_FOUND:
            return "#elif found after #else block";
        case E_ERROR_TYPE::UNDEFINED_DIRECTIVE:
            return "Undefined directive";
    }

    return "";
}

StringInputStream::StringInputStream(const std::string &source) TCPP_NOEXCEPT
        : IInputStream(),
          mSourceStr(source) {}

StringInputStream::StringInputStream(const StringInputStream &inputStream)
TCPP_NOEXCEPT : mSourceStr(inputStream.mSourceStr) {}

StringInputStream::StringInputStream(StringInputStream &&inputStream)
TCPP_NOEXCEPT : mSourceStr(std::move(inputStream.mSourceStr)) {}

std::string StringInputStream::ReadLine() TCPP_NOEXCEPT {
    std::string::size_type pos = mSourceStr.find_first_of('\n');
    pos = (pos == std::string::npos) ? pos : (pos + 1);

    std::string currLine = mSourceStr.substr(0, pos);
    mSourceStr.erase(0, pos);

    return currLine;
}

bool StringInputStream::HasNextLine() const TCPP_NOEXCEPT {
    return !mSourceStr.empty();
}

const TToken Lexer::mEOFToken = {E_TOKEN_TYPE::END};

Lexer::Lexer(IInputStream &inputStream) TCPP_NOEXCEPT
        : mCurrLine(),
          mCurrLineIndex(0),
          mDirectivesTable{
                  {"define", E_TOKEN_TYPE::DEFINE},   {"ifdef", E_TOKEN_TYPE::IFDEF},
                  {"ifndef", E_TOKEN_TYPE::IFNDEF},   {"if", E_TOKEN_TYPE::IF},
                  {"else", E_TOKEN_TYPE::ELSE},       {"elif", E_TOKEN_TYPE::ELIF},
                  {"undef", E_TOKEN_TYPE::UNDEF},     {"endif", E_TOKEN_TYPE::ENDIF},
                  {"defined", E_TOKEN_TYPE::DEFINED},
          } {
    PushStream(inputStream);
}

bool Lexer::AddCustomDirective(const std::string &directive) TCPP_NOEXCEPT {
    if (mCustomDirectivesMap.find(directive) != mCustomDirectivesMap.cend()) {
        return false;
    }

    mCustomDirectivesMap.insert(directive);
    return true;
}

TToken Lexer::GetNextToken() TCPP_NOEXCEPT {
    if (!mTokensQueue.empty()) {
        auto currToken = mTokensQueue.front();
        mTokensQueue.pop_front();

        return currToken;
    }

    if (mCurrLine.empty()) {
        // \note if it's still empty then we've reached the end of the source
        if ((mCurrLine = _requestSourceLine()).empty()) {
            return mEOFToken;
        }
    }

    mCurrLine = _removeMultiLineComments(mCurrLine);
    return _scanTokens(mCurrLine);
}

bool Lexer::HasNextToken() const TCPP_NOEXCEPT {
    IInputStream *pCurrInputStream = _getActiveStream();
    return (pCurrInputStream ? pCurrInputStream->HasNextLine() : false) ||
           !mCurrLine.empty() || !mTokensQueue.empty();
}

void Lexer::AppendFront(const std::vector<TToken> &tokens) TCPP_NOEXCEPT {
    mTokensQueue.insert(mTokensQueue.begin(), tokens.begin(), tokens.end());
}

void Lexer::PushStream(IInputStream &stream) TCPP_NOEXCEPT {
    mStreamsContext.push(&stream);
}

void Lexer::PopStream() TCPP_NOEXCEPT {
    if (mStreamsContext.empty()) {
        return;
    }

    mStreamsContext.pop();
}

size_t Lexer::GetCurrLineIndex() const TCPP_NOEXCEPT { return mCurrLineIndex; }

size_t Lexer::GetCurrPos() const TCPP_NOEXCEPT { return mCurrPos; }

TToken Lexer::_scanTokens(std::string &inputLine) TCPP_NOEXCEPT {
    char ch = '\0';

    static const std::unordered_set<std::string> keywordsMap{
            "auto",    "double",   "int",      "struct",   "break",    "else",
            "long",    "switch",   "case",     "enum",     "register", "typedef",
            "char",    "extern",   "return",   "union",    "const",    "float",
            "short",   "unsigned", "continue", "for",      "signed",   "void",
            "default", "goto",     "sizeof",   "volatile", "do",       "if",
            "static",  "while"};

    static const std::string separators = ",()<>\"+-*/&|!=";

    std::string currStr = "";

    while (!inputLine.empty()) {
        ch = inputLine.front();

        if (ch == '\n') {
            // flush current blob
            if (!currStr.empty()) {
                return {E_TOKEN_TYPE::BLOB, currStr, mCurrLineIndex};
            }

            inputLine.erase(0, 1);
            ++mCurrPos;
            return {E_TOKEN_TYPE::NEWLINE, "\n", mCurrLineIndex, mCurrPos};
        }

        if (std::isspace(ch)) {
            // flush current blob
            if (!currStr.empty()) {
                return {E_TOKEN_TYPE::BLOB, currStr, mCurrLineIndex, mCurrPos};
            }

            inputLine.erase(0, 1);
            ++mCurrPos;
            return {E_TOKEN_TYPE::SPACE, " ", mCurrLineIndex, mCurrPos};
        }

        if (ch == '#') // \note it could be # operator or a directive
        {
            // flush current blob
            if (!currStr.empty()) {
                return {E_TOKEN_TYPE::BLOB, currStr, mCurrLineIndex, mCurrPos};
            }

            for (const auto &currDirective : mDirectivesTable) {
                auto &&currDirectiveStr = std::get<std::string>(currDirective);

                if (inputLine.rfind(currDirectiveStr, 1) == 1) {
                    inputLine.erase(0, currDirectiveStr.length() + 1);
                    mCurrPos += currDirectiveStr.length() + 1;

                    return {std::get<E_TOKEN_TYPE>(currDirective), "", mCurrLineIndex,
                            mCurrPos};
                }
            }

            // \note custom directives
            for (const auto &currDirectiveStr : mCustomDirectivesMap) {
                if (inputLine.rfind(currDirectiveStr, 1) == 1) {
                    inputLine.erase(0, currDirectiveStr.length() + 1);
                    mCurrPos += currDirectiveStr.length() + 1;

                    return {E_TOKEN_TYPE::CUSTOM_DIRECTIVE, currDirectiveStr,
                            mCurrLineIndex, mCurrPos};
                }
            }

            inputLine.erase(0, 1);

            // \note if we've reached this line it's # operator not directive
            if (!inputLine.empty()) {
                char nextCh = inputLine.front();
                switch (nextCh) {
                    case '#': // \note concatenation operator
                        inputLine.erase(0, 1);
                        ++mCurrPos;
                        return {E_TOKEN_TYPE::CONCAT_OP, "", mCurrLineIndex, mCurrPos};
                    default:
                        if (nextCh != ' ') // \note stringification operator
                        {
                            return {E_TOKEN_TYPE::STRINGIZE_OP, "", mCurrLineIndex, mCurrPos};
                        }

                        return {E_TOKEN_TYPE::BLOB, "#", mCurrLineIndex, mCurrPos};
                }
            }
        }

        if (std::isdigit(ch)) {
            // flush current blob
            if (!currStr.empty()) {
                return {E_TOKEN_TYPE::BLOB, currStr, mCurrLineIndex, mCurrPos};
            }

            std::string number;
            std::string::size_type i = 0;

            if (ch == '0' && !inputLine.empty()) {
                inputLine.erase(0, 1);
                ++mCurrPos;

                number.push_back(ch);

                char nextCh = inputLine.front();
                if (nextCh == 'x' || std::isdigit(nextCh)) {
                    inputLine.erase(0, 1);
                    ++mCurrPos;

                    number.push_back(nextCh);
                } else {
                    return {E_TOKEN_TYPE::NUMBER, number, mCurrLineIndex, mCurrPos};
                }
            }

            do {
                number.push_back(ch);
            } while ((i < inputLine.length()) && std::isdigit(ch = inputLine[++i]));

            inputLine.erase(0, number.length());
            mCurrPos += number.length();

            return {E_TOKEN_TYPE::NUMBER, number, mCurrLineIndex, mCurrPos};
        }

        if (ch == '_' || std::isalpha(ch)) ///< \note parse identifier
        {
            // flush current blob
            if (!currStr.empty()) {
                return {E_TOKEN_TYPE::BLOB, currStr, mCurrLineIndex};
            }

            std::string identifier;

            do {
                identifier.push_back(ch);
                inputLine.erase(0, 1);
                ++mCurrPos;
            } while (!inputLine.empty() &&
                     (std::isalnum(ch = inputLine.front()) || (ch == '_')));

            return {(keywordsMap.find(identifier) != keywordsMap.cend())
                    ? E_TOKEN_TYPE::KEYWORD
                    : E_TOKEN_TYPE::IDENTIFIER,
                    identifier, mCurrLineIndex, mCurrPos};
        }

        inputLine.erase(0, 1);
        ++mCurrPos;

        if ((separators.find_first_of(ch) != std::string::npos)) {
            if (!currStr.empty()) {
                auto separatingToken = _scanSeparatorTokens(ch, inputLine);
                if (separatingToken.mType != mEOFToken.mType) {
                    mTokensQueue.push_front(separatingToken);
                }

                return {E_TOKEN_TYPE::BLOB, currStr, mCurrLineIndex,
                        mCurrPos}; // flush current blob
            }

            auto separatingToken = _scanSeparatorTokens(ch, inputLine);
            if (separatingToken.mType != mEOFToken.mType) {
                return separatingToken;
            }
        }

        currStr.push_back(ch);
    }

    // flush current blob
    if (!currStr.empty()) {
        return {E_TOKEN_TYPE::BLOB, currStr, mCurrLineIndex, mCurrPos};
    }

    PopStream();

    //\note try to continue preprocessing if there is at least one input stream
    if (!mStreamsContext.empty()) {
        return GetNextToken();
    }

    return mEOFToken;
}

std::string
Lexer::_removeSingleLineComment(const std::string &line) const TCPP_NOEXCEPT {
    std::string::size_type pos = line.find("//");
    return (pos == std::string::npos) ? line : line.substr(0, pos);
}

std::string
Lexer::_removeMultiLineComments(const std::string &currInput) TCPP_NOEXCEPT {
    std::string input = currInput;

    // \note here below all states of DFA are placed
    std::function<std::string(std::string &)> enterCommentBlock =
            [&enterCommentBlock, this](std::string &input) {
                input.erase(0, 2); // \note remove /*

                while (input.rfind("*/", 0) != 0 && !input.empty()) {
                    input.erase(0, 1);

                    if (input.rfind("/*", 0) == 0) {
                        input = enterCommentBlock(input);
                    }

                    if (input.empty()) {
                        input = _requestSourceLine();
                    }
                }

                input.erase(0, 2); // \note remove */

                return input;
            };

    std::string::size_type pos = input.find("/*");
    if (pos != std::string::npos) {
        std::string restStr = input.substr(pos, std::string::npos);
        return input.substr(0, pos) + enterCommentBlock(restStr);
    }

    return input;
}

std::string Lexer::_requestSourceLine() TCPP_NOEXCEPT {
    IInputStream *pCurrInputStream = _getActiveStream();

    if (!pCurrInputStream->HasNextLine()) {
        return "";
    }

    std::string sourceLine =
            _removeSingleLineComment(pCurrInputStream->ReadLine());
    ++mCurrLineIndex;

    /// \note join lines that were splitted with backslash sign
    std::string::size_type pos = 0;
    while (((pos = sourceLine.find_first_of('\\')) != std::string::npos)) {
        if (pCurrInputStream->HasNextLine()) {
            sourceLine.replace(
                    pos ? (pos - 1) : 0, std::string::npos,
                    _removeSingleLineComment(pCurrInputStream->ReadLine()));
            ++mCurrLineIndex;

            continue;
        }

        sourceLine.erase(sourceLine.begin() + pos, sourceLine.end());
    }

    // remove redundant whitespaces
    {
        bool isPrevChWhitespace = false;
        sourceLine.erase(
                std::remove_if(sourceLine.begin(), sourceLine.end(),
                               [&isPrevChWhitespace](char ch) {
                                   bool shouldReplace =
                                           (ch == ' ' || ch == '\t') && isPrevChWhitespace;
                                   isPrevChWhitespace = (ch == ' ' || ch == '\t');
                                   return shouldReplace;
                               }),
                sourceLine.end());
    }

    return sourceLine;
}

TToken Lexer::_scanSeparatorTokens(char ch,
                                   std::string &inputLine) TCPP_NOEXCEPT {
    switch (ch) {
        case ',':
            return {E_TOKEN_TYPE::COMMA, ",", mCurrLineIndex, mCurrPos};
        case '(':
            return {E_TOKEN_TYPE::OPEN_BRACKET, "(", mCurrLineIndex, mCurrPos};
        case ')':
            return {E_TOKEN_TYPE::CLOSE_BRACKET, ")", mCurrLineIndex, mCurrPos};
        case '<':
            if (!inputLine.empty()) {
                char nextCh = inputLine.front();
                switch (nextCh) {
                    case '<':
                        inputLine.erase(0, 1);
                        ++mCurrPos;
                        return {E_TOKEN_TYPE::LSHIFT, "<<", mCurrLineIndex, mCurrPos};
                    case '=':
                        inputLine.erase(0, 1);
                        ++mCurrPos;
                        return {E_TOKEN_TYPE::LE, "<=", mCurrLineIndex, mCurrPos};
                }
            }

            return {E_TOKEN_TYPE::LESS, "<", mCurrLineIndex, mCurrPos};
        case '>':
            if (!inputLine.empty()) {
                char nextCh = inputLine.front();
                switch (nextCh) {
                    case '>':
                        inputLine.erase(0, 1);
                        ++mCurrPos;
                        return {E_TOKEN_TYPE::RSHIFT, ">>", mCurrLineIndex, mCurrPos};
                    case '=':
                        inputLine.erase(0, 1);
                        ++mCurrPos;
                        return {E_TOKEN_TYPE::GE, ">=", mCurrLineIndex, mCurrPos};
                }
            }

            return {E_TOKEN_TYPE::GREATER, ">", mCurrLineIndex, mCurrPos};
        case '\"':
            return {E_TOKEN_TYPE::QUOTES, "\"", mCurrLineIndex, mCurrPos};
        case '+':
            return {E_TOKEN_TYPE::PLUS, "+", mCurrLineIndex, mCurrPos};
        case '-':
            return {E_TOKEN_TYPE::MINUS, "-", mCurrLineIndex, mCurrPos};
        case '*':
            return {E_TOKEN_TYPE::STAR, "*", mCurrLineIndex, mCurrPos};
        case '/':
            return {E_TOKEN_TYPE::SLASH, "/", mCurrLineIndex, mCurrPos};
        case '&':
            if (!inputLine.empty() && inputLine.front() == '&') {
                inputLine.erase(0, 1);
                ++mCurrPos;
                return {E_TOKEN_TYPE::AND, "&&", mCurrLineIndex, mCurrPos};
            }

            return {E_TOKEN_TYPE::AMPERSAND, "&", mCurrLineIndex, mCurrPos};
        case '|':
            if (!inputLine.empty() && inputLine.front() == '|') {
                inputLine.erase(0, 1);
                ++mCurrPos;
                return {E_TOKEN_TYPE::OR, "||", mCurrLineIndex, mCurrPos};
            }

            return {E_TOKEN_TYPE::VLINE, "|", mCurrLineIndex, mCurrPos};
        case '!':
            if (!inputLine.empty() && inputLine.front() == '=') {
                inputLine.erase(0, 1);
                ++mCurrPos;
                return {E_TOKEN_TYPE::NE, "!=", mCurrLineIndex, mCurrPos};
            }

            return {E_TOKEN_TYPE::NOT, "!", mCurrLineIndex, mCurrPos};
        case '=':
            if (!inputLine.empty() && inputLine.front() == '=') {
                inputLine.erase(0, 1);
                ++mCurrPos;
                return {E_TOKEN_TYPE::EQ, "==", mCurrLineIndex, mCurrPos};
            }

            return {E_TOKEN_TYPE::BLOB, "=", mCurrLineIndex, mCurrPos};
    }

    return mEOFToken;
}

IInputStream *Lexer::_getActiveStream() const TCPP_NOEXCEPT {
    return mStreamsContext.empty() ? nullptr : mStreamsContext.top();
}

Preprocessor::Preprocessor(Lexer &lexer,
                           const TOnErrorCallback &onErrorCallback,
                           const TOnIncludeCallback &onIncludeCallback)
TCPP_NOEXCEPT : mpLexer(&lexer),
                mOnErrorCallback(onErrorCallback),
                mOnIncludeCallback(onIncludeCallback) {
    mSymTable.push_back({"__LINE__"});
}

bool Preprocessor::AddCustomDirectiveHandler(const std::string &directive,
                                             const TDirectiveHandler &handler)
TCPP_NOEXCEPT {
    if ((mCustomDirectivesHandlersMap.find(directive) !=
         mCustomDirectivesHandlersMap.cend()) ||
        !mpLexer->AddCustomDirective(directive)) {
        return false;
    }

    mCustomDirectivesHandlersMap.insert({directive, handler});

    return true;
}

std::string Preprocessor::Process() TCPP_NOEXCEPT {
    TCPP_ASSERT(mpLexer);

    std::string processedStr;

    auto appendString = [&processedStr, this](const std::string &str) {
        if (_shouldTokenBeSkipped()) {
            return;
        }

        processedStr.append(str);
    };

    // \note first stage of preprocessing, expand macros and include directives
    while (mpLexer->HasNextToken()) {
        auto currToken = mpLexer->GetNextToken();

        switch (currToken.mType) {
            case E_TOKEN_TYPE::DEFINE:
                _createMacroDefinition();
                break;
            case E_TOKEN_TYPE::UNDEF:
                currToken = mpLexer->GetNextToken();
                _expect(E_TOKEN_TYPE::IDENTIFIER, currToken.mType);
                _removeMacroDefinition(currToken.mRawView);
                break;
            case E_TOKEN_TYPE::IF:
                mConditionalBlocksStack.push(_processIfConditional());
                break;
            case E_TOKEN_TYPE::IFNDEF:
                mConditionalBlocksStack.push(_processIfndefConditional());
                break;
            case E_TOKEN_TYPE::IFDEF:
                mConditionalBlocksStack.push(_processIfdefConditional());
                break;
            case E_TOKEN_TYPE::ELIF:
                _processElifConditional(mConditionalBlocksStack.top());
                break;
            case E_TOKEN_TYPE::ELSE:
                _processElseConditional(mConditionalBlocksStack.top());
                break;
            case E_TOKEN_TYPE::ENDIF:
                if (mConditionalBlocksStack.empty()) {
                    mOnErrorCallback(
                            {E_ERROR_TYPE::UNBALANCED_ENDIF, mpLexer->GetCurrLineIndex()});
                } else {
                    mConditionalBlocksStack.pop();
                }
                break;
            case E_TOKEN_TYPE::IDENTIFIER: // \note try to expand some macro here
            {
                auto iter = std::find_if(mSymTable.cbegin(), mSymTable.cend(),
                                         [&currToken](auto &&item) {
                                             return item.mName == currToken.mRawView;
                                         });

                auto contextIter = std::find_if(
                        mContextStack.cbegin(), mContextStack.cend(),
                        [&currToken](auto &&item) { return item == currToken.mRawView; });

                if (iter != mSymTable.cend() && contextIter == mContextStack.cend()) {
                    mpLexer->AppendFront(_expandMacroDefinition(*iter, currToken));
                } else {
                    appendString(currToken.mRawView);
                }
            } break;
            case E_TOKEN_TYPE::REJECT_MACRO:
                mContextStack.erase(std::remove_if(mContextStack.begin(),
                                                   mContextStack.end(),
                                                   [&currToken](auto &&item) {
                                                       return item == currToken.mRawView;
                                                   }),
                                    mContextStack.end());
                break;
            case E_TOKEN_TYPE::CONCAT_OP:
                // this feature doesn't work for now
                appendString((currToken = mpLexer->GetNextToken()).mRawView);
                break;
            case E_TOKEN_TYPE::STRINGIZE_OP:
                appendString((currToken = mpLexer->GetNextToken()).mRawView);
                break;
            case E_TOKEN_TYPE::CUSTOM_DIRECTIVE: {
                auto customDirectiveIter =
                        mCustomDirectivesHandlersMap.find(currToken.mRawView);
                if (customDirectiveIter != mCustomDirectivesHandlersMap.cend()) {
                    appendString(
                            customDirectiveIter->second(*this, *mpLexer, processedStr));
                } else {
                    mOnErrorCallback(
                            {E_ERROR_TYPE::UNDEFINED_DIRECTIVE, mpLexer->GetCurrLineIndex()});
                }
            } break;
            default:
                appendString(currToken.mRawView);
                break;
        }

        if (!mpLexer->HasNextToken()) {
            mpLexer->PopStream();
        }
    }

    return processedStr;
}

Preprocessor::TSymTable Preprocessor::GetSymbolsTable() const TCPP_NOEXCEPT {
    return mSymTable;
}

void Preprocessor::_createMacroDefinition() TCPP_NOEXCEPT {
    TMacroDesc macroDesc;

    auto currToken = mpLexer->GetNextToken();
    _expect(E_TOKEN_TYPE::SPACE, currToken.mType);

    currToken = mpLexer->GetNextToken();
    _expect(E_TOKEN_TYPE::IDENTIFIER, currToken.mType);

    macroDesc.mName = currToken.mRawView;

    auto extractValue = [this](TMacroDesc &desc, Lexer &lexer) {
        TToken currToken;

        while ((currToken = lexer.GetNextToken()).mType != E_TOKEN_TYPE::NEWLINE) {
            desc.mValue.push_back(currToken);
        }

        if (desc.mValue.empty()) {
            desc.mValue.push_back(
                    {E_TOKEN_TYPE::NUMBER, "1", mpLexer->GetCurrLineIndex()});
        }

        _expect(E_TOKEN_TYPE::NEWLINE, currToken.mType);
    };

    currToken = mpLexer->GetNextToken();
    switch (currToken.mType) {
        case E_TOKEN_TYPE::SPACE: // object like macro
            extractValue(macroDesc, *mpLexer);
            break;
        case E_TOKEN_TYPE::NEWLINE:
            macroDesc.mValue.push_back(
                    {E_TOKEN_TYPE::NUMBER, "1", mpLexer->GetCurrLineIndex()});
            break;
        case E_TOKEN_TYPE::OPEN_BRACKET: // function line macro
        {
            // \note parse arguments
            while (true) {
                while ((currToken = mpLexer->GetNextToken()).mType == E_TOKEN_TYPE::SPACE)
                    ; // \note skip space tokens

                _expect(E_TOKEN_TYPE::IDENTIFIER, currToken.mType);
                macroDesc.mArgsNames.push_back(currToken.mRawView);

                while ((currToken = mpLexer->GetNextToken()).mType == E_TOKEN_TYPE::SPACE)
                    ;
                if (currToken.mType == E_TOKEN_TYPE::CLOSE_BRACKET) {
                    break;
                }

                _expect(E_TOKEN_TYPE::COMMA, currToken.mType);
            }

            currToken = mpLexer->GetNextToken();
            _expect(E_TOKEN_TYPE::SPACE, currToken.mType);

            // \note parse macro's value
            extractValue(macroDesc, *mpLexer);
        } break;
        default:
            mOnErrorCallback(
                    {E_ERROR_TYPE::INVALID_MACRO_DEFINITION, mpLexer->GetCurrLineIndex()});
            break;
    }

    if (_shouldTokenBeSkipped()) {
        return;
    }

    if (std::find_if(mSymTable.cbegin(), mSymTable.cend(),
                     [&macroDesc](auto &&item) {
                         return item.mName == macroDesc.mName;
                     }) != mSymTable.cend()) {
        mOnErrorCallback(
                {E_ERROR_TYPE::MACRO_ALREADY_DEFINED, mpLexer->GetCurrLineIndex()});
        return;
    }

    mSymTable.push_back(macroDesc);
}

void Preprocessor::_removeMacroDefinition(const std::string &macroName)
TCPP_NOEXCEPT {
    if (_shouldTokenBeSkipped()) {
        return;
    }

    auto iter = std::find_if(
            mSymTable.cbegin(), mSymTable.cend(),
            [&macroName](auto &&item) { return item.mName == macroName; });
    if (iter == mSymTable.cend()) {
        mOnErrorCallback(
                {E_ERROR_TYPE::UNDEFINED_MACRO, mpLexer->GetCurrLineIndex()});
        return;
    }

    mSymTable.erase(iter);

    auto currToken = mpLexer->GetNextToken();
    _expect(E_TOKEN_TYPE::NEWLINE, currToken.mType);
}

std::vector<TToken>
Preprocessor::_expandMacroDefinition(const TMacroDesc &macroDesc,
                                     const TToken &idToken) TCPP_NOEXCEPT {
    // \note expand object like macro with simple replacement
    if (macroDesc.mArgsNames.empty()) {
        static const std::unordered_map<std::string, std::function<TToken()>>
                systemMacrosTable{{"__LINE__", [&idToken]() {
            return TToken{E_TOKEN_TYPE::BLOB,
                          std::to_string(idToken.mLineId)};
        }}};

        auto iter = systemMacrosTable.find(macroDesc.mName);
        if (iter != systemMacrosTable.cend()) {
            return {iter->second()};
        }

        return macroDesc.mValue;
    }

    mContextStack.push_back(macroDesc.mName);

    // \note function like macro's case
    auto currToken = mpLexer->GetNextToken();
    _expect(E_TOKEN_TYPE::OPEN_BRACKET, currToken.mType);

    std::vector<std::vector<TToken>> processingTokens;
    std::vector<TToken> currArgTokens;

    // \note read all arguments values
    while (true) {
        currArgTokens.clear();

        while ((currToken = mpLexer->GetNextToken()).mType == E_TOKEN_TYPE::SPACE)
            ; // \note skip space tokens
        currArgTokens.push_back({currToken});

        while ((currToken = mpLexer->GetNextToken()).mType == E_TOKEN_TYPE::SPACE)
            ;

        while (currToken.mType != E_TOKEN_TYPE::COMMA &&
               currToken.mType != E_TOKEN_TYPE::NEWLINE &&
               currToken.mType != E_TOKEN_TYPE::CLOSE_BRACKET) {
            currArgTokens.push_back({currToken});
            currToken = mpLexer->GetNextToken();
        }

        if (currToken.mType != E_TOKEN_TYPE::COMMA &&
            currToken.mType != E_TOKEN_TYPE::CLOSE_BRACKET) {
            _expect(E_TOKEN_TYPE::COMMA, currToken.mType);
        }

        processingTokens.push_back(currArgTokens);

        if (currToken.mType == E_TOKEN_TYPE::CLOSE_BRACKET) {
            break;
        }
    }

    if (processingTokens.size() != macroDesc.mArgsNames.size()) {
        mOnErrorCallback(
                {E_ERROR_TYPE::INCONSISTENT_MACRO_ARITY, mpLexer->GetCurrLineIndex()});
    }

    // \note execute macro's expansion
    std::vector<TToken> replacementList{macroDesc.mValue.cbegin(),
                                        macroDesc.mValue.cend()};
    const auto &argsList = macroDesc.mArgsNames;

    std::string replacementValue;

    for (short currArgIndex = 0; currArgIndex < processingTokens.size();
         ++currArgIndex) {
        const std::string &currArgName = argsList[currArgIndex];
        auto &&currArgValueTokens = processingTokens[currArgIndex];

        replacementValue.clear();

        for (auto &&currArgToken : currArgValueTokens) {
            replacementValue.append(currArgToken.mRawView);
        }

        for (auto &currToken : replacementList) {
            if ((currToken.mType != E_TOKEN_TYPE::IDENTIFIER) ||
                (currToken.mRawView != currArgName)) {
                continue;
            }

            currToken.mRawView = replacementValue;
        }
    }

    replacementList.push_back({E_TOKEN_TYPE::REJECT_MACRO, macroDesc.mName});
    return replacementList;
}

void Preprocessor::_expect(const E_TOKEN_TYPE &expectedType,
                           const E_TOKEN_TYPE &actualType) const TCPP_NOEXCEPT {
    if (expectedType == actualType) {
        return;
    }

    mOnErrorCallback(
            {E_ERROR_TYPE::UNEXPECTED_TOKEN, mpLexer->GetCurrLineIndex()});
}

Preprocessor::TIfStackEntry
Preprocessor::_processIfConditional() TCPP_NOEXCEPT {
    auto currToken = mpLexer->GetNextToken();
    _expect(E_TOKEN_TYPE::SPACE, currToken.mType);

    std::vector<TToken> expressionTokens;

    while ((currToken = mpLexer->GetNextToken()).mType != E_TOKEN_TYPE::NEWLINE) {
        expressionTokens.push_back(currToken);
    }

    _expect(E_TOKEN_TYPE::NEWLINE, currToken.mType);

    return TIfStackEntry{
            static_cast<bool>(!_evaluateExpression(expressionTokens))};
}

Preprocessor::TIfStackEntry
Preprocessor::_processIfdefConditional() TCPP_NOEXCEPT {
    auto currToken = mpLexer->GetNextToken();
    _expect(E_TOKEN_TYPE::SPACE, currToken.mType);

    currToken = mpLexer->GetNextToken();
    _expect(E_TOKEN_TYPE::IDENTIFIER, currToken.mType);

    std::string macroIdentifier = currToken.mRawView;

    currToken = mpLexer->GetNextToken();
    _expect(E_TOKEN_TYPE::NEWLINE, currToken.mType);

    return TIfStackEntry{std::find_if(mSymTable.cbegin(), mSymTable.cend(),
                                      [&macroIdentifier](auto &&item) {
                                          return item.mName == macroIdentifier;
                                      }) == mSymTable.cend()};
}

Preprocessor::TIfStackEntry
Preprocessor::_processIfndefConditional() TCPP_NOEXCEPT {
    auto currToken = mpLexer->GetNextToken();
    _expect(E_TOKEN_TYPE::SPACE, currToken.mType);

    currToken = mpLexer->GetNextToken();
    _expect(E_TOKEN_TYPE::IDENTIFIER, currToken.mType);

    std::string macroIdentifier = currToken.mRawView;

    currToken = mpLexer->GetNextToken();
    _expect(E_TOKEN_TYPE::NEWLINE, currToken.mType);

    return TIfStackEntry{std::find_if(mSymTable.cbegin(), mSymTable.cend(),
                                      [&macroIdentifier](auto &&item) {
                                          return item.mName == macroIdentifier;
                                      }) != mSymTable.cend()};
}

void Preprocessor::_processElseConditional(TIfStackEntry &currStackEntry)
TCPP_NOEXCEPT {
    if (currStackEntry.mHasElseBeenFound) {
        mOnErrorCallback(
                {E_ERROR_TYPE::ANOTHER_ELSE_BLOCK_FOUND, mpLexer->GetCurrLineIndex()});
        return;
    }

    currStackEntry.mShouldBeSkipped = !currStackEntry.mShouldBeSkipped;
    currStackEntry.mHasElseBeenFound = true;
}

void Preprocessor::_processElifConditional(TIfStackEntry &currStackEntry)
TCPP_NOEXCEPT {
    if (currStackEntry.mHasElseBeenFound) {
        mOnErrorCallback({E_ERROR_TYPE::ELIF_BLOCK_AFTER_ELSE_FOUND,
                          mpLexer->GetCurrLineIndex()});
        return;
    }

    auto currToken = mpLexer->GetNextToken();
    _expect(E_TOKEN_TYPE::SPACE, currToken.mType);

    std::vector<TToken> expressionTokens;

    while ((currToken = mpLexer->GetNextToken()).mType != E_TOKEN_TYPE::NEWLINE) {
        expressionTokens.push_back(currToken);
    }

    _expect(E_TOKEN_TYPE::NEWLINE, currToken.mType);

    currStackEntry.mShouldBeSkipped =
            static_cast<bool>(!_evaluateExpression(expressionTokens));
}

int Preprocessor::_evaluateExpression(
        const std::vector<TToken> &exprTokens) const TCPP_NOEXCEPT {
    size_t pos = 0;

    std::vector<TToken> tokens{exprTokens.begin(), exprTokens.end()};
    tokens.push_back({E_TOKEN_TYPE::END});

    // \note use recursive descent parsing technique to evaluate expression
    auto evalCall = [this, &tokens]() { return 0; };

    auto evalPrimary = [this, &tokens, &evalCall]() {
        auto currToken = tokens.front();

        switch (currToken.mType) {
            case E_TOKEN_TYPE::IDENTIFIER: {
                // \note macro call
                if (tokens.size() >= 2 && tokens[1].mType == E_TOKEN_TYPE::OPEN_BRACKET) {
                    return evalCall();
                }

                tokens.erase(tokens.cbegin());

                // \note simple identifier
                return static_cast<int>(std::find_if(mSymTable.cbegin(), mSymTable.cend(),
                                                     [&currToken](auto &&item) {
                                                         return item.mName ==
                                                                currToken.mRawView;
                                                     }) != mSymTable.cend());
            }
            case E_TOKEN_TYPE::NUMBER:
                tokens.erase(tokens.cbegin());
                return std::stoi(currToken.mRawView);
        }

        return 0;
    };

    auto evalUnary = [this, &tokens, &evalPrimary]() {
        int result = evalPrimary();

        auto currToken = tokens.front();
        switch (currToken.mType) {
            case E_TOKEN_TYPE::MINUS:
                result = -result;
                break;
            case E_TOKEN_TYPE::NOT:
                result = !result;
                break;
        }

        return result;
    };

    auto evalMultiplication = [this, &tokens, &evalUnary]() {
        int result = evalUnary();

        TToken currToken;
        while ((currToken = tokens.front()).mType == E_TOKEN_TYPE::STAR ||
               currToken.mType == E_TOKEN_TYPE::SLASH) {
            switch (currToken.mType) {
                case E_TOKEN_TYPE::STAR:
                    result = result * evalUnary();
                    break;
                case E_TOKEN_TYPE::SLASH:
                    result = result / evalUnary();
                    break;
            }
        }

        return result;
    };

    auto evalAddition = [this, &tokens, &evalMultiplication]() {
        int result = evalMultiplication();

        TToken currToken;
        while ((currToken = tokens.front()).mType == E_TOKEN_TYPE::PLUS ||
               currToken.mType == E_TOKEN_TYPE::MINUS) {
            switch (currToken.mType) {
                case E_TOKEN_TYPE::PLUS:
                    result = result + evalMultiplication();
                    break;
                case E_TOKEN_TYPE::MINUS:
                    result = result - evalMultiplication();
                    break;
            }
        }

        return result;
    };

    auto evalComparison = [this, &tokens, &evalAddition]() {
        int result = evalAddition();

        TToken currToken;
        while ((currToken = tokens.front()).mType == E_TOKEN_TYPE::LESS ||
               currToken.mType == E_TOKEN_TYPE::GREATER ||
               currToken.mType == E_TOKEN_TYPE::LE ||
               currToken.mType == E_TOKEN_TYPE::GE) {
            switch (currToken.mType) {
                case E_TOKEN_TYPE::LESS:
                    result = result < evalAddition();
                    break;
                case E_TOKEN_TYPE::GREATER:
                    result = result > evalAddition();
                    break;
                case E_TOKEN_TYPE::LE:
                    result = result <= evalAddition();
                    break;
                case E_TOKEN_TYPE::GE:
                    result = result >= evalAddition();
                    break;
            }
        }

        return result;
    };

    auto evalEquality = [this, &tokens, &evalComparison]() {
        int result = evalComparison();

        TToken currToken;
        while ((currToken = tokens.front()).mType == E_TOKEN_TYPE::EQ ||
               currToken.mType == E_TOKEN_TYPE::NE) {
            switch (currToken.mType) {
                case E_TOKEN_TYPE::EQ:
                    result = result == evalComparison();
                    break;
                case E_TOKEN_TYPE::NE:
                    result = result != evalComparison();
                    break;
            }
        }

        return result;
    };

    auto evalAndExpr = [this, &tokens, &evalEquality]() {
        int result = evalEquality();

        while (tokens.front().mType == E_TOKEN_TYPE::AND) {
            result = result && evalEquality();
        }

        return result;
    };

    auto evalOrExpr = [this, &tokens, &evalAndExpr]() {
        int result = evalAndExpr();

        while (tokens.front().mType == E_TOKEN_TYPE::OR) {
            result = result || evalAndExpr();
        }

        return result;
    };

    return evalOrExpr();
}

bool Preprocessor::_shouldTokenBeSkipped() const TCPP_NOEXCEPT {
    return !mConditionalBlocksStack.empty() &&
           mConditionalBlocksStack.top().mShouldBeSkipped;
}

extern "C" {
// return a char* on heap remember to free
char *process(char *data) {
    std::string sdata(data);
    StringInputStream sin(sdata);
    Lexer lex(sin);
    Preprocessor pre(lex, nullptr);
    auto x = pre.Process();
    char *cstr = new char[sdata.length() + 1];
    strcpy(cstr, x.c_str());
    return cstr;
}
}