summaryrefslogtreecommitdiff
path: root/src/sexpr/parser.cpp
blob: 8768e14790bc3083db3d3eb2877bc65377cc5546 (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
#include "parser.hpp"
//    parser.cpp - build a tree of S-expressions
//
//    Copyright © 2014 Ben Longbons <b.r.longbons@gmail.com>
//
//    This file is part of The Mana World (Athena server)
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU Affero General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU Affero General Public License for more details.
//
//    You should have received a copy of the GNU Affero General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.

#include <cerrno>

#include "../strings/zstring.hpp"
#include "../strings/xstring.hpp"

#include "../poison.hpp"


namespace tmwa
{
namespace sexpr
{
    bool token_is_int(ZString s, int64_t& out, bool& ok)
    {
        if (!s)
            return false;
        if (s.startswith('-') || s.xslice_h(1).is_digit10())
        {
            const char *z = s.c_str();
            char *end = nullptr;
            errno = 0;
            out = strtoll(z, &end, 0);
            if (errno)
                ok = false;
            return !*end;
        }
        return false;
    }

    bool parse(Lexer& lex, SExpr& out)
    {
        out._list.clear();
        out._str = RString();

        bool rv = true;
        out._span.begin = lex.span().begin;
        switch (lex.peek())
        {
        default:
            return false;
        case TOK_STRING:
            out._type = STRING;
            out._str = lex.val_string();
            break;
        case TOK_TOKEN:
            out._type = TOKEN;
            out._str = lex.val_string();
            if (token_is_int(out._str, out._int, rv))
                out._type = INT;
            break;
        case TOK_OPEN:
            out._type = LIST;
            lex.adv();
            while (lex.peek() != TOK_CLOSE)
            {
                SExpr tmp;
                if (!parse(lex, tmp))
                    return false;
                out._list.push_back(std::move(tmp));
            }
            break;
        }
        out._span.end = lex.span().end;
        lex.adv();
        return rv;
    }
} // namespace sexpr
} // namespace tmwa