A simple scripting language in C++
Ferenc Szontágh
2025-04-13 cb3065c34756a70cb6006fc25777ce3e720ff1a8
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
#ifndef LEXER_HPP
#define LEXER_HPP
 
#include <algorithm>
#include <istream>
#include <sstream>
#include <vector>
 
#include "Token.hpp"
#include "VariableTypes.hpp"
 
class Lexer {
  public:
    Lexer(const std::string & source, const std::string & filename);
    std::vector<Token> tokenize();
 
  private:
    const std::string & src;
    const std::string & filename;
    size_t              pos;
    int                 lineNumber = 1;
    size_t              colNumber  = 1;
    size_t              charNumber = 1;
 
    char peek() const;
    char advance();
    bool isAtEnd() const;
 
    Token string();
    Token number();
    Token identifier();
    Token variable();
    Token comment();
    Token keywordOrIdentifier();
    Token boolean();
    Token singleCharToken(TokenType type, const std::string & lexeme);
    bool  matchSequence(const std::string & sequence, bool caseSensitive = true) const;
    Token variableDeclaration(Variables::Type type);
    void  matchAndConsume(const std::string & sequence, bool caseSensitive = true);
 
    // create token methods
    Token createToken(TokenType type, const std::string & lexeme) const;
    Token createSingleCharToken(TokenType type, const std::string & lexeme);
    Token createUnknownToken(const std::string & lexeme) const;
    Token createErrorToken(const std::string & lexeme) const;
    Token stringToken();
    Token numberToken();
    Token identifierToken();
    Token variableToken();
    Token commentToken();
    Token keywordOrIdentifierToken();
    Token variableDeclarationToken(Variables::Type type);
 
    // validate number types from string
    template <typename Numeric> static bool is_number(const std::string & s) {
        Numeric n;
        return ((std::istringstream(s) >> n >> std::ws).eof());
    }
 
    bool matchSequence(const std::string & sequence, bool caseSensitive = true) {
        if (caseSensitive) {
            return src.substr(pos, sequence.length()) == sequence;
        }
 
        std::string srcSubstr = src.substr(pos, sequence.length());
        std::string seqLower  = sequence;
 
        std::transform(srcSubstr.begin(), srcSubstr.end(), srcSubstr.begin(),
                       [](unsigned char c) { return std::tolower(c); });
 
        std::transform(seqLower.begin(), seqLower.end(), seqLower.begin(),
                       [](unsigned char c) { return std::tolower(c); });
 
        return srcSubstr == seqLower;
    }
};
 
#endif  // LEXER_HPP