aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/server/lexer/token.hpp
blob: f270154d1d36a882fe8d212d2a7d3ca512f8a478 (plain) (blame)
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
// Copyright (c) 2019 Egor Tensin <egor@tensin.name>
// This file is part of the "math-server" project.
// For details, see https://github.com/egor-tensin/math-server
// Distributed under the MIT License.

#pragma once

#include "token_type.hpp"

#include <cstddef>
#include <string_view>
#include <utility>
#include <variant>

namespace math::server::lexer {

class Token {
public:
    using Type = token::Type;

    explicit Token(token::Type type);
    explicit Token(double value);

    bool operator==(const Token& other) const;
    bool operator!=(const Token& other) const {
        return !(*this == other);
    }

    Type get_type() const {
        return m_type;
    }

    double as_number() const;

private:
    token::Type m_type;
    std::variant<double> m_value;

    friend std::ostream& operator<<(std::ostream&, const Token&);
};

class ParsedToken : public Token {
public:
    ParsedToken(Token&& token, std::size_t pos, std::string_view view)
        : Token{std::move(token)}, m_pos{pos}, m_view{view} {}

    std::size_t get_pos() const {
        return m_pos;
    }

    std::size_t get_length() const {
        return m_view.length();
    }

private:
    std::size_t m_pos;
    std::string_view m_view;
};

} // namespace math::server::lexer