aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/server/parser.hpp
blob: a9e5f547f557fc45d3402c6896f3e16e92cd689b (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
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
#pragma once

#include "error.hpp"
#include "lexer.hpp"

#include <optional>
#include <string>
#include <string_view>

namespace math::server {
namespace parser {

class Error : public server::Error {
public:
    explicit Error(const std::string& what)
        : server::Error{"parser error: " + what}
    { }
};

class BinaryOp {
public:
    static bool is(const lexer::Token& token) {
        using Type = lexer::Token::Type;
        switch (token.get_type()) {
            case Type::PLUS:
            case Type::MINUS:
            case Type::ASTERISK:
            case Type::SLASH:
                return true;

            default:
                return false;
        }
    }

    static BinaryOp from_token(const lexer::Token& token) {
        if (!is(token)) {
            throw Error{"internal: token is not a binary operator"};
        }
        return BinaryOp{token};
    }

    static constexpr unsigned min_precedence() { return 0; }

    unsigned get_precedence() const {
        using Type = lexer::Token::Type;
        switch (m_type) {
            case Type::PLUS:
            case Type::MINUS:
                return min_precedence();

            case Type::ASTERISK:
            case Type::SLASH:
                return min_precedence() + 1;

            default:
                throw Error{"internal: undefined operator precedence"};
        }
    }

    double exec(double lhs, double rhs) const {
        using Type = lexer::Token::Type;
        switch (m_type) {
            case Type::PLUS:
                return lhs + rhs;
            case Type::MINUS:
                return lhs - rhs;
            case Type::ASTERISK:
                return lhs * rhs;
            case Type::SLASH:
                // Trapping the CPU would be better?
                if (rhs == 0.) {
                    throw Error{"division by zero"};
                }
                return lhs / rhs;
            default:
                throw Error{"internal: unsupported operator"};
        }
    }

private:
    explicit BinaryOp(const lexer::Token& token)
        : m_type{token.get_type()}
    { }

    lexer::Token::Type m_type;
};

}

class Parser {
public:
    // I did simple recursive descent parsing a long time ago (see
    // https://github.com/egor-tensin/simple-interpreter), this appears to be
    // a finer algorithm for parsing arithmetic expressions.
    // Reference: https://en.wikipedia.org/wiki/Operator-precedence_parser

    explicit Parser(const std::string_view& input)
        : m_lexer{input}
    { }

    double exec() {
        m_lexer.parse_token();
        const auto result = exec_expr();
        if (m_lexer.has_token()) {
            throw parser::Error{"expected a binary operator"};
        }
        return result;
    }

private:
    double exec_expr() {
        return exec_expr(exec_primary(), parser::BinaryOp::min_precedence());
    }

    double exec_expr(double lhs, unsigned min_prec) {
        for (auto op = peek_operator(); op.has_value() && op->get_precedence() >= min_prec;) {
            const auto lhs_op = *op;
            m_lexer.drop_token();
            auto rhs = exec_primary();

            for (op = peek_operator(); op.has_value() && op->get_precedence() > lhs_op.get_precedence(); op = peek_operator()) {
                rhs = exec_expr(rhs, op->get_precedence());
            }

            lhs = lhs_op.exec(lhs, rhs);
        }
        return lhs;
    }

    std::optional<parser::BinaryOp> peek_operator() {
        const auto token = m_lexer.peek_token();
        if (!token.has_value() || !parser::BinaryOp::is(*token)) {
            return {};
        }
        return parser::BinaryOp::from_token(*token);
    }

    double exec_primary() {
        if (!m_lexer.has_token()) {
            throw parser::Error{"expected '-', '(' or a number"};
        }

        using Type = lexer::Token::Type;

        if (m_lexer.drop_token_if(Type::MINUS).has_value()) {
            return -exec_primary();
        }

        if (m_lexer.drop_token_if(Type::LEFT_PAREN).has_value()) {
            const auto inner = exec_expr();
            if (!m_lexer.has_token() || !m_lexer.drop_token_if(Type::RIGHT_PAREN).has_value()) {
                throw parser::Error{"missing closing ')'"};
            }
            return inner;
        }

        if (const auto token = m_lexer.drop_token_if(Type::NUMBER); token.has_value()) {
            return token.value().get_number_value();
        }

        throw parser::Error{"expected '-', '(' or a number"};
    }

    Lexer m_lexer;
};

}